text
stringlengths 54
60.6k
|
|---|
<commit_before><commit_msg>Parse it as a single address.<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: pfuncache.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2004-06-04 11:37:48 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_PFUNCACHE_HXX
#define SC_PFUNCACHE_HXX
#ifndef SC_RANGELST_HXX
#include "rangelst.hxx"
#endif
class ScDocShell;
class ScMarkData;
/** Possible types of selection for print functions */
enum ScPrintSelectionMode
{
SC_PRINTSEL_INVALID,
SC_PRINTSEL_DOCUMENT,
SC_PRINTSEL_CURSOR,
SC_PRINTSEL_RANGE
};
/** Stores the selection in the ScPrintFuncCache so it is only used
for the same selection again. */
class ScPrintSelectionStatus
{
ScPrintSelectionMode eMode;
ScRangeList aRanges;
public:
ScPrintSelectionStatus() : eMode(SC_PRINTSEL_INVALID) {}
~ScPrintSelectionStatus() {}
void SetMode(ScPrintSelectionMode eNew) { eMode = eNew; }
void SetRanges(const ScRangeList& rNew) { aRanges = rNew; }
BOOL operator==(const ScPrintSelectionStatus& rOther) const
{ return eMode == rOther.eMode && aRanges == rOther.aRanges; }
};
/** Stores the data for printing that is needed from several sheets,
so it doesn't have to be calculated for rendering each page. */
class ScPrintFuncCache
{
ScPrintSelectionStatus aSelection;
ScDocShell* pDocSh;
long nTotalPages;
long nPages[MAXTABCOUNT];
long nFirstAttr[MAXTABCOUNT];
public:
ScPrintFuncCache( ScDocShell* pD, const ScMarkData& rMark,
const ScPrintSelectionStatus& rStatus );
~ScPrintFuncCache();
BOOL IsSameSelection( const ScPrintSelectionStatus& rStatus ) const;
long GetPageCount() const { return nTotalPages; }
long GetFirstAttr( SCTAB nTab ) const { return nFirstAttr[nTab]; }
SCTAB GetTabForPage( long nPage ) const;
long GetTabStart( SCTAB nTab ) const;
long GetDisplayStart( SCTAB nTab ) const;
};
#endif
<commit_msg>INTEGRATION: CWS pdf02 (1.2.158); FILE MERGED 2004/10/01 11:57:01 nn 1.2.158.1: #i34865# handle internal links in PDF export<commit_after>/*************************************************************************
*
* $RCSfile: pfuncache.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: pjunck $ $Date: 2004-10-28 09:56:48 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_PFUNCACHE_HXX
#define SC_PFUNCACHE_HXX
#include <vector>
#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#ifndef SC_RANGELST_HXX
#include "rangelst.hxx"
#endif
class ScDocShell;
class ScMarkData;
/** Possible types of selection for print functions */
enum ScPrintSelectionMode
{
SC_PRINTSEL_INVALID,
SC_PRINTSEL_DOCUMENT,
SC_PRINTSEL_CURSOR,
SC_PRINTSEL_RANGE
};
/** Stores the selection in the ScPrintFuncCache so it is only used
for the same selection again. */
class ScPrintSelectionStatus
{
ScPrintSelectionMode eMode;
ScRangeList aRanges;
public:
ScPrintSelectionStatus() : eMode(SC_PRINTSEL_INVALID) {}
~ScPrintSelectionStatus() {}
void SetMode(ScPrintSelectionMode eNew) { eMode = eNew; }
void SetRanges(const ScRangeList& rNew) { aRanges = rNew; }
BOOL operator==(const ScPrintSelectionStatus& rOther) const
{ return eMode == rOther.eMode && aRanges == rOther.aRanges; }
};
/** The range that is printed on a page (excluding repeated columns/rows),
and its position on the page, used to find hyperlink targets. */
struct ScPrintPageLocation
{
long nPage;
ScRange aCellRange;
Rectangle aRectangle; // pixels
ScPrintPageLocation() :
nPage(-1) {} // default: invalid
ScPrintPageLocation( long nP, const ScRange& rRange, const Rectangle& rRect ) :
nPage(nP), aCellRange(rRange), aRectangle(rRect) {}
};
/** Stores the data for printing that is needed from several sheets,
so it doesn't have to be calculated for rendering each page. */
class ScPrintFuncCache
{
ScPrintSelectionStatus aSelection;
ScDocShell* pDocSh;
long nTotalPages;
long nPages[MAXTABCOUNT];
long nFirstAttr[MAXTABCOUNT];
std::vector<ScPrintPageLocation> aLocations;
bool bLocInitialized;
public:
ScPrintFuncCache( ScDocShell* pD, const ScMarkData& rMark,
const ScPrintSelectionStatus& rStatus );
~ScPrintFuncCache();
BOOL IsSameSelection( const ScPrintSelectionStatus& rStatus ) const;
void InitLocations( const ScMarkData& rMark, OutputDevice* pDev );
bool FindLocation( const ScAddress& rCell, ScPrintPageLocation& rLocation ) const;
long GetPageCount() const { return nTotalPages; }
long GetFirstAttr( SCTAB nTab ) const { return nFirstAttr[nTab]; }
SCTAB GetTabForPage( long nPage ) const;
long GetTabStart( SCTAB nTab ) const;
long GetDisplayStart( SCTAB nTab ) const;
};
#endif
<|endoftext|>
|
<commit_before><commit_msg>coverity#1226486 Dereference null return value<commit_after><|endoftext|>
|
<commit_before>#include "unittest/gtest.hpp"
#include "clustering/immediate_consistency/branch/broadcaster.hpp"
#include "clustering/immediate_consistency/branch/listener.hpp"
#include "clustering/immediate_consistency/branch/replier.hpp"
#include "unittest/dummy_metadata_controller.hpp"
#include "unittest/dummy_protocol.hpp"
#include "unittest/clustering_utils.hpp"
#include "unittest/unittest_utils.hpp"
namespace unittest {
namespace {
void run_with_broadcaster(
boost::function<void(
mailbox_cluster_t *,
boost::shared_ptr<metadata_readwrite_view_t<namespace_branch_metadata_t<dummy_protocol_t> > >,
boost::scoped_ptr<broadcaster_t<dummy_protocol_t> > *,
test_store_t *,
boost::scoped_ptr<listener_t<dummy_protocol_t> > *
)> fun)
{
/* Set up a cluster so mailboxes can be created */
simple_mailbox_cluster_t cluster;
/* Set up a metadata meeting-place */
namespace_branch_metadata_t<dummy_protocol_t> initial_metadata;
dummy_metadata_controller_t<namespace_branch_metadata_t<dummy_protocol_t> > metadata_controller(initial_metadata);
/* Set up a broadcaster and initial listener */
test_store_t initial_store;
cond_t interruptor;
boost::scoped_ptr<listener_t<dummy_protocol_t> > initial_listener;
boost::scoped_ptr<broadcaster_t<dummy_protocol_t> > broadcaster(
new broadcaster_t<dummy_protocol_t>(
&cluster,
metadata_controller.get_view(),
&initial_store.store,
&interruptor,
&initial_listener
));
fun(&cluster, metadata_controller.get_view(), &broadcaster, &initial_store, &initial_listener);
}
void run_in_thread_pool_with_broadcaster(
boost::function<void(
mailbox_cluster_t *,
boost::shared_ptr<metadata_readwrite_view_t<namespace_branch_metadata_t<dummy_protocol_t> > >,
boost::scoped_ptr<broadcaster_t<dummy_protocol_t> > *,
test_store_t *,
boost::scoped_ptr<listener_t<dummy_protocol_t> > *
)> fun)
{
run_in_thread_pool(boost::bind(&run_with_broadcaster, fun));
}
/* `let_stuff_happen()` delays for some time to let events occur */
void let_stuff_happen() {
nap(1000);
}
} /* anonymous namespace */
/* The `ReadWrite` test just sends some reads and writes via the broadcaster to a
single mirror. */
void run_read_write_test(mailbox_cluster_t *cluster,
boost::shared_ptr<metadata_readwrite_view_t<namespace_branch_metadata_t<dummy_protocol_t> > > metadata_view,
boost::scoped_ptr<broadcaster_t<dummy_protocol_t> > *broadcaster,
UNUSED test_store_t *store,
boost::scoped_ptr<listener_t<dummy_protocol_t> > *initial_listener)
{
/* Set up a replier so the broadcaster can handle operations */
EXPECT_FALSE((*initial_listener)->get_outdated_signal()->is_pulsed());
replier_t<dummy_protocol_t> replier(cluster, metadata_view, initial_listener->get());
order_source_t order_source;
/* Send some writes via the broadcaster to the mirror */
std::map<std::string, std::string> values_inserted;
for (int i = 0; i < 10; i++) {
dummy_protocol_t::write_t w;
std::string key = std::string(1, 'a' + rand() % 26);
w.values[key] = values_inserted[key] = strprintf("%d", i);
(*broadcaster)->write(w, order_source.check_in("unittest"));
}
/* Now send some reads */
for (std::map<std::string, std::string>::iterator it = values_inserted.begin();
it != values_inserted.end(); it++) {
dummy_protocol_t::read_t r;
r.keys.keys.insert((*it).first);
dummy_protocol_t::read_response_t resp = (*broadcaster)->read(r, order_source.check_in("unittest"));
EXPECT_EQ((*it).second, resp.values[(*it).first]);
}
}
TEST(ClusteringBranch, ReadWrite) {
run_in_thread_pool_with_broadcaster(&run_read_write_test);
}
/* The `Backfill` test starts up a node with one mirror, inserts some data, and
then adds another mirror. */
void run_backfill_test(mailbox_cluster_t *cluster,
boost::shared_ptr<metadata_readwrite_view_t<namespace_branch_metadata_t<dummy_protocol_t> > > metadata_view,
boost::scoped_ptr<broadcaster_t<dummy_protocol_t> > *broadcaster,
test_store_t *store1,
boost::scoped_ptr<listener_t<dummy_protocol_t> > *initial_listener)
{
/* Set up a replier so the broadcaster can handle operations */
EXPECT_FALSE((*initial_listener)->get_outdated_signal()->is_pulsed());
replier_t<dummy_protocol_t> replier(cluster, metadata_view, initial_listener->get());
order_source_t order_source;
/* Start sending operations to the broadcaster */
inserter_t inserter(
boost::bind(&broadcaster_t<dummy_protocol_t>::write, broadcaster->get(), _1, _2),
&order_source);
nap(100);
/* Set up a second mirror */
test_store_t store2;
cond_t interruptor;
listener_t<dummy_protocol_t> listener2(
cluster, metadata_view,
&store2.store,
(*broadcaster)->get_branch_id(),
replier.get_backfiller_id(),
&interruptor);
EXPECT_FALSE((*initial_listener)->get_outdated_signal()->is_pulsed());
EXPECT_FALSE(listener2.get_outdated_signal()->is_pulsed());
nap(100);
/* Stop the inserter, then let any lingering writes finish */
inserter.stop();
/* Let any lingering writes finish */
let_stuff_happen();
/* Confirm that both mirrors have all of the writes */
for (std::map<std::string, std::string>::iterator it = inserter.values_inserted.begin();
it != inserter.values_inserted.end(); it++) {
EXPECT_EQ((*it).second, store1->underlying_store.values[(*it).first]);
EXPECT_EQ((*it).second, store2.underlying_store.values[(*it).first]);
}
}
TEST(ClusteringBranch, Backfill) {
run_in_thread_pool_with_broadcaster(&run_backfill_test);
}
} /* namespace unittest */
<commit_msg>Commented out the ClusteringBranch.ReadWrite test since #479 is still not fixed.<commit_after>#include "unittest/gtest.hpp"
#include "clustering/immediate_consistency/branch/broadcaster.hpp"
#include "clustering/immediate_consistency/branch/listener.hpp"
#include "clustering/immediate_consistency/branch/replier.hpp"
#include "unittest/dummy_metadata_controller.hpp"
#include "unittest/dummy_protocol.hpp"
#include "unittest/clustering_utils.hpp"
#include "unittest/unittest_utils.hpp"
namespace unittest {
namespace {
void run_with_broadcaster(
boost::function<void(
mailbox_cluster_t *,
boost::shared_ptr<metadata_readwrite_view_t<namespace_branch_metadata_t<dummy_protocol_t> > >,
boost::scoped_ptr<broadcaster_t<dummy_protocol_t> > *,
test_store_t *,
boost::scoped_ptr<listener_t<dummy_protocol_t> > *
)> fun)
{
/* Set up a cluster so mailboxes can be created */
simple_mailbox_cluster_t cluster;
/* Set up a metadata meeting-place */
namespace_branch_metadata_t<dummy_protocol_t> initial_metadata;
dummy_metadata_controller_t<namespace_branch_metadata_t<dummy_protocol_t> > metadata_controller(initial_metadata);
/* Set up a broadcaster and initial listener */
test_store_t initial_store;
cond_t interruptor;
boost::scoped_ptr<listener_t<dummy_protocol_t> > initial_listener;
boost::scoped_ptr<broadcaster_t<dummy_protocol_t> > broadcaster(
new broadcaster_t<dummy_protocol_t>(
&cluster,
metadata_controller.get_view(),
&initial_store.store,
&interruptor,
&initial_listener
));
fun(&cluster, metadata_controller.get_view(), &broadcaster, &initial_store, &initial_listener);
}
void run_in_thread_pool_with_broadcaster(
boost::function<void(
mailbox_cluster_t *,
boost::shared_ptr<metadata_readwrite_view_t<namespace_branch_metadata_t<dummy_protocol_t> > >,
boost::scoped_ptr<broadcaster_t<dummy_protocol_t> > *,
test_store_t *,
boost::scoped_ptr<listener_t<dummy_protocol_t> > *
)> fun)
{
run_in_thread_pool(boost::bind(&run_with_broadcaster, fun));
}
/* `let_stuff_happen()` delays for some time to let events occur */
void let_stuff_happen() {
nap(1000);
}
} /* anonymous namespace */
/* The `ReadWrite` test just sends some reads and writes via the broadcaster to a
single mirror. */
void run_read_write_test(mailbox_cluster_t *cluster,
boost::shared_ptr<metadata_readwrite_view_t<namespace_branch_metadata_t<dummy_protocol_t> > > metadata_view,
boost::scoped_ptr<broadcaster_t<dummy_protocol_t> > *broadcaster,
UNUSED test_store_t *store,
boost::scoped_ptr<listener_t<dummy_protocol_t> > *initial_listener)
{
/* Set up a replier so the broadcaster can handle operations */
EXPECT_FALSE((*initial_listener)->get_outdated_signal()->is_pulsed());
replier_t<dummy_protocol_t> replier(cluster, metadata_view, initial_listener->get());
order_source_t order_source;
/* Send some writes via the broadcaster to the mirror */
std::map<std::string, std::string> values_inserted;
for (int i = 0; i < 10; i++) {
dummy_protocol_t::write_t w;
std::string key = std::string(1, 'a' + rand() % 26);
w.values[key] = values_inserted[key] = strprintf("%d", i);
(*broadcaster)->write(w, order_source.check_in("unittest"));
}
/* Now send some reads */
for (std::map<std::string, std::string>::iterator it = values_inserted.begin();
it != values_inserted.end(); it++) {
dummy_protocol_t::read_t r;
r.keys.keys.insert((*it).first);
dummy_protocol_t::read_response_t resp = (*broadcaster)->read(r, order_source.check_in("unittest"));
EXPECT_EQ((*it).second, resp.values[(*it).first]);
}
}
// TODO(sam): TODO(tim): @sam @tim Tim needs to fix the bug that
// causes this test to fail. See issue #479.
// TEST(ClusteringBranch, ReadWrite) {
// run_in_thread_pool_with_broadcaster(&run_read_write_test);
// }
/* The `Backfill` test starts up a node with one mirror, inserts some data, and
then adds another mirror. */
void run_backfill_test(mailbox_cluster_t *cluster,
boost::shared_ptr<metadata_readwrite_view_t<namespace_branch_metadata_t<dummy_protocol_t> > > metadata_view,
boost::scoped_ptr<broadcaster_t<dummy_protocol_t> > *broadcaster,
test_store_t *store1,
boost::scoped_ptr<listener_t<dummy_protocol_t> > *initial_listener)
{
/* Set up a replier so the broadcaster can handle operations */
EXPECT_FALSE((*initial_listener)->get_outdated_signal()->is_pulsed());
replier_t<dummy_protocol_t> replier(cluster, metadata_view, initial_listener->get());
order_source_t order_source;
/* Start sending operations to the broadcaster */
inserter_t inserter(
boost::bind(&broadcaster_t<dummy_protocol_t>::write, broadcaster->get(), _1, _2),
&order_source);
nap(100);
/* Set up a second mirror */
test_store_t store2;
cond_t interruptor;
listener_t<dummy_protocol_t> listener2(
cluster, metadata_view,
&store2.store,
(*broadcaster)->get_branch_id(),
replier.get_backfiller_id(),
&interruptor);
EXPECT_FALSE((*initial_listener)->get_outdated_signal()->is_pulsed());
EXPECT_FALSE(listener2.get_outdated_signal()->is_pulsed());
nap(100);
/* Stop the inserter, then let any lingering writes finish */
inserter.stop();
/* Let any lingering writes finish */
let_stuff_happen();
/* Confirm that both mirrors have all of the writes */
for (std::map<std::string, std::string>::iterator it = inserter.values_inserted.begin();
it != inserter.values_inserted.end(); it++) {
EXPECT_EQ((*it).second, store1->underlying_store.values[(*it).first]);
EXPECT_EQ((*it).second, store2.underlying_store.values[(*it).first]);
}
}
TEST(ClusteringBranch, Backfill) {
run_in_thread_pool_with_broadcaster(&run_backfill_test);
}
} /* namespace unittest */
<|endoftext|>
|
<commit_before>#include "glyphcellrenderer.h"
#include "wxcontext.h"
#include <wx/dcclient.h>
#include <wx/graphics.h>
#include <wx/settings.h>
#include <memory>
GlyphCellRenderer::GlyphCellRenderer(const std::map<wxString, SvgGlyph> &glyphs, int fontSize): glyphs(glyphs), fontSize(fontSize)
{
labelFont = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
glyphColor = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT);
hlColor = wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE);
labelColor = glyphColor.ChangeLightness(150);
}
wxGridCellRenderer *GlyphCellRenderer::Clone() const
{
return nullptr;
}
void GlyphCellRenderer::SetHighlightCell(const wxGridCellCoords &coords)
{
hlCellCoords = coords;
}
const wxGridCellCoords &GlyphCellRenderer::GetHighlightCell() const
{
return hlCellCoords;
}
void GlyphCellRenderer::Draw(wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, const wxRect &rect, int row, int col, bool isSelected)
{
wxGridCellRenderer::Draw(grid, attr, dc, rect, row, col, false);
wxString value = grid.GetTable()->GetValue(row, col);
wxString label;
auto it = glyphs.find(value);
if (it == glyphs.end()) return;
const SvgGlyph &glyph = it->second;
if (!glyph.IsOk())
return;
label.Printf("%04x", glyph.unicode[0]);
std::unique_ptr<wxGraphicsContext> gc(wxGraphicsContext::Create(static_cast<wxPaintDC&>(dc)));
wxRect newRect = rect;
// Oh, crap
if (gc->GetRenderer()->GetName() == L"cairo")
{
newRect.x += dc.GetDeviceOrigin().x;
newRect.y += dc.GetDeviceOrigin().y;
}
std::map<wxString, wxBitmap>::iterator findIt = glyphCache.find(glyph.unicode);
if (findIt == glyphCache.end())
{
bool result;
std::tie(findIt, result) = glyphCache.emplace(glyph.unicode, GetBitmapForGlyph(glyph, fontSize, glyphColor));
if (!result) return;
}
if (hlCellCoords.GetCol() == col && hlCellCoords.GetRow() == row)
{
gc->SetPen(wxPen(hlColor, 1));
gc->DrawRoundedRectangle(newRect.x + 1, newRect.y + 1, newRect.width - 2, newRect.height - 2, 5);
}
newRect.height -= labelFont.GetPixelSize().GetHeight() + 2 * padding;
const wxBitmap &glyphBitmap = findIt->second;
gc->DrawBitmap(glyphBitmap,
newRect.x + (newRect.width - glyphBitmap.GetWidth()) / 2,
newRect.y + (newRect.height - glyphBitmap.GetHeight()) / 2,
glyphBitmap.GetWidth(), glyphBitmap.GetHeight());
double width, height, descent, externalLeading;
gc->SetFont(labelFont, labelColor);
gc->GetTextExtent(label, &width, &height, &descent, &externalLeading);
gc->DrawText(label, newRect.x + (newRect.width - width) / 2, newRect.y + newRect.height + padding);
}
wxSize GlyphCellRenderer::GetBestSize(wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, int row, int col)
{
return wxSize(fontSize + padding, fontSize + labelFont.GetPixelSize().GetHeight() + 3 * padding);
}
<commit_msg>get rid of wxGraphicsRenderer::GetName method usage<commit_after>#include "glyphcellrenderer.h"
#include "wxcontext.h"
#include <wx/dcclient.h>
#include <wx/graphics.h>
#include <wx/settings.h>
#include <memory>
GlyphCellRenderer::GlyphCellRenderer(const std::map<wxString, SvgGlyph> &glyphs, int fontSize): glyphs(glyphs), fontSize(fontSize)
{
labelFont = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
glyphColor = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT);
hlColor = wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE);
labelColor = glyphColor.ChangeLightness(150);
}
wxGridCellRenderer *GlyphCellRenderer::Clone() const
{
return nullptr;
}
void GlyphCellRenderer::SetHighlightCell(const wxGridCellCoords &coords)
{
hlCellCoords = coords;
}
const wxGridCellCoords &GlyphCellRenderer::GetHighlightCell() const
{
return hlCellCoords;
}
void GlyphCellRenderer::Draw(wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, const wxRect &rect, int row, int col, bool isSelected)
{
wxGridCellRenderer::Draw(grid, attr, dc, rect, row, col, false);
wxString value = grid.GetTable()->GetValue(row, col);
wxString label;
auto it = glyphs.find(value);
if (it == glyphs.end()) return;
const SvgGlyph &glyph = it->second;
if (!glyph.IsOk())
return;
label.Printf("%04x", glyph.unicode[0]);
std::unique_ptr<wxGraphicsContext> gc(wxGraphicsContext::Create(static_cast<wxPaintDC&>(dc)));
wxRect newRect = rect;
// replace with gc->GetRenderer()->GetName() == L"cairo" after wx 3.1
bool isCairo = false;
#if wxUSE_CAIRO
isCairo = true;
#endif
// Oh, crap
if (isCairo)
{
newRect.x += dc.GetDeviceOrigin().x;
newRect.y += dc.GetDeviceOrigin().y;
}
std::map<wxString, wxBitmap>::iterator findIt = glyphCache.find(glyph.unicode);
if (findIt == glyphCache.end())
{
bool result;
std::tie(findIt, result) = glyphCache.emplace(glyph.unicode, GetBitmapForGlyph(glyph, fontSize, glyphColor));
if (!result) return;
}
if (hlCellCoords.GetCol() == col && hlCellCoords.GetRow() == row)
{
gc->SetPen(wxPen(hlColor, 1));
gc->DrawRoundedRectangle(newRect.x + 1, newRect.y + 1, newRect.width - 2, newRect.height - 2, 5);
}
newRect.height -= labelFont.GetPixelSize().GetHeight() + 2 * padding;
const wxBitmap &glyphBitmap = findIt->second;
gc->DrawBitmap(glyphBitmap,
newRect.x + (newRect.width - glyphBitmap.GetWidth()) / 2,
newRect.y + (newRect.height - glyphBitmap.GetHeight()) / 2,
glyphBitmap.GetWidth(), glyphBitmap.GetHeight());
double width, height, descent, externalLeading;
gc->SetFont(labelFont, labelColor);
gc->GetTextExtent(label, &width, &height, &descent, &externalLeading);
gc->DrawText(label, newRect.x + (newRect.width - width) / 2, newRect.y + newRect.height + padding);
}
wxSize GlyphCellRenderer::GetBestSize(wxGrid &grid, wxGridCellAttr &attr, wxDC &dc, int row, int col)
{
return wxSize(fontSize + padding, fontSize + labelFont.GetPixelSize().GetHeight() + 3 * padding);
}
<|endoftext|>
|
<commit_before>#include "Patch.hpp"
#include <Utils/Util.hpp>
using namespace AnvilCommon;
using namespace AnvilEldorado::Patches;
void ApplyAfterTagsLoaded()
{
// TODO: Perform any actions that need to be done after tags are loaded here.
}
__declspec(naked) void TagsLoadedHook()
{
__asm
{
call ApplyAfterTagsLoaded
push 0x6D617467
push 0x5030EF
ret
}
}
void AnvilPatch::Patch_Tags()
{
// Enable Tag Editing
Utils::Util::PatchAddressInFile(0x101A5B, "\xEB", 1);
Utils::Util::PatchAddressInFile(0x102874, "\x90\x90", 2);
Utils::Util::PatchAddressInFile(0x1030AA, "\x90\x90", 2);
// Used to call Patches::ApplyAfterTagsLoaded when tags have loaded
Utils::Util::ApplyHook(0x5030EA, TagsLoadedHook);
}<commit_msg>Fixed address of TagsLoadedHook in AnvilEldorado<commit_after>#include "Patch.hpp"
#include <Utils/Util.hpp>
using namespace AnvilCommon;
using namespace AnvilEldorado::Patches;
void ApplyAfterTagsLoaded()
{
// TODO: Perform any actions that need to be done after tags are loaded here.
}
__declspec(naked) void TagsLoadedHook()
{
__asm
{
call ApplyAfterTagsLoaded
push 0x6D617467
push 0x5030EF
ret
}
}
void AnvilPatch::Patch_Tags()
{
// Enable Tag Editing
Utils::Util::PatchAddressInFile(0x101A5B, "\xEB", 1);
Utils::Util::PatchAddressInFile(0x102874, "\x90\x90", 2);
Utils::Util::PatchAddressInFile(0x1030AA, "\x90\x90", 2);
// Used to call Patches::ApplyAfterTagsLoaded when tags have loaded
Utils::Util::ApplyHook(0x1030EA, TagsLoadedHook);
}
<|endoftext|>
|
<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <cstring>
#include <iostream>
#include <ostream>
#include <vector>
#include <visionaray/gl/compositing.h>
#include <visionaray/gl/handle.h>
#include <visionaray/gl/program.h>
#include <visionaray/gl/shader.h>
#include <visionaray/gl/util.h>
#include <visionaray/pixel_format.h>
namespace visionaray
{
namespace gl
{
#if !defined(VSNRAY_OPENGL_LEGACY)
//-------------------------------------------------------------------------------------------------
// Shader program to display color texture w/o depth compositing
//
struct color_program
{
color_program();
~color_program();
// The program
gl::program prog;
// The vertex shader
gl::shader vert;
// The fragment shader
gl::shader frag;
// Attribute location of vertex
GLint vertex_loc;
// Attribute location of texture coordinate
GLint tex_coord_loc;
// Uniform location of color texture
GLint color_loc;
void enable(gl::texture const& color_texture) const;
void disable() const;
};
//-------------------------------------------------------------------------------------------------
// color program implementation
//
color_program::color_program()
: prog(glCreateProgram())
, vert(glCreateShader(GL_VERTEX_SHADER))
, frag(glCreateShader(GL_FRAGMENT_SHADER))
{
vert.set_source(R"(
in vec2 vertex;
in vec2 tex_coord;
varying out vec2 uv;
void main(void)
{
gl_Position = vec4(vertex, 0.0, 1.0);
uv = tex_coord;
}
)");
vert.compile();
if (!vert.check_compiled())
{
return;
}
frag.set_source(R"(
varying in vec2 uv;
uniform sampler2D color_tex;
void main(void)
{
gl_FragColor = texture2D(color_tex, uv);
}
)");
frag.compile();
if (!frag.check_compiled())
{
return;
}
prog.attach_shader(vert);
prog.attach_shader(frag);
prog.link();
if (!prog.check_linked())
{
return;
}
vertex_loc = glGetAttribLocation(prog.get(), "vertex");
tex_coord_loc = glGetAttribLocation(prog.get(), "tex_coord");
color_loc = glGetUniformLocation(prog.get(), "color_tex");
}
color_program::~color_program()
{
prog.detach_shader(vert);
prog.detach_shader(frag);
}
void color_program::enable(gl::texture const& color_texture) const
{
prog.enable();
glUniform1i(color_loc, 0);
glActiveTexture(GL_TEXTURE0 + 0);
glBindTexture(GL_TEXTURE_2D, color_texture.get());
}
void color_program::disable() const
{
prog.disable();
}
//-------------------------------------------------------------------------------------------------
// Shader program to composite depth textures
//
struct depth_program
{
depth_program();
~depth_program();
// The program
gl::program prog;
// The vertex shader
gl::shader vert;
// The fragment shader
gl::shader frag;
// Attribute location of vertex
GLint vertex_loc;
// Attribute location of texture coordinate
GLint tex_coord_loc;
// Uniform location of color texture
GLint color_loc;
// Uniform location of depth texture
GLint depth_loc;
void enable(gl::texture const& color_texture, gl::texture const& depth_texture) const;
void disable() const;
};
//-------------------------------------------------------------------------------------------------
// depth program implementation
//
depth_program::depth_program()
: prog(glCreateProgram())
, vert(glCreateShader(GL_VERTEX_SHADER))
, frag(glCreateShader(GL_FRAGMENT_SHADER))
{
vert.set_source(R"(
in vec2 vertex;
in vec2 tex_coord;
varying out vec2 uv;
void main(void)
{
gl_Position = vec4(vertex, 0.0, 1.0);
uv = tex_coord;
}
)");
vert.compile();
if (!vert.check_compiled())
{
return;
}
frag.set_source(R"(
varying in vec2 uv;
uniform sampler2D color_tex;
uniform sampler2D depth_tex;
void main(void)
{
gl_FragColor = texture2D(color_tex, uv);
gl_FragDepth = texture2D(depth_tex, uv).x;
}
)");
frag.compile();
if (!frag.check_compiled())
{
return;
}
prog.attach_shader(vert);
prog.attach_shader(frag);
prog.link();
if (!prog.check_linked())
{
return;
}
vertex_loc = glGetAttribLocation(prog.get(), "vertex");
tex_coord_loc = glGetAttribLocation(prog.get(), "tex_coord");
color_loc = glGetUniformLocation(prog.get(), "color_tex");
depth_loc = glGetUniformLocation(prog.get(), "depth_tex");
}
depth_program::~depth_program()
{
prog.detach_shader(frag);
}
void depth_program::enable(
gl::texture const& color_texture,
gl::texture const& depth_texture
) const
{
prog.enable();
glUniform1i(color_loc, 0);
glActiveTexture(GL_TEXTURE0 + 0);
glBindTexture(GL_TEXTURE_2D, color_texture.get());
glUniform1i(depth_loc, 1);
glActiveTexture(GL_TEXTURE0 + 1);
glBindTexture(GL_TEXTURE_2D, depth_texture.get());
}
void depth_program::disable() const
{
prog.disable();
}
#endif // !VSNRAY_OPENGL_LEGACY
//-------------------------------------------------------------------------------------------------
// depth compositor private implementation
//
struct depth_compositor::impl
{
#if !defined(VSNRAY_OPENGL_LEGACY)
impl()
: vertex_buffer(create_buffer())
, tex_coord_buffer(create_buffer())
{
GLfloat verts[8] = {
-1.0f, -1.0f,
1.0f, -1.0f,
1.0f, 1.0f,
-1.0f, 1.0f
};
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer.get());
glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(float), verts, GL_STATIC_DRAW);
GLfloat tex_coords[8] = {
0.0f, 0.0f,
1.0f, 0.0f,
1.0f, 1.0f,
0.0f, 1.0f
};
glBindBuffer(GL_ARRAY_BUFFER, tex_coord_buffer.get());
glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(float), tex_coords, GL_STATIC_DRAW);
}
// Shader program to only display color texture w/o depth compositing
color_program color_prog;
// Shader program for depth compositing
depth_program depth_prog;
// Quad vertex buffer
gl::buffer vertex_buffer;
// Quad texture coordinate buffer
gl::buffer tex_coord_buffer;
// GL color texture handle
gl::texture color_texture;
// GL color texture handle
gl::texture depth_texture;
#else
pixel_format_info color_info;
pixel_format_info depth_info;
GLvoid const* depth_buffer = nullptr;
GLvoid const* color_buffer = nullptr;
int width;
int height;
#endif
};
//-------------------------------------------------------------------------------------------------
// depth compositor public interface
//
depth_compositor::depth_compositor()
: impl_(new impl)
{
}
depth_compositor::~depth_compositor()
{
}
void depth_compositor::composite_textures() const
{
#if !defined(VSNRAY_OPENGL_LEGACY)
// Store OpenGL state
GLint active_texture = GL_TEXTURE0;
GLboolean depth_test = GL_FALSE;
glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
glGetBooleanv(GL_DEPTH_TEST, &depth_test);
glEnable(GL_DEPTH_TEST);
impl_->depth_prog.enable(impl_->color_texture, impl_->depth_texture);
glBindBuffer(GL_ARRAY_BUFFER, impl_->vertex_buffer.get());
glVertexAttribPointer(impl_->depth_prog.vertex_loc, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(impl_->depth_prog.vertex_loc);
glBindBuffer(GL_ARRAY_BUFFER, impl_->tex_coord_buffer.get());
glVertexAttribPointer(impl_->depth_prog.tex_coord_loc, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(impl_->depth_prog.tex_coord_loc);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glDisableVertexAttribArray(impl_->depth_prog.tex_coord_loc);
glDisableVertexAttribArray(impl_->depth_prog.vertex_loc);
impl_->depth_prog.disable();
// Restore OpenGL state
glActiveTexture(active_texture);
if (depth_test)
{
glEnable(GL_DEPTH_TEST);
}
else
{
glDisable(GL_DEPTH_TEST);
}
#else
glPushAttrib( GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_ENABLE_BIT );
glEnable(GL_STENCIL_TEST);
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
glStencilFunc(GL_ALWAYS, 1, 1);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
gl::blend_pixels(
impl_->width,
impl_->height,
impl_->depth_info.format,
impl_->depth_info.type,
impl_->depth_buffer
);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glStencilFunc(GL_EQUAL, 1, 1);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
glDisable(GL_DEPTH_TEST);
gl::blend_pixels(
impl_->width,
impl_->height,
impl_->color_info.format,
impl_->color_info.type,
impl_->color_buffer
);
glPopAttrib();
#endif
}
void depth_compositor::display_color_texture() const
{
#if !defined(VSNRAY_OPENGL_LEGACY)
// Store OpenGL state
GLint active_texture = GL_TEXTURE0;
glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
impl_->color_prog.enable(impl_->color_texture);
glBindBuffer(GL_ARRAY_BUFFER, impl_->vertex_buffer.get());
glVertexAttribPointer(impl_->color_prog.vertex_loc, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(impl_->color_prog.vertex_loc);
glBindBuffer(GL_ARRAY_BUFFER, impl_->tex_coord_buffer.get());
glVertexAttribPointer(impl_->color_prog.tex_coord_loc, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(impl_->color_prog.tex_coord_loc);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glDisableVertexAttribArray(impl_->color_prog.tex_coord_loc);
glDisableVertexAttribArray(impl_->color_prog.vertex_loc);
impl_->color_prog.disable();
// Restore OpenGL state
glActiveTexture(active_texture);
#else
gl::blend_pixels(
impl_->width,
impl_->height,
impl_->color_info.format,
impl_->color_info.type,
impl_->color_buffer
);
#endif
}
void depth_compositor::setup_color_texture(pixel_format_info info, GLsizei w, GLsizei h)
{
#if !defined(VSNRAY_OPENGL_LEGACY)
impl_->color_texture.reset( create_texture() );
glBindTexture(GL_TEXTURE_2D, impl_->color_texture.get());
alloc_texture(info, w, h);
#else
impl_->color_info = info;
impl_->width = w;
impl_->height = h;
#endif
}
void depth_compositor::setup_depth_texture(pixel_format_info info, GLsizei w, GLsizei h)
{
#if !defined(VSNRAY_OPENGL_LEGACY)
impl_->depth_texture.reset( create_texture() );
glBindTexture(GL_TEXTURE_2D, impl_->depth_texture.get());
alloc_texture(info, w, h);
#else
impl_->depth_info = info;
impl_->width = w;
impl_->height = h;
#endif
}
void depth_compositor::update_color_texture(
pixel_format_info info,
GLsizei w,
GLsizei h,
GLvoid const* data
) const
{
#if !defined(VSNRAY_OPENGL_LEGACY)
glBindTexture(GL_TEXTURE_2D, impl_->color_texture.get());
gl::update_texture( info, w, h, data );
#else
impl_->color_info = info;
impl_->width = w;
impl_->height = h;
impl_->color_buffer = data;
#endif
}
void depth_compositor::update_depth_texture(
pixel_format_info info,
GLsizei w,
GLsizei h,
GLvoid const* data
) const
{
#if !defined(VSNRAY_OPENGL_LEGACY)
glBindTexture(GL_TEXTURE_2D, impl_->depth_texture.get());
gl::update_texture( info, w, h, data );
#else
impl_->depth_info = info;
impl_->width = w;
impl_->height = h;
impl_->depth_buffer = data;
#endif
}
} // gl
} // visionaray
<commit_msg>No duplicate storage qualifiers in shader<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <cstring>
#include <iostream>
#include <ostream>
#include <vector>
#include <visionaray/gl/compositing.h>
#include <visionaray/gl/handle.h>
#include <visionaray/gl/program.h>
#include <visionaray/gl/shader.h>
#include <visionaray/gl/util.h>
#include <visionaray/pixel_format.h>
namespace visionaray
{
namespace gl
{
#if !defined(VSNRAY_OPENGL_LEGACY)
//-------------------------------------------------------------------------------------------------
// Shader program to display color texture w/o depth compositing
//
struct color_program
{
color_program();
~color_program();
// The program
gl::program prog;
// The vertex shader
gl::shader vert;
// The fragment shader
gl::shader frag;
// Attribute location of vertex
GLint vertex_loc;
// Attribute location of texture coordinate
GLint tex_coord_loc;
// Uniform location of color texture
GLint color_loc;
void enable(gl::texture const& color_texture) const;
void disable() const;
};
//-------------------------------------------------------------------------------------------------
// color program implementation
//
color_program::color_program()
: prog(glCreateProgram())
, vert(glCreateShader(GL_VERTEX_SHADER))
, frag(glCreateShader(GL_FRAGMENT_SHADER))
{
vert.set_source(R"(
attribute vec2 vertex;
attribute vec2 tex_coord;
varying vec2 uv;
void main(void)
{
gl_Position = vec4(vertex, 0.0, 1.0);
uv = tex_coord;
}
)");
vert.compile();
if (!vert.check_compiled())
{
return;
}
frag.set_source(R"(
varying vec2 uv;
uniform sampler2D color_tex;
void main(void)
{
gl_FragColor = texture2D(color_tex, uv);
}
)");
frag.compile();
if (!frag.check_compiled())
{
return;
}
prog.attach_shader(vert);
prog.attach_shader(frag);
prog.link();
if (!prog.check_linked())
{
return;
}
vertex_loc = glGetAttribLocation(prog.get(), "vertex");
tex_coord_loc = glGetAttribLocation(prog.get(), "tex_coord");
color_loc = glGetUniformLocation(prog.get(), "color_tex");
}
color_program::~color_program()
{
prog.detach_shader(vert);
prog.detach_shader(frag);
}
void color_program::enable(gl::texture const& color_texture) const
{
prog.enable();
glUniform1i(color_loc, 0);
glActiveTexture(GL_TEXTURE0 + 0);
glBindTexture(GL_TEXTURE_2D, color_texture.get());
}
void color_program::disable() const
{
prog.disable();
}
//-------------------------------------------------------------------------------------------------
// Shader program to composite depth textures
//
struct depth_program
{
depth_program();
~depth_program();
// The program
gl::program prog;
// The vertex shader
gl::shader vert;
// The fragment shader
gl::shader frag;
// Attribute location of vertex
GLint vertex_loc;
// Attribute location of texture coordinate
GLint tex_coord_loc;
// Uniform location of color texture
GLint color_loc;
// Uniform location of depth texture
GLint depth_loc;
void enable(gl::texture const& color_texture, gl::texture const& depth_texture) const;
void disable() const;
};
//-------------------------------------------------------------------------------------------------
// depth program implementation
//
depth_program::depth_program()
: prog(glCreateProgram())
, vert(glCreateShader(GL_VERTEX_SHADER))
, frag(glCreateShader(GL_FRAGMENT_SHADER))
{
vert.set_source(R"(
in vec2 vertex;
in vec2 tex_coord;
varying out vec2 uv;
void main(void)
{
gl_Position = vec4(vertex, 0.0, 1.0);
uv = tex_coord;
}
)");
vert.compile();
if (!vert.check_compiled())
{
return;
}
frag.set_source(R"(
varying in vec2 uv;
uniform sampler2D color_tex;
uniform sampler2D depth_tex;
void main(void)
{
gl_FragColor = texture2D(color_tex, uv);
gl_FragDepth = texture2D(depth_tex, uv).x;
}
)");
frag.compile();
if (!frag.check_compiled())
{
return;
}
prog.attach_shader(vert);
prog.attach_shader(frag);
prog.link();
if (!prog.check_linked())
{
return;
}
vertex_loc = glGetAttribLocation(prog.get(), "vertex");
tex_coord_loc = glGetAttribLocation(prog.get(), "tex_coord");
color_loc = glGetUniformLocation(prog.get(), "color_tex");
depth_loc = glGetUniformLocation(prog.get(), "depth_tex");
}
depth_program::~depth_program()
{
prog.detach_shader(frag);
}
void depth_program::enable(
gl::texture const& color_texture,
gl::texture const& depth_texture
) const
{
prog.enable();
glUniform1i(color_loc, 0);
glActiveTexture(GL_TEXTURE0 + 0);
glBindTexture(GL_TEXTURE_2D, color_texture.get());
glUniform1i(depth_loc, 1);
glActiveTexture(GL_TEXTURE0 + 1);
glBindTexture(GL_TEXTURE_2D, depth_texture.get());
}
void depth_program::disable() const
{
prog.disable();
}
#endif // !VSNRAY_OPENGL_LEGACY
//-------------------------------------------------------------------------------------------------
// depth compositor private implementation
//
struct depth_compositor::impl
{
#if !defined(VSNRAY_OPENGL_LEGACY)
impl()
: vertex_buffer(create_buffer())
, tex_coord_buffer(create_buffer())
{
GLfloat verts[8] = {
-1.0f, -1.0f,
1.0f, -1.0f,
1.0f, 1.0f,
-1.0f, 1.0f
};
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer.get());
glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(float), verts, GL_STATIC_DRAW);
GLfloat tex_coords[8] = {
0.0f, 0.0f,
1.0f, 0.0f,
1.0f, 1.0f,
0.0f, 1.0f
};
glBindBuffer(GL_ARRAY_BUFFER, tex_coord_buffer.get());
glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(float), tex_coords, GL_STATIC_DRAW);
}
// Shader program to only display color texture w/o depth compositing
color_program color_prog;
// Shader program for depth compositing
depth_program depth_prog;
// Quad vertex buffer
gl::buffer vertex_buffer;
// Quad texture coordinate buffer
gl::buffer tex_coord_buffer;
// GL color texture handle
gl::texture color_texture;
// GL color texture handle
gl::texture depth_texture;
#else
pixel_format_info color_info;
pixel_format_info depth_info;
GLvoid const* depth_buffer = nullptr;
GLvoid const* color_buffer = nullptr;
int width;
int height;
#endif
};
//-------------------------------------------------------------------------------------------------
// depth compositor public interface
//
depth_compositor::depth_compositor()
: impl_(new impl)
{
}
depth_compositor::~depth_compositor()
{
}
void depth_compositor::composite_textures() const
{
#if !defined(VSNRAY_OPENGL_LEGACY)
// Store OpenGL state
GLint active_texture = GL_TEXTURE0;
GLboolean depth_test = GL_FALSE;
glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
glGetBooleanv(GL_DEPTH_TEST, &depth_test);
glEnable(GL_DEPTH_TEST);
impl_->depth_prog.enable(impl_->color_texture, impl_->depth_texture);
glBindBuffer(GL_ARRAY_BUFFER, impl_->vertex_buffer.get());
glVertexAttribPointer(impl_->depth_prog.vertex_loc, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(impl_->depth_prog.vertex_loc);
glBindBuffer(GL_ARRAY_BUFFER, impl_->tex_coord_buffer.get());
glVertexAttribPointer(impl_->depth_prog.tex_coord_loc, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(impl_->depth_prog.tex_coord_loc);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glDisableVertexAttribArray(impl_->depth_prog.tex_coord_loc);
glDisableVertexAttribArray(impl_->depth_prog.vertex_loc);
impl_->depth_prog.disable();
// Restore OpenGL state
glActiveTexture(active_texture);
if (depth_test)
{
glEnable(GL_DEPTH_TEST);
}
else
{
glDisable(GL_DEPTH_TEST);
}
#else
glPushAttrib( GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_ENABLE_BIT );
glEnable(GL_STENCIL_TEST);
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
glStencilFunc(GL_ALWAYS, 1, 1);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
gl::blend_pixels(
impl_->width,
impl_->height,
impl_->depth_info.format,
impl_->depth_info.type,
impl_->depth_buffer
);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glStencilFunc(GL_EQUAL, 1, 1);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
glDisable(GL_DEPTH_TEST);
gl::blend_pixels(
impl_->width,
impl_->height,
impl_->color_info.format,
impl_->color_info.type,
impl_->color_buffer
);
glPopAttrib();
#endif
}
void depth_compositor::display_color_texture() const
{
#if !defined(VSNRAY_OPENGL_LEGACY)
// Store OpenGL state
GLint active_texture = GL_TEXTURE0;
glGetIntegerv(GL_ACTIVE_TEXTURE, &active_texture);
impl_->color_prog.enable(impl_->color_texture);
glBindBuffer(GL_ARRAY_BUFFER, impl_->vertex_buffer.get());
glVertexAttribPointer(impl_->color_prog.vertex_loc, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(impl_->color_prog.vertex_loc);
glBindBuffer(GL_ARRAY_BUFFER, impl_->tex_coord_buffer.get());
glVertexAttribPointer(impl_->color_prog.tex_coord_loc, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(impl_->color_prog.tex_coord_loc);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glDisableVertexAttribArray(impl_->color_prog.tex_coord_loc);
glDisableVertexAttribArray(impl_->color_prog.vertex_loc);
impl_->color_prog.disable();
// Restore OpenGL state
glActiveTexture(active_texture);
#else
gl::blend_pixels(
impl_->width,
impl_->height,
impl_->color_info.format,
impl_->color_info.type,
impl_->color_buffer
);
#endif
}
void depth_compositor::setup_color_texture(pixel_format_info info, GLsizei w, GLsizei h)
{
#if !defined(VSNRAY_OPENGL_LEGACY)
impl_->color_texture.reset( create_texture() );
glBindTexture(GL_TEXTURE_2D, impl_->color_texture.get());
alloc_texture(info, w, h);
#else
impl_->color_info = info;
impl_->width = w;
impl_->height = h;
#endif
}
void depth_compositor::setup_depth_texture(pixel_format_info info, GLsizei w, GLsizei h)
{
#if !defined(VSNRAY_OPENGL_LEGACY)
impl_->depth_texture.reset( create_texture() );
glBindTexture(GL_TEXTURE_2D, impl_->depth_texture.get());
alloc_texture(info, w, h);
#else
impl_->depth_info = info;
impl_->width = w;
impl_->height = h;
#endif
}
void depth_compositor::update_color_texture(
pixel_format_info info,
GLsizei w,
GLsizei h,
GLvoid const* data
) const
{
#if !defined(VSNRAY_OPENGL_LEGACY)
glBindTexture(GL_TEXTURE_2D, impl_->color_texture.get());
gl::update_texture( info, w, h, data );
#else
impl_->color_info = info;
impl_->width = w;
impl_->height = h;
impl_->color_buffer = data;
#endif
}
void depth_compositor::update_depth_texture(
pixel_format_info info,
GLsizei w,
GLsizei h,
GLvoid const* data
) const
{
#if !defined(VSNRAY_OPENGL_LEGACY)
glBindTexture(GL_TEXTURE_2D, impl_->depth_texture.get());
gl::update_texture( info, w, h, data );
#else
impl_->depth_info = info;
impl_->width = w;
impl_->height = h;
impl_->depth_buffer = data;
#endif
}
} // gl
} // visionaray
<|endoftext|>
|
<commit_before>#include "LogsPopup.hpp"
#include "IrcMessage"
#include "common/Channel.hpp"
#include "common/NetworkRequest.hpp"
#include "providers/twitch/TwitchChannel.hpp"
#include "providers/twitch/TwitchMessageBuilder.hpp"
#include "widgets/helper/ChannelView.hpp"
#include <QDateTime>
#include <QJsonArray>
#include <QMessageBox>
#include <QVBoxLayout>
namespace chatterino {
LogsPopup::LogsPopup()
: channel_(Channel::getEmpty())
{
this->initLayout();
this->resize(400, 600);
}
void LogsPopup::initLayout()
{
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setMargin(0);
this->channelView_ = new ChannelView(this);
layout->addWidget(this->channelView_);
this->setLayout(layout);
}
void LogsPopup::setInfo(ChannelPtr channel, QString userName)
{
this->channel_ = channel;
this->userName_ = userName;
this->getRoomID();
this->setWindowTitle(this->userName_ + "'s logs in #" +
this->channel_->getName());
}
void LogsPopup::setMessages(std::vector<MessagePtr> &messages)
{
ChannelPtr logsChannel(new Channel("logs", Channel::Type::Misc));
logsChannel->addMessagesAtStart(messages);
this->channelView_->setChannel(logsChannel);
}
void LogsPopup::getRoomID()
{
TwitchChannel *twitchChannel =
dynamic_cast<TwitchChannel *>(this->channel_.get());
if (twitchChannel == nullptr)
{
return;
}
QString channelName = twitchChannel->getName();
QString url = QString("https://cbenni.com/api/channel/%1").arg(channelName);
NetworkRequest req(url);
req.setCaller(QThread::currentThread());
req.onError([this](int errorCode) {
this->getOverrustleLogs();
return true;
});
req.onSuccess([this, channelName](auto result) -> Outcome {
auto data = result.parseJson();
this->roomID_ = data.value("channel").toObject()["id"].toInt();
this->getLogviewerLogs();
return Success;
});
req.execute();
}
void LogsPopup::getLogviewerLogs()
{
TwitchChannel *twitchChannel =
dynamic_cast<TwitchChannel *>(this->channel_.get());
if (twitchChannel == nullptr)
{
return;
}
QString channelName = twitchChannel->getName();
auto url = QString("https://cbenni.com/api/logs/%1/?nick=%2&before=500")
.arg(channelName, this->userName_);
NetworkRequest req(url);
req.setCaller(QThread::currentThread());
req.onError([this](int errorCode) {
this->getOverrustleLogs();
return true;
});
req.onSuccess([this, channelName](auto result) -> Outcome {
auto data = result.parseJson();
std::vector<MessagePtr> messages;
QJsonValue before = data.value("before");
for (auto i : before.toArray())
{
auto messageObject = i.toObject();
QString message = messageObject.value("text").toString();
// Hacky way to fix the timestamp
message.insert(1, "historical=1;");
message.insert(1, QString("tmi-sent-ts=%10000;")
.arg(messageObject["time"].toInt()));
message.insert(1, QString("room-id=%1;").arg(this->roomID_));
MessageParseArgs args;
auto ircMessage =
Communi::IrcMessage::fromData(message.toUtf8(), nullptr);
auto privMsg =
static_cast<Communi::IrcPrivateMessage *>(ircMessage);
TwitchMessageBuilder builder(this->channel_.get(), privMsg, args);
messages.push_back(builder.build());
};
this->setMessages(messages);
return Success;
});
req.execute();
}
void LogsPopup::getOverrustleLogs()
{
TwitchChannel *twitchChannel =
dynamic_cast<TwitchChannel *>(this->channel_.get());
if (twitchChannel == nullptr)
{
return;
}
QString channelName = twitchChannel->getName();
QString url =
QString("https://overrustlelogs.net/api/v1/stalk/%1/%2.json?limit=500")
.arg(channelName, this->userName_);
NetworkRequest req(url);
req.setCaller(QThread::currentThread());
req.onError([channelName](int errorCode) {
// this->close();
auto box = new QMessageBox(
QMessageBox::Information, "Error getting logs",
"No logs could be found for channel " + channelName);
box->setAttribute(Qt::WA_DeleteOnClose);
box->show();
box->raise();
return true;
});
req.onSuccess([this, channelName](auto result) -> Outcome {
auto data = result.parseJson();
std::vector<MessagePtr> messages;
if (data.contains("lines"))
{
QJsonArray dataMessages = data.value("lines").toArray();
for (auto i : dataMessages)
{
QJsonObject singleMessage = i.toObject();
QTime timeStamp = QDateTime::fromSecsSinceEpoch(
singleMessage.value("timestamp").toInt())
.time();
MessageBuilder builder;
builder.emplace<TimestampElement>(timeStamp);
builder.emplace<TextElement>(this->userName_,
MessageElementFlag::Username,
MessageColor::System);
builder.emplace<TextElement>(
singleMessage.value("text").toString(),
MessageElementFlag::Text, MessageColor::Text);
messages.push_back(builder.release());
}
}
this->setMessages(messages);
return Success;
});
req.execute();
}
} // namespace chatterino
<commit_msg>Added closing LogsPopup with QMessageBox.<commit_after>#include "LogsPopup.hpp"
#include "IrcMessage"
#include "common/Channel.hpp"
#include "common/NetworkRequest.hpp"
#include "providers/twitch/TwitchChannel.hpp"
#include "providers/twitch/TwitchMessageBuilder.hpp"
#include "widgets/helper/ChannelView.hpp"
#include <QDateTime>
#include <QJsonArray>
#include <QMessageBox>
#include <QVBoxLayout>
namespace chatterino {
LogsPopup::LogsPopup()
: channel_(Channel::getEmpty())
{
this->initLayout();
this->resize(400, 600);
}
void LogsPopup::initLayout()
{
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setMargin(0);
this->channelView_ = new ChannelView(this);
layout->addWidget(this->channelView_);
this->setLayout(layout);
}
void LogsPopup::setInfo(ChannelPtr channel, QString userName)
{
this->channel_ = channel;
this->userName_ = userName;
this->getRoomID();
this->setWindowTitle(this->userName_ + "'s logs in #" +
this->channel_->getName());
}
void LogsPopup::setMessages(std::vector<MessagePtr> &messages)
{
ChannelPtr logsChannel(new Channel("logs", Channel::Type::Misc));
logsChannel->addMessagesAtStart(messages);
this->channelView_->setChannel(logsChannel);
}
void LogsPopup::getRoomID()
{
TwitchChannel *twitchChannel =
dynamic_cast<TwitchChannel *>(this->channel_.get());
if (twitchChannel == nullptr)
{
return;
}
QString channelName = twitchChannel->getName();
QString url = QString("https://cbenni.com/api/channel/%1").arg(channelName);
NetworkRequest req(url);
req.setCaller(QThread::currentThread());
req.onError([this](int errorCode) {
this->getOverrustleLogs();
return true;
});
req.onSuccess([this, channelName](auto result) -> Outcome {
auto data = result.parseJson();
this->roomID_ = data.value("channel").toObject()["id"].toInt();
this->getLogviewerLogs();
return Success;
});
req.execute();
}
void LogsPopup::getLogviewerLogs()
{
TwitchChannel *twitchChannel =
dynamic_cast<TwitchChannel *>(this->channel_.get());
if (twitchChannel == nullptr)
{
return;
}
QString channelName = twitchChannel->getName();
auto url = QString("https://cbenni.com/api/logs/%1/?nick=%2&before=500")
.arg(channelName, this->userName_);
NetworkRequest req(url);
req.setCaller(QThread::currentThread());
req.onError([this](int errorCode) {
this->getOverrustleLogs();
return true;
});
req.onSuccess([this, channelName](auto result) -> Outcome {
auto data = result.parseJson();
std::vector<MessagePtr> messages;
QJsonValue before = data.value("before");
for (auto i : before.toArray())
{
auto messageObject = i.toObject();
QString message = messageObject.value("text").toString();
// Hacky way to fix the timestamp
message.insert(1, "historical=1;");
message.insert(1, QString("tmi-sent-ts=%10000;")
.arg(messageObject["time"].toInt()));
message.insert(1, QString("room-id=%1;").arg(this->roomID_));
MessageParseArgs args;
auto ircMessage =
Communi::IrcMessage::fromData(message.toUtf8(), nullptr);
auto privMsg =
static_cast<Communi::IrcPrivateMessage *>(ircMessage);
TwitchMessageBuilder builder(this->channel_.get(), privMsg, args);
messages.push_back(builder.build());
};
this->setMessages(messages);
return Success;
});
req.execute();
}
void LogsPopup::getOverrustleLogs()
{
TwitchChannel *twitchChannel =
dynamic_cast<TwitchChannel *>(this->channel_.get());
if (twitchChannel == nullptr)
{
return;
}
QString channelName = twitchChannel->getName();
QString url =
QString("https://overrustlelogs.net/api/v1/stalk/%1/%2.json?limit=500")
.arg(channelName, this->userName_);
NetworkRequest req(url);
req.setCaller(QThread::currentThread());
req.onError([this, channelName](int errorCode) {
auto box = new QMessageBox(
QMessageBox::Information, "Error getting logs",
"No logs could be found for channel " + channelName);
box->setAttribute(Qt::WA_DeleteOnClose);
box->show();
box->raise();
static QSet<int> closeButtons {
QMessageBox::Ok,
QMessageBox::Close,
};
if (closeButtons.contains(box->exec()))
{
this->close();
}
return true;
});
req.onSuccess([this, channelName](auto result) -> Outcome {
auto data = result.parseJson();
std::vector<MessagePtr> messages;
if (data.contains("lines"))
{
QJsonArray dataMessages = data.value("lines").toArray();
for (auto i : dataMessages)
{
QJsonObject singleMessage = i.toObject();
QTime timeStamp = QDateTime::fromSecsSinceEpoch(
singleMessage.value("timestamp").toInt())
.time();
MessageBuilder builder;
builder.emplace<TimestampElement>(timeStamp);
builder.emplace<TextElement>(this->userName_,
MessageElementFlag::Username,
MessageColor::System);
builder.emplace<TextElement>(
singleMessage.value("text").toString(),
MessageElementFlag::Text, MessageColor::Text);
messages.push_back(builder.release());
}
}
this->setMessages(messages);
return Success;
});
req.execute();
}
} // namespace chatterino
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2011 Martin Klapetek <mklapetek@kde.org>
Copyright (C) 2013 David Edmundson <davidedmundsonk@kde.org>
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 "persondetailsview.h"
#include <QFormLayout>
#include <QLabel>
#include <QDebug>
#include <QList>
#include <KLocalizedString>
#include "abstractfieldwidgetfactory.h"
#include "plugins/emaildetailswidget.h"
namespace KPeople {
class PersonDetailsViewPrivate{
public:
PersonData *m_person;
QFormLayout *m_mainLayout;
QList<AbstractFieldWidgetFactory*> m_plugins;
};
}
using namespace KPeople;
class CoreFieldsPlugin : public AbstractFieldWidgetFactory
{
public:
CoreFieldsPlugin(KABC::Field *field);
virtual ~CoreFieldsPlugin();
virtual QString label() const;
virtual int sortWeight() const;
virtual QWidget* createDetailsWidget(const KABC::Addressee &person, QWidget *parent) const;
private:
KABC::Field* m_field;
};
CoreFieldsPlugin::CoreFieldsPlugin(KABC::Field* field):
m_field(field)
{
}
CoreFieldsPlugin::~CoreFieldsPlugin()
{
}
QString CoreFieldsPlugin::label() const
{
return m_field->label();
}
int CoreFieldsPlugin::sortWeight() const
{
return m_field->category()*10;
}
QWidget* CoreFieldsPlugin::createDetailsWidget(const KABC::Addressee &person, QWidget *parent) const
{
//don't handle emails here - KABC::Field just lists one which is rubbish. Instead use a custom plugin that lists everything
if (m_field->category() == KABC::Field::Email) {
return 0;
}
const QString &text = m_field->value(person);
if (text.isEmpty()) {
return 0;
}
return new QLabel(text, parent);
}
PersonDetailsView::PersonDetailsView(QWidget *parent)
: QWidget(parent),
d_ptr(new PersonDetailsViewPrivate())
{
Q_D(PersonDetailsView);
d->m_mainLayout = new QFormLayout(this);
d->m_person = 0;
//create plugins
Q_FOREACH(KABC::Field *field, KABC::Field::allFields()) {
d->m_plugins << new CoreFieldsPlugin(field);
}
d->m_plugins << new EmailFieldsPlugin();
//TODO Sort plugins
}
PersonDetailsView::~PersonDetailsView()
{
Q_D(PersonDetailsView);
// qDeleteAll<AbstractFieldWidgetFactory>(d->m_plugins);
delete d_ptr;
}
void PersonDetailsView::setPerson(PersonData *person)
{
Q_D(PersonDetailsView);
if (!d->m_person) {
disconnect(d->m_person, SIGNAL(dataChanged()), this, SLOT(reload()));
}
d->m_person = person;
connect(d->m_person, SIGNAL(dataChanged()), this, SLOT(reload()));
reload();
}
// void PersonDetailsView::setPersonsModel(PersonsModel *model)
// {
// Q_D(PersonDetailsView);
// Q_FOREACH (AbstractPersonDetailsWidget *detailsWidget, d->m_detailWidgets) {
// detailsWidget->setPersonsModel(model);
// }
// }
void PersonDetailsView::reload()
{
Q_D(PersonDetailsView);
//delete everything currently in the layout
QLayoutItem *child;
while ((child = layout()->takeAt(0)) != 0) {
delete child->widget();
delete child;
}
Q_FOREACH(AbstractFieldWidgetFactory *widgetFactory, d->m_plugins) {
const QString label = widgetFactory->label() + ':';
QWidget *widget = widgetFactory->createDetailsWidget(d->m_person->person(), this);
if (widget) {
QFont font = widget->font();
font.setBold(true);
widget->setFont(font);
d->m_mainLayout->addRow(label, widget);
}
}
}
<commit_msg>Create our own label in PersonDetailsView<commit_after>/*
Copyright (C) 2011 Martin Klapetek <mklapetek@kde.org>
Copyright (C) 2013 David Edmundson <davidedmundsonk@kde.org>
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 "persondetailsview.h"
#include <QFormLayout>
#include <QLabel>
#include <QDebug>
#include <QList>
#include <KLocalizedString>
#include "abstractfieldwidgetfactory.h"
#include "plugins/emaildetailswidget.h"
namespace KPeople {
class PersonDetailsViewPrivate{
public:
PersonData *m_person;
QFormLayout *m_mainLayout;
QList<AbstractFieldWidgetFactory*> m_plugins;
};
}
using namespace KPeople;
class CoreFieldsPlugin : public AbstractFieldWidgetFactory
{
public:
CoreFieldsPlugin(KABC::Field *field);
virtual ~CoreFieldsPlugin();
virtual QString label() const;
virtual int sortWeight() const;
virtual QWidget* createDetailsWidget(const KABC::Addressee &person, QWidget *parent) const;
private:
KABC::Field* m_field;
};
CoreFieldsPlugin::CoreFieldsPlugin(KABC::Field* field):
m_field(field)
{
}
CoreFieldsPlugin::~CoreFieldsPlugin()
{
}
QString CoreFieldsPlugin::label() const
{
return m_field->label();
}
int CoreFieldsPlugin::sortWeight() const
{
return m_field->category()*10;
}
QWidget* CoreFieldsPlugin::createDetailsWidget(const KABC::Addressee &person, QWidget *parent) const
{
//don't handle emails here - KABC::Field just lists one which is rubbish. Instead use a custom plugin that lists everything
if (m_field->category() == KABC::Field::Email) {
return 0;
}
const QString &text = m_field->value(person);
if (text.isEmpty()) {
return 0;
}
return new QLabel(text, parent);
}
PersonDetailsView::PersonDetailsView(QWidget *parent)
: QWidget(parent),
d_ptr(new PersonDetailsViewPrivate())
{
Q_D(PersonDetailsView);
d->m_mainLayout = new QFormLayout(this);
d->m_person = 0;
//create plugins
Q_FOREACH(KABC::Field *field, KABC::Field::allFields()) {
d->m_plugins << new CoreFieldsPlugin(field);
}
d->m_plugins << new EmailFieldsPlugin();
//TODO Sort plugins
}
PersonDetailsView::~PersonDetailsView()
{
Q_D(PersonDetailsView);
// qDeleteAll<AbstractFieldWidgetFactory>(d->m_plugins);
delete d_ptr;
}
void PersonDetailsView::setPerson(PersonData *person)
{
Q_D(PersonDetailsView);
if (!d->m_person) {
disconnect(d->m_person, SIGNAL(dataChanged()), this, SLOT(reload()));
}
d->m_person = person;
connect(d->m_person, SIGNAL(dataChanged()), this, SLOT(reload()));
reload();
}
// void PersonDetailsView::setPersonsModel(PersonsModel *model)
// {
// Q_D(PersonDetailsView);
// Q_FOREACH (AbstractPersonDetailsWidget *detailsWidget, d->m_detailWidgets) {
// detailsWidget->setPersonsModel(model);
// }
// }
void PersonDetailsView::reload()
{
Q_D(PersonDetailsView);
//delete everything currently in the layout
QLayoutItem *child;
while ((child = layout()->takeAt(0)) != 0) {
delete child->widget();
delete child;
}
Q_FOREACH(AbstractFieldWidgetFactory *widgetFactory, d->m_plugins) {
const QString label = widgetFactory->label() + ':';
QWidget *widget = widgetFactory->createDetailsWidget(d->m_person->person(), this);
if (widget) {
QFont font = widget->font();
font.setBold(true);
widget->setFont(font);
QLabel *widgetLabel = new QLabel(label, this);
d->m_mainLayout->addRow(widgetLabel, widget);
}
}
}
<|endoftext|>
|
<commit_before>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2017 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/base/debugging.h"
#include <cstdarg>
#include <signal.h>
#include "xenia/base/string_buffer.h"
namespace xe {
namespace debugging {
bool IsDebuggerAttached() { return false; }
void Break() { raise(SIGTRAP); }
void DebugPrint(const char* fmt, ...) {
StringBuffer buff;
va_list va;
va_start(va, fmt);
buff.AppendVarargs(fmt, va);
va_end(va);
// OutputDebugStringA(buff.GetString());
}
} // namespace debugging
} // namespace xe
<commit_msg>Fix Travis :|<commit_after>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2017 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/base/debugging.h"
#include <signal.h>
#include <cstdarg>
#include "xenia/base/string_buffer.h"
namespace xe {
namespace debugging {
bool IsDebuggerAttached() { return false; }
void Break() { raise(SIGTRAP); }
void DebugPrint(const char* fmt, ...) {
StringBuffer buff;
va_list va;
va_start(va, fmt);
buff.AppendVarargs(fmt, va);
va_end(va);
// OutputDebugStringA(buff.GetString());
}
} // namespace debugging
} // namespace xe
<|endoftext|>
|
<commit_before>#ifndef STAN_MATH_PRIM_FUN_TO_COMPLEX_HPP
#define STAN_MATH_PRIM_FUN_TO_COMPLEX_HPP
#include <stan/math/prim/meta.hpp>
#include <complex>
namespace stan {
namespace math {
/**
* Return the real part of the complex argument.
*
* @return a complex type with real and imaginary set to 0
*/
std::complex<double> to_complex(){
return std::complex<double>(0, 0);
}
/**
* Return the real part of the complex argument.
*
* @tparam T value type of argument
* @param[in] re real value argument
* @param[in] im imaginary value argument
* @return complex type with real value set to re and imaginary
* set im or 0 if no second argument is supplied
*/
template <typename T>
std::complex<T> to_complex(const T& re, const T& im = 0){
return std::complex<T>(re, im);
}
} // namespace math
} // namespace stan
#endif
<commit_msg>Added inline keyword<commit_after>#ifndef STAN_MATH_PRIM_FUN_TO_COMPLEX_HPP
#define STAN_MATH_PRIM_FUN_TO_COMPLEX_HPP
#include <stan/math/prim/meta.hpp>
#include <complex>
namespace stan {
namespace math {
/**
* Return the real part of the complex argument.
*
* @return a complex type with real and imaginary set to 0
*/
inline std::complex<double> to_complex(){
return std::complex<double>(0, 0);
}
/**
* Return the real part of the complex argument.
*
* @tparam T value type of argument
* @param[in] re real value argument
* @param[in] im imaginary value argument
* @return complex type with real value set to re and imaginary
* set im or 0 if no second argument is supplied
*/
template <typename T>
inline std::complex<T> to_complex(const T& re, const T& im = 0){
return std::complex<T>(re, im);
}
} // namespace math
} // namespace stan
#endif
<|endoftext|>
|
<commit_before>#ifndef STAN_MATH_REV_FUNCTOR_ODE_BDF_HPP
#define STAN_MATH_REV_FUNCTOR_ODE_BDF_HPP
#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/functor/cvodes_integrator.hpp>
#include <ostream>
#include <vector>
namespace stan {
namespace math {
/**
* Solve the ODE initial value problem y' = f(t, y), y(t0) = y0 at a set of
* times, { t1, t2, t3, ... } using the stiff backward differentiation formula
* BDF solver from CVODES.
*
* \p f must define an operator() with the signature as:
* template<typename T_t, typename T_y, typename... T_Args>
* Eigen::Matrix<stan::return_type_t<T_t, T_y, T_Args...>, Eigen::Dynamic, 1>
* operator()(const T_t& t, const Eigen::Matrix<T_y, Eigen::Dynamic, 1>& y,
* std::ostream* msgs, const T_Args&... args);
*
* t is the time, y is the state, msgs is a stream for error messages, and args
* are optional arguments passed to the ODE solve function (which are passed
* through to \p f without modification).
*
* @tparam F Type of ODE right hand side
* @tparam T_0 Type of initial time
* @tparam T_ts Type of output times
* @tparam T_Args Types of pass-through parameters
*
* @param f Right hand side of the ODE
* @param y0 Initial state
* @param t0 Initial time
* @param ts Times at which to solve the ODE at. All values must be sorted and
* not less than t0.
* @param relative_tolerance Relative tolerance passed to CVODES
* @param absolute_tolerance Absolute tolerance passed to CVODES
* @param max_num_steps Upper limit on the number of integration steps to
* take between each output (error if exceeded)
* @param[in, out] msgs the print stream for warning messages
* @param args Extra arguments passed unmodified through to ODE right hand side
* @return Solution to ODE at times \p ts
*/
template <typename F, typename T_initial, typename T_t0, typename T_ts,
typename... T_Args>
std::vector<Eigen::Matrix<stan::return_type_t<T_initial, T_t0, T_ts, T_Args...>,
Eigen::Dynamic, 1>>
ode_bdf_tol(const F& f, const Eigen::Matrix<T_initial, Eigen::Dynamic, 1>& y0,
const T_t0& t0, const std::vector<T_ts>& ts,
double relative_tolerance, double absolute_tolerance,
long int max_num_steps, std::ostream* msgs, const T_Args&... args) {
cvodes_integrator<CV_BDF, F, T_initial, T_t0, T_ts,
T_Args...> integrator(f, y0, t0, ts,
relative_tolerance, absolute_tolerance,
max_num_steps,
msgs, args...);
return integrator();
}
/**
* Solve the ODE initial value problem y' = f(t, y), y(t0) = y0 at a set of
* times, { t1, t2, t3, ... } using the stiff backward differentiation formula
* (BDF) solver in CVODES with a relative tolerance of 1e-10, an absolute
* tolerance of 1e-10, and taking a maximum of 1e8 steps.
*
* \p f must define an operator() with the signature as:
* template<typename T_t, typename T_y, typename... T_Args>
* Eigen::Matrix<stan::return_type_t<T_t, T_y, T_Args...>, Eigen::Dynamic, 1>
* operator()(const T_t& t, const Eigen::Matrix<T_y, Eigen::Dynamic, 1>& y,
* std::ostream* msgs, const T_Args&... args);
*
* t is the time, y is the state, msgs is a stream for error messages, and args
* are optional arguments passed to the ODE solve function (which are passed
* through to \p f without modification).
*
* @tparam F Type of ODE right hand side
* @tparam T_0 Type of initial time
* @tparam T_ts Type of output times
* @tparam T_Args Types of pass-through parameters
*
* @param f Right hand side of the ODE
* @param y0 Initial state
* @param t0 Initial time
* @param ts Times at which to solve the ODE at. All values must be sorted and
* not less than t0.
* @param relative_tolerance Relative tolerance passed to CVODES
* @param absolute_tolerance Absolute tolerance passed to CVODES
* @param max_num_steps Upper limit on the number of integration steps to
* take between each output (error if exceeded)
* @param[in, out] msgs the print stream for warning messages
* @param args Extra arguments passed unmodified through to ODE right hand side
* @return Solution to ODE at times \p ts
*/
template <typename F, typename T_initial, typename T_t0, typename T_ts,
typename... T_Args>
std::vector<Eigen::Matrix<stan::return_type_t<T_initial, T_t0, T_ts, T_Args...>,
Eigen::Dynamic, 1>>
ode_bdf(const F& f, const Eigen::Matrix<T_initial, Eigen::Dynamic, 1>& y0,
const T_t0& t0, const std::vector<T_ts>& ts, std::ostream* msgs,
const T_Args&... args) {
double relative_tolerance = 1e-10;
double absolute_tolerance = 1e-10;
long int max_num_steps = 1e8;
return ode_bdf_tol(f, y0, t0, ts, relative_tolerance, absolute_tolerance,
max_num_steps, msgs, args...);
}
} // namespace math
} // namespace stan
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags/RELEASE_600/final)<commit_after>#ifndef STAN_MATH_REV_FUNCTOR_ODE_BDF_HPP
#define STAN_MATH_REV_FUNCTOR_ODE_BDF_HPP
#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/functor/cvodes_integrator.hpp>
#include <ostream>
#include <vector>
namespace stan {
namespace math {
/**
* Solve the ODE initial value problem y' = f(t, y), y(t0) = y0 at a set of
* times, { t1, t2, t3, ... } using the stiff backward differentiation formula
* BDF solver from CVODES.
*
* \p f must define an operator() with the signature as:
* template<typename T_t, typename T_y, typename... T_Args>
* Eigen::Matrix<stan::return_type_t<T_t, T_y, T_Args...>, Eigen::Dynamic, 1>
* operator()(const T_t& t, const Eigen::Matrix<T_y, Eigen::Dynamic, 1>& y,
* std::ostream* msgs, const T_Args&... args);
*
* t is the time, y is the state, msgs is a stream for error messages, and args
* are optional arguments passed to the ODE solve function (which are passed
* through to \p f without modification).
*
* @tparam F Type of ODE right hand side
* @tparam T_0 Type of initial time
* @tparam T_ts Type of output times
* @tparam T_Args Types of pass-through parameters
*
* @param f Right hand side of the ODE
* @param y0 Initial state
* @param t0 Initial time
* @param ts Times at which to solve the ODE at. All values must be sorted and
* not less than t0.
* @param relative_tolerance Relative tolerance passed to CVODES
* @param absolute_tolerance Absolute tolerance passed to CVODES
* @param max_num_steps Upper limit on the number of integration steps to
* take between each output (error if exceeded)
* @param[in, out] msgs the print stream for warning messages
* @param args Extra arguments passed unmodified through to ODE right hand side
* @return Solution to ODE at times \p ts
*/
template <typename F, typename T_initial, typename T_t0, typename T_ts,
typename... T_Args>
std::vector<Eigen::Matrix<stan::return_type_t<T_initial, T_t0, T_ts, T_Args...>,
Eigen::Dynamic, 1>>
ode_bdf_tol(const F& f, const Eigen::Matrix<T_initial, Eigen::Dynamic, 1>& y0,
const T_t0& t0, const std::vector<T_ts>& ts,
double relative_tolerance, double absolute_tolerance,
long int max_num_steps, std::ostream* msgs, const T_Args&... args) {
cvodes_integrator<CV_BDF, F, T_initial, T_t0, T_ts, T_Args...> integrator(
f, y0, t0, ts, relative_tolerance, absolute_tolerance, max_num_steps,
msgs, args...);
return integrator();
}
/**
* Solve the ODE initial value problem y' = f(t, y), y(t0) = y0 at a set of
* times, { t1, t2, t3, ... } using the stiff backward differentiation formula
* (BDF) solver in CVODES with a relative tolerance of 1e-10, an absolute
* tolerance of 1e-10, and taking a maximum of 1e8 steps.
*
* \p f must define an operator() with the signature as:
* template<typename T_t, typename T_y, typename... T_Args>
* Eigen::Matrix<stan::return_type_t<T_t, T_y, T_Args...>, Eigen::Dynamic, 1>
* operator()(const T_t& t, const Eigen::Matrix<T_y, Eigen::Dynamic, 1>& y,
* std::ostream* msgs, const T_Args&... args);
*
* t is the time, y is the state, msgs is a stream for error messages, and args
* are optional arguments passed to the ODE solve function (which are passed
* through to \p f without modification).
*
* @tparam F Type of ODE right hand side
* @tparam T_0 Type of initial time
* @tparam T_ts Type of output times
* @tparam T_Args Types of pass-through parameters
*
* @param f Right hand side of the ODE
* @param y0 Initial state
* @param t0 Initial time
* @param ts Times at which to solve the ODE at. All values must be sorted and
* not less than t0.
* @param relative_tolerance Relative tolerance passed to CVODES
* @param absolute_tolerance Absolute tolerance passed to CVODES
* @param max_num_steps Upper limit on the number of integration steps to
* take between each output (error if exceeded)
* @param[in, out] msgs the print stream for warning messages
* @param args Extra arguments passed unmodified through to ODE right hand side
* @return Solution to ODE at times \p ts
*/
template <typename F, typename T_initial, typename T_t0, typename T_ts,
typename... T_Args>
std::vector<Eigen::Matrix<stan::return_type_t<T_initial, T_t0, T_ts, T_Args...>,
Eigen::Dynamic, 1>>
ode_bdf(const F& f, const Eigen::Matrix<T_initial, Eigen::Dynamic, 1>& y0,
const T_t0& t0, const std::vector<T_ts>& ts, std::ostream* msgs,
const T_Args&... args) {
double relative_tolerance = 1e-10;
double absolute_tolerance = 1e-10;
long int max_num_steps = 1e8;
return ode_bdf_tol(f, y0, t0, ts, relative_tolerance, absolute_tolerance,
max_num_steps, msgs, args...);
}
} // namespace math
} // namespace stan
#endif
<|endoftext|>
|
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2004 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
#include <iomanip>
#include <fstream>
// Local includes
#include "mesh.h"
#include "libmesh_config.h"
#include "medit_io.h"
// ------------------------------------------------------------
// MEDITIO members
void MEDITIO::write (const std::string& fname)
{
if (libMesh::processor_id() == 0)
if (!this->binary())
this->write_ascii (fname);
}
void MEDITIO::write_nodal_data (const std::string& fname,
const std::vector<Number>& soln,
const std::vector<std::string>& names)
{
if (libMesh::processor_id() == 0)
if (!this->binary())
this->write_ascii (fname, &soln, &names);
}
void MEDITIO::write_ascii (const std::string& fname,
const std::vector<Number>* vec,
const std::vector<std::string>* solution_names)
{
// Current lacks in implementation:
// (i) only 3D meshes.
// (ii) only QUAD4, TRI3, TET4 elements, others are omitted !
// (iii) no distinction between materials.
// (iv) no vector output, just first scalar as output
// assert three dimensions (should be extended later)
assert (this->cmesh().mesh_dimension() == 3);
// Open the output file stream
std::ofstream out (fname.c_str());
assert (out.good());
// Get a reference to the mesh
const MeshBase& mesh = this->cmesh();
// Begin interfacing with the MEdit data file
{
// header:
out << "MeshVersionFormatted 1\n";
out << "Dimension 3\n";
out << "# Mesh generated by libmesh\n\n";
// write the nodes:
out << "# Set of mesh vertices\n";
out << "Vertices\n";
out << mesh.n_nodes() << "\n";
for (unsigned int v=0; v<mesh.n_nodes(); v++)
out << mesh.point(v)(0) << " " << mesh.point(v)(1) << " " << mesh.point(v)(2) << " 0\n";
}
{
// write the connectivity:
out << "\n# Set of Polys\n\n";
// count occurrences of output elements:
int n_tri3 = 0;
int n_quad4 = 0;
int n_tet4 = 0;
const_active_elem_iterator it (mesh.elements_begin());
const const_active_elem_iterator end(mesh.elements_end());
for ( ; it != end; ++it) {
if ((*it)->type() == TRI3) n_tri3++;
if ((*it)->type() == QUAD4) n_quad4++;
if ((*it)->type() == QUAD9) n_quad4+=4; // (QUAD9 is written as 4 QUAD4.)
if ((*it)->type() == TET4) n_tet4++;
} // for
// First: write out TRI3 elements:
out << "Triangles\n";
out << n_tri3 << "\n";
for (it=mesh.elements_begin() ; it != end; ++it)
if ((*it)->type() == TRI3) {
out << (*it)->node(0)+1 << " " << (*it)->node(1)+1 << " " << (*it)->node(2)+1 << " 0\n";
} // if
// Second: write out QUAD4 elements:
out << "Quadrilaterals\n";
out << n_quad4 << "\n";
for (it=mesh.elements_begin() ; it != end; ++it)
if ((*it)->type() == QUAD4) {
out << (*it)->node(0)+1 << " "
<< (*it)->node(1)+1 << " "
<< (*it)->node(2)+1 << " "
<< (*it)->node(3)+1 <<" 0\n";
} // if
else if ((*it)->type() == QUAD9) {
out << (*it)->node(0)+1 << " "
<< (*it)->node(4)+1 << " "
<< (*it)->node(8)+1 << " "
<< (*it)->node(7)+1 <<" 0\n";
out << (*it)->node(7)+1 << " "
<< (*it)->node(8)+1 << " "
<< (*it)->node(6)+1 << " "
<< (*it)->node(3)+1 <<" 0\n";
out << (*it)->node(4)+1 << " "
<< (*it)->node(1)+1 << " "
<< (*it)->node(5)+1 << " "
<< (*it)->node(8)+1 <<" 0\n";
out << (*it)->node(8)+1 << " "
<< (*it)->node(5)+1 << " "
<< (*it)->node(2)+1 << " "
<< (*it)->node(6)+1 <<" 0\n";
} // if
// Third: write out TET4 elements:
out << "Tetrahedra\n";
out << n_tet4 << "\n";
for (it=mesh.elements_begin() ; it != end; ++it)
if ((*it)->type() == TET4) {
out << (*it)->node(0)+1 << " "
<< (*it)->node(1)+1 << " "
<< (*it)->node(2)+1 << " "
<< (*it)->node(3)+1 <<" 0\n";
} // if
}
// end of the out file
out << std::endl << "# end of file" << std::endl;
// optionally write the data
if ((solution_names != NULL) &&
(vec != NULL))
{
// Open the ".bb" file stream
int idx = fname.find_last_of(".");
std::string bbname = fname.substr(0,idx) + ".bb";
std::ofstream bbout (bbname.c_str());
assert (bbout.good());
// Header: 3: 3D mesh, 1: scalar output, 2: node-indexed
const unsigned int n_vars = solution_names->size();
bbout << "3 1 " << mesh.n_nodes() << " 2\n";
for (unsigned int n=0; n<mesh.n_nodes(); n++)
bbout << std::setprecision(10) << (*vec)[n*n_vars + scalar_idx] << " ";
bbout << "\n";
} // endif
}
<commit_msg>Fixed op= bug which should never have compiled.<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2004 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
#include <iomanip>
#include <fstream>
// Local includes
#include "mesh.h"
#include "libmesh_config.h"
#include "medit_io.h"
// ------------------------------------------------------------
// MEDITIO members
void MEDITIO::write (const std::string& fname)
{
if (libMesh::processor_id() == 0)
if (!this->binary())
this->write_ascii (fname);
}
void MEDITIO::write_nodal_data (const std::string& fname,
const std::vector<Number>& soln,
const std::vector<std::string>& names)
{
if (libMesh::processor_id() == 0)
if (!this->binary())
this->write_ascii (fname, &soln, &names);
}
void MEDITIO::write_ascii (const std::string& fname,
const std::vector<Number>* vec,
const std::vector<std::string>* solution_names)
{
// Current lacks in implementation:
// (i) only 3D meshes.
// (ii) only QUAD4, TRI3, TET4 elements, others are omitted !
// (iii) no distinction between materials.
// (iv) no vector output, just first scalar as output
// assert three dimensions (should be extended later)
assert (this->cmesh().mesh_dimension() == 3);
// Open the output file stream
std::ofstream out (fname.c_str());
assert (out.good());
// Get a reference to the mesh
const MeshBase& mesh = this->cmesh();
// Begin interfacing with the MEdit data file
{
// header:
out << "MeshVersionFormatted 1\n";
out << "Dimension 3\n";
out << "# Mesh generated by libmesh\n\n";
// write the nodes:
out << "# Set of mesh vertices\n";
out << "Vertices\n";
out << mesh.n_nodes() << "\n";
for (unsigned int v=0; v<mesh.n_nodes(); v++)
out << mesh.point(v)(0) << " " << mesh.point(v)(1) << " " << mesh.point(v)(2) << " 0\n";
}
{
// write the connectivity:
out << "\n# Set of Polys\n\n";
// count occurrences of output elements:
int n_tri3 = 0;
int n_quad4 = 0;
int n_tet4 = 0;
{
const_active_elem_iterator it (mesh.elements_begin());
const const_active_elem_iterator end(mesh.elements_end());
for ( ; it != end; ++it)
{
if ((*it)->type() == TRI3) n_tri3++;
if ((*it)->type() == QUAD4) n_quad4++;
if ((*it)->type() == QUAD9) n_quad4+=4; // (QUAD9 is written as 4 QUAD4.)
if ((*it)->type() == TET4) n_tet4++;
} // for
}
// First: write out TRI3 elements:
out << "Triangles\n";
out << n_tri3 << "\n";
{
const_active_elem_iterator it (mesh.elements_begin());
const const_active_elem_iterator end(mesh.elements_end());
for ( ; it != end; ++it)
if ((*it)->type() == TRI3)
out << (*it)->node(0)+1 << " " << (*it)->node(1)+1 << " " << (*it)->node(2)+1 << " 0\n";
}
// Second: write out QUAD4 elements:
out << "Quadrilaterals\n";
out << n_quad4 << "\n";
{
const_active_elem_iterator it (mesh.elements_begin());
const const_active_elem_iterator end(mesh.elements_end());
for ( ; it != end; ++it)
if ((*it)->type() == QUAD4)
{
out << (*it)->node(0)+1 << " "
<< (*it)->node(1)+1 << " "
<< (*it)->node(2)+1 << " "
<< (*it)->node(3)+1 <<" 0\n";
} // if
else if ((*it)->type() == QUAD9)
{
out << (*it)->node(0)+1 << " "
<< (*it)->node(4)+1 << " "
<< (*it)->node(8)+1 << " "
<< (*it)->node(7)+1 <<" 0\n";
out << (*it)->node(7)+1 << " "
<< (*it)->node(8)+1 << " "
<< (*it)->node(6)+1 << " "
<< (*it)->node(3)+1 <<" 0\n";
out << (*it)->node(4)+1 << " "
<< (*it)->node(1)+1 << " "
<< (*it)->node(5)+1 << " "
<< (*it)->node(8)+1 <<" 0\n";
out << (*it)->node(8)+1 << " "
<< (*it)->node(5)+1 << " "
<< (*it)->node(2)+1 << " "
<< (*it)->node(6)+1 <<" 0\n";
} // if
}
// Third: write out TET4 elements:
out << "Tetrahedra\n";
out << n_tet4 << "\n";
{
const_active_elem_iterator it (mesh.elements_begin());
const const_active_elem_iterator end(mesh.elements_end());
for ( ; it != end; ++it)
if ((*it)->type() == TET4)
{
out << (*it)->node(0)+1 << " "
<< (*it)->node(1)+1 << " "
<< (*it)->node(2)+1 << " "
<< (*it)->node(3)+1 <<" 0\n";
} // if
}
}
// end of the out file
out << std::endl << "# end of file" << std::endl;
// optionally write the data
if ((solution_names != NULL) &&
(vec != NULL))
{
// Open the ".bb" file stream
int idx = fname.find_last_of(".");
std::string bbname = fname.substr(0,idx) + ".bb";
std::ofstream bbout (bbname.c_str());
assert (bbout.good());
// Header: 3: 3D mesh, 1: scalar output, 2: node-indexed
const unsigned int n_vars = solution_names->size();
bbout << "3 1 " << mesh.n_nodes() << " 2\n";
for (unsigned int n=0; n<mesh.n_nodes(); n++)
bbout << std::setprecision(10) << (*vec)[n*n_vars + scalar_idx] << " ";
bbout << "\n";
} // endif
}
<|endoftext|>
|
<commit_before>//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// 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.
//*****************************************************************************
#pragma once
#include <chrono>
#include <cmath>
#include <cstdlib> // llvm 8.1 gets confused about `malloc` otherwise
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <typeindex>
#include <typeinfo>
#include <unordered_map>
#include <vector>
#include "ngraph/axis_vector.hpp"
#include "ngraph/graph_util.hpp"
#include "ngraph/node.hpp"
#include "ngraph/shape.hpp"
namespace ngraph
{
class Node;
class Function;
class stopwatch;
namespace runtime
{
class Backend;
class Value;
}
std::string to_cplusplus_sourcecode_literal(bool val);
template <typename T>
std::string join(const T& v, const std::string& sep = ", ")
{
std::ostringstream ss;
size_t count = 0;
for (const auto& x : v)
{
if (count++ > 0)
{
ss << sep;
}
ss << x;
}
return ss.str();
}
template <typename T>
std::string vector_to_string(const T& v)
{
std::ostringstream os;
os << "[ " << ngraph::join(v) << " ]";
return os.str();
}
size_t hash_combine(const std::vector<size_t>& list);
void dump(std::ostream& out, const void*, size_t);
std::string to_lower(const std::string& s);
std::string to_upper(const std::string& s);
std::string trim(const std::string& s);
std::vector<std::string> split(const std::string& s, char delimiter, bool trim = false);
template <typename T>
std::string locale_string(T x)
{
std::stringstream ss;
ss.imbue(std::locale(""));
ss << x;
return ss.str();
}
class stopwatch
{
public:
void start()
{
if (m_active == false)
{
m_total_count++;
m_active = true;
m_start_time = m_clock.now();
}
}
void stop()
{
if (m_active == true)
{
auto end_time = m_clock.now();
m_last_time = end_time - m_start_time;
m_total_time += m_last_time;
m_active = false;
}
}
size_t get_call_count() const;
size_t get_seconds() const;
size_t get_milliseconds() const;
size_t get_microseconds() const;
std::chrono::nanoseconds get_timer_value() const;
size_t get_nanoseconds() const;
size_t get_total_seconds() const;
size_t get_total_milliseconds() const;
size_t get_total_microseconds() const;
size_t get_total_nanoseconds() const;
private:
std::chrono::high_resolution_clock m_clock;
std::chrono::time_point<std::chrono::high_resolution_clock> m_start_time;
bool m_active = false;
std::chrono::nanoseconds m_total_time =
std::chrono::high_resolution_clock::duration::zero();
std::chrono::nanoseconds m_last_time = std::chrono::high_resolution_clock::duration::zero();
size_t m_total_count = 0;
};
/// Parses a string containing a literal of the underlying type.
template <typename T>
T parse_string(const std::string& s)
{
T result;
std::stringstream ss;
ss << s;
ss >> result;
// Check that (1) parsing succeeded and (2) the entire string was used.
if (ss.fail() || ss.rdbuf()->in_avail() != 0)
{
throw std::runtime_error("Could not parse literal '" + s + "'");
}
return result;
}
/// template specializations for float and double to handle INFINITY, -INFINITY
/// and NaN values.
template <>
float parse_string<float>(const std::string& s);
template <>
double parse_string<double>(const std::string& s);
/// Parses a list of strings containing literals of the underlying type.
template <typename T>
std::vector<T> parse_string(const std::vector<std::string>& ss)
{
std::vector<T> result;
for (auto s : ss)
{
result.push_back(parse_string<T>(s));
}
return result;
}
template <typename T>
T ceil_div(const T& x, const T& y)
{
return (x == 0 ? 0 : (1 + (x - 1) / y));
}
template <typename T>
T subtract_or_zero(T x, T y)
{
return y > x ? 0 : x - y;
}
void check_fp_values_isinf(const char* name, const float* array, size_t n);
void check_fp_values_isinf(const char* name, const double* array, size_t n);
void check_fp_values_isnan(const char* name, const float* array, size_t n);
void check_fp_values_isnan(const char* name, const double* array, size_t n);
void* ngraph_malloc(size_t size);
void ngraph_free(void*);
size_t round_up(size_t size, size_t alignment);
bool is_valid_permutation(ngraph::AxisVector permutation, ngraph::Rank rank = Rank::dynamic());
template <typename T>
T apply_permutation(T input, ngraph::AxisVector order);
AxisVector get_default_order(size_t rank);
AxisVector get_default_order(const Shape& shape);
AxisVector get_permutation_to_default_order(const AxisVector& axis_order);
//
// Return type struct for cache_fprop, with the modified fprop and bprop
// functions
// and a list of the nodes that have been appended to fprop output/bprop
// input
//
struct FpropCache
{
std::shared_ptr<Function> fprop;
std::shared_ptr<Function> bprop;
std::vector<Node*> fprop_output_nodes;
NodeMap node_param_map;
};
//
// This utility takes forward-propogation and back-propagation functions
// and turns them into clone functions where the intermediate values of
// the forward prop are added to the output of fprop and the input of the bprop
// to avoid repeat calculations.
// The last argument is the adjoints coming into the bprop function, the output
// bprop function will have these nodes as the first N input parameters
//
FpropCache cache_fprop(std::shared_ptr<Function> fprop, std::shared_ptr<Function> bprop);
// NodeExecutors are used in compiler optimization passes like ConstantFolding to execute a node
// using the supplied input and output memory locations.
// A BuildNodeExecutor returns a backend-specific NodeExecutor for a given Node type
using NodeExecutorTy =
std::function<void(const std::vector<void*>& inputs, std::vector<void*>& outputs)>;
using BuildNodeExecutor = std::function<NodeExecutorTy(const ngraph::Node*)>;
using BuildNodeExecutorMap = std::unordered_map<std::type_index, BuildNodeExecutor>;
enum class TensorRole
{
INPUT,
CONSTANT,
OUTPUT,
INTERMEDIATE,
UNKNOWN
};
//
// EnumMask is intended to work with a scoped enum type. It's used to store
// a combination of enum values and provides easy access and manipulation
// of these enum values as a mask.
//
// EnumMask does not provide a set_all() or invert() operator because they
// could do things unexpected by the user, i.e. for enum with 4 bit values,
// invert(001000...) != 110100..., due to the extra bits.
//
template <typename T>
class EnumMask
{
public:
/// Make sure the template type is an enum.
static_assert(std::is_enum<T>::value, "EnumMask template type must be an enum");
/// Extract the underlying type of the enum.
typedef typename std::underlying_type<T>::type value_type;
/// Some bit operations are not safe for signed values, we require enum
/// type to use unsigned underlying type.
static_assert(std::is_unsigned<value_type>::value, "EnumMask enum must use unsigned type.");
constexpr EnumMask()
: m_value{0}
{
}
constexpr EnumMask(const T& enum_value)
: m_value{static_cast<value_type>(enum_value)}
{
}
EnumMask(const EnumMask& other)
: m_value{other.m_value}
{
}
EnumMask(std::initializer_list<T> enum_values)
: m_value{0}
{
for (auto& v : enum_values)
{
m_value |= static_cast<value_type>(v);
}
}
value_type value() const { return m_value; }
/// Check if any of the input parameter enum bit mask match
bool is_any_set(const EnumMask& p) const { return m_value & p.m_value; }
/// Check if all of the input parameter enum bit mask match
bool is_set(const EnumMask& p) const { return (m_value & p.m_value) == p.m_value; }
/// Check if any of the input parameter enum bit mask does not match
bool is_any_clear(const EnumMask& p) const { return !is_set(p); }
/// Check if all of the input parameter enum bit mask do not match
bool is_clear(const EnumMask& p) const { return !is_any_set(p); }
void set(const EnumMask& p) { m_value |= p.m_value; }
void clear(const EnumMask& p) { m_value &= ~p.m_value; }
void clear_all() { m_value = 0; }
bool operator[](const EnumMask& p) const { return is_set(p); }
bool operator==(const EnumMask& other) const { return m_value == other.m_value; }
bool operator!=(const EnumMask& other) const { return m_value != other.m_value; }
EnumMask& operator=(const EnumMask& other)
{
m_value = other.m_value;
return *this;
}
EnumMask& operator&=(const EnumMask& other)
{
m_value &= other.m_value;
return *this;
}
EnumMask& operator|=(const EnumMask& other)
{
m_value |= other.m_value;
return *this;
}
EnumMask operator&(const EnumMask& other) const
{
return EnumMask(m_value & other.m_value);
}
EnumMask operator|(const EnumMask& other) const
{
return EnumMask(m_value | other.m_value);
}
friend std::ostream& operator<<(std::ostream& os, const EnumMask& m)
{
os << m.m_value;
return os;
}
private:
/// Only used internally
explicit EnumMask(const value_type& value)
: m_value{value}
{
}
value_type m_value;
};
/// \brief Function to query parsed version information of the version of ngraph which
/// contains this function. Version information strictly follows Semantic Versioning
/// http://semver.org
/// \param version The major part of the version
/// \param major Returns the major part of the version
/// \param minor Returns the minor part of the version
/// \param patch Returns the patch part of the version
/// \param extra Returns the extra part of the version. This includes everything following
/// the patch version number.
///
/// \note Throws a runtime_error if there is an error during parsing
void parse_version_string(
std::string version, size_t& major, size_t& minor, size_t& patch, std::string& extra);
} // end namespace ngraph
std::ostream& operator<<(std::ostream& os, const ngraph::NodeVector& nv);
<commit_msg>no_fork: Performance issue vector of string to T (#3542)<commit_after>//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// 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.
//*****************************************************************************
#pragma once
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdlib> // llvm 8.1 gets confused about `malloc` otherwise
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <typeindex>
#include <typeinfo>
#include <unordered_map>
#include <vector>
#include "ngraph/axis_vector.hpp"
#include "ngraph/graph_util.hpp"
#include "ngraph/node.hpp"
#include "ngraph/shape.hpp"
namespace ngraph
{
class Node;
class Function;
class stopwatch;
namespace runtime
{
class Backend;
class Value;
}
std::string to_cplusplus_sourcecode_literal(bool val);
template <typename T>
std::string join(const T& v, const std::string& sep = ", ")
{
std::ostringstream ss;
size_t count = 0;
for (const auto& x : v)
{
if (count++ > 0)
{
ss << sep;
}
ss << x;
}
return ss.str();
}
template <typename T>
std::string vector_to_string(const T& v)
{
std::ostringstream os;
os << "[ " << ngraph::join(v) << " ]";
return os.str();
}
size_t hash_combine(const std::vector<size_t>& list);
void dump(std::ostream& out, const void*, size_t);
std::string to_lower(const std::string& s);
std::string to_upper(const std::string& s);
std::string trim(const std::string& s);
std::vector<std::string> split(const std::string& s, char delimiter, bool trim = false);
template <typename T>
std::string locale_string(T x)
{
std::stringstream ss;
ss.imbue(std::locale(""));
ss << x;
return ss.str();
}
class stopwatch
{
public:
void start()
{
if (m_active == false)
{
m_total_count++;
m_active = true;
m_start_time = m_clock.now();
}
}
void stop()
{
if (m_active == true)
{
auto end_time = m_clock.now();
m_last_time = end_time - m_start_time;
m_total_time += m_last_time;
m_active = false;
}
}
size_t get_call_count() const;
size_t get_seconds() const;
size_t get_milliseconds() const;
size_t get_microseconds() const;
std::chrono::nanoseconds get_timer_value() const;
size_t get_nanoseconds() const;
size_t get_total_seconds() const;
size_t get_total_milliseconds() const;
size_t get_total_microseconds() const;
size_t get_total_nanoseconds() const;
private:
std::chrono::high_resolution_clock m_clock;
std::chrono::time_point<std::chrono::high_resolution_clock> m_start_time;
bool m_active = false;
std::chrono::nanoseconds m_total_time =
std::chrono::high_resolution_clock::duration::zero();
std::chrono::nanoseconds m_last_time = std::chrono::high_resolution_clock::duration::zero();
size_t m_total_count = 0;
};
/// Parses a string containing a literal of the underlying type.
template <typename T>
T parse_string(const std::string& s)
{
T result;
std::stringstream ss;
ss << s;
ss >> result;
// Check that (1) parsing succeeded and (2) the entire string was used.
if (ss.fail() || ss.rdbuf()->in_avail() != 0)
{
throw std::runtime_error("Could not parse literal '" + s + "'");
}
return result;
}
/// template specializations for float and double to handle INFINITY, -INFINITY
/// and NaN values.
template <>
float parse_string<float>(const std::string& s);
template <>
double parse_string<double>(const std::string& s);
/// Parses a list of strings containing literals of the underlying type.
template <typename T>
std::vector<T> parse_string(const std::vector<std::string>& ss)
{
std::vector<T> result(ss.size());
std::transform(ss.begin(), ss.end(), result.begin(), [](const std::string& s) {
return parse_string<T>(s);
});
return result;
}
template <typename T>
T ceil_div(const T& x, const T& y)
{
return (x == 0 ? 0 : (1 + (x - 1) / y));
}
template <typename T>
T subtract_or_zero(T x, T y)
{
return y > x ? 0 : x - y;
}
void check_fp_values_isinf(const char* name, const float* array, size_t n);
void check_fp_values_isinf(const char* name, const double* array, size_t n);
void check_fp_values_isnan(const char* name, const float* array, size_t n);
void check_fp_values_isnan(const char* name, const double* array, size_t n);
void* ngraph_malloc(size_t size);
void ngraph_free(void*);
size_t round_up(size_t size, size_t alignment);
bool is_valid_permutation(ngraph::AxisVector permutation, ngraph::Rank rank = Rank::dynamic());
template <typename T>
T apply_permutation(T input, ngraph::AxisVector order);
AxisVector get_default_order(size_t rank);
AxisVector get_default_order(const Shape& shape);
AxisVector get_permutation_to_default_order(const AxisVector& axis_order);
//
// Return type struct for cache_fprop, with the modified fprop and bprop
// functions
// and a list of the nodes that have been appended to fprop output/bprop
// input
//
struct FpropCache
{
std::shared_ptr<Function> fprop;
std::shared_ptr<Function> bprop;
std::vector<Node*> fprop_output_nodes;
NodeMap node_param_map;
};
//
// This utility takes forward-propogation and back-propagation functions
// and turns them into clone functions where the intermediate values of
// the forward prop are added to the output of fprop and the input of the bprop
// to avoid repeat calculations.
// The last argument is the adjoints coming into the bprop function, the output
// bprop function will have these nodes as the first N input parameters
//
FpropCache cache_fprop(std::shared_ptr<Function> fprop, std::shared_ptr<Function> bprop);
// NodeExecutors are used in compiler optimization passes like ConstantFolding to execute a node
// using the supplied input and output memory locations.
// A BuildNodeExecutor returns a backend-specific NodeExecutor for a given Node type
using NodeExecutorTy =
std::function<void(const std::vector<void*>& inputs, std::vector<void*>& outputs)>;
using BuildNodeExecutor = std::function<NodeExecutorTy(const ngraph::Node*)>;
using BuildNodeExecutorMap = std::unordered_map<std::type_index, BuildNodeExecutor>;
enum class TensorRole
{
INPUT,
CONSTANT,
OUTPUT,
INTERMEDIATE,
UNKNOWN
};
//
// EnumMask is intended to work with a scoped enum type. It's used to store
// a combination of enum values and provides easy access and manipulation
// of these enum values as a mask.
//
// EnumMask does not provide a set_all() or invert() operator because they
// could do things unexpected by the user, i.e. for enum with 4 bit values,
// invert(001000...) != 110100..., due to the extra bits.
//
template <typename T>
class EnumMask
{
public:
/// Make sure the template type is an enum.
static_assert(std::is_enum<T>::value, "EnumMask template type must be an enum");
/// Extract the underlying type of the enum.
typedef typename std::underlying_type<T>::type value_type;
/// Some bit operations are not safe for signed values, we require enum
/// type to use unsigned underlying type.
static_assert(std::is_unsigned<value_type>::value, "EnumMask enum must use unsigned type.");
constexpr EnumMask()
: m_value{0}
{
}
constexpr EnumMask(const T& enum_value)
: m_value{static_cast<value_type>(enum_value)}
{
}
EnumMask(const EnumMask& other)
: m_value{other.m_value}
{
}
EnumMask(std::initializer_list<T> enum_values)
: m_value{0}
{
for (auto& v : enum_values)
{
m_value |= static_cast<value_type>(v);
}
}
value_type value() const { return m_value; }
/// Check if any of the input parameter enum bit mask match
bool is_any_set(const EnumMask& p) const { return m_value & p.m_value; }
/// Check if all of the input parameter enum bit mask match
bool is_set(const EnumMask& p) const { return (m_value & p.m_value) == p.m_value; }
/// Check if any of the input parameter enum bit mask does not match
bool is_any_clear(const EnumMask& p) const { return !is_set(p); }
/// Check if all of the input parameter enum bit mask do not match
bool is_clear(const EnumMask& p) const { return !is_any_set(p); }
void set(const EnumMask& p) { m_value |= p.m_value; }
void clear(const EnumMask& p) { m_value &= ~p.m_value; }
void clear_all() { m_value = 0; }
bool operator[](const EnumMask& p) const { return is_set(p); }
bool operator==(const EnumMask& other) const { return m_value == other.m_value; }
bool operator!=(const EnumMask& other) const { return m_value != other.m_value; }
EnumMask& operator=(const EnumMask& other)
{
m_value = other.m_value;
return *this;
}
EnumMask& operator&=(const EnumMask& other)
{
m_value &= other.m_value;
return *this;
}
EnumMask& operator|=(const EnumMask& other)
{
m_value |= other.m_value;
return *this;
}
EnumMask operator&(const EnumMask& other) const
{
return EnumMask(m_value & other.m_value);
}
EnumMask operator|(const EnumMask& other) const
{
return EnumMask(m_value | other.m_value);
}
friend std::ostream& operator<<(std::ostream& os, const EnumMask& m)
{
os << m.m_value;
return os;
}
private:
/// Only used internally
explicit EnumMask(const value_type& value)
: m_value{value}
{
}
value_type m_value;
};
/// \brief Function to query parsed version information of the version of ngraph which
/// contains this function. Version information strictly follows Semantic Versioning
/// http://semver.org
/// \param version The major part of the version
/// \param major Returns the major part of the version
/// \param minor Returns the minor part of the version
/// \param patch Returns the patch part of the version
/// \param extra Returns the extra part of the version. This includes everything following
/// the patch version number.
///
/// \note Throws a runtime_error if there is an error during parsing
void parse_version_string(
std::string version, size_t& major, size_t& minor, size_t& patch, std::string& extra);
} // end namespace ngraph
std::ostream& operator<<(std::ostream& os, const ngraph::NodeVector& nv);
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include "parsers/parse_error.hh"
#include "parsers/tina.hh"
namespace pnmc { namespace parsers {
namespace {
/*------------------------------------------------------------------------------------------------*/
unsigned int
value(std::string::const_iterator cit, std::string::const_iterator cend)
{
std::string s(cit, cend);
try
{
std::size_t pos;
auto value = std::stoi(s, &pos);
std::advance(cit, pos);
if (std::distance(cit, cend) == 1)
{
switch (*cit)
{
case 'K': value *= 1000; break;
case 'M': value *= 1000000; break;
default: throw parse_error("Invalid suffix, got '" + std::string(cit, cend) + "'");
}
}
else if (std::distance(cit, cend) > 1)
{
throw parse_error("Invalid suffix, got " + std::string(cit, cend));
}
return value;
}
catch (const std::invalid_argument&)
{
throw parse_error("Expected a value, got " + s);
}
}
/*------------------------------------------------------------------------------------------------*/
std::pair<std::string, pn::arc>
place_arc(const std::string& s)
{
auto pos = s.find_first_of("*?!");
auto arc_type = pn::arc::type::normal;
if (pos == std::string::npos)
{
return std::make_pair(s, pn::arc{1, arc_type});
}
if (pos == s.length() - 1)
{
throw parse_error("Valuation expected, got '" + s + "'");
}
auto valuation_pos = pos;
switch (s[pos])
{
case '*': break;
case '?':
{
if (s[pos + 1] == '-')
{
++valuation_pos;
arc_type = pn::arc::type::inhibitor;
}
else
{
arc_type = pn::arc::type::read;
}
break;
}
case '!':
{
if (s[pos +1] == '-')
{
++valuation_pos;
arc_type = pn::arc::type::stopwatch_inhibitor;
}
else
{
arc_type = pn::arc::type::stopwatch;
}
break;
}
default :
{
std::stringstream ss;
ss << "Expected '*', '?' or '!', got '" << s[pos] << "'";
throw parse_error(ss.str());
}
}
const auto valuation = value(s.cbegin() + valuation_pos + 1, s.cend());
return std::make_pair(s.substr(0, pos), pn::arc{valuation, arc_type});
}
/*------------------------------------------------------------------------------------------------*/
unsigned int
marking(const std::string& s)
{
if (*s.cbegin() == '(' and *std::prev(s.cend()) == ')')
{
return value(std::next(s.cbegin()), std::prev(s.cend()));
}
else
{
throw parse_error("Invalid marking format: " + s);
}
}
} // namespace anonymous
/*------------------------------------------------------------------------------------------------*/
std::shared_ptr<pn::net>
tina(std::istream& in)
{
// Known limitations:
// - there's must be a transition or place per line
// - labels are ignored
// - time intervals are not completely validated (e.g. [0, 2a] is wrongly validated
std::shared_ptr<pn::net> net_ptr = std::make_shared<pn::net>();
auto& net = *net_ptr;
std::string line, s0, s1, s2, ignore;
line.reserve(1024);
while (std::getline(in, line))
{
std::istringstream ss(line);
// Empty line or comment.
if (((ss >> std::ws).peek() == std::char_traits<char>::to_int_type('#')) or not (ss >> s0))
{
continue;
}
// Net
if (s0 == "net")
{
ss >> s0;
net_ptr->name = s0;
}
// Transitions
else if (s0 == "tr")
{
std::string place_id;
if (ss >> s0)
{
net.add_transition(s0);
}
else
{
throw parse_error("Invalid transition: " + line);
}
// Ignore label, if any.
if ((ss >> std::ws).peek() == std::char_traits<char>::to_int_type(':'))
{
ss >> ignore >> ignore; // ':' <label>
}
// Time interval.
const auto peek = (ss >> std::ws).peek();
if ( peek == std::char_traits<char>::to_int_type('[')
or peek == std::char_traits<char>::to_int_type(']'))
{
s1.clear();
const bool open_lower_endpoint = ss.get() == ']';
bool open_upper_endpoint = false;
while (ss.good())
{
auto c = ss.get();
if (c == '[')
{
open_upper_endpoint = true;
break;
}
if (c == ']')
{
break;
}
s1.push_back(c);
}
if (not ss.good())
{
throw parse_error("Unexpected end of file. Missing '[' or ']'?");
}
std::istringstream ss1(s1);
std::getline(ss1, s2, ','); // split on ','
unsigned int first, last;
try
{
first = std::stoi(s2);
}
catch (const std::invalid_argument&)
{
throw parse_error("Expected a value, got: '" + s2 + "'");
}
ss1 >> s2;
try
{
last = std::stoi(s2);
if ((last < first) or (open_upper_endpoint and first == last))
{
throw parse_error( "Invalid time interval '"
+ (open_lower_endpoint ? std::string("]") : std::string("["))
+ std::to_string(first) + "," + std::to_string(last)
+ (open_upper_endpoint ? std::string("[") : std::string("]"))
+ "'");
}
if (open_upper_endpoint)
{
last -= 1;
}
}
catch (const std::invalid_argument& e)
{
if (s2 == "w")
{
last = std::numeric_limits<unsigned int>::max();
}
else
{
throw parse_error("Expected a value, got: '" + s2 + "'");
}
}
net_ptr->add_time_interval(s0, first, last);
}
bool found_arrow = false;
while (ss >> s1)
{
if (s1 == "->")
{
found_arrow = true;
break;
}
const auto res = place_arc(s1);
net.add_pre_place(s0, res.first, res.second);
}
if (not found_arrow)
{
throw parse_error("Invalid transition (missing '->'): " + line);
}
while (ss >> s1)
{
const auto res = place_arc(s1);
net.add_post_place(s0, res.first, res.second);
}
}
// Places
else if (s0 == "pl")
{
if (ss >> s1)
{
// Ignore label, if any.
if ((ss >> std::ws).peek() == std::char_traits<char>::to_int_type(':'))
{
ss >> ignore >> ignore; // ':' <label>
}
if (ss >> s2)
{
net.add_place(s1, marking(s2));
}
else
{
net.add_place(s1, 0);
}
}
else
{
throw parse_error("Invalid place: " + line);
}
}
// Error.
else
{
throw parse_error("Invalid line: " + line);
}
}
return net_ptr;
}
/*------------------------------------------------------------------------------------------------*/
}} // namespace pnmc::parsers
<commit_msg>Tina parse: check TPN lower endpoint.<commit_after>#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include "parsers/parse_error.hh"
#include "parsers/tina.hh"
namespace pnmc { namespace parsers {
namespace {
/*------------------------------------------------------------------------------------------------*/
unsigned int
value(std::string::const_iterator cit, std::string::const_iterator cend)
{
std::string s(cit, cend);
try
{
std::size_t pos;
auto value = std::stoi(s, &pos);
std::advance(cit, pos);
if (std::distance(cit, cend) == 1)
{
switch (*cit)
{
case 'K': value *= 1000; break;
case 'M': value *= 1000000; break;
default: throw parse_error("Invalid suffix, got '" + std::string(cit, cend) + "'");
}
}
else if (std::distance(cit, cend) > 1)
{
throw parse_error("Invalid suffix, got " + std::string(cit, cend));
}
return value;
}
catch (const std::invalid_argument&)
{
throw parse_error("Expected a value, got " + s);
}
}
/*------------------------------------------------------------------------------------------------*/
std::pair<std::string, pn::arc>
place_arc(const std::string& s)
{
auto pos = s.find_first_of("*?!");
auto arc_type = pn::arc::type::normal;
if (pos == std::string::npos)
{
return std::make_pair(s, pn::arc{1, arc_type});
}
if (pos == s.length() - 1)
{
throw parse_error("Valuation expected, got '" + s + "'");
}
auto valuation_pos = pos;
switch (s[pos])
{
case '*': break;
case '?':
{
if (s[pos + 1] == '-')
{
++valuation_pos;
arc_type = pn::arc::type::inhibitor;
}
else
{
arc_type = pn::arc::type::read;
}
break;
}
case '!':
{
if (s[pos +1] == '-')
{
++valuation_pos;
arc_type = pn::arc::type::stopwatch_inhibitor;
}
else
{
arc_type = pn::arc::type::stopwatch;
}
break;
}
default :
{
std::stringstream ss;
ss << "Expected '*', '?' or '!', got '" << s[pos] << "'";
throw parse_error(ss.str());
}
}
const auto valuation = value(s.cbegin() + valuation_pos + 1, s.cend());
return std::make_pair(s.substr(0, pos), pn::arc{valuation, arc_type});
}
/*------------------------------------------------------------------------------------------------*/
unsigned int
marking(const std::string& s)
{
if (*s.cbegin() == '(' and *std::prev(s.cend()) == ')')
{
return value(std::next(s.cbegin()), std::prev(s.cend()));
}
else
{
throw parse_error("Invalid marking format: " + s);
}
}
} // namespace anonymous
/*------------------------------------------------------------------------------------------------*/
std::shared_ptr<pn::net>
tina(std::istream& in)
{
// Known limitations:
// - there's must be a transition or place per line
// - labels are ignored
// - time intervals are not completely validated (e.g. [0, 2a] is wrongly validated
std::shared_ptr<pn::net> net_ptr = std::make_shared<pn::net>();
auto& net = *net_ptr;
std::string line, s0, s1, s2, ignore;
line.reserve(1024);
while (std::getline(in, line))
{
std::istringstream ss(line);
// Empty line or comment.
if (((ss >> std::ws).peek() == std::char_traits<char>::to_int_type('#')) or not (ss >> s0))
{
continue;
}
// Net
if (s0 == "net")
{
ss >> s0;
net_ptr->name = s0;
}
// Transitions
else if (s0 == "tr")
{
std::string place_id;
if (ss >> s0)
{
net.add_transition(s0);
}
else
{
throw parse_error("Invalid transition: " + line);
}
// Ignore label, if any.
if ((ss >> std::ws).peek() == std::char_traits<char>::to_int_type(':'))
{
ss >> ignore >> ignore; // ':' <label>
}
// Time interval.
const auto peek = (ss >> std::ws).peek();
if ( peek == std::char_traits<char>::to_int_type('[')
or peek == std::char_traits<char>::to_int_type(']'))
{
s1.clear();
const bool open_lower_endpoint = ss.get() == ']';
bool open_upper_endpoint = false;
while (ss.good())
{
auto c = ss.get();
if (c == '[')
{
open_upper_endpoint = true;
break;
}
if (c == ']')
{
break;
}
s1.push_back(c);
}
if (not ss.good())
{
throw parse_error("Unexpected end of file. Missing '[' or ']'?");
}
std::istringstream ss1(s1);
std::getline(ss1, s2, ','); // split on ','
unsigned int first, last;
try
{
first = std::stoi(s2);
}
catch (const std::invalid_argument&)
{
throw parse_error("Expected a value, got: '" + s2 + "'");
}
ss1 >> s2;
try
{
last = std::stoi(s2);
if ((last < first) or ((open_upper_endpoint or open_lower_endpoint) and first == last))
{
throw parse_error( "Invalid time interval '"
+ (open_lower_endpoint ? std::string("]") : std::string("["))
+ std::to_string(first) + "," + std::to_string(last)
+ (open_upper_endpoint ? std::string("[") : std::string("]"))
+ "'");
}
if (open_lower_endpoint)
{
first += 1;
}
if (open_upper_endpoint)
{
last -= 1;
}
}
catch (const std::invalid_argument& e)
{
if (s2 == "w")
{
last = std::numeric_limits<unsigned int>::max();
}
else
{
throw parse_error("Expected a value, got: '" + s2 + "'");
}
}
net_ptr->add_time_interval(s0, first, last);
}
bool found_arrow = false;
while (ss >> s1)
{
if (s1 == "->")
{
found_arrow = true;
break;
}
const auto res = place_arc(s1);
net.add_pre_place(s0, res.first, res.second);
}
if (not found_arrow)
{
throw parse_error("Invalid transition (missing '->'): " + line);
}
while (ss >> s1)
{
const auto res = place_arc(s1);
net.add_post_place(s0, res.first, res.second);
}
}
// Places
else if (s0 == "pl")
{
if (ss >> s1)
{
// Ignore label, if any.
if ((ss >> std::ws).peek() == std::char_traits<char>::to_int_type(':'))
{
ss >> ignore >> ignore; // ':' <label>
}
if (ss >> s2)
{
net.add_place(s1, marking(s2));
}
else
{
net.add_place(s1, 0);
}
}
else
{
throw parse_error("Invalid place: " + line);
}
}
// Error.
else
{
throw parse_error("Invalid line: " + line);
}
}
return net_ptr;
}
/*------------------------------------------------------------------------------------------------*/
}} // namespace pnmc::parsers
<|endoftext|>
|
<commit_before>/*
* Copyright 2015 WebAssembly Community Group participants
*
* 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 <chrono>
#include <sstream>
#include <passes/passes.h>
#include <pass.h>
#include <wasm-validator.h>
namespace wasm {
// PassRegistry
PassRegistry::PassRegistry() {
registerPasses();
}
static PassRegistry singleton;
PassRegistry* PassRegistry::get() {
return &singleton;
}
void PassRegistry::registerPass(const char* name, const char *description, Creator create) {
assert(passInfos.find(name) == passInfos.end());
passInfos[name] = PassInfo(description, create);
}
Pass* PassRegistry::createPass(std::string name) {
if (passInfos.find(name) == passInfos.end()) return nullptr;
auto ret = passInfos[name].create();
ret->name = name;
return ret;
}
std::vector<std::string> PassRegistry::getRegisteredNames() {
std::vector<std::string> ret;
for (auto pair : passInfos) {
ret.push_back(pair.first);
}
return ret;
}
std::string PassRegistry::getPassDescription(std::string name) {
assert(passInfos.find(name) != passInfos.end());
return passInfos[name].description;
}
// PassRunner
void PassRegistry::registerPasses() {
registerPass("coalesce-locals", "reduce # of locals by coalescing", createCoalesceLocalsPass);
registerPass("coalesce-locals-learning", "reduce # of locals by coalescing and learning", createCoalesceLocalsWithLearningPass);
registerPass("dce", "removes unreachable code", createDeadCodeEliminationPass);
registerPass("duplicate-function-elimination", "removes duplicate functions", createDuplicateFunctionEliminationPass);
registerPass("extract-function", "leaves just one function (useful for debugging)", createExtractFunctionPass);
registerPass("legalize-js-interface", "legalizes i64 types on the import/export boundary", createLegalizeJSInterfacePass);
registerPass("merge-blocks", "merges blocks to their parents", createMergeBlocksPass);
registerPass("metrics", "reports metrics", createMetricsPass);
registerPass("nm", "name list", createNameListPass);
registerPass("name-manager", "utility pass to manage names in modules", createNameManagerPass);
registerPass("optimize-instructions", "optimizes instruction combinations", createOptimizeInstructionsPass);
registerPass("post-emscripten", "miscellaneous optimizations for Emscripten-generated code", createPostEmscriptenPass);
registerPass("print", "print in s-expression format", createPrinterPass);
registerPass("print-minified", "print in minified s-expression format", createMinifiedPrinterPass);
registerPass("print-full", "print in full s-expression format", createFullPrinterPass);
registerPass("relooper-jump-threading", "thread relooper jumps (fastcomp output only)", createRelooperJumpThreadingPass);
registerPass("remove-imports", "removes imports and replaces them with nops", createRemoveImportsPass);
registerPass("remove-memory", "removes memory segments", createRemoveMemoryPass);
registerPass("remove-unused-brs", "removes breaks from locations that are not needed", createRemoveUnusedBrsPass);
registerPass("remove-unused-functions", "removes unused functions", createRemoveUnusedFunctionsPass);
registerPass("remove-unused-names", "removes names from locations that are never branched to", createRemoveUnusedNamesPass);
registerPass("reorder-functions", "sorts functions by access frequency", createReorderFunctionsPass);
registerPass("reorder-locals", "sorts locals by access frequency", createReorderLocalsPass);
registerPass("simplify-locals", "miscellaneous locals-related optimizations", createSimplifyLocalsPass);
registerPass("vacuum", "removes obviously unneeded code", createVacuumPass);
registerPass("precompute", "computes compile-time evaluatable expressions", createPrecomputePass);
// registerPass("lower-i64", "lowers i64 into pairs of i32s", createLowerInt64Pass);
}
void PassRunner::addDefaultOptimizationPasses() {
add("duplicate-function-elimination");
add("dce");
add("remove-unused-brs");
add("remove-unused-names");
add("optimize-instructions");
add("precompute");
add("simplify-locals");
add("vacuum"); // previous pass creates garbage
add("remove-unused-brs"); // simplify-locals opens opportunities for phi optimizations
add("coalesce-locals");
add("vacuum"); // previous pass creates garbage
add("reorder-locals");
add("merge-blocks");
add("optimize-instructions");
add("precompute");
add("vacuum"); // should not be needed, last few passes do not create garbage, but just to be safe
add("duplicate-function-elimination"); // optimizations show more functions as duplicate
}
void PassRunner::addDefaultFunctionOptimizationPasses() {
add("dce");
add("remove-unused-brs");
add("remove-unused-names");
add("optimize-instructions");
add("precompute");
add("simplify-locals");
add("vacuum"); // previous pass creates garbage
add("remove-unused-brs"); // simplify-locals opens opportunities for phi optimizations
add("coalesce-locals");
add("vacuum"); // previous pass creates garbage
add("reorder-locals");
add("merge-blocks");
add("optimize-instructions");
add("precompute");
add("vacuum"); // should not be needed, last few passes do not create garbage, but just to be safe
}
void PassRunner::addDefaultGlobalOptimizationPasses() {
add("duplicate-function-elimination");
}
void PassRunner::run() {
if (debug) {
// for debug logging purposes, run each pass in full before running the other
auto totalTime = std::chrono::duration<double>(0);
size_t padding = 0;
std::cerr << "[PassRunner] running passes..." << std::endl;
for (auto pass : passes) {
padding = std::max(padding, pass->name.size());
}
for (auto* pass : passes) {
// ignoring the time, save a printout of the module before, in case this pass breaks it, so we can print the before and after
std::stringstream moduleBefore;
WasmPrinter::printModule(wasm, moduleBefore);
// prepare to run
std::chrono::high_resolution_clock::time_point before;
std::cerr << "[PassRunner] running pass: " << pass->name << "... ";
for (size_t i = 0; i < padding - pass->name.size(); i++) {
std::cerr << ' ';
}
before = std::chrono::high_resolution_clock::now();
if (pass->isFunctionParallel()) {
// function-parallel passes should get a new instance per function
for (auto& func : wasm->functions) {
runPassOnFunction(pass, func.get());
}
} else {
pass->run(this, wasm);
}
auto after = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = after - before;
std::cerr << diff.count() << " seconds." << std::endl;
totalTime += diff;
// validate, ignoring the time
std::cerr << "[PassRunner] (validating)\n";
if (!WasmValidator().validate(*wasm, false, validateGlobally)) {
std::cerr << "Last pass (" << pass->name << ") broke validation. Here is the module before: \n" << moduleBefore.str() << "\n";
abort();
}
}
std::cerr << "[PassRunner] passes took " << totalTime.count() << " seconds." << std::endl;
// validate
std::cerr << "[PassRunner] (final validation)\n";
if (!WasmValidator().validate(*wasm, false, validateGlobally)) {
std::cerr << "final module does not validate\n";
abort();
}
} else {
// non-debug normal mode, run them in an optimal manner - for locality it is better
// to run as many passes as possible on a single function before moving to the next
std::vector<Pass*> stack;
auto flush = [&]() {
if (stack.size() > 0) {
// run the stack of passes on all the functions, in parallel
size_t num = ThreadPool::get()->size();
std::vector<std::function<ThreadWorkState ()>> doWorkers;
std::atomic<size_t> nextFunction;
nextFunction.store(0);
size_t numFunctions = wasm->functions.size();
for (size_t i = 0; i < num; i++) {
doWorkers.push_back([&]() {
auto index = nextFunction.fetch_add(1);
// get the next task, if there is one
if (index >= numFunctions) {
return ThreadWorkState::Finished; // nothing left
}
Function* func = this->wasm->functions[index].get();
// do the current task: run all passes on this function
for (auto* pass : stack) {
runPassOnFunction(pass, func);
}
if (index + 1 == numFunctions) {
return ThreadWorkState::Finished; // we did the last one
}
return ThreadWorkState::More;
});
}
ThreadPool::get()->work(doWorkers);
}
stack.clear();
};
for (auto* pass : passes) {
if (pass->isFunctionParallel()) {
stack.push_back(pass);
} else {
flush();
pass->run(this, wasm);
}
}
flush();
}
}
void PassRunner::runFunction(Function* func) {
if (debug) {
std::cerr << "[PassRunner] running passes on function " << func->name << std::endl;
}
for (auto* pass : passes) {
runPassOnFunction(pass, func);
}
}
PassRunner::~PassRunner() {
for (auto pass : passes) {
delete pass;
}
}
void PassRunner::doAdd(Pass* pass) {
passes.push_back(pass);
pass->prepareToRun(this, wasm);
}
void PassRunner::runPassOnFunction(Pass* pass, Function* func) {
#if 0
if (debug) {
std::cerr << "[PassRunner] runPass " << pass->name << " OnFunction " << func->name << "\n";
}
#endif
// function-parallel passes get a new instance per function
if (pass->isFunctionParallel()) {
auto instance = std::unique_ptr<Pass>(pass->create());
instance->runFunction(this, wasm, func);
} else {
pass->runFunction(this, wasm, func);
}
}
} // namespace wasm
<commit_msg>put heavy pass debugging operations behind BINARYEN_PASS_DEBUG (#755)<commit_after>/*
* Copyright 2015 WebAssembly Community Group participants
*
* 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 <chrono>
#include <sstream>
#include <passes/passes.h>
#include <pass.h>
#include <wasm-validator.h>
namespace wasm {
// PassRegistry
PassRegistry::PassRegistry() {
registerPasses();
}
static PassRegistry singleton;
PassRegistry* PassRegistry::get() {
return &singleton;
}
void PassRegistry::registerPass(const char* name, const char *description, Creator create) {
assert(passInfos.find(name) == passInfos.end());
passInfos[name] = PassInfo(description, create);
}
Pass* PassRegistry::createPass(std::string name) {
if (passInfos.find(name) == passInfos.end()) return nullptr;
auto ret = passInfos[name].create();
ret->name = name;
return ret;
}
std::vector<std::string> PassRegistry::getRegisteredNames() {
std::vector<std::string> ret;
for (auto pair : passInfos) {
ret.push_back(pair.first);
}
return ret;
}
std::string PassRegistry::getPassDescription(std::string name) {
assert(passInfos.find(name) != passInfos.end());
return passInfos[name].description;
}
// PassRunner
void PassRegistry::registerPasses() {
registerPass("coalesce-locals", "reduce # of locals by coalescing", createCoalesceLocalsPass);
registerPass("coalesce-locals-learning", "reduce # of locals by coalescing and learning", createCoalesceLocalsWithLearningPass);
registerPass("dce", "removes unreachable code", createDeadCodeEliminationPass);
registerPass("duplicate-function-elimination", "removes duplicate functions", createDuplicateFunctionEliminationPass);
registerPass("extract-function", "leaves just one function (useful for debugging)", createExtractFunctionPass);
registerPass("legalize-js-interface", "legalizes i64 types on the import/export boundary", createLegalizeJSInterfacePass);
registerPass("merge-blocks", "merges blocks to their parents", createMergeBlocksPass);
registerPass("metrics", "reports metrics", createMetricsPass);
registerPass("nm", "name list", createNameListPass);
registerPass("name-manager", "utility pass to manage names in modules", createNameManagerPass);
registerPass("optimize-instructions", "optimizes instruction combinations", createOptimizeInstructionsPass);
registerPass("post-emscripten", "miscellaneous optimizations for Emscripten-generated code", createPostEmscriptenPass);
registerPass("print", "print in s-expression format", createPrinterPass);
registerPass("print-minified", "print in minified s-expression format", createMinifiedPrinterPass);
registerPass("print-full", "print in full s-expression format", createFullPrinterPass);
registerPass("relooper-jump-threading", "thread relooper jumps (fastcomp output only)", createRelooperJumpThreadingPass);
registerPass("remove-imports", "removes imports and replaces them with nops", createRemoveImportsPass);
registerPass("remove-memory", "removes memory segments", createRemoveMemoryPass);
registerPass("remove-unused-brs", "removes breaks from locations that are not needed", createRemoveUnusedBrsPass);
registerPass("remove-unused-functions", "removes unused functions", createRemoveUnusedFunctionsPass);
registerPass("remove-unused-names", "removes names from locations that are never branched to", createRemoveUnusedNamesPass);
registerPass("reorder-functions", "sorts functions by access frequency", createReorderFunctionsPass);
registerPass("reorder-locals", "sorts locals by access frequency", createReorderLocalsPass);
registerPass("simplify-locals", "miscellaneous locals-related optimizations", createSimplifyLocalsPass);
registerPass("vacuum", "removes obviously unneeded code", createVacuumPass);
registerPass("precompute", "computes compile-time evaluatable expressions", createPrecomputePass);
// registerPass("lower-i64", "lowers i64 into pairs of i32s", createLowerInt64Pass);
}
void PassRunner::addDefaultOptimizationPasses() {
add("duplicate-function-elimination");
add("dce");
add("remove-unused-brs");
add("remove-unused-names");
add("optimize-instructions");
add("precompute");
add("simplify-locals");
add("vacuum"); // previous pass creates garbage
add("remove-unused-brs"); // simplify-locals opens opportunities for phi optimizations
add("coalesce-locals");
add("vacuum"); // previous pass creates garbage
add("reorder-locals");
add("merge-blocks");
add("optimize-instructions");
add("precompute");
add("vacuum"); // should not be needed, last few passes do not create garbage, but just to be safe
add("duplicate-function-elimination"); // optimizations show more functions as duplicate
}
void PassRunner::addDefaultFunctionOptimizationPasses() {
add("dce");
add("remove-unused-brs");
add("remove-unused-names");
add("optimize-instructions");
add("precompute");
add("simplify-locals");
add("vacuum"); // previous pass creates garbage
add("remove-unused-brs"); // simplify-locals opens opportunities for phi optimizations
add("coalesce-locals");
add("vacuum"); // previous pass creates garbage
add("reorder-locals");
add("merge-blocks");
add("optimize-instructions");
add("precompute");
add("vacuum"); // should not be needed, last few passes do not create garbage, but just to be safe
}
void PassRunner::addDefaultGlobalOptimizationPasses() {
add("duplicate-function-elimination");
}
void PassRunner::run() {
if (debug) {
// for debug logging purposes, run each pass in full before running the other
auto totalTime = std::chrono::duration<double>(0);
size_t padding = 0;
std::cerr << "[PassRunner] running passes..." << std::endl;
for (auto pass : passes) {
padding = std::max(padding, pass->name.size());
}
bool passDebug = getenv("BINARYEN_PASS_DEBUG") && getenv("BINARYEN_PASS_DEBUG")[0] != '0';
for (auto* pass : passes) {
// ignoring the time, save a printout of the module before, in case this pass breaks it, so we can print the before and after
std::stringstream moduleBefore;
if (passDebug) {
WasmPrinter::printModule(wasm, moduleBefore);
}
// prepare to run
std::chrono::high_resolution_clock::time_point before;
std::cerr << "[PassRunner] running pass: " << pass->name << "... ";
for (size_t i = 0; i < padding - pass->name.size(); i++) {
std::cerr << ' ';
}
before = std::chrono::high_resolution_clock::now();
if (pass->isFunctionParallel()) {
// function-parallel passes should get a new instance per function
for (auto& func : wasm->functions) {
runPassOnFunction(pass, func.get());
}
} else {
pass->run(this, wasm);
}
auto after = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = after - before;
std::cerr << diff.count() << " seconds." << std::endl;
totalTime += diff;
// validate, ignoring the time
std::cerr << "[PassRunner] (validating)\n";
if (!WasmValidator().validate(*wasm, false, validateGlobally)) {
if (passDebug) {
std::cerr << "Last pass (" << pass->name << ") broke validation. Here is the module before: \n" << moduleBefore.str() << "\n";
} else {
std::cerr << "Last pass (" << pass->name << ") broke validation. Run with BINARYEN_PASS_DEBUG=1 in the env to see the earlier state\n";
}
abort();
}
}
std::cerr << "[PassRunner] passes took " << totalTime.count() << " seconds." << std::endl;
// validate
std::cerr << "[PassRunner] (final validation)\n";
if (!WasmValidator().validate(*wasm, false, validateGlobally)) {
std::cerr << "final module does not validate\n";
abort();
}
} else {
// non-debug normal mode, run them in an optimal manner - for locality it is better
// to run as many passes as possible on a single function before moving to the next
std::vector<Pass*> stack;
auto flush = [&]() {
if (stack.size() > 0) {
// run the stack of passes on all the functions, in parallel
size_t num = ThreadPool::get()->size();
std::vector<std::function<ThreadWorkState ()>> doWorkers;
std::atomic<size_t> nextFunction;
nextFunction.store(0);
size_t numFunctions = wasm->functions.size();
for (size_t i = 0; i < num; i++) {
doWorkers.push_back([&]() {
auto index = nextFunction.fetch_add(1);
// get the next task, if there is one
if (index >= numFunctions) {
return ThreadWorkState::Finished; // nothing left
}
Function* func = this->wasm->functions[index].get();
// do the current task: run all passes on this function
for (auto* pass : stack) {
runPassOnFunction(pass, func);
}
if (index + 1 == numFunctions) {
return ThreadWorkState::Finished; // we did the last one
}
return ThreadWorkState::More;
});
}
ThreadPool::get()->work(doWorkers);
}
stack.clear();
};
for (auto* pass : passes) {
if (pass->isFunctionParallel()) {
stack.push_back(pass);
} else {
flush();
pass->run(this, wasm);
}
}
flush();
}
}
void PassRunner::runFunction(Function* func) {
if (debug) {
std::cerr << "[PassRunner] running passes on function " << func->name << std::endl;
}
for (auto* pass : passes) {
runPassOnFunction(pass, func);
}
}
PassRunner::~PassRunner() {
for (auto pass : passes) {
delete pass;
}
}
void PassRunner::doAdd(Pass* pass) {
passes.push_back(pass);
pass->prepareToRun(this, wasm);
}
void PassRunner::runPassOnFunction(Pass* pass, Function* func) {
#if 0
if (debug) {
std::cerr << "[PassRunner] runPass " << pass->name << " OnFunction " << func->name << "\n";
}
#endif
// function-parallel passes get a new instance per function
if (pass->isFunctionParallel()) {
auto instance = std::unique_ptr<Pass>(pass->create());
instance->runFunction(this, wasm, func);
} else {
pass->runFunction(this, wasm, func);
}
}
} // namespace wasm
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core 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
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#include <boost/tuple/tuple.hpp>
#include <hpp/core/path-planner.hh>
#include <hpp/core/nearest-neighbor.hh>
#include <hpp/util/debug.hh>
#include <hpp/core/roadmap.hh>
#include <hpp/core/problem.hh>
#include <hpp/core/problem-target.hh>
#include <hpp/core/node.hh>
#include <hpp/core/edge.hh>
#include <hpp/core/path.hh>
#include <hpp/core/path-validation.hh>
#include <hpp/core/path-projector.hh>
#include <hpp/core/steering-method.hh>
#include "astar.hh"
#include <hpp/util/timer.hh>
namespace hpp {
namespace core {
PathPlanner::PathPlanner (const Problem& problem) :
problem_ (problem), roadmap_ (Roadmap::create (problem.distance (),
problem.robot())),
interrupt_ (false),
maxIterations_ (std::numeric_limits <unsigned long int>::infinity ()),
timeOut_ (std::numeric_limits <double>::infinity ())
{
}
PathPlanner::PathPlanner (const Problem& problem,
const RoadmapPtr_t& roadmap) :
problem_ (problem), roadmap_ (roadmap),
interrupt_ (false),
maxIterations_ (std::numeric_limits <unsigned long int>::infinity ()),
timeOut_ (std::numeric_limits <double>::infinity ())
{
}
void PathPlanner::init (const PathPlannerWkPtr_t& weak)
{
weakPtr_ = weak;
}
const RoadmapPtr_t& PathPlanner::roadmap () const
{
return roadmap_;
}
const Problem& PathPlanner::problem () const
{
return problem_;
}
void PathPlanner::startSolve ()
{
problem_.checkProblem ();
// Tag init and goal configurations in the roadmap
roadmap()->resetGoalNodes ();
roadmap()->initNode (problem_.initConfig ());
const Configurations_t goals (problem_.goalConfigs ());
for (Configurations_t::const_iterator itGoal = goals.begin ();
itGoal != goals.end (); ++itGoal) {
roadmap()->addGoalNode (*itGoal);
}
problem_.target()->check(roadmap());
}
PathVectorPtr_t PathPlanner::solve ()
{
interrupt_ = false;
bool solved = false;
unsigned long int nIter (0);
boost::posix_time::ptime timeStart(boost::posix_time::microsec_clock::universal_time());
startSolve ();
tryConnectInitAndGoals ();
solved = problem_.target()->reached (roadmap());
if (solved ) {
hppDout (info, "tryConnectInitAndGoals succeeded");
}
if (interrupt_) throw std::runtime_error ("Interruption");
while (!solved) {
std::ostringstream oss;
if (maxIterations_ != std::numeric_limits <unsigned long int>::infinity () && nIter >= maxIterations_) {
oss << "Maximal number of iterations reached: " << maxIterations_;
throw std::runtime_error (oss.str ().c_str ());
}
if(((boost::posix_time::microsec_clock::universal_time() - timeStart).total_milliseconds()) > timeOut_*1000.){
oss << "time out reached : " << timeOut_<<" s";
throw std::runtime_error (oss.str ().c_str ());
}
hppStartBenchmark(ONE_STEP);
oneStep ();
hppStopBenchmark(ONE_STEP);
hppDisplayBenchmark(ONE_STEP);
++nIter;
solved = problem_.target()->reached (roadmap());
if (interrupt_) throw std::runtime_error ("Interruption");
}
PathVectorPtr_t planned = computePath ();
return finishSolve (planned);
}
void PathPlanner::interrupt ()
{
interrupt_ = true;
}
void PathPlanner::maxIterations (const unsigned long int& n)
{
maxIterations_ = n;
}
void PathPlanner::timeOut (const double& time)
{
timeOut_ = time;
}
PathVectorPtr_t PathPlanner::computePath () const
{
return problem_.target()->computePath(roadmap());
}
PathVectorPtr_t PathPlanner::finishSolve (const PathVectorPtr_t& path)
{
return path;
}
void PathPlanner::tryDirectPath ()
{
// call steering method here to build a direct conexion
const SteeringMethodPtr_t& sm (problem ().steeringMethod ());
PathValidationPtr_t pathValidation (problem ().pathValidation ());
PathProjectorPtr_t pathProjector (problem ().pathProjector ());
PathPtr_t validPath, projPath, path;
NodePtr_t initNode = roadmap ()->initNode();
for (NodeVector_t::const_iterator itn = roadmap ()->goalNodes ().begin();
itn != roadmap ()->goalNodes ().end (); ++itn) {
ConfigurationPtr_t q1 ((initNode)->configuration ());
ConfigurationPtr_t q2 ((*itn)->configuration ());
path = (*sm) (*q1, *q2);
if (!path) continue;
if (pathProjector) {
if (!pathProjector->apply (path, projPath)) continue;
} else {
projPath = path;
}
if (projPath) {
PathValidationReportPtr_t report;
bool pathValid = pathValidation->validate (projPath, false, validPath,
report);
if (pathValid && validPath->length() > 0) {
roadmap ()->addEdge (initNode, *itn, projPath);
roadmap ()->addEdge (*itn, initNode, projPath->reverse());
}
}
}
}
void PathPlanner::tryConnectInitAndGoals ()
{
// call steering method here to build a direct conexion
const SteeringMethodPtr_t& sm (problem ().steeringMethod ());
PathValidationPtr_t pathValidation (problem ().pathValidation ());
PathProjectorPtr_t pathProjector (problem ().pathProjector ());
PathPtr_t validPath, projPath, path;
NodePtr_t initNode = roadmap ()->initNode();
NearestNeighborPtr_t nn (roadmap ()->nearestNeighbor ());
// Register edges to add to roadmap and add them after iterating
// among the connected components.
typedef boost::tuple <NodePtr_t, NodePtr_t, PathPtr_t> FutureEdge_t;
typedef std::vector <FutureEdge_t> FutureEdges_t;
FutureEdges_t futureEdges;
ConnectedComponentPtr_t initCC (initNode->connectedComponent ());
for (ConnectedComponents_t::iterator itCC
(roadmap ()->connectedComponents ().begin ());
itCC != roadmap ()->connectedComponents ().end (); ++itCC) {
if (*itCC != initCC) {
value_type d;
NodePtr_t near (nn->search (*initNode->configuration (),
*itCC, d, true));
assert (near);
ConfigurationPtr_t q1 (initNode->configuration ());
ConfigurationPtr_t q2 (near->configuration ());
path = (*sm) (*q1, *q2);
if (!path) continue;
if (pathProjector) {
if (!pathProjector->apply (path, projPath)) continue;
} else {
projPath = path;
}
if (projPath) {
PathValidationReportPtr_t report;
bool pathValid = pathValidation->validate (projPath, false,
validPath, report);
if (pathValid && validPath->length() > 0) {
futureEdges.push_back (FutureEdge_t (initNode, near, projPath));
}
}
}
}
for (NodeVector_t::const_iterator itn = roadmap ()->goalNodes ().begin();
itn != roadmap ()->goalNodes ().end (); ++itn) {
ConnectedComponentPtr_t goalCC ((*itn)->connectedComponent ());
for (ConnectedComponents_t::iterator itCC
(roadmap ()->connectedComponents ().begin ());
itCC != roadmap ()->connectedComponents ().end (); ++itCC) {
if (*itCC != goalCC) {
value_type d;
NodePtr_t near (nn->search (*(*itn)->configuration (), *itCC, d,
false));
assert (near);
ConfigurationPtr_t q1 (near->configuration ());
ConfigurationPtr_t q2 ((*itn)->configuration ());
path = (*sm) (*q1, *q2);
if (!path) continue;
if (pathProjector) {
if (!pathProjector->apply (path, projPath)) continue;
} else {
projPath = path;
}
if (projPath) {
PathValidationReportPtr_t report;
bool pathValid = pathValidation->validate (projPath, false,
validPath, report);
if (pathValid && validPath->length() > 0) {
futureEdges.push_back (FutureEdge_t (near, (*itn), projPath));
}
}
}
}
}
// Add edges
for (FutureEdges_t::const_iterator it (futureEdges.begin ());
it != futureEdges.end (); ++it) {
roadmap ()->addEdge (it->get <0> (), it->get <1> (), it->get <2> ());
}
}
} // namespace core
} // namespace hpp
<commit_msg>Fix compilation warning.<commit_after>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core 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
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#include <boost/tuple/tuple.hpp>
#include <hpp/core/path-planner.hh>
#include <hpp/core/nearest-neighbor.hh>
#include <hpp/util/debug.hh>
#include <hpp/core/roadmap.hh>
#include <hpp/core/problem.hh>
#include <hpp/core/problem-target.hh>
#include <hpp/core/node.hh>
#include <hpp/core/edge.hh>
#include <hpp/core/path.hh>
#include <hpp/core/path-validation.hh>
#include <hpp/core/path-projector.hh>
#include <hpp/core/steering-method.hh>
#include "astar.hh"
#include <hpp/util/timer.hh>
namespace hpp {
namespace core {
PathPlanner::PathPlanner (const Problem& problem) :
problem_ (problem), roadmap_ (Roadmap::create (problem.distance (),
problem.robot())),
interrupt_ (false),
maxIterations_ (std::numeric_limits <unsigned long int>::infinity ()),
timeOut_ (std::numeric_limits <double>::infinity ())
{
}
PathPlanner::PathPlanner (const Problem& problem,
const RoadmapPtr_t& roadmap) :
problem_ (problem), roadmap_ (roadmap),
interrupt_ (false),
maxIterations_ (std::numeric_limits <unsigned long int>::infinity ()),
timeOut_ (std::numeric_limits <double>::infinity ())
{
}
void PathPlanner::init (const PathPlannerWkPtr_t& weak)
{
weakPtr_ = weak;
}
const RoadmapPtr_t& PathPlanner::roadmap () const
{
return roadmap_;
}
const Problem& PathPlanner::problem () const
{
return problem_;
}
void PathPlanner::startSolve ()
{
problem_.checkProblem ();
// Tag init and goal configurations in the roadmap
roadmap()->resetGoalNodes ();
roadmap()->initNode (problem_.initConfig ());
const Configurations_t goals (problem_.goalConfigs ());
for (Configurations_t::const_iterator itGoal = goals.begin ();
itGoal != goals.end (); ++itGoal) {
roadmap()->addGoalNode (*itGoal);
}
problem_.target()->check(roadmap());
}
PathVectorPtr_t PathPlanner::solve ()
{
namespace bpt = boost::posix_time;
interrupt_ = false;
bool solved = false;
unsigned long int nIter (0);
bpt::ptime timeStart(bpt::microsec_clock::universal_time());
startSolve ();
tryConnectInitAndGoals ();
solved = problem_.target()->reached (roadmap());
if (solved ) {
hppDout (info, "tryConnectInitAndGoals succeeded");
}
if (interrupt_) throw std::runtime_error ("Interruption");
while (!solved) {
std::ostringstream oss;
if (maxIterations_ != std::numeric_limits <unsigned long int>::infinity () && nIter >= maxIterations_) {
oss << "Maximal number of iterations reached: " << maxIterations_;
throw std::runtime_error (oss.str ().c_str ());
}
bpt::ptime timeStop(bpt::microsec_clock::universal_time());
if(static_cast<value_type>((timeStop - timeStart).total_milliseconds())
> timeOut_*1000){
oss << "time out reached : " << timeOut_<<" s";
throw std::runtime_error (oss.str ().c_str ());
}
hppStartBenchmark(ONE_STEP);
oneStep ();
hppStopBenchmark(ONE_STEP);
hppDisplayBenchmark(ONE_STEP);
++nIter;
solved = problem_.target()->reached (roadmap());
if (interrupt_) throw std::runtime_error ("Interruption");
}
PathVectorPtr_t planned = computePath ();
return finishSolve (planned);
}
void PathPlanner::interrupt ()
{
interrupt_ = true;
}
void PathPlanner::maxIterations (const unsigned long int& n)
{
maxIterations_ = n;
}
void PathPlanner::timeOut (const double& time)
{
timeOut_ = time;
}
PathVectorPtr_t PathPlanner::computePath () const
{
return problem_.target()->computePath(roadmap());
}
PathVectorPtr_t PathPlanner::finishSolve (const PathVectorPtr_t& path)
{
return path;
}
void PathPlanner::tryDirectPath ()
{
// call steering method here to build a direct conexion
const SteeringMethodPtr_t& sm (problem ().steeringMethod ());
PathValidationPtr_t pathValidation (problem ().pathValidation ());
PathProjectorPtr_t pathProjector (problem ().pathProjector ());
PathPtr_t validPath, projPath, path;
NodePtr_t initNode = roadmap ()->initNode();
for (NodeVector_t::const_iterator itn = roadmap ()->goalNodes ().begin();
itn != roadmap ()->goalNodes ().end (); ++itn) {
ConfigurationPtr_t q1 ((initNode)->configuration ());
ConfigurationPtr_t q2 ((*itn)->configuration ());
path = (*sm) (*q1, *q2);
if (!path) continue;
if (pathProjector) {
if (!pathProjector->apply (path, projPath)) continue;
} else {
projPath = path;
}
if (projPath) {
PathValidationReportPtr_t report;
bool pathValid = pathValidation->validate (projPath, false, validPath,
report);
if (pathValid && validPath->length() > 0) {
roadmap ()->addEdge (initNode, *itn, projPath);
roadmap ()->addEdge (*itn, initNode, projPath->reverse());
}
}
}
}
void PathPlanner::tryConnectInitAndGoals ()
{
// call steering method here to build a direct conexion
const SteeringMethodPtr_t& sm (problem ().steeringMethod ());
PathValidationPtr_t pathValidation (problem ().pathValidation ());
PathProjectorPtr_t pathProjector (problem ().pathProjector ());
PathPtr_t validPath, projPath, path;
NodePtr_t initNode = roadmap ()->initNode();
NearestNeighborPtr_t nn (roadmap ()->nearestNeighbor ());
// Register edges to add to roadmap and add them after iterating
// among the connected components.
typedef boost::tuple <NodePtr_t, NodePtr_t, PathPtr_t> FutureEdge_t;
typedef std::vector <FutureEdge_t> FutureEdges_t;
FutureEdges_t futureEdges;
ConnectedComponentPtr_t initCC (initNode->connectedComponent ());
for (ConnectedComponents_t::iterator itCC
(roadmap ()->connectedComponents ().begin ());
itCC != roadmap ()->connectedComponents ().end (); ++itCC) {
if (*itCC != initCC) {
value_type d;
NodePtr_t near (nn->search (*initNode->configuration (),
*itCC, d, true));
assert (near);
ConfigurationPtr_t q1 (initNode->configuration ());
ConfigurationPtr_t q2 (near->configuration ());
path = (*sm) (*q1, *q2);
if (!path) continue;
if (pathProjector) {
if (!pathProjector->apply (path, projPath)) continue;
} else {
projPath = path;
}
if (projPath) {
PathValidationReportPtr_t report;
bool pathValid = pathValidation->validate (projPath, false,
validPath, report);
if (pathValid && validPath->length() > 0) {
futureEdges.push_back (FutureEdge_t (initNode, near, projPath));
}
}
}
}
for (NodeVector_t::const_iterator itn = roadmap ()->goalNodes ().begin();
itn != roadmap ()->goalNodes ().end (); ++itn) {
ConnectedComponentPtr_t goalCC ((*itn)->connectedComponent ());
for (ConnectedComponents_t::iterator itCC
(roadmap ()->connectedComponents ().begin ());
itCC != roadmap ()->connectedComponents ().end (); ++itCC) {
if (*itCC != goalCC) {
value_type d;
NodePtr_t near (nn->search (*(*itn)->configuration (), *itCC, d,
false));
assert (near);
ConfigurationPtr_t q1 (near->configuration ());
ConfigurationPtr_t q2 ((*itn)->configuration ());
path = (*sm) (*q1, *q2);
if (!path) continue;
if (pathProjector) {
if (!pathProjector->apply (path, projPath)) continue;
} else {
projPath = path;
}
if (projPath) {
PathValidationReportPtr_t report;
bool pathValid = pathValidation->validate (projPath, false,
validPath, report);
if (pathValid && validPath->length() > 0) {
futureEdges.push_back (FutureEdge_t (near, (*itn), projPath));
}
}
}
}
}
// Add edges
for (FutureEdges_t::const_iterator it (futureEdges.begin ());
it != futureEdges.end (); ++it) {
roadmap ()->addEdge (it->get <0> (), it->get <1> (), it->get <2> ());
}
}
} // namespace core
} // namespace hpp
<|endoftext|>
|
<commit_before>#include "queueloader.h"
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <libgen.h>
#include <unistd.h>
#include "config.h"
#include "configcontainer.h"
#include "logger.h"
#include "stflpp.h"
#include "utils.h"
using namespace newsboat;
namespace podboat {
queueloader::queueloader(const std::string& file, pb_controller* c)
: queuefile(file)
, ctrl(c)
{
}
void queueloader::reload(std::vector<download>& downloads, bool remove_unplayed)
{
std::vector<download> dltemp;
std::fstream f;
for (auto& dl : downloads) {
if (dl.status() == dlstatus::DOWNLOADING) { // we are not
// allowed to reload
// if a download is
// in progress!
LOG(level::INFO,
"queueloader::reload: aborting reload due to "
"dlstatus::DOWNLOADING status");
return;
}
switch (dl.status()) {
case dlstatus::QUEUED:
case dlstatus::CANCELLED:
case dlstatus::FAILED:
case dlstatus::ALREADY_DOWNLOADED:
case dlstatus::READY:
LOG(level::DEBUG,
"queueloader::reload: storing %s to new vector",
dl.url());
dltemp.push_back(dl);
break;
case dlstatus::PLAYED:
case dlstatus::FINISHED:
if (!remove_unplayed) {
LOG(level::DEBUG,
"queueloader::reload: storing %s to "
"new "
"vector",
dl.url());
dltemp.push_back(dl);
}
break;
default:
break;
}
}
f.open(queuefile.c_str(), std::fstream::in);
if (f.is_open()) {
std::string line;
do {
std::getline(f, line);
if (!f.eof() && line.length() > 0) {
LOG(level::DEBUG,
"queueloader::reload: loaded `%s' from "
"queue file",
line);
std::vector<std::string> fields =
utils::tokenize_quoted(line);
bool url_found = false;
for (auto& dl : dltemp) {
if (fields[0] == dl.url()) {
LOG(level::INFO,
"queueloader::reload: "
"found `%s' in old "
"vector",
fields[0]);
url_found = true;
break;
}
}
for (auto& dl : downloads) {
if (fields[0] == dl.url()) {
LOG(level::INFO,
"queueloader::reload: "
"found `%s' in new "
"vector",
line);
url_found = true;
break;
}
}
if (!url_found) {
LOG(level::INFO,
"queueloader::reload: found "
"`%s' "
"nowhere -> storing to new "
"vector",
line);
download d(ctrl);
std::string fn;
if (fields.size() == 1)
fn = get_filename(fields[0]);
else
fn = fields[1];
d.set_filename(fn);
if (access(fn.c_str(), F_OK) == 0) {
LOG(level::INFO,
"queueloader::reload: "
"found `%s' on file "
"system "
"-> mark as already "
"downloaded",
fn);
if (fields.size() >= 3) {
if (fields[2] ==
"downloaded")
d.set_status(
dlstatus::
READY);
if (fields[2] ==
"played")
d.set_status(
dlstatus::
PLAYED);
} else
d.set_status(dlstatus::
ALREADY_DOWNLOADED); // TODO: scrap dlstatus::ALREADY_DOWNLOADED state
} else if (
access((fn +
configcontainer::
PARTIAL_FILE_SUFFIX)
.c_str(),
F_OK) == 0) {
LOG(level::INFO,
"queueloader::reload: "
"found `%s' on file "
"system "
"-> mark as partially "
"downloaded",
fn +
configcontainer::
PARTIAL_FILE_SUFFIX);
d.set_status(dlstatus::
ALREADY_DOWNLOADED);
}
d.set_url(fields[0]);
dltemp.push_back(d);
}
}
} while (!f.eof());
f.close();
}
f.open(queuefile.c_str(), std::fstream::out);
if (f.is_open()) {
for (auto& dl : dltemp) {
f << dl.url() << " " << stfl::quote(dl.filename());
if (dl.status() == dlstatus::READY)
f << " downloaded";
if (dl.status() == dlstatus::PLAYED)
f << " played";
f << std::endl;
}
f.close();
}
downloads = dltemp;
}
std::string queueloader::get_filename(const std::string& str)
{
std::string fn = ctrl->get_dlpath();
if (fn[fn.length() - 1] != NEWSBEUTER_PATH_SEP[0])
fn.append(NEWSBEUTER_PATH_SEP);
char buf[1024];
snprintf(buf, sizeof(buf), "%s", str.c_str());
char* base = basename(buf);
if (!base || strlen(base) == 0) {
char lbuf[128];
time_t t = time(nullptr);
strftime(lbuf,
sizeof(lbuf),
"%Y-%b-%d-%H%M%S.unknown",
localtime(&t));
fn.append(lbuf);
} else {
fn.append(utils::replace_all(base, "'", "%27"));
}
return fn;
}
} // namespace podboat
<commit_msg>Constify more for-range loops<commit_after>#include "queueloader.h"
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <libgen.h>
#include <unistd.h>
#include "config.h"
#include "configcontainer.h"
#include "logger.h"
#include "stflpp.h"
#include "utils.h"
using namespace newsboat;
namespace podboat {
queueloader::queueloader(const std::string& file, pb_controller* c)
: queuefile(file)
, ctrl(c)
{
}
void queueloader::reload(std::vector<download>& downloads, bool remove_unplayed)
{
std::vector<download> dltemp;
std::fstream f;
for (const auto& dl : downloads) {
if (dl.status() == dlstatus::DOWNLOADING) { // we are not
// allowed to reload
// if a download is
// in progress!
LOG(level::INFO,
"queueloader::reload: aborting reload due to "
"dlstatus::DOWNLOADING status");
return;
}
switch (dl.status()) {
case dlstatus::QUEUED:
case dlstatus::CANCELLED:
case dlstatus::FAILED:
case dlstatus::ALREADY_DOWNLOADED:
case dlstatus::READY:
LOG(level::DEBUG,
"queueloader::reload: storing %s to new vector",
dl.url());
dltemp.push_back(dl);
break;
case dlstatus::PLAYED:
case dlstatus::FINISHED:
if (!remove_unplayed) {
LOG(level::DEBUG,
"queueloader::reload: storing %s to "
"new "
"vector",
dl.url());
dltemp.push_back(dl);
}
break;
default:
break;
}
}
f.open(queuefile.c_str(), std::fstream::in);
if (f.is_open()) {
std::string line;
do {
std::getline(f, line);
if (!f.eof() && line.length() > 0) {
LOG(level::DEBUG,
"queueloader::reload: loaded `%s' from "
"queue file",
line);
std::vector<std::string> fields =
utils::tokenize_quoted(line);
bool url_found = false;
for (const auto& dl : dltemp) {
if (fields[0] == dl.url()) {
LOG(level::INFO,
"queueloader::reload: "
"found `%s' in old "
"vector",
fields[0]);
url_found = true;
break;
}
}
for (const auto& dl : downloads) {
if (fields[0] == dl.url()) {
LOG(level::INFO,
"queueloader::reload: "
"found `%s' in new "
"vector",
line);
url_found = true;
break;
}
}
if (!url_found) {
LOG(level::INFO,
"queueloader::reload: found "
"`%s' "
"nowhere -> storing to new "
"vector",
line);
download d(ctrl);
std::string fn;
if (fields.size() == 1)
fn = get_filename(fields[0]);
else
fn = fields[1];
d.set_filename(fn);
if (access(fn.c_str(), F_OK) == 0) {
LOG(level::INFO,
"queueloader::reload: "
"found `%s' on file "
"system "
"-> mark as already "
"downloaded",
fn);
if (fields.size() >= 3) {
if (fields[2] ==
"downloaded")
d.set_status(
dlstatus::
READY);
if (fields[2] ==
"played")
d.set_status(
dlstatus::
PLAYED);
} else
d.set_status(dlstatus::
ALREADY_DOWNLOADED); // TODO: scrap dlstatus::ALREADY_DOWNLOADED state
} else if (
access((fn +
configcontainer::
PARTIAL_FILE_SUFFIX)
.c_str(),
F_OK) == 0) {
LOG(level::INFO,
"queueloader::reload: "
"found `%s' on file "
"system "
"-> mark as partially "
"downloaded",
fn +
configcontainer::
PARTIAL_FILE_SUFFIX);
d.set_status(dlstatus::
ALREADY_DOWNLOADED);
}
d.set_url(fields[0]);
dltemp.push_back(d);
}
}
} while (!f.eof());
f.close();
}
f.open(queuefile.c_str(), std::fstream::out);
if (f.is_open()) {
for (const auto& dl : dltemp) {
f << dl.url() << " " << stfl::quote(dl.filename());
if (dl.status() == dlstatus::READY)
f << " downloaded";
if (dl.status() == dlstatus::PLAYED)
f << " played";
f << std::endl;
}
f.close();
}
downloads = dltemp;
}
std::string queueloader::get_filename(const std::string& str)
{
std::string fn = ctrl->get_dlpath();
if (fn[fn.length() - 1] != NEWSBEUTER_PATH_SEP[0])
fn.append(NEWSBEUTER_PATH_SEP);
char buf[1024];
snprintf(buf, sizeof(buf), "%s", str.c_str());
char* base = basename(buf);
if (!base || strlen(base) == 0) {
char lbuf[128];
time_t t = time(nullptr);
strftime(lbuf,
sizeof(lbuf),
"%Y-%b-%d-%H%M%S.unknown",
localtime(&t));
fn.append(lbuf);
} else {
fn.append(utils::replace_all(base, "'", "%27"));
}
return fn;
}
} // namespace podboat
<|endoftext|>
|
<commit_before>#include "queueloader.h"
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <libgen.h>
#include <unistd.h>
#include "config.h"
#include "configcontainer.h"
#include "logger.h"
#include "stflpp.h"
#include "utils.h"
using namespace newsboat;
namespace podboat {
queueloader::queueloader(const std::string& file, pb_controller* c)
: queuefile(file)
, ctrl(c)
{
}
void queueloader::reload(std::vector<download>& downloads, bool remove_unplayed)
{
std::vector<download> dltemp;
std::fstream f;
for (const auto& dl : downloads) {
if (dl.status() == dlstatus::DOWNLOADING) { // we are not
// allowed to reload
// if a download is
// in progress!
LOG(level::INFO,
"queueloader::reload: aborting reload due to "
"dlstatus::DOWNLOADING status");
return;
}
switch (dl.status()) {
case dlstatus::QUEUED:
case dlstatus::CANCELLED:
case dlstatus::FAILED:
case dlstatus::ALREADY_DOWNLOADED:
case dlstatus::READY:
LOG(level::DEBUG,
"queueloader::reload: storing %s to new vector",
dl.url());
dltemp.push_back(dl);
break;
case dlstatus::PLAYED:
case dlstatus::FINISHED:
if (!remove_unplayed) {
LOG(level::DEBUG,
"queueloader::reload: storing %s to "
"new "
"vector",
dl.url());
dltemp.push_back(dl);
}
break;
default:
break;
}
}
f.open(queuefile.c_str(), std::fstream::in);
if (f.is_open()) {
std::string line;
do {
std::getline(f, line);
if (!f.eof() && line.length() > 0) {
LOG(level::DEBUG,
"queueloader::reload: loaded `%s' from "
"queue file",
line);
std::vector<std::string> fields =
utils::tokenize_quoted(line);
bool url_found = false;
for (const auto& dl : dltemp) {
if (fields[0] == dl.url()) {
LOG(level::INFO,
"queueloader::reload: "
"found `%s' in old "
"vector",
fields[0]);
url_found = true;
break;
}
}
for (const auto& dl : downloads) {
if (fields[0] == dl.url()) {
LOG(level::INFO,
"queueloader::reload: "
"found `%s' in new "
"vector",
line);
url_found = true;
break;
}
}
if (!url_found) {
LOG(level::INFO,
"queueloader::reload: found "
"`%s' "
"nowhere -> storing to new "
"vector",
line);
download d(ctrl);
std::string fn;
if (fields.size() == 1)
fn = get_filename(fields[0]);
else
fn = fields[1];
d.set_filename(fn);
if (access(fn.c_str(), F_OK) == 0) {
LOG(level::INFO,
"queueloader::reload: "
"found `%s' on file "
"system "
"-> mark as already "
"downloaded",
fn);
if (fields.size() >= 3) {
if (fields[2] ==
"downloaded")
d.set_status(
dlstatus::
READY);
if (fields[2] ==
"played")
d.set_status(
dlstatus::
PLAYED);
} else
d.set_status(dlstatus::
ALREADY_DOWNLOADED); // TODO: scrap dlstatus::ALREADY_DOWNLOADED state
} else if (
access((fn +
configcontainer::
PARTIAL_FILE_SUFFIX)
.c_str(),
F_OK) == 0) {
LOG(level::INFO,
"queueloader::reload: "
"found `%s' on file "
"system "
"-> mark as partially "
"downloaded",
fn +
configcontainer::
PARTIAL_FILE_SUFFIX);
d.set_status(dlstatus::
ALREADY_DOWNLOADED);
}
d.set_url(fields[0]);
dltemp.push_back(d);
}
}
} while (!f.eof());
f.close();
}
f.open(queuefile.c_str(), std::fstream::out);
if (f.is_open()) {
for (const auto& dl : dltemp) {
f << dl.url() << " " << stfl::quote(dl.filename());
if (dl.status() == dlstatus::READY)
f << " downloaded";
if (dl.status() == dlstatus::PLAYED)
f << " played";
f << std::endl;
}
f.close();
}
downloads = dltemp;
}
std::string queueloader::get_filename(const std::string& str)
{
std::string fn = ctrl->get_dlpath();
if (fn[fn.length() - 1] != NEWSBEUTER_PATH_SEP[0])
fn.append(NEWSBEUTER_PATH_SEP);
char buf[1024];
snprintf(buf, sizeof(buf), "%s", str.c_str());
char* base = basename(buf);
if (!base || strlen(base) == 0) {
char lbuf[128];
time_t t = time(nullptr);
strftime(lbuf,
sizeof(lbuf),
"%Y-%b-%d-%H%M%S.unknown",
localtime(&t));
fn.append(lbuf);
} else {
fn.append(utils::replace_all(base, "'", "%27"));
}
return fn;
}
} // namespace podboat
<commit_msg>Fix podboat segfault when parsing comment in queue<commit_after>#include "queueloader.h"
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <libgen.h>
#include <unistd.h>
#include "config.h"
#include "configcontainer.h"
#include "logger.h"
#include "stflpp.h"
#include "strprintf.h"
#include "utils.h"
using namespace newsboat;
namespace podboat {
queueloader::queueloader(const std::string& file, pb_controller* c)
: queuefile(file)
, ctrl(c)
{
}
void queueloader::reload(std::vector<download>& downloads, bool remove_unplayed)
{
std::vector<download> dltemp;
std::fstream f;
for (const auto& dl : downloads) {
if (dl.status() == dlstatus::DOWNLOADING) { // we are not
// allowed to reload
// if a download is
// in progress!
LOG(level::INFO,
"queueloader::reload: aborting reload due to "
"dlstatus::DOWNLOADING status");
return;
}
switch (dl.status()) {
case dlstatus::QUEUED:
case dlstatus::CANCELLED:
case dlstatus::FAILED:
case dlstatus::ALREADY_DOWNLOADED:
case dlstatus::READY:
LOG(level::DEBUG,
"queueloader::reload: storing %s to new vector",
dl.url());
dltemp.push_back(dl);
break;
case dlstatus::PLAYED:
case dlstatus::FINISHED:
if (!remove_unplayed) {
LOG(level::DEBUG,
"queueloader::reload: storing %s to "
"new "
"vector",
dl.url());
dltemp.push_back(dl);
}
break;
default:
break;
}
}
f.open(queuefile.c_str(), std::fstream::in);
bool comments_ignored = false;
if (f.is_open()) {
std::string line;
do {
std::getline(f, line);
if (!f.eof() && line.length() > 0) {
LOG(level::DEBUG,
"queueloader::reload: loaded `%s' from "
"queue file",
line);
std::vector<std::string> fields =
utils::tokenize_quoted(line);
bool url_found = false;
if (fields.empty()) {
if (!comments_ignored) {
std::cout << StrPrintf::fmt(
_("WARNING: Comment found "
"in %s. The queue file is regenerated "
"when podboat exits and comments will "
"be deleted. Press enter to continue or "
"Ctrl+C to abort"),
queuefile)
<< std::endl;
std::cin.ignore();
comments_ignored = true;
}
continue;
}
for (const auto& dl : dltemp) {
if (fields[0] == dl.url()) {
LOG(level::INFO,
"queueloader::reload: "
"found `%s' in old "
"vector",
fields[0]);
url_found = true;
break;
}
}
for (const auto& dl : downloads) {
if (fields[0] == dl.url()) {
LOG(level::INFO,
"queueloader::reload: "
"found `%s' in new "
"vector",
line);
url_found = true;
break;
}
}
if (!url_found) {
LOG(level::INFO,
"queueloader::reload: found "
"`%s' "
"nowhere -> storing to new "
"vector",
line);
download d(ctrl);
std::string fn;
if (fields.size() == 1)
fn = get_filename(fields[0]);
else
fn = fields[1];
d.set_filename(fn);
if (access(fn.c_str(), F_OK) == 0) {
LOG(level::INFO,
"queueloader::reload: "
"found `%s' on file "
"system "
"-> mark as already "
"downloaded",
fn);
if (fields.size() >= 3) {
if (fields[2] ==
"downloaded")
d.set_status(
dlstatus::
READY);
if (fields[2] ==
"played")
d.set_status(
dlstatus::
PLAYED);
} else
d.set_status(dlstatus::
ALREADY_DOWNLOADED); // TODO: scrap dlstatus::ALREADY_DOWNLOADED state
} else if (
access((fn +
configcontainer::
PARTIAL_FILE_SUFFIX)
.c_str(),
F_OK) == 0) {
LOG(level::INFO,
"queueloader::reload: "
"found `%s' on file "
"system "
"-> mark as partially "
"downloaded",
fn +
configcontainer::
PARTIAL_FILE_SUFFIX);
d.set_status(dlstatus::
ALREADY_DOWNLOADED);
}
d.set_url(fields[0]);
dltemp.push_back(d);
}
}
} while (!f.eof());
f.close();
}
f.open(queuefile.c_str(), std::fstream::out);
if (f.is_open()) {
for (const auto& dl : dltemp) {
f << dl.url() << " " << stfl::quote(dl.filename());
if (dl.status() == dlstatus::READY)
f << " downloaded";
if (dl.status() == dlstatus::PLAYED)
f << " played";
f << std::endl;
}
f.close();
}
downloads = dltemp;
}
std::string queueloader::get_filename(const std::string& str)
{
std::string fn = ctrl->get_dlpath();
if (fn[fn.length() - 1] != NEWSBEUTER_PATH_SEP[0])
fn.append(NEWSBEUTER_PATH_SEP);
char buf[1024];
snprintf(buf, sizeof(buf), "%s", str.c_str());
char* base = basename(buf);
if (!base || strlen(base) == 0) {
char lbuf[128];
time_t t = time(nullptr);
strftime(lbuf,
sizeof(lbuf),
"%Y-%b-%d-%H%M%S.unknown",
localtime(&t));
fn.append(lbuf);
} else {
fn.append(utils::replace_all(base, "'", "%27"));
}
return fn;
}
} // namespace podboat
<|endoftext|>
|
<commit_before>/* This is free and unencumbered software released into the public domain. */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "writer.h"
#include "writer/impl.h"
#ifndef DISABLE_JSONLD
#include "writer/jsonld.h"
#endif
#ifndef DISABLE_NQUADS
#include "writer/nquads.h"
#endif
#ifndef DISABLE_PAJEK
#include "writer/pajek.h"
#endif
#ifndef DISABLE_RDFJSON
#include "writer/rdfjson.h"
#endif
#ifndef DISABLE_TRIX
#include "writer/trix.h"
#endif
#ifndef DISABLE_XSLT
#include "writer/xslt.h"
#endif
#ifdef HAVE_LIBRAPTOR2
#include "raptor.h"
#include "writer/raptor.h"
#endif
#include "format.h"
#include "quad.h"
#include "term.h"
#include "triple.h"
#include <cassert> /* for assert() */
#include <cstdlib> /* for std::abort() */
#include <cstring> /* for std::strcmp() */
#include <stdexcept> /* for std::invalid_argument, std::runtime_error */
using namespace rdf;
static rdf::writer::implementation*
rdf_writer_for(FILE* const stream,
const char* const content_type,
const char* const charset,
const char* const base_uri) {
const format* const format = format::find_for_content_type(content_type);
if (format == nullptr) {
return nullptr; /* unknown content type */
}
assert(format->module_name != nullptr);
#ifndef DISABLE_JSONLD
if (std::strcmp("jsonld", format->module_name) == 0) {
return rdf_writer_for_jsonld(stream, content_type, charset, base_uri);
}
#endif
#ifndef DISABLE_NQUADS
if (std::strcmp("nquads", format->module_name) == 0) {
return rdf_writer_for_nquads(stream, content_type, charset, base_uri);
}
#endif
#ifdef HAVE_LIBRAPTOR2
if (std::strcmp("raptor", format->module_name) == 0) {
return rdf_writer_for_raptor(stream, content_type, charset, base_uri);
}
#endif
#ifndef DISABLE_PAJEK
if (std::strcmp("pajek", format->module_name) == 0) {
return rdf_writer_for_pajek(stream, content_type, charset, base_uri);
}
#endif
#ifndef DISABLE_RDFJSON
if (std::strcmp("rdfjson", format->module_name) == 0) {
return rdf_writer_for_rdfjson(stream, content_type, charset, base_uri);
}
#endif
#ifndef DISABLE_TRIX
if (std::strcmp("trix", format->module_name) == 0) {
return rdf_writer_for_trix(stream, content_type, charset, base_uri);
}
#endif
#ifndef DISABLE_XSLT
if (std::strcmp("xslt", format->module_name) == 0) {
return rdf_writer_for_xslt(stream, content_type, charset, base_uri);
}
#endif
(void)stream, (void)charset, (void)base_uri;
return std::abort(), nullptr; /* never reached */
}
writer::writer(const std::string& file_path,
const std::string& content_type,
const std::string& charset,
const std::string& base_uri)
: _implementation(nullptr) {
assert(false && "file paths not supported yet"); // TODO
(void)file_path, (void)content_type, (void)charset, (void)base_uri; // TODO
}
writer::writer(std::ostream& stream,
const std::string& content_type,
const std::string& charset,
const std::string& base_uri)
: _implementation(nullptr) {
assert(false && "std::ostream not supported yet"); // TODO
(void)stream, (void)content_type, (void)charset, (void)base_uri; // TODO
}
writer::writer(FILE* const stream,
const std::string& content_type,
const std::string& charset,
const std::string& base_uri)
: _implementation(rdf_writer_for(stream, content_type.c_str(), charset.c_str(), base_uri.c_str())) {
if (!_implementation) {
throw std::invalid_argument("unknown content type: " + content_type);
}
}
writer::~writer() noexcept = default;
writer::writer(writer&&) /*noexcept*/ = default;
writer&
writer::operator=(writer&&) /*noexcept*/ = default;
void
writer::configure(const char* const key,
const char* const value) {
assert(_implementation);
assert(key != nullptr); // FIXME
_implementation->configure(key, value);
}
void
writer::define_prefix(const char* prefix,
const char* uri_string) {
assert(_implementation);
_implementation->define_prefix(prefix, uri_string);
}
void
writer::begin() {
assert(_implementation);
_implementation->begin();
}
void
writer::finish() {
assert(_implementation);
_implementation->finish();
}
void
writer::flush() {
assert(_implementation);
_implementation->flush();
}
void
writer::write_triple(const triple& triple) {
assert(_implementation);
_implementation->write_triple(triple);
}
void
writer::write_quad(const quad& quad) {
assert(_implementation);
_implementation->write_quad(quad);
}
void
writer::write_comment(const char* const comment) {
assert(_implementation);
_implementation->write_comment(comment);
}
<commit_msg>Forced the use of Raptor for Turtle serialization for now.<commit_after>/* This is free and unencumbered software released into the public domain. */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "writer.h"
#include "writer/impl.h"
#ifndef DISABLE_JSONLD
#include "writer/jsonld.h"
#endif
#ifndef DISABLE_NQUADS
#include "writer/nquads.h"
#endif
#ifndef DISABLE_PAJEK
#include "writer/pajek.h"
#endif
#ifndef DISABLE_RDFJSON
#include "writer/rdfjson.h"
#endif
#ifndef DISABLE_TRIX
#include "writer/trix.h"
#endif
#ifndef DISABLE_XSLT
#include "writer/xslt.h"
#endif
#ifdef HAVE_LIBRAPTOR2
#include "raptor.h"
#include "writer/raptor.h"
#endif
#include "format.h"
#include "quad.h"
#include "term.h"
#include "triple.h"
#include <cassert> /* for assert() */
#include <cstdlib> /* for std::abort() */
#include <cstring> /* for std::strcmp() */
#include <stdexcept> /* for std::invalid_argument, std::runtime_error */
using namespace rdf;
static rdf::writer::implementation*
rdf_writer_for(FILE* const stream,
const char* const content_type,
const char* const charset,
const char* const base_uri) {
const format* const format = format::find_for_content_type(content_type);
if (format == nullptr) {
return nullptr; /* unknown content type */
}
assert(format->module_name != nullptr);
if (std::strcmp("text/turtle", content_type) == 0) { // FIXME
return rdf_writer_for_raptor(stream, content_type, charset, base_uri);
}
#ifndef DISABLE_JSONLD
if (std::strcmp("jsonld", format->module_name) == 0) {
return rdf_writer_for_jsonld(stream, content_type, charset, base_uri);
}
#endif
#ifndef DISABLE_NQUADS
if (std::strcmp("nquads", format->module_name) == 0) {
return rdf_writer_for_nquads(stream, content_type, charset, base_uri);
}
#endif
#ifdef HAVE_LIBRAPTOR2
if (std::strcmp("raptor", format->module_name) == 0) {
return rdf_writer_for_raptor(stream, content_type, charset, base_uri);
}
#endif
#ifndef DISABLE_PAJEK
if (std::strcmp("pajek", format->module_name) == 0) {
return rdf_writer_for_pajek(stream, content_type, charset, base_uri);
}
#endif
#ifndef DISABLE_RDFJSON
if (std::strcmp("rdfjson", format->module_name) == 0) {
return rdf_writer_for_rdfjson(stream, content_type, charset, base_uri);
}
#endif
#ifndef DISABLE_TRIX
if (std::strcmp("trix", format->module_name) == 0) {
return rdf_writer_for_trix(stream, content_type, charset, base_uri);
}
#endif
#ifndef DISABLE_XSLT
if (std::strcmp("xslt", format->module_name) == 0) {
return rdf_writer_for_xslt(stream, content_type, charset, base_uri);
}
#endif
(void)stream, (void)charset, (void)base_uri;
return std::abort(), nullptr; /* never reached */
}
writer::writer(const std::string& file_path,
const std::string& content_type,
const std::string& charset,
const std::string& base_uri)
: _implementation(nullptr) {
assert(false && "file paths not supported yet"); // TODO
(void)file_path, (void)content_type, (void)charset, (void)base_uri; // TODO
}
writer::writer(std::ostream& stream,
const std::string& content_type,
const std::string& charset,
const std::string& base_uri)
: _implementation(nullptr) {
assert(false && "std::ostream not supported yet"); // TODO
(void)stream, (void)content_type, (void)charset, (void)base_uri; // TODO
}
writer::writer(FILE* const stream,
const std::string& content_type,
const std::string& charset,
const std::string& base_uri)
: _implementation(rdf_writer_for(stream, content_type.c_str(), charset.c_str(), base_uri.c_str())) {
if (!_implementation) {
throw std::invalid_argument("unknown content type: " + content_type);
}
}
writer::~writer() noexcept = default;
writer::writer(writer&&) /*noexcept*/ = default;
writer&
writer::operator=(writer&&) /*noexcept*/ = default;
void
writer::configure(const char* const key,
const char* const value) {
assert(_implementation);
assert(key != nullptr); // FIXME
_implementation->configure(key, value);
}
void
writer::define_prefix(const char* prefix,
const char* uri_string) {
assert(_implementation);
_implementation->define_prefix(prefix, uri_string);
}
void
writer::begin() {
assert(_implementation);
_implementation->begin();
}
void
writer::finish() {
assert(_implementation);
_implementation->finish();
}
void
writer::flush() {
assert(_implementation);
_implementation->flush();
}
void
writer::write_triple(const triple& triple) {
assert(_implementation);
_implementation->write_triple(triple);
}
void
writer::write_quad(const quad& quad) {
assert(_implementation);
_implementation->write_quad(quad);
}
void
writer::write_comment(const char* const comment) {
assert(_implementation);
_implementation->write_comment(comment);
}
<|endoftext|>
|
<commit_before>#include "scene_view.h"
#include "core/crc32.h"
#include "core/input_system.h"
#include "core/path.h"
#include "core/profiler.h"
#include "core/resource_manager.h"
#include "core/string.h"
#include "editor/gizmo.h"
#include "editor/imgui/imgui.h"
#include "editor/log_ui.h"
#include "editor/platform_interface.h"
#include "editor/settings.h"
#include "engine/engine.h"
#include "engine/plugin_manager.h"
#include "renderer/frame_buffer.h"
#include "renderer/pipeline.h"
#include "renderer/render_scene.h"
#include "renderer/renderer.h"
SceneView::SceneView()
{
m_pipeline = nullptr;
m_editor = nullptr;
m_camera_speed = 0.1f;
m_is_mouse_captured = false;
m_show_stats = false;
m_log_ui = nullptr;
}
SceneView::~SceneView()
{
}
void SceneView::setWireframe(bool wireframe)
{
m_pipeline->setWireframe(wireframe);
}
void SceneView::setScene(Lumix::RenderScene* scene)
{
m_pipeline->setScene(scene);
}
void SceneView::shutdown()
{
m_editor->universeCreated().unbind<SceneView, &SceneView::onUniverseCreated>(this);
m_editor->universeDestroyed().unbind<SceneView, &SceneView::onUniverseDestroyed>(this);
Lumix::Pipeline::destroy(m_pipeline);
m_pipeline = nullptr;
}
void SceneView::onUniverseCreated()
{
auto* scene = m_editor->getScene(Lumix::crc32("renderer"));
m_pipeline->setScene(static_cast<Lumix::RenderScene*>(scene));
}
void SceneView::onUniverseDestroyed()
{
m_pipeline->setScene(nullptr);
}
bool SceneView::init(LogUI& log_ui, Lumix::WorldEditor& editor, Lumix::Array<Action*>& actions)
{
m_log_ui = &log_ui;
m_editor = &editor;
auto& engine = editor.getEngine();
auto& allocator = engine.getAllocator();
auto* renderer = static_cast<Lumix::Renderer*>(engine.getPluginManager().getPlugin("renderer"));
Lumix::Path path("pipelines/main.lua");
m_pipeline = Lumix::Pipeline::create(*renderer, path, engine.getAllocator());
m_pipeline->load();
m_pipeline->addCustomCommandHandler("renderGizmos")
.callback.bind<SceneView, &SceneView::renderGizmos>(this);
m_pipeline->addCustomCommandHandler("renderIcons")
.callback.bind<SceneView, &SceneView::renderIcons>(this);
editor.universeCreated().bind<SceneView, &SceneView::onUniverseCreated>(this);
editor.universeDestroyed().bind<SceneView, &SceneView::onUniverseDestroyed>(this);
onUniverseCreated();
m_toggle_gizmo_step_action =
LUMIX_NEW(editor.getAllocator(), Action)("Enable/disable gizmo step", "toggleGizmoStep");
m_toggle_gizmo_step_action->is_global = false;
actions.push(m_toggle_gizmo_step_action);
return true;
}
void SceneView::update()
{
PROFILE_FUNCTION();
if (ImGui::IsAnyItemActive()) return;
if (!m_is_opened) return;
if (ImGui::GetIO().KeyCtrl) return;
m_camera_speed =
Lumix::Math::maximum(0.01f, m_camera_speed + ImGui::GetIO().MouseWheel / 20.0f);
int screen_x = int(ImGui::GetIO().MousePos.x);
int screen_y = int(ImGui::GetIO().MousePos.y);
bool is_inside = screen_x >= m_screen_x && screen_y >= m_screen_y &&
screen_x <= m_screen_x + m_width && screen_y <= m_screen_y + m_height;
if (!is_inside) return;
float speed = m_camera_speed;
if (ImGui::GetIO().KeyShift)
{
speed *= 10;
}
if (ImGui::GetIO().KeysDown['W'])
{
m_editor->navigate(1.0f, 0, speed);
}
if (ImGui::GetIO().KeysDown['S'])
{
m_editor->navigate(-1.0f, 0, speed);
}
if (ImGui::GetIO().KeysDown['A'])
{
m_editor->navigate(0.0f, -1.0f, speed);
}
if (ImGui::GetIO().KeysDown['D'])
{
m_editor->navigate(0.0f, 1.0f, speed);
}
}
void SceneView::renderIcons()
{
m_editor->renderIcons();
}
void SceneView::renderGizmos()
{
m_editor->getGizmo().render();
}
void SceneView::captureMouse(bool capture)
{
if(m_is_mouse_captured == capture) return;
m_is_mouse_captured = capture;
PlatformInterface::showCursor(!m_is_mouse_captured);
if(!m_is_mouse_captured) PlatformInterface::unclipCursor();
}
void SceneView::onGUI()
{
PROFILE_FUNCTION();
m_is_opened = false;
ImVec2 view_pos;
const char* title = "Scene View###Scene View";
if (m_log_ui && m_log_ui->getUnreadErrorCount() > 0)
{
title = "Scene View | errors in log###Scene View";
}
if (ImGui::BeginDock(title))
{
m_is_opened = true;
auto size = ImGui::GetContentRegionAvail();
size.y -= ImGui::GetTextLineHeightWithSpacing();
auto* fb = m_pipeline->getFramebuffer("default");
if (size.x > 0 && size.y > 0 && fb)
{
auto pos = ImGui::GetWindowPos();
m_pipeline->setViewport(0, 0, int(size.x), int(size.y));
m_texture_handle = fb->getRenderbufferHandle(0);
auto cursor_pos = ImGui::GetCursorScreenPos();
m_screen_x = int(cursor_pos.x);
m_screen_y = int(cursor_pos.y);
m_width = int(size.x);
m_height = int(size.y);
auto content_min = ImGui::GetCursorScreenPos();
ImVec2 content_max(content_min.x + size.x, content_min.y + size.y);
ImGui::Image(&m_texture_handle, size);
view_pos = content_min;
if (ImGui::IsItemHovered())
{
m_editor->getGizmo().enableStep(m_toggle_gizmo_step_action->isActive());
auto rel_mp = ImGui::GetMousePos();
rel_mp.x -= m_screen_x;
rel_mp.y -= m_screen_y;
for (int i = 0; i < 3; ++i)
{
if (ImGui::IsMouseClicked(i))
{
ImGui::ResetActiveID();
captureMouse(true);
m_editor->onMouseDown((int)rel_mp.x, (int)rel_mp.y, (Lumix::MouseButton::Value)i);
}
auto& input = m_editor->getEngine().getInputSystem();
auto delta = Lumix::Vec2(input.getMouseXMove(), input.getMouseYMove());
if(delta.x != 0 || delta.y != 0)
{
m_editor->onMouseMove((int)rel_mp.x, (int)rel_mp.y, (int)delta.x, (int)delta.y);
}
}
}
for (int i = 0; i < 3; ++i)
{
auto rel_mp = ImGui::GetMousePos();
rel_mp.x -= m_screen_x;
rel_mp.y -= m_screen_y;
if (ImGui::IsMouseReleased(i))
{
captureMouse(false);
m_editor->onMouseUp((int)rel_mp.x, (int)rel_mp.y, (Lumix::MouseButton::Value)i);
}
}
if(m_is_mouse_captured)
{
PlatformInterface::clipCursor(
content_min.x, content_min.y, content_max.x, content_max.y);
}
m_pipeline->render();
}
ImGui::PushItemWidth(60);
ImGui::DragFloat("Camera speed", &m_camera_speed, 0.1f, 0.01f, 999.0f, "%.2f");
ImGui::SameLine();
if (m_editor->isMeasureToolActive())
{
ImGui::Text("| Measured distance: %f", m_editor->getMeasuredDistance());
}
ImGui::SameLine();
int step = m_editor->getGizmo().getStep();
if (ImGui::DragInt("Gizmo step", &step, 1.0f, 0, 200))
{
m_editor->getGizmo().setStep(step);
}
ImGui::SameLine();
ImGui::Checkbox("Stats", &m_show_stats);
ImGui::SameLine();
}
ImGui::EndDock();
if(m_show_stats)
{
view_pos.x += ImGui::GetStyle().FramePadding.x;
view_pos.y += ImGui::GetStyle().FramePadding.y;
ImGui::SetNextWindowPos(view_pos);
auto col = ImGui::GetStyle().Colors[ImGuiCol_WindowBg];
col.w = 0.3f;
ImGui::PushStyleColor(ImGuiCol_WindowBg, col);
if (ImGui::Begin("###stats_overlay",
nullptr,
ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_AlwaysAutoResize |
ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings |
ImGuiWindowFlags_ShowBorders))
{
const auto& stats = m_pipeline->getStats();
ImGui::LabelText("Draw calls", "%d", stats.m_draw_call_count);
ImGui::LabelText("Instances", "%d", stats.m_instance_count);
char buf[30];
Lumix::toCStringPretty(stats.m_triangle_count, buf, Lumix::lengthOf(buf));
ImGui::LabelText("Triangles", buf);
}
ImGui::End();
ImGui::PopStyleColor();
}
}<commit_msg>improved mouse handling in the Scene View - closes #763<commit_after>#include "scene_view.h"
#include "core/crc32.h"
#include "core/input_system.h"
#include "core/path.h"
#include "core/profiler.h"
#include "core/resource_manager.h"
#include "core/string.h"
#include "editor/gizmo.h"
#include "editor/imgui/imgui.h"
#include "editor/log_ui.h"
#include "editor/platform_interface.h"
#include "editor/settings.h"
#include "engine/engine.h"
#include "engine/plugin_manager.h"
#include "renderer/frame_buffer.h"
#include "renderer/pipeline.h"
#include "renderer/render_scene.h"
#include "renderer/renderer.h"
SceneView::SceneView()
{
m_pipeline = nullptr;
m_editor = nullptr;
m_camera_speed = 0.1f;
m_is_mouse_captured = false;
m_show_stats = false;
m_log_ui = nullptr;
}
SceneView::~SceneView()
{
}
void SceneView::setWireframe(bool wireframe)
{
m_pipeline->setWireframe(wireframe);
}
void SceneView::setScene(Lumix::RenderScene* scene)
{
m_pipeline->setScene(scene);
}
void SceneView::shutdown()
{
m_editor->universeCreated().unbind<SceneView, &SceneView::onUniverseCreated>(this);
m_editor->universeDestroyed().unbind<SceneView, &SceneView::onUniverseDestroyed>(this);
Lumix::Pipeline::destroy(m_pipeline);
m_pipeline = nullptr;
}
void SceneView::onUniverseCreated()
{
auto* scene = m_editor->getScene(Lumix::crc32("renderer"));
m_pipeline->setScene(static_cast<Lumix::RenderScene*>(scene));
}
void SceneView::onUniverseDestroyed()
{
m_pipeline->setScene(nullptr);
}
bool SceneView::init(LogUI& log_ui, Lumix::WorldEditor& editor, Lumix::Array<Action*>& actions)
{
m_log_ui = &log_ui;
m_editor = &editor;
auto& engine = editor.getEngine();
auto& allocator = engine.getAllocator();
auto* renderer = static_cast<Lumix::Renderer*>(engine.getPluginManager().getPlugin("renderer"));
Lumix::Path path("pipelines/main.lua");
m_pipeline = Lumix::Pipeline::create(*renderer, path, engine.getAllocator());
m_pipeline->load();
m_pipeline->addCustomCommandHandler("renderGizmos")
.callback.bind<SceneView, &SceneView::renderGizmos>(this);
m_pipeline->addCustomCommandHandler("renderIcons")
.callback.bind<SceneView, &SceneView::renderIcons>(this);
editor.universeCreated().bind<SceneView, &SceneView::onUniverseCreated>(this);
editor.universeDestroyed().bind<SceneView, &SceneView::onUniverseDestroyed>(this);
onUniverseCreated();
m_toggle_gizmo_step_action =
LUMIX_NEW(editor.getAllocator(), Action)("Enable/disable gizmo step", "toggleGizmoStep");
m_toggle_gizmo_step_action->is_global = false;
actions.push(m_toggle_gizmo_step_action);
return true;
}
void SceneView::update()
{
PROFILE_FUNCTION();
if (ImGui::IsAnyItemActive()) return;
if (!m_is_opened) return;
if (ImGui::GetIO().KeyCtrl) return;
m_camera_speed =
Lumix::Math::maximum(0.01f, m_camera_speed + ImGui::GetIO().MouseWheel / 20.0f);
int screen_x = int(ImGui::GetIO().MousePos.x);
int screen_y = int(ImGui::GetIO().MousePos.y);
bool is_inside = screen_x >= m_screen_x && screen_y >= m_screen_y &&
screen_x <= m_screen_x + m_width && screen_y <= m_screen_y + m_height;
if (!is_inside) return;
float speed = m_camera_speed;
if (ImGui::GetIO().KeyShift)
{
speed *= 10;
}
if (ImGui::GetIO().KeysDown['W'])
{
m_editor->navigate(1.0f, 0, speed);
}
if (ImGui::GetIO().KeysDown['S'])
{
m_editor->navigate(-1.0f, 0, speed);
}
if (ImGui::GetIO().KeysDown['A'])
{
m_editor->navigate(0.0f, -1.0f, speed);
}
if (ImGui::GetIO().KeysDown['D'])
{
m_editor->navigate(0.0f, 1.0f, speed);
}
}
void SceneView::renderIcons()
{
m_editor->renderIcons();
}
void SceneView::renderGizmos()
{
m_editor->getGizmo().render();
}
void SceneView::captureMouse(bool capture)
{
if(m_is_mouse_captured == capture) return;
m_is_mouse_captured = capture;
PlatformInterface::showCursor(!m_is_mouse_captured);
if(!m_is_mouse_captured) PlatformInterface::unclipCursor();
}
void SceneView::onGUI()
{
PROFILE_FUNCTION();
m_is_opened = false;
ImVec2 view_pos;
const char* title = "Scene View###Scene View";
if (m_log_ui && m_log_ui->getUnreadErrorCount() > 0)
{
title = "Scene View | errors in log###Scene View";
}
if (ImGui::BeginDock(title))
{
m_is_opened = true;
auto size = ImGui::GetContentRegionAvail();
size.y -= ImGui::GetTextLineHeightWithSpacing();
auto* fb = m_pipeline->getFramebuffer("default");
if (size.x > 0 && size.y > 0 && fb)
{
auto pos = ImGui::GetWindowPos();
m_pipeline->setViewport(0, 0, int(size.x), int(size.y));
m_texture_handle = fb->getRenderbufferHandle(0);
auto cursor_pos = ImGui::GetCursorScreenPos();
m_screen_x = int(cursor_pos.x);
m_screen_y = int(cursor_pos.y);
m_width = int(size.x);
m_height = int(size.y);
auto content_min = ImGui::GetCursorScreenPos();
ImVec2 content_max(content_min.x + size.x, content_min.y + size.y);
ImGui::Image(&m_texture_handle, size);
view_pos = content_min;
auto rel_mp = ImGui::GetMousePos();
rel_mp.x -= m_screen_x;
rel_mp.y -= m_screen_y;
if (ImGui::IsItemHovered())
{
m_editor->getGizmo().enableStep(m_toggle_gizmo_step_action->isActive());
for (int i = 0; i < 3; ++i)
{
if (ImGui::IsMouseClicked(i))
{
ImGui::ResetActiveID();
captureMouse(true);
m_editor->onMouseDown((int)rel_mp.x, (int)rel_mp.y, (Lumix::MouseButton::Value)i);
break;
}
}
}
if (m_is_mouse_captured || ImGui::IsItemHovered())
{
auto& input = m_editor->getEngine().getInputSystem();
auto delta = Lumix::Vec2(input.getMouseXMove(), input.getMouseYMove());
if (delta.x != 0 || delta.y != 0)
{
m_editor->onMouseMove((int)rel_mp.x, (int)rel_mp.y, (int)delta.x, (int)delta.y);
}
}
if(m_is_mouse_captured)
{
PlatformInterface::clipCursor(
content_min.x, content_min.y, content_max.x, content_max.y);
for (int i = 0; i < 3; ++i)
{
auto rel_mp = ImGui::GetMousePos();
rel_mp.x -= m_screen_x;
rel_mp.y -= m_screen_y;
if (ImGui::IsMouseReleased(i))
{
captureMouse(false);
m_editor->onMouseUp((int)rel_mp.x, (int)rel_mp.y, (Lumix::MouseButton::Value)i);
}
}
}
m_pipeline->render();
}
ImGui::PushItemWidth(60);
ImGui::DragFloat("Camera speed", &m_camera_speed, 0.1f, 0.01f, 999.0f, "%.2f");
ImGui::SameLine();
if (m_editor->isMeasureToolActive())
{
ImGui::Text("| Measured distance: %f", m_editor->getMeasuredDistance());
}
ImGui::SameLine();
int step = m_editor->getGizmo().getStep();
if (ImGui::DragInt("Gizmo step", &step, 1.0f, 0, 200))
{
m_editor->getGizmo().setStep(step);
}
ImGui::SameLine();
ImGui::Checkbox("Stats", &m_show_stats);
ImGui::SameLine();
}
ImGui::EndDock();
if(m_show_stats)
{
view_pos.x += ImGui::GetStyle().FramePadding.x;
view_pos.y += ImGui::GetStyle().FramePadding.y;
ImGui::SetNextWindowPos(view_pos);
auto col = ImGui::GetStyle().Colors[ImGuiCol_WindowBg];
col.w = 0.3f;
ImGui::PushStyleColor(ImGuiCol_WindowBg, col);
if (ImGui::Begin("###stats_overlay",
nullptr,
ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_AlwaysAutoResize |
ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings |
ImGuiWindowFlags_ShowBorders))
{
const auto& stats = m_pipeline->getStats();
ImGui::LabelText("Draw calls", "%d", stats.m_draw_call_count);
ImGui::LabelText("Instances", "%d", stats.m_instance_count);
char buf[30];
Lumix::toCStringPretty(stats.m_triangle_count, buf, Lumix::lengthOf(buf));
ImGui::LabelText("Triangles", buf);
}
ImGui::End();
ImGui::PopStyleColor();
}
}<|endoftext|>
|
<commit_before>/* Joystick_Plugin - for licensing and copyright see license.txt */
#include "StdAfx.h"
#include "Nodes/G2FlowBaseNode.h"
//#include <IScriptSystem.h>
//#include <ScriptHelpers.h>
#include <CPluginJoystick.h>
namespace JoystickPlugin
{
HRESULT PollJoystick( DIJOYSTATE2* js, LPDIRECTINPUTDEVICE8 joystick );
class CFlowJoystickNode :
public CFlowBaseNode<eNCT_Instanced>,
public CScriptableBase
{
private:
SActivationInfo m_actInfo;
int* m_buttons;
int m_xAxis;
int m_yAxis;
int m_zAxis;
int m_xRotate;
int m_yRotate;
int m_zRotate;
int m_slider;
int m_POV;
bool m_bEnabled;
LPDIRECTINPUTDEVICE8 m_currentJoystick;
DIDEVCAPS m_CurrentCapabilities;
public:
CFlowJoystickNode( SActivationInfo* pActInfo )
{
#ifndef SDK_VERSION_343
Init( gEnv->pSystem->GetIScriptSystem(), gEnv->pSystem );
#else
Init( gEnv->pSystem->GetIScriptSystem() );
#endif
SetGlobalName( "Joystick" );
#undef SCRIPT_REG_CLASSNAME
#define SCRIPT_REG_CLASSNAME &CFlowJoystickNode::
SCRIPT_REG_TEMPLFUNC( GetXAxis, "" );
SCRIPT_REG_TEMPLFUNC( GetYAxis, "" );
SCRIPT_REG_TEMPLFUNC( GetZAxis, "" );
SCRIPT_REG_TEMPLFUNC( GetButtonState, "button" );
SCRIPT_REG_TEMPLFUNC( SetJoystick, "joystick" );
SCRIPT_REG_TEMPLFUNC( GetNumButtons, "" );
SCRIPT_REG_TEMPLFUNC( GetPOV, "" );
SCRIPT_REG_TEMPLFUNC( GetSlider, "" );
SCRIPT_REG_TEMPLFUNC( GetXRotate, "" );
SCRIPT_REG_TEMPLFUNC( GetYRotate, "" );
SCRIPT_REG_TEMPLFUNC( GetZRotate, "" );
#undef SCRIPT_REG_CLASSNAME
m_xAxis = 0;
m_yAxis = 0;
m_zAxis = 0;
m_xRotate = 0;
m_yRotate = 0;
m_zRotate = 0;
m_slider = 0;
m_POV = 0;
m_buttons = NULL;
m_currentJoystick = NULL;
m_bEnabled = true;
}
~CFlowJoystickNode()
{
SAFE_DELETE( m_buttons );
if ( m_currentJoystick )
{
m_currentJoystick->Unacquire();
}
}
int CFlowJoystickNode::GetButtonState( IFunctionHandler* pH, int button )
{
if ( !m_buttons || button > m_CurrentCapabilities.dwButtons || button < 1 )
{
return pH->EndFunction();
}
return pH->EndFunction( m_buttons[button - 1] );
}
int CFlowJoystickNode::GetNumButtons( IFunctionHandler* pH )
{
return pH->EndFunction( ( int )m_CurrentCapabilities.dwButtons );
}
int CFlowJoystickNode::SetJoystick( IFunctionHandler* pH, int joystick )
{
if ( joystick > g_joysticks.size() || joystick < 1 )
{
SetNewJoystick( 1 );
return pH->EndFunction();
}
SetNewJoystick( joystick );
return pH->EndFunction();
}
int CFlowJoystickNode::GetXAxis( IFunctionHandler* pH )
{
return pH->EndFunction( m_xAxis );
}
int CFlowJoystickNode::GetYAxis( IFunctionHandler* pH )
{
return pH->EndFunction( m_yAxis );
}
int CFlowJoystickNode::GetZAxis( IFunctionHandler* pH )
{
return pH->EndFunction( m_zAxis );
}
int CFlowJoystickNode::GetXRotate( IFunctionHandler* pH )
{
return pH->EndFunction( m_xRotate );
}
int CFlowJoystickNode::GetYRotate( IFunctionHandler* pH )
{
return pH->EndFunction( m_yRotate );
}
int CFlowJoystickNode::GetZRotate( IFunctionHandler* pH )
{
return pH->EndFunction( m_zRotate );
}
int CFlowJoystickNode::GetPOV( IFunctionHandler* pH )
{
return pH->EndFunction( m_POV );
}
int CFlowJoystickNode::GetSlider( IFunctionHandler* pH )
{
return pH->EndFunction( m_slider );
}
IFlowNodePtr Clone( SActivationInfo* pActInfo )
{
return new CFlowJoystickNode( pActInfo );
}
virtual void GetMemoryUsage( ICrySizer* s ) const
{
s->Add( *this );
}
void Serialize( SActivationInfo* pActInfo, TSerialize ser )
{
if ( ser.IsReading() )
{
m_actInfo = *pActInfo;
}
}
enum EInputPorts
{
EIP_Enabled = 0,
EIP_JoystickSelection
};
enum EOutputPorts
{
EOP_JoystickX = 0,
EOP_JoystickY,
EOP_JoystickZ,
EOP_JoystickRotateX,
EOP_JoystickRotateY,
EOP_JoystickRotateZ,
EOP_Slider,
EOP_POV,
EOP_ButtonPressed,
EOP_ButtonReleased
};
virtual void GetConfiguration( SFlowNodeConfig& config )
{
string joysticks = "enum_string:";
int i = 1;
for ( TJoysticks::const_iterator sit = g_joysticks.begin(); sit != g_joysticks.end(); ++sit )
{
char buffer[32];
itoa( i, buffer, 10 );
joysticks.append( "Joystick" );
joysticks.append( buffer );
joysticks.append( "=" );
joysticks.append( buffer );
joysticks.append( "," );
i++;
}
static const SInputPortConfig inputs[] =
{
InputPortConfig<bool>( "Enabled", true, _HELP( "Enables/Disables the joystick" ) ),
InputPortConfig<string>( "Joystick", "1", _HELP( "Select a joystick" ), "Joystick", _UICONFIG( joysticks ) ),
{0}
};
static const SOutputPortConfig outputs[] =
{
OutputPortConfig<int>( "X", _HELP( "X-axis, usually the left-right movement of a stick." ) ),
OutputPortConfig<int>( "Y", _HELP( "Y-axis, usually the forward-backward movement of a stick." ) ),
OutputPortConfig<int>( "Z", _HELP( "Z-axis, often the throttle control. If the joystick does not have this axis, the value is 0." ) ),
OutputPortConfig<int>( "X-Rotate", _HELP( "X-axis rotation. If the joystick does not have this axis, the value is 0." ) ),
OutputPortConfig<int>( "Y-Rotate", _HELP( "Y-axis rotation. If the joystick does not have this axis, the value is 0." ) ),
OutputPortConfig<int>( "Z-Rotate", _HELP( "Z-axis rotation (often called the rudder). If the joystick does not have this axis, the value is 0." ) ),
OutputPortConfig<int>( "Slider", _HELP( "Two additional axis values (formerly called the u-axis and v-axis) whose semantics depend on the joystick." ) ),
OutputPortConfig<int>( "POV", _HELP( "Direction controllers, such as point-of-view hats. The position is indicated in hundredths of a degree clockwise from north (away from the user). The center position is normally reported as - 1. For indicators that have only five positions, the value for a controller is - 1, 0, 9,000, 18,000, or 27,000." ) ),
OutputPortConfig<int>( "ButtonPressed", _HELP( "Joystick button pressed" ) ),
OutputPortConfig<int>( "ButtonReleased", _HELP( "Joystick button released" ) ),
{0}
};
config.pInputPorts = inputs;
config.pOutputPorts = outputs;
config.sDescription = _HELP( "Joystick infos" );
config.SetCategory( EFLN_APPROVED );
}
void SetNewJoystick( int joystick )
{
if ( joystick == 0 )
{
joystick = 1;
}
TJoysticks::iterator iter = g_joysticks.begin();
if ( joystick == 1 && g_joysticks.size() == 1 )
{
m_currentJoystick = iter->first;
m_CurrentCapabilities.dwSize = sizeof( DIDEVCAPS );
m_CurrentCapabilities = iter->second;
SAFE_DELETE( m_buttons );
m_buttons = new int[m_CurrentCapabilities.dwButtons];
}
else if ( g_joysticks.size() > 1 )
{
TJoysticks::iterator end = g_joysticks.end();
int i = 2;
++iter;
for ( ; iter != end; ++iter )
{
if ( i == joystick )
{
break;
}
i++;
}
m_currentJoystick = iter->first;
m_CurrentCapabilities.dwSize = sizeof( DIDEVCAPS );
m_CurrentCapabilities = iter->second;
SAFE_DELETE( m_buttons );
m_buttons = new int[m_CurrentCapabilities.dwButtons];
}
}
virtual void ProcessEvent( EFlowEvent event, SActivationInfo* pActInfo )
{
switch ( event )
{
case eFE_Initialize:
{
m_actInfo = *pActInfo;
m_bEnabled = true;
pActInfo->pGraph->SetRegularlyUpdated( pActInfo->myID, true );
SetNewJoystick( atoi( GetPortString( &m_actInfo, EIP_JoystickSelection ) ) );
break;
}
case eFE_Activate:
{
if ( IsPortActive( pActInfo, EIP_Enabled ) )
{
m_bEnabled = GetPortBool( pActInfo, EIP_Enabled );
}
else if ( IsPortActive( pActInfo, EIP_JoystickSelection ) )
{
SetNewJoystick( atoi( GetPortString( &m_actInfo, EIP_JoystickSelection ) ) );
}
break;
}
case eFE_Update:
{
if ( m_currentJoystick == NULL || m_buttons == NULL || !m_bEnabled )
{
return;
}
DIJOYSTATE2 js;
if ( PollJoystick( &js, m_currentJoystick ) == DI_OK )
{
m_xAxis = static_cast<int>( js.lX );
m_yAxis = static_cast<int>( js.lY );
m_zAxis = static_cast<int>( js.lZ );
m_xRotate = static_cast<int>( js.lRx );
m_yRotate = static_cast<int>( js.lRy );
m_zRotate = static_cast<int>( js.lRz );
m_slider = static_cast<int>( js.rglSlider[0] );
m_POV = static_cast<int>( js.rgdwPOV[0] );
ActivateOutput( pActInfo, EOP_JoystickX, m_xAxis );
ActivateOutput( pActInfo, EOP_JoystickY, m_yAxis );
ActivateOutput( pActInfo, EOP_JoystickZ, m_zAxis );
ActivateOutput( pActInfo, EOP_JoystickRotateX, m_xRotate );
ActivateOutput( pActInfo, EOP_JoystickRotateY, m_yRotate );
ActivateOutput( pActInfo, EOP_JoystickRotateZ, m_zRotate );
ActivateOutput( pActInfo, EOP_Slider, m_slider );
ActivateOutput( pActInfo, EOP_POV, m_POV );
for ( int i = 0; i < m_CurrentCapabilities.dwButtons; i++ )
{
BYTE button = js.rgbButtons[i];
if ( button & 0x80 )
{
if ( m_buttons[i] != 1 )
{
m_buttons[i] = 1;
}
ActivateOutput( pActInfo, EOP_ButtonPressed, i + 1 );
}
else
{
if ( m_buttons[i] == 1 )
{
m_buttons[i] = 0;
ActivateOutput( pActInfo, EOP_ButtonReleased, i + 1 );
}
}
}
}
break;
}
}
}
virtual void GetMemoryStatistics( ICrySizer* s )
{
s->Add( *this );
}
};
}
REGISTER_FLOW_NODE_EX( "Plugin_Joystick:Input", JoystickPlugin::CFlowJoystickNode, CFlowJoystickNode );<commit_msg>new 344 cdk version syntax<commit_after>/* Joystick_Plugin - for licensing and copyright see license.txt */
#include "StdAfx.h"
#include "Nodes/G2FlowBaseNode.h"
//#include <IScriptSystem.h>
//#include <ScriptHelpers.h>
#include <CPluginJoystick.h>
namespace JoystickPlugin
{
HRESULT PollJoystick( DIJOYSTATE2* js, LPDIRECTINPUTDEVICE8 joystick );
class CFlowJoystickNode :
public CFlowBaseNode<eNCT_Instanced>,
public CScriptableBase
{
private:
SActivationInfo m_actInfo;
int* m_buttons;
int m_xAxis;
int m_yAxis;
int m_zAxis;
int m_xRotate;
int m_yRotate;
int m_zRotate;
int m_slider;
int m_POV;
bool m_bEnabled;
LPDIRECTINPUTDEVICE8 m_currentJoystick;
DIDEVCAPS m_CurrentCapabilities;
public:
CFlowJoystickNode( SActivationInfo* pActInfo )
{
#if CDK_VERSION < 343
Init( gEnv->pSystem->GetIScriptSystem(), gEnv->pSystem );
#else
Init( gEnv->pSystem->GetIScriptSystem() );
#endif
SetGlobalName( "Joystick" );
#undef SCRIPT_REG_CLASSNAME
#define SCRIPT_REG_CLASSNAME &CFlowJoystickNode::
SCRIPT_REG_TEMPLFUNC( GetXAxis, "" );
SCRIPT_REG_TEMPLFUNC( GetYAxis, "" );
SCRIPT_REG_TEMPLFUNC( GetZAxis, "" );
SCRIPT_REG_TEMPLFUNC( GetButtonState, "button" );
SCRIPT_REG_TEMPLFUNC( SetJoystick, "joystick" );
SCRIPT_REG_TEMPLFUNC( GetNumButtons, "" );
SCRIPT_REG_TEMPLFUNC( GetPOV, "" );
SCRIPT_REG_TEMPLFUNC( GetSlider, "" );
SCRIPT_REG_TEMPLFUNC( GetXRotate, "" );
SCRIPT_REG_TEMPLFUNC( GetYRotate, "" );
SCRIPT_REG_TEMPLFUNC( GetZRotate, "" );
#undef SCRIPT_REG_CLASSNAME
m_xAxis = 0;
m_yAxis = 0;
m_zAxis = 0;
m_xRotate = 0;
m_yRotate = 0;
m_zRotate = 0;
m_slider = 0;
m_POV = 0;
m_buttons = NULL;
m_currentJoystick = NULL;
m_bEnabled = true;
}
~CFlowJoystickNode()
{
SAFE_DELETE( m_buttons );
if ( m_currentJoystick )
{
m_currentJoystick->Unacquire();
}
}
int CFlowJoystickNode::GetButtonState( IFunctionHandler* pH, int button )
{
if ( !m_buttons || button > m_CurrentCapabilities.dwButtons || button < 1 )
{
return pH->EndFunction();
}
return pH->EndFunction( m_buttons[button - 1] );
}
int CFlowJoystickNode::GetNumButtons( IFunctionHandler* pH )
{
return pH->EndFunction( ( int )m_CurrentCapabilities.dwButtons );
}
int CFlowJoystickNode::SetJoystick( IFunctionHandler* pH, int joystick )
{
if ( joystick > g_joysticks.size() || joystick < 1 )
{
SetNewJoystick( 1 );
return pH->EndFunction();
}
SetNewJoystick( joystick );
return pH->EndFunction();
}
int CFlowJoystickNode::GetXAxis( IFunctionHandler* pH )
{
return pH->EndFunction( m_xAxis );
}
int CFlowJoystickNode::GetYAxis( IFunctionHandler* pH )
{
return pH->EndFunction( m_yAxis );
}
int CFlowJoystickNode::GetZAxis( IFunctionHandler* pH )
{
return pH->EndFunction( m_zAxis );
}
int CFlowJoystickNode::GetXRotate( IFunctionHandler* pH )
{
return pH->EndFunction( m_xRotate );
}
int CFlowJoystickNode::GetYRotate( IFunctionHandler* pH )
{
return pH->EndFunction( m_yRotate );
}
int CFlowJoystickNode::GetZRotate( IFunctionHandler* pH )
{
return pH->EndFunction( m_zRotate );
}
int CFlowJoystickNode::GetPOV( IFunctionHandler* pH )
{
return pH->EndFunction( m_POV );
}
int CFlowJoystickNode::GetSlider( IFunctionHandler* pH )
{
return pH->EndFunction( m_slider );
}
IFlowNodePtr Clone( SActivationInfo* pActInfo )
{
return new CFlowJoystickNode( pActInfo );
}
virtual void GetMemoryUsage( ICrySizer* s ) const
{
s->Add( *this );
}
void Serialize( SActivationInfo* pActInfo, TSerialize ser )
{
if ( ser.IsReading() )
{
m_actInfo = *pActInfo;
}
}
enum EInputPorts
{
EIP_Enabled = 0,
EIP_JoystickSelection
};
enum EOutputPorts
{
EOP_JoystickX = 0,
EOP_JoystickY,
EOP_JoystickZ,
EOP_JoystickRotateX,
EOP_JoystickRotateY,
EOP_JoystickRotateZ,
EOP_Slider,
EOP_POV,
EOP_ButtonPressed,
EOP_ButtonReleased
};
virtual void GetConfiguration( SFlowNodeConfig& config )
{
string joysticks = "enum_string:";
int i = 1;
for ( TJoysticks::const_iterator sit = g_joysticks.begin(); sit != g_joysticks.end(); ++sit )
{
char buffer[32];
itoa( i, buffer, 10 );
joysticks.append( "Joystick" );
joysticks.append( buffer );
joysticks.append( "=" );
joysticks.append( buffer );
joysticks.append( "," );
i++;
}
static const SInputPortConfig inputs[] =
{
InputPortConfig<bool>( "Enabled", true, _HELP( "Enables/Disables the joystick" ) ),
InputPortConfig<string>( "Joystick", "1", _HELP( "Select a joystick" ), "Joystick", _UICONFIG( joysticks ) ),
{0}
};
static const SOutputPortConfig outputs[] =
{
OutputPortConfig<int>( "X", _HELP( "X-axis, usually the left-right movement of a stick." ) ),
OutputPortConfig<int>( "Y", _HELP( "Y-axis, usually the forward-backward movement of a stick." ) ),
OutputPortConfig<int>( "Z", _HELP( "Z-axis, often the throttle control. If the joystick does not have this axis, the value is 0." ) ),
OutputPortConfig<int>( "X-Rotate", _HELP( "X-axis rotation. If the joystick does not have this axis, the value is 0." ) ),
OutputPortConfig<int>( "Y-Rotate", _HELP( "Y-axis rotation. If the joystick does not have this axis, the value is 0." ) ),
OutputPortConfig<int>( "Z-Rotate", _HELP( "Z-axis rotation (often called the rudder). If the joystick does not have this axis, the value is 0." ) ),
OutputPortConfig<int>( "Slider", _HELP( "Two additional axis values (formerly called the u-axis and v-axis) whose semantics depend on the joystick." ) ),
OutputPortConfig<int>( "POV", _HELP( "Direction controllers, such as point-of-view hats. The position is indicated in hundredths of a degree clockwise from north (away from the user). The center position is normally reported as - 1. For indicators that have only five positions, the value for a controller is - 1, 0, 9,000, 18,000, or 27,000." ) ),
OutputPortConfig<int>( "ButtonPressed", _HELP( "Joystick button pressed" ) ),
OutputPortConfig<int>( "ButtonReleased", _HELP( "Joystick button released" ) ),
{0}
};
config.pInputPorts = inputs;
config.pOutputPorts = outputs;
config.sDescription = _HELP( "Joystick infos" );
config.SetCategory( EFLN_APPROVED );
}
void SetNewJoystick( int joystick )
{
if ( joystick == 0 )
{
joystick = 1;
}
TJoysticks::iterator iter = g_joysticks.begin();
if ( joystick == 1 && g_joysticks.size() == 1 )
{
m_currentJoystick = iter->first;
m_CurrentCapabilities.dwSize = sizeof( DIDEVCAPS );
m_CurrentCapabilities = iter->second;
SAFE_DELETE( m_buttons );
m_buttons = new int[m_CurrentCapabilities.dwButtons];
}
else if ( g_joysticks.size() > 1 )
{
TJoysticks::iterator end = g_joysticks.end();
int i = 2;
++iter;
for ( ; iter != end; ++iter )
{
if ( i == joystick )
{
break;
}
i++;
}
m_currentJoystick = iter->first;
m_CurrentCapabilities.dwSize = sizeof( DIDEVCAPS );
m_CurrentCapabilities = iter->second;
SAFE_DELETE( m_buttons );
m_buttons = new int[m_CurrentCapabilities.dwButtons];
}
}
virtual void ProcessEvent( EFlowEvent event, SActivationInfo* pActInfo )
{
switch ( event )
{
case eFE_Initialize:
{
m_actInfo = *pActInfo;
m_bEnabled = true;
pActInfo->pGraph->SetRegularlyUpdated( pActInfo->myID, true );
SetNewJoystick( atoi( GetPortString( &m_actInfo, EIP_JoystickSelection ) ) );
break;
}
case eFE_Activate:
{
if ( IsPortActive( pActInfo, EIP_Enabled ) )
{
m_bEnabled = GetPortBool( pActInfo, EIP_Enabled );
}
else if ( IsPortActive( pActInfo, EIP_JoystickSelection ) )
{
SetNewJoystick( atoi( GetPortString( &m_actInfo, EIP_JoystickSelection ) ) );
}
break;
}
case eFE_Update:
{
if ( m_currentJoystick == NULL || m_buttons == NULL || !m_bEnabled )
{
return;
}
DIJOYSTATE2 js;
if ( PollJoystick( &js, m_currentJoystick ) == DI_OK )
{
m_xAxis = static_cast<int>( js.lX );
m_yAxis = static_cast<int>( js.lY );
m_zAxis = static_cast<int>( js.lZ );
m_xRotate = static_cast<int>( js.lRx );
m_yRotate = static_cast<int>( js.lRy );
m_zRotate = static_cast<int>( js.lRz );
m_slider = static_cast<int>( js.rglSlider[0] );
m_POV = static_cast<int>( js.rgdwPOV[0] );
ActivateOutput( pActInfo, EOP_JoystickX, m_xAxis );
ActivateOutput( pActInfo, EOP_JoystickY, m_yAxis );
ActivateOutput( pActInfo, EOP_JoystickZ, m_zAxis );
ActivateOutput( pActInfo, EOP_JoystickRotateX, m_xRotate );
ActivateOutput( pActInfo, EOP_JoystickRotateY, m_yRotate );
ActivateOutput( pActInfo, EOP_JoystickRotateZ, m_zRotate );
ActivateOutput( pActInfo, EOP_Slider, m_slider );
ActivateOutput( pActInfo, EOP_POV, m_POV );
for ( int i = 0; i < m_CurrentCapabilities.dwButtons; i++ )
{
BYTE button = js.rgbButtons[i];
if ( button & 0x80 )
{
if ( m_buttons[i] != 1 )
{
m_buttons[i] = 1;
}
ActivateOutput( pActInfo, EOP_ButtonPressed, i + 1 );
}
else
{
if ( m_buttons[i] == 1 )
{
m_buttons[i] = 0;
ActivateOutput( pActInfo, EOP_ButtonReleased, i + 1 );
}
}
}
}
break;
}
}
}
virtual void GetMemoryStatistics( ICrySizer* s )
{
s->Add( *this );
}
};
}
REGISTER_FLOW_NODE_EX( "Plugin_Joystick:Input", JoystickPlugin::CFlowJoystickNode, CFlowJoystickNode );<|endoftext|>
|
<commit_before>//-----------------------------------------------------------------------------
// File: list.cpp
//
// Class: list
// Functions: main
//-----------------------------------------------------------------------------
#include "list.h"
using namespace std;
namespace NP_ADT
{
//-------------------------------------------------------------------------
// constructor
//-------------------------------------------------------------------------
template<class datatype>
CDLL<datatype>::CDLL(size_t n_elements, datatype datum)
:m_size(0), handle(nullptr)
{
if (n_elements <= 0)
throw out_of_range("Empty list");
for (size_t i = 0; i < n_elements; i++)
push_front(datum);
}
//-------------------------------------------------------------------------
// copy constructor
//-------------------------------------------------------------------------
template<typename datatype>
NP_ADT::CDLL<datatype>::CDLL(const CDLL<datatype> & cdll)
: m_size(0), handle(nullptr)
{
CDLL::iterator r_it = cdll.begin();
while (r_it != nullptr)
push_front(*r_it++);
}
//-------------------------------------------------------------------------
// insert element at front of list
//-------------------------------------------------------------------------
template<typename datatype>
void CDLL<datatype>::push_front(datatype datum)
{
node * temp = new node(datum, nullptr, nullptr);
if (m_size++ == 0)
{
temp->next = temp;
temp->prev = temp;
}
else {
node * before = handle->prev;
temp->next = handle;
handle->prev = temp;
temp->prev = before;
before->next = temp;
}
handle = temp;
}
//-------------------------------------------------------------------------
// insert element at end of list
//-------------------------------------------------------------------------
template<typename datatype>
void CDLL<datatype>::push_back(datatype datum)
{
node * temp = new node(datum, nullptr, nullptr);
if (m_size++ == 0)
{
temp->next = temp;
temp->prev = temp;
handle = temp;
}
else {
node * before = handle->prev;
temp->next = handle;
handle->prev = temp;
temp->prev = before;
before->next = temp;
}
}
//-------------------------------------------------------------------------
// removes front element and returns the data from that element
//-------------------------------------------------------------------------
template<typename datatype>
datatype NP_ADT::CDLL<datatype>::pop_front()
{
if (handle == nullptr)
throw runtime_error("Empty list");
datatype poppedData = head()->data;
if (m_size-- == 1) {
handle = nullptr;
}
else {
node * newHead = head()->next;
newHead->prev = head()->prev;
head()->prev->next = newHead;
handle = newHead;
}
return poppedData;
}
//-------------------------------------------------------------------------
// removes back element and returns the data from that element
//-------------------------------------------------------------------------
template<typename datatype>
datatype NP_ADT::CDLL<datatype>::pop_back()
{
if (handle == nullptr)
throw runtime_error("Empty list");
datatype poppedData = tail()->data;
if (m_size-- == 1) {
handle = nullptr;
}
else {
node * newTail = tail()->prev;
newTail->next = tail()->next;
tail()->next->prev = newTail;
}
return poppedData;
}
template<class datatype>
datatype & CDLL<datatype>::front() const
{
if (head() != nullptr)
return head()->data;
else
throw runtime_error("Empty list");
}
template<class datatype>
inline datatype & CDLL<datatype>::back() const
{
if (tail() != nullptr)
return tail()->data;
else
throw runtime_error("Empty list");
}
//-------------------------------------------------------------------------
// constructor using iterators, copies from begin to one before end
//-------------------------------------------------------------------------
/*template<typename datatype>
NP_ADT::CDLL<datatype>::CDLL(iterator begin, iterator end)
:m_size(0), handle(nullptr)
{
while (begin != end)
push_front(*begin++);
}*/
//-----------------------------------------------------------------------------
// empties the list
//-----------------------------------------------------------------------------
/*template<typename datatype>
inline void NP_ADT::CDLL<datatype>::release()
{
while (handle != nullptr)
pop_front();
}*/
//-------------------------------------------------------------------------
// prints out a list
//-------------------------------------------------------------------------
/*template<typename datatype>
const datatype & NP_ADT::CDLL<datatype>::operator[](int index) const
{
CDLL::iterator p = x.begin(); // gets x.h
sout << "(";
while (p != nullptr)
{
sout << *p;
if (p != x.end())
sout << ",";
++p; // advances iterator using next
}
sout << ")\n";
return sout;
}*/
//-------------------------------------------------------------------------
// returns a copy of rlist
//-------------------------------------------------------------------------
/*template<typename datatype>
CDLL<datatype> NP_ADT::CDLL<datatype>::operator=(const CDLL & rlist)
{
if (&rlist != this)
{
CDLL<datatype>::iterator r_it = rlist.begin();
release();
while (r_it != 0)
push_front(*r_it++);
}
return *this;
}*/
//-------------------------------------------------------------------------
// pre-increment
//-------------------------------------------------------------------------
/*template<typename datatype>
inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator++()
{
if (ptr == nullptr)
throw runtime_error("nullptr pointer");
ptr = ptr->next;
return *this;
}*/
//-------------------------------------------------------------------------
// post-increment
//-------------------------------------------------------------------------
/*template<typename datatype>
inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator++(int)
{
if (ptr == nullptr)
throw runtime_error("nullptr pointer");
iterator temp = *this;
ptr = ptr->next;
return temp;
}*/
//-------------------------------------------------------------------------
// pre-decrement
//-------------------------------------------------------------------------
/*template<typename datatype>
inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator--()
{
if (ptr == nullptr)
throw runtime_error("nullptr pointer");
ptr = ptr->prev;
return *this;
}*/
//-------------------------------------------------------------------------
// post-decrement
//-------------------------------------------------------------------------
/*template<typename datatype>
inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator--(int)
{
if (ptr == nullptr)
throw runtime_error("nullptr pointer");
iterator temp = *this;
ptr = ptr->prev;
return temp;
}*/
//-------------------------------------------------------------------------
// [] operator -- l-value
//-------------------------------------------------------------------------
/*template<typename datatype>
datatype & NP_ADT::CDLL<datatype>::operator[](int index)
{
iterator it;
if (index >= 0)
{
if (index >= static_cast<int>(getSize()))
throw out_of_range("index out-of-range");
it = begin();
for (int i = 0; i < index; i++)
it++;
}
else
{
if (index < -(static_cast<int>(getSize())))
throw out_of_range("index out-of-range");
it = end();
for (int i = -1; i > index; i--)
it--;
}
return *it;
}*/
//-------------------------------------------------------------------------
// ostream << overload
//-------------------------------------------------------------------------
//template<typename datatype>
/*template <typename datatype>
ostream & operator << (ostream& sout, const CDLL<datatype> & cdll)
{
return sout;
}*/
} // end namespace NP_ADT
<commit_msg>add comments<commit_after>//-----------------------------------------------------------------------------
// File: list.cpp
//
// Class: list
// Functions: main
//-----------------------------------------------------------------------------
#include "list.h"
using namespace std;
namespace NP_ADT
{
//-------------------------------------------------------------------------
// constructor
//-------------------------------------------------------------------------
template<class datatype>
CDLL<datatype>::CDLL(size_t n_elements, datatype datum)
:m_size(0), handle(nullptr)
{
if (n_elements <= 0)
throw out_of_range("Empty list");
for (size_t i = 0; i < n_elements; i++)
push_front(datum);
}
//-------------------------------------------------------------------------
// copy constructor
//-------------------------------------------------------------------------
template<typename datatype>
NP_ADT::CDLL<datatype>::CDLL(const CDLL<datatype> & cdll)
: m_size(0), handle(nullptr)
{
CDLL::iterator r_it = cdll.begin();
while (r_it != nullptr)
push_front(*r_it++);
}
//-------------------------------------------------------------------------
// insert element at front of list
//-------------------------------------------------------------------------
template<typename datatype>
void CDLL<datatype>::push_front(datatype datum)
{
node * temp = new node(datum, nullptr, nullptr);
if (m_size++ == 0)
{
temp->next = temp;
temp->prev = temp;
}
else {
node * before = handle->prev;
temp->next = handle;
handle->prev = temp;
temp->prev = before;
before->next = temp;
}
handle = temp;
}
//-------------------------------------------------------------------------
// insert element at end of list
//-------------------------------------------------------------------------
template<typename datatype>
void CDLL<datatype>::push_back(datatype datum)
{
node * temp = new node(datum, nullptr, nullptr);
if (m_size++ == 0)
{
temp->next = temp;
temp->prev = temp;
handle = temp;
}
else {
node * before = handle->prev;
temp->next = handle;
handle->prev = temp;
temp->prev = before;
before->next = temp;
}
}
//-------------------------------------------------------------------------
// removes front element and returns the data from that element
//-------------------------------------------------------------------------
template<typename datatype>
datatype NP_ADT::CDLL<datatype>::pop_front()
{
if (handle == nullptr)
throw runtime_error("Empty list");
datatype poppedData = head()->data;
if (m_size-- == 1) {
handle = nullptr;
}
else {
node * newHead = head()->next;
newHead->prev = head()->prev;
head()->prev->next = newHead;
handle = newHead;
}
return poppedData;
}
//-------------------------------------------------------------------------
// removes back element and returns the data from that element
//-------------------------------------------------------------------------
template<typename datatype>
datatype NP_ADT::CDLL<datatype>::pop_back()
{
if (handle == nullptr)
throw runtime_error("Empty list");
datatype poppedData = tail()->data;
if (m_size-- == 1) {
handle = nullptr;
}
else {
node * newTail = tail()->prev;
newTail->next = tail()->next;
tail()->next->prev = newTail;
}
return poppedData;
}
//-------------------------------------------------------------------------
// returns data of the first item
//-------------------------------------------------------------------------
template<class datatype>
datatype & CDLL<datatype>::front() const
{
if (head() != nullptr)
return head()->data;
else
throw runtime_error("Empty list");
}
//-------------------------------------------------------------------------
// returns data of the last item
//-------------------------------------------------------------------------
template<class datatype>
inline datatype & CDLL<datatype>::back() const
{
if (tail() != nullptr)
return tail()->data;
else
throw runtime_error("Empty list");
}
//-------------------------------------------------------------------------
// constructor using iterators, copies from begin to one before end
//-------------------------------------------------------------------------
/*template<typename datatype>
NP_ADT::CDLL<datatype>::CDLL(iterator begin, iterator end)
:m_size(0), handle(nullptr)
{
while (begin != end)
push_front(*begin++);
}*/
//-----------------------------------------------------------------------------
// empties the list
//-----------------------------------------------------------------------------
/*template<typename datatype>
inline void NP_ADT::CDLL<datatype>::release()
{
while (handle != nullptr)
pop_front();
}*/
//-------------------------------------------------------------------------
// prints out a list
//-------------------------------------------------------------------------
/*template<typename datatype>
const datatype & NP_ADT::CDLL<datatype>::operator[](int index) const
{
CDLL::iterator p = x.begin(); // gets x.h
sout << "(";
while (p != nullptr)
{
sout << *p;
if (p != x.end())
sout << ",";
++p; // advances iterator using next
}
sout << ")\n";
return sout;
}*/
//-------------------------------------------------------------------------
// returns a copy of rlist
//-------------------------------------------------------------------------
/*template<typename datatype>
CDLL<datatype> NP_ADT::CDLL<datatype>::operator=(const CDLL & rlist)
{
if (&rlist != this)
{
CDLL<datatype>::iterator r_it = rlist.begin();
release();
while (r_it != 0)
push_front(*r_it++);
}
return *this;
}*/
//-------------------------------------------------------------------------
// pre-increment
//-------------------------------------------------------------------------
/*template<typename datatype>
inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator++()
{
if (ptr == nullptr)
throw runtime_error("nullptr pointer");
ptr = ptr->next;
return *this;
}*/
//-------------------------------------------------------------------------
// post-increment
//-------------------------------------------------------------------------
/*template<typename datatype>
inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator++(int)
{
if (ptr == nullptr)
throw runtime_error("nullptr pointer");
iterator temp = *this;
ptr = ptr->next;
return temp;
}*/
//-------------------------------------------------------------------------
// pre-decrement
//-------------------------------------------------------------------------
/*template<typename datatype>
inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator--()
{
if (ptr == nullptr)
throw runtime_error("nullptr pointer");
ptr = ptr->prev;
return *this;
}*/
//-------------------------------------------------------------------------
// post-decrement
//-------------------------------------------------------------------------
/*template<typename datatype>
inline typename CDLL<datatype>::iterator NP_ADT::CDLL<datatype>::iterator::operator--(int)
{
if (ptr == nullptr)
throw runtime_error("nullptr pointer");
iterator temp = *this;
ptr = ptr->prev;
return temp;
}*/
//-------------------------------------------------------------------------
// [] operator -- l-value
//-------------------------------------------------------------------------
/*template<typename datatype>
datatype & NP_ADT::CDLL<datatype>::operator[](int index)
{
iterator it;
if (index >= 0)
{
if (index >= static_cast<int>(getSize()))
throw out_of_range("index out-of-range");
it = begin();
for (int i = 0; i < index; i++)
it++;
}
else
{
if (index < -(static_cast<int>(getSize())))
throw out_of_range("index out-of-range");
it = end();
for (int i = -1; i > index; i--)
it--;
}
return *it;
}*/
//-------------------------------------------------------------------------
// ostream << overload
//-------------------------------------------------------------------------
//template<typename datatype>
/*template <typename datatype>
ostream & operator << (ostream& sout, const CDLL<datatype> & cdll)
{
return sout;
}*/
} // end namespace NP_ADT
<|endoftext|>
|
<commit_before><commit_msg>Remove temporary output files<commit_after><|endoftext|>
|
<commit_before><commit_msg>Changed the point off of the surface to be calculated to be further off because it ended up thinking it collided with itself.<commit_after><|endoftext|>
|
<commit_before>#include "Renderer.h"
#include <fstream>
Renderer::Renderer()
: m_world(nullptr),m_pixels(std::vector<RGBColor>()) {
}
Renderer::Renderer(World* world, const uint16_t image_width, const uint16_t image_height)
: m_world(world), m_image_width(image_width), m_image_height(image_height), m_pixels(std::vector<RGBColor>(image_width * image_height, RGBColor(BACKGROUND_COLOR))) {
}
Renderer::~Renderer(){
m_world = nullptr;
m_pixels.clear();
}
void Renderer::exportImage(const std::string export_path) const {
const int image_size = m_image_height * m_image_width * 4;
const int headers_size = 14 + 40;
const int filesize = image_size + headers_size;
const int pixelsPerMeter = 2835;
unsigned char bmpfileheader[14] = {'B','M', 0,0,0,0, 0,0,0,0, 54,0,0,0};
//size of the file in bytes
bmpfileheader[ 2] = (unsigned char)(filesize);
bmpfileheader[ 3] = (unsigned char)(filesize>>8);
bmpfileheader[ 4] = (unsigned char)(filesize>>16);
bmpfileheader[ 5] = (unsigned char)(filesize>>24);
unsigned char bmpinfoheader[40] = {40,0,0,0, 0,0,0,0, 0,0,0,0, 1,0,24,0};
//width of the image in bytes
bmpinfoheader[ 4] = (unsigned char)(m_image_width);
bmpinfoheader[ 5] = (unsigned char)(m_image_width>>8);
bmpinfoheader[ 6] = (unsigned char)(m_image_width>>16);
bmpinfoheader[ 7] = (unsigned char)(m_image_width>>24);
//height of the image in bytes
bmpinfoheader[ 8] = (unsigned char)(m_image_height);
bmpinfoheader[ 9] = (unsigned char)(m_image_height>>8);
bmpinfoheader[10] = (unsigned char)(m_image_height>>16);
bmpinfoheader[11] = (unsigned char)(m_image_height>>24);
// Size image in bytes
bmpinfoheader[21] = (unsigned char)(image_size);
bmpinfoheader[22] = (unsigned char)(image_size>>8);
bmpinfoheader[23] = (unsigned char)(image_size>>16);
bmpinfoheader[24] = (unsigned char)(image_size>>24);
bmpinfoheader[25] = (unsigned char)(pixelsPerMeter);
bmpinfoheader[26] = (unsigned char)(pixelsPerMeter>>8);
bmpinfoheader[27] = (unsigned char)(pixelsPerMeter>>16);
bmpinfoheader[28] = (unsigned char)(pixelsPerMeter>>24);
bmpinfoheader[29] = (unsigned char)(pixelsPerMeter);
bmpinfoheader[30] = (unsigned char)(pixelsPerMeter>>8);
bmpinfoheader[31] = (unsigned char)(pixelsPerMeter>>16);
bmpinfoheader[32] = (unsigned char)(pixelsPerMeter>>24);
FILE *file = fopen(export_path.c_str(), "wb");//write-binary
fwrite(bmpfileheader,1,14, file);
fwrite(bmpinfoheader,1,40, file);
for (int i = 0; i < m_pixels.size(); ++i){
const RGBColor pixel = m_pixels[i];
unsigned char color[3] = {
(int) (pixel.b * 255),
(int) (pixel.g * 255),
(int) (pixel.r * 255)
};
fwrite(color, 1, 3, file);
}
fclose(file);
}
<commit_msg>Removed unnecessary copy constructor call<commit_after>#include "Renderer.h"
#include <fstream>
Renderer::Renderer()
: m_world(nullptr),m_pixels(std::vector<RGBColor>()) {
}
Renderer::Renderer(World* world, const uint16_t image_width, const uint16_t image_height)
: m_world(world), m_image_width(image_width), m_image_height(image_height), m_pixels(std::vector<RGBColor>(image_width * image_height, BACKGROUND_COLOR)) {
}
Renderer::~Renderer(){
m_world = nullptr;
m_pixels.clear();
}
void Renderer::exportImage(const std::string export_path) const {
const int image_size = m_image_height * m_image_width * 4;
const int headers_size = 14 + 40;
const int filesize = image_size + headers_size;
const int pixelsPerMeter = 2835;
unsigned char bmpfileheader[14] = {'B','M', 0,0,0,0, 0,0,0,0, 54,0,0,0};
//size of the file in bytes
bmpfileheader[ 2] = (unsigned char)(filesize);
bmpfileheader[ 3] = (unsigned char)(filesize>>8);
bmpfileheader[ 4] = (unsigned char)(filesize>>16);
bmpfileheader[ 5] = (unsigned char)(filesize>>24);
unsigned char bmpinfoheader[40] = {40,0,0,0, 0,0,0,0, 0,0,0,0, 1,0,24,0};
//width of the image in bytes
bmpinfoheader[ 4] = (unsigned char)(m_image_width);
bmpinfoheader[ 5] = (unsigned char)(m_image_width>>8);
bmpinfoheader[ 6] = (unsigned char)(m_image_width>>16);
bmpinfoheader[ 7] = (unsigned char)(m_image_width>>24);
//height of the image in bytes
bmpinfoheader[ 8] = (unsigned char)(m_image_height);
bmpinfoheader[ 9] = (unsigned char)(m_image_height>>8);
bmpinfoheader[10] = (unsigned char)(m_image_height>>16);
bmpinfoheader[11] = (unsigned char)(m_image_height>>24);
// Size image in bytes
bmpinfoheader[21] = (unsigned char)(image_size);
bmpinfoheader[22] = (unsigned char)(image_size>>8);
bmpinfoheader[23] = (unsigned char)(image_size>>16);
bmpinfoheader[24] = (unsigned char)(image_size>>24);
bmpinfoheader[25] = (unsigned char)(pixelsPerMeter);
bmpinfoheader[26] = (unsigned char)(pixelsPerMeter>>8);
bmpinfoheader[27] = (unsigned char)(pixelsPerMeter>>16);
bmpinfoheader[28] = (unsigned char)(pixelsPerMeter>>24);
bmpinfoheader[29] = (unsigned char)(pixelsPerMeter);
bmpinfoheader[30] = (unsigned char)(pixelsPerMeter>>8);
bmpinfoheader[31] = (unsigned char)(pixelsPerMeter>>16);
bmpinfoheader[32] = (unsigned char)(pixelsPerMeter>>24);
FILE *file = fopen(export_path.c_str(), "wb");//write-binary
fwrite(bmpfileheader,1,14, file);
fwrite(bmpinfoheader,1,40, file);
for (int i = 0; i < m_pixels.size(); ++i){
const RGBColor pixel = m_pixels[i];
unsigned char color[3] = {
(int) (pixel.b * 255),
(int) (pixel.g * 255),
(int) (pixel.r * 255)
};
fwrite(color, 1, 3, file);
}
fclose(file);
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2013 Aggregate
*
* 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 "pch.h"
#include "handlers.h"
#include "crypt.hpp"
#if DEBUG_CGI
#ifdef _WIN32
#define SEP ';'
#else
#define SEP ':'
extern char ** environ;
#endif
namespace app
{
class DebugPageHandler: public PageHandler
{
std::string m_service_url;
public:
struct DebugRequestState: FastCGI::RequestState
{
long long m_contentSize;
char* m_buffer;
DebugRequestState()
: m_contentSize(0)
, m_buffer(nullptr)
{}
~DebugRequestState()
{
free(m_buffer);
}
bool alloc(long long size)
{
free(m_buffer);
m_buffer = (char*)malloc((size_t)size);
m_contentSize = m_buffer ? size : 0;
return m_buffer != nullptr;
}
};
std::string name() const
{
return "DEBUG_CGI";
}
static void penv(FastCGI::Request& request, const char * const * envp)
{
request << "<table class='env'>\n";
request << "<thead><tr><th>Name</th><th>Value</th></tr><thead><tbody>\n";
size_t counter = 0;
for ( ; *envp; ++envp)
{
const char* eq = strchr(*envp, '=');
request << "<tr";
if (counter++ % 2)
request << " class='even'";
request << "><td>";
if (eq == *envp) request << " ";
else if (eq == NULL) request << *envp;
else request << std::string(*envp, eq);
request << "</td><td>";
if (eq == NULL) request << " ";
else if (strncmp("PATH=", *envp, 5))
request << eq + 1;
else
{
const char* prev = eq + 1;
const char* c = eq + 1;
while (*c != 0)
{
while (*c != 0 && *c != SEP) ++c;
request << std::string(prev, c);
if (*c != 0) request << "<br/>\n";
if (*c != 0) ++c;
prev = c;
}
}
request << "</td></tr>\n";
}
request << "</table>\n";
}
static void handlers(FastCGI::Request& request,
HandlerMap::const_iterator begin,
HandlerMap::const_iterator end)
{
request << "<table class='handlers'>\n";
request << "<thead><tr><th>URL</th><th>Action</th><th>File</th></tr><thead><tbody>\n";
size_t counter = 0;
for ( ; begin != end; ++begin)
{
request << "<tr";
if (counter++ % 2)
request << " class='even'";
request
<< "><td><nobr><a href='" << begin->first << "'>" << begin->first << "</a></nobr></td>"
<< "<td><nobr>" << begin->second.ptr->name() << "</nobr></td><td>" << begin->second.file << ":"
<< begin->second.line << "</td></tr>\n";
}
request << "</tbody></table>\n";
}
static void requests(FastCGI::Request& request, const FastCGI::Application::ReqList& list)
{
request << "<table class='requests'>\n";
request << "<thead><tr><th>URL</th><th>Remote Addr</th><th>Time (GMT)</th></tr><thead><tbody>\n";
auto _cur = list.begin(), _end = list.end();
size_t counter = 0;
for ( ; _cur != _end; ++_cur)
{
if (_cur->resource == "/debug/?all")
continue;
tyme::tm_t gmt = tyme::gmtime(_cur->now);
char timebuf[100];
tyme::strftime(timebuf, "%a, %d-%b-%Y %H:%M:%S GMT", gmt );
request << "<tr";
if (counter++ % 2)
request << " class='even'";
request
<< "><td><nobr><a href='http://" << _cur->server << _cur->resource << "'>" << _cur->resource << "</a></nobr></td>"
<< "<td><nobr>" << _cur->remote_addr << ":" << _cur->remote_port << "</nobr></td><td>" << timebuf << "</td></tr>\n";
}
request << "</tbody></table>\n";
}
static void cookies(FastCGI::Request& request, const std::map<std::string, std::string>& list)
{
request << "<table class='cookies'>\n";
request << "<thead><tr><th>Name</th><th>Value</th></tr><thead><tbody>\n";
auto _cur = list.begin(), _end = list.end();
size_t counter = 0;
for ( ; _cur != _end; ++_cur)
{
request << "<tr";
if (counter++ % 2)
request << " class='even'";
request
<< "><td><nobr>" << _cur->first << "</nobr></td>"
<< "<td>" << _cur->second << "</td></tr>\n";
}
request << "</tbody></table>\n";
}
bool restrictedPage() { return false; }
const char* getPageTitle(PageTranslation& tr) { return "Debug"; }
void prerender(FastCGI::SessionPtr session, Request& request, PageTranslation& tr)
{
crypt::session_t hash;
crypt::session("reader.login", hash);
request.setCookie("cookie-test", hash, tyme::now() + 86400*60);
long long content_size = request.calcStreamSize();
if (content_size > -1)
{
DebugRequestState* state = new (std::nothrow) DebugRequestState();
if (state)
{
if (state->alloc(content_size))
request.read(state->m_buffer, state->m_contentSize);
request.setRequestState(FastCGI::RequestStatePtr(state));
}
}
}
void render(FastCGI::SessionPtr session, Request& request, PageTranslation& tr)
{
const char* QUERY_STRING = request.getParam("QUERY_STRING");
bool all = (QUERY_STRING != NULL) && (strncmp(QUERY_STRING, "all", 3) == 0);
request << "<style type='text/css'>\n"
"body, td, th { font-family: Helvetica, Arial, sans-serif; font-size: 10pt }\n"
"div#content { width: 650px; margin: 0px auto }\n"
"th, td { text-align: left; vertical-align: top; padding: 0.2em 0.5em }\n"
".even td { background: #ddd }\n"
"th { font-weight: normal; color: white; background: #444; }\n"
"table { width: auto; max-width: 650px }\n"
"</style>\n"
"<title>Debug page</title>\n<div id='content'>\n"
"<h1>Debug page</h1>\n"
"<h2>Table of Contents</h2>\n"
"<ol>\n";
if (all) request <<
"<li><a href='#request'>Environment</a></li>\n"
;
request <<
"<li><a href='#handlers'>Page Handlers</a></li>\n"
"<li><a href='#requests'>Requests</a></li>\n"
"<li><a href='#variables'>Variables</a></li>\n"
"<li><a href='#cookies'>Cookies</a></li>\n"
"<li><a href='#session'>Session</a></li>\n"
"</ol>\n"
"<h2>PID: <em>" << request.app().pid() << "</em></h2>\n"
"<h2>Request Number: <em>" << request.app().requs().size() << "</em></h2>\n";
FastCGI::RequestStatePtr statePtr = request.getRequestState();
DebugRequestState* state = static_cast<DebugRequestState*>(statePtr.get());
if (state && state->m_contentSize > 0)
{
request << "<h2>Data: <em>" << state->m_contentSize << "</em></h2>\n<pre>";
for (long long i = 0; i < state->m_contentSize; i++)
request << state->m_buffer[i];
request << "</pre>\n";
}
if (all) {
request << "<h2 class='head'><a name='request'></a>Environment</h2>\n";
penv(request, request.envp());
}
request << "<h2 class='head'><a name='handlers'></a>Page Handlers</h2>\n";
handlers(request, app::Handlers::begin(), app::Handlers::end());
request << "<h2 class='head'><a name='requests'></a>Requests</h2>\n";
requests(request, request.app().requs());
request << "<h2 class='variables'><a name='variables'></a>Variables</h2>\n";
cookies(request, request.varDebugData());
request << "<h2 class='head'><a name='cookies'></a>Cookies</h2>\n";
cookies(request, request.cookieDebugData());
request << "<h2 class='head'><a name='session'></a>Session</h2>\n";
if (session.get())
{
char time[100];
tyme::strftime(time, "%a, %d-%b-%Y %H:%M:%S GMT", tyme::gmtime(session->getStartTime()));
request
<< "<p>Current user: <a href=\"" << session->getEmail() << "\">" << session->getName() << "<br/>\n"
<< "The session has started on " << time << ".</p>";
}
else
{
request << "<p>There is no session in progress currently.</p>\n";
}
}
};
}
REGISTER_HANDLER("/debug/", app::DebugPageHandler);
REGISTER_REDIRECT("/debug", "/debug/");
#endif
<commit_msg>Cleanup of the debug page<commit_after>/*
* Copyright (C) 2013 Aggregate
*
* 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 "pch.h"
#include "handlers.h"
#include "crypt.hpp"
#if DEBUG_CGI
#ifdef _WIN32
#define SEP ';'
#else
#define SEP ':'
extern char ** environ;
#endif
namespace app
{
class DebugPageHandler: public PageHandler
{
std::string m_service_url;
public:
struct DebugRequestState: FastCGI::RequestState
{
long long m_contentSize;
long long m_read;
char* m_buffer;
DebugRequestState()
: m_contentSize(0)
, m_read(0)
, m_buffer(nullptr)
{}
~DebugRequestState()
{
free(m_buffer);
}
bool alloc(long long size)
{
free(m_buffer);
m_buffer = (char*)malloc((size_t)size);
m_contentSize = m_buffer ? size : 0;
m_read = 0;
return m_buffer != nullptr;
}
};
std::string name() const
{
return "DEBUG_CGI";
}
static void penv(FastCGI::Request& request, const char * const * envp)
{
request << "<table class='env'>\n";
request << "<thead><tr><th>Name</th><th>Value</th></tr><thead><tbody>\n";
size_t counter = 0;
for ( ; *envp; ++envp)
{
const char* eq = strchr(*envp, '=');
request << "<tr";
if (counter++ % 2)
request << " class='even'";
request << "><td>";
if (eq == *envp) request << " ";
else if (eq == NULL) request << *envp;
else request << std::string(*envp, eq);
request << "</td><td>";
if (eq == NULL) request << " ";
else if (strncmp("PATH=", *envp, 5))
request << eq + 1;
else
{
const char* prev = eq + 1;
const char* c = eq + 1;
while (*c != 0)
{
while (*c != 0 && *c != SEP) ++c;
request << std::string(prev, c);
if (*c != 0) request << "<br/>\n";
if (*c != 0) ++c;
prev = c;
}
}
request << "</td></tr>\n";
}
request << "</table>\n";
}
static void handlers(FastCGI::Request& request,
HandlerMap::const_iterator begin,
HandlerMap::const_iterator end)
{
request << "<table class='handlers'>\n";
request << "<thead><tr><th>URL</th><th>Action</th><th>File</th></tr><thead><tbody>\n";
size_t counter = 0;
for ( ; begin != end; ++begin)
{
request << "<tr";
if (counter++ % 2)
request << " class='even'";
request
<< "><td><nobr><a href='" << begin->first << "'>" << begin->first << "</a></nobr></td>"
<< "<td><nobr>" << begin->second.ptr->name() << "</nobr></td><td>" << begin->second.file << ":"
<< begin->second.line << "</td></tr>\n";
}
request << "</tbody></table>\n";
}
static void requests(FastCGI::Request& request, const FastCGI::Application::ReqList& list)
{
request << "<table class='requests'>\n";
request << "<thead><tr><th>URL</th><th>Remote Addr</th><th>Time (GMT)</th></tr><thead><tbody>\n";
auto _cur = list.begin(), _end = list.end();
size_t counter = 0;
for ( ; _cur != _end; ++_cur)
{
if (_cur->resource == "/debug/?all")
continue;
tyme::tm_t gmt = tyme::gmtime(_cur->now);
char timebuf[100];
tyme::strftime(timebuf, "%a, %d-%b-%Y %H:%M:%S GMT", gmt );
request << "<tr";
if (counter++ % 2)
request << " class='even'";
request
<< "><td><nobr><a href='http://" << _cur->server << _cur->resource << "'>" << _cur->resource << "</a></nobr></td>"
<< "<td><nobr>" << _cur->remote_addr << ":" << _cur->remote_port << "</nobr></td><td>" << timebuf << "</td></tr>\n";
}
request << "</tbody></table>\n";
}
static void cookies(FastCGI::Request& request, const std::map<std::string, std::string>& list)
{
request << "<table class='cookies'>\n";
request << "<thead><tr><th>Name</th><th>Value</th></tr><thead><tbody>\n";
auto _cur = list.begin(), _end = list.end();
size_t counter = 0;
for ( ; _cur != _end; ++_cur)
{
request << "<tr";
if (counter++ % 2)
request << " class='even'";
request
<< "><td><nobr>" << _cur->first << "</nobr></td>"
<< "<td>" << _cur->second << "</td></tr>\n";
}
request << "</tbody></table>\n";
}
bool restrictedPage() { return false; }
const char* getPageTitle(PageTranslation& tr) { return "Debug"; }
void prerender(FastCGI::SessionPtr session, Request& request, PageTranslation& tr)
{
crypt::session_t hash;
crypt::session("reader.login", hash);
request.setCookie("cookie-test", hash, tyme::now() + 86400*60);
long long content_size = request.calcStreamSize();
if (content_size > -1)
{
DebugRequestState* state = new (std::nothrow) DebugRequestState();
if (state)
{
if (state->alloc(content_size))
state->m_read = request.read(state->m_buffer, state->m_contentSize);
request.setRequestState(FastCGI::RequestStatePtr(state));
}
}
}
void render(FastCGI::SessionPtr session, Request& request, PageTranslation& tr)
{
bool all = request.getVariable("all") != NULL;
request << "<style type='text/css'>\n"
"body, td, th { font-family: Helvetica, Arial, sans-serif; font-size: 10pt }\n"
"div#content { width: 650px; margin: 0px auto }\n"
"th, td { text-align: left; vertical-align: top; padding: 0.2em 0.5em }\n"
".even td { background: #ddd }\n"
"th { font-weight: normal; color: white; background: #444; }\n"
"table { width: auto; max-width: 650px }\n"
"</style>\n"
"<title>Debug page</title>\n<div id='content'>\n"
"<h1>Debug page</h1>\n"
"<h2>Table of Contents</h2>\n"
"<ol>\n";
if (all) request <<
"<li><a href='#request'>Environment</a></li>\n"
;
request <<
"<li><a href='#handlers'>Page Handlers</a></li>\n"
"<li><a href='#requests'>Requests</a></li>\n"
"<li><a href='#variables'>Variables</a></li>\n"
"<li><a href='#cookies'>Cookies</a></li>\n"
"<li><a href='#session'>Session</a></li>\n"
"</ol>\n"
"<h2>PID: <em>" << request.app().pid() << "</em></h2>\n"
"<h2>Request Number: <em>" << request.app().requs().size() << "</em></h2>\n";
FastCGI::RequestStatePtr statePtr = request.getRequestState();
DebugRequestState* state = static_cast<DebugRequestState*>(statePtr.get());
if (state && state->m_contentSize > 0)
{
request << "<h2>Data: <em>" << state->m_contentSize;
if (state->m_contentSize != state->m_read)
request << " (" << state->m_contentSize - state->m_read << " read)";
request << "</em></h2>\n<pre>";
for (long long i = 0; i < state->m_read; i++)
request << state->m_buffer[i];
request << "</pre>\n";
}
if (all) {
request << "<h2 class='head'><a name='request'></a>Environment</h2>\n";
penv(request, request.envp());
}
request << "<h2 class='head'><a name='handlers'></a>Page Handlers</h2>\n";
handlers(request, app::Handlers::begin(), app::Handlers::end());
request << "<h2 class='head'><a name='requests'></a>Requests</h2>\n";
requests(request, request.app().requs());
request << "<h2 class='variables'><a name='variables'></a>Variables</h2>\n";
cookies(request, request.varDebugData());
request << "<h2 class='head'><a name='cookies'></a>Cookies</h2>\n";
cookies(request, request.cookieDebugData());
request << "<h2 class='head'><a name='session'></a>Session</h2>\n";
if (session.get())
{
char time[100];
tyme::strftime(time, "%a, %d-%b-%Y %H:%M:%S GMT", tyme::gmtime(session->getStartTime()));
request
<< "<p>Current user: <a href=\"" << session->getEmail() << "\">" << session->getName() << "<br/>\n"
<< "The session has started on " << time << ".</p>";
}
else
{
request << "<p>There is no session in progress currently.</p>\n";
}
}
};
}
REGISTER_HANDLER("/debug/", app::DebugPageHandler);
REGISTER_REDIRECT("/debug", "/debug/");
#endif
<|endoftext|>
|
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2008 Ulrich von Zadow
//
// 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
//
// Current versions can be found at www.libavg.de
//
#include "OGLProgram.h"
#include "../base/Logger.h"
#include "../base/Exception.h"
#include "boost/tuple/tuple.hpp"
#include "boost/tuple/tuple_comparison.hpp"
#include <map>
#include <iostream>
namespace avg {
using namespace std;
typedef boost::tuple<OGLShaderPtr, OGLShaderPtr> ShaderPair;
typedef map<ShaderPair, OGLProgramPtr> ProgramCacheType;
static ProgramCacheType ProgramCache;
void OGLProgram::flushCache()
{
ProgramCache.clear();
}
OGLProgramPtr OGLProgram::buildProgram(OGLShaderPtr fragmentShader)
{
return OGLProgram::buildProgram( fragmentShader, OGLShaderPtr());
}
OGLProgramPtr OGLProgram::buildProgram(OGLShaderPtr fragmentShader, OGLShaderPtr vertexShader)
{
ProgramCacheType::iterator pos;
OGLProgramPtr prog;
pos = ProgramCache.find( ShaderPair(fragmentShader,vertexShader) );
if (pos != ProgramCache.end()){
//Found it!
prog = pos->second;
} else {
prog = OGLProgramPtr(new OGLProgram(fragmentShader, vertexShader));
ProgramCache[ShaderPair(fragmentShader, vertexShader)] = prog;
//cerr<<"Build Shader Program: "<<fragmentShader<<", "<<vertexShader<<endl;
}
return prog;
}
void OGLProgram::attachAndLink()
{
int count = 0;
for(vector<OGLShaderPtr>::iterator it=m_vShaders.begin(); it!=m_vShaders.end(); ++it) {
if (*it) {
glproc::AttachObject(m_hProgram, (*it)->getGLHandle());
++count;
}
}
if (count == 0) {
//No Programs ...
m_hProgram = 0;
return;
}
glproc::LinkProgram(m_hProgram);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "OGLProgram::OGLProgram: glLinkProgram()");
GLint bLinked;
glproc::GetObjectParameteriv(m_hProgram, GL_OBJECT_LINK_STATUS_ARB, &bLinked);
dumpInfoLog(m_hProgram);
if (!bLinked) {
throw(Exception(AVG_ERR_VIDEO_GENERAL,"Linking shader programs failed. Aborting."));
}
}
OGLProgram::OGLProgram(OGLShaderPtr pFragmentShader)
{
m_hProgram = glproc::CreateProgramObject();
m_vShaders.push_back(pFragmentShader);
attachAndLink();
}
OGLProgram::OGLProgram(OGLShaderPtr pFragmentShader, OGLShaderPtr pVertexShader)
{
m_hProgram = glproc::CreateProgramObject();
m_vShaders.push_back(pFragmentShader);
m_vShaders.push_back(pVertexShader);
attachAndLink();
}
OGLProgram::OGLProgram(vector<OGLShaderPtr> &vShaders)
{
m_hProgram = glproc::CreateProgramObject();
for(vector<OGLShaderPtr>::iterator it=vShaders.begin(); it!=vShaders.end(); ++it) {
m_vShaders.push_back(*it);
}
attachAndLink();
}
OGLProgram::~OGLProgram()
{
glproc::DeleteProgram(m_hProgram);
//FIXME Deleteing the GLProgram breaks SDLDisplayEngine::render somehow???
}
void OGLProgram::activate()
{
glproc::UseProgramObject(m_hProgram);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "OGLProgram::activate: glUseProgramObject()");
}
void OGLProgram::deactivate()
{
glproc::UseProgramObject(0);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "OGLProgram::deactivate: glUseProgramObject()");
}
GLhandleARB OGLProgram::getProgram()
{
return m_hProgram;
}
void OGLProgram::setUniformIntParam(const std::string& sName, int val)
{
int loc = safeGetUniformLoc(sName);
glproc::Uniform1i(loc, val);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, (string("OGLProgram: glUniform(")+sName+")").c_str());
}
void OGLProgram::setUniformFloatParam(const std::string& sName, float val)
{
int loc = safeGetUniformLoc(sName);
glproc::Uniform1f(loc, val);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, (string("OGLProgram: glUniform(")+sName+")").c_str());
}
void OGLProgram::setUniformFloatArrayParam(const std::string& sName, int count, float* pVal)
{
int loc = safeGetUniformLoc(sName);
glproc::Uniform1fv(loc, count, pVal);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, (string("OGLProgram: glUniform(")+sName+")").c_str());
}
int OGLProgram::safeGetUniformLoc(const std::string& sName)
{
int loc = glproc::GetUniformLocation(m_hProgram, sName.c_str());
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
"OGLProgram::setUniformIntParam: GetUniformLocation()");
return loc;
}
}
<commit_msg>Workaround for windows crash at program end.<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2008 Ulrich von Zadow
//
// 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
//
// Current versions can be found at www.libavg.de
//
#include "OGLProgram.h"
#include "../base/Logger.h"
#include "../base/Exception.h"
#include "boost/tuple/tuple.hpp"
#include "boost/tuple/tuple_comparison.hpp"
#include <map>
#include <iostream>
namespace avg {
using namespace std;
typedef boost::tuple<OGLShaderPtr, OGLShaderPtr> ShaderPair;
typedef map<ShaderPair, OGLProgramPtr> ProgramCacheType;
static ProgramCacheType ProgramCache;
void OGLProgram::flushCache()
{
ProgramCache.clear();
}
OGLProgramPtr OGLProgram::buildProgram(OGLShaderPtr fragmentShader)
{
return OGLProgram::buildProgram( fragmentShader, OGLShaderPtr());
}
OGLProgramPtr OGLProgram::buildProgram(OGLShaderPtr fragmentShader, OGLShaderPtr vertexShader)
{
ProgramCacheType::iterator pos;
OGLProgramPtr prog;
pos = ProgramCache.find( ShaderPair(fragmentShader,vertexShader) );
if (pos != ProgramCache.end()){
//Found it!
prog = pos->second;
} else {
prog = OGLProgramPtr(new OGLProgram(fragmentShader, vertexShader));
ProgramCache[ShaderPair(fragmentShader, vertexShader)] = prog;
//cerr<<"Build Shader Program: "<<fragmentShader<<", "<<vertexShader<<endl;
}
return prog;
}
void OGLProgram::attachAndLink()
{
int count = 0;
for(vector<OGLShaderPtr>::iterator it=m_vShaders.begin(); it!=m_vShaders.end(); ++it) {
if (*it) {
glproc::AttachObject(m_hProgram, (*it)->getGLHandle());
++count;
}
}
if (count == 0) {
//No Programs ...
m_hProgram = 0;
return;
}
glproc::LinkProgram(m_hProgram);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "OGLProgram::OGLProgram: glLinkProgram()");
GLint bLinked;
glproc::GetObjectParameteriv(m_hProgram, GL_OBJECT_LINK_STATUS_ARB, &bLinked);
dumpInfoLog(m_hProgram);
if (!bLinked) {
throw(Exception(AVG_ERR_VIDEO_GENERAL,"Linking shader programs failed. Aborting."));
}
}
OGLProgram::OGLProgram(OGLShaderPtr pFragmentShader)
{
m_hProgram = glproc::CreateProgramObject();
m_vShaders.push_back(pFragmentShader);
attachAndLink();
}
OGLProgram::OGLProgram(OGLShaderPtr pFragmentShader, OGLShaderPtr pVertexShader)
{
m_hProgram = glproc::CreateProgramObject();
m_vShaders.push_back(pFragmentShader);
m_vShaders.push_back(pVertexShader);
attachAndLink();
}
OGLProgram::OGLProgram(vector<OGLShaderPtr> &vShaders)
{
m_hProgram = glproc::CreateProgramObject();
for(vector<OGLShaderPtr>::iterator it=vShaders.begin(); it!=vShaders.end(); ++it) {
m_vShaders.push_back(*it);
}
attachAndLink();
}
OGLProgram::~OGLProgram()
{
//TODO: Fix shader lifetime in GPUXxxFilter.
//glproc::DeleteProgram(m_hProgram);
//FIXME Deleteing the GLProgram breaks SDLDisplayEngine::render somehow???
}
void OGLProgram::activate()
{
glproc::UseProgramObject(m_hProgram);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "OGLProgram::activate: glUseProgramObject()");
}
void OGLProgram::deactivate()
{
glproc::UseProgramObject(0);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, "OGLProgram::deactivate: glUseProgramObject()");
}
GLhandleARB OGLProgram::getProgram()
{
return m_hProgram;
}
void OGLProgram::setUniformIntParam(const std::string& sName, int val)
{
int loc = safeGetUniformLoc(sName);
glproc::Uniform1i(loc, val);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, (string("OGLProgram: glUniform(")+sName+")").c_str());
}
void OGLProgram::setUniformFloatParam(const std::string& sName, float val)
{
int loc = safeGetUniformLoc(sName);
glproc::Uniform1f(loc, val);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, (string("OGLProgram: glUniform(")+sName+")").c_str());
}
void OGLProgram::setUniformFloatArrayParam(const std::string& sName, int count, float* pVal)
{
int loc = safeGetUniformLoc(sName);
glproc::Uniform1fv(loc, count, pVal);
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, (string("OGLProgram: glUniform(")+sName+")").c_str());
}
int OGLProgram::safeGetUniformLoc(const std::string& sName)
{
int loc = glproc::GetUniformLocation(m_hProgram, sName.c_str());
OGLErrorCheck(AVG_ERR_VIDEO_GENERAL,
"OGLProgram::setUniformIntParam: GetUniformLocation()");
return loc;
}
}
<|endoftext|>
|
<commit_before>#include "gui/ng/spritewidget.hpp"
namespace namelessgui
{
RectangularWidget::RectangularWidget(std::string id)
: Widget(id),
sf::RectangleShape(sf::Vector2f())
{
setFillColor(sf::Color(255, 255, 0, 0));
setSize({100, 100});
}
sf::Vector2f RectangularWidget::getSize() const
{
return sf::RectangleShape::getSize();
}
void RectangularWidget::setScale(const sf::Vector2f& factors)
{
sf::RectangleShape::setScale(factors);
}
void RectangularWidget::setScale(float scaleX, float scaleY)
{
sf::RectangleShape::setScale(scaleX, scaleY);
}
sf::Vector2f RectangularWidget::getPosition() const
{
return sf::RectangleShape::getPosition();
}
void RectangularWidget::setPosition(const sf::Vector2f& position)
{
sf::RectangleShape::setPosition(position);
}
void RectangularWidget::render(sf::RenderTarget& target, sf::RenderStates states) const
{
if(_visible)
target.draw(static_cast<sf::RectangleShape>(*this), states);
Widget::render(target, states);
}
void RectangularWidget::setSize(const sf::Vector2f& size)
{
sf::RectangleShape::setSize(size);
}
sf::FloatRect RectangularWidget::getGlobalBounds()
{
return sf::RectangleShape::getGlobalBounds();
}
void RectangularWidget::setTexture(const sf::Texture* texture, bool resetRect)
{
sf::RectangleShape::setTexture(texture, resetRect);
}
} // namespace namelessgui
<commit_msg>Outline no longer accounts to widget area<commit_after>#include "gui/ng/spritewidget.hpp"
namespace namelessgui
{
RectangularWidget::RectangularWidget(std::string id)
: Widget(id),
sf::RectangleShape(sf::Vector2f())
{
setFillColor(sf::Color(255, 255, 0, 0));
setSize({100, 100});
}
sf::Vector2f RectangularWidget::getSize() const
{
return sf::RectangleShape::getSize();
}
void RectangularWidget::setScale(const sf::Vector2f& factors)
{
sf::RectangleShape::setScale(factors);
}
void RectangularWidget::setScale(float scaleX, float scaleY)
{
sf::RectangleShape::setScale(scaleX, scaleY);
}
sf::Vector2f RectangularWidget::getPosition() const
{
return sf::RectangleShape::getPosition();
}
void RectangularWidget::setPosition(const sf::Vector2f& position)
{
sf::RectangleShape::setPosition(position);
}
void RectangularWidget::render(sf::RenderTarget& target, sf::RenderStates states) const
{
if(_visible)
target.draw(static_cast<sf::RectangleShape>(*this), states);
Widget::render(target, states);
}
void RectangularWidget::setSize(const sf::Vector2f& size)
{
sf::RectangleShape::setSize(size);
}
sf::FloatRect RectangularWidget::getGlobalBounds()
{
float outlineThickness = getOutlineThickness();
sf::FloatRect bounds = sf::RectangleShape::getGlobalBounds();
bounds.top += outlineThickness;
bounds.left += outlineThickness;
bounds.height -= 2 * outlineThickness;
bounds.width -= 2 * outlineThickness;
return bounds;
}
void RectangularWidget::setTexture(const sf::Texture* texture, bool resetRect)
{
sf::RectangleShape::setTexture(texture, resetRect);
}
} // namespace namelessgui
<|endoftext|>
|
<commit_before>class Solution {
public:
struct Node;
using NodePtr = shared_ptr<Node>;
struct Node {
int length;
NodePtr parent;
vector<NodePtr> children;
Node(NodePtr p) : length(0), parent(p) {}
Node(int len) : length(len), parent(nullptr) {}
Node(int len, NodePtr p) : length(len), parent(p) {}
};
int lengthLongestPath(string input) {
const char *pb = input.data(), *pe = pb, *end = pb + input.size();
bool isFile = false;
while (pe < end && *pe != '\n' ) {
if (*pe == '.') isFile = true;
++pe;
}
if (isFile) return pe - pb;
NodePtr root = make_shared<Node>(pe - pb);
pb = pe + 1;
vector<NodePtr> files;
NodePtr parent = root;
int level = 1, levelNew;
while (pb < end) {
while (pb < end && *pb == '\t') ++pb;
levelNew = pb - pe - 1;
while (level > levelNew) {
parent = parent->parent;
level -= 1;
}
// child
NodePtr n = make_shared<Node>(parent);
parent->children.push_back(n);
isFile = false;
pe = pb + 1;
while (pe < end && *pe != '\n') {
if (*pe == '.') isFile = true;
++pe;
}
if (isFile) files.push_back(n);
n->length = pe - pb + 1;
// check next level
level += 1;
parent = n;
pb = pe + 1;
}
int len, maxLength = numeric_limits<int>::min();
for (auto& p : files) {
len = p->length;
while (p->parent) {
p = p->parent;
len += p->length;
}
if (maxLength < len) maxLength = len;
}
return maxLength;
}
};
<commit_msg>update solution<commit_after>class Solution {
public:
int lengthLongestPath(string input) {
vector<int> length(1, 0);
bool isFile;
int level, len, maxlen = 0;
for (int i = 0, n = input.size(); i < n; ++i) {
// check level
level = 0;
while (i < n && input[i] == '\t') {
++level;
++i;
}
// check file
len = 0;
isFile = false;
while (i < n && input[i] != '\n') {
if (input[i] == '.') isFile = true;
++len;
++i;
}
// isFile
if (isFile) {
maxlen = max(maxlen, length[level] + len);
} else {
if (level + 1 < length.size()) {
length[level + 1] = length[level] + len + 1;
} else if (level + 1 == length.size()) {
length.push_back(length.back() + len + 1);
} else {
cout << "input error" << endl;
}
}
}
return maxlen;
}
};
<|endoftext|>
|
<commit_before><commit_msg>Localization: fix bug on lossless_map_creator tool (#9928)<commit_after><|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "tablehandles.hxx"
#include <vcl/svapp.hxx>
#include <vcl/outdev.hxx>
#include <vcl/canvastools.hxx>
#include <vcl/hatch.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <basegfx/range/b2drectangle.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <svx/sdr/overlay/overlayobject.hxx>
#include <svx/sdr/overlay/overlaymanager.hxx>
#include <svx/sdrpagewindow.hxx>
#include <svx/sdrpaintwindow.hxx>
#include <svx/svdmrkv.hxx>
#include <svx/svdpagv.hxx>
#include <drawinglayer/primitive2d/polypolygonprimitive2d.hxx>
#include <sdr/overlay/overlayrectangle.hxx>
#include <drawinglayer/primitive2d/hiddengeometryprimitive2d.hxx>
namespace sdr { namespace table {
class OverlayTableEdge : public sdr::overlay::OverlayObject
{
protected:
basegfx::B2DPolyPolygon maPolyPolygon;
bool mbVisible;
// geometry creation for OverlayObject
virtual drawinglayer::primitive2d::Primitive2DSequence createOverlayObjectPrimitive2DSequence() SAL_OVERRIDE;
public:
OverlayTableEdge( const basegfx::B2DPolyPolygon& rPolyPolygon, bool bVisible );
virtual ~OverlayTableEdge();
};
TableEdgeHdl::TableEdgeHdl( const Point& rPnt, bool bHorizontal, sal_Int32 nMin, sal_Int32 nMax, sal_Int32 nEdges )
: SdrHdl( rPnt, HDL_USER )
, mbHorizontal( bHorizontal )
, mnMin( nMin )
, mnMax( nMax )
, maEdges(nEdges)
{
}
void TableEdgeHdl::SetEdge( sal_Int32 nEdge, sal_Int32 nStart, sal_Int32 nEnd, TableEdgeState eState )
{
if( (nEdge >= 0) && (nEdge <= sal::static_int_cast<sal_Int32>(maEdges.size())) )
{
maEdges[nEdge].mnStart = nStart;
maEdges[nEdge].mnEnd = nEnd;
maEdges[nEdge].meState = eState;
}
else
{
OSL_FAIL( "sdr::table::TableEdgeHdl::SetEdge(), invalid edge!" );
}
}
Pointer TableEdgeHdl::GetPointer() const
{
if( mbHorizontal )
return POINTER_VSPLIT;
else
return POINTER_HSPLIT;
}
sal_Int32 TableEdgeHdl::GetValidDragOffset( const SdrDragStat& rDrag ) const
{
return std::min( std::max( static_cast<sal_Int32>(mbHorizontal ? rDrag.GetDY() : rDrag.GetDX()), mnMin ), mnMax );
}
basegfx::B2DPolyPolygon TableEdgeHdl::getSpecialDragPoly(const SdrDragStat& rDrag) const
{
basegfx::B2DPolyPolygon aVisible;
basegfx::B2DPolyPolygon aInvisible;
// create and return visible and non-visible parts for drag
getPolyPolygon(aVisible, aInvisible, &rDrag);
aVisible.append(aInvisible);
return aVisible;
}
void TableEdgeHdl::getPolyPolygon(basegfx::B2DPolyPolygon& rVisible, basegfx::B2DPolyPolygon& rInvisible, const SdrDragStat* pDrag) const
{
// changed method to create visible and invisible partial polygons in one run in
// separate PolyPolygons; both kinds are used
basegfx::B2DPoint aOffset(aPos.X(), aPos.Y());
rVisible.clear();
rInvisible.clear();
if( pDrag )
{
int n = mbHorizontal ? 1 : 0;
aOffset[n] = aOffset[n] + GetValidDragOffset( *pDrag );
}
basegfx::B2DPoint aStart(aOffset), aEnd(aOffset);
int nPos = mbHorizontal ? 0 : 1;
TableEdgeVector::const_iterator aIter( maEdges.begin() );
while( aIter != maEdges.end() )
{
TableEdge aEdge(*aIter++);
aStart[nPos] = aOffset[nPos] + aEdge.mnStart;
aEnd[nPos] = aOffset[nPos] + aEdge.mnEnd;
basegfx::B2DPolygon aPolygon;
aPolygon.append( aStart );
aPolygon.append( aEnd );
if(aEdge.meState == Visible)
{
rVisible.append(aPolygon);
}
else
{
rInvisible.append(aPolygon);
}
}
}
void TableEdgeHdl::CreateB2dIAObject()
{
GetRidOfIAObject();
if(pHdlList && pHdlList->GetView() && !pHdlList->GetView()->areMarkHandlesHidden())
{
SdrMarkView* pView = pHdlList->GetView();
SdrPageView* pPageView = pView->GetSdrPageView();
if(pPageView)
{
basegfx::B2DPolyPolygon aVisible;
basegfx::B2DPolyPolygon aInvisible;
// get visible and invisible parts
getPolyPolygon(aVisible, aInvisible, 0);
if(aVisible.count() || aInvisible.count())
{
for(sal_uInt32 nWindow = 0; nWindow < pPageView->PageWindowCount(); nWindow++)
{
const SdrPageWindow& rPageWindow = *pPageView->GetPageWindow(nWindow);
if(rPageWindow.GetPaintWindow().OutputToWindow())
{
rtl::Reference< ::sdr::overlay::OverlayManager > xManager = rPageWindow.GetOverlayManager();
if (xManager.is())
{
if(aVisible.count())
{
// create overlay object for visible parts
sdr::overlay::OverlayObject* pOverlayObject = new OverlayTableEdge(aVisible, true);
xManager->add(*pOverlayObject);
maOverlayGroup.append(*pOverlayObject);
}
if(aInvisible.count())
{
// also create overlay object vor invisible parts to allow
// a standard HitTest using the primitives from that overlay object
// (see OverlayTableEdge implementation)
sdr::overlay::OverlayObject* pOverlayObject = new OverlayTableEdge(aInvisible, false);
xManager->add(*pOverlayObject);
maOverlayGroup.append(*pOverlayObject);
}
}
}
}
}
}
}
}
OverlayTableEdge::OverlayTableEdge( const basegfx::B2DPolyPolygon& rPolyPolygon, bool bVisible )
: OverlayObject(Color(COL_GRAY))
, maPolyPolygon( rPolyPolygon )
, mbVisible(bVisible)
{
}
OverlayTableEdge::~OverlayTableEdge()
{
}
drawinglayer::primitive2d::Primitive2DSequence OverlayTableEdge::createOverlayObjectPrimitive2DSequence()
{
drawinglayer::primitive2d::Primitive2DSequence aRetval;
if(maPolyPolygon.count())
{
// Discussed with CL. Currently i will leave the transparence out since this
// a little bit expensive. We may check the look with drag polygons later
const drawinglayer::primitive2d::Primitive2DReference aReference(
new drawinglayer::primitive2d::PolyPolygonHairlinePrimitive2D(
maPolyPolygon,
getBaseColor().getBColor()));
if(mbVisible)
{
// visible, just return as sequence
aRetval = drawinglayer::primitive2d::Primitive2DSequence(&aReference, 1);
}
else
{
// embed in HiddenGeometryPrimitive2D to support HitTest of this invisible
// overlay object
const drawinglayer::primitive2d::Primitive2DSequence aSequence(&aReference, 1);
const drawinglayer::primitive2d::Primitive2DReference aNewReference(
new drawinglayer::primitive2d::HiddenGeometryPrimitive2D(aSequence));
aRetval = drawinglayer::primitive2d::Primitive2DSequence(&aNewReference, 1);
}
}
return aRetval;
}
TableBorderHdl::TableBorderHdl(
const Rectangle& rRect,
bool bAnimate)
: SdrHdl(rRect.TopLeft(), HDL_MOVE),
maRectangle(rRect),
mbAnimate(bAnimate)
{
}
Pointer TableBorderHdl::GetPointer() const
{
return POINTER_MOVE;
}
// create marker for this kind
void TableBorderHdl::CreateB2dIAObject()
{
GetRidOfIAObject();
if(pHdlList && pHdlList->GetView() && !pHdlList->GetView()->areMarkHandlesHidden())
{
SdrMarkView* pView = pHdlList->GetView();
SdrPageView* pPageView = pView->GetSdrPageView();
if(pPageView)
{
for(sal_uInt32 nWindow = 0; nWindow < pPageView->PageWindowCount(); nWindow++)
{
const SdrPageWindow& rPageWindow = *pPageView->GetPageWindow(nWindow);
if(rPageWindow.GetPaintWindow().OutputToWindow())
{
rtl::Reference< ::sdr::overlay::OverlayManager > xManager = rPageWindow.GetOverlayManager();
if (xManager.is())
{
const basegfx::B2DRange aRange(vcl::unotools::b2DRectangleFromRectangle(maRectangle));
const SvtOptionsDrawinglayer aSvtOptionsDrawinglayer;
const Color aHilightColor(aSvtOptionsDrawinglayer.getHilightColor());
const double fTransparence(aSvtOptionsDrawinglayer.GetTransparentSelectionPercent() * 0.01);
sdr::overlay::OverlayObject* pOverlayObject = new sdr::overlay::OverlayRectangle(
aRange.getMinimum(),
aRange.getMaximum(),
aHilightColor,
fTransparence,
6.0,
0.0,
0.0,
500,
// make animation dependent from text edit active, because for tables
// this handle is also used when text edit *is* active for it. This
// interferes too much concerning repaint stuff (at least as long as
// text edit is not yet on the overlay)
getAnimate());
xManager->add(*pOverlayObject);
maOverlayGroup.append(*pOverlayObject);
}
}
}
}
}
}
} // end of namespace table
} // end of namespace sdr
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>cleanup tableBorderHdl::CreateB2dIAObject<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "tablehandles.hxx"
#include <vcl/svapp.hxx>
#include <vcl/outdev.hxx>
#include <vcl/canvastools.hxx>
#include <vcl/hatch.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <basegfx/range/b2drectangle.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <svx/sdr/overlay/overlayobject.hxx>
#include <svx/sdr/overlay/overlaymanager.hxx>
#include <svx/sdrpagewindow.hxx>
#include <svx/sdrpaintwindow.hxx>
#include <svx/svdmrkv.hxx>
#include <svx/svdpagv.hxx>
#include <drawinglayer/primitive2d/polypolygonprimitive2d.hxx>
#include <sdr/overlay/overlayrectangle.hxx>
#include <drawinglayer/primitive2d/hiddengeometryprimitive2d.hxx>
namespace sdr { namespace table {
class OverlayTableEdge : public sdr::overlay::OverlayObject
{
protected:
basegfx::B2DPolyPolygon maPolyPolygon;
bool mbVisible;
// geometry creation for OverlayObject
virtual drawinglayer::primitive2d::Primitive2DSequence createOverlayObjectPrimitive2DSequence() SAL_OVERRIDE;
public:
OverlayTableEdge( const basegfx::B2DPolyPolygon& rPolyPolygon, bool bVisible );
virtual ~OverlayTableEdge();
};
TableEdgeHdl::TableEdgeHdl( const Point& rPnt, bool bHorizontal, sal_Int32 nMin, sal_Int32 nMax, sal_Int32 nEdges )
: SdrHdl( rPnt, HDL_USER )
, mbHorizontal( bHorizontal )
, mnMin( nMin )
, mnMax( nMax )
, maEdges(nEdges)
{
}
void TableEdgeHdl::SetEdge( sal_Int32 nEdge, sal_Int32 nStart, sal_Int32 nEnd, TableEdgeState eState )
{
if( (nEdge >= 0) && (nEdge <= sal::static_int_cast<sal_Int32>(maEdges.size())) )
{
maEdges[nEdge].mnStart = nStart;
maEdges[nEdge].mnEnd = nEnd;
maEdges[nEdge].meState = eState;
}
else
{
OSL_FAIL( "sdr::table::TableEdgeHdl::SetEdge(), invalid edge!" );
}
}
Pointer TableEdgeHdl::GetPointer() const
{
if( mbHorizontal )
return POINTER_VSPLIT;
else
return POINTER_HSPLIT;
}
sal_Int32 TableEdgeHdl::GetValidDragOffset( const SdrDragStat& rDrag ) const
{
return std::min( std::max( static_cast<sal_Int32>(mbHorizontal ? rDrag.GetDY() : rDrag.GetDX()), mnMin ), mnMax );
}
basegfx::B2DPolyPolygon TableEdgeHdl::getSpecialDragPoly(const SdrDragStat& rDrag) const
{
basegfx::B2DPolyPolygon aVisible;
basegfx::B2DPolyPolygon aInvisible;
// create and return visible and non-visible parts for drag
getPolyPolygon(aVisible, aInvisible, &rDrag);
aVisible.append(aInvisible);
return aVisible;
}
void TableEdgeHdl::getPolyPolygon(basegfx::B2DPolyPolygon& rVisible, basegfx::B2DPolyPolygon& rInvisible, const SdrDragStat* pDrag) const
{
// changed method to create visible and invisible partial polygons in one run in
// separate PolyPolygons; both kinds are used
basegfx::B2DPoint aOffset(aPos.X(), aPos.Y());
rVisible.clear();
rInvisible.clear();
if( pDrag )
{
int n = mbHorizontal ? 1 : 0;
aOffset[n] = aOffset[n] + GetValidDragOffset( *pDrag );
}
basegfx::B2DPoint aStart(aOffset), aEnd(aOffset);
int nPos = mbHorizontal ? 0 : 1;
TableEdgeVector::const_iterator aIter( maEdges.begin() );
while( aIter != maEdges.end() )
{
TableEdge aEdge(*aIter++);
aStart[nPos] = aOffset[nPos] + aEdge.mnStart;
aEnd[nPos] = aOffset[nPos] + aEdge.mnEnd;
basegfx::B2DPolygon aPolygon;
aPolygon.append( aStart );
aPolygon.append( aEnd );
if(aEdge.meState == Visible)
{
rVisible.append(aPolygon);
}
else
{
rInvisible.append(aPolygon);
}
}
}
void TableEdgeHdl::CreateB2dIAObject()
{
GetRidOfIAObject();
if(pHdlList && pHdlList->GetView() && !pHdlList->GetView()->areMarkHandlesHidden())
{
SdrMarkView* pView = pHdlList->GetView();
SdrPageView* pPageView = pView->GetSdrPageView();
if(pPageView)
{
basegfx::B2DPolyPolygon aVisible;
basegfx::B2DPolyPolygon aInvisible;
// get visible and invisible parts
getPolyPolygon(aVisible, aInvisible, 0);
if(aVisible.count() || aInvisible.count())
{
for(sal_uInt32 nWindow = 0; nWindow < pPageView->PageWindowCount(); nWindow++)
{
const SdrPageWindow& rPageWindow = *pPageView->GetPageWindow(nWindow);
if(rPageWindow.GetPaintWindow().OutputToWindow())
{
rtl::Reference< ::sdr::overlay::OverlayManager > xManager = rPageWindow.GetOverlayManager();
if (xManager.is())
{
if(aVisible.count())
{
// create overlay object for visible parts
sdr::overlay::OverlayObject* pOverlayObject = new OverlayTableEdge(aVisible, true);
xManager->add(*pOverlayObject);
maOverlayGroup.append(*pOverlayObject);
}
if(aInvisible.count())
{
// also create overlay object vor invisible parts to allow
// a standard HitTest using the primitives from that overlay object
// (see OverlayTableEdge implementation)
sdr::overlay::OverlayObject* pOverlayObject = new OverlayTableEdge(aInvisible, false);
xManager->add(*pOverlayObject);
maOverlayGroup.append(*pOverlayObject);
}
}
}
}
}
}
}
}
OverlayTableEdge::OverlayTableEdge( const basegfx::B2DPolyPolygon& rPolyPolygon, bool bVisible )
: OverlayObject(Color(COL_GRAY))
, maPolyPolygon( rPolyPolygon )
, mbVisible(bVisible)
{
}
OverlayTableEdge::~OverlayTableEdge()
{
}
drawinglayer::primitive2d::Primitive2DSequence OverlayTableEdge::createOverlayObjectPrimitive2DSequence()
{
drawinglayer::primitive2d::Primitive2DSequence aRetval;
if(maPolyPolygon.count())
{
// Discussed with CL. Currently i will leave the transparence out since this
// a little bit expensive. We may check the look with drag polygons later
const drawinglayer::primitive2d::Primitive2DReference aReference(
new drawinglayer::primitive2d::PolyPolygonHairlinePrimitive2D(
maPolyPolygon,
getBaseColor().getBColor()));
if(mbVisible)
{
// visible, just return as sequence
aRetval = drawinglayer::primitive2d::Primitive2DSequence(&aReference, 1);
}
else
{
// embed in HiddenGeometryPrimitive2D to support HitTest of this invisible
// overlay object
const drawinglayer::primitive2d::Primitive2DSequence aSequence(&aReference, 1);
const drawinglayer::primitive2d::Primitive2DReference aNewReference(
new drawinglayer::primitive2d::HiddenGeometryPrimitive2D(aSequence));
aRetval = drawinglayer::primitive2d::Primitive2DSequence(&aNewReference, 1);
}
}
return aRetval;
}
TableBorderHdl::TableBorderHdl(
const Rectangle& rRect,
bool bAnimate)
: SdrHdl(rRect.TopLeft(), HDL_MOVE),
maRectangle(rRect),
mbAnimate(bAnimate)
{
}
Pointer TableBorderHdl::GetPointer() const
{
return POINTER_MOVE;
}
// create marker for this kind
void TableBorderHdl::CreateB2dIAObject()
{
GetRidOfIAObject();
if (pHdlList && pHdlList->GetView() && !pHdlList->GetView()->areMarkHandlesHidden())
{
SdrMarkView* pView = pHdlList->GetView();
SdrPageView* pPageView = pView->GetSdrPageView();
if (!pPageView)
return;
for(sal_uInt32 nWindow = 0; nWindow < pPageView->PageWindowCount(); nWindow++)
{
const SdrPageWindow& rPageWindow = *pPageView->GetPageWindow(nWindow);
if (rPageWindow.GetPaintWindow().OutputToWindow())
{
rtl::Reference<sdr::overlay::OverlayManager> xManager = rPageWindow.GetOverlayManager();
if (xManager.is())
{
const basegfx::B2DRange aRange(vcl::unotools::b2DRectangleFromRectangle(maRectangle));
const SvtOptionsDrawinglayer aSvtOptionsDrawinglayer;
const Color aHilightColor(aSvtOptionsDrawinglayer.getHilightColor());
const double fTransparence(aSvtOptionsDrawinglayer.GetTransparentSelectionPercent() * 0.01);
// make animation dependent from text edit active, because for tables
// this handle is also used when text edit *is* active for it. This
// interferes too much concerning repaint stuff (at least as long as
// text edit is not yet on the overlay)
const bool bAnimate = getAnimate();
sdr::overlay::OverlayObject* pOverlayObject =
new sdr::overlay::OverlayRectangle(aRange.getMinimum(), aRange.getMaximum(),
aHilightColor, fTransparence,
6.0, 0.0, 0.0, 500, bAnimate);
xManager->add(*pOverlayObject);
maOverlayGroup.append(*pOverlayObject);
}
}
}
}
}
} // end of namespace table
} // end of namespace sdr
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>#pragma once
#include <phosphor-logging/lg2/concepts.hpp>
#include <string_view>
namespace lg2::details
{
/** A type to handle compile-time validation of header strings. */
struct header_str
{
// Hold the header string value.
std::string_view value;
/** Constructor which performs validation. */
template <typename T>
consteval header_str(const T& s) : value(s)
{
if (value.size() == 0)
{
report_error(
"journald requires headers must have non-zero length.");
}
if (value[0] == '_')
{
report_error("journald requires header do not start with "
"underscore (_)");
}
if (value.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789") !=
std::string_view::npos)
{
report_error(
"journald requires header may only contain underscore, "
"uppercase letters, or numbers ([_A-Z0-9]).");
}
}
/** Cast conversion back to (const char*). */
operator const char*() const
{
return value.data();
}
const char* data() const
{
return value.data();
}
private:
// This does nothing, but is useful for creating nice compile errors in
// a constexpr context.
static void report_error(const char*);
};
/** A helper type for constexpr conversion into header_str, if
* 'maybe_constexpr_string'. For non-constexpr string, this does nothing.
*/
template <typename T>
struct header_str_conversion
{
using type = T;
};
/** Specialization for maybe_constexpr_string. */
template <maybe_constexpr_string T>
struct header_str_conversion<T>
{
using type = const header_str&;
};
/** std-style _t alias for header_str_conversion. */
template <typename T>
using header_str_conversion_t = typename header_str_conversion<T>::type;
} // namespace lg2::details
<commit_msg>lg2: compile time checking for reserved header names<commit_after>#pragma once
#include <array>
#include <phosphor-logging/lg2/concepts.hpp>
#include <string_view>
namespace lg2::details
{
/** A type to handle compile-time validation of header strings. */
struct header_str
{
// Hold the header string value.
std::string_view value;
/** Constructor which performs validation. */
template <typename T>
consteval header_str(const T& s) : value(s)
{
if (value.size() == 0)
{
report_error(
"journald requires headers must have non-zero length.");
}
if (value[0] == '_')
{
report_error("journald requires header do not start with "
"underscore (_)");
}
if (value.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789") !=
std::string_view::npos)
{
report_error(
"journald requires header may only contain underscore, "
"uppercase letters, or numbers ([_A-Z0-9]).");
}
constexpr std::array reserved{
"CODE_FILE", "CODE_FUNC", "CODE_LINE",
"LOG2_FMTMSG", "MESSAGE", "PRIORITY",
};
if (std::ranges::find(reserved, value) != std::end(reserved))
{
report_error("Header name is reserved.");
}
}
/** Cast conversion back to (const char*). */
operator const char*() const
{
return value.data();
}
const char* data() const
{
return value.data();
}
private:
// This does nothing, but is useful for creating nice compile errors in
// a constexpr context.
static void report_error(const char*);
};
/** A helper type for constexpr conversion into header_str, if
* 'maybe_constexpr_string'. For non-constexpr string, this does nothing.
*/
template <typename T>
struct header_str_conversion
{
using type = T;
};
/** Specialization for maybe_constexpr_string. */
template <maybe_constexpr_string T>
struct header_str_conversion<T>
{
using type = const header_str&;
};
/** std-style _t alias for header_str_conversion. */
template <typename T>
using header_str_conversion_t = typename header_str_conversion<T>::type;
} // namespace lg2::details
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: stmenu.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hr $ $Date: 2007-01-02 16:54:04 $
*
* 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
*
* Initial Contributer was Fabalabs Software GmbH, Jakob Lechner
*
* 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
*
************************************************************************/
// SMARTTAGS
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _HELPID_H
#include <helpid.h>
#endif
#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#ifndef _STMENU_HXX
#include <stmenu.hxx>
#endif
#ifndef _STMENU_HRC
#include <stmenu.hrc>
#endif
#ifndef _VIEW_HXX
#include <view.hxx>
#endif
#ifndef _COM_SUN_STAR_TEXT_XTEXTDOCUMENT_HPP_
#include <com/sun/star/text/XTextDocument.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include "com/sun/star/frame/XModel.hpp"
#endif
#ifndef _SWDOCSH_HXX //autogen
#include <docsh.hxx>
#endif
#define C2U(cChar) OUString::createFromAscii(cChar)
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::text;
SwSmartTagPopup::SwSmartTagPopup( SwView* _pSwView, std::vector <ActionReference> _aActionRefs, Reference<XTextRange> _xTextRange ) :
PopupMenu(SW_RES(MN_SMARTTAG_POPUP)),
pSwView ( _pSwView ),
aActionRefs(_aActionRefs), xTextRange (_xTextRange)
{
CreateAutoMnemonics();
PopupMenu *pMenu = GetPopupMenu(MN_SMARTTAG);
if (!pMenu) {
return;
}
pMenu->SetMenuFlags(MENU_FLAG_NOAUTOMNEMONICS);
sal_Bool bEnable = sal_True;
Reference <XController> xController = pSwView->GetController();
nMaxVerbCount=0;
for (int i=0; i<aActionRefs.size(); i++) {
Reference<XSmartTagAction> aSmartTagAction = aActionRefs[i].aSmartTagAction;
sal_Int32 nSmartTagIndex = aActionRefs[i].nSmartTagIndex;
if (aSmartTagAction->getActionCount(nSmartTagIndex, xController)>nMaxVerbCount)
nMaxVerbCount = aSmartTagAction->getActionCount(nSmartTagIndex, xController);
}
// add menuitem for every smarttag
for (sal_uInt16 i=0; i<aActionRefs.size(); i++) {
Reference<XSmartTagAction> aSmartTagAction = aActionRefs[i].aSmartTagAction;
sal_Int32 nSmartTagIndex = aActionRefs[i].nSmartTagIndex;
InsertItem(i+1, aSmartTagAction->getSmartTagCaption(nSmartTagIndex, xController));
PopupMenu* pSubMenu = new PopupMenu;
SetPopupMenu(i+1, pSubMenu);
// add subitem for every action of current smarttag
for (int j=0; j<aSmartTagAction->getActionCount(nSmartTagIndex, xController); j++) {
// compute the unique id that comprises the information in which
// smarttag library the action can be found and which action is actually meant
// This id is needed later in the execute method to invoke the correct
// action in the smarttag object
sal_uInt16 nId = (i*nMaxVerbCount + j) + MN_ST_INSERT_START;
pSubMenu->InsertItem(nId, aSmartTagAction->getActionCaption(nSmartTagIndex, j, xController));
}
}
EnableItem( MN_SMARTTAG, bEnable );
RemoveDisabledEntries( TRUE, TRUE );
}
/** Function: Execute
executes actions by calling the invoke function of the appropriate
smarttag library.
*/
sal_uInt16 SwSmartTagPopup::Execute( Window* pWin, const Rectangle& rWordPos )
{
SetMenuFlags(MENU_FLAG_NOAUTOMNEMONICS);
sal_uInt16 nRet = PopupMenu::Execute(pWin, pWin->LogicToPixel(rWordPos));
if (nRet < MN_ST_INSERT_START) return nRet;
// compute smarttag lib index and action index
nRet -= MN_ST_INSERT_START;
sal_Int32 nRefIndex = nRet / nMaxVerbCount;
sal_Int32 nActionIndex = nRet % nMaxVerbCount;
Reference<XSmartTagAction> aSmartTagAction = aActionRefs[nRefIndex].aSmartTagAction;
sal_Int32 nSmartTagIndex = aActionRefs[nRefIndex].nSmartTagIndex;
Reference <XController> xController = pSwView->GetController();
// execute action
aSmartTagAction->invokeAction(nSmartTagIndex, nActionIndex, xTextRange, xController);
return nRet;
}
<commit_msg>INTEGRATION: CWS smarttags3 (1.2.70); FILE MERGED 2007/06/05 08:17:34 fme 1.2.70.9: #i76130# New Smart Tag API - Controller parameter added to a couple of functions 2007/05/23 14:26:51 fme 1.2.70.8: #i75130# New smart tag API - resync 2007/05/14 12:19:14 fme 1.2.70.7: #i75130# New smart tag API 2007/05/12 06:31:52 fme 1.2.70.6: #i75130# New smart tag API 2007/05/02 08:25:49 fme 1.2.70.5: #i75130# New smart tag API 2007/05/02 07:55:26 fme 1.2.70.4: #i75130# New smart tag API 2007/04/26 13:16:21 fme 1.2.70.3: #i75130# New Smarttag API 2007/04/16 12:13:23 fme 1.2.70.2: #i75130# New Smart Tag API 2007/03/05 13:55:26 fme 1.2.70.1: #i75130# New API and implementation of smart tags<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: stmenu.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2007-06-27 13:26:22 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* Initial Contributer was Fabalabs Software GmbH, Jakob Lechner
*
* 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
*
************************************************************************/
// SMARTTAGS
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifndef _STMENU_HXX
#include <stmenu.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#include <SwSmartTagMgr.hxx>
#ifndef _STMENU_HRC
#include <stmenu.hrc>
#endif
#ifndef _VIEW_HXX
#include <view.hxx>
#endif
#ifndef _BREAKIT_HXX
#include <breakit.hxx>
#endif
#define C2U(cChar) rtl::OUString::createFromAscii(cChar)
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
SwSmartTagPopup::SwSmartTagPopup( SwView* pSwView,
Sequence< rtl::OUString >& rSmartTagTypes,
Sequence< Reference< container::XStringKeyMap > >& rStringKeyMaps,
Reference< text::XTextRange > xTextRange ) :
PopupMenu( SW_RES(MN_SMARTTAG_POPUP) ),
mpSwView ( pSwView ),
mxTextRange( xTextRange )
{
//CreateAutoMnemonics();
Reference <frame::XController> xController = mpSwView->GetController();
const lang::Locale aLocale( SW_BREAKITER()->GetLocale( (LanguageType)GetAppLanguage() ) );
USHORT nMenuPos = 0;
USHORT nSubMenuPos = 0;
USHORT nMenuId = 1;
USHORT nSubMenuId = MN_ST_INSERT_START;
const rtl::OUString aRangeText = mxTextRange->getString();
SmartTagMgr& rSmartTagMgr = SwSmartTagMgr::Get();
const rtl::OUString aApplicationName( rSmartTagMgr.GetApplicationName() );
Sequence < Sequence< Reference< smarttags::XSmartTagAction > > > aActionComponentsSequence;
Sequence < Sequence< sal_Int32 > > aActionIndicesSequence;
rSmartTagMgr.GetActionSequences( rSmartTagTypes,
aActionComponentsSequence,
aActionIndicesSequence );
InsertSeparator(0);
for ( USHORT j = 0; j < aActionComponentsSequence.getLength(); ++j )
{
Reference< container::XStringKeyMap > xSmartTagProperties = rStringKeyMaps[j];
// Get all actions references associated with the current smart tag type:
const Sequence< Reference< smarttags::XSmartTagAction > >& rActionComponents = aActionComponentsSequence[j];
const Sequence< sal_Int32 >& rActionIndices = aActionIndicesSequence[j];
if ( 0 == rActionComponents.getLength() || 0 == rActionIndices.getLength() )
continue;
// Ask first entry for the smart tag type caption:
Reference< smarttags::XSmartTagAction > xAction = rActionComponents[0];
if ( !xAction.is() )
continue;
const sal_Int32 nSmartTagIndex = rActionIndices[0];
const rtl::OUString aSmartTagType = xAction->getSmartTagName( nSmartTagIndex );
const rtl::OUString aSmartTagCaption = xAction->getSmartTagCaption( nSmartTagIndex, aLocale );
// no sub-menues if there's only one smart tag type listed:
PopupMenu* pSbMenu = this;
if ( 1 < aActionComponentsSequence.getLength() )
{
InsertItem( nMenuId, aSmartTagCaption, 0, nMenuPos++);
pSbMenu = new PopupMenu;
SetPopupMenu( nMenuId++, pSbMenu );
}
// sub-menu starts with smart tag caption and separator
const rtl::OUString aSmartTagCaption2 = aSmartTagCaption + C2U(": ") + aRangeText;
nSubMenuPos = 0;
pSbMenu->InsertItem( nMenuId++, aSmartTagCaption2, MIB_NOSELECT, nSubMenuPos++ );
pSbMenu->InsertSeparator( nSubMenuPos++ );
// Add subitem for every action reference for the current smart tag type:
for ( USHORT i = 0; i < rActionComponents.getLength(); ++i )
{
xAction = rActionComponents[i];
for ( sal_Int32 k = 0; k < xAction->getActionCount( aSmartTagType, xController ); ++k )
{
const sal_uInt32 nActionID = xAction->getActionID( aSmartTagType, k, xController );
rtl::OUString aActionCaption = xAction->getActionCaptionFromID( nActionID,
aApplicationName,
aLocale,
xSmartTagProperties,
aRangeText,
rtl::OUString(),
xController,
mxTextRange );
pSbMenu->InsertItem( nSubMenuId++, aActionCaption, 0, nSubMenuPos++ );
InvokeAction aEntry( xAction, xSmartTagProperties, nActionID );
maInvokeActions.push_back( aEntry );
}
}
}
}
/** Function: Execute
executes actions by calling the invoke function of the appropriate
smarttag library.
*/
sal_uInt16 SwSmartTagPopup::Execute( Window* pWin, const Rectangle& rWordPos )
{
sal_uInt16 nId = PopupMenu::Execute(pWin, pWin->LogicToPixel(rWordPos));
if ( nId == MN_SMARTTAG_OPTIONS )
{
SfxBoolItem aBool(SID_OPEN_SMARTTAGOPTIONS, TRUE);
mpSwView->GetViewFrame()->GetDispatcher()->Execute( SID_AUTO_CORRECT_DLG, SFX_CALLMODE_ASYNCHRON, &aBool, 0L );
}
if ( nId < MN_ST_INSERT_START) return nId;
nId -= MN_ST_INSERT_START;
// compute smarttag lib index and action index
if ( nId < maInvokeActions.size() )
{
Reference< smarttags::XSmartTagAction > xSmartTagAction = maInvokeActions[ nId ].mxAction;
// execute action
if ( xSmartTagAction.is() )
{
SmartTagMgr& rSmartTagMgr = SwSmartTagMgr::Get();
xSmartTagAction->invokeAction( maInvokeActions[ nId ].mnActionID,
rSmartTagMgr.GetApplicationName(),
mpSwView->GetController(),
mxTextRange,
maInvokeActions[ nId ].mxSmartTagProperties,
mxTextRange->getString(),
rtl::OUString(),
SW_BREAKITER()->GetLocale( (LanguageType)GetAppLanguage() ) );
}
}
return nId;
}
<|endoftext|>
|
<commit_before>/*
** Copyright 2011 Merethis
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker 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 Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <assert.h>
#include <stdlib.h>
#include "config/applier/endpoint.hh"
#include "exceptions/basic.hh"
#include "io/protocols.hh"
using namespace com::centreon::broker;
using namespace com::centreon::broker::config::applier;
/**************************************
* *
* Private Methods *
* *
**************************************/
/**
* Default constructor.
*/
endpoint::endpoint() : QObject() {}
/**
* @brief Copy constructor.
*
* Any call to this constructor will result in a call to abort().
*
* @param[in] e Object to copy.
*/
endpoint::endpoint(endpoint const& e) : QObject() {
(void)e;
assert(false);
abort();
}
/**
* @brief Assignment operator.
*
* Any call to this method will result in a call to abort().
*
* @param[in] e Object to copy.
*
* @return This object.
*/
endpoint& endpoint::operator=(endpoint const& e) {
(void)e;
assert(false);
abort();
return (*this);
}
/**
* Create and register an endpoint according to configuration.
*
* @param[in] cfg Endpoint configuration.
* @param[in] is_output true if the endpoint will act as output.
*/
void endpoint::_create_endpoint(config::endpoint const& cfg, bool is_output) {
// Create endpoint object.
QSharedPointer<io::endpoint> endp;
int level(1);
for (QMap<QString, io::protocols::protocol>::const_iterator it = io::protocols::instance().begin(),
end = io::protocols::instance().end();
it != end;
++it) {
if ((it.value().osi_from == level)
&& it.value().endpntfactry->had_endpoint()) {
endp = QSharedPointer<io::endpoint>(it.value().endpntfactry->new_endpoint());
break ;
}
}
if (endp.isNull())
throw (exceptions::basic() << "no matching protocol found for endpoint '"
<< cfg.name.toStdString().c_str() << "'");
// XXX : remaining objects.
// Create thread.
QScopedPointer<processing::failover> fo(new processing::failover);
fo->set_endpoint(endp,
(is_output
? processing::failover::output
: processing::failover::input));
// Connect thread.
connect(fo.data(), SIGNAL(finished()), fo.data(), SLOT(deleteLater));
if (!is_output) {
connect(fo.data(), SIGNAL(finished()), this, SLOT(terminated_input()));
_inputs[cfg] = fo.data();
}
else {
connect(fo.data(), SIGNAL(finished()), this, SLOT(terminated_output()));
_outputs[cfg] = fo.data();
}
// Run thread.
fo.take()->start();
return ;
}
/**
* Diff the current configuration with the new configuration.
*
* @param[in] current Current endpoints.
* @param[in] new_endpoints New endpoints configuration.
* @param[out] to_create Endpoints that should be created.
*/
void endpoint::_diff_endpoints(QMap<config::endpoint, processing::failover*> & current,
QList<config::endpoint> const& new_endpoints,
QList<config::endpoint>& to_create) {
// Find which endpoints will be kept, created and deleted.
QMap<config::endpoint, processing::failover*> to_delete(current);
for (QList<config::endpoint>::const_iterator it = new_endpoints.begin(),
end = new_endpoints.end();
it != end;
++it) {
QMap<config::endpoint, processing::failover*>::iterator endp(to_delete.find(*it));
if (endp != to_delete.end())
to_delete.erase(endp);
else
to_create.push_back(*it);
}
// Remove old endpoints.
for (QMap<config::endpoint, processing::failover*>::iterator it = to_delete.begin(),
end = to_delete.end();
it != end;
++it) {
// XXX : send only termination request, object will
// be destroyed by event loop on termination.
// But wait for threads, because
}
return ;
}
/**************************************
* *
* Public Methods *
* *
**************************************/
/**
* Destructor.
*/
endpoint::~endpoint() {}
/**
* Apply the endpoint configuration.
*
* @param[in] inputs Inputs configuration.
* @param[in] outputs Outputs configuration.
*/
void endpoint::apply(QList<config::endpoint> const& inputs,
QList<config::endpoint> const& outputs) {
// Remove old inputs and generate inputs to create.
QList<config::endpoint> in_to_create;
_diff_endpoints(_inputs, inputs, in_to_create);
// Remove old outputs and generate outputs to create.
QList<config::endpoint> out_to_create;
_diff_endpoints(_outputs, outputs, out_to_create);
// Create new outputs.
for (QList<config::endpoint>::iterator it = out_to_create.begin(),
end = out_to_create.end();
it != end;
++it)
_create_endpoint(*it, true);
// Create new inputs.
for (QList<config::endpoint>::iterator it = in_to_create.begin(),
end = in_to_create.end();
it != end;
++it)
_create_endpoint(*it, false);
return ;
}
/**
* Get the class instance.
*
* @return Class instance.
*/
endpoint& endpoint::instance() {
static endpoint gl_endpoint;
return (gl_endpoint);
}
/**
* An input thread finished executing.
*/
void endpoint::terminated_input() {
// XXX
}
/**
* An output thread finished executing.
*/
void endpoint::terminated_output() {
// XXX
}
<commit_msg>Implementation of endpoint configuration applier is finished.<commit_after>/*
** Copyright 2011 Merethis
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker 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 Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <assert.h>
#include <stdlib.h>
#include "config/applier/endpoint.hh"
#include "exceptions/basic.hh"
#include "io/acceptor.hh"
#include "io/connector.hh"
#include "io/protocols.hh"
using namespace com::centreon::broker;
using namespace com::centreon::broker::config::applier;
/**************************************
* *
* Private Methods *
* *
**************************************/
/**
* Default constructor.
*/
endpoint::endpoint() : QObject() {}
/**
* @brief Copy constructor.
*
* Any call to this constructor will result in a call to abort().
*
* @param[in] e Object to copy.
*/
endpoint::endpoint(endpoint const& e) : QObject() {
(void)e;
assert(false);
abort();
}
/**
* @brief Assignment operator.
*
* Any call to this method will result in a call to abort().
*
* @param[in] e Object to copy.
*
* @return This object.
*/
endpoint& endpoint::operator=(endpoint const& e) {
(void)e;
assert(false);
abort();
return (*this);
}
/**
* Create and register an endpoint according to configuration.
*
* @param[in] cfg Endpoint configuration.
* @param[in] is_output true if the endpoint will act as output.
*/
void endpoint::_create_endpoint(config::endpoint const& cfg, bool is_output) {
// Create endpoint object.
QSharedPointer<io::endpoint> endp;
bool is_acceptor;
int level;
for (QMap<QString, io::protocols::protocol>::const_iterator it = io::protocols::instance().begin(),
end = io::protocols::instance().end();
it != end;
++it) {
if ((it.value().osi_from == 1)
&& it.value().endpntfactry->has_endpoint(cfg)) {
endp = QSharedPointer<io::endpoint>(it.value().endpntfactry->new_endpoint(cfg, is_acceptor));
level = it.value().osi_to + 1;
break ;
}
}
if (endp.isNull())
throw (exceptions::basic() << "no matching protocol found for endpoint '"
<< cfg.name.toStdString().c_str() << "'");
// Create remaining objects.
io::endpoint* prev(endp.data());
while (level <= 7) {
// Browse protocol list.
QMap<QString, io::protocols::protocol>::const_iterator it(io::protocols::instance().begin());
QMap<QString, io::protocols::protocol>::const_iterator end(io::protocols::instance().end());
while (it != end) {
if ((it.value().osi_from == level)
&& (it.value().endpntfactry->has_endpoint(cfg))) {
if (is_acceptor) {
QSharedPointer<io::acceptor> current(static_cast<io::acceptor*>(it.value().endpntfactry->new_endpoint(cfg, is_acceptor)));
static_cast<io::acceptor*>(prev)->on(current);
prev = current.data();
}
else {
QSharedPointer<io::connector> current(static_cast<io::connector*>(it.value().endpntfactry->new_endpoint(cfg, is_acceptor)));
static_cast<io::connector*>(prev)->on(current);
prev = current.data();
}
break ;
}
++it;
}
if ((7 == level) && (it == end))
throw (exceptions::basic() << "no matching protocol found for endpoint '"
<< cfg.name.toStdString().c_str() << "'");
++level;
}
// Create thread.
QScopedPointer<processing::failover> fo(new processing::failover);
fo->set_endpoint(endp,
(is_output
? processing::failover::output
: processing::failover::input));
// Connect thread.
connect(fo.data(), SIGNAL(finished()), fo.data(), SLOT(deleteLater));
if (!is_output) {
connect(fo.data(), SIGNAL(finished()), this, SLOT(terminated_input()));
_inputs[cfg] = fo.data();
}
else {
connect(fo.data(), SIGNAL(finished()), this, SLOT(terminated_output()));
_outputs[cfg] = fo.data();
}
// Run thread.
fo.take()->start();
return ;
}
/**
* Diff the current configuration with the new configuration.
*
* @param[in] current Current endpoints.
* @param[in] new_endpoints New endpoints configuration.
* @param[out] to_create Endpoints that should be created.
*/
void endpoint::_diff_endpoints(QMap<config::endpoint, processing::failover*> & current,
QList<config::endpoint> const& new_endpoints,
QList<config::endpoint>& to_create) {
// Find which endpoints will be kept, created and deleted.
QMap<config::endpoint, processing::failover*> to_delete(current);
for (QList<config::endpoint>::const_iterator it = new_endpoints.begin(),
end = new_endpoints.end();
it != end;
++it) {
QMap<config::endpoint, processing::failover*>::iterator endp(to_delete.find(*it));
if (endp != to_delete.end())
to_delete.erase(endp);
else
to_create.push_back(*it);
}
// Remove old endpoints.
for (QMap<config::endpoint, processing::failover*>::iterator it = to_delete.begin(),
end = to_delete.end();
it != end;
++it) {
// XXX : send only termination request, object will
// be destroyed by event loop on termination.
// But wait for threads, because
}
return ;
}
/**************************************
* *
* Public Methods *
* *
**************************************/
/**
* Destructor.
*/
endpoint::~endpoint() {}
/**
* Apply the endpoint configuration.
*
* @param[in] inputs Inputs configuration.
* @param[in] outputs Outputs configuration.
*/
void endpoint::apply(QList<config::endpoint> const& inputs,
QList<config::endpoint> const& outputs) {
// Remove old inputs and generate inputs to create.
QList<config::endpoint> in_to_create;
_diff_endpoints(_inputs, inputs, in_to_create);
// Remove old outputs and generate outputs to create.
QList<config::endpoint> out_to_create;
_diff_endpoints(_outputs, outputs, out_to_create);
// Create new outputs.
for (QList<config::endpoint>::iterator it = out_to_create.begin(),
end = out_to_create.end();
it != end;
++it)
_create_endpoint(*it, true);
// Create new inputs.
for (QList<config::endpoint>::iterator it = in_to_create.begin(),
end = in_to_create.end();
it != end;
++it)
_create_endpoint(*it, false);
return ;
}
/**
* Get the class instance.
*
* @return Class instance.
*/
endpoint& endpoint::instance() {
static endpoint gl_endpoint;
return (gl_endpoint);
}
/**
* An input thread finished executing.
*/
void endpoint::terminated_input() {
// XXX
}
/**
* An output thread finished executing.
*/
void endpoint::terminated_output() {
// XXX
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkPlotParallelCoordinates.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkPlotParallelCoordinates.h"
#include "vtkChartParallelCoordinates.h"
#include "vtkContext2D.h"
#include "vtkAxis.h"
#include "vtkPen.h"
#include "vtkFloatArray.h"
#include "vtkDoubleArray.h"
#include "vtkVector.h"
#include "vtkTransform2D.h"
#include "vtkContextDevice2D.h"
#include "vtkContextMapper2D.h"
#include "vtkPoints2D.h"
#include "vtkTable.h"
#include "vtkDataArray.h"
#include "vtkIdTypeArray.h"
#include "vtkStringArray.h"
#include "vtkTimeStamp.h"
#include "vtkInformation.h"
#include "vtkSmartPointer.h"
// Need to turn some arrays of strings into categories
#include "vtkStringToCategory.h"
#include "vtkObjectFactory.h"
#include "vtkstd/vector"
#include "vtkstd/algorithm"
class vtkPlotParallelCoordinates::Private :
public vtkstd::vector< vtkstd::vector<float> >
{
public:
Private()
{
this->SelectionInitialized = false;
}
vtkstd::vector<float> AxisPos;
bool SelectionInitialized;
};
vtkCxxRevisionMacro(vtkPlotParallelCoordinates, "1.7");
//-----------------------------------------------------------------------------
vtkStandardNewMacro(vtkPlotParallelCoordinates);
//-----------------------------------------------------------------------------
vtkPlotParallelCoordinates::vtkPlotParallelCoordinates()
{
this->Points = NULL;
this->Storage = new vtkPlotParallelCoordinates::Private;
this->Parent = NULL;
this->Pen->SetColor(0, 0, 0, 25);
}
//-----------------------------------------------------------------------------
vtkPlotParallelCoordinates::~vtkPlotParallelCoordinates()
{
if (this->Points)
{
this->Points->Delete();
this->Points = NULL;
}
delete this->Storage;
}
//-----------------------------------------------------------------------------
void vtkPlotParallelCoordinates::Update()
{
if (!this->Visible)
{
return;
}
// Check if we have an input
vtkTable *table = this->Data->GetInput();
if (!table)
{
vtkDebugMacro(<< "Update event called with no input table set.");
return;
}
this->UpdateTableCache(table);
}
//-----------------------------------------------------------------------------
bool vtkPlotParallelCoordinates::Paint(vtkContext2D *painter)
{
// This is where everything should be drawn, or dispatched to other methods.
vtkDebugMacro(<< "Paint event called in vtkPlotParallelCoordinates.");
if (!this->Visible)
{
return false;
}
// Now to plot the points
if (this->Points)
{
painter->ApplyPen(this->Pen);
painter->DrawPoly(this->Points);
painter->GetPen()->SetLineType(vtkPen::SOLID_LINE);
}
painter->ApplyPen(this->Pen);
if (this->Storage->size() == 0)
{
return false;
}
size_t cols = this->Storage->size();
size_t rows = this->Storage->at(0).size();
vtkVector2f* line = new vtkVector2f[cols];
// Update the axis positions
for (size_t i = 0; i < cols; ++i)
{
this->Storage->AxisPos[i] = this->Parent->GetAxis(int(i)) ?
this->Parent->GetAxis(int(i))->GetPoint1()[0] :
0;
}
vtkIdType selection = 0;
vtkIdType id = 0;
vtkIdType selectionSize = 0;
if (this->Selection)
{
selectionSize = this->Selection->GetNumberOfTuples();
if (selectionSize)
{
this->Selection->GetTupleValue(selection, &id);
}
}
// Draw all of the lines
painter->ApplyPen(this->Pen);
for (size_t i = 0; i < rows; ++i)
{
for (size_t j = 0; j < cols; ++j)
{
line[j].Set(this->Storage->AxisPos[j], (*this->Storage)[j][i]);
}
painter->DrawPoly(line[0].GetData(), static_cast<int>(cols));
}
// Now draw the selected lines
if (this->Selection)
{
painter->GetPen()->SetColor(255, 0, 0, 100);
for (vtkIdType i = 0; i < this->Selection->GetNumberOfTuples(); ++i)
{
for (size_t j = 0; j < cols; ++j)
{
this->Selection->GetTupleValue(i, &id);
line[j].Set(this->Storage->AxisPos[j], (*this->Storage)[j][id]);
}
painter->DrawPoly(line[0].GetData(), static_cast<int>(cols));
}
}
delete[] line;
return true;
}
//-----------------------------------------------------------------------------
bool vtkPlotParallelCoordinates::PaintLegend(vtkContext2D *painter, float rect[4])
{
painter->ApplyPen(this->Pen);
painter->DrawLine(rect[0], rect[1]+0.5*rect[3],
rect[0]+rect[2], rect[1]+0.5*rect[3]);
return true;
}
//-----------------------------------------------------------------------------
void vtkPlotParallelCoordinates::GetBounds(double *)
{
}
//-----------------------------------------------------------------------------
bool vtkPlotParallelCoordinates::GetNearestPoint(const vtkVector2f& ,
const vtkVector2f& ,
vtkVector2f* )
{
return false;
}
//-----------------------------------------------------------------------------
void vtkPlotParallelCoordinates::SetParent(vtkChartParallelCoordinates* parent)
{
this->Parent = parent;
}
//-----------------------------------------------------------------------------
bool vtkPlotParallelCoordinates::SetSelectionRange(int axis, float low,
float high)
{
if (!this->Selection)
{
return false;
}
if (this->Storage->SelectionInitialized)
{
// Further refine the selection that has already been made
vtkIdTypeArray *array = vtkIdTypeArray::New();
vtkstd::vector<float>& col = this->Storage->at(axis);
for (vtkIdType i = 0; i < this->Selection->GetNumberOfTuples(); ++i)
{
vtkIdType id = 0;
this->Selection->GetTupleValue(i, &id);
if (col[id] >= low && col[id] <= high)
{
// Remove this point - no longer selected
array->InsertNextValue(id);
}
}
this->Selection->DeepCopy(array);
array->Delete();
}
else
{
// First run - ensure the selection list is empty and build it up
vtkstd::vector<float>& col = this->Storage->at(axis);
for (size_t i = 0; i < col.size(); ++i)
{
if (col[i] >= low && col[i] <= high)
{
// Remove this point - no longer selected
this->Selection->InsertNextValue(i);
}
}
this->Storage->SelectionInitialized = true;
}
return true;
}
//-----------------------------------------------------------------------------
bool vtkPlotParallelCoordinates::ResetSelectionRange()
{
this->Storage->SelectionInitialized = false;
if (this->Selection)
{
this->Selection->SetNumberOfTuples(0);
}
return true;
}
//-----------------------------------------------------------------------------
void vtkPlotParallelCoordinates::SetInput(vtkTable* table)
{
if (table == this->Data->GetInput())
{
return;
}
this->vtkPlot::SetInput(table);
if (this->Parent)
{
// By default make the first 10 columns visible in a plot.
for (vtkIdType i = 0; i < table->GetNumberOfColumns() && i < 10; ++i)
{
this->Parent->SetColumnVisibility(table->GetColumnName(i), true);
}
}
}
//-----------------------------------------------------------------------------
bool vtkPlotParallelCoordinates::UpdateTableCache(vtkTable *table)
{
// Each axis is a column in our storage array, they are scaled from 0.0 to 1.0
if (!this->Parent || !table || table->GetNumberOfColumns() == 0)
{
return false;
}
vtkStringArray* cols = this->Parent->GetVisibleColumns();
this->Storage->resize(cols->GetNumberOfTuples());
this->Storage->AxisPos.resize(cols->GetNumberOfTuples());
vtkIdType rows = table->GetNumberOfRows();
for (vtkIdType i = 0; i < cols->GetNumberOfTuples(); ++i)
{
vtkstd::vector<float>& col = this->Storage->at(i);
vtkAxis* axis = this->Parent->GetAxis(i);
col.resize(rows);
vtkSmartPointer<vtkDataArray> data =
vtkDataArray::SafeDownCast(table->GetColumnByName(cols->GetValue(i)));
if (!data)
{
if (table->GetColumnByName(cols->GetValue(i))->IsA("vtkStringArray"))
{
// We have a different kind of column - attempt to make it into an enum
vtkStringToCategory* stoc = vtkStringToCategory::New();
stoc->SetInput(table);
stoc->SetInputArrayToProcess(0, 0, 0,
vtkDataObject::FIELD_ASSOCIATION_ROWS,
cols->GetValue(i));
stoc->SetCategoryArrayName("enumPC");
stoc->Update();
vtkTable* table2 = vtkTable::SafeDownCast(stoc->GetOutput());
vtkTable* stringTable = vtkTable::SafeDownCast(stoc->GetOutput(1));
if (table2)
{
data = vtkDataArray::SafeDownCast(table2->GetColumnByName("enumPC"));
}
if (stringTable && stringTable->GetColumnByName("Strings"))
{
vtkStringArray* strings =
vtkStringArray::SafeDownCast(stringTable->GetColumnByName("Strings"));
vtkSmartPointer<vtkDoubleArray> arr =
vtkSmartPointer<vtkDoubleArray>::New();
for (vtkIdType j = 0; j < strings->GetNumberOfTuples(); ++j)
{
arr->InsertNextValue(j);
}
// Now we need to set the range on the string axis
axis->SetTickLabels(strings);
axis->SetTickPositions(arr);
axis->SetRange(0.0, strings->GetNumberOfTuples()-1);
axis->Update();
}
stoc->Delete();
}
// If we still don't have a valid data array then skip this column.
if (!data)
{
continue;
}
}
// Also need the range from the appropriate axis, to normalize points
float min = axis->GetMinimum();
float max = axis->GetMaximum();
float scale = 1.0f / (max - min);
for (vtkIdType j = 0; j < rows; ++j)
{
col[j] = (data->GetTuple1(j)-min) * scale;
}
}
this->BuildTime.Modified();
return true;
}
//-----------------------------------------------------------------------------
void vtkPlotParallelCoordinates::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
<commit_msg>BUG: Handle the case where there is only one enum.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkPlotParallelCoordinates.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkPlotParallelCoordinates.h"
#include "vtkChartParallelCoordinates.h"
#include "vtkContext2D.h"
#include "vtkAxis.h"
#include "vtkPen.h"
#include "vtkFloatArray.h"
#include "vtkDoubleArray.h"
#include "vtkVector.h"
#include "vtkTransform2D.h"
#include "vtkContextDevice2D.h"
#include "vtkContextMapper2D.h"
#include "vtkPoints2D.h"
#include "vtkTable.h"
#include "vtkDataArray.h"
#include "vtkIdTypeArray.h"
#include "vtkStringArray.h"
#include "vtkTimeStamp.h"
#include "vtkInformation.h"
#include "vtkSmartPointer.h"
// Need to turn some arrays of strings into categories
#include "vtkStringToCategory.h"
#include "vtkObjectFactory.h"
#include "vtkstd/vector"
#include "vtkstd/algorithm"
class vtkPlotParallelCoordinates::Private :
public vtkstd::vector< vtkstd::vector<float> >
{
public:
Private()
{
this->SelectionInitialized = false;
}
vtkstd::vector<float> AxisPos;
bool SelectionInitialized;
};
vtkCxxRevisionMacro(vtkPlotParallelCoordinates, "1.8");
//-----------------------------------------------------------------------------
vtkStandardNewMacro(vtkPlotParallelCoordinates);
//-----------------------------------------------------------------------------
vtkPlotParallelCoordinates::vtkPlotParallelCoordinates()
{
this->Points = NULL;
this->Storage = new vtkPlotParallelCoordinates::Private;
this->Parent = NULL;
this->Pen->SetColor(0, 0, 0, 25);
}
//-----------------------------------------------------------------------------
vtkPlotParallelCoordinates::~vtkPlotParallelCoordinates()
{
if (this->Points)
{
this->Points->Delete();
this->Points = NULL;
}
delete this->Storage;
}
//-----------------------------------------------------------------------------
void vtkPlotParallelCoordinates::Update()
{
if (!this->Visible)
{
return;
}
// Check if we have an input
vtkTable *table = this->Data->GetInput();
if (!table)
{
vtkDebugMacro(<< "Update event called with no input table set.");
return;
}
this->UpdateTableCache(table);
}
//-----------------------------------------------------------------------------
bool vtkPlotParallelCoordinates::Paint(vtkContext2D *painter)
{
// This is where everything should be drawn, or dispatched to other methods.
vtkDebugMacro(<< "Paint event called in vtkPlotParallelCoordinates.");
if (!this->Visible)
{
return false;
}
// Now to plot the points
if (this->Points)
{
painter->ApplyPen(this->Pen);
painter->DrawPoly(this->Points);
painter->GetPen()->SetLineType(vtkPen::SOLID_LINE);
}
painter->ApplyPen(this->Pen);
if (this->Storage->size() == 0)
{
return false;
}
size_t cols = this->Storage->size();
size_t rows = this->Storage->at(0).size();
vtkVector2f* line = new vtkVector2f[cols];
// Update the axis positions
for (size_t i = 0; i < cols; ++i)
{
this->Storage->AxisPos[i] = this->Parent->GetAxis(int(i)) ?
this->Parent->GetAxis(int(i))->GetPoint1()[0] :
0;
}
vtkIdType selection = 0;
vtkIdType id = 0;
vtkIdType selectionSize = 0;
if (this->Selection)
{
selectionSize = this->Selection->GetNumberOfTuples();
if (selectionSize)
{
this->Selection->GetTupleValue(selection, &id);
}
}
// Draw all of the lines
painter->ApplyPen(this->Pen);
for (size_t i = 0; i < rows; ++i)
{
for (size_t j = 0; j < cols; ++j)
{
line[j].Set(this->Storage->AxisPos[j], (*this->Storage)[j][i]);
}
painter->DrawPoly(line[0].GetData(), static_cast<int>(cols));
}
// Now draw the selected lines
if (this->Selection)
{
painter->GetPen()->SetColor(255, 0, 0, 100);
for (vtkIdType i = 0; i < this->Selection->GetNumberOfTuples(); ++i)
{
for (size_t j = 0; j < cols; ++j)
{
this->Selection->GetTupleValue(i, &id);
line[j].Set(this->Storage->AxisPos[j], (*this->Storage)[j][id]);
}
painter->DrawPoly(line[0].GetData(), static_cast<int>(cols));
}
}
delete[] line;
return true;
}
//-----------------------------------------------------------------------------
bool vtkPlotParallelCoordinates::PaintLegend(vtkContext2D *painter, float rect[4])
{
painter->ApplyPen(this->Pen);
painter->DrawLine(rect[0], rect[1]+0.5*rect[3],
rect[0]+rect[2], rect[1]+0.5*rect[3]);
return true;
}
//-----------------------------------------------------------------------------
void vtkPlotParallelCoordinates::GetBounds(double *)
{
}
//-----------------------------------------------------------------------------
bool vtkPlotParallelCoordinates::GetNearestPoint(const vtkVector2f& ,
const vtkVector2f& ,
vtkVector2f* )
{
return false;
}
//-----------------------------------------------------------------------------
void vtkPlotParallelCoordinates::SetParent(vtkChartParallelCoordinates* parent)
{
this->Parent = parent;
}
//-----------------------------------------------------------------------------
bool vtkPlotParallelCoordinates::SetSelectionRange(int axis, float low,
float high)
{
if (!this->Selection)
{
return false;
}
if (this->Storage->SelectionInitialized)
{
// Further refine the selection that has already been made
vtkIdTypeArray *array = vtkIdTypeArray::New();
vtkstd::vector<float>& col = this->Storage->at(axis);
for (vtkIdType i = 0; i < this->Selection->GetNumberOfTuples(); ++i)
{
vtkIdType id = 0;
this->Selection->GetTupleValue(i, &id);
if (col[id] >= low && col[id] <= high)
{
// Remove this point - no longer selected
array->InsertNextValue(id);
}
}
this->Selection->DeepCopy(array);
array->Delete();
}
else
{
// First run - ensure the selection list is empty and build it up
vtkstd::vector<float>& col = this->Storage->at(axis);
for (size_t i = 0; i < col.size(); ++i)
{
if (col[i] >= low && col[i] <= high)
{
// Remove this point - no longer selected
this->Selection->InsertNextValue(i);
}
}
this->Storage->SelectionInitialized = true;
}
return true;
}
//-----------------------------------------------------------------------------
bool vtkPlotParallelCoordinates::ResetSelectionRange()
{
this->Storage->SelectionInitialized = false;
if (this->Selection)
{
this->Selection->SetNumberOfTuples(0);
}
return true;
}
//-----------------------------------------------------------------------------
void vtkPlotParallelCoordinates::SetInput(vtkTable* table)
{
if (table == this->Data->GetInput())
{
return;
}
this->vtkPlot::SetInput(table);
if (this->Parent)
{
// By default make the first 10 columns visible in a plot.
for (vtkIdType i = 0; i < table->GetNumberOfColumns() && i < 10; ++i)
{
this->Parent->SetColumnVisibility(table->GetColumnName(i), true);
}
}
}
//-----------------------------------------------------------------------------
bool vtkPlotParallelCoordinates::UpdateTableCache(vtkTable *table)
{
// Each axis is a column in our storage array, they are scaled from 0.0 to 1.0
if (!this->Parent || !table || table->GetNumberOfColumns() == 0)
{
return false;
}
vtkStringArray* cols = this->Parent->GetVisibleColumns();
this->Storage->resize(cols->GetNumberOfTuples());
this->Storage->AxisPos.resize(cols->GetNumberOfTuples());
vtkIdType rows = table->GetNumberOfRows();
for (vtkIdType i = 0; i < cols->GetNumberOfTuples(); ++i)
{
vtkstd::vector<float>& col = this->Storage->at(i);
vtkAxis* axis = this->Parent->GetAxis(i);
col.resize(rows);
vtkSmartPointer<vtkDataArray> data =
vtkDataArray::SafeDownCast(table->GetColumnByName(cols->GetValue(i)));
if (!data)
{
if (table->GetColumnByName(cols->GetValue(i))->IsA("vtkStringArray"))
{
// We have a different kind of column - attempt to make it into an enum
vtkStringToCategory* stoc = vtkStringToCategory::New();
stoc->SetInput(table);
stoc->SetInputArrayToProcess(0, 0, 0,
vtkDataObject::FIELD_ASSOCIATION_ROWS,
cols->GetValue(i));
stoc->SetCategoryArrayName("enumPC");
stoc->Update();
vtkTable* table2 = vtkTable::SafeDownCast(stoc->GetOutput());
vtkTable* stringTable = vtkTable::SafeDownCast(stoc->GetOutput(1));
if (table2)
{
data = vtkDataArray::SafeDownCast(table2->GetColumnByName("enumPC"));
}
if (stringTable && stringTable->GetColumnByName("Strings"))
{
vtkStringArray* strings =
vtkStringArray::SafeDownCast(stringTable->GetColumnByName("Strings"));
vtkSmartPointer<vtkDoubleArray> arr =
vtkSmartPointer<vtkDoubleArray>::New();
for (vtkIdType j = 0; j < strings->GetNumberOfTuples(); ++j)
{
arr->InsertNextValue(j);
}
// Now we need to set the range on the string axis
axis->SetTickLabels(strings);
axis->SetTickPositions(arr);
if (strings->GetNumberOfTuples() > 1)
{
axis->SetRange(0.0, strings->GetNumberOfTuples()-1);
}
else
{
axis->SetRange(-0.1, 0.1);
}
axis->Update();
}
stoc->Delete();
}
// If we still don't have a valid data array then skip this column.
if (!data)
{
continue;
}
}
// Also need the range from the appropriate axis, to normalize points
float min = axis->GetMinimum();
float max = axis->GetMaximum();
float scale = 1.0f / (max - min);
for (vtkIdType j = 0; j < rows; ++j)
{
col[j] = (data->GetTuple1(j)-min) * scale;
}
}
this->BuildTime.Modified();
return true;
}
//-----------------------------------------------------------------------------
void vtkPlotParallelCoordinates::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>
*/
#ifndef UAVCAN_NODE_SCHEDULER_HPP_INCLUDED
#define UAVCAN_NODE_SCHEDULER_HPP_INCLUDED
#include <uavcan/error.hpp>
#include <uavcan/util/linked_list.hpp>
#include <uavcan/transport/dispatcher.hpp>
namespace uavcan
{
class UAVCAN_EXPORT Scheduler;
class UAVCAN_EXPORT DeadlineHandler : public LinkedListNode<DeadlineHandler>, Noncopyable
{
MonotonicTime deadline_;
protected:
Scheduler& scheduler_;
explicit DeadlineHandler(Scheduler& scheduler)
: scheduler_(scheduler)
{ }
virtual ~DeadlineHandler() { stop(); }
public:
virtual void handleDeadline(MonotonicTime current) = 0;
void startWithDeadline(MonotonicTime deadline);
void startWithDelay(MonotonicDuration delay);
void stop();
bool isRunning() const;
MonotonicTime getDeadline() const { return deadline_; }
Scheduler& getScheduler() const { return scheduler_; }
};
class UAVCAN_EXPORT DeadlineScheduler : Noncopyable
{
LinkedListRoot<DeadlineHandler> handlers_; // Ordered by deadline, lowest first
public:
void add(DeadlineHandler* mdh);
void remove(DeadlineHandler* mdh);
bool doesExist(const DeadlineHandler* mdh) const;
unsigned getNumHandlers() const { return handlers_.getLength(); }
MonotonicTime pollAndGetMonotonicTime(ISystemClock& sysclock);
MonotonicTime getEarliestDeadline() const;
};
/**
* This class distributes processing time between library components (IO handling, deadline callbacks, ...).
*/
class UAVCAN_EXPORT Scheduler : Noncopyable
{
enum { DefaultDeadlineResolutionMs = 5 };
enum { MinDeadlineResolutionMs = 1 };
enum { MaxDeadlineResolutionMs = 100 };
enum { DefaultCleanupPeriodMs = 1000 };
enum { MinCleanupPeriodMs = 10 };
enum { MaxCleanupPeriodMs = 10000 };
DeadlineScheduler deadline_scheduler_;
Dispatcher dispatcher_;
MonotonicTime prev_cleanup_ts_;
MonotonicDuration deadline_resolution_;
MonotonicDuration cleanup_period_;
bool inside_spin_;
MonotonicTime computeDispatcherSpinDeadline(MonotonicTime spin_deadline) const;
void pollCleanup(MonotonicTime mono_ts, uint32_t num_frames_processed_with_last_spin);
public:
Scheduler(ICanDriver& can_driver, IPoolAllocator& allocator, ISystemClock& sysclock, IOutgoingTransferRegistry& otr)
: dispatcher_(can_driver, allocator, sysclock, otr)
, prev_cleanup_ts_(sysclock.getMonotonic())
, deadline_resolution_(MonotonicDuration::fromMSec(DefaultDeadlineResolutionMs))
, cleanup_period_(MonotonicDuration::fromMSec(DefaultCleanupPeriodMs))
, inside_spin_(false)
{ }
/**
* Spin until the deadline, or until some error occurs.
* Returns negative error code.
*/
int spin(MonotonicTime deadline);
DeadlineScheduler& getDeadlineScheduler() { return deadline_scheduler_; }
Dispatcher& getDispatcher() { return dispatcher_; }
const Dispatcher& getDispatcher() const { return dispatcher_; }
ISystemClock& getSystemClock() { return dispatcher_.getSystemClock(); }
MonotonicTime getMonotonicTime() const { return dispatcher_.getSystemClock().getMonotonic(); }
UtcTime getUtcTime() const { return dispatcher_.getSystemClock().getUtc(); }
/**
* Worst case deadline callback resolution.
* Higher resolution increases CPU usage.
*/
MonotonicDuration getDeadlineResolution() const { return deadline_resolution_; }
void setDeadlineResolution(MonotonicDuration res)
{
res = min(res, MonotonicDuration::fromMSec(MaxDeadlineResolutionMs));
res = max(res, MonotonicDuration::fromMSec(MinDeadlineResolutionMs));
deadline_resolution_ = res;
}
/**
* How often the scheduler will run cleanup (listeners, outgoing transfer registry, ...).
* Cleanup execution time grows linearly with number of listeners and number of items
* in the Outgoing Transfer ID registry.
* Lower period increases CPU usage.
*/
MonotonicDuration getCleanupPeriod() const { return cleanup_period_; }
void setCleanupPeriod(MonotonicDuration period)
{
period = min(period, MonotonicDuration::fromMSec(MaxCleanupPeriodMs));
period = max(period, MonotonicDuration::fromMSec(MinCleanupPeriodMs));
cleanup_period_ = period;
}
};
}
#endif // UAVCAN_NODE_SCHEDULER_HPP_INCLUDED
<commit_msg>Method to generate immediate deadlines in DeadlineHandler<commit_after>/*
* Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>
*/
#ifndef UAVCAN_NODE_SCHEDULER_HPP_INCLUDED
#define UAVCAN_NODE_SCHEDULER_HPP_INCLUDED
#include <uavcan/error.hpp>
#include <uavcan/util/linked_list.hpp>
#include <uavcan/transport/dispatcher.hpp>
namespace uavcan
{
class UAVCAN_EXPORT Scheduler;
class UAVCAN_EXPORT DeadlineHandler : public LinkedListNode<DeadlineHandler>, Noncopyable
{
MonotonicTime deadline_;
protected:
Scheduler& scheduler_;
explicit DeadlineHandler(Scheduler& scheduler)
: scheduler_(scheduler)
{ }
virtual ~DeadlineHandler() { stop(); }
public:
virtual void handleDeadline(MonotonicTime current) = 0;
void startWithDeadline(MonotonicTime deadline);
void startWithDelay(MonotonicDuration delay);
void generateDeadlineImmediately() { startWithDeadline(MonotonicTime::fromUSec(1)); }
void stop();
bool isRunning() const;
MonotonicTime getDeadline() const { return deadline_; }
Scheduler& getScheduler() const { return scheduler_; }
};
class UAVCAN_EXPORT DeadlineScheduler : Noncopyable
{
LinkedListRoot<DeadlineHandler> handlers_; // Ordered by deadline, lowest first
public:
void add(DeadlineHandler* mdh);
void remove(DeadlineHandler* mdh);
bool doesExist(const DeadlineHandler* mdh) const;
unsigned getNumHandlers() const { return handlers_.getLength(); }
MonotonicTime pollAndGetMonotonicTime(ISystemClock& sysclock);
MonotonicTime getEarliestDeadline() const;
};
/**
* This class distributes processing time between library components (IO handling, deadline callbacks, ...).
*/
class UAVCAN_EXPORT Scheduler : Noncopyable
{
enum { DefaultDeadlineResolutionMs = 5 };
enum { MinDeadlineResolutionMs = 1 };
enum { MaxDeadlineResolutionMs = 100 };
enum { DefaultCleanupPeriodMs = 1000 };
enum { MinCleanupPeriodMs = 10 };
enum { MaxCleanupPeriodMs = 10000 };
DeadlineScheduler deadline_scheduler_;
Dispatcher dispatcher_;
MonotonicTime prev_cleanup_ts_;
MonotonicDuration deadline_resolution_;
MonotonicDuration cleanup_period_;
bool inside_spin_;
MonotonicTime computeDispatcherSpinDeadline(MonotonicTime spin_deadline) const;
void pollCleanup(MonotonicTime mono_ts, uint32_t num_frames_processed_with_last_spin);
public:
Scheduler(ICanDriver& can_driver, IPoolAllocator& allocator, ISystemClock& sysclock, IOutgoingTransferRegistry& otr)
: dispatcher_(can_driver, allocator, sysclock, otr)
, prev_cleanup_ts_(sysclock.getMonotonic())
, deadline_resolution_(MonotonicDuration::fromMSec(DefaultDeadlineResolutionMs))
, cleanup_period_(MonotonicDuration::fromMSec(DefaultCleanupPeriodMs))
, inside_spin_(false)
{ }
/**
* Spin until the deadline, or until some error occurs.
* Returns negative error code.
*/
int spin(MonotonicTime deadline);
DeadlineScheduler& getDeadlineScheduler() { return deadline_scheduler_; }
Dispatcher& getDispatcher() { return dispatcher_; }
const Dispatcher& getDispatcher() const { return dispatcher_; }
ISystemClock& getSystemClock() { return dispatcher_.getSystemClock(); }
MonotonicTime getMonotonicTime() const { return dispatcher_.getSystemClock().getMonotonic(); }
UtcTime getUtcTime() const { return dispatcher_.getSystemClock().getUtc(); }
/**
* Worst case deadline callback resolution.
* Higher resolution increases CPU usage.
*/
MonotonicDuration getDeadlineResolution() const { return deadline_resolution_; }
void setDeadlineResolution(MonotonicDuration res)
{
res = min(res, MonotonicDuration::fromMSec(MaxDeadlineResolutionMs));
res = max(res, MonotonicDuration::fromMSec(MinDeadlineResolutionMs));
deadline_resolution_ = res;
}
/**
* How often the scheduler will run cleanup (listeners, outgoing transfer registry, ...).
* Cleanup execution time grows linearly with number of listeners and number of items
* in the Outgoing Transfer ID registry.
* Lower period increases CPU usage.
*/
MonotonicDuration getCleanupPeriod() const { return cleanup_period_; }
void setCleanupPeriod(MonotonicDuration period)
{
period = min(period, MonotonicDuration::fromMSec(MaxCleanupPeriodMs));
period = max(period, MonotonicDuration::fromMSec(MinCleanupPeriodMs));
cleanup_period_ = period;
}
};
}
#endif // UAVCAN_NODE_SCHEDULER_HPP_INCLUDED
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Monteverdi2
Language: C++
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See Copyright.txt for details.
Monteverdi2 is distributed under the CeCILL licence version 2. See
Licence_CeCILL_V2-en.txt or
http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more 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 "mvdDatabaseModel.h"
/*****************************************************************************/
/* INCLUDE SECTION */
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdDatasetModel.h"
#include "mvdI18nApplication.h"
namespace mvd
{
/*
TRANSLATOR mvd::DatabaseModel
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
/* CONSTANTS */
/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION */
/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION */
/*******************************************************************************/
DatabaseModel
::DatabaseModel( QObject* parent ) :
AbstractModel( parent ),
m_DatasetModels(),
m_SelectedDatasetModel( NULL )
{
}
/*******************************************************************************/
DatabaseModel
::~DatabaseModel()
{
}
/*******************************************************************************/
QStringList
DatabaseModel
::QueryDatasetModels() const
{
QDir cacheDir( I18nApplication::ConstInstance()->GetCacheDir() );
QStringList nameFilters;
nameFilters << QString( "*%1" ).arg( I18nApplication::DATASET_EXT );
/*
cacheDir.setNameFilters( nameFilters );
cacheDir.setFilter( QDir::Dirs | QDir::NoDotAndDotDot );
cacheDir.setSorting( QDir::Name );
*/
return cacheDir.entryList(
nameFilters,
QDir::Dirs | QDir::NoDotAndDotDot,
QDir::Name
);
}
/*******************************************************************************/
DatasetModel*
DatabaseModel
::SelectDatasetModel( const DatasetId& id )
{
qDebug() << this << "::SelectDatasetModel(" << id << ")";
// Find dataset model or interrupt by exception.
DatasetModel* datasetModel = FindDatasetModel( id );
assert( datasetModel!=NULL );
try
{
// Load dataset sub-models.
datasetModel->LoadImageModels( -1, -1 );
// If dataset model has been loaded, select it.
SetSelectedDatasetModel( datasetModel );
}
catch( std::exception& exc )
{
throw exc;
}
// Return loaded and selected dataset model.
return datasetModel;
}
/*******************************************************************************/
void
DatabaseModel
::ReleaseDatasetModel( const DatasetId& id )
{
qDebug() << this << "::ReleaseDatasetModel(" << id << ")";
// Find (key, value) pair.
DatasetModelMap::iterator it( DatasetModelIterator( id ) );
delete it.value();
it.value() = NULL;
}
/*******************************************************************************/
DatasetModel*
DatabaseModel
::NewDatasetModel( const DatasetId& id )
{
qDebug() << this << "::NewDatasetModel(" << id << ")";
// Find dataset model or interrupt by exception.
DatasetModel* datasetModel = NULL;
// Otherwise, load it from disk.
try
{
// Create empty dataset model.
datasetModel = new DatasetModel( this );
// Build dataset model.
assert( I18nApplication::ConstInstance() );
DatasetModel::BuildContext context(
I18nApplication::ConstInstance()->GetCacheDir().path(),
id,
false
);
datasetModel->BuildModel( &context );
}
catch( std::exception& exc )
{
// If loading was interrupted, delete allocated memory.
delete datasetModel;
datasetModel = NULL;
// And forward interrupting exception.
throw exc;
}
// Return loaded and selected dataset model.
return datasetModel;
}
/*******************************************************************************/
void
DatabaseModel
::virtual_BuildModel( void* context )
{
InitializeDatasetModels();
}
/**************************************************************************************************************************************************************/
/*******************************************************************************/
void
DatabaseModel
::InitializeDatasetModels()
{
QStringList datasets( QueryDatasetModels() );
ClearDatasetModels();
for( QStringList::const_iterator it( datasets.begin() );
it!=datasets.end();
++it )
{
try
{
DatasetModel* datasetModel = NewDatasetModel( *it );
assert( datasetModel!=NULL );
m_DatasetModels.insert( *it, datasetModel );
}
catch( std::exception& exc )
{
throw exc;
}
}
}
/*******************************************************************************/
void
DatabaseModel
::ClearDatasetModels()
{
while( !m_DatasetModels.empty() )
{
DatasetModelMap::iterator it( m_DatasetModels.begin() );
delete it.value();
it.value() = NULL;
it = m_DatasetModels.erase( it );
}
}
/*******************************************************************************/
/* SLOTS */
/*******************************************************************************/
void
DatabaseModel
::OnDatasetToDeleteSelected( const QString& id)
{
// TODO : pop up a Dialog widget ??
// In DatabaseModel : delete from the map of datasets
// In DatasetModel : delete from disk
// redraw the database widget
}
} // end namespace 'mvd'
<commit_msg>ENH: add verbosity<commit_after>/*=========================================================================
Program: Monteverdi2
Language: C++
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See Copyright.txt for details.
Monteverdi2 is distributed under the CeCILL licence version 2. See
Licence_CeCILL_V2-en.txt or
http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more 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 "mvdDatabaseModel.h"
/*****************************************************************************/
/* INCLUDE SECTION */
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdDatasetModel.h"
#include "mvdI18nApplication.h"
namespace mvd
{
/*
TRANSLATOR mvd::DatabaseModel
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
/* CONSTANTS */
/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION */
/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION */
/*******************************************************************************/
DatabaseModel
::DatabaseModel( QObject* parent ) :
AbstractModel( parent ),
m_DatasetModels(),
m_SelectedDatasetModel( NULL )
{
}
/*******************************************************************************/
DatabaseModel
::~DatabaseModel()
{
}
/*******************************************************************************/
QStringList
DatabaseModel
::QueryDatasetModels() const
{
QDir cacheDir( I18nApplication::ConstInstance()->GetCacheDir() );
QStringList nameFilters;
nameFilters << QString( "*%1" ).arg( I18nApplication::DATASET_EXT );
/*
cacheDir.setNameFilters( nameFilters );
cacheDir.setFilter( QDir::Dirs | QDir::NoDotAndDotDot );
cacheDir.setSorting( QDir::Name );
*/
return cacheDir.entryList(
nameFilters,
QDir::Dirs | QDir::NoDotAndDotDot,
QDir::Name
);
}
/*******************************************************************************/
DatasetModel*
DatabaseModel
::SelectDatasetModel( const DatasetId& id )
{
qDebug() << this << "::SelectDatasetModel(" << id << ")";
// Find dataset model or interrupt by exception.
DatasetModel* datasetModel = FindDatasetModel( id );
assert( datasetModel!=NULL );
try
{
// Load dataset sub-models.
datasetModel->LoadImageModels( -1, -1 );
// If dataset model has been loaded, select it.
SetSelectedDatasetModel( datasetModel );
}
catch( std::exception& exc )
{
throw exc;
}
// Return loaded and selected dataset model.
return datasetModel;
}
/*******************************************************************************/
void
DatabaseModel
::ReleaseDatasetModel( const DatasetId& id )
{
qDebug() << this << "::ReleaseDatasetModel(" << id << ")";
// Find (key, value) pair.
DatasetModelMap::iterator it( DatasetModelIterator( id ) );
delete it.value();
it.value() = NULL;
}
/*******************************************************************************/
DatasetModel*
DatabaseModel
::NewDatasetModel( const DatasetId& id )
{
qDebug() << this << "::NewDatasetModel(" << id << ")";
// Find dataset model or interrupt by exception.
DatasetModel* datasetModel = NULL;
// Otherwise, load it from disk.
try
{
// Create empty dataset model.
datasetModel = new DatasetModel( this );
// Build dataset model.
assert( I18nApplication::ConstInstance() );
DatasetModel::BuildContext context(
I18nApplication::ConstInstance()->GetCacheDir().path(),
id,
false
);
datasetModel->BuildModel( &context );
}
catch( std::exception& exc )
{
// If loading was interrupted, delete allocated memory.
delete datasetModel;
datasetModel = NULL;
// And forward interrupting exception.
throw exc;
}
// Return loaded and selected dataset model.
return datasetModel;
}
/*******************************************************************************/
void
DatabaseModel
::virtual_BuildModel( void* context )
{
InitializeDatasetModels();
}
/**************************************************************************************************************************************************************/
/*******************************************************************************/
void
DatabaseModel
::InitializeDatasetModels()
{
QStringList datasets( QueryDatasetModels() );
ClearDatasetModels();
for( QStringList::const_iterator it( datasets.begin() );
it!=datasets.end();
++it )
{
try
{
DatasetModel* datasetModel = NewDatasetModel( *it );
assert( datasetModel!=NULL );
m_DatasetModels.insert( *it, datasetModel );
}
catch( std::exception& exc )
{
throw exc;
}
}
}
/*******************************************************************************/
void
DatabaseModel
::ClearDatasetModels()
{
while( !m_DatasetModels.empty() )
{
DatasetModelMap::iterator it( m_DatasetModels.begin() );
delete it.value();
it.value() = NULL;
it = m_DatasetModels.erase( it );
}
}
/*******************************************************************************/
/* SLOTS */
/*******************************************************************************/
void
DatabaseModel
::OnDatasetToDeleteSelected( const QString& id)
{
qDebug() << this << " ::OnDatasetToDeleteSelected (WIP) -> Dataset to delete : "<< id;
// TODO : pop up a Dialog widget ??
// In DatabaseModel : delete from the map of datasets
// In DatasetModel : delete from disk
// redraw the database widget
}
} // end namespace 'mvd'
<|endoftext|>
|
<commit_before>#include "transport_sweeper.hpp"
#include <cmath>
#include <iostream>
using std::endl;
using std::cout;
namespace mocc {
real_t TransportSweeper::total_fission( bool old ) const {
real_t tfis = 0.0;
const auto &flux = old ? flux_old_: flux_;
for( auto &xsr: *xs_mesh_ ) {
for( int ig=0; ig<n_group_; ig++ ) {
real_t xsnf = xsr.xsmacnf(ig);
for (auto &ireg: xsr.reg() ) {
tfis += flux((int)ireg, (int)ig)*vol_[ireg]*xsnf;
}
}
}
return tfis;
}
void TransportSweeper::calc_fission_source( real_t k,
ArrayB1& fission_source ) const {
real_t rkeff = 1.0/k;
fission_source = 0.0;
for( auto &xsr: *xs_mesh_ ) {
const auto &xsnf = xsr.xsmacnf();
for( int ig=0; ig<(int)n_group_; ig++ ) {
for( auto &ireg: xsr.reg() ) {
fission_source(ireg) += rkeff * xsnf[ig] *
flux_(ireg, ig);
}
}
}
return;
}
ArrayB3 TransportSweeper::pin_powers() const {
assert(n_reg_ == (int)core_mesh_->n_reg());
ArrayB3 powers(core_mesh_->nz(), core_mesh_->ny(), core_mesh_->nx());
powers = 0.0;
// This isnt the most efficient way to do this, memory-wise, but its
// quick and simple. Calculate volume x flux x kappa-fission for all
// flat source regions, then reduce to the pin mesh.
ArrayB1 fsr_pow(n_reg_);
fsr_pow = 0.0;
for( const auto &xsr: *xs_mesh_ ) {
for( int ig=0; ig<n_group_; ig++ ) {
for( auto ireg: xsr.reg() ) {
fsr_pow(ireg) += flux_(ireg, ig) * xsr.xsmackf(ig) *
vol_[ireg];
}
}
}
int ipin = 0;
int ireg = 0;
real_t tot_pow = 0.0;
for( const auto pin: *core_mesh_ ) {
const PinMesh &pm = pin->mesh();
Position pos = core_mesh_->pin_position(ipin);
for( int ir=0; ir<pm.n_reg(); ir++ ) {
tot_pow += fsr_pow(ireg);
powers(pos.z, pos.y, pos.x) += fsr_pow(ireg);
ireg++;
}
ipin++;
}
// Normalize!
tot_pow = powers.size()/tot_pow;
for( auto &v: powers ) {
v *= tot_pow;
}
return powers;
}
ArrayB2 TransportSweeper::get_pin_flux() const {
assert( core_mesh_ );
ArrayB2 flux( core_mesh_->n_pin(), n_group_ );
auto flux_it = flux.begin();
for( int ig=0; ig<n_group_; ig++ ) {
ArrayB1 flux_1g( flux(blitz::Range::all(), ig) );
this->get_pin_flux_1g( ig, flux_1g );
}
return flux;
}
real_t TransportSweeper::flux_residual() const {
real_t r = 0.0;
auto it = flux_.begin();
auto it_old = flux_.begin();
auto end = flux_.end();
while( it != end ) {
real_t e = *it - *it_old;
r += e*e;
++it;
++it_old;
}
return std::sqrt(r);
}
}
<commit_msg>a fixed that was forgotten<commit_after>#include "transport_sweeper.hpp"
#include <cmath>
#include <iostream>
using std::endl;
using std::cout;
namespace mocc {
real_t TransportSweeper::total_fission( bool old ) const {
real_t tfis = 0.0;
const auto &flux = old ? flux_old_: flux_;
for( auto &xsr: *xs_mesh_ ) {
for( int ig=0; ig<n_group_; ig++ ) {
real_t xsnf = xsr.xsmacnf(ig);
for (auto &ireg: xsr.reg() ) {
tfis += flux((int)ireg, (int)ig)*vol_[ireg]*xsnf;
}
}
}
return tfis;
}
void TransportSweeper::calc_fission_source( real_t k,
ArrayB1& fission_source ) const {
real_t rkeff = 1.0/k;
fission_source = 0.0;
for( auto &xsr: *xs_mesh_ ) {
const auto &xsnf = xsr.xsmacnf();
for( int ig=0; ig<(int)n_group_; ig++ ) {
for( auto &ireg: xsr.reg() ) {
fission_source(ireg) += rkeff * xsnf[ig] *
flux_(ireg, ig);
}
}
}
return;
}
ArrayB3 TransportSweeper::pin_powers() const {
assert(n_reg_ == (int)core_mesh_->n_reg());
ArrayB3 powers(core_mesh_->nz(), core_mesh_->ny(), core_mesh_->nx());
powers = 0.0;
// This isnt the most efficient way to do this, memory-wise, but its
// quick and simple. Calculate volume x flux x kappa-fission for all
// flat source regions, then reduce to the pin mesh.
ArrayB1 fsr_pow(n_reg_);
fsr_pow = 0.0;
for( const auto &xsr: *xs_mesh_ ) {
for( int ig=0; ig<n_group_; ig++ ) {
for( auto ireg: xsr.reg() ) {
fsr_pow(ireg) += flux_(ireg, ig) * xsr.xsmackf(ig) *
vol_[ireg];
}
}
}
int ipin = 0;
int ireg = 0;
real_t tot_pow = 0.0;
for( const auto pin: *core_mesh_ ) {
const PinMesh &pm = pin->mesh();
Position pos = core_mesh_->pin_position(ipin);
for( int ir=0; ir<pm.n_reg(); ir++ ) {
tot_pow += fsr_pow(ireg);
powers(pos.z, pos.y, pos.x) += fsr_pow(ireg);
ireg++;
}
ipin++;
}
// Normalize!
tot_pow = powers.size()/tot_pow;
for( auto &v: powers ) {
v *= tot_pow;
}
return powers;
}
ArrayB2 TransportSweeper::get_pin_flux() const {
assert( core_mesh_ );
ArrayB2 flux( core_mesh_->n_pin(), n_group_ );
auto flux_it = flux.begin();
for( int ig=0; ig<n_group_; ig++ ) {
ArrayB1 flux_1g( flux(blitz::Range::all(), ig) );
this->get_pin_flux_1g( ig, flux_1g );
}
return flux;
}
real_t TransportSweeper::flux_residual() const {
real_t r = 0.0;
auto it = flux_.begin();
auto it_old = flux_old_.begin();
auto end = flux_.end();
while( it != end ) {
real_t e = *it - *it_old;
r += e*e;
++it;
++it_old;
}
return std::sqrt(r);
}
}
<|endoftext|>
|
<commit_before>#include "mitkOpenGLRenderer.h"
#include "Mapper.h"
#include "mitkImageMapper2D.h"
#include "BaseVtkMapper2D.h"
#include "BaseVtkMapper3D.h"
#include "LevelWindow.h"
#include "mitkVtkInteractorCameraController.h"
#include "mitkVtkRenderWindow.h"
#include "mitkRenderWindow.h"
#include <vtkRenderer.h>
#include <vtkLight.h>
#include <vtkLightKit.h>
#include <vtkRenderWindow.h>
#include <vtkTransform.h>
#include "PlaneGeometry.h"
#include "mitkProperties.h"
#include <queue>
#include <utility>
//##ModelId=3E33ECF301AD
mitk::OpenGLRenderer::OpenGLRenderer() : m_VtkMapperPresent(false)
{
m_CameraController=NULL;
m_CameraController = VtkInteractorCameraController::New();
m_CameraController->AddRenderer(this);
m_DataChangedCommand = itk::MemberCommand<mitk::OpenGLRenderer>::New();
#ifdef WIN32
m_DataChangedCommand->SetCallbackFunction(this, mitk::OpenGLRenderer::DataChangedEvent);
#else
m_DataChangedCommand->SetCallbackFunction(this, &mitk::OpenGLRenderer::DataChangedEvent);
#endif
}
//##ModelId=3E3D28AB0018
void mitk::OpenGLRenderer::SetData(mitk::DataTreeIterator* iterator)
{
if(iterator!=GetData())
{
bool geometry_is_set=false;
if(m_DataTreeIterator!=NULL)
{
//remove old connections
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
while(it->hasNext())
{
it->next();
BaseData::Pointer data=it->get()->GetData();
}
delete it;
}
BaseRenderer::SetData(iterator);
if (iterator != NULL)
{
//initialize world geometry: use first slice of first node containing an image
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
while(it->hasNext())
{
it->next();
BaseData::Pointer data=it->get()->GetData();
if(data.IsNotNull())
{
if(geometry_is_set==false)
{
Image::Pointer image = dynamic_cast<Image*>(data.GetPointer());
if(image.IsNotNull())
{
SetWorldGeometry(image->GetGeometry2D(0, 0));
geometry_is_set=true;
}
}
//@todo add connections
//data->AddObserver(itk::EndEvent(), m_DataChangedCommand);
}
}
delete it;
}
//update the vtk-based mappers
Update(); //this is only called to check, whether we have vtk-based mappers!
UpdateVtkActors();
Modified();
}
}
//##ModelId=3ED91D060305
void mitk::OpenGLRenderer::UpdateVtkActors()
{
VtkInteractorCameraController* vicc=dynamic_cast<VtkInteractorCameraController*>(m_CameraController.GetPointer());
if (m_VtkMapperPresent == false)
{
if(vicc!=NULL)
vicc->GetVtkInteractor()->Disable();
return;
}
if(vicc!=NULL)
vicc->GetVtkInteractor()->Enable();
// m_LightKit->RemoveLightsFromRenderer(this->m_VtkRenderer);
// m_MitkVtkRenderWindow->RemoveRenderer(m_VtkRenderer);
// m_VtkRenderer->Delete();
if(m_VtkRenderer==NULL)
{
m_VtkRenderer = vtkRenderer::New();
m_VtkRenderer->SetLayer(0);
m_MitkVtkRenderWindow->AddRenderer( this->m_VtkRenderer );
}
m_VtkRenderer->RemoveAllProps();
//strange: when using a simple light, the backface of the planes are not shown (regardless of SetNumberOfLayers)
//m_Light->Delete();
//m_Light = vtkLight::New();
//m_VtkRenderer->AddLight( m_Light );
if(m_LightKit!=NULL)
{
m_LightKit = vtkLightKit::New();
m_LightKit->AddLightsToRenderer(m_VtkRenderer);
}
// try
if (m_DataTreeIterator != NULL)
{
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
while(it->hasNext())
{
it->next();
mitk::Mapper::Pointer mapper = it->get()->GetMapper(m_MapperID);
if(mapper.IsNotNull())
{
BaseVtkMapper2D* anVtkMapper2D;
anVtkMapper2D=dynamic_cast<BaseVtkMapper2D*>(mapper.GetPointer());
if(anVtkMapper2D != NULL)
{
anVtkMapper2D->Update(this);
m_VtkRenderer->AddProp(anVtkMapper2D->GetProp());
}
else
{
BaseVtkMapper3D* anVtkMapper3D;
anVtkMapper3D=dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer());
if(anVtkMapper3D != NULL)
{
anVtkMapper3D->Update(this);
m_VtkRenderer->AddProp(anVtkMapper3D->GetProp());
}
}
}
}
delete it;
}
// catch( ::itk::ExceptionObject ee)
// {
// printf("%s\n",ee.what());
//// itkGenericOutputMacro(ee->what());
// }
// catch( ...)
// {
// printf("test\n");
// }
}
//##ModelId=3E330D260255
void mitk::OpenGLRenderer::Update()
{
if(m_DataTreeIterator == NULL) return;
m_VtkMapperPresent=false;
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
while(it->hasNext())
{
it->next();
// mitk::LevelWindow lw;
//unsigned int dummy[] = {10,10,10};
//Geometry3D geometry(3,dummy);
mitk::Mapper::Pointer mapper = it->get()->GetMapper(m_MapperID);
if(mapper.IsNotNull())
{
Mapper2D* mapper2d=dynamic_cast<Mapper2D*>(mapper.GetPointer());
if(mapper2d != NULL)
{
BaseVtkMapper2D* vtkmapper2d=dynamic_cast<BaseVtkMapper2D*>(mapper.GetPointer());
if(vtkmapper2d != NULL)
{
vtkmapper2d->Update(this);
m_VtkMapperPresent=true;
}
else
mapper2d->Update();
//ImageMapper2D* imagemapper2d=dynamic_cast<ImageMapper2D*>(mapper.GetPointer());
}
else
{
BaseVtkMapper3D* vtkmapper3d=dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer());
if(vtkmapper3d != NULL)
{
vtkmapper3d->Update(this);
m_VtkMapperPresent=true;
}
}
}
}
delete it;
Modified();
m_LastUpdateTime=GetMTime();
}
//##ModelId=3E330D2903CC
void mitk::OpenGLRenderer::Render()
{
//if we do not have any data, we do nothing else but clearing our window
if(GetData() == NULL)
{
glClear(GL_COLOR_BUFFER_BIT);
return;
}
//has someone transformed our worldgeometry-node? if so, incorporate this transform into
//the worldgeometry itself and reset the transform of the node to identity
/* if(m_WorldGeometryTransformTime<m_WorldGeometryNode->GetVtkTransform()->GetMTime())
{
vtkTransform *i;
m_WorldGeometry->TransformGeometry(m_WorldGeometryNode->GetVtkTransform());
m_WorldGeometryNode->GetVtkTransform()->Identity();
m_WorldGeometryTransformTime=GetWorldGeometryNode()->GetVtkTransform()->GetMTime();
}
*/
//has the data tree been changed?
if(dynamic_cast<mitk::DataTree*>(GetData()->getTree()) == NULL ) return;
// if(m_LastUpdateTime<((mitk::DataTree*)GetData()->getTree())->GetMTime())
if(m_LastUpdateTime < dynamic_cast<mitk::DataTree*>(GetData()->getTree())->GetMTime() )
{
//yes: update vtk-actors
Update();
UpdateVtkActors();
}
else
//has anything else changed (geometry to display, etc.)?
if (m_LastUpdateTime<GetMTime() ||
m_LastUpdateTime<GetDisplayGeometry()->GetMTime() ||
m_LastUpdateTime<GetDisplayGeometry()->GetWorldGeometry()->GetMTime())
{
//std::cout << "OpenGLRenderer calling its update..." << std::endl;
Update();
}
else
if(m_MapperID==2)
{ //@todo in 3D mode wird sonst nix geupdated, da z.Z. weder camera noch nderung des Baums beachtet wird!!!
Update();
}
glClear(GL_COLOR_BUFFER_BIT);
//PlaneGeometry* myPlaneGeom =
// dynamic_cast<PlaneGeometry *>((mitk::Geometry2D*)(GetWorldGeometry()));
glViewport (0, 0, m_Size[0], m_Size[1]);
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluOrtho2D( 0.0, m_Size[0], 0.0, m_Size[1] );
glMatrixMode( GL_MODELVIEW );
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
mitk::DataTree::Pointer tree = dynamic_cast <mitk::DataTree *> (it->getTree());
// std::cout << "Render:: tree: " << *tree << std::endl;
typedef std::pair<int, GLMapper2D*> LayerMapperPair;
std::priority_queue<LayerMapperPair> layers;
int mapperNo = 0;
while(it->hasNext())
{
it->next();
mitk::DataTreeNode::Pointer node = it->get();
mitk::Mapper::Pointer mapper = node->GetMapper(m_MapperID);
if(mapper.IsNotNull())
{
GLMapper2D* mapper2d=dynamic_cast<GLMapper2D*>(mapper.GetPointer());
if(mapper2d!=NULL)
{
// mapper without a layer property are painted first
int layer=-1;
node->GetIntProperty("layer", layer, this);
// pushing negative layer value, since default sort for
// priority_queue is lessthan
layers.push(LayerMapperPair(- (layer<<16) - mapperNo ,mapper2d));
mapperNo++;
}
}
}
delete it;
while (!layers.empty()) {
layers.top().second->Paint(this);
layers.pop();
}
if(m_VtkMapperPresent) {
m_MitkVtkRenderWindow->MitkRender();
}
else
m_RenderWindow->swapBuffers();
}
/*!
\brief Initialize the OpenGLRenderer
This method is called from the two Constructors
*/
void mitk::OpenGLRenderer::InitRenderer(mitk::RenderWindow* renderwindow)
{
BaseRenderer::InitRenderer(renderwindow);
m_InitNeeded = true;
m_ResizeNeeded = true;
m_MitkVtkRenderWindow = mitk::VtkRenderWindow::New();
m_MitkVtkRenderWindow->SetMitkRenderer(this);
/**@todo SetNumberOfLayers commented out, because otherwise the backface of the planes are not shown (only, when a light is added).
* But we need SetNumberOfLayers(2) later, when we want to prevent vtk to clear the widget before it renders (i.e., when we render something in the scene before vtk).
*/
//m_MitkVtkRenderWindow->SetNumberOfLayers(2);
m_VtkRenderer = vtkRenderer::New();
m_MitkVtkRenderWindow->AddRenderer( m_VtkRenderer );
//strange: when using a simple light, the backface of the planes are not shown (regardless of SetNumberOfLayers)
//m_Light = vtkLight::New();
//m_VtkRenderer->AddLight( m_Light );
m_LightKit = vtkLightKit::New();
m_LightKit->AddLightsToRenderer(m_VtkRenderer);
if(m_CameraController)
((VtkInteractorCameraController*)m_CameraController.GetPointer())->SetRenderWindow(m_MitkVtkRenderWindow);
//we should disable vtk doublebuffering, but then it doesn't work
//m_MitkVtkRenderWindow->SwapBuffersOff();
}
/*!
\brief Destructs the OpenGLRenderer.
*/
//##ModelId=3E33ECF301B7
mitk::OpenGLRenderer::~OpenGLRenderer() {
m_VtkRenderer->Delete();
m_MitkVtkRenderWindow->Delete();
}
/*!
\brief Initialize the OpenGL Window
*/
//##ModelId=3E33145B0096
void mitk::OpenGLRenderer::Initialize( ) {
glClearColor(0.0, 0.0, 0.0, 1.0);
glColor3f(1.0, 0.0, 0.0);
}
/*!
\brief Resize the OpenGL Window
*/
//##ModelId=3E33145B00D2
void mitk::OpenGLRenderer::Resize(int w, int h)
{
glViewport (0, 0, w, h);
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluOrtho2D( 0.0, w, 0.0, h );
glMatrixMode( GL_MODELVIEW );
BaseRenderer::Resize(w, h);
Update();
// m_MitkVtkRenderWindow->SetSize(w,h); //@FIXME?
}
/*!
\brief Render the scene
*/
//##ModelId=3E33145B005A
void mitk::OpenGLRenderer::Paint( )
{
// glFlush();
// m_RenderWindow->swapBuffers();
Render();
}
//##ModelId=3E3314B0005C
void mitk::OpenGLRenderer::SetWindowId(void * id)
{
m_MitkVtkRenderWindow->SetWindowId( id );
}
//##ModelId=3E3799420227
void mitk::OpenGLRenderer::InitSize(int w, int h)
{
m_MitkVtkRenderWindow->SetSize(w,h);
GetDisplayGeometry()->Fit();
Modified();
Update();
}
//##ModelId=3EF59AD20235
void mitk::OpenGLRenderer::SetMapperID(const MapperSlotId mapperId)
{
Superclass::SetMapperID(mapperId);
Update();
UpdateVtkActors();
}
//##ModelId=3EF162760271
void mitk::OpenGLRenderer::MakeCurrent()
{
if(m_RenderWindow!=NULL)
{
m_RenderWindow->MakeCurrent();
}
}
void mitk::OpenGLRenderer::DataChangedEvent(const itk::Object *caller, const itk::EventObject &event)
{
if(m_RenderWindow!=NULL)
{
m_RenderWindow->Update();
}
}<commit_msg>correct initialization<commit_after>#include "mitkOpenGLRenderer.h"
#include "Mapper.h"
#include "mitkImageMapper2D.h"
#include "BaseVtkMapper2D.h"
#include "BaseVtkMapper3D.h"
#include "LevelWindow.h"
#include "mitkVtkInteractorCameraController.h"
#include "mitkVtkRenderWindow.h"
#include "mitkRenderWindow.h"
#include <vtkRenderer.h>
#include <vtkLight.h>
#include <vtkLightKit.h>
#include <vtkRenderWindow.h>
#include <vtkTransform.h>
#include "PlaneGeometry.h"
#include "mitkProperties.h"
#include <queue>
#include <utility>
//##ModelId=3E33ECF301AD
mitk::OpenGLRenderer::OpenGLRenderer() : m_VtkMapperPresent(false)
{
m_CameraController=NULL;
m_CameraController = VtkInteractorCameraController::New();
m_CameraController->AddRenderer(this);
m_DataChangedCommand = itk::MemberCommand<mitk::OpenGLRenderer>::New();
#ifdef WIN32
m_DataChangedCommand->SetCallbackFunction(this, mitk::OpenGLRenderer::DataChangedEvent);
#else
m_DataChangedCommand->SetCallbackFunction(this, &mitk::OpenGLRenderer::DataChangedEvent);
#endif
}
//##ModelId=3E3D28AB0018
void mitk::OpenGLRenderer::SetData(mitk::DataTreeIterator* iterator)
{
if(iterator!=GetData())
{
bool geometry_is_set=false;
if(m_DataTreeIterator!=NULL)
{
//remove old connections
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
while(it->hasNext())
{
it->next();
BaseData::Pointer data=it->get()->GetData();
}
delete it;
}
BaseRenderer::SetData(iterator);
if (iterator != NULL)
{
//initialize world geometry: use first slice of first node containing an image
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
while(it->hasNext())
{
it->next();
BaseData::Pointer data=it->get()->GetData();
if(data.IsNotNull())
{
if(geometry_is_set==false)
{
Image::Pointer image = dynamic_cast<Image*>(data.GetPointer());
if(image.IsNotNull())
{
SetWorldGeometry(image->GetGeometry2D(0, 0));
geometry_is_set=true;
}
}
//@todo add connections
//data->AddObserver(itk::EndEvent(), m_DataChangedCommand);
}
}
delete it;
}
//update the vtk-based mappers
Update(); //this is only called to check, whether we have vtk-based mappers!
UpdateVtkActors();
Modified();
}
}
//##ModelId=3ED91D060305
void mitk::OpenGLRenderer::UpdateVtkActors()
{
VtkInteractorCameraController* vicc=dynamic_cast<VtkInteractorCameraController*>(m_CameraController.GetPointer());
if (m_VtkMapperPresent == false)
{
if(vicc!=NULL)
vicc->GetVtkInteractor()->Disable();
return;
}
if(vicc!=NULL)
vicc->GetVtkInteractor()->Enable();
// m_LightKit->RemoveLightsFromRenderer(this->m_VtkRenderer);
// m_MitkVtkRenderWindow->RemoveRenderer(m_VtkRenderer);
// m_VtkRenderer->Delete();
if(m_VtkRenderer==NULL)
{
m_VtkRenderer = vtkRenderer::New();
m_VtkRenderer->SetLayer(0);
m_MitkVtkRenderWindow->AddRenderer( this->m_VtkRenderer );
}
m_VtkRenderer->RemoveAllProps();
//strange: when using a simple light, the backface of the planes are not shown (regardless of SetNumberOfLayers)
//m_Light->Delete();
//m_Light = vtkLight::New();
//m_VtkRenderer->AddLight( m_Light );
if(m_LightKit!=NULL)
{
m_LightKit = vtkLightKit::New();
m_LightKit->AddLightsToRenderer(m_VtkRenderer);
}
// try
if (m_DataTreeIterator != NULL)
{
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
while(it->hasNext())
{
it->next();
mitk::Mapper::Pointer mapper = it->get()->GetMapper(m_MapperID);
if(mapper.IsNotNull())
{
BaseVtkMapper2D* anVtkMapper2D;
anVtkMapper2D=dynamic_cast<BaseVtkMapper2D*>(mapper.GetPointer());
if(anVtkMapper2D != NULL)
{
anVtkMapper2D->Update(this);
m_VtkRenderer->AddProp(anVtkMapper2D->GetProp());
}
else
{
BaseVtkMapper3D* anVtkMapper3D;
anVtkMapper3D=dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer());
if(anVtkMapper3D != NULL)
{
anVtkMapper3D->Update(this);
m_VtkRenderer->AddProp(anVtkMapper3D->GetProp());
}
}
}
}
delete it;
}
// catch( ::itk::ExceptionObject ee)
// {
// printf("%s\n",ee.what());
//// itkGenericOutputMacro(ee->what());
// }
// catch( ...)
// {
// printf("test\n");
// }
}
//##ModelId=3E330D260255
void mitk::OpenGLRenderer::Update()
{
if(m_DataTreeIterator == NULL) return;
m_VtkMapperPresent=false;
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
while(it->hasNext())
{
it->next();
// mitk::LevelWindow lw;
//unsigned int dummy[] = {10,10,10};
//Geometry3D geometry(3,dummy);
mitk::Mapper::Pointer mapper = it->get()->GetMapper(m_MapperID);
if(mapper.IsNotNull())
{
Mapper2D* mapper2d=dynamic_cast<Mapper2D*>(mapper.GetPointer());
if(mapper2d != NULL)
{
BaseVtkMapper2D* vtkmapper2d=dynamic_cast<BaseVtkMapper2D*>(mapper.GetPointer());
if(vtkmapper2d != NULL)
{
vtkmapper2d->Update(this);
m_VtkMapperPresent=true;
}
else
mapper2d->Update();
//ImageMapper2D* imagemapper2d=dynamic_cast<ImageMapper2D*>(mapper.GetPointer());
}
else
{
BaseVtkMapper3D* vtkmapper3d=dynamic_cast<BaseVtkMapper3D*>(mapper.GetPointer());
if(vtkmapper3d != NULL)
{
vtkmapper3d->Update(this);
m_VtkMapperPresent=true;
}
}
}
}
delete it;
Modified();
m_LastUpdateTime=GetMTime();
}
//##ModelId=3E330D2903CC
void mitk::OpenGLRenderer::Render()
{
//if we do not have any data, we do nothing else but clearing our window
if(GetData() == NULL)
{
glClear(GL_COLOR_BUFFER_BIT);
if(m_VtkMapperPresent) {
// m_MitkVtkRenderWindow->MitkRender();
} else
m_RenderWindow->swapBuffers();
return;
}
//has someone transformed our worldgeometry-node? if so, incorporate this transform into
//the worldgeometry itself and reset the transform of the node to identity
/* if(m_WorldGeometryTransformTime<m_WorldGeometryNode->GetVtkTransform()->GetMTime())
{
vtkTransform *i;
m_WorldGeometry->TransformGeometry(m_WorldGeometryNode->GetVtkTransform());
m_WorldGeometryNode->GetVtkTransform()->Identity();
m_WorldGeometryTransformTime=GetWorldGeometryNode()->GetVtkTransform()->GetMTime();
}
*/
//has the data tree been changed?
if(dynamic_cast<mitk::DataTree*>(GetData()->getTree()) == NULL ) return;
// if(m_LastUpdateTime<((mitk::DataTree*)GetData()->getTree())->GetMTime())
if(m_LastUpdateTime < dynamic_cast<mitk::DataTree*>(GetData()->getTree())->GetMTime() )
{
//yes: update vtk-actors
Update();
UpdateVtkActors();
}
else
//has anything else changed (geometry to display, etc.)?
if (m_LastUpdateTime<GetMTime() ||
m_LastUpdateTime<GetDisplayGeometry()->GetMTime() ||
m_LastUpdateTime<GetDisplayGeometry()->GetWorldGeometry()->GetMTime())
{
//std::cout << "OpenGLRenderer calling its update..." << std::endl;
Update();
}
else
if(m_MapperID==2)
{ //@todo in 3D mode wird sonst nix geupdated, da z.Z. weder camera noch nderung des Baums beachtet wird!!!
Update();
}
glClear(GL_COLOR_BUFFER_BIT);
//PlaneGeometry* myPlaneGeom =
// dynamic_cast<PlaneGeometry *>((mitk::Geometry2D*)(GetWorldGeometry()));
glViewport (0, 0, m_Size[0], m_Size[1]);
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluOrtho2D( 0.0, m_Size[0], 0.0, m_Size[1] );
glMatrixMode( GL_MODELVIEW );
mitk::DataTreeIterator* it=m_DataTreeIterator->clone();
mitk::DataTree::Pointer tree = dynamic_cast <mitk::DataTree *> (it->getTree());
// std::cout << "Render:: tree: " << *tree << std::endl;
typedef std::pair<int, GLMapper2D*> LayerMapperPair;
std::priority_queue<LayerMapperPair> layers;
int mapperNo = 0;
while(it->hasNext())
{
it->next();
mitk::DataTreeNode::Pointer node = it->get();
mitk::Mapper::Pointer mapper = node->GetMapper(m_MapperID);
if(mapper.IsNotNull())
{
GLMapper2D* mapper2d=dynamic_cast<GLMapper2D*>(mapper.GetPointer());
if(mapper2d!=NULL)
{
// mapper without a layer property are painted first
int layer=-1;
node->GetIntProperty("layer", layer, this);
// pushing negative layer value, since default sort for
// priority_queue is lessthan
layers.push(LayerMapperPair(- (layer<<16) - mapperNo ,mapper2d));
mapperNo++;
}
}
}
delete it;
while (!layers.empty()) {
layers.top().second->Paint(this);
layers.pop();
}
if(m_VtkMapperPresent) {
m_MitkVtkRenderWindow->MitkRender();
}
else
m_RenderWindow->swapBuffers();
}
/*!
\brief Initialize the OpenGLRenderer
This method is called from the two Constructors
*/
void mitk::OpenGLRenderer::InitRenderer(mitk::RenderWindow* renderwindow)
{
BaseRenderer::InitRenderer(renderwindow);
m_InitNeeded = true;
m_ResizeNeeded = true;
m_MitkVtkRenderWindow = mitk::VtkRenderWindow::New();
m_MitkVtkRenderWindow->SetMitkRenderer(this);
/**@todo SetNumberOfLayers commented out, because otherwise the backface of the planes are not shown (only, when a light is added).
* But we need SetNumberOfLayers(2) later, when we want to prevent vtk to clear the widget before it renders (i.e., when we render something in the scene before vtk).
*/
//m_MitkVtkRenderWindow->SetNumberOfLayers(2);
m_VtkRenderer = vtkRenderer::New();
m_MitkVtkRenderWindow->AddRenderer( m_VtkRenderer );
//strange: when using a simple light, the backface of the planes are not shown (regardless of SetNumberOfLayers)
//m_Light = vtkLight::New();
//m_VtkRenderer->AddLight( m_Light );
m_LightKit = vtkLightKit::New();
m_LightKit->AddLightsToRenderer(m_VtkRenderer);
if(m_CameraController)
((VtkInteractorCameraController*)m_CameraController.GetPointer())->SetRenderWindow(m_MitkVtkRenderWindow);
//we should disable vtk doublebuffering, but then it doesn't work
//m_MitkVtkRenderWindow->SwapBuffersOff();
}
/*!
\brief Destructs the OpenGLRenderer.
*/
//##ModelId=3E33ECF301B7
mitk::OpenGLRenderer::~OpenGLRenderer() {
m_VtkRenderer->Delete();
m_MitkVtkRenderWindow->Delete();
}
/*!
\brief Initialize the OpenGL Window
*/
//##ModelId=3E33145B0096
void mitk::OpenGLRenderer::Initialize( ) {
glClearColor(0.0, 0.0, 0.0, 1.0);
glColor3f(1.0, 0.0, 0.0);
}
/*!
\brief Resize the OpenGL Window
*/
//##ModelId=3E33145B00D2
void mitk::OpenGLRenderer::Resize(int w, int h)
{
glViewport (0, 0, w, h);
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluOrtho2D( 0.0, w, 0.0, h );
glMatrixMode( GL_MODELVIEW );
BaseRenderer::Resize(w, h);
Update();
// m_MitkVtkRenderWindow->SetSize(w,h); //@FIXME?
}
/*!
\brief Render the scene
*/
//##ModelId=3E33145B005A
void mitk::OpenGLRenderer::Paint( )
{
// glFlush();
// m_RenderWindow->swapBuffers();
Render();
}
//##ModelId=3E3314B0005C
void mitk::OpenGLRenderer::SetWindowId(void * id)
{
m_MitkVtkRenderWindow->SetWindowId( id );
}
//##ModelId=3E3799420227
void mitk::OpenGLRenderer::InitSize(int w, int h)
{
m_MitkVtkRenderWindow->SetSize(w,h);
GetDisplayGeometry()->Fit();
Modified();
Update();
}
//##ModelId=3EF59AD20235
void mitk::OpenGLRenderer::SetMapperID(const MapperSlotId mapperId)
{
Superclass::SetMapperID(mapperId);
Update();
UpdateVtkActors();
}
//##ModelId=3EF162760271
void mitk::OpenGLRenderer::MakeCurrent()
{
if(m_RenderWindow!=NULL)
{
m_RenderWindow->MakeCurrent();
}
}
void mitk::OpenGLRenderer::DataChangedEvent(const itk::Object *caller, const itk::EventObject &event)
{
if(m_RenderWindow!=NULL)
{
m_RenderWindow->Update();
}
}<|endoftext|>
|
<commit_before>// Copyright Microsoft Corporation
// Copyright GHI Electronics, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <LPC24.h>
#include "../../Drivers/AT49BV322DT_Flash/AT49BV322DT_Flash.h"
#define TOTAL_DEPLOYMENT_CONTROLLERS 1
static TinyCLR_Storage_Controller deploymentControllers[TOTAL_DEPLOYMENT_CONTROLLERS];
static TinyCLR_Api_Info deploymentApi[TOTAL_DEPLOYMENT_CONTROLLERS];
struct DeploymentState {
uint32_t controllerIndex;
size_t regionCount;
const uint64_t* regionAddresses;
const size_t* regionSizes;
TinyCLR_Storage_Descriptor storageDescriptor;
TinyCLR_Startup_DeploymentConfiguration deploymentConfiguration;
bool isOpened = false;
};
static DeploymentState deploymentStates[TOTAL_DEPLOYMENT_CONTROLLERS];
void LPC24_Deployment_AddApi(const TinyCLR_Api_Manager* apiManager) {
for (auto i = 0; i < TOTAL_DEPLOYMENT_CONTROLLERS; i++) {
deploymentControllers[i].ApiInfo = &deploymentApi[i];
deploymentControllers[i].Acquire = &LPC24_Deployment_Acquire;
deploymentControllers[i].Release = &LPC24_Deployment_Release;
deploymentControllers[i].Open = &LPC24_Deployment_Open;
deploymentControllers[i].Close = &LPC24_Deployment_Close;
deploymentControllers[i].Read = &LPC24_Deployment_Read;
deploymentControllers[i].Write = &LPC24_Deployment_Write;
deploymentControllers[i].Erase = &LPC24_Deployment_Erase;
deploymentControllers[i].IsErased = &LPC24_Deployment_IsErased;
deploymentControllers[i].GetDescriptor = &LPC24_Deployment_GetDescriptor;
deploymentControllers[i].IsPresent = &LPC24_Deployment_IsPresent;
deploymentControllers[i].SetPresenceChangedHandler = &LPC24_Deployment_SetPresenceChangedHandler;
deploymentApi[i].Author = "GHI Electronics, LLC";
deploymentApi[i].Name = "GHIElectronics.TinyCLR.NativeApis.LPC24.StorageController";
deploymentApi[i].Type = TinyCLR_Api_Type::StorageController;
deploymentApi[i].Version = 0;
deploymentApi[i].Implementation = &deploymentControllers[i];
deploymentApi[i].State = &deploymentStates[i];
deploymentStates[i].controllerIndex = i;
deploymentStates[i].regionCount = LPC24_DEPLOYMENT_SECTOR_NUM;
}
return (const TinyCLR_Api_Info*)&deploymentApi;
}
TinyCLR_Result LPC24_Deployment_Acquire(const TinyCLR_Storage_Controller* self) {
return AT49BV322DT_Flash_Acquire();
}
TinyCLR_Result LPC24_Deployment_Release(const TinyCLR_Storage_Controller* self) {
return AT49BV322DT_Flash_Release();
}
TinyCLR_Result LPC24_Deployment_Open(const TinyCLR_Storage_Controller* self) {
auto state = reinterpret_cast<DeploymentState*>(self->ApiInfo->State);
if (state->isOpened)
return TinyCLR_Result::SharingViolation;
state->storageDescriptor.CanReadDirect = true;
state->storageDescriptor.CanWriteDirect = true;
state->storageDescriptor.CanExecuteDirect = true;
state->storageDescriptor.EraseBeforeWrite = true;
state->storageDescriptor.Removable = false;
state->storageDescriptor.RegionsRepeat = true;
size_t regionCount;
AT49BV322DT_Flash_GetSectorMap(state->regionAddresses, state->regionSizes, regionCount);
if (regionCount < state->regionCount)
return TinyCLR_Result::ArgumentOutOfRange;
state->regionAddresses += LPC24_DEPLOYMENT_SECTOR_START;
state->regionSizes += LPC24_DEPLOYMENT_SECTOR_START;
state->storageDescriptor.RegionCount = state->regionCount;
state->storageDescriptor.RegionAddresses = reinterpret_cast<const uint64_t*>(state->regionAddresses);
state->storageDescriptor.RegionSizes = reinterpret_cast<const size_t*>(state->regionSizes);
state->deploymentConfiguration.RegionCount = state->storageDescriptor.RegionCount;
state->deploymentConfiguration.RegionAddresses = state->storageDescriptor.RegionAddresses;
state->deploymentConfiguration.RegionSizes = state->storageDescriptor.RegionSizes;
state->isOpened = true;
return TinyCLR_Result::Success;
}
TinyCLR_Result LPC24_Deployment_Close(const TinyCLR_Storage_Controller* self) {
auto state = reinterpret_cast<DeploymentState*>(self->ApiInfo->State);
if (!state->isOpened)
return TinyCLR_Result::NotFound;
state->isOpened = false;
return TinyCLR_Result::Success;
}
TinyCLR_Result LPC24_Deployment_Read(const TinyCLR_Storage_Controller* self, uint64_t address, size_t& count, uint8_t* data, uint64_t timeout) {
return AT49BV322DT_Flash_Read(address, count, data);
}
TinyCLR_Result LPC24_Deployment_Write(const TinyCLR_Storage_Controller* self, uint64_t address, size_t& count, const uint8_t* data, uint64_t timeout) {
return AT49BV322DT_Flash_Write(address, count, data);;
}
TinyCLR_Result LPC24_Deployment_Erase(const TinyCLR_Storage_Controller* self, uint64_t address, size_t& count, uint64_t timeout) {
auto sector = address;
sector += LPC24_DEPLOYMENT_SECTOR_START;
return AT49BV322DT_Flash_EraseBlock(sector);
}
TinyCLR_Result LPC24_Deployment_IsErased(const TinyCLR_Storage_Controller* self, uint64_t address, size_t count, bool& erased) {
auto sector = address;
sector += LPC24_DEPLOYMENT_SECTOR_START;
return AT49BV322DT_Flash_IsBlockErased(sector, erased);
}
TinyCLR_Result LPC24_Deployment_GetBytesPerSector(const TinyCLR_Storage_Controller* self, uint32_t address, int32_t& size) {
return AT49BV322DT_Flash_GetBytesPerSector(address, size);
}
TinyCLR_Result LPC24_Deployment_SetPresenceChangedHandler(const TinyCLR_Storage_Controller* self, TinyCLR_Storage_PresenceChangedHandler handler) {
return TinyCLR_Result::Success;
}
TinyCLR_Result LPC24_Deployment_IsPresent(const TinyCLR_Storage_Controller* self, bool& present) {
present = true;
return TinyCLR_Result::Success;
}
TinyCLR_Result LPC24_Deployment_GetDescriptor(const TinyCLR_Storage_Controller* self, const TinyCLR_Storage_Descriptor*& descriptor) {
auto state = reinterpret_cast<DeploymentState*>(self->ApiInfo->State);
descriptor = &state->storageDescriptor;
return descriptor->RegionCount > 0 ? TinyCLR_Result::Success : TinyCLR_Result::NotImplemented;
}
const TinyCLR_Startup_DeploymentConfiguration* LPC24_Deployment_GetDeploymentConfiguration() {
auto state = &deploymentStates[0];
return reinterpret_cast<const TinyCLR_Startup_DeploymentConfiguration*>(&state->deploymentConfiguration);
}
<commit_msg>Fixed compile error EMM<commit_after>// Copyright Microsoft Corporation
// Copyright GHI Electronics, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <LPC24.h>
#include "../../Drivers/AT49BV322DT_Flash/AT49BV322DT_Flash.h"
#define TOTAL_DEPLOYMENT_CONTROLLERS 1
const char* deploymentApiNames[TOTAL_DEPLOYMENT_CONTROLLERS] = {
"GHIElectronics.TinyCLR.NativeApis.LPC24.StorageController\\0"
};
static TinyCLR_Storage_Controller deploymentControllers[TOTAL_DEPLOYMENT_CONTROLLERS];
static TinyCLR_Api_Info deploymentApi[TOTAL_DEPLOYMENT_CONTROLLERS];
struct DeploymentState {
uint32_t controllerIndex;
size_t regionCount;
const uint64_t* regionAddresses;
const size_t* regionSizes;
TinyCLR_Storage_Descriptor storageDescriptor;
TinyCLR_Startup_DeploymentConfiguration deploymentConfiguration;
bool isOpened = false;
bool tableInitialized = false;
};
static DeploymentState deploymentStates[TOTAL_DEPLOYMENT_CONTROLLERS];
void LPC24_Deployment_EnsureTableInitialized() {
for (auto i = 0; i < TOTAL_DEPLOYMENT_CONTROLLERS; i++) {
if (deploymentStates[i].tableInitialized)
continue;
deploymentControllers[i].ApiInfo = &deploymentApi[i];
deploymentControllers[i].Acquire = &LPC24_Deployment_Acquire;
deploymentControllers[i].Release = &LPC24_Deployment_Release;
deploymentControllers[i].Open = &LPC24_Deployment_Open;
deploymentControllers[i].Close = &LPC24_Deployment_Close;
deploymentControllers[i].Read = &LPC24_Deployment_Read;
deploymentControllers[i].Write = &LPC24_Deployment_Write;
deploymentControllers[i].Erase = &LPC24_Deployment_Erase;
deploymentControllers[i].IsErased = &LPC24_Deployment_IsErased;
deploymentControllers[i].GetDescriptor = &LPC24_Deployment_GetDescriptor;
deploymentControllers[i].IsPresent = &LPC24_Deployment_IsPresent;
deploymentControllers[i].SetPresenceChangedHandler = &LPC24_Deployment_SetPresenceChangedHandler;
deploymentApi[i].Author = "GHI Electronics, LLC";
deploymentApi[i].Name = deploymentApiNames[i];
deploymentApi[i].Type = TinyCLR_Api_Type::StorageController;
deploymentApi[i].Version = 0;
deploymentApi[i].Implementation = &deploymentControllers[i];
deploymentApi[i].State = &deploymentStates[i];
deploymentStates[i].controllerIndex = i;
deploymentStates[i].regionCount = LPC24_DEPLOYMENT_SECTOR_NUM;
deploymentStates[i].tableInitialized = true;
}
}
void LPC24_Deployment_GetDeploymentApi(const TinyCLR_Api_Info*& api, const TinyCLR_Startup_DeploymentConfiguration*& configuration) {
LPC24_Deployment_EnsureTableInitialized();
auto state = &deploymentStates[0];
api = &deploymentApi[0];
configuration = &state->deploymentConfiguration;
}
void LPC24_Deployment_AddApi(const TinyCLR_Api_Manager* apiManager) {
LPC24_Deployment_EnsureTableInitialized();
for (auto i = 0; i < TOTAL_DEPLOYMENT_CONTROLLERS; i++) {
apiManager->Add(apiManager, &deploymentApi[i]);
}
apiManager->SetDefaultName(apiManager, TinyCLR_Api_Type::StorageController, deploymentApi[0].Name);
}
TinyCLR_Result LPC24_Deployment_Acquire(const TinyCLR_Storage_Controller* self) {
return AT49BV322DT_Flash_Acquire();
}
TinyCLR_Result LPC24_Deployment_Release(const TinyCLR_Storage_Controller* self) {
return AT49BV322DT_Flash_Release();
}
TinyCLR_Result LPC24_Deployment_Open(const TinyCLR_Storage_Controller* self) {
auto state = reinterpret_cast<DeploymentState*>(self->ApiInfo->State);
if (state->isOpened)
return TinyCLR_Result::SharingViolation;
state->storageDescriptor.CanReadDirect = true;
state->storageDescriptor.CanWriteDirect = true;
state->storageDescriptor.CanExecuteDirect = true;
state->storageDescriptor.EraseBeforeWrite = true;
state->storageDescriptor.Removable = false;
state->storageDescriptor.RegionsRepeat = true;
size_t regionCount;
AT49BV322DT_Flash_GetSectorMap(state->regionAddresses, state->regionSizes, regionCount);
if (regionCount < state->regionCount)
return TinyCLR_Result::ArgumentOutOfRange;
state->regionAddresses += LPC24_DEPLOYMENT_SECTOR_START;
state->regionSizes += LPC24_DEPLOYMENT_SECTOR_START;
state->storageDescriptor.RegionCount = state->regionCount;
state->storageDescriptor.RegionAddresses = reinterpret_cast<const uint64_t*>(state->regionAddresses);
state->storageDescriptor.RegionSizes = reinterpret_cast<const size_t*>(state->regionSizes);
state->deploymentConfiguration.RegionCount = state->storageDescriptor.RegionCount;
state->deploymentConfiguration.RegionAddresses = state->storageDescriptor.RegionAddresses;
state->deploymentConfiguration.RegionSizes = state->storageDescriptor.RegionSizes;
state->isOpened = true;
return TinyCLR_Result::Success;
}
TinyCLR_Result LPC24_Deployment_Close(const TinyCLR_Storage_Controller* self) {
auto state = reinterpret_cast<DeploymentState*>(self->ApiInfo->State);
if (!state->isOpened)
return TinyCLR_Result::NotFound;
state->isOpened = false;
return TinyCLR_Result::Success;
}
TinyCLR_Result LPC24_Deployment_Read(const TinyCLR_Storage_Controller* self, uint64_t address, size_t& count, uint8_t* data, uint64_t timeout) {
return AT49BV322DT_Flash_Read(address, count, data);
}
TinyCLR_Result LPC24_Deployment_Write(const TinyCLR_Storage_Controller* self, uint64_t address, size_t& count, const uint8_t* data, uint64_t timeout) {
return AT49BV322DT_Flash_Write(address, count, data);;
}
TinyCLR_Result LPC24_Deployment_Erase(const TinyCLR_Storage_Controller* self, uint64_t address, size_t& count, uint64_t timeout) {
auto sector = address;
sector += LPC24_DEPLOYMENT_SECTOR_START;
return AT49BV322DT_Flash_EraseBlock(sector);
}
TinyCLR_Result LPC24_Deployment_IsErased(const TinyCLR_Storage_Controller* self, uint64_t address, size_t count, bool& erased) {
auto sector = address;
sector += LPC24_DEPLOYMENT_SECTOR_START;
return AT49BV322DT_Flash_IsBlockErased(sector, erased);
}
TinyCLR_Result LPC24_Deployment_GetBytesPerSector(const TinyCLR_Storage_Controller* self, uint32_t address, int32_t& size) {
return AT49BV322DT_Flash_GetBytesPerSector(address, size);
}
TinyCLR_Result LPC24_Deployment_SetPresenceChangedHandler(const TinyCLR_Storage_Controller* self, TinyCLR_Storage_PresenceChangedHandler handler) {
return TinyCLR_Result::Success;
}
TinyCLR_Result LPC24_Deployment_IsPresent(const TinyCLR_Storage_Controller* self, bool& present) {
present = true;
return TinyCLR_Result::Success;
}
TinyCLR_Result LPC24_Deployment_GetDescriptor(const TinyCLR_Storage_Controller* self, const TinyCLR_Storage_Descriptor*& descriptor) {
auto state = reinterpret_cast<DeploymentState*>(self->ApiInfo->State);
descriptor = &state->storageDescriptor;
return descriptor->RegionCount > 0 ? TinyCLR_Result::Success : TinyCLR_Result::NotImplemented;
}
const TinyCLR_Startup_DeploymentConfiguration* LPC24_Deployment_GetDeploymentConfiguration() {
auto state = &deploymentStates[0];
return reinterpret_cast<const TinyCLR_Startup_DeploymentConfiguration*>(&state->deploymentConfiguration);
}
<|endoftext|>
|
<commit_before>#include "mpga.h"
#include <cstdio>
#include <sys/types.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <signal.h>
#include <iostream>
#include <argos3/core/simulator/simulator.h>
#include "mpga_loop_functions.h"
/****************************************/
/****************************************/
/* File name for shared memory area */
static const char* SHARED_MEMORY_FILE = "/MPGA_SHARED_MEMORY";
/****************************************/
/****************************************/
bool SortHighToLow(const CMPGA::SIndividual* pc_a,
const CMPGA::SIndividual* pc_b) {
return pc_a->Score > pc_b->Score;
}
bool SortLowToHigh(const CMPGA::SIndividual* pc_a,
const CMPGA::SIndividual* pc_b) {
return pc_b->Score > pc_a->Score;
}
/****************************************/
/****************************************/
CMPGA::CMPGA(const CRange<Real>& c_allele_range,
UInt32 un_genome_size,
UInt32 un_pop_size,
Real f_mutation_prob,
UInt32 un_num_trials,
UInt32 un_generations,
bool b_maximize,
const std::string& str_argosconf,
TScoreAggregator t_score_aggregator,
UInt32 un_random_seed) :
m_unCurrentGeneration(0),
m_cAlleleRange(c_allele_range),
m_unGenomeSize(un_genome_size),
m_unPopSize(un_pop_size),
m_fMutationProb(f_mutation_prob),
m_unNumTrials(un_num_trials),
m_unGenerations(un_generations),
m_strARGoSConf(str_argosconf),
m_tScoreAggregator(t_score_aggregator),
MasterPID(::getpid()),
m_cIndComparator(b_maximize ? SortHighToLow : SortLowToHigh) {
/* Create shared memory manager */
m_pcSharedMem = new CSharedMem(un_genome_size,
un_pop_size);
/* Create slave processes */
for(UInt32 i = 0; i < m_unPopSize; ++i) {
/* Perform fork */
SlavePIDs.push_back(::fork());
if(SlavePIDs.back() == 0) {
/* We're in a slave */
LaunchARGoS(i);
}
}
/* Create a random number generator */
CRandom::CreateCategory("ga", un_random_seed);
m_pcRNG = CRandom::CreateRNG("ga");
/* Create initial population */
SIndividual* psInd;
for(size_t p = 0; p < m_unPopSize; ++p) {
/* Create individual */
psInd = new SIndividual;
psInd->Score = -1.0;
/* Create random genome */
for(size_t g = 0; g < m_unGenomeSize; ++g) {
psInd->Genome.push_back(m_pcRNG->Uniform(m_cAlleleRange));
}
/* Add individual to the population */
m_tPopulation.push_back(psInd);
}
/* The master sleeps to give enough time to the slaves to
* initialize and suspend properly. If not enough time is given
* here, the master will hang later on. */
::sleep(3);
}
/****************************************/
/****************************************/
CMPGA::~CMPGA() {
/* Terminate slaves */
for(UInt32 i = 0; i < m_unPopSize; ++i) {
::kill(SlavePIDs[i], SIGTERM);
}
/* Clean memory up */
while(!m_tPopulation.empty()) {
delete m_tPopulation.back();
m_tPopulation.pop_back();
}
CRandom::RemoveCategory("ga");
/* Other cleanup in common between master and slaves */
Cleanup();
}
/****************************************/
/****************************************/
const CMPGA::TPopulation& CMPGA::GetPopulation() const {
return m_tPopulation;
}
/****************************************/
/****************************************/
UInt32 CMPGA::GetGeneration() const {
return m_unCurrentGeneration;
}
/****************************************/
/****************************************/
void CMPGA::Cleanup() {
delete m_pcSharedMem;
}
/****************************************/
/****************************************/
void CMPGA::Evaluate() {
/* Set parameters for the processes and resume them */
for(UInt32 i = 0; i < m_unPopSize; ++i) {
/* Set genome */
m_pcSharedMem->SetGenome(i, &(m_tPopulation[i]->Genome[0]));
/* Resume process */
::kill(SlavePIDs[i], SIGCONT);
}
/* Wait for all the slaves to finish the run */
UInt32 unTrialsLeft = m_unPopSize;
int nSlaveInfo;
pid_t tSlavePID;
while(unTrialsLeft > 0) {
/* Wait for next slave to finish */
tSlavePID = ::waitpid(-1, &nSlaveInfo, WUNTRACED);
/* Make sure the slave went back to sleep and didn't crash */
if(!WIFSTOPPED(nSlaveInfo)) {
LOGERR << "[FATAL] Slave process with PID " << tSlavePID << " exited, can't continue. Check file ARGoS_LOGERR_" << tSlavePID << " for more information." << std::endl;
LOG.Flush();
LOGERR.Flush();
Cleanup();
::exit(1);
}
/* All OK, one less slave to wait for */
--unTrialsLeft;
}
/* Copy the scores into the population data */
for(UInt32 i = 0; i < m_unPopSize; ++i) {
m_tPopulation[i]->Score = m_pcSharedMem->GetScore(i);
}
/* Sort the population by score, from the best to the worst */
std::sort(m_tPopulation.begin(),
m_tPopulation.end(),
m_cIndComparator);
}
/****************************************/
/****************************************/
void CMPGA::NextGen() {
++m_unCurrentGeneration;
Selection();
Crossover();
Mutation();
}
/****************************************/
/****************************************/
bool CMPGA::Done() const {
return m_unCurrentGeneration >= m_unGenerations;
}
/****************************************/
/****************************************/
/* Global pointer to the CMPGA object in the current slave, used by
* SlaveHandleSIGTERM() to perform cleanup */
static CMPGA* GA_INSTANCE;
/* SIGTERM handler for slave processes */
void SlaveHandleSIGTERM(int) {
argos::CSimulator::GetInstance().Destroy();
argos::LOG.Flush();
argos::LOGERR.Flush();
GA_INSTANCE->Cleanup();
}
void CMPGA::LaunchARGoS(UInt32 un_slave_id) {
/* Set the global GA instance pointer for signal handler */
GA_INSTANCE = this;
/* Install handler for SIGTERM */
::signal(SIGTERM, SlaveHandleSIGTERM);
/* Initialize ARGoS */
/* Redirect LOG and LOGERR to dedicated files to prevent clutter on the screen */
std::ofstream cLOGFile("ARGoS_LOG_" + ToString(::getpid()), std::ios::out);
LOG.DisableColoredOutput();
LOG.GetStream().rdbuf(cLOGFile.rdbuf());
std::ofstream cLOGERRFile("ARGoS_LOGERR_" + ToString(::getpid()), std::ios::out);
LOGERR.DisableColoredOutput();
LOGERR.GetStream().rdbuf(cLOGERRFile.rdbuf());
/* The CSimulator class of ARGoS is a singleton. Therefore, to
* manipulate an ARGoS experiment, it is enough to get its instance */
argos::CSimulator& cSimulator = argos::CSimulator::GetInstance();
try {
/* Set the .argos configuration file
* This is a relative path which assumed that you launch the executable
* from argos3-examples (as said also in the README) */
cSimulator.SetExperimentFileName(m_strARGoSConf);
/* Load it to configure ARGoS */
cSimulator.LoadExperiment();
LOG.Flush();
LOGERR.Flush();
}
catch(CARGoSException& ex) {
LOGERR << ex.what() << std::endl;
::raise(SIGTERM);
}
/* Get a reference to the loop functions */
CMPGALoopFunctions& cLoopFunctions = dynamic_cast<CMPGALoopFunctions&>(cSimulator.GetLoopFunctions());
/* Create vector of scores */
std::vector<Real> vecScores(m_unPopSize, 0.0);
/* Continue working until killed by parent */
while(1) {
/* Suspend yourself, waiting for parent's resume signal */
::raise(SIGTSTP);
/* Resumed */
/* Configure the controller with the genome */
cLoopFunctions.ConfigureFromGenome(m_pcSharedMem->GetGenome(un_slave_id));
/* Run the trials */
for(size_t i = 0; i < m_unNumTrials; ++i) {
/* Tell the loop functions to get ready for the i-th trial */
cLoopFunctions.SetTrial(i);
/* Reset the experiment.
* This internally calls also CMPGALoopFunctions::Reset(). */
cSimulator.Reset();
/* Run the experiment */
cSimulator.Execute();
/* Store score */
vecScores[i] = cLoopFunctions.Score();
LOG.Flush();
LOGERR.Flush();
}
;
/* Put result in shared memory */
m_pcSharedMem->SetScore(un_slave_id, m_tScoreAggregator(vecScores));
}
}
/****************************************/
/****************************************/
void CMPGA::Selection() {
/* Delete all individuals apart from the top two */
for(UInt32 i = 2; i < m_unPopSize; ++i) {
delete m_tPopulation[i];
m_tPopulation.pop_back();
}
}
/****************************************/
/****************************************/
void CMPGA::Crossover() {
/*
* This is a simple one-point crossover.
*/
SIndividual* psParent1 = m_tPopulation[0];
SIndividual* psParent2 = m_tPopulation[1];
UInt32 unCut;
SIndividual* psInd;
for(UInt32 i = 2; i < m_unPopSize; ++i) {
/* Pick a cutting point at random */
unCut = m_pcRNG->Uniform(CRange<UInt32>(1, m_unGenomeSize-1));
/* Make a new individual */
psInd = new SIndividual;
/* Copy alleles from parent 1 */
for(UInt32 j = 0; j < unCut; ++j) {
psInd->Genome.push_back(psParent1->Genome[j]);
}
/* Copy alleles from parent 2 */
for(UInt32 j = unCut; j < m_unGenomeSize; ++j) {
psInd->Genome.push_back(psParent2->Genome[j]);
}
/* Add individual to the new population */
m_tPopulation.push_back(psInd);
}
}
/****************************************/
/****************************************/
void CMPGA::Mutation() {
/* Mutate the alleles of the newly added individuals by setting a
* new random value from a uniform distribution */
for(UInt32 i = 2; i < m_unPopSize; ++i) {
for(UInt32 a = 0; a < m_unGenomeSize; ++a) {
if(m_pcRNG->Bernoulli(m_fMutationProb))
m_tPopulation[i]->Genome[a] = m_pcRNG->Uniform(m_cAlleleRange);
}
}
}
/****************************************/
/****************************************/
CMPGA::CSharedMem::CSharedMem(UInt32 un_genome_size,
UInt32 un_pop_size) :
m_unGenomeSize(un_genome_size),
m_unPopSize(un_pop_size) {
/* Create shared memory area for master-slave communication */
m_nSharedMemFD = ::shm_open(SHARED_MEMORY_FILE,
O_RDWR | O_CREAT,
S_IRUSR | S_IWUSR);
if(m_nSharedMemFD < 0) {
::perror(SHARED_MEMORY_FILE);
exit(1);
}
/* Resize shared memory area to contain the population data
* - The area must contain m_unPopSize elements
* - Each element must have space for the data of an individual
* - Genome: m_unGenomeSize * sizeof(Real)
* - Score: sizeof(Real)
*/
size_t unShareMemSize = m_unPopSize * (m_unGenomeSize+1) * sizeof(Real);
::ftruncate(m_nSharedMemFD, unShareMemSize);
/* Get pointer to shared memory area */
m_pfSharedMem = reinterpret_cast<Real*>(
::mmap(NULL,
unShareMemSize,
PROT_READ | PROT_WRITE,
MAP_SHARED,
m_nSharedMemFD,
0));
if(m_pfSharedMem == MAP_FAILED) {
::perror("shared memory");
exit(1);
}
}
/****************************************/
/****************************************/
CMPGA::CSharedMem::~CSharedMem() {
munmap(m_pfSharedMem, m_unPopSize * (m_unGenomeSize+1) * sizeof(Real));
close(m_nSharedMemFD);
shm_unlink(SHARED_MEMORY_FILE);
}
/****************************************/
/****************************************/
Real* CMPGA::CSharedMem::GetGenome(UInt32 un_individual) {
return m_pfSharedMem + un_individual * (m_unGenomeSize+1);
}
/****************************************/
/****************************************/
void CMPGA::CSharedMem::SetGenome(UInt32 un_individual,
const Real* pf_genome) {
::memcpy(m_pfSharedMem + un_individual * (m_unGenomeSize+1),
pf_genome,
m_unGenomeSize * sizeof(Real));
}
/****************************************/
/****************************************/
Real CMPGA::CSharedMem::GetScore(UInt32 un_individual) {
return m_pfSharedMem[un_individual * (m_unGenomeSize+1) + m_unGenomeSize];
}
/****************************************/
/****************************************/
void CMPGA::CSharedMem::SetScore(UInt32 un_individual,
Real f_score) {
m_pfSharedMem[un_individual * (m_unGenomeSize+1) + m_unGenomeSize] = f_score;
}
/****************************************/
/****************************************/
<commit_msg>Fixed bug in MPGA. Wrong size for score vector.<commit_after>#include "mpga.h"
#include <cstdio>
#include <sys/types.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <signal.h>
#include <iostream>
#include <argos3/core/simulator/simulator.h>
#include "mpga_loop_functions.h"
/****************************************/
/****************************************/
/* File name for shared memory area */
static const char* SHARED_MEMORY_FILE = "/MPGA_SHARED_MEMORY";
/****************************************/
/****************************************/
bool SortHighToLow(const CMPGA::SIndividual* pc_a,
const CMPGA::SIndividual* pc_b) {
return pc_a->Score > pc_b->Score;
}
bool SortLowToHigh(const CMPGA::SIndividual* pc_a,
const CMPGA::SIndividual* pc_b) {
return pc_b->Score > pc_a->Score;
}
/****************************************/
/****************************************/
CMPGA::CMPGA(const CRange<Real>& c_allele_range,
UInt32 un_genome_size,
UInt32 un_pop_size,
Real f_mutation_prob,
UInt32 un_num_trials,
UInt32 un_generations,
bool b_maximize,
const std::string& str_argosconf,
TScoreAggregator t_score_aggregator,
UInt32 un_random_seed) :
m_unCurrentGeneration(0),
m_cAlleleRange(c_allele_range),
m_unGenomeSize(un_genome_size),
m_unPopSize(un_pop_size),
m_fMutationProb(f_mutation_prob),
m_unNumTrials(un_num_trials),
m_unGenerations(un_generations),
m_strARGoSConf(str_argosconf),
m_tScoreAggregator(t_score_aggregator),
MasterPID(::getpid()),
m_cIndComparator(b_maximize ? SortHighToLow : SortLowToHigh) {
/* Create shared memory manager */
m_pcSharedMem = new CSharedMem(un_genome_size,
un_pop_size);
/* Create slave processes */
for(UInt32 i = 0; i < m_unPopSize; ++i) {
/* Perform fork */
SlavePIDs.push_back(::fork());
if(SlavePIDs.back() == 0) {
/* We're in a slave */
LaunchARGoS(i);
}
}
/* Create a random number generator */
CRandom::CreateCategory("ga", un_random_seed);
m_pcRNG = CRandom::CreateRNG("ga");
/* Create initial population */
SIndividual* psInd;
for(size_t p = 0; p < m_unPopSize; ++p) {
/* Create individual */
psInd = new SIndividual;
psInd->Score = -1.0;
/* Create random genome */
for(size_t g = 0; g < m_unGenomeSize; ++g) {
psInd->Genome.push_back(m_pcRNG->Uniform(m_cAlleleRange));
}
/* Add individual to the population */
m_tPopulation.push_back(psInd);
}
/* The master sleeps to give enough time to the slaves to
* initialize and suspend properly. If not enough time is given
* here, the master will hang later on. */
::sleep(3);
}
/****************************************/
/****************************************/
CMPGA::~CMPGA() {
/* Terminate slaves */
for(UInt32 i = 0; i < m_unPopSize; ++i) {
::kill(SlavePIDs[i], SIGTERM);
}
/* Clean memory up */
while(!m_tPopulation.empty()) {
delete m_tPopulation.back();
m_tPopulation.pop_back();
}
CRandom::RemoveCategory("ga");
/* Other cleanup in common between master and slaves */
Cleanup();
}
/****************************************/
/****************************************/
const CMPGA::TPopulation& CMPGA::GetPopulation() const {
return m_tPopulation;
}
/****************************************/
/****************************************/
UInt32 CMPGA::GetGeneration() const {
return m_unCurrentGeneration;
}
/****************************************/
/****************************************/
void CMPGA::Cleanup() {
delete m_pcSharedMem;
}
/****************************************/
/****************************************/
void CMPGA::Evaluate() {
/* Set parameters for the processes and resume them */
for(UInt32 i = 0; i < m_unPopSize; ++i) {
/* Set genome */
m_pcSharedMem->SetGenome(i, &(m_tPopulation[i]->Genome[0]));
/* Resume process */
::kill(SlavePIDs[i], SIGCONT);
}
/* Wait for all the slaves to finish the run */
UInt32 unTrialsLeft = m_unPopSize;
int nSlaveInfo;
pid_t tSlavePID;
while(unTrialsLeft > 0) {
/* Wait for next slave to finish */
tSlavePID = ::waitpid(-1, &nSlaveInfo, WUNTRACED);
/* Make sure the slave went back to sleep and didn't crash */
if(!WIFSTOPPED(nSlaveInfo)) {
LOGERR << "[FATAL] Slave process with PID " << tSlavePID << " exited, can't continue. Check file ARGoS_LOGERR_" << tSlavePID << " for more information." << std::endl;
LOG.Flush();
LOGERR.Flush();
Cleanup();
::exit(1);
}
/* All OK, one less slave to wait for */
--unTrialsLeft;
}
/* Copy the scores into the population data */
for(UInt32 i = 0; i < m_unPopSize; ++i) {
m_tPopulation[i]->Score = m_pcSharedMem->GetScore(i);
}
/* Sort the population by score, from the best to the worst */
std::sort(m_tPopulation.begin(),
m_tPopulation.end(),
m_cIndComparator);
}
/****************************************/
/****************************************/
void CMPGA::NextGen() {
++m_unCurrentGeneration;
Selection();
Crossover();
Mutation();
}
/****************************************/
/****************************************/
bool CMPGA::Done() const {
return m_unCurrentGeneration >= m_unGenerations;
}
/****************************************/
/****************************************/
/* Global pointer to the CMPGA object in the current slave, used by
* SlaveHandleSIGTERM() to perform cleanup */
static CMPGA* GA_INSTANCE;
/* SIGTERM handler for slave processes */
void SlaveHandleSIGTERM(int) {
argos::CSimulator::GetInstance().Destroy();
argos::LOG.Flush();
argos::LOGERR.Flush();
GA_INSTANCE->Cleanup();
}
void CMPGA::LaunchARGoS(UInt32 un_slave_id) {
/* Set the global GA instance pointer for signal handler */
GA_INSTANCE = this;
/* Install handler for SIGTERM */
::signal(SIGTERM, SlaveHandleSIGTERM);
/* Initialize ARGoS */
/* Redirect LOG and LOGERR to dedicated files to prevent clutter on the screen */
std::ofstream cLOGFile("ARGoS_LOG_" + ToString(::getpid()), std::ios::out);
LOG.DisableColoredOutput();
LOG.GetStream().rdbuf(cLOGFile.rdbuf());
std::ofstream cLOGERRFile("ARGoS_LOGERR_" + ToString(::getpid()), std::ios::out);
LOGERR.DisableColoredOutput();
LOGERR.GetStream().rdbuf(cLOGERRFile.rdbuf());
/* The CSimulator class of ARGoS is a singleton. Therefore, to
* manipulate an ARGoS experiment, it is enough to get its instance */
argos::CSimulator& cSimulator = argos::CSimulator::GetInstance();
try {
/* Set the .argos configuration file
* This is a relative path which assumed that you launch the executable
* from argos3-examples (as said also in the README) */
cSimulator.SetExperimentFileName(m_strARGoSConf);
/* Load it to configure ARGoS */
cSimulator.LoadExperiment();
LOG.Flush();
LOGERR.Flush();
}
catch(CARGoSException& ex) {
LOGERR << ex.what() << std::endl;
::raise(SIGTERM);
}
/* Get a reference to the loop functions */
CMPGALoopFunctions& cLoopFunctions = dynamic_cast<CMPGALoopFunctions&>(cSimulator.GetLoopFunctions());
/* Create vector of scores */
std::vector<Real> vecScores(m_unNumTrials, 0.0);
/* Continue working until killed by parent */
while(1) {
/* Suspend yourself, waiting for parent's resume signal */
::raise(SIGTSTP);
/* Resumed */
/* Configure the controller with the genome */
cLoopFunctions.ConfigureFromGenome(m_pcSharedMem->GetGenome(un_slave_id));
/* Run the trials */
for(size_t i = 0; i < m_unNumTrials; ++i) {
/* Tell the loop functions to get ready for the i-th trial */
cLoopFunctions.SetTrial(i);
/* Reset the experiment.
* This internally calls also CMPGALoopFunctions::Reset(). */
cSimulator.Reset();
/* Run the experiment */
cSimulator.Execute();
/* Store score */
vecScores[i] = cLoopFunctions.Score();
LOG.Flush();
LOGERR.Flush();
}
;
/* Put result in shared memory */
m_pcSharedMem->SetScore(un_slave_id, m_tScoreAggregator(vecScores));
}
}
/****************************************/
/****************************************/
void CMPGA::Selection() {
/* Delete all individuals apart from the top two */
for(UInt32 i = 2; i < m_unPopSize; ++i) {
delete m_tPopulation[i];
m_tPopulation.pop_back();
}
}
/****************************************/
/****************************************/
void CMPGA::Crossover() {
/*
* This is a simple one-point crossover.
*/
SIndividual* psParent1 = m_tPopulation[0];
SIndividual* psParent2 = m_tPopulation[1];
UInt32 unCut;
SIndividual* psInd;
for(UInt32 i = 2; i < m_unPopSize; ++i) {
/* Pick a cutting point at random */
unCut = m_pcRNG->Uniform(CRange<UInt32>(1, m_unGenomeSize-1));
/* Make a new individual */
psInd = new SIndividual;
/* Copy alleles from parent 1 */
for(UInt32 j = 0; j < unCut; ++j) {
psInd->Genome.push_back(psParent1->Genome[j]);
}
/* Copy alleles from parent 2 */
for(UInt32 j = unCut; j < m_unGenomeSize; ++j) {
psInd->Genome.push_back(psParent2->Genome[j]);
}
/* Add individual to the new population */
m_tPopulation.push_back(psInd);
}
}
/****************************************/
/****************************************/
void CMPGA::Mutation() {
/* Mutate the alleles of the newly added individuals by setting a
* new random value from a uniform distribution */
for(UInt32 i = 2; i < m_unPopSize; ++i) {
for(UInt32 a = 0; a < m_unGenomeSize; ++a) {
if(m_pcRNG->Bernoulli(m_fMutationProb))
m_tPopulation[i]->Genome[a] = m_pcRNG->Uniform(m_cAlleleRange);
}
}
}
/****************************************/
/****************************************/
CMPGA::CSharedMem::CSharedMem(UInt32 un_genome_size,
UInt32 un_pop_size) :
m_unGenomeSize(un_genome_size),
m_unPopSize(un_pop_size) {
/* Create shared memory area for master-slave communication */
m_nSharedMemFD = ::shm_open(SHARED_MEMORY_FILE,
O_RDWR | O_CREAT,
S_IRUSR | S_IWUSR);
if(m_nSharedMemFD < 0) {
::perror(SHARED_MEMORY_FILE);
exit(1);
}
/* Resize shared memory area to contain the population data
* - The area must contain m_unPopSize elements
* - Each element must have space for the data of an individual
* - Genome: m_unGenomeSize * sizeof(Real)
* - Score: sizeof(Real)
*/
size_t unShareMemSize = m_unPopSize * (m_unGenomeSize+1) * sizeof(Real);
::ftruncate(m_nSharedMemFD, unShareMemSize);
/* Get pointer to shared memory area */
m_pfSharedMem = reinterpret_cast<Real*>(
::mmap(NULL,
unShareMemSize,
PROT_READ | PROT_WRITE,
MAP_SHARED,
m_nSharedMemFD,
0));
if(m_pfSharedMem == MAP_FAILED) {
::perror("shared memory");
exit(1);
}
}
/****************************************/
/****************************************/
CMPGA::CSharedMem::~CSharedMem() {
munmap(m_pfSharedMem, m_unPopSize * (m_unGenomeSize+1) * sizeof(Real));
close(m_nSharedMemFD);
shm_unlink(SHARED_MEMORY_FILE);
}
/****************************************/
/****************************************/
Real* CMPGA::CSharedMem::GetGenome(UInt32 un_individual) {
return m_pfSharedMem + un_individual * (m_unGenomeSize+1);
}
/****************************************/
/****************************************/
void CMPGA::CSharedMem::SetGenome(UInt32 un_individual,
const Real* pf_genome) {
::memcpy(m_pfSharedMem + un_individual * (m_unGenomeSize+1),
pf_genome,
m_unGenomeSize * sizeof(Real));
}
/****************************************/
/****************************************/
Real CMPGA::CSharedMem::GetScore(UInt32 un_individual) {
return m_pfSharedMem[un_individual * (m_unGenomeSize+1) + m_unGenomeSize];
}
/****************************************/
/****************************************/
void CMPGA::CSharedMem::SetScore(UInt32 un_individual,
Real f_score) {
m_pfSharedMem[un_individual * (m_unGenomeSize+1) + m_unGenomeSize] = f_score;
}
/****************************************/
/****************************************/
<|endoftext|>
|
<commit_before>/*
* An istream which duplicates data.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "istream_tee.hxx"
#include "istream_oo.hxx"
#include "istream_pointer.hxx"
#include "pool.hxx"
#include "util/Cast.hxx"
#include <assert.h>
struct TeeIstream {
struct {
struct istream istream;
/**
* A weak output is one which is closed automatically when all
* "strong" outputs have been closed - it will not keep up the
* istream_tee object alone.
*/
bool weak;
bool enabled = true;
} outputs[2];
IstreamPointer input;
/**
* These flags control whether istream_tee_close[12]() may restart
* reading for the other output.
*/
bool reading = false, in_data = false;
#ifndef NDEBUG
bool closed_while_reading = false, closed_while_data = false;
#endif
/**
* The number of bytes to skip for output 0. The first output has
* already consumed this many bytes, but the second output
* blocked.
*/
size_t skip = 0;
TeeIstream(struct istream &_input,
bool first_weak, bool second_weak)
:input(_input, MakeIstreamHandler<TeeIstream>::handler, this)
{
outputs[0].weak = first_weak;
outputs[1].weak = second_weak;
}
size_t Feed0(const char *data, size_t length);
size_t Feed1(const void *data, size_t length);
size_t Feed(const void *data, size_t length);
/* handler */
size_t OnData(const void *data, size_t length);
ssize_t OnDirect(gcc_unused FdType type, gcc_unused int fd,
gcc_unused size_t max_length) {
// TODO: implement that using sys_tee()
gcc_unreachable();
}
void OnEof();
void OnError(GError *error);
};
static GQuark
tee_quark(void)
{
return g_quark_from_static_string("tee");
}
inline size_t
TeeIstream::Feed0(const char *data, size_t length)
{
if (!outputs[0].enabled)
return length;
if (length <= skip)
/* all of this has already been sent to the first input, but
the second one didn't accept it yet */
return length;
/* skip the part which was already sent */
data += skip;
length -= skip;
size_t nbytes = istream_invoke_data(&outputs[0].istream,
data, length);
if (nbytes > 0) {
skip += nbytes;
return skip;
}
if (outputs[0].enabled || !outputs[1].enabled)
/* first output is blocking, or both closed: give up */
return 0;
/* the first output has been closed inside the data() callback,
but the second is still alive: continue with the second
output */
return length;
}
inline size_t
TeeIstream::Feed1(const void *data, size_t length)
{
if (!outputs[1].enabled)
return length;
size_t nbytes = istream_invoke_data(&outputs[1].istream, data, length);
if (nbytes == 0 && !outputs[1].enabled &&
outputs[0].enabled)
/* during the data callback, outputs[1] has been closed,
but outputs[0] continues; instead of returning 0 here,
use outputs[0]'s result */
return length;
return nbytes;
}
inline size_t
TeeIstream::Feed(const void *data, size_t length)
{
size_t nbytes0 = Feed0((const char *)data, length);
if (nbytes0 == 0)
return 0;
size_t nbytes1 = Feed1(data, nbytes0);
if (nbytes1 > 0 && outputs[0].enabled) {
assert(nbytes1 <= skip);
skip -= nbytes1;
}
return nbytes1;
}
/*
* istream handler
*
*/
inline size_t
TeeIstream::OnData(const void *data, size_t length)
{
assert(input.IsDefined());
assert(!in_data);
const ScopePoolRef ref(*outputs[0].istream.pool TRACE_ARGS);
in_data = true;
size_t nbytes = Feed(data, length);
in_data = false;
return nbytes;
}
inline void
TeeIstream::OnEof()
{
assert(input.IsDefined());
input.Clear();
const ScopePoolRef ref(*outputs[0].istream.pool TRACE_ARGS);
/* clean up in reverse order */
if (outputs[1].enabled) {
outputs[1].enabled = false;
istream_deinit_eof(&outputs[1].istream);
}
if (outputs[0].enabled) {
outputs[0].enabled = false;
istream_deinit_eof(&outputs[0].istream);
}
}
inline void
TeeIstream::OnError(GError *error)
{
assert(input.IsDefined());
input.Clear();
const ScopePoolRef ref(*outputs[0].istream.pool TRACE_ARGS);
/* clean up in reverse order */
if (outputs[1].enabled) {
outputs[1].enabled = false;
istream_deinit_abort(&outputs[1].istream, g_error_copy(error));
}
if (outputs[0].enabled) {
outputs[0].enabled = false;
istream_deinit_abort(&outputs[0].istream, g_error_copy(error));
}
g_error_free(error);
}
/*
* istream implementation 0
*
*/
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wextended-offsetof"
#endif
static inline TeeIstream &
istream_to_tee0(struct istream *istream)
{
return *ContainerCast(istream, TeeIstream, outputs[0].istream);
}
static off_t
istream_tee_available0(struct istream *istream, bool partial)
{
TeeIstream &tee = istream_to_tee0(istream);
assert(tee.outputs[0].enabled);
return tee.input.GetAvailable(partial);
}
static void
istream_tee_read0(struct istream *istream)
{
TeeIstream &tee = istream_to_tee0(istream);
assert(tee.outputs[0].enabled);
assert(!tee.reading);
const ScopePoolRef ref(*tee.outputs[0].istream.pool TRACE_ARGS);
tee.reading = true;
tee.input.Read();
tee.reading = false;
}
static void
istream_tee_close0(struct istream *istream)
{
TeeIstream &tee = istream_to_tee0(istream);
assert(tee.outputs[0].enabled);
tee.outputs[0].enabled = false;
#ifndef NDEBUG
if (tee.reading)
tee.closed_while_reading = true;
if (tee.in_data)
tee.closed_while_data = true;
#endif
if (tee.input.IsDefined()) {
if (!tee.outputs[1].enabled)
tee.input.ClearAndClose();
else if (tee.outputs[1].weak) {
const ScopePoolRef ref(*tee.outputs[0].istream.pool TRACE_ARGS);
tee.input.ClearAndClose();
if (tee.outputs[1].enabled) {
tee.outputs[1].enabled = false;
GError *error =
g_error_new_literal(tee_quark(), 0,
"closing the weak second output");
istream_deinit_abort(&tee.outputs[1].istream, error);
}
}
}
if (tee.input.IsDefined() && tee.outputs[1].enabled &&
istream_has_handler(&tee.outputs[1].istream) &&
!tee.in_data && !tee.reading)
tee.input.Read();
istream_deinit(&tee.outputs[0].istream);
}
static const struct istream_class istream_tee0 = {
.available = istream_tee_available0,
.read = istream_tee_read0,
.close = istream_tee_close0,
};
/*
* istream implementation 2
*
*/
static inline TeeIstream &
istream_to_tee1(struct istream *istream)
{
return *ContainerCast(istream, TeeIstream, outputs[1].istream);
}
static off_t
istream_tee_available1(struct istream *istream, bool partial)
{
TeeIstream &tee = istream_to_tee1(istream);
assert(tee.outputs[1].enabled);
return tee.input.GetAvailable(partial);
}
static void
istream_tee_read1(struct istream *istream)
{
TeeIstream &tee = istream_to_tee1(istream);
assert(!tee.reading);
const ScopePoolRef ref(*tee.outputs[0].istream.pool TRACE_ARGS);
tee.reading = true;
tee.input.Read();
tee.reading = false;
}
static void
istream_tee_close1(struct istream *istream)
{
TeeIstream &tee = istream_to_tee1(istream);
assert(tee.outputs[1].enabled);
tee.outputs[1].enabled = false;
#ifndef NDEBUG
if (tee.reading)
tee.closed_while_reading = true;
if (tee.in_data)
tee.closed_while_data = true;
#endif
if (tee.input.IsDefined()) {
if (!tee.outputs[0].enabled)
tee.input.ClearAndClose();
else if (tee.outputs[0].weak) {
const ScopePoolRef ref(*tee.outputs[0].istream.pool TRACE_ARGS);
tee.input.ClearAndClose();
if (tee.outputs[0].enabled) {
tee.outputs[0].enabled = false;
GError *error =
g_error_new_literal(tee_quark(), 0,
"closing the weak first output");
istream_deinit_abort(&tee.outputs[0].istream, error);
}
}
}
if (tee.input.IsDefined() && tee.outputs[0].enabled &&
istream_has_handler(&tee.outputs[0].istream) &&
!tee.in_data && !tee.reading)
tee.input.Read();
istream_deinit(&tee.outputs[1].istream);
}
static const struct istream_class istream_tee1 = {
.available = istream_tee_available1,
.read = istream_tee_read1,
.close = istream_tee_close1,
};
/*
* constructor
*
*/
struct istream *
istream_tee_new(struct pool *pool, struct istream *input,
bool first_weak, bool second_weak)
{
assert(input != nullptr);
assert(!istream_has_handler(input));
auto tee = NewFromPool<TeeIstream>(*pool, *input,
first_weak, second_weak);
istream_init(&tee->outputs[0].istream, &istream_tee0, pool);
istream_init(&tee->outputs[1].istream, &istream_tee1, pool);
return &tee->outputs[0].istream;
}
struct istream *
istream_tee_second(struct istream *istream)
{
TeeIstream &tee = istream_to_tee0(istream);
return &tee.outputs[1].istream;
}
<commit_msg>istream_tee: rename outputs[2] to first_output, second_output<commit_after>/*
* An istream which duplicates data.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "istream_tee.hxx"
#include "istream_oo.hxx"
#include "istream_pointer.hxx"
#include "pool.hxx"
#include "util/Cast.hxx"
#include <assert.h>
struct TeeIstream {
struct {
struct istream istream;
/**
* A weak output is one which is closed automatically when all
* "strong" outputs have been closed - it will not keep up the
* istream_tee object alone.
*/
bool weak;
bool enabled = true;
} first_output, second_output;
IstreamPointer input;
/**
* These flags control whether istream_tee_close[12]() may restart
* reading for the other output.
*/
bool reading = false, in_data = false;
#ifndef NDEBUG
bool closed_while_reading = false, closed_while_data = false;
#endif
/**
* The number of bytes to skip for output 0. The first output has
* already consumed this many bytes, but the second output
* blocked.
*/
size_t skip = 0;
TeeIstream(struct istream &_input,
bool first_weak, bool second_weak)
:input(_input, MakeIstreamHandler<TeeIstream>::handler, this)
{
first_output.weak = first_weak;
second_output.weak = second_weak;
}
size_t Feed0(const char *data, size_t length);
size_t Feed1(const void *data, size_t length);
size_t Feed(const void *data, size_t length);
/* handler */
size_t OnData(const void *data, size_t length);
ssize_t OnDirect(gcc_unused FdType type, gcc_unused int fd,
gcc_unused size_t max_length) {
// TODO: implement that using sys_tee()
gcc_unreachable();
}
void OnEof();
void OnError(GError *error);
};
static GQuark
tee_quark(void)
{
return g_quark_from_static_string("tee");
}
inline size_t
TeeIstream::Feed0(const char *data, size_t length)
{
if (!first_output.enabled)
return length;
if (length <= skip)
/* all of this has already been sent to the first input, but
the second one didn't accept it yet */
return length;
/* skip the part which was already sent */
data += skip;
length -= skip;
size_t nbytes = istream_invoke_data(&first_output.istream,
data, length);
if (nbytes > 0) {
skip += nbytes;
return skip;
}
if (first_output.enabled || !second_output.enabled)
/* first output is blocking, or both closed: give up */
return 0;
/* the first output has been closed inside the data() callback,
but the second is still alive: continue with the second
output */
return length;
}
inline size_t
TeeIstream::Feed1(const void *data, size_t length)
{
if (!second_output.enabled)
return length;
size_t nbytes = istream_invoke_data(&second_output.istream, data, length);
if (nbytes == 0 && !second_output.enabled &&
first_output.enabled)
/* during the data callback, second_output has been closed,
but first_output continues; instead of returning 0 here,
use first_output's result */
return length;
return nbytes;
}
inline size_t
TeeIstream::Feed(const void *data, size_t length)
{
size_t nbytes0 = Feed0((const char *)data, length);
if (nbytes0 == 0)
return 0;
size_t nbytes1 = Feed1(data, nbytes0);
if (nbytes1 > 0 && first_output.enabled) {
assert(nbytes1 <= skip);
skip -= nbytes1;
}
return nbytes1;
}
/*
* istream handler
*
*/
inline size_t
TeeIstream::OnData(const void *data, size_t length)
{
assert(input.IsDefined());
assert(!in_data);
const ScopePoolRef ref(*first_output.istream.pool TRACE_ARGS);
in_data = true;
size_t nbytes = Feed(data, length);
in_data = false;
return nbytes;
}
inline void
TeeIstream::OnEof()
{
assert(input.IsDefined());
input.Clear();
const ScopePoolRef ref(*first_output.istream.pool TRACE_ARGS);
/* clean up in reverse order */
if (second_output.enabled) {
second_output.enabled = false;
istream_deinit_eof(&second_output.istream);
}
if (first_output.enabled) {
first_output.enabled = false;
istream_deinit_eof(&first_output.istream);
}
}
inline void
TeeIstream::OnError(GError *error)
{
assert(input.IsDefined());
input.Clear();
const ScopePoolRef ref(*first_output.istream.pool TRACE_ARGS);
/* clean up in reverse order */
if (second_output.enabled) {
second_output.enabled = false;
istream_deinit_abort(&second_output.istream, g_error_copy(error));
}
if (first_output.enabled) {
first_output.enabled = false;
istream_deinit_abort(&first_output.istream, g_error_copy(error));
}
g_error_free(error);
}
/*
* istream implementation 0
*
*/
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wextended-offsetof"
#endif
static inline TeeIstream &
istream_to_tee0(struct istream *istream)
{
return *ContainerCast(istream, TeeIstream, first_output.istream);
}
static off_t
istream_tee_available0(struct istream *istream, bool partial)
{
TeeIstream &tee = istream_to_tee0(istream);
assert(tee.first_output.enabled);
return tee.input.GetAvailable(partial);
}
static void
istream_tee_read0(struct istream *istream)
{
TeeIstream &tee = istream_to_tee0(istream);
assert(tee.first_output.enabled);
assert(!tee.reading);
const ScopePoolRef ref(*tee.first_output.istream.pool TRACE_ARGS);
tee.reading = true;
tee.input.Read();
tee.reading = false;
}
static void
istream_tee_close0(struct istream *istream)
{
TeeIstream &tee = istream_to_tee0(istream);
assert(tee.first_output.enabled);
tee.first_output.enabled = false;
#ifndef NDEBUG
if (tee.reading)
tee.closed_while_reading = true;
if (tee.in_data)
tee.closed_while_data = true;
#endif
if (tee.input.IsDefined()) {
if (!tee.second_output.enabled)
tee.input.ClearAndClose();
else if (tee.second_output.weak) {
const ScopePoolRef ref(*tee.first_output.istream.pool TRACE_ARGS);
tee.input.ClearAndClose();
if (tee.second_output.enabled) {
tee.second_output.enabled = false;
GError *error =
g_error_new_literal(tee_quark(), 0,
"closing the weak second output");
istream_deinit_abort(&tee.second_output.istream, error);
}
}
}
if (tee.input.IsDefined() && tee.second_output.enabled &&
istream_has_handler(&tee.second_output.istream) &&
!tee.in_data && !tee.reading)
tee.input.Read();
istream_deinit(&tee.first_output.istream);
}
static const struct istream_class istream_tee0 = {
.available = istream_tee_available0,
.read = istream_tee_read0,
.close = istream_tee_close0,
};
/*
* istream implementation 2
*
*/
static inline TeeIstream &
istream_to_tee1(struct istream *istream)
{
return *ContainerCast(istream, TeeIstream, second_output.istream);
}
static off_t
istream_tee_available1(struct istream *istream, bool partial)
{
TeeIstream &tee = istream_to_tee1(istream);
assert(tee.second_output.enabled);
return tee.input.GetAvailable(partial);
}
static void
istream_tee_read1(struct istream *istream)
{
TeeIstream &tee = istream_to_tee1(istream);
assert(!tee.reading);
const ScopePoolRef ref(*tee.first_output.istream.pool TRACE_ARGS);
tee.reading = true;
tee.input.Read();
tee.reading = false;
}
static void
istream_tee_close1(struct istream *istream)
{
TeeIstream &tee = istream_to_tee1(istream);
assert(tee.second_output.enabled);
tee.second_output.enabled = false;
#ifndef NDEBUG
if (tee.reading)
tee.closed_while_reading = true;
if (tee.in_data)
tee.closed_while_data = true;
#endif
if (tee.input.IsDefined()) {
if (!tee.first_output.enabled)
tee.input.ClearAndClose();
else if (tee.first_output.weak) {
const ScopePoolRef ref(*tee.first_output.istream.pool TRACE_ARGS);
tee.input.ClearAndClose();
if (tee.first_output.enabled) {
tee.first_output.enabled = false;
GError *error =
g_error_new_literal(tee_quark(), 0,
"closing the weak first output");
istream_deinit_abort(&tee.first_output.istream, error);
}
}
}
if (tee.input.IsDefined() && tee.first_output.enabled &&
istream_has_handler(&tee.first_output.istream) &&
!tee.in_data && !tee.reading)
tee.input.Read();
istream_deinit(&tee.second_output.istream);
}
static const struct istream_class istream_tee1 = {
.available = istream_tee_available1,
.read = istream_tee_read1,
.close = istream_tee_close1,
};
/*
* constructor
*
*/
struct istream *
istream_tee_new(struct pool *pool, struct istream *input,
bool first_weak, bool second_weak)
{
assert(input != nullptr);
assert(!istream_has_handler(input));
auto tee = NewFromPool<TeeIstream>(*pool, *input,
first_weak, second_weak);
istream_init(&tee->first_output.istream, &istream_tee0, pool);
istream_init(&tee->second_output.istream, &istream_tee1, pool);
return &tee->first_output.istream;
}
struct istream *
istream_tee_second(struct istream *istream)
{
TeeIstream &tee = istream_to_tee0(istream);
return &tee.second_output.istream;
}
<|endoftext|>
|
<commit_before>#include "sink_buffer.hxx"
#include "istream_oo.hxx"
#include "async.hxx"
#include "pool.hxx"
#include "util/Cast.hxx"
#include <glib.h>
#include <assert.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
struct BufferSink {
struct pool *pool;
struct istream *input;
unsigned char *buffer;
size_t size, position;
const struct sink_buffer_handler *handler;
void *handler_ctx;
struct async_operation async_operation;
/* istream handler */
size_t OnData(const void *data, size_t length);
ssize_t OnDirect(FdType type, int fd, size_t max_length);;
void OnEof();
void OnError(GError *error);
};
static GQuark
sink_buffer_quark(void)
{
return g_quark_from_static_string("sink_buffer");
}
/*
* istream handler
*
*/
inline size_t
BufferSink::OnData(const void *data, size_t length)
{
assert(position < size);
assert(length <= size - position);
memcpy(buffer + position, data, length);
position += length;
return length;
}
inline ssize_t
BufferSink::OnDirect(FdType type, int fd, size_t max_length)
{
size_t length = size - position;
if (length > max_length)
length = max_length;
ssize_t nbytes = type == FdType::FD_SOCKET || type == FdType::FD_TCP
? recv(fd, buffer + position, length, MSG_DONTWAIT)
: read(fd, buffer + position, length);
if (nbytes > 0)
position += (size_t)nbytes;
return nbytes;
}
inline void
BufferSink::OnEof()
{
assert(position == size);
async_operation.Finished();
handler->done(buffer, size, handler_ctx);
}
inline void
BufferSink::OnError(GError *error)
{
async_operation.Finished();
handler->error(error, handler_ctx);
}
/*
* async operation
*
*/
static BufferSink *
async_to_sink_buffer(struct async_operation *ao)
{
return &ContainerCast2(*ao, &BufferSink::async_operation);
}
static void
sink_buffer_abort(struct async_operation *ao)
{
BufferSink *buffer = async_to_sink_buffer(ao);
const ScopePoolRef ref(*buffer->pool TRACE_ARGS);
istream_close_handler(buffer->input);
}
static const struct async_operation_class sink_buffer_operation = {
.abort = sink_buffer_abort,
};
/*
* constructor
*
*/
void
sink_buffer_new(struct pool *pool, struct istream *input,
const struct sink_buffer_handler *handler, void *ctx,
struct async_operation_ref *async_ref)
{
off_t available;
static char empty_buffer[1];
assert(input != NULL);
assert(!istream_has_handler(input));
assert(handler != NULL);
assert(handler->done != NULL);
assert(handler->error != NULL);
available = istream_available(input, false);
if (available == -1 || available >= 0x10000000) {
istream_close_unused(input);
GError *error =
g_error_new_literal(sink_buffer_quark(), 0,
available < 0
? "unknown stream length"
: "stream is too large");
handler->error(error, ctx);
return;
}
if (available == 0) {
istream_close_unused(input);
handler->done(empty_buffer, 0, ctx);
return;
}
auto buffer = NewFromPool<BufferSink>(*pool);
buffer->pool = pool;
istream_assign_handler(&buffer->input, input,
&MakeIstreamHandler<BufferSink>::handler, buffer,
FD_ANY);
buffer->size = (size_t)available;
buffer->position = 0;
buffer->buffer = (unsigned char *)p_malloc(pool, buffer->size);
buffer->handler = handler;
buffer->handler_ctx = ctx;
buffer->async_operation.Init(sink_buffer_operation);
async_ref->Set(buffer->async_operation);
}
<commit_msg>sink_buffer: add constructor<commit_after>#include "sink_buffer.hxx"
#include "istream_oo.hxx"
#include "async.hxx"
#include "pool.hxx"
#include "util/Cast.hxx"
#include <glib.h>
#include <assert.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
struct BufferSink {
struct pool *pool;
struct istream *input;
unsigned char *const buffer;
const size_t size;
size_t position = 0;
const struct sink_buffer_handler *const handler;
void *handler_ctx;
struct async_operation async_operation;
BufferSink(struct pool &_pool, struct istream &_input, size_t available,
const struct sink_buffer_handler &_handler, void *ctx)
:pool(&_pool),
buffer((unsigned char *)p_malloc(pool, available)),
size(available),
handler(&_handler), handler_ctx(ctx) {
istream_assign_handler(&input, &_input,
&MakeIstreamHandler<BufferSink>::handler, this,
FD_ANY);
}
/* istream handler */
size_t OnData(const void *data, size_t length);
ssize_t OnDirect(FdType type, int fd, size_t max_length);;
void OnEof();
void OnError(GError *error);
};
static GQuark
sink_buffer_quark(void)
{
return g_quark_from_static_string("sink_buffer");
}
/*
* istream handler
*
*/
inline size_t
BufferSink::OnData(const void *data, size_t length)
{
assert(position < size);
assert(length <= size - position);
memcpy(buffer + position, data, length);
position += length;
return length;
}
inline ssize_t
BufferSink::OnDirect(FdType type, int fd, size_t max_length)
{
size_t length = size - position;
if (length > max_length)
length = max_length;
ssize_t nbytes = type == FdType::FD_SOCKET || type == FdType::FD_TCP
? recv(fd, buffer + position, length, MSG_DONTWAIT)
: read(fd, buffer + position, length);
if (nbytes > 0)
position += (size_t)nbytes;
return nbytes;
}
inline void
BufferSink::OnEof()
{
assert(position == size);
async_operation.Finished();
handler->done(buffer, size, handler_ctx);
}
inline void
BufferSink::OnError(GError *error)
{
async_operation.Finished();
handler->error(error, handler_ctx);
}
/*
* async operation
*
*/
static BufferSink *
async_to_sink_buffer(struct async_operation *ao)
{
return &ContainerCast2(*ao, &BufferSink::async_operation);
}
static void
sink_buffer_abort(struct async_operation *ao)
{
BufferSink *buffer = async_to_sink_buffer(ao);
const ScopePoolRef ref(*buffer->pool TRACE_ARGS);
istream_close_handler(buffer->input);
}
static const struct async_operation_class sink_buffer_operation = {
.abort = sink_buffer_abort,
};
/*
* constructor
*
*/
void
sink_buffer_new(struct pool *pool, struct istream *input,
const struct sink_buffer_handler *handler, void *ctx,
struct async_operation_ref *async_ref)
{
off_t available;
static char empty_buffer[1];
assert(input != NULL);
assert(!istream_has_handler(input));
assert(handler != NULL);
assert(handler->done != NULL);
assert(handler->error != NULL);
available = istream_available(input, false);
if (available == -1 || available >= 0x10000000) {
istream_close_unused(input);
GError *error =
g_error_new_literal(sink_buffer_quark(), 0,
available < 0
? "unknown stream length"
: "stream is too large");
handler->error(error, ctx);
return;
}
if (available == 0) {
istream_close_unused(input);
handler->done(empty_buffer, 0, ctx);
return;
}
auto buffer = NewFromPool<BufferSink>(*pool, *pool, *input, available,
*handler, ctx);
buffer->async_operation.Init(sink_buffer_operation);
async_ref->Set(buffer->async_operation);
}
<|endoftext|>
|
<commit_before>/** \file
*
* Copyright (c) 2012-2014 by Travis Gockel. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it under the terms of the Apache License
* as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later
* version.
*
* \author Travis Gockel (travis@gockelhut.com)
**/
#include <json-voorhees/parse.hpp>
#include <json-voorhees/array.hpp>
#include <json-voorhees/object.hpp>
#include <json-voorhees/detail/shared_buffer.hpp>
#include "char_convert.hpp"
#include <cassert>
#include <cctype>
#include <istream>
#include <set>
#include <sstream>
#include <boost/lexical_cast.hpp>
#if 0
# include <iostream>
# define JSONV_DBG_NEXT(x) std::cout << x
# define JSONV_DBG_STRUCT(x) std::cout << "\033[0;32m" << x << "\033[m"
#else
# define JSONV_DBG_NEXT(x)
# define JSONV_DBG_STRUCT(x)
#endif
namespace jsonv
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// parse_error //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static std::string parse_error_what(std::size_t line,
std::size_t column,
std::size_t character,
const std::string& message
)
{
std::ostringstream stream;
stream << "On line " << line << " column " << column << " (char " << character << "): " << message;
return stream.str();
}
parse_error::parse_error(size_type line_, size_type column_, size_type character_, const std::string& message_) :
std::runtime_error(parse_error_what(line_, column_, character_, message_)),
_line(line_),
_column(column_),
_character(character_),
_message(message_)
{ }
parse_error::~parse_error() throw()
{ }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// parse //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace detail
{
struct parse_context
{
typedef shared_buffer::size_type size_type;
size_type line;
size_type column;
size_type character;
const char* input;
size_type input_size;
char current;
bool backed_off;
explicit parse_context(const char* input, size_type length) :
line(0),
column(0),
character(0),
input(input),
input_size(length),
backed_off(false)
{ }
parse_context(const parse_context&) = delete;
parse_context& operator=(const parse_context&) = delete;
bool next()
{
if (backed_off)
{
backed_off = false;
return true;
}
if (character < input_size)
{
current = input[character];
JSONV_DBG_NEXT(current);
++character;
if (current == '\n' || current == '\r')
{
++line;
column = 0;
}
else
++column;
return true;
}
else
return false;
}
void previous()
{
if (backed_off)
parse_error("Internal parser error");
backed_off = true;
}
template <typename... T>
void parse_error(T&&... message) const
{
std::ostringstream stream;
parse_error_impl(stream, std::forward<T>(message)...);
}
private:
void parse_error_impl(std::ostringstream& stream) const
{
throw jsonv::parse_error(line, column, character, stream.str());
}
template <typename T, typename... TRest>
void parse_error_impl(std::ostringstream& stream, T&& current, TRest&&... rest) const
{
stream << std::forward<T>(current);
parse_error_impl(stream, std::forward<TRest>(rest)...);
}
};
static bool parse_generic(parse_context& context, value& out, bool eat_whitespace = true);
static bool eat_whitespace(parse_context& context)
{
while (context.next())
{
if (!isspace(context.current))
return true;
}
return false;
}
static value parse_literal(parse_context& context, const value& outval, const char* const literal)
{
assert(context.current == *literal);
for (const char* ptr = literal; *ptr; ++ptr)
{
if (context.current != *ptr)
context.parse_error("Unexpected character '", context.current, "' while trying to match ", literal);
if (!context.next() && ptr[1])
context.parse_error("Unexpected end while trying to match ", literal);
}
context.previous();
return outval;
}
static value parse_null(parse_context& context)
{
return parse_literal(context, value(), "null");
}
static value parse_true(parse_context& context)
{
return parse_literal(context, true, "true");
}
static value parse_false(parse_context& context)
{
return parse_literal(context, false, "false");
}
static std::set<char> get_allowed_number_chars()
{
const std::string allowed_chars_src("-0123456789+-eE.");
return std::set<char>(allowed_chars_src.begin(), allowed_chars_src.end());
}
static value parse_number(parse_context& context)
{
// Regex is probably the more "right" way to get a number, but lexical_cast is faster and easier.
//typedef std::regex regex;
//static const regex number_pattern("^(-)?(0|[1-9][0-9]*)(?:(\\.)([0-9]+))?(?:([eE])([+-])?([0-9]+))?$");
// 0 |1 |2 |3 |4 |5 |6
// sign|whole |dot |decimal |ise |esign |exp
// re.compile("^(-)?(0|[1-9][0-9]*)(?:(\\.)([0-9]+))?(?:([eE])([+-])?([0-9]+))?$") \.
// .match('-123.45e+67').groups()
// ('-', '123', '.', '45', 'e', '+', '67')
static std::set<char> allowed_chars = get_allowed_number_chars();
std::string characters(1, context.current);
bool is_double = false;
while (true)
{
if (!context.next())
// it is okay to end the stream in the middle of a number
break;
if (!allowed_chars.count(context.current))
{
context.previous();
break;
}
else
{
if (context.current == '.')
is_double = true;
characters += context.current;
}
}
try
{
if (is_double)
return boost::lexical_cast<double>(characters);
else if (characters[0] == '-')
return boost::lexical_cast<int64_t>(characters);
else
return static_cast<int64_t>(boost::lexical_cast<uint64_t>(characters));
}
catch (boost::bad_lexical_cast&)
{
context.parse_error("Could not extract ", is_double ? "real" : "integer", " from \"", characters, "\"");
return value();
}
}
static std::string parse_string(parse_context& context)
{
assert(context.current == '\"');
const char* characters_start = context.input + context.character;
std::size_t characters_count = 0;
while (true)
{
if (!context.next())
{
context.parse_error("Unterminated string \"", std::string(characters_start, characters_count));
break;
}
if (context.current == '\"')
{
if (characters_count > 0 && characters_start[characters_count-1] == '\\'
&& !(characters_count > 1 && characters_start[characters_count-2] == '\\') //already escaped
)
{
++characters_count;
}
else
break;
}
else
{
++characters_count;
}
}
try
{
return string_decode(characters_start, characters_count);
}
catch (const detail::decode_error& err)
{
context.parse_error("Error decoding string:", err.what());
// return it un-decoded
return std::string(characters_start, characters_count);
}
}
static value parse_array(parse_context& context)
{
assert(context.current == '[');
JSONV_DBG_STRUCT('[');
array arr;
while (true)
{
if (!eat_whitespace(context))
{
context.parse_error("Unexpected end: unmatched '['");
break;
}
if (context.current == ']')
{
break;
}
else if (context.current == ',')
continue;
else
{
value val;
if (parse_generic(context, val, false))
{
arr.push_back(val);
}
else
{
context.parse_error("Unexpected end: unmatched '['");
break;
}
}
}
JSONV_DBG_STRUCT(']');
return arr;
}
static value parse_object(parse_context& context)
{
assert(context.current == '{');
JSONV_DBG_STRUCT('{');
object obj;
while (true)
{
if (!eat_whitespace(context))
context.parse_error("Unexpected end: unmatched '{'");
switch (context.current)
{
case ',':
// Jump over all commas in a row.
break;
case '\"':
{
JSONV_DBG_STRUCT('(');
std::string key = parse_string(context);
if (!eat_whitespace(context))
context.parse_error("Unexpected end: missing ':' for key '", key, "'");
if (context.current != ':')
context.parse_error("Invalid character '", context.current, "' expecting ':'");
value val;
if (!parse_generic(context, val))
context.parse_error("Unexpected end: missing value for key '", key, "'");
//object::iterator iter = obj.find(key);
//if (iter != obj.end())
// context.parse_error("Duplicate key \"", key, "\"");
obj[key] = val;
JSONV_DBG_STRUCT(')');
break;
}
case '}':
JSONV_DBG_STRUCT('}');
return obj;
default:
context.parse_error("Invalid character '", context.current, "' expecting '}' or a key (string)");
return obj;
}
}
}
static bool parse_generic(parse_context& context, value& out, bool eat_whitespace_)
{
if (eat_whitespace_)
if (!eat_whitespace(context))
return false;
switch (context.current)
{
case '{':
out = parse_object(context);
return true;
case '[':
out = parse_array(context);
return true;
case '\"':
out = parse_string(context);
return true;
case 'n':
out = parse_null(context);
return true;
case 't':
out = parse_true(context);
return true;
case 'f':
out = parse_false(context);
return true;
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
out = parse_number(context);
return true;
default:
context.parse_error("Invalid character '", context.current, "'");
return true;
}
}
}
value parse(const char* input, std::size_t length)
{
detail::parse_context context(input, length);
value out;
if (detail::parse_generic(context, out))
{
return out;
}
else
{
context.parse_error("No input");
return out;
}
}
value parse(std::istream& input)
{
// Copy the input into a buffer
input.seekg(0, std::ios::end);
std::size_t len = input.tellg();
detail::shared_buffer buffer(len);
input.seekg(0, std::ios::beg);
std::copy(std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>(),
buffer.get_mutable(0, len)
);
return parse(buffer.cbegin(), buffer.size());
}
value parse(const std::string& source)
{
return parse(source.c_str(), source.size());
}
}
<commit_msg>Issue 28: In parse_number, do not place characters in the std::string one byte at a time.<commit_after>/** \file
*
* Copyright (c) 2012-2014 by Travis Gockel. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it under the terms of the Apache License
* as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later
* version.
*
* \author Travis Gockel (travis@gockelhut.com)
**/
#include <json-voorhees/parse.hpp>
#include <json-voorhees/array.hpp>
#include <json-voorhees/object.hpp>
#include <json-voorhees/detail/shared_buffer.hpp>
#include "char_convert.hpp"
#include <cassert>
#include <cctype>
#include <istream>
#include <set>
#include <sstream>
#include <boost/lexical_cast.hpp>
#if 0
# include <iostream>
# define JSONV_DBG_NEXT(x) std::cout << x
# define JSONV_DBG_STRUCT(x) std::cout << "\033[0;32m" << x << "\033[m"
#else
# define JSONV_DBG_NEXT(x)
# define JSONV_DBG_STRUCT(x)
#endif
namespace jsonv
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// parse_error //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static std::string parse_error_what(std::size_t line,
std::size_t column,
std::size_t character,
const std::string& message
)
{
std::ostringstream stream;
stream << "On line " << line << " column " << column << " (char " << character << "): " << message;
return stream.str();
}
parse_error::parse_error(size_type line_, size_type column_, size_type character_, const std::string& message_) :
std::runtime_error(parse_error_what(line_, column_, character_, message_)),
_line(line_),
_column(column_),
_character(character_),
_message(message_)
{ }
parse_error::~parse_error() throw()
{ }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// parse //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace detail
{
struct parse_context
{
typedef shared_buffer::size_type size_type;
size_type line;
size_type column;
size_type character;
const char* input;
size_type input_size;
char current;
bool backed_off;
explicit parse_context(const char* input, size_type length) :
line(0),
column(0),
character(0),
input(input),
input_size(length),
backed_off(false)
{ }
parse_context(const parse_context&) = delete;
parse_context& operator=(const parse_context&) = delete;
bool next()
{
if (backed_off)
{
backed_off = false;
return true;
}
if (character < input_size)
{
current = input[character];
JSONV_DBG_NEXT(current);
++character;
if (current == '\n' || current == '\r')
{
++line;
column = 0;
}
else
++column;
return true;
}
else
return false;
}
void previous()
{
if (backed_off)
parse_error("Internal parser error");
backed_off = true;
}
template <typename... T>
void parse_error(T&&... message) const
{
std::ostringstream stream;
parse_error_impl(stream, std::forward<T>(message)...);
}
private:
void parse_error_impl(std::ostringstream& stream) const
{
throw jsonv::parse_error(line, column, character, stream.str());
}
template <typename T, typename... TRest>
void parse_error_impl(std::ostringstream& stream, T&& current, TRest&&... rest) const
{
stream << std::forward<T>(current);
parse_error_impl(stream, std::forward<TRest>(rest)...);
}
};
static bool parse_generic(parse_context& context, value& out, bool eat_whitespace = true);
static bool eat_whitespace(parse_context& context)
{
while (context.next())
{
if (!isspace(context.current))
return true;
}
return false;
}
static value parse_literal(parse_context& context, const value& outval, const char* const literal)
{
assert(context.current == *literal);
for (const char* ptr = literal; *ptr; ++ptr)
{
if (context.current != *ptr)
context.parse_error("Unexpected character '", context.current, "' while trying to match ", literal);
if (!context.next() && ptr[1])
context.parse_error("Unexpected end while trying to match ", literal);
}
context.previous();
return outval;
}
static value parse_null(parse_context& context)
{
return parse_literal(context, value(), "null");
}
static value parse_true(parse_context& context)
{
return parse_literal(context, true, "true");
}
static value parse_false(parse_context& context)
{
return parse_literal(context, false, "false");
}
static std::set<char> get_allowed_number_chars()
{
const std::string allowed_chars_src("-0123456789+-eE.");
return std::set<char>(allowed_chars_src.begin(), allowed_chars_src.end());
}
static value parse_number(parse_context& context)
{
// Regex is probably the more "right" way to get a number, but lexical_cast is faster and easier.
//typedef std::regex regex;
//static const regex number_pattern("^(-)?(0|[1-9][0-9]*)(?:(\\.)([0-9]+))?(?:([eE])([+-])?([0-9]+))?$");
// 0 |1 |2 |3 |4 |5 |6
// sign|whole |dot |decimal |ise |esign |exp
// re.compile("^(-)?(0|[1-9][0-9]*)(?:(\\.)([0-9]+))?(?:([eE])([+-])?([0-9]+))?$") \.
// .match('-123.45e+67').groups()
// ('-', '123', '.', '45', 'e', '+', '67')
static std::set<char> allowed_chars = get_allowed_number_chars();
const char* characters_start = context.input + context.character - 1;
std::size_t characters_count = 1;
bool is_double = false;
while (true)
{
if (!context.next())
// it is okay to end the stream in the middle of a number
break;
if (!allowed_chars.count(context.current))
{
context.previous();
break;
}
else
{
if (context.current == '.')
is_double = true;
++characters_count;
}
}
// TODO(performance): Creating a heap-allocated string here for the sole purpose of lexical_cast and an error
// message is rather pointless...
std::string characters(characters_start, characters_count);
try
{
if (is_double)
return boost::lexical_cast<double>(characters);
else if (characters[0] == '-')
return boost::lexical_cast<int64_t>(characters);
else
return static_cast<int64_t>(boost::lexical_cast<uint64_t>(characters));
}
catch (boost::bad_lexical_cast&)
{
context.parse_error("Could not extract ", is_double ? "real" : "integer", " from \"", characters, "\"");
return value();
}
}
static std::string parse_string(parse_context& context)
{
assert(context.current == '\"');
const char* characters_start = context.input + context.character;
std::size_t characters_count = 0;
while (true)
{
if (!context.next())
{
context.parse_error("Unterminated string \"", std::string(characters_start, characters_count));
break;
}
if (context.current == '\"')
{
if (characters_count > 0 && characters_start[characters_count-1] == '\\'
&& !(characters_count > 1 && characters_start[characters_count-2] == '\\') //already escaped
)
{
++characters_count;
}
else
break;
}
else
{
++characters_count;
}
}
try
{
return string_decode(characters_start, characters_count);
}
catch (const detail::decode_error& err)
{
context.parse_error("Error decoding string:", err.what());
// return it un-decoded
return std::string(characters_start, characters_count);
}
}
static value parse_array(parse_context& context)
{
assert(context.current == '[');
JSONV_DBG_STRUCT('[');
array arr;
while (true)
{
if (!eat_whitespace(context))
{
context.parse_error("Unexpected end: unmatched '['");
break;
}
if (context.current == ']')
{
break;
}
else if (context.current == ',')
continue;
else
{
value val;
if (parse_generic(context, val, false))
{
arr.push_back(val);
}
else
{
context.parse_error("Unexpected end: unmatched '['");
break;
}
}
}
JSONV_DBG_STRUCT(']');
return arr;
}
static value parse_object(parse_context& context)
{
assert(context.current == '{');
JSONV_DBG_STRUCT('{');
object obj;
while (true)
{
if (!eat_whitespace(context))
context.parse_error("Unexpected end: unmatched '{'");
switch (context.current)
{
case ',':
// Jump over all commas in a row.
break;
case '\"':
{
JSONV_DBG_STRUCT('(');
std::string key = parse_string(context);
if (!eat_whitespace(context))
context.parse_error("Unexpected end: missing ':' for key '", key, "'");
if (context.current != ':')
context.parse_error("Invalid character '", context.current, "' expecting ':'");
value val;
if (!parse_generic(context, val))
context.parse_error("Unexpected end: missing value for key '", key, "'");
//object::iterator iter = obj.find(key);
//if (iter != obj.end())
// context.parse_error("Duplicate key \"", key, "\"");
obj[key] = val;
JSONV_DBG_STRUCT(')');
break;
}
case '}':
JSONV_DBG_STRUCT('}');
return obj;
default:
context.parse_error("Invalid character '", context.current, "' expecting '}' or a key (string)");
return obj;
}
}
}
static bool parse_generic(parse_context& context, value& out, bool eat_whitespace_)
{
if (eat_whitespace_)
if (!eat_whitespace(context))
return false;
switch (context.current)
{
case '{':
out = parse_object(context);
return true;
case '[':
out = parse_array(context);
return true;
case '\"':
out = parse_string(context);
return true;
case 'n':
out = parse_null(context);
return true;
case 't':
out = parse_true(context);
return true;
case 'f':
out = parse_false(context);
return true;
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
out = parse_number(context);
return true;
default:
context.parse_error("Invalid character '", context.current, "'");
return true;
}
}
}
value parse(const char* input, std::size_t length)
{
detail::parse_context context(input, length);
value out;
if (detail::parse_generic(context, out))
{
return out;
}
else
{
context.parse_error("No input");
return out;
}
}
value parse(std::istream& input)
{
// Copy the input into a buffer
input.seekg(0, std::ios::end);
std::size_t len = input.tellg();
detail::shared_buffer buffer(len);
input.seekg(0, std::ios::beg);
std::copy(std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>(),
buffer.get_mutable(0, len)
);
return parse(buffer.cbegin(), buffer.size());
}
value parse(const std::string& source)
{
return parse(source.c_str(), source.size());
}
}
<|endoftext|>
|
<commit_before>/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* All contents are licensed under LGPL V2.1 */
/* See LICENSE for full restrictions */
/****************************************************************/
//This kernel adds electromigration flux in the Cahn-Hilliard Equation
//Mathematically it is J_em=c*(D/kT)*z*eE
#include "SplitCHVoltage.h"
template<>
InputParameters validParams<SplitCHVoltage>()
{
InputParameters params = validParams<Kernel>();
params.addClassDescription("Add Electromigration Flux to Split formulation Cahn-Hilliard Kernel");
//params.addRequiredCoupledVar("T", "Temperature in Kelvin Scale");
params.addRequiredCoupledVar("volt", "Voltage");
params.addRequiredCoupledVar("c", "Concentration");
params.addRequiredParam<MaterialPropertyName>("diff_name", "The diffusivity used with the kernel");
params.addParam<MaterialPropertyName>("z_name", "zeff", "Effective charge number of the species");
//params.addParam<MaterialPropertyName>("e_name", "echarge", "Charge of the electron");
return params;
}
SplitCHVoltage::SplitCHVoltage(const std::string & name, InputParameters parameters) :
Kernel(name, parameters),
_T_var(coupled("T")),
_T(coupledValue("T")),
_grad_T(coupledGradient("T")),
_c_var(coupled("c")),
_c(coupledValue("c")),
_D(getMaterialProperty<Real>("diff_name")),
//_Q(getMaterialProperty<Real>("Q_name")),
_z(getMaterialProperty<Real>("z_name")),
_echarge(1.6e-19), // charge of an electron
_kb(8.617343e-5) // Boltzmann constant in eV/K
{
}
Real
SplitCHVoltage::computeQpResidual()
{
Real volt_term = _D[_qp] * _z[_qp] *_echarge * _c[_qp] / (_kb * _T[_qp] );
return volt_term * _grad_volt[_qp] * _grad_test[_i][_qp];
}
Real
SplitCHVoltage::computeQpOffDiagJacobian(unsigned int jvar)
{
if (_c_var == jvar)
return _D[_qp] * _z[_qp] *_echarge * _phi[_j][_qp] * _grad_volt[_qp] / (_kb * _T[_qp]) * _grad_test[_i][_qp];
else if (_volt_var == jvar)
return _D[_qp] * _z[_qp] *_echarge * _c[_qp] * _grad_test[_i][_qp] *
(_grad_phi[_j][_qp]/(_kb * _T[_qp]) + _grad_volt[_qp] * _phi[_j][_qp] / (_kb * _T[_qp] * _T[_qp]));
return 0.0;
}
<commit_msg>Update SplitCHVoltage.C<commit_after>/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* All contents are licensed under LGPL V2.1 */
/* See LICENSE for full restrictions */
/****************************************************************/
//This kernel adds electromigration flux in the Cahn-Hilliard Equation
//Mathematically it is J_em=c*(D/kT)*z*eE
#include "SplitCHVoltage.h"
template<>
InputParameters validParams<SplitCHVoltage>()
{
InputParameters params = validParams<Kernel>();
params.addClassDescription("Add Electromigration Flux to Split formulation Cahn-Hilliard Kernel");
//params.addRequiredCoupledVar("T", "Temperature in Kelvin Scale");
params.addRequiredCoupledVar("volt", "Voltage");
params.addRequiredCoupledVar("c", "Concentration");
params.addRequiredParam<MaterialPropertyName>("diff_name", "The diffusivity used with the kernel");
params.addRequiredParam<MaterialPropertyName>("T", "The temperature used with the kernel");
params.addParam<MaterialPropertyName>("z_name", "zeff", "Effective charge number of the species");
//params.addParam<MaterialPropertyName>("e_name", "eo", "Charge of the electron");
return params;
}
SplitCHVoltage::SplitCHVoltage(const std::string & name, InputParameters parameters) :
Kernel(name, parameters),
//_T_var(coupled("T")),
//_T(coupledValue("T")),
//_grad_T(coupledGradient("T")),
_volt_var(coupled("volt")),
_volt(coupledValue("volt")),
_grad_volt(coupledGradient("volt")),
_c_var(coupled("c")),
_c(coupledValue("c")),
_D(getMaterialProperty<Real>("diff_name")),
_T(getMaterialProperty<Real>("T")),
//_Q(getMaterialProperty<Real>("Q_name")),
_z(getMaterialProperty<Real>("z_name")),
//_T(getParam<Real>("T")),
_kb(8.617343e-5), // Boltzmann constant in eV/K
_eo(1.6e-19) // charge of an electron
{
}
Real
SplitCHVoltage::computeQpResidual()
{
Real volt_term = _D[_qp] * _z[_qp] *_eo * _c[_qp] / (_kb * _T[_qp] );
return volt_term * _grad_volt[_qp] * _grad_test[_i][_qp];
}
Real
SplitCHVoltage::computeQpJacobian()
{
if (_c_var == _var.number()) //Requires c jacobian
return computeQpCJacobian();
return 0.0;
}
Real
SplitCHVoltage::computeQpOffDiagJacobian(unsigned int jvar)
{
if (_c_var == jvar)
return _D[_qp] * _z[_qp] * _eo * _phi[_j][_qp] * _grad_volt[_qp] / (_kb * _T[_qp]) * _grad_test[_i][_qp];
else if (_volt_var == jvar)
return _D[_qp] * _z[_qp] * _eo * _c[_qp] * _grad_test[_i][_qp] *
(_grad_phi[_j][_qp]/(_kb * _T[_qp]) + _grad_volt[_qp] * _phi[_j][_qp] / (_kb * _T[_qp] * _T[_qp]));
return 0.0;
}
Real
SplitCHVoltage::computeQpCJacobian()
{
//Calculate the Jacobian for the c variable
return _D[_qp] * _z[_qp] * _phi[_j][_qp] * _grad_volt[_qp] / (_kb * _T[_qp]) * _grad_test[_i][_qp];
}
<|endoftext|>
|
<commit_before>/*
* GeislerLayer.cpp
*
* Created on: Apr 21, 2010
* Author: gkenyon
*/
#include "GeislerLayer.hpp"
#include <assert.h>
#include <float.h>
namespace PV {
GeislerLayer::GeislerLayer(const char* name, HyPerCol * hc)
: V1(name, hc)
{
}
GeislerLayer::GeislerLayer(const char* name, HyPerCol * hc, PVLayerType type)
: V1(name, hc)
{
}
int GeislerLayer::updateState(float time, float dt)
{
PVParams * params = parent->parameters();
pv_debug_info("[%d]: V1::updateState:", clayer->columnId);
int spikingFlag = (int) params->value(name, "spikingFlag", 1);
assert(spikingFlag == 0);
const int nx = clayer->loc.nx;
const int ny = clayer->loc.ny;
const int nf = clayer->numFeatures;
const int marginWidth = clayer->loc.nPad;
pvdata_t * V = clayer->V;
pvdata_t * phiExc = clayer->phi[PHI_EXC];
pvdata_t * phiInh = clayer->phi[PHI_INH];
pvdata_t * phiInhB = clayer->phi[PHI_INHB];
pvdata_t * activity = clayer->activity->data;
// make sure activity in border is zero
//
for (int k = 0; k < clayer->numExtended; k++) {
activity[k] = 0.0;
}
pvdata_t max_direct = -FLT_MAX;
pvdata_t max_V = -FLT_MAX;
// assume direct input to phiExc, lateral input to phiInh
for (int k = 0; k < clayer->numNeurons; k++) {
pvdata_t direct_input = phiExc[k];
pvdata_t lateral_input = phiInh[k];
V[k] = (direct_input > 0.0f) ? direct_input * lateral_input : direct_input;
max_direct = ( max_direct > direct_input ) ? max_direct : direct_input;
max_V = ( max_V > V[k] ) ? max_V : V[k];
// reset accumulation buffers
phiExc[k] = 0.0;
phiInh[k] = 0.0;
phiInhB[k] = 0.0;
}
pvdata_t scale_factor = fabs( max_direct ) / fabs( max_V + (max_V == 0.0f) );
for (int k = 0; k < clayer->numNeurons; k++) {
int kex = kIndexExtended(k, nx, ny, nf, marginWidth);
V[k] *= scale_factor;
activity[kex] = ( V[k] > 0.0f ) ? V[k] : 0.0f;
}
return 0;
}
}
<commit_msg>removed scaling<commit_after>/*
* GeislerLayer.cpp
*
* Created on: Apr 21, 2010
* Author: gkenyon
*/
#include "GeislerLayer.hpp"
#include <assert.h>
#include <float.h>
namespace PV {
GeislerLayer::GeislerLayer(const char* name, HyPerCol * hc)
: V1(name, hc)
{
}
GeislerLayer::GeislerLayer(const char* name, HyPerCol * hc, PVLayerType type)
: V1(name, hc)
{
}
int GeislerLayer::updateState(float time, float dt)
{
PVParams * params = parent->parameters();
pv_debug_info("[%d]: V1::updateState:", clayer->columnId);
int spikingFlag = (int) params->value(name, "spikingFlag", 1);
assert(spikingFlag == 0);
const int nx = clayer->loc.nx;
const int ny = clayer->loc.ny;
const int nf = clayer->numFeatures;
const int marginWidth = clayer->loc.nPad;
pvdata_t * V = clayer->V;
pvdata_t * phiExc = clayer->phi[PHI_EXC];
pvdata_t * phiInh = clayer->phi[PHI_INH];
pvdata_t * phiInhB = clayer->phi[PHI_INHB];
pvdata_t * activity = clayer->activity->data;
// make sure activity in border is zero
//
for (int k = 0; k < clayer->numExtended; k++) {
activity[k] = 0.0;
}
pvdata_t max_direct = -FLT_MAX;
pvdata_t max_V = -FLT_MAX;
// assume direct input to phiExc, lateral input to phiInh
for (int k = 0; k < clayer->numNeurons; k++) {
pvdata_t direct_input = phiExc[k];
pvdata_t lateral_input = phiInh[k];
V[k] = (direct_input > 0.0f) ? direct_input * lateral_input : direct_input;
max_direct = ( max_direct > direct_input ) ? max_direct : direct_input;
max_V = ( max_V > V[k] ) ? max_V : V[k];
// reset accumulation buffers
phiExc[k] = 0.0;
phiInh[k] = 0.0;
phiInhB[k] = 0.0;
}
pvdata_t scale_factor = fabs( max_direct ) / fabs( max_V + (max_V == 0.0f) );
for (int k = 0; k < clayer->numNeurons; k++) {
int kex = kIndexExtended(k, nx, ny, nf, marginWidth);
//V[k] *= scale_factor;
activity[kex] = ( V[k] > 0.0f ) ? V[k] : 0.0f;
}
return 0;
}
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libetonyek project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <libetonyek/libetonyek.h>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/logic/tribool.hpp>
#include <libxml/xmlreader.h>
#include "libetonyek_utils.h"
#include "libetonyek_xml.h"
#include "IWORKPresentationRedirector.h"
#include "IWORKSpreadsheetRedirector.h"
#include "IWORKTextRedirector.h"
#include "IWORKTokenizer.h"
#include "IWORKZlibStream.h"
#include "KEY1Parser.h"
#include "KEY2Parser.h"
#include "KEY2Token.h"
#include "KEYCollector.h"
#include "KEYDictionary.h"
#include "NUMCollector.h"
#include "NUMDictionary.h"
#include "NUM1Parser.h"
#include "NUM1Token.h"
#include "PAGCollector.h"
#include "PAG1Parser.h"
#include "PAG1Token.h"
#include "PAGDictionary.h"
using boost::logic::indeterminate;
using boost::logic::tribool;
using boost::scoped_ptr;
using boost::shared_ptr;
using std::string;
using librevenge::RVNG_SEEK_SET;
namespace libetonyek
{
namespace
{
enum CheckType
{
CHECK_TYPE_NONE = 0,
CHECK_TYPE_KEYNOTE = 1 << 1,
CHECK_TYPE_NUMBERS = 1 << 2,
CHECK_TYPE_PAGES = 1 << 3,
CHECK_TYPE_ANY = CHECK_TYPE_KEYNOTE | CHECK_TYPE_NUMBERS | CHECK_TYPE_PAGES
};
struct DetectionInfo
{
DetectionInfo();
RVNGInputStreamPtr_t input;
RVNGInputStreamPtr_t package;
EtonyekDocument::Confidence confidence;
EtonyekDocument::Type type;
unsigned version;
};
DetectionInfo::DetectionInfo()
: input()
, package()
, confidence(EtonyekDocument::CONFIDENCE_NONE)
, type(EtonyekDocument::TYPE_UNKNOWN)
, version(0)
{
}
typedef bool (*ProbeXMLFun_t)(const RVNGInputStreamPtr_t &, unsigned &, xmlTextReaderPtr);
std::string queryAttribute(xmlTextReaderPtr reader, const int name, const int ns, const IWORKTokenizer &tokenizer)
{
if (xmlTextReaderHasAttributes(reader))
{
int ret = xmlTextReaderMoveToFirstAttribute(reader);
while (1 == ret)
{
const int id = tokenizer.getQualifiedId(char_cast(xmlTextReaderConstLocalName(reader)), char_cast(xmlTextReaderConstNamespaceUri(reader)));
if ((ns | name) == id)
return char_cast(xmlTextReaderConstValue(reader));
ret = xmlTextReaderMoveToNextAttribute(reader);
}
}
return "";
}
bool probeKeynote1XML(const RVNGInputStreamPtr_t &input, unsigned &version, xmlTextReaderPtr reader)
{
// TODO: implement me
(void) input;
(void) version;
(void) reader;
return false;
}
bool probeKeynote2XML(const RVNGInputStreamPtr_t &input, unsigned &version, xmlTextReaderPtr reader)
{
if (input->isEnd())
return false;
const IWORKTokenizer &tokenizer(KEY2Token::getTokenizer());
assert(reader);
const int id = tokenizer.getQualifiedId(char_cast(xmlTextReaderConstLocalName(reader)), char_cast(xmlTextReaderConstNamespaceUri(reader)));
if ((KEY2Token::NS_URI_KEY | KEY2Token::presentation) == id)
{
const std::string v = queryAttribute(reader, KEY2Token::version, KEY2Token::NS_URI_KEY, tokenizer);
switch (tokenizer.getId(v.c_str()))
{
case KEY2Token::VERSION_STR_2 :
version = 2;
return true;
case KEY2Token::VERSION_STR_3 :
version = 3;
return true;
case KEY2Token::VERSION_STR_4 :
version = 4;
return true;
case KEY2Token::VERSION_STR_5 :
version = 5;
return true;
}
}
return false;
}
bool probeKeynoteXML(const RVNGInputStreamPtr_t &input, unsigned &version, xmlTextReaderPtr reader)
{
if (probeKeynote2XML(input, version, reader))
return true;
input->seek(0, RVNG_SEEK_SET);
return probeKeynote1XML(input, version, reader);
}
bool probeNumbersXML(const RVNGInputStreamPtr_t &input, unsigned &version, xmlTextReaderPtr reader)
{
if (input->isEnd())
return false;
const IWORKTokenizer &tokenizer(NUM1Token::getTokenizer());
assert(reader);
const int id = tokenizer.getQualifiedId(char_cast(xmlTextReaderConstLocalName(reader)), char_cast(xmlTextReaderConstNamespaceUri(reader)));
if ((NUM1Token::NS_URI_LS | NUM1Token::document) == id)
{
const std::string v = queryAttribute(reader, NUM1Token::version, NUM1Token::NS_URI_LS, tokenizer);
switch (tokenizer.getId(v.c_str()))
{
case NUM1Token::VERSION_STR_2 :
version = 2;
return true;
}
}
return false;
}
bool probePagesXML(const RVNGInputStreamPtr_t &input, unsigned &version, xmlTextReaderPtr reader)
{
if (input->isEnd())
return false;
const IWORKTokenizer &tokenizer(PAG1Token::getTokenizer());
assert(reader);
const int id = tokenizer.getQualifiedId(char_cast(xmlTextReaderConstLocalName(reader)), char_cast(xmlTextReaderConstNamespaceUri(reader)));
if ((PAG1Token::NS_URI_SL | PAG1Token::document) == id)
{
const std::string v = queryAttribute(reader, PAG1Token::version, PAG1Token::NS_URI_SL, tokenizer);
switch (tokenizer.getId(v.c_str()))
{
case PAG1Token::VERSION_STR_4 :
version = 4;
return true;
}
}
return false;
}
bool probeXMLImpl(const RVNGInputStreamPtr_t &input, const ProbeXMLFun_t probe, const EtonyekDocument::Type type, DetectionInfo &info)
{
const shared_ptr<xmlTextReader> reader(xmlReaderForIO(readFromStream, closeStream, input.get(), "", 0, 0), xmlFreeTextReader);
if (!reader)
return false;
int ret = 0;
do
{
ret = xmlTextReaderRead(reader.get());
}
while ((1 == ret) && (XML_READER_TYPE_ELEMENT != xmlTextReaderNodeType(reader.get())));
if (1 != ret)
return false;
if (probe(input, info.version, reader.get()))
{
info.type = type;
return true;
}
return false;
}
bool probeXML(const ProbeXMLFun_t probe, const EtonyekDocument::Type type, tribool &isGzipped, DetectionInfo &info)
{
if (isGzipped || indeterminate(isGzipped))
{
try
{
const RVNGInputStreamPtr_t uncompressed(new IWORKZlibStream(info.input));
isGzipped = true;
if (probeXMLImpl(uncompressed, probe, type, info))
{
info.input = uncompressed;
return true;
}
else
{
return false; // compressed, but invalid format
}
}
catch (...)
{
if (isGzipped) // decompression failed? most probably a broken file...
return false;
isGzipped = false;
}
info.input->seek(0, RVNG_SEEK_SET);
}
assert(isGzipped == false);
return probeXMLImpl(info.input, probe, type, info);
}
bool detect(const RVNGInputStreamPtr_t &input, unsigned checkTypes, DetectionInfo &info)
{
info.confidence = EtonyekDocument::CONFIDENCE_SUPPORTED_PART;
bool isXML = true;
tribool isGzipped = indeterminate;
tribool isKeynote1 = indeterminate;
if (input->isStructured())
{
info.package = input;
// check which format it might be
if (CHECK_TYPE_KEYNOTE & checkTypes)
{
if (input->existsSubStream("index.apxl"))
{
checkTypes = CHECK_TYPE_KEYNOTE;
isGzipped = false;
isKeynote1 = false;
info.input.reset(input->getSubStreamByName("index.apxl"));
}
else if (input->existsSubStream("index.apxl.gz"))
{
checkTypes = CHECK_TYPE_KEYNOTE;
isGzipped = true;
isKeynote1 = false;
info.input.reset(input->getSubStreamByName("index.apxl.gz"));
}
else if (input->existsSubStream("presentation.apxl"))
{
checkTypes = CHECK_TYPE_KEYNOTE;
isGzipped = false;
isKeynote1 = true;
info.input.reset(input->getSubStreamByName("presentation.apxl"));
}
else if (input->existsSubStream("presentation.apxl.gz"))
{
checkTypes = CHECK_TYPE_KEYNOTE;
isGzipped = true;
isKeynote1 = true;
info.input.reset(input->getSubStreamByName("presentation.apxl.gz"));
}
}
if ((CHECK_TYPE_NUMBERS | CHECK_TYPE_PAGES) & checkTypes)
{
if (input->existsSubStream("index.xml"))
{
checkTypes &= (CHECK_TYPE_NUMBERS | CHECK_TYPE_PAGES);
isGzipped = false;
info.input.reset(input->getSubStreamByName("index.xml"));
}
else if (input->existsSubStream("index.xml.gz"))
{
checkTypes &= (CHECK_TYPE_NUMBERS | CHECK_TYPE_PAGES);
isGzipped = false;
info.input.reset(input->getSubStreamByName("index.xml.gz"));
}
}
if (!info.input && (CHECK_TYPE_ANY & checkTypes))
{
if (input->existsSubStream("Index.zip"))
{
isXML = false;
info.input.reset(input->getSubStreamByName("Index.zip"));
}
}
if (!info.input)
{
// nothing detected
// TODO: this might also be Index.zip...
return EtonyekDocument::CONFIDENCE_NONE;
}
info.confidence = EtonyekDocument::CONFIDENCE_EXCELLENT; // this is either a valid package of a false positive
}
else
{
info.input = input;
}
assert(bool(info.input));
if (isXML)
{
assert(CHECK_TYPE_ANY & checkTypes);
assert(!info.input->isStructured());
info.input->seek(0, RVNG_SEEK_SET);
if (CHECK_TYPE_KEYNOTE & checkTypes)
{
const ProbeXMLFun_t probe = (isKeynote1 ? probeKeynote1XML : ((!isKeynote1) ? probeKeynote2XML : probeKeynoteXML));
if (probeXML(probe, EtonyekDocument::TYPE_KEYNOTE, isGzipped, info))
return true;
info.input->seek(0, RVNG_SEEK_SET);
}
if (CHECK_TYPE_NUMBERS & checkTypes)
{
if (probeXML(probeNumbersXML, EtonyekDocument::TYPE_NUMBERS, isGzipped, info))
return true;
info.input->seek(0, RVNG_SEEK_SET);
}
if (CHECK_TYPE_PAGES & checkTypes)
{
if (probeXML(probePagesXML, EtonyekDocument::TYPE_PAGES, isGzipped, info))
return true;
}
}
else
{
// TODO: detect type in binary format
}
return EtonyekDocument::CONFIDENCE_NONE;
}
}
namespace
{
shared_ptr<IWORKParser> makeKeynoteParser(const unsigned version, const RVNGInputStreamPtr_t &input, const RVNGInputStreamPtr_t &package, KEYCollector *const collector, KEYDictionary &dict)
{
shared_ptr<IWORKParser> parser;
if (1 == version)
parser.reset(new KEY1Parser(input, package, collector));
else if ((2 <= version) && (5 >= version))
parser.reset(new KEY2Parser(input, package, collector, dict));
else
assert(0);
return parser;
}
}
ETONYEKAPI EtonyekDocument::Confidence EtonyekDocument::isSupported(librevenge::RVNGInputStream *const input, EtonyekDocument::Type *type) try
{
if (!input)
return CONFIDENCE_NONE;
if (type)
*type = TYPE_UNKNOWN;
DetectionInfo info;
if (detect(RVNGInputStreamPtr_t(input, EtonyekDummyDeleter()), CHECK_TYPE_ANY, info))
{
assert(TYPE_UNKNOWN != info.type);
assert(CONFIDENCE_NONE != info.confidence);
assert(bool(info.input));
if (type)
*type = info.type;
return info.confidence;
}
return CONFIDENCE_NONE;
}
catch (...)
{
return CONFIDENCE_NONE;
}
ETONYEKAPI bool EtonyekDocument::parse(librevenge::RVNGInputStream *const input, librevenge::RVNGPresentationInterface *const generator) try
{
if (!input || !generator)
return false;
DetectionInfo info;
if (!detect(RVNGInputStreamPtr_t(input, EtonyekDummyDeleter()), CHECK_TYPE_KEYNOTE, info))
return false;
assert(TYPE_UNKNOWN != info.type);
assert(CONFIDENCE_NONE != info.confidence);
assert(bool(info.input));
assert(0 != info.version);
info.input->seek(0, librevenge::RVNG_SEEK_SET);
KEYDictionary dict;
IWORKPresentationRedirector redirector(generator);
KEYCollector collector(&redirector);
const shared_ptr<IWORKParser> parser = makeKeynoteParser(info.version, info.input, info.package, &collector, dict);
return parser->parse();
}
catch (...)
{
return false;
}
ETONYEKAPI bool EtonyekDocument::parse(librevenge::RVNGInputStream *const input, librevenge::RVNGSpreadsheetInterface *const document) try
{
if (!input || !document)
return false;
DetectionInfo info;
if (!detect(RVNGInputStreamPtr_t(input, EtonyekDummyDeleter()), CHECK_TYPE_NUMBERS, info))
return false;
assert(TYPE_UNKNOWN != info.type);
assert(CONFIDENCE_NONE != info.confidence);
assert(bool(info.input));
assert(0 != info.version);
info.input->seek(0, librevenge::RVNG_SEEK_SET);
IWORKSpreadsheetRedirector redirector(document);
NUMCollector collector(&redirector);
NUMDictionary dict;
NUM1Parser parser(info.input, info.package, &collector, &dict);
return parser.parse();
}
catch (...)
{
return false;
}
ETONYEKAPI bool EtonyekDocument::parse(librevenge::RVNGInputStream *const input, librevenge::RVNGTextInterface *const document) try
{
if (!input || !document)
return false;
DetectionInfo info;
if (!detect(RVNGInputStreamPtr_t(input, EtonyekDummyDeleter()), CHECK_TYPE_PAGES, info))
return false;
assert(TYPE_UNKNOWN != info.type);
assert(CONFIDENCE_NONE != info.confidence);
assert(bool(info.input));
assert(0 != info.version);
info.input->seek(0, librevenge::RVNG_SEEK_SET);
IWORKTextRedirector redirector(document);
PAGCollector collector(&redirector);
PAGDictionary dict;
PAG1Parser parser(info.input, info.package, &collector, &dict);
return parser.parse();
}
catch (...)
{
return false;
}
}
/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<commit_msg>add include for assert()<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libetonyek project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <libetonyek/libetonyek.h>
#include <cassert>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/logic/tribool.hpp>
#include <libxml/xmlreader.h>
#include "libetonyek_utils.h"
#include "libetonyek_xml.h"
#include "IWORKPresentationRedirector.h"
#include "IWORKSpreadsheetRedirector.h"
#include "IWORKTextRedirector.h"
#include "IWORKTokenizer.h"
#include "IWORKZlibStream.h"
#include "KEY1Parser.h"
#include "KEY2Parser.h"
#include "KEY2Token.h"
#include "KEYCollector.h"
#include "KEYDictionary.h"
#include "NUMCollector.h"
#include "NUMDictionary.h"
#include "NUM1Parser.h"
#include "NUM1Token.h"
#include "PAGCollector.h"
#include "PAG1Parser.h"
#include "PAG1Token.h"
#include "PAGDictionary.h"
using boost::logic::indeterminate;
using boost::logic::tribool;
using boost::scoped_ptr;
using boost::shared_ptr;
using std::string;
using librevenge::RVNG_SEEK_SET;
namespace libetonyek
{
namespace
{
enum CheckType
{
CHECK_TYPE_NONE = 0,
CHECK_TYPE_KEYNOTE = 1 << 1,
CHECK_TYPE_NUMBERS = 1 << 2,
CHECK_TYPE_PAGES = 1 << 3,
CHECK_TYPE_ANY = CHECK_TYPE_KEYNOTE | CHECK_TYPE_NUMBERS | CHECK_TYPE_PAGES
};
struct DetectionInfo
{
DetectionInfo();
RVNGInputStreamPtr_t input;
RVNGInputStreamPtr_t package;
EtonyekDocument::Confidence confidence;
EtonyekDocument::Type type;
unsigned version;
};
DetectionInfo::DetectionInfo()
: input()
, package()
, confidence(EtonyekDocument::CONFIDENCE_NONE)
, type(EtonyekDocument::TYPE_UNKNOWN)
, version(0)
{
}
typedef bool (*ProbeXMLFun_t)(const RVNGInputStreamPtr_t &, unsigned &, xmlTextReaderPtr);
std::string queryAttribute(xmlTextReaderPtr reader, const int name, const int ns, const IWORKTokenizer &tokenizer)
{
if (xmlTextReaderHasAttributes(reader))
{
int ret = xmlTextReaderMoveToFirstAttribute(reader);
while (1 == ret)
{
const int id = tokenizer.getQualifiedId(char_cast(xmlTextReaderConstLocalName(reader)), char_cast(xmlTextReaderConstNamespaceUri(reader)));
if ((ns | name) == id)
return char_cast(xmlTextReaderConstValue(reader));
ret = xmlTextReaderMoveToNextAttribute(reader);
}
}
return "";
}
bool probeKeynote1XML(const RVNGInputStreamPtr_t &input, unsigned &version, xmlTextReaderPtr reader)
{
// TODO: implement me
(void) input;
(void) version;
(void) reader;
return false;
}
bool probeKeynote2XML(const RVNGInputStreamPtr_t &input, unsigned &version, xmlTextReaderPtr reader)
{
if (input->isEnd())
return false;
const IWORKTokenizer &tokenizer(KEY2Token::getTokenizer());
assert(reader);
const int id = tokenizer.getQualifiedId(char_cast(xmlTextReaderConstLocalName(reader)), char_cast(xmlTextReaderConstNamespaceUri(reader)));
if ((KEY2Token::NS_URI_KEY | KEY2Token::presentation) == id)
{
const std::string v = queryAttribute(reader, KEY2Token::version, KEY2Token::NS_URI_KEY, tokenizer);
switch (tokenizer.getId(v.c_str()))
{
case KEY2Token::VERSION_STR_2 :
version = 2;
return true;
case KEY2Token::VERSION_STR_3 :
version = 3;
return true;
case KEY2Token::VERSION_STR_4 :
version = 4;
return true;
case KEY2Token::VERSION_STR_5 :
version = 5;
return true;
}
}
return false;
}
bool probeKeynoteXML(const RVNGInputStreamPtr_t &input, unsigned &version, xmlTextReaderPtr reader)
{
if (probeKeynote2XML(input, version, reader))
return true;
input->seek(0, RVNG_SEEK_SET);
return probeKeynote1XML(input, version, reader);
}
bool probeNumbersXML(const RVNGInputStreamPtr_t &input, unsigned &version, xmlTextReaderPtr reader)
{
if (input->isEnd())
return false;
const IWORKTokenizer &tokenizer(NUM1Token::getTokenizer());
assert(reader);
const int id = tokenizer.getQualifiedId(char_cast(xmlTextReaderConstLocalName(reader)), char_cast(xmlTextReaderConstNamespaceUri(reader)));
if ((NUM1Token::NS_URI_LS | NUM1Token::document) == id)
{
const std::string v = queryAttribute(reader, NUM1Token::version, NUM1Token::NS_URI_LS, tokenizer);
switch (tokenizer.getId(v.c_str()))
{
case NUM1Token::VERSION_STR_2 :
version = 2;
return true;
}
}
return false;
}
bool probePagesXML(const RVNGInputStreamPtr_t &input, unsigned &version, xmlTextReaderPtr reader)
{
if (input->isEnd())
return false;
const IWORKTokenizer &tokenizer(PAG1Token::getTokenizer());
assert(reader);
const int id = tokenizer.getQualifiedId(char_cast(xmlTextReaderConstLocalName(reader)), char_cast(xmlTextReaderConstNamespaceUri(reader)));
if ((PAG1Token::NS_URI_SL | PAG1Token::document) == id)
{
const std::string v = queryAttribute(reader, PAG1Token::version, PAG1Token::NS_URI_SL, tokenizer);
switch (tokenizer.getId(v.c_str()))
{
case PAG1Token::VERSION_STR_4 :
version = 4;
return true;
}
}
return false;
}
bool probeXMLImpl(const RVNGInputStreamPtr_t &input, const ProbeXMLFun_t probe, const EtonyekDocument::Type type, DetectionInfo &info)
{
const shared_ptr<xmlTextReader> reader(xmlReaderForIO(readFromStream, closeStream, input.get(), "", 0, 0), xmlFreeTextReader);
if (!reader)
return false;
int ret = 0;
do
{
ret = xmlTextReaderRead(reader.get());
}
while ((1 == ret) && (XML_READER_TYPE_ELEMENT != xmlTextReaderNodeType(reader.get())));
if (1 != ret)
return false;
if (probe(input, info.version, reader.get()))
{
info.type = type;
return true;
}
return false;
}
bool probeXML(const ProbeXMLFun_t probe, const EtonyekDocument::Type type, tribool &isGzipped, DetectionInfo &info)
{
if (isGzipped || indeterminate(isGzipped))
{
try
{
const RVNGInputStreamPtr_t uncompressed(new IWORKZlibStream(info.input));
isGzipped = true;
if (probeXMLImpl(uncompressed, probe, type, info))
{
info.input = uncompressed;
return true;
}
else
{
return false; // compressed, but invalid format
}
}
catch (...)
{
if (isGzipped) // decompression failed? most probably a broken file...
return false;
isGzipped = false;
}
info.input->seek(0, RVNG_SEEK_SET);
}
assert(isGzipped == false);
return probeXMLImpl(info.input, probe, type, info);
}
bool detect(const RVNGInputStreamPtr_t &input, unsigned checkTypes, DetectionInfo &info)
{
info.confidence = EtonyekDocument::CONFIDENCE_SUPPORTED_PART;
bool isXML = true;
tribool isGzipped = indeterminate;
tribool isKeynote1 = indeterminate;
if (input->isStructured())
{
info.package = input;
// check which format it might be
if (CHECK_TYPE_KEYNOTE & checkTypes)
{
if (input->existsSubStream("index.apxl"))
{
checkTypes = CHECK_TYPE_KEYNOTE;
isGzipped = false;
isKeynote1 = false;
info.input.reset(input->getSubStreamByName("index.apxl"));
}
else if (input->existsSubStream("index.apxl.gz"))
{
checkTypes = CHECK_TYPE_KEYNOTE;
isGzipped = true;
isKeynote1 = false;
info.input.reset(input->getSubStreamByName("index.apxl.gz"));
}
else if (input->existsSubStream("presentation.apxl"))
{
checkTypes = CHECK_TYPE_KEYNOTE;
isGzipped = false;
isKeynote1 = true;
info.input.reset(input->getSubStreamByName("presentation.apxl"));
}
else if (input->existsSubStream("presentation.apxl.gz"))
{
checkTypes = CHECK_TYPE_KEYNOTE;
isGzipped = true;
isKeynote1 = true;
info.input.reset(input->getSubStreamByName("presentation.apxl.gz"));
}
}
if ((CHECK_TYPE_NUMBERS | CHECK_TYPE_PAGES) & checkTypes)
{
if (input->existsSubStream("index.xml"))
{
checkTypes &= (CHECK_TYPE_NUMBERS | CHECK_TYPE_PAGES);
isGzipped = false;
info.input.reset(input->getSubStreamByName("index.xml"));
}
else if (input->existsSubStream("index.xml.gz"))
{
checkTypes &= (CHECK_TYPE_NUMBERS | CHECK_TYPE_PAGES);
isGzipped = false;
info.input.reset(input->getSubStreamByName("index.xml.gz"));
}
}
if (!info.input && (CHECK_TYPE_ANY & checkTypes))
{
if (input->existsSubStream("Index.zip"))
{
isXML = false;
info.input.reset(input->getSubStreamByName("Index.zip"));
}
}
if (!info.input)
{
// nothing detected
// TODO: this might also be Index.zip...
return EtonyekDocument::CONFIDENCE_NONE;
}
info.confidence = EtonyekDocument::CONFIDENCE_EXCELLENT; // this is either a valid package of a false positive
}
else
{
info.input = input;
}
assert(bool(info.input));
if (isXML)
{
assert(CHECK_TYPE_ANY & checkTypes);
assert(!info.input->isStructured());
info.input->seek(0, RVNG_SEEK_SET);
if (CHECK_TYPE_KEYNOTE & checkTypes)
{
const ProbeXMLFun_t probe = (isKeynote1 ? probeKeynote1XML : ((!isKeynote1) ? probeKeynote2XML : probeKeynoteXML));
if (probeXML(probe, EtonyekDocument::TYPE_KEYNOTE, isGzipped, info))
return true;
info.input->seek(0, RVNG_SEEK_SET);
}
if (CHECK_TYPE_NUMBERS & checkTypes)
{
if (probeXML(probeNumbersXML, EtonyekDocument::TYPE_NUMBERS, isGzipped, info))
return true;
info.input->seek(0, RVNG_SEEK_SET);
}
if (CHECK_TYPE_PAGES & checkTypes)
{
if (probeXML(probePagesXML, EtonyekDocument::TYPE_PAGES, isGzipped, info))
return true;
}
}
else
{
// TODO: detect type in binary format
}
return EtonyekDocument::CONFIDENCE_NONE;
}
}
namespace
{
shared_ptr<IWORKParser> makeKeynoteParser(const unsigned version, const RVNGInputStreamPtr_t &input, const RVNGInputStreamPtr_t &package, KEYCollector *const collector, KEYDictionary &dict)
{
shared_ptr<IWORKParser> parser;
if (1 == version)
parser.reset(new KEY1Parser(input, package, collector));
else if ((2 <= version) && (5 >= version))
parser.reset(new KEY2Parser(input, package, collector, dict));
else
assert(0);
return parser;
}
}
ETONYEKAPI EtonyekDocument::Confidence EtonyekDocument::isSupported(librevenge::RVNGInputStream *const input, EtonyekDocument::Type *type) try
{
if (!input)
return CONFIDENCE_NONE;
if (type)
*type = TYPE_UNKNOWN;
DetectionInfo info;
if (detect(RVNGInputStreamPtr_t(input, EtonyekDummyDeleter()), CHECK_TYPE_ANY, info))
{
assert(TYPE_UNKNOWN != info.type);
assert(CONFIDENCE_NONE != info.confidence);
assert(bool(info.input));
if (type)
*type = info.type;
return info.confidence;
}
return CONFIDENCE_NONE;
}
catch (...)
{
return CONFIDENCE_NONE;
}
ETONYEKAPI bool EtonyekDocument::parse(librevenge::RVNGInputStream *const input, librevenge::RVNGPresentationInterface *const generator) try
{
if (!input || !generator)
return false;
DetectionInfo info;
if (!detect(RVNGInputStreamPtr_t(input, EtonyekDummyDeleter()), CHECK_TYPE_KEYNOTE, info))
return false;
assert(TYPE_UNKNOWN != info.type);
assert(CONFIDENCE_NONE != info.confidence);
assert(bool(info.input));
assert(0 != info.version);
info.input->seek(0, librevenge::RVNG_SEEK_SET);
KEYDictionary dict;
IWORKPresentationRedirector redirector(generator);
KEYCollector collector(&redirector);
const shared_ptr<IWORKParser> parser = makeKeynoteParser(info.version, info.input, info.package, &collector, dict);
return parser->parse();
}
catch (...)
{
return false;
}
ETONYEKAPI bool EtonyekDocument::parse(librevenge::RVNGInputStream *const input, librevenge::RVNGSpreadsheetInterface *const document) try
{
if (!input || !document)
return false;
DetectionInfo info;
if (!detect(RVNGInputStreamPtr_t(input, EtonyekDummyDeleter()), CHECK_TYPE_NUMBERS, info))
return false;
assert(TYPE_UNKNOWN != info.type);
assert(CONFIDENCE_NONE != info.confidence);
assert(bool(info.input));
assert(0 != info.version);
info.input->seek(0, librevenge::RVNG_SEEK_SET);
IWORKSpreadsheetRedirector redirector(document);
NUMCollector collector(&redirector);
NUMDictionary dict;
NUM1Parser parser(info.input, info.package, &collector, &dict);
return parser.parse();
}
catch (...)
{
return false;
}
ETONYEKAPI bool EtonyekDocument::parse(librevenge::RVNGInputStream *const input, librevenge::RVNGTextInterface *const document) try
{
if (!input || !document)
return false;
DetectionInfo info;
if (!detect(RVNGInputStreamPtr_t(input, EtonyekDummyDeleter()), CHECK_TYPE_PAGES, info))
return false;
assert(TYPE_UNKNOWN != info.type);
assert(CONFIDENCE_NONE != info.confidence);
assert(bool(info.input));
assert(0 != info.version);
info.input->seek(0, librevenge::RVNG_SEEK_SET);
IWORKTextRedirector redirector(document);
PAGCollector collector(&redirector);
PAGDictionary dict;
PAG1Parser parser(info.input, info.package, &collector, &dict);
return parser.parse();
}
catch (...)
{
return false;
}
}
/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<|endoftext|>
|
<commit_before>#include "logger.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <time.h>
#ifndef LOG_DISABLED
#ifdef __unix__
#include <unistd.h>
#define MAX_PATH 255
#else
#include <windows.h>
#endif
static FILE *logFile = NULL;
static void timenow(char * buffer) {
time_t rawtime;
struct tm *timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer, 64, "%Y-%m-%d %H:%M:%S", timeinfo);
}
static void getLogFname(char* logpath) {
#ifdef __unix__
const char *folder = getenv("TMPDIR");
if (folder == nullptr) {
folder = "/tmp";
}
strncpy(logpath, folder, MAX_PATH);
strncat(logpath, "/open-license.log", MAX_PATH - strlen(logpath));
#else
const int plen = GetTempPath(MAX_PATH, logpath);
if(plen == 0) {
fprintf(stderr, "Error getting temporary directory path");
}
strncat(logpath, "open-license.log", MAX_PATH - strlen(logpath));
#endif
}
void _log(const char* format, ...) {
va_list args;
char * buffer;
if (logFile == NULL) {
char logpath[MAX_PATH];
getLogFname(logpath);
logFile = fopen(logpath, "a");
if (logFile == NULL) {
return;
}
}
buffer = (char *) malloc(sizeof(char) * strlen(format) + 64);
timenow(buffer);
sprintf(&buffer[strlen(buffer) - 1], "-[%d]-", getpid());
strcat(buffer, format);
va_start(args, format);
vfprintf(logFile, buffer, args);
va_end(args);
free(buffer);
}
void _shutdown_log() {
if (logFile != NULL) {
fclose(logFile);
logFile = NULL;
}
}
#endif
<commit_msg>fix windows issue<commit_after>#include "logger.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <time.h>
#ifndef LOG_DISABLED
#ifdef __unix__
#include <unistd.h>
#define MAX_PATH 255
#else
#include <windows.h>
#endif
static FILE *logFile = NULL;
static void timenow(char * buffer) {
time_t rawtime;
struct tm *timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer, 64, "%Y-%m-%d %H:%M:%S", timeinfo);
}
static void getLogFname(char* logpath) {
#ifdef __unix__
const char *folder = getenv("TMPDIR");
if (folder == nullptr) {
folder = "/tmp";
}
strncpy(logpath, folder, MAX_PATH);
strncat(logpath, "/open-license.log", MAX_PATH - strlen(logpath));
#else
const int plen = GetTempPath(MAX_PATH, logpath);
if(plen == 0) {
fprintf(stderr, "Error getting temporary directory path");
}
strncat(logpath, "open-license.log", MAX_PATH - strlen(logpath));
#endif
}
void _log(const char* format, ...) {
va_list args;
char * buffer;
if (logFile == NULL) {
char logpath[MAX_PATH];
getLogFname(logpath);
logFile = fopen(logpath, "a");
if (logFile == NULL) {
return;
}
}
buffer = (char *) malloc(sizeof(char) * strlen(format) + 64);
timenow(buffer);
strcat(buffer, format);
va_start(args, format);
vfprintf(logFile, buffer, args);
va_end(args);
free(buffer);
}
void _shutdown_log() {
if (logFile != NULL) {
fclose(logFile);
logFile = NULL;
}
}
#endif
<|endoftext|>
|
<commit_before>#include <pb_view.h>
#include <pb_controller.h>
#include <poddlthread.h>
#include <download.h>
#include <config.h>
#include <logger.h>
#include <dllist.h>
#include <help.h>
#include <utils.h>
#include <sstream>
#include <iostream>
#include <cstring>
using namespace newsbeuter;
namespace podbeuter {
pb_view::pb_view(pb_controller * c) : ctrl(c), dllist_form(dllist_str), help_form(help_str), keys(0) {
}
pb_view::~pb_view() {
stfl::reset();
}
void pb_view::run(bool auto_download) {
bool quit = false;
set_dllist_keymap_hint();
do {
if (ctrl->view_update_necessary()) {
double total_kbps = ctrl->get_total_kbps();
char parbuf[128] = "";
if (ctrl->get_maxdownloads() > 1) {
snprintf(parbuf, sizeof(parbuf), _(" - %u parallel downloads"), ctrl->get_maxdownloads());
}
char buf[1024];
snprintf(buf, sizeof(buf), _("Queue (%u downloads in progress, %u total) - %.2f kb/s total%s"),
static_cast<unsigned int>(ctrl->downloads_in_progress()),
static_cast<unsigned int>(ctrl->downloads().size()), total_kbps, parbuf);
dllist_form.set("head", buf);
LOG(LOG_DEBUG, "pb_view::run: updating view... downloads().size() = %u", ctrl->downloads().size());
if (ctrl->downloads().size() > 0) {
std::string code = "{list";
unsigned int i = 0;
for (std::vector<download>::iterator it=ctrl->downloads().begin();it!=ctrl->downloads().end();++it,++i) {
char lbuf[1024];
snprintf(lbuf, sizeof(lbuf), " %4u [%6.1fMB/%6.1fMB] [%5.1f %%] [%7.2f kb/s] %-20s %s -> %s", i+1, it->current_size()/(1024*1024), it->total_size()/(1024*1024), it->percents_finished(), it->kbps(), it->status_text(), it->url(), it->filename());
code.append(utils::strprintf("{listitem[%u] text:%s}", i, stfl::quote(lbuf).c_str()));
}
code.append("}");
dllist_form.modify("dls", "replace_inner", code);
}
ctrl->set_view_update_necessary(false);
}
const char * event = dllist_form.run(500);
if (auto_download) {
if (ctrl->get_maxdownloads() > ctrl->downloads_in_progress()) {
ctrl->start_downloads();
}
}
if (!event || strcmp(event,"TIMEOUT")==0) continue;
operation op = keys->get_operation(event, "podbeuter");
if (dllist_form.get("msg").length() > 0) {
dllist_form.set("msg", "");
ctrl->set_view_update_necessary(true);
}
switch (op) {
case OP_PB_TOGGLE_DLALL:
auto_download = !auto_download;
break;
case OP_HARDQUIT:
case OP_QUIT:
if (ctrl->downloads_in_progress() > 0) {
dllist_form.set("msg", _("Error: can't quit: download(s) in progress."));
ctrl->set_view_update_necessary(true);
} else {
quit = true;
}
break;
case OP_PB_MOREDL:
ctrl->increase_parallel_downloads();
break;
case OP_PB_LESSDL:
ctrl->decrease_parallel_downloads();
break;
case OP_PB_DOWNLOAD: {
std::istringstream os(dllist_form.get("dlposname"));
int idx = -1;
os >> idx;
if (idx != -1) {
if (ctrl->downloads()[idx].status() != DL_DOWNLOADING) {
poddlthread * thread = new poddlthread(&ctrl->downloads()[idx], ctrl->get_cfgcont());
thread->start();
}
}
}
break;
case OP_PB_PLAY: {
std::istringstream os(dllist_form.get("dlposname"));
int idx = -1;
os >> idx;
if (idx != -1) {
dlstatus_t status = ctrl->downloads()[idx].status();
if (status == DL_FINISHED || status == DL_PLAYED) {
ctrl->play_file(ctrl->downloads()[idx].filename());
ctrl->downloads()[idx].set_status(DL_PLAYED);
} else {
dllist_form.set("msg", _("Error: download needs to be finished before the file can be played."));
}
}
}
break;
case OP_PB_CANCEL: {
std::istringstream os(dllist_form.get("dlposname"));
int idx = -1;
os >> idx;
if (idx != -1) {
if (ctrl->downloads()[idx].status() == DL_DOWNLOADING) {
ctrl->downloads()[idx].set_status(DL_CANCELLED);
}
}
}
break;
case OP_PB_DELETE: {
std::istringstream os(dllist_form.get("dlposname"));
int idx = -1;
os >> idx;
if (idx != -1) {
if (ctrl->downloads()[idx].status() != DL_DOWNLOADING) {
ctrl->downloads()[idx].set_status(DL_DELETED);
}
}
}
break;
case OP_PB_PURGE:
if (ctrl->downloads_in_progress() > 0) {
dllist_form.set("msg", _("Error: unable to perform operation: download(s) in progress."));
} else {
ctrl->reload_queue(true);
}
ctrl->set_view_update_necessary(true);
break;
case OP_HELP:
run_help();
break;
default:
break;
}
} while (!quit);
}
void pb_view::set_bindings() {
if (keys) {
std::string upkey("** "); upkey.append(keys->getkey(OP_SK_UP, "podbeuter"));
std::string downkey("** "); downkey.append(keys->getkey(OP_SK_DOWN, "podbeuter"));
std::string pgupkey("** "); pgupkey.append(keys->getkey(OP_SK_PGUP, "podbeuter"));
std::string pgdownkey("** "); pgdownkey.append(keys->getkey(OP_SK_PGDOWN, "podbeuter"));
dllist_form.set("bind_up", upkey);
dllist_form.set("bind_down", downkey);
dllist_form.set("bind_page_up", pgupkey);
dllist_form.set("bind_page_down", pgdownkey);
help_form.set("bind_up", upkey);
help_form.set("bind_down", downkey);
help_form.set("bind_page_up", pgupkey);
help_form.set("bind_page_down", pgdownkey);
}
}
void pb_view::run_help() {
set_help_keymap_hint();
help_form.set("head",_("Help"));
std::vector<keymap_desc> descs;
keys->get_keymap_descriptions(descs, KM_PODBEUTER);
std::string code = "{list";
for (std::vector<keymap_desc>::iterator it=descs.begin();it!=descs.end();++it) {
std::string line = "{listitem text:";
std::string descline;
descline.append(it->key);
descline.append(8-it->key.length(),' ');
descline.append(it->cmd);
descline.append(24-it->cmd.length(),' ');
descline.append(it->desc);
line.append(stfl::quote(descline));
line.append("}");
code.append(line);
}
code.append("}");
help_form.modify("helptext","replace_inner",code);
bool quit = false;
do {
const char * event = help_form.run(0);
if (!event) continue;
operation op = keys->get_operation(event, "help");
switch (op) {
case OP_HARDQUIT:
case OP_QUIT:
quit = true;
break;
default:
break;
}
} while (!quit);
}
std::string pb_view::prepare_keymaphint(keymap_hint_entry * hints) {
std::string keymap_hint;
for (int i=0;hints[i].op != OP_NIL; ++i) {
keymap_hint.append(keys->getkey(hints[i].op, "podbeuter"));
keymap_hint.append(":");
keymap_hint.append(hints[i].text);
keymap_hint.append(" ");
}
return keymap_hint;
}
void pb_view::set_help_keymap_hint() {
keymap_hint_entry hints[] = {
{ OP_QUIT, _("Quit") },
{ OP_NIL, NULL }
};
std::string keymap_hint = prepare_keymaphint(hints);
help_form.set("help", keymap_hint);
}
void pb_view::set_dllist_keymap_hint() {
keymap_hint_entry hints[] = {
{ OP_QUIT, _("Quit") },
{ OP_PB_DOWNLOAD, _("Download") },
{ OP_PB_CANCEL, _("Cancel") },
{ OP_PB_DELETE, _("Delete") },
{ OP_PB_PURGE, _("Purge Finished") },
{ OP_PB_TOGGLE_DLALL, _("Toggle Automatic Download") },
{ OP_PB_PLAY, _("Play") },
{ OP_HELP, _("Help") },
{ OP_NIL, NULL }
};
std::string keymap_hint = prepare_keymaphint(hints);
dllist_form.set("help", keymap_hint);
}
}
<commit_msg>bind home and end keys to built-in stfl actions<commit_after>#include <pb_view.h>
#include <pb_controller.h>
#include <poddlthread.h>
#include <download.h>
#include <config.h>
#include <logger.h>
#include <dllist.h>
#include <help.h>
#include <utils.h>
#include <sstream>
#include <iostream>
#include <cstring>
using namespace newsbeuter;
namespace podbeuter {
pb_view::pb_view(pb_controller * c) : ctrl(c), dllist_form(dllist_str), help_form(help_str), keys(0) {
}
pb_view::~pb_view() {
stfl::reset();
}
void pb_view::run(bool auto_download) {
bool quit = false;
set_dllist_keymap_hint();
do {
if (ctrl->view_update_necessary()) {
double total_kbps = ctrl->get_total_kbps();
char parbuf[128] = "";
if (ctrl->get_maxdownloads() > 1) {
snprintf(parbuf, sizeof(parbuf), _(" - %u parallel downloads"), ctrl->get_maxdownloads());
}
char buf[1024];
snprintf(buf, sizeof(buf), _("Queue (%u downloads in progress, %u total) - %.2f kb/s total%s"),
static_cast<unsigned int>(ctrl->downloads_in_progress()),
static_cast<unsigned int>(ctrl->downloads().size()), total_kbps, parbuf);
dllist_form.set("head", buf);
LOG(LOG_DEBUG, "pb_view::run: updating view... downloads().size() = %u", ctrl->downloads().size());
if (ctrl->downloads().size() > 0) {
std::string code = "{list";
unsigned int i = 0;
for (std::vector<download>::iterator it=ctrl->downloads().begin();it!=ctrl->downloads().end();++it,++i) {
char lbuf[1024];
snprintf(lbuf, sizeof(lbuf), " %4u [%6.1fMB/%6.1fMB] [%5.1f %%] [%7.2f kb/s] %-20s %s -> %s", i+1, it->current_size()/(1024*1024), it->total_size()/(1024*1024), it->percents_finished(), it->kbps(), it->status_text(), it->url(), it->filename());
code.append(utils::strprintf("{listitem[%u] text:%s}", i, stfl::quote(lbuf).c_str()));
}
code.append("}");
dllist_form.modify("dls", "replace_inner", code);
}
ctrl->set_view_update_necessary(false);
}
const char * event = dllist_form.run(500);
if (auto_download) {
if (ctrl->get_maxdownloads() > ctrl->downloads_in_progress()) {
ctrl->start_downloads();
}
}
if (!event || strcmp(event,"TIMEOUT")==0) continue;
operation op = keys->get_operation(event, "podbeuter");
if (dllist_form.get("msg").length() > 0) {
dllist_form.set("msg", "");
ctrl->set_view_update_necessary(true);
}
switch (op) {
case OP_PB_TOGGLE_DLALL:
auto_download = !auto_download;
break;
case OP_HARDQUIT:
case OP_QUIT:
if (ctrl->downloads_in_progress() > 0) {
dllist_form.set("msg", _("Error: can't quit: download(s) in progress."));
ctrl->set_view_update_necessary(true);
} else {
quit = true;
}
break;
case OP_PB_MOREDL:
ctrl->increase_parallel_downloads();
break;
case OP_PB_LESSDL:
ctrl->decrease_parallel_downloads();
break;
case OP_PB_DOWNLOAD: {
std::istringstream os(dllist_form.get("dlposname"));
int idx = -1;
os >> idx;
if (idx != -1) {
if (ctrl->downloads()[idx].status() != DL_DOWNLOADING) {
poddlthread * thread = new poddlthread(&ctrl->downloads()[idx], ctrl->get_cfgcont());
thread->start();
}
}
}
break;
case OP_PB_PLAY: {
std::istringstream os(dllist_form.get("dlposname"));
int idx = -1;
os >> idx;
if (idx != -1) {
dlstatus_t status = ctrl->downloads()[idx].status();
if (status == DL_FINISHED || status == DL_PLAYED) {
ctrl->play_file(ctrl->downloads()[idx].filename());
ctrl->downloads()[idx].set_status(DL_PLAYED);
} else {
dllist_form.set("msg", _("Error: download needs to be finished before the file can be played."));
}
}
}
break;
case OP_PB_CANCEL: {
std::istringstream os(dllist_form.get("dlposname"));
int idx = -1;
os >> idx;
if (idx != -1) {
if (ctrl->downloads()[idx].status() == DL_DOWNLOADING) {
ctrl->downloads()[idx].set_status(DL_CANCELLED);
}
}
}
break;
case OP_PB_DELETE: {
std::istringstream os(dllist_form.get("dlposname"));
int idx = -1;
os >> idx;
if (idx != -1) {
if (ctrl->downloads()[idx].status() != DL_DOWNLOADING) {
ctrl->downloads()[idx].set_status(DL_DELETED);
}
}
}
break;
case OP_PB_PURGE:
if (ctrl->downloads_in_progress() > 0) {
dllist_form.set("msg", _("Error: unable to perform operation: download(s) in progress."));
} else {
ctrl->reload_queue(true);
}
ctrl->set_view_update_necessary(true);
break;
case OP_HELP:
run_help();
break;
default:
break;
}
} while (!quit);
}
void pb_view::set_bindings() {
if (keys) {
std::string upkey("** "); upkey.append(keys->getkey(OP_SK_UP, "podbeuter"));
std::string downkey("** "); downkey.append(keys->getkey(OP_SK_DOWN, "podbeuter"));
std::string pgupkey("** "); pgupkey.append(keys->getkey(OP_SK_PGUP, "podbeuter"));
std::string pgdownkey("** "); pgdownkey.append(keys->getkey(OP_SK_PGDOWN, "podbeuter"));
std::string homekey("** "); homekey.append(keys->getkey(OP_SK_HOME, "podbeuter"));
std::string endkey("** "); endkey.append(keys->getkey(OP_SK_END, "podbeuter"));
dllist_form.set("bind_up", upkey);
dllist_form.set("bind_down", downkey);
dllist_form.set("bind_page_up", pgupkey);
dllist_form.set("bind_page_down", pgdownkey);
dllist_form.set("bind_home", homekey);
dllist_form.set("bind_end", endkey);
help_form.set("bind_up", upkey);
help_form.set("bind_down", downkey);
help_form.set("bind_page_up", pgupkey);
help_form.set("bind_page_down", pgdownkey);
help_form.set("bind_home", homekey);
help_form.set("bind_end", endkey);
}
}
void pb_view::run_help() {
set_help_keymap_hint();
help_form.set("head",_("Help"));
std::vector<keymap_desc> descs;
keys->get_keymap_descriptions(descs, KM_PODBEUTER);
std::string code = "{list";
for (std::vector<keymap_desc>::iterator it=descs.begin();it!=descs.end();++it) {
std::string line = "{listitem text:";
std::string descline;
descline.append(it->key);
descline.append(8-it->key.length(),' ');
descline.append(it->cmd);
descline.append(24-it->cmd.length(),' ');
descline.append(it->desc);
line.append(stfl::quote(descline));
line.append("}");
code.append(line);
}
code.append("}");
help_form.modify("helptext","replace_inner",code);
bool quit = false;
do {
const char * event = help_form.run(0);
if (!event) continue;
operation op = keys->get_operation(event, "help");
switch (op) {
case OP_HARDQUIT:
case OP_QUIT:
quit = true;
break;
default:
break;
}
} while (!quit);
}
std::string pb_view::prepare_keymaphint(keymap_hint_entry * hints) {
std::string keymap_hint;
for (int i=0;hints[i].op != OP_NIL; ++i) {
keymap_hint.append(keys->getkey(hints[i].op, "podbeuter"));
keymap_hint.append(":");
keymap_hint.append(hints[i].text);
keymap_hint.append(" ");
}
return keymap_hint;
}
void pb_view::set_help_keymap_hint() {
keymap_hint_entry hints[] = {
{ OP_QUIT, _("Quit") },
{ OP_NIL, NULL }
};
std::string keymap_hint = prepare_keymaphint(hints);
help_form.set("help", keymap_hint);
}
void pb_view::set_dllist_keymap_hint() {
keymap_hint_entry hints[] = {
{ OP_QUIT, _("Quit") },
{ OP_PB_DOWNLOAD, _("Download") },
{ OP_PB_CANCEL, _("Cancel") },
{ OP_PB_DELETE, _("Delete") },
{ OP_PB_PURGE, _("Purge Finished") },
{ OP_PB_TOGGLE_DLALL, _("Toggle Automatic Download") },
{ OP_PB_PLAY, _("Play") },
{ OP_HELP, _("Help") },
{ OP_NIL, NULL }
};
std::string keymap_hint = prepare_keymaphint(hints);
dllist_form.set("help", keymap_hint);
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2016 Jason White
*
* 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 <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <iostream>
#include <iomanip>
#include "pefile.h"
#include "pemap.h"
#include "pepatch.h"
namespace {
/**
* A range of memory to patch. This is used to keep track of what needs to be
* patched in the PE file.
*
* All the patch locations need to be found before finishing parsing. If we
* patched while parsing, then parsing could fail and we could be left with an
* incomplete patch. Thus, we keep a list of patches and patch everything all at
* once to mitigate failure cases.
*/
struct Patch
{
// Location to patch.
size_t offset;
// Length of the data.
size_t length;
// Data overwrite the given location with.
const uint8_t* data;
// Name of the patch. Useful to see what's going on.
const char* name;
Patch(size_t offset, size_t length, const uint8_t* data, const char* name = NULL)
: offset(offset),
length(length),
data(data),
name(name)
{}
template<typename T>
Patch(size_t offset, const T* data, const char* name = NULL)
: offset(offset),
length(sizeof(T)),
data((const uint8_t*)data),
name(name)
{
}
friend std::ostream& operator<<(std::ostream& os, const Patch& patch);
/**
* Applies the patch. Note that no bounds checking is done. It is assumed
* that it has already been done.
*/
void apply(uint8_t* buf, bool dryRun) {
std::cout << *this << std::endl;
if (!dryRun) {
for (size_t i = 0; i < length; ++i)
buf[offset+i] = data[i];
}
}
};
std::ostream& operator<<(std::ostream& os, const Patch& patch) {
os << "Patching '" << patch.name
<< "' at offset 0x" << std::hex << patch.offset << std::dec
<< " (" << patch.length << " bytes)";
return os;
}
class Patches
{
private:
// List of patches
std::vector<Patch> _patches;
uint8_t* _buf;
public:
Patches(uint8_t* buf) : _buf(buf) {}
void add(Patch patch) {
_patches.push_back(patch);
}
template<typename T>
void add(const T* addr, const T* data, const char* name = NULL)
{
add(Patch((const uint8_t*)addr - _buf, data, name));
}
void apply(bool dryRun = false) {
for (auto&& patch: _patches)
patch.apply(_buf, dryRun);
}
};
/**
* Helper class to parse image headers.
*/
class ImageHeaders
{
private:
const uint8_t* _buf;
const size_t _length;
// Pointer to the optional header.
const uint8_t* _optional;
void _init();
public:
const IMAGE_DOS_HEADER* dos;
const IMAGE_FILE_HEADER* file;
const IMAGE_SECTION_HEADER* sections;
ImageHeaders(const uint8_t* buf, size_t length);
/**
* The Magic field of the optional header. This is used to determine if the
* optional header is 32- or 64-bit.
*/
uint16_t magic() const {
return *(uint16_t*)_optional;
}
/**
* Returns the optional header of the given type.
*/
template<typename T>
const T* optional() const {
// Bounds check
if (_optional + sizeof(T) >= _buf + _length)
throw InvalidImage("missing IMAGE_OPTIONAL_HEADER");
return (T*)_optional;
}
/**
* Translates a relative virtual address (RVA) to a physical address within
* the mapped file. Note that this does not do any bounds checking. You must
* check the bounds before dereferencing the returned pointer.
*/
const uint8_t* translate(size_t rva) const {
const IMAGE_SECTION_HEADER* s = sections;
for (size_t i = 0; i < file->NumberOfSections; ++i) {
if (rva >= s->VirtualAddress &&
rva < s->VirtualAddress + s->Misc.VirtualSize)
break;
++s;
}
return _buf + rva - s->VirtualAddress + s->PointerToRawData;
}
/**
* Checks if the given image address is valid.
*/
bool isValidAddress(const uint8_t* p) const {
return p >= _buf && p < _buf + _length;
}
};
ImageHeaders::ImageHeaders(const uint8_t* buf, size_t length)
: _buf(buf), _length(length)
{
_init();
}
void ImageHeaders::_init() {
const uint8_t* p = _buf;
const uint8_t* end = _buf + _length;
if (p + sizeof(IMAGE_DOS_HEADER) >= end)
throw InvalidImage("missing DOS header");
dos = (IMAGE_DOS_HEADER*)p;
if (dos->e_magic != IMAGE_DOS_SIGNATURE)
throw InvalidImage("invalid DOS signature");
// Skip to the NT headers. Note that we don't parse this section as
// IMAGE_NT_HEADERS32/IMAGE_NT_HEADERS64 because we don't yet know if this
// image is 32- or 64-bit. That information is in the first field of the
// optional header.
p += dos->e_lfanew;
//
// Check the signature
//
if (p + sizeof(uint32_t) >= end)
throw InvalidImage("missing PE signature");
const uint32_t signature = *(uint32_t*)p;
if (signature != *(const uint32_t*)"PE\0\0")
throw InvalidImage("invalid PE signature");
p += sizeof(signature);
//
// Parse the image file header
//
if (p + sizeof(IMAGE_FILE_HEADER) >= end)
throw InvalidImage("missing IMAGE_FILE_HEADER");
file = (IMAGE_FILE_HEADER*)p;
p += sizeof(IMAGE_FILE_HEADER);
//
// The optional header is here. Parsing of this is delayed because it can
// either be a 32- or 64-bit structure.
//
_optional = p;
p += file->SizeOfOptionalHeader;
//
// Section headers. There are IMAGE_FILE_HEADER.NumberOfSections of these.
//
sections = (IMAGE_SECTION_HEADER*)p;
}
/**
* Patches the timestamp associated with a data directory.
*/
template<typename T>
void patchDataDirectory(const ImageHeaders& headers, Patches& patches,
const IMAGE_DATA_DIRECTORY* imageDataDirs,
uint32_t entry, const char* name, uint32_t timestamp) {
const IMAGE_DATA_DIRECTORY& imageDataDir = imageDataDirs[entry];
// Doesn't exist? Nothing to patch.
if (imageDataDir.VirtualAddress == 0)
return;
if (imageDataDir.Size < sizeof(T)) {
// Note that we check if the size is less than our defined struct.
// Microsoft is free to add elements to the end of the struct in future
// versions as that still maintains ABI compatibility.
throw InvalidImage("invalid IMAGE_DATA_DIRECTORY size");
}
const uint8_t* p = headers.translate(imageDataDir.VirtualAddress);
if (!headers.isValidAddress(p))
throw InvalidImage("invalid IMAGE_DATA_DIRECTORY offset");
const T* dir = (const T*)p;
if (dir->TimeDateStamp != 0)
patches.add(&dir->TimeDateStamp, ×tamp, name);
}
/**
* Patches the image based on the optional header type. The optional header can
* be either 32- or 64-bit.
*/
template<typename T>
void patchOptionalHeader(const ImageHeaders& headers,
Patches& patches, uint32_t timestamp) {
const T* optional = headers.optional<T>();
patches.add(&optional->CheckSum, ×tamp,
"OptionalHeader.CheckSum");
const IMAGE_DATA_DIRECTORY* dataDirs = optional->DataDirectory;
// Patch exports directory timestamp
patchDataDirectory<IMAGE_EXPORT_DIRECTORY>(headers, patches,
dataDirs, IMAGE_DIRECTORY_ENTRY_EXPORT,
"IMAGE_EXPORT_DIRECTORY.TimeDateStamp", timestamp);
// Patch resource directory timestamp
patchDataDirectory<IMAGE_RESOURCE_DIRECTORY>(headers, patches,
dataDirs, IMAGE_DIRECTORY_ENTRY_RESOURCE,
"IMAGE_RESOURCE_DIRECTORY.TimeDateStamp", timestamp);
}
}
void patchImage(const char* imagePath, const char* pdbPath, bool dryRun) {
MemMap image(imagePath);
MemMap pdb(pdbPath);
// Replacement for timestamps
const uint32_t timestamp = 0;
uint8_t* buf = (uint8_t*)image.buf();
const size_t length = image.length();
ImageHeaders headers = ImageHeaders(buf, length);
Patches patches(buf);
if (length < sizeof(IMAGE_DOS_HEADER))
throw InvalidImage("missing DOS header");
patches.add(&headers.file->TimeDateStamp, ×tamp,
"IMAGE_FILE_HEADER.TimeDateStamp");
switch (headers.magic()) {
case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
// Patch as a PE32 file
patchOptionalHeader<IMAGE_OPTIONAL_HEADER32>(headers,
patches, timestamp);
break;
case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
// Patch as a PE32+ file
patchOptionalHeader<IMAGE_OPTIONAL_HEADER64>(headers,
patches, timestamp);
break;
default:
throw InvalidImage("unsupported IMAGE_NT_HEADERS.OptionalHeader");
}
patches.apply(dryRun);
}
<commit_msg>Refactoring and cleanup<commit_after>/*
* Copyright (c) 2016 Jason White
*
* 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 <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <iostream>
#include <iomanip>
#include "pefile.h"
#include "pemap.h"
#include "pepatch.h"
namespace {
/**
* A range of memory to patch. This is used to keep track of what needs to be
* patched in the PE file.
*
* All the patch locations need to be found before finishing parsing. If we
* patched while parsing, then parsing could fail and we could be left with an
* incomplete patch. Thus, we keep a list of patches and patch everything all at
* once to mitigate failure cases.
*/
struct Patch
{
// Location to patch.
size_t offset;
// Length of the data.
size_t length;
// Data overwrite the given location with.
const uint8_t* data;
// Name of the patch. Useful to see what's going on.
const char* name;
Patch(size_t offset, size_t length, const uint8_t* data, const char* name = NULL)
: offset(offset),
length(length),
data(data),
name(name)
{}
template<typename T>
Patch(size_t offset, const T* data, const char* name = NULL)
: offset(offset),
length(sizeof(T)),
data((const uint8_t*)data),
name(name)
{
}
friend std::ostream& operator<<(std::ostream& os, const Patch& patch);
/**
* Applies the patch. Note that no bounds checking is done. It is assumed
* that it has already been done.
*/
void apply(uint8_t* buf, bool dryRun) {
std::cout << *this << std::endl;
if (!dryRun) {
for (size_t i = 0; i < length; ++i)
buf[offset+i] = data[i];
}
}
};
std::ostream& operator<<(std::ostream& os, const Patch& patch) {
os << "Patching '" << patch.name
<< "' at offset 0x" << std::hex << patch.offset << std::dec
<< " (" << patch.length << " bytes)";
return os;
}
class Patches
{
private:
// List of patches
std::vector<Patch> _patches;
uint8_t* _buf;
public:
Patches(uint8_t* buf) : _buf(buf) {}
void add(Patch patch) {
_patches.push_back(patch);
}
template<typename T>
void add(const T* addr, const T* data, const char* name = NULL)
{
add(Patch((const uint8_t*)addr - _buf, data, name));
}
void apply(bool dryRun = false) {
for (auto&& patch: _patches)
patch.apply(_buf, dryRun);
}
};
/**
* Helper class to parse image headers.
*/
class PEFile
{
private:
const uint8_t* _buf;
const size_t _length;
// Pointer to the optional header.
const uint8_t* _optional;
void _init();
public:
const IMAGE_DOS_HEADER* dosHeader;
const IMAGE_FILE_HEADER* fileHeader;
const IMAGE_SECTION_HEADER* sectionHeaders;
PEFile(const uint8_t* buf, size_t length);
/**
* The Magic field of the optional header. This is used to determine if the
* optional header is 32- or 64-bit.
*/
uint16_t magic() const {
return *(uint16_t*)_optional;
}
/**
* Returns the optional header of the given type.
*/
template<typename T>
const T* optional() const {
// Bounds check
if (_optional + sizeof(T) >= _buf + _length)
throw InvalidImage("missing IMAGE_OPTIONAL_HEADER");
return (T*)_optional;
}
/**
* Translates a relative virtual address (RVA) to a physical address within
* the mapped file. Note that this does not do any bounds checking. You must
* check the bounds before dereferencing the returned pointer.
*/
const uint8_t* translate(size_t rva) const {
const IMAGE_SECTION_HEADER* s = sectionHeaders;
for (size_t i = 0; i < fileHeader->NumberOfSections; ++i) {
if (rva >= s->VirtualAddress &&
rva < s->VirtualAddress + s->Misc.VirtualSize)
break;
++s;
}
return _buf + rva - s->VirtualAddress + s->PointerToRawData;
}
/**
* Checks if the given image address is valid.
*/
bool isValidAddress(const uint8_t* p) const {
return p >= _buf && p < _buf + _length;
}
};
PEFile::PEFile(const uint8_t* buf, size_t length)
: _buf(buf), _length(length)
{
_init();
}
void PEFile::_init() {
const uint8_t* p = _buf;
const uint8_t* end = _buf + _length;
if (p + sizeof(IMAGE_DOS_HEADER) >= end)
throw InvalidImage("missing DOS header");
dosHeader = (IMAGE_DOS_HEADER*)p;
if (dosHeader->e_magic != IMAGE_DOS_SIGNATURE)
throw InvalidImage("invalid DOS signature");
// Skip to the NT headers. Note that we don't parse this section as
// IMAGE_NT_HEADERS32/IMAGE_NT_HEADERS64 because we don't yet know if this
// image is 32- or 64-bit. That information is in the first field of the
// optional header.
p += dosHeader->e_lfanew;
//
// Check the signature
//
if (p + sizeof(uint32_t) >= end)
throw InvalidImage("missing PE signature");
const uint32_t signature = *(uint32_t*)p;
if (signature != *(const uint32_t*)"PE\0\0")
throw InvalidImage("invalid PE signature");
p += sizeof(signature);
//
// Parse the image file header
//
if (p + sizeof(IMAGE_FILE_HEADER) >= end)
throw InvalidImage("missing IMAGE_FILE_HEADER");
fileHeader = (IMAGE_FILE_HEADER*)p;
p += sizeof(IMAGE_FILE_HEADER);
//
// The optional header is here. Parsing of this is delayed because it can
// either be a 32- or 64-bit structure.
//
_optional = p;
p += fileHeader->SizeOfOptionalHeader;
//
// Section headers. There are IMAGE_FILE_HEADER.NumberOfSections of these.
//
sectionHeaders = (IMAGE_SECTION_HEADER*)p;
}
/**
* Patches the timestamp associated with a data directory.
*/
template<typename T>
void patchDataDirectory(const PEFile& pe, Patches& patches,
const IMAGE_DATA_DIRECTORY* imageDataDirs,
uint32_t entry, const char* name, uint32_t timestamp) {
const IMAGE_DATA_DIRECTORY& imageDataDir = imageDataDirs[entry];
// Doesn't exist? Nothing to patch.
if (imageDataDir.VirtualAddress == 0)
return;
if (imageDataDir.Size < sizeof(T)) {
// Note that we check if the size is less than our defined struct.
// Microsoft is free to add elements to the end of the struct in future
// versions as that still maintains ABI compatibility.
throw InvalidImage("invalid IMAGE_DATA_DIRECTORY size");
}
const uint8_t* p = pe.translate(imageDataDir.VirtualAddress);
if (!pe.isValidAddress(p))
throw InvalidImage("invalid IMAGE_DATA_DIRECTORY offset");
const T* dir = (const T*)p;
if (dir->TimeDateStamp != 0)
patches.add(&dir->TimeDateStamp, ×tamp, name);
}
/**
* Patches the image based on the optional header type. The optional header can
* be either 32- or 64-bit.
*/
template<typename T>
void patchOptionalHeader(const PEFile& pe,
Patches& patches, uint32_t timestamp) {
const T* optional = pe.optional<T>();
patches.add(&optional->CheckSum, ×tamp,
"OptionalHeader.CheckSum");
const IMAGE_DATA_DIRECTORY* dataDirs = optional->DataDirectory;
// Patch exports directory timestamp
patchDataDirectory<IMAGE_EXPORT_DIRECTORY>(pe, patches,
dataDirs, IMAGE_DIRECTORY_ENTRY_EXPORT,
"IMAGE_EXPORT_DIRECTORY.TimeDateStamp", timestamp);
// Patch resource directory timestamp
patchDataDirectory<IMAGE_RESOURCE_DIRECTORY>(pe, patches,
dataDirs, IMAGE_DIRECTORY_ENTRY_RESOURCE,
"IMAGE_RESOURCE_DIRECTORY.TimeDateStamp", timestamp);
}
}
void patchImage(const char* imagePath, const char* pdbPath, bool dryRun) {
MemMap image(imagePath);
MemMap pdb(pdbPath);
// Replacement for timestamps
const uint32_t timestamp = 0;
uint8_t* buf = (uint8_t*)image.buf();
const size_t length = image.length();
PEFile pe = PEFile(buf, length);
Patches patches(buf);
patches.add(&pe.fileHeader->TimeDateStamp, ×tamp,
"IMAGE_FILE_HEADER.TimeDateStamp");
switch (pe.magic()) {
case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
// Patch as a PE32 file
patchOptionalHeader<IMAGE_OPTIONAL_HEADER32>(pe,
patches, timestamp);
break;
case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
// Patch as a PE32+ file
patchOptionalHeader<IMAGE_OPTIONAL_HEADER64>(pe,
patches, timestamp);
break;
default:
throw InvalidImage("unsupported IMAGE_NT_HEADERS.OptionalHeader");
}
patches.apply(dryRun);
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2016 Jason White
*
* 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 <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <iostream>
#include <iomanip>
#include "pefile.h"
#include "pemap.h"
#include "pepatch.h"
namespace {
/**
* A range of memory to patch. This is used to keep track of what needs to be
* patched in the PE file.
*
* All the patch locations need to be found before finishing parsing. If we
* patched while parsing, then parsing could fail and we could be left with an
* incomplete patch. Thus, we keep a list of patches and patch everything all at
* once to mitigate failure cases.
*/
struct Patch
{
// Location to patch.
size_t offset;
// Length of the data.
size_t length;
// Data overwrite the given location with.
const uint8_t* data;
// Name of the patch. Useful to see what's going on.
const char* name;
Patch(size_t offset, size_t length, const uint8_t* data, const char* name = NULL)
: offset(offset),
length(length),
data(data),
name(name)
{}
template<typename T>
Patch(size_t offset, const T* data, const char* name = NULL)
: offset(offset),
length(sizeof(T)),
data((const uint8_t*)data),
name(name)
{
}
friend std::ostream& operator<<(std::ostream& os, const Patch& patch);
/**
* Applies the patch. Note that no bounds checking is done. It is assumed
* that it has already been done.
*/
void apply(uint8_t* buf, bool dryRun) {
std::cout << *this << std::endl;
if (!dryRun) {
for (size_t i = 0; i < length; ++i)
buf[offset+i] = data[i];
}
}
};
std::ostream& operator<<(std::ostream& os, const Patch& patch) {
os << "Patching '" << patch.name
<< "' at offset 0x" << std::hex << patch.offset << std::dec
<< " (" << patch.length << " bytes)";
return os;
}
class Patches
{
private:
// List of patches
std::vector<Patch> _patches;
uint8_t* _buf;
public:
Patches(uint8_t* buf) : _buf(buf) {}
void add(Patch patch) {
_patches.push_back(patch);
}
template<typename T>
void add(const T* addr, const T* data, const char* name = NULL)
{
add(Patch((const uint8_t*)addr - _buf, data, name));
}
void apply(bool dryRun = false) {
for (auto&& patch: _patches)
patch.apply(_buf, dryRun);
}
};
/**
* Helper class to parse image headers.
*/
class PEFile
{
private:
const uint8_t* _buf;
const size_t _length;
// Pointer to the optional header.
const uint8_t* _optional;
void _init();
public:
const IMAGE_DOS_HEADER* dosHeader;
const IMAGE_FILE_HEADER* fileHeader;
const IMAGE_SECTION_HEADER* sectionHeaders;
PEFile(const uint8_t* buf, size_t length);
/**
* The Magic field of the optional header. This is used to determine if the
* optional header is 32- or 64-bit.
*/
uint16_t magic() const {
return *(uint16_t*)_optional;
}
/**
* Returns the optional header of the given type.
*/
template<typename T>
const T* optional() const {
// Bounds check
if (_optional + sizeof(T) >= _buf + _length)
throw InvalidImage("missing IMAGE_OPTIONAL_HEADER");
return (T*)_optional;
}
/**
* Translates a relative virtual address (RVA) to a physical address within
* the mapped file. Note that this does not do any bounds checking. You must
* check the bounds before dereferencing the returned pointer.
*/
const uint8_t* translate(size_t rva) const {
const IMAGE_SECTION_HEADER* s = sectionHeaders;
for (size_t i = 0; i < fileHeader->NumberOfSections; ++i) {
if (rva >= s->VirtualAddress &&
rva < s->VirtualAddress + s->Misc.VirtualSize)
break;
++s;
}
return _buf + rva - s->VirtualAddress + s->PointerToRawData;
}
/**
* Checks if the given image address is valid.
*/
bool isValidAddress(const uint8_t* p) const {
return p >= _buf && p < _buf + _length;
}
};
PEFile::PEFile(const uint8_t* buf, size_t length)
: _buf(buf), _length(length)
{
_init();
}
void PEFile::_init() {
const uint8_t* p = _buf;
const uint8_t* end = _buf + _length;
if (p + sizeof(IMAGE_DOS_HEADER) >= end)
throw InvalidImage("missing DOS header");
dosHeader = (IMAGE_DOS_HEADER*)p;
if (dosHeader->e_magic != IMAGE_DOS_SIGNATURE)
throw InvalidImage("invalid DOS signature");
// Skip to the NT headers. Note that we don't parse this section as
// IMAGE_NT_HEADERS32/IMAGE_NT_HEADERS64 because we don't yet know if this
// image is 32- or 64-bit. That information is in the first field of the
// optional header.
p += dosHeader->e_lfanew;
//
// Check the signature
//
if (p + sizeof(uint32_t) >= end)
throw InvalidImage("missing PE signature");
const uint32_t signature = *(uint32_t*)p;
if (signature != *(const uint32_t*)"PE\0\0")
throw InvalidImage("invalid PE signature");
p += sizeof(signature);
//
// Parse the image file header
//
if (p + sizeof(IMAGE_FILE_HEADER) >= end)
throw InvalidImage("missing IMAGE_FILE_HEADER");
fileHeader = (IMAGE_FILE_HEADER*)p;
p += sizeof(IMAGE_FILE_HEADER);
//
// The optional header is here. Parsing of this is delayed because it can
// either be a 32- or 64-bit structure.
//
_optional = p;
p += fileHeader->SizeOfOptionalHeader;
//
// Section headers. There are IMAGE_FILE_HEADER.NumberOfSections of these.
//
sectionHeaders = (IMAGE_SECTION_HEADER*)p;
}
/**
* Patches the timestamp associated with a data directory.
*/
template<typename T>
void patchDataDirectory(const PEFile& pe, Patches& patches,
const IMAGE_DATA_DIRECTORY* imageDataDirs,
uint32_t entry, const char* name, uint32_t timestamp) {
const IMAGE_DATA_DIRECTORY& imageDataDir = imageDataDirs[entry];
// Doesn't exist? Nothing to patch.
if (imageDataDir.VirtualAddress == 0)
return;
if (imageDataDir.Size < sizeof(T)) {
// Note that we check if the size is less than our defined struct.
// Microsoft is free to add elements to the end of the struct in future
// versions as that still maintains ABI compatibility.
throw InvalidImage("invalid IMAGE_DATA_DIRECTORY size");
}
const uint8_t* p = pe.translate(imageDataDir.VirtualAddress);
if (!pe.isValidAddress(p))
throw InvalidImage("invalid IMAGE_DATA_DIRECTORY offset");
const T* dir = (const T*)p;
if (dir->TimeDateStamp != 0)
patches.add(&dir->TimeDateStamp, ×tamp, name);
}
/**
* Patches the image based on the optional header type. The optional header can
* be either 32- or 64-bit.
*/
template<typename T>
void patchOptionalHeader(const PEFile& pe,
Patches& patches, uint32_t timestamp) {
const T* optional = pe.optional<T>();
patches.add(&optional->CheckSum, ×tamp,
"OptionalHeader.CheckSum");
const IMAGE_DATA_DIRECTORY* dataDirs = optional->DataDirectory;
// Patch exports directory timestamp
patchDataDirectory<IMAGE_EXPORT_DIRECTORY>(pe, patches,
dataDirs, IMAGE_DIRECTORY_ENTRY_EXPORT,
"IMAGE_EXPORT_DIRECTORY.TimeDateStamp", timestamp);
// Patch resource directory timestamp
patchDataDirectory<IMAGE_RESOURCE_DIRECTORY>(pe, patches,
dataDirs, IMAGE_DIRECTORY_ENTRY_RESOURCE,
"IMAGE_RESOURCE_DIRECTORY.TimeDateStamp", timestamp);
}
}
void patchImage(const char* imagePath, const char* pdbPath, bool dryRun) {
MemMap image(imagePath);
MemMap pdb(pdbPath);
// Replacement for timestamps
const uint32_t timestamp = 0;
uint8_t* buf = (uint8_t*)image.buf();
const size_t length = image.length();
PEFile pe = PEFile(buf, length);
Patches patches(buf);
patches.add(&pe.fileHeader->TimeDateStamp, ×tamp,
"IMAGE_FILE_HEADER.TimeDateStamp");
switch (pe.magic()) {
case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
// Patch as a PE32 file
patchOptionalHeader<IMAGE_OPTIONAL_HEADER32>(pe,
patches, timestamp);
break;
case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
// Patch as a PE32+ file
patchOptionalHeader<IMAGE_OPTIONAL_HEADER64>(pe,
patches, timestamp);
break;
default:
throw InvalidImage("unsupported IMAGE_NT_HEADERS.OptionalHeader");
}
patches.apply(dryRun);
}
<commit_msg>Patch debug data directories<commit_after>/*
* Copyright (c) 2016 Jason White
*
* 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 <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <iostream>
#include <iomanip>
#include "pefile.h"
#include "pemap.h"
#include "pepatch.h"
namespace {
/**
* A range of memory to patch. This is used to keep track of what needs to be
* patched in the PE file.
*
* All the patch locations need to be found before finishing parsing. If we
* patched while parsing, then parsing could fail and we could be left with an
* incomplete patch. Thus, we keep a list of patches and patch everything all at
* once to mitigate failure cases.
*/
struct Patch
{
// Location to patch.
size_t offset;
// Length of the data.
size_t length;
// Data overwrite the given location with.
const uint8_t* data;
// Name of the patch. Useful to see what's going on.
const char* name;
Patch(size_t offset, size_t length, const uint8_t* data, const char* name = NULL)
: offset(offset),
length(length),
data(data),
name(name)
{}
template<typename T>
Patch(size_t offset, const T* data, const char* name = NULL)
: offset(offset),
length(sizeof(T)),
data((const uint8_t*)data),
name(name)
{
}
friend std::ostream& operator<<(std::ostream& os, const Patch& patch);
/**
* Applies the patch. Note that no bounds checking is done. It is assumed
* that it has already been done.
*/
void apply(uint8_t* buf, bool dryRun) {
std::cout << *this << std::endl;
if (!dryRun) {
for (size_t i = 0; i < length; ++i)
buf[offset+i] = data[i];
}
}
};
std::ostream& operator<<(std::ostream& os, const Patch& patch) {
os << "Patching '" << patch.name
<< "' at offset 0x" << std::hex << patch.offset << std::dec
<< " (" << patch.length << " bytes)";
return os;
}
class Patches
{
private:
// List of patches
std::vector<Patch> _patches;
uint8_t* _buf;
public:
Patches(uint8_t* buf) : _buf(buf) {}
void add(Patch patch) {
_patches.push_back(patch);
}
template<typename T>
void add(const T* addr, const T* data, const char* name = NULL)
{
add(Patch((const uint8_t*)addr - _buf, data, name));
}
void apply(bool dryRun = false) {
for (auto&& patch: _patches)
patch.apply(_buf, dryRun);
}
};
/**
* Helper class to parse image headers.
*/
class PEFile
{
private:
const uint8_t* _buf;
const size_t _length;
// Pointer to the optional header.
const uint8_t* _optional;
void _init();
public:
const IMAGE_DOS_HEADER* dosHeader;
const IMAGE_FILE_HEADER* fileHeader;
const IMAGE_SECTION_HEADER* sectionHeaders;
PEFile(const uint8_t* buf, size_t length);
/**
* The Magic field of the optional header. This is used to determine if the
* optional header is 32- or 64-bit.
*/
uint16_t magic() const {
return *(uint16_t*)_optional;
}
/**
* Returns the optional header of the given type.
*/
template<typename T>
const T* optional() const {
// Bounds check
if (_optional + sizeof(T) >= _buf + _length)
throw InvalidImage("missing IMAGE_OPTIONAL_HEADER");
return (T*)_optional;
}
/**
* Translates a relative virtual address (RVA) to a physical address within
* the mapped file. Note that this does not do any bounds checking. You must
* check the bounds before dereferencing the returned pointer.
*/
const uint8_t* translate(size_t rva) const {
const IMAGE_SECTION_HEADER* s = sectionHeaders;
for (size_t i = 0; i < fileHeader->NumberOfSections; ++i) {
if (rva >= s->VirtualAddress &&
rva < s->VirtualAddress + s->Misc.VirtualSize)
break;
++s;
}
return _buf + rva - s->VirtualAddress + s->PointerToRawData;
}
/**
* Checks if the given image address is valid.
*/
bool isValidAddress(const uint8_t* p) const {
return p >= _buf && p < _buf + _length;
}
};
PEFile::PEFile(const uint8_t* buf, size_t length)
: _buf(buf), _length(length)
{
_init();
}
void PEFile::_init() {
const uint8_t* p = _buf;
const uint8_t* end = _buf + _length;
if (p + sizeof(IMAGE_DOS_HEADER) >= end)
throw InvalidImage("missing DOS header");
dosHeader = (IMAGE_DOS_HEADER*)p;
if (dosHeader->e_magic != IMAGE_DOS_SIGNATURE)
throw InvalidImage("invalid DOS signature");
// Skip to the NT headers. Note that we don't parse this section as
// IMAGE_NT_HEADERS32/IMAGE_NT_HEADERS64 because we don't yet know if this
// image is 32- or 64-bit. That information is in the first field of the
// optional header.
p += dosHeader->e_lfanew;
//
// Check the signature
//
if (p + sizeof(uint32_t) >= end)
throw InvalidImage("missing PE signature");
const uint32_t signature = *(uint32_t*)p;
if (signature != *(const uint32_t*)"PE\0\0")
throw InvalidImage("invalid PE signature");
p += sizeof(signature);
//
// Parse the image file header
//
if (p + sizeof(IMAGE_FILE_HEADER) >= end)
throw InvalidImage("missing IMAGE_FILE_HEADER");
fileHeader = (IMAGE_FILE_HEADER*)p;
p += sizeof(IMAGE_FILE_HEADER);
//
// The optional header is here. Parsing of this is delayed because it can
// either be a 32- or 64-bit structure.
//
_optional = p;
p += fileHeader->SizeOfOptionalHeader;
//
// Section headers. There are IMAGE_FILE_HEADER.NumberOfSections of these.
//
sectionHeaders = (IMAGE_SECTION_HEADER*)p;
}
/**
* Patches the timestamp associated with a data directory.
*/
template<typename T>
void patchDataDirectory(const PEFile& pe, Patches& patches,
const IMAGE_DATA_DIRECTORY* imageDataDirs,
uint32_t entry, const char* name, uint32_t timestamp) {
const IMAGE_DATA_DIRECTORY& imageDataDir = imageDataDirs[entry];
// Doesn't exist? Nothing to patch.
if (imageDataDir.VirtualAddress == 0)
return;
if (imageDataDir.Size < sizeof(T)) {
// Note that we check if the size is less than our defined struct.
// Microsoft is free to add elements to the end of the struct in future
// versions as that still maintains ABI compatibility.
throw InvalidImage("IMAGE_DATA_DIRECTORY.Size is invalid");
}
const uint8_t* p = pe.translate(imageDataDir.VirtualAddress);
if (!pe.isValidAddress(p))
throw InvalidImage("IMAGE_DATA_DIRECTORY.VirtualAddress is invalid");
const T* dir = (const T*)p;
if (dir->TimeDateStamp != 0)
patches.add(&dir->TimeDateStamp, ×tamp, name);
}
/**
* There are 0 or more debug data directories. We need to patch the timestamp in
* all of them.
*/
void patchDebugDataDirectories(const PEFile& pe, Patches& patches,
const IMAGE_DATA_DIRECTORY* imageDataDirs, uint32_t timestamp) {
const IMAGE_DATA_DIRECTORY& imageDataDir = imageDataDirs[IMAGE_DIRECTORY_ENTRY_DEBUG];
// Doesn't exist? Nothing to patch.
if (imageDataDir.VirtualAddress == 0)
return;
const uint8_t* p = pe.translate(imageDataDir.VirtualAddress);
if (!pe.isValidAddress(p))
throw InvalidImage("invalid IMAGE_DATA_DIRECTORY.VirtualAddress is invalid");
// The first debug data directory
const IMAGE_DEBUG_DIRECTORY* dir = (const IMAGE_DEBUG_DIRECTORY*)p;
// There can be multiple debug data directories in this section. This is how
// to calculate the number of them.
const size_t debugDirCount = imageDataDir.Size /
sizeof(IMAGE_DEBUG_DIRECTORY);
for (size_t i = 0; i < debugDirCount; ++i) {
if (dir->TimeDateStamp != 0)
patches.add(&dir->TimeDateStamp, ×tamp,
"IMAGE_DEBUG_DIRECTORY.TimeDateStamp");
++dir;
}
}
/**
* Patches the image based on the optional header type. The optional header can
* be either 32- or 64-bit.
*/
template<typename T>
void patchOptionalHeader(const PEFile& pe,
Patches& patches, uint32_t timestamp) {
const T* optional = pe.optional<T>();
patches.add(&optional->CheckSum, ×tamp,
"OptionalHeader.CheckSum");
const IMAGE_DATA_DIRECTORY* dataDirs = optional->DataDirectory;
// Patch exports directory timestamp
patchDataDirectory<IMAGE_EXPORT_DIRECTORY>(pe, patches,
dataDirs, IMAGE_DIRECTORY_ENTRY_EXPORT,
"IMAGE_EXPORT_DIRECTORY.TimeDateStamp", timestamp);
// Patch resource directory timestamp
patchDataDirectory<IMAGE_RESOURCE_DIRECTORY>(pe, patches,
dataDirs, IMAGE_DIRECTORY_ENTRY_RESOURCE,
"IMAGE_RESOURCE_DIRECTORY.TimeDateStamp", timestamp);
// Patch the debug directories
patchDebugDataDirectories(pe, patches, dataDirs, timestamp);
}
}
void patchImage(const char* imagePath, const char* pdbPath, bool dryRun) {
MemMap image(imagePath);
MemMap pdb(pdbPath);
// Replacement for timestamps
const uint32_t timestamp = 0;
uint8_t* buf = (uint8_t*)image.buf();
const size_t length = image.length();
PEFile pe = PEFile(buf, length);
Patches patches(buf);
patches.add(&pe.fileHeader->TimeDateStamp, ×tamp,
"IMAGE_FILE_HEADER.TimeDateStamp");
switch (pe.magic()) {
case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
// Patch as a PE32 file
patchOptionalHeader<IMAGE_OPTIONAL_HEADER32>(pe, patches,
timestamp);
break;
case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
// Patch as a PE32+ file
patchOptionalHeader<IMAGE_OPTIONAL_HEADER64>(pe, patches,
timestamp);
break;
default:
throw InvalidImage("unsupported IMAGE_NT_HEADERS.OptionalHeader");
}
patches.apply(dryRun);
}
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (C) 2006 by FThauer FHammer *
* f.thauer@web.de *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include <qapplication.h>
#ifdef __APPLE__
#include <QMacStyle>
#endif
#include "session.h"
#include "startwindowimpl.h"
#include "configfile.h"
#include "startsplash.h"
#include "game_defs.h"
#include <net/socket_startup.h>
#include <curl/curl.h>
#include <QtGui>
#include <QtCore>
#include <iostream>
#include <cstdlib>
#include <ctime>
#ifdef _MSC_VER
#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#define ENABLE_LEAK_CHECK() \
{ \
int tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); \
tmpFlag |= _CRTDBG_LEAK_CHECK_DF; \
_CrtSetDbgFlag(tmpFlag); \
}
#endif
#endif
#ifndef ENABLE_LEAK_CHECK
#define ENABLE_LEAK_CHECK()
#endif
//Uncomment this for RELEASE
// #include <QtPlugin>
// Q_IMPORT_PLUGIN(qjpeg)
// Q_IMPORT_PLUGIN(qgif)
using namespace std;
class startWindowImpl;
class Game;
int main( int argc, char **argv )
{
//ENABLE_LEAK_CHECK();
//_CrtSetBreakAlloc(49937);
socket_startup();
curl_global_init(CURL_GLOBAL_NOTHING);
/////// can be removed for non-qt-guis ////////////
QApplication a( argc, argv );
//create defaultconfig
ConfigFile *myConfig = new ConfigFile(argv[0], false);
// set PlastiqueStyle even for mac-version to prevent artefacts on styled widgets
a.setStyle(new QPlastiqueStyle);
QString myAppDataPath = QString::fromUtf8(myConfig->readConfigString("AppDataDir").c_str());
//set QApplication default font
QFontDatabase::addApplicationFont (myAppDataPath +"fonts/n019003l.pfb");
QFontDatabase::addApplicationFont (myAppDataPath +"fonts/VeraBd.ttf");
QFontDatabase::addApplicationFont (myAppDataPath +"fonts/c059013l.pfb");
#ifdef _WIN32
QString font1String("font-family: \"Arial\";");
a.setStyleSheet("QApplication, QWidget, QDialog { " + font1String + " font-size: 12px; }");
#else
// #ifdef __APPLE__
// QString font1String("font-family: \"Lucida Grande\";");
// #else
QString font1String("font-family: \"Nimbus Sans L\";");
// #endif
a.setStyleSheet("QApplication, QWidget, QDialog { " + font1String + " font-size: 12px; }");
#endif
QPixmap *pixmap = new QPixmap(myAppDataPath + "gfx/gui/misc/welcomepokerth.png");
StartSplash splash(*pixmap);
splash.show();
splash.showMessage(QString("Version %1").arg(POKERTH_BETA_RELEASE_STRING), 0x0042, QColor(153,213,0));
//Set translations
QTranslator qtTranslator;
qtTranslator.load(QString(myAppDataPath +"translations/qt_") + QString::fromStdString(myConfig->readConfigString("Language")));
a.installTranslator(&qtTranslator);
QTranslator translator;
translator.load(QString(myAppDataPath +"translations/pokerth_") + QString::fromStdString(myConfig->readConfigString("Language")));
a.installTranslator(&translator);
#ifdef __APPLE__
QDir dir(QApplication::applicationDirPath());
dir.cdUp();
dir.cd("plugins");
QApplication::setLibraryPaths(QStringList(dir.absolutePath()));
#endif
qRegisterMetaType<unsigned>("unsigned");
qRegisterMetaType<boost::shared_ptr<Game> >("boost::shared_ptr<Game>");
qRegisterMetaType<ServerStats>("ServerStats");
///////////////////////////////////////////////////
boost::shared_ptr<startWindowImpl>(new startWindowImpl(myConfig));
// boost::shared_ptr<GuiInterface> myGuiInterface(new GuiWrapper(myConfig));
// {
// boost::shared_ptr<Session> session(new Session(myGuiInterface.get(), myConfig));
// session->init(); // TODO handle error
// myGuiInterface->setSession(session);
// }
int retVal = a.exec();
curl_global_cleanup();
socket_cleanup();
return retVal;
}
<commit_msg>Fix main window creation.<commit_after>/***************************************************************************
* Copyright (C) 2006 by FThauer FHammer *
* f.thauer@web.de *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include <qapplication.h>
#ifdef __APPLE__
#include <QMacStyle>
#endif
#include "session.h"
#include "startwindowimpl.h"
#include "configfile.h"
#include "startsplash.h"
#include "game_defs.h"
#include <net/socket_startup.h>
#include <curl/curl.h>
#include <QtGui>
#include <QtCore>
#include <iostream>
#include <cstdlib>
#include <ctime>
#ifdef _MSC_VER
#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#define ENABLE_LEAK_CHECK() \
{ \
int tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); \
tmpFlag |= _CRTDBG_LEAK_CHECK_DF; \
_CrtSetDbgFlag(tmpFlag); \
}
#endif
#endif
#ifndef ENABLE_LEAK_CHECK
#define ENABLE_LEAK_CHECK()
#endif
//Uncomment this for RELEASE
// #include <QtPlugin>
// Q_IMPORT_PLUGIN(qjpeg)
// Q_IMPORT_PLUGIN(qgif)
using namespace std;
class startWindowImpl;
class Game;
int main( int argc, char **argv )
{
//ENABLE_LEAK_CHECK();
//_CrtSetBreakAlloc(49937);
socket_startup();
curl_global_init(CURL_GLOBAL_NOTHING);
/////// can be removed for non-qt-guis ////////////
QApplication a( argc, argv );
//create defaultconfig
ConfigFile *myConfig = new ConfigFile(argv[0], false);
// set PlastiqueStyle even for mac-version to prevent artefacts on styled widgets
a.setStyle(new QPlastiqueStyle);
QString myAppDataPath = QString::fromUtf8(myConfig->readConfigString("AppDataDir").c_str());
//set QApplication default font
QFontDatabase::addApplicationFont (myAppDataPath +"fonts/n019003l.pfb");
QFontDatabase::addApplicationFont (myAppDataPath +"fonts/VeraBd.ttf");
QFontDatabase::addApplicationFont (myAppDataPath +"fonts/c059013l.pfb");
#ifdef _WIN32
QString font1String("font-family: \"Arial\";");
a.setStyleSheet("QApplication, QWidget, QDialog { " + font1String + " font-size: 12px; }");
#else
// #ifdef __APPLE__
// QString font1String("font-family: \"Lucida Grande\";");
// #else
QString font1String("font-family: \"Nimbus Sans L\";");
// #endif
a.setStyleSheet("QApplication, QWidget, QDialog { " + font1String + " font-size: 12px; }");
#endif
QPixmap *pixmap = new QPixmap(myAppDataPath + "gfx/gui/misc/welcomepokerth.png");
StartSplash splash(*pixmap);
splash.show();
splash.showMessage(QString("Version %1").arg(POKERTH_BETA_RELEASE_STRING), 0x0042, QColor(153,213,0));
//Set translations
QTranslator qtTranslator;
qtTranslator.load(QString(myAppDataPath +"translations/qt_") + QString::fromStdString(myConfig->readConfigString("Language")));
a.installTranslator(&qtTranslator);
QTranslator translator;
translator.load(QString(myAppDataPath +"translations/pokerth_") + QString::fromStdString(myConfig->readConfigString("Language")));
a.installTranslator(&translator);
#ifdef __APPLE__
QDir dir(QApplication::applicationDirPath());
dir.cdUp();
dir.cd("plugins");
QApplication::setLibraryPaths(QStringList(dir.absolutePath()));
#endif
qRegisterMetaType<unsigned>("unsigned");
qRegisterMetaType<boost::shared_ptr<Game> >("boost::shared_ptr<Game>");
qRegisterMetaType<ServerStats>("ServerStats");
///////////////////////////////////////////////////
startWindowImpl *mainWin = new startWindowImpl(myConfig);
int retVal = a.exec();
curl_global_cleanup();
socket_cleanup();
return retVal;
}
<|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 <cassert>
#include <raul/Atom.hpp>
#include "interface/EngineInterface.hpp"
#include "client/NodeModel.hpp"
#include "client/PatchModel.hpp"
#include "client/PluginUI.hpp"
#include "App.hpp"
#include "GladeFactory.hpp"
#include "NodeControlWindow.hpp"
#include "NodeModule.hpp"
#include "PatchCanvas.hpp"
#include "PatchWindow.hpp"
#include "Port.hpp"
#include "RenameWindow.hpp"
#include "SubpatchModule.hpp"
#include "WindowFactory.hpp"
namespace Ingen {
namespace GUI {
NodeModule::NodeModule(boost::shared_ptr<PatchCanvas> canvas, SharedPtr<NodeModel> node)
: FlowCanvas::Module(canvas, node->path().name())
, _node(node)
, _gui_widget(NULL)
, _gui_container(NULL)
, _gui_item(NULL)
, _gui_window(NULL)
, _last_gui_request_width(0)
, _last_gui_request_height(0)
{
assert(_node);
node->signal_new_port.connect(sigc::bind(sigc::mem_fun(this, &NodeModule::add_port), true));
node->signal_removed_port.connect(sigc::mem_fun(this, &NodeModule::remove_port));
node->signal_variable.connect(sigc::mem_fun(this, &NodeModule::set_variable));
node->signal_polyphonic.connect(sigc::mem_fun(this, &NodeModule::set_stacked_border));
node->signal_renamed.connect(sigc::mem_fun(this, &NodeModule::rename));
set_stacked_border(node->polyphonic());
}
NodeModule::~NodeModule()
{
NodeControlWindow* win = App::instance().window_factory()->control_window(_node);
if (win) {
// Should remove from window factory via signal
delete win;
}
}
void
NodeModule::create_menu()
{
Glib::RefPtr<Gnome::Glade::Xml> xml = GladeFactory::new_glade_reference();
xml->get_widget_derived("object_menu", _menu);
_menu->init(_node);
_menu->signal_embed_gui.connect(sigc::mem_fun(this, &NodeModule::embed_gui));
_menu->signal_popup_gui.connect(sigc::hide_return(sigc::mem_fun(this, &NodeModule::popup_gui)));
set_menu(_menu);
}
boost::shared_ptr<NodeModule>
NodeModule::create(boost::shared_ptr<PatchCanvas> canvas, SharedPtr<NodeModel> node)
{
boost::shared_ptr<NodeModule> ret;
SharedPtr<PatchModel> patch = PtrCast<PatchModel>(node);
if (patch)
ret = boost::shared_ptr<NodeModule>(new SubpatchModule(canvas, patch));
else
ret = boost::shared_ptr<NodeModule>(new NodeModule(canvas, node));
for (GraphObject::Variables::const_iterator m = node->variables().begin(); m != node->variables().end(); ++m)
ret->set_variable(m->first, m->second);
for (PortModelList::const_iterator p = node->ports().begin(); p != node->ports().end(); ++p) {
ret->add_port(*p, false);
}
ret->resize();
return ret;
}
void
NodeModule::value_changed(uint32_t index, const Atom& value)
{
float control = value.get_float();
if (_plugin_ui) {
SLV2UIInstance inst = _plugin_ui->instance();
const LV2UI_Descriptor* ui_descriptor = slv2_ui_instance_get_descriptor(inst);
LV2UI_Handle ui_handle = slv2_ui_instance_get_handle(inst);
if (ui_descriptor->port_event)
ui_descriptor->port_event(ui_handle, index, 4, 0, &control);
}
}
void
NodeModule::embed_gui(bool embed)
{
if (embed) {
if (_gui_window) {
cerr << "LV2 GUI already popped up, cannot embed" << endl;
return;
}
GtkWidget* c_widget = NULL;
if (!_gui_item) {
const PluginModel* const plugin = dynamic_cast<const PluginModel*>(_node->plugin());
assert(plugin);
_plugin_ui = plugin->ui(App::instance().world(), _node);
if (_plugin_ui) {
c_widget = (GtkWidget*)slv2_ui_instance_get_widget(_plugin_ui->instance());
_gui_widget = Glib::wrap(c_widget);
assert(_gui_widget);
if (_gui_container)
delete _gui_container;
_gui_container = manage(new Gtk::EventBox());
_gui_container->set_name("ingen_embedded_node_gui_container");
_gui_container->set_border_width(2);
_gui_container->add(*_gui_widget);
_gui_container->show_all();
const double y = 4 + _canvas_title.property_text_height();
_gui_item = new Gnome::Canvas::Widget(*this, 2.0, y, *_gui_container);
}
}
if (_gui_item) {
assert(_gui_widget);
_gui_widget->show_all();
_gui_item->show();
Gtk::Requisition r = _gui_container->size_request();
gui_size_request(&r, true);
_gui_item->raise_to_top();
_gui_container->signal_size_request().connect(sigc::bind(
sigc::mem_fun(this, &NodeModule::gui_size_request), false));
for (PortModelList::const_iterator p = _node->ports().begin(); p != _node->ports().end(); ++p)
if ((*p)->type().is_control() && (*p)->is_output())
App::instance().engine()->enable_port_broadcasting((*p)->path());
} else {
cerr << "ERROR: Failed to create canvas item for LV2 UI" << endl;
}
} else { // un-embed
if (_gui_item) {
delete _gui_item;
_gui_item = NULL;
_gui_container = NULL; // managed
_gui_widget = NULL; // managed
_plugin_ui.reset();
}
_ports_y_offset = 0;
_minimum_width = 0; // resize() takes care of it..
for (PortModelList::const_iterator p = _node->ports().begin(); p != _node->ports().end(); ++p)
if ((*p)->type().is_control() && (*p)->is_output())
App::instance().engine()->disable_port_broadcasting((*p)->path());
}
if (embed && _gui_item) {
initialise_gui_values();
set_base_color(0x212222FF);
} else {
set_default_base_color();
}
resize();
}
void
NodeModule::gui_size_request(Gtk::Requisition* r, bool force)
{
if (!force && _last_gui_request_width == r->width && _last_gui_request_height == r->height)
return;
if (r->width + 4 > _width)
set_minimum_width(r->width + 4);
_ports_y_offset = r->height + 2;
resize();
Gtk::Allocation allocation;
allocation.set_width(r->width + 4);
allocation.set_height(r->height + 4);
_gui_container->size_allocate(allocation);
_gui_item->property_width() = _width - 4;
_gui_item->property_height() = r->height;
_last_gui_request_width = r->width;
_last_gui_request_height = r->height;
}
void
NodeModule::rename()
{
set_name(_node->path().name());
resize();
}
void
NodeModule::add_port(SharedPtr<PortModel> port, bool resize_to_fit)
{
uint32_t index = _ports.size(); // FIXME: kluge, engine needs to tell us this
Module::add_port(boost::shared_ptr<Port>(
new Port(PtrCast<NodeModule>(shared_from_this()), port)));
port->signal_value_changed.connect(sigc::bind<0>(
sigc::mem_fun(this, &NodeModule::value_changed), index));
if (resize_to_fit)
resize();
}
void
NodeModule::remove_port(SharedPtr<PortModel> port)
{
SharedPtr<FlowCanvas::Port> p = Module::remove_port(port->path().name());
p.reset();
}
bool
NodeModule::popup_gui()
{
#ifdef HAVE_SLV2
if (_node->plugin()->type() == PluginModel::LV2) {
if (_plugin_ui) {
cerr << "LV2 GUI already embedded, cannot pop up" << endl;
return false;
}
const PluginModel* const plugin = dynamic_cast<const PluginModel*>(_node->plugin());
assert(plugin);
_plugin_ui = plugin->ui(App::instance().world(), _node);
if (_plugin_ui) {
GtkWidget* c_widget = (GtkWidget*)slv2_ui_instance_get_widget(_plugin_ui->instance());
_gui_widget = Glib::wrap(c_widget);
_gui_window = new Gtk::Window();
_gui_window->add(*_gui_widget);
_gui_widget->show_all();
initialise_gui_values();
_gui_window->signal_unmap().connect(
sigc::mem_fun(this, &NodeModule::on_gui_window_close));
_gui_window->present();
return true;
} else {
cerr << "No LV2 GUI" << endl;
}
}
#endif
return false;
}
void
NodeModule::on_gui_window_close()
{
delete _gui_window;
_gui_window = NULL;
_plugin_ui.reset();
_gui_widget = NULL;
}
void
NodeModule::initialise_gui_values()
{
uint32_t index=0;
for (PortModelList::const_iterator p = _node->ports().begin(); p != _node->ports().end(); ++p) {
if ((*p)->type().is_control())
value_changed(index, (*p)->value());
++index;
}
}
void
NodeModule::show_control_window()
{
App::instance().window_factory()->present_controls(_node);
}
void
NodeModule::on_double_click(GdkEventButton* ev)
{
if ( ! popup_gui() )
show_control_window();
}
void
NodeModule::store_location()
{
const float x = static_cast<float>(property_x());
const float y = static_cast<float>(property_y());
const Atom& existing_x = _node->get_variable("ingenuity:canvas-x");
const Atom& existing_y = _node->get_variable("ingenuity:canvas-y");
if (existing_x.type() != Atom::FLOAT || existing_y.type() != Atom::FLOAT
|| existing_x.get_float() != x || existing_y.get_float() != y) {
App::instance().engine()->set_variable(_node->path(), "ingenuity:canvas-x", Atom(x));
App::instance().engine()->set_variable(_node->path(), "ingenuity:canvas-y", Atom(y));
}
}
void
NodeModule::set_variable(const string& key, const Atom& value)
{
if (key == "ingenuity:canvas-x" && value.type() == Atom::FLOAT)
move_to(value.get_float(), property_y());
else if (key == "ingenuity:canvas-y" && value.type() == Atom::FLOAT)
move_to(property_x(), value.get_float());
}
} // namespace GUI
} // namespace Ingen
<commit_msg>Spell kludge correctly :)<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 <cassert>
#include <raul/Atom.hpp>
#include "interface/EngineInterface.hpp"
#include "client/NodeModel.hpp"
#include "client/PatchModel.hpp"
#include "client/PluginUI.hpp"
#include "App.hpp"
#include "GladeFactory.hpp"
#include "NodeControlWindow.hpp"
#include "NodeModule.hpp"
#include "PatchCanvas.hpp"
#include "PatchWindow.hpp"
#include "Port.hpp"
#include "RenameWindow.hpp"
#include "SubpatchModule.hpp"
#include "WindowFactory.hpp"
namespace Ingen {
namespace GUI {
NodeModule::NodeModule(boost::shared_ptr<PatchCanvas> canvas, SharedPtr<NodeModel> node)
: FlowCanvas::Module(canvas, node->path().name())
, _node(node)
, _gui_widget(NULL)
, _gui_container(NULL)
, _gui_item(NULL)
, _gui_window(NULL)
, _last_gui_request_width(0)
, _last_gui_request_height(0)
{
assert(_node);
node->signal_new_port.connect(sigc::bind(sigc::mem_fun(this, &NodeModule::add_port), true));
node->signal_removed_port.connect(sigc::mem_fun(this, &NodeModule::remove_port));
node->signal_variable.connect(sigc::mem_fun(this, &NodeModule::set_variable));
node->signal_polyphonic.connect(sigc::mem_fun(this, &NodeModule::set_stacked_border));
node->signal_renamed.connect(sigc::mem_fun(this, &NodeModule::rename));
set_stacked_border(node->polyphonic());
}
NodeModule::~NodeModule()
{
NodeControlWindow* win = App::instance().window_factory()->control_window(_node);
if (win) {
// Should remove from window factory via signal
delete win;
}
}
void
NodeModule::create_menu()
{
Glib::RefPtr<Gnome::Glade::Xml> xml = GladeFactory::new_glade_reference();
xml->get_widget_derived("object_menu", _menu);
_menu->init(_node);
_menu->signal_embed_gui.connect(sigc::mem_fun(this, &NodeModule::embed_gui));
_menu->signal_popup_gui.connect(sigc::hide_return(sigc::mem_fun(this, &NodeModule::popup_gui)));
set_menu(_menu);
}
boost::shared_ptr<NodeModule>
NodeModule::create(boost::shared_ptr<PatchCanvas> canvas, SharedPtr<NodeModel> node)
{
boost::shared_ptr<NodeModule> ret;
SharedPtr<PatchModel> patch = PtrCast<PatchModel>(node);
if (patch)
ret = boost::shared_ptr<NodeModule>(new SubpatchModule(canvas, patch));
else
ret = boost::shared_ptr<NodeModule>(new NodeModule(canvas, node));
for (GraphObject::Variables::const_iterator m = node->variables().begin(); m != node->variables().end(); ++m)
ret->set_variable(m->first, m->second);
for (PortModelList::const_iterator p = node->ports().begin(); p != node->ports().end(); ++p) {
ret->add_port(*p, false);
}
ret->resize();
return ret;
}
void
NodeModule::value_changed(uint32_t index, const Atom& value)
{
float control = value.get_float();
if (_plugin_ui) {
SLV2UIInstance inst = _plugin_ui->instance();
const LV2UI_Descriptor* ui_descriptor = slv2_ui_instance_get_descriptor(inst);
LV2UI_Handle ui_handle = slv2_ui_instance_get_handle(inst);
if (ui_descriptor->port_event)
ui_descriptor->port_event(ui_handle, index, 4, 0, &control);
}
}
void
NodeModule::embed_gui(bool embed)
{
if (embed) {
if (_gui_window) {
cerr << "LV2 GUI already popped up, cannot embed" << endl;
return;
}
GtkWidget* c_widget = NULL;
if (!_gui_item) {
const PluginModel* const plugin = dynamic_cast<const PluginModel*>(_node->plugin());
assert(plugin);
_plugin_ui = plugin->ui(App::instance().world(), _node);
if (_plugin_ui) {
c_widget = (GtkWidget*)slv2_ui_instance_get_widget(_plugin_ui->instance());
_gui_widget = Glib::wrap(c_widget);
assert(_gui_widget);
if (_gui_container)
delete _gui_container;
_gui_container = manage(new Gtk::EventBox());
_gui_container->set_name("ingen_embedded_node_gui_container");
_gui_container->set_border_width(2);
_gui_container->add(*_gui_widget);
_gui_container->show_all();
const double y = 4 + _canvas_title.property_text_height();
_gui_item = new Gnome::Canvas::Widget(*this, 2.0, y, *_gui_container);
}
}
if (_gui_item) {
assert(_gui_widget);
_gui_widget->show_all();
_gui_item->show();
Gtk::Requisition r = _gui_container->size_request();
gui_size_request(&r, true);
_gui_item->raise_to_top();
_gui_container->signal_size_request().connect(sigc::bind(
sigc::mem_fun(this, &NodeModule::gui_size_request), false));
for (PortModelList::const_iterator p = _node->ports().begin(); p != _node->ports().end(); ++p)
if ((*p)->type().is_control() && (*p)->is_output())
App::instance().engine()->enable_port_broadcasting((*p)->path());
} else {
cerr << "ERROR: Failed to create canvas item for LV2 UI" << endl;
}
} else { // un-embed
if (_gui_item) {
delete _gui_item;
_gui_item = NULL;
_gui_container = NULL; // managed
_gui_widget = NULL; // managed
_plugin_ui.reset();
}
_ports_y_offset = 0;
_minimum_width = 0; // resize() takes care of it..
for (PortModelList::const_iterator p = _node->ports().begin(); p != _node->ports().end(); ++p)
if ((*p)->type().is_control() && (*p)->is_output())
App::instance().engine()->disable_port_broadcasting((*p)->path());
}
if (embed && _gui_item) {
initialise_gui_values();
set_base_color(0x212222FF);
} else {
set_default_base_color();
}
resize();
}
void
NodeModule::gui_size_request(Gtk::Requisition* r, bool force)
{
if (!force && _last_gui_request_width == r->width && _last_gui_request_height == r->height)
return;
if (r->width + 4 > _width)
set_minimum_width(r->width + 4);
_ports_y_offset = r->height + 2;
resize();
Gtk::Allocation allocation;
allocation.set_width(r->width + 4);
allocation.set_height(r->height + 4);
_gui_container->size_allocate(allocation);
_gui_item->property_width() = _width - 4;
_gui_item->property_height() = r->height;
_last_gui_request_width = r->width;
_last_gui_request_height = r->height;
}
void
NodeModule::rename()
{
set_name(_node->path().name());
resize();
}
void
NodeModule::add_port(SharedPtr<PortModel> port, bool resize_to_fit)
{
uint32_t index = _ports.size(); // FIXME: kludge, engine needs to tell us this
Module::add_port(boost::shared_ptr<Port>(
new Port(PtrCast<NodeModule>(shared_from_this()), port)));
port->signal_value_changed.connect(sigc::bind<0>(
sigc::mem_fun(this, &NodeModule::value_changed), index));
if (resize_to_fit)
resize();
}
void
NodeModule::remove_port(SharedPtr<PortModel> port)
{
SharedPtr<FlowCanvas::Port> p = Module::remove_port(port->path().name());
p.reset();
}
bool
NodeModule::popup_gui()
{
#ifdef HAVE_SLV2
if (_node->plugin()->type() == PluginModel::LV2) {
if (_plugin_ui) {
cerr << "LV2 GUI already embedded, cannot pop up" << endl;
return false;
}
const PluginModel* const plugin = dynamic_cast<const PluginModel*>(_node->plugin());
assert(plugin);
_plugin_ui = plugin->ui(App::instance().world(), _node);
if (_plugin_ui) {
GtkWidget* c_widget = (GtkWidget*)slv2_ui_instance_get_widget(_plugin_ui->instance());
_gui_widget = Glib::wrap(c_widget);
_gui_window = new Gtk::Window();
_gui_window->add(*_gui_widget);
_gui_widget->show_all();
initialise_gui_values();
_gui_window->signal_unmap().connect(
sigc::mem_fun(this, &NodeModule::on_gui_window_close));
_gui_window->present();
return true;
} else {
cerr << "No LV2 GUI" << endl;
}
}
#endif
return false;
}
void
NodeModule::on_gui_window_close()
{
delete _gui_window;
_gui_window = NULL;
_plugin_ui.reset();
_gui_widget = NULL;
}
void
NodeModule::initialise_gui_values()
{
uint32_t index=0;
for (PortModelList::const_iterator p = _node->ports().begin(); p != _node->ports().end(); ++p) {
if ((*p)->type().is_control())
value_changed(index, (*p)->value());
++index;
}
}
void
NodeModule::show_control_window()
{
App::instance().window_factory()->present_controls(_node);
}
void
NodeModule::on_double_click(GdkEventButton* ev)
{
if ( ! popup_gui() )
show_control_window();
}
void
NodeModule::store_location()
{
const float x = static_cast<float>(property_x());
const float y = static_cast<float>(property_y());
const Atom& existing_x = _node->get_variable("ingenuity:canvas-x");
const Atom& existing_y = _node->get_variable("ingenuity:canvas-y");
if (existing_x.type() != Atom::FLOAT || existing_y.type() != Atom::FLOAT
|| existing_x.get_float() != x || existing_y.get_float() != y) {
App::instance().engine()->set_variable(_node->path(), "ingenuity:canvas-x", Atom(x));
App::instance().engine()->set_variable(_node->path(), "ingenuity:canvas-y", Atom(y));
}
}
void
NodeModule::set_variable(const string& key, const Atom& value)
{
if (key == "ingenuity:canvas-x" && value.type() == Atom::FLOAT)
move_to(value.get_float(), property_y());
else if (key == "ingenuity:canvas-y" && value.type() == Atom::FLOAT)
move_to(property_x(), value.get_float());
}
} // namespace GUI
} // namespace Ingen
<|endoftext|>
|
<commit_before>#pragma once
#include "types.hh"
#include "hash.hh"
#include "store-api.hh"
#include <map>
#include <variant>
namespace nix {
/* Abstract syntax of derivations. */
struct DerivationOutput
{
StorePath path;
std::string hashAlgo; /* hash used for expected hash computation */
std::string hash; /* expected hash, may be null */
DerivationOutput(StorePath && path, std::string && hashAlgo, std::string && hash)
: path(std::move(path))
, hashAlgo(std::move(hashAlgo))
, hash(std::move(hash))
{ }
void parseHashInfo(bool & recursive, Hash & hash) const;
};
typedef std::map<string, DerivationOutput> DerivationOutputs;
/* For inputs that are sub-derivations, we specify exactly which
output IDs we are interested in. */
typedef std::map<StorePath, StringSet> DerivationInputs;
typedef std::map<string, string> StringPairs;
struct BasicDerivation
{
DerivationOutputs outputs; /* keyed on symbolic IDs */
StorePathSet inputSrcs; /* inputs that are sources */
string platform;
Path builder;
Strings args;
StringPairs env;
BasicDerivation() { }
explicit BasicDerivation(const BasicDerivation & other);
virtual ~BasicDerivation() { };
/* Return the path corresponding to the output identifier `id' in
the given derivation. */
const StorePath & findOutput(const std::string & id) const;
bool isBuiltin() const;
/* Return true iff this is a fixed-output derivation. */
bool isFixedOutput() const;
/* Return the output paths of a derivation. */
StorePathSet outputPaths() const;
};
struct Derivation : BasicDerivation
{
DerivationInputs inputDrvs; /* inputs that are sub-derivations */
/* Print a derivation. */
std::string unparse(const Store & store, bool maskOutputs,
std::map<std::string, StringSet> * actualInputs = nullptr) const;
Derivation() { }
Derivation(Derivation && other) = default;
explicit Derivation(const Derivation & other);
};
class Store;
/* Write a derivation to the Nix store, and return its path. */
StorePath writeDerivation(ref<Store> store,
const Derivation & drv, const string & name, RepairFlag repair = NoRepair);
/* Read a derivation from a file. */
Derivation readDerivation(const Store & store, const Path & drvPath);
// FIXME: remove
bool isDerivation(const string & fileName);
typedef std::variant<
Hash, // regular DRV normalized hash
std::map<std::string, Hash> // known CA drv's output hashes
> DrvHashModulo;
/* Returns hashes with the details of fixed-output subderivations
expunged.
A fixed-output derivation is a derivation whose outputs have a
specified content hash and hash algorithm. (Currently they must have
exactly one output (`out'), which is specified using the `outputHash'
and `outputHashAlgo' attributes, but the algorithm doesn't assume
this.) We don't want changes to such derivations to propagate upwards
through the dependency graph, changing output paths everywhere.
For instance, if we change the url in a call to the `fetchurl'
function, we do not want to rebuild everything depending on it---after
all, (the hash of) the file being downloaded is unchanged. So the
*output paths* should not change. On the other hand, the *derivation
paths* should change to reflect the new dependency graph.
For fixed output derivations, this returns a map from the names of
each output to hashes unique up to the outputs' contents.
For regular derivations, it returns a single hash of the derivation
ATerm, after subderivations have been likewise expunged from that
derivation.
*/
DrvHashModulo hashDerivationModulo(Store & store, const Derivation & drv, bool maskOutputs);
/* Memoisation of hashDerivationModulo(). */
typedef std::map<StorePath, DrvHashModulo> DrvHashes;
extern DrvHashes drvHashes; // FIXME: global, not thread-safe
bool wantOutput(const string & output, const std::set<string> & wanted);
struct Source;
struct Sink;
Source & readDerivation(Source & in, const Store & store, BasicDerivation & drv);
void writeDerivation(Sink & out, const Store & store, const BasicDerivation & drv);
std::string hashPlaceholder(const std::string & outputName);
}
<commit_msg>Apply suggestions from code review<commit_after>#pragma once
#include "types.hh"
#include "hash.hh"
#include "store-api.hh"
#include <map>
#include <variant>
namespace nix {
/* Abstract syntax of derivations. */
struct DerivationOutput
{
StorePath path;
std::string hashAlgo; /* hash used for expected hash computation */
std::string hash; /* expected hash, may be null */
DerivationOutput(StorePath && path, std::string && hashAlgo, std::string && hash)
: path(std::move(path))
, hashAlgo(std::move(hashAlgo))
, hash(std::move(hash))
{ }
void parseHashInfo(bool & recursive, Hash & hash) const;
};
typedef std::map<string, DerivationOutput> DerivationOutputs;
/* For inputs that are sub-derivations, we specify exactly which
output IDs we are interested in. */
typedef std::map<StorePath, StringSet> DerivationInputs;
typedef std::map<string, string> StringPairs;
struct BasicDerivation
{
DerivationOutputs outputs; /* keyed on symbolic IDs */
StorePathSet inputSrcs; /* inputs that are sources */
string platform;
Path builder;
Strings args;
StringPairs env;
BasicDerivation() { }
explicit BasicDerivation(const BasicDerivation & other);
virtual ~BasicDerivation() { };
/* Return the path corresponding to the output identifier `id' in
the given derivation. */
const StorePath & findOutput(const std::string & id) const;
bool isBuiltin() const;
/* Return true iff this is a fixed-output derivation. */
bool isFixedOutput() const;
/* Return the output paths of a derivation. */
StorePathSet outputPaths() const;
};
struct Derivation : BasicDerivation
{
DerivationInputs inputDrvs; /* inputs that are sub-derivations */
/* Print a derivation. */
std::string unparse(const Store & store, bool maskOutputs,
std::map<std::string, StringSet> * actualInputs = nullptr) const;
Derivation() { }
Derivation(Derivation && other) = default;
explicit Derivation(const Derivation & other);
};
class Store;
/* Write a derivation to the Nix store, and return its path. */
StorePath writeDerivation(ref<Store> store,
const Derivation & drv, const string & name, RepairFlag repair = NoRepair);
/* Read a derivation from a file. */
Derivation readDerivation(const Store & store, const Path & drvPath);
// FIXME: remove
bool isDerivation(const string & fileName);
typedef std::variant<
Hash, // regular DRV normalized hash
std::map<std::string, Hash> // known CA drv's output hashes
> DrvHashModulo;
/* Returns hashes with the details of fixed-output subderivations
expunged.
A fixed-output derivation is a derivation whose outputs have a
specified content hash and hash algorithm. (Currently they must have
exactly one output (`out'), which is specified using the `outputHash'
and `outputHashAlgo' attributes, but the algorithm doesn't assume
this.) We don't want changes to such derivations to propagate upwards
through the dependency graph, changing output paths everywhere.
For instance, if we change the url in a call to the `fetchurl'
function, we do not want to rebuild everything depending on it---after
all, (the hash of) the file being downloaded is unchanged. So the
*output paths* should not change. On the other hand, the *derivation
paths* should change to reflect the new dependency graph.
For fixed-output derivations, this returns a map from the name of
each output to its hash, unique up to the output's contents.
For regular derivations, it returns a single hash of the derivation
ATerm, after subderivations have been likewise expunged from that
derivation.
*/
DrvHashModulo hashDerivationModulo(Store & store, const Derivation & drv, bool maskOutputs);
/* Memoisation of hashDerivationModulo(). */
typedef std::map<StorePath, DrvHashModulo> DrvHashes;
extern DrvHashes drvHashes; // FIXME: global, not thread-safe
bool wantOutput(const string & output, const std::set<string> & wanted);
struct Source;
struct Sink;
Source & readDerivation(Source & in, const Store & store, BasicDerivation & drv);
void writeDerivation(Sink & out, const Store & store, const BasicDerivation & drv);
std::string hashPlaceholder(const std::string & outputName);
}
<|endoftext|>
|
<commit_before>#pragma once
#include "evaluation.hpp"
#include "mapping.hpp"
#include <string>
namespace vakkenranking
{
class printer
{
void operator=(printer&) = delete;
printer() = delete;
static std::string round(double x, size_t digits)
{
double multiplier = std::pow(10, digits);
std::stringstream str;
str << std::round(x * multiplier) / multiplier;
size_t find = str.str().find('.');
if(find == std::string::npos)
{
find = str.str().size();
str << '.';
}
int current_digits = str.str().size() - find - 1;
int todo_digits = (int)digits - current_digits;
if(todo_digits > 0)
for(int i = 0; i < todo_digits; i++)
str << '0';
return str.str();
}
public:
static void print_csv(const std::vector<evaluation>& old_data, const std::vector<evaluation>& new_data)
{
const auto mapping_f = mapping::create_mapping_f(old_data);
const std::string sep = ",";
for(const auto& e : new_data)
{
const auto e_old = mapping_f(e.code);
std::cout << '"' << e.code << '"' << sep
<< '"' << round(e.course_grade.avg(), 1) << '"' << sep
<< '"' << round(e.course_grade.stdev(), 1) << '"' << sep
<< '"' << e.course_grade.count() << '"' << sep
<< '"' << round(e.teacher_grade.avg(), 1) << '"' << sep
<< '"' << round(e.teacher_grade.stdev(), 1) << '"' << sep
<< '"' << e.teacher_grade.count() << '"' << sep;
if(e_old.to)
std::cout
<< '"' << round(e_old.to.get().course_grade.avg(), 1) << '"' << sep
<< '"' << round(e_old.to.get().course_grade.stdev(), 1) << '"' << sep
<< '"' << e_old.to.get().course_grade.count() << '"'
<< std::endl;
else
std::cout
<< '"' << '"' << sep
<< '"' << '"' << sep
<< '"' << '"'
<< std::endl;
}
}
static void print(const std::vector<evaluation>& old_data, const std::vector<evaluation>& new_data)
{
const static size_t slice_count = 3;
std::vector<std::vector<evaluation>> slices(slice_count);
const size_t slice_size = ceil((double)new_data.size() / (double)slice_count);
for(size_t i = 0; i < slice_count; ++i)
for(size_t j = i * slice_size; j < (i+1) * slice_size && j < new_data.size(); ++j)
slices[i].push_back(new_data[j]);
const auto mapping_f = mapping::create_mapping_f(old_data);
size_t n = 0;
std::cout << "<!DOCTYPE html><html>\n<head>\n"
<< "\t<meta charset=\"UTF-8\" />\n"
<< "\t<title>OLC III - Vakkenranking najaar 2013-2014</title>\n"
<< "\t<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"http://olciii.nl/wp-content/themes/twentyeleven/style.css\">\n"
<< "\t<style>\n"
<< "\t\t.entry-content {\n"
<< "\t\t\tpadding: 0;\n"
<< "\t\t}\n"
<< "\n"
<< "\t\t.entry-content table, .comment-content table {\n"
<< "\t\t\tborder-bottom: none;\n"
<< "\t\t}\n"
<< "\n"
<< "\t\t.entry-content td, .comment-content td {\n"
<< "\t\t\tpadding: 7px 6px 7px 0;\n"
<< "\t\t}\n"
<< "\n"
<< "\t\t.vakkenranking-bottom-border td {\n"
<< "\t\t\tborder-bottom: 1px solid #DDD;\n"
<< "\t\t}\n"
<< "\n"
<< "\t\tbody {\n"
<< "\t\t\tbackground: none;\n"
<< "\t\t\tfont: 13px \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n"
<< "\t\t}\n"
<< "\t</style>\n"
<< "</head>\n"
<< "<body>\n"
<< "<header class=\"entry-header\">\n"
<< "\t<h1 class=\"entry-title\">Vakkenranking Informatica najaar 2013-2014</h1>\n"
<< "\t<h2>Opleidingscommissie Informatica & Informatiekunde 2013-2014</h2>\n"
<< "</header>\n"
<< "<br />\n"
<< "<div class=\"entry-content\" role=\"main\">\n";
for(size_t i = 0; i < slices.size(); ++i)
{
const auto& slice = slices[i];
if(i == 0)
{
std::cout << "<table style=\"width: 33%; float: left\">\n";
std::cout << "<tr>\n"
<< "\t<td style=\"text-align: center\"><strong>#</strong></td>\n"
<< "\t<td><strong>Vak (vakcode)</strong></td>\n"
<< "\t<td><strong>x</strong></td>\n"
<< "\t<td><strong>n</strong></td>\n"
<< "\t<td><strong>σ</strong></td>\n"
<< "\t<td><strong>x<sub>oud</sub></strong></td>\n"
<< "\t<td> </td>\n"
<< "</tr>\n";
}
else
{
std::cout << "<table style=\"padding-left: 2%; width: 33%; float: left\">\n";
std::cout << "<tr>\n"
<< "\t<td style=\"text-align: center\"><strong>#</strong></td>\n"
<< "\t<td><strong>Vak (vakcode)</strong></td>\n"
<< "\t<td><strong>x</strong></td>\n"
<< "\t<td><strong>n</strong></td>\n"
<< "\t<td><strong>σ</strong></td>\n"
<< "\t<td><strong>x<sub>oud</sub></strong></td>\n"
<< "\t<td> </td>\n"
<< "</tr>\n";
}
for(size_t j = 0; j < slice.size(); ++j)
{
const evaluation& e = slice[j];
const auto e_old = mapping_f(e.code);
const double avg = e.course_grade.avg();
if(j == slice.size() - 1) //Last element in slice
std::cout << "<tr class=\"vakkenranking-bottom-border\">\n";
else
std::cout << "<tr>\n";
std::cout << "\t<td style=\"text-align: center\">" << n << "</td>\n"
<< "\t<td>" << e.name << " (" << e.code << ")</td>\n"
<< "\t<td>" << round(avg, 1) << "</td>\n"
<< "\t<td>" << e.course_grade.count() << "</td>\n"
<< "\t<td>" << round(e.course_grade.stdev(), 1) << "</td>\n";
if(e_old.to)
{
const static size_t threshold = 5;
const static double max_diff = 1.0;
const static double sig_diff = 0.4;
const double old_avg = e_old.to.get().course_grade.avg();
const double diff = avg - old_avg;
std::cout
<< "\t<td>" << round(old_avg, 1) << "</td>\n"
<< "\t<td style=\"text-align: center\">"
<< "<div style=\"color: ";
if(e.course_grade.count() <= threshold || e_old.to.get().course_grade.count() <= threshold)
std::cout << "lightgray";
else if(diff >= max_diff)
std::cout << "green";
else if(diff >= sig_diff)
std::cout << "green";
else if(diff <= -max_diff)
std::cout << "red";
else if(diff <= sig_diff)
std::cout << "red";
std::cout << "\">";
if(diff >= max_diff)
std::cout << "▲▲";
else if(diff >= sig_diff)
std::cout << "▲";
else if(diff <= -max_diff)
std::cout << "▼▼";
else if(diff <= -sig_diff)
std::cout << "▼";
std::cout << "</div>";
}
else
{
std::cout << "\t<td> </td>\n";
std::cout << "\t<td style=\"text-align: center\">";
if(e_old.mapping_type == mapping::type_e::unfound)
std::cout << "<span style=\"font-size: 10px\">?</span>";
else if(e_old.mapping_type == mapping::type_e::added)
std::cout << "<span style=\"font-size: 10px\">!</span>";
else
std::cout << "<span style=\"font-size: 10px\">666</span>";
std::cout << "</td>\n";
}
std::cout << "</tr>\n";
n++;
}
std::cout << "</table>\n" << std::endl;
}
std::cout << "<div style=\"clear: both; font-size: 0;\"> </div>\n"
<< "<p>▲ = 0.4 ≤ δ ≤ 1.0; ▲▲ = δ > 1.0<br />\n"
<< "<span style=\"color: lightgray\">▼ grijs</span> = niet significant aantal deelnemers<br />\n"
<< "<span style=\"color: red\">▼ kleur</span> = significant aantal deelnemers<br />\n"
<< "! = cursus nieuw in 2013-2014<br />\n"
<< "? = geen enquêteresultaten uit 2012-2013</p>\n"
<< "</body></html>";
}
};
}
<commit_msg>printer: updated for 2013-2014 poster<commit_after>#pragma once
#include "evaluation.hpp"
#include "mapping.hpp"
#include <string>
namespace vakkenranking
{
class printer
{
void operator=(printer&) = delete;
printer() = delete;
static std::string round(double x, size_t digits)
{
double multiplier = std::pow(10, digits);
std::stringstream str;
str << std::round(x * multiplier) / multiplier;
size_t find = str.str().find('.');
if(find == std::string::npos)
{
find = str.str().size();
str << '.';
}
int current_digits = str.str().size() - find - 1;
int todo_digits = (int)digits - current_digits;
if(todo_digits > 0)
for(int i = 0; i < todo_digits; i++)
str << '0';
return str.str();
}
public:
static void print_csv(const std::vector<evaluation>& old_data, const std::vector<evaluation>& new_data)
{
const auto mapping_f = mapping::create_mapping_f(old_data);
const std::string sep = ",";
for(const auto& e : new_data)
{
const auto e_old = mapping_f(e.code);
std::cout << '"' << e.code << '"' << sep
<< '"' << round(e.course_grade.avg(), 1) << '"' << sep
<< '"' << round(e.course_grade.stdev(), 1) << '"' << sep
<< '"' << e.course_grade.count() << '"' << sep
<< '"' << round(e.teacher_grade.avg(), 1) << '"' << sep
<< '"' << round(e.teacher_grade.stdev(), 1) << '"' << sep
<< '"' << e.teacher_grade.count() << '"' << sep;
if(e_old.to)
std::cout
<< '"' << round(e_old.to.get().course_grade.avg(), 1) << '"' << sep
<< '"' << round(e_old.to.get().course_grade.stdev(), 1) << '"' << sep
<< '"' << e_old.to.get().course_grade.count() << '"'
<< std::endl;
else
std::cout
<< '"' << '"' << sep
<< '"' << '"' << sep
<< '"' << '"'
<< std::endl;
}
}
static void print(const std::vector<evaluation>& old_data, const std::vector<evaluation>& new_data)
{
const static size_t slice_count = 3;
std::vector<std::vector<evaluation>> slices(slice_count);
const size_t slice_size = ceil((double)new_data.size() / (double)slice_count);
for(size_t i = 0; i < slice_count; ++i)
for(size_t j = i * slice_size; j < (i+1) * slice_size && j < new_data.size(); ++j)
slices[i].push_back(new_data[j]);
const auto mapping_f = mapping::create_mapping_f(old_data);
size_t n = 0;
std::cout << "<!DOCTYPE html><html>\n<head>\n"
<< "\t<meta charset=\"UTF-8\" />\n"
<< "\t<title>OLC III - Vakkenranking 2013-2014</title>\n"
<< "\t<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"http://olciii.nl/wp-content/themes/twentyeleven/style.css\">\n"
<< "\t<style>\n"
<< "\t\t.entry-content {\n"
<< "\t\t\tpadding: 0;\n"
<< "\t\t}\n"
<< "\n"
<< "\t\t.entry-content table, .comment-content table {\n"
<< "\t\t\tborder-bottom: none;\n"
<< "\t\t}\n"
<< "\n"
<< "\t\t.entry-content td, .comment-content td {\n"
<< "\t\t\tpadding: 7px 6px 7px 0;\n"
<< "\t\t}\n"
<< "\n"
<< "\t\t.vakkenranking-bottom-border td {\n"
<< "\t\t\tborder-bottom: 1px solid #DDD;\n"
<< "\t\t}\n"
<< "\n"
<< "\t\tbody {\n"
<< "\t\t\tbackground: none;\n"
<< "\t\t\tfont: 13px \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n"
<< "\t\t}\n"
<< "\t\ttable.legend {\n"
<< "\t\t\twidth: 30%;\n"
<< "\t\t}\n"
<< "\t\ttable.legend td {\n"
<< "\t\t\tborder: none;\n"
<< "\t\t\tpadding: 3px 2px 3px 0px;\n"
<< "\t\t}\n"
<< "\t\ttd.legend-left {\n"
<< "\t\t\ttext-align: center;\n"
<< "\t\t}\n"
<< "\t</style>\n"
<< "</head>\n"
<< "<body>\n"
<< "<header class=\"entry-header\">\n"
<< "\t<h1 class=\"entry-title\">Vakkenranking Informatica 2013-2014</h1>\n"
<< "\t<h2>door Wouter Geraedts <radboud@woutergeraedts.nl></h2>\n"
<< "</header>\n"
<< "<br />\n"
<< "<div class=\"entry-content\" role=\"main\">\n";
for(size_t i = 0; i < slices.size(); ++i)
{
const auto& slice = slices[i];
if(i == 0)
{
std::cout << "<table style=\"width: 33%; float: left\">\n";
std::cout << "<tr>\n"
<< "\t<td style=\"text-align: center\"><strong>#</strong></td>\n"
<< "\t<td><strong>Code</strong></td>\n"
<< "\t<td><strong>Naam</strong></td>\n"
<< "\t<td><strong>x</strong></td>\n"
<< "\t<td><strong>n</strong></td>\n"
<< "\t<td><strong>σ</strong></td>\n"
<< "\t<td><strong>x<sub>oud</sub></strong></td>\n"
<< "\t<td> </td>\n"
<< "</tr>\n";
}
else
{
std::cout << "<table style=\"padding-left: 2%; width: 33%; float: left\">\n";
std::cout << "<tr>\n"
<< "\t<td style=\"text-align: center\"><strong>#</strong></td>\n"
<< "\t<td><strong>Code</strong></td>\n"
<< "\t<td><strong>Naam</strong></td>\n"
<< "\t<td><strong>x</strong></td>\n"
<< "\t<td><strong>n</strong></td>\n"
<< "\t<td><strong>σ</strong></td>\n"
<< "\t<td><strong>x<sub>oud</sub></strong></td>\n"
<< "\t<td> </td>\n"
<< "</tr>\n";
}
for(size_t j = 0; j < slice.size(); ++j)
{
const evaluation& e = slice[j];
const auto e_old = mapping_f(e.code);
const double avg = e.course_grade.avg();
if(j == slice.size() - 1) //Last element in slice
std::cout << "<tr class=\"vakkenranking-bottom-border\">\n";
else
std::cout << "<tr>\n";
std::cout << "\t<td style=\"text-align: center\">" << n << "</td>\n"
<< "\t<td>" << e.code << "</td>\n"
<< "\t<td>" << e.name << "</td>\n"
<< "\t<td>" << round(avg, 1) << "</td>\n"
<< "\t<td>" << e.course_grade.count() << "</td>\n"
<< "\t<td>" << round(e.course_grade.stdev(), 1) << "</td>\n";
if(e_old.to)
{
const static size_t threshold = 5;
const static double max_diff = 1.0;
const static double sig_diff = 0.4;
const double old_avg = e_old.to.get().course_grade.avg();
const double diff = avg - old_avg;
std::cout
<< "\t<td>" << round(old_avg, 1) << "</td>\n"
<< "\t<td style=\"text-align: center\">"
<< "<div style=\"color: ";
if(e.course_grade.count() <= threshold || e_old.to.get().course_grade.count() <= threshold)
std::cout << "#BBB";
else if(diff >= max_diff)
std::cout << "green";
else if(diff >= sig_diff)
std::cout << "green";
else if(diff <= -max_diff)
std::cout << "red";
else if(diff <= sig_diff)
std::cout << "red";
std::cout << "\">";
if(diff >= max_diff)
std::cout << "▲▲";
else if(diff >= sig_diff)
std::cout << "▲";
else if(diff <= -max_diff)
std::cout << "▼▼";
else if(diff <= -sig_diff)
std::cout << "▼";
std::cout << "</div>";
}
else
{
std::cout << "\t<td> </td>\n";
std::cout << "\t<td style=\"text-align: center\">";
if(e_old.mapping_type == mapping::type_e::unfound)
std::cout << "<span style=\"font-size: 10px\">?</span>";
else if(e_old.mapping_type == mapping::type_e::added)
std::cout << "<span style=\"font-size: 10px\">!</span>";
else
std::cout << "<span style=\"font-size: 10px\">666</span>";
std::cout << "</td>\n";
}
std::cout << "</tr>\n";
n++;
}
std::cout << "</table>\n" << std::endl;
}
std::cout << "<div style=\"clear: both; font-size: 0;\"> </div>\n"
<< "<table class=\"legend\">\n"
<< "<tr><td class=\"legend-left\">▲</td><td>→</td><td>0.4 ≤ δ ≤ 1.0</td></tr>\n"
<< "<tr><td class=\"legend-left\">▲▲</td><td>→</td><td>δ > 1.0</td></tr>\n"
<< "<tr><td class=\"legend-left\"><span style=\"color: #BBB\">▼ grijs</span></td><td>→</td><td>niet significant aantal deelnemers</td></tr>\n"
<< "<tr><td class=\"legend-left\"><span style=\"color: red\">▼ kleur</span></td><td>→</td><td>significant aantal deelnemers</td></tr>\n"
<< "<tr><td class=\"legend-left\">!</td><td>→</td><td>cursus nieuw in 2013-2014</td></tr>\n"
<< "<tr><td class=\"legend-left\">?</td><td>→</td><td>geen enquêteresultaten uit 2012-2013</td></tr>\n"
<< "</body></html>";
}
};
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012-2017 Daniele Bartolini and individual contributors.
* License: https://github.com/taylor001/crown/blob/master/LICENSE
*/
#include "config.h"
#include "device.h"
#include "error.h"
#include "log.h"
#include "lua_environment.h"
#include "lua_resource.h"
#include "lua_stack.h"
#include "resource_manager.h"
#include <stdarg.h>
namespace { const crown::log_internal::System LUA = { "Lua" }; }
namespace crown
{
extern void load_api(LuaEnvironment& env);
// When an error occurs, logs the error message and pauses the engine.
static int error_handler(lua_State* L)
{
lua_getfield(L, LUA_GLOBALSINDEX, "debug");
if (!lua_istable(L, -1))
{
lua_pop(L, 1);
return 0;
}
lua_getfield(L, -1, "traceback");
if (!lua_isfunction(L, -1))
{
lua_pop(L, 2);
return 0;
}
lua_pushvalue(L, 1); // Pass error message
lua_pushinteger(L, 2);
lua_call(L, 2, 1); // Call debug.traceback
loge(LUA, lua_tostring(L, -1)); // Print error message
lua_pop(L, 1); // Remove error message from stack
lua_pop(L, 1); // Remove debug.traceback from stack
device()->pause();
return 0;
}
// Redirects require to the resource manager.
static int require(lua_State* L)
{
LuaStack stack(L);
const LuaResource* lr = (LuaResource*)device()->_resource_manager->get(RESOURCE_TYPE_SCRIPT, stack.get_resource_id(1));
luaL_loadbuffer(L, lua_resource::program(lr), lr->size, "");
return 1;
}
LuaEnvironment::LuaEnvironment()
: L(NULL)
, _vec3_used(0)
, _quat_used(0)
, _mat4_used(0)
{
L = luaL_newstate();
CE_ASSERT(L, "Unable to create lua state");
}
LuaEnvironment::~LuaEnvironment()
{
lua_close(L);
}
void LuaEnvironment::load_libs()
{
lua_gc(L, LUA_GCSTOP, 0);
// Open default libraries
luaL_openlibs(L);
// Register crown libraries
load_api(*this);
// Register custom loader
lua_getfield(L, LUA_GLOBALSINDEX, "package");
lua_getfield(L, -1, "loaders");
lua_remove(L, -2);
int num_loaders = 0;
lua_pushnil(L);
while (lua_next(L, -2) != 0)
{
lua_pop(L, 1);
num_loaders++;
}
lua_pushinteger(L, num_loaders + 1);
lua_pushcfunction(L, require);
lua_rawset(L, -3);
lua_pop(L, 1);
// Create metatable for lightuserdata
lua_pushlightuserdata(L, 0);
lua_getfield(L, LUA_REGISTRYINDEX, "Lightuserdata_mt");
lua_setmetatable(L, -2);
lua_pop(L, 1);
// Ensure stack is clean
CE_ASSERT(lua_gettop(L) == 0, "Stack not clean");
lua_gc(L, LUA_GCRESTART, 0);
}
LuaStack LuaEnvironment::execute(const LuaResource* lr)
{
LuaStack stack(L);
lua_pushcfunction(L, error_handler);
luaL_loadbuffer(L, lua_resource::program(lr), lr->size, "<unknown>");
lua_pcall(L, 0, 1, -2);
lua_pop(L, 1);
return stack;
}
LuaStack LuaEnvironment::execute_string(const char* s)
{
LuaStack stack(L);
lua_pushcfunction(L, error_handler);
luaL_loadstring(L, s);
lua_pcall(L, 0, 0, -2);
lua_pop(L, 1);
return stack;
}
void LuaEnvironment::add_module_function(const char* module, const char* name, const lua_CFunction func)
{
luaL_Reg entry[2];
entry[0].name = name;
entry[0].func = func;
entry[1].name = NULL;
entry[1].func = NULL;
luaL_register(L, module, entry);
lua_pop(L, 1);
}
void LuaEnvironment::add_module_function(const char* module, const char* name, const char* func)
{
// Create module if it does not exist
luaL_Reg entry;
entry.name = NULL;
entry.func = NULL;
luaL_register(L, module, &entry);
lua_pop(L, 1);
lua_getglobal(L, module);
lua_getglobal(L, func);
lua_setfield(L, -2, name);
lua_setglobal(L, module);
}
void LuaEnvironment::set_module_constructor(const char* module, const lua_CFunction func)
{
// Create module if it does not exist
luaL_Reg entry;
entry.name = NULL;
entry.func = NULL;
luaL_register(L, module, &entry);
lua_pop(L, 1);
// Create dummy tables to be used as module's metatable
lua_createtable(L, 0, 1);
lua_pushstring(L, "__call");
lua_pushcfunction(L, func);
lua_settable(L, 1); // dummy.__call = func
lua_getglobal(L, module);
lua_pushvalue(L, -2); // Duplicate dummy metatable
lua_setmetatable(L, -2); // setmetatable(module, dummy)
lua_pop(L, -1);
}
void LuaEnvironment::call_global(const char* func, u8 argc, ...)
{
CE_ENSURE(NULL != func);
LuaStack stack(L);
va_list vl;
va_start(vl, argc);
lua_pushcfunction(L, error_handler);
lua_getglobal(L, func);
for (u8 i = 0; i < argc; i++)
{
const int type = va_arg(vl, int);
switch (type)
{
case ARGUMENT_FLOAT:
stack.push_float(va_arg(vl, f64));
break;
default:
CE_FATAL("Unknown argument type");
break;
}
}
va_end(vl);
lua_pcall(L, argc, 0, -argc - 2);
lua_pop(L, -1);
CE_ASSERT(lua_gettop(L) == 0, "Stack not clean");
}
LuaStack LuaEnvironment::get_global(const char* global)
{
LuaStack stack(L);
lua_getglobal(L, global);
return stack;
}
Vector3* LuaEnvironment::next_vector3(const Vector3& v)
{
CE_ASSERT(_vec3_used < CROWN_MAX_LUA_VECTOR3, "Maximum number of Vector3 reached");
return &(_vec3_buffer[_vec3_used++] = v);
}
Quaternion* LuaEnvironment::next_quaternion(const Quaternion& q)
{
CE_ASSERT(_quat_used < CROWN_MAX_LUA_QUATERNION, "Maximum number of Quaternion reached");
return &(_quat_buffer[_quat_used++] = q);
}
Matrix4x4* LuaEnvironment::next_matrix4x4(const Matrix4x4& m)
{
CE_ASSERT(_mat4_used < CROWN_MAX_LUA_MATRIX4X4, "Maximum number of Matrix4x4 reached");
return &(_mat4_buffer[_mat4_used++] = m);
}
bool LuaEnvironment::is_vector3(const Vector3* p) const
{
return p >= &_vec3_buffer[0]
&& p <= &_vec3_buffer[CROWN_MAX_LUA_VECTOR3 - 1];
}
bool LuaEnvironment::is_quaternion(const Quaternion* p) const
{
return p >= &_quat_buffer[0]
&& p <= &_quat_buffer[CROWN_MAX_LUA_QUATERNION - 1];
}
bool LuaEnvironment::is_matrix4x4(const Matrix4x4* p) const
{
return p >= &_mat4_buffer[0]
&& p <= &_mat4_buffer[CROWN_MAX_LUA_MATRIX4X4 - 1];
}
void LuaEnvironment::temp_count(u32& num_vec3, u32& num_quat, u32& num_mat4)
{
num_vec3 = _vec3_used;
num_quat = _quat_used;
num_mat4 = _mat4_used;
}
void LuaEnvironment::set_temp_count(u32 num_vec3, u32 num_quat, u32 num_mat4)
{
_vec3_used = num_vec3;
_quat_used = num_quat;
_mat4_used = num_mat4;
}
void LuaEnvironment::reset_temporaries()
{
_vec3_used = 0;
_quat_used = 0;
_mat4_used = 0;
}
} // namespace crown
<commit_msg>Revert "Create module if it does not exist"<commit_after>/*
* Copyright (c) 2012-2017 Daniele Bartolini and individual contributors.
* License: https://github.com/taylor001/crown/blob/master/LICENSE
*/
#include "config.h"
#include "device.h"
#include "error.h"
#include "log.h"
#include "lua_environment.h"
#include "lua_resource.h"
#include "lua_stack.h"
#include "resource_manager.h"
#include <stdarg.h>
namespace { const crown::log_internal::System LUA = { "Lua" }; }
namespace crown
{
extern void load_api(LuaEnvironment& env);
// When an error occurs, logs the error message and pauses the engine.
static int error_handler(lua_State* L)
{
lua_getfield(L, LUA_GLOBALSINDEX, "debug");
if (!lua_istable(L, -1))
{
lua_pop(L, 1);
return 0;
}
lua_getfield(L, -1, "traceback");
if (!lua_isfunction(L, -1))
{
lua_pop(L, 2);
return 0;
}
lua_pushvalue(L, 1); // Pass error message
lua_pushinteger(L, 2);
lua_call(L, 2, 1); // Call debug.traceback
loge(LUA, lua_tostring(L, -1)); // Print error message
lua_pop(L, 1); // Remove error message from stack
lua_pop(L, 1); // Remove debug.traceback from stack
device()->pause();
return 0;
}
// Redirects require to the resource manager.
static int require(lua_State* L)
{
LuaStack stack(L);
const LuaResource* lr = (LuaResource*)device()->_resource_manager->get(RESOURCE_TYPE_SCRIPT, stack.get_resource_id(1));
luaL_loadbuffer(L, lua_resource::program(lr), lr->size, "");
return 1;
}
LuaEnvironment::LuaEnvironment()
: L(NULL)
, _vec3_used(0)
, _quat_used(0)
, _mat4_used(0)
{
L = luaL_newstate();
CE_ASSERT(L, "Unable to create lua state");
}
LuaEnvironment::~LuaEnvironment()
{
lua_close(L);
}
void LuaEnvironment::load_libs()
{
lua_gc(L, LUA_GCSTOP, 0);
// Open default libraries
luaL_openlibs(L);
// Register crown libraries
load_api(*this);
// Register custom loader
lua_getfield(L, LUA_GLOBALSINDEX, "package");
lua_getfield(L, -1, "loaders");
lua_remove(L, -2);
int num_loaders = 0;
lua_pushnil(L);
while (lua_next(L, -2) != 0)
{
lua_pop(L, 1);
num_loaders++;
}
lua_pushinteger(L, num_loaders + 1);
lua_pushcfunction(L, require);
lua_rawset(L, -3);
lua_pop(L, 1);
// Create metatable for lightuserdata
lua_pushlightuserdata(L, 0);
lua_getfield(L, LUA_REGISTRYINDEX, "Lightuserdata_mt");
lua_setmetatable(L, -2);
lua_pop(L, 1);
// Ensure stack is clean
CE_ASSERT(lua_gettop(L) == 0, "Stack not clean");
lua_gc(L, LUA_GCRESTART, 0);
}
LuaStack LuaEnvironment::execute(const LuaResource* lr)
{
LuaStack stack(L);
lua_pushcfunction(L, error_handler);
luaL_loadbuffer(L, lua_resource::program(lr), lr->size, "<unknown>");
lua_pcall(L, 0, 1, -2);
lua_pop(L, 1);
return stack;
}
LuaStack LuaEnvironment::execute_string(const char* s)
{
LuaStack stack(L);
lua_pushcfunction(L, error_handler);
luaL_loadstring(L, s);
lua_pcall(L, 0, 0, -2);
lua_pop(L, 1);
return stack;
}
void LuaEnvironment::add_module_function(const char* module, const char* name, const lua_CFunction func)
{
luaL_newmetatable(L, module);
luaL_Reg entry[2];
entry[0].name = name;
entry[0].func = func;
entry[1].name = NULL;
entry[1].func = NULL;
luaL_register(L, NULL, entry);
lua_setglobal(L, module);
lua_pop(L, -1);
}
void LuaEnvironment::add_module_function(const char* module, const char* name, const char* func)
{
luaL_newmetatable(L, module);
lua_getglobal(L, func);
lua_setfield(L, -2, name);
lua_setglobal(L, module);
}
void LuaEnvironment::set_module_constructor(const char* module, const lua_CFunction func)
{
// Create dummy tables to be used as module's metatable
lua_createtable(L, 0, 1);
lua_pushstring(L, "__call");
lua_pushcfunction(L, func);
lua_settable(L, 1); // dummy.__call = func
lua_getglobal(L, module);
lua_pushvalue(L, -2); // Duplicate dummy metatable
lua_setmetatable(L, -2); // setmetatable(module, dummy)
lua_pop(L, -1);
}
void LuaEnvironment::call_global(const char* func, u8 argc, ...)
{
CE_ENSURE(NULL != func);
LuaStack stack(L);
va_list vl;
va_start(vl, argc);
lua_pushcfunction(L, error_handler);
lua_getglobal(L, func);
for (u8 i = 0; i < argc; i++)
{
const int type = va_arg(vl, int);
switch (type)
{
case ARGUMENT_FLOAT:
stack.push_float(va_arg(vl, f64));
break;
default:
CE_FATAL("Unknown argument type");
break;
}
}
va_end(vl);
lua_pcall(L, argc, 0, -argc - 2);
lua_pop(L, -1);
CE_ASSERT(lua_gettop(L) == 0, "Stack not clean");
}
LuaStack LuaEnvironment::get_global(const char* global)
{
LuaStack stack(L);
lua_getglobal(L, global);
return stack;
}
Vector3* LuaEnvironment::next_vector3(const Vector3& v)
{
CE_ASSERT(_vec3_used < CROWN_MAX_LUA_VECTOR3, "Maximum number of Vector3 reached");
return &(_vec3_buffer[_vec3_used++] = v);
}
Quaternion* LuaEnvironment::next_quaternion(const Quaternion& q)
{
CE_ASSERT(_quat_used < CROWN_MAX_LUA_QUATERNION, "Maximum number of Quaternion reached");
return &(_quat_buffer[_quat_used++] = q);
}
Matrix4x4* LuaEnvironment::next_matrix4x4(const Matrix4x4& m)
{
CE_ASSERT(_mat4_used < CROWN_MAX_LUA_MATRIX4X4, "Maximum number of Matrix4x4 reached");
return &(_mat4_buffer[_mat4_used++] = m);
}
bool LuaEnvironment::is_vector3(const Vector3* p) const
{
return p >= &_vec3_buffer[0]
&& p <= &_vec3_buffer[CROWN_MAX_LUA_VECTOR3 - 1];
}
bool LuaEnvironment::is_quaternion(const Quaternion* p) const
{
return p >= &_quat_buffer[0]
&& p <= &_quat_buffer[CROWN_MAX_LUA_QUATERNION - 1];
}
bool LuaEnvironment::is_matrix4x4(const Matrix4x4* p) const
{
return p >= &_mat4_buffer[0]
&& p <= &_mat4_buffer[CROWN_MAX_LUA_MATRIX4X4 - 1];
}
void LuaEnvironment::temp_count(u32& num_vec3, u32& num_quat, u32& num_mat4)
{
num_vec3 = _vec3_used;
num_quat = _quat_used;
num_mat4 = _mat4_used;
}
void LuaEnvironment::set_temp_count(u32 num_vec3, u32 num_quat, u32 num_mat4)
{
_vec3_used = num_vec3;
_quat_used = num_quat;
_mat4_used = num_mat4;
}
void LuaEnvironment::reset_temporaries()
{
_vec3_used = 0;
_quat_used = 0;
_mat4_used = 0;
}
} // namespace crown
<|endoftext|>
|
<commit_before>#include <iostream>
#include <functional>
#include <vector>
struct State {};
class FrameReplay {
public:
using init_function_t = std::function<void(const std::vector<uint8_t*>&)>;
using draw_function_t = std::function<void(const State&, const std::vector<uint8_t*>&)>;
FrameReplay(uint32_t frameId,
init_function_t initFunc = [](const std::vector<uint8_t*> &){},
draw_function_t drawFunc = [](const State&, const std::vector<uint8_t*> &){})
: frameId_(frameId),
initFunc_(initFunc),
drawFunc_(drawFunc)
{}
uint32_t getFrameId() const { return frameId_; }
void setInitFunc(init_function_t initFunc) { initFunc_ = initFunc; }
void setDrawFunc(draw_function_t drawFunc) { drawFunc_ = drawFunc; }
void init(const std::vector<uint8_t*> &buffer) { initFunc_(buffer); }
void draw(const State &engine, const std::vector<uint8_t*> &buffer) { drawFunc_(engine, buffer); }
private:
uint32_t frameId_;
init_function_t initFunc_;
draw_function_t drawFunc_;
};
int main()
{
std::vector<FrameReplay*> frames;
{
// frame #0
// some resources
static int res77;
static const char arr_0[] = "frame #0 vs";
auto frame = new FrameReplay(0, [&](const std::vector<uint8_t*> &) { res77 = 1; },
[&](const State&, const std::vector<uint8_t*> &)
{
std::cout << "res77: " << res77 << " ";
std::cout << "arr_0: " << arr_0 << std::endl;
} );
frames.push_back(frame);
}
{
// frame #1
// some resources
static int res77;
static const char arr_0[] = "frame #1 vs";
auto frame = new FrameReplay(1);
frame->setInitFunc([&](const std::vector<uint8_t*> &) { res77 = 2; });
frame->setDrawFunc([&](const State&, const std::vector<uint8_t*> &)
{
std::cout << "res77: " << res77 << " ";
std::cout << "arr_0: " << arr_0 << std::endl;
} );
frames.push_back(frame);
}
for (const auto& f : frames) {
std::cout << "frame #" << f->getFrameId() << std::endl;
f->init({});
f->draw({},{});
}
}
<commit_msg>put into namespace the lambda closure sample.<commit_after>#include <iostream>
#include <functional>
#include <vector>
namespace abc {
struct State {};
class FrameReplay {
public:
using init_function_t = std::function<void(const std::vector<uint8_t*>&)>;
using draw_function_t = std::function<void(const State&, const std::vector<uint8_t*>&)>;
FrameReplay(uint32_t frameId,
init_function_t initFunc = [](const std::vector<uint8_t*> &){},
draw_function_t drawFunc = [](const State&, const std::vector<uint8_t*> &){})
: frameId_(frameId),
initFunc_(initFunc),
drawFunc_(drawFunc)
{}
uint32_t getFrameId() const { return frameId_; }
void setInitFunc(init_function_t initFunc) { initFunc_ = initFunc; }
void setDrawFunc(draw_function_t drawFunc) { drawFunc_ = drawFunc; }
void setHeight(int h) { height_ = h; }
void setWidth(int w) { width_ = w; }
void init(const std::vector<uint8_t*> &buffer) const { initFunc_(buffer); }
void draw(const State &engine, const std::vector<uint8_t*> &buffer) const { drawFunc_(engine, buffer); }
private:
uint32_t frameId_;
init_function_t initFunc_;
draw_function_t drawFunc_;
int height_;
int width_;
};
std::vector<FrameReplay*> init()
{
std::vector<FrameReplay*> frames;
{
// frame #0
// some resources
static int res77;
static const char arr_0[] = "frame #0 vs";
auto frame = new FrameReplay(0, [&](const std::vector<uint8_t*> &) { res77 = 1; },
[&](const State&, const std::vector<uint8_t*> &)
{
std::cout << "res77: " << res77 << " ";
std::cout << "arr_0: " << arr_0 << std::endl;
} );
frames.push_back(frame);
}
{
// frame #1
// some resources
static int res77;
static const char arr_0[] = "frame #1 vs";
auto frame = new FrameReplay(1);
frame->setInitFunc([&](const std::vector<uint8_t*> &) { res77 = 2; });
frame->setDrawFunc([&](const State&, const std::vector<uint8_t*> &)
{
std::cout << "res77: " << res77 << " ";
std::cout << "arr_0: " << arr_0 << std::endl;
} );
frames.push_back(frame);
}
// NVRO
return frames;
}
}
int main()
{
auto frames = abc::init();
for (const auto& f : frames) {
std::cout << "frame #" << f->getFrameId() << std::endl;
f->init({});
f->draw({},{});
}
}
<|endoftext|>
|
<commit_before>/************************************************************************************
**
* @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved.
*
*************************************************************************************/
/**
* @file g_dfs_server.cpp
* @version
* @brief
* @author duye
* @date 2014-09-24
* @note
*
* 1. 2014-09-24 duye Created this file
*
*/
#include <g_dfs_server.h>
#include <g_logger.h>
static const GInt8* LOG_PREFIX = "dfs.server.startup";
namespace gdfs {
DfsServer::DfsServer() : gcom::HostServer() {}
DfsServer::DfsServer(const std::string& dfs_cfg_file_path) : gcom::HostServer(), m_dfsCfgFilePath(dfs_cfg_file_path) {}
DfsServer::~DfsServer()
{
DfsServerFactory::DestroyServer(HTTP_SERVER, m_httpServer);
DfsServerFactory::DestroyServer(FTP_SERVER, m_httpServer);
DfsServerFactory::DestroyServer(CLI_SERVER, m_httpServer);
}
GResult DfsServer::start()
{
G_LOG_IN();
if (getServerState() == HOST_SERVER_WORK)
{
return G_YES;
}
if (m_dfsCfgFilePath.empty())
{
m_dfsCfgFilePath = DEF_DFS_CFG_FILE_PATH;
}
IS_NO_R(m_cfgMgr.load(m_dfsCfgFilePath));
IS_NO_R(initService());
m_serverState = HOST_SERVER_WORK;
// start routine() thread
this->startTask();
G_LOG_OUT();
return G_YES;
}
GResult DfsServer::stop()
{
G_LOG_IN();
m_httpServer->stop();
m_ftpServer->stop();
m_cliServer->stop();
G_LOG_OUT();
return G_NO;
}
DfsServerState DfsServer::routine()
{
G_LOG_IN();
m_httpServer->start();
m_ftpServer->start();
m_cliServer->start();
for (;;)
{
// startup all server
gcom::NetworkServerMonitor::keepServer(m_httpServer);
gcom::NetworkServerMonitor::keepServer(m_ftpServer);
gcom::NetworkServerMonitor::keepServer(m_cliServer);
gsys::System::sleep(5);
}
G_LOG_OUT();
return G_YES;
}
GResult DfsServer::initService()
{
G_LOG_IN();
m_httpServer = DfsServerFactory::createServer(HTTP_SERVER);
m_ftpServer = DfsServerFactory::createServer(FTP_SERVER);
m_cliServer = DfsServerFactory::createServer(CLI_SERVER);
G_LOG_OUT();
return G_YES;
}
}
<commit_msg>Update g_dfs_server.cpp<commit_after>/************************************************************************************
**
* @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved.
*
*************************************************************************************/
/**
* @file g_dfs_server.cpp
* @version
* @brief
* @author duye
* @date 2014-09-24
* @note
*
* 1. 2014-09-24 duye Created this file
*
*/
#include <g_dfs_server.h>
#include <g_logger.h>
static const GInt8* LOG_PREFIX = "dfs.server.startup";
namespace gdfs {
DfsServer::DfsServer() : gcom::HostServer() {}
DfsServer::DfsServer(const std::string& dfs_cfg_file_path) : gcom::HostServer(), m_dfsCfgFilePath(dfs_cfg_file_path) {}
DfsServer::~DfsServer()
{
gcom::ServerFactory::intance().destroyServer(m_httpServer);
gcom::ServerFactory::intance().destroyServer(m_ftpServer);
gcom::ServerFactory::intance().destroyServer(m_cliServer);
}
GResult DfsServer::start()
{
G_LOG_IN();
if (getServerState() == HOST_SERVER_WORK)
{
return G_YES;
}
if (m_dfsCfgFilePath.empty())
{
m_dfsCfgFilePath = DEF_DFS_CFG_FILE_PATH;
}
IS_NO_R(m_cfgMgr.load(m_dfsCfgFilePath));
IS_NO_R(initService());
m_serverState = HOST_SERVER_WORK;
// start routine() thread
this->startTask();
G_LOG_OUT();
return G_YES;
}
GResult DfsServer::stop()
{
G_LOG_IN();
m_httpServer->stop();
m_ftpServer->stop();
m_cliServer->stop();
G_LOG_OUT();
return G_NO;
}
DfsServerState DfsServer::routine()
{
G_LOG_IN();
m_httpServer->start();
m_ftpServer->start();
m_cliServer->start();
for (;;)
{
// startup all server
gcom::NetworkServerMonitor::keepServer(m_httpServer);
gcom::NetworkServerMonitor::keepServer(m_ftpServer);
gcom::NetworkServerMonitor::keepServer(m_cliServer);
gsys::System::sleep(5);
}
G_LOG_OUT();
return G_YES;
}
GResult DfsServer::initService()
{
G_LOG_IN();
m_httpServer = gcom::ServerFactory::intance().createServer(HTTP_SERVER);
m_ftpServer = gcom::ServerFactory::intance().createServer(FTP_SERVER);
m_cliServer = gcom::ServerFactory::intance().createServer(CLI_SERVER);
G_LOG_OUT();
return G_YES;
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "exception.h"
#include "log.h"
#include <string.h>
#include <execinfo.h>
#include <cxxabi.h>
#include <stdarg.h>
#define BUFFER_SIZE 1024
const char*
Exception::init_traceback()
{
void* callstack[128];
// retrieve current stack addresses
int frames = backtrace(callstack, sizeof(callstack) / sizeof(void*));
traceback = "Traceback:";
if (frames == 0) {
traceback += "\n <empty, possibly corrupt>";
return traceback.c_str();
}
// resolve addresses into strings containing "filename(function+address)"
char** strs = backtrace_symbols(callstack, frames);
// iterate over the returned symbol lines. skip the first, it is the
// address of this function.
for (int i = 0; i < frames; ++i) {
int status = 0;
const char *sep = "\t ()+";
char *mangled, *lasts;
std::string result;
for (mangled = strtok_r(strs[i], sep, &lasts); mangled; mangled = strtok_r(nullptr, sep, &lasts)) {
char* unmangled = abi::__cxa_demangle(mangled, nullptr, 0, &status);
if (!result.empty()) {
result += " ";
}
if (status == 0) {
result += unmangled;
} else {
result += mangled;
}
free(unmangled);
}
traceback += "\n " + result;
}
free(strs);
return traceback.c_str();
}
Exception::Exception(const char *filename, int line, const char *format, ...)
: std::runtime_error("")
{
char buffer[BUFFER_SIZE];
va_list argptr;
va_start(argptr, format);
vsnprintf(buffer, BUFFER_SIZE, format, argptr);
va_end(argptr);
msg.assign(buffer);
snprintf(buffer, BUFFER_SIZE, "%s:%d", filename, line);
context.assign(std::string(buffer) + ": " + msg);
#ifdef TRACEBACKS
init_traceback();
#endif
}
<commit_msg>Allways print file:line on exception logs when TRACEBACKS is on<commit_after>/*
* Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "exception.h"
#include "log.h"
#include <string.h>
#include <execinfo.h>
#include <cxxabi.h>
#include <stdarg.h>
#define BUFFER_SIZE 1024
const char*
Exception::init_traceback()
{
void* callstack[128];
// retrieve current stack addresses
int frames = backtrace(callstack, sizeof(callstack) / sizeof(void*));
traceback = "Traceback:";
if (frames == 0) {
traceback += "\n <empty, possibly corrupt>";
return traceback.c_str();
}
// resolve addresses into strings containing "filename(function+address)"
char** strs = backtrace_symbols(callstack, frames);
// iterate over the returned symbol lines. skip the first, it is the
// address of this function.
for (int i = 0; i < frames; ++i) {
int status = 0;
const char *sep = "\t ()+";
char *mangled, *lasts;
std::string result;
for (mangled = strtok_r(strs[i], sep, &lasts); mangled; mangled = strtok_r(nullptr, sep, &lasts)) {
char* unmangled = abi::__cxa_demangle(mangled, nullptr, 0, &status);
if (!result.empty()) {
result += " ";
}
if (status == 0) {
result += unmangled;
} else {
result += mangled;
}
free(unmangled);
}
traceback += "\n " + result;
}
free(strs);
return traceback.c_str();
}
Exception::Exception(const char *filename, int line, const char *format, ...)
: std::runtime_error("")
{
char buffer[BUFFER_SIZE];
va_list argptr;
va_start(argptr, format);
vsnprintf(buffer, BUFFER_SIZE, format, argptr);
va_end(argptr);
msg.assign(buffer);
snprintf(buffer, BUFFER_SIZE, "%s:%d", filename, line);
context.assign(std::string(buffer) + ": " + msg);
#ifdef TRACEBACKS
msg.assign(std::string(buffer) + ": " + msg);
init_traceback();
#endif
}
<|endoftext|>
|
<commit_before><commit_msg>When pasting from other apps, fall back on Fragment span.<commit_after><|endoftext|>
|
<commit_before><commit_msg>refacotr InfoBar to use RenderContext<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: srchdlg.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: kz $ $Date: 2004-02-26 11:03:52 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "srchdlg.hxx"
#include "sfxresid.hxx"
#include "sfxuno.hxx"
#include "srchdlg.hrc"
#include "dialog.hrc"
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_VIEWOPTIONS_HXX
#include <svtools/viewoptions.hxx>
#endif
using namespace ::com::sun::star::uno;
// ============================================================================
namespace sfx2 {
#define USERITEM_NAME DEFINE_CONST_OUSTRING("UserItem")
#define MAX_SAVE_COUNT (USHORT)10
// ============================================================================
// SearchDialog
// ============================================================================
SearchDialog::SearchDialog( Window* pWindow, const ::rtl::OUString& rConfigName ) :
ModelessDialog( pWindow, SfxResId( RID_DLG_SEARCH ) ),
m_aSearchLabel ( this, ResId( FT_SEARCH ) ),
m_aSearchEdit ( this, ResId( ED_SEARCH ) ),
m_aWholeWordsBox ( this, ResId( CB_WHOLEWORDS ) ),
m_aMatchCaseBox ( this, ResId( CB_MATCHCASE ) ),
m_aWrapAroundBox ( this, ResId( CB_WRAPAROUND ) ),
m_aBackwardsBox ( this, ResId( CB_BACKWARDS ) ),
m_aFindBtn ( this, ResId( PB_FIND ) ),
m_aCancelBtn ( this, ResId( PB_CANCELFIND ) ),
m_sToggleText ( ResId( STR_TOGGLE ) ),
m_sConfigName ( rConfigName ),
m_bIsConstructed ( false )
{
FreeResource();
// set handler
m_aFindBtn.SetClickHdl( LINK( this, SearchDialog, FindHdl ) );
m_aBackwardsBox.SetClickHdl( LINK( this, SearchDialog, ToggleHdl ) );
// load config: old search strings and the status of the check boxes
LoadConfig();
// we need to change the text of the WrapAround box, depends on the status of the Backwards box
if ( m_aBackwardsBox.IsChecked() )
ToggleHdl( &m_aBackwardsBox );
// the search edit should have the focus
m_aSearchEdit.GrabFocus();
}
SearchDialog::~SearchDialog()
{
SaveConfig();
}
void SearchDialog::LoadConfig()
{
SvtViewOptions aViewOpt( E_DIALOG, m_sConfigName );
if ( aViewOpt.Exists() )
{
m_sWinState = ByteString( aViewOpt.GetWindowState().getStr(), RTL_TEXTENCODING_ASCII_US );
Any aUserItem = aViewOpt.GetUserItem( USERITEM_NAME );
::rtl::OUString aTemp;
if ( aUserItem >>= aTemp )
{
String sUserData( aTemp );
DBG_ASSERT( sUserData.GetTokenCount() == 5, "invalid config data" );
xub_StrLen nIdx = 0;
String sSearchText = sUserData.GetToken( 0, ';', nIdx );
m_aWholeWordsBox.Check( sUserData.GetToken( 0, ';', nIdx ).ToInt32() == 1 );
m_aMatchCaseBox.Check( sUserData.GetToken( 0, ';', nIdx ).ToInt32() == 1 );
m_aWrapAroundBox.Check( sUserData.GetToken( 0, ';', nIdx ).ToInt32() == 1 );
m_aBackwardsBox.Check( sUserData.GetToken( 0, ';', nIdx ).ToInt32() == 1 );
nIdx = 0;
while ( nIdx != STRING_NOTFOUND )
m_aSearchEdit.InsertEntry( sSearchText.GetToken( 0, '\t', nIdx ) );
m_aSearchEdit.SelectEntryPos(0);
}
}
}
void SearchDialog::SaveConfig()
{
SvtViewOptions aViewOpt( E_DIALOG, m_sConfigName );
aViewOpt.SetWindowState( rtl::OUString::createFromAscii( m_sWinState.GetBuffer() ) );
String sUserData;
USHORT i = 0, nCount = Min( m_aSearchEdit.GetEntryCount(), MAX_SAVE_COUNT );
for ( ; i < nCount; ++i )
{
sUserData += m_aSearchEdit.GetEntry(i);
sUserData += '\t';
}
sUserData.EraseTrailingChars( '\t' );
sUserData += ';';
sUserData += String::CreateFromInt32( m_aWholeWordsBox.IsChecked() ? 1 : 0 );
sUserData += ';';
sUserData += String::CreateFromInt32( m_aMatchCaseBox.IsChecked() ? 1 : 0 );
sUserData += ';';
sUserData += String::CreateFromInt32( m_aWrapAroundBox.IsChecked() ? 1 : 0 );
sUserData += ';';
sUserData += String::CreateFromInt32( m_aBackwardsBox.IsChecked() ? 1 : 0 );
Any aUserItem = makeAny( ::rtl::OUString( sUserData ) );
aViewOpt.SetUserItem( USERITEM_NAME, aUserItem );
}
IMPL_LINK( SearchDialog, FindHdl, PushButton*, EMPTYARG )
{
m_aSearchEdit.InsertEntry( GetSearchText(), 0 );
m_aFindHdl.Call( this );
return 0;
}
IMPL_LINK( SearchDialog, ToggleHdl, CheckBox*, EMPTYARG )
{
String sTemp = m_aWrapAroundBox.GetText();
m_aWrapAroundBox.SetText( m_sToggleText );
m_sToggleText = sTemp;
return 0;
}
void SearchDialog::SetFocusOnEdit()
{
Selection aSelection( 0, m_aSearchEdit.GetText().Len() );
m_aSearchEdit.SetSelection( aSelection );
m_aSearchEdit.GrabFocus();
}
BOOL SearchDialog::Close()
{
Point aPos = GetPosPixel();
BOOL bRet = ModelessDialog::Close();
m_aCloseHdl.Call( this );
return bRet;
}
void SearchDialog::StateChanged( StateChangedType nStateChange )
{
if ( nStateChange == STATE_CHANGE_INITSHOW )
{
if ( m_sWinState.Len() )
SetWindowState( m_sWinState );
m_bIsConstructed = TRUE;
}
ModelessDialog::StateChanged( nStateChange );
}
void SearchDialog::Move()
{
ModelessDialog::Move();
if ( m_bIsConstructed && IsReallyVisible() )
m_sWinState = GetWindowState( WINDOWSTATE_MASK_POS | WINDOWSTATE_MASK_STATE );
}
// ============================================================================
} // namespace sfx2
// ============================================================================
<commit_msg>INTEGRATION: CWS pbhelp02 (1.2.114); FILE MERGED 2004/07/07 06:41:19 pb 1.2.114.2: fix: #115873# use local methods 2004/07/05 13:03:08 pb 1.2.114.1: fix: #i29824# no double entries any more and wrap around as default<commit_after>/*************************************************************************
*
* $RCSfile: srchdlg.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2004-08-11 14:05:29 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "srchdlg.hxx"
#include "sfxresid.hxx"
#include "sfxuno.hxx"
#include "srchdlg.hrc"
#include "dialog.hrc"
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_VIEWOPTIONS_HXX
#include <svtools/viewoptions.hxx>
#endif
using namespace ::com::sun::star::uno;
// ============================================================================
namespace sfx2 {
#define USERITEM_NAME DEFINE_CONST_OUSTRING("UserItem")
#define MAX_SAVE_COUNT (USHORT)10
// ============================================================================
// SearchDialog
// ============================================================================
SearchDialog::SearchDialog( Window* pWindow, const ::rtl::OUString& rConfigName ) :
ModelessDialog( pWindow, SfxResId( RID_DLG_SEARCH ) ),
m_aSearchLabel ( this, ResId( FT_SEARCH ) ),
m_aSearchEdit ( this, ResId( ED_SEARCH ) ),
m_aWholeWordsBox ( this, ResId( CB_WHOLEWORDS ) ),
m_aMatchCaseBox ( this, ResId( CB_MATCHCASE ) ),
m_aWrapAroundBox ( this, ResId( CB_WRAPAROUND ) ),
m_aBackwardsBox ( this, ResId( CB_BACKWARDS ) ),
m_aFindBtn ( this, ResId( PB_FIND ) ),
m_aCancelBtn ( this, ResId( PB_CANCELFIND ) ),
m_sToggleText ( ResId( STR_TOGGLE ) ),
m_sConfigName ( rConfigName ),
m_bIsConstructed ( false )
{
FreeResource();
// set handler
m_aFindBtn.SetClickHdl( LINK( this, SearchDialog, FindHdl ) );
m_aBackwardsBox.SetClickHdl( LINK( this, SearchDialog, ToggleHdl ) );
// load config: old search strings and the status of the check boxes
LoadConfig();
// we need to change the text of the WrapAround box, depends on the status of the Backwards box
if ( m_aBackwardsBox.IsChecked() )
ToggleHdl( &m_aBackwardsBox );
// the search edit should have the focus
m_aSearchEdit.GrabFocus();
}
SearchDialog::~SearchDialog()
{
SaveConfig();
}
void SearchDialog::LoadConfig()
{
SvtViewOptions aViewOpt( E_DIALOG, m_sConfigName );
if ( aViewOpt.Exists() )
{
m_sWinState = ByteString( aViewOpt.GetWindowState().getStr(), RTL_TEXTENCODING_ASCII_US );
Any aUserItem = aViewOpt.GetUserItem( USERITEM_NAME );
::rtl::OUString aTemp;
if ( aUserItem >>= aTemp )
{
String sUserData( aTemp );
DBG_ASSERT( sUserData.GetTokenCount() == 5, "invalid config data" );
xub_StrLen nIdx = 0;
String sSearchText = sUserData.GetToken( 0, ';', nIdx );
m_aWholeWordsBox.Check( sUserData.GetToken( 0, ';', nIdx ).ToInt32() == 1 );
m_aMatchCaseBox.Check( sUserData.GetToken( 0, ';', nIdx ).ToInt32() == 1 );
m_aWrapAroundBox.Check( sUserData.GetToken( 0, ';', nIdx ).ToInt32() == 1 );
m_aBackwardsBox.Check( sUserData.GetToken( 0, ';', nIdx ).ToInt32() == 1 );
nIdx = 0;
while ( nIdx != STRING_NOTFOUND )
m_aSearchEdit.InsertEntry( sSearchText.GetToken( 0, '\t', nIdx ) );
m_aSearchEdit.SelectEntryPos(0);
}
}
else
m_aWrapAroundBox.Check( TRUE );
}
void SearchDialog::SaveConfig()
{
SvtViewOptions aViewOpt( E_DIALOG, m_sConfigName );
aViewOpt.SetWindowState( rtl::OUString::createFromAscii( m_sWinState.GetBuffer() ) );
String sUserData;
USHORT i = 0, nCount = Min( m_aSearchEdit.GetEntryCount(), MAX_SAVE_COUNT );
for ( ; i < nCount; ++i )
{
sUserData += m_aSearchEdit.GetEntry(i);
sUserData += '\t';
}
sUserData.EraseTrailingChars( '\t' );
sUserData += ';';
sUserData += String::CreateFromInt32( m_aWholeWordsBox.IsChecked() ? 1 : 0 );
sUserData += ';';
sUserData += String::CreateFromInt32( m_aMatchCaseBox.IsChecked() ? 1 : 0 );
sUserData += ';';
sUserData += String::CreateFromInt32( m_aWrapAroundBox.IsChecked() ? 1 : 0 );
sUserData += ';';
sUserData += String::CreateFromInt32( m_aBackwardsBox.IsChecked() ? 1 : 0 );
Any aUserItem = makeAny( ::rtl::OUString( sUserData ) );
aViewOpt.SetUserItem( USERITEM_NAME, aUserItem );
}
IMPL_LINK( SearchDialog, FindHdl, PushButton*, EMPTYARG )
{
String sSrchTxt = m_aSearchEdit.GetText();
USHORT nPos = m_aSearchEdit.GetEntryPos( sSrchTxt );
if ( nPos > 0 && nPos != COMBOBOX_ENTRY_NOTFOUND )
m_aSearchEdit.RemoveEntry( nPos );
if ( nPos > 0 )
m_aSearchEdit.InsertEntry( sSrchTxt, 0 );
m_aFindHdl.Call( this );
return 0;
}
IMPL_LINK( SearchDialog, ToggleHdl, CheckBox*, EMPTYARG )
{
String sTemp = m_aWrapAroundBox.GetText();
m_aWrapAroundBox.SetText( m_sToggleText );
m_sToggleText = sTemp;
return 0;
}
void SearchDialog::SetFocusOnEdit()
{
Selection aSelection( 0, m_aSearchEdit.GetText().Len() );
m_aSearchEdit.SetSelection( aSelection );
m_aSearchEdit.GrabFocus();
}
BOOL SearchDialog::Close()
{
Point aPos = GetPosPixel();
BOOL bRet = ModelessDialog::Close();
m_aCloseHdl.Call( this );
return bRet;
}
void SearchDialog::StateChanged( StateChangedType nStateChange )
{
if ( nStateChange == STATE_CHANGE_INITSHOW )
{
if ( m_sWinState.Len() )
SetWindowState( m_sWinState );
m_bIsConstructed = TRUE;
}
ModelessDialog::StateChanged( nStateChange );
}
void SearchDialog::Move()
{
ModelessDialog::Move();
if ( m_bIsConstructed && IsReallyVisible() )
m_sWinState = GetWindowState( WINDOWSTATE_MASK_POS | WINDOWSTATE_MASK_STATE );
}
// ============================================================================
} // namespace sfx2
// ============================================================================
<|endoftext|>
|
<commit_before>#include <string.h>
#include <Arduino.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "pitches.h"
// Forward declarations.
void jeopardySetup();
void jeopardyLoop();
void clearScreen();
// Supported game modes.
enum {
MODE_JEOPARDY,
MODE_BRAINRING, // not implemented
MODE_HAMSA, // not implemented
};
// All available buttons.
enum {
BUTTON_PLAYER_1,
BUTTON_PLAYER_2,
BUTTON_PLAYER_3,
BUTTON_PLAYER_4,
BUTTON_CONTROL_1,
BUTTON_CONTROL_2,
BUTTON_CONTROL_3,
BUTTON_COUNT = BUTTON_CONTROL_3 + 1,
BUTTON_START = BUTTON_CONTROL_1,
BUTTON_RESET = BUTTON_CONTROL_3,
FIRST_PLAYER_BUTTON = BUTTON_PLAYER_1,
LAST_PLAYER_BUTTON = BUTTON_PLAYER_4,
};
// Pin numbers for each button, indexed by the enum values above.
const int kButtonPins[] = {
8, 6, 4, 2, // players
15, 16, 17, // control
};
// Pin numbers for each player's LED, indexed by the buttons enum.
// E.g. kLedPins[BUTTON_PLAYER_1] is the first player's LED.
const int kLedPins[] = {9, 7, 5, 3};
const int kSpeakerPin = 11;
const int kScreenWidth = 16;
// Button debounce delay in milliseconds.
const unsigned long kDebounceMs = 100;
// GLOBAL STATE
// An I2C-connected 16x2 character LCD screen.
LiquidCrystal_I2C lcd(0x3f, 2, 1, 0, 4, 5, 6, 7);
// Selected game mode.
int mode = MODE_JEOPARDY;
// Button state, true means pressed.
bool buttons[BUTTON_COUNT] = { false };
// Button state before the latest update.
bool buttonsBefore[BUTTON_COUNT] = { false };
// For each button, when it was last time pressed in milliseconds since device
// start.
unsigned long lastPressedMs[BUTTON_COUNT] = {0};
// Button labels are printed on the lower line of the screen.
const char* leftButtonLabel = "Start";
const char* rightButtonLabel = "Reset";
void setup() {
for (const int buttonPin : kButtonPins) {
pinMode(buttonPin, INPUT_PULLUP);
}
for (const int ledPin : kLedPins) {
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
}
pinMode(kSpeakerPin, OUTPUT);
// Initialize the screen.
lcd.begin(/*cols=*/16, /*rows=*/2);
lcd.setBacklightPin(3, POSITIVE);
lcd.setBacklight(HIGH);
// Serial is for debugging.
Serial.begin(9600);
// TODO: Select mode.
jeopardySetup();
}
void loop() {
unsigned long now = millis();
// Read all buttons and save their state in a global array.
for (int i = 0; i < BUTTON_COUNT; ++i) {
buttonsBefore[i] = buttons[i];
// Ignore the button state changes if it was pressed less than kDebounceMs
// milliseconds ago to account for contact bouncing.
if (now - lastPressedMs[i] > kDebounceMs) {
// The buttons pins are active LOW.
buttons[i] = (digitalRead(kButtonPins[i]) == LOW);
}
}
// TODO: Dispatch based on current mode.
jeopardyLoop();
}
void jeopardySetup() {
leftButtonLabel = "Start";
rightButtonLabel = "Reset";
clearScreen();
lcd.print("Mode: Jeopardy");
}
void jeopardyLoop() {
static bool gotWinner = false;
static bool started = false;
static unsigned long time = 0;
if (buttons[BUTTON_RESET] && !buttonsBefore[BUTTON_RESET]) {
gotWinner = false;
started = false;
jeopardySetup();
for (int ledPin : kLedPins) {
digitalWrite(ledPin, LOW);
tone(kSpeakerPin, NOTE_D4, 100/*ms*/);
}
return;
}
if (gotWinner) {
return;
}
if (buttons[BUTTON_START] && !buttonsBefore[BUTTON_START]) {
clearScreen();
started = true;
time = millis();
}
if (started) {
lcd.home();
lcd.print((millis() - time) / 1000);
}
for (int i = FIRST_PLAYER_BUTTON; i <= LAST_PLAYER_BUTTON; ++i) {
if (buttons[i] && !buttonsBefore[i]) {
digitalWrite(kLedPins[i], HIGH);
tone(kSpeakerPin, NOTE_G4, 100/*ms*/);
gotWinner = true;
leftButtonLabel = "Continue";
rightButtonLabel = "Reset";
clearScreen();
lcd.print("Player ");
lcd.print(i + 1);
break;
}
}
}
void clearScreen() {
lcd.clear();
lcd.setCursor(/*row=*/0, /*col=*/1);
// Print button functions on the lower line of the screen.
lcd.print(leftButtonLabel);
const int spaces = kScreenWidth - strlen(leftButtonLabel) -
strlen(rightButtonLabel);
for (int i = 0; i < spaces; ++i) {
lcd.print(' ');
}
lcd.print(rightButtonLabel);
lcd.home();
}
<commit_msg>pick the fastest player randomly<commit_after>#include <string.h>
#include <Arduino.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "pitches.h"
// Forward declarations.
void jeopardySetup();
void jeopardyLoop();
void clearScreen();
int fastestPlayer();
// Supported game modes.
enum {
MODE_JEOPARDY,
MODE_BRAINRING, // not implemented
MODE_HAMSA, // not implemented
};
// All available buttons.
enum {
BUTTON_PLAYER_1,
BUTTON_PLAYER_2,
BUTTON_PLAYER_3,
BUTTON_PLAYER_4,
BUTTON_CONTROL_1,
BUTTON_CONTROL_2,
BUTTON_CONTROL_3,
BUTTON_COUNT = BUTTON_CONTROL_3 + 1,
BUTTON_START = BUTTON_CONTROL_1,
BUTTON_RESET = BUTTON_CONTROL_3,
FIRST_PLAYER_BUTTON = BUTTON_PLAYER_1,
LAST_PLAYER_BUTTON = BUTTON_PLAYER_4,
};
// Pin numbers for each button, indexed by the enum values above.
const int kButtonPins[] = {
8, 6, 4, 2, // players
15, 16, 17, // control
};
// Pin numbers for each player's LED, indexed by the buttons enum.
// E.g. kLedPins[BUTTON_PLAYER_1] is the first player's LED.
const int kLedPins[] = {9, 7, 5, 3};
const int kSpeakerPin = 11;
const int kScreenWidth = 16;
// Button debounce delay in milliseconds.
const unsigned long kDebounceMs = 100;
// GLOBAL STATE
// An I2C-connected 16x2 character LCD screen.
LiquidCrystal_I2C lcd(0x3f, 2, 1, 0, 4, 5, 6, 7);
// Selected game mode.
int mode = MODE_JEOPARDY;
// Button state, true means pressed.
bool buttons[BUTTON_COUNT] = { false };
// Button state before the latest update.
bool buttonsBefore[BUTTON_COUNT] = { false };
// For each button, when it was last time pressed in milliseconds since device
// start.
unsigned long lastPressedMs[BUTTON_COUNT] = {0};
// Button labels are printed on the lower line of the screen.
const char* leftButtonLabel = "Start";
const char* rightButtonLabel = "Reset";
void setup() {
// Analog input 0 is not connected, use noise from it for pseudo-random
// generator seeding.
randomSeed(analogRead(0));
// Setup input and output pins.
for (const int buttonPin : kButtonPins) {
pinMode(buttonPin, INPUT_PULLUP);
}
for (const int ledPin : kLedPins) {
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
}
pinMode(kSpeakerPin, OUTPUT);
// Initialize the screen.
lcd.begin(/*cols=*/16, /*rows=*/2);
lcd.setBacklightPin(3, POSITIVE);
lcd.setBacklight(HIGH);
// Serial is for debugging.
Serial.begin(9600);
// TODO: Select mode.
jeopardySetup();
}
void loop() {
unsigned long now = millis();
// Read all buttons and save their state in a global array.
for (int i = 0; i < BUTTON_COUNT; ++i) {
buttonsBefore[i] = buttons[i];
// Ignore the button state changes if it was pressed less than kDebounceMs
// milliseconds ago to account for contact bouncing.
if (now - lastPressedMs[i] > kDebounceMs) {
// The buttons pins are active LOW.
buttons[i] = (digitalRead(kButtonPins[i]) == LOW);
}
}
// TODO: Dispatch based on current mode.
jeopardyLoop();
}
void jeopardySetup() {
leftButtonLabel = "Start";
rightButtonLabel = "Reset";
clearScreen();
lcd.print("Mode: Jeopardy");
}
void jeopardyLoop() {
static bool gotWinner = false;
static bool started = false;
static unsigned long time = 0;
if (buttons[BUTTON_RESET] && !buttonsBefore[BUTTON_RESET]) {
gotWinner = false;
started = false;
jeopardySetup();
for (int ledPin : kLedPins) {
digitalWrite(ledPin, LOW);
tone(kSpeakerPin, NOTE_D4, 100/*ms*/);
}
return;
}
if (gotWinner) {
return;
}
if (buttons[BUTTON_START] && !buttonsBefore[BUTTON_START]) {
clearScreen();
started = true;
time = millis();
}
if (started) {
lcd.home();
lcd.print((millis() - time) / 1000);
}
const int winner = fastestPlayer();
if (winner != -1) {
digitalWrite(kLedPins[winner], HIGH);
tone(kSpeakerPin, NOTE_G4, 100/*ms*/);
gotWinner = true;
leftButtonLabel = "Continue";
rightButtonLabel = "Reset";
clearScreen();
lcd.print("Player ");
lcd.print(winner + 1);
}
}
void clearScreen() {
lcd.clear();
lcd.setCursor(/*row=*/0, /*col=*/1);
// Print button functions on the lower line of the screen.
lcd.print(leftButtonLabel);
const int spaces = kScreenWidth - strlen(leftButtonLabel) -
strlen(rightButtonLabel);
for (int i = 0; i < spaces; ++i) {
lcd.print(' ');
}
lcd.print(rightButtonLabel);
lcd.home();
}
// Returns index of the player who pressed their button first or -1 for nobody.
int fastestPlayer() {
// First, count how many players have pressed a button.
int buttonsPressed = 0;
for (int i = FIRST_PLAYER_BUTTON; i <= LAST_PLAYER_BUTTON; ++i) {
if (buttons[i] && !buttonsBefore[i]) {
++buttonsPressed;
}
}
if (buttonsPressed == 0) {
return -1;
}
int winnerIndex = random(buttonsPressed);
int player = FIRST_PLAYER_BUTTON;
for (int i = 0; i < winnerIndex + 1; ++i) {
while (!buttons[player] || buttonsBefore[player]) {
++player;
}
}
return player;
}
<|endoftext|>
|
<commit_before><commit_msg>Implement writeSync for buffers<commit_after><|endoftext|>
|
<commit_before><commit_msg>Add and move DisallowHeapAllocation scope.<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fuconuno.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-09 04:39:27 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "fuconuno.hxx"
#ifndef _AEITEM_HXX //autogen
#include <svtools/aeitem.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX //autogen
#include <sfx2/viewfrm.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#pragma hdrstop
#ifndef _SVX_FMGLOB_HXX
#include <svx/fmglob.hxx>
#endif
#include <svx/dialogs.hrc>
class SbModule;
#include "app.hrc"
#include "glob.hrc"
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_WINDOW_SHELL_HXX
#include "Window.hxx"
#endif
#ifndef SD_VIEW_SHELL_BASE_HXX
#include "ViewShellBase.hxx"
#endif
#ifndef SD_OBJECT_BAR_MANAGER_HXX
#include "ObjectBarManager.hxx"
#endif
#include "drawdoc.hxx"
#include "sdresid.hxx"
#include "res_bmp.hrc"
namespace sd {
TYPEINIT1( FuConstructUnoControl, FuConstruct );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuConstructUnoControl::FuConstructUnoControl (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq)
: FuConstruct(pViewSh, pWin, pView, pDoc, rReq)
{
SFX_REQUEST_ARG( rReq, pInventorItem, SfxUInt32Item, SID_FM_CONTROL_INVENTOR, FALSE );
SFX_REQUEST_ARG( rReq, pIdentifierItem, SfxUInt16Item, SID_FM_CONTROL_IDENTIFIER, FALSE );
if( pInventorItem )
nInventor = pInventorItem->GetValue();
if( pIdentifierItem )
nIdentifier = pIdentifierItem->GetValue();
pViewShell->GetObjectBarManager().SwitchObjectBar (RID_DRAW_OBJ_TOOLBOX);
}
/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/
FuConstructUnoControl::~FuConstructUnoControl()
{
}
/*************************************************************************
|*
|* MouseButtonDown-event
|*
\************************************************************************/
BOOL FuConstructUnoControl::MouseButtonDown(const MouseEvent& rMEvt)
{
BOOL bReturn = FuConstruct::MouseButtonDown(rMEvt);
if ( rMEvt.IsLeft() && !pView->IsAction() )
{
Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) );
pWindow->CaptureMouse();
USHORT nDrgLog = USHORT ( pWindow->PixelToLogic(Size(DRGPIX,0)).Width() );
pView->BegCreateObj(aPnt, (OutputDevice*) NULL, nDrgLog);
bReturn = TRUE;
}
return bReturn;
}
/*************************************************************************
|*
|* MouseMove-event
|*
\************************************************************************/
BOOL FuConstructUnoControl::MouseMove(const MouseEvent& rMEvt)
{
return FuConstruct::MouseMove(rMEvt);
}
/*************************************************************************
|*
|* MouseButtonUp-event
|*
\************************************************************************/
BOOL FuConstructUnoControl::MouseButtonUp(const MouseEvent& rMEvt)
{
BOOL bReturn = FALSE;
if ( pView->IsCreateObj() && rMEvt.IsLeft() )
{
Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) );
pView->EndCreateObj(SDRCREATE_FORCEEND);
bReturn = TRUE;
}
bReturn = (FuConstruct::MouseButtonUp(rMEvt) || bReturn);
if (!bPermanent)
pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_OBJECT_SELECT, SFX_CALLMODE_ASYNCHRON);
return (bReturn);
}
/*************************************************************************
|*
|* Tastaturereignisse bearbeiten
|*
|* Wird ein KeyEvent bearbeitet, so ist der Return-Wert TRUE, andernfalls
|* FALSE.
|*
\************************************************************************/
BOOL FuConstructUnoControl::KeyInput(const KeyEvent& rKEvt)
{
BOOL bReturn = FuConstruct::KeyInput(rKEvt);
return(bReturn);
}
/*************************************************************************
|*
|* Function aktivieren
|*
\************************************************************************/
void FuConstructUnoControl::Activate()
{
pView->SetCurrentObj( nIdentifier, nInventor );
aNewPointer = Pointer(POINTER_DRAW_RECT);
aOldPointer = pWindow->GetPointer();
pWindow->SetPointer( aNewPointer );
aOldLayer = pView->GetActiveLayer();
String aStr(SdResId(STR_LAYER_CONTROLS));
pView->SetActiveLayer( aStr );
FuConstruct::Activate();
}
/*************************************************************************
|*
|* Function deaktivieren
|*
\************************************************************************/
void FuConstructUnoControl::Deactivate()
{
FuConstruct::Deactivate();
pView->SetActiveLayer( aOldLayer );
pWindow->SetPointer( aOldPointer );
}
// #97016#
SdrObject* FuConstructUnoControl::CreateDefaultObject(const sal_uInt16 nID, const Rectangle& rRectangle)
{
// case SID_FM_CREATE_CONTROL:
SdrObject* pObj = SdrObjFactory::MakeNewObject(
pView->GetCurrentObjInventor(), pView->GetCurrentObjIdentifier(),
0L, pDoc);
if(pObj)
{
pObj->SetLogicRect(rRectangle);
}
return pObj;
}
} // end of namespace sd
<commit_msg>INTEGRATION: CWS impressfunctions (1.6.40); FILE MERGED 2005/10/28 10:57:35 cl 1.6.40.1: #125341# reworked FuPoor classes to use refcounting<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fuconuno.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-12-14 16:57:06 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "fuconuno.hxx"
#ifndef _AEITEM_HXX //autogen
#include <svtools/aeitem.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX //autogen
#include <sfx2/viewfrm.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#pragma hdrstop
#ifndef _SVX_FMGLOB_HXX
#include <svx/fmglob.hxx>
#endif
#include <svx/dialogs.hrc>
class SbModule;
#include "app.hrc"
#include "glob.hrc"
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_WINDOW_SHELL_HXX
#include "Window.hxx"
#endif
#ifndef SD_VIEW_SHELL_BASE_HXX
#include "ViewShellBase.hxx"
#endif
#ifndef SD_OBJECT_BAR_MANAGER_HXX
#include "ObjectBarManager.hxx"
#endif
#include "drawdoc.hxx"
#include "sdresid.hxx"
#include "res_bmp.hrc"
namespace sd {
TYPEINIT1( FuConstructUnoControl, FuConstruct );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuConstructUnoControl::FuConstructUnoControl (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq)
: FuConstruct(pViewSh, pWin, pView, pDoc, rReq)
{
}
FunctionReference FuConstructUnoControl::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq, bool bPermanent )
{
FuConstructUnoControl* pFunc;
FunctionReference xFunc( pFunc = new FuConstructUnoControl( pViewSh, pWin, pView, pDoc, rReq ) );
xFunc->DoExecute(rReq);
pFunc->SetPermanent(bPermanent);
return xFunc;
}
void FuConstructUnoControl::DoExecute( SfxRequest& rReq )
{
FuConstruct::DoExecute( rReq );
SFX_REQUEST_ARG( rReq, pInventorItem, SfxUInt32Item, SID_FM_CONTROL_INVENTOR, FALSE );
SFX_REQUEST_ARG( rReq, pIdentifierItem, SfxUInt16Item, SID_FM_CONTROL_IDENTIFIER, FALSE );
if( pInventorItem )
nInventor = pInventorItem->GetValue();
if( pIdentifierItem )
nIdentifier = pIdentifierItem->GetValue();
pViewShell->GetObjectBarManager().SwitchObjectBar (RID_DRAW_OBJ_TOOLBOX);
}
/*************************************************************************
|*
|* MouseButtonDown-event
|*
\************************************************************************/
BOOL FuConstructUnoControl::MouseButtonDown(const MouseEvent& rMEvt)
{
BOOL bReturn = FuConstruct::MouseButtonDown(rMEvt);
if ( rMEvt.IsLeft() && !pView->IsAction() )
{
Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) );
pWindow->CaptureMouse();
USHORT nDrgLog = USHORT ( pWindow->PixelToLogic(Size(DRGPIX,0)).Width() );
pView->BegCreateObj(aPnt, (OutputDevice*) NULL, nDrgLog);
bReturn = TRUE;
}
return bReturn;
}
/*************************************************************************
|*
|* MouseMove-event
|*
\************************************************************************/
BOOL FuConstructUnoControl::MouseMove(const MouseEvent& rMEvt)
{
return FuConstruct::MouseMove(rMEvt);
}
/*************************************************************************
|*
|* MouseButtonUp-event
|*
\************************************************************************/
BOOL FuConstructUnoControl::MouseButtonUp(const MouseEvent& rMEvt)
{
BOOL bReturn = FALSE;
if ( pView->IsCreateObj() && rMEvt.IsLeft() )
{
Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) );
pView->EndCreateObj(SDRCREATE_FORCEEND);
bReturn = TRUE;
}
bReturn = (FuConstruct::MouseButtonUp(rMEvt) || bReturn);
if (!bPermanent)
pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_OBJECT_SELECT, SFX_CALLMODE_ASYNCHRON);
return (bReturn);
}
/*************************************************************************
|*
|* Tastaturereignisse bearbeiten
|*
|* Wird ein KeyEvent bearbeitet, so ist der Return-Wert TRUE, andernfalls
|* FALSE.
|*
\************************************************************************/
BOOL FuConstructUnoControl::KeyInput(const KeyEvent& rKEvt)
{
BOOL bReturn = FuConstruct::KeyInput(rKEvt);
return(bReturn);
}
/*************************************************************************
|*
|* Function aktivieren
|*
\************************************************************************/
void FuConstructUnoControl::Activate()
{
pView->SetCurrentObj( nIdentifier, nInventor );
aNewPointer = Pointer(POINTER_DRAW_RECT);
aOldPointer = pWindow->GetPointer();
pWindow->SetPointer( aNewPointer );
aOldLayer = pView->GetActiveLayer();
String aStr(SdResId(STR_LAYER_CONTROLS));
pView->SetActiveLayer( aStr );
FuConstruct::Activate();
}
/*************************************************************************
|*
|* Function deaktivieren
|*
\************************************************************************/
void FuConstructUnoControl::Deactivate()
{
FuConstruct::Deactivate();
pView->SetActiveLayer( aOldLayer );
pWindow->SetPointer( aOldPointer );
}
// #97016#
SdrObject* FuConstructUnoControl::CreateDefaultObject(const sal_uInt16 nID, const Rectangle& rRectangle)
{
// case SID_FM_CREATE_CONTROL:
SdrObject* pObj = SdrObjFactory::MakeNewObject(
pView->GetCurrentObjInventor(), pView->GetCurrentObjIdentifier(),
0L, pDoc);
if(pObj)
{
pObj->SetLogicRect(rRectangle);
}
return pObj;
}
} // end of namespace sd
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: fudspord.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2004-01-20 11:01:33 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include "fudspord.hxx"
#include <svx/svxids.hrc>
#ifndef _VCL_POINTR_HXX //autogen
#include <vcl/pointr.hxx>
#endif
#include "app.hrc"
#ifndef SD_FU_POOR_HXX
#include "fupoor.hxx"
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_WINDOW_SHELL_HXX
#include "Window.hxx"
#endif
#include "drawdoc.hxx"
namespace sd {
TYPEINIT1( FuDisplayOrder, FuPoor );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuDisplayOrder::FuDisplayOrder (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq)
: FuPoor(pViewSh, pWin, pView, pDoc, rReq),
pUserMarker(NULL),
pRefObj(NULL)
{
pUserMarker = new SdrViewUserMarker(pView);
}
/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/
FuDisplayOrder::~FuDisplayOrder()
{
delete pUserMarker;
}
/*************************************************************************
|*
|* MouseButtonDown-event
|*
\************************************************************************/
BOOL FuDisplayOrder::MouseButtonDown(const MouseEvent& rMEvt)
{
// #95491# remember button state for creation of own MouseEvents
SetMouseButtonCode(rMEvt.GetButtons());
return TRUE;
}
/*************************************************************************
|*
|* MouseMove-event
|*
\************************************************************************/
BOOL FuDisplayOrder::MouseMove(const MouseEvent& rMEvt)
{
SdrObject* pPickObj;
SdrPageView* pPV;
Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) );
USHORT nHitLog = USHORT ( pWindow->PixelToLogic(Size(HITPIX,0)).Width() );
if ( pView->PickObj(aPnt, pPickObj, pPV) )
{
if (pRefObj != pPickObj)
{
pRefObj = pPickObj;
pUserMarker->SetXPolyPolygon(pRefObj, pView->GetPageViewPvNum(0));
pUserMarker->Show();
}
}
else
{
pRefObj = NULL;
pUserMarker->Hide();
}
return TRUE;
}
/*************************************************************************
|*
|* MouseButtonUp-event
|*
\************************************************************************/
BOOL FuDisplayOrder::MouseButtonUp(const MouseEvent& rMEvt)
{
// #95491# remember button state for creation of own MouseEvents
SetMouseButtonCode(rMEvt.GetButtons());
SdrPageView* pPV = NULL;
Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) );
USHORT nHitLog = USHORT ( pWindow->PixelToLogic(Size(HITPIX,0)).Width() );
if ( pView->PickObj(aPnt, pRefObj, pPV) )
{
if (nSlotId == SID_BEFORE_OBJ)
{
pView->PutMarkedInFrontOfObj(pRefObj);
}
else
{
pView->PutMarkedBehindObj(pRefObj);
}
}
pViewShell->Cancel();
return TRUE;
}
/*************************************************************************
|*
|* Function aktivieren
|*
\************************************************************************/
void FuDisplayOrder::Activate()
{
aPtr = pWindow->GetPointer();
pWindow->SetPointer( Pointer( POINTER_REFHAND ) );
if (pUserMarker)
{
pUserMarker->Show();
}
}
/*************************************************************************
|*
|* Function deaktivieren
|*
\************************************************************************/
void FuDisplayOrder::Deactivate()
{
if (pUserMarker)
{
pUserMarker->Hide();
}
pWindow->SetPointer( aPtr );
}
} // end of namespace sd
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.560); FILE MERGED 2005/09/05 13:22:15 rt 1.3.560.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fudspord.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 04:41:57 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#pragma hdrstop
#include "fudspord.hxx"
#include <svx/svxids.hrc>
#ifndef _VCL_POINTR_HXX //autogen
#include <vcl/pointr.hxx>
#endif
#include "app.hrc"
#ifndef SD_FU_POOR_HXX
#include "fupoor.hxx"
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_WINDOW_SHELL_HXX
#include "Window.hxx"
#endif
#include "drawdoc.hxx"
namespace sd {
TYPEINIT1( FuDisplayOrder, FuPoor );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuDisplayOrder::FuDisplayOrder (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq)
: FuPoor(pViewSh, pWin, pView, pDoc, rReq),
pUserMarker(NULL),
pRefObj(NULL)
{
pUserMarker = new SdrViewUserMarker(pView);
}
/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/
FuDisplayOrder::~FuDisplayOrder()
{
delete pUserMarker;
}
/*************************************************************************
|*
|* MouseButtonDown-event
|*
\************************************************************************/
BOOL FuDisplayOrder::MouseButtonDown(const MouseEvent& rMEvt)
{
// #95491# remember button state for creation of own MouseEvents
SetMouseButtonCode(rMEvt.GetButtons());
return TRUE;
}
/*************************************************************************
|*
|* MouseMove-event
|*
\************************************************************************/
BOOL FuDisplayOrder::MouseMove(const MouseEvent& rMEvt)
{
SdrObject* pPickObj;
SdrPageView* pPV;
Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) );
USHORT nHitLog = USHORT ( pWindow->PixelToLogic(Size(HITPIX,0)).Width() );
if ( pView->PickObj(aPnt, pPickObj, pPV) )
{
if (pRefObj != pPickObj)
{
pRefObj = pPickObj;
pUserMarker->SetXPolyPolygon(pRefObj, pView->GetPageViewPvNum(0));
pUserMarker->Show();
}
}
else
{
pRefObj = NULL;
pUserMarker->Hide();
}
return TRUE;
}
/*************************************************************************
|*
|* MouseButtonUp-event
|*
\************************************************************************/
BOOL FuDisplayOrder::MouseButtonUp(const MouseEvent& rMEvt)
{
// #95491# remember button state for creation of own MouseEvents
SetMouseButtonCode(rMEvt.GetButtons());
SdrPageView* pPV = NULL;
Point aPnt( pWindow->PixelToLogic( rMEvt.GetPosPixel() ) );
USHORT nHitLog = USHORT ( pWindow->PixelToLogic(Size(HITPIX,0)).Width() );
if ( pView->PickObj(aPnt, pRefObj, pPV) )
{
if (nSlotId == SID_BEFORE_OBJ)
{
pView->PutMarkedInFrontOfObj(pRefObj);
}
else
{
pView->PutMarkedBehindObj(pRefObj);
}
}
pViewShell->Cancel();
return TRUE;
}
/*************************************************************************
|*
|* Function aktivieren
|*
\************************************************************************/
void FuDisplayOrder::Activate()
{
aPtr = pWindow->GetPointer();
pWindow->SetPointer( Pointer( POINTER_REFHAND ) );
if (pUserMarker)
{
pUserMarker->Show();
}
}
/*************************************************************************
|*
|* Function deaktivieren
|*
\************************************************************************/
void FuDisplayOrder::Deactivate()
{
if (pUserMarker)
{
pUserMarker->Hide();
}
pWindow->SetPointer( aPtr );
}
} // end of namespace sd
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fusearch.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: kz $ $Date: 2007-05-10 15:31:23 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "fusearch.hxx"
#include <sfx2/viewfrm.hxx>
#include <svx/svxids.hrc>
#include <sfx2/srchitem.hxx>
#include <svx/srchdlg.hxx>
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef SD_FU_POOR_HXX
#include "fupoor.hxx"
#endif
#ifndef SD_FU_SPELL_HXX
#include "fuspell.hxx" // wegen SidArraySpell[]
#endif
#ifndef SD_WINDOW_SHELL_HXX
#include "Window.hxx"
#endif
#include "drawdoc.hxx"
#include "app.hrc"
#include "app.hxx"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_OUTLINER_HXX
#include "Outliner.hxx"
#endif
#ifndef SD_DRAW_VIEW_SHELL_HXX
#include "DrawViewShell.hxx"
#endif
#ifndef SD_OUTLINE_VIEW_SHELL_HXX
#include "OutlineViewShell.hxx"
#endif
#ifndef SD_VIEW_SHELL_BASE_HXX
#include "ViewShellBase.hxx"
#endif
class SfxRequest;
namespace sd {
TYPEINIT1( FuSearch, FuPoor );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuSearch::FuSearch (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq )
: FuPoor(pViewSh, pWin, pView, pDoc, rReq),
pSdOutliner(NULL),
bOwnOutliner(FALSE)
{
}
FunctionReference FuSearch::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
FunctionReference xFunc( new FuSearch( pViewSh, pWin, pView, pDoc, rReq ) );
xFunc->DoExecute(rReq);
return xFunc;
}
void FuSearch::DoExecute( SfxRequest& )
{
mpViewShell->GetViewFrame()->GetBindings().Invalidate( SidArraySpell );
if ( mpViewShell->ISA(DrawViewShell) )
{
bOwnOutliner = TRUE;
pSdOutliner = new ::sd::Outliner( mpDoc, OUTLINERMODE_TEXTOBJECT );
}
else if ( mpViewShell->ISA(OutlineViewShell) )
{
bOwnOutliner = FALSE;
pSdOutliner = mpDoc->GetOutliner();
}
if (pSdOutliner)
pSdOutliner->PrepareSpelling();
}
/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/
FuSearch::~FuSearch()
{
if ( ! mpDocSh->IsInDestruction() && mpDocSh->GetViewShell()!=NULL)
mpDocSh->GetViewShell()->GetViewFrame()->GetBindings().Invalidate( SidArraySpell );
if (pSdOutliner)
pSdOutliner->EndSpelling();
if (bOwnOutliner)
delete pSdOutliner;
}
/*************************************************************************
|*
|* Suchen&Ersetzen
|*
\************************************************************************/
void FuSearch::SearchAndReplace( const SvxSearchItem* pSearchItem )
{
ViewShellBase* pBase = PTR_CAST(ViewShellBase, SfxViewShell::Current());
ViewShell* pViewShell = NULL;
if (pBase != NULL)
pViewShell = pBase->GetMainViewShell().get();
if (pViewShell != NULL)
{
if ( pSdOutliner && pViewShell->ISA(DrawViewShell) && !bOwnOutliner )
{
pSdOutliner->EndSpelling();
bOwnOutliner = TRUE;
pSdOutliner = new ::sd::Outliner( mpDoc, OUTLINERMODE_TEXTOBJECT );
pSdOutliner->PrepareSpelling();
}
else if ( pSdOutliner && pViewShell->ISA(OutlineViewShell) && bOwnOutliner )
{
pSdOutliner->EndSpelling();
delete pSdOutliner;
bOwnOutliner = FALSE;
pSdOutliner = mpDoc->GetOutliner();
pSdOutliner->PrepareSpelling();
}
if (pSdOutliner)
{
BOOL bEndSpelling = pSdOutliner->StartSearchAndReplace(pSearchItem);
if (bEndSpelling)
{
pSdOutliner->EndSpelling();
pSdOutliner->PrepareSpelling();
}
}
}
}
} // end of namespace sd
<commit_msg>INTEGRATION: CWS changefileheader (1.15.220); FILE MERGED 2008/04/01 15:34:44 thb 1.15.220.3: #i85898# Stripping all external header guards 2008/04/01 12:38:56 thb 1.15.220.2: #i85898# Stripping all external header guards 2008/03/31 13:58:06 rt 1.15.220.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fusearch.cxx,v $
* $Revision: 1.16 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "fusearch.hxx"
#include <sfx2/viewfrm.hxx>
#include <svx/svxids.hrc>
#include <sfx2/srchitem.hxx>
#include <svx/srchdlg.hxx>
#include <sfx2/bindings.hxx>
#include "fupoor.hxx"
#include "fuspell.hxx" // wegen SidArraySpell[]
#ifndef SD_WINDOW_SHELL_HXX
#include "Window.hxx"
#endif
#include "drawdoc.hxx"
#include "app.hrc"
#include "app.hxx"
#include "View.hxx"
#include "Outliner.hxx"
#include "DrawViewShell.hxx"
#include "OutlineViewShell.hxx"
#include "ViewShellBase.hxx"
class SfxRequest;
namespace sd {
TYPEINIT1( FuSearch, FuPoor );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuSearch::FuSearch (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq )
: FuPoor(pViewSh, pWin, pView, pDoc, rReq),
pSdOutliner(NULL),
bOwnOutliner(FALSE)
{
}
FunctionReference FuSearch::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
FunctionReference xFunc( new FuSearch( pViewSh, pWin, pView, pDoc, rReq ) );
xFunc->DoExecute(rReq);
return xFunc;
}
void FuSearch::DoExecute( SfxRequest& )
{
mpViewShell->GetViewFrame()->GetBindings().Invalidate( SidArraySpell );
if ( mpViewShell->ISA(DrawViewShell) )
{
bOwnOutliner = TRUE;
pSdOutliner = new ::sd::Outliner( mpDoc, OUTLINERMODE_TEXTOBJECT );
}
else if ( mpViewShell->ISA(OutlineViewShell) )
{
bOwnOutliner = FALSE;
pSdOutliner = mpDoc->GetOutliner();
}
if (pSdOutliner)
pSdOutliner->PrepareSpelling();
}
/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/
FuSearch::~FuSearch()
{
if ( ! mpDocSh->IsInDestruction() && mpDocSh->GetViewShell()!=NULL)
mpDocSh->GetViewShell()->GetViewFrame()->GetBindings().Invalidate( SidArraySpell );
if (pSdOutliner)
pSdOutliner->EndSpelling();
if (bOwnOutliner)
delete pSdOutliner;
}
/*************************************************************************
|*
|* Suchen&Ersetzen
|*
\************************************************************************/
void FuSearch::SearchAndReplace( const SvxSearchItem* pSearchItem )
{
ViewShellBase* pBase = PTR_CAST(ViewShellBase, SfxViewShell::Current());
ViewShell* pViewShell = NULL;
if (pBase != NULL)
pViewShell = pBase->GetMainViewShell().get();
if (pViewShell != NULL)
{
if ( pSdOutliner && pViewShell->ISA(DrawViewShell) && !bOwnOutliner )
{
pSdOutliner->EndSpelling();
bOwnOutliner = TRUE;
pSdOutliner = new ::sd::Outliner( mpDoc, OUTLINERMODE_TEXTOBJECT );
pSdOutliner->PrepareSpelling();
}
else if ( pSdOutliner && pViewShell->ISA(OutlineViewShell) && bOwnOutliner )
{
pSdOutliner->EndSpelling();
delete pSdOutliner;
bOwnOutliner = FALSE;
pSdOutliner = mpDoc->GetOutliner();
pSdOutliner->PrepareSpelling();
}
if (pSdOutliner)
{
BOOL bEndSpelling = pSdOutliner->StartSearchAndReplace(pSearchItem);
if (bEndSpelling)
{
pSdOutliner->EndSpelling();
pSdOutliner->PrepareSpelling();
}
}
}
}
} // end of namespace sd
<|endoftext|>
|
<commit_before><commit_msg>Fix ruler to not generate negative left indent<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: grviewsh.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: ka $ $Date: 2001-10-22 13:36:57 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _SD_GRVIEWSH_HXX
#include "grviewsh.hxx"
#endif
/*************************************************************************
|*
|* Standard-Konstruktor
|*
\************************************************************************/
SdGraphicViewShell::SdGraphicViewShell( SfxViewFrame* pFrame, SfxViewShell *pOldShell ) :
SdDrawViewShell( pFrame, pOldShell )
{
//Construct( pDocSh );
}
/*************************************************************************
|*
|* Copy-Konstruktor
|*
\************************************************************************/
SdGraphicViewShell::SdGraphicViewShell(SfxViewFrame* pFrame,
const SdDrawViewShell& rShell) :
SdDrawViewShell( pFrame, rShell )
{
//Construct( pDocSh );
}
/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/
SdGraphicViewShell::~SdGraphicViewShell()
{
}
/*************************************************************************
|*
|* gemeinsamer Initialisierungsanteil der beiden Konstruktoren
|*
\************************************************************************/
void SdGraphicViewShell::Construct()
{
// Shells fuer Object Bars erzeugen
//SfxShell* pObjBarShell = new SdDrawStdObjectBar(this, pDrView);
//aShellTable.Insert(RID_DRAW_OBJ_TOOLBOX, pObjBarShell);
// ObjectBar einschalten
//SwitchObjectBar(RID_DRAW_OBJ_TOOLBOX);
aPageBtn.Hide();
aMasterPageBtn.Hide();
aLayerBtn.Hide();
}
<commit_msg>INTEGRATION: CWS impress1 (1.2.238); FILE MERGED 2004/01/09 14:52:35 af 1.2.238.4: #111996# Using the FrameView directly in the constructors of the view shells. 2003/12/04 09:22:33 af 1.2.238.3: #111996# Re-inserted the pOldShell argument to the constructor. 2003/09/24 16:08:54 af 1.2.238.2: #111996# Support of new member meShellType. 2003/09/17 08:17:06 af 1.2.238.1: #111996# Transition to stacked sub-shells. Introduction of namespace sd.<commit_after>/*************************************************************************
*
* $RCSfile: grviewsh.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2004-01-20 12:50:36 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "GraphicViewShell.hxx"
namespace sd {
/*************************************************************************
|*
|* Standard-Konstruktor
|*
\************************************************************************/
GraphicViewShell::GraphicViewShell (
SfxViewFrame* pFrame,
ViewShellBase& rViewShellBase,
FrameView* pFrameView)
: DrawViewShell (pFrame, rViewShellBase, PK_STANDARD, pFrameView)
{
//Construct( pDocSh );
meShellType = ST_DRAW;
}
/*************************************************************************
|*
|* Copy-Konstruktor
|*
\************************************************************************/
GraphicViewShell::GraphicViewShell(SfxViewFrame* pFrame,
const DrawViewShell& rShell) :
DrawViewShell( pFrame, rShell )
{
//Construct( pDocSh );
meShellType = ST_DRAW;
}
/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/
GraphicViewShell::~GraphicViewShell()
{
}
/*************************************************************************
|*
|* gemeinsamer Initialisierungsanteil der beiden Konstruktoren
|*
\************************************************************************/
void GraphicViewShell::Construct()
{
// Shells fuer Object Bars erzeugen
//SfxShell* pObjBarShell = new SdDrawStdObjectBar(this, pDrView);
//aShellTable.Insert(RID_DRAW_OBJ_TOOLBOX, pObjBarShell);
// ObjectBar einschalten
//SwitchObjectBar(RID_DRAW_OBJ_TOOLBOX);
aPageBtn.Hide();
aMasterPageBtn.Hide();
aLayerBtn.Hide();
}
} // end of namespace sd
<|endoftext|>
|
<commit_before>/* Copyright 2015 CyberTech Labs Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
#include "src/gamepadConnection.h"
#include <QtCore/QStringList>
#include <QsLog.h>
using namespace trikNetwork;
GamepadConnection::GamepadConnection()
: Connection(Protocol::endOfLineSeparator, Heartbeat::dontUse)
{
}
void GamepadConnection::processData(const QByteArray &data)
{
const QString message(data);
QStringList const cmd = message.split(" ", QString::SkipEmptyParts);
const QString commandName = cmd.at(0).trimmed();
if (commandName == "pad") {
const int padId = cmd.at(1).trimmed().toInt();
if (cmd.at(2).trimmed() == "up") {
emit padUp(padId);
} else {
const int x = cmd.at(2).trimmed().toInt();
const int y = cmd.at(3).trimmed().toInt();
emit pad(padId, x, y);
}
} else if (commandName == "btn") {
const int buttonCode = cmd.at(1).trimmed().toInt();
emit button(buttonCode, 1);
} else if (commandName == "wheel") {
const int perc = cmd.at(1).trimmed().toInt();
emit wheel(perc);
} else {
QLOG_ERROR() << "Gamepad: unknown command" << commandName;
}
}
<commit_msg>Added button down/button up handling to gamepad<commit_after>/* Copyright 2015 CyberTech Labs Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
#include "src/gamepadConnection.h"
#include <QtCore/QStringList>
#include <QsLog.h>
using namespace trikNetwork;
GamepadConnection::GamepadConnection()
: Connection(Protocol::endOfLineSeparator, Heartbeat::dontUse)
{
}
void GamepadConnection::processData(const QByteArray &data)
{
const QString message(data);
QStringList const cmd = message.split(" ", QString::SkipEmptyParts);
const QString commandName = cmd.at(0).trimmed();
if (commandName == "pad") {
const int padId = cmd.at(1).trimmed().toInt();
if (cmd.at(2).trimmed() == "up") {
emit padUp(padId);
} else {
const int x = cmd.at(2).trimmed().toInt();
const int y = cmd.at(3).trimmed().toInt();
emit pad(padId, x, y);
}
} else if (commandName == "btn") {
const int buttonCode = cmd.at(1).trimmed().toInt();
int state = 1;
if (cmd.length() > 2) {
state = cmd.at(2) == "down" ? 1 : 0;
}
emit button(buttonCode, state);
} else if (commandName == "wheel") {
const int perc = cmd.at(1).trimmed().toInt();
emit wheel(perc);
} else {
QLOG_ERROR() << "Gamepad: unknown command" << commandName;
}
}
<|endoftext|>
|
<commit_before>/// \file
/// \ingroup tutorial_hist
/// \notebook
/// Palette coloring for 2D histograms' stack is activated thanks to the option `PFC`
/// (Palette Fill Color).
/// When this option is given to `THStack::Draw` the histograms in the
/// `THStack` get their color from the current color palette defined by
/// `gStyle->SetPalette(...)`. The color is determined according to the number of
/// histograms.
///
/// In this example four 2D histograms are displayed with palette coloring.
/// The color of each graph is picked inside the palette number 1.
///
/// \macro_image
/// \macro_code
///
/// \author Olivier Couet
void thstack2palettecolor () {
gStyle->SetPalette(1);
TH2F * h1 = new TH2F("h1","h1",20,0,6,20,-4,4);
TH2F * h2 = new TH2F("h2","h1",20,0,6,20,-4,4);
TH2F * h3 = new TH2F("h3","h1",20,0,6,20,-4,4);
TH2F * h4 = new TH2F("h4","h1",20,0,6,20,-4,4);
TH2F * h5 = new TH2F("h5","h1",20,0,6,20,-4,4);
h2->Fill(2.,0.,5);
h3->Fill(3.,0.,10);
h4->Fill(4.,0.,15);
h5->Fill(5.,0.,20);
THStack * hs = new THStack("hs","Test of palette colored lego stack");
hs->Add(h1);
hs->Add(h2);
hs->Add(h3);
hs->Add(h4);
hs->Add(h5);
hs->Draw("0lego1 PFC");
}
<commit_msg>modernise example<commit_after>/// \file
/// \ingroup tutorial_hist
/// \notebook
/// Palette coloring for 2D histograms' stack is activated thanks to the option `PFC`
/// (Palette Fill Color).
/// When this option is given to `THStack::Draw` the histograms in the
/// `THStack` get their color from the current color palette defined by
/// `gStyle->SetPalette(...)`. The color is determined according to the number of
/// histograms.
///
/// In this example four 2D histograms are displayed with palette coloring.
/// The color of each graph is picked inside the palette number 1.
///
/// \macro_image
/// \macro_code
///
/// \author Olivier Couet
void thstack2palettecolor () {
gStyle->SetPalette(1);
auto h1 = new TH2F("h1","h1",20,0,6,20,-4,4);
auto h2 = new TH2F("h2","h1",20,0,6,20,-4,4);
auto h3 = new TH2F("h3","h1",20,0,6,20,-4,4);
auto h4 = new TH2F("h4","h1",20,0,6,20,-4,4);
auto h5 = new TH2F("h5","h1",20,0,6,20,-4,4);
h2->Fill(2.,0.,5);
h3->Fill(3.,0.,10);
h4->Fill(4.,0.,15);
h5->Fill(5.,0.,20);
auto hs = new THStack("hs","Test of palette colored lego stack");
hs->Add(h1);
hs->Add(h2);
hs->Add(h3);
hs->Add(h4);
hs->Add(h5);
hs->Draw("0lego1 PFC");
}
<|endoftext|>
|
<commit_before>#include <glib/gstdio.h>
#include <fstream>
#include <iostream>
#include "settings.h"
using namespace AhoViewer;
using namespace AhoViewer::Booru;
#include "config.h"
SettingsManager AhoViewer::Settings;
SettingsManager::SettingsManager()
: ConfigPath(Glib::build_filename(Glib::get_user_config_dir(), PACKAGE)),
ConfigFilePath(Glib::build_filename(ConfigPath, PACKAGE ".cfg")),
BooruPath(Glib::build_filename(ConfigPath, "booru")),
FavoriteTagsPath(Glib::build_filename(ConfigPath, "favorite-tags")),
// Defaults {{{
DefaultBools(
{
{ "AutoOpenArchive", true },
{ "MangaMode", true },
{ "RememberLastFile", true },
{ "RememberLastSavePath", true },
{ "SaveThumbnails", true },
{ "StartFullscreen", false },
{ "StoreRecentFiles", true },
{ "SmartNavigation", false },
{ "BooruBrowserVisible", true },
{ "MenuBarVisible", true },
{ "ScrollbarsVisible", true },
{ "StatusBarVisible", true },
{ "ThumbnailBarVisible", false },
{ "HideAll", false },
{ "HideAllFullscreen", true },
{ "RememberWindowSize", true },
{ "RememberWindowPos", true },
}),
DefaultInts(
{
{ "ArchiveIndex", -1 },
{ "CacheSize", 2 },
{ "SlideshowDelay", 5 },
{ "CursorHideDelay", 2 },
{ "TagViewPosition", 560 },
{ "SelectedBooru", 0 },
{ "BooruLimit", 50 },
{ "BooruWidth", -1 },
}),
DefaultStrings(
{
{ "TitleFormat", "[%i / %c] %f - %p" },
}),
DefaultSites(
{
std::make_tuple("Danbooru", "https://danbooru.donmai.us", Site::Type::DANBOORU, "", ""),
std::make_tuple("Gelbooru", "https://gelbooru.com", Site::Type::GELBOORU, "", ""),
std::make_tuple("Konachan", "https://konachan.com", Site::Type::MOEBOORU, "", ""),
std::make_tuple("yande.re", "https://yande.re", Site::Type::MOEBOORU, "", ""),
std::make_tuple("Safebooru", "https://safebooru.org", Site::Type::GELBOORU, "", ""),
}),
DefaultKeybindings(
{
{
"File",
{
{ "OpenFile", "<Primary>o" },
{ "Preferences", "p" },
{ "Close", "<Primary>w" },
{ "Quit", "<Primary>q" },
}
},
{
"ViewMode",
{
{ "ToggleMangaMode", "g" },
{ "AutoFitMode", "a" },
{ "FitWidthMode", "w" },
{ "FitHeightMode", "h" },
{ "ManualZoomMode", "m" },
}
},
{
"UserInterface",
{
{ "ToggleFullscreen", "f" },
{ "ToggleMenuBar", "<Primary>m" },
{ "ToggleStatusBar", "<Primary>b" },
{ "ToggleScrollbars", "<Primary>l" },
{ "ToggleThumbnailBar", "t" },
{ "ToggleBooruBrowser", "b" },
{ "ToggleHideAll", "i" },
}
},
{
"Zoom",
{
{ "ZoomIn", "<Primary>equal" },
{ "ZoomOut", "<Primary>minus" },
{ "ResetZoom", "<Primary>0" },
}
},
{
"Navigation",
{
{ "NextImage", "Page_Down" },
{ "PreviousImage", "Page_Up" },
{ "FirstImage", "Home" },
{ "LastImage", "End" },
{ "ToggleSlideshow", "s" },
}
},
{
"Scroll",
{
{ "ScrollUp", "Up" },
{ "ScrollDown", "Down" },
{ "ScrollLeft", "Left" },
{ "ScrollRight", "Right" },
}
},
{
"BooruBrowser",
{
{ "NewTab", "<Primary>t" },
{ "SaveImage", "<Primary>s" },
{ "SaveImages", "<Primary><Shift>s" },
{ "ViewPost", "<Primary><Shift>o" },
{ "CopyImageURL", "y" },
{ "CopyPostURL", "<Primary>y" },
}
}
}),
DefaultBGColor("#161616")
// }}}
{
Config.setTabWidth(4); // this is very important
if (Glib::file_test(ConfigFilePath, Glib::FILE_TEST_EXISTS))
{
try
{
Config.readFile(ConfigFilePath.c_str());
}
catch (const libconfig::ParseException &ex)
{
std::cerr << "libconfig::Config.readFile: " << ex.what() << std::endl;
}
}
if (!Glib::file_test(BooruPath, Glib::FILE_TEST_EXISTS))
g_mkdir_with_parents(BooruPath.c_str(), 0700);
if (Glib::file_test(FavoriteTagsPath, Glib::FILE_TEST_EXISTS))
{
std::ifstream ifs(FavoriteTagsPath);
if (ifs)
std::copy(std::istream_iterator<std::string>(ifs),
std::istream_iterator<std::string>(),
std::inserter(m_FavoriteTags, m_FavoriteTags.begin()));
}
load_keybindings();
}
SettingsManager::~SettingsManager()
{
save_sites();
try
{
Config.writeFile(ConfigFilePath.c_str());
}
catch (const libconfig::FileIOException &ex)
{
std::cerr << "libconfig::Config.writeFile: " << ex.what() << std::endl;
}
if (!m_FavoriteTags.empty())
{
std::ofstream ofs(FavoriteTagsPath);
if (ofs)
std::copy(m_FavoriteTags.begin(), m_FavoriteTags.end(),
std::ostream_iterator<std::string>(ofs, "\n"));
}
else if (Glib::file_test(FavoriteTagsPath, Glib::FILE_TEST_EXISTS))
{
g_unlink(FavoriteTagsPath.c_str());
}
}
bool SettingsManager::get_bool(const std::string &key) const
{
if (Config.exists(key))
return Config.lookup(key);
return DefaultBools.at(key);
}
int SettingsManager::get_int(const std::string &key) const
{
if (Config.exists(key))
return Config.lookup(key);
return DefaultInts.at(key);
}
std::string SettingsManager::get_string(const std::string &key) const
{
if (Config.exists(key))
return static_cast<const char*>(Config.lookup(key));
else if (DefaultStrings.find(key) != DefaultStrings.end())
return DefaultStrings.at(key);
return "";
}
std::vector<std::shared_ptr<Site>>& SettingsManager::get_sites()
{
if (m_Sites.size())
{
return m_Sites;
}
else if (Config.exists("Sites"))
{
const Setting &sites = Config.lookup("Sites");
if (sites.getLength() > 0)
{
for (size_t i = 0; i < static_cast<size_t>(sites.getLength()); ++i)
{
const Setting &s = sites[i];
std::string name = s.exists("name") ? s["name"] : "",
url = s.exists("url") ? s["url"] : "",
username = s.exists("username") ? s["username"] : "",
password = s.exists("password") ? s["password"] : "";
m_Sites.push_back(
Site::create(name,
url,
static_cast<Site::Type>(static_cast<int>(s["type"])),
username,
password));
}
return m_Sites;
}
}
for (const SiteTuple &s : DefaultSites)
m_Sites.push_back(Site::create(std::get<0>(s),
std::get<1>(s),
std::get<2>(s),
std::get<3>(s),
std::get<4>(s)));
return m_Sites;
}
bool SettingsManager::get_geometry(int &x, int &y, int &w, int &h) const
{
if (Config.lookupValue("Geometry.x", x) && Config.lookupValue("Geometry.y", y) &&
Config.lookupValue("Geometry.w", w) && Config.lookupValue("Geometry.h", h))
{
return true;
}
return false;
}
void SettingsManager::set_geometry(const int x, const int y, const int w, const int h)
{
if (!Config.exists("Geometry"))
Config.getRoot().add("Geometry", Setting::TypeGroup);
Setting &geo = Config.lookup("Geometry");
set("x", x, Setting::TypeInt, geo);
set("y", y, Setting::TypeInt, geo);
set("w", w, Setting::TypeInt, geo);
set("h", h, Setting::TypeInt, geo);
}
std::string SettingsManager::get_keybinding(const std::string &group, const std::string &name) const
{
return m_Keybindings.at(group).at(name);
}
/**
* Clears the first (only) binding that has the same value as value
* Sets the group and name parameters to those of the binding that was cleared
* Returns true if it actually cleared a binding
**/
bool SettingsManager::clear_keybinding(const std::string &value, std::string &group, std::string &name)
{
for (const std::pair<std::string, std::map<std::string, std::string>> &i : m_Keybindings)
{
for (const std::pair<std::string, std::string> &j : i.second)
{
if (j.second == value)
{
group = i.first;
name = j.first;
set_keybinding(group, name, "");
return true;
}
}
}
return false;
}
void SettingsManager::set_keybinding(const std::string &group, const std::string &name, const std::string &value)
{
if (!Config.exists("Keybindings"))
Config.getRoot().add("Keybindings", Setting::TypeGroup);
Setting &keys = Config.lookup("Keybindings");
if (!keys.exists(group))
keys.add(group, Setting::TypeGroup);
set(name, value, Setting::TypeString, keys[group.c_str()]);
m_Keybindings[group][name] = value;
}
std::string SettingsManager::reset_keybinding(const std::string &group, const std::string &name)
{
if (Config.exists("Keybindings"))
{
Setting &keys = Config.lookup("Keybindings");
if (keys.exists(group) && keys[group.c_str()].exists(name))
keys[group.c_str()].remove(name);
}
return m_Keybindings[group][name] = DefaultKeybindings.at(group).at(name);
}
Gdk::Color SettingsManager::get_background_color() const
{
if (Config.exists("BackgroundColor"))
return Gdk::Color(static_cast<const char*>(Config.lookup("BackgroundColor")));
return DefaultBGColor;
}
void SettingsManager::set_background_color(const Gdk::Color &value)
{
set("BackgroundColor", value.to_string());
}
Site::Rating SettingsManager::get_booru_max_rating() const
{
if (Config.exists("BooruMaxRating"))
return Site::Rating(static_cast<int>(Config.lookup("BooruMaxRating")));
return DefaultBooruMaxRating;
}
void SettingsManager::set_booru_max_rating(const Site::Rating value)
{
set("BooruMaxRating", static_cast<int>(value));
}
ImageBox::ZoomMode SettingsManager::get_zoom_mode() const
{
if (Config.exists("ZoomMode"))
return ImageBox::ZoomMode(static_cast<const char*>(Config.lookup("ZoomMode"))[0]);
return DefaultZoomMode;
}
void SettingsManager::set_zoom_mode(const ImageBox::ZoomMode value)
{
set("ZoomMode", std::string(1, static_cast<char>(value)));
}
void SettingsManager::remove(const std::string &key)
{
if (Config.exists(key))
Config.getRoot().remove(key);
}
void SettingsManager::load_keybindings()
{
if (Config.exists("Keybindings"))
{
Setting &keys = Config.lookup("Keybindings");
for (const std::pair<std::string, std::map<std::string, std::string>> &i : DefaultKeybindings)
{
if (keys.exists(i.first))
{
for (const std::pair<std::string, std::string> &j : i.second)
{
if (keys[i.first.c_str()].exists(j.first))
{
m_Keybindings[i.first][j.first] = keys[i.first.c_str()][j.first.c_str()].c_str();
}
else
{
m_Keybindings[i.first][j.first] = DefaultKeybindings.at(i.first).at(j.first);
}
}
}
else
{
m_Keybindings[i.first] = DefaultKeybindings.at(i.first);
}
}
}
else
{
m_Keybindings = DefaultKeybindings;
}
}
void SettingsManager::save_sites()
{
remove("Sites");
Setting &sites = Config.getRoot().add("Sites", Setting::TypeList);
for (const std::shared_ptr<Site> &s : m_Sites)
{
Setting &site = sites.add(Setting::TypeGroup);
set("name", s->get_name(), Setting::TypeString, site);
set("url", s->get_url(), Setting::TypeString, site);
set("type", static_cast<int>(s->get_type()), Setting::TypeInt, site);
set("username", s->get_username(), Setting::TypeString, site);
#ifndef HAVE_LIBSECRET
set("password", s->get_password(), Setting::TypeString, site);
#endif // !HAVE_LIBSECRET
s->cleanup_cookie();
}
}
<commit_msg>settings: Make Gelbooru the default booru site<commit_after>#include <glib/gstdio.h>
#include <fstream>
#include <iostream>
#include "settings.h"
using namespace AhoViewer;
using namespace AhoViewer::Booru;
#include "config.h"
SettingsManager AhoViewer::Settings;
SettingsManager::SettingsManager()
: ConfigPath(Glib::build_filename(Glib::get_user_config_dir(), PACKAGE)),
ConfigFilePath(Glib::build_filename(ConfigPath, PACKAGE ".cfg")),
BooruPath(Glib::build_filename(ConfigPath, "booru")),
FavoriteTagsPath(Glib::build_filename(ConfigPath, "favorite-tags")),
// Defaults {{{
DefaultBools(
{
{ "AutoOpenArchive", true },
{ "MangaMode", true },
{ "RememberLastFile", true },
{ "RememberLastSavePath", true },
{ "SaveThumbnails", true },
{ "StartFullscreen", false },
{ "StoreRecentFiles", true },
{ "SmartNavigation", false },
{ "BooruBrowserVisible", true },
{ "MenuBarVisible", true },
{ "ScrollbarsVisible", true },
{ "StatusBarVisible", true },
{ "ThumbnailBarVisible", false },
{ "HideAll", false },
{ "HideAllFullscreen", true },
{ "RememberWindowSize", true },
{ "RememberWindowPos", true },
}),
DefaultInts(
{
{ "ArchiveIndex", -1 },
{ "CacheSize", 2 },
{ "SlideshowDelay", 5 },
{ "CursorHideDelay", 2 },
{ "TagViewPosition", 560 },
{ "SelectedBooru", 0 },
{ "BooruLimit", 50 },
{ "BooruWidth", -1 },
}),
DefaultStrings(
{
{ "TitleFormat", "[%i / %c] %f - %p" },
}),
DefaultSites(
{
std::make_tuple("Gelbooru", "https://gelbooru.com", Site::Type::GELBOORU, "", ""),
std::make_tuple("Danbooru", "https://danbooru.donmai.us", Site::Type::DANBOORU, "", ""),
std::make_tuple("Konachan", "https://konachan.com", Site::Type::MOEBOORU, "", ""),
std::make_tuple("yande.re", "https://yande.re", Site::Type::MOEBOORU, "", ""),
std::make_tuple("Safebooru", "https://safebooru.org", Site::Type::GELBOORU, "", ""),
}),
DefaultKeybindings(
{
{
"File",
{
{ "OpenFile", "<Primary>o" },
{ "Preferences", "p" },
{ "Close", "<Primary>w" },
{ "Quit", "<Primary>q" },
}
},
{
"ViewMode",
{
{ "ToggleMangaMode", "g" },
{ "AutoFitMode", "a" },
{ "FitWidthMode", "w" },
{ "FitHeightMode", "h" },
{ "ManualZoomMode", "m" },
}
},
{
"UserInterface",
{
{ "ToggleFullscreen", "f" },
{ "ToggleMenuBar", "<Primary>m" },
{ "ToggleStatusBar", "<Primary>b" },
{ "ToggleScrollbars", "<Primary>l" },
{ "ToggleThumbnailBar", "t" },
{ "ToggleBooruBrowser", "b" },
{ "ToggleHideAll", "i" },
}
},
{
"Zoom",
{
{ "ZoomIn", "<Primary>equal" },
{ "ZoomOut", "<Primary>minus" },
{ "ResetZoom", "<Primary>0" },
}
},
{
"Navigation",
{
{ "NextImage", "Page_Down" },
{ "PreviousImage", "Page_Up" },
{ "FirstImage", "Home" },
{ "LastImage", "End" },
{ "ToggleSlideshow", "s" },
}
},
{
"Scroll",
{
{ "ScrollUp", "Up" },
{ "ScrollDown", "Down" },
{ "ScrollLeft", "Left" },
{ "ScrollRight", "Right" },
}
},
{
"BooruBrowser",
{
{ "NewTab", "<Primary>t" },
{ "SaveImage", "<Primary>s" },
{ "SaveImages", "<Primary><Shift>s" },
{ "ViewPost", "<Primary><Shift>o" },
{ "CopyImageURL", "y" },
{ "CopyPostURL", "<Primary>y" },
}
}
}),
DefaultBGColor("#161616")
// }}}
{
Config.setTabWidth(4); // this is very important
if (Glib::file_test(ConfigFilePath, Glib::FILE_TEST_EXISTS))
{
try
{
Config.readFile(ConfigFilePath.c_str());
}
catch (const libconfig::ParseException &ex)
{
std::cerr << "libconfig::Config.readFile: " << ex.what() << std::endl;
}
}
if (!Glib::file_test(BooruPath, Glib::FILE_TEST_EXISTS))
g_mkdir_with_parents(BooruPath.c_str(), 0700);
if (Glib::file_test(FavoriteTagsPath, Glib::FILE_TEST_EXISTS))
{
std::ifstream ifs(FavoriteTagsPath);
if (ifs)
std::copy(std::istream_iterator<std::string>(ifs),
std::istream_iterator<std::string>(),
std::inserter(m_FavoriteTags, m_FavoriteTags.begin()));
}
load_keybindings();
}
SettingsManager::~SettingsManager()
{
save_sites();
try
{
Config.writeFile(ConfigFilePath.c_str());
}
catch (const libconfig::FileIOException &ex)
{
std::cerr << "libconfig::Config.writeFile: " << ex.what() << std::endl;
}
if (!m_FavoriteTags.empty())
{
std::ofstream ofs(FavoriteTagsPath);
if (ofs)
std::copy(m_FavoriteTags.begin(), m_FavoriteTags.end(),
std::ostream_iterator<std::string>(ofs, "\n"));
}
else if (Glib::file_test(FavoriteTagsPath, Glib::FILE_TEST_EXISTS))
{
g_unlink(FavoriteTagsPath.c_str());
}
}
bool SettingsManager::get_bool(const std::string &key) const
{
if (Config.exists(key))
return Config.lookup(key);
return DefaultBools.at(key);
}
int SettingsManager::get_int(const std::string &key) const
{
if (Config.exists(key))
return Config.lookup(key);
return DefaultInts.at(key);
}
std::string SettingsManager::get_string(const std::string &key) const
{
if (Config.exists(key))
return static_cast<const char*>(Config.lookup(key));
else if (DefaultStrings.find(key) != DefaultStrings.end())
return DefaultStrings.at(key);
return "";
}
std::vector<std::shared_ptr<Site>>& SettingsManager::get_sites()
{
if (m_Sites.size())
{
return m_Sites;
}
else if (Config.exists("Sites"))
{
const Setting &sites = Config.lookup("Sites");
if (sites.getLength() > 0)
{
for (size_t i = 0; i < static_cast<size_t>(sites.getLength()); ++i)
{
const Setting &s = sites[i];
std::string name = s.exists("name") ? s["name"] : "",
url = s.exists("url") ? s["url"] : "",
username = s.exists("username") ? s["username"] : "",
password = s.exists("password") ? s["password"] : "";
m_Sites.push_back(
Site::create(name,
url,
static_cast<Site::Type>(static_cast<int>(s["type"])),
username,
password));
}
return m_Sites;
}
}
for (const SiteTuple &s : DefaultSites)
m_Sites.push_back(Site::create(std::get<0>(s),
std::get<1>(s),
std::get<2>(s),
std::get<3>(s),
std::get<4>(s)));
return m_Sites;
}
bool SettingsManager::get_geometry(int &x, int &y, int &w, int &h) const
{
if (Config.lookupValue("Geometry.x", x) && Config.lookupValue("Geometry.y", y) &&
Config.lookupValue("Geometry.w", w) && Config.lookupValue("Geometry.h", h))
{
return true;
}
return false;
}
void SettingsManager::set_geometry(const int x, const int y, const int w, const int h)
{
if (!Config.exists("Geometry"))
Config.getRoot().add("Geometry", Setting::TypeGroup);
Setting &geo = Config.lookup("Geometry");
set("x", x, Setting::TypeInt, geo);
set("y", y, Setting::TypeInt, geo);
set("w", w, Setting::TypeInt, geo);
set("h", h, Setting::TypeInt, geo);
}
std::string SettingsManager::get_keybinding(const std::string &group, const std::string &name) const
{
return m_Keybindings.at(group).at(name);
}
/**
* Clears the first (only) binding that has the same value as value
* Sets the group and name parameters to those of the binding that was cleared
* Returns true if it actually cleared a binding
**/
bool SettingsManager::clear_keybinding(const std::string &value, std::string &group, std::string &name)
{
for (const std::pair<std::string, std::map<std::string, std::string>> &i : m_Keybindings)
{
for (const std::pair<std::string, std::string> &j : i.second)
{
if (j.second == value)
{
group = i.first;
name = j.first;
set_keybinding(group, name, "");
return true;
}
}
}
return false;
}
void SettingsManager::set_keybinding(const std::string &group, const std::string &name, const std::string &value)
{
if (!Config.exists("Keybindings"))
Config.getRoot().add("Keybindings", Setting::TypeGroup);
Setting &keys = Config.lookup("Keybindings");
if (!keys.exists(group))
keys.add(group, Setting::TypeGroup);
set(name, value, Setting::TypeString, keys[group.c_str()]);
m_Keybindings[group][name] = value;
}
std::string SettingsManager::reset_keybinding(const std::string &group, const std::string &name)
{
if (Config.exists("Keybindings"))
{
Setting &keys = Config.lookup("Keybindings");
if (keys.exists(group) && keys[group.c_str()].exists(name))
keys[group.c_str()].remove(name);
}
return m_Keybindings[group][name] = DefaultKeybindings.at(group).at(name);
}
Gdk::Color SettingsManager::get_background_color() const
{
if (Config.exists("BackgroundColor"))
return Gdk::Color(static_cast<const char*>(Config.lookup("BackgroundColor")));
return DefaultBGColor;
}
void SettingsManager::set_background_color(const Gdk::Color &value)
{
set("BackgroundColor", value.to_string());
}
Site::Rating SettingsManager::get_booru_max_rating() const
{
if (Config.exists("BooruMaxRating"))
return Site::Rating(static_cast<int>(Config.lookup("BooruMaxRating")));
return DefaultBooruMaxRating;
}
void SettingsManager::set_booru_max_rating(const Site::Rating value)
{
set("BooruMaxRating", static_cast<int>(value));
}
ImageBox::ZoomMode SettingsManager::get_zoom_mode() const
{
if (Config.exists("ZoomMode"))
return ImageBox::ZoomMode(static_cast<const char*>(Config.lookup("ZoomMode"))[0]);
return DefaultZoomMode;
}
void SettingsManager::set_zoom_mode(const ImageBox::ZoomMode value)
{
set("ZoomMode", std::string(1, static_cast<char>(value)));
}
void SettingsManager::remove(const std::string &key)
{
if (Config.exists(key))
Config.getRoot().remove(key);
}
void SettingsManager::load_keybindings()
{
if (Config.exists("Keybindings"))
{
Setting &keys = Config.lookup("Keybindings");
for (const std::pair<std::string, std::map<std::string, std::string>> &i : DefaultKeybindings)
{
if (keys.exists(i.first))
{
for (const std::pair<std::string, std::string> &j : i.second)
{
if (keys[i.first.c_str()].exists(j.first))
{
m_Keybindings[i.first][j.first] = keys[i.first.c_str()][j.first.c_str()].c_str();
}
else
{
m_Keybindings[i.first][j.first] = DefaultKeybindings.at(i.first).at(j.first);
}
}
}
else
{
m_Keybindings[i.first] = DefaultKeybindings.at(i.first);
}
}
}
else
{
m_Keybindings = DefaultKeybindings;
}
}
void SettingsManager::save_sites()
{
remove("Sites");
Setting &sites = Config.getRoot().add("Sites", Setting::TypeList);
for (const std::shared_ptr<Site> &s : m_Sites)
{
Setting &site = sites.add(Setting::TypeGroup);
set("name", s->get_name(), Setting::TypeString, site);
set("url", s->get_url(), Setting::TypeString, site);
set("type", static_cast<int>(s->get_type()), Setting::TypeInt, site);
set("username", s->get_username(), Setting::TypeString, site);
#ifndef HAVE_LIBSECRET
set("password", s->get_password(), Setting::TypeString, site);
#endif // !HAVE_LIBSECRET
s->cleanup_cookie();
}
}
<|endoftext|>
|
<commit_before><commit_msg>Debug to account for uppercase<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright (C) 2011-2013 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of SLVision
*
* SLVision is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation (FSF), either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
/*
* Daniel Gallardo Grassot
* daniel.gallardo@upf.edu
* Barcelona 2011
*/
#include "Hand.h"
#include "Fiducial.h"
#include "Globals.h"
Hand::Hand(void)
{
Reset();
centroid = cv::Point(-1,-1);
}
Hand::Hand(unsigned long _sessionID, const cv::Point & _centroid, float area)
{
Reset();
sessionID = _sessionID;
centroid = cv::Point(_centroid);
center_hand = cv::Point(_centroid);
this->area = area;
pinch_area = 0;
}
bool Hand::IsItTheSame( cv::Point &point )
{
if(fabsf(insqdist(centroid.x, centroid.y, point.x, point.y)) <= HAND_CENTROID_SIMILARITY)
return true;
return false;
}
void Hand::Reset()
{
sessionID = 0;
startarm = cv::Point(0,0);
center_hand = cv::Point(0,0);
/* fingers[0] = cv::Point(-1,-1);
fingers[1] = cv::Point(-1,-1);
fingers[2] = cv::Point(-1,-1);
fingers[3] = cv::Point(-1,-1);
fingers[4] = cv::Point(-1,-1);*/
is_updated = false;
hull.clear();
blobPath.clear();
defects.clear();
pinch_area = 0;
}
void Hand::UpdateData( cv::Point &point, cv::vector<cv::Point> &path , float area , TouchFinder* tfinder )
{
this->area = area;
is_updated = true;
this->center_hand = cv::Point(point);
this->blobPath = cv::vector<cv::Point>(path);
//******************************************************
//* Find convex Hull
//*******************************************************
hull.clear();
cv::convexHull( cv::Mat(blobPath), hull, false );
//******************************************************
//* Find defects (Hull valleys)
//*******************************************************
defects.clear();
cv::convexityDefects(cv::Mat(blobPath), hull, defects);
//******************************************************
//* Find fingers and startarm
//*******************************************************
//Start arm calculation
auxiliar_distance = 99;
edge_index = -1;
for(unsigned int i = 0; i < defects.size(); i++)
{
temp_dist = IsNearEdge( blobPath[defects[i][1]] );
if( temp_dist < auxiliar_distance)
{
auxiliar_distance = temp_dist;
edge_index = defects[i][1];
}
}
//Check for a propper hand
if(edge_index == -1) //not a hand (misssed arm)
{
is_hand = false;
return;
}
else is_hand = true;
startarm = cv::Point(blobPath[edge_index].x, blobPath[edge_index].y);
///Find further point of the path
further_index = -1;
auxiliar_distance = 0;
for(unsigned int i = 0; i < defects.size(); i++)
{
if(defects[i][1] != edge_index)
{
temp_dist = insqdist(startarm.x, startarm.y, blobPath[defects[i][1]].x, blobPath[defects[i][1]].y);
if(temp_dist > auxiliar_distance)
{
auxiliar_distance = temp_dist;
further_index = defects[i][1];
}
}
}
//This value gonna be used as crop distance
auxiliar_distance = auxiliar_distance /2.0f;
//
if(further_index == -1) //too less points
{
is_hand = false;
return;
}
endarm = cv::Point(blobPath[further_index].x,blobPath[further_index].y);
center_hand.x = 0;
center_hand.y = 0;
finger_candidates.clear();
int q=0;
for(unsigned int i = 0; i < defects.size(); i++)
{
if( insqdist(endarm.x,
endarm.y,
blobPath[defects[i][1]].x,
blobPath[defects[i][1]].y) < auxiliar_distance)
{
center_hand.x += blobPath[defects[i][1]].x;
center_hand.y += blobPath[defects[i][1]].y;
q++;
finger_candidates.push_back(i);
}
if( insqdist(endarm.x,
endarm.y,
blobPath[defects[i][2]].x,
blobPath[defects[i][2]].y) < auxiliar_distance)
{
center_hand.x += blobPath[defects[i][2]].x;
center_hand.y += blobPath[defects[i][2]].y;
q++;
}
}
center_hand.x = (int)floor((float)center_hand.x/(float)q);
center_hand.y = (int)floor((float)center_hand.y/(float)q);
//Check influence_hand_radius
influence_radius = 0;
for(unsigned int i = 0; i < finger_candidates.size(); i++)
{
temp_dist = insqdist(center_hand.x,
center_hand.y,
blobPath[defects[finger_candidates[i]][1]].x,
blobPath[defects[finger_candidates[i]][1]].y);
if( temp_dist > influence_radius)
{
influence_radius = temp_dist;
}
}
//Asign fingers
numfingers =0;
fingers.clear();
for( int i =0; i <finger_candidates.size(); i++)
{
numfingers++;
if(tfinder != NULL)
{
unsigned int candidate = tfinder->GetTouch(this->sessionID, blobPath[defects[finger_candidates[i]][1]].x,blobPath[defects[finger_candidates[i]][1]].y);
fingers.push_back(candidate);
}
}
//Cross_reference_fingers??
pinch_area = 0;
is_updated = true;
}
void Hand::AddPinch( cv::vector<cv::Point> &path, float area )
{
is_updated = true;
int q = 0;
pinch_centre.x = 0;
pinch_centre.y = 0;
for( unsigned int i = 0; i < path.size(); i++)
{
pinch_centre.x += path[i].x;
pinch_centre.y += path[i].y;
q++;
}
pinch_centre.x = (int)floor((float)pinch_centre.x/(float)q);
pinch_centre.y = (int)floor((float)pinch_centre.y/(float)q);
pinch_area = 0;
for( unsigned int i = 0; i < path.size(); i++)
{
temp_dist = insqdist(pinch_centre.x,
pinch_centre.y,
path[i].x,
path[i].y);
if( temp_dist > pinch_area)
{
pinch_area = temp_dist;
}
}
}
float Hand::IsNearEdge( cv::Point & p )
{
float shortest = 9000;
if(p.x < shortest) shortest = (float)p.x;
if(p.y < shortest) shortest = (float)p.y;
if(p.x - Globals::CamSize.width >= 0 && p.x - Globals::CamSize.width < shortest) shortest = (float)(p.x - Globals::CamSize.width);
if(p.y - Globals::CamSize.height >= 0 && p.y - Globals::CamSize.height < shortest) shortest = (float)(p.y - Globals::CamSize.height);
if ( p.x > 10 && p.y > 10 && p.x <= Globals::CamSize.width-10 && p.y <= Globals::CamSize.height-10)
return 99;
return shortest;
}
void Hand::Draw(TouchFinder* tfinder, bool force)
{
if(!force && !is_hand) return;
//draw blob path
for(unsigned int i = 0; i < blobPath.size(); i++)
{
if(i+1 != blobPath.size())
cv::line(Globals::CameraFrame,blobPath[i],blobPath[i+1],cv::Scalar(0,255,255,255),1,CV_AA);
else
cv::line(Globals::CameraFrame,blobPath[i],blobPath[0],cv::Scalar(0,255,255,255),1,CV_AA);
}
//draw startarm and endarm
cv::circle(Globals::CameraFrame,startarm,10,cv::Scalar(255,0,0),5);
cv::circle(Globals::CameraFrame,endarm,10,cv::Scalar(255,0,255),5);
//draw hand influence
cv::circle(Globals::CameraFrame,center_hand,(int)floor(influence_radius),cv::Scalar(0,0,255),3);
//draw fingers
for(int i = 0; i < fingers.size(); i++)
{
Touch* t = tfinder->GetTouch(fingers[i]);
if( t != NULL)
{
cv::circle(Globals::CameraFrame,cv::Point(t->GetX(),t->GetY()),5,cv::Scalar(0,255,0),5);
}
/* if(fingers[i].x != -1)
{
cv::circle(Globals::CameraFrame,fingers[i],5,cv::Scalar(0,255,0),5);
}
*/
}
//draw pinch
if(pinch_area != 0)
{
cv::circle(Globals::CameraFrame,pinch_centre,(int)floor(pinch_area),cv::Scalar(0,255,255),3);
}
}
unsigned long Hand::GetSID()
{
return sessionID;
}
bool Hand::IsValid()
{
return is_hand;
}
bool Hand::IsUpdated()
{
if(is_updated)
{
is_updated = false;
return true;
}
return false;
}<commit_msg>bug solved on the hover fingers<commit_after>/*
* Copyright (C) 2011-2013 Music Technology Group - Universitat Pompeu Fabra
*
* This file is part of SLVision
*
* SLVision is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation (FSF), either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the Affero GNU General Public License
* version 3 along with this program. If not, see http://www.gnu.org/licenses/
*/
/*
* Daniel Gallardo Grassot
* daniel.gallardo@upf.edu
* Barcelona 2011
*/
#include "Hand.h"
#include "Fiducial.h"
#include "Globals.h"
Hand::Hand(void)
{
Reset();
centroid = cv::Point(-1,-1);
}
Hand::Hand(unsigned long _sessionID, const cv::Point & _centroid, float area)
{
Reset();
sessionID = _sessionID;
centroid = cv::Point(_centroid);
center_hand = cv::Point(_centroid);
this->area = area;
pinch_area = 0;
}
bool Hand::IsItTheSame( cv::Point &point )
{
if(fabsf(insqdist(centroid.x, centroid.y, point.x, point.y)) <= HAND_CENTROID_SIMILARITY)
return true;
return false;
}
void Hand::Reset()
{
sessionID = 0;
startarm = cv::Point(0,0);
center_hand = cv::Point(0,0);
/* fingers[0] = cv::Point(-1,-1);
fingers[1] = cv::Point(-1,-1);
fingers[2] = cv::Point(-1,-1);
fingers[3] = cv::Point(-1,-1);
fingers[4] = cv::Point(-1,-1);*/
is_updated = false;
hull.clear();
blobPath.clear();
defects.clear();
pinch_area = 0;
}
void Hand::UpdateData( cv::Point &point, cv::vector<cv::Point> &path , float area , TouchFinder* tfinder )
{
this->area = area;
is_updated = true;
this->center_hand = cv::Point(point);
this->blobPath = cv::vector<cv::Point>(path);
//******************************************************
//* Find convex Hull
//*******************************************************
hull.clear();
cv::convexHull( cv::Mat(blobPath), hull, false );
//******************************************************
//* Find defects (Hull valleys)
//*******************************************************
defects.clear();
cv::convexityDefects(cv::Mat(blobPath), hull, defects);
//******************************************************
//* Find fingers and startarm
//*******************************************************
//Start arm calculation
auxiliar_distance = 99;
edge_index = -1;
for(unsigned int i = 0; i < defects.size(); i++)
{
temp_dist = IsNearEdge( blobPath[defects[i][1]] );
if( temp_dist < auxiliar_distance)
{
auxiliar_distance = temp_dist;
edge_index = defects[i][1];
}
}
//Check for a propper hand
if(edge_index == -1) //not a hand (misssed arm)
{
is_hand = false;
return;
}
else is_hand = true;
startarm = cv::Point(blobPath[edge_index].x, blobPath[edge_index].y);
///Find further point of the path
further_index = -1;
auxiliar_distance = 0;
for(unsigned int i = 0; i < defects.size(); i++)
{
if(defects[i][1] != edge_index)
{
temp_dist = insqdist(startarm.x, startarm.y, blobPath[defects[i][1]].x, blobPath[defects[i][1]].y);
if(temp_dist > auxiliar_distance)
{
auxiliar_distance = temp_dist;
further_index = defects[i][1];
}
}
}
//This value gonna be used as crop distance
auxiliar_distance = auxiliar_distance /2.0f;
//
if(further_index == -1) //too less points
{
is_hand = false;
return;
}
endarm = cv::Point(blobPath[further_index].x,blobPath[further_index].y);
center_hand.x = 0;
center_hand.y = 0;
finger_candidates.clear();
int q=0;
for(unsigned int i = 0; i < defects.size(); i++)
{
if( insqdist(endarm.x,
endarm.y,
blobPath[defects[i][1]].x,
blobPath[defects[i][1]].y) < auxiliar_distance)
{
center_hand.x += blobPath[defects[i][1]].x;
center_hand.y += blobPath[defects[i][1]].y;
q++;
finger_candidates.push_back(i);
}
if( insqdist(endarm.x,
endarm.y,
blobPath[defects[i][2]].x,
blobPath[defects[i][2]].y) < auxiliar_distance)
{
center_hand.x += blobPath[defects[i][2]].x;
center_hand.y += blobPath[defects[i][2]].y;
q++;
}
}
center_hand.x = (int)floor((float)center_hand.x/(float)q);
center_hand.y = (int)floor((float)center_hand.y/(float)q);
//Check influence_hand_radius
influence_radius = 0;
for(unsigned int i = 0; i < finger_candidates.size(); i++)
{
temp_dist = insqdist(center_hand.x,
center_hand.y,
blobPath[defects[finger_candidates[i]][1]].x,
blobPath[defects[finger_candidates[i]][1]].y);
if( temp_dist > influence_radius)
{
influence_radius = temp_dist;
}
}
//Asign fingers
numfingers =0;
fingers.clear();
for( int i =0; i <finger_candidates.size(); i++)
{
numfingers++;
if(tfinder != NULL)
{
unsigned int candidate = tfinder->GetTouch(blobPath[defects[finger_candidates[i]][1]].x,blobPath[defects[finger_candidates[i]][1]].y,this->sessionID);
fingers.push_back(candidate);
}
}
//Cross_reference_fingers??
pinch_area = 0;
is_updated = true;
}
void Hand::AddPinch( cv::vector<cv::Point> &path, float area )
{
is_updated = true;
int q = 0;
pinch_centre.x = 0;
pinch_centre.y = 0;
for( unsigned int i = 0; i < path.size(); i++)
{
pinch_centre.x += path[i].x;
pinch_centre.y += path[i].y;
q++;
}
pinch_centre.x = (int)floor((float)pinch_centre.x/(float)q);
pinch_centre.y = (int)floor((float)pinch_centre.y/(float)q);
pinch_area = 0;
for( unsigned int i = 0; i < path.size(); i++)
{
temp_dist = insqdist(pinch_centre.x,
pinch_centre.y,
path[i].x,
path[i].y);
if( temp_dist > pinch_area)
{
pinch_area = temp_dist;
}
}
}
float Hand::IsNearEdge( cv::Point & p )
{
float shortest = 9000;
if(p.x < shortest) shortest = (float)p.x;
if(p.y < shortest) shortest = (float)p.y;
if(p.x - Globals::CamSize.width >= 0 && p.x - Globals::CamSize.width < shortest) shortest = (float)(p.x - Globals::CamSize.width);
if(p.y - Globals::CamSize.height >= 0 && p.y - Globals::CamSize.height < shortest) shortest = (float)(p.y - Globals::CamSize.height);
if ( p.x > 10 && p.y > 10 && p.x <= Globals::CamSize.width-10 && p.y <= Globals::CamSize.height-10)
return 99;
return shortest;
}
void Hand::Draw(TouchFinder* tfinder, bool force)
{
if(!force && !is_hand) return;
//draw blob path
for(unsigned int i = 0; i < blobPath.size(); i++)
{
if(i+1 != blobPath.size())
cv::line(Globals::CameraFrame,blobPath[i],blobPath[i+1],cv::Scalar(0,255,255,255),1,CV_AA);
else
cv::line(Globals::CameraFrame,blobPath[i],blobPath[0],cv::Scalar(0,255,255,255),1,CV_AA);
}
//draw startarm and endarm
cv::circle(Globals::CameraFrame,startarm,10,cv::Scalar(255,0,0),5);
cv::circle(Globals::CameraFrame,endarm,10,cv::Scalar(255,0,255),5);
//draw hand influence
cv::circle(Globals::CameraFrame,center_hand,(int)floor(influence_radius),cv::Scalar(0,0,255),3);
//draw fingers
for(int i = 0; i < fingers.size(); i++)
{
Touch* t = tfinder->GetTouch(fingers[i]);
if( t != NULL)
{
cv::circle(Globals::CameraFrame,cv::Point(t->GetX(),t->GetY()),5,cv::Scalar(0,255,0),5);
}
/* if(fingers[i].x != -1)
{
cv::circle(Globals::CameraFrame,fingers[i],5,cv::Scalar(0,255,0),5);
}
*/
}
//draw pinch
if(pinch_area != 0)
{
cv::circle(Globals::CameraFrame,pinch_centre,(int)floor(pinch_area),cv::Scalar(0,255,255),3);
}
}
unsigned long Hand::GetSID()
{
return sessionID;
}
bool Hand::IsValid()
{
return is_hand;
}
bool Hand::IsUpdated()
{
if(is_updated)
{
is_updated = false;
return true;
}
return false;
}<|endoftext|>
|
<commit_before>/*
This file is part of the kolab resource - the implementation of the
Kolab storage format. See www.kolab.org for documentation on this.
Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
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 "task.h"
#include <kcal/todo.h>
#include <kdebug.h>
using namespace Kolab;
// Kolab Storage Specification:
// "The priority can be a number between 1 and 5, with 1 being the highest priority."
// iCalendar (RFC 2445):
// "The priority is specified as an integer in the range
// zero to nine. A value of zero specifies an
// undefined priority. A value of one is the
// highest priority. A value of nine is the lowest
// priority."
static int kcalPriorityToKolab( const int kcalPriority )
{
if ( kcalPriority >= 0 && kcalPriority <= 9 ) {
// We'll map undefined (0) to 3 (default)
// 0 1 2 3 4 5 6 7 8 9
static const int priorityMap[10] = { 3, 1, 1, 2, 2, 3, 3, 4, 4, 5 };
return priorityMap[kcalPriority];
}
else {
kWarning() << "Got invalid priority" << kcalPriority;
return 3;
}
}
static int kolabPrioritytoKCal( const int kolabPriority )
{
if ( kolabPriority >= 1 && kolabPriority <= 5 ) {
// 1 2 3 4 5
static const int priorityMap[5] = { 1, 3, 5, 7, 9 };
return priorityMap[kolabPriority - 1];
}
else {
kWarning() << "Got invalid priority" << kolabPriority;
return 5;
}
}
KCal::Todo* Task::xmlToTask( const QString& xml, const QString& tz, KCal::ResourceKolab *res,
const QString& subResource, quint32 sernum )
{
Task task( res, subResource, sernum, tz );
task.load( xml );
KCal::Todo* todo = new KCal::Todo();
task.saveTo( todo );
return todo;
}
QString Task::taskToXML( KCal::Todo* todo, const QString& tz )
{
Task task( 0, QString(), 0, tz, todo );
return task.saveXML();
}
Task::Task( KCal::ResourceKolab *res, const QString &subResource, quint32 sernum,
const QString& tz, KCal::Todo* task )
: Incidence( res, subResource, sernum, tz, task ),
mPriority( 5 ), mPercentCompleted( 0 ),
mStatus( KCal::Incidence::StatusNone ),
mHasStartDate( false ), mHasDueDate( false ),
mHasCompletedDate( false )
{
if ( task )
setFields( task );
}
Task::~Task()
{
}
void Task::setPriority( int priority )
{
mPriority = priority;
}
int Task::priority() const
{
return mPriority;
}
void Task::setPercentCompleted( int percent )
{
mPercentCompleted = percent;
}
int Task::percentCompleted() const
{
return mPercentCompleted;
}
void Task::setStatus( KCal::Incidence::Status status )
{
mStatus = status;
}
KCal::Incidence::Status Task::status() const
{
return mStatus;
}
void Task::setParent( const QString& parentUid )
{
mParent = parentUid;
}
QString Task::parent() const
{
return mParent;
}
void Task::setDueDate( const KDateTime& date )
{
mDueDate = date;
mHasDueDate = true;
}
KDateTime Task::dueDate() const
{
return mDueDate;
}
void Task::setHasStartDate( bool v )
{
mHasStartDate = v;
}
bool Task::hasStartDate() const
{
return mHasStartDate;
}
bool Task::hasDueDate() const
{
return mHasDueDate;
}
void Task::setCompletedDate( const KDateTime& date )
{
mCompletedDate = date;
mHasCompletedDate = true;
}
KDateTime Task::completedDate() const
{
return mCompletedDate;
}
bool Task::hasCompletedDate() const
{
return mHasCompletedDate;
}
bool Task::loadAttribute( QDomElement& element )
{
QString tagName = element.tagName();
if ( tagName == "priority" ) {
bool ok;
mKolabPriorityFromDom = element.text().toInt( &ok );
if ( !ok || mKolabPriorityFromDom < 1 || mKolabPriorityFromDom > 5 ) {
kWarning() << "Invalid \"priority\" value:" << element.text();
mKolabPriorityFromDom = -1;
}
} else if ( tagName == "x-kcal-priority" ) {
bool ok;
mKCalPriorityFromDom = element.text().toInt( &ok );
if ( !ok || mKCalPriorityFromDom < 0 || mKCalPriorityFromDom > 9 ) {
kWarning() << "Invalid \"x-kcal-priority\" value:" << element.text();
mKCalPriorityFromDom = -1;
}
} else if ( tagName == "completed" ) {
bool ok;
int percent = element.text().toInt( &ok );
if ( !ok || percent < 0 || percent > 100 )
percent = 0;
setPercentCompleted( percent );
} else if ( tagName == "status" ) {
if ( element.text() == "in-progress" )
setStatus( KCal::Incidence::StatusInProcess );
else if ( element.text() == "completed" )
setStatus( KCal::Incidence::StatusCompleted );
else if ( element.text() == "waiting-on-someone-else" )
setStatus( KCal::Incidence::StatusNeedsAction );
else if ( element.text() == "deferred" )
// Guessing a status here
setStatus( KCal::Incidence::StatusCanceled );
else
// Default
setStatus( KCal::Incidence::StatusNone );
} else if ( tagName == "due-date" )
setDueDate( stringToDateTime( element.text() ) );
else if ( tagName == "parent" )
setParent( element.text() );
else if ( tagName == "x-completed-date" )
setCompletedDate( stringToDateTime( element.text() ) );
else if ( tagName == "start-date" ) {
setHasStartDate( true );
setStartDate( element.text() );
} else
return Incidence::loadAttribute( element );
// We handled this
return true;
}
bool Task::saveAttributes( QDomElement& element ) const
{
// Save the base class elements
Incidence::saveAttributes( element );
// We need to save x-kcal-priority as well, since the Kolab priority can only save values from
// 1 to 5, but we have values from 0 to 9, and do not want to loose them
writeString( element, "priority", QString::number( kcalPriorityToKolab( priority() ) ) );
writeString( element, "x-kcal-priority", QString::number( priority() ) );
writeString( element, "completed", QString::number( percentCompleted() ) );
switch( status() ) {
case KCal::Incidence::StatusInProcess:
writeString( element, "status", "in-progress" );
break;
case KCal::Incidence::StatusCompleted:
writeString( element, "status", "completed" );
break;
case KCal::Incidence::StatusNeedsAction:
writeString( element, "status", "waiting-on-someone-else" );
break;
case KCal::Incidence::StatusCanceled:
writeString( element, "status", "deferred" );
break;
case KCal::Incidence::StatusNone:
writeString( element, "status", "not-started" );
break;
case KCal::Incidence::StatusTentative:
case KCal::Incidence::StatusConfirmed:
case KCal::Incidence::StatusDraft:
case KCal::Incidence::StatusFinal:
case KCal::Incidence::StatusX:
// All of these are saved as StatusNone.
writeString( element, "status", "not-started" );
break;
}
if ( hasDueDate() )
writeString( element, "due-date", dateTimeToString( dueDate() ) );
if ( !parent().isNull() )
writeString( element, "parent", parent() );
if ( hasCompletedDate() && percentCompleted() == 100)
writeString( element, "x-completed-date", dateTimeToString( completedDate() ) );
return true;
}
bool Task::loadXML( const QDomDocument& document )
{
mKolabPriorityFromDom = -1;
mKCalPriorityFromDom = -1;
QDomElement top = document.documentElement();
if ( top.tagName() != "task" ) {
qWarning( "XML error: Top tag was %s instead of the expected task",
top.tagName().toAscii().data() );
return false;
}
setHasStartDate( false ); // todo's don't necessarily have one
for ( QDomNode n = top.firstChild(); !n.isNull(); n = n.nextSibling() ) {
if ( n.isComment() )
continue;
if ( n.isElement() ) {
QDomElement e = n.toElement();
if ( !loadAttribute( e ) )
// TODO: Unhandled tag - save for later storage
kDebug() <<"Warning: Unhandled tag" << e.tagName();
} else
kDebug() <<"Node is not a comment or an element???";
}
loadAttachments();
decideAndSetPriority();
return true;
}
QString Task::saveXML() const
{
QDomDocument document = domTree();
QDomElement element = document.createElement( "task" );
element.setAttribute( "version", "1.0" );
saveAttributes( element );
if ( !hasStartDate() && startDate().isValid() ) {
// events and journals always have a start date, but tasks don't.
// Remove the entry done by the inherited save above, because we
// don't have one.
QDomNodeList l = element.elementsByTagName( "start-date" );
Q_ASSERT( l.count() == 1 );
element.removeChild( l.item( 0 ) );
}
document.appendChild( element );
return document.toString();
}
void Task::setFields( const KCal::Todo* task )
{
Incidence::setFields( task );
setPriority( task->priority() );
setPercentCompleted( task->percentComplete() );
setStatus( task->status() );
setHasStartDate( task->hasStartDate() );
if ( task->hasDueDate() )
setDueDate( localToUTC( task->dtDue() ) );
else
mHasDueDate = false;
if ( task->relatedTo() )
setParent( task->relatedTo()->uid() );
else if ( !task->relatedToUid().isEmpty() )
setParent( task->relatedToUid( ) );
else
setParent( QString() );
if ( task->hasCompletedDate() && task->percentComplete() == 100 )
setCompletedDate( localToUTC( task->completed() ) );
else
mHasCompletedDate = false;
}
void Task::decideAndSetPriority()
{
// If we have both Kolab and KCal values in the XML, we prefer the KCal value, but only if the
// values are still in sync
if ( mKolabPriorityFromDom != -1 && mKCalPriorityFromDom != -1 ) {
const bool inSync = ( kolabPrioritytoKCal( mKolabPriorityFromDom ) == mKCalPriorityFromDom );
if ( inSync ) {
setPriority( mKCalPriorityFromDom );
}
else {
// Out of sync, some other client changed the Kolab priority, so we have to ignore our
// KCal priority
setPriority( kolabPrioritytoKCal( mKolabPriorityFromDom ) );
}
}
// Only KCal priority set, use that.
else if ( mKolabPriorityFromDom == -1 && mKCalPriorityFromDom != -1 ) {
kWarning() << "No Kolab priority found, only the KCal priority!";
setPriority( mKCalPriorityFromDom );
}
// Only Kolab priority set, use that
else if ( mKolabPriorityFromDom != -1 && mKCalPriorityFromDom == -1 ) {
setPriority( kolabPrioritytoKCal( mKolabPriorityFromDom ) );
}
// No priority set, use the default
else {
// According the RFC 2445, we should use 0 here, for undefined priority, but AFAIK KOrganizer
// doesn't support that, so we'll use 5.
setPriority( 5 );
}
}
void Task::saveTo( KCal::Todo* task )
{
Incidence::saveTo( task );
task->setPriority( priority() );
task->setPercentComplete( percentCompleted() );
task->setStatus( status() );
task->setHasStartDate( hasStartDate() );
task->setHasDueDate( hasDueDate() );
if ( hasDueDate() )
task->setDtDue( utcToLocal( dueDate() ) );
if ( !parent().isEmpty() )
task->setRelatedToUid( parent() );
if ( hasCompletedDate() && task->percentComplete() == 100 )
task->setCompleted( utcToLocal( mCompletedDate ) );
}
<commit_msg>Note: Kolab proxy resource already fixed with r1063476. SVN_MERGE Merged revisions 1063478 via svnmerge from svn+ssh://tmcguire@svn.kde.org/home/kde/branches/kdepim/enterprise4/kdepim<commit_after>/*
This file is part of the kolab resource - the implementation of the
Kolab storage format. See www.kolab.org for documentation on this.
Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
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 "task.h"
#include <kcal/todo.h>
#include <kdebug.h>
using namespace Kolab;
// Kolab Storage Specification:
// "The priority can be a number between 1 and 5, with 1 being the highest priority."
// iCalendar (RFC 2445):
// "The priority is specified as an integer in the range
// zero to nine. A value of zero specifies an
// undefined priority. A value of one is the
// highest priority. A value of nine is the lowest
// priority."
static int kcalPriorityToKolab( const int kcalPriority )
{
if ( kcalPriority >= 0 && kcalPriority <= 9 ) {
// We'll map undefined (0) to 3 (default)
// 0 1 2 3 4 5 6 7 8 9
static const int priorityMap[10] = { 3, 1, 1, 2, 2, 3, 3, 4, 4, 5 };
return priorityMap[kcalPriority];
}
else {
kWarning() << "Got invalid priority" << kcalPriority;
return 3;
}
}
static int kolabPrioritytoKCal( const int kolabPriority )
{
if ( kolabPriority >= 1 && kolabPriority <= 5 ) {
// 1 2 3 4 5
static const int priorityMap[5] = { 1, 3, 5, 7, 9 };
return priorityMap[kolabPriority - 1];
}
else {
kWarning() << "Got invalid priority" << kolabPriority;
return 5;
}
}
KCal::Todo* Task::xmlToTask( const QString& xml, const QString& tz, KCal::ResourceKolab *res,
const QString& subResource, quint32 sernum )
{
Task task( res, subResource, sernum, tz );
task.load( xml );
KCal::Todo* todo = new KCal::Todo();
task.saveTo( todo );
return todo;
}
QString Task::taskToXML( KCal::Todo* todo, const QString& tz )
{
Task task( 0, QString(), 0, tz, todo );
return task.saveXML();
}
Task::Task( KCal::ResourceKolab *res, const QString &subResource, quint32 sernum,
const QString& tz, KCal::Todo* task )
: Incidence( res, subResource, sernum, tz, task ),
mPriority( 5 ), mPercentCompleted( 0 ),
mStatus( KCal::Incidence::StatusNone ),
mHasStartDate( false ), mHasDueDate( false ),
mHasCompletedDate( false )
{
if ( task )
setFields( task );
}
Task::~Task()
{
}
void Task::setPriority( int priority )
{
mPriority = priority;
}
int Task::priority() const
{
return mPriority;
}
void Task::setPercentCompleted( int percent )
{
mPercentCompleted = percent;
}
int Task::percentCompleted() const
{
return mPercentCompleted;
}
void Task::setStatus( KCal::Incidence::Status status )
{
mStatus = status;
}
KCal::Incidence::Status Task::status() const
{
return mStatus;
}
void Task::setParent( const QString& parentUid )
{
mParent = parentUid;
}
QString Task::parent() const
{
return mParent;
}
void Task::setDueDate( const KDateTime& date )
{
mDueDate = date;
mHasDueDate = true;
}
KDateTime Task::dueDate() const
{
return mDueDate;
}
void Task::setHasStartDate( bool v )
{
mHasStartDate = v;
}
bool Task::hasStartDate() const
{
return mHasStartDate;
}
bool Task::hasDueDate() const
{
return mHasDueDate;
}
void Task::setCompletedDate( const KDateTime& date )
{
mCompletedDate = date;
mHasCompletedDate = true;
}
KDateTime Task::completedDate() const
{
return mCompletedDate;
}
bool Task::hasCompletedDate() const
{
return mHasCompletedDate;
}
bool Task::loadAttribute( QDomElement& element )
{
QString tagName = element.tagName();
if ( tagName == "priority" ) {
bool ok;
mKolabPriorityFromDom = element.text().toInt( &ok );
if ( !ok || mKolabPriorityFromDom < 1 || mKolabPriorityFromDom > 5 ) {
kWarning() << "Invalid \"priority\" value:" << element.text();
mKolabPriorityFromDom = -1;
}
} else if ( tagName == "x-kcal-priority" ) {
bool ok;
mKCalPriorityFromDom = element.text().toInt( &ok );
if ( !ok || mKCalPriorityFromDom < 0 || mKCalPriorityFromDom > 9 ) {
kWarning() << "Invalid \"x-kcal-priority\" value:" << element.text();
mKCalPriorityFromDom = -1;
}
} else if ( tagName == "completed" ) {
bool ok;
int percent = element.text().toInt( &ok );
if ( !ok || percent < 0 || percent > 100 )
percent = 0;
setPercentCompleted( percent );
} else if ( tagName == "status" ) {
if ( element.text() == "in-progress" )
setStatus( KCal::Incidence::StatusInProcess );
else if ( element.text() == "completed" )
setStatus( KCal::Incidence::StatusCompleted );
else if ( element.text() == "waiting-on-someone-else" )
setStatus( KCal::Incidence::StatusNeedsAction );
else if ( element.text() == "deferred" )
// Guessing a status here
setStatus( KCal::Incidence::StatusCanceled );
else
// Default
setStatus( KCal::Incidence::StatusNone );
} else if ( tagName == "due-date" )
setDueDate( stringToDateTime( element.text() ) );
else if ( tagName == "parent" )
setParent( element.text() );
else if ( tagName == "x-completed-date" )
setCompletedDate( stringToDateTime( element.text() ) );
else if ( tagName == "start-date" ) {
setHasStartDate( true );
setStartDate( element.text() );
} else
return Incidence::loadAttribute( element );
// We handled this
return true;
}
bool Task::saveAttributes( QDomElement& element ) const
{
// Save the base class elements
Incidence::saveAttributes( element );
// We need to save x-kcal-priority as well, since the Kolab priority can only save values from
// 1 to 5, but we have values from 0 to 9, and do not want to loose them
writeString( element, "priority", QString::number( kcalPriorityToKolab( priority() ) ) );
writeString( element, "x-kcal-priority", QString::number( priority() ) );
writeString( element, "completed", QString::number( percentCompleted() ) );
switch( status() ) {
case KCal::Incidence::StatusInProcess:
writeString( element, "status", "in-progress" );
break;
case KCal::Incidence::StatusCompleted:
writeString( element, "status", "completed" );
break;
case KCal::Incidence::StatusNeedsAction:
writeString( element, "status", "waiting-on-someone-else" );
break;
case KCal::Incidence::StatusCanceled:
writeString( element, "status", "deferred" );
break;
case KCal::Incidence::StatusNone:
writeString( element, "status", "not-started" );
break;
case KCal::Incidence::StatusTentative:
case KCal::Incidence::StatusConfirmed:
case KCal::Incidence::StatusDraft:
case KCal::Incidence::StatusFinal:
case KCal::Incidence::StatusX:
// All of these are saved as StatusNone.
writeString( element, "status", "not-started" );
break;
}
if ( hasDueDate() )
writeString( element, "due-date", dateTimeToString( dueDate() ) );
if ( !parent().isNull() )
writeString( element, "parent", parent() );
if ( hasCompletedDate() && percentCompleted() == 100)
writeString( element, "x-completed-date", dateTimeToString( completedDate() ) );
return true;
}
bool Task::loadXML( const QDomDocument& document )
{
mKolabPriorityFromDom = -1;
mKCalPriorityFromDom = -1;
QDomElement top = document.documentElement();
if ( top.tagName() != "task" ) {
qWarning( "XML error: Top tag was %s instead of the expected task",
top.tagName().toAscii().data() );
return false;
}
setHasStartDate( false ); // todo's don't necessarily have one
for ( QDomNode n = top.firstChild(); !n.isNull(); n = n.nextSibling() ) {
if ( n.isComment() )
continue;
if ( n.isElement() ) {
QDomElement e = n.toElement();
if ( !loadAttribute( e ) )
// TODO: Unhandled tag - save for later storage
kDebug() <<"Warning: Unhandled tag" << e.tagName();
} else
kDebug() <<"Node is not a comment or an element???";
}
loadAttachments();
decideAndSetPriority();
return true;
}
QString Task::saveXML() const
{
QDomDocument document = domTree();
QDomElement element = document.createElement( "task" );
element.setAttribute( "version", "1.0" );
saveAttributes( element );
if ( !hasStartDate() && startDate().isValid() ) {
// events and journals always have a start date, but tasks don't.
// Remove the entry done by the inherited save above, because we
// don't have one.
QDomNodeList l = element.elementsByTagName( "start-date" );
Q_ASSERT( l.count() == 1 );
element.removeChild( l.item( 0 ) );
}
document.appendChild( element );
return document.toString();
}
void Task::setFields( const KCal::Todo* task )
{
Incidence::setFields( task );
setPriority( task->priority() );
setPercentCompleted( task->percentComplete() );
setStatus( task->status() );
setHasStartDate( task->hasStartDate() );
if ( task->hasDueDate() )
setDueDate( localToUTC( task->dtDue() ) );
else
mHasDueDate = false;
if ( task->relatedTo() )
setParent( task->relatedTo()->uid() );
else if ( !task->relatedToUid().isEmpty() )
setParent( task->relatedToUid( ) );
else
setParent( QString() );
if ( task->hasCompletedDate() && task->percentComplete() == 100 )
setCompletedDate( localToUTC( task->completed() ) );
else
mHasCompletedDate = false;
}
void Task::decideAndSetPriority()
{
// If we have both Kolab and KCal values in the XML, we prefer the KCal value, but only if the
// values are still in sync
if ( mKolabPriorityFromDom != -1 && mKCalPriorityFromDom != -1 ) {
const bool inSync = ( kcalPriorityToKolab( mKCalPriorityFromDom ) == mKolabPriorityFromDom );
if ( inSync ) {
setPriority( mKCalPriorityFromDom );
}
else {
// Out of sync, some other client changed the Kolab priority, so we have to ignore our
// KCal priority
setPriority( kolabPrioritytoKCal( mKolabPriorityFromDom ) );
}
}
// Only KCal priority set, use that.
else if ( mKolabPriorityFromDom == -1 && mKCalPriorityFromDom != -1 ) {
kWarning() << "No Kolab priority found, only the KCal priority!";
setPriority( mKCalPriorityFromDom );
}
// Only Kolab priority set, use that
else if ( mKolabPriorityFromDom != -1 && mKCalPriorityFromDom == -1 ) {
setPriority( kolabPrioritytoKCal( mKolabPriorityFromDom ) );
}
// No priority set, use the default
else {
// According the RFC 2445, we should use 0 here, for undefined priority, but AFAIK KOrganizer
// doesn't support that, so we'll use 5.
setPriority( 5 );
}
}
void Task::saveTo( KCal::Todo* task )
{
Incidence::saveTo( task );
task->setPriority( priority() );
task->setPercentComplete( percentCompleted() );
task->setStatus( status() );
task->setHasStartDate( hasStartDate() );
task->setHasDueDate( hasDueDate() );
if ( hasDueDate() )
task->setDtDue( utcToLocal( dueDate() ) );
if ( !parent().isEmpty() )
task->setRelatedToUid( parent() );
if ( hasCompletedDate() && task->percentComplete() == 100 )
task->setCompleted( utcToLocal( mCompletedDate ) );
}
<|endoftext|>
|
<commit_before>#include "ksp_plugin/rendering_frame.hpp"
#include "geometry/rotation.hpp"
#include "ksp_plugin/celestial.hpp"
#include "quantities/quantities.hpp"
using principia::quantities::Angle;
using principia::quantities::ArcTan;
using principia::quantities::Time;
using principia::geometry::Displacement;
using principia::geometry::InnerProduct;
using principia::geometry::Rotation;
using principia::geometry::Wedge;
namespace principia {
namespace ksp_plugin {
BodyCentredNonRotatingFrame::BodyCentredNonRotatingFrame(
Celestial<Barycentre> const& body) : body_(body) {}
std::unique_ptr<Trajectory<Barycentre>>
BodyCentredNonRotatingFrame::ApparentTrajectory(
Trajectory<Barycentre> const& actual_trajectory) const {
std::unique_ptr<Trajectory<Barycentre>> result =
std::make_unique<Trajectory<Barycentre>>(actual_trajectory.body());
Trajectory<Barycentre>::Timeline const& actual_timeline =
actual_trajectory.timeline();
Trajectory<Barycentre>::Timeline const& reference_body_timeline =
body_.history().timeline();
Trajectory<Barycentre>::Timeline::const_iterator it_in_reference =
reference_body_timeline.lower_bound(actual_timeline.begin()->first);
DegreesOfFreedom<Barycentre> const& current_reference_state =
body_.prolongation().timeline().rbegin()->second;
CHECK(it_in_reference != reference_body_timeline.end());
for (auto const& pair : actual_timeline) {
Instant const& t = pair.first;
DegreesOfFreedom<Barycentre> const& actual_state = pair.second;
while (it_in_reference->first < t) {
++it_in_reference;
}
if (it_in_reference->first == t) {
DegreesOfFreedom<Barycentre> const& reference_state =
it_in_reference->second;
// TODO(egg): We should have a vector space structure on
// |DegreesOfFreedom<Fries>|.
result->Append(t,
{actual_state.position - reference_state.position +
current_reference_state.position,
actual_state.velocity - reference_state.velocity});
}
}
return std::move(result);
}
BarycentricRotatingFrame::BarycentricRotatingFrame(
Celestial<Barycentre> const& primary,
Celestial<Barycentre> const& secondary)
: primary_(primary),
secondary_(secondary) {}
std::unique_ptr<Trajectory<Barycentre>>
BarycentricRotatingFrame::ApparentTrajectory(
Trajectory<Barycentre> const& actual_trajectory) const {
std::unique_ptr<Trajectory<Barycentre>> result =
std::make_unique<Trajectory<Barycentre>>(actual_trajectory.body());
Trajectory<Barycentre>::Timeline const& actual_timeline =
actual_trajectory.timeline();
Trajectory<Barycentre>::Timeline const& primary_timeline =
primary_.history().timeline();
Trajectory<Barycentre>::Timeline const& secondary_timeline =
secondary_.history().timeline();
Trajectory<Barycentre>::Timeline::const_iterator it_in_primary =
primary_timeline.lower_bound(actual_timeline.begin()->first);
Trajectory<Barycentre>::Timeline::const_iterator it_in_secondary =
secondary_timeline.lower_bound(actual_timeline.begin()->first);
DegreesOfFreedom<Barycentre> const& current_primary_state =
primary_.prolongation().timeline().rbegin()->second;
DegreesOfFreedom<Barycentre> const& current_secondary_state =
secondary_.prolongation().timeline().rbegin()->second;
Position<Barycentre> const current_barycentre =
geometry::Barycentre<Displacement<Barycentre>, Mass>(
{current_primary_state.position, current_secondary_state.position},
{primary_.body().mass(), secondary_.body().mass()});
Displacement<Barycentre> const to =
current_primary_state.position - current_barycentre;
for (auto const& pair : actual_timeline) {
Instant const& t = pair.first;
DegreesOfFreedom<Barycentre> const& actual_state = pair.second;
while (it_in_primary->first < t) {
++it_in_primary;
++it_in_secondary;
}
if (it_in_primary->first == t) {
DegreesOfFreedom<Barycentre> const& primary_state = it_in_primary->second;
DegreesOfFreedom<Barycentre> const& secondary_state =
it_in_secondary->second;
Position<Barycentre> const barycentre =
geometry::Barycentre<Displacement<Barycentre>, Mass>(
{primary_state.position, secondary_state.position},
{primary_.body().mass(), secondary_.body().mass()});
Displacement<Barycentre> const from = primary_state.position - barycentre;
auto const wedge = Wedge(from, to);
auto const inverse_product_of_norms = 1 / (from.Norm() * to.Norm());
Angle const angle =
ArcTan(wedge.Norm() * inverse_product_of_norms,
InnerProduct(from, to) * inverse_product_of_norms);
Rotation<Barycentre, Barycentre> const rotation =
Rotation<Barycentre, Barycentre>(angle, wedge);
VLOG(1) << "Rotation :\n"
<< "from : " << from << "\n"
<< "to : " << to << "\n"
<< "wedge : " << wedge << "\n"
<< "angle : " << angle << "\n"
<< "rotation : " << rotation;
// TODO(egg): We should have a vector space structure on
// |DegreesOfFreedom<Fries>|.
result->Append(t,
{rotation(actual_state.position - barycentre) +
current_barycentre,
// This would not be trivial to compute, but we don't use
// it...
actual_state.velocity});
}
}
return std::move(result);
}
} // namespace ksp_plugin
} // namespace principia
<commit_msg>also log positions and masses<commit_after>#include "ksp_plugin/rendering_frame.hpp"
#include "geometry/rotation.hpp"
#include "ksp_plugin/celestial.hpp"
#include "quantities/quantities.hpp"
using principia::quantities::Angle;
using principia::quantities::ArcTan;
using principia::quantities::Time;
using principia::geometry::Displacement;
using principia::geometry::InnerProduct;
using principia::geometry::Rotation;
using principia::geometry::Wedge;
namespace principia {
namespace ksp_plugin {
BodyCentredNonRotatingFrame::BodyCentredNonRotatingFrame(
Celestial<Barycentre> const& body) : body_(body) {}
std::unique_ptr<Trajectory<Barycentre>>
BodyCentredNonRotatingFrame::ApparentTrajectory(
Trajectory<Barycentre> const& actual_trajectory) const {
std::unique_ptr<Trajectory<Barycentre>> result =
std::make_unique<Trajectory<Barycentre>>(actual_trajectory.body());
Trajectory<Barycentre>::Timeline const& actual_timeline =
actual_trajectory.timeline();
Trajectory<Barycentre>::Timeline const& reference_body_timeline =
body_.history().timeline();
Trajectory<Barycentre>::Timeline::const_iterator it_in_reference =
reference_body_timeline.lower_bound(actual_timeline.begin()->first);
DegreesOfFreedom<Barycentre> const& current_reference_state =
body_.prolongation().timeline().rbegin()->second;
CHECK(it_in_reference != reference_body_timeline.end());
for (auto const& pair : actual_timeline) {
Instant const& t = pair.first;
DegreesOfFreedom<Barycentre> const& actual_state = pair.second;
while (it_in_reference->first < t) {
++it_in_reference;
}
if (it_in_reference->first == t) {
DegreesOfFreedom<Barycentre> const& reference_state =
it_in_reference->second;
// TODO(egg): We should have a vector space structure on
// |DegreesOfFreedom<Fries>|.
result->Append(t,
{actual_state.position - reference_state.position +
current_reference_state.position,
actual_state.velocity - reference_state.velocity});
}
}
return std::move(result);
}
BarycentricRotatingFrame::BarycentricRotatingFrame(
Celestial<Barycentre> const& primary,
Celestial<Barycentre> const& secondary)
: primary_(primary),
secondary_(secondary) {}
std::unique_ptr<Trajectory<Barycentre>>
BarycentricRotatingFrame::ApparentTrajectory(
Trajectory<Barycentre> const& actual_trajectory) const {
std::unique_ptr<Trajectory<Barycentre>> result =
std::make_unique<Trajectory<Barycentre>>(actual_trajectory.body());
Trajectory<Barycentre>::Timeline const& actual_timeline =
actual_trajectory.timeline();
Trajectory<Barycentre>::Timeline const& primary_timeline =
primary_.history().timeline();
Trajectory<Barycentre>::Timeline const& secondary_timeline =
secondary_.history().timeline();
Trajectory<Barycentre>::Timeline::const_iterator it_in_primary =
primary_timeline.lower_bound(actual_timeline.begin()->first);
Trajectory<Barycentre>::Timeline::const_iterator it_in_secondary =
secondary_timeline.lower_bound(actual_timeline.begin()->first);
DegreesOfFreedom<Barycentre> const& current_primary_state =
primary_.prolongation().timeline().rbegin()->second;
DegreesOfFreedom<Barycentre> const& current_secondary_state =
secondary_.prolongation().timeline().rbegin()->second;
Position<Barycentre> const current_barycentre =
geometry::Barycentre<Displacement<Barycentre>, Mass>(
{current_primary_state.position, current_secondary_state.position},
{primary_.body().mass(), secondary_.body().mass()});
Displacement<Barycentre> const to =
current_primary_state.position - current_barycentre;
for (auto const& pair : actual_timeline) {
Instant const& t = pair.first;
DegreesOfFreedom<Barycentre> const& actual_state = pair.second;
while (it_in_primary->first < t) {
++it_in_primary;
++it_in_secondary;
}
if (it_in_primary->first == t) {
DegreesOfFreedom<Barycentre> const& primary_state = it_in_primary->second;
DegreesOfFreedom<Barycentre> const& secondary_state =
it_in_secondary->second;
Position<Barycentre> const barycentre =
geometry::Barycentre<Displacement<Barycentre>, Mass>(
{primary_state.position, secondary_state.position},
{primary_.body().mass(), secondary_.body().mass()});
Displacement<Barycentre> const from = primary_state.position - barycentre;
auto const wedge = Wedge(from, to);
auto const inverse_product_of_norms = 1 / (from.Norm() * to.Norm());
Angle const angle =
ArcTan(wedge.Norm() * inverse_product_of_norms,
InnerProduct(from, to) * inverse_product_of_norms);
Rotation<Barycentre, Barycentre> const rotation =
Rotation<Barycentre, Barycentre>(angle, wedge);
VLOG(1) << "Rotation :\n"
<< "primary_.body().mass() :\n"
<< " " << primary_.body().mass() << "\n"
<< "secondary_.body().mass() :\n"
<< " " << secondary_.body().mass() << "\n"
<< "primary_state.position :\n"
<< " " << primary_state.position << "\n"
<< "secondary_state.position :\n"
<< " " << secondary_state.position << "\n"
<< "current_primary_state.position :\n"
<< " " << current_primary_state.position << "\n"
<< "current_secondary_state.position :\n"
<< " " << current_secondary_state.position << "\n"
<< "from : " << from << "\n"
<< "to : " << to << "\n"
<< "wedge : " << wedge << "\n"
<< "angle : " << angle << "\n"
<< "rotation : " << rotation;
// TODO(egg): We should have a vector space structure on
// |DegreesOfFreedom<Fries>|.
result->Append(t,
{rotation(actual_state.position - barycentre) +
current_barycentre,
// This would not be trivial to compute, but we don't use
// it...
actual_state.velocity});
}
}
return std::move(result);
}
} // namespace ksp_plugin
} // namespace principia
<|endoftext|>
|
<commit_before>
#include"symbols.hpp"
#include<string>
#include<map>
Symbol* SymbolsTable::lookup(std::string x) {
Symbol*& s = tb[x];
if(s) return s;
s = new Symbol(x);
return s;
}
SymbolsTable::~SymbolsTable() {
/*go through the*/
}
<commit_msg>src/symbols.cpp: expanded table lookup code<commit_after>#include"all_defines.hpp"
#include"symbols.hpp"
#include<string>
#include<map>
typedef std::map<std::string, Symbol*> maptype;
Symbol* SymbolsTable::lookup(std::string x) {
{/*insert locking of table here*/
Symbol*& s = tb[x];
if(s) return s;
s = new Symbol(x);
return s;
}
}
SymbolsTable::~SymbolsTable() {
/*go through the table and delete each symbol*/
for(maptype::const_iterator it = tb.begin(); it != tb.end(); ++it) {
delete it->second;
}
}
<|endoftext|>
|
<commit_before>#include "testApp.h"
#include <ar.h>
//--------------------------------------------------------------
void testApp::setup() {
ofBackground(0, 0, 0);
ofEnableSmoothing();
ofSetCircleResolution(100);
w = ofGetWidth();
h = ofGetHeight();
centerMarks.x = -1;
threshold = 85;
mode = CC_CALIBRATE;
isCalibrated = false;
movie.initGrabber(w, h, true);
calibrationImage.loadImage("calibration.jpg");
calibrationImage.resize(h, h);
//reserve memory for cv images
rgb.allocate(w, h);
colorOfImage.allocate(h, h, OF_IMAGE_COLOR);
grayImage.allocate(w, h);
grayThres.allocate(h, h);
grayOfImage.allocate(h, h, OF_IMAGE_GRAYSCALE);
fbo.allocate(h, h);
resized.allocate(w, h);
initDisplayMode();
initReadMode();
artk.setup(w, h);
artk.setUndistortionMode(ofxARToolkitPlus::UNDIST_STD);
artk.setThreshold(threshold);
}
//--------------------------------------------------------------
void testApp::update() {
if (movie.isFrameNew()) {
if (movie.isFrameNew()) {
rgb.setFromPixels(movie.getPixels(), w, h);
}
}
movie.update();
switch (mode) {
case CC_MODE_READ:
// cout << "READ" << endl;
break;
case CC_MODE_DISPLAY:
break;
case CC_CALIBRATE:
// convert our camera image to grayscale
grayImage = rgb;
// Pass in the new image pixels to artk
artk.update(grayImage.getPixels());
break;
case CC_MODE_THRESHOLD:
ofPushMatrix();
{
ofTranslate(h, h-240);
ofScale(0.25, 0.25);
rgb.draw(0, 0);
}
ofPopMatrix();
fbo.begin();
rgb.getTextureReference().bind();
mesh.draw();
rgb.getTextureReference().unbind();
fbo.end();
fbo.readToPixels(colorOfImage.getPixelsRef());
colorOfImage.update();
grayOfImage = colorOfImage;
grayOfImage.setImageType(OF_IMAGE_GRAYSCALE);
grayThres.setFromPixels(grayOfImage.getPixelsRef()); // From OF to CV
grayThres.threshold(127);
break;
}
}
//--------------------------------------------------------------
void testApp::draw() {
ofSetColor(255, 255, 255);
switch (mode) {
case CC_MODE_READ:{
ofPushMatrix();
{
ofTranslate(h, h-240);
ofScale(0.25, 0.25);
rgb.draw(0, 0);
}
ofPopMatrix();
grayImage = rgb;
grayThres = grayImage;
grayThres.getTextureReference().bind();
mesh.draw();
grayThres.getTextureReference().unbind();
break;
}
case CC_MODE_DISPLAY:{
drawCircle();
break;
}
case CC_CALIBRATE:{
drawCalibration();
ofPushMatrix();
{
ofTranslate(h, h-240);
ofScale(0.25, 0.25);
rgb.draw(0, 0);
artk.draw(0, 0);
}
ofPopMatrix();
// ARTK 2D stuff
// See if marker ID '0' was detected
// and draw blue corners on that marker only
int myIndex = artk.getMarkerIndex(1);
ofDrawBitmapString(ofToString(artk.getNumDetectedMarkers()), w-40, 40);
if (myIndex >= 0) {
// TODO - this should happen only after some time period
isCalibrated = true;
// mode = CC_MODE_READ;
// Get the corners
vector<ofPoint> corners;
artk.getDetectedMarkerOrderedBorderCorners(myIndex, corners);
sourcePoints.clear();
sourcePoints.push_back(ofVec2f(corners[0].x, corners[0].y));
sourcePoints.push_back(ofVec2f(corners[3].x, corners[3].y));
sourcePoints.push_back(ofVec2f(corners[1].x, corners[1].y));
sourcePoints.push_back(ofVec2f(corners[2].x, corners[2].y));
updateMesh();
// Can also get the center like this:
// ofPoint center = artk.getDetectedMarkerCenter(myIndex);
ofPushMatrix();
{
ofTranslate(h, h-240);
ofScale(0.25, 0.25);
ofSetHexColor(0x00FFff);
for(int i=0;i<corners.size();i++) {
ofDrawBitmapString(ofToString(i), corners[i].x, corners[i].y);
}
}
ofPopMatrix();
}
break;
}
case CC_MODE_THRESHOLD: {
grayThres.draw(0,0);
break;
}
}
}
void testApp::drawCalibration() {
calibrationImage.draw(0, 0);
}
void testApp::drawCircle() {
ofFill();
ofSetColor(255);
ofCircle(ofPoint(h/2, h/2), 300);
}
void testApp::updateMesh() {
mesh.clearTexCoords();
mesh.clearVertices();
mesh.addTexCoords(sourcePoints); // origin coordinates
mesh.addVertices(destinationPoints);
}
void testApp::initDisplayMode() {
}
void testApp::initReadMode() {
// SETUP MESH
destinationPoints.clear();
//we can use 5 vertex to close it clockwise, or change the order to match Tri-strip sequence
mesh.setMode(OF_PRIMITIVE_TRIANGLE_STRIP);
destinationPoints.push_back(ofVec3f(0, 0, 0));
destinationPoints.push_back(ofVec3f(0, h, 0));
destinationPoints.push_back(ofVec3f(h, 0, 0));
destinationPoints.push_back(ofVec3f(h, h, 0));
}
//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button) {
//calculate local mouse x,y in image
// int mx = x % w;
// int my = y % h;
//
// //get hue value on mouse position
// findHue = hue.getPixels()[my * w + mx];
}
//--------------------------------------------------------------
void testApp::findCenterMarks(ofxCvContourFinder &contours) {
int xAve = 0;
int yAve = 0;
for (int i = 0; i < contours.nBlobs; i++) {
xAve += contours.blobs[i].centroid.x;
yAve += contours.blobs[i].centroid.y;
}
xAve = xAve / contours.nBlobs;
yAve = yAve / contours.nBlobs;
centerMarks.set(xAve, yAve);
}
void testApp::sortCentroids(ofxCvContourFinder &contours) {
//contours.findContours(flat, 20, w*h/2, 4, false);
if (contours.nBlobs == 4) { // find center if we have 4 blobs
findCenterMarks(contours);
} else {
centerMarks.x = -1; // otherwise set center to -1
return;
}
sourcePoints.clear();
for (int i = 0; i < contours.nBlobs; i++) {
anglePoint aP;
aP.centroid = contours.blobs[i].centroid;
aP.angle = getAngle(contours.blobs[i].centroid, centerMarks);
blobCenters.push_back(aP);
}
ofSort(blobCenters, byAngle);
sourcePoints.push_back(blobCenters[1].centroid);
sourcePoints.push_back(blobCenters[2].centroid);
sourcePoints.push_back(blobCenters[0].centroid);
sourcePoints.push_back(blobCenters[3].centroid);
}
//--------------------------------------------------------------
float testApp::getAngle(ofPoint &p1, ofPoint &p2) {
float a = atan2(p2.y - p1.y, p1.x - p2.x);
//a = (a+TWO_PI)%(TWO_PI);
if (a < 0) a = a + 2 * PI;
return a;
}
//--------------------------------------------------------------
bool testApp::byAngle(const anglePoint &a, const anglePoint &b) {
return a.angle < b.angle;
}
//--------------------------------------------------------------
void testApp::keyPressed(int key) {
switch (key) {
case '1':
if (isCalibrated) {
mode = CC_MODE_DISPLAY;
}
break;
case '2':
if (isCalibrated) {
mode = CC_MODE_READ;
}
break;
case '3':
mode = CC_CALIBRATE;
isCalibrated = false;
break;
case '4':
mode = CC_MODE_THRESHOLD;
break;
}
}
//--------------------------------------------------------------
void testApp::keyReleased(int key) {
}
//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ) {
}
//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button) {
}
//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button) {
}
//--------------------------------------------------------------
void testApp::windowResized(int w, int h) {
}
//--------------------------------------------------------------
void testApp::gotMessage(ofMessage msg) {
}
//--------------------------------------------------------------
void testApp::dragEvent(ofDragInfo dragInfo) {
}
<commit_msg>fixed case2<commit_after>#include "testApp.h"
#include <ar.h>
//--------------------------------------------------------------
void testApp::setup() {
ofBackground(0, 0, 0);
ofEnableSmoothing();
ofSetCircleResolution(100);
w = ofGetWidth();
h = ofGetHeight();
centerMarks.x = -1;
threshold = 85;
mode = CC_CALIBRATE;
isCalibrated = false;
movie.initGrabber(w, h, true);
calibrationImage.loadImage("calibration.jpg");
calibrationImage.resize(h, h);
//reserve memory for cv images
rgb.allocate(w, h);
colorOfImage.allocate(h, h, OF_IMAGE_COLOR);
grayImage.allocate(w, h);
grayThres.allocate(h, h);
grayOfImage.allocate(h, h, OF_IMAGE_GRAYSCALE);
fbo.allocate(h, h);
resized.allocate(w, h);
initDisplayMode();
initReadMode();
artk.setup(w, h);
artk.setUndistortionMode(ofxARToolkitPlus::UNDIST_STD);
artk.setThreshold(threshold);
}
//--------------------------------------------------------------
void testApp::update() {
if (movie.isFrameNew()) {
if (movie.isFrameNew()) {
rgb.setFromPixels(movie.getPixels(), w, h);
}
}
movie.update();
switch (mode) {
case CC_MODE_READ:
// cout << "READ" << endl;
break;
case CC_MODE_DISPLAY:
break;
case CC_CALIBRATE:
// convert our camera image to grayscale
grayImage = rgb;
// Pass in the new image pixels to artk
artk.update(grayImage.getPixels());
break;
case CC_MODE_THRESHOLD:
ofPushMatrix();
{
ofTranslate(h, h-240);
ofScale(0.25, 0.25);
rgb.draw(0, 0);
}
ofPopMatrix();
fbo.begin();
rgb.getTextureReference().bind();
mesh.draw();
rgb.getTextureReference().unbind();
fbo.end();
fbo.readToPixels(colorOfImage.getPixelsRef());
colorOfImage.update();
grayOfImage = colorOfImage;
grayOfImage.setImageType(OF_IMAGE_GRAYSCALE);
grayThres.setFromPixels(grayOfImage.getPixelsRef()); // From OF to CV
grayThres.threshold(127);
break;
}
}
//--------------------------------------------------------------
void testApp::draw() {
ofSetColor(255, 255, 255);
switch (mode) {
case CC_MODE_READ:{
ofPushMatrix();
{
ofTranslate(h, h-240);
ofScale(0.25, 0.25);
rgb.draw(0, 0);
}
ofPopMatrix();
rgb.getTextureReference().bind();
mesh.draw();
rgb.getTextureReference().unbind();
break;
}
case CC_MODE_DISPLAY:{
drawCircle();
break;
}
case CC_CALIBRATE:{
drawCalibration();
ofPushMatrix();
{
ofTranslate(h, h-240);
ofScale(0.25, 0.25);
rgb.draw(0, 0);
artk.draw(0, 0);
}
ofPopMatrix();
// ARTK 2D stuff
// See if marker ID '0' was detected
// and draw blue corners on that marker only
int myIndex = artk.getMarkerIndex(1);
ofDrawBitmapString(ofToString(artk.getNumDetectedMarkers()), w-40, 40);
if (myIndex >= 0) {
// TODO - this should happen only after some time period
isCalibrated = true;
// mode = CC_MODE_READ;
// Get the corners
vector<ofPoint> corners;
artk.getDetectedMarkerOrderedBorderCorners(myIndex, corners);
sourcePoints.clear();
sourcePoints.push_back(ofVec2f(corners[0].x, corners[0].y));
sourcePoints.push_back(ofVec2f(corners[3].x, corners[3].y));
sourcePoints.push_back(ofVec2f(corners[1].x, corners[1].y));
sourcePoints.push_back(ofVec2f(corners[2].x, corners[2].y));
updateMesh();
// Can also get the center like this:
// ofPoint center = artk.getDetectedMarkerCenter(myIndex);
ofPushMatrix();
{
ofTranslate(h, h-240);
ofScale(0.25, 0.25);
ofSetHexColor(0x00FFff);
for(int i=0;i<corners.size();i++) {
ofDrawBitmapString(ofToString(i), corners[i].x, corners[i].y);
}
}
ofPopMatrix();
}
break;
}
case CC_MODE_THRESHOLD: {
grayThres.draw(0,0);
break;
}
}
}
void testApp::drawCalibration() {
calibrationImage.draw(0, 0);
}
void testApp::drawCircle() {
ofFill();
ofSetColor(255);
ofCircle(ofPoint(h/2, h/2), 300);
}
void testApp::updateMesh() {
mesh.clearTexCoords();
mesh.clearVertices();
mesh.addTexCoords(sourcePoints); // origin coordinates
mesh.addVertices(destinationPoints);
}
void testApp::initDisplayMode() {
}
void testApp::initReadMode() {
// SETUP MESH
destinationPoints.clear();
//we can use 5 vertex to close it clockwise, or change the order to match Tri-strip sequence
mesh.setMode(OF_PRIMITIVE_TRIANGLE_STRIP);
destinationPoints.push_back(ofVec3f(0, 0, 0));
destinationPoints.push_back(ofVec3f(0, h, 0));
destinationPoints.push_back(ofVec3f(h, 0, 0));
destinationPoints.push_back(ofVec3f(h, h, 0));
}
//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button) {
//calculate local mouse x,y in image
// int mx = x % w;
// int my = y % h;
//
// //get hue value on mouse position
// findHue = hue.getPixels()[my * w + mx];
}
//--------------------------------------------------------------
void testApp::findCenterMarks(ofxCvContourFinder &contours) {
int xAve = 0;
int yAve = 0;
for (int i = 0; i < contours.nBlobs; i++) {
xAve += contours.blobs[i].centroid.x;
yAve += contours.blobs[i].centroid.y;
}
xAve = xAve / contours.nBlobs;
yAve = yAve / contours.nBlobs;
centerMarks.set(xAve, yAve);
}
void testApp::sortCentroids(ofxCvContourFinder &contours) {
//contours.findContours(flat, 20, w*h/2, 4, false);
if (contours.nBlobs == 4) { // find center if we have 4 blobs
findCenterMarks(contours);
} else {
centerMarks.x = -1; // otherwise set center to -1
return;
}
sourcePoints.clear();
for (int i = 0; i < contours.nBlobs; i++) {
anglePoint aP;
aP.centroid = contours.blobs[i].centroid;
aP.angle = getAngle(contours.blobs[i].centroid, centerMarks);
blobCenters.push_back(aP);
}
ofSort(blobCenters, byAngle);
sourcePoints.push_back(blobCenters[1].centroid);
sourcePoints.push_back(blobCenters[2].centroid);
sourcePoints.push_back(blobCenters[0].centroid);
sourcePoints.push_back(blobCenters[3].centroid);
}
//--------------------------------------------------------------
float testApp::getAngle(ofPoint &p1, ofPoint &p2) {
float a = atan2(p2.y - p1.y, p1.x - p2.x);
//a = (a+TWO_PI)%(TWO_PI);
if (a < 0) a = a + 2 * PI;
return a;
}
//--------------------------------------------------------------
bool testApp::byAngle(const anglePoint &a, const anglePoint &b) {
return a.angle < b.angle;
}
//--------------------------------------------------------------
void testApp::keyPressed(int key) {
switch (key) {
case '1':
if (isCalibrated) {
mode = CC_MODE_DISPLAY;
}
break;
case '2':
if (isCalibrated) {
mode = CC_MODE_READ;
}
break;
case '3':
mode = CC_CALIBRATE;
isCalibrated = false;
break;
case '4':
mode = CC_MODE_THRESHOLD;
break;
}
}
//--------------------------------------------------------------
void testApp::keyReleased(int key) {
}
//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ) {
}
//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button) {
}
//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button) {
}
//--------------------------------------------------------------
void testApp::windowResized(int w, int h) {
}
//--------------------------------------------------------------
void testApp::gotMessage(ofMessage msg) {
}
//--------------------------------------------------------------
void testApp::dragEvent(ofDragInfo dragInfo) {
}
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2008, 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.
//
//////////////////////////////////////////////////////////////////////////
// System includes
// External includes
#include <boost/python.hpp>
// Local includes
#include "IECore/bindings/RefCountedBinding.h"
#include "IECore/bindings/RunTimeTypedBinding.h"
#include "IECore/bindings/ExceptionBinding.h"
#include "IECore/bindings/ImathBinding.h"
#include "IECore/bindings/KDTreeBinding.h"
#include "IECore/bindings/IndexedIOInterfaceBinding.h"
#include "IECore/bindings/DataBinding.h"
#include "IECore/bindings/SimpleTypedDataBinding.h"
#include "IECore/bindings/VectorTypedDataBinding.h"
#include "IECore/bindings/ObjectBinding.h"
#include "IECore/bindings/TypeIdBinding.h"
#include "IECore/bindings/CompoundDataBinding.h"
#include "IECore/bindings/MessageHandlerBinding.h"
#include "IECore/bindings/AttributeCacheBinding.h"
#include "IECore/bindings/ReaderBinding.h"
#include "IECore/bindings/ParticleReaderBinding.h"
#include "IECore/bindings/PDCParticleReaderBinding.h"
#include "IECore/bindings/BlindDataHolderBinding.h"
#include "IECore/bindings/RenderableBinding.h"
#include "IECore/bindings/VisibleRenderableBinding.h"
#include "IECore/bindings/StateRenderableBinding.h"
#include "IECore/bindings/RendererBinding.h"
#include "IECore/bindings/WriterBinding.h"
#include "IECore/bindings/ParticleWriterBinding.h"
#include "IECore/bindings/PDCParticleWriterBinding.h"
#include "IECore/bindings/ParameterBinding.h"
#include "IECore/bindings/NumericParameterBinding.h"
#include "IECore/bindings/TypedParameterBinding.h"
#include "IECore/bindings/CompoundParameterBinding.h"
#include "IECore/bindings/ValidatedStringParameterBinding.h"
#include "IECore/bindings/PathParameterBinding.h"
#include "IECore/bindings/FileNameParameterBinding.h"
#include "IECore/bindings/DirNameParameterBinding.h"
#include "IECore/bindings/CompoundObjectBinding.h"
#include "IECore/bindings/ObjectReaderBinding.h"
#include "IECore/bindings/ObjectWriterBinding.h"
#include "IECore/bindings/PrimitiveBinding.h"
#include "IECore/bindings/PrimitiveVariableBinding.h"
#include "IECore/bindings/PointsPrimitiveBinding.h"
#include "IECore/bindings/TimerBinding.h"
#include "IECore/bindings/TurbulenceBinding.h"
#include "IECore/bindings/ShaderBinding.h"
#include "IECore/bindings/SearchPathBinding.h"
#include "IECore/bindings/CachedReaderBinding.h"
#include "IECore/bindings/ParameterisedBinding.h"
#include "IECore/bindings/OpBinding.h"
#include "IECore/bindings/ObjectParameterBinding.h"
#include "IECore/bindings/ModifyOpBinding.h"
#include "IECore/bindings/PrimitiveOpBinding.h"
#include "IECore/bindings/ImagePrimitiveBinding.h"
#include "IECore/bindings/ImageReaderBinding.h"
#include "IECore/bindings/ImageWriterBinding.h"
#include "IECore/bindings/PerlinNoiseBinding.h"
#include "IECore/bindings/EXRImageReaderBinding.h"
#include "IECore/bindings/EXRImageWriterBinding.h"
#include "IECore/bindings/HalfBinding.h"
#include "IECore/bindings/TIFFImageReaderBinding.h"
#include "IECore/bindings/TIFFImageWriterBinding.h"
#include "IECore/bindings/CINImageReaderBinding.h"
#include "IECore/bindings/CINImageWriterBinding.h"
#include "IECore/bindings/DPXImageReaderBinding.h"
#include "IECore/bindings/DPXImageWriterBinding.h"
#include "IECore/bindings/JPEGImageReaderBinding.h"
#include "IECore/bindings/JPEGImageWriterBinding.h"
#include "IECore/bindings/MeshPrimitiveBinding.h"
#include "IECore/bindings/MotionPrimitiveBinding.h"
#include "IECore/bindings/TransformBinding.h"
#include "IECore/bindings/MatrixTransformBinding.h"
#include "IECore/bindings/GroupBinding.h"
#include "IECore/bindings/AttributeStateBinding.h"
#include "IECore/bindings/MatrixMotionTransformBinding.h"
#include "IECore/bindings/OBJReaderBinding.h"
#include "IECore/bindings/NullObjectBinding.h"
#include "IECore/bindings/ObjectInterpolatorBinding.h"
#include "IECore/bindings/PointNormalsOpBinding.h"
#include "IECore/bindings/PointDensitiesOpBinding.h"
#include "IECore/bindings/InterpolatedCacheBinding.h"
#include "IECore/bindings/TransformationMatrixBinding.h"
#include "IECore/bindings/TransformationMatrixDataBinding.h"
#include "IECore/bindings/HierarchicalCacheBinding.h"
#include "IECore/bindings/BoundedKDTreeBinding.h"
#include "IECore/bindings/VectorDataFilterOpBinding.h"
#include "IECore/bindings/TypedObjectParameterBinding.h"
#include "IECore/bindings/HeaderGeneratorBinding.h"
#include "IECore/bindings/PreWorldRenderableBinding.h"
#include "IECore/bindings/CameraBinding.h"
#include "IECore/bindings/NURBSPrimitiveBinding.h"
#include "IECore/bindings/DataCastOpBinding.h"
#include "IECore/bindings/DataPromoteOpBinding.h"
#include "IECore/bindings/MatrixMultiplyOpBinding.h"
#include "IECore/bindings/PointBoundsOpBinding.h"
#include "IECore/bindings/ImathRandomBinding.h"
#include "IECore/bindings/RandomRotationOpBinding.h"
#include "IECore/bindings/ImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/CachedImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/MeshPrimitiveBuilderBinding.h"
#include "IECore/bindings/MarchingCubesBinding.h"
#include "IECore/bindings/PointMeshOpBinding.h"
#include "IECore/bindings/CSGImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/SphereImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/PlaneImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/BlobbyImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/ParticleMeshOpBinding.h"
#include "IECore/bindings/TypedPrimitiveOpBinding.h"
#include "IECore/bindings/PrimitiveEvaluatorBinding.h"
#include "IECore/bindings/MeshPrimitiveEvaluatorBinding.h"
#include "IECore/bindings/PrimitiveImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/MeshPrimitiveImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/MeshPrimitiveImplicitSurfaceOpBinding.h"
#include "IECore/bindings/TriangulateOpBinding.h"
#include "IECore/bindings/SpherePrimitiveBinding.h"
#include "IECore/bindings/SpherePrimitiveEvaluatorBinding.h"
#include "IECore/IECore.h"
using namespace IECore;
using namespace boost::python;
// Module declaration
BOOST_PYTHON_MODULE(_IECore)
{
bindRefCounted();(void)
bindRunTimeTyped();
bindException();
bindImath();
bindKDTree();
bindObject();
bindTypeId();
bindData();
bindAllSimpleTypedData();
bindAllVectorTypedData();
bindCompoundData();
bindIndexedIO();
bindMessageHandler();
bindAttributeCache();
bindParameterised();
bindOp();
bindReader();
bindParticleReader();
bindPDCParticleReader();
bindBlindDataHolder();
bindRenderable();
bindStateRenderable();
bindVisibleRenderable();
bindRenderer();
bindWriter();
bindParticleWriter();
bindPDCParticleWriter();
bindObjectReader();
bindObjectWriter();
bindParameter();
bindNumericParameter();
bindTypedParameter();
bindCompoundParameter();
bindValidatedStringParameter();
bindPathParameter();
bindFileNameParameter();
bindDirNameParameter();
bindCompoundObject();
bindPrimitive();
bindPrimitiveVariable();
bindPointsPrimitive();
bindPerlinNoise();
bindHalf();
bindTimer();
bindTurbulence();
bindShader();
bindSearchPath();
bindCachedReader();
bindObjectParameter();
bindModifyOp();
bindPrimitiveOp();
bindImagePrimitive();
bindImageReader();
bindImageWriter();
bindEXRImageReader();
bindEXRImageWriter();
#ifdef IECORE_WITH_TIFF
bindTIFFImageReader();
bindTIFFImageWriter();
#endif
bindCINImageReader();
bindCINImageWriter();
bindDPXImageReader();
bindDPXImageWriter();
#ifdef IECORE_WITH_JPEG
bindJPEGImageReader();
bindJPEGImageWriter();
#endif
bindMeshPrimitive();
bindMotionPrimitive();
bindTransform();
bindMatrixTransform();
bindMatrixMotionTransform();
bindGroup();
bindAttributeState();
bindOBJReader();
bindNullObject();
bindObjectInterpolator();
bindPointNormalsOp();
bindPointDensitiesOp();
bindInterpolatedCache();
bindTransformationMatrix();
bindTransformationMatrixData();
bindHierarchicalCache();
bindBoundedKDTree();
bindVectorDataFilterOp();
bindTypedObjectParameter();
bindHeaderGenerator();
bindPreWorldRenderable();
bindCamera();
bindNURBSPrimitive();
bindDataCastOp();
bindDataPromoteOp();
bindMatrixMultiplyOp();
bindPointBoundsOp();
bindImathRandom();
bindRandomRotationOp();
bindImplicitSurfaceFunction();
bindCachedImplicitSurfaceFunction();
bindMeshPrimitiveBuilder();
bindMarchingCubes();
bindPointMeshOp();
bindCSGImplicitSurfaceFunction();
bindSphereImplicitSurfaceFunction();
bindPlaneImplicitSurfaceFunction();
bindBlobbyImplicitSurfaceFunction();
bindParticleMeshOp();
bindTypedPrimitiveOp();
bindPrimitiveEvaluator();
bindMeshPrimitiveEvaluator();
bindPrimitiveImplicitSurfaceFunction();
bindMeshPrimitiveImplicitSurfaceFunction();
bindMeshPrimitiveImplicitSurfaceOp();
bindTriangulateOp();
bindSpherePrimitive();
bindSpherePrimitiveEvaluator();
def( "majorVersion", &IECore::majorVersion );
def( "minorVersion", &IECore::minorVersion );
def( "patchVersion", &IECore::patchVersion );
def( "versionString", &IECore::versionString, return_value_policy<copy_const_reference>() );
def( "withTIFF", &IECore::withTIFF );
def( "withJPEG", &IECore::withJPEG );
def( "withSQLite", &IECore::withSQLite );
}
<commit_msg>Removed accidentally added token<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2008, 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.
//
//////////////////////////////////////////////////////////////////////////
// System includes
// External includes
#include <boost/python.hpp>
// Local includes
#include "IECore/bindings/RefCountedBinding.h"
#include "IECore/bindings/RunTimeTypedBinding.h"
#include "IECore/bindings/ExceptionBinding.h"
#include "IECore/bindings/ImathBinding.h"
#include "IECore/bindings/KDTreeBinding.h"
#include "IECore/bindings/IndexedIOInterfaceBinding.h"
#include "IECore/bindings/DataBinding.h"
#include "IECore/bindings/SimpleTypedDataBinding.h"
#include "IECore/bindings/VectorTypedDataBinding.h"
#include "IECore/bindings/ObjectBinding.h"
#include "IECore/bindings/TypeIdBinding.h"
#include "IECore/bindings/CompoundDataBinding.h"
#include "IECore/bindings/MessageHandlerBinding.h"
#include "IECore/bindings/AttributeCacheBinding.h"
#include "IECore/bindings/ReaderBinding.h"
#include "IECore/bindings/ParticleReaderBinding.h"
#include "IECore/bindings/PDCParticleReaderBinding.h"
#include "IECore/bindings/BlindDataHolderBinding.h"
#include "IECore/bindings/RenderableBinding.h"
#include "IECore/bindings/VisibleRenderableBinding.h"
#include "IECore/bindings/StateRenderableBinding.h"
#include "IECore/bindings/RendererBinding.h"
#include "IECore/bindings/WriterBinding.h"
#include "IECore/bindings/ParticleWriterBinding.h"
#include "IECore/bindings/PDCParticleWriterBinding.h"
#include "IECore/bindings/ParameterBinding.h"
#include "IECore/bindings/NumericParameterBinding.h"
#include "IECore/bindings/TypedParameterBinding.h"
#include "IECore/bindings/CompoundParameterBinding.h"
#include "IECore/bindings/ValidatedStringParameterBinding.h"
#include "IECore/bindings/PathParameterBinding.h"
#include "IECore/bindings/FileNameParameterBinding.h"
#include "IECore/bindings/DirNameParameterBinding.h"
#include "IECore/bindings/CompoundObjectBinding.h"
#include "IECore/bindings/ObjectReaderBinding.h"
#include "IECore/bindings/ObjectWriterBinding.h"
#include "IECore/bindings/PrimitiveBinding.h"
#include "IECore/bindings/PrimitiveVariableBinding.h"
#include "IECore/bindings/PointsPrimitiveBinding.h"
#include "IECore/bindings/TimerBinding.h"
#include "IECore/bindings/TurbulenceBinding.h"
#include "IECore/bindings/ShaderBinding.h"
#include "IECore/bindings/SearchPathBinding.h"
#include "IECore/bindings/CachedReaderBinding.h"
#include "IECore/bindings/ParameterisedBinding.h"
#include "IECore/bindings/OpBinding.h"
#include "IECore/bindings/ObjectParameterBinding.h"
#include "IECore/bindings/ModifyOpBinding.h"
#include "IECore/bindings/PrimitiveOpBinding.h"
#include "IECore/bindings/ImagePrimitiveBinding.h"
#include "IECore/bindings/ImageReaderBinding.h"
#include "IECore/bindings/ImageWriterBinding.h"
#include "IECore/bindings/PerlinNoiseBinding.h"
#include "IECore/bindings/EXRImageReaderBinding.h"
#include "IECore/bindings/EXRImageWriterBinding.h"
#include "IECore/bindings/HalfBinding.h"
#include "IECore/bindings/TIFFImageReaderBinding.h"
#include "IECore/bindings/TIFFImageWriterBinding.h"
#include "IECore/bindings/CINImageReaderBinding.h"
#include "IECore/bindings/CINImageWriterBinding.h"
#include "IECore/bindings/DPXImageReaderBinding.h"
#include "IECore/bindings/DPXImageWriterBinding.h"
#include "IECore/bindings/JPEGImageReaderBinding.h"
#include "IECore/bindings/JPEGImageWriterBinding.h"
#include "IECore/bindings/MeshPrimitiveBinding.h"
#include "IECore/bindings/MotionPrimitiveBinding.h"
#include "IECore/bindings/TransformBinding.h"
#include "IECore/bindings/MatrixTransformBinding.h"
#include "IECore/bindings/GroupBinding.h"
#include "IECore/bindings/AttributeStateBinding.h"
#include "IECore/bindings/MatrixMotionTransformBinding.h"
#include "IECore/bindings/OBJReaderBinding.h"
#include "IECore/bindings/NullObjectBinding.h"
#include "IECore/bindings/ObjectInterpolatorBinding.h"
#include "IECore/bindings/PointNormalsOpBinding.h"
#include "IECore/bindings/PointDensitiesOpBinding.h"
#include "IECore/bindings/InterpolatedCacheBinding.h"
#include "IECore/bindings/TransformationMatrixBinding.h"
#include "IECore/bindings/TransformationMatrixDataBinding.h"
#include "IECore/bindings/HierarchicalCacheBinding.h"
#include "IECore/bindings/BoundedKDTreeBinding.h"
#include "IECore/bindings/VectorDataFilterOpBinding.h"
#include "IECore/bindings/TypedObjectParameterBinding.h"
#include "IECore/bindings/HeaderGeneratorBinding.h"
#include "IECore/bindings/PreWorldRenderableBinding.h"
#include "IECore/bindings/CameraBinding.h"
#include "IECore/bindings/NURBSPrimitiveBinding.h"
#include "IECore/bindings/DataCastOpBinding.h"
#include "IECore/bindings/DataPromoteOpBinding.h"
#include "IECore/bindings/MatrixMultiplyOpBinding.h"
#include "IECore/bindings/PointBoundsOpBinding.h"
#include "IECore/bindings/ImathRandomBinding.h"
#include "IECore/bindings/RandomRotationOpBinding.h"
#include "IECore/bindings/ImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/CachedImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/MeshPrimitiveBuilderBinding.h"
#include "IECore/bindings/MarchingCubesBinding.h"
#include "IECore/bindings/PointMeshOpBinding.h"
#include "IECore/bindings/CSGImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/SphereImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/PlaneImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/BlobbyImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/ParticleMeshOpBinding.h"
#include "IECore/bindings/TypedPrimitiveOpBinding.h"
#include "IECore/bindings/PrimitiveEvaluatorBinding.h"
#include "IECore/bindings/MeshPrimitiveEvaluatorBinding.h"
#include "IECore/bindings/PrimitiveImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/MeshPrimitiveImplicitSurfaceFunctionBinding.h"
#include "IECore/bindings/MeshPrimitiveImplicitSurfaceOpBinding.h"
#include "IECore/bindings/TriangulateOpBinding.h"
#include "IECore/bindings/SpherePrimitiveBinding.h"
#include "IECore/bindings/SpherePrimitiveEvaluatorBinding.h"
#include "IECore/IECore.h"
using namespace IECore;
using namespace boost::python;
// Module declaration
BOOST_PYTHON_MODULE(_IECore)
{
bindRefCounted();
bindRunTimeTyped();
bindException();
bindImath();
bindKDTree();
bindObject();
bindTypeId();
bindData();
bindAllSimpleTypedData();
bindAllVectorTypedData();
bindCompoundData();
bindIndexedIO();
bindMessageHandler();
bindAttributeCache();
bindParameterised();
bindOp();
bindReader();
bindParticleReader();
bindPDCParticleReader();
bindBlindDataHolder();
bindRenderable();
bindStateRenderable();
bindVisibleRenderable();
bindRenderer();
bindWriter();
bindParticleWriter();
bindPDCParticleWriter();
bindObjectReader();
bindObjectWriter();
bindParameter();
bindNumericParameter();
bindTypedParameter();
bindCompoundParameter();
bindValidatedStringParameter();
bindPathParameter();
bindFileNameParameter();
bindDirNameParameter();
bindCompoundObject();
bindPrimitive();
bindPrimitiveVariable();
bindPointsPrimitive();
bindPerlinNoise();
bindHalf();
bindTimer();
bindTurbulence();
bindShader();
bindSearchPath();
bindCachedReader();
bindObjectParameter();
bindModifyOp();
bindPrimitiveOp();
bindImagePrimitive();
bindImageReader();
bindImageWriter();
bindEXRImageReader();
bindEXRImageWriter();
#ifdef IECORE_WITH_TIFF
bindTIFFImageReader();
bindTIFFImageWriter();
#endif
bindCINImageReader();
bindCINImageWriter();
bindDPXImageReader();
bindDPXImageWriter();
#ifdef IECORE_WITH_JPEG
bindJPEGImageReader();
bindJPEGImageWriter();
#endif
bindMeshPrimitive();
bindMotionPrimitive();
bindTransform();
bindMatrixTransform();
bindMatrixMotionTransform();
bindGroup();
bindAttributeState();
bindOBJReader();
bindNullObject();
bindObjectInterpolator();
bindPointNormalsOp();
bindPointDensitiesOp();
bindInterpolatedCache();
bindTransformationMatrix();
bindTransformationMatrixData();
bindHierarchicalCache();
bindBoundedKDTree();
bindVectorDataFilterOp();
bindTypedObjectParameter();
bindHeaderGenerator();
bindPreWorldRenderable();
bindCamera();
bindNURBSPrimitive();
bindDataCastOp();
bindDataPromoteOp();
bindMatrixMultiplyOp();
bindPointBoundsOp();
bindImathRandom();
bindRandomRotationOp();
bindImplicitSurfaceFunction();
bindCachedImplicitSurfaceFunction();
bindMeshPrimitiveBuilder();
bindMarchingCubes();
bindPointMeshOp();
bindCSGImplicitSurfaceFunction();
bindSphereImplicitSurfaceFunction();
bindPlaneImplicitSurfaceFunction();
bindBlobbyImplicitSurfaceFunction();
bindParticleMeshOp();
bindTypedPrimitiveOp();
bindPrimitiveEvaluator();
bindMeshPrimitiveEvaluator();
bindPrimitiveImplicitSurfaceFunction();
bindMeshPrimitiveImplicitSurfaceFunction();
bindMeshPrimitiveImplicitSurfaceOp();
bindTriangulateOp();
bindSpherePrimitive();
bindSpherePrimitiveEvaluator();
def( "majorVersion", &IECore::majorVersion );
def( "minorVersion", &IECore::minorVersion );
def( "patchVersion", &IECore::patchVersion );
def( "versionString", &IECore::versionString, return_value_policy<copy_const_reference>() );
def( "withTIFF", &IECore::withTIFF );
def( "withJPEG", &IECore::withJPEG );
def( "withSQLite", &IECore::withSQLite );
}
<|endoftext|>
|
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 OpenCV Foundation 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.
//
//M*/
#ifndef __OPENCV_OPTIM_HPP__
#define __OPENCV_OPTIM_HPP__
#include "opencv2/core.hpp"
namespace cv
{
/** @addtogroup core_optim
The algorithms in this section minimize or maximize function value within specified constraints or
without any constraints.
@{
*/
/** @brief Basic interface for all solvers
*/
class CV_EXPORTS MinProblemSolver : public Algorithm
{
public:
/** @brief Represents function being optimized
*/
class CV_EXPORTS Function
{
public:
virtual ~Function() {}
virtual int getDims() const = 0;
virtual double getGradientEps() const;
virtual double calc(const double* x) const = 0;
virtual void getGradient(const double* x,double* grad);
};
/** @brief Getter for the optimized function.
The optimized function is represented by Function interface, which requires derivatives to
implement the sole method calc(double*) to evaluate the function.
@return Smart-pointer to an object that implements Function interface - it represents the
function that is being optimized. It can be empty, if no function was given so far.
*/
virtual Ptr<Function> getFunction() const = 0;
/** @brief Setter for the optimized function.
*It should be called at least once before the call to* minimize(), as default value is not usable.
@param f The new function to optimize.
*/
virtual void setFunction(const Ptr<Function>& f) = 0;
/** @brief Getter for the previously set terminal criteria for this algorithm.
@return Deep copy of the terminal criteria used at the moment.
*/
virtual TermCriteria getTermCriteria() const = 0;
/** @brief Set terminal criteria for solver.
This method *is not necessary* to be called before the first call to minimize(), as the default
value is sensible.
Algorithm stops when the number of function evaluations done exceeds termcrit.maxCount, when
the function values at the vertices of simplex are within termcrit.epsilon range or simplex
becomes so small that it can enclosed in a box with termcrit.epsilon sides, whatever comes
first.
@param termcrit Terminal criteria to be used, represented as cv::TermCriteria structure.
*/
virtual void setTermCriteria(const TermCriteria& termcrit) = 0;
/** @brief actually runs the algorithm and performs the minimization.
The sole input parameter determines the centroid of the starting simplex (roughly, it tells
where to start), all the others (terminal criteria, initial step, function to be minimized) are
supposed to be set via the setters before the call to this method or the default values (not
always sensible) will be used.
@param x The initial point, that will become a centroid of an initial simplex. After the algorithm
will terminate, it will be setted to the point where the algorithm stops, the point of possible
minimum.
@return The value of a function at the point found.
*/
virtual double minimize(InputOutputArray x) = 0;
};
/** @brief This class is used to perform the non-linear non-constrained minimization of a function,
defined on an `n`-dimensional Euclidean space, using the **Nelder-Mead method**, also known as
**downhill simplex method**. The basic idea about the method can be obtained from
<http://en.wikipedia.org/wiki/Nelder-Mead_method>.
It should be noted, that this method, although deterministic, is rather a heuristic and therefore
may converge to a local minima, not necessary a global one. It is iterative optimization technique,
which at each step uses an information about the values of a function evaluated only at `n+1`
points, arranged as a *simplex* in `n`-dimensional space (hence the second name of the method). At
each step new point is chosen to evaluate function at, obtained value is compared with previous
ones and based on this information simplex changes it's shape , slowly moving to the local minimum.
Thus this method is using *only* function values to make decision, on contrary to, say, Nonlinear
Conjugate Gradient method (which is also implemented in optim).
Algorithm stops when the number of function evaluations done exceeds termcrit.maxCount, when the
function values at the vertices of simplex are within termcrit.epsilon range or simplex becomes so
small that it can enclosed in a box with termcrit.epsilon sides, whatever comes first, for some
defined by user positive integer termcrit.maxCount and positive non-integer termcrit.epsilon.
@note DownhillSolver is a derivative of the abstract interface
cv::MinProblemSolver, which in turn is derived from the Algorithm interface and is used to
encapsulate the functionality, common to all non-linear optimization algorithms in the optim
module.
@note term criteria should meet following condition:
@code
termcrit.type == (TermCriteria::MAX_ITER + TermCriteria::EPS) && termcrit.epsilon > 0 && termcrit.maxCount > 0
@endcode
*/
class CV_EXPORTS DownhillSolver : public MinProblemSolver
{
public:
/** @brief Returns the initial step that will be used in downhill simplex algorithm.
@param step Initial step that will be used in algorithm. Note, that although corresponding setter
accepts column-vectors as well as row-vectors, this method will return a row-vector.
@see DownhillSolver::setInitStep
*/
virtual void getInitStep(OutputArray step) const=0;
/** @brief Sets the initial step that will be used in downhill simplex algorithm.
Step, together with initial point (givin in DownhillSolver::minimize) are two `n`-dimensional
vectors that are used to determine the shape of initial simplex. Roughly said, initial point
determines the position of a simplex (it will become simplex's centroid), while step determines the
spread (size in each dimension) of a simplex. To be more precise, if \f$s,x_0\in\mathbb{R}^n\f$ are
the initial step and initial point respectively, the vertices of a simplex will be:
\f$v_0:=x_0-\frac{1}{2} s\f$ and \f$v_i:=x_0+s_i\f$ for \f$i=1,2,\dots,n\f$ where \f$s_i\f$ denotes
projections of the initial step of *n*-th coordinate (the result of projection is treated to be
vector given by \f$s_i:=e_i\cdot\left<e_i\cdot s\right>\f$, where \f$e_i\f$ form canonical basis)
@param step Initial step that will be used in algorithm. Roughly said, it determines the spread
(size in each dimension) of an initial simplex.
*/
virtual void setInitStep(InputArray step)=0;
/** @brief This function returns the reference to the ready-to-use DownhillSolver object.
All the parameters are optional, so this procedure can be called even without parameters at
all. In this case, the default values will be used. As default value for terminal criteria are
the only sensible ones, MinProblemSolver::setFunction() and DownhillSolver::setInitStep()
should be called upon the obtained object, if the respective parameters were not given to
create(). Otherwise, the two ways (give parameters to createDownhillSolver() or miss them out
and call the MinProblemSolver::setFunction() and DownhillSolver::setInitStep()) are absolutely
equivalent (and will drop the same errors in the same way, should invalid input be detected).
@param f Pointer to the function that will be minimized, similarly to the one you submit via
MinProblemSolver::setFunction.
@param initStep Initial step, that will be used to construct the initial simplex, similarly to the one
you submit via MinProblemSolver::setInitStep.
@param termcrit Terminal criteria to the algorithm, similarly to the one you submit via
MinProblemSolver::setTermCriteria.
*/
static Ptr<DownhillSolver> create(const Ptr<MinProblemSolver::Function>& f=Ptr<MinProblemSolver::Function>(),
InputArray initStep=Mat_<double>(1,1,0.0),
TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5000,0.000001));
};
/** @brief This class is used to perform the non-linear non-constrained minimization of a function
with known gradient,
defined on an *n*-dimensional Euclidean space, using the **Nonlinear Conjugate Gradient method**.
The implementation was done based on the beautifully clear explanatory article [An Introduction to
the Conjugate Gradient Method Without the Agonizing
Pain](http://www.cs.cmu.edu/~quake-papers/painless-conjugate-gradient.pdf) by Jonathan Richard
Shewchuk. The method can be seen as an adaptation of a standard Conjugate Gradient method (see, for
example <http://en.wikipedia.org/wiki/Conjugate_gradient_method>) for numerically solving the
systems of linear equations.
It should be noted, that this method, although deterministic, is rather a heuristic method and
therefore may converge to a local minima, not necessary a global one. What is even more disastrous,
most of its behaviour is ruled by gradient, therefore it essentially cannot distinguish between
local minima and maxima. Therefore, if it starts sufficiently near to the local maximum, it may
converge to it. Another obvious restriction is that it should be possible to compute the gradient of
a function at any point, thus it is preferable to have analytic expression for gradient and
computational burden should be born by the user.
The latter responsibility is accompilished via the getGradient method of a
MinProblemSolver::Function interface (which represents function being optimized). This method takes
point a point in *n*-dimensional space (first argument represents the array of coordinates of that
point) and comput its gradient (it should be stored in the second argument as an array).
@note class ConjGradSolver thus does not add any new methods to the basic MinProblemSolver interface.
@note term criteria should meet following condition:
@code
termcrit.type == (TermCriteria::MAX_ITER + TermCriteria::EPS) && termcrit.epsilon > 0 && termcrit.maxCount > 0
// or
termcrit.type == TermCriteria::MAX_ITER) && termcrit.maxCount > 0
@endcode
*/
class CV_EXPORTS ConjGradSolver : public MinProblemSolver
{
public:
/** @brief This function returns the reference to the ready-to-use ConjGradSolver object.
All the parameters are optional, so this procedure can be called even without parameters at
all. In this case, the default values will be used. As default value for terminal criteria are
the only sensible ones, MinProblemSolver::setFunction() should be called upon the obtained
object, if the function was not given to create(). Otherwise, the two ways (submit it to
create() or miss it out and call the MinProblemSolver::setFunction()) are absolutely equivalent
(and will drop the same errors in the same way, should invalid input be detected).
@param f Pointer to the function that will be minimized, similarly to the one you submit via
MinProblemSolver::setFunction.
@param termcrit Terminal criteria to the algorithm, similarly to the one you submit via
MinProblemSolver::setTermCriteria.
*/
static Ptr<ConjGradSolver> create(const Ptr<MinProblemSolver::Function>& f=Ptr<ConjGradSolver::Function>(),
TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5000,0.000001));
};
//! return codes for cv::solveLP() function
enum SolveLPResult
{
SOLVELP_UNBOUNDED = -2, //!< problem is unbounded (target function can achieve arbitrary high values)
SOLVELP_UNFEASIBLE = -1, //!< problem is unfeasible (there are no points that satisfy all the constraints imposed)
SOLVELP_SINGLE = 0, //!< there is only one maximum for target function
SOLVELP_MULTI = 1 //!< there are multiple maxima for target function - the arbitrary one is returned
};
/** @brief Solve given (non-integer) linear programming problem using the Simplex Algorithm (Simplex Method).
What we mean here by "linear programming problem" (or LP problem, for short) can be formulated as:
\f[\mbox{Maximize } c\cdot x\\
\mbox{Subject to:}\\
Ax\leq b\\
x\geq 0\f]
Where \f$c\f$ is fixed `1`-by-`n` row-vector, \f$A\f$ is fixed `m`-by-`n` matrix, \f$b\f$ is fixed `m`-by-`1`
column vector and \f$x\f$ is an arbitrary `n`-by-`1` column vector, which satisfies the constraints.
Simplex algorithm is one of many algorithms that are designed to handle this sort of problems
efficiently. Although it is not optimal in theoretical sense (there exist algorithms that can solve
any problem written as above in polynomial type, while simplex method degenerates to exponential
time for some special cases), it is well-studied, easy to implement and is shown to work well for
real-life purposes.
The particular implementation is taken almost verbatim from **Introduction to Algorithms, third
edition** by T. H. Cormen, C. E. Leiserson, R. L. Rivest and Clifford Stein. In particular, the
Bland's rule <http://en.wikipedia.org/wiki/Bland%27s_rule> is used to prevent cycling.
@param Func This row-vector corresponds to \f$c\f$ in the LP problem formulation (see above). It should
contain 32- or 64-bit floating point numbers. As a convenience, column-vector may be also submitted,
in the latter case it is understood to correspond to \f$c^T\f$.
@param Constr `m`-by-`n+1` matrix, whose rightmost column corresponds to \f$b\f$ in formulation above
and the remaining to \f$A\f$. It should containt 32- or 64-bit floating point numbers.
@param z The solution will be returned here as a column-vector - it corresponds to \f$c\f$ in the
formulation above. It will contain 64-bit floating point numbers.
@return One of cv::SolveLPResult
*/
CV_EXPORTS_W int solveLP(const Mat& Func, const Mat& Constr, Mat& z);
//! @}
}// cv
#endif
<commit_msg>Fixed doc typo<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 OpenCV Foundation 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.
//
//M*/
#ifndef __OPENCV_OPTIM_HPP__
#define __OPENCV_OPTIM_HPP__
#include "opencv2/core.hpp"
namespace cv
{
/** @addtogroup core_optim
The algorithms in this section minimize or maximize function value within specified constraints or
without any constraints.
@{
*/
/** @brief Basic interface for all solvers
*/
class CV_EXPORTS MinProblemSolver : public Algorithm
{
public:
/** @brief Represents function being optimized
*/
class CV_EXPORTS Function
{
public:
virtual ~Function() {}
virtual int getDims() const = 0;
virtual double getGradientEps() const;
virtual double calc(const double* x) const = 0;
virtual void getGradient(const double* x,double* grad);
};
/** @brief Getter for the optimized function.
The optimized function is represented by Function interface, which requires derivatives to
implement the sole method calc(double*) to evaluate the function.
@return Smart-pointer to an object that implements Function interface - it represents the
function that is being optimized. It can be empty, if no function was given so far.
*/
virtual Ptr<Function> getFunction() const = 0;
/** @brief Setter for the optimized function.
*It should be called at least once before the call to* minimize(), as default value is not usable.
@param f The new function to optimize.
*/
virtual void setFunction(const Ptr<Function>& f) = 0;
/** @brief Getter for the previously set terminal criteria for this algorithm.
@return Deep copy of the terminal criteria used at the moment.
*/
virtual TermCriteria getTermCriteria() const = 0;
/** @brief Set terminal criteria for solver.
This method *is not necessary* to be called before the first call to minimize(), as the default
value is sensible.
Algorithm stops when the number of function evaluations done exceeds termcrit.maxCount, when
the function values at the vertices of simplex are within termcrit.epsilon range or simplex
becomes so small that it can enclosed in a box with termcrit.epsilon sides, whatever comes
first.
@param termcrit Terminal criteria to be used, represented as cv::TermCriteria structure.
*/
virtual void setTermCriteria(const TermCriteria& termcrit) = 0;
/** @brief actually runs the algorithm and performs the minimization.
The sole input parameter determines the centroid of the starting simplex (roughly, it tells
where to start), all the others (terminal criteria, initial step, function to be minimized) are
supposed to be set via the setters before the call to this method or the default values (not
always sensible) will be used.
@param x The initial point, that will become a centroid of an initial simplex. After the algorithm
will terminate, it will be setted to the point where the algorithm stops, the point of possible
minimum.
@return The value of a function at the point found.
*/
virtual double minimize(InputOutputArray x) = 0;
};
/** @brief This class is used to perform the non-linear non-constrained minimization of a function,
defined on an `n`-dimensional Euclidean space, using the **Nelder-Mead method**, also known as
**downhill simplex method**. The basic idea about the method can be obtained from
<http://en.wikipedia.org/wiki/Nelder-Mead_method>.
It should be noted, that this method, although deterministic, is rather a heuristic and therefore
may converge to a local minima, not necessary a global one. It is iterative optimization technique,
which at each step uses an information about the values of a function evaluated only at `n+1`
points, arranged as a *simplex* in `n`-dimensional space (hence the second name of the method). At
each step new point is chosen to evaluate function at, obtained value is compared with previous
ones and based on this information simplex changes it's shape , slowly moving to the local minimum.
Thus this method is using *only* function values to make decision, on contrary to, say, Nonlinear
Conjugate Gradient method (which is also implemented in optim).
Algorithm stops when the number of function evaluations done exceeds termcrit.maxCount, when the
function values at the vertices of simplex are within termcrit.epsilon range or simplex becomes so
small that it can enclosed in a box with termcrit.epsilon sides, whatever comes first, for some
defined by user positive integer termcrit.maxCount and positive non-integer termcrit.epsilon.
@note DownhillSolver is a derivative of the abstract interface
cv::MinProblemSolver, which in turn is derived from the Algorithm interface and is used to
encapsulate the functionality, common to all non-linear optimization algorithms in the optim
module.
@note term criteria should meet following condition:
@code
termcrit.type == (TermCriteria::MAX_ITER + TermCriteria::EPS) && termcrit.epsilon > 0 && termcrit.maxCount > 0
@endcode
*/
class CV_EXPORTS DownhillSolver : public MinProblemSolver
{
public:
/** @brief Returns the initial step that will be used in downhill simplex algorithm.
@param step Initial step that will be used in algorithm. Note, that although corresponding setter
accepts column-vectors as well as row-vectors, this method will return a row-vector.
@see DownhillSolver::setInitStep
*/
virtual void getInitStep(OutputArray step) const=0;
/** @brief Sets the initial step that will be used in downhill simplex algorithm.
Step, together with initial point (givin in DownhillSolver::minimize) are two `n`-dimensional
vectors that are used to determine the shape of initial simplex. Roughly said, initial point
determines the position of a simplex (it will become simplex's centroid), while step determines the
spread (size in each dimension) of a simplex. To be more precise, if \f$s,x_0\in\mathbb{R}^n\f$ are
the initial step and initial point respectively, the vertices of a simplex will be:
\f$v_0:=x_0-\frac{1}{2} s\f$ and \f$v_i:=x_0+s_i\f$ for \f$i=1,2,\dots,n\f$ where \f$s_i\f$ denotes
projections of the initial step of *n*-th coordinate (the result of projection is treated to be
vector given by \f$s_i:=e_i\cdot\left<e_i\cdot s\right>\f$, where \f$e_i\f$ form canonical basis)
@param step Initial step that will be used in algorithm. Roughly said, it determines the spread
(size in each dimension) of an initial simplex.
*/
virtual void setInitStep(InputArray step)=0;
/** @brief This function returns the reference to the ready-to-use DownhillSolver object.
All the parameters are optional, so this procedure can be called even without parameters at
all. In this case, the default values will be used. As default value for terminal criteria are
the only sensible ones, MinProblemSolver::setFunction() and DownhillSolver::setInitStep()
should be called upon the obtained object, if the respective parameters were not given to
create(). Otherwise, the two ways (give parameters to createDownhillSolver() or miss them out
and call the MinProblemSolver::setFunction() and DownhillSolver::setInitStep()) are absolutely
equivalent (and will drop the same errors in the same way, should invalid input be detected).
@param f Pointer to the function that will be minimized, similarly to the one you submit via
MinProblemSolver::setFunction.
@param initStep Initial step, that will be used to construct the initial simplex, similarly to the one
you submit via MinProblemSolver::setInitStep.
@param termcrit Terminal criteria to the algorithm, similarly to the one you submit via
MinProblemSolver::setTermCriteria.
*/
static Ptr<DownhillSolver> create(const Ptr<MinProblemSolver::Function>& f=Ptr<MinProblemSolver::Function>(),
InputArray initStep=Mat_<double>(1,1,0.0),
TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5000,0.000001));
};
/** @brief This class is used to perform the non-linear non-constrained minimization of a function
with known gradient,
defined on an *n*-dimensional Euclidean space, using the **Nonlinear Conjugate Gradient method**.
The implementation was done based on the beautifully clear explanatory article [An Introduction to
the Conjugate Gradient Method Without the Agonizing
Pain](http://www.cs.cmu.edu/~quake-papers/painless-conjugate-gradient.pdf) by Jonathan Richard
Shewchuk. The method can be seen as an adaptation of a standard Conjugate Gradient method (see, for
example <http://en.wikipedia.org/wiki/Conjugate_gradient_method>) for numerically solving the
systems of linear equations.
It should be noted, that this method, although deterministic, is rather a heuristic method and
therefore may converge to a local minima, not necessary a global one. What is even more disastrous,
most of its behaviour is ruled by gradient, therefore it essentially cannot distinguish between
local minima and maxima. Therefore, if it starts sufficiently near to the local maximum, it may
converge to it. Another obvious restriction is that it should be possible to compute the gradient of
a function at any point, thus it is preferable to have analytic expression for gradient and
computational burden should be born by the user.
The latter responsibility is accompilished via the getGradient method of a
MinProblemSolver::Function interface (which represents function being optimized). This method takes
point a point in *n*-dimensional space (first argument represents the array of coordinates of that
point) and comput its gradient (it should be stored in the second argument as an array).
@note class ConjGradSolver thus does not add any new methods to the basic MinProblemSolver interface.
@note term criteria should meet following condition:
@code
termcrit.type == (TermCriteria::MAX_ITER + TermCriteria::EPS) && termcrit.epsilon > 0 && termcrit.maxCount > 0
// or
termcrit.type == TermCriteria::MAX_ITER) && termcrit.maxCount > 0
@endcode
*/
class CV_EXPORTS ConjGradSolver : public MinProblemSolver
{
public:
/** @brief This function returns the reference to the ready-to-use ConjGradSolver object.
All the parameters are optional, so this procedure can be called even without parameters at
all. In this case, the default values will be used. As default value for terminal criteria are
the only sensible ones, MinProblemSolver::setFunction() should be called upon the obtained
object, if the function was not given to create(). Otherwise, the two ways (submit it to
create() or miss it out and call the MinProblemSolver::setFunction()) are absolutely equivalent
(and will drop the same errors in the same way, should invalid input be detected).
@param f Pointer to the function that will be minimized, similarly to the one you submit via
MinProblemSolver::setFunction.
@param termcrit Terminal criteria to the algorithm, similarly to the one you submit via
MinProblemSolver::setTermCriteria.
*/
static Ptr<ConjGradSolver> create(const Ptr<MinProblemSolver::Function>& f=Ptr<ConjGradSolver::Function>(),
TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5000,0.000001));
};
//! return codes for cv::solveLP() function
enum SolveLPResult
{
SOLVELP_UNBOUNDED = -2, //!< problem is unbounded (target function can achieve arbitrary high values)
SOLVELP_UNFEASIBLE = -1, //!< problem is unfeasible (there are no points that satisfy all the constraints imposed)
SOLVELP_SINGLE = 0, //!< there is only one maximum for target function
SOLVELP_MULTI = 1 //!< there are multiple maxima for target function - the arbitrary one is returned
};
/** @brief Solve given (non-integer) linear programming problem using the Simplex Algorithm (Simplex Method).
What we mean here by "linear programming problem" (or LP problem, for short) can be formulated as:
\f[\mbox{Maximize } c\cdot x\\
\mbox{Subject to:}\\
Ax\leq b\\
x\geq 0\f]
Where \f$c\f$ is fixed `1`-by-`n` row-vector, \f$A\f$ is fixed `m`-by-`n` matrix, \f$b\f$ is fixed `m`-by-`1`
column vector and \f$x\f$ is an arbitrary `n`-by-`1` column vector, which satisfies the constraints.
Simplex algorithm is one of many algorithms that are designed to handle this sort of problems
efficiently. Although it is not optimal in theoretical sense (there exist algorithms that can solve
any problem written as above in polynomial time, while simplex method degenerates to exponential
time for some special cases), it is well-studied, easy to implement and is shown to work well for
real-life purposes.
The particular implementation is taken almost verbatim from **Introduction to Algorithms, third
edition** by T. H. Cormen, C. E. Leiserson, R. L. Rivest and Clifford Stein. In particular, the
Bland's rule <http://en.wikipedia.org/wiki/Bland%27s_rule> is used to prevent cycling.
@param Func This row-vector corresponds to \f$c\f$ in the LP problem formulation (see above). It should
contain 32- or 64-bit floating point numbers. As a convenience, column-vector may be also submitted,
in the latter case it is understood to correspond to \f$c^T\f$.
@param Constr `m`-by-`n+1` matrix, whose rightmost column corresponds to \f$b\f$ in formulation above
and the remaining to \f$A\f$. It should containt 32- or 64-bit floating point numbers.
@param z The solution will be returned here as a column-vector - it corresponds to \f$c\f$ in the
formulation above. It will contain 64-bit floating point numbers.
@return One of cv::SolveLPResult
*/
CV_EXPORTS_W int solveLP(const Mat& Func, const Mat& Constr, Mat& z);
//! @}
}// cv
#endif
<|endoftext|>
|
<commit_before>// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#ifndef OPENCV_DNN_VERSION_HPP
#define OPENCV_DNN_VERSION_HPP
/// Use with major OpenCV version only.
#define OPENCV_DNN_API_VERSION 20190430
#if !defined CV_DOXYGEN && !defined CV_STATIC_ANALYSIS && !defined CV_DNN_DONT_ADD_INLINE_NS
#define CV__DNN_INLINE_NS __CV_CAT(dnn4_v, OPENCV_DNN_API_VERSION)
#define CV__DNN_INLINE_NS_BEGIN namespace CV__DNN_INLINE_NS {
#define CV__DNN_INLINE_NS_END }
namespace cv { namespace dnn { namespace CV__DNN_INLINE_NS { } using namespace CV__DNN_INLINE_NS; }}
#else
#define CV__DNN_INLINE_NS_BEGIN
#define CV__DNN_INLINE_NS_END
#endif
#endif // OPENCV_DNN_VERSION_HPP
<commit_msg>dnn: bump API version<commit_after>// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#ifndef OPENCV_DNN_VERSION_HPP
#define OPENCV_DNN_VERSION_HPP
/// Use with major OpenCV version only.
#define OPENCV_DNN_API_VERSION 20190621
#if !defined CV_DOXYGEN && !defined CV_STATIC_ANALYSIS && !defined CV_DNN_DONT_ADD_INLINE_NS
#define CV__DNN_INLINE_NS __CV_CAT(dnn4_v, OPENCV_DNN_API_VERSION)
#define CV__DNN_INLINE_NS_BEGIN namespace CV__DNN_INLINE_NS {
#define CV__DNN_INLINE_NS_END }
namespace cv { namespace dnn { namespace CV__DNN_INLINE_NS { } using namespace CV__DNN_INLINE_NS; }}
#else
#define CV__DNN_INLINE_NS_BEGIN
#define CV__DNN_INLINE_NS_END
#endif
#endif // OPENCV_DNN_VERSION_HPP
<|endoftext|>
|
<commit_before>#include "perf_precomp.hpp"
using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;
CV_ENUM(MethodType, CV_TM_SQDIFF, CV_TM_SQDIFF_NORMED, CV_TM_CCORR, CV_TM_CCORR_NORMED, CV_TM_CCOEFF, CV_TM_CCOEFF_NORMED)
typedef std::tr1::tuple<Size, Size, MethodType> ImgSize_TmplSize_Method_t;
typedef perf::TestBaseWithParam<ImgSize_TmplSize_Method_t> ImgSize_TmplSize_Method;
PERF_TEST_P(ImgSize_TmplSize_Method, matchTemplateSmall,
testing::Combine(
testing::Values(szSmall128, cv::Size(320, 240),
cv::Size(640, 480), cv::Size(800, 600),
cv::Size(1024, 768), cv::Size(1280, 1024)),
testing::Values(cv::Size(12, 12), cv::Size(28, 9),
cv::Size(8, 30), cv::Size(16, 16)),
testing::ValuesIn(MethodType::all())
)
)
{
Size imgSz = get<0>(GetParam());
Size tmplSz = get<1>(GetParam());
int method = get<2>(GetParam());
Mat img(imgSz, CV_8UC1);
Mat tmpl(tmplSz, CV_8UC1);
Mat result(imgSz - tmplSz + Size(1,1), CV_32F);
declare
.in(img, WARMUP_RNG)
.in(tmpl, WARMUP_RNG)
.out(result);
TEST_CYCLE() matchTemplate(img, tmpl, result, method);
SANITY_CHECK(result, 65536 * tmpl.total() * 1e-7);
}
PERF_TEST_P(ImgSize_TmplSize_Method, matchTemplateBig,
testing::Combine(
testing::Values(cv::Size(1280, 1024)),
testing::Values(cv::Size(1260, 1000), cv::Size(1261, 1013)),
testing::ValuesIn(MethodType::all())
)
)
{
Size imgSz = get<0>(GetParam());
Size tmplSz = get<1>(GetParam());
int method = get<2>(GetParam());
Mat img(imgSz, CV_8UC1);
Mat tmpl(tmplSz, CV_8UC1);
Mat result(imgSz - tmplSz + Size(1,1), CV_32F);
declare
.in(img, WARMUP_RNG)
.in(tmpl, WARMUP_RNG)
.out(result);
TEST_CYCLE() matchTemplate(img, tmpl, result, method);
SANITY_CHECK(result, 65536 * tmpl.total() * 1e-7);
}
<commit_msg>stricter eps for normed methods<commit_after>#include "perf_precomp.hpp"
using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;
CV_ENUM(MethodType, CV_TM_SQDIFF, CV_TM_SQDIFF_NORMED, CV_TM_CCORR, CV_TM_CCORR_NORMED, CV_TM_CCOEFF, CV_TM_CCOEFF_NORMED)
typedef std::tr1::tuple<Size, Size, MethodType> ImgSize_TmplSize_Method_t;
typedef perf::TestBaseWithParam<ImgSize_TmplSize_Method_t> ImgSize_TmplSize_Method;
PERF_TEST_P(ImgSize_TmplSize_Method, matchTemplateSmall,
testing::Combine(
testing::Values(szSmall128, cv::Size(320, 240),
cv::Size(640, 480), cv::Size(800, 600),
cv::Size(1024, 768), cv::Size(1280, 1024)),
testing::Values(cv::Size(12, 12), cv::Size(28, 9),
cv::Size(8, 30), cv::Size(16, 16)),
testing::ValuesIn(MethodType::all())
)
)
{
Size imgSz = get<0>(GetParam());
Size tmplSz = get<1>(GetParam());
int method = get<2>(GetParam());
Mat img(imgSz, CV_8UC1);
Mat tmpl(tmplSz, CV_8UC1);
Mat result(imgSz - tmplSz + Size(1,1), CV_32F);
declare
.in(img, WARMUP_RNG)
.in(tmpl, WARMUP_RNG)
.out(result);
TEST_CYCLE() matchTemplate(img, tmpl, result, method);
bool isNormed =
method == CV_TM_CCORR_NORMED ||
method == CV_TM_SQDIFF_NORMED ||
method == CV_TM_CCOEFF_NORMED;
double eps = isNormed ? 1e-6
: 255 * 255 * tmpl.total() * 1e-6;
SANITY_CHECK(result, eps);
}
PERF_TEST_P(ImgSize_TmplSize_Method, matchTemplateBig,
testing::Combine(
testing::Values(cv::Size(1280, 1024)),
testing::Values(cv::Size(1260, 1000), cv::Size(1261, 1013)),
testing::ValuesIn(MethodType::all())
)
)
{
Size imgSz = get<0>(GetParam());
Size tmplSz = get<1>(GetParam());
int method = get<2>(GetParam());
Mat img(imgSz, CV_8UC1);
Mat tmpl(tmplSz, CV_8UC1);
Mat result(imgSz - tmplSz + Size(1,1), CV_32F);
declare
.in(img, WARMUP_RNG)
.in(tmpl, WARMUP_RNG)
.out(result);
TEST_CYCLE() matchTemplate(img, tmpl, result, method);
bool isNormed =
method == CV_TM_CCORR_NORMED ||
method == CV_TM_SQDIFF_NORMED ||
method == CV_TM_CCOEFF_NORMED;
double eps = isNormed ? 1e-6
: 255 * 255 * tmpl.total() * 1e-6;
SANITY_CHECK(result, eps);
}
<|endoftext|>
|
<commit_before>#include <cstdio>
#include <algorithm>
#include <string>
#include <map>
#include <cstdlib>
#include <iostream>
#include <cstring>
using namespace std;
map <string ,int> dict;
bool end=false;
//debug
#ifdef LOCAL
#define fp stdin
#else
FILE *fp;
#endif
char last=0;
char ch;
string getword(){
string s;
if (last){
s.push_back(last);
last=0;
}
while((ch=getc(fp))!=EOF){
//printf("is :%c\n",ch);
if(ch=='-'){
if((ch=getc(fp))=='\n'){
continue;
}else{
last=ch;
break;
}
}
if(ch>='A'&&ch<='Z' || ch>='a'&&ch<='z')
s.push_back(ch);
else
break;
}
if(ch==EOF) end=true;
transform(s.begin(), s.end(), s.begin(), (int (*)(int))tolower);
return s;
}
void printdict(){
for ( dit = dict.begin( ); dit != dict.end( ); dit++ ){
coout<<dit<<endl;
}
}
int main(int argc, char const *argv[])
{
#ifndef LOCAL
fp=fopen("case1.in","r");
#else
printf("used LOCAL");
#endif
string word;
while(!end){
word=getword();
if(!dict.count(word)) dict[word]=0;
cout<<word<<endl;
}
printdict();
return 0;
}
<commit_msg>update uoj1109<commit_after>#include <cstdio>
#include <algorithm>
#include <string>
#include <map>
#include <cstdlib>
#include <iostream>
#include <cstring>
using namespace std;
map <string ,int> dict;
bool end=false;
//debug
#ifdef LOCAL
#define fp stdin
#else
FILE *fp;
#endif
char last=0;
char ch;
string getword(){
string s;
if (last){
s.push_back(last);
last=0;
}
while((ch=getc(fp))!=EOF){
//printf("is :%c\n",ch);
if(ch=='-'){
if((ch=getc(fp))=='\n'){
continue;
}else{
last=ch;
break;
}
}
if(ch>='A'&&ch<='Z' || ch>='a'&&ch<='z')
s.push_back(ch);
else
break;
}
if(ch==EOF) end=true;
transform(s.begin(), s.end(), s.begin(), (int (*)(int))tolower);
return s;
}
void printdict(){
map <string, int>::iterator dit;
for ( dit = dict.begin( ); dit != dict.end( ); dit++ ){
coout<<dit<<endl;
}
}
int main(int argc, char const *argv[])
{
#ifndef LOCAL
fp=fopen("case1.in","r");
#else
printf("used LOCAL");
#endif
string word;
while(!end){
word=getword();
if(!dict.count(word)) dict[word]=0;
cout<<word<<endl;
}
printdict();
return 0;
}
<|endoftext|>
|
<commit_before>//===- unittests/AST/PostOrderASTVisitor.cpp - Declaration printer tests --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains tests for the post-order traversing functionality
// of RecursiveASTVisitor.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Tooling/Tooling.h"
#include "gtest/gtest.h"
using namespace clang;
namespace {
class RecordingVisitor
: public RecursiveASTVisitor<RecordingVisitor> {
bool VisitPostOrder;
public:
explicit RecordingVisitor(bool VisitPostOrder)
: VisitPostOrder(VisitPostOrder) {
}
// List of visited nodes during traversal.
std::vector<std::string> VisitedNodes;
bool shouldTraversePostOrder() const { return VisitPostOrder; }
bool VisitUnaryOperator(UnaryOperator *Op) {
VisitedNodes.push_back(Op->getOpcodeStr(Op->getOpcode()));
return true;
}
bool VisitBinaryOperator(BinaryOperator *Op) {
VisitedNodes.push_back(Op->getOpcodeStr());
return true;
}
bool VisitIntegerLiteral(IntegerLiteral *Lit) {
VisitedNodes.push_back(Lit->getValue().toString(10, false));
return true;
}
bool VisitVarDecl(VarDecl* D) {
VisitedNodes.push_back(D->getNameAsString());
return true;
}
bool VisitCXXMethodDecl(CXXMethodDecl *D) {
VisitedNodes.push_back(D->getQualifiedNameAsString());
return true;
}
bool VisitReturnStmt(ReturnStmt *S) {
VisitedNodes.push_back("return");
return true;
}
bool VisitCXXRecordDecl(CXXRecordDecl *Declaration) {
VisitedNodes.push_back(Declaration->getQualifiedNameAsString());
return true;
}
bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
VisitedNodes.push_back(T->getDecl()->getQualifiedNameAsString());
return true;
}
};
}
TEST(RecursiveASTVisitor, PostOrderTraversal) {
auto ASTUnit = tooling::buildASTFromCode(
"class A {"
" class B {"
" int foo() { while(4) { int i = 9; int j = -i; } return (1 + 3) + 2; }"
" };"
"};"
);
auto TU = ASTUnit->getASTContext().getTranslationUnitDecl();
// We traverse the translation unit and store all
// visited nodes.
RecordingVisitor Visitor(true);
Visitor.TraverseTranslationUnitDecl(TU);
std::vector<std::string> expected = {
"4", "9", "i", "-", "j", "1", "3", "+", "2", "+", "return", "A::B::foo", "A::B", "A"
};
// Compare the list of actually visited nodes
// with the expected list of visited nodes.
ASSERT_EQ(expected.size(), Visitor.VisitedNodes.size());
for (std::size_t I = 0; I < expected.size(); I++) {
ASSERT_EQ(expected[I], Visitor.VisitedNodes[I]);
}
}
TEST(RecursiveASTVisitor, NoPostOrderTraversal) {
auto ASTUnit = tooling::buildASTFromCode(
"class A {"
" class B {"
" int foo() { return 1 + 2; }"
" };"
"};"
);
auto TU = ASTUnit->getASTContext().getTranslationUnitDecl();
// We traverse the translation unit and store all
// visited nodes.
RecordingVisitor Visitor(false);
Visitor.TraverseTranslationUnitDecl(TU);
std::vector<std::string> expected = {
"A", "A::B", "A::B::foo", "return", "+", "1", "2"
};
// Compare the list of actually visited nodes
// with the expected list of visited nodes.
ASSERT_EQ(expected.size(), Visitor.VisitedNodes.size());
for (std::size_t I = 0; I < expected.size(); I++) {
ASSERT_EQ(expected[I], Visitor.VisitedNodes[I]);
}
}
<commit_msg>[RecursiveASTVisitor] Improve post-order traversal unit test<commit_after>//===- unittests/AST/PostOrderASTVisitor.cpp - Declaration printer tests --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains tests for the post-order traversing functionality
// of RecursiveASTVisitor.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Tooling/Tooling.h"
#include "gtest/gtest.h"
using namespace clang;
namespace {
class RecordingVisitor
: public RecursiveASTVisitor<RecordingVisitor> {
bool VisitPostOrder;
public:
explicit RecordingVisitor(bool VisitPostOrder)
: VisitPostOrder(VisitPostOrder) {
}
// List of visited nodes during traversal.
std::vector<std::string> VisitedNodes;
bool shouldTraversePostOrder() const { return VisitPostOrder; }
bool VisitUnaryOperator(UnaryOperator *Op) {
VisitedNodes.push_back(Op->getOpcodeStr(Op->getOpcode()));
return true;
}
bool VisitBinaryOperator(BinaryOperator *Op) {
VisitedNodes.push_back(Op->getOpcodeStr());
return true;
}
bool VisitIntegerLiteral(IntegerLiteral *Lit) {
VisitedNodes.push_back(Lit->getValue().toString(10, false));
return true;
}
bool VisitVarDecl(VarDecl* D) {
VisitedNodes.push_back(D->getNameAsString());
return true;
}
bool VisitCXXMethodDecl(CXXMethodDecl *D) {
VisitedNodes.push_back(D->getQualifiedNameAsString());
return true;
}
bool VisitReturnStmt(ReturnStmt *S) {
VisitedNodes.push_back("return");
return true;
}
bool VisitCXXRecordDecl(CXXRecordDecl *Declaration) {
VisitedNodes.push_back(Declaration->getQualifiedNameAsString());
return true;
}
bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
VisitedNodes.push_back(T->getDecl()->getQualifiedNameAsString());
return true;
}
};
}
TEST(RecursiveASTVisitor, PostOrderTraversal) {
auto ASTUnit = tooling::buildASTFromCode(
"class A {"
" class B {"
" int foo() { while(4) { int i = 9; int j = -5; } return (1 + 3) + 2; }"
" };"
"};"
);
auto TU = ASTUnit->getASTContext().getTranslationUnitDecl();
// We traverse the translation unit and store all
// visited nodes.
RecordingVisitor Visitor(true);
Visitor.TraverseTranslationUnitDecl(TU);
std::vector<std::string> expected = {"4", "9", "i", "5", "-",
"j", "1", "3", "+", "2",
"+", "return", "A::B::foo", "A::B", "A"};
// Compare the list of actually visited nodes
// with the expected list of visited nodes.
ASSERT_EQ(expected.size(), Visitor.VisitedNodes.size());
for (std::size_t I = 0; I < expected.size(); I++) {
ASSERT_EQ(expected[I], Visitor.VisitedNodes[I]);
}
}
TEST(RecursiveASTVisitor, NoPostOrderTraversal) {
auto ASTUnit = tooling::buildASTFromCode(
"class A {"
" class B {"
" int foo() { return 1 + 2; }"
" };"
"};"
);
auto TU = ASTUnit->getASTContext().getTranslationUnitDecl();
// We traverse the translation unit and store all
// visited nodes.
RecordingVisitor Visitor(false);
Visitor.TraverseTranslationUnitDecl(TU);
std::vector<std::string> expected = {
"A", "A::B", "A::B::foo", "return", "+", "1", "2"
};
// Compare the list of actually visited nodes
// with the expected list of visited nodes.
ASSERT_EQ(expected.size(), Visitor.VisitedNodes.size());
for (std::size_t I = 0; I < expected.size(); I++) {
ASSERT_EQ(expected[I], Visitor.VisitedNodes[I]);
}
}
<|endoftext|>
|
<commit_before>#pragma once
#include <utility>
#include <memory>
#include <string>
#include <uv.h>
#include "event.hpp"
#include "request.hpp"
#include "util.hpp"
#include "loop.hpp"
namespace uvw {
/**
* @brief AddrInfoEvent event.
*
* It will be emitted by GetAddrInfoReq according with its functionalities.
*/
struct AddrInfoEvent: Event<AddrInfoEvent> {
using Deleter = void(*)(addrinfo *);
AddrInfoEvent(std::unique_ptr<addrinfo, Deleter> _data)
: data{std::move(_data)}
{}
/**
* @brief An initialized instance of `addrinfo`.
*
* See [getaddrinfo](http://linux.die.net/man/3/getaddrinfo) for further
* details.
*/
std::unique_ptr<addrinfo, Deleter> data;
};
/**
* @brief NameInfoEvent event.
*
* It will be emitted by GetNameInfoReq according with its functionalities.
*/
struct NameInfoEvent: Event<NameInfoEvent> {
NameInfoEvent(const char *_hostname, const char *_service)
: hostname{_hostname}, service{_service}
{}
/**
* @brief A valid hostname.
*
* See [getnameinfo](http://linux.die.net/man/3/getnameinfo) for further
* details.
*/
const char * hostname;
/**
* @brief A valid service name.
*
* See [getnameinfo](http://linux.die.net/man/3/getnameinfo) for further
* details.
*/
const char * service;
};
/**
* @brief The GetAddrInfoReq request.
*
* Wrapper for [getaddrinfo](http://linux.die.net/man/3/getaddrinfo).<br/>
* It offers either asynchronous and synchronous access methods.
*
* To create a `GetAddrInfoReq` through a `Loop`, no arguments are required.
*/
class GetAddrInfoReq final: public Request<GetAddrInfoReq, uv_getaddrinfo_t> {
static void getAddrInfoCallback(uv_getaddrinfo_t *req, int status, addrinfo *res) {
auto ptr = reserve(req);
if(status) {
ptr->publish(ErrorEvent{status});
} else {
auto data = std::unique_ptr<addrinfo, void(*)(addrinfo *)>{
res, [](addrinfo *_res){ uv_freeaddrinfo(_res); }};
ptr->publish(AddrInfoEvent{std::move(data)});
}
}
void getNodeAddrInfo(const char *node, const char *service, addrinfo *hints = nullptr) {
invoke(&uv_getaddrinfo, parent(), get(), &getAddrInfoCallback, node, service, hints);
}
auto getNodeAddrInfoSync(const char *node, const char *service, addrinfo *hints = nullptr) {
auto req = get();
auto err = uv_getaddrinfo(parent(), req, nullptr, node, service, hints);
auto _ptr = std::unique_ptr<addrinfo, void(*)(addrinfo *)>{req->addrinfo, [](addrinfo *_res){ uv_freeaddrinfo(_res); }};
return std::make_pair(!err, std::move(_ptr));
}
public:
using Deleter = void(*)(addrinfo *);
using Request::Request;
/**
* @brief Async [getaddrinfo](http://linux.die.net/man/3/getaddrinfo).
* @param node Either a numerical network address or a network hostname.
* @param hints Optional `addrinfo` data structure with additional address
* type constraints.
*/
void getNodeAddrInfo(std::string node, addrinfo *hints = nullptr) {
getNodeAddrInfo(node.data(), nullptr, hints);
}
/**
* @brief Sync [getaddrinfo](http://linux.die.net/man/3/getaddrinfo).
*
* @param node Either a numerical network address or a network hostname.
* @param hints Optional `addrinfo` data structure with additional address
* type constraints.
*
* @return A `std::pair` composed as it follows:
* * A boolean value that is true in case of success, false otherwise.
* * A `std::unique_ptr<addrinfo, Deleter>` containing the data requested.
*/
std::pair<bool, std::unique_ptr<addrinfo, Deleter>>
getNodeAddrInfoSync(std::string node, addrinfo *hints = nullptr) {
return getNodeAddrInfoSync(node.data(), nullptr, hints);
}
/**
* @brief Async [getaddrinfo](http://linux.die.net/man/3/getaddrinfo).
* @param service Either a service name or a port number as a string.
* @param hints Optional `addrinfo` data structure with additional address
* type constraints.
*/
void getServiceAddrInfo(std::string service, addrinfo *hints = nullptr) {
getNodeAddrInfo(nullptr, service.data(), hints);
}
/**
* @brief Sync [getaddrinfo](http://linux.die.net/man/3/getaddrinfo).
*
* @param service Either a service name or a port number as a string.
* @param hints Optional `addrinfo` data structure with additional address
* type constraints.
*
* @return A `std::pair` composed as it follows:
* * A boolean value that is true in case of success, false otherwise.
* * A `std::unique_ptr<addrinfo, Deleter>` containing the data requested.
*/
std::pair<bool, std::unique_ptr<addrinfo, Deleter>>
getServiceAddrInfoSync(std::string service, addrinfo *hints = nullptr) {
return getNodeAddrInfoSync(nullptr, service.data(), hints);
}
/**
* @brief Async [getaddrinfo](http://linux.die.net/man/3/getaddrinfo).
* @param node Either a numerical network address or a network hostname.
* @param service Either a service name or a port number as a string.
* @param hints Optional `addrinfo` data structure with additional address
* type constraints.
*/
void getAddrInfo(std::string node, std::string service, addrinfo *hints = nullptr) {
getNodeAddrInfo(node.data(), service.data(), hints);
}
/**
* @brief Sync [getaddrinfo](http://linux.die.net/man/3/getaddrinfo).
*
* @param node Either a numerical network address or a network hostname.
* @param service Either a service name or a port number as a string.
* @param hints Optional `addrinfo` data structure with additional address
* type constraints.
*
* @return A `std::pair` composed as it follows:
* * A boolean value that is true in case of success, false otherwise.
* * A `std::unique_ptr<addrinfo, Deleter>` containing the data requested.
*/
std::pair<bool, std::unique_ptr<addrinfo, Deleter>>
getAddrInfoSync(std::string node, std::string service, addrinfo *hints = nullptr) {
return getNodeAddrInfoSync(node.data(), service.data(), hints);
}
};
/**
* @brief The GetNameInfoReq request.
*
* Wrapper for [getnameinfo](http://linux.die.net/man/3/getnameinfo).<br/>
* It offers either asynchronous and synchronous access methods.
*
* To create a `GetNameInfoReq` through a `Loop`, no arguments are required.
*/
class GetNameInfoReq final: public Request<GetNameInfoReq, uv_getnameinfo_t> {
static void getNameInfoCallback(uv_getnameinfo_t *req, int status, const char *hostname, const char *service) {
auto ptr = reserve(req);
if(status) { ptr->publish(ErrorEvent{status}); }
else { ptr->publish(NameInfoEvent{hostname, service}); }
}
public:
using Request::Request;
/**
* @brief Async [getnameinfo](http://linux.die.net/man/3/getnameinfo).
* @param ip A valid IP address.
* @param port A valid port number.
* @param flags Optional flags that modify the behavior of `getnameinfo`.
*/
template<typename I = IPv4>
void getNameInfo(std::string ip, unsigned int port, int flags = 0) {
typename details::IpTraits<I>::Type addr;
details::IpTraits<I>::AddrFunc(ip.data(), port, &addr);
invoke(&uv_getnameinfo, parent(), get(), &getNameInfoCallback, &addr, flags);
}
/**
* @brief Async [getnameinfo](http://linux.die.net/man/3/getnameinfo).
* @param addr A valid instance of Addr.
* @param flags Optional flags that modify the behavior of `getnameinfo`.
*/
template<typename I = IPv4>
void getNameInfo(Addr addr, int flags = 0) {
getNameInfo<I>(addr.ip, addr.port, flags);
}
/**
* @brief Sync [getnameinfo](http://linux.die.net/man/3/getnameinfo).
*
* @param ip A valid IP address.
* @param port A valid port number.
* @param flags Optional flags that modify the behavior of `getnameinfo`.
*
* @return A `std::pair` composed as it follows:
* * A boolean value that is true in case of success, false otherwise.
* * A `std::pair` composed as it follows:
* * A `const char *` containing a valid hostname.
* * A `const char *` containing a valid service name.
*/
template<typename I = IPv4>
std::pair<bool, std::pair<const char *, const char *>>
getNameInfoSync(std::string ip, unsigned int port, int flags = 0) {
typename details::IpTraits<I>::Type addr;
details::IpTraits<I>::AddrFunc(ip.data(), port, &addr);
auto req = get();
auto err = uv_getnameinfo(parent(), req, nullptr, &addr, flags);
return std::make_pair(!err, std::make_pair(req->host, req->service));
}
/**
* @brief Sync [getnameinfo](http://linux.die.net/man/3/getnameinfo).
*
* @param addr A valid instance of Addr.
* @param flags Optional flags that modify the behavior of `getnameinfo`.
*
* @return A `std::pair` composed as it follows:
* * A boolean value that is true in case of success, false otherwise.
* * A `std::pair` composed as it follows:
* * A `const char *` containing a valid hostname.
* * A `const char *` containing a valid service name.
*/
template<typename I = IPv4>
std::pair<bool, std::pair<const char *, const char *>>
getNameInfoSync(Addr addr, int flags = 0) {
return getNameInfoSync<I>(addr.ip, addr.port, flags);
}
};
}
<commit_msg>Update dns.hpp<commit_after>#pragma once
#include <utility>
#include <memory>
#include <string>
#include <uv.h>
#include "event.hpp"
#include "request.hpp"
#include "util.hpp"
#include "loop.hpp"
namespace uvw {
/**
* @brief AddrInfoEvent event.
*
* It will be emitted by GetAddrInfoReq according with its functionalities.
*/
struct AddrInfoEvent: Event<AddrInfoEvent> {
using Deleter = void(*)(addrinfo *);
AddrInfoEvent(std::unique_ptr<addrinfo, Deleter> addr)
: data{std::move(addr)}
{}
/**
* @brief An initialized instance of `addrinfo`.
*
* See [getaddrinfo](http://linux.die.net/man/3/getaddrinfo) for further
* details.
*/
std::unique_ptr<addrinfo, Deleter> data;
};
/**
* @brief NameInfoEvent event.
*
* It will be emitted by GetNameInfoReq according with its functionalities.
*/
struct NameInfoEvent: Event<NameInfoEvent> {
NameInfoEvent(const char *host, const char *serv)
: hostname{host}, service{serv}
{}
/**
* @brief A valid hostname.
*
* See [getnameinfo](http://linux.die.net/man/3/getnameinfo) for further
* details.
*/
const char * hostname;
/**
* @brief A valid service name.
*
* See [getnameinfo](http://linux.die.net/man/3/getnameinfo) for further
* details.
*/
const char * service;
};
/**
* @brief The GetAddrInfoReq request.
*
* Wrapper for [getaddrinfo](http://linux.die.net/man/3/getaddrinfo).<br/>
* It offers either asynchronous and synchronous access methods.
*
* To create a `GetAddrInfoReq` through a `Loop`, no arguments are required.
*/
class GetAddrInfoReq final: public Request<GetAddrInfoReq, uv_getaddrinfo_t> {
static void getAddrInfoCallback(uv_getaddrinfo_t *req, int status, addrinfo *res) {
auto ptr = reserve(req);
if(status) {
ptr->publish(ErrorEvent{status});
} else {
auto data = std::unique_ptr<addrinfo, void(*)(addrinfo *)>{
res, [](addrinfo *addr){ uv_freeaddrinfo(addr); }};
ptr->publish(AddrInfoEvent{std::move(data)});
}
}
void getNodeAddrInfo(const char *node, const char *service, addrinfo *hints = nullptr) {
invoke(&uv_getaddrinfo, parent(), get(), &getAddrInfoCallback, node, service, hints);
}
auto getNodeAddrInfoSync(const char *node, const char *service, addrinfo *hints = nullptr) {
auto req = get();
auto err = uv_getaddrinfo(parent(), req, nullptr, node, service, hints);
auto data = std::unique_ptr<addrinfo, void(*)(addrinfo *)>{req->addrinfo, [](addrinfo *addr){ uv_freeaddrinfo(addr); }};
return std::make_pair(!err, std::move(data));
}
public:
using Deleter = void(*)(addrinfo *);
using Request::Request;
/**
* @brief Async [getaddrinfo](http://linux.die.net/man/3/getaddrinfo).
* @param node Either a numerical network address or a network hostname.
* @param hints Optional `addrinfo` data structure with additional address
* type constraints.
*/
void getNodeAddrInfo(std::string node, addrinfo *hints = nullptr) {
getNodeAddrInfo(node.data(), nullptr, hints);
}
/**
* @brief Sync [getaddrinfo](http://linux.die.net/man/3/getaddrinfo).
*
* @param node Either a numerical network address or a network hostname.
* @param hints Optional `addrinfo` data structure with additional address
* type constraints.
*
* @return A `std::pair` composed as it follows:
* * A boolean value that is true in case of success, false otherwise.
* * A `std::unique_ptr<addrinfo, Deleter>` containing the data requested.
*/
std::pair<bool, std::unique_ptr<addrinfo, Deleter>>
getNodeAddrInfoSync(std::string node, addrinfo *hints = nullptr) {
return getNodeAddrInfoSync(node.data(), nullptr, hints);
}
/**
* @brief Async [getaddrinfo](http://linux.die.net/man/3/getaddrinfo).
* @param service Either a service name or a port number as a string.
* @param hints Optional `addrinfo` data structure with additional address
* type constraints.
*/
void getServiceAddrInfo(std::string service, addrinfo *hints = nullptr) {
getNodeAddrInfo(nullptr, service.data(), hints);
}
/**
* @brief Sync [getaddrinfo](http://linux.die.net/man/3/getaddrinfo).
*
* @param service Either a service name or a port number as a string.
* @param hints Optional `addrinfo` data structure with additional address
* type constraints.
*
* @return A `std::pair` composed as it follows:
* * A boolean value that is true in case of success, false otherwise.
* * A `std::unique_ptr<addrinfo, Deleter>` containing the data requested.
*/
std::pair<bool, std::unique_ptr<addrinfo, Deleter>>
getServiceAddrInfoSync(std::string service, addrinfo *hints = nullptr) {
return getNodeAddrInfoSync(nullptr, service.data(), hints);
}
/**
* @brief Async [getaddrinfo](http://linux.die.net/man/3/getaddrinfo).
* @param node Either a numerical network address or a network hostname.
* @param service Either a service name or a port number as a string.
* @param hints Optional `addrinfo` data structure with additional address
* type constraints.
*/
void getAddrInfo(std::string node, std::string service, addrinfo *hints = nullptr) {
getNodeAddrInfo(node.data(), service.data(), hints);
}
/**
* @brief Sync [getaddrinfo](http://linux.die.net/man/3/getaddrinfo).
*
* @param node Either a numerical network address or a network hostname.
* @param service Either a service name or a port number as a string.
* @param hints Optional `addrinfo` data structure with additional address
* type constraints.
*
* @return A `std::pair` composed as it follows:
* * A boolean value that is true in case of success, false otherwise.
* * A `std::unique_ptr<addrinfo, Deleter>` containing the data requested.
*/
std::pair<bool, std::unique_ptr<addrinfo, Deleter>>
getAddrInfoSync(std::string node, std::string service, addrinfo *hints = nullptr) {
return getNodeAddrInfoSync(node.data(), service.data(), hints);
}
};
/**
* @brief The GetNameInfoReq request.
*
* Wrapper for [getnameinfo](http://linux.die.net/man/3/getnameinfo).<br/>
* It offers either asynchronous and synchronous access methods.
*
* To create a `GetNameInfoReq` through a `Loop`, no arguments are required.
*/
class GetNameInfoReq final: public Request<GetNameInfoReq, uv_getnameinfo_t> {
static void getNameInfoCallback(uv_getnameinfo_t *req, int status, const char *hostname, const char *service) {
auto ptr = reserve(req);
if(status) { ptr->publish(ErrorEvent{status}); }
else { ptr->publish(NameInfoEvent{hostname, service}); }
}
public:
using Request::Request;
/**
* @brief Async [getnameinfo](http://linux.die.net/man/3/getnameinfo).
* @param ip A valid IP address.
* @param port A valid port number.
* @param flags Optional flags that modify the behavior of `getnameinfo`.
*/
template<typename I = IPv4>
void getNameInfo(std::string ip, unsigned int port, int flags = 0) {
typename details::IpTraits<I>::Type addr;
details::IpTraits<I>::AddrFunc(ip.data(), port, &addr);
invoke(&uv_getnameinfo, parent(), get(), &getNameInfoCallback, &addr, flags);
}
/**
* @brief Async [getnameinfo](http://linux.die.net/man/3/getnameinfo).
* @param addr A valid instance of Addr.
* @param flags Optional flags that modify the behavior of `getnameinfo`.
*/
template<typename I = IPv4>
void getNameInfo(Addr addr, int flags = 0) {
getNameInfo<I>(addr.ip, addr.port, flags);
}
/**
* @brief Sync [getnameinfo](http://linux.die.net/man/3/getnameinfo).
*
* @param ip A valid IP address.
* @param port A valid port number.
* @param flags Optional flags that modify the behavior of `getnameinfo`.
*
* @return A `std::pair` composed as it follows:
* * A boolean value that is true in case of success, false otherwise.
* * A `std::pair` composed as it follows:
* * A `const char *` containing a valid hostname.
* * A `const char *` containing a valid service name.
*/
template<typename I = IPv4>
std::pair<bool, std::pair<const char *, const char *>>
getNameInfoSync(std::string ip, unsigned int port, int flags = 0) {
typename details::IpTraits<I>::Type addr;
details::IpTraits<I>::AddrFunc(ip.data(), port, &addr);
auto req = get();
auto err = uv_getnameinfo(parent(), req, nullptr, &addr, flags);
return std::make_pair(!err, std::make_pair(req->host, req->service));
}
/**
* @brief Sync [getnameinfo](http://linux.die.net/man/3/getnameinfo).
*
* @param addr A valid instance of Addr.
* @param flags Optional flags that modify the behavior of `getnameinfo`.
*
* @return A `std::pair` composed as it follows:
* * A boolean value that is true in case of success, false otherwise.
* * A `std::pair` composed as it follows:
* * A `const char *` containing a valid hostname.
* * A `const char *` containing a valid service name.
*/
template<typename I = IPv4>
std::pair<bool, std::pair<const char *, const char *>>
getNameInfoSync(Addr addr, int flags = 0) {
return getNameInfoSync<I>(addr.ip, addr.port, flags);
}
};
}
<|endoftext|>
|
<commit_before>/*
SWARM
Copyright (C) 2012-2019 Torbjorn Rognes and Frederic Mahe
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Contact: Torbjorn Rognes <torognes@ifi.uio.no>,
Department of Informatics, University of Oslo,
PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/
#include "swarm.h"
inline void nt_set(char * seq, unsigned int pos, unsigned int base)
{
unsigned int whichlong = pos >> 5;
uint64_t shift = (pos & 31) << 1;
uint64_t mask = 3ULL << shift;
uint64_t x = (reinterpret_cast<uint64_t *>(seq))[whichlong];
x &= ~ mask;
x |= (static_cast<uint64_t>(base)) << shift;
(reinterpret_cast<uint64_t *>(seq))[whichlong] = x;
}
inline void seq_copy(char * a,
unsigned int a_start,
char * b,
unsigned int b_start,
unsigned int length)
{
/* copy part of the compressed sequence b to a */
for(unsigned int i = 0; i < length; i++)
nt_set(a, a_start + i, nt_extract(b, b_start + i));
}
inline bool seq_identical(char * a,
unsigned int a_start,
char * b,
unsigned int b_start,
unsigned int length)
{
/* compare parts of two compressed sequences a and b */
/* return false if different, true if identical */
for(unsigned int i = 0; i < length; i++)
if (nt_extract(a, a_start + i) != nt_extract(b, b_start + i))
return false;
return true;
}
void generate_variant_sequence(char * seed_sequence,
unsigned int seed_seqlen,
struct var_s * var,
char * seq,
unsigned int * seqlen)
{
/* generate the actual sequence of a variant */
switch (var->type)
{
case identical:
memcpy(seq, seed_sequence, nt_bytelength(seed_seqlen));
* seqlen = seed_seqlen;
break;
case substitution:
memcpy(seq, seed_sequence, nt_bytelength(seed_seqlen));
nt_set(seq, var->pos, var->base);
* seqlen = seed_seqlen;
break;
case deletion:
seq_copy(seq, 0,
seed_sequence, 0,
var->pos);
seq_copy(seq, var->pos,
seed_sequence, var->pos + 1,
seed_seqlen - var->pos - 1);
* seqlen = seed_seqlen - 1;
break;
case insertion:
seq_copy(seq, 0,
seed_sequence, 0,
var->pos);
nt_set(seq, var->pos, var->base);
seq_copy(seq, var->pos + 1,
seed_sequence, var->pos,
seed_seqlen - var->pos);
* seqlen = seed_seqlen + 1;
break;
default:
assert(0);
}
}
bool check_variant(char * seed_sequence,
unsigned int seed_seqlen,
var_s * var,
char * amp_sequence,
unsigned int amp_seqlen)
{
/* make sure seed with given variant is really identical to amp */
/* we know the hashes are identical */
switch (var->type)
{
case identical:
if (seed_seqlen != amp_seqlen)
return false;
return seq_identical(seed_sequence, 0,
amp_sequence, 0,
seed_seqlen);
case substitution:
if (seed_seqlen != amp_seqlen)
return false;
if (! seq_identical(seed_sequence, 0,
amp_sequence, 0,
var->pos))
return false;
if (nt_extract(amp_sequence, var->pos) != var->base)
return false;
return seq_identical(seed_sequence, var->pos + 1,
amp_sequence, var->pos + 1,
seed_seqlen - var->pos - 1);
case deletion:
if ((seed_seqlen - 1) != amp_seqlen)
return false;
if (! seq_identical(seed_sequence, 0,
amp_sequence, 0,
var->pos))
return false;
return seq_identical(seed_sequence, var->pos + 1,
amp_sequence, var->pos,
seed_seqlen - var->pos - 1);
case insertion:
if ((seed_seqlen + 1) != amp_seqlen)
return false;
if (! seq_identical(seed_sequence, 0,
amp_sequence, 0,
var->pos))
return false;
if (nt_extract(amp_sequence, var->pos) != var->base)
return false;
return seq_identical(seed_sequence, var->pos,
amp_sequence, var->pos + 1,
seed_seqlen - var->pos);
default:
assert(0);
}
}
inline void add_variant(uint64_t hash,
unsigned char type,
unsigned int pos,
unsigned char base,
var_s * variant_list,
unsigned int * variant_count)
{
#ifdef HASHSTATS
tries++;
#endif
var_s * v = variant_list + (*variant_count)++;
v->hash = hash;
v->type = type;
v->pos = pos;
v->base = base;
}
void generate_variants(char * sequence,
unsigned int seqlen,
uint64_t hash,
var_s * variant_list,
unsigned int * variant_count)
{
/* substitutions */
for(unsigned int i = 0; i < seqlen; i++)
{
unsigned char base = nt_extract(sequence, i);
uint64_t hash1 = hash ^ zobrist_value(i, base);
for (unsigned char v = 0; v < 4; v ++)
if (v != base)
{
uint64_t hash2 = hash1 ^ zobrist_value(i, v);
add_variant(hash2, substitution, i, v,
variant_list, variant_count);
}
}
/* deletions */
hash = zobrist_hash_delete_first(reinterpret_cast<unsigned char *>(sequence), seqlen);
add_variant(hash, deletion, 0, 0, variant_list, variant_count);
unsigned char base_deleted = nt_extract(sequence, 0);
for(unsigned int i = 1; i < seqlen; i++)
{
unsigned char v = nt_extract(sequence, i);
if (v != base_deleted)
{
hash ^= zobrist_value(i - 1, base_deleted) ^ zobrist_value(i - 1, v);
add_variant(hash, deletion, i, 0, variant_list, variant_count);
base_deleted = v;
}
}
/* insertions */
hash = zobrist_hash_insert_first(reinterpret_cast<unsigned char *>(sequence), seqlen);
for (unsigned char v = 0; v < 4; v++)
{
uint64_t hash1 = hash ^ zobrist_value(0, v);
add_variant(hash1, insertion, 0, v, variant_list, variant_count);
}
for (unsigned int i = 0; i < seqlen; i++)
{
unsigned char base = nt_extract(sequence, i);
hash ^= zobrist_value(i, base) ^ zobrist_value(i+1, base);
for (unsigned char v = 0; v < 4; v++)
if (v != base)
{
uint64_t hash1 = hash ^ zobrist_value(i + 1, v);
add_variant(hash1, insertion, i + 1, v,
variant_list, variant_count);
}
}
}
<commit_msg>Fix compiler warning<commit_after>/*
SWARM
Copyright (C) 2012-2019 Torbjorn Rognes and Frederic Mahe
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Contact: Torbjorn Rognes <torognes@ifi.uio.no>,
Department of Informatics, University of Oslo,
PO Box 1080 Blindern, NO-0316 Oslo, Norway
*/
#include "swarm.h"
inline void nt_set(char * seq, unsigned int pos, unsigned int base)
{
unsigned int whichlong = pos >> 5;
uint64_t shift = (pos & 31) << 1;
uint64_t mask = 3ULL << shift;
uint64_t x = (reinterpret_cast<uint64_t *>(seq))[whichlong];
x &= ~ mask;
x |= (static_cast<uint64_t>(base)) << shift;
(reinterpret_cast<uint64_t *>(seq))[whichlong] = x;
}
inline void seq_copy(char * a,
unsigned int a_start,
char * b,
unsigned int b_start,
unsigned int length)
{
/* copy part of the compressed sequence b to a */
for(unsigned int i = 0; i < length; i++)
nt_set(a, a_start + i, nt_extract(b, b_start + i));
}
inline bool seq_identical(char * a,
unsigned int a_start,
char * b,
unsigned int b_start,
unsigned int length)
{
/* compare parts of two compressed sequences a and b */
/* return false if different, true if identical */
for(unsigned int i = 0; i < length; i++)
if (nt_extract(a, a_start + i) != nt_extract(b, b_start + i))
return false;
return true;
}
void generate_variant_sequence(char * seed_sequence,
unsigned int seed_seqlen,
struct var_s * var,
char * seq,
unsigned int * seqlen)
{
/* generate the actual sequence of a variant */
switch (var->type)
{
case identical:
memcpy(seq, seed_sequence, nt_bytelength(seed_seqlen));
* seqlen = seed_seqlen;
break;
case substitution:
memcpy(seq, seed_sequence, nt_bytelength(seed_seqlen));
nt_set(seq, var->pos, var->base);
* seqlen = seed_seqlen;
break;
case deletion:
seq_copy(seq, 0,
seed_sequence, 0,
var->pos);
seq_copy(seq, var->pos,
seed_sequence, var->pos + 1,
seed_seqlen - var->pos - 1);
* seqlen = seed_seqlen - 1;
break;
case insertion:
seq_copy(seq, 0,
seed_sequence, 0,
var->pos);
nt_set(seq, var->pos, var->base);
seq_copy(seq, var->pos + 1,
seed_sequence, var->pos,
seed_seqlen - var->pos);
* seqlen = seed_seqlen + 1;
break;
default:
assert(0);
}
}
bool check_variant(char * seed_sequence,
unsigned int seed_seqlen,
var_s * var,
char * amp_sequence,
unsigned int amp_seqlen)
{
/* make sure seed with given variant is really identical to amp */
/* we know the hashes are identical */
switch (var->type)
{
case identical:
if (seed_seqlen != amp_seqlen)
return false;
return seq_identical(seed_sequence, 0,
amp_sequence, 0,
seed_seqlen);
case substitution:
if (seed_seqlen != amp_seqlen)
return false;
if (! seq_identical(seed_sequence, 0,
amp_sequence, 0,
var->pos))
return false;
if (nt_extract(amp_sequence, var->pos) != var->base)
return false;
return seq_identical(seed_sequence, var->pos + 1,
amp_sequence, var->pos + 1,
seed_seqlen - var->pos - 1);
case deletion:
if ((seed_seqlen - 1) != amp_seqlen)
return false;
if (! seq_identical(seed_sequence, 0,
amp_sequence, 0,
var->pos))
return false;
return seq_identical(seed_sequence, var->pos + 1,
amp_sequence, var->pos,
seed_seqlen - var->pos - 1);
case insertion:
if ((seed_seqlen + 1) != amp_seqlen)
return false;
if (! seq_identical(seed_sequence, 0,
amp_sequence, 0,
var->pos))
return false;
if (nt_extract(amp_sequence, var->pos) != var->base)
return false;
return seq_identical(seed_sequence, var->pos,
amp_sequence, var->pos + 1,
seed_seqlen - var->pos);
default:
assert(0);
return false;
}
}
inline void add_variant(uint64_t hash,
unsigned char type,
unsigned int pos,
unsigned char base,
var_s * variant_list,
unsigned int * variant_count)
{
#ifdef HASHSTATS
tries++;
#endif
var_s * v = variant_list + (*variant_count)++;
v->hash = hash;
v->type = type;
v->pos = pos;
v->base = base;
}
void generate_variants(char * sequence,
unsigned int seqlen,
uint64_t hash,
var_s * variant_list,
unsigned int * variant_count)
{
/* substitutions */
for(unsigned int i = 0; i < seqlen; i++)
{
unsigned char base = nt_extract(sequence, i);
uint64_t hash1 = hash ^ zobrist_value(i, base);
for (unsigned char v = 0; v < 4; v ++)
if (v != base)
{
uint64_t hash2 = hash1 ^ zobrist_value(i, v);
add_variant(hash2, substitution, i, v,
variant_list, variant_count);
}
}
/* deletions */
hash = zobrist_hash_delete_first(reinterpret_cast<unsigned char *>(sequence), seqlen);
add_variant(hash, deletion, 0, 0, variant_list, variant_count);
unsigned char base_deleted = nt_extract(sequence, 0);
for(unsigned int i = 1; i < seqlen; i++)
{
unsigned char v = nt_extract(sequence, i);
if (v != base_deleted)
{
hash ^= zobrist_value(i - 1, base_deleted) ^ zobrist_value(i - 1, v);
add_variant(hash, deletion, i, 0, variant_list, variant_count);
base_deleted = v;
}
}
/* insertions */
hash = zobrist_hash_insert_first(reinterpret_cast<unsigned char *>(sequence), seqlen);
for (unsigned char v = 0; v < 4; v++)
{
uint64_t hash1 = hash ^ zobrist_value(0, v);
add_variant(hash1, insertion, 0, v, variant_list, variant_count);
}
for (unsigned int i = 0; i < seqlen; i++)
{
unsigned char base = nt_extract(sequence, i);
hash ^= zobrist_value(i, base) ^ zobrist_value(i+1, base);
for (unsigned char v = 0; v < 4; v++)
if (v != base)
{
uint64_t hash1 = hash ^ zobrist_value(i + 1, v);
add_variant(hash1, insertion, i + 1, v,
variant_list, variant_count);
}
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Vcoin");
// Client version number
#define CLIENT_VERSION_SUFFIX "-beta"
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "54182cb"
# define GIT_COMMIT_DATE "Wed, 1 Oct 2014 08:01:20 -0700"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>12.0.1<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Vcoin");
// Client version number
#define CLIENT_VERSION_SUFFIX "-beta"
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "54182cb"
# define GIT_COMMIT_DATE "Thu, 1 Jan 2015 01:01:01 -0700"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");
// Client version number
#define CLIENT_VERSION_SUFFIX "-beta"
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "$Format:%h$"
# define GIT_COMMIT_DATE "$Format:%cD$"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(PEERCOIN_VERSION_MAJOR, PEERCOIN_VERSION_MINOR, PEERCOIN_VERSION_REVISION, PEERCOIN_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(PEERCOIN_VERSION_MAJOR, PEERCOIN_VERSION_MINOR, PEERCOIN_VERSION_REVISION, PEERCOIN_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>Remove -beta suffix on release-0.6 branch<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");
// Client version number
#define CLIENT_VERSION_SUFFIX ""
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "$Format:%h$"
# define GIT_COMMIT_DATE "$Format:%cD$"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(PEERCOIN_VERSION_MAJOR, PEERCOIN_VERSION_MINOR, PEERCOIN_VERSION_REVISION, PEERCOIN_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(PEERCOIN_VERSION_MAJOR, PEERCOIN_VERSION_MINOR, PEERCOIN_VERSION_REVISION, PEERCOIN_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>
|
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
#include <Eigen/CXX11/Tensor>
using Eigen::Tensor;
using Eigen::RowMajor;
static void test_simple_lvalue_ref()
{
Tensor<int, 1> input(6);
input.setRandom();
TensorRef<Tensor<int, 1>> ref3(input);
TensorRef<Tensor<int, 1>> ref4 = input;
VERIFY_IS_EQUAL(ref3.data(), input.data());
VERIFY_IS_EQUAL(ref4.data(), input.data());
for (int i = 0; i < 6; ++i) {
VERIFY_IS_EQUAL(ref3(i), input(i));
VERIFY_IS_EQUAL(ref4(i), input(i));
}
for (int i = 0; i < 6; ++i) {
ref3.coeffRef(i) = i;
}
for (int i = 0; i < 6; ++i) {
VERIFY_IS_EQUAL(input(i), i);
}
for (int i = 0; i < 6; ++i) {
ref4.coeffRef(i) = -i * 2;
}
for (int i = 0; i < 6; ++i) {
VERIFY_IS_EQUAL(input(i), -i*2);
}
}
static void test_simple_rvalue_ref()
{
Tensor<int, 1> input1(6);
input1.setRandom();
Tensor<int, 1> input2(6);
input2.setRandom();
TensorRef<Tensor<int, 1>> ref3(input1 + input2);
TensorRef<Tensor<int, 1>> ref4 = input1 + input2;
VERIFY_IS_NOT_EQUAL(ref3.data(), input1.data());
VERIFY_IS_NOT_EQUAL(ref4.data(), input1.data());
VERIFY_IS_NOT_EQUAL(ref3.data(), input2.data());
VERIFY_IS_NOT_EQUAL(ref4.data(), input2.data());
for (int i = 0; i < 6; ++i) {
VERIFY_IS_EQUAL(ref3(i), input1(i) + input2(i));
VERIFY_IS_EQUAL(ref4(i), input1(i) + input2(i));
}
}
static void test_multiple_dims()
{
Tensor<float, 3> input(3,5,7);
input.setRandom();
TensorRef<Tensor<float, 3>> ref(input);
VERIFY_IS_EQUAL(ref.data(), input.data());
VERIFY_IS_EQUAL(ref.dimension(0), 3);
VERIFY_IS_EQUAL(ref.dimension(1), 5);
VERIFY_IS_EQUAL(ref.dimension(2), 7);
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 5; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_EQUAL(ref(i,j,k), input(i,j,k));
}
}
}
}
static void test_slice()
{
Tensor<float, 5> tensor(2,3,5,7,11);
tensor.setRandom();
Eigen::DSizes<ptrdiff_t, 5> indices(1,2,3,4,5);
Eigen::DSizes<ptrdiff_t, 5> sizes(1,1,1,1,1);
TensorRef<Tensor<float, 5>> slice = tensor.slice(indices, sizes);
VERIFY_IS_EQUAL(slice(0,0,0,0,0), tensor(1,2,3,4,5));
Eigen::DSizes<ptrdiff_t, 5> indices2(1,1,3,4,5);
Eigen::DSizes<ptrdiff_t, 5> sizes2(1,1,2,2,3);
slice = tensor.slice(indices2, sizes2);
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
for (int k = 0; k < 3; ++k) {
VERIFY_IS_EQUAL(slice(0,0,i,j,k), tensor(1,1,3+i,4+j,5+k));
}
}
}
Eigen::DSizes<ptrdiff_t, 5> indices3(0,0,0,0,0);
Eigen::DSizes<ptrdiff_t, 5> sizes3(2,3,1,1,1);
slice = tensor.slice(indices3, sizes3);
VERIFY_IS_EQUAL(slice.data(), tensor.data());
}
static void test_ref_of_ref()
{
Tensor<float, 3> input(3,5,7);
input.setRandom();
TensorRef<Tensor<float, 3>> ref(input);
TensorRef<Tensor<float, 3>> ref_of_ref(ref);
TensorRef<Tensor<float, 3>> ref_of_ref2;
ref_of_ref2 = ref;
VERIFY_IS_EQUAL(ref_of_ref.data(), input.data());
VERIFY_IS_EQUAL(ref_of_ref.dimension(0), 3);
VERIFY_IS_EQUAL(ref_of_ref.dimension(1), 5);
VERIFY_IS_EQUAL(ref_of_ref.dimension(2), 7);
VERIFY_IS_EQUAL(ref_of_ref2.data(), input.data());
VERIFY_IS_EQUAL(ref_of_ref2.dimension(0), 3);
VERIFY_IS_EQUAL(ref_of_ref2.dimension(1), 5);
VERIFY_IS_EQUAL(ref_of_ref2.dimension(2), 7);
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 5; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_EQUAL(ref_of_ref(i,j,k), input(i,j,k));
VERIFY_IS_EQUAL(ref_of_ref2(i,j,k), input(i,j,k));
}
}
}
}
static void test_ref_in_expr()
{
Tensor<float, 3> input(3,5,7);
input.setRandom();
TensorRef<Tensor<float, 3>> input_ref(input);
Tensor<float, 3> result(3,5,7);
result.setRandom();
TensorRef<Tensor<float, 3>> result_ref(result);
Tensor<float, 3> bias(3,5,7);
bias.setRandom();
result_ref = input_ref + bias;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 5; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_EQUAL(result_ref(i,j,k), input(i,j,k) + bias(i,j,k));
VERIFY_IS_NOT_EQUAL(result(i,j,k), input(i,j,k) + bias(i,j,k));
}
}
}
result = result_ref;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 5; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_EQUAL(result(i,j,k), input(i,j,k) + bias(i,j,k));
}
}
}
}
static void test_coeff_ref()
{
Tensor<float, 5> tensor(2,3,5,7,11);
tensor.setRandom();
Tensor<float, 5> original = tensor;
TensorRef<Tensor<float, 4>> slice = tensor.chip(7, 4);
slice.coeffRef(0, 0, 0, 0) = 1.0f;
slice.coeffRef(1, 0, 0, 0) += 2.0f;
VERIFY_IS_EQUAL(tensor(0,0,0,0,7), 1.0f);
VERIFY_IS_EQUAL(tensor(1,0,0,0,7), original(1,0,0,0,7) + 2.0f);
}
static void test_nested_ops_with_ref()
{
Tensor<float, 4> t(2, 3, 5, 7);
t.setRandom();
TensorMap<Tensor<const float, 4> > m(t.data(), 2, 3, 5, 7);
array<pair<ptrdiff_t, ptrdiff_t>, 4> paddings;
paddings[0] = make_pair(0, 0);
paddings[1] = make_pair(2, 1);
paddings[2] = make_pair(3, 4);
paddings[3] = make_pair(0, 0);
Eigen::DSizes<Eigen::DenseIndex, 4> shuffle_dims{0, 1, 2, 3};
TensorRef<Tensor<const float, 4> > ref(m.pad(paddings));
array<pair<ptrdiff_t, ptrdiff_t>, 4> trivial;
trivial[0] = make_pair(0, 0);
trivial[1] = make_pair(0, 0);
trivial[2] = make_pair(0, 0);
trivial[3] = make_pair(0, 0);
Tensor<float, 4> padded = ref.shuffle(shuffle_dims).pad(trivial);
VERIFY_IS_EQUAL(padded.dimension(0), 2+0);
VERIFY_IS_EQUAL(padded.dimension(1), 3+3);
VERIFY_IS_EQUAL(padded.dimension(2), 5+7);
VERIFY_IS_EQUAL(padded.dimension(3), 7+0);
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 6; ++j) {
for (int k = 0; k < 12; ++k) {
for (int l = 0; l < 7; ++l) {
if (j >= 2 && j < 5 && k >= 3 && k < 8) {
VERIFY_IS_EQUAL(padded(i,j,k,l), t(i,j-2,k-3,l));
} else {
VERIFY_IS_EQUAL(padded(i,j,k,l), 0.0f);
}
}
}
}
}
}
void test_cxx11_tensor_ref()
{
CALL_SUBTEST(test_simple_lvalue_ref());
CALL_SUBTEST(test_simple_rvalue_ref());
CALL_SUBTEST(test_multiple_dims());
CALL_SUBTEST(test_slice());
CALL_SUBTEST(test_ref_of_ref());
CALL_SUBTEST(test_ref_in_expr());
CALL_SUBTEST(test_coeff_ref());
CALL_SUBTEST(test_nested_ops_with_ref());
}
<commit_msg>Fixed compilation error with clang<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
#include <Eigen/CXX11/Tensor>
using Eigen::Tensor;
using Eigen::RowMajor;
static void test_simple_lvalue_ref()
{
Tensor<int, 1> input(6);
input.setRandom();
TensorRef<Tensor<int, 1>> ref3(input);
TensorRef<Tensor<int, 1>> ref4 = input;
VERIFY_IS_EQUAL(ref3.data(), input.data());
VERIFY_IS_EQUAL(ref4.data(), input.data());
for (int i = 0; i < 6; ++i) {
VERIFY_IS_EQUAL(ref3(i), input(i));
VERIFY_IS_EQUAL(ref4(i), input(i));
}
for (int i = 0; i < 6; ++i) {
ref3.coeffRef(i) = i;
}
for (int i = 0; i < 6; ++i) {
VERIFY_IS_EQUAL(input(i), i);
}
for (int i = 0; i < 6; ++i) {
ref4.coeffRef(i) = -i * 2;
}
for (int i = 0; i < 6; ++i) {
VERIFY_IS_EQUAL(input(i), -i*2);
}
}
static void test_simple_rvalue_ref()
{
Tensor<int, 1> input1(6);
input1.setRandom();
Tensor<int, 1> input2(6);
input2.setRandom();
TensorRef<Tensor<int, 1>> ref3(input1 + input2);
TensorRef<Tensor<int, 1>> ref4 = input1 + input2;
VERIFY_IS_NOT_EQUAL(ref3.data(), input1.data());
VERIFY_IS_NOT_EQUAL(ref4.data(), input1.data());
VERIFY_IS_NOT_EQUAL(ref3.data(), input2.data());
VERIFY_IS_NOT_EQUAL(ref4.data(), input2.data());
for (int i = 0; i < 6; ++i) {
VERIFY_IS_EQUAL(ref3(i), input1(i) + input2(i));
VERIFY_IS_EQUAL(ref4(i), input1(i) + input2(i));
}
}
static void test_multiple_dims()
{
Tensor<float, 3> input(3,5,7);
input.setRandom();
TensorRef<Tensor<float, 3>> ref(input);
VERIFY_IS_EQUAL(ref.data(), input.data());
VERIFY_IS_EQUAL(ref.dimension(0), 3);
VERIFY_IS_EQUAL(ref.dimension(1), 5);
VERIFY_IS_EQUAL(ref.dimension(2), 7);
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 5; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_EQUAL(ref(i,j,k), input(i,j,k));
}
}
}
}
static void test_slice()
{
Tensor<float, 5> tensor(2,3,5,7,11);
tensor.setRandom();
Eigen::DSizes<ptrdiff_t, 5> indices(1,2,3,4,5);
Eigen::DSizes<ptrdiff_t, 5> sizes(1,1,1,1,1);
TensorRef<Tensor<float, 5>> slice = tensor.slice(indices, sizes);
VERIFY_IS_EQUAL(slice(0,0,0,0,0), tensor(1,2,3,4,5));
Eigen::DSizes<ptrdiff_t, 5> indices2(1,1,3,4,5);
Eigen::DSizes<ptrdiff_t, 5> sizes2(1,1,2,2,3);
slice = tensor.slice(indices2, sizes2);
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
for (int k = 0; k < 3; ++k) {
VERIFY_IS_EQUAL(slice(0,0,i,j,k), tensor(1,1,3+i,4+j,5+k));
}
}
}
Eigen::DSizes<ptrdiff_t, 5> indices3(0,0,0,0,0);
Eigen::DSizes<ptrdiff_t, 5> sizes3(2,3,1,1,1);
slice = tensor.slice(indices3, sizes3);
VERIFY_IS_EQUAL(slice.data(), tensor.data());
}
static void test_ref_of_ref()
{
Tensor<float, 3> input(3,5,7);
input.setRandom();
TensorRef<Tensor<float, 3>> ref(input);
TensorRef<Tensor<float, 3>> ref_of_ref(ref);
TensorRef<Tensor<float, 3>> ref_of_ref2;
ref_of_ref2 = ref;
VERIFY_IS_EQUAL(ref_of_ref.data(), input.data());
VERIFY_IS_EQUAL(ref_of_ref.dimension(0), 3);
VERIFY_IS_EQUAL(ref_of_ref.dimension(1), 5);
VERIFY_IS_EQUAL(ref_of_ref.dimension(2), 7);
VERIFY_IS_EQUAL(ref_of_ref2.data(), input.data());
VERIFY_IS_EQUAL(ref_of_ref2.dimension(0), 3);
VERIFY_IS_EQUAL(ref_of_ref2.dimension(1), 5);
VERIFY_IS_EQUAL(ref_of_ref2.dimension(2), 7);
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 5; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_EQUAL(ref_of_ref(i,j,k), input(i,j,k));
VERIFY_IS_EQUAL(ref_of_ref2(i,j,k), input(i,j,k));
}
}
}
}
static void test_ref_in_expr()
{
Tensor<float, 3> input(3,5,7);
input.setRandom();
TensorRef<Tensor<float, 3>> input_ref(input);
Tensor<float, 3> result(3,5,7);
result.setRandom();
TensorRef<Tensor<float, 3>> result_ref(result);
Tensor<float, 3> bias(3,5,7);
bias.setRandom();
result_ref = input_ref + bias;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 5; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_EQUAL(result_ref(i,j,k), input(i,j,k) + bias(i,j,k));
VERIFY_IS_NOT_EQUAL(result(i,j,k), input(i,j,k) + bias(i,j,k));
}
}
}
result = result_ref;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 5; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_EQUAL(result(i,j,k), input(i,j,k) + bias(i,j,k));
}
}
}
}
static void test_coeff_ref()
{
Tensor<float, 5> tensor(2,3,5,7,11);
tensor.setRandom();
Tensor<float, 5> original = tensor;
TensorRef<Tensor<float, 4>> slice = tensor.chip(7, 4);
slice.coeffRef(0, 0, 0, 0) = 1.0f;
slice.coeffRef(1, 0, 0, 0) += 2.0f;
VERIFY_IS_EQUAL(tensor(0,0,0,0,7), 1.0f);
VERIFY_IS_EQUAL(tensor(1,0,0,0,7), original(1,0,0,0,7) + 2.0f);
}
static void test_nested_ops_with_ref()
{
Tensor<float, 4> t(2, 3, 5, 7);
t.setRandom();
TensorMap<Tensor<const float, 4> > m(t.data(), 2, 3, 5, 7);
array<std::pair<ptrdiff_t, ptrdiff_t>, 4> paddings;
paddings[0] = std::make_pair(0, 0);
paddings[1] = std::make_pair(2, 1);
paddings[2] = std::make_pair(3, 4);
paddings[3] = std::make_pair(0, 0);
DSizes<Eigen::DenseIndex, 4> shuffle_dims{0, 1, 2, 3};
TensorRef<Tensor<const float, 4> > ref(m.pad(paddings));
array<std::pair<ptrdiff_t, ptrdiff_t>, 4> trivial;
trivial[0] = std::make_pair(0, 0);
trivial[1] = std::make_pair(0, 0);
trivial[2] = std::make_pair(0, 0);
trivial[3] = std::make_pair(0, 0);
Tensor<float, 4> padded = ref.shuffle(shuffle_dims).pad(trivial);
VERIFY_IS_EQUAL(padded.dimension(0), 2+0);
VERIFY_IS_EQUAL(padded.dimension(1), 3+3);
VERIFY_IS_EQUAL(padded.dimension(2), 5+7);
VERIFY_IS_EQUAL(padded.dimension(3), 7+0);
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 6; ++j) {
for (int k = 0; k < 12; ++k) {
for (int l = 0; l < 7; ++l) {
if (j >= 2 && j < 5 && k >= 3 && k < 8) {
VERIFY_IS_EQUAL(padded(i,j,k,l), t(i,j-2,k-3,l));
} else {
VERIFY_IS_EQUAL(padded(i,j,k,l), 0.0f);
}
}
}
}
}
}
void test_cxx11_tensor_ref()
{
CALL_SUBTEST(test_simple_lvalue_ref());
CALL_SUBTEST(test_simple_rvalue_ref());
CALL_SUBTEST(test_multiple_dims());
CALL_SUBTEST(test_slice());
CALL_SUBTEST(test_ref_of_ref());
CALL_SUBTEST(test_ref_in_expr());
CALL_SUBTEST(test_coeff_ref());
CALL_SUBTEST(test_nested_ops_with_ref());
}
<|endoftext|>
|
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2010 Manuel Yguel <manuel.yguel@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
#include <unsupported/Eigen/Polynomials>
#include <iostream>
#include <algorithm>
using namespace std;
namespace Eigen {
namespace internal {
template<int Size>
struct increment_if_fixed_size
{
enum {
ret = (Size == Dynamic) ? Dynamic : Size+1
};
};
}
}
template<int Deg, typename POLYNOMIAL, typename SOLVER>
bool aux_evalSolver( const POLYNOMIAL& pols, SOLVER& psolve )
{
typedef typename POLYNOMIAL::Index Index;
typedef typename POLYNOMIAL::Scalar Scalar;
typedef typename SOLVER::RootsType RootsType;
typedef Matrix<Scalar,Deg,1> EvalRootsType;
const Index deg = pols.size()-1;
psolve.compute( pols );
const RootsType& roots( psolve.roots() );
EvalRootsType evr( deg );
for( int i=0; i<roots.size(); ++i ){
evr[i] = std::abs( poly_eval( pols, roots[i] ) ); }
bool evalToZero = evr.isZero( test_precision<Scalar>() );
if( !evalToZero )
{
cerr << "WRONG root: " << endl;
cerr << "Polynomial: " << pols.transpose() << endl;
cerr << "Roots found: " << roots.transpose() << endl;
cerr << "Abs value of the polynomial at the roots: " << evr.transpose() << endl;
cerr << endl;
}
std::vector<Scalar> rootModuli( roots.size() );
Map< EvalRootsType > aux( &rootModuli[0], roots.size() );
aux = roots.array().abs();
std::sort( rootModuli.begin(), rootModuli.end() );
bool distinctModuli=true;
for( size_t i=1; i<rootModuli.size() && distinctModuli; ++i )
{
if( internal::isApprox( rootModuli[i], rootModuli[i-1] ) ){
distinctModuli = false; }
}
VERIFY( evalToZero || !distinctModuli );
return distinctModuli;
}
template<int Deg, typename POLYNOMIAL>
void evalSolver( const POLYNOMIAL& pols )
{
typedef typename POLYNOMIAL::Scalar Scalar;
typedef PolynomialSolver<Scalar, Deg > PolynomialSolverType;
PolynomialSolverType psolve;
aux_evalSolver<Deg, POLYNOMIAL, PolynomialSolverType>( pols, psolve );
}
template< int Deg, typename POLYNOMIAL, typename ROOTS, typename REAL_ROOTS >
void evalSolverSugarFunction( const POLYNOMIAL& pols, const ROOTS& roots, const REAL_ROOTS& real_roots )
{
using std::sqrt;
typedef typename POLYNOMIAL::Scalar Scalar;
typedef PolynomialSolver<Scalar, Deg > PolynomialSolverType;
PolynomialSolverType psolve;
if( aux_evalSolver<Deg, POLYNOMIAL, PolynomialSolverType>( pols, psolve ) )
{
//It is supposed that
// 1) the roots found are correct
// 2) the roots have distinct moduli
typedef typename POLYNOMIAL::Scalar Scalar;
typedef typename REAL_ROOTS::Scalar Real;
typedef PolynomialSolver<Scalar, Deg > PolynomialSolverType;
//Test realRoots
std::vector< Real > calc_realRoots;
psolve.realRoots( calc_realRoots );
VERIFY( calc_realRoots.size() == (size_t)real_roots.size() );
const Scalar psPrec = sqrt( test_precision<Scalar>() );
for( size_t i=0; i<calc_realRoots.size(); ++i )
{
bool found = false;
for( size_t j=0; j<calc_realRoots.size()&& !found; ++j )
{
if( internal::isApprox( calc_realRoots[i], real_roots[j] ), psPrec ){
found = true; }
}
VERIFY( found );
}
//Test greatestRoot
VERIFY( internal::isApprox( roots.array().abs().maxCoeff(),
abs( psolve.greatestRoot() ), psPrec ) );
//Test smallestRoot
VERIFY( internal::isApprox( roots.array().abs().minCoeff(),
abs( psolve.smallestRoot() ), psPrec ) );
bool hasRealRoot;
//Test absGreatestRealRoot
Real r = psolve.absGreatestRealRoot( hasRealRoot );
VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
if( hasRealRoot ){
VERIFY( internal::isApprox( real_roots.array().abs().maxCoeff(), abs(r), psPrec ) ); }
//Test absSmallestRealRoot
r = psolve.absSmallestRealRoot( hasRealRoot );
VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
if( hasRealRoot ){
VERIFY( internal::isApprox( real_roots.array().abs().minCoeff(), abs( r ), psPrec ) ); }
//Test greatestRealRoot
r = psolve.greatestRealRoot( hasRealRoot );
VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
if( hasRealRoot ){
VERIFY( internal::isApprox( real_roots.array().maxCoeff(), r, psPrec ) ); }
//Test smallestRealRoot
r = psolve.smallestRealRoot( hasRealRoot );
VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
if( hasRealRoot ){
VERIFY( internal::isApprox( real_roots.array().minCoeff(), r, psPrec ) ); }
}
}
template<typename _Scalar, int _Deg>
void polynomialsolver(int deg)
{
typedef internal::increment_if_fixed_size<_Deg> Dim;
typedef Matrix<_Scalar,Dim::ret,1> PolynomialType;
typedef Matrix<_Scalar,_Deg,1> EvalRootsType;
cout << "Standard cases" << endl;
PolynomialType pols = PolynomialType::Random(deg+1);
evalSolver<_Deg,PolynomialType>( pols );
cout << "Hard cases" << endl;
_Scalar multipleRoot = internal::random<_Scalar>();
EvalRootsType allRoots = EvalRootsType::Constant(deg,multipleRoot);
roots_to_monicPolynomial( allRoots, pols );
evalSolver<_Deg,PolynomialType>( pols );
cout << "Test sugar" << endl;
EvalRootsType realRoots = EvalRootsType::Random(deg);
roots_to_monicPolynomial( realRoots, pols );
evalSolverSugarFunction<_Deg>(
pols,
realRoots.template cast <
std::complex<
typename NumTraits<_Scalar>::Real
>
>(),
realRoots );
}
void test_polynomialsolver()
{
for(int i = 0; i < g_repeat; i++)
{
CALL_SUBTEST_1( (polynomialsolver<float,1>(1)) );
CALL_SUBTEST_2( (polynomialsolver<double,2>(2)) );
CALL_SUBTEST_3( (polynomialsolver<double,3>(3)) );
CALL_SUBTEST_4( (polynomialsolver<float,4>(4)) );
CALL_SUBTEST_5( (polynomialsolver<double,5>(5)) );
CALL_SUBTEST_6( (polynomialsolver<float,6>(6)) );
CALL_SUBTEST_7( (polynomialsolver<float,7>(7)) );
CALL_SUBTEST_8( (polynomialsolver<double,8>(8)) );
CALL_SUBTEST_9( (polynomialsolver<float,Dynamic>(
internal::random<int>(9,13)
)) );
CALL_SUBTEST_10((polynomialsolver<double,Dynamic>(
internal::random<int>(9,13)
)) );
}
}
<commit_msg>fix typo in evalSolverSugarFunction()<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2010 Manuel Yguel <manuel.yguel@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
#include <unsupported/Eigen/Polynomials>
#include <iostream>
#include <algorithm>
using namespace std;
namespace Eigen {
namespace internal {
template<int Size>
struct increment_if_fixed_size
{
enum {
ret = (Size == Dynamic) ? Dynamic : Size+1
};
};
}
}
template<int Deg, typename POLYNOMIAL, typename SOLVER>
bool aux_evalSolver( const POLYNOMIAL& pols, SOLVER& psolve )
{
typedef typename POLYNOMIAL::Index Index;
typedef typename POLYNOMIAL::Scalar Scalar;
typedef typename SOLVER::RootsType RootsType;
typedef Matrix<Scalar,Deg,1> EvalRootsType;
const Index deg = pols.size()-1;
psolve.compute( pols );
const RootsType& roots( psolve.roots() );
EvalRootsType evr( deg );
for( int i=0; i<roots.size(); ++i ){
evr[i] = std::abs( poly_eval( pols, roots[i] ) ); }
bool evalToZero = evr.isZero( test_precision<Scalar>() );
if( !evalToZero )
{
cerr << "WRONG root: " << endl;
cerr << "Polynomial: " << pols.transpose() << endl;
cerr << "Roots found: " << roots.transpose() << endl;
cerr << "Abs value of the polynomial at the roots: " << evr.transpose() << endl;
cerr << endl;
}
std::vector<Scalar> rootModuli( roots.size() );
Map< EvalRootsType > aux( &rootModuli[0], roots.size() );
aux = roots.array().abs();
std::sort( rootModuli.begin(), rootModuli.end() );
bool distinctModuli=true;
for( size_t i=1; i<rootModuli.size() && distinctModuli; ++i )
{
if( internal::isApprox( rootModuli[i], rootModuli[i-1] ) ){
distinctModuli = false; }
}
VERIFY( evalToZero || !distinctModuli );
return distinctModuli;
}
template<int Deg, typename POLYNOMIAL>
void evalSolver( const POLYNOMIAL& pols )
{
typedef typename POLYNOMIAL::Scalar Scalar;
typedef PolynomialSolver<Scalar, Deg > PolynomialSolverType;
PolynomialSolverType psolve;
aux_evalSolver<Deg, POLYNOMIAL, PolynomialSolverType>( pols, psolve );
}
template< int Deg, typename POLYNOMIAL, typename ROOTS, typename REAL_ROOTS >
void evalSolverSugarFunction( const POLYNOMIAL& pols, const ROOTS& roots, const REAL_ROOTS& real_roots )
{
using std::sqrt;
typedef typename POLYNOMIAL::Scalar Scalar;
typedef PolynomialSolver<Scalar, Deg > PolynomialSolverType;
PolynomialSolverType psolve;
if( aux_evalSolver<Deg, POLYNOMIAL, PolynomialSolverType>( pols, psolve ) )
{
//It is supposed that
// 1) the roots found are correct
// 2) the roots have distinct moduli
typedef typename POLYNOMIAL::Scalar Scalar;
typedef typename REAL_ROOTS::Scalar Real;
typedef PolynomialSolver<Scalar, Deg > PolynomialSolverType;
//Test realRoots
std::vector< Real > calc_realRoots;
psolve.realRoots( calc_realRoots );
VERIFY( calc_realRoots.size() == (size_t)real_roots.size() );
const Scalar psPrec = sqrt( test_precision<Scalar>() );
for( size_t i=0; i<calc_realRoots.size(); ++i )
{
bool found = false;
for( size_t j=0; j<calc_realRoots.size()&& !found; ++j )
{
if( internal::isApprox( calc_realRoots[i], real_roots[j], psPrec ) ){
found = true; }
}
VERIFY( found );
}
//Test greatestRoot
VERIFY( internal::isApprox( roots.array().abs().maxCoeff(),
abs( psolve.greatestRoot() ), psPrec ) );
//Test smallestRoot
VERIFY( internal::isApprox( roots.array().abs().minCoeff(),
abs( psolve.smallestRoot() ), psPrec ) );
bool hasRealRoot;
//Test absGreatestRealRoot
Real r = psolve.absGreatestRealRoot( hasRealRoot );
VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
if( hasRealRoot ){
VERIFY( internal::isApprox( real_roots.array().abs().maxCoeff(), abs(r), psPrec ) ); }
//Test absSmallestRealRoot
r = psolve.absSmallestRealRoot( hasRealRoot );
VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
if( hasRealRoot ){
VERIFY( internal::isApprox( real_roots.array().abs().minCoeff(), abs( r ), psPrec ) ); }
//Test greatestRealRoot
r = psolve.greatestRealRoot( hasRealRoot );
VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
if( hasRealRoot ){
VERIFY( internal::isApprox( real_roots.array().maxCoeff(), r, psPrec ) ); }
//Test smallestRealRoot
r = psolve.smallestRealRoot( hasRealRoot );
VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
if( hasRealRoot ){
VERIFY( internal::isApprox( real_roots.array().minCoeff(), r, psPrec ) ); }
}
}
template<typename _Scalar, int _Deg>
void polynomialsolver(int deg)
{
typedef internal::increment_if_fixed_size<_Deg> Dim;
typedef Matrix<_Scalar,Dim::ret,1> PolynomialType;
typedef Matrix<_Scalar,_Deg,1> EvalRootsType;
cout << "Standard cases" << endl;
PolynomialType pols = PolynomialType::Random(deg+1);
evalSolver<_Deg,PolynomialType>( pols );
cout << "Hard cases" << endl;
_Scalar multipleRoot = internal::random<_Scalar>();
EvalRootsType allRoots = EvalRootsType::Constant(deg,multipleRoot);
roots_to_monicPolynomial( allRoots, pols );
evalSolver<_Deg,PolynomialType>( pols );
cout << "Test sugar" << endl;
EvalRootsType realRoots = EvalRootsType::Random(deg);
roots_to_monicPolynomial( realRoots, pols );
evalSolverSugarFunction<_Deg>(
pols,
realRoots.template cast <
std::complex<
typename NumTraits<_Scalar>::Real
>
>(),
realRoots );
}
void test_polynomialsolver()
{
for(int i = 0; i < g_repeat; i++)
{
CALL_SUBTEST_1( (polynomialsolver<float,1>(1)) );
CALL_SUBTEST_2( (polynomialsolver<double,2>(2)) );
CALL_SUBTEST_3( (polynomialsolver<double,3>(3)) );
CALL_SUBTEST_4( (polynomialsolver<float,4>(4)) );
CALL_SUBTEST_5( (polynomialsolver<double,5>(5)) );
CALL_SUBTEST_6( (polynomialsolver<float,6>(6)) );
CALL_SUBTEST_7( (polynomialsolver<float,7>(7)) );
CALL_SUBTEST_8( (polynomialsolver<double,8>(8)) );
CALL_SUBTEST_9( (polynomialsolver<float,Dynamic>(
internal::random<int>(9,13)
)) );
CALL_SUBTEST_10((polynomialsolver<double,Dynamic>(
internal::random<int>(9,13)
)) );
}
}
<|endoftext|>
|
<commit_before>#include "WebSocketConnector.h"
#include "../stringtools.h"
#include "../Interface/Server.h"
#include "../cryptoplugin/ICryptoFactory.h"
#include "../urbackupcommon/WebSocketPipe.h"
#include <assert.h>
extern ICryptoFactory* crypto_fak;
void WebSocketConnector::Execute(str_map& GET, THREAD_ID tid, str_map& PARAMS, IPipe* pipe, const std::string& endpoint_name)
{
if (PARAMS["CONNECTION"] != "Upgrade")
{
pipe->Write("HTTP/1.1 500 Expecting Connection: Upgrade\r\nConnection: Close\r\n\r\n");
return;
}
std::string protocol_list = PARAMS["SEC-WEBSOCKET-PROTOCOL"];
std::vector<std::string> protocols;
Tokenize(protocol_list, protocols, ",");
for (size_t i = 0; i < protocols.size(); ++i)
protocols[i] = trim(protocols[i]);
if (std::find(protocols.begin(), protocols.end(), "urbackup") == protocols.end())
{
pipe->Write("HTTP/1.1 500 urbackup protocol not supported\r\nConnection: Close\r\n\r\n");
return;
}
if (PARAMS["SEC-WEBSOCKET-VERSION"] != "13")
{
pipe->Write("HTTP/1.1 500 websocket protocol version not supported\r\nConnection: Close\r\n\r\n");
return;
}
std::string websocket_key = trim(PARAMS["SEC-WEBSOCKET-KEY"]);
websocket_key += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
std::string key_response = crypto_fak->sha1Binary(websocket_key);
pipe->Write(std::string("HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Accept: ") + base64_encode(reinterpret_cast<const unsigned char*>(key_response.data()),
static_cast<unsigned int>(key_response.size())) + "\r\n"
"Sec-WebSocket-Protocol: urbackup\r\n\r\n");
ICustomClient* client = wrapped_service->createClient();
str_map::iterator it_forwarded_for = PARAMS.find("X-FORWARDED-FOR");
WebSocketPipe* ws_pipe = new WebSocketPipe(pipe, false, true, std::string(), false);
client->Init(tid, ws_pipe, it_forwarded_for != PARAMS.end() ? it_forwarded_for->second : endpoint_name);
while (true)
{
bool b = client->Run(NULL);
if (!b)
{
break;
}
if (client->wantReceive())
{
if (ws_pipe->isReadable(10))
{
client->ReceivePackets(NULL);
}
else if (ws_pipe->hasError())
{
client->ReceivePackets(NULL);
Server->wait(20);
}
}
else
{
Server->wait(20);
}
}
bool want_destory_pipe = client->closeSocket();
wrapped_service->destroyClient(client);
if (want_destory_pipe)
{
delete ws_pipe;
delete pipe;
}
}
std::string WebSocketConnector::getName()
{
return name;
}
<commit_msg>Properly free web socket connections<commit_after>#include "WebSocketConnector.h"
#include "../stringtools.h"
#include "../Interface/Server.h"
#include "../cryptoplugin/ICryptoFactory.h"
#include "../urbackupcommon/WebSocketPipe.h"
#include <assert.h>
extern ICryptoFactory* crypto_fak;
void WebSocketConnector::Execute(str_map& GET, THREAD_ID tid, str_map& PARAMS, IPipe* pipe, const std::string& endpoint_name)
{
if (PARAMS["CONNECTION"] != "Upgrade")
{
pipe->Write("HTTP/1.1 500 Expecting Connection: Upgrade\r\nConnection: Close\r\n\r\n");
delete pipe;
return;
}
std::string protocol_list = PARAMS["SEC-WEBSOCKET-PROTOCOL"];
std::vector<std::string> protocols;
Tokenize(protocol_list, protocols, ",");
for (size_t i = 0; i < protocols.size(); ++i)
protocols[i] = trim(protocols[i]);
if (std::find(protocols.begin(), protocols.end(), "urbackup") == protocols.end())
{
pipe->Write("HTTP/1.1 500 urbackup protocol not supported\r\nConnection: Close\r\n\r\n");
delete pipe;
return;
}
if (PARAMS["SEC-WEBSOCKET-VERSION"] != "13")
{
pipe->Write("HTTP/1.1 500 websocket protocol version not supported\r\nConnection: Close\r\n\r\n");
delete pipe;
return;
}
std::string websocket_key = trim(PARAMS["SEC-WEBSOCKET-KEY"]);
websocket_key += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
std::string key_response = crypto_fak->sha1Binary(websocket_key);
pipe->Write(std::string("HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Accept: ") + base64_encode(reinterpret_cast<const unsigned char*>(key_response.data()),
static_cast<unsigned int>(key_response.size())) + "\r\n"
"Sec-WebSocket-Protocol: urbackup\r\n\r\n");
ICustomClient* client = wrapped_service->createClient();
str_map::iterator it_forwarded_for = PARAMS.find("X-FORWARDED-FOR");
WebSocketPipe* ws_pipe = new WebSocketPipe(pipe, false, true, std::string(), true);
client->Init(tid, ws_pipe, it_forwarded_for != PARAMS.end() ? it_forwarded_for->second : endpoint_name);
while (true)
{
bool b = client->Run(NULL);
if (!b)
{
break;
}
if (client->wantReceive())
{
if (ws_pipe->isReadable(10))
{
client->ReceivePackets(NULL);
}
else if (ws_pipe->hasError())
{
client->ReceivePackets(NULL);
Server->wait(20);
}
}
else
{
Server->wait(20);
}
}
bool want_destory_pipe = client->closeSocket();
wrapped_service->destroyClient(client);
if (want_destory_pipe)
{
delete ws_pipe;
}
}
std::string WebSocketConnector::getName()
{
return name;
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <string.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include "GL/glut.h" // - An interface and windows management library
#include "visuals.h" // Header file for our OpenGL functions
myModel md;
static float tx = 0.0;
static float rotx = 0.0;
static bool animate = false;
static float red = 1.0;
static float green = 0.0;
static float blue = 0.0;
using namespace std;
Point::Point(float x, float y, float z) {
this->x = x;
this->y = y;
this->z = z;
}
float Point::getX() {
return this->x;
}
float Point::getY() {
return this->y;
}
float Point::getZ() {
return this->z;
}
void Point::print(void) {
cout << this->x << " " << this->y << " " << this->z << endl;
}
Faces::Faces(float v1, float vn1, float v2, float vn2, float v3, float vn3) {
this->v = new Point(v1, v2, v3);
this->vn = new Point(vn1, vn2, vn3);
}
Point* Faces::getV() {
return this->v;
}
Point* Faces::getVn() {
return this->vn;
}
void Faces::print(void) {
this->v->print();
this->vn->print();
}
void keimeno(const char *str, float size) {
glPushMatrix();
glScalef(size,size,size);
for (size_t i=0;i<strlen(str);i++) {
glutStrokeCharacter(GLUT_STROKE_ROMAN,str[i]);
}
glPopMatrix();
}
void Render() {
//CLEARS FRAME BUFFER ie COLOR BUFFER& DEPTH BUFFER (1.0)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clean up the colour of the window and the depth buffer
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0, 0, -100);
glTranslatef(tx, 0.0, 0.0);
glRotatef(rotx, 0, 1, 0);
//(01)
glColor3f(0.8, 0.1, 0.1);
DisplayModel(md);
glutSwapBuffers(); // All drawing commands applied to the hidden buffer, so now, bring forward the hidden buffer and hide the visible one
}
//-----------------------------------------------------------
void Resize(int w, int h) {
// define the visible area of the window ( in pixels )
if (h == 0) {
h = 1;
}
glViewport(0, 0, w, h);
// Setup viewing volume
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(2.0, (float)w/(float)h, 1.0, 500.0);
}
void Idle() {
if (animate) {
rotx += 0.4;
}
glutPostRedisplay();
}
void Keyboard(unsigned char key, int x, int y) {
switch(key) {
case 'q' :
exit(0);
break;
case 'a' :
tx -= 0.5f;
break;
case 'd' :
tx += 0.5f;
break;
default :
break;
}
glutPostRedisplay();
}
void Mouse(int button, int state, int x, int y) {
if (state == GLUT_DOWN && button == GLUT_LEFT_BUTTON) {
animate = !animate;
glutPostRedisplay();
}
}
void Setup() {
char path[] = "../planet.obj";
ReadFile(&md, path);
//Parameter handling
glShadeModel (GL_SMOOTH);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL); //renders a fragment if its z value is less or equal of the stored value
glClearDepth(1);
// polygon rendering mode
glEnable(GL_COLOR_MATERIAL);
glColorMaterial( GL_FRONT, GL_AMBIENT_AND_DIFFUSE );
//Set up light source
GLfloat light_position[] = { 0.0, 30.0, 50.0, 0.0 };
glLightfv( GL_LIGHT0, GL_POSITION, light_position);
GLfloat ambientLight[] = { 0.3, 0.3, 0.3, 1.0 };
GLfloat diffuseLight[] = { 0.8, 0.8, 0.8, 1.0 };
// GLfloat specularLight[] = { 1.0, 1.0, 1.0, 1.0 };
glLightfv( GL_LIGHT0, GL_AMBIENT, ambientLight );
glLightfv( GL_LIGHT0, GL_DIFFUSE, diffuseLight );
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glEnable(GL_CULL_FACE);
glFrontFace(GL_CW);
//01
glFrontFace(GL_CCW);
// Black background
glClearColor(0.0f,0.0f,0.0f,1.0f);
}
void MenuSelect(int choice) {
switch (choice) {
case RED:
red = 1.0;
green = 0.0;
blue = 0.0;
break;
case GREEN:
red = 0.0;
green = 1.0;
blue = 0.0;
break;
case BLUE:
red = 0.0;
green = 0.0;
blue = 1.0;
break;
case WHITE:
red = 1.0;
green = 1.0;
blue = 1.0;
break;
default:
break;
}
}
void ReadFile(myModel *md, char *path) {
string line;
float x, y, z;
string::size_type sz, sz2;
ifstream myfile(path);
if (myfile) {
while (getline(myfile, line)) {
if (line.find("v ") == 0) {
string temp = line.substr(3);
x = stod(temp, &sz);
y = stod(temp.substr(sz), &sz2);
z = stod(temp.substr(sz+sz2));
md->v.push_back(new Point(x, y, z));
} else if (line.find("vn ") == 0) {
string temp = line.substr(3);
x = stod(temp, &sz);
y = stod(temp.substr(sz), &sz2);
z = stod(temp.substr(sz+sz2));
md->vn.push_back(new Point(x, y, z));
} else if (line.find("f ") == 0) {
int v1, vn1, v2, vn2, v3, vn3;
string::size_type sz, sz2, sz3, sz4, sz5;
string temp = line.substr(3);
v1 = stoi(temp, &sz);
vn1 = stoi(temp.substr(sz+2), &sz2);
v2 = stoi(temp.substr(sz+2+sz2), &sz3);
vn2 = stoi(temp.substr(sz+2+sz2+sz3+2), &sz4);
v3 = stoi(temp.substr(sz+2+sz2+sz3+2+sz4), &sz5);
vn3 = stoi(temp.substr(sz+2+sz2+sz3+2+sz4+sz5+2));
md->f.push_back(new Faces(v1, vn1, v2, vn2, v3, vn3));
}
}
myfile.close();
}
}
void DisplayModel(myModel md) {
glPushMatrix();
glBegin(GL_POINTS);
for (size_t i = 0; i < md.f.size(); i++) {
/* Vns */
glVertex3f(md.vn[md.f[i]->getVn()->getX()-1]->getX(), md.vn[md.f[i]->getVn()->getX()-1]->getY(), md.vn[md.f[i]->getVn()->getX()-1]->getZ());
glVertex3f(md.vn[md.f[i]->getVn()->getY()-1]->getX(), md.vn[md.f[i]->getVn()->getY()-1]->getY(), md.vn[md.f[i]->getVn()->getY()-1]->getZ());
glVertex3f(md.vn[md.f[i]->getVn()->getZ()-1]->getX(), md.vn[md.f[i]->getVn()->getZ()-1]->getY(), md.vn[md.f[i]->getVn()->getZ()-1]->getZ());
/* Vs */
glVertex3f(md.v[md.f[i]->getV()->getX()-1]->getX(), md.v[md.f[i]->getV()->getX()-1]->getY(), md.v[md.f[i]->getV()->getX()-1]->getZ());
glVertex3f(md.v[md.f[i]->getV()->getY()-1]->getX(), md.v[md.f[i]->getV()->getY()-1]->getY(), md.v[md.f[i]->getV()->getY()-1]->getZ());
glVertex3f(md.v[md.f[i]->getV()->getZ()-1]->getX(), md.v[md.f[i]->getV()->getZ()-1]->getY(), md.v[md.f[i]->getV()->getZ()-1]->getZ());
}
glEnd();
glPopMatrix();
}
<commit_msg>Planet printing update<commit_after>#include <stdio.h>
#include <string.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include "GL/glut.h" // - An interface and windows management library
#include "visuals.h" // Header file for our OpenGL functions
myModel md;
static float tx = 0.0;
static float rotx = 0.0;
static bool animate = false;
static float red = 1.0;
static float green = 0.0;
static float blue = 0.0;
using namespace std;
Point::Point(float x, float y, float z) {
this->x = x;
this->y = y;
this->z = z;
}
float Point::getX() {
return this->x;
}
float Point::getY() {
return this->y;
}
float Point::getZ() {
return this->z;
}
void Point::print(void) {
cout << this->x << " " << this->y << " " << this->z << endl;
}
Faces::Faces(float v1, float vn1, float v2, float vn2, float v3, float vn3) {
this->v = new Point(v1, v2, v3);
this->vn = new Point(vn1, vn2, vn3);
}
Point* Faces::getV() {
return this->v;
}
Point* Faces::getVn() {
return this->vn;
}
void Faces::print(void) {
this->v->print();
this->vn->print();
}
void keimeno(const char *str, float size) {
glPushMatrix();
glScalef(size,size,size);
for (size_t i=0;i<strlen(str);i++) {
glutStrokeCharacter(GLUT_STROKE_ROMAN,str[i]);
}
glPopMatrix();
}
void Render() {
//CLEARS FRAME BUFFER ie COLOR BUFFER& DEPTH BUFFER (1.0)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clean up the colour of the window and the depth buffer
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0, 0, -100);
glTranslatef(tx, 0.0, 0.0);
glRotatef(rotx, 0, 1, 0);
//(01)
glColor3f(0.75, 0.35, 0.05);
DisplayModel(md);
// glColor3f(0.8, 0.4, 0.1);
// glutSolidSphere(0.999, 30, 24);
glutSwapBuffers(); // All drawing commands applied to the hidden buffer, so now, bring forward the hidden buffer and hide the visible one
}
//-----------------------------------------------------------
void Resize(int w, int h) {
// define the visible area of the window ( in pixels )
if (h == 0) {
h = 1;
}
glViewport(0, 0, w, h);
// Setup viewing volume
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(2.0, (float)w/(float)h, 1.0, 500.0);
}
void Idle() {
if (animate) {
rotx += 0.4;
}
glutPostRedisplay();
}
void Keyboard(unsigned char key, int x, int y) {
switch(key) {
case 'q' :
exit(0);
break;
case 'a' :
tx -= 0.5f;
break;
case 'd' :
tx += 0.5f;
break;
default :
break;
}
glutPostRedisplay();
}
void Mouse(int button, int state, int x, int y) {
if (state == GLUT_DOWN && button == GLUT_LEFT_BUTTON) {
animate = !animate;
glutPostRedisplay();
}
}
void Setup() {
char path[] = "../planet.obj";
ReadFile(&md, path);
//Parameter handling
glShadeModel (GL_SMOOTH);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL); //renders a fragment if its z value is less or equal of the stored value
glClearDepth(1);
// polygon rendering mode
glEnable(GL_COLOR_MATERIAL);
glColorMaterial( GL_FRONT, GL_AMBIENT_AND_DIFFUSE );
//Set up light source
GLfloat light_position[] = { 0.0, 30.0, 50.0, 0.0 };
glLightfv( GL_LIGHT0, GL_POSITION, light_position);
GLfloat ambientLight[] = { 0.3, 0.3, 0.3, 1.0 };
GLfloat diffuseLight[] = { 0.8, 0.8, 0.8, 1.0 };
// GLfloat specularLight[] = { 1.0, 1.0, 1.0, 1.0 };
glLightfv( GL_LIGHT0, GL_AMBIENT, ambientLight );
glLightfv( GL_LIGHT0, GL_DIFFUSE, diffuseLight );
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
glEnable(GL_CULL_FACE);
glFrontFace(GL_CW);
//01
glFrontFace(GL_CCW);
// Black background
glClearColor(0.0f,0.0f,0.0f,1.0f);
}
void MenuSelect(int choice) {
switch (choice) {
case RED:
red = 1.0;
green = 0.0;
blue = 0.0;
break;
case GREEN:
red = 0.0;
green = 1.0;
blue = 0.0;
break;
case BLUE:
red = 0.0;
green = 0.0;
blue = 1.0;
break;
case WHITE:
red = 1.0;
green = 1.0;
blue = 1.0;
break;
default:
break;
}
}
void ReadFile(myModel *md, char *path) {
string line;
float x, y, z;
string::size_type sz, sz2;
ifstream myfile(path);
if (myfile) {
while (getline(myfile, line)) {
if (line.find("v ") == 0) {
string temp = line.substr(3);
x = stod(temp, &sz);
y = stod(temp.substr(sz), &sz2);
z = stod(temp.substr(sz+sz2));
md->v.push_back(new Point(x, y, z));
} else if (line.find("vn ") == 0) {
string temp = line.substr(3);
x = stod(temp, &sz);
y = stod(temp.substr(sz), &sz2);
z = stod(temp.substr(sz+sz2));
md->vn.push_back(new Point(x, y, z));
} else if (line.find("f ") == 0) {
int v1, vn1, v2, vn2, v3, vn3;
string::size_type sz, sz2, sz3, sz4, sz5;
string temp = line.substr(3);
v1 = stoi(temp, &sz);
vn1 = stoi(temp.substr(sz+2), &sz2);
v2 = stoi(temp.substr(sz+2+sz2), &sz3);
vn2 = stoi(temp.substr(sz+2+sz2+sz3+2), &sz4);
v3 = stoi(temp.substr(sz+2+sz2+sz3+2+sz4), &sz5);
vn3 = stoi(temp.substr(sz+2+sz2+sz3+2+sz4+sz5+2));
md->f.push_back(new Faces(v1, vn1, v2, vn2, v3, vn3));
}
}
myfile.close();
}
}
void DisplayModel(myModel md) {
glPushMatrix();
glBegin(GL_POINTS);
for (size_t i = 0; i < md.f.size(); i++) {
/* Vns */
glVertex3f(md.vn[md.f[i]->getVn()->getX()-1]->getX(), md.vn[md.f[i]->getVn()->getX()-1]->getY(), md.vn[md.f[i]->getVn()->getX()-1]->getZ());
glVertex3f(md.vn[md.f[i]->getVn()->getY()-1]->getX(), md.vn[md.f[i]->getVn()->getY()-1]->getY(), md.vn[md.f[i]->getVn()->getY()-1]->getZ());
glVertex3f(md.vn[md.f[i]->getVn()->getZ()-1]->getX(), md.vn[md.f[i]->getVn()->getZ()-1]->getY(), md.vn[md.f[i]->getVn()->getZ()-1]->getZ());
/* Vs */
glVertex3f(md.v[md.f[i]->getV()->getX()-1]->getX(), md.v[md.f[i]->getV()->getX()-1]->getY(), md.v[md.f[i]->getV()->getX()-1]->getZ());
glVertex3f(md.v[md.f[i]->getV()->getY()-1]->getX(), md.v[md.f[i]->getV()->getY()-1]->getY(), md.v[md.f[i]->getV()->getY()-1]->getZ());
glVertex3f(md.v[md.f[i]->getV()->getZ()-1]->getX(), md.v[md.f[i]->getV()->getZ()-1]->getY(), md.v[md.f[i]->getV()->getZ()-1]->getZ());
}
glEnd();
glPopMatrix();
}
<|endoftext|>
|
<commit_before>
#include "GameLogger.h"
using namespace std;
GameLogger::GameLogger()
:
lastCompleteFrameNumber(0),
oldState(PlayerInfo::initial),
firstRecording(true),
lastAudioDataTimestamp(0),
lastRecordedPlainImageID(CameraInfo::Bottom)
{
const std::string gameLogPath = params.logDirPath + "/game.log";
const std::string imageLogPath = params.logDirPath + "/images.log";
logfileManager.openFile(gameLogPath);
imageOutFile.open(imageLogPath, ios::out | ios::binary);
lastTimeImageRecorded = getFrameInfo();
getDebugParameterList().add(¶ms);
}
GameLogger::~GameLogger()
{
logfileManager.closeFile();
imageOutFile.close();
getDebugParameterList().remove(¶ms);
}
#define LOGSTUFF(name) \
{ std::ostream& dataStream = logfileManager.log(getFrameInfo().getFrameNumber(), #name); \
Serializer<name>::serialize(get##name(), dataStream); } ((void)0)
void GameLogger::execute()
{
// HACK: wait a bit before starting recording
if(!logfileManager.is_ready()) {
return;
}
if( getBehaviorStateComplete().state.IsInitialized() &&
getBehaviorStateSparse().state.IsInitialized())
{
bool something_recorded = false;
// write out the complete behavior state when it was just created in this frame
if(getBehaviorStateComplete().state.framenumber() >= lastCompleteFrameNumber)
{
LOGSTUFF(BehaviorStateComplete);
LOGSTUFF(RobotInfo);
lastCompleteFrameNumber = getFrameInfo().getFrameNumber();
something_recorded = true;
}
// condition wheather the current frame should be logged:
bool log_this_frame = (getBehaviorStateSparse().state.framenumber() == getFrameInfo().getFrameNumber());
// NOTE: record only the first frame if the state changed to initial or finished
if(!firstRecording && oldState == getPlayerInfo().robotState) {
log_this_frame = log_this_frame && getPlayerInfo().robotState != PlayerInfo::initial;
log_this_frame = log_this_frame && getPlayerInfo().robotState != PlayerInfo::finished;
log_this_frame = log_this_frame && getMotionStatus().currentMotion != motion::init;
}
if(log_this_frame)
{
LOGSTUFF(BehaviorStateSparse);
// proprioception
LOGSTUFF(OdometryData);
LOGSTUFF(CameraMatrix);
LOGSTUFF(CameraMatrixTop);
if(params.logBodyStatus) {
LOGSTUFF(BodyStatus);
}
// perception
LOGSTUFF(GoalPercept);
LOGSTUFF(GoalPerceptTop);
LOGSTUFF(MultiBallPercept);
LOGSTUFF(BallModel);
if(params.logUltraSound) {
LOGSTUFF(UltraSoundReceiveData);
}
LOGSTUFF(FieldPercept);
LOGSTUFF(FieldPerceptTop);
LOGSTUFF(ScanLineEdgelPercept);
LOGSTUFF(ScanLineEdgelPerceptTop);
LOGSTUFF(ShortLinePercept);
LOGSTUFF(RansacLinePercept);
LOGSTUFF(RansacCirclePercept2018);
if(params.logBallCandidates) {
LOGSTUFF(BallCandidates);
LOGSTUFF(BallCandidatesTop);
}
LOGSTUFF(TeamMessage);
// keep the audio device open for some time
if(params.logAudioData)
{
// remember when the capture was on and keep recording for some time after the behavior says stop recording
if(getAudioControl().capture) {
timeOfLastCapture = getFrameInfo();
} else if(getFrameInfo().getTimeSince(timeOfLastCapture.getTime()) < 3000) {
getAudioControl().capture = true;
}
// new data avaliable and capture is still on
if(lastAudioDataTimestamp < getAudioData().timestamp) {
LOGSTUFF(AudioData);
lastAudioDataTimestamp = getAudioData().timestamp;
}
}
if (getWhistlePercept().whistleDetected) {
LOGSTUFF(WhistlePercept);
}
// record images every 1s
if(params.logPlainImages && getFrameInfo().getTimeSince(lastTimeImageRecorded) > params.logPlainImagesDelay && imageOutFile.is_open() && !imageOutFile.fail()) {
unsigned int frameNumber = getFrameInfo().getFrameNumber();
imageOutFile.write((const char*)(&frameNumber), sizeof(unsigned int));
// switch camera each frame
if(lastRecordedPlainImageID == CameraInfo::Top) {
imageOutFile.write((const char*)getImage().data(), getImage().data_size());
lastRecordedPlainImageID = CameraInfo::Bottom;
} else {
imageOutFile.write((const char*)getImageTop().data(), getImageTop().data_size());
lastRecordedPlainImageID = CameraInfo::Top;
}
lastTimeImageRecorded = getFrameInfo();
}
something_recorded = true;
}
if(something_recorded) {
LOGSTUFF(FrameInfo);
firstRecording = false;
}
// remember the old state
oldState = getPlayerInfo().robotState;
}
}
<commit_msg>don't log in unstiff<commit_after>
#include "GameLogger.h"
using namespace std;
GameLogger::GameLogger()
:
lastCompleteFrameNumber(0),
oldState(PlayerInfo::initial),
firstRecording(true),
lastAudioDataTimestamp(0),
lastRecordedPlainImageID(CameraInfo::Bottom)
{
const std::string gameLogPath = params.logDirPath + "/game.log";
const std::string imageLogPath = params.logDirPath + "/images.log";
logfileManager.openFile(gameLogPath);
imageOutFile.open(imageLogPath, ios::out | ios::binary);
lastTimeImageRecorded = getFrameInfo();
getDebugParameterList().add(¶ms);
}
GameLogger::~GameLogger()
{
logfileManager.closeFile();
imageOutFile.close();
getDebugParameterList().remove(¶ms);
}
#define LOGSTUFF(name) \
{ std::ostream& dataStream = logfileManager.log(getFrameInfo().getFrameNumber(), #name); \
Serializer<name>::serialize(get##name(), dataStream); } ((void)0)
void GameLogger::execute()
{
// HACK: wait a bit before starting recording
if(!logfileManager.is_ready()) {
return;
}
if( getBehaviorStateComplete().state.IsInitialized() &&
getBehaviorStateSparse().state.IsInitialized())
{
bool something_recorded = false;
// write out the complete behavior state when it was just created in this frame
if(getBehaviorStateComplete().state.framenumber() >= lastCompleteFrameNumber)
{
LOGSTUFF(BehaviorStateComplete);
LOGSTUFF(RobotInfo);
lastCompleteFrameNumber = getFrameInfo().getFrameNumber();
something_recorded = true;
}
// condition wheather the current frame should be logged:
bool log_this_frame = (getBehaviorStateSparse().state.framenumber() == getFrameInfo().getFrameNumber());
// NOTE: record only the first frame if the state changed to initial or finished
if(!firstRecording && oldState == getPlayerInfo().robotState) {
log_this_frame = log_this_frame && getPlayerInfo().robotState != PlayerInfo::initial;
log_this_frame = log_this_frame && getPlayerInfo().robotState != PlayerInfo::finished;
log_this_frame = log_this_frame && getPlayerInfo().robotState != PlayerInfo::unstiff;
log_this_frame = log_this_frame && getMotionStatus().currentMotion != motion::init;
}
if(log_this_frame)
{
LOGSTUFF(BehaviorStateSparse);
// proprioception
LOGSTUFF(OdometryData);
LOGSTUFF(CameraMatrix);
LOGSTUFF(CameraMatrixTop);
if(params.logBodyStatus) {
LOGSTUFF(BodyStatus);
}
// perception
LOGSTUFF(GoalPercept);
LOGSTUFF(GoalPerceptTop);
LOGSTUFF(MultiBallPercept);
LOGSTUFF(BallModel);
if(params.logUltraSound) {
LOGSTUFF(UltraSoundReceiveData);
}
LOGSTUFF(FieldPercept);
LOGSTUFF(FieldPerceptTop);
LOGSTUFF(ScanLineEdgelPercept);
LOGSTUFF(ScanLineEdgelPerceptTop);
LOGSTUFF(ShortLinePercept);
LOGSTUFF(RansacLinePercept);
LOGSTUFF(RansacCirclePercept2018);
if(params.logBallCandidates) {
LOGSTUFF(BallCandidates);
LOGSTUFF(BallCandidatesTop);
}
LOGSTUFF(TeamMessage);
// keep the audio device open for some time
if(params.logAudioData)
{
// remember when the capture was on and keep recording for some time after the behavior says stop recording
if(getAudioControl().capture) {
timeOfLastCapture = getFrameInfo();
} else if(getFrameInfo().getTimeSince(timeOfLastCapture.getTime()) < 3000) {
getAudioControl().capture = true;
}
// new data avaliable and capture is still on
if(lastAudioDataTimestamp < getAudioData().timestamp) {
LOGSTUFF(AudioData);
lastAudioDataTimestamp = getAudioData().timestamp;
}
}
if (getWhistlePercept().whistleDetected) {
LOGSTUFF(WhistlePercept);
}
// record images every 1s
if(params.logPlainImages && getFrameInfo().getTimeSince(lastTimeImageRecorded) > params.logPlainImagesDelay && imageOutFile.is_open() && !imageOutFile.fail()) {
unsigned int frameNumber = getFrameInfo().getFrameNumber();
imageOutFile.write((const char*)(&frameNumber), sizeof(unsigned int));
// switch camera each frame
if(lastRecordedPlainImageID == CameraInfo::Top) {
imageOutFile.write((const char*)getImage().data(), getImage().data_size());
lastRecordedPlainImageID = CameraInfo::Bottom;
} else {
imageOutFile.write((const char*)getImageTop().data(), getImageTop().data_size());
lastRecordedPlainImageID = CameraInfo::Top;
}
lastTimeImageRecorded = getFrameInfo();
}
something_recorded = true;
}
if(something_recorded) {
LOGSTUFF(FrameInfo);
firstRecording = false;
}
// remember the old state
oldState = getPlayerInfo().robotState;
}
}
<|endoftext|>
|
<commit_before>//===-- SBSourceManager.cpp -------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/API/SBDebugger.h"
#include "lldb/API/SBSourceManager.h"
#include "lldb/API/SBTarget.h"
#include "lldb/API/SBStream.h"
#include "lldb/API/SBFileSpec.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Core/Stream.h"
#include "lldb/Core/StreamFile.h"
#include "lldb/Core/SourceManager.h"
#include "lldb/Target/Target.h"
namespace lldb_private
{
class SourceManagerImpl
{
public:
SourceManagerImpl (const lldb::DebuggerSP &debugger_sp)
{
m_debugger_sp = debugger_sp;
}
SourceManagerImpl (const lldb::TargetSP &target_sp)
{
m_target_sp = target_sp;
}
SourceManagerImpl (const SourceManagerImpl &rhs)
{
if (&rhs == this)
return;
m_debugger_sp = rhs.m_debugger_sp;
m_target_sp = rhs.m_target_sp;
}
size_t
DisplaySourceLinesWithLineNumbers (const lldb_private::FileSpec &file,
uint32_t line,
uint32_t context_before,
uint32_t context_after,
const char* current_line_cstr,
lldb_private::Stream *s)
{
if (file)
return 0;
if (m_debugger_sp)
return m_debugger_sp->GetSourceManager().DisplaySourceLinesWithLineNumbers (file,
line,
context_before,
context_after,
current_line_cstr,
s);
else if (m_target_sp)
return m_target_sp->GetSourceManager().DisplaySourceLinesWithLineNumbers (file,
line,
context_before,
context_after,
current_line_cstr,
s);
else
return 0;
}
private:
lldb::DebuggerSP m_debugger_sp;
lldb::TargetSP m_target_sp;
};
}
using namespace lldb;
using namespace lldb_private;
SBSourceManager::SBSourceManager (const SBDebugger &debugger)
{
m_opaque_ap.reset(new SourceManagerImpl (debugger.get_sp()));
}
SBSourceManager::SBSourceManager (const SBTarget &target)
{
m_opaque_ap.reset(new SourceManagerImpl (target.get_sp()));
}
SBSourceManager::SBSourceManager (const SBSourceManager &rhs)
{
if (&rhs == this)
return;
m_opaque_ap.reset(new SourceManagerImpl (*(rhs.m_opaque_ap.get())));
}
const lldb::SBSourceManager &
SBSourceManager::operator = (const lldb::SBSourceManager &rhs)
{
m_opaque_ap.reset (new SourceManagerImpl (*(rhs.m_opaque_ap.get())));
return *this;
}
SBSourceManager::~SBSourceManager()
{
}
size_t
SBSourceManager::DisplaySourceLinesWithLineNumbers
(
const SBFileSpec &file,
uint32_t line,
uint32_t context_before,
uint32_t context_after,
const char* current_line_cstr,
SBStream &s
)
{
if (m_opaque_ap.get() == NULL)
return 0;
return m_opaque_ap->DisplaySourceLinesWithLineNumbers (file.ref(),
line,
context_before,
context_after,
current_line_cstr,
s.get());
}
<commit_msg>Fix regression of test SourceManagerTestCase.test_display_source_python.<commit_after>//===-- SBSourceManager.cpp -------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/API/SBDebugger.h"
#include "lldb/API/SBSourceManager.h"
#include "lldb/API/SBTarget.h"
#include "lldb/API/SBStream.h"
#include "lldb/API/SBFileSpec.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Core/Stream.h"
#include "lldb/Core/StreamFile.h"
#include "lldb/Core/SourceManager.h"
#include "lldb/Target/Target.h"
namespace lldb_private
{
class SourceManagerImpl
{
public:
SourceManagerImpl (const lldb::DebuggerSP &debugger_sp)
{
m_debugger_sp = debugger_sp;
}
SourceManagerImpl (const lldb::TargetSP &target_sp)
{
m_target_sp = target_sp;
}
SourceManagerImpl (const SourceManagerImpl &rhs)
{
if (&rhs == this)
return;
m_debugger_sp = rhs.m_debugger_sp;
m_target_sp = rhs.m_target_sp;
}
size_t
DisplaySourceLinesWithLineNumbers (const lldb_private::FileSpec &file,
uint32_t line,
uint32_t context_before,
uint32_t context_after,
const char* current_line_cstr,
lldb_private::Stream *s)
{
if (!file)
return 0;
if (m_debugger_sp)
return m_debugger_sp->GetSourceManager().DisplaySourceLinesWithLineNumbers (file,
line,
context_before,
context_after,
current_line_cstr,
s);
else if (m_target_sp)
return m_target_sp->GetSourceManager().DisplaySourceLinesWithLineNumbers (file,
line,
context_before,
context_after,
current_line_cstr,
s);
else
return 0;
}
private:
lldb::DebuggerSP m_debugger_sp;
lldb::TargetSP m_target_sp;
};
}
using namespace lldb;
using namespace lldb_private;
SBSourceManager::SBSourceManager (const SBDebugger &debugger)
{
m_opaque_ap.reset(new SourceManagerImpl (debugger.get_sp()));
}
SBSourceManager::SBSourceManager (const SBTarget &target)
{
m_opaque_ap.reset(new SourceManagerImpl (target.get_sp()));
}
SBSourceManager::SBSourceManager (const SBSourceManager &rhs)
{
if (&rhs == this)
return;
m_opaque_ap.reset(new SourceManagerImpl (*(rhs.m_opaque_ap.get())));
}
const lldb::SBSourceManager &
SBSourceManager::operator = (const lldb::SBSourceManager &rhs)
{
m_opaque_ap.reset (new SourceManagerImpl (*(rhs.m_opaque_ap.get())));
return *this;
}
SBSourceManager::~SBSourceManager()
{
}
size_t
SBSourceManager::DisplaySourceLinesWithLineNumbers
(
const SBFileSpec &file,
uint32_t line,
uint32_t context_before,
uint32_t context_after,
const char* current_line_cstr,
SBStream &s
)
{
if (m_opaque_ap.get() == NULL)
return 0;
return m_opaque_ap->DisplaySourceLinesWithLineNumbers (file.ref(),
line,
context_before,
context_after,
current_line_cstr,
s.get());
}
<|endoftext|>
|
<commit_before>#include <list>
#include "vmmethod.hpp"
namespace rubinius {
namespace jit {
class CFGBlock {
public:
typedef std::list<CFGBlock*> List;
private:
int start_ip_;
int end_ip_;
List children_;
bool loop_;
bool detached_;
CFGBlock* exception_handler_;
int exception_type_;
public:
CFGBlock(int start, bool loop=false)
: start_ip_(start)
, end_ip_(0)
, loop_(loop)
, detached_(true)
, exception_handler_(0)
, exception_type_(-1)
{}
int start_ip() {
return start_ip_;
}
void set_end_ip(int ip) {
end_ip_ = ip;
}
void add_child(CFGBlock* block) {
if(block->detached_p()) {
block->attached();
children_.push_back(block);
}
}
void attached() {
detached_ = false;
}
bool detached_p() {
return detached_;
}
bool loop_p() {
return loop_;
}
CFGBlock* exception_handler() {
return exception_handler_;
}
void set_exception_handler(CFGBlock* blk) {
exception_handler_ = blk;
}
int exception_type() {
return exception_type_;
}
void set_exception_type(int type) {
exception_type_ = type;
}
};
class CFGCalculator {
public:
typedef std::map<opcode, CFGBlock*> Blocks;
private:
Blocks blocks_;
CFGBlock* root_;
CFGBlock* current_;
opcode* stream_;
size_t stream_size_;
public:
CFGCalculator(opcode* stream, size_t size)
: root_(0)
, current_(0)
, stream_(stream)
, stream_size_(size)
{}
CFGCalculator(VMMethod* vmm)
: root_(0)
, current_(0)
, stream_(vmm->opcodes)
, stream_size_(vmm->total)
{}
~CFGCalculator() {
for(Blocks::iterator i = blocks_.begin();
i != blocks_.end();
i++) {
delete i->second;
}
}
CFGBlock* root() {
return root_;
}
CFGBlock* find_block(int ip) {
Blocks::iterator i = blocks_.find(ip);
if(i == blocks_.end()) return 0;
return i->second;
}
void set_block(int ip, CFGBlock* blk) {
assert(!blocks_[ip]);
blocks_[ip] = blk;
}
CFGBlock* add_block(int ip, bool loop=false) {
CFGBlock* blk = find_block(ip);
if(blk) {
// If we hit a block that is the start of a loop header,
// be sure to set it's exception handler. These blocks are created
// during the first pass.
if(blk->loop_p()) {
// Inherit the current exception handler
blk->set_exception_handler(current_->exception_handler());
}
return blk;
}
blk = new CFGBlock(ip, loop);
// Inherit the current exception handler
blk->set_exception_handler(current_->exception_handler());
set_block(ip, blk);
return blk;
}
void find_backward_gotos() {
VMMethod::Iterator iter(stream_, stream_size_);
while(!iter.end()) {
switch(iter.op()) {
case InstructionSequence::insn_goto:
case InstructionSequence::insn_goto_if_true:
case InstructionSequence::insn_goto_if_false:
if(iter.operand1() < iter.position()) {
if(!find_block(iter.operand1())) {
CFGBlock* blk = new CFGBlock(iter.operand1(), true);
set_block(iter.operand1(), blk);
}
}
break;
}
iter.inc();
}
}
void close_current(VMMethod::Iterator& iter, CFGBlock* next) {
current_->set_end_ip(iter.position());
current_->add_child(next);
current_ = next;
}
CFGBlock* start_new_block(VMMethod::Iterator& iter) {
if(!iter.last_instruction()) {
CFGBlock* blk = add_block(iter.next_position());
close_current(iter, blk);
return blk;
}
return 0;
}
void build() {
find_backward_gotos();
// Construct the root block specially.
if(blocks_[0]) {
root_ = blocks_[0];
} else {
root_ = new CFGBlock(0);
blocks_[0] = root_;
}
current_ = root_;
VMMethod::Iterator iter(stream_, stream_size_);
for(;;) {
if(CFGBlock* next_block = find_block(iter.position())) {
if(next_block->loop_p() && current_ != next_block) {
// The handler wasn't setup originally, so we have to set it now.
next_block->set_exception_handler(current_->exception_handler());
close_current(iter, next_block);
} else {
current_ = next_block;
}
}
switch(iter.op()) {
case InstructionSequence::insn_goto:
case InstructionSequence::insn_goto_if_true:
case InstructionSequence::insn_goto_if_false:
if(iter.operand1() > iter.position()) {
current_->add_child(add_block(iter.operand1()));
start_new_block(iter);
} else {
#ifndef NDEBUG
CFGBlock* loop_header = find_block(iter.operand1());
assert(loop_header);
assert(loop_header->exception_handler() == current_->exception_handler());
#endif
}
break;
case InstructionSequence::insn_setup_unwind: {
assert(iter.operand1() > iter.position());
CFGBlock* handler = add_block(iter.operand1());
handler->set_exception_type(iter.operand2());
current_->add_child(handler);
CFGBlock* body = start_new_block(iter);
assert(body); // make sure it's not at the end.
body->set_exception_handler(handler);
break;
}
case InstructionSequence::insn_pop_unwind: {
assert(current_->exception_handler());
CFGBlock* cont = start_new_block(iter);
CFGBlock* current_handler = cont->exception_handler();
assert(current_handler);
// Effectively pop the current handler by setting the
// blocks handler (and thus all blocks after it) to the current
// handlers handler.
cont->set_exception_handler(current_handler->exception_handler());
break;
}
case InstructionSequence::insn_ensure_return:
case InstructionSequence::insn_raise_exc:
case InstructionSequence::insn_raise_return:
case InstructionSequence::insn_raise_break:
case InstructionSequence::insn_reraise:
case InstructionSequence::insn_ret:
start_new_block(iter);
break;
}
if(!iter.advance()) break;
}
current_->set_end_ip(iter.position());
}
};
}}
<commit_msg>Fix CFG block calculation bug<commit_after>#include <list>
#include "vmmethod.hpp"
namespace rubinius {
namespace jit {
class CFGBlock {
public:
typedef std::list<CFGBlock*> List;
private:
int start_ip_;
int end_ip_;
List children_;
bool loop_;
bool detached_;
CFGBlock* exception_handler_;
int exception_type_;
public:
CFGBlock(int start, bool loop=false)
: start_ip_(start)
, end_ip_(0)
, loop_(loop)
, detached_(true)
, exception_handler_(0)
, exception_type_(-1)
{}
int start_ip() {
return start_ip_;
}
void set_end_ip(int ip) {
end_ip_ = ip;
}
void add_child(CFGBlock* block) {
if(block->detached_p()) {
block->attached();
children_.push_back(block);
}
}
void attached() {
detached_ = false;
}
bool detached_p() {
return detached_;
}
bool loop_p() {
return loop_;
}
CFGBlock* exception_handler() {
return exception_handler_;
}
void set_exception_handler(CFGBlock* blk) {
exception_handler_ = blk;
}
int exception_type() {
return exception_type_;
}
void set_exception_type(int type) {
exception_type_ = type;
}
};
class CFGCalculator {
public:
typedef std::map<opcode, CFGBlock*> Blocks;
private:
Blocks blocks_;
CFGBlock* root_;
CFGBlock* current_;
opcode* stream_;
size_t stream_size_;
public:
CFGCalculator(opcode* stream, size_t size)
: root_(0)
, current_(0)
, stream_(stream)
, stream_size_(size)
{}
CFGCalculator(VMMethod* vmm)
: root_(0)
, current_(0)
, stream_(vmm->opcodes)
, stream_size_(vmm->total)
{}
~CFGCalculator() {
for(Blocks::iterator i = blocks_.begin();
i != blocks_.end();
i++) {
delete i->second;
}
}
CFGBlock* root() {
return root_;
}
CFGBlock* find_block(int ip) {
Blocks::iterator i = blocks_.find(ip);
if(i == blocks_.end()) return 0;
return i->second;
}
void set_block(int ip, CFGBlock* blk) {
assert(!blocks_[ip]);
blocks_[ip] = blk;
}
CFGBlock* add_block(int ip, bool loop=false) {
CFGBlock* blk = find_block(ip);
if(blk) {
// If we hit a block that is the start of a loop header,
// be sure to set it's exception handler. These blocks are created
// during the first pass.
if(blk->loop_p()) {
// Inherit the current exception handler
blk->set_exception_handler(current_->exception_handler());
}
return blk;
}
blk = new CFGBlock(ip, loop);
// Inherit the current exception handler
blk->set_exception_handler(current_->exception_handler());
set_block(ip, blk);
return blk;
}
void find_backward_gotos() {
VMMethod::Iterator iter(stream_, stream_size_);
while(!iter.end()) {
switch(iter.op()) {
case InstructionSequence::insn_goto:
case InstructionSequence::insn_goto_if_true:
case InstructionSequence::insn_goto_if_false:
if(iter.operand1() < iter.position()) {
if(!find_block(iter.operand1())) {
CFGBlock* blk = new CFGBlock(iter.operand1(), true);
set_block(iter.operand1(), blk);
}
}
break;
}
iter.inc();
}
}
void close_current(VMMethod::Iterator& iter, CFGBlock* next) {
current_->set_end_ip(iter.position());
current_->add_child(next);
current_ = next;
}
CFGBlock* start_new_block(VMMethod::Iterator& iter) {
if(!iter.last_instruction()) {
CFGBlock* blk = add_block(iter.next_position());
close_current(iter, blk);
return blk;
}
return 0;
}
void build() {
find_backward_gotos();
// Construct the root block specially.
if(blocks_[0]) {
root_ = blocks_[0];
} else {
root_ = new CFGBlock(0);
blocks_[0] = root_;
}
current_ = root_;
VMMethod::Iterator iter(stream_, stream_size_);
for(;;) {
if(CFGBlock* next_block = find_block(iter.position())) {
if(next_block->loop_p() && current_ != next_block) {
// The handler wasn't setup originally, so we have to set it now.
next_block->set_exception_handler(current_->exception_handler());
close_current(iter, next_block);
} else {
current_ = next_block;
}
}
switch(iter.op()) {
case InstructionSequence::insn_goto:
case InstructionSequence::insn_goto_if_true:
case InstructionSequence::insn_goto_if_false:
if(iter.operand1() > iter.position()) {
current_->add_child(add_block(iter.operand1()));
} else {
#ifndef NDEBUG
CFGBlock* loop_header = find_block(iter.operand1());
assert(loop_header);
assert(loop_header->exception_handler() == current_->exception_handler());
#endif
}
start_new_block(iter);
break;
case InstructionSequence::insn_setup_unwind: {
assert(iter.operand1() > iter.position());
CFGBlock* handler = add_block(iter.operand1());
handler->set_exception_type(iter.operand2());
current_->add_child(handler);
CFGBlock* body = start_new_block(iter);
assert(body); // make sure it's not at the end.
body->set_exception_handler(handler);
break;
}
case InstructionSequence::insn_pop_unwind: {
assert(current_->exception_handler());
CFGBlock* cont = start_new_block(iter);
CFGBlock* current_handler = cont->exception_handler();
assert(current_handler);
// Effectively pop the current handler by setting the
// blocks handler (and thus all blocks after it) to the current
// handlers handler.
cont->set_exception_handler(current_handler->exception_handler());
break;
}
case InstructionSequence::insn_ensure_return:
case InstructionSequence::insn_raise_exc:
case InstructionSequence::insn_raise_return:
case InstructionSequence::insn_raise_break:
case InstructionSequence::insn_reraise:
case InstructionSequence::insn_ret:
start_new_block(iter);
break;
}
if(!iter.advance()) break;
}
current_->set_end_ip(iter.position());
}
};
}}
<|endoftext|>
|
<commit_before>#include "atlas/gl/ErrorCheck.hpp"
#include "atlas/gl/GL.hpp"
#include "atlas/core/Log.hpp"
namespace atlas
{
namespace gl
{
class DebugCallbackSettings
{
DebugCallbackSettings() :
errorSources(ATLAS_GL_ERROR_SOURCE_ALL),
errorTypes(ATLAS_GL_ERROR_TYPE_ALL),
errorSeverity(ATLAS_GL_ERROR_SEVERITY_ALL)
{ }
~DebugCallbackSettings()
{ }
DebugCallbackSettings(DebugCallbackSettings&) = delete;
void operator=(DebugCallbackSettings&) = delete;
public:
static DebugCallbackSettings& getInstance()
{
static DebugCallbackSettings instance;
return instance;
}
GLuint errorSources;
GLuint errorTypes;
GLuint errorSeverity;
};
void initializeGLError()
{
#ifdef ATLAS_DEBUG
if (glDebugMessageCallback)
{
INFO_LOG("OpenGL debug callback available.");
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageCallback(openGLErrorCallback, nullptr);
GLuint unusedIds = 0;
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE,
GL_DONT_CARE, 0, &unusedIds, true);
}
else
{
INFO_LOG("OpenGL debug callback is not available.");
}
#else
INFO_LOG("OpenGL debug callback only available in debug builds.");
#endif
DebugCallbackSettings::getInstance();
}
void setGLErrorSources(GLuint sources)
{
DebugCallbackSettings::getInstance().errorSources = sources;
}
void setGLErrorTypes(GLuint types)
{
DebugCallbackSettings::getInstance().errorTypes = types;
}
void setGLErrorSeverity(GLuint severity)
{
DebugCallbackSettings::getInstance().errorSeverity = severity;
}
void APIENTRY openGLErrorCallback(GLenum source, GLenum type, GLuint id,
GLenum severity, GLsizei length, const GLchar* message,
const void* userParam)
{
UNUSED(userParam);
UNUSED(length);
DebugCallbackSettings& settings =
DebugCallbackSettings::getInstance();
std::string errorOrigin;
switch (source)
{
case GL_DEBUG_SOURCE_API:
if (settings.errorSources & ATLAS_GL_ERROR_SOURCE_API)
{
errorOrigin = "OpenGL API";
break;
}
return;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM:
if (settings.errorSources & ATLAS_GL_ERROR_SOURCE_WINDOW_SYSTEM)
{
errorOrigin = "window system";
break;
}
return;
case GL_DEBUG_SOURCE_SHADER_COMPILER:
if (settings.errorSources &
ATLAS_GL_ERROR_SOURCE_SHADER_COMPILER)
{
errorOrigin = "shader compiler";
break;
}
return;
case GL_DEBUG_SOURCE_THIRD_PARTY:
if (settings.errorSources & ATLAS_GL_ERROR_SOURCE_THIRD_PARTY)
{
errorOrigin = "third party";
break;
}
return;
case GL_DEBUG_SOURCE_APPLICATION:
if (settings.errorSources & ATLAS_GL_ERROR_SOURCE_APPLICATION)
{
errorOrigin = "user of application";
break;
}
return;
case GL_DEBUG_SOURCE_OTHER:
if (settings.errorSources & ATLAS_GL_ERROR_SOURCE_OTHER)
{
errorOrigin = "other";
break;
}
return;
}
std::string errorType;
switch (type)
{
case GL_DEBUG_TYPE_ERROR:
if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_ERROR)
{
errorType = "error";
break;
}
return;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
if (settings.errorTypes &
ATLAS_GL_ERROR_TYPE_DEPRECATED_BEHAVIOUR)
{
errorType = "deprecated behaviour";
break;
}
return;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
if (settings.errorTypes &
ATLAS_GL_ERROR_TYPE_UNDEFINED_BEHAVIOUR)
{
errorType = "undefined behaviour";
break;
}
return;
case GL_DEBUG_TYPE_PORTABILITY:
if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_PORTABILITY)
{
errorType = "portability";
break;
}
return;
case GL_DEBUG_TYPE_PERFORMANCE:
if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_PERFORMANCE)
{
errorType = "performance";
break;
}
return;
case GL_DEBUG_TYPE_MARKER:
if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_MARKER)
{
errorType = "marker";
break;
}
return;
case GL_DEBUG_TYPE_PUSH_GROUP:
if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_PUSH_GROUP)
{
errorType = "push group";
break;
}
return;
case GL_DEBUG_TYPE_POP_GROUP:
if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_POP_GROUP)
{
errorType = "pop group";
break;
}
return;
case GL_DEBUG_TYPE_OTHER:
if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_OTHER)
{
errorType = "other";
break;
}
return;
}
std::string errorMessage = "[" + errorType + "] : [" +
errorOrigin + "] : (" + std::to_string(id) + "): " + message;
switch (severity)
{
case GL_DEBUG_SEVERITY_NOTIFICATION:
if (settings.errorSeverity &
ATLAS_GL_ERROR_SEVERITY_NOTIFICATION)
{
INFO_LOG("OpenGL notification: " + errorMessage);
}
break;
case GL_DEBUG_SEVERITY_LOW:
if (settings.errorSeverity &
ATLAS_GL_ERROR_SEVERITY_LOW)
{
WARN_LOG("OpenGL warning: " + errorMessage);
}
break;
case GL_DEBUG_SEVERITY_MEDIUM:
if (settings.errorSeverity & ATLAS_GL_ERROR_SEVERITY_MEDIUM)
{
ERROR_LOG("OpenGL error: " + errorMessage);
}
break;
case GL_DEBUG_SEVERITY_HIGH:
if (settings.errorSeverity & ATLAS_GL_ERROR_SEVERITY_HIGH)
{
CRITICAL_LOG("OpenGL critical error: " + errorMessage);
}
break;
}
}
}
}<commit_msg>[brief] Adds a breakpoint on critical OpenGL errors.<commit_after>#include "atlas/gl/ErrorCheck.hpp"
#include "atlas/gl/GL.hpp"
#include "atlas/core/Log.hpp"
#include "atlas/core/Platform.hpp"
#if defined(ATLAS_PLATFORM_WINDOWS) && defined(ATLAS_DEBUG)
#include <intrin.h>
#endif
namespace atlas
{
namespace gl
{
class DebugCallbackSettings
{
DebugCallbackSettings() :
errorSources(ATLAS_GL_ERROR_SOURCE_ALL),
errorTypes(ATLAS_GL_ERROR_TYPE_ALL),
errorSeverity(ATLAS_GL_ERROR_SEVERITY_ALL)
{ }
~DebugCallbackSettings()
{ }
DebugCallbackSettings(DebugCallbackSettings&) = delete;
void operator=(DebugCallbackSettings&) = delete;
public:
static DebugCallbackSettings& getInstance()
{
static DebugCallbackSettings instance;
return instance;
}
GLuint errorSources;
GLuint errorTypes;
GLuint errorSeverity;
};
void initializeGLError()
{
#ifdef ATLAS_DEBUG
if (glDebugMessageCallback)
{
INFO_LOG("OpenGL debug callback available.");
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageCallback(openGLErrorCallback, nullptr);
GLuint unusedIds = 0;
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE,
GL_DONT_CARE, 0, &unusedIds, true);
}
else
{
INFO_LOG("OpenGL debug callback is not available.");
}
#else
INFO_LOG("OpenGL debug callback only available in debug builds.");
#endif
DebugCallbackSettings::getInstance();
}
void setGLErrorSources(GLuint sources)
{
DebugCallbackSettings::getInstance().errorSources = sources;
}
void setGLErrorTypes(GLuint types)
{
DebugCallbackSettings::getInstance().errorTypes = types;
}
void setGLErrorSeverity(GLuint severity)
{
DebugCallbackSettings::getInstance().errorSeverity = severity;
}
void APIENTRY openGLErrorCallback(GLenum source, GLenum type, GLuint id,
GLenum severity, GLsizei length, const GLchar* message,
const void* userParam)
{
UNUSED(userParam);
UNUSED(length);
DebugCallbackSettings& settings =
DebugCallbackSettings::getInstance();
std::string errorOrigin;
switch (source)
{
case GL_DEBUG_SOURCE_API:
if (settings.errorSources & ATLAS_GL_ERROR_SOURCE_API)
{
errorOrigin = "OpenGL API";
break;
}
return;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM:
if (settings.errorSources & ATLAS_GL_ERROR_SOURCE_WINDOW_SYSTEM)
{
errorOrigin = "window system";
break;
}
return;
case GL_DEBUG_SOURCE_SHADER_COMPILER:
if (settings.errorSources &
ATLAS_GL_ERROR_SOURCE_SHADER_COMPILER)
{
errorOrigin = "shader compiler";
break;
}
return;
case GL_DEBUG_SOURCE_THIRD_PARTY:
if (settings.errorSources & ATLAS_GL_ERROR_SOURCE_THIRD_PARTY)
{
errorOrigin = "third party";
break;
}
return;
case GL_DEBUG_SOURCE_APPLICATION:
if (settings.errorSources & ATLAS_GL_ERROR_SOURCE_APPLICATION)
{
errorOrigin = "user of application";
break;
}
return;
case GL_DEBUG_SOURCE_OTHER:
if (settings.errorSources & ATLAS_GL_ERROR_SOURCE_OTHER)
{
errorOrigin = "other";
break;
}
return;
}
std::string errorType;
switch (type)
{
case GL_DEBUG_TYPE_ERROR:
if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_ERROR)
{
errorType = "error";
break;
}
return;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
if (settings.errorTypes &
ATLAS_GL_ERROR_TYPE_DEPRECATED_BEHAVIOUR)
{
errorType = "deprecated behaviour";
break;
}
return;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
if (settings.errorTypes &
ATLAS_GL_ERROR_TYPE_UNDEFINED_BEHAVIOUR)
{
errorType = "undefined behaviour";
break;
}
return;
case GL_DEBUG_TYPE_PORTABILITY:
if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_PORTABILITY)
{
errorType = "portability";
break;
}
return;
case GL_DEBUG_TYPE_PERFORMANCE:
if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_PERFORMANCE)
{
errorType = "performance";
break;
}
return;
case GL_DEBUG_TYPE_MARKER:
if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_MARKER)
{
errorType = "marker";
break;
}
return;
case GL_DEBUG_TYPE_PUSH_GROUP:
if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_PUSH_GROUP)
{
errorType = "push group";
break;
}
return;
case GL_DEBUG_TYPE_POP_GROUP:
if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_POP_GROUP)
{
errorType = "pop group";
break;
}
return;
case GL_DEBUG_TYPE_OTHER:
if (settings.errorTypes & ATLAS_GL_ERROR_TYPE_OTHER)
{
errorType = "other";
break;
}
return;
}
std::string errorMessage = "[" + errorType + "] : [" +
errorOrigin + "] : (" + std::to_string(id) + "): " + message;
switch (severity)
{
case GL_DEBUG_SEVERITY_NOTIFICATION:
if (settings.errorSeverity &
ATLAS_GL_ERROR_SEVERITY_NOTIFICATION)
{
INFO_LOG("OpenGL notification: " + errorMessage);
}
break;
case GL_DEBUG_SEVERITY_LOW:
if (settings.errorSeverity &
ATLAS_GL_ERROR_SEVERITY_LOW)
{
WARN_LOG("OpenGL warning: " + errorMessage);
}
break;
case GL_DEBUG_SEVERITY_MEDIUM:
if (settings.errorSeverity & ATLAS_GL_ERROR_SEVERITY_MEDIUM)
{
ERROR_LOG("OpenGL error: " + errorMessage);
}
break;
case GL_DEBUG_SEVERITY_HIGH:
if (settings.errorSeverity & ATLAS_GL_ERROR_SEVERITY_HIGH)
{
CRITICAL_LOG("OpenGL critical error: " + errorMessage);
}
#if defined(ATLAS_DEBUG) && defined(ATLAS_PLATFORM_WINDOWS)
__debugbreak();
#endif
break;
}
}
}
}<|endoftext|>
|
<commit_before>// Copyright (c) 2014-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <chainparams.h>
#include <net.h>
#include <signet.h>
#include <validation.h>
#include <test/util/setup_common.h>
#include <boost/signals2/signal.hpp>
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(validation_tests, TestingSetup)
static void TestBlockSubsidyHalvings(const CChainParams& chainParams)
{
const Consensus::Params& consensusParams = chainParams.GetConsensus();
int maxHalvings = 64;
CAmount nInitialSubsidy = 50 * COIN;
CAmount nPreviousSubsidy = nInitialSubsidy * 2; // for height == 0
BOOST_CHECK_EQUAL(nPreviousSubsidy, nInitialSubsidy * 2);
for (int nHalvings = 0; nHalvings < maxHalvings; nHalvings++) {
int nHeight = nHalvings * consensusParams.nSubsidyHalvingInterval;
CAmount nSubsidy = GetBlockSubsidy(nHeight, chainParams);
BOOST_CHECK(nSubsidy <= nInitialSubsidy);
BOOST_CHECK_EQUAL(nSubsidy, nPreviousSubsidy / 2);
nPreviousSubsidy = nSubsidy;
}
BOOST_CHECK_EQUAL(GetBlockSubsidy(maxHalvings * consensusParams.nSubsidyHalvingInterval, chainParams), 0);
}
static void TestBlockSubsidyHalvings(int nSubsidyHalvingInterval)
{
Consensus::Params consensusParams;
consensusParams.nSubsidyHalvingInterval = nSubsidyHalvingInterval;
TestBlockSubsidyHalvings(consensusParams);
}
BOOST_AUTO_TEST_CASE(block_subsidy_test)
{
const auto chainParams = CreateChainParams(*m_node.args, CBaseChainParams::MAIN);
TestBlockSubsidyHalvings(chainParams->GetConsensus()); // As in main
TestBlockSubsidyHalvings(150); // As in regtest
TestBlockSubsidyHalvings(1000); // Just another interval
}
BOOST_AUTO_TEST_CASE(subsidy_limit_test)
{
const auto chainParams = CreateChainParams(*m_node.args, CBaseChainParams::MAIN);
CAmount nSum = 0;
for (int nHeight = 0; nHeight < 14000000; nHeight += 1000) {
CAmount nSubsidy = GetBlockSubsidy(nHeight, chainParams);
BOOST_CHECK(nSubsidy <= 50 * COIN);
nSum += nSubsidy * 1000;
BOOST_CHECK(MoneyRange(nSum));
}
BOOST_CHECK_EQUAL(nSum, CAmount{2099999997690000});
}
BOOST_AUTO_TEST_CASE(signet_parse_tests)
{
ArgsManager signet_argsman;
signet_argsman.ForceSetArg("-signetchallenge", "51"); // set challenge to OP_TRUE
const auto signet_params = CreateChainParams(signet_argsman, CBaseChainParams::SIGNET);
CBlock block;
BOOST_CHECK(signet_params->GetConsensus().signet_challenge == std::vector<uint8_t>{{OP_TRUE}});
CScript challenge{OP_TRUE};
// empty block is invalid
BOOST_CHECK(!SignetTxs::Create(block, challenge));
BOOST_CHECK(!CheckSignetBlockSolution(block, signet_params->GetConsensus()));
// no witness commitment
CMutableTransaction cb;
cb.vout.emplace_back(0, CScript{});
block.vtx.push_back(MakeTransactionRef(cb));
block.vtx.push_back(MakeTransactionRef(cb)); // Add dummy tx to excercise merkle root code
BOOST_CHECK(!SignetTxs::Create(block, challenge));
BOOST_CHECK(!CheckSignetBlockSolution(block, signet_params->GetConsensus()));
// no header is treated valid
std::vector<uint8_t> witness_commitment_section_141{0xaa, 0x21, 0xa9, 0xed};
for (int i = 0; i < 32; ++i) {
witness_commitment_section_141.push_back(0xff);
}
cb.vout.at(0).scriptPubKey = CScript{} << OP_RETURN << witness_commitment_section_141;
block.vtx.at(0) = MakeTransactionRef(cb);
BOOST_CHECK(SignetTxs::Create(block, challenge));
BOOST_CHECK(CheckSignetBlockSolution(block, signet_params->GetConsensus()));
// no data after header, valid
std::vector<uint8_t> witness_commitment_section_325{0xec, 0xc7, 0xda, 0xa2};
cb.vout.at(0).scriptPubKey = CScript{} << OP_RETURN << witness_commitment_section_141 << witness_commitment_section_325;
block.vtx.at(0) = MakeTransactionRef(cb);
BOOST_CHECK(SignetTxs::Create(block, challenge));
BOOST_CHECK(CheckSignetBlockSolution(block, signet_params->GetConsensus()));
// Premature end of data, invalid
witness_commitment_section_325.push_back(0x01);
witness_commitment_section_325.push_back(0x51);
cb.vout.at(0).scriptPubKey = CScript{} << OP_RETURN << witness_commitment_section_141 << witness_commitment_section_325;
block.vtx.at(0) = MakeTransactionRef(cb);
BOOST_CHECK(!SignetTxs::Create(block, challenge));
BOOST_CHECK(!CheckSignetBlockSolution(block, signet_params->GetConsensus()));
// has data, valid
witness_commitment_section_325.push_back(0x00);
cb.vout.at(0).scriptPubKey = CScript{} << OP_RETURN << witness_commitment_section_141 << witness_commitment_section_325;
block.vtx.at(0) = MakeTransactionRef(cb);
BOOST_CHECK(SignetTxs::Create(block, challenge));
BOOST_CHECK(CheckSignetBlockSolution(block, signet_params->GetConsensus()));
// Extraneous data, invalid
witness_commitment_section_325.push_back(0x00);
cb.vout.at(0).scriptPubKey = CScript{} << OP_RETURN << witness_commitment_section_141 << witness_commitment_section_325;
block.vtx.at(0) = MakeTransactionRef(cb);
BOOST_CHECK(!SignetTxs::Create(block, challenge));
BOOST_CHECK(!CheckSignetBlockSolution(block, signet_params->GetConsensus()));
}
static bool ReturnFalse() { return false; }
static bool ReturnTrue() { return true; }
BOOST_AUTO_TEST_CASE(test_combiner_all)
{
boost::signals2::signal<bool (), CombinerAll> Test;
BOOST_CHECK(Test());
Test.connect(&ReturnFalse);
BOOST_CHECK(!Test());
Test.connect(&ReturnTrue);
BOOST_CHECK(!Test());
Test.disconnect(&ReturnFalse);
BOOST_CHECK(Test());
Test.disconnect(&ReturnTrue);
BOOST_CHECK(Test());
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>refactor: fix -Wbraced-scalar-init warning in validation tests<commit_after>// Copyright (c) 2014-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <chainparams.h>
#include <net.h>
#include <signet.h>
#include <validation.h>
#include <test/util/setup_common.h>
#include <boost/signals2/signal.hpp>
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(validation_tests, TestingSetup)
static void TestBlockSubsidyHalvings(const CChainParams& chainParams)
{
const Consensus::Params& consensusParams = chainParams.GetConsensus();
int maxHalvings = 64;
CAmount nInitialSubsidy = 50 * COIN;
CAmount nPreviousSubsidy = nInitialSubsidy * 2; // for height == 0
BOOST_CHECK_EQUAL(nPreviousSubsidy, nInitialSubsidy * 2);
for (int nHalvings = 0; nHalvings < maxHalvings; nHalvings++) {
int nHeight = nHalvings * consensusParams.nSubsidyHalvingInterval;
CAmount nSubsidy = GetBlockSubsidy(nHeight, chainParams);
BOOST_CHECK(nSubsidy <= nInitialSubsidy);
BOOST_CHECK_EQUAL(nSubsidy, nPreviousSubsidy / 2);
nPreviousSubsidy = nSubsidy;
}
BOOST_CHECK_EQUAL(GetBlockSubsidy(maxHalvings * consensusParams.nSubsidyHalvingInterval, chainParams), 0);
}
static void TestBlockSubsidyHalvings(int nSubsidyHalvingInterval)
{
Consensus::Params consensusParams;
consensusParams.nSubsidyHalvingInterval = nSubsidyHalvingInterval;
TestBlockSubsidyHalvings(consensusParams);
}
BOOST_AUTO_TEST_CASE(block_subsidy_test)
{
const auto chainParams = CreateChainParams(*m_node.args, CBaseChainParams::MAIN);
TestBlockSubsidyHalvings(chainParams->GetConsensus()); // As in main
TestBlockSubsidyHalvings(150); // As in regtest
TestBlockSubsidyHalvings(1000); // Just another interval
}
BOOST_AUTO_TEST_CASE(subsidy_limit_test)
{
const auto chainParams = CreateChainParams(*m_node.args, CBaseChainParams::MAIN);
CAmount nSum = 0;
for (int nHeight = 0; nHeight < 14000000; nHeight += 1000) {
CAmount nSubsidy = GetBlockSubsidy(nHeight, chainParams);
BOOST_CHECK(nSubsidy <= 50 * COIN);
nSum += nSubsidy * 1000;
BOOST_CHECK(MoneyRange(nSum));
}
BOOST_CHECK_EQUAL(nSum, CAmount{2099999997690000});
}
BOOST_AUTO_TEST_CASE(signet_parse_tests)
{
ArgsManager signet_argsman;
signet_argsman.ForceSetArg("-signetchallenge", "51"); // set challenge to OP_TRUE
const auto signet_params = CreateChainParams(signet_argsman, CBaseChainParams::SIGNET);
CBlock block;
BOOST_CHECK(signet_params->GetConsensus().signet_challenge == std::vector<uint8_t>{OP_TRUE});
CScript challenge{OP_TRUE};
// empty block is invalid
BOOST_CHECK(!SignetTxs::Create(block, challenge));
BOOST_CHECK(!CheckSignetBlockSolution(block, signet_params->GetConsensus()));
// no witness commitment
CMutableTransaction cb;
cb.vout.emplace_back(0, CScript{});
block.vtx.push_back(MakeTransactionRef(cb));
block.vtx.push_back(MakeTransactionRef(cb)); // Add dummy tx to excercise merkle root code
BOOST_CHECK(!SignetTxs::Create(block, challenge));
BOOST_CHECK(!CheckSignetBlockSolution(block, signet_params->GetConsensus()));
// no header is treated valid
std::vector<uint8_t> witness_commitment_section_141{0xaa, 0x21, 0xa9, 0xed};
for (int i = 0; i < 32; ++i) {
witness_commitment_section_141.push_back(0xff);
}
cb.vout.at(0).scriptPubKey = CScript{} << OP_RETURN << witness_commitment_section_141;
block.vtx.at(0) = MakeTransactionRef(cb);
BOOST_CHECK(SignetTxs::Create(block, challenge));
BOOST_CHECK(CheckSignetBlockSolution(block, signet_params->GetConsensus()));
// no data after header, valid
std::vector<uint8_t> witness_commitment_section_325{0xec, 0xc7, 0xda, 0xa2};
cb.vout.at(0).scriptPubKey = CScript{} << OP_RETURN << witness_commitment_section_141 << witness_commitment_section_325;
block.vtx.at(0) = MakeTransactionRef(cb);
BOOST_CHECK(SignetTxs::Create(block, challenge));
BOOST_CHECK(CheckSignetBlockSolution(block, signet_params->GetConsensus()));
// Premature end of data, invalid
witness_commitment_section_325.push_back(0x01);
witness_commitment_section_325.push_back(0x51);
cb.vout.at(0).scriptPubKey = CScript{} << OP_RETURN << witness_commitment_section_141 << witness_commitment_section_325;
block.vtx.at(0) = MakeTransactionRef(cb);
BOOST_CHECK(!SignetTxs::Create(block, challenge));
BOOST_CHECK(!CheckSignetBlockSolution(block, signet_params->GetConsensus()));
// has data, valid
witness_commitment_section_325.push_back(0x00);
cb.vout.at(0).scriptPubKey = CScript{} << OP_RETURN << witness_commitment_section_141 << witness_commitment_section_325;
block.vtx.at(0) = MakeTransactionRef(cb);
BOOST_CHECK(SignetTxs::Create(block, challenge));
BOOST_CHECK(CheckSignetBlockSolution(block, signet_params->GetConsensus()));
// Extraneous data, invalid
witness_commitment_section_325.push_back(0x00);
cb.vout.at(0).scriptPubKey = CScript{} << OP_RETURN << witness_commitment_section_141 << witness_commitment_section_325;
block.vtx.at(0) = MakeTransactionRef(cb);
BOOST_CHECK(!SignetTxs::Create(block, challenge));
BOOST_CHECK(!CheckSignetBlockSolution(block, signet_params->GetConsensus()));
}
static bool ReturnFalse() { return false; }
static bool ReturnTrue() { return true; }
BOOST_AUTO_TEST_CASE(test_combiner_all)
{
boost::signals2::signal<bool (), CombinerAll> Test;
BOOST_CHECK(Test());
Test.connect(&ReturnFalse);
BOOST_CHECK(!Test());
Test.connect(&ReturnTrue);
BOOST_CHECK(!Test());
Test.disconnect(&ReturnFalse);
BOOST_CHECK(Test());
Test.disconnect(&ReturnTrue);
BOOST_CHECK(Test());
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>
|
<commit_before>/**
* @file persistence_dat.cpp
*
* @brief Purpose: Contains methods to save the game
*
* MIT License
* Copyright (c) 2017 MindScape
*
* https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md
*
*/
#include "persistence_dat.hpp"
#include "../engine/include/log.hpp"
#include <unordered_map>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <stack>
using namespace engine;
PersistenceDat *PersistenceDat::instance = 0;
/**
* @brief Get Instance
*
* Method responsible for get instance
*
* @return void
*/
PersistenceDat *PersistenceDat::get_instance(){
if (!instance) {
instance = nullptr;
}
else {
/*Do nothing*/
}
instance = new PersistenceDat();
return instance;
}
/**
* @brief Dump Method
*
* Method responsible for dump
*
* @param path path to save the open game in a file
* @param data saved game
* @return void
*/
bool PersistenceDat::dump(std::string path, PersistenceMap * data){
std::ofstream save_file;
save_file.open(path);
/* Opens the file to be written */
if (save_file.is_open()) {
for (auto it = data->begin(); it < data->end(); it++) {
/* Writes persistence datas in opened file */
for (auto each_data : *it) {
save_file << each_data.first << " " << each_data.second << " ";
}
save_file << std::endl;
}
}
else {
INFO("Unable to open file");
return false;
}
save_file.close();
return true;
}
/**
* @brief Load Method
*
* Method responsible for load the saved game
*
* @param p_path path to saved game
* @return game loaded
*/
PersistenceMap * PersistenceDat::load(std::string p_path){
PersistenceMap *data = nullptr;
data = new PersistenceMap();
std::stack<std::string> paths;
paths.push(p_path);
std::string line = "";
/* Reads the complete file */
while(!paths.empty()){
std::string path = paths.top();
paths.pop();
std::ifstream save_file;
save_file.open(path, std::ifstream::in);
/* Opens the file to be written */
if (save_file.is_open()){
/* Writes the opened file with game datas*/
while (std::getline(save_file,line)){
bool is_include = false;
std::istringstream iss(line);
std::string key = "";
std::string value = "";
std::unordered_map<std::string, std::string> object_data;
/* If the line are empty or the line initialize with comment tag */
if (line != "" && line[0] != '#'){
while(iss >> key && iss >> value){
/* Writes persistence values in opened file */
if ((is_include = (key == "include"))) {
paths.push(value);
}
else {
/* Do nothing */
}
object_data[key] = value;
}
if (!is_include) {
data->insert_object(object_data);
}
else {
/* Do nothing */
}
}
else {
INFO("The file was opened incorrectly");
}
}
}
else {
INFO("Unable to open file");
return NULL;
}
}
return data;
}
<commit_msg>[DECOMPOSITION] Applies technique in persistence_dat<commit_after>/**
* @file persistence_dat.cpp
*
* @brief Purpose: Contains methods to save the game
*
* MIT License
* Copyright (c) 2017 MindScape
*
* https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md
*
*/
#include "persistence_dat.hpp"
#include "../engine/include/log.hpp"
#include <unordered_map>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <stack>
using namespace engine;
PersistenceDat *PersistenceDat::instance = 0; /**< Instance. Instance of the game */
void write_file(std::stack<std::string> paths, PersistenceMap *data, std::string line);
/**
* @brief Get Instance
*
* Method responsible for get instance
*
* @return void
*/
PersistenceDat *PersistenceDat::get_instance(){
if (!instance) {
instance = nullptr;
}
else {
/*Do nothing*/
}
instance = new PersistenceDat();
return instance;
}
/**
* @brief Dump Method
*
* Method responsible for dump
*
* @param path path to save the open game in a file
* @param data saved game
* @return void
*/
bool PersistenceDat::dump(std::string path, PersistenceMap * data){
std::ofstream save_file; /**< ofstream. Output stream class to operate on file */
save_file.open(path);
/* Opens the file to be written */
if (save_file.is_open()) {
for (auto it = data->begin(); it < data->end(); it++) {
/* Writes persistence datas in opened file */
for (auto each_data : *it) {
save_file << each_data.first << " " << each_data.second << " ";
}
save_file << std::endl;
}
}
else {
INFO("Unable to open file");
return false;
}
save_file.close();
return true;
}
/**
* @brief Load Method
*
* Method responsible for load the saved game
*
* @param p_path path to saved game
* @return game loaded
*/
PersistenceMap * PersistenceDat::load(std::string p_path){
PersistenceMap *data = nullptr; /**< PersistenceMap. Map states */
data = new PersistenceMap();
std::stack<std::string> paths; /**< string. path name */
paths.push(p_path);
std::string line = "";
/* Reads the complete file */
while(!paths.empty()){
std::string path = paths.top(); /**< string. path name */
std::ifstream save_file; /**< ifstream. Input stream class to operate on files */
paths.pop();
save_file.open(path, std::ifstream::in);
/* Opens the file to be written */
if (save_file.is_open()){
/* Writes the opened file with game datas*/
while (std::getline(save_file, line)){
/* If the line isn't empty or the line doesn't initialize with comment tag */
if (line != "" && line[0] != '#'){
write_file(paths, data, line);
}
else {
INFO("The file was opened incorrectly");
}
}
}
else {
INFO("Unable to open file");
return NULL;
}
}
return data;
}
/**
* @brief Writes in file
*
* This function allows writes the data in the files
*
* @param paths. Name of the path will be write.
* @param data. Map states.
* @param line. line that will be written in the file.
* @return void.
*/
void write_file(std::stack<std::string> paths,
PersistenceMap *data, std::string line){
bool is_include = false;
std::string key = ""; /**< string. Access key */
std::string value = ""; /**< string. Data values */
std::istringstream iss(line); /**< istringstream. Input stream class to operate on strings. */
std::unordered_map<std::string, std::string> object_data; /**< object of the dada */
while(iss >> key && iss >> value){
/* Writes persistence values in opened file */
if (is_include = (key == "include")) {
/* If it's to write in the file */
paths.push(value);
}
else {
/* Do nothing */
}
object_data[key] = value;
}
if (!is_include) {
/* If it isn't to write in the file and save the object datas */
data->insert_object(object_data);
}
else {
/* Do nothing */
}
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.