text string | size int64 | token_count int64 |
|---|---|---|
#include "class_9.h"
#include "class_6.h"
#include "class_7.h"
#include "class_1.h"
#include "class_3.h"
#include "class_8.h"
#include <lib_7/class_1.h>
#include <lib_3/class_0.h>
#include <lib_13/class_8.h>
#include <lib_9/class_5.h>
#include <lib_1/class_9.h>
class_9::class_9() {}
class_9::~class_9() {}
| 308 | 154 |
/*=================================================
* FileName: FishManager.cpp
*
* Created by: Komodoman
* Project name: OceanProject
* Unreal Engine version: 4.18.3
* Created on: 2015/03/17
*
* Last Edited on: 2018/03/15
* Last Edited by: Felipe "Zoc" Silveira
*
* -------------------------------------------------
* For parts referencing UE4 code, the following copyright applies:
* Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
*
* Feel free to use this software in any commercial/free game.
* Selling this as a plugin/item, in whole or part, is not allowed.
* See "OceanProject\License.md" for full licensing details.
* =================================================*/
#include "Fish/FishManager.h"
#include "Fish/FlockFish.h"
#include "Classes/Kismet/GameplayStatics.h"
#include "Classes/Engine/World.h"
AFishManager::AFishManager(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
PrimaryActorTick.bCanEverTick = true;
}
void AFishManager::Tick(float val)
{
setup();
if (attachToPlayer)
{
moveToPlayer();
}
}
void AFishManager::moveToPlayer()
{
if (player)
this->SetActorLocation(player->GetActorLocation());
}
float AFishManager::getMinZ()
{
return minZ;
}
float AFishManager::getMaxZ()
{
return maxZ;
}
void AFishManager::setup()
{
if (isSetup == false){
if (!areFishSpawned)
{
maxX = GetActorLocation().X + underwaterBoxLength;
maxY = GetActorLocation().Y + underwaterBoxLength;
minX = GetActorLocation().X - underwaterBoxLength;
minY = GetActorLocation().Y - underwaterBoxLength;
UWorld* const world = GetWorld();
int numFlocks = flockTypes.Num();
for (int i = 0; i < numFlocks; i++)
{
FVector spawnLoc = FVector(FMath::FRandRange(minX, maxX), FMath::FRandRange(minY, maxY), FMath::FRandRange(minZ, maxZ));
AFlockFish *leaderFish = NULL;
for (int j = 0; j < numInFlock[i]; j++)
{
AFlockFish *aFish = Cast<AFlockFish>(world->SpawnActor(flockTypes[i]));
aFish->isLeader = false;
aFish->DebugMode = DebugMode;
aFish->underwaterMax = FVector(maxX, maxY, maxZ);
aFish->underwaterMin = FVector(minX, minY, minZ);
aFish->underwaterBoxLength = underwaterBoxLength;
spawnLoc = FVector(FMath::FRandRange(minX, maxX), FMath::FRandRange(minY, maxY), FMath::FRandRange(minZ, maxZ));
if (j == 0)
{
aFish->isLeader = true;
leaderFish = aFish;
}
else if (leaderFish != NULL)
{
aFish->leader = leaderFish;
}
aFish->SetActorLocation(spawnLoc);
}
}
areFishSpawned = true;
}
if (attachToPlayer)
{
TArray<AActor*> aPlayerList;
UGameplayStatics::GetAllActorsOfClass(this, playerType, aPlayerList);
if (aPlayerList.Num() > 0)
{
player = aPlayerList[0];
isSetup = true;
}
}
else
{
isSetup = true;
}
}
}
| 2,841 | 1,206 |
#include "outmessagelistpage.h"
#include "ui_messagelistpage.h"
#include "guiutil.h"
#include "messagetablemodel.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include "newmessagedialog.h"
#include "platformstyle.h"
#include "messageinfodialog.h"
#include "csvmodelwriter.h"
#include "ui_interface.h"
#include <QSortFilterProxyModel>
#include <QClipboard>
#include <QMessageBox>
#include <QKeyEvent>
#include <QSettings>
#include <QMenu>
using namespace std;
OutMessageListPage::OutMessageListPage(const PlatformStyle *platformStyle, QWidget *parent) :
QDialog(parent),
ui(new Ui::MessageListPage),
model(0),
optionsModel(0)
{
ui->setupUi(this);
QString theme = GUIUtil::getThemeName();
if (!platformStyle->getImagesOnButtons())
{
ui->exportButton->setIcon(QIcon());
ui->newMessage->setIcon(QIcon());
ui->detailButton->setIcon(QIcon());
ui->copyMessage->setIcon(QIcon());
ui->refreshButton->setIcon(QIcon());
}
else
{
ui->exportButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/export"));
ui->newMessage->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/add"));
ui->detailButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/details"));
ui->copyMessage->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/editcopy"));
ui->refreshButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/refresh"));
}
ui->labelExplanation->setText(tr("These are Gtacoin messages you have sent."));
// Context menu actions
QAction *copyGuidAction = new QAction(ui->copyMessage->text(), this);
QAction *copySubjectAction = new QAction(tr("Copy Subject"), this);
QAction *copyMessageAction = new QAction(tr("Copy Msg"), this);
QAction *newMessageAction = new QAction(tr("New Msg"), this);
QAction *detailsAction = new QAction(tr("Details"), this);
// Build context menu
contextMenu = new QMenu();
contextMenu->addAction(copyGuidAction);
contextMenu->addAction(copySubjectAction);
contextMenu->addAction(copyMessageAction);
contextMenu->addAction(detailsAction);
contextMenu->addSeparator();
contextMenu->addAction(newMessageAction);
// Connect signals for context menu actions
connect(copyGuidAction, SIGNAL(triggered()), this, SLOT(on_copyGuid_clicked()));
connect(copySubjectAction, SIGNAL(triggered()), this, SLOT(on_copySubject_clicked()));
connect(copyMessageAction, SIGNAL(triggered()), this, SLOT(on_copyMessage_clicked()));
connect(newMessageAction, SIGNAL(triggered()), this, SLOT(on_newMessage_clicked()));
connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(on_detailButton_clicked()));
connect(detailsAction, SIGNAL(triggered()), this, SLOT(on_detailButton_clicked()));
connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));
}
void OutMessageListPage::on_detailButton_clicked()
{
if(!ui->tableView->selectionModel())
return;
QModelIndexList selection = ui->tableView->selectionModel()->selectedRows();
if(!selection.isEmpty())
{
MessageInfoDialog dlg;
QModelIndex origIndex = proxyModel->mapToSource(selection.at(0));
dlg.setModel(walletModel, model);
dlg.loadRow(origIndex.row());
dlg.exec();
}
}
void OutMessageListPage::on_newMessage_clicked()
{
NewMessageDialog dlg(NewMessageDialog::NewMessage);
dlg.setModel(walletModel, model);
dlg.exec();
}
OutMessageListPage::~OutMessageListPage()
{
delete ui;
}
void OutMessageListPage::showEvent ( QShowEvent * event )
{
if(!walletModel) return;
}
void OutMessageListPage::setModel(WalletModel* walletModel, MessageTableModel *model)
{
this->model = model;
this->walletModel = walletModel;
if(!model) return;
proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(model);
proxyModel->setDynamicSortFilter(true);
proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
proxyModel->setFilterRole(MessageTableModel::TypeRole);
ui->tableView->setModel(proxyModel);
ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
// Set column widths
ui->tableView->setColumnWidth(0, 75); //guid
ui->tableView->setColumnWidth(1, 75); //time
ui->tableView->setColumnWidth(2, 100); //from
ui->tableView->setColumnWidth(3, 100); //to
ui->tableView->setColumnWidth(4, 300); //subject
ui->tableView->setColumnWidth(5, 300); //message
ui->tableView->horizontalHeader()->setStretchLastSection(true);
connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
this, SLOT(selectionChanged()));
// Select row for newly created outmessage
connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewMessage(QModelIndex,int,int)));
selectionChanged();
}
void OutMessageListPage::setOptionsModel(OptionsModel *optionsModel)
{
this->optionsModel = optionsModel;
}
void OutMessageListPage::on_refreshButton_clicked()
{
if(!model)
return;
model->refreshMessageTable();
}
void OutMessageListPage::on_copyMessage_clicked()
{
GUIUtil::copyEntryData(ui->tableView, MessageTableModel::Message);
}
void OutMessageListPage::on_copyGuid_clicked()
{
GUIUtil::copyEntryData(ui->tableView, MessageTableModel::GUID);
}
void OutMessageListPage::on_copySubject_clicked()
{
GUIUtil::copyEntryData(ui->tableView, MessageTableModel::Subject);
}
void OutMessageListPage::selectionChanged()
{
// Set button states based on selected tab and selection
QTableView *table = ui->tableView;
if(!table->selectionModel())
return;
if(table->selectionModel()->hasSelection())
{
ui->copyMessage->setEnabled(true);
ui->detailButton->setEnabled(true);
}
else
{
ui->copyMessage->setEnabled(false);
ui->detailButton->setEnabled(false);
}
}
void OutMessageListPage::keyPressEvent(QKeyEvent * event)
{
if( event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter )
{
on_newMessage_clicked();
event->accept();
}
else
QDialog::keyPressEvent( event );
}
void OutMessageListPage::on_exportButton_clicked()
{
// CSV is currently the only supported format
QString filename = GUIUtil::getSaveFileName(
this,
tr("Export Message Data"), QString(),
tr("Comma separated file (*.csv)"), NULL);
if (filename.isNull()) return;
CSVModelWriter writer(filename);
// name, column, role
writer.setModel(proxyModel);
writer.addColumn(tr("GUID"), MessageTableModel::GUID, Qt::EditRole);
writer.addColumn(tr("Time"), MessageTableModel::Time, Qt::EditRole);
writer.addColumn(tr("From"), MessageTableModel::From, Qt::EditRole);
writer.addColumn(tr("To"), MessageTableModel::To, Qt::EditRole);
writer.addColumn(tr("Subject"), MessageTableModel::Subject, Qt::EditRole);
writer.addColumn(tr("Message"), MessageTableModel::Message, Qt::EditRole);
if(!writer.write())
{
QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file: ") + filename,
QMessageBox::Abort, QMessageBox::Abort);
}
}
void OutMessageListPage::contextualMenu(const QPoint &point)
{
QModelIndex index = ui->tableView->indexAt(point);
if(index.isValid()) {
contextMenu->exec(QCursor::pos());
}
}
void OutMessageListPage::selectNewMessage(const QModelIndex &parent, int begin, int /*end*/)
{
QModelIndex idx = proxyModel->mapFromSource(model->index(begin, MessageTableModel::GUID, parent));
if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newMessageToSelect))
{
// Select row of newly created outmessage, once
ui->tableView->setFocus();
ui->tableView->selectRow(idx.row());
newMessageToSelect.clear();
}
}
| 8,051 | 2,524 |
#include "DriverTimerLocal.h"
#include "HostImplementation.h"
#ifdef GENERIC_TARGET_IMPLEMENTATION
#include <GenericTarget.hpp>
#include <TargetTime.hpp>
#endif
void CreateDriverTimerLocal(void){
#ifndef GENERIC_TARGET_IMPLEMENTATION
#ifdef HOST_IMPLEMENTATION
HostImplementation::CreateDriverTimerLocal();
#endif
#endif
}
void DeleteDriverTimerLocal(void){
#ifndef GENERIC_TARGET_IMPLEMENTATION
#ifdef HOST_IMPLEMENTATION
HostImplementation::DeleteDriverTimerLocal();
#endif
#endif
}
void OutputDriverTimerLocal(int32_t* nanoseconds, int32_t* second, int32_t* minute, int32_t* hour, int32_t* mday, int32_t* mon, int32_t* year, int32_t* wday, int32_t* yday, int32_t* isdst){
#ifdef GENERIC_TARGET_IMPLEMENTATION
TargetTime t = GenericTarget::GetTargetTime();
*nanoseconds = t.local.nanoseconds;
*second = t.local.second;
*minute = t.local.minute;
*hour = t.local.hour;
*mday = t.local.mday;
*mon = t.local.mon;
*year = t.local.year;
*wday = t.local.wday;
*yday = t.local.yday;
*isdst = t.local.isdst;
#else
#ifdef HOST_IMPLEMENTATION
HostImplementation::OutputDriverTimerLocal(nanoseconds, second, minute, hour, mday, mon, year, wday, yday, isdst);
#else
*nanoseconds = 0;
*second = 0;
*minute = 0;
*hour = 0;
*mday = 1;
*mon = 0;
*year = 0;
*wday = 1;
*yday = 0;
*isdst = -1;
#endif
#endif
}
| 1,450 | 601 |
#pragma once
#include <glm/glm.hpp>
#include "Material.hpp"
class PhongMaterial : public Material {
public:
PhongMaterial(const glm::vec3& kd, const glm::vec3& ks, double shininess);
virtual ~PhongMaterial();
// private:
glm::vec3 m_kd;
glm::vec3 m_ks;
double m_shininess;
};
| 291 | 119 |
/*
* Copyright (c) 2021 Nuovation System Designs, LLC
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* This file implements a unit test for Log::Utilities::Memory
*/
#include <LogUtilities/LogFilterAlways.hpp>
#include <LogUtilities/LogFormatterPlain.hpp>
#include <LogUtilities/LogGlobals.hpp>
#include <LogUtilities/LogIndenterNone.hpp>
#include <LogUtilities/LogLogger.hpp>
#include <LogUtilities/LogMemoryUtilities.hpp>
#include <LogUtilities/LogWriterDescriptor.hpp>
#include <ostream>
#include <regex>
#include <string>
#include <fcntl.h>
#include <limits.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <cppunit/TestAssert.h>
#include <cppunit/extensions/HelperMacros.h>
#include "TestLogUtilitiesBasis.hpp"
using namespace Nuovations;
using namespace std;
class TestMemoryLines
{
public:
TestMemoryLines(const char * inMemoryLines);
~TestMemoryLines(void) = default;
bool operator ==(const TestMemoryLines & inMemoryLines) const;
size_t size(void) const;
const std::string & operator ()(void) const;
std::string & operator ()(void);
std::ostream & operator <<(const TestMemoryLines & inMemoryLines) const;
private:
class MemoryLine
{
public:
MemoryLine(void);
bool operator ==(const MemoryLine & inMemoryLine) const;
bool operator !=(const MemoryLine & inMemoryLine) const;
MemoryLine & operator =(const MemoryLine & inMemoryLine);
MemoryLine operator ++(int inDummy);
public:
size_t mAddressPosition;
size_t mDataPosition;
size_t mNewlinePosition;
private:
friend class TestMemoryLines;
MemoryLine(const TestMemoryLines & inMemoryLines);
MemoryLine(const TestMemoryLines & inMemoryLines,
const size_t & inAddressPosition,
const size_t & inDataPosition,
const size_t & inNewlinePosition);
const TestMemoryLines * mTestMemoryLines;
};
MemoryLine begin(void) const;
MemoryLine end(void) const;
bool CompareAddress(const MemoryLine & inOurLine,
const TestMemoryLines & inTheirLines,
const MemoryLine & inTheirLine) const;
bool CompareData(const MemoryLine & inOurLine,
const TestMemoryLines & inTheirLines,
const MemoryLine & inTheirLine) const;
private:
std::string mMemoryLines;
};
class TestLogMemoryUtilities :
public TestLogUtilitiesBasis
{
CPPUNIT_TEST_SUITE(TestLogMemoryUtilities);
CPPUNIT_TEST(TestWithExplicitLoggerWithInvalidWidth);
CPPUNIT_TEST(TestWithExplicitLoggerWithDefaultIndentAndLevel);
CPPUNIT_TEST(TestWithExplicitLoggerWithDefaultIndentWithLevel);
CPPUNIT_TEST(TestWithExplicitLoggerWithIndentAndLevel);
CPPUNIT_TEST(TestWithImplicitLoggerWithInvalidWidth);
CPPUNIT_TEST(TestWithImplicitLoggerWithDefaultIndentAndLevel);
CPPUNIT_TEST(TestWithImplicitLoggerWithDefaultIndentWithLevel);
CPPUNIT_TEST(TestWithImplicitLoggerWithIndentAndLevel);
CPPUNIT_TEST_SUITE_END();
public:
void TestWithExplicitLoggerWithInvalidWidth(void);
void TestWithExplicitLoggerWithDefaultIndentAndLevel(void);
void TestWithExplicitLoggerWithDefaultIndentWithLevel(void);
void TestWithExplicitLoggerWithIndentAndLevel(void);
void TestWithImplicitLoggerWithInvalidWidth(void);
void TestWithImplicitLoggerWithDefaultIndentAndLevel(void);
void TestWithImplicitLoggerWithDefaultIndentWithLevel(void);
void TestWithImplicitLoggerWithIndentAndLevel(void);
private:
int CreateTemporaryFile(char * aPathBuffer);
void CheckResults(const char * aPathBuffer, const TestMemoryLines & aExpected);
static constexpr uint8_t kUint8x8s[8] =
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07
};
static constexpr uint8_t kUint32x8s[32] =
{
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f
};
static constexpr uint16_t kUint16s[16] =
{
0x3000, 0x3001, 0x3002, 0x3003,
0x3004, 0x3005, 0x3006, 0x3007,
0x3008, 0x3009, 0x300a, 0x300b,
0x300c, 0x300d, 0x300e, 0x300f
};
static constexpr uint32_t kUint32s[8] =
{
0x40000000, 0x40000001, 0x40000002, 0x40000003,
0x40000004, 0x40000005, 0x40000006, 0x40000007,
};
static constexpr uint64_t kUint64s[8] =
{
0x5000000000000000, 0x5000000000000001,
0x5000000000000002, 0x5000000000000003,
0x5000000000000004, 0x5000000000000005,
0x5000000000000006, 0x5000000000000007
};
static constexpr size_t kOffsets[2] = { 0, 3 };
static const TestMemoryLines kExpectedMemoryLines;
};
constexpr uint8_t TestLogMemoryUtilities ::kUint8x8s[];
constexpr uint8_t TestLogMemoryUtilities ::kUint32x8s[];
constexpr uint16_t TestLogMemoryUtilities ::kUint16s[];
constexpr uint32_t TestLogMemoryUtilities ::kUint32s[];
constexpr uint64_t TestLogMemoryUtilities ::kUint64s[];
constexpr size_t TestLogMemoryUtilities ::kOffsets[];
const TestMemoryLines TestLogMemoryUtilities ::kExpectedMemoryLines =
"<address>: 00 01 02 03 04 05 06 07 '................'\n"
"<address>: 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f '................'\n"
"<address>: 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f ' !\"#$%&'()*+,-./'\n"
"<address>: 00 30 01 30 02 30 03 30 04 30 05 30 06 30 07 30 '.0.0.0.0.0.0.0.0'\n"
"<address>: 00 00 00 40 01 00 00 40 '...@...@........'\n"
"<address>: 00 00 00 00 00 00 00 50 '.......P........'\n"
"<address>: 00 01 02 03 04 05 06 07 '................'\n"
"<address>: 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f '................'\n"
"<address>: 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f ' !\"#$%&'()*+,-./'\n"
"<address>: 3000 3001 3002 3003 3004 3005 3006 3007 '.0.0.0.0.0.0.0.0'\n"
"<address>: 3008 3009 300a 300b 300c 300d 300e 300f '.0.0.0.0.0.0.0.0'\n"
"<address>: 40000000 40000001 40000002 40000003 '...@...@...@...@'\n"
"<address>: 40000004 40000005 40000006 40000007 '...@...@...@...@'\n"
"<address>: 5000000000000000 5000000000000001 '.......P.......P'\n"
"<address>: 5000000000000002 5000000000000003 '.......P.......P'\n"
"<address>: 5000000000000004 5000000000000005 '.......P.......P'\n"
"<address>: 5000000000000006 5000000000000007 '.......P.......P'\n"
"<address>: 03 04 05 06 07 '................'\n"
"<address>: 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 '............. !\"'\n"
"<address>: 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f '#$%&'()*+,-./...'\n"
"<address>: 03 30 04 30 05 30 06 30 07 30 08 30 09 '.0.0.0.0.0.0....'\n"
"<address>: 03 00 00 40 04 '...@............'\n"
"<address>: 03 00 00 00 00 '................'\n"
"<address>: 03 04 05 06 07 '................'\n"
"<address>: 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 '............. !\"'\n"
"<address>: 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f '#$%&'()*+,-./...'\n"
"<address>: 3003 3004 3005 3006 3007 3008 3009 300a '.0.0.0.0.0.0.0.0'\n"
"<address>: 300b 300c 300d 300e 300f '.0.0.0.0.0......'\n"
"<address>: 40000003 40000004 40000005 40000006 '...@...@...@...@'\n"
"<address>: 40000007 '...@............'\n"
"<address>: 5000000000000003 5000000000000004 '.......P.......P'\n"
"<address>: 5000000000000005 5000000000000006 '.......P.......P'\n"
"<address>: 5000000000000007 '.......P........'\n";
TestMemoryLines :: TestMemoryLines(const char * inMemoryLines) :
mMemoryLines(inMemoryLines)
{
return;
}
TestMemoryLines :: MemoryLine :: MemoryLine(void) :
mAddressPosition(0),
mDataPosition(0),
mNewlinePosition(0),
mTestMemoryLines(nullptr)
{
return;
}
TestMemoryLines :: MemoryLine :: MemoryLine(const TestMemoryLines & inTestMemoryLines) :
mAddressPosition(0),
mDataPosition(0),
mNewlinePosition(0),
mTestMemoryLines(&inTestMemoryLines)
{
return;
}
TestMemoryLines :: MemoryLine :: MemoryLine(const TestMemoryLines & inTestMemoryLines,
const size_t & inAddressPosition,
const size_t & inDataPosition,
const size_t & inNewlinePosition) :
mAddressPosition(inAddressPosition),
mDataPosition(inDataPosition),
mNewlinePosition(inNewlinePosition),
mTestMemoryLines(&inTestMemoryLines)
{
return;
}
bool
TestMemoryLines :: MemoryLine ::operator ==(const MemoryLine & inMemoryLine) const
{
bool lRetval;
lRetval = ((mAddressPosition == inMemoryLine.mAddressPosition) &&
(mDataPosition == inMemoryLine.mDataPosition ) &&
(mNewlinePosition == inMemoryLine.mNewlinePosition) &&
(mTestMemoryLines == inMemoryLine.mTestMemoryLines));
return (lRetval);
}
bool
TestMemoryLines :: MemoryLine :: operator !=(const MemoryLine & inMemoryLine) const
{
return (!(*this == inMemoryLine));
}
TestMemoryLines::MemoryLine &
TestMemoryLines :: MemoryLine :: operator =(const MemoryLine & inMemoryLine)
{
mAddressPosition = inMemoryLine.mAddressPosition;
mDataPosition = inMemoryLine.mDataPosition;
mNewlinePosition = inMemoryLine.mNewlinePosition;
mTestMemoryLines = inMemoryLine.mTestMemoryLines;
return (*this);
}
TestMemoryLines::MemoryLine
TestMemoryLines :: MemoryLine :: operator ++(int inDummy)
{
static const char kColon = ':';
static const char kNewline = '\n';
const MemoryLine lCurrentLine = *this;
const size_t lNextAddressPosition = mNewlinePosition + 1;
(void)inDummy;
// When this has incremented past the last line, ALL of the data
// members should be set to string::npos. The find method covers
// that for data and newline. We have to manually handle it for
// the address.
mAddressPosition = ((lNextAddressPosition >= mTestMemoryLines->size()) ? string::npos : lNextAddressPosition);
mDataPosition = mTestMemoryLines->mMemoryLines.find(kColon, mAddressPosition);
mNewlinePosition = mTestMemoryLines->mMemoryLines.find(kNewline, mAddressPosition);
return (lCurrentLine);
}
TestMemoryLines::MemoryLine
TestMemoryLines :: begin(void) const
{
static const char kColon = ':';
static const char kNewline = '\n';
MemoryLine lMemoryLine(*this);
lMemoryLine.mAddressPosition = 0;
lMemoryLine.mDataPosition = mMemoryLines.find(kColon, lMemoryLine.mAddressPosition);
lMemoryLine.mNewlinePosition = mMemoryLines.find(kNewline, lMemoryLine.mAddressPosition);
// If we found no data and no newline, then the lines are either
// malformed or we are at the end. Regardless, return the end
// iterator. Otherwise, return the start iterator.
if ((lMemoryLine.mDataPosition == string::npos) &&
(lMemoryLine.mNewlinePosition == string::npos)) {
return (end());
} else {
return (lMemoryLine);
}
}
TestMemoryLines::MemoryLine
TestMemoryLines :: end(void) const
{
const MemoryLine kLastMemoryLine(*this,
string::npos,
string::npos,
string::npos);
return (kLastMemoryLine);
}
bool
TestMemoryLines :: CompareAddress(const MemoryLine & inOurLine,
const TestMemoryLines & inTheirLines,
const MemoryLine & inTheirLine) const
{
const auto ourAddressIteratorBegin = mMemoryLines.cbegin() + static_cast<string::difference_type>(inOurLine.mAddressPosition);
const auto ourAddressIteratorEnd = mMemoryLines.cbegin() + static_cast<string::difference_type>(inOurLine.mDataPosition);
const auto theirAddressIteratorBegin = inTheirLines.mMemoryLines.cbegin() + static_cast<string::difference_type>(inTheirLine.mAddressPosition);
const auto theirAddressIteratorEnd = inTheirLines.mMemoryLines.cbegin() + static_cast<string::difference_type>(inTheirLine.mDataPosition);
const regex lRegex("(<address>|0x[[:xdigit:]]{4,16})");
bool lRetval = true;
if (!regex_match(ourAddressIteratorBegin, ourAddressIteratorEnd, lRegex) ||
!regex_match(theirAddressIteratorBegin, theirAddressIteratorEnd, lRegex)) {
lRetval = false;
}
return (lRetval);
}
bool
TestMemoryLines :: CompareData(const MemoryLine & inOurLine,
const TestMemoryLines & inTheirLines,
const MemoryLine & inTheirLine) const
{
const size_t ourDataLength = inOurLine.mNewlinePosition - inOurLine.mDataPosition;
const size_t theirDataLength = inTheirLine.mNewlinePosition - inTheirLine.mDataPosition;
int lCompare;
lCompare = mMemoryLines.compare(inOurLine.mDataPosition,
ourDataLength,
inTheirLines.mMemoryLines,
inTheirLine.mDataPosition,
theirDataLength);
return (lCompare == 0);
}
bool
TestMemoryLines :: operator ==(const TestMemoryLines & inTheirLines) const
{
MemoryLine lOurLine;
MemoryLine lTheirLine;
bool lRetval = true;
// Walk through each line, ours and theirs, comparing the address
// portion for equivalence and comparing the data portion for
// equality.
lOurLine = begin();
lTheirLine = inTheirLines.begin();
while (lRetval) {
const bool lOurEnd = (lOurLine == end());
const bool lTheirEnd = (lTheirLine == inTheirLines.end());
// If we are at our end but not theirs or vice versa, then we
// have a line number mismatch and the lines, collectively are
// not equivalent.
if ((lOurEnd && !lTheirEnd) || (!lOurEnd && lTheirEnd)) {
lRetval = false;
break;
}
if (lOurEnd && lTheirEnd) {
break;
}
// Check the address and the data portion
lRetval = (CompareAddress(lOurLine, inTheirLines, lTheirLine) &&
CompareData(lOurLine, inTheirLines, lTheirLine));
// Get our and their next line
lOurLine++;
lTheirLine++;
}
return (lRetval);
}
size_t
TestMemoryLines :: size(void) const
{
return (mMemoryLines.size());
}
const std::string &
TestMemoryLines :: operator ()(void) const
{
return (mMemoryLines);
}
std::string &
TestMemoryLines :: operator ()(void)
{
return (mMemoryLines);
}
static std::ostream &
operator <<(std::ostream & inStream, const TestMemoryLines & inMemoryLines)
{
const std::string & lString = (const std::string &)(inMemoryLines);
inStream << lString;
return (inStream);
}
namespace Detail
{
template <typename T, size_t N>
constexpr size_t
elementsof(const T (&)[N])
{
return (N);
}
}; // namespace Detail
CPPUNIT_TEST_SUITE_REGISTRATION(TestLogMemoryUtilities);
void
TestLogMemoryUtilities :: TestWithExplicitLoggerWithInvalidWidth(void)
{
Log::Filter::Always lAlwaysFilter;
Log::Indenter::None lNoneIndenter;
Log::Formatter::Plain lPlainFormatter;
char lPathBuffer[PATH_MAX];
int lDescriptor;
lDescriptor = CreateTemporaryFile(lPathBuffer);
CPPUNIT_ASSERT(lDescriptor > 0);
{
Log::Writer::Descriptor lDescriptorWriter(lDescriptor);
Log::Logger lLogger(lAlwaysFilter,
lNoneIndenter,
lPlainFormatter,
lDescriptorWriter);
for (auto lOffset : kOffsets) {
static constexpr unsigned int kWidth = 3;
// Default indent and level
Log::Utilities::Memory::Write(lLogger, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset, kWidth);
Log::Utilities::Memory::Write(lLogger, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset, kWidth);
Log::Utilities::Memory::Write(lLogger, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset, kWidth);
Log::Utilities::Memory::Write(lLogger, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset, kWidth);
Log::Utilities::Memory::Write(lLogger, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset, kWidth);
}
}
close(lDescriptor);
CheckResults(lPathBuffer, "");
}
void
TestLogMemoryUtilities :: TestWithExplicitLoggerWithDefaultIndentAndLevel(void)
{
Log::Filter::Always lAlwaysFilter;
Log::Indenter::None lNoneIndenter;
Log::Formatter::Plain lPlainFormatter;
char lPathBuffer[PATH_MAX];
int lDescriptor;
lDescriptor = CreateTemporaryFile(lPathBuffer);
CPPUNIT_ASSERT(lDescriptor > 0);
{
Log::Writer::Descriptor lDescriptorWriter(lDescriptor);
Log::Logger lLogger(lAlwaysFilter,
lNoneIndenter,
lPlainFormatter,
lDescriptorWriter);
for (auto lOffset : kOffsets) {
// Default indent, level, and width
Log::Utilities::Memory::Write(lLogger, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset);
Log::Utilities::Memory::Write(lLogger, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset);
Log::Utilities::Memory::Write(lLogger, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset);
Log::Utilities::Memory::Write(lLogger, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset);
Log::Utilities::Memory::Write(lLogger, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset);
// Default indent and level
Log::Utilities::Memory::Write(lLogger, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset, sizeof (kUint8x8s[lOffset]));
Log::Utilities::Memory::Write(lLogger, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset, sizeof (kUint32x8s[lOffset]));
Log::Utilities::Memory::Write(lLogger, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset, sizeof (kUint16s[lOffset]));
Log::Utilities::Memory::Write(lLogger, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset, sizeof (kUint32s[lOffset]));
Log::Utilities::Memory::Write(lLogger, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset, sizeof (kUint64s[lOffset]));
}
}
close(lDescriptor);
CheckResults(lPathBuffer, kExpectedMemoryLines);
}
void
TestLogMemoryUtilities :: TestWithExplicitLoggerWithDefaultIndentWithLevel(void)
{
Log::Filter::Always lAlwaysFilter;
Log::Indenter::None lNoneIndenter;
Log::Formatter::Plain lPlainFormatter;
char lPathBuffer[PATH_MAX];
int lDescriptor;
lDescriptor = CreateTemporaryFile(lPathBuffer);
CPPUNIT_ASSERT(lDescriptor > 0);
{
const Log::Level kLevel = 0;
Log::Writer::Descriptor lDescriptorWriter(lDescriptor);
Log::Logger lLogger(lAlwaysFilter,
lNoneIndenter,
lPlainFormatter,
lDescriptorWriter);
for (auto lOffset : kOffsets) {
// Default indent with level and default width
Log::Utilities::Memory::Write(lLogger, kLevel, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset);
Log::Utilities::Memory::Write(lLogger, kLevel, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset);
Log::Utilities::Memory::Write(lLogger, kLevel, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset);
Log::Utilities::Memory::Write(lLogger, kLevel, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset);
Log::Utilities::Memory::Write(lLogger, kLevel, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset);
// Default indent with level
Log::Utilities::Memory::Write(lLogger, kLevel, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset, sizeof (kUint8x8s[lOffset]));
Log::Utilities::Memory::Write(lLogger, kLevel, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset, sizeof (kUint32x8s[lOffset]));
Log::Utilities::Memory::Write(lLogger, kLevel, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset, sizeof (kUint16s[lOffset]));
Log::Utilities::Memory::Write(lLogger, kLevel, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset, sizeof (kUint32s[lOffset]));
Log::Utilities::Memory::Write(lLogger, kLevel, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset, sizeof (kUint64s[lOffset]));
}
}
close(lDescriptor);
CheckResults(lPathBuffer, kExpectedMemoryLines);
}
void
TestLogMemoryUtilities :: TestWithExplicitLoggerWithIndentAndLevel(void)
{
Log::Filter::Always lAlwaysFilter;
Log::Indenter::None lNoneIndenter;
Log::Formatter::Plain lPlainFormatter;
char lPathBuffer[PATH_MAX];
int lDescriptor;
lDescriptor = CreateTemporaryFile(lPathBuffer);
CPPUNIT_ASSERT(lDescriptor > 0);
{
const Log::Indent kIndent = 0;
const Log::Level kLevel = 0;
Log::Writer::Descriptor lDescriptorWriter(lDescriptor);
Log::Logger lLogger(lAlwaysFilter,
lNoneIndenter,
lPlainFormatter,
lDescriptorWriter);
for (auto lOffset : kOffsets) {
// With indent and level and default width
Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset);
Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset);
Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset);
Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset);
Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset);
// With indent and level
Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset, sizeof (kUint8x8s[lOffset]));
Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset, sizeof (kUint32x8s[lOffset]));
Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset, sizeof (kUint16s[lOffset]));
Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset, sizeof (kUint32s[lOffset]));
Log::Utilities::Memory::Write(lLogger, kIndent, kLevel, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset, sizeof (kUint64s[lOffset]));
}
}
close(lDescriptor);
CheckResults(lPathBuffer, kExpectedMemoryLines);
}
void
TestLogMemoryUtilities :: TestWithImplicitLoggerWithInvalidWidth(void)
{
Log::Filter::Always lAlwaysFilter;
Log::Indenter::None lNoneIndenter;
Log::Formatter::Plain lPlainFormatter;
char lPathBuffer[PATH_MAX];
int lDescriptor;
lDescriptor = CreateTemporaryFile(lPathBuffer);
CPPUNIT_ASSERT(lDescriptor > 0);
{
Log::Writer::Descriptor lDescriptorWriter(lDescriptor);
Log::Debug().SetFilter(lAlwaysFilter);
Log::Debug().SetIndenter(lNoneIndenter);
Log::Debug().SetFormatter(lPlainFormatter);
Log::Debug().SetWriter(lDescriptorWriter);
for (auto lOffset : kOffsets) {
static constexpr unsigned int kWidth = 3;
// Default indent and level
Log::Utilities::Memory::Write(&kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset, kWidth);
Log::Utilities::Memory::Write(&kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset, kWidth);
Log::Utilities::Memory::Write(&kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset, kWidth);
Log::Utilities::Memory::Write(&kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset, kWidth);
Log::Utilities::Memory::Write(&kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset, kWidth);
}
}
close(lDescriptor);
CheckResults(lPathBuffer, "");
}
void
TestLogMemoryUtilities :: TestWithImplicitLoggerWithDefaultIndentAndLevel(void)
{
Log::Filter::Always lAlwaysFilter;
Log::Indenter::None lNoneIndenter;
Log::Formatter::Plain lPlainFormatter;
char lPathBuffer[PATH_MAX];
int lDescriptor;
lDescriptor = CreateTemporaryFile(lPathBuffer);
CPPUNIT_ASSERT(lDescriptor > 0);
{
Log::Writer::Descriptor lDescriptorWriter(lDescriptor);
Log::Debug().SetFilter(lAlwaysFilter);
Log::Debug().SetIndenter(lNoneIndenter);
Log::Debug().SetFormatter(lPlainFormatter);
Log::Debug().SetWriter(lDescriptorWriter);
for (auto lOffset : kOffsets) {
// Default indent, level, and width
Log::Utilities::Memory::Write(&kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset);
Log::Utilities::Memory::Write(&kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset);
Log::Utilities::Memory::Write(&kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset);
Log::Utilities::Memory::Write(&kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset);
Log::Utilities::Memory::Write(&kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset);
// Default indent and level
Log::Utilities::Memory::Write(&kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset, sizeof (kUint8x8s[lOffset]));
Log::Utilities::Memory::Write(&kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset, sizeof (kUint32x8s[lOffset]));
Log::Utilities::Memory::Write(&kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset, sizeof (kUint16s[lOffset]));
Log::Utilities::Memory::Write(&kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset, sizeof (kUint32s[lOffset]));
Log::Utilities::Memory::Write(&kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset, sizeof (kUint64s[lOffset]));
}
}
close(lDescriptor);
CheckResults(lPathBuffer, kExpectedMemoryLines);
}
void
TestLogMemoryUtilities :: TestWithImplicitLoggerWithDefaultIndentWithLevel(void)
{
Log::Filter::Always lAlwaysFilter;
Log::Indenter::None lNoneIndenter;
Log::Formatter::Plain lPlainFormatter;
char lPathBuffer[PATH_MAX];
int lDescriptor;
lDescriptor = CreateTemporaryFile(lPathBuffer);
CPPUNIT_ASSERT(lDescriptor > 0);
{
const Log::Level kLevel = 0;
Log::Writer::Descriptor lDescriptorWriter(lDescriptor);
Log::Debug().SetFilter(lAlwaysFilter);
Log::Debug().SetIndenter(lNoneIndenter);
Log::Debug().SetFormatter(lPlainFormatter);
Log::Debug().SetWriter(lDescriptorWriter);
for (auto lOffset : kOffsets) {
// Default indent with level and default width
Log::Utilities::Memory::Write(kLevel, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset);
Log::Utilities::Memory::Write(kLevel, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset);
Log::Utilities::Memory::Write(kLevel, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset);
Log::Utilities::Memory::Write(kLevel, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset);
Log::Utilities::Memory::Write(kLevel, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset);
// Default indent with level
Log::Utilities::Memory::Write(kLevel, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset, sizeof (kUint8x8s[lOffset]));
Log::Utilities::Memory::Write(kLevel, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset, sizeof (kUint32x8s[lOffset]));
Log::Utilities::Memory::Write(kLevel, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset, sizeof (kUint16s[lOffset]));
Log::Utilities::Memory::Write(kLevel, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset, sizeof (kUint32s[lOffset]));
Log::Utilities::Memory::Write(kLevel, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset, sizeof (kUint64s[lOffset]));
}
}
close(lDescriptor);
CheckResults(lPathBuffer, kExpectedMemoryLines);
}
void
TestLogMemoryUtilities :: TestWithImplicitLoggerWithIndentAndLevel(void)
{
Log::Filter::Always lAlwaysFilter;
Log::Indenter::None lNoneIndenter;
Log::Formatter::Plain lPlainFormatter;
char lPathBuffer[PATH_MAX];
int lDescriptor;
lDescriptor = CreateTemporaryFile(lPathBuffer);
CPPUNIT_ASSERT(lDescriptor > 0);
{
const Log::Indent kIndent = 0;
const Log::Level kLevel = 0;
Log::Writer::Descriptor lDescriptorWriter(lDescriptor);
Log::Debug().SetFilter(lAlwaysFilter);
Log::Debug().SetIndenter(lNoneIndenter);
Log::Debug().SetFormatter(lPlainFormatter);
Log::Debug().SetWriter(lDescriptorWriter);
for (auto lOffset : kOffsets) {
// With indent and level and default width
Log::Utilities::Memory::Write(kIndent, kLevel, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset);
Log::Utilities::Memory::Write(kIndent, kLevel, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset);
Log::Utilities::Memory::Write(kIndent, kLevel, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset);
Log::Utilities::Memory::Write(kIndent, kLevel, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset);
Log::Utilities::Memory::Write(kIndent, kLevel, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset);
// With indent and level
Log::Utilities::Memory::Write(kIndent, kLevel, &kUint8x8s[lOffset], Detail::elementsof(kUint8x8s) - lOffset, sizeof (kUint8x8s[lOffset]));
Log::Utilities::Memory::Write(kIndent, kLevel, &kUint32x8s[lOffset], Detail::elementsof(kUint32x8s) - lOffset, sizeof (kUint32x8s[lOffset]));
Log::Utilities::Memory::Write(kIndent, kLevel, &kUint16s[lOffset], Detail::elementsof(kUint16s) - lOffset, sizeof (kUint16s[lOffset]));
Log::Utilities::Memory::Write(kIndent, kLevel, &kUint32s[lOffset], Detail::elementsof(kUint32s) - lOffset, sizeof (kUint32s[lOffset]));
Log::Utilities::Memory::Write(kIndent, kLevel, &kUint64s[lOffset], Detail::elementsof(kUint64s) - lOffset, sizeof (kUint64s[lOffset]));
}
}
close(lDescriptor);
CheckResults(lPathBuffer, kExpectedMemoryLines);
}
int
TestLogMemoryUtilities :: CreateTemporaryFile(char * aPathBuffer)
{
static const char * const kTestName = "memory-utilities";
int lStatus;
lStatus = CreateTemporaryFileFromName(kTestName, aPathBuffer);
return (lStatus);
}
void
TestLogMemoryUtilities :: CheckResults(const char * aPathBuffer,
const TestMemoryLines & aExpected)
{
struct stat lStat;
int lStatus;
int lDescriptor;
char * lBuffer;
ssize_t lResidual;
lStatus = stat(aPathBuffer, &lStat);
CPPUNIT_ASSERT(lStatus == 0);
lDescriptor = open(aPathBuffer, O_RDONLY);
CPPUNIT_ASSERT(lDescriptor > 0);
lBuffer = new char[static_cast<size_t>(lStat.st_size) + 1];
CPPUNIT_ASSERT(lBuffer != NULL);
lResidual = read(lDescriptor, &lBuffer[0], static_cast<size_t>(lStat.st_size));
CPPUNIT_ASSERT_EQUAL(lStat.st_size, static_cast<off_t>(lResidual));
close(lDescriptor);
lBuffer[static_cast<size_t>(lStat.st_size)] = '\0';
CPPUNIT_ASSERT_EQUAL(aExpected, TestMemoryLines(lBuffer));
delete [] lBuffer;
lStatus = unlink(aPathBuffer);
CPPUNIT_ASSERT(lStatus == 0);
}
| 34,309 | 12,369 |
#include "drape/texture_manager.hpp"
#include "drape/gl_functions.hpp"
#include "drape/font_texture.hpp"
#include "drape/symbols_texture.hpp"
#include "drape/static_texture.hpp"
#include "drape/stipple_pen_resource.hpp"
#include "drape/support_manager.hpp"
#include "drape/texture_of_colors.hpp"
#include "drape/tm_read_resources.hpp"
#include "drape/utils/glyph_usage_tracker.hpp"
#include "base/file_name_utils.hpp"
#include "base/stl_helpers.hpp"
#include <algorithm>
#include <cstdint>
#include <limits>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
namespace dp
{
namespace
{
uint32_t const kMaxTextureSize = 1024;
uint32_t const kStippleTextureWidth = 512; /// @todo Should be equal with kMaxStipplePenLength?
uint32_t const kMinStippleTextureHeight = 64;
uint32_t const kMinColorTextureSize = 32;
uint32_t const kGlyphsTextureSize = 1024;
size_t const kInvalidGlyphGroup = std::numeric_limits<size_t>::max();
// Reserved for elements like RuleDrawer or other LineShapes.
uint32_t const kReservedPatterns = 10;
size_t const kReservedColors = 20;
float const kGlyphAreaMultiplier = 1.2f;
float const kGlyphAreaCoverage = 0.9f;
std::string const kSymbolTextures[] = { "symbols" };
uint32_t const kDefaultSymbolsIndex = 0;
void MultilineTextToUniString(TextureManager::TMultilineText const & text, strings::UniString & outString)
{
size_t cnt = 0;
for (strings::UniString const & str : text)
cnt += str.size();
outString.clear();
outString.reserve(cnt);
for (strings::UniString const & str : text)
outString.append(str.begin(), str.end());
}
template <typename ToDo>
void ParseColorsList(std::string const & colorsFile, ToDo toDo)
{
ReaderStreamBuf buffer(GetPlatform().GetReader(colorsFile));
std::istream is(&buffer);
while (is.good())
{
uint32_t color;
is >> color;
toDo(dp::Extract(color));
}
}
m2::PointU StipplePenTextureSize(size_t patternsCount, uint32_t maxTextureSize)
{
uint32_t const sz = base::NextPowOf2(static_cast<uint32_t>(patternsCount) + kReservedPatterns);
// No problem if assert will fire here. Just pen texture will be 2x bigger :)
//ASSERT_LESS_OR_EQUAL(sz, kMinStippleTextureHeight, (patternsCount));
uint32_t const stippleTextureHeight = std::min(maxTextureSize, std::max(sz, kMinStippleTextureHeight));
return m2::PointU(kStippleTextureWidth, stippleTextureHeight);
}
m2::PointU ColorTextureSize(size_t colorsCount, uint32_t maxTextureSize)
{
uint32_t const sz = static_cast<uint32_t>(floor(sqrt(colorsCount + kReservedColors)));
// No problem if assert will fire here. Just color texture will be 2x bigger :)
ASSERT_LESS_OR_EQUAL(sz, kMinColorTextureSize, (colorsCount));
uint32_t colorTextureSize = std::max(base::NextPowOf2(sz), kMinColorTextureSize);
colorTextureSize *= ColorTexture::GetColorSizeInPixels();
colorTextureSize = std::min(maxTextureSize, colorTextureSize);
return m2::PointU(colorTextureSize, colorTextureSize);
}
} // namespace
TextureManager::TextureManager(ref_ptr<GlyphGenerator> glyphGenerator)
: m_maxTextureSize(0)
, m_maxGlypsCount(0)
, m_glyphGenerator(glyphGenerator)
{
m_nothingToUpload.test_and_set();
}
TextureManager::BaseRegion::BaseRegion()
: m_info(nullptr)
, m_texture(nullptr)
{}
bool TextureManager::BaseRegion::IsValid() const
{
return m_info != nullptr && m_texture != nullptr;
}
void TextureManager::BaseRegion::SetResourceInfo(ref_ptr<Texture::ResourceInfo> info)
{
m_info = info;
}
void TextureManager::BaseRegion::SetTexture(ref_ptr<Texture> texture)
{
m_texture = texture;
}
m2::PointF TextureManager::BaseRegion::GetPixelSize() const
{
if (!IsValid())
return m2::PointF(0.0f, 0.0f);
m2::RectF const & texRect = m_info->GetTexRect();
return m2::PointF(texRect.SizeX() * m_texture->GetWidth(),
texRect.SizeY() * m_texture->GetHeight());
}
float TextureManager::BaseRegion::GetPixelHeight() const
{
if (!IsValid())
return 0.0f;
return m_info->GetTexRect().SizeY() * m_texture->GetHeight();
}
m2::RectF const & TextureManager::BaseRegion::GetTexRect() const
{
if (!IsValid())
{
static m2::RectF nilRect(0.0f, 0.0f, 0.0f, 0.0f);
return nilRect;
}
return m_info->GetTexRect();
}
float TextureManager::GlyphRegion::GetOffsetX() const
{
ASSERT(m_info->GetType() == Texture::ResourceType::Glyph, ());
return ref_ptr<GlyphInfo>(m_info)->GetMetrics().m_xOffset;
}
float TextureManager::GlyphRegion::GetOffsetY() const
{
ASSERT(m_info->GetType() == Texture::ResourceType::Glyph, ());
return ref_ptr<GlyphInfo>(m_info)->GetMetrics().m_yOffset;
}
float TextureManager::GlyphRegion::GetAdvanceX() const
{
ASSERT(m_info->GetType() == Texture::ResourceType::Glyph, ());
return ref_ptr<GlyphInfo>(m_info)->GetMetrics().m_xAdvance;
}
float TextureManager::GlyphRegion::GetAdvanceY() const
{
ASSERT(m_info->GetType() == Texture::ResourceType::Glyph, ());
return ref_ptr<GlyphInfo>(m_info)->GetMetrics().m_yAdvance;
}
m2::PointU TextureManager::StippleRegion::GetMaskPixelSize() const
{
ASSERT(m_info->GetType() == Texture::ResourceType::StipplePen, ());
return ref_ptr<StipplePenResourceInfo>(m_info)->GetMaskPixelSize();
}
//uint32_t TextureManager::StippleRegion::GetPatternPixelLength() const
//{
// ASSERT(m_info->GetType() == Texture::ResourceType::StipplePen, ());
// return ref_ptr<StipplePenResourceInfo>(m_info)->GetPatternPixelLength();
//}
void TextureManager::Release()
{
m_hybridGlyphGroups.clear();
m_symbolTextures.clear();
m_stipplePenTexture.reset();
m_colorTexture.reset();
m_trafficArrowTexture.reset();
m_hatchingTexture.reset();
m_smaaAreaTexture.reset();
m_smaaSearchTexture.reset();
m_glyphTextures.clear();
m_glyphManager.reset();
m_glyphGenerator->FinishGeneration();
m_isInitialized = false;
m_nothingToUpload.test_and_set();
}
bool TextureManager::UpdateDynamicTextures(ref_ptr<dp::GraphicsContext> context)
{
if (!HasAsyncRoutines() && m_nothingToUpload.test_and_set())
{
auto const apiVersion = context->GetApiVersion();
if (apiVersion == dp::ApiVersion::OpenGLES2 || apiVersion == dp::ApiVersion::OpenGLES3)
{
// For some reasons OpenGL can not update textures immediately.
// Here we use some timeout to prevent rendering frozening.
double const kUploadTimeoutInSeconds = 2.0;
return m_uploadTimer.ElapsedSeconds() < kUploadTimeoutInSeconds;
}
if (apiVersion == dp::ApiVersion::Metal || apiVersion == dp::ApiVersion::Vulkan)
return false;
CHECK(false, ("Unsupported API version."));
}
CHECK(m_isInitialized, ());
m_uploadTimer.Reset();
CHECK(m_colorTexture != nullptr, ());
m_colorTexture->UpdateState(context);
CHECK(m_stipplePenTexture != nullptr, ());
m_stipplePenTexture->UpdateState(context);
UpdateGlyphTextures(context);
CHECK(m_textureAllocator != nullptr, ());
m_textureAllocator->Flush();
return true;
}
void TextureManager::UpdateGlyphTextures(ref_ptr<dp::GraphicsContext> context)
{
std::lock_guard<std::mutex> lock(m_glyphTexturesMutex);
for (auto & texture : m_glyphTextures)
texture->UpdateState(context);
}
bool TextureManager::HasAsyncRoutines() const
{
CHECK(m_glyphGenerator != nullptr, ());
return !m_glyphGenerator->IsSuspended();
}
ref_ptr<Texture> TextureManager::AllocateGlyphTexture()
{
std::lock_guard<std::mutex> lock(m_glyphTexturesMutex);
m2::PointU size(kGlyphsTextureSize, kGlyphsTextureSize);
m_glyphTextures.push_back(make_unique_dp<FontTexture>(size, make_ref(m_glyphManager),
m_glyphGenerator,
make_ref(m_textureAllocator)));
return make_ref(m_glyphTextures.back());
}
void TextureManager::GetRegionBase(ref_ptr<Texture> tex, TextureManager::BaseRegion & region,
Texture::Key const & key)
{
bool isNew = false;
region.SetResourceInfo(tex != nullptr ? tex->FindResource(key, isNew) : nullptr);
region.SetTexture(tex);
ASSERT(region.IsValid(), ());
if (isNew)
m_nothingToUpload.clear();
}
void TextureManager::GetGlyphsRegions(ref_ptr<FontTexture> tex, strings::UniString const & text,
int fixedHeight, TGlyphsBuffer & regions)
{
ASSERT(tex != nullptr, ());
std::vector<GlyphKey> keys;
keys.reserve(text.size());
for (auto const & c : text)
keys.emplace_back(GlyphKey(c, fixedHeight));
bool hasNew = false;
auto resourcesInfo = tex->FindResources(keys, hasNew);
ASSERT_EQUAL(text.size(), resourcesInfo.size(), ());
regions.reserve(resourcesInfo.size());
for (auto const & info : resourcesInfo)
{
GlyphRegion reg;
reg.SetResourceInfo(info);
reg.SetTexture(tex);
ASSERT(reg.IsValid(), ());
regions.push_back(std::move(reg));
}
if (hasNew)
m_nothingToUpload.clear();
}
uint32_t TextureManager::GetNumberOfUnfoundCharacters(strings::UniString const & text, int fixedHeight,
HybridGlyphGroup const & group) const
{
uint32_t cnt = 0;
for (auto const & c : text)
{
if (group.m_glyphs.find(std::make_pair(c, fixedHeight)) == group.m_glyphs.end())
cnt++;
}
return cnt;
}
void TextureManager::MarkCharactersUsage(strings::UniString const & text, int fixedHeight,
HybridGlyphGroup & group)
{
for (auto const & c : text)
group.m_glyphs.emplace(std::make_pair(c, fixedHeight));
}
size_t TextureManager::FindHybridGlyphsGroup(strings::UniString const & text, int fixedHeight)
{
if (m_hybridGlyphGroups.empty())
{
m_hybridGlyphGroups.push_back(HybridGlyphGroup());
return 0;
}
HybridGlyphGroup & group = m_hybridGlyphGroups.back();
bool hasEnoughSpace = true;
if (group.m_texture != nullptr)
hasEnoughSpace = group.m_texture->HasEnoughSpace(static_cast<uint32_t>(text.size()));
// If we have got the only hybrid texture (in most cases it is)
// we can omit checking of glyphs usage.
if (hasEnoughSpace)
{
size_t const glyphsCount = group.m_glyphs.size() + text.size();
if (m_hybridGlyphGroups.size() == 1 && glyphsCount < m_maxGlypsCount)
return 0;
}
// Looking for a hybrid texture which contains text entirely.
for (size_t i = 0; i < m_hybridGlyphGroups.size() - 1; i++)
{
if (GetNumberOfUnfoundCharacters(text, fixedHeight, m_hybridGlyphGroups[i]) == 0)
return i;
}
// Check if we can contain text in the last hybrid texture.
uint32_t const unfoundChars = GetNumberOfUnfoundCharacters(text, fixedHeight, group);
uint32_t const newCharsCount = static_cast<uint32_t>(group.m_glyphs.size()) + unfoundChars;
if (newCharsCount >= m_maxGlypsCount || !group.m_texture->HasEnoughSpace(unfoundChars))
m_hybridGlyphGroups.push_back(HybridGlyphGroup());
return m_hybridGlyphGroups.size() - 1;
}
size_t TextureManager::FindHybridGlyphsGroup(TMultilineText const & text, int fixedHeight)
{
strings::UniString combinedString;
MultilineTextToUniString(text, combinedString);
return FindHybridGlyphsGroup(combinedString, fixedHeight);
}
void TextureManager::Init(ref_ptr<dp::GraphicsContext> context, Params const & params)
{
CHECK(!m_isInitialized, ());
m_resPostfix = params.m_resPostfix;
m_textureAllocator = CreateAllocator(context);
m_maxTextureSize = std::min(kMaxTextureSize, dp::SupportManager::Instance().GetMaxTextureSize());
auto const apiVersion = context->GetApiVersion();
if (apiVersion == dp::ApiVersion::OpenGLES2 || apiVersion == dp::ApiVersion::OpenGLES3)
GLFunctions::glPixelStore(gl_const::GLUnpackAlignment, 1);
// Initialize symbols.
for (auto const & texName : kSymbolTextures)
{
m_symbolTextures.push_back(make_unique_dp<SymbolsTexture>(context, m_resPostfix, texName,
make_ref(m_textureAllocator)));
}
// Initialize static textures.
m_trafficArrowTexture = make_unique_dp<StaticTexture>(context, "traffic-arrow", m_resPostfix,
dp::TextureFormat::RGBA8, make_ref(m_textureAllocator));
m_hatchingTexture = make_unique_dp<StaticTexture>(context, "area-hatching", m_resPostfix,
dp::TextureFormat::RGBA8, make_ref(m_textureAllocator));
// SMAA is not supported on OpenGL ES2.
if (apiVersion != dp::ApiVersion::OpenGLES2)
{
m_smaaAreaTexture = make_unique_dp<StaticTexture>(context, "smaa-area", StaticTexture::kDefaultResource,
dp::TextureFormat::RedGreen, make_ref(m_textureAllocator));
m_smaaSearchTexture = make_unique_dp<StaticTexture>(context, "smaa-search", StaticTexture::kDefaultResource,
dp::TextureFormat::Alpha, make_ref(m_textureAllocator));
}
// Initialize patterns (reserved ./data/patterns.txt lines count).
std::set<PenPatternT> patterns;
double const visualScale = params.m_visualScale;
uint32_t rowsCount = 0;
impl::ParsePatternsList(params.m_patterns, [&](buffer_vector<double, 8> const & pattern)
{
PenPatternT toAdd;
for (double d : pattern)
toAdd.push_back(impl::PatternFloat2Pixel(d * visualScale));
if (!patterns.insert(toAdd).second)
return;
if (IsTrianglePattern(toAdd))
{
rowsCount = rowsCount + toAdd[2] + toAdd[3];
}
else
{
ASSERT_EQUAL(toAdd.size(), 2, ());
++rowsCount;
}
});
m_stipplePenTexture = make_unique_dp<StipplePenTexture>(StipplePenTextureSize(rowsCount, m_maxTextureSize),
make_ref(m_textureAllocator));
LOG(LDEBUG, ("Patterns texture size =", m_stipplePenTexture->GetWidth(), m_stipplePenTexture->GetHeight()));
ref_ptr<StipplePenTexture> stipplePenTex = make_ref(m_stipplePenTexture);
for (auto const & p : patterns)
stipplePenTex->ReservePattern(p);
// Initialize colors (reserved ./data/colors.txt lines count).
std::vector<dp::Color> colors;
colors.reserve(512);
ParseColorsList(params.m_colors, [&colors](dp::Color const & color)
{
colors.push_back(color);
});
m_colorTexture = make_unique_dp<ColorTexture>(ColorTextureSize(colors.size(), m_maxTextureSize),
make_ref(m_textureAllocator));
LOG(LDEBUG, ("Colors texture size =", m_colorTexture->GetWidth(), m_colorTexture->GetHeight()));
ref_ptr<ColorTexture> colorTex = make_ref(m_colorTexture);
for (auto const & c : colors)
colorTex->ReserveColor(c);
// Initialize glyphs.
m_glyphManager = make_unique_dp<GlyphManager>(params.m_glyphMngParams);
uint32_t const textureSquare = kGlyphsTextureSize * kGlyphsTextureSize;
uint32_t const baseGlyphHeight =
static_cast<uint32_t>(params.m_glyphMngParams.m_baseGlyphHeight * kGlyphAreaMultiplier);
uint32_t const averageGlyphSquare = baseGlyphHeight * baseGlyphHeight;
m_maxGlypsCount = static_cast<uint32_t>(ceil(kGlyphAreaCoverage * textureSquare / averageGlyphSquare));
m_isInitialized = true;
m_nothingToUpload.clear();
}
void TextureManager::OnSwitchMapStyle(ref_ptr<dp::GraphicsContext> context)
{
CHECK(m_isInitialized, ());
// Here we need invalidate only textures which can be changed in map style switch.
// Now we update only symbol textures, if we need update other textures they must be added here.
// For Vulkan we use m_texturesToCleanup to defer textures destroying.
for (size_t i = 0; i < m_symbolTextures.size(); ++i)
{
ASSERT(m_symbolTextures[i] != nullptr, ());
ASSERT(dynamic_cast<SymbolsTexture *>(m_symbolTextures[i].get()) != nullptr, ());
ref_ptr<SymbolsTexture> symbolsTexture = make_ref(m_symbolTextures[i]);
if (context->GetApiVersion() != dp::ApiVersion::Vulkan)
symbolsTexture->Invalidate(context, m_resPostfix, make_ref(m_textureAllocator));
else
symbolsTexture->Invalidate(context, m_resPostfix, make_ref(m_textureAllocator), m_texturesToCleanup);
}
}
void TextureManager::GetTexturesToCleanup(std::vector<drape_ptr<HWTexture>> & textures)
{
CHECK(m_isInitialized, ());
std::swap(textures, m_texturesToCleanup);
}
void TextureManager::GetSymbolRegion(std::string const & symbolName, SymbolRegion & region)
{
CHECK(m_isInitialized, ());
for (size_t i = 0; i < m_symbolTextures.size(); ++i)
{
ASSERT(m_symbolTextures[i] != nullptr, ());
ref_ptr<SymbolsTexture> symbolsTexture = make_ref(m_symbolTextures[i]);
if (symbolsTexture->IsSymbolContained(symbolName))
{
GetRegionBase(symbolsTexture, region, SymbolsTexture::SymbolKey(symbolName));
region.SetTextureIndex(static_cast<uint32_t>(i));
return;
}
}
LOG(LWARNING, ("Detected using of unknown symbol ", symbolName));
}
bool TextureManager::HasSymbolRegion(std::string const & symbolName) const
{
CHECK(m_isInitialized, ());
for (size_t i = 0; i < m_symbolTextures.size(); ++i)
{
ASSERT(m_symbolTextures[i] != nullptr, ());
ref_ptr<SymbolsTexture> symbolsTexture = make_ref(m_symbolTextures[i]);
if (symbolsTexture->IsSymbolContained(symbolName))
return true;
}
return false;
}
void TextureManager::GetStippleRegion(PenPatternT const & pen, StippleRegion & region)
{
CHECK(m_isInitialized, ());
GetRegionBase(make_ref(m_stipplePenTexture), region, StipplePenKey(pen));
}
void TextureManager::GetColorRegion(Color const & color, ColorRegion & region)
{
CHECK(m_isInitialized, ());
GetRegionBase(make_ref(m_colorTexture), region, ColorKey(color));
}
void TextureManager::GetGlyphRegions(TMultilineText const & text, int fixedHeight,
TMultilineGlyphsBuffer & buffers)
{
std::lock_guard<std::mutex> lock(m_calcGlyphsMutex);
CalcGlyphRegions<TMultilineText, TMultilineGlyphsBuffer>(text, fixedHeight, buffers);
}
void TextureManager::GetGlyphRegions(strings::UniString const & text, int fixedHeight,
TGlyphsBuffer & regions)
{
std::lock_guard<std::mutex> lock(m_calcGlyphsMutex);
CalcGlyphRegions<strings::UniString, TGlyphsBuffer>(text, fixedHeight, regions);
}
uint32_t TextureManager::GetAbsentGlyphsCount(ref_ptr<Texture> texture,
strings::UniString const & text,
int fixedHeight) const
{
if (texture == nullptr)
return 0;
ASSERT(dynamic_cast<FontTexture *>(texture.get()) != nullptr, ());
return static_cast<FontTexture *>(texture.get())->GetAbsentGlyphsCount(text, fixedHeight);
}
uint32_t TextureManager::GetAbsentGlyphsCount(ref_ptr<Texture> texture, TMultilineText const & text,
int fixedHeight) const
{
if (texture == nullptr)
return 0;
uint32_t count = 0;
for (size_t i = 0; i < text.size(); ++i)
count += GetAbsentGlyphsCount(texture, text[i], fixedHeight);
return count;
}
bool TextureManager::AreGlyphsReady(strings::UniString const & str, int fixedHeight) const
{
CHECK(m_isInitialized, ());
return m_glyphManager->AreGlyphsReady(str, fixedHeight);
}
ref_ptr<Texture> TextureManager::GetSymbolsTexture() const
{
CHECK(m_isInitialized, ());
ASSERT(!m_symbolTextures.empty(), ());
return make_ref(m_symbolTextures[kDefaultSymbolsIndex]);
}
ref_ptr<Texture> TextureManager::GetTrafficArrowTexture() const
{
CHECK(m_isInitialized, ());
return make_ref(m_trafficArrowTexture);
}
ref_ptr<Texture> TextureManager::GetHatchingTexture() const
{
CHECK(m_isInitialized, ());
return make_ref(m_hatchingTexture);
}
ref_ptr<Texture> TextureManager::GetSMAAAreaTexture() const
{
CHECK(m_isInitialized, ());
return make_ref(m_smaaAreaTexture);
}
ref_ptr<Texture> TextureManager::GetSMAASearchTexture() const
{
CHECK(m_isInitialized, ());
return make_ref(m_smaaSearchTexture);
}
constexpr size_t TextureManager::GetInvalidGlyphGroup()
{
return kInvalidGlyphGroup;
}
} // namespace dp
| 20,078 | 6,980 |
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include "fingerprint_test_fixtures.h"
namespace tests {
TEST_F(FingerprintDevice, isThereEnroll) {
ASSERT_TRUE(NULL != fp_device()->enroll)
<< "enroll() function is not implemented";
}
TEST_F(FingerprintDevice, isTherePreEnroll) {
ASSERT_TRUE(NULL != fp_device()->pre_enroll)
<< "pre_enroll() function is not implemented";
}
TEST_F(FingerprintDevice, isThereGetAuthenticatorId) {
ASSERT_TRUE(NULL != fp_device()->get_authenticator_id)
<< "get_authenticator_id() function is not implemented";
}
TEST_F(FingerprintDevice, isThereCancel) {
ASSERT_TRUE(NULL != fp_device()->cancel)
<< "cancel() function is not implemented";
}
TEST_F(FingerprintDevice, isThereRemove) {
ASSERT_TRUE(NULL != fp_device()->remove)
<< "remove() function is not implemented";
}
TEST_F(FingerprintDevice, isThereAuthenticate) {
ASSERT_TRUE(NULL != fp_device()->authenticate)
<< "authenticate() function is not implemented";
}
TEST_F(FingerprintDevice, isThereSetActiveGroup) {
ASSERT_TRUE(NULL != fp_device()->set_active_group)
<< "set_active_group() function is not implemented";
}
TEST_F(FingerprintDevice, isThereSetNotify) {
ASSERT_TRUE(NULL != fp_device()->set_notify)
<< "set_notify() function is not implemented";
}
} // namespace tests
| 1,971 | 631 |
/*******************************************************************************
# Copyright (C) 2021 Xilinx, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# *******************************************************************************/
#include "hls_stream.h"
#include "ap_int.h"
#include<iostream>
using namespace hls;
using namespace std;
void hostctrl( ap_uint<32> scenario,
ap_uint<32> len,
ap_uint<32> comm,
ap_uint<32> root_src_dst,
ap_uint<32> function,
ap_uint<32> msg_tag,
ap_uint<32> datapath_cfg,
ap_uint<32> compression_flags,
ap_uint<32> stream_flags,
ap_uint<64> addra,
ap_uint<64> addrb,
ap_uint<64> addrc,
stream<ap_uint<32>> &cmd,
stream<ap_uint<32>> &sts
);
int main(){
int nerrors = 0;
ap_uint<64> addra, addrb, addrc;
addra(31,0) = 5;
addra(63,32) = 7;
addrb(31,0) = 3;
addrb(63,32) = 9;
addrc(31,0) = 1;
addrc(63,32) = 6;
stream<ap_uint<32>> cmd;
stream<ap_uint<32>> sts;
sts.write(1);
hostctrl(0, 1, 2, 3, 4, 5, 6, 7, 8, addra, addrb, addrc, cmd, sts);
nerrors += (cmd.read() != 0);
nerrors += (cmd.read() != 1);
nerrors += (cmd.read() != 2);
nerrors += (cmd.read() != 3);
nerrors += (cmd.read() != 4);
nerrors += (cmd.read() != 5);
nerrors += (cmd.read() != 6);
nerrors += (cmd.read() != 7);
nerrors += (cmd.read() != 8);
nerrors += (cmd.read() != addra(31,0));
nerrors += (cmd.read() != addra(63,32));
nerrors += (cmd.read() != addrb(31,0));
nerrors += (cmd.read() != addrb(63,32));
nerrors += (cmd.read() != addrc(31,0));
nerrors += (cmd.read() != addrc(63,32));
return nerrors;
}
| 2,117 | 941 |
/*
* Snake game program using the SDL library
*
* @author J. Alvarez
*/
#include <iostream>
#include <cstring>
#include <vector>
#include <time.h>
#include <stdlib.h>
#include "Snake.hpp"
#include "Food.hpp"
#include "Wall.hpp"
#include "Screen.hpp"
#include "SDL2/SDL.h"
using namespace SnakeGame;
bool holdGame(Screen & screen, int millis) {
int startTime = SDL_GetTicks();
bool quit = false;
while (SDL_GetTicks() - startTime < millis && !quit) {
if(screen.processEvents() == Screen::Action::QUIT)
quit = true;
}
return quit;
}
bool pauseGame(Screen & screen, bool & pause) {
int startTime = SDL_GetTicks();
bool quit = false;
while (!quit && pause) {
int action = screen.processEvents();
switch (action) {
case Screen::Action::QUIT:
quit = true;
break;
case Screen::Action::PAUSE:
pause = false;
break;
}
}
return quit;
}
void resetLevel(Snake & snake, Food & food, bool & starting) {
snake.die();
snake.reset();
food = Food();
starting = true;
}
void createWalls(std::vector<Wall *> & walls) {
const int N_HORIZONTAL = Screen::S_WIDTH / Wall::S_WALL_WIDTH;
const int N_VERTICAL = Screen::S_HEIGHT / Wall::S_WALL_WIDTH - 2;
for (int i = 0; i < N_HORIZONTAL; i++) {
Wall * upperWall = new Wall(i * Wall::S_WALL_WIDTH, 0);
Wall * lowerWall = new Wall(i * Wall::S_WALL_WIDTH,
Screen::S_HEIGHT - 3 * Wall::S_WALL_WIDTH);
walls.push_back(upperWall);
walls.push_back(lowerWall);
}
for (int i = 1; i < N_VERTICAL - 1; i++) {
Wall * leftmostWall = new Wall(0, i * Wall::S_WALL_WIDTH);
Wall * rightmostWall = new Wall(Screen::S_WIDTH - Wall::S_WALL_WIDTH,
i * Wall::S_WALL_WIDTH);
walls.push_back(leftmostWall);
walls.push_back(rightmostWall);
}
}
void drawWalls(std::vector<Wall *> & walls, Screen & screen) {
for (auto wall: walls)
wall->draw(screen);
}
void freeWalls(std::vector<Wall *> & walls) {
for (auto wall: walls)
delete wall;
walls.clear();
}
int main(int argc, char ** argv) {
srand(time(NULL));
Screen screen;
Snake snake;
Food food;
std::vector<Wall *> walls;
createWalls(walls);
int score = 0;
if (!screen.init()) {
SDL_Log("Error initializing screen");
return -1;
}
bool quit = false;
bool starting = true;
bool pause = false;
while (!quit && snake.m_lives > 0) {
screen.clear();
snake.draw(screen);
food.draw(screen);
drawWalls(walls, screen);
screen.update(score, snake.m_lives, false);
if (starting) {
quit = holdGame(screen, 1500);
starting = false;
}
switch (screen.processEvents()) {
case Screen::Action::QUIT:
quit = true;
break;
case Screen::Action::PAUSE:
pause = true;
break;
case Screen::Action::MOVE_UP:
if(!snake.m_hasUpdated)
snake.updateDirection(Snake::Direction::UP);
break;
case Screen::Action::MOVE_DOWN:
if(!snake.m_hasUpdated)
snake.updateDirection(Snake::Direction::DOWN);
break;
case Screen::Action::MOVE_LEFT:
if(!snake.m_hasUpdated)
snake.updateDirection(Snake::Direction::LEFT);
break;
case Screen::Action::MOVE_RIGHT:
if(!snake.m_hasUpdated)
snake.updateDirection(Snake::Direction::RIGHT);
break;
}
if (pause)
quit = pauseGame(screen, pause);
int elapsed = SDL_GetTicks();
if (elapsed/10 % 6 == 0) {
if (!snake.move())
resetLevel(snake, food, starting);
else {
if (snake.collidesWith(food)) {
food = Food();
score += Food::S_VALUE;
snake.addSection();
}
for (auto wall: walls)
if (snake.collidesWith(* wall))
resetLevel(snake, food, starting);
for (int i = 1; i < snake.m_sections.size(); i++)
if (snake.collidesWith(* snake.m_sections[i]))
resetLevel(snake, food, starting);
}
}
if (snake.m_lives == 0) {
screen.clear();
screen.drawGameOver();
screen.update(score, snake.m_lives, true);
holdGame(screen, 3000);
}
}
freeWalls(walls);
screen.close();
return 0;
}
| 3,942 | 1,746 |
#ifndef MBGL_TEXT_TYPES
#define MBGL_TEXT_TYPES
#include <mbgl/util/vec.hpp>
#include <mbgl/util/rect.hpp>
#include <array>
#include <vector>
#include <boost/optional.hpp>
namespace mbgl {
typedef vec2<float> CollisionPoint;
typedef vec2<float> CollisionAnchor;
typedef std::array<float, 2> PlacementRange;
typedef float CollisionAngle;
typedef std::vector<CollisionAngle> CollisionAngles;
typedef std::array<CollisionAngle, 2> CollisionRange;
typedef std::vector<CollisionRange> CollisionList;
typedef std::array<CollisionPoint, 4> CollisionCorners;
struct CollisionRect {
CollisionPoint tl;
CollisionPoint br;
inline explicit CollisionRect() {}
inline explicit CollisionRect(CollisionPoint::Type ax,
CollisionPoint::Type ay,
CollisionPoint::Type bx,
CollisionPoint::Type by)
: tl(ax, ay), br(bx, by) {}
inline explicit CollisionRect(const CollisionPoint &tl,
const CollisionPoint &br)
: tl(tl), br(br) {}
};
// These are the glyph boxes that we want to have placed.
struct GlyphBox {
explicit GlyphBox() {}
explicit GlyphBox(const CollisionRect &box,
const CollisionAnchor &anchor,
float minScale,
float maxScale,
float padding)
: box(box), anchor(anchor), minScale(minScale), maxScale(maxScale), padding(padding) {}
explicit GlyphBox(const CollisionRect &box,
float minScale,
float padding)
: box(box), minScale(minScale), padding(padding) {}
CollisionRect box;
CollisionAnchor anchor;
float minScale = 0.0f;
float maxScale = std::numeric_limits<float>::infinity();
float padding = 0.0f;
boost::optional<CollisionRect> hBox;
};
typedef std::vector<GlyphBox> GlyphBoxes;
// TODO: Transform the vec2<float>s to vec2<int16_t> to save bytes
struct PlacedGlyph {
explicit PlacedGlyph(const vec2<float> &tl, const vec2<float> &tr,
const vec2<float> &bl, const vec2<float> &br,
const Rect<uint16_t> &tex, float angle, const vec2<float> &anchor,
float minScale, float maxScale)
: tl(tl),
tr(tr),
bl(bl),
br(br),
tex(tex),
angle(angle),
anchor(anchor),
minScale(minScale),
maxScale(maxScale) {}
vec2<float> tl, tr, bl, br;
Rect<uint16_t> tex;
float angle;
vec2<float> anchor;
float minScale, maxScale;
};
typedef std::vector<PlacedGlyph> PlacedGlyphs;
// These are the placed boxes contained in the rtree.
struct PlacementBox {
CollisionAnchor anchor;
CollisionRect box;
boost::optional<CollisionRect> hBox;
PlacementRange placementRange = {{0.0f, 0.0f}};
float placementScale = 0.0f;
float maxScale = std::numeric_limits<float>::infinity();
float padding = 0.0f;
};
struct PlacementProperty {
explicit PlacementProperty() {}
explicit PlacementProperty(float zoom, const PlacementRange &rotationRange)
: zoom(zoom), rotationRange(rotationRange) {}
inline operator bool() const {
return !std::isnan(zoom) && zoom != std::numeric_limits<float>::infinity() &&
rotationRange[0] != rotationRange[1];
}
float zoom = std::numeric_limits<float>::infinity();
PlacementRange rotationRange = {{0.0f, 0.0f}};
};
}
#endif
| 3,539 | 1,104 |
// Tip: Hold Left ALT + SHIFT while tapping or holding the arrow keys in order to select multiple columns and write on them at once.
// Also useful for copy & paste operations in which you need to copy a bunch of variable or function names and you can't afford the time of copying them one by one.
//
#include <stdio.h> // for printf()
#include <windows.h> // for interacting with Windows with GetAsyncKeyState()
// Define some functions to use from main(). These functions will contain our game code.
void setup () { printf("- setup() called.\n" ); }
void update () { printf("- update() called.\n" ); }
void draw () { printf("- draw() called.\n" ); }
int main () {
setup(); // Call setup()
int frameCounter = 0; // declare and initialize a variable of (int)eger type for keeping track of the number of frame since execution began.
while( true ) { // Execute code between braces while the condition inside () evaluates to true.
printf("Current frame number: %i\n", frameCounter); // Print the frame count.
update (); // Update frame.
draw (); // Render frame.
if(GetAsyncKeyState(VK_ESCAPE)) // Check for escape key pressed and execute code between braces if the condition between () evaluates to "true".
{
break; // Exit while() loop.
}
Sleep(50); // Wait 50 milliseconds then continue executing
frameCounter = frameCounter + 1; // increase our frame counter by 1
}
return 0; // Exit from the function returning an (int)eger.
}
| 1,550 | 520 |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Linq.Expressions.Interpreter.Instruction
#include "System/Linq/Expressions/Interpreter/Instruction.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Type
class Type;
}
// Forward declaring namespace: System::Linq::Expressions::Interpreter
namespace System::Linq::Expressions::Interpreter {
// Forward declaring type: InterpretedFrame
class InterpretedFrame;
}
// Completed forward declares
// Type namespace: System.Linq.Expressions.Interpreter
namespace System::Linq::Expressions::Interpreter {
// Forward declaring type: NewArrayInstruction
class NewArrayInstruction;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::System::Linq::Expressions::Interpreter::NewArrayInstruction);
DEFINE_IL2CPP_ARG_TYPE(::System::Linq::Expressions::Interpreter::NewArrayInstruction*, "System.Linq.Expressions.Interpreter", "NewArrayInstruction");
// Type namespace: System.Linq.Expressions.Interpreter
namespace System::Linq::Expressions::Interpreter {
// Size: 0x18
#pragma pack(push, 1)
// Autogenerated type: System.Linq.Expressions.Interpreter.NewArrayInstruction
// [TokenAttribute] Offset: FFFFFFFF
class NewArrayInstruction : public ::System::Linq::Expressions::Interpreter::Instruction {
public:
public:
// private readonly System.Type _elementType
// Size: 0x8
// Offset: 0x10
::System::Type* elementType;
// Field size check
static_assert(sizeof(::System::Type*) == 0x8);
public:
// Creating conversion operator: operator ::System::Type*
constexpr operator ::System::Type*() const noexcept {
return elementType;
}
// Get instance field reference: private readonly System.Type _elementType
[[deprecated("Use field access instead!")]] ::System::Type*& dyn__elementType();
// System.Void .ctor(System.Type elementType)
// Offset: 0xE941CC
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static NewArrayInstruction* New_ctor(::System::Type* elementType) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Expressions::Interpreter::NewArrayInstruction::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<NewArrayInstruction*, creationType>(elementType)));
}
// public override System.Int32 get_ConsumedStack()
// Offset: 0xE941F8
// Implemented from: System.Linq.Expressions.Interpreter.Instruction
// Base method: System.Int32 Instruction::get_ConsumedStack()
int get_ConsumedStack();
// public override System.Int32 get_ProducedStack()
// Offset: 0xE94200
// Implemented from: System.Linq.Expressions.Interpreter.Instruction
// Base method: System.Int32 Instruction::get_ProducedStack()
int get_ProducedStack();
// public override System.String get_InstructionName()
// Offset: 0xE94208
// Implemented from: System.Linq.Expressions.Interpreter.Instruction
// Base method: System.String Instruction::get_InstructionName()
::StringW get_InstructionName();
// public override System.Int32 Run(System.Linq.Expressions.Interpreter.InterpretedFrame frame)
// Offset: 0xE9424C
// Implemented from: System.Linq.Expressions.Interpreter.Instruction
// Base method: System.Int32 Instruction::Run(System.Linq.Expressions.Interpreter.InterpretedFrame frame)
int Run(::System::Linq::Expressions::Interpreter::InterpretedFrame* frame);
}; // System.Linq.Expressions.Interpreter.NewArrayInstruction
#pragma pack(pop)
static check_size<sizeof(NewArrayInstruction), 16 + sizeof(::System::Type*)> __System_Linq_Expressions_Interpreter_NewArrayInstructionSizeCheck;
static_assert(sizeof(NewArrayInstruction) == 0x18);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::NewArrayInstruction::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::NewArrayInstruction::get_ConsumedStack
// Il2CppName: get_ConsumedStack
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Linq::Expressions::Interpreter::NewArrayInstruction::*)()>(&System::Linq::Expressions::Interpreter::NewArrayInstruction::get_ConsumedStack)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::NewArrayInstruction*), "get_ConsumedStack", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::NewArrayInstruction::get_ProducedStack
// Il2CppName: get_ProducedStack
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Linq::Expressions::Interpreter::NewArrayInstruction::*)()>(&System::Linq::Expressions::Interpreter::NewArrayInstruction::get_ProducedStack)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::NewArrayInstruction*), "get_ProducedStack", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::NewArrayInstruction::get_InstructionName
// Il2CppName: get_InstructionName
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (System::Linq::Expressions::Interpreter::NewArrayInstruction::*)()>(&System::Linq::Expressions::Interpreter::NewArrayInstruction::get_InstructionName)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::NewArrayInstruction*), "get_InstructionName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::NewArrayInstruction::Run
// Il2CppName: Run
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Linq::Expressions::Interpreter::NewArrayInstruction::*)(::System::Linq::Expressions::Interpreter::InterpretedFrame*)>(&System::Linq::Expressions::Interpreter::NewArrayInstruction::Run)> {
static const MethodInfo* get() {
static auto* frame = &::il2cpp_utils::GetClassFromName("System.Linq.Expressions.Interpreter", "InterpretedFrame")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::NewArrayInstruction*), "Run", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{frame});
}
};
| 7,343 | 2,334 |
/*
* Phonetisaurus.cpp
*
Copyright (c) [2012-], Josef Robert Novak
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <stdio.h>
#include <string>
#include <fst/fstlib.h>
#include <iostream>
#include <set>
#include <algorithm>
#include "../g2p_train/FstPathFinder.hpp"
#include "Phonetisaurus.hpp"
using namespace fst;
Phonetisaurus::Phonetisaurus()
{
//Default constructor
}
Phonetisaurus::Phonetisaurus(const char *_g2pmodel_file)
{
//Base constructor. Load the clusters file, the models and setup shop.
eps = "<eps>";
sb = "<s>";
se = "</s>";
skip = "_";
skipSeqs.insert(eps);
skipSeqs.insert(sb);
skipSeqs.insert(se);
skipSeqs.insert(skip);
skipSeqs.insert("-");
g2pmodel = StdVectorFst::Read(_g2pmodel_file);
isyms = (SymbolTable *) g2pmodel->InputSymbols();
tie = isyms->Find(1); //The separator symbol is reserved for index 1
osyms = (SymbolTable *) g2pmodel->OutputSymbols();
loadClusters();
epsMapper = makeEpsMapper();
//We need make sure the g2pmodel is arcsorted
ILabelCompare<StdArc> icomp;
ArcSort(g2pmodel, icomp);
}
void
Phonetisaurus::loadClusters()
{
/*
Load the clusters file containing the list of
subsequences generated during multiple-to-multiple alignment
*/
for (size_t i = 2; i < isyms->NumSymbols(); i++) {
string sym = isyms->Find(i);
if (sym.find(tie) != string::npos) {
char *tmpstring = (char *) sym.c_str();
char *p = strtok(tmpstring, tie.c_str());
vector <string> cluster;
while (p) {
cluster.push_back(p);
p = strtok(NULL, tie.c_str());
}
clusters[cluster] = i;
}
}
return;
}
StdVectorFst
Phonetisaurus::makeEpsMapper()
{
/*
Generate a mapper FST to transform unwanted output symbols
to the epsilon symbol.
This can be used to remove unwanted symbols from the final
result, but in tests was 7x slower than manual removal
via the FstPathFinder object.
*/
StdVectorFst mfst;
mfst.AddState();
mfst.SetStart(0);
set <string>::iterator sit;
for (size_t i = 0; i < osyms->NumSymbols(); i++) {
string sym = osyms->Find(i);
sit = skipSeqs.find(sym);
if (sit != skipSeqs.end())
mfst.AddArc(0, StdArc(i, 0, 0, 0));
else
mfst.AddArc(0, StdArc(i, i, 0, 0));
}
mfst.SetFinal(0, 0);
ILabelCompare<StdArc> icomp;
ArcSort(&mfst, icomp);
mfst.SetInputSymbols(osyms);
mfst.SetOutputSymbols(osyms);
return mfst;
}
StdVectorFst
Phonetisaurus::entryToFSA(vector <string> entry)
{
/*
Transform an input spelling/pronunciation into an equivalent
FSA, adding extra arcs as needed to accomodate clusters.
*/
StdVectorFst efst;
efst.AddState();
efst.SetStart(0);
efst.AddState();
efst.AddArc(0, StdArc(isyms->Find(sb), isyms->Find(sb), 0, 1));
size_t i = 0;
//Build the basic FSA
for (i = 0; i < entry.size(); i++) {
efst.AddState();
string ch = entry[i];
efst.AddArc(i + 1,
StdArc(isyms->Find(ch), isyms->Find(ch), 0, i + 2));
if (i == 0)
continue;
}
//Add any cluster arcs
map<vector<string>,int>::iterator it_i;
for (it_i = clusters.begin(); it_i != clusters.end(); it_i++) {
vector<string>::iterator it_j;
vector<string>::iterator start = entry.begin();
vector<string> cluster = (*it_i).first;
while (it_j != entry.end()) {
it_j =
search(start, entry.end(), cluster.begin(), cluster.end());
if (it_j != entry.end()) {
efst.AddArc(it_j - entry.begin() + 1, StdArc((*it_i).second, //input symbol
(*it_i).second, //output symbol
0, //weight
it_j - entry.begin() + cluster.size() + 1 //destination state
));
start = it_j + cluster.size();
}
}
}
efst.AddState();
efst.AddArc(i + 1, StdArc(isyms->Find(se), isyms->Find(se), 0, i + 2));
efst.SetFinal(i + 2, 0);
efst.SetInputSymbols(isyms);
efst.SetOutputSymbols(isyms);
return efst;
}
vector<PathData> Phonetisaurus::phoneticize(vector <string> entry,
int nbest, int beam)
{
/*
Generate pronunciation/spelling hypotheses for an
input entry.
*/
StdVectorFst
result;
StdVectorFst
epsMapped;
StdVectorFst
shortest;
StdVectorFst
efst = entryToFSA(entry);
StdVectorFst
smbr;
Compose(efst, *g2pmodel, &result);
Project(&result, PROJECT_OUTPUT);
if (nbest > 1) {
//This is a cheesy hack.
ShortestPath(result, &shortest, beam);
}
else {
ShortestPath(result, &shortest, 1);
}
RmEpsilon(&shortest);
FstPathFinder
pathfinder(skipSeqs);
pathfinder.findAllStrings(shortest);
return pathfinder.paths;
}
void
printPath(PathData * path, string onepath, int k, ofstream * hypfile,
string correct, string word, bool output_cost)
{
if (word != "") {
if (k != 0) {
*hypfile << word << "(" << (k + 1) << ")" << " ";
}
else {
*hypfile << word << " ";
}
}
if (output_cost) {
if (path) {
*hypfile << path->pathcost << " " << onepath;
}
else {
*hypfile << "999.999 " << onepath;
}
}
else {
*hypfile << onepath;
}
if (correct != "")
*hypfile << " " << correct;
*hypfile << "\n";
}
bool
Phonetisaurus::printPaths(vector<PathData> paths, int nbest,
ofstream * hypfile, string correct, string word,
bool output_cost)
{
/*
Convenience function to print out a path vector.
Will print only the first N unique entries.
*/
set <string> seen;
set <string>::iterator sit;
int numseen = 0;
string onepath;
size_t k;
bool empty_path = true;
for (k = 0; k < paths.size(); k++) {
if (k >= nbest)
break;
size_t j;
for (j = 0; j < paths[k].path.size(); j++) {
if (paths[k].path[j] != tie)
replace(paths[k].path[j].begin(),
paths[k].path[j].end(), *tie.c_str(), ' ');
onepath += paths[k].path[j];
if (j != paths[k].path.size() - 1)
onepath += " ";
}
if (onepath == "") {
continue;
}
empty_path = false;
printPath(&paths[k], onepath, k, hypfile, correct, word,
output_cost);
onepath = "";
}
if (empty_path) {
if (k == 0) {
printPath(NULL, "-", 0, hypfile, correct, word, output_cost);
}
else {
printPath(&paths[0], "-", 0, hypfile, correct, word,
output_cost);
}
}
return empty_path;
}
| 8,454 | 2,988 |
#ifndef SETTINGS_DIALOG_HPP
#define SETTINGS_DIALOG_HPP
#include <QDialog>
#include "Settings.hpp"
#include "ui_settings.h"
class SettingsDialog : public QDialog {
Q_OBJECT
public:
SettingsDialog(QWidget *parent);
protected slots:
void editorPathChanged(QString);
void browseEditorPath();
private:
Ui::SettingsDialog mUi;
Settings mSettings;
};
#endif
| 417 | 146 |
#include <algorithm>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <QAbstractBarSeries>
#include <QApplication>
#include <QBoxLayout>
#include <QClipboard>
#include <QComboBox>
#include <QDateEdit>
#include <QDateTimeEdit>
#include <QDebug>
#include <QFileInfo>
#include <QFormLayout>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QIcon>
#include <QLabel>
#include <QLineEdit>
#include <QMainWindow>
#include <QMenu>
#include <QMenuBar>
#include <QObject>
#include <QProgressBar>
#include <QPushButton>
#include <QResource>
#include <QSlider>
#include <QString>
#include <QStringList>
#include <QTableWidget>
#include <QtCharts>
#include <QtCore>
#include <QTextEdit>
#include <QTextStream>
#include <QtGui>
#include <QTimeEdit>
#include <QtWidgets/QToolBar>
#include <QVBoxLayout>
#include <QWidget>
#include <sstream>
#include <string>
#include <tuple>
#include <vector>
#pragma once
| 934 | 341 |
// Copyright (C) 2017-2018 Jonathan Müller <jonathanmueller.dev@gmail.com>
// This file is subject to the license terms in the LICENSE file
// found in the top-level directory of this distribution.
#include <cppast/cpp_friend.hpp>
#include <cppast/cpp_template.hpp>
#include <cppast/cpp_template_parameter.hpp>
#include "libclang_visitor.hpp"
#include "parse_functions.hpp"
using namespace cppast;
std::unique_ptr<cpp_entity> detail::parse_cpp_friend(const detail::parse_context& context,
const CXCursor& cur)
{
DEBUG_ASSERT(clang_getCursorKind(cur) == CXCursor_FriendDecl, detail::assert_handler{});
std::string comment;
std::unique_ptr<cpp_entity> entity;
std::unique_ptr<cpp_type> type;
std::string namespace_str;
type_safe::optional<cpp_template_instantiation_type::builder> inst_builder;
detail::visit_children(cur, [&](const CXCursor& child) {
auto kind = clang_getCursorKind(child);
if (kind == CXCursor_TypeRef)
{
auto referenced = clang_getCursorReferenced(child);
if (inst_builder)
{
namespace_str.clear();
inst_builder.value().add_argument(
detail::parse_type(context, referenced, clang_getCursorType(referenced)));
}
else if (clang_getCursorKind(referenced) == CXCursor_TemplateTypeParameter)
// parse template parameter type
type = cpp_template_parameter_type::build(
cpp_template_type_parameter_ref(detail::get_entity_id(referenced),
detail::get_cursor_name(child).c_str()));
else if (!namespace_str.empty())
{
// parse as user defined type
// we can't use the other branch here,
// as then the class name would be wrong
auto name = detail::get_cursor_name(referenced);
type = cpp_user_defined_type::build(
cpp_type_ref(detail::get_entity_id(referenced),
namespace_str + "::" + name.c_str()));
}
else
{
// for some reason libclang gives a type ref here
// we actually need a class decl cursor, so parse the referenced one
// this might be a definition, so give friend information to the parser
entity = parse_entity(context, nullptr, referenced, cur);
comment = type_safe::copy(entity->comment()).value_or("");
}
}
else if (kind == CXCursor_NamespaceRef)
namespace_str += detail::get_cursor_name(child).c_str();
else if (kind == CXCursor_TemplateRef)
{
if (!namespace_str.empty())
namespace_str += "::";
auto templ = cpp_template_ref(detail::get_entity_id(clang_getCursorReferenced(child)),
namespace_str + detail::get_cursor_name(child).c_str());
namespace_str.clear();
if (!inst_builder)
inst_builder = cpp_template_instantiation_type::builder(std::move(templ));
else
inst_builder.value().add_argument(std::move(templ));
}
else if (clang_isDeclaration(kind))
{
entity = parse_entity(context, nullptr, child, cur);
if (entity)
{
// steal comment
comment = type_safe::copy(entity->comment()).value_or("");
entity->set_comment(type_safe::nullopt);
}
}
else if (inst_builder && clang_isExpression(kind))
{
namespace_str.clear();
inst_builder.value().add_argument(detail::parse_expression(context, child));
}
});
std::unique_ptr<cpp_entity> result;
if (entity)
result = cpp_friend::build(std::move(entity));
else if (type)
result = cpp_friend::build(std::move(type));
else if (inst_builder)
result = cpp_friend::build(inst_builder.value().finish());
else
DEBUG_UNREACHABLE(detail::parse_error_handler{}, cur,
"unknown child entity of friend declaration");
if (!comment.empty())
// set comment of entity...
result->set_comment(std::move(comment));
// ... but override if this finds a different comment
// due to clang_getCursorReferenced(), this may happen
context.comments.match(*result, cur);
return result;
}
| 4,812 | 1,268 |
#include "stdafx.h"
#include "Input.h"
JF::JFCInput::JFCInput()
{
memset(m_bKeyCodeArray, 0, sizeof(m_bKeyCodeArray));
memset(m_bKeyCodeArrayUp, 0, sizeof(m_bKeyCodeArrayUp));
m_vMousePos = { 0, 0, 0 };
m_vClickPos = { 0, 0, 0 };
}
JF::JFCInput::~JFCInput()
{
}
void JF::JFCInput::OnKeyDown(WPARAM wParam)
{
m_bKeyCodeArray[wParam] = true;
m_bKeyCodeArrayUp[wParam] = false;
}
void JF::JFCInput::OnKeyUp(WPARAM wParam)
{
m_bKeyCodeArray[wParam] = false;
m_bKeyCodeArrayUp[wParam] = true;
}
void JF::JFCInput::OnMouseMove(LPARAM lParam)
{
m_vMousePos.x = LOWORD(lParam);
m_vMousePos.y = HIWORD(lParam);
}
void JF::JFCInput::OnMouseClick(LPARAM lParam)
{
m_vClickPos.x = LOWORD(lParam);
m_vClickPos.y = HIWORD(lParam);
}
bool JF::JFCInput::GetKey(WPARAM wParam)
{
return m_bKeyCodeArray[wParam];
}
bool JF::JFCInput::GetKeyDown(WPARAM wParam)
{
return m_bKeyCodeArray[wParam];
}
bool JF::JFCInput::GetKeyUP(WPARAM wParam)
{
bool ret = m_bKeyCodeArrayUp[wParam];
m_bKeyCodeArrayUp[wParam] = false;
return ret;
}
bool JF::JFCInput::GetMouseButton(WPARAM wParam)
{
return m_bKeyCodeArray[wParam];
}
bool JF::JFCInput::GetMouseButtonDown(WPARAM wParam)
{
return m_bKeyCodeArray[wParam];
}
bool JF::JFCInput::GetMouseButtonUp(WPARAM wParam)
{
return m_bKeyCodeArray[wParam];
}
XMFLOAT3 JF::JFCInput::GetMousePosition() const
{
return m_vMousePos;
} | 1,375 | 645 |
#pragma once
#include "message_list.hpp"
#include "source_address.hpp"
namespace dbg
{
void FireAssert(SourceAddress const & sa, string const & msg);
}
#define CHECK(x, message) do { if (x) {} else { ::dbg::FireAssert(SRC(), ::msg::MessageList message); } } while (false)
#ifdef DEBUG
#define ASSERT(x, msg) CHECK(x, msg)
#else
#define ASSERT(x, msg)
#endif
| 369 | 137 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/task_manager/task_manager_resource_providers.h"
#include <string>
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/file_version_info.h"
#include "base/i18n/rtl.h"
#include "base/memory/scoped_ptr.h"
#include "base/process_util.h"
#include "base/stl_util.h"
#include "base/string_util.h"
#include "base/threading/thread.h"
#include "base/utf_string_conversions.h"
#include "build/build_config.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/background/background_contents_service.h"
#include "chrome/browser/background/background_contents_service_factory.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/favicon/favicon_tab_helper.h"
#include "chrome/browser/instant/instant_controller.h"
#include "chrome/browser/prerender/prerender_manager.h"
#include "chrome/browser/prerender/prerender_manager_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_info_cache.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/tab_contents/background_contents.h"
#include "chrome/browser/tab_contents/tab_util.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_instant_controller.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/panels/panel.h"
#include "chrome/browser/ui/panels/panel_manager.h"
#include "chrome/browser/ui/tab_contents/tab_contents.h"
#include "chrome/browser/ui/tab_contents/tab_contents_iterator.h"
#include "chrome/browser/view_type_utils.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/browser_child_process_host_iterator.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/child_process_data.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/process_type.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "third_party/sqlite/sqlite3.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/image/image_skia.h"
#include "v8/include/v8.h"
#if defined(OS_MACOSX)
#include "ui/gfx/image/image_skia_util_mac.h"
#endif
#if defined(OS_WIN)
#include "chrome/browser/app_icon_win.h"
#include "ui/gfx/icon_util.h"
#endif // defined(OS_WIN)
using content::BrowserChildProcessHostIterator;
using content::BrowserThread;
using content::WebContents;
using extensions::Extension;
namespace {
// Returns the appropriate message prefix ID for tabs and extensions,
// reflecting whether they are apps or in incognito mode.
int GetMessagePrefixID(bool is_app,
bool is_extension,
bool is_incognito,
bool is_prerender,
bool is_instant_preview) {
if (is_app) {
if (is_incognito)
return IDS_TASK_MANAGER_APP_INCOGNITO_PREFIX;
else
return IDS_TASK_MANAGER_APP_PREFIX;
} else if (is_extension) {
if (is_incognito)
return IDS_TASK_MANAGER_EXTENSION_INCOGNITO_PREFIX;
else
return IDS_TASK_MANAGER_EXTENSION_PREFIX;
} else if (is_prerender) {
return IDS_TASK_MANAGER_PRERENDER_PREFIX;
} else if (is_instant_preview) {
return IDS_TASK_MANAGER_INSTANT_PREVIEW_PREFIX;
} else {
return IDS_TASK_MANAGER_TAB_PREFIX;
}
}
string16 GetProfileNameFromInfoCache(Profile* profile) {
ProfileInfoCache& cache =
g_browser_process->profile_manager()->GetProfileInfoCache();
size_t index = cache.GetIndexOfProfileWithPath(
profile->GetOriginalProfile()->GetPath());
if (index == std::string::npos)
return string16();
else
return cache.GetNameOfProfileAtIndex(index);
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// TaskManagerRendererResource class
////////////////////////////////////////////////////////////////////////////////
TaskManagerRendererResource::TaskManagerRendererResource(
base::ProcessHandle process, content::RenderViewHost* render_view_host)
: process_(process),
render_view_host_(render_view_host),
pending_stats_update_(false),
fps_(0.0f),
pending_fps_update_(false),
v8_memory_allocated_(0),
v8_memory_used_(0),
pending_v8_memory_allocated_update_(false) {
// We cache the process and pid as when a Tab/BackgroundContents is closed the
// process reference becomes NULL and the TaskManager still needs it.
pid_ = base::GetProcId(process_);
unique_process_id_ = render_view_host_->GetProcess()->GetID();
memset(&stats_, 0, sizeof(stats_));
}
TaskManagerRendererResource::~TaskManagerRendererResource() {
}
void TaskManagerRendererResource::Refresh() {
if (!pending_stats_update_) {
render_view_host_->Send(new ChromeViewMsg_GetCacheResourceStats);
pending_stats_update_ = true;
}
if (!pending_fps_update_) {
render_view_host_->Send(
new ChromeViewMsg_GetFPS(render_view_host_->GetRoutingID()));
pending_fps_update_ = true;
}
if (!pending_v8_memory_allocated_update_) {
render_view_host_->Send(new ChromeViewMsg_GetV8HeapStats);
pending_v8_memory_allocated_update_ = true;
}
}
WebKit::WebCache::ResourceTypeStats
TaskManagerRendererResource::GetWebCoreCacheStats() const {
return stats_;
}
float TaskManagerRendererResource::GetFPS() const {
return fps_;
}
size_t TaskManagerRendererResource::GetV8MemoryAllocated() const {
return v8_memory_allocated_;
}
size_t TaskManagerRendererResource::GetV8MemoryUsed() const {
return v8_memory_used_;
}
void TaskManagerRendererResource::NotifyResourceTypeStats(
const WebKit::WebCache::ResourceTypeStats& stats) {
stats_ = stats;
pending_stats_update_ = false;
}
void TaskManagerRendererResource::NotifyFPS(float fps) {
fps_ = fps;
pending_fps_update_ = false;
}
void TaskManagerRendererResource::NotifyV8HeapStats(
size_t v8_memory_allocated, size_t v8_memory_used) {
v8_memory_allocated_ = v8_memory_allocated;
v8_memory_used_ = v8_memory_used;
pending_v8_memory_allocated_update_ = false;
}
base::ProcessHandle TaskManagerRendererResource::GetProcess() const {
return process_;
}
int TaskManagerRendererResource::GetUniqueChildProcessId() const {
return unique_process_id_;
}
TaskManager::Resource::Type TaskManagerRendererResource::GetType() const {
return RENDERER;
}
int TaskManagerRendererResource::GetRoutingID() const {
return render_view_host_->GetRoutingID();
}
bool TaskManagerRendererResource::ReportsCacheStats() const {
return true;
}
bool TaskManagerRendererResource::ReportsFPS() const {
return true;
}
bool TaskManagerRendererResource::ReportsV8MemoryStats() const {
return true;
}
bool TaskManagerRendererResource::CanInspect() const {
return true;
}
void TaskManagerRendererResource::Inspect() const {
DevToolsWindow::OpenDevToolsWindow(render_view_host_);
}
bool TaskManagerRendererResource::SupportNetworkUsage() const {
return true;
}
////////////////////////////////////////////////////////////////////////////////
// TaskManagerTabContentsResource class
////////////////////////////////////////////////////////////////////////////////
// static
gfx::ImageSkia* TaskManagerTabContentsResource::prerender_icon_ = NULL;
TaskManagerTabContentsResource::TaskManagerTabContentsResource(
TabContents* tab_contents)
: TaskManagerRendererResource(
tab_contents->web_contents()->GetRenderProcessHost()->GetHandle(),
tab_contents->web_contents()->GetRenderViewHost()),
tab_contents_(tab_contents),
is_instant_preview_(false) {
if (!prerender_icon_) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
prerender_icon_ = rb.GetImageSkiaNamed(IDR_PRERENDER);
}
for (BrowserList::const_iterator i = BrowserList::begin();
i != BrowserList::end(); ++i) {
if ((*i)->instant_controller()->instant() &&
(*i)->instant_controller()->instant()->GetPreviewContents() ==
tab_contents_) {
is_instant_preview_ = true;
break;
}
}
}
TaskManagerTabContentsResource::~TaskManagerTabContentsResource() {
}
void TaskManagerTabContentsResource::InstantCommitted() {
DCHECK(is_instant_preview_);
is_instant_preview_ = false;
}
bool TaskManagerTabContentsResource::IsPrerendering() const {
prerender::PrerenderManager* prerender_manager =
prerender::PrerenderManagerFactory::GetForProfile(
tab_contents_->profile());
return prerender_manager &&
prerender_manager->IsWebContentsPrerendering(
tab_contents_->web_contents());
}
bool TaskManagerTabContentsResource::HostsExtension() const {
return tab_contents_->web_contents()->GetURL().SchemeIs(
chrome::kExtensionScheme);
}
TaskManager::Resource::Type TaskManagerTabContentsResource::GetType() const {
return HostsExtension() ? EXTENSION : RENDERER;
}
string16 TaskManagerTabContentsResource::GetTitle() const {
// Fall back on the URL if there's no title.
WebContents* contents = tab_contents_->web_contents();
string16 tab_title = contents->GetTitle();
GURL url = contents->GetURL();
if (tab_title.empty()) {
tab_title = UTF8ToUTF16(url.spec());
// Force URL to be LTR.
tab_title = base::i18n::GetDisplayStringInLTRDirectionality(tab_title);
} else {
// Since the tab_title will be concatenated with
// IDS_TASK_MANAGER_TAB_PREFIX, we need to explicitly set the tab_title to
// be LTR format if there is no strong RTL charater in it. Otherwise, if
// IDS_TASK_MANAGER_TAB_PREFIX is an RTL word, the concatenated result
// might be wrong. For example, http://mail.yahoo.com, whose title is
// "Yahoo! Mail: The best web-based Email!", without setting it explicitly
// as LTR format, the concatenated result will be "!Yahoo! Mail: The best
// web-based Email :BAT", in which the capital letters "BAT" stands for
// the Hebrew word for "tab".
base::i18n::AdjustStringForLocaleDirection(&tab_title);
}
// Only classify as an app if the URL is an app and the tab is hosting an
// extension process. (It's possible to be showing the URL from before it
// was installed as an app.)
ExtensionService* extension_service =
tab_contents_->profile()->GetExtensionService();
extensions::ProcessMap* process_map = extension_service->process_map();
bool is_app = extension_service->IsInstalledApp(url) &&
process_map->Contains(contents->GetRenderProcessHost()->GetID());
int message_id = GetMessagePrefixID(
is_app,
HostsExtension(),
tab_contents_->profile()->IsOffTheRecord(),
IsPrerendering(),
is_instant_preview_);
return l10n_util::GetStringFUTF16(message_id, tab_title);
}
string16 TaskManagerTabContentsResource::GetProfileName() const {
return GetProfileNameFromInfoCache(tab_contents_->profile());
}
gfx::ImageSkia TaskManagerTabContentsResource::GetIcon() const {
if (IsPrerendering())
return *prerender_icon_;
return tab_contents_->favicon_tab_helper()->GetFavicon().AsImageSkia();
}
WebContents* TaskManagerTabContentsResource::GetWebContents() const {
return tab_contents_->web_contents();
}
const Extension* TaskManagerTabContentsResource::GetExtension() const {
if (HostsExtension()) {
ExtensionService* extension_service =
tab_contents_->profile()->GetExtensionService();
return extension_service->extensions()->GetByID(
tab_contents_->web_contents()->GetURL().host());
}
return NULL;
}
////////////////////////////////////////////////////////////////////////////////
// TaskManagerTabContentsResourceProvider class
////////////////////////////////////////////////////////////////////////////////
TaskManagerTabContentsResourceProvider::
TaskManagerTabContentsResourceProvider(TaskManager* task_manager)
: updating_(false),
task_manager_(task_manager) {
}
TaskManagerTabContentsResourceProvider::
~TaskManagerTabContentsResourceProvider() {
}
TaskManager::Resource* TaskManagerTabContentsResourceProvider::GetResource(
int origin_pid,
int render_process_host_id,
int routing_id) {
WebContents* web_contents =
tab_util::GetWebContentsByID(render_process_host_id, routing_id);
if (!web_contents) // Not one of our resource.
return NULL;
// If an origin PID was specified then the request originated in a plugin
// working on the WebContents's behalf, so ignore it.
if (origin_pid)
return NULL;
TabContents* tab_contents = TabContents::FromWebContents(web_contents);
std::map<TabContents*, TaskManagerTabContentsResource*>::iterator
res_iter = resources_.find(tab_contents);
if (res_iter == resources_.end()) {
// Can happen if the tab was closed while a network request was being
// performed.
return NULL;
}
return res_iter->second;
}
void TaskManagerTabContentsResourceProvider::StartUpdating() {
DCHECK(!updating_);
updating_ = true;
// Add all the existing TabContentses.
for (TabContentsIterator iterator; !iterator.done(); ++iterator)
Add(*iterator);
// Then we register for notifications to get new tabs.
registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_CONNECTED,
content::NotificationService::AllBrowserContextsAndSources());
registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_SWAPPED,
content::NotificationService::AllBrowserContextsAndSources());
registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
content::NotificationService::AllBrowserContextsAndSources());
registrar_.Add(this, chrome::NOTIFICATION_INSTANT_COMMITTED,
content::NotificationService::AllBrowserContextsAndSources());
}
void TaskManagerTabContentsResourceProvider::StopUpdating() {
DCHECK(updating_);
updating_ = false;
// Then we unregister for notifications to get new tabs.
registrar_.Remove(
this, content::NOTIFICATION_WEB_CONTENTS_CONNECTED,
content::NotificationService::AllBrowserContextsAndSources());
registrar_.Remove(
this, content::NOTIFICATION_WEB_CONTENTS_SWAPPED,
content::NotificationService::AllBrowserContextsAndSources());
registrar_.Remove(
this, content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
content::NotificationService::AllBrowserContextsAndSources());
registrar_.Remove(
this, chrome::NOTIFICATION_INSTANT_COMMITTED,
content::NotificationService::AllBrowserContextsAndSources());
// Delete all the resources.
STLDeleteContainerPairSecondPointers(resources_.begin(), resources_.end());
resources_.clear();
}
void TaskManagerTabContentsResourceProvider::AddToTaskManager(
TabContents* tab_contents) {
TaskManagerTabContentsResource* resource =
new TaskManagerTabContentsResource(tab_contents);
resources_[tab_contents] = resource;
task_manager_->AddResource(resource);
}
void TaskManagerTabContentsResourceProvider::Add(TabContents* tab_contents) {
if (!updating_)
return;
// Don't add dead tabs or tabs that haven't yet connected.
if (!tab_contents->web_contents()->GetRenderProcessHost()->GetHandle() ||
!tab_contents->web_contents()->WillNotifyDisconnection()) {
return;
}
std::map<TabContents*, TaskManagerTabContentsResource*>::const_iterator
iter = resources_.find(tab_contents);
if (iter != resources_.end()) {
// The case may happen that we have added a WebContents as part of the
// iteration performed during StartUpdating() call but the notification that
// it has connected was not fired yet. So when the notification happens, we
// already know about this tab and just ignore it.
return;
}
AddToTaskManager(tab_contents);
}
void TaskManagerTabContentsResourceProvider::Remove(TabContents* tab_contents) {
if (!updating_)
return;
std::map<TabContents*, TaskManagerTabContentsResource*>::iterator
iter = resources_.find(tab_contents);
if (iter == resources_.end()) {
// Since WebContents are destroyed asynchronously (see TabContentsCollector
// in navigation_controller.cc), we can be notified of a tab being removed
// that we don't know. This can happen if the user closes a tab and quickly
// opens the task manager, before the tab is actually destroyed.
return;
}
// Remove the resource from the Task Manager.
TaskManagerTabContentsResource* resource = iter->second;
task_manager_->RemoveResource(resource);
// And from the provider.
resources_.erase(iter);
// Finally, delete the resource.
delete resource;
}
void TaskManagerTabContentsResourceProvider::Update(TabContents* tab_contents) {
if (!updating_)
return;
std::map<TabContents*, TaskManagerTabContentsResource*>::iterator
iter = resources_.find(tab_contents);
DCHECK(iter != resources_.end());
if (iter != resources_.end())
iter->second->InstantCommitted();
}
void TaskManagerTabContentsResourceProvider::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
TabContents* tab_contents;
if (type == chrome::NOTIFICATION_INSTANT_COMMITTED) {
tab_contents = content::Source<TabContents>(source).ptr();
} else {
tab_contents = TabContents::FromWebContents(
content::Source<WebContents>(source).ptr());
}
// A background page does not have a TabContents.
if (!tab_contents)
return;
switch (type) {
case content::NOTIFICATION_WEB_CONTENTS_CONNECTED:
Add(tab_contents);
break;
case content::NOTIFICATION_WEB_CONTENTS_SWAPPED:
Remove(tab_contents);
Add(tab_contents);
break;
case content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED:
Remove(tab_contents);
break;
case chrome::NOTIFICATION_INSTANT_COMMITTED:
Update(tab_contents);
break;
default:
NOTREACHED() << "Unexpected notification.";
return;
}
}
////////////////////////////////////////////////////////////////////////////////
// TaskManagerPanelResource class
////////////////////////////////////////////////////////////////////////////////
TaskManagerPanelResource::TaskManagerPanelResource(Panel* panel)
: TaskManagerRendererResource(
panel->GetWebContents()->GetRenderProcessHost()->GetHandle(),
panel->GetWebContents()->GetRenderViewHost()),
panel_(panel) {
message_prefix_id_ = GetMessagePrefixID(
GetExtension()->is_app(), true, panel->profile()->IsOffTheRecord(),
false, false);
}
TaskManagerPanelResource::~TaskManagerPanelResource() {
}
TaskManager::Resource::Type TaskManagerPanelResource::GetType() const {
return EXTENSION;
}
string16 TaskManagerPanelResource::GetTitle() const {
string16 title = panel_->GetWindowTitle();
// Since the title will be concatenated with an IDS_TASK_MANAGER_* prefix
// we need to explicitly set the title to be LTR format if there is no
// strong RTL charater in it. Otherwise, if the task manager prefix is an
// RTL word, the concatenated result might be wrong. For example,
// a page whose title is "Yahoo! Mail: The best web-based Email!", without
// setting it explicitly as LTR format, the concatenated result will be
// "!Yahoo! Mail: The best web-based Email :PPA", in which the capital
// letters "PPA" stands for the Hebrew word for "app".
base::i18n::AdjustStringForLocaleDirection(&title);
return l10n_util::GetStringFUTF16(message_prefix_id_, title);
}
string16 TaskManagerPanelResource::GetProfileName() const {
return GetProfileNameFromInfoCache(panel_->profile());
}
gfx::ImageSkia TaskManagerPanelResource::GetIcon() const {
return panel_->GetCurrentPageIcon();
}
WebContents* TaskManagerPanelResource::GetWebContents() const {
return panel_->GetWebContents();
}
const Extension* TaskManagerPanelResource::GetExtension() const {
ExtensionService* extension_service =
panel_->profile()->GetExtensionService();
return extension_service->extensions()->GetByID(panel_->extension_id());
}
////////////////////////////////////////////////////////////////////////////////
// TaskManagerPanelResourceProvider class
////////////////////////////////////////////////////////////////////////////////
TaskManagerPanelResourceProvider::TaskManagerPanelResourceProvider(
TaskManager* task_manager)
: updating_(false),
task_manager_(task_manager) {
}
TaskManagerPanelResourceProvider::~TaskManagerPanelResourceProvider() {
}
TaskManager::Resource* TaskManagerPanelResourceProvider::GetResource(
int origin_pid,
int render_process_host_id,
int routing_id) {
// If an origin PID was specified, the request is from a plugin, not the
// render view host process
if (origin_pid)
return NULL;
for (PanelResourceMap::iterator i = resources_.begin();
i != resources_.end(); ++i) {
WebContents* contents = i->first->GetWebContents();
if (contents &&
contents->GetRenderProcessHost()->GetID() == render_process_host_id &&
contents->GetRenderViewHost()->GetRoutingID() == routing_id) {
return i->second;
}
}
// Can happen if the panel went away while a network request was being
// performed.
return NULL;
}
void TaskManagerPanelResourceProvider::StartUpdating() {
if (!CommandLine::ForCurrentProcess()->HasSwitch(
switches::kBrowserlessPanels))
return;
DCHECK(!updating_);
updating_ = true;
// Add all the Panels.
std::vector<Panel*> panels = PanelManager::GetInstance()->panels();
for (size_t i = 0; i < panels.size(); ++i)
Add(panels[i]);
// Then we register for notifications to get new and remove closed panels.
registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_CONNECTED,
content::NotificationService::AllSources());
registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
content::NotificationService::AllSources());
}
void TaskManagerPanelResourceProvider::StopUpdating() {
if (!CommandLine::ForCurrentProcess()->HasSwitch(
switches::kBrowserlessPanels))
return;
DCHECK(updating_);
updating_ = false;
// Unregister for notifications about new/removed panels.
registrar_.Remove(this, content::NOTIFICATION_WEB_CONTENTS_CONNECTED,
content::NotificationService::AllSources());
registrar_.Remove(this, content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
content::NotificationService::AllSources());
// Delete all the resources.
STLDeleteContainerPairSecondPointers(resources_.begin(), resources_.end());
resources_.clear();
}
void TaskManagerPanelResourceProvider::Add(Panel* panel) {
if (!updating_)
return;
PanelResourceMap::const_iterator iter = resources_.find(panel);
if (iter != resources_.end())
return;
TaskManagerPanelResource* resource = new TaskManagerPanelResource(panel);
resources_[panel] = resource;
task_manager_->AddResource(resource);
}
void TaskManagerPanelResourceProvider::Remove(Panel* panel) {
if (!updating_)
return;
PanelResourceMap::iterator iter = resources_.find(panel);
if (iter == resources_.end())
return;
TaskManagerPanelResource* resource = iter->second;
task_manager_->RemoveResource(resource);
resources_.erase(iter);
delete resource;
}
void TaskManagerPanelResourceProvider::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
WebContents* web_contents = content::Source<WebContents>(source).ptr();
if (chrome::GetViewType(web_contents) != chrome::VIEW_TYPE_PANEL)
return;
switch (type) {
case content::NOTIFICATION_WEB_CONTENTS_CONNECTED:
{
std::vector<Panel*>panels = PanelManager::GetInstance()->panels();
for (size_t i = 0; i < panels.size(); ++i) {
if (panels[i]->GetWebContents() == web_contents) {
Add(panels[i]);
break;
}
}
break;
}
case content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED:
{
for (PanelResourceMap::iterator iter = resources_.begin();
iter != resources_.end(); ++iter) {
Panel* panel = iter->first;
if (panel->GetWebContents() == web_contents) {
Remove(panel);
break;
}
}
break;
}
default:
NOTREACHED() << "Unexpected notificiation.";
break;
}
}
////////////////////////////////////////////////////////////////////////////////
// TaskManagerBackgroundContentsResource class
////////////////////////////////////////////////////////////////////////////////
gfx::ImageSkia* TaskManagerBackgroundContentsResource::default_icon_ = NULL;
// TODO(atwilson): http://crbug.com/116893
// HACK: if the process handle is invalid, we use the current process's handle.
// This preserves old behavior but is incorrect, and should be fixed.
TaskManagerBackgroundContentsResource::TaskManagerBackgroundContentsResource(
BackgroundContents* background_contents,
const string16& application_name)
: TaskManagerRendererResource(
background_contents->web_contents()->GetRenderProcessHost()->
GetHandle() ?
background_contents->web_contents()->GetRenderProcessHost()->
GetHandle() :
base::Process::Current().handle(),
background_contents->web_contents()->GetRenderViewHost()),
background_contents_(background_contents),
application_name_(application_name) {
// Just use the same icon that other extension resources do.
// TODO(atwilson): Use the favicon when that's available.
if (!default_icon_) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
default_icon_ = rb.GetImageSkiaNamed(IDR_PLUGIN);
}
// Ensure that the string has the appropriate direction markers (see comment
// in TaskManagerTabContentsResource::GetTitle()).
base::i18n::AdjustStringForLocaleDirection(&application_name_);
}
TaskManagerBackgroundContentsResource::~TaskManagerBackgroundContentsResource(
) {
}
string16 TaskManagerBackgroundContentsResource::GetTitle() const {
string16 title = application_name_;
if (title.empty()) {
// No title (can't locate the parent app for some reason) so just display
// the URL (properly forced to be LTR).
title = base::i18n::GetDisplayStringInLTRDirectionality(
UTF8ToUTF16(background_contents_->GetURL().spec()));
}
return l10n_util::GetStringFUTF16(IDS_TASK_MANAGER_BACKGROUND_PREFIX, title);
}
string16 TaskManagerBackgroundContentsResource::GetProfileName() const {
return string16();
}
gfx::ImageSkia TaskManagerBackgroundContentsResource::GetIcon() const {
return *default_icon_;
}
bool TaskManagerBackgroundContentsResource::IsBackground() const {
return true;
}
////////////////////////////////////////////////////////////////////////////////
// TaskManagerBackgroundContentsResourceProvider class
////////////////////////////////////////////////////////////////////////////////
TaskManagerBackgroundContentsResourceProvider::
TaskManagerBackgroundContentsResourceProvider(TaskManager* task_manager)
: updating_(false),
task_manager_(task_manager) {
}
TaskManagerBackgroundContentsResourceProvider::
~TaskManagerBackgroundContentsResourceProvider() {
}
TaskManager::Resource*
TaskManagerBackgroundContentsResourceProvider::GetResource(
int origin_pid,
int render_process_host_id,
int routing_id) {
// If an origin PID was specified, the request is from a plugin, not the
// render view host process
if (origin_pid)
return NULL;
for (Resources::iterator i = resources_.begin(); i != resources_.end(); i++) {
WebContents* tab = i->first->web_contents();
if (tab->GetRenderProcessHost()->GetID() == render_process_host_id
&& tab->GetRenderViewHost()->GetRoutingID() == routing_id) {
return i->second;
}
}
// Can happen if the page went away while a network request was being
// performed.
return NULL;
}
void TaskManagerBackgroundContentsResourceProvider::StartUpdating() {
DCHECK(!updating_);
updating_ = true;
// Add all the existing BackgroundContents from every profile, including
// incognito profiles.
ProfileManager* profile_manager = g_browser_process->profile_manager();
std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles());
size_t num_default_profiles = profiles.size();
for (size_t i = 0; i < num_default_profiles; ++i) {
if (profiles[i]->HasOffTheRecordProfile()) {
profiles.push_back(profiles[i]->GetOffTheRecordProfile());
}
}
for (size_t i = 0; i < profiles.size(); ++i) {
BackgroundContentsService* background_contents_service =
BackgroundContentsServiceFactory::GetForProfile(profiles[i]);
std::vector<BackgroundContents*> contents =
background_contents_service->GetBackgroundContents();
ExtensionService* extension_service = profiles[i]->GetExtensionService();
for (std::vector<BackgroundContents*>::iterator iterator = contents.begin();
iterator != contents.end(); ++iterator) {
string16 application_name;
// Lookup the name from the parent extension.
if (extension_service) {
const string16& application_id =
background_contents_service->GetParentApplicationId(*iterator);
const Extension* extension = extension_service->GetExtensionById(
UTF16ToUTF8(application_id), false);
if (extension)
application_name = UTF8ToUTF16(extension->name());
}
Add(*iterator, application_name);
}
}
// Then we register for notifications to get new BackgroundContents.
registrar_.Add(this, chrome::NOTIFICATION_BACKGROUND_CONTENTS_OPENED,
content::NotificationService::AllBrowserContextsAndSources());
registrar_.Add(this, chrome::NOTIFICATION_BACKGROUND_CONTENTS_NAVIGATED,
content::NotificationService::AllBrowserContextsAndSources());
registrar_.Add(this, chrome::NOTIFICATION_BACKGROUND_CONTENTS_DELETED,
content::NotificationService::AllBrowserContextsAndSources());
}
void TaskManagerBackgroundContentsResourceProvider::StopUpdating() {
DCHECK(updating_);
updating_ = false;
// Unregister for notifications
registrar_.Remove(
this, chrome::NOTIFICATION_BACKGROUND_CONTENTS_OPENED,
content::NotificationService::AllBrowserContextsAndSources());
registrar_.Remove(
this, chrome::NOTIFICATION_BACKGROUND_CONTENTS_NAVIGATED,
content::NotificationService::AllBrowserContextsAndSources());
registrar_.Remove(
this, chrome::NOTIFICATION_BACKGROUND_CONTENTS_DELETED,
content::NotificationService::AllBrowserContextsAndSources());
// Delete all the resources.
STLDeleteContainerPairSecondPointers(resources_.begin(), resources_.end());
resources_.clear();
}
void TaskManagerBackgroundContentsResourceProvider::AddToTaskManager(
BackgroundContents* background_contents,
const string16& application_name) {
TaskManagerBackgroundContentsResource* resource =
new TaskManagerBackgroundContentsResource(background_contents,
application_name);
resources_[background_contents] = resource;
task_manager_->AddResource(resource);
}
void TaskManagerBackgroundContentsResourceProvider::Add(
BackgroundContents* contents, const string16& application_name) {
if (!updating_)
return;
// TODO(atwilson): http://crbug.com/116893
// We should check that the process handle is valid here, but it won't
// be in the case of NOTIFICATION_BACKGROUND_CONTENTS_OPENED.
// Should never add the same BackgroundContents twice.
DCHECK(resources_.find(contents) == resources_.end());
AddToTaskManager(contents, application_name);
}
void TaskManagerBackgroundContentsResourceProvider::Remove(
BackgroundContents* contents) {
if (!updating_)
return;
Resources::iterator iter = resources_.find(contents);
DCHECK(iter != resources_.end());
// Remove the resource from the Task Manager.
TaskManagerBackgroundContentsResource* resource = iter->second;
task_manager_->RemoveResource(resource);
// And from the provider.
resources_.erase(iter);
// Finally, delete the resource.
delete resource;
}
void TaskManagerBackgroundContentsResourceProvider::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
switch (type) {
case chrome::NOTIFICATION_BACKGROUND_CONTENTS_OPENED: {
// Get the name from the parent application. If no parent application is
// found, just pass an empty string - BackgroundContentsResource::GetTitle
// will display the URL instead in this case. This should never happen
// except in rare cases when an extension is being unloaded or chrome is
// exiting while the task manager is displayed.
string16 application_name;
ExtensionService* service =
content::Source<Profile>(source)->GetExtensionService();
if (service) {
std::string application_id = UTF16ToUTF8(
content::Details<BackgroundContentsOpenedDetails>(details)->
application_id);
const Extension* extension =
service->GetExtensionById(application_id, false);
// Extension can be NULL when running unit tests.
if (extension)
application_name = UTF8ToUTF16(extension->name());
}
Add(content::Details<BackgroundContentsOpenedDetails>(details)->contents,
application_name);
// Opening a new BackgroundContents needs to force the display to refresh
// (applications may now be considered "background" that weren't before).
task_manager_->ModelChanged();
break;
}
case chrome::NOTIFICATION_BACKGROUND_CONTENTS_NAVIGATED: {
BackgroundContents* contents =
content::Details<BackgroundContents>(details).ptr();
// Should never get a NAVIGATED before OPENED.
DCHECK(resources_.find(contents) != resources_.end());
// Preserve the application name.
string16 application_name(
resources_.find(contents)->second->application_name());
Remove(contents);
Add(contents, application_name);
break;
}
case chrome::NOTIFICATION_BACKGROUND_CONTENTS_DELETED:
Remove(content::Details<BackgroundContents>(details).ptr());
// Closing a BackgroundContents needs to force the display to refresh
// (applications may now be considered "foreground" that weren't before).
task_manager_->ModelChanged();
break;
default:
NOTREACHED() << "Unexpected notification.";
return;
}
}
////////////////////////////////////////////////////////////////////////////////
// TaskManagerChildProcessResource class
////////////////////////////////////////////////////////////////////////////////
gfx::ImageSkia* TaskManagerChildProcessResource::default_icon_ = NULL;
TaskManagerChildProcessResource::TaskManagerChildProcessResource(
content::ProcessType type,
const string16& name,
base::ProcessHandle handle,
int unique_process_id)
: type_(type),
name_(name),
handle_(handle),
unique_process_id_(unique_process_id),
network_usage_support_(false) {
// We cache the process id because it's not cheap to calculate, and it won't
// be available when we get the plugin disconnected notification.
pid_ = base::GetProcId(handle);
if (!default_icon_) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
default_icon_ = rb.GetImageSkiaNamed(IDR_PLUGIN);
// TODO(jabdelmalek): use different icon for web workers.
}
}
TaskManagerChildProcessResource::~TaskManagerChildProcessResource() {
}
// TaskManagerResource methods:
string16 TaskManagerChildProcessResource::GetTitle() const {
if (title_.empty())
title_ = GetLocalizedTitle();
return title_;
}
string16 TaskManagerChildProcessResource::GetProfileName() const {
return string16();
}
gfx::ImageSkia TaskManagerChildProcessResource::GetIcon() const {
return *default_icon_;
}
base::ProcessHandle TaskManagerChildProcessResource::GetProcess() const {
return handle_;
}
int TaskManagerChildProcessResource::GetUniqueChildProcessId() const {
return unique_process_id_;
}
TaskManager::Resource::Type TaskManagerChildProcessResource::GetType() const {
// Translate types to TaskManager::ResourceType, since ChildProcessData's type
// is not available for all TaskManager resources.
switch (type_) {
case content::PROCESS_TYPE_PLUGIN:
case content::PROCESS_TYPE_PPAPI_PLUGIN:
case content::PROCESS_TYPE_PPAPI_BROKER:
return TaskManager::Resource::PLUGIN;
case content::PROCESS_TYPE_NACL_LOADER:
case content::PROCESS_TYPE_NACL_BROKER:
return TaskManager::Resource::NACL;
case content::PROCESS_TYPE_UTILITY:
return TaskManager::Resource::UTILITY;
case content::PROCESS_TYPE_PROFILE_IMPORT:
return TaskManager::Resource::PROFILE_IMPORT;
case content::PROCESS_TYPE_ZYGOTE:
return TaskManager::Resource::ZYGOTE;
case content::PROCESS_TYPE_SANDBOX_HELPER:
return TaskManager::Resource::SANDBOX_HELPER;
case content::PROCESS_TYPE_GPU:
return TaskManager::Resource::GPU;
default:
return TaskManager::Resource::UNKNOWN;
}
}
bool TaskManagerChildProcessResource::SupportNetworkUsage() const {
return network_usage_support_;
}
void TaskManagerChildProcessResource::SetSupportNetworkUsage() {
network_usage_support_ = true;
}
string16 TaskManagerChildProcessResource::GetLocalizedTitle() const {
string16 title = name_;
if (title.empty()) {
switch (type_) {
case content::PROCESS_TYPE_PLUGIN:
case content::PROCESS_TYPE_PPAPI_PLUGIN:
case content::PROCESS_TYPE_PPAPI_BROKER:
title = l10n_util::GetStringUTF16(IDS_TASK_MANAGER_UNKNOWN_PLUGIN_NAME);
break;
default:
// Nothing to do for non-plugin processes.
break;
}
}
// Explicitly mark name as LTR if there is no strong RTL character,
// to avoid the wrong concatenation result similar to "!Yahoo Mail: the
// best web-based Email: NIGULP", in which "NIGULP" stands for the Hebrew
// or Arabic word for "plugin".
base::i18n::AdjustStringForLocaleDirection(&title);
switch (type_) {
case content::PROCESS_TYPE_UTILITY:
return l10n_util::GetStringUTF16(IDS_TASK_MANAGER_UTILITY_PREFIX);
case content::PROCESS_TYPE_PROFILE_IMPORT:
return l10n_util::GetStringUTF16(IDS_TASK_MANAGER_UTILITY_PREFIX);
case content::PROCESS_TYPE_GPU:
return l10n_util::GetStringUTF16(IDS_TASK_MANAGER_GPU_PREFIX);
case content::PROCESS_TYPE_NACL_BROKER:
return l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NACL_BROKER_PREFIX);
case content::PROCESS_TYPE_PLUGIN:
case content::PROCESS_TYPE_PPAPI_PLUGIN:
return l10n_util::GetStringFUTF16(IDS_TASK_MANAGER_PLUGIN_PREFIX, title);
case content::PROCESS_TYPE_PPAPI_BROKER:
return l10n_util::GetStringFUTF16(IDS_TASK_MANAGER_PLUGIN_BROKER_PREFIX,
title);
case content::PROCESS_TYPE_NACL_LOADER:
return l10n_util::GetStringFUTF16(IDS_TASK_MANAGER_NACL_PREFIX, title);
// These types don't need display names or get them from elsewhere.
case content::PROCESS_TYPE_BROWSER:
case content::PROCESS_TYPE_RENDERER:
case content::PROCESS_TYPE_ZYGOTE:
case content::PROCESS_TYPE_SANDBOX_HELPER:
case content::PROCESS_TYPE_MAX:
NOTREACHED();
break;
case content::PROCESS_TYPE_WORKER:
NOTREACHED() << "Workers are not handled by this provider.";
break;
case content::PROCESS_TYPE_UNKNOWN:
NOTREACHED() << "Need localized name for child process type.";
}
return title;
}
////////////////////////////////////////////////////////////////////////////////
// TaskManagerChildProcessResourceProvider class
////////////////////////////////////////////////////////////////////////////////
TaskManagerChildProcessResourceProvider::
TaskManagerChildProcessResourceProvider(TaskManager* task_manager)
: task_manager_(task_manager),
updating_(false) {
}
TaskManagerChildProcessResourceProvider::
~TaskManagerChildProcessResourceProvider() {
}
TaskManager::Resource* TaskManagerChildProcessResourceProvider::GetResource(
int origin_pid,
int render_process_host_id,
int routing_id) {
PidResourceMap::iterator iter = pid_to_resources_.find(origin_pid);
if (iter != pid_to_resources_.end())
return iter->second;
else
return NULL;
}
void TaskManagerChildProcessResourceProvider::StartUpdating() {
DCHECK(!updating_);
updating_ = true;
// Register for notifications to get new child processes.
registrar_.Add(this, content::NOTIFICATION_CHILD_PROCESS_HOST_CONNECTED,
content::NotificationService::AllBrowserContextsAndSources());
registrar_.Add(this, content::NOTIFICATION_CHILD_PROCESS_HOST_DISCONNECTED,
content::NotificationService::AllBrowserContextsAndSources());
// Get the existing child processes.
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(
&TaskManagerChildProcessResourceProvider::RetrieveChildProcessData,
this));
}
void TaskManagerChildProcessResourceProvider::StopUpdating() {
DCHECK(updating_);
updating_ = false;
// Unregister for notifications to get new plugin processes.
registrar_.Remove(
this, content::NOTIFICATION_CHILD_PROCESS_HOST_CONNECTED,
content::NotificationService::AllBrowserContextsAndSources());
registrar_.Remove(
this,
content::NOTIFICATION_CHILD_PROCESS_HOST_DISCONNECTED,
content::NotificationService::AllBrowserContextsAndSources());
// Delete all the resources.
STLDeleteContainerPairSecondPointers(resources_.begin(), resources_.end());
resources_.clear();
pid_to_resources_.clear();
}
void TaskManagerChildProcessResourceProvider::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
content::ChildProcessData data =
*content::Details<content::ChildProcessData>(details).ptr();
switch (type) {
case content::NOTIFICATION_CHILD_PROCESS_HOST_CONNECTED:
Add(data);
break;
case content::NOTIFICATION_CHILD_PROCESS_HOST_DISCONNECTED:
Remove(data);
break;
default:
NOTREACHED() << "Unexpected notification.";
return;
}
}
void TaskManagerChildProcessResourceProvider::Add(
const content::ChildProcessData& child_process_data) {
if (!updating_)
return;
// Workers are handled by TaskManagerWorkerResourceProvider.
if (child_process_data.type == content::PROCESS_TYPE_WORKER)
return;
if (resources_.count(child_process_data.handle)) {
// The case may happen that we have added a child_process_info as part of
// the iteration performed during StartUpdating() call but the notification
// that it has connected was not fired yet. So when the notification
// happens, we already know about this plugin and just ignore it.
return;
}
AddToTaskManager(child_process_data);
}
void TaskManagerChildProcessResourceProvider::Remove(
const content::ChildProcessData& child_process_data) {
if (!updating_)
return;
if (child_process_data.type == content::PROCESS_TYPE_WORKER)
return;
ChildProcessMap::iterator iter = resources_.find(child_process_data.handle);
if (iter == resources_.end()) {
// ChildProcessData disconnection notifications are asynchronous, so we
// might be notified for a plugin we don't know anything about (if it was
// closed before the task manager was shown and destroyed after that).
return;
}
// Remove the resource from the Task Manager.
TaskManagerChildProcessResource* resource = iter->second;
task_manager_->RemoveResource(resource);
// Remove it from the provider.
resources_.erase(iter);
// Remove it from our pid map.
PidResourceMap::iterator pid_iter =
pid_to_resources_.find(resource->process_id());
DCHECK(pid_iter != pid_to_resources_.end());
if (pid_iter != pid_to_resources_.end())
pid_to_resources_.erase(pid_iter);
// Finally, delete the resource.
delete resource;
}
void TaskManagerChildProcessResourceProvider::AddToTaskManager(
const content::ChildProcessData& child_process_data) {
TaskManagerChildProcessResource* resource =
new TaskManagerChildProcessResource(
child_process_data.type,
child_process_data.name,
child_process_data.handle,
child_process_data.id);
resources_[child_process_data.handle] = resource;
pid_to_resources_[resource->process_id()] = resource;
task_manager_->AddResource(resource);
}
// The ChildProcessData::Iterator has to be used from the IO thread.
void TaskManagerChildProcessResourceProvider::RetrieveChildProcessData() {
std::vector<content::ChildProcessData> child_processes;
for (BrowserChildProcessHostIterator iter; !iter.Done(); ++iter) {
// Only add processes which are already started, since we need their handle.
if (iter.GetData().handle == base::kNullProcessHandle)
continue;
child_processes.push_back(iter.GetData());
}
// Now notify the UI thread that we have retrieved information about child
// processes.
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(
&TaskManagerChildProcessResourceProvider::ChildProcessDataRetreived,
this, child_processes));
}
// This is called on the UI thread.
void TaskManagerChildProcessResourceProvider::ChildProcessDataRetreived(
const std::vector<content::ChildProcessData>& child_processes) {
for (size_t i = 0; i < child_processes.size(); ++i)
Add(child_processes[i]);
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_TASK_MANAGER_CHILD_PROCESSES_DATA_READY,
content::Source<TaskManagerChildProcessResourceProvider>(this),
content::NotificationService::NoDetails());
}
////////////////////////////////////////////////////////////////////////////////
// TaskManagerExtensionProcessResource class
////////////////////////////////////////////////////////////////////////////////
gfx::ImageSkia* TaskManagerExtensionProcessResource::default_icon_ = NULL;
TaskManagerExtensionProcessResource::TaskManagerExtensionProcessResource(
content::RenderViewHost* render_view_host)
: render_view_host_(render_view_host) {
if (!default_icon_) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
default_icon_ = rb.GetImageSkiaNamed(IDR_PLUGIN);
}
process_handle_ = render_view_host_->GetProcess()->GetHandle();
unique_process_id_ = render_view_host->GetProcess()->GetID();
pid_ = base::GetProcId(process_handle_);
string16 extension_name = UTF8ToUTF16(GetExtension()->name());
DCHECK(!extension_name.empty());
Profile* profile = Profile::FromBrowserContext(
render_view_host->GetProcess()->GetBrowserContext());
int message_id = GetMessagePrefixID(GetExtension()->is_app(), true,
profile->IsOffTheRecord(), false, false);
title_ = l10n_util::GetStringFUTF16(message_id, extension_name);
}
TaskManagerExtensionProcessResource::~TaskManagerExtensionProcessResource() {
}
string16 TaskManagerExtensionProcessResource::GetTitle() const {
return title_;
}
string16 TaskManagerExtensionProcessResource::GetProfileName() const {
return GetProfileNameFromInfoCache(Profile::FromBrowserContext(
render_view_host_->GetProcess()->GetBrowserContext()));
}
gfx::ImageSkia TaskManagerExtensionProcessResource::GetIcon() const {
return *default_icon_;
}
base::ProcessHandle TaskManagerExtensionProcessResource::GetProcess() const {
return process_handle_;
}
int TaskManagerExtensionProcessResource::GetUniqueChildProcessId() const {
return unique_process_id_;
}
TaskManager::Resource::Type
TaskManagerExtensionProcessResource::GetType() const {
return EXTENSION;
}
bool TaskManagerExtensionProcessResource::CanInspect() const {
return true;
}
void TaskManagerExtensionProcessResource::Inspect() const {
DevToolsWindow::OpenDevToolsWindow(render_view_host_);
}
bool TaskManagerExtensionProcessResource::SupportNetworkUsage() const {
return true;
}
void TaskManagerExtensionProcessResource::SetSupportNetworkUsage() {
NOTREACHED();
}
const Extension* TaskManagerExtensionProcessResource::GetExtension() const {
Profile* profile = Profile::FromBrowserContext(
render_view_host_->GetProcess()->GetBrowserContext());
ExtensionProcessManager* process_manager =
extensions::ExtensionSystem::Get(profile)->process_manager();
return process_manager->GetExtensionForRenderViewHost(render_view_host_);
}
bool TaskManagerExtensionProcessResource::IsBackground() const {
WebContents* web_contents =
WebContents::FromRenderViewHost(render_view_host_);
chrome::ViewType view_type = chrome::GetViewType(web_contents);
return view_type == chrome::VIEW_TYPE_EXTENSION_BACKGROUND_PAGE;
}
////////////////////////////////////////////////////////////////////////////////
// TaskManagerExtensionProcessResourceProvider class
////////////////////////////////////////////////////////////////////////////////
TaskManagerExtensionProcessResourceProvider::
TaskManagerExtensionProcessResourceProvider(TaskManager* task_manager)
: task_manager_(task_manager),
updating_(false) {
}
TaskManagerExtensionProcessResourceProvider::
~TaskManagerExtensionProcessResourceProvider() {
}
TaskManager::Resource* TaskManagerExtensionProcessResourceProvider::GetResource(
int origin_pid,
int render_process_host_id,
int routing_id) {
std::map<int, TaskManagerExtensionProcessResource*>::iterator iter =
pid_to_resources_.find(origin_pid);
if (iter != pid_to_resources_.end())
return iter->second;
else
return NULL;
}
void TaskManagerExtensionProcessResourceProvider::StartUpdating() {
DCHECK(!updating_);
updating_ = true;
// Add all the existing extension views from all Profiles, including those
// from incognito split mode.
ProfileManager* profile_manager = g_browser_process->profile_manager();
std::vector<Profile*> profiles(profile_manager->GetLoadedProfiles());
size_t num_default_profiles = profiles.size();
for (size_t i = 0; i < num_default_profiles; ++i) {
if (profiles[i]->HasOffTheRecordProfile()) {
profiles.push_back(profiles[i]->GetOffTheRecordProfile());
}
}
for (size_t i = 0; i < profiles.size(); ++i) {
ExtensionProcessManager* process_manager =
profiles[i]->GetExtensionProcessManager();
if (process_manager) {
const ExtensionProcessManager::ViewSet all_views =
process_manager->GetAllViews();
ExtensionProcessManager::ViewSet::const_iterator jt = all_views.begin();
for (; jt != all_views.end(); ++jt) {
content::RenderViewHost* rvh = *jt;
// Don't add dead extension processes.
if (!rvh->IsRenderViewLive())
continue;
AddToTaskManager(rvh);
}
}
}
// Register for notifications about extension process changes.
registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_VIEW_REGISTERED,
content::NotificationService::AllBrowserContextsAndSources());
registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
content::NotificationService::AllBrowserContextsAndSources());
registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_VIEW_UNREGISTERED,
content::NotificationService::AllBrowserContextsAndSources());
}
void TaskManagerExtensionProcessResourceProvider::StopUpdating() {
DCHECK(updating_);
updating_ = false;
// Unregister for notifications about extension process changes.
registrar_.Remove(
this, chrome::NOTIFICATION_EXTENSION_VIEW_REGISTERED,
content::NotificationService::AllBrowserContextsAndSources());
registrar_.Remove(
this, chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
content::NotificationService::AllBrowserContextsAndSources());
registrar_.Remove(
this, chrome::NOTIFICATION_EXTENSION_VIEW_UNREGISTERED,
content::NotificationService::AllBrowserContextsAndSources());
// Delete all the resources.
STLDeleteContainerPairSecondPointers(resources_.begin(), resources_.end());
resources_.clear();
pid_to_resources_.clear();
}
void TaskManagerExtensionProcessResourceProvider::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
switch (type) {
case chrome::NOTIFICATION_EXTENSION_VIEW_REGISTERED:
AddToTaskManager(
content::Details<content::RenderViewHost>(details).ptr());
break;
case chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED:
RemoveFromTaskManager(
content::Details<extensions::ExtensionHost>(details).ptr()->
render_view_host());
break;
case chrome::NOTIFICATION_EXTENSION_VIEW_UNREGISTERED:
RemoveFromTaskManager(
content::Details<content::RenderViewHost>(details).ptr());
break;
default:
NOTREACHED() << "Unexpected notification.";
return;
}
}
bool TaskManagerExtensionProcessResourceProvider::
IsHandledByThisProvider(content::RenderViewHost* render_view_host) {
// Don't add WebContents (those are handled by
// TaskManagerTabContentsResourceProvider) or background contents (handled
// by TaskManagerBackgroundResourceProvider).
WebContents* web_contents = WebContents::FromRenderViewHost(render_view_host);
chrome::ViewType view_type = chrome::GetViewType(web_contents);
#if defined(USE_ASH)
return (view_type != chrome::VIEW_TYPE_TAB_CONTENTS &&
view_type != chrome::VIEW_TYPE_BACKGROUND_CONTENTS);
#else
return (view_type != chrome::VIEW_TYPE_TAB_CONTENTS &&
view_type != chrome::VIEW_TYPE_BACKGROUND_CONTENTS &&
view_type != chrome::VIEW_TYPE_PANEL);
#endif // USE_ASH
}
void TaskManagerExtensionProcessResourceProvider::AddToTaskManager(
content::RenderViewHost* render_view_host) {
if (!IsHandledByThisProvider(render_view_host))
return;
TaskManagerExtensionProcessResource* resource =
new TaskManagerExtensionProcessResource(render_view_host);
DCHECK(resources_.find(render_view_host) == resources_.end());
resources_[render_view_host] = resource;
pid_to_resources_[resource->process_id()] = resource;
task_manager_->AddResource(resource);
}
void TaskManagerExtensionProcessResourceProvider::RemoveFromTaskManager(
content::RenderViewHost* render_view_host) {
if (!updating_)
return;
std::map<content::RenderViewHost*, TaskManagerExtensionProcessResource*>
::iterator iter = resources_.find(render_view_host);
if (iter == resources_.end())
return;
// Remove the resource from the Task Manager.
TaskManagerExtensionProcessResource* resource = iter->second;
task_manager_->RemoveResource(resource);
// Remove it from the provider.
resources_.erase(iter);
// Remove it from our pid map.
std::map<int, TaskManagerExtensionProcessResource*>::iterator pid_iter =
pid_to_resources_.find(resource->process_id());
DCHECK(pid_iter != pid_to_resources_.end());
if (pid_iter != pid_to_resources_.end())
pid_to_resources_.erase(pid_iter);
// Finally, delete the resource.
delete resource;
}
////////////////////////////////////////////////////////////////////////////////
// TaskManagerBrowserProcessResource class
////////////////////////////////////////////////////////////////////////////////
gfx::ImageSkia* TaskManagerBrowserProcessResource::default_icon_ = NULL;
TaskManagerBrowserProcessResource::TaskManagerBrowserProcessResource()
: title_() {
int pid = base::GetCurrentProcId();
bool success = base::OpenPrivilegedProcessHandle(pid, &process_);
DCHECK(success);
#if defined(OS_WIN)
if (!default_icon_) {
HICON icon = GetAppIcon();
if (icon) {
scoped_ptr<SkBitmap> bitmap(IconUtil::CreateSkBitmapFromHICON(icon));
default_icon_ = new gfx::ImageSkia(*bitmap);
}
}
#elif defined(OS_POSIX) && !defined(OS_MACOSX)
if (!default_icon_) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
default_icon_ = rb.GetImageSkiaNamed(IDR_PRODUCT_LOGO_16);
}
#elif defined(OS_MACOSX)
if (!default_icon_) {
// IDR_PRODUCT_LOGO_16 doesn't quite look like chrome/mac's icns icon. Load
// the real app icon (requires a nsimage->image_skia->nsimage
// conversion :-().
default_icon_ = new gfx::ImageSkia(gfx::ApplicationIconAtSize(16));
}
#else
// TODO(port): Port icon code.
NOTIMPLEMENTED();
#endif // defined(OS_WIN)
}
TaskManagerBrowserProcessResource::~TaskManagerBrowserProcessResource() {
base::CloseProcessHandle(process_);
}
// TaskManagerResource methods:
string16 TaskManagerBrowserProcessResource::GetTitle() const {
if (title_.empty()) {
title_ = l10n_util::GetStringUTF16(IDS_TASK_MANAGER_WEB_BROWSER_CELL_TEXT);
}
return title_;
}
string16 TaskManagerBrowserProcessResource::GetProfileName() const {
return string16();
}
gfx::ImageSkia TaskManagerBrowserProcessResource::GetIcon() const {
return *default_icon_;
}
size_t TaskManagerBrowserProcessResource::SqliteMemoryUsedBytes() const {
return static_cast<size_t>(sqlite3_memory_used());
}
base::ProcessHandle TaskManagerBrowserProcessResource::GetProcess() const {
return base::GetCurrentProcessHandle(); // process_;
}
int TaskManagerBrowserProcessResource::GetUniqueChildProcessId() const {
return 0;
}
TaskManager::Resource::Type TaskManagerBrowserProcessResource::GetType() const {
return BROWSER;
}
bool TaskManagerBrowserProcessResource::SupportNetworkUsage() const {
return true;
}
void TaskManagerBrowserProcessResource::SetSupportNetworkUsage() {
NOTREACHED();
}
bool TaskManagerBrowserProcessResource::ReportsSqliteMemoryUsed() const {
return true;
}
// BrowserProcess uses v8 for proxy resolver in certain cases.
bool TaskManagerBrowserProcessResource::ReportsV8MemoryStats() const {
const CommandLine* command_line = CommandLine::ForCurrentProcess();
bool using_v8 = !command_line->HasSwitch(switches::kWinHttpProxyResolver);
if (using_v8 && command_line->HasSwitch(switches::kSingleProcess)) {
using_v8 = false;
}
return using_v8;
}
size_t TaskManagerBrowserProcessResource::GetV8MemoryAllocated() const {
v8::HeapStatistics stats;
v8::V8::GetHeapStatistics(&stats);
return stats.total_heap_size();
}
size_t TaskManagerBrowserProcessResource::GetV8MemoryUsed() const {
v8::HeapStatistics stats;
v8::V8::GetHeapStatistics(&stats);
return stats.used_heap_size();
}
////////////////////////////////////////////////////////////////////////////////
// TaskManagerBrowserProcessResourceProvider class
////////////////////////////////////////////////////////////////////////////////
TaskManagerBrowserProcessResourceProvider::
TaskManagerBrowserProcessResourceProvider(TaskManager* task_manager)
: updating_(false),
task_manager_(task_manager) {
}
TaskManagerBrowserProcessResourceProvider::
~TaskManagerBrowserProcessResourceProvider() {
}
TaskManager::Resource* TaskManagerBrowserProcessResourceProvider::GetResource(
int origin_pid,
int render_process_host_id,
int routing_id) {
if (origin_pid || render_process_host_id != -1) {
return NULL;
}
return &resource_;
}
void TaskManagerBrowserProcessResourceProvider::StartUpdating() {
task_manager_->AddResource(&resource_);
}
void TaskManagerBrowserProcessResourceProvider::StopUpdating() {
}
| 60,491 | 17,448 |
// Copyright (C) 2016 Vicente J. Botet Escriba
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef JASEL_EXAMPLE_FRAMEWORK_MEM_USAGE_HPP
#define JASEL_EXAMPLE_FRAMEWORK_MEM_USAGE_HPP
#if __cplusplus >= 201402L
#include <type_traits>
#include <experimental/meta.hpp>
#include <cstddef>
// mem_usage_able/mem_usage.hpp
namespace std
{
namespace experimental
{
inline namespace fundamental_v3
{
namespace mem_usage_able
{
template <typename T, typename Enabler=void>
struct traits : traits<T, meta::when<true>> {};
template <typename R, bool B>
struct traits<R, meta::when<B>>
{
template <typename T>
static constexpr size_t apply(T&& v) = delete;
};
template <typename R>
struct traits<R, meta::when<std::is_trivial<R>::value>>
{
template <typename T>
static constexpr size_t apply(T&& ) noexcept { return sizeof ( remove_cv_t<remove_reference_t<T>> ); }
};
template <typename T>
constexpr auto mem_usage(T&& v) noexcept -> decltype(traits<remove_cv_t<remove_reference_t<T>>>::apply(std::forward<T>(v)))
{
return traits<remove_cv_t<remove_reference_t<T>>>::apply(std::forward<T>(v));
}
template <typename R>
struct traits<R*>
{
template <typename T>
static constexpr auto apply(T* v) noexcept -> decltype( mem_usage_able::mem_usage ( *v ) )
{
return sizeof v + (v?mem_usage_able::mem_usage ( *v ):0);
}
};
}
}
}
}
#endif
#endif
| 1,528 | 591 |
/**
*\file
* TestBufferView.h
*\author
* Sylvain Doremus
*/
#ifndef ___D3D11Renderer_BufferView_HPP___
#define ___D3D11Renderer_BufferView_HPP___
#pragma once
#include "renderer/D3D11Renderer/D3D11RendererPrerequisites.hpp"
namespace ashes::d3d11
{
class BufferView
{
public:
BufferView( VkDevice device
, VkBufferViewCreateInfo createInfo );
~BufferView();
inline ID3D11ShaderResourceView * getView()const
{
return m_view;
}
inline VkDevice getDevice()const
{
return m_device;
}
private:
VkDevice m_device;
VkBufferViewCreateInfo m_createInfo;
ID3D11ShaderResourceView * m_view;
};
}
#endif
| 634 | 275 |
/*
* 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
*
* 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.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/internal/ValidationContextImpl.hpp>
#include <xercesc/framework/XMLRefInfo.hpp>
#include <xercesc/validators/DTD/DTDEntityDecl.hpp>
#include <xercesc/validators/datatype/InvalidDatatypeValueException.hpp>
#include <xercesc/validators/schema/NamespaceScope.hpp>
#include <xercesc/internal/ElemStack.hpp>
#include <xercesc/internal/XMLScanner.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Constructor and Destructor
// ---------------------------------------------------------------------------
ValidationContextImpl::~ValidationContextImpl()
{
if (fIdRefList)
delete fIdRefList;
}
ValidationContextImpl::ValidationContextImpl(MemoryManager* const manager)
:ValidationContext(manager)
,fIdRefList(0)
,fEntityDeclPool(0)
,fToCheckIdRefList(true)
,fValidatingMemberType(0)
,fElemStack(0)
,fScanner(0)
,fNamespaceScope(0)
{
fIdRefList = new (fMemoryManager) RefHashTableOf<XMLRefInfo>(109, fMemoryManager);
}
/**
* IdRefList
*
*/
RefHashTableOf<XMLRefInfo>* ValidationContextImpl::getIdRefList() const
{
return fIdRefList;
}
void ValidationContextImpl::setIdRefList(RefHashTableOf<XMLRefInfo>* const newIdRefList)
{
if (fIdRefList)
delete fIdRefList;
fIdRefList = newIdRefList;
}
void ValidationContextImpl::clearIdRefList()
{
if (fIdRefList)
fIdRefList->removeAll();
}
void ValidationContextImpl::addId(const XMLCh * const content)
{
if (!fIdRefList || !fToCheckIdRefList)
return;
XMLRefInfo* idEntry = fIdRefList->get(content);
if (idEntry)
{
if (idEntry->getDeclared())
{
ThrowXMLwithMemMgr1(InvalidDatatypeValueException
, XMLExcepts::VALUE_ID_Not_Unique
, content
, fMemoryManager);
}
}
else
{
idEntry = new (fMemoryManager) XMLRefInfo(content, false, false, fMemoryManager);
fIdRefList->put((void*)idEntry->getRefName(), idEntry);
}
//
// Mark it declared
//
idEntry->setDeclared(true);
}
void ValidationContextImpl::addIdRef(const XMLCh * const content)
{
if (!fIdRefList || !fToCheckIdRefList)
return;
XMLRefInfo* idEntry = fIdRefList->get(content);
if (!idEntry)
{
idEntry = new (fMemoryManager) XMLRefInfo(content, false, false, fMemoryManager);
fIdRefList->put((void*)idEntry->getRefName(), idEntry);
}
//
// Mark it used
//
idEntry->setUsed(true);
}
void ValidationContextImpl::toCheckIdRefList(bool toCheck)
{
fToCheckIdRefList = toCheck;
}
/**
* EntityDeclPool
*
*/
const NameIdPool<DTDEntityDecl>* ValidationContextImpl::getEntityDeclPool() const
{
return fEntityDeclPool;
}
const NameIdPool<DTDEntityDecl>* ValidationContextImpl::setEntityDeclPool(const NameIdPool<DTDEntityDecl>* const newEntityDeclPool)
{
// we don't own it so we return the existing one for the owner to delete
const NameIdPool<DTDEntityDecl>* tempPool = fEntityDeclPool;
fEntityDeclPool = newEntityDeclPool;
return tempPool;
}
void ValidationContextImpl::checkEntity(const XMLCh * const content) const
{
if (fEntityDeclPool)
{
const DTDEntityDecl* decl = fEntityDeclPool->getByKey(content);
if (!decl || !decl->isUnparsed())
{
ThrowXMLwithMemMgr1(InvalidDatatypeValueException
, XMLExcepts::VALUE_ENTITY_Invalid
, content
, fMemoryManager);
}
}
else
{
ThrowXMLwithMemMgr1
(
InvalidDatatypeValueException
, XMLExcepts::VALUE_ENTITY_Invalid
, content
, fMemoryManager
);
}
}
/* QName
*/
bool ValidationContextImpl::isPrefixUnknown(XMLCh* prefix) {
bool unknown = false;
if (XMLString::equals(prefix, XMLUni::fgXMLNSString)) {
return true;
}
else if (!XMLString::equals(prefix, XMLUni::fgXMLString)) {
if(fElemStack && !fElemStack->isEmpty())
fElemStack->mapPrefixToURI(prefix, unknown);
else if(fNamespaceScope)
unknown = (fNamespaceScope->getNamespaceForPrefix(prefix)==fNamespaceScope->getEmptyNamespaceId());
}
return unknown;
}
const XMLCh* ValidationContextImpl::getURIForPrefix(XMLCh* prefix) {
bool unknown = false;
unsigned int uriId = 0;
if(fElemStack)
uriId = fElemStack->mapPrefixToURI(prefix, unknown);
else if(fNamespaceScope)
{
uriId = fNamespaceScope->getNamespaceForPrefix(prefix);
unknown = uriId == fNamespaceScope->getEmptyNamespaceId();
}
if (!unknown)
return fScanner->getURIText(uriId);
return XMLUni::fgZeroLenString;
}
XERCES_CPP_NAMESPACE_END
| 5,800 | 1,797 |
// -*- C++ -*-
// $Id: OS_NS_math.inl 1861 2011-08-31 16:18:08Z mesnierp $
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
namespace ACE_OS {
ACE_INLINE double
log2 (double x)
{
return ace_log2_helper (x);
}
} // ACE_OS namespace
ACE_END_VERSIONED_NAMESPACE_DECL
| 267 | 137 |
/*
* Anti-doublon
*/
#ifndef __OPENKN_MATH__MATH_IO_HPP__
#define __OPENKN_MATH__MATH_IO_HPP__
/*
* External Includes
*/
#include <cstring>
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include "Eigen/Dense"
using namespace Eigen;
/*
* Namespace
*/
namespace kn {
/**
* \cond
* \brief ignore the comments and read the header on a matrix file if specified; the user should not use this function.
* \param matrixFile the input matrix ifstream
* \return true if the matrix format is spefifyed, false otherwise
* \throw MathException invalid format
*/
bool readMatrixHeader(std::ifstream &matrixFile, unsigned int &row, unsigned int &column);
/// \endcond
/**
* \cond
* \brief ignore the comments and read the header on a matrix file if specified; the user should not use this function.
* \param matrixFile the input matrix ifstream
* \return true if the matrix format is spefifyed, false otherwise
* \throw MathException invalid format
*/
bool readMatrixHeader(std::ifstream &matrixFile, unsigned int &mat);
/// \endcond
/**
* \brief Load a Matrix from a file. The format is : some optional comments begining by '#', a optional header writing "row " and the number of rows, in the next line, "column " and the number of columns, and then, line by line, the matrix content.
* \param M the Matrix to be loaded
* \param fileName the name of the file to open
* \throw MathException matrix size is incorrect / error opening file / invalid format
*/
template <class EigenMatrix>
void loadMatrix(EigenMatrix &M, const std::string &fileName){
// open the file
std::ifstream matrixFile(fileName.c_str());
if(!matrixFile.is_open()){
std::cerr << "error opening file : " << fileName << std::endl;
exit(0);
}
// read header
unsigned int row = 0;
unsigned int column = 0;
bool header = readMatrixHeader(matrixFile,row,column);
// read the data
if(header) readMatrixFromHeader(M,matrixFile,row,column);
else readMatrix(M,matrixFile);
// close
matrixFile.close();
}
/**
* \cond
* \brief read the content of a Matrix from the header information (row,col); the user should not use this function.
* \param M the Matrix to be filled
* \param matrixFile the input matrix ifstream
* \param row the expected matrix row number
* \param column the expected matrix column number
* \throw MathException incompatible matrix size
*/
template <class EigenMatrix>
void readMatrixFromHeader(EigenMatrix &M,
std::ifstream &matrixFile,
const unsigned int &row,
const unsigned int &column) {
// if the matrix is already build
if((unsigned int)M.rows() != row || (unsigned int)M.cols() != column)
M.resize(row,column);
// read the matrix
for(unsigned int i=0; i<row; ++i)
for(unsigned int j=0; j<column; ++j)
matrixFile >> M(i,j);
}
/// \endcond
/**
* \cond
* \brief read the content of a Matrix without any size information (row,col); the user should not use this function.
* \param M the Matrix to be filled
* \param matrixFile the input matrix ifstream
* \throw MathException incompatible matrix size / invalid matrix file
*/
template <class EigenMatrix>
void readMatrix(EigenMatrix &M, std::ifstream &matrixFile){
unsigned int row = 0;
int column = -1; // unknown while you didn't read a line
std::vector<double> content;
std::string stringContent;
// first read the matrix in a std::vector to check the consistency of the data
do{ // for every line
std::getline(matrixFile,stringContent);
std::istringstream readContent(stringContent, std::istringstream::in);
unsigned int index = 0;
while(!readContent.eof() && stringContent != ""){ // for every element of a line
double value;
readContent >> value;
content.push_back(value);
index++;
}
// remove the eof
//content.erase(content.end()-1);
//index--;
if(column == -1 && index != 0){ // 1st line : find 'column'
column = index;
row++;
}else{
if(index != 0){ // check empty line or invalid column
if(column != (int)index ){
std::cerr << "readMatrix : invalid matrix file" << std::endl;
exit(0);
}else row++;
}else{
//Matrix reading complete (empty line found)
break;
}
}
}
while(!matrixFile.eof());
if(row==0 && column==-1) return;
// if the matrix is already build
if((unsigned int)M.rows() != row || M.cols() != column)
M.resize(row,column);
// copy the data
for(unsigned int i=0; i<row; ++i)
for(int j=0; j<column; ++j)
M(i,j) = content[i*column+j];
//std::copy(content.begin(), content.end(), M.data());
}
/// \endcond
/**
* \brief Export a Matrix in a file. The format is : some optional comments begining by '#', a optional header writing "row " and the number of rows, in the next line, "column " and the number of columns, and then, line by line, the matrix content.
* \param M the Matrix to be exported
* \param fileName the name of the target file
* \param headerMode if true, write the number of row and colums before the data, else write directly the data
* \param comments add some comments at the begining of the file, the caracter "#" is automatically added
* \throw MathException error opening file
*/
template <class EigenMatrix>
void saveMatrix(const EigenMatrix &M,
const std::string &fileName,
const bool headerMode = false,
const std::string &comments = "") {
// open the file
std::ofstream matrixFile(fileName.c_str());
if(!matrixFile.is_open()){
std::cerr << "error opening file : " << fileName << std::endl;
exit(0);
}
// write comments
if(comments != "")
matrixFile << "# " << comments << std::endl;
// write header
if(headerMode)
matrixFile << "row " << M.rows() << std::endl
<< "col " << M.cols() << std::endl;
// additional line
if(comments != "" || headerMode)
matrixFile << std::endl;
// write matrix content
for (unsigned int i=0; i<(unsigned int)M.rows(); ++i){
for (unsigned int j=0; j<(unsigned int)M.cols(); ++j)
matrixFile << M(i,j) << " ";
matrixFile << std::endl;
}
// close file
matrixFile.close();
}
/*
* End of Namespace
*/
}
/*
* End of Anti-doublon
*/
#endif
| 6,734 | 2,012 |
/***********************************************************************
created: 13/4/2004
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS 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 "CEGUI/widgets/Scrollbar.h"
#include "CEGUI/widgets/Thumb.h"
#include "CEGUI/WindowManager.h"
#include "CEGUI/Exceptions.h"
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
const String Scrollbar::EventNamespace("Scrollbar");
const String Scrollbar::WidgetTypeName("CEGUI/Scrollbar");
//----------------------------------------------------------------------------//
const String Scrollbar::EventScrollPositionChanged("ScrollPositionChanged");
const String Scrollbar::EventThumbTrackStarted("ThumbTrackStarted");
const String Scrollbar::EventThumbTrackEnded("ThumbTrackEnded");
const String Scrollbar::EventScrollConfigChanged("ScrollConfigChanged");
//----------------------------------------------------------------------------//
const String Scrollbar::ThumbName("__auto_thumb__");
const String Scrollbar::IncreaseButtonName("__auto_incbtn__");
const String Scrollbar::DecreaseButtonName("__auto_decbtn__");
//----------------------------------------------------------------------------//
ScrollbarWindowRenderer::ScrollbarWindowRenderer(const String& name) :
WindowRenderer(name, Scrollbar::EventNamespace)
{
}
//----------------------------------------------------------------------------//
Scrollbar::Scrollbar(const String& type, const String& name) :
Window(type, name),
d_documentSize(1.0f),
d_pageSize(0.0f),
d_stepSize(1.0f),
d_overlapSize(0.0f),
d_position(0.0f),
d_endLockPosition(false)
{
addScrollbarProperties();
}
//----------------------------------------------------------------------------//
Scrollbar::~Scrollbar(void)
{
}
//----------------------------------------------------------------------------//
void Scrollbar::initialiseComponents()
{
// Set up thumb
Thumb* const t = getThumb();
t->subscribeEvent(Thumb::EventThumbPositionChanged,
Event::Subscriber(&CEGUI::Scrollbar::handleThumbMoved,
this));
t->subscribeEvent(Thumb::EventThumbTrackStarted,
Event::Subscriber(&CEGUI::Scrollbar::handleThumbTrackStarted,
this));
t->subscribeEvent(Thumb::EventThumbTrackEnded,
Event::Subscriber(&CEGUI::Scrollbar::handleThumbTrackEnded,
this));
// set up Increase button
getIncreaseButton()->
subscribeEvent(PushButton::EventCursorPressHold,
Event::Subscriber(&CEGUI::Scrollbar::handleIncreaseClicked,
this));
// set up Decrease button
getDecreaseButton()->
subscribeEvent(PushButton::EventCursorPressHold,
Event::Subscriber(&CEGUI::Scrollbar::handleDecreaseClicked,
this));
// do initial layout
Window::initialiseComponents();
}
//----------------------------------------------------------------------------//
void Scrollbar::setDocumentSize(float document_size)
{
if (d_documentSize != document_size)
{
const bool reset_max_position = d_endLockPosition && isAtEnd();
d_documentSize = document_size;
if (reset_max_position)
setScrollPosition(getMaxScrollPosition());
else
updateThumb();
WindowEventArgs args(this);
onScrollConfigChanged(args);
}
}
//----------------------------------------------------------------------------//
void Scrollbar::setPageSize(float page_size)
{
if (d_pageSize != page_size)
{
const bool reset_max_position = d_endLockPosition && isAtEnd();
d_pageSize = page_size;
if (reset_max_position)
setScrollPosition(getMaxScrollPosition());
else
updateThumb();
WindowEventArgs args(this);
onScrollConfigChanged(args);
}
}
//----------------------------------------------------------------------------//
void Scrollbar::setStepSize(float step_size)
{
if (d_stepSize != step_size)
{
d_stepSize = step_size;
WindowEventArgs args(this);
onScrollConfigChanged(args);
}
}
//----------------------------------------------------------------------------//
void Scrollbar::setOverlapSize(float overlap_size)
{
if (d_overlapSize != overlap_size)
{
d_overlapSize = overlap_size;
WindowEventArgs args(this);
onScrollConfigChanged(args);
}
}
//----------------------------------------------------------------------------//
void Scrollbar::setScrollPosition(float position)
{
const bool modified = setScrollPosition_impl(position);
updateThumb();
// notification if required
if (modified)
{
WindowEventArgs args(this);
onScrollPositionChanged(args);
}
}
//----------------------------------------------------------------------------//
bool Scrollbar::validateWindowRenderer(const WindowRenderer* renderer) const
{
return dynamic_cast<const ScrollbarWindowRenderer*>(renderer) != nullptr;
}
//----------------------------------------------------------------------------//
void Scrollbar::onScrollPositionChanged(WindowEventArgs& e)
{
fireEvent(EventScrollPositionChanged, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Scrollbar::onThumbTrackStarted(WindowEventArgs& e)
{
fireEvent(EventThumbTrackStarted, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Scrollbar::onThumbTrackEnded(WindowEventArgs& e)
{
fireEvent(EventThumbTrackEnded, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Scrollbar::onScrollConfigChanged(WindowEventArgs& e)
{
performChildLayout(false, false);
fireEvent(EventScrollConfigChanged, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Scrollbar::onCursorPressHold(CursorInputEventArgs& e)
{
// base class processing
Window::onCursorPressHold(e);
if (e.source != CursorInputSource::Left)
return;
const float adj = getAdjustDirectionFromPoint(e.position);
if (adj > 0)
scrollForwardsByPage();
else if (adj < 0)
scrollBackwardsByPage();
++e.handled;
}
//----------------------------------------------------------------------------//
void Scrollbar::onScroll(CursorInputEventArgs& e)
{
// base class processing
Window::onScroll(e);
// scroll by vertical scroll * stepSize
setScrollPosition(d_position + d_stepSize * -e.scroll);
// ensure the message does not go to our parent.
++e.handled;
}
//----------------------------------------------------------------------------//
bool Scrollbar::handleThumbMoved(const EventArgs&)
{
// adjust scroll bar position as required.
setScrollPosition(getValueFromThumb());
return true;
}
//----------------------------------------------------------------------------//
bool Scrollbar::handleIncreaseClicked(const EventArgs& e)
{
if (static_cast<const CursorInputEventArgs&>(e).source != CursorInputSource::Left)
return false;
scrollForwardsByStep();
return true;
}
//----------------------------------------------------------------------------//
bool Scrollbar::handleDecreaseClicked(const EventArgs& e)
{
if (static_cast<const CursorInputEventArgs&>(e).source != CursorInputSource::Left)
return false;
scrollBackwardsByStep();
return true;
}
//----------------------------------------------------------------------------//
bool Scrollbar::handleThumbTrackStarted(const EventArgs&)
{
// simply trigger our own version of this event
WindowEventArgs args(this);
onThumbTrackStarted(args);
return true;
}
//----------------------------------------------------------------------------//
bool Scrollbar::handleThumbTrackEnded(const EventArgs&)
{
// simply trigger our own version of this event
WindowEventArgs args(this);
onThumbTrackEnded(args);
return true;
}
//----------------------------------------------------------------------------//
void Scrollbar::addScrollbarProperties(void)
{
const String& propertyOrigin = WidgetTypeName;
CEGUI_DEFINE_PROPERTY(Scrollbar, float,
"DocumentSize", "Property to get/set the document size for the Scrollbar. Value is a float.",
&Scrollbar::setDocumentSize, &Scrollbar::getDocumentSize, 1.0f
);
CEGUI_DEFINE_PROPERTY(Scrollbar, float,
"PageSize", "Property to get/set the page size for the Scrollbar. Value is a float.",
&Scrollbar::setPageSize, &Scrollbar::getPageSize, 0.0f
);
CEGUI_DEFINE_PROPERTY(Scrollbar, float,
"StepSize", "Property to get/set the step size for the Scrollbar. Value is a float.",
&Scrollbar::setStepSize, &Scrollbar::getStepSize, 1.0f
);
CEGUI_DEFINE_PROPERTY(Scrollbar, float,
"OverlapSize", "Property to get/set the overlap size for the Scrollbar. Value is a float.",
&Scrollbar::setOverlapSize, &Scrollbar::getOverlapSize, 0.0f
);
CEGUI_DEFINE_PROPERTY(Scrollbar, float,
"ScrollPosition", "Property to get/set the scroll position of the Scrollbar. Value is a float.",
&Scrollbar::setScrollPosition, &Scrollbar::getScrollPosition, 0.0f
);
CEGUI_DEFINE_PROPERTY(Scrollbar, float,
"UnitIntervalScrollPosition",
"Property to access the scroll position of the Scrollbar as a value in "
"the interval [0, 1]. Value is a float.",
&Scrollbar::setUnitIntervalScrollPosition,
&Scrollbar::getUnitIntervalScrollPosition, 0.0f
);
CEGUI_DEFINE_PROPERTY(Scrollbar, bool,
"EndLockEnabled", "Property to get/set the 'end lock' mode setting for the Scrollbar. "
"Value is either \"true\" or \"false\".",
&Scrollbar::setEndLockEnabled, &Scrollbar::isEndLockEnabled, false
);
}
//----------------------------------------------------------------------------//
void Scrollbar::banPropertiesForAutoWindow()
{
Window::banPropertiesForAutoWindow();
banPropertyFromXML("DocumentSize");
banPropertyFromXML("PageSize");
banPropertyFromXML("StepSize");
banPropertyFromXML("OverlapSize");
banPropertyFromXML("ScrollPosition");
banPropertyFromXML("Visible");
}
//----------------------------------------------------------------------------//
PushButton* Scrollbar::getIncreaseButton() const
{
return static_cast<PushButton*>(getChild(IncreaseButtonName));
}
//----------------------------------------------------------------------------//
PushButton* Scrollbar::getDecreaseButton() const
{
return static_cast<PushButton*>(getChild(DecreaseButtonName));
}
//----------------------------------------------------------------------------//
Thumb* Scrollbar::getThumb() const
{
return static_cast<Thumb*>(getChild(ThumbName));
}
//----------------------------------------------------------------------------//
void Scrollbar::updateThumb(void)
{
if (!d_windowRenderer)
throw InvalidRequestException(
"This function must be implemented by the window renderer object "
"(no window renderer is assigned.)");
static_cast<ScrollbarWindowRenderer*>(d_windowRenderer)->updateThumb();
}
//----------------------------------------------------------------------------//
float Scrollbar::getValueFromThumb(void) const
{
if (!d_windowRenderer)
throw InvalidRequestException(
"This function must be implemented by the window renderer object "
"(no window renderer is assigned.)");
return static_cast<ScrollbarWindowRenderer*>(
d_windowRenderer)->getValueFromThumb();
}
//----------------------------------------------------------------------------//
float Scrollbar::getAdjustDirectionFromPoint(const glm::vec2& pt) const
{
if (!d_windowRenderer)
throw InvalidRequestException(
"This function must be implemented by the window renderer object "
"(no window renderer is assigned.)");
return static_cast<ScrollbarWindowRenderer*>(
d_windowRenderer)->getAdjustDirectionFromPoint(pt);
}
//----------------------------------------------------------------------------//
bool Scrollbar::setScrollPosition_impl(const float position)
{
const float old_pos = d_position;
const float max_pos = getMaxScrollPosition();
// limit position to valid range: 0 <= position <= max_pos
d_position = (position >= 0) ?
((position <= max_pos) ?
position :
max_pos) :
0.0f;
return d_position != old_pos;
}
//----------------------------------------------------------------------------//
void Scrollbar::setConfig(const float* const document_size,
const float* const page_size,
const float* const step_size,
const float* const overlap_size,
const float* const position)
{
const bool reset_max_position = d_endLockPosition && isAtEnd();
bool config_changed = false;
bool position_changed = false;
if (document_size && (d_documentSize != *document_size))
{
d_documentSize = *document_size;
config_changed = true;
}
if (page_size && (d_pageSize != *page_size))
{
d_pageSize = *page_size;
config_changed = true;
}
if (step_size && (d_stepSize != *step_size))
{
d_stepSize = *step_size;
config_changed = true;
}
if (overlap_size && (d_overlapSize != *overlap_size))
{
d_overlapSize = *overlap_size;
config_changed = true;
}
if (position)
position_changed = setScrollPosition_impl(*position);
else if (reset_max_position)
position_changed = setScrollPosition_impl(getMaxScrollPosition());
// _always_ update the thumb to keep things in sync. (though this
// can cause a double-trigger of EventScrollPositionChanged, which
// also happens with setScrollPosition anyway).
updateThumb();
//
// Fire appropriate events based on actions we took.
//
if (config_changed)
{
WindowEventArgs args(this);
onScrollConfigChanged(args);
}
if (position_changed)
{
WindowEventArgs args(this);
onScrollPositionChanged(args);
}
}
//----------------------------------------------------------------------------//
float Scrollbar::getMaxScrollPosition() const
{
// max position is (docSize - pageSize)
// but must be at least 0 (in case doc size is very small)
return std::max((d_documentSize - d_pageSize), 0.0f);
}
//----------------------------------------------------------------------------//
bool Scrollbar::isAtEnd() const
{
return d_position >= getMaxScrollPosition();
}
//----------------------------------------------------------------------------//
void Scrollbar::setEndLockEnabled(const bool enabled)
{
d_endLockPosition = enabled;
}
//----------------------------------------------------------------------------//
bool Scrollbar::isEndLockEnabled() const
{
return d_endLockPosition;
}
//----------------------------------------------------------------------------//
float Scrollbar::getUnitIntervalScrollPosition() const
{
const float range = d_documentSize - d_pageSize;
return (range > 0) ? d_position / range : 0.0f;
}
//----------------------------------------------------------------------------//
void Scrollbar::setUnitIntervalScrollPosition(float position)
{
const float range = d_documentSize - d_pageSize;
setScrollPosition(range > 0 ? position * range : 0.0f);
}
//----------------------------------------------------------------------------//
void Scrollbar::scrollForwardsByStep()
{
setScrollPosition(d_position + d_stepSize);
}
//----------------------------------------------------------------------------//
void Scrollbar::scrollBackwardsByStep()
{
setScrollPosition(d_position - d_stepSize);
}
//----------------------------------------------------------------------------//
void Scrollbar::scrollForwardsByPage()
{
setScrollPosition(d_position + (d_pageSize - d_overlapSize));
}
//----------------------------------------------------------------------------//
void Scrollbar::scrollBackwardsByPage()
{
setScrollPosition(d_position - (d_pageSize - d_overlapSize));
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
| 18,274 | 4,679 |
/*
SequentialCounter.cpp
Li-Yi Wei
07/07/2007
*/
#include "SequentialCounter.hpp"
SequentialCounter::SequentialCounter(void)
{
// nothing else to do
}
SequentialCounter::SequentialCounter(const int dimension, const int digit_min, const int digit_max) : Counter(dimension), _digit_min(dimension), _digit_max(dimension), _value(dimension)
{
for(int i = 0; i < dimension; i++)
{
_digit_min[i] = digit_min;
_digit_max[i] = digit_max;
}
Reset();
}
SequentialCounter::SequentialCounter(const int dimension, const vector<int> & digit_min, const vector<int> & digit_max) : Counter(dimension), _digit_min(digit_min), _digit_max(digit_max), _value(dimension)
{
Reset();
}
SequentialCounter::~SequentialCounter(void)
{
// nothing to do
}
int SequentialCounter::Reset(void)
{
for(unsigned int i = 0; i < _value.size(); i++)
{
_value[i] = _digit_min[i];
}
return 1;
}
int SequentialCounter::Get(vector<int> & value) const
{
value = _value;
return 1;
}
int SequentialCounter::Next(void)
{
unsigned int which_dim = 0;
for(which_dim = 0; which_dim < _value.size(); which_dim++)
{
if(_value[which_dim] < _digit_max[which_dim])
{
_value[which_dim]++;
for(unsigned int i = 0; i < which_dim; i++)
{
_value[i] = _digit_min[i];
}
break;
}
}
return (which_dim < _value.size());
}
int SequentialCounter::Reset(const int dimension, const int digit_min, const int digit_max)
{
return Reset(dimension, vector<int>(dimension, digit_min), vector<int>(dimension, digit_max));
}
int SequentialCounter::Reset(const int dimension, const vector<int> & digit_min, const vector<int> & digit_max)
{
if(! Counter::Reset(dimension))
{
return 0;
}
else
{
_value.resize(dimension);
_digit_min = digit_min;
_digit_max = digit_max;
return Reset();
}
}
| 2,008 | 707 |
/*
* Copyright (c) 2020 Andreas Pohl
* Licensed under MIT (https://github.com/apohl79/audiogridder/blob/master/COPYING)
*
* Author: Andreas Pohl
*/
#include "App.hpp"
#include <signal.h>
#include "Server.hpp"
namespace e47 {
App::App() : m_menuWindow(this) {}
void App::initialise(const String& commandLineParameters) {
m_logger = FileLogger::createDateStampedLogger(getApplicationName(), "Main_", ".log", "");
Logger::setCurrentLogger(m_logger);
signal(SIGPIPE, SIG_IGN);
showSplashWindow();
setSplashInfo("Starting server...");
m_server = std::make_unique<Server>();
m_server->startThread();
}
void App::shutdown() {
m_server->signalThreadShouldExit();
m_server->waitForThreadToExit(1000);
Logger::setCurrentLogger(nullptr);
delete m_logger;
}
void App::restartServer() {
hideEditor();
hidePluginList();
hideServerSettings();
m_server->signalThreadShouldExit();
m_server->waitForThreadToExit(1000);
m_server = std::make_unique<Server>();
m_server->startThread();
}
const KnownPluginList& App::getPluginList() { return m_server->getPluginList(); }
void App::showEditor(std::shared_ptr<AudioProcessor> proc, Thread::ThreadID tid, WindowCaptureCallback func) {
if (proc->hasEditor()) {
std::lock_guard<std::mutex> lock(m_windowMtx);
m_windowOwner = tid;
m_windowProc = proc;
m_windowFunc = func;
m_window = std::make_unique<ProcessorWindow>(m_windowProc, m_windowFunc);
}
}
void App::hideEditor(Thread::ThreadID tid) {
if (tid == 0 || tid == m_windowOwner) {
std::lock_guard<std::mutex> lock(m_windowMtx);
m_window.reset();
m_windowOwner = 0;
m_windowProc.reset();
m_windowFunc = nullptr;
}
}
void App::resetEditor() {
std::lock_guard<std::mutex> lock(m_windowMtx);
m_window.reset();
}
void App::restartEditor() {
std::lock_guard<std::mutex> lock(m_windowMtx);
m_window = std::make_unique<ProcessorWindow>(m_windowProc, m_windowFunc);
}
} // namespace e47
// This kicks the whole thing off..
START_JUCE_APPLICATION(e47::App)
| 2,130 | 741 |
/**
* Created by Xiaozhong on 2020/9/19.
* Copyright (c) 2020/9/19 Xiaozhong. All rights reserved.
*/
#include "iostream"
#include "vector"
#include "algorithm"
using namespace std;
class Node {
public:
int val;
Node *prev;
Node *next;
Node *child;
};
class Solution {
private:
Node *dfs(Node *prev, Node *curr) {
if (!curr) return prev;
// 首先将当前节点和前一个节点连接好
curr->prev = prev;
prev->next = curr;
// 记录下当前节点的下一个节点,因为在递归操作中,会把 curr 的 next 修改掉,所以先暂存,下面要进行使用
Node *temp = curr->next;
// 将分支进行处理
Node *tail = dfs(curr, curr->child);
// 断开分支
curr->child = nullptr;
// 从分支的尾部和 curr 原来的 next 进行处理
return dfs(tail, temp);
}
public:
Node *flatten(Node *head) {
if (!head) return head;
// 建立一个虚拟头部节点,方便操作
Node *pseudoHead = new Node();
dfs(pseudoHead, head);
// 将虚拟头部节点与主体断开连接
pseudoHead->next->prev = nullptr;
return pseudoHead->next;
}
}; | 1,020 | 446 |
// -*- C++ -*-
// $Id: Hello_Sender_exec.cpp 97306 2013-08-31 14:05:50Z johnnyw $
#include "Hello_Sender_exec.h"
#include "ace/Guard_T.h"
#include "ace/Log_Msg.h"
#include "tao/ORB_Core.h"
#include "ace/Date_Time.h"
#include "ace/OS_NS_unistd.h"
#include "ace/Reactor.h"
namespace CIAO_Hello_Sender_Impl
{
// TAO_IDL - Generated from
// be/be_visitor_component/facet_exs.cpp:75
//============================================================
// Facet Executor Implementation Class: connector_status_exec_i
//============================================================
connector_status_exec_i::connector_status_exec_i (
::Hello::CCM_Sender_Context_ptr ctx,
Atomic_Boolean &ready_to_start)
: ciao_context_ (
::Hello::CCM_Sender_Context::_duplicate (ctx)),
ready_to_start_(ready_to_start)
{
}
connector_status_exec_i::~connector_status_exec_i (void)
{
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("~connector_status_exec_i\n")));
}
// Operations from ::CCM_DDS::ConnectorStatusListener
void
connector_status_exec_i::on_inconsistent_topic (
::DDS::Topic_ptr /* the_topic */,
const ::DDS::InconsistentTopicStatus & /* status */)
{
/* Your code here. */
}
void
connector_status_exec_i::on_requested_incompatible_qos (
::DDS::DataReader_ptr /* the_reader */,
const ::DDS::RequestedIncompatibleQosStatus & /* status */)
{
/* Your code here. */
}
void
connector_status_exec_i::on_sample_rejected (
::DDS::DataReader_ptr /* the_reader */,
const ::DDS::SampleRejectedStatus & /* status */)
{
/* Your code here. */
}
void
connector_status_exec_i::on_offered_deadline_missed (
::DDS::DataWriter_ptr /* the_writer */,
const ::DDS::OfferedDeadlineMissedStatus & /* status */)
{
/* Your code here. */
}
void
connector_status_exec_i::on_offered_incompatible_qos (
::DDS::DataWriter_ptr /* the_writer */,
const ::DDS::OfferedIncompatibleQosStatus & /* status */)
{
/* Your code here. */
}
void
connector_status_exec_i::on_unexpected_status (
::DDS::Entity_ptr /* the_entity */,
::DDS::StatusKind status_kind)
{
if (status_kind == DDS::PUBLICATION_MATCHED_STATUS)
{
// be aware that when only the sender runs, ready_to_start will never
// be true.
this->ready_to_start_ = true;
}
}
//============================================================
// Pulse generator
//============================================================
pulse_Generator::pulse_Generator (Sender_exec_i &callback)
: pulse_callback_ (callback)
{
}
pulse_Generator::~pulse_Generator ()
{
}
int
pulse_Generator::handle_timeout (const ACE_Time_Value &,
const void *)
{
// Notify the subscribers
this->pulse_callback_.tick ();
return 0;
}
//============================================================
// Component Executor Implementation Class: Sender_exec_i
//============================================================
Sender_exec_i::Sender_exec_i (void)
: rate_ (1),
iteration_ (0),
iterations_ (1000),
log_time_ (false),
msg_ ("Hello World!"),
ready_to_start_(false)
{
this->ticker_ = new pulse_Generator (*this);
}
Sender_exec_i::~Sender_exec_i (void)
{
delete this->ticker_;
}
// Supported operations and attributes.
// Component attributes and port operations.
::CORBA::ULong
Sender_exec_i::rate (void)
{
return this->rate_;
}
void
Sender_exec_i::rate (
::CORBA::ULong rate)
{
if (rate == 0)
{
rate = 1;
}
else
{
this->rate_ = rate;
}
}
::CORBA::ULong
Sender_exec_i::iterations (void)
{
return this->iterations_;
}
void
Sender_exec_i::iterations (
::CORBA::ULong iterations)
{
this->iterations_ = iterations;
}
char *
Sender_exec_i::message (void)
{
return CORBA::string_dup (this->msg_.c_str());
}
void
Sender_exec_i::message (
const char * message)
{
this->msg_ = message;
}
::CORBA::Boolean
Sender_exec_i::log_time (void)
{
return this->log_time_;
}
void
Sender_exec_i::log_time (
::CORBA::Boolean log_time)
{
this->log_time_ = log_time;
}
::CCM_DDS::CCM_ConnectorStatusListener_ptr
Sender_exec_i::get_connector_status (void)
{
if ( ::CORBA::is_nil (this->ciao_connector_status_.in ()))
{
connector_status_exec_i *tmp = 0;
ACE_NEW_RETURN (
tmp,
connector_status_exec_i (
this->ciao_context_.in (),
this->ready_to_start_),
::CCM_DDS::CCM_ConnectorStatusListener::_nil ());
this->ciao_connector_status_ = tmp;
}
return
::CCM_DDS::CCM_ConnectorStatusListener::_duplicate (
this->ciao_connector_status_.in ());
}
ACE_CString
Sender_exec_i::create_message (const ACE_CString &msg)
{
if (!this->log_time_)
return msg;
char timestamp[16];
ACE_Date_Time now;
ACE_OS::sprintf (timestamp,
"%02d.%06d",
static_cast<int> (now.second()),
static_cast<int> (now.microsec ()));
ACE_CString ret (timestamp);
ret = ret + " " + msg;
return ret.c_str ();
}
void
Sender_exec_i::tick ()
{
// Start writing after DataWriter find first DataReader that matched the
// Topic It is still possible that other Readers aren't yet ready to
// receive data, for that case in the profile the durability is set to
// TRANSIENT_DURABILITY_QOS, so each Reader should receive each message.
if(this->ready_to_start_.value())
{
if (this->iteration_ < this->iterations_)
{
Hello::Writer_var writer =
this->ciao_context_->get_connection_info_in_data ();
if (! ::CORBA::is_nil (writer.in ()))
{
DDSHello new_msg;
ACE_CString msg = create_message (this->msg_);
new_msg.hello = msg.c_str ();
new_msg.iterator = ++this->iteration_;
writer->write_one (new_msg, ::DDS::HANDLE_NIL);
ACE_DEBUG ((LM_DEBUG, "Sender_exec_i::tick - "
"Written sample: <%C> - <%u>\n",
msg.c_str (),
new_msg.iterator));
}
}
else
{
// We are done
this->stop ();
}
}
}
void
Sender_exec_i::start (void)
{
ACE_Reactor* reactor = 0;
::CORBA::Object_var ccm_object = this->ciao_context_->get_CCM_object();
if (!::CORBA::is_nil (ccm_object.in ()))
{
::CORBA::ORB_var orb = ccm_object->_get_orb ();
if (!::CORBA::is_nil (orb.in ()))
{
reactor = orb->orb_core ()->reactor ();
}
}
if (reactor)
{
// calculate the interval time
long const usec = 1000000 / this->rate_;
if (reactor->schedule_timer (
this->ticker_,
0,
ACE_Time_Value (3, usec),
ACE_Time_Value (0, usec)) == -1)
{
ACE_ERROR ((LM_ERROR, ACE_TEXT ("Sender_exec_i::start : ")
ACE_TEXT ("Error scheduling timer")));
}
}
else
{
throw ::CORBA::INTERNAL ();
}
}
void
Sender_exec_i::stop (void)
{
ACE_Reactor* reactor = 0;
::CORBA::Object_var ccm_object = this->ciao_context_->get_CCM_object();
if (!::CORBA::is_nil (ccm_object.in ()))
{
::CORBA::ORB_var orb = ccm_object->_get_orb ();
if (!::CORBA::is_nil (orb.in ()))
{
reactor = orb->orb_core ()->reactor ();
}
}
if (reactor)
{
reactor->cancel_timer (this->ticker_);
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Sender_exec_i::stop : Timer canceled.\n")));
}
else
{
throw ::CORBA::INTERNAL ();
}
if (!this->ready_to_start_.value())
{
ACE_ERROR ((LM_ERROR, ACE_TEXT ("Sender_exec_i::stop - ")
ACE_TEXT ("Sender never got ready to start\n")));
}
}
// Operations from Components::SessionComponent.
void
Sender_exec_i::set_session_context (
::Components::SessionContext_ptr ctx)
{
this->ciao_context_ =
::Hello::CCM_Sender_Context::_narrow (ctx);
if ( ::CORBA::is_nil (this->ciao_context_.in ()))
{
throw ::CORBA::INTERNAL ();
}
}
void
Sender_exec_i::configuration_complete (void)
{
/* Your code here. */
}
void
Sender_exec_i::ccm_activate (void)
{
this->start ();
}
void
Sender_exec_i::ccm_passivate (void)
{
this->stop ();
}
void
Sender_exec_i::ccm_remove (void)
{
/* Your code here. */
}
extern "C" HELLO_SENDER_EXEC_Export ::Components::EnterpriseComponent_ptr
create_Hello_Sender_Impl (void)
{
::Components::EnterpriseComponent_ptr retval =
::Components::EnterpriseComponent::_nil ();
ACE_NEW_NORETURN (
retval,
Sender_exec_i);
return retval;
}
}
| 9,305 | 3,284 |
#include <bits/stdc++.h>
#include <limits>
using namespace std;
int count_changes_to_palindrom(string s) {
int changes{0};
for (size_t idx = 0; idx < s.length(); ++idx) {
auto current_letter = s.at(idx);
auto mirror_letter = s.at(s.length() - idx - 1);
cout << current_letter << "--" << mirror_letter;
// Rule 1
int change_cost{0};
if (int(current_letter) < int(mirror_letter)) {
cout << " is not allowed" << endl;
} else {
change_cost = int(current_letter) - int(mirror_letter);
}
cout << " costs " << to_string(change_cost) << endl;
changes += change_cost;
}
cout << " Total Cost: " << changes << endl;
return changes;
}
// Complete the theLoveLetterMystery function below.
int theLoveLetterMystery(string s) {
cout << "Input: " << s << endl;
int changes_left = count_changes_to_palindrom(s);
cout << "---" << endl;
reverse(s.begin(), s.end());
cout << "Reversed: " << s << endl;
int changes_right = count_changes_to_palindrom(s);
cout << "=================" << endl;
return min(changes_left, changes_right);
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int q;
cin >> q;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
for (int q_itr = 0; q_itr < q; q_itr++) {
string s;
getline(cin, s);
int result = theLoveLetterMystery(s);
fout << result << "\n";
}
fout.close();
return 0;
}
| 1,538 | 533 |
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
if (obstacleGrid.empty() || obstacleGrid[0].empty()){
return 0;
}
int row = obstacleGrid.size();
int column = obstacleGrid[0].size();
vector<vector<int>> board(row, vector<int>(column, 0));
if (obstacleGrid[0][0] == 1){
return 0;
}
board[0][0] = 1;
for (int i = 1; i < column; ++i){
board[0][i] = (obstacleGrid[0][i] == 1) ? 0 : board[0][i - 1] ;
}
for (int i = 1; i < row; ++i){
board[i][0] = (obstacleGrid[i][0] == 1) ? 0 : board[i - 1][0];
}
for (int i = 1; i < row; i ++){
for (int j = 1; j < column; ++j){
board[i][j] = (obstacleGrid[i][j] == 1) ? 0 : board[i - 1][j] + board[i][j - 1];
}
}
return board[row - 1][column - 1];
}
}; | 948 | 368 |
#include "agent_based_epidemic_sim/core/hazard_transmission_model.h"
#include <array>
#include <iterator>
#include <numeric>
#include <vector>
#include "absl/random/distributions.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "agent_based_epidemic_sim/core/constants.h"
#include "agent_based_epidemic_sim/core/integral_types.h"
#include "agent_based_epidemic_sim/core/random.h"
#include "agent_based_epidemic_sim/port/logging.h"
namespace abesim {
// TODO: Fix variable naming in this implementation. For now it is
// easiest to simply mirror the python implementation until it is stable.
float HazardTransmissionModel::ComputeDose(const float distance,
absl::Duration duration,
const Exposure* exposure) {
const float t = absl::ToDoubleMinutes(duration);
const float fd = risk_at_distance_function_(distance);
// TODO: Thread these factors through on the Exposure in the
// Location phase (e.g. Location::ProcessVisits).
const float finf = exposure->infectivity;
const float fsym = exposure->symptom_factor;
const float floc = exposure->location_transmissibility;
const float fage = exposure->susceptibility;
const float h = t * fd * finf * fsym * floc * fage;
return h;
}
HealthTransition HazardTransmissionModel::GetInfectionOutcome(
absl::Span<const Exposure* const> exposures) {
absl::Time latest_exposure_time = absl::InfinitePast();
float sum_dose = 0;
for (const Exposure* exposure : exposures) {
if (exposure->infectivity == 0 || exposure->symptom_factor == 0 ||
exposure->location_transmissibility == 0 ||
exposure->susceptibility == 0) {
continue;
}
latest_exposure_time = std::max(latest_exposure_time,
exposure->start_time + exposure->duration);
// TODO: Remove proximity_trace.
if (exposure->distance >= 0) {
sum_dose += ComputeDose(exposure->distance, exposure->duration, exposure);
} else {
for (const float& proximity : exposure->proximity_trace.values) {
sum_dose += ComputeDose(proximity, kProximityTraceInterval, exposure);
}
}
}
const float prob_infection = 1 - std::exp(-lambda_ * sum_dose);
HealthTransition health_transition;
health_transition.time = latest_exposure_time;
health_transition.health_state = absl::Bernoulli(GetBitGen(), prob_infection)
? HealthState::EXPOSED
: HealthState::SUSCEPTIBLE;
return health_transition;
}
} // namespace abesim
| 2,626 | 834 |
#include "RecorteMarioSaltando.hpp"
#define ESTADOS_MARIO 12
#define DESPLAZAMIENTO_X 20
#define ALTO 28
#define ANCHO 20
RecorteMarioSaltando::RecorteMarioSaltando(){
estadoActual = 0;
inicializarEstados(ESTADOS_MARIO,DESPLAZAMIENTO_X,ALTO,ANCHO);
}
void RecorteMarioSaltando::actualizarSprite(){
if(ciclos%5==0){
estadoActual++;
if(estadoActual==11 && ciclos%5==0){
estadoActual=0;
}
}
ciclos++;
}
SDL_Rect RecorteMarioSaltando::obtenerRecorte(int recorte) {
return Recorte::obtenerRecorte(estadoActual);
}
#include "RecorteMarioSaltando.hpp"
| 609 | 259 |
/* CirKit: A circuit toolkit
* Copyright (C) 2009-2015 University of Bremen
* Copyright (C) 2015-2016 EPFL
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @file rm3_graph.hpp
*
* @brief A dedicated data-structure for RM3 graphs
*
* @author Mathias Soeken
* @since 2.3
*/
#ifndef RM3_GRAPH_HPP
#define RM3_GRAPH_HPP
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
#include <core/utils/hash_utils.hpp>
namespace cirkit
{
using rm3_node = unsigned;
class rm3_graph
{
public:
rm3_graph( unsigned num_vars = 0u );
void create_po( const rm3_node& n, const std::string& name = std::string() );
rm3_node create_rm3( const rm3_node& x, const rm3_node& y, const rm3_node& z );
rm3_node create_not( const rm3_node& x );
unsigned num_gates() const;
unsigned num_inputs() const;
unsigned num_outputs() const;
void print_statistics( std::ostream& os ) const;
private:
unsigned num_vars = 0u;
std::vector<unsigned> nodes;
std::vector<std::string> inputs;
std::vector<std::pair<unsigned, std::string>> outputs;
using rm3_graph_hash_key_t = std::tuple<rm3_node, rm3_node, rm3_node>;
std::unordered_map<rm3_graph_hash_key_t, rm3_node, hash<rm3_graph_hash_key_t>> strash;
};
}
#endif
// Local Variables:
// c-basic-offset: 2
// eval: (c-set-offset 'substatement-open 0)
// eval: (c-set-offset 'innamespace 0)
// End:
| 2,433 | 892 |
/*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) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., 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 Intel Corporation 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*/
#include "test_precomp.hpp"
#include "test_chessboardgenerator.hpp"
namespace cv {
ChessBoardGenerator::ChessBoardGenerator(const Size& _patternSize) : sensorWidth(32), sensorHeight(24),
squareEdgePointsNum(200), min_cos(std::sqrt(3.f)*0.5f), cov(0.5),
patternSize(_patternSize), rendererResolutionMultiplier(4), tvec(Mat::zeros(1, 3, CV_32F))
{
rvec.create(3, 1, CV_32F);
cvtest::Rodrigues(Mat::eye(3, 3, CV_32F), rvec);
}
void ChessBoardGenerator::generateEdge(const Point3f& p1, const Point3f& p2, vector<Point3f>& out) const
{
Point3f step = (p2 - p1) * (1.f/squareEdgePointsNum);
for(size_t n = 0; n < squareEdgePointsNum; ++n)
out.push_back( p1 + step * (float)n);
}
Size ChessBoardGenerator::cornersSize() const
{
return Size(patternSize.width-1, patternSize.height-1);
}
struct Mult
{
float m;
Mult(int mult) : m((float)mult) {}
Point2f operator()(const Point2f& p)const { return p * m; }
};
void ChessBoardGenerator::generateBasis(Point3f& pb1, Point3f& pb2) const
{
RNG& rng = theRNG();
Vec3f n;
for(;;)
{
n[0] = rng.uniform(-1.f, 1.f);
n[1] = rng.uniform(-1.f, 1.f);
n[2] = rng.uniform(0.0f, 1.f);
float len = (float)norm(n);
if (len < 1e-3)
continue;
n[0]/=len;
n[1]/=len;
n[2]/=len;
if (n[2] > min_cos)
break;
}
Vec3f n_temp = n; n_temp[0] += 100;
Vec3f b1 = n.cross(n_temp);
Vec3f b2 = n.cross(b1);
float len_b1 = (float)norm(b1);
float len_b2 = (float)norm(b2);
pb1 = Point3f(b1[0]/len_b1, b1[1]/len_b1, b1[2]/len_b1);
pb2 = Point3f(b2[0]/len_b1, b2[1]/len_b2, b2[2]/len_b2);
}
Mat ChessBoardGenerator::generateChessBoard(const Mat& bg, const Mat& camMat, const Mat& distCoeffs,
const Point3f& zero, const Point3f& pb1, const Point3f& pb2,
float sqWidth, float sqHeight, const vector<Point3f>& whole,
vector<Point2f>& corners) const
{
vector< vector<Point> > squares_black;
for(int i = 0; i < patternSize.width; ++i)
for(int j = 0; j < patternSize.height; ++j)
if ( (i % 2 == 0 && j % 2 == 0) || (i % 2 != 0 && j % 2 != 0) )
{
vector<Point3f> pts_square3d;
vector<Point2f> pts_square2d;
Point3f p1 = zero + (i + 0) * sqWidth * pb1 + (j + 0) * sqHeight * pb2;
Point3f p2 = zero + (i + 1) * sqWidth * pb1 + (j + 0) * sqHeight * pb2;
Point3f p3 = zero + (i + 1) * sqWidth * pb1 + (j + 1) * sqHeight * pb2;
Point3f p4 = zero + (i + 0) * sqWidth * pb1 + (j + 1) * sqHeight * pb2;
generateEdge(p1, p2, pts_square3d);
generateEdge(p2, p3, pts_square3d);
generateEdge(p3, p4, pts_square3d);
generateEdge(p4, p1, pts_square3d);
projectPoints(Mat(pts_square3d), rvec, tvec, camMat, distCoeffs, pts_square2d);
squares_black.resize(squares_black.size() + 1);
vector<Point2f> temp;
approxPolyDP(Mat(pts_square2d), temp, 1.0, true);
transform(temp.begin(), temp.end(), back_inserter(squares_black.back()), Mult(rendererResolutionMultiplier));
}
/* calculate corners */
corners3d.clear();
for(int j = 0; j < patternSize.height - 1; ++j)
for(int i = 0; i < patternSize.width - 1; ++i)
corners3d.push_back(zero + (i + 1) * sqWidth * pb1 + (j + 1) * sqHeight * pb2);
corners.clear();
projectPoints(Mat(corners3d), rvec, tvec, camMat, distCoeffs, corners);
vector<Point3f> whole3d;
vector<Point2f> whole2d;
generateEdge(whole[0], whole[1], whole3d);
generateEdge(whole[1], whole[2], whole3d);
generateEdge(whole[2], whole[3], whole3d);
generateEdge(whole[3], whole[0], whole3d);
projectPoints(Mat(whole3d), rvec, tvec, camMat, distCoeffs, whole2d);
vector<Point2f> temp_whole2d;
approxPolyDP(Mat(whole2d), temp_whole2d, 1.0, true);
vector< vector<Point > > whole_contour(1);
transform(temp_whole2d.begin(), temp_whole2d.end(),
back_inserter(whole_contour.front()), Mult(rendererResolutionMultiplier));
Mat result;
if (rendererResolutionMultiplier == 1)
{
result = bg.clone();
drawContours(result, whole_contour, -1, Scalar::all(255), FILLED, LINE_AA);
drawContours(result, squares_black, -1, Scalar::all(0), FILLED, LINE_AA);
}
else
{
Mat tmp;
resize(bg, tmp, bg.size() * rendererResolutionMultiplier, 0, 0, INTER_LINEAR_EXACT);
drawContours(tmp, whole_contour, -1, Scalar::all(255), FILLED, LINE_AA);
drawContours(tmp, squares_black, -1, Scalar::all(0), FILLED, LINE_AA);
resize(tmp, result, bg.size(), 0, 0, INTER_AREA);
}
return result;
}
Mat ChessBoardGenerator::operator ()(const Mat& bg, const Mat& camMat, const Mat& distCoeffs, vector<Point2f>& corners) const
{
cov = std::min(cov, 0.8);
double fovx, fovy, focalLen;
Point2d principalPoint;
double aspect;
calibrationMatrixValues( camMat, bg.size(), sensorWidth, sensorHeight,
fovx, fovy, focalLen, principalPoint, aspect);
RNG& rng = theRNG();
float d1 = static_cast<float>(rng.uniform(0.1, 10.0));
float ah = static_cast<float>(rng.uniform(-fovx/2 * cov, fovx/2 * cov) * CV_PI / 180);
float av = static_cast<float>(rng.uniform(-fovy/2 * cov, fovy/2 * cov) * CV_PI / 180);
Point3f p;
p.z = cos(ah) * d1;
p.x = sin(ah) * d1;
p.y = p.z * tan(av);
Point3f pb1, pb2;
generateBasis(pb1, pb2);
float cbHalfWidth = static_cast<float>(norm(p) * sin( std::min(fovx, fovy) * 0.5 * CV_PI / 180));
float cbHalfHeight = cbHalfWidth * patternSize.height / patternSize.width;
float cbHalfWidthEx = cbHalfWidth * ( patternSize.width + 1) / patternSize.width;
float cbHalfHeightEx = cbHalfHeight * (patternSize.height + 1) / patternSize.height;
vector<Point3f> pts3d(4);
vector<Point2f> pts2d(4);
for(;;)
{
pts3d[0] = p + pb1 * cbHalfWidthEx + cbHalfHeightEx * pb2;
pts3d[1] = p + pb1 * cbHalfWidthEx - cbHalfHeightEx * pb2;
pts3d[2] = p - pb1 * cbHalfWidthEx - cbHalfHeightEx * pb2;
pts3d[3] = p - pb1 * cbHalfWidthEx + cbHalfHeightEx * pb2;
/* can remake with better perf */
projectPoints(Mat(pts3d), rvec, tvec, camMat, distCoeffs, pts2d);
bool inrect1 = pts2d[0].x < bg.cols && pts2d[0].y < bg.rows && pts2d[0].x > 0 && pts2d[0].y > 0;
bool inrect2 = pts2d[1].x < bg.cols && pts2d[1].y < bg.rows && pts2d[1].x > 0 && pts2d[1].y > 0;
bool inrect3 = pts2d[2].x < bg.cols && pts2d[2].y < bg.rows && pts2d[2].x > 0 && pts2d[2].y > 0;
bool inrect4 = pts2d[3].x < bg.cols && pts2d[3].y < bg.rows && pts2d[3].x > 0 && pts2d[3].y > 0;
if (inrect1 && inrect2 && inrect3 && inrect4)
break;
cbHalfWidth*=0.8f;
cbHalfHeight = cbHalfWidth * patternSize.height / patternSize.width;
cbHalfWidthEx = cbHalfWidth * ( patternSize.width + 1) / patternSize.width;
cbHalfHeightEx = cbHalfHeight * (patternSize.height + 1) / patternSize.height;
}
Point3f zero = p - pb1 * cbHalfWidth - cbHalfHeight * pb2;
float sqWidth = 2 * cbHalfWidth/patternSize.width;
float sqHeight = 2 * cbHalfHeight/patternSize.height;
return generateChessBoard(bg, camMat, distCoeffs, zero, pb1, pb2, sqWidth, sqHeight, pts3d, corners);
}
Mat ChessBoardGenerator::operator ()(const Mat& bg, const Mat& camMat, const Mat& distCoeffs,
const Size2f& squareSize, vector<Point2f>& corners) const
{
cov = std::min(cov, 0.8);
double fovx, fovy, focalLen;
Point2d principalPoint;
double aspect;
calibrationMatrixValues( camMat, bg.size(), sensorWidth, sensorHeight,
fovx, fovy, focalLen, principalPoint, aspect);
RNG& rng = theRNG();
float d1 = static_cast<float>(rng.uniform(0.1, 10.0));
float ah = static_cast<float>(rng.uniform(-fovx/2 * cov, fovx/2 * cov) * CV_PI / 180);
float av = static_cast<float>(rng.uniform(-fovy/2 * cov, fovy/2 * cov) * CV_PI / 180);
Point3f p;
p.z = cos(ah) * d1;
p.x = sin(ah) * d1;
p.y = p.z * tan(av);
Point3f pb1, pb2;
generateBasis(pb1, pb2);
float cbHalfWidth = squareSize.width * patternSize.width * 0.5f;
float cbHalfHeight = squareSize.height * patternSize.height * 0.5f;
float cbHalfWidthEx = cbHalfWidth * ( patternSize.width + 1) / patternSize.width;
float cbHalfHeightEx = cbHalfHeight * (patternSize.height + 1) / patternSize.height;
vector<Point3f> pts3d(4);
vector<Point2f> pts2d(4);
for(;;)
{
pts3d[0] = p + pb1 * cbHalfWidthEx + cbHalfHeightEx * pb2;
pts3d[1] = p + pb1 * cbHalfWidthEx - cbHalfHeightEx * pb2;
pts3d[2] = p - pb1 * cbHalfWidthEx - cbHalfHeightEx * pb2;
pts3d[3] = p - pb1 * cbHalfWidthEx + cbHalfHeightEx * pb2;
/* can remake with better perf */
projectPoints(Mat(pts3d), rvec, tvec, camMat, distCoeffs, pts2d);
bool inrect1 = pts2d[0].x < bg.cols && pts2d[0].y < bg.rows && pts2d[0].x > 0 && pts2d[0].y > 0;
bool inrect2 = pts2d[1].x < bg.cols && pts2d[1].y < bg.rows && pts2d[1].x > 0 && pts2d[1].y > 0;
bool inrect3 = pts2d[2].x < bg.cols && pts2d[2].y < bg.rows && pts2d[2].x > 0 && pts2d[2].y > 0;
bool inrect4 = pts2d[3].x < bg.cols && pts2d[3].y < bg.rows && pts2d[3].x > 0 && pts2d[3].y > 0;
if ( inrect1 && inrect2 && inrect3 && inrect4)
break;
p.z *= 1.1f;
}
Point3f zero = p - pb1 * cbHalfWidth - cbHalfHeight * pb2;
return generateChessBoard(bg, camMat, distCoeffs, zero, pb1, pb2,
squareSize.width, squareSize.height, pts3d, corners);
}
Mat ChessBoardGenerator::operator ()(const Mat& bg, const Mat& camMat, const Mat& distCoeffs,
const Size2f& squareSize, const Point3f& pos, vector<Point2f>& corners) const
{
cov = std::min(cov, 0.8);
Point3f p = pos;
Point3f pb1, pb2;
generateBasis(pb1, pb2);
float cbHalfWidth = squareSize.width * patternSize.width * 0.5f;
float cbHalfHeight = squareSize.height * patternSize.height * 0.5f;
float cbHalfWidthEx = cbHalfWidth * ( patternSize.width + 1) / patternSize.width;
float cbHalfHeightEx = cbHalfHeight * (patternSize.height + 1) / patternSize.height;
vector<Point3f> pts3d(4);
vector<Point2f> pts2d(4);
pts3d[0] = p + pb1 * cbHalfWidthEx + cbHalfHeightEx * pb2;
pts3d[1] = p + pb1 * cbHalfWidthEx - cbHalfHeightEx * pb2;
pts3d[2] = p - pb1 * cbHalfWidthEx - cbHalfHeightEx * pb2;
pts3d[3] = p - pb1 * cbHalfWidthEx + cbHalfHeightEx * pb2;
/* can remake with better perf */
projectPoints(Mat(pts3d), rvec, tvec, camMat, distCoeffs, pts2d);
Point3f zero = p - pb1 * cbHalfWidth - cbHalfHeight * pb2;
return generateChessBoard(bg, camMat, distCoeffs, zero, pb1, pb2,
squareSize.width, squareSize.height, pts3d, corners);
}
} // namespace
| 13,473 | 5,133 |
#include "../include/cli3DS.h"
Option::Option(std::string _text) : text(_text) {
selectable = false;
selected = false;
view_entry = NULL;
}
std::string Option::get_text() {
return text;
}
void Option::set_selectable() {
view_entry = NULL;
selectable = true;
}
bool Option::get_selectable() {
return selectable;
}
void Option::toggle_selected() {
if(selected)
selected = false;
else
selected = true;
}
bool Option::get_selected() {
return selected;
}
void Option::set_current_view(View *_view) {
current_view = _view;
}
void Option::set_view_entry(View *_view_entry) {
view_entry = _view_entry;
selectable = false;
}
View *Option::click() {
if(selectable) {
selected = !selected;
} else if(view_entry != NULL) {
if(view_entry->is_executable()) {
((ExecutionSplash*) view_entry)->start_execution();
((ExecutionSplash*) view_entry)->set_previous_view(current_view);
} else {
((Menu*) view_entry)->set_previous_view(current_view);
}
return view_entry;
}
return NULL;
}
| 1,134 | 371 |
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
/*
* 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/.
*/
/*
* The main entry point for the LibreOfficeKit process serving
* a document editing session.
*/
#include <config.h>
#include <dlfcn.h>
#ifdef __linux__
#include <ftw.h>
#include <sys/vfs.h>
#include <linux/magic.h>
#include <sys/capability.h>
#include <sys/sysmacros.h>
#endif
#ifdef __FreeBSD__
#include <sys/capsicum.h>
#include <ftw.h>
#define FTW_CONTINUE 0
#define FTW_STOP (-1)
#define FTW_SKIP_SUBTREE 0
#define FTW_ACTIONRETVAL 0
#endif
#include <unistd.h>
#include <utime.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sysexits.h>
#include <atomic>
#include <cassert>
#include <climits>
#include <condition_variable>
#include <chrono>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <memory>
#include <string>
#include <sstream>
#include <thread>
#define LOK_USE_UNSTABLE_API
#include <LibreOfficeKit/LibreOfficeKitInit.h>
#include <Poco/File.h>
#include <Poco/Exception.h>
#include <Poco/JSON/Object.h>
#include <Poco/JSON/Parser.h>
#include <Poco/Net/Socket.h>
#include <Poco/URI.h>
#include "ChildSession.hpp"
#include <Common.hpp>
#include <MobileApp.hpp>
#include <FileUtil.hpp>
#include <common/JailUtil.hpp>
#include <common/JsonUtil.hpp>
#include "KitHelper.hpp"
#include "Kit.hpp"
#include <Protocol.hpp>
#include <Log.hpp>
#include <Png.hpp>
#include <Rectangle.hpp>
#include <TileDesc.hpp>
#include <Unit.hpp>
#include <UserMessages.hpp>
#include <Util.hpp>
#include "Watermark.hpp"
#include "RenderTiles.hpp"
#include "SetupKitEnvironment.hpp"
#include <common/ConfigUtil.hpp>
#include <common/TraceEvent.hpp>
#if !MOBILEAPP
#include <common/SigUtil.hpp>
#include <common/Seccomp.hpp>
#include <utility>
#endif
#ifdef FUZZER
#include <kit/DummyLibreOfficeKit.hpp>
#include <wsd/COOLWSD.hpp>
#endif
#if MOBILEAPP
#include "COOLWSD.hpp"
#endif
#ifdef IOS
#include "ios.h"
#endif
#define LIB_SOFFICEAPP "lib" "sofficeapp" ".so"
#define LIB_MERGED "lib" "mergedlo" ".so"
using Poco::Exception;
using Poco::File;
using Poco::JSON::Array;
using Poco::JSON::Object;
using Poco::JSON::Parser;
using Poco::URI;
#ifndef BUILDING_TESTS
using Poco::Path;
#endif
using namespace COOLProtocol;
extern "C" { void dump_kit_state(void); /* easy for gdb */ }
#if !MOBILEAPP
// A Kit process hosts only a single document in its lifetime.
class Document;
static Document *singletonDocument = nullptr;
#endif
/// Used for test code to accelerating waiting until idle and to
/// flush sockets with a 'processtoidle' -> 'idle' reply.
static std::chrono::steady_clock::time_point ProcessToIdleDeadline;
#ifndef BUILDING_TESTS
static bool AnonymizeUserData = false;
static uint64_t AnonymizationSalt = 82589933;
#endif
/// When chroot is enabled, this is blank as all
/// the paths inside the jail, relative to it's jail.
/// E.g. /tmp/user/docs/...
/// However, without chroot, the jail path is
/// absolute in the system root.
/// I.e. ChildRoot/JailId/tmp/user/docs/...
/// We need to know where the jail really is
/// because WSD doesn't know if chroot will succeed
/// or fail, but it assumes the document path to
/// be relative to the root of the jail (i.e. chroot
/// expected to succeed). If it fails, or when caps
/// are disabled, file paths would be relative to the
/// system root, not the jail.
static std::string JailRoot;
#if !MOBILEAPP
static void flushTraceEventRecordings();
#endif
// Abnormally we get LOK events from another thread, which must be
// push safely into our main poll loop to process to keep all
// socket buffer & event processing in a single, thread.
bool pushToMainThread(LibreOfficeKitCallback cb, int type, const char *p, void *data);
#if !MOBILEAPP
static LokHookFunction2* initFunction = nullptr;
namespace
{
#ifndef BUILDING_TESTS
enum class LinkOrCopyType
{
All,
LO
};
LinkOrCopyType linkOrCopyType;
std::string sourceForLinkOrCopy;
Path destinationForLinkOrCopy;
bool forceInitialCopy; // some stackable file-systems have very slow first hard link creation
std::string linkableForLinkOrCopy; // Place to stash copies that we can hard-link from
std::chrono::time_point<std::chrono::steady_clock> linkOrCopyStartTime;
bool linkOrCopyVerboseLogging = false;
unsigned linkOrCopyFileCount = 0; // Track to help quantify the link-or-copy performance.
constexpr unsigned SlowLinkOrCopyLimitInSecs = 2; // After this many seconds, start spamming the logs.
bool detectSlowStackingFileSystem(const std::string &directory)
{
#ifdef __linux__
#ifndef OVERLAYFS_SUPER_MAGIC
// From linux/magic.h.
#define OVERLAYFS_SUPER_MAGIC 0x794c7630
#endif
struct statfs fs;
if (::statfs(directory.c_str(), &fs) != 0)
{
LOG_SYS("statfs failed on '" << directory << "'");
return false;
}
switch (fs.f_type) {
// case FUSE_SUPER_MAGIC: ?
case OVERLAYFS_SUPER_MAGIC:
return true;
default:
return false;
}
#else
(void)directory;
return false;
#endif
}
/// Returns the LinkOrCopyType as a human-readable string (for logging).
std::string linkOrCopyTypeString(LinkOrCopyType type)
{
switch (type)
{
case LinkOrCopyType::LO:
return "LibreOffice";
case LinkOrCopyType::All:
return "all";
default:
assert(!"Unknown LinkOrCopyType.");
return "unknown";
}
}
bool shouldCopyDir(const char *path)
{
switch (linkOrCopyType)
{
case LinkOrCopyType::LO:
return
strcmp(path, "program/wizards") != 0 &&
strcmp(path, "sdk") != 0 &&
strcmp(path, "debugsource") != 0 &&
strcmp(path, "share/basic") != 0 &&
strncmp(path, "share/extensions/dict-", // preloaded
sizeof("share/extensions/dict")) != 0 &&
strcmp(path, "share/Scripts/java") != 0 &&
strcmp(path, "share/Scripts/javascript") != 0 &&
strcmp(path, "share/config/wizard") != 0 &&
strcmp(path, "readmes") != 0 &&
strcmp(path, "help") != 0;
default: // LinkOrCopyType::All
return true;
}
}
bool shouldLinkFile(const char *path)
{
switch (linkOrCopyType)
{
case LinkOrCopyType::LO:
{
if (strstr(path, "LICENSE") || strstr(path, "EULA") || strstr(path, "CREDITS")
|| strstr(path, "NOTICE"))
return false;
const char* dot = strrchr(path, '.');
if (!dot)
return true;
if (!strcmp(dot, ".dbg"))
return false;
if (!strcmp(dot, ".so"))
{
// NSS is problematic ...
if (strstr(path, "libnspr4") ||
strstr(path, "libplds4") ||
strstr(path, "libplc4") ||
strstr(path, "libnss3") ||
strstr(path, "libnssckbi") ||
strstr(path, "libnsutil3") ||
strstr(path, "libssl3") ||
strstr(path, "libsoftokn3") ||
strstr(path, "libsqlite3") ||
strstr(path, "libfreeblpriv3"))
return true;
// As is Python ...
if (strstr(path, "python-core"))
return true;
// otherwise drop the rest of the code.
return false;
}
const char *vers;
if ((vers = strstr(path, ".so."))) // .so.[digit]+
{
for(int i = sizeof (".so."); vers[i] != '\0'; ++i)
if (!isdigit(vers[i]) && vers[i] != '.')
return true;
return false;
}
return true;
}
default: // LinkOrCopyType::All
return true;
}
}
void linkOrCopyFile(const char* fpath, const std::string& newPath)
{
++linkOrCopyFileCount;
if (linkOrCopyVerboseLogging)
LOG_INF("Linking file \"" << fpath << "\" to \"" << newPath << '"');
if (!forceInitialCopy)
{
// first try a simple hard-link
if (link(fpath, newPath.c_str()) == 0)
return;
}
// else always copy before linking to linkable/
// incrementally build our 'linkable/' copy nearby
static bool canChown = true; // only if we can get permissions right
if ((forceInitialCopy || errno == EXDEV) && canChown)
{
// then copy somewhere closer and hard link from there
if (!forceInitialCopy)
LOG_TRC("link(\"" << fpath << "\", \"" << newPath << "\") failed: " << strerror(errno)
<< ". Will try to link template.");
std::string linkableCopy = linkableForLinkOrCopy + fpath;
if (::link(linkableCopy.c_str(), newPath.c_str()) == 0)
return;
if (errno == ENOENT)
{
File(Path(linkableCopy).parent()).createDirectories();
if (!FileUtil::copy(fpath, linkableCopy.c_str(), /*log=*/false, /*throw_on_error=*/false))
LOG_TRC("Failed to create linkable copy [" << fpath << "] to [" << linkableCopy.c_str() << "]");
else {
// Match system permissions, so a file we can write is not shared across jails.
struct stat ownerInfo;
if (::stat(fpath, &ownerInfo) != 0 ||
::chown(linkableCopy.c_str(), ownerInfo.st_uid, ownerInfo.st_gid) != 0)
{
LOG_ERR("Failed to stat or chown " << ownerInfo.st_uid << ":" << ownerInfo.st_gid <<
" " << linkableCopy << ": " << strerror(errno) << " missing cap_chown?, disabling linkable");
unlink(linkableCopy.c_str());
canChown = false;
}
else if (::link(linkableCopy.c_str(), newPath.c_str()) == 0)
return;
}
}
LOG_TRC("link(\"" << linkableCopy << "\", \"" << newPath << "\") failed: " << strerror(errno)
<< ". Cannot create linkable copy.");
}
static bool warned = false;
if (!warned)
{
LOG_ERR("link(\"" << fpath << "\", \"" << newPath.c_str() << "\") failed: " << strerror(errno)
<< ". Very slow copying path triggered.");
warned = true;
} else
LOG_TRC("link(\"" << fpath << "\", \"" << newPath.c_str() << "\") failed: " << strerror(errno)
<< ". Will copy.");
if (!FileUtil::copy(fpath, newPath.c_str(), /*log=*/false, /*throw_on_error=*/false))
{
LOG_FTL("Failed to copy or link [" << fpath << "] to [" << newPath << "]. Exiting.");
Log::shutdown();
std::_Exit(EX_SOFTWARE);
}
}
int linkOrCopyFunction(const char *fpath,
const struct stat* sb,
int typeflag,
struct FTW* /*ftwbuf*/)
{
if (strcmp(fpath, sourceForLinkOrCopy.c_str()) == 0)
{
LOG_TRC("nftw: Skipping redundant path: " << fpath);
return FTW_CONTINUE;
}
if (!linkOrCopyVerboseLogging)
{
const auto durationInSecs = std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::steady_clock::now() - linkOrCopyStartTime);
if (durationInSecs.count() > SlowLinkOrCopyLimitInSecs)
{
LOG_WRN("Linking/copying files from "
<< sourceForLinkOrCopy << " to " << destinationForLinkOrCopy.toString()
<< " is taking too much time. Enabling verbose link/copy logging.");
linkOrCopyVerboseLogging = true;
}
}
assert(fpath[strlen(sourceForLinkOrCopy.c_str())] == '/');
const char *relativeOldPath = fpath + strlen(sourceForLinkOrCopy.c_str()) + 1;
const Path newPath(destinationForLinkOrCopy, Path(relativeOldPath));
switch (typeflag)
{
case FTW_F:
case FTW_SLN:
File(newPath.parent()).createDirectories();
if (shouldLinkFile(relativeOldPath))
linkOrCopyFile(fpath, newPath.toString());
break;
case FTW_D:
{
struct stat st;
if (stat(fpath, &st) == -1)
{
LOG_SYS("nftw: stat(\"" << fpath << "\") failed");
return FTW_STOP;
}
if (!shouldCopyDir(relativeOldPath))
{
LOG_TRC("nftw: Skipping redundant path: " << relativeOldPath);
return FTW_SKIP_SUBTREE;
}
File(newPath).createDirectories();
struct utimbuf ut;
ut.actime = st.st_atime;
ut.modtime = st.st_mtime;
if (utime(newPath.toString().c_str(), &ut) == -1)
{
LOG_SYS("nftw: utime(\"" << newPath.toString() << "\") failed");
return FTW_STOP;
}
}
break;
case FTW_SL:
{
const std::size_t size = sb->st_size;
char target[size + 1];
const ssize_t written = readlink(fpath, target, size);
if (written <= 0 || static_cast<std::size_t>(written) > size)
{
LOG_SYS("nftw: readlink(\"" << fpath << "\") failed");
Log::shutdown();
std::_Exit(EX_SOFTWARE);
}
target[written] = '\0';
File(newPath.parent()).createDirectories();
if (symlink(target, newPath.toString().c_str()) == -1)
{
LOG_SYS("nftw: symlink(\"" << target << "\", \"" << newPath.toString()
<< "\") failed");
return FTW_STOP;
}
}
break;
case FTW_DNR:
LOG_ERR("nftw: Cannot read directory '" << fpath << '\'');
return FTW_STOP;
case FTW_NS:
LOG_ERR("nftw: stat failed for '" << fpath << '\'');
return FTW_STOP;
default:
LOG_FTL("nftw: unexpected typeflag: '" << typeflag);
assert(!"nftw: unexpected typeflag.");
break;
}
return FTW_CONTINUE;
}
void linkOrCopy(std::string source,
const Path& destination,
std::string linkable,
LinkOrCopyType type)
{
std::string resolved = FileUtil::realpath(source);
if (resolved != source)
{
LOG_DBG("linkOrCopy: Using real path [" << resolved << "] instead of original link ["
<< source << "].");
source = std::move(resolved);
}
LOG_INF("linkOrCopy " << linkOrCopyTypeString(type) << " from [" << source << "] to ["
<< destination.toString() << "].");
linkOrCopyType = type;
sourceForLinkOrCopy = source;
if (sourceForLinkOrCopy.back() == '/')
sourceForLinkOrCopy.pop_back();
destinationForLinkOrCopy = destination;
linkableForLinkOrCopy = linkable;
linkOrCopyFileCount = 0;
linkOrCopyStartTime = std::chrono::steady_clock::now();
forceInitialCopy = detectSlowStackingFileSystem(destination.toString());
if (nftw(source.c_str(), linkOrCopyFunction, 10, FTW_ACTIONRETVAL|FTW_PHYS) == -1)
{
LOG_SYS("linkOrCopy: nftw() failed for '" << source << '\'');
}
if (linkOrCopyVerboseLogging)
{
linkOrCopyVerboseLogging = false;
const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - linkOrCopyStartTime).count();
const double seconds = (ms + 1) / 1000.; // At least 1ms to avoid div-by-zero.
const auto rate = linkOrCopyFileCount / seconds;
LOG_INF("Linking/Copying of " << linkOrCopyFileCount << " files from " << source
<< " to " << destinationForLinkOrCopy.toString()
<< " finished in " << seconds << " seconds, or " << rate
<< " files / second.");
}
}
#ifndef __FreeBSD__
void dropCapability(cap_value_t capability)
{
cap_t caps;
cap_value_t cap_list[] = { capability };
caps = cap_get_proc();
if (caps == nullptr)
{
LOG_SFL("cap_get_proc() failed");
Log::shutdown();
std::_Exit(1);
}
char *capText = cap_to_text(caps, nullptr);
LOG_TRC("Capabilities first: " << capText);
cap_free(capText);
if (cap_set_flag(caps, CAP_EFFECTIVE, sizeof(cap_list)/sizeof(cap_list[0]), cap_list, CAP_CLEAR) == -1 ||
cap_set_flag(caps, CAP_PERMITTED, sizeof(cap_list)/sizeof(cap_list[0]), cap_list, CAP_CLEAR) == -1)
{
LOG_SFL("cap_set_flag() failed");
Log::shutdown();
std::_Exit(1);
}
if (cap_set_proc(caps) == -1)
{
LOG_SFL("cap_set_proc() failed");
Log::shutdown();
std::_Exit(1);
}
capText = cap_to_text(caps, nullptr);
LOG_TRC("Capabilities now: " << capText);
cap_free(capText);
cap_free(caps);
}
#endif // __FreeBSD__
#endif
}
#endif
/// A document container.
/// Owns LOKitDocument instance and connections.
/// Manages the lifetime of a document.
/// Technically, we can host multiple documents
/// per process. But for security reasons don't.
/// However, we could have a coolkit instance
/// per user or group of users (a trusted circle).
class Document final : public DocumentManagerInterface
{
public:
/// We have two types of password protected documents
/// 1) Documents which require password to view
/// 2) Document which require password to modify
enum class PasswordType { ToView, ToModify };
public:
Document(const std::shared_ptr<lok::Office>& loKit,
const std::string& jailId,
const std::string& docKey,
const std::string& docId,
const std::string& url,
std::shared_ptr<TileQueue> tileQueue,
const std::shared_ptr<WebSocketHandler>& websocketHandler,
unsigned mobileAppDocId)
: _loKit(loKit),
_jailId(jailId),
_docKey(docKey),
_docId(docId),
_url(url),
_obfuscatedFileId(Util::getFilenameFromURL(docKey)),
_tileQueue(std::move(tileQueue)),
_websocketHandler(websocketHandler),
_haveDocPassword(false),
_isDocPasswordProtected(false),
_docPasswordType(PasswordType::ToView),
_stop(false),
_editorId(-1),
_editorChangeWarning(false),
_mobileAppDocId(mobileAppDocId),
_inputProcessingEnabled(true)
{
LOG_INF("Document ctor for [" << _docKey <<
"] url [" << anonymizeUrl(_url) << "] on child [" << _jailId <<
"] and id [" << _docId << "].");
assert(_loKit);
#if !MOBILEAPP
assert(singletonDocument == nullptr);
singletonDocument = this;
#endif
}
virtual ~Document()
{
LOG_INF("~Document dtor for [" << _docKey <<
"] url [" << anonymizeUrl(_url) << "] on child [" << _jailId <<
"] and id [" << _docId << "]. There are " <<
_sessions.size() << " views.");
// Wait for the callback worker to finish.
_stop = true;
_tileQueue->put("eof");
for (const auto& session : _sessions)
{
session.second->resetDocManager();
}
#ifdef IOS
DocumentData::deallocate(_mobileAppDocId);
#endif
}
const std::string& getUrl() const { return _url; }
/// Post the message - in the unipoll world we're in the right thread anyway
bool postMessage(const char* data, int size, const WSOpCode code) const
{
LOG_TRC("postMessage called with: " << getAbbreviatedMessage(data, size));
if (!_websocketHandler)
{
LOG_ERR("Child Doc: Bad socket while sending [" << getAbbreviatedMessage(data, size) << "].");
return false;
}
_websocketHandler->sendMessage(data, size, code);
return true;
}
bool createSession(const std::string& sessionId, int canonicalViewId)
{
try
{
if (_sessions.find(sessionId) != _sessions.end())
{
LOG_ERR("Session [" << sessionId << "] on url [" << anonymizeUrl(_url) << "] already exists.");
return true;
}
LOG_INF("Creating " << (_sessions.empty() ? "first" : "new") <<
" session for url: " << anonymizeUrl(_url) << " for sessionId: " <<
sessionId << " on jailId: " << _jailId);
auto session = std::make_shared<ChildSession>(
_websocketHandler, sessionId,
_jailId, JailRoot, *this);
_sessions.emplace(sessionId, session);
session->setCanonicalViewId(canonicalViewId);
int viewId = session->getViewId();
_lastUpdatedAt[viewId] = std::chrono::steady_clock::now();
_speedCount[viewId] = 0;
LOG_DBG("Sessions: " << _sessions.size());
return true;
}
catch (const std::exception& ex)
{
LOG_ERR("Exception while creating session [" << sessionId <<
"] on url [" << anonymizeUrl(_url) << "] - '" << ex.what() << "'.");
return false;
}
}
/// Purges dead connections and returns
/// the remaining number of clients.
/// Returns -1 on failure.
std::size_t purgeSessions()
{
std::vector<std::shared_ptr<ChildSession>> deadSessions;
std::size_t num_sessions = 0;
{
// If there are no live sessions, we don't need to do anything at all and can just
// bluntly exit, no need to clean up our own data structures. Also, there is a bug that
// causes the deadSessions.clear() call below to crash in some situations when the last
// session is being removed.
for (auto it = _sessions.cbegin(); it != _sessions.cend(); )
{
if (it->second->isCloseFrame())
{
deadSessions.push_back(it->second);
it = _sessions.erase(it);
}
else
{
++it;
}
}
num_sessions = _sessions.size();
#if !MOBILEAPP
if (num_sessions == 0)
{
LOG_FTL("Document [" << anonymizeUrl(_url) << "] has no more views, exiting bluntly.");
flushTraceEventRecordings();
Log::shutdown();
std::_Exit(EX_OK);
}
#endif
}
deadSessions.clear();
return num_sessions;
}
/// Set Document password for given URL
void setDocumentPassword(int passwordType)
{
// Log whether the document is password protected and a password is provided
LOG_INF("setDocumentPassword: passwordProtected=" << _isDocPasswordProtected <<
" passwordProvided=" << _haveDocPassword);
if (_isDocPasswordProtected && _haveDocPassword)
{
// it means this is the second attempt with the wrong password; abort the load operation
_loKit->setDocumentPassword(_jailedUrl.c_str(), nullptr);
return;
}
// One thing for sure, this is a password protected document
_isDocPasswordProtected = true;
if (passwordType == LOK_CALLBACK_DOCUMENT_PASSWORD)
_docPasswordType = PasswordType::ToView;
else if (passwordType == LOK_CALLBACK_DOCUMENT_PASSWORD_TO_MODIFY)
_docPasswordType = PasswordType::ToModify;
LOG_INF("Calling _loKit->setDocumentPassword");
if (_haveDocPassword)
_loKit->setDocumentPassword(_jailedUrl.c_str(), _docPassword.c_str());
else
_loKit->setDocumentPassword(_jailedUrl.c_str(), nullptr);
LOG_INF("setDocumentPassword returned.");
}
void renderTile(const StringVector& tokens)
{
TileCombined tileCombined(TileDesc::parse(tokens));
renderTiles(tileCombined, false);
}
void renderCombinedTiles(const StringVector& tokens)
{
TileCombined tileCombined = TileCombined::parse(tokens);
renderTiles(tileCombined, true);
}
void renderTiles(TileCombined &tileCombined, bool combined)
{
// Find a session matching our view / render settings.
const auto session = _sessions.findByCanonicalId(tileCombined.getNormalizedViewId());
if (!session)
{
LOG_ERR("Session is not found. Maybe exited after rendering request.");
return;
}
if (!_loKitDocument)
{
LOG_ERR("Tile rendering requested before loading document.");
return;
}
if (_loKitDocument->getViewsCount() <= 0)
{
LOG_ERR("Tile rendering requested without views.");
return;
}
#ifdef FIXME_RENDER_SETTINGS
// if necessary select a suitable rendering view eg. with 'show non-printing chars'
if (tileCombined.getNormalizedViewId())
_loKitDocument->setView(session->getViewId());
#endif
const auto blenderFunc = [&](unsigned char* data, int offsetX, int offsetY,
std::size_t pixmapWidth, std::size_t pixmapHeight,
int pixelWidth, int pixelHeight, LibreOfficeKitTileMode mode) {
if (session->watermark())
session->watermark()->blending(data, offsetX, offsetY, pixmapWidth, pixmapHeight,
pixelWidth, pixelHeight, mode);
};
const auto postMessageFunc = [&](const char* buffer, std::size_t length) {
postMessage(buffer, length, WSOpCode::Binary);
};
if (!RenderTiles::doRender(_loKitDocument, tileCombined, _pngCache, _pngPool, combined,
blenderFunc, postMessageFunc, _mobileAppDocId))
{
LOG_DBG("All tiles skipped, not producing empty tilecombine: message");
return;
}
}
bool sendTextFrame(const std::string& message)
{
return sendFrame(message.data(), message.size());
}
bool sendFrame(const char* buffer, int length, WSOpCode opCode = WSOpCode::Text) override
{
try
{
return postMessage(buffer, length, opCode);
}
catch (const Exception& exc)
{
LOG_ERR("Document::sendFrame: Exception: " << exc.displayText() <<
(exc.nested() ? "( " + exc.nested()->displayText() + ')' : ""));
}
return false;
}
void alertAllUsers(const std::string& cmd, const std::string& kind) override
{
alertAllUsers("errortoall: cmd=" + cmd + " kind=" + kind);
}
unsigned getMobileAppDocId() const override
{
return _mobileAppDocId;
}
static void GlobalCallback(const int type, const char* p, void* data)
{
if (SigUtil::getTerminationFlag())
return;
// unusual LOK event from another thread,
// pData - is Document with process' lifetime.
if (pushToMainThread(GlobalCallback, type, p, data))
return;
const std::string payload = p ? p : "(nil)";
Document* self = static_cast<Document*>(data);
if (type == LOK_CALLBACK_PROFILE_FRAME)
{
// We must send the trace data to the WSD process for output
LOG_TRC("Document::GlobalCallback " << lokCallbackTypeToString(type) << ": " << payload.length() << " bytes.");
self->sendTextFrame("traceevent: \n" + payload);
return;
}
LOG_TRC("Document::GlobalCallback " << lokCallbackTypeToString(type) <<
" [" << payload << "].");
if (type == LOK_CALLBACK_DOCUMENT_PASSWORD_TO_MODIFY ||
type == LOK_CALLBACK_DOCUMENT_PASSWORD)
{
// Mark the document password type.
self->setDocumentPassword(type);
return;
}
else if (type == LOK_CALLBACK_STATUS_INDICATOR_START ||
type == LOK_CALLBACK_STATUS_INDICATOR_SET_VALUE ||
type == LOK_CALLBACK_STATUS_INDICATOR_FINISH)
{
for (auto& it : self->_sessions)
{
std::shared_ptr<ChildSession> session = it.second;
if (session && !session->isCloseFrame())
{
session->loKitCallback(type, payload);
}
}
return;
}
else if (type == LOK_CALLBACK_JSDIALOG || type == LOK_CALLBACK_HYPERLINK_CLICKED)
{
if (self->_sessions.size() == 1)
{
auto it = self->_sessions.begin();
std::shared_ptr<ChildSession> session = it->second;
if (session && !session->isCloseFrame())
{
session->loKitCallback(type, payload);
// TODO. It should filter some messages
// before loading the document
session->getProtocol()->enableProcessInput(true);
}
}
}
// Broadcast leftover status indicator callbacks to all clients
self->broadcastCallbackToClients(type, payload);
}
static void ViewCallback(const int type, const char* p, void* data)
{
if (SigUtil::getTerminationFlag())
return;
// unusual LOK event from another thread.
// pData - is CallbackDescriptors which share process' lifetime.
if (pushToMainThread(ViewCallback, type, p, data))
return;
CallbackDescriptor* descriptor = static_cast<CallbackDescriptor*>(data);
assert(descriptor && "Null callback data.");
assert(descriptor->getDoc() && "Null Document instance.");
std::shared_ptr<TileQueue> tileQueue = descriptor->getDoc()->getTileQueue();
assert(tileQueue && "Null TileQueue.");
const std::string payload = p ? p : "(nil)";
LOG_TRC("Document::ViewCallback [" << descriptor->getViewId() <<
"] [" << lokCallbackTypeToString(type) <<
"] [" << payload << "].");
// when we examine the content of the JSON
std::string targetViewId;
if (type == LOK_CALLBACK_CELL_CURSOR)
{
StringVector tokens(Util::tokenize(payload, ','));
// Payload may be 'EMPTY'.
if (tokens.size() == 4)
{
int cursorX = std::stoi(tokens[0]);
int cursorY = std::stoi(tokens[1]);
int cursorWidth = std::stoi(tokens[2]);
int cursorHeight = std::stoi(tokens[3]);
tileQueue->updateCursorPosition(0, 0, cursorX, cursorY, cursorWidth, cursorHeight);
}
}
else if (type == LOK_CALLBACK_INVALIDATE_VISIBLE_CURSOR)
{
Poco::JSON::Parser parser;
const Poco::Dynamic::Var result = parser.parse(payload);
const auto& command = result.extract<Poco::JSON::Object::Ptr>();
std::string rectangle = command->get("rectangle").toString();
StringVector tokens(Util::tokenize(rectangle, ','));
// Payload may be 'EMPTY'.
if (tokens.size() == 4)
{
int cursorX = std::stoi(tokens[0]);
int cursorY = std::stoi(tokens[1]);
int cursorWidth = std::stoi(tokens[2]);
int cursorHeight = std::stoi(tokens[3]);
tileQueue->updateCursorPosition(0, 0, cursorX, cursorY, cursorWidth, cursorHeight);
}
}
else if (type == LOK_CALLBACK_INVALIDATE_VIEW_CURSOR ||
type == LOK_CALLBACK_CELL_VIEW_CURSOR)
{
Poco::JSON::Parser parser;
const Poco::Dynamic::Var result = parser.parse(payload);
const auto& command = result.extract<Poco::JSON::Object::Ptr>();
targetViewId = command->get("viewId").toString();
std::string part = command->get("part").toString();
std::string text = command->get("rectangle").toString();
StringVector tokens(Util::tokenize(text, ','));
// Payload may be 'EMPTY'.
if (tokens.size() == 4)
{
int cursorX = std::stoi(tokens[0]);
int cursorY = std::stoi(tokens[1]);
int cursorWidth = std::stoi(tokens[2]);
int cursorHeight = std::stoi(tokens[3]);
tileQueue->updateCursorPosition(std::stoi(targetViewId), std::stoi(part), cursorX, cursorY, cursorWidth, cursorHeight);
}
}
// merge various callback types together if possible
if (type == LOK_CALLBACK_INVALIDATE_TILES ||
type == LOK_CALLBACK_DOCUMENT_SIZE_CHANGED)
{
// no point in handling invalidations or page resizes per-view,
// all views have to be in sync
tileQueue->put("callback all " + std::to_string(type) + ' ' + payload);
}
else
tileQueue->put("callback " + std::to_string(descriptor->getViewId()) + ' ' + std::to_string(type) + ' ' + payload);
LOG_TRC("Document::ViewCallback end.");
}
private:
/// Helper method to broadcast callback and its payload to all clients
void broadcastCallbackToClients(const int type, const std::string& payload)
{
_tileQueue->put("callback all " + std::to_string(type) + ' ' + payload);
}
/// Load a document (or view) and register callbacks.
bool onLoad(const std::string& sessionId,
const std::string& uriAnonym,
const std::string& renderOpts) override
{
LOG_INF("Loading url [" << uriAnonym << "] for session [" << sessionId <<
"] which has " << (_sessions.size() - 1) << " sessions.");
// This shouldn't happen, but for sanity.
const auto it = _sessions.find(sessionId);
if (it == _sessions.end() || !it->second)
{
LOG_ERR("Cannot find session [" << sessionId << "] to load view for.");
return false;
}
std::shared_ptr<ChildSession> session = it->second;
try
{
if (!load(session, renderOpts))
return false;
}
catch (const std::exception &exc)
{
LOG_ERR("Exception while loading url [" << uriAnonym <<
"] for session [" << sessionId << "]: " << exc.what());
return false;
}
return true;
}
void onUnload(const ChildSession& session) override
{
const auto& sessionId = session.getId();
LOG_INF("Unloading session [" << sessionId << "] on url [" << anonymizeUrl(_url) << "].");
const int viewId = session.getViewId();
_tileQueue->removeCursorPosition(viewId);
if (_loKitDocument == nullptr)
{
LOG_ERR("Unloading session [" << sessionId << "] without loKitDocument.");
return;
}
_loKitDocument->setView(viewId);
_loKitDocument->registerCallback(nullptr, nullptr);
_loKit->registerCallback(nullptr, nullptr);
int viewCount = _loKitDocument->getViewsCount();
if (viewCount == 1)
{
#if !MOBILEAPP
if (_sessions.empty())
{
LOG_INF("Document [" << anonymizeUrl(_url) << "] has no more views, exiting bluntly.");
flushTraceEventRecordings();
Log::shutdown();
std::_Exit(EX_OK);
}
#endif
LOG_INF("Document [" << anonymizeUrl(_url) << "] has no more views, but has " <<
_sessions.size() << " sessions still. Destroying the document.");
#ifdef __ANDROID__
_loKitDocumentForAndroidOnly.reset();
#endif
_loKitDocument.reset();
LOG_INF("Document [" << anonymizeUrl(_url) << "] session [" << sessionId << "] unloaded Document.");
return;
}
else
{
_loKitDocument->destroyView(viewId);
}
// Since callback messages are processed on idle-timer,
// we could receive callbacks after destroying a view.
// Retain the CallbackDescriptor object, which is shared with Core.
// Do not: _viewIdToCallbackDescr.erase(viewId);
viewCount = _loKitDocument->getViewsCount();
LOG_INF("Document [" << anonymizeUrl(_url) << "] session [" <<
sessionId << "] unloaded view [" << viewId << "]. Have " <<
viewCount << " view" << (viewCount != 1 ? "s." : "."));
if (viewCount > 0)
{
// Broadcast updated view info
notifyViewInfo();
}
}
std::map<int, UserInfo> getViewInfo() override
{
return _sessionUserInfo;
}
std::shared_ptr<TileQueue>& getTileQueue() override
{
return _tileQueue;
}
int getEditorId() const override
{
return _editorId;
}
/// Notify all views with the given message
bool notifyAll(const std::string& msg) override
{
// Broadcast updated viewinfo to all clients.
return sendTextFrame("client-all " + msg);
}
/// Notify all views of viewId and their associated usernames
void notifyViewInfo() override
{
// Get the list of view ids from the core
const int viewCount = getLOKitDocument()->getViewsCount();
std::vector<int> viewIds(viewCount);
getLOKitDocument()->getViewIds(viewIds.data(), viewCount);
const std::map<int, UserInfo> viewInfoMap = getViewInfo();
const std::map<std::string, int> viewColorsMap = getViewColors();
// Double check if list of viewids from core and our list matches,
// and create an array of JSON objects containing id and username
std::ostringstream oss;
oss << "viewinfo: [";
for (const auto& viewId : viewIds)
{
oss << "{\"id\":" << viewId << ',';
int color = 0;
const auto itView = viewInfoMap.find(viewId);
if (itView == viewInfoMap.end())
{
LOG_ERR("No username found for viewId [" << viewId << "].");
oss << "\"username\":\"Unknown\",";
}
else
{
oss << "\"userid\":\"" << JsonUtil::escapeJSONValue(itView->second.getUserId()) << "\",";
const std::string username = itView->second.getUserName();
oss << "\"username\":\"" << JsonUtil::escapeJSONValue(username) << "\",";
if (!itView->second.getUserExtraInfo().empty())
oss << "\"userextrainfo\":" << itView->second.getUserExtraInfo() << ',';
const bool readonly = itView->second.isReadOnly();
oss << "\"readonly\":\"" << readonly << "\",";
const auto it = viewColorsMap.find(username);
if (it != viewColorsMap.end())
{
color = it->second;
}
}
oss << "\"color\":" << color << "},";
}
if (viewCount > 0)
oss.seekp(-1, std::ios_base::cur); // Remove last comma.
oss << ']';
// Broadcast updated viewinfo to all clients.
notifyAll(oss.str());
}
void updateEditorSpeeds(int id, int speed) override
{
int maxSpeed = -1, fastestUser = -1;
auto now = std::chrono::steady_clock::now();
_lastUpdatedAt[id] = now;
_speedCount[id] = speed;
for (const auto& it : _sessions)
{
const std::shared_ptr<ChildSession> session = it.second;
int sessionId = session->getViewId();
auto duration = (_lastUpdatedAt[id] - now);
std::chrono::milliseconds::rep durationInMs = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
if (_speedCount[sessionId] != 0 && durationInMs > 5000)
{
_speedCount[sessionId] = session->getSpeed();
_lastUpdatedAt[sessionId] = now;
}
if (_speedCount[sessionId] > maxSpeed)
{
maxSpeed = _speedCount[sessionId];
fastestUser = sessionId;
}
}
// 0 for preventing selection of the first always
// 1 for preventing new users from directly becoming editors
if (_editorId != fastestUser && (maxSpeed != 0 && maxSpeed != 1)) {
if (!_editorChangeWarning && _editorId != -1)
{
_editorChangeWarning = true;
}
else
{
_editorChangeWarning = false;
_editorId = fastestUser;
for (const auto& it : _sessions)
it.second->sendTextFrame("editor: " + std::to_string(_editorId));
}
}
else
_editorChangeWarning = false;
}
private:
// Get the color value for all author names from the core
std::map<std::string, int> getViewColors()
{
char* values = _loKitDocument->getCommandValues(".uno:TrackedChangeAuthors");
const std::string colorValues = std::string(values == nullptr ? "" : values);
std::free(values);
std::map<std::string, int> viewColors;
try
{
if (!colorValues.empty())
{
Poco::JSON::Parser parser;
Poco::JSON::Object::Ptr root = parser.parse(colorValues).extract<Poco::JSON::Object::Ptr>();
if (root->get("authors").type() == typeid(Poco::JSON::Array::Ptr))
{
Poco::JSON::Array::Ptr authorsArray = root->get("authors").extract<Poco::JSON::Array::Ptr>();
for (auto& authorVar: *authorsArray)
{
Poco::JSON::Object::Ptr authorObj = authorVar.extract<Poco::JSON::Object::Ptr>();
std::string authorName = authorObj->get("name").convert<std::string>();
int colorValue = authorObj->get("color").convert<int>();
viewColors[authorName] = colorValue;
}
}
}
}
catch(const Exception& exc)
{
LOG_ERR("Poco Exception: " << exc.displayText() <<
(exc.nested() ? " (" + exc.nested()->displayText() + ')' : ""));
}
return viewColors;
}
std::shared_ptr<lok::Document> load(const std::shared_ptr<ChildSession>& session,
const std::string& renderOpts)
{
const std::string sessionId = session->getId();
const std::string& uri = session->getJailedFilePath();
const std::string& uriAnonym = session->getJailedFilePathAnonym();
const std::string& userName = session->getUserName();
const std::string& userNameAnonym = session->getUserNameAnonym();
const std::string& docPassword = session->getDocPassword();
const bool haveDocPassword = session->getHaveDocPassword();
const std::string& lang = session->getLang();
const std::string& deviceFormFactor = session->getDeviceFormFactor();
const std::string& batchMode = session->getBatchMode();
const std::string& enableMacrosExecution = session->getEnableMacrosExecution();
const std::string& macroSecurityLevel = session->getMacroSecurityLevel();
std::string spellOnline;
std::string options;
if (!lang.empty())
options = "Language=" + lang;
if (!deviceFormFactor.empty())
options += ",DeviceFormFactor=" + deviceFormFactor;
if (!batchMode.empty())
options += ",Batch=" + batchMode;
if (!enableMacrosExecution.empty())
options += ",EnableMacrosExecution=" + enableMacrosExecution;
if (!macroSecurityLevel.empty())
options += ",MacroSecurityLevel=" + macroSecurityLevel;
if (!_loKitDocument)
{
// This is the first time we are loading the document
LOG_INF("Loading new document from URI: [" << uriAnonym << "] for session [" << sessionId << "].");
_loKit->registerCallback(GlobalCallback, this);
const int flags = LOK_FEATURE_DOCUMENT_PASSWORD
| LOK_FEATURE_DOCUMENT_PASSWORD_TO_MODIFY
| LOK_FEATURE_PART_IN_INVALIDATION_CALLBACK
| LOK_FEATURE_NO_TILED_ANNOTATIONS
| LOK_FEATURE_RANGE_HEADERS
| LOK_FEATURE_VIEWID_IN_VISCURSOR_INVALIDATION_CALLBACK;
_loKit->setOptionalFeatures(flags);
// Save the provided password with us and the jailed url
_haveDocPassword = haveDocPassword;
_docPassword = docPassword;
_jailedUrl = uri;
_isDocPasswordProtected = false;
const char *pURL = uri.c_str();
LOG_DBG("Calling lokit::documentLoad(" << FileUtil::anonymizeUrl(pURL) << ", \"" << options << "\").");
const auto start = std::chrono::steady_clock::now();
_loKitDocument.reset(_loKit->documentLoad(pURL, options.c_str()));
#ifdef __ANDROID__
_loKitDocumentForAndroidOnly = _loKitDocument;
#endif
const auto duration = std::chrono::steady_clock::now() - start;
const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(duration);
LOG_DBG("Returned lokit::documentLoad(" << FileUtil::anonymizeUrl(pURL) << ") in "
<< elapsed);
#ifdef IOS
DocumentData::get(_mobileAppDocId).loKitDocument = _loKitDocument.get();
#endif
if (!_loKitDocument || !_loKitDocument->get())
{
LOG_ERR("Failed to load: " << uriAnonym << ", error: " << _loKit->getError());
// Checking if wrong password or no password was reason for failure.
if (_isDocPasswordProtected)
{
LOG_INF("Document [" << uriAnonym << "] is password protected.");
if (!_haveDocPassword)
{
LOG_INF("No password provided for password-protected document [" << uriAnonym << "].");
std::string passwordFrame = "passwordrequired:";
if (_docPasswordType == PasswordType::ToView)
passwordFrame += "to-view";
else if (_docPasswordType == PasswordType::ToModify)
passwordFrame += "to-modify";
session->sendTextFrameAndLogError("error: cmd=load kind=" + passwordFrame);
}
else
{
LOG_INF("Wrong password for password-protected document [" << uriAnonym << "].");
session->sendTextFrameAndLogError("error: cmd=load kind=wrongpassword");
}
return nullptr;
}
session->sendTextFrameAndLogError("error: cmd=load kind=faileddocloading");
return nullptr;
}
// Only save the options on opening the document.
// No support for changing them after opening a document.
_renderOpts = renderOpts;
spellOnline = session->getSpellOnline();
}
else
{
LOG_INF("Document with url [" << uriAnonym << "] already loaded. Need to create new view for session [" << sessionId << "].");
// Check if this document requires password
if (_isDocPasswordProtected)
{
if (!haveDocPassword)
{
std::string passwordFrame = "passwordrequired:";
if (_docPasswordType == PasswordType::ToView)
passwordFrame += "to-view";
else if (_docPasswordType == PasswordType::ToModify)
passwordFrame += "to-modify";
session->sendTextFrameAndLogError("error: cmd=load kind=" + passwordFrame);
return nullptr;
}
else if (docPassword != _docPassword)
{
session->sendTextFrameAndLogError("error: cmd=load kind=wrongpassword");
return nullptr;
}
}
LOG_INF("Creating view to url [" << uriAnonym << "] for session [" << sessionId << "] with " << options << '.');
_loKitDocument->createView(options.c_str());
LOG_TRC("View to url [" << uriAnonym << "] created.");
}
LOG_INF("Initializing for rendering session [" << sessionId << "] on document url [" <<
anonymizeUrl(_url) << "] with: [" << makeRenderParams(_renderOpts, userNameAnonym, spellOnline) << "].");
// initializeForRendering() should be called before
// registerCallback(), as the previous creates a new view in Impress.
const std::string renderParams = makeRenderParams(_renderOpts, userName, spellOnline);
_loKitDocument->initializeForRendering(renderParams.c_str());
const int viewId = _loKitDocument->getView();
session->setViewId(viewId);
_sessionUserInfo[viewId] = UserInfo(session->getViewUserId(), session->getViewUserName(),
session->getViewUserExtraInfo(), session->isReadOnly());
_loKitDocument->setViewLanguage(viewId, lang.c_str());
// viewId's monotonically increase, and CallbackDescriptors are never freed.
_viewIdToCallbackDescr.emplace(viewId,
std::unique_ptr<CallbackDescriptor>(new CallbackDescriptor({ this, viewId })));
_loKitDocument->registerCallback(ViewCallback, _viewIdToCallbackDescr[viewId].get());
const int viewCount = _loKitDocument->getViewsCount();
LOG_INF("Document url [" << anonymizeUrl(_url) << "] for session [" <<
sessionId << "] loaded view [" << viewId << "]. Have " <<
viewCount << " view" << (viewCount != 1 ? "s." : "."));
session->initWatermark();
return _loKitDocument;
}
bool forwardToChild(const std::string& prefix, const std::vector<char>& payload)
{
assert(payload.size() > prefix.size());
// Remove the prefix and trim.
std::size_t index = prefix.size();
for ( ; index < payload.size(); ++index)
{
if (payload[index] != ' ')
{
break;
}
}
const char* data = payload.data() + index;
std::size_t size = payload.size() - index;
std::string name;
std::string sessionId;
if (COOLProtocol::parseNameValuePair(prefix, name, sessionId, '-') && name == "child")
{
const auto it = _sessions.find(sessionId);
if (it != _sessions.end())
{
std::shared_ptr<ChildSession> session = it->second;
static const std::string disconnect("disconnect");
if (size == disconnect.size() &&
strncmp(data, disconnect.data(), disconnect.size()) == 0)
{
if(session->getViewId() == _editorId) {
_editorId = -1;
}
LOG_DBG("Removing ChildSession [" << sessionId << "].");
// Tell them we're going quietly.
session->sendTextFrame("disconnected:");
_sessions.erase(it);
const std::size_t count = _sessions.size();
LOG_DBG("Have " << count << " child" << (count == 1 ? "" : "ren") <<
" after removing ChildSession [" << sessionId << "].");
// No longer needed, and allow session dtor to take it.
session.reset();
return true;
}
// No longer needed, and allow the handler to take it.
if (session)
{
std::vector<char> vect(size);
vect.assign(data, data + size);
// TODO this is probably wrong...
session->handleMessage(vect);
return true;
}
}
const std::string abbrMessage = getAbbreviatedMessage(data, size);
LOG_ERR("Child session [" << sessionId << "] not found to forward message: " << abbrMessage);
}
else
{
LOG_ERR("Failed to parse prefix of forward-to-child message: " << prefix);
}
return false;
}
template <typename T>
static Object::Ptr makePropertyValue(const std::string& type, const T& val)
{
Object::Ptr obj = new Object();
obj->set("type", type);
obj->set("value", val);
return obj;
}
static std::string makeRenderParams(const std::string& renderOpts, const std::string& userName, const std::string& spellOnline)
{
Object::Ptr renderOptsObj;
// Fill the object with renderoptions, if any
if (!renderOpts.empty())
{
Parser parser;
Poco::Dynamic::Var var = parser.parse(renderOpts);
renderOptsObj = var.extract<Object::Ptr>();
}
else
{
renderOptsObj = new Object();
}
// Append name of the user, if any, who opened the document to rendering options
if (!userName.empty())
{
// userName must be decoded already.
renderOptsObj->set(".uno:Author", makePropertyValue("string", userName));
}
// By default we enable spell-checking, unless it's disabled explicitly.
const bool bSet = (spellOnline != "false");
renderOptsObj->set(".uno:SpellOnline", makePropertyValue("boolean", bSet));
if (renderOptsObj)
{
std::ostringstream ossRenderOpts;
renderOptsObj->stringify(ossRenderOpts);
return ossRenderOpts.str();
}
return std::string();
}
public:
void enableProcessInput(bool enable = true){ _inputProcessingEnabled = enable; }
bool processInputEnabled() const { return _inputProcessingEnabled; }
bool hasQueueItems() const
{
return _tileQueue && !_tileQueue->isEmpty();
}
// poll is idle, are we ?
void checkIdle()
{
if (!processInputEnabled() || hasQueueItems())
{
LOG_TRC("Nearly idle - but have more queued items to process");
return; // more to do
}
sendTextFrame("idle");
// get rid of idle check for now.
ProcessToIdleDeadline = std::chrono::steady_clock::now() - std::chrono::milliseconds(10);
}
void drainQueue()
{
try
{
while (processInputEnabled() && hasQueueItems())
{
if (_stop || SigUtil::getTerminationFlag())
{
LOG_INF("_stop or TerminationFlag is set, breaking Document::drainQueue of loop");
break;
}
const TileQueue::Payload input = _tileQueue->pop();
LOG_TRC("Kit handling queue message: " << COOLProtocol::getAbbreviatedMessage(input));
const StringVector tokens = Util::tokenize(input.data(), input.size());
if (tokens.equals(0, "eof"))
{
LOG_INF("Received EOF. Finishing.");
break;
}
if (tokens.equals(0, "tile"))
{
renderTile(tokens);
}
else if (tokens.equals(0, "tilecombine"))
{
renderCombinedTiles(tokens);
}
else if (tokens.startsWith(0, "child-"))
{
forwardToChild(tokens[0], input);
}
else if (tokens.equals(0, "processtoidle"))
{
ProcessToIdleDeadline = std::chrono::steady_clock::now();
uint32_t timeoutUs = 0;
if (tokens.getUInt32(1, "timeout", timeoutUs))
ProcessToIdleDeadline += std::chrono::microseconds(timeoutUs);
}
else if (tokens.equals(0, "callback"))
{
if (tokens.size() >= 3)
{
bool broadcast = false;
int viewId = -1;
int exceptViewId = -1;
const std::string& target = tokens[1];
if (target == "all")
{
broadcast = true;
}
else if (COOLProtocol::matchPrefix("except-", target))
{
exceptViewId = std::stoi(target.substr(7));
broadcast = true;
}
else
{
viewId = std::stoi(target);
}
const int type = std::stoi(tokens[2]);
// payload is the rest of the message
const std::size_t offset = tokens[0].length() + tokens[1].length()
+ tokens[2].length() + 3; // + delims
const std::string payload(input.data() + offset, input.size() - offset);
// Forward the callback to the same view, demultiplexing is done by the LibreOffice core.
bool isFound = false;
for (const auto& it : _sessions)
{
if (!it.second)
continue;
ChildSession& session = *it.second;
if ((broadcast && (session.getViewId() != exceptViewId))
|| (!broadcast && (session.getViewId() == viewId)))
{
if (!session.isCloseFrame())
{
isFound = true;
session.loKitCallback(type, payload);
}
else
{
LOG_ERR("Session-thread of session ["
<< session.getId() << "] for view [" << viewId
<< "] is not running. Dropping ["
<< lokCallbackTypeToString(type) << "] payload ["
<< payload << ']');
}
if (!broadcast)
{
break;
}
}
}
if (!isFound)
{
LOG_ERR("Document::ViewCallback. Session [" << viewId <<
"] is no longer active to process [" << lokCallbackTypeToString(type) <<
"] [" << payload << "] message to Master Session.");
}
}
else
{
LOG_ERR("Invalid callback message: [" << COOLProtocol::getAbbreviatedMessage(input) << "].");
}
}
else
{
LOG_ERR("Unexpected request: [" << COOLProtocol::getAbbreviatedMessage(input) << "].");
}
}
}
catch (const std::exception& exc)
{
LOG_FTL("drainQueue: Exception: " << exc.what());
#if !MOBILEAPP
flushTraceEventRecordings();
Log::shutdown();
std::_Exit(EX_SOFTWARE);
#endif
}
catch (...)
{
LOG_FTL("drainQueue: Unknown exception");
#if !MOBILEAPP
flushTraceEventRecordings();
Log::shutdown();
std::_Exit(EX_SOFTWARE);
#endif
}
}
private:
/// Return access to the lok::Office instance.
std::shared_ptr<lok::Office> getLOKit() override
{
return _loKit;
}
/// Return access to the lok::Document instance.
std::shared_ptr<lok::Document> getLOKitDocument() override
{
if (!_loKitDocument)
{
LOG_ERR("Document [" << _docKey << "] is not loaded.");
throw std::runtime_error("Document " + _docKey + " is not loaded.");
}
return _loKitDocument;
}
std::string getObfuscatedFileId() override
{
return _obfuscatedFileId;
}
void alertAllUsers(const std::string& msg)
{
sendTextFrame(msg);
}
public:
void dumpState(std::ostream& oss)
{
oss << "Kit Document:\n"
<< "\n\tstop: " << _stop
<< "\n\tjailId: " << _jailId
<< "\n\tdocKey: " << _docKey
<< "\n\tdocId: " << _docId
<< "\n\turl: " << _url
<< "\n\tobfuscatedFileId: " << _obfuscatedFileId
<< "\n\tjailedUrl: " << _jailedUrl
<< "\n\trenderOpts: " << _renderOpts
<< "\n\thaveDocPassword: " << _haveDocPassword // not the pwd itself
<< "\n\tisDocPasswordProtected: " << _isDocPasswordProtected
<< "\n\tdocPasswordType: " << (int)_docPasswordType
<< "\n\teditorId: " << _editorId
<< "\n\teditorChangeWarning: " << _editorChangeWarning
<< "\n\tmobileAppDocId: " << _mobileAppDocId
<< "\n\tinputProcessingEnabled: " << _inputProcessingEnabled
<< "\n";
// dumpState:
// TODO: _websocketHandler - but this is an odd one.
_tileQueue->dumpState(oss);
_pngCache.dumpState(oss);
oss << "\tviewIdToCallbackDescr:";
for (const auto &it : _viewIdToCallbackDescr)
{
oss << "\n\t\tviewId: " << it.first
<< " editorId: " << it.second->getDoc()->getEditorId()
<< " mobileAppDocId: " << it.second->getDoc()->getMobileAppDocId();
}
oss << "\n";
_pngPool.dumpState(oss);
_sessions.dumpState(oss);
oss << "\tlastUpdatedAt:";
for (const auto &it : _lastUpdatedAt)
{
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
it.second.time_since_epoch()).count();
oss << "\n\t\tviewId: " << it.first
<< " last update time(ms): " << ms;
}
oss << "\n";
oss << "\tspeedCount:";
for (const auto &it : _speedCount)
{
oss << "\n\t\tviewId: " << it.first
<< " speed: " << it.second;
}
oss << "\n";
/// For showing disconnected user info in the doc repair dialog.
oss << "\tsessionUserInfo:";
for (const auto &it : _sessionUserInfo)
{
oss << "\n\t\tviewId: " << it.first
<< " userId: " << it.second.getUserId()
<< " userName: " << it.second.getUserName()
<< " userExtraInfo: " << it.second.getUserExtraInfo()
<< " readOnly: " << it.second.isReadOnly();
}
oss << "\n";
}
private:
std::shared_ptr<lok::Office> _loKit;
const std::string _jailId;
/// URL-based key. May be repeated during the lifetime of WSD.
const std::string _docKey;
/// Short numerical ID. Unique during the lifetime of WSD.
const std::string _docId;
const std::string _url;
const std::string _obfuscatedFileId;
std::string _jailedUrl;
std::string _renderOpts;
std::shared_ptr<lok::Document> _loKitDocument;
#ifdef __ANDROID__
static std::shared_ptr<lok::Document> _loKitDocumentForAndroidOnly;
#endif
std::shared_ptr<TileQueue> _tileQueue;
std::shared_ptr<WebSocketHandler> _websocketHandler;
PngCache _pngCache;
// Document password provided
std::string _docPassword;
// Whether password was provided or not
bool _haveDocPassword;
// Whether document is password protected
bool _isDocPasswordProtected;
// Whether password is required to view the document, or modify it
PasswordType _docPasswordType;
std::atomic<bool> _stop;
ThreadPool _pngPool;
std::condition_variable _cvLoading;
int _editorId;
bool _editorChangeWarning;
std::map<int, std::unique_ptr<CallbackDescriptor>> _viewIdToCallbackDescr;
SessionMap<ChildSession> _sessions;
std::map<int, std::chrono::steady_clock::time_point> _lastUpdatedAt;
std::map<int, int> _speedCount;
/// For showing disconnected user info in the doc repair dialog.
std::map<int, UserInfo> _sessionUserInfo;
#ifdef __ANDROID__
friend std::shared_ptr<lok::Document> getLOKDocumentForAndroidOnly();
#endif
const unsigned _mobileAppDocId;
bool _inputProcessingEnabled;
};
#if !defined FUZZER && !defined BUILDING_TESTS && !MOBILEAPP
// When building the fuzzer we link COOLWSD.cpp into the same executable so the
// Protected::emitOneRecording() there gets used. When building the unit tests the one in
// TraceEvent.cpp gets used.
static constexpr int traceEventRecordingsCapacity = 100;
static std::vector<std::string> traceEventRecordings;
static void flushTraceEventRecordings()
{
if (traceEventRecordings.size() == 0)
return;
std::size_t totalLength = 0;
for (const auto& i: traceEventRecordings)
totalLength += i.length();
std::string recordings;
recordings.reserve(totalLength);
for (const auto& i: traceEventRecordings)
recordings += i;
singletonDocument->sendTextFrame("traceevent: \n" + recordings);
traceEventRecordings.clear();
}
// The checks for singletonDocument below are to catch if this gets called in the ForKit process.
void TraceEvent::emitOneRecordingIfEnabled(const std::string &recording)
{
// This can be called before the config system is initialized. Guard against that, as calling
// config::getBool() would cause an assertion failure.
static bool configChecked = false;
static bool traceEventsEnabled;
if (!configChecked && config::isInitialized())
{
traceEventsEnabled = config::getBool("trace_event[@enable]", false);
configChecked = true;
}
if (configChecked && !traceEventsEnabled)
return;
if (singletonDocument == nullptr)
return;
singletonDocument->sendTextFrame("forcedtraceevent: \n" + recording);
}
void TraceEvent::emitOneRecording(const std::string &recording)
{
static const bool traceEventsEnabled = config::getBool("trace_event[@enable]", false);
if (!traceEventsEnabled)
return;
if (!TraceEvent::isRecordingOn())
return;
if (singletonDocument == nullptr)
return;
if (traceEventRecordings.size() >= traceEventRecordingsCapacity)
flushTraceEventRecordings();
else if (traceEventRecordings.size() == 0 && traceEventRecordings.capacity() < traceEventRecordingsCapacity)
traceEventRecordings.reserve(traceEventRecordingsCapacity);
traceEventRecordings.emplace_back(recording + "\n");
}
#elif !MOBILEAPP
static void flushTraceEventRecordings()
{
}
#endif
#ifdef __ANDROID__
std::shared_ptr<lok::Document> Document::_loKitDocumentForAndroidOnly = std::shared_ptr<lok::Document>();
std::shared_ptr<lok::Document> getLOKDocumentForAndroidOnly()
{
return Document::_loKitDocumentForAndroidOnly;
}
#endif
class KitSocketPoll final : public SocketPoll
{
std::chrono::steady_clock::time_point _pollEnd;
std::shared_ptr<Document> _document;
static KitSocketPoll *mainPoll;
KitSocketPoll() :
SocketPoll("kit")
{
#ifdef IOS
terminationFlag = false;
#endif
mainPoll = this;
}
public:
~KitSocketPoll()
{
// Just to make it easier to set a breakpoint
mainPoll = nullptr;
}
static void dumpGlobalState(std::ostream &oss)
{
if (mainPoll)
{
if (!mainPoll->_document)
oss << "KitSocketPoll: no doc\n";
else
{
mainPoll->_document->dumpState(oss);
mainPoll->dumpState(oss);
}
}
else
oss << "KitSocketPoll: none\n";
}
static std::shared_ptr<KitSocketPoll> create()
{
KitSocketPoll *p = new KitSocketPoll();
auto result = std::shared_ptr<KitSocketPoll>(p);
#ifdef IOS
std::unique_lock<std::mutex> lock(KSPollsMutex);
KSPolls.push_back(result);
#endif
return result;
}
// process pending message-queue events.
void drainQueue()
{
SigUtil::checkDumpGlobalState(dump_kit_state);
if (_document)
_document->drainQueue();
}
// called from inside poll, inside a wakeup
void wakeupHook()
{
_pollEnd = std::chrono::steady_clock::now();
}
// a LOK compatible poll function merging the functions.
// returns the number of events signalled
int kitPoll(int timeoutMicroS)
{
ProfileZone profileZone("KitSocketPoll::kitPoll");
if (SigUtil::getTerminationFlag())
{
LOG_TRC("Termination of unipoll mainloop flagged");
return -1;
}
// The maximum number of extra events to process beyond the first.
int maxExtraEvents = 15;
int eventsSignalled = 0;
auto startTime = std::chrono::steady_clock::now();
// handle processtoidle waiting optimization
bool checkForIdle = ProcessToIdleDeadline >= startTime;
if (timeoutMicroS < 0)
{
// Flush at most 1 + maxExtraEvents, or return when nothing left.
while (poll(std::chrono::microseconds::zero()) > 0 && maxExtraEvents-- > 0)
++eventsSignalled;
}
else
{
if (checkForIdle)
timeoutMicroS = 0;
// Flush at most maxEvents+1, or return when nothing left.
_pollEnd = startTime + std::chrono::microseconds(timeoutMicroS);
do
{
int realTimeout = timeoutMicroS;
if (_document && _document->hasQueueItems())
realTimeout = 0;
if (poll(std::chrono::microseconds(realTimeout)) <= 0)
break;
const auto now = std::chrono::steady_clock::now();
drainQueue();
timeoutMicroS = std::chrono::duration_cast<std::chrono::microseconds>(_pollEnd - now).count();
++eventsSignalled;
}
while (timeoutMicroS > 0 && !SigUtil::getTerminationFlag() && maxExtraEvents-- > 0);
}
if (_document && checkForIdle && eventsSignalled == 0 &&
timeoutMicroS > 0 && !hasCallbacks() && !hasBuffered())
{
auto remainingTime = ProcessToIdleDeadline - startTime;
LOG_TRC("Poll of " << timeoutMicroS << " vs. remaining time of: " <<
std::chrono::duration_cast<std::chrono::microseconds>(remainingTime).count());
// would we poll until then if we could ?
if (remainingTime < std::chrono::microseconds(timeoutMicroS))
_document->checkIdle();
else
LOG_TRC("Poll of woudl not close gap - continuing");
}
drainQueue();
#if !MOBILEAPP
if (_document && _document->purgeSessions() == 0)
{
LOG_INF("Last session discarded. Setting TerminationFlag");
SigUtil::setTerminationFlag();
return -1;
}
#endif
// Report the number of events we processed.
return eventsSignalled;
}
void setDocument(std::shared_ptr<Document> document)
{
_document = std::move(document);
}
// unusual LOK event from another thread, push into our loop to process.
static bool pushToMainThread(LibreOfficeKitCallback callback, int type, const char *p, void *data)
{
if (mainPoll && mainPoll->getThreadOwner() != std::this_thread::get_id())
{
LOG_TRC("Unusual push callback to main thread");
std::shared_ptr<std::string> pCopy;
if (p)
pCopy = std::make_shared<std::string>(p, strlen(p));
mainPoll->addCallback([=]{
LOG_TRC("Unusual process callback in main thread");
callback(type, pCopy ? pCopy->c_str() : nullptr, data);
});
return true;
}
return false;
}
#ifdef IOS
static std::mutex KSPollsMutex;
// static std::condition_variable KSPollsCV;
static std::vector<std::weak_ptr<KitSocketPoll>> KSPolls;
std::mutex terminationMutex;
std::condition_variable terminationCV;
bool terminationFlag;
#endif
};
KitSocketPoll *KitSocketPoll::mainPoll = nullptr;
bool pushToMainThread(LibreOfficeKitCallback cb, int type, const char *p, void *data)
{
return KitSocketPoll::pushToMainThread(cb, type, p, data);
}
#ifdef IOS
std::mutex KitSocketPoll::KSPollsMutex;
// std::condition_variable KitSocketPoll::KSPollsCV;
std::vector<std::weak_ptr<KitSocketPoll>> KitSocketPoll::KSPolls;
#endif
class KitWebSocketHandler final : public WebSocketHandler
{
std::shared_ptr<TileQueue> _queue;
std::string _socketName;
std::shared_ptr<lok::Office> _loKit;
std::string _jailId;
std::shared_ptr<Document> _document;
std::shared_ptr<KitSocketPoll> _ksPoll;
const unsigned _mobileAppDocId;
public:
KitWebSocketHandler(const std::string& socketName, const std::shared_ptr<lok::Office>& loKit, const std::string& jailId, std::shared_ptr<KitSocketPoll> ksPoll, unsigned mobileAppDocId) :
WebSocketHandler(/* isClient = */ true, /* isMasking */ false),
_queue(std::make_shared<TileQueue>()),
_socketName(socketName),
_loKit(loKit),
_jailId(jailId),
_ksPoll(ksPoll),
_mobileAppDocId(mobileAppDocId)
{
}
~KitWebSocketHandler()
{
// Just to make it easier to set a breakpoint
}
protected:
void handleMessage(const std::vector<char>& data) override
{
// To get A LOT of Trace Events, to exercide their handling, uncomment this:
// ProfileZone profileZone("KitWebSocketHandler::handleMessage");
std::string message(data.data(), data.size());
#if !MOBILEAPP
if (UnitKit::get().filterKitMessage(this, message))
return;
#endif
StringVector tokens = Util::tokenize(message);
Log::StreamLogger logger = Log::debug();
if (logger.enabled())
{
logger << _socketName << ": recv [";
for (const auto& token : tokens)
{
// Don't log user-data, there are anonymized versions that get logged instead.
if (tokens.startsWith(token, "jail") ||
tokens.startsWith(token, "author") ||
tokens.startsWith(token, "name") ||
tokens.startsWith(token, "url"))
continue;
logger << tokens.getParam(token) << ' ';
}
LOG_END(logger, true);
}
// Note: Syntax or parsing errors here are unexpected and fatal.
if (SigUtil::getTerminationFlag())
{
LOG_DBG("Too late, TerminationFlag is set, we're going down");
}
else if (tokens.equals(0, "session"))
{
const std::string& sessionId = tokens[1];
const std::string& docKey = tokens[2];
const std::string& docId = tokens[3];
const int canonicalViewId = std::stoi(tokens[4]);
const std::string fileId = Util::getFilenameFromURL(docKey);
Util::mapAnonymized(fileId, fileId); // Identity mapping, since fileId is already obfuscated
std::string url;
URI::decode(docKey, url);
LOG_INF("New session [" << sessionId << "] request on url [" << url << "] with viewId " << canonicalViewId);
#ifndef IOS
Util::setThreadName("kit" SHARED_DOC_THREADNAME_SUFFIX + docId);
#endif
if (!_document)
{
_document = std::make_shared<Document>(
_loKit, _jailId, docKey, docId, url, _queue,
std::static_pointer_cast<WebSocketHandler>(shared_from_this()),
_mobileAppDocId);
_ksPoll->setDocument(_document);
// We need to send the process name information to WSD if Trace Event recording is enabled (but
// not turned on) because it might be turned on later.
// We can do this only after creating the Document object.
TraceEvent::emitOneRecordingIfEnabled(std::string("{\"name\":\"process_name\",\"ph\":\"M\",\"args\":{\"name\":\"")
+ "Kit-" + docId
+ "\"},\"pid\":"
+ std::to_string(getpid())
+ ",\"tid\":"
+ std::to_string(Util::getThreadId())
+ "},\n");
}
// Validate and create session.
if (!(url == _document->getUrl() && _document->createSession(sessionId, canonicalViewId)))
{
LOG_DBG("CreateSession failed.");
}
}
else if (tokens.equals(0, "exit"))
{
#if !MOBILEAPP
LOG_INF("Terminating immediately due to parent 'exit' command.");
flushTraceEventRecordings();
Log::shutdown();
std::_Exit(EX_SOFTWARE);
#else
#ifdef IOS
LOG_INF("Setting our KitSocketPoll's termination flag due to 'exit' command.");
std::unique_lock<std::mutex> lock(_ksPoll->terminationMutex);
_ksPoll->terminationFlag = true;
_ksPoll->terminationCV.notify_all();
#else
LOG_INF("Setting TerminationFlag due to 'exit' command.");
SigUtil::setTerminationFlag();
#endif
_document.reset();
#endif
}
else if (tokens.equals(0, "tile") || tokens.equals(0, "tilecombine") || tokens.equals(0, "canceltiles") ||
tokens.equals(0, "paintwindow") || tokens.equals(0, "resizewindow") ||
COOLProtocol::getFirstToken(tokens[0], '-') == "child")
{
if (_document)
{
_queue->put(message);
}
else
{
LOG_WRN("No document while processing " << tokens[0] << " request.");
}
}
else if (tokens.size() == 3 && tokens.equals(0, "setconfig"))
{
#if !MOBILEAPP
// Currently only rlimit entries are supported.
if (!Rlimit::handleSetrlimitCommand(tokens))
{
LOG_ERR("Unknown setconfig command: " << message);
}
#endif
}
else if (tokens.equals(0, "setloglevel"))
{
Log::logger().setLevel(tokens[1]);
}
else
{
LOG_ERR("Bad or unknown token [" << tokens[0] << ']');
}
}
virtual void enableProcessInput(bool enable = true) override
{
WebSocketHandler::enableProcessInput(enable);
if (_document)
_document->enableProcessInput(enable);
// Wake up poll to process data from socket input buffer
if (enable && _ksPoll)
{
_ksPoll->wakeup();
}
}
void onDisconnect() override
{
#if !MOBILEAPP
LOG_ERR("Kit connection lost without exit arriving from wsd. Setting TerminationFlag");
SigUtil::setTerminationFlag();
#endif
#ifdef IOS
{
std::unique_lock<std::mutex> lock(_ksPoll->terminationMutex);
_ksPoll->terminationFlag = true;
_ksPoll->terminationCV.notify_all();
}
#endif
_ksPoll.reset();
}
};
void documentViewCallback(const int type, const char* payload, void* data)
{
Document::ViewCallback(type, payload, data);
}
/// Called by LOK main-loop the central location for data processing.
int pollCallback(void* pData, int timeoutUs)
{
#ifndef IOS
if (!pData)
return 0;
else
return reinterpret_cast<KitSocketPoll*>(pData)->kitPoll(timeoutUs);
#else
std::unique_lock<std::mutex> lock(KitSocketPoll::KSPollsMutex);
std::vector<std::shared_ptr<KitSocketPoll>> v;
for (const auto &i : KitSocketPoll::KSPolls)
{
auto p = i.lock();
if (p)
v.push_back(p);
}
lock.unlock();
if (v.size() == 0)
{
std::this_thread::sleep_for(std::chrono::microseconds(timeoutUs));
}
else
{
for (const auto &p : v)
p->kitPoll(timeoutUs);
}
// We never want to exit the main loop
return 0;
#endif
}
/// Called by LOK main-loop
void wakeCallback(void* pData)
{
#ifndef IOS
if (!pData)
return;
else
return reinterpret_cast<KitSocketPoll*>(pData)->wakeup();
#else
std::unique_lock<std::mutex> lock(KitSocketPoll::KSPollsMutex);
if (KitSocketPoll::KSPolls.size() == 0)
return;
std::vector<std::shared_ptr<KitSocketPoll>> v;
for (const auto &i : KitSocketPoll::KSPolls)
{
auto p = i.lock();
if (p)
v.push_back(p);
}
lock.unlock();
for (const auto &p : v)
p->wakeup();
#endif
}
#ifndef BUILDING_TESTS
void lokit_main(
#if !MOBILEAPP
const std::string& childRoot,
const std::string& jailId,
const std::string& sysTemplate,
const std::string& loTemplate,
const std::string& loSubPath,
bool noCapabilities,
bool noSeccomp,
bool queryVersion,
bool displayVersion,
#else
int docBrokerSocket,
const std::string& userInterface,
#endif
std::size_t numericIdentifier
)
{
#if !MOBILEAPP
#ifndef FUZZER
SigUtil::setFatalSignals("kit startup of " COOLWSD_VERSION " " COOLWSD_VERSION_HASH);
SigUtil::setTerminationSignals();
#endif
Util::setThreadName("kit_spare_" + Util::encodeId(numericIdentifier, 3));
// Reinitialize logging when forked.
const bool logToFile = std::getenv("COOL_LOGFILE");
const char* logFilename = std::getenv("COOL_LOGFILENAME");
const char* logLevel = std::getenv("COOL_LOGLEVEL");
const bool logColor = config::getBool("logging.color", true) && isatty(fileno(stderr));
std::map<std::string, std::string> logProperties;
if (logToFile && logFilename)
{
logProperties["path"] = std::string(logFilename);
}
Util::rng::reseed();
const std::string LogLevel = logLevel ? logLevel : "trace";
const bool bTraceStartup = (std::getenv("COOL_TRACE_STARTUP") != nullptr);
Log::initialize("kit", bTraceStartup ? "trace" : logLevel, logColor, logToFile, logProperties);
if (bTraceStartup && LogLevel != "trace")
{
LOG_INF("Setting log-level to [trace] and delaying setting to configured [" << LogLevel << "] until after Kit initialization.");
}
const char* pAnonymizationSalt = std::getenv("COOL_ANONYMIZATION_SALT");
if (pAnonymizationSalt)
{
AnonymizationSalt = std::stoull(std::string(pAnonymizationSalt));
AnonymizeUserData = true;
}
LOG_INF("User-data anonymization is " << (AnonymizeUserData ? "enabled." : "disabled."));
assert(!childRoot.empty());
assert(!sysTemplate.empty());
assert(!loTemplate.empty());
assert(!loSubPath.empty());
LOG_INF("Kit process for Jail [" << jailId << "] started.");
std::string userdir_url;
std::string instdir_path;
int ProcSMapsFile = -1;
// lokit's destroy typically throws from
// framework/source/services/modulemanager.cxx:198
// So we insure it lives until std::_Exit is called.
std::shared_ptr<lok::Office> loKit;
ChildSession::NoCapsForKit = noCapabilities;
#endif // MOBILEAPP
try
{
#if !MOBILEAPP
const Path jailPath = Path::forDirectory(childRoot + '/' + jailId);
const std::string jailPathStr = jailPath.toString();
LOG_INF("Jail path: " << jailPathStr);
File(jailPath).createDirectories();
chmod(jailPathStr.c_str(), S_IXUSR | S_IWUSR | S_IRUSR);
if (!ChildSession::NoCapsForKit)
{
std::chrono::time_point<std::chrono::steady_clock> jailSetupStartTime
= std::chrono::steady_clock::now();
userdir_url = "file:///tmp/user";
instdir_path = '/' + loSubPath + "/program";
Poco::Path jailLOInstallation(jailPath, loSubPath);
jailLOInstallation.makeDirectory();
const std::string loJailDestPath = jailLOInstallation.toString();
// The bind-mount implementation: inlined here to mirror
// the fallback link/copy version bellow.
const auto mountJail = [&]() -> bool {
// Mount sysTemplate for the jail directory.
LOG_INF("Mounting " << sysTemplate << " -> " << jailPathStr);
if (!JailUtil::bind(sysTemplate, jailPathStr)
|| !JailUtil::remountReadonly(sysTemplate, jailPathStr))
{
LOG_ERR("Failed to mount [" << sysTemplate << "] -> [" << jailPathStr
<< "], will link/copy contents.");
return false;
}
// Mount loTemplate inside it.
LOG_INF("Mounting " << loTemplate << " -> " << loJailDestPath);
Poco::File(loJailDestPath).createDirectories();
if (!JailUtil::bind(loTemplate, loJailDestPath)
|| !JailUtil::remountReadonly(loTemplate, loJailDestPath))
{
LOG_WRN("Failed to mount [" << loTemplate << "] -> [" << loJailDestPath
<< "], will link/copy contents.");
return false;
}
// tmpdir inside the jail for added sercurity.
const std::string tempRoot = Poco::Path(childRoot, "tmp").toString();
const std::string tmpSubDir = Poco::Path(tempRoot, "cool-" + jailId).toString();
Poco::File(tmpSubDir).createDirectories();
const std::string jailTmpDir = Poco::Path(jailPath, "tmp").toString();
LOG_INF("Mounting random temp dir " << tmpSubDir << " -> " << jailTmpDir);
if (!JailUtil::bind(tmpSubDir, jailTmpDir))
{
LOG_ERR("Failed to mount [" << tmpSubDir << "] -> [" << jailTmpDir
<< "], will link/copy contents.");
return false;
}
return true;
};
// Copy (link) LO installation and other necessary files into it from the template.
bool bindMount = JailUtil::isBindMountingEnabled();
if (bindMount)
{
if (!mountJail())
{
LOG_INF("Cleaning up jail before linking/copying.");
JailUtil::removeJail(jailPathStr);
bindMount = false;
JailUtil::disableBindMounting();
}
}
if (!bindMount)
{
LOG_INF("Mounting is disabled, will link/copy " << sysTemplate << " -> "
<< jailPathStr);
const std::string linkablePath = childRoot + "/linkable";
linkOrCopy(sysTemplate, jailPath, linkablePath, LinkOrCopyType::All);
linkOrCopy(loTemplate, loJailDestPath, linkablePath, LinkOrCopyType::LO);
// Update the dynamic files inside the jail.
if (!JailUtil::SysTemplate::updateDynamicFiles(jailPathStr))
{
LOG_ERR(
"Failed to update the dynamic files in the jail ["
<< jailPathStr
<< "]. If the systemplate directory is owned by a superuser or is "
"read-only, running the installation scripts with the owner's account "
"should update these files. Some functionality may be missing.");
}
// Create a file to mark this a copied jail.
JailUtil::markJailCopied(jailPathStr);
}
// Setup the devices inside /tmp and set TMPDIR.
JailUtil::setupJailDevNodes(Poco::Path(jailPath, "/tmp").toString());
::setenv("TMPDIR", "/tmp", 1);
// HOME must be writable, so create it in /tmp.
constexpr const char* HomePathInJail = "/tmp/home";
Poco::File(Poco::Path(jailPath, HomePathInJail)).createDirectories();
::setenv("HOME", HomePathInJail, 1);
const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - jailSetupStartTime);
LOG_DBG("Initialized jail files in " << ms);
ProcSMapsFile = open("/proc/self/smaps", O_RDONLY);
if (ProcSMapsFile < 0)
LOG_SYS("Failed to open /proc/self/smaps. Memory stats will be missing.");
LOG_INF("chroot(\"" << jailPathStr << "\")");
if (chroot(jailPathStr.c_str()) == -1)
{
LOG_SFL("chroot(\"" << jailPathStr << "\") failed");
Log::shutdown();
std::_Exit(EX_SOFTWARE);
}
if (chdir("/") == -1)
{
LOG_SFL("chdir(\"/\") in jail failed");
Log::shutdown();
std::_Exit(EX_SOFTWARE);
}
#ifndef __FreeBSD__
dropCapability(CAP_SYS_CHROOT);
dropCapability(CAP_MKNOD);
dropCapability(CAP_FOWNER);
dropCapability(CAP_CHOWN);
#else
cap_enter();
#endif
LOG_DBG("Initialized jail nodes, dropped caps.");
}
else // noCapabilities set
{
LOG_WRN("Security warning: running without chroot jails is insecure.");
LOG_INF("Using template ["
<< loTemplate << "] as install subpath directly, without chroot jail setup.");
userdir_url = "file:///" + jailPathStr + "/tmp/user";
instdir_path = '/' + loTemplate + "/program";
JailRoot = jailPathStr;
}
LOG_DBG("Initializing LOK with instdir [" << instdir_path << "] and userdir ["
<< userdir_url << "].");
LibreOfficeKit *kit;
{
const char *instdir = instdir_path.c_str();
const char *userdir = userdir_url.c_str();
#ifndef KIT_IN_PROCESS
kit = UnitKit::get().lok_init(instdir, userdir);
#else
kit = nullptr;
#ifdef FUZZER
if (COOLWSD::DummyLOK)
kit = dummy_lok_init_2(instdir, userdir);
#endif
#endif
if (!kit)
{
kit = (initFunction ? initFunction(instdir, userdir)
: lok_init_2(instdir, userdir));
}
loKit = std::make_shared<lok::Office>(kit);
if (!loKit)
{
LOG_FTL("LibreOfficeKit initialization failed. Exiting.");
Log::shutdown();
std::_Exit(EX_SOFTWARE);
}
}
// Lock down the syscalls that can be used
if (!Seccomp::lockdown(Seccomp::Type::KIT))
{
if (!noSeccomp)
{
LOG_FTL("LibreOfficeKit seccomp security lockdown failed. Exiting.");
Log::shutdown();
std::_Exit(EX_SOFTWARE);
}
LOG_ERR("LibreOfficeKit seccomp security lockdown failed, but configured to continue. "
"You are running in a significantly less secure mode.");
}
rlimit rlim = { 0, 0 };
if (getrlimit(RLIMIT_AS, &rlim) == 0)
LOG_INF("RLIMIT_AS is " << Util::getHumanizedBytes(rlim.rlim_max) << " (" << rlim.rlim_max << " bytes)");
else
LOG_SYS("Failed to get RLIMIT_AS");
if (getrlimit(RLIMIT_STACK, &rlim) == 0)
LOG_INF("RLIMIT_STACK is " << Util::getHumanizedBytes(rlim.rlim_max) << " (" << rlim.rlim_max << " bytes)");
else
LOG_SYS("Failed to get RLIMIT_STACK");
if (getrlimit(RLIMIT_FSIZE, &rlim) == 0)
LOG_INF("RLIMIT_FSIZE is " << Util::getHumanizedBytes(rlim.rlim_max) << " (" << rlim.rlim_max << " bytes)");
else
LOG_SYS("Failed to get RLIMIT_FSIZE");
if (getrlimit(RLIMIT_NOFILE, &rlim) == 0)
LOG_INF("RLIMIT_NOFILE is " << rlim.rlim_max << " files.");
else
LOG_SYS("Failed to get RLIMIT_NOFILE");
LOG_INF("Kit process for Jail [" << jailId << "] is ready.");
std::string pathAndQuery(NEW_CHILD_URI);
pathAndQuery.append("?jailid=");
pathAndQuery.append(jailId);
if (queryVersion)
{
char* versionInfo = loKit->getVersionInfo();
std::string versionString(versionInfo);
if (displayVersion)
std::cout << "office version details: " << versionString << std::endl;
SigUtil::setVersionInfo(versionString);
// Add some parameters we want to pass to the client. Could not figure out how to get
// the configuration parameters from COOLWSD.cpp's initialize() or coolwsd.xml here, so
// oh well, just have the value hardcoded in KitHelper.hpp. It isn't really useful to
// "tune" it at end-user installations anyway, I think.
auto versionJSON = Poco::JSON::Parser().parse(versionString).extract<Poco::JSON::Object::Ptr>();
versionJSON->set("tunnelled_dialog_image_cache_size", std::to_string(LOKitHelper::tunnelledDialogImageCacheSize));
std::stringstream ss;
versionJSON->stringify(ss);
versionString = ss.str();
std::string encodedVersion;
Poco::URI::encode(versionString, "?#/", encodedVersion);
pathAndQuery.append("&version=");
pathAndQuery.append(encodedVersion);
free(versionInfo);
}
#else // MOBILEAPP
#ifndef IOS
// Was not done by the preload.
// For iOS we call it in -[AppDelegate application: didFinishLaunchingWithOptions:]
setupKitEnvironment(userInterface);
#endif
#if (defined(__linux__) && !defined(__ANDROID__)) || defined(__FreeBSD__)
Poco::URI userInstallationURI("file", LO_PATH);
LibreOfficeKit *kit = lok_init_2(LO_PATH "/program", userInstallationURI.toString().c_str());
#else
#ifdef IOS // In the iOS app we call lok_init_2() just once, when the app starts
static LibreOfficeKit *kit = lo_kit;
#else
static LibreOfficeKit *kit = lok_init_2(nullptr, nullptr);
#endif
#endif
assert(kit);
static std::shared_ptr<lok::Office> loKit = std::make_shared<lok::Office>(kit);
assert(loKit);
COOLWSD::LOKitVersion = loKit->getVersionInfo();
// Dummies
const std::string jailId = "jailid";
#endif // MOBILEAPP
auto mainKit = KitSocketPoll::create();
mainKit->runOnClientThread(); // We will do the polling on this thread.
std::shared_ptr<KitWebSocketHandler> websocketHandler =
std::make_shared<KitWebSocketHandler>("child_ws", loKit, jailId, mainKit, numericIdentifier);
#if !MOBILEAPP
mainKit->insertNewUnixSocket(MasterLocation, pathAndQuery, websocketHandler, ProcSMapsFile);
#else
mainKit->insertNewFakeSocket(docBrokerSocket, websocketHandler);
#endif
LOG_INF("New kit client websocket inserted.");
#if !MOBILEAPP
if (bTraceStartup && LogLevel != "trace")
{
LOG_INF("Kit initialization complete: setting log-level to [" << LogLevel << "] as configured.");
Log::logger().setLevel(LogLevel);
}
#endif
#ifndef IOS
if (!LIBREOFFICEKIT_HAS(kit, runLoop))
{
LOG_FTL("Kit is missing Unipoll API");
std::cout << "Fatal: out of date LibreOfficeKit - no Unipoll API\n";
std::_Exit(EX_SOFTWARE);
}
LOG_INF("Kit unipoll loop run");
loKit->runLoop(pollCallback, wakeCallback, mainKit.get());
LOG_INF("Kit unipoll loop run terminated.");
#if MOBILEAPP
SocketPoll::wakeupWorld();
#else
// Trap the signal handler, if invoked,
// to prevent exiting.
LOG_INF("Kit process for Jail [" << jailId << "] finished.");
Log::shutdown();
// Let forkit handle the jail cleanup.
#endif
#else // IOS
std::unique_lock<std::mutex> lock(mainKit->terminationMutex);
mainKit->terminationCV.wait(lock,[&]{ return mainKit->terminationFlag; } );
#endif // !IOS
}
catch (const Exception& exc)
{
LOG_ERR("Poco Exception: " << exc.displayText() <<
(exc.nested() ? " (" + exc.nested()->displayText() + ')' : ""));
}
catch (const std::exception& exc)
{
LOG_ERR("Exception: " << exc.what());
}
#if !MOBILEAPP
LOG_INF("Kit process for Jail [" << jailId << "] finished.");
flushTraceEventRecordings();
Log::shutdown();
// Wait for the signal handler, if invoked, to prevent exiting until done.
SigUtil::waitSigHandlerTrap();
std::_Exit(EX_OK);
#endif
}
#ifdef IOS
// In the iOS app we can have several documents open in the app process at the same time, thus
// several lokit_main() functions running at the same time. We want just one LO main loop, though,
// so we start it separately in its own thread.
void runKitLoopInAThread()
{
std::thread([&]
{
Util::setThreadName("lokit_runloop");
std::shared_ptr<lok::Office> loKit = std::make_shared<lok::Office>(lo_kit);
int dummy;
loKit->runLoop(pollCallback, wakeCallback, &dummy);
// Should never return
assert(false);
NSLog(@"loKit->runLoop() unexpectedly returned");
std::abort();
}).detach();
}
#endif // IOS
#endif // !BUILDING_TESTS
std::string anonymizeUrl(const std::string& url)
{
#ifndef BUILDING_TESTS
return AnonymizeUserData ? Util::anonymizeUrl(url, AnonymizationSalt) : url;
#else
return url;
#endif
}
#if !MOBILEAPP
/// Initializes LibreOfficeKit for cross-fork re-use.
bool globalPreinit(const std::string &loTemplate)
{
#ifdef FUZZER
if (COOLWSD::DummyLOK)
return true;
#endif
const std::string libSofficeapp = loTemplate + "/program/" LIB_SOFFICEAPP;
const std::string libMerged = loTemplate + "/program/" LIB_MERGED;
std::string loadedLibrary;
void *handle;
if (File(libMerged).exists())
{
LOG_TRC("dlopen(" << libMerged << ", RTLD_GLOBAL|RTLD_NOW)");
handle = dlopen(libMerged.c_str(), RTLD_GLOBAL|RTLD_NOW);
if (!handle)
{
LOG_FTL("Failed to load " << libMerged << ": " << dlerror());
return false;
}
loadedLibrary = libMerged;
}
else
{
if (File(libSofficeapp).exists())
{
LOG_TRC("dlopen(" << libSofficeapp << ", RTLD_GLOBAL|RTLD_NOW)");
handle = dlopen(libSofficeapp.c_str(), RTLD_GLOBAL|RTLD_NOW);
if (!handle)
{
LOG_FTL("Failed to load " << libSofficeapp << ": " << dlerror());
return false;
}
loadedLibrary = libSofficeapp;
}
else
{
LOG_FTL("Neither " << libSofficeapp << " or " << libMerged << " exist.");
return false;
}
}
LokHookPreInit* preInit = reinterpret_cast<LokHookPreInit *>(dlsym(handle, "lok_preinit"));
if (!preInit)
{
LOG_FTL("No lok_preinit symbol in " << loadedLibrary << ": " << dlerror());
return false;
}
initFunction = reinterpret_cast<LokHookFunction2 *>(dlsym(handle, "libreofficekit_hook_2"));
if (!initFunction)
{
LOG_FTL("No libreofficekit_hook_2 symbol in " << loadedLibrary << ": " << dlerror());
}
// Disable problematic components that may be present from a
// desktop or developer's install if env. var not set.
::setenv("UNODISABLELIBRARY",
"abp avmediagst avmediavlc cmdmail losessioninstall OGLTrans PresenterScreen "
"syssh ucpftp1 ucpgio1 ucphier1 ucpimage updatecheckui updatefeed updchk"
// Database
"dbaxml dbmm dbp dbu deployment firebird_sdbc mork "
"mysql mysqlc odbc postgresql-sdbc postgresql-sdbc-impl sdbc2 sdbt"
// Java
"javaloader javavm jdbc rpt rptui rptxml ",
0 /* no overwrite */);
LOG_TRC("Invoking lok_preinit(" << loTemplate << "/program\", \"file:///tmp/user\")");
const auto start = std::chrono::steady_clock::now();
if (preInit((loTemplate + "/program").c_str(), "file:///tmp/user") != 0)
{
LOG_FTL("lok_preinit() in " << loadedLibrary << " failed");
return false;
}
LOG_TRC("Finished lok_preinit(" << loTemplate << "/program\", \"file:///tmp/user\") in "
<< std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start));
return true;
}
/// Anonymize usernames.
std::string anonymizeUsername(const std::string& username)
{
#ifndef BUILDING_TESTS
return AnonymizeUserData ? Util::anonymize(username, AnonymizationSalt) : username;
#else
return username;
#endif
}
#endif // !MOBILEAPP
void dump_kit_state()
{
std::ostringstream oss;
KitSocketPoll::dumpGlobalState(oss);
const std::string msg = oss.str();
fprintf(stderr, "%s", msg.c_str());
LOG_TRC(msg);
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
| 105,333 | 30,198 |
#include "defs.h"
#include <optional>
#include <utility>
#include <vector>
/**
* Solves the quadratic formula of where a ray intersects the surface of a
* sphere.
*
* Derivation comes from:
*
* ```
* radius^2 = |P - center| * |P - center| => <P-center, P-center>
* P = origin + dir*t
* ```
*
* Plugging p into radius eq and solving for t
* gives a value t that equals points on surface of the sphere.
*/
std::pair<double, double> intersect_ray_sphere(const Point &origin,
const Point &dir,
const Sphere &sphere) {
auto oc = origin - sphere.center;
auto k1 = dir * dir;
auto k2 = 2.0 * (oc * dir);
auto k3 = oc * oc - sphere.radius * sphere.radius;
auto discriminant = k2 * k2 - 4.0 * k1 * k3;
if (discriminant < 0.0) {
return std::make_pair(DBL_MAX, DBL_MAX);
} else {
auto t1 = (-k2 + std::sqrt(discriminant)) / (2.0 * k1);
auto t2 = (-k2 - std::sqrt(discriminant)) / (2.0 * k1);
return std::make_pair(t1, t2);
}
}
/**
* Computation of the light vectors is done by computing
* normal vectors of the surface of the sphere and then
* taking the dot product
* with the direction from the light source.
* Depending on light source type, adjust vector as appropriate.
*/
double compute_lighting(const Point &P, const Point &N, const Scene &scene) {
auto i = 0.0;
for (auto &l : scene.lights) {
if (l.type == AMBIENT) {
i += l.intensity;
} else {
Point L;
if (l.type == POINT) {
L = l.vector - P;
} else if (l.type == DIRECTIONAL) {
L = l.vector;
}
double dot = N * L;
if (dot > 0) {
i += (l.intensity * dot) / (N.length() * L.length());
}
}
}
return i;
}
/**
* Simulate a single ray from point extending outwards in dir.
* Returns the color for the specific square.
* This is the algorithm that outputs the colors
* necessary to create the image.
*/
Color trace_ray(const Scene &scene, const Point &dir, double t_min,
double t_max) {
auto t = DBL_MAX;
std::optional<Sphere> m;
for (auto &s : scene.spheres) {
auto t_s = intersect_ray_sphere(scene.camera, dir, s);
auto fst = t_s.first;
auto snd = t_s.second;
if (fst < t && t_min < fst && fst < t_max) {
t = fst;
m = s;
}
if (snd < t && t_min < snd && snd < t_max) {
t = snd;
m = s;
}
}
if (m) {
auto P = scene.camera + (dir * t);
auto N = P - m.value().center;
N = N / N.length();
return m.value().color * compute_lighting(P, N, scene);
}
return WHITE;
}
| 2,742 | 964 |
#include "main.h"
int main() {
const char* base_map =
".............."
". ... ."
". .... * ."
". . ."
". O . v.. ."
". R<<. ."
". .... .. ."
". ... . ."
". . O ."
". . .. ."
". . .. ."
". .. .. ."
". .... ."
"~~~~~~~~~~~~~~";
using St = State<Setup<14, 14, 2, 1, 6>>;
St::Map map(base_map);
St st(map);
st.print(map);
EXPECT_EQ(33, search(st, map));
return 0;
}
| 572 | 224 |
//===-- ProcessInfoTest.cpp -------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "lldb/Utility/ProcessInfo.h"
#include "gtest/gtest.h"
using namespace lldb_private;
TEST(ProcessInfoTest, Constructor) {
ProcessInfo Info("foo", ArchSpec("x86_64-pc-linux"), 47);
EXPECT_STREQ("foo", Info.GetName());
EXPECT_EQ(ArchSpec("x86_64-pc-linux"), Info.GetArchitecture());
EXPECT_EQ(47u, Info.GetProcessID());
}
| 708 | 243 |
/*
Copyright (c) "2018-2019", Shenzhen Mindeng Technology Co., Ltd(www.niiengine.com),
Mindeng Base Communication Application Framework
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list
of conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution.
Neither the name of the "ORGANIZATION" nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "MdfFileManager.h"
#include "MdfServerConnect.h"
#include "MdfRouteClientConnect.h"
#include "MdfDatabaseClientConnect.h"
#include "MdfFileClientConnect.h"
#include "MdfUserManager.h"
#include "MBCAF.HubServer.pb.h"
#include "MBCAF.ServerBase.pb.h"
#include "MBCAF.MsgServer.pb.h"
using namespace MBCAF::Proto;
namespace Mdf
{
//-----------------------------------------------------------------------
M_SingletonImpl(FileManager);
//-----------------------------------------------------------------------
void FileManager::FileQ(ServerConnect * conn, MdfMessage * msg)
{
MBCAF::HubServer::FileQ proto;
if(!msg->toProto(&proto))
return;
Mui32 fromid = conn->getUserID();
Mui32 toid = proto.to_user_id();
String fname = proto.file_name();
Mui32 fsize = proto.file_size();
Mui32 tmode = proto.trans_mode();
Mlog("FileQ, %u->%u, fileName: %s, trans_mode: %u.", fromid, toid, fname.c_str(), tmode);
FileClientConnect * fileconn = FileClientConnect::getRandomConnect();
if (fileconn)
{
HandleExtData attach(conn->getID());
MBCAF::HubServer::FileTransferQ proto2;
proto2.set_from_user_id(fromid);
proto2.set_to_user_id(toid);
proto2.set_file_name(fname);
proto2.set_file_size(fsize);
proto2.set_trans_mode((MBCAF::Proto::TransferFileType)tmode);
proto2.set_attach_data(attach.getBuffer(), attach.getSize());
MdfMessage remsg;
remsg.setProto(&proto2);
remsg.setCommandID(SBMSG(FileTransferQ));
remsg.setSeqIdx(msg->getSeqIdx());
if (MBCAF::Proto::TFT_Offline == tmode)
{
fileconn->send(&remsg);
}
else
{
User * tempusr = M_Only(UserManager)->getUser(toid);
if (tempusr && tempusr->getPCState())
{
fileconn->send(&remsg);
}
else
{
RouteClientConnect * routeconn = RouteClientConnect::getPrimaryConnect();
if (routeconn)
{
MessageExtData extdata(MEDT_ProtoToFile, conn->getID(), remsg.getContentSize(), remsg.getContent());
MBCAF::MsgServer::BuddyObjectStateQ proto3;
proto3.set_user_id(fromid);
proto3.add_user_id_list(toid);
proto3.set_attach_data(extdata.getBuffer(), extdata.getSize());
MdfMessage remsg2;
remsg2.setProto(&proto3);
remsg2.setCommandID(MSMSG(BuddyObjectStateQ));
remsg2.setSeqIdx(msg->getSeqIdx());
routeconn->send(&remsg2);
}
}
}
}
else
{
Mlog("FileQ, no file server. ");
MBCAF::HubServer::FileA proto2;
proto2.set_result_code(1);
proto2.set_from_user_id(fromid);
proto2.set_to_user_id(toid);
proto2.set_file_name(fname);
proto2.set_task_id("");
proto2.set_trans_mode((MBCAF::Proto::TransferFileType)tmode);
MdfMessage remsg;
remsg.setProto(&proto2);
remsg.setCommandID(HSMSG(FileA));
remsg.setSeqIdx(msg->getSeqIdx());
conn->send(&remsg);
}
}
//-----------------------------------------------------------------------
void FileManager::OfflineFileQ(ServerConnect * conn, MdfMessage * msg)
{
Mui32 userid = conn->getUserID();
Mlog("OfflineFileQ, req_id=%u ", userid);
HandleExtData extdata(conn->getID());
DataBaseClientConnect * dbconn = DataBaseClientConnect::getPrimaryConnect();
if (dbconn)
{
MBCAF::HubServer::FileExistOfflineQ proto;
if(!msg->toProto(&proto))
return;
proto.set_user_id(userid);
proto.set_attach_data(extdata.getBuffer(), extdata.getSize());
msg->setProto(&proto);
dbconn->send(msg);
}
else
{
Mlog("warning no DB connection available ");
MBCAF::HubServer::FileExistOfflineA proto;
proto.set_user_id(userid);
MdfMessage remsg;
remsg.setProto(&proto);
remsg.setCommandID(HSMSG(OfflineFileA));
remsg.setSeqIdx(msg->getSeqIdx());
conn->send(&remsg);
}
}
//-----------------------------------------------------------------------
void FileManager::AddOfflineFileQ(ServerConnect * conn, MdfMessage * msg)
{
MBCAF::HubServer::FileAddOfflineQ proto;
if(!msg->toProto(&proto))
return;
Mui32 fromid = conn->getUserID();
Mui32 toid = proto.to_user_id();
String taskid = proto.task_id();
String fname = proto.file_name();
Mui32 fsize = proto.file_size();
Mlog("AddOfflineFileQ, %u->%u, task_id: %s, file_name: %s, size: %u ",
fromid, toid, taskid.c_str(), fname.c_str(), fsize);
DataBaseClientConnect * dbconn = DataBaseClientConnect::getPrimaryConnect();
if (dbconn)
{
proto.set_from_user_id(fromid);
msg->setProto(&proto);
dbconn->send(msg);
}
FileClientConnect * fileconn = FileClientConnect::getRandomConnect();
if (fileconn)
{
const list<MBCAF::Proto::IPAddress> & addrlist = fileconn->GetFileServerIPList();
MBCAF::HubServer::FileNotify proto2;
proto2.set_from_user_id(fromid);
proto2.set_to_user_id(toid);
proto2.set_file_name(fname);
proto2.set_file_size(fsize);
proto2.set_task_id(taskid);
proto2.set_trans_mode(MBCAF::Proto::TFT_Offline);
proto2.set_offline_ready(1);
list<MBCAF::Proto::IPAddress>::const_iterator it, itend = addrlist.end();
for (it = addrlist.begin(); it != itend; ++it)
{
MBCAF::Proto::IPAddress * ip_addr = proto2.add_ip_addr_list();
ip_addr->set_ip((*it).ip());
ip_addr->set_port((*it).port());
}
MdfMessage remsg;
remsg.setProto(&proto2);
remsg.setCommandID(HSMSG(FileNotify));
User * tempusr = M_Only(UserManager)->getUser(toid);
if (tempusr)
{
tempusr->broadcastToPC(&remsg);
}
RouteClientConnect * conn = RouteClientConnect::getPrimaryConnect();
if (conn)
{
conn->send(&remsg);
}
}
}
//-----------------------------------------------------------------------
void FileManager::DeleteOfflineFileQ(ServerConnect * conn, MdfMessage * msg)
{
MBCAF::HubServer::FileDeleteOfflineQ proto;
if(!msg->toProto(&proto))
return;
Mui32 fromid = proto.from_user_id();
Mui32 toid = proto.to_user_id();
String taskid = proto.task_id();
Mlog("DeleteOfflineFileQ, %u->%u, task_id=%s ", fromid, toid, taskid.c_str());
DataBaseClientConnect * dbconn = DataBaseClientConnect::getPrimaryConnect();
if (dbconn)
{
proto.set_from_user_id(fromid);
msg->setProto(&proto);
dbconn->send(msg);
}
}
//-----------------------------------------------------------------------
void FileManager::prcOfflineFileA(MdfMessage * msg)
{
MBCAF::HubServer::FileExistOfflineA proto;
if(!msg->toProto(&proto))
return;
Mui32 userid = proto.user_id();
Mui32 filecnt = proto.offline_file_list_size();
HandleExtData attach((Mui8*)proto.attach_data().c_str(), proto.attach_data().length());
Mlog("prcOfflineFileA, req_id=%u, file_cnt=%u ", userid, filecnt);
ServerConnect * conn = M_Only(UserManager)->getMsgConnect(userid, attach.getHandle());
if (conn)
{
FileClientConnect * fileconn = FileClientConnect::getRandomConnect();
if (fileconn)
{
const list<MBCAF::Proto::IPAddress> & iplist = fileconn->GetFileServerIPList();
for(list<MBCAF::Proto::IPAddress>::const_iterator it = iplist.begin(); it != iplist.end(); ++it)
{
MBCAF::Proto::IPAddress * ip_addr = proto.add_ip_addr_list();
ip_addr->set_ip((*it).ip());
ip_addr->set_port((*it).port());
}
}
else
{
Mlog("prcOfflineFileA, no file server. ");
}
msg->setProto(&proto);
conn->send(msg);
}
}
//-----------------------------------------------------------------------
void FileManager::prcFileNotify(MdfMessage * msg)
{
MBCAF::HubServer::FileNotify proto;
if(!msg->toProto(&proto))
return;
Mui32 fromid = proto.from_user_id();
Mui32 userid = proto.to_user_id();
String fname = proto.file_name();
String taskid = proto.task_id();
Mui32 tmode = proto.trans_mode();
Mui32 ready = proto.offline_ready();
Mlog("prcFileNotify, from_id: %u, to_id: %u, file_name: %s, task_id: %s, trans_mode: %u,\
offline_ready: %u. ", fromid, userid, fname.c_str(), taskid.c_str(), tmode, ready);
User * tempusr = M_Only(UserManager)->getUser(userid);
if(tempusr)
{
tempusr->broadcast(msg);
}
}
//-----------------------------------------------------------------------
} | 11,677 | 3,548 |
#include <iostream>
#include <vector>
#include <random>
#include <string>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "phong_shader.hpp"
#include "Shaders/shaders.hpp"
PhongShader::PhongShader()
{
std::string vSSrc = Shaders::getVertexShader();
std::string fSSrc = Shaders::getFragmentShader();
prog = std::make_shared<OGLProgram>();
prog->compileAndAttachShader(vSSrc.c_str(), GL_VERTEX_SHADER);
prog->compileAndAttachShader(fSSrc.c_str(), GL_FRAGMENT_SHADER);
prog->link();
attributeBindingPoints["aPos"] = 0;
attributeBindingPoints["aNormal"] = 1;
binding_point_pos_att = 0;
binding_point_normal_att = 1;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
// position
auto pos_loc = prog->getAttributeLocation("aPos");
glVertexAttribFormat(pos_loc, 3, GL_FLOAT, GL_FALSE, 0);
glVertexAttribBinding(pos_loc, attributeBindingPoints["aPos"]);
glEnableVertexAttribArray(pos_loc);
// normals
auto normal_loc = prog->getAttributeLocation("aNormal");
glVertexAttribFormat(normal_loc, 3, GL_FLOAT, GL_FALSE, 0);
glVertexAttribBinding(normal_loc, attributeBindingPoints["aNormal"]);
glEnableVertexAttribArray(normal_loc);
glBindVertexArray(0);
}
PhongShader::~PhongShader()
{
}
void PhongShader::use()
{
prog->use();
}
void PhongShader::draw(Mesh* mesh)
{
glBindVertexArray(vao);
//glBindVertexBuffer(attributeBindingPoints["aPos"], mesh->getPositionsPointer(), 0, 0);
//glBindVertexBuffer(attributeBindingPoints["aNormal"], mesh->getNormalsPointer(), 0, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->getIndecesPointer());
glDrawElements(GL_TRIANGLES, mesh->getFaceIndeces().size(), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
}
void PhongShader::setAttributeBindingPoint(const char* attr_name, GLuint binding_point)
{
glBindVertexArray(vao);
prog->setAttributeBindingPoint(attr_name, binding_point);
glBindVertexArray(0);
}
void PhongShader::setUniformBlockBindingPoint(const char* unif_name, GLuint binding_point)
{
prog->setUniformBlockBindingPoint(unif_name, binding_point);
}
void PhongShader::setUniformMatrix4(const char* unif_name, const glm::mat4& mat)
{
prog->setUniformMatrix4(unif_name, mat);
}
void PhongShader::setUniformVector3(const char* unif_name, const glm::vec3& vec)
{
prog->setUniformVector3(unif_name, vec);
}
| 2,303 | 872 |
#include "utils.h"
static FILE* out;
static jrawMonitorID vmtrace_lock;
static jlong start_time;
void check_jvmti_error(jvmtiEnv *jvmti, jvmtiError errnum, const char *str) {
if (errnum != JVMTI_ERROR_NONE) {
char *errnum_str;
errnum_str = NULL;
(void) jvmti->GetErrorName(errnum, &errnum_str);
printf("ERROR: JVMTI: %d(%s): %s\n", errnum,
(errnum_str == NULL ? "Unknown" : errnum_str),
(str == NULL ? "" : str));
}
}
namespace utils {
uint64_t hash_object(JNIEnv *env, jobject object) {
jclass cls = env->FindClass("java/lang/System");
if (!cls) {
printf("Find class `System` failure\n");
return 0;
}
jmethodID method = env->GetStaticMethodID(cls, "identityHashCode", "(Ljava/lang/Object;)I");
if (!method) {
printf("Get method `identityHashCode` failure\n");
}
jint hash = env->CallStaticIntMethod(cls, method, object);
return hash;
}
void trace(jvmtiEnv* jvmti, const char* fmt, ...) {
jlong current_time;
jvmti->GetTime(¤t_time);
char buf[1024];
va_list args;
va_start(args, fmt);
vsnprintf(buf, sizeof(buf), fmt, args);
va_end(args);
jvmti->RawMonitorEnter(vmtrace_lock);
fprintf(out, "[%.5f] %s\n", (current_time - start_time) / 1000000000.0, buf);
jvmti->RawMonitorExit(vmtrace_lock);
}
void init(jvmtiEnv *jvmti, char* options) {
if (options == NULL || !options[0]) {
out = stderr;
} else if ((out = fopen(options, "w")) == NULL) {
fprintf(stderr, "Cannot open output file: %s\n", options);
return;
}
jvmtiError err_code = jvmti->CreateRawMonitor("vmtrace_lock", &vmtrace_lock);
CHECK_ERROR("Create raw monitor failure");
jvmti->GetTime(&start_time);
CHECK_ERROR("Get time failure");
}
void fini() {
if (out != NULL && out != stderr) {
fclose(out);
}
}
void acq_big_lock(jvmtiEnv *jvmti) {
jvmtiError err_code = jvmti->RawMonitorEnter(vmtrace_lock);
CHECK_ERROR("Cannot enter with raw monitor");
}
void rel_big_lock(jvmtiEnv *jvmti) {
jvmtiError err_code = jvmti->RawMonitorExit(vmtrace_lock);
CHECK_ERROR("Cannot exit with raw monitor");
}
} // namespace Utils | 2,183 | 842 |
/*
* GridTools
*
* Copyright (c) 2014-2021, ETH Zurich
* All rights reserved.
*
* Please, refer to the LICENSE file in the root directory.
* SPDX-License-Identifier: BSD-3-Clause
*/
#pragma once
#include "../../meta/list.hpp"
namespace gridtools {
namespace stencil {
namespace core {
template <class Plh, class CacheTypes = meta::list<>, class CacheIOPolicies = meta::list<>>
struct cache_info {
using plh_t = Plh;
using cache_types_t = CacheTypes;
using cache_io_policies_t = CacheIOPolicies;
};
} // namespace core
} // namespace stencil
} // namespace gridtools
| 688 | 215 |
#include <iostream>
#include <numeric>
#include <fstream>
#include <climits>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
#include <list>
#include <map>
#include <set>
#include <stack>
#include <deque>
#include <vector>
#include <string>
#include <cstdlib>
#include <cassert>
#include <sstream>
#include <iterator>
#include <algorithm>
#define llu unsigned long long
using namespace std;
int main(){
llu n;
bool divTods;
bool divDiv;
vector<llu> tot;
vector<llu> tat;
while(cin >> n){
tot.clear();
tat.clear();
llu plate[n];
for(llu x=0; x<n; ++x){
cin >> plate[x];
}
sort(plate,plate+n);
for(llu y=1; y<n; ++y){
plate[y]-=plate[0];
}
plate[0]=0;
for(llu x=0; x<n; ++x){
for(llu dv=1; dv*dv<plate[x]; ++dv){
if(plate[x]%dv==0){
divTods=true;
for(llu y=0; y<n && divTods; ++y){
if(plate[y]%dv!=0){
divTods=false;
}
}
if(divTods){
tot.push_back(dv);
}
divDiv=true;
for(llu y=0; y<n && divDiv; ++y){
if(plate[y]%(plate[x]/dv)!=0){
divDiv=false;
}
}
if(divDiv){
tot.push_back(plate[x]/dv);
}
}
}
}
for(llu z=0;z<tot.size();++z){
if(tot[z]!=1){
cout << tot[z];
if(z+1!=tot.size()){
cout << " ";
}
for(llu s=0;s<tot.size();++s){
if(tot[s]!=tot[z]){
tat.push_back(tot[s]);
}
}
tot.clear();
for(llu s=0;s<tat.size();++s){
tot.push_back(tat[s]);
}
tat.clear();
z=0;
}
}
cout << endl;
}
} | 1,532 | 865 |
/**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2012 UniPro <ugene@unipro.ru>
* http://ugene.unipro.ru
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "GenomeAlignerIndex.h"
#include "GenomeAlignerSettingsController.h"
#include "GenomeAlignerTask.h"
#include <U2Core/AppContext.h>
#include <U2Core/AppResources.h>
#include <U2Core/AppSettings.h>
#include <U2Core/GUrl.h>
#include <U2Core/UserApplicationsSettings.h>
#include <U2Algorithm/OpenCLGpuRegistry.h>
#include <U2Gui/LastUsedDirHelper.h>
#include "GenomeAlignerSettingsWidget.h"
#include <QtGui/QFileDialog>
namespace U2 {
static const int MIN_READ_SIZE = 10;
static const int MIN_PART_SIZE = 1;
static const int DEFAULT_PART_SIZE = 10;
GenomeAlignerSettingsWidget::GenomeAlignerSettingsWidget(QWidget* parent) : DnaAssemblyAlgorithmMainWidget(parent) {
setupUi(this);
tabWidget->setCurrentIndex(0);
layout()->setContentsMargins(0,0,0,0);
connect(buildIndexFileButton, SIGNAL(clicked()), SLOT(sl_onSetIndexDirButtonClicked()));
connect(partSlider, SIGNAL(valueChanged(int)), SLOT(sl_onPartSliderChanged(int)));
connect(readSlider, SIGNAL(valueChanged(int)), SLOT(sl_onReadSliderChanged(int)));
buildIndexFileButton->toggle();
#ifdef OPENCL_SUPPORT
if (AppContext::getOpenCLGpuRegistry()->getEnabledGpus().empty()) {
#endif
gpuBox->setEnabled(false);
#ifdef OPENCL_SUPPORT
}
#endif
systemSize = AppContext::getAppSettings()->getAppResourcePool()->getMaxMemorySizeInMB();
systemSize = systemSize < 2000 ? systemSize : 2000; // TODO: UGENE-1181
partSlider->setEnabled(false);
readSlider->setMinimum(MIN_READ_SIZE);
readSlider->setMaximum(systemSize);
readSlider->setValue(systemSize*2/3);
QString indexDirPath = GenomeAlignerSettingsUtils::getIndexDir();
QDir indexDir(indexDirPath);
indexDir.mkpath(indexDirPath);
indexDirEdit->setText(indexDirPath);
partSizeLabel->setText(QByteArray::number(partSlider->value()) + " Mb");
indexSizeLabel->setText(QByteArray::number(partSlider->value()*13) + " Mb");
totalSizeLabel->setText(QByteArray::number(partSlider->value()*13 + readSlider->value()) + " Mb");
systemSizeLabel->setText(QByteArray::number(systemSize) + " Mb");
}
QMap<QString,QVariant> GenomeAlignerSettingsWidget::getDnaAssemblyCustomSettings() {
QMap<QString,QVariant> settings;
settings.insert(GenomeAlignerTask::OPTION_ALIGN_REVERSED, reverseBox->isChecked());
settings.insert(GenomeAlignerTask::OPTION_OPENCL, gpuBox->isChecked());
settings.insert(GenomeAlignerTask::OPTION_BEST, firstMatchBox->isChecked());
settings.insert(GenomeAlignerTask::OPTION_READS_MEMORY_SIZE, readSlider->value());
settings.insert(GenomeAlignerTask::OPTION_SEQ_PART_SIZE, partSlider->value());
settings.insert(GenomeAlignerTask::OPTION_INDEX_DIR, indexDirEdit->text());
if (omitQualitiesBox->isChecked()) {
settings.insert(GenomeAlignerTask::OPTION_QUAL_THRESHOLD, qualThresholdBox->value() );
}
if (groupBox_mismatches->isChecked()) {
settings.insert(GenomeAlignerTask::OPTION_MISMATCHES, mismatchesAllowedSpinBox->value());
settings.insert(GenomeAlignerTask::OPTION_IF_ABS_MISMATCHES, absRadioButton->isChecked());
settings.insert(GenomeAlignerTask::OPTION_PERCENTAGE_MISMATCHES, percentMismatchesAllowedSpinBox->value());
} else {
settings.insert(GenomeAlignerTask::OPTION_MISMATCHES, 0);
settings.insert(GenomeAlignerTask::OPTION_IF_ABS_MISMATCHES, true);
settings.insert(GenomeAlignerTask::OPTION_PERCENTAGE_MISMATCHES, 0);
}
return settings;
}
bool GenomeAlignerSettingsWidget::buildIndexUrl(const GUrl& url, bool prebuiltIndex, QString &error) {
if (prebuiltIndex) {
GenomeAlignerIndex index;
index.baseFileName = url.dirPath() + "/" + url.baseFileName();
QByteArray e;
bool res = index.deserialize(e);
if (!res || url.lastFileSuffix() != GenomeAlignerIndex::HEADER_EXTENSION) {
error = tr("This index file is corrupted. Please, load a valid index file.");
return false;
}
partSlider->setMinimum(MIN_PART_SIZE);
partSlider->setMaximum(index.seqPartSize);
partSlider->setEnabled(true);
partSlider->setValue(index.seqPartSize);
} else {
QString refUrl = url.getURLString();
QFile file(refUrl);
if (file.exists()) {
int fileSize = 1 + (int)(file.size()/(1024*1024));
int maxPartSize = qMin(fileSize*13, systemSize - MIN_READ_SIZE)/13;
partSlider->setMinimum(MIN_PART_SIZE);
partSlider->setMaximum(maxPartSize);
partSlider->setEnabled(true);
partSlider->setValue(qMin(maxPartSize, DEFAULT_PART_SIZE));
}
}
return true;
}
void GenomeAlignerSettingsWidget::prebuiltIndex(bool value) {
indexTab->setEnabled(!value);
}
bool GenomeAlignerSettingsWidget::isParametersOk(QString &error) {
bool gpuOk = (gpuBox->isChecked() == false) || ((gpuBox->isChecked() == true) && (partSlider->value() <= 10)); // 128MB is the minimum size for a buffer, according to CL_DEVICE_MAX_MEM_ALLOC_SIZE OpenCL documentation
if ((systemSize < readSlider->value() + 13*partSlider->value()) || !gpuOk) {
error = "There is no enough memory for the aligning on your computer. Try to reduce a memory size for short reads or for the reference fragment.";
return false;
}
return true;
}
bool GenomeAlignerSettingsWidget::isIndexOk(QString &error, GUrl refName) {
GenomeAlignerIndex index;
if (indexTab->isEnabled()) { //prebuiltIndex is not checked
index.baseFileName = indexDirEdit->text() + "/" + refName.baseFileName();
} else {
index.baseFileName = refName.dirPath() + "/" + refName.baseFileName();
}
QByteArray e;
bool res = index.deserialize(e);
if (indexTab->isEnabled()) { //prebuiltIndex is not checked
if (!res) {
return true;
}
if (index.seqPartSize == partSlider->value()) {
return true;
}
error = tr("The index directory has already contain the prebuilt index. But its reference fragmentation parameter is %1 and it doesn't equal to \
the parameter you have chosen (%2).\n\nPress \"Ok\" to delete this index file and create a new during the aligning.\nPress \"Cancel\" to change this parameter \
or the index directory.").arg(index.seqPartSize).arg(partSlider->value());
return false;
} else {
if (!res || refName.lastFileSuffix() != GenomeAlignerIndex::HEADER_EXTENSION) {
error = tr("This index file is corrupted. Please, load a valid index file.");
return false;
}
return true;
}
}
void GenomeAlignerSettingsWidget::sl_onSetIndexDirButtonClicked() {
LastUsedDirHelper lod;
lod.url = QFileDialog::getExistingDirectory(this, tr("Set index files directory"), indexDirEdit->text());
if (!lod.url.isEmpty()) {
GUrl result = lod.url;
indexDirEdit->setText(result.getURLString());
}
}
void GenomeAlignerSettingsWidget::sl_onPartSliderChanged(int value) {
partSizeLabel->setText(QByteArray::number(value) + " Mb");
indexSizeLabel->setText(QByteArray::number(value*13) + " Mb");
if (systemSize - 13*value >= MIN_READ_SIZE) {
readSlider->setMaximum(systemSize - 13*value);
} else {
readSlider->setMaximum(MIN_READ_SIZE);
}
totalSizeLabel->setText(QByteArray::number(value*13 + readSlider->value()) + " Mb");
}
void GenomeAlignerSettingsWidget::sl_onReadSliderChanged(int value) {
readSizeLabel->setText(QByteArray::number(value) + " Mb");
totalSizeLabel->setText(QByteArray::number(partSlider->value()*13 + value) + " Mb");
}
} //namespace
| 8,527 | 2,770 |
#include <cstdio>
#include <cstring>
#include <string>
//http://wjwwood.io/serial/doc/1.1.0/classserial_1_1_serial.html
#include "telecom/telecom.h"
#define ERR_CHECK \
do { if (com.status() != 0){ \
fprintf(stdout, "Error: %s\n", com.verboseStatus().c_str()); \
return com.status(); \
} } while(0)
int main(int argc, char *argv[]){
if (argc != 4){
fprintf(stderr, "usage: ./programname dst-hostname dst-udpport src-udpport\n");
exit(1);
}
Telecom com(argv[1], atoi(argv[2]), atoi(argv[3]));
com.setFailureAction(false);
com.setBlockingTime(0,0);
ERR_CHECK;
time_t timer;
time(&timer);
// Joystick js(); // #include "joystick.hh"
// Exit if !js.isFound()
// com.fdAdd(js.fd());
while(1){
com.update();
ERR_CHECK;
// JoystickEvent event;
// Receive from remote
if(com.recvAvail()){
std::string msg = com.recv();
//ERR_CHECK; // This makes it crash???
if(!msg.empty())
printf("Received message: %s\n", msg.c_str());
if(!msg.compare("EOM\n")){ break; } // delete if not want remote close
}
// Reboot if comunication channel closed
while(com.isComClosed()){
printf("Rebooting connection\n");
com.reboot();
}
// Get user stdio input to send
if(com.stdioReadAvail()){
std::string msg = com.stdioRead();
ERR_CHECK;
if(!msg.compare("EOM\n")){ // Assume desired for connection to close
com.send(msg); // Delete for debug connection testing
printf("Received EOM closing\n");
break;
}
com.send(msg);
ERR_CHECK;
}
// Example if including joystick
// if(com.fdReadAvail(js.fd()) && js.sample(&event)){
// ... process buttons and axis of event ... }
// heartbeat
if(difftime(time(NULL), timer) > 10){
timer = time(NULL);
printf(".\n");
}
}
}
| 1,891 | 692 |
//
// main.cpp
//
// Exercises the calendar class.
//
// --------------------------------------------------------------------------
// Attribution: "Programming Abstractions in C++" by Eric Roberts
// Chapter 6, Exercise 5
// Stanford University, Autumn Quarter 2012
// http://web.stanford.edu/class/archive/cs/cs106b/cs106b.1136/materials/CS106BX-Reader.pdf
// --------------------------------------------------------------------------
//
// Created by Glenn Streiff on 12/16/15.
// Copyright © 2015 Glenn Streiff. All rights reserved.
//
#include <iostream>
#include "calendar.h"
const std::string HEADER = "CS106B Programming Abstractions in C++: Ex 6.5\n";
const std::string DETAIL = "Extend the Ex 2.11 calendar.h interface.";
const std::string BANNER = HEADER + DETAIL;
int main(int argc, char * argv[]) {
std::cout << BANNER << std::endl << std::endl;
Date moonLanding(JULY, 20, 1969);
std::cout << moonLanding.toString() << std::endl;
return 0;
}
| 989 | 352 |
#include "../../include/solution.h"
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
int len = 0;
auto tail = head;
while (tail) {
len++;
tail = tail->next;
}
int id = 0;
ListNode* fake_head = new ListNode(0);
fake_head->next = head;
tail = fake_head;
while (tail) {
if (id == len - n) {
if (tail->next) tail->next = tail->next->next;
break;
}
tail = tail->next;
id++;
}
return fake_head->next;
}
ListNode* removeNthFromEndv2(ListNode* head, int n) {
ListNode* dummy = new ListNode();
dummy->next = head;
ListNode* slow = dummy;
ListNode* fast = dummy;
int gap = n + 1;
while (gap--) {
fast = fast->next;
}
while (fast) {
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next;
return dummy->next;
}
};
int main() {
string line;
while (getline(cin, line)) {
ListNode* head = stringToListNode(line);
prettyPrintLinkedList(head);
head = Solution().removeNthFromEndv2(head, 2);
prettyPrintLinkedList(head);
}
return 0;
} | 1,346 | 415 |
#include "AnimationChannel.hpp"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/matrix_interpolation.hpp>
#include <Utils/Serialization/SerializationArchives.hpp>
namespace AGE{
void AnimationChannel::findKeyIndex(float t, glm::uvec3 &keys, glm::uvec3 &nextKeys)
{
if (scale.size() <= 1)
{
keys.x = 0;
nextKeys.x = 0;
}
else
{
for (unsigned int i = 0; i < scale.size() - 1; i++)
{
if (t < scale[i + 1].time) {
keys.x = i;
nextKeys.x = i + 1;
break;
}
}
}
if (rotation.size() <= 1)
{
keys.y = 0;
nextKeys.y = 0;
}
else
{
for (unsigned int i = 0; i < rotation.size() - 1; i++)
{
if (t < rotation[i + 1].time) {
keys.y = i;
nextKeys.y = i + 1;
break;
}
}
}
if (translation.size() <= 1)
{
keys.z = 0;
nextKeys.z = 0;
}
else
{
for (unsigned int i = 0; i < translation.size() - 1; i++)
{
if (t < translation[i + 1].time) {
keys.z = i;
nextKeys.z = i + 1;
break;
}
}
}
}
void AnimationChannel::getInterpolatedTransform(float t, glm::mat4 &res)
{
glm::uvec3 key = glm::uvec3(static_cast<unsigned int>(t));
glm::uvec3 nextKey = glm::uvec3(key.x + 1);
findKeyIndex(t, key, nextKey);
res = glm::translate(glm::mat4(1), glm::mix(translation[key.z].value, translation[nextKey.z].value, (t - translation[key.z].time) / translation[key.z].deltaTime));
res = glm::scale(res, glm::mix(scale[key.x].value, scale[nextKey.x].value, (t - scale[key.x].time) / scale[key.x].deltaTime));
res *= glm::mat4_cast(glm::normalize(glm::slerp(rotation[key.y].value, rotation[nextKey.y].value, (t - rotation[key.y].time) / rotation[key.y].deltaTime)));
}
}
SERIALIZATION_SERIALIZE_METHOD_DEFINITION(AGE::AnimationChannel, *"*/ ar(cereal::make_nvp(MACRO_STR(bone), boneIndex)); ar(cereal::make_nvp(MACRO_STR(scale), scale)); ar(cereal::make_nvp(MACRO_STR(rotation), rotation)); ar(cereal::make_nvp(MACRO_STR(translation), translation)); /*"*);
| 2,100 | 1,023 |
// --------------------------------------------------------------------
/*
tcbn_create.cpp
Dec/27/2011
*/
// --------------------------------------------------------------------
#include <iostream>
#include <cstring>
#include <map>
#include <tcbdb.h>
using namespace std;
// --------------------------------------------------------------------
typedef map<string,string> Unit;
// --------------------------------------------------------------------
extern map <string,Unit> dict_append_proc
(map <string,Unit> dict_aa,string id,string name,
int population,string date_mod);
// --------------------------------------------------------------------
extern void tcbn_display_proc (TCBDB *bdb);
extern void dict_to_tcbn_proc (map <string,Unit> dict_aa,TCBDB *bdb);
// --------------------------------------------------------------------
static map <string,Unit > data_prepare_proc ()
{
map <string,Unit> dict_aa;
dict_aa = dict_append_proc (dict_aa,"t0831","水戸",52673,"1922-11-7");
dict_aa = dict_append_proc (dict_aa,"t0832","古河",98231,"1922-12-12");
dict_aa = dict_append_proc (dict_aa,"t0833","結城",23429,"1922-3-28");
dict_aa = dict_append_proc (dict_aa,"t0834","土浦",51486,"1922-9-21");
dict_aa = dict_append_proc (dict_aa,"t0835","牛久",83971,"1922-1-5");
dict_aa = dict_append_proc (dict_aa,"t0836","取手",74948,"1922-5-22");
dict_aa = dict_append_proc (dict_aa,"t0837","つくば",46785,"1922-7-17");
dict_aa = dict_append_proc (dict_aa,"t0838","日立",59614,"1922-3-04");
dict_aa = dict_append_proc (dict_aa,"t0839","守谷",71823,"1922-5-9");
return dict_aa;
}
// --------------------------------------------------------------------
int main(int argc, char *argv[])
{
char file_in[160];
char id_in[10];
int population_in;
TCBDB *bdb;
int ecode;
cerr << "*** 開始 ***\n";
strcpy (file_in,argv[1]);
cerr << file_in << '\n';
map <string,Unit> dict_aa = data_prepare_proc ();
bdb = tcbdbnew();
if(!tcbdbopen(bdb, file_in, BDBOWRITER | BDBOCREAT))
{
ecode = tcbdbecode(bdb);
fprintf(stderr, "open error: %s\n", tcbdberrmsg(ecode));
}
dict_to_tcbn_proc (dict_aa,bdb);
tcbn_display_proc (bdb);
if(!tcbdbclose(bdb))
{
ecode = tcbdbecode(bdb);
fprintf(stderr, "close error: %s\n", tcbdberrmsg(ecode));
}
tcbdbdel(bdb);
cerr << "*** 終了 ***\n";
return 0;
}
// --------------------------------------------------------------------
| 2,380 | 1,009 |
#pragma once
#include <memory>
#include <functional>
#include <cstdlib>
#include "IDiscIO.hpp"
#include "Util.hpp"
namespace nod {
class IFileIO {
public:
virtual ~IFileIO() = default;
virtual bool exists() = 0;
virtual uint64_t size() = 0;
struct IWriteStream : nod::IWriteStream {
uint64_t copyFromDisc(IPartReadStream& discio, uint64_t length) {
uint64_t read = 0;
uint8_t buf[0x7c00];
while (length) {
uint64_t thisSz = nod::min(uint64_t(0x7c00), length);
uint64_t readSz = discio.read(buf, thisSz);
if (thisSz != readSz) {
LogModule.report(logvisor::Error, "unable to read enough from disc");
return read;
}
if (write(buf, readSz) != readSz) {
LogModule.report(logvisor::Error, "unable to write in file");
return read;
}
length -= thisSz;
read += thisSz;
}
return read;
}
uint64_t copyFromDisc(IPartReadStream& discio, uint64_t length, const std::function<void(float)>& prog) {
uint64_t read = 0;
uint8_t buf[0x7c00];
uint64_t total = length;
while (length) {
uint64_t thisSz = nod::min(uint64_t(0x7c00), length);
uint64_t readSz = discio.read(buf, thisSz);
if (thisSz != readSz) {
LogModule.report(logvisor::Error, "unable to read enough from disc");
return read;
}
if (write(buf, readSz) != readSz) {
LogModule.report(logvisor::Error, "unable to write in file");
return read;
}
length -= thisSz;
read += thisSz;
prog(read / float(total));
}
return read;
}
};
virtual std::unique_ptr<IWriteStream> beginWriteStream() const = 0;
virtual std::unique_ptr<IWriteStream> beginWriteStream(uint64_t offset) const = 0;
struct IReadStream : nod::IReadStream {
virtual uint64_t copyToDisc(struct IPartWriteStream& discio, uint64_t length) = 0;
};
virtual std::unique_ptr<IReadStream> beginReadStream() const = 0;
virtual std::unique_ptr<IReadStream> beginReadStream(uint64_t offset) const = 0;
};
std::unique_ptr<IFileIO> NewFileIO(SystemStringView path, int64_t maxWriteSize = -1);
} // namespace nod
| 2,229 | 798 |
//
// Created by Alex Beccaro on 03/12/18.
//
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#include "../../src/problems/101-150/106/problem106.hpp"
BOOST_AUTO_TEST_SUITE( Problem106 )
BOOST_AUTO_TEST_CASE( Example1 ) {
auto res = problems::problem106::solve(4);
BOOST_CHECK_EQUAL(res, 1);
}
BOOST_AUTO_TEST_CASE( Example2 ) {
auto res = problems::problem106::solve(7);
BOOST_CHECK_EQUAL(res, 70);
}
BOOST_AUTO_TEST_CASE( Solution ) {
auto res = problems::problem106::solve();
BOOST_CHECK_EQUAL(res, 21384);
}
BOOST_AUTO_TEST_SUITE_END() | 633 | 279 |
#include <algorithm>
#include <ctime>
#include <fstream>
#include <iostream>
#include <sstream>
#include <openssl/hmac.h>
#include <tw/authenticator.h>
#include <tw/base64.h>
#include <tw/oauth.h>
#include <utils.h>
static const char *INSTRUCTIONS = "In order to allow LynxBot to use your "
"Twitter account, you must register it as a Twitter app. This is done by "
"signing into https://apps.twitter.com and clicking the \"Create New App\" "
"button. Give your app a unique name (e.g. lynxbot-TWITTERNAME), fill in the "
"rest of the form and agree to the Developer Agreement.\n\nOnce you submit the "
"form you will be redirected to your app's overview page. You can change the "
"access level to read only (LynxBot does not do any writing).\nNext, click the "
"Keys and Access Tokens tab. Under \"Your Access Token\", click Create my "
"access token to generate access tokens for LynxBot.\n\nYou will now see four "
"tokens on the page:\nConsumer Key\nConsumer Secret\nAccess Token\nAccess "
"Token Secret\nYou will need to enter them into this console.\n\nWARNING: "
"Your access tokens will be stored in plaintext.\n";
static void get_str(std::string &target);
tw::Authenticator::Authenticator()
{
configpath = utils::configdir() + utils::config("twitter");
if (read_keys() == -1)
interactive_setup();
}
/* siggen: generate an oauth signature for a twitter api request */
void tw::Authenticator::siggen(const std::string &method, const std::string &URL,
const param_vec &head_params, const param_vec &body_params)
{
size_t i;
std::vector<std::string> enc_params;
std::string base_str, signing_key;
unsigned char digest[1024];
unsigned int digest_len;
/* get ouath data */
odata.c_key = consumerkey;
odata.nonce = noncegen();
odata.sig_method = "HMAC-SHA1";
odata.timestamp = std::to_string(time(nullptr));
odata.token = token;
odata.version = "1.0";
/* generate the base string */
for (auto p : head_params)
enc_params.push_back(pencode(p.first) + "=" + pencode(p.second));
for (auto p : body_params)
enc_params.push_back(pencode(p.first) + "=" + pencode(p.second));
enc_params.push_back("oauth_consumer_key=" + odata.c_key);
enc_params.push_back("oauth_nonce=" + odata.nonce);
enc_params.push_back("oauth_signature_method=" + odata.sig_method);
enc_params.push_back("oauth_timestamp=" + odata.timestamp);
enc_params.push_back("oauth_token=" + odata.token);
enc_params.push_back("oauth_version=" + odata.version);
std::sort(enc_params.begin(), enc_params.end());
std::string param_str;
for (i = 0; i < enc_params.size(); ++i) {
param_str += enc_params[i];
if (i != enc_params.size() - 1)
param_str += '&';
}
base_str += method + "&";
base_str += pencode(URL) + "&";
base_str += pencode(param_str);
/* get the signing key */
signing_key += pencode(consumersecret) + "&";
signing_key += pencode(tokensecret);
HMAC(EVP_sha1(), signing_key.c_str(), signing_key.length(),
(unsigned char *)base_str.c_str(), base_str.length(),
digest, &digest_len);
odata.sig = base64_enc((char *)digest, digest_len);
}
struct tw::Authenticator::oauth_data tw::Authenticator::auth_data()
{
return odata;
}
/* read_keys: read twitter keys from file (will be encrypted eventually) */
int tw::Authenticator::read_keys()
{
std::ifstream reader(configpath);
std::string line;
int lnum = 0;
if (!reader.is_open())
return -1;
while (std::getline(reader, line)) {
switch (++lnum) {
case 1:
consumerkey = line;
break;
case 2:
consumersecret = line;
break;
case 3:
token = line;
break;
case 4:
tokensecret = line;
break;
default:
return 1;
}
}
if (lnum != 4)
return 1;
return 0;
}
/* interactive_setup: obtain access tokens from user */
void tw::Authenticator::interactive_setup()
{
char c = '\0';
std::cout << configpath << " was not found." << std::endl;
std::cout << "Would you like to set up LynxBot to use Twitter? (y/n) ";
std::ofstream writer(configpath);
while (c != 'y' && c != 'n')
std::cin >> c;
if (c == 'n')
return;
std::cout << INSTRUCTIONS << std::endl;
std::cout << "Would you like to proceed? (y/n) ";
c = '\0';
while (c != 'y' && c != 'n')
std::cin >> c;
if (c == 'n')
return;
std::cout << "Enter your Consumer Key:" << std::endl;
get_str(consumerkey);
std::cout << "Enter your Consumer Secret:" << std::endl;
get_str(consumersecret);
std::cout << "Enter your Access Token:" << std::endl;
get_str(token);
std::cout << "Enter your Access Token Secret:" << std::endl;
get_str(tokensecret);
writer << consumerkey << std::endl << consumersecret << std::endl
<< token << std::endl << tokensecret << std::endl;
writer.close();
std::cout << "Your tokens have been saved to " << configpath
<< std::endl;
std::cin.get();
}
/* get_str: read a string from stdin */
static void get_str(std::string &target)
{
std::string line;
while (true) {
std::getline(std::cin, line);
if (!line.empty()) break;
std::cout << "Invalid string, try again:" << std::endl;
}
target = line;
}
| 5,030 | 1,888 |
// Bring in gtest
#include <gtest/gtest.h>
#include <boost/cstdint.hpp>
// Helpful functions from libsm
#include <sm/eigen/gtest.hpp>
#include <sm/kinematics/quaternion_algebra.hpp>
#include <sm/kinematics/UncertainTransformation.hpp>
TEST(UncertainTransformationTestSuite, testConstructor)
{
using namespace sm::kinematics;
UncertainTransformation T_a_b;
Eigen::Matrix4d T;
T.setIdentity();
UncertainTransformation::covariance_t U;
U.setZero();
sm::eigen::assertNear(T, T_a_b.T(), 1e-10, SM_SOURCE_FILE_POS, "Checking for the default constructor creating identity");
sm::eigen::assertNear(U, T_a_b.U(), 1e-10, SM_SOURCE_FILE_POS, "Checking for the default constructor creating zero uncertainty");
}
TEST(UncertainTransformationTestSuite, testTV4Multiplication)
{
using namespace sm::kinematics;
for(int i = 0; i < 100; i++)
{
UncertainTransformation T_a_b;
T_a_b.setRandom();
Eigen::Vector4d v_b;
v_b.setRandom();
v_b *= 100.0;
Eigen::Vector4d v_a = T_a_b * v_b;
Eigen::Vector4d v_a_prime = T_a_b.T() * v_b;
sm::eigen::assertNear(v_a, v_a_prime, 1e-10, SM_SOURCE_FILE_POS, "Checking for composition equal to matrix multiplication");
}
}
TEST(UncertainTransformationTestSuite, testTVhMultiplication)
{
using namespace sm::kinematics;
for(int i = 0; i < 100; i++)
{
UncertainTransformation T_a_b;
T_a_b.setRandom();
Eigen::Vector3d v_b;
v_b.setRandom();
v_b *= 100.0;
HomogeneousPoint V_b(v_b);
Eigen::Vector3d v_a = T_a_b * v_b;
HomogeneousPoint V_a = T_a_b * V_b;
sm::eigen::assertNear(V_a.toEuclidean(), v_a, 1e-10, SM_SOURCE_FILE_POS, "Checking for composition equal to matrix multiplication");
}
}
TEST(UncertainTransformationTestSuite, testTVMultiplication)
{
using namespace sm::kinematics;
for(int i = 0; i < 100; i++)
{
UncertainTransformation T_a_b;
T_a_b.setRandom();
Eigen::Vector3d v_b;
v_b.setRandom();
v_b *= 100.0;
Eigen::Vector3d v_a = T_a_b * v_b;
Eigen::Vector3d v_a_prime = T_a_b.C() * v_b + T_a_b.t();
sm::eigen::assertNear(v_a, v_a_prime, 1e-10, SM_SOURCE_FILE_POS, "Checking for composition equal to matrix multiplication");
}
}
TEST(UncertainTransformationTestSuite, testTTMultiplication)
{
try {
using namespace sm::kinematics;
for(int i = 0; i < 100; i++)
{
UncertainTransformation T_a_b;
T_a_b.setRandom();
UncertainTransformation T_b_c;
T_b_c.setRandom();
UncertainTransformation T_a_c = T_a_b * T_b_c;
Eigen::Matrix4d T_a_c_prime = T_a_b.T() * T_b_c.T();
sm::eigen::assertNear(T_a_c.T(), T_a_c_prime, 1e-10, SM_SOURCE_FILE_POS, "Checking for composition equal to matrix multiplication");
}
} catch(const std::exception & e)
{
FAIL() << e.what();
}
}
TEST(UncertainTransformationTestSuite, testInvert)
{
using namespace sm::kinematics;
for(int i = 0; i < 100; i++)
{
UncertainTransformation T_a_b;
T_a_b.setRandom();
UncertainTransformation T_b_a = T_a_b.inverse();
UncertainTransformation T_a_b_prime = T_b_a.inverse();
sm::eigen::assertNear(T_a_b_prime.T(), T_a_b.T(), 1e-10, SM_SOURCE_FILE_POS, "Checking for identity");
}
}
TEST(UncertainTransformationTestSuite, testInvertProducesIdentity)
{
using namespace sm::kinematics;
for(int i = 0; i < 100; i++)
{
UncertainTransformation T_a_b;
T_a_b.setRandom();
UncertainTransformation T_b_a = T_a_b.inverse();
UncertainTransformation Eye1 = T_a_b * T_b_a;
UncertainTransformation Eye2 = T_b_a * T_a_b;
sm::eigen::assertNear(Eye1.T(), Eigen::Matrix4d::Identity(), 1e-10, SM_SOURCE_FILE_POS, "Checking for identity");
sm::eigen::assertNear(Eye2.T(), Eigen::Matrix4d::Identity(), 1e-10, SM_SOURCE_FILE_POS, "Checking for identity");
}
}
TEST(UncertainTransformationTestSuite, testInverse)
{
using namespace sm::kinematics;
UncertainTransformation TT_01;
TT_01.setRandom();
UncertainTransformation TT_10 = TT_01.inverse();
UncertainTransformation TTT_01 = TT_10.inverse();
Eigen::Matrix4d r1_T_01 = TT_01.T();
Eigen::Matrix4d r2_T_01 = TTT_01.T();
sm::eigen::assertNear(r1_T_01, r2_T_01, 1e-10, SM_SOURCE_FILE_POS, "Testing that composition and inverse derive the same answer");
UncertainTransformation::covariance_t r1_U_01 = TT_01.U();
UncertainTransformation::covariance_t r2_U_01 = TTT_01.U();
sm::eigen::assertNear(r1_U_01, r2_U_01, 1e-10, SM_SOURCE_FILE_POS, "Testing that composition and inverse derive the same answer");
}
TEST(UncertainTransformationTestSuite, testComposition2)
{
using namespace sm::kinematics;
UncertainTransformation TT_01;
TT_01.setRandom();
UncertainTransformation TT_12;
TT_12.setRandom();
UncertainTransformation TT_02 = TT_01 * TT_12;
UncertainTransformation TT_10 = TT_01.inverse();
UncertainTransformation TT_21 = TT_12.inverse();
UncertainTransformation TT_20 = TT_21 * TT_10;
UncertainTransformation TT_20direct = TT_02.inverse();
Eigen::Matrix4d r1_T_20 = TT_20.T();
Eigen::Matrix4d r2_T_20 = TT_20direct.T();
sm::eigen::assertNear(r1_T_20, r2_T_20, 1e-10, SM_SOURCE_FILE_POS, "Testing that composition and inverse derive the same answer");
UncertainTransformation::covariance_t r1_U_20 = TT_20.U();
UncertainTransformation::covariance_t r2_U_20 = TT_20direct.U();
sm::eigen::assertNear(r1_U_20, r2_U_20, 1e-8, SM_SOURCE_FILE_POS, "Testing that composition and inverse derive the same answer");
}
TEST(UncertainTransformationTestSuite, testTVMultiplication2)
{
using namespace sm::kinematics;
for(int i = 0; i < 10; i++)
{
UncertainTransformation T_a_b;
T_a_b.setRandom();
UncertainHomogeneousPoint v_b;
v_b.setRandom();
UncertainHomogeneousPoint v_a = T_a_b * v_b;
Eigen::Vector3d v_a_prime = T_a_b.C() * v_b.toEuclidean() + T_a_b.t();
sm::eigen::assertNear(v_a.toEuclidean(), v_a_prime, 1e-10, SM_SOURCE_FILE_POS, "Checking for composition equal to matrix multiplication");
}
}
// lestefan: added this
TEST(UncertainTransformationTestSuite, testUOplus)
{
using namespace sm::kinematics;
for(int i = 0; i < 10; i++)
{
UncertainTransformation T_a_b_1;
T_a_b_1.setRandom();
UncertainTransformation::covariance_t UOplus = T_a_b_1.UOplus();
UncertainTransformation T_a_b_2=T_a_b_1;
T_a_b_2.setUOplus(UOplus);
sm::eigen::assertNear(T_a_b_1.U(), T_a_b_2.U(), 1e-10, SM_SOURCE_FILE_POS, "Checking for getting and setting OPlus-type uncertainties");
}
}
| 6,685 | 2,798 |
#include <bits/stdc++.h>
using namespace std;
int N, V;
int K[10];
vector<int> C[10];
int ans;
void func(int r, int c) {
if (r == N) {
ans += 1;
} else if (c >= (int) C[r].size()) {
func(r + 1, 0);
} else {
int curr = 1;
if (c - 1 >= 0) {
curr = max(curr, C[r][c - 1]);
}
if (r - 1 >= 0) {
curr = max(curr, C[r - 1][c] + 1);
}
for ( ; curr <= V; curr++) {
C[r][c] = curr;
func(r, c + 1);
}
}
}
int main() {
while (cin >> N) {
for (int i = 0; i < N; i++) {
cin >> K[i];
C[i].clear();
for (int j = 0; j < K[i]; j++) {
C[i].push_back(0);
}
}
cin >> V;
ans = 0;
func(0, 0);
cout << ans << "\n";
}
return 0;
}
| 885 | 365 |
#include <unistd.h>
#include "db_logger.h"
#include "util.h"
// static
bool DbLogger::LOG_FLOW_INFO_ = false;
bool DbLogger::Connect() {
//
return true;
}
DbLogger::DbLogger(string table_subfix) : table_subfix_(table_subfix) {
if (!Connect()) {
exit(-1);
}
has_init_coflow_info_table_ = false;
if (LOG_FLOW_INFO_) InitFlowInfoTable();
}
DbLogger::~DbLogger() {
// flush all data to database if needed
}
string DbLogger::GetTableName(string tabel_type) {
return tabel_type + (table_subfix_ == "" ? "" : "_" + table_subfix_);
}
bool DbLogger::DropIfExist(string table_type) {
if (!Connect()) {
return false;
}
string table_name = GetTableName(table_type);
// sql to drop table. You may also write to file named TRAFFIC_AUDIT_FILE_NAME
// query << "drop table if exists " << table_name;
// if (!query.exec()) {
// cerr << query.str() << endl;
// cerr << query.error() << endl;
// return false;
// }
// cout << "Dropped table " << table_name << endl;
return true;
}
void DbLogger::InitCoflowInfoTable() {
if (has_init_coflow_info_table_) return;
if (!DropIfExist("CoflowInfo")) return;
string table_name = GetTableName("CoflowInfo");
// sql to write table. You may also write to file named TRAFFIC_AUDIT_FILE_NAME
// query << "CREATE TABLE `" << table_name << "` (\n"
// << " `job_id` INT(11) NOT NULL,\n"
// << " `insert_ts` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n"
// << " `*cast` VARCHAR(5) DEFAULT NULL,\n"
// << " `bin` VARCHAR(5) DEFAULT NULL,\n"
// << " `map` SMALLINT DEFAULT NULL,\n"
// << " `red` SMALLINT DEFAULT NULL,\n"
// << " `flow#` INT DEFAULT NULL,\n"
// << " `map_loc` VARCHAR(500) DEFAULT NULL,\n"
// << " `red_loc` VARCHAR(500) DEFAULT NULL,\n"
// << " `bn_load_Gbit` DOUBLE DEFAULT NULL,\n"
// << " `lb_optc` DOUBLE DEFAULT NULL,\n"
// << " `lb_elec` DOUBLE DEFAULT NULL,\n"
// << " `lb_elec_bit` BIGINT DEFAULT NULL,\n"
// << " `ttl_Gbit` DOUBLE DEFAULT NULL,\n"
// << " `avg_Gbit` DOUBLE DEFAULT NULL,\n"
// << " `min_Gbit` DOUBLE DEFAULT NULL,\n"
// << " `max_Gbit` DOUBLE DEFAULT NULL,\n"
// << " `tArr` DOUBLE DEFAULT NULL,\n"
// << " `tFin` DOUBLE DEFAULT NULL,\n"
// << " `cct` DOUBLE DEFAULT NULL,\n"
// << " `r_optc` DOUBLE DEFAULT NULL,\n"
// << " `r_elec` DOUBLE DEFAULT NULL,\n"
// << " PRIMARY KEY (`job_id`)\n"
// << ");";
// cout << "Created table " << table_name << endl;
has_init_coflow_info_table_ = true;
}
void DbLogger::WriteCoflowFeatures(Coflow *coflow) {
if (!Connect()) return;
if (!has_init_coflow_info_table_) InitCoflowInfoTable();
// read a coflow. start building up knowledge.
double total_flow_size_Gbit = 0.0;
double min_flow_size_Gbit = -1.0;
double max_flow_size_Gbit = -1.0;
const map<pair<int, int>, long> &mr_demand_byte = coflow->GetMRFlowBytes();
int flow_num = (int) coflow->GetFlows()->size();
for (Flow *flow : *(coflow->GetFlows())) {
double this_flow_size_Gbit = ((double) flow->GetSizeInBit() / 1e9);
total_flow_size_Gbit += this_flow_size_Gbit; // each flow >= 1MB
if (min_flow_size_Gbit > this_flow_size_Gbit || min_flow_size_Gbit < 0) {
min_flow_size_Gbit = this_flow_size_Gbit;
}
if (max_flow_size_Gbit < this_flow_size_Gbit || max_flow_size_Gbit < 0) {
max_flow_size_Gbit = this_flow_size_Gbit;
}
}
double avg_flow_size_Gbit = total_flow_size_Gbit / (double) flow_num;
string cast_pattern = "";
int map = coflow->GetNumMap();
int red = coflow->GetNumRed();
if (map == 1 && red == 1) {
cast_pattern = "1"; // single-flow
} else if (map > 1 && red == 1) {
cast_pattern = "m21"; // incast
} else if (map == 1 && red > 1) {
cast_pattern = "12m"; // one sender, multiple receiver.
} else if (map > 1 && red > 1) {
cast_pattern = "m2m"; // many-to-many
}
string bin;
// double lb_elec_MB = lb_elec / (double) 8.0/ 1000000;
bin += (avg_flow_size_Gbit / 8.0 * 1e3 < 5.0) ?
'S' : 'L'; // short if avg flow size < 5MB, long other wise
bin += (flow_num <= 50) ? 'N' : 'W';// narrow if max flow# <= 50
string table_name = GetTableName("CoflowInfo");
// sql to write table. You may also write to file named TRAFFIC_AUDIT_FILE_NAME
// use INSERT and UPDATE so that part of the info written may stay.
// query << "INSERT INTO " << table_name << " "
// << "(`job_id`, `*cast`, `bin`, `map`, `red`, `flow#`, "
// << "`map_loc`, `red_loc`, "
// << "`bn_load_Gbit`, `lb_optc`, `lb_elec`, `lb_elec_bit`, "
// << "`ttl_Gbit`, `avg_Gbit`, `min_Gbit`, `max_Gbit`) VALUES ("
// << coflow->GetJobId() << ','
// << "'" << cast_pattern << "'" << ','
// << "'" << bin << "'" << ','
// << map << ','
// << red << ','
// << flow_num << ','
// << "'" << Join(coflow->GetMapperLocations(), '_') << "'" << ','
// << "'" << Join(coflow->GetReducerLocations(), '_') << "'" << ','
// << coflow->GetMaxMapRedLoadGb() << ',' // bn_load_GB
// << coflow->GetMaxOptimalWorkSpanInSeconds() << ',' // lb_optc
// << coflow->GetMaxPortLoadInSec() << ',' // lb_elec
// << coflow->GetMaxPortLoadInBits() << ',' // lb_elec_bit
// << total_flow_size_Gbit << ','
// << avg_flow_size_Gbit << ','
// << min_flow_size_Gbit << ','
// << max_flow_size_Gbit << ") "
// << "ON DUPLICATE KEY UPDATE "
// << "`*cast`= values (`*cast`), "
// << "`bin`= values (`bin`), "
// << "`map`= values (`map`), "
// << "`red`= values (`red`), "
// << "`flow#`= values (`flow#`), "
// << "`map_loc`= values (`map_loc`), "
// << "`red_loc`= values (`red_loc`), "
// << "`lb_optc`= values (`lb_optc`), "
// << "`lb_elec`= values (`lb_elec`), "
// << "`lb_elec_bit`= values (`lb_elec_bit`), "
// << "`ttl_Gbit`= values (`ttl_Gbit`), "
// << "`avg_Gbit`= values (`avg_Gbit`), "
// << "`min_Gbit`= values (`min_Gbit`), "
// << "`max_Gbit`= values (`max_Gbit`); ";
}
void DbLogger::WriteOnCoflowFinish(double finish_time,
Coflow *coflow) {
if (!has_init_coflow_info_table_) InitCoflowInfoTable();
double cct = (finish_time - coflow->GetStartTime());
double optc_lb = coflow->GetMaxOptimalWorkSpanInSeconds();
double elec_lb = coflow->GetMaxPortLoadInSeconds();
double cct_over_optc = cct / optc_lb;
double cct_over_elec = cct / elec_lb;
string table_name = GetTableName("CoflowInfo");
// sql to write table. You may also write to file named TRAFFIC_AUDIT_FILE_NAME
// use INSERT and UPDATE so that part of the info written may stay.
// query << "INSERT INTO " << table_name << " "
// << "(`job_id`, `tArr`, `tFin`, `cct`, `r_optc`, `r_elec`) VALUES ("
// << coflow->GetJobId() << ','
// << coflow->GetStartTime() << ','
// << finish_time << ','
// << (cct > 0 ? to_string(cct) : "null") << ','
// << (optc_lb > 0 ? to_string(cct_over_optc) : "null") << ','
// << (optc_lb > 0 ? to_string(cct_over_elec) : "null") << ") "
// << "ON DUPLICATE KEY UPDATE "
// << "`tArr`= values (`tArr`), "
// << "`tFin`= values (`tFin`), "
// << "`cct`= values (`cct`), "
// << "`r_optc`= values (`r_optc`), "
// << "`r_elec`= values (`r_elec`); ";
}
void DbLogger::InitFlowInfoTable() {
if (!DropIfExist("FlowInfo")) return;
string table_name = GetTableName("FlowInfo");
// table schema
// query << "CREATE TABLE `" << table_name << "` (\n"
// << " `job_id` INT(11) NOT NULL,\n"
// << " `flow_id` INT(11) NOT NULL,\n"
// << " `insert_ts` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n"
// << " `src` smallint NOT NULL,\n"
// << " `dst` smallint NOT NULL,\n"
// << " `flow_size_bit` BIGINT DEFAULT NULL,\n"
// << " `tArr` DOUBLE DEFAULT NULL,\n"
// << " `tFin` DOUBLE DEFAULT NULL,\n"
// << " `fct` DOUBLE DEFAULT NULL,\n"
// << " PRIMARY KEY (`flow_id`)\n"
// << ");";
// cout << "Created table " << table_name << endl;
}
void DbLogger::WriteOnFlowFinish(double finish_time, Flow *flow) {
if (!LOG_FLOW_INFO_) return;
double fct = (finish_time - flow->GetStartTime());
string table_name = GetTableName("FlowInfo");
// sql to write table. You may also write to file named TRAFFIC_AUDIT_FILE_NAME
// always use INSERT as there is appending.
// query << "INSERT INTO " << table_name << " "
// << "(`job_id`, `flow_id`, `src` ,`dst`, `flow_size_bit`, "
// << "`tArr`, `tFin`, `fct`) VALUES ("
// << flow->GetParentCoflow()->GetJobId() << ','
// << flow->GetFlowId() << ','
// << flow->GetSrc() << ','
// << flow->GetDest() << ','
// << flow->GetSizeInBit() << ','
// << flow->GetStartTime() << ','
// << finish_time << ','
// << fct << ");";
} | 9,414 | 3,561 |
//sets up the game and starts the main loop
#include "Game.h"
int Game::instances = 0;
void Game::run() {
bool running = true; //set running to true
SDL_Event sdlEvent;
std::cout << "Progress: About to enter main loop" << std::endl;
while (running)
{
while (SDL_PollEvent(&sdlEvent))
{
if (sdlEvent.type == SDL_QUIT)
running = false;
else
stateCurrent->handleSDLEvent(sdlEvent, *this);
}
stateCurrent->draw(window, *this); //draw current state
stateCurrent->update(*this); //update the current state
}
}
Game::Game() {
window = setupRC(glContext);
//create and initialise all states
stateMap = new StateMap();
stateMainMenu = new StateMainMenu();
stateIntro = new StateIntro();
stateCredits = new StateCredits();
stateCombat = new StateCombat();
stateCharSelect = new StateCharSelect();
stateGameOver = new StateGameOver();
stateMap->init(*this);
stateMainMenu->init(*this);
stateIntro->init(*this);
stateCredits->init(*this);
stateCombat->init(*this);
stateCharSelect->init(*this);
stateGameOver->init(*this);
stateCurrent = stateIntro; //set starting state
instances++;
if (instances > 1)
Label::exitFatalError("Attempt to create multiple game instances"); //stop multiplse instances
//create and initalise all objects in the map
player = new Player();
monsterFactory = new MonsterFactory();
monArr[0] = monsterFactory->orderMonster("fodder");
monArr[1] = monsterFactory->orderMonster("fodder");
monArr[2] = monsterFactory->orderMonster("fodder");
monArr[3] = monsterFactory->orderMonster("fodder");
monArr[4] = monsterFactory->orderMonster("fodder");
monArr[5] = monsterFactory->orderMonster("brute");
monArr[6] = monsterFactory->orderMonster("brute");
monArr[7] = monsterFactory->orderMonster("brute");
monArr[8] = monsterFactory->orderMonster("raider");
itemArr[0]= new ItemStimulant(new Item("Stimulant", 0, 0, 1));
itemArr[1]= new ItemHealthPack(new Item("Health Pack", 0, 1, 0));
itemArr[2]= new ItemHealthPack(new Item("Health Pack", 0, 1, 0));
itemArr[3]= new ItemCombatPack(new Item("Combat Pack", 2, 0, 0));
itemArr[4]= new ItemCombatPack(new Item("Combat Pack", 2, 0, 0));
}
SDL_Window * Game::setupRC(SDL_GLContext &context) // setup SDL window
{
TTF_Font* textFont;
SDL_Window *window;
if (SDL_Init(SDL_INIT_VIDEO) < 0) // Initialize video
Label::exitFatalError("Unable to initialize SDL");
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
window = SDL_CreateWindow("Fantasy Rogue Game",
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
800, 600, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN );
if (!window)
Label::exitFatalError("Unable to create window");
context = SDL_GL_CreateContext(window);
SDL_GL_SetSwapInterval(1);
if (TTF_Init()== -1)
Label::exitFatalError("TTF failed to initialise.");
textFont = TTF_OpenFont("MavenPro-Regular.ttf", 24);
if (textFont == NULL)
Label::exitFatalError("Failed to open font.");
return window;
}
Game::~Game() {
delete stateCurrent;
delete stateMap;
delete stateMainMenu;
delete stateIntro;
delete stateCredits;
delete stateCombat;
delete stateCharSelect;
delete stateGameOver;
SDL_DestroyWindow(window);
SDL_Quit();
}
| 3,497 | 1,346 |
#include "HelperApp.h"
#include <vector>
#include <QApplication>
#include <QHostAddress>
#include <Core/Macros.h>
HelperApp::HelperApp(u16 port, QObject* parent)
: QObject(parent)
, m_menu()
, m_tcpSocket()
, m_socketReadData()
, m_dbConn()
, m_projectsWindow(m_dbConn)
, m_errorsWindow(m_dbConn)
, m_aboutWindow()
, m_callbackQueue()
{
QHostAddress address(QHostAddress::LocalHost);
m_tcpSocket.connectToHost(address, port);
connect(&m_tcpSocket, &QTcpSocket::readyRead,
this, &HelperApp::SocketReadyForRead);
connect(&m_tcpSocket, &QTcpSocket::bytesWritten,
this, &HelperApp::OnBytesWritten);
QAction* aboutAction = m_menu.addAction("About Asset Pipeline");
aboutAction->setMenuRole(QAction::AboutRole);
connect(aboutAction, &QAction::triggered, this, &HelperApp::ShowAboutWindow);
QAction* quitAction = m_menu.addAction("Quit Asset Pipeline");
quitAction->setMenuRole(QAction::QuitRole);
quitAction->setShortcut(QKeySequence::Quit);
connect(quitAction, &QAction::triggered, [=] {
SendIPCMessage(IPCHELPERTOAPP_QUIT);
RegisterOnBytesSent([](size_t bytes) {
QMetaObject::invokeMethod(qApp, "quit", Qt::QueuedConnection);
});
});
m_tcpSocket.waitForConnected();
}
HelperApp::~HelperApp()
{}
void HelperApp::ShowAboutWindow()
{
m_aboutWindow.show();
}
void HelperApp::SocketReadyForRead()
{
qint64 bytesAvailable = m_tcpSocket.bytesAvailable();
m_socketReadData.resize((size_t)bytesAvailable);
m_tcpSocket.read((char*)&m_socketReadData[0],
(qint64)m_socketReadData.size());
for (size_t i = 0; i < m_socketReadData.size(); ++i) {
ReceiveByte(m_socketReadData[i]);
}
}
void HelperApp::ReceiveByte(u8 byte)
{
IPCAppToHelperAction action = (IPCAppToHelperAction)byte;
switch (action) {
case IPCAPPTOHELPER_SHOW_PROJECTS_WINDOW:
m_projectsWindow.show();
break;
case IPCAPPTOHELPER_SHOW_ERRORS_WINDOW:
m_errorsWindow.show();
break;
case IPCAPPTOHELPER_SHOW_ABOUT_WINDOW:
ShowAboutWindow();
break;
case IPCAPPTOHELPER_REFRESH_ERRORS:
// Only actually reload if the window is visible (this is a
// performance optimization). If the window becomes visible after
// this, it will reload the data anyway.
if (m_errorsWindow.isVisible())
m_errorsWindow.ReloadErrors();
break;
case IPCAPPTOHELPER_QUIT:
QMetaObject::invokeMethod(qApp, "quit", Qt::QueuedConnection);
break;
}
}
void HelperApp::SendIPCMessage(IPCHelperToAppAction action)
{
if ((u32)action > 0xFF)
FATAL("Size of message exceeded one byte");
u8 byte = (u8)action;
m_tcpSocket.write((const char*)&byte, 1);
}
void HelperApp::RegisterOnBytesSent(const BytesSentFunc& func)
{
m_callbackQueue.push_back(func);
}
void HelperApp::OnBytesWritten(qint64 bytes)
{
for (size_t i = 0; i < m_callbackQueue.size(); ++i) {
m_callbackQueue[i]((size_t)bytes);
}
m_callbackQueue.clear();
}
| 3,206 | 1,084 |
#include "cameranorotation.h"
CameraNoRotation::CameraNoRotation()
{
}
void CameraNoRotation::mouseMove(const QPointF &p)
{
if(firstPassInMouseMove){
lastPos3D=mousePosTo3D(p);
firstPassInMouseMove=false;
return;
}
QTime currentTime = QTime::currentTime();
vp = mousePosTo3D(p);
//at=eye+atMinusEyeXPlane;
at.setY(vp.y());
direction=rotationXZByY(QVector3D(0,0,0.2),3*doubleRotationCameraX);
lastPos3D=vp;
lastTime = currentTime;
}
| 499 | 204 |
#include "parameters_parser.hh"
#include "flags.hh"
namespace Kakoune
{
String generate_switches_doc(const SwitchMap& switches)
{
String res;
if (switches.empty())
return res;
auto switch_len = [](auto& sw) { return sw.key.column_length() + (sw.value.takes_arg ? 5 : 0); };
auto switches_len = switches | transform(switch_len);
const ColumnCount maxlen = *std::max_element(switches_len.begin(), switches_len.end());
for (auto& sw : switches) {
res += format("-{} {}{}{}\n",
sw.key,
sw.value.takes_arg ? "<arg>" : "",
String{' ', maxlen - switch_len(sw) + 1},
sw.value.description);
}
return res;
}
ParametersParser::ParametersParser(ParameterList params, const ParameterDesc& desc)
: m_params(params),
m_desc(desc)
{
const bool switches_only_at_start = desc.flags & ParameterDesc::Flags::SwitchesOnlyAtStart;
const bool ignore_unknown_switches = desc.flags & ParameterDesc::Flags::IgnoreUnknownSwitches;
bool only_pos = desc.flags & ParameterDesc::Flags::SwitchesAsPositional;
Vector<bool> switch_seen(desc.switches.size(), false);
for (size_t i = 0; i < params.size(); ++i)
{
if (not only_pos and not ignore_unknown_switches and params[i] == "--")
only_pos = true;
else if (not only_pos and not params[i].empty() and params[i][0_byte] == '-')
{
auto it = m_desc.switches.find(params[i].substr(1_byte));
if (it == m_desc.switches.end())
{
if (ignore_unknown_switches)
{
m_positional_indices.push_back(i);
if (switches_only_at_start)
only_pos = true;
continue;
}
throw unknown_option(params[i]);
}
auto switch_index = it - m_desc.switches.begin();
if (switch_seen[switch_index])
throw runtime_error{format("switch '-{}' specified more than once", it->key)};
switch_seen[switch_index] = true;
if (it->value.takes_arg and ++i == params.size())
throw missing_option_value(it->key);
}
else // positional
{
if (switches_only_at_start)
only_pos = true;
m_positional_indices.push_back(i);
}
}
size_t count = m_positional_indices.size();
if (count > desc.max_positionals or count < desc.min_positionals)
throw wrong_argument_count();
}
Optional<StringView> ParametersParser::get_switch(StringView name) const
{
auto it = m_desc.switches.find(name);
kak_assert(it != m_desc.switches.end());
for (size_t i = 0; i < m_params.size(); ++i)
{
const auto& param = m_params[i];
if (param.substr(0_byte, 1_byte) == "-" and param.substr(1_byte) == name)
return it->value.takes_arg ? m_params[i+1] : StringView{};
if (param == "--")
break;
}
return {};
}
}
| 3,094 | 967 |
/*++
Copyright (c) 1995 Microsoft Corporation
Module Name:
apimonwin.h
Abstract:
Implemenation for the base ApiMon child window class.
Author:
Wesley Witt (wesw) Dec-9-1995
Environment:
User Mode
--*/
#include "apimonp.h"
#pragma hdrstop
#include "apimonwn.h"
ApiMonWindow::ApiMonWindow()
{
hInstance = GetModuleHandle( NULL );
hwndWin = NULL;
hwndList = NULL;
SortRoutine = NULL;
hFont = NULL;
Color = 0;
ZeroMemory( &Position, sizeof(POSITION) );
}
ApiMonWindow::~ApiMonWindow()
{
}
BOOL
ApiMonWindow::Create(
LPSTR ClassName,
LPSTR Title
)
{
hwndWin = CreateMDIWindow(
ClassName,
Title,
0,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
hwndMDIClient,
hInstance,
(LPARAM) this
);
if (!hwndWin) {
return FALSE;
}
ShowWindow(
hwndWin,
SW_SHOW
);
return TRUE;
}
BOOL
ApiMonWindow::Register(
LPSTR ClassName,
ULONG ChildIconId,
WNDPROC WindowProc
)
{
WNDCLASSEX wc;
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(ChildIconId));
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)COLOR_APPWORKSPACE;
wc.lpszMenuName = NULL;
wc.hIconSm = (HICON)LoadImage(
hInstance,
MAKEINTRESOURCE(ChildIconId),
IMAGE_ICON,
16,
16,
0
);
wc.lpfnWndProc = WindowProc;
wc.lpszClassName = ClassName;
return RegisterClassEx( &wc );
}
void
ApiMonWindow::ChangeFont(
HFONT hFont
)
{
if (hwndList) {
ApiMonWindow::hFont = hFont;
SendMessage(
hwndList,
WM_SETFONT,
(WPARAM)hFont,
MAKELPARAM( TRUE, 0 )
);
}
}
void
ApiMonWindow::ChangeColor(
COLORREF Color
)
{
if (hwndList) {
ApiMonWindow::Color = Color;
ListView_SetBkColor( hwndList, Color );
ListView_SetTextBkColor( hwndList, Color );
InvalidateRect( hwndList, NULL, TRUE );
UpdateWindow( hwndList );
}
}
void
ApiMonWindow::ChangePosition(
PPOSITION Position
)
{
ApiMonWindow::Position = *Position;
SetWindowPosition( hwndWin, Position );
}
void
ApiMonWindow::SetFocus()
{
BringWindowToTop( hwndWin );
SetForegroundWindow( hwndWin );
}
BOOL
ApiMonWindow::Update(
BOOL ForceUpdate
)
{
if ((!hwndWin) || (!hwndList)) {
return FALSE;
}
return TRUE;
}
void
ApiMonWindow::DeleteAllItems()
{
ListView_DeleteAllItems( hwndList );
}
| 3,202 | 1,187 |
#include<iostream>
using namespace std;
int main(int argc, char* argv[])
{
int n = 0;
cin >> n;
int* o = new int[n] {0};
for (int i = 0; i < n; ++i)
{
cin >> o[i];
}
int max = o[0];
int min = o[0];
for (int i = 0; i < n; ++i)
{
if (o[i] < min)
{
min = o[i];
}
if (o[i] > max)
{
max = o[i];
}
}
for (int i = 0; i < n; ++i)
{
if (o[i] == max)
{
o[i] = min;
}
}
for (int i = 0; i < n; ++i)
{
cout << o[i] << " ";
}
delete[] o;
return EXIT_SUCCESS;
} | 500 | 297 |
#include "SED.h"
// Could remove the columns that are all zeros and speed up the computation
SED::SED(){}
void SED::ComputeObjFunMuti( vector<int> all_distance_block, VectorXd* smp_vec_muti, vector<double>* obj_seq_pt, int val_idx ) {
double obj_tmp = 0;
for (int i=0; i<all_distance_block.size(); i++) {
est_distribution[all_distance_block[i]] = ComputeEstDbt(smp_vec_muti, all_distance_block[i]);
obj_tmp += pow( est_distribution[all_distance_block[i]] - all_distribution[all_distance_block[i]] , 2);
}
(*obj_seq_pt)[val_idx] = obj_tmp;
}
double SED::ComputeObjFun(VectorXd smp_vec) {
vector<double> obj_seq(num_thread_assign, 0);
if (num_thread_assign>1) {
thread *multi_thread = new thread[num_thread_assign-1];
for (int i=0; i<num_thread_assign-1; i++) {
multi_thread[i] = thread(&SED::ComputeObjFunMuti, this, all_partition[i], &smp_vec, &obj_seq, i);
}
ComputeObjFunMuti( all_partition[num_thread_assign-1], &smp_vec, &obj_seq, num_thread-1);
for (int i=0; i<num_thread_assign-1; i++) {
multi_thread[i].join();
}
delete [] multi_thread;
} else {
ComputeObjFunMuti( all_partition[num_thread_assign-1], &smp_vec, &obj_seq, num_thread-1);
}
double obj = 0;
for (int i=0; i<num_thread_assign; i++) {
obj += obj_seq[i];
}
return obj;
}
void SED::ComputeGradientMuti( vector<int> all_distance_block, VectorXd* smp_vec_muti, VectorXd* smp_der_seq_pt, int val_idx ) {
VectorXd smp_der_seq_tmp = VectorXd::Zero(M);
for (int i=0; i<all_distance_block.size(); i++) {
double mut_factor = (2.0*( est_distribution[all_distance_block[i]] - all_distribution[all_distance_block[i]] ) );
ComputeEstProj(smp_vec_muti, smp_der_seq_pt, mut_factor, all_distance_block[i]);
}
}
VectorXd SED::ComputeGradient(VectorXd smp_vec) {
vector<VectorXd> smp_der_seq(num_thread_assign, VectorXd::Zero(M));
if (num_thread_assign>1) {
thread *multi_thread = new thread[num_thread_assign-1];
for (int i=0; i<num_thread_assign-1; i++) {
multi_thread[i] = thread(&SED::ComputeGradientMuti, this, all_partition[i], &smp_vec, &smp_der_seq[i], i);
}
ComputeGradientMuti( all_partition[num_thread_assign-1], &smp_vec, &smp_der_seq[num_thread_assign-1], num_thread_assign-1 );
for (int i=0; i<num_thread_assign-1; i++) {
multi_thread[i].join();
}
delete [] multi_thread;
} else {
ComputeGradientMuti( all_partition[num_thread_assign-1], &smp_vec, &smp_der_seq[num_thread_assign-1], num_thread_assign-1 );
}
VectorXd smp_der = VectorXd::Zero(M);
for (int i=0; i<num_thread_assign; i++) {
smp_der.noalias() += smp_der_seq[i];
}
return smp_der;
}
SED::~SED() {}
| 2,961 | 1,135 |
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 1992-2001 by Sun Microsystems, Inc.
* All rights reserved.
*/
#pragma ident "%Z%%M% %I% %E% SMI"
#include <memory.h>
#include <stddef.h>
#include <sys/types.h>
#include <Fir.h>
extern "C" {
char *bcopy(char *, char *, int);
char *memmove(char *, char *, int);
}
#define BCOPY(src, dest, num) memmove(dest, src, num)
/*
* convolve()
* returns the convolution of coef[length] and in_buf[length]:
*
* convolution = coef[0] * in_buf[length - 1] +
* coef[1] * in_buf[length - 2] +
* ...
* coef[length - 1] * in_buf[0]
*/
double
convolve(
double *coefs,
double *in_buf,
int length)
{
if (length <= 0)
return (0.0);
else {
in_buf += --length;
double sum = *coefs * *in_buf;
while (length--)
sum += *++coefs * *--in_buf;
return (sum);
}
}
void // convert short to double
short2double(
double *out,
short *in,
int size)
{
while (size-- > 0)
*out++ = (double)*in++;
}
short
double2short(double in) // limit double to short
{
if (in <= -32768.0)
return (-32768);
else if (in >= 32767.0)
return (32767);
else
return ((short)in);
}
void Fir:: // update state with data[size]
updateState(
double *data,
int size)
{
if (size >= order)
memcpy(state, data + size - order, order * sizeof (double));
else {
int old = order - size;
BCOPY((char *)(state + size), (char *)state,
old * sizeof (double));
memcpy(state + order - size, data, size * sizeof (double));
}
}
void Fir::
update_short(
short *in,
int size)
{
double *in_buf = new double[size];
short2double(in_buf, in, size);
updateState(in_buf, size);
delete in_buf;
}
void Fir::
resetState(void) // reset state to all zero
{
for (int i = 0; i < order; i++)
state[i] = 0.0;
}
Fir::
Fir(void)
{
}
Fir::
Fir(int order_in): order(order_in) // construct Fir object
{
state = new double[order];
resetState();
coef = new double[order + 1];
delay = (order + 1) >> 1; // assuming symmetric FIR
}
Fir::
~Fir() // destruct Fir object
{
delete coef;
delete state;
}
int Fir::
getOrder(void) // returns filter order
{
return (order);
}
int Fir::
getNumCoefs(void) // returns number of filter coefficients
{
return (order + 1);
}
void Fir::
putCoef(double *coef_in) // copy coef_in in filter coefficients
{
memcpy(coef, coef_in, (order + 1) * sizeof (double));
}
void Fir::
getCoef(double *coef_out) // returns filter coefs in coef_out
{
memcpy(coef_out, coef, (order + 1) * sizeof (double));
}
int Fir:: // filter in[size], and updates the state.
filter_noadjust(
short *in,
int size,
short *out)
{
if (size <= 0)
return (0);
double *in_buf = new double[size];
short2double(in_buf, in, size); // convert short input to double
int i;
int init_size = (size <= order)? size : order;
int init_order = order;
double *state_ptr = state;
short *out_ptr = out;
// the first "order" outputs need state in convolution
for (i = 1; i <= init_size; i++)
*out_ptr++ = double2short(convolve(coef, in_buf, i) +
convolve(coef + i, state_ptr++, init_order--));
// starting from "order + 1"th output, state is no longer needed
state_ptr = in_buf;
while (i++ <= size)
*out_ptr++ =
double2short(convolve(coef, state_ptr++, order + 1));
updateState(in_buf, size);
delete in_buf;
return (out_ptr - out);
}
int Fir::
getFlushSize(void)
{
int group_delay = (order + 1) >> 1;
return ((delay < group_delay)? group_delay - delay : 0);
}
int Fir::
flush(short *out) // zero input response of Fir
{
int num = getFlushSize();
if (num > 0) {
short *in = new short[num];
memset(in, 0, num * sizeof (short));
num = filter_noadjust(in, num, out);
delete in;
}
return (num);
}
/*
* filter() filters in[size] with filter delay adjusted to 0
*
* All FIR filters introduce a delay of "order" samples between input and
* output sequences. Most FIR filters are symmetric filters to keep the
* linear phase responses. For those FIR fitlers the group delay is
* "(order + 1) / 2". So filter_nodelay adjusts the group delay in the
* output sequence such that the output is aligned with the input and
* direct comparison between them is possible.
*
* The first call of filter returns "size - group_delay" output samples.
* After all the input samples have been filtered, filter() needs
* to be called with size = 0 to get the residual output samples to make
* the output sequence the same length as the input.
*
*/
int Fir::
filter(
short *in,
int size,
short *out)
{
if ((size <= 0) || (in == NULL))
return (flush(out));
else if (delay <= 0)
return (filter_noadjust(in, size, out));
else if (size <= delay) {
update_short(in, size);
delay -= size;
return (0);
} else {
update_short(in, delay);
in += delay;
size -= delay;
delay = 0;
return (filter_noadjust(in, size, out));
}
}
| 5,652 | 2,184 |
/*
* Copyright (c) 2016 dresden elektronik ingenieurtechnik gmbh.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
*/
#include "de_web_plugin_private.h"
/*! WSNDemo sensor data handler send by routers and end devices.
\param ind a WSNDemo data frame
*/
void DeRestPluginPrivate::wsnDemoDataIndication(const deCONZ::ApsDataIndication &ind)
{
// check valid WSNDemo endpoint
if (ind.srcEndpoint() != 0x01)
{
return;
}
// check WSNDemo cluster
if (ind.clusterId() != 0x0001)
{
return;
}
QDataStream stream(ind.asdu());
stream.setByteOrder(QDataStream::LittleEndian);
uint8_t msgType;
uint8_t nodeType;
quint64 ieeeAddr;
uint16_t nwkAddr;
uint32_t version;
uint32_t channelMask;
uint16_t panId;
uint8_t channel;
uint16_t parentAddr;
uint8_t lqi;
int8_t rssi;
uint8_t fieldType;
uint8_t fieldSize;
// if fieldtype == 0x01 (sensor data)
uint32_t battery;
uint32_t temperature;
uint32_t illuminance;
stream >> msgType;
stream >> nodeType;
stream >> ieeeAddr;
stream >> nwkAddr;
stream >> version;
stream >> channelMask;
stream >> panId;
stream >> channel;
stream >> parentAddr;
stream >> lqi;
stream >> rssi;
stream >> fieldType;
stream >> fieldSize;
if (fieldType == 0x01)
{
stream >> battery;
stream >> temperature;
stream >> illuminance;
DBG_Printf(DBG_INFO, "Sensor 0x%016llX battery: %u, temperature: %u, light: %u\n", ieeeAddr, battery, temperature, illuminance);
// std::vector<Sensor>::iterator i = sensors.begin();
// std::vector<Sensor>::iterator end = sensors.end();
/* TODO review code for new sensor API
for ( ; i != end; ++i)
{
if (i->address().ext() == ieeeAddr)
{
bool updated = false;
if (i->temperature() != (double)temperature)
{
updated = true;
i->setTemperature(temperature);
}
if (i->lux() != (double)illuminance)
{
updated = true;
i->setLux(illuminance);
}
if (updated)
{
updateEtag(i->etag);
}
return;
}
}
*/
// does not exist yet create Sensor instance
DBG_Printf(DBG_INFO, "found new sensor 0x%016llX\n", ieeeAddr);
Sensor sensor;
sensor.setName(QString("Sensor %1").arg(sensors.size() + 1));
/*
sensor.address().setExt(ieeeAddr);
sensor.address().setNwk(nwkAddr);
sensor.setId(sensor.address().toStringExt());
sensor.setLux(illuminance);
sensor.setTemperature(temperature);
*/
updateEtag(sensor.etag);
sensors.push_back(sensor);
}
}
| 3,104 | 1,028 |
#include <gtest/gtest.h>
#include <searchlib.h>
#include <filesystem>
#include <fstream>
#include "test_utils.h"
using namespace searchlib;
const auto KJV_PATH = "../../test/t_kjv.tsv";
auto normalizer = [](auto sv) { return unicode::to_lowercase(sv); };
static auto kjv_index() {
InMemoryInvertedIndex<TextRange> invidx;
InMemoryIndexer indexer(invidx, normalizer);
std::ifstream fs(KJV_PATH);
if (fs) {
std::string line;
while (std::getline(fs, line)) {
auto fields = split(line, '\t');
auto document_id = std::stoi(fields[0]);
const auto &s = fields[4];
indexer.index_document(document_id, UTF8PlainTextTokenizer(s));
}
}
return invidx;
}
TEST(KJVTest, SimpleTest) {
const auto &invidx = kjv_index();
{
auto expr = parse_query(invidx, normalizer, R"( apple )");
ASSERT_TRUE(expr);
auto postings = perform_search(invidx, *expr);
ASSERT_TRUE(postings);
ASSERT_EQ(8, postings->size());
auto term = U"apple";
EXPECT_EQ(8, invidx.df(term));
EXPECT_AP(0.411, tf_idf_score(invidx, *expr, *postings, 0));
EXPECT_AP(0.745, tf_idf_score(invidx, *expr, *postings, 1));
EXPECT_AP(0.852, tf_idf_score(invidx, *expr, *postings, 2));
EXPECT_AP(0.351, tf_idf_score(invidx, *expr, *postings, 3));
EXPECT_AP(0.341, tf_idf_score(invidx, *expr, *postings, 4));
EXPECT_AP(0.341, tf_idf_score(invidx, *expr, *postings, 5));
EXPECT_AP(0.298, tf_idf_score(invidx, *expr, *postings, 6));
EXPECT_AP(0.385, tf_idf_score(invidx, *expr, *postings, 7));
EXPECT_AP(0.660, bm25_score(invidx, *expr, *postings, 0));
EXPECT_AP(1.753, bm25_score(invidx, *expr, *postings, 1));
EXPECT_AP(2.146, bm25_score(invidx, *expr, *postings, 2));
EXPECT_AP(0.500, bm25_score(invidx, *expr, *postings, 3));
EXPECT_AP(0.475, bm25_score(invidx, *expr, *postings, 4));
EXPECT_AP(0.475, bm25_score(invidx, *expr, *postings, 5));
EXPECT_AP(0.374, bm25_score(invidx, *expr, *postings, 6));
EXPECT_AP(0.588, bm25_score(invidx, *expr, *postings, 7));
}
{
auto expr = parse_query(invidx, normalizer, R"( "apple tree" )");
ASSERT_TRUE(expr);
auto postings = perform_search(invidx, *expr);
ASSERT_TRUE(postings);
ASSERT_EQ(3, postings->size());
EXPECT_EQ(1, postings->search_hit_count(0));
EXPECT_EQ(1, postings->search_hit_count(1));
EXPECT_EQ(1, postings->search_hit_count(2));
EXPECT_EQ(2, term_count_score(invidx, *expr, *postings, 0));
EXPECT_EQ(2, term_count_score(invidx, *expr, *postings, 1));
EXPECT_EQ(5, term_count_score(invidx, *expr, *postings, 2));
EXPECT_AP(0.572, tf_idf_score(invidx, *expr, *postings, 0));
EXPECT_AP(0.556, tf_idf_score(invidx, *expr, *postings, 1));
EXPECT_AP(1.051, tf_idf_score(invidx, *expr, *postings, 2));
EXPECT_AP(0.817, bm25_score(invidx, *expr, *postings, 0));
EXPECT_AP(0.776, bm25_score(invidx, *expr, *postings, 1));
EXPECT_AP(1.285, bm25_score(invidx, *expr, *postings, 2));
}
}
TEST(KJVTest, UTF8DecodePerformance) {
// auto normalizer = [](const auto &str) {
// return unicode::to_lowercase(str);
// };
auto normalizer = to_lowercase;
std::ifstream fs(KJV_PATH);
std::string s;
while (std::getline(fs, s)) {
UTF8PlainTextTokenizer tokenizer(s);
tokenizer(normalizer, [&](auto &str, auto, auto) {});
}
}
| 3,366 | 1,558 |
// Copyright 2009 by BBN Technologies Corp.
// All Rights Reserved.
#include "Generic/common/leak_detection.h"
#include "Generic/theories/Region.h"
#include "Generic/common/LocatedString.h"
#include "Generic/common/OutputUtil.h"
#include "Generic/common/InternalInconsistencyException.h"
#include <wchar.h>
#include "Generic/reader/DefaultDocumentReader.h"
#include "Generic/state/XMLStrings.h"
#include "Generic/state/XMLTheoryElement.h"
// Note: Region formerly kept a pointer to the document that contained it.
// But it was never used, and made things a little more difficult for
// serialization, so I removed the pointer. If you want to add it back, then
// be sure to modify Document::Document(SerifXML::XMLTheoryElement documentElem)
// appropriately (in particular, the new Regions created during zoning will
// need to have their document pointers adjusted when they are "stolen").
Region::Region(const Document* document, Symbol tagName, int region_no, LocatedString *content)
: _tagName(tagName), _region_no(region_no),
_is_speaker_region(false), _is_receiver_region(false), _content_flags(0x00)
{
if(content != 0) {
_content = _new LocatedString(*content);
}
else {
_content = 0;
}
}
Region::~Region() {
delete _content;
}
void Region::toLowerCase() {
if (_content != 0)
_content->toLowerCase();
}
void Region::dump(std::ostream &out, int indent) {
char *newline = OutputUtil::getNewIndentedLinebreakString(indent);
out << "(region " << _region_no << "):";
if (_content != 0) {
out << newline;
_content->dump(out, indent + 2);
}
delete[] newline;
}
void Region::updateObjectIDTable() const {
throw InternalInconsistencyException("Region::updateObjectIDTable()",
"Using unimplemented method.");
}
void Region::saveState(StateSaver *stateSaver) const {
throw InternalInconsistencyException("Region::saveState()",
"Using unimplemented method.");
}
void Region::resolvePointers(StateLoader * stateLoader) {
throw InternalInconsistencyException("Region::resolvePointers()",
"Using unimplemented method.");
}
const wchar_t* Region::XMLIdentifierPrefix() const {
return L"region";
}
void Region::saveXML(SerifXML::XMLTheoryElement regionElem, const Theory *context) const {
using namespace SerifXML;
if (context != 0)
throw InternalInconsistencyException("Region::saveXML", "Expected context to be NULL");
if (!getRegionTag().is_null()) {
regionElem.setAttribute(X_tag, getRegionTag());
}
regionElem.setAttribute(X_is_speaker, isSpeakerRegion());
regionElem.setAttribute(X_is_receiver, isReceiverRegion());
getString()->saveXML(regionElem);
// Note: we don't serialize getRegionNumber(), since it's redundant --
// in particular, the i-th region in a document will be given region
// number i.
}
Region::Region(SerifXML::XMLTheoryElement regionElem, size_t region_no)
: _region_no(static_cast<int>(region_no)), _tagName(),
_is_speaker_region(false), _is_receiver_region(false), _content(0)
{
using namespace SerifXML;
regionElem.loadId(this);
_tagName = regionElem.getAttribute<Symbol>(X_tag, Symbol());
_is_speaker_region = regionElem.getAttribute<bool>(X_is_speaker, false);
_is_receiver_region = regionElem.getAttribute<bool>(X_is_receiver, false);
_content = _new LocatedString(regionElem);
}
| 3,405 | 1,139 |
// Author: Mihai Oltean, https://mihaioltean.github.io, mihai.oltean@gmail.com
// More details: https://jenny5.org, https://jenny5-robot.github.io/
// Source code: github.com/jenny5-robot
// License: MIT
// ---------------------------------------------------------------------------
#include "lidar_controller.h"
#include "jenny5_defs.h"
t_lidar_controller LIDAR_controller;
//----------------------------------------------------------------
t_lidar_controller::t_lidar_controller(void)
{
}
//----------------------------------------------------------------
int t_lidar_controller::connect(const char* port)
{
//-------------- START INITIALIZATION ------------------------------
if (!arduino_controller.connect(port, 115200)) { // real number - 1
//sprintf(error_string, "Error attaching to Jenny 5' LIDAR!\n");
return CANNOT_CONNECT_TO_JENNY5_LIDAR_ERROR;
}
// now wait to see if I have been connected
// wait for no more than 3 seconds. If it takes more it means that something is not right, so we have to abandon it
clock_t start_time = clock();
bool LIDAR_responded = false;
while (1) {
if (!arduino_controller.update_commands_from_serial())
Sleep(5); // no new data from serial ... we make a little pause so that we don't kill the processor
if (!LIDAR_responded)
if (arduino_controller.query_for_event(IS_ALIVE_EVENT)) { // have we received the event from Serial ?
LIDAR_responded = true;
break;
}
// measure the passed time
clock_t end_time = clock();
double wait_time = (double)(end_time - start_time) / CLOCKS_PER_SEC;
// if more than 3 seconds then game over
if (wait_time > NUM_SECONDS_TO_WAIT_FOR_CONNECTION) {
if (!LIDAR_responded)
return LIDAR_does_not_respond_ERROR;
}
}
return E_OK;
}
//----------------------------------------------------------------
bool t_lidar_controller::setup(char* error_string)
{
arduino_controller.send_create_LiDAR(8, 9, 10, 12);// dir, step, enable, IR_pin
clock_t start_time = clock();
bool lidar_controller_created = false;
while (1) {
if (!arduino_controller.update_commands_from_serial())
Sleep(5); // no new data from serial ... we make a little pause so that we don't kill the processor
if (!lidar_controller_created)
if (arduino_controller.query_for_event(LIDAR_CONTROLLER_CREATED_EVENT)) // have we received the event from Serial ?
lidar_controller_created = true;
if (lidar_controller_created)
break;
// measure the passed time
clock_t end_time = clock();
double wait_time = (double)(end_time - start_time) / CLOCKS_PER_SEC;
// if more than 3 seconds then game over
if (wait_time > NUM_SECONDS_TO_WAIT_FOR_CONNECTION) {
if (!lidar_controller_created)
sprintf(error_string, "Cannot create LIDAR controller! Game over!\n");
return false;
}
}
return true;
}
//----------------------------------------------------------------
bool t_lidar_controller::update_data(void)
{
int motor_position;
intptr_t distance;
bool at_least_one_new_LIDAR_distance = false;
while (arduino_controller.query_for_event(LIDAR_READ_EVENT, &motor_position, &distance)) { // have we received the event from Serial ?
lidar_distances[motor_position] = int(distance);
at_least_one_new_LIDAR_distance = true;
}
return at_least_one_new_LIDAR_distance;
}
//----------------------------------------------------------------
void t_lidar_controller::disconnect(void)
{
arduino_controller.close_connection();
}
//----------------------------------------------------------------
bool t_lidar_controller::is_connected(void)
{
return arduino_controller.is_open();
}
//----------------------------------------------------------------
const char *t_lidar_controller::error_to_string(int error)
{
switch (error) {
case E_OK:
return "LIDAR PERFECT\n";
case CANNOT_CONNECT_TO_JENNY5_LIDAR_ERROR:
return CANNOT_CONNECT_TO_JENNY5_LIDAR_STR;
case LIDAR_does_not_respond_ERROR:
return LIDAR_does_not_respond_STR;
}
return NULL;
}
//---------------------------------------------------------------- | 4,048 | 1,417 |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <linux/input.h>
#include "common.h"
#include "device.h"
#include "screen_ui.h"
#ifdef MFLD_PRX_KEY_LAYOUT
static const char* HEADERS[] = { "Volume up/down to move highlight;",
"camera button to select.",
"",
NULL };
#else
static const char* HEADERS[] = { "Volume up/down to move highlight;",
"power button to select.",
"",
NULL };
#endif
static const char* ITEMS[] = {"reboot system now",
"apply update from ADB",
"wipe data/factory reset",
"wipe cache partition",
NULL };
class IntelUI : public ScreenRecoveryUI {
public:
virtual KeyAction CheckKey(int key) {
#ifdef MFLD_PRX_KEY_LAYOUT
if (IsKeyPressed(KEY_POWER) && key == KEY_VOLUMEUP) {
#else
if (IsKeyPressed(KEY_VOLUMEDOWN) && key == KEY_VOLUMEUP) {
#endif
return TOGGLE;
}
return ENQUEUE;
}
};
class IntelDevice : public Device {
public:
IntelDevice() :
ui(new IntelUI) {
}
RecoveryUI* GetUI() { return ui; }
int HandleMenuKey(int key, int visible) {
if (visible) {
switch (key) {
case KEY_DOWN:
case KEY_VOLUMEDOWN:
return kHighlightDown;
case KEY_UP:
case KEY_VOLUMEUP:
return kHighlightUp;
#ifdef MFLD_PRX_KEY_LAYOUT
case KEY_CAMERA:
case KEY_ENTER:
#else
case KEY_POWER:
#endif
return kInvokeItem;
}
}
return kNoAction;
}
BuiltinAction InvokeMenuItem(int menu_position) {
switch (menu_position) {
case 0: return REBOOT;
case 1: return APPLY_ADB_SIDELOAD;
case 2: return WIPE_DATA;
case 3: return WIPE_CACHE;
default: return NO_ACTION;
}
}
const char* const* GetMenuHeaders() { return HEADERS; }
const char* const* GetMenuItems() { return ITEMS; }
private:
RecoveryUI* ui;
};
Device* make_device() {
return new IntelDevice();
}
| 2,926 | 865 |
/**
* @file plrmsg.cpp
*
* Implementation of functionality for printing the ingame chat messages.
*/
#include "all.h"
static BYTE plr_msg_slot;
_plrmsg plr_msgs[PMSG_COUNT];
/** Maps from player_num to text colour, as used in chat messages. */
const char text_color_from_player_num[MAX_PLRS + 5] = { COL_WHITE, COL_WHITE, COL_WHITE, COL_WHITE, COL_GOLD, COL_RED, COL_BLUE, COL_ORANGE, COL_BEIGE };
int msgs;
int vislines;
int msgtime;
int namecolor;
BOOL donamecolor;
const char *const DevTable[] = {
"<KPhoenix>",
"<KP>",
"<KPhoenix[W]>",
"<KPhoenix[R]>",
"<KPhoenix[S]>"
};
const char *const ContributorTable[] = {
"<Tiron>",
"<Lanthanide>"
};
const char *const DonatorTable[] = {
"<MAXIMADSZINE>",
"<MAXIMADSIMUS>"
};
int DevTableSize = sizeof(DevTable) / sizeof(DevTable[0]);
int ContributorTableSize = sizeof(ContributorTable) / sizeof(ContributorTable[0]);
int DonatorTableSize = sizeof(DonatorTable) / sizeof(DonatorTable[0]);
void plrmsg_delay(BOOL delay)
{
int i;
_plrmsg *pMsg;
static DWORD plrmsg_ticks;
if (delay) {
plrmsg_ticks = -GetTickCount();
return;
}
plrmsg_ticks += GetTickCount();
pMsg = plr_msgs;
for (i = 0; i < PMSG_COUNT; i++, pMsg++)
pMsg->time += plrmsg_ticks;
}
char *ErrorPlrMsg(const char *pszMsg)
{
char *result;
_plrmsg *pMsg = &plr_msgs[plr_msg_slot];
for (msgs = PMSG_COUNT - 2; msgs > -1; msgs--) {
plr_msgs[msgs + 1] = plr_msgs[msgs];
}
plr_msg_slot = (plr_msg_slot) & (PMSG_COUNT - 1);
pMsg->player = MAX_PLRS;
pMsg->time = GetTickCount();
result = strncpy(pMsg->str, pszMsg, sizeof(pMsg->str));
pMsg->str[sizeof(pMsg->str) - 1] = '\0';
return result;
}
size_t __cdecl EventPlrMsg(const char *pszFmt, ...)
{
_plrmsg *pMsg;
va_list va;
for (msgs = PMSG_COUNT - 2; msgs > -1; msgs--) {
plr_msgs[msgs + 1] = plr_msgs[msgs];
}
va_start(va, pszFmt);
pMsg = &plr_msgs[plr_msg_slot];
plr_msg_slot = (plr_msg_slot) & (PMSG_COUNT - 1);
pMsg->player = MAX_PLRS;
pMsg->time = GetTickCount();
vsprintf(pMsg->str, pszFmt, va);
//strcpy(pMsg->name, "");
va_end(va);
return strlen(pMsg->str);
}
void SendPlrMsg(int pnum, const char *pszStr)
{
for (msgs = PMSG_COUNT - 2; msgs > -1; msgs--) {
plr_msgs[msgs + 1] = plr_msgs[msgs];
}
_plrmsg *pMsg = &plr_msgs[plr_msg_slot];
plr_msg_slot = plr_msg_slot & (PMSG_COUNT - 1);
pMsg->player = pnum;
pMsg->time = GetTickCount();
//memset(pMsg->name, 0, sizeof(pMsg->name));
sprintf(pMsg->name, "<%s>", plr[pnum]._pName);
sprintf(pMsg->str, "%s %s", pMsg->name, pszStr);
//sprintf(pMsg->str, "%s %i", pMsg->name, pMsg->time);
}
void ClearPlrMsg()
{
int i;
_plrmsg *pMsg = plr_msgs;
DWORD tick = GetTickCount();
for (i = 0; i < PMSG_COUNT; i++, pMsg++) {
if ((int)(tick - pMsg->time) > 640)
pMsg->str[0] = '\0';
}
}
void InitPlrMsg()
{
memset(plr_msgs, 0, sizeof(plr_msgs));
plr_msg_slot = 0;
}
void DrawPlrMsg()
{
int i;
DWORD x = 10 + SCREEN_X;
DWORD y = BORDER_TOP + PANEL_TOP - 73 - 4;
DWORD width = SCREEN_WIDTH - 20;
_plrmsg *pMsg;
if (chrflag || questlog || stashflag) {
if (invflag || sbookflag)
return;
x += SPANEL_WIDTH;
width -= SPANEL_WIDTH;
} else if (invflag || sbookflag)
width -= SPANEL_WIDTH;
pMsg = plr_msgs;
if (talkflag) {
vislines = PMSG_COUNT;
} else {
vislines = 3;
}
for (i = 0; i < vislines; i++) {
namecolor = MAX_PLRS;
for (int u = 0; u <= DevTableSize - 1; u++) {
if (strcmp(pMsg->name, DevTable[u]) == 0) {
namecolor = MAX_PLRS + 1;
}
}
for (int u = 0; u <= ContributorTableSize - 1; u++) {
if (strcmp(pMsg->name, ContributorTable[u]) == 0) {
namecolor = MAX_PLRS + 2;
}
}
for (int u = 0; u <= DonatorTableSize - 1; u++) {
if (strcmp(pMsg->name, DonatorTable[u]) == 0) {
namecolor = MAX_PLRS + 3;
}
}
if (talkflag && pMsg->str[0]) {
DrawTransparentBox(x, y - 15, width, 30, 0);
PrintPlrMsg(x, y, width, pMsg->str, text_color_from_player_num[pMsg->player]);
if (pMsg->player != MAX_PLRS)
PrintPlrMsg(x, y, width, pMsg->name, text_color_from_player_num[namecolor]);
} else if (GetTickCount() - pMsg->time < 15000) {
DrawTransparentBox(x, y - 15, width, 30, 0);
PrintPlrMsg(x, y, width, pMsg->str, text_color_from_player_num[pMsg->player]);
if (pMsg->player != MAX_PLRS)
PrintPlrMsg(x, y, width, pMsg->name, text_color_from_player_num[namecolor]);
}
pMsg++;
y -= 30;
}
}
void PrintPlrMsg(DWORD x, DWORD y, DWORD width, const char *str, BYTE col)
{
int line = 0;
while (*str) {
BYTE c;
int screen = PitchTbl[y] + x;
DWORD len = 0;
const char *sstr = str;
const char *endstr = sstr;
while (1) {
if (*sstr) {
c = gbFontTransTbl[(BYTE)*sstr++];
c = fontframe[c];
len += fontkern[c] + 1;
if (!c) // allow wordwrap on blank glyph
endstr = sstr;
else if (len >= width)
break;
} else {
endstr = sstr;
break;
}
}
while (str < endstr) {
c = gbFontTransTbl[(BYTE)*str++];
c = fontframe[c];
if (c)
PrintChar(screen, c, col);
screen += fontkern[c] + 1;
}
y += 10;
line++;
if (line == 3)
break;
}
}
| 5,336 | 2,601 |
30 atime=1476297919.065719166
30 ctime=1476297919.066923277
| 60 | 54 |
/**
* Copyright (c) 2018, University Osnabrück
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University Osnabrück nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL University Osnabrück BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CHANNELHANDLER_HPP
#define CHANNELHANDLER_HPP
// LVR2 includes
#include <lvr2/io/DataStruct.hpp>
#include <lvr2/geometry/Handles.hpp>
// Std lib includes
#include <iostream>
#include <array>
#include <exception>
// Boost includes
#include <boost/optional.hpp>
namespace lvr2
{
// forward declaration for ElementProxyPtr
template<typename T>
class ElementProxy;
/**
* @brief This class emulates a Pointer behaviour for an ElementProxy if its & operator is
* used. The arithmetic is based on the width of an ElementProxy. It was necessary for the
* Octree. USE WITH CARE.
*
* @tparam T the type of the underlying data array.
*/
template<typename T>
class ElementProxyPtr
{
public:
ElementProxyPtr(T* ptr = nullptr, size_t w = 0) : m_ptr(ptr), m_w(w) {}
// "Pointer" arithmetic
ElementProxyPtr operator+(const ElementProxyPtr&) = delete;
ssize_t operator-(const ElementProxyPtr& p)
{
return (this->m_ptr - p.m_ptr) / m_w;
}
ElementProxyPtr& operator++()
{
m_ptr += m_w;
return *this;
}
ElementProxyPtr operator+(size_t i)
{
ElementProxyPtr tmp(*this);
tmp += i;
return tmp;
}
ElementProxyPtr operator++(int)
{
ElementProxyPtr tmp(*this);
operator++();
return tmp;
}
ElementProxyPtr& operator+=(size_t i)
{
m_ptr += (m_w * i);
return *this;
}
ElementProxyPtr operator-=(size_t i)
{
m_ptr -= (m_w * i);
}
// comparison operators
bool operator< (const ElementProxyPtr& rhs) const { return (*this).m_ptr < rhs.m_ptr; }
bool operator> (const ElementProxyPtr& rhs) const { return rhs < (*this); }
bool operator<=(const ElementProxyPtr& rhs) const { return !((*this) > rhs); }
bool operator>=(const ElementProxyPtr& rhs) const { return !((*this) < rhs); }
bool operator==(const ElementProxyPtr& rhs) const { return (*this).m_ptr == rhs.m_ptr; }
bool operator!=(const ElementProxyPtr& rhs) const { return !(*this == rhs); }
// member access.
ElementProxy<T> operator*() { return ElementProxy<T>(m_ptr, m_w); }
// TODO [] operator ?!
// I don't think we are able to return a useful raw pointer.
// Array pointer breaks the abstraction.
// Pointer to Elementproxy is pointless because we would need to create one with new.
// We cannot overload the -> operator in ElementProxy for the same reasons.
ElementProxy<T>* operator->() = delete;
private:
T* m_ptr;
size_t m_w;
};
template<typename T>
class ElementProxy
{
public:
friend class ElementProxyPtr<T>;
/**
* @brief look at ElementProxyPtr documentation.
*
* @return
*/
ElementProxyPtr<T> operator&()
{
return ElementProxyPtr<T>(m_ptr, m_w);
}
ElementProxy operator=(const T& v)
{
if( m_ptr && (m_w == 1))
m_ptr[0] = v;
return *this;
}
template<typename BaseVecT>
ElementProxy operator=(const BaseVecT& v)
{
if( m_ptr && (m_w > 2))
{
m_ptr[0] = v.x;
m_ptr[1] = v.y;
m_ptr[2] = v.z;
}
return *this;
}
template<typename BaseVecT>
ElementProxy operator+=(const BaseVecT& v)
{
if( m_ptr && (m_w > 2))
{
m_ptr[0] += v.x;
m_ptr[1] += v.y;
m_ptr[2] += v.z;
}
return *this;
}
template<typename BaseVecT>
ElementProxy operator-=(const BaseVecT& v)
{
if( m_ptr && (m_w > 2))
{
m_ptr[0] -= v.x;
m_ptr[1] -= v.y;
m_ptr[2] -= v.z;
}
return *this;
}
template<typename BaseVecT>
BaseVecT operator+(const BaseVecT& v)
{
if(m_w > 2)
{
*this += v;
return BaseVecT(m_ptr[0], m_ptr[1], m_ptr[2]);
}
throw std::range_error("Element Proxy: Width to small for BaseVec addition");
}
template<typename BaseVecT>
BaseVecT operator-(const BaseVecT& v)
{
if(m_w > 2)
{
*this -= v;
return BaseVecT(m_ptr[0], m_ptr[1], m_ptr[2]);
}
throw std::range_error("Element Proxy: Width to small for BaseVec subtraction");
}
ElementProxy(T* pos = nullptr, unsigned w = 0) : m_ptr(pos), m_w(w) {}
T& operator[](int i)
{
if(m_ptr && (i < m_w))
{
return m_ptr[i];
}
throw std::range_error("Element Proxy: Index larger than width");
}
const T& operator[](int i) const
{
if(m_ptr && (i < m_w))
{
return m_ptr[i];
}
throw std::range_error("Element Proxy: Index out of Bounds");
}
/// User defined conversion operator
template<typename BaseVecT>
operator BaseVecT() const
{
if(m_w == 3)
{
return BaseVecT(m_ptr[0], m_ptr[1], m_ptr[2]);
}
throw std::range_error("Element Proxy: Width != 3 in BaseVecT conversion");
}
operator std::array<VertexHandle, 3>() const
{
std::array<VertexHandle, 3> arr0 = {VertexHandle(0), VertexHandle(0), VertexHandle(0)};
if(m_w == 3)
{
std::array<VertexHandle, 3> arr = {VertexHandle(m_ptr[0]), VertexHandle(m_ptr[1]), VertexHandle(m_ptr[2])};
return arr;
}
throw std::range_error("Element Proxy: Width != 3 in std::array conversion.");
}
operator EdgeHandle() const
{
if(m_w == 1)
{
return EdgeHandle(m_ptr[0]);
}
throw std::range_error("Element Proxy: Width != 1 in EdgeHandle conversion.");
}
operator FaceHandle() const
{
if(m_w == 1)
{
return FaceHandle(m_ptr[0]);
}
throw std::range_error("Element Proxy: Width != 1 in FaceHandle conversion.");
}
operator T() const
{
if(m_w == 1)
{
return m_ptr[0];
}
throw std::range_error("Element Proxy: Width != 1 in content type conversion.");
}
private:
T* m_ptr;
unsigned m_w;
};
template<typename T>
class AttributeChannel
{
public:
typedef boost::optional<AttributeChannel<T>> Optional;
using DataPtr = boost::shared_array<T>;
AttributeChannel(size_t n, unsigned width)
: m_elementWidth(width), m_numElements(n),
m_data(new T[m_numElements * width])
{}
AttributeChannel(size_t n, unsigned width, DataPtr ptr)
: m_numElements(n),
m_elementWidth(width),
m_data(ptr)
{}
ElementProxy<T> operator[](const unsigned& idx)
{
T* ptr = m_data.get();
return ElementProxy<T>(&(ptr[idx * m_elementWidth]), m_elementWidth);
}
DataPtr dataPtr() const { return m_data;}
unsigned width() const { return m_elementWidth;}
size_t numElements() const { return m_numElements;}
private:
size_t m_numElements;
unsigned m_elementWidth;
DataPtr m_data;
};
// Some type aliases
using FloatChannel = AttributeChannel<float>;
using UCharChannel = AttributeChannel<unsigned char>;
using IndexChannel = AttributeChannel<unsigned int>;
using FloatChannelOptional = boost::optional<FloatChannel>;
using UCharChannelOptional= boost::optional<UCharChannel>;
using IndexChannelOptional = boost::optional<IndexChannel>;
using FloatProxy = ElementProxy<float>;
using UCharProxy = ElementProxy<unsigned char>;
using IndexProxy = ElementProxy<unsigned int>;
using FloatChannelPtr = std::shared_ptr<FloatChannel>;
using UCharChannelPtr = std::shared_ptr<UCharChannel>;
using IndexChannelPtr = std::shared_ptr<IndexChannel>;
using intOptional = boost::optional<int>;
using floatOptional = boost::optional<float>;
using ucharOptional = boost::optional<unsigned char>;
class ChannelManager
{
public:
ChannelManager() {}
bool removeIndexChannel(const std::string& name)
{
return m_indexChannels.erase(name) > 0;
}
bool removeFloatChannel(const std::string& name)
{
return m_floatChannels.erase(name) > 0;
}
bool removeUCharChannel(const std::string& name)
{
return m_ucharChannels.erase(name) > 0;
}
void addIndexChannel(
indexArray array,
std::string name,
size_t n,
unsigned width);
void addFloatChannel(
floatArr array,
std::string name,
size_t n,
unsigned width);
void addUCharChannel(
ucharArr array,
std::string name,
size_t n,
unsigned width);
void addEmptyFloatChannel(
std::string name,
size_t n,
unsigned width);
void addEmptyUCharChannel(
std::string name,
size_t n,
unsigned width);
void addEmptyIndexChannel(
std::string name,
size_t n,
unsigned width);
void addChannel(indexArray array, std::string name, size_t n, unsigned width)
{ addIndexChannel(array, name, n, width);}
void addChannel(floatArr array, std::string name, size_t n, unsigned width)
{ addFloatChannel(array, name, n, width);}
void addChannel(ucharArr array, std::string name, size_t n, unsigned width)
{ addUCharChannel(array, name, n, width);}
void getChannel(std::string name, FloatChannelOptional& channelOptional )
{ channelOptional = getFloatChannel(name);}
void getChannel(std::string name, IndexChannelOptional& channelOptional)
{ channelOptional = getIndexChannel(name);}
void getChannel(std::string name, UCharChannelOptional& channelOptional)
{ channelOptional = getUCharChannel(name);}
bool hasUCharChannel(std::string name);
bool hasFloatChannel(std::string name);
bool hasIndexChannel(std::string name);
unsigned ucharChannelWidth(std::string name);
unsigned floatChannelWidth(std::string name);
unsigned indexChannelWidth(std::string name);
FloatProxy getFloatHandle(int idx, const std::string& name);
UCharProxy getUCharHandle(int idx, const std::string& name);
IndexProxy getIndexHandle(int idx, const std::string& name);
FloatProxy operator[](size_t idx);
floatArr getFloatArray(size_t& n, unsigned& w, const std::string name);
ucharArr getUCharArray(size_t& n, unsigned& w, const std::string name);
indexArray getIndexArray(size_t& n, unsigned& w, const std::string name);
FloatChannelOptional getFloatChannel(std::string name);
UCharChannelOptional getUCharChannel(std::string name);
IndexChannelOptional getIndexChannel(std::string name);
floatOptional getFloatAtomic(std::string name);
ucharOptional getUCharAtomic(std::string name);
intOptional getIntAtomic(std::string name);
void addFloatChannel(FloatChannelPtr data, std::string name);
void addUCharChannel(UCharChannelPtr data, std::string name);
void addIndexChannel(IndexChannelPtr data, std::string name);
void addFloatAtomic(float data, std::string name);
void addUCharAtomic(unsigned char data, std::string name);
void addIntAtomic(int data, std::string name);
private:
std::map<std::string, FloatChannelPtr> m_floatChannels;
std::map<std::string, UCharChannelPtr> m_ucharChannels;
std::map<std::string, IndexChannelPtr> m_indexChannels;
std::map<std::string, float> m_floatAtomics;
std::map<std::string, unsigned char> m_ucharAtomics;
std::map<std::string, int> m_intAtomics;
using FloatChannelMap = std::map<std::string, FloatChannelPtr>;
using UCharChannelMap = std::map<std::string, UCharChannelPtr>;
using IndexChannelMap = std::map<std::string, IndexChannelPtr>;
};
} // namespace lvr2
#endif // CHANNELHANDLER_HPP
| 13,547 | 4,265 |
//==============================================================================
///
/// File: DeviceGraphicsDX11Shader.cpp
///
/// Copyright (C) 2000-2013 by Smells Like Donkey, Inc. All rights reserved.
///
/// This file is subject to the terms and conditions defined in
/// file 'LICENSE.txt', which is part of this source code package.
///
//==============================================================================
#include "DeviceGraphicsDX11Shader.hpp"
#include "DeviceGraphicsDX11Renderer.hpp"
#include "DeviceGraphicsDX11VertexShader.hpp"
#include "DeviceGraphicsDX11PixelShader.hpp"
#include "MoreMath.hpp"
#include "DeviceGlobalsManager.hpp"
#include "System.hpp"
#include "DeviceConsole.hpp"
#include "Factory.hpp"
#include "FilePath.hpp"
#include "ShaderResource.hpp"
#include "TextFileStream.hpp"
#include "DeviceFileManager.hpp"
#include "CheckedCast.hpp"
#include "StringCast.hpp"
#include "FragmentShaderResource.hpp"
#include "VertexShaderResource.hpp"
#include "GeometryShaderResource.hpp"
//==============================================================================
//==============================================================================
namespace DT2 {
//==============================================================================
/// Register with object factory
//==============================================================================
IMPLEMENT_FACTORY_CREATION(DeviceGraphicsDX11Shader)
//==============================================================================
/// Standard class constructors/destructors
//==============================================================================
DeviceGraphicsDX11Shader::DeviceGraphicsDX11Shader (void)
: _layout (NULL),
_pixel_shader (NULL),
_vertex_shader (NULL)
{
for (DTuint i = 0; i < ARRAY_SIZE(_constants); ++i) {
_constants[i] = NULL;
}
}
DeviceGraphicsDX11Shader::~DeviceGraphicsDX11Shader (void)
{
clear();
RELEASE(_pixel_shader);
RELEASE(_vertex_shader);
}
//==============================================================================
//==============================================================================
void DeviceGraphicsDX11Shader::clear(void)
{
SAFE_RELEASE(_layout);
for (DTuint i = 0; i < ARRAY_SIZE(_constants); ++i) {
SAFE_RELEASE(_constants[i]);
}
for (DTuint i = 0; i < _parameters.size(); ++i) {
SAFE_RELEASE(_parameters[i]);
}
_parameters.clear();
}
//==============================================================================
//==============================================================================
#define ADD_DESC(A,F) \
if (program->hasAttrib(A)) { \
String attrib_name = program->getAttribName(A); \
String index = attrib_name.endDigits(); \
name_buffer[desc_index] = attrib_name.trimEndDigits(); \
desc[desc_index].SemanticName = name_buffer[desc_index].cStr(); \
desc[desc_index].SemanticIndex = index.size() ? castFromString<DTint>(index) : 0; \
desc[desc_index].Format = F; \
desc[desc_index].InputSlot = A; \
desc[desc_index].AlignedByteOffset = 0; \
desc[desc_index].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; \
desc[desc_index].InstanceDataStepRate = 0; \
++desc_index; \
}
#define ADD_CONSTANT(A,S) \
if (!program->getUniformName(A).empty()) { \
String constant_name = program->getUniformName(A); \
DTint ps_resource_index = program->getFragmentShader() ? program->getFragmentShader()->getShaderResourceIndex (constant_name) : -1; \
DTint vs_resource_index = program->getVertexShader() ? program->getVertexShader()->getShaderResourceIndex (constant_name) : -1; \
\
D3D11_BUFFER_DESC desc; \
desc.ByteWidth = S; \
desc.MiscFlags = 0; \
desc.StructureByteStride = 0; \
desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; \
desc.Usage = D3D11_USAGE_DYNAMIC; \
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; \
\
HRESULT hr = device->CreateBuffer(&desc, NULL, &_constants[A]); \
Assert(SUCCEEDED(hr)); \
\
if (vs_resource_index >= 0) _vs_constants[vs_resource_index] = _constants[A]; \
if (ps_resource_index >= 0) _ps_constants[ps_resource_index] = _constants[A]; \
}
void DeviceGraphicsDX11Shader::syncToResource (ShaderResource *program)
{
if (program->getRecacheData()) {
DeviceGraphicsDX11Renderer *renderer = checkedCast<DeviceGraphicsDX11Renderer*>(System::getRenderer());
ID3D11Device1 *device = renderer->getD3D11Device();
ID3D11DeviceContext1 *context = renderer->getD3D11Context();
SAFE_ASSIGN(_pixel_shader, checkedCast<DeviceGraphicsDX11Renderer*>(System::getRenderer())->getPixelShaderCached(program->getFragmentShader()));
SAFE_ASSIGN(_vertex_shader, checkedCast<DeviceGraphicsDX11Renderer*>(System::getRenderer())->getVertexShaderCached(program->getVertexShader()));
if (!_pixel_shader || !_vertex_shader) { // Geometry shader is optional
program->setRecacheData(false);
return;
}
// Clear previous resources
clear();
HRESULT hr;
//
// Build a layout (Input element description)
//
D3D11_INPUT_ELEMENT_DESC desc[D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT];
String name_buffer[D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT];
::memset(desc,0,sizeof(desc));
DTuint desc_index = 0;
ADD_DESC(ShaderResource::ATTRIB_POSITION, DXGI_FORMAT_R32G32B32_FLOAT);
ADD_DESC(ShaderResource::ATTRIB_COLOR, DXGI_FORMAT_R8G8B8A8_UNORM);
ADD_DESC(ShaderResource::ATTRIB_NORMAL, DXGI_FORMAT_R32G32B32_FLOAT);
ADD_DESC(ShaderResource::ATTRIB_TEXCOORD0, DXGI_FORMAT_R32G32_FLOAT);
ADD_DESC(ShaderResource::ATTRIB_TEXCOORD1, DXGI_FORMAT_R32G32_FLOAT);
ADD_DESC(ShaderResource::ATTRIB_TEXCOORD2, DXGI_FORMAT_R32G32_FLOAT);
ADD_DESC(ShaderResource::ATTRIB_TEXCOORD3, DXGI_FORMAT_R32G32_FLOAT);
ADD_DESC(ShaderResource::ATTRIB_WEIGHTS_INDEX, DXGI_FORMAT_R16G16B16A16_UINT);
ADD_DESC(ShaderResource::ATTRIB_WEIGHTS_STRENGTH, DXGI_FORMAT_R32G32B32A32_FLOAT);
const String *bytecode = program->getVertexShader()->getShader("HLSL");
hr = device->CreateInputLayout(desc,desc_index,&(*bytecode)[0],bytecode->size(),&_layout);
Assert(SUCCEEDED(hr));
//
// Constants (Uniforms)
//
::memset(_constants,0,sizeof(_constants));
::memset(_vs_constants,0,sizeof(_vs_constants));
::memset(_ps_constants,0,sizeof(_ps_constants));
ADD_CONSTANT(ShaderResource::UNIFORM_COLOR, sizeof(float) * 4);
ADD_CONSTANT(ShaderResource::UNIFORM_TEXTURE0, sizeof(float) * 16);
ADD_CONSTANT(ShaderResource::UNIFORM_TEXTURE1, sizeof(float) * 16);
ADD_CONSTANT(ShaderResource::UNIFORM_MODELVIEW, sizeof(float) * 16);
ADD_CONSTANT(ShaderResource::UNIFORM_PROJECTION, sizeof(float) * 16);
ADD_CONSTANT(ShaderResource::UNIFORM_CAMERA, sizeof(float) * 16);
//ADD_CONSTANT(ShaderResource::UNIFORM_SKELETON,???);
const Array<ShaderResource::Parameter> ¶meters = program->getParameters();
_parameters.resize(parameters.size());
for (DTuint i = 0; i < parameters.size(); ++i) {
String constant_name = parameters[i].name;
DTint ps_resource_index = program->getFragmentShader() ? program->getFragmentShader()->getShaderResourceIndex (constant_name) : -1;
DTint vs_resource_index = program->getVertexShader() ? program->getVertexShader()->getShaderResourceIndex (constant_name) : -1;
D3D11_BUFFER_DESC desc;
desc.ByteWidth = parameters[i].data.size();
desc.MiscFlags = 0;
desc.StructureByteStride = 0;
desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
HRESULT hr = device->CreateBuffer(&desc, NULL, &_parameters[i]);
Assert(SUCCEEDED(hr));
if (vs_resource_index >= 0) _vs_constants[vs_resource_index] = _parameters[i];
if (ps_resource_index >= 0) _ps_constants[ps_resource_index] = _parameters[i];
}
program->setRecacheData(false);
}
// recache all of our parameters
if (program->getRecacheParameters()) {
DeviceGraphicsDX11Renderer *renderer = checkedCast<DeviceGraphicsDX11Renderer*>(System::getRenderer());
ID3D11DeviceContext1 *context = renderer->getD3D11Context();
// Get Parameters. This creates a mapping from our internal index to an opengl uniform location
const Array<ShaderResource::Parameter> ¶meters = program->getParameters();
for (DTuint i = 0; i < parameters.size(); ++i) {
const ShaderResource::Parameter &p = parameters[i];
context->UpdateSubresource(_parameters[i], 0, NULL, ¶meters[0].data[0], parameters[i].data.size(), parameters[i].data.size());
}
program->setRecacheParameters(false);
}
}
//==============================================================================
//==============================================================================
void DeviceGraphicsDX11Shader::setConstantValue (ID3D11Buffer *buffer, DTubyte *data, DTuint size)
{
if (!buffer)
return;
DeviceGraphicsDX11Renderer *renderer = checkedCast<DeviceGraphicsDX11Renderer*>(System::getRenderer());
ID3D11DeviceContext1 *context = renderer->getD3D11Context();
D3D11_MAPPED_SUBRESOURCE res;
HRESULT hr = context->Map(buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &res);
::memcpy(res.pData,data,size);
context->Unmap(buffer, 0);
}
//==============================================================================
//==============================================================================
} // DT2
| 11,113 | 3,442 |
#include <vector>
#include <algorithm>
using namespace std;
#include "longestArithmeticSubsequence.h"
/////////// For Testing ///////////////////////////////////////////////////////
#include <time.h>
#include <cassert>
#include <string>
#include <iostream>
#include "../common/iostreamhelper.h"
void testLongestArithmeticSubsequence() {
//return; //TODO: if you want to test, make this line a comment.
cout << "--- Longest Arithmetic Subsequence -----------------------" << endl;
{
auto las1 = buildLongestArithmeticSubsequenceK(5, 2);
auto las1Len = lenghtOfLongestArithmeticSubsequence(las1);
cout << las1 << ", " << las1Len << endl;
assert(las1Len == 2);
auto las2 = buildLongestArithmeticSubsequenceK(5, 3);
auto las2Len = lenghtOfLongestArithmeticSubsequence(las2);
cout << las2 << ", " << las2Len << endl;
assert(las2Len == 3);
auto las3 = buildLongestArithmeticSubsequenceK(8, 2);
auto las3Len = lenghtOfLongestArithmeticSubsequence(las3);
cout << las3 << ", " << las3Len << endl;
assert(las3Len == 2);
}
cout << "OK!" << endl;
}
| 1,162 | 361 |
// Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/builtins/builtins-utils-gen.h"
#include "src/builtins/builtins.h"
#include "src/code-stub-assembler.h"
namespace v8 {
namespace internal {
// ES section #sec-reflect.has
TF_BUILTIN(ReflectHas, CodeStubAssembler) {
Node* target = Parameter(Descriptor::kTarget);
Node* key = Parameter(Descriptor::kKey);
Node* context = Parameter(Descriptor::kContext);
ThrowIfNotJSReceiver(context, target, MessageTemplate::kCalledOnNonObject,
"Reflect.has");
Return(CallBuiltin(Builtins::kHasProperty, context, key, target));
}
} // namespace internal
} // namespace v8
| 775 | 254 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/animation/timing_input.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/bindings/core/v8/unrestricted_double_or_keyframe_animation_options.h"
#include "third_party/blink/renderer/bindings/core/v8/unrestricted_double_or_keyframe_effect_options.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_keyframe_animation_options.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_keyframe_effect_options.h"
#include "third_party/blink/renderer/core/animation/animation_test_helper.h"
#include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
#include "v8/include/v8.h"
namespace blink {
class AnimationTimingInputTest : public testing::Test {
public:
Timing ApplyTimingInputNumber(v8::Isolate*,
String timing_property,
double timing_property_value,
bool& timing_conversion_success,
bool is_keyframeeffectoptions = true);
Timing ApplyTimingInputString(v8::Isolate*,
String timing_property,
String timing_property_value,
bool& timing_conversion_success,
bool is_keyframeeffectoptions = true);
private:
void SetUp() override { page_holder_ = std::make_unique<DummyPageHolder>(); }
Document* GetDocument() const { return &page_holder_->GetDocument(); }
std::unique_ptr<DummyPageHolder> page_holder_;
};
Timing AnimationTimingInputTest::ApplyTimingInputNumber(
v8::Isolate* isolate,
String timing_property,
double timing_property_value,
bool& timing_conversion_success,
bool is_keyframeeffectoptions) {
v8::Local<v8::Object> timing_input = v8::Object::New(isolate);
SetV8ObjectPropertyAsNumber(isolate, timing_input, timing_property,
timing_property_value);
DummyExceptionStateForTesting exception_state;
Timing result;
if (is_keyframeeffectoptions) {
KeyframeEffectOptions* timing_input_dictionary =
NativeValueTraits<KeyframeEffectOptions>::NativeValue(
isolate, timing_input, exception_state);
UnrestrictedDoubleOrKeyframeEffectOptions timing_input =
UnrestrictedDoubleOrKeyframeEffectOptions::FromKeyframeEffectOptions(
timing_input_dictionary);
result = TimingInput::Convert(timing_input, GetDocument(), exception_state);
} else {
KeyframeAnimationOptions* timing_input_dictionary =
NativeValueTraits<KeyframeAnimationOptions>::NativeValue(
isolate, timing_input, exception_state);
UnrestrictedDoubleOrKeyframeAnimationOptions timing_input =
UnrestrictedDoubleOrKeyframeAnimationOptions::
FromKeyframeAnimationOptions(timing_input_dictionary);
result = TimingInput::Convert(timing_input, GetDocument(), exception_state);
}
timing_conversion_success = !exception_state.HadException();
return result;
}
Timing AnimationTimingInputTest::ApplyTimingInputString(
v8::Isolate* isolate,
String timing_property,
String timing_property_value,
bool& timing_conversion_success,
bool is_keyframeeffectoptions) {
v8::Local<v8::Object> timing_input = v8::Object::New(isolate);
SetV8ObjectPropertyAsString(isolate, timing_input, timing_property,
timing_property_value);
DummyExceptionStateForTesting exception_state;
Timing result;
if (is_keyframeeffectoptions) {
KeyframeEffectOptions* timing_input_dictionary =
NativeValueTraits<KeyframeEffectOptions>::NativeValue(
isolate, timing_input, exception_state);
UnrestrictedDoubleOrKeyframeEffectOptions timing_input =
UnrestrictedDoubleOrKeyframeEffectOptions::FromKeyframeEffectOptions(
timing_input_dictionary);
result = TimingInput::Convert(timing_input, GetDocument(), exception_state);
} else {
KeyframeAnimationOptions* timing_input_dictionary =
NativeValueTraits<KeyframeAnimationOptions>::NativeValue(
isolate, timing_input, exception_state);
UnrestrictedDoubleOrKeyframeAnimationOptions timing_input =
UnrestrictedDoubleOrKeyframeAnimationOptions::
FromKeyframeAnimationOptions(timing_input_dictionary);
result = TimingInput::Convert(timing_input, GetDocument(), exception_state);
}
timing_conversion_success = !exception_state.HadException();
return result;
}
TEST_F(AnimationTimingInputTest, TimingInputStartDelay) {
V8TestingScope scope;
bool ignored_success;
EXPECT_EQ(1.1, ApplyTimingInputNumber(scope.GetIsolate(), "delay", 1100,
ignored_success)
.start_delay);
EXPECT_EQ(-1, ApplyTimingInputNumber(scope.GetIsolate(), "delay", -1000,
ignored_success)
.start_delay);
EXPECT_EQ(1, ApplyTimingInputString(scope.GetIsolate(), "delay", "1000",
ignored_success)
.start_delay);
EXPECT_EQ(0, ApplyTimingInputString(scope.GetIsolate(), "delay", "1s",
ignored_success)
.start_delay);
EXPECT_EQ(0, ApplyTimingInputString(scope.GetIsolate(), "delay", "Infinity",
ignored_success)
.start_delay);
EXPECT_EQ(0, ApplyTimingInputString(scope.GetIsolate(), "delay", "-Infinity",
ignored_success)
.start_delay);
EXPECT_EQ(0, ApplyTimingInputString(scope.GetIsolate(), "delay", "NaN",
ignored_success)
.start_delay);
EXPECT_EQ(0, ApplyTimingInputString(scope.GetIsolate(), "delay", "rubbish",
ignored_success)
.start_delay);
}
TEST_F(AnimationTimingInputTest,
TimingInputStartDelayKeyframeAnimationOptions) {
V8TestingScope scope;
bool ignored_success;
EXPECT_EQ(1.1, ApplyTimingInputNumber(scope.GetIsolate(), "delay", 1100,
ignored_success, false)
.start_delay);
EXPECT_EQ(-1, ApplyTimingInputNumber(scope.GetIsolate(), "delay", -1000,
ignored_success, false)
.start_delay);
EXPECT_EQ(1, ApplyTimingInputString(scope.GetIsolate(), "delay", "1000",
ignored_success, false)
.start_delay);
EXPECT_EQ(0, ApplyTimingInputString(scope.GetIsolate(), "delay", "1s",
ignored_success, false)
.start_delay);
EXPECT_EQ(0, ApplyTimingInputString(scope.GetIsolate(), "delay", "Infinity",
ignored_success, false)
.start_delay);
EXPECT_EQ(0, ApplyTimingInputString(scope.GetIsolate(), "delay", "-Infinity",
ignored_success, false)
.start_delay);
EXPECT_EQ(0, ApplyTimingInputString(scope.GetIsolate(), "delay", "NaN",
ignored_success, false)
.start_delay);
EXPECT_EQ(0, ApplyTimingInputString(scope.GetIsolate(), "delay", "rubbish",
ignored_success, false)
.start_delay);
}
TEST_F(AnimationTimingInputTest, TimingInputEndDelay) {
V8TestingScope scope;
bool ignored_success;
EXPECT_EQ(10, ApplyTimingInputNumber(scope.GetIsolate(), "endDelay", 10000,
ignored_success)
.end_delay);
EXPECT_EQ(-2.5, ApplyTimingInputNumber(scope.GetIsolate(), "endDelay", -2500,
ignored_success)
.end_delay);
}
TEST_F(AnimationTimingInputTest, TimingInputFillMode) {
V8TestingScope scope;
Timing::FillMode default_fill_mode = Timing::FillMode::AUTO;
bool ignored_success;
EXPECT_EQ(Timing::FillMode::AUTO,
ApplyTimingInputString(scope.GetIsolate(), "fill", "auto",
ignored_success)
.fill_mode);
EXPECT_EQ(Timing::FillMode::FORWARDS,
ApplyTimingInputString(scope.GetIsolate(), "fill", "forwards",
ignored_success)
.fill_mode);
EXPECT_EQ(Timing::FillMode::NONE,
ApplyTimingInputString(scope.GetIsolate(), "fill", "none",
ignored_success)
.fill_mode);
EXPECT_EQ(Timing::FillMode::BACKWARDS,
ApplyTimingInputString(scope.GetIsolate(), "fill", "backwards",
ignored_success)
.fill_mode);
EXPECT_EQ(Timing::FillMode::BOTH,
ApplyTimingInputString(scope.GetIsolate(), "fill", "both",
ignored_success)
.fill_mode);
EXPECT_EQ(default_fill_mode,
ApplyTimingInputString(scope.GetIsolate(), "fill", "everything!",
ignored_success)
.fill_mode);
EXPECT_EQ(default_fill_mode,
ApplyTimingInputString(scope.GetIsolate(), "fill",
"backwardsandforwards", ignored_success)
.fill_mode);
EXPECT_EQ(
default_fill_mode,
ApplyTimingInputNumber(scope.GetIsolate(), "fill", 2, ignored_success)
.fill_mode);
}
TEST_F(AnimationTimingInputTest, TimingInputIterationStart) {
V8TestingScope scope;
bool success;
EXPECT_EQ(1.1, ApplyTimingInputNumber(scope.GetIsolate(), "iterationStart",
1.1, success)
.iteration_start);
EXPECT_TRUE(success);
ApplyTimingInputNumber(scope.GetIsolate(), "iterationStart", -1, success);
EXPECT_FALSE(success);
ApplyTimingInputString(scope.GetIsolate(), "iterationStart", "Infinity",
success);
EXPECT_FALSE(success);
ApplyTimingInputString(scope.GetIsolate(), "iterationStart", "-Infinity",
success);
EXPECT_FALSE(success);
ApplyTimingInputString(scope.GetIsolate(), "iterationStart", "NaN", success);
EXPECT_FALSE(success);
ApplyTimingInputString(scope.GetIsolate(), "iterationStart", "rubbish",
success);
EXPECT_FALSE(success);
}
TEST_F(AnimationTimingInputTest, TimingInputIterationCount) {
V8TestingScope scope;
bool success;
EXPECT_EQ(2.1, ApplyTimingInputNumber(scope.GetIsolate(), "iterations", 2.1,
success)
.iteration_count);
EXPECT_TRUE(success);
Timing timing = ApplyTimingInputString(scope.GetIsolate(), "iterations",
"Infinity", success);
EXPECT_TRUE(success);
EXPECT_TRUE(std::isinf(timing.iteration_count));
EXPECT_GT(timing.iteration_count, 0);
ApplyTimingInputNumber(scope.GetIsolate(), "iterations", -1, success);
EXPECT_FALSE(success);
ApplyTimingInputString(scope.GetIsolate(), "iterations", "-Infinity",
success);
EXPECT_FALSE(success);
ApplyTimingInputString(scope.GetIsolate(), "iterations", "NaN", success);
EXPECT_FALSE(success);
ApplyTimingInputString(scope.GetIsolate(), "iterations", "rubbish", success);
EXPECT_FALSE(success);
}
TEST_F(AnimationTimingInputTest, TimingInputIterationDuration) {
V8TestingScope scope;
bool success;
EXPECT_EQ(
AnimationTimeDelta::FromSecondsD(1.1),
ApplyTimingInputNumber(scope.GetIsolate(), "duration", 1100, success)
.iteration_duration);
EXPECT_TRUE(success);
Timing timing =
ApplyTimingInputNumber(scope.GetIsolate(), "duration",
std::numeric_limits<double>::infinity(), success);
EXPECT_TRUE(success);
EXPECT_TRUE(timing.iteration_duration->is_max());
EXPECT_FALSE(
ApplyTimingInputString(scope.GetIsolate(), "duration", "auto", success)
.iteration_duration);
EXPECT_TRUE(success);
ApplyTimingInputString(scope.GetIsolate(), "duration", "1000", success);
EXPECT_FALSE(success);
ApplyTimingInputNumber(scope.GetIsolate(), "duration", -1000, success);
EXPECT_FALSE(success);
ApplyTimingInputString(scope.GetIsolate(), "duration", "-Infinity", success);
EXPECT_FALSE(success);
ApplyTimingInputString(scope.GetIsolate(), "duration", "NaN", success);
EXPECT_FALSE(success);
ApplyTimingInputString(scope.GetIsolate(), "duration", "rubbish", success);
EXPECT_FALSE(success);
}
TEST_F(AnimationTimingInputTest, TimingInputDirection) {
V8TestingScope scope;
Timing::PlaybackDirection default_playback_direction =
Timing::PlaybackDirection::NORMAL;
bool ignored_success;
EXPECT_EQ(Timing::PlaybackDirection::NORMAL,
ApplyTimingInputString(scope.GetIsolate(), "direction", "normal",
ignored_success)
.direction);
EXPECT_EQ(Timing::PlaybackDirection::REVERSE,
ApplyTimingInputString(scope.GetIsolate(), "direction", "reverse",
ignored_success)
.direction);
EXPECT_EQ(Timing::PlaybackDirection::ALTERNATE_NORMAL,
ApplyTimingInputString(scope.GetIsolate(), "direction", "alternate",
ignored_success)
.direction);
EXPECT_EQ(Timing::PlaybackDirection::ALTERNATE_REVERSE,
ApplyTimingInputString(scope.GetIsolate(), "direction",
"alternate-reverse", ignored_success)
.direction);
EXPECT_EQ(default_playback_direction,
ApplyTimingInputString(scope.GetIsolate(), "direction", "rubbish",
ignored_success)
.direction);
EXPECT_EQ(default_playback_direction,
ApplyTimingInputNumber(scope.GetIsolate(), "direction", 2,
ignored_success)
.direction);
}
TEST_F(AnimationTimingInputTest, TimingInputTimingFunction) {
V8TestingScope scope;
const scoped_refptr<TimingFunction> default_timing_function =
LinearTimingFunction::Shared();
bool success;
EXPECT_EQ(
*CubicBezierTimingFunction::Preset(
CubicBezierTimingFunction::EaseType::EASE),
*ApplyTimingInputString(scope.GetIsolate(), "easing", "ease", success)
.timing_function);
EXPECT_TRUE(success);
EXPECT_EQ(
*CubicBezierTimingFunction::Preset(
CubicBezierTimingFunction::EaseType::EASE_IN),
*ApplyTimingInputString(scope.GetIsolate(), "easing", "ease-in", success)
.timing_function);
EXPECT_TRUE(success);
EXPECT_EQ(
*CubicBezierTimingFunction::Preset(
CubicBezierTimingFunction::EaseType::EASE_OUT),
*ApplyTimingInputString(scope.GetIsolate(), "easing", "ease-out", success)
.timing_function);
EXPECT_TRUE(success);
EXPECT_EQ(*CubicBezierTimingFunction::Preset(
CubicBezierTimingFunction::EaseType::EASE_IN_OUT),
*ApplyTimingInputString(scope.GetIsolate(), "easing", "ease-in-out",
success)
.timing_function);
EXPECT_TRUE(success);
EXPECT_EQ(
*LinearTimingFunction::Shared(),
*ApplyTimingInputString(scope.GetIsolate(), "easing", "linear", success)
.timing_function);
EXPECT_TRUE(success);
EXPECT_EQ(
*StepsTimingFunction::Preset(StepsTimingFunction::StepPosition::START),
*ApplyTimingInputString(scope.GetIsolate(), "easing", "step-start",
success)
.timing_function);
EXPECT_TRUE(success);
EXPECT_EQ(
*StepsTimingFunction::Preset(StepsTimingFunction::StepPosition::END),
*ApplyTimingInputString(scope.GetIsolate(), "easing", "step-end", success)
.timing_function);
EXPECT_TRUE(success);
EXPECT_EQ(*CubicBezierTimingFunction::Create(1, 1, 0.3, 0.3),
*ApplyTimingInputString(scope.GetIsolate(), "easing",
"cubic-bezier(1, 1, 0.3, 0.3)", success)
.timing_function);
EXPECT_TRUE(success);
EXPECT_EQ(
*StepsTimingFunction::Create(3, StepsTimingFunction::StepPosition::START),
*ApplyTimingInputString(scope.GetIsolate(), "easing", "steps(3, start)",
success)
.timing_function);
EXPECT_TRUE(success);
EXPECT_EQ(
*StepsTimingFunction::Create(5, StepsTimingFunction::StepPosition::END),
*ApplyTimingInputString(scope.GetIsolate(), "easing", "steps(5, end)",
success)
.timing_function);
EXPECT_TRUE(success);
ApplyTimingInputString(scope.GetIsolate(), "easing", "", success);
EXPECT_FALSE(success);
ApplyTimingInputString(scope.GetIsolate(), "easing", "steps(5.6, end)",
success);
EXPECT_FALSE(success);
ApplyTimingInputString(scope.GetIsolate(), "easing",
"cubic-bezier(2, 2, 0.3, 0.3)", success);
EXPECT_FALSE(success);
ApplyTimingInputString(scope.GetIsolate(), "easing", "rubbish", success);
EXPECT_FALSE(success);
ApplyTimingInputNumber(scope.GetIsolate(), "easing", 2, success);
EXPECT_FALSE(success);
ApplyTimingInputString(scope.GetIsolate(), "easing", "initial", success);
EXPECT_FALSE(success);
}
TEST_F(AnimationTimingInputTest, TimingInputEmpty) {
DummyExceptionStateForTesting exception_state;
Timing control_timing;
UnrestrictedDoubleOrKeyframeEffectOptions timing_input =
UnrestrictedDoubleOrKeyframeEffectOptions::FromKeyframeEffectOptions(
KeyframeEffectOptions::Create());
Timing updated_timing =
TimingInput::Convert(timing_input, nullptr, exception_state);
EXPECT_FALSE(exception_state.HadException());
EXPECT_EQ(control_timing.start_delay, updated_timing.start_delay);
EXPECT_EQ(control_timing.fill_mode, updated_timing.fill_mode);
EXPECT_EQ(control_timing.iteration_start, updated_timing.iteration_start);
EXPECT_EQ(control_timing.iteration_count, updated_timing.iteration_count);
EXPECT_FALSE(updated_timing.iteration_duration);
EXPECT_EQ(control_timing.direction, updated_timing.direction);
EXPECT_EQ(*control_timing.timing_function, *updated_timing.timing_function);
}
TEST_F(AnimationTimingInputTest, TimingInputEmptyKeyframeAnimationOptions) {
DummyExceptionStateForTesting exception_state;
Timing control_timing;
UnrestrictedDoubleOrKeyframeAnimationOptions input_timing =
UnrestrictedDoubleOrKeyframeAnimationOptions::
FromKeyframeAnimationOptions(KeyframeAnimationOptions::Create());
Timing updated_timing =
TimingInput::Convert(input_timing, nullptr, exception_state);
EXPECT_FALSE(exception_state.HadException());
EXPECT_EQ(control_timing.start_delay, updated_timing.start_delay);
EXPECT_EQ(control_timing.fill_mode, updated_timing.fill_mode);
EXPECT_EQ(control_timing.iteration_start, updated_timing.iteration_start);
EXPECT_EQ(control_timing.iteration_count, updated_timing.iteration_count);
EXPECT_FALSE(updated_timing.iteration_duration);
EXPECT_EQ(control_timing.direction, updated_timing.direction);
EXPECT_EQ(*control_timing.timing_function, *updated_timing.timing_function);
}
} // namespace blink
| 19,705 | 6,111 |
#include<iostream>
using namespace std;
int main(){
// Floyd's Pattern
int n;
cin>>n;
int count = 0;
for(int i=1; i<=n; i++){
for(int j=1; j<=i; j++){
cout<<count+1<<" ";
count = count + 1;
}
cout<<endl;
}
return 0;
} | 294 | 112 |
/*
* Copyright (c) 2011 Motorola Mobility, 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 Motorola Mobility, Inc. nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebKitSettings.h"
#include "WebKitEnumTypes.h"
#include "WebKitSettingsPrivate.h"
#include "WebPageProxy.h"
#include "WebPreferences.h"
#include <WebCore/UserAgent.h>
#include <glib/gi18n-lib.h>
#include <wtf/glib/WTFGType.h>
#include <wtf/text/CString.h>
#if PLATFORM(GTK)
#include "HardwareAccelerationManager.h"
#endif
#if PLATFORM(WAYLAND)
#include <WebCore/PlatformDisplay.h>
#endif
using namespace WebKit;
struct _WebKitSettingsPrivate {
_WebKitSettingsPrivate()
: preferences(WebPreferences::create(String(), "WebKit2.", "WebKit2."))
{
defaultFontFamily = preferences->standardFontFamily().utf8();
monospaceFontFamily = preferences->fixedFontFamily().utf8();
serifFontFamily = preferences->serifFontFamily().utf8();
sansSerifFontFamily = preferences->sansSerifFontFamily().utf8();
cursiveFontFamily = preferences->cursiveFontFamily().utf8();
fantasyFontFamily = preferences->fantasyFontFamily().utf8();
pictographFontFamily = preferences->pictographFontFamily().utf8();
defaultCharset = preferences->defaultTextEncodingName().utf8();
}
RefPtr<WebPreferences> preferences;
CString defaultFontFamily;
CString monospaceFontFamily;
CString serifFontFamily;
CString sansSerifFontFamily;
CString cursiveFontFamily;
CString fantasyFontFamily;
CString pictographFontFamily;
CString defaultCharset;
CString userAgent;
bool allowModalDialogs { false };
bool zoomTextOnly { false };
};
/**
* SECTION:WebKitSettings
* @short_description: Control the behaviour of a #WebKitWebView
*
* #WebKitSettings can be applied to a #WebKitWebView to control text charset,
* color, font sizes, printing mode, script support, loading of images and various
* other things on a #WebKitWebView. After creation, a #WebKitSettings object
* contains default settings.
*
* <informalexample><programlisting>
* /<!-- -->* Disable JavaScript. *<!-- -->/
* WebKitSettings *settings = webkit_web_view_group_get_settings (my_view_group);
* webkit_settings_set_enable_javascript (settings, FALSE);
*
* </programlisting></informalexample>
*/
WEBKIT_DEFINE_TYPE(WebKitSettings, webkit_settings, G_TYPE_OBJECT)
enum {
PROP_0,
PROP_ENABLE_JAVASCRIPT,
PROP_AUTO_LOAD_IMAGES,
PROP_LOAD_ICONS_IGNORING_IMAGE_LOAD_SETTING,
PROP_ENABLE_OFFLINE_WEB_APPLICATION_CACHE,
PROP_ENABLE_HTML5_LOCAL_STORAGE,
PROP_ENABLE_HTML5_DATABASE,
PROP_ENABLE_XSS_AUDITOR,
PROP_ENABLE_FRAME_FLATTENING,
PROP_ENABLE_PLUGINS,
PROP_ENABLE_JAVA,
PROP_JAVASCRIPT_CAN_OPEN_WINDOWS_AUTOMATICALLY,
PROP_ENABLE_HYPERLINK_AUDITING,
PROP_DEFAULT_FONT_FAMILY,
PROP_MONOSPACE_FONT_FAMILY,
PROP_SERIF_FONT_FAMILY,
PROP_SANS_SERIF_FONT_FAMILY,
PROP_CURSIVE_FONT_FAMILY,
PROP_FANTASY_FONT_FAMILY,
PROP_PICTOGRAPH_FONT_FAMILY,
PROP_DEFAULT_FONT_SIZE,
PROP_DEFAULT_MONOSPACE_FONT_SIZE,
PROP_MINIMUM_FONT_SIZE,
PROP_DEFAULT_CHARSET,
PROP_ENABLE_PRIVATE_BROWSING,
PROP_ENABLE_DEVELOPER_EXTRAS,
PROP_ENABLE_RESIZABLE_TEXT_AREAS,
PROP_ENABLE_TABS_TO_LINKS,
PROP_ENABLE_DNS_PREFETCHING,
PROP_ENABLE_CARET_BROWSING,
PROP_ENABLE_FULLSCREEN,
PROP_PRINT_BACKGROUNDS,
PROP_ENABLE_WEBAUDIO,
PROP_ENABLE_WEBGL,
PROP_ALLOW_MODAL_DIALOGS,
PROP_ZOOM_TEXT_ONLY,
PROP_JAVASCRIPT_CAN_ACCESS_CLIPBOARD,
PROP_MEDIA_PLAYBACK_REQUIRES_USER_GESTURE,
PROP_MEDIA_PLAYBACK_ALLOWS_INLINE,
PROP_DRAW_COMPOSITING_INDICATORS,
PROP_ENABLE_SITE_SPECIFIC_QUIRKS,
PROP_ENABLE_PAGE_CACHE,
PROP_USER_AGENT,
PROP_ENABLE_SMOOTH_SCROLLING,
PROP_ENABLE_ACCELERATED_2D_CANVAS,
PROP_ENABLE_WRITE_CONSOLE_MESSAGES_TO_STDOUT,
PROP_ENABLE_MEDIA_STREAM,
PROP_ENABLE_SPATIAL_NAVIGATION,
PROP_ENABLE_MEDIASOURCE,
PROP_ALLOW_FILE_ACCESS_FROM_FILE_URLS,
PROP_ALLOW_UNIVERSAL_ACCESS_FROM_FILE_URLS,
#if PLATFORM(GTK)
PROP_HARDWARE_ACCELERATION_POLICY,
#endif
};
static void webKitSettingsConstructed(GObject* object)
{
G_OBJECT_CLASS(webkit_settings_parent_class)->constructed(object);
WebPreferences* prefs = WEBKIT_SETTINGS(object)->priv->preferences.get();
prefs->setShouldRespectImageOrientation(true);
}
static void webKitSettingsSetProperty(GObject* object, guint propId, const GValue* value, GParamSpec* paramSpec)
{
WebKitSettings* settings = WEBKIT_SETTINGS(object);
switch (propId) {
case PROP_ENABLE_JAVASCRIPT:
webkit_settings_set_enable_javascript(settings, g_value_get_boolean(value));
break;
case PROP_AUTO_LOAD_IMAGES:
webkit_settings_set_auto_load_images(settings, g_value_get_boolean(value));
break;
case PROP_LOAD_ICONS_IGNORING_IMAGE_LOAD_SETTING:
webkit_settings_set_load_icons_ignoring_image_load_setting(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_OFFLINE_WEB_APPLICATION_CACHE:
webkit_settings_set_enable_offline_web_application_cache(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_HTML5_LOCAL_STORAGE:
webkit_settings_set_enable_html5_local_storage(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_HTML5_DATABASE:
webkit_settings_set_enable_html5_database(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_XSS_AUDITOR:
webkit_settings_set_enable_xss_auditor(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_FRAME_FLATTENING:
webkit_settings_set_enable_frame_flattening(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_PLUGINS:
webkit_settings_set_enable_plugins(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_JAVA:
webkit_settings_set_enable_java(settings, g_value_get_boolean(value));
break;
case PROP_JAVASCRIPT_CAN_OPEN_WINDOWS_AUTOMATICALLY:
webkit_settings_set_javascript_can_open_windows_automatically(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_HYPERLINK_AUDITING:
webkit_settings_set_enable_hyperlink_auditing(settings, g_value_get_boolean(value));
break;
case PROP_DEFAULT_FONT_FAMILY:
webkit_settings_set_default_font_family(settings, g_value_get_string(value));
break;
case PROP_MONOSPACE_FONT_FAMILY:
webkit_settings_set_monospace_font_family(settings, g_value_get_string(value));
break;
case PROP_SERIF_FONT_FAMILY:
webkit_settings_set_serif_font_family(settings, g_value_get_string(value));
break;
case PROP_SANS_SERIF_FONT_FAMILY:
webkit_settings_set_sans_serif_font_family(settings, g_value_get_string(value));
break;
case PROP_CURSIVE_FONT_FAMILY:
webkit_settings_set_cursive_font_family(settings, g_value_get_string(value));
break;
case PROP_FANTASY_FONT_FAMILY:
webkit_settings_set_fantasy_font_family(settings, g_value_get_string(value));
break;
case PROP_PICTOGRAPH_FONT_FAMILY:
webkit_settings_set_pictograph_font_family(settings, g_value_get_string(value));
break;
case PROP_DEFAULT_FONT_SIZE:
webkit_settings_set_default_font_size(settings, g_value_get_uint(value));
break;
case PROP_DEFAULT_MONOSPACE_FONT_SIZE:
webkit_settings_set_default_monospace_font_size(settings, g_value_get_uint(value));
break;
case PROP_MINIMUM_FONT_SIZE:
webkit_settings_set_minimum_font_size(settings, g_value_get_uint(value));
break;
case PROP_DEFAULT_CHARSET:
webkit_settings_set_default_charset(settings, g_value_get_string(value));
break;
case PROP_ENABLE_PRIVATE_BROWSING:
G_GNUC_BEGIN_IGNORE_DEPRECATIONS;
webkit_settings_set_enable_private_browsing(settings, g_value_get_boolean(value));
G_GNUC_END_IGNORE_DEPRECATIONS;
break;
case PROP_ENABLE_DEVELOPER_EXTRAS:
webkit_settings_set_enable_developer_extras(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_RESIZABLE_TEXT_AREAS:
webkit_settings_set_enable_resizable_text_areas(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_TABS_TO_LINKS:
webkit_settings_set_enable_tabs_to_links(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_DNS_PREFETCHING:
webkit_settings_set_enable_dns_prefetching(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_CARET_BROWSING:
webkit_settings_set_enable_caret_browsing(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_FULLSCREEN:
webkit_settings_set_enable_fullscreen(settings, g_value_get_boolean(value));
break;
case PROP_PRINT_BACKGROUNDS:
webkit_settings_set_print_backgrounds(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_WEBAUDIO:
webkit_settings_set_enable_webaudio(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_WEBGL:
webkit_settings_set_enable_webgl(settings, g_value_get_boolean(value));
break;
case PROP_ALLOW_MODAL_DIALOGS:
webkit_settings_set_allow_modal_dialogs(settings, g_value_get_boolean(value));
break;
case PROP_ZOOM_TEXT_ONLY:
webkit_settings_set_zoom_text_only(settings, g_value_get_boolean(value));
break;
case PROP_JAVASCRIPT_CAN_ACCESS_CLIPBOARD:
webkit_settings_set_javascript_can_access_clipboard(settings, g_value_get_boolean(value));
break;
case PROP_MEDIA_PLAYBACK_REQUIRES_USER_GESTURE:
webkit_settings_set_media_playback_requires_user_gesture(settings, g_value_get_boolean(value));
break;
case PROP_MEDIA_PLAYBACK_ALLOWS_INLINE:
webkit_settings_set_media_playback_allows_inline(settings, g_value_get_boolean(value));
break;
case PROP_DRAW_COMPOSITING_INDICATORS:
if (g_value_get_boolean(value))
webkit_settings_set_draw_compositing_indicators(settings, g_value_get_boolean(value));
else {
char* debugVisualsEnvironment = getenv("WEBKIT_SHOW_COMPOSITING_DEBUG_VISUALS");
bool showDebugVisuals = debugVisualsEnvironment && !strcmp(debugVisualsEnvironment, "1");
webkit_settings_set_draw_compositing_indicators(settings, showDebugVisuals);
}
break;
case PROP_ENABLE_SITE_SPECIFIC_QUIRKS:
webkit_settings_set_enable_site_specific_quirks(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_PAGE_CACHE:
webkit_settings_set_enable_page_cache(settings, g_value_get_boolean(value));
break;
case PROP_USER_AGENT:
webkit_settings_set_user_agent(settings, g_value_get_string(value));
break;
case PROP_ENABLE_SMOOTH_SCROLLING:
webkit_settings_set_enable_smooth_scrolling(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_ACCELERATED_2D_CANVAS:
webkit_settings_set_enable_accelerated_2d_canvas(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_WRITE_CONSOLE_MESSAGES_TO_STDOUT:
webkit_settings_set_enable_write_console_messages_to_stdout(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_MEDIA_STREAM:
webkit_settings_set_enable_media_stream(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_SPATIAL_NAVIGATION:
webkit_settings_set_enable_spatial_navigation(settings, g_value_get_boolean(value));
break;
case PROP_ENABLE_MEDIASOURCE:
webkit_settings_set_enable_mediasource(settings, g_value_get_boolean(value));
break;
case PROP_ALLOW_FILE_ACCESS_FROM_FILE_URLS:
webkit_settings_set_allow_file_access_from_file_urls(settings, g_value_get_boolean(value));
break;
case PROP_ALLOW_UNIVERSAL_ACCESS_FROM_FILE_URLS:
webkit_settings_set_allow_universal_access_from_file_urls(settings, g_value_get_boolean(value));
break;
#if PLATFORM(GTK)
case PROP_HARDWARE_ACCELERATION_POLICY:
webkit_settings_set_hardware_acceleration_policy(settings, static_cast<WebKitHardwareAccelerationPolicy>(g_value_get_enum(value)));
break;
#endif
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec);
break;
}
}
static void webKitSettingsGetProperty(GObject* object, guint propId, GValue* value, GParamSpec* paramSpec)
{
WebKitSettings* settings = WEBKIT_SETTINGS(object);
switch (propId) {
case PROP_ENABLE_JAVASCRIPT:
g_value_set_boolean(value, webkit_settings_get_enable_javascript(settings));
break;
case PROP_AUTO_LOAD_IMAGES:
g_value_set_boolean(value, webkit_settings_get_auto_load_images(settings));
break;
case PROP_LOAD_ICONS_IGNORING_IMAGE_LOAD_SETTING:
g_value_set_boolean(value, webkit_settings_get_load_icons_ignoring_image_load_setting(settings));
break;
case PROP_ENABLE_OFFLINE_WEB_APPLICATION_CACHE:
g_value_set_boolean(value, webkit_settings_get_enable_offline_web_application_cache(settings));
break;
case PROP_ENABLE_HTML5_LOCAL_STORAGE:
g_value_set_boolean(value, webkit_settings_get_enable_html5_local_storage(settings));
break;
case PROP_ENABLE_HTML5_DATABASE:
g_value_set_boolean(value, webkit_settings_get_enable_html5_database(settings));
break;
case PROP_ENABLE_XSS_AUDITOR:
g_value_set_boolean(value, webkit_settings_get_enable_xss_auditor(settings));
break;
case PROP_ENABLE_FRAME_FLATTENING:
g_value_set_boolean(value, webkit_settings_get_enable_frame_flattening(settings));
break;
case PROP_ENABLE_PLUGINS:
g_value_set_boolean(value, webkit_settings_get_enable_plugins(settings));
break;
case PROP_ENABLE_JAVA:
g_value_set_boolean(value, webkit_settings_get_enable_java(settings));
break;
case PROP_JAVASCRIPT_CAN_OPEN_WINDOWS_AUTOMATICALLY:
g_value_set_boolean(value, webkit_settings_get_javascript_can_open_windows_automatically(settings));
break;
case PROP_ENABLE_HYPERLINK_AUDITING:
g_value_set_boolean(value, webkit_settings_get_enable_hyperlink_auditing(settings));
break;
case PROP_DEFAULT_FONT_FAMILY:
g_value_set_string(value, webkit_settings_get_default_font_family(settings));
break;
case PROP_MONOSPACE_FONT_FAMILY:
g_value_set_string(value, webkit_settings_get_monospace_font_family(settings));
break;
case PROP_SERIF_FONT_FAMILY:
g_value_set_string(value, webkit_settings_get_serif_font_family(settings));
break;
case PROP_SANS_SERIF_FONT_FAMILY:
g_value_set_string(value, webkit_settings_get_sans_serif_font_family(settings));
break;
case PROP_CURSIVE_FONT_FAMILY:
g_value_set_string(value, webkit_settings_get_cursive_font_family(settings));
break;
case PROP_FANTASY_FONT_FAMILY:
g_value_set_string(value, webkit_settings_get_fantasy_font_family(settings));
break;
case PROP_PICTOGRAPH_FONT_FAMILY:
g_value_set_string(value, webkit_settings_get_pictograph_font_family(settings));
break;
case PROP_DEFAULT_FONT_SIZE:
g_value_set_uint(value, webkit_settings_get_default_font_size(settings));
break;
case PROP_DEFAULT_MONOSPACE_FONT_SIZE:
g_value_set_uint(value, webkit_settings_get_default_monospace_font_size(settings));
break;
case PROP_MINIMUM_FONT_SIZE:
g_value_set_uint(value, webkit_settings_get_minimum_font_size(settings));
break;
case PROP_DEFAULT_CHARSET:
g_value_set_string(value, webkit_settings_get_default_charset(settings));
break;
case PROP_ENABLE_PRIVATE_BROWSING:
G_GNUC_BEGIN_IGNORE_DEPRECATIONS;
g_value_set_boolean(value, webkit_settings_get_enable_private_browsing(settings));
G_GNUC_END_IGNORE_DEPRECATIONS;
break;
case PROP_ENABLE_DEVELOPER_EXTRAS:
g_value_set_boolean(value, webkit_settings_get_enable_developer_extras(settings));
break;
case PROP_ENABLE_RESIZABLE_TEXT_AREAS:
g_value_set_boolean(value, webkit_settings_get_enable_resizable_text_areas(settings));
break;
case PROP_ENABLE_TABS_TO_LINKS:
g_value_set_boolean(value, webkit_settings_get_enable_tabs_to_links(settings));
break;
case PROP_ENABLE_DNS_PREFETCHING:
g_value_set_boolean(value, webkit_settings_get_enable_dns_prefetching(settings));
break;
case PROP_ENABLE_CARET_BROWSING:
g_value_set_boolean(value, webkit_settings_get_enable_caret_browsing(settings));
break;
case PROP_ENABLE_FULLSCREEN:
g_value_set_boolean(value, webkit_settings_get_enable_fullscreen(settings));
break;
case PROP_PRINT_BACKGROUNDS:
g_value_set_boolean(value, webkit_settings_get_print_backgrounds(settings));
break;
case PROP_ENABLE_WEBAUDIO:
g_value_set_boolean(value, webkit_settings_get_enable_webaudio(settings));
break;
case PROP_ENABLE_WEBGL:
g_value_set_boolean(value, webkit_settings_get_enable_webgl(settings));
break;
case PROP_ALLOW_MODAL_DIALOGS:
g_value_set_boolean(value, webkit_settings_get_allow_modal_dialogs(settings));
break;
case PROP_ZOOM_TEXT_ONLY:
g_value_set_boolean(value, webkit_settings_get_zoom_text_only(settings));
break;
case PROP_JAVASCRIPT_CAN_ACCESS_CLIPBOARD:
g_value_set_boolean(value, webkit_settings_get_javascript_can_access_clipboard(settings));
break;
case PROP_MEDIA_PLAYBACK_REQUIRES_USER_GESTURE:
g_value_set_boolean(value, webkit_settings_get_media_playback_requires_user_gesture(settings));
break;
case PROP_MEDIA_PLAYBACK_ALLOWS_INLINE:
g_value_set_boolean(value, webkit_settings_get_media_playback_allows_inline(settings));
break;
case PROP_DRAW_COMPOSITING_INDICATORS:
g_value_set_boolean(value, webkit_settings_get_draw_compositing_indicators(settings));
break;
case PROP_ENABLE_SITE_SPECIFIC_QUIRKS:
g_value_set_boolean(value, webkit_settings_get_enable_site_specific_quirks(settings));
break;
case PROP_ENABLE_PAGE_CACHE:
g_value_set_boolean(value, webkit_settings_get_enable_page_cache(settings));
break;
case PROP_USER_AGENT:
g_value_set_string(value, webkit_settings_get_user_agent(settings));
break;
case PROP_ENABLE_SMOOTH_SCROLLING:
g_value_set_boolean(value, webkit_settings_get_enable_smooth_scrolling(settings));
break;
case PROP_ENABLE_ACCELERATED_2D_CANVAS:
g_value_set_boolean(value, webkit_settings_get_enable_accelerated_2d_canvas(settings));
break;
case PROP_ENABLE_WRITE_CONSOLE_MESSAGES_TO_STDOUT:
g_value_set_boolean(value, webkit_settings_get_enable_write_console_messages_to_stdout(settings));
break;
case PROP_ENABLE_MEDIA_STREAM:
g_value_set_boolean(value, webkit_settings_get_enable_media_stream(settings));
break;
case PROP_ENABLE_SPATIAL_NAVIGATION:
g_value_set_boolean(value, webkit_settings_get_enable_spatial_navigation(settings));
break;
case PROP_ENABLE_MEDIASOURCE:
g_value_set_boolean(value, webkit_settings_get_enable_mediasource(settings));
break;
case PROP_ALLOW_FILE_ACCESS_FROM_FILE_URLS:
g_value_set_boolean(value, webkit_settings_get_allow_file_access_from_file_urls(settings));
break;
case PROP_ALLOW_UNIVERSAL_ACCESS_FROM_FILE_URLS:
g_value_set_boolean(value, webkit_settings_get_allow_universal_access_from_file_urls(settings));
break;
#if PLATFORM(GTK)
case PROP_HARDWARE_ACCELERATION_POLICY:
g_value_set_enum(value, webkit_settings_get_hardware_acceleration_policy(settings));
break;
#endif
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propId, paramSpec);
break;
}
}
static void webkit_settings_class_init(WebKitSettingsClass* klass)
{
GObjectClass* gObjectClass = G_OBJECT_CLASS(klass);
gObjectClass->constructed = webKitSettingsConstructed;
gObjectClass->set_property = webKitSettingsSetProperty;
gObjectClass->get_property = webKitSettingsGetProperty;
GParamFlags readWriteConstructParamFlags = static_cast<GParamFlags>(WEBKIT_PARAM_READWRITE | G_PARAM_CONSTRUCT);
/**
* WebKitSettings:enable-javascript:
*
* Determines whether or not JavaScript executes within a page.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_JAVASCRIPT,
g_param_spec_boolean("enable-javascript",
_("Enable JavaScript"),
_("Enable JavaScript."),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:auto-load-images:
*
* Determines whether images should be automatically loaded or not.
* On devices where network bandwidth is of concern, it might be
* useful to turn this property off.
*/
g_object_class_install_property(gObjectClass,
PROP_AUTO_LOAD_IMAGES,
g_param_spec_boolean("auto-load-images",
_("Auto load images"),
_("Load images automatically."),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:load-icons-ignoring-image-load-setting:
*
* Determines whether a site can load favicons irrespective
* of the value of #WebKitSettings:auto-load-images.
*/
g_object_class_install_property(gObjectClass,
PROP_LOAD_ICONS_IGNORING_IMAGE_LOAD_SETTING,
g_param_spec_boolean("load-icons-ignoring-image-load-setting",
_("Load icons ignoring image load setting"),
_("Whether to load site icons ignoring image load setting."),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-offline-web-application-cache:
*
* Whether to enable HTML5 offline web application cache support. Offline
* web application cache allows web applications to run even when
* the user is not connected to the network.
*
* HTML5 offline web application specification is available at
* http://dev.w3.org/html5/spec/offline.html.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_OFFLINE_WEB_APPLICATION_CACHE,
g_param_spec_boolean("enable-offline-web-application-cache",
_("Enable offline web application cache"),
_("Whether to enable offline web application cache."),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-html5-local-storage:
*
* Whether to enable HTML5 local storage support. Local storage provides
* simple synchronous storage access.
*
* HTML5 local storage specification is available at
* http://dev.w3.org/html5/webstorage/.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_HTML5_LOCAL_STORAGE,
g_param_spec_boolean("enable-html5-local-storage",
_("Enable HTML5 local storage"),
_("Whether to enable HTML5 Local Storage support."),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-html5-database:
*
* Whether to enable HTML5 client-side SQL database support. Client-side
* SQL database allows web pages to store structured data and be able to
* use SQL to manipulate that data asynchronously.
*
* HTML5 database specification is available at
* http://www.w3.org/TR/webdatabase/.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_HTML5_DATABASE,
g_param_spec_boolean("enable-html5-database",
_("Enable HTML5 database"),
_("Whether to enable HTML5 database support."),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-xss-auditor:
*
* Whether to enable the XSS auditor. This feature filters some kinds of
* reflective XSS attacks on vulnerable web sites.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_XSS_AUDITOR,
g_param_spec_boolean("enable-xss-auditor",
_("Enable XSS auditor"),
_("Whether to enable the XSS auditor."),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-frame-flattening:
*
* Whether to enable the frame flattening. With this setting each subframe is expanded
* to its contents, which will flatten all the frames to become one scrollable page.
* On touch devices scrollable subframes on a page can result in a confusing user experience.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_FRAME_FLATTENING,
g_param_spec_boolean("enable-frame-flattening",
_("Enable frame flattening"),
_("Whether to enable frame flattening."),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-plugins:
*
* Determines whether or not plugins on the page are enabled.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_PLUGINS,
g_param_spec_boolean("enable-plugins",
_("Enable plugins"),
_("Enable embedded plugin objects."),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-java:
*
* Determines whether or not Java is enabled on the page.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_JAVA,
g_param_spec_boolean("enable-java",
_("Enable Java"),
_("Whether Java support should be enabled."),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:javascript-can-open-windows-automatically:
*
* Whether JavaScript can open popup windows automatically without user
* intervention.
*/
g_object_class_install_property(gObjectClass,
PROP_JAVASCRIPT_CAN_OPEN_WINDOWS_AUTOMATICALLY,
g_param_spec_boolean("javascript-can-open-windows-automatically",
_("JavaScript can open windows automatically"),
_("Whether JavaScript can open windows automatically."),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-hyperlink-auditing:
*
* Determines whether or not hyperlink auditing is enabled.
*
* The hyperlink auditing specification is available at
* http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#hyperlink-auditing.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_HYPERLINK_AUDITING,
g_param_spec_boolean("enable-hyperlink-auditing",
_("Enable hyperlink auditing"),
_("Whether <a ping> should be able to send pings."),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:default-font-family:
*
* The font family to use as the default for content that does not specify a font.
*/
g_object_class_install_property(gObjectClass,
PROP_DEFAULT_FONT_FAMILY,
g_param_spec_string("default-font-family",
_("Default font family"),
_("The font family to use as the default for content that does not specify a font."),
"sans-serif",
readWriteConstructParamFlags));
/**
* WebKitSettings:monospace-font-family:
*
* The font family used as the default for content using a monospace font.
*
*/
g_object_class_install_property(gObjectClass,
PROP_MONOSPACE_FONT_FAMILY,
g_param_spec_string("monospace-font-family",
_("Monospace font family"),
_("The font family used as the default for content using monospace font."),
"monospace",
readWriteConstructParamFlags));
/**
* WebKitSettings:serif-font-family:
*
* The font family used as the default for content using a serif font.
*/
g_object_class_install_property(gObjectClass,
PROP_SERIF_FONT_FAMILY,
g_param_spec_string("serif-font-family",
_("Serif font family"),
_("The font family used as the default for content using serif font."),
"serif",
readWriteConstructParamFlags));
/**
* WebKitSettings:sans-serif-font-family:
*
* The font family used as the default for content using a sans-serif font.
*/
g_object_class_install_property(gObjectClass,
PROP_SANS_SERIF_FONT_FAMILY,
g_param_spec_string("sans-serif-font-family",
_("Sans-serif font family"),
_("The font family used as the default for content using sans-serif font."),
"sans-serif",
readWriteConstructParamFlags));
/**
* WebKitSettings:cursive-font-family:
*
* The font family used as the default for content using a cursive font.
*/
g_object_class_install_property(gObjectClass,
PROP_CURSIVE_FONT_FAMILY,
g_param_spec_string("cursive-font-family",
_("Cursive font family"),
_("The font family used as the default for content using cursive font."),
"serif",
readWriteConstructParamFlags));
/**
* WebKitSettings:fantasy-font-family:
*
* The font family used as the default for content using a fantasy font.
*/
g_object_class_install_property(gObjectClass,
PROP_FANTASY_FONT_FAMILY,
g_param_spec_string("fantasy-font-family",
_("Fantasy font family"),
_("The font family used as the default for content using fantasy font."),
"serif",
readWriteConstructParamFlags));
/**
* WebKitSettings:pictograph-font-family:
*
* The font family used as the default for content using a pictograph font.
*/
g_object_class_install_property(gObjectClass,
PROP_PICTOGRAPH_FONT_FAMILY,
g_param_spec_string("pictograph-font-family",
_("Pictograph font family"),
_("The font family used as the default for content using pictograph font."),
"serif",
readWriteConstructParamFlags));
/**
* WebKitSettings:default-font-size:
*
* The default font size in pixels to use for content displayed if
* no font size is specified.
*/
g_object_class_install_property(gObjectClass,
PROP_DEFAULT_FONT_SIZE,
g_param_spec_uint("default-font-size",
_("Default font size"),
_("The default font size used to display text."),
0, G_MAXUINT, 16,
readWriteConstructParamFlags));
/**
* WebKitSettings:default-monospace-font-size:
*
* The default font size in pixels to use for content displayed in
* monospace font if no font size is specified.
*/
g_object_class_install_property(gObjectClass,
PROP_DEFAULT_MONOSPACE_FONT_SIZE,
g_param_spec_uint("default-monospace-font-size",
_("Default monospace font size"),
_("The default font size used to display monospace text."),
0, G_MAXUINT, 13,
readWriteConstructParamFlags));
/**
* WebKitSettings:minimum-font-size:
*
* The minimum font size in points used to display text. This setting
* controls the absolute smallest size. Values other than 0 can
* potentially break page layouts.
*/
g_object_class_install_property(gObjectClass,
PROP_MINIMUM_FONT_SIZE,
g_param_spec_uint("minimum-font-size",
_("Minimum font size"),
_("The minimum font size used to display text."),
0, G_MAXUINT, 0,
readWriteConstructParamFlags));
/**
* WebKitSettings:default-charset:
*
* The default text charset used when interpreting content with an unspecified charset.
*/
g_object_class_install_property(gObjectClass,
PROP_DEFAULT_CHARSET,
g_param_spec_string("default-charset",
_("Default charset"),
_("The default text charset used when interpreting content with unspecified charset."),
"iso-8859-1",
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-private-browsing:
*
* Determines whether or not private browsing is enabled. Private browsing
* will disable history, cache and form auto-fill for any pages visited.
*
* Deprecated: 2.16. Use #WebKitWebView:is-ephemeral or #WebKitWebsiteDataManager:is-ephemeral instead.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_PRIVATE_BROWSING,
g_param_spec_boolean("enable-private-browsing",
_("Enable private browsing"),
_("Whether to enable private browsing"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-developer-extras:
*
* Determines whether or not developer tools, such as the Web Inspector, are enabled.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_DEVELOPER_EXTRAS,
g_param_spec_boolean("enable-developer-extras",
_("Enable developer extras"),
_("Whether to enable developer extras"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-resizable-text-areas:
*
* Determines whether or not text areas can be resized.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_RESIZABLE_TEXT_AREAS,
g_param_spec_boolean("enable-resizable-text-areas",
_("Enable resizable text areas"),
_("Whether to enable resizable text areas"),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-tabs-to-links:
*
* Determines whether the tab key cycles through the elements on the page.
* When this setting is enabled, users will be able to focus the next element
* in the page by pressing the tab key. If the selected element is editable,
* then pressing tab key will insert the tab character.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_TABS_TO_LINKS,
g_param_spec_boolean("enable-tabs-to-links",
_("Enable tabs to links"),
_("Whether to enable tabs to links"),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-dns-prefetching:
*
* Determines whether or not to prefetch domain names. DNS prefetching attempts
* to resolve domain names before a user tries to follow a link.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_DNS_PREFETCHING,
g_param_spec_boolean("enable-dns-prefetching",
_("Enable DNS prefetching"),
_("Whether to enable DNS prefetching"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-caret-browsing:
*
* Whether to enable accessibility enhanced keyboard navigation.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_CARET_BROWSING,
g_param_spec_boolean("enable-caret-browsing",
_("Enable Caret Browsing"),
_("Whether to enable accessibility enhanced keyboard navigation"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-fullscreen:
*
* Whether to enable the Javascript Fullscreen API. The API
* allows any HTML element to request fullscreen display. See also
* the current draft of the spec:
* http://www.w3.org/TR/fullscreen/
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_FULLSCREEN,
g_param_spec_boolean("enable-fullscreen",
_("Enable Fullscreen"),
_("Whether to enable the Javascript Fullscreen API"),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:print-backgrounds:
*
* Whether background images should be drawn during printing.
*/
g_object_class_install_property(gObjectClass,
PROP_PRINT_BACKGROUNDS,
g_param_spec_boolean("print-backgrounds",
_("Print Backgrounds"),
_("Whether background images should be drawn during printing"),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-webaudio:
*
*
* Enable or disable support for WebAudio on pages. WebAudio is an
* experimental proposal for allowing web pages to generate Audio
* WAVE data from JavaScript. The standard is currently a
* work-in-progress by the W3C Audio Working Group.
*
* See also https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_WEBAUDIO,
g_param_spec_boolean("enable-webaudio",
_("Enable WebAudio"),
_("Whether WebAudio content should be handled"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-webgl:
*
* Enable or disable support for WebGL on pages. WebGL is an experimental
* proposal for allowing web pages to use OpenGL ES-like calls directly. The
* standard is currently a work-in-progress by the Khronos Group.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_WEBGL,
g_param_spec_boolean("enable-webgl",
_("Enable WebGL"),
_("Whether WebGL content should be rendered"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:allow-modal-dialogs:
*
* Determine whether it's allowed to create and run modal dialogs
* from a #WebKitWebView through JavaScript with
* <function>window.showModalDialog</function>. If it's set to
* %FALSE, the associated #WebKitWebView won't be able to create
* new modal dialogs, so not even the #WebKitWebView::create
* signal will be emitted.
*/
g_object_class_install_property(gObjectClass,
PROP_ALLOW_MODAL_DIALOGS,
g_param_spec_boolean("allow-modal-dialogs",
_("Allow modal dialogs"),
_("Whether it is possible to create modal dialogs"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:zoom-text-only:
*
* Whether #WebKitWebView:zoom-level affects only the
* text of the page or all the contents. Other contents containing text
* like form controls will be also affected by zoom factor when
* this property is enabled.
*/
g_object_class_install_property(gObjectClass,
PROP_ZOOM_TEXT_ONLY,
g_param_spec_boolean("zoom-text-only",
_("Zoom Text Only"),
_("Whether zoom level of web view changes only the text size"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:javascript-can-access-clipboard:
*
* Whether JavaScript can access the clipboard. The default value is %FALSE. If
* set to %TRUE, document.execCommand() allows cut, copy and paste commands.
*
*/
g_object_class_install_property(gObjectClass,
PROP_JAVASCRIPT_CAN_ACCESS_CLIPBOARD,
g_param_spec_boolean("javascript-can-access-clipboard",
_("JavaScript can access clipboard"),
_("Whether JavaScript can access Clipboard"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:media-playback-requires-user-gesture:
*
* Whether a user gesture (such as clicking the play button)
* would be required to start media playback or load media. This is off
* by default, so media playback could start automatically.
* Setting it on requires a gesture by the user to start playback, or to
* load the media.
*/
g_object_class_install_property(gObjectClass,
PROP_MEDIA_PLAYBACK_REQUIRES_USER_GESTURE,
g_param_spec_boolean("media-playback-requires-user-gesture",
_("Media playback requires user gesture"),
_("Whether media playback requires user gesture"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:media-playback-allows-inline:
*
* Whether media playback is full-screen only or inline playback is allowed.
* This is %TRUE by default, so media playback can be inline. Setting it to
* %FALSE allows specifying that media playback should be always fullscreen.
*/
g_object_class_install_property(gObjectClass,
PROP_MEDIA_PLAYBACK_ALLOWS_INLINE,
g_param_spec_boolean("media-playback-allows-inline",
_("Media playback allows inline"),
_("Whether media playback allows inline"),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:draw-compositing-indicators:
*
* Whether to draw compositing borders and repaint counters on layers drawn
* with accelerated compositing. This is useful for debugging issues related
* to web content that is composited with the GPU.
*/
g_object_class_install_property(gObjectClass,
PROP_DRAW_COMPOSITING_INDICATORS,
g_param_spec_boolean("draw-compositing-indicators",
_("Draw compositing indicators"),
_("Whether to draw compositing borders and repaint counters"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-site-specific-quirks:
*
* Whether to turn on site-specific quirks. Turning this on will
* tell WebKit to use some site-specific workarounds for
* better web compatibility. For example, older versions of
* MediaWiki will incorrectly send to WebKit a CSS file with KHTML
* workarounds. By turning on site-specific quirks, WebKit will
* special-case this and other cases to make some specific sites work.
*/
g_object_class_install_property(
gObjectClass,
PROP_ENABLE_SITE_SPECIFIC_QUIRKS,
g_param_spec_boolean(
"enable-site-specific-quirks",
_("Enable Site Specific Quirks"),
_("Enables the site-specific compatibility workarounds"),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-page-cache:
*
* Enable or disable the page cache. Disabling the page cache is
* generally only useful for special circumstances like low-memory
* scenarios or special purpose applications like static HTML
* viewers. This setting only controls the Page Cache, this cache
* is different than the disk-based or memory-based traditional
* resource caches, its point is to make going back and forth
* between pages much faster. For details about the different types
* of caches and their purposes see:
* http://webkit.org/blog/427/webkit-page-cache-i-the-basics/
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_PAGE_CACHE,
g_param_spec_boolean("enable-page-cache",
_("Enable page cache"),
_("Whether the page cache should be used"),
TRUE,
readWriteConstructParamFlags));
/**
* WebKitSettings:user-agent:
*
* The user-agent string used by WebKit. Unusual user-agent strings may cause web
* content to render incorrectly or fail to run, as many web pages are written to
* parse the user-agent strings of only the most popular browsers. Therefore, it's
* typically better to not completely override the standard user-agent, but to use
* webkit_settings_set_user_agent_with_application_details() instead.
*
* If this property is set to the empty string or %NULL, it will revert to the standard
* user-agent.
*/
g_object_class_install_property(gObjectClass,
PROP_USER_AGENT,
g_param_spec_string("user-agent",
_("User agent string"),
_("The user agent string"),
0, // A null string forces the standard user agent.
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-smooth-scrolling:
*
* Enable or disable smooth scrolling.
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_SMOOTH_SCROLLING,
g_param_spec_boolean("enable-smooth-scrolling",
_("Enable smooth scrolling"),
_("Whether to enable smooth scrolling"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-accelerated-2d-canvas:
*
* Enable or disable accelerated 2D canvas. Accelerated 2D canvas is only available
* if WebKitGTK+ was compiled with a version of Cairo including the unstable CairoGL API.
* When accelerated 2D canvas is enabled, WebKit may render some 2D canvas content
* using hardware accelerated drawing operations.
*
* Since: 2.2
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_ACCELERATED_2D_CANVAS,
g_param_spec_boolean("enable-accelerated-2d-canvas",
_("Enable accelerated 2D canvas"),
_("Whether to enable accelerated 2D canvas"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-write-console-messages-to-stdout:
*
* Enable or disable writing console messages to stdout. These are messages
* sent to the console with console.log and related methods.
*
* Since: 2.2
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_WRITE_CONSOLE_MESSAGES_TO_STDOUT,
g_param_spec_boolean("enable-write-console-messages-to-stdout",
_("Write console messages on stdout"),
_("Whether to write console messages on stdout"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-media-stream:
*
* Enable or disable support for MediaStream on pages. MediaStream
* is an experimental proposal for allowing web pages to access
* audio and video devices for capture.
*
* See also http://dev.w3.org/2011/webrtc/editor/getusermedia.html
*
* Since: 2.4
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_MEDIA_STREAM,
g_param_spec_boolean("enable-media-stream",
_("Enable MediaStream"),
_("Whether MediaStream content should be handled"),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-spatial-navigation:
*
* Whether to enable Spatial Navigation. This feature consists in the ability
* to navigate between focusable elements in a Web page, such as hyperlinks
* and form controls, by using Left, Right, Up and Down arrow keys.
* For example, if an user presses the Right key, heuristics determine whether
* there is an element they might be trying to reach towards the right, and if
* there are multiple elements, which element they probably wants.
*
* Since: 2.4
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_SPATIAL_NAVIGATION,
g_param_spec_boolean("enable-spatial-navigation",
_("Enable Spatial Navigation"),
_("Whether to enable Spatial Navigation support."),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:enable-mediasource:
*
* Enable or disable support for MediaSource on pages. MediaSource is an
* experimental proposal which extends HTMLMediaElement to allow
* JavaScript to generate media streams for playback. The standard is
* currently a work-in-progress by the W3C HTML Media Task Force.
*
* See also http://www.w3.org/TR/media-source/
*
* Since: 2.4
*/
g_object_class_install_property(gObjectClass,
PROP_ENABLE_MEDIASOURCE,
g_param_spec_boolean("enable-mediasource",
_("Enable MediaSource"),
_("Whether MediaSource should be enabled."),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:allow-file-access-from-file-urls:
*
* Whether file access is allowed from file URLs. By default, when
* something is loaded in a #WebKitWebView using a file URI, cross
* origin requests to other file resources are not allowed. This
* setting allows you to change that behaviour, so that it would be
* possible to do a XMLHttpRequest of a local file, for example.
*
* Since: 2.10
*/
g_object_class_install_property(gObjectClass,
PROP_ALLOW_FILE_ACCESS_FROM_FILE_URLS,
g_param_spec_boolean("allow-file-access-from-file-urls",
_("Allow file access from file URLs"),
_("Whether file access is allowed from file URLs."),
FALSE,
readWriteConstructParamFlags));
/**
* WebKitSettings:allow-universal-access-from-file-urls:
*
* Whether or not JavaScript running in the context of a file scheme URL
* should be allowed to access content from any origin. By default, when
* something is loaded in a #WebKitWebView using a file scheme URL,
* access to the local file system and arbitrary local storage is not
* allowed. This setting allows you to change that behaviour, so that
* it would be possible to use local storage, for example.
*
* Since: 2.14
*/
g_object_class_install_property(gObjectClass,
PROP_ALLOW_UNIVERSAL_ACCESS_FROM_FILE_URLS,
g_param_spec_boolean("allow-universal-access-from-file-urls",
_("Allow universal access from the context of file scheme URLs"),
_("Whether or not universal access is allowed from the context of file scheme URLs"),
FALSE,
readWriteConstructParamFlags));
#if PLATFORM(GTK)
/**
* WebKitSettings:hardware-acceleration-policy:
*
* The #WebKitHardwareAccelerationPolicy to decide how to enable and disable
* hardware acceleration. The default value %WEBKIT_HARDWARE_ACCELERATION_POLICY_ON_DEMAND
* enables the hardware acceleration when the web contents request it, disabling it again
* when no longer needed. It's possible to enforce hardware acceleration to be always enabled
* by using %WEBKIT_HARDWARE_ACCELERATION_POLICY_ALWAYS. And it's also possible to disable it
* completely using %WEBKIT_HARDWARE_ACCELERATION_POLICY_NEVER. Note that disabling hardware
* acceleration might cause some websites to not render correctly or consume more CPU.
*
* Note that changing this setting might not be possible if hardware acceleration is not
* supported by the hardware or the system. In that case you can get the value to know the
* actual policy being used, but changing the setting will not have any effect.
*
* Since: 2.16
*/
g_object_class_install_property(gObjectClass,
PROP_HARDWARE_ACCELERATION_POLICY,
g_param_spec_enum("hardware-acceleration-policy",
_("Hardware Acceleration Policy"),
_("The policy to decide how to enable and disable hardware acceleration"),
WEBKIT_TYPE_HARDWARE_ACCELERATION_POLICY,
WEBKIT_HARDWARE_ACCELERATION_POLICY_ON_DEMAND,
readWriteConstructParamFlags));
#endif // PLATFOTM(GTK)
}
WebPreferences* webkitSettingsGetPreferences(WebKitSettings* settings)
{
return settings->priv->preferences.get();
}
/**
* webkit_settings_new:
*
* Creates a new #WebKitSettings instance with default values. It must
* be manually attached to a #WebKitWebView.
* See also webkit_settings_new_with_settings().
*
* Returns: a new #WebKitSettings instance.
*/
WebKitSettings* webkit_settings_new()
{
return WEBKIT_SETTINGS(g_object_new(WEBKIT_TYPE_SETTINGS, NULL));
}
/**
* webkit_settings_new_with_settings:
* @first_setting_name: name of first setting to set
* @...: value of first setting, followed by more settings,
* %NULL-terminated
*
* Creates a new #WebKitSettings instance with the given settings. It must
* be manually attached to a #WebKitWebView.
*
* Returns: a new #WebKitSettings instance.
*/
WebKitSettings* webkit_settings_new_with_settings(const gchar* firstSettingName, ...)
{
va_list args;
va_start(args, firstSettingName);
WebKitSettings* settings = WEBKIT_SETTINGS(g_object_new_valist(WEBKIT_TYPE_SETTINGS, firstSettingName, args));
va_end(args);
return settings;
}
/**
* webkit_settings_get_enable_javascript:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-javascript property.
*
* Returns: %TRUE If JavaScript is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_javascript(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->javaScriptEnabled();
}
/**
* webkit_settings_set_enable_javascript:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-javascript property.
*/
void webkit_settings_set_enable_javascript(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->javaScriptEnabled();
if (currentValue == enabled)
return;
priv->preferences->setJavaScriptEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-javascript");
}
/**
* webkit_settings_get_auto_load_images:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:auto-load-images property.
*
* Returns: %TRUE If auto loading of images is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_auto_load_images(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->loadsImagesAutomatically();
}
/**
* webkit_settings_set_auto_load_images:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:auto-load-images property.
*/
void webkit_settings_set_auto_load_images(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->loadsImagesAutomatically();
if (currentValue == enabled)
return;
priv->preferences->setLoadsImagesAutomatically(enabled);
g_object_notify(G_OBJECT(settings), "auto-load-images");
}
/**
* webkit_settings_get_load_icons_ignoring_image_load_setting:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:load-icons-ignoring-image-load-setting property.
*
* Returns: %TRUE If site icon can be loaded irrespective of image loading preference or %FALSE otherwise.
*/
gboolean webkit_settings_get_load_icons_ignoring_image_load_setting(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->loadsSiteIconsIgnoringImageLoadingPreference();
}
/**
* webkit_settings_set_load_icons_ignoring_image_load_setting:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:load-icons-ignoring-image-load-setting property.
*/
void webkit_settings_set_load_icons_ignoring_image_load_setting(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->loadsSiteIconsIgnoringImageLoadingPreference();
if (currentValue == enabled)
return;
priv->preferences->setLoadsSiteIconsIgnoringImageLoadingPreference(enabled);
g_object_notify(G_OBJECT(settings), "load-icons-ignoring-image-load-setting");
}
/**
* webkit_settings_get_enable_offline_web_application_cache:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-offline-web-application-cache property.
*
* Returns: %TRUE If HTML5 offline web application cache support is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_offline_web_application_cache(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->offlineWebApplicationCacheEnabled();
}
/**
* webkit_settings_set_enable_offline_web_application_cache:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-offline-web-application-cache property.
*/
void webkit_settings_set_enable_offline_web_application_cache(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->offlineWebApplicationCacheEnabled();
if (currentValue == enabled)
return;
priv->preferences->setOfflineWebApplicationCacheEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-offline-web-application-cache");
}
/**
* webkit_settings_get_enable_html5_local_storage:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-html5-local-storage property.
*
* Returns: %TRUE If HTML5 local storage support is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_html5_local_storage(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->localStorageEnabled();
}
/**
* webkit_settings_set_enable_html5_local_storage:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-html5-local-storage property.
*/
void webkit_settings_set_enable_html5_local_storage(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->localStorageEnabled();
if (currentValue == enabled)
return;
priv->preferences->setLocalStorageEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-html5-local-storage");
}
/**
* webkit_settings_get_enable_html5_database:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-html5-database property.
*
* Returns: %TRUE If HTML5 database support is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_html5_database(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->databasesEnabled();
}
/**
* webkit_settings_set_enable_html5_database:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-html5-database property.
*/
void webkit_settings_set_enable_html5_database(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->databasesEnabled();
if (currentValue == enabled)
return;
priv->preferences->setDatabasesEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-html5-database");
}
/**
* webkit_settings_get_enable_xss_auditor:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-xss-auditor property.
*
* Returns: %TRUE If XSS auditing is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_xss_auditor(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->xssAuditorEnabled();
}
/**
* webkit_settings_set_enable_xss_auditor:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-xss-auditor property.
*/
void webkit_settings_set_enable_xss_auditor(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->xssAuditorEnabled();
if (currentValue == enabled)
return;
priv->preferences->setXSSAuditorEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-xss-auditor");
}
/**
* webkit_settings_get_enable_frame_flattening:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-frame-flattening property.
*
* Returns: %TRUE If frame flattening is enabled or %FALSE otherwise.
*
**/
gboolean webkit_settings_get_enable_frame_flattening(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
// FIXME: Expose more frame flattening values.
return settings->priv->preferences->frameFlattening() != WebCore::FrameFlatteningDisabled;
}
/**
* webkit_settings_set_enable_frame_flattening:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-frame-flattening property.
*/
void webkit_settings_set_enable_frame_flattening(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->frameFlattening() != WebCore::FrameFlatteningDisabled;
if (currentValue == enabled)
return;
// FIXME: Expose more frame flattening values.
priv->preferences->setFrameFlattening(enabled ? WebCore::FrameFlatteningFullyEnabled : WebCore::FrameFlatteningDisabled);
g_object_notify(G_OBJECT(settings), "enable-frame-flattening");
}
/**
* webkit_settings_get_enable_plugins:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-plugins property.
*
* Returns: %TRUE If plugins are enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_plugins(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->pluginsEnabled();
}
/**
* webkit_settings_set_enable_plugins:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-plugins property.
*/
void webkit_settings_set_enable_plugins(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->pluginsEnabled();
if (currentValue == enabled)
return;
priv->preferences->setPluginsEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-plugins");
}
/**
* webkit_settings_get_enable_java:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-java property.
*
* Returns: %TRUE If Java is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_java(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->javaEnabled();
}
/**
* webkit_settings_set_enable_java:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-java property.
*/
void webkit_settings_set_enable_java(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->javaEnabled();
if (currentValue == enabled)
return;
priv->preferences->setJavaEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-java");
}
/**
* webkit_settings_get_javascript_can_open_windows_automatically:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:javascript-can-open-windows-automatically property.
*
* Returns: %TRUE If JavaScript can open window automatically or %FALSE otherwise.
*/
gboolean webkit_settings_get_javascript_can_open_windows_automatically(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->javaScriptCanOpenWindowsAutomatically();
}
/**
* webkit_settings_set_javascript_can_open_windows_automatically:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:javascript-can-open-windows-automatically property.
*/
void webkit_settings_set_javascript_can_open_windows_automatically(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->javaScriptCanOpenWindowsAutomatically();
if (currentValue == enabled)
return;
priv->preferences->setJavaScriptCanOpenWindowsAutomatically(enabled);
g_object_notify(G_OBJECT(settings), "javascript-can-open-windows-automatically");
}
/**
* webkit_settings_get_enable_hyperlink_auditing:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-hyperlink-auditing property.
*
* Returns: %TRUE If hyper link auditing is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_hyperlink_auditing(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->hyperlinkAuditingEnabled();
}
/**
* webkit_settings_set_enable_hyperlink_auditing:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-hyperlink-auditing property.
*/
void webkit_settings_set_enable_hyperlink_auditing(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->hyperlinkAuditingEnabled();
if (currentValue == enabled)
return;
priv->preferences->setHyperlinkAuditingEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-hyperlink-auditing");
}
/**
* webkit_web_settings_get_default_font_family:
* @settings: a #WebKitSettings
*
* Gets the #WebKitSettings:default-font-family property.
*
* Returns: The default font family used to display content that does not specify a font.
*/
const gchar* webkit_settings_get_default_font_family(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0);
return settings->priv->defaultFontFamily.data();
}
/**
* webkit_settings_set_default_font_family:
* @settings: a #WebKitSettings
* @default_font_family: the new default font family
*
* Set the #WebKitSettings:default-font-family property.
*/
void webkit_settings_set_default_font_family(WebKitSettings* settings, const gchar* defaultFontFamily)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
g_return_if_fail(defaultFontFamily);
WebKitSettingsPrivate* priv = settings->priv;
if (!g_strcmp0(priv->defaultFontFamily.data(), defaultFontFamily))
return;
String standardFontFamily = String::fromUTF8(defaultFontFamily);
priv->preferences->setStandardFontFamily(standardFontFamily);
priv->defaultFontFamily = standardFontFamily.utf8();
g_object_notify(G_OBJECT(settings), "default-font-family");
}
/**
* webkit_settings_get_monospace_font_family:
* @settings: a #WebKitSettings
*
* Gets the #WebKitSettings:monospace-font-family property.
*
* Returns: Default font family used to display content marked with monospace font.
*/
const gchar* webkit_settings_get_monospace_font_family(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0);
return settings->priv->monospaceFontFamily.data();
}
/**
* webkit_settings_set_monospace_font_family:
* @settings: a #WebKitSettings
* @monospace_font_family: the new default monospace font family
*
* Set the #WebKitSettings:monospace-font-family property.
*/
void webkit_settings_set_monospace_font_family(WebKitSettings* settings, const gchar* monospaceFontFamily)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
g_return_if_fail(monospaceFontFamily);
WebKitSettingsPrivate* priv = settings->priv;
if (!g_strcmp0(priv->monospaceFontFamily.data(), monospaceFontFamily))
return;
String fixedFontFamily = String::fromUTF8(monospaceFontFamily);
priv->preferences->setFixedFontFamily(fixedFontFamily);
priv->monospaceFontFamily = fixedFontFamily.utf8();
g_object_notify(G_OBJECT(settings), "monospace-font-family");
}
/**
* webkit_settings_get_serif_font_family:
* @settings: a #WebKitSettings
*
* Gets the #WebKitSettings:serif-font-family property.
*
* Returns: The default font family used to display content marked with serif font.
*/
const gchar* webkit_settings_get_serif_font_family(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0);
return settings->priv->serifFontFamily.data();
}
/**
* webkit_settings_set_serif_font_family:
* @settings: a #WebKitSettings
* @serif_font_family: the new default serif font family
*
* Set the #WebKitSettings:serif-font-family property.
*/
void webkit_settings_set_serif_font_family(WebKitSettings* settings, const gchar* serifFontFamily)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
g_return_if_fail(serifFontFamily);
WebKitSettingsPrivate* priv = settings->priv;
if (!g_strcmp0(priv->serifFontFamily.data(), serifFontFamily))
return;
String serifFontFamilyString = String::fromUTF8(serifFontFamily);
priv->preferences->setSerifFontFamily(serifFontFamilyString);
priv->serifFontFamily = serifFontFamilyString.utf8();
g_object_notify(G_OBJECT(settings), "serif-font-family");
}
/**
* webkit_settings_get_sans_serif_font_family:
* @settings: a #WebKitSettings
*
* Gets the #WebKitSettings:sans-serif-font-family property.
*
* Returns: The default font family used to display content marked with sans-serif font.
*/
const gchar* webkit_settings_get_sans_serif_font_family(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0);
return settings->priv->sansSerifFontFamily.data();
}
/**
* webkit_settings_set_sans_serif_font_family:
* @settings: a #WebKitSettings
* @sans_serif_font_family: the new default sans-serif font family
*
* Set the #WebKitSettings:sans-serif-font-family property.
*/
void webkit_settings_set_sans_serif_font_family(WebKitSettings* settings, const gchar* sansSerifFontFamily)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
g_return_if_fail(sansSerifFontFamily);
WebKitSettingsPrivate* priv = settings->priv;
if (!g_strcmp0(priv->sansSerifFontFamily.data(), sansSerifFontFamily))
return;
String sansSerifFontFamilyString = String::fromUTF8(sansSerifFontFamily);
priv->preferences->setSansSerifFontFamily(sansSerifFontFamilyString);
priv->sansSerifFontFamily = sansSerifFontFamilyString.utf8();
g_object_notify(G_OBJECT(settings), "sans-serif-font-family");
}
/**
* webkit_settings_get_cursive_font_family:
* @settings: a #WebKitSettings
*
* Gets the #WebKitSettings:cursive-font-family property.
*
* Returns: The default font family used to display content marked with cursive font.
*/
const gchar* webkit_settings_get_cursive_font_family(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0);
return settings->priv->cursiveFontFamily.data();
}
/**
* webkit_settings_set_cursive_font_family:
* @settings: a #WebKitSettings
* @cursive_font_family: the new default cursive font family
*
* Set the #WebKitSettings:cursive-font-family property.
*/
void webkit_settings_set_cursive_font_family(WebKitSettings* settings, const gchar* cursiveFontFamily)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
g_return_if_fail(cursiveFontFamily);
WebKitSettingsPrivate* priv = settings->priv;
if (!g_strcmp0(priv->cursiveFontFamily.data(), cursiveFontFamily))
return;
String cursiveFontFamilyString = String::fromUTF8(cursiveFontFamily);
priv->preferences->setCursiveFontFamily(cursiveFontFamilyString);
priv->cursiveFontFamily = cursiveFontFamilyString.utf8();
g_object_notify(G_OBJECT(settings), "cursive-font-family");
}
/**
* webkit_settings_get_fantasy_font_family:
* @settings: a #WebKitSettings
*
* Gets the #WebKitSettings:fantasy-font-family property.
*
* Returns: The default font family used to display content marked with fantasy font.
*/
const gchar* webkit_settings_get_fantasy_font_family(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0);
return settings->priv->fantasyFontFamily.data();
}
/**
* webkit_settings_set_fantasy_font_family:
* @settings: a #WebKitSettings
* @fantasy_font_family: the new default fantasy font family
*
* Set the #WebKitSettings:fantasy-font-family property.
*/
void webkit_settings_set_fantasy_font_family(WebKitSettings* settings, const gchar* fantasyFontFamily)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
g_return_if_fail(fantasyFontFamily);
WebKitSettingsPrivate* priv = settings->priv;
if (!g_strcmp0(priv->fantasyFontFamily.data(), fantasyFontFamily))
return;
String fantasyFontFamilyString = String::fromUTF8(fantasyFontFamily);
priv->preferences->setFantasyFontFamily(fantasyFontFamilyString);
priv->fantasyFontFamily = fantasyFontFamilyString.utf8();
g_object_notify(G_OBJECT(settings), "fantasy-font-family");
}
/**
* webkit_settings_get_pictograph_font_family:
* @settings: a #WebKitSettings
*
* Gets the #WebKitSettings:pictograph-font-family property.
*
* Returns: The default font family used to display content marked with pictograph font.
*/
const gchar* webkit_settings_get_pictograph_font_family(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0);
return settings->priv->pictographFontFamily.data();
}
/**
* webkit_settings_set_pictograph_font_family:
* @settings: a #WebKitSettings
* @pictograph_font_family: the new default pictograph font family
*
* Set the #WebKitSettings:pictograph-font-family property.
*/
void webkit_settings_set_pictograph_font_family(WebKitSettings* settings, const gchar* pictographFontFamily)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
g_return_if_fail(pictographFontFamily);
WebKitSettingsPrivate* priv = settings->priv;
if (!g_strcmp0(priv->pictographFontFamily.data(), pictographFontFamily))
return;
String pictographFontFamilyString = String::fromUTF8(pictographFontFamily);
priv->preferences->setPictographFontFamily(pictographFontFamilyString);
priv->pictographFontFamily = pictographFontFamilyString.utf8();
g_object_notify(G_OBJECT(settings), "pictograph-font-family");
}
/**
* webkit_settings_get_default_font_size:
* @settings: a #WebKitSettings
*
* Gets the #WebKitSettings:default-font-size property.
*
* Returns: The default font size.
*/
guint32 webkit_settings_get_default_font_size(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0);
return settings->priv->preferences->defaultFontSize();
}
/**
* webkit_settings_set_default_font_size:
* @settings: a #WebKitSettings
* @font_size: default font size to be set in pixels
*
* Set the #WebKitSettings:default-font-size property.
*/
void webkit_settings_set_default_font_size(WebKitSettings* settings, guint32 fontSize)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
uint32_t currentSize = priv->preferences->defaultFontSize();
if (currentSize == fontSize)
return;
priv->preferences->setDefaultFontSize(fontSize);
g_object_notify(G_OBJECT(settings), "default-font-size");
}
/**
* webkit_settings_get_default_monospace_font_size:
* @settings: a #WebKitSettings
*
* Gets the #WebKitSettings:default-monospace-font-size property.
*
* Returns: Default monospace font size.
*/
guint32 webkit_settings_get_default_monospace_font_size(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0);
return settings->priv->preferences->defaultFixedFontSize();
}
/**
* webkit_settings_set_default_monospace_font_size:
* @settings: a #WebKitSettings
* @font_size: default monospace font size to be set in pixels
*
* Set the #WebKitSettings:default-monospace-font-size property.
*/
void webkit_settings_set_default_monospace_font_size(WebKitSettings* settings, guint32 fontSize)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
uint32_t currentSize = priv->preferences->defaultFixedFontSize();
if (currentSize == fontSize)
return;
priv->preferences->setDefaultFixedFontSize(fontSize);
g_object_notify(G_OBJECT(settings), "default-monospace-font-size");
}
/**
* webkit_settings_get_minimum_font_size:
* @settings: a #WebKitSettings
*
* Gets the #WebKitSettings:minimum-font-size property.
*
* Returns: Minimum font size.
*/
guint32 webkit_settings_get_minimum_font_size(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0);
return settings->priv->preferences->minimumFontSize();
}
/**
* webkit_settings_set_minimum_font_size:
* @settings: a #WebKitSettings
* @font_size: minimum font size to be set in points
*
* Set the #WebKitSettings:minimum-font-size property.
*/
void webkit_settings_set_minimum_font_size(WebKitSettings* settings, guint32 fontSize)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
uint32_t currentSize = priv->preferences->minimumFontSize();
if (currentSize == fontSize)
return;
priv->preferences->setMinimumFontSize(fontSize);
g_object_notify(G_OBJECT(settings), "minimum-font-size");
}
/**
* webkit_settings_get_default_charset:
* @settings: a #WebKitSettings
*
* Gets the #WebKitSettings:default-charset property.
*
* Returns: Default charset.
*/
const gchar* webkit_settings_get_default_charset(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0);
return settings->priv->defaultCharset.data();
}
/**
* webkit_settings_set_default_charset:
* @settings: a #WebKitSettings
* @default_charset: default charset to be set
*
* Set the #WebKitSettings:default-charset property.
*/
void webkit_settings_set_default_charset(WebKitSettings* settings, const gchar* defaultCharset)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
g_return_if_fail(defaultCharset);
WebKitSettingsPrivate* priv = settings->priv;
if (!g_strcmp0(priv->defaultCharset.data(), defaultCharset))
return;
String defaultCharsetString = String::fromUTF8(defaultCharset);
priv->preferences->setDefaultTextEncodingName(defaultCharsetString);
priv->defaultCharset = defaultCharsetString.utf8();
g_object_notify(G_OBJECT(settings), "default-charset");
}
/**
* webkit_settings_get_enable_private_browsing:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-private-browsing property.
*
* Returns: %TRUE If private browsing is enabled or %FALSE otherwise.
*
* Deprecated: 2.16. Use #WebKitWebView:is-ephemeral or #WebKitWebContext:is-ephemeral instead.
*/
gboolean webkit_settings_get_enable_private_browsing(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->privateBrowsingEnabled();
}
/**
* webkit_settings_set_enable_private_browsing:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-private-browsing property.
*
* Deprecated: 2.16. Use #WebKitWebView:is-ephemeral or #WebKitWebContext:is-ephemeral instead.
*/
void webkit_settings_set_enable_private_browsing(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->privateBrowsingEnabled();
if (currentValue == enabled)
return;
priv->preferences->setPrivateBrowsingEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-private-browsing");
}
/**
* webkit_settings_get_enable_developer_extras:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-developer-extras property.
*
* Returns: %TRUE If developer extras is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_developer_extras(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->developerExtrasEnabled();
}
/**
* webkit_settings_set_enable_developer_extras:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-developer-extras property.
*/
void webkit_settings_set_enable_developer_extras(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->developerExtrasEnabled();
if (currentValue == enabled)
return;
priv->preferences->setDeveloperExtrasEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-developer-extras");
}
/**
* webkit_settings_get_enable_resizable_text_areas:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-resizable-text-areas property.
*
* Returns: %TRUE If text areas can be resized or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_resizable_text_areas(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->textAreasAreResizable();
}
/**
* webkit_settings_set_enable_resizable_text_areas:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-resizable-text-areas property.
*/
void webkit_settings_set_enable_resizable_text_areas(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->textAreasAreResizable();
if (currentValue == enabled)
return;
priv->preferences->setTextAreasAreResizable(enabled);
g_object_notify(G_OBJECT(settings), "enable-resizable-text-areas");
}
/**
* webkit_settings_get_enable_tabs_to_links:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-tabs-to-links property.
*
* Returns: %TRUE If tabs to link is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_tabs_to_links(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->tabsToLinks();
}
/**
* webkit_settings_set_enable_tabs_to_links:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-tabs-to-links property.
*/
void webkit_settings_set_enable_tabs_to_links(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->tabsToLinks();
if (currentValue == enabled)
return;
priv->preferences->setTabsToLinks(enabled);
g_object_notify(G_OBJECT(settings), "enable-tabs-to-links");
}
/**
* webkit_settings_get_enable_dns_prefetching:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-dns-prefetching property.
*
* Returns: %TRUE If DNS prefetching is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_dns_prefetching(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->dnsPrefetchingEnabled();
}
/**
* webkit_settings_set_enable_dns_prefetching:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-dns-prefetching property.
*/
void webkit_settings_set_enable_dns_prefetching(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->dnsPrefetchingEnabled();
if (currentValue == enabled)
return;
priv->preferences->setDNSPrefetchingEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-dns-prefetching");
}
/**
* webkit_settings_get_enable_caret_browsing:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-caret-browsing property.
*
* Returns: %TRUE If caret browsing is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_caret_browsing(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->caretBrowsingEnabled();
}
/**
* webkit_settings_set_enable_caret_browsing:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-caret-browsing property.
*/
void webkit_settings_set_enable_caret_browsing(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->caretBrowsingEnabled();
if (currentValue == enabled)
return;
priv->preferences->setCaretBrowsingEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-caret-browsing");
}
/**
* webkit_settings_get_enable_fullscreen:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-fullscreen property.
*
* Returns: %TRUE If fullscreen support is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_fullscreen(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->fullScreenEnabled();
}
/**
* webkit_settings_set_enable_fullscreen:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-fullscreen property.
*/
void webkit_settings_set_enable_fullscreen(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->fullScreenEnabled();
if (currentValue == enabled)
return;
priv->preferences->setFullScreenEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-fullscreen");
}
/**
* webkit_settings_get_print_backgrounds:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:print-backgrounds property.
*
* Returns: %TRUE If background images should be printed or %FALSE otherwise.
*/
gboolean webkit_settings_get_print_backgrounds(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->shouldPrintBackgrounds();
}
/**
* webkit_settings_set_print_backgrounds:
* @settings: a #WebKitSettings
* @print_backgrounds: Value to be set
*
* Set the #WebKitSettings:print-backgrounds property.
*/
void webkit_settings_set_print_backgrounds(WebKitSettings* settings, gboolean printBackgrounds)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->shouldPrintBackgrounds();
if (currentValue == printBackgrounds)
return;
priv->preferences->setShouldPrintBackgrounds(printBackgrounds);
g_object_notify(G_OBJECT(settings), "print-backgrounds");
}
/**
* webkit_settings_get_enable_webaudio:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-webaudio property.
*
* Returns: %TRUE If webaudio support is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_webaudio(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->webAudioEnabled();
}
/**
* webkit_settings_set_enable_webaudio:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-webaudio property.
*/
void webkit_settings_set_enable_webaudio(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->webAudioEnabled();
if (currentValue == enabled)
return;
priv->preferences->setWebAudioEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-webaudio");
}
/**
* webkit_settings_get_enable_webgl:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-webgl property.
*
* Returns: %TRUE If WebGL support is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_webgl(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->webGLEnabled();
}
/**
* webkit_settings_set_enable_webgl:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-webgl property.
*/
void webkit_settings_set_enable_webgl(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->webGLEnabled();
if (currentValue == enabled)
return;
priv->preferences->setWebGLEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-webgl");
}
/**
* webkit_settings_get_allow_modal_dialogs:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:allow-modal-dialogs property.
*
* Returns: %TRUE if it's allowed to create and run modal dialogs or %FALSE otherwise.
*/
gboolean webkit_settings_get_allow_modal_dialogs(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->allowModalDialogs;
}
/**
* webkit_settings_set_allow_modal_dialogs:
* @settings: a #WebKitSettings
* @allowed: Value to be set
*
* Set the #WebKitSettings:allow-modal-dialogs property.
*/
void webkit_settings_set_allow_modal_dialogs(WebKitSettings* settings, gboolean allowed)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
if (priv->allowModalDialogs == allowed)
return;
priv->allowModalDialogs = allowed;
g_object_notify(G_OBJECT(settings), "allow-modal-dialogs");
}
/**
* webkit_settings_get_zoom_text_only:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:zoom-text-only property.
*
* Returns: %TRUE If zoom level of the view should only affect the text
* or %FALSE if all view contents should be scaled.
*/
gboolean webkit_settings_get_zoom_text_only(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->zoomTextOnly;
}
/**
* webkit_settings_set_zoom_text_only:
* @settings: a #WebKitSettings
* @zoom_text_only: Value to be set
*
* Set the #WebKitSettings:zoom-text-only property.
*/
void webkit_settings_set_zoom_text_only(WebKitSettings* settings, gboolean zoomTextOnly)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
if (priv->zoomTextOnly == zoomTextOnly)
return;
priv->zoomTextOnly = zoomTextOnly;
g_object_notify(G_OBJECT(settings), "zoom-text-only");
}
/**
* webkit_settings_get_javascript_can_access_clipboard:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:javascript-can-access-clipboard property.
*
* Returns: %TRUE If javascript-can-access-clipboard is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_javascript_can_access_clipboard(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->javaScriptCanAccessClipboard()
&& settings->priv->preferences->domPasteAllowed();
}
/**
* webkit_settings_set_javascript_can_access_clipboard:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:javascript-can-access-clipboard property.
*/
void webkit_settings_set_javascript_can_access_clipboard(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->javaScriptCanAccessClipboard() && priv->preferences->domPasteAllowed();
if (currentValue == enabled)
return;
priv->preferences->setJavaScriptCanAccessClipboard(enabled);
priv->preferences->setDOMPasteAllowed(enabled);
g_object_notify(G_OBJECT(settings), "javascript-can-access-clipboard");
}
/**
* webkit_settings_get_media_playback_requires_user_gesture:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:media-playback-requires-user-gesture property.
*
* Returns: %TRUE If an user gesture is needed to play or load media
* or %FALSE if no user gesture is needed.
*/
gboolean webkit_settings_get_media_playback_requires_user_gesture(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->requiresUserGestureForMediaPlayback();
}
/**
* webkit_settings_set_media_playback_requires_user_gesture:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:media-playback-requires-user-gesture property.
*/
void webkit_settings_set_media_playback_requires_user_gesture(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->requiresUserGestureForMediaPlayback();
if (currentValue == enabled)
return;
priv->preferences->setRequiresUserGestureForMediaPlayback(enabled);
g_object_notify(G_OBJECT(settings), "media-playback-requires-user-gesture");
}
/**
* webkit_settings_get_media_playback_allows_inline:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:media-playback-allows-inline property.
*
* Returns: %TRUE If inline playback is allowed for media
* or %FALSE if only fullscreen playback is allowed.
*/
gboolean webkit_settings_get_media_playback_allows_inline(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), TRUE);
return settings->priv->preferences->allowsInlineMediaPlayback();
}
/**
* webkit_settings_set_media_playback_allows_inline:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:media-playback-allows-inline property.
*/
void webkit_settings_set_media_playback_allows_inline(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->allowsInlineMediaPlayback();
if (currentValue == enabled)
return;
priv->preferences->setAllowsInlineMediaPlayback(enabled);
g_object_notify(G_OBJECT(settings), "media-playback-allows-inline");
}
/**
* webkit_settings_get_draw_compositing_indicators:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:draw-compositing-indicators property.
*
* Returns: %TRUE If compositing borders are drawn or %FALSE otherwise.
*/
gboolean webkit_settings_get_draw_compositing_indicators(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->compositingBordersVisible()
&& settings->priv->preferences->compositingRepaintCountersVisible();
}
/**
* webkit_settings_set_draw_compositing_indicators:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:draw-compositing-indicators property.
*/
void webkit_settings_set_draw_compositing_indicators(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
if (priv->preferences->compositingBordersVisible() == enabled
&& priv->preferences->compositingRepaintCountersVisible() == enabled)
return;
priv->preferences->setCompositingBordersVisible(enabled);
priv->preferences->setCompositingRepaintCountersVisible(enabled);
g_object_notify(G_OBJECT(settings), "draw-compositing-indicators");
}
/**
* webkit_settings_get_enable_site_specific_quirks:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-site-specific-quirks property.
*
* Returns: %TRUE if site specific quirks are enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_site_specific_quirks(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->needsSiteSpecificQuirks();
}
/**
* webkit_settings_set_enable_site_specific_quirks:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-site-specific-quirks property.
*/
void webkit_settings_set_enable_site_specific_quirks(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->needsSiteSpecificQuirks();
if (currentValue == enabled)
return;
priv->preferences->setNeedsSiteSpecificQuirks(enabled);
g_object_notify(G_OBJECT(settings), "enable-site-specific-quirks");
}
/**
* webkit_settings_get_enable_page_cache:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-page-cache property.
*
* Returns: %TRUE if page cache enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_page_cache(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->usesPageCache();
}
/**
* webkit_settings_set_enable_page_cache:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-page-cache property.
*/
void webkit_settings_set_enable_page_cache(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->usesPageCache();
if (currentValue == enabled)
return;
priv->preferences->setUsesPageCache(enabled);
g_object_notify(G_OBJECT(settings), "enable-page-cache");
}
/**
* webkit_settings_get_user_agent:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:user-agent property.
*
* Returns: The current value of the user-agent property.
*/
const char* webkit_settings_get_user_agent(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), 0);
WebKitSettingsPrivate* priv = settings->priv;
ASSERT(!priv->userAgent.isNull());
return priv->userAgent.data();
}
/**
* webkit_settings_set_user_agent:
* @settings: a #WebKitSettings
* @user_agent: (allow-none): The new custom user agent string or %NULL to use the default user agent
*
* Set the #WebKitSettings:user-agent property.
*/
void webkit_settings_set_user_agent(WebKitSettings* settings, const char* userAgent)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
CString newUserAgent = (!userAgent || !strlen(userAgent)) ? WebCore::standardUserAgent("").utf8() : userAgent;
if (newUserAgent == priv->userAgent)
return;
priv->userAgent = newUserAgent;
g_object_notify(G_OBJECT(settings), "user-agent");
}
/**
* webkit_settings_set_user_agent_with_application_details:
* @settings: a #WebKitSettings
* @application_name: (allow-none): The application name used for the user agent or %NULL to use the default user agent.
* @application_version: (allow-none): The application version for the user agent or %NULL to user the default version.
*
* Set the #WebKitSettings:user-agent property by appending the application details to the default user
* agent. If no application name or version is given, the default user agent used will be used. If only
* the version is given, the default engine version is used with the given application name.
*/
void webkit_settings_set_user_agent_with_application_details(WebKitSettings* settings, const char* applicationName, const char* applicationVersion)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
CString newUserAgent = WebCore::standardUserAgent(String::fromUTF8(applicationName), String::fromUTF8(applicationVersion)).utf8();
webkit_settings_set_user_agent(settings, newUserAgent.data());
}
/**
* webkit_settings_get_enable_smooth_scrolling:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-smooth-scrolling property.
*
* Returns: %TRUE if smooth scrolling is enabled or %FALSE otherwise.
*/
gboolean webkit_settings_get_enable_smooth_scrolling(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->scrollAnimatorEnabled();
}
/**
* webkit_settings_set_enable_smooth_scrolling:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-smooth-scrolling property.
*/
void webkit_settings_set_enable_smooth_scrolling(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->scrollAnimatorEnabled();
if (currentValue == enabled)
return;
priv->preferences->setScrollAnimatorEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-smooth-scrolling");
}
/**
* webkit_settings_get_enable_accelerated_2d_canvas:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-accelerated-2d-canvas property.
*
* Returns: %TRUE if accelerated 2D canvas is enabled or %FALSE otherwise.
*
* Since: 2.2
*/
gboolean webkit_settings_get_enable_accelerated_2d_canvas(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->accelerated2dCanvasEnabled();
}
/**
* webkit_settings_set_enable_accelerated_2d_canvas:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-accelerated-2d-canvas property.
*
* Since: 2.2
*/
void webkit_settings_set_enable_accelerated_2d_canvas(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
if (priv->preferences->accelerated2dCanvasEnabled() == enabled)
return;
priv->preferences->setAccelerated2dCanvasEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-accelerated-2d-canvas");
}
/**
* webkit_settings_get_enable_write_console_messages_to_stdout:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-write-console-messages-to-stdout property.
*
* Returns: %TRUE if writing console messages to stdout is enabled or %FALSE
* otherwise.
*
* Since: 2.2
*/
gboolean webkit_settings_get_enable_write_console_messages_to_stdout(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->logsPageMessagesToSystemConsoleEnabled();
}
/**
* webkit_settings_set_enable_write_console_messages_to_stdout:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-write-console-messages-to-stdout property.
*
* Since: 2.2
*/
void webkit_settings_set_enable_write_console_messages_to_stdout(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->logsPageMessagesToSystemConsoleEnabled();
if (currentValue == enabled)
return;
priv->preferences->setLogsPageMessagesToSystemConsoleEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-write-console-messages-to-stdout");
}
/**
* webkit_settings_get_enable_media_stream:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-media-stream property.
*
* Returns: %TRUE If mediastream support is enabled or %FALSE otherwise.
*
* Since: 2.4
*/
gboolean webkit_settings_get_enable_media_stream(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->mediaStreamEnabled();
}
/**
* webkit_settings_set_enable_media_stream:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-media-stream property.
*
* Since: 2.4
*/
void webkit_settings_set_enable_media_stream(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->mediaStreamEnabled();
if (currentValue == enabled)
return;
priv->preferences->setMediaDevicesEnabled(enabled);
priv->preferences->setMediaStreamEnabled(enabled);
priv->preferences->setPeerConnectionEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-media-stream");
}
/**
* webkit_settings_set_enable_spatial_navigation:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-spatial-navigation property.
*
* Since: 2.2
*/
void webkit_settings_set_enable_spatial_navigation(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->spatialNavigationEnabled();
if (currentValue == enabled)
return;
priv->preferences->setSpatialNavigationEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-spatial-navigation");
}
/**
* webkit_settings_get_enable_spatial_navigation:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-spatial-navigation property.
*
* Returns: %TRUE If HTML5 spatial navigation support is enabled or %FALSE otherwise.
*
* Since: 2.2
*/
gboolean webkit_settings_get_enable_spatial_navigation(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->spatialNavigationEnabled();
}
/**
* webkit_settings_get_enable_mediasource:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:enable-mediasource property.
*
* Returns: %TRUE If MediaSource support is enabled or %FALSE otherwise.
*
* Since: 2.4
*/
gboolean webkit_settings_get_enable_mediasource(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->mediaSourceEnabled();
}
/**
* webkit_settings_set_enable_mediasource:
* @settings: a #WebKitSettings
* @enabled: Value to be set
*
* Set the #WebKitSettings:enable-mediasource property.
*
* Since: 2.4
*/
void webkit_settings_set_enable_mediasource(WebKitSettings* settings, gboolean enabled)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool currentValue = priv->preferences->mediaSourceEnabled();
if (currentValue == enabled)
return;
priv->preferences->setMediaSourceEnabled(enabled);
g_object_notify(G_OBJECT(settings), "enable-mediasource");
}
/**
* webkit_settings_get_allow_file_access_from_file_urls:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:allow-file-access-from-file-urls property.
*
* Returns: %TRUE If file access from file URLs is allowed or %FALSE otherwise.
*
* Since: 2.10
*/
gboolean webkit_settings_get_allow_file_access_from_file_urls(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->allowFileAccessFromFileURLs();
}
/**
* webkit_settings_set_allow_file_access_from_file_urls:
* @settings: a #WebKitSettings
* @allowed: Value to be set
*
* Set the #WebKitSettings:allow-file-access-from-file-urls property.
*
* Since: 2.10
*/
void webkit_settings_set_allow_file_access_from_file_urls(WebKitSettings* settings, gboolean allowed)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
if (priv->preferences->allowFileAccessFromFileURLs() == allowed)
return;
priv->preferences->setAllowFileAccessFromFileURLs(allowed);
g_object_notify(G_OBJECT(settings), "allow-file-access-from-file-urls");
}
/**
* webkit_settings_get_allow_universal_access_from_file_urls:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:allow-universal-access-from-file-urls property.
*
* Returns: %TRUE If universal access from file URLs is allowed or %FALSE otherwise.
*
* Since: 2.14
*/
gboolean webkit_settings_get_allow_universal_access_from_file_urls(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), FALSE);
return settings->priv->preferences->allowUniversalAccessFromFileURLs();
}
/**
* webkit_settings_set_allow_universal_access_from_file_urls:
* @settings: a #WebKitSettings
* @allowed: Value to be set
*
* Set the #WebKitSettings:allow-universal-access-from-file-urls property.
*
* Since: 2.14
*/
void webkit_settings_set_allow_universal_access_from_file_urls(WebKitSettings* settings, gboolean allowed)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
if (priv->preferences->allowUniversalAccessFromFileURLs() == allowed)
return;
priv->preferences->setAllowUniversalAccessFromFileURLs(allowed);
g_object_notify(G_OBJECT(settings), "allow-universal-access-from-file-urls");
}
#if PLATFORM(GTK)
/**
* webkit_settings_get_hardware_acceleration_policy:
* @settings: a #WebKitSettings
*
* Get the #WebKitSettings:hardware-acceleration-policy property.
*
* Return: a #WebKitHardwareAccelerationPolicy
*
* Since: 2.16
*/
WebKitHardwareAccelerationPolicy webkit_settings_get_hardware_acceleration_policy(WebKitSettings* settings)
{
g_return_val_if_fail(WEBKIT_IS_SETTINGS(settings), WEBKIT_HARDWARE_ACCELERATION_POLICY_ON_DEMAND);
WebKitSettingsPrivate* priv = settings->priv;
if (!priv->preferences->acceleratedCompositingEnabled())
return WEBKIT_HARDWARE_ACCELERATION_POLICY_NEVER;
if (priv->preferences->forceCompositingMode())
return WEBKIT_HARDWARE_ACCELERATION_POLICY_ALWAYS;
return WEBKIT_HARDWARE_ACCELERATION_POLICY_ON_DEMAND;
}
/**
* webkit_settings_set_hardware_acceleration_policy:
* @settings: a #WebKitSettings
* @policy: a #WebKitHardwareAccelerationPolicy
*
* Set the #WebKitSettings:hardware-acceleration-policy property.
*
* Since: 2.16
*/
void webkit_settings_set_hardware_acceleration_policy(WebKitSettings* settings, WebKitHardwareAccelerationPolicy policy)
{
g_return_if_fail(WEBKIT_IS_SETTINGS(settings));
WebKitSettingsPrivate* priv = settings->priv;
bool changed = false;
switch (policy) {
case WEBKIT_HARDWARE_ACCELERATION_POLICY_ALWAYS:
if (!HardwareAccelerationManager::singleton().canUseHardwareAcceleration())
return;
if (!priv->preferences->acceleratedCompositingEnabled()) {
priv->preferences->setAcceleratedCompositingEnabled(true);
changed = true;
}
if (!priv->preferences->forceCompositingMode()) {
priv->preferences->setForceCompositingMode(true);
changed = true;
}
break;
case WEBKIT_HARDWARE_ACCELERATION_POLICY_NEVER:
if (HardwareAccelerationManager::singleton().forceHardwareAcceleration())
return;
if (priv->preferences->acceleratedCompositingEnabled()) {
priv->preferences->setAcceleratedCompositingEnabled(false);
changed = true;
}
if (priv->preferences->forceCompositingMode()) {
priv->preferences->setForceCompositingMode(false);
changed = true;
}
break;
case WEBKIT_HARDWARE_ACCELERATION_POLICY_ON_DEMAND:
if (!priv->preferences->acceleratedCompositingEnabled() && HardwareAccelerationManager::singleton().canUseHardwareAcceleration()) {
priv->preferences->setAcceleratedCompositingEnabled(true);
changed = true;
}
if (priv->preferences->forceCompositingMode() && !HardwareAccelerationManager::singleton().forceHardwareAcceleration()) {
priv->preferences->setForceCompositingMode(false);
changed = true;
}
break;
}
if (changed)
g_object_notify(G_OBJECT(settings), "hardware-acceleration-policy");
}
#endif // PLATFORM(GTK)
| 124,497 | 37,579 |
/*
* 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
*
* 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.
*/
/*
* $Id: DOM_RangeException.hpp 568078 2007-08-21 11:43:25Z amassari $
*/
#ifndef DOM_RangeException_HEADER_GUARD_
#define DOM_RangeException_HEADER_GUARD_
#include "DOM_DOMException.hpp"
XERCES_CPP_NAMESPACE_BEGIN
/**
* Encapsulate range related DOM error or warning. DOM level 2 implementation.
*
* <p> The DOM will create and throw an instance of DOM_RangeException
* when an error condition in range is detected. Exceptions can occur
* when an application directly manipulates the range elements in DOM document
* tree that is produced by the parser.
*
* <p>Unlike the other classes in the C++ DOM API, DOM_RangeException
* is NOT a reference to an underlying implementation class, and
* does not provide automatic memory management. Code that catches
* a DOM Range exception is responsible for deleting it, or otherwise
* arranging for its disposal.
*
*/
class DEPRECATED_DOM_EXPORT DOM_RangeException : public DOM_DOMException {
public:
/** @name Enumerators for DOM Range Exceptions */
//@{
enum RangeExceptionCode {
BAD_BOUNDARYPOINTS_ERR = 1,
INVALID_NODE_TYPE_ERR = 2
};
//@}
public:
/** @name Constructors and assignment operator */
//@{
/**
* Default constructor for DOM_RangeException.
*
*/
DOM_RangeException();
/**
* Constructor which takes an error code and a message.
*
* @param code The error code which indicates the exception
* @param message The string containing the error message
*/
DOM_RangeException(RangeExceptionCode code, const DOMString &message);
/**
* Copy constructor.
*
* @param other The object to be copied.
*/
DOM_RangeException(const DOM_RangeException &other);
//@}
/** @name Destructor. */
//@{
/**
* Destructor for DOM_RangeException. Applications are responsible
* for deleting DOM_RangeException objects that they catch after they
* have completed their exception processing.
*
*/
virtual ~DOM_RangeException();
//@}
/** @name Public variables. */
//@{
/**
* A code value, from the set defined by the RangeExceptionCode enum,
* indicating the type of error that occured.
*/
RangeExceptionCode code;
//@}
};
XERCES_CPP_NAMESPACE_END
#endif
| 3,283 | 983 |
// Copyright (c) 2016 ASMlover. All rights reserved.
//
// ____ __
// /\ _`\ /\ \
// \ \ \/\_\\ \ \___ __ ___ ____
// \ \ \/_/_\ \ _ `\ /'__`\ / __`\ /',__\
// \ \ \L\ \\ \ \ \ \/\ \L\.\_/\ \L\ \/\__, `\
// \ \____/ \ \_\ \_\ \__/.\_\ \____/\/\____/
// \/___/ \/_/\/_/\/__/\/_/\/___/ \/___/
//
// 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 ofconditions 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 materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include <memory>
#include <Chaos/Base/Copyable.hh>
namespace Chaos {
template <typename T, typename Allocator = std::allocator<char>>
class ContextRef : public Copyable {
struct Node {
std::shared_ptr<void> parent;
T value;
template <typename... Args>
Node(std::shared_ptr<void> p, Args&&... args)
: parent(std::move(p))
, value(std::forward<Args>(args)...) {
}
};
std::shared_ptr<Node> node_;
Allocator alloc_;
template <typename Y, typename YAllocator>
friend class ContextRef;
public:
using value_type = T;
using allocator_type = Allocator;
explicit ContextRef(const allocator_type& alloc) noexcept
: alloc_(alloc) {
}
template <typename... Args>
ContextRef(
std::shared_ptr<void> parent, const allocator_type& alloc, Args&&... args)
: node_(std::allocate_shared<Node>(
alloc, std::move(parent), std::forward<Args>(args)...))
, alloc_(alloc) {
}
ContextRef(const ContextRef& r) noexcept
: node_(r.node_)
, alloc_(r.alloc_) {
}
ContextRef(ContextRef&& r) noexcept
: node_(std::move(r.node_))
, alloc_(std::move(r.alloc_)) {
}
ContextRef& operator=(const ContextRef& r) noexcept {
node_ = r.node_;
alloc_ = r.alloc_;
return *this;
}
ContextRef& operator=(ContextRef&& r) noexcept {
node_ = std::move(r.node_);
alloc_ = std::move(r.alloc_);
return *this;
}
void swap(ContextRef& r) noexcept {
std::swap(node_, r.node_);
std::swap(alloc_, r.alloc_);
}
template <typename U, typename... Args>
ContextRef<U, Allocator> spawn(Args&&... args) const {
return ContextRef<U, Allocator>(node_, alloc_, std::forward<Args>(args)...);
}
template <typename U, typename UAllocator, typename... Args>
ContextRef<U, UAllocator> spawn_with_allocator(
const UAllocator& alloc, Args&&... args) const {
return ContextRef<U, UAllocator>(node_, alloc, std::forward<Args>(args)...);
}
std::shared_ptr<void> get_pointer(void) const {
return node_;
}
allocator_type get_allocator(void) const {
return alloc_;
}
T* get(void) {
return node_ == nullptr ? nullptr : &node_->value;
}
const T* get(void) const {
return node_ == nullptr ? nullptr : &node_->value;
}
T& operator*(void) {
return node_->value;
}
const T& operator*(void) const {
return node_->value;
}
T* operator->(void) {
return &node_->value;
}
const T* operator->(void) const {
return &node_->value;
}
explicit operator bool(void) const {
return node_ != nullptr;
}
ContextRef<void, Allocator> operator()(void) const {
return ContextRef<void, Allocator>(*this);
}
};
template <typename Allocator>
class ContextRef<void, Allocator> : public Copyable {
std::shared_ptr<void> node_;
Allocator alloc_;
public:
using value_type = void;
using allocator_type = Allocator;
explicit ContextRef(const allocator_type& alloc) noexcept
: alloc_(alloc) {
}
ContextRef(std::shared_ptr<void> parent, const allocator_type& alloc) noexcept
: node_(std::move(parent))
, alloc_(alloc) {
}
ContextRef(std::shared_ptr<void> parent) noexcept
: ContextRef(parent, Allocator()) {
}
ContextRef(const ContextRef& r) noexcept
: node_(r.node_)
, alloc_(r.alloc_) {
}
template <typename Y>
ContextRef(const ContextRef<Y, Allocator>& r) noexcept
: node_(r.node_)
, alloc_(r.alloc_) {
}
ContextRef(ContextRef&& r) noexcept
: node_(std::move(r.node_))
, alloc_(std::move(r.alloc_)) {
}
template <typename Y>
ContextRef(ContextRef<Y, Allocator>&& r) noexcept
: node_(std::move(r.node_))
, alloc_(std::move(r.alloc_)) {
}
ContextRef& operator=(const ContextRef& r) {
node_ = r.node_;
alloc_ = r.alloc_;
return *this;
}
template <typename Y>
ContextRef& operator=(const ContextRef<Y>& r) {
node_ = r.node_;
alloc_ = r.alloc_;
return *this;
}
ContextRef& operator=(ContextRef&& r) noexcept {
node_ = std::move(r.node_);
alloc_ = std::move(r.alloc_);
return *this;
}
template <typename Y>
ContextRef& operator=(ContextRef<Y>&& r) noexcept {
node_ = std::move(r.node_);
alloc_ = std::move(r.alloc_);
return *this;
}
ContextRef& operator=(std::shared_ptr<void> parent) noexcept {
node_ = std::move(parent);
return *this;
}
void swap(ContextRef& r) noexcept {
std::swap(node_, r.node_);
std::swap(alloc_, r.alloc_);
}
template <typename U, typename... Args>
ContextRef<U, Allocator> spawn(Args&&... args) const {
return ContextRef<U, Allocator>(node_, alloc_, std::forward<Args>(args)...);
}
template <typename U, typename UAllocator, typename... Args>
ContextRef<U, UAllocator> spawn_with_allocator(
const UAllocator& alloc, Args&&... args) const {
return ContextRef<U, UAllocator>(node_, alloc, std::forward<Args>(args)...);
}
std::shared_ptr<void> get_pointer(void) const {
return node_;
}
allocator_type get_allocator(void) const {
return alloc_;
}
explicit operator bool(void) const {
return node_ != nullptr;
}
ContextRef<void, Allocator> operator()(void) const {
return *this;
}
};
template <typename T, typename Allocator>
inline bool operator==(const ContextRef<T, Allocator>& p, std::nullptr_t) {
return !p;
}
template <typename T, typename Allocator>
inline bool operator==(std::nullptr_t, const ContextRef<T, Allocator>& p) {
return p == nullptr;
}
template <typename T, typename Allocator>
inline bool operator!=(const ContextRef<T, Allocator>& p, std::nullptr_t) {
return !(p == nullptr);
}
template <typename T, typename Allocator>
inline bool operator!=(std::nullptr_t, const ContextRef<T, Allocator>& p) {
return !(p == nullptr);
}
template <typename T, typename Allocator, typename... Args>
inline ContextRef<T, Allocator> make_context_with_allocator(
const Allocator& alloc, Args&&... args) {
return ContextRef<T, Allocator>(
std::shared_ptr<void>(), alloc, std::forward<Args>(args)...);
}
template <typename T,
typename Allocator = std::allocator<char>, typename... Args>
inline ContextRef<T, Allocator> make_context(Args&&... args) {
return make_context_with_allocator(Allocator(), std::forward<Args>(args)...);
}
}
| 7,976 | 2,890 |
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/common/validation_checker.h"
#include "modules/common/math/math_utils.h"
#include "modules/prediction/common/prediction_gflags.h"
namespace apollo {
namespace prediction {
using common::TrajectoryPoint;
double ValidationChecker::ProbabilityByCentripetalAcceleration(
const LaneSequence& lane_sequence, const double speed) {
double centripetal_acc_cost_sum = 0.0;
double centripetal_acc_cost_sqr_sum = 0.0;
for (int i = 0; i < lane_sequence.path_point_size(); ++i) {
const auto& path_point = lane_sequence.path_point(i);
double centripetal_acc = speed * speed * std::fabs(path_point.kappa());
double centripetal_acc_cost =
centripetal_acc / FLAGS_centripedal_acc_threshold;
centripetal_acc_cost_sum += centripetal_acc_cost;
centripetal_acc_cost_sqr_sum += centripetal_acc_cost * centripetal_acc_cost;
}
double mean_cost = centripetal_acc_cost_sqr_sum /
(centripetal_acc_cost_sum + FLAGS_double_precision);
return std::exp(-FLAGS_centripetal_acc_coeff * mean_cost);
}
bool ValidationChecker::ValidCentripetalAcceleration(
const std::vector<TrajectoryPoint>& trajectory_points) {
for (size_t i = 0; i + 1 < trajectory_points.size(); ++i) {
const auto& p0 = trajectory_points[i];
const auto& p1 = trajectory_points[i + 1];
double time_diff = std::abs(p1.relative_time() - p0.relative_time());
if (time_diff < FLAGS_double_precision) {
continue;
}
double theta_diff = std::abs(common::math::NormalizeAngle(
p1.path_point().theta() - p0.path_point().theta()));
double v = (p0.v() + p1.v()) * 0.5;
double angular_a = v * theta_diff / time_diff;
if (angular_a > FLAGS_centripedal_acc_threshold) {
return false;
}
}
return true;
}
bool ValidationChecker::ValidTrajectoryPoint(
const TrajectoryPoint& trajectory_point) {
return trajectory_point.has_path_point() &&
(!std::isnan(trajectory_point.path_point().x())) &&
(!std::isnan(trajectory_point.path_point().y())) &&
(!std::isnan(trajectory_point.path_point().theta())) &&
(!std::isnan(trajectory_point.v())) &&
(!std::isnan(trajectory_point.a())) &&
(!std::isnan(trajectory_point.relative_time()));
}
} // namespace prediction
} // namespace apollo
| 3,100 | 1,014 |
// Copyright 2020, Robotec.ai sp. z o.o.
//
// 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 <memory>
#include "rosbag2_cpp/cache/cache_consumer.hpp"
#include "rosbag2_cpp/logging.hpp"
namespace rosbag2_cpp
{
namespace cache
{
CacheConsumer::CacheConsumer(
std::shared_ptr<MessageCacheInterface> message_cache,
consume_callback_function_t consume_callback)
: message_cache_(message_cache),
consume_callback_(consume_callback)
{
consumer_thread_ = std::thread(&CacheConsumer::exec_consuming, this);
}
CacheConsumer::~CacheConsumer()
{
stop();
}
void CacheConsumer::stop()
{
message_cache_->begin_flushing();
is_stop_issued_ = true;
ROSBAG2_CPP_LOG_INFO_STREAM(
"Writing remaining messages from cache to the bag. It may take a while");
if (consumer_thread_.joinable()) {
consumer_thread_.join();
}
message_cache_->done_flushing();
}
void CacheConsumer::start()
{
is_stop_issued_ = false;
if (!consumer_thread_.joinable()) {
consumer_thread_ = std::thread(&CacheConsumer::exec_consuming, this);
}
}
void CacheConsumer::exec_consuming()
{
bool exit_flag = false;
bool flushing = false;
while (!exit_flag) {
message_cache_->wait_for_data();
message_cache_->swap_buffers();
// Get the current consumer buffer.
auto consumer_buffer = message_cache_->get_consumer_buffer();
consume_callback_(consumer_buffer->data());
consumer_buffer->clear();
message_cache_->release_consumer_buffer();
if (flushing) {exit_flag = true;} // this was the final run
if (is_stop_issued_) {flushing = true;} // run one final time to flush
}
}
} // namespace cache
} // namespace rosbag2_cpp
| 2,177 | 712 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Record implementation */
#include "sles_allinclusive.h"
static SLresult IRecord_SetRecordState(SLRecordItf self, SLuint32 state)
{
SL_ENTER_INTERFACE
switch (state) {
case SL_RECORDSTATE_STOPPED:
case SL_RECORDSTATE_PAUSED:
case SL_RECORDSTATE_RECORDING:
{
IRecord *thiz = (IRecord *) self;
interface_lock_exclusive(thiz);
thiz->mState = state;
#ifdef ANDROID
android_audioRecorder_setRecordState(InterfaceToCAudioRecorder(thiz), state);
#endif
interface_unlock_exclusive(thiz);
result = SL_RESULT_SUCCESS;
}
break;
default:
result = SL_RESULT_PARAMETER_INVALID;
break;
}
SL_LEAVE_INTERFACE
}
static SLresult IRecord_GetRecordState(SLRecordItf self, SLuint32 *pState)
{
SL_ENTER_INTERFACE
IRecord *thiz = (IRecord *) self;
if (NULL == pState) {
result = SL_RESULT_PARAMETER_INVALID;
} else {
interface_lock_shared(thiz);
SLuint32 state = thiz->mState;
interface_unlock_shared(thiz);
*pState = state;
result = SL_RESULT_SUCCESS;
}
SL_LEAVE_INTERFACE
}
static SLresult IRecord_SetDurationLimit(SLRecordItf self, SLmillisecond msec)
{
SL_ENTER_INTERFACE
IRecord *thiz = (IRecord *) self;
interface_lock_exclusive(thiz);
if (thiz->mDurationLimit != msec) {
thiz->mDurationLimit = msec;
interface_unlock_exclusive_attributes(thiz, ATTR_TRANSPORT);
} else {
interface_unlock_exclusive(thiz);
}
result = SL_RESULT_SUCCESS;
SL_LEAVE_INTERFACE
}
static SLresult IRecord_GetPosition(SLRecordItf self, SLmillisecond *pMsec)
{
SL_ENTER_INTERFACE
if (NULL == pMsec) {
result = SL_RESULT_PARAMETER_INVALID;
} else {
IRecord *thiz = (IRecord *) self;
SLmillisecond position;
interface_lock_shared(thiz);
#ifdef ANDROID
// Android does not use the mPosition field for audio recorders
if (SL_OBJECTID_AUDIORECORDER == InterfaceToObjectID(thiz)) {
android_audioRecorder_getPosition(InterfaceToCAudioRecorder(thiz), &position);
} else {
position = thiz->mPosition;
}
#else
position = thiz->mPosition;
#endif
interface_unlock_shared(thiz);
*pMsec = position;
result = SL_RESULT_SUCCESS;
}
SL_LEAVE_INTERFACE
}
static SLresult IRecord_RegisterCallback(SLRecordItf self, slRecordCallback callback,
void *pContext)
{
SL_ENTER_INTERFACE
IRecord *thiz = (IRecord *) self;
interface_lock_exclusive(thiz);
thiz->mCallback = callback;
thiz->mContext = pContext;
interface_unlock_exclusive(thiz);
result = SL_RESULT_SUCCESS;
SL_LEAVE_INTERFACE
}
static SLresult IRecord_SetCallbackEventsMask(SLRecordItf self, SLuint32 eventFlags)
{
SL_ENTER_INTERFACE
if (eventFlags & ~(
SL_RECORDEVENT_HEADATLIMIT |
SL_RECORDEVENT_HEADATMARKER |
SL_RECORDEVENT_HEADATNEWPOS |
SL_RECORDEVENT_HEADMOVING |
SL_RECORDEVENT_HEADSTALLED |
SL_RECORDEVENT_BUFFER_FULL)) {
result = SL_RESULT_PARAMETER_INVALID;
} else {
IRecord *thiz = (IRecord *) self;
interface_lock_exclusive(thiz);
if (thiz->mCallbackEventsMask != eventFlags) {
thiz->mCallbackEventsMask = eventFlags;
interface_unlock_exclusive_attributes(thiz, ATTR_TRANSPORT);
} else {
interface_unlock_exclusive(thiz);
}
result = SL_RESULT_SUCCESS;
}
SL_LEAVE_INTERFACE
}
static SLresult IRecord_GetCallbackEventsMask(SLRecordItf self, SLuint32 *pEventFlags)
{
SL_ENTER_INTERFACE
if (NULL == pEventFlags) {
result = SL_RESULT_PARAMETER_INVALID;
} else {
IRecord *thiz = (IRecord *) self;
interface_lock_shared(thiz);
SLuint32 callbackEventsMask = thiz->mCallbackEventsMask;
interface_unlock_shared(thiz);
*pEventFlags = callbackEventsMask;
result = SL_RESULT_SUCCESS;
}
SL_LEAVE_INTERFACE
}
static SLresult IRecord_SetMarkerPosition(SLRecordItf self, SLmillisecond mSec)
{
SL_ENTER_INTERFACE
if (SL_TIME_UNKNOWN == mSec) {
result = SL_RESULT_PARAMETER_INVALID;
} else {
IRecord *thiz = (IRecord *) self;
bool significant = false;
interface_lock_exclusive(thiz);
if (thiz->mMarkerPosition != mSec) {
thiz->mMarkerPosition = mSec;
if (thiz->mCallbackEventsMask & SL_PLAYEVENT_HEADATMARKER) {
significant = true;
}
}
if (significant) {
interface_unlock_exclusive_attributes(thiz, ATTR_TRANSPORT);
} else {
interface_unlock_exclusive(thiz);
}
result = SL_RESULT_SUCCESS;
}
SL_LEAVE_INTERFACE
}
static SLresult IRecord_ClearMarkerPosition(SLRecordItf self)
{
SL_ENTER_INTERFACE
IRecord *thiz = (IRecord *) self;
bool significant = false;
interface_lock_exclusive(thiz);
// clearing the marker position is equivalent to setting the marker to SL_TIME_UNKNOWN
if (thiz->mMarkerPosition != SL_TIME_UNKNOWN) {
thiz->mMarkerPosition = SL_TIME_UNKNOWN;
if (thiz->mCallbackEventsMask & SL_PLAYEVENT_HEADATMARKER) {
significant = true;
}
}
if (significant) {
interface_unlock_exclusive_attributes(thiz, ATTR_TRANSPORT);
} else {
interface_unlock_exclusive(thiz);
}
result = SL_RESULT_SUCCESS;
SL_LEAVE_INTERFACE
}
static SLresult IRecord_GetMarkerPosition(SLRecordItf self, SLmillisecond *pMsec)
{
SL_ENTER_INTERFACE
if (NULL == pMsec) {
result = SL_RESULT_PARAMETER_INVALID;
} else {
IRecord *thiz = (IRecord *) self;
interface_lock_shared(thiz);
SLmillisecond markerPosition = thiz->mMarkerPosition;
interface_unlock_shared(thiz);
*pMsec = markerPosition;
if (SL_TIME_UNKNOWN == markerPosition) {
result = SL_RESULT_PRECONDITIONS_VIOLATED;
} else {
result = SL_RESULT_SUCCESS;
}
}
SL_LEAVE_INTERFACE
}
static SLresult IRecord_SetPositionUpdatePeriod(SLRecordItf self, SLmillisecond mSec)
{
SL_ENTER_INTERFACE
if (0 == mSec) {
result = SL_RESULT_PARAMETER_INVALID;
} else {
IRecord *thiz = (IRecord *) self;
interface_lock_exclusive(thiz);
if (thiz->mPositionUpdatePeriod != mSec) {
thiz->mPositionUpdatePeriod = mSec;
interface_unlock_exclusive_attributes(thiz, ATTR_TRANSPORT);
} else {
interface_unlock_exclusive(thiz);
}
result = SL_RESULT_SUCCESS;
}
SL_LEAVE_INTERFACE
}
static SLresult IRecord_GetPositionUpdatePeriod(SLRecordItf self, SLmillisecond *pMsec)
{
SL_ENTER_INTERFACE
if (NULL == pMsec) {
result = SL_RESULT_PARAMETER_INVALID;
} else {
IRecord *thiz = (IRecord *) self;
interface_lock_shared(thiz);
SLmillisecond positionUpdatePeriod = thiz->mPositionUpdatePeriod;
interface_unlock_shared(thiz);
*pMsec = positionUpdatePeriod;
result = SL_RESULT_SUCCESS;
}
SL_LEAVE_INTERFACE
}
static const struct SLRecordItf_ IRecord_Itf = {
IRecord_SetRecordState,
IRecord_GetRecordState,
IRecord_SetDurationLimit,
IRecord_GetPosition,
IRecord_RegisterCallback,
IRecord_SetCallbackEventsMask,
IRecord_GetCallbackEventsMask,
IRecord_SetMarkerPosition,
IRecord_ClearMarkerPosition,
IRecord_GetMarkerPosition,
IRecord_SetPositionUpdatePeriod,
IRecord_GetPositionUpdatePeriod
};
void IRecord_init(void *self)
{
IRecord *thiz = (IRecord *) self;
thiz->mItf = &IRecord_Itf;
thiz->mState = SL_RECORDSTATE_STOPPED;
thiz->mDurationLimit = 0;
thiz->mPosition = (SLmillisecond) 0;
thiz->mCallback = NULL;
thiz->mContext = NULL;
thiz->mCallbackEventsMask = 0;
thiz->mMarkerPosition = SL_TIME_UNKNOWN;
thiz->mPositionUpdatePeriod = 1000; // per spec
}
| 8,742 | 2,993 |
/* ----------------------------------------------------------------------------
* GTSAM Copyright 2010, Georgia Tech Research Corporation,
* Atlanta, Georgia 30332-0415
* All Rights Reserved
* Authors: Frank Dellaert, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/*
* @file testDecisionTreeFactor.cpp
* @brief unit tests for DiscreteConditional
* @author Duy-Nguyen Ta
* @date Feb 14, 2011
*/
#include <boost/assign/std/map.hpp>
#include <boost/assign/std/vector.hpp>
#include <boost/make_shared.hpp>
using namespace boost::assign;
#include <CppUnitLite/TestHarness.h>
#include <gtsam/discrete/DecisionTreeFactor.h>
#include <gtsam/discrete/DiscreteConditional.h>
using namespace std;
using namespace gtsam;
/* ************************************************************************* */
TEST( DiscreteConditional, constructors)
{
DiscreteKey X(0, 2), Y(2, 3), Z(1, 2); // watch ordering !
DiscreteConditional::shared_ptr expected1 = //
boost::make_shared<DiscreteConditional>(X | Y = "1/1 2/3 1/4");
EXPECT(expected1);
EXPECT_LONGS_EQUAL(0, *(expected1->beginFrontals()));
EXPECT_LONGS_EQUAL(2, *(expected1->beginParents()));
EXPECT(expected1->endParents() == expected1->end());
EXPECT(expected1->endFrontals() == expected1->beginParents());
DecisionTreeFactor f1(X & Y, "0.5 0.4 0.2 0.5 0.6 0.8");
DiscreteConditional actual1(1, f1);
EXPECT(assert_equal(*expected1, actual1, 1e-9));
DecisionTreeFactor f2(X & Y & Z,
"0.2 0.5 0.3 0.6 0.4 0.7 0.25 0.55 0.35 0.65 0.45 0.75");
DiscreteConditional actual2(1, f2);
EXPECT(assert_equal(f2 / *f2.sum(1), *actual2.toFactor(), 1e-9));
}
/* ************************************************************************* */
TEST(DiscreteConditional, constructors_alt_interface) {
DiscreteKey X(0, 2), Y(2, 3), Z(1, 2); // watch ordering !
Signature::Table table;
Signature::Row r1, r2, r3;
r1 += 1.0, 1.0;
r2 += 2.0, 3.0;
r3 += 1.0, 4.0;
table += r1, r2, r3;
auto actual1 = boost::make_shared<DiscreteConditional>(X | Y = table);
EXPECT(actual1);
DecisionTreeFactor f1(X & Y, "0.5 0.4 0.2 0.5 0.6 0.8");
DiscreteConditional expected1(1, f1);
EXPECT(assert_equal(expected1, *actual1, 1e-9));
DecisionTreeFactor f2(
X & Y & Z, "0.2 0.5 0.3 0.6 0.4 0.7 0.25 0.55 0.35 0.65 0.45 0.75");
DiscreteConditional actual2(1, f2);
EXPECT(assert_equal(f2 / *f2.sum(1), *actual2.toFactor(), 1e-9));
}
/* ************************************************************************* */
TEST(DiscreteConditional, constructors2) {
// Declare keys and ordering
DiscreteKey C(0, 2), B(1, 2);
DecisionTreeFactor actual(C & B, "0.8 0.75 0.2 0.25");
Signature signature((C | B) = "4/1 3/1");
DiscreteConditional expected(signature);
DecisionTreeFactor::shared_ptr expectedFactor = expected.toFactor();
EXPECT(assert_equal(*expectedFactor, actual));
}
/* ************************************************************************* */
TEST(DiscreteConditional, constructors3) {
// Declare keys and ordering
DiscreteKey C(0, 2), B(1, 2), A(2, 2);
DecisionTreeFactor actual(C & B & A, "0.8 0.5 0.5 0.2 0.2 0.5 0.5 0.8");
Signature signature((C | B, A) = "4/1 1/1 1/1 1/4");
DiscreteConditional expected(signature);
DecisionTreeFactor::shared_ptr expectedFactor = expected.toFactor();
EXPECT(assert_equal(*expectedFactor, actual));
}
/* ************************************************************************* */
TEST(DiscreteConditional, Combine) {
DiscreteKey A(0, 2), B(1, 2);
vector<DiscreteConditional::shared_ptr> c;
c.push_back(boost::make_shared<DiscreteConditional>(A | B = "1/2 2/1"));
c.push_back(boost::make_shared<DiscreteConditional>(B % "1/2"));
DecisionTreeFactor factor(A & B, "0.111111 0.444444 0.222222 0.222222");
DiscreteConditional actual(2, factor);
auto expected = DiscreteConditional::Combine(c.begin(), c.end());
EXPECT(assert_equal(*expected, actual, 1e-5));
}
/* ************************************************************************* */
int main() {
TestResult tr;
return TestRegistry::runAllTests(tr);
}
/* ************************************************************************* */
| 4,302 | 1,642 |
#include <torch/script.h> // One-stop header.
#include <torch/torch.h>
#include <chrono>
#include <iostream>
#include <memory>
using Time = decltype(std::chrono::high_resolution_clock::now());
Time time() {return std::chrono::high_resolution_clock::now();};
double
time_diff(Time t1, Time t2)
{
typedef std::chrono::microseconds ms;
auto diff = t2 - t1;
ms counter = std::chrono::duration_cast<ms>(diff);
return counter.count() / 1000.0;
}
bool
test_predictor_latency(const char* argv[])
{
auto model_path = argv[1];
int batch_size = 64;
int repeat = 100;
bool use_gpu = true;
torch::Device device = torch::kCPU;
if (torch::cuda::is_available() && use_gpu){
std::cout << "CUDA is available, running on GPU" << std::endl;
device = torch::Device("cuda:5");
}
std::cout << "start to load model from " << argv[1] << std::endl;
torch::jit::script::Module module = torch::jit::load(argv[1]);
module.to(device);
std::cout << "create input tensor..." << std::endl;
// Create a vector of inputs.
std::vector<torch::jit::IValue> inputs;
inputs.push_back(torch::ones({20, batch_size}, at::kLong).to(device));
inputs.push_back(torch::ones({20, batch_size, 200}).to(device));
inputs.push_back(torch::ones({20, batch_size, 200}).to(device));
// warmup
std::cout << "warm up..." << std::endl;
auto output = module.forward(inputs);
std::cout << "start to inference..." << std::endl;
Time time1 = time();
for(int i=0; i < repeat; ++i){
auto output = module.forward(inputs);
}
auto time2 = time();
std::cout << "repeat time: " << repeat << " , model: " << model_path << std::endl;
std::cout << "batch: " << batch_size << " , predict cost: " << time_diff(time1, time2) / static_cast<float>(repeat) << " ms." << std::endl;
}
int main(int argc, const char* argv[]) {
if (argc < 2) {
std::cerr << "usage: ./exe model_dir_name\n";
return -1;
}
test_predictor_latency(argv);
}
| 2,063 | 757 |
#ifndef XPCC_LPC111X__ADC_HPP
#define XPCC_LPC111X__ADC_HPP
#include "../device.h"
/* ---------- ADC Data Register bit names --------------------*/
#define ADC_GDR_DONE (1 << 31)
#define ADC_DR_DONE ADC_GDR_DONE
/* ---------- ADC Control Register bit names ------------------*/
#define ADC_CR_SEL_MASK (0xff << 0) ///< Mask for deleting Channel selection
#define ADC_CR_BURST ( 1 << 16) ///< Burst mode
#define ADC_CR_START_NOW (0x1 << 24) ///< Manually start a conversion now
#define ADC_CR_START_PIO0_2 (0x2 << 24) ///< Start conversion whenever the selected edge on PIO0_2 occurs
#define ADC_CR_START_PIO1_5 (0x3 << 24) ///< Start conversion whenever the selected edge on PIO1_5 occurs
#define ADC_CR_START_CT32B0_MAT0 (0x4 << 24) ///< Start conversion whenever the selected edge on CT32B0_MAT0 occurs (timer match)
#define ADC_CR_START_CT32B0_MAT1 (0x5 << 24) ///< Start conversion whenever the selected edge on CT32B0_MAT1 occurs (timer match)
#define ADC_CR_START_CT16B0_MAT0 (0x6 << 24) ///< Start conversion whenever the selected edge on CT16B0_MAT0 occurs (timer match)
#define ADC_CR_START_CT16B0_MAT1 (0x7 << 24) ///< Start conversion whenever the selected edge on CT16B0_MAT1 occurs (timer match)
#define ADC_CR_EDGE_RISING ( 0 << 27) ///< Start conversion whenever a rising edge occurs
#define ADC_CR_EDGE_FALLING ( 1 << 27) ///< Start conversion whenever a falling edge occurs
#define ADC_CR_START_EDGE_MASK ADC_CR_START_CT16B0_MAT1 | ADC_CR_EDGE_FALLING
/* ---------- ADC Status Register bit names -------------------*/
#define ADC_STAT_DONE_MASK ( 0xff) ///< Individual DONE flags for channels 7 to 0.
/* ---------- ADC INterrtup Enable Register bit names ---------*/
#define ADC_INTEN_ADGINTEN ( 1 << 8) ///< Interrupt when global DONE is 1
/* ---------- Power-down configuration register bit names -----*/
#define PDRUNCFG_ADC_PD (1 << 4)
/* ---------- System AHB clock control register bit names -----*/
#define SYSAHBCLKCTRL_ADC (1 << 13)
#define ADC_OFFSET 0x10
#define ADC_INDEX 4
namespace xpcc
{
namespace lpc
{
/**
* \brief Analog-to-Digital Converter Module of
* LPC111x, LPC11D14 and LPC11Cxx parts.
*
* Two usage scenarios where considered when designing this class:
*
* 1) Manual control: Single Channel, Single Shot
* From a given set of channels a conversion can be started
* manually and the result is fetched after waiting for the
* ADC to finish this single channel. The ADC stops after
* this sample automatically.
* When using timers or external pins as a start condition repeated
* conversion can be achieved.
*
* 2) Automatic mode: Multiple Channels, automatic repeat
* Some channels are selected to be sampled automatically.
* The latest result can be fetched by polling or an interrupt
* handler can be installed.
*
* Whats not possible by hardware: convert multiple channels
* triggered by a timer. When triggered by a timer only a single
* channel (BURST = 0) can be selected.
*
* AD4 is not supported because the pin is used by the Serial Wire
* Debug interface.
*
* TOOD:
* - Overrun flag support
* - Enable/Disable/Test Interrupts
* - Clock setting depending on the CPU frequency. 48 MHz is used now.
*/
class Adc
{
public:
/**
* \brief Channels which can be used as ADC input.
*
* You can specify the channel by using a pin-name, like PIO0_11
* or just the plain channel number, like CHANNEL_0.
*
* ChannelMask corresponds directly to the bitmask in the ADC module
* Channel can be casted to and from an integer.
*
*/
enum class ChannelMask
{
PIO0_11 = 0x01,
PIO1_0 = 0x02,
PIO1_1 = 0x04,
PIO1_2 = 0x08,
// PIO1_3 = 0x10,
PIO1_4 = 0x20,
PIO1_10 = 0x40,
PIO1_11 = 0x80,
CHANNEL_0 = 0x01,
CHANNEL_1 = 0x02,
CHANNEL_2 = 0x04,
CHANNEL_3 = 0x08,
// CHANNEL_4 = 0x10,
CHANNEL_5 = 0x20,
CHANNEL_6 = 0x40,
CHANNEL_7 = 0x80,
};
enum class Channel
{
PIO0_11 = 0,
PIO1_0 = 1,
PIO1_1 = 2,
PIO1_2 = 3,
// PIO1_3 = 4,
PIO1_4 = 5,
PIO1_10 = 6,
PIO1_11 = 7,
CHANNEL_0 = 0,
CHANNEL_1 = 1,
CHANNEL_2 = 2,
CHANNEL_3 = 3,
// CHANNEL_4 = 4,
CHANNEL_5 = 5,
CHANNEL_6 = 6,
CHANNEL_7 = 7,
};
/**
* \brief Configure the selected channels as analog input.
*
* \param channelBitmask Select which channels are configured
* by a bitmask. The corresponding IO pins
* are changed to analog mode.
*/
static void inline
configurePins(uint8_t channelBitmask = 0xff)
{
if (channelBitmask & 0x01) {
LPC_IOCON->R_PIO0_11 = 0x02; /* ADC IN0 */
}
if (channelBitmask & 0x02) {
LPC_IOCON->R_PIO1_0 = 0x02; /* ADC IN1 */
}
if (channelBitmask & 0x04) {
LPC_IOCON->R_PIO1_1 = 0x02; /* ADC IN2 */
}
if (channelBitmask & 0x08) {
LPC_IOCON->R_PIO1_2 = 0x02; /* ADC IN3 */
}
// if (channelBitmask & 0x10) {}
if (channelBitmask & 0x20) {
LPC_IOCON->PIO1_4 = 0x01; // Select AD5 pin function
}
if (channelBitmask & 0x40) {
LPC_IOCON->PIO1_10 = 0x01; // Select AD6 pin function
}
if (channelBitmask & 0x80) {
LPC_IOCON->PIO1_11 = 0x01; // Select AD7 pin function
}
}
protected:
/**
* \brief Read a ADC data register. Clears DONE and OVERRUN flags.
*/
static inline uint32_t
getAdcRegister(Channel channel)
{
return (*(volatile unsigned long *)
(LPC_ADC_BASE + ADC_OFFSET + ADC_INDEX * static_cast<uint8_t>(channel)));
}
};
/**
* \brief Implementation of the Manual Single Mode.
*
* Use all the common features from Adc class.
*/
class AdcManualSingle : public Adc
{
public:
/**
* \brief Start condition of the ADC.
*
* Only in software controlled mode a start condition can be given.
* If the conversion is started manually with START_NOW only one
* conversion is made.
* If a hardware source as a start condition is selected repeated
* samples can be generated if this condition appears regularly
* (e.g. repeated timer match)
*/
enum class StartCondition
{
START_NOW = ADC_CR_START_NOW, ///< Manually start a conversion now
START_PIO0_2 = ADC_CR_START_PIO0_2, ///< Start conversion whenever the selected edge on PIO0_2 occurs
START_PIO1_5 = ADC_CR_START_PIO1_5, ///< Start conversion whenever the selected edge on PIO1_5 occurs
START_CT32B0_MAT0 = ADC_CR_START_CT32B0_MAT0, ///< Start conversion whenever the selected edge on CT32B0_MAT0 occurs (timer match)
START_CT32B0_MAT1 = ADC_CR_START_CT32B0_MAT1, ///< Start conversion whenever the selected edge on CT32B0_MAT1 occurs (timer match)
START_CT16B0_MAT0 = ADC_CR_START_CT16B0_MAT0, ///< Start conversion whenever the selected edge on CT16B0_MAT0 occurs (timer match)
START_CT16B0_MAT1 = ADC_CR_START_CT16B0_MAT1, ///< Start conversion whenever the selected edge on CT16B0_MAT1 occurs (timer match)
};
enum class StartEdge
{
RISING = ADC_CR_EDGE_RISING,
FALLING = ADC_CR_EDGE_FALLING,
};
/**
* \brief Initialise the ADC block in Manual Single Mode.
*/
static void inline
initialize()
{
/* Disable Power down bit to the ADC block. */
LPC_SYSCON->PDRUNCFG &= ~(PDRUNCFG_ADC_PD);
/* Enable AHB clock to the ADC. */
LPC_SYSCON->SYSAHBCLKCTRL |= SYSAHBCLKCTRL_ADC;
/* Set clock: 48 MHz / (10 + 1) = 4.36 MHz < 4.5 MHz */
LPC_ADC->CR = (10 << 8);
}
/**
* \brief Start a single conversion of the single selected channel.
*/
static inline void
startConversion(
ChannelMask channelMask,
StartCondition startCondition = StartCondition::START_NOW,
StartEdge startEdge = StartEdge::RISING)
{
// clear and then select channel bits
LPC_ADC->CR &= ~(ADC_CR_SEL_MASK | ADC_CR_START_EDGE_MASK);
LPC_ADC->CR |=
static_cast<uint32_t>(startCondition) |
static_cast<uint32_t>(startEdge) |
static_cast<uint32_t>(channelMask);
}
/**
* \brief Check if the conversion is finished.
*/
static inline bool
isConversionFinished(void)
{
return (LPC_ADC->GDR & ADC_GDR_DONE);
}
/**
* \brief Get the latest value from the ADC from the global data register
*/
static inline uint16_t
getValue()
{
// Result is left adjusted to a 16 bit boundary
// Convert to right adjusted value.
return ((LPC_ADC->GDR & 0xffff) >> 6);
}
/**
* \brief Get the latest value from the ADC from the channel register. Clear the interrupt flag.
*/
static inline uint16_t
getValue(Channel channel)
{
return ((getAdcRegister(channel) & 0xffff) >> 6);
}
static inline bool
read(uint16_t & val)
{
if (isConversionFinished()) {
val = getValue();
return true;
}
else {
return false;
}
}
/**
* Clear the interrupt flag of the given channel.
*/
static inline void
clearInterruptFlag(Channel channel)
{
// just read to clear flag
getAdcRegister(channel);
}
};
/**
* \brief Converting multiple channels in free running mode
*/
class AdcAutomaticBurst : public Adc
{
public:
/**
* \brief Resolution of the successive-approximation ADC.
*/
enum class Resolution
{
BITS_10 = (0x0 << 17), ///< 11 clocks / 10 bits
BITS_9 = (0x1 << 17), ///< 10 clocks / 9 bits
BITS_8 = (0x2 << 17), ///< 9 clocks / 8 bits
BITS_7 = (0x3 << 17), ///< 8 clocks / 7 bits
BITS_6 = (0x4 << 17), ///< 7 clocks / 6 bits
BITS_5 = (0x5 << 17), ///< 6 clocks / 5 bits
BITS_4 = (0x6 << 17), ///< 5 clocks / 4 bits
BITS_3 = (0x7 << 17), ///< 4 clocks / 3 bits
};
/**
* \brief Initialise the ADC module in free running mode.
*
* \param resolution More bits mean lower conversion rate.
*/
static inline void
initialize (Resolution resolution = Resolution::BITS_10)
{
/* Disable Power down bit to the ADC block. */
LPC_SYSCON->PDRUNCFG &= ~(PDRUNCFG_ADC_PD);
/* Enable AHB clock to the ADC. */
LPC_SYSCON->SYSAHBCLKCTRL |= SYSAHBCLKCTRL_ADC;
/* Disable ADGINTEN in INTEN */
LPC_ADC->INTEN &= ~ADC_INTEN_ADGINTEN;
/* Set clock and resolution */
LPC_ADC->CR = (static_cast<uint32_t>(resolution)) | (10 << 8);
/* Enable interrupts */
NVIC_EnableIRQ(ADC_IRQn);
}
/**
* \brief Start a conversion of the selected channel(s).
*
* The conversion is repeated automatically.
* When using interrupts it may be a good idea to set only on bit in the
* interruptMask to generate an interrupt when all channels are converted once.
*
* \param channelMask Bitmask of the channels that should be converted
* \param interruptMask Bitmask of channels that will generate an interrupt.
*/
static inline void
startConversion(uint8_t channelMask, uint8_t interruptMask = 0)
{
// clear and then set the interrupt Mask, ADGINEN is cleared, too.
LPC_ADC->INTEN = 0;
LPC_ADC->INTEN = interruptMask;
// clear and then select channel bits
LPC_ADC->CR &= ~(ADC_CR_SEL_MASK | ADC_CR_START_EDGE_MASK);
LPC_ADC->CR |= channelMask;
// Set burst to start conversion now.
LPC_ADC->CR |= ADC_CR_BURST;
}
/**
* \brief Check if a single channel has finished
*/
static inline bool
isConversionFinished(Channel channel)
{
return (getAdcRegister(channel) & ADC_DR_DONE);
}
/**
* \brief Check if a group of channels have finished.
*
* Can be used for a single channel too if the ChannelMask is known.
*/
static inline bool
isConversionFinished(uint8_t channelMask)
{
return ((LPC_ADC->STAT & ADC_STAT_DONE_MASK) & channelMask);
}
/**
* \brief Get the value of a single channel. Check before if result is ready.
*/
static inline uint16_t
getValue(Channel channel)
{
return ((getAdcRegister(channel) & 0xffff) >> 6);
}
/**
* \brief Returns true if the value is ready and puts it into the variable.
*/
static inline bool
read(uint16_t & val, Channel channel)
{
uint32_t reg = getAdcRegister(channel);
if (reg & ADC_DR_DONE) {
val = (reg & 0xffff) >> 6;
return true;
}
else {
return false;
}
}
};
} // namespace lpc
}
#endif // XPCC_LPC111X__ADC_HPP
| 12,580 | 5,703 |
template<typename C>
void print2nd(const C& container) {
if (container.size() > 2) {
C::const_iterator iter(container.begin());
...
}
} | 147 | 52 |
#include "SimpleRenderModeFactory.h"
#include "LoggerAPI.h"
#include "Vertex.h"
#include <array>
#include <cassert>
using std::array;
SimpleRenderModeFactory::SimpleRenderModeFactory(GPUPtr &gpu, const ScenePtr &scene) :
m_gpu(gpu),
m_scene(scene)
{
}
SimpleRenderMode SimpleRenderModeFactory::createRenderMode(vk::Format swapchainFormat, vk::Extent2D extent, const std::vector<vk::PipelineShaderStageCreateInfo> &shaders)
{
bool succeed = createRenderPass(swapchainFormat);
assert(succeed);
createPipelineLayout();
auto viewport = vk::Viewport();
viewport.setWidth((float)extent.width);
viewport.setHeight((float)extent.height);
viewport.setX(0);
viewport.setY(0);
viewport.setMinDepth(0.0f);
viewport.setMaxDepth(1.0f);
auto scissors = vk::Rect2D();
scissors.setOffset({ 0,0 });
scissors.setExtent(extent);
succeed = createPipeline(shaders, viewport, scissors);
assert(succeed);
succeed = createSwapchain(extent);
assert(succeed);
createCommandPool();
recordCommandBuffers();
return m_result;
}
void SimpleRenderModeFactory::recordCommandBuffers()
{
m_result.commandBuffers.resize(m_result.swapchainFramebuffers.size());
auto commandBufferAllocInfo = vk::CommandBufferAllocateInfo();
commandBufferAllocInfo.setCommandBufferCount(static_cast<uint32_t>(m_result.commandBuffers.size()));
commandBufferAllocInfo.setCommandPool(m_result.commandPool);
commandBufferAllocInfo.setLevel(vk::CommandBufferLevel::ePrimary);
m_gpu->createCommandBuffers(commandBufferAllocInfo, m_result.commandBuffers.data());
for (size_t i = 0; i < m_result.commandBuffers.size(); ++i)
{
auto beginInfo = vk::CommandBufferBeginInfo();
beginInfo.setFlags(vk::CommandBufferUsageFlagBits::eSimultaneousUse);
if (vk::Result::eSuccess != m_result.commandBuffers[i].begin(&beginInfo))
{
LoggerAPI::getLogger()->logCritical("Could not begin record command buffer");
}
auto renderPassBeginInfo = vk::RenderPassBeginInfo();
renderPassBeginInfo.setRenderPass(m_result.renderPass);
renderPassBeginInfo.setFramebuffer(m_result.swapchainFramebuffers[i]);
auto renderArea = vk::Rect2D({ 0,0 }, m_gpu->getPresentationExtent());
renderPassBeginInfo.setRenderArea(renderArea);
renderPassBeginInfo.setClearValueCount(1);
vk::ClearValue clearValues[] = { 0.0, 0.0, 0.0, 1.0 };
renderPassBeginInfo.setPClearValues(clearValues);
m_result.commandBuffers[i].beginRenderPass(renderPassBeginInfo, vk::SubpassContents::eInline);
m_result.commandBuffers[i].bindPipeline(vk::PipelineBindPoint::eGraphics, m_result.pipeline);
for (const auto &ro : m_scene->renderableObjects)
{
vk::DeviceSize offset[] = { 0 };
m_result.commandBuffers[i].bindVertexBuffers(0, 1, &ro->sharedBuffer, offset);
m_result.commandBuffers[i].bindIndexBuffer(ro->sharedBuffer, ro->vertexOffset, vk::IndexType::eUint32);
m_result.commandBuffers[i].drawIndexed(ro->indexCount, 1, 0, 0, 0);
}
m_result.commandBuffers[i].endRenderPass();
m_result.commandBuffers[i].end();
}
}
bool SimpleRenderModeFactory::createRenderPass(vk::Format swapchainFormat)
{
auto colorAttachment = vk::AttachmentDescription();
colorAttachment.setFormat(swapchainFormat);
colorAttachment.setSamples(vk::SampleCountFlagBits::e1);
colorAttachment.setLoadOp(vk::AttachmentLoadOp::eClear);
colorAttachment.setStoreOp(vk::AttachmentStoreOp::eStore);
colorAttachment.setStencilLoadOp(vk::AttachmentLoadOp::eDontCare);
colorAttachment.setStencilStoreOp(vk::AttachmentStoreOp::eDontCare);
colorAttachment.setInitialLayout(vk::ImageLayout::eUndefined);
colorAttachment.setFinalLayout(vk::ImageLayout::ePresentSrcKHR);
auto attatchmentRef = vk::AttachmentReference();
attatchmentRef.setAttachment(0);
attatchmentRef.setLayout(vk::ImageLayout::eColorAttachmentOptimal);
auto subpassDesc = vk::SubpassDescription();
subpassDesc.setPipelineBindPoint(vk::PipelineBindPoint::eGraphics);
subpassDesc.setColorAttachmentCount(1);
subpassDesc.setPColorAttachments(&attatchmentRef);
auto subpassDependency = vk::SubpassDependency();
subpassDependency.setSrcSubpass(VK_SUBPASS_EXTERNAL);
subpassDependency.setDstSubpass(0);
subpassDependency.setSrcStageMask(vk::PipelineStageFlags(vk::PipelineStageFlagBits::eColorAttachmentOutput));
subpassDependency.setSrcAccessMask(vk::AccessFlags(0));
subpassDependency.setDstStageMask(vk::PipelineStageFlags(vk::PipelineStageFlagBits::eColorAttachmentOutput));
subpassDependency.setDstAccessMask(vk::AccessFlags(vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite));
auto renderPassInfo = vk::RenderPassCreateInfo();
renderPassInfo.setSubpassCount(1);
renderPassInfo.setPSubpasses(&subpassDesc);
renderPassInfo.setAttachmentCount(1);
renderPassInfo.setPAttachments(&colorAttachment);
renderPassInfo.setDependencyCount(1);
renderPassInfo.setPDependencies(&subpassDependency);
m_gpu->createRenderPass(renderPassInfo, m_result.renderPass);
return true;
}
void SimpleRenderModeFactory::createPipelineLayout()
{
auto layoutCreateInfo = vk::PipelineLayoutCreateInfo();
layoutCreateInfo.setSetLayoutCount(0);
layoutCreateInfo.setPushConstantRangeCount(0);
m_gpu->createPipelineLayout(layoutCreateInfo, m_result.pipelineLayout);
}
bool SimpleRenderModeFactory::createPipeline(const std::vector<vk::PipelineShaderStageCreateInfo> &shaders, const vk::Viewport &viewport, const vk::Rect2D &scissors)
{
auto pipelineCreateInfo = vk::GraphicsPipelineCreateInfo();
pipelineCreateInfo.setStageCount(static_cast<uint32_t>(shaders.size()));
pipelineCreateInfo.setPStages(shaders.data());
auto bindingDescription = new vk::VertexInputBindingDescription();
bindingDescription->setBinding(0);
bindingDescription->setInputRate(vk::VertexInputRate::eVertex);
bindingDescription->setStride(sizeof(Vertex));
auto attributeDescriptions = array<vk::VertexInputAttributeDescription, 2>();
attributeDescriptions.at(0).setBinding(0);
attributeDescriptions.at(0).setFormat(vk::Format::eR32G32B32Sfloat);
attributeDescriptions.at(0).setLocation(0);
attributeDescriptions.at(0).setOffset(offsetof(Vertex, Vertex::postion));
attributeDescriptions.at(1).setBinding(0);
attributeDescriptions.at(1).setFormat(vk::Format::eR32G32B32A32Sfloat);
attributeDescriptions.at(1).setLocation(1);
attributeDescriptions.at(1).setOffset(offsetof(Vertex, Vertex::color));
auto vertexInputState = vk::PipelineVertexInputStateCreateInfo();
vertexInputState.setPVertexAttributeDescriptions(attributeDescriptions.data());
vertexInputState.setPVertexBindingDescriptions(bindingDescription);
vertexInputState.setVertexAttributeDescriptionCount(static_cast<uint32_t>(attributeDescriptions.size()));
vertexInputState.setVertexBindingDescriptionCount(1);
pipelineCreateInfo.setPVertexInputState(&vertexInputState);
auto inputAssemblyState = vk::PipelineInputAssemblyStateCreateInfo();
inputAssemblyState.setTopology(vk::PrimitiveTopology::eTriangleList);
inputAssemblyState.setPrimitiveRestartEnable(false);
pipelineCreateInfo.setPInputAssemblyState(&inputAssemblyState);
auto viewportState = vk::PipelineViewportStateCreateInfo();
viewportState.setViewportCount(1);
viewportState.setScissorCount(1);
viewportState.setPScissors(&scissors);
viewportState.setPViewports(&viewport);
pipelineCreateInfo.setPViewportState(&viewportState);
auto rasteizerState = vk::PipelineRasterizationStateCreateInfo();
rasteizerState.setDepthClampEnable(false);
rasteizerState.setRasterizerDiscardEnable(false);
rasteizerState.setPolygonMode(vk::PolygonMode::eFill);
rasteizerState.setLineWidth(1.0f);
rasteizerState.setCullMode(vk::CullModeFlagBits::eBack);
rasteizerState.setFrontFace(vk::FrontFace::eClockwise);
rasteizerState.setDepthBiasEnable(false);
pipelineCreateInfo.setPRasterizationState(&rasteizerState);
auto multisampleState = vk::PipelineMultisampleStateCreateInfo();
multisampleState.setSampleShadingEnable(false);
multisampleState.setRasterizationSamples(vk::SampleCountFlagBits::e1);
pipelineCreateInfo.setPMultisampleState(&multisampleState);
pipelineCreateInfo.setPDepthStencilState(nullptr);
auto attachState = vk::PipelineColorBlendAttachmentState();
attachState.setColorWriteMask(vk::ColorComponentFlags(vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA));
attachState.setBlendEnable(false);
attachState.setSrcAlphaBlendFactor(vk::BlendFactor::eOne);
attachState.setDstAlphaBlendFactor(vk::BlendFactor::eZero);
attachState.setColorBlendOp(vk::BlendOp::eAdd);
attachState.setAlphaBlendOp(vk::BlendOp::eAdd);
auto colorBlendState = vk::PipelineColorBlendStateCreateInfo();
colorBlendState.setLogicOpEnable(false);
colorBlendState.setLogicOp(vk::LogicOp::eCopy);
colorBlendState.setBlendConstants({ 0.0f, 0.0f, 0.0f, 0.0f });
colorBlendState.setAttachmentCount(1);
colorBlendState.setPAttachments(&attachState);
pipelineCreateInfo.setPColorBlendState(&colorBlendState);
pipelineCreateInfo.setPDynamicState(nullptr); //not supported
pipelineCreateInfo.setLayout(m_result.pipelineLayout);
pipelineCreateInfo.setRenderPass(m_result.renderPass);
pipelineCreateInfo.setSubpass(0);
m_gpu->createPipeline(pipelineCreateInfo, m_result.pipeline);
return true;
}
bool SimpleRenderModeFactory::createSwapchain(vk::Extent2D extent)
{
m_result.swapchainFramebuffers.resize(m_gpu->getSwapchainImagesCount());
for (int i = 0; i < m_result.swapchainFramebuffers.size(); ++i)
{
auto createInfo = vk::FramebufferCreateInfo();
createInfo.setRenderPass(m_result.renderPass);
createInfo.setAttachmentCount(1);
createInfo.setWidth(extent.width);
createInfo.setHeight(extent.height);
createInfo.setLayers(1);
m_gpu->createFramebuffer(createInfo, i, m_result.swapchainFramebuffers[i]);
}
return true;
}
void SimpleRenderModeFactory::createCommandPool()
{
m_gpu->createGraphicsCommandPool(m_result.commandPool);
}
bool createCommandBuffers()
{
return false;
}
bool createSyncObjects()
{
return false;
}
| 10,305 | 3,635 |
#include "track.h"
using namespace mctracker::tracker;
Track
::Track(const float& _x, const float& _y, const KalmanParam& _param, const cv::Mat& h, const int cameraNum)
: Entity(), hist(h)
{
kf = std::shared_ptr<KalmanFilter>(new KalmanFilter(_x, _y, _param.getDt()));
ntimes_propagated = 0;
freezed = 0;
ntime_missed = 0;
isgood = false;
m_label = -1;
time = (double)cv::getTickCount();
sizes.resize(cameraNum);
}
const cv::Mat
Track::update()
{
if(points.size() > 0)
{
cv::Point2f result(0,0);
for(const auto& p : points)
{
result += p;
}
const auto& correction = correct(result.x, result.y);
points.clear();
return correction;
}
ntime_missed++;
return cv::Mat();
}
const cv::Mat
Track::predict()
{
const auto& prediction = kf->predict();
m_history.push_back(cv::Point2f(prediction.at<float>(0), prediction.at<float>(1)));
checkHistory();
return prediction;
}
const cv::Mat
Track::correct(const float& _x, const float& _y)
{
ntimes_propagated++;
time_in_sec = ((double) cv::getTickCount() - time) / cv::getTickFrequency();
return kf->correct(_x, _y);
}
const cv::Point2f
Track::getPoint()
{
const auto& prediction = kf->getPrediction();
return cv::Point2f(prediction.at<float>(0), prediction.at<float>(1));
}
const std::string
Track::label2string()
{
std::stringstream ss;
ss << m_label;
return ss.str();
}
| 1,522 | 551 |
/*------------------------------------------------------------
* CACTI 6.5
* Copyright 2008 Hewlett-Packard Development Corporation
* All Rights Reserved
*
* Permission to use, copy, and modify this software and its documentation is
* hereby granted only under the following terms and conditions. Both the
* above copyright notice and this permission notice must appear in all copies
* of the software, derivative works or modified versions, and any portions
* thereof, and both notices must appear in supporting documentation.
*
* Users of this software agree to the terms and conditions set forth herein, and
* hereby grant back to Hewlett-Packard Company and its affiliated companies ("HP")
* a non-exclusive, unrestricted, royalty-free right and license under any changes,
* enhancements or extensions made to the core functions of the software, including
* but not limited to those affording compatibility with other hardware or software
* environments, but excluding applications which incorporate this software.
* Users further agree to use their best efforts to return to HP any such changes,
* enhancements or extensions that they make and inform HP of noteworthy uses of
* this software. Correspondence should be provided to HP at:
*
* Director of Intellectual Property Licensing
* Office of Strategy and Technology
* Hewlett-Packard Company
* 1501 Page Mill Road
* Palo Alto, California 94304
*
* This software may be distributed (but not offered for sale or transferred
* for compensation) to third parties, provided such third parties agree to
* abide by the terms and conditions of this notice.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND HP DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL HP
* CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
* SOFTWARE.
*------------------------------------------------------------*/
#include <iostream>
#include <string>
#include <iomanip>
#include "parameter.h"
#include "area.h"
using namespace std;
namespace CactiArea
{
InputParameter * g_ip;
TechnologyParameter g_tp;
void TechnologyParameter::DeviceType::display(uint32_t indent)
{
string indent_str(indent, ' ');
cout << indent_str << "C_g_ideal = " << setw(12) << C_g_ideal << " F/um" << endl;
cout << indent_str << "C_fringe = " << setw(12) << C_fringe << " F/um" << endl;
cout << indent_str << "C_overlap = " << setw(12) << C_overlap << " F/um" << endl;
cout << indent_str << "C_junc = " << setw(12) << C_junc << " F/um^2" << endl;
cout << indent_str << "l_phy = " << setw(12) << l_phy << " um" << endl;
cout << indent_str << "l_elec = " << setw(12) << l_elec << " um" << endl;
cout << indent_str << "R_nch_on = " << setw(12) << R_nch_on << " ohm-um" << endl;
cout << indent_str << "R_pch_on = " << setw(12) << R_pch_on << " ohm-um" << endl;
cout << indent_str << "Vdd = " << setw(12) << Vdd_cacti << " V" << endl;
cout << indent_str << "Vth = " << setw(12) << Vth << " V" << endl;
cout << indent_str << "I_on_n = " << setw(12) << I_on_n << " A/um" << endl;
cout << indent_str << "I_on_p = " << setw(12) << I_on_p << " A/um" << endl;
cout << indent_str << "I_off_n = " << setw(12) << I_off_n << " A/um" << endl;
cout << indent_str << "I_off_p = " << setw(12) << I_off_p << " A/um" << endl;
cout << indent_str << "C_ox = " << setw(12) << C_ox << " F/um^2" << endl;
cout << indent_str << "t_ox = " << setw(12) << t_ox << " um" << endl;
cout << indent_str << "n_to_p_eff_curr_drv_ratio = " << n_to_p_eff_curr_drv_ratio << endl;
}
void TechnologyParameter::InterconnectType::display(uint32_t indent)
{
string indent_str(indent, ' ');
cout << indent_str << "pitch = " << setw(12) << pitch << " um" << endl;
cout << indent_str << "R_per_um = " << setw(12) << R_per_um << " ohm/um" << endl;
cout << indent_str << "C_per_um = " << setw(12) << C_per_um << " F/um" << endl;
}
void TechnologyParameter::MemoryType::display(uint32_t indent)
{
string indent_str(indent, ' ');
cout << indent_str << "b_w = " << setw(12) << b_w << " um" << endl;
cout << indent_str << "b_h = " << setw(12) << b_h << " um" << endl;
cout << indent_str << "cell_a_w = " << setw(12) << cell_a_w << " um" << endl;
cout << indent_str << "cell_pmos_w = " << setw(12) << cell_pmos_w << " um" << endl;
cout << indent_str << "cell_nmos_w = " << setw(12) << cell_nmos_w << " um" << endl;
cout << indent_str << "Vbitpre = " << setw(12) << Vbitpre_cacti << " V" << endl;
}
void TechnologyParameter::display(uint32_t indent)
{
string indent_str(indent, ' ');
cout << indent_str << "ram_wl_stitching_overhead_ = " << setw(12) << ram_wl_stitching_overhead_ << " um" << endl;
cout << indent_str << "min_w_nmos_ = " << setw(12) << min_w_nmos_ << " um" << endl;
cout << indent_str << "max_w_nmos_ = " << setw(12) << max_w_nmos_ << " um" << endl;
cout << indent_str << "unit_len_wire_del = " << setw(12) << unit_len_wire_del << " s/um^2" << endl;
cout << indent_str << "FO4 = " << setw(12) << FO4 << " s" << endl;
cout << indent_str << "kinv = " << setw(12) << kinv << " s" << endl;
cout << indent_str << "vpp = " << setw(12) << vpp << " V" << endl;
cout << indent_str << "w_sense_en = " << setw(12) << w_sense_en << " um" << endl;
cout << indent_str << "w_sense_n = " << setw(12) << w_sense_n << " um" << endl;
cout << indent_str << "w_sense_p = " << setw(12) << w_sense_p << " um" << endl;
cout << indent_str << "w_iso = " << setw(12) << w_iso << " um" << endl;
cout << indent_str << "w_poly_contact = " << setw(12) << w_poly_contact << " um" << endl;
cout << indent_str << "spacing_poly_to_poly = " << setw(12) << spacing_poly_to_poly << " um" << endl;
cout << indent_str << "spacing_poly_to_contact = " << setw(12) << spacing_poly_to_contact << " um" << endl;
cout << endl;
cout << indent_str << "w_comp_inv_p1 = " << setw(12) << w_comp_inv_p1 << " um" << endl;
cout << indent_str << "w_comp_inv_p2 = " << setw(12) << w_comp_inv_p2 << " um" << endl;
cout << indent_str << "w_comp_inv_p3 = " << setw(12) << w_comp_inv_p3 << " um" << endl;
cout << indent_str << "w_comp_inv_n1 = " << setw(12) << w_comp_inv_n1 << " um" << endl;
cout << indent_str << "w_comp_inv_n2 = " << setw(12) << w_comp_inv_n2 << " um" << endl;
cout << indent_str << "w_comp_inv_n3 = " << setw(12) << w_comp_inv_n3 << " um" << endl;
cout << indent_str << "w_eval_inv_p = " << setw(12) << w_eval_inv_p << " um" << endl;
cout << indent_str << "w_eval_inv_n = " << setw(12) << w_eval_inv_n << " um" << endl;
cout << indent_str << "w_comp_n = " << setw(12) << w_comp_n << " um" << endl;
cout << indent_str << "w_comp_p = " << setw(12) << w_comp_p << " um" << endl;
cout << endl;
cout << indent_str << "dram_cell_I_on = " << setw(12) << dram_cell_I_on << " A/um" << endl;
cout << indent_str << "dram_cell_Vdd = " << setw(12) << dram_cell_Vdd << " V" << endl;
cout << indent_str << "dram_cell_I_off_worst_case_len_temp = " << setw(12) << dram_cell_I_off_worst_case_len_temp << " A/um" << endl;
cout << indent_str << "dram_cell_C = " << setw(12) << dram_cell_C << " F" << endl;
cout << indent_str << "gm_sense_amp_latch = " << setw(12) << gm_sense_amp_latch << " F/s" << endl;
cout << endl;
cout << indent_str << "w_nmos_b_mux = " << setw(12) << w_nmos_b_mux << " um" << endl;
cout << indent_str << "w_nmos_sa_mux = " << setw(12) << w_nmos_sa_mux << " um" << endl;
cout << indent_str << "w_pmos_bl_precharge = " << setw(12) << w_pmos_bl_precharge << " um" << endl;
cout << indent_str << "w_pmos_bl_eq = " << setw(12) << w_pmos_bl_eq << " um" << endl;
cout << indent_str << "MIN_GAP_BET_P_AND_N_DIFFS = " << setw(12) << MIN_GAP_BET_P_AND_N_DIFFS << " um" << endl;
cout << indent_str << "HPOWERRAIL = " << setw(12) << HPOWERRAIL << " um" << endl;
cout << indent_str << "cell_h_def = " << setw(12) << cell_h_def << " um" << endl;
cout << endl;
cout << indent_str << "SRAM cell transistor: " << endl;
sram_cell.display(indent + 2);
cout << endl;
cout << indent_str << "DRAM access transistor: " << endl;
dram_acc.display(indent + 2);
cout << endl;
cout << indent_str << "DRAM wordline transistor: " << endl;
dram_wl.display(indent + 2);
cout << endl;
cout << indent_str << "peripheral global transistor: " << endl;
peri_global.display(indent + 2);
cout << endl;
cout << indent_str << "wire local" << endl;
wire_local.display(indent + 2);
cout << endl;
cout << indent_str << "wire inside mat" << endl;
wire_inside_mat.display(indent + 2);
cout << endl;
cout << indent_str << "wire outside mat" << endl;
wire_outside_mat.display(indent + 2);
cout << endl;
cout << indent_str << "SRAM" << endl;
sram.display(indent + 2);
cout << endl;
cout << indent_str << "DRAM" << endl;
dram.display(indent + 2);
}
DynamicParameter::DynamicParameter():
use_inp_params(0), cell(), is_valid(true)
{
}
DynamicParameter::DynamicParameter(
bool is_tag_,
int pure_ram_,
double Nspd_,
unsigned int Ndwl_,
unsigned int Ndbl_,
unsigned int Ndcm,
unsigned int Ndsam_lev_1_,
unsigned int Ndsam_lev_2_,
bool is_main_mem_):
is_tag(is_tag_), pure_ram(pure_ram_), tagbits(0), Nspd(Nspd_), Ndwl(Ndwl_), Ndbl(Ndbl_),
Ndsam_lev_1(Ndsam_lev_1_), Ndsam_lev_2(Ndsam_lev_2_),
number_way_select_signals_mat(0), V_b_sense(0), use_inp_params(0),
is_main_mem(is_main_mem_), cell(), is_valid(false)
{
ram_cell_tech_type = (is_tag) ? g_ip->tag_arr_ram_cell_tech_type : g_ip->data_arr_ram_cell_tech_type;
is_dram = ((ram_cell_tech_type == lp_dram) || (ram_cell_tech_type == comm_dram));
unsigned int capacity_per_die = g_ip->cache_sz / NUMBER_STACKED_DIE_LAYERS; // capacity per stacked die layer
const TechnologyParameter::InterconnectType & wire_local = g_tp.wire_local;
bool fully_assoc = (g_ip->fully_assoc) ? true : false;
if (fully_assoc)
{ // fully-assocative cache -- ref: CACTi 2.0 report
if (Ndwl != 1 || //Ndwl is fixed to 1 for FA
Ndcm != 1 || //Ndcm is fixed to 1 for FA
Nspd < 1 || Nspd > 1 || //Nspd is fixed to 1 for FA
Ndsam_lev_1 != 1 || //Ndsam_lev_1 is fixed to one
Ndsam_lev_2 != 1 || //Ndsam_lev_2 is fixed to one
Ndbl < 2)
{
return;
}
}
if ((is_dram) && (!is_tag) && (Ndcm > 1))
{
return; // For a DRAM array, each bitline has its own sense-amp
}
// If it's not an FA tag/data array, Ndwl should be at least two and Ndbl should be
// at least two because an array is assumed to have at least one mat. And a mat
// is formed out of two horizontal subarrays and two vertical subarrays
if (fully_assoc == false && (Ndwl < 1 || Ndbl < 1))
{
return;
}
// if data array, let tagbits = 0
if (is_tag)
{
if (g_ip->specific_tag)
{
tagbits = g_ip->tag_w;
}
else
{
if (fully_assoc)
{
tagbits = ADDRESS_BITS + EXTRA_TAG_BITS - _log2(g_ip->block_sz);
}
else
{
tagbits = ADDRESS_BITS + EXTRA_TAG_BITS - _log2(capacity_per_die) +
_log2(g_ip->tag_assoc*2 - 1) - _log2(g_ip->nbanks);
}
}
tagbits = (((tagbits + 3) >> 2) << 2);
if (fully_assoc)
{
num_r_subarray = (int)(capacity_per_die / (g_ip->block_sz * Ndbl));
num_c_subarray = (int)((tagbits * Nspd / Ndwl) + EPSILON);
}
else
{
num_r_subarray = (int)(capacity_per_die / (g_ip->nbanks *
g_ip->block_sz * g_ip->tag_assoc * Ndbl * Nspd) + EPSILON);
num_c_subarray = (int)((tagbits * g_ip->tag_assoc * Nspd / Ndwl) + EPSILON);
}
//burst_length = 1;
}
else
{
if (fully_assoc)
{
num_r_subarray = (int) (capacity_per_die) / (g_ip->block_sz * Ndbl);
num_c_subarray = 8 * g_ip->block_sz;
}
else
{
num_r_subarray = (int)(capacity_per_die / (g_ip->nbanks *
g_ip->block_sz * g_ip->data_assoc * Ndbl * Nspd) + EPSILON);
num_c_subarray = (int)((8 * g_ip->block_sz * g_ip->data_assoc * Nspd / Ndwl) + EPSILON);
}
// burst_length = g_ip->block_sz * 8 / g_ip->out_w;
}
if ((!fully_assoc)&&(num_r_subarray < MINSUBARRAYROWS)) return;
if (num_r_subarray == 0) return;
if (num_r_subarray > MAXSUBARRAYROWS) return;
if (num_c_subarray < MINSUBARRAYCOLS) return;
if (num_c_subarray > MAXSUBARRAYCOLS) return;
num_subarrays = Ndwl * Ndbl;
// calculate wire parameters
if(is_tag)
{
cell.h = g_tp.sram.b_h + 2 * wire_local.pitch * (g_ip->num_rw_ports - 1 + g_ip->num_rd_ports);
cell.w = g_tp.sram.b_w + 2 * wire_local.pitch * (g_ip->num_rw_ports - 1 +
(g_ip->num_rd_ports - g_ip->num_se_rd_ports)) +
wire_local.pitch * g_ip->num_se_rd_ports;
}
else
{
if (is_dram)
{
cell.h = g_tp.dram.b_h;
cell.w = g_tp.dram.b_w;
}
else
{
cell.h = g_tp.sram.b_h + 2 * wire_local.pitch * (g_ip->num_wr_ports +
g_ip->num_rw_ports - 1 + g_ip->num_rd_ports);
cell.w = g_tp.sram.b_w + 2 * wire_local.pitch * (g_ip->num_rw_ports - 1 +
(g_ip->num_rd_ports - g_ip->num_se_rd_ports) +
g_ip->num_wr_ports) + g_tp.wire_local.pitch * g_ip->num_se_rd_ports;
}
}
double c_b_metal = cell.h * wire_local.C_per_um;
double C_bl;
if (is_dram)
{
deg_bl_muxing = 1;
if (ram_cell_tech_type == comm_dram)
{
C_bl = num_r_subarray * c_b_metal;
V_b_sense = (g_tp.dram_cell_Vdd/2) * g_tp.dram_cell_C / (g_tp.dram_cell_C + C_bl);
if (V_b_sense < VBITSENSEMIN)
{
return;
}
V_b_sense = VBITSENSEMIN; // in any case, we fix sense amp input signal to a constant value
dram_refresh_period = 64e-3;
}
else
{
double Cbitrow_drain_cap = drain_C_(g_tp.dram.cell_a_w, NCH, 1, 0, cell.w, true, true) / 2.0;
C_bl = num_r_subarray * (Cbitrow_drain_cap + c_b_metal);
V_b_sense = (g_tp.dram_cell_Vdd/2) * g_tp.dram_cell_C /(g_tp.dram_cell_C + C_bl);
if (V_b_sense < VBITSENSEMIN)
{
return; //Sense amp input signal is smaller that minimum allowable sense amp input signal
}
V_b_sense = VBITSENSEMIN; // in any case, we fix sense amp input signal to a constant value
//v_storage_worst = g_tp.dram_cell_Vdd / 2 - VBITSENSEMIN * (g_tp.dram_cell_C + C_bl) / g_tp.dram_cell_C;
//dram_refresh_period = 1.1 * g_tp.dram_cell_C * v_storage_worst / g_tp.dram_cell_I_off_worst_case_len_temp;
dram_refresh_period = 0.9 * g_tp.dram_cell_C * VDD_STORAGE_LOSS_FRACTION_WORST * g_tp.dram_cell_Vdd / g_tp.dram_cell_I_off_worst_case_len_temp;
}
}
else
{ //SRAM
V_b_sense = (0.05 * g_tp.sram_cell.Vdd_cacti > VBITSENSEMIN) ? 0.05 * g_tp.sram_cell.Vdd_cacti : VBITSENSEMIN;
deg_bl_muxing = Ndcm;
// "/ 2.0" below is due to the fact that two adjacent access transistors share drain
// contacts in a physical layout
double Cbitrow_drain_cap = drain_C_(g_tp.sram.cell_a_w, NCH, 1, 0, cell.w, false, true) / 2.0;
C_bl = num_r_subarray * (Cbitrow_drain_cap + c_b_metal);
dram_refresh_period = 0;
}
if (fully_assoc)
{
num_mats_h_dir = 1;
num_mats_v_dir = Ndbl / 2;
num_do_b_mat = 8 * g_ip->block_sz;
num_mats = num_mats_h_dir * num_mats_v_dir;
}
else
{
num_mats_h_dir = MAX(Ndwl / 2, 1);
num_mats_v_dir = MAX(Ndbl / 2, 1);
num_mats = num_mats_h_dir * num_mats_v_dir;
num_do_b_mat = MAX((num_subarrays/num_mats) * num_c_subarray / (deg_bl_muxing * Ndsam_lev_1 * Ndsam_lev_2), 1);
}
if (!(fully_assoc&&is_tag) && (num_do_b_mat < (num_subarrays/num_mats)))
{
return;
}
int deg_sa_mux_l1_non_assoc;
if (!is_tag)
{
if (is_main_mem == true)
{
num_do_b_subbank = g_ip->int_prefetch_w * g_ip->out_w;
deg_sa_mux_l1_non_assoc = Ndsam_lev_1;
}
else
{
if (g_ip->fast_access == true)
{
num_do_b_subbank = g_ip->out_w * g_ip->data_assoc;
deg_sa_mux_l1_non_assoc = Ndsam_lev_1;
}
else
{
if (!fully_assoc)
{
num_do_b_subbank = g_ip->out_w;
deg_sa_mux_l1_non_assoc = Ndsam_lev_1 / g_ip->data_assoc;
if (deg_sa_mux_l1_non_assoc < 1)
{
return;
}
}
else
{
num_do_b_subbank = 8 * g_ip->block_sz;
deg_sa_mux_l1_non_assoc = 1;
}
}
}
}
else
{
num_do_b_subbank = tagbits * g_ip->tag_assoc;
if (fully_assoc == false && (num_do_b_mat < tagbits))
{
return;
}
deg_sa_mux_l1_non_assoc = Ndsam_lev_1;
//num_do_b_mat = g_ip->tag_assoc / num_mats_h_dir;
}
deg_senseamp_muxing_non_associativity = deg_sa_mux_l1_non_assoc;
if (fully_assoc)
{
num_act_mats_hor_dir = 1;
}
else
{
num_act_mats_hor_dir = num_do_b_subbank / num_do_b_mat;
if (num_act_mats_hor_dir == 0)
{
return;
}
}
if (is_tag)
{
if (fully_assoc)
{
num_do_b_mat = 0;
num_do_b_subbank = 0;
}
else
{
num_do_b_mat = g_ip->tag_assoc / num_act_mats_hor_dir;
num_do_b_subbank = num_act_mats_hor_dir * num_do_b_mat;
}
}
if ((g_ip->is_cache == false && is_main_mem == true) || (PAGE_MODE == 1 && is_dram))
{
if (num_act_mats_hor_dir * num_do_b_mat * Ndsam_lev_1 * Ndsam_lev_2 != (int)g_ip->page_sz_bits)
{
return;
}
}
if (is_tag == false && g_ip->is_main_mem == true &&
num_act_mats_hor_dir*num_do_b_mat*Ndsam_lev_1*Ndsam_lev_2 < ((int) g_ip->out_w * (int) g_ip->burst_len * (int) g_ip->data_assoc))
{
return;
}
if (num_act_mats_hor_dir > num_mats_h_dir)
{
return;
}
if(!is_tag)
{
if(g_ip->fast_access == true)
{
num_di_b_mat = num_do_b_mat / g_ip->data_assoc;
}
else
{
num_di_b_mat = num_do_b_mat;
}
}
else
{
num_di_b_mat = tagbits;
}
int num_di_b_subbank = num_di_b_mat * num_act_mats_hor_dir;
int num_addr_b_row_dec = (fully_assoc == true) ? 0 : _log2(num_r_subarray);
int number_subbanks = num_mats / num_act_mats_hor_dir;
number_subbanks_decode = _log2(number_subbanks);
num_rw_ports = g_ip->num_rw_ports;
num_rd_ports = g_ip->num_rd_ports;
num_wr_ports = g_ip->num_wr_ports;
num_se_rd_ports = g_ip->num_se_rd_ports;
if (is_dram && is_main_mem)
{
number_addr_bits_mat = MAX((unsigned int) num_addr_b_row_dec,
_log2(deg_bl_muxing) + _log2(deg_sa_mux_l1_non_assoc) + _log2(Ndsam_lev_2));
}
else
{
number_addr_bits_mat = num_addr_b_row_dec + _log2(deg_bl_muxing) +
_log2(deg_sa_mux_l1_non_assoc) + _log2(Ndsam_lev_2);
}
if (is_tag)
{
num_di_b_bank_per_port = tagbits;
num_do_b_bank_per_port = g_ip->data_assoc;
}
else
{
num_di_b_bank_per_port = g_ip->out_w + g_ip->data_assoc;
num_do_b_bank_per_port = g_ip->out_w;
}
if ((!is_tag) && (g_ip->data_assoc > 1) && (!g_ip->fast_access))
{
number_way_select_signals_mat = g_ip->data_assoc;
}
// add ECC adjustment to all data signals that traverse on H-trees.
if (g_ip->add_ecc_b_ == true)
{
num_do_b_mat += (int) (ceil(num_do_b_mat / num_bits_per_ecc_b_));
num_di_b_mat += (int) (ceil(num_di_b_mat / num_bits_per_ecc_b_));
num_di_b_subbank += (int) (ceil(num_di_b_subbank / num_bits_per_ecc_b_));
num_do_b_subbank += (int) (ceil(num_do_b_subbank / num_bits_per_ecc_b_));
}
is_valid = true;
}
}/*namespace cactiarea*/
| 20,848 | 8,602 |
//
// Created by ekaterina on 08.10.2020.
//
// Copyright 2020 Your Name <ekaterina>
#ifndef INCLUDE_HEADER_HPP_
#define INCLUDE_HEADER_HPP_
#include <vector>
#include <string>
#include "Student.hpp"
class Table {
public:
explicit Table(const json& j);
~Table();
static Table parseFile(const std::string& s);
//вызов метода без создания экземпляра класса
size_t w_name, w_group, w_avg, w_debt, w_space;
void print(std::ostream& out) const;
std::vector<Student> m_students;
std::vector<size_t> m_w;
};
#endif // INCLUDE_HEADER_HPP_
| 556 | 237 |
// Copyright (c) Lawrence Livermore National Security, LLC and other Conduit
// Project developers. See top-level LICENSE AND COPYRIGHT files for dates and
// other details. No copyright assignment is required to contribute to Conduit.
//-----------------------------------------------------------------------------
///
/// file: t_relay_io_hdf5.cpp
///
//-----------------------------------------------------------------------------
#include "conduit_relay.hpp"
#include "conduit_relay_io_hdf5.hpp"
#include "hdf5.h"
#include <iostream>
#include "gtest/gtest.h"
using namespace conduit;
using namespace conduit::relay;
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_write_read_by_file_name)
{
uint32 a_val = 20;
uint32 b_val = 8;
uint32 c_val = 13;
uint32 d_val = 121;
Node n;
n["a"] = a_val;
n["b"] = b_val;
n["c"] = c_val;
EXPECT_EQ(n["a"].as_uint32(), a_val);
EXPECT_EQ(n["b"].as_uint32(), b_val);
EXPECT_EQ(n["c"].as_uint32(), c_val);
// write our node as a group @ "myobj"
io::hdf5_write(n,"tout_hdf5_wr.hdf5:myobj");
// directly read our object
Node n_load;
io::hdf5_read("tout_hdf5_wr.hdf5:myobj",n_load);
n_load.print_detailed();
EXPECT_EQ(n_load["a"].as_uint32(), a_val);
EXPECT_EQ(n_load["b"].as_uint32(), b_val);
EXPECT_EQ(n_load["c"].as_uint32(), c_val);
Node n_load_2;
// read from root of hdf5 file
io::hdf5_read("tout_hdf5_wr.hdf5",n_load_2);
EXPECT_EQ(n_load_2["myobj/a"].as_uint32(), a_val);
EXPECT_EQ(n_load_2["myobj/b"].as_uint32(), b_val);
EXPECT_EQ(n_load_2["myobj/c"].as_uint32(), c_val);
Node n_load_generic;
// read from root of hdf5 file
io::load("tout_hdf5_wr.hdf5",n_load_generic);
EXPECT_EQ(n_load_generic["myobj/a"].as_uint32(), a_val);
EXPECT_EQ(n_load_generic["myobj/b"].as_uint32(), b_val);
EXPECT_EQ(n_load_generic["myobj/c"].as_uint32(), c_val);
// save load from generic io interface
io::save(n_load_generic["myobj"],"tout_hdf5_wr_generic.hdf5:myobj");
n_load_generic["myobj/d"] = d_val;
io::load_merged("tout_hdf5_wr_generic.hdf5",n_load_generic);
EXPECT_EQ(n_load_generic["myobj/a"].as_uint32(), a_val);
EXPECT_EQ(n_load_generic["myobj/b"].as_uint32(), b_val);
EXPECT_EQ(n_load_generic["myobj/c"].as_uint32(), c_val);
EXPECT_EQ(n_load_generic["myobj/d"].as_uint32(), d_val);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_write_read_special_paths)
{
uint32 a_val = 20;
uint32 b_val = 8;
Node n;
n["a"] = a_val;
n["b"] = b_val;
EXPECT_EQ(n["a"].as_uint32(), a_val);
EXPECT_EQ(n["b"].as_uint32(), b_val);
// write our node as a group @ "/myobj"
io::hdf5_write(n,"tout_hdf5_wr_special_paths_1.hdf5:/myobj");
// write our node as a group @ "/"
// make sure "/" works
io::hdf5_write(n,"tout_hdf5_wr_special_paths_2.hdf5:/");
// make sure empty after ":" this works
io::hdf5_write(n,"tout_hdf5_wr_special_paths_3.hdf5:");
Node n_load;
io::hdf5_read("tout_hdf5_wr_special_paths_2.hdf5:/",n_load);
EXPECT_EQ(n_load["a"].as_uint32(), a_val);
EXPECT_EQ(n_load["b"].as_uint32(), b_val);
n_load.reset();
io::hdf5_read("tout_hdf5_wr_special_paths_2.hdf5:/",n_load);
EXPECT_EQ(n_load["a"].as_uint32(), a_val);
EXPECT_EQ(n_load["b"].as_uint32(), b_val);
n_load.reset();
io::hdf5_read("tout_hdf5_wr_special_paths_2.hdf5:",n_load);
EXPECT_EQ(n_load["a"].as_uint32(), a_val);
EXPECT_EQ(n_load["b"].as_uint32(), b_val);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_write_read_string)
{
uint32 a_val = 20;
std::string s_val = "{string value!}";
Node n;
n["a"] = a_val;
n["s"] = s_val;
EXPECT_EQ(n["a"].as_uint32(), a_val);
EXPECT_EQ(n["s"].as_string(), s_val);
// write our node as a group @ "myobj"
io::hdf5_write(n,"tout_hdf5_wr_string.hdf5:myobj");
Node n_out;
io::hdf5_read("tout_hdf5_wr_string.hdf5:myobj",n_out);
EXPECT_EQ(n_out["a"].as_uint32(), a_val);
EXPECT_EQ(n_out["s"].as_string(), s_val);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_write_read_array)
{
Node n_in(DataType::float64(10));
float64_array val_in = n_in.value();
for(index_t i=0;i<10;i++)
{
val_in[i] = 3.1415 * i;
}
// write our node as a group @ "myobj"
io::hdf5_write(n_in,"tout_hdf5_wr_array.hdf5:myobj");
Node n_out;
io::hdf5_read("tout_hdf5_wr_array.hdf5:myobj",n_out);
float64_array val_out = n_out.value();
for(index_t i=0;i<10;i++)
{
EXPECT_EQ(val_in[i],val_out[i]);
}
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, write_and_read_conduit_leaf_to_hdf5_dataset_handle)
{
std::string ofname = "tout_hdf5_wr_conduit_leaf_to_hdf5_dataset_handle.hdf5";
hid_t h5_file_id = H5Fcreate(ofname.c_str(),
H5F_ACC_TRUNC,
H5P_DEFAULT,
H5P_DEFAULT);
// create a dataset for a 16-bit signed integer array with 2 elements
hid_t h5_dtype = H5T_NATIVE_SHORT;
hsize_t num_eles = 2;
hid_t h5_dspace_id = H5Screate_simple(1,
&num_eles,
NULL);
// create new dataset
hid_t h5_dset_id = H5Dcreate(h5_file_id,
"mydata",
h5_dtype,
h5_dspace_id,
H5P_DEFAULT,
H5P_DEFAULT,
H5P_DEFAULT);
Node n;
n.set(DataType::c_short(2));
short_array vals = n.value();
vals[0] = -16;
vals[1] = -16;
// this should succeed
io::hdf5_write(n,h5_dset_id);
// this should also succeed
vals[1] = 16;
io::hdf5_write(n,h5_dset_id);
n.set(DataType::uint16(10));
// this should fail
EXPECT_THROW(io::hdf5_write(n,h5_dset_id),Error);
Node n_read;
io::hdf5_read(h5_dset_id,n_read);
// check values of data
short_array read_vals = n_read.value();
EXPECT_EQ(-16,read_vals[0]);
EXPECT_EQ(16,read_vals[1]);
H5Sclose(h5_dspace_id);
H5Dclose(h5_dset_id);
H5Fclose(h5_file_id);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, write_and_read_conduit_leaf_to_extendible_hdf5_dataset_handle_with_offset)
{
std::string ofname = "tout_hdf5_wr_conduit_leaf_to_hdf5_extendible_dataset_handle_with_offset.hdf5";
hid_t h5_file_id = H5Fcreate(ofname.c_str(),
H5F_ACC_TRUNC,
H5P_DEFAULT,
H5P_DEFAULT);
// create a dataset for a 16-bit signed integer array with 2 elements
hid_t h5_dtype = H5T_NATIVE_SHORT;
hsize_t num_eles = 2;
hsize_t dims[1] = {H5S_UNLIMITED};
hid_t h5_dspace_id = H5Screate_simple(1,
&num_eles,
dims);
/*
* Modify dataset creation properties, i.e. enable chunking.
*/
hid_t cparms;
hsize_t chunk_dims[1] = {1};
cparms = H5Pcreate (H5P_DATASET_CREATE);
H5Pset_chunk(cparms, 1, chunk_dims);
// create new dataset
hid_t h5_dset_id = H5Dcreate1(h5_file_id,
"mydata",
h5_dtype,
h5_dspace_id,
cparms);
Node n, opts;
n.set(DataType::c_short(2));
short_array vals = n.value();
vals[0] = -16;
vals[1] = -15;
// this should succeed
io::hdf5_write(n,h5_dset_id);
vals[0] = 1;
vals[1] = 2;
opts["offset"] = 2;
opts["stride"] = 1;
io::hdf5_write(n,h5_dset_id,opts);
Node n_read, opts_read;
io::hdf5_read_info(h5_dset_id,opts_read,n_read);
EXPECT_EQ(4,(int) n_read["num_elements"].to_value());
io::hdf5_read(h5_dset_id,opts_read,n_read);
// check values of data
short_array read_vals = n_read.value();
EXPECT_EQ(-16,read_vals[0]);
EXPECT_EQ(-15,read_vals[1]);
EXPECT_EQ(1,read_vals[2]);
EXPECT_EQ(2,read_vals[3]);
opts_read["offset"] = 2;
opts_read["stride"] = 1;
io::hdf5_read(h5_dset_id,opts_read,n_read);
// check values of data
read_vals = n_read.value();
EXPECT_EQ(1,read_vals[0]);
EXPECT_EQ(2,read_vals[1]);
vals[0] = -1;
vals[1] = -3;
opts["offset"] = 0;
opts["stride"] = 2;
io::hdf5_write(n,h5_dset_id,opts);
opts_read["offset"] = 0;
opts_read["stride"] = 1;
io::hdf5_read(h5_dset_id,opts_read,n_read);
// check values of data
read_vals = n_read.value();
EXPECT_EQ(-1,read_vals[0]);
EXPECT_EQ(-15,read_vals[1]);
EXPECT_EQ(-3,read_vals[2]);
EXPECT_EQ(2,read_vals[3]);
vals[0] = 5;
vals[1] = 6;
opts["offset"] = 7;
opts["stride"] = 1;
io::hdf5_write(n,h5_dset_id,opts);
opts_read["offset"] = 0;
opts_read["stride"] = 1;
io::hdf5_read(h5_dset_id,opts_read,n_read);
// check values of data
read_vals = n_read.value();
EXPECT_EQ(-1,read_vals[0]);
EXPECT_EQ(-15,read_vals[1]);
EXPECT_EQ(-3,read_vals[2]);
EXPECT_EQ(2,read_vals[3]);
EXPECT_EQ(0,read_vals[4]);
EXPECT_EQ(0,read_vals[5]);
EXPECT_EQ(0,read_vals[6]);
EXPECT_EQ(5,read_vals[7]);
EXPECT_EQ(6,read_vals[8]);
opts["offset"] = -1;
opts["stride"] = 2;
opts_read["offset"] = -1;
opts_read["stride"] = 2;
//this should fail
EXPECT_THROW(io::hdf5_write(n,h5_dset_id,opts),Error);
EXPECT_THROW(io::hdf5_read(h5_dset_id,opts_read,n_read),Error);
opts["offset"] = 0;
opts["stride"] = 0;
opts_read["offset"] = 0;
opts_read["stride"] = 0;
//this should fail
EXPECT_THROW(io::hdf5_write(n,h5_dset_id,opts),Error);
EXPECT_THROW(io::hdf5_read(h5_dset_id,opts_read,n_read),Error);
H5Sclose(h5_dspace_id);
H5Dclose(h5_dset_id);
H5Fclose(h5_file_id);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, write_and_read_conduit_leaf_to_fixed_hdf5_dataset_handle_with_offset)
{
std::string ofname = "tout_hdf5_wr_conduit_leaf_to_fixed_hdf5_dataset_handle_with_offset.hdf5";
hid_t h5_file_id = H5Fcreate(ofname.c_str(),
H5F_ACC_TRUNC,
H5P_DEFAULT,
H5P_DEFAULT);
// create a dataset for a 16-bit signed integer array with 2 elements
hid_t h5_dtype = H5T_NATIVE_SHORT;
hsize_t num_eles = 2;
hid_t h5_dspace_id = H5Screate_simple(1,
&num_eles,
NULL);
// create new dataset
hid_t h5_dset_id = H5Dcreate(h5_file_id,
"mydata",
h5_dtype,
h5_dspace_id,
H5P_DEFAULT,
H5P_DEFAULT,
H5P_DEFAULT);
Node n, opts;
n.set(DataType::c_short(2));
short_array vals = n.value();
vals[0] = -16;
vals[1] = -15;
// this should succeed
io::hdf5_write(n,h5_dset_id);
vals[0] = 1;
vals[1] = 2;
opts["offset"] = 2;
opts["stride"] = 1;
io::hdf5_write(n,h5_dset_id,opts);
Node n_read, opts_read;
io::hdf5_read_info(h5_dset_id,opts_read,n_read);
EXPECT_EQ(4,(int) n_read["num_elements"].to_value());
io::hdf5_read(h5_dset_id,opts_read,n_read);
// check values of data
short_array read_vals = n_read.value();
EXPECT_EQ(-16,read_vals[0]);
EXPECT_EQ(-15,read_vals[1]);
EXPECT_EQ(1,read_vals[2]);
EXPECT_EQ(2,read_vals[3]);
opts_read["offset"] = 2;
opts_read["stride"] = 1;
io::hdf5_read(h5_dset_id,opts_read,n_read);
// check values of data
read_vals = n_read.value();
EXPECT_EQ(1,read_vals[0]);
EXPECT_EQ(2,read_vals[1]);
vals[0] = -1;
vals[1] = -3;
opts["offset"] = 0;
opts["stride"] = 2;
io::hdf5_write(n,h5_dset_id,opts);
opts_read["offset"] = 0;
opts_read["stride"] = 1;
io::hdf5_read(h5_dset_id,opts_read,n_read);
// check values of data
read_vals = n_read.value();
EXPECT_EQ(-1,read_vals[0]);
EXPECT_EQ(-15,read_vals[1]);
EXPECT_EQ(-3,read_vals[2]);
EXPECT_EQ(2,read_vals[3]);
vals[0] = 5;
vals[1] = 6;
opts["offset"] = 7;
opts["stride"] = 1;
io::hdf5_write(n,h5_dset_id,opts);
opts_read["offset"] = 0;
opts_read["stride"] = 1;
io::hdf5_read(h5_dset_id,opts_read,n_read);
// check values of data
read_vals = n_read.value();
EXPECT_EQ(-1,read_vals[0]);
EXPECT_EQ(-15,read_vals[1]);
EXPECT_EQ(-3,read_vals[2]);
EXPECT_EQ(2,read_vals[3]);
EXPECT_EQ(0,read_vals[4]);
EXPECT_EQ(0,read_vals[5]);
EXPECT_EQ(0,read_vals[6]);
EXPECT_EQ(5,read_vals[7]);
EXPECT_EQ(6,read_vals[8]);
opts["offset"] = -1;
opts["stride"] = 2;
opts_read["offset"] = -1;
opts_read["stride"] = 2;
//this should fail
EXPECT_THROW(io::hdf5_write(n,h5_dset_id,opts),Error);
EXPECT_THROW(io::hdf5_read(h5_dset_id,opts_read,n_read),Error);
opts["offset"] = 0;
opts["stride"] = 0;
opts_read["offset"] = 0;
opts_read["stride"] = 0;
//this should fail
EXPECT_THROW(io::hdf5_write(n,h5_dset_id,opts),Error);
EXPECT_THROW(io::hdf5_read(h5_dset_id,opts_read,n_read),Error);
H5Sclose(h5_dspace_id);
H5Dclose(h5_dset_id);
H5Fclose(h5_file_id);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, write_conduit_object_to_hdf5_group_handle_with_offset)
{
std::string ofname = "tout_hdf5_wr_conduit_object_to_hdf5_group_handle_with_offset.hdf5";
hid_t h5_file_id = H5Fcreate(ofname.c_str(),
H5F_ACC_TRUNC,
H5P_DEFAULT,
H5P_DEFAULT);
hid_t h5_group_id = H5Gcreate(h5_file_id,
"mygroup",
H5P_DEFAULT,
H5P_DEFAULT,
H5P_DEFAULT);
Node n, opts;
n["a/b"].set(DataType::int16(2));
int16_array vals = n["a/b"].value();
vals[0] =-16;
vals[1] =-16;
// this should succeed
io::hdf5_write(n,h5_group_id);
n["a/c"] = "mystring";
// this should also succeed
vals[1] = 16;
io::hdf5_write(n,h5_group_id);
Node n_read;
io::hdf5_read(h5_group_id,n_read);
n["a/b"].set(DataType::int16(10));
// this should fail
EXPECT_THROW(io::hdf5_write(n,h5_group_id),Error);
n["a/b"].set(DataType::int16(10));
vals = n["a/b"].value();
opts["offset"] = 5;
for (int i = 0; i < 10; i++) {
vals[i] = i + 1;
}
io::hdf5_write(n,h5_group_id,opts);
io::hdf5_read(h5_group_id,n_read);
// check values of data with offset
int16_array read_vals = n_read["a/b"].value();
for (int i = 0; i < 10; i++) {
EXPECT_EQ(i + 1, read_vals[i + 5]);
}
// this is also offset
EXPECT_EQ("mystrmystring",n_read["a/c"].as_string());
opts["offset"] = 20;
opts["stride"] = 2;
for (int i = 0; i < 10; i++) {
vals[i] = i + 1;
}
n["a/d"].set(DataType::int16(5));
int16_array vals2 = n["a/d"].value();
for (int i = 0; i < 5; i++) {
vals2[i] = (i + 1) * -1;
}
io::hdf5_write(n,h5_group_id,opts);
io::hdf5_read(h5_group_id,n_read);
// check values of data
read_vals = n_read["a/b"].value();
for (int i = 0; i < 10; i++) {
EXPECT_EQ(i + 1, read_vals[i + 5]);
}
for (int i = 0; i < 10; i++) {
EXPECT_EQ(i + 1, read_vals[2*i + 20]);
}
read_vals = n_read["a/d"].value();
for (int i = 0; i < 5; i++) {
EXPECT_EQ((i + 1) * -1, read_vals[2*i + 20]);
}
Node n_read_info;
io::hdf5_read_info(h5_group_id,n_read_info);
EXPECT_EQ(39,(int) n_read_info["a/b/num_elements"].to_value());
EXPECT_EQ(37,(int) n_read_info["a/c/num_elements"].to_value());
EXPECT_EQ(29,(int) n_read_info["a/d/num_elements"].to_value());
// this doesn't change because the null-terminated character
// wasn't overwritten
EXPECT_EQ("mystrmystring",n_read["a/c"].as_string());
Node opts_read;
opts_read["offset"] = 5;
io::hdf5_read_info(h5_group_id,opts_read,n_read_info);
io::hdf5_read(h5_group_id,opts_read,n_read);
// check values of data
read_vals = n_read["a/b"].value();
for (int i = 0; i < 10; i++) {
EXPECT_EQ(i + 1, read_vals[i]);
}
EXPECT_EQ("mystring",n_read["a/c"].as_string());
EXPECT_EQ(34,(int) n_read_info["a/b/num_elements"].to_value());
EXPECT_EQ(32,(int) n_read_info["a/c/num_elements"].to_value());
opts_read["offset"] = 20;
opts_read["stride"] = 2;
io::hdf5_read_info(h5_group_id,opts_read,n_read_info);
io::hdf5_read(h5_group_id,opts_read,n_read);
// check values of data
read_vals = n_read["a/b"].value();
for (int i = 0; i < 10; i++) {
EXPECT_EQ(i + 1, read_vals[i]);
}
read_vals = n_read["a/d"].value();
for (int i = 0; i < 5; i++) {
EXPECT_EQ((i + 1) * -1, read_vals[i]);
}
EXPECT_EQ(10,(int) n_read_info["a/b/num_elements"].to_value());
EXPECT_EQ(5,(int) n_read_info["a/d/num_elements"].to_value());
opts_read["offset"] = 20;
opts_read["stride"] = 3;
io::hdf5_read_info(h5_group_id,opts_read,n_read_info);
io::hdf5_read(h5_group_id,opts_read,n_read);
// check values of data
read_vals = n_read["a/b"].value();
EXPECT_EQ(1, read_vals[0]);
EXPECT_EQ(4, read_vals[2]);
EXPECT_EQ(7, read_vals[4]);
EXPECT_EQ(10, read_vals[6]);
read_vals = n_read["a/d"].value();
EXPECT_EQ(-1, read_vals[0]);
EXPECT_EQ(-4, read_vals[2]);
EXPECT_EQ(7,(int) n_read_info["a/b/num_elements"].to_value());
EXPECT_EQ(3,(int) n_read_info["a/d/num_elements"].to_value());
H5Gclose(h5_group_id);
H5Fclose(h5_file_id);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, write_conduit_object_to_hdf5_group_handle)
{
std::string ofname = "tout_hdf5_wr_conduit_object_to_hdf5_group_handle.hdf5";
hid_t h5_file_id = H5Fcreate(ofname.c_str(),
H5F_ACC_TRUNC,
H5P_DEFAULT,
H5P_DEFAULT);
hid_t h5_group_id = H5Gcreate(h5_file_id,
"mygroup",
H5P_DEFAULT,
H5P_DEFAULT,
H5P_DEFAULT);
Node n;
n["a/b"].set(DataType::int16(2));
int16_array vals = n["a/b"].value();
vals[0] =-16;
vals[1] =-16;
// this should succeed
io::hdf5_write(n,h5_group_id);
n["a/c"] = "mystring";
// this should also succeed
vals[1] = 16;
io::hdf5_write(n,h5_group_id);
n["a/b"].set(DataType::uint16(10));
// this should fail
EXPECT_THROW(io::hdf5_write(n,h5_group_id),Error);
Node n_read;
io::hdf5_read(h5_group_id,n_read);
// check values of data
int16_array read_vals = n_read["a/b"].value();
EXPECT_EQ(-16,read_vals[0]);
EXPECT_EQ(16,read_vals[1]);
EXPECT_EQ("mystring",n_read["a/c"].as_string());
H5Gclose(h5_group_id);
H5Fclose(h5_file_id);
}
//-----------------------------------------------------------------------------
// This variant tests when a caller code has already opened a HDF5 file
// and has a handle ready.
TEST(conduit_relay_io_hdf5, conduit_hdf5_write_read_by_file_handle)
{
uint32 a_val = 20;
uint32 b_val = 8;
uint32 c_val = 13;
Node n;
n["a"] = a_val;
n["b"] = b_val;
n["c"] = c_val;
EXPECT_EQ(n["a"].as_uint32(), a_val);
EXPECT_EQ(n["b"].as_uint32(), b_val);
EXPECT_EQ(n["c"].as_uint32(), c_val);
std::string test_file_name = "tout_hdf5_write_read_by_file_handle.hdf5";
// Set up hdf5 file and group that caller code would already have.
hid_t h5_file_id = H5Fcreate(test_file_name.c_str(),
H5F_ACC_TRUNC,
H5P_DEFAULT,
H5P_DEFAULT);
// Prepare group that caller code wants conduit to save it's tree to that
// group. (could also specify group name for conduit to create via
// hdf5_path argument to write call.
hid_t h5_group_id = H5Gcreate(h5_file_id,
"sample_group_name",
H5P_DEFAULT,
H5P_DEFAULT,
H5P_DEFAULT);
io::hdf5_write(n,h5_group_id);
hid_t status = H5Gclose(h5_group_id);
// Another variant of this - caller code has a pre-existing group they
// want to write into, but they want to use the 'group name' arg to do it
// Relay should be able to write into existing group.
h5_group_id = H5Gcreate(h5_file_id,
"sample_group_name2",
H5P_DEFAULT,
H5P_DEFAULT,
H5P_DEFAULT);
io::hdf5_write(n,h5_file_id, "sample_group_name2");
status = H5Gclose(h5_group_id);
status = H5Fclose(h5_file_id);
h5_file_id = H5Fopen(test_file_name.c_str(),
H5F_ACC_RDONLY,
H5P_DEFAULT);
// Caller code switches to group it wants to read in. (could also
// specify group name for conduit to read out via hdf5_path arg to read
// call)
h5_group_id = H5Gopen(h5_file_id, "sample_group_name", 0);
Node n_load;
io::hdf5_read(h5_group_id, n_load);
status = H5Gclose(h5_group_id);
status = H5Fclose(h5_file_id);
EXPECT_EQ(n_load["a"].as_uint32(), a_val);
EXPECT_EQ(n_load["b"].as_uint32(), b_val);
EXPECT_EQ(n_load["c"].as_uint32(), c_val);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_write_to_existing_dset)
{
Node n_in(DataType::uint32(2));
uint32_array val_in = n_in.value();
val_in[0] = 1;
val_in[1] = 2;
// Set up hdf5 file and group that caller code would already have.
hid_t h5_file_id = H5Fcreate("tout_hdf5_wr_existing_dset.hdf5",
H5F_ACC_TRUNC,
H5P_DEFAULT,
H5P_DEFAULT);
io::hdf5_write(n_in,h5_file_id,"myarray");
val_in[0] = 3;
val_in[1] = 4;
io::hdf5_write(n_in,h5_file_id,"myarray");
// trying to write an incompatible dataset will throw an error
Node n_incompat;
n_incompat = 64;
EXPECT_THROW(io::hdf5_write(n_incompat,h5_file_id,"myarray"),
conduit::Error);
H5Fclose(h5_file_id);
// check that the second set of values are the ones we get back
Node n_read;
io::hdf5_read("tout_hdf5_wr_existing_dset.hdf5:myarray",n_read);
uint32_array val = n_read.value();
EXPECT_EQ(val[0],3);
EXPECT_EQ(val[1],4);
Node n_w2;
n_w2["myarray"].set_external(n_read);
n_w2["a/b/c"].set_uint64(123);
// this should be compatible
io::hdf5_write(n_w2,"tout_hdf5_wr_existing_dset.hdf5");
n_read.reset();
io::hdf5_read("tout_hdf5_wr_existing_dset.hdf5",n_read);
uint32_array myarray_val = n_read["myarray"].value();
uint64 a_b_c_val = n_read["a/b/c"].value();
EXPECT_EQ(myarray_val[0],3);
EXPECT_EQ(myarray_val[1],4);
EXPECT_EQ(a_b_c_val,123);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_write_read_leaf_arrays)
{
Node n;
n["v_int8"].set(DataType::int8(5));
n["v_int16"].set(DataType::int16(5));
n["v_int32"].set(DataType::int32(5));
n["v_int64"].set(DataType::int64(5));
n["v_uint8"].set(DataType::uint8(5));
n["v_uint16"].set(DataType::uint16(5));
n["v_uint32"].set(DataType::uint32(5));
n["v_uint64"].set(DataType::uint64(5));
n["v_float32"].set(DataType::float32(5));
n["v_float64"].set(DataType::float64(5));
n["v_string"].set("my_string");
int8 *v_int8_ptr = n["v_int8"].value();
int16 *v_int16_ptr = n["v_int16"].value();
int32 *v_int32_ptr = n["v_int32"].value();
int64 *v_int64_ptr = n["v_int64"].value();
uint8 *v_uint8_ptr = n["v_uint8"].value();
uint16 *v_uint16_ptr = n["v_uint16"].value();
uint32 *v_uint32_ptr = n["v_uint32"].value();
uint64 *v_uint64_ptr = n["v_uint64"].value();
float32 *v_float32_ptr = n["v_float32"].value();
float64 *v_float64_ptr = n["v_float64"].value();
for(index_t i=0; i < 5; i++)
{
v_int8_ptr[i] = -8;
v_int16_ptr[i] = -16;
v_int32_ptr[i] = -32;
v_int64_ptr[i] = -64;
v_uint8_ptr[i] = 8;
v_uint16_ptr[i] = 16;
v_uint32_ptr[i] = 32;
v_uint64_ptr[i] = 64;
v_float32_ptr[i] = 32.0;
v_float64_ptr[i] = 64.0;
}
n.print_detailed();
io::hdf5_write(n,"tout_hdf5_wr_leaf_arrays.hdf5");
Node n_load;
io::hdf5_read("tout_hdf5_wr_leaf_arrays.hdf5",n_load);
n_load.print_detailed();
int8_array v_int8_out = n_load["v_int8"].value();
int16_array v_int16_out = n_load["v_int16"].value();
int32_array v_int32_out = n_load["v_int32"].value();
int64_array v_int64_out = n_load["v_int64"].value();
EXPECT_EQ(v_int8_out.number_of_elements(),5);
EXPECT_EQ(v_int16_out.number_of_elements(),5);
EXPECT_EQ(v_int32_out.number_of_elements(),5);
EXPECT_EQ(v_int64_out.number_of_elements(),5);
uint8_array v_uint8_out = n_load["v_uint8"].value();
uint16_array v_uint16_out = n_load["v_uint16"].value();
uint32_array v_uint32_out = n_load["v_uint32"].value();
uint64_array v_uint64_out = n_load["v_uint64"].value();
EXPECT_EQ(v_uint8_out.number_of_elements(),5);
EXPECT_EQ(v_uint16_out.number_of_elements(),5);
EXPECT_EQ(v_uint32_out.number_of_elements(),5);
EXPECT_EQ(v_uint64_out.number_of_elements(),5);
float32_array v_float32_out = n_load["v_float32"].value();
float64_array v_float64_out = n_load["v_float64"].value();
EXPECT_EQ(v_float32_out.number_of_elements(),5);
EXPECT_EQ(v_float64_out.number_of_elements(),5);
std::string v_string_out = n_load["v_string"].as_string();
EXPECT_EQ(v_string_out,"my_string");
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_write_read_empty)
{
Node n;
n["path/to/empty"];
n.print_detailed();
io::hdf5_write(n,"tout_hdf5_wr_empty.hdf5");
Node n_load;
io::hdf5_read("tout_hdf5_wr_empty.hdf5",n_load);
n_load.print_detailed();
EXPECT_EQ(n["path/to/empty"].dtype().id(),
n_load["path/to/empty"].dtype().id());
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, hdf5_write_zero_sized_leaf)
{
// this tests
Node n;
n["a"].set(DataType::float64(0));
n.print_detailed();
io::hdf5_write(n,"tout_hdf5_w_0.hdf5");
EXPECT_EQ(n["a"].dtype().number_of_elements(),0);
EXPECT_EQ(n["a"].dtype().id(),DataType::FLOAT64_ID);
Node n_load;
io::hdf5_read("tout_hdf5_w_0.hdf5",n_load);
n_load.print_detailed();
EXPECT_EQ(n_load["a"].dtype().number_of_elements(),0);
EXPECT_EQ(n_load["a"].dtype().id(),DataType::FLOAT64_ID);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_write_read_childless_object)
{
Node n;
n["path/to/empty"].set(DataType::object());
n.print_detailed();
io::hdf5_write(n,"tout_hdf5_wr_cl_obj.hdf5");
Node n_load;
io::hdf5_read("tout_hdf5_wr_cl_obj.hdf5",n_load);
n_load.print_detailed();
EXPECT_EQ(n["path/to/empty"].dtype().id(),
n_load["path/to/empty"].dtype().id());
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_test_write_incompat)
{
Node n;
n["a/b/leaf"] = DataType::uint32(2);
n["a/b/grp/leaf"].set_uint32(10);
uint32_array vals = n["a/b/leaf"].value();
vals[0] = 1;
vals[1] = 2;
io::hdf5_write(n,"tout_hdf5_test_write_incompat.hdf5");
n.print();
Node n2;
n2["a/b/leaf/v"] = DataType::float64(2);
n2["a/b/grp/leaf/v"].set_float64(10.0);
n2.print();
hid_t h5_file_id = H5Fopen("tout_hdf5_test_write_incompat.hdf5",
H5F_ACC_RDWR,
H5P_DEFAULT);
try
{
io::hdf5_write(n2,h5_file_id);
}
catch(Error &e)
{
CONDUIT_INFO(e.message());
}
H5Fclose(h5_file_id);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, auto_endian)
{
Node n;
n["a"].set_int64(12345689);
n["b"].set_int64(-12345689);
if(Endianness::machine_is_big_endian())
{
n.endian_swap_to_little();
}
else
{
n.endian_swap_to_big();
}
io::hdf5_write(n,"tout_hdf5_wr_opp_endian.hdf5");
Node n_load;
io::hdf5_read("tout_hdf5_wr_opp_endian.hdf5",n_load);
EXPECT_EQ(n_load["a"].as_int64(),12345689);
EXPECT_EQ(n_load["b"].as_int64(),-12345689);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, hdf5_path_exists)
{
std::string test_file_name = "tout_hdf5_wr_hdf5_path_exists.hdf5";
Node n;
n["a/b/c/d"] = 10;
n["a/b/c/f"] = 20;
io::hdf5_write(n,test_file_name);
hid_t h5_file_id = H5Fopen(test_file_name.c_str(),
H5F_ACC_RDONLY,
H5P_DEFAULT);
hid_t h5_grp_a = H5Gopen(h5_file_id, "a", 0);
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"a"));
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"a/b"));
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"a/b/c"));
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"a/b/c/d"));
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"a/b/c/f"));
EXPECT_TRUE(io::hdf5_has_path(h5_grp_a,"b"));
EXPECT_TRUE(io::hdf5_has_path(h5_grp_a,"b/c"));
EXPECT_TRUE(io::hdf5_has_path(h5_grp_a,"b/c/d"));
EXPECT_TRUE(io::hdf5_has_path(h5_grp_a,"b/c/f"));
EXPECT_FALSE(io::hdf5_has_path(h5_file_id,"BAD"));
EXPECT_FALSE(io::hdf5_has_path(h5_file_id,"a/BAD"));
EXPECT_FALSE(io::hdf5_has_path(h5_file_id,"a/b/BAD"));
EXPECT_FALSE(io::hdf5_has_path(h5_file_id,"a/b/c/BAD"));
EXPECT_FALSE(io::hdf5_has_path(h5_file_id,"a/b/c/d/e/f/g"));
EXPECT_FALSE(io::hdf5_has_path(h5_grp_a,"BAD"));
EXPECT_FALSE(io::hdf5_has_path(h5_grp_a,"b/BAD"));
EXPECT_FALSE(io::hdf5_has_path(h5_grp_a,"b/c/BAD"));
EXPECT_FALSE(io::hdf5_has_path(h5_grp_a,"b/c/d/e/f/g"));
H5Gclose(h5_grp_a);
H5Fclose(h5_file_id);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, hdf5_create_append_methods)
{
std::string test_file_name = "tout_hdf5_open_append.hdf5";
utils::remove_path_if_exists(test_file_name);
Node n;
n["a/b/c/d"] = 10;
io::hdf5_write(n,test_file_name,true);
n.reset();
n["a/b/c/e"] = 20;
io::hdf5_write(n,test_file_name,true);
Node n_load;
io::hdf5_read(test_file_name,n_load);
EXPECT_TRUE(n_load.has_path("a"));
EXPECT_TRUE(n_load.has_path("a/b"));
EXPECT_TRUE(n_load.has_path("a/b/c"));
EXPECT_TRUE(n_load.has_path("a/b/c/d"));
EXPECT_TRUE(n_load.has_path("a/b/c/e"));
EXPECT_EQ(n_load["a/b/c/d"].to_int32(),10);
EXPECT_EQ(n_load["a/b/c/e"].to_int32(),20);
io::hdf5_write(n,test_file_name,false);
n_load.reset();
io::hdf5_read(test_file_name,n_load);
EXPECT_FALSE(n_load.has_path("a/b/c/d"));
EXPECT_EQ(n_load["a/b/c/e"].to_int32(),20);
n.reset();
n["a/b/c/d"] = 10;
io::hdf5_save(n,test_file_name);
n_load.reset();
io::hdf5_read(test_file_name,n_load);
EXPECT_FALSE(n_load.has_path("a/b/c/e"));
EXPECT_EQ(n_load["a/b/c/d"].to_int32(),10);
n.reset();
n["a/b/c/e"] = 20;
io::hdf5_write(n,test_file_name,true);
n.reset();
n["a/b/c/e"] = 20;
io::hdf5_append(n,test_file_name);
n_load.reset();
io::hdf5_read(test_file_name,n_load);
EXPECT_TRUE(n_load.has_path("a/b/c/d"));
EXPECT_TRUE(n_load.has_path("a/b/c/e"));
EXPECT_EQ(n_load["a/b/c/d"].to_int32(),10);
EXPECT_EQ(n_load["a/b/c/e"].to_int32(),20);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, hdf5_create_open_methods)
{
std::string test_file_name = "tout_hdf5_open_and_create.hdf5";
Node n;
n["a/b/c/d"] = 10;
hid_t h5_file_id = io::hdf5_create_file(test_file_name);
io::hdf5_write(n,h5_file_id);
io::hdf5_close_file(h5_file_id);
h5_file_id = io::hdf5_open_file_for_read(test_file_name);
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"a"));
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"a/b"));
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"a/b/c"));
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"a/b/c/d"));
Node n_read;
io::hdf5_read(h5_file_id,"a/b/c/d",n_read);
EXPECT_EQ(10,n_read.to_int());
io::hdf5_close_file(h5_file_id);
h5_file_id = io::hdf5_open_file_for_read_write(test_file_name);
Node n2;
n2 = 12;
io::hdf5_write(n2,h5_file_id,"a/b/c/e");
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"a/b/c/e"));
io::hdf5_read(h5_file_id,"a/b/c/e",n_read);
EXPECT_EQ(12,n_read.to_int());
io::hdf5_close_file(h5_file_id);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_save_generic_options)
{
// 5k zeros, should compress well, but under default
// threshold size
Node n;
n["value"] = DataType::float64(5000);
Node opts;
opts["hdf5/chunking/threshold"] = 2000;
opts["hdf5/chunking/chunk_size"] = 2000;
std::string tout_std = "tout_hdf5_save_generic_default_options.hdf5";
std::string tout_cmp = "tout_hdf5_save_generic_test_options.hdf5";
utils::remove_path_if_exists(tout_std);
utils::remove_path_if_exists(tout_cmp);
io::save(n,tout_std, "hdf5");
io::save(n,tout_cmp, "hdf5", opts);
EXPECT_TRUE(utils::is_file(tout_std));
EXPECT_TRUE(utils::is_file(tout_cmp));
int64 tout_std_fs = utils::file_size(tout_std);
int64 tout_cmp_fs = utils::file_size(tout_cmp);
CONDUIT_INFO("fs test: std = "
<< tout_std_fs
<< ", cmp ="
<< tout_cmp_fs);
EXPECT_TRUE(tout_cmp_fs < tout_std_fs);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_group_list_children)
{
Node n;
n["path/sub1/a"];
n["path/sub1/b"];
n["path/sub1/c"];
n["path/sub2/d"];
n["path/sub2/e"];
n["path/sub2/f"];
std::string tout = "tout_hdf5_grp_chld_names.hdf5";
utils::remove_path_if_exists(tout);
io::save(n,tout, "hdf5");
EXPECT_TRUE(utils::is_file(tout));
hid_t h5_file_id = io::hdf5_open_file_for_read(tout);
std::vector<std::string> cnames;
io::hdf5_group_list_child_names(h5_file_id,"/",cnames);
EXPECT_EQ(cnames.size(),1);
EXPECT_EQ(cnames[0],"path");
io::hdf5_group_list_child_names(h5_file_id,"path",cnames);
EXPECT_EQ(cnames.size(),2);
EXPECT_EQ(cnames[0],"sub1");
EXPECT_EQ(cnames[1],"sub2");
io::hdf5_group_list_child_names(h5_file_id,"path/sub1",cnames);
EXPECT_EQ(cnames.size(),3);
EXPECT_EQ(cnames[0],"a");
EXPECT_EQ(cnames[1],"b");
EXPECT_EQ(cnames[2],"c");
io::hdf5_group_list_child_names(h5_file_id,"path/sub2",cnames);
EXPECT_EQ(cnames.size(),3);
EXPECT_EQ(cnames[0],"d");
EXPECT_EQ(cnames[1],"e");
EXPECT_EQ(cnames[2],"f");
// check leaf, which has no children
// this doesn't throw an error, but it creates an empty list
io::hdf5_group_list_child_names(h5_file_id,"path/sub1/a",cnames);
EXPECT_EQ(cnames.size(),0);
// totally bogus paths will trigger an error
EXPECT_THROW(io::hdf5_group_list_child_names(h5_file_id,"this/isnt/right",cnames),Error);
// empty string won't work in this case
EXPECT_THROW(io::hdf5_group_list_child_names(h5_file_id,"",cnames),Error);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, check_if_file_is_hdf5_file)
{
Node n;
n["path/mydata"] = 20;
std::string tout = "tout_hdf5_check_hdf5_file.hdf5";
utils::remove_path_if_exists(tout);
io::save(n,tout, "hdf5");
// this should be recoged as hdf5
EXPECT_TRUE(io::is_hdf5_file(tout));
// check behavior with files that have open handles
hid_t h5_file_id = io::hdf5_open_file_for_read_write(tout);
EXPECT_TRUE(io::is_hdf5_file(tout));
io::hdf5_close_file(h5_file_id);
h5_file_id = io::hdf5_open_file_for_read(tout);
EXPECT_TRUE(io::is_hdf5_file(tout));
io::hdf5_close_file(h5_file_id);
tout = "tout_hdf5_check_non_hdf5_file.json";
utils::remove_path_if_exists(tout);
io::save(n,tout,"json");
// this should *not* be recoged as hdf5
EXPECT_FALSE(io::is_hdf5_file(tout));
// check totally bad path
EXPECT_FALSE(io::is_hdf5_file("/path/to/somewhere/that/cant/exist"));
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, test_remove_path)
{
Node n;
n["path/mydata"] = 20;
n["path/otherdata/leaf"] = 42;
std::string tout = "tout_test_remove_path.hdf5";
utils::remove_path_if_exists(tout);
io::save(n,tout, "hdf5");
hid_t h5_file_id = io::hdf5_open_file_for_read_write(tout);
io::hdf5_remove_path(h5_file_id,"path/otherdata/leaf");
io::hdf5_close_file(h5_file_id);
n.reset();
io::load(tout,n);
EXPECT_FALSE(n.has_path("path/otherdata/leaf"));
EXPECT_TRUE(n.has_path("path/otherdata"));
n.print();
h5_file_id = io::hdf5_open_file_for_read_write(tout);
io::hdf5_remove_path(h5_file_id,"path/otherdata");
io::hdf5_close_file(h5_file_id);
n.reset();
io::load(tout,n);
EXPECT_FALSE(n.has_path("path/otherdata"));
EXPECT_TRUE(n.has_path("path"));
n.print();
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, file_name_in_error)
{
Node n;
n["path/mydata"] = 20;
n["path/otherdata/leaf"] = 42;
std::string tout = "tout_our_file_to_test.hdf5";
utils::remove_path_if_exists(tout);
io::save(n,tout, "hdf5");
hid_t h5_file_id = io::hdf5_open_file_for_read_write(tout);
Node n_read;
bool had_error = false;
try
{
io::hdf5_read(h5_file_id,"bad",n_read);
}
catch(Error &e)
{
had_error = true;
std::cout << "error message: " << e.message() ;
// error should have the file name in it
std::size_t found = e.message().find(tout);
EXPECT_TRUE(found!=std::string::npos);
}
// make sure we took the error path
EXPECT_TRUE(had_error);
io::hdf5_close_file(h5_file_id);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, test_read_various_string_style)
{
std::string tout = "tout_hdf5_wr_various_string_style.hdf5";
hid_t h5_file_id = H5Fcreate(tout.c_str(),
H5F_ACC_TRUNC,
H5P_DEFAULT,
H5P_DEFAULT);
// write this string several ways and make sure relay
// can reads them all as we expect
// 21 chars + null term (22 total)
std::string my_string = "this is my {} string!";
// case 0: conduit's current way to of doing things
Node n;
n.set(my_string);
io::hdf5_write(n,h5_file_id,"case_0");
// case 1: string that reflects our current data type
hid_t h5_dtype_id = H5Tcopy(H5T_C_S1);
// set size
hsize_t num_eles = 22;
H5Tset_size(h5_dtype_id, (size_t)num_eles);
H5Tset_strpad(h5_dtype_id, H5T_STR_NULLTERM);
hid_t h5_dspace_id = H5Screate(H5S_SCALAR);
// create new dataset
hid_t h5_dset_id = H5Dcreate(h5_file_id,
"case_1",
h5_dtype_id,
h5_dspace_id,
H5P_DEFAULT,
H5P_DEFAULT,
H5P_DEFAULT);
// write data
hid_t status = H5Dwrite(h5_dset_id,
h5_dtype_id,
H5S_ALL,
H5S_ALL,
H5P_DEFAULT,
my_string.c_str());
H5Tclose(h5_dtype_id);
H5Sclose(h5_dspace_id);
H5Dclose(h5_dset_id);
// case 2: string that is a simple array (old conduit way)
h5_dtype_id = H5T_C_S1;
num_eles = 22;
h5_dspace_id = H5Screate_simple(1,
&num_eles,
NULL);
// create new dataset
h5_dset_id = H5Dcreate(h5_file_id,
"case_2",
h5_dtype_id,
h5_dspace_id,
H5P_DEFAULT,
H5P_DEFAULT,
H5P_DEFAULT);
// write data
status = H5Dwrite(h5_dset_id,
h5_dtype_id,
H5S_ALL,
H5S_ALL,
H5P_DEFAULT,
my_string.c_str());
// H5Tclose(h5_dtype_id) -- don't need b/c we are using standard dtype
H5Sclose(h5_dspace_id);
H5Dclose(h5_dset_id);
// case 3: fixed lenght with diff term style
std::string my_string3 = "this is my {} string! ";
// len w/o null = 30
h5_dtype_id = H5Tcopy(H5T_C_S1);
num_eles = 30;
H5Tset_size(h5_dtype_id, (size_t)num_eles);
H5Tset_strpad(h5_dtype_id, H5T_STR_SPACEPAD);
h5_dspace_id = H5Screate(H5S_SCALAR);
// create new dataset
h5_dset_id = H5Dcreate(h5_file_id,
"case_3",
h5_dtype_id,
h5_dspace_id,
H5P_DEFAULT,
H5P_DEFAULT,
H5P_DEFAULT);
// write data
status = H5Dwrite(h5_dset_id,
h5_dtype_id,
H5S_ALL,
H5S_ALL,
H5P_DEFAULT,
my_string3.c_str());
H5Tclose(h5_dtype_id);
H5Sclose(h5_dspace_id);
H5Dclose(h5_dset_id);
// temp buffer to create a null padded string as
// input to write to hdf5
Node n_tmp;
n_tmp.set(DataType::uint8(30));
uint8 *mystring4_char_ptr = n_tmp.value();
// null out entire string (leave no doubt for test)
for(int i=0; i < 30; i++)
{
mystring4_char_ptr[i] = 0;
}
// copy over part of my_string before final space pad
for(size_t i=0; i < my_string.size(); i++)
{
mystring4_char_ptr[i] = my_string[i];
}
h5_dtype_id = H5Tcopy(H5T_C_S1);
num_eles = 30;
H5Tset_size(h5_dtype_id, (size_t)num_eles);
H5Tset_strpad(h5_dtype_id, H5T_STR_NULLPAD);
h5_dspace_id = H5Screate(H5S_SCALAR);
// create new dataset
h5_dset_id = H5Dcreate(h5_file_id,
"case_4",
h5_dtype_id,
h5_dspace_id,
H5P_DEFAULT,
H5P_DEFAULT,
H5P_DEFAULT);
// write data
status = H5Dwrite(h5_dset_id,
h5_dtype_id,
H5S_ALL,
H5S_ALL,
H5P_DEFAULT,
mystring4_char_ptr);
H5Tclose(h5_dtype_id);
H5Sclose(h5_dspace_id);
H5Dclose(h5_dset_id);
// case 5: string written using variable length
h5_dtype_id = H5Tcreate(H5T_STRING, H5T_VARIABLE);
h5_dspace_id = H5Screate(H5S_SCALAR);
const char *mystr_char_ptr = my_string.c_str();
// create new dataset
h5_dset_id = H5Dcreate(h5_file_id,
"case_5",
h5_dtype_id,
h5_dspace_id,
H5P_DEFAULT,
H5P_DEFAULT,
H5P_DEFAULT);
// write data
status = H5Dwrite(h5_dset_id,
h5_dtype_id,
H5S_ALL,
H5S_ALL,
H5P_DEFAULT,
&mystr_char_ptr);
//
H5Tclose(h5_dtype_id);
H5Sclose(h5_dspace_id);
H5Dclose(h5_dset_id);
H5Fclose(h5_file_id);
// load back in and make sure we get the correct string for each case
Node n_load;
io::load(tout,n_load);
n_load.print();
EXPECT_EQ(n_load["case_0"].as_string(), my_string );
EXPECT_EQ(n_load["case_1"].as_string(), my_string );
EXPECT_EQ(n_load["case_2"].as_string(), my_string );
EXPECT_EQ(n_load["case_3"].as_string(), my_string3 );
EXPECT_EQ(n_load["case_4"].as_string(), my_string );
EXPECT_EQ(n_load["case_5"].as_string(), my_string );
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_write_read_string_compress)
{
uint32 s_len = 10000;
std::string tout_std = "tout_hdf5_wr_string_no_compression.hdf5";
std::string tout_cmp = "tout_hdf5_wr_string_with_compression.hdf5";
std::string s_val = std::string(s_len, 'z');
Node n;
n["my_string"] = s_val;
Node opts;
opts["hdf5/chunking/threshold"] = 100;
opts["hdf5/chunking/chunk_size"] = 100;
// write out the string w and w/o compression
io::save(n,tout_std, "hdf5");
io::save(n,tout_cmp, "hdf5", opts);
Node n_out;
io::hdf5_read(tout_cmp,n_out);
EXPECT_EQ(n_out["my_string"].as_string(), s_val);
int64 tout_std_fs = utils::file_size(tout_std);
int64 tout_cmp_fs = utils::file_size(tout_cmp);
CONDUIT_INFO("fs test: std = "
<< tout_std_fs
<< ", cmp ="
<< tout_cmp_fs);
EXPECT_TRUE(tout_cmp_fs < tout_std_fs);
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_list)
{
std::string tout_std = "tout_hdf5_list.hdf5";
Node n;
n.append() = "42";
n.append() = "42";
n.append() = "42";
n.append() = "42";
Node &n_sub = n.append();
n_sub.append() = 42;
n_sub.append() = 42;
n_sub.append() = 42;
n_sub.append() = 42;
n_sub.append() = 42.0;
io::save(n,tout_std, "hdf5");
Node n_load, info;
io::load(tout_std,"hdf5",n_load);
n_load.print();
EXPECT_FALSE(n.diff(n_load,info));
hid_t h5_file_id = io::hdf5_open_file_for_read(tout_std);
/// check subpath of written list
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"0"));
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"4"));
EXPECT_FALSE(io::hdf5_has_path(h5_file_id,"5"));
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"4/0"));
EXPECT_TRUE(io::hdf5_has_path(h5_file_id,"4/4"));
EXPECT_FALSE(io::hdf5_has_path(h5_file_id,"4/5"));
n_load.reset();
io::hdf5_read(h5_file_id,"4/4",n_load);
EXPECT_EQ(n_load.to_float64(),42.0);
io::hdf5_close_file(h5_file_id);
// simple compat check (could be expanded)
Node n_check;
n_check = 42.0;
// this isn't compat with the existing file
h5_file_id = io::hdf5_open_file_for_read_write(tout_std);
EXPECT_THROW(io::hdf5_write(n_check,h5_file_id),Error);
// orig should be compat
n_check.set(n);
io::hdf5_write(n_check,h5_file_id);
// lets change the value of one of the list entries
n_check[4][4] = 3.1415;
io::hdf5_write(n_check,h5_file_id);
io::hdf5_close_file(h5_file_id);
io::load(tout_std,"hdf5",n_load);
n_load.print();
EXPECT_FALSE(n_check.diff(n_load,info));
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_list_with_offset)
{
std::string tout_std = "tout_hdf5_list_with_offset.hdf5";
Node n, opts;
n.append() = DataType::c_short(1);
short_array vals = n[0].value();
vals[0] = 1;
io::save(n,tout_std, "hdf5");
vals[0] = 2;
opts["offset"] = 1;
io::save(n,tout_std, "hdf5",opts);
Node n_load, info;
io::load(tout_std,"hdf5",n_load);
// check values of data
// since we didn't use save_merged, the first value should be overwritten
short_array read_vals = n_load[0].value();
EXPECT_EQ(0,read_vals[0]);
EXPECT_EQ(2,read_vals[1]);
// let's try again
vals[0] = 1;
io::save(n,tout_std, "hdf5");
vals[0] = 2;
opts["offset"] = 1;
io::save_merged(n,tout_std, "hdf5",opts);
io::load(tout_std,"hdf5",n_load);
read_vals = n_load[0].value();
EXPECT_EQ(1,read_vals[0]);
EXPECT_EQ(2,read_vals[1]);
vals[0] = 3;
opts["offset"] = 2;
io::save_merged(n,tout_std, "hdf5",opts);
vals[0] = 4;
opts["offset"] = 3;
io::save_merged(n,tout_std, "hdf5",opts);
vals[0] = 5;
opts["offset"] = 4;
io::save_merged(n,tout_std, "hdf5",opts);
vals[0] = 6;
opts["offset"] = 5;
io::save_merged(n,tout_std, "hdf5",opts);
io::load_merged(tout_std,"hdf5",n_load);
read_vals = n_load[0].value();
EXPECT_EQ(1,read_vals[0]);
EXPECT_EQ(2,read_vals[1]);
EXPECT_EQ(3,read_vals[2]);
EXPECT_EQ(4,read_vals[3]);
EXPECT_EQ(5,read_vals[4]);
EXPECT_EQ(6,read_vals[5]);
// try loading with offset and size
Node opts_read;
opts_read["offset"] = 2;
opts_read["size"] = 2;
io::load(tout_std,"hdf5",opts_read,n_load);
read_vals = n_load[0].value();
EXPECT_EQ(3,read_vals[0]);
EXPECT_EQ(4,read_vals[1]);
EXPECT_EQ(2, read_vals.number_of_elements());
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, conduit_hdf5_compat_with_empty)
{
std::string tout_std = "tout_hdf5_empty_compat.hdf5";
Node n;
n["myval"] = 42;
io::save(n,tout_std);
n["empty"] = DataType::empty();
n.print();
io::save_merged(n,tout_std);
// used to fail due to bad compat check
io::save_merged(n,tout_std);
Node n_load, n_diff_info;
io::load(tout_std,"hdf5",n_load);
n_load.print();
EXPECT_FALSE(n.diff(n_load,n_diff_info));
}
//-----------------------------------------------------------------------------
TEST(conduit_relay_io_hdf5, test_ref_path_error_msg)
{
// check that ref path only appears in the error message string once
Node n_about;
io::about(n_about);
// skip test if hdf5 isn't enabled
if(n_about["protocols/hdf5"].as_string() != "enabled")
return;
std::string tfile_out = "tout_hdf5_io_for_ref_path_error_msg.hdf5";
// remove files if they already exist
utils::remove_path_if_exists(tfile_out);
Node n, n_read, n_check, opts, info;
n["my/path/to/some/data"]= { 0,1,2,3,4,5,6,7,8,9};
io::save(n,tfile_out, "hdf5");
// bad offset
opts.reset();
opts["offset"] = 1000;
try
{
io::load(tfile_out,"hdf5",opts,n_read);
}
catch(conduit::Error &e)
{
std::string msg = e.message();
std::cout << "error message:"
<< msg << std::endl;
int count = 0;
std::string::size_type pos = 0;
std::string path = "my/path/to/some/data";
while ((pos = msg.find(path, pos )) != std::string::npos)
{
count++;
pos += path.length();
}
std::cout << "# of occurrences of path: " << count << std::endl;
// the path should only appear in the error message string once
EXPECT_EQ(count,1);
}
}
| 53,068 | 22,544 |
//
// code_1.cpp
// Algorithm
//
// Created by Mohd Shoaib Rayeen on 23/11/18.
// Copyright © 2018 Shoaib Rayeen. All rights reserved.
//
#include <iostream>
using namespace std;
long countWays(int n, int k) {
long dp[n + 1];
memset(dp, 0, sizeof(dp));
int mod = 1000000007;
dp[1] = k;
long same = 0, diff = k;
for (int i = 2; i <= n; i++) {
same = diff;
diff = dp[i-1] * (k-1);
diff = diff % mod;
dp[i] = (same + diff) % mod;
}
return dp[n];
}
int main() {
int n;
cout << "\nEnter N\t:\t";
cin >> n;
int k;
cout << "\nEnter K\t:\t";
cin >> k;
cout << "\nNumber of Ways\t:\t" << countWays(n,k) << endl;
return 0;
}
| 721 | 324 |
#include "CrosshairDrawer.hpp"
#include "Dr16.hpp"
#include "math.h"
#include "BoardPacket.hpp"
void CrosshairDrawner::Init()
{
SetDefaultTicksToUpdate(550);
m_pGimbalController = (GimbalController*)GetOwner()->GetEntity(ECT_GimbalController);
m_rpcIndex = 255;
BoardPacketManager::Instance()->GetTestPacket().AddObserver(this);
m_lastMaxProjectileVelocity = JudgeSystem::Instance()->GameRobotStatus.shooter_id1_17mm_speed_limit;
}
void CrosshairDrawner::Update()
{
if(m_rpcIndex == 0)
{
m_DrawBuffer.operate_tpye = JudgeSystem::GOT_Add;
m_DrawBuffer.graphic_name[2] = 1;
m_DrawBuffer.color = JudgeSystem::GCT_Cyan;
m_DrawBuffer.width = 2;
m_DrawBuffer.graphic_tpye = JudgeSystem::GT_Line;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
m_DrawBuffer.color = JudgeSystem::GCT_Green;
m_DrawBuffer.graphic_name[2] = 2;
m_DrawBuffer.radius = 50;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
m_DrawBuffer.graphic_name[2] = 3;
m_DrawBuffer.radius = 50;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
m_DrawBuffer.graphic_name[2] = 4;
m_DrawBuffer.radius = 50;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
m_DrawBuffer.graphic_name[2] = 5;
m_DrawBuffer.radius = 50;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
m_DrawBuffer.graphic_name[2] = 6;
m_DrawBuffer.radius = 50;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
m_DrawBuffer.graphic_name[2] = 7;
m_DrawBuffer.radius = 50;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
}
uint16_t latestMaxVel = JudgeSystem::Instance()->GameRobotStatus.shooter_id1_17mm_speed_limit;
if(latestMaxVel == m_lastMaxProjectileVelocity)
{
return;
}
m_lastMaxProjectileVelocity = latestMaxVel;
if(m_rpcIndex == 1)
{
m_DrawBuffer.operate_tpye = JudgeSystem::GOT_Modify;
m_DrawBuffer.graphic_tpye = JudgeSystem::GT_Line;
float _v = m_lastMaxProjectileVelocity;
float _v2 = _v * _v;
float _gimbalPitchAngle = - m_pGimbalController->GetGimbalMotor(GimbalController::GMT_Pitch)->sensorFeedBack.positionFdb;
float _cos = cos(_gimbalPitchAngle);
float _sin = sin(_gimbalPitchAngle);
float _time = 0.0f;
float _atan = 0.0f;
float _halfArmorLanding = 0.0;
float _l = 0.0f;
int16_t _dropPixel;
float _invV = 1 / _v;
m_DrawBuffer.graphic_name[2] = 1;
m_DrawBuffer.color = JudgeSystem::GCT_Orange;
m_DrawBuffer.width = 2;
_time = (_v * _sin + sqrt(_v2 * _sin * _sin + 2.0f * GRAVITY * GIMBAL_HEIGHT)) * INV_GRAVITY;
_atan = atan2(_sin - 0.5f * GRAVITY * _time * _invV, _cos);
_dropPixel = (int16_t)(PIXEL_RATIO * tan(_gimbalPitchAngle - _atan));
if(_dropPixel > 539)
{
_dropPixel = 539;
}
m_DrawBuffer.start_x = 960;
m_DrawBuffer.start_y = 540;
m_DrawBuffer.end_x = 960;
m_DrawBuffer.end_y = 540 - _dropPixel;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
m_DrawBuffer.graphic_name[2] = 2;
m_DrawBuffer.start_y = 540 - _dropPixel;
m_DrawBuffer.end_y = 540 - _dropPixel;
_l = _v * _time * _cos / cos(_atan);
_halfArmorLanding = PIXEL_RATIO * REF_LEN / _l;
m_DrawBuffer.start_x = 960 - _halfArmorLanding;
m_DrawBuffer.end_x = 960 + _halfArmorLanding;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
m_DrawBuffer.graphic_name[2] = 3;
m_DrawBuffer.color = JudgeSystem::GCT_Green;
_time = 0.1f;
_atan = atan2(_sin - 0.5f * GRAVITY * _time * _invV, _cos);
_dropPixel = (int16_t)(PIXEL_RATIO * tan(_gimbalPitchAngle - _atan));
if(_dropPixel > 539)
{
_dropPixel = 539;
}
m_DrawBuffer.start_y = 540 - _dropPixel;
m_DrawBuffer.end_y = 540 - _dropPixel;
_l = _v * _time * _cos / cos(_atan);
_halfArmorLanding = PIXEL_RATIO * REF_LEN / _l;
m_DrawBuffer.start_x = 960 - _halfArmorLanding;
m_DrawBuffer.end_x = 960 + _halfArmorLanding;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
m_DrawBuffer.graphic_name[2] = 4;
_time = 0.2f;
_atan = atan2(_sin - 0.5f * GRAVITY * _time * _invV, _cos);
_dropPixel = (int16_t)(PIXEL_RATIO * tan(_gimbalPitchAngle - _atan));
if(_dropPixel > 539)
{
_dropPixel = 539;
}
m_DrawBuffer.start_y = 540 - _dropPixel;
m_DrawBuffer.end_y = 540 - _dropPixel;
_l = _v * _time * _cos / cos(_atan);
_halfArmorLanding = PIXEL_RATIO * REF_LEN / _l;
m_DrawBuffer.start_x = 960 - _halfArmorLanding;
m_DrawBuffer.end_x = 960 + _halfArmorLanding;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
m_DrawBuffer.graphic_name[2] = 5;
_time = 0.4f;
_atan = atan2(_sin - 0.5f * GRAVITY * _time * _invV, _cos);
_dropPixel = (int16_t)(PIXEL_RATIO * tan(_gimbalPitchAngle - _atan));
if(_dropPixel > 539)
{
_dropPixel = 539;
}
m_DrawBuffer.start_y = 540 - _dropPixel;
m_DrawBuffer.end_y = 540 - _dropPixel;
_l = _v * _time * _cos / cos(_atan);
_halfArmorLanding = PIXEL_RATIO * REF_LEN / _l;
m_DrawBuffer.start_x = 960 - _halfArmorLanding;
m_DrawBuffer.end_x = 960 + _halfArmorLanding;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
m_DrawBuffer.graphic_name[2] = 6;
_time = 0.6f;
_atan = atan2(_sin - 0.5f * GRAVITY * _time * _invV, _cos);
_dropPixel = (int16_t)(PIXEL_RATIO * tan(_gimbalPitchAngle - _atan));
if(_dropPixel > 539)
{
_dropPixel = 539;
}
m_DrawBuffer.start_y = 540 - _dropPixel;
m_DrawBuffer.end_y = 540 - _dropPixel;
_l = _v * _time * _cos / cos(_atan);
_halfArmorLanding = PIXEL_RATIO * REF_LEN / _l;
m_DrawBuffer.start_x = 960 - _halfArmorLanding;
m_DrawBuffer.end_x = 960 + _halfArmorLanding;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
m_DrawBuffer.graphic_name[2] = 7;
_time = 0.8f;
_atan = atan2(_sin - 0.5f * GRAVITY * _time * _invV, _cos);
_dropPixel = (int16_t)(PIXEL_RATIO * tan(_gimbalPitchAngle - _atan));
if(_dropPixel > 539)
{
_dropPixel = 539;
}
m_DrawBuffer.start_y = 540 - _dropPixel;
m_DrawBuffer.end_y = 540 - _dropPixel;
_l = _v * _time * _cos / cos(_atan);
_halfArmorLanding = PIXEL_RATIO * REF_LEN / _l;
m_DrawBuffer.start_x = 960 - _halfArmorLanding;
m_DrawBuffer.end_x = 960 + _halfArmorLanding;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
}
else if(m_rpcIndex == 2)
{
/* code */
m_DrawBuffer.operate_tpye = JudgeSystem::GOT_Delete;
m_DrawBuffer.graphic_tpye = JudgeSystem::GT_Line;
m_DrawBuffer.layer = 0;
m_DrawBuffer.color = JudgeSystem::GCT_Black;
m_DrawBuffer.width = 2;
m_DrawBuffer.start_x = 960;
m_DrawBuffer.start_y = 540;
m_DrawBuffer.radius = m_Radius;
JudgeSystem::Instance()->ModfiyShapeOnClient(&m_DrawBuffer);
}
}
void CrosshairDrawner::OnNotify(void* _param)
{
m_rpcIndex = *(uint8_t*)_param;
}
| 7,723 | 3,056 |
// Copyright 2009-2021 NTESS. Under the terms
// of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
//
// Copyright (c) 2009-2021, NTESS
// All rights reserved.
//
// Portions are copyright of other developers:
// See the file CONTRIBUTORS.TXT in the top level directory
// the distribution for more information.
//
// This file is part of the SST software package. For license
// information, see the LICENSE file in the top level directory of the
// distribution.
#include <sst_config.h>
#include "cpu.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
static unsigned int missRate[][3] = {{0,51,32}, //app 0
{0,18,15}}; //app 1
static unsigned int isLoad[] = {3,32}; // out of 64
using namespace SST::VaultSim;
MemReqEvent *cpu::getInst(int cacheLevel, int app, int core) {
/*
app: MD(0) PHD(1)
l/s ratio 21:1 1:1
L1 miss/1Kinst 51 18
L2 miss/inst 32 15
*/
//printf("using missrate %d\n", missRate[app][cacheLevel]);
unsigned int roll1K = rng->generateNextUInt32() & 0x3ff;
if (roll1K <= missRate[app][cacheLevel]) {
//is a memory access
unsigned int roll = rng->generateNextUInt32();
unsigned int memRoll = roll & 0x3f;
Addr addr;
if ((memRoll & 0x1) == 0) {
// stride
addr = coreAddr[core] + (1 << 6);
addr = (addr >> 6) << 6;
} else {
//random
addr = (roll >> 6) << 6;
}
coreAddr[core] = addr;
bool isWrite;
if (memRoll <= isLoad[app]) {
isWrite = false;
} else {
isWrite = true;
}
MemReqEvent *event = new MemReqEvent((ReqId)this, addr, isWrite, 0, 0 );
return event;
} else {
return 0;
}
}
| 1,701 | 675 |
#include <cstdio>
int main(){
int n, k; scanf("%d %d", &n, &k);
int t = 240 - k;
int count(0);
while(t >= 5 * (count + 1)){++count; t -= 5 * count;}
count = (n < count) ? n : count;
printf("%d\n", count);
return 0;
}
| 248 | 111 |
/*
* Copyright (c) 2010 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE banner below
* An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the VPX_AUTHORS file in this directory
*/
/*
Copyright (c) 2010, Google 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 Google nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef VPX_DSP_BITREADER_H_
#define VPX_DSP_BITREADER_H_
#include <stddef.h>
#include <assert.h>
#include <limits.h>
#include <stdint.h>
#include "vpx_config.hh"
#include "billing.hh"
#include "../model/numeric.hh"
//#include "vpx_ports/mem.h"
//#include "vpx/vp8dx.h"
//#include "vpx/vpx_integer.h"
//#include "vpx_dsp/prob.h"
typedef size_t BD_VALUE;
#define BD_VALUE_SIZE ((int)sizeof(BD_VALUE) * CHAR_BIT)
// This is meant to be a large, positive constant that can still be efficiently
// loaded as an immediate (on platforms like ARM, for example).
// Even relatively modest values like 100 would work fine.
#define LOTS_OF_BITS 0x40000000
static std::atomic<uint32_t> test_packet_reader_atomic_test;
typedef std::pair<const uint8_t*, const uint8_t*> ROBuffer;
class PacketReader{
protected:
bool isEof;
public:
PacketReader() {
isEof = false;
}
// returns a buffer with at least sizeof(BD_VALUE) before it
virtual ROBuffer getNext() = 0;
bool eof()const {
return isEof;
}
virtual ~PacketReader(){}
};
class TestPacketReader :public PacketReader{
const uint8_t*cur;
const uint8_t*end;
public:
TestPacketReader(const uint8_t *start, const uint8_t *ed) {
isEof = false;
cur = start;
end = ed;
}
ROBuffer getNext(){
if (cur == end) {
isEof = true;
return {NULL, NULL};
}
if (end - cur > 16) {
size_t val = (test_packet_reader_atomic_test += 7)%16 + 1;
cur += val;
return {cur - val, cur};
}
const uint8_t *ret = cur;
cur = end;
return {ret, end};
}
bool eof()const {
return isEof;
}
};
class BiRope {
public:
ROBuffer rope[2];
// if we want partial data from a previous valuex
uint8_t backing[sizeof(BD_VALUE)];
BiRope() {
memset(&backing[0], 0, sizeof(BD_VALUE));
for (size_t i= 0; i < sizeof(rope)/sizeof(rope[0]); ++i) {
rope[i] = {NULL, NULL};
}
}
void push(ROBuffer data) {
if(rope[0].first == NULL) {
rope[0] = data;
}else {
always_assert(rope[1].first == NULL);
rope[1] = data;
}
}
size_t size() const {
return (rope[0].second-rope[0].first) +
(rope[1].second - rope[1].first);
}
void memcpy_ro(uint8_t *dest, size_t size) const {
if ((ptrdiff_t)size < rope[0].second-rope[0].first) {
memcpy(dest, rope[0].first, size);
return;
}
size_t del = rope[0].second-rope[0].first;
if (del) {
memcpy(dest, rope[0].first, del);
}
dest += del;
size -=del;
if (size) {
always_assert(rope[1].second - rope[1].first >= (ptrdiff_t)size);
memcpy(dest, rope[1].first, size);
}
}
void operator += (size_t del) {
if ((ptrdiff_t)del < rope[0].second - rope[0].first) {
rope[0].first += del;
return;
}
del -= rope[0].second - rope[0].first;
rope[0] = rope[1];
rope[1] = {NULL, NULL};
always_assert((ptrdiff_t)del <= rope[0].second - rope[0].first);
rope[0].first += del;
if (rope[0].first == rope[0].second) {
rope[0] = {NULL, NULL};
}
}
/*
void memcpy_pop(uint8_t *dest, size_t size) {
if (size < rope[0].second-rope[0].first) {
memcpy(dest, rope[0].first, size);
rope[0].first += size;
return;
} else {
size_t del = rope[0].second-rope[0].first;
memcpy(dest, rope[0].first, del);
dest += del;
size -= del;
rope[0] = rope[1];
rope[1] = {NULL, NULL};
}
if (size) {
always_assert(rope[0].second - rope[0].first < size);
memcpy(dest, rope[0].first, size);
rope[0].first += size;
if (rope[0].first == rope[0].second) {
rope[0] = {NULL, NULL};
}
}
}*/
};
typedef struct {
// Be careful when reordering this struct, it may impact the cache negatively.
BD_VALUE value;
unsigned int range;
int count;
BiRope buffer;
PacketReader *reader;
// vpx_decrypt_cb decrypt_cb;
// void *decrypt_state;
} vpx_reader;
int vpx_reader_init(vpx_reader *r,
PacketReader *reader);
static INLINE void vpx_reader_fill(vpx_reader *r) {
BD_VALUE value = r->value;
int count = r->count;
size_t bytes_left = r->buffer.size();
size_t bits_left = bytes_left * CHAR_BIT;
int shift = BD_VALUE_SIZE - CHAR_BIT - (count + CHAR_BIT);
if (bits_left <= BD_VALUE_SIZE && !r->reader->eof()) {
// pull some from reader
uint8_t local_buffer[sizeof(BD_VALUE)] = {0};
r->buffer.memcpy_ro(local_buffer, bytes_left);
r->buffer += bytes_left; // clear it out
while(true) {
auto next = r->reader->getNext();
if (next.second - next.first + bytes_left <= sizeof(BD_VALUE)) {
if (next.first != next.second) {
memcpy(local_buffer + bytes_left, next.first, next.second - next.first);
}
bytes_left += next.second - next.first;
} else {
if (bytes_left) {
memcpy(r->buffer.backing, local_buffer, bytes_left);
r->buffer.push({r->buffer.backing, r->buffer.backing + bytes_left});
}
r->buffer.push(next);
break;
}
if (r->reader->eof()) {
always_assert(bytes_left <= sizeof(BD_VALUE)); // otherwise we'd have break'd
memcpy(r->buffer.backing, local_buffer, bytes_left);
r->buffer.push({r->buffer.backing, r->buffer.backing + bytes_left});
break; // setup a simplistic rope that just points to the backing store
}
}
bytes_left = r->buffer.size();
bits_left = bytes_left * CHAR_BIT;
}
if (bits_left > BD_VALUE_SIZE) {
const int bits = (shift & 0xfffffff8) + CHAR_BIT;
BD_VALUE nv;
BD_VALUE big_endian_values;
r->buffer.memcpy_ro((uint8_t*)&big_endian_values, sizeof(BD_VALUE));
if (sizeof(BD_VALUE) == 8) {
big_endian_values = htobe64(big_endian_values);
} else {
big_endian_values = htobe32(big_endian_values);
}
nv = big_endian_values >> (BD_VALUE_SIZE - bits);
count += bits;
r->buffer += (bits >> 3);
value = r->value | (nv << (shift & 0x7));
} else {
const int bits_over = (int)(shift + CHAR_BIT - bits_left);
int loop_end = 0;
if (bits_over >= 0) {
count += LOTS_OF_BITS;
loop_end = bits_over;
}
if (bits_over < 0 || bits_left) {
while (shift >= loop_end) {
count += CHAR_BIT;
uint8_t cur_val = 0;
r->buffer.memcpy_ro(&cur_val, 1);
r->buffer += 1;
value |= ((BD_VALUE)cur_val) << shift;
shift -= CHAR_BIT;
}
}
}
// NOTE: Variable 'buffer' may not relate to 'r->buffer' after decryption,
// so we increase 'r->buffer' by the amount that 'buffer' moved, rather than
// assign 'buffer' to 'r->buffer'.
r->value = value;
r->count = count;
}
// Check if we have reached the end of the buffer.
//
// Variable 'count' stores the number of bits in the 'value' buffer, minus
// 8. The top byte is part of the algorithm, and the remainder is buffered
// to be shifted into it. So if count == 8, the top 16 bits of 'value' are
// occupied, 8 for the algorithm and 8 in the buffer.
//
// When reading a byte from the user's buffer, count is filled with 8 and
// one byte is filled into the value buffer. When we reach the end of the
// data, count is additionally filled with LOTS_OF_BITS. So when
// count == LOTS_OF_BITS - 1, the user's data has been exhausted.
//
// 1 if we have tried to decode bits after the end of stream was encountered.
// 0 No error.
#define vpx_reader_has_error(r) ((r)->count > BD_VALUE_SIZE && (r)->count < LOTS_OF_BITS)
extern int r_bitcount;
constexpr static uint8_t vpx_norm[256] = {
0, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/*
inline unsigned int count_leading_zeros_uint8(uint8_t split) {
unsigned int shift = 0;
if (split < 128) {
shift = 1;
}
if (split < 64) {
shift = 2;
}
if (split < 32) {
shift = 3;
}
if (split < 16) {
shift = 4;
}
if (split < 8) {
shift = 5;
}
if (split < 4) {
shift = 6;
}
if (split == 1) {
shift = 7;
}
return shift;
}
*/
#ifndef _WIN32
__attribute__((always_inline))
#endif
inline uint8_t count_leading_zeros_uint8(uint8_t v) {
return vpx_norm[v];
dev_assert(v);
return __builtin_clz((uint32_t)v) - 24; // slower
uint8_t r = 0; // result of log2(v) will go here
if (v & 0xf0) {
r |= 4;
v >>= 4;
}
if (v & 0xc) {
v >>= 2;
r |= 2;
}
if (v & 0x2) {
v >>= 1;
r |= 1;
}
return 7 - r;
}
inline bool vpx_reader_fill_and_read(vpx_reader *r, unsigned int split, Billing bill) {
BD_VALUE bigsplit = (BD_VALUE)split << (BD_VALUE_SIZE - CHAR_BIT);
vpx_reader_fill(r);
BD_VALUE value = r->value;
bool bit = (value >= bigsplit);
int count = r->count;
unsigned int range;
if (bit) {
range = r->range - split;
value = value - bigsplit;
} else {
range = split;
}
//unsigned int shift = vpx_norm[range];
unsigned int shift = count_leading_zeros_uint8(range);
range <<= shift;
value <<= shift;
count -= shift;
write_bit_bill(bill, true, shift);
r->value = value;
r->count = count;
r->range = range;
return bit;
}
#ifndef _WIN32
__attribute__((always_inline))
#endif
inline bool vpx_read(vpx_reader *r, int prob, Billing bill) {
int split = (r->range * prob + (256 - prob)) >> CHAR_BIT;
BD_VALUE value = r->value;
int count = r->count;
BD_VALUE bigsplit = (BD_VALUE)split << (BD_VALUE_SIZE - CHAR_BIT);
bool bit = value >= bigsplit;
unsigned int range;
#if 0
BD_VALUE mask = -(long long)bit;
value -= mask & bigsplit;
range = (r->range & mask) + (split ^ mask) - mask;
#else
if (bit) {
range = r->range - split;
value = value - bigsplit;
} else {
range = split;
}
#endif
if (__builtin_expect(r->count < 0, 0)) {
bit = vpx_reader_fill_and_read(r, split, bill);
#ifdef DEBUG_ARICODER
fprintf(stderr, "R %d %d %d\n", r_bitcount++, prob, bit);
#endif
return bit;
}
//unsigned int shift = vpx_norm[range];
unsigned int shift = count_leading_zeros_uint8(range);
range <<= shift;
value <<= shift;
count -= shift;
write_bit_bill(bill, true, shift);
r->value = value;
r->count = count;
r->range = range;
#ifdef DEBUG_ARICODER
fprintf(stderr, "R %d %d %d\n", r_bitcount++, prob, bit);
#endif
return bit;
}
#endif // VPX_DSP_BITREADER_H_
| 13,990 | 5,391 |
#include <AMReX.H>
#include "MyTest.H"
int main (int argc, char* argv[])
{
amrex::Initialize(argc, argv);
{
BL_PROFILE("main");
MyTest mytest;
for (int i = 0; i < 1; ++i) {
mytest.solve();
}
mytest.writePlotfile();
}
amrex::Finalize();
}
| 310 | 128 |