text
stringlengths 54
60.6k
|
---|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved
*/
#include "../StroikaPreComp.h"
#include <cstdlib>
#include <cstring>
#include <ctime>
#include "Timezone.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Time;
time_t Time::GetLocaltimeToGMTOffset ()
{
#if 0
// WRONG - but COULD use this API - but not sure needed
#if qPlatform_Windows
TIME_ZONE_INFORMATION tzInfo;
memset (&tzInfo, 0, sizeof (tzInfo));
(void)::GetTimeZoneInformation (&tzInfo);
int unsignedBias = abs (tzInfo.Bias);
int hrs = unsignedBias / 60;
int mins = unsignedBias - hrs * 60;
tzBiasString = ::Format (L"%s%.2d:%.2d", (tzInfo.Bias >= 0? L"-": L"+"), hrs, mins);
#endif
#endif
/*
* COULD this be cached? It SHOULD be - but what about when the timezone changes? there maybe a better way to compute this using the
* timezone global var???
*/
struct tm tm;
memset (&tm, 0, sizeof(tm));
tm.tm_year = 70;
tm.tm_mon = 0; // Jan
tm.tm_mday = 1;
time_t result = mktime (&tm);
return result;
}
<commit_msg>in Time::GetLocaltimeToGMTOffset () code - check daylight flag for daylight savings time; probably still wrong/bad API, but better<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved
*/
#include "../StroikaPreComp.h"
#include <cstdlib>
#include <cstring>
#include <ctime>
#include "../Configuration/Common.h"
#include "Timezone.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Time;
time_t Time::GetLocaltimeToGMTOffset ()
{
#if 0
// WRONG - but COULD use this API - but not sure needed
#if qPlatform_Windows
TIME_ZONE_INFORMATION tzInfo;
memset (&tzInfo, 0, sizeof (tzInfo));
(void)::GetTimeZoneInformation (&tzInfo);
int unsignedBias = abs (tzInfo.Bias);
int hrs = unsignedBias / 60;
int mins = unsignedBias - hrs * 60;
tzBiasString = ::Format (L"%s%.2d:%.2d", (tzInfo.Bias >= 0? L"-": L"+"), hrs, mins);
#endif
#endif
static bool sCalledOnce_ = false;
if (not sCalledOnce_) {
tzset ();
sCalledOnce_ = true;
}
/*
* COULD this be cached? It SHOULD be - but what about when the timezone changes? there maybe a better way to compute this using the
* timezone global var???
*/
struct tm tm;
memset (&tm, 0, sizeof(tm));
tm.tm_year = 70;
tm.tm_mon = 0; // Jan
tm.tm_mday = 1;
tm.tm_isdst = daylight;
time_t result = mktime (&tm);
return result;
}
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include "AVT.hpp"
#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/StringTokenizer.hpp>
#include "AVTPartSimple.hpp"
#include "AVTPartXPath.hpp"
#include "StylesheetConstructionContext.hpp"
/**
* Construct an AVT by parsing the string, and either
* constructing a vector of AVTParts, or simply hold
* on to the string if the AVT is simple.
*/
AVT::AVT(
const DOMString& name,
const XMLCh* type,
const XMLCh* stringedValue,
const PrefixResolver& resolver,
StylesheetConstructionContext& constructionContext) :
AVTPart(),
m_name(name),
m_pcType(type)
{
StringTokenizer tokenizer(stringedValue, "{}\"\'", true);
const int nTokens = tokenizer.countTokens();
if(nTokens < 2)
{
m_simpleString = stringedValue; // then do the simple thing
}
else
{
m_parts.reserve(nTokens + 1);
DOMString buffer;
DOMString exprBuffer;
DOMString t; // base token
DOMString lookahead; // next token
DOMString error; // if non-null, break from loop
while(tokenizer.hasMoreTokens())
{
if(length(lookahead))
{
t = lookahead;
lookahead = DOMString();
}
else t = tokenizer.nextToken();
if(length(t) == 1)
{
switch(t.charAt(0))
{
case('\"'):
case('\''):
{
// just keep on going, since we're not in an attribute template
append(buffer,t);
break;
}
case('{'):
{
// Attribute Value Template start
lookahead = tokenizer.nextToken();
if(equals(lookahead, "{"))
{
// Double curlys mean escape to show curly
append(buffer,lookahead);
lookahead = DOMString();
break; // from switch
}
/*
else if(lookahead.equals("\"") || lookahead.equals("\'"))
{
// Error. Expressions can not begin with quotes.
error = "Expressions can not begin with quotes.";
break; // from switch
}
*/
else
{
if(length(buffer) > 0)
{
m_parts.push_back(new AVTPartSimple(buffer));
buffer = DOMString();
}
exprBuffer = DOMString();
append(exprBuffer,lookahead);
while(length(lookahead) > 0 && !equals(lookahead, "}"))
{
lookahead = tokenizer.nextToken();
if(length(lookahead) == 1)
{
switch(lookahead.charAt(0))
{
case '\'':
case '\"':
{
// String start
append(exprBuffer,lookahead);
const DOMString quote = lookahead;
// Consume stuff 'till next quote
lookahead = tokenizer.nextToken();
while(!equals(lookahead, quote))
{
append(exprBuffer,lookahead);
lookahead = tokenizer.nextToken();
}
append(exprBuffer,lookahead);
break;
}
case '{':
{
// What's another curly doing here?
error = "Error: Can not have \"{\" within expression.";
break;
}
case '}':
{
// Proper close of attribute template.
// Evaluate the expression.
// XObject xobj = evalXPathStr(expression, contextNode, namespaceContext);
// buffer.append(xobj.str());
buffer = DOMString();
XPath *xpath = constructionContext.createXPath(exprBuffer, resolver);
m_parts.push_back(new AVTPartXPath(xpath));
lookahead = DOMString(); // breaks out of inner while loop
break;
}
default:
{
// part of the template stuff, just add it.
append(exprBuffer,lookahead);
}
} // end inner switch
} // end if lookahead length == 1
else
{
// part of the template stuff, just add it.
append(exprBuffer,lookahead);
}
} // end while(!lookahead.equals("}"))
if(length(error) > 0)
{
break; // from inner while loop
}
}
break;
}
case('}'):
{
lookahead = tokenizer.nextToken();
if(equals(lookahead, "}"))
{
// Double curlys mean escape to show curly
append(buffer,lookahead);
lookahead = DOMString(); // swallow
}
else
{
// Illegal, I think...
constructionContext.warn("Found \"}\" but no attribute template open!");
append(buffer,"}");
// leave the lookahead to be processed by the next round.
}
break;
}
default:
{
// Anything else just add to string.
append(buffer,t);
}
} // end switch t
} // end if length == 1
else
{
// Anything else just add to string.
append(buffer,t);
}
if(length(error) > 0)
{
constructionContext.warn("Attr Template, "+error);
break;
}
} // end while(tokenizer.hasMoreTokens())
if(length(buffer) > 0)
{
m_parts.push_back(new AVTPartSimple(buffer));
buffer = DOMString();
}
} // end else nTokens > 1
if(m_parts.empty() && length(m_simpleString) == 0)
{
// Error?
m_simpleString = DOMString();
}
}
AVT::~AVT()
{
for (unsigned i = 0; i < m_parts.size(); ++i)
{
delete (m_parts[i]);
}
m_pcType = 0;
}
void
AVT::evaluate(
DOMString& buf,
const DOM_Node& contextNode,
const PrefixResolver& prefixResolver,
XPathExecutionContext& executionContext) const
{
if(length(m_simpleString) > 0)
{
buf = m_simpleString;
}
else if(!m_parts.empty())
{
buf = DOMString();
const int n = m_parts.size();
for(int i = 0; i < n; i++)
{
assert(m_parts[i] != 0);
m_parts[i]->evaluate(buf, contextNode, prefixResolver, executionContext);
}
}
else
{
buf = DOMString();
}
}
<commit_msg>Fixed parsing problem causing crash in test lre06<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include "AVT.hpp"
#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/StringTokenizer.hpp>
#include "AVTPartSimple.hpp"
#include "AVTPartXPath.hpp"
#include "StylesheetConstructionContext.hpp"
/**
* Construct an AVT by parsing the string, and either
* constructing a vector of AVTParts, or simply hold
* on to the string if the AVT is simple.
*/
AVT::AVT(
const DOMString& name,
const XMLCh* type,
const XMLCh* stringedValue,
const PrefixResolver& resolver,
StylesheetConstructionContext& constructionContext) :
AVTPart(),
m_name(name),
m_pcType(type)
{
StringTokenizer tokenizer(stringedValue, "{}\"\'", true);
const int nTokens = tokenizer.countTokens();
if(nTokens < 2)
{
m_simpleString = stringedValue; // then do the simple thing
}
else
{
m_parts.reserve(nTokens + 1);
DOMString buffer;
DOMString exprBuffer;
DOMString t; // base token
DOMString lookahead; // next token
DOMString error; // if non-null, break from loop
while(tokenizer.hasMoreTokens())
{
if(length(lookahead))
{
t = lookahead;
lookahead = DOMString();
}
else t = tokenizer.nextToken();
if(length(t) == 1)
{
switch(t.charAt(0))
{
case('\"'):
case('\''):
{
// just keep on going, since we're not in an attribute template
append(buffer,t);
break;
}
case('{'):
{
// Attribute Value Template start
lookahead = tokenizer.nextToken();
if(equals(lookahead, "{"))
{
// Double curlys mean escape to show curly
append(buffer,lookahead);
lookahead = DOMString();
break; // from switch
}
else
{
if(length(buffer) > 0)
{
m_parts.push_back(new AVTPartSimple(buffer));
buffer = DOMString();
}
exprBuffer = DOMString();
while(length(lookahead) > 0 && !equals(lookahead, "}"))
{
if(length(lookahead) == 1)
{
switch(lookahead.charAt(0))
{
case '\'':
case '\"':
{
// String start
append(exprBuffer,lookahead);
const DOMString quote = lookahead;
// Consume stuff 'till next quote
lookahead = tokenizer.nextToken();
while(!equals(lookahead, quote))
{
append(exprBuffer,lookahead);
lookahead = tokenizer.nextToken();
}
append(exprBuffer,lookahead);
break;
}
case '{':
{
// What's another curly doing here?
error = "Error: Can not have \"{\" within expression.";
break;
}
default:
{
// part of the template stuff, just add it.
append(exprBuffer,lookahead);
}
} // end inner switch
} // end if lookahead length == 1
else
{
// part of the template stuff, just add it.
append(exprBuffer,lookahead);
}
lookahead = tokenizer.nextToken();
} // end while(!lookahead.equals("}"))
assert(equals(lookahead, "}"));
// Proper close of attribute template. Evaluate the
// expression.
buffer = DOMString();
XPath *xpath = constructionContext.createXPath(exprBuffer, resolver);
m_parts.push_back(new AVTPartXPath(xpath));
lookahead = DOMString(); // breaks out of inner while loop
if(length(error) > 0)
{
break; // from inner while loop
}
}
break;
}
case('}'):
{
lookahead = tokenizer.nextToken();
if(equals(lookahead, "}"))
{
// Double curlys mean escape to show curly
append(buffer,lookahead);
lookahead = DOMString(); // swallow
}
else
{
// Illegal, I think...
constructionContext.warn("Found \"}\" but no attribute template open!");
append(buffer,"}");
// leave the lookahead to be processed by the next round.
}
break;
}
default:
{
// Anything else just add to string.
append(buffer,t);
}
} // end switch t
} // end if length == 1
else
{
// Anything else just add to string.
append(buffer,t);
}
if(length(error) > 0)
{
constructionContext.warn("Attr Template, "+error);
break;
}
} // end while(tokenizer.hasMoreTokens())
if(length(buffer) > 0)
{
m_parts.push_back(new AVTPartSimple(buffer));
buffer = DOMString();
}
} // end else nTokens > 1
if(m_parts.empty() && length(m_simpleString) == 0)
{
// Error?
m_simpleString = DOMString();
}
}
AVT::~AVT()
{
for (unsigned i = 0; i < m_parts.size(); ++i)
{
delete (m_parts[i]);
}
m_pcType = 0;
}
void
AVT::evaluate(
DOMString& buf,
const DOM_Node& contextNode,
const PrefixResolver& prefixResolver,
XPathExecutionContext& executionContext) const
{
if(length(m_simpleString) > 0)
{
buf = m_simpleString;
}
else if(!m_parts.empty())
{
buf = DOMString();
const int n = m_parts.size();
for(int i = 0; i < n; i++)
{
assert(m_parts[i] != 0);
m_parts[i]->evaluate(buf, contextNode, prefixResolver, executionContext);
}
}
else
{
buf = DOMString();
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <panic.h>
#include <Log.h>
#include <utilities/utility.h>
#include <processor/Processor.h>
#include <processor/types.h>
#include <processor/PhysicalMemoryManager.h>
#include <LockGuard.h>
#include "VirtualAddressSpace.h"
ArmV7VirtualAddressSpace ArmV7VirtualAddressSpace::m_KernelSpace;
/** Array of free pages, used during the mapping algorithms in case a new page
table needs to be mapped, which must be done without relinquishing the lock
(which means we can't call the PMM!)
There is one page per processor. */
physical_uintptr_t g_EscrowPages[256]; /// \todo MAX_PROCESSORS
VirtualAddressSpace &VirtualAddressSpace::getKernelAddressSpace()
{
return ArmV7VirtualAddressSpace::m_KernelSpace;
}
VirtualAddressSpace *VirtualAddressSpace::create()
{
// TODO
//return new X86VirtualAddressSpace();
return 0;
}
ArmV7VirtualAddressSpace::ArmV7VirtualAddressSpace() :
VirtualAddressSpace(reinterpret_cast<void*> (0))
{
}
ArmV7VirtualAddressSpace::~ArmV7VirtualAddressSpace()
{
}
uint32_t ArmV7VirtualAddressSpace::toFlags(size_t flags)
{
uint32_t ret = 0; // No access.
if(flags & KernelMode)
{
ret = 1; // Read/write in privileged mode, not usable in user mode
}
else
{
if(flags & Write)
ret = 3; // Read/write all
else
ret = 2; // Read/write privileged, read-only user
}
return ret;
}
size_t ArmV7VirtualAddressSpace::fromFlags(uint32_t flags)
{
switch(flags)
{
case 0:
return 0; // Zero permissions
case 1:
return (Write | KernelMode);
case 2:
return 0; // Read-only by user mode... how to represent that?
case 3:
return Write; // Read/write all
default:
return 0;
}
}
bool ArmV7VirtualAddressSpace::initialise()
{
return true;
}
bool ArmV7VirtualAddressSpace::isAddressValid(void *virtualAddress)
{
// No address is "invalid" in the sense that we're looking for here.
return true;
}
bool ArmV7VirtualAddressSpace::map(physical_uintptr_t physicalAddress,
void *virtualAddress,
size_t flags)
{
return doMap(physicalAddress, virtualAddress, flags);
}
void ArmV7VirtualAddressSpace::unmap(void *virtualAddress)
{
return doUnmap(virtualAddress);
}
bool ArmV7VirtualAddressSpace::isMapped(void *virtualAddress)
{
return doIsMapped(virtualAddress);
}
void ArmV7VirtualAddressSpace::getMapping(void *virtualAddress,
physical_uintptr_t &physicalAddress,
size_t &flags)
{
doGetMapping(virtualAddress, physicalAddress, flags);
}
void ArmV7VirtualAddressSpace::setFlags(void *virtualAddress, size_t newFlags)
{
return doSetFlags(virtualAddress, newFlags);
}
void *ArmV7VirtualAddressSpace::allocateStack()
{
return doAllocateStack(USERSPACE_VIRTUAL_STACK_SIZE);
}
void *ArmV7VirtualAddressSpace::allocateStack(size_t stackSz)
{
return doAllocateStack(stackSz);
}
bool ArmV7VirtualAddressSpace::doIsMapped(void *virtualAddress)
{
uintptr_t addr = reinterpret_cast<uintptr_t>(virtualAddress);
uint32_t pdir_offset = addr >> 20;
uint32_t ptab_offset = (addr >> 12) & 0xFF;
// Grab the entry in the page directory
FirstLevelDescriptor *pdir = reinterpret_cast<FirstLevelDescriptor *>(m_VirtualPageDirectory);
if(pdir[pdir_offset].descriptor.entry)
{
// What type is the entry?
switch(pdir[pdir_offset].descriptor.fault.type)
{
case 1:
{
// Page table walk.
SecondLevelDescriptor *ptbl = reinterpret_cast<SecondLevelDescriptor *>(reinterpret_cast<uintptr_t>(m_VirtualPageTables) + pdir_offset);
if(!ptbl[ptab_offset].descriptor.fault.type)
return false;
break;
}
case 2:
// Section or supersection
WARNING("ArmV7VirtualAddressSpace::isAddressValid - sections and supersections not yet supported");
break;
default:
return false;
}
}
return true;
}
bool ArmV7VirtualAddressSpace::doMap(physical_uintptr_t physicalAddress,
void *virtualAddress,
size_t flags)
{
// Check if we have an allocated escrow page - if we don't, allocate it.
if (g_EscrowPages[Processor::id()] == 0)
{
g_EscrowPages[Processor::id()] = PhysicalMemoryManager::instance().allocatePage();
if (g_EscrowPages[Processor::id()] == 0)
{
// Still 0, we have problems.
FATAL("Out of memory");
}
}
LockGuard<Spinlock> guard(m_Lock);
// Grab offsets for the virtual address
uintptr_t addr = reinterpret_cast<uintptr_t>(virtualAddress);
uint32_t pdir_offset = addr >> 20;
uint32_t ptbl_offset = (addr >> 12) & 0xFF;
// Is there a page table for this page yet?
FirstLevelDescriptor *pdir = reinterpret_cast<FirstLevelDescriptor *>(m_VirtualPageDirectory);
if(!pdir[pdir_offset].descriptor.entry)
{
// There isn't - allocate one.
uintptr_t page = g_EscrowPages[Processor::id()];
g_EscrowPages[Processor::id()] = 0;
// Point to the page, which defines a page table, is not shareable,
// and is in domain 0. Note that there's 4 page tables in a 4K page,
// so we handle that here.
for(int i = 0; i < 4; i++)
{
/// \note For later: when creating high-memory page table mappings, they should be in
/// DOMAIN ONE - which holds all paging structures. This way they can be locked down
/// appropriately.
pdir[pdir_offset + i].descriptor.entry = page + (i * 1024);
pdir[pdir_offset + i].descriptor.pageTable.type = 1;
pdir[pdir_offset + i].descriptor.pageTable.sbz1 = pdir[pdir_offset + i].descriptor.pageTable.sbz2 = 0;
pdir[pdir_offset + i].descriptor.pageTable.ns = 1;
pdir[pdir_offset + i].descriptor.pageTable.domain = 0; // DOMAIN0: Main memory
pdir[pdir_offset + i].descriptor.pageTable.imp = 0;
// Map in the page table we've just created so we can zero it.
// mapaddr is the virtual address of the page table we just allocated
// physical space for.
uintptr_t mapaddr = reinterpret_cast<uintptr_t>(m_VirtualPageTables);
mapaddr += ((pdir_offset + i) * 0x400);
uint32_t ptbl_offset2 = (mapaddr >> 12) & 0xFF;
// Grab the right page table for this new page
uintptr_t ptbl_addr = reinterpret_cast<uintptr_t>(m_VirtualPageTables) + (mapaddr >> 20);
SecondLevelDescriptor *ptbl = reinterpret_cast<SecondLevelDescriptor*>(ptbl_addr);
ptbl[ptbl_offset2].descriptor.entry = page + (i * 1024);
ptbl[ptbl_offset2].descriptor.smallpage.type = 2;
ptbl[ptbl_offset2].descriptor.smallpage.b = 0;
ptbl[ptbl_offset2].descriptor.smallpage.c = 0;
ptbl[ptbl_offset2].descriptor.smallpage.ap1 = 3; // Page table, give it READ/WRITE
ptbl[ptbl_offset2].descriptor.smallpage.sbz = 0;
ptbl[ptbl_offset2].descriptor.smallpage.ap2 = 0;
ptbl[ptbl_offset2].descriptor.smallpage.s = 0;
ptbl[ptbl_offset2].descriptor.smallpage.nG = 1;
// Mapped, so clear the page now
memset(reinterpret_cast<void*>(mapaddr), 0, 1024);
}
}
// Grab the virtual address for the page table for this page
uintptr_t mapaddr = reinterpret_cast<uintptr_t>(USERSPACE_PAGETABLES);
mapaddr += pdir_offset * 0x400;
// Perform the mapping, if necessary
SecondLevelDescriptor *ptbl = reinterpret_cast<SecondLevelDescriptor*>(mapaddr);
if(ptbl[ptbl_offset].descriptor.entry & 0x3)
{
return false; // Already mapped.
}
else
{
ptbl[ptbl_offset].descriptor.entry = physicalAddress;
ptbl[ptbl_offset].descriptor.smallpage.type = 2;
ptbl[ptbl_offset].descriptor.smallpage.b = 0;
ptbl[ptbl_offset].descriptor.smallpage.c = 0;
ptbl[ptbl_offset].descriptor.smallpage.ap1 = toFlags(flags);
ptbl[ptbl_offset].descriptor.smallpage.sbz = 0;
ptbl[ptbl_offset].descriptor.smallpage.ap2 = 0;
ptbl[ptbl_offset].descriptor.smallpage.s = 0;
ptbl[ptbl_offset].descriptor.smallpage.nG = 1;
}
return true;
}
void ArmV7VirtualAddressSpace::doGetMapping(void *virtualAddress,
physical_uintptr_t &physicalAddress,
size_t &flags)
{
uintptr_t addr = reinterpret_cast<uintptr_t>(virtualAddress);
uint32_t pdir_offset = addr >> 20;
uint32_t ptab_offset = (addr >> 12) & 0xFF;
// Grab the entry in the page directory
FirstLevelDescriptor *pdir = reinterpret_cast<FirstLevelDescriptor *>(m_VirtualPageDirectory);
if(pdir[pdir_offset].descriptor.entry)
{
// What type is the entry?
switch(pdir[pdir_offset].descriptor.fault.type)
{
case 1:
{
// Page table walk.
SecondLevelDescriptor *ptbl = reinterpret_cast<SecondLevelDescriptor *>(reinterpret_cast<uintptr_t>(m_VirtualPageTables) + pdir_offset);
if(!ptbl[ptab_offset].descriptor.fault.type)
return;
else
{
physicalAddress = ptbl[ptab_offset].descriptor.smallpage.base << 12;
flags = fromFlags(ptbl[ptab_offset].descriptor.smallpage.ap1);
}
break;
}
case 2:
// Section or supersection
WARNING("ArmV7VirtualAddressSpace::doGetMapping - sections and supersections not yet supported");
break;
default:
return;
}
}
}
void ArmV7VirtualAddressSpace::doSetFlags(void *virtualAddress, size_t newFlags)
{
}
void ArmV7VirtualAddressSpace::doUnmap(void *virtualAddress)
{
uintptr_t addr = reinterpret_cast<uintptr_t>(virtualAddress);
uint32_t pdir_offset = addr >> 20;
uint32_t ptab_offset = (addr >> 12) & 0xFF;
// Grab the entry in the page directory
FirstLevelDescriptor *pdir = reinterpret_cast<FirstLevelDescriptor *>(m_VirtualPageDirectory);
if(pdir[pdir_offset].descriptor.entry)
{
// What type is the entry?
switch(pdir[pdir_offset].descriptor.fault.type)
{
case 1:
{
// Page table walk.
SecondLevelDescriptor *ptbl = reinterpret_cast<SecondLevelDescriptor *>(reinterpret_cast<uintptr_t>(m_VirtualPageTables) + pdir_offset);
ptbl[ptab_offset].descriptor.fault.type = 0; // Unmap.
break;
}
case 2:
// Section or supersection
pdir[pdir_offset].descriptor.fault.type = 0;
break;
default:
return;
}
}
}
void *ArmV7VirtualAddressSpace::doAllocateStack(size_t sSize)
{
return 0;
}
void ArmV7VirtualAddressSpace::freeStack(void *pStack)
{
}
<commit_msg>ArmV7VirtualAddressSpace::doAllocateStack, freeStack, and doSetFlags<commit_after>/*
* Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <panic.h>
#include <Log.h>
#include <utilities/utility.h>
#include <processor/Processor.h>
#include <processor/types.h>
#include <processor/PhysicalMemoryManager.h>
#include <LockGuard.h>
#include "VirtualAddressSpace.h"
ArmV7VirtualAddressSpace ArmV7VirtualAddressSpace::m_KernelSpace;
/** Array of free pages, used during the mapping algorithms in case a new page
table needs to be mapped, which must be done without relinquishing the lock
(which means we can't call the PMM!)
There is one page per processor. */
physical_uintptr_t g_EscrowPages[256]; /// \todo MAX_PROCESSORS
VirtualAddressSpace &VirtualAddressSpace::getKernelAddressSpace()
{
return ArmV7VirtualAddressSpace::m_KernelSpace;
}
VirtualAddressSpace *VirtualAddressSpace::create()
{
// TODO
//return new X86VirtualAddressSpace();
return 0;
}
ArmV7VirtualAddressSpace::ArmV7VirtualAddressSpace() :
VirtualAddressSpace(reinterpret_cast<void*> (0))
{
}
ArmV7VirtualAddressSpace::~ArmV7VirtualAddressSpace()
{
}
uint32_t ArmV7VirtualAddressSpace::toFlags(size_t flags)
{
uint32_t ret = 0; // No access.
if(flags & KernelMode)
{
ret = 1; // Read/write in privileged mode, not usable in user mode
}
else
{
if(flags & Write)
ret = 3; // Read/write all
else
ret = 2; // Read/write privileged, read-only user
}
return ret;
}
size_t ArmV7VirtualAddressSpace::fromFlags(uint32_t flags)
{
switch(flags)
{
case 0:
return 0; // Zero permissions
case 1:
return (Write | KernelMode);
case 2:
return 0; // Read-only by user mode... how to represent that?
case 3:
return Write; // Read/write all
default:
return 0;
}
}
bool ArmV7VirtualAddressSpace::initialise()
{
return true;
}
bool ArmV7VirtualAddressSpace::isAddressValid(void *virtualAddress)
{
// No address is "invalid" in the sense that we're looking for here.
return true;
}
bool ArmV7VirtualAddressSpace::map(physical_uintptr_t physicalAddress,
void *virtualAddress,
size_t flags)
{
return doMap(physicalAddress, virtualAddress, flags);
}
void ArmV7VirtualAddressSpace::unmap(void *virtualAddress)
{
return doUnmap(virtualAddress);
}
bool ArmV7VirtualAddressSpace::isMapped(void *virtualAddress)
{
return doIsMapped(virtualAddress);
}
void ArmV7VirtualAddressSpace::getMapping(void *virtualAddress,
physical_uintptr_t &physicalAddress,
size_t &flags)
{
doGetMapping(virtualAddress, physicalAddress, flags);
}
void ArmV7VirtualAddressSpace::setFlags(void *virtualAddress, size_t newFlags)
{
return doSetFlags(virtualAddress, newFlags);
}
void *ArmV7VirtualAddressSpace::allocateStack()
{
return doAllocateStack(USERSPACE_VIRTUAL_STACK_SIZE);
}
void *ArmV7VirtualAddressSpace::allocateStack(size_t stackSz)
{
return doAllocateStack(stackSz);
}
bool ArmV7VirtualAddressSpace::doIsMapped(void *virtualAddress)
{
uintptr_t addr = reinterpret_cast<uintptr_t>(virtualAddress);
uint32_t pdir_offset = addr >> 20;
uint32_t ptab_offset = (addr >> 12) & 0xFF;
// Grab the entry in the page directory
FirstLevelDescriptor *pdir = reinterpret_cast<FirstLevelDescriptor *>(m_VirtualPageDirectory);
if(pdir[pdir_offset].descriptor.entry)
{
// What type is the entry?
switch(pdir[pdir_offset].descriptor.fault.type)
{
case 1:
{
// Page table walk.
SecondLevelDescriptor *ptbl = reinterpret_cast<SecondLevelDescriptor *>(reinterpret_cast<uintptr_t>(m_VirtualPageTables) + pdir_offset);
if(!ptbl[ptab_offset].descriptor.fault.type)
return false;
break;
}
case 2:
// Section or supersection
WARNING("ArmV7VirtualAddressSpace::isAddressValid - sections and supersections not yet supported");
break;
default:
return false;
}
}
return true;
}
bool ArmV7VirtualAddressSpace::doMap(physical_uintptr_t physicalAddress,
void *virtualAddress,
size_t flags)
{
// Check if we have an allocated escrow page - if we don't, allocate it.
if (g_EscrowPages[Processor::id()] == 0)
{
g_EscrowPages[Processor::id()] = PhysicalMemoryManager::instance().allocatePage();
if (g_EscrowPages[Processor::id()] == 0)
{
// Still 0, we have problems.
FATAL("Out of memory");
}
}
LockGuard<Spinlock> guard(m_Lock);
// Grab offsets for the virtual address
uintptr_t addr = reinterpret_cast<uintptr_t>(virtualAddress);
uint32_t pdir_offset = addr >> 20;
uint32_t ptbl_offset = (addr >> 12) & 0xFF;
// Is there a page table for this page yet?
FirstLevelDescriptor *pdir = reinterpret_cast<FirstLevelDescriptor *>(m_VirtualPageDirectory);
if(!pdir[pdir_offset].descriptor.entry)
{
// There isn't - allocate one.
uintptr_t page = g_EscrowPages[Processor::id()];
g_EscrowPages[Processor::id()] = 0;
// Point to the page, which defines a page table, is not shareable,
// and is in domain 0. Note that there's 4 page tables in a 4K page,
// so we handle that here.
for(int i = 0; i < 4; i++)
{
/// \note For later: when creating high-memory page table mappings, they should be in
/// DOMAIN ONE - which holds all paging structures. This way they can be locked down
/// appropriately.
pdir[pdir_offset + i].descriptor.entry = page + (i * 1024);
pdir[pdir_offset + i].descriptor.pageTable.type = 1;
pdir[pdir_offset + i].descriptor.pageTable.sbz1 = pdir[pdir_offset + i].descriptor.pageTable.sbz2 = 0;
pdir[pdir_offset + i].descriptor.pageTable.ns = 1;
pdir[pdir_offset + i].descriptor.pageTable.domain = 0; // DOMAIN0: Main memory
pdir[pdir_offset + i].descriptor.pageTable.imp = 0;
// Map in the page table we've just created so we can zero it.
// mapaddr is the virtual address of the page table we just allocated
// physical space for.
uintptr_t mapaddr = reinterpret_cast<uintptr_t>(m_VirtualPageTables);
mapaddr += ((pdir_offset + i) * 0x400);
uint32_t ptbl_offset2 = (mapaddr >> 12) & 0xFF;
// Grab the right page table for this new page
uintptr_t ptbl_addr = reinterpret_cast<uintptr_t>(m_VirtualPageTables) + (mapaddr >> 20);
SecondLevelDescriptor *ptbl = reinterpret_cast<SecondLevelDescriptor*>(ptbl_addr);
ptbl[ptbl_offset2].descriptor.entry = page + (i * 1024);
ptbl[ptbl_offset2].descriptor.smallpage.type = 2;
ptbl[ptbl_offset2].descriptor.smallpage.b = 0;
ptbl[ptbl_offset2].descriptor.smallpage.c = 0;
ptbl[ptbl_offset2].descriptor.smallpage.ap1 = 3; // Page table, give it READ/WRITE
ptbl[ptbl_offset2].descriptor.smallpage.sbz = 0;
ptbl[ptbl_offset2].descriptor.smallpage.ap2 = 0;
ptbl[ptbl_offset2].descriptor.smallpage.s = 0;
ptbl[ptbl_offset2].descriptor.smallpage.nG = 1;
// Mapped, so clear the page now
memset(reinterpret_cast<void*>(mapaddr), 0, 1024);
}
}
// Grab the virtual address for the page table for this page
uintptr_t mapaddr = reinterpret_cast<uintptr_t>(USERSPACE_PAGETABLES);
mapaddr += pdir_offset * 0x400;
// Perform the mapping, if necessary
SecondLevelDescriptor *ptbl = reinterpret_cast<SecondLevelDescriptor*>(mapaddr);
if(ptbl[ptbl_offset].descriptor.entry & 0x3)
{
return false; // Already mapped.
}
else
{
ptbl[ptbl_offset].descriptor.entry = physicalAddress;
ptbl[ptbl_offset].descriptor.smallpage.type = 2;
ptbl[ptbl_offset].descriptor.smallpage.b = 0;
ptbl[ptbl_offset].descriptor.smallpage.c = 0;
ptbl[ptbl_offset].descriptor.smallpage.ap1 = toFlags(flags);
ptbl[ptbl_offset].descriptor.smallpage.sbz = 0;
ptbl[ptbl_offset].descriptor.smallpage.ap2 = 0;
ptbl[ptbl_offset].descriptor.smallpage.s = 0;
ptbl[ptbl_offset].descriptor.smallpage.nG = 1;
}
return true;
}
void ArmV7VirtualAddressSpace::doGetMapping(void *virtualAddress,
physical_uintptr_t &physicalAddress,
size_t &flags)
{
uintptr_t addr = reinterpret_cast<uintptr_t>(virtualAddress);
uint32_t pdir_offset = addr >> 20;
uint32_t ptab_offset = (addr >> 12) & 0xFF;
// Grab the entry in the page directory
FirstLevelDescriptor *pdir = reinterpret_cast<FirstLevelDescriptor *>(m_VirtualPageDirectory);
if(pdir[pdir_offset].descriptor.entry)
{
// What type is the entry?
switch(pdir[pdir_offset].descriptor.fault.type)
{
case 1:
{
// Page table walk.
SecondLevelDescriptor *ptbl = reinterpret_cast<SecondLevelDescriptor *>(reinterpret_cast<uintptr_t>(m_VirtualPageTables) + pdir_offset);
if(!ptbl[ptab_offset].descriptor.fault.type)
return;
else
{
physicalAddress = ptbl[ptab_offset].descriptor.smallpage.base << 12;
flags = fromFlags(ptbl[ptab_offset].descriptor.smallpage.ap1);
}
break;
}
case 2:
// Section or supersection
WARNING("ArmV7VirtualAddressSpace::doGetMapping - sections and supersections not yet supported");
break;
default:
return;
}
}
}
void ArmV7VirtualAddressSpace::doSetFlags(void *virtualAddress, size_t newFlags)
{
uintptr_t addr = reinterpret_cast<uintptr_t>(virtualAddress);
uint32_t pdir_offset = addr >> 20;
uint32_t ptab_offset = (addr >> 12) & 0xFF;
// Grab the entry in the page directory
FirstLevelDescriptor *pdir = reinterpret_cast<FirstLevelDescriptor *>(m_VirtualPageDirectory);
if(pdir[pdir_offset].descriptor.entry)
{
// What type is the entry?
switch(pdir[pdir_offset].descriptor.fault.type)
{
case 1:
{
// Page table walk.
SecondLevelDescriptor *ptbl = reinterpret_cast<SecondLevelDescriptor *>(reinterpret_cast<uintptr_t>(m_VirtualPageTables) + pdir_offset);
ptbl[ptab_offset].descriptor.smallpage.ap1 = toFlags(newFlags);
break;
}
case 2:
// Section or supersection
WARNING("ArmV7VirtualAddressSpace::doSetFlags - sections and supersections not yet supported");
break;
default:
return;
}
}
}
void ArmV7VirtualAddressSpace::doUnmap(void *virtualAddress)
{
uintptr_t addr = reinterpret_cast<uintptr_t>(virtualAddress);
uint32_t pdir_offset = addr >> 20;
uint32_t ptab_offset = (addr >> 12) & 0xFF;
// Grab the entry in the page directory
FirstLevelDescriptor *pdir = reinterpret_cast<FirstLevelDescriptor *>(m_VirtualPageDirectory);
if(pdir[pdir_offset].descriptor.entry)
{
// What type is the entry?
switch(pdir[pdir_offset].descriptor.fault.type)
{
case 1:
{
// Page table walk.
SecondLevelDescriptor *ptbl = reinterpret_cast<SecondLevelDescriptor *>(reinterpret_cast<uintptr_t>(m_VirtualPageTables) + pdir_offset);
ptbl[ptab_offset].descriptor.fault.type = 0; // Unmap.
break;
}
case 2:
// Section or supersection
pdir[pdir_offset].descriptor.fault.type = 0;
break;
default:
return;
}
}
}
void *ArmV7VirtualAddressSpace::doAllocateStack(size_t sSize)
{
m_Lock.acquire();
// Get a virtual address for the stack
void *pStack = 0;
if (m_freeStacks.count() != 0)
{
pStack = m_freeStacks.popBack();
m_Lock.release();
}
else
{
pStack = m_pStackTop;
m_pStackTop = adjust_pointer(m_pStackTop, -sSize);
m_Lock.release();
// Map it in
uintptr_t stackBottom = reinterpret_cast<uintptr_t>(pStack) - sSize;
for (size_t j = 0; j < sSize; j += PhysicalMemoryManager::getPageSize())
{
physical_uintptr_t phys = PhysicalMemoryManager::instance().allocatePage();
bool b = map(phys,
reinterpret_cast<void*> (j + stackBottom),
VirtualAddressSpace::Write);
if (!b)
WARNING("map() failed in doAllocateStack");
}
}
return pStack;
}
void ArmV7VirtualAddressSpace::freeStack(void *pStack)
{
// Add the stack to the list
m_freeStacks.pushBack(pStack);
}
<|endoftext|> |
<commit_before>#include "mediamanager.h"
#include "media/processing/filtergraph.h"
#include "media/processing/filter.h"
#include "media/delivery/delivery.h"
#include "ui/gui/videoviewfactory.h"
#include "initiation/negotiation/sdptypes.h"
#include "statisticsinterface.h"
#include "resourceallocator.h"
#include "common.h"
#include "settingskeys.h"
#include "logger.h"
#include <QHostAddress>
#include <QtEndian>
#include <QSettings>
MediaManager::MediaManager():
stats_(nullptr),
fg_(new FilterGraph()),
streamer_(nullptr)
{}
MediaManager::~MediaManager()
{
fg_->running(false);
fg_->uninit();
}
void MediaManager::init(std::shared_ptr<VideoviewFactory> viewfactory,
StatisticsInterface *stats)
{
Logger::getLogger()->printDebug(DEBUG_NORMAL, this, "Initiating");
viewfactory_ = viewfactory;
stats_ = stats;
streamer_ = std::unique_ptr<Delivery> (new Delivery());
connect(
streamer_.get(),
&Delivery::handleZRTPFailure,
this,
&MediaManager::handleZRTPFailure);
connect(
streamer_.get(),
&Delivery::handleNoEncryption,
this,
&MediaManager::handleNoEncryption);
std::shared_ptr<ResourceAllocator> hwResources =
std::shared_ptr<ResourceAllocator>(new ResourceAllocator());
fg_->init(viewfactory_->getSelfVideos(), stats, hwResources);
streamer_->init(stats_, hwResources);
QObject::connect(this, &MediaManager::updateVideoSettings,
fg_.get(), &FilterGraph::updateVideoSettings);
QObject::connect(this, &MediaManager::updateAudioSettings,
fg_.get(), &FilterGraph::updateAudioSettings);
QObject::connect(this, &MediaManager::updateAutomaticSettings,
fg_.get(), &FilterGraph::updateAutomaticSettings);
}
void MediaManager::uninit()
{
Logger::getLogger()->printDebug(DEBUG_NORMAL, this, "Closing");
// first filter graph, then streamer because of the rtpfilters
fg_->running(false);
fg_->uninit();
stats_ = nullptr;
if (streamer_ != nullptr)
{
streamer_->uninit();
streamer_ = nullptr;
}
}
void MediaManager::addParticipant(uint32_t sessionID,
std::shared_ptr<SDPMessageInfo> peerInfo,
const std::shared_ptr<SDPMessageInfo> localInfo)
{
// TODO: support stop-time and start-time as recommended by RFC 4566 section 5.9
Q_ASSERT(peerInfo->media.size() == localInfo->media.size());
if (peerInfo->media.size() != localInfo->media.size() || peerInfo->media.empty())
{
Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, "Media manager",
"addParticipant, invalid SDPs",
{"LocalInfo", "PeerInfo"},
{QString::number(localInfo->media.size()),
QString::number(peerInfo->media.size())});
return;
}
if(peerInfo->timeDescriptions.at(0).startTime != 0 ||
localInfo->timeDescriptions.at(0).startTime != 0)
{
Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this,
"Nonzero start-time not supported!");
return;
}
if (getMediaNettype(peerInfo, 0) == "IN")
{
if(!streamer_->addPeer(sessionID,
getMediaAddrtype(peerInfo, 0),
getMediaAddress(peerInfo, 0),
getMediaAddrtype(localInfo, 0),
getMediaAddress(localInfo, 0)))
{
Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this,
"Error creating RTP peer. Simultaneous destruction?");
return;
}
}
else
{
Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this,
"What are we using if not the internet!?");
return;
}
Logger::getLogger()->printDebug(DEBUG_NORMAL, this, "Start creating media.",
{"Outgoing media", "Incoming media"},
{QString::number(peerInfo->media.size()),
QString::number(localInfo->media.size())});
if (stats_ != nullptr)
{
sdpToStats(sessionID, peerInfo, false);
sdpToStats(sessionID, localInfo, true);
}
// create each agreed media stream
for(int i = 0; i < peerInfo->media.size(); ++i) {
// TODO: I don't like that we match
createOutgoingMedia(sessionID,
localInfo->media.at(i),
getMediaAddress(peerInfo, i),
peerInfo->media.at(i));
}
for (int i = 0; i < localInfo->media.size(); ++i)
{
createIncomingMedia(sessionID, localInfo->media.at(i),
getMediaAddress(localInfo, i),
peerInfo->media.at(i));
}
// TODO: crashes at the moment.
//fg_->print();
}
void MediaManager::createOutgoingMedia(uint32_t sessionID,
const MediaInfo& localMedia,
QString peerAddress,
const MediaInfo& remoteMedia)
{
if (peerAddress == "")
{
Logger::getLogger()->printProgramError(this, "Address was empty when creating outgoing media");
return;
}
bool send = true;
bool recv = true;
transportAttributes(remoteMedia.flagAttributes, send, recv);
// if they want to receive
if(recv && remoteMedia.receivePort != 0)
{
Q_ASSERT(remoteMedia.receivePort);
Q_ASSERT(!remoteMedia.rtpNums.empty());
QString codec = rtpNumberToCodec(remoteMedia);
if(remoteMedia.proto == "RTP/AVP")
{
std::shared_ptr<Filter> framedSource = streamer_->addSendStream(sessionID, peerAddress,
localMedia.receivePort, remoteMedia.receivePort,
codec, remoteMedia.rtpNums.at(0));
Q_ASSERT(framedSource != nullptr);
if(remoteMedia.type == "audio")
{
fg_->sendAudioTo(sessionID, std::shared_ptr<Filter>(framedSource));
}
else if(remoteMedia.type == "video")
{
fg_->sendVideoto(sessionID, std::shared_ptr<Filter>(framedSource));
}
else
{
Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this, "Unsupported media type!",
{"type"}, QStringList() << remoteMedia.type);
}
}
else
{
Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this, "SDP transport protocol not supported.");
}
}
else
{
Logger::getLogger()->printDebug(DEBUG_NORMAL, this,
"Not creating media because they don't seem to want any according to attribute.");
// TODO: Spec says we should still send RTCP
}
}
void MediaManager::createIncomingMedia(uint32_t sessionID,
const MediaInfo &localMedia,
QString localAddress,
const MediaInfo &remoteMedia)
{
if (localAddress == "")
{
Logger::getLogger()->printProgramError(this, "Address was empty when creating incoming media");
return;
}
bool send = true;
bool recv = true;
transportAttributes(localMedia.flagAttributes, send, recv);
if(recv)
{
Q_ASSERT(localMedia.receivePort);
Q_ASSERT(!localMedia.rtpNums.empty());
QString codec = rtpNumberToCodec(localMedia);
if(localMedia.proto == "RTP/AVP")
{
std::shared_ptr<Filter> rtpSink = streamer_->addReceiveStream(sessionID, localAddress,
localMedia.receivePort,
remoteMedia.receivePort,
codec, localMedia.rtpNums.at(0));
Q_ASSERT(rtpSink != nullptr);
if(localMedia.type == "audio")
{
fg_->receiveAudioFrom(sessionID, std::shared_ptr<Filter>(rtpSink));
}
else if(localMedia.type == "video")
{
VideoInterface *view = viewfactory_->getVideo(sessionID);
Q_ASSERT(view);
if (view != nullptr)
{
fg_->receiveVideoFrom(sessionID, std::shared_ptr<Filter>(rtpSink), view);
}
else {
Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this, "Failed to get view from viewFactory");
}
}
else
{
Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this, "Unsupported incoming media type!",
{"type"}, QStringList() << localMedia.type);
}
}
else
{
Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this,
"Incoming SDP transport protocol not supported.");
}
}
else
{
Logger::getLogger()->printDebug(DEBUG_NORMAL, this,
"Not creating media because they don't seem to want any according to attribute.");
}
}
void MediaManager::removeParticipant(uint32_t sessionID)
{
fg_->removeParticipant(sessionID);
streamer_->removePeer(sessionID);
Logger::getLogger()->printDebug(DEBUG_NORMAL, "Media Manager", "Session media removed",
{"SessionID"}, {QString::number(sessionID)});
}
QString MediaManager::rtpNumberToCodec(const MediaInfo& info)
{
// If we are not using raw.
// This is the place where all other preset audio video codec numbers should be set
// but its unlikely that we will support any besides raw pcmu.
if(info.rtpNums.at(0) != 0)
{
Q_ASSERT(!info.codecs.empty());
if(!info.codecs.empty())
{
return info.codecs.at(0).codec;
}
}
return "PCMU";
}
void MediaManager::transportAttributes(const QList<SDPAttributeType>& attributes, bool& send, bool& recv)
{
send = true;
recv = true;
for(SDPAttributeType attribute : attributes)
{
if(attribute == A_SENDRECV)
{
send = true;
recv = true;
}
else if(attribute == A_SENDONLY)
{
send = true;
recv = false;
}
else if(attribute == A_RECVONLY)
{
send = false;
recv = true;
}
else if(attribute == A_INACTIVE)
{
send = false;
recv = false;
}
}
}
void MediaManager::sdpToStats(uint32_t sessionID, std::shared_ptr<SDPMessageInfo> sdp, bool incoming)
{
// TODO: This feels like a hack to do this here. Instead we should give stats the whole SDP
QStringList ipList;
QStringList audioPorts;
QStringList videoPorts;
// create each agreed media stream
for (auto& media : sdp->media)
{
if (media.type == "audio")
{
audioPorts.append(QString::number(media.receivePort));
}
else if (media.type == "video")
{
videoPorts.append(QString::number(media.receivePort));
}
if (media.connection_address != "")
{
ipList.append(media.connection_address);
}
else
{
ipList.append(sdp->connection_address);
}
}
if (stats_)
{
if (incoming)
{
stats_->incomingMedia(sessionID, sdp->originator_username, ipList, audioPorts, videoPorts);
}
else
{
stats_->outgoingMedia(sessionID, sdp->originator_username,ipList, audioPorts, videoPorts);
}
}
}
QString MediaManager::getMediaNettype(std::shared_ptr<SDPMessageInfo> sdp, int mediaIndex)
{
if (sdp->media.size() >= mediaIndex && sdp->media.at(mediaIndex).connection_nettype != "")
{
return sdp->media.at(mediaIndex).connection_nettype;
}
return sdp->connection_nettype;
}
QString MediaManager::getMediaAddrtype(std::shared_ptr<SDPMessageInfo> sdp, int mediaIndex)
{
if (sdp->media.size() >= mediaIndex && sdp->media.at(mediaIndex).connection_addrtype != "")
{
return sdp->media.at(mediaIndex).connection_addrtype;
}
return sdp->connection_addrtype;
}
QString MediaManager::getMediaAddress(std::shared_ptr<SDPMessageInfo> sdp, int mediaIndex)
{
if (sdp->media.size() >= mediaIndex && sdp->media.at(mediaIndex).connection_address != "")
{
return sdp->media.at(mediaIndex).connection_address;
}
return sdp->connection_address;
}
<commit_msg>fix(Statistics): Use correct name in graphs<commit_after>#include "mediamanager.h"
#include "media/processing/filtergraph.h"
#include "media/processing/filter.h"
#include "media/delivery/delivery.h"
#include "ui/gui/videoviewfactory.h"
#include "initiation/negotiation/sdptypes.h"
#include "statisticsinterface.h"
#include "resourceallocator.h"
#include "common.h"
#include "settingskeys.h"
#include "logger.h"
#include <QHostAddress>
#include <QtEndian>
#include <QSettings>
MediaManager::MediaManager():
stats_(nullptr),
fg_(new FilterGraph()),
streamer_(nullptr)
{}
MediaManager::~MediaManager()
{
fg_->running(false);
fg_->uninit();
}
void MediaManager::init(std::shared_ptr<VideoviewFactory> viewfactory,
StatisticsInterface *stats)
{
Logger::getLogger()->printDebug(DEBUG_NORMAL, this, "Initiating");
viewfactory_ = viewfactory;
stats_ = stats;
streamer_ = std::unique_ptr<Delivery> (new Delivery());
connect(
streamer_.get(),
&Delivery::handleZRTPFailure,
this,
&MediaManager::handleZRTPFailure);
connect(
streamer_.get(),
&Delivery::handleNoEncryption,
this,
&MediaManager::handleNoEncryption);
std::shared_ptr<ResourceAllocator> hwResources =
std::shared_ptr<ResourceAllocator>(new ResourceAllocator());
fg_->init(viewfactory_->getSelfVideos(), stats, hwResources);
streamer_->init(stats_, hwResources);
QObject::connect(this, &MediaManager::updateVideoSettings,
fg_.get(), &FilterGraph::updateVideoSettings);
QObject::connect(this, &MediaManager::updateAudioSettings,
fg_.get(), &FilterGraph::updateAudioSettings);
QObject::connect(this, &MediaManager::updateAutomaticSettings,
fg_.get(), &FilterGraph::updateAutomaticSettings);
}
void MediaManager::uninit()
{
Logger::getLogger()->printDebug(DEBUG_NORMAL, this, "Closing");
// first filter graph, then streamer because of the rtpfilters
fg_->running(false);
fg_->uninit();
stats_ = nullptr;
if (streamer_ != nullptr)
{
streamer_->uninit();
streamer_ = nullptr;
}
}
void MediaManager::addParticipant(uint32_t sessionID,
std::shared_ptr<SDPMessageInfo> peerInfo,
const std::shared_ptr<SDPMessageInfo> localInfo)
{
// TODO: support stop-time and start-time as recommended by RFC 4566 section 5.9
Q_ASSERT(peerInfo->media.size() == localInfo->media.size());
if (peerInfo->media.size() != localInfo->media.size() || peerInfo->media.empty())
{
Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, "Media manager",
"addParticipant, invalid SDPs",
{"LocalInfo", "PeerInfo"},
{QString::number(localInfo->media.size()),
QString::number(peerInfo->media.size())});
return;
}
if(peerInfo->timeDescriptions.at(0).startTime != 0 ||
localInfo->timeDescriptions.at(0).startTime != 0)
{
Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this,
"Nonzero start-time not supported!");
return;
}
if (getMediaNettype(peerInfo, 0) == "IN")
{
if(!streamer_->addPeer(sessionID,
getMediaAddrtype(peerInfo, 0),
getMediaAddress(peerInfo, 0),
getMediaAddrtype(localInfo, 0),
getMediaAddress(localInfo, 0)))
{
Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this,
"Error creating RTP peer. Simultaneous destruction?");
return;
}
}
else
{
Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this,
"What are we using if not the internet!?");
return;
}
Logger::getLogger()->printDebug(DEBUG_NORMAL, this, "Start creating media.",
{"Outgoing media", "Incoming media"},
{QString::number(peerInfo->media.size()),
QString::number(localInfo->media.size())});
if (stats_ != nullptr)
{
sdpToStats(sessionID, peerInfo, true);
sdpToStats(sessionID, localInfo, false);
}
// create each agreed media stream
for(int i = 0; i < peerInfo->media.size(); ++i) {
// TODO: I don't like that we match
createOutgoingMedia(sessionID,
localInfo->media.at(i),
getMediaAddress(peerInfo, i),
peerInfo->media.at(i));
}
for (int i = 0; i < localInfo->media.size(); ++i)
{
createIncomingMedia(sessionID, localInfo->media.at(i),
getMediaAddress(localInfo, i),
peerInfo->media.at(i));
}
// TODO: crashes at the moment.
//fg_->print();
}
void MediaManager::createOutgoingMedia(uint32_t sessionID,
const MediaInfo& localMedia,
QString peerAddress,
const MediaInfo& remoteMedia)
{
if (peerAddress == "")
{
Logger::getLogger()->printProgramError(this, "Address was empty when creating outgoing media");
return;
}
bool send = true;
bool recv = true;
transportAttributes(remoteMedia.flagAttributes, send, recv);
// if they want to receive
if(recv && remoteMedia.receivePort != 0)
{
Q_ASSERT(remoteMedia.receivePort);
Q_ASSERT(!remoteMedia.rtpNums.empty());
QString codec = rtpNumberToCodec(remoteMedia);
if(remoteMedia.proto == "RTP/AVP")
{
std::shared_ptr<Filter> framedSource = streamer_->addSendStream(sessionID, peerAddress,
localMedia.receivePort, remoteMedia.receivePort,
codec, remoteMedia.rtpNums.at(0));
Q_ASSERT(framedSource != nullptr);
if(remoteMedia.type == "audio")
{
fg_->sendAudioTo(sessionID, std::shared_ptr<Filter>(framedSource));
}
else if(remoteMedia.type == "video")
{
fg_->sendVideoto(sessionID, std::shared_ptr<Filter>(framedSource));
}
else
{
Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this, "Unsupported media type!",
{"type"}, QStringList() << remoteMedia.type);
}
}
else
{
Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this, "SDP transport protocol not supported.");
}
}
else
{
Logger::getLogger()->printDebug(DEBUG_NORMAL, this,
"Not creating media because they don't seem to want any according to attribute.");
// TODO: Spec says we should still send RTCP
}
}
void MediaManager::createIncomingMedia(uint32_t sessionID,
const MediaInfo &localMedia,
QString localAddress,
const MediaInfo &remoteMedia)
{
if (localAddress == "")
{
Logger::getLogger()->printProgramError(this, "Address was empty when creating incoming media");
return;
}
bool send = true;
bool recv = true;
transportAttributes(localMedia.flagAttributes, send, recv);
if(recv)
{
Q_ASSERT(localMedia.receivePort);
Q_ASSERT(!localMedia.rtpNums.empty());
QString codec = rtpNumberToCodec(localMedia);
if(localMedia.proto == "RTP/AVP")
{
std::shared_ptr<Filter> rtpSink = streamer_->addReceiveStream(sessionID, localAddress,
localMedia.receivePort,
remoteMedia.receivePort,
codec, localMedia.rtpNums.at(0));
Q_ASSERT(rtpSink != nullptr);
if(localMedia.type == "audio")
{
fg_->receiveAudioFrom(sessionID, std::shared_ptr<Filter>(rtpSink));
}
else if(localMedia.type == "video")
{
VideoInterface *view = viewfactory_->getVideo(sessionID);
Q_ASSERT(view);
if (view != nullptr)
{
fg_->receiveVideoFrom(sessionID, std::shared_ptr<Filter>(rtpSink), view);
}
else {
Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this, "Failed to get view from viewFactory");
}
}
else
{
Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this, "Unsupported incoming media type!",
{"type"}, QStringList() << localMedia.type);
}
}
else
{
Logger::getLogger()->printDebug(DEBUG_PROGRAM_ERROR, this,
"Incoming SDP transport protocol not supported.");
}
}
else
{
Logger::getLogger()->printDebug(DEBUG_NORMAL, this,
"Not creating media because they don't seem to want any according to attribute.");
}
}
void MediaManager::removeParticipant(uint32_t sessionID)
{
fg_->removeParticipant(sessionID);
streamer_->removePeer(sessionID);
Logger::getLogger()->printDebug(DEBUG_NORMAL, "Media Manager", "Session media removed",
{"SessionID"}, {QString::number(sessionID)});
}
QString MediaManager::rtpNumberToCodec(const MediaInfo& info)
{
// If we are not using raw.
// This is the place where all other preset audio video codec numbers should be set
// but its unlikely that we will support any besides raw pcmu.
if(info.rtpNums.at(0) != 0)
{
Q_ASSERT(!info.codecs.empty());
if(!info.codecs.empty())
{
return info.codecs.at(0).codec;
}
}
return "PCMU";
}
void MediaManager::transportAttributes(const QList<SDPAttributeType>& attributes, bool& send, bool& recv)
{
send = true;
recv = true;
for(SDPAttributeType attribute : attributes)
{
if(attribute == A_SENDRECV)
{
send = true;
recv = true;
}
else if(attribute == A_SENDONLY)
{
send = true;
recv = false;
}
else if(attribute == A_RECVONLY)
{
send = false;
recv = true;
}
else if(attribute == A_INACTIVE)
{
send = false;
recv = false;
}
}
}
void MediaManager::sdpToStats(uint32_t sessionID, std::shared_ptr<SDPMessageInfo> sdp, bool incoming)
{
// TODO: This feels like a hack to do this here. Instead we should give stats the whole SDP
QStringList ipList;
QStringList audioPorts;
QStringList videoPorts;
// create each agreed media stream
for (auto& media : sdp->media)
{
if (media.type == "audio")
{
audioPorts.append(QString::number(media.receivePort));
}
else if (media.type == "video")
{
videoPorts.append(QString::number(media.receivePort));
}
if (media.connection_address != "")
{
ipList.append(media.connection_address);
}
else
{
ipList.append(sdp->connection_address);
}
}
if (stats_)
{
if (incoming)
{
stats_->incomingMedia(sessionID, sdp->originator_username, ipList, audioPorts, videoPorts);
}
else
{
stats_->outgoingMedia(sessionID, sdp->originator_username,ipList, audioPorts, videoPorts);
}
}
}
QString MediaManager::getMediaNettype(std::shared_ptr<SDPMessageInfo> sdp, int mediaIndex)
{
if (sdp->media.size() >= mediaIndex && sdp->media.at(mediaIndex).connection_nettype != "")
{
return sdp->media.at(mediaIndex).connection_nettype;
}
return sdp->connection_nettype;
}
QString MediaManager::getMediaAddrtype(std::shared_ptr<SDPMessageInfo> sdp, int mediaIndex)
{
if (sdp->media.size() >= mediaIndex && sdp->media.at(mediaIndex).connection_addrtype != "")
{
return sdp->media.at(mediaIndex).connection_addrtype;
}
return sdp->connection_addrtype;
}
QString MediaManager::getMediaAddress(std::shared_ptr<SDPMessageInfo> sdp, int mediaIndex)
{
if (sdp->media.size() >= mediaIndex && sdp->media.at(mediaIndex).connection_address != "")
{
return sdp->media.at(mediaIndex).connection_address;
}
return sdp->connection_address;
}
<|endoftext|> |
<commit_before>/* rbOOmit: An implementation of the Certified Reduced Basis method. */
/* Copyright (C) 2009, 2010 David J. Knezevic */
/* This file is part of rbOOmit. */
/* rbOOmit 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. */
/* rbOOmit 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 */
// <h1>Reduced Basis: Example 6 - Heat transfer on a curved domain in 3D</h1>
// In this example we consider heat transfer modeled by a Poisson equation with
// Robin boundary condition:
// -kappa \Laplacian u = 1, on \Omega
// -kappa du\dn = kappa Bi u, on \partial\Omega_Biot,
// u = 0 on \partial\Omega_Dirichlet,
//
// We consider a reference domain \Omega_hat = [0,0.4]x[0,0.4]x[0,3], and the
// physical domain is then obtain via the parametrized mapping:
// x = -1/mu + (1/mu+x_hat)*cos(mu*z_hat)
// y = y_hat
// z = (1/mu+x_hat)*sin(mu*z_hat)
// for (x_hat,y_hat,z_hat) \in \Omega_hat. (Here "hats" denotes reference domain.)
// Also, the "reference Dirichlet boundaries" are [0,0.4]x[0,0.4]x{0} and
// [0,0.4]x[0,0.4]x{3}, and the remaining boundaries are the "Biot" boundaries.
// Then, after putting the PDE into weak form and mapping it to the reference domain,
// we obtain:
// \kappa \int_\Omega_hat [ (1+mu*x_hat) v_x w_x + v_y w_y + 1/(1+mu*x_hat) v_z w_z ]
// + \kappa Bi \int_\partial\Omega_hat_Biot1 u v
// + \kappa Bi \int_\partial\Omega_hat_Biot2 (1+mu x_hat) u v
// + \kappa Bi \int_\partial\Omega_hat_Biot3 (1+0.4mu) u v
// = \int_\Omega_hat (1+mu x_hat) v
// where
// \partial\Omega_hat_Biot1 = [0] x [0,0.4] x [0,3]
// \partial\Omega_hat_Biot2 = [0,0.4] x {0} x [0,3] \UNION [0,0.4] x {0.4} x [0,3]
// \partial\Omega_hat_Biot3 = [0.4] x [0,0.4] x [0,3]
// The term
// \kappa \int_\Omega_hat 1/(1+mu*x_hat) v_z w_z
// is "non-affine" (in the Reduced Basis sense), since we can't express it
// in the form \sum theta_q(kappa,mu) a(v,w). As a result, (as in
// reduced_basis_ex4) we must employ the Empirical Interpolation Method (EIM)
// in order to apply the Reduced Basis method here.
// The approach we use is to construct an EIM approximation, G_EIM, to the vector-valued function
// G(x_hat,y_hat;mu) = (1 + mu*x_hat, 1, 1/(1+mu*x_hat))
// and then we express the "volumetric integral part" of the left-hand side operator as
// a(v,w;mu) = \int_\hat\Omega G_EIM(x_hat,y_hat;mu) \dot (v_x w_x, v_y w_y, v_z w_z).
// (We actually only need EIM for the third component of G_EIM, but it's helpful to
// demonstrate "vector-valued" EIM here.)
// C++ include files that we need
#include <iostream>
#include <algorithm>
#include <cmath>
#include <set>
// Basic include file needed for the mesh functionality.
#include "libmesh.h"
#include "mesh.h"
#include "mesh_generation.h"
#include "exodusII_io.h"
#include "equation_systems.h"
#include "dof_map.h"
#include "getpot.h"
#include "elem.h"
// local includes
#include "rb_classes.h"
#include "eim_classes.h"
#include "assembly.h"
// Bring in everything from the libMesh namespace
using namespace libMesh;
// Define a function to scale the mesh according to the parameter.
void transform_mesh_and_plot(EquationSystems& es, Real curvature, const std::string& filename);
// The main program.
int main (int argc, char** argv)
{
// Initialize libMesh.
LibMeshInit init (argc, argv);
#if !defined(LIBMESH_HAVE_XDR)
// We need XDR support to write out reduced bases
libmesh_example_assert(false, "--enable-xdr");
#elif defined(LIBMESH_DEFAULT_SINGLE_PRECISION)
// XDR binary support requires double precision
libmesh_example_assert(false, "--disable-singleprecision");
#endif
// FIXME: This example currently segfaults with Trilinos?
libmesh_example_assert(libMesh::default_solver_package() == PETSC_SOLVERS, "--enable-petsc");
// This is a 3D example
libmesh_example_assert(3 == LIBMESH_DIM, "3D support");
// Parse the input file using GetPot
std::string eim_parameters = "eim.in";
std::string rb_parameters = "rb.in";
std::string main_parameters = "reduced_basis_ex6.in";
GetPot infile(main_parameters);
unsigned int n_elem_xy = infile("n_elem_xy", 1);
unsigned int n_elem_z = infile("n_elem_z", 1);
// Do we write the RB basis functions to disk?
bool store_basis_functions = infile("store_basis_functions", true);
// Read the "online_mode" flag from the command line
GetPot command_line (argc, argv);
int online_mode = 0;
if ( command_line.search(1, "-online_mode") )
online_mode = command_line.next(online_mode);
// Build a mesh.
Mesh mesh;
MeshTools::Generation::build_cube (mesh,
n_elem_xy, n_elem_xy, n_elem_z,
0., 0.4,
0., 0.4,
0., 3.,
HEX8);
// Create an equation systems object.
EquationSystems equation_systems (mesh);
SimpleEIMConstruction & eim_construction =
equation_systems.add_system<SimpleEIMConstruction> ("EIM");
SimpleRBConstruction & rb_construction =
equation_systems.add_system<SimpleRBConstruction> ("RB");
// Initialize the data structures for the equation system.
equation_systems.init ();
// Print out some information about the "truth" discretization
equation_systems.print_info();
mesh.print_info();
// Initialize the standard RBEvaluation object
SimpleRBEvaluation rb_eval;
// Initialize the EIM RBEvaluation object
SimpleEIMEvaluation eim_rb_eval;
// Set the rb_eval objects for the RBConstructions
eim_construction.set_rb_evaluation(eim_rb_eval);
rb_construction.set_rb_evaluation(rb_eval);
if(!online_mode) // Perform the Offline stage of the RB method
{
// Read data from input file and print state
eim_construction.process_parameters_file(eim_parameters);
eim_construction.print_info();
// Perform the EIM Greedy and write out the data
eim_construction.initialize_rb_construction();
eim_construction.train_reduced_basis();
eim_construction.get_rb_evaluation().write_offline_data_to_files("eim_data");
// Read data from input file and print state
rb_construction.process_parameters_file(rb_parameters);
// attach the EIM theta objects to the RBConstruction and RBEvaluation objects
eim_rb_eval.initialize_eim_theta_objects();
rb_eval.get_rb_theta_expansion().attach_multiple_A_theta(eim_rb_eval.get_eim_theta_objects());
// attach the EIM assembly objects to the RBConstruction object
eim_construction.initialize_eim_assembly_objects();
rb_construction.get_rb_assembly_expansion().attach_multiple_A_assembly(eim_construction.get_eim_assembly_objects());
// Print out the state of rb_construction now that the EIM objects have been attached
rb_construction.print_info();
// Need to initialize _after_ EIM greedy so that
// the system knows how many affine terms there are
rb_construction.initialize_rb_construction();
rb_construction.train_reduced_basis();
rb_construction.get_rb_evaluation().write_offline_data_to_files("rb_data");
// Write out the basis functions, if requested
if(store_basis_functions)
{
// Write out the basis functions
eim_construction.get_rb_evaluation().write_out_basis_functions(eim_construction,"eim_data");
rb_construction.get_rb_evaluation().write_out_basis_functions(rb_construction,"rb_data");
}
}
else // Perform the Online stage of the RB method
{
eim_rb_eval.read_offline_data_from_files("eim_data");
// attach the EIM theta objects to rb_eval objects
eim_rb_eval.initialize_eim_theta_objects();
rb_eval.get_rb_theta_expansion().attach_multiple_A_theta(eim_rb_eval.get_eim_theta_objects());
// Read in the offline data for rb_eval
rb_eval.read_offline_data_from_files("rb_data");
// Get the parameters at which we will do a reduced basis solve
Real online_curvature = infile("online_curvature", 0.);
Real online_Bi = infile("online_Bi", 0.);
Real online_kappa = infile("online_kappa", 0.);
RBParameters online_mu;
online_mu.set_value("curvature", online_curvature);
online_mu.set_value("Bi", online_Bi);
online_mu.set_value("kappa", online_kappa);
rb_eval.set_parameters(online_mu);
rb_eval.print_parameters();
rb_eval.rb_solve( rb_eval.get_n_basis_functions() );
// plot the solution, if requested
if(store_basis_functions)
{
// read in the data from files
eim_rb_eval.read_in_basis_functions(eim_construction,"eim_data");
rb_eval.read_in_basis_functions(rb_construction,"rb_data");
eim_construction.load_rb_solution();
rb_construction.load_rb_solution();
transform_mesh_and_plot(equation_systems,online_curvature,"RB_sol.e");
}
}
return 0;
}
void transform_mesh_and_plot(EquationSystems& es, Real curvature, const std::string& filename)
{
// Loop over the mesh nodes and move them!
MeshBase& mesh = es.get_mesh();
MeshBase::node_iterator node_it = mesh.nodes_begin();
const MeshBase::node_iterator node_end = mesh.nodes_end();
for( ; node_it != node_end; node_it++)
{
Node* node = *node_it;
Real x = (*node)(0);
Real z = (*node)(2);
(*node)(0) = -1./curvature + (1./curvature + x)*cos(curvature*z);
(*node)(2) = (1./curvature + x)*sin(curvature*z);
}
#ifdef LIBMESH_HAVE_EXODUS_API
ExodusII_IO(mesh).write_equation_systems(filename, es);
#endif
}
<commit_msg>fixed comments in reduced_basis_ex6<commit_after>/* rbOOmit: An implementation of the Certified Reduced Basis method. */
/* Copyright (C) 2009, 2010 David J. Knezevic */
/* This file is part of rbOOmit. */
/* rbOOmit 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. */
/* rbOOmit 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 */
// <h1>Reduced Basis: Example 6 - Heat transfer on a curved domain in 3D</h1>
// In this example we consider heat transfer modeled by a Poisson equation with
// Robin boundary condition:
// -kappa \Laplacian u = 1, on \Omega
// -kappa du\dn = kappa Bi u, on \partial\Omega_Biot,
// u = 0 on \partial\Omega_Dirichlet,
//
// We consider a reference domain \Omega_hat = [0,0.4]x[0,0.4]x[0,3], and the
// physical domain is then obtain via the parametrized mapping:
// x = -1/mu + (1/mu+x_hat)*cos(mu*z_hat)
// y = y_hat
// z = (1/mu+x_hat)*sin(mu*z_hat)
// for (x_hat,y_hat,z_hat) \in \Omega_hat. (Here "hats" denotes reference domain.)
// Also, the "reference Dirichlet boundaries" are [0,0.4]x[0,0.4]x{0} and
// [0,0.4]x[0,0.4]x{3}, and the remaining boundaries are the "Biot" boundaries.
// Then, after putting the PDE into weak form and mapping it to the reference domain,
// we obtain:
// \kappa \int_\Omega_hat [ (1+mu*x_hat) v_x w_x + v_y w_y + 1/(1+mu*x_hat) v_z w_z ]
// + \kappa Bi \int_\partial\Omega_hat_Biot1 u v
// + \kappa Bi \int_\partial\Omega_hat_Biot2 (1+mu x_hat) u v
// + \kappa Bi \int_\partial\Omega_hat_Biot3 (1+0.4mu) u v
// = \int_\Omega_hat (1+mu x_hat) v
// where
// \partial\Omega_hat_Biot1 = [0] x [0,0.4] x [0,3]
// \partial\Omega_hat_Biot2 = [0,0.4] x {0} x [0,3] \UNION [0,0.4] x {0.4} x [0,3]
// \partial\Omega_hat_Biot3 = [0.4] x [0,0.4] x [0,3]
// The term
// \kappa \int_\Omega_hat 1/(1+mu*x_hat) v_z w_z
// is "non-affine" (in the Reduced Basis sense), since we can't express it
// in the form \sum theta_q(kappa,mu) a(v,w). As a result, (as in
// reduced_basis_ex4) we must employ the Empirical Interpolation Method (EIM)
// in order to apply the Reduced Basis method here.
// The approach we use is to construct an EIM approximation, G_EIM, to the vector-valued function
// G(x_hat,y_hat;mu) = (1 + mu*x_hat, 1, 1/(1+mu*x_hat))
// and then we express the "volumetric integral part" of the left-hand side operator as
// a(v,w;mu) = \int_\hat\Omega G_EIM(x_hat,y_hat;mu) \dot (v_x w_x, v_y w_y, v_z w_z).
// (We actually only need EIM for the third component of G_EIM, but it's helpful to
// demonstrate "vector-valued" EIM here.)
// C++ include files that we need
#include <iostream>
#include <algorithm>
#include <cmath>
#include <set>
// Basic include file needed for the mesh functionality.
#include "libmesh.h"
#include "mesh.h"
#include "mesh_generation.h"
#include "exodusII_io.h"
#include "equation_systems.h"
#include "dof_map.h"
#include "getpot.h"
#include "elem.h"
// local includes
#include "rb_classes.h"
#include "eim_classes.h"
#include "assembly.h"
// Bring in everything from the libMesh namespace
using namespace libMesh;
// Define a function to scale the mesh according to the parameter.
void transform_mesh_and_plot(EquationSystems& es, Real curvature, const std::string& filename);
// The main program.
int main (int argc, char** argv)
{
// Initialize libMesh.
LibMeshInit init (argc, argv);
#if !defined(LIBMESH_HAVE_XDR)
// We need XDR support to write out reduced bases
libmesh_example_assert(false, "--enable-xdr");
#elif defined(LIBMESH_DEFAULT_SINGLE_PRECISION)
// XDR binary support requires double precision
libmesh_example_assert(false, "--disable-singleprecision");
#endif
// FIXME: This example currently segfaults with Trilinos?
libmesh_example_assert(libMesh::default_solver_package() == PETSC_SOLVERS, "--enable-petsc");
// This is a 3D example
libmesh_example_assert(3 == LIBMESH_DIM, "3D support");
// Parse the input file using GetPot
std::string eim_parameters = "eim.in";
std::string rb_parameters = "rb.in";
std::string main_parameters = "reduced_basis_ex6.in";
GetPot infile(main_parameters);
unsigned int n_elem_xy = infile("n_elem_xy", 1);
unsigned int n_elem_z = infile("n_elem_z", 1);
// Do we write the RB basis functions to disk?
bool store_basis_functions = infile("store_basis_functions", true);
// Read the "online_mode" flag from the command line
GetPot command_line (argc, argv);
int online_mode = 0;
if ( command_line.search(1, "-online_mode") )
online_mode = command_line.next(online_mode);
// Build a mesh.
Mesh mesh;
MeshTools::Generation::build_cube (mesh,
n_elem_xy, n_elem_xy, n_elem_z,
0., 0.4,
0., 0.4,
0., 3.,
HEX8);
// Create an equation systems object.
EquationSystems equation_systems (mesh);
SimpleEIMConstruction & eim_construction =
equation_systems.add_system<SimpleEIMConstruction> ("EIM");
SimpleRBConstruction & rb_construction =
equation_systems.add_system<SimpleRBConstruction> ("RB");
// Initialize the data structures for the equation system.
equation_systems.init ();
// Print out some information about the "truth" discretization
equation_systems.print_info();
mesh.print_info();
// Initialize the standard RBEvaluation object
SimpleRBEvaluation rb_eval;
// Initialize the EIM RBEvaluation object
SimpleEIMEvaluation eim_rb_eval;
// Set the rb_eval objects for the RBConstructions
eim_construction.set_rb_evaluation(eim_rb_eval);
rb_construction.set_rb_evaluation(rb_eval);
if(!online_mode) // Perform the Offline stage of the RB method
{
// Read data from input file and print state
eim_construction.process_parameters_file(eim_parameters);
eim_construction.print_info();
// Perform the EIM Greedy and write out the data
eim_construction.initialize_rb_construction();
eim_construction.train_reduced_basis();
eim_construction.get_rb_evaluation().write_offline_data_to_files("eim_data");
// Read data from input file and print state
rb_construction.process_parameters_file(rb_parameters);
// attach the EIM theta objects to the RBEvaluation
eim_rb_eval.initialize_eim_theta_objects();
rb_eval.get_rb_theta_expansion().attach_multiple_A_theta(eim_rb_eval.get_eim_theta_objects());
// attach the EIM assembly objects to the RBConstruction
eim_construction.initialize_eim_assembly_objects();
rb_construction.get_rb_assembly_expansion().attach_multiple_A_assembly(eim_construction.get_eim_assembly_objects());
// Print out the state of rb_construction now that the EIM objects have been attached
rb_construction.print_info();
// Need to initialize _after_ EIM greedy so that
// the system knows how many affine terms there are
rb_construction.initialize_rb_construction();
rb_construction.train_reduced_basis();
rb_construction.get_rb_evaluation().write_offline_data_to_files("rb_data");
// Write out the basis functions, if requested
if(store_basis_functions)
{
// Write out the basis functions
eim_construction.get_rb_evaluation().write_out_basis_functions(eim_construction,"eim_data");
rb_construction.get_rb_evaluation().write_out_basis_functions(rb_construction,"rb_data");
}
}
else // Perform the Online stage of the RB method
{
eim_rb_eval.read_offline_data_from_files("eim_data");
// attach the EIM theta objects to rb_eval objects
eim_rb_eval.initialize_eim_theta_objects();
rb_eval.get_rb_theta_expansion().attach_multiple_A_theta(eim_rb_eval.get_eim_theta_objects());
// Read in the offline data for rb_eval
rb_eval.read_offline_data_from_files("rb_data");
// Get the parameters at which we will do a reduced basis solve
Real online_curvature = infile("online_curvature", 0.);
Real online_Bi = infile("online_Bi", 0.);
Real online_kappa = infile("online_kappa", 0.);
RBParameters online_mu;
online_mu.set_value("curvature", online_curvature);
online_mu.set_value("Bi", online_Bi);
online_mu.set_value("kappa", online_kappa);
rb_eval.set_parameters(online_mu);
rb_eval.print_parameters();
rb_eval.rb_solve( rb_eval.get_n_basis_functions() );
// plot the solution, if requested
if(store_basis_functions)
{
// read in the data from files
eim_rb_eval.read_in_basis_functions(eim_construction,"eim_data");
rb_eval.read_in_basis_functions(rb_construction,"rb_data");
eim_construction.load_rb_solution();
rb_construction.load_rb_solution();
transform_mesh_and_plot(equation_systems,online_curvature,"RB_sol.e");
}
}
return 0;
}
void transform_mesh_and_plot(EquationSystems& es, Real curvature, const std::string& filename)
{
// Loop over the mesh nodes and move them!
MeshBase& mesh = es.get_mesh();
MeshBase::node_iterator node_it = mesh.nodes_begin();
const MeshBase::node_iterator node_end = mesh.nodes_end();
for( ; node_it != node_end; node_it++)
{
Node* node = *node_it;
Real x = (*node)(0);
Real z = (*node)(2);
(*node)(0) = -1./curvature + (1./curvature + x)*cos(curvature*z);
(*node)(2) = (1./curvature + x)*sin(curvature*z);
}
#ifdef LIBMESH_HAVE_EXODUS_API
ExodusII_IO(mesh).write_equation_systems(filename, es);
#endif
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 <iostream>
#include <fstream>
#include "itkExtractImageFilter.h"
#include "itkVectorIndexSelectionCastImageFilter.h"
#include "otbExtractROI.h"
#include "otbMultiChannelExtractROI.h"
#include "otbMultiToMonoChannelExtractROI.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otb_boost_string_header.h"
int otbExtractROITestMetaData(int itkNotUsed(argc), char* argv[])
{
typedef float PixelType;
typedef otb::Image<PixelType> ImageType;
typedef otb::ImageFileReader<ImageType> ImageFileReaderType;
typedef otb::ImageFileWriter<ImageType> ImageFileWriterType;
typedef otb::ExtractROI<PixelType, PixelType> ExtractROIType;
ImageFileReaderType::Pointer readerInput = ImageFileReaderType::New();
ImageFileReaderType::Pointer reader00 = ImageFileReaderType::New();
ImageFileReaderType::Pointer reader57 = ImageFileReaderType::New();
ImageFileWriterType::Pointer writer00 = ImageFileWriterType::New();
ImageFileWriterType::Pointer writer57 = ImageFileWriterType::New();
ExtractROIType::Pointer extract00 = ExtractROIType::New();
ExtractROIType::Pointer extract57 = ExtractROIType::New();
// Read input file
readerInput->SetFileName(argv[1]);
readerInput->GenerateOutputInformation();
// Extract left up image
extract00->SetInput(readerInput->GetOutput());
extract00->SetSizeX(50);
extract00->SetSizeY(25);
extract00->SetStartX(0);
extract00->SetStartY(0);
extract00->UpdateOutputInformation();
// Save left up image information
std::ofstream file00;
file00.open(argv[4]);
file00 << static_cast<ImageType::Pointer>(extract00->GetOutput()) << std::endl;
file00.close();
// Extract image with non-zero index
extract57->SetInput(readerInput->GetOutput());
extract57->SetSizeX(50);
extract57->SetSizeY(25);
extract57->SetStartX(5);
extract57->SetStartY(7);
extract57->UpdateOutputInformation();
// Save extract image information
std::ofstream file57;
file57.open(argv[5]);
file57 << static_cast<ImageType::Pointer>(extract57->GetOutput()) << std::endl;
file57.close();
// Write left up image
writer00->SetFileName(argv[2]);
writer00->SetInput(extract00->GetOutput());
// writer00->SetWriteGeomFile(true);
writer00->Update();
// Write image with non zero index
writer57->SetFileName(argv[3]);
writer57->SetInput(extract57->GetOutput());
// writer57->SetWriteGeomFile(true);
writer57->Update();
// Reading image with left up index
reader00->SetFileName(argv[2]);
reader00->GenerateOutputInformation();
if (reader00->GetOutput()->GetProjectionRef() != "" || boost::algorithm::istarts_with(reader00->GetOutput()->GetProjectionRef(), "LOCAL_CS"))
{
std::cout << "The read generated extract from index (0, 0) must NOT contain a ProjectionReference." << std::endl;
std::cout << "Found ProjectionReference: " << reader00->GetOutput()->GetProjectionRef() << std::endl;
return EXIT_FAILURE;
}
if (reader00->GetOutput()->GetGCPCount() == 0)
{
std::cout << "The read generated extract from index (0, 0) must contain a list a GCPs.." << std::endl;
return EXIT_FAILURE;
}
// Reading image with non-zero index
reader57->SetFileName(argv[3]);
reader57->GenerateOutputInformation();
if (reader57->GetOutput()->GetProjectionRef() != "" || boost::algorithm::istarts_with(reader57->GetOutput()->GetProjectionRef(), "LOCAL_CS"))
{
std::cout << "The read generated extract from index (x, y) must NOT contain a ProjectionReference." << std::endl;
std::cout << "Found ProjectionReference: " << reader57->GetOutput()->GetProjectionRef() << std::endl;
return EXIT_FAILURE;
}
if (reader57->GetOutput()->GetGCPCount() != 0)
{
std::cout << "The read generated extract from index (x, y) must NOT contain a list a GCPs.." << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>TEST: update test logic<commit_after>/*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 <iostream>
#include <fstream>
#include "itkExtractImageFilter.h"
#include "itkVectorIndexSelectionCastImageFilter.h"
#include "otbExtractROI.h"
#include "otbMultiChannelExtractROI.h"
#include "otbMultiToMonoChannelExtractROI.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
int otbExtractROITestMetaData(int itkNotUsed(argc), char* argv[])
{
typedef float PixelType;
typedef otb::Image<PixelType> ImageType;
typedef otb::ImageFileReader<ImageType> ImageFileReaderType;
typedef otb::ImageFileWriter<ImageType> ImageFileWriterType;
typedef otb::ExtractROI<PixelType, PixelType> ExtractROIType;
ImageFileReaderType::Pointer readerInput = ImageFileReaderType::New();
ImageFileReaderType::Pointer reader00 = ImageFileReaderType::New();
ImageFileReaderType::Pointer reader57 = ImageFileReaderType::New();
ImageFileWriterType::Pointer writer00 = ImageFileWriterType::New();
ImageFileWriterType::Pointer writer57 = ImageFileWriterType::New();
ExtractROIType::Pointer extract00 = ExtractROIType::New();
ExtractROIType::Pointer extract57 = ExtractROIType::New();
// Read input file
readerInput->SetFileName(argv[1]);
readerInput->GenerateOutputInformation();
// Extract left up image
extract00->SetInput(readerInput->GetOutput());
extract00->SetSizeX(50);
extract00->SetSizeY(25);
extract00->SetStartX(0);
extract00->SetStartY(0);
extract00->UpdateOutputInformation();
// Save left up image information
std::ofstream file00;
file00.open(argv[4]);
file00 << static_cast<ImageType::Pointer>(extract00->GetOutput()) << std::endl;
file00.close();
// Extract image with non-zero index
extract57->SetInput(readerInput->GetOutput());
extract57->SetSizeX(50);
extract57->SetSizeY(25);
extract57->SetStartX(5);
extract57->SetStartY(7);
extract57->UpdateOutputInformation();
// Save extract image information
std::ofstream file57;
file57.open(argv[5]);
file57 << static_cast<ImageType::Pointer>(extract57->GetOutput()) << std::endl;
file57.close();
// Write left up image
writer00->SetFileName(argv[2]);
writer00->SetInput(extract00->GetOutput());
// writer00->SetWriteGeomFile(true);
writer00->Update();
// Write image with non zero index
writer57->SetFileName(argv[3]);
writer57->SetInput(extract57->GetOutput());
// writer57->SetWriteGeomFile(true);
writer57->Update();
// Reading image with left up index
reader00->SetFileName(argv[2]);
reader00->GenerateOutputInformation();
// The input image should have a sensor model and GCP, but the output images
// should only have the sensor model (priority over GCP). This behaviour
// must be consistent regardless of the ROI.
if (reader00->GetOutput()->GetProjectionRef().size())
{
std::cout << "The read generated extract from index (0, 0) must NOT contain a ProjectionReference." << std::endl;
std::cout << "Found ProjectionReference: " << reader00->GetOutput()->GetProjectionRef() << std::endl;
return EXIT_FAILURE;
}
if (reader00->GetOutput()->GetGCPCount())
{
std::cout << "The read generated extract from index (0, 0) must NOT contain a list a GCPs.." << std::endl;
return EXIT_FAILURE;
}
// Reading image with non-zero index
reader57->SetFileName(argv[3]);
reader57->GenerateOutputInformation();
if (reader57->GetOutput()->GetProjectionRef().size())
{
std::cout << "The read generated extract from index (x, y) must NOT contain a ProjectionReference." << std::endl;
std::cout << "Found ProjectionReference: " << reader57->GetOutput()->GetProjectionRef() << std::endl;
return EXIT_FAILURE;
}
if (reader57->GetOutput()->GetGCPCount())
{
std::cout << "The read generated extract from index (x, y) must NOT contain a list a GCPs.." << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// MGenTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "MGenTest.h"
#include "../MGen/GLibrary/GLib.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// The one and only application object
CWinApp theApp;
using namespace std;
CString current_dir, full_url, server, url;
DWORD service;
WORD port;
ofstream logfile;
int ci = 0;
int nRetCode = 0;
/*
string url_encode(const string &value) {
ostringstream escaped;
escaped.fill('0');
escaped << hex;
for (string::const_iterator i = value.begin(), n = value.end(); i != n; ++i) {
string::value_type c = (*i);
// Keep alphanumeric and other accepted characters intact
if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
escaped << c;
continue;
}
// Any other characters are percent-encoded
escaped << uppercase;
escaped << '%' << setw(2) << int((unsigned char)c);
escaped << nouppercase;
}
return escaped.str();
}
void HTTPPost(CString server, WORD port, CString url, CString data) {
cout << "HTTPPost to server " << server << " port " << port << " url " << url << " : " << data << "\n";
CString strHeaders = "Content-Type: application/x-www-form-urlencoded";
try {
char szBuf [2550];
DWORD dwRet;
CInternetSession session;
CHttpConnection* pConnection = session.GetHttpConnection(server, port);
CHttpFile* pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST, url);
pFile->AddRequestHeaders(strHeaders);
data = url_encode(data.GetBuffer()).c_str();
cout << "HTTPPost to server " << server << " port " << port << " url " << url << " : " << data << "\n";
pFile->SendRequestEx(data.GetLength());
pFile->Write(data, data.GetLength());
//BOOL result = pFile->SendRequest(strHeaders, (LPVOID)(LPCTSTR)data, data.GetLength());
pFile->QueryInfoStatusCode(dwRet);
cout << "HTTP return code: " << dwRet << "\n";
if (dwRet == HTTP_STATUS_OK) {
UINT nRead = pFile->Read(szBuf, 2550);
if (nRead > 0) {
cout << "HTTP result: " << szBuf << "\n";
}
}
}
catch (CInternetException *e) {
//e->ReportError();
TCHAR szCause[2550];
e->GetErrorMessage(szCause, 2550);
cout << "Error when sending HTTP request: " << szCause << "\n";
e->Delete();
}
}
*/
void Run(CString fname, CString par, int delay) {
SHELLEXECUTEINFO sei = { 0 };
sei.cbSize = sizeof(SHELLEXECUTEINFO);
sei.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI;
sei.hwnd = NULL;
sei.lpVerb = NULL;
sei.lpFile = fname;
sei.lpParameters = par;
sei.lpDirectory = NULL;
sei.nShow = SW_SHOWNORMAL;
sei.hInstApp = NULL;
ShellExecuteEx(&sei);
WaitForSingleObject(sei.hProcess, delay);
}
void Log(CString st, int level = 0) {
cout << st;
logfile << st;
if (ci && level > 0) {
CString cat;
if (level == 1) cat = "Information";
if (level == 2) cat = "Warning";
if (level == 3) cat = "Error";
CString par = "AddMessage \"" + st + "\" -Category " + cat;
Run("appveyor", par, 1000);
}
}
CString file(CString fname) {
CString st, st2;
ifstream fs;
// Check file exists
if (!CGLib::fileExists(fname)) {
cout << "Not found file " << fname << "\n";
}
fs.open(fname);
char pch[2550];
while (fs.good()) {
// Get line
fs.getline(pch, 2550);
st2 = pch;
if (st2 != "") {
st += "- " + st2 + "\n";
}
}
fs.close();
return st;
}
void ClearBuffer() {
fstream fs;
fs.open("autotest\\buffer.log", ios::out);
fs.close();
}
void PublishTest(CString tname, int result, int tpassed) {
CString st;
CString st2;
st2.Format("%s: code %d in %d ms\n", tname, result, tpassed);
if (result) {
nRetCode = 2;
Log(st2, 3);
}
else {
Log(st2, 1);
}
// Show errors
CString errors = file("autotest/buffer.log");
cout << errors;
if (ci) {
CString cat = "Passed";
if (result) cat = "Failed";
st.Format("UpdateTest \"%s\" -Framework MSTest -FileName MGen.exe -Duration %d -Outcome %s -ErrorMessage \"%d\"", tname, tpassed, cat, result);
Run("appveyor", st, 1000);
// Send errors separately in case of command line overflow
st.Format("UpdateTest \"%s\" -Framework MSTest -FileName MGen.exe -Duration %d -Outcome %s -ErrorMessage \"%d\" -ErrorStackTrace \"%s\"", tname, tpassed, cat, result, errors);
Run("appveyor", st, 1000);
}
/*
// Send HTTP
st.Format("{"
" \"testName\": \"%s\","
" \"testFramework\" : \"MSTest\","
" \"fileName\" : \"MGen.exe\","
" \"outcome\" : \"%s\","
" \"durationMilliseconds\" : \"%d\","
" \"ErrorMessage\" : \"%s\","
" \"ErrorStackTrace\" : \"\","
" \"StdOut\" : \"\","
" \"StdErr\" : \"\""
" }", tname, cat, tpassed, errors);
if (ci) {
HTTPPost(server, port, url + "api/tests", st);
}
*/
}
void LoadConfig() {
milliseconds time_start, time_stop;
CString fname = "autotest\\test.txt";
// Check file exists
if (!CGLib::fileExists(fname)) {
cout << "Not found file " << fname << "\n";
}
ifstream fs;
fs.open(fname);
LPDWORD ecode = new DWORD;
CString st, st2;
char pch[2550];
int pos = 0;
int passed;
while (fs.good()) {
fs.getline(pch, 2550);
st = pch;
pos = st.Find("#");
if (pos != -1) st = st.Left(pos);
st.Trim();
if (st.GetLength()) {
ClearBuffer();
if (ci) Run("appveyor", "AddTest \"" + st + "\" -Framework MSTest -FileName MGen.exe -Outcome Running", 1000);
Log("Starting test config: " + st + "\n");
//::ShellExecute(GetDesktopWindow(), "open", "MGen", "-test " + st, NULL, SW_SHOWNORMAL);
st2 = "-test " + st;
SHELLEXECUTEINFO sei = { 0 };
sei.cbSize = sizeof(SHELLEXECUTEINFO);
sei.fMask = SEE_MASK_NOCLOSEPROCESS;
sei.hwnd = NULL;
sei.lpVerb = NULL;
sei.lpFile = "MGen.exe";
sei.lpParameters = st2;
sei.lpDirectory = NULL;
sei.nShow = SW_SHOW;
sei.hInstApp = NULL;
time_start = duration_cast< milliseconds >(system_clock::now().time_since_epoch());
ShellExecuteEx(&sei);
if (WaitForSingleObject(sei.hProcess, 60000) == WAIT_TIMEOUT) {
Log(st + ": Timeout waiting for process\n", 3);
exit(1);
}
time_stop = duration_cast< milliseconds >(system_clock::now().time_since_epoch());
passed = static_cast<int>((time_stop - time_start).count());
GetExitCodeProcess(sei.hProcess, ecode);
PublishTest(st, *ecode, passed);
}
}
delete ecode;
fs.close();
}
int test() {
//full_url = "http://my.test.server:882/some/path/script.php?parameters=123";
//AfxParseURL(full_url, service, server, url, port);
//ci = 1;
if (getenv("APPVEYOR_PROJECT_NAME") != NULL) {
ci = 1;
//if (getenv("APPVEYOR_API_URL") != NULL) full_url = getenv("APPVEYOR_API_URL");
//AfxParseURL(full_url, service, server, url, port);
}
logfile.open("autotest\\test.log", ios_base::app);
TCHAR buffer[MAX_PATH];
GetCurrentDirectory(MAX_PATH, buffer);
current_dir = string(buffer).c_str();
Log("Current dir: " + current_dir + "\n");
LoadConfig();
logfile.close();
// Do not pause if continuous integration
if (!ci) {
cout << "Press any key to continue... ";
_getch();
}
return 0;
}
int main()
{
HMODULE hModule = ::GetModuleHandle(nullptr);
if (hModule != nullptr)
{
// initialize MFC and print and error on failure
if (!AfxWinInit(hModule, nullptr, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
wprintf(L"Fatal Error: MFC initialization failed\n");
nRetCode = 1;
}
else
{
test();
}
}
else
{
// TODO: change error code to suit your needs
wprintf(L"Fatal Error: GetModuleHandle failed\n");
nRetCode = 1;
}
return nRetCode;
}
<commit_msg>MgenTest: Rewrite for full clarity (closed #760)<commit_after>// MGenTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "MGenTest.h"
#include "../MGen/GLibrary/GLib.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// The one and only application object
CWinApp theApp;
using namespace std;
CString current_dir;
ofstream logfile;
int ci = 0;
int nRetCode = 0;
void Run(CString fname, CString par, int delay) {
SHELLEXECUTEINFO sei = { 0 };
sei.cbSize = sizeof(SHELLEXECUTEINFO);
sei.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI;
sei.hwnd = NULL;
sei.lpVerb = NULL;
sei.lpFile = fname;
sei.lpParameters = par;
sei.lpDirectory = NULL;
sei.nShow = SW_SHOWNORMAL;
sei.hInstApp = NULL;
ShellExecuteEx(&sei);
WaitForSingleObject(sei.hProcess, delay);
}
void Log(CString st, int level = 0) {
cout << st;
logfile << st;
if (ci && level > 0) {
CString cat;
if (level == 1) cat = "Information";
if (level == 2) cat = "Warning";
if (level == 3) cat = "Error";
CString par = "AddMessage \"" + st + "\" -Category " + cat;
Run("appveyor", par, 1000);
}
}
CString file(CString fname) {
CString st, st2;
ifstream fs;
// Check file exists
if (!CGLib::fileExists(fname)) {
cout << "Not found file " << fname << "\n";
}
fs.open(fname);
char pch[2550];
while (fs.good()) {
// Get line
fs.getline(pch, 2550);
st2 = pch;
if (st2 != "") {
st += "- " + st2 + "\n";
}
}
fs.close();
return st;
}
void ClearBuffer() {
fstream fs;
fs.open("autotest\\buffer.log", ios::out);
fs.close();
}
void PublishTest(CString tname, int result, int tpassed) {
CString st;
CString st2;
st2.Format("%s: code %d in %d ms\n", tname, result, tpassed);
if (result) {
nRetCode = 2;
Log(st2, 3);
}
else {
Log(st2, 1);
}
// Show errors
CString errors = file("autotest/buffer.log");
cout << errors;
if (ci) {
CString cat = "Passed";
if (result) cat = "Failed";
st.Format("UpdateTest \"%s\" -Framework MSTest -FileName MGen.exe -Duration %d -Outcome %s -ErrorMessage \"%d\"", tname, tpassed, cat, result);
Run("appveyor", st, 1000);
// Send errors separately in case of command line overflow
st.Format("UpdateTest \"%s\" -Framework MSTest -FileName MGen.exe -Duration %d -Outcome %s -ErrorMessage \"%d\" -ErrorStackTrace \"%s\"", tname, tpassed, cat, result, errors);
Run("appveyor", st, 1000);
}
}
void LoadConfig() {
milliseconds time_start, time_stop;
CString fname = "autotest\\test.txt";
// Check file exists
if (!CGLib::fileExists(fname)) {
cout << "Not found file " << fname << "\n";
}
ifstream fs;
fs.open(fname);
LPDWORD ecode = new DWORD;
CString st, st2;
char pch[2550];
int pos = 0;
int passed;
while (fs.good()) {
fs.getline(pch, 2550);
st = pch;
pos = st.Find("#");
if (pos != -1) st = st.Left(pos);
st.Trim();
if (st.GetLength()) {
ClearBuffer();
if (ci) Run("appveyor", "AddTest \"" + st + "\" -Framework MSTest -FileName MGen.exe -Outcome Running", 1000);
Log("Starting test config: " + st + "\n");
st2 = "-test " + st;
SHELLEXECUTEINFO sei = { 0 };
sei.cbSize = sizeof(SHELLEXECUTEINFO);
sei.fMask = SEE_MASK_NOCLOSEPROCESS;
sei.hwnd = NULL;
sei.lpVerb = NULL;
sei.lpFile = "MGen.exe";
sei.lpParameters = st2;
sei.lpDirectory = NULL;
sei.nShow = SW_SHOW;
sei.hInstApp = NULL;
time_start = duration_cast< milliseconds >(system_clock::now().time_since_epoch());
ShellExecuteEx(&sei);
if (WaitForSingleObject(sei.hProcess, 60000) == WAIT_TIMEOUT) {
Log(st + ": Timeout waiting for process\n", 3);
exit(1);
}
time_stop = duration_cast< milliseconds >(system_clock::now().time_since_epoch());
passed = static_cast<int>((time_stop - time_start).count());
GetExitCodeProcess(sei.hProcess, ecode);
PublishTest(st, *ecode, passed);
}
}
delete ecode;
fs.close();
}
int test() {
if (getenv("APPVEYOR_PROJECT_NAME") != NULL) {
ci = 1;
}
logfile.open("autotest\\test.log", ios_base::app);
TCHAR buffer[MAX_PATH];
GetCurrentDirectory(MAX_PATH, buffer);
current_dir = string(buffer).c_str();
Log("Current dir: " + current_dir + "\n");
LoadConfig();
logfile.close();
// Do not pause if continuous integration
if (!ci) {
cout << "Press any key to continue... ";
_getch();
}
return 0;
}
int main()
{
HMODULE hModule = ::GetModuleHandle(nullptr);
if (hModule != nullptr)
{
// initialize MFC and print and error on failure
if (!AfxWinInit(hModule, nullptr, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
wprintf(L"Fatal Error: MFC initialization failed\n");
nRetCode = 1;
}
else
{
test();
}
}
else
{
// TODO: change error code to suit your needs
wprintf(L"Fatal Error: GetModuleHandle failed\n");
nRetCode = 1;
}
return nRetCode;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2013 The Communi Project
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "appwindow.h"
#include <QApplication>
#include <QNetworkProxy>
#include <QIcon>
#include <QUrl>
#include <Irc>
static void setApplicationProxy(QUrl url)
{
if (!url.isEmpty()) {
if (url.port() == -1)
url.setPort(8080);
QNetworkProxy proxy(QNetworkProxy::HttpProxy, url.host(), url.port(), url.userName(), url.password());
QNetworkProxy::setApplicationProxy(proxy);
}
}
int main(int argc, char* argv[])
{
#ifdef Q_OS_MAC
// QTBUG-32789 - GUI widgets use the wrong font on OS X Mavericks
QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande");
#endif
QApplication app(argc, argv);
app.setApplicationName("CommuniNG");
app.setOrganizationName("Communi");
app.setApplicationVersion(Irc::version());
app.setOrganizationDomain("communi.github.com");
app.setProperty("description", AppWindow::tr("%1 %2 - http://%3").arg(app.applicationName())
.arg(app.applicationVersion())
.arg(app.organizationDomain()));
AppWindow window;
QStringList args = app.arguments();
QUrl proxy;
int index = args.indexOf("-proxy");
if (index != -1)
proxy = QUrl(args.value(index + 1));
else
proxy = QUrl(qgetenv("http_proxy"));
setApplicationProxy(proxy);
window.show();
return app.exec();
}
<commit_msg>Add -reset cmd line argument<commit_after>/*
* Copyright (C) 2008-2013 The Communi Project
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "appwindow.h"
#include <QApplication>
#include <QNetworkProxy>
#include <QSettings>
#include <QIcon>
#include <QUrl>
#include <Irc>
static void setApplicationProxy(QUrl url)
{
if (!url.isEmpty()) {
if (url.port() == -1)
url.setPort(8080);
QNetworkProxy proxy(QNetworkProxy::HttpProxy, url.host(), url.port(), url.userName(), url.password());
QNetworkProxy::setApplicationProxy(proxy);
}
}
int main(int argc, char* argv[])
{
#ifdef Q_OS_MAC
// QTBUG-32789 - GUI widgets use the wrong font on OS X Mavericks
QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande");
#endif
QApplication app(argc, argv);
app.setApplicationName("CommuniNG");
app.setOrganizationName("Communi");
app.setApplicationVersion(Irc::version());
app.setOrganizationDomain("communi.github.com");
app.setProperty("description", AppWindow::tr("%1 %2 - http://%3").arg(app.applicationName())
.arg(app.applicationVersion())
.arg(app.organizationDomain()));
QStringList args = app.arguments();
if (args.contains("-reset"))
QSettings().clear();
QUrl proxy;
int index = args.indexOf("-proxy");
if (index != -1)
proxy = QUrl(args.value(index + 1));
else
proxy = QUrl(qgetenv("http_proxy"));
setApplicationProxy(proxy);
AppWindow window;
window.show();
return app.exec();
}
<|endoftext|> |
<commit_before>/* -*- mode: c++; c-basic-offset:4 -*-
uiserver/encryptcommand.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2007 Klarälvdalens Datakonsult AB
Kleopatra is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Kleopatra 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
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "encryptcommand.h"
#include "keyselectionjob.h"
#include "kleo-assuan.h"
#include <kleo/encryptjob.h>
#include <gpgme++/encryptionresult.h>
#include <gpgme++/error.h>
#include <KLocale>
#include <QMap>
#include <QStringList>
using namespace Kleo;
class EncryptCommand::Private
: public AssuanCommandPrivateBaseMixin<EncryptCommand::Private, EncryptCommand>
{
Q_OBJECT
public:
Private( EncryptCommand * qq )
:AssuanCommandPrivateBaseMixin<EncryptCommand::Private, EncryptCommand>()
, m_deleteInputFiles( false ), m_activeEncryptJobs( 0 ), m_statusSent( 0 ), q( qq )
{}
virtual ~Private() {}
void checkInputs();
void startKeySelection();
void startEncryptJobs( const std::vector<GpgME::Key>& keys );
struct Input {
QIODevice* input;
QString inputFileName;
int id;
};
struct Result {
GpgME::EncryptionResult result;
QByteArray data;
unsigned int id;
unsigned int error;
QString errorString;
};
bool m_deleteInputFiles;
std::vector<Input> m_inputs;
int m_activeEncryptJobs;
QMap<const EncryptJob*, uint> m_jobs;
QMap<uint, Result> m_results;
int m_statusSent;
public Q_SLOTS:
void slotKeySelectionError( const GpgME::Error&, const GpgME::KeyListResult& );
void slotKeySelectionResult( const std::vector<GpgME::Key>& );
void slotEncryptionResult( const GpgME::EncryptionResult& result, const QByteArray& cipherText );
private:
bool trySendingStatus( const QString & str );
public:
EncryptCommand *q;
};
void EncryptCommand::Private::checkInputs()
{
const int numInputs = q->numBulkInputDevices( "INPUT" );
const int numOutputs = q->numBulkOutputDevices( "OUTPUT" );
const int numMessages = q->numBulkInputDevices( "MESSAGE" );
//TODO use better error code if possible
if ( numMessages != 0 )
throw assuan_exception(makeError( GPG_ERR_ASS_NO_INPUT ), i18n( "Only --input and --output can be provided to the encrypt command, no --message") );
// for each input, we need an output
//TODO use better error code if possible
if ( numInputs != numOutputs )
throw assuan_exception( makeError( GPG_ERR_ASS_NO_INPUT ), i18n( "For each --input there needs to be an --output" ) );
for ( int i = 0; i < numInputs; ++i ) {
Input input;
input.input = q->bulkInputDevice( "INPUT", i );
assert( input.input );
input.inputFileName = q->bulkInputDeviceFileName( "INPUT", i );
input.id = i;
m_inputs.push_back( input );
}
m_deleteInputFiles = q->hasOption( "--delete-input-files" );
}
void EncryptCommand::Private::startKeySelection()
{
KeySelectionJob* job = new KeySelectionJob( this );
job->setSecretKeysOnly( false );
job->setPatterns( QStringList() ); // FIXME
connect( job, SIGNAL( error( GpgME::Error, GpgME::KeyListResult ) ),
this, SLOT( slotKeySelectionError( GpgME::Error, GpgME::KeyListResult ) ) );
connect( job, SIGNAL( result( std::vector<GpgME::Key> ) ),
this, SLOT( slotKeySelectionResult( std::vector<GpgME::Key> ) ) );
job->start();
}
void EncryptCommand::Private::startEncryptJobs( const std::vector<GpgME::Key>& keys )
{
assert( m_activeEncryptJobs == 0 );
if ( keys.empty() ) {
q->done();
return;
}
const CryptoBackend::Protocol* const backend = CryptoBackendFactory::instance()->protocol( keys.front().protocolAsString() );
assert( backend );
Q_FOREACH( const Input i, m_inputs ) {
EncryptJob* job = backend->encryptJob();
connect( job, SIGNAL( result( GpgME::EncryptionResult, QByteArray ) ),
this, SLOT( slotEncryptionResult( GpgME::EncryptionResult, QByteArray ) ) );
if ( const GpgME::Error error = job->start( keys, i.input->readAll(), /*always trust*/true ) ) { //TODO how to handle trust arg? Add an option?
q->done( error );
return;
}
m_jobs.insert( job, i.id );
++m_activeEncryptJobs;
}
}
void EncryptCommand::Private::slotEncryptionResult( const GpgME::EncryptionResult& result, const QByteArray& cipherText )
{
assert( m_activeEncryptJobs > 0 );
const EncryptJob * const job = qobject_cast<EncryptJob*>( sender() );
assert( job );
assert( m_jobs.contains( job ) );
const unsigned int id = m_jobs[job];
{
Result res;
res.result = result;
res.data = cipherText;
res.id = id;
m_results.insert( id, res );
}
// send status for all results received so far, but in order of id
while ( m_results.contains( m_statusSent ) ) {
EncryptCommand::Private::Result result = m_results[m_statusSent];
QString resultString;
try {
const GpgME::EncryptionResult encres = result.result;
assert( !encres.isNull() );
const GpgME::Error encryptError = encres.error();
if ( encryptError )
throw assuan_exception( encryptError, i18n( "Encryption failed: " ) );
// FIXME adjust for smime?
writeToOutputDeviceOrAskForFileName( result.id, result.data, QString() );
resultString = "OK - Super Duper Weenie\n";
} catch ( const assuan_exception& e ) {
result.error = e.error_code();
result.errorString = e.what();
m_results[result.id] = result;
resultString = "ERR " + result.errorString;
// FIXME ask to continue or cancel
}
if ( !trySendingStatus( resultString ) )
return; // trySendingStatus calls done() if it fails
++m_statusSent;
}
--m_activeEncryptJobs;
if ( m_activeEncryptJobs == 0 )
q->done();
}
bool EncryptCommand::Private::trySendingStatus( const QString & str )
{
if ( const int err = q->sendStatus( "ENCRYPT", str ) ) {
const QString errorString = i18n("Problem writing out the cipher text.");
q->done( err, errorString );
return false;
}
return true;
}
void EncryptCommand::Private::slotKeySelectionResult( const std::vector<GpgME::Key>& keys )
{
startEncryptJobs( keys );
}
void EncryptCommand::Private::slotKeySelectionError( const GpgME::Error& error, const GpgME::KeyListResult& )
{
assert( error );
if ( error == q->makeError( GPG_ERR_CANCELED ) )
q->done( error, i18n( "User canceled key selection" ) );
else
q->done( error, i18n( "Error while listing and selecting keys" ) );
}
EncryptCommand::EncryptCommand()
:d( new Private( this ) )
{
}
EncryptCommand::~EncryptCommand()
{
}
int EncryptCommand::doStart()
{
try {
d->checkInputs();
d->startKeySelection();
} catch ( const assuan_exception& e ) {
done( e.error_code(), e.what());
return e.error_code();
}
return 0;
}
void EncryptCommand::doCanceled()
{
}
#include "encryptcommand.moc"
<commit_msg>Use --silent, enable armor and text mode, use recipients, treat cancel correctly.<commit_after>/* -*- mode: c++; c-basic-offset:4 -*-
uiserver/encryptcommand.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2007 Klarälvdalens Datakonsult AB
Kleopatra is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
Kleopatra 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
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include "encryptcommand.h"
#include "keyselectionjob.h"
#include "kleo-assuan.h"
#include <kleo/encryptjob.h>
#include <gpgme++/encryptionresult.h>
#include <gpgme++/error.h>
#include <KLocale>
#include <QMap>
#include <QStringList>
using namespace Kleo;
class EncryptCommand::Private
: public AssuanCommandPrivateBaseMixin<EncryptCommand::Private, EncryptCommand>
{
Q_OBJECT
public:
Private( EncryptCommand * qq )
:AssuanCommandPrivateBaseMixin<EncryptCommand::Private, EncryptCommand>()
, m_deleteInputFiles( false ), m_activeEncryptJobs( 0 ), m_statusSent( 0 ), q( qq )
{}
virtual ~Private() {}
void checkInputs();
void startKeySelection();
void startEncryptJobs( const std::vector<GpgME::Key>& keys );
struct Input {
QIODevice* input;
QString inputFileName;
int id;
};
struct Result {
GpgME::EncryptionResult result;
QByteArray data;
unsigned int id;
unsigned int error;
QString errorString;
};
bool m_deleteInputFiles;
std::vector<Input> m_inputs;
int m_activeEncryptJobs;
QMap<const EncryptJob*, uint> m_jobs;
QMap<uint, Result> m_results;
int m_statusSent;
public Q_SLOTS:
void slotKeySelectionError( const GpgME::Error&, const GpgME::KeyListResult& );
void slotKeySelectionResult( const std::vector<GpgME::Key>& );
void slotEncryptionResult( const GpgME::EncryptionResult& result, const QByteArray& cipherText );
private:
bool trySendingStatus( const QString & str );
public:
EncryptCommand *q;
};
void EncryptCommand::Private::checkInputs()
{
const int numInputs = q->numBulkInputDevices( "INPUT" );
const int numOutputs = q->numBulkOutputDevices( "OUTPUT" );
const int numMessages = q->numBulkInputDevices( "MESSAGE" );
//TODO use better error code if possible
if ( numMessages != 0 )
throw assuan_exception( makeError( GPG_ERR_ASS_NO_INPUT ), i18n( "Only INPUT and OUTPUT can be provided to the ENCRYPT command, no MESSAGE") );
// for each input, we need an output
//TODO use better error code if possible
if ( numInputs != numOutputs )
throw assuan_exception( makeError( GPG_ERR_ASS_NO_INPUT ), i18n( "For each INPUT there needs to be an OUTPUT" ) );
for ( int i = 0; i < numInputs; ++i ) {
Input input;
input.input = q->bulkInputDevice( "INPUT", i );
assert( input.input );
input.inputFileName = q->bulkInputDeviceFileName( "INPUT", i );
input.id = i;
m_inputs.push_back( input );
}
m_deleteInputFiles = q->hasOption( "--delete-input-files" );
}
void EncryptCommand::Private::startKeySelection()
{
KeySelectionJob* job = new KeySelectionJob( this );
job->setSecretKeysOnly( false );
job->setPatterns( q->recipients() );
job->setSilent( q->hasOption( "silent" ) );
connect( job, SIGNAL( error( GpgME::Error, GpgME::KeyListResult ) ),
this, SLOT( slotKeySelectionError( GpgME::Error, GpgME::KeyListResult ) ) );
connect( job, SIGNAL( result( std::vector<GpgME::Key> ) ),
this, SLOT( slotKeySelectionResult( std::vector<GpgME::Key> ) ) );
job->start();
}
void EncryptCommand::Private::startEncryptJobs( const std::vector<GpgME::Key>& keys )
{
assert( m_activeEncryptJobs == 0 );
if ( keys.empty() ) {
q->done();
return;
}
const CryptoBackend::Protocol* const backend = CryptoBackendFactory::instance()->protocol( keys.front().protocolAsString() );
assert( backend );
Q_FOREACH( const Input i, m_inputs ) {
EncryptJob* job = backend->encryptJob( true, true );
connect( job, SIGNAL( result( GpgME::EncryptionResult, QByteArray ) ),
this, SLOT( slotEncryptionResult( GpgME::EncryptionResult, QByteArray ) ) );
if ( const GpgME::Error error = job->start( keys, i.input->readAll(), /*always trust*/true ) ) { //TODO how to handle trust arg? Add an option?
q->done( error );
return;
}
m_jobs.insert( job, i.id );
++m_activeEncryptJobs;
}
}
void EncryptCommand::Private::slotEncryptionResult( const GpgME::EncryptionResult& result, const QByteArray& cipherText )
{
assert( m_activeEncryptJobs > 0 );
const EncryptJob * const job = qobject_cast<EncryptJob*>( sender() );
assert( job );
assert( m_jobs.contains( job ) );
const unsigned int id = m_jobs[job];
{
Result res;
res.result = result;
res.data = cipherText;
res.id = id;
m_results.insert( id, res );
}
// send status for all results received so far, but in order of id
while ( m_results.contains( m_statusSent ) ) {
EncryptCommand::Private::Result result = m_results[m_statusSent];
QString resultString;
try {
const GpgME::EncryptionResult encres = result.result;
assert( !encres.isNull() );
const GpgME::Error encryptError = encres.error();
if ( encryptError )
throw assuan_exception( encryptError, i18n( "Encryption failed: " ) );
// FIXME adjust for smime?
writeToOutputDeviceOrAskForFileName( result.id, result.data, QString() );
resultString = "OK - Super Duper Weenie\n";
} catch ( const assuan_exception& e ) {
result.error = e.error_code();
result.errorString = e.what();
m_results[result.id] = result;
resultString = "ERR " + result.errorString;
// FIXME ask to continue or cancel
}
if ( !trySendingStatus( resultString ) )
return; // trySendingStatus calls done() if it fails
++m_statusSent;
}
--m_activeEncryptJobs;
if ( m_activeEncryptJobs == 0 )
q->done();
}
bool EncryptCommand::Private::trySendingStatus( const QString & str )
{
if ( const int err = q->sendStatus( "ENCRYPT", str ) ) {
const QString errorString = i18n("Problem writing out the cipher text.");
q->done( err, errorString );
return false;
}
return true;
}
void EncryptCommand::Private::slotKeySelectionResult( const std::vector<GpgME::Key>& keys )
{
startEncryptJobs( keys );
}
void EncryptCommand::Private::slotKeySelectionError( const GpgME::Error& error, const GpgME::KeyListResult& )
{
assert( error || error.isCanceled() );
if ( error.isCanceled() )
q->done( error, i18n( "User canceled key selection" ) );
else
q->done( error, i18n( "Error while listing and selecting keys" ) );
}
EncryptCommand::EncryptCommand()
:d( new Private( this ) )
{
}
EncryptCommand::~EncryptCommand()
{
}
int EncryptCommand::doStart()
{
try {
d->checkInputs();
d->startKeySelection();
} catch ( const assuan_exception& e ) {
done( e.error_code(), e.what());
return e.error_code();
}
return 0;
}
void EncryptCommand::doCanceled()
{
}
#include "encryptcommand.moc"
<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- *
* OpenSim: toyLeg_example.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2012 Stanford University and the Authors *
* Author(s): Matt S. DeMers *
* *
* 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. *
* -------------------------------------------------------------------------- */
/*
* Below is an example of an OpenSim application that provides its own
* main() routine. This application acts as an example for utilizing the
* ControllabeSpring actuator.
*/
// Author: Matt DeMers
//==============================================================================
//==============================================================================
#include "PistonActuator.h"
#include "ControllableSpring.h"
#include <OpenSim/OpenSim.h>
using namespace OpenSim;
using namespace SimTK;
//______________________________________________________________________________
/**
* Run a simulation of block sliding with contact on by two muscles sliding with contact
*/
int main()
{
try {
// Create a new OpenSim model
Model osimModel;
osimModel.setName("osimModel");
double Pi = SimTK::Pi;
// Get the ground body
OpenSim::Body& ground = osimModel.getGroundBody();
ground.addDisplayGeometry("ground.vtp");
// create linkage body
double linkageMass = 0.001, linkageLength = 0.5;
Vec3 linkageMassCenter(0,-linkageLength/2,0);
Inertia linkageInertia = Inertia::cylinderAlongY(0.0, 0.5);
OpenSim::Body *linkage1 = new OpenSim::Body("linkage1", linkageMass, linkageMassCenter, linkageMass*linkageInertia);
// Graphical representation
linkage1->addDisplayGeometry("linkage1.vtp");
// Creat a second linkage body
OpenSim::Body *linkage2 = new OpenSim::Body("linkage2", linkageMass, linkageMassCenter, linkageMass*linkageInertia);
linkage2->addDisplayGeometry("linkage1.vtp");
// Creat a block to be the pelvis
double blockMass = 20.0, blockSideLength = 0.2;
Vec3 blockMassCenter(0);
Inertia blockInertia = blockMass*Inertia::brick(blockSideLength, blockSideLength, blockSideLength);
OpenSim::Body *block = new OpenSim::Body("block", blockMass, blockMassCenter, blockInertia);
block->addDisplayGeometry("big_block_centered.vtp");
// Create 1 degree-of-freedom pin joints between the bodies to creat a kinematic chain from ground through the block
Vec3 orientationInGround(0), locationInGround(0), locationInParent(0.0, 0.5, 0.0), orientationInChild(0), locationInChild(0);
PinJoint *ankle = new PinJoint("ankle", ground, locationInGround, orientationInGround, *linkage1,
locationInChild, orientationInChild);
PinJoint *knee = new PinJoint("knee", *linkage1, locationInParent, orientationInChild, *linkage2,
locationInChild, orientationInChild);
PinJoint *hip = new PinJoint("hip", *linkage2, locationInParent, orientationInChild, *block,
locationInChild, orientationInChild);
double range[2] = {-SimTK::Pi*2, SimTK::Pi*2};
CoordinateSet& ankleCoordinateSet = ankle->upd_CoordinateSet();
ankleCoordinateSet[0].setName("q1");
ankleCoordinateSet[0].setRange(range);
CoordinateSet& kneeCoordinateSet = knee->upd_CoordinateSet();
kneeCoordinateSet[0].setName("q2");
kneeCoordinateSet[0].setRange(range);
CoordinateSet& hipCoordinateSet = hip->upd_CoordinateSet();
hipCoordinateSet[0].setName("q3");
hipCoordinateSet[0].setRange(range);
// Add the bodies to the model
osimModel.addBody(linkage1);
osimModel.addBody(linkage2);
osimModel.addBody(block);
// Define contraints on the model
// Add a point on line constraint to limit the block to vertical motion
Vec3 lineDirection(0,1,0), pointOnLine(0,0,0), pointOnBlock(0);
PointOnLineConstraint *lineConstraint = new PointOnLineConstraint(ground, lineDirection, pointOnLine, *block, pointOnBlock);
osimModel.addConstraint(lineConstraint);
// Add PistonActuator between the first linkage and the block
Vec3 pointOnBodies(0);
PistonActuator *piston = new PistonActuator();
piston->setName("piston");
piston->setBodyA(linkage1);
piston->setBodyB(block);
piston->setPointA(pointOnBodies);
piston->setPointB(pointOnBodies);
piston->setOptimalForce(200.0);
piston->setPointsAreGlobal(false);
osimModel.addForce(piston);
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Added ControllableSpring between the first linkage and the second block
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ControllableSpring *spring = new ControllableSpring;
spring->setName("spring");
spring->setBodyA(block);
spring->setBodyB(linkage1);
spring->setPointA(pointOnBodies);
spring->setPointB(pointOnBodies);
spring->setOptimalForce(2000.0);
spring->setPointsAreGlobal(false);
spring->setRestLength(0.8);
osimModel.addForce(spring);
// define the simulation times
double t0(0.0), tf(15);
// define the control values for the piston
//double controlT0[1] = {0.982}, controlTf[1] = {0.978};
// define the control values for the spring
//double controlT0[1] = {1.0}, controlT1[1] = {1.0}, controlT2[1] = {0.25},
// controlT3[1] = {.25}, controlT4[1] = {5};
//ControlSet *controlSet = new ControlSet();
//ControlLinear *control1 = new ControlLinear();
//control1->setName("spring"); // change this between 'piston' and 'spring'
////control1->setUseSteps(true);
//controlSet->adoptAndAppend(control1);
//// set control values for the piston
///*controlSet->setControlValues(t0, controlT0);
//controlSet->setControlValues(tf, controlTf);*/
//// set control values for the spring
//controlSet->setControlValues(t0, controlT0);
//controlSet->setControlValues(4.0, controlT1);
//controlSet->setControlValues(7.0, controlT2);
//controlSet->setControlValues(10.0, controlT3);
//controlSet->setControlValues(tf, controlT4);
//ControlSetController *legController = new ControlSetController();
//legController->setControlSet(controlSet);
PrescribedController *legController = new PrescribedController();
legController->setActuators(osimModel.updActuators());
legController->prescribeControlForActuator("piston", new Constant(2.0));
legController->prescribeControlForActuator("spring", new Constant(2.0));
osimModel.addController(legController);
// define the acceration due to gravity
osimModel.setGravity(Vec3(0, -9.80665, 0));
// enable the model visualizer see the model in action, which can be
// useful for debugging
osimModel.setUseVisualizer(false);
// Initialize system
SimTK::State& si = osimModel.initSystem();
// Pin joint initial states
double q1_i = -Pi/4;
double q2_i = - 2*q1_i;
CoordinateSet &coordinates = osimModel.updCoordinateSet();
coordinates[0].setValue(si, q1_i, true);
coordinates[1].setValue(si,q2_i, true);
// Compute initial conditions for muscles
osimModel.equilibrateMuscles(si);
// Setup integrator and manager
SimTK::RungeKuttaMersonIntegrator integrator(osimModel.getMultibodySystem());
integrator.setAccuracy(1.0e-3);
ForceReporter *forces = new ForceReporter(&osimModel);
osimModel.updAnalysisSet().adoptAndAppend(forces);
Manager manager(osimModel, integrator);
//Examine the model
osimModel.printDetailedInfo(si, std::cout);
// Save the model
osimModel.print("toyLeg.osim");
// Print out the initial position and velocity states
si.getQ().dump("Initial q's");
si.getU().dump("Initial u's");
std::cout << "Initial time: " << si.getTime() << std::endl;
// Integrate
manager.setInitialTime(t0);
manager.setFinalTime(tf);
std::cout<<"\n\nIntegrating from " << t0 << " to " << tf << std::endl;
manager.integrate(si);
// Save results
Storage statesDegrees(manager.getStateStorage());
osimModel.updSimbodyEngine().convertRadiansToDegrees(statesDegrees);
//statesDegrees.print("PistonActuatedLeg_states_degrees.mot");
statesDegrees.print("SpringActuatedLeg_states_degrees.mot");
forces->getForceStorage().print("actuator_forces.mot");
}
catch (const std::exception& ex)
{
std::cout << "Exception in toyLeg_example: " << ex.what() << std::endl;
return 1;
}
std::cout << "Exiting" << std::endl;
return 0;
}
<commit_msg>API Example: toyleg changed the control functions from constant to linear <commit_after>/* -------------------------------------------------------------------------- *
* OpenSim: toyLeg_example.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2012 Stanford University and the Authors *
* Author(s): Matt S. DeMers *
* *
* 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. *
* -------------------------------------------------------------------------- */
/*
* Below is an example of an OpenSim application that provides its own
* main() routine. This application acts as an example for utilizing the
* ControllabeSpring actuator.
*/
// Author: Matt DeMers
//==============================================================================
//==============================================================================
#include "PistonActuator.h"
#include "ControllableSpring.h"
#include <OpenSim/OpenSim.h>
using namespace OpenSim;
using namespace SimTK;
//______________________________________________________________________________
/**
* Run a simulation of block sliding with contact on by two muscles sliding with contact
*/
int main()
{
try {
// Create a new OpenSim model
Model osimModel;
osimModel.setName("osimModel");
double Pi = SimTK::Pi;
// Get the ground body
OpenSim::Body& ground = osimModel.getGroundBody();
ground.addDisplayGeometry("ground.vtp");
// create linkage body
double linkageMass = 0.001, linkageLength = 0.5;
Vec3 linkageMassCenter(0,-linkageLength/2,0);
Inertia linkageInertia = Inertia::cylinderAlongY(0.0, 0.5);
OpenSim::Body *linkage1 = new OpenSim::Body("linkage1", linkageMass, linkageMassCenter, linkageMass*linkageInertia);
// Graphical representation
linkage1->addDisplayGeometry("linkage1.vtp");
// Creat a second linkage body
OpenSim::Body *linkage2 = new OpenSim::Body("linkage2", linkageMass, linkageMassCenter, linkageMass*linkageInertia);
linkage2->addDisplayGeometry("linkage1.vtp");
// Creat a block to be the pelvis
double blockMass = 20.0, blockSideLength = 0.2;
Vec3 blockMassCenter(0);
Inertia blockInertia = blockMass*Inertia::brick(blockSideLength, blockSideLength, blockSideLength);
OpenSim::Body *block = new OpenSim::Body("block", blockMass, blockMassCenter, blockInertia);
block->addDisplayGeometry("big_block_centered.vtp");
// Create 1 degree-of-freedom pin joints between the bodies to creat a kinematic chain from ground through the block
Vec3 orientationInGround(0), locationInGround(0), locationInParent(0.0, 0.5, 0.0), orientationInChild(0), locationInChild(0);
PinJoint *ankle = new PinJoint("ankle", ground, locationInGround, orientationInGround, *linkage1,
locationInChild, orientationInChild);
PinJoint *knee = new PinJoint("knee", *linkage1, locationInParent, orientationInChild, *linkage2,
locationInChild, orientationInChild);
PinJoint *hip = new PinJoint("hip", *linkage2, locationInParent, orientationInChild, *block,
locationInChild, orientationInChild);
double range[2] = {-SimTK::Pi*2, SimTK::Pi*2};
CoordinateSet& ankleCoordinateSet = ankle->upd_CoordinateSet();
ankleCoordinateSet[0].setName("q1");
ankleCoordinateSet[0].setRange(range);
CoordinateSet& kneeCoordinateSet = knee->upd_CoordinateSet();
kneeCoordinateSet[0].setName("q2");
kneeCoordinateSet[0].setRange(range);
CoordinateSet& hipCoordinateSet = hip->upd_CoordinateSet();
hipCoordinateSet[0].setName("q3");
hipCoordinateSet[0].setRange(range);
// Add the bodies to the model
osimModel.addBody(linkage1);
osimModel.addBody(linkage2);
osimModel.addBody(block);
// Define contraints on the model
// Add a point on line constraint to limit the block to vertical motion
Vec3 lineDirection(0,1,0), pointOnLine(0,0,0), pointOnBlock(0);
PointOnLineConstraint *lineConstraint = new PointOnLineConstraint(ground, lineDirection, pointOnLine, *block, pointOnBlock);
osimModel.addConstraint(lineConstraint);
// Add PistonActuator between the first linkage and the block
Vec3 pointOnBodies(0);
PistonActuator *piston = new PistonActuator();
piston->setName("piston");
piston->setBodyA(linkage1);
piston->setBodyB(block);
piston->setPointA(pointOnBodies);
piston->setPointB(pointOnBodies);
piston->setOptimalForce(200.0);
piston->setPointsAreGlobal(false);
osimModel.addForce(piston);
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Added ControllableSpring between the first linkage and the second block
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ControllableSpring *spring = new ControllableSpring;
spring->setName("spring");
spring->setBodyA(block);
spring->setBodyB(linkage1);
spring->setPointA(pointOnBodies);
spring->setPointB(pointOnBodies);
spring->setOptimalForce(2000.0);
spring->setPointsAreGlobal(false);
spring->setRestLength(0.8);
osimModel.addForce(spring);
// define the simulation times
double t0(0.0), tf(15);
// define the control values for the piston
//double controlT0[1] = {0.982}, controlTf[1] = {0.978};
// define the control values for the spring
//double controlT0[1] = {1.0}, controlT1[1] = {1.0}, controlT2[1] = {0.25},
// controlT3[1] = {.25}, controlT4[1] = {5};
//ControlSet *controlSet = new ControlSet();
//ControlLinear *control1 = new ControlLinear();
//control1->setName("spring"); // change this between 'piston' and 'spring'
////control1->setUseSteps(true);
//controlSet->adoptAndAppend(control1);
//// set control values for the piston
///*controlSet->setControlValues(t0, controlT0);
//controlSet->setControlValues(tf, controlTf);*/
//// set control values for the spring
//controlSet->setControlValues(t0, controlT0);
//controlSet->setControlValues(4.0, controlT1);
//controlSet->setControlValues(7.0, controlT2);
//controlSet->setControlValues(10.0, controlT3);
//controlSet->setControlValues(tf, controlT4);
//ControlSetController *legController = new ControlSetController();
//legController->setControlSet(controlSet);
PrescribedController *legController = new PrescribedController();
legController->setActuators(osimModel.updActuators());
legController->prescribeControlForActuator("piston", new LinearFunction(1, 0));
legController->prescribeControlForActuator("spring", new LinearFunction(1, 0));
osimModel.addController(legController);
// define the acceration due to gravity
osimModel.setGravity(Vec3(0, -9.80665, 0));
// enable the model visualizer see the model in action, which can be
// useful for debugging
osimModel.setUseVisualizer(false);
// Initialize system
SimTK::State& si = osimModel.initSystem();
// Pin joint initial states
double q1_i = -Pi/4;
double q2_i = - 2*q1_i;
CoordinateSet &coordinates = osimModel.updCoordinateSet();
coordinates[0].setValue(si, q1_i, true);
coordinates[1].setValue(si,q2_i, true);
// Compute initial conditions for muscles
osimModel.equilibrateMuscles(si);
// Setup integrator and manager
SimTK::RungeKuttaMersonIntegrator integrator(osimModel.getMultibodySystem());
integrator.setAccuracy(1.0e-3);
ForceReporter *forces = new ForceReporter(&osimModel);
osimModel.updAnalysisSet().adoptAndAppend(forces);
Manager manager(osimModel, integrator);
//Examine the model
osimModel.printDetailedInfo(si, std::cout);
// Save the model
osimModel.print("toyLeg.osim");
// Print out the initial position and velocity states
si.getQ().dump("Initial q's");
si.getU().dump("Initial u's");
std::cout << "Initial time: " << si.getTime() << std::endl;
// Integrate
manager.setInitialTime(t0);
manager.setFinalTime(tf);
std::cout<<"\n\nIntegrating from " << t0 << " to " << tf << std::endl;
manager.integrate(si);
// Save results
Storage statesDegrees(manager.getStateStorage());
osimModel.updSimbodyEngine().convertRadiansToDegrees(statesDegrees);
//statesDegrees.print("PistonActuatedLeg_states_degrees.mot");
statesDegrees.print("SpringActuatedLeg_states_degrees.mot");
forces->getForceStorage().print("actuator_forces.mot");
}
catch (const std::exception& ex)
{
std::cout << "Exception in toyLeg_example: " << ex.what() << std::endl;
return 1;
}
std::cout << "Exiting" << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>#pragma once
#include <agency/detail/config.hpp>
#include <agency/detail/requires.hpp>
#include <agency/execution/executor/detail/new_executor_traits/is_bulk_executor.hpp>
#include <agency/execution/executor/detail/new_executor_traits/is_bulk_synchronous_executor.hpp>
#include <agency/execution/executor/detail/new_executor_traits/is_bulk_asynchronous_executor.hpp>
#include <agency/execution/executor/detail/new_executor_traits/is_bulk_continuation_executor.hpp>
#include <agency/execution/executor/detail/new_executor_traits/executor_future.hpp>
#include <agency/execution/executor/detail/new_executor_traits/executor_shape.hpp>
#include <agency/execution/executor/detail/new_executor_traits/executor_execution_depth.hpp>
#include <agency/execution/executor/detail/new_executor_traits/bulk_then_execute.hpp>
#include <agency/execution/executor/detail/new_executor_traits/bulk_async_execute.hpp>
#include <future>
namespace agency
{
namespace detail
{
namespace new_executor_traits_detail
{
// this case handles executors which have .bulk_then_execute()
__agency_exec_check_disable__
template<class E, class Function, class Future, class ResultFactory, class... Factories,
__AGENCY_REQUIRES(BulkContinuationExecutor<E>()),
__AGENCY_REQUIRES(executor_execution_depth<E>::value == sizeof...(Factories))
>
__AGENCY_ANNOTATION
executor_future_t<
E,
result_of_t<ResultFactory()>
>
bulk_then_execute(E& exec, Function f, executor_shape_t<E> shape, Future& predecessor, ResultFactory result_factory, Factories... shared_factories)
{
return exec.bulk_then_execute(f, shape, predecessor, result_factory, shared_factories...);
}
template<class Function, class SharedFuture,
bool Enable = std::is_void<typename future_traits<SharedFuture>::value_type>::value
>
struct bulk_then_execute_functor
{
mutable Function f_;
mutable SharedFuture fut_;
using predecessor_type = typename future_traits<SharedFuture>::value_type;
__agency_exec_check_disable__
__AGENCY_ANNOTATION
~bulk_then_execute_functor() = default;
__agency_exec_check_disable__
__AGENCY_ANNOTATION
bulk_then_execute_functor(Function f, const SharedFuture& fut)
: f_(f), fut_(fut)
{}
__agency_exec_check_disable__
__AGENCY_ANNOTATION
bulk_then_execute_functor(const bulk_then_execute_functor&) = default;
__agency_exec_check_disable__
template<class Index, class... Args>
__AGENCY_ANNOTATION
auto operator()(const Index &idx, Args&... args) const ->
decltype(f_(idx, const_cast<predecessor_type&>(fut_.get()),args...))
{
predecessor_type& predecessor = const_cast<predecessor_type&>(fut_.get());
return f_(idx, predecessor, args...);
}
};
template<class Function, class SharedFuture>
struct bulk_then_execute_functor<Function,SharedFuture,true>
{
mutable Function f_;
mutable SharedFuture fut_;
__agency_exec_check_disable__
__AGENCY_ANNOTATION
~bulk_then_execute_functor() = default;
__agency_exec_check_disable__
__AGENCY_ANNOTATION
bulk_then_execute_functor(Function f, const SharedFuture& fut)
: f_(f), fut_(fut)
{}
__agency_exec_check_disable__
__AGENCY_ANNOTATION
bulk_then_execute_functor(const bulk_then_execute_functor&) = default;
__agency_exec_check_disable__
template<class Index, class... Args>
__AGENCY_ANNOTATION
auto operator()(const Index &idx, Args&... args) const ->
decltype(f_(idx, args...))
{
fut_.wait();
return f_(idx, args...);
}
};
// this case handles executors which have .bulk_async_execute() and may or may not have .bulk_execute()
__agency_exec_check_disable__
template<class E, class Function, class Future, class ResultFactory, class... Factories,
__AGENCY_REQUIRES(!BulkContinuationExecutor<E>() && BulkAsynchronousExecutor<E>()),
__AGENCY_REQUIRES(executor_execution_depth<E>::value == sizeof...(Factories))
>
__AGENCY_ANNOTATION
executor_future_t<
E,
result_of_t<ResultFactory()>
>
bulk_then_execute(E& exec, Function f, executor_shape_t<E> shape, Future& predecessor, ResultFactory result_factory, Factories... shared_factories)
{
// XXX we may wish to allow the executor to participate in this sharing operation
auto shared_predecessor_future = future_traits<Future>::share(predecessor);
using shared_predecessor_future_type = decltype(shared_predecessor_future);
auto functor = bulk_then_execute_functor<Function,shared_predecessor_future_type>{f, shared_predecessor_future};
return bulk_async_execute(exec, functor, shape, result_factory, shared_factories...);
}
// this case handles executors which only have .bulk_execute()
__agency_exec_check_disable__
template<class E, class Function, class Future, class ResultFactory, class... Factories,
__AGENCY_REQUIRES(!BulkContinuationExecutor<E>() && !BulkAsynchronousExecutor<E>()),
__AGENCY_REQUIRES(executor_execution_depth<E>::value == sizeof...(Factories))
>
__AGENCY_ANNOTATION
executor_future_t<
E,
result_of_t<ResultFactory()>
>
bulk_then_execute(E& exec, Function f, executor_shape_t<E> shape, Future& predecessor, ResultFactory result_factory, Factories... shared_factories)
{
// XXX we may wish to allow the executor to participate in this sharing operation
auto shared_predecessor_future = future_traits<Future>::share(predecessor);
// XXX we should call async_execute(exec, ...) instead of std::async() here
// XXX alternatively, we could call then_execute(exec, predecessor, ...) and not wait inside the function
// XXX need to use a __host__ __device__ functor here instead of a lambda
return std::async(std::launch::deferred, [=]() mutable
{
using shared_predecessor_future_type = decltype(shared_predecessor_future);
auto functor = bulk_then_execute_functor<Function,shared_predecessor_future_type>{f, shared_predecessor_future};
return bulk_execute(exec, functor, shape, result_factory, shared_factories...);
});
}
} // end new_executor_traits_detail
} // end detail
} // end agency
<commit_msg>Implement bulk_then_execute() with predecessor.then() + exec.bulk_execute()<commit_after>#pragma once
#include <agency/detail/config.hpp>
#include <agency/detail/requires.hpp>
#include <agency/execution/executor/detail/new_executor_traits/is_bulk_executor.hpp>
#include <agency/execution/executor/detail/new_executor_traits/is_bulk_synchronous_executor.hpp>
#include <agency/execution/executor/detail/new_executor_traits/is_bulk_asynchronous_executor.hpp>
#include <agency/execution/executor/detail/new_executor_traits/is_bulk_continuation_executor.hpp>
#include <agency/execution/executor/detail/new_executor_traits/executor_future.hpp>
#include <agency/execution/executor/detail/new_executor_traits/executor_shape.hpp>
#include <agency/execution/executor/detail/new_executor_traits/executor_execution_depth.hpp>
#include <agency/execution/executor/detail/new_executor_traits/bulk_then_execute.hpp>
#include <future>
namespace agency
{
namespace detail
{
namespace new_executor_traits_detail
{
// this case handles executors which have .bulk_then_execute()
__agency_exec_check_disable__
template<class E, class Function, class Future, class ResultFactory, class... Factories,
__AGENCY_REQUIRES(BulkContinuationExecutor<E>()),
__AGENCY_REQUIRES(executor_execution_depth<E>::value == sizeof...(Factories))
>
__AGENCY_ANNOTATION
executor_future_t<
E,
result_of_t<ResultFactory()>
>
bulk_then_execute(E& exec, Function f, executor_shape_t<E> shape, Future& predecessor, ResultFactory result_factory, Factories... shared_factories)
{
return exec.bulk_then_execute(f, shape, predecessor, result_factory, shared_factories...);
}
namespace bulk_then_execute_detail
{
template<class Function, class SharedFuture,
bool Enable = std::is_void<typename future_traits<SharedFuture>::value_type>::value
>
struct bulk_then_execute_functor
{
mutable Function f_;
mutable SharedFuture fut_;
using predecessor_type = typename future_traits<SharedFuture>::value_type;
__agency_exec_check_disable__
__AGENCY_ANNOTATION
~bulk_then_execute_functor() = default;
__agency_exec_check_disable__
__AGENCY_ANNOTATION
bulk_then_execute_functor(Function f, const SharedFuture& fut)
: f_(f), fut_(fut)
{}
__agency_exec_check_disable__
__AGENCY_ANNOTATION
bulk_then_execute_functor(const bulk_then_execute_functor&) = default;
__agency_exec_check_disable__
template<class Index, class... Args>
__AGENCY_ANNOTATION
auto operator()(const Index &idx, Args&... args) const ->
decltype(f_(idx, const_cast<predecessor_type&>(fut_.get()),args...))
{
predecessor_type& predecessor = const_cast<predecessor_type&>(fut_.get());
return f_(idx, predecessor, args...);
}
};
template<class Function, class SharedFuture>
struct bulk_then_execute_functor<Function,SharedFuture,true>
{
mutable Function f_;
mutable SharedFuture fut_;
__agency_exec_check_disable__
__AGENCY_ANNOTATION
~bulk_then_execute_functor() = default;
__agency_exec_check_disable__
__AGENCY_ANNOTATION
bulk_then_execute_functor(Function f, const SharedFuture& fut)
: f_(f), fut_(fut)
{}
__agency_exec_check_disable__
__AGENCY_ANNOTATION
bulk_then_execute_functor(const bulk_then_execute_functor&) = default;
__agency_exec_check_disable__
template<class Index, class... Args>
__AGENCY_ANNOTATION
auto operator()(const Index &idx, Args&... args) const ->
decltype(f_(idx, args...))
{
fut_.wait();
return f_(idx, args...);
}
};
} // end bulk_then_execute_detail
// this case handles executors which have .bulk_async_execute() and may or may not have .bulk_execute()
__agency_exec_check_disable__
template<class E, class Function, class Future, class ResultFactory, class... Factories,
__AGENCY_REQUIRES(!BulkContinuationExecutor<E>() && BulkAsynchronousExecutor<E>()),
__AGENCY_REQUIRES(executor_execution_depth<E>::value == sizeof...(Factories))
>
__AGENCY_ANNOTATION
executor_future_t<
E,
result_of_t<ResultFactory()>
>
bulk_then_execute(E& exec, Function f, executor_shape_t<E> shape, Future& predecessor, ResultFactory result_factory, Factories... shared_factories)
{
using namespace bulk_then_execute_detail;
// XXX we may wish to allow the executor to participate in this sharing operation
auto shared_predecessor_future = future_traits<Future>::share(predecessor);
using shared_predecessor_future_type = decltype(shared_predecessor_future);
auto functor = bulk_then_execute_functor<Function,shared_predecessor_future_type>{f, shared_predecessor_future};
return exec.bulk_async_execute(functor, shape, result_factory, shared_factories...);
}
namespace bulk_then_execute_detail
{
// this functor is used by the implementation of bulk_then_execute() below which calls .then() with a nested bulk_execute() inside
// this definition is for the general case, when the predecessor Future type is non-void
template<class Executor, class Function, class Predecessor, class ResultFactory, class... SharedFactories>
struct then_with_nested_bulk_execute_functor
{
mutable Executor exec;
mutable Function f;
executor_shape_t<Executor> shape;
mutable ResultFactory result_factory;
mutable detail::tuple<SharedFactories...> shared_factories;
// this functor is passed to bulk_execute() below
// it has a reference to the predecessor future to use as a parameter to f
struct functor_for_bulk_execute
{
mutable Function f;
Predecessor& predecessor;
template<class Index, class Result, class... SharedArgs>
__AGENCY_ANNOTATION
void operator()(const Index& idx, Result& result, SharedArgs&... shared_args) const
{
agency::detail::invoke(f, idx, predecessor, result, shared_args...);
}
};
template<size_t... Indices>
__AGENCY_ANNOTATION
result_of_t<ResultFactory()> impl(detail::index_sequence<Indices...>, Predecessor& predecessor) const
{
functor_for_bulk_execute functor{f, predecessor};
return exec.bulk_execute(functor, shape, result_factory, detail::get<Indices>(shared_factories)...);
}
__AGENCY_ANNOTATION
result_of_t<ResultFactory()> operator()(Predecessor& predecessor) const
{
return impl(detail::make_index_sequence<sizeof...(SharedFactories)>(), predecessor);
}
};
// this specialization is for the case when the predecessor Future type is void
template<class Executor, class Function, class ResultFactory, class... SharedFactories>
struct then_with_nested_bulk_execute_functor<Executor,Function,void,ResultFactory,SharedFactories...>
{
mutable Executor exec;
mutable Function f;
executor_shape_t<Executor> shape;
mutable ResultFactory result_factory;
mutable detail::tuple<SharedFactories...> shared_factories;
template<size_t... Indices>
__AGENCY_ANNOTATION
result_of_t<ResultFactory()> impl(detail::index_sequence<Indices...>) const
{
return exec.bulk_execute(f, shape, result_factory, detail::get<Indices>(shared_factories)...);
}
// the predecessor future is void, so operator() receives no parameter
__AGENCY_ANNOTATION
result_of_t<ResultFactory()> operator()() const
{
return impl(detail::make_index_sequence<sizeof...(SharedFactories)>());
}
};
} // end bulk_then_execute_detail
// this case handles executors which only have .bulk_execute()
__agency_exec_check_disable__
template<class E, class Function, class Future, class ResultFactory, class... Factories,
__AGENCY_REQUIRES(!BulkContinuationExecutor<E>() && !BulkAsynchronousExecutor<E>()),
__AGENCY_REQUIRES(executor_execution_depth<E>::value == sizeof...(Factories))
>
__AGENCY_ANNOTATION
executor_future_t<
E,
result_of_t<ResultFactory()>
>
bulk_then_execute(E& exec, Function f, executor_shape_t<E> shape, Future& predecessor, ResultFactory result_factory, Factories... shared_factories)
{
using namespace bulk_then_execute_detail;
using predecessor_type = future_value_t<Future>;
then_with_nested_bulk_execute_functor<E,Function,predecessor_type,ResultFactory,Factories...> functor{exec,f,shape,result_factory,detail::make_tuple(shared_factories...)};
auto intermediate_fut = future_traits<Future>::then(predecessor, std::move(functor));
using result_type = result_of_t<ResultFactory()>;
// XXX we may wish to allow the executor to participate in this cast operation
return future_traits<decltype(intermediate_fut)>::template cast<result_type>(intermediate_fut);
}
} // end new_executor_traits_detail
} // end detail
} // end agency
<|endoftext|> |
<commit_before>// $Id$
// vim:tabstop=2
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2010 Hieu Hoang
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 "ChartParser.h"
#include "ChartParserCallback.h"
#include "ChartRuleLookupManager.h"
#include "DummyScoreProducers.h"
#include "StaticData.h"
#include "TreeInput.h"
using namespace std;
using namespace Moses;
namespace Moses
{
extern bool g_debug;
ChartParserUnknown::ChartParserUnknown(const TranslationSystem &system) : m_system(system) {}
ChartParserUnknown::~ChartParserUnknown() {
RemoveAllInColl(m_unksrcs);
RemoveAllInColl(m_cacheTargetPhraseCollection);
}
void ChartParserUnknown::Process(const Word &sourceWord, const WordsRange &range, ChartParserCallback &to) {
// unknown word, add as trans opt
const StaticData &staticData = StaticData::Instance();
const UnknownWordPenaltyProducer *unknownWordPenaltyProducer = m_system.GetUnknownWordPenaltyProducer();
vector<float> wordPenaltyScore(1, -0.434294482); // TODO what is this number?
size_t isDigit = 0;
if (staticData.GetDropUnknown()) {
const Factor *f = sourceWord[0]; // TODO hack. shouldn't know which factor is surface
const string &s = f->GetString();
isDigit = s.find_first_of("0123456789");
if (isDigit == string::npos)
isDigit = 0;
else
isDigit = 1;
// modify the starting bitmap
}
Phrase* unksrc = new Phrase(1);
unksrc->AddWord() = sourceWord;
m_unksrcs.push_back(unksrc);
//TranslationOption *transOpt;
if (! staticData.GetDropUnknown() || isDigit) {
// loop
const UnknownLHSList &lhsList = staticData.GetUnknownLHS();
UnknownLHSList::const_iterator iterLHS;
for (iterLHS = lhsList.begin(); iterLHS != lhsList.end(); ++iterLHS) {
const string &targetLHSStr = iterLHS->first;
float prob = iterLHS->second;
// lhs
//const Word &sourceLHS = staticData.GetInputDefaultNonTerminal();
Word targetLHS(true);
targetLHS.CreateFromString(Output, staticData.GetOutputFactorOrder(), targetLHSStr, true);
CHECK(targetLHS.GetFactor(0) != NULL);
// add to dictionary
TargetPhrase *targetPhrase = new TargetPhrase();
Word &targetWord = targetPhrase->AddWord();
targetWord.CreateUnknownWord(sourceWord);
// scores
vector<float> unknownScore(1, FloorScore(TransformScore(prob)));
//targetPhrase->SetScore();
targetPhrase->SetScore(unknownWordPenaltyProducer, unknownScore);
targetPhrase->SetScore(m_system.GetWordPenaltyProducer(), wordPenaltyScore);
targetPhrase->SetSourcePhrase(*unksrc);
targetPhrase->SetTargetLHS(targetLHS);
// chart rule
to.AddPhraseOOV(*targetPhrase, m_cacheTargetPhraseCollection, range);
} // for (iterLHS
} else {
// drop source word. create blank trans opt
vector<float> unknownScore(1, FloorScore(-numeric_limits<float>::infinity()));
TargetPhrase *targetPhrase = new TargetPhrase();
// loop
const UnknownLHSList &lhsList = staticData.GetUnknownLHS();
UnknownLHSList::const_iterator iterLHS;
for (iterLHS = lhsList.begin(); iterLHS != lhsList.end(); ++iterLHS) {
const string &targetLHSStr = iterLHS->first;
//float prob = iterLHS->second;
Word targetLHS(true);
targetLHS.CreateFromString(Output, staticData.GetOutputFactorOrder(), targetLHSStr, true);
CHECK(targetLHS.GetFactor(0) != NULL);
targetPhrase->SetSourcePhrase(*unksrc);
targetPhrase->SetScore(unknownWordPenaltyProducer, unknownScore);
targetPhrase->SetTargetLHS(targetLHS);
// chart rule
to.AddPhraseOOV(*targetPhrase, m_cacheTargetPhraseCollection, range);
}
}
}
ChartParser::ChartParser(InputType const &source, const TranslationSystem &system, ChartCellCollectionBase &cells) :
m_unknown(system),
m_decodeGraphList(system.GetDecodeGraphs()),
m_source(source) {
system.InitializeBeforeSentenceProcessing(source);
const std::vector<PhraseDictionaryFeature*> &dictionaries = system.GetPhraseDictionaries();
m_ruleLookupManagers.reserve(dictionaries.size());
for (std::vector<PhraseDictionaryFeature*>::const_iterator p = dictionaries.begin();
p != dictionaries.end(); ++p) {
PhraseDictionaryFeature *pdf = *p;
const PhraseDictionary *dict = pdf->GetDictionary();
PhraseDictionary *nonConstDict = const_cast<PhraseDictionary*>(dict);
m_ruleLookupManagers.push_back(nonConstDict->CreateRuleLookupManager(source, cells));
}
}
ChartParser::~ChartParser() {
RemoveAllInColl(m_ruleLookupManagers);
}
void ChartParser::Create(const WordsRange &wordsRange, ChartParserCallback &to) {
assert(m_decodeGraphList.size() == m_ruleLookupManagers.size());
std::vector <DecodeGraph*>::const_iterator iterDecodeGraph;
std::vector <ChartRuleLookupManager*>::const_iterator iterRuleLookupManagers = m_ruleLookupManagers.begin();
for (iterDecodeGraph = m_decodeGraphList.begin(); iterDecodeGraph != m_decodeGraphList.end(); ++iterDecodeGraph, ++iterRuleLookupManagers) {
const DecodeGraph &decodeGraph = **iterDecodeGraph;
assert(decodeGraph.GetSize() == 1);
ChartRuleLookupManager &ruleLookupManager = **iterRuleLookupManagers;
size_t maxSpan = decodeGraph.GetMaxChartSpan();
if (maxSpan == 0 || wordsRange.GetNumWordsCovered() <= maxSpan) {
ruleLookupManager.GetChartRuleCollection(wordsRange, to);
}
}
if (wordsRange.GetNumWordsCovered() == 1 && wordsRange.GetStartPos() != 0 && wordsRange.GetStartPos() != m_source.GetSize()-1) {
bool alwaysCreateDirectTranslationOption = StaticData::Instance().IsAlwaysCreateDirectTranslationOption();
if (to.Empty() || alwaysCreateDirectTranslationOption) {
// create unknown words for 1 word coverage where we don't have any trans options
const Word &sourceWord = m_source.GetWord(wordsRange.GetStartPos());
m_unknown.Process(sourceWord, wordsRange, to);
}
}
}
} // namespace Moses
<commit_msg>add word alignment for OOV too. Exist for pb but not hiero model<commit_after>// $Id$
// vim:tabstop=2
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2010 Hieu Hoang
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 "ChartParser.h"
#include "ChartParserCallback.h"
#include "ChartRuleLookupManager.h"
#include "DummyScoreProducers.h"
#include "StaticData.h"
#include "TreeInput.h"
using namespace std;
using namespace Moses;
namespace Moses
{
extern bool g_debug;
ChartParserUnknown::ChartParserUnknown(const TranslationSystem &system) : m_system(system) {}
ChartParserUnknown::~ChartParserUnknown() {
RemoveAllInColl(m_unksrcs);
RemoveAllInColl(m_cacheTargetPhraseCollection);
}
void ChartParserUnknown::Process(const Word &sourceWord, const WordsRange &range, ChartParserCallback &to) {
// unknown word, add as trans opt
const StaticData &staticData = StaticData::Instance();
const UnknownWordPenaltyProducer *unknownWordPenaltyProducer = m_system.GetUnknownWordPenaltyProducer();
vector<float> wordPenaltyScore(1, -0.434294482); // TODO what is this number?
size_t isDigit = 0;
if (staticData.GetDropUnknown()) {
const Factor *f = sourceWord[0]; // TODO hack. shouldn't know which factor is surface
const string &s = f->GetString();
isDigit = s.find_first_of("0123456789");
if (isDigit == string::npos)
isDigit = 0;
else
isDigit = 1;
// modify the starting bitmap
}
Phrase* unksrc = new Phrase(1);
unksrc->AddWord() = sourceWord;
m_unksrcs.push_back(unksrc);
//TranslationOption *transOpt;
if (! staticData.GetDropUnknown() || isDigit) {
// loop
const UnknownLHSList &lhsList = staticData.GetUnknownLHS();
UnknownLHSList::const_iterator iterLHS;
for (iterLHS = lhsList.begin(); iterLHS != lhsList.end(); ++iterLHS) {
const string &targetLHSStr = iterLHS->first;
float prob = iterLHS->second;
// lhs
//const Word &sourceLHS = staticData.GetInputDefaultNonTerminal();
Word targetLHS(true);
targetLHS.CreateFromString(Output, staticData.GetOutputFactorOrder(), targetLHSStr, true);
CHECK(targetLHS.GetFactor(0) != NULL);
// add to dictionary
TargetPhrase *targetPhrase = new TargetPhrase();
Word &targetWord = targetPhrase->AddWord();
targetWord.CreateUnknownWord(sourceWord);
// scores
vector<float> unknownScore(1, FloorScore(TransformScore(prob)));
//targetPhrase->SetScore();
targetPhrase->SetScore(unknownWordPenaltyProducer, unknownScore);
targetPhrase->SetScore(m_system.GetWordPenaltyProducer(), wordPenaltyScore);
targetPhrase->SetSourcePhrase(*unksrc);
targetPhrase->SetTargetLHS(targetLHS);
targetPhrase->SetAlignmentInfo("0-0");
// chart rule
to.AddPhraseOOV(*targetPhrase, m_cacheTargetPhraseCollection, range);
} // for (iterLHS
} else {
// drop source word. create blank trans opt
vector<float> unknownScore(1, FloorScore(-numeric_limits<float>::infinity()));
TargetPhrase *targetPhrase = new TargetPhrase();
// loop
const UnknownLHSList &lhsList = staticData.GetUnknownLHS();
UnknownLHSList::const_iterator iterLHS;
for (iterLHS = lhsList.begin(); iterLHS != lhsList.end(); ++iterLHS) {
const string &targetLHSStr = iterLHS->first;
//float prob = iterLHS->second;
Word targetLHS(true);
targetLHS.CreateFromString(Output, staticData.GetOutputFactorOrder(), targetLHSStr, true);
CHECK(targetLHS.GetFactor(0) != NULL);
targetPhrase->SetSourcePhrase(*unksrc);
targetPhrase->SetScore(unknownWordPenaltyProducer, unknownScore);
targetPhrase->SetTargetLHS(targetLHS);
// chart rule
to.AddPhraseOOV(*targetPhrase, m_cacheTargetPhraseCollection, range);
}
}
}
ChartParser::ChartParser(InputType const &source, const TranslationSystem &system, ChartCellCollectionBase &cells) :
m_unknown(system),
m_decodeGraphList(system.GetDecodeGraphs()),
m_source(source) {
system.InitializeBeforeSentenceProcessing(source);
const std::vector<PhraseDictionaryFeature*> &dictionaries = system.GetPhraseDictionaries();
m_ruleLookupManagers.reserve(dictionaries.size());
for (std::vector<PhraseDictionaryFeature*>::const_iterator p = dictionaries.begin();
p != dictionaries.end(); ++p) {
PhraseDictionaryFeature *pdf = *p;
const PhraseDictionary *dict = pdf->GetDictionary();
PhraseDictionary *nonConstDict = const_cast<PhraseDictionary*>(dict);
m_ruleLookupManagers.push_back(nonConstDict->CreateRuleLookupManager(source, cells));
}
}
ChartParser::~ChartParser() {
RemoveAllInColl(m_ruleLookupManagers);
}
void ChartParser::Create(const WordsRange &wordsRange, ChartParserCallback &to) {
assert(m_decodeGraphList.size() == m_ruleLookupManagers.size());
std::vector <DecodeGraph*>::const_iterator iterDecodeGraph;
std::vector <ChartRuleLookupManager*>::const_iterator iterRuleLookupManagers = m_ruleLookupManagers.begin();
for (iterDecodeGraph = m_decodeGraphList.begin(); iterDecodeGraph != m_decodeGraphList.end(); ++iterDecodeGraph, ++iterRuleLookupManagers) {
const DecodeGraph &decodeGraph = **iterDecodeGraph;
assert(decodeGraph.GetSize() == 1);
ChartRuleLookupManager &ruleLookupManager = **iterRuleLookupManagers;
size_t maxSpan = decodeGraph.GetMaxChartSpan();
if (maxSpan == 0 || wordsRange.GetNumWordsCovered() <= maxSpan) {
ruleLookupManager.GetChartRuleCollection(wordsRange, to);
}
}
if (wordsRange.GetNumWordsCovered() == 1 && wordsRange.GetStartPos() != 0 && wordsRange.GetStartPos() != m_source.GetSize()-1) {
bool alwaysCreateDirectTranslationOption = StaticData::Instance().IsAlwaysCreateDirectTranslationOption();
if (to.Empty() || alwaysCreateDirectTranslationOption) {
// create unknown words for 1 word coverage where we don't have any trans options
const Word &sourceWord = m_source.GetWord(wordsRange.GetStartPos());
m_unknown.Process(sourceWord, wordsRange, to);
}
}
}
} // namespace Moses
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/win_util.h"
#include <shellapi.h>
#include <windows.h>
#include "chrome/browser/browser_main_win.h"
#include "base/command_line.h"
#include "base/path_service.h"
#include "base/win_util.h"
#include "chrome/browser/first_run.h"
#include "chrome/browser/metrics/metrics_service.h"
#include "chrome/browser/views/uninstall_dialog.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/env_vars.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/message_box_flags.h"
#include "chrome/common/result_codes.h"
#include "chrome/installer/util/helper.h"
#include "chrome/installer/util/install_util.h"
#include "chrome/installer/util/shell_util.h"
#include "chrome/views/controls/message_box_view.h"
#include "chrome/views/widget/accelerator_handler.h"
#include "chrome/views/window/window.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
// Displays a warning message if the user is running chrome on windows 2000.
// Returns true if the OS is win2000, false otherwise.
bool CheckForWin2000() {
if (win_util::GetWinVersion() == win_util::WINVERSION_2000) {
const std::wstring text = l10n_util::GetString(IDS_UNSUPPORTED_OS_WIN2000);
const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME);
win_util::MessageBox(NULL, text, caption,
MB_OK | MB_ICONWARNING | MB_TOPMOST);
return true;
}
return false;
}
int AskForUninstallConfirmation() {
int ret = ResultCodes::NORMAL_EXIT;
UninstallDialog::ShowUninstallDialog(ret);
MessageLoop::current()->Run();
return ret;
}
void ShowCloseBrowserFirstMessageBox() {
const std::wstring text = l10n_util::GetString(IDS_UNINSTALL_CLOSE_APP);
const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME);
const UINT flags = MB_OK | MB_ICONWARNING | MB_TOPMOST;
win_util::MessageBox(NULL, text, caption, flags);
}
int DoUninstallTasks(bool chrome_still_running) {
if (chrome_still_running) {
ShowCloseBrowserFirstMessageBox();
return ResultCodes::UNINSTALL_CHROME_ALIVE;
}
int ret = AskForUninstallConfirmation();
if (ret != ResultCodes::UNINSTALL_USER_CANCEL) {
// The following actions are just best effort.
LOG(INFO) << "Executing uninstall actions";
if (!FirstRun::RemoveSentinel())
LOG(INFO) << "Failed to delete sentinel file.";
// We want to remove user level shortcuts and we only care about the ones
// created by us and not by the installer so |alternate| is false.
if (!ShellUtil::RemoveChromeDesktopShortcut(ShellUtil::CURRENT_USER, false))
LOG(INFO) << "Failed to delete desktop shortcut.";
if (!ShellUtil::RemoveChromeQuickLaunchShortcut(ShellUtil::CURRENT_USER))
LOG(INFO) << "Failed to delete quick launch shortcut.";
}
return ret;
}
// Prepares the localized strings that are going to be displayed to
// the user if the browser process dies. These strings are stored in the
// environment block so they are accessible in the early stages of the
// chrome executable's lifetime.
void PrepareRestartOnCrashEnviroment(const CommandLine &parsed_command_line) {
// Clear this var so child processes don't show the dialog by default.
::SetEnvironmentVariableW(env_vars::kShowRestart, NULL);
// For non-interactive tests we don't restart on crash.
if (::GetEnvironmentVariableW(env_vars::kHeadless, NULL, 0))
return;
// If the known command-line test options are used we don't create the
// environment block which means we don't get the restart dialog.
if (parsed_command_line.HasSwitch(switches::kBrowserCrashTest) ||
parsed_command_line.HasSwitch(switches::kBrowserAssertTest) ||
parsed_command_line.HasSwitch(switches::kNoErrorDialogs))
return;
// The encoding we use for the info is "title|context|direction" where
// direction is either env_vars::kRtlLocale or env_vars::kLtrLocale depending
// on the current locale.
std::wstring dlg_strings;
dlg_strings.append(l10n_util::GetString(IDS_CRASH_RECOVERY_TITLE));
dlg_strings.append(L"|");
dlg_strings.append(l10n_util::GetString(IDS_CRASH_RECOVERY_CONTENT));
dlg_strings.append(L"|");
if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT)
dlg_strings.append(env_vars::kRtlLocale);
else
dlg_strings.append(env_vars::kLtrLocale);
::SetEnvironmentVariableW(env_vars::kRestartInfo, dlg_strings.c_str());
}
// This method handles the --hide-icons and --show-icons command line options
// for chrome that get triggered by Windows from registry entries
// HideIconsCommand & ShowIconsCommand. Chrome doesn't support hide icons
// functionality so we just ask the users if they want to uninstall Chrome.
int HandleIconsCommands(const CommandLine &parsed_command_line) {
if (parsed_command_line.HasSwitch(switches::kHideIcons)) {
std::wstring cp_applet;
win_util::WinVersion version = win_util::GetWinVersion();
if (version >= win_util::WINVERSION_VISTA) {
cp_applet.assign(L"Programs and Features"); // Windows Vista and later.
} else if (version >= win_util::WINVERSION_XP) {
cp_applet.assign(L"Add/Remove Programs"); // Windows XP.
} else {
return ResultCodes::UNSUPPORTED_PARAM; // Not supported
}
const std::wstring msg = l10n_util::GetStringF(IDS_HIDE_ICONS_NOT_SUPPORTED,
cp_applet);
const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME);
const UINT flags = MB_OKCANCEL | MB_ICONWARNING | MB_TOPMOST;
if (IDOK == win_util::MessageBox(NULL, msg, caption, flags))
ShellExecute(NULL, NULL, L"appwiz.cpl", NULL, NULL, SW_SHOWNORMAL);
return ResultCodes::NORMAL_EXIT; // Exit as we are not launching browser.
}
// We don't hide icons so we shouldn't do anything special to show them
return ResultCodes::UNSUPPORTED_PARAM;
}
// Check if there is any machine level Chrome installed on the current
// machine. If yes and the current Chrome process is user level, we do not
// allow the user level Chrome to run. So we notify the user and uninstall
// user level Chrome.
bool CheckMachineLevelInstall() {
scoped_ptr<installer::Version> version(InstallUtil::GetChromeVersion(true));
if (version.get()) {
std::wstring exe;
PathService::Get(base::DIR_EXE, &exe);
std::transform(exe.begin(), exe.end(), exe.begin(), tolower);
std::wstring user_exe_path = installer::GetChromeInstallPath(false);
std::transform(user_exe_path.begin(), user_exe_path.end(),
user_exe_path.begin(), tolower);
if (exe == user_exe_path) {
const std::wstring text =
l10n_util::GetString(IDS_MACHINE_LEVEL_INSTALL_CONFLICT);
const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME);
const UINT flags = MB_OK | MB_ICONERROR | MB_TOPMOST;
win_util::MessageBox(NULL, text, caption, flags);
std::wstring uninstall_cmd = InstallUtil::GetChromeUninstallCmd(false);
if (!uninstall_cmd.empty()) {
uninstall_cmd.append(L" --");
uninstall_cmd.append(installer_util::switches::kForceUninstall);
uninstall_cmd.append(L" --");
uninstall_cmd.append(installer_util::switches::kDoNotRemoveSharedItems);
base::LaunchApp(uninstall_cmd, false, false, NULL);
}
return true;
}
}
return false;
}
bool DoUpgradeTasks(const CommandLine& command_line) {
if (!Upgrade::SwapNewChromeExeIfPresent())
return false;
// At this point the chrome.exe has been swapped with the new one.
if (!Upgrade::RelaunchChromeBrowser(command_line)) {
// The re-launch fails. Feel free to panic now.
NOTREACHED();
}
return true;
}
// We record in UMA the conditions that can prevent breakpad from generating
// and sending crash reports. Namely that the crash reporting registration
// failed and that the process is being debugged.
void RecordBreakpadStatusUMA(MetricsService* metrics) {
DWORD len = ::GetEnvironmentVariableW(env_vars::kNoOOBreakpad, NULL, 0);
metrics->RecordBreakpadRegistration((len == 0));
metrics->RecordBreakpadHasDebugger(TRUE == ::IsDebuggerPresent());
}
<commit_msg>Make uninstall dialog handle keyboard events (TAB).<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/win_util.h"
#include <shellapi.h>
#include <windows.h>
#include "chrome/browser/browser_main_win.h"
#include "base/command_line.h"
#include "base/path_service.h"
#include "base/win_util.h"
#include "chrome/browser/first_run.h"
#include "chrome/browser/metrics/metrics_service.h"
#include "chrome/browser/views/uninstall_dialog.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/env_vars.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/message_box_flags.h"
#include "chrome/common/result_codes.h"
#include "chrome/installer/util/helper.h"
#include "chrome/installer/util/install_util.h"
#include "chrome/installer/util/shell_util.h"
#include "chrome/views/controls/message_box_view.h"
#include "chrome/views/widget/accelerator_handler.h"
#include "chrome/views/window/window.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
// Displays a warning message if the user is running chrome on windows 2000.
// Returns true if the OS is win2000, false otherwise.
bool CheckForWin2000() {
if (win_util::GetWinVersion() == win_util::WINVERSION_2000) {
const std::wstring text = l10n_util::GetString(IDS_UNSUPPORTED_OS_WIN2000);
const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME);
win_util::MessageBox(NULL, text, caption,
MB_OK | MB_ICONWARNING | MB_TOPMOST);
return true;
}
return false;
}
int AskForUninstallConfirmation() {
int ret = ResultCodes::NORMAL_EXIT;
UninstallDialog::ShowUninstallDialog(ret);
MessageLoopForUI::current()->Run(g_browser_process->accelerator_handler());
return ret;
}
void ShowCloseBrowserFirstMessageBox() {
const std::wstring text = l10n_util::GetString(IDS_UNINSTALL_CLOSE_APP);
const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME);
const UINT flags = MB_OK | MB_ICONWARNING | MB_TOPMOST;
win_util::MessageBox(NULL, text, caption, flags);
}
int DoUninstallTasks(bool chrome_still_running) {
if (chrome_still_running) {
ShowCloseBrowserFirstMessageBox();
return ResultCodes::UNINSTALL_CHROME_ALIVE;
}
int ret = AskForUninstallConfirmation();
if (ret != ResultCodes::UNINSTALL_USER_CANCEL) {
// The following actions are just best effort.
LOG(INFO) << "Executing uninstall actions";
if (!FirstRun::RemoveSentinel())
LOG(INFO) << "Failed to delete sentinel file.";
// We want to remove user level shortcuts and we only care about the ones
// created by us and not by the installer so |alternate| is false.
if (!ShellUtil::RemoveChromeDesktopShortcut(ShellUtil::CURRENT_USER, false))
LOG(INFO) << "Failed to delete desktop shortcut.";
if (!ShellUtil::RemoveChromeQuickLaunchShortcut(ShellUtil::CURRENT_USER))
LOG(INFO) << "Failed to delete quick launch shortcut.";
}
return ret;
}
// Prepares the localized strings that are going to be displayed to
// the user if the browser process dies. These strings are stored in the
// environment block so they are accessible in the early stages of the
// chrome executable's lifetime.
void PrepareRestartOnCrashEnviroment(const CommandLine &parsed_command_line) {
// Clear this var so child processes don't show the dialog by default.
::SetEnvironmentVariableW(env_vars::kShowRestart, NULL);
// For non-interactive tests we don't restart on crash.
if (::GetEnvironmentVariableW(env_vars::kHeadless, NULL, 0))
return;
// If the known command-line test options are used we don't create the
// environment block which means we don't get the restart dialog.
if (parsed_command_line.HasSwitch(switches::kBrowserCrashTest) ||
parsed_command_line.HasSwitch(switches::kBrowserAssertTest) ||
parsed_command_line.HasSwitch(switches::kNoErrorDialogs))
return;
// The encoding we use for the info is "title|context|direction" where
// direction is either env_vars::kRtlLocale or env_vars::kLtrLocale depending
// on the current locale.
std::wstring dlg_strings;
dlg_strings.append(l10n_util::GetString(IDS_CRASH_RECOVERY_TITLE));
dlg_strings.append(L"|");
dlg_strings.append(l10n_util::GetString(IDS_CRASH_RECOVERY_CONTENT));
dlg_strings.append(L"|");
if (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT)
dlg_strings.append(env_vars::kRtlLocale);
else
dlg_strings.append(env_vars::kLtrLocale);
::SetEnvironmentVariableW(env_vars::kRestartInfo, dlg_strings.c_str());
}
// This method handles the --hide-icons and --show-icons command line options
// for chrome that get triggered by Windows from registry entries
// HideIconsCommand & ShowIconsCommand. Chrome doesn't support hide icons
// functionality so we just ask the users if they want to uninstall Chrome.
int HandleIconsCommands(const CommandLine &parsed_command_line) {
if (parsed_command_line.HasSwitch(switches::kHideIcons)) {
std::wstring cp_applet;
win_util::WinVersion version = win_util::GetWinVersion();
if (version >= win_util::WINVERSION_VISTA) {
cp_applet.assign(L"Programs and Features"); // Windows Vista and later.
} else if (version >= win_util::WINVERSION_XP) {
cp_applet.assign(L"Add/Remove Programs"); // Windows XP.
} else {
return ResultCodes::UNSUPPORTED_PARAM; // Not supported
}
const std::wstring msg = l10n_util::GetStringF(IDS_HIDE_ICONS_NOT_SUPPORTED,
cp_applet);
const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME);
const UINT flags = MB_OKCANCEL | MB_ICONWARNING | MB_TOPMOST;
if (IDOK == win_util::MessageBox(NULL, msg, caption, flags))
ShellExecute(NULL, NULL, L"appwiz.cpl", NULL, NULL, SW_SHOWNORMAL);
return ResultCodes::NORMAL_EXIT; // Exit as we are not launching browser.
}
// We don't hide icons so we shouldn't do anything special to show them
return ResultCodes::UNSUPPORTED_PARAM;
}
// Check if there is any machine level Chrome installed on the current
// machine. If yes and the current Chrome process is user level, we do not
// allow the user level Chrome to run. So we notify the user and uninstall
// user level Chrome.
bool CheckMachineLevelInstall() {
scoped_ptr<installer::Version> version(InstallUtil::GetChromeVersion(true));
if (version.get()) {
std::wstring exe;
PathService::Get(base::DIR_EXE, &exe);
std::transform(exe.begin(), exe.end(), exe.begin(), tolower);
std::wstring user_exe_path = installer::GetChromeInstallPath(false);
std::transform(user_exe_path.begin(), user_exe_path.end(),
user_exe_path.begin(), tolower);
if (exe == user_exe_path) {
const std::wstring text =
l10n_util::GetString(IDS_MACHINE_LEVEL_INSTALL_CONFLICT);
const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME);
const UINT flags = MB_OK | MB_ICONERROR | MB_TOPMOST;
win_util::MessageBox(NULL, text, caption, flags);
std::wstring uninstall_cmd = InstallUtil::GetChromeUninstallCmd(false);
if (!uninstall_cmd.empty()) {
uninstall_cmd.append(L" --");
uninstall_cmd.append(installer_util::switches::kForceUninstall);
uninstall_cmd.append(L" --");
uninstall_cmd.append(installer_util::switches::kDoNotRemoveSharedItems);
base::LaunchApp(uninstall_cmd, false, false, NULL);
}
return true;
}
}
return false;
}
bool DoUpgradeTasks(const CommandLine& command_line) {
if (!Upgrade::SwapNewChromeExeIfPresent())
return false;
// At this point the chrome.exe has been swapped with the new one.
if (!Upgrade::RelaunchChromeBrowser(command_line)) {
// The re-launch fails. Feel free to panic now.
NOTREACHED();
}
return true;
}
// We record in UMA the conditions that can prevent breakpad from generating
// and sending crash reports. Namely that the crash reporting registration
// failed and that the process is being debugged.
void RecordBreakpadStatusUMA(MetricsService* metrics) {
DWORD len = ::GetEnvironmentVariableW(env_vars::kNoOOBreakpad, NULL, 0);
metrics->RecordBreakpadRegistration((len == 0));
metrics->RecordBreakpadHasDebugger(TRUE == ::IsDebuggerPresent());
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/string_util.h"
#if defined(OS_WIN)
#include "base/win_util.h"
#endif // defined(OS_WIN)
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/browser/net/url_request_failed_dns_job.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "net/url_request/url_request_unittest.h"
class ErrorPageTest : public UITest {
protected:
bool WaitForTitleMatching(const std::wstring& title) {
for (int i = 0; i < 100; ++i) {
if (GetActiveTabTitle() == title)
return true;
PlatformThread::Sleep(sleep_timeout_ms() / 10);
}
EXPECT_EQ(title, GetActiveTabTitle());
return false;
}
};
TEST_F(ErrorPageTest, DNSError_Basic) {
#if defined(OS_WIN)
// Flaky on XP, http://crbug.com/19361.
if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
return;
#endif // defined(OS_WIN)
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
}
TEST_F(ErrorPageTest, DNSError_GoBack1) {
#if defined(OS_WIN)
// Flaky on XP, http://crbug.com/19361.
if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
return;
#endif // defined(OS_WIN)
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoBack());
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
TEST_F(ErrorPageTest, DNSError_GoBack2) {
#if defined(OS_WIN)
// Flaky on XP, http://crbug.com/19361.
if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
return;
#endif // defined(OS_WIN)
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title3.html"))));
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoBack());
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
TEST_F(ErrorPageTest, DNSError_GoBack2AndForward) {
#if defined(OS_WIN)
// Flaky on XP, http://crbug.com/19361.
if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
return;
#endif // defined(OS_WIN)
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title3.html"))));
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoBack());
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoForwardBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
}
TEST_F(ErrorPageTest, DNSError_GoBack2Forward2) {
#if defined(OS_WIN)
// Flaky on XP, http://crbug.com/19361.
if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
return;
#endif // defined(OS_WIN)
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title3.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoBack());
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoForwardBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoForward());
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
TEST_F(ErrorPageTest, IFrameDNSError_Basic) {
#if defined(OS_WIN)
// Flaky on XP, http://crbug.com/19361.
if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
return;
#endif // defined(OS_WIN)
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));
EXPECT_TRUE(WaitForTitleMatching(L"Blah"));
}
TEST_F(ErrorPageTest, IFrameDNSError_GoBack) {
#if defined(OS_WIN)
// Flaky on XP, http://crbug.com/19361.
if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
return;
#endif // defined(OS_WIN)
// Test that a DNS error occuring in an iframe does not result in an
// additional session history entry.
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));
EXPECT_TRUE(GetActiveTab()->GoBack());
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
TEST_F(ErrorPageTest, IFrameDNSError_GoBackAndForward) {
#if defined(OS_WIN)
// Flaky on XP, http://crbug.com/19361.
if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
return;
#endif // defined(OS_WIN)
// Test that a DNS error occuring in an iframe does not result in an
// additional session history entry.
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));
EXPECT_TRUE(GetActiveTab()->GoBack());
EXPECT_TRUE(GetActiveTab()->GoForward());
EXPECT_TRUE(WaitForTitleMatching(L"Blah"));
}
TEST_F(ErrorPageTest, IFrame404) {
#if defined(OS_WIN)
// Flaky on XP, http://crbug.com/19361.
if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
return;
#endif // defined(OS_WIN)
// iframes that have 404 pages should not trigger an alternate error page.
// In this test, the iframe sets the title of the parent page to "SUCCESS"
// when the iframe loads. If the iframe fails to load (because an alternate
// error page loads instead), then the title will remain as "FAIL".
scoped_refptr<HTTPTestServer> server =
HTTPTestServer::CreateServer(L"chrome/test/data", NULL);
ASSERT_TRUE(NULL != server.get());
GURL test_url = server->TestServerPage("files/iframe404.html");
NavigateToURL(test_url);
EXPECT_TRUE(WaitForTitleMatching(L"SUCCESS"));
}
TEST_F(ErrorPageTest, Page404) {
#if defined(OS_WIN)
// Flaky on XP, http://crbug.com/19361.
if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
return;
#endif // defined(OS_WIN)
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(
URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("page404.html"))), 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
}
TEST_F(ErrorPageTest, Page404_GoBack) {
#if defined(OS_WIN)
// Flaky on XP, http://crbug.com/19361.
if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
return;
#endif // defined(OS_WIN)
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(
URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("page404.html"))), 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoBack());
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
<commit_msg>Mark ErrorPageTest.IFrameDNSError_GoBackAndForward as flaky since it failed on Linux.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/string_util.h"
#if defined(OS_WIN)
#include "base/win_util.h"
#endif // defined(OS_WIN)
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/browser/net/url_request_failed_dns_job.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "net/url_request/url_request_unittest.h"
class ErrorPageTest : public UITest {
protected:
bool WaitForTitleMatching(const std::wstring& title) {
for (int i = 0; i < 100; ++i) {
if (GetActiveTabTitle() == title)
return true;
PlatformThread::Sleep(sleep_timeout_ms() / 10);
}
EXPECT_EQ(title, GetActiveTabTitle());
return false;
}
};
TEST_F(ErrorPageTest, DNSError_Basic) {
#if defined(OS_WIN)
// Flaky on XP, http://crbug.com/19361.
if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
return;
#endif // defined(OS_WIN)
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
}
TEST_F(ErrorPageTest, DNSError_GoBack1) {
#if defined(OS_WIN)
// Flaky on XP, http://crbug.com/19361.
if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
return;
#endif // defined(OS_WIN)
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoBack());
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
TEST_F(ErrorPageTest, DNSError_GoBack2) {
#if defined(OS_WIN)
// Flaky on XP, http://crbug.com/19361.
if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
return;
#endif // defined(OS_WIN)
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title3.html"))));
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoBack());
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
TEST_F(ErrorPageTest, DNSError_GoBack2AndForward) {
#if defined(OS_WIN)
// Flaky on XP, http://crbug.com/19361.
if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
return;
#endif // defined(OS_WIN)
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title3.html"))));
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoBack());
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoForwardBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
}
TEST_F(ErrorPageTest, DNSError_GoBack2Forward2) {
#if defined(OS_WIN)
// Flaky on XP, http://crbug.com/19361.
if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
return;
#endif // defined(OS_WIN)
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title3.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoBack());
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoForwardBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoForward());
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
TEST_F(ErrorPageTest, IFrameDNSError_Basic) {
#if defined(OS_WIN)
// Flaky on XP, http://crbug.com/19361.
if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
return;
#endif // defined(OS_WIN)
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));
EXPECT_TRUE(WaitForTitleMatching(L"Blah"));
}
TEST_F(ErrorPageTest, IFrameDNSError_GoBack) {
#if defined(OS_WIN)
// Flaky on XP, http://crbug.com/19361.
if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
return;
#endif // defined(OS_WIN)
// Test that a DNS error occuring in an iframe does not result in an
// additional session history entry.
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));
EXPECT_TRUE(GetActiveTab()->GoBack());
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
// Flaky on Linux too.
TEST_F(ErrorPageTest, FLAKY_IFrameDNSError_GoBackAndForward) {
#if defined(OS_WIN)
// Flaky on XP, http://crbug.com/19361.
if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
return;
#endif // defined(OS_WIN)
// Test that a DNS error occuring in an iframe does not result in an
// additional session history entry.
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));
EXPECT_TRUE(GetActiveTab()->GoBack());
EXPECT_TRUE(GetActiveTab()->GoForward());
EXPECT_TRUE(WaitForTitleMatching(L"Blah"));
}
TEST_F(ErrorPageTest, IFrame404) {
#if defined(OS_WIN)
// Flaky on XP, http://crbug.com/19361.
if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
return;
#endif // defined(OS_WIN)
// iframes that have 404 pages should not trigger an alternate error page.
// In this test, the iframe sets the title of the parent page to "SUCCESS"
// when the iframe loads. If the iframe fails to load (because an alternate
// error page loads instead), then the title will remain as "FAIL".
scoped_refptr<HTTPTestServer> server =
HTTPTestServer::CreateServer(L"chrome/test/data", NULL);
ASSERT_TRUE(NULL != server.get());
GURL test_url = server->TestServerPage("files/iframe404.html");
NavigateToURL(test_url);
EXPECT_TRUE(WaitForTitleMatching(L"SUCCESS"));
}
TEST_F(ErrorPageTest, Page404) {
#if defined(OS_WIN)
// Flaky on XP, http://crbug.com/19361.
if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
return;
#endif // defined(OS_WIN)
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(
URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("page404.html"))), 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
}
TEST_F(ErrorPageTest, Page404_GoBack) {
#if defined(OS_WIN)
// Flaky on XP, http://crbug.com/19361.
if (win_util::GetWinVersion() < win_util::WINVERSION_VISTA)
return;
#endif // defined(OS_WIN)
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(
URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("page404.html"))), 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoBack());
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/string_util.h"
#include "base/test/test_timeouts.h"
#include "base/threading/platform_thread.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/browser/net/url_request_failed_dns_job.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "net/test/test_server.h"
class ErrorPageTest : public UITest {
protected:
bool WaitForTitleMatching(const std::wstring& title) {
for (int i = 0; i < 10; ++i) {
if (GetActiveTabTitle() == title)
return true;
base::PlatformThread::Sleep(TestTimeouts::action_timeout_ms());
}
EXPECT_EQ(title, GetActiveTabTitle());
return false;
}
};
TEST_F(ErrorPageTest, DNSError_Basic) {
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
}
TEST_F(ErrorPageTest, DNSError_GoBack1) {
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoBack());
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
TEST_F(ErrorPageTest, DNSError_GoBack2) {
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title3.html"))));
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoBack());
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
TEST_F(ErrorPageTest, DNSError_GoBack2AndForward) {
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title3.html"))));
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoBack());
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoForwardBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
}
// Flaky on Linux x64, see http://crbug.com/79412
#if defined(OS_LINUX) && defined(ARCH_CPU_64_BITS)
#define MAYBE_DNSError_GoBack2Forward2 FLAKY_DNSError_GoBack2Forward2
#else
#define MAYBE_DNSError_GoBack2Forward2 DNSError_GoBack2Forward2
#endif
TEST_F(ErrorPageTest, DNSError_GoBack2Forward2) {
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title3.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoBack());
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoForwardBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoForward());
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
TEST_F(ErrorPageTest, IFrameDNSError_Basic) {
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));
EXPECT_TRUE(WaitForTitleMatching(L"Blah"));
}
TEST_F(ErrorPageTest, IFrameDNSError_GoBack) {
// Test that a DNS error occuring in an iframe does not result in an
// additional session history entry.
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));
EXPECT_TRUE(GetActiveTab()->GoBack());
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
TEST_F(ErrorPageTest, IFrameDNSError_GoBackAndForward) {
// Test that a DNS error occuring in an iframe does not result in an
// additional session history entry.
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));
EXPECT_TRUE(GetActiveTab()->GoBack());
EXPECT_TRUE(GetActiveTab()->GoForward());
EXPECT_TRUE(WaitForTitleMatching(L"Blah"));
}
// Checks that the Link Doctor is not loaded when we receive an actual 404 page.
TEST_F(ErrorPageTest, Page404) {
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("page404.html"))));
EXPECT_TRUE(WaitForTitleMatching(L"SUCCESS"));
}
<commit_msg>Disable flaky error page tests<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/string_util.h"
#include "base/test/test_timeouts.h"
#include "base/threading/platform_thread.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/browser/net/url_request_failed_dns_job.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "net/test/test_server.h"
class ErrorPageTest : public UITest {
protected:
bool WaitForTitleMatching(const std::wstring& title) {
for (int i = 0; i < 10; ++i) {
if (GetActiveTabTitle() == title)
return true;
base::PlatformThread::Sleep(TestTimeouts::action_timeout_ms());
}
EXPECT_EQ(title, GetActiveTabTitle());
return false;
}
};
TEST_F(ErrorPageTest, DNSError_Basic) {
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
}
TEST_F(ErrorPageTest, DNSError_GoBack1) {
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoBack());
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
// Flaky on Linux, see http://crbug.com/19361
#if defined(OS_LINUX)
#define MAYBE_DNSError_GoBack2 FLAKY_DNSError_GoBack2
#else
#define MAYBE_DNSError_GoBack2 DNSError_GoBack2
#endif
TEST_F(ErrorPageTest, MAYBE_DNSError_GoBack2) {
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title3.html"))));
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoBack());
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
// Flaky on Linux, see http://crbug.com/19361
#if defined(OS_LINUX)
#define MAYBE_DNSError_GoBack2AndForwar FLAKY_DNSError_GoBack2AndForwar
#else
#define MAYBE_DNSError_GoBack2AndForwar DNSError_GoBack2AndForwar
#endif
TEST_F(ErrorPageTest, MAYBE_DNSError_GoBack2AndForward) {
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title3.html"))));
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoBack());
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoForwardBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
}
// Flaky on Linux, see http://crbug.com/19361
#if defined(OS_LINUX)
#define MAYBE_DNSError_GoBack2Forward2 FLAKY_DNSError_GoBack2Forward2
#else
#define MAYBE_DNSError_GoBack2Forward2 DNSError_GoBack2Forward2
#endif
TEST_F(ErrorPageTest, MAYBE_DNSError_GoBack2Forward2) {
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title3.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoBack());
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoForwardBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoForward());
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
TEST_F(ErrorPageTest, IFrameDNSError_Basic) {
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));
EXPECT_TRUE(WaitForTitleMatching(L"Blah"));
}
TEST_F(ErrorPageTest, IFrameDNSError_GoBack) {
// Test that a DNS error occuring in an iframe does not result in an
// additional session history entry.
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));
EXPECT_TRUE(GetActiveTab()->GoBack());
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
TEST_F(ErrorPageTest, IFrameDNSError_GoBackAndForward) {
// Test that a DNS error occuring in an iframe does not result in an
// additional session history entry.
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));
EXPECT_TRUE(GetActiveTab()->GoBack());
EXPECT_TRUE(GetActiveTab()->GoForward());
EXPECT_TRUE(WaitForTitleMatching(L"Blah"));
}
// Checks that the Link Doctor is not loaded when we receive an actual 404 page.
TEST_F(ErrorPageTest, Page404) {
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("page404.html"))));
EXPECT_TRUE(WaitForTitleMatching(L"SUCCESS"));
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/gtk/tabs/tab_gtk.h"
#include <gdk/gdkkeysyms.h>
#include "app/gtk_dnd_util.h"
#include "app/gfx/path.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "chrome/browser/gtk/menu_gtk.h"
#include "chrome/browser/gtk/standard_menus.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
namespace {
// Returns the width of the title for the current font, in pixels.
int GetTitleWidth(gfx::Font* font, std::wstring title) {
DCHECK(font);
if (title.empty())
return 0;
return font->GetStringWidth(title);
}
} // namespace
class TabGtk::ContextMenuController : public MenuGtk::Delegate {
public:
explicit ContextMenuController(TabGtk* tab)
: tab_(tab) {
static const MenuCreateMaterial context_menu_blueprint[] = {
{ MENU_NORMAL, TabStripModel::CommandNewTab, IDS_TAB_CXMENU_NEWTAB,
0, NULL, GDK_t, GDK_CONTROL_MASK, true },
{ MENU_SEPARATOR },
{ MENU_NORMAL, TabStripModel::CommandReload, IDS_TAB_CXMENU_RELOAD,
0, NULL, GDK_r, GDK_CONTROL_MASK, true },
{ MENU_NORMAL, TabStripModel::CommandDuplicate,
IDS_TAB_CXMENU_DUPLICATE },
{ MENU_CHECKBOX, TabStripModel::CommandTogglePinned,
IDS_TAB_CXMENU_PIN_TAB },
{ MENU_SEPARATOR },
{ MENU_NORMAL, TabStripModel::CommandCloseTab, IDS_TAB_CXMENU_CLOSETAB,
0, NULL, GDK_w, GDK_CONTROL_MASK, true },
{ MENU_NORMAL, TabStripModel::CommandCloseOtherTabs,
IDS_TAB_CXMENU_CLOSEOTHERTABS },
{ MENU_NORMAL, TabStripModel::CommandCloseTabsToRight,
IDS_TAB_CXMENU_CLOSETABSTORIGHT },
{ MENU_NORMAL, TabStripModel::CommandCloseTabsOpenedBy,
IDS_TAB_CXMENU_CLOSETABSOPENEDBY },
{ MENU_SEPARATOR },
{ MENU_NORMAL, TabStripModel::CommandRestoreTab, IDS_RESTORE_TAB,
0, NULL, GDK_t, GDK_CONTROL_MASK | GDK_SHIFT_MASK, true },
{ MENU_NORMAL, TabStripModel::CommandBookmarkAllTabs,
IDS_TAB_CXMENU_BOOKMARK_ALL_TABS, 0, NULL, GDK_d,
GDK_CONTROL_MASK | GDK_SHIFT_MASK, true },
{ MENU_END },
};
menu_.reset(new MenuGtk(this, context_menu_blueprint, NULL));
}
virtual ~ContextMenuController() {}
void RunMenu() {
menu_->PopupAsContext(gtk_get_current_event_time());
}
void Cancel() {
tab_ = NULL;
menu_->Cancel();
}
private:
// MenuGtk::Delegate implementation:
virtual bool IsCommandEnabled(int command_id) const {
if (!tab_)
return false;
return tab_->delegate()->IsCommandEnabledForTab(
static_cast<TabStripModel::ContextMenuCommand>(command_id), tab_);
}
virtual bool IsItemChecked(int command_id) const {
if (!tab_ || command_id != TabStripModel::CommandTogglePinned)
return false;
return tab_->is_pinned();
}
virtual void ExecuteCommand(int command_id) {
if (!tab_)
return;
tab_->delegate()->ExecuteCommandForTab(
static_cast<TabStripModel::ContextMenuCommand>(command_id), tab_);
}
// The context menu.
scoped_ptr<MenuGtk> menu_;
// The Tab the context menu was brought up for. Set to NULL when the menu
// is canceled.
TabGtk* tab_;
DISALLOW_COPY_AND_ASSIGN(ContextMenuController);
};
///////////////////////////////////////////////////////////////////////////////
// TabGtk, public:
TabGtk::TabGtk(TabDelegate* delegate)
: TabRendererGtk(delegate->GetThemeProvider()),
delegate_(delegate),
closing_(false),
last_mouse_down_(NULL),
drag_widget_(NULL),
title_width_(0),
ALLOW_THIS_IN_INITIALIZER_LIST(destroy_factory_(this)) {
event_box_ = gtk_event_box_new();
gtk_event_box_set_visible_window(GTK_EVENT_BOX(event_box_), FALSE);
g_signal_connect(G_OBJECT(event_box_), "button-press-event",
G_CALLBACK(OnButtonPressEvent), this);
g_signal_connect(G_OBJECT(event_box_), "button-release-event",
G_CALLBACK(OnButtonReleaseEvent), this);
g_signal_connect(G_OBJECT(event_box_), "enter-notify-event",
G_CALLBACK(OnEnterNotifyEvent), this);
g_signal_connect(G_OBJECT(event_box_), "leave-notify-event",
G_CALLBACK(OnLeaveNotifyEvent), this);
gtk_widget_add_events(event_box_,
GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK |
GDK_LEAVE_NOTIFY_MASK | GDK_LEAVE_NOTIFY_MASK);
gtk_container_add(GTK_CONTAINER(event_box_), TabRendererGtk::widget());
gtk_widget_show_all(event_box_);
}
TabGtk::~TabGtk() {
if (menu_controller_.get()) {
// The menu is showing. Close the menu.
menu_controller_->Cancel();
// Invoke this so that we hide the highlight.
ContextMenuClosed();
}
}
// static
gboolean TabGtk::OnButtonPressEvent(GtkWidget* widget, GdkEventButton* event,
TabGtk* tab) {
// Every button press ensures either a button-release-event or a drag-fail
// signal for |widget|.
if (event->button == 1 && event->type == GDK_BUTTON_PRESS) {
// Store whether or not we were selected just now... we only want to be
// able to drag foreground tabs, so we don't start dragging the tab if
// it was in the background.
bool just_selected = !tab->IsSelected();
if (just_selected) {
tab->delegate_->SelectTab(tab);
}
// Hook into the message loop to handle dragging.
MessageLoopForUI::current()->AddObserver(tab);
// Store the button press event, used to initiate a drag.
tab->last_mouse_down_ = gdk_event_copy(reinterpret_cast<GdkEvent*>(event));
} else if (event->button == 3) {
tab->ShowContextMenu();
}
return TRUE;
}
// static
gboolean TabGtk::OnButtonReleaseEvent(GtkWidget* widget, GdkEventButton* event,
TabGtk* tab) {
if (event->button == 1) {
MessageLoopForUI::current()->RemoveObserver(tab);
if (tab->last_mouse_down_) {
gdk_event_free(tab->last_mouse_down_);
tab->last_mouse_down_ = NULL;
}
}
// Middle mouse up means close the tab, but only if the mouse is over it
// (like a button).
if (event->button == 2 &&
event->x >= 0 && event->y >= 0 &&
event->x < widget->allocation.width &&
event->y < widget->allocation.height) {
tab->delegate_->CloseTab(tab);
}
return TRUE;
}
// static
gboolean TabGtk::OnDragFailed(GtkWidget* widget, GdkDragContext* context,
GtkDragResult result,
TabGtk* tab) {
bool canceled = (result == GTK_DRAG_RESULT_USER_CANCELLED);
tab->EndDrag(canceled);
return TRUE;
}
// static
void TabGtk::OnDragBegin(GtkWidget* widget, GdkDragContext* context,
TabGtk* tab) {
GdkPixbuf* pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8, 1, 1);
gtk_drag_set_icon_pixbuf(context, pixbuf, 0, 0);
g_object_unref(pixbuf);
}
///////////////////////////////////////////////////////////////////////////////
// TabGtk, MessageLoop::Observer implementation:
void TabGtk::WillProcessEvent(GdkEvent* event) {
// Nothing to do.
}
void TabGtk::DidProcessEvent(GdkEvent* event) {
if (!(event->type == GDK_MOTION_NOTIFY || event->type == GDK_LEAVE_NOTIFY ||
event->type == GDK_ENTER_NOTIFY)) {
return;
}
if (drag_widget_) {
delegate_->ContinueDrag(NULL);
return;
}
gint old_x = static_cast<gint>(last_mouse_down_->button.x_root);
gint old_y = static_cast<gint>(last_mouse_down_->button.y_root);
gdouble new_x;
gdouble new_y;
gdk_event_get_root_coords(event, &new_x, &new_y);
if (gtk_drag_check_threshold(widget(), old_x, old_y,
static_cast<gint>(new_x), static_cast<gint>(new_y))) {
StartDragging(gfx::Point(
static_cast<int>(last_mouse_down_->button.x),
static_cast<int>(last_mouse_down_->button.y)));
}
}
///////////////////////////////////////////////////////////////////////////////
// TabGtk, TabRendererGtk overrides:
bool TabGtk::IsSelected() const {
return delegate_->IsTabSelected(this);
}
bool TabGtk::IsVisible() const {
return GTK_WIDGET_FLAGS(event_box_) & GTK_VISIBLE;
}
void TabGtk::SetVisible(bool visible) const {
if (visible) {
gtk_widget_show(event_box_);
} else {
gtk_widget_hide(event_box_);
}
}
void TabGtk::CloseButtonClicked() {
delegate_->CloseTab(this);
}
void TabGtk::UpdateData(TabContents* contents, bool loading_only) {
TabRendererGtk::UpdateData(contents, loading_only);
// Cache the title width so we don't recalculate it every time the tab is
// resized.
title_width_ = GetTitleWidth(title_font(), GetTitle());
UpdateTooltipState();
}
void TabGtk::SetBounds(const gfx::Rect& bounds) {
TabRendererGtk::SetBounds(bounds);
UpdateTooltipState();
}
///////////////////////////////////////////////////////////////////////////////
// TabGtk, private:
void TabGtk::ShowContextMenu() {
if (!menu_controller_.get())
menu_controller_.reset(new ContextMenuController(this));
menu_controller_->RunMenu();
}
void TabGtk::ContextMenuClosed() {
delegate()->StopAllHighlighting();
menu_controller_.reset();
}
void TabGtk::UpdateTooltipState() {
// Only show the tooltip if the title is truncated.
if (title_width_ > title_bounds().width()) {
gtk_widget_set_tooltip_text(widget(), WideToUTF8(GetTitle()).c_str());
} else {
gtk_widget_set_has_tooltip(widget(), FALSE);
}
}
void TabGtk::CreateDragWidget() {
drag_widget_ = gtk_invisible_new();
g_signal_connect(drag_widget_, "drag-failed",
G_CALLBACK(OnDragFailed), this);
g_signal_connect_after(drag_widget_, "drag-begin",
G_CALLBACK(OnDragBegin), this);
}
void TabGtk::DestroyDragWidget() {
if (drag_widget_) {
gtk_widget_destroy(drag_widget_);
drag_widget_ = NULL;
}
}
void TabGtk::StartDragging(gfx::Point drag_offset) {
CreateDragWidget();
GtkTargetList* list = GtkDndUtil::GetTargetListFromCodeMask(
GtkDndUtil::CHROME_TAB);
gtk_drag_begin(drag_widget_, list, GDK_ACTION_COPY,
1, // Drags are always initiated by the left button.
last_mouse_down_);
delegate_->MaybeStartDrag(this, drag_offset);
}
void TabGtk::EndDrag(bool canceled) {
// We must let gtk clean up after we handle the drag operation, otherwise
// there will be outstanding references to the drag widget when we try to
// destroy it.
MessageLoop::current()->PostTask(FROM_HERE,
destroy_factory_.NewRunnableMethod(&TabGtk::DestroyDragWidget));
if (last_mouse_down_) {
gdk_event_free(last_mouse_down_);
last_mouse_down_ = NULL;
}
// Notify the drag helper that we're done with any potential drag operations.
// Clean up the drag helper, which is re-created on the next mouse press.
delegate_->EndDrag(canceled);
MessageLoopForUI::current()->RemoveObserver(this);
}
<commit_msg>If we're in the middle of a drag, don't allow the user to middle click to close or right click for the context menu.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/gtk/tabs/tab_gtk.h"
#include <gdk/gdkkeysyms.h>
#include "app/gtk_dnd_util.h"
#include "app/gfx/path.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "chrome/browser/gtk/menu_gtk.h"
#include "chrome/browser/gtk/standard_menus.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
namespace {
// Returns the width of the title for the current font, in pixels.
int GetTitleWidth(gfx::Font* font, std::wstring title) {
DCHECK(font);
if (title.empty())
return 0;
return font->GetStringWidth(title);
}
} // namespace
class TabGtk::ContextMenuController : public MenuGtk::Delegate {
public:
explicit ContextMenuController(TabGtk* tab)
: tab_(tab) {
static const MenuCreateMaterial context_menu_blueprint[] = {
{ MENU_NORMAL, TabStripModel::CommandNewTab, IDS_TAB_CXMENU_NEWTAB,
0, NULL, GDK_t, GDK_CONTROL_MASK, true },
{ MENU_SEPARATOR },
{ MENU_NORMAL, TabStripModel::CommandReload, IDS_TAB_CXMENU_RELOAD,
0, NULL, GDK_r, GDK_CONTROL_MASK, true },
{ MENU_NORMAL, TabStripModel::CommandDuplicate,
IDS_TAB_CXMENU_DUPLICATE },
{ MENU_CHECKBOX, TabStripModel::CommandTogglePinned,
IDS_TAB_CXMENU_PIN_TAB },
{ MENU_SEPARATOR },
{ MENU_NORMAL, TabStripModel::CommandCloseTab, IDS_TAB_CXMENU_CLOSETAB,
0, NULL, GDK_w, GDK_CONTROL_MASK, true },
{ MENU_NORMAL, TabStripModel::CommandCloseOtherTabs,
IDS_TAB_CXMENU_CLOSEOTHERTABS },
{ MENU_NORMAL, TabStripModel::CommandCloseTabsToRight,
IDS_TAB_CXMENU_CLOSETABSTORIGHT },
{ MENU_NORMAL, TabStripModel::CommandCloseTabsOpenedBy,
IDS_TAB_CXMENU_CLOSETABSOPENEDBY },
{ MENU_SEPARATOR },
{ MENU_NORMAL, TabStripModel::CommandRestoreTab, IDS_RESTORE_TAB,
0, NULL, GDK_t, GDK_CONTROL_MASK | GDK_SHIFT_MASK, true },
{ MENU_NORMAL, TabStripModel::CommandBookmarkAllTabs,
IDS_TAB_CXMENU_BOOKMARK_ALL_TABS, 0, NULL, GDK_d,
GDK_CONTROL_MASK | GDK_SHIFT_MASK, true },
{ MENU_END },
};
menu_.reset(new MenuGtk(this, context_menu_blueprint, NULL));
}
virtual ~ContextMenuController() {}
void RunMenu() {
menu_->PopupAsContext(gtk_get_current_event_time());
}
void Cancel() {
tab_ = NULL;
menu_->Cancel();
}
private:
// MenuGtk::Delegate implementation:
virtual bool IsCommandEnabled(int command_id) const {
if (!tab_)
return false;
return tab_->delegate()->IsCommandEnabledForTab(
static_cast<TabStripModel::ContextMenuCommand>(command_id), tab_);
}
virtual bool IsItemChecked(int command_id) const {
if (!tab_ || command_id != TabStripModel::CommandTogglePinned)
return false;
return tab_->is_pinned();
}
virtual void ExecuteCommand(int command_id) {
if (!tab_)
return;
tab_->delegate()->ExecuteCommandForTab(
static_cast<TabStripModel::ContextMenuCommand>(command_id), tab_);
}
// The context menu.
scoped_ptr<MenuGtk> menu_;
// The Tab the context menu was brought up for. Set to NULL when the menu
// is canceled.
TabGtk* tab_;
DISALLOW_COPY_AND_ASSIGN(ContextMenuController);
};
///////////////////////////////////////////////////////////////////////////////
// TabGtk, public:
TabGtk::TabGtk(TabDelegate* delegate)
: TabRendererGtk(delegate->GetThemeProvider()),
delegate_(delegate),
closing_(false),
last_mouse_down_(NULL),
drag_widget_(NULL),
title_width_(0),
ALLOW_THIS_IN_INITIALIZER_LIST(destroy_factory_(this)) {
event_box_ = gtk_event_box_new();
gtk_event_box_set_visible_window(GTK_EVENT_BOX(event_box_), FALSE);
g_signal_connect(G_OBJECT(event_box_), "button-press-event",
G_CALLBACK(OnButtonPressEvent), this);
g_signal_connect(G_OBJECT(event_box_), "button-release-event",
G_CALLBACK(OnButtonReleaseEvent), this);
g_signal_connect(G_OBJECT(event_box_), "enter-notify-event",
G_CALLBACK(OnEnterNotifyEvent), this);
g_signal_connect(G_OBJECT(event_box_), "leave-notify-event",
G_CALLBACK(OnLeaveNotifyEvent), this);
gtk_widget_add_events(event_box_,
GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK |
GDK_LEAVE_NOTIFY_MASK | GDK_LEAVE_NOTIFY_MASK);
gtk_container_add(GTK_CONTAINER(event_box_), TabRendererGtk::widget());
gtk_widget_show_all(event_box_);
}
TabGtk::~TabGtk() {
if (menu_controller_.get()) {
// The menu is showing. Close the menu.
menu_controller_->Cancel();
// Invoke this so that we hide the highlight.
ContextMenuClosed();
}
}
// static
gboolean TabGtk::OnButtonPressEvent(GtkWidget* widget, GdkEventButton* event,
TabGtk* tab) {
// Every button press ensures either a button-release-event or a drag-fail
// signal for |widget|.
if (event->button == 1 && event->type == GDK_BUTTON_PRESS) {
// Store whether or not we were selected just now... we only want to be
// able to drag foreground tabs, so we don't start dragging the tab if
// it was in the background.
bool just_selected = !tab->IsSelected();
if (just_selected) {
tab->delegate_->SelectTab(tab);
}
// Hook into the message loop to handle dragging.
MessageLoopForUI::current()->AddObserver(tab);
// Store the button press event, used to initiate a drag.
tab->last_mouse_down_ = gdk_event_copy(reinterpret_cast<GdkEvent*>(event));
} else if (event->button == 3) {
// Only show the context menu if the left mouse button isn't down (i.e.,
// the user might want to drag instead).
if (!tab->last_mouse_down_)
tab->ShowContextMenu();
}
return TRUE;
}
// static
gboolean TabGtk::OnButtonReleaseEvent(GtkWidget* widget, GdkEventButton* event,
TabGtk* tab) {
if (event->button == 1) {
MessageLoopForUI::current()->RemoveObserver(tab);
if (tab->last_mouse_down_) {
gdk_event_free(tab->last_mouse_down_);
tab->last_mouse_down_ = NULL;
}
}
// Middle mouse up means close the tab, but only if the mouse is over it
// (like a button).
if (event->button == 2 &&
event->x >= 0 && event->y >= 0 &&
event->x < widget->allocation.width &&
event->y < widget->allocation.height) {
// If the user is currently holding the left mouse button down but hasn't
// moved the mouse yet, a drag hasn't started yet. In that case, clean up
// some state before closing the tab to avoid a crash. Once the drag has
// started, we don't get the middle mouse click here.
if (tab->last_mouse_down_) {
DCHECK(!tab->drag_widget_);
MessageLoopForUI::current()->RemoveObserver(tab);
gdk_event_free(tab->last_mouse_down_);
tab->last_mouse_down_ = NULL;
}
tab->delegate_->CloseTab(tab);
}
return TRUE;
}
// static
gboolean TabGtk::OnDragFailed(GtkWidget* widget, GdkDragContext* context,
GtkDragResult result,
TabGtk* tab) {
bool canceled = (result == GTK_DRAG_RESULT_USER_CANCELLED);
tab->EndDrag(canceled);
return TRUE;
}
// static
void TabGtk::OnDragBegin(GtkWidget* widget, GdkDragContext* context,
TabGtk* tab) {
GdkPixbuf* pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8, 1, 1);
gtk_drag_set_icon_pixbuf(context, pixbuf, 0, 0);
g_object_unref(pixbuf);
}
///////////////////////////////////////////////////////////////////////////////
// TabGtk, MessageLoop::Observer implementation:
void TabGtk::WillProcessEvent(GdkEvent* event) {
// Nothing to do.
}
void TabGtk::DidProcessEvent(GdkEvent* event) {
if (!(event->type == GDK_MOTION_NOTIFY || event->type == GDK_LEAVE_NOTIFY ||
event->type == GDK_ENTER_NOTIFY)) {
return;
}
if (drag_widget_) {
delegate_->ContinueDrag(NULL);
return;
}
gint old_x = static_cast<gint>(last_mouse_down_->button.x_root);
gint old_y = static_cast<gint>(last_mouse_down_->button.y_root);
gdouble new_x;
gdouble new_y;
gdk_event_get_root_coords(event, &new_x, &new_y);
if (gtk_drag_check_threshold(widget(), old_x, old_y,
static_cast<gint>(new_x), static_cast<gint>(new_y))) {
StartDragging(gfx::Point(
static_cast<int>(last_mouse_down_->button.x),
static_cast<int>(last_mouse_down_->button.y)));
}
}
///////////////////////////////////////////////////////////////////////////////
// TabGtk, TabRendererGtk overrides:
bool TabGtk::IsSelected() const {
return delegate_->IsTabSelected(this);
}
bool TabGtk::IsVisible() const {
return GTK_WIDGET_FLAGS(event_box_) & GTK_VISIBLE;
}
void TabGtk::SetVisible(bool visible) const {
if (visible) {
gtk_widget_show(event_box_);
} else {
gtk_widget_hide(event_box_);
}
}
void TabGtk::CloseButtonClicked() {
delegate_->CloseTab(this);
}
void TabGtk::UpdateData(TabContents* contents, bool loading_only) {
TabRendererGtk::UpdateData(contents, loading_only);
// Cache the title width so we don't recalculate it every time the tab is
// resized.
title_width_ = GetTitleWidth(title_font(), GetTitle());
UpdateTooltipState();
}
void TabGtk::SetBounds(const gfx::Rect& bounds) {
TabRendererGtk::SetBounds(bounds);
UpdateTooltipState();
}
///////////////////////////////////////////////////////////////////////////////
// TabGtk, private:
void TabGtk::ShowContextMenu() {
if (!menu_controller_.get())
menu_controller_.reset(new ContextMenuController(this));
menu_controller_->RunMenu();
}
void TabGtk::ContextMenuClosed() {
delegate()->StopAllHighlighting();
menu_controller_.reset();
}
void TabGtk::UpdateTooltipState() {
// Only show the tooltip if the title is truncated.
if (title_width_ > title_bounds().width()) {
gtk_widget_set_tooltip_text(widget(), WideToUTF8(GetTitle()).c_str());
} else {
gtk_widget_set_has_tooltip(widget(), FALSE);
}
}
void TabGtk::CreateDragWidget() {
drag_widget_ = gtk_invisible_new();
g_signal_connect(drag_widget_, "drag-failed",
G_CALLBACK(OnDragFailed), this);
g_signal_connect_after(drag_widget_, "drag-begin",
G_CALLBACK(OnDragBegin), this);
}
void TabGtk::DestroyDragWidget() {
if (drag_widget_) {
gtk_widget_destroy(drag_widget_);
drag_widget_ = NULL;
}
}
void TabGtk::StartDragging(gfx::Point drag_offset) {
CreateDragWidget();
GtkTargetList* list = GtkDndUtil::GetTargetListFromCodeMask(
GtkDndUtil::CHROME_TAB);
gtk_drag_begin(drag_widget_, list, GDK_ACTION_COPY,
1, // Drags are always initiated by the left button.
last_mouse_down_);
delegate_->MaybeStartDrag(this, drag_offset);
}
void TabGtk::EndDrag(bool canceled) {
// We must let gtk clean up after we handle the drag operation, otherwise
// there will be outstanding references to the drag widget when we try to
// destroy it.
MessageLoop::current()->PostTask(FROM_HERE,
destroy_factory_.NewRunnableMethod(&TabGtk::DestroyDragWidget));
if (last_mouse_down_) {
gdk_event_free(last_mouse_down_);
last_mouse_down_ = NULL;
}
// Notify the drag helper that we're done with any potential drag operations.
// Clean up the drag helper, which is re-created on the next mouse press.
delegate_->EndDrag(canceled);
MessageLoopForUI::current()->RemoveObserver(this);
}
<|endoftext|> |
<commit_before>#include "Arduino.h"
#include "i2c_t3.h"
#define combine(high,low) ( ( (uint16_t)(high << 8) ) | (uint16_t)(low) )
#define lowbyte(value) ( (uint8_t)(value) )
#define highbyte(value) ( (uint8_t)(value>>8) )
#define MaxChannels 4
#define InternalReference 2.5f
#define DefaultAddress 40
#define VoltageReferenceChannel 3
#define I2CTimeout 1000;
using namespace std;
enum class sampleDelayMode{Unknown, On, Off};
enum class i2CFilterMode{Unknown, On, Off};
enum class referenceMode{Unknown, Supply, External};
class AD7991
{
public:
AD7991();
~AD7991();
bool isConnected();
uint8_t getAddress();
void setAddress(uint8_t address);
float getVoltageSingle(uint8_t Channel);
float* getVoltageMultiple(uint8_t DACsToUse);
float* getVoltageSingleRepeat(uint8_t Channel, size_t NumberOfRepeats);
float* getVoltageMultipleRepeat(uint8_t DACsToUse, size_t NumberOfRepeats);
uint16_t getVoltageSingleInt(uint8_t Channel);
uint16_t* getVoltageMultipleInt(uint8_t DACsToUse);
uint16_t* getVoltageSingleRepeatInt(uint8_t Channel, size_t NumberOfRepeats);
uint16_t* getVoltageMultipleRepeatInt(uint8_t DACsToUse, size_t NumberOfRepeats);
bool setI2CFilter(i2CFilterMode ModeSetting);
i2CFilterMode getI2CFilter();
bool setSampleDelayMode(sampleDelayMode ModeSetting);
sampleDelayMode getSampleDelayMode();
bool setReference(referenceMode ModeSetting);
referenceMode getReference();
void setVRefExt(float VRef);
float getVRefExt();
private:
uint8_t Address;
referenceMode ReferenceMode;
i2CFilterMode I2CFilterMode;
sampleDelayMode SampleDelayMode;
uint8_t DACsActive;
uint8_t ConfigByte;
uint8_t PriorConfigByte;
uint8_t MSBByte;
uint8_t LSBByte;
bool NeedToUpdateConfigByte;
const uint8_t VRefChannel = VoltageReferenceChannel;
const float VRefInt = InternalReference;
float VRefExt;
};
AD7991::AD7991()
{
I2CFilterMode = i2CFilterMode::On;
ReferenceMode = referenceMode::Supply;
SampleDelayMode = sampleDelayMode::On;
NeedToUpdateConfigByte = true;
Address = DefaultAddress;
}
AD7991::~AD7991()
{
}
uint8_t AD7991::getAddress()
{
return Address;
}
void AD7991::setAddress(uint8_t address)
{
Address = address;
}
bool AD7991::isConnected()
{
int Status = 5;
Wire.beginTransmission(Address);
Status = Wire.endTransmission();
if (Status == 0)
{
return true;
}
else
{
return false;
}
}
float AD7991::getVoltageSingle(uint8_t Channel)
{
UpdateChannelSingle(Channel);
}
float* AD7991::getVoltageMultiple(uint8_t DACsToUse)
{
uint8_t NumberOfChannelsToUse = UpdateChannelDACsActive(uint8_t NewDACsActive);
}
float* AD7991::getVoltageSingleRepeat(uint8_t Channel, size_t NumberOfRepeats)
{
UpdateChannelSingle(Channel);
}
float* AD7991::getVoltageMultipleRepeat(uint8_t DACsToUse, size_t NumberOfRepeats)
{
uint8_t NumberOfChannelsToUse = UpdateChannelDACsActive(uint8_t NewDACsActive);
}
uint16_t AD7991::getVoltageSingleInt(uint8_t Channel)
{
UpdateChannelSingle(Channel);
}
uint16_t* AD7991::getVoltageMultipleInt(uint8_t DACsToUse)
{
uint8_t NumberOfChannelsToUse = UpdateChannelDACsActive(uint8_t NewDACsActive);
}
uint16_t* AD7991::getVoltageSingleRepeatInt(uint8_t Channel, size_t NumberOfRepeats)
{
UpdateChannelSingle(Channel);
}
uint16_t* AD7991::getVoltageMultipleRepeatInt(uint8_t DACsToUse, size_t NumberOfRepeats)
{
uint8_t NumberOfChannelsToUse = UpdateChannelDACsActive(uint8_t NewDACsActive);
}
bool AD7991::setI2CFilter(i2CFilterMode ModeSetting)
{
if (ModeSetting != I2CFilterMode)
{
I2CFilterMode = ModeSetting;
NeedToUpdateConfigByte = true;
}
}
i2CFilterMode AD7991::getI2CFilter()
{
return I2CFilterMode;
}
bool AD7991::setSampleDelayMode(sampleDelayMode ModeSetting)
{
if (ModeSetting != SampleDelayMode)
{
SampleDelayMode = ModeSetting;
NeedToUpdateConfigByte = true;
}
}
sampleDelayMode AD7991::getSampleDelayMode()
{
return SampleDelayMode;
}
bool AD7991::setOutputMode(outputMode ModeSetting)
{
}
outputMode AD7991::getOutputMode()
{
return OutputMode;
}
bool AD7991::setReference(referenceMode ModeSetting)
{
if (ModeSetting != ReferenceMode)
{
ReferenceMode = ModeSetting;
NeedToUpdateConfigByte = true;
}
}
referenceMode AD7991::getReference()
{
return ReferenceMode;
}
void AD7991::setVRefExt(float VRef)
{
VRefExt = Vref;
}
float AD7991::getVRefExt()
{
return VRefExt;
}
void AD7991::UpdateChannelSingle(uint8_t Channel)
{
uint8_t NewDACsActive = 0;
Channel = CheckChannel(Channel);
bitWrite(NewDACsActive, Channel, 1);
if ( (NewDACsActive != DACsActive) | NeedToUpdateConfigByte)
{
NeedToUpdateConfigByte = true;
DACsActive = NewDACsActive;
UpdateConfigByte();
}
}
uint8_t AD7991::UpdateChannelDACsActive(uint8_t NewDACsActive)
{
if (bitRead(NewDACsActive,VRefChannel) & (ReferenceMode == referenceMode::External))
{
Serial.println("Can not use external reference with VRef channel on AD799X.");
bitWrite(NewDACsActive,VRefChannel,0);
}
if ( (NewDACsActive != DACsActive) | NeedToUpdateConfigByte)
{
NeedToUpdateConfigByte = true;
DACsActive = NewDACsActive;
UpdateConfigByte();
}
return (uint8_t)(bitRead(DACsActive,0) + bitRead(DACsActive,1) + bitRead(DACsActive,2) + bitRead(DACsActive,3));
}
uint8_t AD7991::CheckChannel(uint8_t Channel)
{
Channel = constrain(Channel,0,NumberOfChannels);
if (Channel == VRefChannel)
{
if (ReferenceMode::External)
{
Serial.println("Can not use external reference with VRef channel on AD799X.");
return VRefChannel-1;
}
}
return Channel;
}
void AD7991::UpdateConfigByte()
{
if (NeedToUpdateConfigByte)
{
SetConfigByte();
SendI2C();
NeedToUpdateConfigByte = false;
}
}
void AD7991::SetConfigByte()
{
ConfigByte = DACsActive << 4;
switch(ReferenceMode)
{
case referenceMode::External:
bitWrite(ConfigByte,3,1);
break;
case referenceMode::Supply:
case referenceMode::Unknown:
case default:
break;
}
switch(I2CFilterMode)
{
case i2CFilterMode::Off:
bitWrite(ConfigByte,2,1);
break;
case i2CFilterMode::On:
case i2CFilterMode::Unknown:
case default:
break;
}
switch(SampleDelayMode)
{
case sampleDelayMode::Off:
bitWrite(ConfigByte,1,1);
bitWrite(ConfigByte,0,1);
break;
case sampleDelayMode::On:
case sampleDelayMode::Unknown:
case default:
break;
}
}
void AD7991::SendI2C()
{
bool MoveOn = false;
const int MaxAttempts = 16;
int CurrentAttempt = 0;
int SendSuccess = 5;
while (!MoveOn)
{
Wire.beginTransmission(Address);
Wire.write(ConfigByte);
SendSuccess = Wire.endTransmission(I2C_STOP, I2CTimeout);
if(SendSuccess != 0)
{
Wire.finish();
Wire.resetBus();
CurrentAttempt++;
if (CurrentAttempt > MaxAttempts)
{
MoveOn = true;
Serial.println("Unrecoverable I2C transmission error with AD799X.");
}
}
else
{
MoveOn = true;
}
}
}
void AD7991::RecieveI2CInt(size_t NumberOfSamples)
{
if(NumberOfSamples > 0)
{
Wire.requestFrom(Address, 2*NumberOfSamples, I2C_STOP, I2CTimeout*2*NumberOfSamples);
int BytesToCollect = Wire.available();
for (int RecieveByteNumber=0; RecieveByteNumber < BytesToCollect; RecieveByteNumber++)
{
if(RecieveByteNumber<I2CRecieveBufferSize)
{
I2CRecieveBuffer[RecieveByteNumber] = Wire.readByte();
}
else
{
Wire.readByte();
}
}
}
}
void AD7991::RecieveI2CFloat(size_t NumberOfSamples)
{
if(NumberOfSamples > 0)
{
Wire.requestFrom(Address, 2*NumberOfSamples, I2C_STOP, I2CTimeout*2*NumberOfSamples);
int BytesToCollect = Wire.available();
for (int RecieveByteNumber=0; RecieveByteNumber < BytesToCollect; RecieveByteNumber++)
{
if(RecieveByteNumber<I2CRecieveBufferSize)
{
I2CRecieveBuffer[RecieveByteNumber] = Wire.readByte();
}
else
{
Wire.readByte();
}
}
}
}<commit_msg>More fleshing out of all the classes. Mostly complete.<commit_after>#include "Arduino.h"
#include "i2c_t3.h"
#define combine(high,low) ( ( (uint16_t)(high << 8) ) | (uint16_t)(low) )
#define lowbyte(value) ( (uint8_t)(value) )
#define highbyte(value) ( (uint8_t)(value>>8) )
#define MaxChannels 4
#define InternalReference 2.5f
#define DefaultAddress 40
#define VoltageReferenceChannel 3
#define I2CTimeout 1000;
//LowByteShift changes across the AD799X family.
// For AD7991, 0 shift. For AD7995, 2 shift. For AD7999, 4 shift.
#define LowByteShift 0;
using namespace std;
enum class sampleDelayMode{Unknown, On, Off};
enum class i2CFilterMode{Unknown, On, Off};
enum class referenceMode{Unknown, Supply, External};
class AD7991
{
public:
AD7991();
~AD7991();
bool isConnected();
uint8_t getAddress();
void setAddress(uint8_t address);
float getVoltageSingle(uint8_t Channel);
void getVoltageMultiple(float* Data, uint8_t DACsToUse);
void getVoltageSingleRepeat(float* Data, uint8_t Channel, size_t NumberOfRepeats);
void getVoltageMultipleRepeat(float* Data, uint8_t DACsToUse, size_t NumberOfRepeats);
uint16_t getVoltageSingleInt(uint8_t Channel);
void getVoltageMultipleInt(uint16_t* Data, uint8_t DACsToUse);
void getVoltageSingleRepeatInt(uint16_t* Data, uint8_t Channel, size_t NumberOfRepeats);
void getVoltageMultipleRepeatInt(uint16_t* Data, uint8_t DACsToUse, size_t NumberOfRepeats);
bool setI2CFilter(i2CFilterMode ModeSetting);
i2CFilterMode getI2CFilter();
bool setSampleDelayMode(sampleDelayMode ModeSetting);
sampleDelayMode getSampleDelayMode();
bool setReference(referenceMode ModeSetting);
referenceMode getReference();
void setVRefExt(float VRef);
float getVRefExt();
float getVRef();
private:
uint8_t Address;
referenceMode ReferenceMode;
i2CFilterMode I2CFilterMode;
sampleDelayMode SampleDelayMode;
uint8_t DACsActive;
uint8_t ConfigByte;
uint8_t PriorConfigByte;
uint8_t MSBByte;
uint8_t LSBByte;
bool NeedToUpdateConfigByte;
const uint8_t VRefChannel = VoltageReferenceChannel;
const float VRefInt = InternalReference;
float VRefExt;
};
AD7991::AD7991()
{
I2CFilterMode = i2CFilterMode::On;
ReferenceMode = referenceMode::Supply;
SampleDelayMode = sampleDelayMode::On;
NeedToUpdateConfigByte = true;
Address = DefaultAddress;
}
AD7991::~AD7991()
{
}
uint8_t AD7991::getAddress()
{
return Address;
}
void AD7991::setAddress(uint8_t address)
{
Address = address;
}
bool AD7991::isConnected()
{
int Status = 5;
Wire.beginTransmission(Address);
Status = Wire.endTransmission();
if (Status == 0)
{
return true;
}
else
{
return false;
}
}
float AD7991::getVoltageSingle(uint8_t Channel)
{
UpdateChannelSingle(Channel);
float CurrentData;
RecieveI2CFloat(&CurrentData, 1);
return CurrentData;
}
void AD7991::getVoltageMultiple(float* Data, uint8_t DACsToUse)
{
uint8_t NumberOfChannelsToUse = UpdateChannelDACsActive(uint8_t NewDACsActive);
RecieveI2CFloat(Data, (size_t)NumberOfChannelsToUse);
}
void AD7991::getVoltageSingleRepeat(float* Data, uint8_t Channel, size_t NumberOfRepeats)
{
UpdateChannelSingle(Channel);
RecieveI2CFloat(Data, NumberOfRepeats);
}
void AD7991::getVoltageMultipleRepeat(float* Data, uint8_t DACsToUse, size_t NumberOfRepeats)
{
uint8_t NumberOfChannelsToUse = UpdateChannelDACsActive(uint8_t NewDACsActive);
RecieveI2CFloat(Data, (size_t)NumberOfChannelsToUse * NumberOfRepeats);
}
uint16_t AD7991::getVoltageSingleInt(uint8_t Channel)
{
UpdateChannelSingle(Channel);
int CurrentData;
RecieveI2CInt(&CurrentData, 1);
return CurrentData;
}
void AD7991::getVoltageMultipleInt(uint16_t* Data, uint8_t DACsToUse)
{
uint8_t NumberOfChannelsToUse = UpdateChannelDACsActive(uint8_t NewDACsActive);
RecieveI2CInt(Data, (size_t)NumberOfChannelsToUse);
}
void AD7991::getVoltageSingleRepeatInt(uint16_t* Data, uint8_t Channel, size_t NumberOfRepeats)
{
UpdateChannelSingle(Channel);
RecieveI2CInt(Data, NumberOfRepeats);
}
void AD7991::getVoltageMultipleRepeatInt(uint16_t* Data, uint8_t DACsToUse, size_t NumberOfRepeats)
{
uint8_t NumberOfChannelsToUse = UpdateChannelDACsActive(uint8_t NewDACsActive);
RecieveI2CInt(Data, (size_t)NumberOfChannelsToUse * NumberOfRepeats);
}
float AD7991::getVRef()
{
switch(ReferenceMode)
{
case referenceMode::Internal:
return VRefInt;
case referenceMode::Supply:
case default:
return VRefExt;
}
}
bool AD7991::setI2CFilter(i2CFilterMode ModeSetting)
{
if (ModeSetting != I2CFilterMode)
{
I2CFilterMode = ModeSetting;
NeedToUpdateConfigByte = true;
}
}
i2CFilterMode AD7991::getI2CFilter()
{
return I2CFilterMode;
}
bool AD7991::setSampleDelayMode(sampleDelayMode ModeSetting)
{
if (ModeSetting != SampleDelayMode)
{
SampleDelayMode = ModeSetting;
NeedToUpdateConfigByte = true;
}
}
sampleDelayMode AD7991::getSampleDelayMode()
{
return SampleDelayMode;
}
bool AD7991::setOutputMode(outputMode ModeSetting)
{
}
outputMode AD7991::getOutputMode()
{
return OutputMode;
}
bool AD7991::setReference(referenceMode ModeSetting)
{
if (ModeSetting != ReferenceMode)
{
ReferenceMode = ModeSetting;
NeedToUpdateConfigByte = true;
}
}
referenceMode AD7991::getReference()
{
return ReferenceMode;
}
void AD7991::setVRefExt(float VRef)
{
VRefExt = Vref;
}
float AD7991::getVRefExt()
{
return VRefExt;
}
void AD7991::UpdateChannelSingle(uint8_t Channel)
{
uint8_t NewDACsActive = 0;
Channel = CheckChannel(Channel);
bitWrite(NewDACsActive, Channel, 1);
if ( (NewDACsActive != DACsActive) | NeedToUpdateConfigByte)
{
NeedToUpdateConfigByte = true;
DACsActive = NewDACsActive;
UpdateConfigByte();
}
}
uint8_t AD7991::UpdateChannelDACsActive(uint8_t NewDACsActive)
{
if (bitRead(NewDACsActive,VRefChannel) & (ReferenceMode == referenceMode::External))
{
Serial.println("Can not use external reference with VRef channel on AD799X.");
bitWrite(NewDACsActive,VRefChannel,0);
}
if ( (NewDACsActive != DACsActive) | NeedToUpdateConfigByte)
{
NeedToUpdateConfigByte = true;
DACsActive = NewDACsActive;
UpdateConfigByte();
}
return (uint8_t)(bitRead(DACsActive,0) + bitRead(DACsActive,1) + bitRead(DACsActive,2) + bitRead(DACsActive,3));
}
uint8_t AD7991::CheckChannel(uint8_t Channel)
{
Channel = constrain(Channel,0,NumberOfChannels);
if (Channel == VRefChannel)
{
if (ReferenceMode::External)
{
Serial.println("Can not use external reference with VRef channel on AD799X.");
return VRefChannel-1;
}
}
return Channel;
}
void AD7991::UpdateConfigByte()
{
if (NeedToUpdateConfigByte)
{
SetConfigByte();
SendI2C();
NeedToUpdateConfigByte = false;
}
}
void AD7991::SetConfigByte()
{
ConfigByte = DACsActive << 4;
switch(ReferenceMode)
{
case referenceMode::External:
bitWrite(ConfigByte,3,1);
break;
case referenceMode::Supply:
case referenceMode::Unknown:
case default:
break;
}
switch(I2CFilterMode)
{
case i2CFilterMode::Off:
bitWrite(ConfigByte,2,1);
break;
case i2CFilterMode::On:
case i2CFilterMode::Unknown:
case default:
break;
}
switch(SampleDelayMode)
{
case sampleDelayMode::Off:
bitWrite(ConfigByte,1,1);
bitWrite(ConfigByte,0,1);
break;
case sampleDelayMode::On:
case sampleDelayMode::Unknown:
case default:
break;
}
}
void AD7991::SendI2C()
{
bool MoveOn = false;
const int MaxAttempts = 16;
int CurrentAttempt = 0;
int SendSuccess = 5;
while (!MoveOn)
{
Wire.beginTransmission(Address);
Wire.write(ConfigByte);
SendSuccess = Wire.endTransmission(I2C_STOP, I2CTimeout);
if(SendSuccess != 0)
{
Wire.finish();
Wire.resetBus();
CurrentAttempt++;
if (CurrentAttempt > MaxAttempts)
{
MoveOn = true;
Serial.println("Unrecoverable I2C transmission error with AD799X.");
}
}
else
{
MoveOn = true;
}
}
}
size_t AD7991::RecieveI2CInt(uint16_t* Data, size_t NumberOfSamples)
{
if(NumberOfSamples > 0)
{
Wire.requestFrom(Address, 2*NumberOfSamples, I2C_STOP, I2CTimeout*2*NumberOfSamples);
int BytesToCollect = Wire.available();
int CurrentIndex = 0;
while (Wire.available())
{
MSBByte = Wire.readByte();
LSBByte = Wire.readByte();
//uint8_t CurrentChannel = MSBByte >> 4;
uint16_t CurrentValue = combine( ((MSBByte << 4)>>4), LSBByte ) >> LowByteShift;
Data[CurrentIndex] = CurrentValue;
CurrentIndex++;
}
return CurrentIndex;
}
else
{
return 0;
}
}
size_t AD7991::RecieveI2CFloat(float* Data, size_t NumberOfSamples)
{
if(NumberOfSamples > 0)
{
float MaxValue = (float)((((uint16_t)-1)>>4)>>LowByteShift);
Wire.requestFrom(Address, 2*NumberOfSamples, I2C_STOP, I2CTimeout*2*NumberOfSamples);
int BytesToCollect = Wire.available();
int CurrentIndex = 0;
while (Wire.available())
{
MSBByte = Wire.readByte();
LSBByte = Wire.readByte();
//uint8_t CurrentChannel = MSBByte >> 4;
uint16_t CurrentValue = combine( ((MSBByte << 4)>>4), LSBByte ) >> LowByteShift;
Data[CurrentIndex] = getVRef()*((float)CurrentValue)/MaxValue;
CurrentIndex++;
}
return CurrentIndex;
}
else
{
return 0;
}
}<|endoftext|> |
<commit_before>#ifndef KR_COMMON_TIMER_HPP_
#define KR_COMMON_TIEMR_HPP_
#include <chrono>
#include <string>
#include <cassert>
#include <ostream>
#include <iomanip>
#include <iostream>
#include <thread>
namespace kr {
// I don't think anyone wants a timer that ticks every hour?
// Unless you are playing with 10 billions points or something
typedef std::chrono::seconds sec;
typedef std::chrono::milliseconds ms;
typedef std::chrono::microseconds us;
typedef std::chrono::nanoseconds ns;
namespace common {
/**
* @brief The is_duration struct
*/
template <typename>
struct is_duration : std::false_type {};
template <typename T, typename U>
struct is_duration<std::chrono::duration<T, U>> : std::true_type {};
/**
* @brief Unit
* @return unit as a string
*/
template <typename T>
std::string Unit() {
return "unknown unit";
}
template <>
std::string Unit<sec>() {
return "sec";
}
template <>
std::string Unit<ms>() {
return "ms";
}
template <>
std::string Unit<us>() {
return "us";
}
template <>
std::string Unit<ns>() {
return "ns";
}
/**
* @brief Ratio
* @return ration of between type T and U
*/
template <typename T, typename U>
double Ratio() {
typedef typename T::period TP;
typedef typename U::period UP;
typedef typename std::ratio_divide<TP, UP>::type RP;
return static_cast<double>(RP::num) / RP::den;
}
/**
* @brief The Timer class
*/
template <typename D>
class Timer {
static_assert(is_duration<D>::value, "Not a valid duration type");
public:
explicit Timer(const std::string& name, int report_every_n_iter = 0)
: name_(name), report_every_n_iter_(report_every_n_iter) {}
Timer(const Timer&) = delete;
Timer& operator=(const Timer&) = delete;
int iteration() const { return iteration_; }
const std::string& name() const { return name_; }
/**
* @brief Start, start timing
*/
void Start() {
assert(!running_);
running_ = true;
start_ = std::chrono::high_resolution_clock::now();
}
/**
* @brief Stop, stop timing
*/
void Stop() {
assert(running_);
elapsed_ = std::chrono::duration_cast<D>(
std::chrono::high_resolution_clock::now() - start_);
total_ += elapsed_;
++iteration_;
min_ = std::min(elapsed_, min_);
max_ = std::max(elapsed_, max_);
running_ = false;
if (report_every_n_iter_ == 0) return;
if (!(iteration_ % report_every_n_iter_)) Report();
}
/**
* @brief Elapsed, last elapsed time duration
*/
template <typename T = D>
double Elapsed() const {
return elapsed_.count() * Ratio<D, T>();
}
/**
* @brief Min, shortest time duration recorded
*/
template <typename T = D>
double Min() const {
return min_.count() * Ratio<D, T>();
}
/**
* @brief Max, longest time duration recorded
*/
template <typename T = D>
double Max() const {
return max_.count() * Ratio<D, T>();
}
/**
* @brief Average, average time duration
*/
template <typename T = D>
double Average() const {
return total_.count() * Ratio<D, T>() / iteration_;
}
/**
* @brief Reset timer
*/
void Reset() {
iteration_ = 0;
running_ = false;
}
template <typename T = D>
void Sleep(int tick) {
T duration(tick);
std::this_thread::sleep_for(duration);
}
/**
* @brief Report
* @param unit_name A string representing the unit
*/
template <typename T = D>
void Report(std::ostream& os = std::cout) const {
os << name_ << " - iterations: " << iteration_ << ", unit: " << Unit<T>()
<< ", average: " << Average<T>() << " "
<< ", min: " << Min<T>() << ", max: " << Max<T>() << std::endl;
}
private:
std::string name_{"timer"};
int iteration_{0};
int report_every_n_iter_{0};
bool running_{false};
std::chrono::high_resolution_clock::time_point start_;
D min_{D::max()};
D max_{D::min()};
D elapsed_{0};
D total_{0};
};
typedef Timer<sec> TimerSec;
typedef Timer<ms> TimerMs;
typedef Timer<us> TimerUs;
typedef Timer<ns> TimerNs;
template <typename C>
void PrintClockData() {
std::cout << "- precision: ";
// if time unit is less or equal one millisecond
typedef typename C::period P; // type of time unit
if (std::ratio_less_equal<P, std::milli>::value) {
// convert to and print as milliseconds
typedef typename std::ratio_multiply<P, std::kilo>::type TT;
std::cout << std::fixed << static_cast<double>(TT::num) / TT::den << " ms"
<< std::endl;
} else {
// print as seconds
std::cout << std::fixed << static_cast<double>(P::num) / P::den << " sec"
<< std::endl;
}
std::cout << "- is_steady: " << std::boolalpha << C::is_steady << std::endl;
}
} // namespace common
} // namespace kr
#endif // KR_COMMON_TIMER_HPP_
<commit_msg>move assert after timing<commit_after>#ifndef KR_COMMON_TIMER_HPP_
#define KR_COMMON_TIEMR_HPP_
#include <chrono>
#include <string>
#include <cassert>
#include <ostream>
#include <iomanip>
#include <iostream>
#include <thread>
namespace kr {
// I don't think anyone wants a timer that ticks every hour?
// Unless you are playing with 10 billions points or something
typedef std::chrono::seconds sec;
typedef std::chrono::milliseconds ms;
typedef std::chrono::microseconds us;
typedef std::chrono::nanoseconds ns;
namespace common {
/**
* @brief The is_duration struct
*/
template <typename>
struct is_duration : std::false_type {};
template <typename T, typename U>
struct is_duration<std::chrono::duration<T, U>> : std::true_type {};
/**
* @brief Unit
* @return unit as a string
*/
template <typename T>
std::string Unit() {
return "unknown unit";
}
template <>
std::string Unit<sec>() {
return "sec";
}
template <>
std::string Unit<ms>() {
return "ms";
}
template <>
std::string Unit<us>() {
return "us";
}
template <>
std::string Unit<ns>() {
return "ns";
}
/**
* @brief Ratio
* @return ration of between type T and U
*/
template <typename T, typename U>
double Ratio() {
typedef typename T::period TP;
typedef typename U::period UP;
typedef typename std::ratio_divide<TP, UP>::type RP;
return static_cast<double>(RP::num) / RP::den;
}
/**
* @brief The Timer class
*/
template <typename D>
class Timer {
static_assert(is_duration<D>::value, "Not a valid duration type");
public:
explicit Timer(const std::string& name, int report_every_n_iter = 0)
: name_(name), report_every_n_iter_(report_every_n_iter) {}
Timer(const Timer&) = delete;
Timer& operator=(const Timer&) = delete;
int iteration() const { return iteration_; }
const std::string& name() const { return name_; }
/**
* @brief Start, start timing
*/
void Start() {
assert(!running_);
running_ = true;
start_ = std::chrono::high_resolution_clock::now();
}
/**
* @brief Stop, stop timing
*/
void Stop() {
elapsed_ = std::chrono::duration_cast<D>(
std::chrono::high_resolution_clock::now() - start_);
assert(running_);
total_ += elapsed_;
++iteration_;
min_ = std::min(elapsed_, min_);
max_ = std::max(elapsed_, max_);
running_ = false;
if (report_every_n_iter_ == 0) return;
if (!(iteration_ % report_every_n_iter_)) Report();
}
/**
* @brief Elapsed, last elapsed time duration
*/
template <typename T = D>
double Elapsed() const {
return elapsed_.count() * Ratio<D, T>();
}
/**
* @brief Min, shortest time duration recorded
*/
template <typename T = D>
double Min() const {
return min_.count() * Ratio<D, T>();
}
/**
* @brief Max, longest time duration recorded
*/
template <typename T = D>
double Max() const {
return max_.count() * Ratio<D, T>();
}
/**
* @brief Average, average time duration
*/
template <typename T = D>
double Average() const {
return total_.count() * Ratio<D, T>() / iteration_;
}
/**
* @brief Reset timer
*/
void Reset() {
iteration_ = 0;
running_ = false;
}
template <typename T = D>
void Sleep(int tick) {
T duration(tick);
std::this_thread::sleep_for(duration);
}
/**
* @brief Report
* @param unit_name A string representing the unit
*/
template <typename T = D>
void Report(std::ostream& os = std::cout) const {
os << name_ << " - iterations: " << iteration_ << ", unit: " << Unit<T>()
<< ", average: " << Average<T>() << " "
<< ", min: " << Min<T>() << ", max: " << Max<T>() << std::endl;
}
private:
std::string name_{"timer"};
int iteration_{0};
int report_every_n_iter_{0};
bool running_{false};
std::chrono::high_resolution_clock::time_point start_;
D min_{D::max()};
D max_{D::min()};
D elapsed_{0};
D total_{0};
};
typedef Timer<sec> TimerSec;
typedef Timer<ms> TimerMs;
typedef Timer<us> TimerUs;
typedef Timer<ns> TimerNs;
template <typename C>
void PrintClockData() {
std::cout << "- precision: ";
// if time unit is less or equal one millisecond
typedef typename C::period P; // type of time unit
if (std::ratio_less_equal<P, std::milli>::value) {
// convert to and print as milliseconds
typedef typename std::ratio_multiply<P, std::kilo>::type TT;
std::cout << std::fixed << static_cast<double>(TT::num) / TT::den << " ms"
<< std::endl;
} else {
// print as seconds
std::cout << std::fixed << static_cast<double>(P::num) / P::den << " sec"
<< std::endl;
}
std::cout << "- is_steady: " << std::boolalpha << C::is_steady << std::endl;
}
} // namespace common
} // namespace kr
#endif // KR_COMMON_TIMER_HPP_
<|endoftext|> |
<commit_before>/*
* gram_matrix.cc
* Copyright 2016 John Lawson
*
* 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 "gram_matrix.h"
#include <tuple>
namespace ptope {
const char GramMatrix::N = 'N';
const char GramMatrix::T = 'T';
const char GramMatrix::U = 'U';
const double GramMatrix::one = 1.0;
const double GramMatrix::minus_one = -1.0;
const arma::blas_int GramMatrix::int_one = 1;
void
GramMatrix::from( ptope::VectorSet const& vectors ) {
priv_products_prepare( vectors );
priv_products_compute( vectors );
}
GramMatrix::Entry
GramMatrix::at( std::size_t const& index ) const {
Entry result;
std::tie(result.row, result.col) = priv_rfp_index_to_ij( index );
result.val = m_matrix[index];
return result;
}
double
GramMatrix::at( std::size_t const& row, std::size_t const& col ) const {
return m_matrix[ priv_ij_to_rfp_index( row, col ) ];
}
std::size_t
GramMatrix::priv_min_product_size( ptope::VectorSet const& vectors ) {
std::size_t num = vectors.size();
return ( num * ( num + 1 ) ) / 2;
}
std::pair<std::size_t, std::size_t>
GramMatrix::priv_rfp_index_to_ij( std::size_t const& index ) const {
std::size_t rfp_col = index / m_rfp_nrows;
std::size_t row_cutoff = m_nvecs / 2 + 1 + rfp_col;
std::size_t rfp_row = index % m_rfp_nrows;
std::size_t row;
std::size_t col;
if( rfp_row < row_cutoff ) {
row = rfp_row;
col = rfp_col + m_rfp_ncols - ( m_nvecs % 2 );
} else {
col = m_rfp_ncols - rfp_col - 1 - ( m_nvecs % 2 );
row = m_rfp_nrows - rfp_row - 1;
}
return { row, col };
}
std::size_t
GramMatrix::priv_ij_to_rfp_index( std::size_t const& row ,
std::size_t const& col ) const {
return 0;
}
void
GramMatrix::priv_products_prepare( ptope::VectorSet const& vectors ) {
m_nvecs = vectors.size();
m_nelems = priv_min_product_size( vectors );
m_rfp_ncols = ( m_nvecs + 1 ) / 2;
m_rfp_nrows = m_nvecs + 1 - ( m_nvecs % 2 );
m_matrix.set_min_size( m_nelems );
m_matrix.zeros();
}
void
GramMatrix::priv_products_compute( ptope::VectorSet const& vectors ) {
std::size_t total_dim = vectors.dimension();
std::size_t real_dim = total_dim - 1;
double const * vector_ptr = vectors.memptr();
double const * hyp_part_ptr = vector_ptr + real_dim;
arma::blas_int n = m_nvecs;
arma::blas_int k = real_dim;
arma::blas_int lda = total_dim;
double * out_ptr = m_matrix.memptr();
/* Compute hyperbolic part of product */
arma_fortran(arma_dsfrk)(&N, &U, &T, &n, &int_one, &one, hyp_part_ptr, &lda,
&one, out_ptr);
/* Compute inner product of euclidean part and subtract the hyperbolic
* product. */
arma_fortran(arma_dsfrk)(&N, &U, &T, &n, &k, &one, vector_ptr, &lda,
&minus_one, out_ptr);
}
}
<commit_msg>Fixes problem with rfp indexing.<commit_after>/*
* gram_matrix.cc
* Copyright 2016 John Lawson
*
* 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 "gram_matrix.h"
#include <tuple>
namespace ptope {
const char GramMatrix::N = 'N';
const char GramMatrix::T = 'T';
const char GramMatrix::U = 'U';
const double GramMatrix::one = 1.0;
const double GramMatrix::minus_one = -1.0;
const arma::blas_int GramMatrix::int_one = 1;
void
GramMatrix::from( ptope::VectorSet const& vectors ) {
priv_products_prepare( vectors );
priv_products_compute( vectors );
}
GramMatrix::Entry
GramMatrix::at( std::size_t const& index ) const {
Entry result;
std::tie(result.row, result.col) = priv_rfp_index_to_ij( index );
result.val = m_matrix[index];
return result;
}
double
GramMatrix::at( std::size_t const& row, std::size_t const& col ) const {
return m_matrix[ priv_ij_to_rfp_index( row, col ) ];
}
std::size_t
GramMatrix::priv_min_product_size( ptope::VectorSet const& vectors ) {
std::size_t num = vectors.size();
return ( num * ( num + 1 ) ) / 2;
}
std::pair<std::size_t, std::size_t>
GramMatrix::priv_rfp_index_to_ij( std::size_t const& index ) const {
std::size_t rfp_col = index / m_rfp_nrows;
std::size_t row_cutoff = m_nvecs / 2 + 1 + rfp_col;
std::size_t rfp_row = index % m_rfp_nrows;
std::size_t row;
std::size_t col;
if( rfp_row < row_cutoff ) {
row = rfp_row;
col = rfp_col + m_rfp_ncols - ( m_nvecs % 2 );
} else {
col = rfp_row + rfp_col - row_cutoff;
row = rfp_col;
}
return { row, col };
}
std::size_t
GramMatrix::priv_ij_to_rfp_index( std::size_t const& row ,
std::size_t const& col ) const {
std::size_t result;
if( row > col ) {
result = priv_ij_to_rfp_index( col, row );
} else {
std::size_t rfp_row;
std::size_t rfp_col;
std::size_t col_threshold = m_rfp_ncols - (m_nvecs % 2);
if( col >= col_threshold ) {
rfp_row = row;
rfp_col = col - col_threshold;
} else {
rfp_row = col_threshold + col + 1;
rfp_col = row;
}
result = rfp_col * m_rfp_nrows + rfp_row;
}
return result;
}
void
GramMatrix::priv_products_prepare( ptope::VectorSet const& vectors ) {
m_nvecs = vectors.size();
m_nelems = priv_min_product_size( vectors );
m_rfp_ncols = ( m_nvecs + 1 ) / 2;
m_rfp_nrows = m_nvecs + 1 - ( m_nvecs % 2 );
m_matrix.set_min_size( m_nelems );
m_matrix.zeros();
}
void
GramMatrix::priv_products_compute( ptope::VectorSet const& vectors ) {
std::size_t total_dim = vectors.dimension();
std::size_t real_dim = total_dim - 1;
double const * vector_ptr = vectors.memptr();
double const * hyp_part_ptr = vector_ptr + real_dim;
arma::blas_int n = m_nvecs;
arma::blas_int k = real_dim;
arma::blas_int lda = total_dim;
double * out_ptr = m_matrix.memptr();
/* Compute hyperbolic part of product */
arma_fortran(arma_dsfrk)(&N, &U, &T, &n, &int_one, &one, hyp_part_ptr, &lda,
&one, out_ptr);
/* Compute inner product of euclidean part and subtract the hyperbolic
* product. */
arma_fortran(arma_dsfrk)(&N, &U, &T, &n, &k, &one, vector_ptr, &lda,
&minus_one, out_ptr);
}
}
<|endoftext|> |
<commit_before>#include "renderer.hpp"
#include "renderer_types.hpp"
#include "../src/estd.hpp"
FrameSeriesResource makeFrameSeries()
{
return estd::make_unique<FrameSeries>();
}
namespace
{
struct ProgramBindings {
std::vector<GLint> textureUniforms;
struct ArrayAttrib {
GLint id;
int componentCount;
};
std::vector<ArrayAttrib> arrayAttribs;
std::vector<GLint> floatVectorsUniforms;
};
}
ProgramBindings programBindings(FrameSeries::ShaderProgramMaterials const&
program,
ProgramInputs const& inputs)
{
auto bindings = ProgramBindings {};
std::transform(std::begin(inputs.textures),
std::end(inputs.textures),
std::back_inserter(bindings.textureUniforms),
[&program](ProgramInputs::TextureInput const& element) {
return glGetUniformLocation(program.programId, element.name.c_str());
});
std::transform(std::begin(inputs.attribs),
std::end(inputs.attribs),
std::back_inserter(bindings.arrayAttribs),
[&program](ProgramInputs::AttribArrayInput const& element) ->
ProgramBindings::ArrayAttrib {
return {
glGetAttribLocation(program.programId, element.name.c_str()),
element.componentCount
};
});
std::transform(std::begin(inputs.floatValues),
std::end(inputs.floatValues),
std::back_inserter(bindings.floatVectorsUniforms),
[&program](ProgramInputs::FloatInput const& element) {
return glGetUniformLocation(program.programId, element.name.c_str());
});
return bindings;
};
void drawOne(FrameSeries& output,
ProgramDef programDef,
ProgramInputs inputs,
GeometryDef geometryDef)
{
output.beginFrame();
// define and draw the content of the frame
if (programDef.vertexShader.source.empty()
|| programDef.fragmentShader.source.empty()) {
return;
}
auto const& program = output.program(programDef);
glUseProgram(program.programId);
{
auto vars = programBindings(program, inputs);
auto textureTargets = std::vector<GLenum> {};
{
auto i = 0;
for (auto& textureInput : inputs.textures) {
auto unit = i;
auto uniformId = vars.textureUniforms[i];
i++;
if (uniformId < 0) {
continue;
}
auto const& texture = output.texture(textureInput.content);
auto target = GL_TEXTURE0 + unit;
textureTargets.emplace_back(target);
glActiveTexture(target);
glBindTexture(GL_TEXTURE_2D, texture.textureId);
glUniform1i(uniformId, unit);
OGL_TRACE;
}
}
{
auto i = 0;
for (auto& floatInput : inputs.floatValues) {
auto uniformId = vars.floatVectorsUniforms[i];
i++;
auto const& values = floatInput.values;
switch (values.size()) {
case 4:
glUniform4f(uniformId,
values[0],
values[1],
values[2],
values[3]);
break;
case 3:
glUniform3f(uniformId,
values[0],
values[1],
values[2]);
break;
case 2:
glUniform2f(uniformId,
values[0],
values[1]);
break;
case 1:
glUniform1f(uniformId,
values[0]);
break;
default:
printf("invalid number of float inputs: %lu\n", values.size());
}
OGL_TRACE;
}
}
auto const& mesh = output.mesh(geometryDef);
// draw here
glBindVertexArray(mesh.vertexArray);
{
auto& vertexAttribVars = vars.arrayAttribs;
int i = 0;
for (auto attrib : vertexAttribVars) {
glBindBuffer(GL_ARRAY_BUFFER, mesh.vertexBuffers[i]);
glVertexAttribPointer(attrib.id, attrib.componentCount, GL_FLOAT, GL_FALSE, 0,
0);
glEnableVertexAttribArray(attrib.id);
i++;
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.indicesBuffer);
glDrawElements(GL_TRIANGLES,
mesh.indicesCount,
GL_UNSIGNED_INT,
0);
for (auto attrib : vertexAttribVars) {
glDisableVertexAttribArray(attrib.id);
}
}
glBindVertexArray(0);
// unbind
for (auto target : textureTargets) {
glActiveTexture(target);
glBindTexture(GL_TEXTURE_2D, 0);
}
glActiveTexture(GL_TEXTURE0);
OGL_TRACE;
}
glUseProgram(0);
};
<commit_msg>implement matrix uniform binding<commit_after>#include "renderer.hpp"
#include "renderer_types.hpp"
#include "../src/estd.hpp"
FrameSeriesResource makeFrameSeries()
{
return estd::make_unique<FrameSeries>();
}
namespace
{
struct ProgramBindings {
std::vector<GLint> textureUniforms;
struct ArrayAttrib {
GLint id;
int componentCount;
};
std::vector<ArrayAttrib> arrayAttribs;
std::vector<GLint> floatVectorsUniforms;
};
}
ProgramBindings programBindings(FrameSeries::ShaderProgramMaterials const&
program,
ProgramInputs const& inputs)
{
auto bindings = ProgramBindings {};
std::transform(std::begin(inputs.textures),
std::end(inputs.textures),
std::back_inserter(bindings.textureUniforms),
[&program](ProgramInputs::TextureInput const& element) {
return glGetUniformLocation(program.programId, element.name.c_str());
});
std::transform(std::begin(inputs.attribs),
std::end(inputs.attribs),
std::back_inserter(bindings.arrayAttribs),
[&program](ProgramInputs::AttribArrayInput const& element) ->
ProgramBindings::ArrayAttrib {
return {
glGetAttribLocation(program.programId, element.name.c_str()),
element.componentCount
};
});
std::transform(std::begin(inputs.floatValues),
std::end(inputs.floatValues),
std::back_inserter(bindings.floatVectorsUniforms),
[&program](ProgramInputs::FloatInput const& element) {
return glGetUniformLocation(program.programId, element.name.c_str());
});
return bindings;
};
void drawOne(FrameSeries& output,
ProgramDef programDef,
ProgramInputs inputs,
GeometryDef geometryDef)
{
output.beginFrame();
// define and draw the content of the frame
if (programDef.vertexShader.source.empty()
|| programDef.fragmentShader.source.empty()) {
return;
}
auto const& program = output.program(programDef);
glUseProgram(program.programId);
{
auto vars = programBindings(program, inputs);
auto textureTargets = std::vector<GLenum> {};
{
auto i = 0;
for (auto& textureInput : inputs.textures) {
auto unit = i;
auto uniformId = vars.textureUniforms[i];
i++;
if (uniformId < 0) {
continue;
}
auto const& texture = output.texture(textureInput.content);
auto target = GL_TEXTURE0 + unit;
textureTargets.emplace_back(target);
glActiveTexture(target);
glBindTexture(GL_TEXTURE_2D, texture.textureId);
glUniform1i(uniformId, unit);
OGL_TRACE;
}
}
{
auto i = 0;
for (auto& floatInput : inputs.floatValues) {
auto uniformId = vars.floatVectorsUniforms[i];
i++;
auto const& values = floatInput.values;
auto const width = values.size();
auto const last_row = floatInput.last_row;
if (last_row == 0) {
switch (width) {
case 4:
glUniform4fv(uniformId,
1,
&values.front());
break;
case 3:
glUniform3fv(uniformId,
1,
&values.front());
break;
case 2:
glUniform2fv(uniformId,
1,
&values.front());
break;
case 1:
glUniform1fv(uniformId,
1,
&values.front());
break;
default:
printf("invalid number of float inputs: %lu\n", width);
}
} else if (last_row == 1) {
switch (width) {
case 2:
glUniformMatrix2fv(uniformId,
1,
GL_TRUE,
&values.front());
break;
case 4:
glUniformMatrix4x2fv(uniformId,
1,
GL_TRUE,
&values.front());
break;
case 3:
glUniformMatrix3x2fv(uniformId,
1,
GL_TRUE,
&values.front());
break;
default:
printf("invalid number of float inputs: %lu, rows: %u\n", width, last_row);
}
} else if (floatInput.last_row == 2) {
switch (width) {
case 3:
glUniformMatrix3fv(uniformId,
1,
GL_TRUE,
&values.front());
break;
case 4:
glUniformMatrix4x3fv(uniformId,
1,
GL_TRUE,
&values.front());
break;
case 2:
glUniformMatrix2x3fv(uniformId,
1,
GL_TRUE,
&values.front());
break;
default:
printf("invalid number of float inputs: %lu, rows: %u\n", width, last_row);
}
} else if (floatInput.last_row == 3) {
switch (width) {
case 4:
glUniformMatrix4fv(uniformId,
1,
GL_TRUE,
&values.front());
break;
case 3:
glUniformMatrix3x4fv(uniformId,
1,
GL_TRUE,
&values.front());
break;
case 2:
glUniformMatrix2x4fv(uniformId,
1,
GL_TRUE,
&values.front());
break;
default:
printf("invalid number of float inputs: %lu, rows: %u\n", width, last_row);
}
}
OGL_TRACE;
}
}
auto const& mesh = output.mesh(geometryDef);
// draw here
glBindVertexArray(mesh.vertexArray);
{
auto& vertexAttribVars = vars.arrayAttribs;
int i = 0;
for (auto attrib : vertexAttribVars) {
glBindBuffer(GL_ARRAY_BUFFER, mesh.vertexBuffers[i]);
glVertexAttribPointer(attrib.id, attrib.componentCount, GL_FLOAT, GL_FALSE, 0,
0);
glEnableVertexAttribArray(attrib.id);
i++;
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.indicesBuffer);
glDrawElements(GL_TRIANGLES,
mesh.indicesCount,
GL_UNSIGNED_INT,
0);
for (auto attrib : vertexAttribVars) {
glDisableVertexAttribArray(attrib.id);
}
}
glBindVertexArray(0);
// unbind
for (auto target : textureTargets) {
glActiveTexture(target);
glBindTexture(GL_TEXTURE_2D, 0);
}
glActiveTexture(GL_TEXTURE0);
OGL_TRACE;
}
glUseProgram(0);
};
<|endoftext|> |
<commit_before>// @(#)root/cintex:$Name: $:$Id: CINTFunctionBuilder.cxx,v 1.11 2006/07/03 10:22:13 roiser Exp $
// Author: Pere Mato 2005
// Copyright CERN, CH-1211 Geneva 23, 2004-2005, All rights reserved.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose is hereby granted without fee, provided that this copyright and
// permissions notice appear in all copies and derivatives.
//
// This software is provided "as is" without express or implied warranty.
#include "Reflex/Reflex.h"
#include "Reflex/Tools.h"
#include "CINTdefs.h"
#include "CINTFunctionBuilder.h"
#include "CINTScopeBuilder.h"
#include "CINTFunctional.h"
#include "CINTTypedefBuilder.h"
#include "Api.h"
using namespace ROOT::Reflex;
using namespace std;
namespace ROOT { namespace Cintex {
CINTFunctionBuilder::CINTFunctionBuilder(const ROOT::Reflex::Member& m)
: fFunction(m) {
// CINTFunctionBuilder constructor.
}
CINTFunctionBuilder::~CINTFunctionBuilder() {
// CINTFunctionBuilder destructor.
}
void CINTFunctionBuilder::Setup() {
// Setup a CINT function.
Scope scope = fFunction.DeclaringScope();
bool global = scope.IsTopScope();
if ( global ) {
G__lastifuncposition();
}
else {
CINTScopeBuilder::Setup(scope);
string sname = scope.Name(SCOPED);
int ns_tag = G__search_tagname(sname.c_str(),'n');
G__tag_memfunc_setup(ns_tag);
}
Setup(fFunction);
if ( global ) {
G__resetifuncposition();
}
else {
G__tag_memfunc_reset();
}
return;
}
void CINTFunctionBuilder::Setup(const Member& function) {
// Setup a CINT function.
Type cl = Type::ByName(function.DeclaringScope().Name(SCOPED));
int access = G__PUBLIC;
int const_ness = 0;
int virtuality = 0;
int reference = 0;
int memory_type = 1; // G__LOCAL; // G__AUTO=-1
int tagnum = CintTag(function.DeclaringScope().Name(SCOPED));
//---Alocate a context
StubContext_t* stub_context = new StubContext_t(function, cl);
//---Function Name and hash value
string funcname = function.Name();
int hash, tmp;
//---Return type ----------------
Type rt = function.TypeOf().ReturnType();
reference = rt.IsReference() ? 1 : 0;
int ret_typedeft = -1;
if ( rt.IsTypedef()) {
ret_typedeft = CINTTypedefBuilder::Setup(rt);
rt = rt.FinalType();
}
//CINTScopeBuilder::Setup( rt );
CintTypeDesc ret_desc = CintType( rt );
char ret_type = rt.IsPointer() ? (ret_desc.first - ('a'-'A')) : ret_desc.first;
int ret_tag = CintTag( ret_desc.second );
if( function.IsOperator() ) {
// remove space between "operator" keywork and the actual operator
if ( funcname[8] == ' ' && ! isalpha( funcname[9] ) )
funcname = "operator" + funcname.substr(9);
}
G__InterfaceMethod stub;
if( function.IsConstructor() ) {
//stub = Constructor_stub;
stub = Allocate_stub_function(stub_context, & Constructor_stub_with_context);
funcname = G__ClassInfo(tagnum).Name();
ret_tag = tagnum;
}
else if ( function.IsDestructor() ) {
//stub = Destructor_stub;
stub = Allocate_stub_function(stub_context, & Destructor_stub_with_context);
funcname = "~";
funcname += G__ClassInfo(tagnum).Name();
}
else {
//stub = Method_stub;
stub = Allocate_stub_function(stub_context, & Method_stub_with_context);
}
if ( function.IsPrivate() )
access = G__PRIVATE;
else if ( function.IsProtected() )
access = G__PROTECTED;
else if ( function.IsPublic() )
access = G__PUBLIC;
if ( function.TypeOf().IsConst() )
const_ness = G__CONSTFUNC;
if ( function.IsVirtual() )
virtuality = 1;
if ( function.IsStatic() )
memory_type += G__CLASSSCOPE;
string signature = CintSignature(function);
int nparam = function.TypeOf().FunctionParameterSize();
//---Cint function hash
G__hash(funcname, hash, tmp);
G__usermemfunc_setup( const_cast<char*>(funcname.c_str()), // function Name
hash, // function Name hash value
(int (*)(void))stub, // method stub function
ret_type, // return type (void)
ret_tag, // return TypeNth tag number
ret_typedeft, // typedef number
reference, // reftype
nparam, // number of paramerters
memory_type, // memory type
access, // access type
const_ness, // CV qualifiers
const_cast<char*>(signature.c_str()), // signature
(char*)NULL, // comment line
(void*)NULL, // true2pf
virtuality, // virtuality
stub_context // user ParameterNth
);
}
}}
<commit_msg>Declare to CINT the sopes of all return and parameter types of free functions<commit_after>// @(#)root/cintex:$Name: $:$Id: CINTFunctionBuilder.cxx,v 1.12 2006/07/14 06:58:00 roiser Exp $
// Author: Pere Mato 2005
// Copyright CERN, CH-1211 Geneva 23, 2004-2005, All rights reserved.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose is hereby granted without fee, provided that this copyright and
// permissions notice appear in all copies and derivatives.
//
// This software is provided "as is" without express or implied warranty.
#include "Reflex/Reflex.h"
#include "Reflex/Tools.h"
#include "CINTdefs.h"
#include "CINTFunctionBuilder.h"
#include "CINTScopeBuilder.h"
#include "CINTFunctional.h"
#include "CINTTypedefBuilder.h"
#include "Api.h"
using namespace ROOT::Reflex;
using namespace std;
namespace ROOT { namespace Cintex {
CINTFunctionBuilder::CINTFunctionBuilder(const ROOT::Reflex::Member& m)
: fFunction(m) {
// CINTFunctionBuilder constructor.
}
CINTFunctionBuilder::~CINTFunctionBuilder() {
// CINTFunctionBuilder destructor.
}
void CINTFunctionBuilder::Setup() {
// Setup a CINT function.
Scope scope = fFunction.DeclaringScope();
bool global = scope.IsTopScope();
CINTScopeBuilder::Setup(fFunction.TypeOf());
if ( global ) {
G__lastifuncposition();
}
else {
CINTScopeBuilder::Setup(scope);
string sname = scope.Name(SCOPED);
int ns_tag = G__search_tagname(sname.c_str(),'n');
G__tag_memfunc_setup(ns_tag);
}
Setup(fFunction);
if ( global ) {
G__resetifuncposition();
}
else {
G__tag_memfunc_reset();
}
return;
}
void CINTFunctionBuilder::Setup(const Member& function) {
// Setup a CINT function.
Type cl = Type::ByName(function.DeclaringScope().Name(SCOPED));
int access = G__PUBLIC;
int const_ness = 0;
int virtuality = 0;
int reference = 0;
int memory_type = 1; // G__LOCAL; // G__AUTO=-1
int tagnum = CintTag(function.DeclaringScope().Name(SCOPED));
//---Alocate a context
StubContext_t* stub_context = new StubContext_t(function, cl);
//---Function Name and hash value
string funcname = function.Name();
int hash, tmp;
//---Return type ----------------
Type rt = function.TypeOf().ReturnType();
reference = rt.IsReference() ? 1 : 0;
int ret_typedeft = -1;
if ( rt.IsTypedef()) {
ret_typedeft = CINTTypedefBuilder::Setup(rt);
rt = rt.FinalType();
}
//CINTScopeBuilder::Setup( rt );
CintTypeDesc ret_desc = CintType( rt );
char ret_type = rt.IsPointer() ? (ret_desc.first - ('a'-'A')) : ret_desc.first;
int ret_tag = CintTag( ret_desc.second );
if( function.IsOperator() ) {
// remove space between "operator" keywork and the actual operator
if ( funcname[8] == ' ' && ! isalpha( funcname[9] ) )
funcname = "operator" + funcname.substr(9);
}
G__InterfaceMethod stub;
if( function.IsConstructor() ) {
//stub = Constructor_stub;
stub = Allocate_stub_function(stub_context, & Constructor_stub_with_context);
funcname = G__ClassInfo(tagnum).Name();
ret_tag = tagnum;
}
else if ( function.IsDestructor() ) {
//stub = Destructor_stub;
stub = Allocate_stub_function(stub_context, & Destructor_stub_with_context);
funcname = "~";
funcname += G__ClassInfo(tagnum).Name();
}
else {
//stub = Method_stub;
stub = Allocate_stub_function(stub_context, & Method_stub_with_context);
}
if ( function.IsPrivate() )
access = G__PRIVATE;
else if ( function.IsProtected() )
access = G__PROTECTED;
else if ( function.IsPublic() )
access = G__PUBLIC;
if ( function.TypeOf().IsConst() )
const_ness = G__CONSTFUNC;
if ( function.IsVirtual() )
virtuality = 1;
if ( function.IsStatic() )
memory_type += G__CLASSSCOPE;
string signature = CintSignature(function);
int nparam = function.TypeOf().FunctionParameterSize();
//---Cint function hash
G__hash(funcname, hash, tmp);
G__usermemfunc_setup( const_cast<char*>(funcname.c_str()), // function Name
hash, // function Name hash value
(int (*)(void))stub, // method stub function
ret_type, // return type (void)
ret_tag, // return TypeNth tag number
ret_typedeft, // typedef number
reference, // reftype
nparam, // number of paramerters
memory_type, // memory type
access, // access type
const_ness, // CV qualifiers
const_cast<char*>(signature.c_str()), // signature
(char*)NULL, // comment line
(void*)NULL, // true2pf
virtuality, // virtuality
stub_context // user ParameterNth
);
}
}}
<|endoftext|> |
<commit_before>#include "extensions/common/wasm/null/null_plugin.h"
namespace Envoy {
namespace Extensions {
namespace Common {
namespace Wasm {
namespace Null {
namespace Plugin {
namespace CommonWasmTestCpp {
ThreadSafeSingleton<NullPluginRegistry> null_plugin_registry_;
} // namespace CommonWasmTestCpp
/**
* Config registration for a Wasm filter plugin. @see NamedHttpFilterConfigFactory.
*/
class PluginFactory : public NullVmPluginFactory {
public:
PluginFactory() {}
const std::string name() const override {
// Work around issue with coverage doubly registering.
return "CommonWasmTestCpp" + std::string(suffix_++, '_');
}
std::unique_ptr<NullVmPlugin> create() const override {
return std::make_unique<NullPlugin>(
&Envoy::Extensions::Common::Wasm::Null::Plugin::CommonWasmTestCpp::null_plugin_registry_
.get());
}
private:
static int suffix_;
};
int PluginFactory::suffix_ = 0;
/**
* Static registration for the null Wasm filter. @see RegisterFactory.
*/
static Registry::RegisterFactory<PluginFactory, NullVmPluginFactory> register_;
} // namespace Plugin
} // namespace Null
} // namespace Wasm
} // namespace Common
} // namespace Extensions
} // namespace Envoy
<commit_msg>Add FIXME<commit_after>#include "extensions/common/wasm/null/null_plugin.h"
namespace Envoy {
namespace Extensions {
namespace Common {
namespace Wasm {
namespace Null {
namespace Plugin {
namespace CommonWasmTestCpp {
ThreadSafeSingleton<NullPluginRegistry> null_plugin_registry_;
} // namespace CommonWasmTestCpp
/**
* Config registration for a Wasm filter plugin. @see NamedHttpFilterConfigFactory.
*/
class PluginFactory : public NullVmPluginFactory {
public:
PluginFactory() {}
const std::string name() const override {
// FIXME: work around issue with coverage doubly registering this factory.
return "CommonWasmTestCpp" + std::string(suffix_++, '_');
}
std::unique_ptr<NullVmPlugin> create() const override {
return std::make_unique<NullPlugin>(
&Envoy::Extensions::Common::Wasm::Null::Plugin::CommonWasmTestCpp::null_plugin_registry_
.get());
}
private:
static int suffix_;
};
int PluginFactory::suffix_ = 0;
/**
* Static registration for the null Wasm filter. @see RegisterFactory.
*/
static Registry::RegisterFactory<PluginFactory, NullVmPluginFactory> register_;
} // namespace Plugin
} // namespace Null
} // namespace Wasm
} // namespace Common
} // namespace Extensions
} // namespace Envoy
<|endoftext|> |
<commit_before>#include <iostream>
#include "libaps.h"
#include "constants.h"
#include <thread>
#include "EthernetControl.h"
using namespace std;
int main ()
{
cout << "BBN AP2 Test Executable" << endl;
cout << "Testing only EthernetControl" << endl;
string dev("Intel(R) 82579LM Gigabit Network Connection");
EthernetControl *ec = new EthernetControl();
EthernetControl::set_device_active(dev,true);
EthernetControl::enumerate();
#if 0
set_logging_level(5);
int numDevices = get_numDevices();
cout << numDevices << " APS device" << (numDevices > 1 ? "s": "") << " found" << endl;
if (numDevices < 1)
return 0;
char s[] = "stdout";
set_log(s);
cout << "Attempting to initialize libaps" << endl;
init();
char serialBuffer[100];
for (int cnt; cnt < numDevices; cnt++) {
get_deviceSerial(cnt, serialBuffer);
cout << "Device " << cnt << " serial #: " << serialBuffer << endl;
}
int rc;
rc = connect_by_ID(0);
cout << "connect_by_ID(0) returned " << rc << endl;
cout << "Set sample rate " << endl;
set_sampleRate(0,100);
cout << "current PLL frequency = " << get_sampleRate(0) << " MHz" << endl;
cout << "setting trigger source = EXTERNAL" << endl;
set_trigger_source(0, EXTERNAL);
cout << "get trigger source returns " << ((get_trigger_source(0) == INTERNAL) ? "INTERNAL" : "EXTERNAL") << endl;
cout << "setting trigger source = INTERNAL" << endl;
set_trigger_source(0, INTERNAL);
cout << "get trigger source returns " << ((get_trigger_source(0) == INTERNAL) ? "INTERNAL" : "EXTERNAL") << endl;
cout << "get channel(0) enable: " << get_channel_enabled(0,0) << endl;
cout << "set channel(0) enabled = 1" << endl;
set_channel_enabled(0,0,true);
const int wfs = 1000;
short wf[wfs];
for (int cnt = 0; cnt < wfs; cnt++)
wf[cnt] = (cnt < wfs/2) ? 32767 : -32767;
cout << "loading waveform" << endl;
set_waveform_int(0, 0, wf, wfs);
cout << "Running" << endl;
set_sampleRate(0,50);
run(0);
std::this_thread::sleep_for(std::chrono::seconds(10));
cout << "Stopping" << endl;
stop(0);
set_channel_enabled(0,0,false);
cout << "get channel(0) enable: " << get_channel_enabled(0,0) << endl;
rc = disconnect_by_ID(0);
cout << "disconnect_by_ID(0) returned " << rc << endl;
#endif
return 0;
}<commit_msg>Added lookup by description and name to main test<commit_after>#include <iostream>
#include "libaps.h"
#include "constants.h"
#include <thread>
#include "logger.h"
#include "EthernetControl.h"
using namespace std;
int main ()
{
cout << "BBN AP2 Test Executable" << endl;
FILELog::ReportingLevel() = TLogLevel(5);;
cout << "Testing only EthernetControl" << endl;
// lookup based on device name
//string dev("\\Device\\NPF_{F47ACE9E-1961-4A8E-BA14-2564E3764BFA}");
// lookup based on description
string dev("Intel(R) 82579LM Gigabit Network Connection");
EthernetControl *ec = new EthernetControl();
EthernetControl::set_device_active(dev,true);
EthernetControl::enumerate();
#if 0
set_logging_level(5);
int numDevices = get_numDevices();
cout << numDevices << " APS device" << (numDevices > 1 ? "s": "") << " found" << endl;
if (numDevices < 1)
return 0;
char s[] = "stdout";
set_log(s);
cout << "Attempting to initialize libaps" << endl;
init();
char serialBuffer[100];
for (int cnt; cnt < numDevices; cnt++) {
get_deviceSerial(cnt, serialBuffer);
cout << "Device " << cnt << " serial #: " << serialBuffer << endl;
}
int rc;
rc = connect_by_ID(0);
cout << "connect_by_ID(0) returned " << rc << endl;
cout << "Set sample rate " << endl;
set_sampleRate(0,100);
cout << "current PLL frequency = " << get_sampleRate(0) << " MHz" << endl;
cout << "setting trigger source = EXTERNAL" << endl;
set_trigger_source(0, EXTERNAL);
cout << "get trigger source returns " << ((get_trigger_source(0) == INTERNAL) ? "INTERNAL" : "EXTERNAL") << endl;
cout << "setting trigger source = INTERNAL" << endl;
set_trigger_source(0, INTERNAL);
cout << "get trigger source returns " << ((get_trigger_source(0) == INTERNAL) ? "INTERNAL" : "EXTERNAL") << endl;
cout << "get channel(0) enable: " << get_channel_enabled(0,0) << endl;
cout << "set channel(0) enabled = 1" << endl;
set_channel_enabled(0,0,true);
const int wfs = 1000;
short wf[wfs];
for (int cnt = 0; cnt < wfs; cnt++)
wf[cnt] = (cnt < wfs/2) ? 32767 : -32767;
cout << "loading waveform" << endl;
set_waveform_int(0, 0, wf, wfs);
cout << "Running" << endl;
set_sampleRate(0,50);
run(0);
std::this_thread::sleep_for(std::chrono::seconds(10));
cout << "Stopping" << endl;
stop(0);
set_channel_enabled(0,0,false);
cout << "get channel(0) enable: " << get_channel_enabled(0,0) << endl;
rc = disconnect_by_ID(0);
cout << "disconnect_by_ID(0) returned " << rc << endl;
#endif
return 0;
}<|endoftext|> |
<commit_before>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/internal/openssl_util.h"
#include "google/cloud/internal/base64_transforms.h"
#include <openssl/bio.h>
#include <openssl/buffer.h>
#include <openssl/evp.h>
#include <openssl/md5.h>
#include <openssl/opensslv.h>
#include <openssl/pem.h>
#include <memory>
namespace google {
namespace cloud {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace internal {
namespace {
// The name of the function to free an EVP_MD_CTX changed in OpenSSL 1.1.0.
#if (OPENSSL_VERSION_NUMBER < 0x10100000L) // Older than version 1.1.0.
inline std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_destroy)>
GetDigestCtx() {
return std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_destroy)>(
EVP_MD_CTX_create(), &EVP_MD_CTX_destroy);
};
#else
inline std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)> GetDigestCtx() {
return std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
EVP_MD_CTX_new(), &EVP_MD_CTX_free);
};
#endif
} // namespace
StatusOr<std::vector<std::uint8_t>> SignUsingSha256(
std::string const& str, std::string const& pem_contents) {
auto digest_ctx = GetDigestCtx();
if (!digest_ctx) {
return Status(StatusCode::kInvalidArgument,
"Invalid ServiceAccountCredentials: "
"could not create context for OpenSSL digest. ");
}
EVP_MD const* digest_type = EVP_sha256();
if (digest_type == nullptr) {
return Status(StatusCode::kInvalidArgument,
"Invalid ServiceAccountCredentials: "
"could not find specified digest in OpenSSL. ");
}
auto pem_buffer = std::unique_ptr<BIO, decltype(&BIO_free)>(
BIO_new_mem_buf(pem_contents.data(),
static_cast<int>(pem_contents.length())),
&BIO_free);
if (!pem_buffer) {
return Status(StatusCode::kInvalidArgument,
"Invalid ServiceAccountCredentials: "
"could not create PEM buffer. ");
}
auto private_key = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>(
PEM_read_bio_PrivateKey(
pem_buffer.get(),
nullptr, // EVP_PKEY **x
nullptr, // pem_password_cb *cb -- a custom callback.
// void *u -- this represents the password for the PEM (only
// applicable for formats such as PKCS12 (.p12 files) that use
// a password, which we don't currently support.
nullptr),
&EVP_PKEY_free);
if (!private_key) {
return Status(StatusCode::kInvalidArgument,
"Invalid ServiceAccountCredentials: "
"could not parse PEM to get private key ");
}
int const digest_sign_success_code = 1;
if (digest_sign_success_code !=
EVP_DigestSignInit(digest_ctx.get(),
nullptr, // `EVP_PKEY_CTX **pctx`
digest_type,
nullptr, // `ENGINE *e`
private_key.get())) {
return Status(StatusCode::kInvalidArgument,
"Invalid ServiceAccountCredentials: "
"could not initialize PEM digest. ");
}
if (digest_sign_success_code !=
EVP_DigestSignUpdate(digest_ctx.get(), str.data(), str.length())) {
return Status(StatusCode::kInvalidArgument,
"Invalid ServiceAccountCredentials: "
"could not update PEM digest. ");
}
std::size_t signed_str_size = 0;
// Calling this method with a nullptr buffer will populate our size var
// with the resulting buffer's size. This allows us to then call it again,
// with the correct buffer and size, which actually populates the buffer.
if (digest_sign_success_code !=
EVP_DigestSignFinal(digest_ctx.get(),
nullptr, // unsigned char *sig
&signed_str_size)) {
return Status(StatusCode::kInvalidArgument,
"Invalid ServiceAccountCredentials: "
"could not finalize PEM digest (1/2). ");
}
std::vector<unsigned char> signed_str(signed_str_size);
if (digest_sign_success_code != EVP_DigestSignFinal(digest_ctx.get(),
signed_str.data(),
&signed_str_size)) {
return Status(StatusCode::kInvalidArgument,
"Invalid ServiceAccountCredentials: "
"could not finalize PEM digest (2/2). ");
}
return StatusOr<std::vector<unsigned char>>(
{signed_str.begin(), signed_str.end()});
}
StatusOr<std::vector<std::uint8_t>> UrlsafeBase64Decode(
std::string const& str) {
if (str.empty()) return std::vector<std::uint8_t>{};
std::string b64str = str;
std::replace(b64str.begin(), b64str.end(), '-', '+');
std::replace(b64str.begin(), b64str.end(), '_', '/');
// To restore the padding there are only two cases:
// https://en.wikipedia.org/wiki/Base64#Decoding_Base64_without_padding
if (b64str.length() % 4 == 2) {
b64str.append("==");
} else if (b64str.length() % 4 == 3) {
b64str.append("=");
}
return Base64DecodeToBytes(b64str);
}
} // namespace internal
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace cloud
} // namespace google
<commit_msg>impl(rest): better errors in SignUsingSha256() (#8738)<commit_after>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/internal/openssl_util.h"
#include "google/cloud/internal/base64_transforms.h"
#include <openssl/bio.h>
#include <openssl/buffer.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/md5.h>
#include <openssl/opensslv.h>
#include <openssl/pem.h>
#include <algorithm>
#include <array>
#include <memory>
#include <type_traits>
namespace google {
namespace cloud {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
namespace internal {
namespace {
struct OpenSslDeleter {
void operator()(EVP_MD_CTX* ptr) {
// The name of the function to free an EVP_MD_CTX changed in OpenSSL 1.1.0.
#if (OPENSSL_VERSION_NUMBER < 0x10100000L) // Older than version 1.1.0.
EVP_MD_CTX_destroy(ptr);
#else
EVP_MD_CTX_free(ptr);
#endif
}
void operator()(EVP_PKEY* ptr) { EVP_PKEY_free(ptr); }
void operator()(BIO* ptr) { BIO_free(ptr); }
};
std::unique_ptr<EVP_MD_CTX, OpenSslDeleter> GetDigestCtx() {
// The name of the function to create an EVP_MD_CTX changed in OpenSSL 1.1.0.
#if (OPENSSL_VERSION_NUMBER < 0x10100000L) // Older than version 1.1.0.
return std::unique_ptr<EVP_MD_CTX, OpenSslDeleter>(EVP_MD_CTX_create());
#else
return std::unique_ptr<EVP_MD_CTX, OpenSslDeleter>(EVP_MD_CTX_new());
#endif
}
std::string CaptureSslErrors() {
std::string msg;
char const* sep = "";
while (auto code = ERR_get_error()) {
// OpenSSL guarantees that 256 bytes is enough:
// https://www.openssl.org/docs/man1.1.1/man3/ERR_error_string_n.html
// https://www.openssl.org/docs/man1.0.2/man3/ERR_error_string_n.html
// we could not find a macro or constant to replace the 256 literal.
auto constexpr kMaxOpenSslErrorLength = 256;
std::array<char, kMaxOpenSslErrorLength> buf{};
ERR_error_string_n(code, buf.data(), buf.size());
msg += sep;
msg += buf.data();
sep = ", ";
}
return msg;
}
} // namespace
StatusOr<std::vector<std::uint8_t>> SignUsingSha256(
std::string const& str, std::string const& pem_contents) {
ERR_clear_error();
auto pem_buffer = std::unique_ptr<BIO, OpenSslDeleter>(BIO_new_mem_buf(
pem_contents.data(), static_cast<int>(pem_contents.length())));
if (!pem_buffer) {
return Status(StatusCode::kInvalidArgument,
"Invalid ServiceAccountCredentials - "
"could not create PEM buffer: " +
CaptureSslErrors());
}
auto private_key =
std::unique_ptr<EVP_PKEY, OpenSslDeleter>(PEM_read_bio_PrivateKey(
pem_buffer.get(),
nullptr, // EVP_PKEY **x
nullptr, // pem_password_cb *cb -- a custom callback.
// void *u -- this represents the password for the PEM (only
// applicable for formats such as PKCS12 (.p12 files) that use
// a password, which we don't currently support.
nullptr));
if (!private_key) {
return Status(StatusCode::kInvalidArgument,
"Invalid ServiceAccountCredentials - "
"could not parse PEM to get private key: " +
CaptureSslErrors());
}
auto digest_ctx = GetDigestCtx();
if (!digest_ctx) {
return Status(StatusCode::kInvalidArgument,
"Invalid ServiceAccountCredentials - "
"could not create context for OpenSSL digest: " +
CaptureSslErrors());
}
auto constexpr kOpenSslSuccess = 1;
if (EVP_DigestSignInit(digest_ctx.get(), nullptr, EVP_sha256(), nullptr,
private_key.get()) != kOpenSslSuccess) {
return Status(StatusCode::kInvalidArgument,
"Invalid ServiceAccountCredentials - "
"could not initialize signing digest: " +
CaptureSslErrors());
}
if (EVP_DigestSignUpdate(digest_ctx.get(), str.data(), str.size()) !=
kOpenSslSuccess) {
return Status(StatusCode::kInvalidArgument,
"Invalid ServiceAccountCredentials - could not sign blob: " +
CaptureSslErrors());
}
// The signed SHA256 size depends on the size (the experts say "modulus") of
// they key. First query the size:
std::size_t actual_len = 0;
if (EVP_DigestSignFinal(digest_ctx.get(), nullptr, &actual_len) !=
kOpenSslSuccess) {
return Status(StatusCode::kInvalidArgument,
"Invalid ServiceAccountCredentials - could not sign blob: " +
CaptureSslErrors());
}
// Then compute the actual signed digest. Note that OpenSSL requires a
// `unsigned char*` buffer, so we feed it that.
std::vector<unsigned char> buffer(actual_len);
if (EVP_DigestSignFinal(digest_ctx.get(), buffer.data(), &actual_len) !=
kOpenSslSuccess) {
return Status(StatusCode::kInvalidArgument,
"Invalid ServiceAccountCredentials - could not sign blob: " +
CaptureSslErrors());
}
return StatusOr<std::vector<std::uint8_t>>(
{buffer.begin(), std::next(buffer.begin(), actual_len)});
}
StatusOr<std::vector<std::uint8_t>> UrlsafeBase64Decode(
std::string const& str) {
if (str.empty()) return std::vector<std::uint8_t>{};
std::string b64str = str;
std::replace(b64str.begin(), b64str.end(), '-', '+');
std::replace(b64str.begin(), b64str.end(), '_', '/');
// To restore the padding there are only two cases:
// https://en.wikipedia.org/wiki/Base64#Decoding_Base64_without_padding
if (b64str.length() % 4 == 2) {
b64str.append("==");
} else if (b64str.length() % 4 == 3) {
b64str.append("=");
}
return Base64DecodeToBytes(b64str);
}
} // namespace internal
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace cloud
} // namespace google
<|endoftext|> |
<commit_before>// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/internal/rest_request.h"
#include "google/cloud/log.h"
namespace google {
namespace cloud {
namespace rest_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
RestRequest::RestRequest() = default;
RestRequest::RestRequest(std::string path) : path_(std::move(path)) {}
RestRequest::RestRequest(std::string path, HttpHeaders headers)
: path_(std::move(path)), headers_(std::move(headers)) {}
RestRequest::RestRequest(std::string path, HttpParameters parameters)
: path_(std::move(path)), parameters_(std::move(parameters)) {}
RestRequest::RestRequest(std::string path, HttpHeaders headers,
HttpParameters parameters)
: path_(std::move(path)),
headers_(std::move(headers)),
parameters_(std::move(parameters)) {}
RestRequest& RestRequest::SetPath(std::string path) & {
path_ = std::move(path);
return *this;
}
RestRequest& RestRequest::AddHeader(std::string header, std::string value) & {
std::transform(header.begin(), header.end(), header.begin(),
[](unsigned char c) { return std::tolower(c); });
auto iter = headers_.find(header);
if (iter == headers_.end()) {
std::vector<std::string> v = {std::move(value)};
headers_.emplace(std::move(header), std::move(v));
} else {
iter->second.push_back(value);
}
return *this;
}
RestRequest& RestRequest::AddHeader(
std::pair<std::string, std::string> header) & {
return AddHeader(std::move(header.first), std::move(header.second));
}
RestRequest& RestRequest::AddQueryParameter(std::string parameter,
std::string value) & {
parameters_.emplace_back(std::move(parameter), std::move(value));
return *this;
}
RestRequest& RestRequest::AddQueryParameter(
std::pair<std::string, std::string> parameter) & {
return AddQueryParameter(std::move(parameter.first),
std::move(parameter.second));
}
std::vector<std::string> RestRequest::GetHeader(std::string header) const {
std::transform(header.begin(), header.end(), header.begin(),
[](unsigned char c) { return std::tolower(c); });
auto iter = headers_.find(header);
if (iter == headers_.end()) {
return {};
}
return iter->second;
}
std::vector<std::string> RestRequest::GetQueryParameter(
std::string const& parameter) const {
std::vector<std::string> parameter_values;
for (auto const& p : parameters_) {
if (p.first == parameter) {
parameter_values.push_back(p.second);
}
}
return parameter_values;
}
bool operator==(RestRequest const& lhs, RestRequest const& rhs) {
return (lhs.path_ == rhs.path_) && (lhs.headers_ == rhs.headers_) &&
(lhs.parameters_ == rhs.parameters_);
}
bool operator!=(RestRequest const& lhs, RestRequest const& rhs) {
return !(lhs == rhs);
}
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace rest_internal
} // namespace cloud
} // namespace google
<commit_msg>fix(rest): add missing include for std::tolower (#8196)<commit_after>// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/internal/rest_request.h"
#include "google/cloud/log.h"
#include <cctype>
namespace google {
namespace cloud {
namespace rest_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
RestRequest::RestRequest() = default;
RestRequest::RestRequest(std::string path) : path_(std::move(path)) {}
RestRequest::RestRequest(std::string path, HttpHeaders headers)
: path_(std::move(path)), headers_(std::move(headers)) {}
RestRequest::RestRequest(std::string path, HttpParameters parameters)
: path_(std::move(path)), parameters_(std::move(parameters)) {}
RestRequest::RestRequest(std::string path, HttpHeaders headers,
HttpParameters parameters)
: path_(std::move(path)),
headers_(std::move(headers)),
parameters_(std::move(parameters)) {}
RestRequest& RestRequest::SetPath(std::string path) & {
path_ = std::move(path);
return *this;
}
RestRequest& RestRequest::AddHeader(std::string header, std::string value) & {
std::transform(header.begin(), header.end(), header.begin(),
[](unsigned char c) { return std::tolower(c); });
auto iter = headers_.find(header);
if (iter == headers_.end()) {
std::vector<std::string> v = {std::move(value)};
headers_.emplace(std::move(header), std::move(v));
} else {
iter->second.push_back(value);
}
return *this;
}
RestRequest& RestRequest::AddHeader(
std::pair<std::string, std::string> header) & {
return AddHeader(std::move(header.first), std::move(header.second));
}
RestRequest& RestRequest::AddQueryParameter(std::string parameter,
std::string value) & {
parameters_.emplace_back(std::move(parameter), std::move(value));
return *this;
}
RestRequest& RestRequest::AddQueryParameter(
std::pair<std::string, std::string> parameter) & {
return AddQueryParameter(std::move(parameter.first),
std::move(parameter.second));
}
std::vector<std::string> RestRequest::GetHeader(std::string header) const {
std::transform(header.begin(), header.end(), header.begin(),
[](unsigned char c) { return std::tolower(c); });
auto iter = headers_.find(header);
if (iter == headers_.end()) {
return {};
}
return iter->second;
}
std::vector<std::string> RestRequest::GetQueryParameter(
std::string const& parameter) const {
std::vector<std::string> parameter_values;
for (auto const& p : parameters_) {
if (p.first == parameter) {
parameter_values.push_back(p.second);
}
}
return parameter_values;
}
bool operator==(RestRequest const& lhs, RestRequest const& rhs) {
return (lhs.path_ == rhs.path_) && (lhs.headers_ == rhs.headers_) &&
(lhs.parameters_ == rhs.parameters_);
}
bool operator!=(RestRequest const& lhs, RestRequest const& rhs) {
return !(lhs == rhs);
}
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace rest_internal
} // namespace cloud
} // namespace google
<|endoftext|> |
<commit_before>// Copyright (c) 2021 Kingsley Chen <kingsamchen at gmail dot com>
// This file is subject to the terms of license that can be found
// in the LICENSE file.
#include <algorithm>
#include <deque>
#include <functional>
#include <memory>
#include <string>
#include <string_view>
#include <thread>
#include <unordered_map>
#include <Windows.h>
#include "spdlog/fmt/fmt.h"
#include "spdlog/sinks/basic_file_sink.h"
#include "spdlog/spdlog.h"
#include "himsw/labor_monitor.h"
#include "himsw/resource.h"
#include "himsw/tray.h"
#include "himsw/win_last_error.h"
namespace {
template<typename T>
void ignore_result(T&&) {}
template<typename Iter>
std::string join_string(Iter begin, Iter end, std::string_view sep) {
if (begin == end) {
return std::string{};
}
std::string str(*begin);
for (auto it = begin + 1; it != end; ++it) {
str.append(sep.data(), sep.length()).append(*it);
}
return str;
}
std::string now_in_date() {
auto tp = std::time(nullptr);
struct tm tm;
localtime_s(&tm, &tp);
std::ostringstream oss;
oss << std::put_time(&tm, "%Y-%m-%d %H:%M:%S ");
return oss.str();
}
class dialog_window;
class dialog_window_manager {
public:
~dialog_window_manager() = default;
dialog_window_manager(const dialog_window_manager&) = delete;
dialog_window_manager(dialog_window_manager&&) = delete;
dialog_window_manager& operator=(const dialog_window_manager&) = delete;
dialog_window_manager& operator=(dialog_window_manager&&) = delete;
static dialog_window_manager& instance() {
static dialog_window_manager instance;
return instance;
}
void enroll(HWND hwnd, dialog_window* ptr) {
dlg_table_[hwnd] = ptr;
}
void unroll(HWND hwnd) {
dlg_table_.erase(hwnd);
if (dlg_table_.empty()) {
PostQuitMessage(0);
}
}
bool any_dialog_message_processed(MSG* msg) {
return std::any_of(dlg_table_.begin(), dlg_table_.end(), [msg](auto& entry) {
return ::IsDialogMessageW(entry.first, msg) == TRUE;
});
}
static INT_PTR dialog_proc(HWND dlg, UINT msg, WPARAM wparam, LPARAM lparam);
private:
dialog_window_manager() = default;
private:
std::unordered_map<HWND, dialog_window*> dlg_table_;
};
class dialog_window {
struct passkey {
explicit passkey() = default;
};
public:
~dialog_window() = default;
dialog_window(const dialog_window&) = delete;
dialog_window(dialog_window&&) = delete;
dialog_window& operator=(const dialog_window&) = delete;
dialog_window& operator=(dialog_window&&) = delete;
static std::shared_ptr<dialog_window> make() {
auto window = std::make_shared<dialog_window>(passkey{});
dialog_window_manager::instance().enroll(window->dlg_, window.get());
window->show();
return window;
}
explicit dialog_window(passkey) {
auto instance = ::GetModuleHandleW(nullptr);
dlg_ = ::CreateDialogParamW(instance,
MAKEINTRESOURCE(IDD_DLGMAIN),
nullptr,
&dialog_window_manager::dialog_proc,
0);
if (!dlg_) {
throw himsw::win_last_error("Failed to create dialog window");
}
::SetTimer(dlg_, IDT_TIMER, 1000 * 10, nullptr);
// Leak on purpose
auto hicon = ::LoadIconW(instance, MAKEINTRESOURCE(IDI_ICON));
if (!hicon) {
throw himsw::win_last_error("Failed to load application icon");
}
tray_ = std::make_unique<himsw::tray>(dlg_, IDI_ICON, hicon, k_tray_msgid, L"himsw");
events_[WM_CLOSE] = [this](WPARAM, LPARAM) {
on_close();
};
events_[WM_SIZE] = [this](WPARAM wparam, LPARAM) {
if (wparam == SIZE_MINIMIZED) {
on_minimized();
}
};
events_[WM_TIMER] = [this](WPARAM, LPARAM) {
// currently only one timer.
on_timer();
};
events_[k_tray_msgid] = [this](WPARAM wparam, LPARAM lparam) {
auto icon_id = static_cast<UINT>(wparam);
auto mouse_msg = static_cast<UINT>(lparam);
if (icon_id == IDI_ICON) {
on_tray_icon(mouse_msg);
}
};
}
void show(bool visible = true) {
auto cmd = visible ? SW_SHOWNORMAL : SW_HIDE;
::ShowWindow(dlg_, cmd);
visible_ = visible;
}
bool visible() const noexcept {
return visible_;
}
bool try_process_event(int event_id, WPARAM wparam, LPARAM lparam) {
auto entry = events_.find(event_id);
if (entry == events_.end()) {
return false;
}
entry->second(wparam, lparam);
return true;
}
void update_info(const std::string& msg) {
msgs_.push_front(now_in_date() + msg);
if (msgs_.size() > k_max_kept_msgs) {
msgs_.pop_back();
}
auto text = join_string(msgs_.begin(), msgs_.end(), "\r\n");
::SetDlgItemTextA(dlg_, IDC_MSG, text.c_str());
}
private:
void on_close() {
tray_ = nullptr;
::KillTimer(dlg_, IDT_TIMER);
::DestroyWindow(dlg_);
dialog_window_manager::instance().unroll(dlg_);
}
void on_minimized() {
show(!visible());
}
void on_timer() {
himsw::labor_monitor::instance().tick();
}
void on_tray_icon(UINT mouse_msg) {
switch (mouse_msg) {
case WM_LBUTTONDBLCLK:
show(!visible());
break;
default:
break;
}
}
private:
HWND dlg_{nullptr};
bool visible_{false};
std::unordered_map<int, std::function<void(WPARAM, LPARAM)>> events_;
std::unique_ptr<himsw::tray> tray_;
std::deque<std::string> msgs_;
static constexpr size_t k_max_kept_msgs{10};
static constexpr int k_tray_msgid{WM_USER + 10};
};
INT_PTR dialog_window_manager::dialog_proc(HWND dlg, UINT msg, WPARAM wparam, LPARAM lparam) {
auto& mgr = dialog_window_manager::instance();
auto it = mgr.dlg_table_.find(dlg);
if (it != mgr.dlg_table_.end() && it->second->try_process_event(msg, wparam, lparam)) {
return TRUE;
}
return FALSE;
}
class main_loop {
public:
main_loop() = default;
~main_loop() = default;
main_loop(const main_loop&) = delete;
main_loop(main_loop&&) = delete;
main_loop& operator=(const main_loop&) = delete;
main_loop& operator=(main_loop&&) = delete;
void run() {
MSG msg;
while (::GetMessageW(&msg, nullptr, 0, 0) != 0) {
if (!dialog_window_manager::instance().any_dialog_message_processed(&msg)) {
::TranslateMessage(&msg);
::DispatchMessageW(&msg);
}
}
}
};
} // namespace
int WINAPI wWinMain(HINSTANCE, HINSTANCE, PWSTR, int) {
constexpr int critical_failure = 1;
::SetProcessDPIAware();
try {
spdlog::set_default_logger(spdlog::basic_logger_mt("main_logger", "himsw.log", true));
himsw::labor_monitor::instance().prepare();
auto main_window = dialog_window::make();
himsw::labor_monitor::instance().set_info_update_handler(
[ptr = std::weak_ptr(main_window)](const std::string& msg) {
if (auto wnd = ptr.lock(); wnd) {
wnd->update_info(msg);
}
});
main_loop loop;
loop.run();
} catch (const spdlog::spdlog_ex& ex) {
auto reason = fmt::format("Failed to initialize logging component; ex={}", ex.what());
::MessageBoxA(nullptr, reason.c_str(), "Error", MB_ICONERROR);
return critical_failure;
} catch (const himsw::win_last_error& ex) {
const std::string cause = "Failed to prepare the labor monitor";
spdlog::error("{}; ex={} ec={}", cause, ex.what(), ex.error_code());
::MessageBoxA(nullptr, cause.c_str(), "Error", MB_ICONERROR);
return critical_failure;
}
return 0;
}
<commit_msg>himsw: don't truncate old logs<commit_after>// Copyright (c) 2021 Kingsley Chen <kingsamchen at gmail dot com>
// This file is subject to the terms of license that can be found
// in the LICENSE file.
#include <algorithm>
#include <deque>
#include <functional>
#include <memory>
#include <string>
#include <string_view>
#include <thread>
#include <unordered_map>
#include <Windows.h>
#include "spdlog/fmt/fmt.h"
#include "spdlog/sinks/basic_file_sink.h"
#include "spdlog/spdlog.h"
#include "himsw/labor_monitor.h"
#include "himsw/resource.h"
#include "himsw/tray.h"
#include "himsw/win_last_error.h"
namespace {
template<typename T>
void ignore_result(T&&) {}
template<typename Iter>
std::string join_string(Iter begin, Iter end, std::string_view sep) {
if (begin == end) {
return std::string{};
}
std::string str(*begin);
for (auto it = begin + 1; it != end; ++it) {
str.append(sep.data(), sep.length()).append(*it);
}
return str;
}
std::string now_in_date() {
auto tp = std::time(nullptr);
struct tm tm;
localtime_s(&tm, &tp);
std::ostringstream oss;
oss << std::put_time(&tm, "%Y-%m-%d %H:%M:%S ");
return oss.str();
}
class dialog_window;
class dialog_window_manager {
public:
~dialog_window_manager() = default;
dialog_window_manager(const dialog_window_manager&) = delete;
dialog_window_manager(dialog_window_manager&&) = delete;
dialog_window_manager& operator=(const dialog_window_manager&) = delete;
dialog_window_manager& operator=(dialog_window_manager&&) = delete;
static dialog_window_manager& instance() {
static dialog_window_manager instance;
return instance;
}
void enroll(HWND hwnd, dialog_window* ptr) {
dlg_table_[hwnd] = ptr;
}
void unroll(HWND hwnd) {
dlg_table_.erase(hwnd);
if (dlg_table_.empty()) {
PostQuitMessage(0);
}
}
bool any_dialog_message_processed(MSG* msg) {
return std::any_of(dlg_table_.begin(), dlg_table_.end(), [msg](auto& entry) {
return ::IsDialogMessageW(entry.first, msg) == TRUE;
});
}
static INT_PTR dialog_proc(HWND dlg, UINT msg, WPARAM wparam, LPARAM lparam);
private:
dialog_window_manager() = default;
private:
std::unordered_map<HWND, dialog_window*> dlg_table_;
};
class dialog_window {
struct passkey {
explicit passkey() = default;
};
public:
~dialog_window() = default;
dialog_window(const dialog_window&) = delete;
dialog_window(dialog_window&&) = delete;
dialog_window& operator=(const dialog_window&) = delete;
dialog_window& operator=(dialog_window&&) = delete;
static std::shared_ptr<dialog_window> make() {
auto window = std::make_shared<dialog_window>(passkey{});
dialog_window_manager::instance().enroll(window->dlg_, window.get());
window->show();
return window;
}
explicit dialog_window(passkey) {
auto instance = ::GetModuleHandleW(nullptr);
dlg_ = ::CreateDialogParamW(instance,
MAKEINTRESOURCE(IDD_DLGMAIN),
nullptr,
&dialog_window_manager::dialog_proc,
0);
if (!dlg_) {
throw himsw::win_last_error("Failed to create dialog window");
}
::SetTimer(dlg_, IDT_TIMER, 1000 * 10, nullptr);
// Leak on purpose
auto hicon = ::LoadIconW(instance, MAKEINTRESOURCE(IDI_ICON));
if (!hicon) {
throw himsw::win_last_error("Failed to load application icon");
}
tray_ = std::make_unique<himsw::tray>(dlg_, IDI_ICON, hicon, k_tray_msgid, L"himsw");
events_[WM_CLOSE] = [this](WPARAM, LPARAM) {
on_close();
};
events_[WM_SIZE] = [this](WPARAM wparam, LPARAM) {
if (wparam == SIZE_MINIMIZED) {
on_minimized();
}
};
events_[WM_TIMER] = [this](WPARAM, LPARAM) {
// currently only one timer.
on_timer();
};
events_[k_tray_msgid] = [this](WPARAM wparam, LPARAM lparam) {
auto icon_id = static_cast<UINT>(wparam);
auto mouse_msg = static_cast<UINT>(lparam);
if (icon_id == IDI_ICON) {
on_tray_icon(mouse_msg);
}
};
}
void show(bool visible = true) {
auto cmd = visible ? SW_SHOWNORMAL : SW_HIDE;
::ShowWindow(dlg_, cmd);
visible_ = visible;
}
bool visible() const noexcept {
return visible_;
}
bool try_process_event(int event_id, WPARAM wparam, LPARAM lparam) {
auto entry = events_.find(event_id);
if (entry == events_.end()) {
return false;
}
entry->second(wparam, lparam);
return true;
}
void update_info(const std::string& msg) {
msgs_.push_front(now_in_date() + msg);
if (msgs_.size() > k_max_kept_msgs) {
msgs_.pop_back();
}
auto text = join_string(msgs_.begin(), msgs_.end(), "\r\n");
::SetDlgItemTextA(dlg_, IDC_MSG, text.c_str());
}
private:
void on_close() {
tray_ = nullptr;
::KillTimer(dlg_, IDT_TIMER);
::DestroyWindow(dlg_);
dialog_window_manager::instance().unroll(dlg_);
}
void on_minimized() {
show(!visible());
}
void on_timer() {
himsw::labor_monitor::instance().tick();
}
void on_tray_icon(UINT mouse_msg) {
switch (mouse_msg) {
case WM_LBUTTONDBLCLK:
show(!visible());
break;
default:
break;
}
}
private:
HWND dlg_{nullptr};
bool visible_{false};
std::unordered_map<int, std::function<void(WPARAM, LPARAM)>> events_;
std::unique_ptr<himsw::tray> tray_;
std::deque<std::string> msgs_;
static constexpr size_t k_max_kept_msgs{10};
static constexpr int k_tray_msgid{WM_USER + 10};
};
INT_PTR dialog_window_manager::dialog_proc(HWND dlg, UINT msg, WPARAM wparam, LPARAM lparam) {
auto& mgr = dialog_window_manager::instance();
auto it = mgr.dlg_table_.find(dlg);
if (it != mgr.dlg_table_.end() && it->second->try_process_event(msg, wparam, lparam)) {
return TRUE;
}
return FALSE;
}
class main_loop {
public:
main_loop() = default;
~main_loop() = default;
main_loop(const main_loop&) = delete;
main_loop(main_loop&&) = delete;
main_loop& operator=(const main_loop&) = delete;
main_loop& operator=(main_loop&&) = delete;
void run() {
MSG msg;
while (::GetMessageW(&msg, nullptr, 0, 0) != 0) {
if (!dialog_window_manager::instance().any_dialog_message_processed(&msg)) {
::TranslateMessage(&msg);
::DispatchMessageW(&msg);
}
}
}
};
} // namespace
int WINAPI wWinMain(HINSTANCE, HINSTANCE, PWSTR, int) {
constexpr int critical_failure = 1;
::SetProcessDPIAware();
try {
spdlog::set_default_logger(spdlog::basic_logger_mt("main_logger", "himsw.log"));
himsw::labor_monitor::instance().prepare();
auto main_window = dialog_window::make();
himsw::labor_monitor::instance().set_info_update_handler(
[ptr = std::weak_ptr(main_window)](const std::string& msg) {
if (auto wnd = ptr.lock(); wnd) {
wnd->update_info(msg);
}
});
main_loop loop;
loop.run();
} catch (const spdlog::spdlog_ex& ex) {
auto reason = fmt::format("Failed to initialize logging component; ex={}", ex.what());
::MessageBoxA(nullptr, reason.c_str(), "Error", MB_ICONERROR);
return critical_failure;
} catch (const himsw::win_last_error& ex) {
const std::string cause = "Failed to prepare the labor monitor";
spdlog::error("{}; ex={} ec={}", cause, ex.what(), ex.error_code());
::MessageBoxA(nullptr, cause.c_str(), "Error", MB_ICONERROR);
return critical_failure;
}
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Deflate axis (#8760)<commit_after><|endoftext|> |
<commit_before>#include <iostream>
#include <cctype>
#ifndef DEBUG
//#define DEBUG
#endif // DEBUG
#define exit_failure() std::cout << "INVALID" << std::endl; \
exit(1);
// check binary operations
bool isbinop(const char & c){
return (c=='+' || c=='*' || c=='/');
}
// check letters and points
void validate(const char* str){
if (*(str+std::strlen(str)-1) == '-' || isbinop(*str+std::strlen(str)-1)){
exit_failure();
}
while (*str){
if (std::isalpha(*str)){
exit_failure();
}
if (*str=='.'){
exit_failure();
}
str++;
}
}
// remove spaces
void skip_space(char * str){
while (*str != ' ' && *str != 0) {
str++;
}
char* p = str;
while (*str == ' ') {
str++;
}
for(*p = *str; *str != 0;){
if (*++str != ' ') *++p = *str;
}
}
// number with sign
int prim(const char*& str){
int sign = 1;
if (*str == '-'){
if (*(str+1) == '-'){
exit_failure();
}
sign = -1;
str++;
}
int result = *str - '0';
while(*(str+1) != '\n' && std::isdigit(*(str+1))){
result = result * 10 + (*++str - '0');
}
#ifdef DEBUG
std::cout << "Number values: " << sign * result << std::endl;
#endif
return sign * result;
}
// term value
int term(const char*& str){
int result = prim(str);
str++;
while(*str != '\n'){
char c = *str;
if (c=='*' || c=='/'){
str++;
if (!isbinop(*str)){
if (c == '/') result /= prim(str);
if (c == '*') result *= prim(str);
str++;
}else{
exit_failure();
}
}
else break;
}
if (*str!='\n')
str--;
#ifdef DEBUG
std::cout << "Transitional term values: " << result << ", " << std::endl;
#endif
return result;
}
int _expr(const char*& str){
int result = term(str);
str++;
while(*str!='\n'){
char c = *str;
if (c=='+' || c=='-'){
str++;
if (!isbinop(*str)){
if (c == '+') result += term(str);
if (c == '-') result -= term(str);
str++;
}else{
exit_failure();
}
}
else break;
}
return result;
}
int expr(char* str){
skip_space(str);
const char * cstr = str;
validate(cstr);
return _expr(cstr);
}
int main(int argc, char * argv[]){
if (argc < 2){
std::cout << "INPUT_FAILURE";
return -1;
}
std::cout << expr(argv[1]) << std::endl;
return 0;
}<commit_msg>div zero fixed<commit_after>#include <iostream>
#include <cctype>
#ifndef DEBUG
//#define DEBUG
#endif // DEBUG
#define exit_failure() std::cout << "INVALID" << std::endl; \
exit(1);
// check binary operations
bool isbinop(const char & c){
return (c=='+' || c=='*' || c=='/');
}
// check letters and points
void validate(const char* str){
if (*(str+std::strlen(str)-1) == '-' || isbinop(*str+std::strlen(str)-1)){
exit_failure();
}
while (*str){
if (std::isalpha(*str)){
exit_failure();
}
if (*str=='.'){
exit_failure();
}
str++;
}
}
// remove spaces
void skip_space(char * str){
while (*str != ' ' && *str != 0) {
str++;
}
char* p = str;
while (*str == ' ') {
str++;
}
for(*p = *str; *str != 0;){
if (*++str != ' ') *++p = *str;
}
}
// number with sign
int prim(const char*& str){
int sign = 1;
if (*str == '-'){
if (*(str+1) == '-'){
exit_failure();
}
sign = -1;
str++;
}
int result = *str - '0';
while(*(str+1) != '\n' && std::isdigit(*(str+1))){
result = result * 10 + (*++str - '0');
}
#ifdef DEBUG
std::cout << "Number values: " << sign * result << std::endl;
#endif
return sign * result;
}
// term value
int term(const char*& str){
int result = prim(str);
str++;
while(*str != '\n'){
char c = *str;
if (c=='*' || c=='/'){
str++;
if (!isbinop(*str)){
if (c == '/') {
int value = prim(str);
if (value != 0){
result /= prim(str);
}
else{
exit_failure();
}
}
if (c == '*') result *= prim(str);
str++;
}else{
exit_failure();
}
}
else break;
}
if (*str!='\n')
str--;
#ifdef DEBUG
std::cout << "Transitional term values: " << result << ", " << std::endl;
#endif
return result;
}
int _expr(const char*& str){
int result = term(str);
str++;
while(*str!='\n'){
char c = *str;
if (c=='+' || c=='-'){
str++;
if (!isbinop(*str)){
if (c == '+') result += term(str);
if (c == '-') result -= term(str);
str++;
}else{
exit_failure();
}
}
else break;
}
return result;
}
int expr(char* str){
skip_space(str);
const char * cstr = str;
validate(cstr);
return _expr(cstr);
}
int main(int argc, char * argv[]){
if (argc < 2){
std::cout << "INPUT_FAILURE";
return -1;
}
std::cout << expr(argv[1]) << std::endl;
return 0;
}<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include "core/posix.hh"
#include "core/vla.hh"
#include "core/reactor.hh"
#include "core/future-util.hh"
#include "core/stream.hh"
#include "core/circular_buffer.hh"
#include "core/align.hh"
#include <atomic>
#include <list>
#include <queue>
#include <fcntl.h>
#include <linux/if_tun.h>
#include "ip.hh"
#include "net/native-stack.hh"
#include <xen/xen.h>
#include <xen/memory.h>
#include <xen/sys/gntalloc.h>
#include "core/xen/xenstore.hh"
#include "core/xen/evtchn.hh"
#include "xenfront.hh"
#include <unordered_set>
using namespace net;
namespace xen {
using phys = uint64_t;
class xenfront_device : public device {
public:
xenstore* _xenstore = xenstore::instance();
private:
net::hw_features _hw_features;
ethernet_address _hw_address;
std::string _device_str;
public:
bool _userspace;
public:
xenfront_device(boost::program_options::variables_map opts, bool userspace)
: _hw_address(net::parse_ethernet_address(_xenstore->read(path("mac"))))
, _device_str("device/vif/" + std::to_string(opts["vif"].as<unsigned>()))
, _userspace(userspace) {
_hw_features.rx_csum_offload = true;
_hw_features.tx_csum_l4_offload = true;
}
std::string path(std::string s) { return _device_str + "/" + s; }
ethernet_address hw_address() override {
return _hw_address;
}
net::hw_features hw_features() override {
return _hw_features;
}
virtual std::unique_ptr<qp> init_local_queue(boost::program_options::variables_map opts, uint16_t qid) override;
};
class xenfront_qp : public net::qp {
private:
xenfront_device* _dev;
unsigned _otherend;
std::string _backend;
gntalloc *_gntalloc;
evtchn *_evtchn;
port _tx_evtchn;
port _rx_evtchn;
front_ring<tx> _tx_ring;
front_ring<rx> _rx_ring;
grant_head *_tx_refs;
grant_head *_rx_refs;
std::unordered_map<std::string, int> _features;
static std::unordered_map<std::string, std::string> _supported_features;
port bind_tx_evtchn(bool split);
port bind_rx_evtchn(bool split);
future<> alloc_rx_references();
future<> handle_tx_completions();
future<> queue_rx_packet();
void alloc_one_rx_reference(unsigned id);
std::string path(std::string s) { return _dev->path(s); }
public:
explicit xenfront_qp(xenfront_device* dev, boost::program_options::variables_map opts);
~xenfront_qp();
virtual void rx_start() override;
virtual future<> send(packet p) override;
};
std::unordered_map<std::string, std::string>
xenfront_qp::_supported_features = {
{ "feature-split-event-channels", "feature-split-event-channels" },
{ "feature-rx-copy", "request-rx-copy" }
};
void
xenfront_qp::rx_start() {
keep_doing([this] {
return _rx_evtchn.pending().then([this] {
return queue_rx_packet();
});
});
}
future<>
xenfront_qp::send(packet _p) {
uint32_t frag = 0;
// There doesn't seem to be a way to tell xen, when using the userspace
// drivers, to map a particular page. Therefore, the only alternative
// here is to copy. All pages shared must come from the gntalloc mmap.
//
// A better solution could be to change the packet allocation path to
// use a pre-determined page for data.
//
// In-kernel should be fine
// FIXME: negotiate and use scatter/gather
_p.linearize();
return _tx_ring.entries.has_room().then([this, p = std::move(_p), frag] () mutable {
auto req_prod = _tx_ring._sring->req_prod;
auto f = p.frag(frag);
auto ref = _tx_refs->new_ref(f.base, f.size);
unsigned idx = _tx_ring.entries.get_index();
assert(!_tx_ring.entries[idx]);
_tx_ring.entries[idx] = ref;
auto req = &_tx_ring._sring->_ring[idx].req;
req->gref = ref.xen_id;
req->offset = 0;
req->flags = {};
if (p.offload_info().protocol != ip_protocol_num::unused) {
req->flags.csum_blank = true;
req->flags.data_validated = true;
} else {
req->flags.data_validated = true;
}
req->id = idx;
req->size = f.size;
_tx_ring.req_prod_pvt = idx;
_tx_ring._sring->req_prod = req_prod + 1;
_tx_ring._sring->req_event++;
if ((frag + 1) == p.nr_frags()) {
_tx_evtchn.notify();
return make_ready_future<>();
} else {
return make_ready_future<>();
}
});
// FIXME: Don't forget to clear all grant refs when frontend closes. Or is it automatic?
}
#define rmb() asm volatile("lfence":::"memory");
#define wmb() asm volatile("":::"memory");
template <typename T>
future<> front_ring<T>::entries::has_room() {
return _available.wait();
}
template <typename T>
void front_ring<T>::entries::free_index(unsigned id) {
_available.signal();
}
template <typename T>
unsigned front_ring<T>::entries::get_index() {
return front_ring<T>::idx(_next_idx++);
}
template <typename T>
void front_ring<T>::process_ring(std::function<bool (gntref &entry, T& el)> func, grant_head *refs)
{
auto prod = _sring->rsp_prod;
rmb();
for (unsigned i = rsp_cons; i != prod; i++) {
auto el = _sring->_ring[idx(i)];
if (el.rsp.status < 0) {
dump("Packet error", el.rsp);
continue;
}
auto& entry = entries[i];
if (!func(entry, el)) {
continue;
}
assert(entry.xen_id >= 0);
refs->free_ref(entry);
entries.free_index(i);
prod = _sring->rsp_prod;
}
rsp_cons = prod;
_sring->rsp_event = prod + 1;
}
future<> xenfront_qp::queue_rx_packet()
{
uint64_t bunch;
_rx_ring.process_ring([this, &bunch] (gntref &entry, rx &rx) mutable {
packet p(static_cast<char *>(entry.page) + rx.rsp.offset, rx.rsp.status);
_dev->l2receive(std::move(p));
bunch++;
return true;
}, _rx_refs);
_stats.rx.good.update_pkts_bunch(bunch);
return make_ready_future<>();
}
void xenfront_qp::alloc_one_rx_reference(unsigned index) {
_rx_ring.entries[index] = _rx_refs->new_ref();
// This is how the backend knows where to put data.
auto req = &_rx_ring._sring->_ring[index].req;
req->id = index;
req->gref = _rx_ring.entries[index].xen_id;
}
future<> xenfront_qp::alloc_rx_references() {
return _rx_ring.entries.has_room().then([this] () {
unsigned i = _rx_ring.entries.get_index();
auto req_prod = _rx_ring.req_prod_pvt;
alloc_one_rx_reference(i);
++req_prod;
_rx_ring.req_prod_pvt = req_prod;
wmb();
_rx_ring._sring->req_prod = req_prod;
/* ready */
_rx_evtchn.notify();
});
}
future<> xenfront_qp::handle_tx_completions() {
_tx_ring.process_ring([this] (gntref &entry, tx &tx) {
if (tx.rsp.status == 1) {
return false;
}
if (tx.rsp.status != 0) {
_tx_ring.dump("TX positive packet error", tx.rsp);
return false;
}
return true;
}, _tx_refs);
return make_ready_future<>();
}
port xenfront_qp::bind_tx_evtchn(bool split) {
return _evtchn->bind();
}
port xenfront_qp::bind_rx_evtchn(bool split) {
if (split) {
return _evtchn->bind();
}
return _evtchn->bind(_tx_evtchn.number());
}
xenfront_qp::xenfront_qp(xenfront_device* dev, boost::program_options::variables_map opts)
: qp(true), _dev(dev)
, _otherend(_dev->_xenstore->read<int>(path("backend-id")))
, _backend(_dev->_xenstore->read(path("backend")))
, _gntalloc(gntalloc::instance(_dev->_userspace, _otherend))
, _evtchn(evtchn::instance(_dev->_userspace, _otherend))
, _tx_ring(_gntalloc->alloc_ref())
, _rx_ring(_gntalloc->alloc_ref())
, _tx_refs(_gntalloc->alloc_ref(front_ring<tx>::nr_ents))
, _rx_refs(_gntalloc->alloc_ref(front_ring<rx>::nr_ents)) {
auto all_features = _dev->_xenstore->ls(_backend);
for (auto&& feat : all_features) {
if (feat.compare(0, 8, "feature-") == 0) {
auto val = _dev->_xenstore->read<int>(_backend + "/" + feat);
try {
auto key = _supported_features.at(feat);
_features[key] = val;
} catch (const std::out_of_range& oor) {
_features[feat] = 0;
}
}
}
if (!opts["split-event-channels"].as<bool>()) {
_features["feature-split-event-channels"] = 0;
}
bool split = _features["feature-split-event-channels"];
_tx_evtchn = bind_tx_evtchn(split);
_rx_evtchn = bind_rx_evtchn(split);
{
auto t = xenstore::xenstore_transaction();
for (auto&& f: _features) {
_dev->_xenstore->write(path(f.first), f.second, t);
}
if (split) {
_dev->_xenstore->write<int>(path("event-channel-tx"), _tx_evtchn.number(), t);
_dev->_xenstore->write<int>(path("event-channel-rx"), _rx_evtchn.number(), t);
} else {
_dev->_xenstore->write<int>(path("event-channel"), _rx_evtchn.number(), t);
}
_dev->_xenstore->write<int>(path("tx-ring-ref"), _tx_ring.ref, t);
_dev->_xenstore->write<int>(path("rx-ring-ref"), _rx_ring.ref, t);
_dev->_xenstore->write<int>(path("state"), 4, t);
}
keep_doing([this] {
return alloc_rx_references();
});
_rx_evtchn.umask();
keep_doing([this] () {
return _tx_evtchn.pending().then([this] {
handle_tx_completions();
});
});
_tx_evtchn.umask();
}
xenfront_qp::~xenfront_qp() {
{
auto t = xenstore::xenstore_transaction();
for (auto& f: _features) {
_dev->_xenstore->remove(path(f.first), t);
}
_dev->_xenstore->remove(path("event-channel-tx"), t);
_dev->_xenstore->remove(path("event-channel-rx"), t);
_dev->_xenstore->remove(path("event-channel"), t);
_dev->_xenstore->remove(path("tx-ring-ref"), t);
_dev->_xenstore->remove(path("rx-ring-ref"), t);
_dev->_xenstore->write<int>(path("state"), 6, t);
}
_dev->_xenstore->write<int>(path("state"), 1);
}
boost::program_options::options_description
get_xenfront_net_options_description() {
boost::program_options::options_description opts(
"xenfront net options");
opts.add_options()
("vif",
boost::program_options::value<unsigned>()->default_value(0),
"vif number to hijack")
("split-event-channels",
boost::program_options::value<bool>()->default_value(true),
"Split event channel support")
;
return opts;
}
std::unique_ptr<qp> xenfront_device::init_local_queue(boost::program_options::variables_map opts, uint16_t qid) {
assert(!qid);
return std::make_unique<xenfront_qp>(this, opts);
}
std::unique_ptr<net::device> create_xenfront_net_device(boost::program_options::variables_map opts, bool userspace) {
static bool called = false;
assert(!called);
called = true;
return std::make_unique<xenfront_device>(opts, userspace);
}
}
<commit_msg>xenfront: Fix: initialize the "bunch" variable<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include "core/posix.hh"
#include "core/vla.hh"
#include "core/reactor.hh"
#include "core/future-util.hh"
#include "core/stream.hh"
#include "core/circular_buffer.hh"
#include "core/align.hh"
#include <atomic>
#include <list>
#include <queue>
#include <fcntl.h>
#include <linux/if_tun.h>
#include "ip.hh"
#include "net/native-stack.hh"
#include <xen/xen.h>
#include <xen/memory.h>
#include <xen/sys/gntalloc.h>
#include "core/xen/xenstore.hh"
#include "core/xen/evtchn.hh"
#include "xenfront.hh"
#include <unordered_set>
using namespace net;
namespace xen {
using phys = uint64_t;
class xenfront_device : public device {
public:
xenstore* _xenstore = xenstore::instance();
private:
net::hw_features _hw_features;
ethernet_address _hw_address;
std::string _device_str;
public:
bool _userspace;
public:
xenfront_device(boost::program_options::variables_map opts, bool userspace)
: _hw_address(net::parse_ethernet_address(_xenstore->read(path("mac"))))
, _device_str("device/vif/" + std::to_string(opts["vif"].as<unsigned>()))
, _userspace(userspace) {
_hw_features.rx_csum_offload = true;
_hw_features.tx_csum_l4_offload = true;
}
std::string path(std::string s) { return _device_str + "/" + s; }
ethernet_address hw_address() override {
return _hw_address;
}
net::hw_features hw_features() override {
return _hw_features;
}
virtual std::unique_ptr<qp> init_local_queue(boost::program_options::variables_map opts, uint16_t qid) override;
};
class xenfront_qp : public net::qp {
private:
xenfront_device* _dev;
unsigned _otherend;
std::string _backend;
gntalloc *_gntalloc;
evtchn *_evtchn;
port _tx_evtchn;
port _rx_evtchn;
front_ring<tx> _tx_ring;
front_ring<rx> _rx_ring;
grant_head *_tx_refs;
grant_head *_rx_refs;
std::unordered_map<std::string, int> _features;
static std::unordered_map<std::string, std::string> _supported_features;
port bind_tx_evtchn(bool split);
port bind_rx_evtchn(bool split);
future<> alloc_rx_references();
future<> handle_tx_completions();
future<> queue_rx_packet();
void alloc_one_rx_reference(unsigned id);
std::string path(std::string s) { return _dev->path(s); }
public:
explicit xenfront_qp(xenfront_device* dev, boost::program_options::variables_map opts);
~xenfront_qp();
virtual void rx_start() override;
virtual future<> send(packet p) override;
};
std::unordered_map<std::string, std::string>
xenfront_qp::_supported_features = {
{ "feature-split-event-channels", "feature-split-event-channels" },
{ "feature-rx-copy", "request-rx-copy" }
};
void
xenfront_qp::rx_start() {
keep_doing([this] {
return _rx_evtchn.pending().then([this] {
return queue_rx_packet();
});
});
}
future<>
xenfront_qp::send(packet _p) {
uint32_t frag = 0;
// There doesn't seem to be a way to tell xen, when using the userspace
// drivers, to map a particular page. Therefore, the only alternative
// here is to copy. All pages shared must come from the gntalloc mmap.
//
// A better solution could be to change the packet allocation path to
// use a pre-determined page for data.
//
// In-kernel should be fine
// FIXME: negotiate and use scatter/gather
_p.linearize();
return _tx_ring.entries.has_room().then([this, p = std::move(_p), frag] () mutable {
auto req_prod = _tx_ring._sring->req_prod;
auto f = p.frag(frag);
auto ref = _tx_refs->new_ref(f.base, f.size);
unsigned idx = _tx_ring.entries.get_index();
assert(!_tx_ring.entries[idx]);
_tx_ring.entries[idx] = ref;
auto req = &_tx_ring._sring->_ring[idx].req;
req->gref = ref.xen_id;
req->offset = 0;
req->flags = {};
if (p.offload_info().protocol != ip_protocol_num::unused) {
req->flags.csum_blank = true;
req->flags.data_validated = true;
} else {
req->flags.data_validated = true;
}
req->id = idx;
req->size = f.size;
_tx_ring.req_prod_pvt = idx;
_tx_ring._sring->req_prod = req_prod + 1;
_tx_ring._sring->req_event++;
if ((frag + 1) == p.nr_frags()) {
_tx_evtchn.notify();
return make_ready_future<>();
} else {
return make_ready_future<>();
}
});
// FIXME: Don't forget to clear all grant refs when frontend closes. Or is it automatic?
}
#define rmb() asm volatile("lfence":::"memory");
#define wmb() asm volatile("":::"memory");
template <typename T>
future<> front_ring<T>::entries::has_room() {
return _available.wait();
}
template <typename T>
void front_ring<T>::entries::free_index(unsigned id) {
_available.signal();
}
template <typename T>
unsigned front_ring<T>::entries::get_index() {
return front_ring<T>::idx(_next_idx++);
}
template <typename T>
void front_ring<T>::process_ring(std::function<bool (gntref &entry, T& el)> func, grant_head *refs)
{
auto prod = _sring->rsp_prod;
rmb();
for (unsigned i = rsp_cons; i != prod; i++) {
auto el = _sring->_ring[idx(i)];
if (el.rsp.status < 0) {
dump("Packet error", el.rsp);
continue;
}
auto& entry = entries[i];
if (!func(entry, el)) {
continue;
}
assert(entry.xen_id >= 0);
refs->free_ref(entry);
entries.free_index(i);
prod = _sring->rsp_prod;
}
rsp_cons = prod;
_sring->rsp_event = prod + 1;
}
future<> xenfront_qp::queue_rx_packet()
{
uint64_t bunch = 0;
_rx_ring.process_ring([this, &bunch] (gntref &entry, rx &rx) mutable {
packet p(static_cast<char *>(entry.page) + rx.rsp.offset, rx.rsp.status);
_dev->l2receive(std::move(p));
bunch++;
return true;
}, _rx_refs);
_stats.rx.good.update_pkts_bunch(bunch);
return make_ready_future<>();
}
void xenfront_qp::alloc_one_rx_reference(unsigned index) {
_rx_ring.entries[index] = _rx_refs->new_ref();
// This is how the backend knows where to put data.
auto req = &_rx_ring._sring->_ring[index].req;
req->id = index;
req->gref = _rx_ring.entries[index].xen_id;
}
future<> xenfront_qp::alloc_rx_references() {
return _rx_ring.entries.has_room().then([this] () {
unsigned i = _rx_ring.entries.get_index();
auto req_prod = _rx_ring.req_prod_pvt;
alloc_one_rx_reference(i);
++req_prod;
_rx_ring.req_prod_pvt = req_prod;
wmb();
_rx_ring._sring->req_prod = req_prod;
/* ready */
_rx_evtchn.notify();
});
}
future<> xenfront_qp::handle_tx_completions() {
_tx_ring.process_ring([this] (gntref &entry, tx &tx) {
if (tx.rsp.status == 1) {
return false;
}
if (tx.rsp.status != 0) {
_tx_ring.dump("TX positive packet error", tx.rsp);
return false;
}
return true;
}, _tx_refs);
return make_ready_future<>();
}
port xenfront_qp::bind_tx_evtchn(bool split) {
return _evtchn->bind();
}
port xenfront_qp::bind_rx_evtchn(bool split) {
if (split) {
return _evtchn->bind();
}
return _evtchn->bind(_tx_evtchn.number());
}
xenfront_qp::xenfront_qp(xenfront_device* dev, boost::program_options::variables_map opts)
: qp(true), _dev(dev)
, _otherend(_dev->_xenstore->read<int>(path("backend-id")))
, _backend(_dev->_xenstore->read(path("backend")))
, _gntalloc(gntalloc::instance(_dev->_userspace, _otherend))
, _evtchn(evtchn::instance(_dev->_userspace, _otherend))
, _tx_ring(_gntalloc->alloc_ref())
, _rx_ring(_gntalloc->alloc_ref())
, _tx_refs(_gntalloc->alloc_ref(front_ring<tx>::nr_ents))
, _rx_refs(_gntalloc->alloc_ref(front_ring<rx>::nr_ents)) {
auto all_features = _dev->_xenstore->ls(_backend);
for (auto&& feat : all_features) {
if (feat.compare(0, 8, "feature-") == 0) {
auto val = _dev->_xenstore->read<int>(_backend + "/" + feat);
try {
auto key = _supported_features.at(feat);
_features[key] = val;
} catch (const std::out_of_range& oor) {
_features[feat] = 0;
}
}
}
if (!opts["split-event-channels"].as<bool>()) {
_features["feature-split-event-channels"] = 0;
}
bool split = _features["feature-split-event-channels"];
_tx_evtchn = bind_tx_evtchn(split);
_rx_evtchn = bind_rx_evtchn(split);
{
auto t = xenstore::xenstore_transaction();
for (auto&& f: _features) {
_dev->_xenstore->write(path(f.first), f.second, t);
}
if (split) {
_dev->_xenstore->write<int>(path("event-channel-tx"), _tx_evtchn.number(), t);
_dev->_xenstore->write<int>(path("event-channel-rx"), _rx_evtchn.number(), t);
} else {
_dev->_xenstore->write<int>(path("event-channel"), _rx_evtchn.number(), t);
}
_dev->_xenstore->write<int>(path("tx-ring-ref"), _tx_ring.ref, t);
_dev->_xenstore->write<int>(path("rx-ring-ref"), _rx_ring.ref, t);
_dev->_xenstore->write<int>(path("state"), 4, t);
}
keep_doing([this] {
return alloc_rx_references();
});
_rx_evtchn.umask();
keep_doing([this] () {
return _tx_evtchn.pending().then([this] {
handle_tx_completions();
});
});
_tx_evtchn.umask();
}
xenfront_qp::~xenfront_qp() {
{
auto t = xenstore::xenstore_transaction();
for (auto& f: _features) {
_dev->_xenstore->remove(path(f.first), t);
}
_dev->_xenstore->remove(path("event-channel-tx"), t);
_dev->_xenstore->remove(path("event-channel-rx"), t);
_dev->_xenstore->remove(path("event-channel"), t);
_dev->_xenstore->remove(path("tx-ring-ref"), t);
_dev->_xenstore->remove(path("rx-ring-ref"), t);
_dev->_xenstore->write<int>(path("state"), 6, t);
}
_dev->_xenstore->write<int>(path("state"), 1);
}
boost::program_options::options_description
get_xenfront_net_options_description() {
boost::program_options::options_description opts(
"xenfront net options");
opts.add_options()
("vif",
boost::program_options::value<unsigned>()->default_value(0),
"vif number to hijack")
("split-event-channels",
boost::program_options::value<bool>()->default_value(true),
"Split event channel support")
;
return opts;
}
std::unique_ptr<qp> xenfront_device::init_local_queue(boost::program_options::variables_map opts, uint16_t qid) {
assert(!qid);
return std::make_unique<xenfront_qp>(this, opts);
}
std::unique_ptr<net::device> create_xenfront_net_device(boost::program_options::variables_map opts, bool userspace) {
static bool called = false;
assert(!called);
called = true;
return std::make_unique<xenfront_device>(opts, userspace);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015-2016
// Author: Chrono Law
#ifndef _NGX_COMMON_HEADERS_HPP
#define _NGX_COMMON_HEADERS_HPP
#include <nginx.h> // for NGINX_VER...
#if __cplusplus < 201103L
#error "ngx_cpp_module need C++11 implementation!"
#endif
extern "C" {
#include <ngx_http.h>
// in ngx_http_core_module.h
//#include <ngx_thread_pool.h>
}
#include <cassert>
#include <boost/core/ignore_unused.hpp>
#define ngx_cpp_version 1000000
#define NGX_CPP_VERSION "1.0.0"
#endif //_NGX_COMMON_HEADERS_HPP
<commit_msg>Nginx.hpp<commit_after>// Copyright (c) 2015-2017
// Author: Chrono Law
#ifndef _NGX_COMMON_HEADERS_HPP
#define _NGX_COMMON_HEADERS_HPP
#include <nginx.h> // for NGINX_VER...
extern "C" {
#include <ngx_http.h>
// in ngx_http_core_module.h
//#include <ngx_thread_pool.h>
#include <ngx_md5.h>
#include <ngx_sha1.h>
#include <ngx_murmurhash.h>
}
#define ngx_cpp_version 1001000
#define NGX_CPP_VERSION "1.1.0"
#endif //_NGX_COMMON_HEADERS_HPP
<|endoftext|> |
<commit_before>// -*- c-mode -*-
/*********************************************************************
Numexpr - Fast numerical array expression evaluator for NumPy.
License: MIT
Author: See AUTHORS.txt
See LICENSE.txt for details about copyright and rights to use.
**********************************************************************/
/* These #if blocks make it easier to query this file, without having
to define every row function before #including it. */
#ifndef FUNC_FF
#define ELIDE_FUNC_FF
#define FUNC_FF(...)
#endif
FUNC_FF(FUNC_SQRT_FF, "sqrt_ff", sqrtf, sqrtf2, vsSqrt)
FUNC_FF(FUNC_SIN_FF, "sin_ff", sinf, sinf2, vsSin)
FUNC_FF(FUNC_COS_FF, "cos_ff", cosf, cosf2, vsCos)
FUNC_FF(FUNC_TAN_FF, "tan_ff", tanf, tanf2, vsTan)
FUNC_FF(FUNC_ARCSIN_FF, "arcsin_ff", asinf, asinf2, vsAsin)
FUNC_FF(FUNC_ARCCOS_FF, "arccos_ff", acosf, acosf2, vsAcos)
FUNC_FF(FUNC_ARCTAN_FF, "arctan_ff", atanf, atanf2, vsAtan)
FUNC_FF(FUNC_SINH_FF, "sinh_ff", sinhf, sinhf2, vsSinh)
FUNC_FF(FUNC_COSH_FF, "cosh_ff", coshf, coshf2, vsCosh)
FUNC_FF(FUNC_TANH_FF, "tanh_ff", tanhf, tanhf2, vsTanh)
FUNC_FF(FUNC_ARCSINH_FF, "arcsinh_ff", asinhf, asinhf2, vsAsinh)
FUNC_FF(FUNC_ARCCOSH_FF, "arccosh_ff", acoshf, acoshf2, vsAcosh)
FUNC_FF(FUNC_ARCTANH_FF, "arctanh_ff", atanhf, atanhf2, vsAtanh)
FUNC_FF(FUNC_LOG_FF, "log_ff", logf, logf2, vsLn)
FUNC_FF(FUNC_LOG1P_FF, "log1p_ff", log1pf, log1pf2, vsLog1p)
FUNC_FF(FUNC_LOG10_FF, "log10_ff", log10f, log10f2, vsLog10)
FUNC_FF(FUNC_EXP_FF, "exp_ff", expf, expf2, vsExp)
FUNC_FF(FUNC_EXPM1_FF, "expm1_ff", expm1f, expm1f2, vsExpm1)
FUNC_FF(FUNC_ABS_FF, "absolute_ff", fabsf, fabsf2, vsAbs)
FUNC_FF(FUNC_CONJ_FF, "conjugate_ff",fconjf, fconjf2, vsConj)
FUNC_FF(FUNC_CEIL_FF, "ceil_ff", ceilf, ceilf2, NULL)
FUNC_FF(FUNC_FLOOR_FF, "floor_ff", floorf, floorf2, NULL)
FUNC_FF(FUNC_FF_LAST, NULL, NULL, NULL, NULL)
#ifdef ELIDE_FUNC_FF
#undef ELIDE_FUNC_FF
#undef FUNC_FF
#endif
#ifndef FUNC_FFF
#define ELIDE_FUNC_FFF
#define FUNC_FFF(...)
#endif
FUNC_FFF(FUNC_FMOD_FFF, "fmod_fff", fmodf, fmodf2, vsfmod)
FUNC_FFF(FUNC_ARCTAN2_FFF, "arctan2_fff", atan2f, atan2f2, vsAtan2)
FUNC_FFF(FUNC_FFF_LAST, NULL, NULL, NULL, NULL)
#ifdef ELIDE_FUNC_FFF
#undef ELIDE_FUNC_FFF
#undef FUNC_FFF
#endif
#ifndef FUNC_DD
#define ELIDE_FUNC_DD
#define FUNC_DD(...)
#endif
FUNC_DD(FUNC_SQRT_DD, "sqrt_dd", sqrt, vdSqrt)
FUNC_DD(FUNC_SIN_DD, "sin_dd", sin, vdSin)
FUNC_DD(FUNC_COS_DD, "cos_dd", cos, vdCos)
FUNC_DD(FUNC_TAN_DD, "tan_dd", tan, vdTan)
FUNC_DD(FUNC_ARCSIN_DD, "arcsin_dd", asin, vdAsin)
FUNC_DD(FUNC_ARCCOS_DD, "arccos_dd", acos, vdAcos)
FUNC_DD(FUNC_ARCTAN_DD, "arctan_dd", atan, vdAtan)
FUNC_DD(FUNC_SINH_DD, "sinh_dd", sinh, vdSinh)
FUNC_DD(FUNC_COSH_DD, "cosh_dd", cosh, vdCosh)
FUNC_DD(FUNC_TANH_DD, "tanh_dd", tanh, vdTanh)
FUNC_DD(FUNC_ARCSINH_DD, "arcsinh_dd", asinh, vdAsinh)
FUNC_DD(FUNC_ARCCOSH_DD, "arccosh_dd", acosh, vdAcosh)
FUNC_DD(FUNC_ARCTANH_DD, "arctanh_dd", atanh, vdAtanh)
FUNC_DD(FUNC_LOG_DD, "log_dd", log, vdLn)
FUNC_DD(FUNC_LOG1P_DD, "log1p_dd", log1p, vdLog1p)
FUNC_DD(FUNC_LOG10_DD, "log10_dd", log10, vdLog10)
FUNC_DD(FUNC_EXP_DD, "exp_dd", exp, vdExp)
FUNC_DD(FUNC_EXPM1_DD, "expm1_dd", expm1, vdExpm1)
FUNC_DD(FUNC_ABS_DD, "absolute_dd", fabs, vdAbs)
FUNC_DD(FUNC_CONJ_DD, "conjugate_dd",fconj, vdConj)
FUNC_DD(FUNC_CEIL_DD, "ceil_dd", ceil, NULL)
FUNC_DD(FUNC_FLOOR_DD, "floor_dd", floor, NULL)
FUNC_DD(FUNC_DD_LAST, NULL, NULL, NULL)
#ifdef ELIDE_FUNC_DD
#undef ELIDE_FUNC_DD
#undef FUNC_DD
#endif
#ifndef FUNC_DDD
#define ELIDE_FUNC_DDD
#define FUNC_DDD(...)
#endif
FUNC_DDD(FUNC_FMOD_DDD, "fmod_ddd", fmod, vdfmod)
FUNC_DDD(FUNC_ARCTAN2_DDD, "arctan2_ddd", atan2, vdAtan2)
FUNC_DDD(FUNC_DDD_LAST, NULL, NULL, NULL)
#ifdef ELIDE_FUNC_DDD
#undef ELIDE_FUNC_DDD
#undef FUNC_DDD
#endif
#ifndef FUNC_CC
#define ELIDE_FUNC_CC
#define FUNC_CC(...)
#endif
FUNC_CC(FUNC_SQRT_CC, "sqrt_cc", nc_sqrt, vzSqrt)
FUNC_CC(FUNC_SIN_CC, "sin_cc", nc_sin, vzSin)
FUNC_CC(FUNC_COS_CC, "cos_cc", nc_cos, vzCos)
FUNC_CC(FUNC_TAN_CC, "tan_cc", nc_tan, vzTan)
FUNC_CC(FUNC_ARCSIN_CC, "arcsin_cc", nc_asin, vzAsin)
FUNC_CC(FUNC_ARCCOS_CC, "arccos_cc", nc_acos, vzAcos)
FUNC_CC(FUNC_ARCTAN_CC, "arctan_cc", nc_atan, vzAtan)
FUNC_CC(FUNC_SINH_CC, "sinh_cc", nc_sinh, vzSinh)
FUNC_CC(FUNC_COSH_CC, "cosh_cc", nc_cosh, vzCosh)
FUNC_CC(FUNC_TANH_CC, "tanh_cc", nc_tanh, vzTanh)
FUNC_CC(FUNC_ARCSINH_CC, "arcsinh_cc", nc_asinh, vzAsinh)
FUNC_CC(FUNC_ARCCOSH_CC, "arccosh_cc", nc_acosh, vzAcosh)
FUNC_CC(FUNC_ARCTANH_CC, "arctanh_cc", nc_atanh, vzAtanh)
FUNC_CC(FUNC_LOG_CC, "log_cc", nc_log, vzLn)
FUNC_CC(FUNC_LOG1P_CC, "log1p_cc", nc_log1p, vzLog1p)
FUNC_CC(FUNC_LOG10_CC, "log10_cc", nc_log10, vzLog10)
FUNC_CC(FUNC_EXP_CC, "exp_cc", nc_exp, vzExp)
FUNC_CC(FUNC_EXPM1_CC, "expm1_cc", nc_expm1, vzExpm1)
FUNC_CC(FUNC_ABS_CC, "absolute_cc", nc_abs, vzAbs_)
FUNC_CC(FUNC_CONJ_CC, "conjugate_cc",nc_conj, vzConj)
FUNC_CC(FUNC_CC_LAST, NULL, NULL, NULL)
#ifdef ELIDE_FUNC_CC
#undef ELIDE_FUNC_CC
#undef FUNC_CC
#endif
#ifndef FUNC_CCC
#define ELIDE_FUNC_CCC
#define FUNC_CCC(...)
#endif
FUNC_CCC(FUNC_POW_CCC, "pow_ccc", nc_pow)
FUNC_CCC(FUNC_CCC_LAST, NULL, NULL)
#ifdef ELIDE_FUNC_CCC
#undef ELIDE_FUNC_CCC
#undef FUNC_CCC
#endif
<commit_msg>Use VML functions for ceil and floor<commit_after>// -*- c-mode -*-
/*********************************************************************
Numexpr - Fast numerical array expression evaluator for NumPy.
License: MIT
Author: See AUTHORS.txt
See LICENSE.txt for details about copyright and rights to use.
**********************************************************************/
/* These #if blocks make it easier to query this file, without having
to define every row function before #including it. */
#ifndef FUNC_FF
#define ELIDE_FUNC_FF
#define FUNC_FF(...)
#endif
FUNC_FF(FUNC_SQRT_FF, "sqrt_ff", sqrtf, sqrtf2, vsSqrt)
FUNC_FF(FUNC_SIN_FF, "sin_ff", sinf, sinf2, vsSin)
FUNC_FF(FUNC_COS_FF, "cos_ff", cosf, cosf2, vsCos)
FUNC_FF(FUNC_TAN_FF, "tan_ff", tanf, tanf2, vsTan)
FUNC_FF(FUNC_ARCSIN_FF, "arcsin_ff", asinf, asinf2, vsAsin)
FUNC_FF(FUNC_ARCCOS_FF, "arccos_ff", acosf, acosf2, vsAcos)
FUNC_FF(FUNC_ARCTAN_FF, "arctan_ff", atanf, atanf2, vsAtan)
FUNC_FF(FUNC_SINH_FF, "sinh_ff", sinhf, sinhf2, vsSinh)
FUNC_FF(FUNC_COSH_FF, "cosh_ff", coshf, coshf2, vsCosh)
FUNC_FF(FUNC_TANH_FF, "tanh_ff", tanhf, tanhf2, vsTanh)
FUNC_FF(FUNC_ARCSINH_FF, "arcsinh_ff", asinhf, asinhf2, vsAsinh)
FUNC_FF(FUNC_ARCCOSH_FF, "arccosh_ff", acoshf, acoshf2, vsAcosh)
FUNC_FF(FUNC_ARCTANH_FF, "arctanh_ff", atanhf, atanhf2, vsAtanh)
FUNC_FF(FUNC_LOG_FF, "log_ff", logf, logf2, vsLn)
FUNC_FF(FUNC_LOG1P_FF, "log1p_ff", log1pf, log1pf2, vsLog1p)
FUNC_FF(FUNC_LOG10_FF, "log10_ff", log10f, log10f2, vsLog10)
FUNC_FF(FUNC_EXP_FF, "exp_ff", expf, expf2, vsExp)
FUNC_FF(FUNC_EXPM1_FF, "expm1_ff", expm1f, expm1f2, vsExpm1)
FUNC_FF(FUNC_ABS_FF, "absolute_ff", fabsf, fabsf2, vsAbs)
FUNC_FF(FUNC_CONJ_FF, "conjugate_ff",fconjf, fconjf2, vsConj)
FUNC_FF(FUNC_CEIL_FF, "ceil_ff", ceilf, ceilf2, vsCeil)
FUNC_FF(FUNC_FLOOR_FF, "floor_ff", floorf, floorf2, vsFloor)
FUNC_FF(FUNC_FF_LAST, NULL, NULL, NULL, NULL)
#ifdef ELIDE_FUNC_FF
#undef ELIDE_FUNC_FF
#undef FUNC_FF
#endif
#ifndef FUNC_FFF
#define ELIDE_FUNC_FFF
#define FUNC_FFF(...)
#endif
FUNC_FFF(FUNC_FMOD_FFF, "fmod_fff", fmodf, fmodf2, vsfmod)
FUNC_FFF(FUNC_ARCTAN2_FFF, "arctan2_fff", atan2f, atan2f2, vsAtan2)
FUNC_FFF(FUNC_FFF_LAST, NULL, NULL, NULL, NULL)
#ifdef ELIDE_FUNC_FFF
#undef ELIDE_FUNC_FFF
#undef FUNC_FFF
#endif
#ifndef FUNC_DD
#define ELIDE_FUNC_DD
#define FUNC_DD(...)
#endif
FUNC_DD(FUNC_SQRT_DD, "sqrt_dd", sqrt, vdSqrt)
FUNC_DD(FUNC_SIN_DD, "sin_dd", sin, vdSin)
FUNC_DD(FUNC_COS_DD, "cos_dd", cos, vdCos)
FUNC_DD(FUNC_TAN_DD, "tan_dd", tan, vdTan)
FUNC_DD(FUNC_ARCSIN_DD, "arcsin_dd", asin, vdAsin)
FUNC_DD(FUNC_ARCCOS_DD, "arccos_dd", acos, vdAcos)
FUNC_DD(FUNC_ARCTAN_DD, "arctan_dd", atan, vdAtan)
FUNC_DD(FUNC_SINH_DD, "sinh_dd", sinh, vdSinh)
FUNC_DD(FUNC_COSH_DD, "cosh_dd", cosh, vdCosh)
FUNC_DD(FUNC_TANH_DD, "tanh_dd", tanh, vdTanh)
FUNC_DD(FUNC_ARCSINH_DD, "arcsinh_dd", asinh, vdAsinh)
FUNC_DD(FUNC_ARCCOSH_DD, "arccosh_dd", acosh, vdAcosh)
FUNC_DD(FUNC_ARCTANH_DD, "arctanh_dd", atanh, vdAtanh)
FUNC_DD(FUNC_LOG_DD, "log_dd", log, vdLn)
FUNC_DD(FUNC_LOG1P_DD, "log1p_dd", log1p, vdLog1p)
FUNC_DD(FUNC_LOG10_DD, "log10_dd", log10, vdLog10)
FUNC_DD(FUNC_EXP_DD, "exp_dd", exp, vdExp)
FUNC_DD(FUNC_EXPM1_DD, "expm1_dd", expm1, vdExpm1)
FUNC_DD(FUNC_ABS_DD, "absolute_dd", fabs, vdAbs)
FUNC_DD(FUNC_CONJ_DD, "conjugate_dd",fconj, vdConj)
FUNC_DD(FUNC_CEIL_DD, "ceil_dd", ceil, vdCeil)
FUNC_DD(FUNC_FLOOR_DD, "floor_dd", floor, vdFloor)
FUNC_DD(FUNC_DD_LAST, NULL, NULL, NULL)
#ifdef ELIDE_FUNC_DD
#undef ELIDE_FUNC_DD
#undef FUNC_DD
#endif
#ifndef FUNC_DDD
#define ELIDE_FUNC_DDD
#define FUNC_DDD(...)
#endif
FUNC_DDD(FUNC_FMOD_DDD, "fmod_ddd", fmod, vdfmod)
FUNC_DDD(FUNC_ARCTAN2_DDD, "arctan2_ddd", atan2, vdAtan2)
FUNC_DDD(FUNC_DDD_LAST, NULL, NULL, NULL)
#ifdef ELIDE_FUNC_DDD
#undef ELIDE_FUNC_DDD
#undef FUNC_DDD
#endif
#ifndef FUNC_CC
#define ELIDE_FUNC_CC
#define FUNC_CC(...)
#endif
FUNC_CC(FUNC_SQRT_CC, "sqrt_cc", nc_sqrt, vzSqrt)
FUNC_CC(FUNC_SIN_CC, "sin_cc", nc_sin, vzSin)
FUNC_CC(FUNC_COS_CC, "cos_cc", nc_cos, vzCos)
FUNC_CC(FUNC_TAN_CC, "tan_cc", nc_tan, vzTan)
FUNC_CC(FUNC_ARCSIN_CC, "arcsin_cc", nc_asin, vzAsin)
FUNC_CC(FUNC_ARCCOS_CC, "arccos_cc", nc_acos, vzAcos)
FUNC_CC(FUNC_ARCTAN_CC, "arctan_cc", nc_atan, vzAtan)
FUNC_CC(FUNC_SINH_CC, "sinh_cc", nc_sinh, vzSinh)
FUNC_CC(FUNC_COSH_CC, "cosh_cc", nc_cosh, vzCosh)
FUNC_CC(FUNC_TANH_CC, "tanh_cc", nc_tanh, vzTanh)
FUNC_CC(FUNC_ARCSINH_CC, "arcsinh_cc", nc_asinh, vzAsinh)
FUNC_CC(FUNC_ARCCOSH_CC, "arccosh_cc", nc_acosh, vzAcosh)
FUNC_CC(FUNC_ARCTANH_CC, "arctanh_cc", nc_atanh, vzAtanh)
FUNC_CC(FUNC_LOG_CC, "log_cc", nc_log, vzLn)
FUNC_CC(FUNC_LOG1P_CC, "log1p_cc", nc_log1p, vzLog1p)
FUNC_CC(FUNC_LOG10_CC, "log10_cc", nc_log10, vzLog10)
FUNC_CC(FUNC_EXP_CC, "exp_cc", nc_exp, vzExp)
FUNC_CC(FUNC_EXPM1_CC, "expm1_cc", nc_expm1, vzExpm1)
FUNC_CC(FUNC_ABS_CC, "absolute_cc", nc_abs, vzAbs_)
FUNC_CC(FUNC_CONJ_CC, "conjugate_cc",nc_conj, vzConj)
FUNC_CC(FUNC_CC_LAST, NULL, NULL, NULL)
#ifdef ELIDE_FUNC_CC
#undef ELIDE_FUNC_CC
#undef FUNC_CC
#endif
#ifndef FUNC_CCC
#define ELIDE_FUNC_CCC
#define FUNC_CCC(...)
#endif
FUNC_CCC(FUNC_POW_CCC, "pow_ccc", nc_pow)
FUNC_CCC(FUNC_CCC_LAST, NULL, NULL)
#ifdef ELIDE_FUNC_CCC
#undef ELIDE_FUNC_CCC
#undef FUNC_CCC
#endif
<|endoftext|> |
<commit_before>/* wgraph.c
A generic weighted graph data type
by Steven Skiena
*/
/*
Copyright 2003 by Steven S. Skiena; all rights reserved.
Permission is granted for use in non-commerical applications
provided this copyright notice remains intact and unchanged.
This program appears in my book:
"Programming Challenges: The Programming Contest Training Manual"
by Steven Skiena and Miguel Revilla, Springer-Verlag, New York 2003.
See our website www.programming-challenges.com for additional information.
This book can be ordered from Amazon.com at
http://www.amazon.com/exec/obidos/ASIN/0387001638/thealgorithmrepo/
*/
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <cstdio>
#include "wgraph.h"
using namespace std;
void initialize_graph(graph * g)
//graph *g; /* graph to initialize */
{
int i; /* counter */
g -> nvertices = 0;
g -> nedges = 0;
for (i=1; i<=MAXV; i++) g->degree[i] = 0;
}
void read_graph(graph * g, bool directed)
//graph *g; /* graph to initialize */
//bool directed; /* is this graph directed? */
{
int i; /* counter */
int m; /* number of edges */
int x,y,w; /* placeholder for edge and weight */
string xIp, yIp;
initialize_graph(g);
// scanf("%d %d\n",&(g->nvertices),&m);
cin >> g->nvertices >> m;
for (i=1; i<=m; i++) {
// scanf("%d %d %d\n",&x,&y,&w);
cin >> x >> xIp >> y >> yIp >> w;
insert_edge(g,x+1,y+1,directed,w);
}
}
void insert_edge(graph * g, int x, int y, bool directed, int w)
//graph *g; /* graph to initialize */
//int x, y; /* placeholder for edge (x,y) */
//bool directed; /* is this edge directed? */
//int w; /* edge weight */
{
if (g->degree[x] > MAXDEGREE)
printf("Warning: insertion(%d,%d) exceeds degree bound\n",x,y);
g->edges[x][g->degree[x]].v = y;
g->edges[x][g->degree[x]].weight = w;
/*g->edges[x][g->degree[x]].in = false;*/
g->degree[x] ++;
if (directed == false)
insert_edge(g,y,x,true,w);
else
g->nedges ++;
}
void delete_edge(graph * g, int x, int y, bool directed)
//graph *g; /* graph to initialize */
//int x, y; /* placeholder for edge (x,y) */
//bool directed; /* is this edge directed? */
{
int i; /* counter */
for (i=0; i<g->degree[x]; i++)
if (g->edges[x][i].v == y) {
g->degree[x] --;
g->edges[x][i] = g->edges[x][g->degree[x]];
if (directed == false)
delete_edge(g,y,x,true);
return;
}
printf("Warning: deletion(%d,%d) not found in g.\n",x,y);
}
void print_graph(graph * g)
//graph *g; /* graph to print */
{
int i,j; /* counters */
for (i=1; i<=g->nvertices; i++) {
printf("%d: ",i);
for (j=0; j<g->degree[i]; j++)
printf(" %d",g->edges[i][j].v);
printf("\n");
}
}
//bool processed[MAXV]; /* which vertices have been processed */
//bool discovered[MAXV]; /* which vertices have been found */
//int parent[MAXV]; /* discovery relation */
//void initialize_search(graph * g)
//graph *g; /* graph to traverse */
//{
// int i; /* counter */
// for (i=1; i<=g->nvertices; i++) {
// processed[i] = false;
// discovered[i] = false;
// parent[i] = -1;
// }
//}
//void dfs(graph * g, int v)
//graph *g; /* graph to traverse */
//int v; /* vertex to start searching from */
//{
// int i; /* counter */
// int y; /* successor vertex */
//
// discovered[v] = true;
// process_vertex(v);
//
// for (i=0; i<g->degree[v]; i++) {
// y = g->edges[v][i].v;
// if (discovered[y] == false) {
// parent[y] = v;
// dfs(g,y);
// } else
// if (processed[y] == false)
// process_edge(v,y);
// }
//
// processed[v] = true;
//
//
void process_vertex(int v)
//int v; /* vertex to process */
{
printf(" %d",v);
}
void process_edge(int x, int y)
//int x,y; /* edge to process */
{
}
void find_path(int start, int end, int parents[])
//int start; /* first vertex on path */
//int end; /* last vertex on path */
//int parents[]; /* array of parent pointers */
{
if ((start == end) || (end == -1))
printf("\n%d",start);
else {
find_path(start,parents[end],parents);
printf(" %d",end);
}
}
//void connected_components(graph * g)
//graph *g; /* graph to analyze */
//{
// int c; /* component number */
// int i; /* counter */
//
// initialize_search(g);
//
// c = 0;
// for (i=1; i<=g->nvertices; i++)
// if (discovered[i] == false) {
// c = c+1;
// printf("Component %d:",c);
// dfs(g,i);
// printf("\n");
// }
//}
<commit_msg>Added error message/exit fow when the degree of a vertex grows too high.<commit_after>/* wgraph.c
A generic weighted graph data type
by Steven Skiena
*/
/*
Copyright 2003 by Steven S. Skiena; all rights reserved.
Permission is granted for use in non-commerical applications
provided this copyright notice remains intact and unchanged.
This program appears in my book:
"Programming Challenges: The Programming Contest Training Manual"
by Steven Skiena and Miguel Revilla, Springer-Verlag, New York 2003.
See our website www.programming-challenges.com for additional information.
This book can be ordered from Amazon.com at
http://www.amazon.com/exec/obidos/ASIN/0387001638/thealgorithmrepo/
*/
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <cstdio>
#include "wgraph.h"
using namespace std;
void initialize_graph(graph * g)
//graph *g; /* graph to initialize */
{
int i; /* counter */
g -> nvertices = 0;
g -> nedges = 0;
for (i=1; i<=MAXV; i++) g->degree[i] = 0;
}
void read_graph(graph * g, bool directed)
//graph *g; /* graph to initialize */
//bool directed; /* is this graph directed? */
{
int i; /* counter */
int m; /* number of edges */
int x,y,w; /* placeholder for edge and weight */
string xIp, yIp;
initialize_graph(g);
// scanf("%d %d\n",&(g->nvertices),&m);
cin >> g->nvertices >> m;
for (i=1; i<=m; i++) {
// scanf("%d %d %d\n",&x,&y,&w);
cin >> x >> xIp >> y >> yIp >> w;
insert_edge(g,x+1,y+1,directed,w);
}
}
void insert_edge(graph * g, int x, int y, bool directed, int w)
//graph *g; /* graph to initialize */
//int x, y; /* placeholder for edge (x,y) */
//bool directed; /* is this edge directed? */
//int w; /* edge weight */
{
if (g->degree[x] > MAXDEGREE)
{
cerr << "ddijk: maximum degree for " << x << " was exceeded." << endl;
exit(1);
// printf("Warning: insertion(%d,%d) exceeds degree bound\n",x,y);
}
g->edges[x][g->degree[x]].v = y;
g->edges[x][g->degree[x]].weight = w;
/*g->edges[x][g->degree[x]].in = false;*/
g->degree[x] ++;
if (directed == false)
insert_edge(g,y,x,true,w);
else
g->nedges ++;
}
void delete_edge(graph * g, int x, int y, bool directed)
//graph *g; /* graph to initialize */
//int x, y; /* placeholder for edge (x,y) */
//bool directed; /* is this edge directed? */
{
int i; /* counter */
for (i=0; i<g->degree[x]; i++)
if (g->edges[x][i].v == y) {
g->degree[x] --;
g->edges[x][i] = g->edges[x][g->degree[x]];
if (directed == false)
delete_edge(g,y,x,true);
return;
}
printf("Warning: deletion(%d,%d) not found in g.\n",x,y);
}
void print_graph(graph * g)
//graph *g; /* graph to print */
{
int i,j; /* counters */
for (i=1; i<=g->nvertices; i++) {
printf("%d: ",i);
for (j=0; j<g->degree[i]; j++)
printf(" %d",g->edges[i][j].v);
printf("\n");
}
}
//bool processed[MAXV]; /* which vertices have been processed */
//bool discovered[MAXV]; /* which vertices have been found */
//int parent[MAXV]; /* discovery relation */
//void initialize_search(graph * g)
//graph *g; /* graph to traverse */
//{
// int i; /* counter */
// for (i=1; i<=g->nvertices; i++) {
// processed[i] = false;
// discovered[i] = false;
// parent[i] = -1;
// }
//}
//void dfs(graph * g, int v)
//graph *g; /* graph to traverse */
//int v; /* vertex to start searching from */
//{
// int i; /* counter */
// int y; /* successor vertex */
//
// discovered[v] = true;
// process_vertex(v);
//
// for (i=0; i<g->degree[v]; i++) {
// y = g->edges[v][i].v;
// if (discovered[y] == false) {
// parent[y] = v;
// dfs(g,y);
// } else
// if (processed[y] == false)
// process_edge(v,y);
// }
//
// processed[v] = true;
//
//
void process_vertex(int v)
//int v; /* vertex to process */
{
printf(" %d",v);
}
void process_edge(int x, int y)
//int x,y; /* edge to process */
{
}
void find_path(int start, int end, int parents[])
//int start; /* first vertex on path */
//int end; /* last vertex on path */
//int parents[]; /* array of parent pointers */
{
if ((start == end) || (end == -1))
printf("\n%d",start);
else {
find_path(start,parents[end],parents);
printf(" %d",end);
}
}
//void connected_components(graph * g)
//graph *g; /* graph to analyze */
//{
// int c; /* component number */
// int i; /* counter */
//
// initialize_search(g);
//
// c = 0;
// for (i=1; i<=g->nvertices; i++)
// if (discovered[i] == false) {
// c = c+1;
// printf("Component %d:",c);
// dfs(g,i);
// printf("\n");
// }
//}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef CPM_CPM_SUPPORT_HPP
#define CPM_CPM_SUPPORT_HPP
#ifdef CPM_BENCHMARK
#include "../../lib/cxxopts/src/cxxopts.hpp"
namespace cpm {
struct cpm_registry {
cpm_registry(void (*function)(cpm::benchmark<>&)){
benchs.emplace_back(function);
}
static std::vector<void(*)(cpm::benchmark<>&)> benchs;
};
template<template<typename...> class TT, typename T>
struct is_specialization_of : std::false_type {};
template<template<typename...> class TT, typename... Args>
struct is_specialization_of<TT, TT<Args...>> : std::true_type {};
template<typename T>
struct is_section : is_specialization_of<cpm::section, std::decay_t<T>> {};
} //end of namespace cpm
//Internal helpers
#define CPM_UNIQUE_DETAIL(x, y) x##y
#define CPM_UNIQUE(x, y) CPM_UNIQUE_DETAIL(x, y)
#define CPM_UNIQUE_NAME(x) CPM_UNIQUE(x, __LINE__)
//Declarations of benchs functions
#define CPM_BENCH() \
void CPM_UNIQUE_NAME(bench_) (cpm::benchmark<>& bench); \
namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(bench_)); } \
void CPM_UNIQUE_NAME(bench_) (cpm::benchmark<>& bench)
//Declaration of section functions
#define CPM_SECTION(name) \
void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master); \
namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(section_)); } \
void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master) { \
auto bench = master.multi(name);
#define CPM_SECTION_O(name, W, R) \
void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master); \
namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(section_)); } \
void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master) { \
auto bench = master.multi(name); \
bench.warmup = W; \
bench.repeat = R;
#define CPM_SECTION_P(name, policy) \
void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master); \
namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(section_)); } \
void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master) { \
auto bench = master.multi<policy>(name);
#define CPM_SECTION_PO(name, policy, W, R) \
void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master); \
namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(section_)); } \
void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master) { \
auto bench = master.multi<policy>(name); \
bench.warmup = W; \
bench.repeat = R;
//Normal versions for simple bench
#define CPM_SIMPLE(...) bench.measure_simple(__VA_ARGS__);
#define CPM_GLOBAL(...) bench.measure_global(__VA_ARGS__);
#define CPM_TWO_PASS(...) bench.measure_two_pass(__VA_ARGS__);
#define CPM_TWO_PASS_NS(...) bench.measure_two_pass<false>(__VA_ARGS__);
//Versions with policies
#define CPM_SIMPLE_P(policy, ...) \
static_assert(!cpm::is_section<decltype(bench)>::value, "CPM_SIMPLE_P cannot be used inside CPM_SECTION"); \
bench.measure_simple<policy>(__VA_ARGS__);
#define CPM_GLOBAL_P(policy, ...) \
static_assert(!cpm::is_section<decltype(bench)>::value, "CPM_GLOBAL_P cannot be used inside CPM_SECTION"); \
bench.measure_global<policy>(__VA_ARGS__);
#define CPM_TWO_PASS_P(policy, ...) \
static_assert(!cpm::is_section<decltype(bench)>::value, "CPM_TWO_PASS_P cannot be used inside CPM_SECTION"); \
bench.measure_two_pass<true, policy>(__VA_ARGS__);
#define CPM_TWO_PASS_NS_P(policy, ...) \
static_assert(!cpm::is_section<decltype(bench)>::value, "CPM_TWO_PASS_NS_P cannot be used inside CPM_SECTION"); \
bench.template measure_two_pass<false, policy>(__VA_ARGS__);
//Direct bench functions
#define CPM_DIRECT_BENCH_SIMPLE(...) CPM_BENCH() { CPM_SIMPLE(__VA_ARGS__); }
#define CPM_DIRECT_BENCH_TWO_PASS(...) CPM_BENCH() { CPM_TWO_PASS(__VA_ARGS__); }
#define CPM_DIRECT_BENCH_TWO_PASS_NS(...) CPM_BENCH() { CPM_TWO_PASS_NS(__VA_ARGS__); }
//Direct bench functions with policies
#define CPM_DIRECT_BENCH_SIMPLE_P(policy,...) CPM_BENCH() { CPM_SIMPLE_P(POLICY(policy),__VA_ARGS__); }
#define CPM_DIRECT_BENCH_TWO_PASS_P(policy,...) CPM_BENCH() { CPM_TWO_PASS_P(POLICY(policy),__VA_ARGS__); }
#define CPM_DIRECT_BENCH_TWO_PASS_NS_P(policy,...) CPM_BENCH() { CPM_TWO_PASS_NS_P(POLICY(policy),__VA_ARGS__); }
//Direct section functions
#define FE_1(WHAT, X) WHAT(X)
#define FE_2(WHAT, X, ...) WHAT(X)FE_1(WHAT, __VA_ARGS__)
#define FE_3(WHAT, X, ...) WHAT(X)FE_2(WHAT, __VA_ARGS__)
#define FE_4(WHAT, X, ...) WHAT(X)FE_3(WHAT, __VA_ARGS__)
#define FE_5(WHAT, X, ...) WHAT(X)FE_4(WHAT, __VA_ARGS__)
#define FE_6(WHAT, X, ...) WHAT(X)FE_5(WHAT, __VA_ARGS__)
#define FE_7(WHAT, X, ...) WHAT(X)FE_6(WHAT, __VA_ARGS__)
#define FE_8(WHAT, X, ...) WHAT(X)FE_7(WHAT, __VA_ARGS__)
#define GET_MACRO(_1,_2,_3,_4,_5,_6,_7,_8,NAME,...) NAME
#define FOR_EACH(action,...) \
GET_MACRO(__VA_ARGS__,FE_8,FE_7,FE_6,FE_5,FE_4,FE_3,FE_2,FE_1)(action,__VA_ARGS__)
#define FFE_1(WHAT, I, X) WHAT(I,X)
#define FFE_2(WHAT, I, X, ...) WHAT(I,X)FFE_1(WHAT, I, __VA_ARGS__)
#define FFE_3(WHAT, I, X, ...) WHAT(I,X)FFE_2(WHAT, I, __VA_ARGS__)
#define FFE_4(WHAT, I, X, ...) WHAT(I,X)FFE_3(WHAT, I, __VA_ARGS__)
#define FFE_5(WHAT, I, X, ...) WHAT(I,X)FFE_4(WHAT, I, __VA_ARGS__)
#define FFE_6(WHAT, I, X, ...) WHAT(I,X)FFE_5(WHAT, I, __VA_ARGS__)
#define FFE_7(WHAT, I, X, ...) WHAT(I,X)FFE_6(WHAT, I, __VA_ARGS__)
#define FFE_8(WHAT, I, X, ...) WHAT(I,X)FFE_7(WHAT, I, __VA_ARGS__)
#define F_FOR_EACH(action,I,...) \
GET_MACRO(__VA_ARGS__,FFE_8,FFE_7,FFE_6,FFE_5,FFE_4,FFE_3,FFE_2,FFE_1)(action,I,__VA_ARGS__)
#define EMIT_TWO_PASS(init, X) CPM_TWO_PASS((X).first, init, (X).second);
#define EMIT_TWO_PASS_NS(init, X) CPM_TWO_PASS_NS((X).first, init, (X).second);
#define CPM_SECTION_FUNCTOR(name, ...) \
(std::make_pair(name, (__VA_ARGS__)))
#define CPM_DIRECT_SECTION_TWO_PASS(name, init, ...) \
CPM_SECTION(name) \
F_FOR_EACH(EMIT_TWO_PASS, init, __VA_ARGS__) \
}
#define CPM_DIRECT_SECTION_TWO_PASS_P(name, policy, init, ...) \
CPM_SECTION_P(name, POLICY(policy)) \
F_FOR_EACH(EMIT_TWO_PASS, init, __VA_ARGS__) \
}
#define CPM_DIRECT_SECTION_TWO_PASS_NS(name, init, ...) \
CPM_SECTION(name) \
F_FOR_EACH(EMIT_TWO_PASS_NS, init, __VA_ARGS__) \
}
#define CPM_DIRECT_SECTION_TWO_PASS_NS_P(name, policy, init, ...) \
CPM_SECTION_P(name, POLICY(policy)) \
F_FOR_EACH(EMIT_TWO_PASS_NS, init, __VA_ARGS__) \
}
#define CPM_SECTION_INIT(...) (__VA_ARGS__)
//Helpers to create policy
#define POLICY(...) __VA_ARGS__
#define VALUES_POLICY(...) cpm::values_policy<__VA_ARGS__>
#define NARY_POLICY(...) cpm::simple_nary_policy<__VA_ARGS__>
#define STD_STOP_POLICY cpm::std_stop_policy
#define STOP_POLICY(start, stop, add, mul) cpm::increasing_policy<start, stop, add, mul, stop_policy::STOP>
#define TIMEOUT_POLICY(start, stop, add, mul) cpm::increasing_policy<start, stop, add, mul, stop_policy::TIMEOUT>
int main(int argc, char* argv[]){
cxxopts::Options options(argv[0], "");
try {
options.add_options()
("n,name", "Benchmark name", cxxopts::value<std::string>())
("t,tag", "Tag name", cxxopts::value<std::string>())
("c,configuration", "Configuration", cxxopts::value<std::string>())
("o,output", "Output folder", cxxopts::value<std::string>())
("h,help", "Print help")
;
options.parse(argc, argv);
if (options.count("help")){
std::cout << options.help({""}) << std::endl;
return 0;
}
} catch (const cxxopts::OptionException& e){
std::cout << "cpm: error parsing options: " << e.what() << std::endl;
return -1;
}
std::string output_folder{"./results"};
if (options.count("output")){
output_folder = options["output"].as<std::string>();
}
std::string benchmark_name{CPM_BENCHMARK};
if (options.count("name")){
benchmark_name = options["name"].as<std::string>();
}
std::string tag;
if (options.count("tag")){
tag = options["tag"].as<std::string>();
}
std::string configuration;
if (options.count("configuration")){
configuration = options["configuration"].as<std::string>();
}
cpm::benchmark<> bench(benchmark_name, output_folder, tag, configuration);
#ifdef CPM_WARMUP
bench.warmup = CPM_WARMUP
#endif
#ifdef CPM_REPEAT
bench.warmup = CPM_REPEAT
#endif
bench.begin();
for(auto f : cpm::cpm_registry::benchs){
f(bench);
}
return 0;
}
std::vector<void(*)(cpm::benchmark<>&)> cpm::cpm_registry::benchs;
#endif
#endif //CPM_CPM_SUPPORT_HPP
<commit_msg>Fix semicolon<commit_after>//=======================================================================
// Copyright (c) 2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef CPM_CPM_SUPPORT_HPP
#define CPM_CPM_SUPPORT_HPP
#ifdef CPM_BENCHMARK
#include "../../lib/cxxopts/src/cxxopts.hpp"
namespace cpm {
struct cpm_registry {
cpm_registry(void (*function)(cpm::benchmark<>&)){
benchs.emplace_back(function);
}
static std::vector<void(*)(cpm::benchmark<>&)> benchs;
};
template<template<typename...> class TT, typename T>
struct is_specialization_of : std::false_type {};
template<template<typename...> class TT, typename... Args>
struct is_specialization_of<TT, TT<Args...>> : std::true_type {};
template<typename T>
struct is_section : is_specialization_of<cpm::section, std::decay_t<T>> {};
} //end of namespace cpm
//Internal helpers
#define CPM_UNIQUE_DETAIL(x, y) x##y
#define CPM_UNIQUE(x, y) CPM_UNIQUE_DETAIL(x, y)
#define CPM_UNIQUE_NAME(x) CPM_UNIQUE(x, __LINE__)
//Declarations of benchs functions
#define CPM_BENCH() \
void CPM_UNIQUE_NAME(bench_) (cpm::benchmark<>& bench); \
namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(bench_)); } \
void CPM_UNIQUE_NAME(bench_) (cpm::benchmark<>& bench)
//Declaration of section functions
#define CPM_SECTION(name) \
void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master); \
namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(section_)); } \
void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master) { \
auto bench = master.multi(name);
#define CPM_SECTION_O(name, W, R) \
void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master); \
namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(section_)); } \
void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master) { \
auto bench = master.multi(name); \
bench.warmup = W; \
bench.repeat = R;
#define CPM_SECTION_P(name, policy) \
void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master); \
namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(section_)); } \
void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master) { \
auto bench = master.multi<policy>(name);
#define CPM_SECTION_PO(name, policy, W, R) \
void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master); \
namespace { cpm::cpm_registry CPM_UNIQUE_NAME(register_) (& CPM_UNIQUE_NAME(section_)); } \
void CPM_UNIQUE_NAME(section_) (cpm::benchmark<>& master) { \
auto bench = master.multi<policy>(name); \
bench.warmup = W; \
bench.repeat = R;
//Normal versions for simple bench
#define CPM_SIMPLE(...) bench.measure_simple(__VA_ARGS__);
#define CPM_GLOBAL(...) bench.measure_global(__VA_ARGS__);
#define CPM_TWO_PASS(...) bench.measure_two_pass(__VA_ARGS__);
#define CPM_TWO_PASS_NS(...) bench.measure_two_pass<false>(__VA_ARGS__);
//Versions with policies
#define CPM_SIMPLE_P(policy, ...) \
static_assert(!cpm::is_section<decltype(bench)>::value, "CPM_SIMPLE_P cannot be used inside CPM_SECTION"); \
bench.measure_simple<policy>(__VA_ARGS__);
#define CPM_GLOBAL_P(policy, ...) \
static_assert(!cpm::is_section<decltype(bench)>::value, "CPM_GLOBAL_P cannot be used inside CPM_SECTION"); \
bench.measure_global<policy>(__VA_ARGS__);
#define CPM_TWO_PASS_P(policy, ...) \
static_assert(!cpm::is_section<decltype(bench)>::value, "CPM_TWO_PASS_P cannot be used inside CPM_SECTION"); \
bench.measure_two_pass<true, policy>(__VA_ARGS__);
#define CPM_TWO_PASS_NS_P(policy, ...) \
static_assert(!cpm::is_section<decltype(bench)>::value, "CPM_TWO_PASS_NS_P cannot be used inside CPM_SECTION"); \
bench.template measure_two_pass<false, policy>(__VA_ARGS__);
//Direct bench functions
#define CPM_DIRECT_BENCH_SIMPLE(...) CPM_BENCH() { CPM_SIMPLE(__VA_ARGS__); }
#define CPM_DIRECT_BENCH_TWO_PASS(...) CPM_BENCH() { CPM_TWO_PASS(__VA_ARGS__); }
#define CPM_DIRECT_BENCH_TWO_PASS_NS(...) CPM_BENCH() { CPM_TWO_PASS_NS(__VA_ARGS__); }
//Direct bench functions with policies
#define CPM_DIRECT_BENCH_SIMPLE_P(policy,...) CPM_BENCH() { CPM_SIMPLE_P(POLICY(policy),__VA_ARGS__); }
#define CPM_DIRECT_BENCH_TWO_PASS_P(policy,...) CPM_BENCH() { CPM_TWO_PASS_P(POLICY(policy),__VA_ARGS__); }
#define CPM_DIRECT_BENCH_TWO_PASS_NS_P(policy,...) CPM_BENCH() { CPM_TWO_PASS_NS_P(POLICY(policy),__VA_ARGS__); }
//Direct section functions
#define FE_1(WHAT, X) WHAT(X)
#define FE_2(WHAT, X, ...) WHAT(X)FE_1(WHAT, __VA_ARGS__)
#define FE_3(WHAT, X, ...) WHAT(X)FE_2(WHAT, __VA_ARGS__)
#define FE_4(WHAT, X, ...) WHAT(X)FE_3(WHAT, __VA_ARGS__)
#define FE_5(WHAT, X, ...) WHAT(X)FE_4(WHAT, __VA_ARGS__)
#define FE_6(WHAT, X, ...) WHAT(X)FE_5(WHAT, __VA_ARGS__)
#define FE_7(WHAT, X, ...) WHAT(X)FE_6(WHAT, __VA_ARGS__)
#define FE_8(WHAT, X, ...) WHAT(X)FE_7(WHAT, __VA_ARGS__)
#define GET_MACRO(_1,_2,_3,_4,_5,_6,_7,_8,NAME,...) NAME
#define FOR_EACH(action,...) \
GET_MACRO(__VA_ARGS__,FE_8,FE_7,FE_6,FE_5,FE_4,FE_3,FE_2,FE_1)(action,__VA_ARGS__)
#define FFE_1(WHAT, I, X) WHAT(I,X)
#define FFE_2(WHAT, I, X, ...) WHAT(I,X)FFE_1(WHAT, I, __VA_ARGS__)
#define FFE_3(WHAT, I, X, ...) WHAT(I,X)FFE_2(WHAT, I, __VA_ARGS__)
#define FFE_4(WHAT, I, X, ...) WHAT(I,X)FFE_3(WHAT, I, __VA_ARGS__)
#define FFE_5(WHAT, I, X, ...) WHAT(I,X)FFE_4(WHAT, I, __VA_ARGS__)
#define FFE_6(WHAT, I, X, ...) WHAT(I,X)FFE_5(WHAT, I, __VA_ARGS__)
#define FFE_7(WHAT, I, X, ...) WHAT(I,X)FFE_6(WHAT, I, __VA_ARGS__)
#define FFE_8(WHAT, I, X, ...) WHAT(I,X)FFE_7(WHAT, I, __VA_ARGS__)
#define F_FOR_EACH(action,I,...) \
GET_MACRO(__VA_ARGS__,FFE_8,FFE_7,FFE_6,FFE_5,FFE_4,FFE_3,FFE_2,FFE_1)(action,I,__VA_ARGS__)
#define EMIT_TWO_PASS(init, X) CPM_TWO_PASS((X).first, init, (X).second);
#define EMIT_TWO_PASS_NS(init, X) CPM_TWO_PASS_NS((X).first, init, (X).second);
#define CPM_SECTION_FUNCTOR(name, ...) \
(std::make_pair(name, (__VA_ARGS__)))
#define CPM_DIRECT_SECTION_TWO_PASS(name, init, ...) \
CPM_SECTION(name) \
F_FOR_EACH(EMIT_TWO_PASS, init, __VA_ARGS__) \
}
#define CPM_DIRECT_SECTION_TWO_PASS_P(name, policy, init, ...) \
CPM_SECTION_P(name, POLICY(policy)) \
F_FOR_EACH(EMIT_TWO_PASS, init, __VA_ARGS__) \
}
#define CPM_DIRECT_SECTION_TWO_PASS_NS(name, init, ...) \
CPM_SECTION(name) \
F_FOR_EACH(EMIT_TWO_PASS_NS, init, __VA_ARGS__) \
}
#define CPM_DIRECT_SECTION_TWO_PASS_NS_P(name, policy, init, ...) \
CPM_SECTION_P(name, POLICY(policy)) \
F_FOR_EACH(EMIT_TWO_PASS_NS, init, __VA_ARGS__) \
}
#define CPM_SECTION_INIT(...) (__VA_ARGS__)
//Helpers to create policy
#define POLICY(...) __VA_ARGS__
#define VALUES_POLICY(...) cpm::values_policy<__VA_ARGS__>
#define NARY_POLICY(...) cpm::simple_nary_policy<__VA_ARGS__>
#define STD_STOP_POLICY cpm::std_stop_policy
#define STOP_POLICY(start, stop, add, mul) cpm::increasing_policy<start, stop, add, mul, stop_policy::STOP>
#define TIMEOUT_POLICY(start, stop, add, mul) cpm::increasing_policy<start, stop, add, mul, stop_policy::TIMEOUT>
int main(int argc, char* argv[]){
cxxopts::Options options(argv[0], "");
try {
options.add_options()
("n,name", "Benchmark name", cxxopts::value<std::string>())
("t,tag", "Tag name", cxxopts::value<std::string>())
("c,configuration", "Configuration", cxxopts::value<std::string>())
("o,output", "Output folder", cxxopts::value<std::string>())
("h,help", "Print help")
;
options.parse(argc, argv);
if (options.count("help")){
std::cout << options.help({""}) << std::endl;
return 0;
}
} catch (const cxxopts::OptionException& e){
std::cout << "cpm: error parsing options: " << e.what() << std::endl;
return -1;
}
std::string output_folder{"./results"};
if (options.count("output")){
output_folder = options["output"].as<std::string>();
}
std::string benchmark_name{CPM_BENCHMARK};
if (options.count("name")){
benchmark_name = options["name"].as<std::string>();
}
std::string tag;
if (options.count("tag")){
tag = options["tag"].as<std::string>();
}
std::string configuration;
if (options.count("configuration")){
configuration = options["configuration"].as<std::string>();
}
cpm::benchmark<> bench(benchmark_name, output_folder, tag, configuration);
#ifdef CPM_WARMUP
bench.warmup = CPM_WARMUP;
#endif
#ifdef CPM_REPEAT
bench.warmup = CPM_REPEAT;
#endif
bench.begin();
for(auto f : cpm::cpm_registry::benchs){
f(bench);
}
return 0;
}
std::vector<void(*)(cpm::benchmark<>&)> cpm::cpm_registry::benchs;
#endif
#endif //CPM_CPM_SUPPORT_HPP
<|endoftext|> |
<commit_before>#ifndef stubbing_h__
#define stubbing_h__
#include <functional>
#include <type_traits>
#include <unordered_set>
#include <vector>
#include <stdexcept>
#include <utility>
#include "fakeit/FakeitExceptions.hpp"
#include "fakeit/ActualInvocation.hpp"
#include "fakeit/quantifier.hpp"
#include "mockutils/traits.hpp"
#include "mockutils/DefaultValue.hpp"
#include "mockutils/Macros.hpp"
namespace fakeit {
struct MethodVerificationProgress {
MethodVerificationProgress() {
}
virtual ~MethodVerificationProgress() THROWS {
}
void Never() {
Exactly(0);
}
virtual void Once() {
Exactly(1);
}
virtual void Twice() {
Exactly(2);
}
virtual void AtLeastOnce() {
verifyInvocations(-1);
}
virtual void Exactly(const int times) {
if (times < 0) {
throw std::invalid_argument(std::string("bad argument times:").append(std::to_string(times)));
}
verifyInvocations(times);
}
virtual void Exactly(const Quantity & q) {
Exactly(q.quantity);
}
virtual void AtLeast(const int times) {
if (times < 0) {
throw std::invalid_argument(std::string("bad argument times:").append(std::to_string(times)));
}
verifyInvocations(-times);
}
virtual void AtLeast(const Quantity & q) {
AtLeast(q.quantity);
}
protected:
virtual void verifyInvocations(const int times) = 0;
private:
MethodVerificationProgress & operator=(const MethodVerificationProgress & other) = delete;
};
template<typename R, typename ... arglist>
struct FirstFunctionStubbingProgress {
virtual ~FirstFunctionStubbingProgress() THROWS {
}
template<typename U = R>
typename std::enable_if<!std::is_reference<U>::value, FirstFunctionStubbingProgress<R, arglist...>&>::type
Return(const R& r) {
return Do([r](const arglist&...)->R {return r;});
}
template<typename U = R>
typename std::enable_if<std::is_reference<U>::value, FirstFunctionStubbingProgress<R, arglist...>&>::type
Return(const R& r) {
return Do([&r](const arglist&...)->R {return r;});
}
FirstFunctionStubbingProgress<R, arglist...>&
Return(const Quantifier<R>& q) {
const R& value = q.value;
auto method = [value](const arglist&...)->R {return value;};
std::shared_ptr<BehaviorMock<R, arglist...>> doMock { new DoMock<R, arglist...>(method, q.quantity) };
return DoImpl(doMock);
}
template<typename first, typename second, typename ... tail>
FirstFunctionStubbingProgress<R, arglist...>&
Return(const first& f, const second& s, const tail&... t) {
Return(f);
return Return(s, t...);
}
template<typename U = R>
typename std::enable_if<!std::is_reference<U>::value, void>::type
AlwaysReturn(const R& r) {
return AlwaysDo([r](const arglist&...)->R {return r;});
}
template<typename U = R>
typename std::enable_if<std::is_reference<U>::value,void>::type
AlwaysReturn(const R& r) {
return AlwaysDo([&r](const arglist&...)->R {return r;});
}
FirstFunctionStubbingProgress<R, arglist...>&
Return() {
return Do([](const arglist&...)->R {return DefaultValue::value<R>();});
}
void AlwaysReturn() {
return AlwaysDo([](const arglist&...)->R {return DefaultValue::value<R>();});
}
template<typename E>
FirstFunctionStubbingProgress<R, arglist...>& Throw(const E& e) {
return Do([e](const arglist&...)->R {throw e;});
}
template<typename E>
FirstFunctionStubbingProgress<R, arglist...>&
Throw(const Quantifier<E>& q) {
const E& value = q.value;
auto method = [value](const arglist&...)->R {throw value;};
std::shared_ptr<BehaviorMock<R, arglist...>> doMock { new DoMock<R, arglist...>(method, q.quantity) };
return DoImpl(doMock);
}
template<typename first, typename second, typename ... tail>
FirstFunctionStubbingProgress<R, arglist...>&
Throw(const first& f, const second& s, const tail&... t) {
Throw(f);
return Throw(s, t...);
}
template<typename E>
void AlwaysThrow(const E& e) {
return AlwaysDo([e](const arglist&...)->R {throw e;});
}
virtual void operator=(std::function<R(arglist...)> method) {
AlwaysDo(method);
}
virtual FirstFunctionStubbingProgress<R, arglist...>&
Do(std::function<R(arglist...)> method) {
std::shared_ptr<BehaviorMock<R, arglist...>> ptr { new DoMock<R, arglist...>(method) };
return DoImpl(ptr);
}
template<typename F>
FirstFunctionStubbingProgress<R, arglist...>&
Do(const Quantifier<F>& q) {
std::shared_ptr<BehaviorMock<R, arglist...>> doMock { new DoMock<R, arglist...>(q.value, q.quantity) };
return DoImpl(doMock);
}
template<typename first, typename second, typename ... tail>
FirstFunctionStubbingProgress<R, arglist...>&
Do(const first& f, const second& s, const tail&... t) {
Do(f);
return Do(s, t...);
}
virtual void AlwaysDo(std::function<R(arglist...)> method) {
std::shared_ptr<BehaviorMock<R, arglist...>> ptr { new DoForeverMock<R, arglist...>(method) };
DoImpl(ptr);
}
protected:
virtual FirstFunctionStubbingProgress<R, arglist...>& DoImpl(std::shared_ptr<BehaviorMock<R, arglist...> > ptr) = 0;
private:
FirstFunctionStubbingProgress & operator=(const FirstFunctionStubbingProgress & other) = delete;
};
template<typename R, typename ... arglist>
struct FirstProcedureStubbingProgress {
virtual ~FirstProcedureStubbingProgress() THROWS {
}
FirstProcedureStubbingProgress<R, arglist...>& Return() {
return Do([](const arglist&...)->R {return DefaultValue::value<R>();});
}
void AlwaysReturn() {
return AlwaysDo([](const arglist&...)->R {return DefaultValue::value<R>();});
}
FirstProcedureStubbingProgress<R, arglist...>&
Return(const Quantifier<R>& q) {
auto method = [](const arglist&...)->R {return DefaultValue::value<R>();};
std::shared_ptr<BehaviorMock<R, arglist...>> doMock { new DoMock<R, arglist...>(method, q.quantity) };
return DoImpl(doMock);
}
template<typename E>
FirstProcedureStubbingProgress<R, arglist...>& Throw(const E& e) {
return Do([e](const arglist&...)->R {throw e;});
}
template<typename E>
FirstProcedureStubbingProgress<R, arglist...>&
Throw(const Quantifier<E>& q) {
const E& value = q.value;
auto method = [value](const arglist&...)->R {throw value;};
std::shared_ptr<BehaviorMock<R, arglist...>> doMock { new DoMock<R, arglist...>(method, q.quantity) };
return DoImpl(doMock);
}
template<typename first, typename second, typename ... tail>
FirstProcedureStubbingProgress<R, arglist...>&
Throw(const first& f, const second& s, const tail&... t) {
Throw(f);
return Throw(s, t...);
}
template<typename E>
void AlwaysThrow(const E e) {
return AlwaysDo([e](const arglist&...)->R {throw e;});
}
virtual void operator=(std::function<R(arglist...)> method) {
AlwaysDo(method);
}
virtual FirstProcedureStubbingProgress<R, arglist...>& Do(std::function<R(arglist...)> method) {
std::shared_ptr<BehaviorMock<R, arglist...>> ptr { new DoMock<R, arglist...>(method) };
return DoImpl(ptr);
}
template<typename F>
FirstProcedureStubbingProgress<R, arglist...>&
Do(const Quantifier<F>& q) {
std::shared_ptr<BehaviorMock<R, arglist...>> doMock { new DoMock<R, arglist...>(q.value, q.quantity) };
return DoImpl(doMock);
}
template<typename first, typename second, typename ... tail>
FirstProcedureStubbingProgress<R, arglist...>&
Do(const first& f, const second& s, const tail&... t) {
Do(f);
return Do(s, t...);
}
virtual void AlwaysDo(std::function<R(arglist...)> method) {
std::shared_ptr<BehaviorMock<R, arglist...>> ptr { new DoForeverMock<R, arglist...>(method) };
DoImpl(ptr);
}
protected:
virtual FirstProcedureStubbingProgress<R, arglist...>& DoImpl(std::shared_ptr<BehaviorMock<R, arglist...> > ptr)=0;
private:
FirstProcedureStubbingProgress & operator=(const FirstProcedureStubbingProgress & other) = delete;
};
template<typename R, typename ... arglist>
struct FunctionStubbingProgress: public virtual FirstFunctionStubbingProgress<R, arglist...> {
FunctionStubbingProgress() = default;
virtual ~FunctionStubbingProgress() {
}
private:
FunctionStubbingProgress & operator=(const FunctionStubbingProgress & other) = delete;
};
template<typename R, typename ... arglist>
struct ProcedureStubbingProgress: //
public virtual FirstProcedureStubbingProgress<R, arglist...> {
ProcedureStubbingProgress() = default;
virtual ~ProcedureStubbingProgress() override {
}
private:
ProcedureStubbingProgress & operator=(const ProcedureStubbingProgress & other) = delete;
};
}
#endif // stubbing_h__
<commit_msg>remove unused code<commit_after>#ifndef stubbing_h__
#define stubbing_h__
#include <functional>
#include <type_traits>
#include <unordered_set>
#include <vector>
#include <stdexcept>
#include <utility>
#include "fakeit/FakeitExceptions.hpp"
#include "fakeit/ActualInvocation.hpp"
#include "fakeit/quantifier.hpp"
#include "mockutils/traits.hpp"
#include "mockutils/DefaultValue.hpp"
#include "mockutils/Macros.hpp"
namespace fakeit {
struct MethodVerificationProgress {
MethodVerificationProgress() {
}
virtual ~MethodVerificationProgress() THROWS {
}
void Never() {
Exactly(0);
}
virtual void Once() {
Exactly(1);
}
virtual void Twice() {
Exactly(2);
}
virtual void AtLeastOnce() {
verifyInvocations(-1);
}
virtual void Exactly(const int times) {
if (times < 0) {
throw std::invalid_argument(std::string("bad argument times:").append(std::to_string(times)));
}
verifyInvocations(times);
}
virtual void Exactly(const Quantity & q) {
Exactly(q.quantity);
}
virtual void AtLeast(const int times) {
if (times < 0) {
throw std::invalid_argument(std::string("bad argument times:").append(std::to_string(times)));
}
verifyInvocations(-times);
}
virtual void AtLeast(const Quantity & q) {
AtLeast(q.quantity);
}
protected:
virtual void verifyInvocations(const int times) = 0;
private:
MethodVerificationProgress & operator=(const MethodVerificationProgress & other) = delete;
};
template<typename R, typename ... arglist>
struct FirstFunctionStubbingProgress {
virtual ~FirstFunctionStubbingProgress() THROWS {
}
template<typename U = R>
typename std::enable_if<!std::is_reference<U>::value, FirstFunctionStubbingProgress<R, arglist...>&>::type
Return(const R& r) {
return Do([r](const arglist&...)->R {return r;});
}
template<typename U = R>
typename std::enable_if<std::is_reference<U>::value, FirstFunctionStubbingProgress<R, arglist...>&>::type
Return(const R& r) {
return Do([&r](const arglist&...)->R {return r;});
}
FirstFunctionStubbingProgress<R, arglist...>&
Return(const Quantifier<R>& q) {
const R& value = q.value;
auto method = [value](const arglist&...)->R {return value;};
std::shared_ptr<BehaviorMock<R, arglist...>> doMock { new DoMock<R, arglist...>(method, q.quantity) };
return DoImpl(doMock);
}
template<typename first, typename second, typename ... tail>
FirstFunctionStubbingProgress<R, arglist...>&
Return(const first& f, const second& s, const tail&... t) {
Return(f);
return Return(s, t...);
}
template<typename U = R>
typename std::enable_if<!std::is_reference<U>::value, void>::type
AlwaysReturn(const R& r) {
return AlwaysDo([r](const arglist&...)->R {return r;});
}
template<typename U = R>
typename std::enable_if<std::is_reference<U>::value,void>::type
AlwaysReturn(const R& r) {
return AlwaysDo([&r](const arglist&...)->R {return r;});
}
FirstFunctionStubbingProgress<R, arglist...>&
Return() {
return Do([](const arglist&...)->R {return DefaultValue::value<R>();});
}
void AlwaysReturn() {
return AlwaysDo([](const arglist&...)->R {return DefaultValue::value<R>();});
}
template<typename E>
FirstFunctionStubbingProgress<R, arglist...>& Throw(const E& e) {
return Do([e](const arglist&...)->R {throw e;});
}
template<typename E>
FirstFunctionStubbingProgress<R, arglist...>&
Throw(const Quantifier<E>& q) {
const E& value = q.value;
auto method = [value](const arglist&...)->R {throw value;};
std::shared_ptr<BehaviorMock<R, arglist...>> doMock { new DoMock<R, arglist...>(method, q.quantity) };
return DoImpl(doMock);
}
template<typename first, typename second, typename ... tail>
FirstFunctionStubbingProgress<R, arglist...>&
Throw(const first& f, const second& s, const tail&... t) {
Throw(f);
return Throw(s, t...);
}
template<typename E>
void AlwaysThrow(const E& e) {
return AlwaysDo([e](const arglist&...)->R {throw e;});
}
// virtual void operator=(std::function<R(arglist...)> method) {
// AlwaysDo(method);
// }
virtual FirstFunctionStubbingProgress<R, arglist...>&
Do(std::function<R(arglist...)> method) {
std::shared_ptr<BehaviorMock<R, arglist...>> ptr { new DoMock<R, arglist...>(method) };
return DoImpl(ptr);
}
template<typename F>
FirstFunctionStubbingProgress<R, arglist...>&
Do(const Quantifier<F>& q) {
std::shared_ptr<BehaviorMock<R, arglist...>> doMock { new DoMock<R, arglist...>(q.value, q.quantity) };
return DoImpl(doMock);
}
template<typename first, typename second, typename ... tail>
FirstFunctionStubbingProgress<R, arglist...>&
Do(const first& f, const second& s, const tail&... t) {
Do(f);
return Do(s, t...);
}
virtual void AlwaysDo(std::function<R(arglist...)> method) {
std::shared_ptr<BehaviorMock<R, arglist...>> ptr { new DoForeverMock<R, arglist...>(method) };
DoImpl(ptr);
}
protected:
virtual FirstFunctionStubbingProgress<R, arglist...>& DoImpl(std::shared_ptr<BehaviorMock<R, arglist...> > ptr) = 0;
private:
FirstFunctionStubbingProgress & operator=(const FirstFunctionStubbingProgress & other) = delete;
};
template<typename R, typename ... arglist>
struct FirstProcedureStubbingProgress {
virtual ~FirstProcedureStubbingProgress() THROWS {
}
FirstProcedureStubbingProgress<R, arglist...>& Return() {
return Do([](const arglist&...)->R {return DefaultValue::value<R>();});
}
void AlwaysReturn() {
return AlwaysDo([](const arglist&...)->R {return DefaultValue::value<R>();});
}
FirstProcedureStubbingProgress<R, arglist...>&
Return(const Quantifier<R>& q) {
auto method = [](const arglist&...)->R {return DefaultValue::value<R>();};
std::shared_ptr<BehaviorMock<R, arglist...>> doMock { new DoMock<R, arglist...>(method, q.quantity) };
return DoImpl(doMock);
}
template<typename E>
FirstProcedureStubbingProgress<R, arglist...>& Throw(const E& e) {
return Do([e](const arglist&...)->R {throw e;});
}
template<typename E>
FirstProcedureStubbingProgress<R, arglist...>&
Throw(const Quantifier<E>& q) {
const E& value = q.value;
auto method = [value](const arglist&...)->R {throw value;};
std::shared_ptr<BehaviorMock<R, arglist...>> doMock { new DoMock<R, arglist...>(method, q.quantity) };
return DoImpl(doMock);
}
template<typename first, typename second, typename ... tail>
FirstProcedureStubbingProgress<R, arglist...>&
Throw(const first& f, const second& s, const tail&... t) {
Throw(f);
return Throw(s, t...);
}
template<typename E>
void AlwaysThrow(const E e) {
return AlwaysDo([e](const arglist&...)->R {throw e;});
}
// virtual void operator=(std::function<R(arglist...)> method) {
// AlwaysDo(method);
// }
virtual FirstProcedureStubbingProgress<R, arglist...>& Do(std::function<R(arglist...)> method) {
std::shared_ptr<BehaviorMock<R, arglist...>> ptr { new DoMock<R, arglist...>(method) };
return DoImpl(ptr);
}
template<typename F>
FirstProcedureStubbingProgress<R, arglist...>&
Do(const Quantifier<F>& q) {
std::shared_ptr<BehaviorMock<R, arglist...>> doMock { new DoMock<R, arglist...>(q.value, q.quantity) };
return DoImpl(doMock);
}
template<typename first, typename second, typename ... tail>
FirstProcedureStubbingProgress<R, arglist...>&
Do(const first& f, const second& s, const tail&... t) {
Do(f);
return Do(s, t...);
}
virtual void AlwaysDo(std::function<R(arglist...)> method) {
std::shared_ptr<BehaviorMock<R, arglist...>> ptr { new DoForeverMock<R, arglist...>(method) };
DoImpl(ptr);
}
protected:
virtual FirstProcedureStubbingProgress<R, arglist...>& DoImpl(std::shared_ptr<BehaviorMock<R, arglist...> > ptr)=0;
private:
FirstProcedureStubbingProgress & operator=(const FirstProcedureStubbingProgress & other) = delete;
};
template<typename R, typename ... arglist>
struct FunctionStubbingProgress: public virtual FirstFunctionStubbingProgress<R, arglist...> {
FunctionStubbingProgress() = default;
virtual ~FunctionStubbingProgress() {
}
private:
FunctionStubbingProgress & operator=(const FunctionStubbingProgress & other) = delete;
};
template<typename R, typename ... arglist>
struct ProcedureStubbingProgress: //
public virtual FirstProcedureStubbingProgress<R, arglist...> {
ProcedureStubbingProgress() = default;
virtual ~ProcedureStubbingProgress() override {
}
private:
ProcedureStubbingProgress & operator=(const ProcedureStubbingProgress & other) = delete;
};
}
#endif // stubbing_h__
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "helpers/memenv/memenv.h"
#include "leveldb/env.h"
#include "leveldb/status.h"
#include "port/port.h"
#include "util/mutexlock.h"
#include <map>
#include <string.h>
#include <string>
#include <vector>
namespace leveldb {
namespace {
class FileState {
public:
// FileStates are reference counted. The initial reference count is zero
// and the caller must call Ref() at least once.
FileState() : refs_(0), size_(0) {}
// Increase the reference count.
void Ref() {
MutexLock lock(&refs_mutex_);
++refs_;
}
// Decrease the reference count. Delete if this is the last reference.
void Unref() {
bool do_delete = false;
{
MutexLock lock(&refs_mutex_);
--refs_;
assert(refs_ >= 0);
if (refs_ <= 0) {
do_delete = true;
}
}
if (do_delete) {
delete this;
}
}
uint64_t Size() const { return size_; }
Status Read(uint64_t offset, size_t n, Slice* result, char* scratch) const {
if (offset > size_) {
return Status::IOError("Offset greater than file size.");
}
const uint64_t available = size_ - offset;
if (n > available) {
n = available;
}
if (n == 0) {
*result = Slice();
return Status::OK();
}
size_t block = offset / kBlockSize;
size_t block_offset = offset % kBlockSize;
if (n <= kBlockSize - block_offset) {
// The requested bytes are all in the first block.
*result = Slice(blocks_[block] + block_offset, n);
return Status::OK();
}
size_t bytes_to_copy = n;
char* dst = scratch;
while (bytes_to_copy > 0) {
size_t avail = kBlockSize - block_offset;
if (avail > bytes_to_copy) {
avail = bytes_to_copy;
}
memcpy(dst, blocks_[block] + block_offset, avail);
bytes_to_copy -= avail;
dst += avail;
block++;
block_offset = 0;
}
*result = Slice(scratch, n);
return Status::OK();
}
Status Append(const Slice& data) {
const char* src = data.data();
size_t src_len = data.size();
while (src_len > 0) {
size_t avail;
size_t offset = size_ % kBlockSize;
if (offset != 0) {
// There is some room in the last block.
avail = kBlockSize - offset;
} else {
// No room in the last block; push new one.
blocks_.push_back(new char[kBlockSize]);
avail = kBlockSize;
}
if (avail > src_len) {
avail = src_len;
}
memcpy(blocks_.back() + offset, src, avail);
src_len -= avail;
src += avail;
size_ += avail;
}
return Status::OK();
}
private:
// Private since only Unref() should be used to delete it.
~FileState() {
for (std::vector<char*>::iterator i = blocks_.begin(); i != blocks_.end();
++i) {
delete [] *i;
}
}
// No copying allowed.
FileState(const FileState&);
void operator=(const FileState&);
port::Mutex refs_mutex_;
int refs_; // Protected by refs_mutex_;
// The following fields are not protected by any mutex. They are only mutable
// while the file is being written, and concurrent access is not allowed
// to writable files.
std::vector<char*> blocks_;
uint64_t size_;
enum { kBlockSize = 8 * 1024 };
};
class SequentialFileImpl : public SequentialFile {
public:
explicit SequentialFileImpl(FileState* file) : file_(file), pos_(0) {
file_->Ref();
}
~SequentialFileImpl() {
file_->Unref();
}
virtual Status Read(size_t n, Slice* result, char* scratch) {
Status s = file_->Read(pos_, n, result, scratch);
if (s.ok()) {
pos_ += result->size();
}
return s;
}
virtual Status Skip(uint64_t n) {
if (pos_ > file_->Size()) {
return Status::IOError("pos_ > file_->Size()");
}
const size_t available = file_->Size() - pos_;
if (n > available) {
n = available;
}
pos_ += n;
return Status::OK();
}
private:
FileState* file_;
size_t pos_;
};
class RandomAccessFileImpl : public RandomAccessFile {
public:
explicit RandomAccessFileImpl(FileState* file) : file_(file) {
file_->Ref();
}
~RandomAccessFileImpl() {
file_->Unref();
}
virtual Status Read(uint64_t offset, size_t n, Slice* result,
char* scratch) const {
return file_->Read(offset, n, result, scratch);
}
private:
FileState* file_;
};
class WritableFileImpl : public WritableFile {
public:
WritableFileImpl(FileState* file) : file_(file) {
file_->Ref();
}
~WritableFileImpl() {
file_->Unref();
}
virtual Status Append(const Slice& data) {
return file_->Append(data);
}
virtual Status Close() { return Status::OK(); }
virtual Status Flush() { return Status::OK(); }
virtual Status Sync() { return Status::OK(); }
private:
FileState* file_;
};
class NoOpLogger : public Logger {
public:
virtual void Logv(const char* format, va_list ap) { }
};
class InMemoryEnv : public EnvWrapper {
public:
explicit InMemoryEnv(Env* base_env) : EnvWrapper(base_env) { }
virtual ~InMemoryEnv() {
for (FileSystem::iterator i = file_map_.begin(); i != file_map_.end(); ++i){
i->second->Unref();
}
}
// Partial implementation of the Env interface.
virtual Status NewSequentialFile(const std::string& fname,
SequentialFile** result) {
MutexLock lock(&mutex_);
if (file_map_.find(fname) == file_map_.end()) {
*result = NULL;
return Status::IOError(fname, "File not found");
}
*result = new SequentialFileImpl(file_map_[fname]);
return Status::OK();
}
virtual Status NewRandomAccessFile(const std::string& fname,
RandomAccessFile** result) {
MutexLock lock(&mutex_);
if (file_map_.find(fname) == file_map_.end()) {
*result = NULL;
return Status::IOError(fname, "File not found");
}
*result = new RandomAccessFileImpl(file_map_[fname]);
return Status::OK();
}
virtual Status NewWritableFile(const std::string& fname,
WritableFile** result) {
MutexLock lock(&mutex_);
if (file_map_.find(fname) != file_map_.end()) {
DeleteFileInternal(fname);
}
FileState* file = new FileState();
file->Ref();
file_map_[fname] = file;
*result = new WritableFileImpl(file);
return Status::OK();
}
virtual bool FileExists(const std::string& fname) {
MutexLock lock(&mutex_);
return file_map_.find(fname) != file_map_.end();
}
virtual Status GetChildren(const std::string& dir,
std::vector<std::string>* result) {
MutexLock lock(&mutex_);
result->clear();
for (FileSystem::iterator i = file_map_.begin(); i != file_map_.end(); ++i){
const std::string& filename = i->first;
if (filename.size() >= dir.size() + 1 && filename[dir.size()] == '/' &&
Slice(filename).starts_with(Slice(dir))) {
result->push_back(filename.substr(dir.size() + 1));
}
}
return Status::OK();
}
void DeleteFileInternal(const std::string& fname) {
if (file_map_.find(fname) == file_map_.end()) {
return;
}
file_map_[fname]->Unref();
file_map_.erase(fname);
}
virtual Status DeleteFile(const std::string& fname) {
MutexLock lock(&mutex_);
if (file_map_.find(fname) == file_map_.end()) {
return Status::IOError(fname, "File not found");
}
DeleteFileInternal(fname);
return Status::OK();
}
virtual Status CreateDir(const std::string& dirname) {
return Status::OK();
}
virtual Status DeleteDir(const std::string& dirname) {
return Status::OK();
}
virtual Status GetFileSize(const std::string& fname, uint64_t* file_size) {
MutexLock lock(&mutex_);
if (file_map_.find(fname) == file_map_.end()) {
return Status::IOError(fname, "File not found");
}
*file_size = file_map_[fname]->Size();
return Status::OK();
}
virtual Status RenameFile(const std::string& src,
const std::string& target) {
MutexLock lock(&mutex_);
if (file_map_.find(src) == file_map_.end()) {
return Status::IOError(src, "File not found");
}
DeleteFileInternal(target);
file_map_[target] = file_map_[src];
file_map_.erase(src);
return Status::OK();
}
virtual Status LockFile(const std::string& fname, FileLock** lock) {
*lock = new FileLock;
return Status::OK();
}
virtual Status UnlockFile(FileLock* lock) {
delete lock;
return Status::OK();
}
virtual Status GetTestDirectory(std::string* path) {
*path = "/test";
return Status::OK();
}
virtual Status NewLogger(const std::string& fname, Logger** result) {
*result = new NoOpLogger;
return Status::OK();
}
private:
// Map from filenames to FileState objects, representing a simple file system.
typedef std::map<std::string, FileState*> FileSystem;
port::Mutex mutex_;
FileSystem file_map_; // Protected by mutex_.
};
} // namespace
Env* NewMemEnv(Env* base_env) {
return new InMemoryEnv(base_env);
}
} // namespace leveldb
<commit_msg>Delete memenv.cc<commit_after><|endoftext|> |
<commit_before>#include <ros/ros.h>
#include <humanoid_catching/CalculateTorques.h>
#include <Moby/qpOASES.h>
#include <Ravelin/VectorNd.h>
#include <Ravelin/MatrixNd.h>
#include <Ravelin/Quatd.h>
#include <Ravelin/Opsd.h>
#include <Moby/qpOASES.h>
#include <Ravelin/LinAlgd.h>
namespace {
using namespace std;
using namespace humanoid_catching;
using namespace Ravelin;
static const double GRAVITY = 9.81;
class Balancer {
private:
//! Node handle
ros::NodeHandle nh;
//! Private nh
ros::NodeHandle pnh;
//! Balancer Service
ros::ServiceServer balancerService;
public:
Balancer() :
pnh("~") {
balancerService = nh.advertiseService("/balancer/calculate_torques",
&Balancer::calculateTorques, this);
}
private:
static Vector3d toVector(const geometry_msgs::Vector3& v3) {
Vector3d v;
v[0] = v3.x;
v[1] = v3.y;
v[2] = v3.z;
return v;
}
static Vector3d toVector(const geometry_msgs::Point& p) {
Vector3d v;
v[0] = p.x;
v[1] = p.y;
v[2] = p.z;
return v;
}
bool calculateTorques(humanoid_catching::CalculateTorques::Request& req,
humanoid_catching::CalculateTorques::Response& res) {
ROS_INFO("Calculating torques frame %s", req.header.frame_id.c_str());
// x
// linear velocity of body
Vector3d x = toVector(req.body_velocity.linear);
// w
// angular velocity of body
Vector3d w = toVector(req.body_velocity.angular);
// v(t)
// | x |
// | w |
VectorNd v(6);
v.set_sub_vec(0, x);
v.set_sub_vec(3, w);
// R
// Pole rotation matrix
Matrix3d R = MatrixNd(Quatd(req.body_com.orientation.x, req.body_com.orientation.y, req.body_com.orientation.z, req.body_com.orientation.w));
// J
// Pole inertia matrix
Matrix3d J = MatrixNd(VectorNd(req.body_inertia_matrix.size(), &req.body_inertia_matrix[0]));
// JRobot
// Robot jacobian matrix
Matrix3d JRobot = MatrixNd(VectorNd(req.jacobian_matrix.size(), &req.jacobian_matrix[0]));
// 3x3 working matrix
Matrix3d temp;
// RJR_t
Matrix3d RJR = R.mult(J, temp).mult(Matrix3d::transpose(R), temp);
// M
// | Im 0 |
// | 0 RJR_t|
MatrixNd M(6, 6);
M.set_zero(M.rows(), M.columns());
M.set_sub_mat(0, 0, Matrix3d::identity() * req.body_mass);
M.set_sub_mat(3, 3, RJR);
// delta t
double deltaT = req.time_delta.toSec();
// Working vector
Vector3d tempVector;
// fext
// | g |
// | -w x RJR_tw |
VectorNd fExt(6);
fExt[0] = 0;
fExt[1] = 0;
fExt[2] = GRAVITY;
fExt.set_sub_vec(3, Vector3d::cross(-w, RJR.mult(w, tempVector)));
// n_hat
// x component of ground contact position
Vector3d nHat;
nHat[0] = req.ground_contact.x;
nHat[1] = 0;
nHat[2] = 0;
// s_hat
// s component of contact position
Vector3d sHat;
nHat[0] = 0;
nHat[1] = req.ground_contact.y;
nHat[2] = 0;
// t_hat
// z component of contact position
Vector3d tHat;
tHat[0] = 0;
tHat[1] = 0;
tHat[2] = req.ground_contact.z;
// q_hat
// contact normal
Vector3d qHat = toVector(req.contact_normal);
// p
// contact point
Vector3d p = toVector(req.ground_contact);
// x_bar
// pole COM
Vector3d xBar = toVector(req.body_com.position);
// r
Vector3d r = p - xBar;
// N
// | n_hat |
// | r x n_hat |
VectorNd N(6);
N.set_sub_vec(0, nHat);
N.set_sub_vec(3, r.cross(nHat, tempVector));
// S
// | s_hat |
// | r x s_hat |
VectorNd S(6);
S.set_sub_vec(0, sHat);
S.set_sub_vec(3, r.cross(sHat, tempVector));
// T
// | t_hat |
// | r x t_hat |
VectorNd T(6);
T.set_sub_vec(0, tHat);
T.set_sub_vec(3, r.cross(tHat, tempVector));
// Q
VectorNd Q(6);
Q.set_sub_vec(0, qHat);
Q.set_sub_vec(3, -r.cross(qHat, tempVector));
// Result vector
// Torques, f_n, f_s, f_t, f_robot, v_(t + tdelta)
const int torqueIdx = 0;
const int fNIdx = req.torque_limits.size();
const int fSIdx = fNIdx + 1;
const int fTIdx = fSIdx + 1;
const int fRobotIdx = fTIdx + 1;
const int vTDeltaIdx = fRobotIdx + 1;
VectorNd z(req.torque_limits.size() + 1 + 1 + 1 + 1 + 6);
// Set up minimization function
MatrixNd H(6, z.size());
H.set_sub_mat(0, vTDeltaIdx, M);
VectorNd c(6);
c.set_zero(c.rows());
// Linear equality constraints
MatrixNd A(6 * 3 + req.torque_limits.size(), z.size());
VectorNd b(6 * 3 + req.torque_limits.size());
// Sv(t + t_delta) = 0 (no tangent velocity)
unsigned idx = 0;
A.set_sub_mat(idx, vTDeltaIdx, S);
b.set_sub_vec(idx, VectorNd::zero(6));
idx += 6;
// Tv(t + t_delta) = 0 (no tangent velocity)
A.set_sub_mat(idx, vTDeltaIdx, T);
b.set_sub_vec(idx, VectorNd::zero(6));
idx += 6;
// J_robot(transpose) * Q(transpose) * f_robot = torques
MatrixNd JQ(req.torque_limits.size(), 1);
MatrixNd Jt(JRobot.columns(), JRobot.rows());
JRobot.transpose(Jt);
MatrixNd::mult(Jt, MatrixNd(Q, eTranspose), JQ);
A.set_sub_mat(idx, fRobotIdx, JQ);
A.set_sub_mat(idx, torqueIdx, MatrixNd::identity(req.torque_limits.size()).negate());
b.set_sub_vec(idx, VectorNd::zero(req.torque_limits.size()));
idx += 6;
// v_(t + t_delta) = v_t + M_inv (N_t * f_n + S_t * f_s + T_t * f_t + delta_t * f_ext + Q_t * delta_t * f_robot)
// Manipulated to fit constraint form
// -v_t - M_inv * delta_t * f_ext = M_inv * N_t * f_n + M_inv * S_t * f_s + M_inv * T_t * f_t + M_inv * Q_t * delta_t * f_robot + -v_(t + t_delta)
LinAlgd linAlgd;
MatrixNd MInverse = M;
linAlgd.pseudo_invert(MInverse);
MatrixNd MInverseN(MInverse.rows(), N.columns());
MInverse.mult(N, MInverseN);
A.set_sub_mat(idx, fNIdx, MInverseN);
MatrixNd MInverseS(MInverse.rows(), S.columns());
MInverse.mult(S, MInverseS);
A.set_sub_mat(idx, fSIdx, MInverseS);
MatrixNd MInverseT(MInverse.rows(), T.columns());
MInverse.mult(T, MInverseT);
A.set_sub_mat(idx, fTIdx,MInverseT);
MatrixNd MInverseQ(MInverse.rows(), Q.columns());
MInverse.mult(Q, MInverseQ);
MInverseQ *= deltaT;
A.set_sub_mat(idx, fRobotIdx, MInverseQ);
A.set_sub_mat(idx, vTDeltaIdx, MatrixNd::identity(6).negate());
VectorNd MInverseFExt(6);
MInverseFExt.set_zero();
MInverse.mult(fExt, MInverseFExt, deltaT);
MInverseFExt.negate() -= v;
b.set_sub_vec(idx, MInverseFExt);
// Linear inequality constraints
MatrixNd Mc(6, z.size());
VectorNd q(6);
// Nv(t) >= 0 (non-negative normal velocity)
Mc.set_sub_mat(0, req.torque_limits.size() + 6 * 4, N);
q.set_sub_vec(0, VectorNd::zero(6));
// Solution variable constraint
VectorNd lb(z.size());
VectorNd ub(z.size());
// Torque constraints
unsigned int bound = 0;
for (bound; bound < req.torque_limits.size(); ++bound) {
lb[bound] = req.torque_limits[bound].minimum;
ub[bound] = req.torque_limits[bound].maximum;
}
// f_n >= 0
lb[bound] = 0;
ub[bound] = INFINITY;
++bound;
// f_s (no constraints)
lb[bound] = INFINITY;
ub[bound] = INFINITY;
++bound;
// f_t (no constraints)
lb[bound] = INFINITY;
ub[bound] = INFINITY;
++bound;
// f_robot >= 0
lb[bound] = INFINITY;
ub[bound] = INFINITY;
++bound;
// v_t (no constraints)
for (bound; bound < z.size(); ++bound) {
lb[bound] = INFINITY;
ub[bound] = INFINITY;
}
// Call solver
Moby::QPOASES qp;
if (!qp.qp_activeset(H, p, lb, ub, Mc, q, A, b, z)){
ROS_ERROR("QP failed to find feasible point");
return false;
}
ROS_INFO_STREAM("QP solved successfully: " << z);
// Copy over result
res.torques.resize(req.torque_limits.size());
for (unsigned int i = 0; i < z.size(); ++i) {
res.torques[i] = z[i];
}
return true;
}
};
}
int main(int argc, char** argv) {
ros::init(argc, argv, "balancer");
Balancer bal;
ros::spin();
}
<commit_msg>Cleanup balancing code<commit_after>#include <ros/ros.h>
#include <humanoid_catching/CalculateTorques.h>
#include <Moby/qpOASES.h>
#include <Ravelin/VectorNd.h>
#include <Ravelin/MatrixNd.h>
#include <Ravelin/Quatd.h>
#include <Ravelin/Opsd.h>
#include <Moby/qpOASES.h>
#include <Ravelin/LinAlgd.h>
namespace {
using namespace std;
using namespace humanoid_catching;
using namespace Ravelin;
static const double GRAVITY = 9.81;
class Balancer {
private:
//! Node handle
ros::NodeHandle nh;
//! Private nh
ros::NodeHandle pnh;
//! Balancer Service
ros::ServiceServer balancerService;
public:
Balancer() :
pnh("~") {
balancerService = nh.advertiseService("/balancer/calculate_torques",
&Balancer::calculateTorques, this);
}
private:
/**
* Convert a geometry_msgs::Vector3 to a Ravelin::Vector3d
* @param v3 geometry_msgs::Vector3
* @return Ravelin Vector3d
*/
static Vector3d toVector(const geometry_msgs::Vector3& v3) {
Vector3d v;
v[0] = v3.x;
v[1] = v3.y;
v[2] = v3.z;
return v;
}
/**
* Convert a geometry_msgs::Point to a Ravelin::Vector3d
* @param p geometry_msgs::Point
* @return Ravelin Vector3d
*/
static Vector3d toVector(const geometry_msgs::Point& p) {
Vector3d v;
v[0] = p.x;
v[1] = p.y;
v[2] = p.z;
return v;
}
/**
* Calculate balancing torques
* @param req Request
* @param res Response
* @return Success
*/
bool calculateTorques(humanoid_catching::CalculateTorques::Request& req,
humanoid_catching::CalculateTorques::Response& res) {
ROS_INFO("Calculating torques frame %s", req.header.frame_id.c_str());
// x
// linear velocity of body
const Vector3d x = toVector(req.body_velocity.linear);
// w
// angular velocity of body
const Vector3d w = toVector(req.body_velocity.angular);
// v(t)
// | x |
// | w |
VectorNd v(6);
v.set_sub_vec(0, x);
v.set_sub_vec(3, w);
// R
// Pole rotation matrix
const Matrix3d R = MatrixNd(Quatd(req.body_com.orientation.x, req.body_com.orientation.y, req.body_com.orientation.z, req.body_com.orientation.w));
// J
// Pole inertia matrix
const Matrix3d J = MatrixNd(VectorNd(req.body_inertia_matrix.size(), &req.body_inertia_matrix[0]));
// JRobot
// Robot end effector jacobian matrix
const Matrix3d JRobot = MatrixNd(VectorNd(req.jacobian_matrix.size(), &req.jacobian_matrix[0]));
// RJR_t
Matrix3d RJR;
Matrix3d RTranspose = R.transpose(RTranspose);
RJR = R.mult(J, RJR).mult(RTranspose, RJR);
// M
// | Im 0 |
// | 0 RJR_t|
MatrixNd M(6, 6);
M.set_zero(M.rows(), M.columns());
M.set_sub_mat(0, 0, Matrix3d::identity() * req.body_mass);
M.set_sub_mat(3, 3, RJR);
// delta t
double deltaT = req.time_delta.toSec();
// Working vector
Vector3d tempVector;
// fext
// | g |
// | -w x RJR_tw |
VectorNd fExt(6);
fExt[0] = 0;
fExt[1] = 0;
fExt[2] = GRAVITY;
fExt.set_sub_vec(3, Vector3d::cross(-w, RJR.mult(w, tempVector)));
// n_hat
// x component of ground contact position
Vector3d nHat;
nHat[0] = req.ground_contact.x;
nHat[1] = 0;
nHat[2] = 0;
// s_hat
// s component of contact position
Vector3d sHat;
nHat[0] = 0;
nHat[1] = req.ground_contact.y;
nHat[2] = 0;
// t_hat
// z component of contact position
Vector3d tHat;
tHat[0] = 0;
tHat[1] = 0;
tHat[2] = req.ground_contact.z;
// q_hat
// contact normal
const Vector3d qHat = toVector(req.contact_normal);
// p
// contact point
const Vector3d p = toVector(req.ground_contact);
// x_bar
// pole COM
const Vector3d xBar = toVector(req.body_com.position);
// r
const Vector3d r = p - xBar;
// N
// | n_hat |
// | r x n_hat |
VectorNd N(6);
N.set_sub_vec(0, nHat);
N.set_sub_vec(3, r.cross(nHat, tempVector));
// S
// | s_hat |
// | r x s_hat |
VectorNd S(6);
S.set_sub_vec(0, sHat);
S.set_sub_vec(3, r.cross(sHat, tempVector));
// T
// | t_hat |
// | r x t_hat |
VectorNd T(6);
T.set_sub_vec(0, tHat);
T.set_sub_vec(3, r.cross(tHat, tempVector));
// Q
VectorNd Q(6);
Q.set_sub_vec(0, qHat);
Q.set_sub_vec(3, -r.cross(qHat, tempVector));
// Result vector
// Torques, f_n, f_s, f_t, f_robot, v_(t + tdelta)
const int torqueIdx = 0;
const int fNIdx = req.torque_limits.size();
const int fSIdx = fNIdx + 1;
const int fTIdx = fSIdx + 1;
const int fRobotIdx = fTIdx + 1;
const int vTDeltaIdx = fRobotIdx + 1;
VectorNd z(req.torque_limits.size() + 1 + 1 + 1 + 1 + 6);
// Set up minimization function
MatrixNd H(6, z.size());
H.set_sub_mat(0, vTDeltaIdx, M);
VectorNd c(6);
c.set_zero(c.rows());
// Linear equality constraints
MatrixNd A(1 * 2 + req.torque_limits.size() + 6, z.size());
VectorNd b(1 * 2 + req.torque_limits.size() + 6);
// Sv(t + t_delta) = 0 (no tangent velocity)
unsigned idx = 0;
A.set_sub_mat(idx, vTDeltaIdx, S);
b.set_sub_vec(idx, VectorNd::zero(1));
idx += 1;
// Tv(t + t_delta) = 0 (no tangent velocity)
A.set_sub_mat(idx, vTDeltaIdx, T);
b.set_sub_vec(idx, VectorNd::zero(1));
idx += 1;
// J_robot(transpose) * Q(transpose) * f_robot = torques
// Transformed to:
// J_Robot(transpose) * Q(transpose) * f_robot - I * torques = 0
MatrixNd JQ(req.torque_limits.size(), 1);
MatrixNd Jt(JRobot.columns(), JRobot.rows());
JRobot.transpose(Jt);
Jt.mult(MatrixNd(Q, eTranspose), JQ);
A.set_sub_mat(idx, fRobotIdx, JQ);
A.set_sub_mat(idx, torqueIdx, MatrixNd::identity(req.torque_limits.size()).negate());
b.set_sub_vec(idx, VectorNd::zero(req.torque_limits.size()));
idx += req.torque_limits.size();
// v_(t + t_delta) = v_t + M_inv (N_t * f_n + S_t * f_s + T_t * f_t + delta_t * f_ext + Q_t * delta_t * f_robot)
// Manipulated to fit constraint form
// -v_t - M_inv * delta_t * f_ext = M_inv * N_t * f_n + M_inv * S_t * f_s + M_inv * T_t * f_t + M_inv * Q_t * delta_t * f_robot + -I * v_(t + t_delta)
LinAlgd linAlgd;
MatrixNd MInverse = M;
linAlgd.pseudo_invert(MInverse);
MatrixNd MInverseN(MInverse.rows(), N.columns());
MInverse.mult(N, MInverseN);
A.set_sub_mat(idx, fNIdx, MInverseN);
MatrixNd MInverseS(MInverse.rows(), S.columns());
MInverse.mult(S, MInverseS);
A.set_sub_mat(idx, fSIdx, MInverseS);
MatrixNd MInverseT(MInverse.rows(), T.columns());
MInverse.mult(T, MInverseT);
A.set_sub_mat(idx, fTIdx, MInverseT);
MatrixNd MInverseQ(MInverse.rows(), Q.columns());
MInverse.mult(Q, MInverseQ);
MInverseQ *= deltaT;
A.set_sub_mat(idx, fRobotIdx, MInverseQ);
A.set_sub_mat(idx, vTDeltaIdx, MatrixNd::identity(6).negate());
VectorNd MInverseFExt(6);
MInverseFExt.set_zero();
MInverse.mult(fExt, MInverseFExt, deltaT);
MInverseFExt.negate() -= v;
b.set_sub_vec(idx, MInverseFExt);
// Linear inequality constraints
MatrixNd Mc(6, z.size());
VectorNd q(6);
// Nv(t) >= 0 (non-negative normal velocity)
Mc.set_sub_mat(0, vTDeltaIdx, N);
q.set_sub_vec(0, VectorNd::zero(6));
// Solution variable constraint
VectorNd lb(z.size());
VectorNd ub(z.size());
// Torque constraints
unsigned int bound = 0;
for (bound; bound < req.torque_limits.size(); ++bound) {
lb[bound] = req.torque_limits[bound].minimum;
ub[bound] = req.torque_limits[bound].maximum;
}
// f_n >= 0
lb[bound] = 0;
ub[bound] = INFINITY;
++bound;
// f_s (no constraints)
lb[bound] = INFINITY;
ub[bound] = INFINITY;
++bound;
// f_t (no constraints)
lb[bound] = INFINITY;
ub[bound] = INFINITY;
++bound;
// f_robot >= 0
lb[bound] = 0;
ub[bound] = INFINITY;
++bound;
// v_t (no constraints)
for (bound; bound < z.size(); ++bound) {
lb[bound] = INFINITY;
ub[bound] = INFINITY;
}
// Call solver
Moby::QPOASES qp;
if (!qp.qp_activeset(H, p, lb, ub, Mc, q, A, b, z)){
ROS_ERROR("QP failed to find feasible point");
return false;
}
ROS_INFO_STREAM("QP solved successfully: " << z);
// Copy over result
res.torques.resize(req.torque_limits.size());
for (unsigned int i = 0; i < z.size(); ++i) {
res.torques[i] = z[i];
}
return true;
}
};
}
int main(int argc, char** argv) {
ros::init(argc, argv, "balancer");
Balancer bal;
ros::spin();
}
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice 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 "OgreGLES2FBOMultiRenderTarget.h"
namespace Ogre {
GLES2FBOMultiRenderTarget::GLES2FBOMultiRenderTarget(GLES2FBOManager *manager, const String &name):
MultiRenderTarget(name),
fbo(manager, 0 /* TODO: multisampling on MRTs? */)
{
}
GLES2FBOMultiRenderTarget::~GLES2FBOMultiRenderTarget()
{
}
void GLES2FBOMultiRenderTarget::bindSurfaceImpl(size_t attachment, RenderTexture *target)
{
#if GL_OES_packed_depth_stencil
/// Check if the render target is in the rendertarget->FBO map
GLES2FrameBufferObject *fbobj = 0;
target->getCustomAttribute("FBO", &fbobj);
assert(fbobj);
fbo.bindSurface(attachment, fbobj->getSurface(0));
GL_CHECK_ERROR;
#endif
// Initialise?
// Set width and height
mWidth = fbo.getWidth();
mHeight = fbo.getHeight();
}
void GLES2FBOMultiRenderTarget::unbindSurfaceImpl(size_t attachment)
{
fbo.unbindSurface(attachment);
GL_CHECK_ERROR;
// Set width and height
mWidth = fbo.getWidth();
mHeight = fbo.getHeight();
}
void GLES2FBOMultiRenderTarget::getCustomAttribute( const String& name, void *pData )
{
if(name=="FBO")
{
*static_cast<GLES2FrameBufferObject **>(pData) = &fbo;
}
}
//-----------------------------------------------------------------------------
bool GLES2FBOMultiRenderTarget::attachDepthBuffer( DepthBuffer *depthBuffer )
{
bool result;
if( (result = MultiRenderTarget::attachDepthBuffer( depthBuffer )) )
fbo.attachDepthBuffer( depthBuffer );
return result;
}
//-----------------------------------------------------------------------------
void GLES2FBOMultiRenderTarget::detachDepthBuffer()
{
fbo.detachDepthBuffer();
MultiRenderTarget::detachDepthBuffer();
}
//-----------------------------------------------------------------------------
void GLES2FBOMultiRenderTarget::_detachDepthBuffer()
{
fbo.detachDepthBuffer();
MultiRenderTarget::_detachDepthBuffer();
}
}
<commit_msg>Fix the GLES 2 build<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice 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 "OgreGLES2FBOMultiRenderTarget.h"
#include "OgreLogManager.h"
namespace Ogre {
GLES2FBOMultiRenderTarget::GLES2FBOMultiRenderTarget(GLES2FBOManager *manager, const String &name):
MultiRenderTarget(name),
fbo(manager, 0 /* TODO: multisampling on MRTs? */)
{
}
GLES2FBOMultiRenderTarget::~GLES2FBOMultiRenderTarget()
{
}
void GLES2FBOMultiRenderTarget::bindSurfaceImpl(size_t attachment, RenderTexture *target)
{
#if GL_OES_packed_depth_stencil
/// Check if the render target is in the rendertarget->FBO map
GLES2FrameBufferObject *fbobj = 0;
target->getCustomAttribute("FBO", &fbobj);
assert(fbobj);
fbo.bindSurface(attachment, fbobj->getSurface(0));
GL_CHECK_ERROR;
#endif
// Initialise?
// Set width and height
mWidth = fbo.getWidth();
mHeight = fbo.getHeight();
}
void GLES2FBOMultiRenderTarget::unbindSurfaceImpl(size_t attachment)
{
fbo.unbindSurface(attachment);
GL_CHECK_ERROR;
// Set width and height
mWidth = fbo.getWidth();
mHeight = fbo.getHeight();
}
void GLES2FBOMultiRenderTarget::getCustomAttribute( const String& name, void *pData )
{
if(name=="FBO")
{
*static_cast<GLES2FrameBufferObject **>(pData) = &fbo;
}
}
//-----------------------------------------------------------------------------
bool GLES2FBOMultiRenderTarget::attachDepthBuffer( DepthBuffer *depthBuffer )
{
bool result;
if( (result = MultiRenderTarget::attachDepthBuffer( depthBuffer )) )
fbo.attachDepthBuffer( depthBuffer );
return result;
}
//-----------------------------------------------------------------------------
void GLES2FBOMultiRenderTarget::detachDepthBuffer()
{
fbo.detachDepthBuffer();
MultiRenderTarget::detachDepthBuffer();
}
//-----------------------------------------------------------------------------
void GLES2FBOMultiRenderTarget::_detachDepthBuffer()
{
fbo.detachDepthBuffer();
MultiRenderTarget::_detachDepthBuffer();
}
}
<|endoftext|> |
<commit_before>// Copyright 2016,xiong feng.
#include "RpcServer.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <memory>
#include <vector>
#include <string>
#include "glog/logging.h"
#include "RpcConnection.h"
#include "IterNetFunc.h"
#include "IterNetAddress.h"
#include "ReactorLoop.h"
#include "Event.h"
#include "Mutex.h"
#include "Task.h"
#include "Thread.h"
#include "EpollMultiplex.h"
#include "IterNetFunc.h"
#include "RpcConnectionFactory.h"
using namespace minirpc;
class AcceptTask : public Task
{
public:
explicit AcceptTask(RpcServer::Impl *impl)
: impl_(impl)
{
}
virtual ~AcceptTask()
{
}
std::string taskName()
{
return "AcceptTask";
}
void handle() const override;
private:
RpcServer::Impl *impl_;
};
class acceptEventHandler:public EventHandler
{
public:
explicit acceptEventHandler(RpcServer::Impl* impl)
:impl_(impl)
{
}
virtual ~acceptEventHandler()
{
}
void handlePacket() override;
private:
RpcServer::Impl* impl_;
};
class RpcServer::Impl
{
public:
Impl(std::vector<ReactorLoop*> loop, const string &host,
int port, ServerMessageHandlerFactory *factory);
~Impl();
void handleAccept();
void addAcceptEvent();
void start();
private:
std::vector<ReactorLoop*> loop_;
NetAddress listen_address_;
std::unique_ptr<Event> acceptEvent_;
int listen_fd_;
int idleFd_;
bool listenning_;
bool started_;
std::shared_ptr<RpcConnectionFactory> manager_;
std::shared_ptr<AcceptTask> acceptTask_;
size_t round_robin_;
};
RpcServer::Impl::Impl(std::vector<ReactorLoop*> loop, const string &host,
int port, ServerMessageHandlerFactory *factory)
: loop_(loop),
listen_address_(host, port),
listen_fd_(0),
idleFd_(::open("/dev/null", O_RDONLY | O_CLOEXEC)),
listenning_(false),
manager_(new RpcConnectionFactory(factory)),
acceptTask_(new AcceptTask(this)),
round_robin_(0)
{
}
RpcServer::Impl::~Impl()
{
LOG(INFO) << "RpcServer " << this << " die ";
loop_[0]->deleteEvent(acceptEvent_.get());
::close(listen_fd_);
::close(idleFd_);
}
void RpcServer::Impl::handleAccept()
{
int fd = -1;
bool result = false;
while (true)
{
struct sockaddr_in address;
result = NetFunc::Accept(listen_fd_, &address, &fd, &idleFd_);
if (result == false)
{
return;
}
if (fd == 0)
{
break;
}
NetAddress client_address(address);
LOG(INFO) << "accept connection from " << client_address.DebugString()
<< ", fd: " << fd;
std::shared_ptr<RpcConnection> connection = manager_->getConnection(fd);
LOG(INFO) << "connection " << connection
<< "use count" << connection.use_count();
connection->setAddress(address);
auto size = loop_.size();
round_robin_ = (round_robin_+1)%(size);
if (size > 1 && round_robin_ == 0)
round_robin_++;
connection->setReactorLoop(loop_[round_robin_]);
connection->start();
}
}
void RpcServer::Impl::start()
{
listen_fd_ = NetFunc::Listen(listen_address_);
acceptEvent_.reset(new Event(listen_fd_));
LOG(INFO) << "create listen fd " << listen_fd_ << " for "
<< listen_address_.DebugString();
acceptEvent_->setReadHandler(new acceptEventHandler(this));
acceptEvent_->disableWriting();
loop_[0]->runTask(acceptTask_);
}
void RpcServer::Impl::addAcceptEvent()
{
LOG(INFO)<< "Add accept event to loop" << loop_[0];
loop_[0]->addEvent(acceptEvent_.get());
}
void acceptEventHandler::handlePacket()
{
impl_->handleAccept();
}
void AcceptTask::handle() const
{
impl_->addAcceptEvent();
}
//////////////////RpcServer///
RpcServer::RpcServer(std::vector<ReactorLoop*> loop, const string &host,
int port, ServerMessageHandlerFactory *factory)
//: impl_{ std::make_unique<Impl>() } //only c++14
: impl_( new Impl(loop, host, port, factory) )
{
}
RpcServer::~RpcServer()
{
}
void RpcServer::start()
{
impl_->start();
}
<commit_msg>Update RpcServer.cpp<commit_after>// Copyright 2016,xiong feng.
#include "RpcServer.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <memory>
#include <vector>
#include <string>
#include "glog/logging.h"
#include "RpcConnection.h"
#include "IterNetFunc.h"
#include "IterNetAddress.h"
#include "ReactorLoop.h"
#include "Event.h"
#include "Mutex.h"
#include "Task.h"
#include "Thread.h"
#include "EpollMultiplex.h"
#include "IterNetFunc.h"
#include "RpcConnectionFactory.h"
using namespace minirpc;
class AcceptTask : public Task
{
public:
explicit AcceptTask(RpcServer::Impl *impl)
: impl_(impl)
{
}
std::string taskName()
{
return "AcceptTask";
}
void handle() const override;
private:
RpcServer::Impl *impl_;
};
class acceptEventHandler:public EventHandler
{
public:
explicit acceptEventHandler(RpcServer::Impl* impl)
:impl_(impl)
{
}
void handlePacket() override;
private:
RpcServer::Impl* impl_;
};
class RpcServer::Impl
{
public:
Impl(std::vector<ReactorLoop*> loop, const string &host,
int port, ServerMessageHandlerFactory *factory);
~Impl();
void handleAccept();
void addAcceptEvent();
void start();
private:
std::vector<ReactorLoop*> loop_;
NetAddress listen_address_;
std::unique_ptr<Event> acceptEvent_;
int listen_fd_;
int idleFd_;
bool listenning_;
bool started_;
std::shared_ptr<RpcConnectionFactory> manager_;
std::shared_ptr<AcceptTask> acceptTask_;
size_t round_robin_;
};
RpcServer::Impl::Impl(std::vector<ReactorLoop*> loop, const string &host,
int port, ServerMessageHandlerFactory *factory)
: loop_(loop),
listen_address_(host, port),
listen_fd_(0),
idleFd_(::open("/dev/null", O_RDONLY | O_CLOEXEC)),
listenning_(false),
manager_(new RpcConnectionFactory(factory)),
acceptTask_(new AcceptTask(this)),
round_robin_(0)
{
}
RpcServer::Impl::~Impl()
{
LOG(INFO) << "RpcServer " << this << " die ";
loop_[0]->deleteEvent(acceptEvent_.get());
::close(listen_fd_);
::close(idleFd_);
}
void RpcServer::Impl::handleAccept()
{
int fd = -1;
bool result = false;
while (true)
{
struct sockaddr_in address;
result = NetFunc::Accept(listen_fd_, &address, &fd, &idleFd_);
if (result == false)
{
return;
}
if (fd == 0)
{
break;
}
NetAddress client_address(address);
LOG(INFO) << "accept connection from " << client_address.DebugString()
<< ", fd: " << fd;
std::shared_ptr<RpcConnection> connection = manager_->getConnection(fd);
LOG(INFO) << "connection " << connection
<< "use count" << connection.use_count();
connection->setAddress(address);
auto size = loop_.size();
round_robin_ = (round_robin_+1)%(size);
if (size > 1 && round_robin_ == 0)
round_robin_++;
connection->setReactorLoop(loop_[round_robin_]);
connection->start();
}
}
void RpcServer::Impl::start()
{
listen_fd_ = NetFunc::Listen(listen_address_);
acceptEvent_.reset(new Event(listen_fd_));
LOG(INFO) << "create listen fd " << listen_fd_ << " for "
<< listen_address_.DebugString();
acceptEvent_->setReadHandler(new acceptEventHandler(this));
acceptEvent_->disableWriting();
loop_[0]->runTask(acceptTask_);
}
void RpcServer::Impl::addAcceptEvent()
{
LOG(INFO)<< "Add accept event to loop" << loop_[0];
loop_[0]->addEvent(acceptEvent_.get());
}
void acceptEventHandler::handlePacket()
{
impl_->handleAccept();
}
void AcceptTask::handle() const
{
impl_->addAcceptEvent();
}
//////////////////RpcServer///
RpcServer::RpcServer(std::vector<ReactorLoop*> loop, const string &host,
int port, ServerMessageHandlerFactory *factory)
//: impl_{ std::make_unique<Impl>() } //only c++14
: impl_( new Impl(loop, host, port, factory) )
{
}
RpcServer::~RpcServer()
{
}
void RpcServer::start()
{
impl_->start();
}
<|endoftext|> |
<commit_before>//===- ComputeClosure.cpp - Implement interprocedural closing of graphs ---===//
//
// Compute the interprocedural closure of a data structure graph
//
//===----------------------------------------------------------------------===//
// DEBUG_IP_CLOSURE - Define this to debug the act of linking up graphs
//#define DEBUG_IP_CLOSURE 1
#include "llvm/Analysis/DataStructure.h"
#include "llvm/iOther.h"
#include "Support/STLExtras.h"
#include <algorithm>
#ifdef DEBUG_IP_CLOSURE
#include "llvm/Assembly/Writer.h"
#endif
// Make all of the pointers that point to Val also point to N.
//
static void copyEdgesFromTo(PointerVal Val, DSNode *N) {
assert(Val.Index == 0 && "copyEdgesFromTo:index != 0 TODO");
const vector<PointerValSet*> &PVSToUpdate(Val.Node->getReferrers());
for (unsigned i = 0, e = PVSToUpdate.size(); i != e; ++i)
PVSToUpdate[i]->add(N); // TODO: support index
}
static void ResolveNodesTo(const PointerVal &FromPtr,
const PointerValSet &ToVals) {
assert(FromPtr.Index == 0 &&
"Resolved node return pointer should be index 0!");
assert(isa<ShadowDSNode>(FromPtr.Node) &&
"Resolved node should be a shadow!");
ShadowDSNode *Shadow = cast<ShadowDSNode>(FromPtr.Node);
assert(Shadow->isCriticalNode() && "Shadow node should be a critical node!");
Shadow->resetCriticalMark();
// Make everything that pointed to the shadow node also point to the values in
// ToVals...
//
for (unsigned i = 0, e = ToVals.size(); i != e; ++i)
copyEdgesFromTo(ToVals[i], Shadow);
// Make everything that pointed to the shadow node now also point to the
// values it is equivalent to...
const vector<PointerValSet*> &PVSToUpdate(Shadow->getReferrers());
for (unsigned i = 0, e = PVSToUpdate.size(); i != e; ++i)
PVSToUpdate[i]->add(ToVals);
}
// ResolveNodeTo - The specified node is now known to point to the set of values
// in ToVals, instead of the old shadow node subgraph that it was pointing to.
//
static void ResolveNodeTo(DSNode *Node, const PointerValSet &ToVals) {
assert(Node->getNumLinks() == 1 && "Resolved node can only be a scalar!!");
const PointerValSet &PVS = Node->getLink(0);
// Only resolve the first pointer, although there many be many pointers here.
// The problem is that the inlined function might return one of the arguments
// to the function, and if so, extra values can be added to the arg or call
// node that point to what the other one got resolved to. Since these will
// be added to the end of the PVS pointed in, we just ignore them.
//
ResolveNodesTo(PVS[0], ToVals);
}
// isResolvableCallNode - Return true if node is a call node and it is a call
// node that we can inline...
//
static bool isResolvableCallNode(CallDSNode *CN) {
// Only operate on call nodes with direct method calls
Function *F = CN->getCall()->getCalledFunction();
if (F == 0) return false;
// Only work on call nodes with direct calls to methods with bodies.
return !F->isExternal();
}
// computeClosure - Replace all of the resolvable call nodes with the contents
// of their corresponding method data structure graph...
//
void FunctionDSGraph::computeClosure(const DataStructure &DS) {
// Note that this cannot be a real vector because the keys will be changing
// as nodes are eliminated!
//
typedef pair<vector<PointerValSet>, CallInst *> CallDescriptor;
vector<pair<CallDescriptor, PointerValSet> > CallMap;
unsigned NumInlines = 0;
// Loop over the resolvable call nodes...
vector<CallDSNode*>::iterator NI;
NI = std::find_if(CallNodes.begin(), CallNodes.end(), isResolvableCallNode);
while (NI != CallNodes.end()) {
CallDSNode *CN = *NI;
Function *F = CN->getCall()->getCalledFunction();
if (NumInlines++ == 20) { // CUTE hack huh?
cerr << "Infinite (?) recursion halted\n";
return;
}
CallNodes.erase(NI); // Remove the call node from the graph
unsigned CallNodeOffset = NI-CallNodes.begin();
// Find out if we have already incorporated this node... if so, it will be
// in the CallMap...
//
#if 0
cerr << "\nSearching for: " << (void*)CN->getCall() << ": ";
for (unsigned X = 0; X != CN->getArgs().size(); ++X) {
cerr << " " << X << " is\n";
CN->getArgs().first[X].print(cerr);
}
#endif
const vector<PointerValSet> &Args = CN->getArgs();
PointerValSet *CMI = 0;
for (unsigned i = 0, e = CallMap.size(); i != e; ++i) {
#if 0
cerr << "Found: " << (void*)CallMap[i].first.second << ": ";
for (unsigned X = 0; X != CallMap[i].first.first.size(); ++X) {
cerr << " " << X << " is\n"; CallMap[i].first.first[X].print(cerr);
}
#endif
// Look to see if the function call takes a superset of the values we are
// providing as input
//
CallDescriptor &CD = CallMap[i].first;
if (CD.second == CN->getCall() && CD.first.size() == Args.size()) {
bool FoundMismatch = false;
for (unsigned j = 0, je = Args.size(); j != je; ++j) {
PointerValSet ArgSet = CD.first[j];
if (ArgSet.add(Args[j])) {
FoundMismatch = true; break;
}
}
if (!FoundMismatch) { CMI = &CallMap[i].second; break; }
}
}
// Hold the set of values that correspond to the incorporated methods
// return set.
//
PointerValSet RetVals;
if (CMI) {
// We have already inlined an identical function call!
RetVals = *CMI;
} else {
// Get the datastructure graph for the new method. Note that we are not
// allowed to modify this graph because it will be the cached graph that
// is returned by other users that want the local datastructure graph for
// a method.
//
const FunctionDSGraph &NewFunction = DS.getDSGraph(F);
// StartNode - The first node of the incorporated graph, last node of the
// preexisting data structure graph...
//
unsigned StartArgNode = ArgNodes.size();
unsigned StartAllocNode = AllocNodes.size();
// Incorporate a copy of the called function graph into the current graph,
// allowing us to do local transformations to local graph to link
// arguments to call values, and call node to return value...
//
RetVals = cloneFunctionIntoSelf(NewFunction, false);
CallMap.push_back(make_pair(CallDescriptor(CN->getArgs(), CN->getCall()),
RetVals));
// If the call node has arguments, process them now!
if (CN->getNumArgs()) {
// The ArgNodes of the incorporated graph should be the nodes starting
// at StartNode, ordered the same way as the call arguments. The arg
// nodes are seperated by a single shadow node, but that shadow node
// might get eliminated in the process of optimization.
//
for (unsigned i = 0, e = CN->getNumArgs(); i != e; ++i) {
// Get the arg node of the incorporated method...
ArgDSNode *ArgNode = ArgNodes[StartArgNode];
// Now we make all of the nodes inside of the incorporated method
// point to the real arguments values, not to the shadow nodes for the
// argument.
//
ResolveNodeTo(ArgNode, CN->getArgValues(i));
// Remove the argnode from the set of nodes in this method...
ArgNodes.erase(ArgNodes.begin()+StartArgNode);
// ArgNode is no longer useful, delete now!
delete ArgNode;
}
}
// Loop through the nodes, deleting alloca nodes in the inlined function.
// Since the memory has been released, we cannot access their pointer
// fields (with defined results at least), so it is not possible to use
// any pointers to the alloca. Drop them now, and remove the alloca's
// since they are dead (we just removed all links to them).
//
for (unsigned i = StartAllocNode; i != AllocNodes.size(); ++i)
if (AllocNodes[i]->isAllocaNode()) {
AllocDSNode *NDS = AllocNodes[i];
NDS->removeAllIncomingEdges(); // These edges are invalid now
delete NDS; // Node is dead
AllocNodes.erase(AllocNodes.begin()+i); // Remove slot in Nodes array
--i; // Don't skip the next node
}
}
// If the function returns a pointer value... Resolve values pointing to
// the shadow nodes pointed to by CN to now point the values in RetVals...
//
if (CN->getNumLinks()) ResolveNodeTo(CN, RetVals);
// Now the call node is completely destructable. Eliminate it now.
delete CN;
bool Changed = true;
while (Changed) {
// Eliminate shadow nodes that are not distinguishable from some other
// node in the graph...
//
Changed = UnlinkUndistinguishableNodes();
// Eliminate shadow nodes that are now extraneous due to linking...
Changed |= RemoveUnreachableNodes();
}
//if (F == Func) return; // Only do one self inlining
// Move on to the next call node...
NI = std::find_if(CallNodes.begin(), CallNodes.end(), isResolvableCallNode);
}
}
<commit_msg>Increase limit for perimeter<commit_after>//===- ComputeClosure.cpp - Implement interprocedural closing of graphs ---===//
//
// Compute the interprocedural closure of a data structure graph
//
//===----------------------------------------------------------------------===//
// DEBUG_IP_CLOSURE - Define this to debug the act of linking up graphs
//#define DEBUG_IP_CLOSURE 1
#include "llvm/Analysis/DataStructure.h"
#include "llvm/iOther.h"
#include "Support/STLExtras.h"
#include <algorithm>
#ifdef DEBUG_IP_CLOSURE
#include "llvm/Assembly/Writer.h"
#endif
// Make all of the pointers that point to Val also point to N.
//
static void copyEdgesFromTo(PointerVal Val, DSNode *N) {
assert(Val.Index == 0 && "copyEdgesFromTo:index != 0 TODO");
const vector<PointerValSet*> &PVSToUpdate(Val.Node->getReferrers());
for (unsigned i = 0, e = PVSToUpdate.size(); i != e; ++i)
PVSToUpdate[i]->add(N); // TODO: support index
}
static void ResolveNodesTo(const PointerVal &FromPtr,
const PointerValSet &ToVals) {
assert(FromPtr.Index == 0 &&
"Resolved node return pointer should be index 0!");
assert(isa<ShadowDSNode>(FromPtr.Node) &&
"Resolved node should be a shadow!");
ShadowDSNode *Shadow = cast<ShadowDSNode>(FromPtr.Node);
assert(Shadow->isCriticalNode() && "Shadow node should be a critical node!");
Shadow->resetCriticalMark();
// Make everything that pointed to the shadow node also point to the values in
// ToVals...
//
for (unsigned i = 0, e = ToVals.size(); i != e; ++i)
copyEdgesFromTo(ToVals[i], Shadow);
// Make everything that pointed to the shadow node now also point to the
// values it is equivalent to...
const vector<PointerValSet*> &PVSToUpdate(Shadow->getReferrers());
for (unsigned i = 0, e = PVSToUpdate.size(); i != e; ++i)
PVSToUpdate[i]->add(ToVals);
}
// ResolveNodeTo - The specified node is now known to point to the set of values
// in ToVals, instead of the old shadow node subgraph that it was pointing to.
//
static void ResolveNodeTo(DSNode *Node, const PointerValSet &ToVals) {
assert(Node->getNumLinks() == 1 && "Resolved node can only be a scalar!!");
const PointerValSet &PVS = Node->getLink(0);
// Only resolve the first pointer, although there many be many pointers here.
// The problem is that the inlined function might return one of the arguments
// to the function, and if so, extra values can be added to the arg or call
// node that point to what the other one got resolved to. Since these will
// be added to the end of the PVS pointed in, we just ignore them.
//
ResolveNodesTo(PVS[0], ToVals);
}
// isResolvableCallNode - Return true if node is a call node and it is a call
// node that we can inline...
//
static bool isResolvableCallNode(CallDSNode *CN) {
// Only operate on call nodes with direct method calls
Function *F = CN->getCall()->getCalledFunction();
if (F == 0) return false;
// Only work on call nodes with direct calls to methods with bodies.
return !F->isExternal();
}
// computeClosure - Replace all of the resolvable call nodes with the contents
// of their corresponding method data structure graph...
//
void FunctionDSGraph::computeClosure(const DataStructure &DS) {
// Note that this cannot be a real vector because the keys will be changing
// as nodes are eliminated!
//
typedef pair<vector<PointerValSet>, CallInst *> CallDescriptor;
vector<pair<CallDescriptor, PointerValSet> > CallMap;
unsigned NumInlines = 0;
// Loop over the resolvable call nodes...
vector<CallDSNode*>::iterator NI;
NI = std::find_if(CallNodes.begin(), CallNodes.end(), isResolvableCallNode);
while (NI != CallNodes.end()) {
CallDSNode *CN = *NI;
Function *F = CN->getCall()->getCalledFunction();
if (NumInlines++ == 40) { // CUTE hack huh?
cerr << "Infinite (?) recursion halted\n";
return;
}
CallNodes.erase(NI); // Remove the call node from the graph
unsigned CallNodeOffset = NI-CallNodes.begin();
// Find out if we have already incorporated this node... if so, it will be
// in the CallMap...
//
#if 0
cerr << "\nSearching for: " << (void*)CN->getCall() << ": ";
for (unsigned X = 0; X != CN->getArgs().size(); ++X) {
cerr << " " << X << " is\n";
CN->getArgs().first[X].print(cerr);
}
#endif
const vector<PointerValSet> &Args = CN->getArgs();
PointerValSet *CMI = 0;
for (unsigned i = 0, e = CallMap.size(); i != e; ++i) {
#if 0
cerr << "Found: " << (void*)CallMap[i].first.second << ": ";
for (unsigned X = 0; X != CallMap[i].first.first.size(); ++X) {
cerr << " " << X << " is\n"; CallMap[i].first.first[X].print(cerr);
}
#endif
// Look to see if the function call takes a superset of the values we are
// providing as input
//
CallDescriptor &CD = CallMap[i].first;
if (CD.second == CN->getCall() && CD.first.size() == Args.size()) {
bool FoundMismatch = false;
for (unsigned j = 0, je = Args.size(); j != je; ++j) {
PointerValSet ArgSet = CD.first[j];
if (ArgSet.add(Args[j])) {
FoundMismatch = true; break;
}
}
if (!FoundMismatch) { CMI = &CallMap[i].second; break; }
}
}
// Hold the set of values that correspond to the incorporated methods
// return set.
//
PointerValSet RetVals;
if (CMI) {
// We have already inlined an identical function call!
RetVals = *CMI;
} else {
// Get the datastructure graph for the new method. Note that we are not
// allowed to modify this graph because it will be the cached graph that
// is returned by other users that want the local datastructure graph for
// a method.
//
const FunctionDSGraph &NewFunction = DS.getDSGraph(F);
// StartNode - The first node of the incorporated graph, last node of the
// preexisting data structure graph...
//
unsigned StartArgNode = ArgNodes.size();
unsigned StartAllocNode = AllocNodes.size();
// Incorporate a copy of the called function graph into the current graph,
// allowing us to do local transformations to local graph to link
// arguments to call values, and call node to return value...
//
RetVals = cloneFunctionIntoSelf(NewFunction, false);
CallMap.push_back(make_pair(CallDescriptor(CN->getArgs(), CN->getCall()),
RetVals));
// If the call node has arguments, process them now!
if (CN->getNumArgs()) {
// The ArgNodes of the incorporated graph should be the nodes starting
// at StartNode, ordered the same way as the call arguments. The arg
// nodes are seperated by a single shadow node, but that shadow node
// might get eliminated in the process of optimization.
//
for (unsigned i = 0, e = CN->getNumArgs(); i != e; ++i) {
// Get the arg node of the incorporated method...
ArgDSNode *ArgNode = ArgNodes[StartArgNode];
// Now we make all of the nodes inside of the incorporated method
// point to the real arguments values, not to the shadow nodes for the
// argument.
//
ResolveNodeTo(ArgNode, CN->getArgValues(i));
// Remove the argnode from the set of nodes in this method...
ArgNodes.erase(ArgNodes.begin()+StartArgNode);
// ArgNode is no longer useful, delete now!
delete ArgNode;
}
}
// Loop through the nodes, deleting alloca nodes in the inlined function.
// Since the memory has been released, we cannot access their pointer
// fields (with defined results at least), so it is not possible to use
// any pointers to the alloca. Drop them now, and remove the alloca's
// since they are dead (we just removed all links to them).
//
for (unsigned i = StartAllocNode; i != AllocNodes.size(); ++i)
if (AllocNodes[i]->isAllocaNode()) {
AllocDSNode *NDS = AllocNodes[i];
NDS->removeAllIncomingEdges(); // These edges are invalid now
delete NDS; // Node is dead
AllocNodes.erase(AllocNodes.begin()+i); // Remove slot in Nodes array
--i; // Don't skip the next node
}
}
// If the function returns a pointer value... Resolve values pointing to
// the shadow nodes pointed to by CN to now point the values in RetVals...
//
if (CN->getNumLinks()) ResolveNodeTo(CN, RetVals);
// Now the call node is completely destructable. Eliminate it now.
delete CN;
bool Changed = true;
while (Changed) {
// Eliminate shadow nodes that are not distinguishable from some other
// node in the graph...
//
Changed = UnlinkUndistinguishableNodes();
// Eliminate shadow nodes that are now extraneous due to linking...
Changed |= RemoveUnreachableNodes();
}
//if (F == Func) return; // Only do one self inlining
// Move on to the next call node...
NI = std::find_if(CallNodes.begin(), CallNodes.end(), isResolvableCallNode);
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
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 author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_UPNP_HPP
#define TORRENT_UPNP_HPP
#include "libtorrent/socket.hpp"
#include "libtorrent/http_connection.hpp"
#include "libtorrent/connection_queue.hpp"
#include <boost/function.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <set>
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
#include <fstream>
#endif
namespace libtorrent
{
// int: external tcp port
// int: external udp port
// std::string: error message
typedef boost::function<void(int, int, std::string const&)> portmap_callback_t;
class upnp : boost::noncopyable
{
public:
upnp(io_service& ios, connection_queue& cc
, address const& listen_interface, std::string const& user_agent
, portmap_callback_t const& cb);
~upnp();
void rebind(address const& listen_interface);
// maps the ports, if a port is set to 0
// it will not be mapped
void set_mappings(int tcp, int udp);
void close();
private:
static address_v4 upnp_multicast_address;
static udp::endpoint upnp_multicast_endpoint;
enum { num_mappings = 2 };
enum { default_lease_time = 3600 };
void update_mapping(int i, int port);
void resend_request(asio::error_code const& e);
void on_reply(asio::error_code const& e
, std::size_t bytes_transferred);
void discover_device();
struct rootdevice;
void on_upnp_xml(asio::error_code const& e
, libtorrent::http_parser const& p, rootdevice& d);
void on_upnp_map_response(asio::error_code const& e
, libtorrent::http_parser const& p, rootdevice& d
, int mapping);
void on_upnp_unmap_response(asio::error_code const& e
, libtorrent::http_parser const& p, rootdevice& d
, int mapping);
void on_expire(asio::error_code const& e);
void post(rootdevice& d, std::stringstream const& s
, std::string const& soap_action);
void map_port(rootdevice& d, int i);
void unmap_port(rootdevice& d, int i);
struct mapping_t
{
mapping_t()
: need_update(false)
, local_port(0)
, external_port(0)
, protocol(1)
{}
// the time the port mapping will expire
ptime expires;
bool need_update;
// the local port for this mapping. If this is set
// to 0, the mapping is not in use
int local_port;
// the external (on the NAT router) port
// for the mapping. This is the port we
// should announce to others
int external_port;
// 1 = udp, 0 = tcp
int protocol;
};
struct rootdevice
{
rootdevice(): lease_duration(default_lease_time)
, supports_specific_external(true)
, service_namespace(0)
{
mapping[0].protocol = 0;
mapping[1].protocol = 1;
}
// the interface url, through which the list of
// supported interfaces are fetched
std::string url;
// the url to the WANIP or WANPPP interface
std::string control_url;
// either the WANIP namespace or the WANPPP namespace
char const* service_namespace;
mapping_t mapping[num_mappings];
std::string hostname;
int port;
std::string path;
int lease_duration;
// true if the device supports specifying a
// specific external port, false if it doesn't
bool supports_specific_external;
boost::shared_ptr<http_connection> upnp_connection;
void close() const { if (upnp_connection) upnp_connection->close(); }
bool operator<(rootdevice const& rhs) const
{ return url < rhs.url; }
};
int m_udp_local_port;
int m_tcp_local_port;
std::string const& m_user_agent;
// the set of devices we've found
std::set<rootdevice> m_devices;
portmap_callback_t m_callback;
// current retry count
int m_retry_count;
// used to receive responses in
char m_receive_buffer[1024];
// the endpoint we received the message from
udp::endpoint m_remote;
// the local address we're listening on
address_v4 m_local_ip;
// the udp socket used to send and receive
// multicast messages on the network
datagram_socket m_socket;
// used to resend udp packets in case
// they time out
deadline_timer m_broadcast_timer;
// timer used to refresh mappings
deadline_timer m_refresh_timer;
asio::strand m_strand;
bool m_disabled;
bool m_closing;
connection_queue& m_cc;
#ifdef TORRENT_UPNP_LOGGING
std::ofstream m_log;
#endif
};
}
#endif
<commit_msg>fixed warnings in previous check in<commit_after>/*
Copyright (c) 2007, Arvid Norberg
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 author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_UPNP_HPP
#define TORRENT_UPNP_HPP
#include "libtorrent/socket.hpp"
#include "libtorrent/http_connection.hpp"
#include "libtorrent/connection_queue.hpp"
#include <boost/function.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <set>
#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)
#include <fstream>
#endif
namespace libtorrent
{
// int: external tcp port
// int: external udp port
// std::string: error message
typedef boost::function<void(int, int, std::string const&)> portmap_callback_t;
class upnp : boost::noncopyable
{
public:
upnp(io_service& ios, connection_queue& cc
, address const& listen_interface, std::string const& user_agent
, portmap_callback_t const& cb);
~upnp();
void rebind(address const& listen_interface);
// maps the ports, if a port is set to 0
// it will not be mapped
void set_mappings(int tcp, int udp);
void close();
private:
static address_v4 upnp_multicast_address;
static udp::endpoint upnp_multicast_endpoint;
enum { num_mappings = 2 };
enum { default_lease_time = 3600 };
void update_mapping(int i, int port);
void resend_request(asio::error_code const& e);
void on_reply(asio::error_code const& e
, std::size_t bytes_transferred);
void discover_device();
struct rootdevice;
void on_upnp_xml(asio::error_code const& e
, libtorrent::http_parser const& p, rootdevice& d);
void on_upnp_map_response(asio::error_code const& e
, libtorrent::http_parser const& p, rootdevice& d
, int mapping);
void on_upnp_unmap_response(asio::error_code const& e
, libtorrent::http_parser const& p, rootdevice& d
, int mapping);
void on_expire(asio::error_code const& e);
void post(rootdevice& d, std::stringstream const& s
, std::string const& soap_action);
void map_port(rootdevice& d, int i);
void unmap_port(rootdevice& d, int i);
struct mapping_t
{
mapping_t()
: need_update(false)
, local_port(0)
, external_port(0)
, protocol(1)
{}
// the time the port mapping will expire
ptime expires;
bool need_update;
// the local port for this mapping. If this is set
// to 0, the mapping is not in use
int local_port;
// the external (on the NAT router) port
// for the mapping. This is the port we
// should announce to others
int external_port;
// 1 = udp, 0 = tcp
int protocol;
};
struct rootdevice
{
rootdevice(): service_namespace(0)
, lease_duration(default_lease_time)
, supports_specific_external(true)
{
mapping[0].protocol = 0;
mapping[1].protocol = 1;
}
// the interface url, through which the list of
// supported interfaces are fetched
std::string url;
// the url to the WANIP or WANPPP interface
std::string control_url;
// either the WANIP namespace or the WANPPP namespace
char const* service_namespace;
mapping_t mapping[num_mappings];
std::string hostname;
int port;
std::string path;
int lease_duration;
// true if the device supports specifying a
// specific external port, false if it doesn't
bool supports_specific_external;
boost::shared_ptr<http_connection> upnp_connection;
void close() const { if (upnp_connection) upnp_connection->close(); }
bool operator<(rootdevice const& rhs) const
{ return url < rhs.url; }
};
int m_udp_local_port;
int m_tcp_local_port;
std::string const& m_user_agent;
// the set of devices we've found
std::set<rootdevice> m_devices;
portmap_callback_t m_callback;
// current retry count
int m_retry_count;
// used to receive responses in
char m_receive_buffer[1024];
// the endpoint we received the message from
udp::endpoint m_remote;
// the local address we're listening on
address_v4 m_local_ip;
// the udp socket used to send and receive
// multicast messages on the network
datagram_socket m_socket;
// used to resend udp packets in case
// they time out
deadline_timer m_broadcast_timer;
// timer used to refresh mappings
deadline_timer m_refresh_timer;
asio::strand m_strand;
bool m_disabled;
bool m_closing;
connection_queue& m_cc;
#ifdef TORRENT_UPNP_LOGGING
std::ofstream m_log;
#endif
};
}
#endif
<|endoftext|> |
<commit_before><commit_msg>Delete AliAnalysisTaskSEDvsRT.cxx<commit_after><|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "SupervisorFeature.h"
#include "ApplicationFeatures/DaemonFeature.h"
#include "Basics/ArangoGlobalContext.h"
#include "Logger/Logger.h"
#include "Logger/LoggerFeature.h"
#include "ProgramOptions/ProgramOptions.h"
#include "ProgramOptions/Section.h"
using namespace arangodb;
using namespace arangodb::application_features;
using namespace arangodb::basics;
using namespace arangodb::options;
namespace {
static bool DONE = false;
static int CLIENT_PID = false;
static char const* restartMessage = "will now start a new child process";
static char const* noRestartMessage = "will intentionally not start a new child process";
static char const* fixErrorMessage = "please check what causes the child process to fail and fix the error first";
static char const* translateSignal(int signal) {
if (signal >= 128) {
signal -= 128;
}
switch (signal) {
#ifdef SIGHUP
case SIGHUP: return "SIGHUP";
#endif
#ifdef SIGINT
case SIGINT: return "SIGINT";
#endif
#ifdef SIGQUIT
case SIGQUIT: return "SIGQUIT";
#endif
#ifdef SIGKILL
case SIGILL: return "SIGILL";
#endif
#ifdef SIGTRAP
case SIGTRAP: return "SIGTRAP";
#endif
#ifdef SIGABRT
case SIGABRT: return "SIGABRT";
#endif
#ifdef SIGBUS
case SIGBUS: return "SIGBUS";
#endif
#ifdef SIGFPE
case SIGFPE: return "SIGFPE";
#endif
#ifdef SIGKILL
case SIGKILL: return "SIGKILL";
#endif
#ifdef SIGSEGV
case SIGSEGV: return "SIGSEGV";
#endif
#ifdef SIGPIPE
case SIGPIPE: return "SIGPIPE";
#endif
#ifdef SIGTERM
case SIGTERM: return "SIGTERM";
#endif
#ifdef SIGCONT
case SIGCONT: return "SIGCONT";
#endif
#ifdef SIGSTOP
case SIGSTOP: return "SIGSTOP";
#endif
default: return "unknown";
}
}
static void StopHandler(int) {
LOG_TOPIC(INFO, Logger::STARTUP) << "received SIGINT for supervisor; commanding client [" << CLIENT_PID << "] to shut down.";
int rc = kill(CLIENT_PID, SIGTERM);
if (rc < 0) {
LOG_TOPIC(ERR, Logger::STARTUP) << "commanding client [" << CLIENT_PID << "] to shut down failed: [" << errno << "] " << strerror(errno);
}
DONE = true;
}
}
static void HUPHandler(int) {
LOG_TOPIC(INFO, Logger::STARTUP) << "received SIGHUP for supervisor; commanding client [" << CLIENT_PID << "] to logrotate.";
int rc = kill(CLIENT_PID, SIGHUP);
if (rc < 0) {
LOG_TOPIC(ERR, Logger::STARTUP) << "commanding client [" << CLIENT_PID << "] to logrotate failed: [" << errno << "] " << strerror(errno);
}
}
SupervisorFeature::SupervisorFeature(
application_features::ApplicationServer* server)
: ApplicationFeature(server, "Supervisor"), _supervisor(false), _clientPid(0) {
setOptional(true);
requiresElevatedPrivileges(false);
startsAfter("Daemon");
startsAfter("Logger");
startsAfter("WorkMonitor");
}
void SupervisorFeature::collectOptions(
std::shared_ptr<ProgramOptions> options) {
options->addHiddenOption("--supervisor",
"background the server, starts a supervisor",
new BooleanParameter(&_supervisor));
}
void SupervisorFeature::validateOptions(
std::shared_ptr<ProgramOptions> options) {
if (_supervisor) {
try {
DaemonFeature* daemon = ApplicationServer::getFeature<DaemonFeature>("Daemon");
// force daemon mode
daemon->setDaemon(true);
// revalidate options
daemon->validateOptions(options);
} catch (...) {
LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "daemon mode not available, cannot start supervisor";
FATAL_ERROR_EXIT();
}
}
}
void SupervisorFeature::daemonize() {
static time_t const MIN_TIME_ALIVE_IN_SEC = 30;
if (!_supervisor) {
return;
}
time_t startTime = time(0);
time_t t;
bool done = false;
int result = EXIT_SUCCESS;
// will be reseted in SchedulerFeature
ArangoGlobalContext::CONTEXT->unmaskStandardSignals();
LoggerFeature* logger = nullptr;
try {
logger = ApplicationServer::getFeature<LoggerFeature>("Logger");
} catch (...) {
LOG_TOPIC(FATAL, Logger::STARTUP)
<< "unknown feature 'Logger', giving up";
FATAL_ERROR_EXIT();
}
logger->setSupervisor(true);
logger->prepare();
LOG_TOPIC(DEBUG, Logger::STARTUP) << "starting supervisor loop";
while (!done) {
logger->setSupervisor(false);
signal(SIGINT, SIG_DFL);
signal(SIGTERM, SIG_DFL);
LOG_TOPIC(DEBUG, Logger::STARTUP) << "supervisor will now try to fork a new child process";
// fork of the server
_clientPid = fork();
if (_clientPid < 0) {
LOG_TOPIC(FATAL, Logger::STARTUP) << "fork failed, giving up";
FATAL_ERROR_EXIT();
}
// parent (supervisor)
if (0 < _clientPid) {
signal(SIGINT, StopHandler);
signal(SIGTERM, StopHandler);
signal(SIGHUP, HUPHandler);
LOG_TOPIC(INFO, Logger::STARTUP) << "supervisor has forked a child process with pid " << _clientPid;
TRI_SetProcessTitle("arangodb [supervisor]");
LOG_TOPIC(DEBUG, Logger::STARTUP) << "supervisor mode: within parent";
CLIENT_PID = _clientPid;
DONE = false;
int status;
int res = waitpid(_clientPid, &status, 0);
bool horrible = true;
LOG_TOPIC(INFO, Logger::STARTUP) << "waitpid woke up with return value "
<< res << " and status " << status
<< " and DONE = " << (DONE ? "true" : "false");
if (DONE) {
// signal handler for SIGINT or SIGTERM was invoked
done = true;
horrible = false;
}
else {
TRI_ASSERT(horrible);
if (WIFEXITED(status)) {
// give information about cause of death
if (WEXITSTATUS(status) == 0) {
LOG_TOPIC(INFO, Logger::STARTUP) << "child process " << _clientPid
<< " died of natural causes. " << noRestartMessage;
done = true;
horrible = false;
} else {
t = time(0) - startTime;
if (t < MIN_TIME_ALIVE_IN_SEC) {
LOG_TOPIC(ERR, Logger::STARTUP)
<< "child process " << _clientPid << " died a horrible death, exit status"
<< WEXITSTATUS(status) << ". the child process only survived for " << t
<< " seconds. this is lower than the minimum threshold value of " << MIN_TIME_ALIVE_IN_SEC
<< " s. " << noRestartMessage << ". " << fixErrorMessage;
done = true;
} else {
LOG_TOPIC(ERR, Logger::STARTUP)
<< "child process " << _clientPid
<< " died a horrible death, exit status " << WEXITSTATUS(status)
<< ". " << restartMessage;
done = false;
}
}
} else if (WIFSIGNALED(status)) {
int const s = WTERMSIG(status);
switch (s) {
case 2: // SIGINT
case 9: // SIGKILL
case 15: // SIGTERM
LOG_TOPIC(INFO, Logger::STARTUP)
<< "child process " << _clientPid
<< " died of natural causes, exit status " << s
<< " (" << translateSignal(s) << "). " << noRestartMessage;
done = true;
horrible = false;
break;
default:
TRI_ASSERT(horrible);
t = time(0) - startTime;
if (t < MIN_TIME_ALIVE_IN_SEC) {
LOG_TOPIC(ERR, Logger::STARTUP)
<< "child process " << _clientPid << " died a horrible death, signal "
<< s << " (" << translateSignal(s) << "). the child process only survived for " << t
<< " seconds. this is lower than the minimum threshold value of " << MIN_TIME_ALIVE_IN_SEC
<< " s. " << noRestartMessage << ". " << fixErrorMessage;
done = true;
#ifdef WCOREDUMP
if (WCOREDUMP(status)) {
LOG_TOPIC(WARN, Logger::STARTUP) << "child process "
<< _clientPid
<< " also produced a core dump";
}
#endif
} else {
LOG_TOPIC(ERR, Logger::STARTUP) << "child process " << _clientPid
<< " died a horrible death, signal "
<< s << " (" << translateSignal(s) << "). "
<< restartMessage;
done = false;
}
break;
}
} else {
LOG_TOPIC(ERR, Logger::STARTUP)
<< "child process " << _clientPid
<< " died a horrible death, unknown cause. " << restartMessage;
done = false;
}
}
if (horrible) {
result = EXIT_FAILURE;
} else {
result = EXIT_SUCCESS;
}
}
// child - run the normal boot sequence
else {
Logger::shutdown();
LOG_TOPIC(DEBUG, Logger::STARTUP) << "supervisor mode: within child";
TRI_SetProcessTitle("arangodb [server]");
#ifdef TRI_HAVE_PRCTL
// force child to stop if supervisor dies
prctl(PR_SET_PDEATHSIG, SIGTERM, 0, 0, 0);
#endif
try {
DaemonFeature* daemon = ApplicationServer::getFeature<DaemonFeature>("Daemon");
// disable daemon mode
daemon->setDaemon(false);
} catch (...) {
}
return;
}
}
LOG_TOPIC(DEBUG, Logger::STARTUP) << "supervisor mode: finished";
Logger::flush();
Logger::shutdown();
exit(result);
}
<commit_msg>Reword 'horrible' messages (#2531)<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "SupervisorFeature.h"
#include "ApplicationFeatures/DaemonFeature.h"
#include "Basics/ArangoGlobalContext.h"
#include "Logger/Logger.h"
#include "Logger/LoggerFeature.h"
#include "ProgramOptions/ProgramOptions.h"
#include "ProgramOptions/Section.h"
using namespace arangodb;
using namespace arangodb::application_features;
using namespace arangodb::basics;
using namespace arangodb::options;
namespace {
static bool DONE = false;
static int CLIENT_PID = false;
static char const* restartMessage = "will now start a new child process";
static char const* noRestartMessage = "will intentionally not start a new child process";
static char const* fixErrorMessage = "please check what causes the child process to fail and fix the error first";
static char const* translateSignal(int signal) {
if (signal >= 128) {
signal -= 128;
}
switch (signal) {
#ifdef SIGHUP
case SIGHUP: return "SIGHUP";
#endif
#ifdef SIGINT
case SIGINT: return "SIGINT";
#endif
#ifdef SIGQUIT
case SIGQUIT: return "SIGQUIT";
#endif
#ifdef SIGKILL
case SIGILL: return "SIGILL";
#endif
#ifdef SIGTRAP
case SIGTRAP: return "SIGTRAP";
#endif
#ifdef SIGABRT
case SIGABRT: return "SIGABRT";
#endif
#ifdef SIGBUS
case SIGBUS: return "SIGBUS";
#endif
#ifdef SIGFPE
case SIGFPE: return "SIGFPE";
#endif
#ifdef SIGKILL
case SIGKILL: return "SIGKILL";
#endif
#ifdef SIGSEGV
case SIGSEGV: return "SIGSEGV";
#endif
#ifdef SIGPIPE
case SIGPIPE: return "SIGPIPE";
#endif
#ifdef SIGTERM
case SIGTERM: return "SIGTERM";
#endif
#ifdef SIGCONT
case SIGCONT: return "SIGCONT";
#endif
#ifdef SIGSTOP
case SIGSTOP: return "SIGSTOP";
#endif
default: return "unknown";
}
}
static void StopHandler(int) {
LOG_TOPIC(INFO, Logger::STARTUP) << "received SIGINT for supervisor; commanding client [" << CLIENT_PID << "] to shut down.";
int rc = kill(CLIENT_PID, SIGTERM);
if (rc < 0) {
LOG_TOPIC(ERR, Logger::STARTUP) << "commanding client [" << CLIENT_PID << "] to shut down failed: [" << errno << "] " << strerror(errno);
}
DONE = true;
}
}
static void HUPHandler(int) {
LOG_TOPIC(INFO, Logger::STARTUP) << "received SIGHUP for supervisor; commanding client [" << CLIENT_PID << "] to logrotate.";
int rc = kill(CLIENT_PID, SIGHUP);
if (rc < 0) {
LOG_TOPIC(ERR, Logger::STARTUP) << "commanding client [" << CLIENT_PID << "] to logrotate failed: [" << errno << "] " << strerror(errno);
}
}
SupervisorFeature::SupervisorFeature(
application_features::ApplicationServer* server)
: ApplicationFeature(server, "Supervisor"), _supervisor(false), _clientPid(0) {
setOptional(true);
requiresElevatedPrivileges(false);
startsAfter("Daemon");
startsAfter("Logger");
startsAfter("WorkMonitor");
}
void SupervisorFeature::collectOptions(
std::shared_ptr<ProgramOptions> options) {
options->addHiddenOption("--supervisor",
"background the server, starts a supervisor",
new BooleanParameter(&_supervisor));
}
void SupervisorFeature::validateOptions(
std::shared_ptr<ProgramOptions> options) {
if (_supervisor) {
try {
DaemonFeature* daemon = ApplicationServer::getFeature<DaemonFeature>("Daemon");
// force daemon mode
daemon->setDaemon(true);
// revalidate options
daemon->validateOptions(options);
} catch (...) {
LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "daemon mode not available, cannot start supervisor";
FATAL_ERROR_EXIT();
}
}
}
void SupervisorFeature::daemonize() {
static time_t const MIN_TIME_ALIVE_IN_SEC = 30;
if (!_supervisor) {
return;
}
time_t startTime = time(0);
time_t t;
bool done = false;
int result = EXIT_SUCCESS;
// will be reseted in SchedulerFeature
ArangoGlobalContext::CONTEXT->unmaskStandardSignals();
LoggerFeature* logger = nullptr;
try {
logger = ApplicationServer::getFeature<LoggerFeature>("Logger");
} catch (...) {
LOG_TOPIC(FATAL, Logger::STARTUP)
<< "unknown feature 'Logger', giving up";
FATAL_ERROR_EXIT();
}
logger->setSupervisor(true);
logger->prepare();
LOG_TOPIC(DEBUG, Logger::STARTUP) << "starting supervisor loop";
while (!done) {
logger->setSupervisor(false);
signal(SIGINT, SIG_DFL);
signal(SIGTERM, SIG_DFL);
LOG_TOPIC(DEBUG, Logger::STARTUP) << "supervisor will now try to fork a new child process";
// fork of the server
_clientPid = fork();
if (_clientPid < 0) {
LOG_TOPIC(FATAL, Logger::STARTUP) << "fork failed, giving up";
FATAL_ERROR_EXIT();
}
// parent (supervisor)
if (0 < _clientPid) {
signal(SIGINT, StopHandler);
signal(SIGTERM, StopHandler);
signal(SIGHUP, HUPHandler);
LOG_TOPIC(INFO, Logger::STARTUP) << "supervisor has forked a child process with pid " << _clientPid;
TRI_SetProcessTitle("arangodb [supervisor]");
LOG_TOPIC(DEBUG, Logger::STARTUP) << "supervisor mode: within parent";
CLIENT_PID = _clientPid;
DONE = false;
int status;
int res = waitpid(_clientPid, &status, 0);
bool horrible = true;
LOG_TOPIC(INFO, Logger::STARTUP) << "waitpid woke up with return value "
<< res << " and status " << status
<< " and DONE = " << (DONE ? "true" : "false");
if (DONE) {
// signal handler for SIGINT or SIGTERM was invoked
done = true;
horrible = false;
}
else {
TRI_ASSERT(horrible);
if (WIFEXITED(status)) {
// give information about cause of death
if (WEXITSTATUS(status) == 0) {
LOG_TOPIC(INFO, Logger::STARTUP) << "child process " << _clientPid
<< " terminated normally. " << noRestartMessage;
done = true;
horrible = false;
} else {
t = time(0) - startTime;
if (t < MIN_TIME_ALIVE_IN_SEC) {
LOG_TOPIC(ERR, Logger::STARTUP)
<< "child process " << _clientPid << " terminated unexpectedly, exit status"
<< WEXITSTATUS(status) << ". the child process only survived for " << t
<< " seconds. this is lower than the minimum threshold value of " << MIN_TIME_ALIVE_IN_SEC
<< " s. " << noRestartMessage << ". " << fixErrorMessage;
done = true;
} else {
LOG_TOPIC(ERR, Logger::STARTUP)
<< "child process " << _clientPid
<< " terminated unexpectedly, exit status " << WEXITSTATUS(status)
<< ". " << restartMessage;
done = false;
}
}
} else if (WIFSIGNALED(status)) {
int const s = WTERMSIG(status);
switch (s) {
case 2: // SIGINT
case 9: // SIGKILL
case 15: // SIGTERM
LOG_TOPIC(INFO, Logger::STARTUP)
<< "child process " << _clientPid
<< " terminated normally, exit status " << s
<< " (" << translateSignal(s) << "). " << noRestartMessage;
done = true;
horrible = false;
break;
default:
TRI_ASSERT(horrible);
t = time(0) - startTime;
if (t < MIN_TIME_ALIVE_IN_SEC) {
LOG_TOPIC(ERR, Logger::STARTUP)
<< "child process " << _clientPid << " terminated unexpectedly, signal "
<< s << " (" << translateSignal(s) << "). the child process only survived for " << t
<< " seconds. this is lower than the minimum threshold value of " << MIN_TIME_ALIVE_IN_SEC
<< " s. " << noRestartMessage << ". " << fixErrorMessage;
done = true;
#ifdef WCOREDUMP
if (WCOREDUMP(status)) {
LOG_TOPIC(WARN, Logger::STARTUP) << "child process "
<< _clientPid
<< " also produced a core dump";
}
#endif
} else {
LOG_TOPIC(ERR, Logger::STARTUP) << "child process " << _clientPid
<< " terminated unexpectedly, signal "
<< s << " (" << translateSignal(s) << "). "
<< restartMessage;
done = false;
}
break;
}
} else {
LOG_TOPIC(ERR, Logger::STARTUP)
<< "child process " << _clientPid
<< " terminated unexpectedly, unknown cause. " << restartMessage;
done = false;
}
}
if (horrible) {
result = EXIT_FAILURE;
} else {
result = EXIT_SUCCESS;
}
}
// child - run the normal boot sequence
else {
Logger::shutdown();
LOG_TOPIC(DEBUG, Logger::STARTUP) << "supervisor mode: within child";
TRI_SetProcessTitle("arangodb [server]");
#ifdef TRI_HAVE_PRCTL
// force child to stop if supervisor dies
prctl(PR_SET_PDEATHSIG, SIGTERM, 0, 0, 0);
#endif
try {
DaemonFeature* daemon = ApplicationServer::getFeature<DaemonFeature>("Daemon");
// disable daemon mode
daemon->setDaemon(false);
} catch (...) {
}
return;
}
}
LOG_TOPIC(DEBUG, Logger::STARTUP) << "supervisor mode: finished";
Logger::flush();
Logger::shutdown();
exit(result);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "SkJpegUtility.h"
/////////////////////////////////////////////////////////////////////
static void sk_init_source(j_decompress_ptr cinfo) {
skjpeg_source_mgr* src = (skjpeg_source_mgr*)cinfo->src;
src->next_input_byte = (const JOCTET*)src->fBuffer;
src->bytes_in_buffer = 0;
src->current_offset = 0;
src->fStream->rewind();
}
static boolean sk_seek_input_data(j_decompress_ptr cinfo, long byte_offset) {
skjpeg_source_mgr* src = (skjpeg_source_mgr*)cinfo->src;
if (byte_offset > src->current_offset) {
(void)src->fStream->skip(byte_offset - src->current_offset);
} else {
src->fStream->rewind();
(void)src->fStream->skip(byte_offset);
}
src->current_offset = byte_offset;
src->next_input_byte = (const JOCTET*)src->fBuffer;
src->bytes_in_buffer = 0;
return TRUE;
}
static boolean sk_fill_input_buffer(j_decompress_ptr cinfo) {
skjpeg_source_mgr* src = (skjpeg_source_mgr*)cinfo->src;
if (src->fDecoder != NULL && src->fDecoder->shouldCancelDecode()) {
return FALSE;
}
size_t bytes = src->fStream->read(src->fBuffer, skjpeg_source_mgr::kBufferSize);
// note that JPEG is happy with less than the full read,
// as long as the result is non-zero
if (bytes == 0) {
return FALSE;
}
src->current_offset += bytes;
src->next_input_byte = (const JOCTET*)src->fBuffer;
src->bytes_in_buffer = bytes;
return TRUE;
}
static void sk_skip_input_data(j_decompress_ptr cinfo, long num_bytes) {
skjpeg_source_mgr* src = (skjpeg_source_mgr*)cinfo->src;
if (num_bytes > (long)src->bytes_in_buffer) {
long bytesToSkip = num_bytes - src->bytes_in_buffer;
while (bytesToSkip > 0) {
long bytes = (long)src->fStream->skip(bytesToSkip);
if (bytes <= 0 || bytes > bytesToSkip) {
// SkDebugf("xxxxxxxxxxxxxx failure to skip request %d returned %d\n", bytesToSkip, bytes);
cinfo->err->error_exit((j_common_ptr)cinfo);
return;
}
src->current_offset += bytes;
bytesToSkip -= bytes;
}
src->next_input_byte = (const JOCTET*)src->fBuffer;
src->bytes_in_buffer = 0;
} else {
src->next_input_byte += num_bytes;
src->bytes_in_buffer -= num_bytes;
}
}
static boolean sk_resync_to_restart(j_decompress_ptr cinfo, int desired) {
skjpeg_source_mgr* src = (skjpeg_source_mgr*)cinfo->src;
// what is the desired param for???
if (!src->fStream->rewind()) {
SkDebugf("xxxxxxxxxxxxxx failure to rewind\n");
cinfo->err->error_exit((j_common_ptr)cinfo);
return FALSE;
}
src->next_input_byte = (const JOCTET*)src->fBuffer;
src->bytes_in_buffer = 0;
return TRUE;
}
static void sk_term_source(j_decompress_ptr /*cinfo*/) {}
static void skmem_init_source(j_decompress_ptr cinfo) {
skjpeg_source_mgr* src = (skjpeg_source_mgr*)cinfo->src;
src->next_input_byte = (const JOCTET*)src->fMemoryBase;
src->start_input_byte = (const JOCTET*)src->fMemoryBase;
src->bytes_in_buffer = src->fMemoryBaseSize;
src->current_offset = src->fMemoryBaseSize;
}
static boolean skmem_fill_input_buffer(j_decompress_ptr cinfo) {
SkDebugf("xxxxxxxxxxxxxx skmem_fill_input_buffer called\n");
return FALSE;
}
static void skmem_skip_input_data(j_decompress_ptr cinfo, long num_bytes) {
skjpeg_source_mgr* src = (skjpeg_source_mgr*)cinfo->src;
// SkDebugf("xxxxxxxxxxxxxx skmem_skip_input_data called %d\n", num_bytes);
src->next_input_byte = (const JOCTET*)((const char*)src->next_input_byte + num_bytes);
src->bytes_in_buffer -= num_bytes;
}
static boolean skmem_resync_to_restart(j_decompress_ptr cinfo, int desired) {
SkDebugf("xxxxxxxxxxxxxx skmem_resync_to_restart called\n");
return TRUE;
}
static void skmem_term_source(j_decompress_ptr /*cinfo*/) {}
///////////////////////////////////////////////////////////////////////////////
skjpeg_source_mgr::skjpeg_source_mgr(SkStream* stream, SkImageDecoder* decoder,
bool copyStream, bool ownStream) : fStream(stream) {
fDecoder = decoder;
const void* baseAddr = stream->getMemoryBase();
fMemoryBase = NULL;
fUnrefStream = ownStream;
if (copyStream) {
fMemoryBaseSize = stream->getLength();
fMemoryBase = sk_malloc_throw(fMemoryBaseSize);
stream->read(fMemoryBase, fMemoryBaseSize);
init_source = skmem_init_source;
fill_input_buffer = skmem_fill_input_buffer;
skip_input_data = skmem_skip_input_data;
resync_to_restart = skmem_resync_to_restart;
term_source = skmem_term_source;
seek_input_data = NULL;
} else {
fMemoryBase = NULL;
fMemoryBaseSize = 0;
init_source = sk_init_source;
fill_input_buffer = sk_fill_input_buffer;
skip_input_data = sk_skip_input_data;
resync_to_restart = sk_resync_to_restart;
term_source = sk_term_source;
seek_input_data = sk_seek_input_data;
}
// SkDebugf("**************** use memorybase %p %d\n", fMemoryBase, fMemoryBaseSize);
}
skjpeg_source_mgr::~skjpeg_source_mgr() {
if (fMemoryBase) {
sk_free(fMemoryBase);
}
if (fUnrefStream) {
fStream->unref();
}
}
///////////////////////////////////////////////////////////////////////////////
static void sk_init_destination(j_compress_ptr cinfo) {
skjpeg_destination_mgr* dest = (skjpeg_destination_mgr*)cinfo->dest;
dest->next_output_byte = dest->fBuffer;
dest->free_in_buffer = skjpeg_destination_mgr::kBufferSize;
}
static boolean sk_empty_output_buffer(j_compress_ptr cinfo) {
skjpeg_destination_mgr* dest = (skjpeg_destination_mgr*)cinfo->dest;
// if (!dest->fStream->write(dest->fBuffer, skjpeg_destination_mgr::kBufferSize - dest->free_in_buffer))
if (!dest->fStream->write(dest->fBuffer,
skjpeg_destination_mgr::kBufferSize)) {
ERREXIT(cinfo, JERR_FILE_WRITE);
return false;
}
dest->next_output_byte = dest->fBuffer;
dest->free_in_buffer = skjpeg_destination_mgr::kBufferSize;
return TRUE;
}
static void sk_term_destination (j_compress_ptr cinfo) {
skjpeg_destination_mgr* dest = (skjpeg_destination_mgr*)cinfo->dest;
size_t size = skjpeg_destination_mgr::kBufferSize - dest->free_in_buffer;
if (size > 0) {
if (!dest->fStream->write(dest->fBuffer, size)) {
ERREXIT(cinfo, JERR_FILE_WRITE);
return;
}
}
dest->fStream->flush();
}
skjpeg_destination_mgr::skjpeg_destination_mgr(SkWStream* stream)
: fStream(stream) {
this->init_destination = sk_init_destination;
this->empty_output_buffer = sk_empty_output_buffer;
this->term_destination = sk_term_destination;
}
void skjpeg_error_exit(j_common_ptr cinfo) {
skjpeg_error_mgr* error = (skjpeg_error_mgr*)cinfo->err;
(*error->output_message) (cinfo);
/* Let the memory manager delete any temp files before we die */
jpeg_destroy(cinfo);
longjmp(error->fJmpBuf, -1);
}
<commit_msg>am ea22e420: Fix bug in SkImageDecoder.buildTileIndex()<commit_after>/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "SkJpegUtility.h"
/////////////////////////////////////////////////////////////////////
static void sk_init_source(j_decompress_ptr cinfo) {
skjpeg_source_mgr* src = (skjpeg_source_mgr*)cinfo->src;
src->next_input_byte = (const JOCTET*)src->fBuffer;
src->bytes_in_buffer = 0;
src->current_offset = 0;
src->fStream->rewind();
}
static boolean sk_seek_input_data(j_decompress_ptr cinfo, long byte_offset) {
skjpeg_source_mgr* src = (skjpeg_source_mgr*)cinfo->src;
if (byte_offset > src->current_offset) {
(void)src->fStream->skip(byte_offset - src->current_offset);
} else {
src->fStream->rewind();
(void)src->fStream->skip(byte_offset);
}
src->current_offset = byte_offset;
src->next_input_byte = (const JOCTET*)src->fBuffer;
src->bytes_in_buffer = 0;
return TRUE;
}
static boolean sk_fill_input_buffer(j_decompress_ptr cinfo) {
skjpeg_source_mgr* src = (skjpeg_source_mgr*)cinfo->src;
if (src->fDecoder != NULL && src->fDecoder->shouldCancelDecode()) {
return FALSE;
}
size_t bytes = src->fStream->read(src->fBuffer, skjpeg_source_mgr::kBufferSize);
// note that JPEG is happy with less than the full read,
// as long as the result is non-zero
if (bytes == 0) {
return FALSE;
}
src->current_offset += bytes;
src->next_input_byte = (const JOCTET*)src->fBuffer;
src->bytes_in_buffer = bytes;
return TRUE;
}
static void sk_skip_input_data(j_decompress_ptr cinfo, long num_bytes) {
skjpeg_source_mgr* src = (skjpeg_source_mgr*)cinfo->src;
if (num_bytes > (long)src->bytes_in_buffer) {
long bytesToSkip = num_bytes - src->bytes_in_buffer;
while (bytesToSkip > 0) {
long bytes = (long)src->fStream->skip(bytesToSkip);
if (bytes <= 0 || bytes > bytesToSkip) {
// SkDebugf("xxxxxxxxxxxxxx failure to skip request %d returned %d\n", bytesToSkip, bytes);
cinfo->err->error_exit((j_common_ptr)cinfo);
return;
}
src->current_offset += bytes;
bytesToSkip -= bytes;
}
src->next_input_byte = (const JOCTET*)src->fBuffer;
src->bytes_in_buffer = 0;
} else {
src->next_input_byte += num_bytes;
src->bytes_in_buffer -= num_bytes;
}
}
static boolean sk_resync_to_restart(j_decompress_ptr cinfo, int desired) {
skjpeg_source_mgr* src = (skjpeg_source_mgr*)cinfo->src;
// what is the desired param for???
if (!src->fStream->rewind()) {
SkDebugf("xxxxxxxxxxxxxx failure to rewind\n");
cinfo->err->error_exit((j_common_ptr)cinfo);
return FALSE;
}
src->next_input_byte = (const JOCTET*)src->fBuffer;
src->bytes_in_buffer = 0;
return TRUE;
}
static void sk_term_source(j_decompress_ptr /*cinfo*/) {}
static void skmem_init_source(j_decompress_ptr cinfo) {
skjpeg_source_mgr* src = (skjpeg_source_mgr*)cinfo->src;
src->next_input_byte = (const JOCTET*)src->fMemoryBase;
src->start_input_byte = (const JOCTET*)src->fMemoryBase;
src->bytes_in_buffer = src->fMemoryBaseSize;
src->current_offset = src->fMemoryBaseSize;
}
static boolean skmem_fill_input_buffer(j_decompress_ptr cinfo) {
SkDebugf("xxxxxxxxxxxxxx skmem_fill_input_buffer called\n");
return FALSE;
}
static void skmem_skip_input_data(j_decompress_ptr cinfo, long num_bytes) {
skjpeg_source_mgr* src = (skjpeg_source_mgr*)cinfo->src;
// SkDebugf("xxxxxxxxxxxxxx skmem_skip_input_data called %d\n", num_bytes);
src->next_input_byte = (const JOCTET*)((const char*)src->next_input_byte + num_bytes);
src->bytes_in_buffer -= num_bytes;
}
static boolean skmem_resync_to_restart(j_decompress_ptr cinfo, int desired) {
SkDebugf("xxxxxxxxxxxxxx skmem_resync_to_restart called\n");
return TRUE;
}
static void skmem_term_source(j_decompress_ptr /*cinfo*/) {}
///////////////////////////////////////////////////////////////////////////////
skjpeg_source_mgr::skjpeg_source_mgr(SkStream* stream, SkImageDecoder* decoder,
bool copyStream, bool ownStream) : fStream(stream) {
fDecoder = decoder;
const void* baseAddr = stream->getMemoryBase();
size_t bufferSize = 4096;
size_t len;
fMemoryBase = NULL;
fUnrefStream = ownStream;
if (copyStream) {
fMemoryBaseSize = 0;
fMemoryBase = sk_malloc_throw(bufferSize);
while ((len = stream->read(fMemoryBase + fMemoryBaseSize,
bufferSize - fMemoryBaseSize)) != 0) {
fMemoryBaseSize += len;
if (fMemoryBaseSize == bufferSize) {
bufferSize *= 2;
fMemoryBase = sk_realloc_throw(fMemoryBase, bufferSize);
}
}
fMemoryBase = sk_realloc_throw(fMemoryBase, fMemoryBaseSize);
init_source = skmem_init_source;
fill_input_buffer = skmem_fill_input_buffer;
skip_input_data = skmem_skip_input_data;
resync_to_restart = skmem_resync_to_restart;
term_source = skmem_term_source;
seek_input_data = NULL;
} else {
fMemoryBase = NULL;
fMemoryBaseSize = 0;
init_source = sk_init_source;
fill_input_buffer = sk_fill_input_buffer;
skip_input_data = sk_skip_input_data;
resync_to_restart = sk_resync_to_restart;
term_source = sk_term_source;
seek_input_data = sk_seek_input_data;
}
// SkDebugf("**************** use memorybase %p %d\n", fMemoryBase, fMemoryBaseSize);
}
skjpeg_source_mgr::~skjpeg_source_mgr() {
if (fMemoryBase) {
sk_free(fMemoryBase);
}
if (fUnrefStream) {
fStream->unref();
}
}
///////////////////////////////////////////////////////////////////////////////
static void sk_init_destination(j_compress_ptr cinfo) {
skjpeg_destination_mgr* dest = (skjpeg_destination_mgr*)cinfo->dest;
dest->next_output_byte = dest->fBuffer;
dest->free_in_buffer = skjpeg_destination_mgr::kBufferSize;
}
static boolean sk_empty_output_buffer(j_compress_ptr cinfo) {
skjpeg_destination_mgr* dest = (skjpeg_destination_mgr*)cinfo->dest;
// if (!dest->fStream->write(dest->fBuffer, skjpeg_destination_mgr::kBufferSize - dest->free_in_buffer))
if (!dest->fStream->write(dest->fBuffer,
skjpeg_destination_mgr::kBufferSize)) {
ERREXIT(cinfo, JERR_FILE_WRITE);
return false;
}
dest->next_output_byte = dest->fBuffer;
dest->free_in_buffer = skjpeg_destination_mgr::kBufferSize;
return TRUE;
}
static void sk_term_destination (j_compress_ptr cinfo) {
skjpeg_destination_mgr* dest = (skjpeg_destination_mgr*)cinfo->dest;
size_t size = skjpeg_destination_mgr::kBufferSize - dest->free_in_buffer;
if (size > 0) {
if (!dest->fStream->write(dest->fBuffer, size)) {
ERREXIT(cinfo, JERR_FILE_WRITE);
return;
}
}
dest->fStream->flush();
}
skjpeg_destination_mgr::skjpeg_destination_mgr(SkWStream* stream)
: fStream(stream) {
this->init_destination = sk_init_destination;
this->empty_output_buffer = sk_empty_output_buffer;
this->term_destination = sk_term_destination;
}
void skjpeg_error_exit(j_common_ptr cinfo) {
skjpeg_error_mgr* error = (skjpeg_error_mgr*)cinfo->err;
(*error->output_message) (cinfo);
/* Let the memory manager delete any temp files before we die */
jpeg_destroy(cinfo);
longjmp(error->fJmpBuf, -1);
}
<|endoftext|> |
<commit_before>/* This file is part of Ingen.
* Copyright (C) 2007 Dave Robillard <http://drobilla.net>
*
* Ingen is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* Ingen 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 details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "config.h"
#include <iostream>
#include <string>
#include <signal.h>
#include <dlfcn.h>
#include <boost/optional.hpp>
#include <glibmm/convert.h>
#include <glibmm/miscutils.h>
#include <glibmm/spawn.h>
#include <glibmm/thread.h>
#include "raul/Path.hpp"
#include "raul/SharedPtr.hpp"
#include "redlandmm/World.hpp"
#include "shared/runtime_paths.hpp"
#include "module/global.hpp"
#include "module/Module.hpp"
#include "module/World.hpp"
#include "engine/tuning.hpp"
#include "engine/Engine.hpp"
#include "engine/QueuedEngineInterface.hpp"
#include "engine/JackAudioDriver.hpp"
#include "serialisation/Parser.hpp"
#include "cmdline.h"
#ifdef HAVE_LIBLO
#include "engine/OSCEngineReceiver.hpp"
#endif
#ifdef HAVE_SOUP
#include "engine/HTTPEngineReceiver.hpp"
#endif
#ifdef WITH_BINDINGS
#include "bindings/ingen_bindings.hpp"
#endif
using namespace std;
using namespace Ingen;
SharedPtr<Engine> engine;
void
catch_int(int)
{
signal(SIGINT, catch_int);
signal(SIGTERM, catch_int);
cout << "[Main] Ingen interrupted." << endl;
engine->quit();
}
int
main(int argc, char** argv)
{
/* Parse command line options */
gengetopt_args_info args;
if (cmdline_parser (argc, argv, &args) != 0)
return 1;
if (argc <= 1) {
cmdline_parser_print_help();
cerr << endl << "*** Ingen requires at least one command line parameter" << endl;
cerr << "*** Just want a graphical application? Try 'ingen -eg'" << endl;
return 1;
} else if (args.connect_given && args.engine_flag) {
cerr << "\n*** Nonsense arguments, can't both run a local engine "
<< "and connect to a remote one." << endl
<< "*** Run separate instances if that is what you want" << endl;
return 1;
}
/* Set bundle path from executable location so resources/modules can be found */
Shared::set_bundle_path_from_code((void*)&main);
SharedPtr<Glib::Module> engine_module;
SharedPtr<Glib::Module> engine_http_module;
SharedPtr<Glib::Module> engine_osc_module;
SharedPtr<Glib::Module> engine_queued_module;
SharedPtr<Glib::Module> engine_jack_module;
SharedPtr<Glib::Module> client_module;
SharedPtr<Glib::Module> gui_module;
SharedPtr<Glib::Module> bindings_module;
SharedPtr<Shared::EngineInterface> engine_interface;
Glib::thread_init();
#if HAVE_SOUP
g_type_init();
#endif
Ingen::Shared::World* world = Ingen::Shared::get_world();
/* Set up RDF world */
world->rdf_world->add_prefix("xsd", "http://www.w3.org/2001/XMLSchema#");
world->rdf_world->add_prefix("ingen", "http://drobilla.net/ns/ingen#");
world->rdf_world->add_prefix("ingenuity", "http://drobilla.net/ns/ingenuity#");
world->rdf_world->add_prefix("lv2", "http://lv2plug.in/ns/lv2core#");
world->rdf_world->add_prefix("lv2ev", "http://lv2plug.in/ns/ext/event#");
world->rdf_world->add_prefix("lv2var", "http://lv2plug.in/ns/ext/instance-var#");
world->rdf_world->add_prefix("lv2midi", "http://lv2plug.in/ns/ext/midi");
world->rdf_world->add_prefix("rdfs", "http://www.w3.org/2000/01/rdf-schema#");
world->rdf_world->add_prefix("owl", "http://www.w3.org/2002/07/owl#");
world->rdf_world->add_prefix("doap", "http://usefulinc.com/ns/doap#");
world->rdf_world->add_prefix("dc", "http://purl.org/dc/elements/1.1/");
/* Run engine */
if (args.engine_flag) {
engine_module = Ingen::Shared::load_module("ingen_engine");
engine_http_module = Ingen::Shared::load_module("ingen_engine_http");
engine_osc_module = Ingen::Shared::load_module("ingen_engine_osc");
engine_jack_module = Ingen::Shared::load_module("ingen_engine_jack");
engine_queued_module = Ingen::Shared::load_module("ingen_engine_queued");
if (!engine_queued_module) {
cerr << "ERROR: Unable to load (queued) engine interface module" << endl;
Ingen::Shared::destroy_world();
return 1;
}
if (engine_module) {
Engine* (*new_engine)(Ingen::Shared::World* world) = NULL;
if (engine_module->get_symbol("new_engine", (void*&)new_engine)) {
engine = SharedPtr<Engine>(new_engine(world));
world->local_engine = engine;
/* Load queued (direct in-process) engine interface */
if (args.gui_given && engine_queued_module) {
Ingen::QueuedEngineInterface* (*new_interface)(Ingen::Engine& engine);
if (engine_osc_module->get_symbol("new_queued_interface", (void*&)new_interface)) {
SharedPtr<QueuedEngineInterface> interface(new_interface(*engine));
world->local_engine->add_event_source(interface);
engine_interface = interface;
world->engine = engine_interface;
}
} else {
#ifdef HAVE_LIBLO
if (engine_osc_module) {
Ingen::OSCEngineReceiver* (*new_receiver)(
Ingen::Engine& engine, size_t queue_size, uint16_t port);
if (engine_osc_module->get_symbol("new_osc_receiver", (void*&)new_receiver)) {
SharedPtr<EventSource> source(new_receiver(*engine,
pre_processor_queue_size, args.engine_port_arg));
world->local_engine->add_event_source(source);
}
}
#endif
#ifdef HAVE_SOUP
if (engine_http_module) {
// FIXE: leak
Ingen::HTTPEngineReceiver* (*new_receiver)(Ingen::Engine& engine, uint16_t port);
if (engine_http_module->get_symbol("new_http_receiver", (void*&)new_receiver)) {
boost::shared_ptr<HTTPEngineReceiver> receiver(new_receiver(
*world->local_engine, args.engine_port_arg));
world->local_engine->add_event_source(receiver);
receiver->activate();
}
}
#endif
}
} else {
engine_module.reset();
}
} else {
cerr << "Unable to load engine module." << endl;
}
}
/* Load client library */
if (args.load_given || args.gui_given) {
client_module = Ingen::Shared::load_module("ingen_client");
if (!client_module)
cerr << "Unable to load client module." << endl;
}
/* If we don't have a local engine interface (for GUI), use network */
if (client_module && ! engine_interface) {
SharedPtr<Shared::EngineInterface> (*new_remote_interface)(const std::string&) = NULL;
if (client_module->get_symbol("new_remote_interface", (void*&)new_remote_interface)) {
engine_interface = new_remote_interface(args.connect_arg);
} else {
cerr << "Unable to find symbol 'new_remote_interface' in "
"ingen_client module, aborting." << endl;
return -1;
}
}
/* Activate the engine, if we have one */
if (engine) {
Ingen::JackAudioDriver* (*new_driver)(
Ingen::Engine& engine,
const std::string server_name,
const std::string client_name,
void* jack_client) = NULL;
if (engine_jack_module->get_symbol("new_jack_audio_driver", (void*&)new_driver)) {
engine->set_driver(DataType::AUDIO, SharedPtr<Driver>(new_driver(
*engine, "default", args.jack_name_arg, NULL)));
} else {
cerr << Glib::Module::get_last_error() << endl;
}
engine->activate(args.parallelism_arg);
}
world->engine = engine_interface;
void (*gui_run)() = NULL;
/* Load GUI */
bool run_gui = false;
if (args.gui_given) {
gui_module = Ingen::Shared::load_module("ingen_gui");
void (*init)(int, char**, Ingen::Shared::World*);
bool found = gui_module->get_symbol("init", (void*&)init);
found = found && gui_module->get_symbol("run", (void*&)gui_run);
if (found) {
run_gui = true;
init(argc, argv, world);
} else {
cerr << "Unable to find hooks in GUI module, GUI not loaded." << endl;
}
}
/* Load a patch */
if (args.load_given && engine_interface) {
boost::optional<Path> data_path;
boost::optional<Path> parent;
boost::optional<Symbol> symbol;
const Glib::ustring path = (args.path_given ? args.path_arg : "/");
if (Path::is_valid(path)) {
const Path p(path);
parent = p.parent();
symbol = p.name();
} else {
cerr << "Invalid path: '" << path << endl;
}
bool found = false;
if (!world->serialisation_module)
world->serialisation_module = Ingen::Shared::load_module("ingen_serialisation");
Serialisation::Parser* (*new_parser)() = NULL;
if (world->serialisation_module)
found = world->serialisation_module->get_symbol("new_parser", (void*&)new_parser);
if (world->serialisation_module && found) {
SharedPtr<Serialisation::Parser> parser(new_parser());
// Assumption: Containing ':' means URI, otherwise filename
string uri = args.load_arg;
if (uri.find(':') == string::npos) {
if (Glib::path_is_absolute(args.load_arg))
uri = Glib::filename_to_uri(args.load_arg);
else
uri = Glib::filename_to_uri(Glib::build_filename(
Glib::get_current_dir(), args.load_arg));
}
engine_interface->load_plugins();
parser->parse_document(world, engine_interface.get(), uri, data_path, parent, symbol);
} else {
cerr << "Unable to load serialisation module, aborting." << endl;
return -1;
}
}
/* Run GUI (if applicable) */
if (run_gui)
gui_run();
/* Run a script */
if (args.run_given) {
#ifdef WITH_BINDINGS
bool (*run_script)(Ingen::Shared::World*, const char*) = NULL;
SharedPtr<Glib::Module> bindings_module = Ingen::Shared::load_module("ingen_bindings");
if (!bindings_module)
cerr << Glib::Module::get_last_error() << endl;
bindings_module->make_resident();
bool found = bindings_module->get_symbol("run", (void*&)(run_script));
if (found) {
setenv("PYTHONPATH", "../../bindings", 1);
run_script(world, args.run_arg);
} else {
cerr << "FAILED: " << Glib::Module::get_last_error() << endl;
}
#else
cerr << "This build of ingen does not support scripting." << endl;
#endif
/* Listen to OSC and do our own main thing. */
} else if (engine && !run_gui) {
signal(SIGINT, catch_int);
signal(SIGTERM, catch_int);
engine->main();
}
if (engine) {
engine->deactivate();
engine.reset();
}
engine_interface.reset();
client_module.reset();
world->serialisation_module.reset();
gui_module.reset();
engine_module.reset();
Ingen::Shared::destroy_world();
return 0;
}
<commit_msg>Fix assertion death on ingen -egl<commit_after>/* This file is part of Ingen.
* Copyright (C) 2007 Dave Robillard <http://drobilla.net>
*
* Ingen is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* Ingen 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 details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "config.h"
#include <iostream>
#include <string>
#include <signal.h>
#include <dlfcn.h>
#include <boost/optional.hpp>
#include <glibmm/convert.h>
#include <glibmm/miscutils.h>
#include <glibmm/spawn.h>
#include <glibmm/thread.h>
#include "raul/Path.hpp"
#include "raul/SharedPtr.hpp"
#include "redlandmm/World.hpp"
#include "shared/runtime_paths.hpp"
#include "module/global.hpp"
#include "module/Module.hpp"
#include "module/World.hpp"
#include "engine/tuning.hpp"
#include "engine/Engine.hpp"
#include "engine/QueuedEngineInterface.hpp"
#include "engine/JackAudioDriver.hpp"
#include "serialisation/Parser.hpp"
#include "cmdline.h"
#ifdef HAVE_LIBLO
#include "engine/OSCEngineReceiver.hpp"
#endif
#ifdef HAVE_SOUP
#include "engine/HTTPEngineReceiver.hpp"
#endif
#ifdef WITH_BINDINGS
#include "bindings/ingen_bindings.hpp"
#endif
using namespace std;
using namespace Ingen;
SharedPtr<Engine> engine;
void
catch_int(int)
{
signal(SIGINT, catch_int);
signal(SIGTERM, catch_int);
cout << "[Main] Ingen interrupted." << endl;
engine->quit();
}
int
main(int argc, char** argv)
{
/* Parse command line options */
gengetopt_args_info args;
if (cmdline_parser (argc, argv, &args) != 0)
return 1;
if (argc <= 1) {
cmdline_parser_print_help();
cerr << endl << "*** Ingen requires at least one command line parameter" << endl;
cerr << "*** Just want a graphical application? Try 'ingen -eg'" << endl;
return 1;
} else if (args.connect_given && args.engine_flag) {
cerr << "\n*** Nonsense arguments, can't both run a local engine "
<< "and connect to a remote one." << endl
<< "*** Run separate instances if that is what you want" << endl;
return 1;
}
/* Set bundle path from executable location so resources/modules can be found */
Shared::set_bundle_path_from_code((void*)&main);
SharedPtr<Glib::Module> engine_module;
SharedPtr<Glib::Module> engine_http_module;
SharedPtr<Glib::Module> engine_osc_module;
SharedPtr<Glib::Module> engine_queued_module;
SharedPtr<Glib::Module> engine_jack_module;
SharedPtr<Glib::Module> client_module;
SharedPtr<Glib::Module> gui_module;
SharedPtr<Glib::Module> bindings_module;
SharedPtr<Shared::EngineInterface> engine_interface;
Glib::thread_init();
#if HAVE_SOUP
g_type_init();
#endif
Ingen::Shared::World* world = Ingen::Shared::get_world();
/* Set up RDF world */
world->rdf_world->add_prefix("xsd", "http://www.w3.org/2001/XMLSchema#");
world->rdf_world->add_prefix("ingen", "http://drobilla.net/ns/ingen#");
world->rdf_world->add_prefix("ingenuity", "http://drobilla.net/ns/ingenuity#");
world->rdf_world->add_prefix("lv2", "http://lv2plug.in/ns/lv2core#");
world->rdf_world->add_prefix("lv2ev", "http://lv2plug.in/ns/ext/event#");
world->rdf_world->add_prefix("lv2var", "http://lv2plug.in/ns/ext/instance-var#");
world->rdf_world->add_prefix("lv2midi", "http://lv2plug.in/ns/ext/midi");
world->rdf_world->add_prefix("rdfs", "http://www.w3.org/2000/01/rdf-schema#");
world->rdf_world->add_prefix("owl", "http://www.w3.org/2002/07/owl#");
world->rdf_world->add_prefix("doap", "http://usefulinc.com/ns/doap#");
world->rdf_world->add_prefix("dc", "http://purl.org/dc/elements/1.1/");
/* Run engine */
if (args.engine_flag) {
engine_module = Ingen::Shared::load_module("ingen_engine");
engine_http_module = Ingen::Shared::load_module("ingen_engine_http");
engine_osc_module = Ingen::Shared::load_module("ingen_engine_osc");
engine_jack_module = Ingen::Shared::load_module("ingen_engine_jack");
engine_queued_module = Ingen::Shared::load_module("ingen_engine_queued");
if (!engine_queued_module) {
cerr << "ERROR: Unable to load (queued) engine interface module" << endl;
Ingen::Shared::destroy_world();
return 1;
}
if (engine_module) {
Engine* (*new_engine)(Ingen::Shared::World* world) = NULL;
if (engine_module->get_symbol("new_engine", (void*&)new_engine)) {
engine = SharedPtr<Engine>(new_engine(world));
world->local_engine = engine;
/* Load queued (direct in-process) engine interface */
if (args.gui_given && engine_queued_module) {
Ingen::QueuedEngineInterface* (*new_interface)(Ingen::Engine& engine);
if (engine_osc_module->get_symbol("new_queued_interface", (void*&)new_interface)) {
SharedPtr<QueuedEngineInterface> interface(new_interface(*engine));
world->local_engine->add_event_source(interface);
engine_interface = interface;
world->engine = engine_interface;
}
} else {
#ifdef HAVE_LIBLO
if (engine_osc_module) {
Ingen::OSCEngineReceiver* (*new_receiver)(
Ingen::Engine& engine, size_t queue_size, uint16_t port);
if (engine_osc_module->get_symbol("new_osc_receiver", (void*&)new_receiver)) {
SharedPtr<EventSource> source(new_receiver(*engine,
pre_processor_queue_size, args.engine_port_arg));
world->local_engine->add_event_source(source);
}
}
#endif
#ifdef HAVE_SOUP
if (engine_http_module) {
// FIXE: leak
Ingen::HTTPEngineReceiver* (*new_receiver)(Ingen::Engine& engine, uint16_t port);
if (engine_http_module->get_symbol("new_http_receiver", (void*&)new_receiver)) {
boost::shared_ptr<HTTPEngineReceiver> receiver(new_receiver(
*world->local_engine, args.engine_port_arg));
world->local_engine->add_event_source(receiver);
receiver->activate();
}
}
#endif
}
} else {
engine_module.reset();
}
} else {
cerr << "Unable to load engine module." << endl;
}
}
/* Load client library */
if (args.load_given || args.gui_given) {
client_module = Ingen::Shared::load_module("ingen_client");
if (!client_module)
cerr << "Unable to load client module." << endl;
}
/* If we don't have a local engine interface (for GUI), use network */
if (client_module && ! engine_interface) {
SharedPtr<Shared::EngineInterface> (*new_remote_interface)(const std::string&) = NULL;
if (client_module->get_symbol("new_remote_interface", (void*&)new_remote_interface)) {
engine_interface = new_remote_interface(args.connect_arg);
} else {
cerr << "Unable to find symbol 'new_remote_interface' in "
"ingen_client module, aborting." << endl;
return -1;
}
}
/* Activate the engine, if we have one */
if (engine) {
Ingen::JackAudioDriver* (*new_driver)(
Ingen::Engine& engine,
const std::string server_name,
const std::string client_name,
void* jack_client) = NULL;
if (engine_jack_module->get_symbol("new_jack_audio_driver", (void*&)new_driver)) {
engine->set_driver(DataType::AUDIO, SharedPtr<Driver>(new_driver(
*engine, "default", args.jack_name_arg, NULL)));
} else {
cerr << Glib::Module::get_last_error() << endl;
}
engine->activate(args.parallelism_arg);
}
world->engine = engine_interface;
void (*gui_run)() = NULL;
/* Load GUI */
bool run_gui = false;
if (args.gui_given) {
gui_module = Ingen::Shared::load_module("ingen_gui");
void (*init)(int, char**, Ingen::Shared::World*);
bool found = gui_module->get_symbol("init", (void*&)init);
found = found && gui_module->get_symbol("run", (void*&)gui_run);
if (found) {
run_gui = true;
init(argc, argv, world);
} else {
cerr << "Unable to find hooks in GUI module, GUI not loaded." << endl;
}
}
/* Load a patch */
if (args.load_given && engine_interface) {
boost::optional<Path> data_path;
boost::optional<Path> parent;
boost::optional<Symbol> symbol;
const Glib::ustring path = (args.path_given ? args.path_arg : "/");
if (Path::is_valid(path)) {
const Path p(path);
parent = p.parent();
const string s = p.name();
if (Symbol::is_valid(s))
symbol = s;
} else {
cerr << "Invalid path: '" << path << endl;
}
bool found = false;
if (!world->serialisation_module)
world->serialisation_module = Ingen::Shared::load_module("ingen_serialisation");
Serialisation::Parser* (*new_parser)() = NULL;
if (world->serialisation_module)
found = world->serialisation_module->get_symbol("new_parser", (void*&)new_parser);
if (world->serialisation_module && found) {
SharedPtr<Serialisation::Parser> parser(new_parser());
// Assumption: Containing ':' means URI, otherwise filename
string uri = args.load_arg;
if (uri.find(':') == string::npos) {
if (Glib::path_is_absolute(args.load_arg))
uri = Glib::filename_to_uri(args.load_arg);
else
uri = Glib::filename_to_uri(Glib::build_filename(
Glib::get_current_dir(), args.load_arg));
}
engine_interface->load_plugins();
parser->parse_document(world, engine_interface.get(), uri, data_path, parent, symbol);
} else {
cerr << "Unable to load serialisation module, aborting." << endl;
return -1;
}
}
/* Run GUI (if applicable) */
if (run_gui)
gui_run();
/* Run a script */
if (args.run_given) {
#ifdef WITH_BINDINGS
bool (*run_script)(Ingen::Shared::World*, const char*) = NULL;
SharedPtr<Glib::Module> bindings_module = Ingen::Shared::load_module("ingen_bindings");
if (!bindings_module)
cerr << Glib::Module::get_last_error() << endl;
bindings_module->make_resident();
bool found = bindings_module->get_symbol("run", (void*&)(run_script));
if (found) {
setenv("PYTHONPATH", "../../bindings", 1);
run_script(world, args.run_arg);
} else {
cerr << "FAILED: " << Glib::Module::get_last_error() << endl;
}
#else
cerr << "This build of ingen does not support scripting." << endl;
#endif
/* Listen to OSC and do our own main thing. */
} else if (engine && !run_gui) {
signal(SIGINT, catch_int);
signal(SIGTERM, catch_int);
engine->main();
}
if (engine) {
engine->deactivate();
engine.reset();
}
engine_interface.reset();
client_module.reset();
world->serialisation_module.reset();
gui_module.reset();
engine_module.reset();
Ingen::Shared::destroy_world();
return 0;
}
<|endoftext|> |
<commit_before>#include <QFileInfo>
#include <QRegularExpression>
#include "OutputParser.h"
#include "ParseState.h"
#include "TestModel.h"
using namespace QtcGtest::Internal;
namespace
{
const QRegularExpression gtestStartPattern (
QLatin1String ("^(.*)\\[==========\\] Running \\d+ tests? from \\d+ test cases?\\.\\s*$"));
enum GtestStart {GtestStartUnrelated = 1};
const QRegularExpression gtestEndPattern (
QLatin1String ("^(.*)\\[==========\\] (\\d+) tests? from (\\d+) test cases? ran. \\((\\d+) ms total\\)\\s*$"));
enum GtestEnd{GtestEndUnrelated = 1, GtestEndTestsRun, GtestEndCasesRun, GtestEndTimeSpent};
const QRegularExpression gtestDisabledPattern (
QLatin1String ("^\\s*YOU HAVE (\\d+) DISABLED TESTS\\s*$"));
enum GtestDisabled{GtestDisabledCount = 1};
const QRegularExpression gtestFilterPattern (
QLatin1String ("^\\s*Note: (Google Test filter = .*)\\s*$"));
enum GtestFilter{GtestFilterLine = 1};
const QRegularExpression newCasePattern (
QLatin1String ("^(.*)\\[\\-{10}\\] \\d+ tests? from ([\\w/]+)(, where TypeParam = (\\w+))?\\s*$"));
enum NewCase{NewCaseUnrelated = 1, NewCaseName, NewCaseFullParameter, NewCaseParameterType};
const QRegularExpression endCasePattern (
QLatin1String ("^(.*)\\[\\-{10}\\] \\d+ tests? from ([\\w/]+) \\((\\d+) ms total\\)\\s*$"));
enum EndCase{EndCaseUnrelated = 1, EndCaseName, EndCaseTimeSpent};
const QRegularExpression beginTestPattern (
QLatin1String ("^(.*)\\[ RUN \\] ([\\w/]+)\\.([\\w/]+)\\s*$"));
enum NewTest{NewTestUnrelated = 1, NewTestCaseName, NewTestName};
const QRegularExpression failTestPattern (
QLatin1String ("^(.*)\\[ FAILED \\] ([\\w/]+)\\.([\\w/]+) \\((\\d+) ms\\)\\s*$"));
enum FailTest{FailTestUnrelated = 1, FailTestCaseName, FailTestName, FailTestTimeSpent};
const QRegularExpression passTestPattern (
QLatin1String ("^(.*)\\[ OK \\] ([\\w/]+)\\.([\\w/]+) \\((\\d+) ms\\)\\s*$"));
enum PassTest{PassTestUnrelated = 1, PassTestCaseName, PassTestName, PassTestTimeSpent};
const QRegularExpression failDetailPattern (
QLatin1String ("^(.+):(\\d+): Failure\\s*$"));
enum FailDetail{FailDetailFileName = 1, FailDetailLine};
}
OutputParser::OutputParser(QObject *parent) :
QObject(parent)
{
}
bool OutputParser::isGoogleTestRun(const QString &line) const
{
QRegularExpressionMatch match = gtestStartPattern.match (line);
QRegularExpressionMatch matchFilter = gtestFilterPattern.match (line);
return (match.hasMatch () || matchFilter.hasMatch ());
}
void OutputParser::parseMessage(const QString &line, TestModel &model, ParseState &state)
{
QRegularExpressionMatch match;
match = newCasePattern.match (line);
if (match.hasMatch ())
{
state.currentCase = match.captured (NewCaseName);
if (match.lastCapturedIndex() == NewCaseParameterType)
{
state.currentCase += QString (QLatin1String(" <%1>")).arg (match.captured (NewCaseParameterType));
}
state.passedCount = state.failedCount = 0;
model.addCase (state.currentCase);
return;
}
match = endCasePattern.match (line);
if (match.hasMatch ())
{
int totalTime = match.captured (EndCaseTimeSpent).toInt ();
model.updateCase (state.currentCase, state.passedCount, state.failedCount, totalTime);
state.currentCase.clear ();
state.currentTest.clear ();
return;
}
match = beginTestPattern.match (line);
if (match.hasMatch ())
{
state.currentTest = match.captured (NewTestName);
model.addTest (state.currentTest, state.currentCase);
return;
}
match = passTestPattern.match (line);
if (match.hasMatch ())
{
QString unrelated = match.captured(PassTestUnrelated);
if (!unrelated.isEmpty()) {
model.addTestDetail (state.currentTest, state.currentCase, unrelated);
}
++state.passedCount;
++state.passedTotalCount;
int totalTime = match.captured (PassTestTimeSpent).toInt ();
model.updateTest (state.currentTest, state.currentCase, true, totalTime);
state.currentTest.clear ();
return;
}
match = failTestPattern.match (line);
if (match.hasMatch ())
{
QString unrelated = match.captured(PassTestUnrelated);
if (!unrelated.isEmpty()) {
model.addTestDetail (state.currentTest, state.currentCase, unrelated);
}
++state.failedCount;
++state.failedTotalCount;
int totalTime = match.captured (FailTestTimeSpent).toInt ();
model.updateTest (state.currentTest, state.currentCase, false, totalTime);
state.currentTest.clear ();
return;
}
match = failDetailPattern.match (line);
if (match.hasMatch ())
{
Q_ASSERT (!state.projectPath.isEmpty ());
QString file = match.captured (FailDetailFileName);
QFileInfo info (file);
if (info.isRelative ())
{
file = state.projectPath + QLatin1Char ('/') + match.captured (FailDetailFileName);
}
int lineNumber = match.captured (FailDetailLine).toInt ();
model.addTestError (state.currentTest, state.currentCase, line, file, lineNumber);
return;
}
match = gtestEndPattern.match (line);
if (match.hasMatch ())
{
state.totalTime = match.captured (GtestEndTimeSpent).toInt ();
return;
}
match = gtestDisabledPattern.match (line);
if (match.hasMatch ())
{
state.disabledCount = match.captured (GtestDisabledCount).toInt ();
return;
}
match = gtestFilterPattern.match (line);
if (match.hasMatch ())
{
model.addNote(match.captured (GtestFilterLine));
return;
}
if (!state.currentTest.isEmpty ())
{
Q_ASSERT (!state.currentCase.isEmpty ());
model.addTestDetail (state.currentTest, state.currentCase, line);
}
}
<commit_msg>Use of raw strings.<commit_after>#include <QFileInfo>
#include <QRegularExpression>
#include "OutputParser.h"
#include "ParseState.h"
#include "TestModel.h"
using namespace QtcGtest::Internal;
namespace
{
const QRegularExpression gtestStartPattern (
QLatin1String (R"(^(.*)\[==========\] Running \d+ tests? from \d+ test cases?\.\s*$)"));
enum GtestStart {GtestStartUnrelated = 1};
const QRegularExpression gtestEndPattern (
QLatin1String (R"(^(.*)\[==========\] (\d+) tests? from (\d+) test cases? ran. \((\d+) ms total\)\s*$)"));
enum GtestEnd{GtestEndUnrelated = 1, GtestEndTestsRun, GtestEndCasesRun, GtestEndTimeSpent};
const QRegularExpression gtestDisabledPattern (
QLatin1String (R"(^\s*YOU HAVE (\d+) DISABLED TESTS\s*$)"));
enum GtestDisabled{GtestDisabledCount = 1};
const QRegularExpression gtestFilterPattern (
QLatin1String (R"(^\s*Note: (Google Test filter = .*)\s*$)"));
enum GtestFilter{GtestFilterLine = 1};
const QRegularExpression newCasePattern (
QLatin1String (R"(^(.*)\[\-{10}\] \d+ tests? from ([\w/]+)(, where TypeParam = (\w+))?\s*$)"));
enum NewCase{NewCaseUnrelated = 1, NewCaseName, NewCaseFullParameter, NewCaseParameterType};
const QRegularExpression endCasePattern (
QLatin1String (R"(^(.*)\[\-{10}\] \d+ tests? from ([\w/]+) \((\d+) ms total\)\s*$)"));
enum EndCase{EndCaseUnrelated = 1, EndCaseName, EndCaseTimeSpent};
const QRegularExpression beginTestPattern (
QLatin1String (R"(^(.*)\[ RUN \] ([\w/]+)\.([\w/]+)\s*$)"));
enum NewTest{NewTestUnrelated = 1, NewTestCaseName, NewTestName};
const QRegularExpression failTestPattern (
QLatin1String (R"(^(.*)\[ FAILED \] ([\w/]+)\.([\w/]+) \((\d+) ms\)\s*$)"));
enum FailTest{FailTestUnrelated = 1, FailTestCaseName, FailTestName, FailTestTimeSpent};
const QRegularExpression passTestPattern (
QLatin1String (R"(^(.*)\[ OK \] ([\w/]+)\.([\w/]+) \((\d+) ms\)\s*$)"));
enum PassTest{PassTestUnrelated = 1, PassTestCaseName, PassTestName, PassTestTimeSpent};
const QRegularExpression failDetailPattern (
QLatin1String (R"(^(.+):(\d+): Failure\s*$)"));
enum FailDetail{FailDetailFileName = 1, FailDetailLine};
}
OutputParser::OutputParser(QObject *parent) :
QObject(parent)
{
}
bool OutputParser::isGoogleTestRun(const QString &line) const
{
QRegularExpressionMatch match = gtestStartPattern.match (line);
QRegularExpressionMatch matchFilter = gtestFilterPattern.match (line);
return (match.hasMatch () || matchFilter.hasMatch ());
}
void OutputParser::parseMessage(const QString &line, TestModel &model, ParseState &state)
{
QRegularExpressionMatch match;
match = newCasePattern.match (line);
if (match.hasMatch ())
{
state.currentCase = match.captured (NewCaseName);
if (match.lastCapturedIndex() == NewCaseParameterType)
{
state.currentCase += QString (QLatin1String(" <%1>")).arg (match.captured (NewCaseParameterType));
}
state.passedCount = state.failedCount = 0;
model.addCase (state.currentCase);
return;
}
match = endCasePattern.match (line);
if (match.hasMatch ())
{
int totalTime = match.captured (EndCaseTimeSpent).toInt ();
model.updateCase (state.currentCase, state.passedCount, state.failedCount, totalTime);
state.currentCase.clear ();
state.currentTest.clear ();
return;
}
match = beginTestPattern.match (line);
if (match.hasMatch ())
{
state.currentTest = match.captured (NewTestName);
model.addTest (state.currentTest, state.currentCase);
return;
}
match = passTestPattern.match (line);
if (match.hasMatch ())
{
QString unrelated = match.captured(PassTestUnrelated);
if (!unrelated.isEmpty()) {
model.addTestDetail (state.currentTest, state.currentCase, unrelated);
}
++state.passedCount;
++state.passedTotalCount;
int totalTime = match.captured (PassTestTimeSpent).toInt ();
model.updateTest (state.currentTest, state.currentCase, true, totalTime);
state.currentTest.clear ();
return;
}
match = failTestPattern.match (line);
if (match.hasMatch ())
{
QString unrelated = match.captured(PassTestUnrelated);
if (!unrelated.isEmpty()) {
model.addTestDetail (state.currentTest, state.currentCase, unrelated);
}
++state.failedCount;
++state.failedTotalCount;
int totalTime = match.captured (FailTestTimeSpent).toInt ();
model.updateTest (state.currentTest, state.currentCase, false, totalTime);
state.currentTest.clear ();
return;
}
match = failDetailPattern.match (line);
if (match.hasMatch ())
{
Q_ASSERT (!state.projectPath.isEmpty ());
QString file = match.captured (FailDetailFileName);
QFileInfo info (file);
if (info.isRelative ())
{
file = state.projectPath + QLatin1Char ('/') + match.captured (FailDetailFileName);
}
int lineNumber = match.captured (FailDetailLine).toInt ();
model.addTestError (state.currentTest, state.currentCase, line, file, lineNumber);
return;
}
match = gtestEndPattern.match (line);
if (match.hasMatch ())
{
state.totalTime = match.captured (GtestEndTimeSpent).toInt ();
return;
}
match = gtestDisabledPattern.match (line);
if (match.hasMatch ())
{
state.disabledCount = match.captured (GtestDisabledCount).toInt ();
return;
}
match = gtestFilterPattern.match (line);
if (match.hasMatch ())
{
model.addNote(match.captured (GtestFilterLine));
return;
}
if (!state.currentTest.isEmpty ())
{
Q_ASSERT (!state.currentCase.isEmpty ());
model.addTestDetail (state.currentTest, state.currentCase, line);
}
}
<|endoftext|> |
<commit_before>// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Engine - Network module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_ENETPACKET_HPP
#define NAZARA_ENETPACKET_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Network/NetPacket.hpp>
namespace Nz
{
enum ENetPacketFlag
{
ENetPacketFlag_Reliable,
ENetPacketFlag_Unsequenced,
ENetPacketFlag_UnreliableFragment
};
template<>
struct EnumAsFlags<ENetPacketFlag>
{
static constexpr bool value = true;
static constexpr int max = ENetPacketFlag_UnreliableFragment;
};
using ENetPacketFlags = Flags<ENetPacketFlag>;
class MemoryPool;
struct ENetPacket
{
MemoryPool* owner;
ENetPacketFlags flags;
NetPacket data;
std::size_t referenceCount = 0;
};
struct NAZARA_NETWORK_API ENetPacketRef
{
ENetPacketRef() = default;
ENetPacketRef(ENetPacket* packet)
{
Reset(packet);
}
ENetPacketRef(const ENetPacketRef& packet) :
ENetPacketRef()
{
Reset(packet);
}
ENetPacketRef(ENetPacketRef&& packet) :
m_packet(packet.m_packet)
{
packet.m_packet = nullptr;
}
~ENetPacketRef()
{
Reset();
}
void Reset(ENetPacket* packet = nullptr);
operator ENetPacket*() const
{
return m_packet;
}
ENetPacket* operator->() const
{
return m_packet;
}
ENetPacketRef& operator=(ENetPacket* packet)
{
Reset(packet);
return *this;
}
ENetPacketRef& operator=(const ENetPacketRef& packet)
{
Reset(packet);
return *this;
}
ENetPacketRef& operator=(ENetPacketRef&& packet)
{
m_packet = packet.m_packet;
packet.m_packet = nullptr;
return *this;
}
ENetPacket* m_packet = nullptr;
};
}
#endif // NAZARA_ENETPACKET_HPP
<commit_msg>Network/ENetPacketFlags: Add Unreliable flag typedef for zero<commit_after>// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Engine - Network module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_ENETPACKET_HPP
#define NAZARA_ENETPACKET_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Network/NetPacket.hpp>
namespace Nz
{
enum ENetPacketFlag
{
ENetPacketFlag_Reliable,
ENetPacketFlag_Unsequenced,
ENetPacketFlag_UnreliableFragment
};
template<>
struct EnumAsFlags<ENetPacketFlag>
{
static constexpr bool value = true;
static constexpr int max = ENetPacketFlag_UnreliableFragment;
};
using ENetPacketFlags = Flags<ENetPacketFlag>;
constexpr ENetPacketFlags ENetPacketFlag_Unreliable = 0;
class MemoryPool;
struct ENetPacket
{
MemoryPool* owner;
ENetPacketFlags flags;
NetPacket data;
std::size_t referenceCount = 0;
};
struct NAZARA_NETWORK_API ENetPacketRef
{
ENetPacketRef() = default;
ENetPacketRef(ENetPacket* packet)
{
Reset(packet);
}
ENetPacketRef(const ENetPacketRef& packet) :
ENetPacketRef()
{
Reset(packet);
}
ENetPacketRef(ENetPacketRef&& packet) :
m_packet(packet.m_packet)
{
packet.m_packet = nullptr;
}
~ENetPacketRef()
{
Reset();
}
void Reset(ENetPacket* packet = nullptr);
operator ENetPacket*() const
{
return m_packet;
}
ENetPacket* operator->() const
{
return m_packet;
}
ENetPacketRef& operator=(ENetPacket* packet)
{
Reset(packet);
return *this;
}
ENetPacketRef& operator=(const ENetPacketRef& packet)
{
Reset(packet);
return *this;
}
ENetPacketRef& operator=(ENetPacketRef&& packet)
{
m_packet = packet.m_packet;
packet.m_packet = nullptr;
return *this;
}
ENetPacket* m_packet = nullptr;
};
}
#endif // NAZARA_ENETPACKET_HPP
<|endoftext|> |
<commit_before>#include <string>
#include <cstdlib>
#include <cstring>
#include "Stat0.hpp"
#include "IStat.hpp"
std::string const Stat0::getstat(){
FILE* file = fopen("/proc/self/status", "r");
int result = -1;
char line[128];
std::string statinfo;
while (fgets(line, 128, file) != NULL){
if (strncmp(line, "VmRSS:", 6) == 0){
statinfo = line;
break;
}
}
fclose(file);
return statinfo;
}
<commit_msg>Modified Stat0 implmentation.<commit_after>#include <string>
#include <cstring>
#include <iostream>
#include <fstream>
#include "Stat0.hpp"
#include "IStat.hpp"
std::string const Stat0::getstat(){
std::ifstream file( "/proc/self/status", std::ios::in );
std::string statinfo;
if( file.is_open() ){
while( getline( file, statinfo ) ){
if ( std::string::npos != statinfo.find("VmRSS:") ){
return statinfo;
}
}
}
return "";
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008-2012, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software 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 "IECoreGL/ToGLMeshConverter.h"
#include "IECoreGL/MeshPrimitive.h"
#include "IECoreScene/FaceVaryingPromotionOp.h"
#include "IECoreScene/MeshNormalsOp.h"
#include "IECoreScene/MeshPrimitive.h"
#include "IECoreScene/TriangulateOp.h"
#include "IECore/DespatchTypedData.h"
#include "IECore/MessageHandler.h"
#include "boost/format.hpp"
#include <cassert>
using namespace IECoreGL;
IE_CORE_DEFINERUNTIMETYPED( ToGLMeshConverter );
ToGLConverter::ConverterDescription<ToGLMeshConverter> ToGLMeshConverter::g_description;
ToGLMeshConverter::ToGLMeshConverter( IECoreScene::ConstMeshPrimitivePtr toConvert )
: ToGLConverter( "Converts IECoreScene::MeshPrimitive objects to IECoreGL::MeshPrimitive objects.", IECoreScene::MeshPrimitive::staticTypeId() )
{
srcParameter()->setValue( boost::const_pointer_cast<IECoreScene::MeshPrimitive>( toConvert ) );
}
ToGLMeshConverter::~ToGLMeshConverter()
{
}
IECore::RunTimeTypedPtr ToGLMeshConverter::doConversion( IECore::ConstObjectPtr src, IECore::ConstCompoundObjectPtr operands ) const
{
IECoreScene::MeshPrimitivePtr mesh = boost::static_pointer_cast<IECoreScene::MeshPrimitive>( src->copy() ); // safe because the parameter validated it for us
if( !mesh->variableData<IECore::V3fVectorData>( "P", IECoreScene::PrimitiveVariable::Vertex ) )
{
throw IECore::Exception( "Must specify primitive variable \"P\", of type V3fVectorData and interpolation type Vertex." );
}
if( mesh->variables.find( "N" )==mesh->variables.end() )
{
// the mesh has no normals - we need to explicitly add some. if it's a polygon
// mesh (interpolation==linear) then we add per-face normals for a faceted look
// and if it's a subdivision mesh we add smooth per-vertex normals.
IECoreScene::MeshNormalsOpPtr normalOp = new IECoreScene::MeshNormalsOp();
normalOp->inputParameter()->setValue( mesh );
normalOp->copyParameter()->setTypedValue( false );
normalOp->interpolationParameter()->setNumericValue(
mesh->interpolation() == "linear" ? IECoreScene::PrimitiveVariable::Uniform : IECoreScene::PrimitiveVariable::Vertex
);
normalOp->operate();
}
IECoreScene::TriangulateOpPtr op = new IECoreScene::TriangulateOp();
op->inputParameter()->setValue( mesh );
op->throwExceptionsParameter()->setTypedValue( false ); // it's better to see something than nothing
op->copyParameter()->setTypedValue( false );
op->operate();
IECoreScene::FaceVaryingPromotionOpPtr faceVaryingOp = new IECoreScene::FaceVaryingPromotionOp;
faceVaryingOp->inputParameter()->setValue( mesh );
faceVaryingOp->copyParameter()->setTypedValue( false );
faceVaryingOp->operate();
MeshPrimitivePtr glMesh = new MeshPrimitive( mesh->numFaces() );
for ( IECoreScene::PrimitiveVariableMap::iterator pIt = mesh->variables.begin(); pIt != mesh->variables.end(); ++pIt )
{
if( pIt->second.data )
{
glMesh->addPrimitiveVariable( pIt->first, pIt->second );
}
else
{
IECore::msg( IECore::Msg::Warning, "ToGLMeshConverter", boost::format( "No data given for primvar \"%s\"" ) % pIt->first );
}
}
return glMesh;
}
<commit_msg>IECoreGL : favor MeshAlgo triangulate over Op<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008-2012, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software 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 "IECoreGL/ToGLMeshConverter.h"
#include "IECoreGL/MeshPrimitive.h"
#include "IECoreScene/FaceVaryingPromotionOp.h"
#include "IECoreScene/MeshAlgo.h"
#include "IECoreScene/MeshNormalsOp.h"
#include "IECoreScene/MeshPrimitive.h"
#include "IECore/DespatchTypedData.h"
#include "IECore/MessageHandler.h"
#include "IECore/SimpleTypedData.h"
#include "boost/format.hpp"
#include <cassert>
using namespace IECoreGL;
IE_CORE_DEFINERUNTIMETYPED( ToGLMeshConverter );
ToGLConverter::ConverterDescription<ToGLMeshConverter> ToGLMeshConverter::g_description;
ToGLMeshConverter::ToGLMeshConverter( IECoreScene::ConstMeshPrimitivePtr toConvert )
: ToGLConverter( "Converts IECoreScene::MeshPrimitive objects to IECoreGL::MeshPrimitive objects.", IECoreScene::MeshPrimitive::staticTypeId() )
{
srcParameter()->setValue( boost::const_pointer_cast<IECoreScene::MeshPrimitive>( toConvert ) );
}
ToGLMeshConverter::~ToGLMeshConverter()
{
}
IECore::RunTimeTypedPtr ToGLMeshConverter::doConversion( IECore::ConstObjectPtr src, IECore::ConstCompoundObjectPtr operands ) const
{
IECoreScene::MeshPrimitivePtr mesh = boost::static_pointer_cast<IECoreScene::MeshPrimitive>( src->copy() ); // safe because the parameter validated it for us
if( !mesh->variableData<IECore::V3fVectorData>( "P", IECoreScene::PrimitiveVariable::Vertex ) )
{
throw IECore::Exception( "Must specify primitive variable \"P\", of type V3fVectorData and interpolation type Vertex." );
}
if( mesh->variables.find( "N" )==mesh->variables.end() )
{
// the mesh has no normals - we need to explicitly add some. if it's a polygon
// mesh (interpolation==linear) then we add per-face normals for a faceted look
// and if it's a subdivision mesh we add smooth per-vertex normals.
IECoreScene::MeshNormalsOpPtr normalOp = new IECoreScene::MeshNormalsOp();
normalOp->inputParameter()->setValue( mesh );
normalOp->copyParameter()->setTypedValue( false );
normalOp->interpolationParameter()->setNumericValue(
mesh->interpolation() == "linear" ? IECoreScene::PrimitiveVariable::Uniform : IECoreScene::PrimitiveVariable::Vertex
);
normalOp->operate();
}
mesh = IECoreScene::MeshAlgo::triangulate( mesh.get() );
IECoreScene::FaceVaryingPromotionOpPtr faceVaryingOp = new IECoreScene::FaceVaryingPromotionOp;
faceVaryingOp->inputParameter()->setValue( mesh );
faceVaryingOp->copyParameter()->setTypedValue( false );
faceVaryingOp->operate();
MeshPrimitivePtr glMesh = new MeshPrimitive( mesh->numFaces() );
for ( IECoreScene::PrimitiveVariableMap::iterator pIt = mesh->variables.begin(); pIt != mesh->variables.end(); ++pIt )
{
if( pIt->second.data )
{
glMesh->addPrimitiveVariable( pIt->first, pIt->second );
}
else
{
IECore::msg( IECore::Msg::Warning, "ToGLMeshConverter", boost::format( "No data given for primvar \"%s\"" ) % pIt->first );
}
}
return glMesh;
}
<|endoftext|> |
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************/
#include "condor_common.h"
#include "../condor_daemon_core.V6/condor_daemon_core.h"
#include "condor_debug.h"
#include "subsystem_info.h"
#include "match_maker.h"
/* Using daemoncore, you get the benefits of a logging system with dprintf
and you can read config files automatically. To start testing
your daemon, run it with "-f -t" until you start specifying
a config file to use(the daemon will automatically look in
/etc/condor_config, ~condor/condor_config, or the env var
CONDOR_CONFIG if -t is not specifed). -f means run in the
foreground, -t means print the debugging output to the terminal.
*/
//-------------------------------------------------------------
// about self
DECL_SUBSYSTEM("MatchMaker", SUBSYSTEM_TYPE_DAEMON); // used by Daemon Core
MatchMaker *match_maker;
//-------------------------------------------------------------
int
main_init(int argc, char *argv[])
{
dprintf(D_ALWAYS, "main_init() called\n");
match_maker = new MatchMaker;
match_maker->init( );
return TRUE;
}
//-------------------------------------------------------------
int
main_config( bool is_full )
{
(void) is_full;
dprintf(D_ALWAYS, "main_config() called\n");
match_maker->config( );
return TRUE;
}
//-------------------------------------------------------------
int
main_shutdown_fast()
{
dprintf(D_ALWAYS, "main_shutdown_fast() called\n");
match_maker->shutdownFast();
delete match_maker;
DC_Exit(0);
return TRUE; // to satisfy c++
}
//-------------------------------------------------------------
int
main_shutdown_graceful()
{
dprintf(D_ALWAYS, "main_shutdown_graceful() called\n");
match_maker->shutdownGraceful();
delete match_maker;
DC_Exit(0);
return TRUE; // to satisfy c++
}
//-------------------------------------------------------------
void
main_pre_dc_init( int argc, char* argv[] )
{
(void) argc;
(void) argv;
// dprintf isn't safe yet...
}
//-------------------------------------------------------------
void
main_pre_command_sock_init( )
{
}
<commit_msg>Fixed a number of warnings<commit_after>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************/
#include "condor_common.h"
#include "../condor_daemon_core.V6/condor_daemon_core.h"
#include "condor_debug.h"
#include "subsystem_info.h"
#include "match_maker.h"
/* Using daemoncore, you get the benefits of a logging system with dprintf
and you can read config files automatically. To start testing
your daemon, run it with "-f -t" until you start specifying
a config file to use(the daemon will automatically look in
/etc/condor_config, ~condor/condor_config, or the env var
CONDOR_CONFIG if -t is not specifed). -f means run in the
foreground, -t means print the debugging output to the terminal.
*/
//-------------------------------------------------------------
// about self
DECL_SUBSYSTEM("MatchMaker", SUBSYSTEM_TYPE_DAEMON); // used by Daemon Core
MatchMaker *match_maker;
//-------------------------------------------------------------
int
main_init(int /*argc*/, char */*argv*/[])
{
dprintf(D_ALWAYS, "main_init() called\n");
match_maker = new MatchMaker;
match_maker->init( );
return TRUE;
}
//-------------------------------------------------------------
int
main_config( bool /*is_full*/ )
{
dprintf(D_ALWAYS, "main_config() called\n");
match_maker->config( );
return TRUE;
}
//-------------------------------------------------------------
int
main_shutdown_fast(void)
{
dprintf(D_ALWAYS, "main_shutdown_fast() called\n");
match_maker->shutdownFast();
delete match_maker;
DC_Exit(0);
return TRUE; // to satisfy c++
}
//-------------------------------------------------------------
int
main_shutdown_graceful(void)
{
dprintf(D_ALWAYS, "main_shutdown_graceful() called\n");
match_maker->shutdownGraceful();
delete match_maker;
DC_Exit(0);
return TRUE; // to satisfy c++
}
//-------------------------------------------------------------
void
main_pre_dc_init( int /*argc*/, char* /*argv*/[] )
{
// dprintf isn't safe yet...
}
//-------------------------------------------------------------
void
main_pre_command_sock_init( void )
{
}
<|endoftext|> |
<commit_before>//=============================================================================
//
// Adventure Game Studio (AGS)
//
// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
// The full list of copyright holders can be found in the Copyright.txt
// file, which is part of this source code distribution.
//
// The AGS source code is provided under the Artistic License 2.0.
// A copy of this license can be found in the file License.txt and at
// http://www.opensource.org/licenses/artistic-license-2.0.php
//
//=============================================================================
//
// Game configuration
//
#include "util/wgt2allg.h"
#include "ac/gamesetup.h"
#include "ac/gamestate.h"
#include "main/mainheader.h"
#include "main/config.h"
#include "ac/spritecache.h"
#include "platform/base/override_defines.h" //_getcwd()
#include "util/filestream.h"
#include "util/textstreamreader.h"
#include "util/path.h"
using AGS::Common::DataStream;
using AGS::Common::TextStreamReader;
using AGS::Common::String;
extern GameSetup usetup;
extern int spritewidth[MAX_SPRITES],spriteheight[MAX_SPRITES];
extern SpriteCache spriteset;
extern int psp_video_framedrop;
extern int psp_audio_enabled;
extern int psp_midi_enabled;
extern int psp_ignore_acsetup_cfg_file;
extern int psp_clear_cache_on_room_change;
extern int psp_midi_preload_patches;
extern int psp_audio_cachesize;
extern char psp_game_file_name[];
extern int psp_gfx_smooth_sprites;
extern char psp_translation[];
extern int force_letterbox;
extern char replayfile[MAX_PATH];
extern GameState play;
//char datname[80]="ac.clb";
char ac_conf_file_defname[MAX_PATH] = "acsetup.cfg";
char *ac_config_file = &ac_conf_file_defname[0];
char conffilebuf[512];
char filetouse[MAX_PATH] = "nofile";
// Replace the filename part of complete path WASGV with INIFIL
void INIgetdirec(char *wasgv, char *inifil) {
int u = strlen(wasgv) - 1;
for (u = strlen(wasgv) - 1; u >= 0; u--) {
if ((wasgv[u] == '\\') || (wasgv[u] == '/')) {
memcpy(&wasgv[u + 1], inifil, strlen(inifil) + 1);
break;
}
}
if (u <= 0) {
// no slashes - either the path is just "f:acwin.exe"
if (strchr(wasgv, ':') != NULL)
memcpy(strchr(wasgv, ':') + 1, inifil, strlen(inifil) + 1);
// or it's just "acwin.exe" (unlikely)
else
strcpy(wasgv, inifil);
}
}
char *INIreaditem(const char *sectn, const char *entry) {
DataStream *fin = Common::File::OpenFileRead(filetouse);
if (fin == NULL)
return NULL;
TextStreamReader reader(fin);
//char templine[200];
char wantsect[100];
sprintf (wantsect, "[%s]", sectn);
// NOTE: the string is used as a raw buffer down there;
// FIXME that as soon as string class is optimized for common use
String line;
while (!reader.EOS()) {
//fgets (templine, 199, fin);
line = reader.ReadLine();
// find the section
if (strnicmp (wantsect, line.GetCStr(), strlen(wantsect)) == 0) {
while (!reader.EOS()) {
// we're in the right section, find the entry
//fgets (templine, 199, fin);
line = reader.ReadLine();
if (line[0] == '[')
break;
if (reader.EOS())
break;
// Have we found the entry?
if (strnicmp (line.GetCStr(), entry, strlen(entry)) == 0) {
const char *pptr = &line.GetCStr()[strlen(entry)];
while ((pptr[0] == ' ') || (pptr[0] == '\t'))
pptr++;
if (pptr[0] == '=') {
pptr++;
while ((pptr[0] == ' ') || (pptr[0] == '\t'))
pptr++;
char *toret = (char*)malloc (strlen(pptr) + 5);
strcpy (toret, pptr);
return toret;
}
}
}
}
}
return NULL;
}
int INIreadint (const char *sectn, const char *item, int errornosect = 1) {
char *tempstr = INIreaditem (sectn, item);
if (tempstr == NULL)
return -1;
int toret = atoi(tempstr);
free (tempstr);
return toret;
}
void read_config_file(char *argv0) {
// Try current directory for config first; else try exe dir
strcpy (ac_conf_file_defname, "acsetup.cfg");
ac_config_file = &ac_conf_file_defname[0];
if (!Common::File::TestReadFile(ac_config_file)) {
strcpy(conffilebuf,argv0);
/* for (int ee=0;ee<(int)strlen(conffilebuf);ee++) {
if (conffilebuf[ee]=='/') conffilebuf[ee]='\\';
}*/
fix_filename_case(conffilebuf);
fix_filename_slashes(conffilebuf);
INIgetdirec(conffilebuf,ac_config_file);
// printf("Using config: '%s'\n",conffilebuf);
ac_config_file=&conffilebuf[0];
}
else {
// put the full path, or it gets written back to the Windows folder
_getcwd (ac_config_file, 255);
strcat (ac_config_file, "\\acsetup.cfg");
fix_filename_case(ac_config_file);
fix_filename_slashes(ac_config_file);
}
// set default dir if no config file
usetup.data_files_dir = ".";
usetup.translation = NULL;
#ifdef WINDOWS_VERSION
usetup.digicard = DIGI_DIRECTAMX(0);
#endif
// Don't read in the standard config file if disabled.
if (psp_ignore_acsetup_cfg_file)
{
usetup.gfxDriverID = "DX5";
usetup.enable_antialiasing = psp_gfx_smooth_sprites;
usetup.translation = psp_translation;
return;
}
if (Common::File::TestReadFile(ac_config_file)) {
strcpy(filetouse,ac_config_file);
#ifndef WINDOWS_VERSION
usetup.digicard=INIreadint("sound","digiid");
usetup.midicard=INIreadint("sound","midiid");
#else
int idx = INIreadint("sound","digiwinindx", 0);
if (idx == 0)
idx = DIGI_DIRECTAMX(0);
else if (idx == 1)
idx = DIGI_WAVOUTID(0);
else if (idx == 2)
idx = DIGI_NONE;
else if (idx == 3)
idx = DIGI_DIRECTX(0);
else
idx = DIGI_AUTODETECT;
usetup.digicard = idx;
idx = INIreadint("sound","midiwinindx", 0);
if (idx == 1)
idx = MIDI_NONE;
else if (idx == 2)
idx = MIDI_WIN32MAPPER;
else
idx = MIDI_AUTODETECT;
usetup.midicard = idx;
if (usetup.digicard < 0)
usetup.digicard = DIGI_AUTODETECT;
if (usetup.midicard < 0)
usetup.midicard = MIDI_AUTODETECT;
#endif
usetup.windowed = INIreadint("misc","windowed");
if (usetup.windowed < 0)
usetup.windowed = 0;
usetup.refresh = INIreadint ("misc", "refresh", 0);
usetup.enable_antialiasing = INIreadint ("misc", "antialias", 0);
usetup.force_hicolor_mode = INIreadint("misc", "notruecolor", 0);
usetup.enable_side_borders = INIreadint("misc", "sideborders", 0);
#if defined(IOS_VERSION) || defined(PSP_VERSION) || defined(ANDROID_VERSION)
// PSP: Letterboxing is not useful on the PSP.
force_letterbox = 0;
#else
force_letterbox = INIreadint ("misc", "forceletterbox", 0);
#endif
if (usetup.enable_antialiasing < 0)
usetup.enable_antialiasing = 0;
if (usetup.force_hicolor_mode < 0)
usetup.force_hicolor_mode = 0;
if (usetup.enable_side_borders < 0)
usetup.enable_side_borders = 1;
// This option is backwards (usevox is 0 if no_speech_pack)
usetup.no_speech_pack = INIreadint ("sound", "usespeech", 0);
if (usetup.no_speech_pack == 0)
usetup.no_speech_pack = 1;
else
usetup.no_speech_pack = 0;
usetup.data_files_dir = INIreaditem("misc","datadir");
if (usetup.data_files_dir.IsEmpty())
usetup.data_files_dir = ".";
// strip any trailing slash
// TODO: move this to Path namespace later
AGS::Common::Path::FixupPath(usetup.data_files_dir);
#if defined (WINDOWS_VERSION)
// if the path is just x:\ don't strip the slash
if (!(usetup.data_files_dir->GetLength() < 4 && usetup.data_files_dir[1] == ':'))
{
usetup.data_files_dir->TrimRight('/');
}
#else
usetup.data_files_dir->TrimRight('/');
#endif
usetup.main_data_filename = INIreaditem ("misc", "datafile");
#if defined(IOS_VERSION) || defined(PSP_VERSION) || defined(ANDROID_VERSION)
// PSP: No graphic filters are available.
usetup.gfxFilterID = NULL;
#else
usetup.gfxFilterID = INIreaditem("misc", "gfxfilter");
#endif
#if defined (WINDOWS_VERSION)
usetup.gfxDriverID = INIreaditem("misc", "gfxdriver");
#else
usetup.gfxDriverID = "DX5";
#endif
usetup.translation = INIreaditem ("language", "translation");
#if !defined(IOS_VERSION) && !defined(PSP_VERSION) && !defined(ANDROID_VERSION)
// PSP: Don't let the setup determine the cache size as it is always too big.
int tempint = INIreadint ("misc", "cachemax");
if (tempint > 0)
spriteset.maxCacheSize = tempint * 1024;
#endif
char *repfile = INIreaditem ("misc", "replay");
if (repfile != NULL) {
strcpy (replayfile, repfile);
free (repfile);
play.playback = 1;
}
else
play.playback = 0;
}
if (usetup.gfxDriverID == NULL)
usetup.gfxDriverID = "DX5";
}
<commit_msg>Fixed typos related to previous commit<commit_after>//=============================================================================
//
// Adventure Game Studio (AGS)
//
// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
// The full list of copyright holders can be found in the Copyright.txt
// file, which is part of this source code distribution.
//
// The AGS source code is provided under the Artistic License 2.0.
// A copy of this license can be found in the file License.txt and at
// http://www.opensource.org/licenses/artistic-license-2.0.php
//
//=============================================================================
//
// Game configuration
//
#include "util/wgt2allg.h"
#include "ac/gamesetup.h"
#include "ac/gamestate.h"
#include "main/mainheader.h"
#include "main/config.h"
#include "ac/spritecache.h"
#include "platform/base/override_defines.h" //_getcwd()
#include "util/filestream.h"
#include "util/textstreamreader.h"
#include "util/path.h"
using AGS::Common::DataStream;
using AGS::Common::TextStreamReader;
using AGS::Common::String;
extern GameSetup usetup;
extern int spritewidth[MAX_SPRITES],spriteheight[MAX_SPRITES];
extern SpriteCache spriteset;
extern int psp_video_framedrop;
extern int psp_audio_enabled;
extern int psp_midi_enabled;
extern int psp_ignore_acsetup_cfg_file;
extern int psp_clear_cache_on_room_change;
extern int psp_midi_preload_patches;
extern int psp_audio_cachesize;
extern char psp_game_file_name[];
extern int psp_gfx_smooth_sprites;
extern char psp_translation[];
extern int force_letterbox;
extern char replayfile[MAX_PATH];
extern GameState play;
//char datname[80]="ac.clb";
char ac_conf_file_defname[MAX_PATH] = "acsetup.cfg";
char *ac_config_file = &ac_conf_file_defname[0];
char conffilebuf[512];
char filetouse[MAX_PATH] = "nofile";
// Replace the filename part of complete path WASGV with INIFIL
void INIgetdirec(char *wasgv, char *inifil) {
int u = strlen(wasgv) - 1;
for (u = strlen(wasgv) - 1; u >= 0; u--) {
if ((wasgv[u] == '\\') || (wasgv[u] == '/')) {
memcpy(&wasgv[u + 1], inifil, strlen(inifil) + 1);
break;
}
}
if (u <= 0) {
// no slashes - either the path is just "f:acwin.exe"
if (strchr(wasgv, ':') != NULL)
memcpy(strchr(wasgv, ':') + 1, inifil, strlen(inifil) + 1);
// or it's just "acwin.exe" (unlikely)
else
strcpy(wasgv, inifil);
}
}
char *INIreaditem(const char *sectn, const char *entry) {
DataStream *fin = Common::File::OpenFileRead(filetouse);
if (fin == NULL)
return NULL;
TextStreamReader reader(fin);
//char templine[200];
char wantsect[100];
sprintf (wantsect, "[%s]", sectn);
// NOTE: the string is used as a raw buffer down there;
// FIXME that as soon as string class is optimized for common use
String line;
while (!reader.EOS()) {
//fgets (templine, 199, fin);
line = reader.ReadLine();
// find the section
if (strnicmp (wantsect, line.GetCStr(), strlen(wantsect)) == 0) {
while (!reader.EOS()) {
// we're in the right section, find the entry
//fgets (templine, 199, fin);
line = reader.ReadLine();
if (line[0] == '[')
break;
if (reader.EOS())
break;
// Have we found the entry?
if (strnicmp (line.GetCStr(), entry, strlen(entry)) == 0) {
const char *pptr = &line.GetCStr()[strlen(entry)];
while ((pptr[0] == ' ') || (pptr[0] == '\t'))
pptr++;
if (pptr[0] == '=') {
pptr++;
while ((pptr[0] == ' ') || (pptr[0] == '\t'))
pptr++;
char *toret = (char*)malloc (strlen(pptr) + 5);
strcpy (toret, pptr);
return toret;
}
}
}
}
}
return NULL;
}
int INIreadint (const char *sectn, const char *item, int errornosect = 1) {
char *tempstr = INIreaditem (sectn, item);
if (tempstr == NULL)
return -1;
int toret = atoi(tempstr);
free (tempstr);
return toret;
}
void read_config_file(char *argv0) {
// Try current directory for config first; else try exe dir
strcpy (ac_conf_file_defname, "acsetup.cfg");
ac_config_file = &ac_conf_file_defname[0];
if (!Common::File::TestReadFile(ac_config_file)) {
strcpy(conffilebuf,argv0);
/* for (int ee=0;ee<(int)strlen(conffilebuf);ee++) {
if (conffilebuf[ee]=='/') conffilebuf[ee]='\\';
}*/
fix_filename_case(conffilebuf);
fix_filename_slashes(conffilebuf);
INIgetdirec(conffilebuf,ac_config_file);
// printf("Using config: '%s'\n",conffilebuf);
ac_config_file=&conffilebuf[0];
}
else {
// put the full path, or it gets written back to the Windows folder
_getcwd (ac_config_file, 255);
strcat (ac_config_file, "\\acsetup.cfg");
fix_filename_case(ac_config_file);
fix_filename_slashes(ac_config_file);
}
// set default dir if no config file
usetup.data_files_dir = ".";
usetup.translation = NULL;
#ifdef WINDOWS_VERSION
usetup.digicard = DIGI_DIRECTAMX(0);
#endif
// Don't read in the standard config file if disabled.
if (psp_ignore_acsetup_cfg_file)
{
usetup.gfxDriverID = "DX5";
usetup.enable_antialiasing = psp_gfx_smooth_sprites;
usetup.translation = psp_translation;
return;
}
if (Common::File::TestReadFile(ac_config_file)) {
strcpy(filetouse,ac_config_file);
#ifndef WINDOWS_VERSION
usetup.digicard=INIreadint("sound","digiid");
usetup.midicard=INIreadint("sound","midiid");
#else
int idx = INIreadint("sound","digiwinindx", 0);
if (idx == 0)
idx = DIGI_DIRECTAMX(0);
else if (idx == 1)
idx = DIGI_WAVOUTID(0);
else if (idx == 2)
idx = DIGI_NONE;
else if (idx == 3)
idx = DIGI_DIRECTX(0);
else
idx = DIGI_AUTODETECT;
usetup.digicard = idx;
idx = INIreadint("sound","midiwinindx", 0);
if (idx == 1)
idx = MIDI_NONE;
else if (idx == 2)
idx = MIDI_WIN32MAPPER;
else
idx = MIDI_AUTODETECT;
usetup.midicard = idx;
if (usetup.digicard < 0)
usetup.digicard = DIGI_AUTODETECT;
if (usetup.midicard < 0)
usetup.midicard = MIDI_AUTODETECT;
#endif
usetup.windowed = INIreadint("misc","windowed");
if (usetup.windowed < 0)
usetup.windowed = 0;
usetup.refresh = INIreadint ("misc", "refresh", 0);
usetup.enable_antialiasing = INIreadint ("misc", "antialias", 0);
usetup.force_hicolor_mode = INIreadint("misc", "notruecolor", 0);
usetup.enable_side_borders = INIreadint("misc", "sideborders", 0);
#if defined(IOS_VERSION) || defined(PSP_VERSION) || defined(ANDROID_VERSION)
// PSP: Letterboxing is not useful on the PSP.
force_letterbox = 0;
#else
force_letterbox = INIreadint ("misc", "forceletterbox", 0);
#endif
if (usetup.enable_antialiasing < 0)
usetup.enable_antialiasing = 0;
if (usetup.force_hicolor_mode < 0)
usetup.force_hicolor_mode = 0;
if (usetup.enable_side_borders < 0)
usetup.enable_side_borders = 1;
// This option is backwards (usevox is 0 if no_speech_pack)
usetup.no_speech_pack = INIreadint ("sound", "usespeech", 0);
if (usetup.no_speech_pack == 0)
usetup.no_speech_pack = 1;
else
usetup.no_speech_pack = 0;
usetup.data_files_dir = INIreaditem("misc","datadir");
if (usetup.data_files_dir.IsEmpty())
usetup.data_files_dir = ".";
// strip any trailing slash
// TODO: move this to Path namespace later
AGS::Common::Path::FixupPath(usetup.data_files_dir);
#if defined (WINDOWS_VERSION)
// if the path is just x:\ don't strip the slash
if (!(usetup.data_files_dir.GetLength() < 4 && usetup.data_files_dir[1] == ':'))
{
usetup.data_files_dir.TrimRight('/');
}
#else
usetup.data_files_dir.TrimRight('/');
#endif
usetup.main_data_filename = INIreaditem ("misc", "datafile");
#if defined(IOS_VERSION) || defined(PSP_VERSION) || defined(ANDROID_VERSION)
// PSP: No graphic filters are available.
usetup.gfxFilterID = NULL;
#else
usetup.gfxFilterID = INIreaditem("misc", "gfxfilter");
#endif
#if defined (WINDOWS_VERSION)
usetup.gfxDriverID = INIreaditem("misc", "gfxdriver");
#else
usetup.gfxDriverID = "DX5";
#endif
usetup.translation = INIreaditem ("language", "translation");
#if !defined(IOS_VERSION) && !defined(PSP_VERSION) && !defined(ANDROID_VERSION)
// PSP: Don't let the setup determine the cache size as it is always too big.
int tempint = INIreadint ("misc", "cachemax");
if (tempint > 0)
spriteset.maxCacheSize = tempint * 1024;
#endif
char *repfile = INIreaditem ("misc", "replay");
if (repfile != NULL) {
strcpy (replayfile, repfile);
free (repfile);
play.playback = 1;
}
else
play.playback = 0;
}
if (usetup.gfxDriverID == NULL)
usetup.gfxDriverID = "DX5";
}
<|endoftext|> |
<commit_before>#ifndef HAVE_DETAIL_FACTORY_HPP
#define HAVE_DETAIL_FACTORY_HPP
namespace arrayadapt {
/*
*
*/
namespace detail {
/*
*
*/
template <class DataT, size_t kDims, template<class, size_t> class AdapterT>
struct Factory { };
template <class DataT, template<class, size_t> class AdapterT>
struct Factory<DataT, 1, AdapterT> {
/*
*
*/
typedef AdapterT<DataT, 1> concrete_adapter_t;
template <class RealOrImag>
static inline concrete_adapter_t wrap(const mxArray* u, size_t length) {
mxAssert(mxGetClassID(u) == mx_traits<DataT>::classId,
"ArrayAdapter::wrap(): differing Matlab/C types");
return wrap(RealOrImag::get_ptr(u), length);
}
static inline concrete_adapter_t wrap(void* const mxarray, size_t length) {
mxAssert(length > 1,
"ArrayAdapter::wrap(): singleton dimension given (1-dimensional)");
concrete_adapter_t a(mxarray);
a.dimensions[0] = length;
return a;
}
}; // struct Factory<DataT, 1, AdapterT>
template <class DataT, template<class, size_t> class AdapterT>
struct Factory<DataT, 2, AdapterT> {
/*
*
*/
typedef AdapterT<DataT, 2> concrete_adapter_t;
template <class RealOrImag>
static inline concrete_adapter_t wrap(const mxArray* u, size_t nrows, size_t ncols) {
mxAssert(mxGetClassID(u) == mx_traits<DataT>::classId,
"ArrayAdapter::wrap(): differing Matlab/C types");
mxAssert(mxGetNumberOfDimensions(u) == 2,
"ArrayAdapter::wrap(): wrong number of dimensions");
return wrap(RealOrImag::get_ptr(u), nrows, ncols);
}
static inline concrete_adapter_t wrap(void* const mxarray, size_t nrows, size_t ncols) {
mxAssert(nrows > 1,
"ArrayAdapter::wrap(): singleton dimension (1 of 2) given");
mxAssert(ncols > 1,
"ArrayAdapter::wrap(): singleton dimension (2 of 2) given");
concrete_adapter_t a(mxarray);
a.dimensions[0] = nrows;
a.dimensions[1] = ncols;
return a;
}
}; // struct Factory<DataT, 2, AdapterT>
template <class DataT, template<class, size_t> class AdapterT>
struct Factory<DataT, 3, AdapterT> {
/*
*
*/
typedef AdapterT<DataT, 3> concrete_adapter_t;
template <class RealOrImag>
static inline concrete_adapter_t wrap(const mxArray* u,
size_t d1,
size_t d2,
size_t d3) {
mxAssert(mxGetClassID(u) == mx_traits<DataT>::classId,
"ArrayAdapter::wrap(): differing Matlab/C types");
mxAssert(mxGetNumberOfDimensions(u) == 3,
"ArrayAdapter::wrap(): wrong number of dimensions");
return wrap(RealOrImag::get_ptr(u), d1, d2, d3);
}
static inline concrete_adapter_t wrap(void* const mxarray,
size_t d1,
size_t d2,
size_t d3) {
mxAssert(d1 > 1,
"ArrayAdapter::wrap(): singleton dimension (1 of 3) given ");
mxAssert(d2 > 1,
"ArrayAdapter::wrap(): singleton dimension (2 of 3) given ");
mxAssert(d3 > 1,
"ArrayAdapter::wrap(): singleton dimension (3 of 3) given ");
concrete_adapter_t a(mxarray);
a.dimensions[0] = d1;
a.dimensions[1] = d2;
a.dimensions[2] = d3;
return a;
}
}; // struct Factory<DataT, 3, AdapterT>
} // namespace detail
} // namespace arrayadapt
#endif // HAVE_DETAIL_FACTORY_HPP
<commit_msg>drop the non-singleton-dimension constraint<commit_after>#ifndef HAVE_DETAIL_FACTORY_HPP
#define HAVE_DETAIL_FACTORY_HPP
namespace arrayadapt {
/*
*
*/
namespace detail {
/*
*
*/
template <class DataT, size_t kDims, template<class, size_t> class AdapterT>
struct Factory { };
template <class DataT, template<class, size_t> class AdapterT>
struct Factory<DataT, 1, AdapterT> {
/*
*
*/
typedef AdapterT<DataT, 1> concrete_adapter_t;
template <class RealOrImag>
static inline concrete_adapter_t wrap(const mxArray* u, size_t length) {
mxAssert(mxGetClassID(u) == mx_traits<DataT>::classId,
"ArrayAdapter::wrap(): differing Matlab/C types");
return wrap(RealOrImag::get_ptr(u), length);
}
static inline concrete_adapter_t wrap(void* const mxarray, size_t length) {
mxAssert(length > 0,
"ArrayAdapter::wrap(): zero-size dimension (1 of 1) given");
concrete_adapter_t a(mxarray);
a.dimensions[0] = length;
return a;
}
}; // struct Factory<DataT, 1, AdapterT>
template <class DataT, template<class, size_t> class AdapterT>
struct Factory<DataT, 2, AdapterT> {
/*
*
*/
typedef AdapterT<DataT, 2> concrete_adapter_t;
template <class RealOrImag>
static inline concrete_adapter_t wrap(const mxArray* u, size_t nrows, size_t ncols) {
mxAssert(mxGetClassID(u) == mx_traits<DataT>::classId,
"ArrayAdapter::wrap(): differing Matlab/C types");
mxAssert(mxGetNumberOfDimensions(u) == 2,
"ArrayAdapter::wrap(): wrong number of dimensions");
return wrap(RealOrImag::get_ptr(u), nrows, ncols);
}
static inline concrete_adapter_t wrap(void* const mxarray, size_t nrows, size_t ncols) {
mxAssert(nrows > 0,
"ArrayAdapter::wrap(): zero-size dimension (1 of 2) given");
mxAssert(ncols > 0,
"ArrayAdapter::wrap(): zero-size dimension (2 of 2) given");
concrete_adapter_t a(mxarray);
a.dimensions[0] = nrows;
a.dimensions[1] = ncols;
return a;
}
}; // struct Factory<DataT, 2, AdapterT>
template <class DataT, template<class, size_t> class AdapterT>
struct Factory<DataT, 3, AdapterT> {
/*
*
*/
typedef AdapterT<DataT, 3> concrete_adapter_t;
template <class RealOrImag>
static inline concrete_adapter_t wrap(const mxArray* u,
size_t d1,
size_t d2,
size_t d3) {
mxAssert(mxGetClassID(u) == mx_traits<DataT>::classId,
"ArrayAdapter::wrap(): differing Matlab/C types");
mxAssert(mxGetNumberOfDimensions(u) == 3,
"ArrayAdapter::wrap(): wrong number of dimensions");
return wrap(RealOrImag::get_ptr(u), d1, d2, d3);
}
static inline concrete_adapter_t wrap(void* const mxarray,
size_t d1,
size_t d2,
size_t d3) {
mxAssert(d1 > 0,
"ArrayAdapter::wrap(): zero-size dimension (1 of 3) given ");
mxAssert(d2 > 0,
"ArrayAdapter::wrap(): zero-size dimension (2 of 3) given ");
mxAssert(d3 > 0,
"ArrayAdapter::wrap(): zero-size dimension (3 of 3) given ");
concrete_adapter_t a(mxarray);
a.dimensions[0] = d1;
a.dimensions[1] = d2;
a.dimensions[2] = d3;
return a;
}
}; // struct Factory<DataT, 3, AdapterT>
} // namespace detail
} // namespace arrayadapt
#endif // HAVE_DETAIL_FACTORY_HPP
<|endoftext|> |
<commit_before>#include "ProcessUtils.h"
#include "FileOps.h"
#include "Platform.h"
#include "StringUtils.h"
#include "Log.h"
#include <string.h>
#include <vector>
#include <iostream>
#ifdef PLATFORM_WINDOWS
#include <windows.h>
#else
#include <stdlib.h>
#include <sys/wait.h>
#include <errno.h>
#endif
#ifdef PLATFORM_MAC
#include <Security/Security.h>
#include <mach-o/dyld.h>
#endif
PLATFORM_PID ProcessUtils::currentProcessId()
{
#ifdef PLATFORM_UNIX
return getpid();
#else
return GetCurrentProcessId();
#endif
}
int ProcessUtils::runSync(const std::string& executable,
const std::list<std::string>& args)
{
#ifdef PLATFORM_UNIX
return runSyncUnix(executable,args);
#else
return runSyncWindows(executable,args);
#endif
}
#ifdef PLATFORM_UNIX
int ProcessUtils::runSyncUnix(const std::string& executable,
const std::list<std::string>& args)
{
int pid = runAsyncUnix(executable,args);
int status = 0;
waitpid(pid,&status,0);
return status;
}
#endif
#ifdef PLATFORM_WINDOWS
int ProcessUtils::runSyncWindows(const std::string& executable,
const std::list<std::string>& args)
{
// TODO - Implement me
return 0;
}
#endif
void ProcessUtils::runAsync(const std::string& executable,
const std::list<std::string>& args)
{
#ifdef PLATFORM_WINDOWS
runAsyncWindows(executable,args);
#elif defined(PLATFORM_UNIX)
runAsyncUnix(executable,args);
#endif
}
void ProcessUtils::runElevated(const std::string& executable,
const std::list<std::string>& args)
{
#ifdef PLATFORM_WINDOWS
runElevatedWindows(executable,args);
#elif defined(PLATFORM_MAC)
runElevatedMac(executable,args);
#elif defined(PLATFORM_LINUX)
runElevatedLinux(executable,args);
#endif
}
bool ProcessUtils::waitForProcess(PLATFORM_PID pid)
{
#ifdef PLATFORM_UNIX
pid_t result = ::waitpid(pid, 0, 0);
if (result < 0)
{
LOG(Error,"waitpid() failed with error: " + std::string(strerror(errno)));
}
return result > 0;
#elif defined(PLATFORM_WINDOWS)
HANDLE hProc;
if (!(hProc = OpenProcess(SYNCHRONIZE, FALSE, pid)))
{
LOG(Error,"Unable to get process handle for pid " + intToStr(pid) + " last error " + intToStr(GetLastError()));
return false;
}
DWORD dwRet = WaitForSingleObject(hProc, INFINITE);
CloseHandle(hProc);
if (dwRet == WAIT_FAILED)
{
LOG(Error,"WaitForSingleObject failed with error " + intToStr(GetLastError()));
}
return (dwRet == WAIT_OBJECT_0);
#endif
}
#ifdef PLATFORM_LINUX
void ProcessUtils::runElevatedLinux(const std::string& executable,
const std::list<std::string>& args)
{
std::string sudoMessage = FileOps::fileName(executable.c_str()) + " needs administrative privileges. Please enter your password.";
std::vector<std::string> sudos;
sudos.push_back("kdesudo");
sudos.push_back("gksudo");
sudos.push_back("gksu");
for (int i=0; i < sudos.size(); i++)
{
const std::string& sudoBinary = sudos.at(i);
std::list<std::string> sudoArgs;
sudoArgs.push_back("-u");
sudoArgs.push_back("root");
if (sudoBinary == "kdesudo")
{
sudoArgs.push_back("-d");
sudoArgs.push_back("--comment");
sudoArgs.push_back(sudoMessage);
}
else
{
sudoArgs.push_back(sudoMessage);
}
sudoArgs.push_back("--");
sudoArgs.push_back(executable);
std::copy(args.begin(),args.end(),std::back_inserter(sudoArgs));
// != 255: some sudo has been found and user failed to authenticate
// or user authenticated correctly
int result = ProcessUtils::runSync(sudoBinary,sudoArgs);
if (result != 255)
{
break;
}
}
}
#endif
#ifdef PLATFORM_MAC
void ProcessUtils::runElevatedMac(const std::string& executable,
const std::list<std::string>& args)
{
// request elevation using the Security Service.
//
// This only works when the application is being run directly
// from the Mac. Attempting to run the app via a remote SSH session
// (for example) will fail with an interaction-not-allowed error
OSStatus status;
AuthorizationRef authorizationRef;
status = AuthorizationCreate(
NULL,
kAuthorizationEmptyEnvironment,
kAuthorizationFlagDefaults,
&authorizationRef);
AuthorizationItem right = { kAuthorizationRightExecute, 0, NULL, 0 };
AuthorizationRights rights = { 1, &right };
AuthorizationFlags flags = kAuthorizationFlagDefaults |
kAuthorizationFlagInteractionAllowed |
kAuthorizationFlagPreAuthorize |
kAuthorizationFlagExtendRights;
if (status == errAuthorizationSuccess)
{
status = AuthorizationCopyRights(authorizationRef, &rights, NULL,
flags, NULL);
if (status == errAuthorizationSuccess)
{
char** argv;
argv = (char**) malloc(sizeof(char*) * args.size() + 1);
int i = 0;
for (std::list<std::string>::const_iterator iter = args.begin(); iter != args.end(); iter++)
{
argv[i] = strdup(iter->c_str());
++i;
}
argv[i] = NULL;
FILE* pipe = NULL;
char* tool = strdup(executable.c_str());
status = AuthorizationExecuteWithPrivileges(authorizationRef, tool,
kAuthorizationFlagDefaults, argv, &pipe);
if (status == errAuthorizationSuccess)
{
// AuthorizationExecuteWithPrivileges does not provide a way to get the process ID
// of the child process.
//
// Discussions on Apple development forums suggest two approaches for working around this,
//
// - Modify the child process to sent its process ID back to the parent via
// the pipe passed to AuthorizationExecuteWithPrivileges.
//
// - Use the generic Unix wait() call.
//
// This code uses wait(), which is simpler, but suffers from the problem that wait() waits
// for any child process, not necessarily the specific process launched
// by AuthorizationExecuteWithPrivileges.
//
// Apple's documentation (see 'Authorization Services Programming Guide') suggests
// installing files in an installer as a legitimate use for
// AuthorizationExecuteWithPrivileges but in general strongly recommends
// not using this call and discusses a number of other alternatives
// for performing privileged operations,
// which we could consider in future.
int childStatus;
pid_t childPid = wait(&childStatus);
if (childStatus != 0)
{
LOG(Error,"elevated process failed with status " + intToStr(childStatus) + " pid "
+ intToStr(childPid));
}
else
{
LOG(Info,"elevated process succeded with pid " + intToStr(childPid));
}
}
else
{
LOG(Error,"failed to launch elevated process " + intToStr(status));
}
// If we want to know more information about what has happened:
// http://developer.apple.com/mac/library/documentation/Security/Reference/authorization_ref/Reference/reference.html#//apple_ref/doc/uid/TP30000826-CH4g-CJBEABHG
free(tool);
for (i = 0; i < args.size(); i++)
{
free(argv[i]);
}
}
else
{
LOG(Error,"failed to get rights to launch elevated process. status: " + intToStr(status));
}
}
}
#endif
#ifdef PLATFORM_WINDOWS
void ProcessUtils::runElevatedWindows(const std::string& executable,
const std::list<std::string>& arguments)
{
std::string args;
// quote process arguments
for (std::list<std::string>::const_iterator iter = arguments.begin();
iter != arguments.end();
iter++)
{
std::string arg = *iter;
if (arg.at(0) != '"' && arg.at(arg.size()-1) != '"')
{
arg.insert(0,"\"");
arg.append("\"");
}
args += arg;
args += " ";
}
SHELLEXECUTEINFO executeInfo;
ZeroMemory(&executeInfo,sizeof(executeInfo));
executeInfo.cbSize = sizeof(SHELLEXECUTEINFO);
executeInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
// request UAC elevation
executeInfo.lpVerb = "runas";
executeInfo.lpFile = executable.c_str();
executeInfo.lpParameters = args.c_str();
executeInfo.nShow = SW_SHOWNORMAL;
LOG(Info,"Attempting to execute " + executable + " with administrator priviledges");
if (!ShellExecuteEx(&executeInfo))
{
LOG(Error,"Failed to start with admin priviledges using ShellExecuteEx()");
return;
}
WaitForSingleObject(executeInfo.hProcess, INFINITE);
}
#endif
#ifdef PLATFORM_UNIX
int ProcessUtils::runAsyncUnix(const std::string& executable,
const std::list<std::string>& args)
{
pid_t child = fork();
if (child == 0)
{
// in child process
char** argBuffer = new char*[args.size() + 2];
argBuffer[0] = strdup(executable.c_str());
int i = 1;
for (std::list<std::string>::const_iterator iter = args.begin(); iter != args.end(); iter++)
{
argBuffer[i] = strdup(iter->c_str());
++i;
}
argBuffer[i] = 0;
if (execvp(executable.c_str(),argBuffer) == -1)
{
LOG(Error,"error starting child: " + std::string(strerror(errno)));
exit(1);
}
}
else
{
LOG(Info,"Started child process " + intToStr(child));
}
}
#endif
#ifdef PLATFORM_WINDOWS
void ProcessUtils::runAsyncWindows(const std::string& executable,
const std::list<std::string>& args)
{
std::string commandLine = executable;
for (std::list<std::string>::const_iterator iter = args.begin(); iter != args.end(); iter++)
{
if (!commandLine.empty())
{
commandLine.append(" ");
}
commandLine.append(*iter);
}
STARTUPINFO startupInfo;
ZeroMemory(&startupInfo,sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);
PROCESS_INFORMATION processInfo;
ZeroMemory(&processInfo,sizeof(processInfo));
char* commandLineStr = strdup(commandLine.c_str());
bool result = CreateProcess(
executable.c_str(),
commandLineStr,
0 /* process attributes */,
0 /* thread attributes */,
false /* inherit handles */,
NORMAL_PRIORITY_CLASS /* creation flags */,
0 /* environment */,
0 /* current directory */,
&startupInfo /* startup info */,
&processInfo /* process information */
);
if (!result)
{
LOG(Error,"Failed to start child process. " + executable + " Last error: " + intToStr(GetLastError()));
}
}
#endif
std::string ProcessUtils::currentProcessPath()
{
#ifdef PLATFORM_LINUX
std::string path = FileOps::canonicalPath("/proc/self/exe");
LOG(Info,"Current process path " + path);
return path;
#elif defined(PLATFORM_MAC)
uint32_t bufferSize = PATH_MAX;
char buffer[bufferSize];
_NSGetExecutablePath(buffer,&bufferSize);
return buffer;
#else
char fileName[MAX_PATH];
GetModuleFileName(0 /* get path of current process */,fileName,MAX_PATH);
return fileName;
#endif
}
<commit_msg>Fix possible out-of-bounds array access if an empty command-line argument is passed to ProcessUtils::runElevated() on Windows<commit_after>#include "ProcessUtils.h"
#include "FileOps.h"
#include "Platform.h"
#include "StringUtils.h"
#include "Log.h"
#include <string.h>
#include <vector>
#include <iostream>
#ifdef PLATFORM_WINDOWS
#include <windows.h>
#else
#include <stdlib.h>
#include <sys/wait.h>
#include <errno.h>
#endif
#ifdef PLATFORM_MAC
#include <Security/Security.h>
#include <mach-o/dyld.h>
#endif
PLATFORM_PID ProcessUtils::currentProcessId()
{
#ifdef PLATFORM_UNIX
return getpid();
#else
return GetCurrentProcessId();
#endif
}
int ProcessUtils::runSync(const std::string& executable,
const std::list<std::string>& args)
{
#ifdef PLATFORM_UNIX
return runSyncUnix(executable,args);
#else
return runSyncWindows(executable,args);
#endif
}
#ifdef PLATFORM_UNIX
int ProcessUtils::runSyncUnix(const std::string& executable,
const std::list<std::string>& args)
{
int pid = runAsyncUnix(executable,args);
int status = 0;
waitpid(pid,&status,0);
return status;
}
#endif
#ifdef PLATFORM_WINDOWS
int ProcessUtils::runSyncWindows(const std::string& executable,
const std::list<std::string>& args)
{
// TODO - Implement me
return 0;
}
#endif
void ProcessUtils::runAsync(const std::string& executable,
const std::list<std::string>& args)
{
#ifdef PLATFORM_WINDOWS
runAsyncWindows(executable,args);
#elif defined(PLATFORM_UNIX)
runAsyncUnix(executable,args);
#endif
}
void ProcessUtils::runElevated(const std::string& executable,
const std::list<std::string>& args)
{
#ifdef PLATFORM_WINDOWS
runElevatedWindows(executable,args);
#elif defined(PLATFORM_MAC)
runElevatedMac(executable,args);
#elif defined(PLATFORM_LINUX)
runElevatedLinux(executable,args);
#endif
}
bool ProcessUtils::waitForProcess(PLATFORM_PID pid)
{
#ifdef PLATFORM_UNIX
pid_t result = ::waitpid(pid, 0, 0);
if (result < 0)
{
LOG(Error,"waitpid() failed with error: " + std::string(strerror(errno)));
}
return result > 0;
#elif defined(PLATFORM_WINDOWS)
HANDLE hProc;
if (!(hProc = OpenProcess(SYNCHRONIZE, FALSE, pid)))
{
LOG(Error,"Unable to get process handle for pid " + intToStr(pid) + " last error " + intToStr(GetLastError()));
return false;
}
DWORD dwRet = WaitForSingleObject(hProc, INFINITE);
CloseHandle(hProc);
if (dwRet == WAIT_FAILED)
{
LOG(Error,"WaitForSingleObject failed with error " + intToStr(GetLastError()));
}
return (dwRet == WAIT_OBJECT_0);
#endif
}
#ifdef PLATFORM_LINUX
void ProcessUtils::runElevatedLinux(const std::string& executable,
const std::list<std::string>& args)
{
std::string sudoMessage = FileOps::fileName(executable.c_str()) + " needs administrative privileges. Please enter your password.";
std::vector<std::string> sudos;
sudos.push_back("kdesudo");
sudos.push_back("gksudo");
sudos.push_back("gksu");
for (int i=0; i < sudos.size(); i++)
{
const std::string& sudoBinary = sudos.at(i);
std::list<std::string> sudoArgs;
sudoArgs.push_back("-u");
sudoArgs.push_back("root");
if (sudoBinary == "kdesudo")
{
sudoArgs.push_back("-d");
sudoArgs.push_back("--comment");
sudoArgs.push_back(sudoMessage);
}
else
{
sudoArgs.push_back(sudoMessage);
}
sudoArgs.push_back("--");
sudoArgs.push_back(executable);
std::copy(args.begin(),args.end(),std::back_inserter(sudoArgs));
// != 255: some sudo has been found and user failed to authenticate
// or user authenticated correctly
int result = ProcessUtils::runSync(sudoBinary,sudoArgs);
if (result != 255)
{
break;
}
}
}
#endif
#ifdef PLATFORM_MAC
void ProcessUtils::runElevatedMac(const std::string& executable,
const std::list<std::string>& args)
{
// request elevation using the Security Service.
//
// This only works when the application is being run directly
// from the Mac. Attempting to run the app via a remote SSH session
// (for example) will fail with an interaction-not-allowed error
OSStatus status;
AuthorizationRef authorizationRef;
status = AuthorizationCreate(
NULL,
kAuthorizationEmptyEnvironment,
kAuthorizationFlagDefaults,
&authorizationRef);
AuthorizationItem right = { kAuthorizationRightExecute, 0, NULL, 0 };
AuthorizationRights rights = { 1, &right };
AuthorizationFlags flags = kAuthorizationFlagDefaults |
kAuthorizationFlagInteractionAllowed |
kAuthorizationFlagPreAuthorize |
kAuthorizationFlagExtendRights;
if (status == errAuthorizationSuccess)
{
status = AuthorizationCopyRights(authorizationRef, &rights, NULL,
flags, NULL);
if (status == errAuthorizationSuccess)
{
char** argv;
argv = (char**) malloc(sizeof(char*) * args.size() + 1);
int i = 0;
for (std::list<std::string>::const_iterator iter = args.begin(); iter != args.end(); iter++)
{
argv[i] = strdup(iter->c_str());
++i;
}
argv[i] = NULL;
FILE* pipe = NULL;
char* tool = strdup(executable.c_str());
status = AuthorizationExecuteWithPrivileges(authorizationRef, tool,
kAuthorizationFlagDefaults, argv, &pipe);
if (status == errAuthorizationSuccess)
{
// AuthorizationExecuteWithPrivileges does not provide a way to get the process ID
// of the child process.
//
// Discussions on Apple development forums suggest two approaches for working around this,
//
// - Modify the child process to sent its process ID back to the parent via
// the pipe passed to AuthorizationExecuteWithPrivileges.
//
// - Use the generic Unix wait() call.
//
// This code uses wait(), which is simpler, but suffers from the problem that wait() waits
// for any child process, not necessarily the specific process launched
// by AuthorizationExecuteWithPrivileges.
//
// Apple's documentation (see 'Authorization Services Programming Guide') suggests
// installing files in an installer as a legitimate use for
// AuthorizationExecuteWithPrivileges but in general strongly recommends
// not using this call and discusses a number of other alternatives
// for performing privileged operations,
// which we could consider in future.
int childStatus;
pid_t childPid = wait(&childStatus);
if (childStatus != 0)
{
LOG(Error,"elevated process failed with status " + intToStr(childStatus) + " pid "
+ intToStr(childPid));
}
else
{
LOG(Info,"elevated process succeded with pid " + intToStr(childPid));
}
}
else
{
LOG(Error,"failed to launch elevated process " + intToStr(status));
}
// If we want to know more information about what has happened:
// http://developer.apple.com/mac/library/documentation/Security/Reference/authorization_ref/Reference/reference.html#//apple_ref/doc/uid/TP30000826-CH4g-CJBEABHG
free(tool);
for (i = 0; i < args.size(); i++)
{
free(argv[i]);
}
}
else
{
LOG(Error,"failed to get rights to launch elevated process. status: " + intToStr(status));
}
}
}
#endif
#ifdef PLATFORM_WINDOWS
void ProcessUtils::runElevatedWindows(const std::string& executable,
const std::list<std::string>& arguments)
{
std::string args;
// quote process arguments
for (std::list<std::string>::const_iterator iter = arguments.begin();
iter != arguments.end();
iter++)
{
std::string arg = *iter;
if (!arg.empty() && arg.at(0) != '"' && arg.at(arg.size()-1) != '"')
{
arg.insert(0,"\"");
arg.append("\"");
}
args += arg;
args += " ";
}
SHELLEXECUTEINFO executeInfo;
ZeroMemory(&executeInfo,sizeof(executeInfo));
executeInfo.cbSize = sizeof(SHELLEXECUTEINFO);
executeInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
// request UAC elevation
executeInfo.lpVerb = "runas";
executeInfo.lpFile = executable.c_str();
executeInfo.lpParameters = args.c_str();
executeInfo.nShow = SW_SHOWNORMAL;
LOG(Info,"Attempting to execute " + executable + " with administrator priviledges");
if (!ShellExecuteEx(&executeInfo))
{
LOG(Error,"Failed to start with admin priviledges using ShellExecuteEx()");
return;
}
WaitForSingleObject(executeInfo.hProcess, INFINITE);
}
#endif
#ifdef PLATFORM_UNIX
int ProcessUtils::runAsyncUnix(const std::string& executable,
const std::list<std::string>& args)
{
pid_t child = fork();
if (child == 0)
{
// in child process
char** argBuffer = new char*[args.size() + 2];
argBuffer[0] = strdup(executable.c_str());
int i = 1;
for (std::list<std::string>::const_iterator iter = args.begin(); iter != args.end(); iter++)
{
argBuffer[i] = strdup(iter->c_str());
++i;
}
argBuffer[i] = 0;
if (execvp(executable.c_str(),argBuffer) == -1)
{
LOG(Error,"error starting child: " + std::string(strerror(errno)));
exit(1);
}
}
else
{
LOG(Info,"Started child process " + intToStr(child));
}
}
#endif
#ifdef PLATFORM_WINDOWS
void ProcessUtils::runAsyncWindows(const std::string& executable,
const std::list<std::string>& args)
{
std::string commandLine = executable;
for (std::list<std::string>::const_iterator iter = args.begin(); iter != args.end(); iter++)
{
if (!commandLine.empty())
{
commandLine.append(" ");
}
commandLine.append(*iter);
}
STARTUPINFO startupInfo;
ZeroMemory(&startupInfo,sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);
PROCESS_INFORMATION processInfo;
ZeroMemory(&processInfo,sizeof(processInfo));
char* commandLineStr = strdup(commandLine.c_str());
bool result = CreateProcess(
executable.c_str(),
commandLineStr,
0 /* process attributes */,
0 /* thread attributes */,
false /* inherit handles */,
NORMAL_PRIORITY_CLASS /* creation flags */,
0 /* environment */,
0 /* current directory */,
&startupInfo /* startup info */,
&processInfo /* process information */
);
if (!result)
{
LOG(Error,"Failed to start child process. " + executable + " Last error: " + intToStr(GetLastError()));
}
}
#endif
std::string ProcessUtils::currentProcessPath()
{
#ifdef PLATFORM_LINUX
std::string path = FileOps::canonicalPath("/proc/self/exe");
LOG(Info,"Current process path " + path);
return path;
#elif defined(PLATFORM_MAC)
uint32_t bufferSize = PATH_MAX;
char buffer[bufferSize];
_NSGetExecutablePath(buffer,&bufferSize);
return buffer;
#else
char fileName[MAX_PATH];
GetModuleFileName(0 /* get path of current process */,fileName,MAX_PATH);
return fileName;
#endif
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015 - 2022, Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "ProfileTable.hpp"
#include <limits.h>
#include <pthread.h>
#include <cstdint>
#include <string.h>
#include <algorithm>
#include <string>
#include "geopm_time.h"
#include "geopm_hint.h"
#include "geopm_hash.h"
#include "geopm/Exception.hpp"
#include "config.h"
namespace geopm
{
ProfileTableImp::ProfileTableImp(size_t size, void *buffer)
: m_buffer_size(size)
, m_table((struct table_s *)buffer)
, m_key_map_lock(PTHREAD_MUTEX_INITIALIZER)
, m_is_pshared(true)
, m_key_map_last(m_key_map.end())
{
if (buffer == NULL) {
throw Exception("ProfileTableImp: Buffer pointer is NULL", GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
if (size < (sizeof(struct table_s) + 4 * sizeof(struct geopm_prof_message_s))) {
throw Exception("ProfileTableImp: table size too small",
GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
}
// set up prof message array
memset(buffer, 0, size);
m_table->max_size = (m_buffer_size - sizeof(struct table_s)) / sizeof(struct geopm_prof_message_s);
m_table->curr_size = 0;
// set up lock
pthread_mutexattr_t lock_attr;
int err = pthread_mutexattr_init(&lock_attr);
if (err) {
throw Exception("ProfileTableImp: pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
}
if (m_is_pshared) {
err = pthread_mutexattr_setpshared(&lock_attr, PTHREAD_PROCESS_SHARED);
if (err) {
(void) pthread_mutexattr_destroy(&lock_attr);
throw Exception("ProfileTableImp: pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
}
}
err = pthread_mutex_init(&(m_table->lock), &lock_attr);
if (err) {
(void) pthread_mutexattr_destroy(&lock_attr);
throw Exception("ProfileTableImp: pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
}
err = pthread_mutexattr_destroy(&lock_attr);
if (err) {
throw Exception("ProfileTableImp: pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
}
m_table_value = (struct geopm_prof_message_s *)((char *)buffer + sizeof(struct table_s));
}
void ProfileTableImp::insert(const struct geopm_prof_message_s &value)
{
int err = pthread_mutex_lock(&(m_table->lock));
if (err) {
throw Exception("ProfileTableImp::insert(): pthread_mutex_lock()", err, __FILE__, __LINE__);
}
// update the progress for the same region if not an entry or exit
bool is_inserted = false;
if (m_table->curr_size > 0) {
size_t curr_idx = m_table->curr_size - 1;
if (value.region_id == m_table_value[curr_idx].region_id &&
m_table_value[curr_idx].progress != 0.0 &&
m_table_value[curr_idx].progress != 1.0) {
m_table_value[curr_idx] = value;
is_inserted = true;
}
}
if (!is_inserted) {
// check for overflow
if (m_table->curr_size >= m_table->max_size) {
(void) pthread_mutex_unlock(&(m_table->lock));
throw Exception("ProfileTableImp::insert(): table overflowed.",
GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
}
m_table_value[m_table->curr_size] = value;
++m_table->curr_size;
}
err = pthread_mutex_unlock(&(m_table->lock));
if (err) {
throw Exception("ProfileTableImp::insert(): pthread_mutex_unlock()", err, __FILE__, __LINE__);
}
}
uint64_t ProfileTableImp::key(const std::string &name)
{
uint64_t result = 0;
int err = pthread_mutex_lock(&(m_key_map_lock));
if (err) {
throw Exception("ProfileTableImp::key(): pthread_mutex_lock()", err, __FILE__, __LINE__);
}
auto key_map_it = m_key_map.find(name);
err = pthread_mutex_unlock(&(m_key_map_lock));
if (err) {
throw Exception("ProfileTableImp::key(): pthread_mutex_unlock()", err, __FILE__, __LINE__);
}
if (key_map_it != m_key_map.end()) {
result = key_map_it->second;
}
else {
result = geopm_crc32_str((char *)(&name.front()));
if (GEOPM_REGION_HASH_INVALID == result) {
throw Exception("ProfileTableImp::key(): CRC 32 hashed to zero!", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
}
err = pthread_mutex_lock(&(m_key_map_lock));
if (err) {
throw Exception("ProfileTableImp::key(): pthread_mutex_lock()", err, __FILE__, __LINE__);
}
if (m_key_set.find(result) != m_key_set.end()) {
pthread_mutex_unlock(&(m_key_map_lock));
throw Exception("ProfileTableImp::key(): String hash collision", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
}
m_key_set.insert(result);
m_key_map.insert(std::pair<const std::string, uint64_t>(name, result));
m_key_map_last = m_key_map.begin();
err = pthread_mutex_unlock(&(m_key_map_lock));
if (err) {
throw Exception("ProfileTableImp::key(): pthread_mutex_unlock()", err, __FILE__, __LINE__);
}
}
return result;
}
size_t ProfileTableImp::capacity(void) const
{
return m_table->max_size;
}
size_t ProfileTableImp::size(void) const
{
size_t result = 0;
int err = pthread_mutex_lock(&(m_table->lock));
if (err) {
throw Exception("ProfileTableImp::size(): pthread_mutex_lock()", err, __FILE__, __LINE__);
}
result = m_table->curr_size;
err = pthread_mutex_unlock(&(m_table->lock));
if (err) {
throw Exception("ProfileTableImp::size(): pthread_mutex_unlock()", err, __FILE__, __LINE__);
}
return result;
}
void ProfileTableImp::dump(std::vector<std::pair<uint64_t, struct geopm_prof_message_s> >::iterator content, size_t &length)
{
int err;
err = pthread_mutex_lock(&(m_table->lock));
if (err) {
throw Exception("ProfileTableImp::dump(): pthread_mutex_lock()", err, __FILE__, __LINE__);
}
for (size_t depth = 0; depth != m_table->curr_size; ++depth) {
content->first = m_table_value[depth].region_id;
content->second = m_table_value[depth];
++content;
}
length = m_table->curr_size;
m_table->curr_size = 0;
err = pthread_mutex_unlock(&(m_table->lock));
if (err) {
throw Exception("ProfileTableImp::dump(): pthread_mutex_unlock()", err, __FILE__, __LINE__);
}
}
bool ProfileTableImp::name_fill(size_t header_offset)
{
bool result = false;
size_t buffer_remain = m_buffer_size - header_offset - 1;
char *buffer_ptr = (char *)m_table + header_offset;
while (m_key_map_last != m_key_map.end() &&
buffer_remain > m_key_map_last->first.length()) {
strncpy(buffer_ptr, m_key_map_last->first.c_str(), buffer_remain);
buffer_remain -= m_key_map_last->first.length() + 1;
buffer_ptr += m_key_map_last->first.length() + 1;
++m_key_map_last;
}
memset(buffer_ptr, 0, buffer_remain);
if (m_key_map_last == m_key_map.end() && buffer_remain) {
// We are done, set last character to '\1'
buffer_ptr[buffer_remain] = '\1';
m_key_map_last = m_key_map.begin();
result = true;
}
else {
buffer_ptr[buffer_remain] = '\0';
}
return result;
}
bool ProfileTableImp::name_set(size_t header_offset, std::set<std::string> &name)
{
// Check if last character is '\1' to see more names remain to be passed
bool result = (((char *)m_table)[m_buffer_size - 1] == '\1');
size_t buffer_remain = m_buffer_size - header_offset - 1;
char *buffer_ptr = (char *)m_table + header_offset;
while (buffer_remain) {
size_t name_len = strnlen(buffer_ptr, buffer_remain);
if (name_len == buffer_remain) {
throw Exception("ProfileTableImp::name_set(): buffer missing null termination", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
}
if (name_len) {
name.insert(std::string(buffer_ptr));
buffer_remain -= name_len + 1;
buffer_ptr += name_len + 1;
}
else {
buffer_remain = 0;
}
}
return result;
}
}
<commit_msg>Enhance error message in ProfileTable if mutex unlock fails<commit_after>/*
* Copyright (c) 2015 - 2022, Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "ProfileTable.hpp"
#include <limits.h>
#include <pthread.h>
#include <cstdint>
#include <string.h>
#include <algorithm>
#include <string>
#include "geopm_time.h"
#include "geopm_hint.h"
#include "geopm_hash.h"
#include "geopm/Exception.hpp"
#include "config.h"
namespace geopm
{
ProfileTableImp::ProfileTableImp(size_t size, void *buffer)
: m_buffer_size(size)
, m_table((struct table_s *)buffer)
, m_key_map_lock(PTHREAD_MUTEX_INITIALIZER)
, m_is_pshared(true)
, m_key_map_last(m_key_map.end())
{
if (buffer == NULL) {
throw Exception("ProfileTableImp: Buffer pointer is NULL", GEOPM_ERROR_INVALID, __FILE__, __LINE__);
}
if (size < (sizeof(struct table_s) + 4 * sizeof(struct geopm_prof_message_s))) {
throw Exception("ProfileTableImp: table size too small",
GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
}
// set up prof message array
memset(buffer, 0, size);
m_table->max_size = (m_buffer_size - sizeof(struct table_s)) / sizeof(struct geopm_prof_message_s);
m_table->curr_size = 0;
// set up lock
pthread_mutexattr_t lock_attr;
int err = pthread_mutexattr_init(&lock_attr);
if (err) {
throw Exception("ProfileTableImp: pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
}
if (m_is_pshared) {
err = pthread_mutexattr_setpshared(&lock_attr, PTHREAD_PROCESS_SHARED);
if (err) {
(void) pthread_mutexattr_destroy(&lock_attr);
throw Exception("ProfileTableImp: pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
}
}
err = pthread_mutex_init(&(m_table->lock), &lock_attr);
if (err) {
(void) pthread_mutexattr_destroy(&lock_attr);
throw Exception("ProfileTableImp: pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
}
err = pthread_mutexattr_destroy(&lock_attr);
if (err) {
throw Exception("ProfileTableImp: pthread mutex initialization", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
}
m_table_value = (struct geopm_prof_message_s *)((char *)buffer + sizeof(struct table_s));
}
void ProfileTableImp::insert(const struct geopm_prof_message_s &value)
{
int err = pthread_mutex_lock(&(m_table->lock));
if (err) {
throw Exception("ProfileTableImp::insert(): pthread_mutex_lock()", err, __FILE__, __LINE__);
}
// update the progress for the same region if not an entry or exit
bool is_inserted = false;
if (m_table->curr_size > 0) {
size_t curr_idx = m_table->curr_size - 1;
if (value.region_id == m_table_value[curr_idx].region_id &&
m_table_value[curr_idx].progress != 0.0 &&
m_table_value[curr_idx].progress != 1.0) {
m_table_value[curr_idx] = value;
is_inserted = true;
}
}
if (!is_inserted) {
// check for overflow
if (m_table->curr_size >= m_table->max_size) {
err = pthread_mutex_unlock(&(m_table->lock));
std::string err_msg = "ProfileTableImp::insert(): table overflowed";
if (err != 0) {
err_msg += ", when throwing exception, failed pthread_mutex_unlock()";
}
throw Exception(err_msg,
GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
}
m_table_value[m_table->curr_size] = value;
++m_table->curr_size;
}
err = pthread_mutex_unlock(&(m_table->lock));
if (err) {
throw Exception("ProfileTableImp::insert(): pthread_mutex_unlock()", err, __FILE__, __LINE__);
}
}
uint64_t ProfileTableImp::key(const std::string &name)
{
uint64_t result = 0;
int err = pthread_mutex_lock(&(m_key_map_lock));
if (err) {
throw Exception("ProfileTableImp::key(): pthread_mutex_lock()", err, __FILE__, __LINE__);
}
auto key_map_it = m_key_map.find(name);
err = pthread_mutex_unlock(&(m_key_map_lock));
if (err) {
throw Exception("ProfileTableImp::key(): pthread_mutex_unlock()", err, __FILE__, __LINE__);
}
if (key_map_it != m_key_map.end()) {
result = key_map_it->second;
}
else {
result = geopm_crc32_str((char *)(&name.front()));
if (GEOPM_REGION_HASH_INVALID == result) {
throw Exception("ProfileTableImp::key(): CRC 32 hashed to zero!", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
}
err = pthread_mutex_lock(&(m_key_map_lock));
if (err) {
throw Exception("ProfileTableImp::key(): pthread_mutex_lock()", err, __FILE__, __LINE__);
}
if (m_key_set.find(result) != m_key_set.end()) {
pthread_mutex_unlock(&(m_key_map_lock));
throw Exception("ProfileTableImp::key(): String hash collision", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
}
m_key_set.insert(result);
m_key_map.insert(std::pair<const std::string, uint64_t>(name, result));
m_key_map_last = m_key_map.begin();
err = pthread_mutex_unlock(&(m_key_map_lock));
if (err) {
throw Exception("ProfileTableImp::key(): pthread_mutex_unlock()", err, __FILE__, __LINE__);
}
}
return result;
}
size_t ProfileTableImp::capacity(void) const
{
return m_table->max_size;
}
size_t ProfileTableImp::size(void) const
{
size_t result = 0;
int err = pthread_mutex_lock(&(m_table->lock));
if (err) {
throw Exception("ProfileTableImp::size(): pthread_mutex_lock()", err, __FILE__, __LINE__);
}
result = m_table->curr_size;
err = pthread_mutex_unlock(&(m_table->lock));
if (err) {
throw Exception("ProfileTableImp::size(): pthread_mutex_unlock()", err, __FILE__, __LINE__);
}
return result;
}
void ProfileTableImp::dump(std::vector<std::pair<uint64_t, struct geopm_prof_message_s> >::iterator content, size_t &length)
{
int err;
err = pthread_mutex_lock(&(m_table->lock));
if (err) {
throw Exception("ProfileTableImp::dump(): pthread_mutex_lock()", err, __FILE__, __LINE__);
}
for (size_t depth = 0; depth != m_table->curr_size; ++depth) {
content->first = m_table_value[depth].region_id;
content->second = m_table_value[depth];
++content;
}
length = m_table->curr_size;
m_table->curr_size = 0;
err = pthread_mutex_unlock(&(m_table->lock));
if (err) {
throw Exception("ProfileTableImp::dump(): pthread_mutex_unlock()", err, __FILE__, __LINE__);
}
}
bool ProfileTableImp::name_fill(size_t header_offset)
{
bool result = false;
size_t buffer_remain = m_buffer_size - header_offset - 1;
char *buffer_ptr = (char *)m_table + header_offset;
while (m_key_map_last != m_key_map.end() &&
buffer_remain > m_key_map_last->first.length()) {
strncpy(buffer_ptr, m_key_map_last->first.c_str(), buffer_remain);
buffer_remain -= m_key_map_last->first.length() + 1;
buffer_ptr += m_key_map_last->first.length() + 1;
++m_key_map_last;
}
memset(buffer_ptr, 0, buffer_remain);
if (m_key_map_last == m_key_map.end() && buffer_remain) {
// We are done, set last character to '\1'
buffer_ptr[buffer_remain] = '\1';
m_key_map_last = m_key_map.begin();
result = true;
}
else {
buffer_ptr[buffer_remain] = '\0';
}
return result;
}
bool ProfileTableImp::name_set(size_t header_offset, std::set<std::string> &name)
{
// Check if last character is '\1' to see more names remain to be passed
bool result = (((char *)m_table)[m_buffer_size - 1] == '\1');
size_t buffer_remain = m_buffer_size - header_offset - 1;
char *buffer_ptr = (char *)m_table + header_offset;
while (buffer_remain) {
size_t name_len = strnlen(buffer_ptr, buffer_remain);
if (name_len == buffer_remain) {
throw Exception("ProfileTableImp::name_set(): buffer missing null termination", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
}
if (name_len) {
name.insert(std::string(buffer_ptr));
buffer_remain -= name_len + 1;
buffer_ptr += name_len + 1;
}
else {
buffer_remain = 0;
}
}
return result;
}
}
<|endoftext|> |
<commit_before>//===-- DWARFDebugInfoEntry.cpp --------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "DWARFDebugInfoEntry.h"
#include "DWARFCompileUnit.h"
#include "DWARFContext.h"
#include "DWARFDebugAbbrev.h"
#include "DWARFFormValue.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace dwarf;
void DWARFDebugInfoEntryMinimal::dump(raw_ostream &OS,
const DWARFCompileUnit *cu,
unsigned recurseDepth,
unsigned indent) const {
DataExtractor debug_info_data = cu->getDebugInfoExtractor();
uint32_t offset = Offset;
if (debug_info_data.isValidOffset(offset)) {
uint64_t abbrCode = debug_info_data.getULEB128(&offset);
OS.indent(indent) << format("\n0x%8.8x: ", Offset);
if (abbrCode) {
if (AbbrevDecl) {
OS << TagString(AbbrevDecl->getTag())
<< format(" [%u] %c\n", abbrCode,
AbbrevDecl->hasChildren() ? '*': ' ');
// Dump all data in the .debug_info for the attributes
const uint32_t numAttributes = AbbrevDecl->getNumAttributes();
for (uint32_t i = 0; i != numAttributes; ++i) {
uint16_t attr = AbbrevDecl->getAttrByIndex(i);
uint16_t form = AbbrevDecl->getFormByIndex(i);
dumpAttribute(OS, cu, &offset, attr, form, indent);
}
const DWARFDebugInfoEntryMinimal *child = getFirstChild();
if (recurseDepth > 0 && child) {
while (child) {
child->dump(OS, cu, recurseDepth-1, indent+2);
child = child->getSibling();
}
}
} else {
OS << "Abbreviation code not found in 'debug_abbrev' class for code: "
<< abbrCode << '\n';
}
} else {
OS << "NULL\n";
}
}
}
void DWARFDebugInfoEntryMinimal::dumpAttribute(raw_ostream &OS,
const DWARFCompileUnit *cu,
uint32_t* offset_ptr,
uint16_t attr,
uint16_t form,
unsigned indent) const {
OS.indent(indent) << format("0x%8.8x: ", *offset_ptr)
<< AttributeString(attr)
<< " [" << FormEncodingString(form) << ']';
DWARFFormValue formValue(form);
if (!formValue.extractValue(cu->getDebugInfoExtractor(), offset_ptr, cu))
return;
OS << "\t(";
formValue.dump(OS, 0, cu);
OS << ")\n";
}
bool DWARFDebugInfoEntryMinimal::extractFast(const DWARFCompileUnit *cu,
const uint8_t *fixed_form_sizes,
uint32_t *offset_ptr) {
Offset = *offset_ptr;
DataExtractor debug_info_data = cu->getDebugInfoExtractor();
uint64_t abbrCode = debug_info_data.getULEB128(offset_ptr);
assert (fixed_form_sizes); // For best performance this should be specified!
if (abbrCode) {
uint32_t offset = *offset_ptr;
AbbrevDecl = cu->getAbbreviations()->getAbbreviationDeclaration(abbrCode);
// Skip all data in the .debug_info for the attributes
const uint32_t numAttributes = AbbrevDecl->getNumAttributes();
uint32_t i;
uint16_t form;
for (i=0; i<numAttributes; ++i) {
form = AbbrevDecl->getFormByIndex(i);
const uint8_t fixed_skip_size = fixed_form_sizes[form];
if (fixed_skip_size)
offset += fixed_skip_size;
else {
bool form_is_indirect = false;
do {
form_is_indirect = false;
uint32_t form_size = 0;
switch (form) {
// Blocks if inlined data that have a length field and the data bytes
// inlined in the .debug_info.
case DW_FORM_block:
form_size = debug_info_data.getULEB128(&offset);
break;
case DW_FORM_block1:
form_size = debug_info_data.getU8(&offset);
break;
case DW_FORM_block2:
form_size = debug_info_data.getU16(&offset);
break;
case DW_FORM_block4:
form_size = debug_info_data.getU32(&offset);
break;
// Inlined NULL terminated C-strings
case DW_FORM_string:
debug_info_data.getCStr(&offset);
break;
// Compile unit address sized values
case DW_FORM_addr:
case DW_FORM_ref_addr:
form_size = cu->getAddressByteSize();
break;
// 1 byte values
case DW_FORM_data1:
case DW_FORM_flag:
case DW_FORM_ref1:
form_size = 1;
break;
// 2 byte values
case DW_FORM_data2:
case DW_FORM_ref2:
form_size = 2;
break;
// 4 byte values
case DW_FORM_strp:
case DW_FORM_data4:
case DW_FORM_ref4:
form_size = 4;
break;
// 8 byte values
case DW_FORM_data8:
case DW_FORM_ref8:
form_size = 8;
break;
// signed or unsigned LEB 128 values
case DW_FORM_sdata:
case DW_FORM_udata:
case DW_FORM_ref_udata:
debug_info_data.getULEB128(&offset);
break;
case DW_FORM_indirect:
form_is_indirect = true;
form = debug_info_data.getULEB128(&offset);
break;
default:
*offset_ptr = Offset;
return false;
}
offset += form_size;
} while (form_is_indirect);
}
}
*offset_ptr = offset;
return true;
} else {
AbbrevDecl = NULL;
return true; // NULL debug tag entry
}
return false;
}
bool
DWARFDebugInfoEntryMinimal::extract(const DWARFCompileUnit *cu,
uint32_t *offset_ptr) {
DataExtractor debug_info_data = cu->getDebugInfoExtractor();
const uint32_t cu_end_offset = cu->getNextCompileUnitOffset();
const uint8_t cu_addr_size = cu->getAddressByteSize();
uint32_t offset = *offset_ptr;
if ((offset < cu_end_offset) && debug_info_data.isValidOffset(offset)) {
Offset = offset;
uint64_t abbrCode = debug_info_data.getULEB128(&offset);
if (abbrCode) {
AbbrevDecl = cu->getAbbreviations()->getAbbreviationDeclaration(abbrCode);
if (AbbrevDecl) {
uint16_t tag = AbbrevDecl->getTag();
bool isCompileUnitTag = tag == DW_TAG_compile_unit;
if(cu && isCompileUnitTag)
const_cast<DWARFCompileUnit*>(cu)->setBaseAddress(0);
// Skip all data in the .debug_info for the attributes
const uint32_t numAttributes = AbbrevDecl->getNumAttributes();
for (uint32_t i = 0; i != numAttributes; ++i) {
uint16_t attr = AbbrevDecl->getAttrByIndex(i);
uint16_t form = AbbrevDecl->getFormByIndex(i);
if (isCompileUnitTag &&
((attr == DW_AT_entry_pc) || (attr == DW_AT_low_pc))) {
DWARFFormValue form_value(form);
if (form_value.extractValue(debug_info_data, &offset, cu)) {
if (attr == DW_AT_low_pc || attr == DW_AT_entry_pc)
const_cast<DWARFCompileUnit*>(cu)
->setBaseAddress(form_value.getUnsigned());
}
} else {
bool form_is_indirect = false;
do {
form_is_indirect = false;
register uint32_t form_size = 0;
switch (form) {
// Blocks if inlined data that have a length field and the data
// bytes // inlined in the .debug_info
case DW_FORM_block:
form_size = debug_info_data.getULEB128(&offset);
break;
case DW_FORM_block1:
form_size = debug_info_data.getU8(&offset);
break;
case DW_FORM_block2:
form_size = debug_info_data.getU16(&offset);
break;
case DW_FORM_block4:
form_size = debug_info_data.getU32(&offset);
break;
// Inlined NULL terminated C-strings
case DW_FORM_string:
debug_info_data.getCStr(&offset);
break;
// Compile unit address sized values
case DW_FORM_addr:
case DW_FORM_ref_addr:
form_size = cu_addr_size;
break;
// 1 byte values
case DW_FORM_data1:
case DW_FORM_flag:
case DW_FORM_ref1:
form_size = 1;
break;
// 2 byte values
case DW_FORM_data2:
case DW_FORM_ref2:
form_size = 2;
break;
// 4 byte values
case DW_FORM_strp:
form_size = 4;
break;
case DW_FORM_data4:
case DW_FORM_ref4:
form_size = 4;
break;
// 8 byte values
case DW_FORM_data8:
case DW_FORM_ref8:
form_size = 8;
break;
// signed or unsigned LEB 128 values
case DW_FORM_sdata:
case DW_FORM_udata:
case DW_FORM_ref_udata:
debug_info_data.getULEB128(&offset);
break;
case DW_FORM_indirect:
form = debug_info_data.getULEB128(&offset);
form_is_indirect = true;
break;
default:
*offset_ptr = offset;
return false;
}
offset += form_size;
} while (form_is_indirect);
}
}
*offset_ptr = offset;
return true;
}
} else {
AbbrevDecl = NULL;
*offset_ptr = offset;
return true; // NULL debug tag entry
}
}
return false;
}
uint32_t
DWARFDebugInfoEntryMinimal::getAttributeValue(const DWARFCompileUnit *cu,
const uint16_t attr,
DWARFFormValue &form_value,
uint32_t *end_attr_offset_ptr)
const {
if (AbbrevDecl) {
uint32_t attr_idx = AbbrevDecl->findAttributeIndex(attr);
if (attr_idx != -1U) {
uint32_t offset = getOffset();
DataExtractor debug_info_data = cu->getDebugInfoExtractor();
// Skip the abbreviation code so we are at the data for the attributes
debug_info_data.getULEB128(&offset);
uint32_t idx = 0;
while (idx < attr_idx)
DWARFFormValue::skipValue(AbbrevDecl->getFormByIndex(idx++),
debug_info_data, &offset, cu);
const uint32_t attr_offset = offset;
form_value = DWARFFormValue(AbbrevDecl->getFormByIndex(idx));
if (form_value.extractValue(debug_info_data, &offset, cu)) {
if (end_attr_offset_ptr)
*end_attr_offset_ptr = offset;
return attr_offset;
}
}
}
return 0;
}
const char*
DWARFDebugInfoEntryMinimal::getAttributeValueAsString(
const DWARFCompileUnit* cu,
const uint16_t attr,
const char* fail_value) const {
DWARFFormValue form_value;
if (getAttributeValue(cu, attr, form_value)) {
DataExtractor stringExtractor(cu->getContext().getStringSection(),
false, 0);
return form_value.getAsCString(&stringExtractor);
}
return fail_value;
}
uint64_t
DWARFDebugInfoEntryMinimal::getAttributeValueAsUnsigned(
const DWARFCompileUnit* cu,
const uint16_t attr,
uint64_t fail_value) const {
DWARFFormValue form_value;
if (getAttributeValue(cu, attr, form_value))
return form_value.getUnsigned();
return fail_value;
}
int64_t
DWARFDebugInfoEntryMinimal::getAttributeValueAsSigned(
const DWARFCompileUnit* cu,
const uint16_t attr,
int64_t fail_value) const {
DWARFFormValue form_value;
if (getAttributeValue(cu, attr, form_value))
return form_value.getSigned();
return fail_value;
}
uint64_t
DWARFDebugInfoEntryMinimal::getAttributeValueAsReference(const DWARFCompileUnit* cu,
const uint16_t attr,
uint64_t fail_value) const {
DWARFFormValue form_value;
if (getAttributeValue(cu, attr, form_value))
return form_value.getReference(cu);
return fail_value;
}
<commit_msg>DWARF: Improve indentation of DIE dumping so it's easier to see the structure.<commit_after>//===-- DWARFDebugInfoEntry.cpp --------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "DWARFDebugInfoEntry.h"
#include "DWARFCompileUnit.h"
#include "DWARFContext.h"
#include "DWARFDebugAbbrev.h"
#include "DWARFFormValue.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace dwarf;
void DWARFDebugInfoEntryMinimal::dump(raw_ostream &OS,
const DWARFCompileUnit *cu,
unsigned recurseDepth,
unsigned indent) const {
DataExtractor debug_info_data = cu->getDebugInfoExtractor();
uint32_t offset = Offset;
if (debug_info_data.isValidOffset(offset)) {
uint64_t abbrCode = debug_info_data.getULEB128(&offset);
OS << format("\n0x%8.8x: ", Offset);
if (abbrCode) {
if (AbbrevDecl) {
OS.indent(indent) << TagString(AbbrevDecl->getTag())
<< format(" [%u] %c\n", abbrCode,
AbbrevDecl->hasChildren() ? '*': ' ');
// Dump all data in the .debug_info for the attributes
const uint32_t numAttributes = AbbrevDecl->getNumAttributes();
for (uint32_t i = 0; i != numAttributes; ++i) {
uint16_t attr = AbbrevDecl->getAttrByIndex(i);
uint16_t form = AbbrevDecl->getFormByIndex(i);
dumpAttribute(OS, cu, &offset, attr, form, indent);
}
const DWARFDebugInfoEntryMinimal *child = getFirstChild();
if (recurseDepth > 0 && child) {
while (child) {
child->dump(OS, cu, recurseDepth-1, indent+2);
child = child->getSibling();
}
}
} else {
OS << "Abbreviation code not found in 'debug_abbrev' class for code: "
<< abbrCode << '\n';
}
} else {
OS.indent(indent) << "NULL\n";
}
}
}
void DWARFDebugInfoEntryMinimal::dumpAttribute(raw_ostream &OS,
const DWARFCompileUnit *cu,
uint32_t* offset_ptr,
uint16_t attr,
uint16_t form,
unsigned indent) const {
OS << format("0x%8.8x: ", *offset_ptr);
OS.indent(indent+2) << AttributeString(attr)
<< " [" << FormEncodingString(form) << ']';
DWARFFormValue formValue(form);
if (!formValue.extractValue(cu->getDebugInfoExtractor(), offset_ptr, cu))
return;
OS << "\t(";
formValue.dump(OS, 0, cu);
OS << ")\n";
}
bool DWARFDebugInfoEntryMinimal::extractFast(const DWARFCompileUnit *cu,
const uint8_t *fixed_form_sizes,
uint32_t *offset_ptr) {
Offset = *offset_ptr;
DataExtractor debug_info_data = cu->getDebugInfoExtractor();
uint64_t abbrCode = debug_info_data.getULEB128(offset_ptr);
assert (fixed_form_sizes); // For best performance this should be specified!
if (abbrCode) {
uint32_t offset = *offset_ptr;
AbbrevDecl = cu->getAbbreviations()->getAbbreviationDeclaration(abbrCode);
// Skip all data in the .debug_info for the attributes
const uint32_t numAttributes = AbbrevDecl->getNumAttributes();
uint32_t i;
uint16_t form;
for (i=0; i<numAttributes; ++i) {
form = AbbrevDecl->getFormByIndex(i);
const uint8_t fixed_skip_size = fixed_form_sizes[form];
if (fixed_skip_size)
offset += fixed_skip_size;
else {
bool form_is_indirect = false;
do {
form_is_indirect = false;
uint32_t form_size = 0;
switch (form) {
// Blocks if inlined data that have a length field and the data bytes
// inlined in the .debug_info.
case DW_FORM_block:
form_size = debug_info_data.getULEB128(&offset);
break;
case DW_FORM_block1:
form_size = debug_info_data.getU8(&offset);
break;
case DW_FORM_block2:
form_size = debug_info_data.getU16(&offset);
break;
case DW_FORM_block4:
form_size = debug_info_data.getU32(&offset);
break;
// Inlined NULL terminated C-strings
case DW_FORM_string:
debug_info_data.getCStr(&offset);
break;
// Compile unit address sized values
case DW_FORM_addr:
case DW_FORM_ref_addr:
form_size = cu->getAddressByteSize();
break;
// 1 byte values
case DW_FORM_data1:
case DW_FORM_flag:
case DW_FORM_ref1:
form_size = 1;
break;
// 2 byte values
case DW_FORM_data2:
case DW_FORM_ref2:
form_size = 2;
break;
// 4 byte values
case DW_FORM_strp:
case DW_FORM_data4:
case DW_FORM_ref4:
form_size = 4;
break;
// 8 byte values
case DW_FORM_data8:
case DW_FORM_ref8:
form_size = 8;
break;
// signed or unsigned LEB 128 values
case DW_FORM_sdata:
case DW_FORM_udata:
case DW_FORM_ref_udata:
debug_info_data.getULEB128(&offset);
break;
case DW_FORM_indirect:
form_is_indirect = true;
form = debug_info_data.getULEB128(&offset);
break;
default:
*offset_ptr = Offset;
return false;
}
offset += form_size;
} while (form_is_indirect);
}
}
*offset_ptr = offset;
return true;
} else {
AbbrevDecl = NULL;
return true; // NULL debug tag entry
}
return false;
}
bool
DWARFDebugInfoEntryMinimal::extract(const DWARFCompileUnit *cu,
uint32_t *offset_ptr) {
DataExtractor debug_info_data = cu->getDebugInfoExtractor();
const uint32_t cu_end_offset = cu->getNextCompileUnitOffset();
const uint8_t cu_addr_size = cu->getAddressByteSize();
uint32_t offset = *offset_ptr;
if ((offset < cu_end_offset) && debug_info_data.isValidOffset(offset)) {
Offset = offset;
uint64_t abbrCode = debug_info_data.getULEB128(&offset);
if (abbrCode) {
AbbrevDecl = cu->getAbbreviations()->getAbbreviationDeclaration(abbrCode);
if (AbbrevDecl) {
uint16_t tag = AbbrevDecl->getTag();
bool isCompileUnitTag = tag == DW_TAG_compile_unit;
if(cu && isCompileUnitTag)
const_cast<DWARFCompileUnit*>(cu)->setBaseAddress(0);
// Skip all data in the .debug_info for the attributes
const uint32_t numAttributes = AbbrevDecl->getNumAttributes();
for (uint32_t i = 0; i != numAttributes; ++i) {
uint16_t attr = AbbrevDecl->getAttrByIndex(i);
uint16_t form = AbbrevDecl->getFormByIndex(i);
if (isCompileUnitTag &&
((attr == DW_AT_entry_pc) || (attr == DW_AT_low_pc))) {
DWARFFormValue form_value(form);
if (form_value.extractValue(debug_info_data, &offset, cu)) {
if (attr == DW_AT_low_pc || attr == DW_AT_entry_pc)
const_cast<DWARFCompileUnit*>(cu)
->setBaseAddress(form_value.getUnsigned());
}
} else {
bool form_is_indirect = false;
do {
form_is_indirect = false;
register uint32_t form_size = 0;
switch (form) {
// Blocks if inlined data that have a length field and the data
// bytes // inlined in the .debug_info
case DW_FORM_block:
form_size = debug_info_data.getULEB128(&offset);
break;
case DW_FORM_block1:
form_size = debug_info_data.getU8(&offset);
break;
case DW_FORM_block2:
form_size = debug_info_data.getU16(&offset);
break;
case DW_FORM_block4:
form_size = debug_info_data.getU32(&offset);
break;
// Inlined NULL terminated C-strings
case DW_FORM_string:
debug_info_data.getCStr(&offset);
break;
// Compile unit address sized values
case DW_FORM_addr:
case DW_FORM_ref_addr:
form_size = cu_addr_size;
break;
// 1 byte values
case DW_FORM_data1:
case DW_FORM_flag:
case DW_FORM_ref1:
form_size = 1;
break;
// 2 byte values
case DW_FORM_data2:
case DW_FORM_ref2:
form_size = 2;
break;
// 4 byte values
case DW_FORM_strp:
form_size = 4;
break;
case DW_FORM_data4:
case DW_FORM_ref4:
form_size = 4;
break;
// 8 byte values
case DW_FORM_data8:
case DW_FORM_ref8:
form_size = 8;
break;
// signed or unsigned LEB 128 values
case DW_FORM_sdata:
case DW_FORM_udata:
case DW_FORM_ref_udata:
debug_info_data.getULEB128(&offset);
break;
case DW_FORM_indirect:
form = debug_info_data.getULEB128(&offset);
form_is_indirect = true;
break;
default:
*offset_ptr = offset;
return false;
}
offset += form_size;
} while (form_is_indirect);
}
}
*offset_ptr = offset;
return true;
}
} else {
AbbrevDecl = NULL;
*offset_ptr = offset;
return true; // NULL debug tag entry
}
}
return false;
}
uint32_t
DWARFDebugInfoEntryMinimal::getAttributeValue(const DWARFCompileUnit *cu,
const uint16_t attr,
DWARFFormValue &form_value,
uint32_t *end_attr_offset_ptr)
const {
if (AbbrevDecl) {
uint32_t attr_idx = AbbrevDecl->findAttributeIndex(attr);
if (attr_idx != -1U) {
uint32_t offset = getOffset();
DataExtractor debug_info_data = cu->getDebugInfoExtractor();
// Skip the abbreviation code so we are at the data for the attributes
debug_info_data.getULEB128(&offset);
uint32_t idx = 0;
while (idx < attr_idx)
DWARFFormValue::skipValue(AbbrevDecl->getFormByIndex(idx++),
debug_info_data, &offset, cu);
const uint32_t attr_offset = offset;
form_value = DWARFFormValue(AbbrevDecl->getFormByIndex(idx));
if (form_value.extractValue(debug_info_data, &offset, cu)) {
if (end_attr_offset_ptr)
*end_attr_offset_ptr = offset;
return attr_offset;
}
}
}
return 0;
}
const char*
DWARFDebugInfoEntryMinimal::getAttributeValueAsString(
const DWARFCompileUnit* cu,
const uint16_t attr,
const char* fail_value) const {
DWARFFormValue form_value;
if (getAttributeValue(cu, attr, form_value)) {
DataExtractor stringExtractor(cu->getContext().getStringSection(),
false, 0);
return form_value.getAsCString(&stringExtractor);
}
return fail_value;
}
uint64_t
DWARFDebugInfoEntryMinimal::getAttributeValueAsUnsigned(
const DWARFCompileUnit* cu,
const uint16_t attr,
uint64_t fail_value) const {
DWARFFormValue form_value;
if (getAttributeValue(cu, attr, form_value))
return form_value.getUnsigned();
return fail_value;
}
int64_t
DWARFDebugInfoEntryMinimal::getAttributeValueAsSigned(
const DWARFCompileUnit* cu,
const uint16_t attr,
int64_t fail_value) const {
DWARFFormValue form_value;
if (getAttributeValue(cu, attr, form_value))
return form_value.getSigned();
return fail_value;
}
uint64_t
DWARFDebugInfoEntryMinimal::getAttributeValueAsReference(const DWARFCompileUnit* cu,
const uint16_t attr,
uint64_t fail_value) const {
DWARFFormValue form_value;
if (getAttributeValue(cu, attr, form_value))
return form_value.getReference(cu);
return fail_value;
}
<|endoftext|> |
<commit_before>#include <ncurses.h>
#include "../../../src/configuration.hh"
#include "../../../src/concat_c.hh"
#include "../../../src/contents.hh"
#include "../../../src/key_aliases.hh"
#include "../../../src/show_message.hh"
#include "../../vick-move/src/move.hh"
namespace vick {
namespace insert_mode {
struct insert_c : public change {
const std::string track;
const move_t y, x;
insert_c(const std::string& track, move_t y, move_t x)
: track(track)
, y(y)
, x(x)
{
}
virtual bool is_overriding() override { return true; }
virtual void undo(contents& contents) override
{
contents.cont[y] = contents.cont[y].substr(0, x) +
contents.cont[y].substr(x + track.size());
contents.y = y;
contents.x = x;
if (contents.x && contents.x >= contents.cont[y].size())
contents.x = contents.cont[y].size() - 1;
}
virtual void redo(contents& contents) override
{
contents.cont[y] =
contents.cont[y].substr(0, x) + track + contents.cont[y].substr(x);
contents.y = y;
contents.x = x + track.size();
if (contents.x >= contents.cont[y].size())
contents.x = contents.cont[y].size() - 1;
}
virtual std::shared_ptr<change>
regenerate(const contents& contents) const override
{
return std::make_shared<insert_c>(track, contents.y, contents.x);
}
};
struct newline_c : public change {
const std::string first, second;
const int y;
newline_c(const contents& contents)
: first(contents.cont[contents.y].substr(0, contents.x))
, second(contents.cont[contents.y].substr(contents.x))
, y(contents.y)
{
}
virtual bool is_overriding() { return true; }
virtual void undo(contents& contents)
{
contents.cont[y] = first + second;
contents.cont.erase(contents.cont.begin() + y + 1);
contents.y = y;
contents.x = first.size();
}
virtual void redo(contents& contents)
{
contents.cont[y] = first;
contents.cont.insert(contents.cont.begin() + y + 1, second);
contents.y = y + 1;
contents.x = 0;
}
virtual std::shared_ptr<change> regenerate(const contents& contents) const
{
return std::make_shared<newline_c>(contents);
}
};
boost::optional<std::shared_ptr<change> >
enter_insert_mode(contents& contents, boost::optional<int> pref)
{
std::string track;
auto x = contents.x;
char ch;
show_message("--INSERT--");
contents.is_inserting = true;
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT--");
}
while ((ch = getch()) != QUIT_KEY) {
if (ch == '\n') {
std::vector<std::shared_ptr<change> > changes;
changes.reserve(3);
if (track.size())
changes.push_back(
std::make_shared<insert_c>(track, contents.y, x));
changes.push_back(std::make_shared<newline_c>(contents));
changes.back()->redo(contents);
auto recursed = enter_insert_mode(contents, pref);
if (recursed) changes.push_back(recursed.get());
return boost::optional<std::shared_ptr<change> >(
std::make_shared<concat_c>(changes));
}
if (contents.x >= contents.cont[contents.y].size()) {
contents.cont[contents.y].push_back(ch);
contents.x = contents.cont[contents.y].size();
track += ch;
}
else {
contents.cont[contents.y].insert(contents.x, 1, ch);
contents.x++;
track += ch;
}
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT--");
}
}
contents.is_inserting = false;
showing_message = false;
return boost::optional<std::shared_ptr<change> >(
std::make_shared<insert_c>(track, contents.y, x));
}
struct replace_c : public change {
const std::string o, n;
const move_t y, x;
replace_c(const std::string& o, const std::string& n, move_t y, move_t x)
: o(o)
, n(n)
, y(y)
, x(x)
{
}
virtual bool is_overriding() override { return true; }
virtual void undo(contents& contents) override
{
contents.cont[y] = contents.cont[y].substr(0, x) + o +
contents.cont[y].substr(x + o.size());
}
virtual void redo(contents& contents) override
{
contents.cont[y] = contents.cont[y].substr(0, x) + n +
contents.cont[y].substr(x + n.size());
}
virtual std::shared_ptr<change>
regenerate(const contents& contents) const override
{
return std::make_shared<replace_c>(
contents.cont[contents.y].substr(contents.x, n.size()), n,
contents.y, contents.x);
}
};
boost::optional<std::shared_ptr<change> >
enter_replace_mode(contents& contents, boost::optional<int> pref)
{
std::string o, n;
auto x = contents.x;
char ch;
show_message("--INSERT (REPLACE)--");
contents.is_inserting = true;
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT (REPLACE)--");
}
while ((ch = getch()) != QUIT_KEY) {
if (ch == '\n') {
o = contents.cont[contents.y][contents.x];
std::vector<std::shared_ptr<change> > changes;
changes.reserve(3);
if (o.size())
changes.push_back(
std::make_shared<replace_c>(o, n, contents.y, x));
changes.push_back(std::make_shared<newline_c>(contents));
changes.back()->redo(contents);
auto recursed = enter_replace_mode(contents, pref);
if (recursed) changes.push_back(recursed.get());
return boost::optional<std::shared_ptr<change> >(
std::make_shared<concat_c>(changes));
}
if (contents.x >= contents.cont[contents.y].size()) {
contents.cont[contents.y].push_back(ch);
contents.x = contents.cont[contents.y].size();
n += ch;
}
else {
o += contents.cont[contents.y][contents.x];
n += ch;
contents.cont[contents.y][contents.x] = ch;
contents.x++;
}
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT (REPLACE)--");
}
}
contents.is_inserting = false;
showing_message = false;
return boost::optional<std::shared_ptr<change> >(
std::make_shared<replace_c>(o, n, contents.y, x));
}
struct append_c : public change {
const std::string track;
const move_t y, x;
append_c(const std::string& track, move_t y, move_t x)
: track(track)
, y(y)
, x(x)
{
}
virtual bool is_overriding() override { return true; }
virtual void undo(contents& contents) override
{
contents.cont[y] = contents.cont[y].substr(0, x) +
contents.cont[y].substr(x + track.size());
contents.y = y;
contents.x = x;
if (contents.x && contents.x >= contents.cont[y].size())
contents.x = contents.cont[y].size() - 1;
}
virtual void redo(contents& contents) override
{
contents.cont[y] =
contents.cont[y].substr(0, x) + track + contents.cont[y].substr(x);
contents.y = y;
contents.x = x + track.size();
if (contents.x >= contents.cont[y].size())
contents.x = contents.cont[y].size() - 1;
}
virtual std::shared_ptr<change>
regenerate(const contents& contents) const override
{
return std::make_shared<append_c>(track, contents.y, contents.x + 1);
}
};
boost::optional<std::shared_ptr<change> >
enter_append_mode(contents& contents, boost::optional<int> pref)
{
if (contents.cont[contents.y].size() == 0)
return enter_insert_mode(contents, pref);
contents.x++;
std::string track;
auto x = contents.x;
char ch;
show_message("--INSERT--");
contents.is_inserting = true;
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT--");
}
while ((ch = getch()) != QUIT_KEY) {
if (ch == '\n') {
std::vector<std::shared_ptr<change> > changes;
changes.reserve(3);
if (track.size())
changes.push_back(
std::make_shared<insert_c>(track, contents.y, x));
changes.push_back(std::make_shared<newline_c>(contents));
changes.back()->redo(contents);
auto recursed = enter_insert_mode(contents, pref);
if (recursed) changes.push_back(recursed.get());
return boost::optional<std::shared_ptr<change> >(
std::make_shared<concat_c>(changes));
}
if (contents.x >= contents.cont[contents.y].size()) {
contents.cont[contents.y].push_back(ch);
contents.x = contents.cont[contents.y].size();
track += ch;
}
else {
contents.cont[contents.y].insert(contents.x, 1, ch);
contents.x++;
track += ch;
}
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT--");
}
}
contents.is_inserting = false;
showing_message = false;
return boost::optional<std::shared_ptr<change> >(
std::make_shared<append_c>(track, contents.y, x));
}
}
}
<commit_msg>Make the prompt yn functions return optional<bool>, and make function that will repeat until actual value.<commit_after>#include <ncurses.h>
#include "../../../src/configuration.hh"
#include "../../../src/concat_c.hh"
#include "../../../src/contents.hh"
#include "../../../src/key_aliases.hh"
#include "../../../src/show_message.hh"
#include "../../vick-move/src/move.hh"
namespace vick {
namespace insert_mode {
struct insert_c : public change {
const std::string track;
const move_t y, x;
insert_c(const std::string& track, move_t y, move_t x)
: track(track)
, y(y)
, x(x)
{
}
virtual bool is_overriding() override { return true; }
virtual void undo(contents& contents) override
{
contents.cont[y] = contents.cont[y].substr(0, x) +
contents.cont[y].substr(x + track.size());
contents.y = y;
contents.x = x;
if (contents.x and contents.x >= contents.cont[y].size())
contents.x = contents.cont[y].size() - 1;
}
virtual void redo(contents& contents) override
{
contents.cont[y] =
contents.cont[y].substr(0, x) + track + contents.cont[y].substr(x);
contents.y = y;
contents.x = x + track.size();
if (contents.x >= contents.cont[y].size())
contents.x = contents.cont[y].size() - 1;
}
virtual std::shared_ptr<change>
regenerate(const contents& contents) const override
{
return std::make_shared<insert_c>(track, contents.y, contents.x);
}
};
struct newline_c : public change {
const std::string first, second;
const int y;
newline_c(const contents& contents)
: first(contents.cont[contents.y].substr(0, contents.x))
, second(contents.cont[contents.y].substr(contents.x))
, y(contents.y)
{
}
virtual bool is_overriding() { return true; }
virtual void undo(contents& contents)
{
contents.cont[y] = first + second;
contents.cont.erase(contents.cont.begin() + y + 1);
contents.y = y;
contents.x = first.size();
}
virtual void redo(contents& contents)
{
contents.cont[y] = first;
contents.cont.insert(contents.cont.begin() + y + 1, second);
contents.y = y + 1;
contents.x = 0;
}
virtual std::shared_ptr<change> regenerate(const contents& contents) const
{
return std::make_shared<newline_c>(contents);
}
};
boost::optional<std::shared_ptr<change> >
enter_insert_mode(contents& contents, boost::optional<int> pref)
{
std::string track;
auto x = contents.x;
char ch;
show_message("--INSERT--");
contents.is_inserting = true;
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT--");
}
while ((ch = getch()) != QUIT_KEY) {
if (ch == '\n') {
std::vector<std::shared_ptr<change> > changes;
changes.reserve(3);
if (track.size())
changes.push_back(
std::make_shared<insert_c>(track, contents.y, x));
changes.push_back(std::make_shared<newline_c>(contents));
changes.back()->redo(contents);
auto recursed = enter_insert_mode(contents, pref);
if (recursed) changes.push_back(recursed.get());
return boost::optional<std::shared_ptr<change> >(
std::make_shared<concat_c>(changes));
}
if (contents.x >= contents.cont[contents.y].size()) {
contents.cont[contents.y].push_back(ch);
contents.x = contents.cont[contents.y].size();
track += ch;
}
else {
contents.cont[contents.y].insert(contents.x, 1, ch);
contents.x++;
track += ch;
}
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT--");
}
}
contents.is_inserting = false;
showing_message = false;
return boost::optional<std::shared_ptr<change> >(
std::make_shared<insert_c>(track, contents.y, x));
}
struct replace_c : public change {
const std::string o, n;
const move_t y, x;
replace_c(const std::string& o, const std::string& n, move_t y, move_t x)
: o(o)
, n(n)
, y(y)
, x(x)
{
}
virtual bool is_overriding() override { return true; }
virtual void undo(contents& contents) override
{
contents.cont[y] = contents.cont[y].substr(0, x) + o +
contents.cont[y].substr(x + o.size());
}
virtual void redo(contents& contents) override
{
contents.cont[y] = contents.cont[y].substr(0, x) + n +
contents.cont[y].substr(x + n.size());
}
virtual std::shared_ptr<change>
regenerate(const contents& contents) const override
{
return std::make_shared<replace_c>(
contents.cont[contents.y].substr(contents.x, n.size()), n,
contents.y, contents.x);
}
};
boost::optional<std::shared_ptr<change> >
enter_replace_mode(contents& contents, boost::optional<int> pref)
{
std::string o, n;
auto x = contents.x;
char ch;
show_message("--INSERT (REPLACE)--");
contents.is_inserting = true;
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT (REPLACE)--");
}
while ((ch = getch()) != QUIT_KEY) {
if (ch == '\n') {
o = contents.cont[contents.y][contents.x];
std::vector<std::shared_ptr<change> > changes;
changes.reserve(3);
if (o.size())
changes.push_back(
std::make_shared<replace_c>(o, n, contents.y, x));
changes.push_back(std::make_shared<newline_c>(contents));
changes.back()->redo(contents);
auto recursed = enter_replace_mode(contents, pref);
if (recursed) changes.push_back(recursed.get());
return boost::optional<std::shared_ptr<change> >(
std::make_shared<concat_c>(changes));
}
if (contents.x >= contents.cont[contents.y].size()) {
contents.cont[contents.y].push_back(ch);
contents.x = contents.cont[contents.y].size();
n += ch;
}
else {
o += contents.cont[contents.y][contents.x];
n += ch;
contents.cont[contents.y][contents.x] = ch;
contents.x++;
}
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT (REPLACE)--");
}
}
contents.is_inserting = false;
showing_message = false;
return boost::optional<std::shared_ptr<change> >(
std::make_shared<replace_c>(o, n, contents.y, x));
}
struct append_c : public change {
const std::string track;
const move_t y, x;
append_c(const std::string& track, move_t y, move_t x)
: track(track)
, y(y)
, x(x)
{
}
virtual bool is_overriding() override { return true; }
virtual void undo(contents& contents) override
{
contents.cont[y] = contents.cont[y].substr(0, x) +
contents.cont[y].substr(x + track.size());
contents.y = y;
contents.x = x;
if (contents.x and contents.x >= contents.cont[y].size())
contents.x = contents.cont[y].size() - 1;
}
virtual void redo(contents& contents) override
{
contents.cont[y] =
contents.cont[y].substr(0, x) + track + contents.cont[y].substr(x);
contents.y = y;
contents.x = x + track.size();
if (contents.x >= contents.cont[y].size())
contents.x = contents.cont[y].size() - 1;
}
virtual std::shared_ptr<change>
regenerate(const contents& contents) const override
{
return std::make_shared<append_c>(track, contents.y, contents.x + 1);
}
};
boost::optional<std::shared_ptr<change> >
enter_append_mode(contents& contents, boost::optional<int> pref)
{
if (contents.cont[contents.y].size() == 0)
return enter_insert_mode(contents, pref);
contents.x++;
std::string track;
auto x = contents.x;
char ch;
show_message("--INSERT--");
contents.is_inserting = true;
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT--");
}
while ((ch = getch()) != QUIT_KEY) {
if (ch == '\n') {
std::vector<std::shared_ptr<change> > changes;
changes.reserve(3);
if (track.size())
changes.push_back(
std::make_shared<insert_c>(track, contents.y, x));
changes.push_back(std::make_shared<newline_c>(contents));
changes.back()->redo(contents);
auto recursed = enter_insert_mode(contents, pref);
if (recursed) changes.push_back(recursed.get());
return boost::optional<std::shared_ptr<change> >(
std::make_shared<concat_c>(changes));
}
if (contents.x >= contents.cont[contents.y].size()) {
contents.cont[contents.y].push_back(ch);
contents.x = contents.cont[contents.y].size();
track += ch;
}
else {
contents.cont[contents.y].insert(contents.x, 1, ch);
contents.x++;
track += ch;
}
if (get_contents().refresh) {
print_contents(get_contents());
show_message("--INSERT--");
}
}
contents.is_inserting = false;
showing_message = false;
return boost::optional<std::shared_ptr<change> >(
std::make_shared<append_c>(track, contents.y, x));
}
}
}
<|endoftext|> |
<commit_before>#include "../../../src/contents.hh"
void enter_insert_mode (contents&, boost::optional<int> = boost::none);
void enter_replace_mode(contents&, boost::optional<int> = boost::none);
void enter_append_mode (contents&, boost::optional<int> = boost::none);
<commit_msg>Add documentation to header<commit_after>#include "../../../src/contents.hh"
/*!
* \file insert_mode.hh
* \brief Basic commands that have to do with inserting text into the buffer
*
* These commands all rely on `global_insert_map` to dictate what keys
* do special things.
*
* \see enter_insert_mode
* \see enter_replace_mode
* \see enter_append_mode
* \see global_insert_map
*/
/*!
* \brief Enters insert mode and prompts for user input continually
*
* Keys pressed are governed against `global_insert_map` before being
* inserted raw
*
* EVERYTHING that happens in insert mode counts as one edit
*
* \see global_insert_map
*/
void enter_insert_mode (contents&, boost::optional<int> = boost::none);
/*!
* \brief Similar to insert mode but overrides text
*
* Enter replace mode, a subgenre of insert mode. Instead of
* inserting text, you replace the text at the cursor (or append text
* if already replaced last character in line).
*
* Keys pressed are governed against `global_insert_map` before being
* inserted raw
*
* EVERYTHING that happens in replace mode counts as one edit
*
* \see enter_insert_mode()
* \see global_insert_map
*/
void enter_replace_mode(contents&, boost::optional<int> = boost::none);
/*!
* \brief Moves forward a character then enters insert mode
*
* EVERYTHING that happens in insert mode counts as one edit
*
* \see enter_insert_mode()
* \see global_insert_map
*/
void enter_append_mode (contents&, boost::optional<int> = boost::none);
<|endoftext|> |
<commit_before>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// author: Elisavet Sakellari <[email protected]>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "ExternalInterpreterSource.h"
#include "cling/Interpreter/Interpreter.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTImporter.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/Sema.h"
using namespace clang;
namespace {
class ClingASTImporter : public ASTImporter {
private:
cling::ExternalInterpreterSource &m_Source;
public:
ClingASTImporter(ASTContext &ToContext, FileManager &ToFileManager,
ASTContext &FromContext, FileManager &FromFileManager,
bool MinimalImport,
cling::ExternalInterpreterSource& source):
ASTImporter(ToContext, ToFileManager, FromContext, FromFileManager,
MinimalImport), m_Source(source) {}
virtual ~ClingASTImporter() = default;
Decl *Imported(Decl *From, Decl *To) override {
ASTImporter::Imported(From, To);
if (clang::TagDecl* toTagDecl = dyn_cast<TagDecl>(To)) {
toTagDecl->setHasExternalLexicalStorage();
toTagDecl->setMustBuildLookupTable();
toTagDecl->setHasExternalVisibleStorage();
}
if (NamespaceDecl *toNamespaceDecl = dyn_cast<NamespaceDecl>(To)) {
toNamespaceDecl->setHasExternalVisibleStorage();
}
if (ObjCContainerDecl *toContainerDecl = dyn_cast<ObjCContainerDecl>(To)) {
toContainerDecl->setHasExternalLexicalStorage();
toContainerDecl->setHasExternalVisibleStorage();
}
// Put the name of the Decl imported with the
// DeclarationName coming from the parent, in my map.
if (NamedDecl *toNamedDecl = llvm::dyn_cast<NamedDecl>(To)) {
NamedDecl *fromNamedDecl = llvm::dyn_cast<NamedDecl>(From);
m_Source.addToImportedDecls(toNamedDecl->getDeclName(),
fromNamedDecl->getDeclName());
}
if (DeclContext *toDeclContext = llvm::dyn_cast<DeclContext>(To)) {
DeclContext *fromDeclContext = llvm::dyn_cast<DeclContext>(From);
m_Source.addToImportedDeclContexts(toDeclContext, fromDeclContext);
}
return To;
}
};
}
namespace cling {
ExternalInterpreterSource::ExternalInterpreterSource(
const cling::Interpreter *parent, cling::Interpreter *child) :
m_ParentInterpreter(parent), m_ChildInterpreter(child) {
clang::DeclContext *parentTUDeclContext =
m_ParentInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
clang::DeclContext *childTUDeclContext =
m_ChildInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
// Also keep in the map of Decl Contexts the Translation Unit Decl Context
m_ImportedDeclContexts[childTUDeclContext] = parentTUDeclContext;
FileManager &childFM = m_ChildInterpreter->getCI()->getFileManager();
FileManager &parentFM = m_ParentInterpreter->getCI()->getFileManager();
ASTContext &fromASTContext = m_ParentInterpreter->getCI()->getASTContext();
ASTContext &toASTContext = m_ChildInterpreter->getCI()->getASTContext();
ClingASTImporter* importer
= new ClingASTImporter(toASTContext, childFM, fromASTContext, parentFM,
/*MinimalImport : ON*/ true, *this);
m_Importer.reset(llvm::dyn_cast<ASTImporter>(importer));
}
ExternalInterpreterSource::~ExternalInterpreterSource() {}
void ExternalInterpreterSource::ImportDecl(Decl *declToImport,
DeclarationName &childDeclName,
DeclarationName &parentDeclName,
const DeclContext *childCurrentDeclContext) {
// Don't do the import if we have a Function Template.
// Not supported by clang.
// FIXME: This is also a temporary check. Will be de-activated
// once clang supports the import of function templates.
if (declToImport->isFunctionOrFunctionTemplate()
&& declToImport->isTemplateDecl())
return;
if (Decl *importedDecl = m_Importer->Import(declToImport)) {
if (NamedDecl *importedNamedDecl = llvm::dyn_cast<NamedDecl>(importedDecl)) {
SetExternalVisibleDeclsForName(childCurrentDeclContext,
importedNamedDecl->getDeclName(),
importedNamedDecl);
}
// Put the name of the Decl imported with the
// DeclarationName coming from the parent, in my map.
m_ImportedDecls[childDeclName] = parentDeclName;
}
}
void ExternalInterpreterSource::ImportDeclContext(
DeclContext *declContextToImport,
DeclarationName &childDeclName,
DeclarationName &parentDeclName,
const DeclContext *childCurrentDeclContext) {
if (DeclContext *importedDeclContext =
m_Importer->ImportContext(declContextToImport)) {
importedDeclContext->setHasExternalVisibleStorage(true);
if (NamedDecl *importedNamedDecl =
llvm::dyn_cast<NamedDecl>(importedDeclContext)) {
SetExternalVisibleDeclsForName(childCurrentDeclContext,
importedNamedDecl->getDeclName(),
importedNamedDecl);
}
// Put the name of the DeclContext imported with the
// DeclarationName coming from the parent, in my map.
m_ImportedDecls[childDeclName] = parentDeclName;
// And also put the declaration context I found from the parent Interpreter
// in the map of the child Interpreter to have it for the future.
m_ImportedDeclContexts[importedDeclContext] = declContextToImport;
}
}
bool ExternalInterpreterSource::Import(DeclContext::lookup_result lookup_result,
const DeclContext *childCurrentDeclContext,
DeclarationName &childDeclName,
DeclarationName &parentDeclName) {
for (DeclContext::lookup_iterator I = lookup_result.begin(),
E = lookup_result.end(); I != E; ++I) {
// Check if this Name we are looking for is
// a DeclContext (for example a Namespace, function etc.).
if (DeclContext *declContextToImport = llvm::dyn_cast<DeclContext>(*I)) {
ImportDeclContext(declContextToImport, childDeclName,
parentDeclName, childCurrentDeclContext);
}
ImportDecl(*I, childDeclName, parentDeclName, childCurrentDeclContext);
}
return true;
}
///\brief This is the one of the most important function of the class
/// since from here initiates the lookup and import part of the missing
/// Decl(s) (Contexts).
///
bool ExternalInterpreterSource::FindExternalVisibleDeclsByName(
const DeclContext *childCurrentDeclContext, DeclarationName childDeclName) {
assert(childDeclName && "Child Decl name is empty");
assert(childCurrentDeclContext->hasExternalVisibleStorage() &&
"DeclContext has no visible decls in storage");
//Check if we have already found this declaration Name before
DeclarationName parentDeclName;
std::map<clang::DeclarationName,
clang::DeclarationName>::iterator IDecl =
m_ImportedDecls.find(childDeclName);
if (IDecl != m_ImportedDecls.end()) {
parentDeclName = IDecl->second;
} else {
// Get the identifier info from the parent interpreter
// for this Name.
std::string name = childDeclName.getAsString();
IdentifierTable &parentIdentifierTable =
m_ParentInterpreter->getCI()->getASTContext().Idents;
IdentifierInfo &parentIdentifierInfo =
parentIdentifierTable.get(name);
parentDeclName = DeclarationName(&parentIdentifierInfo);
}
// Search in the map of the stored Decl Contexts for this
// Decl Context.
std::map<const clang::DeclContext *, clang::DeclContext *>::iterator
IDeclContext = m_ImportedDeclContexts.find(childCurrentDeclContext);
// If childCurrentDeclContext was found before and is already in the map,
// then do the lookup using the stored pointer.
if (IDeclContext == m_ImportedDeclContexts.end()) return false;
DeclContext *parentDeclContext = IDeclContext->second;
DeclContext::lookup_result lookup_result =
parentDeclContext->lookup(parentDeclName);
// Check if we found this Name in the parent interpreter
if (!lookup_result.empty()) {
if (Import(lookup_result,
childCurrentDeclContext, childDeclName, parentDeclName))
return true;
}
return false;
}
///\brief Make available to child all decls in parent's decl context
/// that corresponds to child decl context.
void ExternalInterpreterSource::completeVisibleDeclsMap(
const clang::DeclContext *childDeclContext) {
assert (childDeclContext && "No child decl context!");
if (!childDeclContext->hasExternalVisibleStorage())
return;
// Search in the map of the stored Decl Contexts for this
// Decl Context.
std::map<const clang::DeclContext *, clang::DeclContext *>::iterator
IDeclContext = m_ImportedDeclContexts.find(childDeclContext);
// If childCurrentDeclContext was found before and is already in the map,
// then do the lookup using the stored pointer.
if (IDeclContext == m_ImportedDeclContexts.end()) return ;
DeclContext *parentDeclContext = IDeclContext->second;
// Filter the decls from the external source using the stem information
// stored in Sema.
StringRef filter =
m_ChildInterpreter->getCI()->getPreprocessor().getCodeCompletionFilter();
for (DeclContext::decl_iterator IDeclContext =
parentDeclContext->decls_begin(),
EDeclContext =
parentDeclContext->decls_end();
IDeclContext != EDeclContext; ++IDeclContext) {
if (NamedDecl* parentDecl = llvm::dyn_cast<NamedDecl>(*IDeclContext)) {
DeclarationName childDeclName = parentDecl->getDeclName();
if (auto II = childDeclName.getAsIdentifierInfo()) {
StringRef name = II->getName();
if (!name.empty() && name.startswith(filter))
ImportDecl(parentDecl, childDeclName, childDeclName,
childDeclContext);
}
}
}
const_cast<DeclContext *>(childDeclContext)->
setHasExternalVisibleStorage(false);
}
} // end namespace cling
<commit_msg>Don’t import UsingDecl or UsingShadowDecl. Fixes atexit test failure on gcc on OS X.<commit_after>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// author: Elisavet Sakellari <[email protected]>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "ExternalInterpreterSource.h"
#include "cling/Interpreter/Interpreter.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTImporter.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/Sema.h"
using namespace clang;
namespace {
class ClingASTImporter : public ASTImporter {
private:
cling::ExternalInterpreterSource &m_Source;
public:
ClingASTImporter(ASTContext &ToContext, FileManager &ToFileManager,
ASTContext &FromContext, FileManager &FromFileManager,
bool MinimalImport,
cling::ExternalInterpreterSource& source):
ASTImporter(ToContext, ToFileManager, FromContext, FromFileManager,
MinimalImport), m_Source(source) {}
virtual ~ClingASTImporter() = default;
Decl *Imported(Decl *From, Decl *To) override {
ASTImporter::Imported(From, To);
if (clang::TagDecl* toTagDecl = dyn_cast<TagDecl>(To)) {
toTagDecl->setHasExternalLexicalStorage();
toTagDecl->setMustBuildLookupTable();
toTagDecl->setHasExternalVisibleStorage();
}
if (NamespaceDecl *toNamespaceDecl = dyn_cast<NamespaceDecl>(To)) {
toNamespaceDecl->setHasExternalVisibleStorage();
}
if (ObjCContainerDecl *toContainerDecl = dyn_cast<ObjCContainerDecl>(To)) {
toContainerDecl->setHasExternalLexicalStorage();
toContainerDecl->setHasExternalVisibleStorage();
}
// Put the name of the Decl imported with the
// DeclarationName coming from the parent, in my map.
if (NamedDecl *toNamedDecl = llvm::dyn_cast<NamedDecl>(To)) {
NamedDecl *fromNamedDecl = llvm::dyn_cast<NamedDecl>(From);
m_Source.addToImportedDecls(toNamedDecl->getDeclName(),
fromNamedDecl->getDeclName());
}
if (DeclContext *toDeclContext = llvm::dyn_cast<DeclContext>(To)) {
DeclContext *fromDeclContext = llvm::dyn_cast<DeclContext>(From);
m_Source.addToImportedDeclContexts(toDeclContext, fromDeclContext);
}
return To;
}
};
}
namespace cling {
ExternalInterpreterSource::ExternalInterpreterSource(
const cling::Interpreter *parent, cling::Interpreter *child) :
m_ParentInterpreter(parent), m_ChildInterpreter(child) {
clang::DeclContext *parentTUDeclContext =
m_ParentInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
clang::DeclContext *childTUDeclContext =
m_ChildInterpreter->getCI()->getASTContext().getTranslationUnitDecl();
// Also keep in the map of Decl Contexts the Translation Unit Decl Context
m_ImportedDeclContexts[childTUDeclContext] = parentTUDeclContext;
FileManager &childFM = m_ChildInterpreter->getCI()->getFileManager();
FileManager &parentFM = m_ParentInterpreter->getCI()->getFileManager();
ASTContext &fromASTContext = m_ParentInterpreter->getCI()->getASTContext();
ASTContext &toASTContext = m_ChildInterpreter->getCI()->getASTContext();
ClingASTImporter* importer
= new ClingASTImporter(toASTContext, childFM, fromASTContext, parentFM,
/*MinimalImport : ON*/ true, *this);
m_Importer.reset(llvm::dyn_cast<ASTImporter>(importer));
}
ExternalInterpreterSource::~ExternalInterpreterSource() {}
void ExternalInterpreterSource::ImportDecl(Decl *declToImport,
DeclarationName &childDeclName,
DeclarationName &parentDeclName,
const DeclContext *childCurrentDeclContext) {
// Don't do the import if we have a Function Template or using decls. They
// are not supported by clang.
// FIXME: These are temporary checks and should be de-activated once clang
// supports their import.
if ((declToImport->isFunctionOrFunctionTemplate()
&& declToImport->isTemplateDecl()) || dyn_cast<UsingDecl>(declToImport)
|| dyn_cast<UsingShadowDecl>(declToImport)) {
#ifndef NDEBUG
// DiagnosticsTrap isn't working here!
DiagnosticsEngine& Diags = m_Importer->getFromContext().getDiagnostics();
const bool OwnClient = Diags.ownsClient();
std::unique_ptr<DiagnosticConsumer> Prev = Diags.takeClient();
DiagnosticConsumer Trap;
Diags.setClient(&Trap, false);
assert((!Trap.getNumErrors() && m_Importer->Import(declToImport)==nullptr
&& Trap.getNumErrors() != 0) && "Import using worked!");
assert(Trap.getNumErrors() == 1 && "Import caused multiple errors");
Diags.setClient(Prev.get(), OwnClient);
Prev.release();
#if LLVM_VERSION_MAJOR >= 4
// In LLVM 4 the test above still works, but the errors generated are
// still propogated...So just reset the Diags.
Diags.Reset(true);
#endif
#endif
return;
}
if (Decl *importedDecl = m_Importer->Import(declToImport)) {
if (NamedDecl *importedNamedDecl = llvm::dyn_cast<NamedDecl>(importedDecl)) {
SetExternalVisibleDeclsForName(childCurrentDeclContext,
importedNamedDecl->getDeclName(),
importedNamedDecl);
}
// Put the name of the Decl imported with the
// DeclarationName coming from the parent, in my map.
m_ImportedDecls[childDeclName] = parentDeclName;
}
}
void ExternalInterpreterSource::ImportDeclContext(
DeclContext *declContextToImport,
DeclarationName &childDeclName,
DeclarationName &parentDeclName,
const DeclContext *childCurrentDeclContext) {
if (DeclContext *importedDeclContext =
m_Importer->ImportContext(declContextToImport)) {
importedDeclContext->setHasExternalVisibleStorage(true);
if (NamedDecl *importedNamedDecl =
llvm::dyn_cast<NamedDecl>(importedDeclContext)) {
SetExternalVisibleDeclsForName(childCurrentDeclContext,
importedNamedDecl->getDeclName(),
importedNamedDecl);
}
// Put the name of the DeclContext imported with the
// DeclarationName coming from the parent, in my map.
m_ImportedDecls[childDeclName] = parentDeclName;
// And also put the declaration context I found from the parent Interpreter
// in the map of the child Interpreter to have it for the future.
m_ImportedDeclContexts[importedDeclContext] = declContextToImport;
}
}
bool ExternalInterpreterSource::Import(DeclContext::lookup_result lookup_result,
const DeclContext *childCurrentDeclContext,
DeclarationName &childDeclName,
DeclarationName &parentDeclName) {
for (DeclContext::lookup_iterator I = lookup_result.begin(),
E = lookup_result.end(); I != E; ++I) {
// Check if this Name we are looking for is
// a DeclContext (for example a Namespace, function etc.).
if (DeclContext *declContextToImport = llvm::dyn_cast<DeclContext>(*I)) {
ImportDeclContext(declContextToImport, childDeclName,
parentDeclName, childCurrentDeclContext);
}
ImportDecl(*I, childDeclName, parentDeclName, childCurrentDeclContext);
}
return true;
}
///\brief This is the one of the most important function of the class
/// since from here initiates the lookup and import part of the missing
/// Decl(s) (Contexts).
///
bool ExternalInterpreterSource::FindExternalVisibleDeclsByName(
const DeclContext *childCurrentDeclContext, DeclarationName childDeclName) {
assert(childDeclName && "Child Decl name is empty");
assert(childCurrentDeclContext->hasExternalVisibleStorage() &&
"DeclContext has no visible decls in storage");
//Check if we have already found this declaration Name before
DeclarationName parentDeclName;
std::map<clang::DeclarationName,
clang::DeclarationName>::iterator IDecl =
m_ImportedDecls.find(childDeclName);
if (IDecl != m_ImportedDecls.end()) {
parentDeclName = IDecl->second;
} else {
// Get the identifier info from the parent interpreter
// for this Name.
std::string name = childDeclName.getAsString();
IdentifierTable &parentIdentifierTable =
m_ParentInterpreter->getCI()->getASTContext().Idents;
IdentifierInfo &parentIdentifierInfo =
parentIdentifierTable.get(name);
parentDeclName = DeclarationName(&parentIdentifierInfo);
}
// Search in the map of the stored Decl Contexts for this
// Decl Context.
std::map<const clang::DeclContext *, clang::DeclContext *>::iterator
IDeclContext = m_ImportedDeclContexts.find(childCurrentDeclContext);
// If childCurrentDeclContext was found before and is already in the map,
// then do the lookup using the stored pointer.
if (IDeclContext == m_ImportedDeclContexts.end()) return false;
DeclContext *parentDeclContext = IDeclContext->second;
DeclContext::lookup_result lookup_result =
parentDeclContext->lookup(parentDeclName);
// Check if we found this Name in the parent interpreter
if (!lookup_result.empty()) {
if (Import(lookup_result,
childCurrentDeclContext, childDeclName, parentDeclName))
return true;
}
return false;
}
///\brief Make available to child all decls in parent's decl context
/// that corresponds to child decl context.
void ExternalInterpreterSource::completeVisibleDeclsMap(
const clang::DeclContext *childDeclContext) {
assert (childDeclContext && "No child decl context!");
if (!childDeclContext->hasExternalVisibleStorage())
return;
// Search in the map of the stored Decl Contexts for this
// Decl Context.
std::map<const clang::DeclContext *, clang::DeclContext *>::iterator
IDeclContext = m_ImportedDeclContexts.find(childDeclContext);
// If childCurrentDeclContext was found before and is already in the map,
// then do the lookup using the stored pointer.
if (IDeclContext == m_ImportedDeclContexts.end()) return ;
DeclContext *parentDeclContext = IDeclContext->second;
// Filter the decls from the external source using the stem information
// stored in Sema.
StringRef filter =
m_ChildInterpreter->getCI()->getPreprocessor().getCodeCompletionFilter();
for (DeclContext::decl_iterator IDeclContext =
parentDeclContext->decls_begin(),
EDeclContext =
parentDeclContext->decls_end();
IDeclContext != EDeclContext; ++IDeclContext) {
if (NamedDecl* parentDecl = llvm::dyn_cast<NamedDecl>(*IDeclContext)) {
DeclarationName childDeclName = parentDecl->getDeclName();
if (auto II = childDeclName.getAsIdentifierInfo()) {
StringRef name = II->getName();
if (!name.empty() && name.startswith(filter))
ImportDecl(parentDecl, childDeclName, childDeclName,
childDeclContext);
}
}
}
const_cast<DeclContext *>(childDeclContext)->
setHasExternalVisibleStorage(false);
}
} // end namespace cling
<|endoftext|> |
<commit_before>#ifndef COBALT_UTILITY_ENUMERATOR_HPP_INCLUDED
#define COBALT_UTILITY_ENUMERATOR_HPP_INCLUDED
#pragma once
#include <type_traits>
namespace cobalt {
template <typename Iterator>
class enumerator {
public:
typedef Iterator iterator;
enumerator(iterator begin, iterator end)
: _begin(begin)
, _end(end)
{
}
iterator begin() const { return _begin; }
iterator end() const { return _end; }
private:
iterator _begin;
iterator _end;
};
template <typename Container>
enumerator<typename Container::iterator> make_enumerator(Container& container) {
return { std::begin(container), std::end(container) };
}
template <typename Container>
enumerator<typename Container::const_iterator> make_enumerator(const Container& container) {
return { std::cbegin(container), std::cend(container) };
}
template <typename T, size_t N>
enumerator<T*> make_enumerator(T(&array)[N]) {
return { &array[0], &array[N] };
}
template <typename T, typename = std::enable_if_t<std::is_pointer<T>::value>>
enumerator<T> make_enumerator(T begin, T end) {
return { begin, end };
}
} // namespace cobalt
#endif // COBALT_UTILITY_ENUMERATOR_HPP_INCLUDED
<commit_msg>Using std::begin/std::end for C arrays<commit_after>#ifndef COBALT_UTILITY_ENUMERATOR_HPP_INCLUDED
#define COBALT_UTILITY_ENUMERATOR_HPP_INCLUDED
#pragma once
#include <type_traits>
namespace cobalt {
template <typename Iterator>
class enumerator {
public:
typedef Iterator iterator;
enumerator(iterator begin, iterator end)
: _begin(begin)
, _end(end)
{
}
iterator begin() const { return _begin; }
iterator end() const { return _end; }
private:
iterator _begin;
iterator _end;
};
template <typename Container>
enumerator<typename Container::iterator> make_enumerator(Container& container) {
return { std::begin(container), std::end(container) };
}
template <typename Container>
enumerator<typename Container::const_iterator> make_enumerator(const Container& container) {
return { std::cbegin(container), std::cend(container) };
}
template <typename T, size_t N>
enumerator<T*> make_enumerator(T(&array)[N]) {
return { std::begin(array), std::end(array) };
}
template <typename T, typename = std::enable_if_t<std::is_pointer<T>::value>>
enumerator<T> make_enumerator(T begin, T end) {
return { begin, end };
}
} // namespace cobalt
#endif // COBALT_UTILITY_ENUMERATOR_HPP_INCLUDED
<|endoftext|> |
<commit_before>/*************************************************************************/
/* wrapped.hpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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. */
/*************************************************************************/
#ifndef GODOT_CPP_WRAPPED_HPP
#define GODOT_CPP_WRAPPED_HPP
#include <godot_cpp/core/memory.hpp>
#include <godot_cpp/godot.hpp>
namespace godot {
typedef void GodotObject;
// Base for all engine classes, to contain the pointer to the engine instance.
class Wrapped {
friend class GDExtensionBinding;
friend void postinitialize_handler(Wrapped *);
protected:
virtual const char *_get_extension_class() const; // This is needed to retrieve the class name before the godot object has its _extension and _extension_instance members assigned.
virtual const GDNativeInstanceBindingCallbacks *_get_bindings_callbacks() const = 0;
void _postinitialize();
Wrapped(const char *p_godot_class);
Wrapped(GodotObject *p_godot_object);
public:
// Must be public but you should not touch this.
GodotObject *_owner = nullptr;
};
} // namespace godot
#define GDCLASS(m_class, m_inherits) \
private: \
void operator=(const m_class &p_rval) {} \
friend class ClassDB; \
\
protected: \
virtual const char *_get_extension_class() const override { \
return get_class_static(); \
} \
\
virtual const GDNativeInstanceBindingCallbacks *_get_bindings_callbacks() const override { \
return &___binding_callbacks; \
} \
\
static void (*_get_bind_methods())() { \
return &m_class::_bind_methods; \
} \
\
template <class T> \
static void register_virtuals() { \
m_inherits::register_virtuals<T>(); \
} \
\
public: \
static void initialize_class() { \
static bool initialized = false; \
if (initialized) { \
return; \
} \
m_inherits::initialize_class(); \
if (m_class::_get_bind_methods() != m_inherits::_get_bind_methods()) { \
_bind_methods(); \
m_inherits::register_virtuals<m_class>(); \
} \
initialized = true; \
} \
\
static const char *get_class_static() { \
return #m_class; \
} \
\
static const char *get_parent_class_static() { \
return #m_inherits; \
} \
\
static GDNativeObjectPtr create(void *data) { \
m_class *new_object = memnew(m_class); \
return new_object->_owner; \
} \
\
static void free(void *data, GDExtensionClassInstancePtr ptr) { \
if (ptr) { \
m_class *cls = reinterpret_cast<m_class *>(ptr); \
cls->~m_class(); \
::godot::Memory::free_static(cls); \
} \
} \
\
static void *___binding_create_callback(void *p_token, void *p_instance) { \
return nullptr; \
} \
static void ___binding_free_callback(void *p_token, void *p_instance, void *p_binding) { \
} \
static GDNativeBool ___binding_reference_callback(void *p_token, void *p_instance, GDNativeBool p_reference) { \
return true; \
} \
static constexpr GDNativeInstanceBindingCallbacks ___binding_callbacks = { \
___binding_create_callback, \
___binding_free_callback, \
___binding_reference_callback, \
};
// Don't use this for your classes, use GDCLASS() instead.
#define GDNATIVE_CLASS(m_class, m_inherits) \
private: \
void operator=(const m_class &p_rval) {} \
\
protected: \
virtual const GDNativeInstanceBindingCallbacks *_get_bindings_callbacks() const override { \
return &___binding_callbacks; \
} \
\
m_class(const char *p_godot_class) : m_inherits(p_godot_class) {} \
m_class(GodotObject *p_godot_object) : m_inherits(p_godot_object) {} \
\
static void (*_get_bind_methods())() { \
return nullptr; \
} \
\
public: \
static void initialize_class() {} \
\
static const char *get_class_static() { \
return #m_class; \
} \
\
static const char *get_parent_class_static() { \
return #m_inherits; \
} \
\
static void *___binding_create_callback(void *p_token, void *p_instance) { \
return memnew(m_class((GodotObject *)p_instance)); \
} \
static void ___binding_free_callback(void *p_token, void *p_instance, void *p_binding) { \
Memory::free_static(reinterpret_cast<m_class *>(p_binding)); \
} \
static GDNativeBool ___binding_reference_callback(void *p_token, void *p_instance, GDNativeBool p_reference) { \
return true; \
} \
static constexpr GDNativeInstanceBindingCallbacks ___binding_callbacks = { \
___binding_create_callback, \
___binding_free_callback, \
___binding_reference_callback, \
}; \
m_class() : m_class(#m_class) {}
#endif // ! GODOT_CPP_WRAPPED_HPP
<commit_msg>Fix GDCLASS when inherited class is in another namespace<commit_after>/*************************************************************************/
/* wrapped.hpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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. */
/*************************************************************************/
#ifndef GODOT_CPP_WRAPPED_HPP
#define GODOT_CPP_WRAPPED_HPP
#include <godot_cpp/core/memory.hpp>
#include <godot_cpp/godot.hpp>
namespace godot {
typedef void GodotObject;
// Base for all engine classes, to contain the pointer to the engine instance.
class Wrapped {
friend class GDExtensionBinding;
friend void postinitialize_handler(Wrapped *);
protected:
virtual const char *_get_extension_class() const; // This is needed to retrieve the class name before the godot object has its _extension and _extension_instance members assigned.
virtual const GDNativeInstanceBindingCallbacks *_get_bindings_callbacks() const = 0;
void _postinitialize();
Wrapped(const char *p_godot_class);
Wrapped(GodotObject *p_godot_object);
public:
static const char *get_class_static() {
return "Wrapped";
}
// Must be public but you should not touch this.
GodotObject *_owner = nullptr;
};
} // namespace godot
#define GDCLASS(m_class, m_inherits) \
private: \
void operator=(const m_class &p_rval) {} \
friend class ClassDB; \
\
protected: \
virtual const char *_get_extension_class() const override { \
return get_class_static(); \
} \
\
virtual const GDNativeInstanceBindingCallbacks *_get_bindings_callbacks() const override { \
return &___binding_callbacks; \
} \
\
static void (*_get_bind_methods())() { \
return &m_class::_bind_methods; \
} \
\
template <class T> \
static void register_virtuals() { \
m_inherits::register_virtuals<T>(); \
} \
\
public: \
static void initialize_class() { \
static bool initialized = false; \
if (initialized) { \
return; \
} \
m_inherits::initialize_class(); \
if (m_class::_get_bind_methods() != m_inherits::_get_bind_methods()) { \
_bind_methods(); \
m_inherits::register_virtuals<m_class>(); \
} \
initialized = true; \
} \
\
static const char *get_class_static() { \
return #m_class; \
} \
\
static const char *get_parent_class_static() { \
return m_inherits::get_class_static(); \
} \
\
static GDNativeObjectPtr create(void *data) { \
m_class *new_object = memnew(m_class); \
return new_object->_owner; \
} \
\
static void free(void *data, GDExtensionClassInstancePtr ptr) { \
if (ptr) { \
m_class *cls = reinterpret_cast<m_class *>(ptr); \
cls->~m_class(); \
::godot::Memory::free_static(cls); \
} \
} \
\
static void *___binding_create_callback(void *p_token, void *p_instance) { \
return nullptr; \
} \
static void ___binding_free_callback(void *p_token, void *p_instance, void *p_binding) { \
} \
static GDNativeBool ___binding_reference_callback(void *p_token, void *p_instance, GDNativeBool p_reference) { \
return true; \
} \
static constexpr GDNativeInstanceBindingCallbacks ___binding_callbacks = { \
___binding_create_callback, \
___binding_free_callback, \
___binding_reference_callback, \
};
// Don't use this for your classes, use GDCLASS() instead.
#define GDNATIVE_CLASS(m_class, m_inherits) \
private: \
void operator=(const m_class &p_rval) {} \
\
protected: \
virtual const GDNativeInstanceBindingCallbacks *_get_bindings_callbacks() const override { \
return &___binding_callbacks; \
} \
\
m_class(const char *p_godot_class) : m_inherits(p_godot_class) {} \
m_class(GodotObject *p_godot_object) : m_inherits(p_godot_object) {} \
\
static void (*_get_bind_methods())() { \
return nullptr; \
} \
\
public: \
static void initialize_class() {} \
\
static const char *get_class_static() { \
return #m_class; \
} \
\
static const char *get_parent_class_static() { \
return m_inherits::get_class_static(); \
} \
\
static void *___binding_create_callback(void *p_token, void *p_instance) { \
return memnew(m_class((GodotObject *)p_instance)); \
} \
static void ___binding_free_callback(void *p_token, void *p_instance, void *p_binding) { \
Memory::free_static(reinterpret_cast<m_class *>(p_binding)); \
} \
static GDNativeBool ___binding_reference_callback(void *p_token, void *p_instance, GDNativeBool p_reference) { \
return true; \
} \
static constexpr GDNativeInstanceBindingCallbacks ___binding_callbacks = { \
___binding_create_callback, \
___binding_free_callback, \
___binding_reference_callback, \
}; \
m_class() : m_class(#m_class) {}
#endif // ! GODOT_CPP_WRAPPED_HPP
<|endoftext|> |
<commit_before>/**
* @file Resolution.hpp
* @brief Resolution class prototype.
* @author zer0
* @date 2018-07-10
*/
#ifndef __INCLUDE_LIBTBAG__LIBTBAG_GRAPHIC_RESOLUTION_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_GRAPHIC_RESOLUTION_HPP__
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <libtbag/config.h>
#include <libtbag/predef.hpp>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace graphic {
#ifndef RESOLUTION_MAP
#define RESOLUTION_MAP(_XX) \
/* _XX(category, def, name, width, height, brief) */ \
_XX(CIF , SUB_QCIF , Sub-QCIF, 128, 96, Common Intermediate Format ) \
_XX(CIF , QCIF_176_144 , QCIF , 176, 144, Common Intermediate Format ) \
_XX(CIF , QCIF_220_176 , QCIF , 220, 176, Common Intermediate Format ) \
_XX(CIF , CIF , CIF , 352, 288, Common Intermediate Format ) \
_XX(CIF , CIF4 , 4CIF , 704, 576, Common Intermediate Format ) \
_XX(CIF , CIF16 , 16CIF , 1408, 1152, Common Intermediate Format ) \
_XX(CGA , CGA_320_200 , CGA , 320, 200, Color Graphics Adaptor ) \
_XX(CGA , CGA_640_200 , CGA , 640, 200, Color Graphics Adaptor ) \
_XX(EGA , EGA_320_200 , EGA , 320, 200, Enhanced Graphics Adaptor ) \
_XX(EGA , EGA_640_200 , EGA , 640, 200, Enhanced Graphics Adaptor ) \
_XX(EGA , EGA_640_350 , EGA , 640, 350, Enhanced Graphics Adaptor ) \
_XX(HGC , HGC_640_400 , HGC , 640, 400, Hercules Graphics Card ) \
_XX(HGC , HGC_720_348 , HGC , 720, 348, Hercules Graphics Card ) \
_XX(VGA , QQVGA , qqVGA , 160, 120, quarter quarter VGA ) \
_XX(VGA , HQVGA , HqVGA , 240, 160, Half quarter VGA ) \
_XX(VGA , QVGA , qVGA , 320, 240, quarter VGA ) \
_XX(VGA , WQVGA , WqVGA , 400, 240, Wide quarter VGA ) \
_XX(VGA , HVGA , HVGA , 480, 320, Half-size VGA ) \
_XX(VGA , VGA , VGA , 640, 480, Video Graphics Array ) \
_XX(VGA , WVGA , WVGA , 800, 480, Wide VGA ) \
_XX(VGA , FWVGA , FWVGA , 854, 480, Full Wide VGA ) \
_XX(VGA , SVGA , SVGA , 800, 600, Super VGA ) \
_XX(VGA , DVGA , DVGA , 960, 640, Double-size VGA ) \
_XX(VGA , WSVGA_1024_576 , WSVGA , 1024, 576, Wide Super VGA ) \
_XX(VGA , WSVGA_1024_600 , WSVGA , 1024, 600, Wide Super VGA ) \
_XX(XGA , XGA , XGA , 1024, 768, eXtended Graphics Array ) \
_XX(XGA , WXGA_1280_768 , WXGA , 1280, 768, Wide XGA ) \
_XX(XGA , WXGA_1280_800 , WXGA , 1280, 800, Wide XGA ) \
_XX(XGA , FWXGA , FWXGA , 1366, 768, Full Wide XGA ) \
_XX(XGA , XGA_PLUS , XGA+ , 1152, 864, XGA Plus ) \
_XX(XGA , WXGA_PLUS , WXGA+ , 1440, 900, Wide XGA Plus ) \
_XX(XGA , WSXGA , WSXGA , 1680, 1050, Widescreen Super XGA ) \
_XX(XGA , SXGA , SXGA , 1280, 1024, Super XGA ) \
_XX(XGA , SXGA_PLUS , SXGA+ , 1400, 1050, Super XGA ) \
_XX(XGA , UXGA , UXGA , 1600, 1200, Ultra XGA ) \
_XX(XGA , WUXGA , WUXGA , 1920, 1200, Wide Ultra XGA ) \
_XX(QXGA, QWXGA , QWXGA , 2048, 1152, Quad Wide XGA ) \
_XX(QXGA, QXGA , QXGA , 2048, 1536, Quad XGA ) \
_XX(QXGA, WQXGA_2560_1600, WQXGA , 2560, 1600, Wide Quad XGA ) \
_XX(QXGA, WQXGA_2880_1800, WQXGA , 2880, 1800, Wide Quad XGA ) \
_XX(QXGA, QWXGA , QWXGA , 2560, 2048, Quad Wide XGA ) \
_XX(QXGA, WQSXGA , WQSXGA , 3200, 2048, Wide Quad Super XGA ) \
_XX(QXGA, QUXGA , QUXGA , 3200, 2400, Quad Ultra XGA ) \
_XX(QXGA, WQUXGA , WQUXGA , 3840, 2400, Wide Quad Ultra XGA ) \
_XX(HXGA, HXGA , HXGA , 4096, 3072, Hex XGA ) \
_XX(HXGA, WHXGA , WHXGA , 5120, 3200, Wide Hex XGA ) \
_XX(HXGA, HSXGA , HSXGA , 5120, 4096, Hex Super XGA ) \
_XX(HXGA, WHSXGA , WHSXGA , 6400, 4096, Wide Hex Super XGA ) \
_XX(HXGA, HUXGA , HUXGA , 6400, 4800, Hex Ultra XGA ) \
_XX(HXGA, WHUXGA , WHUXGA , 7680, 4800, Wide Hex Ultra XGA ) \
_XX(HD , NHD , nHD , 640, 360, one ninth of a Full HD frame ) \
_XX(HD , QHD , qHD , 960, 540, one quarter of Full-HD ) \
_XX(HD , HD , HD , 1280, 720, HD ) \
_XX(HD , HD_PLUS , HD+ , 1600, 900, HD Plus ) \
_XX(HD , FHD , FHD , 1920, 1080, Full HD ) \
_XX(HD , WQHD , WQHD/QHD, 2560, 1440, Wide Quad HD/Quad HD ) \
_XX(HD , QHD_PLUS , QHD+ , 3200, 1800, Quad HD Plus ) \
_XX(HD , UHD , UHD , 3840, 2160, Ultra HD/4K ) \
_XX(HD , UHD_PLUS , UHD+ , 5120, 2880, Ultra HD Plus/5K ) \
_XX(HD , QUHD , QUHD , 7680, 4320, Quad Ultra HD/8K ) \
/* -- END -- */
#endif
} // namespace graphic
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
#endif // __INCLUDE_LIBTBAG__LIBTBAG_GRAPHIC_RESOLUTION_HPP__
<commit_msg>Update Graphics display resolution.<commit_after>/**
* @file Resolution.hpp
* @brief Graphics display resolution.
* @author zer0
* @date 2018-07-10
* * @see <https://en.wikipedia.org/wiki/Graphics_display_resolution>
*/
#ifndef __INCLUDE_LIBTBAG__LIBTBAG_GRAPHIC_RESOLUTION_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_GRAPHIC_RESOLUTION_HPP__
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <libtbag/config.h>
#include <libtbag/predef.hpp>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace graphic {
# /****************************************************/
# /* Parameter syntax: */
# /* _XX(define, name, width, height, aspect_ratio) */
# /****************************************************/
#ifndef HIGH_DEFINITION_MAP
#define HIGH_DEFINITION_MAP(_XX) \
_XX( NHD, nHD, 640, 360, 16:9) \
_XX( QHD, qHD, 960, 540, 16:9) \
_XX( HD, HD, 1280, 720, 16:9) \
_XX( HD_PLUS, HD+, 1600, 900, 16:9) \
_XX( FHD, FHD, 1920, 1080, 16:9) \
_XX( WQHD, WQHD, 2560, 1440, 16:9) \
_XX( QHD_PLUS, QHD+, 3200, 1800, 16:9) \
_XX( UHD_4K, 4K UHD, 3840, 2160, 16:9) \
_XX(UHD_PLUS_5K, 5K UHD+, 5120, 2880, 16:9) \
_XX( UHD_8K, 8K UHD, 7680, 4320, 16:9) \
/* -- END -- */
#endif
#ifndef VIDEO_GRAPHICS_ARRAY_MAP
#define VIDEO_GRAPHICS_ARRAY_MAP(_XX) \
_XX( QQVGA, QQVGA, 160, 120, 4:3 ) \
_XX( HQVGA_240_160, HQVGA, 240, 160, 3:2 ) \
_XX( HQVGA_256_160, HQVGA, 256, 160, 16:10) \
_XX( QVGA, QVGA, 320, 240, 4:3 ) \
_XX( WQVGA_384_240, WQVGA, 384, 240, 16:10) \
_XX( WQVGA_360_240, WQVGA, 360, 240, 3:2 ) \
_XX( WQVGA_400_240, WQVGA, 400, 240, 5:3 ) \
_XX( HVGA, HVGA, 480, 320, 3:2 ) \
_XX( VGA, VGA, 640, 480, 4:3 ) \
_XX( WVGA_768_480, WVGA, 768, 480, 16:10) \
_XX( WVGA_720_480, WVGA, 720, 480, 3:2 ) \
_XX( WVGA_800_480, WVGA, 800, 480, 5:3 ) \
_XX( FWVGA, FWVGA, 854, 480, 16:9 ) \
_XX( SVGA, SVGA, 800, 600, 4:3 ) \
_XX( DVGA, DVGA, 960, 640, 3:2 ) \
_XX(WSVGA_1024_576, WSVGA, 1024, 576, 16:9 ) \
_XX(WSVGA_1024_600, WSVGA, 1024, 600, 128:75) \
/* -- END -- */
#endif
#ifndef EXTENDED_GRAPHICS_ARRAY_MAP
#define EXTENDED_GRAPHICS_ARRAY_MAP(_XX) \
_XX( XGA, XGA, 1024, 768, 4:3 ) \
_XX(WXGA_1152_768, WXGA, 1152, 768, 3:2 ) \
_XX(WXGA_1280_768, WXGA, 1280, 768, 5:3 ) \
_XX(WXGA_1280_800, WXGA, 1280, 800, 16:10) \
_XX(WXGA_1360_768, WXGA, 1360, 768, 16:9 ) \
_XX( FWXGA, FWXGA, 1366, 768, 16:9 ) \
_XX( XGA_PLUS, XGA+, 1152, 864, 4:3 ) \
_XX( WXGA_PLUS, WXGA+, 1440, 900, 16:10) \
_XX( WSXGA, WSXGA, 1440, 960, 3:2 ) \
_XX( SXGA, SXGA, 1280, 1024, 5:4 ) \
_XX( SXGA_PLUS, SXGA+, 1400, 1050, 4:3 ) \
_XX( WSXGA_PLUS, WSXGA+, 1680, 1050, 16:10) \
_XX( UXGA, UXGA, 1600, 1200, 4:3 ) \
_XX( WUXGA, WUXGA, 1920, 1200, 16:10) \
/* -- END -- */
#endif
#ifndef QUAD_EXTENDED_GRAPHICS_ARRAY_MAP
#define QUAD_EXTENDED_GRAPHICS_ARRAY_MAP(_XX) \
_XX( QWXGA, QWXGA, 2048, 1152, 16:9 ) \
_XX( QXGA, QXGA, 2048, 1536, 4:3 ) \
_XX(WQXGA_2560_1600, WQXGA, 2560, 1600, 16:10) \
_XX(WQXGA_2880_1800, WQXGA, 2880, 1800, 16:10) \
_XX( QSXGA, QSXGA, 2560, 2048, 5:4 ) \
_XX( WQSXGA, WQSXGA, 3200, 2048, 25:16) \
_XX( QUXGA, QUXGA, 3200, 2400, 4:3 ) \
_XX( WQUXGA, WQUXGA, 3840, 2400, 16:10) \
/* -- END -- */
#endif
#ifndef HYPER_EXTENDED_GRAPHICS_ARRAY_MAP
#define HYPER_EXTENDED_GRAPHICS_ARRAY_MAP(_XX) \
_XX( HXGA, HXGA, 4096, 3072, 4:3 ) \
_XX( WHXGA, WHXGA, 5120, 3200, 16:10) \
_XX( HSXGA, HSXGA, 5120, 4096, 5:4 ) \
_XX(WHSXGA, WHSXGA, 6400, 4096, 25:16) \
_XX( HUXGA, HUXGA, 6400, 4800, 4:3 ) \
_XX(WHUXGA, WHUXGA, 7680, 4800, 16:10) \
/* -- END -- */
#endif
#ifndef STANDARD_DISPLAY_RESOLUTIONS_MAP
#define STANDARD_DISPLAY_RESOLUTIONS_MAP(_XX) \
_XX( 160, 120, 4:3 ) \
_XX( 320, 200, 8:5 ) \
_XX( 640, 200, 16:5 ) \
_XX( 640, 350, 64:35) \
_XX( 640, 480, 4:3 ) \
_XX( 720, 348, 60:29) \
_XX( 800, 600, 4:3 ) \
_XX(1024, 768, 4:3 ) \
_XX(1152, 864, 4:3 ) \
_XX(1280, 1024, 5:4 ) \
_XX(1400, 1050, 4:3 ) \
_XX(1600, 1200, 4:3 ) \
_XX(2048, 1536, 4:3 ) \
_XX(2560, 2048, 5:4 ) \
_XX(3200, 2400, 4:3 ) \
_XX(4096, 3072, 4:3 ) \
_XX(5120, 4096, 5:4 ) \
_XX(6400, 4800, 4:3 ) \
/* -- END -- */
#endif
#ifndef WIDESCREEN_DISPLAY_RESOLUTIONS_MAP
#define WIDESCREEN_DISPLAY_RESOLUTIONS_MAP(_XX) \
_XX( 240, 160, 3:2 ) \
_XX( 320, 240, 4:3 ) \
_XX( 432, 240, 9:5 ) \
_XX( 480, 270, 16:9 ) \
_XX( 480, 320, 3:2 ) \
_XX( 640, 400, 8:5 ) \
_XX( 800, 480, 5:3 ) \
_XX( 854, 480, 427:240) \
_XX(1024, 576, 16:9 ) \
_XX(1280, 720, 16:9 ) \
_XX(1280, 768, 5:3 ) \
_XX(1280, 800, 8:5 ) \
_XX(1366, 768, 683:384) \
_XX(1366, 900, 683:450) \
_XX(1440, 900, 8:5 ) \
_XX(1600, 900, 16:9 ) \
_XX(1680, 945, 16:9 ) \
_XX(1680, 1050, 8:5 ) \
_XX(1920, 1080, 16:9 ) \
_XX(1920, 1200, 8:5 ) \
_XX(2048, 1152, 16:9 ) \
_XX(2560, 1440, 16:9 ) \
_XX(2560, 1600, 8:5 ) \
_XX(3200, 2048, 25:16 ) \
_XX(3840, 2160, 16:9 ) \
_XX(3200, 2400, 4:3 ) \
_XX(5120, 2880, 16:9 ) \
_XX(5120, 3200, 8:5 ) \
_XX(5760, 3240, 16:9 ) \
_XX(6400, 4096, 25:16 ) \
_XX(7680, 4320, 16:9 ) \
_XX(7680, 4800, 8:5 ) \
/* -- END -- */
#endif
} // namespace graphic
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
#endif // __INCLUDE_LIBTBAG__LIBTBAG_GRAPHIC_RESOLUTION_HPP__
<|endoftext|> |
<commit_before>/*
** Copyright (C) 2014 Aldebaran Robotics
** See COPYING for the license
*/
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <qi/log.hpp>
#include <qi/type/typeinterface.hpp>
#include "authprovider_p.hpp"
qiLogCategory("qimessaging.authprovider");
namespace qi {
const std::string QiAuthPrefix = "__qi_auth_";
const std::string AuthProvider::UserAuthPrefix = "auth_";
const std::string AuthProvider::Error_Reason_Key = QiAuthPrefix + "err_reason";
const std::string AuthProvider::State_Key = QiAuthPrefix + "state";
namespace auth_provider_private
{
static CapabilityMap extractAuthData(const CapabilityMap& cmap)
{
CapabilityMap authData;
// Extract all capabilities related to authentication
for (CapabilityMap::const_iterator it = cmap.begin(), end = cmap.end(); it != end; ++it)
{
const std::string& key = it->first;
if (boost::algorithm::starts_with(key, QiAuthPrefix))
authData[key] = it->second;
else if (boost::algorithm::starts_with(key, AuthProvider::UserAuthPrefix))
authData[key.substr(AuthProvider::UserAuthPrefix.length(), std::string::npos)] = it->second;
}
return authData;
}
static CapabilityMap prepareAuthCaps(const CapabilityMap& data)
{
CapabilityMap result;
for (CapabilityMap::const_iterator it = data.begin(), end = data.end(); it != end; ++it)
{
if (boost::algorithm::starts_with(it->first, QiAuthPrefix))
result[it->first] = it->second;
else
result[AuthProvider::UserAuthPrefix + it->first] = it->second;
}
return result;
}
} // auth_provider_private
CapabilityMap AuthProvider::processAuth(const CapabilityMap &authData)
{
CapabilityMap result;
result = auth_provider_private::extractAuthData(authData);
result = _processAuth(result);
assert(result.find(AuthProvider::State_Key) != result.end());
return auth_provider_private::prepareAuthCaps(result);
}
AuthProviderPtr NullAuthProviderFactory::newProvider()
{
return boost::make_shared<NullAuthProvider>();
}
CapabilityMap NullAuthProvider::_processAuth(const CapabilityMap &authData)
{
CapabilityMap reply;
reply[State_Key] = AnyValue::from(State_Done);
return reply;
}
}
<commit_msg>Force serialization to unsigned int for auth state<commit_after>/*
** Copyright (C) 2014 Aldebaran Robotics
** See COPYING for the license
*/
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <qi/log.hpp>
#include <qi/type/typeinterface.hpp>
#include "authprovider_p.hpp"
qiLogCategory("qimessaging.authprovider");
namespace qi {
const std::string QiAuthPrefix = "__qi_auth_";
const std::string AuthProvider::UserAuthPrefix = "auth_";
const std::string AuthProvider::Error_Reason_Key = QiAuthPrefix + "err_reason";
const std::string AuthProvider::State_Key = QiAuthPrefix + "state";
namespace auth_provider_private
{
static CapabilityMap extractAuthData(const CapabilityMap& cmap)
{
CapabilityMap authData;
// Extract all capabilities related to authentication
for (CapabilityMap::const_iterator it = cmap.begin(), end = cmap.end(); it != end; ++it)
{
const std::string& key = it->first;
if (boost::algorithm::starts_with(key, QiAuthPrefix))
authData[key] = it->second;
else if (boost::algorithm::starts_with(key, AuthProvider::UserAuthPrefix))
authData[key.substr(AuthProvider::UserAuthPrefix.length(), std::string::npos)] = it->second;
}
return authData;
}
static CapabilityMap prepareAuthCaps(const CapabilityMap& data)
{
CapabilityMap result;
for (CapabilityMap::const_iterator it = data.begin(), end = data.end(); it != end; ++it)
{
if (boost::algorithm::starts_with(it->first, QiAuthPrefix))
result[it->first] = it->second;
else
result[AuthProvider::UserAuthPrefix + it->first] = it->second;
}
return result;
}
} // auth_provider_private
CapabilityMap AuthProvider::processAuth(const CapabilityMap &authData)
{
CapabilityMap result;
result = auth_provider_private::extractAuthData(authData);
result = _processAuth(result);
assert(result.find(AuthProvider::State_Key) != result.end());
return auth_provider_private::prepareAuthCaps(result);
}
AuthProviderPtr NullAuthProviderFactory::newProvider()
{
return boost::make_shared<NullAuthProvider>();
}
CapabilityMap NullAuthProvider::_processAuth(const CapabilityMap &authData)
{
CapabilityMap reply;
const int state = State_Done;
reply[State_Key] = AnyValue::from(state);
return reply;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: toolbarmanager.hxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: vg $ $Date: 2006-04-07 10:18: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
*
************************************************************************/
#ifndef __FRAMEWORK_UIELEMENT_TOOLBARMANAGER_HXX_
#define __FRAMEWORK_UIELEMENT_TOOLBARMANAGER_HXX_
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_
#include <com/sun/star/frame/XStatusListener.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_
#include <com/sun/star/container/XIndexAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_
#include <com/sun/star/frame/XModuleManager.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XUICONTROLLERREGISTRATION_HPP_
#include <com/sun/star/frame/XUIControllerRegistration.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XIMAGEMANAGER_HPP_
#include <com/sun/star/ui/XImageManager.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_
#include <com/sun/star/frame/XStatusListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSUBTOOLBARCONTROLLER_HPP_
#include <com/sun/star/frame/XSubToolbarController.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_ITEMSTYLE_HPP_
#include <com/sun/star/ui/ItemStyle.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _RTL_USTRING_
#include <rtl/ustring.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif
#include <vcl/toolbox.hxx>
namespace com
{
namespace sun
{
namespace star
{
namespace frame
{
class XLayoutManager;
}
}
}
}
namespace framework
{
class ToolBar;
class ToolBarManager : public ::com::sun::star::frame::XFrameActionListener ,
public ::com::sun::star::frame::XStatusListener ,
public ::com::sun::star::lang::XComponent ,
public ::com::sun::star::lang::XTypeProvider ,
public ::com::sun::star::ui::XUIConfigurationListener,
public ThreadHelpBase ,
public ::cppu::OWeakObject
{
public:
ToolBarManager( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rServicveManager,
const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame,
const rtl::OUString& rResourceName,
ToolBar* pToolBar );
virtual ~ToolBarManager();
// XInterface, XTypeProvider, XServiceInfo
DECLARE_XINTERFACE
DECLARE_XTYPEPROVIDER
ToolBox* GetToolBar() const;
// XFrameActionListener
virtual void SAL_CALL frameAction( const com::sun::star::frame::FrameActionEvent& Action ) throw ( ::com::sun::star::uno::RuntimeException );
// XStatusListener
virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException );
// XEventListener
virtual void SAL_CALL disposing( const com::sun::star::lang::EventObject& Source ) throw ( ::com::sun::star::uno::RuntimeException );
// XUIConfigurationListener
virtual void SAL_CALL elementInserted( const ::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL elementRemoved( const ::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL elementReplaced( const ::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException);
// XComponent
void SAL_CALL dispose() throw ( ::com::sun::star::uno::RuntimeException );
void SAL_CALL addEventListener( const com::sun::star::uno::Reference< XEventListener >& xListener ) throw( com::sun::star::uno::RuntimeException );
void SAL_CALL removeEventListener( const com::sun::star::uno::Reference< XEventListener >& xListener ) throw( com::sun::star::uno::RuntimeException );
void CheckAndUpdateImages();
void RefreshImages();
void FillToolbar( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& rToolBarData );
void notifyRegisteredControllers( const rtl::OUString& aUIElementName, const rtl::OUString& aCommand );
void Destroy();
protected:
enum ExecuteCommand
{
EXEC_CMD_CLOSETOOLBAR,
EXEC_CMD_NONE,
EXEC_CMD_COUNT
};
struct ExecuteInfo
{
rtl::OUString aToolbarResName;
ExecuteCommand nCmd;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XLayoutManager > xLayoutManager;
};
struct ControllerParams
{
sal_Int16 nWidth;
};
typedef std::vector< ControllerParams > ControllerParamsVector;
DECL_LINK( Click, ToolBox * );
DECL_LINK( DropdownClick, ToolBox * );
DECL_LINK( DoubleClick, ToolBox * );
DECL_LINK( Select, ToolBox * );
DECL_LINK( Highlight, ToolBox * );
DECL_LINK( Activate, ToolBox * );
DECL_LINK( Deactivate, ToolBox * );
DECL_LINK( StateChanged, StateChangedType* );
DECL_LINK( DataChanged, DataChangedEvent* );
DECL_LINK( MenuButton, ToolBox * );
DECL_LINK( MenuSelect, Menu * );
DECL_LINK( MenuDeactivate, Menu * );
DECL_LINK( AsyncUpdateControllersHdl, Timer * );
DECL_STATIC_LINK( ToolBarManager, ExecuteHdl_Impl, ExecuteInfo* );
void RemoveControllers();
rtl::OUString RetrieveLabelFromCommand( const rtl::OUString& aCmdURL );
void CreateControllers( const ControllerParamsVector& );
void UpdateControllers();
void AddFrameActionListener();
void AddImageOrientationListener();
void UpdateImageOrientation();
void ImplClearPopupMenu( ToolBox *pToolBar );
void RequestImages();
sal_uInt16 ConvertStyleToToolboxItemBits( sal_Int32 nStyle );
::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > GetModelFromFrame() const;
sal_Bool IsPluginMode() const;
protected:
struct CommandInfo
{
CommandInfo() : nId( 0 ),
nImageInfo( 0 ),
bMirrored( false ),
bRotated( false ) {}
USHORT nId;
std::vector<USHORT> aIds;
sal_Int16 nImageInfo;
sal_Bool bMirrored : 1,
bRotated : 1;
};
typedef std::vector< ::com::sun::star::uno::Reference< com::sun::star::frame::XStatusListener > > ToolBarControllerVector;
typedef ::std::vector< ::com::sun::star::uno::Reference< ::com::sun::star::frame::XSubToolbarController > > SubToolBarControllerVector;
typedef BaseHash< CommandInfo > CommandToInfoMap;
typedef BaseHash< SubToolBarControllerVector > SubToolBarToSubToolBarControllerMap;
sal_Bool m_bDisposed : 1,
m_bIsHiContrast : 1,
m_bSmallSymbols : 1,
m_bModuleIdentified : 1,
m_bAddedToTaskPaneList : 1,
m_bVerticalTextEnabled : 1,
m_bFrameActionRegistered : 1,
m_bUpdateControllers : 1;
sal_Bool m_bImageOrientationRegistered : 1,
m_bImageMirrored : 1,
m_bCanBeCustomized : 1;
long m_lImageRotation;
ToolBar* m_pToolBar;
rtl::OUString m_aModuleIdentifier;
rtl::OUString m_aResourceName;
com::sun::star::uno::Reference< com::sun::star::frame::XFrame > m_xFrame;
com::sun::star::uno::Reference< com::sun::star::container::XNameAccess > m_xUICommandLabels;
ToolBarControllerVector m_aControllerVector;
::cppu::OMultiTypeInterfaceContainerHelper m_aListenerContainer; /// container for ALL Listener
::com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > m_xServiceManager;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XUIControllerRegistration > m_xToolbarControllerRegistration;
::com::sun::star::uno::Reference< ::com::sun::star::ui::XImageManager > m_xModuleImageManager;
::com::sun::star::uno::Reference< ::com::sun::star::ui::XImageManager > m_xDocImageManager;
::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > m_xImageOrientationListener;
CommandToInfoMap m_aCommandMap;
SubToolBarToSubToolBarControllerMap m_aSubToolBarControllerMap;
Timer m_aAsyncUpdateControllersTimer;
sal_Int16 m_nSymbolsStyle;
};
}
#endif // __FRAMEWORK_UIELEMENT_TOOLBARMANAGER_HXX_
<commit_msg>#100000# make types public for solaris compiler<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: toolbarmanager.hxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: vg $ $Date: 2006-04-10 10:26:15 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef __FRAMEWORK_UIELEMENT_TOOLBARMANAGER_HXX_
#define __FRAMEWORK_UIELEMENT_TOOLBARMANAGER_HXX_
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_
#include <com/sun/star/frame/XStatusListener.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_
#include <com/sun/star/container/XIndexAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_
#include <com/sun/star/frame/XModuleManager.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XUICONTROLLERREGISTRATION_HPP_
#include <com/sun/star/frame/XUIControllerRegistration.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XIMAGEMANAGER_HPP_
#include <com/sun/star/ui/XImageManager.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_
#include <com/sun/star/frame/XStatusListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSUBTOOLBARCONTROLLER_HPP_
#include <com/sun/star/frame/XSubToolbarController.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_ITEMSTYLE_HPP_
#include <com/sun/star/ui/ItemStyle.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _RTL_USTRING_
#include <rtl/ustring.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif
#include <vcl/toolbox.hxx>
namespace com
{
namespace sun
{
namespace star
{
namespace frame
{
class XLayoutManager;
}
}
}
}
namespace framework
{
class ToolBar;
class ToolBarManager : public ::com::sun::star::frame::XFrameActionListener ,
public ::com::sun::star::frame::XStatusListener ,
public ::com::sun::star::lang::XComponent ,
public ::com::sun::star::lang::XTypeProvider ,
public ::com::sun::star::ui::XUIConfigurationListener,
public ThreadHelpBase ,
public ::cppu::OWeakObject
{
public:
ToolBarManager( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rServicveManager,
const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame,
const rtl::OUString& rResourceName,
ToolBar* pToolBar );
virtual ~ToolBarManager();
// XInterface, XTypeProvider, XServiceInfo
DECLARE_XINTERFACE
DECLARE_XTYPEPROVIDER
ToolBox* GetToolBar() const;
// XFrameActionListener
virtual void SAL_CALL frameAction( const com::sun::star::frame::FrameActionEvent& Action ) throw ( ::com::sun::star::uno::RuntimeException );
// XStatusListener
virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException );
// XEventListener
virtual void SAL_CALL disposing( const com::sun::star::lang::EventObject& Source ) throw ( ::com::sun::star::uno::RuntimeException );
// XUIConfigurationListener
virtual void SAL_CALL elementInserted( const ::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL elementRemoved( const ::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL elementReplaced( const ::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException);
// XComponent
void SAL_CALL dispose() throw ( ::com::sun::star::uno::RuntimeException );
void SAL_CALL addEventListener( const com::sun::star::uno::Reference< XEventListener >& xListener ) throw( com::sun::star::uno::RuntimeException );
void SAL_CALL removeEventListener( const com::sun::star::uno::Reference< XEventListener >& xListener ) throw( com::sun::star::uno::RuntimeException );
void CheckAndUpdateImages();
void RefreshImages();
void FillToolbar( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& rToolBarData );
void notifyRegisteredControllers( const rtl::OUString& aUIElementName, const rtl::OUString& aCommand );
void Destroy();
enum ExecuteCommand
{
EXEC_CMD_CLOSETOOLBAR,
EXEC_CMD_NONE,
EXEC_CMD_COUNT
};
struct ExecuteInfo
{
rtl::OUString aToolbarResName;
ExecuteCommand nCmd;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XLayoutManager > xLayoutManager;
};
struct ControllerParams
{
sal_Int16 nWidth;
};
typedef std::vector< ControllerParams > ControllerParamsVector;
protected:
DECL_LINK( Click, ToolBox * );
DECL_LINK( DropdownClick, ToolBox * );
DECL_LINK( DoubleClick, ToolBox * );
DECL_LINK( Select, ToolBox * );
DECL_LINK( Highlight, ToolBox * );
DECL_LINK( Activate, ToolBox * );
DECL_LINK( Deactivate, ToolBox * );
DECL_LINK( StateChanged, StateChangedType* );
DECL_LINK( DataChanged, DataChangedEvent* );
DECL_LINK( MenuButton, ToolBox * );
DECL_LINK( MenuSelect, Menu * );
DECL_LINK( MenuDeactivate, Menu * );
DECL_LINK( AsyncUpdateControllersHdl, Timer * );
DECL_STATIC_LINK( ToolBarManager, ExecuteHdl_Impl, ExecuteInfo* );
void RemoveControllers();
rtl::OUString RetrieveLabelFromCommand( const rtl::OUString& aCmdURL );
void CreateControllers( const ControllerParamsVector& );
void UpdateControllers();
void AddFrameActionListener();
void AddImageOrientationListener();
void UpdateImageOrientation();
void ImplClearPopupMenu( ToolBox *pToolBar );
void RequestImages();
sal_uInt16 ConvertStyleToToolboxItemBits( sal_Int32 nStyle );
::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > GetModelFromFrame() const;
sal_Bool IsPluginMode() const;
protected:
struct CommandInfo
{
CommandInfo() : nId( 0 ),
nImageInfo( 0 ),
bMirrored( false ),
bRotated( false ) {}
USHORT nId;
std::vector<USHORT> aIds;
sal_Int16 nImageInfo;
sal_Bool bMirrored : 1,
bRotated : 1;
};
typedef std::vector< ::com::sun::star::uno::Reference< com::sun::star::frame::XStatusListener > > ToolBarControllerVector;
typedef ::std::vector< ::com::sun::star::uno::Reference< ::com::sun::star::frame::XSubToolbarController > > SubToolBarControllerVector;
typedef BaseHash< CommandInfo > CommandToInfoMap;
typedef BaseHash< SubToolBarControllerVector > SubToolBarToSubToolBarControllerMap;
sal_Bool m_bDisposed : 1,
m_bIsHiContrast : 1,
m_bSmallSymbols : 1,
m_bModuleIdentified : 1,
m_bAddedToTaskPaneList : 1,
m_bVerticalTextEnabled : 1,
m_bFrameActionRegistered : 1,
m_bUpdateControllers : 1;
sal_Bool m_bImageOrientationRegistered : 1,
m_bImageMirrored : 1,
m_bCanBeCustomized : 1;
long m_lImageRotation;
ToolBar* m_pToolBar;
rtl::OUString m_aModuleIdentifier;
rtl::OUString m_aResourceName;
com::sun::star::uno::Reference< com::sun::star::frame::XFrame > m_xFrame;
com::sun::star::uno::Reference< com::sun::star::container::XNameAccess > m_xUICommandLabels;
ToolBarControllerVector m_aControllerVector;
::cppu::OMultiTypeInterfaceContainerHelper m_aListenerContainer; /// container for ALL Listener
::com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > m_xServiceManager;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XUIControllerRegistration > m_xToolbarControllerRegistration;
::com::sun::star::uno::Reference< ::com::sun::star::ui::XImageManager > m_xModuleImageManager;
::com::sun::star::uno::Reference< ::com::sun::star::ui::XImageManager > m_xDocImageManager;
::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > m_xImageOrientationListener;
CommandToInfoMap m_aCommandMap;
SubToolBarToSubToolBarControllerMap m_aSubToolBarControllerMap;
Timer m_aAsyncUpdateControllersTimer;
sal_Int16 m_nSymbolsStyle;
};
}
#endif // __FRAMEWORK_UIELEMENT_TOOLBARMANAGER_HXX_
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2011 J-P Nurmi <[email protected]>
* Copyright (C) 2010-2011 SmokeX [email protected]
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*/
#include "ircsession.h"
#include "ircsession_p.h"
#include "ircmessage.h"
#include "ircutil.h"
#include <QTcpSocket>
#include <QStringList>
/*!
\class IrcSession ircsession.h
\brief The IrcSession class provides an IRC session.
IRC (Internet Relay Chat protocol) is a simple communication protocol.
IrcSession provides means to establish a connection to an IRC server.
IrcSession works asynchronously. None of the functions block the
calling thread but they return immediately and the actual work is done
behind the scenes in the event loop.
Example usage:
\code
IrcSession* session = new IrcSession(this);
session->setNick("jpnurmi");
session->setIdent("jpn");
session->setRealName("J-P Nurmi");
session->connectToServer("irc.freenode.net", 6667);
\endcode
\note IrcSession supports SSL (Secure Sockets Layer) connections since version 0.3.0
Example SSL usage:
\code
IrcSession* session = new IrcSession(this);
// ...
QSslSocket* socket = new QSslSocket(session);
socket->ignoreSslErrors();
socket->setPeerVerifyMode(QSslSocket::VerifyNone);
session->setSocket(socket);
session->connectToServer("irc.secure.ssl", 6669);
\endcode
\sa setSocket()
*/
/*!
\fn void IrcSession::connecting()
This signal is emitted when the connection is being established.
*/
/*!
\fn void IrcSession::connected()
This signal is emitted when the welcome message has been received.
\sa Irc::RPL_WELCOME
*/
/*!
\fn void IrcSession::disconnected()
This signal is emitted when the session has been disconnected.
*/
IrcSessionPrivate::IrcSessionPrivate(IrcSession* session) :
q_ptr(session),
parser(),
buffer(),
socket(0),
host(),
port(6667),
userName(),
nickName(),
realName()
{
}
void IrcSessionPrivate::_q_connected()
{
Q_Q(IrcSession);
emit q->connecting();
QString password;
emit q->password(&password);
if (!password.isEmpty()) {
IrcPasswordMessage passwdMsg(password);
q->sendMessage(&passwdMsg);
}
IrcNickNameMessage nickMsg(nickName);
q->sendMessage(&nickMsg);
IrcUserMessage userMsg(userName, realName);
q->sendMessage(&userMsg);
}
void IrcSessionPrivate::_q_disconnected()
{
Q_Q(IrcSession);
emit q->disconnected();
}
void IrcSessionPrivate::_q_reconnect()
{
if (socket)
{
socket->connectToHost(host, port);
if (socket->inherits("QSslSocket"))
QMetaObject::invokeMethod(socket, "startClientEncryption");
}
}
void IrcSessionPrivate::_q_error(QAbstractSocket::SocketError error)
{
qDebug() << "IrcSessionPrivate::_q_error():" << error;
}
void IrcSessionPrivate::_q_state(QAbstractSocket::SocketState state)
{
qDebug() << "IrcSessionPrivate::_q_state():" << state;
}
void IrcSessionPrivate::_q_readData()
{
buffer += socket->readAll();
// try reading RFC compliant message lines first
readLines("\r\n");
// fall back to RFC incompliant lines...
readLines("\n");
}
void IrcSessionPrivate::readLines(const QByteArray& delimiter)
{
int i = -1;
while ((i = buffer.indexOf(delimiter)) != -1)
{
QByteArray line = buffer.left(i).trimmed();
buffer = buffer.mid(i + delimiter.length());
if (!line.isEmpty())
processLine(line);
}
}
void IrcSessionPrivate::processLine(const QByteArray& line)
{
Q_Q(IrcSession);
parser.parse(line);
qDebug() << line;
QString prefix = parser.prefix();
QString command = parser.command();
QStringList params = parser.params();
IrcMessage* msg = 0;
// numeric
bool isNumeric = false;
uint code = command.toInt(&isNumeric);
if (isNumeric)
{
// connected!
if (code == Irc::RPL_WELCOME)
emit q->connected();
msg = IrcNumericMessage::create(prefix, params);
}
// error
else if (command == QLatin1String("ERROR"))
{
msg = IrcErrorMessage::create(prefix, params);
}
// handle PING/PONG
else if (command == QLatin1String("PING"))
{
msg = IrcPingMessage::create(prefix, params);
// TODO: ifAutomatic?
IrcPongMessage pong(static_cast<IrcPingMessage*>(msg)->target());
q->sendMessage(&pong);
}
// connection registration
else if (command == QLatin1String("NICK"))
{
msg = IrcNickNameMessage::create(prefix, params);
}
else if (command == QLatin1String("QUIT"))
{
msg = IrcQuitMessage::create(prefix, params);
}
// channel operations
else if (command == QLatin1String("JOIN"))
{
msg = IrcJoinMessage::create(prefix, params);
}
else if (command == QLatin1String("PART"))
{
msg = IrcPartMessage::create(prefix, params);
}
else if (command == QLatin1String("TOPIC"))
{
msg = IrcTopicMessage::create(prefix, params);
}
else if (command == QLatin1String("NAMES"))
{
msg = IrcNamesMessage::create(prefix, params);
}
else if (command == QLatin1String("LIST"))
{
msg = IrcListMessage::create(prefix, params);
}
else if (command == QLatin1String("INVITE"))
{
msg = IrcInviteMessage::create(prefix, params);
}
else if (command == QLatin1String("KICK"))
{
msg = IrcKickMessage::create(prefix, params);
}
// mode operations
else if (command == QLatin1String("MODE"))
{
if (params.value(0).startsWith(QLatin1Char('#')))
msg = IrcChannelModeMessage::create(prefix, params);
else
msg = IrcUserModeMessage::create(prefix, params);
}
// sending messages & ctcp messages
else if (command == QLatin1String("PRIVMSG"))
{
if (params.value(1).startsWith(QLatin1String("\1ACTION ")))
msg = IrcCtcpActionMessage::create(prefix, params);
else if (params.value(1).startsWith(QLatin1Char('\1')))
msg = IrcCtcpRequestMessage::create(prefix, params);
else
msg = IrcPrivateMessage::create(prefix, params);
}
else if (command == QLatin1String("NOTICE"))
{
if (params.value(1).startsWith(QLatin1Char('\1')))
msg = IrcCtcpReplyMessage::create(prefix, params);
else
msg = IrcNoticeMessage::create(prefix, params);
}
// user-based queries
else if (command == QLatin1String("WHO"))
{
msg = IrcWhoMessage::create(prefix, params);
}
else if (command == QLatin1String("WHOIS"))
{
msg = IrcWhoisMessage::create(prefix, params);
}
else if (command == QLatin1String("WHOWAS"))
{
msg = IrcWhowasMessage::create(prefix, params);
}
// unknown
else
{
msg = IrcMessage::create(prefix, params);
}
emit q->messageReceived(msg);
delete msg;
}
bool IrcSessionPrivate::isConnected() const
{
return socket &&
(socket->state() == QAbstractSocket::ConnectingState
|| socket->state() == QAbstractSocket::ConnectedState);
}
/*!
Constructs a new IRC session with \a parent.
*/
IrcSession::IrcSession(QObject* parent) : QObject(parent), d_ptr(new IrcSessionPrivate(this))
{
setSocket(new QTcpSocket(this));
}
/*!
Destructs the IRC session.
*/
IrcSession::~IrcSession()
{
Q_D(IrcSession);
if (d->socket)
d->socket->close();
}
/*!
Returns the encoding.
The default value is a null QByteArray.
*/
QByteArray IrcSession::encoding() const
{
Q_D(const IrcSession);
return d->parser.encoding();
}
/*!
Sets the \a encoding.
See QTextCodec documentation for supported encodings.
Encoding auto-detection can be turned on by passing a null QByteArray.
The fallback locale is QTextCodec::codecForLocale().
*/
void IrcSession::setEncoding(const QByteArray& encoding)
{
Q_D(IrcSession);
d->parser.setEncoding(encoding);
}
/*!
Returns the host.
*/
QString IrcSession::host() const
{
Q_D(const IrcSession);
return d->host;
}
/*!
Sets the \a host.
*/
void IrcSession::setHost(const QString& host)
{
Q_D(IrcSession);
if (d->isConnected())
qWarning("IrcSession::setHost() has no effect until re-connect");
d->host = host;
}
/*!
Returns the port.
*/
quint16 IrcSession::port() const
{
Q_D(const IrcSession);
return d->port;
}
/*!
Sets the \a port.
*/
void IrcSession::setPort(quint16 port)
{
Q_D(IrcSession);
if (d->isConnected())
qWarning("IrcSession::setPort() has no effect until re-connect");
d->port = port;
}
/*!
Returns the user name.
*/
QString IrcSession::userName() const
{
Q_D(const IrcSession);
return d->userName;
}
/*!
Sets the user \a name.
\note setUserName() has no effect on already established connection.
*/
void IrcSession::setUserName(const QString& name)
{
Q_D(IrcSession);
if (d->isConnected())
qWarning("IrcSession::setUserName() has no effect until re-connect");
d->userName = name;
}
/*!
Returns the nick name.
*/
QString IrcSession::nickName() const
{
Q_D(const IrcSession);
return d->nickName;
}
/*!
Sets the nick \a name.
*/
void IrcSession::setNickName(const QString& name)
{
Q_D(IrcSession);
if (d->nickName != name)
{
d->nickName = name;
IrcNickNameMessage msg(name);
sendMessage(&msg);
}
}
/*!
Returns the real name.
*/
QString IrcSession::realName() const
{
Q_D(const IrcSession);
return d->realName;
}
/*!
Sets the real \a name.
\note setRealName() has no effect on already established connection.
*/
void IrcSession::setRealName(const QString& name)
{
Q_D(IrcSession);
if (d->isConnected())
qWarning("IrcSession::setRealName() has no effect until re-connect");
d->realName = name;
}
/*!
Returns the socket.
IrcSession creates an instance of QTcpSocket by default.
This function was introduced in version 0.3.0.
*/
QAbstractSocket* IrcSession::socket() const
{
Q_D(const IrcSession);
return d->socket;
}
/*!
Sets the \a socket. The previously set socket is deleted if its parent is \c this.
IrcSession supports QSslSocket in the way that it automatically calls
QSslSocket::startClientEncryption() while connecting.
This function was introduced in version 0.3.0.
*/
void IrcSession::setSocket(QAbstractSocket* socket)
{
Q_D(IrcSession);
if (d->socket != socket)
{
if (d->socket)
{
d->socket->disconnect(this);
if (d->socket->parent() == this)
d->socket->deleteLater();
}
d->socket = socket;
if (socket)
{
connect(socket, SIGNAL(connected()), this, SLOT(_q_connected()));
connect(socket, SIGNAL(disconnected()), this, SLOT(_q_disconnected()));
connect(socket, SIGNAL(readyRead()), this, SLOT(_q_readData()));
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(_q_error(QAbstractSocket::SocketError)));
connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(_q_state(QAbstractSocket::SocketState)));
}
}
}
/*!
Connects to the server.
*/
void IrcSession::open()
{
Q_D(IrcSession);
if (d->userName.isEmpty())
{
qCritical("IrcSession::open(): userName is empty!");
return;
}
if (d->nickName.isEmpty())
{
qCritical("IrcSession::open(): nickName is empty!");
return;
}
if (d->realName.isEmpty())
{
qCritical("IrcSession::open(): realName is empty!");
return;
}
d->_q_reconnect();
}
/*!
Disconnects from the server.
*/
void IrcSession::close()
{
Q_D(IrcSession);
if (d->socket)
d->socket->disconnectFromHost();
}
/*!
Sends a \a message to the server.
\sa sendRaw()
*/
bool IrcSession::sendMessage(const IrcMessage* message)
{
return message && sendRaw(message->toString());
}
/*!
Sends a raw \a message to the server.
\sa sendMessage()
*/
bool IrcSession::sendRaw(const QString& message)
{
Q_D(IrcSession);
qint64 bytes = -1;
if (d->socket)
bytes = d->socket->write(message.toUtf8() + QByteArray("\r\n"));
return bytes != -1;
}
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug debug, const IrcSession* session)
{
if (!session)
return debug << "IrcSession(0x0) ";
debug.nospace() << session->metaObject()->className() << '(' << (void*) session;
if (!session->objectName().isEmpty())
debug << ", name = " << session->objectName();
if (!session->host().isEmpty())
debug << ", host = " << session->host()
<< ", port = " << session->port();
debug << ')';
return debug.space();
}
#endif // QT_NO_DEBUG_STREAM
#include "moc_ircsession.cpp"
<commit_msg>IrcSession::processLine() shaping up...<commit_after>/*
* Copyright (C) 2008-2011 J-P Nurmi <[email protected]>
* Copyright (C) 2010-2011 SmokeX [email protected]
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*/
#include "ircsession.h"
#include "ircsession_p.h"
#include "ircmessage.h"
#include "ircutil.h"
#include <QTcpSocket>
#include <QStringList>
/*!
\class IrcSession ircsession.h
\brief The IrcSession class provides an IRC session.
IRC (Internet Relay Chat protocol) is a simple communication protocol.
IrcSession provides means to establish a connection to an IRC server.
IrcSession works asynchronously. None of the functions block the
calling thread but they return immediately and the actual work is done
behind the scenes in the event loop.
Example usage:
\code
IrcSession* session = new IrcSession(this);
session->setNick("jpnurmi");
session->setIdent("jpn");
session->setRealName("J-P Nurmi");
session->connectToServer("irc.freenode.net", 6667);
\endcode
\note IrcSession supports SSL (Secure Sockets Layer) connections since version 0.3.0
Example SSL usage:
\code
IrcSession* session = new IrcSession(this);
// ...
QSslSocket* socket = new QSslSocket(session);
socket->ignoreSslErrors();
socket->setPeerVerifyMode(QSslSocket::VerifyNone);
session->setSocket(socket);
session->connectToServer("irc.secure.ssl", 6669);
\endcode
\sa setSocket()
*/
/*!
\fn void IrcSession::connecting()
This signal is emitted when the connection is being established.
*/
/*!
\fn void IrcSession::connected()
This signal is emitted when the welcome message has been received.
\sa Irc::RPL_WELCOME
*/
/*!
\fn void IrcSession::disconnected()
This signal is emitted when the session has been disconnected.
*/
IrcSessionPrivate::IrcSessionPrivate(IrcSession* session) :
q_ptr(session),
parser(),
buffer(),
socket(0),
host(),
port(6667),
userName(),
nickName(),
realName()
{
}
void IrcSessionPrivate::_q_connected()
{
Q_Q(IrcSession);
emit q->connecting();
QString password;
emit q->password(&password);
if (!password.isEmpty()) {
IrcPasswordMessage passwdMsg;
passwdMsg.setPassword(password);
q->sendMessage(&passwdMsg);
}
IrcNickNameMessage nickMsg;
nickMsg.setNickName(nickName);
q->sendMessage(&nickMsg);
IrcUserMessage userMsg;
userMsg.setUserName(userName);
userMsg.setRealName(realName);
q->sendMessage(&userMsg);
}
void IrcSessionPrivate::_q_disconnected()
{
Q_Q(IrcSession);
emit q->disconnected();
}
void IrcSessionPrivate::_q_reconnect()
{
if (socket)
{
socket->connectToHost(host, port);
if (socket->inherits("QSslSocket"))
QMetaObject::invokeMethod(socket, "startClientEncryption");
}
}
void IrcSessionPrivate::_q_error(QAbstractSocket::SocketError error)
{
qDebug() << "IrcSessionPrivate::_q_error():" << error;
}
void IrcSessionPrivate::_q_state(QAbstractSocket::SocketState state)
{
qDebug() << "IrcSessionPrivate::_q_state():" << state;
}
void IrcSessionPrivate::_q_readData()
{
buffer += socket->readAll();
// try reading RFC compliant message lines first
readLines("\r\n");
// fall back to RFC incompliant lines...
readLines("\n");
}
void IrcSessionPrivate::readLines(const QByteArray& delimiter)
{
int i = -1;
while ((i = buffer.indexOf(delimiter)) != -1)
{
QByteArray line = buffer.left(i).trimmed();
buffer = buffer.mid(i + delimiter.length());
if (!line.isEmpty())
processLine(line);
}
}
void IrcSessionPrivate::processLine(const QByteArray& line)
{
Q_Q(IrcSession);
parser.parse(line);
qDebug() << line;
QString prefix = parser.prefix();
QString command = parser.command();
QStringList params = parser.params();
IrcMessage* msg = IrcMessage::create(command);
if (msg)
{
msg->initFrom(prefix, params);
switch (msg->type())
{
case IrcMessage::Numeric:
if (static_cast<IrcNumericMessage*>(msg)->code() == Irc::RPL_WELCOME)
emit q->connected();
break;
case IrcMessage::Ping: {
// TODO: ifAutomatic?
IrcPongMessage pongMsg;
pongMsg.setTarget(static_cast<IrcPingMessage*>(msg)->target());
q->sendMessage(&pongMsg);
break;
}
}
// TODO: mode operations
/*else if (command == QLatin1String("MODE"))
{
if (params.value(0).startsWith(QLatin1Char('#')))
msg = IrcChannelModeMessage::create(prefix, params);
else
msg = IrcUserModeMessage::create(prefix, params);
}*/
// TODO: sending messages & ctcp messages
/*else if (command == QLatin1String("PRIVMSG"))
{
if (params.value(1).startsWith(QLatin1String("\1ACTION ")))
msg = IrcCtcpActionMessage::create(prefix, params);
else if (params.value(1).startsWith(QLatin1Char('\1')))
msg = IrcCtcpRequestMessage::create(prefix, params);
else
msg = IrcPrivateMessage::create(prefix, params);
}
else if (command == QLatin1String("NOTICE"))
{
if (params.value(1).startsWith(QLatin1Char('\1')))
msg = IrcCtcpReplyMessage::create(prefix, params);
else
msg = IrcNoticeMessage::create(prefix, params);
}*/
emit q->messageReceived(msg);
msg->deleteLater();
}
}
bool IrcSessionPrivate::isConnected() const
{
return socket &&
(socket->state() == QAbstractSocket::ConnectingState
|| socket->state() == QAbstractSocket::ConnectedState);
}
/*!
Constructs a new IRC session with \a parent.
*/
IrcSession::IrcSession(QObject* parent) : QObject(parent), d_ptr(new IrcSessionPrivate(this))
{
setSocket(new QTcpSocket(this));
}
/*!
Destructs the IRC session.
*/
IrcSession::~IrcSession()
{
Q_D(IrcSession);
if (d->socket)
d->socket->close();
}
/*!
Returns the encoding.
The default value is a null QByteArray.
*/
QByteArray IrcSession::encoding() const
{
Q_D(const IrcSession);
return d->parser.encoding();
}
/*!
Sets the \a encoding.
See QTextCodec documentation for supported encodings.
Encoding auto-detection can be turned on by passing a null QByteArray.
The fallback locale is QTextCodec::codecForLocale().
*/
void IrcSession::setEncoding(const QByteArray& encoding)
{
Q_D(IrcSession);
d->parser.setEncoding(encoding);
}
/*!
Returns the host.
*/
QString IrcSession::host() const
{
Q_D(const IrcSession);
return d->host;
}
/*!
Sets the \a host.
*/
void IrcSession::setHost(const QString& host)
{
Q_D(IrcSession);
if (d->isConnected())
qWarning("IrcSession::setHost() has no effect until re-connect");
d->host = host;
}
/*!
Returns the port.
*/
quint16 IrcSession::port() const
{
Q_D(const IrcSession);
return d->port;
}
/*!
Sets the \a port.
*/
void IrcSession::setPort(quint16 port)
{
Q_D(IrcSession);
if (d->isConnected())
qWarning("IrcSession::setPort() has no effect until re-connect");
d->port = port;
}
/*!
Returns the user name.
*/
QString IrcSession::userName() const
{
Q_D(const IrcSession);
return d->userName;
}
/*!
Sets the user \a name.
\note setUserName() has no effect on already established connection.
*/
void IrcSession::setUserName(const QString& name)
{
Q_D(IrcSession);
if (d->isConnected())
qWarning("IrcSession::setUserName() has no effect until re-connect");
d->userName = name;
}
/*!
Returns the nick name.
*/
QString IrcSession::nickName() const
{
Q_D(const IrcSession);
return d->nickName;
}
/*!
Sets the nick \a name.
*/
void IrcSession::setNickName(const QString& name)
{
Q_D(IrcSession);
if (d->nickName != name)
{
d->nickName = name;
IrcNickNameMessage msg;
msg.setNickName(name);
sendMessage(&msg);
}
}
/*!
Returns the real name.
*/
QString IrcSession::realName() const
{
Q_D(const IrcSession);
return d->realName;
}
/*!
Sets the real \a name.
\note setRealName() has no effect on already established connection.
*/
void IrcSession::setRealName(const QString& name)
{
Q_D(IrcSession);
if (d->isConnected())
qWarning("IrcSession::setRealName() has no effect until re-connect");
d->realName = name;
}
/*!
Returns the socket.
IrcSession creates an instance of QTcpSocket by default.
This function was introduced in version 0.3.0.
*/
QAbstractSocket* IrcSession::socket() const
{
Q_D(const IrcSession);
return d->socket;
}
/*!
Sets the \a socket. The previously set socket is deleted if its parent is \c this.
IrcSession supports QSslSocket in the way that it automatically calls
QSslSocket::startClientEncryption() while connecting.
This function was introduced in version 0.3.0.
*/
void IrcSession::setSocket(QAbstractSocket* socket)
{
Q_D(IrcSession);
if (d->socket != socket)
{
if (d->socket)
{
d->socket->disconnect(this);
if (d->socket->parent() == this)
d->socket->deleteLater();
}
d->socket = socket;
if (socket)
{
connect(socket, SIGNAL(connected()), this, SLOT(_q_connected()));
connect(socket, SIGNAL(disconnected()), this, SLOT(_q_disconnected()));
connect(socket, SIGNAL(readyRead()), this, SLOT(_q_readData()));
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(_q_error(QAbstractSocket::SocketError)));
connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(_q_state(QAbstractSocket::SocketState)));
}
}
}
/*!
Connects to the server.
*/
void IrcSession::open()
{
Q_D(IrcSession);
if (d->userName.isEmpty())
{
qCritical("IrcSession::open(): userName is empty!");
return;
}
if (d->nickName.isEmpty())
{
qCritical("IrcSession::open(): nickName is empty!");
return;
}
if (d->realName.isEmpty())
{
qCritical("IrcSession::open(): realName is empty!");
return;
}
d->_q_reconnect();
}
/*!
Disconnects from the server.
*/
void IrcSession::close()
{
Q_D(IrcSession);
if (d->socket)
d->socket->disconnectFromHost();
}
/*!
Sends a \a message to the server.
\sa sendRaw()
*/
bool IrcSession::sendMessage(const IrcMessage* message)
{
return message && sendRaw(message->toString());
}
/*!
Sends a raw \a message to the server.
\sa sendMessage()
*/
bool IrcSession::sendRaw(const QString& message)
{
Q_D(IrcSession);
qint64 bytes = -1;
if (d->socket)
bytes = d->socket->write(message.toUtf8() + QByteArray("\r\n"));
return bytes != -1;
}
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug debug, const IrcSession* session)
{
if (!session)
return debug << "IrcSession(0x0) ";
debug.nospace() << session->metaObject()->className() << '(' << (void*) session;
if (!session->objectName().isEmpty())
debug << ", name = " << session->objectName();
if (!session->host().isEmpty())
debug << ", host = " << session->host()
<< ", port = " << session->port();
debug << ')';
return debug.space();
}
#endif // QT_NO_DEBUG_STREAM
#include "moc_ircsession.cpp"
<|endoftext|> |
<commit_before>/* Copyright (C) 2018, Project Pluto. See LICENSE. */
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __has_include
#if __has_include(<cgi_func.h>)
#include "cgi_func.h"
#else
#error \
'cgi_func.h' not found. This project depends on the 'lunar'\
library. See www.github.com/Bill-Gray/lunar .\
Clone that repository, 'make' and 'make install' it.
#endif
#else
#include "cgi_func.h"
#endif
#include "watdefs.h"
int sat_id_main( const int argc, const char **argv);
int main( const int unused_argc, const char **unused_argv)
{
const char *argv[20];
const size_t max_buff_size = 40000; /* room for 500 obs */
char *buff = (char *)malloc( max_buff_size), *tptr;
char field[30];
const char *temp_obs_filename = "sat_obs.txt";
double search_radius = 4.; /* look 4 degrees for matches */
double motion_cutoff = 20.; /* up to 20" discrepancy OK */
double low_speed_cutoff = 0.001; /* anything slower than this is almost */
const int argc = 6; /* certainly not an artsat */
FILE *lock_file = fopen( "lock.txt", "w");
size_t bytes_written = 0;
int cgi_status;
extern int verbose;
#ifndef _WIN32
extern char **environ;
avoid_runaway_process( 15);
#endif /* _WIN32 */
setbuf( lock_file, NULL);
INTENTIONALLY_UNUSED_PARAMETER( unused_argc);
INTENTIONALLY_UNUSED_PARAMETER( unused_argv);
printf( "Content-type: text/html\n\n");
printf( "<html> <body> <pre>\n");
if( !lock_file)
{
printf( "<p> Server is busy. Try again in a minute or two. </p>");
printf( "<p> Your orbit is very important to us! </p>");
return( 0);
}
fprintf( lock_file, "We're in\n");
#ifndef _WIN32
for( size_t i = 0; environ[i]; i++)
fprintf( lock_file, "%s\n", environ[i]);
#endif
cgi_status = initialize_cgi_reading( );
fprintf( lock_file, "CGI status %d\n", cgi_status);
if( cgi_status <= 0)
{
printf( "<p> <b> CGI data reading failed : error %d </b>", cgi_status);
printf( "This isn't supposed to happen.</p>\n");
return( 0);
}
while( !get_cgi_data( field, buff, NULL, max_buff_size))
{
// fprintf( lock_file, "Field '%s'\n", field);
if( !strcmp( field, "TextArea") || !strcmp( field, "upfile"))
{
if( strlen( buff) > 70)
{
FILE *ofile = fopen( temp_obs_filename,
(bytes_written ? "ab" : "wb"));
fprintf( lock_file, "File opened : %p\n", (void *)ofile);
if( !ofile)
{
printf( "<p> Couldn't open %s : %s </p>\n", temp_obs_filename, strerror( errno));
fprintf( lock_file, "Couldn't open %s: %s\n", temp_obs_filename, strerror( errno));
return( -1);
}
bytes_written += fwrite( buff, 1, strlen( buff), ofile);
fclose( ofile);
}
}
if( !strcmp( field, "radius"))
{
const char *verbosity = strchr( buff, 'v');
search_radius = atof( buff);
if( verbosity)
verbose = atoi( verbosity + 1) + 1;
}
// if( !strcmp( field, "motion"))
// motion_cutoff = atof( buff);
// if( !strcmp( field, "low_speed"))
// low_speed_cutoff = atof( buff);
}
fprintf( lock_file, "Fields read\n");
// printf( "<p>Fields read</p>\n");
if( verbose)
printf( "Searching to %f degrees; %u bytes read from input\n",
search_radius, (unsigned)bytes_written);
argv[0] = "sat_id";
argv[1] = temp_obs_filename;
argv[2] = "-t../../tles/tle_list.txt";
sprintf( field, "-r%.2f", search_radius);
argv[3] = field;
sprintf( buff, "-y%f", motion_cutoff);
argv[4] = buff;
tptr = buff + strlen( buff) + 1;
sprintf( tptr, "-z%f", low_speed_cutoff);
argv[5] = tptr;
argv[6] = NULL;
sat_id_main( argc, argv);
free( buff);
printf( "On-line Sat_ID compiled " __DATE__ " " __TIME__ " UTC-5h\n");
printf( "See <a href='https://www.github.com/Bill-Gray/sat_code'>"
"https://www.github.com/Bill-Gray/sat_code</a> for source code\n");
printf( "</pre> </body> </html>");
return( 0);
}
<commit_msg>Added some debugging statements for on-line Sat_ID<commit_after>/* Copyright (C) 2018, Project Pluto. See LICENSE. */
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __has_include
#if __has_include(<cgi_func.h>)
#include "cgi_func.h"
#else
#error \
'cgi_func.h' not found. This project depends on the 'lunar'\
library. See www.github.com/Bill-Gray/lunar .\
Clone that repository, 'make' and 'make install' it.
#endif
#else
#include "cgi_func.h"
#endif
#include "watdefs.h"
int sat_id_main( const int argc, const char **argv);
int main( const int unused_argc, const char **unused_argv)
{
const char *argv[20];
const size_t max_buff_size = 40000; /* room for 500 obs */
char *buff = (char *)malloc( max_buff_size), *tptr;
char field[30];
const char *temp_obs_filename = "sat_obs.txt";
double search_radius = 4.; /* look 4 degrees for matches */
double motion_cutoff = 20.; /* up to 20" discrepancy OK */
double low_speed_cutoff = 0.001; /* anything slower than this is almost */
const int argc = 6; /* certainly not an artsat */
FILE *lock_file = fopen( "lock.txt", "w");
size_t bytes_written = 0, i;
int cgi_status;
extern int verbose;
#ifndef _WIN32
extern char **environ;
avoid_runaway_process( 15);
#endif /* _WIN32 */
setbuf( lock_file, NULL);
INTENTIONALLY_UNUSED_PARAMETER( unused_argc);
INTENTIONALLY_UNUSED_PARAMETER( unused_argv);
printf( "Content-type: text/html\n\n");
printf( "<html> <body> <pre>\n");
if( !lock_file)
{
printf( "<p> Server is busy. Try again in a minute or two. </p>");
printf( "<p> Your orbit is very important to us! </p>");
return( 0);
}
fprintf( lock_file, "We're in\n");
#ifndef _WIN32
for( size_t i = 0; environ[i]; i++)
fprintf( lock_file, "%s\n", environ[i]);
#endif
cgi_status = initialize_cgi_reading( );
fprintf( lock_file, "CGI status %d\n", cgi_status);
if( cgi_status <= 0)
{
printf( "<p> <b> CGI data reading failed : error %d </b>", cgi_status);
printf( "This isn't supposed to happen.</p>\n");
return( 0);
}
while( !get_cgi_data( field, buff, NULL, max_buff_size))
{
fprintf( lock_file, "Field '%s'\n", field);
if( !strcmp( field, "TextArea") || !strcmp( field, "upfile"))
{
if( strlen( buff) > 70)
{
FILE *ofile = fopen( temp_obs_filename,
(bytes_written ? "ab" : "wb"));
fprintf( lock_file, "File opened : %p\n", (void *)ofile);
if( !ofile)
{
printf( "<p> Couldn't open %s : %s </p>\n", temp_obs_filename, strerror( errno));
fprintf( lock_file, "Couldn't open %s: %s\n", temp_obs_filename, strerror( errno));
return( -1);
}
bytes_written += fwrite( buff, 1, strlen( buff), ofile);
fclose( ofile);
}
}
if( !strcmp( field, "radius"))
{
const char *verbosity = strchr( buff, 'v');
search_radius = atof( buff);
if( verbosity)
verbose = atoi( verbosity + 1) + 1;
}
// if( !strcmp( field, "motion"))
// motion_cutoff = atof( buff);
// if( !strcmp( field, "low_speed"))
// low_speed_cutoff = atof( buff);
}
fprintf( lock_file, "Fields read\n");
// printf( "<p>Fields read</p>\n");
if( verbose)
printf( "Searching to %f degrees; %u bytes read from input\n",
search_radius, (unsigned)bytes_written);
argv[0] = "sat_id";
argv[1] = temp_obs_filename;
argv[2] = "-t../../tles/tle_list.txt";
sprintf( field, "-r%.2f", search_radius);
argv[3] = field;
sprintf( buff, "-y%f", motion_cutoff);
argv[4] = buff;
tptr = buff + strlen( buff) + 1;
sprintf( tptr, "-z%f", low_speed_cutoff);
argv[5] = tptr;
argv[6] = NULL;
for( i = 0; argv[i]; i++)
fprintf( lock_file, "arg %d: '%s'\n", (int)i, argv[i]);
sat_id_main( argc, argv);
fprintf( lock_file, "sat_id_main called\n");
free( buff);
printf( "On-line Sat_ID compiled " __DATE__ " " __TIME__ " UTC-5h\n");
printf( "See <a href='https://www.github.com/Bill-Gray/sat_code'>"
"https://www.github.com/Bill-Gray/sat_code</a> for source code\n");
printf( "</pre> </body> </html>");
return( 0);
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
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 author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_CHAINED_BUFFER_HPP_INCLUDED
#define TORRENT_CHAINED_BUFFER_HPP_INCLUDED
#include <boost/function/function1.hpp>
#include <boost/version.hpp>
#if BOOST_VERSION < 103500
#include <asio/buffer.hpp>
#else
#include <boost/asio/buffer.hpp>
#endif
#include <list>
#include <cstring>
namespace libtorrent
{
#if BOOST_VERSION >= 103500
namespace asio = boost::asio;
#endif
struct chained_buffer
{
chained_buffer(): m_bytes(0), m_capacity(0) {}
struct buffer_t
{
boost::function<void(char*)> free; // destructs the buffer
char* buf; // the first byte of the buffer
int size; // the total size of the buffer
char* start; // the first byte to send/receive in the buffer
int used_size; // this is the number of bytes to send/receive
};
bool empty() const { return m_bytes == 0; }
int size() const { return m_bytes; }
int capacity() const { return m_capacity; }
void pop_front(int bytes_to_pop)
{
TORRENT_ASSERT(bytes_to_pop <= m_bytes);
while (bytes_to_pop > 0 && !m_vec.empty())
{
buffer_t& b = m_vec.front();
if (b.used_size > bytes_to_pop)
{
b.start += bytes_to_pop;
b.used_size -= bytes_to_pop;
m_bytes -= bytes_to_pop;
TORRENT_ASSERT(m_bytes <= m_capacity);
TORRENT_ASSERT(m_bytes >= 0);
TORRENT_ASSERT(m_capacity >= 0);
break;
}
b.free(b.buf);
m_bytes -= b.used_size;
m_capacity -= b.size;
bytes_to_pop -= b.used_size;
TORRENT_ASSERT(m_bytes >= 0);
TORRENT_ASSERT(m_capacity >= 0);
TORRENT_ASSERT(m_bytes <= m_capacity);
m_vec.pop_front();
}
}
template <class D>
void append_buffer(char* buffer, int s, int used_size, D const& destructor)
{
TORRENT_ASSERT(s >= used_size);
buffer_t b;
b.buf = buffer;
b.size = s;
b.start = buffer;
b.used_size = used_size;
b.free = destructor;
m_vec.push_back(b);
m_bytes += used_size;
m_capacity += s;
TORRENT_ASSERT(m_bytes <= m_capacity);
}
// returns the number of bytes available at the
// end of the last chained buffer.
int space_in_last_buffer()
{
if (m_vec.empty()) return 0;
buffer_t& b = m_vec.back();
return b.size - b.used_size - (b.start - b.buf);
}
// tries to copy the given buffer to the end of the
// last chained buffer. If there's not enough room
// it returns false
bool append(char const* buf, int s)
{
char* insert = allocate_appendix(s);
if (insert == 0) return false;
std::memcpy(insert, buf, s);
return true;
}
// tries to allocate memory from the end
// of the last buffer. If there isn't
// enough room, returns 0
char* allocate_appendix(int s)
{
if (m_vec.empty()) return 0;
buffer_t& b = m_vec.back();
char* insert = b.start + b.used_size;
if (insert + s > b.buf + b.size) return 0;
b.used_size += s;
m_bytes += s;
TORRENT_ASSERT(m_bytes <= m_capacity);
return insert;
}
std::list<asio::const_buffer> const& build_iovec(int to_send)
{
m_tmp_vec.clear();
for (std::list<buffer_t>::iterator i = m_vec.begin()
, end(m_vec.end()); to_send > 0 && i != end; ++i)
{
if (i->used_size > to_send)
{
TORRENT_ASSERT(to_send > 0);
m_tmp_vec.push_back(asio::const_buffer(i->start, to_send));
break;
}
TORRENT_ASSERT(i->used_size > 0);
m_tmp_vec.push_back(asio::const_buffer(i->start, i->used_size));
to_send -= i->used_size;
}
return m_tmp_vec;
}
~chained_buffer()
{
for (std::list<buffer_t>::iterator i = m_vec.begin()
, end(m_vec.end()); i != end; ++i)
{
i->free(i->buf);
}
}
private:
// this is the list of all the buffers we want to
// send
std::list<buffer_t> m_vec;
// this is the number of bytes in the send buf.
// this will always be equal to the sum of the
// size of all buffers in vec
int m_bytes;
// the total size of all buffers in the chain
// including unused space
int m_capacity;
// this is the vector of buffers used when
// invoking the async write call
std::list<asio::const_buffer> m_tmp_vec;
};
}
#endif
<commit_msg>use memcpy() instead of std::memcpy()<commit_after>/*
Copyright (c) 2007, Arvid Norberg
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 author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_CHAINED_BUFFER_HPP_INCLUDED
#define TORRENT_CHAINED_BUFFER_HPP_INCLUDED
#include <boost/function/function1.hpp>
#include <boost/version.hpp>
#if BOOST_VERSION < 103500
#include <asio/buffer.hpp>
#else
#include <boost/asio/buffer.hpp>
#endif
#include <list>
#include <string.h> // for memcpy
namespace libtorrent
{
#if BOOST_VERSION >= 103500
namespace asio = boost::asio;
#endif
struct chained_buffer
{
chained_buffer(): m_bytes(0), m_capacity(0) {}
struct buffer_t
{
boost::function<void(char*)> free; // destructs the buffer
char* buf; // the first byte of the buffer
int size; // the total size of the buffer
char* start; // the first byte to send/receive in the buffer
int used_size; // this is the number of bytes to send/receive
};
bool empty() const { return m_bytes == 0; }
int size() const { return m_bytes; }
int capacity() const { return m_capacity; }
void pop_front(int bytes_to_pop)
{
TORRENT_ASSERT(bytes_to_pop <= m_bytes);
while (bytes_to_pop > 0 && !m_vec.empty())
{
buffer_t& b = m_vec.front();
if (b.used_size > bytes_to_pop)
{
b.start += bytes_to_pop;
b.used_size -= bytes_to_pop;
m_bytes -= bytes_to_pop;
TORRENT_ASSERT(m_bytes <= m_capacity);
TORRENT_ASSERT(m_bytes >= 0);
TORRENT_ASSERT(m_capacity >= 0);
break;
}
b.free(b.buf);
m_bytes -= b.used_size;
m_capacity -= b.size;
bytes_to_pop -= b.used_size;
TORRENT_ASSERT(m_bytes >= 0);
TORRENT_ASSERT(m_capacity >= 0);
TORRENT_ASSERT(m_bytes <= m_capacity);
m_vec.pop_front();
}
}
template <class D>
void append_buffer(char* buffer, int s, int used_size, D const& destructor)
{
TORRENT_ASSERT(s >= used_size);
buffer_t b;
b.buf = buffer;
b.size = s;
b.start = buffer;
b.used_size = used_size;
b.free = destructor;
m_vec.push_back(b);
m_bytes += used_size;
m_capacity += s;
TORRENT_ASSERT(m_bytes <= m_capacity);
}
// returns the number of bytes available at the
// end of the last chained buffer.
int space_in_last_buffer()
{
if (m_vec.empty()) return 0;
buffer_t& b = m_vec.back();
return b.size - b.used_size - (b.start - b.buf);
}
// tries to copy the given buffer to the end of the
// last chained buffer. If there's not enough room
// it returns false
bool append(char const* buf, int s)
{
char* insert = allocate_appendix(s);
if (insert == 0) return false;
memcpy(insert, buf, s);
return true;
}
// tries to allocate memory from the end
// of the last buffer. If there isn't
// enough room, returns 0
char* allocate_appendix(int s)
{
if (m_vec.empty()) return 0;
buffer_t& b = m_vec.back();
char* insert = b.start + b.used_size;
if (insert + s > b.buf + b.size) return 0;
b.used_size += s;
m_bytes += s;
TORRENT_ASSERT(m_bytes <= m_capacity);
return insert;
}
std::list<asio::const_buffer> const& build_iovec(int to_send)
{
m_tmp_vec.clear();
for (std::list<buffer_t>::iterator i = m_vec.begin()
, end(m_vec.end()); to_send > 0 && i != end; ++i)
{
if (i->used_size > to_send)
{
TORRENT_ASSERT(to_send > 0);
m_tmp_vec.push_back(asio::const_buffer(i->start, to_send));
break;
}
TORRENT_ASSERT(i->used_size > 0);
m_tmp_vec.push_back(asio::const_buffer(i->start, i->used_size));
to_send -= i->used_size;
}
return m_tmp_vec;
}
~chained_buffer()
{
for (std::list<buffer_t>::iterator i = m_vec.begin()
, end(m_vec.end()); i != end; ++i)
{
i->free(i->buf);
}
}
private:
// this is the list of all the buffers we want to
// send
std::list<buffer_t> m_vec;
// this is the number of bytes in the send buf.
// this will always be equal to the sum of the
// size of all buffers in vec
int m_bytes;
// the total size of all buffers in the chain
// including unused space
int m_capacity;
// this is the vector of buffers used when
// invoking the async write call
std::list<asio::const_buffer> m_tmp_vec;
};
}
#endif
<|endoftext|> |
<commit_before>#include<iostream>
#include<stdio.h>
#include<string>
#include<math.h>
#include<vector>
#include<ctime>
#include<opencv2/opencv.hpp>
using namespace cv;
using namespace std;
typedef struct
{
int x;
int y;
float b;
float g;
float r;
}Tuple;
bool Isequal(vector<Tuple> a, vector<Tuple> b)
{
int s = a.size();
for (int i = 0; i < s; i++)
{
if (a[i].x == b[i].x&&a[i].y == b[i].y&&a[i].r == b[i].r&&a[i].g == b[i].g&&a[i].b == b[i].b)
continue;
else
return false;
}
return true;
}
int main()
{
srand(time(0));
Mat src = imread("/Users/frank/workspace/github/c_practice/opencv/image/test.jpg"); //图片地址
imshow("input", src);
int width = src.cols;
int height = src.rows;
int dims = src.channels();
Tuple t;
//Kmeans//
vector<Tuple> sum_points;
vector<Tuple> points;
int K = 6;
int temp_K = K;
//图中所点存入sum_points
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
Vec3b rgb = src.at<Vec3b>(i, j);
t.x = j;
t.y = i;
t.b = (float)(rgb[0]);
t.g = (float)(rgb[1]);
t.r = (float)(rgb[2]);
sum_points.push_back(t);
}
}
// 随机K个点
for (; temp_K > 0; temp_K--)
{
int w = rand() % (width);
int h = rand() % (height);
Vec3b rgb = src.at<Vec3b>(w, h);
Tuple temppoint;
temppoint.x = w;
temppoint.y = h;
temppoint.b = (float)(rgb[0]);
temppoint.g = (float)(rgb[1]);
temppoint.r = (float)(rgb[2]);
points.push_back(temppoint);
}
// 记录label值
vector<int> label(sum_points.size(), 0);
// 每次更新迭代的质心点坐标
vector<Tuple> new_points(points.size());
// 记录迭代多少次
int index = 0;
do
{
if (index != 0)
{
for (int i = 0; i < points.size(); i++)
{
points[i].x = new_points[i].x;
points[i].y = new_points[i].y;
points[i].b = new_points[i].b;
points[i].r = new_points[i].r;
points[i].g = new_points[i].g;
}
}
// 欧式距离判断并更新质心点位置
// 1、欧式距离计算分类
for (int j = 0; j < sum_points.size(); j++)
{
float min_distance = float(INT_MAX);
for (int i = 0; i < points.size(); i++)
{
float distance = sqrt((float)pow((sum_points[j].b - points[i].b), 2) + pow((sum_points[j].g - points[i].g), 2) + pow((sum_points[j].r - points[i].r), 2));
if (distance < min_distance)
//if (distance < 1)
{
min_distance = distance;
label[j] = i;
}
}
}
// 2、更新质心的坐标点(通过label值)
// 定义k类分别的点值变量
vector<int> k(points.size(), 0);
vector<float> b(points.size(), 0.0);
vector<float> g(points.size(), 0.0);
vector<float> r(points.size(), 0.0);
for (int i = 0; i < label.size(); i++)
{
for (int j = 0; j < points.size(); j++)
{
// 找到对应的类别进行后续的质心坐标运算
if (j == label[i])
{
k[j]++;
b[j] += sum_points[i].b;
g[j] += sum_points[i].g;
r[j] += sum_points[i].r;
break;
}
}
}
// 更新坐标
for (int i = 0; i < points.size(); i++)
{
b[i] /= k[i];
g[i] /= k[i];
r[i] /= k[i];
}
// 质心坐标值填补
for (int i = 0; i < points.size(); i++)
{
Tuple temp;
temp.x = 0;
temp.y = 0;
temp.b = b[i];
temp.g = g[i];
temp.r = r[i];
new_points[i] = temp;
}
index++;
} while (!Isequal(points,new_points));
Mat result = Mat::zeros(src.size(), CV_8UC3);
for (int i = 0; i < sum_points.size(); i++)
{
sum_points[i].b = points[label[i]].b;
sum_points[i].g = points[label[i]].g;
sum_points[i].r = points[label[i]].r;
}
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
result.at<Vec3b>(i, j)[0] = sum_points[j+i*width].b;
result.at<Vec3b>(i, j)[1] = sum_points[j + i * width].g;
result.at<Vec3b>(i, j)[2] = sum_points[j + i * width].r;
}
}
imshow("kmeans-demo", result);
waitKey(0);
return 0;
}<commit_msg>修改代码,在osx上显示图片<commit_after>#include<iostream>
#include<stdio.h>
#include<string>
#include<math.h>
#include<vector>
#include<ctime>
#include<opencv2/opencv.hpp>
using namespace cv;
using namespace std;
typedef struct
{
int x;
int y;
float b;
float g;
float r;
}Tuple;
bool Isequal(vector<Tuple> a, vector<Tuple> b)
{
int s = a.size();
for (int i = 0; i < s; i++)
{
if (a[i].x == b[i].x&&a[i].y == b[i].y&&a[i].r == b[i].r&&a[i].g == b[i].g&&a[i].b == b[i].b)
continue;
else
return false;
}
return true;
}
int main()
{
srand(time(0));
// 图片地址
Mat src = imread("/Users/frank/workspace/github/c_practice/opencv/image/test.jpg", 1);
if (src.empty())
{
cout << "Error : Image cannot be loaded..!!" << endl;
return -1;
}
else
{
namedWindow("MyWindow", 0);
imshow("MyWindow", src);
waitKey(5000);
}
int width = src.cols;
int height = src.rows;
int dims = src.channels();
Tuple t;
// Kmeans
vector<Tuple> sum_points;
vector<Tuple> points;
int K = 6;
int temp_K = K;
// 图中所点存入sum_points
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
Vec3b rgb = src.at<Vec3b>(i, j);
t.x = j;
t.y = i;
t.b = (float)(rgb[0]);
t.g = (float)(rgb[1]);
t.r = (float)(rgb[2]);
sum_points.push_back(t);
}
}
// 随机K个点
for (; temp_K > 0; temp_K--)
{
int w = rand() % (width);
int h = rand() % (height);
Vec3b rgb = src.at<Vec3b>(w, h);
Tuple temppoint;
temppoint.x = w;
temppoint.y = h;
temppoint.b = (float)(rgb[0]);
temppoint.g = (float)(rgb[1]);
temppoint.r = (float)(rgb[2]);
points.push_back(temppoint);
}
// 记录label值
vector<int> label(sum_points.size(), 0);
// 每次更新迭代的质心点坐标
vector<Tuple> new_points(points.size());
// 记录迭代多少次
int index = 0;
do
{
if (index != 0)
{
for (int i = 0; i < points.size(); i++)
{
points[i].x = new_points[i].x;
points[i].y = new_points[i].y;
points[i].b = new_points[i].b;
points[i].r = new_points[i].r;
points[i].g = new_points[i].g;
}
}
// 欧式距离判断并更新质心点位置
// 1、欧式距离计算分类
for (int j = 0; j < sum_points.size(); j++)
{
float min_distance = float(INT_MAX);
for (int i = 0; i < points.size(); i++)
{
float distance = sqrt((float)pow((sum_points[j].b - points[i].b), 2) + pow((sum_points[j].g - points[i].g), 2) + pow((sum_points[j].r - points[i].r), 2));
if (distance < min_distance)
//if (distance < 1)
{
min_distance = distance;
label[j] = i;
}
}
}
// 2、更新质心的坐标点(通过label值)
// 定义k类分别的点值变量
vector<int> k(points.size(), 0);
vector<float> b(points.size(), 0.0);
vector<float> g(points.size(), 0.0);
vector<float> r(points.size(), 0.0);
for (int i = 0; i < label.size(); i++)
{
for (int j = 0; j < points.size(); j++)
{
// 找到对应的类别进行后续的质心坐标运算
if (j == label[i])
{
k[j]++;
b[j] += sum_points[i].b;
g[j] += sum_points[i].g;
r[j] += sum_points[i].r;
break;
}
}
}
// 更新坐标
for (int i = 0; i < points.size(); i++)
{
b[i] /= k[i];
g[i] /= k[i];
r[i] /= k[i];
}
// 质心坐标值填补
for (int i = 0; i < points.size(); i++)
{
Tuple temp;
temp.x = 0;
temp.y = 0;
temp.b = b[i];
temp.g = g[i];
temp.r = r[i];
new_points[i] = temp;
}
index++;
} while (!Isequal(points,new_points));
Mat result = Mat::zeros(src.size(), CV_8UC3);
for (int i = 0; i < sum_points.size(); i++)
{
sum_points[i].b = points[label[i]].b;
sum_points[i].g = points[label[i]].g;
sum_points[i].r = points[label[i]].r;
}
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
result.at<Vec3b>(i, j)[0] = sum_points[j+i*width].b;
result.at<Vec3b>(i, j)[1] = sum_points[j + i * width].g;
result.at<Vec3b>(i, j)[2] = sum_points[j + i * width].r;
}
}
namedWindow("kmeans-demo", 0);
imshow("kmeans-demo", result);
waitKey(0);
return 0;
}<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/message_loop.h"
#include "chrome/browser/chrome_plugin_service_filter.h"
#include "chrome/browser/chromeos/gview_request_interceptor.h"
#include "chrome/browser/plugin_prefs.h"
#include "chrome/browser/plugin_prefs_factory.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/testing_pref_service.h"
#include "content/browser/mock_resource_context.h"
#include "content/browser/plugin_service.h"
#include "content/browser/renderer_host/dummy_resource_handler.h"
#include "content/browser/renderer_host/resource_dispatcher_host_request_info.h"
#include "content/test/test_browser_thread.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_job.h"
#include "net/url_request/url_request_job_factory.h"
#include "net/url_request/url_request_test_job.h"
#include "net/url_request/url_request_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/plugins/npapi/plugin_list.h"
using content::BrowserThread;
namespace chromeos {
namespace {
const char kPdfUrl[] = "http://foo.com/file.pdf";
const char kPptUrl[] = "http://foo.com/file.ppt";
const char kHtmlUrl[] = "http://foo.com/index.html";
const char kPdfBlob[] = "blob:blobinternal:///d17c4eef-28e7-42bd-bafa-78d5cb8";
const char kPdfUrlIntercepted[] =
"http://docs.google.com/gview?url=http%3A//foo.com/file.pdf";
const char kPptUrlIntercepted[] =
"http://docs.google.com/gview?url=http%3A//foo.com/file.ppt";
class GViewURLRequestTestJob : public net::URLRequestTestJob {
public:
explicit GViewURLRequestTestJob(net::URLRequest* request)
: net::URLRequestTestJob(request, true) {
}
virtual bool GetMimeType(std::string* mime_type) const {
// During the course of a single test, two URLRequestJobs are
// created -- the first is for the viewable document URL, and the
// second is for the rediected URL. In order to test the
// interceptor, the mime type of the first request must be one of
// the supported viewable mime types. So when the net::URLRequestJob
// is a request for one of the test URLs that point to viewable
// content, return an appropraite mime type. Otherwise, return
// "text/html".
const GURL& request_url = request_->url();
if (request_url == GURL(kPdfUrl) || request_url == GURL(kPdfBlob)) {
*mime_type = "application/pdf";
} else if (request_url == GURL(kPptUrl)) {
*mime_type = "application/vnd.ms-powerpoint";
} else {
*mime_type = "text/html";
}
return true;
}
private:
~GViewURLRequestTestJob() {}
};
class GViewRequestProtocolFactory
: public net::URLRequestJobFactory::ProtocolHandler {
public:
GViewRequestProtocolFactory() {}
virtual ~GViewRequestProtocolFactory() {}
virtual net::URLRequestJob* MaybeCreateJob(net::URLRequest* request) const {
return new GViewURLRequestTestJob(request);
}
};
void QuitMessageLoop(const std::vector<webkit::WebPluginInfo>&) {
MessageLoop::current()->Quit();
}
class GViewRequestInterceptorTest : public testing::Test {
public:
GViewRequestInterceptorTest()
: ui_thread_(BrowserThread::UI, &message_loop_),
file_thread_(BrowserThread::FILE, &message_loop_),
io_thread_(BrowserThread::IO, &message_loop_) {}
virtual void SetUp() {
content::ResourceContext* resource_context =
content::MockResourceContext::GetInstance();
net::URLRequestContext* request_context =
resource_context->request_context();
old_factory_ = request_context->job_factory();
job_factory_.SetProtocolHandler("http", new GViewRequestProtocolFactory);
job_factory_.AddInterceptor(new GViewRequestInterceptor);
request_context->set_job_factory(&job_factory_);
PluginPrefsFactory::GetInstance()->ForceRegisterPrefsForTest(&prefs_);
plugin_prefs_ = new PluginPrefs();
plugin_prefs_->SetPrefs(&prefs_);
ChromePluginServiceFilter* filter =
ChromePluginServiceFilter::GetInstance();
filter->RegisterResourceContext(plugin_prefs_, resource_context);
PluginService::GetInstance()->set_filter(filter);
ASSERT_TRUE(PathService::Get(chrome::FILE_PDF_PLUGIN, &pdf_path_));
handler_ = new content::DummyResourceHandler();
PluginService::GetInstance()->RefreshPluginList();
PluginService::GetInstance()->GetPlugins(base::Bind(&QuitMessageLoop));
MessageLoop::current()->Run();
}
virtual void TearDown() {
plugin_prefs_->ShutdownOnUIThread();
content::ResourceContext* resource_context =
content::MockResourceContext::GetInstance();
net::URLRequestContext* request_context =
resource_context->request_context();
request_context->set_job_factory(old_factory_);
ChromePluginServiceFilter* filter =
ChromePluginServiceFilter::GetInstance();
filter->UnregisterResourceContext(resource_context);
PluginService::GetInstance()->set_filter(NULL);
}
// GetPluginInfoByPath() will only use stale information. Because plugin
// refresh is asynchronous, spin a MessageLoop until the callback is run,
// after which, the test will continue.
void RegisterPDFPlugin() {
webkit::WebPluginInfo info;
info.path = pdf_path_;
webkit::npapi::PluginList::Singleton()->RegisterInternalPlugin(info);
PluginService::GetInstance()->RefreshPluginList();
PluginService::GetInstance()->GetPlugins(base::Bind(&QuitMessageLoop));
MessageLoop::current()->Run();
}
void UnregisterPDFPlugin() {
webkit::npapi::PluginList::Singleton()->UnregisterInternalPlugin(pdf_path_);
PluginService::GetInstance()->RefreshPluginList();
PluginService::GetInstance()->GetPlugins(base::Bind(&QuitMessageLoop));
MessageLoop::current()->Run();
}
void SetPDFPluginLoadedState(bool want_loaded) {
webkit::WebPluginInfo info;
bool is_loaded = PluginService::GetInstance()->GetPluginInfoByPath(
pdf_path_, &info);
if (is_loaded && !want_loaded) {
UnregisterPDFPlugin();
is_loaded = PluginService::GetInstance()->GetPluginInfoByPath(
pdf_path_, &info);
} else if (!is_loaded && want_loaded) {
// This "loads" the plug-in even if it's not present on the
// system - which is OK since we don't actually use it, just
// need it to be "enabled" for the test.
RegisterPDFPlugin();
is_loaded = PluginService::GetInstance()->GetPluginInfoByPath(
pdf_path_, &info);
}
EXPECT_EQ(want_loaded, is_loaded);
}
void SetupRequest(net::URLRequest* request) {
content::ResourceContext* context =
content::MockResourceContext::GetInstance();
ResourceDispatcherHostRequestInfo* info =
new ResourceDispatcherHostRequestInfo(handler_,
ChildProcessInfo::RENDER_PROCESS,
-1, // child_id
MSG_ROUTING_NONE,
0, // origin_pid
request->identifier(),
false, // is_main_frame
-1, // frame_id
ResourceType::MAIN_FRAME,
content::PAGE_TRANSITION_LINK,
0, // upload_size
false, // is_download
true, // allow_download
false, // has_user_gesture
context);
request->SetUserData(NULL, info);
request->set_context(context->request_context());
}
protected:
MessageLoopForIO message_loop_;
content::TestBrowserThread ui_thread_;
content::TestBrowserThread file_thread_;
content::TestBrowserThread io_thread_;
TestingPrefService prefs_;
scoped_refptr<PluginPrefs> plugin_prefs_;
net::URLRequestJobFactory job_factory_;
const net::URLRequestJobFactory* old_factory_;
scoped_refptr<ResourceHandler> handler_;
TestDelegate test_delegate_;
FilePath pdf_path_;
};
TEST_F(GViewRequestInterceptorTest, DoNotInterceptHtml) {
net::URLRequest request(GURL(kHtmlUrl), &test_delegate_);
SetupRequest(&request);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(0, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kHtmlUrl), request.url());
}
TEST_F(GViewRequestInterceptorTest, DoNotInterceptDownload) {
net::URLRequest request(GURL(kPdfUrl), &test_delegate_);
SetupRequest(&request);
request.set_load_flags(net::LOAD_IS_DOWNLOAD);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(0, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPdfUrl), request.url());
}
TEST_F(GViewRequestInterceptorTest, DoNotInterceptPdfWhenEnabled) {
SetPDFPluginLoadedState(true);
plugin_prefs_->EnablePlugin(true, pdf_path_);
net::URLRequest request(GURL(kPdfUrl), &test_delegate_);
SetupRequest(&request);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(0, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPdfUrl), request.url());
}
TEST_F(GViewRequestInterceptorTest, InterceptPdfWhenDisabled) {
SetPDFPluginLoadedState(true);
plugin_prefs_->EnablePlugin(false, pdf_path_);
net::URLRequest request(GURL(kPdfUrl), &test_delegate_);
SetupRequest(&request);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(1, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPdfUrlIntercepted), request.url());
}
TEST_F(GViewRequestInterceptorTest, InterceptPdfWithNoPlugin) {
SetPDFPluginLoadedState(false);
net::URLRequest request(GURL(kPdfUrl), &test_delegate_);
SetupRequest(&request);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(1, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPdfUrlIntercepted), request.url());
}
TEST_F(GViewRequestInterceptorTest, InterceptPowerpoint) {
net::URLRequest request(GURL(kPptUrl), &test_delegate_);
SetupRequest(&request);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(1, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPptUrlIntercepted), request.url());
}
TEST_F(GViewRequestInterceptorTest, DoNotInterceptPost) {
SetPDFPluginLoadedState(false);
net::URLRequest request(GURL(kPdfUrl), &test_delegate_);
SetupRequest(&request);
request.set_method("POST");
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(0, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPdfUrl), request.url());
}
TEST_F(GViewRequestInterceptorTest, DoNotInterceptBlob) {
SetPDFPluginLoadedState(false);
net::URLRequest request(GURL(kPdfBlob), &test_delegate_);
SetupRequest(&request);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(0, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPdfBlob), request.url());
}
} // namespace
} // namespace chromeos
<commit_msg>Fix GViewRequestInterceptorTest.* that has been failing on Linux ChromeOS bots<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/message_loop.h"
#include "chrome/browser/chrome_plugin_service_filter.h"
#include "chrome/browser/chromeos/gview_request_interceptor.h"
#include "chrome/browser/plugin_prefs.h"
#include "chrome/browser/plugin_prefs_factory.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/base/testing_pref_service.h"
#include "content/browser/mock_resource_context.h"
#include "content/browser/plugin_service.h"
#include "content/browser/renderer_host/dummy_resource_handler.h"
#include "content/browser/renderer_host/resource_dispatcher_host_request_info.h"
#include "content/test/test_browser_thread.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_job.h"
#include "net/url_request/url_request_job_factory.h"
#include "net/url_request/url_request_test_job.h"
#include "net/url_request/url_request_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/plugins/npapi/plugin_list.h"
using content::BrowserThread;
namespace chromeos {
namespace {
const char kPdfUrl[] = "http://foo.com/file.pdf";
const char kPptUrl[] = "http://foo.com/file.ppt";
const char kHtmlUrl[] = "http://foo.com/index.html";
const char kPdfBlob[] = "blob:blobinternal:///d17c4eef-28e7-42bd-bafa-78d5cb8";
const char kPdfUrlIntercepted[] =
"http://docs.google.com/gview?url=http%3A//foo.com/file.pdf";
const char kPptUrlIntercepted[] =
"http://docs.google.com/gview?url=http%3A//foo.com/file.ppt";
class GViewURLRequestTestJob : public net::URLRequestTestJob {
public:
explicit GViewURLRequestTestJob(net::URLRequest* request)
: net::URLRequestTestJob(request, true) {
}
virtual bool GetMimeType(std::string* mime_type) const {
// During the course of a single test, two URLRequestJobs are
// created -- the first is for the viewable document URL, and the
// second is for the rediected URL. In order to test the
// interceptor, the mime type of the first request must be one of
// the supported viewable mime types. So when the net::URLRequestJob
// is a request for one of the test URLs that point to viewable
// content, return an appropraite mime type. Otherwise, return
// "text/html".
const GURL& request_url = request_->url();
if (request_url == GURL(kPdfUrl) || request_url == GURL(kPdfBlob)) {
*mime_type = "application/pdf";
} else if (request_url == GURL(kPptUrl)) {
*mime_type = "application/vnd.ms-powerpoint";
} else {
*mime_type = "text/html";
}
return true;
}
private:
~GViewURLRequestTestJob() {}
};
class GViewRequestProtocolFactory
: public net::URLRequestJobFactory::ProtocolHandler {
public:
GViewRequestProtocolFactory() {}
virtual ~GViewRequestProtocolFactory() {}
virtual net::URLRequestJob* MaybeCreateJob(net::URLRequest* request) const {
return new GViewURLRequestTestJob(request);
}
};
void QuitMessageLoop(const std::vector<webkit::WebPluginInfo>&) {
MessageLoop::current()->Quit();
}
class GViewRequestInterceptorTest : public testing::Test {
public:
GViewRequestInterceptorTest()
: ui_thread_(BrowserThread::UI, &message_loop_),
file_thread_(BrowserThread::FILE, &message_loop_),
io_thread_(BrowserThread::IO, &message_loop_) {}
virtual void SetUp() {
content::ResourceContext* resource_context =
content::MockResourceContext::GetInstance();
net::URLRequestContext* request_context =
resource_context->request_context();
old_factory_ = request_context->job_factory();
job_factory_.SetProtocolHandler("http", new GViewRequestProtocolFactory);
job_factory_.AddInterceptor(new GViewRequestInterceptor);
request_context->set_job_factory(&job_factory_);
PluginPrefsFactory::GetInstance()->ForceRegisterPrefsForTest(&prefs_);
plugin_prefs_ = new PluginPrefs();
plugin_prefs_->SetPrefs(&prefs_);
ChromePluginServiceFilter* filter =
ChromePluginServiceFilter::GetInstance();
filter->RegisterResourceContext(plugin_prefs_, resource_context);
PluginService::GetInstance()->set_filter(filter);
ASSERT_TRUE(PathService::Get(chrome::FILE_PDF_PLUGIN, &pdf_path_));
handler_ = new content::DummyResourceHandler();
PluginService::GetInstance()->RefreshPluginList();
PluginService::GetInstance()->GetPlugins(base::Bind(&QuitMessageLoop));
MessageLoop::current()->RunAllPending();
}
virtual void TearDown() {
plugin_prefs_->ShutdownOnUIThread();
content::ResourceContext* resource_context =
content::MockResourceContext::GetInstance();
net::URLRequestContext* request_context =
resource_context->request_context();
request_context->set_job_factory(old_factory_);
ChromePluginServiceFilter* filter =
ChromePluginServiceFilter::GetInstance();
filter->UnregisterResourceContext(resource_context);
PluginService::GetInstance()->set_filter(NULL);
}
// GetPluginInfoByPath() will only use stale information. Because plugin
// refresh is asynchronous, spin a MessageLoop until the callback is run,
// after which, the test will continue.
void RegisterPDFPlugin() {
webkit::WebPluginInfo info;
info.path = pdf_path_;
webkit::npapi::PluginList::Singleton()->RegisterInternalPlugin(info);
PluginService::GetInstance()->RefreshPluginList();
PluginService::GetInstance()->GetPlugins(base::Bind(&QuitMessageLoop));
MessageLoop::current()->RunAllPending();
}
void UnregisterPDFPlugin() {
webkit::npapi::PluginList::Singleton()->UnregisterInternalPlugin(pdf_path_);
PluginService::GetInstance()->RefreshPluginList();
PluginService::GetInstance()->GetPlugins(base::Bind(&QuitMessageLoop));
MessageLoop::current()->RunAllPending();
}
void SetPDFPluginLoadedState(bool want_loaded) {
webkit::WebPluginInfo info;
bool is_loaded = PluginService::GetInstance()->GetPluginInfoByPath(
pdf_path_, &info);
if (is_loaded && !want_loaded) {
UnregisterPDFPlugin();
is_loaded = PluginService::GetInstance()->GetPluginInfoByPath(
pdf_path_, &info);
} else if (!is_loaded && want_loaded) {
// This "loads" the plug-in even if it's not present on the
// system - which is OK since we don't actually use it, just
// need it to be "enabled" for the test.
RegisterPDFPlugin();
is_loaded = PluginService::GetInstance()->GetPluginInfoByPath(
pdf_path_, &info);
}
EXPECT_EQ(want_loaded, is_loaded);
}
void SetupRequest(net::URLRequest* request) {
content::ResourceContext* context =
content::MockResourceContext::GetInstance();
ResourceDispatcherHostRequestInfo* info =
new ResourceDispatcherHostRequestInfo(handler_,
ChildProcessInfo::RENDER_PROCESS,
-1, // child_id
MSG_ROUTING_NONE,
0, // origin_pid
request->identifier(),
false, // is_main_frame
-1, // frame_id
ResourceType::MAIN_FRAME,
content::PAGE_TRANSITION_LINK,
0, // upload_size
false, // is_download
true, // allow_download
false, // has_user_gesture
context);
request->SetUserData(NULL, info);
request->set_context(context->request_context());
}
protected:
MessageLoopForIO message_loop_;
content::TestBrowserThread ui_thread_;
content::TestBrowserThread file_thread_;
content::TestBrowserThread io_thread_;
TestingPrefService prefs_;
scoped_refptr<PluginPrefs> plugin_prefs_;
net::URLRequestJobFactory job_factory_;
const net::URLRequestJobFactory* old_factory_;
scoped_refptr<ResourceHandler> handler_;
TestDelegate test_delegate_;
FilePath pdf_path_;
};
TEST_F(GViewRequestInterceptorTest, DoNotInterceptHtml) {
net::URLRequest request(GURL(kHtmlUrl), &test_delegate_);
SetupRequest(&request);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(0, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kHtmlUrl), request.url());
}
TEST_F(GViewRequestInterceptorTest, DoNotInterceptDownload) {
net::URLRequest request(GURL(kPdfUrl), &test_delegate_);
SetupRequest(&request);
request.set_load_flags(net::LOAD_IS_DOWNLOAD);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(0, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPdfUrl), request.url());
}
TEST_F(GViewRequestInterceptorTest, DISABLED_DoNotInterceptPdfWhenEnabled) {
SetPDFPluginLoadedState(true);
plugin_prefs_->EnablePlugin(true, pdf_path_);
net::URLRequest request(GURL(kPdfUrl), &test_delegate_);
SetupRequest(&request);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(0, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPdfUrl), request.url());
}
TEST_F(GViewRequestInterceptorTest, DISABLED_InterceptPdfWhenDisabled) {
SetPDFPluginLoadedState(true);
plugin_prefs_->EnablePlugin(false, pdf_path_);
net::URLRequest request(GURL(kPdfUrl), &test_delegate_);
SetupRequest(&request);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(1, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPdfUrlIntercepted), request.url());
}
TEST_F(GViewRequestInterceptorTest, InterceptPdfWithNoPlugin) {
SetPDFPluginLoadedState(false);
net::URLRequest request(GURL(kPdfUrl), &test_delegate_);
SetupRequest(&request);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(1, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPdfUrlIntercepted), request.url());
}
TEST_F(GViewRequestInterceptorTest, InterceptPowerpoint) {
net::URLRequest request(GURL(kPptUrl), &test_delegate_);
SetupRequest(&request);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(1, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPptUrlIntercepted), request.url());
}
TEST_F(GViewRequestInterceptorTest, DoNotInterceptPost) {
SetPDFPluginLoadedState(false);
net::URLRequest request(GURL(kPdfUrl), &test_delegate_);
SetupRequest(&request);
request.set_method("POST");
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(0, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPdfUrl), request.url());
}
TEST_F(GViewRequestInterceptorTest, DoNotInterceptBlob) {
SetPDFPluginLoadedState(false);
net::URLRequest request(GURL(kPdfBlob), &test_delegate_);
SetupRequest(&request);
request.Start();
MessageLoop::current()->Run();
EXPECT_EQ(0, test_delegate_.received_redirect_count());
EXPECT_EQ(GURL(kPdfBlob), request.url());
}
} // namespace
} // namespace chromeos
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkTestingMacros.h"
#include "mitkPlanarArrow.h"
#include "mitkPlaneGeometry.h"
class mitkPlanarArrowTestClass
{
public:
static void TestPlanarArrowPlacement( mitk::PlanarArrow::Pointer PlanarArrow )
{
// Test for correct minimum number of control points in cross-mode
MITK_TEST_CONDITION( PlanarArrow->GetMinimumNumberOfControlPoints() == 2, "Minimum number of control points" );
// Test for correct maximum number of control points in cross-mode
MITK_TEST_CONDITION( PlanarArrow->GetMaximumNumberOfControlPoints() == 2, "Maximum number of control points" );
// Initial placement of PlanarArrow
mitk::Point2D p0;
p0[0] = 00.0; p0[1] = 0.0;
PlanarArrow->PlaceFigure( p0 );
// Add second control point
mitk::Point2D p1;
p1[0] = 50.0; p1[1] = 00.0;
PlanarArrow->SetControlPoint(1, p1 );
// Test for number of control points
MITK_TEST_CONDITION( PlanarArrow->GetNumberOfControlPoints() == 2, "Number of control points after placement" );
// Test for number of polylines
const mitk::PlanarFigure::PolyLineType polyLine0 = PlanarArrow->GetPolyLine( 0 );
mitk::PlanarFigure::PolyLineType::const_iterator iter = polyLine0.begin();
MITK_TEST_CONDITION( PlanarArrow->GetPolyLinesSize() == 1, "Number of polylines after placement" );
// Get polylines and check if the generated coordinates are OK
const mitk::Point2D& pp0 = *iter;
iter++;
const mitk::Point2D& pp1 = *iter;
MITK_TEST_CONDITION( (pp0 == p0) && (pp1 == p1), "Correct polyline 1" );
// Test for number of measurement features
// none yet
}
};
/**
* mitkPlanarArrowTest tests the methods and behavior of mitk::PlanarArrow with sub-tests:
*
* 1. Instantiation and basic tests
*
*/
int mitkPlanarArrowTest(int /* argc */, char* /*argv*/[])
{
// always start with this!
MITK_TEST_BEGIN("PlanarArrow")
// create PlaneGeometry on which to place the PlanarArrow
mitk::PlaneGeometry::Pointer planeGeometry = mitk::PlaneGeometry::New();
planeGeometry->InitializeStandardPlane( 100.0, 100.0 );
// **************************************************************************
// 1. Instantiation and basic tests
mitk::PlanarArrow::Pointer PlanarArrow = mitk::PlanarArrow::New();
PlanarArrow->SetPlaneGeometry( planeGeometry );
// first test: did this work?
MITK_TEST_CONDITION_REQUIRED( PlanarArrow.IsNotNull(), "Testing instantiation" );
// Test placement of PlanarArrow by control points
mitkPlanarArrowTestClass::TestPlanarArrowPlacement( PlanarArrow );
PlanarArrow->EvaluateFeatures();
mitk::PlanarArrow::Pointer clonedArrow = PlanarArrow->Clone();
MITK_TEST_CONDITION_REQUIRED( clonedArrow.IsNotNull(), "Testing cloning" );
bool identical( true );
identical &= clonedArrow->GetMinimumNumberOfControlPoints() == PlanarArrow->GetMinimumNumberOfControlPoints();
identical &= clonedArrow->GetMaximumNumberOfControlPoints() == PlanarArrow->GetMaximumNumberOfControlPoints();
identical &= clonedArrow->IsClosed() == PlanarArrow->IsClosed();
identical &= clonedArrow->IsPlaced() == PlanarArrow->IsPlaced();
identical &= clonedArrow->GetNumberOfControlPoints() == PlanarArrow->GetNumberOfControlPoints();
identical &= clonedArrow->GetNumberOfControlPoints() == PlanarArrow->GetNumberOfControlPoints();
identical &= clonedArrow->GetSelectedControlPoint() == PlanarArrow->GetSelectedControlPoint();
identical &= clonedArrow->IsPreviewControlPointVisible() == PlanarArrow->IsPreviewControlPointVisible();
identical &= clonedArrow->GetPolyLinesSize() == PlanarArrow->GetPolyLinesSize();
identical &= clonedArrow->GetHelperPolyLinesSize() == PlanarArrow->GetHelperPolyLinesSize();
identical &= clonedArrow->ResetOnPointSelect() == PlanarArrow->ResetOnPointSelect();
for ( unsigned int i=0; i<clonedArrow->GetNumberOfControlPoints(); ++i )
{
identical &= clonedArrow->GetControlPoint(i) == PlanarArrow->GetControlPoint(i);
}
for ( unsigned int i=0; i<clonedArrow->GetPolyLinesSize(); ++i )
{
mitk::PlanarFigure::PolyLineType polyLine = clonedArrow->GetPolyLine( i );
for ( int j=0; j<polyLine.size(); ++j )
{
identical &= polyLine.at(j) == PlanarArrow->GetPolyLine(i).at(j);
}
}
MITK_TEST_CONDITION_REQUIRED( identical, "Cloning completely successful" );
// always end with this!
MITK_TEST_END();
}
<commit_msg>COMP: Merge branch 'bug-18556-add-copydeep-for-planarFigure'<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkTestingMacros.h"
#include "mitkPlanarArrow.h"
#include "mitkPlaneGeometry.h"
class mitkPlanarArrowTestClass
{
public:
static void TestPlanarArrowPlacement( mitk::PlanarArrow::Pointer PlanarArrow )
{
// Test for correct minimum number of control points in cross-mode
MITK_TEST_CONDITION( PlanarArrow->GetMinimumNumberOfControlPoints() == 2, "Minimum number of control points" );
// Test for correct maximum number of control points in cross-mode
MITK_TEST_CONDITION( PlanarArrow->GetMaximumNumberOfControlPoints() == 2, "Maximum number of control points" );
// Initial placement of PlanarArrow
mitk::Point2D p0;
p0[0] = 00.0; p0[1] = 0.0;
PlanarArrow->PlaceFigure( p0 );
// Add second control point
mitk::Point2D p1;
p1[0] = 50.0; p1[1] = 00.0;
PlanarArrow->SetControlPoint(1, p1 );
// Test for number of control points
MITK_TEST_CONDITION( PlanarArrow->GetNumberOfControlPoints() == 2, "Number of control points after placement" );
// Test for number of polylines
const mitk::PlanarFigure::PolyLineType polyLine0 = PlanarArrow->GetPolyLine( 0 );
mitk::PlanarFigure::PolyLineType::const_iterator iter = polyLine0.begin();
MITK_TEST_CONDITION( PlanarArrow->GetPolyLinesSize() == 1, "Number of polylines after placement" );
// Get polylines and check if the generated coordinates are OK
const mitk::Point2D& pp0 = *iter;
iter++;
const mitk::Point2D& pp1 = *iter;
MITK_TEST_CONDITION( (pp0 == p0) && (pp1 == p1), "Correct polyline 1" );
// Test for number of measurement features
// none yet
}
};
/**
* mitkPlanarArrowTest tests the methods and behavior of mitk::PlanarArrow with sub-tests:
*
* 1. Instantiation and basic tests
*
*/
int mitkPlanarArrowTest(int /* argc */, char* /*argv*/[])
{
// always start with this!
MITK_TEST_BEGIN("PlanarArrow")
// create PlaneGeometry on which to place the PlanarArrow
mitk::PlaneGeometry::Pointer planeGeometry = mitk::PlaneGeometry::New();
planeGeometry->InitializeStandardPlane( 100.0, 100.0 );
// **************************************************************************
// 1. Instantiation and basic tests
mitk::PlanarArrow::Pointer PlanarArrow = mitk::PlanarArrow::New();
PlanarArrow->SetPlaneGeometry( planeGeometry );
// first test: did this work?
MITK_TEST_CONDITION_REQUIRED( PlanarArrow.IsNotNull(), "Testing instantiation" );
// Test placement of PlanarArrow by control points
mitkPlanarArrowTestClass::TestPlanarArrowPlacement( PlanarArrow );
PlanarArrow->EvaluateFeatures();
mitk::PlanarArrow::Pointer clonedArrow = PlanarArrow->Clone();
MITK_TEST_CONDITION_REQUIRED( clonedArrow.IsNotNull(), "Testing cloning" );
bool identical( true );
identical &= clonedArrow->GetMinimumNumberOfControlPoints() == PlanarArrow->GetMinimumNumberOfControlPoints();
identical &= clonedArrow->GetMaximumNumberOfControlPoints() == PlanarArrow->GetMaximumNumberOfControlPoints();
identical &= clonedArrow->IsClosed() == PlanarArrow->IsClosed();
identical &= clonedArrow->IsPlaced() == PlanarArrow->IsPlaced();
identical &= clonedArrow->GetNumberOfControlPoints() == PlanarArrow->GetNumberOfControlPoints();
identical &= clonedArrow->GetNumberOfControlPoints() == PlanarArrow->GetNumberOfControlPoints();
identical &= clonedArrow->GetSelectedControlPoint() == PlanarArrow->GetSelectedControlPoint();
identical &= clonedArrow->IsPreviewControlPointVisible() == PlanarArrow->IsPreviewControlPointVisible();
identical &= clonedArrow->GetPolyLinesSize() == PlanarArrow->GetPolyLinesSize();
identical &= clonedArrow->GetHelperPolyLinesSize() == PlanarArrow->GetHelperPolyLinesSize();
identical &= clonedArrow->ResetOnPointSelect() == PlanarArrow->ResetOnPointSelect();
for ( unsigned int i=0; i<clonedArrow->GetNumberOfControlPoints(); ++i )
{
identical &= clonedArrow->GetControlPoint(i) == PlanarArrow->GetControlPoint(i);
}
for ( unsigned int i=0; i<clonedArrow->GetPolyLinesSize(); ++i )
{
mitk::PlanarFigure::PolyLineType polyLine = clonedArrow->GetPolyLine( i );
for ( unsigned int j=0; j<polyLine.size(); ++j )
{
identical &= polyLine.at(j) == PlanarArrow->GetPolyLine(i).at(j);
}
}
MITK_TEST_CONDITION_REQUIRED( identical, "Cloning completely successful" );
// always end with this!
MITK_TEST_END();
}
<|endoftext|> |
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU General Public License as published by the Free *
* Software Foundation; either version 2 of the License, or (at your option) *
* any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *
* more details. *
* *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., 51 *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
*******************************************************************************
* SOFA :: Applications *
* *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy *
* *
* Contact information: [email protected] *
******************************************************************************/
#include <sofa/simulation/tree/TreeSimulation.h>
#include <sofa/simulation/tree/GNode.h>
#include <sofa/component/misc/ReadState.h>
#include <sofa/component/misc/WriteState.h>
#include <sofa/component/misc/CompareState.h>
#include <sofa/component/misc/ReadTopology.h>
#include <sofa/component/misc/WriteTopology.h>
#include <sofa/component/misc/CompareTopology.h>
#include <sofa/component/init.h>
#include <sofa/helper/system/thread/TimeoutWatchdog.h>
#include <sofa/helper/system/FileRepository.h>
#include <sofa/helper/system/SetDirectory.h>
#include <sofa/helper/ArgumentParser.h>
#include <sofa/helper/Factory.h>
#include <sofa/helper/BackTrace.h>
#include <iostream>
#include <fstream>
#include <ctime>
using sofa::helper::system::DataRepository;
using sofa::helper::system::SetDirectory;
using sofa::simulation::tree::GNode;
#ifndef WIN32
#include <dlfcn.h>
bool loadPlugin(const char* filename)
{
void *handle;
handle=dlopen(filename, RTLD_LAZY);
if (!handle)
{
std::cerr<<"Error loading plugin "<<filename<<": "<<dlerror()<<std::endl;
return false;
}
std::cerr<<"Plugin "<<filename<<" loaded."<<std::endl;
return true;
}
#else
bool loadPlugin(const char* filename)
{
HINSTANCE DLLHandle;
DLLHandle = LoadLibraryA(filename); //warning: issue between unicode and ansi encoding on Visual c++ -> force to ansi-> dirty!
if (DLLHandle == NULL)
{
std::cerr<<"Error loading plugin "<<filename<<std::endl;
return false;
}
std::cerr<<"Plugin "<<filename<<" loaded."<<std::endl;
return true;
}
#endif
// ---------------------------------------------------------------------
// ---
// ---------------------------------------------------------------------
void apply(const std::string& directory, std::vector<std::string>& files,
unsigned int iterations, bool reinit, bool useTopology)
{
sofa::component::init(); // ensures all components are initialized, also introduce a dependency to all libraries, avoiding problems with -Wl,--as-needed flag
sofa::simulation::Simulation* simulation = sofa::simulation::getSimulation();
//Launch the comparison for each scenes
for (unsigned int i = 0; i < files.size(); ++i)
{
const std::string& currentFile = files[i];
GNode* groot = dynamic_cast<GNode*> (simulation->load(currentFile.c_str()));
if (groot == NULL)
{
std::cerr << "CANNOT open " << currentFile << " !" << std::endl;
continue;
}
simulation->init(groot);
//Filename where the simulation of the current scene will be saved (in Sofa/applications/projects/sofaVerification/simulation/)
std::string refFile;
if(directory.empty())
{
refFile += SetDirectory::GetParentDir(DataRepository.getFirstPath().c_str());
refFile += "/applications/projects/sofaVerification/simulation/";
refFile += SetDirectory::GetFileName(currentFile.c_str());
}
else
{
refFile += directory;
refFile += '/';
refFile += SetDirectory::GetFileName(currentFile.c_str());
}
//If we initialize the system, we add only WriteState components, to store the reference states
if (reinit)
{
if (useTopology)
{
sofa::component::misc::WriteTopologyCreator writeVisitor(sofa::core::ExecParams::defaultInstance());
writeVisitor.setCreateInMapping(true);
writeVisitor.setSceneName(refFile);
writeVisitor.execute(groot);
sofa::component::misc::WriteTopologyActivator v_write(true,sofa::core::ExecParams::defaultInstance());
v_write.execute(groot);
}
else
{
sofa::component::misc::WriteStateCreator writeVisitor(sofa::core::ExecParams::defaultInstance());
writeVisitor.setCreateInMapping(true);
writeVisitor.setSceneName(refFile);
writeVisitor.execute(groot);
sofa::component::misc::WriteStateActivator v_write(true,sofa::core::ExecParams::defaultInstance());
v_write.execute(groot);
}
}
else
{
if (useTopology)
{
//We add CompareTopology components: as it derives from the ReadTopology, we use the ReadTopologyActivator to enable them.
sofa::component::misc::CompareTopologyCreator compareVisitor(sofa::core::ExecParams::defaultInstance());
compareVisitor.setCreateInMapping(true);
compareVisitor.setSceneName(refFile);
compareVisitor.execute(groot);
sofa::component::misc::ReadTopologyActivator v_read(sofa::core::ExecParams::defaultInstance(),true);
v_read.execute(groot);
}
else
{
//We add CompareState components: as it derives from the ReadState, we use the ReadStateActivator to enable them.
sofa::component::misc::CompareStateCreator compareVisitor(sofa::core::ExecParams::defaultInstance());
compareVisitor.setCreateInMapping(true);
compareVisitor.setSceneName(refFile);
compareVisitor.execute(groot);
sofa::component::misc::ReadStateActivator v_read(true,sofa::core::ExecParams::defaultInstance());
v_read.execute(groot);
}
}
//Do as many iterations as specified in entry of the program. At each step, the compare state will compare the computed states to the recorded states
std::cout << "Computing " << iterations << " for " << currentFile << std::endl;
//Save the initial time
clock_t curtime = clock();
for (unsigned int i = 0; i < iterations; i++)
{
simulation->animate(groot);
}
double t = static_cast<double>(clock() - curtime) / CLOCKS_PER_SEC;
std::cout << "ITERATIONS " << iterations << " TIME " << t << " seconds ";
//We read the final error: the summation of all the error made at each time step
if (!reinit)
{
if (useTopology)
{
sofa::component::misc::CompareTopologyResult result(sofa::core::ExecParams::defaultInstance());
result.execute(groot);
std::cout << "ERROR " << result.getTotalError() << ' ';
const std::vector<unsigned int>& listResult = result.getErrors();
if (listResult.size() != 5)
{
std::cerr
<< "ERROR while reading detail of errors by topological element."
<< std::endl;
break;
}
std::cout
<< "ERROR by element type "
<< " EDGES " << static_cast<double>(listResult[0])
/ result.getNumCompareTopology()
<< " TRIANGLES " << static_cast<double>(listResult[1])
/ result.getNumCompareTopology()
<< " QUADS " << static_cast<double>(listResult[2])
/ result.getNumCompareTopology()
<< " TETRAHEDRA " << static_cast<double>(listResult[3])
/ result.getNumCompareTopology()
<< " HEXAHEDRA " << static_cast<double>(listResult[4])
/ result.getNumCompareTopology();
}
else
{
sofa::component::misc::CompareStateResult result(sofa::core::ExecParams::defaultInstance());
result.execute(groot);
std::cout
<< "ERROR " << result.getTotalError() << " ERRORBYDOF "
<< static_cast<double>(result.getErrorByDof())
/ result.getNumCompareState() << std::endl;
}
}
std::cout << std::endl;
//Clear and prepare for next scene
simulation->unload(groot);
delete groot;
}
}
int main(int argc, char** argv)
{
sofa::helper::BackTrace::autodump();
std::string directory;
std::vector<std::string> fileArguments;
std::vector<std::string> sceneFiles;
std::vector<std::string> plugins;
unsigned int iterations = 100;
bool reinit = false;
bool topology = false;
unsigned lifetime = 0;
sofa::simulation::setSimulation(new sofa::simulation::tree::TreeSimulation());
sofa::helper::parse(
&fileArguments,
"This is SOFA verification. "
"To use it, specify in the command line the scene files you want to test, "
"or a \".ini\" file containing the path to the scenes.")
.option(&reinit, 'r', "reinit", "Recreate the references state files")
.option(&iterations, 'i', "iteration", "Number of iterations for testing")
.option(&directory, 'd', "directory", "The directory for reference files")
.option(&plugins,'p',"plugin","load given plugins")
.option(&topology, 't', "topology", "Specific mode to run tests on topology")
.option(&lifetime, 'l', "lifetime", "Maximum execution time in seconds (default: 0 -> no limit")
(argc, argv);
#ifdef SOFA_HAVE_BOOST
sofa::helper::system::thread::TimeoutWatchdog watchdog;
if(lifetime > 0)
{
watchdog.start(lifetime);
}
#endif
for (unsigned int i=0; i<plugins.size(); i++)
loadPlugin(plugins[i].c_str());
for(size_t i = 0; i < fileArguments.size(); ++i)
{
std::string currentFile = fileArguments[i];
DataRepository.findFile(currentFile);
if (currentFile.compare(currentFile.size() - 4, 4, ".ini") == 0)
{
//This is an ini file: get the list of scenes to test
std::ifstream iniFileStream(currentFile.c_str());
while (!iniFileStream.eof())
{
std::string line;
std::string currentScene;
// extracting the filename line by line because each line can contain
// extra data, ignored by this program but that may be useful for
// other tools.
getline(iniFileStream, line);
std::istringstream lineStream(line);
lineStream >> currentScene;
DataRepository.findFile(currentScene);
sceneFiles.push_back(currentScene);
}
}
else
{
// this is supposed to be a scene file
sceneFiles.push_back(currentFile);
}
}
std::cout
<< "*********************************************************************\n"
<< "******* Arguments ***************************************************\n"
<< "iterations: " << iterations << '\n'
<< "reinit: " << reinit << '\n'
<< "useTopology: " << topology << '\n'
<< "files : " << '\n';
for(size_t i = 0; i < sceneFiles.size(); ++i)
{
std::cout << " " << sceneFiles[i] << '\n';
}
apply(directory, sceneFiles, iterations, reinit, topology);
return 0;
}
<commit_msg>r9428/sofa-dev : CHANGE: in SofaVerification added a command line option to specify additionnal directories to search scenes and data files.<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU General Public License as published by the Free *
* Software Foundation; either version 2 of the License, or (at your option) *
* any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *
* more details. *
* *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, write to the Free Software Foundation, Inc., 51 *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
*******************************************************************************
* SOFA :: Applications *
* *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy *
* *
* Contact information: [email protected] *
******************************************************************************/
#include <sofa/simulation/tree/TreeSimulation.h>
#include <sofa/simulation/tree/GNode.h>
#include <sofa/component/misc/ReadState.h>
#include <sofa/component/misc/WriteState.h>
#include <sofa/component/misc/CompareState.h>
#include <sofa/component/misc/ReadTopology.h>
#include <sofa/component/misc/WriteTopology.h>
#include <sofa/component/misc/CompareTopology.h>
#include <sofa/component/init.h>
#include <sofa/helper/system/thread/TimeoutWatchdog.h>
#include <sofa/helper/system/FileRepository.h>
#include <sofa/helper/system/SetDirectory.h>
#include <sofa/helper/ArgumentParser.h>
#include <sofa/helper/Factory.h>
#include <sofa/helper/BackTrace.h>
#include <iostream>
#include <fstream>
#include <ctime>
using sofa::helper::system::DataRepository;
using sofa::helper::system::SetDirectory;
using sofa::simulation::tree::GNode;
#ifndef WIN32
#include <dlfcn.h>
bool loadPlugin(const char* filename)
{
void *handle;
handle=dlopen(filename, RTLD_LAZY);
if (!handle)
{
std::cerr<<"Error loading plugin "<<filename<<": "<<dlerror()<<std::endl;
return false;
}
std::cerr<<"Plugin "<<filename<<" loaded."<<std::endl;
return true;
}
#else
bool loadPlugin(const char* filename)
{
HINSTANCE DLLHandle;
DLLHandle = LoadLibraryA(filename); //warning: issue between unicode and ansi encoding on Visual c++ -> force to ansi-> dirty!
if (DLLHandle == NULL)
{
std::cerr<<"Error loading plugin "<<filename<<std::endl;
return false;
}
std::cerr<<"Plugin "<<filename<<" loaded."<<std::endl;
return true;
}
#endif
// ---------------------------------------------------------------------
// ---
// ---------------------------------------------------------------------
void apply(const std::string& directory, std::vector<std::string>& files,
unsigned int iterations, bool reinit, bool useTopology)
{
sofa::component::init(); // ensures all components are initialized, also introduce a dependency to all libraries, avoiding problems with -Wl,--as-needed flag
sofa::simulation::Simulation* simulation = sofa::simulation::getSimulation();
//Launch the comparison for each scenes
for (unsigned int i = 0; i < files.size(); ++i)
{
const std::string& currentFile = files[i];
GNode* groot = dynamic_cast<GNode*> (simulation->load(currentFile.c_str()));
if (groot == NULL)
{
std::cerr << "CANNOT open " << currentFile << " !" << std::endl;
continue;
}
simulation->init(groot);
//Filename where the simulation of the current scene will be saved (in Sofa/applications/projects/sofaVerification/simulation/)
std::string refFile;
if(directory.empty())
{
refFile += SetDirectory::GetParentDir(DataRepository.getFirstPath().c_str());
refFile += "/applications/projects/sofaVerification/simulation/";
refFile += SetDirectory::GetFileName(currentFile.c_str());
}
else
{
refFile += directory;
refFile += '/';
refFile += SetDirectory::GetFileName(currentFile.c_str());
}
//If we initialize the system, we add only WriteState components, to store the reference states
if (reinit)
{
if (useTopology)
{
sofa::component::misc::WriteTopologyCreator writeVisitor(sofa::core::ExecParams::defaultInstance());
writeVisitor.setCreateInMapping(true);
writeVisitor.setSceneName(refFile);
writeVisitor.execute(groot);
sofa::component::misc::WriteTopologyActivator v_write(true,sofa::core::ExecParams::defaultInstance());
v_write.execute(groot);
}
else
{
sofa::component::misc::WriteStateCreator writeVisitor(sofa::core::ExecParams::defaultInstance());
writeVisitor.setCreateInMapping(true);
writeVisitor.setSceneName(refFile);
writeVisitor.execute(groot);
sofa::component::misc::WriteStateActivator v_write(true,sofa::core::ExecParams::defaultInstance());
v_write.execute(groot);
}
}
else
{
if (useTopology)
{
//We add CompareTopology components: as it derives from the ReadTopology, we use the ReadTopologyActivator to enable them.
sofa::component::misc::CompareTopologyCreator compareVisitor(sofa::core::ExecParams::defaultInstance());
compareVisitor.setCreateInMapping(true);
compareVisitor.setSceneName(refFile);
compareVisitor.execute(groot);
sofa::component::misc::ReadTopologyActivator v_read(sofa::core::ExecParams::defaultInstance(),true);
v_read.execute(groot);
}
else
{
//We add CompareState components: as it derives from the ReadState, we use the ReadStateActivator to enable them.
sofa::component::misc::CompareStateCreator compareVisitor(sofa::core::ExecParams::defaultInstance());
compareVisitor.setCreateInMapping(true);
compareVisitor.setSceneName(refFile);
compareVisitor.execute(groot);
sofa::component::misc::ReadStateActivator v_read(true,sofa::core::ExecParams::defaultInstance());
v_read.execute(groot);
}
}
//Do as many iterations as specified in entry of the program. At each step, the compare state will compare the computed states to the recorded states
std::cout << "Computing " << iterations << " for " << currentFile << std::endl;
//Save the initial time
clock_t curtime = clock();
for (unsigned int i = 0; i < iterations; i++)
{
simulation->animate(groot);
}
double t = static_cast<double>(clock() - curtime) / CLOCKS_PER_SEC;
std::cout << "ITERATIONS " << iterations << " TIME " << t << " seconds ";
//We read the final error: the summation of all the error made at each time step
if (!reinit)
{
if (useTopology)
{
sofa::component::misc::CompareTopologyResult result(sofa::core::ExecParams::defaultInstance());
result.execute(groot);
std::cout << "ERROR " << result.getTotalError() << ' ';
const std::vector<unsigned int>& listResult = result.getErrors();
if (listResult.size() != 5)
{
std::cerr
<< "ERROR while reading detail of errors by topological element."
<< std::endl;
break;
}
std::cout
<< "ERROR by element type "
<< " EDGES " << static_cast<double>(listResult[0])
/ result.getNumCompareTopology()
<< " TRIANGLES " << static_cast<double>(listResult[1])
/ result.getNumCompareTopology()
<< " QUADS " << static_cast<double>(listResult[2])
/ result.getNumCompareTopology()
<< " TETRAHEDRA " << static_cast<double>(listResult[3])
/ result.getNumCompareTopology()
<< " HEXAHEDRA " << static_cast<double>(listResult[4])
/ result.getNumCompareTopology();
}
else
{
sofa::component::misc::CompareStateResult result(sofa::core::ExecParams::defaultInstance());
result.execute(groot);
std::cout
<< "ERROR " << result.getTotalError() << " ERRORBYDOF "
<< static_cast<double>(result.getErrorByDof())
/ result.getNumCompareState() << std::endl;
}
}
std::cout << std::endl;
//Clear and prepare for next scene
simulation->unload(groot);
delete groot;
}
}
int main(int argc, char** argv)
{
sofa::helper::BackTrace::autodump();
std::string refdir;
std::string dataPath;
std::vector<std::string> fileArguments;
std::vector<std::string> sceneFiles;
std::vector<std::string> plugins;
unsigned int iterations = 100;
bool reinit = false;
bool topology = false;
unsigned lifetime = 0;
sofa::simulation::setSimulation(new sofa::simulation::tree::TreeSimulation());
sofa::helper::parse(
&fileArguments,
"This is SOFA verification. "
"To use it, specify in the command line the scene files you want to test, "
"or a \".ini\" file containing the path to the scenes.")
.option(&reinit, 'r', "reinit", "Recreate the references state files")
.option(&iterations, 'i', "iteration", "Number of iterations for testing")
.option(&refdir, 'd', "refdir", "The directory for reference files")
.option(&dataPath, 'a', "datapath", "A colon-separated (semi-colon on Windows) list of directories to search for data files (scenes, resources...)")
.option(&plugins, 'p', "plugin", "Load given plugins")
.option(&topology, 't', "topology", "Specific mode to run tests on topology")
.option(&lifetime, 'l', "lifetime", "Maximum execution time in seconds (default: 0 -> no limit")
(argc, argv);
#ifdef SOFA_HAVE_BOOST
sofa::helper::system::thread::TimeoutWatchdog watchdog;
if(lifetime > 0)
{
watchdog.start(lifetime);
}
#endif
for(unsigned int i = 0; i < plugins.size(); i++)
{
loadPlugin(plugins[i].c_str());
}
DataRepository.addLastPath(dataPath);
for(size_t i = 0; i < fileArguments.size(); ++i)
{
std::string currentFile = fileArguments[i];
DataRepository.findFile(currentFile);
if (currentFile.compare(currentFile.size() - 4, 4, ".ini") == 0)
{
//This is an ini file: get the list of scenes to test
std::ifstream iniFileStream(currentFile.c_str());
while (!iniFileStream.eof())
{
std::string line;
std::string currentScene;
// extracting the filename line by line because each line can contain
// extra data, ignored by this program but that may be useful for
// other tools.
getline(iniFileStream, line);
std::istringstream lineStream(line);
lineStream >> currentScene;
DataRepository.findFile(currentScene);
sceneFiles.push_back(currentScene);
}
}
else
{
// this is supposed to be a scene file
sceneFiles.push_back(currentFile);
}
}
std::cout
<< "*********************************************************************\n"
<< "******* Arguments ***************************************************\n"
<< "iterations: " << iterations << '\n'
<< "reinit: " << reinit << '\n'
<< "useTopology: " << topology << '\n'
<< "files : " << '\n';
for(size_t i = 0; i < sceneFiles.size(); ++i)
{
std::cout << " " << sceneFiles[i] << '\n';
}
apply(refdir, sceneFiles, iterations, reinit, topology);
return 0;
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "camera.h"
Camera::Camera(DeviceResources* resources)
{
m_pDeviceResources = resources;
XMVECTORF32 eye = { 0.0f, 5.0f, -10.0, 0.0f };
XMVECTORF32 at = { 0.0f, 0.0f, 0.0f, 0.0f };
XMVECTORF32 up = { 0.0f, 1.0f, 0.0f, 0.0f };
m_eyePosition = &eye;
m_focusPosition = &at;
m_upDirection = &up;
}
Camera::~Camera()
{
}
void Camera::Initialize()
{
float aspectRatio = GetAspectRatio();
float fieldOfView = GetFieldOfView();
m_pDeviceResources->ConstBufferData = new ConstantBufferData();
m_pDeviceResources->ConstBufferData->view = GetViewMatrix();
m_pDeviceResources->ConstBufferData->projection = GetProjectionMatrix();
}
XMFLOAT4X4 Camera::GetViewMatrix()
{
XMFLOAT4X4 view;
auto matrix = XMMatrixTranspose(XMMatrixLookAtRH(*m_eyePosition, *m_focusPosition, *m_upDirection));
XMStoreFloat4x4(&view, matrix);
return view;
}
XMFLOAT4X4 Camera::GetProjectionMatrix()
{
XMFLOAT4X4 projection;
auto matrix = XMMatrixTranspose(XMMatrixPerspectiveFovRH(GetFieldOfView(), GetAspectRatio(), m_pDeviceResources->NearZ, m_pDeviceResources->FarZ));
XMStoreFloat4x4(&projection, matrix);
return projection;
}
void Camera::RotateHorizontal(float Angle)
{
}
void Camera::RotateVertical(float Angle)
{
}
void Camera::MoveX(float Angle)
{
}
void Camera::MoveY(float Angle)
{
}
void Camera::MoveZ(float Angle)
{
}<commit_msg>refac<commit_after>#include "stdafx.h"
#include "camera.h"
Camera::Camera(DeviceResources* resources)
{
m_pDeviceResources = resources;
XMVECTORF32 eyePosition = { 0.0f, 5.0f, -10.0, 0.0f };
XMVECTORF32 focusPosition = { 0.0f, 0.0f, 0.0f, 0.0f };
XMVECTORF32 upDirection = { 0.0f, 1.0f, 0.0f, 0.0f };
m_eyePosition = &eyePosition;
m_focusPosition = &focusPosition;
m_upDirection = &upDirection;
}
Camera::~Camera()
{
}
void Camera::Initialize()
{
float aspectRatio = GetAspectRatio();
float fieldOfView = GetFieldOfView();
m_pDeviceResources->ConstBufferData = new ConstantBufferData();
m_pDeviceResources->ConstBufferData->view = GetViewMatrix();
m_pDeviceResources->ConstBufferData->projection = GetProjectionMatrix();
}
XMFLOAT4X4 Camera::GetViewMatrix()
{
XMFLOAT4X4 view;
auto matrix = XMMatrixTranspose(XMMatrixLookAtRH(*m_eyePosition, *m_focusPosition, *m_upDirection));
XMStoreFloat4x4(&view, matrix);
return view;
}
XMFLOAT4X4 Camera::GetProjectionMatrix()
{
XMFLOAT4X4 projection;
auto matrix = XMMatrixTranspose(XMMatrixPerspectiveFovRH(GetFieldOfView(), GetAspectRatio(), m_pDeviceResources->NearZ, m_pDeviceResources->FarZ));
XMStoreFloat4x4(&projection, matrix);
return projection;
}
void Camera::RotateHorizontal(float Angle)
{
}
void Camera::RotateVertical(float Angle)
{
}
void Camera::MoveX(float Angle)
{
}
void Camera::MoveY(float Angle)
{
}
void Camera::MoveZ(float Angle)
{
}<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/network_state_notifier.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/cros/cros_in_process_browser_test.h"
#include "chrome/browser/chromeos/cros/mock_network_library.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_registrar.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "chrome/test/ui_test_utils.h"
namespace chromeos {
using ::testing::Return;
using ::testing::_;
class NetworkStateNotifierTest : public CrosInProcessBrowserTest,
public NotificationObserver {
public:
NetworkStateNotifierTest()
: notification_received_(false) {
}
protected:
virtual void SetUpInProcessBrowserTestFixture() {
InitStatusAreaMocks();
SetStatusAreaMocksExpectations();
// Initialize network state notifier.
ASSERT_TRUE(CrosLibrary::Get()->EnsureLoaded());
ASSERT_TRUE(mock_network_library_);
EXPECT_CALL(*mock_network_library_, Connected())
.Times(1)
.WillRepeatedly((Return(true)))
.RetiresOnSaturation();
NetworkStateNotifier::Get();
}
// NotificationObserver overrides.
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
EXPECT_TRUE(ChromeThread::CurrentlyOn(ChromeThread::UI));
EXPECT_TRUE(NotificationType::NETWORK_STATE_CHANGED == type);
chromeos::NetworkStateDetails* state_details =
Details<chromeos::NetworkStateDetails>(details).ptr();
state_ = state_details->state();
notification_received_ = true;
}
void WaitForNotification() {
notification_received_ = false;
while (!notification_received_) {
ui_test_utils::RunAllPendingInMessageLoop();
}
}
protected:
NetworkStateDetails::State state_;
bool notification_received_;
};
IN_PROC_BROWSER_TEST_F(NetworkStateNotifierTest, TestConnected) {
// NETWORK_STATE_CHAGNED has to be registered in UI thread.
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::NETWORK_STATE_CHANGED,
NotificationService::AllSources());
EXPECT_CALL(*mock_network_library_, Connected())
.Times(1)
.WillRepeatedly((Return(true)))
.RetiresOnSaturation();
NetworkStateNotifier* notifier = NetworkStateNotifier::Get();
notifier->NetworkChanged(mock_network_library_);
WaitForNotification();
EXPECT_EQ(chromeos::NetworkStateDetails::CONNECTED, state_);
}
IN_PROC_BROWSER_TEST_F(NetworkStateNotifierTest, TestConnecting) {
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::NETWORK_STATE_CHANGED,
NotificationService::AllSources());
EXPECT_CALL(*mock_network_library_, Connected())
.Times(1)
.WillOnce((Return(false)))
.RetiresOnSaturation();
EXPECT_CALL(*mock_network_library_, Connecting())
.Times(1)
.WillOnce((Return(true)))
.RetiresOnSaturation();
NetworkStateNotifier* notifier = NetworkStateNotifier::Get();
notifier->NetworkChanged(mock_network_library_);
WaitForNotification();
EXPECT_EQ(chromeos::NetworkStateDetails::CONNECTING, state_);
}
IN_PROC_BROWSER_TEST_F(NetworkStateNotifierTest, TestDisconnected) {
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::NETWORK_STATE_CHANGED,
NotificationService::AllSources());
EXPECT_CALL(*mock_network_library_, Connected())
.Times(1)
.WillOnce((Return(false)))
.RetiresOnSaturation();
EXPECT_CALL(*mock_network_library_, Connecting())
.Times(1)
.WillOnce((Return(false)))
.RetiresOnSaturation();
NetworkStateNotifier* notifier = NetworkStateNotifier::Get();
notifier->NetworkChanged(mock_network_library_);
WaitForNotification();
EXPECT_EQ(chromeos::NetworkStateDetails::DISCONNECTED, state_);
}
} // namespace chromeos
<commit_msg>Use WaitForNotification instead of busy loop.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/network_state_notifier.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/cros/cros_in_process_browser_test.h"
#include "chrome/browser/chromeos/cros/mock_network_library.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_registrar.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "chrome/test/ui_test_utils.h"
namespace chromeos {
using ::testing::Return;
using ::testing::_;
class NetworkStateNotifierTest : public CrosInProcessBrowserTest,
public NotificationObserver {
public:
NetworkStateNotifierTest() {
}
protected:
virtual void SetUpInProcessBrowserTestFixture() {
InitStatusAreaMocks();
SetStatusAreaMocksExpectations();
// Initialize network state notifier.
ASSERT_TRUE(CrosLibrary::Get()->EnsureLoaded());
ASSERT_TRUE(mock_network_library_);
EXPECT_CALL(*mock_network_library_, Connected())
.Times(1)
.WillRepeatedly((Return(true)))
.RetiresOnSaturation();
NetworkStateNotifier::Get();
}
// NotificationObserver overrides.
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
EXPECT_TRUE(ChromeThread::CurrentlyOn(ChromeThread::UI));
EXPECT_TRUE(NotificationType::NETWORK_STATE_CHANGED == type);
chromeos::NetworkStateDetails* state_details =
Details<chromeos::NetworkStateDetails>(details).ptr();
state_ = state_details->state();
}
void WaitForNotification() {
ui_test_utils::WaitForNotification(
NotificationType::NETWORK_STATE_CHANGED);
}
protected:
NetworkStateDetails::State state_;
};
IN_PROC_BROWSER_TEST_F(NetworkStateNotifierTest, TestConnected) {
// NETWORK_STATE_CHAGNED has to be registered in UI thread.
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::NETWORK_STATE_CHANGED,
NotificationService::AllSources());
EXPECT_CALL(*mock_network_library_, Connected())
.Times(1)
.WillRepeatedly((Return(true)))
.RetiresOnSaturation();
NetworkStateNotifier* notifier = NetworkStateNotifier::Get();
notifier->NetworkChanged(mock_network_library_);
WaitForNotification();
EXPECT_EQ(chromeos::NetworkStateDetails::CONNECTED, state_);
}
IN_PROC_BROWSER_TEST_F(NetworkStateNotifierTest, TestConnecting) {
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::NETWORK_STATE_CHANGED,
NotificationService::AllSources());
EXPECT_CALL(*mock_network_library_, Connected())
.Times(1)
.WillOnce((Return(false)))
.RetiresOnSaturation();
EXPECT_CALL(*mock_network_library_, Connecting())
.Times(1)
.WillOnce((Return(true)))
.RetiresOnSaturation();
NetworkStateNotifier* notifier = NetworkStateNotifier::Get();
notifier->NetworkChanged(mock_network_library_);
WaitForNotification();
EXPECT_EQ(chromeos::NetworkStateDetails::CONNECTING, state_);
}
IN_PROC_BROWSER_TEST_F(NetworkStateNotifierTest, TestDisconnected) {
NotificationRegistrar registrar;
registrar.Add(this, NotificationType::NETWORK_STATE_CHANGED,
NotificationService::AllSources());
EXPECT_CALL(*mock_network_library_, Connected())
.Times(1)
.WillOnce((Return(false)))
.RetiresOnSaturation();
EXPECT_CALL(*mock_network_library_, Connecting())
.Times(1)
.WillOnce((Return(false)))
.RetiresOnSaturation();
NetworkStateNotifier* notifier = NetworkStateNotifier::Get();
notifier->NetworkChanged(mock_network_library_);
WaitForNotification();
EXPECT_EQ(chromeos::NetworkStateDetails::DISCONNECTED, state_);
}
} // namespace chromeos
<|endoftext|> |
<commit_before>#pragma once
#include <algorithm>
#include <codecvt>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
#include <Windows.h>
#ifdef CUSTOM_LOGGER
#include CUSTOM_LOGGER
#endif
#ifdef _DEBUG
#ifndef LOG_DEBUG
#define LOG_DEBUG std::wcout << L"[DEBUG] "
#endif
#endif
#ifndef LOG_INFO
#define LOG_INFO std::wcout << L"[INFO] "
#endif
#ifndef LOG_WARNING
#define LOG_WARNING std::wcout << L"[WARNING] "
#endif
#ifndef LOG_ERROR
#define LOG_ERROR std::wcout << L"[ERROR] "
#endif
#include <RenHook/Hooks/Hooks.hpp><commit_msg>Add line separator for LOG_* functions<commit_after>#pragma once
#include <algorithm>
#include <codecvt>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
#include <Windows.h>
#ifdef CUSTOM_LOGGER
#include CUSTOM_LOGGER
#endif
#ifdef _DEBUG
#ifndef LOG_DEBUG
#define LOG_DEBUG std::wcout << L"[DEBUG] "
#endif
#endif
#ifndef LOG_INFO
#define LOG_INFO std::wcout << L"[INFO] "
#endif
#ifndef LOG_WARNING
#define LOG_WARNING std::wcout << L"[WARNING] "
#endif
#ifndef LOG_ERROR
#define LOG_ERROR std::wcout << L"[ERROR] "
#endif
#ifndef LOG_LINE_SEPARATOR
#define LOG_LINE_SEPARATOR std::endl
#endif
#include <RenHook/Hooks/Hooks.hpp><|endoftext|> |
<commit_before>//==============================================================================
// Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved.
/// \author AMD Developer Tools Team
/// \file
/// \brief Occupancy File Info Data Data Handler Interface Implementation
//==============================================================================
// std
#include <fstream>
#include <functional>
// Common
#include <DeviceInfoUtils.h>
// profiler common
#include <ProfilerOutputFileDefs.h>
#include <StringUtils.h>
#include "OccupancyFileInfoDataHandlerImp.h"
#include "OccupancyInfoDataHandlerImp.h"
#include "AtpDataHandlerImp.h"
OccupancyFileInfoDataHandler::OccupancyFileInfoDataHandler(std::string& occupancyFileName):
m_occupancyFileName(occupancyFileName),
m_bIsDataReady(false),
m_ppHeaderList(nullptr),
m_headerColumnCount(0u),
m_occupancyFileMajorVersion(0u),
m_occupancyFileMinorVersion(0u)
{
}
bool OccupancyFileInfoDataHandler::ParseOccupancyFile(const char* pOccupancyFile)
{
bool success = m_bIsDataReady;
if (!m_bIsDataReady)
{
success = Parse(pOccupancyFile);
if (success)
{
GenerateKernelInfoByThreadId();
}
m_bIsDataReady = success;
}
return success;
}
bool OccupancyFileInfoDataHandler::Parse(const char* pOccupancyFile)
{
bool success = false;
bool foundVersion = false;
std::ifstream occupancyFileStream;
occupancyFileStream.open(pOccupancyFile, std::ifstream::in);
typedef size_t StringHash;
std::map<StringHash, unsigned int> stringHashMap;
bool bFoundHeader = false;
size_t kernelCount = 0u;
size_t currentKernelCount = 0u;
auto GetColumnIndex = [&](std::string columnName)->size_t
{
std::hash<std::string> stringHash;
size_t index = std::string::npos;
StringHash columnNameHash = stringHash(columnName);
if (stringHashMap.find(columnNameHash) != stringHashMap.end())
{
index = stringHashMap[columnNameHash];
}
return index;
};
std::vector<std::string> columnData;
auto ColumnStrOutToUint = [&](std::string columnName)->unsigned int
{
unsigned int outVal;
std::string tempString = columnData[GetColumnIndex(columnName)];
if (!StringUtils::Parse(tempString, outVal))
{
outVal = 0u;
}
return outVal;
};
if (occupancyFileStream.is_open())
{
while (!occupancyFileStream.eof())
{
constexpr size_t lineSizeBuffer = 2048;
char lineBuffer[lineSizeBuffer];
occupancyFileStream.getline(lineBuffer, lineSizeBuffer);
if ('#' == lineBuffer[0])
{
// Comments Section of the Occupancy File
std::string occupancyHeader(lineBuffer);
std::string profilerVersionNameString(FILE_HEADER_PROFILER_VERSION);
size_t profilerVersionNameStringPosition = occupancyHeader.find(profilerVersionNameString);
if (std::string::npos != profilerVersionNameStringPosition)
{
std::string profilerVersionString = std::string(occupancyHeader.begin() + profilerVersionNameStringPosition + profilerVersionNameString.size() + 1, occupancyHeader.end());
if (!StringUtils::ParseMajorMinorVersion(profilerVersionString, m_occupancyFileMajorVersion, m_occupancyFileMinorVersion))
{
m_occupancyFileMajorVersion = m_occupancyFileMinorVersion = 0u;
}
else
{
foundVersion = true;
}
}
std::string kernelCountNameString(FILE_HEADER_KERNEL_COUNT);
size_t kernelCountStringPosition = occupancyHeader.find(kernelCountNameString);
if (std::string::npos != kernelCountStringPosition)
{
std::string kernelCountString = std::string(occupancyHeader.begin() + kernelCountStringPosition + kernelCountNameString.size() + 1, occupancyHeader.end());
if (!StringUtils::Parse(kernelCountString, kernelCount))
{
kernelCount = 0u;
}
}
}
else
{
if (!bFoundHeader)
{
bFoundHeader = true;
std::vector<std::string> columnHeaders;
StringUtils::Split(columnHeaders, lineBuffer, ",");
m_headerColumnCount = static_cast<unsigned int>(columnHeaders.size());
m_ppHeaderList = new(std::nothrow) char* [m_headerColumnCount];
if (nullptr != m_ppHeaderList)
{
unsigned int headerIndex = 0;
std::hash<std::string> stringHash;
for (std::vector<std::string>::iterator columnHeaderIter = columnHeaders.begin(); columnHeaderIter != columnHeaders.end(); ++columnHeaderIter)
{
StringHash columnNameHash = stringHash(*columnHeaderIter);
stringHashMap.insert(std::pair<StringHash, unsigned int>(columnNameHash, headerIndex));
m_ppHeaderList[headerIndex] = new(std::nothrow) char[columnHeaderIter->size() + 1];
if (nullptr != m_ppHeaderList)
{
memcpy(m_ppHeaderList[headerIndex], columnHeaderIter->c_str(), columnHeaderIter->size());
m_ppHeaderList[headerIndex][columnHeaderIter->size()] = '\0';
headerIndex++;
}
}
}
}
else
{
columnData.clear();
StringUtils::Split(columnData, lineBuffer, ",");
OccupancyInfoDataHandler* pTmpOccupancyInfo = new OccupancyInfoDataHandler();
pTmpOccupancyInfo->m_occupancyInfo.m_nTID = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_THREADID);
pTmpOccupancyInfo->m_occupancyInfo.m_strKernelName = columnData[GetColumnIndex(OCCUPANCY_COLUMN_NAME_KERNELNAME)];
pTmpOccupancyInfo->m_occupancyInfo.m_strDeviceName = columnData[GetColumnIndex(OCCUPANCY_COLUMN_NAME_DEVICENAME)];
pTmpOccupancyInfo->m_occupancyInfo.m_nDeviceGfxIpVer = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_GRAPHICSIPVERSION);
pTmpOccupancyInfo->m_occupancyInfo.m_nNbrComputeUnits = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_NUMBEROFCOMPUTEUNITS);
pTmpOccupancyInfo->m_occupancyInfo.m_nMaxWavesPerCU = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_MAXNUMBEROFWAVEFRONTSPERCU);
pTmpOccupancyInfo->m_occupancyInfo.m_nMaxWGPerCU = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_MAXNUMBEROFWORKGROUPPERCU);
pTmpOccupancyInfo->m_occupancyInfo.m_nMaxVGPRS = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_MAXNUMBEROFVGPR);
pTmpOccupancyInfo->m_occupancyInfo.m_nMaxSGPRS = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_MAXNUMBEROFSGPR);
pTmpOccupancyInfo->m_occupancyInfo.m_nMaxLDS = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_MAXAMOUNTOFLDS);
pTmpOccupancyInfo->m_occupancyInfo.m_nUsedVGPRS = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_NUMBEROFVGPRUSED);
pTmpOccupancyInfo->m_occupancyInfo.m_nUsedSGPRS = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_NUMBEROFSGPRUSED);
pTmpOccupancyInfo->m_occupancyInfo.m_nUsedLDS = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_AMOUNTOFLDSUSED);
pTmpOccupancyInfo->m_occupancyInfo.m_nWavefrontSize = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_SIZEOFWAVEFRONT);
pTmpOccupancyInfo->m_occupancyInfo.m_nWorkgroupSize = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_WORKGROUPSIZE);
pTmpOccupancyInfo->m_occupancyInfo.m_nWavesPerWG = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_WAVEFRONTSPERWORKGROUP);
pTmpOccupancyInfo->m_occupancyInfo.m_nMaxWGSize = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_MAXWORKGROUPSIZE);
pTmpOccupancyInfo->m_occupancyInfo.m_nMaxWavesPerWG = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_MAXWAVEFRONTSPERWORKGROUP);
pTmpOccupancyInfo->m_occupancyInfo.m_nGlobalWorkSize = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_GLOBALWORKSIZE);
pTmpOccupancyInfo->m_occupancyInfo.m_nMaxGlobalWorkSize = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_MAXIMUMGLOBALWORKSIZE);
pTmpOccupancyInfo->m_occupancyInfo.m_nVGPRLimitedWaveCount = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_NBRVGPRLIMITEDWAVES);
pTmpOccupancyInfo->m_occupancyInfo.m_nSGPRLimitedWaveCount = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_NBRSGPRLIMITEDWAVES);
pTmpOccupancyInfo->m_occupancyInfo.m_nLDSLimitedWaveCount = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_NBRLDSLIMITEDWAVES);
pTmpOccupancyInfo->m_occupancyInfo.m_nWGLimitedWaveCount = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_NBROFWGLIMITEDWAVES);
pTmpOccupancyInfo->m_occupancyInfo.m_nSimdsPerCU = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_SIMDSPERCU);
if (0 == pTmpOccupancyInfo->m_occupancyInfo.m_nSimdsPerCU) // hardcode to 4 if the occupancy file does not have this data
{
pTmpOccupancyInfo->m_occupancyInfo.m_nSimdsPerCU = 4;
}
pTmpOccupancyInfo->m_occupancyInfo.m_fOccupancy = static_cast<float>(ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_KERNELOCCUPANCY));
if (pTmpOccupancyInfo->m_occupancyInfo.m_nDeviceGfxIpVer == 0)
{
AMDTDeviceInfoUtils::Instance()->GetHardwareGeneration(pTmpOccupancyInfo->m_occupancyInfo.m_strDeviceName.c_str(), pTmpOccupancyInfo->m_occupancyInfo.m_gen);
}
else
{
AMDTDeviceInfoUtils::Instance()->GfxIPVerToHwGeneration(pTmpOccupancyInfo->m_occupancyInfo.m_nDeviceGfxIpVer, pTmpOccupancyInfo->m_occupancyInfo.m_gen);
}
m_occupancyInfoList.push_back(pTmpOccupancyInfo);
AtpDataHandler::Instance()->OnParserProgress("Parsing Occupancy Data", static_cast<unsigned int>(currentKernelCount), static_cast<unsigned int>(kernelCount));
currentKernelCount++;
}
}
}
success = foundVersion;
}
return success;
}
bool OccupancyFileInfoDataHandler::IsDataReady() const
{
return m_bIsDataReady;
}
void OccupancyFileInfoDataHandler::GetOccupancyFileVersion(unsigned int& major, unsigned int& minor) const
{
major = m_occupancyFileMajorVersion;
minor = m_occupancyFileMinorVersion;
}
void OccupancyFileInfoDataHandler::GetHeaderInOrder(char** ppColumnNames, unsigned int& columnCount) const
{
if (nullptr != ppColumnNames && nullptr != m_ppHeaderList)
{
columnCount = static_cast<unsigned int>(m_headerColumnCount);
*ppColumnNames = *m_ppHeaderList;
}
}
void OccupancyFileInfoDataHandler::GetOccupancyThreads(osThreadId** ppThreadId, unsigned int& threadCount) const
{
if (!m_kernelCountInfoByThreadId.empty())
{
threadCount = static_cast<unsigned int>(m_kernelCountInfoByThreadId.size());
*ppThreadId = new(std::nothrow) osThreadId[threadCount];
if (nullptr != *ppThreadId)
{
m_threadIdList.push_back(*ppThreadId);
unsigned int threadIndex = 0;
for (OccupancyInfoByThreadId::const_iterator it = m_kernelCountInfoByThreadId.begin(); it != m_kernelCountInfoByThreadId.end(); ++it)
{
(*ppThreadId)[threadIndex] = it->first;
threadIndex++;
}
}
}
else
{
threadCount = 0u;
}
}
void OccupancyFileInfoDataHandler::GetKernelCountByThreadId(osThreadId threadId, unsigned int& kernelCount) const
{
OccupancyInfoByThreadId::const_iterator it = m_kernelCountInfoByThreadId.find(threadId);
if (it != m_kernelCountInfoByThreadId.end())
{
kernelCount = static_cast<unsigned int>(it->second.size());
}
}
const IOccupancyInfoDataHandler* OccupancyFileInfoDataHandler::GetOccupancyInfoDataHandler(osThreadId threadId, unsigned int index) const
{
IOccupancyInfoDataHandler* pRetHandler = nullptr;
OccupancyInfoByThreadId::const_iterator occupancyInfoIter = m_kernelCountInfoByThreadId.find(threadId);
if (occupancyInfoIter != m_kernelCountInfoByThreadId.end() && index < occupancyInfoIter->second.size())
{
pRetHandler = occupancyInfoIter->second[index];
}
return pRetHandler;
}
void OccupancyFileInfoDataHandler::ReleaseData()
{
m_bIsDataReady = false;
OccupancyInfoByThreadId::iterator iter;
for (iter = m_kernelCountInfoByThreadId.begin(); iter != m_kernelCountInfoByThreadId.end(); ++iter)
{
for (std::vector<IOccupancyInfoDataHandler*>::iterator infoListIter = iter->second.begin(); infoListIter != iter->second.end() && nullptr != (*infoListIter); ++infoListIter)
{
delete(*infoListIter);
}
iter->second.clear();
}
m_kernelCountInfoByThreadId.clear();
m_occupancyInfoList.clear();
for (unsigned int i = 0; i < m_headerColumnCount; i++)
{
delete[] m_ppHeaderList[i];
}
delete[] m_ppHeaderList;
for (std::vector<osThreadId*>::iterator it = m_threadIdList.begin(); it != m_threadIdList.end(); ++it)
{
delete(*it);
}
m_threadIdList.clear();
}
OccupancyFileInfoDataHandler::~OccupancyFileInfoDataHandler()
{
if (m_bIsDataReady)
{
OccupancyInfoByThreadId::iterator iter;
for (iter = m_kernelCountInfoByThreadId.begin(); iter != m_kernelCountInfoByThreadId.end(); ++iter)
{
for (std::vector<IOccupancyInfoDataHandler*>::iterator infoListIter = iter->second.begin(); infoListIter != iter->second.end() && nullptr != (*infoListIter); ++infoListIter)
{
delete(*infoListIter);
}
iter->second.clear();
}
m_kernelCountInfoByThreadId.clear();
m_occupancyInfoList.clear();
for (unsigned int i = 0; i < m_headerColumnCount; i++)
{
delete[] m_ppHeaderList[i];
}
delete[] m_ppHeaderList;
for (std::vector<osThreadId*>::iterator it = m_threadIdList.begin(); it != m_threadIdList.end(); ++it)
{
delete(*it);
}
m_threadIdList.clear();
}
}
void OccupancyFileInfoDataHandler::GenerateKernelInfoByThreadId()
{
for (std::vector<IOccupancyInfoDataHandler*>::iterator it = m_occupancyInfoList.begin(); it != m_occupancyInfoList.end(); ++it)
{
OccupancyInfoByThreadId::iterator occupancyInfoByThreadIter = m_kernelCountInfoByThreadId.find((*it)->GetThreadId());
if (occupancyInfoByThreadIter != m_kernelCountInfoByThreadId.end())
{
occupancyInfoByThreadIter->second.push_back(*it);
}
else
{
std::vector<IOccupancyInfoDataHandler*> newList;
newList.push_back(*it);
m_kernelCountInfoByThreadId.insert(std::pair<osThreadId, std::vector<IOccupancyInfoDataHandler*>>((*it)->GetThreadId(), newList));
}
}
}
<commit_msg>Fix an issue with Occupancy file parser<commit_after>//==============================================================================
// Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved.
/// \author AMD Developer Tools Team
/// \file
/// \brief Occupancy File Info Data Data Handler Interface Implementation
//==============================================================================
// std
#include <fstream>
#include <functional>
// Common
#include <DeviceInfoUtils.h>
// profiler common
#include <ProfilerOutputFileDefs.h>
#include <StringUtils.h>
#include "OccupancyFileInfoDataHandlerImp.h"
#include "OccupancyInfoDataHandlerImp.h"
#include "AtpDataHandlerImp.h"
OccupancyFileInfoDataHandler::OccupancyFileInfoDataHandler(std::string& occupancyFileName):
m_occupancyFileName(occupancyFileName),
m_bIsDataReady(false),
m_ppHeaderList(nullptr),
m_headerColumnCount(0u),
m_occupancyFileMajorVersion(0u),
m_occupancyFileMinorVersion(0u)
{
}
bool OccupancyFileInfoDataHandler::ParseOccupancyFile(const char* pOccupancyFile)
{
bool success = m_bIsDataReady;
if (!m_bIsDataReady)
{
success = Parse(pOccupancyFile);
if (success)
{
GenerateKernelInfoByThreadId();
}
m_bIsDataReady = success;
}
return success;
}
bool OccupancyFileInfoDataHandler::Parse(const char* pOccupancyFile)
{
bool success = false;
bool foundVersion = false;
std::ifstream occupancyFileStream;
occupancyFileStream.open(pOccupancyFile, std::ifstream::in);
typedef size_t StringHash;
std::map<StringHash, unsigned int> stringHashMap;
bool bFoundHeader = false;
size_t kernelCount = 0u;
size_t currentKernelCount = 0u;
auto GetColumnIndex = [&](std::string columnName)->size_t
{
std::hash<std::string> stringHash;
size_t index = std::string::npos;
StringHash columnNameHash = stringHash(columnName);
if (stringHashMap.find(columnNameHash) != stringHashMap.end())
{
index = stringHashMap[columnNameHash];
}
return index;
};
std::vector<std::string> columnData;
auto ColumnStrOutToUint = [&](std::string columnName)->unsigned int
{
unsigned int outVal;
std::string tempString = columnData[GetColumnIndex(columnName)];
if (!StringUtils::Parse(tempString, outVal))
{
outVal = 0u;
}
return outVal;
};
if (occupancyFileStream.is_open())
{
while (!occupancyFileStream.eof())
{
constexpr size_t lineSizeBuffer = 2048;
char lineBuffer[lineSizeBuffer];
occupancyFileStream.getline(lineBuffer, lineSizeBuffer);
if (occupancyFileStream.eof())
{
break;
}
if ('#' == lineBuffer[0])
{
// Comments Section of the Occupancy File
std::string occupancyHeader(lineBuffer);
std::string profilerVersionNameString(FILE_HEADER_PROFILER_VERSION);
size_t profilerVersionNameStringPosition = occupancyHeader.find(profilerVersionNameString);
if (std::string::npos != profilerVersionNameStringPosition)
{
std::string profilerVersionString = std::string(occupancyHeader.begin() + profilerVersionNameStringPosition + profilerVersionNameString.size() + 1, occupancyHeader.end());
if (!StringUtils::ParseMajorMinorVersion(profilerVersionString, m_occupancyFileMajorVersion, m_occupancyFileMinorVersion))
{
m_occupancyFileMajorVersion = m_occupancyFileMinorVersion = 0u;
}
else
{
foundVersion = true;
}
}
std::string kernelCountNameString(FILE_HEADER_KERNEL_COUNT);
size_t kernelCountStringPosition = occupancyHeader.find(kernelCountNameString);
if (std::string::npos != kernelCountStringPosition)
{
std::string kernelCountString = std::string(occupancyHeader.begin() + kernelCountStringPosition + kernelCountNameString.size() + 1, occupancyHeader.end());
if (!StringUtils::Parse(kernelCountString, kernelCount))
{
kernelCount = 0u;
}
}
}
else
{
if (!bFoundHeader)
{
bFoundHeader = true;
std::vector<std::string> columnHeaders;
StringUtils::Split(columnHeaders, lineBuffer, ",");
m_headerColumnCount = static_cast<unsigned int>(columnHeaders.size());
m_ppHeaderList = new(std::nothrow) char* [m_headerColumnCount];
if (nullptr != m_ppHeaderList)
{
unsigned int headerIndex = 0;
std::hash<std::string> stringHash;
for (std::vector<std::string>::iterator columnHeaderIter = columnHeaders.begin(); columnHeaderIter != columnHeaders.end(); ++columnHeaderIter)
{
StringHash columnNameHash = stringHash(*columnHeaderIter);
stringHashMap.insert(std::pair<StringHash, unsigned int>(columnNameHash, headerIndex));
m_ppHeaderList[headerIndex] = new(std::nothrow) char[columnHeaderIter->size() + 1];
if (nullptr != m_ppHeaderList)
{
memcpy(m_ppHeaderList[headerIndex], columnHeaderIter->c_str(), columnHeaderIter->size());
m_ppHeaderList[headerIndex][columnHeaderIter->size()] = '\0';
headerIndex++;
}
}
}
}
else
{
columnData.clear();
StringUtils::Split(columnData, lineBuffer, ",");
OccupancyInfoDataHandler* pTmpOccupancyInfo = new OccupancyInfoDataHandler();
pTmpOccupancyInfo->m_occupancyInfo.m_nTID = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_THREADID);
pTmpOccupancyInfo->m_occupancyInfo.m_strKernelName = columnData[GetColumnIndex(OCCUPANCY_COLUMN_NAME_KERNELNAME)];
pTmpOccupancyInfo->m_occupancyInfo.m_strDeviceName = columnData[GetColumnIndex(OCCUPANCY_COLUMN_NAME_DEVICENAME)];
pTmpOccupancyInfo->m_occupancyInfo.m_nDeviceGfxIpVer = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_GRAPHICSIPVERSION);
pTmpOccupancyInfo->m_occupancyInfo.m_nNbrComputeUnits = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_NUMBEROFCOMPUTEUNITS);
pTmpOccupancyInfo->m_occupancyInfo.m_nMaxWavesPerCU = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_MAXNUMBEROFWAVEFRONTSPERCU);
pTmpOccupancyInfo->m_occupancyInfo.m_nMaxWGPerCU = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_MAXNUMBEROFWORKGROUPPERCU);
pTmpOccupancyInfo->m_occupancyInfo.m_nMaxVGPRS = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_MAXNUMBEROFVGPR);
pTmpOccupancyInfo->m_occupancyInfo.m_nMaxSGPRS = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_MAXNUMBEROFSGPR);
pTmpOccupancyInfo->m_occupancyInfo.m_nMaxLDS = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_MAXAMOUNTOFLDS);
pTmpOccupancyInfo->m_occupancyInfo.m_nUsedVGPRS = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_NUMBEROFVGPRUSED);
pTmpOccupancyInfo->m_occupancyInfo.m_nUsedSGPRS = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_NUMBEROFSGPRUSED);
pTmpOccupancyInfo->m_occupancyInfo.m_nUsedLDS = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_AMOUNTOFLDSUSED);
pTmpOccupancyInfo->m_occupancyInfo.m_nWavefrontSize = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_SIZEOFWAVEFRONT);
pTmpOccupancyInfo->m_occupancyInfo.m_nWorkgroupSize = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_WORKGROUPSIZE);
pTmpOccupancyInfo->m_occupancyInfo.m_nWavesPerWG = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_WAVEFRONTSPERWORKGROUP);
pTmpOccupancyInfo->m_occupancyInfo.m_nMaxWGSize = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_MAXWORKGROUPSIZE);
pTmpOccupancyInfo->m_occupancyInfo.m_nMaxWavesPerWG = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_MAXWAVEFRONTSPERWORKGROUP);
pTmpOccupancyInfo->m_occupancyInfo.m_nGlobalWorkSize = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_GLOBALWORKSIZE);
pTmpOccupancyInfo->m_occupancyInfo.m_nMaxGlobalWorkSize = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_MAXIMUMGLOBALWORKSIZE);
pTmpOccupancyInfo->m_occupancyInfo.m_nVGPRLimitedWaveCount = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_NBRVGPRLIMITEDWAVES);
pTmpOccupancyInfo->m_occupancyInfo.m_nSGPRLimitedWaveCount = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_NBRSGPRLIMITEDWAVES);
pTmpOccupancyInfo->m_occupancyInfo.m_nLDSLimitedWaveCount = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_NBRLDSLIMITEDWAVES);
pTmpOccupancyInfo->m_occupancyInfo.m_nWGLimitedWaveCount = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_NBROFWGLIMITEDWAVES);
pTmpOccupancyInfo->m_occupancyInfo.m_nSimdsPerCU = ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_SIMDSPERCU);
if (0 == pTmpOccupancyInfo->m_occupancyInfo.m_nSimdsPerCU) // hardcode to 4 if the occupancy file does not have this data
{
pTmpOccupancyInfo->m_occupancyInfo.m_nSimdsPerCU = 4;
}
pTmpOccupancyInfo->m_occupancyInfo.m_fOccupancy = static_cast<float>(ColumnStrOutToUint(OCCUPANCY_COLUMN_NAME_KERNELOCCUPANCY));
if (pTmpOccupancyInfo->m_occupancyInfo.m_nDeviceGfxIpVer == 0)
{
AMDTDeviceInfoUtils::Instance()->GetHardwareGeneration(pTmpOccupancyInfo->m_occupancyInfo.m_strDeviceName.c_str(), pTmpOccupancyInfo->m_occupancyInfo.m_gen);
}
else
{
AMDTDeviceInfoUtils::Instance()->GfxIPVerToHwGeneration(pTmpOccupancyInfo->m_occupancyInfo.m_nDeviceGfxIpVer, pTmpOccupancyInfo->m_occupancyInfo.m_gen);
}
m_occupancyInfoList.push_back(pTmpOccupancyInfo);
AtpDataHandler::Instance()->OnParserProgress("Parsing Occupancy Data", static_cast<unsigned int>(currentKernelCount), static_cast<unsigned int>(kernelCount));
currentKernelCount++;
}
}
}
success = foundVersion;
}
return success;
}
bool OccupancyFileInfoDataHandler::IsDataReady() const
{
return m_bIsDataReady;
}
void OccupancyFileInfoDataHandler::GetOccupancyFileVersion(unsigned int& major, unsigned int& minor) const
{
major = m_occupancyFileMajorVersion;
minor = m_occupancyFileMinorVersion;
}
void OccupancyFileInfoDataHandler::GetHeaderInOrder(char** ppColumnNames, unsigned int& columnCount) const
{
if (nullptr != ppColumnNames && nullptr != m_ppHeaderList)
{
columnCount = static_cast<unsigned int>(m_headerColumnCount);
*ppColumnNames = *m_ppHeaderList;
}
}
void OccupancyFileInfoDataHandler::GetOccupancyThreads(osThreadId** ppThreadId, unsigned int& threadCount) const
{
if (!m_kernelCountInfoByThreadId.empty())
{
threadCount = static_cast<unsigned int>(m_kernelCountInfoByThreadId.size());
*ppThreadId = new(std::nothrow) osThreadId[threadCount];
if (nullptr != *ppThreadId)
{
m_threadIdList.push_back(*ppThreadId);
unsigned int threadIndex = 0;
for (OccupancyInfoByThreadId::const_iterator it = m_kernelCountInfoByThreadId.begin(); it != m_kernelCountInfoByThreadId.end(); ++it)
{
(*ppThreadId)[threadIndex] = it->first;
threadIndex++;
}
}
}
else
{
threadCount = 0u;
}
}
void OccupancyFileInfoDataHandler::GetKernelCountByThreadId(osThreadId threadId, unsigned int& kernelCount) const
{
OccupancyInfoByThreadId::const_iterator it = m_kernelCountInfoByThreadId.find(threadId);
if (it != m_kernelCountInfoByThreadId.end())
{
kernelCount = static_cast<unsigned int>(it->second.size());
}
}
const IOccupancyInfoDataHandler* OccupancyFileInfoDataHandler::GetOccupancyInfoDataHandler(osThreadId threadId, unsigned int index) const
{
IOccupancyInfoDataHandler* pRetHandler = nullptr;
OccupancyInfoByThreadId::const_iterator occupancyInfoIter = m_kernelCountInfoByThreadId.find(threadId);
if (occupancyInfoIter != m_kernelCountInfoByThreadId.end() && index < occupancyInfoIter->second.size())
{
pRetHandler = occupancyInfoIter->second[index];
}
return pRetHandler;
}
void OccupancyFileInfoDataHandler::ReleaseData()
{
m_bIsDataReady = false;
OccupancyInfoByThreadId::iterator iter;
for (iter = m_kernelCountInfoByThreadId.begin(); iter != m_kernelCountInfoByThreadId.end(); ++iter)
{
for (std::vector<IOccupancyInfoDataHandler*>::iterator infoListIter = iter->second.begin(); infoListIter != iter->second.end() && nullptr != (*infoListIter); ++infoListIter)
{
delete(*infoListIter);
}
iter->second.clear();
}
m_kernelCountInfoByThreadId.clear();
m_occupancyInfoList.clear();
for (unsigned int i = 0; i < m_headerColumnCount; i++)
{
delete[] m_ppHeaderList[i];
}
delete[] m_ppHeaderList;
for (std::vector<osThreadId*>::iterator it = m_threadIdList.begin(); it != m_threadIdList.end(); ++it)
{
delete(*it);
}
m_threadIdList.clear();
}
OccupancyFileInfoDataHandler::~OccupancyFileInfoDataHandler()
{
if (m_bIsDataReady)
{
OccupancyInfoByThreadId::iterator iter;
for (iter = m_kernelCountInfoByThreadId.begin(); iter != m_kernelCountInfoByThreadId.end(); ++iter)
{
for (std::vector<IOccupancyInfoDataHandler*>::iterator infoListIter = iter->second.begin(); infoListIter != iter->second.end() && nullptr != (*infoListIter); ++infoListIter)
{
delete(*infoListIter);
}
iter->second.clear();
}
m_kernelCountInfoByThreadId.clear();
m_occupancyInfoList.clear();
for (unsigned int i = 0; i < m_headerColumnCount; i++)
{
delete[] m_ppHeaderList[i];
}
delete[] m_ppHeaderList;
for (std::vector<osThreadId*>::iterator it = m_threadIdList.begin(); it != m_threadIdList.end(); ++it)
{
delete(*it);
}
m_threadIdList.clear();
}
}
void OccupancyFileInfoDataHandler::GenerateKernelInfoByThreadId()
{
for (std::vector<IOccupancyInfoDataHandler*>::iterator it = m_occupancyInfoList.begin(); it != m_occupancyInfoList.end(); ++it)
{
OccupancyInfoByThreadId::iterator occupancyInfoByThreadIter = m_kernelCountInfoByThreadId.find((*it)->GetThreadId());
if (occupancyInfoByThreadIter != m_kernelCountInfoByThreadId.end())
{
occupancyInfoByThreadIter->second.push_back(*it);
}
else
{
std::vector<IOccupancyInfoDataHandler*> newList;
newList.push_back(*it);
m_kernelCountInfoByThreadId.insert(std::pair<osThreadId, std::vector<IOccupancyInfoDataHandler*>>((*it)->GetThreadId(), newList));
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define GLM_FORCE_RADIANS
#include <string>
#include "axis.h"
#include "camera.h"
#include "frustum.h"
#include "gl_util.h"
#include "grid.h"
#include "tango_data.h"
#include "trace.h"
GLuint screen_width;
GLuint screen_height;
Camera *cam;
Axis *axis;
Frustum *frustum;
Grid *grid;
Trace *trace;
enum CameraType {
FIRST_PERSON = 0,
THIRD_PERSON = 1,
TOP_DOWN = 2
};
int camera_type;
// Quaternion format of rotation.
const glm::vec3 kThirdPersonCameraPosition = glm::vec3(0.0f, 3.0f, 3.0f);
const glm::quat kThirdPersonCameraRotation = glm::quat(0.92388f, -0.38268f,
0.0f, 0.0f);
const glm::vec3 kTopDownCameraPosition = glm::vec3(0.0f, 10.0f, 0.0f);
const glm::quat kTopDownCameraRotation = glm::quat(0.70711f, -0.70711f, 0.0f,
0.0f);
bool SetupGraphics(int w, int h) {
LOGI("setupGraphics(%d, %d)", w, h);
screen_width = w;
screen_height = h;
cam = new Camera();
axis = new Axis();
frustum = new Frustum();
trace = new Trace();
grid = new Grid();
camera_type = FIRST_PERSON;
cam->SetAspectRatio((float) (w / h));
return true;
}
// Render frustum and trace with current position and rotation
// updated from TangoData, TangoPosition and TangoRotation is updated via callback function
// OnPoseAvailable(), which is updated when new pose data is available.
bool RenderFrame() {
glEnable (GL_DEPTH_TEST);
glEnable (GL_CULL_FACE);
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
glViewport(0, 0, screen_width, screen_height);
grid->SetPosition(glm::vec3(0.0f, -0.8f, 0.0f));
grid->Render(cam->GetCurrentProjectionViewMatrix());
int pose_index =
TangoData::GetInstance().current_pose_status[1]==TANGO_POSE_VALID ? 1 : 0;
glm::vec3 position = GlUtil::ConvertPositionToOpenGL(
TangoData::GetInstance().tango_position[pose_index]);
glm::quat rotation = GlUtil::ConvertRotationToOpenGL(
TangoData::GetInstance().tango_rotation[pose_index]);
cam->SetPosition(position);
if (camera_type == FIRST_PERSON) {
cam->SetRotation(rotation);
} else {
if(camera_type == TOP_DOWN){
cam->SetPosition(position+kTopDownCameraPosition);
}else{
cam->SetPosition(position+kThirdPersonCameraPosition);
}
frustum->SetPosition(position);
frustum->SetRotation(rotation);
frustum->Render(cam->GetCurrentProjectionViewMatrix());
trace->UpdateVertexArray(position);
trace->Render(cam->GetCurrentProjectionViewMatrix());
axis->SetPosition(position);
axis->SetRotation(rotation);
axis->Render(cam->GetCurrentProjectionViewMatrix());
}
return true;
}
void SetCamera(int camera_index) {
camera_type = camera_index;
switch (camera_index) {
case FIRST_PERSON:
LOGI("setting to First Person Camera");
break;
case THIRD_PERSON:
cam->SetRotation(kThirdPersonCameraRotation);
LOGI("setting to Third Person Camera");
break;
case TOP_DOWN:
cam->SetRotation(kTopDownCameraRotation);
LOGI("setting to Top Down Camera");
break;
default:
break;
}
}
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT void JNICALL Java_com_projecttango_areadescriptionnative_TangoJNINative_Initialize(
JNIEnv* env, jobject obj, bool is_learning, bool is_load_adf) {
LOGI("leanring:%d, adf:%d", is_learning, is_load_adf);
LOGI("In onCreate: Initialing and setting config");
if (!TangoData::GetInstance().Initialize())
{
LOGE("Tango initialization failed");
}
if (!TangoData::GetInstance().SetConfig(is_learning, is_load_adf))
{
LOGE("Tango set config failed");
}
}
JNIEXPORT void JNICALL Java_com_projecttango_areadescriptionnative_TangoJNINative_ConnectService(
JNIEnv* env, jobject obj) {
LOGI("In OnResume: Locking config and connecting service");
if (!TangoData::GetInstance().LockConfig()) {
LOGE("Tango lock config failed");
}
if (!TangoData::GetInstance().Connect()) {
LOGE("Tango connect failed");
}
}
JNIEXPORT void JNICALL Java_com_projecttango_areadescriptionnative_TangoJNINative_DisconnectService(
JNIEnv* env, jobject obj) {
LOGI("In OnPause: Unlocking config and disconnecting service");
if (TangoData::GetInstance().UnlockConfig()) {
LOGE("Tango unlock file failed");
}
TangoData::GetInstance().Disconnect();
}
JNIEXPORT void JNICALL Java_com_projecttango_areadescriptionnative_TangoJNINative_OnDestroy(
JNIEnv* env, jobject obj) {
delete cam;
delete axis;
delete grid;
delete frustum;
delete trace;
}
JNIEXPORT void JNICALL Java_com_projecttango_areadescriptionnative_TangoJNINative_SetupGraphic(
JNIEnv* env, jobject obj, jint width, jint height) {
SetupGraphics(width, height);
}
JNIEXPORT void JNICALL Java_com_projecttango_areadescriptionnative_TangoJNINative_Render(
JNIEnv* env, jobject obj) {
RenderFrame();
}
JNIEXPORT void JNICALL Java_com_projecttango_areadescriptionnative_TangoJNINative_SetCamera(
JNIEnv* env, jobject obj, int camera_index) {
SetCamera(camera_index);
}
JNIEXPORT jstring JNICALL Java_com_projecttango_areadescriptionnative_TangoJNINative_SaveADF(
JNIEnv* env, jobject obj) {
// Save ADF.
return (env)->NewStringUTF(TangoData::GetInstance().SaveADF());
}
JNIEXPORT void JNICALL Java_com_projecttango_areadescriptionnative_TangoJNINative_RemoveAllAdfs(
JNIEnv* env, jobject obj) {
TangoData::GetInstance().RemoveAllAdfs();
}
JNIEXPORT jstring JNICALL Java_com_projecttango_areadescriptionnative_TangoJNINative_GetUUID(
JNIEnv* env, jobject obj) {
return (env)->NewStringUTF(TangoData::GetInstance().uuid_);
}
JNIEXPORT jstring JNICALL Java_com_projecttango_areadescriptionnative_TangoJNINative_GetIsEnabledLearn(
JNIEnv* env, jobject obj) {
return (env)->NewStringUTF(
TangoData::GetInstance().is_learning_mode_enabled ? "Enabled" : "Disable");
}
JNIEXPORT jstring JNICALL Java_com_projecttango_areadescriptionnative_TangoJNINative_GetPoseString(
JNIEnv* env, jobject obj, int index) {
char pose_string[100];
char status[30];
switch (TangoData::GetInstance().current_pose_status[index]) {
case TANGO_POSE_INITIALIZING:
sprintf(status,"Initializing");
break;
case TANGO_POSE_VALID:
sprintf(status, "Valid");
break;
case TANGO_POSE_INVALID:
sprintf(status, "Invalid");
break;
case TANGO_POSE_UNKNOWN:
sprintf(status, "Unknown");
break;
default:
break;
}
sprintf(pose_string, "status:%s, count:%d, pose:%4.2f %4.2f %4.2f, delta_time: %4.2fms",
status,
TangoData::GetInstance().frame_count[index],
TangoData::GetInstance().tango_position[index].x,
TangoData::GetInstance().tango_position[index].y,
TangoData::GetInstance().tango_position[index].z,
TangoData::GetInstance().frame_delta_time[index]*1000.0f);
return (env)->NewStringUTF(pose_string);
}
JNIEXPORT jstring JNICALL Java_com_projecttango_areadescriptionnative_TangoJNINative_GetVersionString(
JNIEnv* env, jobject obj) {
return (env)->NewStringUTF(TangoData::GetInstance().GetVersonString());
}
#ifdef __cplusplus
}
#endif
<commit_msg>- fixed area description sample sample matrices issue<commit_after>/*
* Copyright 2014 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define GLM_FORCE_RADIANS
#include <string>
#include "axis.h"
#include "camera.h"
#include "frustum.h"
#include "gl_util.h"
#include "grid.h"
#include "tango_data.h"
#include "trace.h"
GLuint screen_width;
GLuint screen_height;
Camera *cam;
Axis *axis;
Frustum *frustum;
Grid *grid;
Trace *trace;
enum CameraType {
FIRST_PERSON = 0,
THIRD_PERSON = 1,
TOP_DOWN = 2
};
int camera_type;
// Quaternion format of rotation.
const glm::vec3 kThirdPersonCameraPosition = glm::vec3(0.0f, 3.0f, 3.0f);
const glm::quat kThirdPersonCameraRotation = glm::quat(0.92388f, -0.38268f,
0.0f, 0.0f);
const glm::vec3 kTopDownCameraPosition = glm::vec3(0.0f, 10.0f, 0.0f);
const glm::quat kTopDownCameraRotation = glm::quat(0.70711f, -0.70711f, 0.0f,
0.0f);
bool SetupGraphics(int w, int h) {
LOGI("setupGraphics(%d, %d)", w, h);
screen_width = w;
screen_height = h;
cam = new Camera();
axis = new Axis();
frustum = new Frustum();
trace = new Trace();
grid = new Grid();
camera_type = FIRST_PERSON;
cam->SetAspectRatio((float) (w / h));
return true;
}
// Render frustum and trace with current position and rotation
// updated from TangoData, TangoPosition and TangoRotation is updated via callback function
// OnPoseAvailable(), which is updated when new pose data is available.
bool RenderFrame() {
glEnable (GL_DEPTH_TEST);
glEnable (GL_CULL_FACE);
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
glViewport(0, 0, screen_width, screen_height);
grid->SetPosition(glm::vec3(0.0f, -0.8f, 0.0f));
grid->Render(cam->GetProjectionMatrix(), cam->GetViewMatrix());
int pose_index =
TangoData::GetInstance().current_pose_status[1]==TANGO_POSE_VALID ? 1 : 0;
glm::vec3 position = GlUtil::ConvertPositionToOpenGL(
TangoData::GetInstance().tango_position[pose_index]);
glm::quat rotation = GlUtil::ConvertRotationToOpenGL(
TangoData::GetInstance().tango_rotation[pose_index]);
cam->SetPosition(position);
if (camera_type == FIRST_PERSON) {
cam->SetRotation(rotation);
} else {
if(camera_type == TOP_DOWN){
cam->SetPosition(position+kTopDownCameraPosition);
}else{
cam->SetPosition(position+kThirdPersonCameraPosition);
}
frustum->SetPosition(position);
frustum->SetRotation(rotation);
frustum->Render(cam->GetProjectionMatrix(), cam->GetViewMatrix());
trace->UpdateVertexArray(position);
trace->Render(cam->GetProjectionMatrix(), cam->GetViewMatrix());
axis->SetPosition(position);
axis->SetRotation(rotation);
axis->Render(cam->GetProjectionMatrix(), cam->GetViewMatrix());
}
return true;
}
void SetCamera(int camera_index) {
camera_type = camera_index;
switch (camera_index) {
case FIRST_PERSON:
LOGI("setting to First Person Camera");
break;
case THIRD_PERSON:
cam->SetRotation(kThirdPersonCameraRotation);
LOGI("setting to Third Person Camera");
break;
case TOP_DOWN:
cam->SetRotation(kTopDownCameraRotation);
LOGI("setting to Top Down Camera");
break;
default:
break;
}
}
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT void JNICALL Java_com_projecttango_areadescriptionnative_TangoJNINative_Initialize(
JNIEnv* env, jobject obj, bool is_learning, bool is_load_adf) {
LOGI("leanring:%d, adf:%d", is_learning, is_load_adf);
LOGI("In onCreate: Initialing and setting config");
if (!TangoData::GetInstance().Initialize())
{
LOGE("Tango initialization failed");
}
if (!TangoData::GetInstance().SetConfig(is_learning, is_load_adf))
{
LOGE("Tango set config failed");
}
}
JNIEXPORT void JNICALL Java_com_projecttango_areadescriptionnative_TangoJNINative_ConnectService(
JNIEnv* env, jobject obj) {
LOGI("In OnResume: Locking config and connecting service");
if (!TangoData::GetInstance().LockConfig()) {
LOGE("Tango lock config failed");
}
if (!TangoData::GetInstance().Connect()) {
LOGE("Tango connect failed");
}
}
JNIEXPORT void JNICALL Java_com_projecttango_areadescriptionnative_TangoJNINative_DisconnectService(
JNIEnv* env, jobject obj) {
LOGI("In OnPause: Unlocking config and disconnecting service");
if (TangoData::GetInstance().UnlockConfig()) {
LOGE("Tango unlock file failed");
}
TangoData::GetInstance().Disconnect();
}
JNIEXPORT void JNICALL Java_com_projecttango_areadescriptionnative_TangoJNINative_OnDestroy(
JNIEnv* env, jobject obj) {
delete cam;
delete axis;
delete grid;
delete frustum;
delete trace;
}
JNIEXPORT void JNICALL Java_com_projecttango_areadescriptionnative_TangoJNINative_SetupGraphic(
JNIEnv* env, jobject obj, jint width, jint height) {
SetupGraphics(width, height);
}
JNIEXPORT void JNICALL Java_com_projecttango_areadescriptionnative_TangoJNINative_Render(
JNIEnv* env, jobject obj) {
RenderFrame();
}
JNIEXPORT void JNICALL Java_com_projecttango_areadescriptionnative_TangoJNINative_SetCamera(
JNIEnv* env, jobject obj, int camera_index) {
SetCamera(camera_index);
}
JNIEXPORT jstring JNICALL Java_com_projecttango_areadescriptionnative_TangoJNINative_SaveADF(
JNIEnv* env, jobject obj) {
// Save ADF.
return (env)->NewStringUTF(TangoData::GetInstance().SaveADF());
}
JNIEXPORT void JNICALL Java_com_projecttango_areadescriptionnative_TangoJNINative_RemoveAllAdfs(
JNIEnv* env, jobject obj) {
TangoData::GetInstance().RemoveAllAdfs();
}
JNIEXPORT jstring JNICALL Java_com_projecttango_areadescriptionnative_TangoJNINative_GetUUID(
JNIEnv* env, jobject obj) {
return (env)->NewStringUTF(TangoData::GetInstance().uuid_);
}
JNIEXPORT jstring JNICALL Java_com_projecttango_areadescriptionnative_TangoJNINative_GetIsEnabledLearn(
JNIEnv* env, jobject obj) {
return (env)->NewStringUTF(
TangoData::GetInstance().is_learning_mode_enabled ? "Enabled" : "Disable");
}
JNIEXPORT jstring JNICALL Java_com_projecttango_areadescriptionnative_TangoJNINative_GetPoseString(
JNIEnv* env, jobject obj, int index) {
char pose_string[100];
char status[30];
switch (TangoData::GetInstance().current_pose_status[index]) {
case TANGO_POSE_INITIALIZING:
sprintf(status,"Initializing");
break;
case TANGO_POSE_VALID:
sprintf(status, "Valid");
break;
case TANGO_POSE_INVALID:
sprintf(status, "Invalid");
break;
case TANGO_POSE_UNKNOWN:
sprintf(status, "Unknown");
break;
default:
break;
}
sprintf(pose_string, "status:%s, count:%d, pose:%4.2f %4.2f %4.2f, delta_time: %4.2fms",
status,
TangoData::GetInstance().frame_count[index],
TangoData::GetInstance().tango_position[index].x,
TangoData::GetInstance().tango_position[index].y,
TangoData::GetInstance().tango_position[index].z,
TangoData::GetInstance().frame_delta_time[index]*1000.0f);
return (env)->NewStringUTF(pose_string);
}
JNIEXPORT jstring JNICALL Java_com_projecttango_areadescriptionnative_TangoJNINative_GetVersionString(
JNIEnv* env, jobject obj) {
return (env)->NewStringUTF(TangoData::GetInstance().GetVersonString());
}
#ifdef __cplusplus
}
#endif
<|endoftext|> |
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_loop/message_loop.h"
#include "chrome/browser/extensions/api/feedback_private/feedback_private_api.h"
#include "chrome/browser/extensions/extension_apitest.h"
namespace extensions {
class FeedbackApiTest: public ExtensionApiTest {
public:
FeedbackApiTest() {}
virtual ~FeedbackApiTest() {}
};
IN_PROC_BROWSER_TEST_F(FeedbackApiTest, Basic) {
EXPECT_TRUE(RunExtensionTest("feedback_private/basic")) << message_;
}
} // namespace extensions
<commit_msg>Disable FeedbackApiTest.Basic on Linux<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_loop/message_loop.h"
#include "chrome/browser/extensions/api/feedback_private/feedback_private_api.h"
#include "chrome/browser/extensions/extension_apitest.h"
namespace extensions {
class FeedbackApiTest: public ExtensionApiTest {
public:
FeedbackApiTest() {}
virtual ~FeedbackApiTest() {}
};
// Falis on Linux. crbug.com/297414
#if defined(OS_LINUX)
#define MAYBE_Basic DISABLED_Basic
#else
#define MAYBE_Basic Basic
#endif
IN_PROC_BROWSER_TEST_F(FeedbackApiTest, MAYBE_Basic) {
EXPECT_TRUE(RunExtensionTest("feedback_private/basic")) << message_;
}
} // namespace extensions
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/external_extension_provider_impl.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/logging.h"
#include "base/memory/linked_ptr.h"
#include "base/metrics/field_trial.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/values.h"
#include "base/version.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/external_extension_provider_interface.h"
#include "chrome/browser/extensions/external_policy_extension_loader.h"
#include "chrome/browser/extensions/external_pref_extension_loader.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/browser_thread.h"
#include "ui/base/l10n/l10n_util.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/policy/app_pack_updater.h"
#include "chrome/browser/policy/browser_policy_connector.h"
#endif
#if !defined(OS_CHROMEOS)
#include "chrome/browser/extensions/default_apps.h"
#endif
#if defined(OS_WIN)
#include "chrome/browser/extensions/external_registry_extension_loader_win.h"
#endif
using content::BrowserThread;
// Constants for keeping track of extension preferences in a dictionary.
const char ExternalExtensionProviderImpl::kExternalCrx[] = "external_crx";
const char ExternalExtensionProviderImpl::kExternalVersion[] =
"external_version";
const char ExternalExtensionProviderImpl::kExternalUpdateUrl[] =
"external_update_url";
const char ExternalExtensionProviderImpl::kSupportedLocales[] =
"supported_locales";
ExternalExtensionProviderImpl::ExternalExtensionProviderImpl(
VisitorInterface* service,
ExternalExtensionLoader* loader,
Extension::Location crx_location,
Extension::Location download_location,
int creation_flags)
: crx_location_(crx_location),
download_location_(download_location),
service_(service),
prefs_(NULL),
ready_(false),
loader_(loader),
creation_flags_(creation_flags),
auto_acknowledge_(false) {
loader_->Init(this);
}
ExternalExtensionProviderImpl::~ExternalExtensionProviderImpl() {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
loader_->OwnerShutdown();
}
void ExternalExtensionProviderImpl::VisitRegisteredExtension() {
// The loader will call back to SetPrefs.
loader_->StartLoading();
}
void ExternalExtensionProviderImpl::SetPrefs(DictionaryValue* prefs) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Check if the service is still alive. It is possible that it went
// away while |loader_| was working on the FILE thread.
if (!service_) return;
prefs_.reset(prefs);
ready_ = true; // Queries for extensions are allowed from this point.
// Set of unsupported extensions that need to be deleted from prefs_.
std::set<std::string> unsupported_extensions;
// Notify ExtensionService about all the extensions this provider has.
for (DictionaryValue::key_iterator i = prefs_->begin_keys();
i != prefs_->end_keys(); ++i) {
const std::string& extension_id = *i;
DictionaryValue* extension;
if (!Extension::IdIsValid(extension_id)) {
LOG(WARNING) << "Malformed extension dictionary: key "
<< extension_id.c_str() << " is not a valid id.";
continue;
}
if (!prefs_->GetDictionaryWithoutPathExpansion(extension_id, &extension)) {
LOG(WARNING) << "Malformed extension dictionary: key "
<< extension_id.c_str()
<< " has a value that is not a dictionary.";
continue;
}
FilePath::StringType external_crx;
std::string external_version;
std::string external_update_url;
bool has_external_crx = extension->GetString(kExternalCrx, &external_crx);
bool has_external_version = extension->GetString(kExternalVersion,
&external_version);
bool has_external_update_url = extension->GetString(kExternalUpdateUrl,
&external_update_url);
if (has_external_crx != has_external_version) {
LOG(WARNING) << "Malformed extension dictionary for extension: "
<< extension_id.c_str() << ". " << kExternalCrx
<< " and " << kExternalVersion << " must be used together.";
continue;
}
if (has_external_crx == has_external_update_url) {
LOG(WARNING) << "Malformed extension dictionary for extension: "
<< extension_id.c_str() << ". Exactly one of the "
<< "followng keys should be used: " << kExternalCrx
<< ", " << kExternalUpdateUrl << ".";
continue;
}
// Check that extension supports current browser locale.
ListValue* supported_locales = NULL;
if (extension->GetList(kSupportedLocales, &supported_locales)) {
std::vector<std::string> browser_locales;
l10n_util::GetParentLocales(g_browser_process->GetApplicationLocale(),
&browser_locales);
size_t num_locales = supported_locales->GetSize();
bool locale_supported = false;
for (size_t j = 0; j < num_locales; j++) {
std::string current_locale;
if (supported_locales->GetString(j, ¤t_locale) &&
l10n_util::IsValidLocaleSyntax(current_locale)) {
current_locale = l10n_util::NormalizeLocale(current_locale);
if (std::find(browser_locales.begin(), browser_locales.end(),
current_locale) != browser_locales.end()) {
locale_supported = true;
break;
}
} else {
LOG(WARNING) << "Unrecognized locale '" << current_locale
<< "' found as supported locale for extension: "
<< extension_id;
}
}
if (!locale_supported) {
unsupported_extensions.insert(extension_id);
LOG(INFO) << "Skip installing (or uninstall) external extension: "
<< extension_id << " because the extension doesn't support "
<< "the browser locale.";
continue;
}
}
if (has_external_crx) {
if (crx_location_ == Extension::INVALID) {
LOG(WARNING) << "This provider does not support installing external "
<< "extensions from crx files.";
continue;
}
if (external_crx.find(FilePath::kParentDirectory) !=
base::StringPiece::npos) {
LOG(WARNING) << "Path traversal not allowed in path: "
<< external_crx.c_str();
continue;
}
// If the path is relative, and the provider has a base path,
// build the absolute path to the crx file.
FilePath path(external_crx);
if (!path.IsAbsolute()) {
FilePath base_path = loader_->GetBaseCrxFilePath();
if (base_path.empty()) {
LOG(WARNING) << "File path " << external_crx.c_str()
<< " is relative. An absolute path is required.";
continue;
}
path = base_path.Append(external_crx);
}
scoped_ptr<Version> version;
version.reset(Version::GetVersionFromString(external_version));
if (!version.get()) {
LOG(WARNING) << "Malformed extension dictionary for extension: "
<< extension_id.c_str() << ". Invalid version string \""
<< external_version << "\".";
continue;
}
service_->OnExternalExtensionFileFound(extension_id, version.get(), path,
crx_location_, creation_flags_,
auto_acknowledge_);
} else { // if (has_external_update_url)
CHECK(has_external_update_url); // Checking of keys above ensures this.
if (download_location_ == Extension::INVALID) {
LOG(WARNING) << "This provider does not support installing external "
<< "extensions from update URLs.";
continue;
}
GURL update_url(external_update_url);
if (!update_url.is_valid()) {
LOG(WARNING) << "Malformed extension dictionary for extension: "
<< extension_id.c_str() << ". Key " << kExternalUpdateUrl
<< " has value \"" << external_update_url
<< "\", which is not a valid URL.";
continue;
}
service_->OnExternalExtensionUpdateUrlFound(
extension_id, update_url, download_location_);
}
}
for (std::set<std::string>::iterator it = unsupported_extensions.begin();
it != unsupported_extensions.end(); ++it) {
// Remove extension for the list of know external extensions. The extension
// will be uninstalled later because provider doesn't provide it anymore.
prefs_->Remove(*it, NULL);
}
service_->OnExternalProviderReady(this);
}
void ExternalExtensionProviderImpl::ServiceShutdown() {
service_ = NULL;
}
bool ExternalExtensionProviderImpl::IsReady() const {
return ready_;
}
int ExternalExtensionProviderImpl::GetCreationFlags() const {
return creation_flags_;
}
bool ExternalExtensionProviderImpl::HasExtension(
const std::string& id) const {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
CHECK(prefs_.get());
CHECK(ready_);
return prefs_->HasKey(id);
}
bool ExternalExtensionProviderImpl::GetExtensionDetails(
const std::string& id, Extension::Location* location,
scoped_ptr<Version>* version) const {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
CHECK(prefs_.get());
CHECK(ready_);
DictionaryValue* extension = NULL;
if (!prefs_->GetDictionary(id, &extension))
return false;
Extension::Location loc = Extension::INVALID;
if (extension->HasKey(kExternalUpdateUrl)) {
loc = download_location_;
} else if (extension->HasKey(kExternalCrx)) {
loc = crx_location_;
std::string external_version;
if (!extension->GetString(kExternalVersion, &external_version))
return false;
if (version)
version->reset(Version::GetVersionFromString(external_version));
} else {
NOTREACHED(); // Chrome should not allow prefs to get into this state.
return false;
}
if (location)
*location = loc;
return true;
}
// static
void ExternalExtensionProviderImpl::CreateExternalProviders(
VisitorInterface* service,
Profile* profile,
ProviderCollection* provider_list) {
// On Mac OS, items in /Library/... should be written by the superuser.
// Check that all components of the path are writable by root only.
ExternalPrefExtensionLoader::Options check_admin_permissions_on_mac;
#if defined(OS_MACOSX)
check_admin_permissions_on_mac =
ExternalPrefExtensionLoader::ENSURE_PATH_CONTROLLED_BY_ADMIN;
#else
check_admin_permissions_on_mac = ExternalPrefExtensionLoader::NONE;
#endif
provider_list->push_back(
linked_ptr<ExternalExtensionProviderInterface>(
new ExternalExtensionProviderImpl(
service,
new ExternalPrefExtensionLoader(
chrome::DIR_EXTERNAL_EXTENSIONS,
check_admin_permissions_on_mac),
Extension::EXTERNAL_PREF,
Extension::EXTERNAL_PREF_DOWNLOAD,
Extension::NO_FLAGS)));
#if defined(OS_CHROMEOS) || defined (OS_MACOSX)
// Define a per-user source of external extensions.
// On Chrome OS, this serves as a source for OEM customization.
provider_list->push_back(
linked_ptr<ExternalExtensionProviderInterface>(
new ExternalExtensionProviderImpl(
service,
new ExternalPrefExtensionLoader(
chrome::DIR_USER_EXTERNAL_EXTENSIONS,
ExternalPrefExtensionLoader::NONE),
Extension::EXTERNAL_PREF,
Extension::EXTERNAL_PREF_DOWNLOAD,
Extension::NO_FLAGS)));
#endif
#if defined(OS_WIN)
provider_list->push_back(
linked_ptr<ExternalExtensionProviderInterface>(
new ExternalExtensionProviderImpl(
service,
new ExternalRegistryExtensionLoader,
Extension::EXTERNAL_REGISTRY,
Extension::INVALID,
Extension::NO_FLAGS)));
#endif
provider_list->push_back(
linked_ptr<ExternalExtensionProviderInterface>(
new ExternalExtensionProviderImpl(
service,
new ExternalPolicyExtensionLoader(profile),
Extension::INVALID,
Extension::EXTERNAL_POLICY_DOWNLOAD,
Extension::NO_FLAGS)));
#if !defined(OS_CHROMEOS)
provider_list->push_back(
linked_ptr<ExternalExtensionProviderInterface>(
new default_apps::Provider(
profile,
service,
new ExternalPrefExtensionLoader(
chrome::DIR_DEFAULT_APPS,
ExternalPrefExtensionLoader::NONE),
Extension::EXTERNAL_PREF,
Extension::INVALID,
Extension::FROM_BOOKMARK)));
#endif
#if defined(OS_CHROMEOS)
chromeos::UserManager* user_manager = chromeos::UserManager::Get();
policy::BrowserPolicyConnector* connector =
g_browser_process->browser_policy_connector();
if (user_manager && user_manager->IsLoggedInAsDemoUser() &&
connector->GetDeviceMode() == policy::DEVICE_MODE_KIOSK &&
connector->GetAppPackUpdater()) {
provider_list->push_back(
linked_ptr<ExternalExtensionProviderInterface>(
new ExternalExtensionProviderImpl(
service,
connector->GetAppPackUpdater()->CreateExternalExtensionLoader(),
Extension::EXTERNAL_PREF,
Extension::INVALID,
Extension::NO_FLAGS)));
}
#endif
}
<commit_msg>Mark default apps as "from webstore" so NaCl gets enabled. Default apps serve as OEM customization and should be able to load NaCl modules. This is a problem now because they aren't really distinguishable from normal extensions. To fix this, mark them as "from webstore" when they're loaded. BUG=28707 TEST=none Review URL: https://chromiumcodereview.appspot.com/9950070<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/external_extension_provider_impl.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/logging.h"
#include "base/memory/linked_ptr.h"
#include "base/metrics/field_trial.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/values.h"
#include "base/version.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/external_extension_provider_interface.h"
#include "chrome/browser/extensions/external_policy_extension_loader.h"
#include "chrome/browser/extensions/external_pref_extension_loader.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/browser_thread.h"
#include "ui/base/l10n/l10n_util.h"
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/policy/app_pack_updater.h"
#include "chrome/browser/policy/browser_policy_connector.h"
#endif
#if !defined(OS_CHROMEOS)
#include "chrome/browser/extensions/default_apps.h"
#endif
#if defined(OS_WIN)
#include "chrome/browser/extensions/external_registry_extension_loader_win.h"
#endif
using content::BrowserThread;
// Constants for keeping track of extension preferences in a dictionary.
const char ExternalExtensionProviderImpl::kExternalCrx[] = "external_crx";
const char ExternalExtensionProviderImpl::kExternalVersion[] =
"external_version";
const char ExternalExtensionProviderImpl::kExternalUpdateUrl[] =
"external_update_url";
const char ExternalExtensionProviderImpl::kSupportedLocales[] =
"supported_locales";
ExternalExtensionProviderImpl::ExternalExtensionProviderImpl(
VisitorInterface* service,
ExternalExtensionLoader* loader,
Extension::Location crx_location,
Extension::Location download_location,
int creation_flags)
: crx_location_(crx_location),
download_location_(download_location),
service_(service),
prefs_(NULL),
ready_(false),
loader_(loader),
creation_flags_(creation_flags),
auto_acknowledge_(false) {
loader_->Init(this);
}
ExternalExtensionProviderImpl::~ExternalExtensionProviderImpl() {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
loader_->OwnerShutdown();
}
void ExternalExtensionProviderImpl::VisitRegisteredExtension() {
// The loader will call back to SetPrefs.
loader_->StartLoading();
}
void ExternalExtensionProviderImpl::SetPrefs(DictionaryValue* prefs) {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// Check if the service is still alive. It is possible that it went
// away while |loader_| was working on the FILE thread.
if (!service_) return;
prefs_.reset(prefs);
ready_ = true; // Queries for extensions are allowed from this point.
// Set of unsupported extensions that need to be deleted from prefs_.
std::set<std::string> unsupported_extensions;
// Notify ExtensionService about all the extensions this provider has.
for (DictionaryValue::key_iterator i = prefs_->begin_keys();
i != prefs_->end_keys(); ++i) {
const std::string& extension_id = *i;
DictionaryValue* extension;
if (!Extension::IdIsValid(extension_id)) {
LOG(WARNING) << "Malformed extension dictionary: key "
<< extension_id.c_str() << " is not a valid id.";
continue;
}
if (!prefs_->GetDictionaryWithoutPathExpansion(extension_id, &extension)) {
LOG(WARNING) << "Malformed extension dictionary: key "
<< extension_id.c_str()
<< " has a value that is not a dictionary.";
continue;
}
FilePath::StringType external_crx;
std::string external_version;
std::string external_update_url;
bool has_external_crx = extension->GetString(kExternalCrx, &external_crx);
bool has_external_version = extension->GetString(kExternalVersion,
&external_version);
bool has_external_update_url = extension->GetString(kExternalUpdateUrl,
&external_update_url);
if (has_external_crx != has_external_version) {
LOG(WARNING) << "Malformed extension dictionary for extension: "
<< extension_id.c_str() << ". " << kExternalCrx
<< " and " << kExternalVersion << " must be used together.";
continue;
}
if (has_external_crx == has_external_update_url) {
LOG(WARNING) << "Malformed extension dictionary for extension: "
<< extension_id.c_str() << ". Exactly one of the "
<< "followng keys should be used: " << kExternalCrx
<< ", " << kExternalUpdateUrl << ".";
continue;
}
// Check that extension supports current browser locale.
ListValue* supported_locales = NULL;
if (extension->GetList(kSupportedLocales, &supported_locales)) {
std::vector<std::string> browser_locales;
l10n_util::GetParentLocales(g_browser_process->GetApplicationLocale(),
&browser_locales);
size_t num_locales = supported_locales->GetSize();
bool locale_supported = false;
for (size_t j = 0; j < num_locales; j++) {
std::string current_locale;
if (supported_locales->GetString(j, ¤t_locale) &&
l10n_util::IsValidLocaleSyntax(current_locale)) {
current_locale = l10n_util::NormalizeLocale(current_locale);
if (std::find(browser_locales.begin(), browser_locales.end(),
current_locale) != browser_locales.end()) {
locale_supported = true;
break;
}
} else {
LOG(WARNING) << "Unrecognized locale '" << current_locale
<< "' found as supported locale for extension: "
<< extension_id;
}
}
if (!locale_supported) {
unsupported_extensions.insert(extension_id);
LOG(INFO) << "Skip installing (or uninstall) external extension: "
<< extension_id << " because the extension doesn't support "
<< "the browser locale.";
continue;
}
}
if (has_external_crx) {
if (crx_location_ == Extension::INVALID) {
LOG(WARNING) << "This provider does not support installing external "
<< "extensions from crx files.";
continue;
}
if (external_crx.find(FilePath::kParentDirectory) !=
base::StringPiece::npos) {
LOG(WARNING) << "Path traversal not allowed in path: "
<< external_crx.c_str();
continue;
}
// If the path is relative, and the provider has a base path,
// build the absolute path to the crx file.
FilePath path(external_crx);
if (!path.IsAbsolute()) {
FilePath base_path = loader_->GetBaseCrxFilePath();
if (base_path.empty()) {
LOG(WARNING) << "File path " << external_crx.c_str()
<< " is relative. An absolute path is required.";
continue;
}
path = base_path.Append(external_crx);
}
scoped_ptr<Version> version;
version.reset(Version::GetVersionFromString(external_version));
if (!version.get()) {
LOG(WARNING) << "Malformed extension dictionary for extension: "
<< extension_id.c_str() << ". Invalid version string \""
<< external_version << "\".";
continue;
}
service_->OnExternalExtensionFileFound(extension_id, version.get(), path,
crx_location_, creation_flags_,
auto_acknowledge_);
} else { // if (has_external_update_url)
CHECK(has_external_update_url); // Checking of keys above ensures this.
if (download_location_ == Extension::INVALID) {
LOG(WARNING) << "This provider does not support installing external "
<< "extensions from update URLs.";
continue;
}
GURL update_url(external_update_url);
if (!update_url.is_valid()) {
LOG(WARNING) << "Malformed extension dictionary for extension: "
<< extension_id.c_str() << ". Key " << kExternalUpdateUrl
<< " has value \"" << external_update_url
<< "\", which is not a valid URL.";
continue;
}
service_->OnExternalExtensionUpdateUrlFound(
extension_id, update_url, download_location_);
}
}
for (std::set<std::string>::iterator it = unsupported_extensions.begin();
it != unsupported_extensions.end(); ++it) {
// Remove extension for the list of know external extensions. The extension
// will be uninstalled later because provider doesn't provide it anymore.
prefs_->Remove(*it, NULL);
}
service_->OnExternalProviderReady(this);
}
void ExternalExtensionProviderImpl::ServiceShutdown() {
service_ = NULL;
}
bool ExternalExtensionProviderImpl::IsReady() const {
return ready_;
}
int ExternalExtensionProviderImpl::GetCreationFlags() const {
return creation_flags_;
}
bool ExternalExtensionProviderImpl::HasExtension(
const std::string& id) const {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
CHECK(prefs_.get());
CHECK(ready_);
return prefs_->HasKey(id);
}
bool ExternalExtensionProviderImpl::GetExtensionDetails(
const std::string& id, Extension::Location* location,
scoped_ptr<Version>* version) const {
CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
CHECK(prefs_.get());
CHECK(ready_);
DictionaryValue* extension = NULL;
if (!prefs_->GetDictionary(id, &extension))
return false;
Extension::Location loc = Extension::INVALID;
if (extension->HasKey(kExternalUpdateUrl)) {
loc = download_location_;
} else if (extension->HasKey(kExternalCrx)) {
loc = crx_location_;
std::string external_version;
if (!extension->GetString(kExternalVersion, &external_version))
return false;
if (version)
version->reset(Version::GetVersionFromString(external_version));
} else {
NOTREACHED(); // Chrome should not allow prefs to get into this state.
return false;
}
if (location)
*location = loc;
return true;
}
// static
void ExternalExtensionProviderImpl::CreateExternalProviders(
VisitorInterface* service,
Profile* profile,
ProviderCollection* provider_list) {
// On Mac OS, items in /Library/... should be written by the superuser.
// Check that all components of the path are writable by root only.
ExternalPrefExtensionLoader::Options check_admin_permissions_on_mac;
#if defined(OS_MACOSX)
check_admin_permissions_on_mac =
ExternalPrefExtensionLoader::ENSURE_PATH_CONTROLLED_BY_ADMIN;
#else
check_admin_permissions_on_mac = ExternalPrefExtensionLoader::NONE;
#endif
provider_list->push_back(
linked_ptr<ExternalExtensionProviderInterface>(
new ExternalExtensionProviderImpl(
service,
new ExternalPrefExtensionLoader(
chrome::DIR_EXTERNAL_EXTENSIONS,
check_admin_permissions_on_mac),
Extension::EXTERNAL_PREF,
Extension::EXTERNAL_PREF_DOWNLOAD,
Extension::NO_FLAGS)));
#if defined(OS_CHROMEOS)
// Define a per-user source of external default extensions, which serves
// as a source for OEM customization. Mark these default extensions as
// being from the webstore so they can load Native Client modules.
provider_list->push_back(
linked_ptr<ExternalExtensionProviderInterface>(
new ExternalExtensionProviderImpl(
service,
new ExternalPrefExtensionLoader(
chrome::DIR_USER_EXTERNAL_EXTENSIONS,
ExternalPrefExtensionLoader::NONE),
Extension::EXTERNAL_PREF,
Extension::EXTERNAL_PREF_DOWNLOAD,
Extension::FROM_WEBSTORE)));
#endif
#if defined (OS_MACOSX)
// Define a per-user source of external extensions.
provider_list->push_back(
linked_ptr<ExternalExtensionProviderInterface>(
new ExternalExtensionProviderImpl(
service,
new ExternalPrefExtensionLoader(
chrome::DIR_USER_EXTERNAL_EXTENSIONS,
ExternalPrefExtensionLoader::NONE),
Extension::EXTERNAL_PREF,
Extension::EXTERNAL_PREF_DOWNLOAD,
Extension::NO_FLAGS)));
#endif
#if defined(OS_WIN)
provider_list->push_back(
linked_ptr<ExternalExtensionProviderInterface>(
new ExternalExtensionProviderImpl(
service,
new ExternalRegistryExtensionLoader,
Extension::EXTERNAL_REGISTRY,
Extension::INVALID,
Extension::NO_FLAGS)));
#endif
provider_list->push_back(
linked_ptr<ExternalExtensionProviderInterface>(
new ExternalExtensionProviderImpl(
service,
new ExternalPolicyExtensionLoader(profile),
Extension::INVALID,
Extension::EXTERNAL_POLICY_DOWNLOAD,
Extension::NO_FLAGS)));
#if !defined(OS_CHROMEOS)
provider_list->push_back(
linked_ptr<ExternalExtensionProviderInterface>(
new default_apps::Provider(
profile,
service,
new ExternalPrefExtensionLoader(
chrome::DIR_DEFAULT_APPS,
ExternalPrefExtensionLoader::NONE),
Extension::EXTERNAL_PREF,
Extension::INVALID,
Extension::FROM_BOOKMARK)));
#endif
#if defined(OS_CHROMEOS)
chromeos::UserManager* user_manager = chromeos::UserManager::Get();
policy::BrowserPolicyConnector* connector =
g_browser_process->browser_policy_connector();
if (user_manager && user_manager->IsLoggedInAsDemoUser() &&
connector->GetDeviceMode() == policy::DEVICE_MODE_KIOSK &&
connector->GetAppPackUpdater()) {
provider_list->push_back(
linked_ptr<ExternalExtensionProviderInterface>(
new ExternalExtensionProviderImpl(
service,
connector->GetAppPackUpdater()->CreateExternalExtensionLoader(),
Extension::EXTERNAL_PREF,
Extension::INVALID,
Extension::NO_FLAGS)));
}
#endif
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/options2/chromeos/set_wallpaper_options_handler.h"
#include "ash/desktop_background/desktop_background_controller.h"
#include "ash/shell.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/metrics/histogram.h"
#include "base/path_service.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/chrome_select_file_policy.h"
#include "chrome/browser/ui/webui/options2/chromeos/wallpaper_thumbnail_source.h"
#include "chrome/browser/ui/webui/web_ui_util.h"
#include "chrome/common/chrome_paths.h"
#include "content/public/browser/web_ui.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/views/widget/widget.h"
namespace chromeos {
namespace options2 {
namespace {
// Returns info about extensions for files we support as wallpaper images.
ui::SelectFileDialog::FileTypeInfo GetUserImageFileTypeInfo() {
ui::SelectFileDialog::FileTypeInfo file_type_info;
file_type_info.extensions.resize(3);
file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("jpg"));
file_type_info.extensions[1].push_back(FILE_PATH_LITERAL("jpeg"));
file_type_info.extensions[2].push_back(FILE_PATH_LITERAL("png"));
return file_type_info;
}
} // namespace
SetWallpaperOptionsHandler::SetWallpaperOptionsHandler()
: ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
}
SetWallpaperOptionsHandler::~SetWallpaperOptionsHandler() {
if (select_file_dialog_.get())
select_file_dialog_->ListenerDestroyed();
}
void SetWallpaperOptionsHandler::GetLocalizedValues(
DictionaryValue* localized_strings) {
DCHECK(localized_strings);
localized_strings->SetString("setWallpaperPage",
l10n_util::GetStringUTF16(IDS_OPTIONS_SET_WALLPAPER_DIALOG_TITLE));
localized_strings->SetString("setWallpaperPageDescription",
l10n_util::GetStringUTF16(IDS_OPTIONS_SET_WALLPAPER_DIALOG_TEXT));
localized_strings->SetString("setWallpaperAuthor",
l10n_util::GetStringUTF16(IDS_OPTIONS_SET_WALLPAPER_AUTHOR_TEXT));
localized_strings->SetString("dailyWallpaperLabel",
l10n_util::GetStringUTF16(IDS_OPTIONS_SET_WALLPAPER_DAILY));
localized_strings->SetString("customWallpaper",
l10n_util::GetStringUTF16(IDS_OPTIONS_CUSTOME_WALLPAPER));
}
void SetWallpaperOptionsHandler::RegisterMessages() {
web_ui()->RegisterMessageCallback("onSetWallpaperPageInitialized",
base::Bind(&SetWallpaperOptionsHandler::HandlePageInitialized,
base::Unretained(this)));
web_ui()->RegisterMessageCallback("onSetWallpaperPageShown",
base::Bind(&SetWallpaperOptionsHandler::HandlePageShown,
base::Unretained(this)));
web_ui()->RegisterMessageCallback("selectDefaultWallpaper",
base::Bind(&SetWallpaperOptionsHandler::HandleDefaultWallpaper,
base::Unretained(this)));
web_ui()->RegisterMessageCallback("selectDailyWallpaper",
base::Bind(&SetWallpaperOptionsHandler::HandleDailyWallpaper,
base::Unretained(this)));
web_ui()->RegisterMessageCallback("chooseWallpaper",
base::Bind(&SetWallpaperOptionsHandler::HandleChooseFile,
base::Unretained(this)));
web_ui()->RegisterMessageCallback("changeWallpaperLayout",
base::Bind(&SetWallpaperOptionsHandler::HandleLayoutChanged,
base::Unretained(this)));
}
void SetWallpaperOptionsHandler::SetCustomWallpaperThumbnail() {
web_ui()->CallJavascriptFunction("SetWallpaperOptions.setCustomImage");
}
void SetWallpaperOptionsHandler::FileSelected(const FilePath& path,
int index,
void* params) {
UserManager* user_manager = UserManager::Get();
// Default wallpaper layout is CENTER_CROPPED.
user_manager->SaveUserWallpaperFromFile(
user_manager->GetLoggedInUser().email(), path, ash::CENTER_CROPPED,
weak_factory_.GetWeakPtr());
web_ui()->CallJavascriptFunction("SetWallpaperOptions.didSelectFile");
}
void SetWallpaperOptionsHandler::SendDefaultImages() {
ListValue images;
DictionaryValue* image_detail;
ash::WallpaperInfo image_info;
for (int i = 0; i < ash::GetWallpaperCount(); ++i) {
images.Append(image_detail = new DictionaryValue());
image_info = ash::GetWallpaperInfo(i);
image_detail->SetString("url", GetDefaultWallpaperThumbnailURL(i));
image_detail->SetString("author", image_info.author);
image_detail->SetString("website", image_info.website);
}
web_ui()->CallJavascriptFunction("SetWallpaperOptions.setDefaultImages",
images);
}
void SetWallpaperOptionsHandler::SendLayoutOptions(
ash::WallpaperLayout layout) {
ListValue layouts;
DictionaryValue* entry;
layouts.Append(entry = new DictionaryValue());
entry->SetString("name",
l10n_util::GetStringUTF16(IDS_OPTIONS_WALLPAPER_CENTER_LAYOUT));
entry->SetInteger("index", ash::CENTER);
layouts.Append(entry = new DictionaryValue());
entry->SetString("name",
l10n_util::GetStringUTF16(IDS_OPTIONS_WALLPAPER_CENTER_CROPPED_LAYOUT));
entry->SetInteger("index", ash::CENTER_CROPPED);
layouts.Append(entry = new DictionaryValue());
entry->SetString("name",
l10n_util::GetStringUTF16(IDS_OPTIONS_WALLPAPER_STRETCH_LAYOUT));
entry->SetInteger("index", ash::STRETCH);
base::FundamentalValue selected_value(static_cast<int>(layout));
web_ui()->CallJavascriptFunction(
"SetWallpaperOptions.populateWallpaperLayouts", layouts, selected_value);
}
void SetWallpaperOptionsHandler::HandlePageInitialized(
const base::ListValue* args) {
DCHECK(args && args->empty());
SendDefaultImages();
}
void SetWallpaperOptionsHandler::HandlePageShown(const base::ListValue* args) {
DCHECK(args && args->empty());
User::WallpaperType type;
int index;
base::Time date;
UserManager::Get()->GetLoggedInUserWallpaperProperties(&type, &index, &date);
if (type == User::DAILY && date != base::Time::Now().LocalMidnight()) {
index = ash::GetNextWallpaperIndex(index);
UserManager::Get()->SaveLoggedInUserWallpaperProperties(User::DAILY,
index);
ash::Shell::GetInstance()->user_wallpaper_delegate()->
InitializeWallpaper();
}
base::StringValue image_url(GetDefaultWallpaperThumbnailURL(index));
base::FundamentalValue is_daily(type == User::DAILY);
if (type == User::CUSTOMIZED) {
ash::WallpaperLayout layout = static_cast<ash::WallpaperLayout>(index);
SendLayoutOptions(layout);
web_ui()->CallJavascriptFunction("SetWallpaperOptions.setCustomImage");
} else {
SendLayoutOptions(ash::CENTER_CROPPED);
web_ui()->CallJavascriptFunction("SetWallpaperOptions.setSelectedImage",
image_url, is_daily);
}
}
void SetWallpaperOptionsHandler::HandleChooseFile(const ListValue* args) {
DCHECK(args && args->empty());
select_file_dialog_ = ui::SelectFileDialog::Create(
this, new ChromeSelectFilePolicy(web_ui()->GetWebContents()));
FilePath downloads_path;
if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &downloads_path))
NOTREACHED();
// Static so we initialize it only once.
CR_DEFINE_STATIC_LOCAL(ui::SelectFileDialog::FileTypeInfo, file_type_info,
(GetUserImageFileTypeInfo()));
select_file_dialog_->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE,
l10n_util::GetStringUTF16(IDS_DOWNLOAD_TITLE),
downloads_path, &file_type_info, 0,
FILE_PATH_LITERAL(""),
GetBrowserWindow(), NULL);
}
void SetWallpaperOptionsHandler::HandleLayoutChanged(const ListValue* args) {
int selected_layout = ash::CENTER_CROPPED;
if (!ExtractIntegerValue(args, &selected_layout))
NOTREACHED() << "Could not read wallpaper layout from JSON argument";
ash::WallpaperLayout layout =
static_cast<ash::WallpaperLayout>(selected_layout);
UserManager::Get()->SetLoggedInUserCustomWallpaperLayout(layout);
}
void SetWallpaperOptionsHandler::HandleDefaultWallpaper(const ListValue* args) {
std::string image_url;
if (!args ||
args->GetSize() != 1 ||
!args->GetString(0, &image_url))
NOTREACHED();
if (image_url.empty())
return;
int user_image_index;
if (IsDefaultWallpaperURL(image_url, &user_image_index)) {
UserManager::Get()->SaveLoggedInUserWallpaperProperties(User::DEFAULT,
user_image_index);
ash::Shell::GetInstance()->user_wallpaper_delegate()->InitializeWallpaper();
}
}
void SetWallpaperOptionsHandler::HandleDailyWallpaper(const ListValue* args) {
User::WallpaperType type;
int index;
base::Time date;
UserManager::Get()->GetLoggedInUserWallpaperProperties(&type, &index, &date);
if (date != base::Time::Now().LocalMidnight())
index = ash::GetNextWallpaperIndex(index);
UserManager::Get()->SaveLoggedInUserWallpaperProperties(User::DAILY, index);
ash::Shell::GetInstance()->desktop_background_controller()->
SetDefaultWallpaper(index);
base::StringValue image_url(GetDefaultWallpaperThumbnailURL(index));
base::FundamentalValue is_daily(true);
web_ui()->CallJavascriptFunction("SetWallpaperOptions.setSelectedImage",
image_url, is_daily);
}
gfx::NativeWindow SetWallpaperOptionsHandler::GetBrowserWindow() const {
Browser* browser =
browser::FindBrowserWithWebContents(web_ui()->GetWebContents());
return browser->window()->GetNativeWindow();
}
} // namespace options2
} // namespace chromeos
<commit_msg>Fixed SelectFile parameter for the Wallpaper chooser<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/options2/chromeos/set_wallpaper_options_handler.h"
#include "ash/desktop_background/desktop_background_controller.h"
#include "ash/shell.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/metrics/histogram.h"
#include "base/path_service.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/chrome_select_file_policy.h"
#include "chrome/browser/ui/webui/options2/chromeos/wallpaper_thumbnail_source.h"
#include "chrome/browser/ui/webui/web_ui_util.h"
#include "chrome/common/chrome_paths.h"
#include "content/public/browser/web_ui.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/views/widget/widget.h"
namespace chromeos {
namespace options2 {
namespace {
// Returns info about extensions for files we support as wallpaper images.
ui::SelectFileDialog::FileTypeInfo GetUserImageFileTypeInfo() {
ui::SelectFileDialog::FileTypeInfo file_type_info;
file_type_info.extensions.resize(1);
file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("jpg"));
file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("jpeg"));
file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("png"));
file_type_info.extension_description_overrides.resize(1);
file_type_info.extension_description_overrides[0] =
l10n_util::GetStringUTF16(IDS_IMAGE_FILES);
file_type_info.include_all_files = true;
return file_type_info;
}
} // namespace
SetWallpaperOptionsHandler::SetWallpaperOptionsHandler()
: ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
}
SetWallpaperOptionsHandler::~SetWallpaperOptionsHandler() {
if (select_file_dialog_.get())
select_file_dialog_->ListenerDestroyed();
}
void SetWallpaperOptionsHandler::GetLocalizedValues(
DictionaryValue* localized_strings) {
DCHECK(localized_strings);
localized_strings->SetString("setWallpaperPage",
l10n_util::GetStringUTF16(IDS_OPTIONS_SET_WALLPAPER_DIALOG_TITLE));
localized_strings->SetString("setWallpaperPageDescription",
l10n_util::GetStringUTF16(IDS_OPTIONS_SET_WALLPAPER_DIALOG_TEXT));
localized_strings->SetString("setWallpaperAuthor",
l10n_util::GetStringUTF16(IDS_OPTIONS_SET_WALLPAPER_AUTHOR_TEXT));
localized_strings->SetString("dailyWallpaperLabel",
l10n_util::GetStringUTF16(IDS_OPTIONS_SET_WALLPAPER_DAILY));
localized_strings->SetString("customWallpaper",
l10n_util::GetStringUTF16(IDS_OPTIONS_CUSTOME_WALLPAPER));
}
void SetWallpaperOptionsHandler::RegisterMessages() {
web_ui()->RegisterMessageCallback("onSetWallpaperPageInitialized",
base::Bind(&SetWallpaperOptionsHandler::HandlePageInitialized,
base::Unretained(this)));
web_ui()->RegisterMessageCallback("onSetWallpaperPageShown",
base::Bind(&SetWallpaperOptionsHandler::HandlePageShown,
base::Unretained(this)));
web_ui()->RegisterMessageCallback("selectDefaultWallpaper",
base::Bind(&SetWallpaperOptionsHandler::HandleDefaultWallpaper,
base::Unretained(this)));
web_ui()->RegisterMessageCallback("selectDailyWallpaper",
base::Bind(&SetWallpaperOptionsHandler::HandleDailyWallpaper,
base::Unretained(this)));
web_ui()->RegisterMessageCallback("chooseWallpaper",
base::Bind(&SetWallpaperOptionsHandler::HandleChooseFile,
base::Unretained(this)));
web_ui()->RegisterMessageCallback("changeWallpaperLayout",
base::Bind(&SetWallpaperOptionsHandler::HandleLayoutChanged,
base::Unretained(this)));
}
void SetWallpaperOptionsHandler::SetCustomWallpaperThumbnail() {
web_ui()->CallJavascriptFunction("SetWallpaperOptions.setCustomImage");
}
void SetWallpaperOptionsHandler::FileSelected(const FilePath& path,
int index,
void* params) {
UserManager* user_manager = UserManager::Get();
// Default wallpaper layout is CENTER_CROPPED.
user_manager->SaveUserWallpaperFromFile(
user_manager->GetLoggedInUser().email(), path, ash::CENTER_CROPPED,
weak_factory_.GetWeakPtr());
web_ui()->CallJavascriptFunction("SetWallpaperOptions.didSelectFile");
}
void SetWallpaperOptionsHandler::SendDefaultImages() {
ListValue images;
DictionaryValue* image_detail;
ash::WallpaperInfo image_info;
for (int i = 0; i < ash::GetWallpaperCount(); ++i) {
images.Append(image_detail = new DictionaryValue());
image_info = ash::GetWallpaperInfo(i);
image_detail->SetString("url", GetDefaultWallpaperThumbnailURL(i));
image_detail->SetString("author", image_info.author);
image_detail->SetString("website", image_info.website);
}
web_ui()->CallJavascriptFunction("SetWallpaperOptions.setDefaultImages",
images);
}
void SetWallpaperOptionsHandler::SendLayoutOptions(
ash::WallpaperLayout layout) {
ListValue layouts;
DictionaryValue* entry;
layouts.Append(entry = new DictionaryValue());
entry->SetString("name",
l10n_util::GetStringUTF16(IDS_OPTIONS_WALLPAPER_CENTER_LAYOUT));
entry->SetInteger("index", ash::CENTER);
layouts.Append(entry = new DictionaryValue());
entry->SetString("name",
l10n_util::GetStringUTF16(IDS_OPTIONS_WALLPAPER_CENTER_CROPPED_LAYOUT));
entry->SetInteger("index", ash::CENTER_CROPPED);
layouts.Append(entry = new DictionaryValue());
entry->SetString("name",
l10n_util::GetStringUTF16(IDS_OPTIONS_WALLPAPER_STRETCH_LAYOUT));
entry->SetInteger("index", ash::STRETCH);
base::FundamentalValue selected_value(static_cast<int>(layout));
web_ui()->CallJavascriptFunction(
"SetWallpaperOptions.populateWallpaperLayouts", layouts, selected_value);
}
void SetWallpaperOptionsHandler::HandlePageInitialized(
const base::ListValue* args) {
DCHECK(args && args->empty());
SendDefaultImages();
}
void SetWallpaperOptionsHandler::HandlePageShown(const base::ListValue* args) {
DCHECK(args && args->empty());
User::WallpaperType type;
int index;
base::Time date;
UserManager::Get()->GetLoggedInUserWallpaperProperties(&type, &index, &date);
if (type == User::DAILY && date != base::Time::Now().LocalMidnight()) {
index = ash::GetNextWallpaperIndex(index);
UserManager::Get()->SaveLoggedInUserWallpaperProperties(User::DAILY,
index);
ash::Shell::GetInstance()->user_wallpaper_delegate()->
InitializeWallpaper();
}
base::StringValue image_url(GetDefaultWallpaperThumbnailURL(index));
base::FundamentalValue is_daily(type == User::DAILY);
if (type == User::CUSTOMIZED) {
ash::WallpaperLayout layout = static_cast<ash::WallpaperLayout>(index);
SendLayoutOptions(layout);
web_ui()->CallJavascriptFunction("SetWallpaperOptions.setCustomImage");
} else {
SendLayoutOptions(ash::CENTER_CROPPED);
web_ui()->CallJavascriptFunction("SetWallpaperOptions.setSelectedImage",
image_url, is_daily);
}
}
void SetWallpaperOptionsHandler::HandleChooseFile(const ListValue* args) {
DCHECK(args && args->empty());
select_file_dialog_ = ui::SelectFileDialog::Create(
this, new ChromeSelectFilePolicy(web_ui()->GetWebContents()));
FilePath downloads_path;
if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &downloads_path))
NOTREACHED();
// Static so we initialize it only once.
CR_DEFINE_STATIC_LOCAL(ui::SelectFileDialog::FileTypeInfo, file_type_info,
(GetUserImageFileTypeInfo()));
select_file_dialog_->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE,
l10n_util::GetStringUTF16(IDS_DOWNLOAD_TITLE),
downloads_path, &file_type_info, 0,
FILE_PATH_LITERAL(""),
GetBrowserWindow(), NULL);
}
void SetWallpaperOptionsHandler::HandleLayoutChanged(const ListValue* args) {
int selected_layout = ash::CENTER_CROPPED;
if (!ExtractIntegerValue(args, &selected_layout))
NOTREACHED() << "Could not read wallpaper layout from JSON argument";
ash::WallpaperLayout layout =
static_cast<ash::WallpaperLayout>(selected_layout);
UserManager::Get()->SetLoggedInUserCustomWallpaperLayout(layout);
}
void SetWallpaperOptionsHandler::HandleDefaultWallpaper(const ListValue* args) {
std::string image_url;
if (!args ||
args->GetSize() != 1 ||
!args->GetString(0, &image_url))
NOTREACHED();
if (image_url.empty())
return;
int user_image_index;
if (IsDefaultWallpaperURL(image_url, &user_image_index)) {
UserManager::Get()->SaveLoggedInUserWallpaperProperties(User::DEFAULT,
user_image_index);
ash::Shell::GetInstance()->user_wallpaper_delegate()->InitializeWallpaper();
}
}
void SetWallpaperOptionsHandler::HandleDailyWallpaper(const ListValue* args) {
User::WallpaperType type;
int index;
base::Time date;
UserManager::Get()->GetLoggedInUserWallpaperProperties(&type, &index, &date);
if (date != base::Time::Now().LocalMidnight())
index = ash::GetNextWallpaperIndex(index);
UserManager::Get()->SaveLoggedInUserWallpaperProperties(User::DAILY, index);
ash::Shell::GetInstance()->desktop_background_controller()->
SetDefaultWallpaper(index);
base::StringValue image_url(GetDefaultWallpaperThumbnailURL(index));
base::FundamentalValue is_daily(true);
web_ui()->CallJavascriptFunction("SetWallpaperOptions.setSelectedImage",
image_url, is_daily);
}
gfx::NativeWindow SetWallpaperOptionsHandler::GetBrowserWindow() const {
Browser* browser =
browser::FindBrowserWithWebContents(web_ui()->GetWebContents());
return browser->window()->GetNativeWindow();
}
} // namespace options2
} // namespace chromeos
<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright 2015 Cloudius Systems
*/
#pragma once
#include <string>
#include <vector>
#include <time.h>
#include <sstream>
#include <seastar/json/formatter.hh>
#include <seastar/core/sstring.hh>
#include <seastar/core/iostream.hh>
namespace seastar {
namespace json {
/**
* The base class for all json element.
* Every json element has a name
* An indication if it was set or not
* And is this element is mandatory.
* When a mandatory element is not set
* this is not a valid object
*/
class json_base_element {
public:
/**
* The constructors
*/
json_base_element()
: _mandatory(false), _set(false) {
}
virtual ~json_base_element() = default;
/**
* Check if it's a mandatory parameter
* and if it's set.
* @return true if this is not a mandatory parameter
* or if it is and it's value is set
*/
virtual bool is_verify() {
return !(_mandatory && !_set);
}
json_base_element& operator=(const json_base_element& o) {
// Names and mandatory are never changed after creation
_set = o._set;
return *this;
}
/**
* returns the internal value in a json format
* Each inherit class must implement this method
* @return formated internal value
*/
virtual std::string to_string() = 0;
virtual future<> write(output_stream<char>& s) const = 0;
std::string _name;
bool _mandatory;
bool _set;
};
/**
* Basic json element instantiate
* the json_element template.
* it adds a value to the base definition
* and the to_string implementation using the formatter
*/
template<class T>
class json_element : public json_base_element {
public:
/**
* the assignment operator also set
* the set value to true.
* @param new_value the new value
* @return the value itself
*/
json_element &operator=(const T& new_value) {
_value = new_value;
_set = true;
return *this;
}
/**
* the assignment operator also set
* the set value to true.
* @param new_value the new value
* @return the value itself
*/
template<class C>
json_element &operator=(const C& new_value) {
_value = new_value;
_set = true;
return *this;
}
/**
* The brackets operator
* @return the value
*/
const T& operator()() const {
return _value;
}
/**
* The to_string return the value
* formated as a json value
* @return the value foramted for json
*/
virtual std::string to_string() override
{
return formatter::to_json(_value);
}
virtual future<> write(output_stream<char>& s) const override {
return formatter::write(s, _value);
}
private:
T _value;
};
/**
* json_list is based on std vector implementation.
*
* When values are added with push it is set the "set" flag to true
* hence will be included in the parsed object
*/
template<class T>
class json_list : public json_base_element {
public:
/**
* Add an element to the list.
* @param element a new element that will be added to the list
*/
void push(const T& element) {
_set = true;
_elements.push_back(element);
}
virtual std::string to_string() override
{
return formatter::to_json(_elements);
}
/**
* Assignment can be done from any object that support const range
* iteration and that it's elements can be assigned to the list elements
*/
template<class C>
json_list& operator=(const C& list) {
_elements.clear();
for (auto i : list) {
push(i);
}
return *this;
}
virtual future<> write(output_stream<char>& s) const override {
return formatter::write(s, _elements);
}
std::vector<T> _elements;
};
class jsonable {
public:
virtual ~jsonable() = default;
/**
* create a foramted string of the object.
* @return the object formated.
*/
virtual std::string to_json() const = 0;
/*!
* \brief write an object to the output stream
*
* The defult implementation uses the to_json
* Object implementation override it.
*/
virtual future<> write(output_stream<char>& s) const {
return s.write(to_json());
}
};
/**
* The base class for all json objects
* It holds a list of all the element in it,
* allowing it implement the to_json method.
*
* It also allows iterating over the element
* in the object, even if not all the member
* are known in advance and in practice mimic
* reflection
*/
struct json_base : public jsonable {
virtual ~json_base() = default;
json_base() = default;
json_base(const json_base&) = delete;
json_base operator=(const json_base&) = delete;
/**
* create a foramted string of the object.
* @return the object formated.
*/
virtual std::string to_json() const;
/*!
* \brief write to an output stream
*/
virtual future<> write(output_stream<char>&) const;
/**
* Check that all mandatory elements are set
* @return true if all mandatory parameters are set
*/
virtual bool is_verify() const;
/**
* Register an element in an object
* @param element the element to be added
* @param name the element name
* @param mandatory is this element mandatory.
*/
virtual void add(json_base_element* element, std::string name,
bool mandatory = false);
std::vector<json_base_element*> _elements;
};
/**
* There are cases where a json request needs to return a successful
* empty reply.
* The json_void class will be used to mark that the reply should be empty.
*
*/
struct json_void : public jsonable{
virtual std::string to_json() const {
return "";
}
/*!
* \brief write to an output stream
*/
virtual future<> write(output_stream<char>& s) const {
return s.close();
}
};
/**
* The json return type, is a helper class to return a json
* formatted string.
* It uses autoboxing in its constructor so when a function return
* type is json_return_type, it could return a type that would be converted
* ie.
* json_return_type foo() {
* return "hello";
* }
*
* would return a json formatted string: "hello" (rather then hello)
*/
struct json_return_type {
sstring _res;
std::function<future<>(output_stream<char>&&)> _body_writer;
json_return_type(std::function<future<>(output_stream<char>&&)>&& body_writer) : _body_writer(std::move(body_writer)) {
}
template<class T>
json_return_type(const T& res) {
_res = formatter::to_json(res);
}
json_return_type(json_return_type&& o) noexcept : _res(std::move(o._res)), _body_writer(std::move(o._body_writer)) {
}
};
/*!
* \brief capture a range and return a serialize function for it as a json array.
*
* To use it, pass a range and a mapping function.
* For example, if res is a map:
*
* return make_ready_future<json::json_return_type>(stream_range_as_array(res, [](const auto&i) {return i.first}));
*/
template<typename Container, typename Func>
GCC6_CONCEPT( requires requires (Container c, Func aa, output_stream<char> s) { { formatter::write(s, aa(*c.begin())) } -> future<>; } )
std::function<future<>(output_stream<char>&&)> stream_range_as_array(Container val, Func fun) {
return [val = std::move(val), fun = std::move(fun)](output_stream<char>&& s) {
return do_with(output_stream<char>(std::move(s)), Container(std::move(val)), Func(std::move(fun)), true, [](output_stream<char>& s, const Container& val, const Func& f, bool& first){
return s.write("[").then([&val, &s, &first, &f] () {
return do_for_each(val, [&s, &first, &f](const typename Container::value_type& v){
auto fut = first ? make_ready_future<>() : s.write(", ");
first = false;
return fut.then([&s, &f, &v]() {
return formatter::write(s, f(v));
});
});
}).then([&s](){
return s.write("]").then([&s] {
return s.close();
});
});
});
};
}
/*!
* \brief capture an object and return a serialize function for it.
*
* To use it:
* return make_ready_future<json::json_return_type>(stream_object(res));
*/
template<class T>
std::function<future<>(output_stream<char>&&)> stream_object(T val) {
return [val = std::move(val)](output_stream<char>&& s) {
return do_with(output_stream<char>(std::move(s)), T(std::move(val)), [](output_stream<char>& s, const T& val){
return formatter::write(s, val).then([&s] {
return s.close();
});
});
};
}
}
}
<commit_msg>json: add move assignment to json_return_type<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright 2015 Cloudius Systems
*/
#pragma once
#include <string>
#include <vector>
#include <time.h>
#include <sstream>
#include <seastar/json/formatter.hh>
#include <seastar/core/sstring.hh>
#include <seastar/core/iostream.hh>
namespace seastar {
namespace json {
/**
* The base class for all json element.
* Every json element has a name
* An indication if it was set or not
* And is this element is mandatory.
* When a mandatory element is not set
* this is not a valid object
*/
class json_base_element {
public:
/**
* The constructors
*/
json_base_element()
: _mandatory(false), _set(false) {
}
virtual ~json_base_element() = default;
/**
* Check if it's a mandatory parameter
* and if it's set.
* @return true if this is not a mandatory parameter
* or if it is and it's value is set
*/
virtual bool is_verify() {
return !(_mandatory && !_set);
}
json_base_element& operator=(const json_base_element& o) {
// Names and mandatory are never changed after creation
_set = o._set;
return *this;
}
/**
* returns the internal value in a json format
* Each inherit class must implement this method
* @return formated internal value
*/
virtual std::string to_string() = 0;
virtual future<> write(output_stream<char>& s) const = 0;
std::string _name;
bool _mandatory;
bool _set;
};
/**
* Basic json element instantiate
* the json_element template.
* it adds a value to the base definition
* and the to_string implementation using the formatter
*/
template<class T>
class json_element : public json_base_element {
public:
/**
* the assignment operator also set
* the set value to true.
* @param new_value the new value
* @return the value itself
*/
json_element &operator=(const T& new_value) {
_value = new_value;
_set = true;
return *this;
}
/**
* the assignment operator also set
* the set value to true.
* @param new_value the new value
* @return the value itself
*/
template<class C>
json_element &operator=(const C& new_value) {
_value = new_value;
_set = true;
return *this;
}
/**
* The brackets operator
* @return the value
*/
const T& operator()() const {
return _value;
}
/**
* The to_string return the value
* formated as a json value
* @return the value foramted for json
*/
virtual std::string to_string() override
{
return formatter::to_json(_value);
}
virtual future<> write(output_stream<char>& s) const override {
return formatter::write(s, _value);
}
private:
T _value;
};
/**
* json_list is based on std vector implementation.
*
* When values are added with push it is set the "set" flag to true
* hence will be included in the parsed object
*/
template<class T>
class json_list : public json_base_element {
public:
/**
* Add an element to the list.
* @param element a new element that will be added to the list
*/
void push(const T& element) {
_set = true;
_elements.push_back(element);
}
virtual std::string to_string() override
{
return formatter::to_json(_elements);
}
/**
* Assignment can be done from any object that support const range
* iteration and that it's elements can be assigned to the list elements
*/
template<class C>
json_list& operator=(const C& list) {
_elements.clear();
for (auto i : list) {
push(i);
}
return *this;
}
virtual future<> write(output_stream<char>& s) const override {
return formatter::write(s, _elements);
}
std::vector<T> _elements;
};
class jsonable {
public:
virtual ~jsonable() = default;
/**
* create a foramted string of the object.
* @return the object formated.
*/
virtual std::string to_json() const = 0;
/*!
* \brief write an object to the output stream
*
* The defult implementation uses the to_json
* Object implementation override it.
*/
virtual future<> write(output_stream<char>& s) const {
return s.write(to_json());
}
};
/**
* The base class for all json objects
* It holds a list of all the element in it,
* allowing it implement the to_json method.
*
* It also allows iterating over the element
* in the object, even if not all the member
* are known in advance and in practice mimic
* reflection
*/
struct json_base : public jsonable {
virtual ~json_base() = default;
json_base() = default;
json_base(const json_base&) = delete;
json_base operator=(const json_base&) = delete;
/**
* create a foramted string of the object.
* @return the object formated.
*/
virtual std::string to_json() const;
/*!
* \brief write to an output stream
*/
virtual future<> write(output_stream<char>&) const;
/**
* Check that all mandatory elements are set
* @return true if all mandatory parameters are set
*/
virtual bool is_verify() const;
/**
* Register an element in an object
* @param element the element to be added
* @param name the element name
* @param mandatory is this element mandatory.
*/
virtual void add(json_base_element* element, std::string name,
bool mandatory = false);
std::vector<json_base_element*> _elements;
};
/**
* There are cases where a json request needs to return a successful
* empty reply.
* The json_void class will be used to mark that the reply should be empty.
*
*/
struct json_void : public jsonable{
virtual std::string to_json() const {
return "";
}
/*!
* \brief write to an output stream
*/
virtual future<> write(output_stream<char>& s) const {
return s.close();
}
};
/**
* The json return type, is a helper class to return a json
* formatted string.
* It uses autoboxing in its constructor so when a function return
* type is json_return_type, it could return a type that would be converted
* ie.
* json_return_type foo() {
* return "hello";
* }
*
* would return a json formatted string: "hello" (rather then hello)
*/
struct json_return_type {
sstring _res;
std::function<future<>(output_stream<char>&&)> _body_writer;
json_return_type(std::function<future<>(output_stream<char>&&)>&& body_writer) : _body_writer(std::move(body_writer)) {
}
template<class T>
json_return_type(const T& res) {
_res = formatter::to_json(res);
}
json_return_type(json_return_type&& o) noexcept : _res(std::move(o._res)), _body_writer(std::move(o._body_writer)) {
}
json_return_type& operator=(json_return_type&& o) noexcept {
_res = std::move(o._res);
_body_writer = std::move(o._body_writer);
return *this;
}
};
/*!
* \brief capture a range and return a serialize function for it as a json array.
*
* To use it, pass a range and a mapping function.
* For example, if res is a map:
*
* return make_ready_future<json::json_return_type>(stream_range_as_array(res, [](const auto&i) {return i.first}));
*/
template<typename Container, typename Func>
GCC6_CONCEPT( requires requires (Container c, Func aa, output_stream<char> s) { { formatter::write(s, aa(*c.begin())) } -> future<>; } )
std::function<future<>(output_stream<char>&&)> stream_range_as_array(Container val, Func fun) {
return [val = std::move(val), fun = std::move(fun)](output_stream<char>&& s) {
return do_with(output_stream<char>(std::move(s)), Container(std::move(val)), Func(std::move(fun)), true, [](output_stream<char>& s, const Container& val, const Func& f, bool& first){
return s.write("[").then([&val, &s, &first, &f] () {
return do_for_each(val, [&s, &first, &f](const typename Container::value_type& v){
auto fut = first ? make_ready_future<>() : s.write(", ");
first = false;
return fut.then([&s, &f, &v]() {
return formatter::write(s, f(v));
});
});
}).then([&s](){
return s.write("]").then([&s] {
return s.close();
});
});
});
};
}
/*!
* \brief capture an object and return a serialize function for it.
*
* To use it:
* return make_ready_future<json::json_return_type>(stream_object(res));
*/
template<class T>
std::function<future<>(output_stream<char>&&)> stream_object(T val) {
return [val = std::move(val)](output_stream<char>&& s) {
return do_with(output_stream<char>(std::move(s)), T(std::move(val)), [](output_stream<char>& s, const T& val){
return formatter::write(s, val).then([&s] {
return s.close();
});
});
};
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2019 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_CONTRIB_INTEGER_HPP
#define TAO_PEGTL_CONTRIB_INTEGER_HPP
#include <cstdint>
#include <cstdlib>
#include <type_traits>
#include "../ascii.hpp"
#include "../parse.hpp"
#include "../parse_error.hpp"
#include "../rules.hpp"
#include <iostream>
namespace TAO_PEGTL_NAMESPACE::integer
{
namespace internal
{
struct unsigned_rule_old
: plus< digit >
{
};
struct unsigned_rule_new
: if_then_else< one< '0' >, not_at< digit >, plus< digit > >
{
};
struct signed_rule_old
: seq< opt< one< '-', '+' > >, plus< digit > >
{
};
struct signed_rule_new
: seq< opt< one< '-', '+' > >, if_then_else< one< '0' >, not_at< digit >, plus< digit > > >
{
};
struct signed_rule_bis
: seq< opt< one< '-' > >, if_then_else< one< '0' >, not_at< digit >, plus< digit > > >
{
};
struct signed_rule_ter
: seq< one< '-', '+' >, if_then_else< one< '0' >, not_at< digit >, plus< digit > > >
{
};
[[nodiscard]] constexpr bool is_digit( const char c ) noexcept
{
// We don't use std::isdigit() because it might
// return true for other values on MS platforms.
return ( '0' <= c ) && ( c <= '9' );
}
template< typename Integer, Integer Maximum = ( std::numeric_limits< Integer >::max )() >
[[nodiscard]] constexpr bool accumulate_digit( Integer& result, const char digit ) noexcept
{
// Assumes that digit is a digit as per is_digit(); returns false on overflow.
static_assert( std::is_integral_v< Integer > );
constexpr Integer cutoff = Maximum / 10;
constexpr Integer cutlim = Maximum % 10;
const Integer c = digit - '0';
if( ( result > cutoff ) || ( ( result == cutoff ) && ( c > cutlim ) ) ) {
return false;
}
result *= 10;
result += c;
return true;
}
template< typename Integer, Integer Maximum = ( std::numeric_limits< Integer >::max )() >
[[nodiscard]] constexpr bool accumulate_digits( Integer& result, const std::string_view input ) noexcept
{
// Assumes input is a non-empty sequence of digits; returns false on overflow.
for( std::size_t i = 0; i < input.size(); ++i ) {
if( !accumulate_digit< Integer, Maximum >( result, input[ i ] ) ) {
return false;
}
}
return true;
}
template< typename Integer, Integer Maximum = ( std::numeric_limits< Integer >::max )() >
[[nodiscard]] constexpr bool convert_positive( Integer& result, const std::string_view input ) noexcept
{
// Assumes result == 0 and that input is a non-empty sequence of digits; returns false on overflow.
static_assert( std::is_integral_v< Integer > );
return accumulate_digits< Integer, Maximum >( result, input );
}
template< typename Signed >
[[nodiscard]] constexpr bool convert_negative( Signed& result, const std::string_view input ) noexcept
{
// Assumes result == 0 and that input is a non-empty sequence of digits; returns false on overflow.
static_assert( std::is_signed_v< Signed > );
using Unsigned = std::make_unsigned_t< Signed >;
constexpr Unsigned maximum = static_cast< Unsigned >( ( std::numeric_limits< Signed >::max )() ) + 1;
Unsigned temporary = 0;
if( accumulate_digits< Unsigned, maximum >( temporary, input ) ) {
result = static_cast< Signed >( ~temporary ) + 1;
return true;
}
return false;
}
template< typename Unsigned, Unsigned Maximum = ( std::numeric_limits< Unsigned >::max )() >
[[nodiscard]] constexpr bool convert_unsigned( Unsigned& result, const std::string_view input ) noexcept
{
// Assumes result == 0 and that input is a non-empty sequence of digits; returns false on overflow.
static_assert( std::is_unsigned_v< Unsigned > );
return accumulate_digits< Unsigned, Maximum >( result, input );
}
template< typename Signed >
[[nodiscard]] constexpr bool convert_signed( Signed& result, const std::string_view input ) noexcept
{
// Assumes result == 0 and that input is an optional sign followed by a non-empty sequence of digits; returns false on overflow.
static_assert( std::is_signed_v< Signed > );
if( input[ 0 ] == '-' ) {
return convert_negative< Signed >( result, std::string_view( input.data() + 1, input.size() - 1 ) );
}
const auto offset = unsigned( input[ 0 ] == '+' );
return convert_positive< Signed >( result, std::string_view( input.data() + offset, input.size() - offset ) );
}
template< typename Input >
[[nodiscard]] bool match_unsigned( Input& in ) noexcept( noexcept( in.empty() ) )
{
if( !in.empty() ) {
const char c = in.peek_char();
if( is_digit( c ) ) {
in.bump_in_this_line();
if( c == '0' ) {
return in.empty() || ( !is_digit( in.peek_char() ) ); // Or throw exception?
}
while( ( !in.empty() ) && is_digit( in.peek_char() ) ) {
in.bump_in_this_line();
}
return true;
}
}
return false;
}
template< typename Input,
typename Unsigned,
Unsigned Maximum = ( std::numeric_limits< Unsigned >::max )() >
[[nodiscard]] bool match_and_convert_unsigned_with_maximum( Input& in, Unsigned& st )
{
// Assumes st == 0.
if( !in.empty() ) {
char c = in.peek_char();
if( is_digit( c ) ) {
if( c == '0' ) {
in.bump_in_this_line();
return in.empty() || ( !is_digit( in.peek_char() ) ); // Or throw exception?
}
while( ( !in.empty() ) && is_digit( c = in.peek_char() ) ) {
if( !accumulate_digit< Unsigned, Maximum >( st, c ) ) {
throw parse_error( "integer overflow", in ); // Should be fine for most applications.
}
in.bump_in_this_line();
}
return true;
}
}
return false;
}
} // namespace internal
struct unsigned_action
{
// Assumes that 'in' contains a non-empty sequence of ASCII digits.
template< typename Input, typename Unsigned >
static auto apply( const Input& in, Unsigned& st ) -> std::enable_if_t< std::is_integral_v< Unsigned >, void >
{
st = 0;
if( !internal::convert_unsigned( st, in.string_view() ) ) {
throw parse_error( "unsigned integer overflow", in );
}
}
template< typename Input, typename State >
static auto apply( const Input& in, State& st ) -> std::enable_if_t< std::is_class_v< State >, void >
{
apply( in, st.converted );
}
template< typename Input, typename Unsigned, typename... Ts >
static auto apply( const Input& in, std::vector< Unsigned, Ts... >& st ) -> std::enable_if_t< std::is_integral_v< Unsigned >, void >
{
Unsigned u = 0;
apply( in, u );
st.emplace_back( u );
}
};
struct unsigned_rule
{
using analyze_t = internal::unsigned_rule_new::analyze_t;
template< apply_mode A,
rewind_mode M,
template< typename... >
class Action,
template< typename... >
class Control,
typename Input,
typename... States >
[[nodiscard]] static bool match( Input& in, States&&... /*unused*/ ) noexcept( noexcept( in.empty() ) )
{
return internal::match_unsigned( in ); // Does not check for any overflow.
}
};
struct unsigned_rule_with_action
{
using analyze_t = internal::unsigned_rule_new::analyze_t;
template< apply_mode A,
rewind_mode M,
template< typename... >
class Action,
template< typename... >
class Control,
typename Input,
typename... States >
[[nodiscard]] static auto match( Input& in, States&&... /*unused*/ ) noexcept( noexcept( in.empty() ) ) -> std::enable_if_t< A == apply_mode::nothing, bool >
{
return internal::match_unsigned( in ); // Does not check for any overflow.
}
template< apply_mode A,
rewind_mode M,
template< typename... >
class Action,
template< typename... >
class Control,
typename Input,
typename Unsigned >
[[nodiscard]] static auto match( Input& in, Unsigned& st ) -> std::enable_if_t< ( A == apply_mode::action ) && std::is_unsigned_v< Unsigned >, bool >
{
st = 0;
return internal::match_and_convert_unsigned_with_maximum( in, st ); // Throws on overflow.
}
// TODO: Overload for st.converted?
// TODO: Overload for std::vector< Unsigned >?
};
template< typename Unsigned, Unsigned Maximum >
struct maximum_action
{
// Assumes that 'in' contains a non-empty sequence of ASCII digits.
static_assert( std::is_unsigned_v< Unsigned > );
template< typename Input >
static auto apply( const Input& in, Unsigned& st ) -> std::enable_if_t< std::is_integral_v< Unsigned >, void >
{
st = 0;
if( !internal::convert_unsigned< Unsigned, Maximum >( st, in.string_view() ) ) {
throw parse_error( "unsigned integer overflow", in );
}
}
template< typename Input, typename State >
static auto apply( const Input& in, State& st ) -> std::enable_if_t< std::is_class_v< State >, void >
{
apply( in, st.converted );
}
template< typename Input, typename... Ts >
static auto apply( const Input& in, std::vector< Unsigned, Ts... >& st ) -> std::enable_if_t< std::is_integral_v< Unsigned >, void >
{
Unsigned u = 0;
apply( in, u );
st.emplace_back( u );
}
};
template< typename Unsigned, Unsigned Maximum = ( std::numeric_limits< Unsigned >::max )() >
struct maximum_rule
{
static_assert( std::is_unsigned_v< Unsigned > );
using analyze_t = internal::unsigned_rule_new::analyze_t;
template< apply_mode A,
rewind_mode M,
template< typename... >
class Action,
template< typename... >
class Control,
typename Input,
typename... States >
[[nodiscard]] static bool match( Input& in, States&&... /*unused*/ )
{
Unsigned st = 0;
return internal::match_and_convert_unsigned_with_maximum< Input, Unsigned, Maximum >( in, st ); // Throws on overflow.
}
};
template< typename Unsigned, Unsigned Maximum = ( std::numeric_limits< Unsigned >::max )() >
struct maximum_rule_with_action
{
static_assert( std::is_unsigned_v< Unsigned > );
using analyze_t = internal::unsigned_rule_new::analyze_t;
template< apply_mode A,
rewind_mode M,
template< typename... >
class Action,
template< typename... >
class Control,
typename Input,
typename... States >
[[nodiscard]] static auto match( Input& in, States&&... /*unused*/ ) -> std::enable_if_t< A == apply_mode::nothing, bool >
{
Unsigned st = 0;
return internal::match_and_convert_unsigned_with_maximum< Input, Unsigned, Maximum >( in, st ); // Throws on overflow.
}
template< apply_mode A,
rewind_mode M,
template< typename... >
class Action,
template< typename... >
class Control,
typename Input,
typename Unsigned2 >
[[nodiscard]] static auto match( Input& in, Unsigned& st ) -> std::enable_if_t< ( A == apply_mode::action ) && std::is_same_v< Unsigned, Unsigned2 >, bool >
{
st = 0;
return internal::match_and_convert_unsigned_with_maximum< Input, Unsigned, Maximum >( in, st ); // Throws on overflow.
}
// TODO: Overload for st.converted?
// TODO: Overload for std::vector< Unsigned >?
};
struct signed_action
{
// Assumes that 'in' contains a non-empty sequence of ASCII digits,
// with optional leading sign; with sign, in.size() must be >= 2.
template< typename Input, typename Signed >
static auto apply( const Input& in, Signed& st ) -> std::enable_if_t< std::is_integral_v< Signed >, void >
{
st = 0;
if( !internal::convert_signed( st, in.string_view() ) ) {
throw parse_error( "signed integer overflow", in );
}
}
template< typename Input, typename State >
static auto apply( const Input& in, State& st ) -> std::enable_if_t< std::is_class_v< State >, void >
{
apply( in, st.converted );
}
template< typename Input, typename Signed, typename... Ts >
static auto apply( const Input& in, std::vector< Signed, Ts... >& st ) -> std::enable_if_t< std::is_integral_v< Signed >, void >
{
Signed s = 0;
apply( in, s );
st.emplace_back( s );
}
};
struct signed_rule
{
using analyze_t = internal::signed_rule_new::analyze_t;
template< apply_mode A,
rewind_mode M,
template< typename... >
class Action,
template< typename... >
class Control,
typename Input,
typename... States >
[[nodiscard]] static bool match( Input& in, States&&... /*unused*/ ) noexcept( noexcept( in.empty() ) )
{
return TAO_PEGTL_NAMESPACE::parse< internal::signed_rule_new >( in ); // Does not check for any overflow.
}
};
struct signed_rule_with_action
{
using analyze_t = internal::signed_rule_new::analyze_t;
template< apply_mode A,
rewind_mode M,
template< typename... >
class Action,
template< typename... >
class Control,
typename Input,
typename... States >
[[nodiscard]] static auto match( Input& in, States&&... /*unused*/ ) noexcept( noexcept( in.empty() ) ) -> std::enable_if_t< A == apply_mode::nothing, bool >
{
return TAO_PEGTL_NAMESPACE::parse< internal::signed_rule_new >( in ); // Does not check for any overflow.
}
template< apply_mode A,
rewind_mode M,
template< typename... >
class Action,
template< typename... >
class Control,
typename Input,
typename Signed >
[[nodiscard]] static auto match( Input& in, Signed& st ) -> std::enable_if_t< ( A == apply_mode::action ) && std::is_signed_v< Signed >, bool >
{
return TAO_PEGTL_NAMESPACE::parse< internal::signed_rule_new, signed_action >( in, st ); // Throws on overflow.
}
// TODO: Overload for st.converted?
// TODO: Overload for std::vector< Signed >?
};
} // namespace TAO_PEGTL_NAMESPACE::integer
#endif
<commit_msg>Small fix.<commit_after>// Copyright (c) 2019 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_CONTRIB_INTEGER_HPP
#define TAO_PEGTL_CONTRIB_INTEGER_HPP
#include <cstdint>
#include <cstdlib>
#include <type_traits>
#include "../ascii.hpp"
#include "../parse.hpp"
#include "../parse_error.hpp"
#include "../rules.hpp"
namespace TAO_PEGTL_NAMESPACE::integer
{
namespace internal
{
struct unsigned_rule_old
: plus< digit >
{
};
struct unsigned_rule_new
: if_then_else< one< '0' >, not_at< digit >, plus< digit > >
{
};
struct signed_rule_old
: seq< opt< one< '-', '+' > >, plus< digit > >
{
};
struct signed_rule_new
: seq< opt< one< '-', '+' > >, if_then_else< one< '0' >, not_at< digit >, plus< digit > > >
{
};
struct signed_rule_bis
: seq< opt< one< '-' > >, if_then_else< one< '0' >, not_at< digit >, plus< digit > > >
{
};
struct signed_rule_ter
: seq< one< '-', '+' >, if_then_else< one< '0' >, not_at< digit >, plus< digit > > >
{
};
[[nodiscard]] constexpr bool is_digit( const char c ) noexcept
{
// We don't use std::isdigit() because it might
// return true for other values on MS platforms.
return ( '0' <= c ) && ( c <= '9' );
}
template< typename Integer, Integer Maximum = ( std::numeric_limits< Integer >::max )() >
[[nodiscard]] constexpr bool accumulate_digit( Integer& result, const char digit ) noexcept
{
// Assumes that digit is a digit as per is_digit(); returns false on overflow.
static_assert( std::is_integral_v< Integer > );
constexpr Integer cutoff = Maximum / 10;
constexpr Integer cutlim = Maximum % 10;
const Integer c = digit - '0';
if( ( result > cutoff ) || ( ( result == cutoff ) && ( c > cutlim ) ) ) {
return false;
}
result *= 10;
result += c;
return true;
}
template< typename Integer, Integer Maximum = ( std::numeric_limits< Integer >::max )() >
[[nodiscard]] constexpr bool accumulate_digits( Integer& result, const std::string_view input ) noexcept
{
// Assumes input is a non-empty sequence of digits; returns false on overflow.
for( std::size_t i = 0; i < input.size(); ++i ) {
if( !accumulate_digit< Integer, Maximum >( result, input[ i ] ) ) {
return false;
}
}
return true;
}
template< typename Integer, Integer Maximum = ( std::numeric_limits< Integer >::max )() >
[[nodiscard]] constexpr bool convert_positive( Integer& result, const std::string_view input ) noexcept
{
// Assumes result == 0 and that input is a non-empty sequence of digits; returns false on overflow.
static_assert( std::is_integral_v< Integer > );
return accumulate_digits< Integer, Maximum >( result, input );
}
template< typename Signed >
[[nodiscard]] constexpr bool convert_negative( Signed& result, const std::string_view input ) noexcept
{
// Assumes result == 0 and that input is a non-empty sequence of digits; returns false on overflow.
static_assert( std::is_signed_v< Signed > );
using Unsigned = std::make_unsigned_t< Signed >;
constexpr Unsigned maximum = static_cast< Unsigned >( ( std::numeric_limits< Signed >::max )() ) + 1;
Unsigned temporary = 0;
if( accumulate_digits< Unsigned, maximum >( temporary, input ) ) {
result = static_cast< Signed >( ~temporary ) + 1;
return true;
}
return false;
}
template< typename Unsigned, Unsigned Maximum = ( std::numeric_limits< Unsigned >::max )() >
[[nodiscard]] constexpr bool convert_unsigned( Unsigned& result, const std::string_view input ) noexcept
{
// Assumes result == 0 and that input is a non-empty sequence of digits; returns false on overflow.
static_assert( std::is_unsigned_v< Unsigned > );
return accumulate_digits< Unsigned, Maximum >( result, input );
}
template< typename Signed >
[[nodiscard]] constexpr bool convert_signed( Signed& result, const std::string_view input ) noexcept
{
// Assumes result == 0 and that input is an optional sign followed by a non-empty sequence of digits; returns false on overflow.
static_assert( std::is_signed_v< Signed > );
if( input[ 0 ] == '-' ) {
return convert_negative< Signed >( result, std::string_view( input.data() + 1, input.size() - 1 ) );
}
const auto offset = unsigned( input[ 0 ] == '+' );
return convert_positive< Signed >( result, std::string_view( input.data() + offset, input.size() - offset ) );
}
template< typename Input >
[[nodiscard]] bool match_unsigned( Input& in ) noexcept( noexcept( in.empty() ) )
{
if( !in.empty() ) {
const char c = in.peek_char();
if( is_digit( c ) ) {
in.bump_in_this_line();
if( c == '0' ) {
return in.empty() || ( !is_digit( in.peek_char() ) ); // Or throw exception?
}
while( ( !in.empty() ) && is_digit( in.peek_char() ) ) {
in.bump_in_this_line();
}
return true;
}
}
return false;
}
template< typename Input,
typename Unsigned,
Unsigned Maximum = ( std::numeric_limits< Unsigned >::max )() >
[[nodiscard]] bool match_and_convert_unsigned_with_maximum( Input& in, Unsigned& st )
{
// Assumes st == 0.
if( !in.empty() ) {
char c = in.peek_char();
if( is_digit( c ) ) {
if( c == '0' ) {
in.bump_in_this_line();
return in.empty() || ( !is_digit( in.peek_char() ) ); // Or throw exception?
}
while( ( !in.empty() ) && is_digit( c = in.peek_char() ) ) {
if( !accumulate_digit< Unsigned, Maximum >( st, c ) ) {
throw parse_error( "integer overflow", in ); // Should be fine for most applications.
}
in.bump_in_this_line();
}
return true;
}
}
return false;
}
} // namespace internal
struct unsigned_action
{
// Assumes that 'in' contains a non-empty sequence of ASCII digits.
template< typename Input, typename Unsigned >
static auto apply( const Input& in, Unsigned& st ) -> std::enable_if_t< std::is_integral_v< Unsigned >, void >
{
st = 0;
if( !internal::convert_unsigned( st, in.string_view() ) ) {
throw parse_error( "unsigned integer overflow", in );
}
}
template< typename Input, typename State >
static auto apply( const Input& in, State& st ) -> std::enable_if_t< std::is_class_v< State >, void >
{
apply( in, st.converted );
}
template< typename Input, typename Unsigned, typename... Ts >
static auto apply( const Input& in, std::vector< Unsigned, Ts... >& st ) -> std::enable_if_t< std::is_integral_v< Unsigned >, void >
{
Unsigned u = 0;
apply( in, u );
st.emplace_back( u );
}
};
struct unsigned_rule
{
using analyze_t = internal::unsigned_rule_new::analyze_t;
template< apply_mode A,
rewind_mode M,
template< typename... >
class Action,
template< typename... >
class Control,
typename Input,
typename... States >
[[nodiscard]] static bool match( Input& in, States&&... /*unused*/ ) noexcept( noexcept( in.empty() ) )
{
return internal::match_unsigned( in ); // Does not check for any overflow.
}
};
struct unsigned_rule_with_action
{
using analyze_t = internal::unsigned_rule_new::analyze_t;
template< apply_mode A,
rewind_mode M,
template< typename... >
class Action,
template< typename... >
class Control,
typename Input,
typename... States >
[[nodiscard]] static auto match( Input& in, States&&... /*unused*/ ) noexcept( noexcept( in.empty() ) ) -> std::enable_if_t< A == apply_mode::nothing, bool >
{
return internal::match_unsigned( in ); // Does not check for any overflow.
}
template< apply_mode A,
rewind_mode M,
template< typename... >
class Action,
template< typename... >
class Control,
typename Input,
typename Unsigned >
[[nodiscard]] static auto match( Input& in, Unsigned& st ) -> std::enable_if_t< ( A == apply_mode::action ) && std::is_unsigned_v< Unsigned >, bool >
{
st = 0;
return internal::match_and_convert_unsigned_with_maximum( in, st ); // Throws on overflow.
}
// TODO: Overload for st.converted?
// TODO: Overload for std::vector< Unsigned >?
};
template< typename Unsigned, Unsigned Maximum >
struct maximum_action
{
// Assumes that 'in' contains a non-empty sequence of ASCII digits.
static_assert( std::is_unsigned_v< Unsigned > );
template< typename Input >
static auto apply( const Input& in, Unsigned& st ) -> std::enable_if_t< std::is_integral_v< Unsigned >, void >
{
st = 0;
if( !internal::convert_unsigned< Unsigned, Maximum >( st, in.string_view() ) ) {
throw parse_error( "unsigned integer overflow", in );
}
}
template< typename Input, typename State >
static auto apply( const Input& in, State& st ) -> std::enable_if_t< std::is_class_v< State >, void >
{
apply( in, st.converted );
}
template< typename Input, typename... Ts >
static auto apply( const Input& in, std::vector< Unsigned, Ts... >& st ) -> std::enable_if_t< std::is_integral_v< Unsigned >, void >
{
Unsigned u = 0;
apply( in, u );
st.emplace_back( u );
}
};
template< typename Unsigned, Unsigned Maximum = ( std::numeric_limits< Unsigned >::max )() >
struct maximum_rule
{
static_assert( std::is_unsigned_v< Unsigned > );
using analyze_t = internal::unsigned_rule_new::analyze_t;
template< apply_mode A,
rewind_mode M,
template< typename... >
class Action,
template< typename... >
class Control,
typename Input,
typename... States >
[[nodiscard]] static bool match( Input& in, States&&... /*unused*/ )
{
Unsigned st = 0;
return internal::match_and_convert_unsigned_with_maximum< Input, Unsigned, Maximum >( in, st ); // Throws on overflow.
}
};
template< typename Unsigned, Unsigned Maximum = ( std::numeric_limits< Unsigned >::max )() >
struct maximum_rule_with_action
{
static_assert( std::is_unsigned_v< Unsigned > );
using analyze_t = internal::unsigned_rule_new::analyze_t;
template< apply_mode A,
rewind_mode M,
template< typename... >
class Action,
template< typename... >
class Control,
typename Input,
typename... States >
[[nodiscard]] static auto match( Input& in, States&&... /*unused*/ ) -> std::enable_if_t< A == apply_mode::nothing, bool >
{
Unsigned st = 0;
return internal::match_and_convert_unsigned_with_maximum< Input, Unsigned, Maximum >( in, st ); // Throws on overflow.
}
template< apply_mode A,
rewind_mode M,
template< typename... >
class Action,
template< typename... >
class Control,
typename Input,
typename Unsigned2 >
[[nodiscard]] static auto match( Input& in, Unsigned& st ) -> std::enable_if_t< ( A == apply_mode::action ) && std::is_same_v< Unsigned, Unsigned2 >, bool >
{
st = 0;
return internal::match_and_convert_unsigned_with_maximum< Input, Unsigned, Maximum >( in, st ); // Throws on overflow.
}
// TODO: Overload for st.converted?
// TODO: Overload for std::vector< Unsigned >?
};
struct signed_action
{
// Assumes that 'in' contains a non-empty sequence of ASCII digits,
// with optional leading sign; with sign, in.size() must be >= 2.
template< typename Input, typename Signed >
static auto apply( const Input& in, Signed& st ) -> std::enable_if_t< std::is_integral_v< Signed >, void >
{
st = 0;
if( !internal::convert_signed( st, in.string_view() ) ) {
throw parse_error( "signed integer overflow", in );
}
}
template< typename Input, typename State >
static auto apply( const Input& in, State& st ) -> std::enable_if_t< std::is_class_v< State >, void >
{
apply( in, st.converted );
}
template< typename Input, typename Signed, typename... Ts >
static auto apply( const Input& in, std::vector< Signed, Ts... >& st ) -> std::enable_if_t< std::is_integral_v< Signed >, void >
{
Signed s = 0;
apply( in, s );
st.emplace_back( s );
}
};
struct signed_rule
{
using analyze_t = internal::signed_rule_new::analyze_t;
template< apply_mode A,
rewind_mode M,
template< typename... >
class Action,
template< typename... >
class Control,
typename Input,
typename... States >
[[nodiscard]] static bool match( Input& in, States&&... /*unused*/ ) noexcept( noexcept( in.empty() ) )
{
return TAO_PEGTL_NAMESPACE::parse< internal::signed_rule_new >( in ); // Does not check for any overflow.
}
};
struct signed_rule_with_action
{
using analyze_t = internal::signed_rule_new::analyze_t;
template< apply_mode A,
rewind_mode M,
template< typename... >
class Action,
template< typename... >
class Control,
typename Input,
typename... States >
[[nodiscard]] static auto match( Input& in, States&&... /*unused*/ ) noexcept( noexcept( in.empty() ) ) -> std::enable_if_t< A == apply_mode::nothing, bool >
{
return TAO_PEGTL_NAMESPACE::parse< internal::signed_rule_new >( in ); // Does not check for any overflow.
}
template< apply_mode A,
rewind_mode M,
template< typename... >
class Action,
template< typename... >
class Control,
typename Input,
typename Signed >
[[nodiscard]] static auto match( Input& in, Signed& st ) -> std::enable_if_t< ( A == apply_mode::action ) && std::is_signed_v< Signed >, bool >
{
return TAO_PEGTL_NAMESPACE::parse< internal::signed_rule_new, signed_action >( in, st ); // Throws on overflow.
}
// TODO: Overload for st.converted?
// TODO: Overload for std::vector< Signed >?
};
} // namespace TAO_PEGTL_NAMESPACE::integer
#endif
<|endoftext|> |
<commit_before><commit_msg>PocoSQLControlDao: fix checking of control ID<commit_after><|endoftext|> |
<commit_before>#ifndef ORG_EEROS_CONTROL_MOUSEINPUT_HPP_
#define ORG_EEROS_CONTROL_MOUSEINPUT_HPP_
#include <eeros/control/Blockio.hpp>
#include <eeros/math/Matrix.hpp>
#include <eeros/hal/Mouse.hpp>
using namespace eeros::math;
using namespace eeros::hal;
namespace eeros {
namespace control {
/**
* This block serves to read the input from a standard mouse with x, y coordinates, two
* wheels and three buttons. The range of all the input parameters together with the scaling
* can be choosen as needed.
*
* @since v0.6
*/
class MouseInput: public Blockio<0,1,Vector4> {
public:
MouseInput(std::string dev, int priority = 20);
MouseInput(std::string dev, Vector4 scale, Vector4 min, Vector4 max, int priority = 20);
/**
* Disabling use of copy constructor because the block should never be copied unintentionally.
*/
MouseInput(const MouseInput& s) = delete;
Output<Matrix<3,1,bool>>& getButtonOut();
virtual void run();
virtual void setInitPos(double x, double y, double z, double r);
virtual void setInitPos(Vector4 pos);
virtual void reset(double x, double y, double z, double r);
protected:
Mouse mouse;
Output<Matrix<3,1,bool>> buttonOut;
double x, y, z, r;
bool first;
double axisScale_x = 0.0001;
double axisScale_y = 0.0001;
double axisScale_z = 0.001;
double axisScale_r = 0.2;
double min_x = -0.03;
double max_x = 0.045;
double min_y = -0.03;
double max_y = 0.03;
double min_z = -0.053;
double max_z = -0.015;
double min_r = -2.8;
double max_r = 2.8;
};
};
};
#endif /* ORG_EEROS_CONTROL_MOUSEINPUT_HPP_ */
<commit_msg>Enlarge range to fit for delta robot with lower table<commit_after>#ifndef ORG_EEROS_CONTROL_MOUSEINPUT_HPP_
#define ORG_EEROS_CONTROL_MOUSEINPUT_HPP_
#include <eeros/control/Blockio.hpp>
#include <eeros/math/Matrix.hpp>
#include <eeros/hal/Mouse.hpp>
using namespace eeros::math;
using namespace eeros::hal;
namespace eeros {
namespace control {
/**
* This block serves to read the input from a standard mouse with x, y coordinates, two
* wheels and three buttons. The range of all the input parameters together with the scaling
* can be choosen as needed.
*
* @since v0.6
*/
class MouseInput: public Blockio<0,1,Vector4> {
public:
MouseInput(std::string dev, int priority = 20);
MouseInput(std::string dev, Vector4 scale, Vector4 min, Vector4 max, int priority = 20);
/**
* Disabling use of copy constructor because the block should never be copied unintentionally.
*/
MouseInput(const MouseInput& s) = delete;
Output<Matrix<3,1,bool>>& getButtonOut();
virtual void run();
virtual void setInitPos(double x, double y, double z, double r);
virtual void setInitPos(Vector4 pos);
virtual void reset(double x, double y, double z, double r);
protected:
Mouse mouse;
Output<Matrix<3,1,bool>> buttonOut;
double x, y, z, r;
bool first;
double axisScale_x = 0.0001;
double axisScale_y = 0.0001;
double axisScale_z = 0.001;
double axisScale_r = 0.2;
double min_x = -0.03;
double max_x = 0.045;
double min_y = -0.03;
double max_y = 0.03;
double min_z = -0.063;
double max_z = -0.015;
double min_r = -2.8;
double max_r = 2.8;
};
};
};
#endif /* ORG_EEROS_CONTROL_MOUSEINPUT_HPP_ */
<|endoftext|> |
<commit_before>#include "Animation.h"
Animation::~Animation() {}
Animation::Animation(float x, float y, float z, std::vector<Model*> *frames) : Entity(x, y, z)
{
this->name = frames->at(0)->name;
this->frames = frames;
}
void Animation::runOnce()
{
isOnce = true;
}
/*** get ***/
float Animation::getWidth()
{
return currentModel->width;
}
float Animation::getHeight()
{
return currentModel->height;
}
float Animation::getDepth()
{
return currentModel->depth;
}
bool Animation::getIsRunning()
{
return isRunning;
}
bool Animation::getIsOnce()
{
return isOnce;
}
float Animation::getRate()
{
return rate;
}
float * Animation::getScale()
{
return frames->at(0)->getScale();
}
bool Animation::getPingPong()
{
return isPingPong;
}
Model * Animation::getFrame(int i)
{
return frames->at(i);
}
Model * Animation::getCurrentFrame()
{
int numFrames = frames->size() - 1;
if (isRunning) {
// ping-pong mode
if (isPingPong) {
if (pingPongAscending) {
if (frameCounter < numFrames) {
currentModel = frames->at(floor(frameCounter));
frameCounter += rate;
} else {
pingPongAscending = false;
frameCounter -= rate;
currentModel = frames->at(floor(frameCounter));
}
} else {
if (frameCounter > 0) {
currentModel = frames->at(floor(frameCounter));
frameCounter -= rate;
} else {
pingPongAscending = true;
frameCounter += rate;
currentModel = frames->at(floor(frameCounter));
}
}
// standard linear mode
} else {
if (frameCounter < numFrames) {
currentModel = frames->at(floor(frameCounter));
frameCounter += rate;
} else {
if (isOnce) {
currentModel = frames->at(6);
isRunning = false;
} else {
frameCounter = 0.0;
currentModel = frames->at(floor(frameCounter));
}
}
}
} else {
currentModel = frames->at(6);
}
currentModel->position.x = this->position.x;
currentModel->position.y = this->position.y;
currentModel->position.z = this->position.z;
return currentModel;
}
int Animation::getNumFrames()
{
return frames->size();
}
/*** set ***/
void Animation::setRate(float rate)
{
this->rate = rate;
}
void Animation::setScale(float scale)
{
for (int i = 0; i < frames->size(); ++i) {
frames->at(i)->setScale(scale);
}
}
void Animation::setPingPong(bool pong)
{
isPingPong = pong;
}
<commit_msg>Selector position above Animations now only based on the height of the first frame of animation<commit_after>#include "Animation.h"
Animation::~Animation() {}
Animation::Animation(float x, float y, float z, std::vector<Model*> *frames) : Entity(x, y, z)
{
this->name = frames->at(0)->name;
this->frames = frames;
}
void Animation::runOnce()
{
isOnce = true;
}
/*** get ***/
float Animation::getWidth()
{
return currentModel->width;
}
float Animation::getHeight()
{
return frames->at(0)->height;
}
float Animation::getDepth()
{
return currentModel->depth;
}
bool Animation::getIsRunning()
{
return isRunning;
}
bool Animation::getIsOnce()
{
return isOnce;
}
float Animation::getRate()
{
return rate;
}
float * Animation::getScale()
{
return frames->at(0)->getScale();
}
bool Animation::getPingPong()
{
return isPingPong;
}
Model * Animation::getFrame(int i)
{
return frames->at(i);
}
Model * Animation::getCurrentFrame()
{
int numFrames = frames->size() - 1;
if (isRunning) {
// ping-pong mode
if (isPingPong) {
if (pingPongAscending) {
if (frameCounter < numFrames) {
currentModel = frames->at(floor(frameCounter));
frameCounter += rate;
} else {
pingPongAscending = false;
frameCounter -= rate;
currentModel = frames->at(floor(frameCounter));
}
} else {
if (frameCounter > 0) {
currentModel = frames->at(floor(frameCounter));
frameCounter -= rate;
} else {
pingPongAscending = true;
frameCounter += rate;
currentModel = frames->at(floor(frameCounter));
}
}
// standard linear mode
} else {
if (frameCounter < numFrames) {
currentModel = frames->at(floor(frameCounter));
frameCounter += rate;
} else {
if (isOnce) {
currentModel = frames->at(6);
isRunning = false;
} else {
frameCounter = 0.0;
currentModel = frames->at(floor(frameCounter));
}
}
}
} else {
currentModel = frames->at(6);
}
currentModel->position.x = this->position.x;
currentModel->position.y = this->position.y;
currentModel->position.z = this->position.z;
return currentModel;
}
int Animation::getNumFrames()
{
return frames->size();
}
/*** set ***/
void Animation::setRate(float rate)
{
this->rate = rate;
}
void Animation::setScale(float scale)
{
for (int i = 0; i < frames->size(); ++i) {
frames->at(i)->setScale(scale);
}
}
void Animation::setPingPong(bool pong)
{
isPingPong = pong;
}
<|endoftext|> |
<commit_before><commit_msg>Added assign logic<commit_after><|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 "otbImage.h"
#include "otbLineSegmentDetector.h"
#include "otbDrawLineSpatialObjectListFilter.h"
#include "otbLineSpatialObjectList.h"
#include "itkLineIterator.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
int otbLineSegmentDetector( int argc, char * argv[] )
{
const char * infname = argv[1];
const char * outfname = argv[2];
typedef double InputPixelType;
const unsigned int Dimension = 2;
/** Typedefs */
typedef otb::Image< InputPixelType, Dimension > InputImageType;
typedef InputImageType::IndexType IndexType;
typedef otb::ImageFileReader<InputImageType> ReaderType;
typedef otb::ImageFileWriter<InputImageType> WriterType;
typedef otb::DrawLineSpatialObjectListFilter< InputImageType ,InputImageType > DrawLineListType;
typedef otb::LineSegmentDetector<InputImageType , InputPixelType> lsdFilterType;
typedef itk::LineIterator<InputImageType> LineIteratorFilter;
/** Instanciation of smart pointer*/
lsdFilterType::Pointer lsdFilter = lsdFilterType::New();
DrawLineListType::Pointer drawLineFilter = DrawLineListType::New();
ReaderType::Pointer reader = ReaderType::New();
/** */
typedef otb::LineSpatialObjectList LinesListType;
typedef LinesListType::LineType LineType;
LinesListType::Pointer list = LinesListType::New();
LineType::PointListType pointList;
LineType::LinePointType pointBegin , pointEnd;
IndexType IndexBegin , IndexEnd;
/***/
reader->SetFileName(infname);
reader->GenerateOutputInformation();
lsdFilter->SetInput(reader->GetOutput());
drawLineFilter->SetInput(reader->GetOutput());
drawLineFilter->SetInputLineSpatialObjectList(lsdFilter->GetOutput());
// LinesListType::const_iterator it = lsdFilter->GetOutput()->begin();
// LinesListType::const_iterator itEnd = lsdFilter->GetOutput()->end();
// while(it != itEnd)
// {
// LineType::PointListType & pointsList = (*it)->GetPoints();
// LineType::PointListType::const_iterator itPoints = pointsList.begin();
// float x = (*itPoints).GetPosition()[0];
// float y = (*itPoints).GetPosition()[1];
// IndexBegin[0] = static_cast<int>(x) ; IndexBegin[1] = static_cast<int>(y);
// itPoints++;
// float x1 = (*itPoints).GetPosition()[0];
// float y1 = (*itPoints).GetPosition()[1];
// IndexEnd[0]= static_cast<int>(x1) ; IndexEnd[1] = static_cast<int>(y1);
// LineIteratorFilter itLine(reader->GetOutput(),IndexBegin, IndexEnd);
// itLine.GoToBegin();
// while(!itLine.IsAtEnd())
// {
// if(reader->GetOutput()->GetRequestedRegion().IsInside(itLine.GetIndex()))
// itLine.Set(255.);
// ++itLine;
// }
// ++it;
// }
/** Write The Output Image*/
WriterType::Pointer writer = WriterType::New();
writer->SetFileName(outfname);
writer->SetInput(drawLineFilter->GetOutput());
writer->Update();
std::cout << " lsdFilter Ouput Size" << lsdFilter->GetOutput()->size() <<std::endl;
return EXIT_SUCCESS;
}
<commit_msg>ENH : correct warnings<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 "otbImage.h"
#include "otbLineSegmentDetector.h"
#include "otbDrawLineSpatialObjectListFilter.h"
#include "otbLineSpatialObjectList.h"
#include "itkLineIterator.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
int otbLineSegmentDetector( int argc, char * argv[] )
{
const char * infname = argv[1];
const char * outfname = argv[2];
typedef double InputPixelType;
const unsigned int Dimension = 2;
/** Typedefs */
typedef otb::Image< InputPixelType, Dimension > InputImageType;
typedef InputImageType::IndexType IndexType;
typedef otb::ImageFileReader<InputImageType> ReaderType;
typedef otb::ImageFileWriter<InputImageType> WriterType;
typedef otb::DrawLineSpatialObjectListFilter< InputImageType ,InputImageType > DrawLineListType;
typedef otb::LineSegmentDetector<InputImageType , InputPixelType> lsdFilterType;
typedef itk::LineIterator<InputImageType> LineIteratorFilter;
/** Instanciation of smart pointer*/
lsdFilterType::Pointer lsdFilter = lsdFilterType::New();
DrawLineListType::Pointer drawLineFilter = DrawLineListType::New();
ReaderType::Pointer reader = ReaderType::New();
/** */
//typedef otb::LineSpatialObjectList LinesListType;
//typedef LinesListType::LineType LineType;
//LinesListType::Pointer list = LinesListType::New();
//LineType::PointListType pointList;
//LineType::LinePointType pointBegin , pointEnd;
// IndexType IndexBegin , IndexEnd;
/***/
reader->SetFileName(infname);
reader->GenerateOutputInformation();
lsdFilter->SetInput(reader->GetOutput());
drawLineFilter->SetInput(reader->GetOutput());
drawLineFilter->SetInputLineSpatialObjectList(lsdFilter->GetOutput());
// LinesListType::const_iterator it = lsdFilter->GetOutput()->begin();
// LinesListType::const_iterator itEnd = lsdFilter->GetOutput()->end();
// while(it != itEnd)
// {
// LineType::PointListType & pointsList = (*it)->GetPoints();
// LineType::PointListType::const_iterator itPoints = pointsList.begin();
// float x = (*itPoints).GetPosition()[0];
// float y = (*itPoints).GetPosition()[1];
// IndexBegin[0] = static_cast<int>(x) ; IndexBegin[1] = static_cast<int>(y);
// itPoints++;
// float x1 = (*itPoints).GetPosition()[0];
// float y1 = (*itPoints).GetPosition()[1];
// IndexEnd[0]= static_cast<int>(x1) ; IndexEnd[1] = static_cast<int>(y1);
// LineIteratorFilter itLine(reader->GetOutput(),IndexBegin, IndexEnd);
// itLine.GoToBegin();
// while(!itLine.IsAtEnd())
// {
// if(reader->GetOutput()->GetRequestedRegion().IsInside(itLine.GetIndex()))
// itLine.Set(255.);
// ++itLine;
// }
// ++it;
// }
/** Write The Output Image*/
WriterType::Pointer writer = WriterType::New();
writer->SetFileName(outfname);
writer->SetInput(drawLineFilter->GetOutput());
writer->Update();
std::cout << " lsdFilter Ouput Size" << lsdFilter->GetOutput()->size() <<std::endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (C) 2010 Kim Jung Nissen <[email protected]>
*
* 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 "gameloop.h"
#include "input/inputdevice.h"
#include "input/keyboard.h"
#include <QtCore/QTime>
#include <QtCore/QDebug>
#include <QtCore/QCoreApplication>
GameLoop::GameLoop(Keyboard *keyb)
{
keyboard = keyb;
connect(this, SIGNAL(startGameLoop()), SLOT(gameLoop()), Qt::QueuedConnection);
}
void GameLoop::run()
{
emit startGameLoop();
}
void GameLoop::gameLoop()
{
int nextTick = 0;
int loops = 0;
int timeLapse = 0;
QTime timer;
int updatesPerSecond = 25;
int maxFrameSkip = 5;
int millisecondsPerUpdate = 1000 / updatesPerSecond;
timer.start();
qDebug() << "starting gameloop";
while (true) {
QCoreApplication::processEvents();
loops = 0;
while (timer.elapsed() > nextTick && loops < maxFrameSkip) {
foreach(int button, keyboard->buttonCapabilities()) {
if(keyboard->buttonPressed(button))
qDebug() << keyboard->buttonName(button) << " is pressed ";
}
nextTick += millisecondsPerUpdate;
++loops;
}
timeLapse = (timer.elapsed() + millisecondsPerUpdate - nextTick) / millisecondsPerUpdate;
}
}
#include "gameloop.moc"
<commit_msg>Delete the unneccesary elapse time variable which maked it slower in the loop.<commit_after>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (C) 2010 Kim Jung Nissen <[email protected]>
*
* 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 "gameloop.h"
#include "input/inputdevice.h"
#include "input/keyboard.h"
#include <QtCore/QTime>
#include <QtCore/QDebug>
#include <QtCore/QCoreApplication>
GameLoop::GameLoop(Keyboard *keyb)
{
keyboard = keyb;
connect(this, SIGNAL(startGameLoop()), SLOT(gameLoop()), Qt::QueuedConnection);
}
void GameLoop::run()
{
emit startGameLoop();
}
void GameLoop::gameLoop()
{
int nextTick = 0;
int loops = 0;
QTime timer;
int updatesPerSecond = 25;
int maxFrameSkip = 5;
int millisecondsPerUpdate = 1000 / updatesPerSecond;
timer.start();
qDebug() << "starting gameloop";
while (true) {
QCoreApplication::processEvents();
loops = 0;
while (timer.elapsed() > nextTick && loops < maxFrameSkip) {
foreach(int button, keyboard->buttonCapabilities()) {
if (keyboard->buttonPressed(button))
qDebug() << keyboard->buttonName(button) << " is pressed ";
}
nextTick += millisecondsPerUpdate;
++loops;
}
}
}
#include "gameloop.moc"
<|endoftext|> |
<commit_before>//---------------------------------------------------------
// Copyright 2019 Ontario Institute for Cancer Research
// Written by Jared Simpson ([email protected])
//---------------------------------------------------------
//
// nanopolish_fast5_loader -- A class that manages
// opening and reading from fast5 files
//
#include <omp.h>
#include "nanopolish_fast5_loader.h"
//
Fast5Loader::Fast5Loader()
{
}
//
Fast5Loader::~Fast5Loader()
{
}
Fast5Data Fast5Loader::load_read(const std::string& filename, const std::string& read_name)
{
Fast5Data data;
data.rt.n = 0;
data.rt.raw = NULL;
fast5_file f5_file = fast5_open(filename);
if(!fast5_is_open(f5_file)) {
data.is_valid = false;
return data;
}
data.read_name = read_name;
data.is_valid = true;
// metadata
data.sequencing_kit = fast5_get_sequencing_kit(f5_file, read_name);
data.experiment_type = fast5_get_experiment_type(f5_file, read_name);
// raw data
data.channel_params = fast5_get_channel_params(f5_file, read_name);
data.rt = fast5_get_raw_samples(f5_file, read_name, data.channel_params);
data.start_time = fast5_get_start_time(f5_file, read_name);
fast5_close(f5_file);
return data;
}
Fast5Data Fast5Loader::load_read(slow5_file_t *slow5_file, const std::string &read_name)
{
Fast5Data data;
slow5_rec_t *rec = NULL;
int ret = slow5_get(read_name.c_str(), &rec, slow5_file);
if(ret < 0){
fprintf(stderr,"Error in when fetching the read\n");
exit(EXIT_FAILURE);
}
data.rt.n = rec->len_raw_signal;
data.channel_params.range = rec->range;
data.channel_params.offset = rec->offset;
data.channel_params.digitisation = rec->digitisation;
data.channel_params.sample_rate = rec->sampling_rate;
int err;
char *cid = slow5_aux_get_string(rec, "channel_number", NULL, &err);
if(err < 0){
fprintf(stderr,"[warning] Error in when fetching the channel_number\n");
}else{
data.channel_params.channel_id = atoi(cid);
}
data.start_time = slow5_aux_get_uint64(rec, "start_time", &err);
if(err < 0){
fprintf(stderr,"[warning] Error in when fetching the start_time\n");
}
data.read_name = read_name;
// metadata
char* sequencing_kit = slow5_hdr_get("sequencing_kit", 0, slow5_file->header);
data.sequencing_kit = (sequencing_kit)?std::string(sequencing_kit):"";
char* experiment_type = slow5_hdr_get("experiment_type", 0, slow5_file->header);
data.experiment_type = (experiment_type)?std::string(experiment_type):"";
// raw data
// convert to pA
float* rawptr = (float*)calloc(rec->len_raw_signal, sizeof(float));
raw_table rawtbl = { 0, 0, 0, NULL };
data.rt = (raw_table) { rec->len_raw_signal, 0, rec->len_raw_signal, rawptr };
hsize_t nsample = rec->len_raw_signal;
float digitisation = rec->digitisation;
float offset = rec->offset;
float range = rec->range;
float raw_unit = range / digitisation;
for (size_t i = 0; i < nsample; i++) {
float signal = rec->raw_signal[i];
rawptr[i] = (signal + offset) * raw_unit;
}
slow5_rec_free(rec);
data.is_valid = true;
return data;
}
<commit_msg>return instead of exiting if the read is not found in the slow5 file<commit_after>//---------------------------------------------------------
// Copyright 2019 Ontario Institute for Cancer Research
// Written by Jared Simpson ([email protected])
//---------------------------------------------------------
//
// nanopolish_fast5_loader -- A class that manages
// opening and reading from fast5 files
//
#include <omp.h>
#include "nanopolish_fast5_loader.h"
//
Fast5Loader::Fast5Loader()
{
}
//
Fast5Loader::~Fast5Loader()
{
}
Fast5Data Fast5Loader::load_read(const std::string& filename, const std::string& read_name)
{
Fast5Data data;
data.rt.n = 0;
data.rt.raw = NULL;
fast5_file f5_file = fast5_open(filename);
if(!fast5_is_open(f5_file)) {
data.is_valid = false;
return data;
}
data.read_name = read_name;
data.is_valid = true;
// metadata
data.sequencing_kit = fast5_get_sequencing_kit(f5_file, read_name);
data.experiment_type = fast5_get_experiment_type(f5_file, read_name);
// raw data
data.channel_params = fast5_get_channel_params(f5_file, read_name);
data.rt = fast5_get_raw_samples(f5_file, read_name, data.channel_params);
data.start_time = fast5_get_start_time(f5_file, read_name);
fast5_close(f5_file);
return data;
}
Fast5Data Fast5Loader::load_read(slow5_file_t *slow5_file, const std::string &read_name)
{
Fast5Data data;
data.rt.n = 0;
data.rt.raw = NULL;
slow5_rec_t *rec = NULL;
int ret = slow5_get(read_name.c_str(), &rec, slow5_file);
if(ret < 0){
fprintf(stderr,"Error in when fetching the read\n");
data.is_valid = false;
return data;
}
data.rt.n = rec->len_raw_signal;
data.channel_params.range = rec->range;
data.channel_params.offset = rec->offset;
data.channel_params.digitisation = rec->digitisation;
data.channel_params.sample_rate = rec->sampling_rate;
int err;
char *cid = slow5_aux_get_string(rec, "channel_number", NULL, &err);
if(err < 0){
fprintf(stderr,"[warning] Error in when fetching the channel_number\n");
}else{
data.channel_params.channel_id = atoi(cid);
}
data.start_time = slow5_aux_get_uint64(rec, "start_time", &err);
if(err < 0){
fprintf(stderr,"[warning] Error in when fetching the start_time\n");
}
data.read_name = read_name;
// metadata
char* sequencing_kit = slow5_hdr_get("sequencing_kit", 0, slow5_file->header);
data.sequencing_kit = (sequencing_kit)?std::string(sequencing_kit):"";
char* experiment_type = slow5_hdr_get("experiment_type", 0, slow5_file->header);
data.experiment_type = (experiment_type)?std::string(experiment_type):"";
// raw data
// convert to pA
float* rawptr = (float*)calloc(rec->len_raw_signal, sizeof(float));
raw_table rawtbl = { 0, 0, 0, NULL };
data.rt = (raw_table) { rec->len_raw_signal, 0, rec->len_raw_signal, rawptr };
hsize_t nsample = rec->len_raw_signal;
float digitisation = rec->digitisation;
float offset = rec->offset;
float range = rec->range;
float raw_unit = range / digitisation;
for (size_t i = 0; i < nsample; i++) {
float signal = rec->raw_signal[i];
rawptr[i] = (signal + offset) * raw_unit;
}
slow5_rec_free(rec);
data.is_valid = true;
return data;
}
<|endoftext|> |
<commit_before>// Copyright 2016 The SwiftShader Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef sw_Types_hpp
#define sw_Types_hpp
#include <limits>
#include <type_traits>
// GCC warns against bitfields not fitting the entire range of an enum with a fixed underlying type of unsigned int, which gets promoted to an error with -Werror and cannot be suppressed.
// However, GCC already defaults to using unsigned int as the underlying type of an unscoped enum without a fixed underlying type. So we can just omit it.
#if defined(__GNUC__) && !defined(__clang__)
namespace {
enum E
{
};
static_assert(!std::numeric_limits<std::underlying_type<E>::type>::is_signed, "expected unscoped enum whose underlying type is not fixed to be unsigned");
} // namespace
# define ENUM_UNDERLYING_TYPE_UNSIGNED_INT
#else
# define ENUM_UNDERLYING_TYPE_UNSIGNED_INT : unsigned int
#endif
#if defined(_MSC_VER)
typedef signed __int8 int8_t;
typedef signed __int16 int16_t;
typedef signed __int32 int32_t;
typedef signed __int64 int64_t;
typedef unsigned __int8 uint8_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t;
# define ALIGN(bytes, type) __declspec(align(bytes)) type
#else
# include <stdint.h>
# define ALIGN(bytes, type) type __attribute__((aligned(bytes)))
#endif
namespace sw {
typedef ALIGN(1, uint8_t) byte;
typedef ALIGN(2, uint16_t) word;
typedef ALIGN(4, uint32_t) dword;
typedef ALIGN(8, uint64_t) qword;
typedef ALIGN(1, int8_t) sbyte;
template<typename T, int N>
struct alignas(sizeof(T) * N) vec
{
vec() = default;
constexpr explicit vec(T replicate)
{
for(int i = 0; i < N; i++)
{
v[i] = replicate;
}
}
template<typename... ARGS>
constexpr vec(T arg0, ARGS... args)
: v{ arg0, args... }
{
}
// Require explicit use of replicate constructor.
vec &operator=(T) = delete;
T &operator[](int i)
{
return v[i];
}
const T &operator[](int i) const
{
return v[i];
}
T v[N];
};
template<typename T>
struct alignas(sizeof(T) * 4) vec<T, 4>
{
vec() = default;
constexpr explicit vec(T replicate)
: x(replicate)
, y(replicate)
, z(replicate)
, w(replicate)
{
}
constexpr vec(T x, T y, T z, T w)
: x(x)
, y(y)
, z(z)
, w(w)
{
}
// Require explicit use of replicate constructor.
vec &operator=(T) = delete;
T &operator[](int i)
{
return v[i];
}
const T &operator[](int i) const
{
return v[i];
}
union
{
T v[4];
struct
{
T x;
T y;
T z;
T w;
};
};
};
template<typename T, int N>
bool operator==(const vec<T, N> &a, const vec<T, N> &b)
{
for(int i = 0; i < N; i++)
{
if(a.v[i] != b.v[i])
{
return false;
}
}
return true;
}
template<typename T, int N>
bool operator!=(const vec<T, N> &a, const vec<T, N> &b)
{
return !(a == b);
}
template<typename T>
using vec2 = vec<T, 2>;
template<typename T>
using vec4 = vec<T, 4>;
template<typename T>
using vec8 = vec<T, 8>;
template<typename T>
using vec16 = vec<T, 16>;
using int2 = vec2<int>;
using uint2 = vec2<unsigned int>;
using float2 = vec2<float>;
using dword2 = vec2<dword>;
using qword2 = vec2<qword>;
using int4 = vec4<int>;
using uint4 = vec4<unsigned int>;
using float4 = vec4<float>;
using byte4 = vec4<byte>;
using sbyte4 = vec4<sbyte>;
using short4 = vec4<short>;
using ushort4 = vec4<unsigned short>;
using word4 = vec4<word>;
using dword4 = vec4<dword>;
using byte8 = vec8<byte>;
using sbyte8 = vec8<sbyte>;
using short8 = vec8<short>;
using ushort8 = vec8<unsigned short>;
using byte16 = vec16<byte>;
using sbyte16 = vec16<sbyte>;
inline constexpr float4 vector(float x, float y, float z, float w)
{
return float4{ x, y, z, w };
}
inline constexpr float4 replicate(float f)
{
return vector(f, f, f, f);
}
#define OFFSET(s, m) (int)(size_t) & reinterpret_cast<const volatile char &>((((s *)0)->m))
} // namespace sw
#endif // sw_Types_hpp
<commit_msg>Fix null dereference in OFFSET macro<commit_after>// Copyright 2016 The SwiftShader Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef sw_Types_hpp
#define sw_Types_hpp
#include <limits>
#include <type_traits>
// GCC warns against bitfields not fitting the entire range of an enum with a fixed underlying type of unsigned int, which gets promoted to an error with -Werror and cannot be suppressed.
// However, GCC already defaults to using unsigned int as the underlying type of an unscoped enum without a fixed underlying type. So we can just omit it.
#if defined(__GNUC__) && !defined(__clang__)
namespace {
enum E
{
};
static_assert(!std::numeric_limits<std::underlying_type<E>::type>::is_signed, "expected unscoped enum whose underlying type is not fixed to be unsigned");
} // namespace
# define ENUM_UNDERLYING_TYPE_UNSIGNED_INT
#else
# define ENUM_UNDERLYING_TYPE_UNSIGNED_INT : unsigned int
#endif
#if defined(_MSC_VER)
typedef signed __int8 int8_t;
typedef signed __int16 int16_t;
typedef signed __int32 int32_t;
typedef signed __int64 int64_t;
typedef unsigned __int8 uint8_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t;
# define ALIGN(bytes, type) __declspec(align(bytes)) type
#else
# include <stdint.h>
# define ALIGN(bytes, type) type __attribute__((aligned(bytes)))
#endif
namespace sw {
typedef ALIGN(1, uint8_t) byte;
typedef ALIGN(2, uint16_t) word;
typedef ALIGN(4, uint32_t) dword;
typedef ALIGN(8, uint64_t) qword;
typedef ALIGN(1, int8_t) sbyte;
template<typename T, int N>
struct alignas(sizeof(T) * N) vec
{
vec() = default;
constexpr explicit vec(T replicate)
{
for(int i = 0; i < N; i++)
{
v[i] = replicate;
}
}
template<typename... ARGS>
constexpr vec(T arg0, ARGS... args)
: v{ arg0, args... }
{
}
// Require explicit use of replicate constructor.
vec &operator=(T) = delete;
T &operator[](int i)
{
return v[i];
}
const T &operator[](int i) const
{
return v[i];
}
T v[N];
};
template<typename T>
struct alignas(sizeof(T) * 4) vec<T, 4>
{
vec() = default;
constexpr explicit vec(T replicate)
: x(replicate)
, y(replicate)
, z(replicate)
, w(replicate)
{
}
constexpr vec(T x, T y, T z, T w)
: x(x)
, y(y)
, z(z)
, w(w)
{
}
// Require explicit use of replicate constructor.
vec &operator=(T) = delete;
T &operator[](int i)
{
return v[i];
}
const T &operator[](int i) const
{
return v[i];
}
union
{
T v[4];
struct
{
T x;
T y;
T z;
T w;
};
};
};
template<typename T, int N>
bool operator==(const vec<T, N> &a, const vec<T, N> &b)
{
for(int i = 0; i < N; i++)
{
if(a.v[i] != b.v[i])
{
return false;
}
}
return true;
}
template<typename T, int N>
bool operator!=(const vec<T, N> &a, const vec<T, N> &b)
{
return !(a == b);
}
template<typename T>
using vec2 = vec<T, 2>;
template<typename T>
using vec4 = vec<T, 4>;
template<typename T>
using vec8 = vec<T, 8>;
template<typename T>
using vec16 = vec<T, 16>;
using int2 = vec2<int>;
using uint2 = vec2<unsigned int>;
using float2 = vec2<float>;
using dword2 = vec2<dword>;
using qword2 = vec2<qword>;
using int4 = vec4<int>;
using uint4 = vec4<unsigned int>;
using float4 = vec4<float>;
using byte4 = vec4<byte>;
using sbyte4 = vec4<sbyte>;
using short4 = vec4<short>;
using ushort4 = vec4<unsigned short>;
using word4 = vec4<word>;
using dword4 = vec4<dword>;
using byte8 = vec8<byte>;
using sbyte8 = vec8<sbyte>;
using short8 = vec8<short>;
using ushort8 = vec8<unsigned short>;
using byte16 = vec16<byte>;
using sbyte16 = vec16<sbyte>;
inline constexpr float4 vector(float x, float y, float z, float w)
{
return float4{ x, y, z, w };
}
inline constexpr float4 replicate(float f)
{
return vector(f, f, f, f);
}
// The OFFSET macro is a generalization of the offsetof() macro defined in <cstddef>.
// It allows e.g. getting the offset of array elements, even when indexed dynamically.
// We cast the address '32' and subtract it again, because null-dereference is undefined behavior.
#define OFFSET(s, m) ((int)(size_t) & reinterpret_cast<const volatile char &>((((s *)32)->m)) - 32)
} // namespace sw
#endif // sw_Types_hpp
<|endoftext|> |
<commit_before>#include "Players/Genetic_AI.h"
#include <iostream>
#include <fstream>
#include <array>
#include <string>
#include <cmath>
#include "Game/Color.h"
#include "Utility/String.h"
#include "Utility/Exceptions.h"
class Board;
class Clock;
int Genetic_AI::next_id = 0;
Genetic_AI::Genetic_AI() noexcept : id_number(next_id++)
{
}
Genetic_AI::Genetic_AI(const Genetic_AI& A, const Genetic_AI& B) noexcept :
genome(A.genome, B.genome),
id_number(next_id++)
{
recalibrate_self();
}
Genetic_AI::Genetic_AI(const std::string& file_name, int id_in) try : Genetic_AI(std::ifstream(file_name), id_in)
{
}
catch(const Genetic_AI_Creation_Error& e)
{
throw Genetic_AI_Creation_Error(e.what() + file_name);
}
Genetic_AI::Genetic_AI(std::istream& is, int id_in) : id_number(id_in)
{
read_from(is);
}
Genetic_AI::Genetic_AI(std::istream&& is, int id_in) : id_number(id_in)
{
read_from(is);
}
void Genetic_AI::read_from(std::istream& is)
{
if( ! is)
{
throw Genetic_AI_Creation_Error("Could not read: ");
}
for(std::string line; std::getline(is, line);)
{
line = String::strip_comments(line, "#");
if( ! String::starts_with(line, "ID"))
{
continue;
}
auto param_value = String::split(line, ":", 1);
if(param_value.size() != 2 || String::trim_outer_whitespace(param_value[0]) != "ID")
{
continue;
}
if(id_number == String::to_number<int>(param_value[1]))
{
read_data(is);
return;
}
}
throw Genetic_AI_Creation_Error("Could not locate ID " + std::to_string(id_number) + " inside file ");
}
void Genetic_AI::read_data(std::istream& is)
{
try
{
genome.read_from(is);
recalibrate_self();
next_id = std::max(next_id, id() + 1);
}
catch(const Genetic_AI_Creation_Error& e)
{
throw Genetic_AI_Creation_Error("Error in creating Genetic AI #" + std::to_string(id()) + "\n" + e.what() + "\nFile: ");
}
}
double Genetic_AI::internal_evaluate(const Board& board, Piece_Color perspective, size_t depth) const noexcept
{
return genome.evaluate(board, perspective, depth);
}
const std::array<double, 6>& Genetic_AI::piece_values() const noexcept
{
return genome.piece_values();
}
Clock::seconds Genetic_AI::time_to_examine(const Board& board, const Clock& clock) const noexcept
{
return genome.time_to_examine(board, clock);
}
double Genetic_AI::speculation_time_factor(double game_progress) const noexcept
{
return genome.speculation_time_factor(game_progress);
}
double Genetic_AI::branching_factor(double game_progress) const noexcept
{
return genome.branching_factor(game_progress);
}
double Genetic_AI::game_progress(const Board& board) const noexcept
{
return genome.game_progress(board);
}
void Genetic_AI::mutate(size_t mutation_count) noexcept
{
for(size_t i = 0; i < mutation_count; ++i)
{
genome.mutate();
}
recalibrate_self();
}
void Genetic_AI::print(const std::string& file_name) const noexcept
{
if(file_name.empty())
{
print(std::cout);
}
else
{
auto dest = std::ofstream(file_name, std::ofstream::app);
print(dest);
}
}
void Genetic_AI::print(std::ostream& os) const noexcept
{
os << "ID: " << id() << '\n';
genome.print(os);
os << "END\n" << std::endl;
}
std::string Genetic_AI::name() const noexcept
{
return "Genetic AI " + std::to_string(id());
}
std::string Genetic_AI::author() const noexcept
{
return "Mark Harrison";
}
int Genetic_AI::id() const noexcept
{
return id_number;
}
bool Genetic_AI::operator<(const Genetic_AI& other) const noexcept
{
return id() < other.id();
}
int find_last_id(const std::string& players_file_name)
{
std::ifstream player_input(players_file_name);
if( ! player_input)
{
throw std::invalid_argument("File not found: " + players_file_name);
}
std::string last_player;
for(std::string line; std::getline(player_input, line);)
{
if(String::starts_with(line, "ID:"))
{
last_player = line;
}
}
if(last_player.empty())
{
throw std::runtime_error("No valid ID found in file: " + players_file_name);
}
auto split = String::split(last_player, ":", 1);
if(split.size() != 2)
{
throw std::runtime_error("Invalid ID line: " + last_player);
}
try
{
return String::to_number<int>(split.back());
}
catch(const std::exception&)
{
throw std::runtime_error("Could not convert to ID number: " + last_player);
}
}
<commit_msg>Calibrate Genetic_AI in default ctor<commit_after>#include "Players/Genetic_AI.h"
#include <iostream>
#include <fstream>
#include <array>
#include <string>
#include <cmath>
#include "Game/Color.h"
#include "Utility/String.h"
#include "Utility/Exceptions.h"
class Board;
class Clock;
int Genetic_AI::next_id = 0;
Genetic_AI::Genetic_AI() noexcept : id_number(next_id++)
{
recalibrate_self();
}
Genetic_AI::Genetic_AI(const Genetic_AI& A, const Genetic_AI& B) noexcept :
genome(A.genome, B.genome),
id_number(next_id++)
{
recalibrate_self();
}
Genetic_AI::Genetic_AI(const std::string& file_name, int id_in) try : Genetic_AI(std::ifstream(file_name), id_in)
{
}
catch(const Genetic_AI_Creation_Error& e)
{
throw Genetic_AI_Creation_Error(e.what() + file_name);
}
Genetic_AI::Genetic_AI(std::istream& is, int id_in) : id_number(id_in)
{
read_from(is);
}
Genetic_AI::Genetic_AI(std::istream&& is, int id_in) : id_number(id_in)
{
read_from(is);
}
void Genetic_AI::read_from(std::istream& is)
{
if( ! is)
{
throw Genetic_AI_Creation_Error("Could not read: ");
}
for(std::string line; std::getline(is, line);)
{
line = String::strip_comments(line, "#");
if( ! String::starts_with(line, "ID"))
{
continue;
}
auto param_value = String::split(line, ":", 1);
if(param_value.size() != 2 || String::trim_outer_whitespace(param_value[0]) != "ID")
{
continue;
}
if(id_number == String::to_number<int>(param_value[1]))
{
read_data(is);
return;
}
}
throw Genetic_AI_Creation_Error("Could not locate ID " + std::to_string(id_number) + " inside file ");
}
void Genetic_AI::read_data(std::istream& is)
{
try
{
genome.read_from(is);
recalibrate_self();
next_id = std::max(next_id, id() + 1);
}
catch(const Genetic_AI_Creation_Error& e)
{
throw Genetic_AI_Creation_Error("Error in creating Genetic AI #" + std::to_string(id()) + "\n" + e.what() + "\nFile: ");
}
}
double Genetic_AI::internal_evaluate(const Board& board, Piece_Color perspective, size_t depth) const noexcept
{
return genome.evaluate(board, perspective, depth);
}
const std::array<double, 6>& Genetic_AI::piece_values() const noexcept
{
return genome.piece_values();
}
Clock::seconds Genetic_AI::time_to_examine(const Board& board, const Clock& clock) const noexcept
{
return genome.time_to_examine(board, clock);
}
double Genetic_AI::speculation_time_factor(double game_progress) const noexcept
{
return genome.speculation_time_factor(game_progress);
}
double Genetic_AI::branching_factor(double game_progress) const noexcept
{
return genome.branching_factor(game_progress);
}
double Genetic_AI::game_progress(const Board& board) const noexcept
{
return genome.game_progress(board);
}
void Genetic_AI::mutate(size_t mutation_count) noexcept
{
for(size_t i = 0; i < mutation_count; ++i)
{
genome.mutate();
}
recalibrate_self();
}
void Genetic_AI::print(const std::string& file_name) const noexcept
{
if(file_name.empty())
{
print(std::cout);
}
else
{
auto dest = std::ofstream(file_name, std::ofstream::app);
print(dest);
}
}
void Genetic_AI::print(std::ostream& os) const noexcept
{
os << "ID: " << id() << '\n';
genome.print(os);
os << "END\n" << std::endl;
}
std::string Genetic_AI::name() const noexcept
{
return "Genetic AI " + std::to_string(id());
}
std::string Genetic_AI::author() const noexcept
{
return "Mark Harrison";
}
int Genetic_AI::id() const noexcept
{
return id_number;
}
bool Genetic_AI::operator<(const Genetic_AI& other) const noexcept
{
return id() < other.id();
}
int find_last_id(const std::string& players_file_name)
{
std::ifstream player_input(players_file_name);
if( ! player_input)
{
throw std::invalid_argument("File not found: " + players_file_name);
}
std::string last_player;
for(std::string line; std::getline(player_input, line);)
{
if(String::starts_with(line, "ID:"))
{
last_player = line;
}
}
if(last_player.empty())
{
throw std::runtime_error("No valid ID found in file: " + players_file_name);
}
auto split = String::split(last_player, ":", 1);
if(split.size() != 2)
{
throw std::runtime_error("Invalid ID line: " + last_player);
}
try
{
return String::to_number<int>(split.back());
}
catch(const std::exception&)
{
throw std::runtime_error("Could not convert to ID number: " + last_player);
}
}
<|endoftext|> |
<commit_before>/////////////////////////////////////////////////////////////////////////
// $Id: unmapped.cc,v 1.25 2008/01/26 22:24:02 sshwarts Exp $
/////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2001 MandrakeSoft S.A.
//
// MandrakeSoft S.A.
// 43, rue d'Aboukir
// 75002 Paris - France
// http://www.linux-mandrake.com/
// http://www.mandrakesoft.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 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
// Define BX_PLUGGABLE in files that can be compiled into plugins. For
// platforms that require a special tag on exported symbols, BX_PLUGGABLE
// is used to know when we are exporting symbols and when we are importing.
#define BX_PLUGGABLE
#include "iodev.h"
#define LOG_THIS theUnmappedDevice->
bx_unmapped_c *theUnmappedDevice = NULL;
int libunmapped_LTX_plugin_init(plugin_t *plugin, plugintype_t type, int argc, char *argv[])
{
theUnmappedDevice = new bx_unmapped_c();
bx_devices.pluginUnmapped = theUnmappedDevice;
BX_REGISTER_DEVICE_DEVMODEL(plugin, type, theUnmappedDevice, BX_PLUGIN_UNMAPPED);
return(0); // Success
}
void libunmapped_LTX_plugin_fini(void)
{
delete theUnmappedDevice;
}
bx_unmapped_c::bx_unmapped_c(void)
{
put("UNMP");
settype(UNMAPLOG);
}
bx_unmapped_c::~bx_unmapped_c(void)
{
BX_DEBUG(("Exit"));
}
void bx_unmapped_c::init(void)
{
DEV_register_default_ioread_handler(this, read_handler, "Unmapped", 7);
DEV_register_default_iowrite_handler(this, write_handler, "Unmapped", 7);
s.port80 = 0x00;
s.port8e = 0x00;
s.shutdown = 0;
}
// static IO port read callback handler
// redirects to non-static class handler to avoid virtual functions
Bit32u bx_unmapped_c::read_handler(void *this_ptr, Bit32u address, unsigned io_len)
{
#if !BX_USE_UM_SMF
bx_unmapped_c *class_ptr = (bx_unmapped_c *) this_ptr;
return( class_ptr->read(address, io_len) );
}
Bit32u bx_unmapped_c::read(Bit32u address, unsigned io_len)
{
#else
UNUSED(this_ptr);
#endif // !BX_USE_UM_SMF
UNUSED(io_len);
Bit32u retval;
// This function gets called for access to any IO ports which
// are not mapped to any device handler. Reads return 0
if (address >= 0x02e0 && address <= 0x02ef) {
retval = 0;
goto return_from_read;
}
switch (address) {
case 0x80:
retval = BX_UM_THIS s.port80;
break;
case 0x8e:
retval = BX_UM_THIS s.port8e;
break;
#if BX_PORT_E9_HACK
// Unused port on ISA - this can be used by the emulated code
// to detect it is running inside Bochs and that the debugging
// features are available (write 0xFF or something on unused
// port 0x80, then read from 0xe9, if value is 0xe9, debug
// output is available) (see write() for that) -- Andreas and Emmanuel
case 0xe9:
retval = 0xe9;
break;
#endif
case 0x03df:
retval = 0xffffffff;
BX_DEBUG(("unsupported IO read from port %04x (CGA)", address));
break;
case 0x023a:
case 0x02f8: /* UART */
case 0x02f9: /* UART */
case 0x02fb: /* UART */
case 0x02fc: /* UART */
case 0x02fd: /* UART */
case 0x02ea:
case 0x02eb:
case 0x03e8:
case 0x03e9:
case 0x03ea:
case 0x03eb:
case 0x03ec:
case 0x03ed:
case 0x03f8: /* UART */
case 0x03f9: /* UART */
case 0x03fb: /* UART */
case 0x03fc: /* UART */
case 0x03fd: /* UART */
case 0x17c6:
retval = 0xffffffff;
BX_DEBUG(("unsupported IO read from port %04x", address));
break;
default:
retval = 0xffffffff;
}
return_from_read:
if (bx_dbg.unsupported_io)
switch (io_len) {
case 1:
retval = (Bit8u)retval;
BX_DEBUG(("unmapped: 8-bit read from %04x = %02x", address, retval));
break;
case 2:
retval = (Bit16u)retval;
BX_DEBUG(("unmapped: 16-bit read from %04x = %04x", address, retval));
break;
case 4:
BX_DEBUG(("unmapped: 32-bit read from %04x = %08x", address, retval));
break;
default:
BX_DEBUG(("unmapped: %d-bit read from %04x = %x", io_len * 8, address, retval));
}
return retval;
}
// static IO port write callback handler
// redirects to non-static class handler to avoid virtual functions
void bx_unmapped_c::write_handler(void *this_ptr, Bit32u address, Bit32u value, unsigned io_len)
{
#if !BX_USE_UM_SMF
bx_unmapped_c *class_ptr = (bx_unmapped_c *) this_ptr;
class_ptr->write(address, value, io_len);
}
void bx_unmapped_c::write(Bit32u address, Bit32u value, unsigned io_len)
{
#else
UNUSED(this_ptr);
#endif // !BX_USE_UM_SMF
UNUSED(io_len);
// This function gets called for access to any IO ports which
// are not mapped to any device handler. Writes to an unmapped
// IO port are ignored.
// ???
if (address >= 0x02e0 && address <= 0x02ef)
goto return_from_write;
switch (address) {
case 0x80: // diagnostic test port to display progress of POST
//BX_DEBUG(("Diagnostic port 80h: write = %02xh", (unsigned) value));
BX_UM_THIS s.port80 = value;
break;
case 0x8e: // ???
BX_UM_THIS s.port8e = value;
break;
#if BX_PORT_E9_HACK
// This port doesn't exist on normal ISA architecture. However,
// we define a convention here, to display on the console of the
// system running Bochs, anything that is written to it. The
// idea is to provide debug output very early when writing
// BIOS or OS code for example, without having to bother with
// properly setting up a serial port or anything.
//
// Idea by Andreas Beck ([email protected])
case 0xe9:
putchar(value);
fflush(stdout);
break;
#endif
case 0xed: // Dummy port used as I/O delay
break;
case 0xee: // ???
break;
case 0x2f2:
case 0x2f3:
case 0x2f4:
case 0x2f5:
case 0x2f6:
case 0x2f7:
case 0x3e8:
case 0x3e9:
case 0x3eb:
case 0x3ec:
case 0x3ed:
// BX_DEBUG(("unsupported IO write to port %04x of %02x",
// address, value));
break;
case 0x8900: // Shutdown port, could be moved in a PM device
// or a host <-> guest communication device
switch (value) {
case 'S': if (BX_UM_THIS s.shutdown == 0) BX_UM_THIS s.shutdown = 1; break;
case 'h': if (BX_UM_THIS s.shutdown == 1) BX_UM_THIS s.shutdown = 2; break;
case 'u': if (BX_UM_THIS s.shutdown == 2) BX_UM_THIS s.shutdown = 3; break;
case 't': if (BX_UM_THIS s.shutdown == 3) BX_UM_THIS s.shutdown = 4; break;
case 'd': if (BX_UM_THIS s.shutdown == 4) BX_UM_THIS s.shutdown = 5; break;
case 'o': if (BX_UM_THIS s.shutdown == 5) BX_UM_THIS s.shutdown = 6; break;
case 'w': if (BX_UM_THIS s.shutdown == 6) BX_UM_THIS s.shutdown = 7; break;
case 'n': if (BX_UM_THIS s.shutdown == 7) BX_UM_THIS s.shutdown = 8; break;
#if BX_DEBUGGER
// Very handy for debugging:
// output 'D' to port 8900, and bochs quits to debugger
case 'D': bx_debug_break (); break;
#endif
default : BX_UM_THIS s.shutdown = 0; break;
}
if (BX_UM_THIS s.shutdown == 8) {
bx_user_quit = 1;
LOG_THIS setonoff(LOGLEV_PANIC, ACT_FATAL);
BX_PANIC(("Shutdown port: shutdown requested"));
}
break;
case 0xfedc:
bx_dbg.debugger = (value > 0);
BX_DEBUG(( "DEBUGGER = %u", (unsigned) bx_dbg.debugger));
break;
default:
break;
}
return_from_write:
if (bx_dbg.unsupported_io)
switch (io_len) {
case 1:
BX_INFO(("unmapped: 8-bit write to %04x = %02x", address, value));
break;
case 2:
BX_INFO(("unmapped: 16-bit write to %04x = %04x", address, value));
break;
case 4:
BX_INFO(("unmapped: 32-bit write to %04x = %08x", address, value));
break;
default:
BX_INFO(("unmapped: %d-bit write to %04x = %x", io_len * 8, address, value));
break;
}
}
<commit_msg>tab2space in unmapped.cc<commit_after>/////////////////////////////////////////////////////////////////////////
// $Id: unmapped.cc,v 1.26 2008/01/29 17:34:52 sshwarts Exp $
/////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2001 MandrakeSoft S.A.
//
// MandrakeSoft S.A.
// 43, rue d'Aboukir
// 75002 Paris - France
// http://www.linux-mandrake.com/
// http://www.mandrakesoft.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 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
/////////////////////////////////////////////////////////////////////////
// Define BX_PLUGGABLE in files that can be compiled into plugins. For
// platforms that require a special tag on exported symbols, BX_PLUGGABLE
// is used to know when we are exporting symbols and when we are importing.
#define BX_PLUGGABLE
#include "iodev.h"
#define LOG_THIS theUnmappedDevice->
bx_unmapped_c *theUnmappedDevice = NULL;
int libunmapped_LTX_plugin_init(plugin_t *plugin, plugintype_t type, int argc, char *argv[])
{
theUnmappedDevice = new bx_unmapped_c();
bx_devices.pluginUnmapped = theUnmappedDevice;
BX_REGISTER_DEVICE_DEVMODEL(plugin, type, theUnmappedDevice, BX_PLUGIN_UNMAPPED);
return(0); // Success
}
void libunmapped_LTX_plugin_fini(void)
{
delete theUnmappedDevice;
}
bx_unmapped_c::bx_unmapped_c(void)
{
put("UNMP");
settype(UNMAPLOG);
}
bx_unmapped_c::~bx_unmapped_c(void)
{
BX_DEBUG(("Exit"));
}
void bx_unmapped_c::init(void)
{
DEV_register_default_ioread_handler(this, read_handler, "Unmapped", 7);
DEV_register_default_iowrite_handler(this, write_handler, "Unmapped", 7);
s.port80 = 0x00;
s.port8e = 0x00;
s.shutdown = 0;
}
// static IO port read callback handler
// redirects to non-static class handler to avoid virtual functions
Bit32u bx_unmapped_c::read_handler(void *this_ptr, Bit32u address, unsigned io_len)
{
#if !BX_USE_UM_SMF
bx_unmapped_c *class_ptr = (bx_unmapped_c *) this_ptr;
return class_ptr->read(address, io_len);
}
Bit32u bx_unmapped_c::read(Bit32u address, unsigned io_len)
{
#else
UNUSED(this_ptr);
#endif // !BX_USE_UM_SMF
UNUSED(io_len);
Bit32u retval;
// This function gets called for access to any IO ports which
// are not mapped to any device handler. Reads return 0
if (address >= 0x02e0 && address <= 0x02ef) {
retval = 0;
goto return_from_read;
}
switch (address) {
case 0x80:
retval = BX_UM_THIS s.port80;
break;
case 0x8e:
retval = BX_UM_THIS s.port8e;
break;
#if BX_PORT_E9_HACK
// Unused port on ISA - this can be used by the emulated code
// to detect it is running inside Bochs and that the debugging
// features are available (write 0xFF or something on unused
// port 0x80, then read from 0xe9, if value is 0xe9, debug
// output is available) (see write() for that) -- Andreas and Emmanuel
case 0xe9:
retval = 0xe9;
break;
#endif
case 0x03df:
retval = 0xffffffff;
BX_DEBUG(("unsupported IO read from port %04x (CGA)", address));
break;
case 0x023a:
case 0x02f8: /* UART */
case 0x02f9: /* UART */
case 0x02fb: /* UART */
case 0x02fc: /* UART */
case 0x02fd: /* UART */
case 0x02ea:
case 0x02eb:
case 0x03e8:
case 0x03e9:
case 0x03ea:
case 0x03eb:
case 0x03ec:
case 0x03ed:
case 0x03f8: /* UART */
case 0x03f9: /* UART */
case 0x03fb: /* UART */
case 0x03fc: /* UART */
case 0x03fd: /* UART */
case 0x17c6:
retval = 0xffffffff;
BX_DEBUG(("unsupported IO read from port %04x", address));
break;
default:
retval = 0xffffffff;
}
return_from_read:
if (bx_dbg.unsupported_io) {
switch (io_len) {
case 1:
retval = (Bit8u)retval;
BX_DEBUG(("unmapped: 8-bit read from %04x = %02x", address, retval));
break;
case 2:
retval = (Bit16u)retval;
BX_DEBUG(("unmapped: 16-bit read from %04x = %04x", address, retval));
break;
case 4:
BX_DEBUG(("unmapped: 32-bit read from %04x = %08x", address, retval));
break;
default:
BX_DEBUG(("unmapped: %d-bit read from %04x = %x", io_len * 8, address, retval));
}
}
return retval;
}
// static IO port write callback handler
// redirects to non-static class handler to avoid virtual functions
void bx_unmapped_c::write_handler(void *this_ptr, Bit32u address, Bit32u value, unsigned io_len)
{
#if !BX_USE_UM_SMF
bx_unmapped_c *class_ptr = (bx_unmapped_c *) this_ptr;
class_ptr->write(address, value, io_len);
}
void bx_unmapped_c::write(Bit32u address, Bit32u value, unsigned io_len)
{
#else
UNUSED(this_ptr);
#endif // !BX_USE_UM_SMF
UNUSED(io_len);
// This function gets called for access to any IO ports which
// are not mapped to any device handler. Writes to an unmapped
// IO port are ignored.
if (address >= 0x02e0 && address <= 0x02ef)
goto return_from_write;
switch (address) {
case 0x80: // diagnostic test port to display progress of POST
//BX_DEBUG(("Diagnostic port 80h: write = %02xh", (unsigned) value));
BX_UM_THIS s.port80 = value;
break;
case 0x8e: // ???
BX_UM_THIS s.port8e = value;
break;
#if BX_PORT_E9_HACK
// This port doesn't exist on normal ISA architecture. However,
// we define a convention here, to display on the console of the
// system running Bochs, anything that is written to it. The
// idea is to provide debug output very early when writing
// BIOS or OS code for example, without having to bother with
// properly setting up a serial port or anything.
//
// Idea by Andreas Beck ([email protected])
case 0xe9:
putchar(value);
fflush(stdout);
break;
#endif
case 0xed: // Dummy port used as I/O delay
break;
case 0xee: // ???
break;
case 0x2f2:
case 0x2f3:
case 0x2f4:
case 0x2f5:
case 0x2f6:
case 0x2f7:
case 0x3e8:
case 0x3e9:
case 0x3eb:
case 0x3ec:
case 0x3ed:
// BX_DEBUG(("unsupported IO write to port %04x of %02x", address, value));
break;
case 0x8900: // Shutdown port, could be moved in a PM device
// or a host <-> guest communication device
switch (value) {
case 'S': if (BX_UM_THIS s.shutdown == 0) BX_UM_THIS s.shutdown = 1; break;
case 'h': if (BX_UM_THIS s.shutdown == 1) BX_UM_THIS s.shutdown = 2; break;
case 'u': if (BX_UM_THIS s.shutdown == 2) BX_UM_THIS s.shutdown = 3; break;
case 't': if (BX_UM_THIS s.shutdown == 3) BX_UM_THIS s.shutdown = 4; break;
case 'd': if (BX_UM_THIS s.shutdown == 4) BX_UM_THIS s.shutdown = 5; break;
case 'o': if (BX_UM_THIS s.shutdown == 5) BX_UM_THIS s.shutdown = 6; break;
case 'w': if (BX_UM_THIS s.shutdown == 6) BX_UM_THIS s.shutdown = 7; break;
case 'n': if (BX_UM_THIS s.shutdown == 7) BX_UM_THIS s.shutdown = 8; break;
#if BX_DEBUGGER
// Very handy for debugging:
// output 'D' to port 8900, and bochs quits to debugger
case 'D': bx_debug_break(); break;
#endif
default : BX_UM_THIS s.shutdown = 0; break;
}
if (BX_UM_THIS s.shutdown == 8) {
bx_user_quit = 1;
LOG_THIS setonoff(LOGLEV_PANIC, ACT_FATAL);
BX_PANIC(("Shutdown port: shutdown requested"));
}
break;
case 0xfedc:
bx_dbg.debugger = (value > 0);
BX_DEBUG(( "DEBUGGER = %u", (unsigned) bx_dbg.debugger));
break;
default:
break;
}
return_from_write:
if (bx_dbg.unsupported_io) {
switch (io_len) {
case 1:
BX_INFO(("unmapped: 8-bit write to %04x = %02x", address, value));
break;
case 2:
BX_INFO(("unmapped: 16-bit write to %04x = %04x", address, value));
break;
case 4:
BX_INFO(("unmapped: 32-bit write to %04x = %08x", address, value));
break;
default:
BX_INFO(("unmapped: %d-bit write to %04x = %x", io_len * 8, address, value));
break;
}
}
}
<|endoftext|> |
<commit_before>#include "Players/Genetic_AI.h"
#include <iostream>
#include <fstream>
#include <map>
#include <algorithm>
class Board;
class Clock;
#include "Game/Color.h"
#include "Utility/String.h"
#include "Exceptions/Genetic_AI_Creation_Error.h"
int Genetic_AI::next_id = 0;
size_t Genetic_AI::max_origin_pool_id = 0;
//! Generate a randomly mutated Genetic_AI
//
//! \param mutation_count The number of genome mutations to apply to the AI after construction.
Genetic_AI::Genetic_AI(int mutation_count) :
id_number(next_id++)
{
mutate(mutation_count);
recalibrate_self();
}
//! Create a new Genetic_AI via sexual reproduction.
//
//! The offspring is formed by randomly taking genes from each parent.
//! \param A The first parent.
//! \param B The second parent.
Genetic_AI::Genetic_AI(const Genetic_AI& A, const Genetic_AI& B) :
genome(A.genome, B.genome),
id_number(next_id++)
{
auto A_parents = A.ancestry;
auto B_parents = B.ancestry;
for(size_t i = 0; i <= max_origin_pool_id; ++i)
{
ancestry[i] = (A_parents[i] + B_parents[i])/2;
}
recalibrate_self();
}
//! Create a Genetic_AI from information in a text file.
//
//! \param file_name The name of the text file.
//! \throws Genetic_AI_Creation_Error if the file cannot be opened or if there is an error during reading.
Genetic_AI::Genetic_AI(const std::string& file_name)
{
std::ifstream ifs(file_name);
if( ! ifs)
{
throw Genetic_AI_Creation_Error("Could not read: " + file_name);
}
read_from(ifs);
recalibrate_self();
}
//! Create a Genetic_AI from information in an input stream (std::ifstream, std::cin, etc.).
//
//! \param is Input stream.
//! \throws Genetic_AI_Creation_Error If there is an error during reading.
Genetic_AI::Genetic_AI(std::istream& is)
{
read_from(is);
recalibrate_self();
}
//! Create a Genetic_AI from a text file by searching for a specfic ID.
//
//! \param file_name The name of the file with the Genetic_AI data.
//! \param id_in The ID to search for.
//! \throws Genetic_AI_Creation_Error If there is an error during reading.
Genetic_AI::Genetic_AI(const std::string& file_name, int id_in) : id_number(id_in)
{
std::ifstream ifs(file_name);
if( ! ifs)
{
throw Genetic_AI_Creation_Error("Could not read: " + file_name);
}
std::string line;
while(std::getline(ifs, line))
{
line = String::strip_comments(line, "#");
if( ! String::starts_with(line, "ID"))
{
continue;
}
auto param_value = String::split(line, ":", 1);
if(param_value.size() != 2 || String::trim_outer_whitespace(param_value[0]) != "ID")
{
throw Genetic_AI_Creation_Error("Bad ID line: " + line);
}
if(id_in == std::stoi(param_value[1]))
{
read_ancestry(ifs);
genome.read_from(ifs);
recalibrate_self();
next_id = std::max(next_id, id_number + 1);
return;
}
}
throw Genetic_AI_Creation_Error("Could not locate ID " + std::to_string(id_in) + " inside file " + file_name);
}
void Genetic_AI::read_from(std::istream& is)
{
std::string line;
while(std::getline(is, line))
{
line = String::strip_comments(line, "#");
if(line.empty())
{
continue;
}
if(String::starts_with(line, "ID"))
{
auto param_value = String::split(line, ":", 1);
if(param_value.size() != 2 || String::trim_outer_whitespace(param_value[0]) != "ID")
{
throw Genetic_AI_Creation_Error("Bad ID line: " + line);
}
id_number = std::stoi(param_value[1]);
break;
}
else
{
throw Genetic_AI_Creation_Error("Invalid Genetic_AI line: " + line);
}
}
if( ! is)
{
throw Genetic_AI_Creation_Error("Incomplete Genetic_AI spec in file for ID " + std::to_string(id_number));
}
read_ancestry(is);
genome.read_from(is);
next_id = std::max(next_id, id_number + 1);
}
double Genetic_AI::internal_evaluate(const Board& board, Color perspective, size_t depth) const
{
return genome.evaluate(board, perspective, depth);
}
double Genetic_AI::time_to_examine(const Board& board, const Clock& clock) const
{
return genome.time_to_examine(board, clock);
}
double Genetic_AI::speculation_time_factor(const Board& board) const
{
return genome.speculation_time_factor(board);
}
//! Apply random mutations to the Genome of the Genetic_AI
//
//! \param mutation_count The number of mutation actions to apply to the genome. Defaults to 1 if unspecified.
void Genetic_AI::mutate(int mutation_count)
{
for(int i = 0; i < mutation_count; ++i)
{
genome.mutate();
}
recalibrate_self();
}
//! Prints the information defining this AI.
//
//! The printed information includes the ID number, ancestry information, and genetic data.
//! \param file_name The name of the text file to print to. If empty, print to stdout.
void Genetic_AI::print(const std::string& file_name) const
{
if(file_name.empty())
{
print(std::cout);
}
else
{
auto dest = std::ofstream(file_name, std::ofstream::app);
print(dest);
}
}
//! Print AI information to the given std::ostream.
//
//! \param os The stream to be written to.
void Genetic_AI::print(std::ostream& os) const
{
os << "ID: " << id() << '\n';
os << "Name: Ancestry\n";
for(size_t i = 0; i <= max_origin_pool_id; ++i)
{
auto fraction = (ancestry.count(i) > 0 ? ancestry.at(i) : 0.0);
os << i << ": " << fraction << "\n";
}
os << "\n";
genome.print(os);
os << "END" << "\n" << std::endl;
}
//! Reports the name of the AI and ID number.
//
//! \returns "Genetic AI" plus the ID.
std::string Genetic_AI::name() const
{
return "Genetic AI " + std::to_string(id());
}
//! Reports the author of this chess engine.
//
//! \returns "Mark Harrison"
std::string Genetic_AI::author() const
{
return "Mark Harrison";
}
//! Reports the ID number of the Genetic_AI.
//
//! \returns The ID number.
int Genetic_AI::id() const
{
return id_number;
}
//! A comparison function to sort Genetic_AI collections.
//
//! \param other Another Genetic_AI.
//! \returns If the other AI should go after this AI.
bool Genetic_AI::operator<(const Genetic_AI& other) const
{
return id() < other.id();
}
//! This function identifies the first gene pool into which a newly created Genetic_AI is placed.
//
//! \param pool_id The ID number of the gene pool.
void Genetic_AI::set_origin_pool(size_t pool_id)
{
ancestry.clear();
ancestry[pool_id] = 1.0;
max_origin_pool_id = std::max(max_origin_pool_id, pool_id);
}
void Genetic_AI::read_ancestry(std::istream& is)
{
auto id_string = "(ID: " + std::to_string(id()) + ")";
std::string line;
while(std::getline(is, line))
{
line = String::strip_comments(line, "#");
if(line.empty())
{
continue;
}
if(String::starts_with(line, "Name"))
{
auto data = String::split(line, ":", 1);
auto header = String::trim_outer_whitespace(data.front());
if(data.size() != 2 || header != "Name")
{
throw Genetic_AI_Creation_Error("Bad section header (" + id_string + "): " + line);
}
auto section = String::remove_extra_whitespace(data.back());
if(section == "Ancestry")
{
break;
}
else
{
throw Genetic_AI_Creation_Error("Missing ancestry data " + id_string);
}
}
}
while(std::getline(is, line))
{
if(String::trim_outer_whitespace(line).empty())
{
break;
}
line = String::strip_comments(line, "#");
if(line.empty())
{
continue;
}
auto pool_fraction = String::split(line, ":");
if(pool_fraction.size() != 2)
{
throw Genetic_AI_Creation_Error("Bad ancestry line " + id_string + ": " + line);
}
try
{
auto pool = String::string_to_size_t(pool_fraction[0]);
auto fraction = std::stod(pool_fraction[1]);
ancestry[pool] = fraction;
max_origin_pool_id = std::max(max_origin_pool_id, pool);
}
catch(const std::exception&)
{
throw Genetic_AI_Creation_Error("Bad ancesry line " + id_string + ": " + line);
}
}
}
<commit_msg>Genetic_AI::mutate() calls recalibrate_self()<commit_after>#include "Players/Genetic_AI.h"
#include <iostream>
#include <fstream>
#include <map>
#include <algorithm>
class Board;
class Clock;
#include "Game/Color.h"
#include "Utility/String.h"
#include "Exceptions/Genetic_AI_Creation_Error.h"
int Genetic_AI::next_id = 0;
size_t Genetic_AI::max_origin_pool_id = 0;
//! Generate a randomly mutated Genetic_AI
//
//! \param mutation_count The number of genome mutations to apply to the AI after construction.
Genetic_AI::Genetic_AI(int mutation_count) :
id_number(next_id++)
{
mutate(mutation_count);
}
//! Create a new Genetic_AI via sexual reproduction.
//
//! The offspring is formed by randomly taking genes from each parent.
//! \param A The first parent.
//! \param B The second parent.
Genetic_AI::Genetic_AI(const Genetic_AI& A, const Genetic_AI& B) :
genome(A.genome, B.genome),
id_number(next_id++)
{
auto A_parents = A.ancestry;
auto B_parents = B.ancestry;
for(size_t i = 0; i <= max_origin_pool_id; ++i)
{
ancestry[i] = (A_parents[i] + B_parents[i])/2;
}
recalibrate_self();
}
//! Create a Genetic_AI from information in a text file.
//
//! \param file_name The name of the text file.
//! \throws Genetic_AI_Creation_Error if the file cannot be opened or if there is an error during reading.
Genetic_AI::Genetic_AI(const std::string& file_name)
{
std::ifstream ifs(file_name);
if( ! ifs)
{
throw Genetic_AI_Creation_Error("Could not read: " + file_name);
}
read_from(ifs);
recalibrate_self();
}
//! Create a Genetic_AI from information in an input stream (std::ifstream, std::cin, etc.).
//
//! \param is Input stream.
//! \throws Genetic_AI_Creation_Error If there is an error during reading.
Genetic_AI::Genetic_AI(std::istream& is)
{
read_from(is);
recalibrate_self();
}
//! Create a Genetic_AI from a text file by searching for a specfic ID.
//
//! \param file_name The name of the file with the Genetic_AI data.
//! \param id_in The ID to search for.
//! \throws Genetic_AI_Creation_Error If there is an error during reading.
Genetic_AI::Genetic_AI(const std::string& file_name, int id_in) : id_number(id_in)
{
std::ifstream ifs(file_name);
if( ! ifs)
{
throw Genetic_AI_Creation_Error("Could not read: " + file_name);
}
std::string line;
while(std::getline(ifs, line))
{
line = String::strip_comments(line, "#");
if( ! String::starts_with(line, "ID"))
{
continue;
}
auto param_value = String::split(line, ":", 1);
if(param_value.size() != 2 || String::trim_outer_whitespace(param_value[0]) != "ID")
{
throw Genetic_AI_Creation_Error("Bad ID line: " + line);
}
if(id_in == std::stoi(param_value[1]))
{
read_ancestry(ifs);
genome.read_from(ifs);
recalibrate_self();
next_id = std::max(next_id, id_number + 1);
return;
}
}
throw Genetic_AI_Creation_Error("Could not locate ID " + std::to_string(id_in) + " inside file " + file_name);
}
void Genetic_AI::read_from(std::istream& is)
{
std::string line;
while(std::getline(is, line))
{
line = String::strip_comments(line, "#");
if(line.empty())
{
continue;
}
if(String::starts_with(line, "ID"))
{
auto param_value = String::split(line, ":", 1);
if(param_value.size() != 2 || String::trim_outer_whitespace(param_value[0]) != "ID")
{
throw Genetic_AI_Creation_Error("Bad ID line: " + line);
}
id_number = std::stoi(param_value[1]);
break;
}
else
{
throw Genetic_AI_Creation_Error("Invalid Genetic_AI line: " + line);
}
}
if( ! is)
{
throw Genetic_AI_Creation_Error("Incomplete Genetic_AI spec in file for ID " + std::to_string(id_number));
}
read_ancestry(is);
genome.read_from(is);
next_id = std::max(next_id, id_number + 1);
}
double Genetic_AI::internal_evaluate(const Board& board, Color perspective, size_t depth) const
{
return genome.evaluate(board, perspective, depth);
}
double Genetic_AI::time_to_examine(const Board& board, const Clock& clock) const
{
return genome.time_to_examine(board, clock);
}
double Genetic_AI::speculation_time_factor(const Board& board) const
{
return genome.speculation_time_factor(board);
}
//! Apply random mutations to the Genome of the Genetic_AI
//
//! \param mutation_count The number of mutation actions to apply to the genome. Defaults to 1 if unspecified.
void Genetic_AI::mutate(int mutation_count)
{
for(int i = 0; i < mutation_count; ++i)
{
genome.mutate();
}
recalibrate_self();
}
//! Prints the information defining this AI.
//
//! The printed information includes the ID number, ancestry information, and genetic data.
//! \param file_name The name of the text file to print to. If empty, print to stdout.
void Genetic_AI::print(const std::string& file_name) const
{
if(file_name.empty())
{
print(std::cout);
}
else
{
auto dest = std::ofstream(file_name, std::ofstream::app);
print(dest);
}
}
//! Print AI information to the given std::ostream.
//
//! \param os The stream to be written to.
void Genetic_AI::print(std::ostream& os) const
{
os << "ID: " << id() << '\n';
os << "Name: Ancestry\n";
for(size_t i = 0; i <= max_origin_pool_id; ++i)
{
auto fraction = (ancestry.count(i) > 0 ? ancestry.at(i) : 0.0);
os << i << ": " << fraction << "\n";
}
os << "\n";
genome.print(os);
os << "END" << "\n" << std::endl;
}
//! Reports the name of the AI and ID number.
//
//! \returns "Genetic AI" plus the ID.
std::string Genetic_AI::name() const
{
return "Genetic AI " + std::to_string(id());
}
//! Reports the author of this chess engine.
//
//! \returns "Mark Harrison"
std::string Genetic_AI::author() const
{
return "Mark Harrison";
}
//! Reports the ID number of the Genetic_AI.
//
//! \returns The ID number.
int Genetic_AI::id() const
{
return id_number;
}
//! A comparison function to sort Genetic_AI collections.
//
//! \param other Another Genetic_AI.
//! \returns If the other AI should go after this AI.
bool Genetic_AI::operator<(const Genetic_AI& other) const
{
return id() < other.id();
}
//! This function identifies the first gene pool into which a newly created Genetic_AI is placed.
//
//! \param pool_id The ID number of the gene pool.
void Genetic_AI::set_origin_pool(size_t pool_id)
{
ancestry.clear();
ancestry[pool_id] = 1.0;
max_origin_pool_id = std::max(max_origin_pool_id, pool_id);
}
void Genetic_AI::read_ancestry(std::istream& is)
{
auto id_string = "(ID: " + std::to_string(id()) + ")";
std::string line;
while(std::getline(is, line))
{
line = String::strip_comments(line, "#");
if(line.empty())
{
continue;
}
if(String::starts_with(line, "Name"))
{
auto data = String::split(line, ":", 1);
auto header = String::trim_outer_whitespace(data.front());
if(data.size() != 2 || header != "Name")
{
throw Genetic_AI_Creation_Error("Bad section header (" + id_string + "): " + line);
}
auto section = String::remove_extra_whitespace(data.back());
if(section == "Ancestry")
{
break;
}
else
{
throw Genetic_AI_Creation_Error("Missing ancestry data " + id_string);
}
}
}
while(std::getline(is, line))
{
if(String::trim_outer_whitespace(line).empty())
{
break;
}
line = String::strip_comments(line, "#");
if(line.empty())
{
continue;
}
auto pool_fraction = String::split(line, ":");
if(pool_fraction.size() != 2)
{
throw Genetic_AI_Creation_Error("Bad ancestry line " + id_string + ": " + line);
}
try
{
auto pool = String::string_to_size_t(pool_fraction[0]);
auto fraction = std::stod(pool_fraction[1]);
ancestry[pool] = fraction;
max_origin_pool_id = std::max(max_origin_pool_id, pool);
}
catch(const std::exception&)
{
throw Genetic_AI_Creation_Error("Bad ancesry line " + id_string + ": " + line);
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of the Ford Motor Company nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef __QNXNTO__
#include <openssl/ssl3.h>
#else
#include <openssl/ssl.h>
#endif //__QNXNTO__
#include <limits>
#include <fstream>
#include <sstream>
#include "utils/make_shared.h"
#include "gtest/gtest.h"
#include "security_manager/crypto_manager_impl.h"
#include "security_manager/mock_security_manager_settings.h"
using ::testing::Return;
using ::testing::ReturnRef;
using ::testing::NiceMock;
namespace {
const size_t kUpdatesBeforeHour = 24;
const std::string kAllCiphers = "ALL";
const std::string kCaCertPath = "";
const uint32_t kServiceNumber = 2u;
const size_t kMaxSizeVector = 1u;
const std::string kCertPath = "certificate.crt";
const std::string kPrivateKeyPath = "private.key";
#ifdef __QNXNTO__
const std::string kFordCipher = SSL3_TXT_RSA_DES_192_CBC3_SHA;
#else
// Used cipher from ford protocol requirement
const std::string kFordCipher = TLS1_TXT_RSA_WITH_AES_256_GCM_SHA384;
#endif
}
namespace test {
namespace components {
namespace crypto_manager_test {
using security_manager::CryptoManagerImpl;
class CryptoManagerTest : public testing::Test {
protected:
typedef NiceMock<security_manager_test::MockCryptoManagerSettings>
MockCryptoManagerSettings;
static void SetUpTestCase() {
std::ifstream certificate_file("server/spt_credential.pem");
ASSERT_TRUE(certificate_file.is_open())
<< "Could not open certificate data file";
const std::string certificate(
(std::istreambuf_iterator<char>(certificate_file)),
std::istreambuf_iterator<char>());
ASSERT_FALSE(certificate.empty()) << "Certificate data file is empty";
certificate_data_base64_ = certificate;
}
void SetUp() OVERRIDE {
ASSERT_FALSE(certificate_data_base64_.empty());
mock_security_manager_settings_ =
utils::MakeShared<MockCryptoManagerSettings>();
crypto_manager_ =
utils::MakeShared<CryptoManagerImpl>(mock_security_manager_settings_);
forced_protected_services_.reserve(kMaxSizeVector);
forced_unprotected_services_.reserve(kMaxSizeVector);
}
void InitSecurityManager() {
SetInitialValues(
security_manager::CLIENT, security_manager::TLSv1_2, kAllCiphers);
const bool crypto_manager_initialization = crypto_manager_->Init();
ASSERT_TRUE(crypto_manager_initialization);
}
void SetInitialValues(security_manager::Mode mode,
security_manager::Protocol protocol,
const std::string& cipher) {
ON_CALL(*mock_security_manager_settings_, force_unprotected_service())
.WillByDefault(ReturnRef(forced_unprotected_services_));
ON_CALL(*mock_security_manager_settings_, force_protected_service())
.WillByDefault(ReturnRef(forced_protected_services_));
ON_CALL(*mock_security_manager_settings_, security_manager_mode())
.WillByDefault(Return(mode));
ON_CALL(*mock_security_manager_settings_, security_manager_protocol_name())
.WillByDefault(Return(protocol));
ON_CALL(*mock_security_manager_settings_, certificate_data())
.WillByDefault(ReturnRef(certificate_data_base64_));
ON_CALL(*mock_security_manager_settings_, ciphers_list())
.WillByDefault(ReturnRef(cipher));
ON_CALL(*mock_security_manager_settings_, ca_cert_path())
.WillByDefault(ReturnRef(kCaCertPath));
ON_CALL(*mock_security_manager_settings_, module_cert_path())
.WillByDefault(ReturnRef(kCertPath));
ON_CALL(*mock_security_manager_settings_, module_key_path())
.WillByDefault(ReturnRef(kPrivateKeyPath));
ON_CALL(*mock_security_manager_settings_, verify_peer())
.WillByDefault(Return(false));
}
utils::SharedPtr<CryptoManagerImpl> crypto_manager_;
utils::SharedPtr<MockCryptoManagerSettings> mock_security_manager_settings_;
static std::string certificate_data_base64_;
std::vector<int> forced_protected_services_;
std::vector<int> forced_unprotected_services_;
};
std::string CryptoManagerTest::certificate_data_base64_;
TEST_F(CryptoManagerTest, UsingBeforeInit) {
EXPECT_TRUE(crypto_manager_->CreateSSLContext() == NULL);
EXPECT_EQ(std::string("Initialization is not completed"),
crypto_manager_->LastError());
}
TEST_F(CryptoManagerTest, WrongInit) {
forced_protected_services_.push_back(kServiceNumber);
forced_unprotected_services_.push_back(kServiceNumber);
EXPECT_CALL(*mock_security_manager_settings_, security_manager_mode())
.WillOnce(Return(security_manager::SERVER));
EXPECT_CALL(*mock_security_manager_settings_, force_unprotected_service())
.WillOnce(ReturnRef(forced_unprotected_services_));
EXPECT_CALL(*mock_security_manager_settings_, force_protected_service())
.WillOnce(ReturnRef(forced_protected_services_));
EXPECT_FALSE(crypto_manager_->Init());
forced_protected_services_.pop_back();
forced_unprotected_services_.pop_back();
EXPECT_NE(std::string(), crypto_manager_->LastError());
// Unexistent cipher value
const std::string invalid_cipher = "INVALID_UNKNOWN_CIPHER";
EXPECT_CALL(*mock_security_manager_settings_, security_manager_mode())
.WillOnce(Return(security_manager::SERVER));
EXPECT_CALL(*mock_security_manager_settings_, force_unprotected_service())
.WillOnce(ReturnRef(forced_unprotected_services_));
EXPECT_CALL(*mock_security_manager_settings_, force_protected_service())
.WillOnce(ReturnRef(forced_protected_services_));
EXPECT_CALL(*mock_security_manager_settings_,
security_manager_protocol_name())
.WillOnce(Return(security_manager::TLSv1_2));
EXPECT_CALL(*mock_security_manager_settings_, certificate_data())
.WillOnce(ReturnRef(certificate_data_base64_));
EXPECT_CALL(*mock_security_manager_settings_, ciphers_list())
.WillRepeatedly(ReturnRef(invalid_cipher));
EXPECT_FALSE(crypto_manager_->Init());
EXPECT_NE(std::string(), crypto_manager_->LastError());
}
// #ifndef __QNXNTO__
TEST_F(CryptoManagerTest, CorrectInit) {
// Empty cert and key values for SERVER
SetInitialValues(
security_manager::SERVER, security_manager::TLSv1_2, kFordCipher);
EXPECT_TRUE(crypto_manager_->Init());
// Recall init
SetInitialValues(
security_manager::CLIENT, security_manager::TLSv1_2, kFordCipher);
EXPECT_TRUE(crypto_manager_->Init());
// Recall init with other protocols
SetInitialValues(
security_manager::CLIENT, security_manager::TLSv1_2, kFordCipher);
EXPECT_TRUE(crypto_manager_->Init());
SetInitialValues(
security_manager::CLIENT, security_manager::TLSv1_1, kFordCipher);
EXPECT_TRUE(crypto_manager_->Init());
SetInitialValues(
security_manager::CLIENT, security_manager::DTLSv1, kFordCipher);
EXPECT_TRUE(crypto_manager_->Init());
// Cipher value
SetInitialValues(
security_manager::SERVER, security_manager::TLSv1_2, kAllCiphers);
EXPECT_TRUE(crypto_manager_->Init());
SetInitialValues(
security_manager::SERVER, security_manager::DTLSv1, kAllCiphers);
EXPECT_TRUE(crypto_manager_->Init());
}
// #endif // __QNX__
TEST_F(CryptoManagerTest, ReleaseSSLContext_Null) {
EXPECT_NO_THROW(crypto_manager_->ReleaseSSLContext(NULL));
}
TEST_F(CryptoManagerTest, CreateReleaseSSLContext) {
const size_t max_payload_size = 1000u;
SetInitialValues(
security_manager::CLIENT, security_manager::TLSv1_2, kAllCiphers);
EXPECT_TRUE(crypto_manager_->Init());
EXPECT_CALL(*mock_security_manager_settings_, security_manager_mode())
.Times(2)
.WillRepeatedly(Return(security_manager::CLIENT));
EXPECT_CALL(*mock_security_manager_settings_, maximum_payload_size())
.Times(1)
.WillRepeatedly(Return(max_payload_size));
security_manager::SSLContext* context = crypto_manager_->CreateSSLContext();
EXPECT_TRUE(context);
EXPECT_NO_THROW(crypto_manager_->ReleaseSSLContext(context));
}
TEST_F(CryptoManagerTest, OnCertificateUpdated) {
InitSecurityManager();
EXPECT_TRUE(crypto_manager_->OnCertificateUpdated(certificate_data_base64_));
}
TEST_F(CryptoManagerTest, OnCertificateUpdated_UpdateNotRequired) {
time_t system_time = 0;
time_t certificates_time = 1;
size_t updates_before = 0;
SetInitialValues(
security_manager::CLIENT, security_manager::TLSv1_2, kAllCiphers);
ASSERT_TRUE(crypto_manager_->Init());
EXPECT_CALL(*mock_security_manager_settings_, update_before_hours())
.WillOnce(Return(updates_before));
EXPECT_FALSE(crypto_manager_->IsCertificateUpdateRequired(system_time,
certificates_time));
size_t max_updates_ = std::numeric_limits<size_t>::max();
SetInitialValues(
security_manager::CLIENT, security_manager::TLSv1_2, kAllCiphers);
EXPECT_CALL(*mock_security_manager_settings_, update_before_hours())
.WillOnce(Return(max_updates_));
ASSERT_TRUE(crypto_manager_->Init());
EXPECT_TRUE(crypto_manager_->IsCertificateUpdateRequired(system_time,
certificates_time));
}
TEST_F(CryptoManagerTest, OnCertificateUpdated_NotInitialized) {
EXPECT_FALSE(crypto_manager_->OnCertificateUpdated(certificate_data_base64_));
}
TEST_F(CryptoManagerTest, OnCertificateUpdated_NullString) {
InitSecurityManager();
EXPECT_FALSE(crypto_manager_->OnCertificateUpdated(std::string()));
}
TEST_F(CryptoManagerTest, OnCertificateUpdated_MalformedSign) {
InitSecurityManager();
// Corrupt the middle symbol
certificate_data_base64_[certificate_data_base64_.size() / 2] = '?';
EXPECT_FALSE(crypto_manager_->OnCertificateUpdated(certificate_data_base64_));
}
TEST_F(CryptoManagerTest, OnCertificateUpdated_WrongInitFolder) {
SetInitialValues(
security_manager::CLIENT, security_manager::TLSv1_2, kAllCiphers);
ASSERT_TRUE(crypto_manager_->Init());
const std::string certificate = "wrong_data";
ASSERT_FALSE(certificate.empty());
EXPECT_FALSE(crypto_manager_->OnCertificateUpdated(certificate));
}
} // namespace crypto_manager_test
} // namespace components
} // namespace test
<commit_msg>Fixed affected mocks and UT's<commit_after>/*
* Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of the Ford Motor Company nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef __QNXNTO__
#include <openssl/ssl3.h>
#else
#include <openssl/ssl.h>
#endif //__QNXNTO__
#include <limits>
#include <fstream>
#include <sstream>
#include "utils/make_shared.h"
#include "gtest/gtest.h"
#include "security_manager/crypto_manager_impl.h"
#include "security_manager/mock_security_manager_settings.h"
using ::testing::Return;
using ::testing::ReturnRef;
using ::testing::NiceMock;
namespace {
const size_t kUpdatesBeforeHour = 24;
const std::string kAllCiphers = "ALL";
const std::string kCaCertPath = "";
const uint32_t kServiceNumber = 2u;
const size_t kMaxSizeVector = 1u;
const std::string kCertPath = "certificate.crt";
const std::string kPrivateKeyPath = "private.key";
#ifdef __QNXNTO__
const std::string kFordCipher = SSL3_TXT_RSA_DES_192_CBC3_SHA;
#else
// Used cipher from ford protocol requirement
const std::string kFordCipher = TLS1_TXT_RSA_WITH_AES_256_GCM_SHA384;
#endif
}
namespace test {
namespace components {
namespace crypto_manager_test {
using security_manager::CryptoManagerImpl;
class CryptoManagerTest : public testing::Test {
protected:
typedef NiceMock<security_manager_test::MockCryptoManagerSettings>
MockCryptoManagerSettings;
static void SetUpTestCase() {
std::ifstream certificate_file("server/spt_credential.pem");
ASSERT_TRUE(certificate_file.is_open())
<< "Could not open certificate data file";
const std::string certificate(
(std::istreambuf_iterator<char>(certificate_file)),
std::istreambuf_iterator<char>());
ASSERT_FALSE(certificate.empty()) << "Certificate data file is empty";
certificate_data_base64_ = certificate;
}
void SetUp() OVERRIDE {
ASSERT_FALSE(certificate_data_base64_.empty());
mock_security_manager_settings_ =
utils::MakeShared<MockCryptoManagerSettings>();
crypto_manager_ =
utils::MakeShared<CryptoManagerImpl>(mock_security_manager_settings_);
forced_protected_services_.reserve(kMaxSizeVector);
forced_unprotected_services_.reserve(kMaxSizeVector);
}
void InitSecurityManager() {
SetInitialValues(
security_manager::CLIENT, security_manager::TLSv1_2, kAllCiphers);
const bool crypto_manager_initialization = crypto_manager_->Init();
ASSERT_TRUE(crypto_manager_initialization);
}
void SetInitialValues(security_manager::Mode mode,
security_manager::Protocol protocol,
const std::string& cipher) {
ON_CALL(*mock_security_manager_settings_, force_unprotected_service())
.WillByDefault(ReturnRef(forced_unprotected_services_));
ON_CALL(*mock_security_manager_settings_, force_protected_service())
.WillByDefault(ReturnRef(forced_protected_services_));
ON_CALL(*mock_security_manager_settings_, security_manager_mode())
.WillByDefault(Return(mode));
ON_CALL(*mock_security_manager_settings_, security_manager_protocol_name())
.WillByDefault(Return(protocol));
ON_CALL(*mock_security_manager_settings_, certificate_data())
.WillByDefault(ReturnRef(certificate_data_base64_));
ON_CALL(*mock_security_manager_settings_, ciphers_list())
.WillByDefault(ReturnRef(cipher));
ON_CALL(*mock_security_manager_settings_, ca_cert_path())
.WillByDefault(ReturnRef(kCaCertPath));
ON_CALL(*mock_security_manager_settings_, module_cert_path())
.WillByDefault(ReturnRef(kCertPath));
ON_CALL(*mock_security_manager_settings_, module_key_path())
.WillByDefault(ReturnRef(kPrivateKeyPath));
ON_CALL(*mock_security_manager_settings_, verify_peer())
.WillByDefault(Return(false));
}
utils::SharedPtr<CryptoManagerImpl> crypto_manager_;
utils::SharedPtr<MockCryptoManagerSettings> mock_security_manager_settings_;
static std::string certificate_data_base64_;
std::vector<int> forced_protected_services_;
std::vector<int> forced_unprotected_services_;
};
std::string CryptoManagerTest::certificate_data_base64_;
TEST_F(CryptoManagerTest, UsingBeforeInit) {
EXPECT_TRUE(crypto_manager_->CreateSSLContext() == NULL);
EXPECT_EQ(std::string("Initialization is not completed"),
crypto_manager_->LastError());
}
TEST_F(CryptoManagerTest, WrongInit) {
// We have to cast (-1) to security_manager::Protocol Enum to be accepted by
// crypto_manager_->Init(...)
// Unknown protocol version
security_manager::Protocol UNKNOWN =
static_cast<security_manager::Protocol>(-1);
// Unexistent cipher value
const std::string invalid_cipher = "INVALID_UNKNOWN_CIPHER";
const security_manager::Mode mode = security_manager::SERVER;
SetInitialValues(mode, UNKNOWN, invalid_cipher);
EXPECT_FALSE(crypto_manager_->Init());
EXPECT_NE(std::string(), crypto_manager_->LastError());
>>>>>>> Fixed affected mocks and UT's
EXPECT_CALL(*mock_security_manager_settings_,
security_manager_protocol_name())
.WillOnce(Return(security_manager::TLSv1_2));
EXPECT_CALL(*mock_security_manager_settings_, certificate_data())
.WillOnce(ReturnRef(certificate_data_base64_));
EXPECT_CALL(*mock_security_manager_settings_, ciphers_list())
.WillRepeatedly(ReturnRef(invalid_cipher));
EXPECT_FALSE(crypto_manager_->Init());
EXPECT_NE(std::string(), crypto_manager_->LastError());
}
// #ifndef __QNXNTO__
TEST_F(CryptoManagerTest, CorrectInit) {
// Empty cert and key values for SERVER
SetInitialValues(
security_manager::SERVER, security_manager::TLSv1_2, kFordCipher);
EXPECT_TRUE(crypto_manager_->Init());
// Recall init
SetInitialValues(
security_manager::CLIENT, security_manager::TLSv1_2, kFordCipher);
EXPECT_TRUE(crypto_manager_->Init());
// Recall init with other protocols
SetInitialValues(
security_manager::CLIENT, security_manager::TLSv1_2, kFordCipher);
EXPECT_TRUE(crypto_manager_->Init());
SetInitialValues(
security_manager::CLIENT, security_manager::TLSv1_1, kFordCipher);
EXPECT_TRUE(crypto_manager_->Init());
SetInitialValues(
security_manager::CLIENT, security_manager::DTLSv1, kFordCipher);
EXPECT_TRUE(crypto_manager_->Init());
// Cipher value
SetInitialValues(
security_manager::SERVER, security_manager::TLSv1_2, kAllCiphers);
EXPECT_TRUE(crypto_manager_->Init());
SetInitialValues(
security_manager::SERVER, security_manager::DTLSv1, kAllCiphers);
EXPECT_TRUE(crypto_manager_->Init());
}
// #endif // __QNX__
TEST_F(CryptoManagerTest, ReleaseSSLContext_Null) {
EXPECT_NO_THROW(crypto_manager_->ReleaseSSLContext(NULL));
}
TEST_F(CryptoManagerTest, CreateReleaseSSLContext) {
const size_t max_payload_size = 1000u;
SetInitialValues(
security_manager::CLIENT, security_manager::TLSv1_2, kAllCiphers);
EXPECT_TRUE(crypto_manager_->Init());
EXPECT_CALL(*mock_security_manager_settings_, security_manager_mode())
.Times(2)
.WillRepeatedly(Return(security_manager::CLIENT));
EXPECT_CALL(*mock_security_manager_settings_, maximum_payload_size())
.Times(1)
.WillRepeatedly(Return(max_payload_size));
security_manager::SSLContext* context = crypto_manager_->CreateSSLContext();
EXPECT_TRUE(context);
EXPECT_NO_THROW(crypto_manager_->ReleaseSSLContext(context));
}
TEST_F(CryptoManagerTest, OnCertificateUpdated) {
InitSecurityManager();
EXPECT_TRUE(crypto_manager_->OnCertificateUpdated(certificate_data_base64_));
}
TEST_F(CryptoManagerTest, OnCertificateUpdated_UpdateNotRequired) {
time_t system_time = 0;
time_t certificates_time = 1;
size_t updates_before = 0;
SetInitialValues(
security_manager::CLIENT, security_manager::TLSv1_2, kAllCiphers);
ASSERT_TRUE(crypto_manager_->Init());
EXPECT_CALL(*mock_security_manager_settings_, update_before_hours())
.WillOnce(Return(updates_before));
EXPECT_FALSE(crypto_manager_->IsCertificateUpdateRequired(system_time,
certificates_time));
size_t max_updates_ = std::numeric_limits<size_t>::max();
SetInitialValues(
security_manager::CLIENT, security_manager::TLSv1_2, kAllCiphers);
EXPECT_CALL(*mock_security_manager_settings_, update_before_hours())
.WillOnce(Return(max_updates_));
ASSERT_TRUE(crypto_manager_->Init());
EXPECT_TRUE(crypto_manager_->IsCertificateUpdateRequired(system_time,
certificates_time));
}
TEST_F(CryptoManagerTest, OnCertificateUpdated_NotInitialized) {
EXPECT_FALSE(crypto_manager_->OnCertificateUpdated(certificate_data_base64_));
}
TEST_F(CryptoManagerTest, OnCertificateUpdated_NullString) {
InitSecurityManager();
EXPECT_FALSE(crypto_manager_->OnCertificateUpdated(std::string()));
}
TEST_F(CryptoManagerTest, OnCertificateUpdated_MalformedSign) {
InitSecurityManager();
// Corrupt the middle symbol
certificate_data_base64_[certificate_data_base64_.size() / 2] = '?';
EXPECT_FALSE(crypto_manager_->OnCertificateUpdated(certificate_data_base64_));
}
TEST_F(CryptoManagerTest, OnCertificateUpdated_WrongInitFolder) {
SetInitialValues(
security_manager::CLIENT, security_manager::TLSv1_2, kAllCiphers);
ASSERT_TRUE(crypto_manager_->Init());
const std::string certificate = "wrong_data";
ASSERT_FALSE(certificate.empty());
EXPECT_FALSE(crypto_manager_->OnCertificateUpdated(certificate));
}
} // namespace crypto_manager_test
} // namespace components
} // namespace test
<|endoftext|> |
<commit_before>/*
* TimerService.cpp
*
* Created on: 05.04.2017
* Author: jonasfuhrmann
*/
#include "TimerService.h"
#include "Logger.h"
#include "LogScope.h"
#include <sys/neutrino.h>
#include <time.h>
#include <signal.h>
TimerService::TimerService(int chid, char code) throw(int)
: timerid()
, code(code)
, timerRunning(false)
, timerCreated(false){
LOG_SCOPE;
coid = ConnectAttach_r(0, 0, chid, 0, 0);
if(coid < 0) {
LOG_ERROR << "Error in ConnectAttach_r\n";
throw(-coid);
}
}
TimerService::~TimerService() throw(int) {
if(timerCreated){
if(timer_delete(timerid) == -1) { // delete the timer
LOG_ERROR << "Error in timer_delete\n";
throw(EXIT_FAILURE);
}
}
}
void TimerService::setAlarm(milliseconds time, int value) throw(int) {
// initialize the sigevent
timerRunning = true;
SIGEV_PULSE_INIT(&event, coid, SIGEV_PULSE_PRIO_INHERIT, code, value);
if (timer_create(CLOCK_REALTIME, &event, &timerid) == -1) {
LOG_ERROR << "Error in timer_create\n";
throw(EXIT_FAILURE);
} else {
timerCreated = true;
}
unsigned int milliseconds = time;
unsigned int seconds = 0;
if(time >= SECOND) {
milliseconds = time % SECOND;
seconds = (time - milliseconds);
}
timer.it_value.tv_nsec = milliseconds * MILLISECOND;
timer.it_value.tv_sec = seconds / SECOND;
timer.it_interval = { 0, 0 }; // Make it a one shot timer
if(timer_settime(timerid, 0, &timer, NULL) == -1) {
LOG_ERROR << "Error in timer_settime\n";
throw(EXIT_FAILURE);
} else {
timerRunning = true;
}
}
void TimerService::stopAlarm() throw(int) {
if(timerRunning && timerCreated){
if(timer_gettime(timerid, &timer) == -1) { // get the current time of timer
LOG_ERROR << "Error in timer_gettime\n";
throw(EXIT_FAILURE);
}
if(timer_delete(timerid) == -1) { // delete the timer
LOG_ERROR << "Error in timer_delete\n";
throw(EXIT_FAILURE);
}
timerRunning = false;
timerCreated = false;
}
}
void TimerService::resumeAlarm() throw(int) {
if (timer_create(CLOCK_REALTIME, &event, &timerid) == -1) { // create new timer with last values
LOG_ERROR << "Error in timer_create\n";
throw(EXIT_FAILURE);
} else {
timerCreated = true;
}
if(timer_settime(timerid, 0, &timer, NULL) == -1) { // set new timer to resume
LOG_ERROR << "Error in timer_settime\n";
throw(EXIT_FAILURE);
} else {
timerRunning = true;
}
}
TimerService::milliseconds TimerService::killAlarm() throw(int) {
unsigned int mSec = 0;;
unsigned int seconds = 0;
if(timerRunning){
if(timer_gettime(timerid, &timer) == -1) { // get the current time of timer
LOG_ERROR << "Error in timer_gettime\n";
throw(EXIT_FAILURE);
}
if(timer_delete(timerid) == -1) { // delete the timer
LOG_ERROR << "Error in timer_delete\n";
throw(EXIT_FAILURE);
}
mSec = timer.it_value.tv_nsec / MILLISECOND + timer.it_value.tv_sec * SECOND; //Inacurate, but sowhat
}
timerRunning = false;
timerCreated = false;
return mSec; //Zero at failure
}
<commit_msg>Changed timer<commit_after>/*
* TimerService.cpp
*
* Created on: 05.04.2017
* Author: jonasfuhrmann
*/
#include "TimerService.h"
#include "Logger.h"
#include "LogScope.h"
#include <sys/neutrino.h>
#include <time.h>
#include <signal.h>
TimerService::TimerService(int chid, char code) throw(int)
: timerid()
, code(code)
, timerRunning(false)
, timerCreated(false){
LOG_SCOPE;
coid = ConnectAttach_r(0, 0, chid, 0, 0);
if(coid < 0) {
LOG_ERROR << "Error in ConnectAttach_r\n";
throw(-coid);
}
}
TimerService::~TimerService() throw(int) {
if(timerCreated){
if(timer_delete(timerid) == -1) { // delete the timer
LOG_ERROR << "Error in timer_delete\n";
throw(EXIT_FAILURE);
}
}
}
void TimerService::setAlarm(milliseconds time, int value) throw(int) {
// initialize the sigevent
timerRunning = true;
SIGEV_PULSE_INIT(&event, coid, SIGEV_PULSE_PRIO_INHERIT, code, value);
if (timer_create(CLOCK_REALTIME, &event, &timerid) == -1) {
LOG_ERROR << "Error in timer_create\n";
throw(EXIT_FAILURE);
} else {
timerCreated = true;
}
unsigned int milliseconds = time;
unsigned int seconds = 0;
if(time >= SECOND) {
milliseconds = time % SECOND;
seconds = (time - milliseconds);
}
timer.it_value.tv_nsec = milliseconds * MILLISECOND;
timer.it_value.tv_sec = seconds / SECOND;
timer.it_interval = { 0, 0 }; // Make it a one shot timer
if(timer_settime(timerid, 0, &timer, NULL) == -1) {
LOG_ERROR << "Error in timer_settime\n";
throw(EXIT_FAILURE);
} else {
timerRunning = true;
}
}
void TimerService::stopAlarm() throw(int) {
if(timerCreated){
if(timerRunning){
if(timer_gettime(timerid, &timer) == -1) { // get the current time of timer
LOG_ERROR << "Error in timer_gettime\n";
throw(EXIT_FAILURE);
}
}
if(timer_delete(timerid) == -1) { // delete the timer
LOG_ERROR << "Error in timer_delete\n";
throw(EXIT_FAILURE);
}
timerRunning = false;
timerCreated = false;
}
}
void TimerService::resumeAlarm() throw(int) {
if (timer_create(CLOCK_REALTIME, &event, &timerid) == -1) { // create new timer with last values
LOG_ERROR << "Error in timer_create\n";
throw(EXIT_FAILURE);
} else {
timerCreated = true;
}
if(timer_settime(timerid, 0, &timer, NULL) == -1) { // set new timer to resume
LOG_ERROR << "Error in timer_settime\n";
throw(EXIT_FAILURE);
} else {
timerRunning = true;
}
}
TimerService::milliseconds TimerService::killAlarm() throw(int) {
unsigned int mSec = 0;;
unsigned int seconds = 0;
if(timerRunning){
if(timer_gettime(timerid, &timer) == -1) { // get the current time of timer
LOG_ERROR << "Error in timer_gettime\n";
throw(EXIT_FAILURE);
}
if(timer_delete(timerid) == -1) { // delete the timer
LOG_ERROR << "Error in timer_delete\n";
throw(EXIT_FAILURE);
}
mSec = timer.it_value.tv_nsec / MILLISECOND + timer.it_value.tv_sec * SECOND; //Inacurate, but sowhat
}
timerRunning = false;
timerCreated = false;
return mSec; //Zero at failure
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: wrapInstanceTable.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2000 National Library of Medicine
All rights reserved.
See COPYRIGHT.txt for copyright details.
=========================================================================*/
#include "wrapInstanceTable.h"
#include "wrapException.h"
namespace _wrap_
{
/**
* Constructor takes interpreter to which the InstanceTable will be
* attached. It also initializes the temporary object number to zero.
*/
InstanceTable::InstanceTable(Tcl_Interp* interp):
m_Interpreter(interp),
m_TempNameNumber(0)
{
}
/**
* Set a mapping from "name" to object "object" with type "type".
* This deletes any instance of an object already having the given name.
*/
void InstanceTable::SetObject(const String& name, void* object,
const CvQualifiedType& type)
{
if(this->Exists(name))
{
this->DeleteObject(name);
}
m_InstanceMap[name] = Reference(object, type);
m_AddressToNameMap[object] = name;
}
/**
* Delete the object corresponding to the given name.
* This looks up the function pointer that was registered for the object's
* type, and calls it to do the actual deletion.
*/
void InstanceTable::DeleteObject(const String& name)
{
this->CheckExists(name);
const Type* type = m_InstanceMap[name].GetCvQualifiedType().GetType();
void* object = m_InstanceMap[name].GetObject();
// Make sure we know how to delete this object.
if(m_DeleteFunctionMap.count(type) < 1)
{
// throw _wrap_UndefinedObjectTypeException(type->GetName());
throw _wrap_UndefinedObjectTypeException("");
}
// Remove the object's address from our table.
m_AddressToNameMap.erase(object);
// Call the registered delete function.
m_DeleteFunctionMap[type](object);
// Remove from the instance table.
m_InstanceMap.erase(name);
// Remove the Tcl command for this instance.
Tcl_DeleteCommand(m_Interpreter, const_cast<char*>(name.c_str()));
}
/**
* Check if there is an object with the given name.
*/
bool InstanceTable::Exists(const String& name) const
{
return (m_InstanceMap.count(name) > 0);
}
/**
* Get the Reference holding the object with the given name.
*/
const Reference& InstanceTable::GetEntry(const String& name) const
{
this->CheckExists(name);
InstanceMap::const_iterator i = m_InstanceMap.find(name);
return i->second;
}
/**
* Get a pointer to the object with the given name.
*/
void* InstanceTable::GetObject(const String& name)
{
this->CheckExists(name);
return m_InstanceMap[name].GetObject();
}
/**
* Get the type string for the object with the given name.
*/
const CvQualifiedType& InstanceTable::GetType(const String& name)
{
this->CheckExists(name);
return m_InstanceMap[name].GetCvQualifiedType();
}
/**
* Allow object type deletion functions to be added.
*/
void InstanceTable::SetDeleteFunction(const Type* type,
DeleteFunction func)
{
m_DeleteFunctionMap[type] = func;
}
/**
* Create a unique name for a temporary object, and set the given object
* to have this name. The name chosen is returned.
*/
String InstanceTable::CreateTemporary(void* object,
const CvQualifiedType& type)
{
char tempName[15];
sprintf(tempName, "__temp%x", m_TempNameNumber++);
String name = tempName;
this->SetObject(name, object, type);
return name;
}
/**
* If the given object name was generated by InsertTemporary(), the object
* is deleted.
*/
void InstanceTable::DeleteIfTemporary(const String& name)
{
this->CheckExists(name);
if(name.substr(0,6) == "__temp")
{
this->DeleteObject(name);
}
}
/**
* When an instance deletes itself, this callback is made to remove it from
* the instance table.
*/
void InstanceTable::DeleteCallBack(void* object)
{
if(m_AddressToNameMap.count(object) > 0)
{
String name = m_AddressToNameMap[object];
this->DeleteObject(name);
}
}
/**
* Make sure an object with the given name exists.
* Throw an exception if it doesn't exist.
*/
void InstanceTable::CheckExists(const String& name) const
{
if(!this->Exists(name))
{
throw _wrap_UndefinedInstanceNameException(name);
}
}
/**
* Get an InstanceTable object set up to deal with the given Tcl interpreter.
* If one exists, it will be returned. Otherwise, a new one will be
* created.
*/
InstanceTable* InstanceTable::GetForInterpreter(Tcl_Interp* interp)
{
// See if an InstanceTable exists for the given interpreter.
if(interpreterInstanceTableMap.count(interp) == 0)
{
// No, we must create a new InstanceTable for this interpreter.
interpreterInstanceTableMap[interp] = new InstanceTable(interp);
}
// Return the InstanceTable.
return interpreterInstanceTableMap[interp];
}
/**
* Map from a Tcl interpreter to the InstanceTable for it.
*/
InstanceTable::InterpreterInstanceTableMap InstanceTable::interpreterInstanceTableMap;
} // namespace _wrap_
<commit_msg>ENH: Undefined object type exception call will now report the name of the type.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: wrapInstanceTable.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2000 National Library of Medicine
All rights reserved.
See COPYRIGHT.txt for copyright details.
=========================================================================*/
#include "wrapInstanceTable.h"
#include "wrapException.h"
namespace _wrap_
{
/**
* Constructor takes interpreter to which the InstanceTable will be
* attached. It also initializes the temporary object number to zero.
*/
InstanceTable::InstanceTable(Tcl_Interp* interp):
m_Interpreter(interp),
m_TempNameNumber(0)
{
}
/**
* Set a mapping from "name" to object "object" with type "type".
* This deletes any instance of an object already having the given name.
*/
void InstanceTable::SetObject(const String& name, void* object,
const CvQualifiedType& type)
{
if(this->Exists(name))
{
this->DeleteObject(name);
}
m_InstanceMap[name] = Reference(object, type);
m_AddressToNameMap[object] = name;
}
/**
* Delete the object corresponding to the given name.
* This looks up the function pointer that was registered for the object's
* type, and calls it to do the actual deletion.
*/
void InstanceTable::DeleteObject(const String& name)
{
this->CheckExists(name);
const Type* type = m_InstanceMap[name].GetCvQualifiedType().GetType();
void* object = m_InstanceMap[name].GetObject();
// Make sure we know how to delete this object.
if(m_DeleteFunctionMap.count(type) < 1)
{
throw _wrap_UndefinedObjectTypeException(type->Name());
}
// Remove the object's address from our table.
m_AddressToNameMap.erase(object);
// Call the registered delete function.
m_DeleteFunctionMap[type](object);
// Remove from the instance table.
m_InstanceMap.erase(name);
// Remove the Tcl command for this instance.
Tcl_DeleteCommand(m_Interpreter, const_cast<char*>(name.c_str()));
}
/**
* Check if there is an object with the given name.
*/
bool InstanceTable::Exists(const String& name) const
{
return (m_InstanceMap.count(name) > 0);
}
/**
* Get the Reference holding the object with the given name.
*/
const Reference& InstanceTable::GetEntry(const String& name) const
{
this->CheckExists(name);
InstanceMap::const_iterator i = m_InstanceMap.find(name);
return i->second;
}
/**
* Get a pointer to the object with the given name.
*/
void* InstanceTable::GetObject(const String& name)
{
this->CheckExists(name);
return m_InstanceMap[name].GetObject();
}
/**
* Get the type string for the object with the given name.
*/
const CvQualifiedType& InstanceTable::GetType(const String& name)
{
this->CheckExists(name);
return m_InstanceMap[name].GetCvQualifiedType();
}
/**
* Allow object type deletion functions to be added.
*/
void InstanceTable::SetDeleteFunction(const Type* type,
DeleteFunction func)
{
m_DeleteFunctionMap[type] = func;
}
/**
* Create a unique name for a temporary object, and set the given object
* to have this name. The name chosen is returned.
*/
String InstanceTable::CreateTemporary(void* object,
const CvQualifiedType& type)
{
char tempName[15];
sprintf(tempName, "__temp%x", m_TempNameNumber++);
String name = tempName;
this->SetObject(name, object, type);
return name;
}
/**
* If the given object name was generated by InsertTemporary(), the object
* is deleted.
*/
void InstanceTable::DeleteIfTemporary(const String& name)
{
this->CheckExists(name);
if(name.substr(0,6) == "__temp")
{
this->DeleteObject(name);
}
}
/**
* When an instance deletes itself, this callback is made to remove it from
* the instance table.
*/
void InstanceTable::DeleteCallBack(void* object)
{
if(m_AddressToNameMap.count(object) > 0)
{
String name = m_AddressToNameMap[object];
this->DeleteObject(name);
}
}
/**
* Make sure an object with the given name exists.
* Throw an exception if it doesn't exist.
*/
void InstanceTable::CheckExists(const String& name) const
{
if(!this->Exists(name))
{
throw _wrap_UndefinedInstanceNameException(name);
}
}
/**
* Get an InstanceTable object set up to deal with the given Tcl interpreter.
* If one exists, it will be returned. Otherwise, a new one will be
* created.
*/
InstanceTable* InstanceTable::GetForInterpreter(Tcl_Interp* interp)
{
// See if an InstanceTable exists for the given interpreter.
if(interpreterInstanceTableMap.count(interp) == 0)
{
// No, we must create a new InstanceTable for this interpreter.
interpreterInstanceTableMap[interp] = new InstanceTable(interp);
}
// Return the InstanceTable.
return interpreterInstanceTableMap[interp];
}
/**
* Map from a Tcl interpreter to the InstanceTable for it.
*/
InstanceTable::InterpreterInstanceTableMap InstanceTable::interpreterInstanceTableMap;
} // namespace _wrap_
<|endoftext|> |
<commit_before>/*
* Author: Vladimir Ivan
*
* Copyright (c) 2017, University Of Edinburgh
* 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 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 "task_map/CoM.h"
REGISTER_TASKMAP_TYPE("CoM", exotica::CoM);
namespace exotica
{
CoM::CoM()
{
}
CoM::~CoM()
{
}
void CoM::update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi)
{
if (phi.rows() != dim_) throw_named("Wrong size of phi!");
phi.setZero();
double M = mass_.sum();
if (M == 0.0) return;
KDL::Vector com;
for (int i = 0; i < Kinematics.Phi.rows(); i++)
{
com += Kinematics.Phi(i).p * mass_(i);
if (debug_)
{
com_marker_.points[i].x = Kinematics.Phi(i).p[0];
com_marker_.points[i].y = Kinematics.Phi(i).p[1];
com_marker_.points[i].z = Kinematics.Phi(i).p[2];
}
}
com = com / M;
for (int i = 0; i < dim_; i++) phi(i) = com[i];
if (debug_)
{
COM_marker_.pose.position.x = phi(0);
COM_marker_.pose.position.y = phi(1);
COM_marker_.pose.position.z = phi(2);
COM_marker_.header.stamp = com_marker_.header.stamp = ros::Time::now();
com_pub_.publish(com_marker_);
COM_pub_.publish(COM_marker_);
}
}
void CoM::update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi, Eigen::MatrixXdRef J)
{
if (phi.rows() != dim_) throw_named("Wrong size of phi!");
if (J.rows() != dim_ || J.cols() != Kinematics.J(0).data.cols()) throw_named("Wrong size of J! " << Kinematics.J(0).data.cols());
phi.setZero();
J.setZero();
KDL::Vector com;
double M = mass_.sum();
if (M == 0.0) return;
for (int i = 0; i < Kinematics.Phi.rows(); i++)
{
com += Kinematics.Phi(i).p * mass_(i);
J += mass_(i) / M * Kinematics.J(i).data.topRows(dim_);
if (debug_)
{
com_marker_.points[i].x = Kinematics.Phi(i).p[0];
com_marker_.points[i].y = Kinematics.Phi(i).p[1];
com_marker_.points[i].z = Kinematics.Phi(i).p[2];
}
}
com = com / M;
for (int i = 0; i < dim_; i++) phi(i) = com[i];
if (debug_)
{
COM_marker_.pose.position.x = phi(0);
COM_marker_.pose.position.y = phi(1);
COM_marker_.pose.position.z = phi(2);
COM_marker_.header.stamp = com_marker_.header.stamp = ros::Time::now();
com_pub_.publish(com_marker_);
COM_pub_.publish(COM_marker_);
}
}
int CoM::taskSpaceDim()
{
return dim_;
}
void CoM::Initialize()
{
enable_z_ = init_.EnableZ;
if (enable_z_)
dim_ = 3;
else
dim_ = 2;
if (Frames.size() > 0)
{
if (debug_)
HIGHLIGHT_NAMED("CoM", "Initialisation with " << Frames.size() << " passed into map.");
mass_.resize(Frames.size());
for (int i = 0; i < Frames.size(); i++)
{
if (Frames[i].FrameBLinkName != "")
{
throw_named("Requesting CoM frame with base other than root! '" << Frames[i].FrameALinkName << "'");
}
Frames[i].FrameALinkName = scene_->getSolver().getTreeMap()[Frames[i].FrameALinkName]->Segment.getName();
Frames[i].FrameAOffset.p = scene_->getSolver().getTreeMap()[Frames[i].FrameALinkName]->Segment.getInertia().getCOG();
mass_(i) = scene_->getSolver().getTreeMap()[Frames[i].FrameALinkName]->Segment.getInertia().getMass();
}
}
else
{
int N = scene_->getSolver().getTree().size();
mass_.resize(N);
Frames.resize(N);
if (debug_)
HIGHLIGHT_NAMED("CoM", "Initialisation for tree of size "
<< Frames.size());
for (int i = 0; i < N; i++)
{
Frames[i].FrameALinkName = scene_->getSolver().getTree()[i]->Segment.getName();
Frames[i].FrameAOffset.p = scene_->getSolver().getTree()[i]->Segment.getInertia().getCOG();
mass_(i) = scene_->getSolver().getTree()[i]->Segment.getInertia().getMass();
if (debug_)
HIGHLIGHT_NAMED("CoM-Initialize",
"FrameALinkName: "
<< Frames[i].FrameALinkName
<< ", mass: " << mass_(i) << ", CoG: ("
<< Frames[i].FrameAOffset.p.x() << ", "
<< Frames[i].FrameAOffset.p.y() << ", "
<< Frames[i].FrameAOffset.p.z() << ")");
}
}
if (debug_)
{
InitDebug();
HIGHLIGHT_NAMED("CoM", "Total model mass: " << mass_.sum() << " kg");
}
}
void CoM::assignScene(Scene_ptr scene)
{
scene_ = scene;
Initialize();
}
void CoM::Instantiate(CoMInitializer& init)
{
init_ = init;
}
void CoM::InitDebug()
{
com_marker_.points.resize(Frames.size());
com_marker_.type = visualization_msgs::Marker::SPHERE_LIST;
com_marker_.color.a = .7;
com_marker_.color.r = 0.5;
com_marker_.color.g = 0;
com_marker_.color.b = 0;
com_marker_.scale.x = com_marker_.scale.y = com_marker_.scale.z = .02;
com_marker_.action = visualization_msgs::Marker::ADD;
COM_marker_.type = visualization_msgs::Marker::CYLINDER;
COM_marker_.color.a = 1;
COM_marker_.color.r = 1;
COM_marker_.color.g = 0;
COM_marker_.color.b = 0;
COM_marker_.scale.x = COM_marker_.scale.y = .15;
COM_marker_.scale.z = .02;
COM_marker_.action = visualization_msgs::Marker::ADD;
com_marker_.header.frame_id = COM_marker_.header.frame_id =
"exotica/" + scene_->getRootFrameName();
com_pub_ = Server::advertise<visualization_msgs::Marker>(
object_name_ + "/coms_marker", 1, true);
COM_pub_ = Server::advertise<visualization_msgs::Marker>(
object_name_ + "/COM_marker", 1, true);
}
}
<commit_msg>Removed setZero<commit_after>/*
* Author: Vladimir Ivan
*
* Copyright (c) 2017, University Of Edinburgh
* 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 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 "task_map/CoM.h"
REGISTER_TASKMAP_TYPE("CoM", exotica::CoM);
namespace exotica
{
CoM::CoM()
{
}
CoM::~CoM()
{
}
void CoM::update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi)
{
if (phi.rows() != dim_) throw_named("Wrong size of phi!");
double M = mass_.sum();
if (M == 0.0) return;
KDL::Vector com;
for (int i = 0; i < Kinematics.Phi.rows(); i++)
{
com += Kinematics.Phi(i).p * mass_(i);
if (debug_)
{
com_marker_.points[i].x = Kinematics.Phi(i).p[0];
com_marker_.points[i].y = Kinematics.Phi(i).p[1];
com_marker_.points[i].z = Kinematics.Phi(i).p[2];
}
}
com = com / M;
for (int i = 0; i < dim_; i++) phi(i) = com[i];
if (debug_)
{
COM_marker_.pose.position.x = phi(0);
COM_marker_.pose.position.y = phi(1);
COM_marker_.pose.position.z = phi(2);
COM_marker_.header.stamp = com_marker_.header.stamp = ros::Time::now();
com_pub_.publish(com_marker_);
COM_pub_.publish(COM_marker_);
}
}
void CoM::update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi, Eigen::MatrixXdRef J)
{
if (phi.rows() != dim_) throw_named("Wrong size of phi!");
if (J.rows() != dim_ || J.cols() != Kinematics.J(0).data.cols()) throw_named("Wrong size of J! " << Kinematics.J(0).data.cols());
J.setZero();
KDL::Vector com;
double M = mass_.sum();
if (M == 0.0) return;
for (int i = 0; i < Kinematics.Phi.rows(); i++)
{
com += Kinematics.Phi(i).p * mass_(i);
J += mass_(i) / M * Kinematics.J(i).data.topRows(dim_);
if (debug_)
{
com_marker_.points[i].x = Kinematics.Phi(i).p[0];
com_marker_.points[i].y = Kinematics.Phi(i).p[1];
com_marker_.points[i].z = Kinematics.Phi(i).p[2];
}
}
com = com / M;
for (int i = 0; i < dim_; i++) phi(i) = com[i];
if (debug_)
{
COM_marker_.pose.position.x = phi(0);
COM_marker_.pose.position.y = phi(1);
COM_marker_.pose.position.z = phi(2);
COM_marker_.header.stamp = com_marker_.header.stamp = ros::Time::now();
com_pub_.publish(com_marker_);
COM_pub_.publish(COM_marker_);
}
}
int CoM::taskSpaceDim()
{
return dim_;
}
void CoM::Initialize()
{
enable_z_ = init_.EnableZ;
if (enable_z_)
dim_ = 3;
else
dim_ = 2;
if (Frames.size() > 0)
{
if (debug_)
HIGHLIGHT_NAMED("CoM", "Initialisation with " << Frames.size() << " passed into map.");
mass_.resize(Frames.size());
for (int i = 0; i < Frames.size(); i++)
{
if (Frames[i].FrameBLinkName != "")
{
throw_named("Requesting CoM frame with base other than root! '" << Frames[i].FrameALinkName << "'");
}
Frames[i].FrameALinkName = scene_->getSolver().getTreeMap()[Frames[i].FrameALinkName]->Segment.getName();
Frames[i].FrameAOffset.p = scene_->getSolver().getTreeMap()[Frames[i].FrameALinkName]->Segment.getInertia().getCOG();
mass_(i) = scene_->getSolver().getTreeMap()[Frames[i].FrameALinkName]->Segment.getInertia().getMass();
}
}
else
{
int N = scene_->getSolver().getTree().size();
mass_.resize(N);
Frames.resize(N);
if (debug_)
HIGHLIGHT_NAMED("CoM", "Initialisation for tree of size "
<< Frames.size());
for (int i = 0; i < N; i++)
{
Frames[i].FrameALinkName = scene_->getSolver().getTree()[i]->Segment.getName();
Frames[i].FrameAOffset.p = scene_->getSolver().getTree()[i]->Segment.getInertia().getCOG();
mass_(i) = scene_->getSolver().getTree()[i]->Segment.getInertia().getMass();
if (debug_)
HIGHLIGHT_NAMED("CoM-Initialize",
"FrameALinkName: "
<< Frames[i].FrameALinkName
<< ", mass: " << mass_(i) << ", CoG: ("
<< Frames[i].FrameAOffset.p.x() << ", "
<< Frames[i].FrameAOffset.p.y() << ", "
<< Frames[i].FrameAOffset.p.z() << ")");
}
}
if (debug_)
{
InitDebug();
HIGHLIGHT_NAMED("CoM", "Total model mass: " << mass_.sum() << " kg");
}
}
void CoM::assignScene(Scene_ptr scene)
{
scene_ = scene;
Initialize();
}
void CoM::Instantiate(CoMInitializer& init)
{
init_ = init;
}
void CoM::InitDebug()
{
com_marker_.points.resize(Frames.size());
com_marker_.type = visualization_msgs::Marker::SPHERE_LIST;
com_marker_.color.a = .7;
com_marker_.color.r = 0.5;
com_marker_.color.g = 0;
com_marker_.color.b = 0;
com_marker_.scale.x = com_marker_.scale.y = com_marker_.scale.z = .02;
com_marker_.action = visualization_msgs::Marker::ADD;
COM_marker_.type = visualization_msgs::Marker::CYLINDER;
COM_marker_.color.a = 1;
COM_marker_.color.r = 1;
COM_marker_.color.g = 0;
COM_marker_.color.b = 0;
COM_marker_.scale.x = COM_marker_.scale.y = .15;
COM_marker_.scale.z = .02;
COM_marker_.action = visualization_msgs::Marker::ADD;
com_marker_.header.frame_id = COM_marker_.header.frame_id =
"exotica/" + scene_->getRootFrameName();
com_pub_ = Server::advertise<visualization_msgs::Marker>(
object_name_ + "/coms_marker", 1, true);
COM_pub_ = Server::advertise<visualization_msgs::Marker>(
object_name_ + "/COM_marker", 1, true);
}
}
<|endoftext|> |
<commit_before>#include "nxtFlashTool.h"
using namespace qReal;
using namespace gui;
NxtFlashTool::NxtFlashTool(ErrorReporter *errorReporter)
: mErrorReporter(errorReporter), mUploadState(done)
{
QProcessEnvironment environment;
environment.insert("QREALDIR", qApp->applicationDirPath());
environment.insert("DISPLAY", ":0.0");
mFlashProcess.setProcessEnvironment(environment);
mUploadProcess.setProcessEnvironment(environment);
// for debug
// mUploadProcess.setStandardErrorFile("/home/me/downloads/incoming/errors");
// mUploadProcess.setStandardOutputFile("/home/me/downloads/incoming/out");
connect(&mFlashProcess, SIGNAL(readyRead()), this, SLOT(readNxtFlashData()));
connect(&mFlashProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(error(QProcess::ProcessError)));
connect(&mFlashProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(nxtFlashingFinished(int, QProcess::ExitStatus)));
connect(&mUploadProcess, SIGNAL(readyRead()), this, SLOT(readNxtUploadData()));
connect(&mUploadProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(error(QProcess::ProcessError)));
connect(&mUploadProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(nxtUploadingFinished(int, QProcess::ExitStatus)));
}
void NxtFlashTool::flashRobot()
{
#ifdef Q_OS_WIN
mFlashProcess.start(qApp->applicationDirPath() + "/nxt-tools/flash.bat");
#else
mFlashProcess.start("sh", QStringList() << qApp->applicationDirPath() + "/nxt-tools/flash.sh");
#endif
mErrorReporter->addInformation("Firmware flash started. Please don't disconnect robot during the process");
emit showErrors(mErrorReporter);
}
void NxtFlashTool::error(QProcess::ProcessError error)
{
qDebug() << "error:" << error;
mErrorReporter->addInformation("Some error occured. Make sure you are running QReal with superuser privileges");
emit showErrors(mErrorReporter);
}
void NxtFlashTool::nxtFlashingFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
qDebug() << "finished with code " << exitCode << ", status: " << exitStatus;
if (exitCode == 0)
mErrorReporter->addInformation("Flashing process completed.");
else if (exitCode == 127)
mErrorReporter->addError("flash.sh not found. Make sure it is present in QReal installation directory");
else if (exitCode == 139)
mErrorReporter->addError("QReal requires superuser privileges to flash NXT robot");
emit showErrors(mErrorReporter);
}
void NxtFlashTool::readNxtFlashData()
{
QStringList output = QString(mFlashProcess.readAll()).split("\n", QString::SkipEmptyParts);
qDebug() << "exit code:" << mFlashProcess.exitCode();
qDebug() << output;
foreach (QString error, output){
if (error == "NXT not found. Is it properly plugged in via USB?")
mErrorReporter->addError("NXT not found. Check USB connection and make sure the robot is ON");
else if (error == "NXT found, but not running in reset mode.")
mErrorReporter->addError("NXT is not in reset mode. Please reset your NXT manually and try again");
else if (error == "Firmware flash complete.")
mErrorReporter->addInformation("Firmware flash complete!");
}
emit showErrors(mErrorReporter);
}
void NxtFlashTool::uploadProgram()
{
#ifdef Q_OS_WIN
mFlashProcess.start(qApp->applicationDirPath() + "/nxt-tools/upload.bat");
#else
mUploadProcess.start("sh", QStringList() << qApp->applicationDirPath() + "/nxt-tools/upload.sh");
#endif
mErrorReporter->addInformation("Uploading program started. Please don't disconnect robot during the process");
emit showErrors(mErrorReporter);
}
void NxtFlashTool::nxtUploadingFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
qDebug() << "finished uploading with code " << exitCode << ", status: " << exitStatus;
if (exitCode == 127) // most likely wineconsole didn't start and generate files needed to proceed compilation
mErrorReporter->addError("Uploading failed. Make sure that X-server allows root to run GUI applications");
else if (exitCode == 139)
mErrorReporter->addError("QReal requires superuser privileges to flash NXT robot");
emit showErrors(mErrorReporter);
}
void NxtFlashTool::readNxtUploadData()
{
QStringList output = QString(mUploadProcess.readAll()).split("\n", QString::SkipEmptyParts);
qDebug() << "exit code:" << mUploadProcess.exitCode();
qDebug() << output;
/* each command produces its own output, so thousands of 'em. using UploadState enum
to determine in which state we are (to show appropriate error if something goes wrong)
*/
foreach (QString error, output){
if (error.contains("Removing "))
mUploadState = clean;
else if (error.contains("Compiling "))
mUploadState = compile;
else if (error.contains("Generating binary image file"))
mUploadState = link;
else if (error.contains("Executing NeXTTool to upload"))
mUploadState = uploadStart;
else if (error.contains("_OSEK.rxe="))
mUploadState = flash;
else if (error.contains("NeXTTool is terminated")) {
if (mUploadState == uploadStart)
mErrorReporter->addError("Could not upload program. Make sure the robot is connected and ON");
else if (mUploadState == flash)
mErrorReporter->addInformation("Uploading completed successfully");
mUploadState = done;
}
else if (error.contains("An unhandled exception occurred")) {
mErrorReporter->addError("QReal requires superuser privileges to upload programs on NXT robot");
break;
}
}
qDebug() << mUploadState;
emit showErrors(mErrorReporter);
}
<commit_msg>Fixes for Windows build and flash of robot program<commit_after>#include "nxtFlashTool.h"
using namespace qReal;
using namespace gui;
NxtFlashTool::NxtFlashTool(ErrorReporter *errorReporter)
: mErrorReporter(errorReporter), mUploadState(done)
{
QProcessEnvironment environment(QProcessEnvironment::systemEnvironment());
environment.insert("QREALDIR", qApp->applicationDirPath());
environment.insert("DISPLAY", ":0.0");
mFlashProcess.setProcessEnvironment(environment);
mUploadProcess.setProcessEnvironment(environment);
// for debug
// mUploadProcess.setStandardErrorFile("/home/me/downloads/incoming/errors");
// mUploadProcess.setStandardOutputFile("/home/me/downloads/incoming/out");
connect(&mFlashProcess, SIGNAL(readyRead()), this, SLOT(readNxtFlashData()));
connect(&mFlashProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(error(QProcess::ProcessError)));
connect(&mFlashProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(nxtFlashingFinished(int, QProcess::ExitStatus)));
connect(&mUploadProcess, SIGNAL(readyRead()), this, SLOT(readNxtUploadData()));
connect(&mUploadProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(error(QProcess::ProcessError)));
connect(&mUploadProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(nxtUploadingFinished(int, QProcess::ExitStatus)));
}
void NxtFlashTool::flashRobot()
{
#ifdef Q_OS_WIN
mFlashProcess.start(qApp->applicationDirPath() + "/nxt-tools/flash.bat");
#else
mFlashProcess.start("sh", QStringList() << qApp->applicationDirPath() + "/nxt-tools/flash.sh");
#endif
mErrorReporter->addInformation("Firmware flash started. Please don't disconnect robot during the process");
emit showErrors(mErrorReporter);
}
void NxtFlashTool::error(QProcess::ProcessError error)
{
qDebug() << "error:" << error;
mErrorReporter->addInformation("Some error occured. Make sure you are running QReal with superuser privileges");
emit showErrors(mErrorReporter);
}
void NxtFlashTool::nxtFlashingFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
qDebug() << "finished with code " << exitCode << ", status: " << exitStatus;
if (exitCode == 0)
mErrorReporter->addInformation("Flashing process completed.");
else if (exitCode == 127)
mErrorReporter->addError("flash.sh not found. Make sure it is present in QReal installation directory");
else if (exitCode == 139)
mErrorReporter->addError("QReal requires superuser privileges to flash NXT robot");
emit showErrors(mErrorReporter);
}
void NxtFlashTool::readNxtFlashData()
{
QStringList output = QString(mFlashProcess.readAll()).split("\n", QString::SkipEmptyParts);
qDebug() << "exit code:" << mFlashProcess.exitCode();
qDebug() << output;
foreach (QString error, output){
if (error == "NXT not found. Is it properly plugged in via USB?")
mErrorReporter->addError("NXT not found. Check USB connection and make sure the robot is ON");
else if (error == "NXT found, but not running in reset mode.")
mErrorReporter->addError("NXT is not in reset mode. Please reset your NXT manually and try again");
else if (error == "Firmware flash complete.")
mErrorReporter->addInformation("Firmware flash complete!");
}
emit showErrors(mErrorReporter);
}
void NxtFlashTool::uploadProgram()
{
#ifdef Q_OS_WIN
mFlashProcess.start("cmd", QStringList() << "/C" << qApp->applicationDirPath() + "/nxt-tools/upload.bat");
#else
mUploadProcess.start("sh", QStringList() << qApp->applicationDirPath() + "/nxt-tools/upload.sh");
#endif
mErrorReporter->addInformation("Uploading program started. Please don't disconnect robot during the process");
emit showErrors(mErrorReporter);
}
void NxtFlashTool::nxtUploadingFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
qDebug() << "finished uploading with code " << exitCode << ", status: " << exitStatus;
if (exitCode == 127) // most likely wineconsole didn't start and generate files needed to proceed compilation
mErrorReporter->addError("Uploading failed. Make sure that X-server allows root to run GUI applications");
else if (exitCode == 139)
mErrorReporter->addError("QReal requires superuser privileges to flash NXT robot");
emit showErrors(mErrorReporter);
}
void NxtFlashTool::readNxtUploadData()
{
QStringList output = QString(mUploadProcess.readAll()).split("\n", QString::SkipEmptyParts);
qDebug() << "exit code:" << mUploadProcess.exitCode();
qDebug() << output;
/* each command produces its own output, so thousands of 'em. using UploadState enum
to determine in which state we are (to show appropriate error if something goes wrong)
*/
foreach (QString error, output){
if (error.contains("Removing "))
mUploadState = clean;
else if (error.contains("Compiling "))
mUploadState = compile;
else if (error.contains("Generating binary image file"))
mUploadState = link;
else if (error.contains("Executing NeXTTool to upload"))
mUploadState = uploadStart;
else if (error.contains("_OSEK.rxe="))
mUploadState = flash;
else if (error.contains("NeXTTool is terminated")) {
if (mUploadState == uploadStart)
mErrorReporter->addError("Could not upload program. Make sure the robot is connected and ON");
else if (mUploadState == flash)
mErrorReporter->addInformation("Uploading completed successfully");
mUploadState = done;
}
else if (error.contains("An unhandled exception occurred")) {
mErrorReporter->addError("QReal requires superuser privileges to upload programs on NXT robot");
break;
}
}
qDebug() << mUploadState;
emit showErrors(mErrorReporter);
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_recovery_ffdc_base.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
#ifndef __P9_PM_RECOVERY_BASE_
#define __P9_PM_RECOVERY_BASE_
///
/// @file p9_stop_ffdc_base.H
/// @brief Models generic platform for the FFDC collection of PM complex
///
/// *HWP HWP Owner: Greg Still <[email protected]>
/// *HWP FW Owner: Prem S Jha <[email protected]>
/// *HWP Team: PM
/// *HWP Level: 2
/// *HWP Consumed by: Hostboot:Phyp
//
// *INDENT-OFF*
//--------------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------------
#include <fapi2.H>
#include <stdint.h>
#include <p9_hcd_memmap_cme_sram.H>
#include <p9_hcd_memmap_occ_sram.H>
#include <p9_pm_recovery_ffdc_defines.H>
#include <p9_pm_ocb_indir_access.H>
#include <p9_cme_sram_access.H>
#include <p9_pm_ocb_indir_setup_linear.H>
#include <p9_ppe_utils.H>
namespace p9_stop_recov_ffdc
{
class PlatPmComplex
{
public:
/// @brief constructor
/// @param[in] i_procChipTgt fapi2 target for P9 chip
/// @param[in] i_imageHdrBaseAddr sram address of start of image header
/// @param[in] i_traceBufBaseAddr sram address of start of trace buffer
/// @param[in] i_globalBaseAddr sram address of start of global variables
/// @param[in] i_plat platform id
PlatPmComplex( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > i_procChipTgt,
uint32_t i_imageHdrBaseAddr, uint32_t i_traceBufBaseAddr,
uint32_t i_globalBaseAddr,
PmComplexPlatId i_plat );
/// @brief destructor
virtual ~PlatPmComplex() { };
/// @brief collects category of FFDC common for all platforms in PM complex.
/// @param[in] i_pHomerBuf points to base of P9 HOMER.
// @return fapi2 return code.
virtual fapi2::ReturnCode collectFfdc( void* i_pHomerBuf );
/// @brief sets start address of platform's trace buffer.
void setTraceBufAddr (uint32_t i_addr)
{ iv_traceBufBaseAddress = i_addr; }
///@brief returns instance id.
PmComplexPlatId getPlatId() { return iv_plat ; }
/// @brief returns proc chip target associated with platform
fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > getProcChip() const { return iv_procChip; }
protected:
///@brief reads the PPE Halt State from XSR, w/o halting the PPE
///@param[in] i_xirBaseAddress XCR SCOM Address of the PPE
///@param[out] o_haltCondition p9_stop_recov_ffdc::PpeHaltCondition
///@return fapi2 return code
fapi2::ReturnCode readPpeHaltState (
const uint64_t i_xirBaseAddress,
uint8_t& o_haltCondition );
///@brief collects PPE State (XIRs, SPRs, GPRs) to a loc in HOMER
///@param[in] i_xirBaseAddress XCR SCOM Address of the PPE
///@param[in] i_pHomerOffset PPE section base address in HOMER
///@param[in] i_mode PPE_DUMP_MODE, defaults to HALT
///@return fapi2 return code
fapi2::ReturnCode collectPpeState (
const uint64_t i_xirBaseAddress,
const uint8_t* i_pHomerOffset,
const PPE_DUMP_MODE i_mode = HALT );
///@brief collects FFDC from CME/OCC SRAM
///@param[in] i_chipletTarget fapi2 target for EX or Proc
///@param[in] i_pSramData points to HOMER location containing SRAM contents
///@param[in] i_dataType type of FFDC data
///@param[in] i_sramLength length of SRAM FFDC in bytes
///@return fapi2 return code
fapi2::ReturnCode collectSramInfo( const fapi2::Target< fapi2::TARGET_TYPE_EX >& i_exTgt,
uint8_t * i_pSramData,
FfdcDataType i_dataType,
uint32_t i_sramLength );
fapi2::ReturnCode collectSramInfo( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > & i_procChip,
uint8_t * i_pSramData,
FfdcDataType i_dataType,
uint32_t i_sramLength );
///@brief updates parts of PPE FFDC Header common for all platforms.
///param[in] i_pFfdcHdr points to the PPE FFDC header
///param[in] i_ffdcValid bit vector summarizing FFDC validity
///param[in] i_haltState FFDC halt state
///@note refer to PPE Spec for halt state description.
fapi2::ReturnCode updatePpeFfdcHeader( PpeFfdcHeader * i_pFfdcHdr,
uint8_t i_ffdcValid, uint8_t i_haltState );
#ifndef __HOSTBOOT_MODULE
///@brief to debug FFDC contents collected from SRAM.
///param[in] i_pSram points to location of SRAM info in HOMER.
///param[in] i_len length of info.
///@return fapi2 return code
fapi2::ReturnCode debugSramInfo( uint8_t * i_pSram, uint32_t i_len );
#endif
private:
fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > iv_procChip; // processor chip target
uint32_t iv_imageHeaderBaseAddress; // base address of platform's image header
uint32_t iv_traceBufBaseAddress; // base address of platforms's trace buffer
uint32_t iv_globalBaseAddress; // base address of platform's global variables
PmComplexPlatId iv_plat;
};
} //namespace p9_stop_recov_ffdc ends
#endif //__P9_PM_RECOVERY_BASE_
<commit_msg>PM Recovery FFDC: Added support to collect Register data for PPM<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_recovery_ffdc_base.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
#ifndef __P9_PM_RECOVERY_BASE_
#define __P9_PM_RECOVERY_BASE_
///
/// @file p9_stop_ffdc_base.H
/// @brief Models generic platform for the FFDC collection of PM complex
///
/// *HWP HWP Owner: Greg Still <[email protected]>
/// *HWP FW Owner: Prem S Jha <[email protected]>
/// *HWP Team: PM
/// *HWP Level: 2
/// *HWP Consumed by: Hostboot:Phyp
//
// *INDENT-OFF*
//--------------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------------
#include <fapi2.H>
#include <collect_reg_ffdc.H>
#include <stdint.h>
#include <p9_hcd_memmap_cme_sram.H>
#include <p9_hcd_memmap_occ_sram.H>
#include <p9_pm_recovery_ffdc_defines.H>
#include <p9_pm_ocb_indir_access.H>
#include <p9_cme_sram_access.H>
#include <p9_pm_ocb_indir_setup_linear.H>
#include <p9_ppe_utils.H>
namespace p9_stop_recov_ffdc
{
class PlatPmComplex
{
public:
/// @brief constructor
/// @param[in] i_procChipTgt fapi2 target for P9 chip
/// @param[in] i_imageHdrBaseAddr sram address of start of image header
/// @param[in] i_traceBufBaseAddr sram address of start of trace buffer
/// @param[in] i_globalBaseAddr sram address of start of global variables
/// @param[in] i_plat platform id
PlatPmComplex( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > i_procChipTgt,
uint32_t i_imageHdrBaseAddr, uint32_t i_traceBufBaseAddr,
uint32_t i_globalBaseAddr,
PmComplexPlatId i_plat );
/// @brief destructor
virtual ~PlatPmComplex() { };
/// @brief collects category of FFDC common for all platforms in PM complex.
/// @param[in] i_pHomerBuf points to base of P9 HOMER.
// @return fapi2 return code.
virtual fapi2::ReturnCode collectFfdc( void* i_pHomerBuf );
/// @brief sets start address of platform's trace buffer.
void setTraceBufAddr (uint32_t i_addr)
{ iv_traceBufBaseAddress = i_addr; }
///@brief returns instance id.
PmComplexPlatId getPlatId() { return iv_plat ; }
/// @brief returns proc chip target associated with platform
fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > getProcChip() const { return iv_procChip; }
protected:
///@brief reads the PPE Halt State from XSR, w/o halting the PPE
///@param[in] i_xirBaseAddress XCR SCOM Address of the PPE
///@param[out] o_haltCondition p9_stop_recov_ffdc::PpeHaltCondition
///@return fapi2 return code
fapi2::ReturnCode readPpeHaltState (
const uint64_t i_xirBaseAddress,
uint8_t& o_haltCondition );
///@brief collects PPE State (XIRs, SPRs, GPRs) to a loc in HOMER
///@param[in] i_xirBaseAddress XCR SCOM Address of the PPE
///@param[in] i_pHomerOffset PPE section base address in HOMER
///@param[in] i_mode PPE_DUMP_MODE, defaults to HALT
///@return fapi2 return code
fapi2::ReturnCode collectPpeState (
const uint64_t i_xirBaseAddress,
const uint8_t* i_pHomerOffset,
const PPE_DUMP_MODE i_mode = HALT );
///@brief collects FFDC from CME/OCC SRAM
///@param[in] i_chipletTarget fapi2 target for EX or Proc
///@param[in] i_pSramData points to HOMER location containing SRAM contents
///@param[in] i_dataType type of FFDC data
///@param[in] i_sramLength length of SRAM FFDC in bytes
///@return fapi2 return code
fapi2::ReturnCode collectSramInfo( const fapi2::Target< fapi2::TARGET_TYPE_EX >& i_exTgt,
uint8_t * i_pSramData,
FfdcDataType i_dataType,
uint32_t i_sramLength );
fapi2::ReturnCode collectSramInfo( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > & i_procChip,
uint8_t * i_pSramData,
FfdcDataType i_dataType,
uint32_t i_sramLength );
///@brief Collects register data
///param[in] i_chipletTarget Chip/chilpet target
///param[out] o_pHomerBuf Homer base address to fill register
// data
// param[in] i_ffdcId Hwp ffdc id to know register
// collection type
///@return fapi2 return code
template<fapi2::TargetType T>
fapi2::ReturnCode collectRegisterData( const fapi2::Target<T>& i_chipletTarget,
uint8_t* o_pHomerBuf,
fapi2::HwpFfdcId i_ffdcId);
///@brief updates parts of PPE FFDC Header common for all platforms.
///param[in] i_pFfdcHdr points to the PPE FFDC header
///param[in] i_ffdcValid bit vector summarizing FFDC validity
///param[in] i_haltState FFDC halt state
///@note refer to PPE Spec for halt state description.
fapi2::ReturnCode updatePpeFfdcHeader( PpeFfdcHeader * i_pFfdcHdr,
uint8_t i_ffdcValid, uint8_t i_haltState );
#ifndef __HOSTBOOT_MODULE
///@brief to debug FFDC contents collected from SRAM.
///param[in] i_pSram points to location of SRAM info in HOMER.
///param[in] i_len length of info.
///@return fapi2 return code
fapi2::ReturnCode debugSramInfo( uint8_t * i_pSram, uint32_t i_len );
#endif
private:
fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > iv_procChip; // processor chip target
uint32_t iv_imageHeaderBaseAddress; // base address of platform's image header
uint32_t iv_traceBufBaseAddress; // base address of platforms's trace buffer
uint32_t iv_globalBaseAddress; // base address of platform's global variables
PmComplexPlatId iv_plat;
};
template<fapi2::TargetType T>
fapi2::ReturnCode PlatPmComplex::collectRegisterData(const fapi2::Target<T>& i_chipletTarget,
uint8_t *o_pHomerBuf,
fapi2::HwpFfdcId i_ffdcId)
{
FAPI_DBG(">> collectRegisterData");
std::vector<uint32_t> l_cfamAddresses;
std::vector<uint64_t> l_scomAddresses;
uint32_t l_ffdcRegReadSize = 0;
uint32_t l_offset = 0;
fapi2::ScomReader<T> l_scomReader(i_chipletTarget);
fapi2::getAddressData(i_ffdcId, l_scomAddresses, l_cfamAddresses, l_ffdcRegReadSize);
FAPI_TRY((fapi2::collectRegisterAndAddressData<uint64_t,
fapi2::ScomReader<T> >(l_scomAddresses, l_scomReader,
l_offset, o_pHomerBuf)),
"Failed in collectRegisterAndAddressData");
fapi_try_exit:
FAPI_DBG("<< collectRegisterData");
return fapi2::current_err;
}
} //namespace p9_stop_recov_ffdc ends
#endif //__P9_PM_RECOVERY_BASE_
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016-2018 metaverse core developers (see MVS-AUTHORS).
* Copyright (C) 2013, 2016 Swirly Cloud Limited.
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include <cctype>
#include <jsoncpp/json/json.h>
#include <metaverse/mgbubble/Mongoose.hpp>
#include <metaverse/mgbubble/utility/Tokeniser.hpp>
#include <metaverse/explorer/extensions/exception.hpp>
namespace mgbubble {
void HttpMessage::data_to_arg(uint8_t rpc_version) {
auto vargv_to_argv = [this]() {
// convert to char** argv
int i = 0;
for(auto& iter : this->vargv_){
if (i >= max_paramters){
break;
}
this->argv_[i++] = iter.c_str();
}
argc_ = i;
};
Json::Reader reader;
Json::Value root;
const char* begin = body().data();
const char* end = body().data() + body().size();
if (!reader.parse(begin, end, root) || !root.isObject()) {
throw libbitcoin::explorer::jsonrpc_parse_error();
}
if (root["method"].isString()) {
vargv_.emplace_back(root["method"].asString());
}
if (root.isMember("params") && !root["params"].isArray()) {
throw libbitcoin::explorer::jsonrpc_invalid_params();
}
if (rpc_version == 1) {
/* ***************** /rpc **********************
* application/json
* {"method":"xxx", "params":["p1","p2"]}
* ******************************************/
for (auto& param : root["params"]) {
if (!param.isObject())
vargv_.emplace_back(param.asString());
}
} else {
/* ***************** /rpc/v2 **********************
* application/json
* {
* "method":"xxx",
* "params":[
* {
* k1:v1, ==> Command Option
* k2:v2
* },
* "p1", ==> Command Argument
* "p2"
* ]
* }
* ******************************************/
if (root["jsonrpc"].asString() != "2.0") {
throw libbitcoin::explorer::jsonrpc_invalid_request();
}
if (root["id"].isString()) {
jsonrpc_id_ = std::stol(root["id"].asString());
} else {
jsonrpc_id_ = root["id"].asInt64();
}
// push options
for (auto& param : root["params"]) {
if (param.isObject()) {
for (auto& key : param.getMemberNames()) {
// --option
vargv_.emplace_back("--" + key);
// value
if (!param[key].isNull()) {
vargv_.emplace_back(param[key].asString());
}
}
break;
}
}
// push arguments at last
for (auto& param : root["params"]) {
if (!param.isObject()){
vargv_.emplace_back(param.asString());
}
}
}
vargv_to_argv();
}
void WebsocketMessage::data_to_arg(uint8_t api_version) {
Tokeniser<' '> args;
args.reset(+*impl_);
// store args from ws message
do {
//skip spaces
if (args.top().front() == ' '){
args.pop();
continue;
} else if (std::iscntrl(args.top().front())){
break;
} else {
this->vargv_.push_back({args.top().data(), args.top().size()});
args.pop();
}
}while(!args.empty());
// convert to char** argv
int i = 0;
for(auto& iter : vargv_){
if (i >= max_paramters){
break;
}
argv_[i++] = iter.c_str();
}
argc_ = i;
}
void ToCommandArg::add_arg(std::string&& outside)
{
vargv_.push_back(outside);
argc_++;
}
} // mgbubble
<commit_msg>fix issue #255 : sendmore can not send to multiple receivers in json-rpc calling<commit_after>/*
* Copyright (c) 2016-2018 metaverse core developers (see MVS-AUTHORS).
* Copyright (C) 2013, 2016 Swirly Cloud Limited.
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include <cctype>
#include <jsoncpp/json/json.h>
#include <metaverse/mgbubble/Mongoose.hpp>
#include <metaverse/mgbubble/utility/Tokeniser.hpp>
#include <metaverse/explorer/extensions/exception.hpp>
namespace mgbubble {
void HttpMessage::data_to_arg(uint8_t rpc_version) {
auto vargv_to_argv = [this]() {
// convert to char** argv
int i = 0;
for(auto& iter : this->vargv_){
if (i >= max_paramters){
break;
}
this->argv_[i++] = iter.c_str();
}
argc_ = i;
};
Json::Reader reader;
Json::Value root;
const char* begin = body().data();
const char* end = body().data() + body().size();
if (!reader.parse(begin, end, root) || !root.isObject()) {
throw libbitcoin::explorer::jsonrpc_parse_error();
}
if (root["method"].isString()) {
vargv_.emplace_back(root["method"].asString());
}
if (root.isMember("params") && !root["params"].isArray()) {
throw libbitcoin::explorer::jsonrpc_invalid_params();
}
if (rpc_version == 1) {
/* ***************** /rpc **********************
* application/json
* {"method":"xxx", "params":["p1","p2"]}
* ******************************************/
for (auto& param : root["params"]) {
if (!param.isObject())
vargv_.emplace_back(param.asString());
}
} else {
/* ***************** /rpc/v2 **********************
* application/json
* {
* "method":"xxx",
* "params":[
* {
* k1:v1, ==> Command Option
* k2:v2
* },
* "p1", ==> Command Argument
* "p2"
* ]
* }
* ******************************************/
if (root["jsonrpc"].asString() != "2.0") {
throw libbitcoin::explorer::jsonrpc_invalid_request();
}
if (root["id"].isString()) {
jsonrpc_id_ = std::stol(root["id"].asString());
} else {
jsonrpc_id_ = root["id"].asInt64();
}
// push options
for (auto& param : root["params"]) {
if (param.isObject()) {
for (auto& key : param.getMemberNames()) {
if (!param[key].empty()) {
if (!param[key].isArray()) {
// --option
vargv_.emplace_back("--" + key);
// value
vargv_.emplace_back(param[key].asString());
} else {
for (auto& member : param[key]) {
// --option
vargv_.emplace_back("--" + key);
// value
vargv_.emplace_back(member.asString());
}
}
} else {
// --option
vargv_.emplace_back("--" + key);
}
}
break;
}
}
// push arguments at last
for (auto& param : root["params"]) {
if (!param.isObject()){
vargv_.emplace_back(param.asString());
}
}
}
vargv_to_argv();
}
void WebsocketMessage::data_to_arg(uint8_t api_version) {
Tokeniser<' '> args;
args.reset(+*impl_);
// store args from ws message
do {
//skip spaces
if (args.top().front() == ' '){
args.pop();
continue;
} else if (std::iscntrl(args.top().front())){
break;
} else {
this->vargv_.push_back({args.top().data(), args.top().size()});
args.pop();
}
}while(!args.empty());
// convert to char** argv
int i = 0;
for(auto& iter : vargv_){
if (i >= max_paramters){
break;
}
argv_[i++] = iter.c_str();
}
argc_ = i;
}
void ToCommandArg::add_arg(std::string&& outside)
{
vargv_.push_back(outside);
argc_++;
}
} // mgbubble
<|endoftext|> |
<commit_before>
// Qt includes
#include <QDebug>
#include <QTableView>
#include <QLayout>
#include <QStandardItemModel>
#include <QWidget>
// Visomics includes
#include "voTableView.h"
#include "voDataObject.h"
// VTK includes
#include <vtkIdTypeArray.h>
#include <vtkQtTableRepresentation.h>
#include <vtkQtTableView.h>
#include <vtkTable.h>
// --------------------------------------------------------------------------
class voTableViewPrivate
{
public:
voTableViewPrivate();
QTableView* TableView;
QStandardItemModel Model;
};
// --------------------------------------------------------------------------
// voTableViewPrivate methods
// --------------------------------------------------------------------------
voTableViewPrivate::voTableViewPrivate()
{
this->TableView = 0;
}
// --------------------------------------------------------------------------
// voTableView methods
// --------------------------------------------------------------------------
voTableView::voTableView(QWidget* newParent):
Superclass(newParent), d_ptr(new voTableViewPrivate)
{
}
// --------------------------------------------------------------------------
voTableView::~voTableView()
{
}
// --------------------------------------------------------------------------
void voTableView::setupUi(QLayout *layout)
{
Q_D(voTableView);
d->TableView = new QTableView();
d->TableView->setModel(&d->Model);
layout->addWidget(d->TableView);
}
// --------------------------------------------------------------------------
void voTableView::setDataObject(voDataObject *dataObject)
{
Q_D(voTableView);
if (!dataObject)
{
qCritical() << "voTableView - Failed to setDataObject - dataObject is NULL";
return;
}
vtkTable * table = vtkTable::SafeDownCast(dataObject->data());
if (!table)
{
qCritical() << "voTableView - Failed to setDataObject - vtkTable data is expected !";
return;
}
// Update the model if necessary
//if (t->GetMTime() > this->LastModelMTime)
// {
// Note: this will clear the current selection.
vtkIdType num_rows = table->GetNumberOfRows();
vtkIdType num_cols = table->GetNumberOfColumns();
d->Model.setRowCount(static_cast<int>(num_cols - 1));
d->Model.setColumnCount(static_cast<int>(num_rows));
for (vtkIdType r = 0; r < num_rows; ++r)
{
d->Model.setHeaderData(static_cast<int>(r), Qt::Horizontal, QString(table->GetValue(r, 0).ToString()));
for (vtkIdType c = 1; c < num_cols; ++c)
{
QStandardItem* item = new QStandardItem(QString(table->GetValue(r, c).ToString()));
d->Model.setItem(static_cast<int>(c), static_cast<int>(r), item);
}
}
for (vtkIdType c = 1; c < num_cols; ++c)
{
d->Model.setHeaderData(static_cast<int>(c), Qt::Vertical, QString(table->GetColumnName(c)));
}
d->TableView->hideRow(0);
// this->LastModelMTime = table->GetMTime();
// }
// Retrieve the selected subtable
//vtkSmartPointer<vtkTable> ot = vtkSmartPointer<vtkTable>::New();
//this->selectedTable(ot);
//this->Outputs["output"] = ot;
}
// --------------------------------------------------------------------------
//void voTableView::selectedTable(vtkTable* table)
//{
// vtkTable* t = vtkTable::SafeDownCast(this->input().data());
// if (!t)
// {
// return;
// }
// QSet<vtkIdType> rows;
// QSet<vtkIdType> cols;
// // Always select the first column (headers)
// cols << 0;
// const QModelIndexList selected = this->View->selectionModel()->selectedIndexes();
// if (selected.size() == 0)
// {
// table->ShallowCopy(t);
// return;
// }
// foreach (QModelIndex ind, selected)
// {
// cols << ind.row();
// rows << ind.column();
// }
// foreach (vtkIdType c, cols)
// {
// vtkAbstractArray* col = t->GetColumn(c);
// vtkAbstractArray* new_col = col->NewInstance();
// new_col->SetName(col->GetName());
// new_col->SetNumberOfTuples(rows.size());
// table->AddColumn(new_col);
// int ind = 0;
// foreach (vtkIdType r, rows)
// {
// new_col->InsertTuple(ind, r, col);
// ++ind;
// }
// new_col->Delete();
// }
//}
<commit_msg>Prevent QTable items from being editable by user<commit_after>
// Qt includes
#include <QDebug>
#include <QTableView>
#include <QLayout>
#include <QStandardItemModel>
#include <QWidget>
// Visomics includes
#include "voTableView.h"
#include "voDataObject.h"
// VTK includes
#include <vtkIdTypeArray.h>
#include <vtkQtTableRepresentation.h>
#include <vtkQtTableView.h>
#include <vtkTable.h>
// --------------------------------------------------------------------------
class voTableViewPrivate
{
public:
voTableViewPrivate();
QTableView* TableView;
QStandardItemModel Model;
};
// --------------------------------------------------------------------------
// voTableViewPrivate methods
// --------------------------------------------------------------------------
voTableViewPrivate::voTableViewPrivate()
{
this->TableView = 0;
}
// --------------------------------------------------------------------------
// voTableView methods
// --------------------------------------------------------------------------
voTableView::voTableView(QWidget* newParent):
Superclass(newParent), d_ptr(new voTableViewPrivate)
{
}
// --------------------------------------------------------------------------
voTableView::~voTableView()
{
}
// --------------------------------------------------------------------------
void voTableView::setupUi(QLayout *layout)
{
Q_D(voTableView);
d->TableView = new QTableView();
d->TableView->setModel(&d->Model);
layout->addWidget(d->TableView);
}
// --------------------------------------------------------------------------
void voTableView::setDataObject(voDataObject *dataObject)
{
Q_D(voTableView);
if (!dataObject)
{
qCritical() << "voTableView - Failed to setDataObject - dataObject is NULL";
return;
}
vtkTable * table = vtkTable::SafeDownCast(dataObject->data());
if (!table)
{
qCritical() << "voTableView - Failed to setDataObject - vtkTable data is expected !";
return;
}
// Update the model if necessary
//if (t->GetMTime() > this->LastModelMTime)
// {
// Note: this will clear the current selection.
vtkIdType num_rows = table->GetNumberOfRows();
vtkIdType num_cols = table->GetNumberOfColumns();
d->Model.setRowCount(static_cast<int>(num_cols - 1));
d->Model.setColumnCount(static_cast<int>(num_rows));
for (vtkIdType r = 0; r < num_rows; ++r)
{
d->Model.setHeaderData(static_cast<int>(r), Qt::Horizontal, QString(table->GetValue(r, 0).ToString()));
for (vtkIdType c = 1; c < num_cols; ++c)
{
QStandardItem* item = new QStandardItem(QString(table->GetValue(r, c).ToString()));
item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); // Item is view-only
d->Model.setItem(static_cast<int>(c), static_cast<int>(r), item);
}
}
for (vtkIdType c = 1; c < num_cols; ++c)
{
d->Model.setHeaderData(static_cast<int>(c), Qt::Vertical, QString(table->GetColumnName(c)));
}
d->TableView->hideRow(0);
// this->LastModelMTime = table->GetMTime();
// }
// Retrieve the selected subtable
//vtkSmartPointer<vtkTable> ot = vtkSmartPointer<vtkTable>::New();
//this->selectedTable(ot);
//this->Outputs["output"] = ot;
}
// --------------------------------------------------------------------------
//void voTableView::selectedTable(vtkTable* table)
//{
// vtkTable* t = vtkTable::SafeDownCast(this->input().data());
// if (!t)
// {
// return;
// }
// QSet<vtkIdType> rows;
// QSet<vtkIdType> cols;
// // Always select the first column (headers)
// cols << 0;
// const QModelIndexList selected = this->View->selectionModel()->selectedIndexes();
// if (selected.size() == 0)
// {
// table->ShallowCopy(t);
// return;
// }
// foreach (QModelIndex ind, selected)
// {
// cols << ind.row();
// rows << ind.column();
// }
// foreach (vtkIdType c, cols)
// {
// vtkAbstractArray* col = t->GetColumn(c);
// vtkAbstractArray* new_col = col->NewInstance();
// new_col->SetName(col->GetName());
// new_col->SetNumberOfTuples(rows.size());
// table->AddColumn(new_col);
// int ind = 0;
// foreach (vtkIdType r, rows)
// {
// new_col->InsertTuple(ind, r, col);
// ++ind;
// }
// new_col->Delete();
// }
//}
<|endoftext|> |
<commit_before>// @(#)root/meta:$Name: $:$Id: TGenericClassInfo.cxx,v 1.17 2007/01/31 19:59:53 pcanal Exp $
// Author: Philippe Canal 08/05/2002
/*************************************************************************
* Copyright (C) 1995-2002, Rene Brun, Fons Rademakers and al. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TROOT.h"
#include "TClass.h"
#include "TStreamerInfo.h"
#include "TStreamer.h"
#include "TVirtualIsAProxy.h"
#include "TVirtualCollectionProxy.h"
#include "TCollectionProxyInfo.h"
namespace ROOT {
const TInitBehavior *DefineBehavior(void * /*parent_type*/,
void * /*actual_type*/)
{
// This function loads the default behavior for the
// loading of classes.
static TDefaultInitBehavior theDefault;
return &theDefault;
}
TGenericClassInfo::TGenericClassInfo(const char *fullClassname,
const char *declFileName, Int_t declFileLine,
const type_info &info, const TInitBehavior *action,
void *showmembers, VoidFuncPtr_t dictionary,
TVirtualIsAProxy *isa, Int_t pragmabits, Int_t sizof)
: fAction(action), fClass(0), fClassName(fullClassname),
fDeclFileName(declFileName), fDeclFileLine(declFileLine),
fDictionary(dictionary), fInfo(info),
fImplFileName(0), fImplFileLine(0),
fIsA(isa), fShowMembers(showmembers),
fVersion(1),
fNew(0),fNewArray(0),fDelete(0),fDeleteArray(0),fDestructor(0), fStreamer(0),
fCollectionProxy(0), fSizeof(sizof)
{
// Constructor.
Init(pragmabits);
}
TGenericClassInfo::TGenericClassInfo(const char *fullClassname, Int_t version,
const char *declFileName, Int_t declFileLine,
const type_info &info, const TInitBehavior *action,
void* showmembers, VoidFuncPtr_t dictionary,
TVirtualIsAProxy *isa, Int_t pragmabits, Int_t sizof)
: fAction(action), fClass(0), fClassName(fullClassname),
fDeclFileName(declFileName), fDeclFileLine(declFileLine),
fDictionary(dictionary), fInfo(info),
fImplFileName(0), fImplFileLine(0),
fIsA(isa), fShowMembers(showmembers),
fVersion(version),
fNew(0),fNewArray(0),fDelete(0),fDeleteArray(0),fDestructor(0), fStreamer(0),
fCollectionProxy(0), fSizeof(sizof),
fCollectionProxyInfo(0), fCollectionStreamerInfo(0)
{
// Constructor with version number.
Init(pragmabits);
}
TGenericClassInfo::TGenericClassInfo(const char *fullClassname, Int_t version,
const char *declFileName, Int_t declFileLine,
const type_info &info, const TInitBehavior *action,
VoidFuncPtr_t dictionary,
TVirtualIsAProxy *isa, Int_t pragmabits, Int_t sizof)
: fAction(action), fClass(0), fClassName(fullClassname),
fDeclFileName(declFileName), fDeclFileLine(declFileLine),
fDictionary(dictionary), fInfo(info),
fImplFileName(0), fImplFileLine(0),
fIsA(isa), fShowMembers(0),
fVersion(version),
fNew(0),fNewArray(0),fDelete(0),fDeleteArray(0),fDestructor(0), fStreamer(0),
fCollectionProxy(0), fSizeof(sizof),
fCollectionProxyInfo(0), fCollectionStreamerInfo(0)
{
// Constructor with version number and no showmembers.
Init(pragmabits);
}
class TForNamespace {}; // Dummy class to give a typeid to namespace (See also TClassTable.cc)
TGenericClassInfo::TGenericClassInfo(const char *fullClassname, Int_t version,
const char *declFileName, Int_t declFileLine,
const TInitBehavior *action,
VoidFuncPtr_t dictionary, Int_t pragmabits)
: fAction(action), fClass(0), fClassName(fullClassname),
fDeclFileName(declFileName), fDeclFileLine(declFileLine),
fDictionary(dictionary), fInfo(typeid(TForNamespace)),
fImplFileName(0), fImplFileLine(0),
fIsA(0), fShowMembers(0),
fVersion(version),
fNew(0),fNewArray(0),fDelete(0),fDeleteArray(0),fDestructor(0), fStreamer(0),
fCollectionProxy(0), fSizeof(0),
fCollectionProxyInfo(0), fCollectionStreamerInfo(0)
{
// Constructor for namespace
Init(pragmabits);
}
/* TGenericClassInfo::TGenericClassInfo(const TGenericClassInfo& gci) :
fAction(gci.fAction),
fClass(gci.fClass),
fClassName(gci.fClassName),
fDeclFileName(gci.fDeclFileName),
fDeclFileLine(gci.fDeclFileLine),
fDictionary(gci.fDictionary),
fInfo(gci.fInfo),
fImplFileName(gci.fImplFileName),
fImplFileLine(gci.fImplFileLine),
fIsA(gci.fIsA),
fShowMembers(gci.fShowMembers),
fVersion(gci.fVersion),
fNew(gci.fNew),
fNewArray(gci.fNewArray),
fDelete(gci.fDelete),
fDeleteArray(gci.fDeleteArray),
fDestructor(gci.fDestructor),
fStreamer(gci.fStreamer),
fCollectionProxy(gci.fCollectionProxy),
fSizeof(gci.fSizeof)
{ }
TGenericClassInfo& TGenericClassInfo::operator=(const TGenericClassInfo& gci)
{
if(this!=&gci) {
fAction=gci.fAction;
fClass=gci.fClass;
fClassName=gci.fClassName;
fDeclFileName=gci.fDeclFileName;
fDeclFileLine=gci.fDeclFileLine;
fDictionary=gci.fDictionary;
fInfo=gci.fInfo;
fImplFileName=gci.fImplFileName;
fImplFileLine=gci.fImplFileLine;
fIsA=gci.fIsA;
fShowMembers=gci.fShowMembers;
fVersion=gci.fVersion;
fNew=gci.fNew;
fNewArray=gci.fNewArray;
fDelete=gci.fDelete;
fDeleteArray=gci.fDeleteArray;
fDestructor=gci.fDestructor;
fStreamer=gci.fStreamer;
fCollectionProxy=gci.fCollectionProxy;
fSizeof=gci.fSizeof;
} return *this;
}
*/
void TGenericClassInfo::Init(Int_t pragmabits)
{
// Initilization routine.
if (fVersion==-2) fVersion = TStreamerInfo::Class_Version();
if (!fAction) return;
GetAction().Register(fClassName,
fVersion,
fInfo, // typeid(RootClass),
fDictionary,
pragmabits);
}
TGenericClassInfo::~TGenericClassInfo()
{
// Destructor.
delete fCollectionProxyInfo;
delete fCollectionStreamerInfo;
if (!fClass) delete fIsA; // fIsA is adopted by the class if any.
fIsA = 0;
if (!gROOT) return;
if (fAction) GetAction().Unregister(GetClassName());
}
const TInitBehavior &TGenericClassInfo::GetAction() const
{
// Return the creator action.
return *fAction;
}
TClass *TGenericClassInfo::GetClass()
{
// Generate and return the TClass object.
if (!fClass && fAction) {
fClass = GetAction().CreateClass(GetClassName(),
GetVersion(),
GetInfo(),
GetIsA(),
(ShowMembersFunc_t)GetShowMembers(),
GetDeclFileName(),
GetImplFileName(),
GetDeclFileLine(),
GetImplFileLine());
fClass->SetNew(fNew);
fClass->SetNewArray(fNewArray);
fClass->SetDelete(fDelete);
fClass->SetDeleteArray(fDeleteArray);
fClass->SetDestructor(fDestructor);
fClass->AdoptStreamer(fStreamer); fStreamer = 0;
// If IsZombie is true, something went wront and we will not be
// able to properly copy the collection proxy
if (!fClass->IsZombie()) {
if (fCollectionProxy) fClass->CopyCollectionProxy(*fCollectionProxy);
else if (fCollectionProxyInfo) {
fClass->SetCollectionProxy(*fCollectionProxyInfo);
}
}
fClass->SetClassSize(fSizeof);
}
return fClass;
}
const char *TGenericClassInfo::GetClassName() const
{
// Return the class name
return fClassName;
}
TCollectionProxyInfo *TGenericClassInfo::GetCollectionProxyInfo() const
{
// Return the set of info we have for the CollectionProxy, if any
return fCollectionProxyInfo;
}
TCollectionProxyInfo *TGenericClassInfo::GetCollectionStreamerInfo() const
{
// Return the set of info we have for the Collection Streamer, if any
return fCollectionProxyInfo;
}
const type_info &TGenericClassInfo::GetInfo() const
{
// Return the typeifno value
return fInfo;
}
void *TGenericClassInfo::GetShowMembers() const
{
// Return the point of the ShowMembers function
return fShowMembers;
}
void TGenericClassInfo::SetFromTemplate()
{
// Import the information from the class template.
TNamed *info = ROOT::RegisterClassTemplate(GetClassName(), 0, 0);
if (info) SetImplFile(info->GetTitle(), info->GetUniqueID());
}
Int_t TGenericClassInfo::SetImplFile(const char *file, Int_t line)
{
// Set the name of the implementation file.
fImplFileName = file;
fImplFileLine = line;
if (fClass) fClass->AddImplFile(file,line);
return 0;
}
Int_t TGenericClassInfo::SetDeclFile(const char *file, Int_t line)
{
// Set the name of the declaration file.
fDeclFileName = file;
fDeclFileLine = line;
if (fClass) fClass->SetDeclFile(file,line);
return 0;
}
Short_t TGenericClassInfo::SetVersion(Short_t version)
{
// Set a class version number.
ROOT::ResetClassVersion(fClass, GetClassName(),version);
fVersion = version;
return version;
}
void TGenericClassInfo::AdoptCollectionProxyInfo(TCollectionProxyInfo *info)
{
// Set the info for the CollectionProxy
fCollectionProxyInfo = info;
}
void TGenericClassInfo::AdoptCollectionStreamerInfo(TCollectionProxyInfo *info)
{
// Set the info for the Collection Streamer
fCollectionProxyInfo = info;
}
Short_t TGenericClassInfo::AdoptStreamer(TClassStreamer *streamer)
{
// Set a Streamer object. The streamer object is now 'owned'
// by the TGenericClassInfo.
delete fStreamer; fStreamer = 0;
if (fClass) {
fClass->AdoptStreamer(streamer);
} else {
fStreamer = streamer;
}
return 0;
}
Short_t TGenericClassInfo::AdoptCollectionProxy(TVirtualCollectionProxy *collProxy)
{
// Set the CollectProxy object. The CollectionProxy object is now 'owned'
// by the TGenericClassInfo.
delete fCollectionProxy; fCollectionProxy = 0;
fCollectionProxy = collProxy;
if (fClass && fCollectionProxy && !fClass->IsZombie()) {
fClass->CopyCollectionProxy(*fCollectionProxy);
}
return 0;
}
Short_t TGenericClassInfo::SetStreamer(ClassStreamerFunc_t streamer)
{
// Set a Streamer function.
delete fStreamer; fStreamer = 0;
if (fClass) {
fClass->AdoptStreamer(new TClassStreamer(streamer));
} else {
fStreamer = new TClassStreamer(streamer);
}
return 0;
}
const char *TGenericClassInfo::GetDeclFileName() const
{
// Get the name of the declaring header file.
return fDeclFileName;
}
Int_t TGenericClassInfo::GetDeclFileLine() const
{
// Get the declaring line number.
return fDeclFileLine;
}
const char *TGenericClassInfo::GetImplFileName()
{
// Get the implementation filename.
if (!fImplFileName) SetFromTemplate();
return fImplFileName;
}
Int_t TGenericClassInfo::GetImplFileLine()
{
// Get the ClassImp line number.
if (!fImplFileLine) SetFromTemplate();
return fImplFileLine;
}
Int_t TGenericClassInfo::GetVersion() const
{
// Return the class version number.
return fVersion;
}
TClass *TGenericClassInfo::IsA(const void *obj)
{
// Return the actual type of the object.
return (*GetIsA())(obj);
}
TVirtualIsAProxy* TGenericClassInfo::GetIsA() const
{
// Return the IsA proxy.
return fIsA;
}
void TGenericClassInfo::SetNew(NewFunc_t newFunc)
{
// Install a new wrapper around 'new'.
fNew = newFunc;
if (fClass) fClass->SetNew(fNew);
}
void TGenericClassInfo::SetNewArray(NewArrFunc_t newArrayFunc)
{
// Install a new wrapper around 'new []'.
fNewArray = newArrayFunc;
if (fClass) fClass->SetNewArray(fNewArray);
}
void TGenericClassInfo::SetDelete(DelFunc_t deleteFunc)
{
// Install a new wrapper around 'delete'.
fDelete = deleteFunc;
if (fClass) fClass->SetDelete(fDelete);
}
void TGenericClassInfo::SetDeleteArray(DelArrFunc_t deleteArrayFunc)
{
// Install a new wrapper around 'delete []'.
fDeleteArray = deleteArrayFunc;
if (fClass) fClass->SetDeleteArray(fDeleteArray);
}
void TGenericClassInfo::SetDestructor(DesFunc_t destructorFunc)
{
// Install a new wrapper around the destructor.
fDestructor = destructorFunc;
if (fClass) fClass->SetDestructor(fDestructor);
}
NewFunc_t TGenericClassInfo::GetNew() const
{
// Get the wrapper around 'new'.
return fNew;
}
NewArrFunc_t TGenericClassInfo::GetNewArray() const
{
// Get the wrapper around 'new []'.
return fNewArray;
}
DelFunc_t TGenericClassInfo::GetDelete() const
{
// Get the wrapper around 'delete'.
return fDelete;
}
DelArrFunc_t TGenericClassInfo::GetDeleteArray() const
{
// Get the wrapper around 'delete []'.
return fDeleteArray;
}
DesFunc_t TGenericClassInfo::GetDestructor() const
{
// Get the wrapper around the destructor.
return fDestructor;
}
}
<commit_msg>-use TVirtualStreamerinfo instead of TStreamerInfo.<commit_after>// @(#)root/meta:$Name: $:$Id: TGenericClassInfo.cxx,v 1.18 2007/02/01 21:59:28 pcanal Exp $
// Author: Philippe Canal 08/05/2002
/*************************************************************************
* Copyright (C) 1995-2002, Rene Brun, Fons Rademakers and al. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TROOT.h"
#include "TClass.h"
#include "TVirtualStreamerInfo.h"
#include "TStreamer.h"
#include "TVirtualIsAProxy.h"
#include "TVirtualCollectionProxy.h"
#include "TCollectionProxyInfo.h"
namespace ROOT {
const TInitBehavior *DefineBehavior(void * /*parent_type*/,
void * /*actual_type*/)
{
// This function loads the default behavior for the
// loading of classes.
static TDefaultInitBehavior theDefault;
return &theDefault;
}
TGenericClassInfo::TGenericClassInfo(const char *fullClassname,
const char *declFileName, Int_t declFileLine,
const type_info &info, const TInitBehavior *action,
void *showmembers, VoidFuncPtr_t dictionary,
TVirtualIsAProxy *isa, Int_t pragmabits, Int_t sizof)
: fAction(action), fClass(0), fClassName(fullClassname),
fDeclFileName(declFileName), fDeclFileLine(declFileLine),
fDictionary(dictionary), fInfo(info),
fImplFileName(0), fImplFileLine(0),
fIsA(isa), fShowMembers(showmembers),
fVersion(1),
fNew(0),fNewArray(0),fDelete(0),fDeleteArray(0),fDestructor(0), fStreamer(0),
fCollectionProxy(0), fSizeof(sizof)
{
// Constructor.
Init(pragmabits);
}
TGenericClassInfo::TGenericClassInfo(const char *fullClassname, Int_t version,
const char *declFileName, Int_t declFileLine,
const type_info &info, const TInitBehavior *action,
void* showmembers, VoidFuncPtr_t dictionary,
TVirtualIsAProxy *isa, Int_t pragmabits, Int_t sizof)
: fAction(action), fClass(0), fClassName(fullClassname),
fDeclFileName(declFileName), fDeclFileLine(declFileLine),
fDictionary(dictionary), fInfo(info),
fImplFileName(0), fImplFileLine(0),
fIsA(isa), fShowMembers(showmembers),
fVersion(version),
fNew(0),fNewArray(0),fDelete(0),fDeleteArray(0),fDestructor(0), fStreamer(0),
fCollectionProxy(0), fSizeof(sizof),
fCollectionProxyInfo(0), fCollectionStreamerInfo(0)
{
// Constructor with version number.
Init(pragmabits);
}
TGenericClassInfo::TGenericClassInfo(const char *fullClassname, Int_t version,
const char *declFileName, Int_t declFileLine,
const type_info &info, const TInitBehavior *action,
VoidFuncPtr_t dictionary,
TVirtualIsAProxy *isa, Int_t pragmabits, Int_t sizof)
: fAction(action), fClass(0), fClassName(fullClassname),
fDeclFileName(declFileName), fDeclFileLine(declFileLine),
fDictionary(dictionary), fInfo(info),
fImplFileName(0), fImplFileLine(0),
fIsA(isa), fShowMembers(0),
fVersion(version),
fNew(0),fNewArray(0),fDelete(0),fDeleteArray(0),fDestructor(0), fStreamer(0),
fCollectionProxy(0), fSizeof(sizof),
fCollectionProxyInfo(0), fCollectionStreamerInfo(0)
{
// Constructor with version number and no showmembers.
Init(pragmabits);
}
class TForNamespace {}; // Dummy class to give a typeid to namespace (See also TClassTable.cc)
TGenericClassInfo::TGenericClassInfo(const char *fullClassname, Int_t version,
const char *declFileName, Int_t declFileLine,
const TInitBehavior *action,
VoidFuncPtr_t dictionary, Int_t pragmabits)
: fAction(action), fClass(0), fClassName(fullClassname),
fDeclFileName(declFileName), fDeclFileLine(declFileLine),
fDictionary(dictionary), fInfo(typeid(TForNamespace)),
fImplFileName(0), fImplFileLine(0),
fIsA(0), fShowMembers(0),
fVersion(version),
fNew(0),fNewArray(0),fDelete(0),fDeleteArray(0),fDestructor(0), fStreamer(0),
fCollectionProxy(0), fSizeof(0),
fCollectionProxyInfo(0), fCollectionStreamerInfo(0)
{
// Constructor for namespace
Init(pragmabits);
}
/* TGenericClassInfo::TGenericClassInfo(const TGenericClassInfo& gci) :
fAction(gci.fAction),
fClass(gci.fClass),
fClassName(gci.fClassName),
fDeclFileName(gci.fDeclFileName),
fDeclFileLine(gci.fDeclFileLine),
fDictionary(gci.fDictionary),
fInfo(gci.fInfo),
fImplFileName(gci.fImplFileName),
fImplFileLine(gci.fImplFileLine),
fIsA(gci.fIsA),
fShowMembers(gci.fShowMembers),
fVersion(gci.fVersion),
fNew(gci.fNew),
fNewArray(gci.fNewArray),
fDelete(gci.fDelete),
fDeleteArray(gci.fDeleteArray),
fDestructor(gci.fDestructor),
fStreamer(gci.fStreamer),
fCollectionProxy(gci.fCollectionProxy),
fSizeof(gci.fSizeof)
{ }
TGenericClassInfo& TGenericClassInfo::operator=(const TGenericClassInfo& gci)
{
if(this!=&gci) {
fAction=gci.fAction;
fClass=gci.fClass;
fClassName=gci.fClassName;
fDeclFileName=gci.fDeclFileName;
fDeclFileLine=gci.fDeclFileLine;
fDictionary=gci.fDictionary;
fInfo=gci.fInfo;
fImplFileName=gci.fImplFileName;
fImplFileLine=gci.fImplFileLine;
fIsA=gci.fIsA;
fShowMembers=gci.fShowMembers;
fVersion=gci.fVersion;
fNew=gci.fNew;
fNewArray=gci.fNewArray;
fDelete=gci.fDelete;
fDeleteArray=gci.fDeleteArray;
fDestructor=gci.fDestructor;
fStreamer=gci.fStreamer;
fCollectionProxy=gci.fCollectionProxy;
fSizeof=gci.fSizeof;
} return *this;
}
*/
void TGenericClassInfo::Init(Int_t pragmabits)
{
// Initilization routine.
//TVirtualStreamerInfo::Class_Version MUST be the same as TStreamerInfo::Class_Version
if (fVersion==-2) fVersion = TVirtualStreamerInfo::Class_Version();
if (!fAction) return;
GetAction().Register(fClassName,
fVersion,
fInfo, // typeid(RootClass),
fDictionary,
pragmabits);
}
TGenericClassInfo::~TGenericClassInfo()
{
// Destructor.
delete fCollectionProxyInfo;
delete fCollectionStreamerInfo;
if (!fClass) delete fIsA; // fIsA is adopted by the class if any.
fIsA = 0;
if (!gROOT) return;
if (fAction) GetAction().Unregister(GetClassName());
}
const TInitBehavior &TGenericClassInfo::GetAction() const
{
// Return the creator action.
return *fAction;
}
TClass *TGenericClassInfo::GetClass()
{
// Generate and return the TClass object.
if (!fClass && fAction) {
fClass = GetAction().CreateClass(GetClassName(),
GetVersion(),
GetInfo(),
GetIsA(),
(ShowMembersFunc_t)GetShowMembers(),
GetDeclFileName(),
GetImplFileName(),
GetDeclFileLine(),
GetImplFileLine());
fClass->SetNew(fNew);
fClass->SetNewArray(fNewArray);
fClass->SetDelete(fDelete);
fClass->SetDeleteArray(fDeleteArray);
fClass->SetDestructor(fDestructor);
fClass->AdoptStreamer(fStreamer); fStreamer = 0;
// If IsZombie is true, something went wront and we will not be
// able to properly copy the collection proxy
if (!fClass->IsZombie()) {
if (fCollectionProxy) fClass->CopyCollectionProxy(*fCollectionProxy);
else if (fCollectionProxyInfo) {
fClass->SetCollectionProxy(*fCollectionProxyInfo);
}
}
fClass->SetClassSize(fSizeof);
}
return fClass;
}
const char *TGenericClassInfo::GetClassName() const
{
// Return the class name
return fClassName;
}
TCollectionProxyInfo *TGenericClassInfo::GetCollectionProxyInfo() const
{
// Return the set of info we have for the CollectionProxy, if any
return fCollectionProxyInfo;
}
TCollectionProxyInfo *TGenericClassInfo::GetCollectionStreamerInfo() const
{
// Return the set of info we have for the Collection Streamer, if any
return fCollectionProxyInfo;
}
const type_info &TGenericClassInfo::GetInfo() const
{
// Return the typeifno value
return fInfo;
}
void *TGenericClassInfo::GetShowMembers() const
{
// Return the point of the ShowMembers function
return fShowMembers;
}
void TGenericClassInfo::SetFromTemplate()
{
// Import the information from the class template.
TNamed *info = ROOT::RegisterClassTemplate(GetClassName(), 0, 0);
if (info) SetImplFile(info->GetTitle(), info->GetUniqueID());
}
Int_t TGenericClassInfo::SetImplFile(const char *file, Int_t line)
{
// Set the name of the implementation file.
fImplFileName = file;
fImplFileLine = line;
if (fClass) fClass->AddImplFile(file,line);
return 0;
}
Int_t TGenericClassInfo::SetDeclFile(const char *file, Int_t line)
{
// Set the name of the declaration file.
fDeclFileName = file;
fDeclFileLine = line;
if (fClass) fClass->SetDeclFile(file,line);
return 0;
}
Short_t TGenericClassInfo::SetVersion(Short_t version)
{
// Set a class version number.
ROOT::ResetClassVersion(fClass, GetClassName(),version);
fVersion = version;
return version;
}
void TGenericClassInfo::AdoptCollectionProxyInfo(TCollectionProxyInfo *info)
{
// Set the info for the CollectionProxy
fCollectionProxyInfo = info;
}
void TGenericClassInfo::AdoptCollectionStreamerInfo(TCollectionProxyInfo *info)
{
// Set the info for the Collection Streamer
fCollectionProxyInfo = info;
}
Short_t TGenericClassInfo::AdoptStreamer(TClassStreamer *streamer)
{
// Set a Streamer object. The streamer object is now 'owned'
// by the TGenericClassInfo.
delete fStreamer; fStreamer = 0;
if (fClass) {
fClass->AdoptStreamer(streamer);
} else {
fStreamer = streamer;
}
return 0;
}
Short_t TGenericClassInfo::AdoptCollectionProxy(TVirtualCollectionProxy *collProxy)
{
// Set the CollectProxy object. The CollectionProxy object is now 'owned'
// by the TGenericClassInfo.
delete fCollectionProxy; fCollectionProxy = 0;
fCollectionProxy = collProxy;
if (fClass && fCollectionProxy && !fClass->IsZombie()) {
fClass->CopyCollectionProxy(*fCollectionProxy);
}
return 0;
}
Short_t TGenericClassInfo::SetStreamer(ClassStreamerFunc_t streamer)
{
// Set a Streamer function.
delete fStreamer; fStreamer = 0;
if (fClass) {
fClass->AdoptStreamer(new TClassStreamer(streamer));
} else {
fStreamer = new TClassStreamer(streamer);
}
return 0;
}
const char *TGenericClassInfo::GetDeclFileName() const
{
// Get the name of the declaring header file.
return fDeclFileName;
}
Int_t TGenericClassInfo::GetDeclFileLine() const
{
// Get the declaring line number.
return fDeclFileLine;
}
const char *TGenericClassInfo::GetImplFileName()
{
// Get the implementation filename.
if (!fImplFileName) SetFromTemplate();
return fImplFileName;
}
Int_t TGenericClassInfo::GetImplFileLine()
{
// Get the ClassImp line number.
if (!fImplFileLine) SetFromTemplate();
return fImplFileLine;
}
Int_t TGenericClassInfo::GetVersion() const
{
// Return the class version number.
return fVersion;
}
TClass *TGenericClassInfo::IsA(const void *obj)
{
// Return the actual type of the object.
return (*GetIsA())(obj);
}
TVirtualIsAProxy* TGenericClassInfo::GetIsA() const
{
// Return the IsA proxy.
return fIsA;
}
void TGenericClassInfo::SetNew(NewFunc_t newFunc)
{
// Install a new wrapper around 'new'.
fNew = newFunc;
if (fClass) fClass->SetNew(fNew);
}
void TGenericClassInfo::SetNewArray(NewArrFunc_t newArrayFunc)
{
// Install a new wrapper around 'new []'.
fNewArray = newArrayFunc;
if (fClass) fClass->SetNewArray(fNewArray);
}
void TGenericClassInfo::SetDelete(DelFunc_t deleteFunc)
{
// Install a new wrapper around 'delete'.
fDelete = deleteFunc;
if (fClass) fClass->SetDelete(fDelete);
}
void TGenericClassInfo::SetDeleteArray(DelArrFunc_t deleteArrayFunc)
{
// Install a new wrapper around 'delete []'.
fDeleteArray = deleteArrayFunc;
if (fClass) fClass->SetDeleteArray(fDeleteArray);
}
void TGenericClassInfo::SetDestructor(DesFunc_t destructorFunc)
{
// Install a new wrapper around the destructor.
fDestructor = destructorFunc;
if (fClass) fClass->SetDestructor(fDestructor);
}
NewFunc_t TGenericClassInfo::GetNew() const
{
// Get the wrapper around 'new'.
return fNew;
}
NewArrFunc_t TGenericClassInfo::GetNewArray() const
{
// Get the wrapper around 'new []'.
return fNewArray;
}
DelFunc_t TGenericClassInfo::GetDelete() const
{
// Get the wrapper around 'delete'.
return fDelete;
}
DelArrFunc_t TGenericClassInfo::GetDeleteArray() const
{
// Get the wrapper around 'delete []'.
return fDeleteArray;
}
DesFunc_t TGenericClassInfo::GetDestructor() const
{
// Get the wrapper around the destructor.
return fDestructor;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/
#ifndef PEGTL_CONTRIB_JSON_HH
#define PEGTL_CONTRIB_JSON_HH
#include "../rules.hh"
#include "../ascii.hh"
#include "../utf8.hh"
#include "abnf.hh"
namespace pegtl
{
namespace json
{
// JSON grammar according to RFC 7159 (for UTF-8 encoded JSON only).
struct ws : one< ' ', '\t', '\n', '\r' > {};
struct begin_array : pad< one< '[' >, ws > {};
struct begin_object : pad< one< '{' >, ws > {};
struct end_array : pad< one< ']' >, ws > {};
struct end_object : pad< one< '}' >, ws > {};
struct name_separator : pad< one< ':' >, ws > {};
struct value_separator : pad< one< ',' >, ws > {};
struct false_ : pegtl_string_t( "false" ) {};
struct null : pegtl_string_t( "null" ) {};
struct true_ : pegtl_string_t( "true" ) {};
struct digits : plus< abnf::DIGIT > {};
struct exp : seq< one< 'e', 'E' >, opt< one< '-', '+' > >, must< digits > > {};
struct frac : if_must< one< '.' >, digits > {};
struct int_ : sor< one< '0' >, digits > {};
struct number : seq< opt< one< '-' > >, int_, opt< frac >, opt< exp > > {};
struct xdigit : abnf::HEXDIG {};
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 string_content : until< at< one< '"' > >, must< char_ > > {};
struct string : seq< one< '"' >, must< string_content >, any >
{
using content = string_content;
};
struct value;
struct key : string {};
struct member : if_must< key, name_separator, value > {};
struct object : seq< begin_object, opt< list_must< member, value_separator > >, must< end_object > >
{
using content = list_must< member, value_separator >;
};
struct array : seq< begin_array, opt< list_must< value, value_separator > >, must< end_array > >
{
using content = list_must< value, value_separator >;
};
struct value : sor< string, number, object, array, false_, true_, null > {};
struct text : pad< value, ws > {};
} // json
} // pegtl
#endif
<commit_msg>Simplify, create explicit anchors<commit_after>// Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/
#ifndef PEGTL_CONTRIB_JSON_HH
#define PEGTL_CONTRIB_JSON_HH
#include "../rules.hh"
#include "../ascii.hh"
#include "../utf8.hh"
#include "abnf.hh"
namespace pegtl
{
namespace json
{
// JSON grammar according to RFC 7159 (for UTF-8 encoded JSON only).
struct ws : one< ' ', '\t', '\n', '\r' > {};
struct begin_array : pad< one< '[' >, ws > {};
struct begin_object : pad< one< '{' >, ws > {};
struct end_array : pad< one< ']' >, ws > {};
struct end_object : pad< one< '}' >, ws > {};
struct name_separator : pad< one< ':' >, ws > {};
struct value_separator : pad< one< ',' >, ws > {};
struct false_ : pegtl_string_t( "false" ) {};
struct null : pegtl_string_t( "null" ) {};
struct true_ : pegtl_string_t( "true" ) {};
struct digits : plus< abnf::DIGIT > {};
struct exp : seq< one< 'e', 'E' >, opt< one< '-', '+' > >, must< digits > > {};
struct frac : if_must< one< '.' >, digits > {};
struct int_ : sor< one< '0' >, digits > {};
struct number : seq< opt< one< '-' > >, int_, opt< frac >, opt< exp > > {};
struct xdigit : abnf::HEXDIG {};
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 string_content : until< at< one< '"' > >, must< char_ > > {};
struct string : seq< one< '"' >, must< string_content >, any >
{
using content = string_content;
};
struct value;
struct key : string {};
struct member : if_must< key, name_separator, value > {};
struct object_content : list_must< member, value_separator > {};
struct object : seq< begin_object, opt< object_content >, must< end_object > >
{
using content = object_content;
};
struct array_content : list_must< value, value_separator > {};
struct array : seq< begin_array, opt< array_content >, must< end_array > >
{
using content = array_content;
};
struct value : sor< string, number, object, array, false_, true_, null > {};
struct text : pad< value, ws > {};
} // json
} // pegtl
#endif
<|endoftext|> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.