text string | size int64 | token_count int64 |
|---|---|---|
/*
* Copyright 2016-2020 Christian Lockley
*
* 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 "watchdogd.hpp"
int Identify(long timeout, const char * identity, const char * deviceName, bool verbose)
{
struct sockaddr_un address = {0};
struct identinfo buf;
int fd = -1;
address.sun_family = AF_UNIX;
strncpy(address.sun_path, "\0watchdogd.wdt.identity", sizeof(address.sun_path)-1);
fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0);
if (fd < 0) {
goto error;
}
if (connect(fd, (struct sockaddr*)&address, sizeof(address)) < 0) {
close(fd);
goto direct;
}
read(fd, &buf, sizeof(buf));
close(fd);
if (verbose) {
printf("watchdog was set to %li seconds\n", buf.timeout);
}
printf("%s\n", buf.name);
return 0;
direct:
if (!identity) {
size_t len0 = 0, len1 = 0;
int addZero = isdigit(*(basename(deviceName)+(strlen(basename(deviceName))-1)));
size_t l = strlen(basename(deviceName))+1;
char * watchdogBasename = (char*)calloc(1, l+1);
memcpy(watchdogBasename, basename(deviceName), l);
if (!addZero) {
watchdogBasename[strlen(watchdogBasename)] = '0';
}
char * sysfsIdentity = (char*)calloc(1, strlen(watchdogBasename)+strlen("/sys/class/watchdog//identity")+1);
char * sysfsTimeout = (char*)calloc(1, strlen(watchdogBasename)+strlen("/sys/class/watchdog//identity")+1);
sprintf(sysfsIdentity, "/sys/class/watchdog/%s/identity", watchdogBasename);
sprintf(sysfsTimeout, "/sys/class/watchdog/%s/timeout", watchdogBasename);
FILE * timeoutFile = fopen(sysfsTimeout, "r");
FILE * identityFile = fopen(sysfsIdentity, "r");
if (!identityFile||!timeoutFile)
goto error;
char *timeoutString = nullptr;
char *identityString = nullptr;
getline(&timeoutString, &len0, timeoutFile);
getline(&identityString, &len1, identityFile);
timeoutString[strlen(timeoutString)-1] = '\0';
identityString[strlen(identityString)-1] = '\0';
if (verbose) {
printf("watchdog was set to %s seconds\n", timeoutString);
}
printf("%s\n", identityString);
return 0;
}
if (verbose) {
printf("watchdog was set to %li seconds\n", timeout);
}
printf("%s\n", identity);
return 0;
error:
if (access(deviceName, R_OK|W_OK) != 0) {
printf("%s\n", "unable to open watchdog device, this operation requires permission from system Administrator");
return 0;
}
printf("%s\n", "Unable to open watchdog device");
return 0;
}
| 2,910 | 1,084 |
#include "test/engine/TestSystems.h"
#include "engine/system/Entity.h"
#include "engine/system/EntityManager.h"
#include "engine/utility/Debug.h"
namespace
{
//############################################################################
void TestEntityManagerSingleComponent(void)
{
EntityManager<float> entMan;
int const ent0 = entMan.AddEntity(2.0f);
int const ent1 = entMan.AddEntity(3.0f);
int const nonEnt = (ent0 + 1 == ent1 ? ent1 : ent0) + 1;
ASSERT(entMan.EntityCount() == 0);
entMan.Advance();
ASSERT(entMan.EntityCount() == 2);
ASSERT(entMan.GetComponent<float>(ent0) == 2.0f);
ASSERT(entMan.GetComponent<float>(ent1) == 3.0f);
ASSERT(entMan.ContainsComponent<float>(ent0));
ASSERT(entMan.ContainsComponent<float>(ent1));
EXPECT_ERROR(entMan.ContainsComponent<float>(nonEnt););
EXPECT_ERROR(entMan.GetComponent<float>(nonEnt););
entMan.SetComponent<float>(ent0, 4.0f);
entMan.Advance();
ASSERT(entMan.GetComponent<float>(ent0) == 4.0f);
entMan.SetComponent<float>(ent0, 2.0f);
ASSERT(entMan.GetComponent<float>(ent0) == 4.0f);
EXPECT_ERROR(entMan.SetComponent<float>(ent0, 3.0f););
entMan.UpdateComponent<float>(ent0) = 3.5f;
entMan.UpdateComponent<float>(ent1) = 5.5f;
entMan.Advance();
ASSERT(entMan.GetComponent<float>(ent0) == 3.5f);
ASSERT(entMan.GetComponent<float>(ent1) == 5.5f);
}
//############################################################################
void TestEntityManagerMultipleComponents(void)
{
EntityManager<float, int, bool> entMan;
int const ent0 = entMan.AddEntity(4.0f, 2);
int const ent1 = entMan.AddEntity(false, 2.0f);
int const ent2 = entMan.AddEntity(7, 3.0f, true);
ASSERT(entMan.EntityCount() == 0);
entMan.Advance();
ASSERT(entMan.EntityCount() == 3);
ASSERT(entMan.GetComponent<float>(ent0) == 4.0f);
ASSERT(entMan.ContainsComponent<float>(ent0));
ASSERT(entMan.ContainsComponent<float>(ent1));
ASSERT(entMan.ContainsComponent<float>(ent2));
ASSERT(entMan.ContainsComponent<int>(ent0));
ASSERT(!entMan.ContainsComponent<int>(ent1));
ASSERT(entMan.ContainsComponent<int>(ent2));
ASSERT(!entMan.ContainsComponent<bool>(ent0));
ASSERT(entMan.ContainsComponent<bool>(ent1));
ASSERT(entMan.ContainsComponent<bool>(ent2));
entMan.UpdateComponent<float>(ent1) = 3.5f;
EXPECT_ERROR(entMan.UpdateComponent<bool>(ent0););
ASSERT(entMan.GetComponent<float>(ent0) == 4.0f);
ASSERT(entMan.GetComponent<float>(ent1) == 2.0f);
ASSERT(entMan.GetComponent<float>(ent2) == 3.0f);
ASSERT(entMan.GetComponent<int>(ent0) == 2);
ASSERT(entMan.GetComponent<int>(ent2) == 7);
ASSERT(entMan.GetComponent<bool>(ent1) == false);
ASSERT(entMan.GetComponent<bool>(ent2) == true);
entMan.Advance();
ASSERT(entMan.GetComponent<float>(ent1) == 3.5f);
entMan.AddComponent(ent1, 4);
entMan.RemoveComponent<bool>(ent1);
entMan.Advance();
ASSERT(entMan.GetComponent<int>(ent1) == 4);
ASSERT(!entMan.ContainsComponent<bool>(ent1));
}
//############################################################################
void TestEntityManagerDestruction(void)
{
EntityManager<float, int, bool> entMan;
int const ent0 = entMan.AddEntity(4.0f, 2);
int const ent1 = entMan.AddEntity(false, 2.0f);
int const ent2 = entMan.AddEntity(7, 3.0f, true);
EXPECT_ERROR(entMan.DestroyEntity(ent1););
entMan.Advance();
entMan.DestroyEntity(ent1);
ASSERT(entMan.EntityCount() == 3);
entMan.Advance();
ASSERT(entMan.EntityCount() == 2);
ASSERT(entMan.DoesEntityExist(ent1) == false);
}
//############################################################################
void TestEntityManagerGroupGetters(void)
{
using EntMan = EntityManager<float, int, bool>;
EntMan entMan;
int const ent0 = entMan.AddEntity(4.0f, 2);
int const ent1 = entMan.AddEntity(false, 2.0f);
int const ent2 = entMan.AddEntity(7, 3.0f, true);
entMan.Advance();
auto compArray = entMan.GetComponents<float, bool>();
SortedArray<int> const & entityIds = compArray.EntityIds();
Array<bool const *> const & compBools = compArray.Components<bool>();
Array<float const *> const & compFloats = compArray.Components<float>();
ASSERT(entityIds.Size() == 2);
ASSERT(compBools.Size() == 2);
ASSERT(compFloats.Size() == 2);
int const ents[2] = { ent1, ent2 };
bool found[2] = { false, false };
for (int i = 0; i < entityIds.Size(); ++i)
{
ASSERT(entMan.GetEntityId(compBools[i]) == entityIds[i]);
ASSERT(entMan.GetEntityId(compFloats[i]) == entityIds[i]);
for (int j = 0; j < 2; ++j)
{
if (entityIds[i] == ents[j])
{
ASSERT(!found[j]);
found[j] = true;
break;
}
}
}
ASSERT(found[0] && found[1]);
}
//############################################################################
void TestEntityManagerIdGetterHelper(
EntityManager<float, int, bool> const & entMan)
{
Array<int> entityIds;
for (int i = 0; i < entMan.EntityCount(); ++i)
{
ASSERT(!entityIds.Contains(entMan.GetEntityId(i)));
entityIds.EmplaceBack(entMan.GetEntityId(i));
}
ASSERT(entityIds.Size() == entMan.EntityCount());
}
//############################################################################
void TestEntityManagerIdGetter(void)
{
EntityManager<float, int, bool> entMan;
int const ent0 = entMan.AddEntity(4.0f, 2);
int const ent1 = entMan.AddEntity(false, 2.0f);
int const ent2 = entMan.AddEntity(7, 3.0f, true);
entMan.Advance();
TestEntityManagerIdGetterHelper(entMan);
entMan.DestroyEntity(ent1);
entMan.Advance();
TestEntityManagerIdGetterHelper(entMan);
int const ent3 = entMan.AddEntity(2.5f, false, 4);
entMan.Advance();
TestEntityManagerIdGetterHelper(entMan);
entMan.DestroyEntity(ent2);
entMan.DestroyEntity(ent3);
entMan.DestroyEntity(ent0);
entMan.Advance();
TestEntityManagerIdGetterHelper(entMan);
}
//############################################################################
void TestEntityCreation(void)
{
EntityManager<float, int> entMan;
int const entIndex = entMan.AddEntity(2.0f);
Entity<float, int> ent(entMan, entIndex);
auto easyEnt = MakeEntity(entMan, entIndex);
ASSERT(easyEnt == ent);
ASSERT(!(easyEnt != ent));
EXPECT_ERROR(ent.GetComponent<float>(););
entMan.Advance();
ASSERT(ent.GetComponent<float>() == 2.0f);
EXPECT_ERROR(ent.GetComponent<int>(););
}
//############################################################################
void TestEntityManagers(void)
{
TestEntityManagerSingleComponent();
TestEntityManagerMultipleComponents();
TestEntityManagerDestruction();
TestEntityManagerGroupGetters();
}
//############################################################################
void TestEntities(void)
{
TestEntityCreation();
}
}
//##############################################################################
void TestAllSystems(void)
{
TestEntityManagers();
TestEntities();
}
| 7,285 | 2,572 |
#ifndef CGIROOT_HPP
#define CGIROOT_HPP
#include <string>
#include <Wt/WAnchor>
#include <Wt/WApplication>
#include <Wt/WButtonGroup>
#include <Wt/WComboBox>
#include <Wt/WContainerWidget>
#include <Wt/WDialog>
#include <Wt/WEnvironment>
#include <Wt/WFileUpload>
#include <Wt/WFormWidget>
#include <Wt/WImage>
#include <Wt/WInPlaceEdit>
#include <Wt/WIntValidator>
#include <Wt/WLineEdit>
#include <Wt/WLengthValidator>
#include <Wt/WMenuItem>
#include <Wt/WMessageBox>
#include <Wt/WPushButton>
#include <Wt/WRegExpValidator>
#include <Wt/WSignalMapper>
#include <Wt/WString>
#include <Wt/WText>
#include <Wt/WTextArea>
#include <Wt/WTextEdit>
#include <Wt/WWidget>
#include "clientinfo.hpp"
#include "db.hpp"
#include "serverinfo.hpp"
namespace SAAIIR {
class CgiRoot;
}
class SAAIIR::CgiRoot : public Wt::WApplication {
public:
CgiRoot(const Wt::WEnvironment& env);
virtual ~CgiRoot();
private:
ClientInfo *clientInfo;
ServerInfo *serverInfo;
std::string __loggedInUser;
std::string __lastIP;
std::string __lastCCode;
std::string __lastCName;
std::string __lastDate;
std::string __lastTime;
std::string __acLoggedInUser;
std::string __acLoggedInCode;
std::string __acLastIP;
std::string __acLastCCode;
std::string __acLastCName;
std::string __acLastDate;
std::string __acLastTime;
int __capResult;
std::string __capImage;
void GenCap();
void InitEnv(const Wt::WEnvironment& env);
bool IsReqRoot(const Wt::WEnvironment& env);
std::string IsReqACP(const Wt::WEnvironment& env);
DB db;
DB dbPics;
bool Validate(Wt::WFormWidget *widget);
bool ValidatePic(const std::string& file);
void ValidatePicClose(Wt::WDialog *sender);
bool ValidatePicFlag;
std::string ValidatePicPostAction;
std::string ValidatePicPostArgs;
/************* Home *************/
Wt::WWidget *Initialize_Home();
Wt::WContainerWidget *dvMainWrapper;
Wt::WContainerWidget *dvRegister;
Wt::WWidget *CMainMenu();
Wt::WWidget *CHowTo();
Wt::WWidget *CLinks();
Wt::WWidget *CContact();
Wt::WWidget *CAbout();
Wt::WMenu *mainMenu;
Wt::WContainerWidget *dvMainVote;
Wt::WLineEdit *followEdit;
Wt::WLineEdit *followCapEdit;
Wt::WLineEdit *academyUserEdit;
Wt::WLineEdit *academyPwEdit;
Wt::WLineEdit *academyCapEdit;
Wt::WLineEdit *voteCapEdit;
Wt::WLineEdit *regTyroCapEdit;
Wt::WImage *followCaptcha;
Wt::WImage *academyCaptcha;
Wt::WImage *voteCaptcha;
Wt::WImage *regTyroCaptcha;
Wt::WIntValidator *followCapValidator;
Wt::WIntValidator *academyCapValidator;
Wt::WIntValidator *voteCapValidator;
Wt::WIntValidator *regTyroCapValidator;
Wt::WText *errFollowing;
Wt::WText *errACLogin;
Wt::WText *errVote;
Wt::WButtonGroup *dvMainVoteRadioGroup;
bool IsForgetFormShownAcademy;
Wt::WContainerWidget *dvForgetFormWrapperAcademy;
Wt::WText *errForgetAcademy;
Wt::WLineEdit *forgetEmailEditAcademy;
Wt::WLineEdit *forgetCapEditAcademy;
Wt::WIntValidator *forgetCapValidatorAcademy;
Wt::WRegExpValidator *forgetEmailValidatorAcademy;
void ForgetOKAcademy();
void ReGenCap();
void AcademyForgetForm();
void FollowingOK();
void AcademiesOK();
void VoteOK();
void VoteChart();
Wt::WText *errContactForm;
Wt::WComboBox *contactToCmb;
Wt::WLineEdit *contactFromEdit;
Wt::WLineEdit *contactEmailEdit;
Wt::WLineEdit *contactUrlEdit;
Wt::WLineEdit *contactSubjectEdit;
Wt::WTextArea *contactBodyTArea;
Wt::WPushButton *contactSendBtn;
Wt::WPushButton *contactClearBtn;
Wt::WLineEdit *contactCapEdit;
Wt::WImage *contactCaptcha;
Wt::WLengthValidator *contactFromValidator;
Wt::WRegExpValidator *contactEmailValidator;
Wt::WRegExpValidator *contactUrlValidator;
Wt::WLengthValidator *contactSubjectValidator;
Wt::WLengthValidator *contactBodyValidator;
Wt::WIntValidator *contactCapValidator;
void SetCContactForm(bool flag);
void ContactToCmbChanged(Wt::WString to);
void ContactClearOK_RP();
void SendMessageOK();
Wt::WDialog *dlg;
Wt::WMessageBox *msgBox;
Wt::WComboBox *regProvinceCmb;
Wt::WComboBox *regCityCmb;
Wt::WLineEdit *regTermTitleEdit;
Wt::WComboBox *regTermBegdateCmbY;
Wt::WComboBox *regTermBegdateCmbM;
Wt::WComboBox *regTermBegdateCmbD;
Wt::WComboBox *regTermEnddateCmbY;
Wt::WComboBox *regTermEnddateCmbM;
Wt::WComboBox *regTermEnddateCmbD;
Wt::WComboBox *regTermDaypartCmb;
Wt::WLineEdit *tyroFNameEdit;
Wt::WLineEdit *tyroLNameEdit;
Wt::WComboBox *tyroSexCmb ;
Wt::WLineEdit *tyroFatherSNameEdit;
Wt::WLineEdit *tyroNationalCodeEdit;
Wt::WLineEdit *tyroBirthIdEdit;
Wt::WComboBox *tyroBirthDateCmbY;
Wt::WComboBox *tyroBirthDateCmbM;
Wt::WComboBox *tyroBirthDateCmbD;
Wt::WComboBox *tyroBirthlocCmb;
Wt::WComboBox *tyroBirthEmissionLocCmb;
Wt::WComboBox *tyroGraduateCertCmb;
Wt::WLineEdit *tyroGraduateCourseEdit;
Wt::WComboBox *tyroJobCmb;
Wt::WTextArea *tyroAddrTArea;
Wt::WLineEdit *tyroTelEdit;
Wt::WLineEdit *tyroMobileEdit;
Wt::WLineEdit *tyroEmailEdit;
Wt::WLengthValidator *tyroFNameValidator;
Wt::WLengthValidator *tyroLNameValidator;
Wt::WLengthValidator *tyroSexValidator;
Wt::WLengthValidator *tyroFatherSNameValidator;
Wt::WRegExpValidator *tyroNationalCodeValidator;
Wt::WRegExpValidator *tyroBirthIdValidator;
Wt::WLengthValidator *tyroBirthDateYValidator;
Wt::WLengthValidator *tyroBirthDateMValidator;
Wt::WLengthValidator *tyroBirthDateDValidator;
Wt::WLengthValidator *tyroBirthlocValidator;
Wt::WLengthValidator *tyroBirthEmissionLocValidator;
Wt::WLengthValidator *tyroGraduateCertValidator;
Wt::WLengthValidator *tyroGraduateCourseValidator;
Wt::WLengthValidator *tyroJobValidator;
Wt::WLengthValidator *tyroAddrValidator;
Wt::WRegExpValidator *tyroTelValidator;
Wt::WRegExpValidator *tyroMobileValidator;
Wt::WRegExpValidator *tyroEmailValidator;
Wt::WText *errTyroForm;
Wt::WFileUpload *tyroPicBirthCertFUP;
Wt::WFileUpload *tyroPicNationalCardFUP;
Wt::WFileUpload *tyroPicPersonnelFUP;
Wt::WFileUpload *tyroPicServiceFUP;
Wt::WPushButton *tyroPicBirthCertBtn;
Wt::WPushButton *tyroPicNationalCardBtn;
Wt::WPushButton *tyroPicPersonnelBtn;
Wt::WPushButton *tyroPicServiceBtn;
Wt::WPushButton *tyroRegFinishBtn;
std::string regTermAcCode,
regTermActCode,
regTermStTitle,
regTermBegdate,
regTermEnddate,
regTermDaypart,
regTermBegtime,
regTermEndtime,
regTermLoc,
regTermAcmName;
std::string regTyroFName,
regTyroLName,
regTyroSex,
regTyroFatherSName,
regTyroNationalCode,
regTyroBirthId,
regTyroBirthDateY,
regTyroBirthDateM,
regTyroBirthDateD,
regTyroBirthloc,
regTyroBirthEmissionLoc,
regTyroGraduateCert,
regTyroGraduateCourse,
regTyroJob,
regTyroAddr,
regTyroTel,
regTyroMobile,
regTyroEmail;
void RegProvinceCmbChanged(Wt::WString pr);
void ReturnHome();
void RegStep_2();
void RegStep_3(Wt::WPushButton *sender);
void RegStep_4();
void RegStep_5();
void RegStep_5_1();
void RegStep_5_2();
void RegStep_5_3();
void RegStep_5_4();
void RegStep_6();
/************* End Home *************/
/************* Root Login *************/
Wt::WContainerWidget *dvForgetFormWrapper_Root;
bool IsForgetFormShown_Root;
Wt::WImage *loginCaptcha_Root;
Wt::WIntValidator *loginCapValidator_Root;
Wt::WIntValidator *forgetCapValidator_Root;
Wt::WLengthValidator *loginUserValidator_Root;
Wt::WLengthValidator *loginPwValidator_Root;
Wt::WRegExpValidator *forgetEmailValidator_Root;
Wt::WText *errLogin_Root;
Wt::WText *errForget_Root;
void Error_Root(const std::wstring& err, Wt::WText *txt);
Wt::WLineEdit *loginUserEdit_Root;
Wt::WLineEdit *loginPwEdit_Root;
Wt::WLineEdit *loginCapEdit_Root;
Wt::WLineEdit *forgetEmailEdit_Root;
Wt::WLineEdit *forgetCapEdit_Root;
Wt::WWidget *Initialize_Root();
void InitializeTables_Root();
Wt::WWidget *RootLoginForm();
Wt::WWidget *RootRegisterForm();
void RootForgetForm();
void ReGenCap_Root();
void LoginOK_Root();
void ForgetOK_Root();
/************* End Root Login *************/
/************* Root Panel *************/
Wt::WMenu *mainMenu_RP;
void ExitRootPanel(Wt::WMenuItem *mItem);
/*Wt::WWidget *CHome_RP();
Wt::WWidget *CBase_RP();*/
Wt::WWidget *CAcademies_RP();
Wt::WWidget *CPages_RP();
Wt::WWidget *CContact_RP();
Wt::WWidget *CPwEMail_RP();
Wt::WWidget *CExit_RP();
void Initialize_RP();
Wt::WComboBox *pagesPListCmb_RP;
Wt::WTextEdit *pagesTEdit_RP;
Wt::WPushButton *pagesSaveBtn_RP;
Wt::WPushButton *pagesCloseBtn_RP;
std::wstring GetPageContent(const std::string& pg);
void SetPageContent(const std::string& pg, const std::string& content);
void SetCPagesForm_RP(bool flag);
void PagesPListCmbChanged_RP(Wt::WString pg);
void PagesTEditChanged_RP();
void PagesSaveBtnOK_RP();
void PagesCloseBtnOK_RP();
Wt::WLineEdit *currentPwEdit_RP;
Wt::WLineEdit *newPwEdit_RP;
Wt::WLineEdit *confirmPwEdit_RP;
Wt::WLineEdit *currentEmailEdit_RP;
Wt::WLineEdit *currentPwEmailEdit_RP;
Wt::WLengthValidator *currentPwValidator_RP;
Wt::WLengthValidator *newPwValidator_RP;
Wt::WLengthValidator *confirmPwValidator_RP;
Wt::WRegExpValidator *currentEmailValidator_RP;
Wt::WLengthValidator *currentPwEmailValidator_RP;
Wt::WText *errPw_RP;
Wt::WText *errEmail_RP;
void PwOK_RP();
void EmailOK_RP();
Wt::WText *errAddContact_RP;
Wt::WLengthValidator *contactNameValidator_RP;
Wt::WRegExpValidator *contactAddrValidator_RP;
Wt::WLineEdit *contactNameEdit_RP;
Wt::WLineEdit *contactAddrEdit_RP;
Wt::WPushButton *contactSaveBtn_RP;
Wt::WContainerWidget *dvContactTableWrapper_RP;
Wt::WInPlaceEdit *GetContactCell_RP(const std::string& cell, const std::string& id, const char *field,
Wt::WSignalMapper<Wt::WInPlaceEdit *> *map);
Wt::WPushButton *tableBtn_RP;
void CContactDataTable_RP();
void SaveContactTableCell_RP(Wt::WInPlaceEdit *sender);
void EraseContactTableCell_RP(Wt::WPushButton *sender);
void EraseContactTableCellOK_RP(Wt::StandardButton result);
void AddContactOK_RP();
Wt::WComboBox *academiesProvinceCmb_RP;
Wt::WComboBox *academiesCityCmb_RP;
void SetCAcademiesForm_RP(int flag);
void AcademiesProvinceCmbChanged_RP(Wt::WString pr);
void AcademiesCityCmbChanged_RP(Wt::WString pr);
void AcademiesAddBtnOK_RP();
//void AcademiesReturnBtnOK_RP();
Wt::WContainerWidget *dvAcademiesWrapper_RP;
Wt::WPushButton *academiesAddBtn_RP;
//Wt::WPushButton *academiesReturnBtn_RP;
void CAcademiesDataTable_RP();
void CourseAcademiesTableCell_RP(Wt::WPushButton *sender);
void MoreInfoAcademiesTableCell_RP(Wt::WAnchor *sender);
void MoreInfoAcademiesTableCell_RP(Wt::WPushButton *sender);
//void CpAcademiesTableCell_RP(Wt::WAnchor *sender);
void SuspendAcademiesTableCell_RP(Wt::WPushButton *sender);
void SuspendAcademiesTableCellOK_RP(Wt::StandardButton result);
void EditAcademiesTableCell_RP(Wt::WPushButton *sender);
void EraseAcademiesTableCell_RP(Wt::WPushButton *sender);
void EraseAcademiesTableCellOK_RP(Wt::StandardButton result);
Wt::WLineEdit *academiesNameEdit_RP;
Wt::WComboBox *academiesSexCmb_RP;
Wt::WLineEdit *academiesSubstationEdit_RP;
Wt::WComboBox *academiesJustificationCmb_RP;
Wt::WTextArea *academiesAddrTArea_RP;
Wt::WLineEdit *academiesTelEdit_RP;
Wt::WLineEdit *academiesManagerEdit_RP;
Wt::WLineEdit *academiesFounderEdit_RP;
Wt::WLineEdit *academiesUserEdit_RP;
Wt::WLineEdit *academiesPwEdit_RP;
Wt::WPushButton *academiesSaveBtn_RP;
/*Wt::WPushButton *eraseAcademiesBtn_RP;
Wt::WPushButton *suspendAcademiesBtn_RP;*/
Wt::WLengthValidator *academiesNameValidator_RP;
Wt::WLengthValidator *academiesSexValidator_RP;
Wt::WIntValidator *academiesSubstationValidator_RP;
Wt::WLengthValidator *academiesJustificationValidator_RP;
Wt::WLengthValidator *academiesAddrValidator_RP;
Wt::WRegExpValidator *academiesTelValidator_RP;
Wt::WLengthValidator *academiesManagerValidator_RP;
Wt::WLengthValidator *academiesFounderValidator_RP;
Wt::WLengthValidator *academiesUserValidator_RP;
Wt::WLengthValidator *academiesPwValidator_RP;
Wt::WText *errAcademiesForm_RP;
Wt::WWidget *GetAcademiesForm_RP(Wt::WString form);
void AcademiesFormSaveBtnOK_RP();
void AcCourseAddBtnOK_RP(Wt::WPushButton *sender);
void GetAcCourseDialog_RP(std::string acCode);
void GetAcCourseDialog_RP();
void EditAcCourseTableCell_RP(Wt::WPushButton *sender);
void EraseAcCourseTableCell_RP(Wt::WPushButton *sender);
void EraseAcCourseTableCellOK_RP(Wt::StandardButton result);
Wt::WComboBox *acCourseSkTitleCmb_RP;
Wt::WLineEdit *acCourseBackgroundEdit_RP;
Wt::WComboBox *acCourseJustdateCmbY_RP;
Wt::WComboBox *acCourseJustdateCmbM_RP;
Wt::WComboBox *acCourseJustdateCmbD_RP;
Wt::WComboBox *acCourseActstatCmb_RP;
Wt::WLineEdit *acCourseTyroaveragEdit_RP;
Wt::WPushButton *courseSaveBtn_RP;
Wt::WPushButton *eraseAcCourseBtn_RP;
Wt::WPushButton *suspendAcCourseBtn_RP;
Wt::WLengthValidator *acCourseSkTitleValidator_RP;
Wt::WIntValidator *acCourseBackgroundValidator_RP;
Wt::WLengthValidator *acCourseJustdateValidatorY_RP;
Wt::WLengthValidator *acCourseJustdateValidatorM_RP;
Wt::WLengthValidator *acCourseJustdateValidatorD_RP;
Wt::WLengthValidator *acCourseActstatValidator_RP;
Wt::WIntValidator *acCourseTyroaveragValidator_RP;
Wt::WText *errAcCourseForm_RP;
Wt::WWidget *GetAcCourseForm_RP(Wt::WString form);
void AcCourseFormSaveBtnOK_RP();
/************* End Root Panel *************/
/************* Academy Panel *************/
void Initialize_ACP();
void ClearLoginForm_ACP();
Wt::WContainerWidget *academyPage;
Wt::WWidget *FirstLogin_ACP();
Wt::WText *errConfirmFL_ACP;
Wt::WLineEdit *newEmailEditFL_ACP;
Wt::WLineEdit *confirmEmailEditFL_ACP;
Wt::WLineEdit *newPwEditFL_ACP;
Wt::WLineEdit *confirmPwEditFL_ACP;
Wt::WLineEdit *currentPwEditFL_ACP;
Wt::WPushButton *btnConfirmOK;
Wt::WRegExpValidator *newEmailValidatorFL_ACP;
Wt::WRegExpValidator *confirmEmailValidatorFL_ACP;
Wt::WLengthValidator *newPwValidatorFL_ACP;
Wt::WLengthValidator *confirmPwValidatorFL_ACP;
Wt::WLengthValidator *currentPwValidatorFL_ACP;
void ConfirmOKFL_ACP();
std::string AcSessionGen(const std::string& acCode, bool isRoot);
bool AcSessionValidate(const std::string& session);
void Go_ACPanel(const std::string& acCode);
void GoAway_ACP();
void Initialize_ACPanel();
Wt::WMenu *mainMenu_ACP;
void ExitACPanel(Wt::WMenuItem *mItem);
Wt::WWidget *CMentors_ACP();
Wt::WWidget *CTyros_ACP();
Wt::WWidget *CTerms_ACP();
Wt::WWidget *CPwEMail_ACP();
Wt::WWidget *CExit_ACP();
Wt::WLineEdit *currentPwEdit_ACP;
Wt::WLineEdit *newPwEdit_ACP;
Wt::WLineEdit *confirmPwEdit_ACP;
Wt::WLineEdit *currentEmailEdit_ACP;
Wt::WLineEdit *currentPwEmailEdit_ACP;
Wt::WLengthValidator *currentPwValidator_ACP;
Wt::WLengthValidator *newPwValidator_ACP;
Wt::WLengthValidator *confirmPwValidator_ACP;
Wt::WRegExpValidator *currentEmailValidator_ACP;
Wt::WLengthValidator *currentPwEmailValidator_ACP;
Wt::WText *errPw_ACP;
Wt::WText *errEmail_ACP;
void PwOK_ACP();
void EmailOK_ACP();
void MentorsAddBtnOK_ACP();
Wt::WContainerWidget *dvMentorsWrapper_ACP;
void CMentorsDataTable_ACP();
void MoreInfoMentorsTableCell_ACP(Wt::WAnchor *sender);
void MoreInfoMentorsTableCell_ACP(Wt::WPushButton *sender);
void CardMentorsTableCell_ACP(Wt::WPushButton *sender);
void EditMentorsTableCell_ACP(Wt::WPushButton *sender);
void EraseMentorsTableCell_ACP(Wt::WPushButton *sender);
void EraseMentorsTableCellOK_ACP(Wt::StandardButton result);
Wt::WLineEdit *mentorsFNameEdit_ACP;
Wt::WLineEdit *mentorsLNameEdit_ACP;
Wt::WComboBox *mentorsSexCmb_ACP;
Wt::WLineEdit *mentorsNationalCodeEdit_ACP;
Wt::WLineEdit *mentorsBirthIdEdit_ACP;
Wt::WComboBox *mentorsBirthDateCmbY_ACP;
Wt::WComboBox *mentorsBirthDateCmbM_ACP;
Wt::WComboBox *mentorsBirthDateCmbD_ACP;
Wt::WComboBox *mentorsBirthlocCmb_ACP;
Wt::WComboBox *mentorsBirthEmissionLocCmb_ACP;
Wt::WComboBox *mentorsGraduateCertCmb_ACP;
Wt::WLineEdit *mentorsGraduateCourseEdit_ACP;
Wt::WTextArea *mentorsAddrTArea_ACP;
Wt::WLineEdit *mentorsTelEdit_ACP;
Wt::WLineEdit *mentorsMobileEdit_ACP;
Wt::WLineEdit *mentorsEmailEdit_ACP;
Wt::WFileUpload *mentorsPicFUP_ACP;
Wt::WPushButton *mentorsSaveBtn_ACP;
Wt::WLengthValidator *mentorsFNameValidator_ACP;
Wt::WLengthValidator *mentorsLNameValidator_ACP;
Wt::WLengthValidator *mentorsSexValidator_ACP;
Wt::WRegExpValidator *mentorsNationalCodeValidator_ACP;
Wt::WRegExpValidator *mentorsBirthIdValidator_ACP;
Wt::WLengthValidator *mentorsBirthDateYValidator_ACP;
Wt::WLengthValidator *mentorsBirthDateMValidator_ACP;
Wt::WLengthValidator *mentorsBirthDateDValidator_ACP;
Wt::WLengthValidator *mentorsBirthlocValidator_ACP;
Wt::WLengthValidator *mentorsBirthEmissionLocValidator_ACP;
Wt::WLengthValidator *mentorsGraduateCertValidator_ACP;
Wt::WLengthValidator *mentorsGraduateCourseValidator_ACP;
Wt::WLengthValidator *mentorsAddrValidator_ACP;
Wt::WRegExpValidator *mentorsTelValidator_ACP;
Wt::WRegExpValidator *mentorsMobileValidator_ACP;
Wt::WRegExpValidator *mentorsEmailValidator_ACP;
Wt::WText *errMentorsForm_ACP;
Wt::WWidget *GetMentorsForm_ACP(Wt::WString form);
void MentorsFormFileUploaded_ACP();
void MentorsFormFileTooLarge_ACP();
void MentorsFormSaveBtnOK_ACP();
void MCardAddBtnOK_ACP(Wt::WPushButton *sender);
void GetMCardDialog_ACP(std::string acmCode);
void GetMCardDialog_ACP();
void EditMCardTableCell_ACP(Wt::WPushButton *sender);
void EraseMCardTableCell_ACP(Wt::WPushButton *sender);
void EraseMCardTableCellOK_ACP(Wt::StandardButton result);
Wt::WComboBox *mCardStTitleCmb_ACP;
Wt::WComboBox *mCardDateCmbY_ACP;
Wt::WComboBox *mCardDateCmbM_ACP;
Wt::WComboBox *mCardDateCmbD_ACP;
Wt::WLineEdit *mCardPercentEdit_ACP;
Wt::WPushButton *cardSaveBtn_ACP;
Wt::WPushButton *eraseCardBtn_ACP;
Wt::WPushButton *suspendCardBtn_ACP;
Wt::WLengthValidator *mCardStTitleValidator_ACP;
Wt::WLengthValidator *mCardDateValidatorY_ACP;
Wt::WLengthValidator *mCardDateValidatorM_ACP;
Wt::WLengthValidator *mCardDateValidatorD_ACP;
Wt::WIntValidator *mCardPercentValidator_ACP;
Wt::WText *errMCardForm_ACP;
Wt::WWidget *GetMCardForm_ACP(Wt::WString form);
void MCardFormSaveBtnOK_ACP();
void TermsAddBtnOK_ACP();
Wt::WContainerWidget *dvTermsWrapper_ACP;
void CTermsDataTable_ACP();
void NoticeTermsTableCell_ACP(Wt::WPushButton *sender);
void EditTermsTableCell_ACP(Wt::WPushButton *sender);
void EraseTermsTableCell_ACP(Wt::WPushButton *sender);
void EraseTermsTableCellOK_ACP(Wt::StandardButton result);
Wt::WComboBox *termsStTitleCmb_ACP;
Wt::WComboBox *termsBegdateCmbY_ACP;
Wt::WComboBox *termsBegdateCmbM_ACP;
Wt::WComboBox *termsBegdateCmbD_ACP;
Wt::WComboBox *termsEnddateCmbY_ACP;
Wt::WComboBox *termsEnddateCmbM_ACP;
Wt::WComboBox *termsEnddateCmbD_ACP;
Wt::WComboBox *termsDaypartCmb_ACP;
Wt::WComboBox *termsBegtimeCmbH_ACP;
Wt::WComboBox *termsBegtimeCmbM_ACP;
Wt::WComboBox *termsEndtimeCmbH_ACP;
Wt::WComboBox *termsEndtimeCmbM_ACP;
Wt::WComboBox *termsLocCmb_ACP;
Wt::WComboBox *termsMentorCmb_ACP;
Wt::WPushButton *termsSaveBtn_ACP;
Wt::WLengthValidator *termsStTitleValidator_ACP;
Wt::WLengthValidator *termsBegdateValidatorY_ACP;
Wt::WLengthValidator *termsBegdateValidatorM_ACP;
Wt::WLengthValidator *termsBegdateValidatorD_ACP;
Wt::WLengthValidator *termsEnddateValidatorY_ACP;
Wt::WLengthValidator *termsEnddateValidatorM_ACP;
Wt::WLengthValidator *termsEnddateValidatorD_ACP;
Wt::WLengthValidator *termsDaypartValidator_ACP;
Wt::WLengthValidator *termsBegtimeValidatorH_ACP;
Wt::WLengthValidator *termsBegtimeValidatorM_ACP;
Wt::WLengthValidator *termsEndtimeValidatorH_ACP;
Wt::WLengthValidator *termsEndtimeValidatorM_ACP;
Wt::WLengthValidator *termsLocValidator_ACP;
Wt::WLengthValidator *termsMentorValidator_ACP;
Wt::WText *errTermsForm_ACP;
Wt::WWidget *GetTermsForm_ACP(Wt::WString form);
void TermsFormSaveBtnOK_ACP();
Wt::WContainerWidget *dvTyrosWrapper_ACP;
void CTyrosDataTable_ACP();
void MoreInfoTyrosTableCell_ACP(Wt::WPushButton *sender);
void ShowTyroPic_ACP(Wt::WAnchor *sender);
void EditPicsTyrosTableCell_ACP(Wt::WPushButton *sender);
void EditPicsTyrosTableCellOK_ACP(Wt::WFileUpload *sender);
void EditTyrosTableCell_ACP(Wt::WPushButton *sender);
void EraseTyrosTableCell_ACP(Wt::WPushButton *sender);
void EraseTyrosTableCellOK_ACP(Wt::StandardButton result);
Wt::WLineEdit *tyrosFNameEdit_ACP;
Wt::WLineEdit *tyrosLNameEdit_ACP;
Wt::WComboBox *tyrosSexCmb_ACP;
Wt::WLineEdit *tyrosFatherSNameEdit_ACP;
Wt::WLineEdit *tyrosNationalCodeEdit_ACP;
Wt::WLineEdit *tyrosBirthIdEdit_ACP;
Wt::WComboBox *tyrosBirthDateCmbY_ACP;
Wt::WComboBox *tyrosBirthDateCmbM_ACP;
Wt::WComboBox *tyrosBirthDateCmbD_ACP;
Wt::WComboBox *tyrosBirthlocCmb_ACP;
Wt::WComboBox *tyrosBirthEmissionLocCmb_ACP;
Wt::WComboBox *tyrosGraduateCertCmb_ACP;
Wt::WLineEdit *tyrosGraduateCourseEdit_ACP;
Wt::WComboBox *tyrosJobCmb_ACP;
Wt::WTextArea *tyrosAddrTArea_ACP;
Wt::WLineEdit *tyrosTelEdit_ACP;
Wt::WLineEdit *tyrosMobileEdit_ACP;
Wt::WLineEdit *tyrosEmailEdit_ACP;
Wt::WPushButton *tyrosSaveBtn_ACP;
Wt::WLengthValidator *tyrosFNameValidator_ACP;
Wt::WLengthValidator *tyrosLNameValidator_ACP;
Wt::WLengthValidator *tyrosSexValidator_ACP;
Wt::WLengthValidator *tyrosFatherSNameValidator_ACP;
Wt::WRegExpValidator *tyrosNationalCodeValidator_ACP;
Wt::WRegExpValidator *tyrosBirthIdValidator_ACP;
Wt::WLengthValidator *tyrosBirthDateYValidator_ACP;
Wt::WLengthValidator *tyrosBirthDateMValidator_ACP;
Wt::WLengthValidator *tyrosBirthDateDValidator_ACP;
Wt::WLengthValidator *tyrosBirthlocValidator_ACP;
Wt::WLengthValidator *tyrosBirthEmissionLocValidator_ACP;
Wt::WLengthValidator *tyrosGraduateCertValidator_ACP;
Wt::WLengthValidator *tyrosGraduateCourseValidator_ACP;
Wt::WLengthValidator *tyrosJobValidator_ACP;
Wt::WLengthValidator *tyrosAddrValidator_ACP;
Wt::WRegExpValidator *tyrosTelValidator_ACP;
Wt::WRegExpValidator *tyrosMobileValidator_ACP;
Wt::WRegExpValidator *tyrosEmailValidator_ACP;
Wt::WText *errTyrosForm_ACP;
Wt::WWidget *GetTyrosForm_ACP(Wt::WString form);
void TyrosFormSaveBtnOK_ACP();
Wt::WFileUpload *tyrosPicBirthCertFUP_ACP;
Wt::WFileUpload *tyrosPicNationalCardFUP_ACP;
Wt::WFileUpload *tyrosPicPersonnelFUP_ACP;
Wt::WFileUpload *tyrosPicServiceFUP_ACP;
/************* End Academy Panel *************/
};
#endif /* CGIROOT_HPP */
| 23,952 | 9,269 |
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2019-2022 Second State INC
#include "executor/executor.h"
#include <array>
#include <cstdint>
#include <cstring>
namespace WasmEdge {
namespace Executor {
Expect<void> Executor::runExpression(Runtime::StoreManager &StoreMgr,
Runtime::StackManager &StackMgr,
AST::InstrView Instrs) {
return execute(StoreMgr, StackMgr, Instrs.begin(), Instrs.end());
}
Expect<void>
Executor::runFunction(Runtime::StoreManager &StoreMgr,
Runtime::StackManager &StackMgr,
const Runtime::Instance::FunctionInstance &Func,
Span<const ValVariant> Params) {
// Set start time.
if (Stat && Conf.getStatisticsConfigure().isTimeMeasuring()) {
Stat->startRecordWasm();
}
// Reset and push a dummy frame into stack.
StackMgr.pushFrame(nullptr, AST::InstrView::iterator(), 0, 0);
// Push arguments.
for (auto &Val : Params) {
StackMgr.push(Val);
}
// Enter and execute function.
AST::InstrView::iterator StartIt;
if (auto Res =
enterFunction(StoreMgr, StackMgr, Func, Func.getInstrs().end())) {
StartIt = *Res;
} else {
return Unexpect(Res);
}
auto Res = execute(StoreMgr, StackMgr, StartIt, Func.getInstrs().end());
if (Res) {
spdlog::debug(" Execution succeeded.");
} else if (Res.error() == ErrCode::Terminated) {
spdlog::debug(" Terminated.");
}
if (Stat && Conf.getStatisticsConfigure().isTimeMeasuring()) {
Stat->stopRecordWasm();
}
// If Statistics is enabled, then dump it here.
if (Stat) {
Stat->dumpToLog(Conf);
}
if (Res || Res.error() == ErrCode::Terminated) {
return {};
}
return Unexpect(Res);
}
Expect<void> Executor::execute(Runtime::StoreManager &StoreMgr,
Runtime::StackManager &StackMgr,
const AST::InstrView::iterator Start,
const AST::InstrView::iterator End) {
AST::InstrView::iterator PC = Start;
AST::InstrView::iterator PCEnd = End;
auto Dispatch = [this, &PC, &StoreMgr, &StackMgr]() -> Expect<void> {
const AST::Instruction &Instr = *PC;
switch (Instr.getOpCode()) {
// Control instructions.
case OpCode::Unreachable:
spdlog::error(ErrCode::Unreachable);
spdlog::error(
ErrInfo::InfoInstruction(Instr.getOpCode(), Instr.getOffset()));
return Unexpect(ErrCode::Unreachable);
case OpCode::Nop:
return {};
case OpCode::Block:
return {};
case OpCode::Loop:
return {};
case OpCode::If:
return runIfElseOp(StackMgr, Instr, PC);
case OpCode::Else:
if (Stat && Conf.getStatisticsConfigure().isCostMeasuring()) {
// Reach here means end of if-statement.
if (unlikely(!Stat->subInstrCost(Instr.getOpCode()))) {
spdlog::error(
ErrInfo::InfoInstruction(Instr.getOpCode(), Instr.getOffset()));
return Unexpect(ErrCode::CostLimitExceeded);
}
if (unlikely(!Stat->addInstrCost(OpCode::End))) {
spdlog::error(
ErrInfo::InfoInstruction(Instr.getOpCode(), Instr.getOffset()));
return Unexpect(ErrCode::CostLimitExceeded);
}
}
PC += PC->getJumpEnd();
[[fallthrough]];
case OpCode::End:
PC = StackMgr.maybePopFrame(PC);
return {};
case OpCode::Br:
return runBrOp(StackMgr, Instr, PC);
case OpCode::Br_if:
return runBrIfOp(StackMgr, Instr, PC);
case OpCode::Br_table:
return runBrTableOp(StackMgr, Instr, PC);
case OpCode::Return:
return runReturnOp(StackMgr, PC);
case OpCode::Call:
return runCallOp(StoreMgr, StackMgr, Instr, PC);
case OpCode::Call_indirect:
return runCallIndirectOp(StoreMgr, StackMgr, Instr, PC);
case OpCode::Return_call:
return runCallOp(StoreMgr, StackMgr, Instr, PC, true);
case OpCode::Return_call_indirect:
return runCallIndirectOp(StoreMgr, StackMgr, Instr, PC, true);
// Reference Instructions
case OpCode::Ref__null:
StackMgr.push<UnknownRef>(UnknownRef());
return {};
case OpCode::Ref__is_null: {
ValVariant &Val = StackMgr.getTop();
if (isNullRef(Val)) {
Val.emplace<uint32_t>(UINT32_C(1));
} else {
Val.emplace<uint32_t>(UINT32_C(0));
}
return {};
}
case OpCode::Ref__func: {
auto *ModInst = StackMgr.getModule();
auto *FuncInst = *ModInst->getFunc(Instr.getTargetIndex());
StackMgr.push<FuncRef>(FuncRef(FuncInst));
return {};
}
// Parametric Instructions
case OpCode::Drop:
StackMgr.pop();
return {};
case OpCode::Select:
case OpCode::Select_t: {
// Pop the i32 value and select values from stack.
ValVariant CondVal = StackMgr.pop();
ValVariant Val2 = StackMgr.pop();
ValVariant Val1 = StackMgr.pop();
// Select the value.
if (CondVal.get<uint32_t>() == 0) {
StackMgr.push(Val2);
} else {
StackMgr.push(Val1);
}
return {};
}
// Variable Instructions
case OpCode::Local__get:
return runLocalGetOp(StackMgr, Instr.getStackOffset());
case OpCode::Local__set:
return runLocalSetOp(StackMgr, Instr.getStackOffset());
case OpCode::Local__tee:
return runLocalTeeOp(StackMgr, Instr.getStackOffset());
case OpCode::Global__get:
return runGlobalGetOp(StackMgr, Instr.getTargetIndex());
case OpCode::Global__set:
return runGlobalSetOp(StackMgr, Instr.getTargetIndex());
// Table Instructions
case OpCode::Table__get:
return runTableGetOp(
StackMgr, *getTabInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::Table__set:
return runTableSetOp(
StackMgr, *getTabInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::Table__init:
return runTableInitOp(
StackMgr, *getTabInstByIdx(StackMgr, Instr.getTargetIndex()),
*getElemInstByIdx(StackMgr, Instr.getSourceIndex()), Instr);
case OpCode::Elem__drop:
return runElemDropOp(*getElemInstByIdx(StackMgr, Instr.getTargetIndex()));
case OpCode::Table__copy:
return runTableCopyOp(
StackMgr, *getTabInstByIdx(StackMgr, Instr.getTargetIndex()),
*getTabInstByIdx(StackMgr, Instr.getSourceIndex()), Instr);
case OpCode::Table__grow:
return runTableGrowOp(StackMgr,
*getTabInstByIdx(StackMgr, Instr.getTargetIndex()));
case OpCode::Table__size:
return runTableSizeOp(StackMgr,
*getTabInstByIdx(StackMgr, Instr.getTargetIndex()));
case OpCode::Table__fill:
return runTableFillOp(
StackMgr, *getTabInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
// Memory Instructions
case OpCode::I32__load:
return runLoadOp<uint32_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::I64__load:
return runLoadOp<uint64_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::F32__load:
return runLoadOp<float>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::F64__load:
return runLoadOp<double>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::I32__load8_s:
return runLoadOp<int32_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr,
8);
case OpCode::I32__load8_u:
return runLoadOp<uint32_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr,
8);
case OpCode::I32__load16_s:
return runLoadOp<int32_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr,
16);
case OpCode::I32__load16_u:
return runLoadOp<uint32_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr,
16);
case OpCode::I64__load8_s:
return runLoadOp<int64_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr,
8);
case OpCode::I64__load8_u:
return runLoadOp<uint64_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr,
8);
case OpCode::I64__load16_s:
return runLoadOp<int64_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr,
16);
case OpCode::I64__load16_u:
return runLoadOp<uint64_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr,
16);
case OpCode::I64__load32_s:
return runLoadOp<int64_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr,
32);
case OpCode::I64__load32_u:
return runLoadOp<uint64_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr,
32);
case OpCode::I32__store:
return runStoreOp<uint32_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::I64__store:
return runStoreOp<uint64_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::F32__store:
return runStoreOp<float>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::F64__store:
return runStoreOp<double>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::I32__store8:
return runStoreOp<uint32_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr,
8);
case OpCode::I32__store16:
return runStoreOp<uint32_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr,
16);
case OpCode::I64__store8:
return runStoreOp<uint64_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr,
8);
case OpCode::I64__store16:
return runStoreOp<uint64_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr,
16);
case OpCode::I64__store32:
return runStoreOp<uint64_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr,
32);
case OpCode::Memory__grow:
return runMemoryGrowOp(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()));
case OpCode::Memory__size:
return runMemorySizeOp(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()));
case OpCode::Memory__init:
return runMemoryInitOp(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()),
*getDataInstByIdx(StackMgr, Instr.getSourceIndex()), Instr);
case OpCode::Data__drop:
return runDataDropOp(*getDataInstByIdx(StackMgr, Instr.getTargetIndex()));
case OpCode::Memory__copy:
return runMemoryCopyOp(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()),
*getMemInstByIdx(StackMgr, Instr.getSourceIndex()), Instr);
case OpCode::Memory__fill:
return runMemoryFillOp(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
// Const numeric instructions
case OpCode::I32__const:
case OpCode::I64__const:
case OpCode::F32__const:
case OpCode::F64__const:
StackMgr.push(Instr.getNum());
return {};
// Unary numeric instructions
case OpCode::I32__eqz:
return runEqzOp<uint32_t>(StackMgr.getTop());
case OpCode::I64__eqz:
return runEqzOp<uint64_t>(StackMgr.getTop());
case OpCode::I32__clz:
return runClzOp<uint32_t>(StackMgr.getTop());
case OpCode::I32__ctz:
return runCtzOp<uint32_t>(StackMgr.getTop());
case OpCode::I32__popcnt:
return runPopcntOp<uint32_t>(StackMgr.getTop());
case OpCode::I64__clz:
return runClzOp<uint64_t>(StackMgr.getTop());
case OpCode::I64__ctz:
return runCtzOp<uint64_t>(StackMgr.getTop());
case OpCode::I64__popcnt:
return runPopcntOp<uint64_t>(StackMgr.getTop());
case OpCode::F32__abs:
return runAbsOp<float>(StackMgr.getTop());
case OpCode::F32__neg:
return runNegOp<float>(StackMgr.getTop());
case OpCode::F32__ceil:
return runCeilOp<float>(StackMgr.getTop());
case OpCode::F32__floor:
return runFloorOp<float>(StackMgr.getTop());
case OpCode::F32__trunc:
return runTruncOp<float>(StackMgr.getTop());
case OpCode::F32__nearest:
return runNearestOp<float>(StackMgr.getTop());
case OpCode::F32__sqrt:
return runSqrtOp<float>(StackMgr.getTop());
case OpCode::F64__abs:
return runAbsOp<double>(StackMgr.getTop());
case OpCode::F64__neg:
return runNegOp<double>(StackMgr.getTop());
case OpCode::F64__ceil:
return runCeilOp<double>(StackMgr.getTop());
case OpCode::F64__floor:
return runFloorOp<double>(StackMgr.getTop());
case OpCode::F64__trunc:
return runTruncOp<double>(StackMgr.getTop());
case OpCode::F64__nearest:
return runNearestOp<double>(StackMgr.getTop());
case OpCode::F64__sqrt:
return runSqrtOp<double>(StackMgr.getTop());
case OpCode::I32__wrap_i64:
return runWrapOp<uint64_t, uint32_t>(StackMgr.getTop());
case OpCode::I32__trunc_f32_s:
return runTruncateOp<float, int32_t>(Instr, StackMgr.getTop());
case OpCode::I32__trunc_f32_u:
return runTruncateOp<float, uint32_t>(Instr, StackMgr.getTop());
case OpCode::I32__trunc_f64_s:
return runTruncateOp<double, int32_t>(Instr, StackMgr.getTop());
case OpCode::I32__trunc_f64_u:
return runTruncateOp<double, uint32_t>(Instr, StackMgr.getTop());
case OpCode::I64__extend_i32_s:
return runExtendOp<int32_t, uint64_t>(StackMgr.getTop());
case OpCode::I64__extend_i32_u:
return runExtendOp<uint32_t, uint64_t>(StackMgr.getTop());
case OpCode::I64__trunc_f32_s:
return runTruncateOp<float, int64_t>(Instr, StackMgr.getTop());
case OpCode::I64__trunc_f32_u:
return runTruncateOp<float, uint64_t>(Instr, StackMgr.getTop());
case OpCode::I64__trunc_f64_s:
return runTruncateOp<double, int64_t>(Instr, StackMgr.getTop());
case OpCode::I64__trunc_f64_u:
return runTruncateOp<double, uint64_t>(Instr, StackMgr.getTop());
case OpCode::F32__convert_i32_s:
return runConvertOp<int32_t, float>(StackMgr.getTop());
case OpCode::F32__convert_i32_u:
return runConvertOp<uint32_t, float>(StackMgr.getTop());
case OpCode::F32__convert_i64_s:
return runConvertOp<int64_t, float>(StackMgr.getTop());
case OpCode::F32__convert_i64_u:
return runConvertOp<uint64_t, float>(StackMgr.getTop());
case OpCode::F32__demote_f64:
return runDemoteOp<double, float>(StackMgr.getTop());
case OpCode::F64__convert_i32_s:
return runConvertOp<int32_t, double>(StackMgr.getTop());
case OpCode::F64__convert_i32_u:
return runConvertOp<uint32_t, double>(StackMgr.getTop());
case OpCode::F64__convert_i64_s:
return runConvertOp<int64_t, double>(StackMgr.getTop());
case OpCode::F64__convert_i64_u:
return runConvertOp<uint64_t, double>(StackMgr.getTop());
case OpCode::F64__promote_f32:
return runPromoteOp<float, double>(StackMgr.getTop());
case OpCode::I32__reinterpret_f32:
return runReinterpretOp<float, uint32_t>(StackMgr.getTop());
case OpCode::I64__reinterpret_f64:
return runReinterpretOp<double, uint64_t>(StackMgr.getTop());
case OpCode::F32__reinterpret_i32:
return runReinterpretOp<uint32_t, float>(StackMgr.getTop());
case OpCode::F64__reinterpret_i64:
return runReinterpretOp<uint64_t, double>(StackMgr.getTop());
case OpCode::I32__extend8_s:
return runExtendOp<int32_t, uint32_t, 8>(StackMgr.getTop());
case OpCode::I32__extend16_s:
return runExtendOp<int32_t, uint32_t, 16>(StackMgr.getTop());
case OpCode::I64__extend8_s:
return runExtendOp<int64_t, uint64_t, 8>(StackMgr.getTop());
case OpCode::I64__extend16_s:
return runExtendOp<int64_t, uint64_t, 16>(StackMgr.getTop());
case OpCode::I64__extend32_s:
return runExtendOp<int64_t, uint64_t, 32>(StackMgr.getTop());
case OpCode::I32__trunc_sat_f32_s:
return runTruncateSatOp<float, int32_t>(StackMgr.getTop());
case OpCode::I32__trunc_sat_f32_u:
return runTruncateSatOp<float, uint32_t>(StackMgr.getTop());
case OpCode::I32__trunc_sat_f64_s:
return runTruncateSatOp<double, int32_t>(StackMgr.getTop());
case OpCode::I32__trunc_sat_f64_u:
return runTruncateSatOp<double, uint32_t>(StackMgr.getTop());
case OpCode::I64__trunc_sat_f32_s:
return runTruncateSatOp<float, int64_t>(StackMgr.getTop());
case OpCode::I64__trunc_sat_f32_u:
return runTruncateSatOp<float, uint64_t>(StackMgr.getTop());
case OpCode::I64__trunc_sat_f64_s:
return runTruncateSatOp<double, int64_t>(StackMgr.getTop());
case OpCode::I64__trunc_sat_f64_u:
return runTruncateSatOp<double, uint64_t>(StackMgr.getTop());
// Binary numeric instructions
case OpCode::I32__eq: {
ValVariant Rhs = StackMgr.pop();
return runEqOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32__ne: {
ValVariant Rhs = StackMgr.pop();
return runNeOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32__lt_s: {
ValVariant Rhs = StackMgr.pop();
return runLtOp<int32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32__lt_u: {
ValVariant Rhs = StackMgr.pop();
return runLtOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32__gt_s: {
ValVariant Rhs = StackMgr.pop();
return runGtOp<int32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32__gt_u: {
ValVariant Rhs = StackMgr.pop();
return runGtOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32__le_s: {
ValVariant Rhs = StackMgr.pop();
return runLeOp<int32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32__le_u: {
ValVariant Rhs = StackMgr.pop();
return runLeOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32__ge_s: {
ValVariant Rhs = StackMgr.pop();
return runGeOp<int32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32__ge_u: {
ValVariant Rhs = StackMgr.pop();
return runGeOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64__eq: {
ValVariant Rhs = StackMgr.pop();
return runEqOp<uint64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64__ne: {
ValVariant Rhs = StackMgr.pop();
return runNeOp<uint64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64__lt_s: {
ValVariant Rhs = StackMgr.pop();
return runLtOp<int64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64__lt_u: {
ValVariant Rhs = StackMgr.pop();
return runLtOp<uint64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64__gt_s: {
ValVariant Rhs = StackMgr.pop();
return runGtOp<int64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64__gt_u: {
ValVariant Rhs = StackMgr.pop();
return runGtOp<uint64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64__le_s: {
ValVariant Rhs = StackMgr.pop();
return runLeOp<int64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64__le_u: {
ValVariant Rhs = StackMgr.pop();
return runLeOp<uint64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64__ge_s: {
ValVariant Rhs = StackMgr.pop();
return runGeOp<int64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64__ge_u: {
ValVariant Rhs = StackMgr.pop();
return runGeOp<uint64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::F32__eq: {
ValVariant Rhs = StackMgr.pop();
return runEqOp<float>(StackMgr.getTop(), Rhs);
}
case OpCode::F32__ne: {
ValVariant Rhs = StackMgr.pop();
return runNeOp<float>(StackMgr.getTop(), Rhs);
}
case OpCode::F32__lt: {
ValVariant Rhs = StackMgr.pop();
return runLtOp<float>(StackMgr.getTop(), Rhs);
}
case OpCode::F32__gt: {
ValVariant Rhs = StackMgr.pop();
return runGtOp<float>(StackMgr.getTop(), Rhs);
}
case OpCode::F32__le: {
ValVariant Rhs = StackMgr.pop();
return runLeOp<float>(StackMgr.getTop(), Rhs);
}
case OpCode::F32__ge: {
ValVariant Rhs = StackMgr.pop();
return runGeOp<float>(StackMgr.getTop(), Rhs);
}
case OpCode::F64__eq: {
ValVariant Rhs = StackMgr.pop();
return runEqOp<double>(StackMgr.getTop(), Rhs);
}
case OpCode::F64__ne: {
ValVariant Rhs = StackMgr.pop();
return runNeOp<double>(StackMgr.getTop(), Rhs);
}
case OpCode::F64__lt: {
ValVariant Rhs = StackMgr.pop();
return runLtOp<double>(StackMgr.getTop(), Rhs);
}
case OpCode::F64__gt: {
ValVariant Rhs = StackMgr.pop();
return runGtOp<double>(StackMgr.getTop(), Rhs);
}
case OpCode::F64__le: {
ValVariant Rhs = StackMgr.pop();
return runLeOp<double>(StackMgr.getTop(), Rhs);
}
case OpCode::F64__ge: {
ValVariant Rhs = StackMgr.pop();
return runGeOp<double>(StackMgr.getTop(), Rhs);
}
case OpCode::I32__add: {
ValVariant Rhs = StackMgr.pop();
return runAddOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32__sub: {
ValVariant Rhs = StackMgr.pop();
return runSubOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32__mul: {
ValVariant Rhs = StackMgr.pop();
return runMulOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32__div_s: {
ValVariant Rhs = StackMgr.pop();
return runDivOp<int32_t>(Instr, StackMgr.getTop(), Rhs);
}
case OpCode::I32__div_u: {
ValVariant Rhs = StackMgr.pop();
return runDivOp<uint32_t>(Instr, StackMgr.getTop(), Rhs);
}
case OpCode::I32__rem_s: {
ValVariant Rhs = StackMgr.pop();
return runRemOp<int32_t>(Instr, StackMgr.getTop(), Rhs);
}
case OpCode::I32__rem_u: {
ValVariant Rhs = StackMgr.pop();
return runRemOp<uint32_t>(Instr, StackMgr.getTop(), Rhs);
}
case OpCode::I32__and: {
ValVariant Rhs = StackMgr.pop();
return runAndOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32__or: {
ValVariant Rhs = StackMgr.pop();
return runOrOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32__xor: {
ValVariant Rhs = StackMgr.pop();
return runXorOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32__shl: {
ValVariant Rhs = StackMgr.pop();
return runShlOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32__shr_s: {
ValVariant Rhs = StackMgr.pop();
return runShrOp<int32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32__shr_u: {
ValVariant Rhs = StackMgr.pop();
return runShrOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32__rotl: {
ValVariant Rhs = StackMgr.pop();
return runRotlOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32__rotr: {
ValVariant Rhs = StackMgr.pop();
return runRotrOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64__add: {
ValVariant Rhs = StackMgr.pop();
return runAddOp<uint64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64__sub: {
ValVariant Rhs = StackMgr.pop();
return runSubOp<uint64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64__mul: {
ValVariant Rhs = StackMgr.pop();
return runMulOp<uint64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64__div_s: {
ValVariant Rhs = StackMgr.pop();
return runDivOp<int64_t>(Instr, StackMgr.getTop(), Rhs);
}
case OpCode::I64__div_u: {
ValVariant Rhs = StackMgr.pop();
return runDivOp<uint64_t>(Instr, StackMgr.getTop(), Rhs);
}
case OpCode::I64__rem_s: {
ValVariant Rhs = StackMgr.pop();
return runRemOp<int64_t>(Instr, StackMgr.getTop(), Rhs);
}
case OpCode::I64__rem_u: {
ValVariant Rhs = StackMgr.pop();
return runRemOp<uint64_t>(Instr, StackMgr.getTop(), Rhs);
}
case OpCode::I64__and: {
ValVariant Rhs = StackMgr.pop();
return runAndOp<uint64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64__or: {
ValVariant Rhs = StackMgr.pop();
return runOrOp<uint64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64__xor: {
ValVariant Rhs = StackMgr.pop();
return runXorOp<uint64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64__shl: {
ValVariant Rhs = StackMgr.pop();
return runShlOp<uint64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64__shr_s: {
ValVariant Rhs = StackMgr.pop();
return runShrOp<int64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64__shr_u: {
ValVariant Rhs = StackMgr.pop();
return runShrOp<uint64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64__rotl: {
ValVariant Rhs = StackMgr.pop();
return runRotlOp<uint64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64__rotr: {
ValVariant Rhs = StackMgr.pop();
return runRotrOp<uint64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::F32__add: {
ValVariant Rhs = StackMgr.pop();
return runAddOp<float>(StackMgr.getTop(), Rhs);
}
case OpCode::F32__sub: {
ValVariant Rhs = StackMgr.pop();
return runSubOp<float>(StackMgr.getTop(), Rhs);
}
case OpCode::F32__mul: {
ValVariant Rhs = StackMgr.pop();
return runMulOp<float>(StackMgr.getTop(), Rhs);
}
case OpCode::F32__div: {
ValVariant Rhs = StackMgr.pop();
return runDivOp<float>(Instr, StackMgr.getTop(), Rhs);
}
case OpCode::F32__min: {
ValVariant Rhs = StackMgr.pop();
return runMinOp<float>(StackMgr.getTop(), Rhs);
}
case OpCode::F32__max: {
ValVariant Rhs = StackMgr.pop();
return runMaxOp<float>(StackMgr.getTop(), Rhs);
}
case OpCode::F32__copysign: {
ValVariant Rhs = StackMgr.pop();
return runCopysignOp<float>(StackMgr.getTop(), Rhs);
}
case OpCode::F64__add: {
ValVariant Rhs = StackMgr.pop();
return runAddOp<double>(StackMgr.getTop(), Rhs);
}
case OpCode::F64__sub: {
ValVariant Rhs = StackMgr.pop();
return runSubOp<double>(StackMgr.getTop(), Rhs);
}
case OpCode::F64__mul: {
ValVariant Rhs = StackMgr.pop();
return runMulOp<double>(StackMgr.getTop(), Rhs);
}
case OpCode::F64__div: {
ValVariant Rhs = StackMgr.pop();
return runDivOp<double>(Instr, StackMgr.getTop(), Rhs);
}
case OpCode::F64__min: {
ValVariant Rhs = StackMgr.pop();
return runMinOp<double>(StackMgr.getTop(), Rhs);
}
case OpCode::F64__max: {
ValVariant Rhs = StackMgr.pop();
return runMaxOp<double>(StackMgr.getTop(), Rhs);
}
case OpCode::F64__copysign: {
ValVariant Rhs = StackMgr.pop();
return runCopysignOp<double>(StackMgr.getTop(), Rhs);
}
// SIMD Memory Instructions
case OpCode::V128__load:
return runLoadOp<uint128_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::V128__load8x8_s:
return runLoadExpandOp<int8_t, int16_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::V128__load8x8_u:
return runLoadExpandOp<uint8_t, uint16_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::V128__load16x4_s:
return runLoadExpandOp<int16_t, int32_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::V128__load16x4_u:
return runLoadExpandOp<uint16_t, uint32_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::V128__load32x2_s:
return runLoadExpandOp<int32_t, int64_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::V128__load32x2_u:
return runLoadExpandOp<uint32_t, uint64_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::V128__load8_splat:
return runLoadSplatOp<uint8_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::V128__load16_splat:
return runLoadSplatOp<uint16_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::V128__load32_splat:
return runLoadSplatOp<uint32_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::V128__load64_splat:
return runLoadSplatOp<uint64_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::V128__load32_zero:
return runLoadOp<uint128_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr,
32);
case OpCode::V128__load64_zero:
return runLoadOp<uint128_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr,
64);
case OpCode::V128__store:
return runStoreOp<uint128_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::V128__load8_lane:
return runLoadLaneOp<uint8_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::V128__load16_lane:
return runLoadLaneOp<uint16_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::V128__load32_lane:
return runLoadLaneOp<uint32_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::V128__load64_lane:
return runLoadLaneOp<uint64_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::V128__store8_lane:
return runStoreLaneOp<uint8_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::V128__store16_lane:
return runStoreLaneOp<uint16_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::V128__store32_lane:
return runStoreLaneOp<uint32_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
case OpCode::V128__store64_lane:
return runStoreLaneOp<uint64_t>(
StackMgr, *getMemInstByIdx(StackMgr, Instr.getTargetIndex()), Instr);
// SIMD Const Instructions
case OpCode::V128__const:
StackMgr.push(Instr.getNum());
return {};
// SIMD Shuffle Instructions
case OpCode::I8x16__shuffle: {
ValVariant Val2 = StackMgr.pop();
ValVariant &Val1 = StackMgr.getTop();
std::array<uint8_t, 32> Data;
std::array<uint8_t, 16> Result;
std::memcpy(&Data[0], &Val1, 16);
std::memcpy(&Data[16], &Val2, 16);
const auto V3 = Instr.getNum().get<uint128_t>();
for (size_t I = 0; I < 16; ++I) {
const uint8_t Index = static_cast<uint8_t>(V3 >> (I * 8));
Result[I] = Data[Index];
}
std::memcpy(&Val1, &Result[0], 16);
return {};
}
// SIMD Lane Instructions
case OpCode::I8x16__extract_lane_s:
return runExtractLaneOp<int8_t, int32_t>(StackMgr.getTop(),
Instr.getMemoryLane());
case OpCode::I8x16__extract_lane_u:
return runExtractLaneOp<uint8_t, uint32_t>(StackMgr.getTop(),
Instr.getMemoryLane());
case OpCode::I16x8__extract_lane_s:
return runExtractLaneOp<int16_t, int32_t>(StackMgr.getTop(),
Instr.getMemoryLane());
case OpCode::I16x8__extract_lane_u:
return runExtractLaneOp<uint16_t, uint32_t>(StackMgr.getTop(),
Instr.getMemoryLane());
case OpCode::I32x4__extract_lane:
return runExtractLaneOp<uint32_t>(StackMgr.getTop(),
Instr.getMemoryLane());
case OpCode::I64x2__extract_lane:
return runExtractLaneOp<uint64_t>(StackMgr.getTop(),
Instr.getMemoryLane());
case OpCode::F32x4__extract_lane:
return runExtractLaneOp<float>(StackMgr.getTop(), Instr.getMemoryLane());
case OpCode::F64x2__extract_lane:
return runExtractLaneOp<double>(StackMgr.getTop(), Instr.getMemoryLane());
case OpCode::I8x16__replace_lane: {
ValVariant Rhs = StackMgr.pop();
return runReplaceLaneOp<uint32_t, uint8_t>(StackMgr.getTop(), Rhs,
Instr.getMemoryLane());
}
case OpCode::I16x8__replace_lane: {
ValVariant Rhs = StackMgr.pop();
return runReplaceLaneOp<uint32_t, uint16_t>(StackMgr.getTop(), Rhs,
Instr.getMemoryLane());
}
case OpCode::I32x4__replace_lane: {
ValVariant Rhs = StackMgr.pop();
return runReplaceLaneOp<uint32_t>(StackMgr.getTop(), Rhs,
Instr.getMemoryLane());
}
case OpCode::I64x2__replace_lane: {
ValVariant Rhs = StackMgr.pop();
return runReplaceLaneOp<uint64_t>(StackMgr.getTop(), Rhs,
Instr.getMemoryLane());
}
case OpCode::F32x4__replace_lane: {
ValVariant Rhs = StackMgr.pop();
return runReplaceLaneOp<float>(StackMgr.getTop(), Rhs,
Instr.getMemoryLane());
}
case OpCode::F64x2__replace_lane: {
ValVariant Rhs = StackMgr.pop();
return runReplaceLaneOp<double>(StackMgr.getTop(), Rhs,
Instr.getMemoryLane());
}
// SIMD Numeric Instructions
case OpCode::I8x16__swizzle: {
const ValVariant Val2 = StackMgr.pop();
ValVariant &Val1 = StackMgr.getTop();
const uint8x16_t &Index = Val2.get<uint8x16_t>();
uint8x16_t &Vector = Val1.get<uint8x16_t>();
const uint8x16_t Limit = uint8x16_t{} + 16;
const uint8x16_t Zero = uint8x16_t{};
const uint8x16_t Exceed = (Index >= Limit);
#ifdef __clang__
uint8x16_t Result = {Vector[Index[0] & 0xF], Vector[Index[1] & 0xF],
Vector[Index[2] & 0xF], Vector[Index[3] & 0xF],
Vector[Index[4] & 0xF], Vector[Index[5] & 0xF],
Vector[Index[6] & 0xF], Vector[Index[7] & 0xF],
Vector[Index[8] & 0xF], Vector[Index[9] & 0xF],
Vector[Index[10] & 0xF], Vector[Index[11] & 0xF],
Vector[Index[12] & 0xF], Vector[Index[13] & 0xF],
Vector[Index[14] & 0xF], Vector[Index[15] & 0xF]};
#else
uint8x16_t Result = __builtin_shuffle(Vector, Index);
#endif
Vector = detail::vectorSelect(Exceed, Zero, Result);
return {};
}
case OpCode::I8x16__splat:
return runSplatOp<uint32_t, uint8_t>(StackMgr.getTop());
case OpCode::I16x8__splat:
return runSplatOp<uint32_t, uint16_t>(StackMgr.getTop());
case OpCode::I32x4__splat:
return runSplatOp<uint32_t>(StackMgr.getTop());
case OpCode::I64x2__splat:
return runSplatOp<uint64_t>(StackMgr.getTop());
case OpCode::F32x4__splat:
return runSplatOp<float>(StackMgr.getTop());
case OpCode::F64x2__splat:
return runSplatOp<double>(StackMgr.getTop());
case OpCode::I8x16__eq: {
ValVariant Rhs = StackMgr.pop();
return runVectorEqOp<uint8_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I8x16__ne: {
ValVariant Rhs = StackMgr.pop();
return runVectorNeOp<uint8_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I8x16__lt_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorLtOp<int8_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I8x16__lt_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorLtOp<uint8_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I8x16__gt_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorGtOp<int8_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I8x16__gt_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorGtOp<uint8_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I8x16__le_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorLeOp<int8_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I8x16__le_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorLeOp<uint8_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I8x16__ge_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorGeOp<int8_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I8x16__ge_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorGeOp<uint8_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__eq: {
ValVariant Rhs = StackMgr.pop();
return runVectorEqOp<uint16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__ne: {
ValVariant Rhs = StackMgr.pop();
return runVectorNeOp<uint16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__lt_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorLtOp<int16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__lt_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorLtOp<uint16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__gt_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorGtOp<int16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__gt_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorGtOp<uint16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__le_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorLeOp<int16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__le_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorLeOp<uint16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__ge_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorGeOp<int16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__ge_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorGeOp<uint16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32x4__eq: {
ValVariant Rhs = StackMgr.pop();
return runVectorEqOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32x4__ne: {
ValVariant Rhs = StackMgr.pop();
return runVectorNeOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32x4__lt_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorLtOp<int32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32x4__lt_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorLtOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32x4__gt_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorGtOp<int32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32x4__gt_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorGtOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32x4__le_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorLeOp<int32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32x4__le_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorLeOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32x4__ge_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorGeOp<int32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32x4__ge_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorGeOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64x2__eq: {
ValVariant Rhs = StackMgr.pop();
return runVectorEqOp<uint64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64x2__ne: {
ValVariant Rhs = StackMgr.pop();
return runVectorNeOp<uint64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64x2__lt_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorLtOp<int64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64x2__gt_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorGtOp<int64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64x2__le_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorLeOp<int64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64x2__ge_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorGeOp<int64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::F32x4__eq: {
ValVariant Rhs = StackMgr.pop();
return runVectorEqOp<float>(StackMgr.getTop(), Rhs);
}
case OpCode::F32x4__ne: {
ValVariant Rhs = StackMgr.pop();
return runVectorNeOp<float>(StackMgr.getTop(), Rhs);
}
case OpCode::F32x4__lt: {
ValVariant Rhs = StackMgr.pop();
return runVectorLtOp<float>(StackMgr.getTop(), Rhs);
}
case OpCode::F32x4__gt: {
ValVariant Rhs = StackMgr.pop();
return runVectorGtOp<float>(StackMgr.getTop(), Rhs);
}
case OpCode::F32x4__le: {
ValVariant Rhs = StackMgr.pop();
return runVectorLeOp<float>(StackMgr.getTop(), Rhs);
}
case OpCode::F32x4__ge: {
ValVariant Rhs = StackMgr.pop();
return runVectorGeOp<float>(StackMgr.getTop(), Rhs);
}
case OpCode::F64x2__eq: {
ValVariant Rhs = StackMgr.pop();
return runVectorEqOp<double>(StackMgr.getTop(), Rhs);
}
case OpCode::F64x2__ne: {
ValVariant Rhs = StackMgr.pop();
return runVectorNeOp<double>(StackMgr.getTop(), Rhs);
}
case OpCode::F64x2__lt: {
ValVariant Rhs = StackMgr.pop();
return runVectorLtOp<double>(StackMgr.getTop(), Rhs);
}
case OpCode::F64x2__gt: {
ValVariant Rhs = StackMgr.pop();
return runVectorGtOp<double>(StackMgr.getTop(), Rhs);
}
case OpCode::F64x2__le: {
ValVariant Rhs = StackMgr.pop();
return runVectorLeOp<double>(StackMgr.getTop(), Rhs);
}
case OpCode::F64x2__ge: {
ValVariant Rhs = StackMgr.pop();
return runVectorGeOp<double>(StackMgr.getTop(), Rhs);
}
case OpCode::V128__not: {
auto &Val = StackMgr.getTop().get<uint64x2_t>();
Val = ~Val;
return {};
}
case OpCode::V128__and: {
const ValVariant Val2 = StackMgr.pop();
ValVariant &Val1 = StackMgr.getTop();
Val1.get<uint64x2_t>() &= Val2.get<uint64x2_t>();
return {};
}
case OpCode::V128__andnot: {
const ValVariant Val2 = StackMgr.pop();
ValVariant &Val1 = StackMgr.getTop();
Val1.get<uint64x2_t>() &= ~Val2.get<uint64x2_t>();
return {};
}
case OpCode::V128__or: {
const ValVariant Val2 = StackMgr.pop();
ValVariant &Val1 = StackMgr.getTop();
Val1.get<uint64x2_t>() |= Val2.get<uint64x2_t>();
return {};
}
case OpCode::V128__xor: {
const ValVariant Val2 = StackMgr.pop();
ValVariant &Val1 = StackMgr.getTop();
Val1.get<uint64x2_t>() ^= Val2.get<uint64x2_t>();
return {};
}
case OpCode::V128__bitselect: {
const uint64x2_t C = StackMgr.pop().get<uint64x2_t>();
const uint64x2_t Val2 = StackMgr.pop().get<uint64x2_t>();
uint64x2_t &Val1 = StackMgr.getTop().get<uint64x2_t>();
Val1 = (Val1 & C) | (Val2 & ~C);
return {};
}
case OpCode::V128__any_true:
return runVectorAnyTrueOp(StackMgr.getTop());
case OpCode::I8x16__abs:
return runVectorAbsOp<int8_t>(StackMgr.getTop());
case OpCode::I8x16__neg:
return runVectorNegOp<int8_t>(StackMgr.getTop());
case OpCode::I8x16__popcnt:
return runVectorPopcntOp(StackMgr.getTop());
case OpCode::I8x16__all_true:
return runVectorAllTrueOp<uint8_t>(StackMgr.getTop());
case OpCode::I8x16__bitmask:
return runVectorBitMaskOp<uint8_t>(StackMgr.getTop());
case OpCode::I8x16__narrow_i16x8_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorNarrowOp<int16_t, int8_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I8x16__narrow_i16x8_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorNarrowOp<int16_t, uint8_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I8x16__shl: {
ValVariant Rhs = StackMgr.pop();
return runVectorShlOp<uint8_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I8x16__shr_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorShrOp<int8_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I8x16__shr_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorShrOp<uint8_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I8x16__add: {
ValVariant Rhs = StackMgr.pop();
return runVectorAddOp<uint8_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I8x16__add_sat_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorAddSatOp<int8_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I8x16__add_sat_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorAddSatOp<uint8_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I8x16__sub: {
ValVariant Rhs = StackMgr.pop();
return runVectorSubOp<uint8_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I8x16__sub_sat_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorSubSatOp<int8_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I8x16__sub_sat_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorSubSatOp<uint8_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I8x16__min_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorMinOp<int8_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I8x16__min_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorMinOp<uint8_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I8x16__max_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorMaxOp<int8_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I8x16__max_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorMaxOp<uint8_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I8x16__avgr_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorAvgrOp<uint8_t, uint16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__abs:
return runVectorAbsOp<int16_t>(StackMgr.getTop());
case OpCode::I16x8__neg:
return runVectorNegOp<int16_t>(StackMgr.getTop());
case OpCode::I16x8__all_true:
return runVectorAllTrueOp<uint16_t>(StackMgr.getTop());
case OpCode::I16x8__bitmask:
return runVectorBitMaskOp<uint16_t>(StackMgr.getTop());
case OpCode::I16x8__narrow_i32x4_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorNarrowOp<int32_t, int16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__narrow_i32x4_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorNarrowOp<int32_t, uint16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__extend_low_i8x16_s:
return runVectorExtendLowOp<int8_t, int16_t>(StackMgr.getTop());
case OpCode::I16x8__extend_high_i8x16_s:
return runVectorExtendHighOp<int8_t, int16_t>(StackMgr.getTop());
case OpCode::I16x8__extend_low_i8x16_u:
return runVectorExtendLowOp<uint8_t, uint16_t>(StackMgr.getTop());
case OpCode::I16x8__extend_high_i8x16_u:
return runVectorExtendHighOp<uint8_t, uint16_t>(StackMgr.getTop());
case OpCode::I16x8__shl: {
ValVariant Rhs = StackMgr.pop();
return runVectorShlOp<uint16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__shr_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorShrOp<int16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__shr_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorShrOp<uint16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__add: {
ValVariant Rhs = StackMgr.pop();
return runVectorAddOp<uint16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__add_sat_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorAddSatOp<int16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__add_sat_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorAddSatOp<uint16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__sub: {
ValVariant Rhs = StackMgr.pop();
return runVectorSubOp<uint16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__sub_sat_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorSubSatOp<int16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__sub_sat_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorSubSatOp<uint16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__mul: {
ValVariant Rhs = StackMgr.pop();
return runVectorMulOp<uint16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__min_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorMinOp<int16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__min_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorMinOp<uint16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__max_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorMaxOp<int16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__max_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorMaxOp<uint16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__avgr_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorAvgrOp<uint16_t, uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__extmul_low_i8x16_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorExtMulLowOp<int8_t, int16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__extmul_high_i8x16_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorExtMulHighOp<int8_t, int16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__extmul_low_i8x16_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorExtMulLowOp<uint8_t, uint16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__extmul_high_i8x16_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorExtMulHighOp<uint8_t, uint16_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__q15mulr_sat_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorQ15MulSatOp(StackMgr.getTop(), Rhs);
}
case OpCode::I16x8__extadd_pairwise_i8x16_s:
return runVectorExtAddPairwiseOp<int8_t, int16_t>(StackMgr.getTop());
case OpCode::I16x8__extadd_pairwise_i8x16_u:
return runVectorExtAddPairwiseOp<uint8_t, uint16_t>(StackMgr.getTop());
case OpCode::I32x4__abs:
return runVectorAbsOp<int32_t>(StackMgr.getTop());
case OpCode::I32x4__neg:
return runVectorNegOp<int32_t>(StackMgr.getTop());
case OpCode::I32x4__all_true:
return runVectorAllTrueOp<uint32_t>(StackMgr.getTop());
case OpCode::I32x4__bitmask:
return runVectorBitMaskOp<uint32_t>(StackMgr.getTop());
case OpCode::I32x4__extend_low_i16x8_s:
return runVectorExtendLowOp<int16_t, int32_t>(StackMgr.getTop());
case OpCode::I32x4__extend_high_i16x8_s:
return runVectorExtendHighOp<int16_t, int32_t>(StackMgr.getTop());
case OpCode::I32x4__extend_low_i16x8_u:
return runVectorExtendLowOp<uint16_t, uint32_t>(StackMgr.getTop());
case OpCode::I32x4__extend_high_i16x8_u:
return runVectorExtendHighOp<uint16_t, uint32_t>(StackMgr.getTop());
case OpCode::I32x4__shl: {
ValVariant Rhs = StackMgr.pop();
return runVectorShlOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32x4__shr_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorShrOp<int32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32x4__shr_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorShrOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32x4__add: {
ValVariant Rhs = StackMgr.pop();
return runVectorAddOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32x4__sub: {
ValVariant Rhs = StackMgr.pop();
return runVectorSubOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32x4__mul: {
ValVariant Rhs = StackMgr.pop();
return runVectorMulOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32x4__min_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorMinOp<int32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32x4__min_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorMinOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32x4__max_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorMaxOp<int32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32x4__max_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorMaxOp<uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32x4__extmul_low_i16x8_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorExtMulLowOp<int16_t, int32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32x4__extmul_high_i16x8_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorExtMulHighOp<int16_t, int32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32x4__extmul_low_i16x8_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorExtMulLowOp<uint16_t, uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32x4__extmul_high_i16x8_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorExtMulHighOp<uint16_t, uint32_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I32x4__extadd_pairwise_i16x8_s:
return runVectorExtAddPairwiseOp<int16_t, int32_t>(StackMgr.getTop());
case OpCode::I32x4__extadd_pairwise_i16x8_u:
return runVectorExtAddPairwiseOp<uint16_t, uint32_t>(StackMgr.getTop());
case OpCode::I64x2__abs:
return runVectorAbsOp<int64_t>(StackMgr.getTop());
case OpCode::I64x2__neg:
return runVectorNegOp<int64_t>(StackMgr.getTop());
case OpCode::I64x2__all_true:
return runVectorAllTrueOp<uint64_t>(StackMgr.getTop());
case OpCode::I64x2__bitmask:
return runVectorBitMaskOp<uint64_t>(StackMgr.getTop());
case OpCode::I64x2__extend_low_i32x4_s:
return runVectorExtendLowOp<int32_t, int64_t>(StackMgr.getTop());
case OpCode::I64x2__extend_high_i32x4_s:
return runVectorExtendHighOp<int32_t, int64_t>(StackMgr.getTop());
case OpCode::I64x2__extend_low_i32x4_u:
return runVectorExtendLowOp<uint32_t, uint64_t>(StackMgr.getTop());
case OpCode::I64x2__extend_high_i32x4_u:
return runVectorExtendHighOp<uint32_t, uint64_t>(StackMgr.getTop());
case OpCode::I64x2__shl: {
ValVariant Rhs = StackMgr.pop();
return runVectorShlOp<uint64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64x2__shr_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorShrOp<int64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64x2__shr_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorShrOp<uint64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64x2__add: {
ValVariant Rhs = StackMgr.pop();
return runVectorAddOp<uint64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64x2__sub: {
ValVariant Rhs = StackMgr.pop();
return runVectorSubOp<uint64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64x2__mul: {
ValVariant Rhs = StackMgr.pop();
return runVectorMulOp<uint64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64x2__extmul_low_i32x4_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorExtMulLowOp<int32_t, int64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64x2__extmul_high_i32x4_s: {
ValVariant Rhs = StackMgr.pop();
return runVectorExtMulHighOp<int32_t, int64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64x2__extmul_low_i32x4_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorExtMulLowOp<uint32_t, uint64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::I64x2__extmul_high_i32x4_u: {
ValVariant Rhs = StackMgr.pop();
return runVectorExtMulHighOp<uint32_t, uint64_t>(StackMgr.getTop(), Rhs);
}
case OpCode::F32x4__abs:
return runVectorAbsOp<float>(StackMgr.getTop());
case OpCode::F32x4__neg:
return runVectorNegOp<float>(StackMgr.getTop());
case OpCode::F32x4__sqrt:
return runVectorSqrtOp<float>(StackMgr.getTop());
case OpCode::F32x4__add: {
ValVariant Rhs = StackMgr.pop();
return runVectorAddOp<float>(StackMgr.getTop(), Rhs);
}
case OpCode::F32x4__sub: {
ValVariant Rhs = StackMgr.pop();
return runVectorSubOp<float>(StackMgr.getTop(), Rhs);
}
case OpCode::F32x4__mul: {
ValVariant Rhs = StackMgr.pop();
return runVectorMulOp<float>(StackMgr.getTop(), Rhs);
}
case OpCode::F32x4__div: {
ValVariant Rhs = StackMgr.pop();
return runVectorDivOp<float>(StackMgr.getTop(), Rhs);
}
case OpCode::F32x4__min: {
ValVariant Rhs = StackMgr.pop();
return runVectorFMinOp<float>(StackMgr.getTop(), Rhs);
}
case OpCode::F32x4__max: {
ValVariant Rhs = StackMgr.pop();
return runVectorFMaxOp<float>(StackMgr.getTop(), Rhs);
}
case OpCode::F32x4__pmin: {
ValVariant Rhs = StackMgr.pop();
return runVectorMinOp<float>(StackMgr.getTop(), Rhs);
}
case OpCode::F32x4__pmax: {
ValVariant Rhs = StackMgr.pop();
return runVectorMaxOp<float>(StackMgr.getTop(), Rhs);
}
case OpCode::F64x2__abs:
return runVectorAbsOp<double>(StackMgr.getTop());
case OpCode::F64x2__neg:
return runVectorNegOp<double>(StackMgr.getTop());
case OpCode::F64x2__sqrt:
return runVectorSqrtOp<double>(StackMgr.getTop());
case OpCode::F64x2__add: {
ValVariant Rhs = StackMgr.pop();
return runVectorAddOp<double>(StackMgr.getTop(), Rhs);
}
case OpCode::F64x2__sub: {
ValVariant Rhs = StackMgr.pop();
return runVectorSubOp<double>(StackMgr.getTop(), Rhs);
}
case OpCode::F64x2__mul: {
ValVariant Rhs = StackMgr.pop();
return runVectorMulOp<double>(StackMgr.getTop(), Rhs);
}
case OpCode::F64x2__div: {
ValVariant Rhs = StackMgr.pop();
return runVectorDivOp<double>(StackMgr.getTop(), Rhs);
}
case OpCode::F64x2__min: {
ValVariant Rhs = StackMgr.pop();
return runVectorFMinOp<double>(StackMgr.getTop(), Rhs);
}
case OpCode::F64x2__max: {
ValVariant Rhs = StackMgr.pop();
return runVectorFMaxOp<double>(StackMgr.getTop(), Rhs);
}
case OpCode::F64x2__pmin: {
ValVariant Rhs = StackMgr.pop();
return runVectorMinOp<double>(StackMgr.getTop(), Rhs);
}
case OpCode::F64x2__pmax: {
ValVariant Rhs = StackMgr.pop();
return runVectorMaxOp<double>(StackMgr.getTop(), Rhs);
}
case OpCode::I32x4__trunc_sat_f32x4_s:
return runVectorTruncSatOp<float, int32_t>(StackMgr.getTop());
case OpCode::I32x4__trunc_sat_f32x4_u:
return runVectorTruncSatOp<float, uint32_t>(StackMgr.getTop());
case OpCode::F32x4__convert_i32x4_s:
return runVectorConvertOp<int32_t, float>(StackMgr.getTop());
case OpCode::F32x4__convert_i32x4_u:
return runVectorConvertOp<uint32_t, float>(StackMgr.getTop());
case OpCode::I32x4__trunc_sat_f64x2_s_zero:
return runVectorTruncSatOp<double, int32_t>(StackMgr.getTop());
case OpCode::I32x4__trunc_sat_f64x2_u_zero:
return runVectorTruncSatOp<double, uint32_t>(StackMgr.getTop());
case OpCode::F64x2__convert_low_i32x4_s:
return runVectorConvertOp<int32_t, double>(StackMgr.getTop());
case OpCode::F64x2__convert_low_i32x4_u:
return runVectorConvertOp<uint32_t, double>(StackMgr.getTop());
case OpCode::F32x4__demote_f64x2_zero:
return runVectorDemoteOp(StackMgr.getTop());
case OpCode::F64x2__promote_low_f32x4:
return runVectorPromoteOp(StackMgr.getTop());
case OpCode::I32x4__dot_i16x8_s: {
using int32x8_t [[gnu::vector_size(32)]] = int32_t;
const ValVariant Val2 = StackMgr.pop();
ValVariant &Val1 = StackMgr.getTop();
auto &V2 = Val2.get<int16x8_t>();
auto &V1 = Val1.get<int16x8_t>();
const auto M = __builtin_convertvector(V1, int32x8_t) *
__builtin_convertvector(V2, int32x8_t);
const int32x4_t L = {M[0], M[2], M[4], M[6]};
const int32x4_t R = {M[1], M[3], M[5], M[7]};
Val1.emplace<int32x4_t>(L + R);
return {};
}
case OpCode::F32x4__ceil:
return runVectorCeilOp<float>(StackMgr.getTop());
case OpCode::F32x4__floor:
return runVectorFloorOp<float>(StackMgr.getTop());
case OpCode::F32x4__trunc:
return runVectorTruncOp<float>(StackMgr.getTop());
case OpCode::F32x4__nearest:
return runVectorNearestOp<float>(StackMgr.getTop());
case OpCode::F64x2__ceil:
return runVectorCeilOp<double>(StackMgr.getTop());
case OpCode::F64x2__floor:
return runVectorFloorOp<double>(StackMgr.getTop());
case OpCode::F64x2__trunc:
return runVectorTruncOp<double>(StackMgr.getTop());
case OpCode::F64x2__nearest:
return runVectorNearestOp<double>(StackMgr.getTop());
default:
return {};
}
};
while (PC != PCEnd) {
OpCode Code = PC->getOpCode();
if (Stat) {
if (Conf.getStatisticsConfigure().isInstructionCounting()) {
Stat->incInstrCount();
}
// Add cost. Note: if-else case should be processed additionally.
if (Conf.getStatisticsConfigure().isCostMeasuring()) {
if (unlikely(!Stat->addInstrCost(Code))) {
const AST::Instruction &Instr = *PC;
spdlog::error(
ErrInfo::InfoInstruction(Instr.getOpCode(), Instr.getOffset()));
return Unexpect(ErrCode::CostLimitExceeded);
}
}
}
if (auto Res = Dispatch(); !Res) {
return Unexpect(Res);
}
PC++;
}
return {};
}
} // namespace Executor
} // namespace WasmEdge
| 62,201 | 24,510 |
/*
* Copyright (C) 2012 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef GAZEBO_PHYSICS_CONTACT_HH_
#define GAZEBO_PHYSICS_CONTACT_HH_
#include <vector>
#include <string>
#include <ignition/math/Vector3.hh>
#include "gazebo/common/Time.hh"
#include "gazebo/msgs/msgs.hh"
#include "gazebo/physics/JointWrench.hh"
#include "gazebo/physics/PhysicsTypes.hh"
#include "gazebo/util/system.hh"
// For the sake of efficiency, use fixed size arrays for collision
// MAX_COLLIDE_RETURNS limits contact detection, needs to be large
// for proper contact dynamics.
// MAX_CONTACT_JOINTS truncates <max_contacts> specified in SDF
#define MAX_COLLIDE_RETURNS 250
#define MAX_CONTACT_JOINTS 250
namespace gazebo
{
namespace physics
{
class Collision;
/// \addtogroup gazebo_physics
/// \{
/// \class Contact Contact.hh physics/physics.hh
/// \brief A contact between two collisions. Each contact can consist of
/// a number of contact points
class GZ_PHYSICS_VISIBLE Contact
{
/// \brief Constructor.
public: Contact();
/// \brief Copy constructor
/// \param[in] _contact Contact to copy.
public: Contact(const Contact &_contact);
/// \brief Destructor.
public: virtual ~Contact();
/// \brief Operator =.
/// \param[in] _contact Contact to copy.
/// \return Reference to this contact
public: Contact &operator =(const Contact &_contact);
/// \brief Operator =.
/// \param[in] _contact msgs::Contact to copy.
/// \return Reference to this contact
public: Contact &operator =(const msgs::Contact &_contact);
/// \brief Populate a msgs::Contact with data from this.
/// \param[out] _msg Contact message the will hold the data.
public: void FillMsg(msgs::Contact &_msg) const;
/// \brief Produce a debug string.
/// \return A string that contains the values of the contact.
public: std::string DebugString() const;
/// \brief Reset to default values.
public: void Reset();
/// \brief Pointer to the first collision object
public: Collision *collision1;
/// \brief Pointer to the second collision object
public: Collision *collision2;
/// \brief Array of forces for the contact.
/// All forces and torques are in the world frame.
/// All forces and torques are relative to the center of mass of the
/// respective links that the collision elments are attached to.
public: JointWrench wrench[MAX_CONTACT_JOINTS];
/// \brief Array of force positions.
public: ignition::math::Vector3d positions[MAX_CONTACT_JOINTS];
/// \brief Array of force normals.
public: ignition::math::Vector3d normals[MAX_CONTACT_JOINTS];
/// \brief Array of contact depths
public: double depths[MAX_CONTACT_JOINTS];
/// \brief Length of all the arrays.
public: int count;
/// \brief Time at which the contact occurred.
public: common::Time time;
/// \brief World in which the contact occurred
public: WorldPtr world;
};
/// \}
}
}
#endif
| 3,698 | 1,133 |
#include "stdafx.h"
#pragma hdrstop
#ifdef DEBUG
#include "PHDebug.h"
#endif
#include "alife_space.h"
#include "Hit.h"
#include "PHDestroyable.h"
#include "Car.h"
#include "Actor.h"
#include "script_entity_action.h"
#include "../xrEngine/xr_level_controller.h"
#include "../xrEngine/CameraBase.h"
#include "../Include/xrRender/Kinematics.h"
#include "Level.h"
#include "CarWeapon.h"
#include "script_game_object.h"
void CCar::OnMouseMove(int dx, int dy)
{
if (Remote()) return;
CCameraBase* C = active_camera;
float scale = (C->f_fov/g_fov)*psMouseSens * psMouseSensScale/50.f;
if (dx)
{
float d = float(dx)*scale;
C->Move ((d<0)?kLEFT:kRIGHT, _abs(d));
}
if (dy)
{
float d = ((psMouseInvert.test(1))?-1:1)*float(dy)*scale*3.f/4.f;
C->Move ((d>0)?kUP:kDOWN, _abs(d));
}
}
bool CCar::bfAssignMovement(CScriptEntityAction *tpEntityAction)
{
if (tpEntityAction->m_tMovementAction.m_bCompleted)
return(false);
u32 l_tInput = tpEntityAction->m_tMovementAction.m_tInputKeys;
vfProcessInputKey(kFWD , !!(l_tInput & CScriptMovementAction::eInputKeyForward ));
vfProcessInputKey(kBACK , !!(l_tInput & CScriptMovementAction::eInputKeyBack ));
vfProcessInputKey(kL_STRAFE , !!(l_tInput & CScriptMovementAction::eInputKeyLeft ));
vfProcessInputKey(kR_STRAFE , !!(l_tInput & CScriptMovementAction::eInputKeyRight ));
vfProcessInputKey(kACCEL , !!(l_tInput & CScriptMovementAction::eInputKeyShiftUp ));
vfProcessInputKey(kCROUCH , !!(l_tInput & CScriptMovementAction::eInputKeyShiftDown ));
vfProcessInputKey(kJUMP , !!(l_tInput & CScriptMovementAction::eInputKeyBreaks ));
if (!!(l_tInput & CScriptMovementAction::eInputKeyEngineOn)) StartEngine();
if (!!(l_tInput & CScriptMovementAction::eInputKeyEngineOff)) StopEngine();
//if (_abs(tpEntityAction->m_tMovementAction.m_fSpeed) > EPS_L)
//m_current_rpm = _abs(tpEntityAction->m_tMovementAction.m_fSpeed*m_current_gear_ratio);
return (true);
}
bool CCar::bfAssignObject(CScriptEntityAction *tpEntityAction)
{
CScriptObjectAction &l_tObjectAction = tpEntityAction->m_tObjectAction;
if (l_tObjectAction.m_bCompleted || !xr_strlen(l_tObjectAction.m_caBoneName))
return((l_tObjectAction.m_bCompleted = true) == false);
s16 l_sBoneID = smart_cast<IKinematics*>(Visual())->LL_BoneID(l_tObjectAction.m_caBoneName);
if (is_Door(l_sBoneID)) {
switch(l_tObjectAction.m_tGoalType) {
case MonsterSpace::eObjectActionActivate : {
if (!DoorOpen(l_sBoneID))
return((l_tObjectAction.m_bCompleted = true) == false);
break;
}
case MonsterSpace::eObjectActionDeactivate : {
if (!DoorClose(l_sBoneID))
return((l_tObjectAction.m_bCompleted = true) == false);
break;
}
case MonsterSpace::eObjectActionUse : {
if (!DoorSwitch(l_sBoneID))
return((l_tObjectAction.m_bCompleted = true) == false);
break;
}
default :
return ((l_tObjectAction.m_bCompleted = true) == false);
}
return (false);
}
SCarLight* light=nullptr;
if (m_lights.findLight(l_sBoneID,light)) {
switch(l_tObjectAction.m_tGoalType) {
case MonsterSpace::eObjectActionActivate : {
light->TurnOn();
return ((l_tObjectAction.m_bCompleted = true) == false);
}
case MonsterSpace::eObjectActionDeactivate : {
light->TurnOff();
return ((l_tObjectAction.m_bCompleted = true) == false);
}
case MonsterSpace::eObjectActionUse : {
light->Switch();
return ((l_tObjectAction.m_bCompleted = true) == false);
}
default :
return ((l_tObjectAction.m_bCompleted = true) == false);
}
}
return (false);
}
void CCar::vfProcessInputKey (int iCommand, bool bPressed)
{
if (bPressed)
OnKeyboardPress (iCommand);
else
OnKeyboardRelease (iCommand);
}
float const base_fov = g_fov;
float const dest_fov = g_fov - (g_fov-30.f);
void CCar::OnKeyboardPress(int cmd)
{
if (Remote()) return;
switch (cmd)
{
case kCAM_1:
OnCameraChange(ectFirst);
break;
case kCAM_2:
OnCameraChange(ectChase);
break;
case kCAM_3:
OnCameraChange(ectFree);
break;
case kACCEL:
TransmissionUp();
break;
case kCROUCH:
TransmissionDown();
break;
case kFWD:
PressForward();
break;
case kBACK:
PressBack();
break;
case kR_STRAFE:
PressRight();
if (OwnerActor())
OwnerActor()->steer_Vehicle(1);
break;
case kL_STRAFE:
PressLeft();
if (OwnerActor())
OwnerActor()->steer_Vehicle(-1);
break;
case kJUMP:
PressBreaks();
break;
case kTURN_ENGINE:
SwitchEngine();
if (HasWeapon())
m_car_weapon->Action(CCarWeapon::eWpnActivate, b_engine_on);
break;
case kTORCH:
m_lights.SwitchHeadLights();
break;
case kUSE:
if (HasWeapon()) (g_fov = base_fov);
break;
case kWPN_ZOOM:
if (HasWeapon()) (g_fov = dest_fov);
break;
case kWPN_FIRE:
if (HasWeapon())
m_car_weapon->Action(CCarWeapon::eWpnFire, 1);
break;
case kSWITCH_HORN:
SwitchHorn();
break;
};
}
void CCar::OnKeyboardRelease(int cmd)
{
if (Remote()) return;
switch (cmd)
{
case kACCEL:
break;
case kFWD:
ReleaseForward();
break;
case kBACK:
ReleaseBack();
break;
case kL_STRAFE:
ReleaseLeft();
if (OwnerActor()) OwnerActor()->steer_Vehicle(0);
break;
case kR_STRAFE:
ReleaseRight();
if (OwnerActor()) OwnerActor()->steer_Vehicle(0);
break;
case kWPN_FIRE:
if (HasWeapon()) m_car_weapon->Action(CCarWeapon::eWpnFire, 0);
break;
case kJUMP:
ReleaseBreaks();
break;
case kWPN_ZOOM:
if (HasWeapon()) (g_fov = base_fov);
break;
case kSWITCH_HORN: snd_horn.destroy(); break;
};
}
void CCar::OnKeyboardHold(int cmd)
{
if (Remote())
return;
switch (cmd)
{
case kCAM_ZOOM_IN:
case kCAM_ZOOM_OUT:
case kUP:
case kDOWN:
case kLEFT:
case kRIGHT:
{
active_camera->Move(cmd);
break;
}
}
}
void CCar::Action(u16 id, u32 flags)
{
if(m_car_weapon)m_car_weapon->Action(id,flags);
}
void CCar::SetParam(int id, Fvector2 val)
{
if(m_car_weapon)m_car_weapon->SetParam(id,val);
}
void CCar::SetParam (int id, Fvector val)
{
if(m_car_weapon)m_car_weapon->SetParam(id,val);
}
bool CCar::WpnCanHit()
{
if(m_car_weapon) return m_car_weapon->AllowFire();
return false;
}
float CCar::FireDirDiff()
{
if(m_car_weapon) return m_car_weapon->FireDirDiff();
return 0.0f;
}
#include "script_game_object.h"
#include "car_memory.h"
#include "visual_memory_manager.h"
bool CCar::isObjectVisible (CScriptGameObject* O_)
{
if(m_memory)
{
return m_memory->visual().visible_now(&O_->object());
}else
{
if(!O_)
{
Msg("Attempt to call CCar::isObjectVisible method wihth passed NULL parameter");
return false;
}
CObject* O = &O_->object();
Fvector dir_to_object;
Fvector to_point;
O->Center(to_point);
Fvector from_point;
Center (from_point);
if(HasWeapon())
{
from_point.y = XFORM().c.y + m_car_weapon->_height();
}
dir_to_object.sub(to_point,from_point).normalize_safe();
float ray_length = from_point.distance_to(to_point);
BOOL res = Level().ObjectSpace.RayTest(from_point, dir_to_object, ray_length, collide::rqtStatic, nullptr, nullptr);
return (0==res);
}
}
bool CCar::HasWeapon()
{
return (m_car_weapon != nullptr);
}
Fvector CCar::CurrentVel()
{
Fvector lin_vel;
m_pPhysicsShell->get_LinearVel(lin_vel);
return lin_vel;
}
| 7,464 | 3,474 |
#include "ba.hpp"
static mat2_t J_intrinsics(const mat3_t &K) {
// J = [K[0, 0], 0.0,
// 0.0, K[1, 1]];
mat2_t J = zeros(2, 2);
J(0, 0) = K(0, 0);
J(1, 1) = K(1, 1);
return J;
}
static matx_t J_project(const vec3_t &p_C) {
const real_t x = p_C(0);
const real_t y = p_C(1);
const real_t z = p_C(2);
// J = [1 / z, 0, -x / z^2,
// 0, 1 / z, -y / z^2];
matx_t J = zeros(2, 3);
J(0, 0) = 1.0 / z;
J(1, 1) = 1.0 / z;
J(0, 2) = -x / (z * z);
J(1, 2) = -y / (z * z);
return J;
}
static mat3_t J_camera_rotation(const quat_t &q_WC,
const vec3_t &r_WC,
const vec3_t &p_W) {
const mat3_t C_WC = q_WC.toRotationMatrix();
const mat3_t C_CW = C_WC.transpose();
return C_CW * skew(p_W - r_WC);
}
static mat3_t J_camera_translation(const quat_t &q_WC) {
const mat3_t C_WC = q_WC.toRotationMatrix();
const mat3_t C_CW = C_WC.transpose();
return -C_CW;
}
static mat3_t J_target_point(const quat_t &q_WC) {
const mat3_t C_WC = q_WC.toRotationMatrix();
const mat3_t C_CW = C_WC.transpose();
return C_CW;
}
int ba_residual_size(ba_data_t &data) {
// Calculate residual size
int r_size = 0;
for (int k = 0; k < data.nb_frames; k++) {
r_size += data.point_ids[k][0];
}
r_size = r_size * 2;
// ^ Scale 2 because each pixel error are size 2
return r_size;
}
vecx_t ba_residuals(ba_data_t &data) {
// Initialize memory for residuals
int r_size = ba_residual_size(data);
vecx_t r{r_size};
// Loop over time
int res_idx = 0; // Residual index
for (int k = 0; k < data.nb_frames; k++) {
// Form camera pose and its inverse
const mat4_t T_WC = data.cam_poses[k].T();
const mat4_t T_CW = T_WC.inverse();
// Get point ids and measurements at time step k
const int nb_ids = data.point_ids[k][0];
const int *point_ids = &data.point_ids[k][1];
for (int i = 0; i < nb_ids; i++) {
// Get point in world frame and transform to camera frame
const int id = point_ids[i];
const vec3_t p_W{data.points[id]};
const vec3_t p_C = tf_point(T_CW, p_W);
// Project point in camera frame down to image plane
const vec3_t x{p_C(0) / p_C(2), p_C(1) / p_C(2), 1.0};
const vec2_t z_hat = (data.cam_K * x).head(2);
// Calculate reprojection error
const vec2_t z = data.keypoints[k][i];
r.block(res_idx, 0, 2, 1) = z - z_hat;
res_idx += 2;
}
}
return r;
}
matx_t ba_jacobian(ba_data_t &data) {
// Initialize memory for jacobian
int J_rows = ba_residual_size(data);
int J_cols = (data.nb_frames * 6) + (data.nb_points * 3);
matx_t J = zeros(J_rows, J_cols);
// Loop over camera poses
int pose_idx = 0;
int meas_idx = 0;
for (int k = 0; k < data.nb_frames; k++) {
// Form camera pose
const mat4_t T_WC = data.cam_poses[k].T();
const quat_t q_WC = tf_quat(T_WC);
const vec3_t r_WC = tf_trans(T_WC);
const mat4_t T_CW = T_WC.inverse();
// Get point ids and measurements at time step k
const int nb_ids = data.point_ids[k][0];
const int *point_ids = &data.point_ids[k][1];
// Loop over observations at time k
for (int i = 0; i < nb_ids; i++) {
// Get point in world frame and transform to camera frame
const int id = point_ids[i];
const vec3_t p_W{data.points[id]};
const vec3_t p_C = tf_point(T_CW, p_W);
// Camera pose jacobian
const int rs = meas_idx * 2;
int cs = pose_idx * 6;
const mat2_t J_K = J_intrinsics(data.cam_K);
const matx_t J_P = J_project(p_C);
const matx_t J_h = J_K * J_P;
const mat3_t J_C = J_camera_rotation(q_WC, r_WC, p_W);
const mat3_t J_r = J_camera_translation(q_WC);
const matx_t J_cam_rot = -1 * J_h * J_C;
const matx_t J_cam_pos = -1 * J_h * J_r;
J.block(rs, cs, 2, 3) = J_cam_rot;
J.block(rs, cs + 3, 2, 3) = J_cam_pos;
// Point jacobian
cs = (data.nb_frames * 6) + point_ids[i] * 3;
const matx_t J_point = -1 * J_h * J_target_point(q_WC);
J.block(rs, cs, 2, 3) = J_point;
meas_idx++;
}
pose_idx++;
}
return J;
}
void ba_update(ba_data_t &data, const vecx_t &e, const matx_t &E) {
const real_t lambda = 1e-4; // LM damping term
// Solve Gauss-Newton system [H dx = g]: Solve for dx
matx_t H = E.transpose() * E; // Hessian approx: H = J^t J
matx_t H_diag = (H.diagonal().asDiagonal());
H = H + lambda * H_diag; // R. Fletcher trust region mod
const vecx_t g = -E.transpose() * e;
const vecx_t dx = H.ldlt().solve(g); // Cholesky decomp
// Update camera poses
for (int k = 0; k < data.nb_frames; k++) {
const int s = k * 6;
// Update camera rotation
const vec3_t dalpha{dx(s), dx(s + 1), dx(s + 2)};
const quat_t q = data.cam_poses[k].rot();
const quat_t dq = quat_delta(dalpha);
data.cam_poses[k].set_rot(dq * q);
// Update camera position
const vec3_t r_WC = data.cam_poses[k].trans();
const vec3_t dr_WC{dx(s + 3), dx(s + 4), dx(s + 5)};
data.cam_poses[k].set_trans(r_WC + dr_WC);
}
// Update points
for (int i = 0; i < data.nb_points; i++) {
const int s = (data.nb_frames * 6) + (i * 3);
const vec3_t dp_W{dx(s), dx(s + 1), dx(s + 2)};
data.points[i][0] += dp_W(0);
data.points[i][1] += dp_W(1);
data.points[i][2] += dp_W(2);
}
}
real_t ba_cost(const vecx_t &e) {
return 0.5 * e.transpose() * e;
}
void ba_solve(ba_data_t &data) {
int max_iter = 10;
real_t cost_prev = 0.0;
for (int iter = 0; iter < max_iter; iter++) {
// Update
struct timespec t_start = tic();
const vecx_t e = ba_residuals(data);
const matx_t E = ba_jacobian(data);
ba_update(data, e, E);
// Calculate reprojection error
double sse = 0.0;
int N = 0;
for (int i = 0; i < e.size(); i += 2) {
const real_t dx = e(i);
const real_t dy = e(i + 1);
const real_t reproj_error = sqrt(dx * dx + dy * dy);
sse += reproj_error * reproj_error;
N++;
}
const double rmse_reproj_error = sqrt(sse / N);
// Print cost
const real_t cost = ba_cost(e);
printf(" - iter[%d] ", iter);
printf("cost: %.2e ", cost);
printf("time: %.3fs ", toc(&t_start));
printf("rmse_reproj_error: %.2fpx\n", rmse_reproj_error);
// Termination criteria
real_t cost_diff = fabs(cost - cost_prev);
if (cost_diff < 1.0e-1) {
printf("Done!\n");
break;
}
cost_prev = cost;
}
}
void ba_save(const ba_data_t &data, std::string &save_dir) {
// Create save directory
const char last_char = save_dir[save_dir.length() - 1];
const std::string postfix = (last_char == '/') ? "" : "/";
save_dir += postfix;
const std::string cmd = "mkdir -p " + save_dir;
const int retval = system(cmd.c_str());
if (retval != 0) {
printf("Error! Failed to save results to [%s]", save_dir.c_str());
}
// Save camera matrix
{
const std::string csv_path = save_dir + "camera.csv";
FILE *camera_csv = fopen(csv_path.c_str(), "w");
fprintf(camera_csv, "#camera_K\n");
fprintf(camera_csv, "%f, 0.0000, %f\n", data.cam_K(0, 0), data.cam_K(0, 2));
fprintf(camera_csv, "0.0000, %f, %f\n", data.cam_K(1, 1), data.cam_K(1, 2));
fprintf(camera_csv, "0.0000, 0.0000, 1.0000\n");
fclose(camera_csv);
}
// Save camera poses
{
const std::string csv_path = save_dir + "camera_poses.csv";
FILE *poses_csv = fopen(csv_path.c_str(), "w");
fprintf(poses_csv, "#qw,qx,qy,qz,rx,ry,rz\n");
for (const auto &pose : data.cam_poses) {
const auto &q = pose.rot();
const auto &r = pose.trans();
fprintf(poses_csv, "%f,%f,%f,%f,", q.w(), q.x(), q.y(), q.z());
fprintf(poses_csv, "%f,%f,%f", r(0), r(1), r(2));
fprintf(poses_csv, "\n");
}
fclose(poses_csv);
}
// Save target pose
{
const std::string csv_path = save_dir + "target_pose.csv";
FILE *target_csv = fopen(csv_path.c_str(), "w");
fprintf(target_csv, "#qw,qx,qy,qz,rx,ry,rz\n");
{
const auto &q = data.target_pose.rot();
const auto &r = data.target_pose.trans();
fprintf(target_csv, "%f,%f,%f,%f,", q.w(), q.x(), q.y(), q.z());
fprintf(target_csv, "%f,%f,%f", r(0), r(1), r(2));
fprintf(target_csv, "\n");
}
fclose(target_csv);
}
// Save keypoints
{
const std::string csv_path = save_dir + "keypoints.csv";
FILE *keypoints_csv = fopen(csv_path.c_str(), "w");
fprintf(keypoints_csv, "#size,keypoints\n");
for (const auto &kps : data.keypoints) {
int nb_kps = kps.size();
fprintf(keypoints_csv, "%d,", nb_kps * 2);
for (int j = 0; j < nb_kps; j++) {
fprintf(keypoints_csv, "%f,", kps[j](0));
fprintf(keypoints_csv, "%f", kps[j](1));
if (j + 1 < nb_kps) {
fprintf(keypoints_csv, ",");
}
}
fprintf(keypoints_csv, "\n");
}
fclose(keypoints_csv);
}
// Save point ids
{
const std::string csv_path = save_dir + "point_ids.csv";
FILE *point_ids_csv = fopen(csv_path.c_str(), "w");
fprintf(point_ids_csv, "#size,point_ids\n");
for (int i = 0; i < data.nb_ids; i++) {
int nb_ids = data.point_ids[i][0];
fprintf(point_ids_csv, "%d,", data.point_ids[i][0]);
for (int j = 1; j < (nb_ids + 1); j++) {
fprintf(point_ids_csv, "%d", data.point_ids[i][j]);
if (j + 1 < (nb_ids + 1)) {
fprintf(point_ids_csv, ",");
}
}
fprintf(point_ids_csv, "\n");
}
fclose(point_ids_csv);
}
// Save points
{
const std::string csv_path = save_dir + "points.csv";
FILE *points_csv = fopen(csv_path.c_str(), "w");
fprintf(points_csv, "#x,y,z\n");
for (int i = 0; i < data.nb_points; i++) {
fprintf(points_csv, "%f,", data.points[i][0]);
fprintf(points_csv, "%f,", data.points[i][1]);
fprintf(points_csv, "%f\n", data.points[i][2]);
}
fclose(points_csv);
}
}
| 9,970 | 4,372 |
// Fortnite (1.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.IsSelected
// (Public, HasOutParms, BlueprintCallable, BlueprintEvent)
// Parameters:
// bool Selected (Parm, OutParm, ZeroConstructor, IsPlainOldData)
void UItemManagementEquipSlot_C::IsSelected(bool* Selected)
{
static auto fn = UObject::FindObject<UFunction>("Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.IsSelected");
UItemManagementEquipSlot_C_IsSelected_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (Selected != nullptr)
*Selected = params.Selected;
}
// Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.OnFocusReceived
// (BlueprintCosmetic, Event, Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// struct FGeometry* MyGeometry (Parm, IsPlainOldData)
// struct FFocusEvent* InFocusEvent (Parm)
// struct FEventReply ReturnValue (Parm, OutParm, ReturnParm)
struct FEventReply UItemManagementEquipSlot_C::OnFocusReceived(struct FGeometry* MyGeometry, struct FFocusEvent* InFocusEvent)
{
static auto fn = UObject::FindObject<UFunction>("Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.OnFocusReceived");
UItemManagementEquipSlot_C_OnFocusReceived_Params params;
params.MyGeometry = MyGeometry;
params.InFocusEvent = InFocusEvent;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.SetSelected
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// bool Selected (Parm, ZeroConstructor, IsPlainOldData)
void UItemManagementEquipSlot_C::SetSelected(bool Selected)
{
static auto fn = UObject::FindObject<UFunction>("Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.SetSelected");
UItemManagementEquipSlot_C_SetSelected_Params params;
params.Selected = Selected;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.OnDragDetected
// (BlueprintCosmetic, Event, Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// struct FGeometry* MyGeometry (Parm, IsPlainOldData)
// struct FPointerEvent* PointerEvent (ConstParm, Parm, OutParm, ReferenceParm)
// class UDragDropOperation* Operation (Parm, OutParm, ZeroConstructor, IsPlainOldData)
void UItemManagementEquipSlot_C::OnDragDetected(struct FGeometry* MyGeometry, struct FPointerEvent* PointerEvent, class UDragDropOperation** Operation)
{
static auto fn = UObject::FindObject<UFunction>("Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.OnDragDetected");
UItemManagementEquipSlot_C_OnDragDetected_Params params;
params.MyGeometry = MyGeometry;
params.PointerEvent = PointerEvent;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (Operation != nullptr)
*Operation = params.Operation;
}
// Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.OnMouseButtonDown
// (BlueprintCosmetic, Event, Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// struct FGeometry* MyGeometry (Parm, IsPlainOldData)
// struct FPointerEvent* MouseEvent (ConstParm, Parm, OutParm, ReferenceParm)
// struct FEventReply ReturnValue (Parm, OutParm, ReturnParm)
struct FEventReply UItemManagementEquipSlot_C::OnMouseButtonDown(struct FGeometry* MyGeometry, struct FPointerEvent* MouseEvent)
{
static auto fn = UObject::FindObject<UFunction>("Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.OnMouseButtonDown");
UItemManagementEquipSlot_C_OnMouseButtonDown_Params params;
params.MyGeometry = MyGeometry;
params.MouseEvent = MouseEvent;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.OnDrop
// (BlueprintCosmetic, Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent)
// Parameters:
// struct FGeometry* MyGeometry (Parm, IsPlainOldData)
// struct FPointerEvent* PointerEvent (Parm)
// class UDragDropOperation** Operation (Parm, ZeroConstructor, IsPlainOldData)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
bool UItemManagementEquipSlot_C::OnDrop(struct FGeometry* MyGeometry, struct FPointerEvent* PointerEvent, class UDragDropOperation** Operation)
{
static auto fn = UObject::FindObject<UFunction>("Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.OnDrop");
UItemManagementEquipSlot_C_OnDrop_Params params;
params.MyGeometry = MyGeometry;
params.PointerEvent = PointerEvent;
params.Operation = Operation;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.RefreshItem
// (Public, BlueprintCallable, BlueprintEvent)
void UItemManagementEquipSlot_C::RefreshItem()
{
static auto fn = UObject::FindObject<UFunction>("Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.RefreshItem");
UItemManagementEquipSlot_C_RefreshItem_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.Construct
// (BlueprintCosmetic, Event, Public, BlueprintEvent)
void UItemManagementEquipSlot_C::Construct()
{
static auto fn = UObject::FindObject<UFunction>("Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.Construct");
UItemManagementEquipSlot_C_Construct_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.OnFocusLost
// (BlueprintCosmetic, Event, Public, BlueprintEvent)
// Parameters:
// struct FFocusEvent* InFocusEvent (Parm)
void UItemManagementEquipSlot_C::OnFocusLost(struct FFocusEvent* InFocusEvent)
{
static auto fn = UObject::FindObject<UFunction>("Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.OnFocusLost");
UItemManagementEquipSlot_C_OnFocusLost_Params params;
params.InFocusEvent = InFocusEvent;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.BndEvt__InputActionWidget_K2Node_ComponentBoundEvent_6_OnInputMethodChanged__DelegateSignature
// (BlueprintEvent)
// Parameters:
// bool bUsingGamepad (Parm, ZeroConstructor, IsPlainOldData)
void UItemManagementEquipSlot_C::BndEvt__InputActionWidget_K2Node_ComponentBoundEvent_6_OnInputMethodChanged__DelegateSignature(bool bUsingGamepad)
{
static auto fn = UObject::FindObject<UFunction>("Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.BndEvt__InputActionWidget_K2Node_ComponentBoundEvent_6_OnInputMethodChanged__DelegateSignature");
UItemManagementEquipSlot_C_BndEvt__InputActionWidget_K2Node_ComponentBoundEvent_6_OnInputMethodChanged__DelegateSignature_Params params;
params.bUsingGamepad = bUsingGamepad;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.OnDragCancelled
// (BlueprintCosmetic, Event, Public, HasOutParms, BlueprintEvent)
// Parameters:
// struct FPointerEvent* PointerEvent (ConstParm, Parm, OutParm, ReferenceParm)
// class UDragDropOperation** Operation (Parm, ZeroConstructor, IsPlainOldData)
void UItemManagementEquipSlot_C::OnDragCancelled(struct FPointerEvent* PointerEvent, class UDragDropOperation** Operation)
{
static auto fn = UObject::FindObject<UFunction>("Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.OnDragCancelled");
UItemManagementEquipSlot_C_OnDragCancelled_Params params;
params.PointerEvent = PointerEvent;
params.Operation = Operation;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.ExecuteUbergraph_ItemManagementEquipSlot
// (HasDefaults)
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void UItemManagementEquipSlot_C::ExecuteUbergraph_ItemManagementEquipSlot(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function ItemManagementEquipSlot.ItemManagementEquipSlot_C.ExecuteUbergraph_ItemManagementEquipSlot");
UItemManagementEquipSlot_C_ExecuteUbergraph_ItemManagementEquipSlot_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 9,808 | 3,002 |
/*-----------------------------------------------------------------------------
* This file is part of the Colony.Core Project. The Colony.Core Project is an
* open source project with a BSD type of licensing agreement. See the license
* agreement (license.txt) in the top/ directory or on the Internet at
* http://integerfox.com/colony.core/license.txt
*
* Copyright (c) 2014-2020 John T. Taylor
*
* Redistributions of the source code must retain the above copyright notice.
*----------------------------------------------------------------------------*/
#include "Catch/catch.hpp"
#include "Cpl/Text/FString.h"
#include "Cpl/System/Api.h"
#include "Cpl/System/Thread.h"
#include "Cpl/System/Trace.h"
#include "Cpl/Io/AtomicOutput.h"
#include "Cpl/Io/Stdio/StdOut.h"
#include "Cpl/System/_testsupport/Shutdown_TS.h"
#define SECT_ "_0test"
///
using namespace Cpl::Io;
////////////////////////////////////////////////////////////////////////////////
namespace {
class MyRunnable : public Cpl::System::Runnable
{
public:
///
const char* m_msg;
///
Cpl::System::Thread& m_masterThread;
///
int m_maxLoops;
///
unsigned long m_delay;
///
AtomicOutput<MyRunnable> m_out;
public:
///
MyRunnable( Cpl::System::Thread& masterThread, Output& fd, Cpl::System::Mutex& lock, int maxLoops, unsigned long delay, const char* msg )
:m_msg( msg ),
m_masterThread( masterThread ),
m_maxLoops( maxLoops ),
m_delay( delay ),
m_out( fd, lock )
{
}
public:
///
bool many( Output& fd )
{
Cpl::Text::FString<256> buffer;
bool io = false;
if ( fd.write( buffer, "1: %s", m_msg ) )
{
if ( fd.write( buffer, "2: %s", m_msg ) )
{
if ( fd.write( buffer, "3: %s", m_msg ) )
{
io = true;
}
}
}
return io;
}
///
void appRun()
{
Cpl::Text::FString<256> buffer;
// Wait till I'm told to start
Cpl::System::Thread::wait();
int i;
for ( i=0; i < m_maxLoops; i++ )
{
m_out.write( buffer, "** %s", m_msg );
m_out.requestOutputs( *this, &MyRunnable::many );
Cpl::System::Api::sleep( m_delay );
}
m_masterThread.signal();
}
};
}; // end namespace
////////////////////////////////////////////////////////////////////////////////
TEST_CASE( "atomic", "[atomic]" )
{
CPL_SYSTEM_TRACE_FUNC( SECT_ );
Cpl::System::Shutdown_TS::clearAndUseCounter();
Cpl::Io::Stdio::StdOut fd;
Cpl::System::Mutex lock;
MyRunnable appleRun( Cpl::System::Thread::getCurrent(), fd, lock, 10, 3, "Apple: very long string for more chance of interleaving 123456789 122456789 abcdef\n" );
MyRunnable orangeRun( Cpl::System::Thread::getCurrent(), fd, lock, 5, 7, "Orange: very long string for more chance of interleaving 123456789 122456789 abcdef\n" );
MyRunnable cherryRun( Cpl::System::Thread::getCurrent(), fd, lock, 13, 2, "Cherry: very long string for more chance of interleaving 123456789 122456789 abcdef\n" );
Cpl::System::Thread* appleThreadPtr = Cpl::System::Thread::create( appleRun, "APPLE" );
Cpl::System::Thread* orangeThreadPtr = Cpl::System::Thread::create( orangeRun, "ORANGE" );
Cpl::System::Thread* cherryThreadPtr = Cpl::System::Thread::create( cherryRun, "CHERRY" );
// Wait till all threads have spun up
Cpl::System::Api::sleep( 100 );
// Start all threads running
orangeThreadPtr->signal();
appleThreadPtr->signal();
cherryThreadPtr->signal();
// Wait for all threads to finish
Cpl::System::Thread::wait();
Cpl::System::Thread::wait();
Cpl::System::Thread::wait();
// Destroy all threads
Cpl::System::Thread::destroy( *orangeThreadPtr );
Cpl::System::Thread::destroy( *appleThreadPtr );
Cpl::System::Thread::destroy( *cherryThreadPtr );
REQUIRE( Cpl::System::Shutdown_TS::getAndClearCounter() == 0u );
}
| 4,159 | 1,404 |
/*
* Copyright (c) 2012-2021 Devin Smith <devin@devinsmith.net>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <algorithm> // std::replace
#include <cstring>
#include <stdexcept>
// FreeTDS stuff
#define MSDBLIB 1
#include <sqlfront.h>
#include <sybdb.h>
#include "SqlConnection.h"
namespace drs {
// Sadly, FreeTDS does not seem to check the return value of this message
// handler.
extern "C" int
sql_db_msg_handler(DBPROCESS * dbproc, DBINT msgno, int msgstate,
int severity, char *msgtext, char *srvname, char *procname, int line)
{
if (msgno == 5701 || msgno == 5703 || msgno == 5704)
return 0;
auto *conn = reinterpret_cast<SqlConnection *>(dbgetuserdata(dbproc));
if (conn != nullptr) {
return conn->MsgHandler(dbproc, msgno, msgstate, severity, msgtext, srvname,
procname, line);
}
// No connection associated??
return 0;
}
int SqlConnection::MsgHandler(DBPROCESS * dbproc, DBINT msgno, int msgstate,
int severity, char *msgtext, char *srvname, char *procname, int line)
{
/*
* If the severity is something other than 0 or the msg number is
* 0 (user informational messages).
*/
if (severity >= 0 || msgno == 0) {
/*
* If the message was something other than informational, and
* the severity was greater than 0, then print information to
* stderr with a little pre-amble information.
*/
if (msgno > 0 && severity > 0) {
_error.clear();
// Incorporate format?
_error += "Msg ";
_error += std::to_string(msgno);
_error += ", Level ";
_error += std::to_string(severity);
_error += ", State ";
_error += std::to_string(msgstate);
_error += "\nServer '";
_error += srvname;
_error += "'";
if (procname != nullptr && *procname != '\0') {
_error += ", Procedure '";
_error += procname;
_error += "'";
}
if (line > 0) {
_error += ", Line ";
_error += std::to_string(line);
}
_error += "\n";
char *database = dbname(dbproc);
if (database != nullptr && *database != '\0') {
_error += "Database '";
_error += database;
_error += "'\n";
}
_error += msgtext;
} else {
if (_error.back() != '\n') {
_error.append(1, '\n');
}
_error += msgtext;
if (msgno == 3621) {
severity = 1;
} else {
severity = 0;
}
}
}
if (msgno == 904) {
/* Database cannot be autostarted during server shutdown or startup */
_error += "Database does not exist, returning 0.\n";
return 0;
}
if (msgno == 911) {
/* Database does not exist */
_error += "Database does not exist, returning 0.\n";
return 0;
}
if (msgno == 952) {
/* Database is in transition. */
_error += "Database is in transition, returning 0.\n";
return 0;
}
return severity > 0;
}
extern "C" int
sql_db_err_handler(DBPROCESS *dbproc, int severity, int dberr,
int oserr, char *dberrstr, char *oserrstr)
{
// For server messages, cancel the query and rely on the
// message handler to capture the appropriate error message.
return INT_CANCEL;
}
// FreeTDS DBLib requires some initialization.
void sql_startup()
{
dbinit();
dbmsghandle(sql_db_msg_handler);
dberrhandle(sql_db_err_handler);
dbsetlogintime(5);
}
void sql_shutdown()
{
dbexit();
}
SqlConnection::~SqlConnection()
{
Disconnect();
}
void SqlConnection::Connect()
{
if (_dbHandle == nullptr || dbdead(_dbHandle)) {
LOGINREC *login = dblogin();
DBSETLAPP(login, "Microsoft");
dbsetlversion(login, DBVERSION_72);
DBSETLUSER(login, _user.c_str());
DBSETLPWD(login, _pass.c_str());
_dbHandle = tdsdbopen(login, fix_server(_server).c_str(), 1);
dbloginfree(login);
if (_dbHandle == nullptr || dbdead(_dbHandle))
throw std::runtime_error("Failed to connect to SQL Server");
// FreeTDS is so gross. Yep, instead of a void *, it's a BYTE * which
// is an "unsigned char *"
dbsetuserdata(_dbHandle, reinterpret_cast<BYTE *>(this));
dbuse(_dbHandle, _database.c_str());
run_initial_query();
}
}
void SqlConnection::run_initial_query()
{
// Heterogeneous queries require the ANSI_NULLS and ANSI_WARNINGS options to
// be set for the connection.
ExecDML("SET ANSI_NULLS ON;"
"SET ANSI_NULL_DFLT_ON ON;"
"SET ANSI_PADDING ON;"
"SET ANSI_WARNINGS ON;"
"SET QUOTED_IDENTIFIER ON;"
"SET CONCAT_NULL_YIELDS_NULL ON;");
}
void SqlConnection::Disconnect()
{
if (_dbHandle != nullptr) {
dbclose(_dbHandle);
_dbHandle = nullptr;
}
}
void SqlConnection::Dispose()
{
// We're done, so clear our error state.
_error.clear();
// Did we already fetch all result sets?
if (_fetched_results)
return;
// If the current result set has rows, drain them.
if (!_fetched_rows) {
while (NextRow());
}
// While there are more results, drain those rows as well.
while (NextResult()) {
while (NextRow());
}
_fetched_results = true;
}
void SqlConnection::ExecDML(const char *sql)
{
Connect();
// Dispose of any previous result set (if any).
Dispose();
_fetched_rows = false;
_fetched_results = false;
if (dbcmd(_dbHandle, sql) == FAIL)
throw std::runtime_error("Failed to submit command to freetds");
if (dbsqlexec(_dbHandle) == FAIL)
throw std::runtime_error("Failed to execute DML");
Dispose();
}
bool SqlConnection::NextResult()
{
// In order to advance to the next result set, we need to fetch
// all rows.
if (!_fetched_rows) {
while (NextRow());
}
int res = dbresults(_dbHandle);
if (res == FAIL)
throw std::runtime_error("Failed to fetch next result");
if (res == NO_MORE_RESULTS) {
_fetched_results = true;
return false;
}
return true;
}
bool SqlConnection::NextRow()
{
int row_code;
do {
row_code = dbnextrow(_dbHandle);
if (row_code == NO_MORE_ROWS) {
_fetched_rows = true;
return false;
}
if (row_code == REG_ROW)
return true;
if (row_code == FAIL) {
// ERROR ??
return false;
}
} while (row_code == BUF_FULL);
return false;
}
void SqlConnection::ExecSql(const char *sql)
{
Connect();
// Dispose of any previous result set (if any).
Dispose();
_fetched_rows = false;
_fetched_results = false;
if (dbcmd(_dbHandle, sql) == FAIL)
throw std::runtime_error("Failed to submit command to freetds");
if (dbsqlexec(_dbHandle) == FAIL) {
if (!_error.empty()) {
throw std::runtime_error(_error);
} else {
throw std::runtime_error("Failed to execute SQL");
}
}
int res = dbresults(_dbHandle);
if (res == FAIL)
throw std::runtime_error("Failed to fetch results SQL");
if (res == NO_MORE_RESULTS)
_fetched_results = true;
}
int
SqlConnection::GetOrdinal(const char *colName)
{
int i;
char errorStr[2048];
int total_cols = dbnumcols(_dbHandle);
for (i = 0; i < total_cols; i++) {
if (strcmp(dbcolname(_dbHandle, i + 1), colName) == 0) {
break;
}
}
if (i == total_cols) {
snprintf(errorStr, sizeof(errorStr),
"Requested column '%s' but does not exist.", colName);
throw std::runtime_error(errorStr);
}
return i;
}
std::string
SqlConnection::GetStringCol(int col)
{
if (col > dbnumcols(_dbHandle))
throw std::runtime_error("Requested string on nonexistent column");
int coltype = dbcoltype(_dbHandle, col + 1);
DBINT srclen = dbdatlen(_dbHandle, col + 1);
if (coltype == SYBDATETIME) {
DBDATETIME data;
DBDATEREC output;
char date_string[64];
memcpy(&data, dbdata(_dbHandle, col + 1), srclen);
dbdatecrack(_dbHandle, &output, &data);
snprintf(date_string, sizeof(date_string),
"%04d-%02d-%02d %02d:%02d:%02d.%03d", output.year, output.month,
output.day, output.hour, output.minute, output.second,
output.millisecond);
return date_string;
} else if (coltype != SYBCHAR && coltype != SYBTEXT) {
char nonstr[4096];
int dest_size;
dest_size = dbconvert(_dbHandle, coltype, dbdata(_dbHandle, col + 1),
srclen, SYBCHAR, (BYTE *)nonstr, sizeof(nonstr));
if (dest_size == -1) {
throw std::runtime_error("Could not convert source to string.");
}
nonstr[dest_size] = '\0';
return nonstr;
}
return std::string((const char *)dbdata(_dbHandle, col + 1), srclen);
}
std::string
SqlConnection::GetStringColByName(const char *colName)
{
return GetStringCol(GetOrdinal(colName));
}
int
SqlConnection::GetInt32ColByName(const char *colName)
{
return GetInt32Col(GetOrdinal(colName));
}
int
SqlConnection::GetInt32Col(int col)
{
int ret;
DBINT srclen;
int coltype;
if (col > dbnumcols(_dbHandle))
return 0;
srclen = dbdatlen(_dbHandle, col + 1);
coltype = dbcoltype(_dbHandle, col + 1);
if (coltype == SYBINT4) {
memcpy(&ret, dbdata(_dbHandle, col + 1), srclen);
} else if (coltype == SYBNUMERIC) {
dbconvert(nullptr, SYBNUMERIC, (BYTE *)dbdata(_dbHandle, col + 1), -1,
SYBINT4, (BYTE *)&ret, 4);
} else {
dbconvert(nullptr, coltype, (BYTE *)dbdata(_dbHandle, col + 1), -1,
SYBINT4, (BYTE *)&ret, 4);
}
return ret;
}
int
SqlConnection::GetMoneyCol(int col, int *dol, int *cen)
{
int64_t t64;
BYTE *src;
if (col > dbnumcols(_dbHandle))
return 0;
src = dbdata(_dbHandle, col + 1);
t64 = (int64_t)src[4] | (int64_t)src[5] << 8 |
(int64_t)src[6] << 16 | (int64_t)src[7] << 24 |
(int64_t)src[0] << 32 | (int64_t)src[1] << 40 |
(int64_t)src[2] << 48 | (int64_t)src[3] << 56;
*dol = (int)(t64 / 10000);
if (t64 < 0) t64 = -t64;
*cen = (int)(t64 % 10000);
return 1;
}
bool
SqlConnection::IsNullCol(int col)
{
if (col > dbnumcols(_dbHandle))
return true;
DBINT srclen = dbdatlen(_dbHandle, col + 1);
return srclen <= 0;
}
void SqlConnection::ExecStoredProc(const char *proc, struct db_params *params,
size_t parm_count)
{
execute_proc_common(proc, params, parm_count);
int res = dbresults(_dbHandle);
if (res == FAIL)
throw std::runtime_error("Failed to get results");
if (res == NO_MORE_RESULTS)
_fetched_results = true;
}
void SqlConnection::ExecNonQuery(const char *proc, struct db_params *params,
size_t parm_count)
{
execute_proc_common(proc, params, parm_count);
Dispose();
}
void SqlConnection::ExecStoredProc(const char *proc,
const std::vector<db_param>& params)
{
execute_proc_common2(proc, params);
int res = dbresults(_dbHandle);
if (res == FAIL)
throw std::runtime_error("Failed to get results");
if (res == NO_MORE_RESULTS)
_fetched_results = true;
}
void SqlConnection::ExecNonQuery(const char *proc,
const std::vector<db_param>& params)
{
execute_proc_common2(proc, params);
Dispose();
}
std::string SqlConnection::fix_server(const std::string& str)
{
std::string clean_server = str;
// A server contains a host and port, but users may be providing
// a server string with properties that aren't supported by FreeTDS.
// FreeTDS doesn't need the leading "tcp:" in some connection strings.
// Remove it if it exists.
std::string tcp_prefix("tcp:");
if (clean_server.compare(0, tcp_prefix.size(), tcp_prefix) == 0)
clean_server = clean_server.substr(tcp_prefix.size());
// Some people use commas instead of colon to separate the port number.
std::replace(clean_server.begin(), clean_server.end(), ',', ':');
return clean_server;
}
std::vector<std::string> SqlConnection::GetAllColumnNames()
{
int total_cols = dbnumcols(_dbHandle);
std::vector<std::string> columns;
columns.reserve(total_cols);
for (int i = 0; i < total_cols; i++) {
columns.emplace_back(dbcolname(_dbHandle, i + 1));
}
return columns;
}
void SqlConnection::execute_proc_common(const char *proc, struct db_params *params, size_t parm_count)
{
Connect();
Dispose();
_fetched_rows = false;
_fetched_results = false;
if (dbrpcinit(_dbHandle, proc, 0) == FAIL) {
std::string error = "Failed to init stored procedure: ";
error += proc;
throw std::runtime_error(error);
}
for (int i = 0; i < parm_count; i++) {
int real_type = 0;
switch (params[i].type) {
case BIT_TYPE:
real_type = SYBBITN;
case INT32_TYPE:
real_type = SYBINT4;
break;
case STRING_TYPE:
real_type = SYBCHAR;
break;
default:
throw std::runtime_error("Unknown stored procedure parameter type");
}
if (dbrpcparam(_dbHandle, params[i].name, params[i].status,
real_type, params[i].maxlen, params[i].datalen,
(BYTE *)params[i].value) == FAIL) {
std::string error = "Failed to set parameter ";
if (params[i].name != nullptr) {
error += params[i].name;
error.append(1, ' ');
}
error += "on procedure ";
error += proc;
throw std::runtime_error(error);
}
}
if (dbrpcsend(_dbHandle) == FAIL)
throw std::runtime_error("Failed to send RPC");
// Wait for the server to return
if (dbsqlok(_dbHandle) == FAIL)
throw std::runtime_error(_error);
// FreeTDS's implementation of dblib does not always process the result of
// of the message handler. For instance there are situations where an error
// has occurred but dbsqlok returned success. In these situations we need to
// check the actual _error property and throw if it is not blank.
if (!_error.empty())
throw std::runtime_error(_error);
}
void SqlConnection::execute_proc_common2(const char *proc,
const std::vector<db_param>& params)
{
Connect();
Dispose();
_fetched_rows = false;
_fetched_results = false;
if (dbrpcinit(_dbHandle, proc, 0) == FAIL) {
std::string error = "Failed to init stored procedure: ";
error += proc;
throw std::runtime_error(error);
}
for (const auto& param : params) {
int real_type = 0;
BYTE *value = (BYTE *)¶m.ivalue;
switch (param.type) {
case ParamType::Bit:
real_type = SYBBITN;
break;
case ParamType::Int:
real_type = SYBINT4;
break;
case ParamType::String:
real_type = SYBCHAR;
value = (BYTE *)param.pvalue;
break;
default:
// Not reached?
throw std::runtime_error("Unknown stored procedure parameter type");
}
if (dbrpcparam(_dbHandle, param.name, 0,
real_type, -1, param.datalen, value) == FAIL) {
std::string error = "Failed to set parameter ";
if (param.name != nullptr) {
error += param.name;
error.append(1, ' ');
}
error += "on procedure ";
error += proc;
throw std::runtime_error(error);
}
}
if (dbrpcsend(_dbHandle) == FAIL)
throw std::runtime_error("Failed to send RPC");
// Wait for the server to return
if (dbsqlok(_dbHandle) == FAIL)
throw std::runtime_error(_error);
// FreeTDS's implementation of dblib does not always process the result of
// of the message handler. For instance there are situations where an error
// has occurred but dbsqlok returned success. In these situations we need to
// check the actual _error property and throw if it is not blank.
if (!_error.empty())
throw std::runtime_error(_error);
}
}
| 16,033 | 5,744 |
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int> > ans;
if (root == NULL) return ans;
vector<int> path;
pathSumHelper(root, sum, ans, path);
return ans;
}
void pathSumHelper(TreeNode *root, int sum, vector<vector<int> > &ans, vector<int> &path) {
if (root == NULL) {
return;
}
if (sum == root->val && root->left == NULL && root->right == NULL) {
path.push_back(root->val);
ans.push_back(path);
path.pop_back();
return;
}
path.push_back(root->val);
pathSumHelper(root->left, sum - root->val, ans, path);
pathSumHelper(root->right, sum - root->val, ans, path);
path.pop_back();
}
};
int main() {
int sum = 22;
TreeNode *root = new TreeNode(5);
root->left = new TreeNode(4);
root->right = new TreeNode(8);
root->left->left = new TreeNode(11);
root->right->left = new TreeNode(13);
root->right->right = new TreeNode(4);
root->left->left->left = new TreeNode(7);
root->left->left->right = new TreeNode(2);
root->right->right->left = new TreeNode(5);
root->right->right->right = new TreeNode(1);
Solution s;
auto ans = s.pathSum(root, sum);
for (int i = 0; i < ans.size(); i++) {
for (int j = 0; j < ans[i].size(); j++) {
printf("%d ", ans[i][j]);
}
printf("\n");
}
return 0;
}
| 1,708 | 584 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2008 INRIA
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
*/
#include "simple-net-device.h"
#include "simple-channel.h"
#include "ns3/node.h"
#include "ns3/packet.h"
#include "ns3/log.h"
#include "ns3/pointer.h"
#include "ns3/error-model.h"
#include "ns3/trace-source-accessor.h"
#include "ns3/ipv4-header.h"
#include "ns3/arp-header.h"
#include "ns3/tcp-l4-protocol.h"
#include "ns3/udp-l4-protocol.h"
#include "ns3/udp-header.h"
#include "ns3/tcp-header.h"
#include "ns3/message.h"
#include "ns3/mal-proxy.h"
#include "ns3/ethernet-header.h"
#include "ns3/ethernet-trailer.h"
#include "ns3/llc-snap-header.h"
NS_LOG_COMPONENT_DEFINE ("SimpleNetDevice");
namespace ns3 {
NS_OBJECT_ENSURE_REGISTERED (SimpleNetDevice);
TypeId
SimpleNetDevice::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::SimpleNetDevice")
.SetParent<NetDevice> ()
.AddConstructor<SimpleNetDevice> ()
.AddAttribute ("ReceiveErrorModel",
"The receiver error model used to simulate packet loss",
PointerValue (),
MakePointerAccessor (&SimpleNetDevice::m_receiveErrorModel),
MakePointerChecker<ErrorModel> ())
.AddTraceSource ("PhyRxDrop",
"Trace source indicating a packet has been dropped by the device during reception",
MakeTraceSourceAccessor (&SimpleNetDevice::m_phyRxDropTrace))
;
return tid;
}
SimpleNetDevice::SimpleNetDevice ()
: m_channel (0),
m_node (0),
m_mtu (1500),
//m_mtu (0xffff),
m_ifIndex (0)
{
}
void
SimpleNetDevice::AddHeaderTrailer (Ptr<Packet> p, Mac48Address source, Mac48Address dest, uint16_t protocolNumber)
{
EthernetHeader header (false);
header.SetSource (source);
header.SetDestination (dest);
EthernetTrailer trailer;
uint16_t lengthType = 0;
lengthType = protocolNumber;
LlcSnapHeader llc;
llc.SetType (protocolNumber);
p->AddHeader (llc);
//
// This corresponds to the length interpretation of the lengthType
// field but with an LLC/SNAP header added to the payload as in
// IEEE 802.2
//
lengthType = p->GetSize ();
//
// All Ethernet frames must carry a minimum payload of 46 bytes. The
// LLC SNAP header counts as part of this payload. We need to padd out
// if we don't have enough bytes. These must be real bytes since they
// will be written to pcap files and compared in regression trace files.
//
if (p->GetSize () < 46)
{
uint8_t buffer[46];
memset (buffer, 0, 46);
Ptr<Packet> padd = Create<Packet> (buffer, 46 - p->GetSize ());
p->AddAtEnd (padd);
}
NS_ASSERT_MSG (p->GetSize () <= GetMtu (),
"CsmaNetDevice::AddHeader(): 802.3 Length/Type field with LLC/SNAP: "
"length interpretation must not exceed device frame size minus overhead " << p->GetSize() << ":" << GetMtu());
NS_LOG_LOGIC ("header.SetLengthType (" << lengthType << ")");
header.SetLengthType (lengthType);
p->AddHeader (header);
if (Node::ChecksumEnabled ())
{
trailer.EnableFcs (true);
}
trailer.CalcFcs (p);
p->AddTrailer (trailer);
}
Ipv4Header SimpleNetDevice::GetIPHeader(Ptr<Packet> packet_received)
{
Ptr<Packet> packet = packet_received->Copy ();
EthernetTrailer trailer;
packet->RemoveTrailer (trailer);
EthernetHeader header (false);
packet->RemoveHeader (header);
Ipv4Header ipHeader;
packet->PeekHeader(ipHeader);
return ipHeader;
}
bool
SimpleNetDevice::GhostIntercept(Ptr<Packet> packet_received, bool sending, bool *writeToTap, Mac48Address from)
{
ProfileFunction("GhostIntercept", true);
NS_LOG_FUNCTION(this << " UID : " << packet_received->GetUid() << " NODE: " << m_node->GetId());
MaliciousTag mtag;
int protocol;
packet_received->PeekPacketTag(mtag);
Ptr<Packet> packet = packet_received->Copy ();
Ipv4Header ipHeader;
packet->PeekHeader(ipHeader);
//uint32_t size = packet->PeekHeader(ipHeader);
NS_LOG_INFO("Packet " << packet_received->GetUid() << " IP header " << ipHeader);
protocol = ipHeader.GetProtocol();
if (protocol != UdpL4Protocol::PROT_NUMBER && protocol != TcpL4Protocol::PROT_NUMBER) {
NS_LOG_DEBUG( "GhostIntercept false 7: protocol" << protocol);
packet->AddHeader(ipHeader);
// Proxy only receives TCP and UDP packets
ProfileFunction("GhostIntercept", false);
return false;
}
// don't process UDP packets that you are receiving
/* // REPLAY requires to look at packets being received
if (protocol == UdpL4Protocol::PROT_NUMBER && !sending) {
return false;
}
*/
if (sending) {
if (mtag.GetMalStatus() == MaliciousTag::FROMPROXY && mtag.GetSrcNode() == m_node->GetId()) {
ProfileFunction("GhostIntercept", false);
return false;
// if sending, and from my proxy, no point to intercept, but possibly to write tap...?
}
}
Ptr<Packet> pcopy = packet->Copy();
pcopy->RemoveHeader(ipHeader);
if (ipHeader.GetPayloadSize () < pcopy->GetSize ())
{
pcopy->RemoveAtEnd (pcopy->GetSize () - ipHeader.GetPayloadSize ());
}
uint16_t destPort = 0;
// check port: if the port is not a listening one, create a new one
if (protocol == UdpL4Protocol::PROT_NUMBER) {
UdpHeader udpHeader;
pcopy->PeekHeader (udpHeader);
destPort = udpHeader.GetDestinationPort() ;
if (!m_node->IsLocalPort(false, destPort)) {
ProfileFunction("GhostIntercept", false);
return false;
}
//see if the malicious proxy cares about this message type
/* XXX - Now this is done at TapDevice
Ptr<Application> app = m_node->GetApplication(0);
uint8_t *msg = new uint8_t[pcopy->GetSize()];
pcopy->CopyData(msg, pcopy->GetSize());
uint32_t offset = 8; //size of udp header
Message *m = new Message(msg+offset);
Application *ptr;
ptr = GetPointer(app);
Ptr<MalProxy> proxy = Ptr<MalProxy>((MalProxy*)ptr);
if (!proxy->MalMsg(m)) {
std::cout << "GhostIntercept false 3 type: " << m->type << std::endl;
delete m;
delete msg;
ProfileFunction("GhostIntercept", false);
return false;
}
delete m;
delete msg;
*/
}
if (protocol == TcpL4Protocol::PROT_NUMBER) {
TcpHeader tcpHeader;
pcopy->PeekHeader (tcpHeader);
destPort = tcpHeader.GetDestinationPort() ;
if (!m_node->IsLocalPort(true, destPort)) {
ProfileFunction("GhostIntercept", false);
return false;
}
}
packet->RemovePacketTag(mtag);
mtag.StartTimer();
mtag.SetIPDest(ipHeader.GetDestination().Get());
mtag.SetIPSource(ipHeader.GetSource().Get());
if (mtag.GetSrcNode() != m_node->GetId()) { // from outside - intercept
NS_LOG_INFO(" Packet from outside. destination should be me " << ipHeader.GetDestination()); // actually, the destination should be already me
}
else {
if (mtag.GetMalStatus() == MaliciousTag::FROMTAP) {
NS_LOG_INFO(" Intercept packet from my TAP: to handle this packet should muck destination from original "
<< ipHeader.GetDestination() << " to myaddr " << ipHeader.GetSource()); // from my tap device. should intercept
mtag.SetSpoof(true);
}
else {
// from my proxy, do not intercept and it should be written on my tap
if (m_node->IsLocalAddress(ipHeader.GetDestination())) {
NS_LOG_INFO("from proxy and me for mine - spoof: " << mtag.IsSpoof() << " to my tap");
(*writeToTap) = true;
packet->AddPacketTag(mtag);
ProfileFunction("GhostIntercept", false);
return false;
}
}
}
packet->AddPacketTag(mtag);
// add sending information
// make ipv4 receive the packet
ProfileFunction("GhostIntercept", false);
if (m_node->IsMalicious()) m_rxCallback (this, packet, 2048, from);
//if (m_node->IsMalicious()) m_rxCallback (this, packet, 2048, header.GetSource ());
return true;
}
void
SimpleNetDevice::Receive (Ptr<Packet> packet, uint16_t protocol,
Mac48Address to, Mac48Address from)
{
ProfileFunction("SimpleReceive", true);
NS_LOG_FUNCTION (m_node->GetId() << " pcaket: " << packet->GetUid() << protocol << to << from);
NetDevice::PacketType packetType;
if (m_receiveErrorModel && m_receiveErrorModel->IsCorrupt (packet) )
{
m_phyRxDropTrace (packet);
ProfileFunction("SimpleReceive", false);
return;
}
Ptr<Packet> originalPacket = packet->Copy ();
EthernetTrailer trailer;
originalPacket->RemoveTrailer (trailer);
if (Node::ChecksumEnabled ())
{
trailer.EnableFcs (true);
}
trailer.CheckFcs (originalPacket);
bool crcGood = trailer.CheckFcs (originalPacket);
if (!crcGood)
{
NS_LOG_INFO ("CRC error on originalPacket " << originalPacket);
m_phyRxDropTrace (originalPacket);
ProfileFunction("SimpleReceive", false);
return;
}
EthernetHeader header (false);
originalPacket->RemoveHeader (header);
uint16_t protocol_new;
NS_LOG_INFO("Ethernet Header: " << header);
//
// If the length/type is less than 1500, it corresponds to a length
// interpretation originalPacket. In this case, it is an 802.3 originalPacket and
// will also have an 802.2 LLC header. If greater than 1500, we
// find the protocol number (Ethernet type) directly.
//
if (header.GetLengthType () <= 1500)
{
if (originalPacket->GetSize() < header.GetLengthType()) return;
NS_ASSERT (originalPacket->GetSize () >= header.GetLengthType ());
uint32_t padlen = originalPacket->GetSize () - header.GetLengthType ();
if (padlen > 46) return;
if (padlen > 0)
{
originalPacket->RemoveAtEnd (padlen);
}
LlcSnapHeader llc;
originalPacket->RemoveHeader (llc);
protocol_new = llc.GetType ();
}
else
{
protocol_new = header.GetLengthType ();
}
bool writeToTap = false;
if (m_node->IsMalicious() && protocol == 2048) {
//NS_LOG_INFO("try intercept while receiving at node " << m_node->GetId());
//if (GhostIntercept(originalPacket, false, &writeToTap, from)) return;
}
if (to == m_address)
{
packetType = NetDevice::PACKET_HOST;
}
else if (to.IsBroadcast ())
{
packetType = NetDevice::PACKET_BROADCAST;
}
else if (to.IsGroup ())
{
packetType = NetDevice::PACKET_MULTICAST;
}
else
{
packetType = NetDevice::PACKET_OTHERHOST;
}
/*
if (protocol_new == 2048 && m_node->IsMalicious()
&& m_node->IsLocalAddress(GetIPHeader(packet).GetDestination())) {
writeToTap = true;
}
*/
if (!m_promiscCallback.IsNull ())
{
m_promiscCallback (this, originalPacket, protocol, from, to, packetType); // this writes to tap
}
ProfileFunction("SimpleReceive", false);
/*if (writeToTap) return;*/
if (packetType != PACKET_OTHERHOST)
m_rxCallback (this, packet, protocol_new, from); // local up
}
void
SimpleNetDevice::AddChannel (Ptr<SimpleChannel> channel, Mac48Address dest_addr)
{
uint64_t mac = 0;
dest_addr.CopyTo((uint8_t*)&mac);
m_channels[mac] = channel;
channel->Add (this);
}
uint32_t
SimpleNetDevice::GetNChannels (void)
{
return m_channels.size ();
}
/*
Ptr<Channel>
SimpleNetDevice::GetChannel (uint32_t i)
{
return m_channels[i];
}
*/
// hjlee deprecate later
void
SimpleNetDevice::SetChannel (Ptr<SimpleChannel> channel)
{
m_channel = channel;
m_channel->Add (this);
}
void
SimpleNetDevice::SetReceiveErrorModel (Ptr<ErrorModel> em)
{
m_receiveErrorModel = em;
}
void
SimpleNetDevice::SetIfIndex (const uint32_t index)
{
m_ifIndex = index;
}
uint32_t
SimpleNetDevice::GetIfIndex (void) const
{
return m_ifIndex;
}
Ptr<Channel>
SimpleNetDevice::GetChannel (void) const
{
return m_channel;
}
void
SimpleNetDevice::SetAddress (Address address)
{
m_address = Mac48Address::ConvertFrom (address);
}
Address
SimpleNetDevice::GetAddress (void) const
{
//
// Implicit conversion from Mac48Address to Address
//
return m_address;
}
bool
SimpleNetDevice::SetMtu (const uint16_t mtu)
{
m_mtu = mtu;
return true;
}
uint16_t
SimpleNetDevice::GetMtu (void) const
{
return m_mtu;
}
bool
SimpleNetDevice::IsLinkUp (void) const
{
return true;
}
void
SimpleNetDevice::AddLinkChangeCallback (Callback<void> callback)
{}
bool
SimpleNetDevice::IsBroadcast (void) const
{
return true;
}
Address
SimpleNetDevice::GetBroadcast (void) const
{
return Mac48Address ("ff:ff:ff:ff:ff:ff");
}
bool
SimpleNetDevice::IsMulticast (void) const
{
return false;
}
Address
SimpleNetDevice::GetMulticast (Ipv4Address multicastGroup) const
{
return Mac48Address::GetMulticast (multicastGroup);
}
Address SimpleNetDevice::GetMulticast (Ipv6Address addr) const
{
return Mac48Address::GetMulticast (addr);
}
bool
SimpleNetDevice::IsPointToPoint (void) const
{
return false;
}
bool
SimpleNetDevice::IsBridge (void) const
{
return false;
}
bool
SimpleNetDevice::Send (Ptr<Packet> packet, const Address& dest, uint16_t protocolNumber)
{
NS_LOG_FUNCTION (" pcaket: " << packet->GetUid() << dest << protocolNumber);
Mac48Address to = Mac48Address::ConvertFrom (dest);
//m_channel->Send (packet, protocolNumber, to, m_address, this);
SendFrom(packet, m_address, dest, protocolNumber);
return true;
}
bool
SimpleNetDevice::SendFrom (Ptr<Packet> packet, const Address& source, const Address& dest, uint16_t protocolNumber)
{
NS_LOG_FUNCTION (" pcaket: " << packet->GetUid() << source << dest << protocolNumber);
ProfileFunction("SimpleSendFrom", true);
Mac48Address to = Mac48Address::ConvertFrom (dest);
Mac48Address from = Mac48Address::ConvertFrom (source);
AddHeaderTrailer (packet, from, to, protocolNumber);
//to avoid having to write a hash function for uint8_t[6], just sticking
// the mac address into a uint64_t
uint64_t mac = 0;
to.CopyTo((uint8_t*)&mac);
__gnu_cxx::hash_map<uint64_t, Ptr<SimpleChannel> >::iterator ch = m_channels.find(mac);
ProfileFunction("SimpleSendFrom", false);
if (ch != m_channels.end()) {
(ch->second)->Send (packet, protocolNumber, to, from, this);
} else {
NS_LOG_INFO(" no matching address for " << to << ", broadcast ");
for (ch = m_channels.begin(); ch != m_channels.end(); ch++) {
(ch->second)->Send (packet, protocolNumber, to, from, this);
}
}
return true;
}
Ptr<Node>
SimpleNetDevice::GetNode (void) const
{
return m_node;
}
void
SimpleNetDevice::SetNode (Ptr<Node> node)
{
m_node = node;
}
bool
SimpleNetDevice::NeedsArp (void) const
{
return true;
}
void
SimpleNetDevice::SetReceiveCallback (NetDevice::ReceiveCallback cb)
{
m_rxCallback = cb;
}
void
SimpleNetDevice::DoDispose (void)
{
m_channel = 0;
m_node = 0;
m_receiveErrorModel = 0;
NetDevice::DoDispose ();
}
void
SimpleNetDevice::SetPromiscReceiveCallback (PromiscReceiveCallback cb)
{
m_promiscCallback = cb;
}
bool
SimpleNetDevice::SupportsSendFrom (void) const
{
return true;
}
} // namespace ns3
| 15,215 | 5,622 |
/*
* This file is part of ACADO Toolkit.
*
* ACADO Toolkit -- A Toolkit for Automatic Control and Dynamic Optimization.
* Copyright (C) 2008-2014 by Boris Houska, Hans Joachim Ferreau,
* Milan Vukov, Rien Quirynen, KU Leuven.
* Developed within the Optimization in Engineering Center (OPTEC)
* under supervision of Moritz Diehl. All rights reserved.
*
* ACADO Toolkit is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* ACADO Toolkit is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with ACADO Toolkit; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/acado/validated_integrator/ellipsoidal_integrator.hpp
* \author Boris Houska, Mario Villanueva, Benoit Chachuat
*/
#ifndef ACADO_TOOLKIT_ELLIPSOIDAL_INTEGRATOR_HPP
#define ACADO_TOOLKIT_ELLIPSOIDAL_INTEGRATOR_HPP
#include <iostream>
#include <iomanip>
#include <acado/clock/clock.hpp>
#include <acado/utils/acado_utils.hpp>
#include <acado/user_interaction/algorithmic_base.hpp>
#include <acado/matrix_vector/matrix_vector.hpp>
#include <acado/variables_grid/variables_grid.hpp>
#include <acado/symbolic_expression/symbolic_expression.hpp>
#include <acado/function/function.hpp>
#include <acado/set_arithmetics/set_arithmetics.hpp>
BEGIN_NAMESPACE_ACADO
/**
* \brief Validated integrator for ODEs based on Taylor models with ellipsoidal remainder term.
*
* \author Mario Villanueva, Boris Houska
*/
class EllipsoidalIntegrator : public AlgorithmicBase
{
public:
/** Default constructor. */
EllipsoidalIntegrator( );
/** Constructor that takes the differential equation and the order (default 3) as an argument.
*
* \param rhs_ The differential equation.
* \param N_ The order of the intergrator (default = 3).
*/
EllipsoidalIntegrator( const DifferentialEquation &rhs_, const int &N_ = 3 );
/** Copy constructor (deep copy). */
EllipsoidalIntegrator( const EllipsoidalIntegrator& arg );
/** Destructor. */
virtual ~EllipsoidalIntegrator( );
/** Assignment operator (deep copy). */
virtual EllipsoidalIntegrator& operator=( const EllipsoidalIntegrator& arg );
Tmatrix<Interval> integrate( double t0, double tf, int M, const Tmatrix<Interval> &x );
Tmatrix<Interval> integrate( double t0, double tf, int M, const Tmatrix<Interval> &x, const Tmatrix<Interval> &p );
Tmatrix<Interval> integrate( double t0, double tf, int M, const Tmatrix<Interval> &x,
const Tmatrix<Interval> &p, const Tmatrix<Interval> &w );
template <typename T> returnValue integrate( double t0, double tf,
Tmatrix<T> *x, Tmatrix<T> *p = 0, Tmatrix<T> *w = 0 );
template <typename T> double step( const double &t, const double &tf,
Tmatrix<T> *x, Tmatrix<T> *p = 0, Tmatrix<T> *w = 0 );
returnValue init( const DifferentialEquation &rhs_, const int &N_ = 3 );
Tmatrix<Interval> boundQ() const;
template <typename T> Tmatrix<Interval> getStateBound( const Tmatrix<T> &x ) const;
// PRIVATE FUNCTIONS:
// ----------------------------------------------------------
private:
virtual returnValue setupOptions( );
void copy( const EllipsoidalIntegrator& arg );
template <typename T> void phase0( double t,
Tmatrix<T> *x, Tmatrix<T> *p, Tmatrix<T> *w,
Tmatrix<T> &coeff, Tmatrix<double> &C );
template <typename T> double phase1( double t, double tf,
Tmatrix<T> *x, Tmatrix<T> *p, Tmatrix<T> *w,
Tmatrix<T> &coeff,
Tmatrix<double> &C );
template <typename T> void phase2( double t, double h,
Tmatrix<T> *x, Tmatrix<T> *p, Tmatrix<T> *w,
Tmatrix<T> &coeff,
Tmatrix<double> &C );
template <typename T> Tmatrix<T> evaluate( Function &f, double t,
Tmatrix<T> *x, Tmatrix<T> *p, Tmatrix<T> *w ) const;
template <typename T> Tmatrix<T> evaluate( Function &f, Interval t,
Tmatrix<T> *x, Tmatrix<T> *p, Tmatrix<T> *w ) const;
template <typename T> Tmatrix<T> phi( const Tmatrix<T> &coeff, const double &h ) const;
template <typename T> Tmatrix<double> hat( const Tmatrix<T> &x ) const;
Tmatrix<Interval> evalC ( const Tmatrix<double> &C, double h ) const;
Tmatrix<double> evalC2( const Tmatrix<double> &C, double h ) const;
double scale( const Interval &E, const Interval &X ) const;
double norm ( const Tmatrix<Interval> &E, Tmatrix<Interval> &X ) const;
BooleanType isIncluded( const Tmatrix<Interval> &A, const Tmatrix<Interval> &B ) const;
template <typename T> Tmatrix<Interval> bound( const Tmatrix<T> &x ) const;
template <typename T> Tmatrix<Interval> getRemainder( const Tmatrix<T> &x ) const;
template <typename T> Tmatrix<T> getPolynomial( const Tmatrix<T> &x ) const;
template <typename T> void center( Tmatrix<T> &x ) const;
void updateQ( Tmatrix<double> C, Tmatrix<Interval> R );
void setInfinity();
// PRIVATE MEMBERS:
// ----------------------------------------------------------
private:
int nx; // number of differential states.
int N ; // the order of the integrator.
Function g ; // Taylor expansion of the solution trajectory
Function gr ; // Remainder term associated with g
Function dg ; // Jacobian of the function g : g(t,x,...)/dx
Function ddg; // Directional derivative of dg: (d^2 g(t,x,...)/d^2x)*r*r
Tmatrix<double> Q; // Ellipsoidal remainder matrix
RealClock totalTime ;
RealClock Phase0Time;
RealClock Phase1Time;
};
CLOSE_NAMESPACE_ACADO
#include <acado/validated_integrator/ellipsoidal_integrator.ipp>
#endif // ACADO_TOOLKIT_ELLIPSOIDAL_INTEGRATOR_HPP
// end of file.
| 6,270 | 2,314 |
/**
🍪 thew6rst
🍪 12.02.2021 10:45:31
**/
#ifdef W
#include "k_II.h"
#else
#include <bits/stdc++.h>
using namespace std;
#endif
#define pb emplace_back
#define all(x) x.begin(), x.end()
#define sz(x) static_cast<int32_t>(x.size())
template<class T> class Y {
T f;
public:
template<class U> explicit Y(U&& f): f(forward<U>(f)) {}
template<class... Args> decltype(auto) operator()(Args&&... args) {
return f(ref(*this), forward<Args>(args)...);
}
}; template<class T> Y(T) -> Y<T>;
const int64_t DESPACITO = 2e18;
const int INF = 2e9, MOD = 1e9+7;
const int N = 2e5 + 5;
const int LG = 20;
int main() {
cin.tie(nullptr)->sync_with_stdio(false);
int i, n, Q;
cin >> n >> Q;
vector<vector<int>> g(n);
for(i = 1; i < n; i++) {
int p; cin >> p;
g[--p].pb(i);
}
array<vector<int>, LG> anc;
for(auto& x: anc) x.assign(n, -1);
Y([&](auto dfs, int v, int p) -> void {
anc[0][v] = p;
for(int k = 1; k < LG; k++)
anc[k][v] = ~anc[k-1][v]? anc[k-1][anc[k-1][v]] : -1;
for(auto& x: g[v])
dfs(x, v);
})(0, -1);
auto walk = [&anc](int v, int d) {
for(int k = LG-1; ~v and ~k; k--)
if(d>>k & 1) v = anc[k][v];
return ~v? v+1 : v;
};
while(Q--) {
int x, d; cin >> x >> d;
cout << walk(--x, d) << '\n';
} | 1,464 | 670 |
// Copyright 2017 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 "net/reporting/reporting_header_parser.h"
#include <sstream>
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/json/json_reader.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/simple_test_tick_clock.h"
#include "base/time/time.h"
#include "base/values.h"
#include "net/base/features.h"
#include "net/base/schemeful_site.h"
#include "net/reporting/mock_persistent_reporting_store.h"
#include "net/reporting/reporting_cache.h"
#include "net/reporting/reporting_endpoint.h"
#include "net/reporting/reporting_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
#include "url/origin.h"
namespace net {
namespace {
using CommandType = MockPersistentReportingStore::Command::Type;
// This test is parametrized on a boolean that represents whether to use a
// MockPersistentReportingStore.
class ReportingHeaderParserTest : public ReportingTestBase,
public ::testing::WithParamInterface<bool> {
protected:
ReportingHeaderParserTest() {
// This is a private API of the reporting service, so no need to test the
// case kPartitionNelAndReportingByNetworkIsolationKey is disabled - the
// feature is only applied at the entry points of the service.
feature_list_.InitAndEnableFeature(
features::kPartitionNelAndReportingByNetworkIsolationKey);
ReportingPolicy policy;
policy.max_endpoints_per_origin = 10;
policy.max_endpoint_count = 20;
UsePolicy(policy);
if (GetParam())
store_ = std::make_unique<MockPersistentReportingStore>();
else
store_ = nullptr;
UseStore(store_.get());
}
~ReportingHeaderParserTest() override = default;
void SetUp() override {
// All ReportingCache methods assume that the store has been initialized.
if (mock_store()) {
mock_store()->LoadReportingClients(
base::BindOnce(&ReportingCache::AddClientsLoadedFromStore,
base::Unretained(cache())));
mock_store()->FinishLoading(true);
}
}
MockPersistentReportingStore* mock_store() { return store_.get(); }
ReportingEndpointGroup MakeEndpointGroup(
const std::string& name,
const std::vector<ReportingEndpoint::EndpointInfo>& endpoints,
OriginSubdomains include_subdomains = OriginSubdomains::DEFAULT,
base::TimeDelta ttl = base::TimeDelta::FromDays(1),
url::Origin origin = url::Origin()) {
ReportingEndpointGroupKey group_key(kNik_ /* unused */,
url::Origin() /* unused */, name);
ReportingEndpointGroup group;
group.group_key = group_key;
group.include_subdomains = include_subdomains;
group.ttl = ttl;
group.endpoints = std::move(endpoints);
return group;
}
// Constructs a string which would represent a single group in a Report-To
// header. If |group_name| is an empty string, the group name will be omitted
// (and thus default to "default" when parsed). Setting |omit_defaults| omits
// the priority, weight, and include_subdomains fields if they are default,
// otherwise they are spelled out fully.
std::string ConstructHeaderGroupString(const ReportingEndpointGroup& group,
bool omit_defaults = true) {
std::ostringstream s;
s << "{ ";
if (!group.group_key.group_name.empty()) {
s << "\"group\": \"" << group.group_key.group_name << "\", ";
}
s << "\"max_age\": " << group.ttl.InSeconds() << ", ";
if (group.include_subdomains != OriginSubdomains::DEFAULT) {
s << "\"include_subdomains\": true, ";
} else if (!omit_defaults) {
s << "\"include_subdomains\": false, ";
}
s << "\"endpoints\": [";
for (const ReportingEndpoint::EndpointInfo& endpoint_info :
group.endpoints) {
s << "{ ";
s << "\"url\": \"" << endpoint_info.url.spec() << "\"";
if (!omit_defaults ||
endpoint_info.priority !=
ReportingEndpoint::EndpointInfo::kDefaultPriority) {
s << ", \"priority\": " << endpoint_info.priority;
}
if (!omit_defaults ||
endpoint_info.weight !=
ReportingEndpoint::EndpointInfo::kDefaultWeight) {
s << ", \"weight\": " << endpoint_info.weight;
}
s << " }, ";
}
if (!group.endpoints.empty())
s.seekp(-2, s.cur); // Overwrite trailing comma and space.
s << "]";
s << " }";
return s.str();
}
void ParseHeader(const NetworkIsolationKey& network_isolation_key,
const GURL& url,
const std::string& json) {
std::unique_ptr<base::Value> value =
base::JSONReader::ReadDeprecated("[" + json + "]");
if (value) {
ReportingHeaderParser::ParseHeader(context(), network_isolation_key, url,
std::move(value));
}
}
base::test::ScopedFeatureList feature_list_;
const GURL kUrl1_ = GURL("https://origin1.test/path");
const url::Origin kOrigin1_ = url::Origin::Create(kUrl1_);
const GURL kUrl2_ = GURL("https://origin2.test/path");
const url::Origin kOrigin2_ = url::Origin::Create(kUrl2_);
const NetworkIsolationKey kNik_ =
NetworkIsolationKey(SchemefulSite(kOrigin1_), SchemefulSite(kOrigin1_));
const NetworkIsolationKey kOtherNik_ =
NetworkIsolationKey(SchemefulSite(kOrigin2_), SchemefulSite(kOrigin2_));
const GURL kUrlEtld_ = GURL("https://co.uk/foo.html/");
const url::Origin kOriginEtld_ = url::Origin::Create(kUrlEtld_);
const GURL kEndpoint1_ = GURL("https://endpoint1.test/");
const GURL kEndpoint2_ = GURL("https://endpoint2.test/");
const GURL kEndpoint3_ = GURL("https://endpoint3.test/");
const GURL kEndpointPathAbsolute_ =
GURL("https://origin1.test/path-absolute-url");
const std::string kGroup1_ = "group1";
const std::string kGroup2_ = "group2";
// There are 2^3 = 8 of these to test the different combinations of matching
// vs mismatching NIK, origin, and group.
const ReportingEndpointGroupKey kGroupKey11_ =
ReportingEndpointGroupKey(kNik_, kOrigin1_, kGroup1_);
const ReportingEndpointGroupKey kGroupKey21_ =
ReportingEndpointGroupKey(kNik_, kOrigin2_, kGroup1_);
const ReportingEndpointGroupKey kGroupKey12_ =
ReportingEndpointGroupKey(kNik_, kOrigin1_, kGroup2_);
const ReportingEndpointGroupKey kGroupKey22_ =
ReportingEndpointGroupKey(kNik_, kOrigin2_, kGroup2_);
private:
std::unique_ptr<MockPersistentReportingStore> store_;
};
// TODO(juliatuttle): Ideally these tests should be expecting that JSON parsing
// (and therefore header parsing) may happen asynchronously, but the entire
// pipeline is also tested by NetworkErrorLoggingEndToEndTest.
TEST_P(ReportingHeaderParserTest, Invalid) {
static const struct {
const char* header_value;
const char* description;
} kInvalidHeaderTestCases[] = {
{"{\"max_age\":1, \"endpoints\": [{}]}", "missing url"},
{"{\"max_age\":1, \"endpoints\": [{\"url\":0}]}", "non-string url"},
{"{\"max_age\":1, \"endpoints\": [{\"url\":\"//scheme/relative\"}]}",
"scheme-relative url"},
{"{\"max_age\":1, \"endpoints\": [{\"url\":\"relative/path\"}]}",
"path relative url"},
{"{\"max_age\":1, \"endpoints\": [{\"url\":\"http://insecure/\"}]}",
"insecure url"},
{"{\"endpoints\": [{\"url\":\"https://endpoint/\"}]}", "missing max_age"},
{"{\"max_age\":\"\", \"endpoints\": [{\"url\":\"https://endpoint/\"}]}",
"non-integer max_age"},
{"{\"max_age\":-1, \"endpoints\": [{\"url\":\"https://endpoint/\"}]}",
"negative max_age"},
{"{\"max_age\":1, \"group\":0, "
"\"endpoints\": [{\"url\":\"https://endpoint/\"}]}",
"non-string group"},
// Note that a non-boolean include_subdomains field is *not* invalid, per
// the spec.
// Priority should be a nonnegative integer.
{"{\"max_age\":1, "
"\"endpoints\": [{\"url\":\"https://endpoint/\",\"priority\":\"\"}]}",
"non-integer priority"},
{"{\"max_age\":1, "
"\"endpoints\": [{\"url\":\"https://endpoint/\",\"priority\":-1}]}",
"negative priority"},
// Weight should be a non-negative integer.
{"{\"max_age\":1, "
"\"endpoints\": [{\"url\":\"https://endpoint/\",\"weight\":\"\"}]}",
"non-integer weight"},
{"{\"max_age\":1, "
"\"endpoints\": [{\"url\":\"https://endpoint/\",\"weight\":-1}]}",
"negative weight"},
{"[{\"max_age\":1, \"endpoints\": [{\"url\":\"https://a/\"}]},"
"{\"max_age\":1, \"endpoints\": [{\"url\":\"https://b/\"}]}]",
"wrapped in list"}};
for (size_t i = 0; i < base::size(kInvalidHeaderTestCases); ++i) {
auto& test_case = kInvalidHeaderTestCases[i];
ParseHeader(kNik_, kUrl1_, test_case.header_value);
EXPECT_EQ(0u, cache()->GetEndpointCount())
<< "Invalid Report-To header (" << test_case.description << ": \""
<< test_case.header_value << "\") parsed as valid.";
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(0, mock_store()->StoredEndpointsCount());
EXPECT_EQ(0, mock_store()->StoredEndpointGroupsCount());
}
}
}
TEST_P(ReportingHeaderParserTest, Basic) {
std::vector<ReportingEndpoint::EndpointInfo> endpoints = {{kEndpoint1_}};
std::string header =
ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints));
ParseHeader(kNik_, kUrl1_, header);
EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT));
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_EQ(1u, cache()->GetEndpointCount());
ReportingEndpoint endpoint = FindEndpointInCache(kGroupKey11_, kEndpoint1_);
ASSERT_TRUE(endpoint);
EXPECT_EQ(kOrigin1_, endpoint.group_key.origin);
EXPECT_EQ(kGroup1_, endpoint.group_key.group_name);
EXPECT_EQ(kEndpoint1_, endpoint.info.url);
EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultPriority,
endpoint.info.priority);
EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultWeight,
endpoint.info.weight);
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(1, mock_store()->StoredEndpointsCount());
EXPECT_EQ(1, mock_store()->StoredEndpointGroupsCount());
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey11_, kEndpoint1_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
kGroupKey11_);
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
}
TEST_P(ReportingHeaderParserTest, PathAbsoluteURLEndpoint) {
std::string header =
"{\"group\": \"group1\", \"max_age\":1, \"endpoints\": "
"[{\"url\":\"/path-absolute-url\"}]}";
ParseHeader(kNik_, kUrl1_, header);
EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT));
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_EQ(1u, cache()->GetEndpointCount());
ReportingEndpoint endpoint =
FindEndpointInCache(kGroupKey11_, kEndpointPathAbsolute_);
ASSERT_TRUE(endpoint);
EXPECT_EQ(kOrigin1_, endpoint.group_key.origin);
EXPECT_EQ(kGroup1_, endpoint.group_key.group_name);
EXPECT_EQ(kEndpointPathAbsolute_, endpoint.info.url);
EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultPriority,
endpoint.info.priority);
EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultWeight,
endpoint.info.weight);
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(1, mock_store()->StoredEndpointsCount());
EXPECT_EQ(1, mock_store()->StoredEndpointGroupsCount());
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(
CommandType::ADD_REPORTING_ENDPOINT,
ReportingEndpoint(kGroupKey11_, ReportingEndpoint::EndpointInfo{
kEndpointPathAbsolute_}));
expected_commands.emplace_back(
CommandType::ADD_REPORTING_ENDPOINT_GROUP,
CachedReportingEndpointGroup(
kGroupKey11_, OriginSubdomains::DEFAULT /* irrelevant */,
base::Time() /* irrelevant */, base::Time() /* irrelevant */));
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
}
TEST_P(ReportingHeaderParserTest, OmittedGroupName) {
ReportingEndpointGroupKey kGroupKey(kNik_, kOrigin1_, "default");
std::vector<ReportingEndpoint::EndpointInfo> endpoints = {{kEndpoint1_}};
std::string header =
ConstructHeaderGroupString(MakeEndpointGroup(std::string(), endpoints));
ParseHeader(kNik_, kUrl1_, header);
EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(EndpointGroupExistsInCache(kGroupKey, OriginSubdomains::DEFAULT));
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_EQ(1u, cache()->GetEndpointCount());
ReportingEndpoint endpoint = FindEndpointInCache(kGroupKey, kEndpoint1_);
ASSERT_TRUE(endpoint);
EXPECT_EQ(kOrigin1_, endpoint.group_key.origin);
EXPECT_EQ("default", endpoint.group_key.group_name);
EXPECT_EQ(kEndpoint1_, endpoint.info.url);
EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultPriority,
endpoint.info.priority);
EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultWeight,
endpoint.info.weight);
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(1, mock_store()->StoredEndpointsCount());
EXPECT_EQ(1, mock_store()->StoredEndpointGroupsCount());
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey, kEndpoint1_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
kGroupKey);
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
}
TEST_P(ReportingHeaderParserTest, IncludeSubdomainsTrue) {
std::vector<ReportingEndpoint::EndpointInfo> endpoints = {{kEndpoint1_}};
std::string header = ConstructHeaderGroupString(
MakeEndpointGroup(kGroup1_, endpoints, OriginSubdomains::INCLUDE));
ParseHeader(kNik_, kUrl1_, header);
EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::INCLUDE));
EXPECT_EQ(1u, cache()->GetEndpointCount());
EXPECT_TRUE(EndpointExistsInCache(kGroupKey11_, kEndpoint1_));
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(1, mock_store()->StoredEndpointsCount());
EXPECT_EQ(1, mock_store()->StoredEndpointGroupsCount());
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey11_, kEndpoint1_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
kGroupKey11_);
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
}
TEST_P(ReportingHeaderParserTest, IncludeSubdomainsFalse) {
std::vector<ReportingEndpoint::EndpointInfo> endpoints = {{kEndpoint1_}};
std::string header = ConstructHeaderGroupString(
MakeEndpointGroup(kGroup1_, endpoints, OriginSubdomains::EXCLUDE),
false /* omit_defaults */);
ParseHeader(kNik_, kUrl1_, header);
EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::EXCLUDE));
EXPECT_EQ(1u, cache()->GetEndpointCount());
EXPECT_TRUE(EndpointExistsInCache(kGroupKey11_, kEndpoint1_));
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(1, mock_store()->StoredEndpointsCount());
EXPECT_EQ(1, mock_store()->StoredEndpointGroupsCount());
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey11_, kEndpoint1_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
kGroupKey11_);
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
}
TEST_P(ReportingHeaderParserTest, IncludeSubdomainsEtldRejected) {
ReportingEndpointGroupKey kGroupKey(kNik_, kOriginEtld_, kGroup1_);
std::vector<ReportingEndpoint::EndpointInfo> endpoints = {{kEndpoint1_}};
std::string header = ConstructHeaderGroupString(
MakeEndpointGroup(kGroup1_, endpoints, OriginSubdomains::INCLUDE));
ParseHeader(kNik_, kUrlEtld_, header);
EXPECT_EQ(0u, cache()->GetEndpointGroupCountForTesting());
EXPECT_FALSE(
EndpointGroupExistsInCache(kGroupKey, OriginSubdomains::INCLUDE));
EXPECT_EQ(0u, cache()->GetEndpointCount());
EXPECT_FALSE(EndpointExistsInCache(kGroupKey, kEndpoint1_));
}
TEST_P(ReportingHeaderParserTest, NonIncludeSubdomainsEtldAccepted) {
ReportingEndpointGroupKey kGroupKey(kNik_, kOriginEtld_, kGroup1_);
std::vector<ReportingEndpoint::EndpointInfo> endpoints = {{kEndpoint1_}};
std::string header = ConstructHeaderGroupString(
MakeEndpointGroup(kGroup1_, endpoints, OriginSubdomains::EXCLUDE));
ParseHeader(kNik_, kUrlEtld_, header);
EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(EndpointGroupExistsInCache(kGroupKey, OriginSubdomains::EXCLUDE));
EXPECT_EQ(1u, cache()->GetEndpointCount());
EXPECT_TRUE(EndpointExistsInCache(kGroupKey, kEndpoint1_));
}
TEST_P(ReportingHeaderParserTest, IncludeSubdomainsNotBoolean) {
std::string header =
"{\"group\": \"" + kGroup1_ +
"\", "
"\"max_age\":86400, \"include_subdomains\": \"NotABoolean\", "
"\"endpoints\": [{\"url\":\"" +
kEndpoint1_.spec() + "\"}]}";
ParseHeader(kNik_, kUrl1_, header);
EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT));
EXPECT_EQ(1u, cache()->GetEndpointCount());
EXPECT_TRUE(EndpointExistsInCache(kGroupKey11_, kEndpoint1_));
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(1, mock_store()->StoredEndpointsCount());
EXPECT_EQ(1, mock_store()->StoredEndpointGroupsCount());
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey11_, kEndpoint1_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
kGroupKey11_);
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
}
TEST_P(ReportingHeaderParserTest, NonDefaultPriority) {
const int kNonDefaultPriority = 10;
std::vector<ReportingEndpoint::EndpointInfo> endpoints = {
{kEndpoint1_, kNonDefaultPriority}};
std::string header =
ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints));
ParseHeader(kNik_, kUrl1_, header);
EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT));
EXPECT_EQ(1u, cache()->GetEndpointCount());
ReportingEndpoint endpoint = FindEndpointInCache(kGroupKey11_, kEndpoint1_);
ASSERT_TRUE(endpoint);
EXPECT_EQ(kNonDefaultPriority, endpoint.info.priority);
EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultWeight,
endpoint.info.weight);
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(1, mock_store()->StoredEndpointsCount());
EXPECT_EQ(1, mock_store()->StoredEndpointGroupsCount());
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey11_, kEndpoint1_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
kGroupKey11_);
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
}
TEST_P(ReportingHeaderParserTest, NonDefaultWeight) {
const int kNonDefaultWeight = 10;
std::vector<ReportingEndpoint::EndpointInfo> endpoints = {
{kEndpoint1_, ReportingEndpoint::EndpointInfo::kDefaultPriority,
kNonDefaultWeight}};
std::string header =
ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints));
ParseHeader(kNik_, kUrl1_, header);
EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT));
EXPECT_EQ(1u, cache()->GetEndpointCount());
ReportingEndpoint endpoint = FindEndpointInCache(kGroupKey11_, kEndpoint1_);
ASSERT_TRUE(endpoint);
EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultPriority,
endpoint.info.priority);
EXPECT_EQ(kNonDefaultWeight, endpoint.info.weight);
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(1, mock_store()->StoredEndpointsCount());
EXPECT_EQ(1, mock_store()->StoredEndpointGroupsCount());
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey11_, kEndpoint1_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
kGroupKey11_);
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
}
TEST_P(ReportingHeaderParserTest, MaxAge) {
const int kMaxAgeSecs = 100;
base::TimeDelta ttl = base::TimeDelta::FromSeconds(kMaxAgeSecs);
base::Time expires = clock()->Now() + ttl;
std::vector<ReportingEndpoint::EndpointInfo> endpoints = {{kEndpoint1_}};
std::string header = ConstructHeaderGroupString(
MakeEndpointGroup(kGroup1_, endpoints, OriginSubdomains::DEFAULT, ttl));
ParseHeader(kNik_, kUrl1_, header);
EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(EndpointGroupExistsInCache(kGroupKey11_,
OriginSubdomains::DEFAULT, expires));
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(1, mock_store()->StoredEndpointsCount());
EXPECT_EQ(1, mock_store()->StoredEndpointGroupsCount());
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey11_, kEndpoint1_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
kGroupKey11_);
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
}
TEST_P(ReportingHeaderParserTest, MultipleEndpointsSameGroup) {
std::vector<ReportingEndpoint::EndpointInfo> endpoints = {{kEndpoint1_},
{kEndpoint2_}};
std::string header =
ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints));
ParseHeader(kNik_, kUrl1_, header);
EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT));
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_EQ(2u, cache()->GetEndpointCount());
ReportingEndpoint endpoint = FindEndpointInCache(kGroupKey11_, kEndpoint1_);
ASSERT_TRUE(endpoint);
EXPECT_EQ(kOrigin1_, endpoint.group_key.origin);
EXPECT_EQ(kGroup1_, endpoint.group_key.group_name);
EXPECT_EQ(kEndpoint1_, endpoint.info.url);
EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultPriority,
endpoint.info.priority);
EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultWeight,
endpoint.info.weight);
ReportingEndpoint endpoint2 = FindEndpointInCache(kGroupKey11_, kEndpoint2_);
ASSERT_TRUE(endpoint2);
EXPECT_EQ(kOrigin1_, endpoint2.group_key.origin);
EXPECT_EQ(kGroup1_, endpoint2.group_key.group_name);
EXPECT_EQ(kEndpoint2_, endpoint2.info.url);
EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultPriority,
endpoint2.info.priority);
EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultWeight,
endpoint2.info.weight);
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(2, mock_store()->StoredEndpointsCount());
EXPECT_EQ(1, mock_store()->StoredEndpointGroupsCount());
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey11_, kEndpoint1_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey11_, kEndpoint2_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
kGroupKey11_);
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
}
TEST_P(ReportingHeaderParserTest, MultipleEndpointsDifferentGroups) {
std::vector<ReportingEndpoint::EndpointInfo> endpoints1 = {{kEndpoint1_}};
std::vector<ReportingEndpoint::EndpointInfo> endpoints2 = {{kEndpoint1_}};
std::string header =
ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints1)) +
", " +
ConstructHeaderGroupString(MakeEndpointGroup(kGroup2_, endpoints2));
ParseHeader(kNik_, kUrl1_, header);
EXPECT_EQ(2u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT));
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey12_, OriginSubdomains::DEFAULT));
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_EQ(2u, cache()->GetEndpointCount());
ReportingEndpoint endpoint = FindEndpointInCache(kGroupKey11_, kEndpoint1_);
ASSERT_TRUE(endpoint);
EXPECT_EQ(kOrigin1_, endpoint.group_key.origin);
EXPECT_EQ(kGroup1_, endpoint.group_key.group_name);
EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultPriority,
endpoint.info.priority);
EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultWeight,
endpoint.info.weight);
ReportingEndpoint endpoint2 = FindEndpointInCache(kGroupKey12_, kEndpoint1_);
ASSERT_TRUE(endpoint2);
EXPECT_EQ(kOrigin1_, endpoint2.group_key.origin);
EXPECT_EQ(kGroup2_, endpoint2.group_key.group_name);
EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultPriority,
endpoint2.info.priority);
EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultWeight,
endpoint2.info.weight);
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(2, mock_store()->StoredEndpointsCount());
EXPECT_EQ(2, mock_store()->StoredEndpointGroupsCount());
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey11_, kEndpoint1_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey12_, kEndpoint1_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
kGroupKey11_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
kGroupKey12_);
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
}
TEST_P(ReportingHeaderParserTest, MultipleHeadersFromDifferentOrigins) {
// First origin sets a header with two endpoints in the same group.
std::vector<ReportingEndpoint::EndpointInfo> endpoints1 = {{kEndpoint1_},
{kEndpoint2_}};
std::string header1 =
ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints1));
ParseHeader(kNik_, kUrl1_, header1);
// Second origin has two endpoint groups.
std::vector<ReportingEndpoint::EndpointInfo> endpoints2 = {{kEndpoint1_}};
std::vector<ReportingEndpoint::EndpointInfo> endpoints3 = {{kEndpoint2_}};
std::string header2 =
ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints2)) +
", " +
ConstructHeaderGroupString(MakeEndpointGroup(kGroup2_, endpoints3));
ParseHeader(kNik_, kUrl2_, header2);
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin2_));
EXPECT_EQ(3u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT));
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey21_, OriginSubdomains::DEFAULT));
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey22_, OriginSubdomains::DEFAULT));
EXPECT_EQ(4u, cache()->GetEndpointCount());
EXPECT_TRUE(FindEndpointInCache(kGroupKey11_, kEndpoint1_));
EXPECT_TRUE(FindEndpointInCache(kGroupKey11_, kEndpoint2_));
EXPECT_TRUE(FindEndpointInCache(kGroupKey21_, kEndpoint1_));
EXPECT_TRUE(FindEndpointInCache(kGroupKey22_, kEndpoint2_));
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(4, mock_store()->StoredEndpointsCount());
EXPECT_EQ(3, mock_store()->StoredEndpointGroupsCount());
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey11_, kEndpoint1_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey11_, kEndpoint2_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey21_, kEndpoint1_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey22_, kEndpoint2_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
kGroupKey11_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
kGroupKey21_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
kGroupKey22_);
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
}
// Test that each combination of NIK, origin, and group name is considered
// distinct.
// See also: ReportingCacheTest.ClientsKeyedByEndpointGroupKey
TEST_P(ReportingHeaderParserTest, EndpointGroupKey) {
// Raise the endpoint limits for this test.
ReportingPolicy policy;
policy.max_endpoints_per_origin = 5; // This test should use 4.
policy.max_endpoint_count = 20; // This test should use 16.
UsePolicy(policy);
std::vector<ReportingEndpoint::EndpointInfo> endpoints1 = {{kEndpoint1_},
{kEndpoint2_}};
std::string header1 =
ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints1)) +
", " +
ConstructHeaderGroupString(MakeEndpointGroup(kGroup2_, endpoints1));
const ReportingEndpointGroupKey kOtherGroupKey11 =
ReportingEndpointGroupKey(kOtherNik_, kOrigin1_, kGroup1_);
const ReportingEndpointGroupKey kOtherGroupKey21 =
ReportingEndpointGroupKey(kOtherNik_, kOrigin2_, kGroup1_);
const ReportingEndpointGroupKey kOtherGroupKey12 =
ReportingEndpointGroupKey(kOtherNik_, kOrigin1_, kGroup2_);
const ReportingEndpointGroupKey kOtherGroupKey22 =
ReportingEndpointGroupKey(kOtherNik_, kOrigin2_, kGroup2_);
const struct {
NetworkIsolationKey network_isolation_key;
GURL url;
ReportingEndpointGroupKey group1_key;
ReportingEndpointGroupKey group2_key;
} kHeaderSources[] = {
{kNik_, kUrl1_, kGroupKey11_, kGroupKey12_},
{kNik_, kUrl2_, kGroupKey21_, kGroupKey22_},
{kOtherNik_, kUrl1_, kOtherGroupKey11, kOtherGroupKey12},
{kOtherNik_, kUrl2_, kOtherGroupKey21, kOtherGroupKey22},
};
size_t endpoint_group_count = 0u;
size_t endpoint_count = 0u;
MockPersistentReportingStore::CommandList expected_commands;
// Set 2 endpoints in each of 2 groups for each of 2x2 combinations of
// (NIK, origin).
for (const auto& source : kHeaderSources) {
// Verify pre-parsing state
EXPECT_FALSE(FindEndpointInCache(source.group1_key, kEndpoint1_));
EXPECT_FALSE(FindEndpointInCache(source.group1_key, kEndpoint2_));
EXPECT_FALSE(FindEndpointInCache(source.group2_key, kEndpoint1_));
EXPECT_FALSE(FindEndpointInCache(source.group2_key, kEndpoint2_));
EXPECT_FALSE(EndpointGroupExistsInCache(source.group1_key,
OriginSubdomains::DEFAULT));
EXPECT_FALSE(EndpointGroupExistsInCache(source.group2_key,
OriginSubdomains::DEFAULT));
ParseHeader(source.network_isolation_key, source.url, header1);
endpoint_group_count += 2u;
endpoint_count += 4u;
EXPECT_EQ(endpoint_group_count, cache()->GetEndpointGroupCountForTesting());
EXPECT_EQ(endpoint_count, cache()->GetEndpointCount());
// Verify post-parsing state
EXPECT_TRUE(FindEndpointInCache(source.group1_key, kEndpoint1_));
EXPECT_TRUE(FindEndpointInCache(source.group1_key, kEndpoint2_));
EXPECT_TRUE(FindEndpointInCache(source.group2_key, kEndpoint1_));
EXPECT_TRUE(FindEndpointInCache(source.group2_key, kEndpoint2_));
EXPECT_TRUE(EndpointGroupExistsInCache(source.group1_key,
OriginSubdomains::DEFAULT));
EXPECT_TRUE(EndpointGroupExistsInCache(source.group2_key,
OriginSubdomains::DEFAULT));
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(static_cast<int>(endpoint_count),
mock_store()->StoredEndpointsCount());
EXPECT_EQ(static_cast<int>(endpoint_group_count),
mock_store()->StoredEndpointGroupsCount());
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
source.group1_key, kEndpoint1_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
source.group1_key, kEndpoint2_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
source.group1_key);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
source.group2_key, kEndpoint1_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
source.group2_key, kEndpoint2_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
source.group2_key);
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
}
// Check that expected data is present in the ReportingCache at the end.
for (const auto& source : kHeaderSources) {
EXPECT_TRUE(FindEndpointInCache(source.group1_key, kEndpoint1_));
EXPECT_TRUE(FindEndpointInCache(source.group1_key, kEndpoint2_));
EXPECT_TRUE(FindEndpointInCache(source.group2_key, kEndpoint1_));
EXPECT_TRUE(FindEndpointInCache(source.group2_key, kEndpoint2_));
EXPECT_TRUE(EndpointGroupExistsInCache(source.group1_key,
OriginSubdomains::DEFAULT));
EXPECT_TRUE(EndpointGroupExistsInCache(source.group2_key,
OriginSubdomains::DEFAULT));
EXPECT_TRUE(cache()->ClientExistsForTesting(
source.network_isolation_key, url::Origin::Create(source.url)));
}
// Test updating existing configurations
// This removes endpoint 1, updates the priority of endpoint 2, and adds
// endpoint 3.
std::vector<ReportingEndpoint::EndpointInfo> endpoints2 = {{kEndpoint2_, 2},
{kEndpoint3_}};
// Removes group 1, updates include_subdomains for group 2.
std::string header2 = ConstructHeaderGroupString(
MakeEndpointGroup(kGroup2_, endpoints2, OriginSubdomains::INCLUDE));
for (const auto& source : kHeaderSources) {
// Verify pre-update state
EXPECT_TRUE(EndpointGroupExistsInCache(source.group1_key,
OriginSubdomains::DEFAULT));
EXPECT_TRUE(EndpointGroupExistsInCache(source.group2_key,
OriginSubdomains::DEFAULT));
EXPECT_TRUE(FindEndpointInCache(source.group2_key, kEndpoint1_));
ReportingEndpoint endpoint =
FindEndpointInCache(source.group2_key, kEndpoint2_);
EXPECT_TRUE(endpoint);
EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultPriority,
endpoint.info.priority);
EXPECT_FALSE(FindEndpointInCache(source.group2_key, kEndpoint3_));
ParseHeader(source.network_isolation_key, source.url, header2);
endpoint_group_count--;
endpoint_count -= 2;
EXPECT_EQ(endpoint_group_count, cache()->GetEndpointGroupCountForTesting());
EXPECT_EQ(endpoint_count, cache()->GetEndpointCount());
// Verify post-update state
EXPECT_FALSE(EndpointGroupExistsInCache(source.group1_key,
OriginSubdomains::DEFAULT));
EXPECT_TRUE(EndpointGroupExistsInCache(source.group2_key,
OriginSubdomains::INCLUDE));
EXPECT_FALSE(FindEndpointInCache(source.group2_key, kEndpoint1_));
endpoint = FindEndpointInCache(source.group2_key, kEndpoint2_);
EXPECT_TRUE(endpoint);
EXPECT_EQ(2, endpoint.info.priority);
EXPECT_TRUE(FindEndpointInCache(source.group2_key, kEndpoint3_));
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(static_cast<int>(endpoint_count),
mock_store()->StoredEndpointsCount());
EXPECT_EQ(static_cast<int>(endpoint_group_count),
mock_store()->StoredEndpointGroupsCount());
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
source.group1_key, kEndpoint1_);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
source.group1_key, kEndpoint2_);
expected_commands.emplace_back(
CommandType::DELETE_REPORTING_ENDPOINT_GROUP, source.group1_key);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
source.group2_key, kEndpoint1_);
expected_commands.emplace_back(
CommandType::UPDATE_REPORTING_ENDPOINT_DETAILS, source.group2_key,
kEndpoint2_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
source.group2_key, kEndpoint3_);
expected_commands.emplace_back(
CommandType::UPDATE_REPORTING_ENDPOINT_GROUP_DETAILS,
source.group2_key);
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
}
// Check that expected data is present in the ReportingCache at the end.
for (const auto& source : kHeaderSources) {
EXPECT_FALSE(FindEndpointInCache(source.group1_key, kEndpoint1_));
EXPECT_FALSE(FindEndpointInCache(source.group1_key, kEndpoint2_));
EXPECT_FALSE(FindEndpointInCache(source.group2_key, kEndpoint1_));
EXPECT_TRUE(FindEndpointInCache(source.group2_key, kEndpoint2_));
EXPECT_TRUE(FindEndpointInCache(source.group2_key, kEndpoint3_));
EXPECT_FALSE(EndpointGroupExistsInCache(source.group1_key,
OriginSubdomains::DEFAULT));
EXPECT_TRUE(EndpointGroupExistsInCache(source.group2_key,
OriginSubdomains::INCLUDE));
EXPECT_TRUE(cache()->ClientExistsForTesting(
source.network_isolation_key, url::Origin::Create(source.url)));
}
}
TEST_P(ReportingHeaderParserTest,
HeaderErroneouslyContainsMultipleGroupsOfSameName) {
// Add a preexisting header to test that a header with multiple groups of the
// same name is treated as if it specified a single group with the combined
// set of specified endpoints. In particular, it must overwrite/update any
// preexisting group all at once. See https://crbug.com/1116529.
std::vector<ReportingEndpoint::EndpointInfo> preexisting = {{kEndpoint1_}};
std::string preexisting_header =
ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, preexisting));
ParseHeader(kNik_, kUrl1_, preexisting_header);
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT));
EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_EQ(1u, cache()->GetEndpointCount());
ReportingEndpoint endpoint = FindEndpointInCache(kGroupKey11_, kEndpoint1_);
ASSERT_TRUE(endpoint);
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(1, mock_store()->StoredEndpointsCount());
EXPECT_EQ(1, mock_store()->StoredEndpointGroupsCount());
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey11_, kEndpoint1_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
kGroupKey11_);
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
// Reset commands so we can check that the next part, adding the header with
// duplicate groups, does not cause clearing of preexisting endpoints twice.
mock_store()->ClearCommands();
}
std::vector<ReportingEndpoint::EndpointInfo> endpoints1 = {{kEndpoint1_}};
std::vector<ReportingEndpoint::EndpointInfo> endpoints2 = {{kEndpoint2_}};
std::string duplicate_groups_header =
ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints1)) +
", " +
ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints2));
ParseHeader(kNik_, kUrl1_, duplicate_groups_header);
// Result is as if they set the two groups with the same name as one group.
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT));
EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_EQ(2u, cache()->GetEndpointCount());
ReportingEndpoint endpoint1 = FindEndpointInCache(kGroupKey11_, kEndpoint1_);
ASSERT_TRUE(endpoint);
EXPECT_EQ(kOrigin1_, endpoint.group_key.origin);
EXPECT_EQ(kGroup1_, endpoint.group_key.group_name);
EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultPriority,
endpoint.info.priority);
EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultWeight,
endpoint.info.weight);
ReportingEndpoint endpoint2 = FindEndpointInCache(kGroupKey11_, kEndpoint2_);
ASSERT_TRUE(endpoint2);
EXPECT_EQ(kOrigin1_, endpoint2.group_key.origin);
EXPECT_EQ(kGroup1_, endpoint2.group_key.group_name);
EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultPriority,
endpoint2.info.priority);
EXPECT_EQ(ReportingEndpoint::EndpointInfo::kDefaultWeight,
endpoint2.info.weight);
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(2, mock_store()->StoredEndpointsCount());
EXPECT_EQ(1, mock_store()->StoredEndpointGroupsCount());
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(
CommandType::UPDATE_REPORTING_ENDPOINT_DETAILS, kGroupKey11_,
kEndpoint1_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey11_, kEndpoint2_);
expected_commands.emplace_back(
CommandType::UPDATE_REPORTING_ENDPOINT_GROUP_DETAILS, kGroupKey11_);
MockPersistentReportingStore::CommandList actual_commands =
mock_store()->GetAllCommands();
EXPECT_THAT(actual_commands, testing::IsSupersetOf(expected_commands));
for (const auto& command : actual_commands) {
EXPECT_NE(CommandType::DELETE_REPORTING_ENDPOINT, command.type);
EXPECT_NE(CommandType::DELETE_REPORTING_ENDPOINT_GROUP, command.type);
// The endpoint with URL kEndpoint1_ is only ever updated, not added anew.
EXPECT_NE(
MockPersistentReportingStore::Command(
CommandType::ADD_REPORTING_ENDPOINT, kGroupKey11_, kEndpoint1_),
command);
// The group is only ever updated, not added anew.
EXPECT_NE(MockPersistentReportingStore::Command(
CommandType::ADD_REPORTING_ENDPOINT_GROUP, kGroupKey11_),
command);
}
}
}
TEST_P(ReportingHeaderParserTest,
HeaderErroneouslyContainsGroupsWithRedundantEndpoints) {
std::vector<ReportingEndpoint::EndpointInfo> endpoints = {{kEndpoint1_},
{kEndpoint1_}};
std::string header =
ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints));
ParseHeader(kNik_, kUrl1_, header);
// We should dedupe the identical endpoint URLs.
EXPECT_EQ(1u, cache()->GetEndpointCount());
ASSERT_TRUE(FindEndpointInCache(kGroupKey11_, kEndpoint1_));
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT));
EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
}
TEST_P(ReportingHeaderParserTest,
HeaderErroneouslyContainsMultipleGroupsOfSameNameAndEndpoints) {
std::vector<ReportingEndpoint::EndpointInfo> endpoints = {{kEndpoint1_}};
std::string header =
ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints)) +
", " + ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints));
ParseHeader(kNik_, kUrl1_, header);
// We should dedupe the identical endpoint URLs, even when they're in
// different group.
EXPECT_EQ(1u, cache()->GetEndpointCount());
ASSERT_TRUE(FindEndpointInCache(kGroupKey11_, kEndpoint1_));
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT));
EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
}
TEST_P(ReportingHeaderParserTest,
HeaderErroneouslyContainsGroupsOfSameNameAndOverlappingEndpoints) {
std::vector<ReportingEndpoint::EndpointInfo> endpoints1 = {{kEndpoint1_},
{kEndpoint2_}};
std::vector<ReportingEndpoint::EndpointInfo> endpoints2 = {{kEndpoint1_},
{kEndpoint3_}};
std::string header =
ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints1)) +
", " +
ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints2));
ParseHeader(kNik_, kUrl1_, header);
// We should dedupe the identical endpoint URLs, even when they're in
// different group.
EXPECT_EQ(3u, cache()->GetEndpointCount());
ASSERT_TRUE(FindEndpointInCache(kGroupKey11_, kEndpoint1_));
ASSERT_TRUE(FindEndpointInCache(kGroupKey11_, kEndpoint2_));
ASSERT_TRUE(FindEndpointInCache(kGroupKey11_, kEndpoint3_));
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT));
EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
}
TEST_P(ReportingHeaderParserTest, OverwriteOldHeader) {
// First, the origin sets a header with two endpoints in the same group.
std::vector<ReportingEndpoint::EndpointInfo> endpoints1 = {
{kEndpoint1_, 10 /* priority */}, {kEndpoint2_}};
std::string header1 =
ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints1));
ParseHeader(kNik_, kUrl1_, header1);
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT));
EXPECT_EQ(2u, cache()->GetEndpointCount());
EXPECT_TRUE(FindEndpointInCache(kGroupKey11_, kEndpoint1_));
EXPECT_TRUE(FindEndpointInCache(kGroupKey11_, kEndpoint2_));
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(2,
mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT));
EXPECT_EQ(1, mock_store()->CountCommands(
CommandType::ADD_REPORTING_ENDPOINT_GROUP));
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey11_, kEndpoint1_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey11_, kEndpoint2_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
kGroupKey11_);
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
// Second header from the same origin should overwrite the previous one.
std::vector<ReportingEndpoint::EndpointInfo> endpoints2 = {
// This endpoint should update the priority of the existing one.
{kEndpoint1_, 20 /* priority */}};
// The second endpoint in this group will be deleted.
// This group is new.
std::vector<ReportingEndpoint::EndpointInfo> endpoints3 = {{kEndpoint2_}};
std::string header2 =
ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints2)) +
", " +
ConstructHeaderGroupString(MakeEndpointGroup(kGroup2_, endpoints3));
ParseHeader(kNik_, kUrl1_, header2);
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT));
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey12_, OriginSubdomains::DEFAULT));
EXPECT_EQ(2u, cache()->GetEndpointCount());
EXPECT_TRUE(FindEndpointInCache(kGroupKey11_, kEndpoint1_));
EXPECT_EQ(20, FindEndpointInCache(kGroupKey11_, kEndpoint1_).info.priority);
EXPECT_FALSE(FindEndpointInCache(kGroupKey11_, kEndpoint2_));
EXPECT_TRUE(FindEndpointInCache(kGroupKey12_, kEndpoint2_));
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(2 + 1,
mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT));
EXPECT_EQ(1 + 1, mock_store()->CountCommands(
CommandType::ADD_REPORTING_ENDPOINT_GROUP));
EXPECT_EQ(
1, mock_store()->CountCommands(CommandType::DELETE_REPORTING_ENDPOINT));
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey12_, kEndpoint2_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
kGroupKey12_);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
kGroupKey11_, kEndpoint2_);
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
}
TEST_P(ReportingHeaderParserTest, OverwriteOldHeaderWithCompletelyNew) {
ReportingEndpointGroupKey kGroupKey1(kNik_, kOrigin1_, "1");
ReportingEndpointGroupKey kGroupKey2(kNik_, kOrigin1_, "2");
ReportingEndpointGroupKey kGroupKey3(kNik_, kOrigin1_, "3");
ReportingEndpointGroupKey kGroupKey4(kNik_, kOrigin1_, "4");
ReportingEndpointGroupKey kGroupKey5(kNik_, kOrigin1_, "5");
std::vector<ReportingEndpoint::EndpointInfo> endpoints1_1 = {{MakeURL(10)},
{MakeURL(11)}};
std::vector<ReportingEndpoint::EndpointInfo> endpoints2_1 = {{MakeURL(20)},
{MakeURL(21)}};
std::vector<ReportingEndpoint::EndpointInfo> endpoints3_1 = {{MakeURL(30)},
{MakeURL(31)}};
std::string header1 =
ConstructHeaderGroupString(MakeEndpointGroup("1", endpoints1_1)) + ", " +
ConstructHeaderGroupString(MakeEndpointGroup("2", endpoints2_1)) + ", " +
ConstructHeaderGroupString(MakeEndpointGroup("3", endpoints3_1));
ParseHeader(kNik_, kUrl1_, header1);
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_EQ(3u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey1, OriginSubdomains::DEFAULT));
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey2, OriginSubdomains::DEFAULT));
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey3, OriginSubdomains::DEFAULT));
EXPECT_EQ(6u, cache()->GetEndpointCount());
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(6,
mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT));
EXPECT_EQ(3, mock_store()->CountCommands(
CommandType::ADD_REPORTING_ENDPOINT_GROUP));
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey1, endpoints1_1[0].url);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey1, endpoints1_1[1].url);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey2, endpoints2_1[0].url);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey2, endpoints2_1[1].url);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey3, endpoints3_1[0].url);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey3, endpoints3_1[1].url);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
kGroupKey1);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
kGroupKey2);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
kGroupKey3);
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
// Replace endpoints in each group with completely new endpoints.
std::vector<ReportingEndpoint::EndpointInfo> endpoints1_2 = {{MakeURL(12)}};
std::vector<ReportingEndpoint::EndpointInfo> endpoints2_2 = {{MakeURL(22)}};
std::vector<ReportingEndpoint::EndpointInfo> endpoints3_2 = {{MakeURL(32)}};
std::string header2 =
ConstructHeaderGroupString(MakeEndpointGroup("1", endpoints1_2)) + ", " +
ConstructHeaderGroupString(MakeEndpointGroup("2", endpoints2_2)) + ", " +
ConstructHeaderGroupString(MakeEndpointGroup("3", endpoints3_2));
ParseHeader(kNik_, kUrl1_, header2);
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_EQ(3u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey1, OriginSubdomains::DEFAULT));
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey2, OriginSubdomains::DEFAULT));
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey3, OriginSubdomains::DEFAULT));
EXPECT_EQ(3u, cache()->GetEndpointCount());
EXPECT_TRUE(FindEndpointInCache(kGroupKey1, MakeURL(12)));
EXPECT_FALSE(FindEndpointInCache(kGroupKey1, MakeURL(10)));
EXPECT_FALSE(FindEndpointInCache(kGroupKey1, MakeURL(11)));
EXPECT_TRUE(FindEndpointInCache(kGroupKey2, MakeURL(22)));
EXPECT_FALSE(FindEndpointInCache(kGroupKey2, MakeURL(20)));
EXPECT_FALSE(FindEndpointInCache(kGroupKey2, MakeURL(21)));
EXPECT_TRUE(FindEndpointInCache(kGroupKey3, MakeURL(32)));
EXPECT_FALSE(FindEndpointInCache(kGroupKey3, MakeURL(30)));
EXPECT_FALSE(FindEndpointInCache(kGroupKey3, MakeURL(31)));
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(6 + 3,
mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT));
EXPECT_EQ(3, mock_store()->CountCommands(
CommandType::ADD_REPORTING_ENDPOINT_GROUP));
EXPECT_EQ(
6, mock_store()->CountCommands(CommandType::DELETE_REPORTING_ENDPOINT));
EXPECT_EQ(0, mock_store()->CountCommands(
CommandType::DELETE_REPORTING_ENDPOINT_GROUP));
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey1, endpoints1_2[0].url);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey2, endpoints2_2[0].url);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey3, endpoints3_2[0].url);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
kGroupKey1, endpoints1_1[0].url);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
kGroupKey1, endpoints1_1[1].url);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
kGroupKey2, endpoints2_1[0].url);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
kGroupKey2, endpoints2_1[1].url);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
kGroupKey3, endpoints3_1[0].url);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
kGroupKey3, endpoints3_1[1].url);
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
// Replace all the groups with completely new groups.
std::vector<ReportingEndpoint::EndpointInfo> endpoints4_3 = {{MakeURL(40)}};
std::vector<ReportingEndpoint::EndpointInfo> endpoints5_3 = {{MakeURL(50)}};
std::string header3 =
ConstructHeaderGroupString(MakeEndpointGroup("4", endpoints4_3)) + ", " +
ConstructHeaderGroupString(MakeEndpointGroup("5", endpoints5_3));
ParseHeader(kNik_, kUrl1_, header3);
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_EQ(2u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey4, OriginSubdomains::DEFAULT));
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey4, OriginSubdomains::DEFAULT));
EXPECT_FALSE(
EndpointGroupExistsInCache(kGroupKey1, OriginSubdomains::DEFAULT));
EXPECT_FALSE(
EndpointGroupExistsInCache(kGroupKey2, OriginSubdomains::DEFAULT));
EXPECT_FALSE(
EndpointGroupExistsInCache(kGroupKey3, OriginSubdomains::DEFAULT));
EXPECT_EQ(2u, cache()->GetEndpointCount());
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(6 + 3 + 2,
mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT));
EXPECT_EQ(3 + 2, mock_store()->CountCommands(
CommandType::ADD_REPORTING_ENDPOINT_GROUP));
EXPECT_EQ(6 + 3, mock_store()->CountCommands(
CommandType::DELETE_REPORTING_ENDPOINT));
EXPECT_EQ(3, mock_store()->CountCommands(
CommandType::DELETE_REPORTING_ENDPOINT_GROUP));
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey4, endpoints4_3[0].url);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey5, endpoints5_3[0].url);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
kGroupKey4);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
kGroupKey5);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
kGroupKey1, endpoints1_2[0].url);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
kGroupKey2, endpoints2_2[0].url);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
kGroupKey3, endpoints3_2[0].url);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT_GROUP,
kGroupKey1);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT_GROUP,
kGroupKey2);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT_GROUP,
kGroupKey3);
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
}
TEST_P(ReportingHeaderParserTest, ZeroMaxAgeRemovesEndpointGroup) {
// Without a pre-existing client, max_age: 0 should do nothing.
ASSERT_EQ(0u, cache()->GetEndpointCount());
ParseHeader(kNik_, kUrl1_,
"{\"endpoints\":[{\"url\":\"" + kEndpoint1_.spec() +
"\"}],\"max_age\":0}");
EXPECT_EQ(0u, cache()->GetEndpointCount());
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(0,
mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT));
EXPECT_EQ(0, mock_store()->CountCommands(
CommandType::ADD_REPORTING_ENDPOINT_GROUP));
}
// Set a header with two endpoint groups.
std::vector<ReportingEndpoint::EndpointInfo> endpoints1 = {{kEndpoint1_}};
std::vector<ReportingEndpoint::EndpointInfo> endpoints2 = {{kEndpoint2_}};
std::string header1 =
ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints1)) +
", " +
ConstructHeaderGroupString(MakeEndpointGroup(kGroup2_, endpoints2));
ParseHeader(kNik_, kUrl1_, header1);
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_EQ(2u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT));
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey12_, OriginSubdomains::DEFAULT));
EXPECT_EQ(2u, cache()->GetEndpointCount());
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(2,
mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT));
EXPECT_EQ(2, mock_store()->CountCommands(
CommandType::ADD_REPORTING_ENDPOINT_GROUP));
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey11_, kEndpoint1_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey12_, kEndpoint2_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
kGroupKey11_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
kGroupKey12_);
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
// Set another header with max_age: 0 to delete one of the groups.
std::string header2 = ConstructHeaderGroupString(MakeEndpointGroup(
kGroup1_, endpoints1, OriginSubdomains::DEFAULT,
base::TimeDelta::FromSeconds(0))) +
", " +
ConstructHeaderGroupString(MakeEndpointGroup(
kGroup2_, endpoints2)); // Other group stays.
ParseHeader(kNik_, kUrl1_, header2);
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting());
// Group was deleted.
EXPECT_FALSE(
EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT));
// Other group remains in the cache.
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey12_, OriginSubdomains::DEFAULT));
EXPECT_EQ(1u, cache()->GetEndpointCount());
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(2,
mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT));
EXPECT_EQ(2, mock_store()->CountCommands(
CommandType::ADD_REPORTING_ENDPOINT_GROUP));
EXPECT_EQ(
1, mock_store()->CountCommands(CommandType::DELETE_REPORTING_ENDPOINT));
EXPECT_EQ(1, mock_store()->CountCommands(
CommandType::DELETE_REPORTING_ENDPOINT_GROUP));
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
kGroupKey11_, kEndpoint1_);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT_GROUP,
kGroupKey11_);
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
// Set another header with max_age: 0 to delete the other group. (Should work
// even if the endpoints field is an empty list.)
std::string header3 = ConstructHeaderGroupString(MakeEndpointGroup(
kGroup2_, std::vector<ReportingEndpoint::EndpointInfo>(),
OriginSubdomains::DEFAULT, base::TimeDelta::FromSeconds(0)));
ParseHeader(kNik_, kUrl1_, header3);
// Deletion of the last remaining group also deletes the client for this
// origin.
EXPECT_FALSE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_EQ(0u, cache()->GetEndpointGroupCountForTesting());
EXPECT_EQ(0u, cache()->GetEndpointCount());
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(2,
mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT));
EXPECT_EQ(2, mock_store()->CountCommands(
CommandType::ADD_REPORTING_ENDPOINT_GROUP));
EXPECT_EQ(1 + 1, mock_store()->CountCommands(
CommandType::DELETE_REPORTING_ENDPOINT));
EXPECT_EQ(1 + 1, mock_store()->CountCommands(
CommandType::DELETE_REPORTING_ENDPOINT_GROUP));
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
kGroupKey12_, kEndpoint2_);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT_GROUP,
kGroupKey12_);
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
}
// Invalid advertisements that parse as JSON should remove an endpoint group,
// while those that don't are ignored.
TEST_P(ReportingHeaderParserTest, InvalidAdvertisementRemovesEndpointGroup) {
std::string invalid_non_json_header = "Goats should wear hats.";
std::string invalid_json_header = "\"Goats should wear hats.\"";
// Without a pre-existing client, neither invalid header does anything.
ASSERT_EQ(0u, cache()->GetEndpointCount());
ParseHeader(kNik_, kUrl1_, invalid_non_json_header);
EXPECT_EQ(0u, cache()->GetEndpointCount());
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(0,
mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT));
EXPECT_EQ(0, mock_store()->CountCommands(
CommandType::ADD_REPORTING_ENDPOINT_GROUP));
}
ASSERT_EQ(0u, cache()->GetEndpointCount());
ParseHeader(kNik_, kUrl1_, invalid_json_header);
EXPECT_EQ(0u, cache()->GetEndpointCount());
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(0,
mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT));
EXPECT_EQ(0, mock_store()->CountCommands(
CommandType::ADD_REPORTING_ENDPOINT_GROUP));
}
// Set a header with two endpoint groups.
std::vector<ReportingEndpoint::EndpointInfo> endpoints1 = {{kEndpoint1_}};
std::vector<ReportingEndpoint::EndpointInfo> endpoints2 = {{kEndpoint2_}};
std::string header1 =
ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints1)) +
", " +
ConstructHeaderGroupString(MakeEndpointGroup(kGroup2_, endpoints2));
ParseHeader(kNik_, kUrl1_, header1);
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_EQ(2u, cache()->GetEndpointGroupCountForTesting());
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT));
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey12_, OriginSubdomains::DEFAULT));
EXPECT_EQ(2u, cache()->GetEndpointCount());
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(2,
mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT));
EXPECT_EQ(2, mock_store()->CountCommands(
CommandType::ADD_REPORTING_ENDPOINT_GROUP));
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey11_, kEndpoint1_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT,
kGroupKey12_, kEndpoint2_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
kGroupKey11_);
expected_commands.emplace_back(CommandType::ADD_REPORTING_ENDPOINT_GROUP,
kGroupKey12_);
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
// Set another header with max_age: 0 to delete one of the groups.
std::string header2 = ConstructHeaderGroupString(MakeEndpointGroup(
kGroup1_, endpoints1, OriginSubdomains::DEFAULT,
base::TimeDelta::FromSeconds(0))) +
", " +
ConstructHeaderGroupString(MakeEndpointGroup(
kGroup2_, endpoints2)); // Other group stays.
ParseHeader(kNik_, kUrl1_, header2);
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_EQ(1u, cache()->GetEndpointGroupCountForTesting());
// Group was deleted.
EXPECT_FALSE(
EndpointGroupExistsInCache(kGroupKey11_, OriginSubdomains::DEFAULT));
// Other group remains in the cache.
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey12_, OriginSubdomains::DEFAULT));
EXPECT_EQ(1u, cache()->GetEndpointCount());
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(2,
mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT));
EXPECT_EQ(2, mock_store()->CountCommands(
CommandType::ADD_REPORTING_ENDPOINT_GROUP));
EXPECT_EQ(
1, mock_store()->CountCommands(CommandType::DELETE_REPORTING_ENDPOINT));
EXPECT_EQ(1, mock_store()->CountCommands(
CommandType::DELETE_REPORTING_ENDPOINT_GROUP));
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
kGroupKey11_, kEndpoint1_);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT_GROUP,
kGroupKey11_);
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
// Invalid header values that are not JSON lists (without the outer brackets)
// are ignored.
ParseHeader(kNik_, kUrl1_, invalid_non_json_header);
EXPECT_TRUE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_TRUE(
EndpointGroupExistsInCache(kGroupKey12_, OriginSubdomains::DEFAULT));
EXPECT_EQ(1u, cache()->GetEndpointCount());
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(2,
mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT));
EXPECT_EQ(2, mock_store()->CountCommands(
CommandType::ADD_REPORTING_ENDPOINT_GROUP));
EXPECT_EQ(
1, mock_store()->CountCommands(CommandType::DELETE_REPORTING_ENDPOINT));
EXPECT_EQ(1, mock_store()->CountCommands(
CommandType::DELETE_REPORTING_ENDPOINT_GROUP));
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
kGroupKey11_, kEndpoint1_);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT_GROUP,
kGroupKey11_);
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
// Invalid headers that do parse as JSON should delete the corresponding
// client.
ParseHeader(kNik_, kUrl1_, invalid_json_header);
// Deletion of the last remaining group also deletes the client for this
// origin.
EXPECT_FALSE(ClientExistsInCacheForOrigin(kOrigin1_));
EXPECT_EQ(0u, cache()->GetEndpointGroupCountForTesting());
EXPECT_EQ(0u, cache()->GetEndpointCount());
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(2,
mock_store()->CountCommands(CommandType::ADD_REPORTING_ENDPOINT));
EXPECT_EQ(2, mock_store()->CountCommands(
CommandType::ADD_REPORTING_ENDPOINT_GROUP));
EXPECT_EQ(1 + 1, mock_store()->CountCommands(
CommandType::DELETE_REPORTING_ENDPOINT));
EXPECT_EQ(1 + 1, mock_store()->CountCommands(
CommandType::DELETE_REPORTING_ENDPOINT_GROUP));
MockPersistentReportingStore::CommandList expected_commands;
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT,
kGroupKey12_, kEndpoint2_);
expected_commands.emplace_back(CommandType::DELETE_REPORTING_ENDPOINT_GROUP,
kGroupKey12_);
EXPECT_THAT(mock_store()->GetAllCommands(),
testing::IsSupersetOf(expected_commands));
}
}
TEST_P(ReportingHeaderParserTest, EvictEndpointsOverPerOriginLimit1) {
// Set a header with too many endpoints, all in the same group.
std::vector<ReportingEndpoint::EndpointInfo> endpoints;
for (size_t i = 0; i < policy().max_endpoints_per_origin + 1; ++i) {
endpoints.push_back({MakeURL(i)});
}
std::string header =
ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints));
ParseHeader(kNik_, kUrl1_, header);
// Endpoint count should be at most the limit.
EXPECT_GE(policy().max_endpoints_per_origin, cache()->GetEndpointCount());
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(policy().max_endpoints_per_origin + 1,
static_cast<unsigned long>(mock_store()->CountCommands(
CommandType::ADD_REPORTING_ENDPOINT)));
EXPECT_EQ(1, mock_store()->CountCommands(
CommandType::ADD_REPORTING_ENDPOINT_GROUP));
EXPECT_EQ(
1, mock_store()->CountCommands(CommandType::DELETE_REPORTING_ENDPOINT));
}
}
TEST_P(ReportingHeaderParserTest, EvictEndpointsOverPerOriginLimit2) {
// Set a header with too many endpoints, in different groups.
std::string header;
for (size_t i = 0; i < policy().max_endpoints_per_origin + 1; ++i) {
std::vector<ReportingEndpoint::EndpointInfo> endpoints = {{MakeURL(i)}};
header = header + ConstructHeaderGroupString(MakeEndpointGroup(
base::NumberToString(i), endpoints));
if (i != policy().max_endpoints_per_origin)
header = header + ", ";
}
ParseHeader(kNik_, kUrl1_, header);
// Endpoint count should be at most the limit.
EXPECT_GE(policy().max_endpoints_per_origin, cache()->GetEndpointCount());
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(policy().max_endpoints_per_origin + 1,
static_cast<unsigned long>(mock_store()->CountCommands(
CommandType::ADD_REPORTING_ENDPOINT)));
EXPECT_EQ(policy().max_endpoints_per_origin + 1,
static_cast<unsigned long>(mock_store()->CountCommands(
CommandType::ADD_REPORTING_ENDPOINT_GROUP)));
EXPECT_EQ(
1, mock_store()->CountCommands(CommandType::DELETE_REPORTING_ENDPOINT));
EXPECT_EQ(1, mock_store()->CountCommands(
CommandType::DELETE_REPORTING_ENDPOINT_GROUP));
}
}
TEST_P(ReportingHeaderParserTest, EvictEndpointsOverGlobalLimit) {
// Set headers from different origins up to the global limit.
for (size_t i = 0; i < policy().max_endpoint_count; ++i) {
std::vector<ReportingEndpoint::EndpointInfo> endpoints = {{MakeURL(i)}};
std::string header =
ConstructHeaderGroupString(MakeEndpointGroup(kGroup1_, endpoints));
ParseHeader(kNik_, MakeURL(i), header);
}
EXPECT_EQ(policy().max_endpoint_count, cache()->GetEndpointCount());
// Parse one more header to trigger eviction.
ParseHeader(kNik_, kUrl1_,
"{\"endpoints\":[{\"url\":\"" + kEndpoint1_.spec() +
"\"}],\"max_age\":1}");
// Endpoint count should be at most the limit.
EXPECT_GE(policy().max_endpoint_count, cache()->GetEndpointCount());
if (mock_store()) {
mock_store()->Flush();
EXPECT_EQ(policy().max_endpoint_count + 1,
static_cast<unsigned long>(mock_store()->CountCommands(
CommandType::ADD_REPORTING_ENDPOINT)));
EXPECT_EQ(policy().max_endpoint_count + 1,
static_cast<unsigned long>(mock_store()->CountCommands(
CommandType::ADD_REPORTING_ENDPOINT_GROUP)));
EXPECT_EQ(
1, mock_store()->CountCommands(CommandType::DELETE_REPORTING_ENDPOINT));
EXPECT_EQ(1, mock_store()->CountCommands(
CommandType::DELETE_REPORTING_ENDPOINT_GROUP));
}
}
INSTANTIATE_TEST_SUITE_P(ReportingHeaderParserStoreTest,
ReportingHeaderParserTest,
testing::Bool());
} // namespace
} // namespace net
| 78,997 | 24,992 |
/**
* \file
* \copyright
* Copyright (c) 2012-2019, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*
*/
#include "FemConditionModel.h"
#include "Applications/DataHolderLib/BoundaryCondition.h"
#include "Applications/DataHolderLib/SourceTerm.h"
#include "TreeItem.h"
/**
* Constructor.
*/
FemConditionModel::FemConditionModel(QObject* parent) : TreeModel(parent)
{
QList<QVariant> root_data;
delete _rootItem;
root_data << "Parameter"
<< "Value";
_rootItem = new TreeItem(root_data, nullptr);
}
void FemConditionModel::setFemCondition(DataHolderLib::FemCondition* cond)
{
beginResetModel();
this->clearView();
QList<QVariant> cond_data;
cond_data << QString::fromStdString(cond->getConditionClassStr()) + ":"
<< QString::fromStdString(cond->getParamName());
TreeItem* cond_item = new TreeItem(cond_data, _rootItem);
_rootItem->appendChild(cond_item);
QList<QVariant> type_data;
std::string type_str;
if (cond->getConditionClassStr() == "Boundary Condition")
type_str = DataHolderLib::BoundaryCondition::convertTypeToString(
static_cast<DataHolderLib::BoundaryCondition*>(cond)->getType());
else if (cond->getConditionClassStr() == "Source Term")
type_str = DataHolderLib::SourceTerm::convertTypeToString(
static_cast<DataHolderLib::SourceTerm*>(cond)->getType());
type_data << "Type:" << QString::fromStdString(type_str);
TreeItem* type_item = new TreeItem(type_data, cond_item);
cond_item->appendChild(type_item);
QString const obj_class_str =
(cond->getBaseObjType() == DataHolderLib::BaseObjType::MESH)
? "Mesh:"
: "Geometry:";
QList<QVariant> obj_class_data;
obj_class_data << "Set on " + obj_class_str
<< QString::fromStdString(cond->getBaseObjName());
TreeItem* obj_class_item = new TreeItem(obj_class_data, cond_item);
cond_item->appendChild(obj_class_item);
QString const obj_str =
(cond->getBaseObjType() == DataHolderLib::BaseObjType::MESH)
? "Mesh array:"
: "Geo-Object:";
QString const name_str =
(cond->getBaseObjType() == DataHolderLib::BaseObjType::MESH)
? QString::fromStdString(cond->getParamName())
: QString::fromStdString(cond->getObjName());
QList<QVariant> obj_data;
obj_data << obj_str << name_str;
TreeItem* obj_item = new TreeItem(obj_data, cond_item);
cond_item->appendChild(obj_item);
endResetModel();
}
void FemConditionModel::setProcessVariable(DataHolderLib::FemCondition* cond)
{
beginResetModel();
this->clearView();
DataHolderLib::ProcessVariable const& var(cond->getProcessVar());
QList<QVariant> pvar_data;
pvar_data << "Process variable:" << QString::fromStdString(var.name);
TreeItem* pvar_item = new TreeItem(pvar_data, _rootItem);
_rootItem->appendChild(pvar_item);
QList<QVariant> order_data;
order_data << "Order:" << QString::number(var.order);
TreeItem* order_item = new TreeItem(order_data, pvar_item);
pvar_item->appendChild(order_item);
QList<QVariant> comp_data;
comp_data << "Number of components:" << QString::number(var.components);
TreeItem* comp_item = new TreeItem(comp_data, pvar_item);
pvar_item->appendChild(comp_item);
endResetModel();
}
void FemConditionModel::clearView()
{
beginResetModel();
_rootItem->removeChildren(0, _rootItem->childCount());
endResetModel();
}
| 3,693 | 1,199 |
/**
* 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.
**/
#ifndef QUICKSTEP_TYPES_NULL_COERCIBILITY_CHECK_MACRO_HPP_
#define QUICKSTEP_TYPES_NULL_COERCIBILITY_CHECK_MACRO_HPP_
#include "types/Type.hpp"
#include "types/TypeID.hpp"
/** \addtogroup Types
* @{
*/
/**
* @brief A code-snippet for use in implementations of Type::isCoercibleFrom()
* and Type::isSafelyCoercibleFrom() that does common checks for
* nullability of types.
**/
#define QUICKSTEP_NULL_COERCIBILITY_CHECK() \
do { \
if (original_type.isNullable() && !nullable_) { \
return false; \
} else if (original_type.getTypeID() == kNullType) { \
return true; \
} \
} while (false)
/** @} */
#endif // QUICKSTEP_TYPES_NULL_COERCIBILITY_CHECK_MACRO_HPP_
| 1,723 | 534 |
#define CATCH_CONFIG_RUNNER
#include <catch2/catch.hpp>
#include <Nazara/Audio/Audio.hpp>
#include <Nazara/Core/Log.hpp>
#include <Nazara/Core/AbstractLogger.hpp>
#include <Nazara/Core/Modules.hpp>
#include <Nazara/Network/Network.hpp>
#include <Nazara/Physics2D/Physics2D.hpp>
#include <Nazara/Utility/Utility.hpp>
int main(int argc, char* argv[])
{
Nz::Modules<Nz::Audio, Nz::Network, Nz::Physics2D, Nz::Utility> nazaza;
return Catch::Session().run(argc, argv);
}
| 471 | 202 |
#include <iostream> //import input output
using namespace std; //mengguanakan file fungsi std
int main() //fungsi
{
double x, y; //deklarasi variable menggunakan tipe data double
cout << "Masukkan x: "; //cetak ke layar monitor x
cin >> x; //inputan kemudian di simpan di variable x
cout << "Masukkan y: "; //cetak ke layar monitor Y
cin >> y; ////cetak ke layar monitor Y
if (x > y) {
cout << "Bilangan terbesar adalah X" << "\n";
} else {
cout << "Bilangan terbesar adalah Y" << "\n";
}
return 0;
} | 589 | 209 |
#include "../../CK2ToEU4/Source/Mappers/PrimaryTagMapper/PrimaryTagMapper.h"
#include "gtest/gtest.h"
#include <sstream>
TEST(Mappers_PrimaryTagMapperTests, CultureTagsDefaultToEmpty)
{
std::stringstream input;
const mappers::PrimaryTagMapper tagMapper(input);
ASSERT_TRUE(tagMapper.getCultureTags().empty());
}
TEST(Mappers_PrimaryTagMapperTests, CultureTagsCanBeLoaded)
{
std::stringstream input;
input << "group1 = { culture1 = {primary = TAG} culture2 = {} culture3 = {primary = GAT} }\n";
input << "group2 = { culture4 = {primary = GAT} culture5 = {} culture6 = {primary = GOT} }\n";
const mappers::PrimaryTagMapper tagMapper(input);
ASSERT_EQ(tagMapper.getCultureTags().size(), 4);
}
TEST(Mappers_PrimaryTagMapperTests, TagMapperReturnsNullOnMiss)
{
std::stringstream input;
input << "group1 = { culture1 = {primary = TAG} culture2 = {} culture3 = {primary = GAT} }\n";
input << "group2 = { culture4 = {primary = GAT} culture5 = {} culture6 = {primary = GOT} }\n";
const mappers::PrimaryTagMapper tagMapper(input);
ASSERT_FALSE(tagMapper.getPrimaryTagForCulture("culture2"));
ASSERT_FALSE(tagMapper.getPrimaryTagForCulture("culture5"));
}
TEST(Mappers_PrimaryTagMapperTests, TagMapperReturnsTagOnHit)
{
std::stringstream input;
input << "group1 = { culture1 = {primary = TAG} culture2 = {} culture3 = {primary = GAT} }\n";
input << "group2 = { culture4 = {primary = GAT} culture5 = {} culture6 = {primary = GOT} }\n";
const mappers::PrimaryTagMapper tagMapper(input);
ASSERT_EQ(*tagMapper.getPrimaryTagForCulture("culture1"), "TAG");
ASSERT_EQ(*tagMapper.getPrimaryTagForCulture("culture3"), "GAT");
ASSERT_EQ(*tagMapper.getPrimaryTagForCulture("culture4"), "GAT");
ASSERT_EQ(*tagMapper.getPrimaryTagForCulture("culture6"), "GOT");
}
| 1,771 | 607 |
//===-- DataBufferMemoryMap.cpp ---------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// C Includes
#include <fcntl.h>
#include <sys/stat.h>
#ifdef _WIN32
#include "lldb/Host/windows/windows.h"
#else
#include <sys/mman.h>
#define MAP_EXTRA_HOST_READ_FLAGS 0
#if defined(__APPLE__)
//----------------------------------------------------------------------
// Newer versions of MacOSX have a flag that will allow us to read from
// binaries whose code signature is invalid without crashing by using
// the MAP_RESILIENT_CODESIGN flag. Also if a file from removable media
// is mapped we can avoid crashing and return zeroes to any pages we try
// to read if the media becomes unavailable by using the
// MAP_RESILIENT_MEDIA flag.
//----------------------------------------------------------------------
#if defined(MAP_RESILIENT_CODESIGN)
#undef MAP_EXTRA_HOST_READ_FLAGS
#if defined(MAP_RESILIENT_MEDIA)
#define MAP_EXTRA_HOST_READ_FLAGS MAP_RESILIENT_CODESIGN | MAP_RESILIENT_MEDIA
#else
#define MAP_EXTRA_HOST_READ_FLAGS MAP_RESILIENT_CODESIGN
#endif
#endif // #if defined(MAP_RESILIENT_CODESIGN)
#endif // #if defined (__APPLE__)
#endif // #else #ifdef _WIN32
// C++ Includes
#include <cerrno>
#include <climits>
// Other libraries and framework includes
#include "llvm/Support/MathExtras.h"
// Project includes
#include "lldb/Core/DataBufferMemoryMap.h"
#include "lldb/Core/Error.h"
#include "lldb/Core/Log.h"
#include "lldb/Host/File.h"
#include "lldb/Host/FileSpec.h"
#include "lldb/Host/HostInfo.h"
using namespace lldb;
using namespace lldb_private;
//----------------------------------------------------------------------
// Default Constructor
//----------------------------------------------------------------------
DataBufferMemoryMap::DataBufferMemoryMap()
: m_mmap_addr(nullptr), m_mmap_size(0), m_data(nullptr), m_size(0) {}
//----------------------------------------------------------------------
// Virtual destructor since this class inherits from a pure virtual
// base class.
//----------------------------------------------------------------------
DataBufferMemoryMap::~DataBufferMemoryMap() { Clear(); }
//----------------------------------------------------------------------
// Return a pointer to the bytes owned by this object, or nullptr if
// the object contains no bytes.
//----------------------------------------------------------------------
uint8_t *DataBufferMemoryMap::GetBytes() { return m_data; }
//----------------------------------------------------------------------
// Return a const pointer to the bytes owned by this object, or nullptr
// if the object contains no bytes.
//----------------------------------------------------------------------
const uint8_t *DataBufferMemoryMap::GetBytes() const { return m_data; }
//----------------------------------------------------------------------
// Return the number of bytes this object currently contains.
//----------------------------------------------------------------------
uint64_t DataBufferMemoryMap::GetByteSize() const { return m_size; }
//----------------------------------------------------------------------
// Reverts this object to an empty state by unmapping any memory
// that is currently owned.
//----------------------------------------------------------------------
void DataBufferMemoryMap::Clear() {
if (m_mmap_addr != nullptr) {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MMAP));
if (log)
log->Printf("DataBufferMemoryMap::Clear() m_mmap_addr = %p, m_mmap_size "
"= %" PRIu64 "",
(void *)m_mmap_addr, (uint64_t)m_mmap_size);
#ifdef _WIN32
UnmapViewOfFile(m_mmap_addr);
#else
::munmap((void *)m_mmap_addr, m_mmap_size);
#endif
m_mmap_addr = nullptr;
m_mmap_size = 0;
m_data = nullptr;
m_size = 0;
}
}
//----------------------------------------------------------------------
// Memory map "length" bytes from "file" starting "offset"
// bytes into the file. If "length" is set to SIZE_MAX, then
// map as many bytes as possible.
//
// Returns the number of bytes mapped starting from the requested
// offset.
//----------------------------------------------------------------------
size_t DataBufferMemoryMap::MemoryMapFromFileSpec(const FileSpec *filespec,
lldb::offset_t offset,
size_t length,
bool writeable) {
if (filespec != nullptr) {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MMAP));
if (log) {
log->Printf("DataBufferMemoryMap::MemoryMapFromFileSpec(file=\"%s\", "
"offset=0x%" PRIx64 ", length=0x%" PRIx64 ", writeable=%i",
filespec->GetPath().c_str(), offset, (uint64_t)length,
writeable);
}
char path[PATH_MAX];
if (filespec->GetPath(path, sizeof(path))) {
uint32_t options = File::eOpenOptionRead;
if (writeable)
options |= File::eOpenOptionWrite;
File file;
Error error(file.Open(path, options));
if (error.Success()) {
const bool fd_is_file = true;
return MemoryMapFromFileDescriptor(file.GetDescriptor(), offset, length,
writeable, fd_is_file);
}
}
}
// We should only get here if there was an error
Clear();
return 0;
}
#ifdef _WIN32
static size_t win32memmapalignment = 0;
void LoadWin32MemMapAlignment() {
SYSTEM_INFO data;
GetSystemInfo(&data);
win32memmapalignment = data.dwAllocationGranularity;
}
#endif
//----------------------------------------------------------------------
// The file descriptor FD is assumed to already be opened as read only
// and the STAT structure is assumed to a valid pointer and already
// containing valid data from a call to stat().
//
// Memory map FILE_LENGTH bytes in FILE starting FILE_OFFSET bytes into
// the file. If FILE_LENGTH is set to SIZE_MAX, then map as many bytes
// as possible.
//
// RETURNS
// Number of bytes mapped starting from the requested offset.
//----------------------------------------------------------------------
size_t DataBufferMemoryMap::MemoryMapFromFileDescriptor(int fd,
lldb::offset_t offset,
size_t length,
bool writeable,
bool fd_is_file) {
Clear();
if (fd >= 0) {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MMAP |
LIBLLDB_LOG_VERBOSE));
if (log) {
log->Printf("DataBufferMemoryMap::MemoryMapFromFileDescriptor(fd=%i, "
"offset=0x%" PRIx64 ", length=0x%" PRIx64
", writeable=%i, fd_is_file=%i)",
fd, offset, (uint64_t)length, writeable, fd_is_file);
}
#ifdef _WIN32
HANDLE handle = (HANDLE)_get_osfhandle(fd);
DWORD file_size_low, file_size_high;
file_size_low = GetFileSize(handle, &file_size_high);
const lldb::offset_t file_size =
llvm::Make_64(file_size_high, file_size_low);
const lldb::offset_t max_bytes_available = file_size - offset;
const size_t max_bytes_mappable =
(size_t)std::min<lldb::offset_t>(SIZE_MAX, max_bytes_available);
if (length == SIZE_MAX || length > max_bytes_mappable) {
// Cap the length if too much data was requested
length = max_bytes_mappable;
}
if (length > 0) {
HANDLE fileMapping = CreateFileMapping(
handle, nullptr, writeable ? PAGE_READWRITE : PAGE_READONLY,
file_size_high, file_size_low, nullptr);
if (fileMapping != nullptr) {
if (win32memmapalignment == 0)
LoadWin32MemMapAlignment();
lldb::offset_t realoffset = offset;
lldb::offset_t delta = 0;
if (realoffset % win32memmapalignment != 0) {
realoffset = realoffset / win32memmapalignment * win32memmapalignment;
delta = offset - realoffset;
}
LPVOID data = MapViewOfFile(fileMapping,
writeable ? FILE_MAP_WRITE : FILE_MAP_READ,
0, realoffset, length + delta);
m_mmap_addr = (uint8_t *)data;
if (!data) {
Error error;
error.SetErrorToErrno();
} else {
m_data = m_mmap_addr + delta;
m_size = length;
}
CloseHandle(fileMapping);
}
}
#else
struct stat stat;
if (::fstat(fd, &stat) == 0) {
if (S_ISREG(stat.st_mode) &&
(stat.st_size > static_cast<off_t>(offset))) {
const size_t max_bytes_available = stat.st_size - offset;
if (length == SIZE_MAX) {
length = max_bytes_available;
} else if (length > max_bytes_available) {
// Cap the length if too much data was requested
length = max_bytes_available;
}
if (length > 0) {
int prot = PROT_READ;
int flags = MAP_PRIVATE;
if (writeable)
prot |= PROT_WRITE;
else
flags |= MAP_EXTRA_HOST_READ_FLAGS;
if (fd_is_file)
flags |= MAP_FILE;
m_mmap_addr =
(uint8_t *)::mmap(nullptr, length, prot, flags, fd, offset);
Error error;
if (m_mmap_addr == (void *)-1) {
error.SetErrorToErrno();
if (error.GetError() == EINVAL) {
// We may still have a shot at memory mapping if we align things
// correctly
size_t page_offset = offset % HostInfo::GetPageSize();
if (page_offset != 0) {
m_mmap_addr =
(uint8_t *)::mmap(nullptr, length + page_offset, prot,
flags, fd, offset - page_offset);
if (m_mmap_addr == (void *)-1) {
// Failed to map file
m_mmap_addr = nullptr;
} else if (m_mmap_addr != nullptr) {
// We recovered and were able to memory map
// after we aligned things to page boundaries
// Save the actual mmap'ed size
m_mmap_size = length + page_offset;
// Our data is at an offset into the mapped data
m_data = m_mmap_addr + page_offset;
// Our pretend size is the size that was requested
m_size = length;
}
}
}
if (error.GetError() == ENOMEM) {
error.SetErrorStringWithFormat("could not allocate %" PRId64
" bytes of memory to mmap in file",
(uint64_t)length);
}
} else {
// We were able to map the requested data in one chunk
// where our mmap and actual data are the same.
m_mmap_size = length;
m_data = m_mmap_addr;
m_size = length;
}
if (log) {
log->Printf(
"DataBufferMemoryMap::MemoryMapFromFileSpec() m_mmap_addr = "
"%p, m_mmap_size = %" PRIu64 ", error = %s",
(void *)m_mmap_addr, (uint64_t)m_mmap_size, error.AsCString());
}
}
}
}
#endif
}
return GetByteSize();
}
| 11,805 | 3,412 |
#include "../include/dispatcher.h"
//Funcao de ordenacao para o vetor de processos
bool ordena (Processo *proc1, Processo *proc2){
return (proc1->getTempoInicializacao() < proc2->getTempoInicializacao());
}
Dispatcher::Dispatcher(vector< Processo* > processosArquivo, Disco *discoArquivo){
tempo_atual = 0;
//Atribui para a lista de processos do Dispatcher
proximosProcessos = processosArquivo;
//Atribui para a estrutura de disco do Dispatcher
disco = discoArquivo;
//Ordena em ordem crescente de tempo de inicializacao
sort(proximosProcessos.begin(), proximosProcessos.end(), ordena);
}
void Dispatcher::rodaCPU(Processo* processo){
//Diminui tempo do processo em 1 quantum (simula execucao)
processo->setTempoProcessador(processo->getTempoProcessador() - 1);
cout << "Processo rodando: " << processo->getID() << endl;
/************** Acoes a serem simuladas na operacao *********/
//Operacoes de um processo no sistema de arquivos
realizarOperacoes(disco, processo->getID(),processo->getPrioridade());
}
void Dispatcher::executa(){
FilaGlobal filaGlobal;
Processo *processoAtual = nullptr;
//Enquanto houver processos para executar
while(!filaGlobal.estaoVazias() || !proximosProcessos.empty()){
//Enquanto o tempo atual for igual ao tempo de inicializacao
//dos proximos processos a serem inseridos, insere na fila global
while(!proximosProcessos.empty() &&
proximosProcessos.front()->getTempoInicializacao() == tempo_atual){
cout << endl << "dispatcher =>" << endl;
proximosProcessos.front()->print();
//Insere elemento na fila
filaGlobal.insere(proximosProcessos.front());
//Apaga primeiro elemento
proximosProcessos.erase(proximosProcessos.begin());
}
//Com elementos devidamente inseridos na fila de prontos,
//pode-se escolher 1 da fila global
if(!processoAtual && !filaGlobal.estaoVazias()){
processoAtual = filaGlobal.escolhe_processo();
}
//Se processo nao for null
if(processoAtual){
//Manda pra CPU
rodaCPU(processoAtual);
if(processoAtual->getTempoProcessador() <= 0){
//TODO: Operacoes de desalocacao de E/S e memoria
processoAtual = nullptr;
}
//Se n tiver acabado e for processo usuario, sofre preempcao
else if(processoAtual->eh_usuario()){
filaGlobal.realimenta(processoAtual);
processoAtual = nullptr;
}
} //if processoAtual
tempo_atual++;
} //while houver processos
//Apos fim da execucao, imprimir relatorio de operacoes pros processos
relatorioOperacoes(disco);
cout << endl << "Mapa de ocupacao do disco:" << endl;
//Impressao dos blocos
imprimirBlocos(disco);
}
| 2,716 | 934 |
/*
* Copyright 2021 Assured Information Security, 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 "BreakpointManager.hh"
#include "core/breakpoint/BreakpointImpl.hh"
#include "core/domain/DomainImpl.hh"
#include "core/domain/VcpuImpl.hh"
#include <introvirt/core/exception/CommandFailedException.hh>
#include <introvirt/util/compiler.hh>
#include <log4cxx/logger.h>
#include <cassert>
#include <stdexcept>
namespace introvirt {
static InternalBreakpoint* HiddenBreakpoint = nullptr;
static thread_local std::shared_ptr<InternalBreakpoint> active_breakpoint = nullptr;
static log4cxx::LoggerPtr
logger(log4cxx::Logger::getLogger("introvirt.breakpoint.BreakpointManager"));
void InternalBreakpoint::watchpoint_event(Event& event) {
if (mapping_.address() != event.mem_access().physical_address().address()) {
LOG4CXX_WARN(logger,
"Incorrect physical address: " << event.mem_access().physical_address());
}
if (event.mem_access().read_violation()) {
LOG4CXX_DEBUG(logger, event.task().process_name()
<< ": Hiding breakpoint from guest at " << mapping_ << " RIP: 0x"
<< std::hex << event.vcpu().registers().rip());
}
if (event.mem_access().write_violation()) {
LOG4CXX_DEBUG(logger, event.task().process_name()
<< ": Guest attempted to write breakpoint memory at "
<< mapping_);
}
if (*mapping_ == 0xCC && !nested_bp()) {
disable();
HiddenBreakpoint = this;
}
}
void InternalBreakpoint::step_event() {
// Re-read the original byte and then restore the breakpoint
LOG4CXX_TRACE(logger, "Restoring breakpoint after guest memory access");
original_byte_ = *mapping_;
enable();
single_step_.reset();
}
void InternalBreakpoint::deliver_breakpoint(Event& event) {
// Get a copy of the callback set so that we don't have to hold a lock
std::unique_lock lock(mtx_);
std::vector<std::shared_ptr<BreakpointImplCallback>> callbacks;
callbacks.reserve(breakpoint_list_.size());
for (auto& weakptr : breakpoint_list_) {
auto entry = weakptr.lock();
if (entry)
callbacks.push_back(entry->callback());
}
lock.unlock();
LOG4CXX_DEBUG(logger, "Delivering " << callbacks.size() << " breakpoint callbacks");
for (auto& entry : callbacks) {
try {
entry->deliver_event(event);
} catch (TraceableException& ex) {
LOG4CXX_WARN(logger, "Caught exception in deliver_breakpoint(): " << ex);
}
}
}
void InternalBreakpoint::add_callback(const std::shared_ptr<BreakpointImpl>& bpimpl) {
std::unique_lock lock(mtx_);
breakpoint_list_.push_back(bpimpl);
if (breakpoint_list_.size() == 1) {
enable();
}
}
bool InternalBreakpoint::remove_expired() {
std::unique_lock lock(mtx_);
for (auto iter = breakpoint_list_.begin(); iter != breakpoint_list_.end();) {
auto& weakptr = *iter;
if (weakptr.expired()) {
iter = breakpoint_list_.erase(iter);
} else {
++iter;
}
}
if (breakpoint_list_.empty()) {
disable();
return true;
}
return false;
}
InternalBreakpoint::InternalBreakpoint(const guest_phys_ptr<void>& address)
: mapping_(static_ptr_cast<uint8_t>(address)), original_byte_(*mapping_) {
enable();
// Configure out watchpoint if supported
try {
#if 0
auto& domain = const_cast<DomainImpl&>(static_cast<const DomainImpl&>(address.domain()));
watchpoint_ = domain.create_watchpoint(
address, 1, true, true, false,
std::bind(&InternalBreakpoint::watchpoint_event, this, std::placeholders::_1));
#endif
} catch (CommandFailedException& ex) {
// Guest doesn't support watchpoints
LOG4CXX_DEBUG(logger, "Failed to create watchpoint for breakpoint: " << ex.what());
}
}
InternalBreakpoint::~InternalBreakpoint() { disable(); }
void BreakpointManager::add_ref(const std::shared_ptr<BreakpointImpl>& breakpoint) {
std::lock_guard lock(breakpoints_.mtx_);
if (unlikely(interrupted_))
return;
std::shared_ptr<InternalBreakpoint> entry;
guest_phys_ptr<uint8_t> physical_address = breakpoint->ptr();
// See if we can find it in the breakpoint map
auto iter = breakpoints_.map_.find(physical_address.address());
if (iter == breakpoints_.map_.end()) {
// Entry doesn't exist, create it
entry = std::make_shared<InternalBreakpoint>(physical_address);
iter = breakpoints_.map_.emplace(physical_address.address(), std::move(entry)).first;
} else {
// Entry exists, try to lock it
entry = iter->second.lock();
if (!entry) {
// Entry has expired, recreate it
entry = std::make_shared<InternalBreakpoint>(physical_address);
iter = breakpoints_.map_.emplace(physical_address.address(), std::move(entry)).first;
}
}
// Store it with the breakpoint
breakpoint->internal_breakpoint(entry);
// Register the breakpoint with the internal breakpoint
entry->add_callback(breakpoint);
}
void BreakpointManager::remove_ref(BreakpointImpl& breakpoint) {
std::lock_guard lock(breakpoints_.mtx_);
if (unlikely(interrupted_))
return;
auto entry = breakpoint.internal_breakpoint();
if (entry->remove_expired()) {
// The internal breakpoint has no more callbacks and can be erased
breakpoints_.map_.erase(breakpoint.ptr().address());
}
}
bool BreakpointManager::handle_int3_event(Event& event, bool deliver_events) {
auto& vcpu = event.vcpu();
auto& regs = vcpu.registers();
guest_ptr<uint8_t> rip(vcpu, regs.rip());
const uint64_t physical_rip = guest_phys_ptr<uint8_t>(rip).address();
if (unlikely(interrupted_)) {
return false;
}
// Find the breakpoint for the event
std::unique_lock breakpoints_lock(breakpoints_.mtx_);
LOG4CXX_DEBUG(logger, "VCPU " << vcpu.id() << ": INT3 received for " << rip);
auto iter = breakpoints_.map_.find(physical_rip);
if (unlikely(iter == breakpoints_.map_.end())) {
// We don't have a breakpoint for this!
// Check to see if there's an actual int3 instruction in place
if (*guest_ptr<uint8_t>(rip) == 0xCC) {
LOG4CXX_DEBUG(logger, "Injecting unwanted Int3");
vcpu.inject_exception(x86::Exception::INT3);
return false;
} else {
LOG4CXX_DEBUG(logger, "Hit unknown breakpoint. This is probably bad for the guest.")
}
return false;
}
// Get our breakpoint entry
active_breakpoint = iter->second.lock();
if (unlikely(!active_breakpoint)) {
// Maybe all of our breakpoints were removed while we were waiting.
// If that's the case, the breakpoint instruction should have already been removed.
LOG4CXX_DEBUG(logger, "Failed to lock internal breakpoint from weak_ptr.");
return false;
}
// No longer need to lock on this since we have out internal breakpoint
breakpoints_lock.unlock();
// Reinject the exeception if this is a nested Int3
if (active_breakpoint->nested_bp())
vcpu.inject_exception(x86::Exception::INT3);
// Run callbacks
active_breakpoint->disable();
if (deliver_events) {
active_breakpoint->deliver_breakpoint(event);
if (active_breakpoint->remove_expired()) {
// No one left waiting for this breakpoint. No need for a callback.
LOG4CXX_TRACE(logger, "Breakpoing removed, not stepping VCPU " << vcpu.id());
active_breakpoint.reset();
breakpoints_lock.lock();
breakpoints_.map_.erase(physical_rip);
return false;
}
// Check if one of our callbacks changed RIP
if (regs.rip() != rip.address()) {
// A callback must have changed RIP, just turn the breakpoint back on
active_breakpoint.reset();
active_breakpoint->enable();
LOG4CXX_TRACE(logger, "RIP changed, not stepping VCPU " << vcpu.id());
return false;
}
}
// It did not, we need to single step the guest
LOG4CXX_DEBUG(logger, "Waiting for BP step on VCPU " << vcpu.id());
return true;
}
void BreakpointManager::step(Event& event) {
if (HiddenBreakpoint != nullptr) {
// Unhide the BP
HiddenBreakpoint->step_event();
HiddenBreakpoint = nullptr;
}
// Stepping done, turn the breakpoint back on
if (active_breakpoint != nullptr) {
active_breakpoint->enable();
active_breakpoint.reset();
LOG4CXX_DEBUG(logger, "BP step on VCPU " << event.vcpu().id());
}
}
void BreakpointManager::interrupt() {
// Clean up and unblock any pending events
interrupted_ = true;
std::lock_guard lock2(breakpoints_.mtx_);
// Disable all breakpoints
for (auto& [address, weakptr] : breakpoints_.map_) {
auto entry = weakptr.lock();
if (entry)
entry->disable();
}
}
void BreakpointManager::start_injection() {
if (active_breakpoint) {
active_breakpoint->enable();
}
}
void BreakpointManager::end_injection() {
if (active_breakpoint) {
active_breakpoint->disable();
}
}
BreakpointManager::BreakpointManager() {}
BreakpointManager::~BreakpointManager() = default;
} // namespace introvirt
| 10,123 | 3,063 |
#include <cstdio>
#include <cstring>
char PROG[] = "cbarn";
#include <algorithm>
using namespace std;
int n;
long long x, c[1000];
long long squaresum(long long begin, long long end) {
return (end * (end + 1) * (2 * end + 1) -
(begin - 1) * begin * (2 * begin - 1)) / 6;
}
long long endat(int i) {
return x + c[i] - 1;
}
void update(int i) {
x = max(0ll, endat(i));
}
void init() {
scanf("%d", &n);
x = 0ll;
for (int i = 0; i < n; i++) {
scanf("%lld", &c[i]);
update(i);
}
}
void pickstart() {
for (int i = 0;; i++) {
if (!x) {
rotate(c, c + i, c + n);
break;
}
update(i);
}
}
long long calc() {
long long ret = 0;
for (int i = 0; i < n; i++) {
ret += squaresum(x, endat(i));
update(i);
}
return ret;
}
void actualMain() {
init();
pickstart();
printf("%lld\n", calc());
}
int main() {
int size = sizeof(PROG);
char in[size + 3], out[size + 4];
freopen(strcat(strcpy(in, PROG), ".in"), "r", stdin);
freopen(strcat(strcpy(out, PROG), ".out"), "w", stdout);
actualMain();
fclose(stdin);
fclose(stdout);
return 0;
}
| 1,061 | 500 |
// Boost.TypeErasure library
//
// Copyright 2011-2012 Steven Watanabe
//
// 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)
//
// $Id$
#if !defined(BOOST_PP_IS_ITERATING)
#ifndef BOOST_TYPE_ERASURE_TUPLE_HPP_INCLUDED
#define BOOST_TYPE_ERASURE_TUPLE_HPP_INCLUDED
#include <boost/config.hpp>
#ifdef BOOST_TYPE_ERASURE_DOXYGEN
namespace boost {
namespace type_erasure {
/**
* @ref tuple is a Boost.Fusion Random Access Sequence containing
* @ref any "anys". @c Concept specifies the \Concept for each
* of the elements. The remaining arguments must be (possibly const
* and/or reference qualified) placeholders, which are the
* @ref placeholder "placeholders" of the elements.
*/
template <class Concept, class... T> class tuple {
public:
/**
* Constructs a tuple. Each element of @c args will
* be used to initialize the corresponding @ref any member.
* The @ref binding for the tuple elements is determined
* by mapping the placeholders in @c T to the corresponding
* types in @c U.
*/
template <class... U> explicit tuple(U &&... args);
};
/**
* Returns the Nth @ref any in the tuple.
*/
template <int N, class Concept, class... T>
any<Concept, TN> &get(tuple<Concept, T...> &arg);
/** \overload */
template <int N, class Concept, class... T>
const any<Concept, TN> &get(const tuple<Concept, T...> &arg);
} // namespace type_erasure
} // namespace boost
#elif !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) && \
!defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
#include <boost/fusion/include/category_of.hpp>
#include <boost/fusion/include/iterator_facade.hpp>
#include <boost/fusion/include/sequence_facade.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/insert.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/map.hpp>
#include <boost/type_erasure/any.hpp>
#include <boost/type_erasure/config.hpp>
#include <boost/type_erasure/static_binding.hpp>
#include <boost/type_traits/remove_const.hpp>
#include <boost/type_traits/remove_reference.hpp>
namespace boost {
namespace type_erasure {
template <class Concept, class... T> struct cons;
template <class Concept> struct cons<Concept> {
template <class Binding> cons(const Binding &) {}
};
template <class Concept, class T0, class... T> struct cons<Concept, T0, T...> {
typedef any<Concept, T0> value_type;
typedef cons<Concept, T...> rest_type;
template <class Binding, class U0, class... U>
cons(const Binding &b, U0 &&u0, U &&... u)
: value(std::forward<U0>(u0), b), rest(b, std::forward<U>(u)...) {}
any<Concept, T0> value;
cons<Concept, T...> rest;
};
namespace detail {
template <int N, class Cons> struct cons_advance {
typedef typename cons_advance<N - 1, Cons>::type::rest_type type;
static const type &call(const Cons &c) {
return cons_advance<N - 1, Cons>::call(c).rest;
}
};
template <class Cons> struct cons_advance<0, Cons> {
typedef Cons type;
static const type &call(const Cons &c) { return c; }
};
template <class... T> struct make_map;
template <class T0, class... T> struct make_map<T0, T...> {
typedef typename ::boost::mpl::insert<
typename ::boost::type_erasure::detail::make_map<T...>::type, T0>::type
type;
};
template <> struct make_map<> { typedef ::boost::mpl::map0<> type; };
} // namespace detail
/** INTERNAL ONLY */
template <class Tuple, int N>
class tuple_iterator : public ::boost::fusion::iterator_facade<
tuple_iterator<Tuple, N>,
::boost::fusion::random_access_traversal_tag> {
public:
typedef ::boost::mpl::int_<N> index;
explicit tuple_iterator(Tuple &t_arg) : t(&t_arg) {}
template <class It> struct value_of {
typedef typename Tuple::template value_at<Tuple, mpl::int_<N>>::type type;
};
template <class It> struct deref {
typedef typename Tuple::template at<Tuple, mpl::int_<N>>::type type;
static type call(It it) {
return Tuple::template at<Tuple, mpl::int_<N>>::call(*it.t);
}
};
template <class It, class M> struct advance {
typedef tuple_iterator<Tuple, (It::index::value + M::value)> type;
static type call(It it) { return type(*it.t); }
};
template <class It> struct next : advance<It, ::boost::mpl::int_<1>> {};
template <class It> struct prior : advance<It, ::boost::mpl::int_<-1>> {};
template <class It1, class It2> struct distance {
typedef typename ::boost::mpl::minus<typename It2::index,
typename It1::index>::type type;
static type call(It1, It2) { return type(); }
};
private:
Tuple *t;
};
template <class Concept, class... T>
class tuple : public ::boost::fusion::sequence_facade<
::boost::type_erasure::tuple<Concept, T...>,
::boost::fusion::forward_traversal_tag> {
public:
template <class... U>
explicit tuple(U &&... args)
: impl(::boost::type_erasure::make_binding<
typename ::boost::type_erasure::detail::make_map<
::boost::mpl::pair<
typename ::boost::remove_const<
typename ::boost::remove_reference<T>::type>::type,
typename ::boost::remove_const<
typename ::boost::remove_reference<U>::type>::
type>...>::type>(),
std::forward<U>(args)...) {}
template <class Seq> struct begin {
typedef ::boost::type_erasure::tuple_iterator<Seq, 0> type;
static type call(Seq &seq) { return type(seq); }
};
template <class Seq> struct end {
typedef ::boost::type_erasure::tuple_iterator<Seq, sizeof...(T)> type;
static type call(Seq &seq) { return type(seq); }
};
template <class Seq> struct size {
typedef ::boost::mpl::int_<sizeof...(T)> type;
static type call(Seq &seq) { return type(); }
};
template <class Seq> struct empty {
typedef ::boost::mpl::bool_<sizeof...(T) == 0> type;
static type call(Seq &seq) { return type(); }
};
template <class Seq, class N> struct at {
typedef typename ::boost::type_erasure::detail::cons_advance<
N::value, ::boost::type_erasure::cons<Concept, T...>>::type::value_type
value_type;
typedef
typename ::boost::mpl::if_<::boost::is_const<Seq>, const value_type &,
value_type &>::type type;
static type call(Seq &seq) {
return const_cast<type>(
::boost::type_erasure::detail::cons_advance<
N::value,
::boost::type_erasure::cons<Concept, T...>>::call(seq.impl)
.value);
}
};
template <class Seq, class N> struct value_at {
typedef typename ::boost::type_erasure::detail::cons_advance<
N::value, ::boost::type_erasure::cons<Concept, T...>>::type::value_type
value_type;
};
::boost::type_erasure::cons<Concept, T...> impl;
};
template <int N, class Concept, class... T>
typename ::boost::type_erasure::detail::cons_advance<
N, ::boost::type_erasure::cons<Concept, T...>>::type::value_type &
get(::boost::type_erasure::tuple<Concept, T...> &t) {
return const_cast<typename ::boost::type_erasure::detail::cons_advance<
N, ::boost::type_erasure::cons<Concept, T...>>::type::value_type &>(
::boost::type_erasure::detail::cons_advance<
N, ::boost::type_erasure::cons<Concept, T...>>::call(t.impl)
.value);
}
template <int N, class Concept, class... T>
const typename ::boost::type_erasure::detail::cons_advance<
N, ::boost::type_erasure::cons<Concept, T...>>::type::value_type &
get(const ::boost::type_erasure::tuple<Concept, T...> &t) {
return ::boost::type_erasure::detail::cons_advance<
N, ::boost::type_erasure::cons<Concept, T...>>::call(t.impl)
.value;
}
} // namespace type_erasure
} // namespace boost
#else
#include <boost/fusion/include/category_of.hpp>
#include <boost/fusion/include/iterator_facade.hpp>
#include <boost/fusion/include/sequence_facade.hpp>
#include <boost/mpl/equal_to.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/map.hpp>
#include <boost/mpl/minus.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/iteration/iterate.hpp>
#include <boost/preprocessor/repetition/enum.hpp>
#include <boost/preprocessor/repetition/enum_binary_params.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum_params_with_a_default.hpp>
#include <boost/preprocessor/repetition/enum_trailing_binary_params.hpp>
#include <boost/preprocessor/repetition/enum_trailing_params.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/type_erasure/any.hpp>
#include <boost/type_erasure/config.hpp>
#include <boost/type_erasure/static_binding.hpp>
namespace boost {
namespace type_erasure {
/** INTERNAL ONLY */
struct na {};
namespace detail {
template <int N, class Tuple> struct get_impl;
template <class Concept, BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT(
BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, class T,
::boost::type_erasure::na)>
struct tuple_storage;
} // namespace detail
/** INTERNAL ONLY */
template <class Tuple, int N>
class tuple_iterator : public ::boost::fusion::iterator_facade<
tuple_iterator<Tuple, N>,
::boost::fusion::random_access_traversal_tag> {
public:
typedef ::boost::mpl::int_<N> index;
explicit tuple_iterator(Tuple &t_arg) : t(&t_arg) {}
template <class It> struct value_of {
typedef typename ::boost::type_erasure::detail::get_impl<
It::index::value, Tuple>::value_type type;
};
template <class It>
struct deref
: ::boost::type_erasure::detail::get_impl<It::index::value, Tuple> {
typedef typename ::boost::type_erasure::detail::get_impl<It::index::value,
Tuple>::type type;
static type call(It it) {
return ::boost::type_erasure::detail::get_impl<It::index::value,
Tuple>::call(*it.t);
}
};
template <class It, class M> struct advance {
typedef tuple_iterator<Tuple, (It::index::value + M::value)> type;
static type call(It it) { return type(*it.t); }
};
template <class It> struct next : advance<It, ::boost::mpl::int_<1>> {};
template <class It> struct prior : advance<It, ::boost::mpl::int_<-1>> {};
template <class It1, class It2> struct distance {
typedef typename ::boost::mpl::minus<typename It2::index,
typename It1::index>::type type;
static type call(It1, It2) { return type(); }
};
private:
Tuple *t;
};
/** INTERNAL ONLY */
template <class Derived>
struct tuple_base : ::boost::fusion::sequence_facade<
Derived, ::boost::fusion::random_access_traversal_tag> {
template <class Seq> struct begin {
typedef ::boost::type_erasure::tuple_iterator<Seq, 0> type;
static type call(Seq &seq) { return type(seq); }
};
template <class Seq> struct end {
typedef ::boost::type_erasure::tuple_iterator<Seq, Seq::tuple_size::value>
type;
static type call(Seq &seq) { return type(seq); }
};
template <class Seq> struct size {
typedef typename Seq::tuple_size type;
static type call(Seq &seq) { return type(); }
};
template <class Seq> struct empty {
typedef typename boost::mpl::equal_to<typename Seq::tuple_size,
boost::mpl::int_<0>>::type type;
static type call(Seq &seq) { return type(); }
};
template <class Seq, class N>
struct at : ::boost::type_erasure::detail::get_impl<N::value, Seq> {};
template <class Seq, class N> struct value_at {
typedef
typename ::boost::type_erasure::detail::get_impl<N::value,
Seq>::value_type type;
};
};
template <class Concept, BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT(
BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, class T,
::boost::type_erasure::na)>
class tuple;
template <int N, class Concept BOOST_PP_ENUM_TRAILING_PARAMS(
BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, class T)>
typename detail::get_impl<N, tuple<Concept BOOST_PP_ENUM_TRAILING_PARAMS(
BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, T)>>::type
get(tuple<Concept BOOST_PP_ENUM_TRAILING_PARAMS(
BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, T)> &arg) {
return detail::get_impl<
N, tuple<Concept BOOST_PP_ENUM_TRAILING_PARAMS(
BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, T)>>::call(arg);
}
template <int N, class Concept BOOST_PP_ENUM_TRAILING_PARAMS(
BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, class T)>
typename detail::get_impl<N, const tuple<Concept BOOST_PP_ENUM_TRAILING_PARAMS(
BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, T)>>::type
get(const tuple<Concept BOOST_PP_ENUM_TRAILING_PARAMS(
BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, T)> &arg) {
return detail::get_impl<
N, const tuple<Concept BOOST_PP_ENUM_TRAILING_PARAMS(
BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, T)>>::call(arg);
}
/** INTERNAL ONLY */
#define BOOST_PP_FILENAME_1 <boost/type_erasure/tuple.hpp>
/** INTERNAL ONLY */
#define BOOST_PP_ITERATION_LIMITS (0, BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE)
#include BOOST_PP_ITERATE()
} // namespace type_erasure
} // namespace boost
#endif
#endif
#else
#define N BOOST_PP_ITERATION()
#define BOOST_TYPE_ERASURE_TAG_TYPEDEF(z, n, data) \
typedef BOOST_PP_CAT(T, n) BOOST_PP_CAT(tag_type, n); \
typedef typename ::boost::remove_reference<BOOST_PP_CAT(T, n)>::type \
BOOST_PP_CAT(tag, n);
#define BOOST_TYPE_ERASURE_PAIR(z, n, data) \
::boost::mpl::pair<BOOST_PP_CAT(tag, n), BOOST_PP_CAT(U, n)>
#define BOOST_TYPE_ERASURE_CONSTRUCT(z, n, data) \
BOOST_PP_CAT(t, n)(BOOST_PP_CAT(u, n), table)
#define BOOST_TYPE_ERASURE_TUPLE_MEMBER(z, n, data) \
::boost::type_erasure::any<Concept, BOOST_PP_CAT(T, n)> BOOST_PP_CAT(t, n);
#if N == 1
#define BOOST_TYPE_ERASURE_EXPLICIT explicit
#else
#define BOOST_TYPE_ERASURE_EXPLICIT
#endif
namespace detail {
template <class Concept BOOST_PP_ENUM_TRAILING_PARAMS(N, class T)>
struct tuple_storage
#if N != BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE
<Concept BOOST_PP_ENUM_TRAILING_PARAMS(N, T)>
#endif
{
#if N
template <class Table BOOST_PP_ENUM_TRAILING_PARAMS(N, class U)>
tuple_storage(const Table &table BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(N, U,
&u))
: BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_CONSTRUCT, ~) {}
#else
template <class Table> explicit tuple_storage(const Table &) {}
#endif
BOOST_PP_REPEAT(N, BOOST_TYPE_ERASURE_TUPLE_MEMBER, `)
};
#if N != BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE
template <class Tuple> struct get_impl<N, Tuple> {
typedef any<typename Tuple::concept_type,
typename Tuple::BOOST_PP_CAT(tag_type, N)>
value_type;
typedef value_type &type;
static type call(Tuple &arg) { return arg.impl.BOOST_PP_CAT(t, N); }
};
template <class Tuple> struct get_impl<N, const Tuple> {
typedef any<typename Tuple::concept_type,
typename Tuple::BOOST_PP_CAT(tag_type, N)>
value_type;
typedef const value_type &type;
static type call(const Tuple &arg) { return arg.impl.BOOST_PP_CAT(t, N); }
};
#endif
} // namespace detail
template <class Concept BOOST_PP_ENUM_TRAILING_PARAMS(N, class T)>
class tuple
#if N != BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE
<Concept BOOST_PP_ENUM_TRAILING_PARAMS(N, T)>
#endif
: public tuple_base<tuple<Concept BOOST_PP_ENUM_TRAILING_PARAMS(N, T)>> {
typedef Concept concept_type;
BOOST_PP_REPEAT(N, BOOST_TYPE_ERASURE_TAG_TYPEDEF, ~)
public:
typedef ::boost::mpl::int_<N> tuple_size;
#if N
template <BOOST_PP_ENUM_PARAMS(N, class U)>
#endif
BOOST_TYPE_ERASURE_EXPLICIT tuple(BOOST_PP_ENUM_BINARY_PARAMS(N, U, &u))
: impl(::boost::type_erasure::make_binding<
::boost::mpl::map<BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_PAIR, ~)>>()
BOOST_PP_ENUM_TRAILING_PARAMS(N, u)) {
}
#if N
template <BOOST_PP_ENUM_PARAMS(N, class U)>
BOOST_TYPE_ERASURE_EXPLICIT tuple(BOOST_PP_ENUM_BINARY_PARAMS(N, const U, &u))
: impl(::boost::type_erasure::make_binding<
::boost::mpl::map<BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_PAIR, ~)>>()
BOOST_PP_ENUM_TRAILING_PARAMS(N, u)) {}
#endif
private:
template <int M, class Tuple>
friend struct ::boost::type_erasure::detail::get_impl;
::boost::type_erasure::detail::tuple_storage<
Concept BOOST_PP_ENUM_TRAILING_PARAMS(N, T)>
impl;
};
#undef BOOST_TYPE_ERASURE_EXPLICIT
#undef BOOST_TYPE_ERASURE_TUPLE_MEMBER
#undef BOOST_TYPE_ERASURE_CONSTRUCT
#undef BOOST_TYPE_ERASURE_PAIR
#undef BOOST_TYPE_ERASURE_TAG_TYPEDEF
#undef N
#endif
| 17,204 | 6,064 |
/*
* OpenSplice DDS
*
* This software and documentation are Copyright 2006 to TO_YEAR PrismTech
* Limited, its affiliated companies and licensors. 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
*/
#include <org/opensplice/pub/qos/DataWriterQosImpl.hpp>
namespace org
{
namespace opensplice
{
namespace pub
{
namespace qos
{
DataWriterQosImpl::DataWriterQosImpl() : strength_(0), lifecycle_(true)
{ }
DataWriterQosImpl::DataWriterQosImpl(const org::opensplice::topic::qos::TopicQosImpl& tqos)
: durability_(tqos.policy<dds::core::policy::Durability>()),
#ifdef OMG_DDS_PERSISTENCE_SUPPORT
durability_service_(tqos.policy<dds::core::policy::DurabilityService>()),
#endif
deadline_(tqos.policy<dds::core::policy::Deadline>()),
budget_(tqos.policy<dds::core::policy::LatencyBudget>()),
liveliness_(tqos.policy<dds::core::policy::Liveliness>()),
reliability_(tqos.policy<dds::core::policy::Reliability>()),
order_(tqos.policy<dds::core::policy::DestinationOrder>()),
history_(tqos.policy<dds::core::policy::History>()),
resources_(tqos.policy<dds::core::policy::ResourceLimits>()),
priority_(tqos.policy<dds::core::policy::TransportPriority>()),
lifespan_(tqos.policy<dds::core::policy::Lifespan>()),
ownership_(tqos.policy<dds::core::policy::Ownership>()),
strength_(0)
{ }
DataWriterQosImpl::DataWriterQosImpl(
dds::core::policy::UserData user_data,
dds::core::policy::Durability durability,
#ifdef OMG_DDS_PERSISTENCE_SUPPORT
dds::core::policy::DurabilityService durability_service,
#endif // OMG_DDS_PERSISTENCE_SUPPORT
dds::core::policy::Deadline deadline,
dds::core::policy::LatencyBudget budget,
dds::core::policy::Liveliness liveliness,
dds::core::policy::Reliability reliability,
dds::core::policy::DestinationOrder order,
dds::core::policy::History history,
dds::core::policy::ResourceLimits resources,
dds::core::policy::TransportPriority priority,
dds::core::policy::Lifespan lifespan,
dds::core::policy::Ownership ownership,
#ifdef OMG_DDS_OWNERSHIP_SUPPORT
dds::core::policy::OwnershipStrength strength,
#endif // OMG_DDS_OWNERSHIP_SUPPORT
dds::core::policy::WriterDataLifecycle lifecycle)
: user_data_(user_data),
durability_(durability),
#ifdef OMG_DDS_PERSISTENCE_SUPPORT
durability_service_(durability_service),
#endif // OMG_DDS_PERSISTENCE_SUPPORT
deadline_(deadline),
budget_(budget),
liveliness_(liveliness),
reliability_(reliability),
order_(order),
history_(history),
resources_(resources),
priority_(priority),
lifespan_(lifespan),
ownership_(ownership),
strength_(strength),
lifecycle_(lifecycle) {}
DataWriterQosImpl::~DataWriterQosImpl() { }
void DataWriterQosImpl::policy(const dds::core::policy::UserData& user_data)
{
user_data_ = user_data;
}
void DataWriterQosImpl::policy(const dds::core::policy::Durability& durability)
{
durability_ = durability;
}
#ifdef OMG_DDS_PERSISTENCE_SUPPORT
void DataWriterQosImpl::policy(const dds::core::policy::DurabilityService& durability_service)
{
durability_service_ = durability_service;
}
#endif // OMG_DDS_PERSISTENCE_SUPPORT
void DataWriterQosImpl::policy(const dds::core::policy::Deadline& deadline)
{
deadline_ = deadline;
}
void DataWriterQosImpl::policy(const dds::core::policy::LatencyBudget& budget)
{
budget_ = budget;
}
void DataWriterQosImpl::policy(const dds::core::policy::Liveliness& liveliness)
{
liveliness_ = liveliness;
}
void DataWriterQosImpl::policy(const dds::core::policy::Reliability& reliability)
{
reliability_ = reliability;
}
void DataWriterQosImpl::policy(const dds::core::policy::DestinationOrder& order)
{
order_ = order;
}
void DataWriterQosImpl::policy(const dds::core::policy::History& history)
{
history_ = history;
}
void DataWriterQosImpl::policy(const dds::core::policy::ResourceLimits& resources)
{
resources_ = resources;
}
void DataWriterQosImpl::policy(const dds::core::policy::TransportPriority& priority)
{
priority_ = priority;
}
void DataWriterQosImpl::policy(const dds::core::policy::Lifespan& lifespan)
{
lifespan_ = lifespan;
}
void DataWriterQosImpl::policy(const dds::core::policy::Ownership& ownership)
{
ownership_ = ownership;
}
#ifdef OMG_DDS_OWNERSHIP_SUPPORT
void
DataWriterQosImpl::policy(const dds::core::policy::OwnershipStrength& strength)
{
strength_ = strength;
}
#endif // OMG_DDS_OWNERSHIP_SUPPORT
void
DataWriterQosImpl::policy(const dds::core::policy::WriterDataLifecycle& lifecycle)
{
lifecycle_ = lifecycle;
}
}
}
}
}
| 5,419 | 1,874 |
#include "netcdf/lpm_netcdf.hpp"
#ifdef LPM_USE_NETCDF
#include "util/lpm_string_util.hpp"
#include <sstream>
namespace Lpm {
template <typename Geo>
void NcWriter<Geo>::open() {
int retval = nc_create(fname.c_str(), NC_NETCDF4 | NC_CLOBBER, &ncid);
CHECK_NCERR(retval);
text_att_type att = std::make_pair("LPM", "Lagrangian Particle Methods");
define_file_attribute(att);
att = std::make_pair("LPM_version", std::string(version()));
define_file_attribute(att);
att = std::make_pair("LPM_revision", std::string(revision()));
define_file_attribute(att);
att = std::make_pair("LPM_has_uncommitted_changes", (has_uncomitted_changes() ? "true" : "false"));
define_file_attribute(att);
}
template <typename Geo>
void NcWriter<Geo>::define_file_attribute(const text_att_type& att_pair) const {
const int att_len = att_pair.second.size();
int retval = nc_put_att_text(ncid, NC_GLOBAL, att_pair.first.c_str(), att_len,
att_pair.second.c_str());
CHECK_NCERR(retval);
}
template <typename Geo>
void NcWriter<Geo>::define_time_dim() {
LPM_ASSERT(ncid != NC_EBADID);
LPM_REQUIRE_MSG(time_dimid == NC_EBADID, "time dimension already defined.");
int retval = nc_def_dim(ncid, "time", NC_UNLIMITED, &time_dimid);
CHECK_NCERR(retval);
n_nc_dims++;
int varid = NC_EBADID;
retval = nc_def_var(ncid, "time", nc_real_type::value, 1, &time_dimid, &varid);
CHECK_NCERR(retval);
const auto unit_str = ekat::units::to_string(ekat::units::s);
retval = nc_put_att_text(ncid, varid, "units", unit_str.size(), unit_str.c_str());
CHECK_NCERR(retval);
name_varid_map.emplace("time", varid);
add_time_value(0);
}
template <typename Geo>
void NcWriter<Geo>::add_time_value(const Real t) const {
const int varid = name_varid_map.at("time");
size_t next_time_idx = 0;
int retval = nc_inq_dimlen(ncid, time_dimid, &next_time_idx);
CHECK_NCERR(retval);
retval = nc_put_var1(ncid, varid, &next_time_idx, &t);
CHECK_NCERR(retval);
}
template <typename Geo>
void NcWriter<Geo>::define_particles_dim(const Index np) {
LPM_ASSERT(ncid != NC_EBADID);
LPM_REQUIRE(particles_dimid != NC_EBADID);
int retval = nc_def_dim(ncid, "n_particles", np, &particles_dimid);
CHECK_NCERR(retval);
n_nc_dims++;
}
template <typename Geo>
void NcWriter<Geo>::define_coord_dim() {
LPM_ASSERT(ncid != NC_EBADID);
LPM_REQUIRE(coord_dimid == NC_EBADID);
int retval = nc_def_dim(ncid, "coord", Geo::ndim, &coord_dimid);
CHECK_NCERR(retval);
n_nc_dims++;
}
template <typename Geo> template <FieldLocation FL>
void NcWriter<Geo>::define_scalar_field(const ScalarField<FL>& s) {
LPM_ASSERT(ncid != NC_EBADID);
LPM_ASSERT(time_dimid != NC_EBADID);
int m_ndims = 2;
int dimids[2];
dimids[0] = time_dimid;
std::string loc_string;
switch (FL) {
case( ParticleField ) : {
LPM_REQUIRE(particles_dimid != NC_EBADID);
dimids[1] = particles_dimid;
break;
}
case( VertexField ) : {
LPM_REQUIRE(vertices_dimid != NC_EBADID);
dimids[1] = vertices_dimid;
break;
}
case( EdgeField ) : {
LPM_REQUIRE(edges_dimid != NC_EBADID);
dimids[1] = edges_dimid;
break;
}
case( FaceField ) : {
LPM_REQUIRE(faces_dimid != NC_EBADID);
dimids[1] = faces_dimid;
break;
}
}
int varid = NC_EBADID;
int retval = nc_def_var(ncid, s.name.c_str(), nc_real_type::value, m_ndims, dimids, &varid);
CHECK_NCERR(retval);
name_varid_map.emplace(s.name, varid);
for (auto& md : s.metadata) {
retval = nc_put_att_text(ncid, varid, md.first.c_str(), md.second.size(), md.second.c_str());
CHECK_NCERR(retval);
}
}
template <typename Geo>
void NcWriter<Geo>::define_edges(const Edges& edges) {
LPM_ASSERT(ncid != NC_EBADID);
LPM_REQUIRE_MSG(edges_dimid == NC_EBADID, "edges dimension already defined.");
LPM_REQUIRE(two_dimid == NC_EBADID);
int retval = nc_def_dim(ncid, "edges", edges.nh(), &edges_dimid);
CHECK_NCERR(retval);
n_nc_dims++;
retval = nc_def_dim(ncid, "two", 2, &two_dimid);
CHECK_NCERR(retval);
n_nc_dims++;
const auto nedges = edges.nh();
const auto nmaxedges = edges.n_max();
const auto nleaves = edges._hn_leaves();
int origs_varid = NC_EBADID;
int dests_varid = NC_EBADID;
int lefts_varid = NC_EBADID;
int rights_varid = NC_EBADID;
int kids_varid = NC_EBADID;
int parents_varid = NC_EBADID;
retval = nc_def_var(ncid, "edges.origs", nc_index_type::value, 1, &edges_dimid, &origs_varid);
CHECK_NCERR(retval);
name_varid_map.emplace("edges.origs", origs_varid);
retval = nc_put_att(ncid, NC_GLOBAL, "edges.n_max", nc_index_type::value, 1, &nmaxedges);
CHECK_NCERR(retval);
retval = nc_put_att(ncid, NC_GLOBAL, "edges.n_leaves", nc_index_type::value, 1, &nleaves);
CHECK_NCERR(retval);
retval = nc_def_var(ncid, "edges.dests", nc_index_type::value, 1, &edges_dimid, &dests_varid);
CHECK_NCERR(retval);
name_varid_map.emplace("edges.dests", dests_varid);
retval = nc_def_var(ncid, "edges.lefts", nc_index_type::value, 1, &edges_dimid, &lefts_varid);
CHECK_NCERR(retval);
name_varid_map.emplace("edges.lefts", lefts_varid);
retval = nc_def_var(ncid, "edges.rights", nc_index_type::value, 1, &edges_dimid, &rights_varid);
CHECK_NCERR(retval);
name_varid_map.emplace("edges.rights", rights_varid);
const int kid_dims[2] = {edges_dimid, two_dimid};
retval = nc_def_var(ncid, "edges.kids", nc_index_type::value, 2, kid_dims, &kids_varid);
CHECK_NCERR(retval);
name_varid_map.emplace("edges.kids", kids_varid);
retval = nc_def_var(ncid, "edges.parent", nc_index_type::value, 1, &edges_dimid, &parents_varid);
CHECK_NCERR(retval);
name_varid_map.emplace("edges.parent", parents_varid);
const size_t start = 0;
const size_t count = nedges;
retval = nc_put_vara(ncid, origs_varid, &start, &count, edges._ho.data());
CHECK_NCERR(retval);
retval = nc_put_vara(ncid, dests_varid, &start, &count, edges._hd.data());
CHECK_NCERR(retval);
retval = nc_put_vara(ncid, lefts_varid, &start, &count, edges._hl.data());
CHECK_NCERR(retval);
retval = nc_put_vara(ncid, rights_varid, &start, &count, edges._hr.data());
CHECK_NCERR(retval);
retval = nc_put_vara(ncid, parents_varid, &start, &count, edges._hp.data());
for (size_t i=0; i<nedges; ++i) {
for (size_t j=0; j<2; ++j) {
const size_t idx[2] = {i,j};
const auto kid_idx = edges.kid_host(i,j);
retval = nc_put_var1(ncid, kids_varid, idx, &kid_idx);
CHECK_NCERR(retval);
}
}
}
template <typename Geo> template <typename FaceType>
void NcWriter<Geo>::define_faces(const Faces<FaceType, Geo>& faces) {
LPM_ASSERT(ncid != NC_EBADID);
LPM_REQUIRE_MSG(faces_dimid == NC_EBADID, "faces dimension already defined.");
LPM_REQUIRE(facekind_dimid == NC_EBADID);
LPM_REQUIRE(coord_dimid != NC_EBADID);
int retval = nc_def_dim(ncid, "faces", faces.nh(), &faces_dimid);
CHECK_NCERR(retval);
n_nc_dims++;
retval = nc_def_dim(ncid, "four", 4, &four_dimid);
CHECK_NCERR(retval);
n_nc_dims++;
retval = nc_def_dim(ncid, "facekind", FaceType::nverts, &facekind_dimid);
CHECK_NCERR(retval);
n_nc_dims++;
const auto nmaxfaces = faces.n_max();
const auto nfaces = faces.nh();
const auto nleaves = faces.n_leaves_host();
int mask_varid = NC_EBADID;
int verts_varid = NC_EBADID;
int edges_varid = NC_EBADID;
int phys_crd_varid = NC_EBADID;
int lag_crd_varid = NC_EBADID;
int level_varid = NC_EBADID;
int parents_varid = NC_EBADID;
int kids_varid = NC_EBADID;
int area_varid = NC_EBADID;
int crd_inds_varid = NC_EBADID;
retval = nc_def_var(ncid, "faces.mask", NC_UBYTE, 1, &faces_dimid, &mask_varid);
CHECK_NCERR(retval);
name_varid_map.emplace("faces.mask", mask_varid);
const int vert_and_edge_dims[2] = {faces_dimid, facekind_dimid};
retval = nc_def_var(ncid, "faces.vertices", nc_index_type::value, 2, vert_and_edge_dims, &verts_varid);
CHECK_NCERR(retval);
name_varid_map.emplace("faces.vertices", verts_varid);
retval = nc_def_var(ncid, "faces.edges", nc_index_type::value, 2, vert_and_edge_dims,
&edges_varid);
CHECK_NCERR(retval);
name_varid_map.emplace("faces.edges", edges_varid);
retval = nc_def_var(ncid, "faces.crd_inds", nc_index_type::value, 1, &faces_dimid, &crd_inds_varid);
CHECK_NCERR(retval);
name_varid_map.emplace("faces.crd_inds", crd_inds_varid);
retval = nc_def_var(ncid, "faces.level", NC_INT, 1, &faces_dimid, &level_varid);
CHECK_NCERR(retval);
name_varid_map.emplace("faces.level", level_varid);
retval = nc_def_var(ncid, "faces.parent", nc_index_type::value, 1, &faces_dimid, &parents_varid);
CHECK_NCERR(retval);
name_varid_map.emplace("faces.parent", parents_varid);
const int kid_dims[2] = {faces_dimid, four_dimid};
retval = nc_def_var(ncid, "faces.kids", nc_index_type::value, 2, kid_dims, &kids_varid);
CHECK_NCERR(retval);
name_varid_map.emplace("faces.kids", kids_varid);
retval = nc_put_att(ncid, NC_GLOBAL, "faces.n_leaves", nc_index_type::value, 1, &nleaves);
CHECK_NCERR(retval);
retval = nc_put_att(ncid, NC_GLOBAL, "faces.n_max", nc_index_type::value, 1, &nmaxfaces);
CHECK_NCERR(retval);
const int pcrd_dims[3] = {time_dimid, faces_dimid, coord_dimid};
retval = nc_def_var(ncid, "faces.phys_crds", nc_real_type::value, 3, pcrd_dims, &phys_crd_varid);
CHECK_NCERR(retval);
name_varid_map.emplace("faces.phys_crds", phys_crd_varid);
const int lcrd_dims[2] = {faces_dimid, coord_dimid};
retval = nc_def_var(ncid, "faces.lag_crds", nc_real_type::value, 2, lcrd_dims,
&lag_crd_varid);
CHECK_NCERR(retval);
name_varid_map.emplace("faces.lag_crds", lag_crd_varid);
retval = nc_def_var(ncid, "faces.area", nc_real_type::value, 1, &faces_dimid, &area_varid);
CHECK_NCERR(retval);
name_varid_map.emplace("faces.area", area_varid);
const auto area_unit_str = ekat::units::to_string(ekat::units::m * ekat::units::m);
retval = nc_put_att_text(ncid, area_varid, "units", area_unit_str.size(), area_unit_str.c_str());
for (size_t i=0; i<nfaces; ++i) {
const size_t mask_idx = i;
const uint_fast8_t mask_val = (faces._hmask(i) ? 1 : 0);
retval = nc_put_var1(ncid, mask_varid, &mask_idx, &mask_val);
CHECK_NCERR(retval);
for (size_t j=0; j<4; ++j) {
const size_t kids_idx[2] = {i,j};
retval = nc_put_var1(ncid, kids_varid, kids_idx, &faces._hostkids(i,j));
CHECK_NCERR(retval);
}
for (size_t j=0; j<FaceType::nverts; ++j) {
const size_t vert_and_edge_idx[2] = {i,j};
retval = nc_put_var1(ncid, verts_varid, vert_and_edge_idx, &faces._hostverts(i,j));
CHECK_NCERR(retval);
retval = nc_put_var1(ncid, edges_varid, vert_and_edge_idx, &faces._hostedges(i,j));
}
for (size_t j=0; j<Geo::ndim; ++j) {
const size_t pcrd_idx[3] = {0, i, j};
const size_t lcrd_idx[2] = {i,j};
const Real pcrd_val = faces.phys_crds->get_crd_component_host(i,j);
const Real lcrd_val = faces.lag_crds->get_crd_component_host(i,j);
retval = nc_put_var1(ncid, phys_crd_varid, pcrd_idx, &pcrd_val);
CHECK_NCERR(retval);
retval = nc_put_var1(ncid, lag_crd_varid, lcrd_idx, &lcrd_val);
CHECK_NCERR(retval);
}
}
const size_t start = 0;
const size_t count = nfaces;
retval = nc_put_vara(ncid, crd_inds_varid, &start, &count, faces._host_crd_inds.data());
CHECK_NCERR(retval);
retval = nc_put_vara(ncid, parents_varid, &start, &count, faces._hostparent.data());
CHECK_NCERR(retval);
retval = nc_put_vara(ncid, area_varid, &start, &count, faces._hostarea.data());
CHECK_NCERR(retval);
retval = nc_put_vara(ncid, level_varid, &start, &count, faces._hlevel.data());
CHECK_NCERR(retval);
}
template <typename Geo>
void NcWriter<Geo>::update_crds(const size_t time_idx, const int varid, const Coords<Geo>& crds) {
LPM_ASSERT(ncid != NC_EBADID);
LPM_REQUIRE(varid != NC_EBADID);
LPM_REQUIRE_MSG(time_idx < n_timesteps(), "time variable must be defined before adding timestep data.");
for (size_t i=0; i<crds.nh(); ++i) {
for (size_t j=0; j<Geo::ndim; ++j) {
const size_t idx[3] = {time_idx, i, j};
const Real crd_val = crds.get_crd_component_host(i,j);
int retval = nc_put_var1(ncid, varid, idx, &crd_val);
CHECK_NCERR(retval);
}
}
}
template <typename Geo> template <typename SeedType>
void NcWriter<Geo>::define_polymesh(const PolyMesh2d<SeedType>& mesh) {
define_vertices(mesh.vertices);
define_edges(mesh.edges);
define_faces(mesh.faces);
int varid = NC_EBADID;
int* ignore_me;
int retval = nc_def_var(ncid, "base_tree_depth", NC_INT, 0, ignore_me, &varid);
CHECK_NCERR(retval);
name_varid_map.emplace("base_tree_depth", varid);
const auto mesh_id_str = SeedType::id_string();
retval = nc_put_att_text(ncid, NC_GLOBAL, "MeshSeed", mesh_id_str.size(), mesh_id_str.c_str());
CHECK_NCERR(retval);
}
template <typename Geo>
void NcWriter<Geo>::update_particle_phys_crds(const size_t time_idx, const Coords<Geo>& pcrds) {
//TODO after particle class is defined
}
template <typename Geo>
void NcWriter<Geo>::update_vertex_phys_crds(const size_t time_idx, const Vertices<Coords<Geo>>& verts) {
update_crds(time_idx, name_varid_map.at("vertices.phys_crds"), *(verts.phys_crds));
}
template <typename Geo> template <FieldLocation FL>
void NcWriter<Geo>::put_scalar_field(const size_t time_idx, const ScalarField<FL>& s) {
LPM_REQUIRE(time_idx < n_timesteps());
const int varid = name_varid_map.at(s.name);
const size_t start[2] = {time_idx, 0};
size_t count[2];
count[0] = 1;
switch (FL) {
case (ParticleField) : {
count[1] = n_particles();
break;
}
case( VertexField ) : {
count[1] = n_vertices();
break;
}
case( EdgeField ) : {
count[1] = n_edges();
break;
}
case( FaceField ) : {
count[1] = n_faces();
break;
}
}
int retval = nc_put_vara(ncid, varid, start, count, s.hview.data());
CHECK_NCERR(retval);
}
template <typename Geo> template <FieldLocation FL>
void NcWriter<Geo>::put_vector_field(const size_t time_idx, const VectorField<Geo,FL>& v) {
LPM_REQUIRE(time_idx < n_timesteps());
const int varid = name_varid_map.at(v.name);
Index n_entries;
switch (FL) {
case (ParticleField) : {
n_entries = n_particles();
break;
}
case( VertexField ) : {
n_entries = n_vertices();
break;
}
case( EdgeField ) : {
n_entries = n_edges();
break;
}
case( FaceField ) : {
n_entries = n_faces();
break;
}
}
for (size_t i=0; i<n_entries; ++i) {
for (size_t j=0; j<Geo::ndim; ++j) {
const size_t idx[3] = {time_idx, i, j};
int retval = nc_put_var1(ncid, varid, idx, &v.hview(i,j));
CHECK_NCERR(retval);
}
}
}
template <typename Geo> template <typename FaceType>
void NcWriter<Geo>::update_face_phys_crds(const size_t time_idx, const Faces<FaceType, Geo>& faces) {
update_crds(time_idx, name_varid_map.at("faces.phys_crds"), *(faces.phys_crds));
const size_t start[2] = {time_idx, 0};
const size_t count[2] = {1, faces.nh()};
int retval = nc_put_vara(ncid, name_varid_map.at("faces.area"), start, count, faces._hostarea.data());
}
template <typename Geo>
void NcWriter<Geo>::define_vertices(const Vertices<Coords<Geo>>& vertices) {
LPM_ASSERT(ncid != NC_EBADID);
LPM_REQUIRE_MSG(vertices_dimid == NC_EBADID, "vertices dimension already defined.");
const Index nverts = vertices.nh();
int retval = nc_def_dim(ncid, "vertices", vertices.nh(), &vertices_dimid);
CHECK_NCERR(retval);
n_nc_dims++;
const auto h_inds = vertices.host_crd_inds();
{
int varid = NC_EBADID;
retval = nc_def_var(ncid, "vertices.crd_inds", nc_index_type::value, 1, &vertices_dimid, &varid);
CHECK_NCERR(retval);
name_varid_map.emplace("vertices.crd_inds", varid);
size_t start=0;
size_t count=nverts;
retval = nc_put_vara(ncid, varid, &start, &count, h_inds.data());
CHECK_NCERR(retval);
const auto nmaxverts = vertices.n_max();
retval = nc_put_att(ncid, NC_GLOBAL, "vertices.n_max", nc_index_type::value, 1, &nmaxverts);
CHECK_NCERR(retval);
}
{
int varid = NC_EBADID;
const int m_ndims = 3;
const int dimids[3] = {time_dimid, vertices_dimid, coord_dimid};
retval = nc_def_var(ncid, "vertices.phys_crds", nc_real_type::value, m_ndims, dimids, &varid);
CHECK_NCERR(retval);
name_varid_map.emplace("vertices.phys_crds", varid);
for (size_t i=0; i<nverts; ++i) {
for (size_t j=0; j<Geo::ndim; ++j) {
const size_t idx[3] = {0, i, j};
const Real crd_val = vertices.phys_crds->get_crd_component_host(h_inds(i),j);
retval = nc_put_var1(ncid, varid, idx, &crd_val);
CHECK_NCERR(retval);
}
}
}
{
int varid = NC_EBADID;
const int m_ndims = 2;
const int dimids[2] = {vertices_dimid, coord_dimid};
retval = nc_def_var(ncid, "vertices.lag_crds", nc_real_type::value, m_ndims, dimids, &varid);
CHECK_NCERR(retval);
name_varid_map.emplace("vertices.lag_crds", varid);
for (size_t i=0; i<nverts; ++i) {
for (size_t j=0; j<Geo::ndim; ++j) {
const size_t idx[2] = {i, j};
const Real crd_val = vertices.lag_crds->get_crd_component_host(h_inds(i),j);
retval = nc_put_var1(ncid, varid, idx, &crd_val);
CHECK_NCERR(retval);
}
}
}
{
//TODO: If verts are dual...
}
}
template <typename Geo>
std::string NcWriter<Geo>::info_string(const int tab_level) const {
auto tabstr = indent_string(tab_level);
std::ostringstream ss;
ss << tabstr << "NcWriter info:\n";
tabstr += "\t";
ss << tabstr << "filename: " << fname << "\n";
ss << tabstr << "ncid: " << ncid << "\n";
ss << tabstr << "n_nc_dims: " << n_nc_dims << "\n";
ss << tabstr << "variables:\n";
for (auto& v : name_varid_map) {
ss << "\t" << v.first << "\n";
}
return ss.str();
}
template <typename Geo> template <FieldLocation FL>
void NcWriter<Geo>::define_vector_field(const VectorField<Geo,FL>& v) {
LPM_ASSERT(ncid != NC_EBADID);
LPM_ASSERT(time_dimid != NC_EBADID);
LPM_ASSERT(coord_dimid != NC_EBADID);
int m_ndims = 3;
int dimids[3];
dimids[0] = time_dimid;
dimids[2] = coord_dimid;
switch (FL) {
case( ParticleField ) : {
LPM_REQUIRE(particles_dimid != NC_EBADID);
dimids[1] = particles_dimid;
break;
}
case( VertexField ) : {
LPM_REQUIRE(vertices_dimid != NC_EBADID);
dimids[1] = vertices_dimid;
break;
}
case( EdgeField ) : {
LPM_REQUIRE(edges_dimid != NC_EBADID);
dimids[1] = edges_dimid;
break;
}
case( FaceField ) : {
LPM_REQUIRE(faces_dimid != NC_EBADID);
dimids[1] = faces_dimid;
break;
}
}
int varid = NC_EBADID;
int retval = nc_def_var(ncid, v.name.c_str(), nc_real_type::value, m_ndims, dimids, &varid);
CHECK_NCERR(retval);
name_varid_map.emplace(v.name, varid);
for (auto& md : v.metadata) {
retval = nc_put_att_text(ncid, varid, md.first.c_str(), md.second.size(), md.second.c_str());
CHECK_NCERR(retval);
}
}
template <typename Geo>
void NcWriter<Geo>::define_single_real_var(const std::string& name,
const ekat::units::Units& units, const Real val, const std::vector<text_att_type> metadata) {
LPM_ASSERT(ncid != NC_EBADID);
int* ignore_me;
int varid = NC_EBADID;
int retval = nc_def_var(ncid, name.c_str(), nc_real_type::value, 0, ignore_me, &varid);
CHECK_NCERR(retval);
name_varid_map.emplace(name, varid);
const auto unitstr = ekat::units::to_string(units);
retval = nc_put_att_text(ncid, varid, "units", unitstr.size(), unitstr.c_str());
for (auto& md : metadata) {
retval = nc_put_att_text(ncid, varid, md.first.c_str(), md.second.size(), md.second.c_str());
CHECK_NCERR(retval);
}
retval = nc_put_var(ncid, varid, &val);
}
template <typename Geo>
void NcWriter<Geo>::close() {
int retval = nc_close(ncid);
CHECK_NCERR(retval);
}
template <typename Geo>
Index NcWriter<Geo>::n_timesteps() const {
size_t nsteps;
int retval = nc_inq_dimlen(ncid, time_dimid, &nsteps);
CHECK_NCERR(retval);
return Index(nsteps);
}
template <typename Geo>
Index NcWriter<Geo>::n_particles() const {
size_t np;
int retval = nc_inq_dimlen(ncid, particles_dimid, &np);
CHECK_NCERR(retval);
return Index(np);
}
template <typename Geo>
Index NcWriter<Geo>::n_vertices() const {
size_t nverts;
int retval = nc_inq_dimlen(ncid, vertices_dimid, &nverts);
if (retval == NC_EBADDIM) {
nverts = 0;
}
else {
CHECK_NCERR(retval);
}
return Index(nverts);
}
template <typename Geo>
Index NcWriter<Geo>::n_edges() const {
size_t nedges;
int retval = nc_inq_dimlen(ncid, edges_dimid, &nedges);
if (retval == NC_EBADDIM) {
nedges = 0;
}
else {
CHECK_NCERR(retval);
}
return Index(nedges);
}
template <typename Geo>
Index NcWriter<Geo>::n_faces() const {
size_t nfaces;
int retval = nc_inq_dimlen(ncid, faces_dimid, &nfaces);
if (retval == NC_EBADDIM) {
nfaces = 0;
}
else {
CHECK_NCERR(retval);
}
return Index(nfaces);
}
template <typename SeedType>
std::shared_ptr<PolyMesh2d<SeedType>> PolymeshReader::init_polymesh() {
auto result = std::shared_ptr<PolyMesh2d<SeedType>>(new PolyMesh2d<SeedType>(nmaxverts, nmaxedges, nmaxfaces));
fill_vertices(result->vertices);
fill_edges(result->edges);
fill_faces(result->faces);
fill_crds(*(result->vertices.phys_crds), *(result->vertices.lag_crds),
*(result->faces.phys_crds), *(result->faces.lag_crds));
result->update_device();
return result;
}
template <typename Geo>
void PolymeshReader::fill_vertices(Vertices<Coords<Geo>>& verts) {
LPM_ASSERT(vertices_dimid != NC_EBADID);
const Index nverts = n_vertices();
verts._nh() = nverts;
auto h_vert_crds = verts.host_crd_inds();
const size_t start = 0;
const size_t count = nverts;
int retval = nc_get_vara(ncid, name_varid_map.at("vertices.crd_inds"), &start, &count, h_vert_crds.data());
CHECK_NCERR(retval);
}
template <typename FaceType, typename Geo>
void PolymeshReader::fill_faces(Faces<FaceType, Geo>& faces) {
LPM_ASSERT(faces_dimid != NC_EBADID);
LPM_ASSERT(facekind_dimid != NC_EBADID);
size_t nfaceverts;
int retval = nc_inq_dimlen(ncid, facekind_dimid, &nfaceverts);
CHECK_NCERR(retval);
LPM_REQUIRE(nfaceverts == FaceType::nverts);
const Index nfaces = n_faces();
Index nleaves;
retval = nc_get_att(ncid, NC_GLOBAL, "faces.n_leaves", &nleaves);
faces._nh() = nfaces;
faces._hn_leaves() = nleaves;
{
const size_t start = 0;
const size_t count = nfaces;
retval = nc_get_vara(ncid, name_varid_map.at("faces.crd_inds"), &start, &count, faces._host_crd_inds.data());
CHECK_NCERR(retval);
retval = nc_get_vara(ncid, name_varid_map.at("faces.parent"), &start, &count, faces._hostparent.data());
CHECK_NCERR(retval);
retval = nc_get_vara(ncid, name_varid_map.at("faces.level"), &start, &count, faces._hlevel.data());
CHECK_NCERR(retval);
retval = nc_get_vara(ncid, name_varid_map.at("faces.area"), &start, &count, faces._hostarea.data());
}
for (size_t i=0; i<nfaces; ++i) {
size_t idx1 = i;
uint_fast8_t mask_val;
retval = nc_get_var1(ncid, name_varid_map.at("faces.mask"), &idx1, &mask_val);
CHECK_NCERR(retval);
faces._hmask(i) = (mask_val > 0 ? true : false);
for (size_t j=0; j<nfaceverts; ++j) {
size_t idx2[2] = {i,j};
retval = nc_get_var1(ncid, name_varid_map.at("faces.vertices"), idx2, &faces._hostverts(i,j));
CHECK_NCERR(retval);
retval = nc_get_var1(ncid, name_varid_map.at("faces.edges"), idx2, &faces._hostedges(i,j));
CHECK_NCERR(retval);
}
for (size_t j=0; j<4; ++j) {
size_t idx3[2] = {i,j};
retval = nc_get_var1(ncid, name_varid_map.at("faces.kids"), idx3, &faces._hostkids(i,j));
}
}
}
template <typename Geo>
void PolymeshReader::fill_crds(Coords<Geo>& vert_phys_crds, Coords<Geo>& vert_lag_crds,
Coords<Geo>& face_phys_crds, Coords<Geo>& face_lag_crds) {
const Index nverts = n_vertices();
vert_phys_crds._nh() = nverts;
vert_lag_crds._nh() = nverts;
const size_t last_time_idx = n_timesteps()-1;
for (size_t i=0; i<nverts; ++i) {
for (size_t j=0; j<Geo::ndim; ++j) {
const size_t pidx[3] = {last_time_idx, i,j};
const size_t lidx[2] = {i,j};
Real pcrdval;
Real lcrdval;
int retval = nc_get_var1(ncid, name_varid_map.at("vertices.phys_crds"), pidx, &pcrdval);
CHECK_NCERR(retval);
retval = nc_get_var1(ncid, name_varid_map.at("vertices.lag_crds"), lidx, &lcrdval);
CHECK_NCERR(retval);
vert_phys_crds._hostcrds(i,j) = pcrdval;
vert_lag_crds._hostcrds(i,j) = lcrdval;
}
}
const Index nfaces = n_faces();
face_phys_crds._nh() = nfaces;
face_lag_crds._nh() = nfaces;
for (size_t i=0; i<nfaces; ++i) {
for (size_t j=0; j<Geo::ndim; ++j) {
const size_t pidx[3] = {last_time_idx, i,j};
const size_t lidx[2] = {i,j};
Real pcrdval;
Real lcrdval;
int retval = nc_get_var1(ncid, name_varid_map.at("faces.phys_crds"), pidx, &pcrdval);
CHECK_NCERR(retval);
retval = nc_get_var1(ncid, name_varid_map.at("faces.lag_crds"), lidx, &lcrdval);
CHECK_NCERR(retval);
face_phys_crds._hostcrds(i,j) = pcrdval;
face_lag_crds._hostcrds(i,j) = lcrdval;
}
}
}
// ETI
template class NcWriter<PlaneGeometry>;
template class NcWriter<SphereGeometry>;
}
#endif
| 25,506 | 11,143 |
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/core/utils/Outcome.h>
#include <aws/core/auth/AWSAuthSigner.h>
#include <aws/core/client/CoreErrors.h>
#include <aws/core/client/RetryStrategy.h>
#include <aws/core/http/HttpClient.h>
#include <aws/core/http/HttpResponse.h>
#include <aws/core/http/HttpClientFactory.h>
#include <aws/core/auth/AWSCredentialsProviderChain.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <aws/core/utils/threading/Executor.h>
#include <aws/pinpoint-email/PinpointEmailClient.h>
#include <aws/pinpoint-email/PinpointEmailEndpoint.h>
#include <aws/pinpoint-email/PinpointEmailErrorMarshaller.h>
#include <aws/pinpoint-email/model/CreateConfigurationSetRequest.h>
#include <aws/pinpoint-email/model/CreateConfigurationSetEventDestinationRequest.h>
#include <aws/pinpoint-email/model/CreateDedicatedIpPoolRequest.h>
#include <aws/pinpoint-email/model/CreateEmailIdentityRequest.h>
#include <aws/pinpoint-email/model/DeleteConfigurationSetRequest.h>
#include <aws/pinpoint-email/model/DeleteConfigurationSetEventDestinationRequest.h>
#include <aws/pinpoint-email/model/DeleteDedicatedIpPoolRequest.h>
#include <aws/pinpoint-email/model/DeleteEmailIdentityRequest.h>
#include <aws/pinpoint-email/model/GetAccountRequest.h>
#include <aws/pinpoint-email/model/GetConfigurationSetRequest.h>
#include <aws/pinpoint-email/model/GetConfigurationSetEventDestinationsRequest.h>
#include <aws/pinpoint-email/model/GetDedicatedIpRequest.h>
#include <aws/pinpoint-email/model/GetDedicatedIpsRequest.h>
#include <aws/pinpoint-email/model/GetEmailIdentityRequest.h>
#include <aws/pinpoint-email/model/ListConfigurationSetsRequest.h>
#include <aws/pinpoint-email/model/ListDedicatedIpPoolsRequest.h>
#include <aws/pinpoint-email/model/ListEmailIdentitiesRequest.h>
#include <aws/pinpoint-email/model/PutAccountDedicatedIpWarmupAttributesRequest.h>
#include <aws/pinpoint-email/model/PutAccountSendingAttributesRequest.h>
#include <aws/pinpoint-email/model/PutConfigurationSetDeliveryOptionsRequest.h>
#include <aws/pinpoint-email/model/PutConfigurationSetReputationOptionsRequest.h>
#include <aws/pinpoint-email/model/PutConfigurationSetSendingOptionsRequest.h>
#include <aws/pinpoint-email/model/PutConfigurationSetTrackingOptionsRequest.h>
#include <aws/pinpoint-email/model/PutDedicatedIpInPoolRequest.h>
#include <aws/pinpoint-email/model/PutDedicatedIpWarmupAttributesRequest.h>
#include <aws/pinpoint-email/model/PutEmailIdentityDkimAttributesRequest.h>
#include <aws/pinpoint-email/model/PutEmailIdentityFeedbackAttributesRequest.h>
#include <aws/pinpoint-email/model/PutEmailIdentityMailFromAttributesRequest.h>
#include <aws/pinpoint-email/model/SendEmailRequest.h>
#include <aws/pinpoint-email/model/UpdateConfigurationSetEventDestinationRequest.h>
using namespace Aws;
using namespace Aws::Auth;
using namespace Aws::Client;
using namespace Aws::PinpointEmail;
using namespace Aws::PinpointEmail::Model;
using namespace Aws::Http;
using namespace Aws::Utils::Json;
static const char* SERVICE_NAME = "ses";
static const char* ALLOCATION_TAG = "PinpointEmailClient";
PinpointEmailClient::PinpointEmailClient(const Client::ClientConfiguration& clientConfiguration) :
BASECLASS(clientConfiguration,
Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<DefaultAWSCredentialsProviderChain>(ALLOCATION_TAG),
SERVICE_NAME, clientConfiguration.region),
Aws::MakeShared<PinpointEmailErrorMarshaller>(ALLOCATION_TAG)),
m_executor(clientConfiguration.executor)
{
init(clientConfiguration);
}
PinpointEmailClient::PinpointEmailClient(const AWSCredentials& credentials, const Client::ClientConfiguration& clientConfiguration) :
BASECLASS(clientConfiguration,
Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<SimpleAWSCredentialsProvider>(ALLOCATION_TAG, credentials),
SERVICE_NAME, clientConfiguration.region),
Aws::MakeShared<PinpointEmailErrorMarshaller>(ALLOCATION_TAG)),
m_executor(clientConfiguration.executor)
{
init(clientConfiguration);
}
PinpointEmailClient::PinpointEmailClient(const std::shared_ptr<AWSCredentialsProvider>& credentialsProvider,
const Client::ClientConfiguration& clientConfiguration) :
BASECLASS(clientConfiguration,
Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, credentialsProvider,
SERVICE_NAME, clientConfiguration.region),
Aws::MakeShared<PinpointEmailErrorMarshaller>(ALLOCATION_TAG)),
m_executor(clientConfiguration.executor)
{
init(clientConfiguration);
}
PinpointEmailClient::~PinpointEmailClient()
{
}
void PinpointEmailClient::init(const ClientConfiguration& config)
{
Aws::StringStream ss;
ss << SchemeMapper::ToString(config.scheme) << "://";
if(config.endpointOverride.empty())
{
ss << PinpointEmailEndpoint::ForRegion(config.region, config.useDualStack);
}
else
{
ss << config.endpointOverride;
}
m_uri = ss.str();
}
CreateConfigurationSetOutcome PinpointEmailClient::CreateConfigurationSet(const CreateConfigurationSetRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/configuration-sets";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return CreateConfigurationSetOutcome(CreateConfigurationSetResult(outcome.GetResult()));
}
else
{
return CreateConfigurationSetOutcome(outcome.GetError());
}
}
CreateConfigurationSetOutcomeCallable PinpointEmailClient::CreateConfigurationSetCallable(const CreateConfigurationSetRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< CreateConfigurationSetOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateConfigurationSet(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::CreateConfigurationSetAsync(const CreateConfigurationSetRequest& request, const CreateConfigurationSetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->CreateConfigurationSetAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::CreateConfigurationSetAsyncHelper(const CreateConfigurationSetRequest& request, const CreateConfigurationSetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, CreateConfigurationSet(request), context);
}
CreateConfigurationSetEventDestinationOutcome PinpointEmailClient::CreateConfigurationSetEventDestination(const CreateConfigurationSetEventDestinationRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/configuration-sets/";
ss << request.GetConfigurationSetName();
ss << "/event-destinations";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return CreateConfigurationSetEventDestinationOutcome(CreateConfigurationSetEventDestinationResult(outcome.GetResult()));
}
else
{
return CreateConfigurationSetEventDestinationOutcome(outcome.GetError());
}
}
CreateConfigurationSetEventDestinationOutcomeCallable PinpointEmailClient::CreateConfigurationSetEventDestinationCallable(const CreateConfigurationSetEventDestinationRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< CreateConfigurationSetEventDestinationOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateConfigurationSetEventDestination(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::CreateConfigurationSetEventDestinationAsync(const CreateConfigurationSetEventDestinationRequest& request, const CreateConfigurationSetEventDestinationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->CreateConfigurationSetEventDestinationAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::CreateConfigurationSetEventDestinationAsyncHelper(const CreateConfigurationSetEventDestinationRequest& request, const CreateConfigurationSetEventDestinationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, CreateConfigurationSetEventDestination(request), context);
}
CreateDedicatedIpPoolOutcome PinpointEmailClient::CreateDedicatedIpPool(const CreateDedicatedIpPoolRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/dedicated-ip-pools";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return CreateDedicatedIpPoolOutcome(CreateDedicatedIpPoolResult(outcome.GetResult()));
}
else
{
return CreateDedicatedIpPoolOutcome(outcome.GetError());
}
}
CreateDedicatedIpPoolOutcomeCallable PinpointEmailClient::CreateDedicatedIpPoolCallable(const CreateDedicatedIpPoolRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< CreateDedicatedIpPoolOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateDedicatedIpPool(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::CreateDedicatedIpPoolAsync(const CreateDedicatedIpPoolRequest& request, const CreateDedicatedIpPoolResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->CreateDedicatedIpPoolAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::CreateDedicatedIpPoolAsyncHelper(const CreateDedicatedIpPoolRequest& request, const CreateDedicatedIpPoolResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, CreateDedicatedIpPool(request), context);
}
CreateEmailIdentityOutcome PinpointEmailClient::CreateEmailIdentity(const CreateEmailIdentityRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/identities";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return CreateEmailIdentityOutcome(CreateEmailIdentityResult(outcome.GetResult()));
}
else
{
return CreateEmailIdentityOutcome(outcome.GetError());
}
}
CreateEmailIdentityOutcomeCallable PinpointEmailClient::CreateEmailIdentityCallable(const CreateEmailIdentityRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< CreateEmailIdentityOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateEmailIdentity(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::CreateEmailIdentityAsync(const CreateEmailIdentityRequest& request, const CreateEmailIdentityResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->CreateEmailIdentityAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::CreateEmailIdentityAsyncHelper(const CreateEmailIdentityRequest& request, const CreateEmailIdentityResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, CreateEmailIdentity(request), context);
}
DeleteConfigurationSetOutcome PinpointEmailClient::DeleteConfigurationSet(const DeleteConfigurationSetRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/configuration-sets/";
ss << request.GetConfigurationSetName();
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_DELETE, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return DeleteConfigurationSetOutcome(DeleteConfigurationSetResult(outcome.GetResult()));
}
else
{
return DeleteConfigurationSetOutcome(outcome.GetError());
}
}
DeleteConfigurationSetOutcomeCallable PinpointEmailClient::DeleteConfigurationSetCallable(const DeleteConfigurationSetRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< DeleteConfigurationSetOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteConfigurationSet(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::DeleteConfigurationSetAsync(const DeleteConfigurationSetRequest& request, const DeleteConfigurationSetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->DeleteConfigurationSetAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::DeleteConfigurationSetAsyncHelper(const DeleteConfigurationSetRequest& request, const DeleteConfigurationSetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, DeleteConfigurationSet(request), context);
}
DeleteConfigurationSetEventDestinationOutcome PinpointEmailClient::DeleteConfigurationSetEventDestination(const DeleteConfigurationSetEventDestinationRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/configuration-sets/";
ss << request.GetConfigurationSetName();
ss << "/event-destinations/";
ss << request.GetEventDestinationName();
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_DELETE, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return DeleteConfigurationSetEventDestinationOutcome(DeleteConfigurationSetEventDestinationResult(outcome.GetResult()));
}
else
{
return DeleteConfigurationSetEventDestinationOutcome(outcome.GetError());
}
}
DeleteConfigurationSetEventDestinationOutcomeCallable PinpointEmailClient::DeleteConfigurationSetEventDestinationCallable(const DeleteConfigurationSetEventDestinationRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< DeleteConfigurationSetEventDestinationOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteConfigurationSetEventDestination(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::DeleteConfigurationSetEventDestinationAsync(const DeleteConfigurationSetEventDestinationRequest& request, const DeleteConfigurationSetEventDestinationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->DeleteConfigurationSetEventDestinationAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::DeleteConfigurationSetEventDestinationAsyncHelper(const DeleteConfigurationSetEventDestinationRequest& request, const DeleteConfigurationSetEventDestinationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, DeleteConfigurationSetEventDestination(request), context);
}
DeleteDedicatedIpPoolOutcome PinpointEmailClient::DeleteDedicatedIpPool(const DeleteDedicatedIpPoolRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/dedicated-ip-pools/";
ss << request.GetPoolName();
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_DELETE, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return DeleteDedicatedIpPoolOutcome(DeleteDedicatedIpPoolResult(outcome.GetResult()));
}
else
{
return DeleteDedicatedIpPoolOutcome(outcome.GetError());
}
}
DeleteDedicatedIpPoolOutcomeCallable PinpointEmailClient::DeleteDedicatedIpPoolCallable(const DeleteDedicatedIpPoolRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< DeleteDedicatedIpPoolOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteDedicatedIpPool(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::DeleteDedicatedIpPoolAsync(const DeleteDedicatedIpPoolRequest& request, const DeleteDedicatedIpPoolResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->DeleteDedicatedIpPoolAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::DeleteDedicatedIpPoolAsyncHelper(const DeleteDedicatedIpPoolRequest& request, const DeleteDedicatedIpPoolResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, DeleteDedicatedIpPool(request), context);
}
DeleteEmailIdentityOutcome PinpointEmailClient::DeleteEmailIdentity(const DeleteEmailIdentityRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/identities/";
ss << request.GetEmailIdentity();
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_DELETE, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return DeleteEmailIdentityOutcome(DeleteEmailIdentityResult(outcome.GetResult()));
}
else
{
return DeleteEmailIdentityOutcome(outcome.GetError());
}
}
DeleteEmailIdentityOutcomeCallable PinpointEmailClient::DeleteEmailIdentityCallable(const DeleteEmailIdentityRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< DeleteEmailIdentityOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteEmailIdentity(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::DeleteEmailIdentityAsync(const DeleteEmailIdentityRequest& request, const DeleteEmailIdentityResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->DeleteEmailIdentityAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::DeleteEmailIdentityAsyncHelper(const DeleteEmailIdentityRequest& request, const DeleteEmailIdentityResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, DeleteEmailIdentity(request), context);
}
GetAccountOutcome PinpointEmailClient::GetAccount(const GetAccountRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/account";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return GetAccountOutcome(GetAccountResult(outcome.GetResult()));
}
else
{
return GetAccountOutcome(outcome.GetError());
}
}
GetAccountOutcomeCallable PinpointEmailClient::GetAccountCallable(const GetAccountRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< GetAccountOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetAccount(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::GetAccountAsync(const GetAccountRequest& request, const GetAccountResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->GetAccountAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::GetAccountAsyncHelper(const GetAccountRequest& request, const GetAccountResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, GetAccount(request), context);
}
GetConfigurationSetOutcome PinpointEmailClient::GetConfigurationSet(const GetConfigurationSetRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/configuration-sets/";
ss << request.GetConfigurationSetName();
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return GetConfigurationSetOutcome(GetConfigurationSetResult(outcome.GetResult()));
}
else
{
return GetConfigurationSetOutcome(outcome.GetError());
}
}
GetConfigurationSetOutcomeCallable PinpointEmailClient::GetConfigurationSetCallable(const GetConfigurationSetRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< GetConfigurationSetOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetConfigurationSet(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::GetConfigurationSetAsync(const GetConfigurationSetRequest& request, const GetConfigurationSetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->GetConfigurationSetAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::GetConfigurationSetAsyncHelper(const GetConfigurationSetRequest& request, const GetConfigurationSetResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, GetConfigurationSet(request), context);
}
GetConfigurationSetEventDestinationsOutcome PinpointEmailClient::GetConfigurationSetEventDestinations(const GetConfigurationSetEventDestinationsRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/configuration-sets/";
ss << request.GetConfigurationSetName();
ss << "/event-destinations";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return GetConfigurationSetEventDestinationsOutcome(GetConfigurationSetEventDestinationsResult(outcome.GetResult()));
}
else
{
return GetConfigurationSetEventDestinationsOutcome(outcome.GetError());
}
}
GetConfigurationSetEventDestinationsOutcomeCallable PinpointEmailClient::GetConfigurationSetEventDestinationsCallable(const GetConfigurationSetEventDestinationsRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< GetConfigurationSetEventDestinationsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetConfigurationSetEventDestinations(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::GetConfigurationSetEventDestinationsAsync(const GetConfigurationSetEventDestinationsRequest& request, const GetConfigurationSetEventDestinationsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->GetConfigurationSetEventDestinationsAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::GetConfigurationSetEventDestinationsAsyncHelper(const GetConfigurationSetEventDestinationsRequest& request, const GetConfigurationSetEventDestinationsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, GetConfigurationSetEventDestinations(request), context);
}
GetDedicatedIpOutcome PinpointEmailClient::GetDedicatedIp(const GetDedicatedIpRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/dedicated-ips/";
ss << request.GetIp();
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return GetDedicatedIpOutcome(GetDedicatedIpResult(outcome.GetResult()));
}
else
{
return GetDedicatedIpOutcome(outcome.GetError());
}
}
GetDedicatedIpOutcomeCallable PinpointEmailClient::GetDedicatedIpCallable(const GetDedicatedIpRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< GetDedicatedIpOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetDedicatedIp(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::GetDedicatedIpAsync(const GetDedicatedIpRequest& request, const GetDedicatedIpResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->GetDedicatedIpAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::GetDedicatedIpAsyncHelper(const GetDedicatedIpRequest& request, const GetDedicatedIpResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, GetDedicatedIp(request), context);
}
GetDedicatedIpsOutcome PinpointEmailClient::GetDedicatedIps(const GetDedicatedIpsRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/dedicated-ips";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return GetDedicatedIpsOutcome(GetDedicatedIpsResult(outcome.GetResult()));
}
else
{
return GetDedicatedIpsOutcome(outcome.GetError());
}
}
GetDedicatedIpsOutcomeCallable PinpointEmailClient::GetDedicatedIpsCallable(const GetDedicatedIpsRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< GetDedicatedIpsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetDedicatedIps(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::GetDedicatedIpsAsync(const GetDedicatedIpsRequest& request, const GetDedicatedIpsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->GetDedicatedIpsAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::GetDedicatedIpsAsyncHelper(const GetDedicatedIpsRequest& request, const GetDedicatedIpsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, GetDedicatedIps(request), context);
}
GetEmailIdentityOutcome PinpointEmailClient::GetEmailIdentity(const GetEmailIdentityRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/identities/";
ss << request.GetEmailIdentity();
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return GetEmailIdentityOutcome(GetEmailIdentityResult(outcome.GetResult()));
}
else
{
return GetEmailIdentityOutcome(outcome.GetError());
}
}
GetEmailIdentityOutcomeCallable PinpointEmailClient::GetEmailIdentityCallable(const GetEmailIdentityRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< GetEmailIdentityOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetEmailIdentity(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::GetEmailIdentityAsync(const GetEmailIdentityRequest& request, const GetEmailIdentityResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->GetEmailIdentityAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::GetEmailIdentityAsyncHelper(const GetEmailIdentityRequest& request, const GetEmailIdentityResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, GetEmailIdentity(request), context);
}
ListConfigurationSetsOutcome PinpointEmailClient::ListConfigurationSets(const ListConfigurationSetsRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/configuration-sets";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return ListConfigurationSetsOutcome(ListConfigurationSetsResult(outcome.GetResult()));
}
else
{
return ListConfigurationSetsOutcome(outcome.GetError());
}
}
ListConfigurationSetsOutcomeCallable PinpointEmailClient::ListConfigurationSetsCallable(const ListConfigurationSetsRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< ListConfigurationSetsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListConfigurationSets(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::ListConfigurationSetsAsync(const ListConfigurationSetsRequest& request, const ListConfigurationSetsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->ListConfigurationSetsAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::ListConfigurationSetsAsyncHelper(const ListConfigurationSetsRequest& request, const ListConfigurationSetsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, ListConfigurationSets(request), context);
}
ListDedicatedIpPoolsOutcome PinpointEmailClient::ListDedicatedIpPools(const ListDedicatedIpPoolsRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/dedicated-ip-pools";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return ListDedicatedIpPoolsOutcome(ListDedicatedIpPoolsResult(outcome.GetResult()));
}
else
{
return ListDedicatedIpPoolsOutcome(outcome.GetError());
}
}
ListDedicatedIpPoolsOutcomeCallable PinpointEmailClient::ListDedicatedIpPoolsCallable(const ListDedicatedIpPoolsRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< ListDedicatedIpPoolsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListDedicatedIpPools(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::ListDedicatedIpPoolsAsync(const ListDedicatedIpPoolsRequest& request, const ListDedicatedIpPoolsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->ListDedicatedIpPoolsAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::ListDedicatedIpPoolsAsyncHelper(const ListDedicatedIpPoolsRequest& request, const ListDedicatedIpPoolsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, ListDedicatedIpPools(request), context);
}
ListEmailIdentitiesOutcome PinpointEmailClient::ListEmailIdentities(const ListEmailIdentitiesRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/identities";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return ListEmailIdentitiesOutcome(ListEmailIdentitiesResult(outcome.GetResult()));
}
else
{
return ListEmailIdentitiesOutcome(outcome.GetError());
}
}
ListEmailIdentitiesOutcomeCallable PinpointEmailClient::ListEmailIdentitiesCallable(const ListEmailIdentitiesRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< ListEmailIdentitiesOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListEmailIdentities(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::ListEmailIdentitiesAsync(const ListEmailIdentitiesRequest& request, const ListEmailIdentitiesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->ListEmailIdentitiesAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::ListEmailIdentitiesAsyncHelper(const ListEmailIdentitiesRequest& request, const ListEmailIdentitiesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, ListEmailIdentities(request), context);
}
PutAccountDedicatedIpWarmupAttributesOutcome PinpointEmailClient::PutAccountDedicatedIpWarmupAttributes(const PutAccountDedicatedIpWarmupAttributesRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/account/dedicated-ips/warmup";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_PUT, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return PutAccountDedicatedIpWarmupAttributesOutcome(PutAccountDedicatedIpWarmupAttributesResult(outcome.GetResult()));
}
else
{
return PutAccountDedicatedIpWarmupAttributesOutcome(outcome.GetError());
}
}
PutAccountDedicatedIpWarmupAttributesOutcomeCallable PinpointEmailClient::PutAccountDedicatedIpWarmupAttributesCallable(const PutAccountDedicatedIpWarmupAttributesRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< PutAccountDedicatedIpWarmupAttributesOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->PutAccountDedicatedIpWarmupAttributes(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::PutAccountDedicatedIpWarmupAttributesAsync(const PutAccountDedicatedIpWarmupAttributesRequest& request, const PutAccountDedicatedIpWarmupAttributesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->PutAccountDedicatedIpWarmupAttributesAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::PutAccountDedicatedIpWarmupAttributesAsyncHelper(const PutAccountDedicatedIpWarmupAttributesRequest& request, const PutAccountDedicatedIpWarmupAttributesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, PutAccountDedicatedIpWarmupAttributes(request), context);
}
PutAccountSendingAttributesOutcome PinpointEmailClient::PutAccountSendingAttributes(const PutAccountSendingAttributesRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/account/sending";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_PUT, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return PutAccountSendingAttributesOutcome(PutAccountSendingAttributesResult(outcome.GetResult()));
}
else
{
return PutAccountSendingAttributesOutcome(outcome.GetError());
}
}
PutAccountSendingAttributesOutcomeCallable PinpointEmailClient::PutAccountSendingAttributesCallable(const PutAccountSendingAttributesRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< PutAccountSendingAttributesOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->PutAccountSendingAttributes(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::PutAccountSendingAttributesAsync(const PutAccountSendingAttributesRequest& request, const PutAccountSendingAttributesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->PutAccountSendingAttributesAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::PutAccountSendingAttributesAsyncHelper(const PutAccountSendingAttributesRequest& request, const PutAccountSendingAttributesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, PutAccountSendingAttributes(request), context);
}
PutConfigurationSetDeliveryOptionsOutcome PinpointEmailClient::PutConfigurationSetDeliveryOptions(const PutConfigurationSetDeliveryOptionsRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/configuration-sets/";
ss << request.GetConfigurationSetName();
ss << "/delivery-options";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_PUT, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return PutConfigurationSetDeliveryOptionsOutcome(PutConfigurationSetDeliveryOptionsResult(outcome.GetResult()));
}
else
{
return PutConfigurationSetDeliveryOptionsOutcome(outcome.GetError());
}
}
PutConfigurationSetDeliveryOptionsOutcomeCallable PinpointEmailClient::PutConfigurationSetDeliveryOptionsCallable(const PutConfigurationSetDeliveryOptionsRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< PutConfigurationSetDeliveryOptionsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->PutConfigurationSetDeliveryOptions(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::PutConfigurationSetDeliveryOptionsAsync(const PutConfigurationSetDeliveryOptionsRequest& request, const PutConfigurationSetDeliveryOptionsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->PutConfigurationSetDeliveryOptionsAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::PutConfigurationSetDeliveryOptionsAsyncHelper(const PutConfigurationSetDeliveryOptionsRequest& request, const PutConfigurationSetDeliveryOptionsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, PutConfigurationSetDeliveryOptions(request), context);
}
PutConfigurationSetReputationOptionsOutcome PinpointEmailClient::PutConfigurationSetReputationOptions(const PutConfigurationSetReputationOptionsRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/configuration-sets/";
ss << request.GetConfigurationSetName();
ss << "/reputation-options";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_PUT, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return PutConfigurationSetReputationOptionsOutcome(PutConfigurationSetReputationOptionsResult(outcome.GetResult()));
}
else
{
return PutConfigurationSetReputationOptionsOutcome(outcome.GetError());
}
}
PutConfigurationSetReputationOptionsOutcomeCallable PinpointEmailClient::PutConfigurationSetReputationOptionsCallable(const PutConfigurationSetReputationOptionsRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< PutConfigurationSetReputationOptionsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->PutConfigurationSetReputationOptions(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::PutConfigurationSetReputationOptionsAsync(const PutConfigurationSetReputationOptionsRequest& request, const PutConfigurationSetReputationOptionsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->PutConfigurationSetReputationOptionsAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::PutConfigurationSetReputationOptionsAsyncHelper(const PutConfigurationSetReputationOptionsRequest& request, const PutConfigurationSetReputationOptionsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, PutConfigurationSetReputationOptions(request), context);
}
PutConfigurationSetSendingOptionsOutcome PinpointEmailClient::PutConfigurationSetSendingOptions(const PutConfigurationSetSendingOptionsRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/configuration-sets/";
ss << request.GetConfigurationSetName();
ss << "/sending";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_PUT, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return PutConfigurationSetSendingOptionsOutcome(PutConfigurationSetSendingOptionsResult(outcome.GetResult()));
}
else
{
return PutConfigurationSetSendingOptionsOutcome(outcome.GetError());
}
}
PutConfigurationSetSendingOptionsOutcomeCallable PinpointEmailClient::PutConfigurationSetSendingOptionsCallable(const PutConfigurationSetSendingOptionsRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< PutConfigurationSetSendingOptionsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->PutConfigurationSetSendingOptions(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::PutConfigurationSetSendingOptionsAsync(const PutConfigurationSetSendingOptionsRequest& request, const PutConfigurationSetSendingOptionsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->PutConfigurationSetSendingOptionsAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::PutConfigurationSetSendingOptionsAsyncHelper(const PutConfigurationSetSendingOptionsRequest& request, const PutConfigurationSetSendingOptionsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, PutConfigurationSetSendingOptions(request), context);
}
PutConfigurationSetTrackingOptionsOutcome PinpointEmailClient::PutConfigurationSetTrackingOptions(const PutConfigurationSetTrackingOptionsRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/configuration-sets/";
ss << request.GetConfigurationSetName();
ss << "/tracking-options";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_PUT, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return PutConfigurationSetTrackingOptionsOutcome(PutConfigurationSetTrackingOptionsResult(outcome.GetResult()));
}
else
{
return PutConfigurationSetTrackingOptionsOutcome(outcome.GetError());
}
}
PutConfigurationSetTrackingOptionsOutcomeCallable PinpointEmailClient::PutConfigurationSetTrackingOptionsCallable(const PutConfigurationSetTrackingOptionsRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< PutConfigurationSetTrackingOptionsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->PutConfigurationSetTrackingOptions(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::PutConfigurationSetTrackingOptionsAsync(const PutConfigurationSetTrackingOptionsRequest& request, const PutConfigurationSetTrackingOptionsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->PutConfigurationSetTrackingOptionsAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::PutConfigurationSetTrackingOptionsAsyncHelper(const PutConfigurationSetTrackingOptionsRequest& request, const PutConfigurationSetTrackingOptionsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, PutConfigurationSetTrackingOptions(request), context);
}
PutDedicatedIpInPoolOutcome PinpointEmailClient::PutDedicatedIpInPool(const PutDedicatedIpInPoolRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/dedicated-ips/";
ss << request.GetIp();
ss << "/pool";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_PUT, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return PutDedicatedIpInPoolOutcome(PutDedicatedIpInPoolResult(outcome.GetResult()));
}
else
{
return PutDedicatedIpInPoolOutcome(outcome.GetError());
}
}
PutDedicatedIpInPoolOutcomeCallable PinpointEmailClient::PutDedicatedIpInPoolCallable(const PutDedicatedIpInPoolRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< PutDedicatedIpInPoolOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->PutDedicatedIpInPool(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::PutDedicatedIpInPoolAsync(const PutDedicatedIpInPoolRequest& request, const PutDedicatedIpInPoolResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->PutDedicatedIpInPoolAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::PutDedicatedIpInPoolAsyncHelper(const PutDedicatedIpInPoolRequest& request, const PutDedicatedIpInPoolResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, PutDedicatedIpInPool(request), context);
}
PutDedicatedIpWarmupAttributesOutcome PinpointEmailClient::PutDedicatedIpWarmupAttributes(const PutDedicatedIpWarmupAttributesRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/dedicated-ips/";
ss << request.GetIp();
ss << "/warmup";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_PUT, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return PutDedicatedIpWarmupAttributesOutcome(PutDedicatedIpWarmupAttributesResult(outcome.GetResult()));
}
else
{
return PutDedicatedIpWarmupAttributesOutcome(outcome.GetError());
}
}
PutDedicatedIpWarmupAttributesOutcomeCallable PinpointEmailClient::PutDedicatedIpWarmupAttributesCallable(const PutDedicatedIpWarmupAttributesRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< PutDedicatedIpWarmupAttributesOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->PutDedicatedIpWarmupAttributes(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::PutDedicatedIpWarmupAttributesAsync(const PutDedicatedIpWarmupAttributesRequest& request, const PutDedicatedIpWarmupAttributesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->PutDedicatedIpWarmupAttributesAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::PutDedicatedIpWarmupAttributesAsyncHelper(const PutDedicatedIpWarmupAttributesRequest& request, const PutDedicatedIpWarmupAttributesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, PutDedicatedIpWarmupAttributes(request), context);
}
PutEmailIdentityDkimAttributesOutcome PinpointEmailClient::PutEmailIdentityDkimAttributes(const PutEmailIdentityDkimAttributesRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/identities/";
ss << request.GetEmailIdentity();
ss << "/dkim";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_PUT, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return PutEmailIdentityDkimAttributesOutcome(PutEmailIdentityDkimAttributesResult(outcome.GetResult()));
}
else
{
return PutEmailIdentityDkimAttributesOutcome(outcome.GetError());
}
}
PutEmailIdentityDkimAttributesOutcomeCallable PinpointEmailClient::PutEmailIdentityDkimAttributesCallable(const PutEmailIdentityDkimAttributesRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< PutEmailIdentityDkimAttributesOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->PutEmailIdentityDkimAttributes(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::PutEmailIdentityDkimAttributesAsync(const PutEmailIdentityDkimAttributesRequest& request, const PutEmailIdentityDkimAttributesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->PutEmailIdentityDkimAttributesAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::PutEmailIdentityDkimAttributesAsyncHelper(const PutEmailIdentityDkimAttributesRequest& request, const PutEmailIdentityDkimAttributesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, PutEmailIdentityDkimAttributes(request), context);
}
PutEmailIdentityFeedbackAttributesOutcome PinpointEmailClient::PutEmailIdentityFeedbackAttributes(const PutEmailIdentityFeedbackAttributesRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/identities/";
ss << request.GetEmailIdentity();
ss << "/feedback";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_PUT, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return PutEmailIdentityFeedbackAttributesOutcome(PutEmailIdentityFeedbackAttributesResult(outcome.GetResult()));
}
else
{
return PutEmailIdentityFeedbackAttributesOutcome(outcome.GetError());
}
}
PutEmailIdentityFeedbackAttributesOutcomeCallable PinpointEmailClient::PutEmailIdentityFeedbackAttributesCallable(const PutEmailIdentityFeedbackAttributesRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< PutEmailIdentityFeedbackAttributesOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->PutEmailIdentityFeedbackAttributes(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::PutEmailIdentityFeedbackAttributesAsync(const PutEmailIdentityFeedbackAttributesRequest& request, const PutEmailIdentityFeedbackAttributesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->PutEmailIdentityFeedbackAttributesAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::PutEmailIdentityFeedbackAttributesAsyncHelper(const PutEmailIdentityFeedbackAttributesRequest& request, const PutEmailIdentityFeedbackAttributesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, PutEmailIdentityFeedbackAttributes(request), context);
}
PutEmailIdentityMailFromAttributesOutcome PinpointEmailClient::PutEmailIdentityMailFromAttributes(const PutEmailIdentityMailFromAttributesRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/identities/";
ss << request.GetEmailIdentity();
ss << "/mail-from";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_PUT, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return PutEmailIdentityMailFromAttributesOutcome(PutEmailIdentityMailFromAttributesResult(outcome.GetResult()));
}
else
{
return PutEmailIdentityMailFromAttributesOutcome(outcome.GetError());
}
}
PutEmailIdentityMailFromAttributesOutcomeCallable PinpointEmailClient::PutEmailIdentityMailFromAttributesCallable(const PutEmailIdentityMailFromAttributesRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< PutEmailIdentityMailFromAttributesOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->PutEmailIdentityMailFromAttributes(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::PutEmailIdentityMailFromAttributesAsync(const PutEmailIdentityMailFromAttributesRequest& request, const PutEmailIdentityMailFromAttributesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->PutEmailIdentityMailFromAttributesAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::PutEmailIdentityMailFromAttributesAsyncHelper(const PutEmailIdentityMailFromAttributesRequest& request, const PutEmailIdentityMailFromAttributesResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, PutEmailIdentityMailFromAttributes(request), context);
}
SendEmailOutcome PinpointEmailClient::SendEmail(const SendEmailRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/outbound-emails";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return SendEmailOutcome(SendEmailResult(outcome.GetResult()));
}
else
{
return SendEmailOutcome(outcome.GetError());
}
}
SendEmailOutcomeCallable PinpointEmailClient::SendEmailCallable(const SendEmailRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< SendEmailOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->SendEmail(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::SendEmailAsync(const SendEmailRequest& request, const SendEmailResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->SendEmailAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::SendEmailAsyncHelper(const SendEmailRequest& request, const SendEmailResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, SendEmail(request), context);
}
UpdateConfigurationSetEventDestinationOutcome PinpointEmailClient::UpdateConfigurationSetEventDestination(const UpdateConfigurationSetEventDestinationRequest& request) const
{
Aws::StringStream ss;
Aws::Http::URI uri = m_uri;
ss << "/v1/email/configuration-sets/";
ss << request.GetConfigurationSetName();
ss << "/event-destinations/";
ss << request.GetEventDestinationName();
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_PUT, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return UpdateConfigurationSetEventDestinationOutcome(UpdateConfigurationSetEventDestinationResult(outcome.GetResult()));
}
else
{
return UpdateConfigurationSetEventDestinationOutcome(outcome.GetError());
}
}
UpdateConfigurationSetEventDestinationOutcomeCallable PinpointEmailClient::UpdateConfigurationSetEventDestinationCallable(const UpdateConfigurationSetEventDestinationRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< UpdateConfigurationSetEventDestinationOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateConfigurationSetEventDestination(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void PinpointEmailClient::UpdateConfigurationSetEventDestinationAsync(const UpdateConfigurationSetEventDestinationRequest& request, const UpdateConfigurationSetEventDestinationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->UpdateConfigurationSetEventDestinationAsyncHelper( request, handler, context ); } );
}
void PinpointEmailClient::UpdateConfigurationSetEventDestinationAsyncHelper(const UpdateConfigurationSetEventDestinationRequest& request, const UpdateConfigurationSetEventDestinationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, UpdateConfigurationSetEventDestination(request), context);
}
| 59,736 | 17,499 |
/*===================================================================
BlueBerry Platform
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "berryIntroRegistry.h"
#include <berryIConfigurationElement.h>
#include <berryIExtension.h>
#include "berryIntroDescriptor.h"
#include "internal/berryRegistryReader.h"
#include "berryWorkbenchPlugin.h"
namespace berry
{
const QString IntroRegistry::TAG_INTRO = "intro";
const QString IntroRegistry::TAG_INTROPRODUCTBINDING = "introProductBinding";
const QString IntroRegistry::ATT_INTROID = "introId";
const QString IntroRegistry::ATT_PRODUCTID = "productId";
QString IntroRegistry::GetIntroForProduct(
const QString& targetProductId,
const QList<IExtension::Pointer>& extensions) const
{
for (int i = 0; i < extensions.size(); i++)
{
QList<IConfigurationElement::Pointer> elements(
extensions[i]->GetConfigurationElements());
for (int j = 0; j < elements.size(); j++)
{
if (elements[j]->GetName() == TAG_INTROPRODUCTBINDING)
{
QString introId = elements[j]->GetAttribute(ATT_INTROID);
QString productId = elements[j]->GetAttribute(ATT_PRODUCTID);
if (introId.isEmpty() || productId.isEmpty())
{
//TODO IStatus
/*
IStatus status = new Status(
IStatus.ERROR,
elements[j].getDeclaringExtension()
.getNamespace(),
IStatus.ERROR,
"introId and productId must be defined.", new IllegalArgumentException());
WorkbenchPlugin.log("Invalid intro binding", status);
*/
WorkbenchPlugin::Log(
elements[j]->GetDeclaringExtension()->GetNamespaceIdentifier()
+ ": Invalid intro binding. introId and productId must be defined");
continue;
}
if (targetProductId == productId)
{
return introId;
}
}
}
}
return "";
}
int IntroRegistry::GetIntroCount() const
{
return static_cast<int> (GetIntros().size());
}
QList<IIntroDescriptor::Pointer> IntroRegistry::GetIntros() const
{
IExtensionPoint::Pointer point =
Platform::GetExtensionRegistry()->GetExtensionPoint(
PlatformUI::PLUGIN_ID() + "." + WorkbenchRegistryConstants::PL_INTRO);
if (!point)
{
return QList<IIntroDescriptor::Pointer>();
}
QList<IExtension::Pointer> extensions(point->GetExtensions());
extensions = RegistryReader::OrderExtensions(extensions);
QList<IIntroDescriptor::Pointer> list;
for (int i = 0; i < extensions.size(); i++)
{
QList<IConfigurationElement::Pointer> elements(
extensions[i]->GetConfigurationElements());
for (int j = 0; j < elements.size(); j++)
{
if (elements[j]->GetName() == TAG_INTRO)
{
try
{
IIntroDescriptor::Pointer
descriptor(new IntroDescriptor(elements[j]));
list.push_back(descriptor);
}
catch (const CoreException& e)
{
// log an error since its not safe to open a dialog here
//TODO IStatus
WorkbenchPlugin::Log("Unable to create intro descriptor", e); // e.getStatus());
}
}
}
}
return list;
}
IIntroDescriptor::Pointer IntroRegistry::GetIntroForProduct(
const QString& targetProductId) const
{
IExtensionPoint::Pointer point =
Platform::GetExtensionRegistry()->GetExtensionPoint(
PlatformUI::PLUGIN_ID() + "." + WorkbenchRegistryConstants::PL_INTRO);
if (!point)
{
return IIntroDescriptor::Pointer();
}
QList<IExtension::Pointer> extensions(point->GetExtensions());
extensions = RegistryReader::OrderExtensions(extensions);
QString targetIntroId = GetIntroForProduct(targetProductId, extensions);
if (targetIntroId.isEmpty())
{
return IIntroDescriptor::Pointer();
}
IIntroDescriptor::Pointer descriptor;
QList<IIntroDescriptor::Pointer> intros(GetIntros());
for (int i = 0; i < intros.size(); i++)
{
if (intros[i]->GetId() == targetIntroId)
{
descriptor = intros[i];
break;
}
}
return descriptor;
}
IIntroDescriptor::Pointer IntroRegistry::GetIntro(const QString& id) const
{
QList<IIntroDescriptor::Pointer> intros(GetIntros());
for (int i = 0; i < intros.size(); i++)
{
IIntroDescriptor::Pointer desc = intros[i];
if (desc->GetId() == id)
{
return desc;
}
}
return IIntroDescriptor::Pointer();
}
}
| 4,784 | 1,435 |
/*
*
* Copyright 2013 Netflix, 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 "CadmiumCrypto.h"
#include <assert.h>
#include "CadmiumCryptoImpl.h"
using namespace std;
namespace cadmium {
using namespace base;
namespace crypto {
namespace //anonymous
{
map<string, CadmiumCrypto::Algorithm> gStr2AlgTab;
void initStr2AlgTab()
{
gStr2AlgTab["HMAC"] = CadmiumCrypto::HMAC;
gStr2AlgTab["AES-CBC"] = CadmiumCrypto::AES_CBC;
gStr2AlgTab["AES-CTR"] = CadmiumCrypto::AES_CTR;
gStr2AlgTab["AES-GCM"] = CadmiumCrypto::AES_GCM;
gStr2AlgTab["RSAES-PKCS1-v1_5"] = CadmiumCrypto::RSAES_PKCS1_V1_5;
gStr2AlgTab["RSASSA-PKCS1-v1_5"] = CadmiumCrypto::RSASSA_PKCS1_V1_5;
gStr2AlgTab["RSA-OAEP"] = CadmiumCrypto::RSA_OAEP;
gStr2AlgTab["SHA-1"] = CadmiumCrypto::SHA1;
gStr2AlgTab["SHA-224"] = CadmiumCrypto::SHA224;
gStr2AlgTab["SHA-256"] = CadmiumCrypto::SHA256;
gStr2AlgTab["SHA-384"] = CadmiumCrypto::SHA384;
gStr2AlgTab["SHA-512"] = CadmiumCrypto::SHA512;
gStr2AlgTab["AES-KW"] = CadmiumCrypto::AES_KW;
gStr2AlgTab["DH"] = CadmiumCrypto::DH;
gStr2AlgTab["PBKDF2"] = CadmiumCrypto::PBKDF2;
gStr2AlgTab["SYSTEM"] = CadmiumCrypto::SYSTEM;
}
} // anonymous namespace
// CadmiumCrypto is "compiler firewall" in front of CadmiumCryptoImpl
CadmiumCrypto::CadmiumCrypto(IDeviceInfo * pDeviceInfo)
: impl_(new CadmiumCryptoImpl(pDeviceInfo))
{
initStr2AlgTab();
}
CadmiumCrypto::~CadmiumCrypto()
{
}
CadErr CadmiumCrypto::init(const Vuc& prngSeed)
{
return impl_->init(prngSeed);
}
void CadmiumCrypto::addEntropy(const string& entropyBytes)
{
impl_->addEntropy(entropyBytes);
}
CadErr CadmiumCrypto::digest(Algorithm algorithm, const string& data, string& digest)
{
return impl_->digest(algorithm, data, digest);
}
CadErr CadmiumCrypto::importKey(KeyFormat format, const string& keyData,
const Variant& algVar, bool extractable, const vector<KeyUsage>& keyUsage,
uint32_t& keyHandle)
{
return impl_->importKey(format, keyData, algVar, extractable, keyUsage,
keyHandle);
}
CadErr CadmiumCrypto::exportKey(uint32_t keyHandle, KeyFormat format, string& keyData)
{
return impl_->exportKey(keyHandle, format, keyData);
}
CadErr CadmiumCrypto::getKeyInfo(uint32_t keyHandle, KeyType& type, bool& extractable,
Variant& algVar, vector<KeyUsage>& usage) const
{
return impl_->getKeyInfo(keyHandle, type, extractable, algVar, usage);
}
CadErr CadmiumCrypto::symKeyGen(const Variant& algVar, bool extractable,
const vector<KeyUsage> keyUsage, uint32_t &keyHandle)
{
return impl_->symKeyGen(algVar, extractable, keyUsage, keyHandle);
}
CadErr CadmiumCrypto::aesCbc(uint32_t keyHandle, const string& ivIn,
const string& dataIn, CipherOp cipherOp, string& dataOut)
{
return impl_->aesCbc(keyHandle, ivIn, dataIn, cipherOp, dataOut);
}
CadErr CadmiumCrypto::aesGcm(uint32_t keyHandle, const string& ivIn, const string& dataIn,
const string& aadIn, uint8_t taglen, CipherOp cipherOp, string& dataOut)
{
return impl_->aesGcm(keyHandle, ivIn, dataIn, aadIn, taglen, cipherOp, dataOut);
}
CadErr CadmiumCrypto::rsaCrypt(uint32_t keyHandle, const string& dataIn,
CipherOp cipherOp, string& dataOut)
{
return impl_->rsaCrypt(keyHandle, dataIn, cipherOp, dataOut);
}
CadErr CadmiumCrypto::hmac(uint32_t keyHandle, Algorithm shaAlgo, KeyUsage opUsage,
const string& data, string& hmac)
{
return impl_->hmac(keyHandle, shaAlgo, opUsage, data, hmac);
}
CadErr CadmiumCrypto::rsaKeyGen(const Variant& algVar, bool extractable,
vector<KeyUsage> keyUsage, uint32_t& pubKeyHandle, uint32_t& privKeyHandle)
{
return impl_->rsaKeyGen(algVar, extractable, keyUsage, pubKeyHandle, privKeyHandle);
}
CadErr CadmiumCrypto::rsaSign(uint32_t keyHandle, Algorithm shaAlgo, const string& data,
string& sig)
{
return impl_->rsaSign(keyHandle, shaAlgo, data, sig);
}
CadErr CadmiumCrypto::rsaVerify(uint32_t keyHandle, Algorithm shaAlgo, const string& data,
const string& sig, bool& isVerified)
{
return impl_->rsaVerify(keyHandle, shaAlgo, data, sig, isVerified);
}
CadErr CadmiumCrypto::dhKeyGen(const Variant& algVar, bool extractable,
vector<KeyUsage> keyUsage, uint32_t& pubKeyHandle, uint32_t& privKeyHandle)
{
return impl_->dhKeyGen(algVar, extractable, keyUsage, pubKeyHandle, privKeyHandle);
}
CadErr CadmiumCrypto::dhDerive(uint32_t baseKeyHandle, const string& peerPublicKeyData,
const Variant& derivedAlgObj, bool extractable, vector<KeyUsage> keyUsage,
uint32_t& keyHandle)
{
return impl_->dhDerive(baseKeyHandle, peerPublicKeyData, derivedAlgObj,
extractable, keyUsage, keyHandle);
}
CadErr CadmiumCrypto::unwrapJwe(const string& jweData, uint32_t wrappingKeyHandle,
const base::Variant& algVar, bool extractable, const vector<KeyUsage>& keyUsage,
uint32_t& keyHandle)
{
return impl_->unwrapJwe(jweData, wrappingKeyHandle, algVar, extractable,
keyUsage, keyHandle);
}
CadErr CadmiumCrypto::wrapJwe(uint32_t toBeWrappedKeyHandle, uint32_t wrappingKeyHandle,
const Variant& wrappingAlgoObj, JweEncMethod jweEncMethod, string& wrappedKeyJcs)
{
return impl_->wrapJwe(toBeWrappedKeyHandle, wrappingKeyHandle, wrappingAlgoObj,
jweEncMethod, wrappedKeyJcs);
}
CadErr CadmiumCrypto::pbkdf2Derive(const string& salt, uint32_t iterations,
const base::Variant& prf, const string& password,
const base::Variant& derivedAlgObj, bool extractable,
const vector<KeyUsage> usage, uint32_t &keyHandle)
{
return impl_->pbkdf2Derive(salt, iterations, prf, password, derivedAlgObj,
extractable, usage, keyHandle);
}
CadErr CadmiumCrypto::getKeyByName(const string keyName, uint32_t &keyHandle, string& metadata)
{
return impl_->getKeyByName(keyName, keyHandle, metadata);
}
CadErr CadmiumCrypto::getDeviceId(string& deviceId) const
{
return impl_->getDeviceId(deviceId);
}
CadErr CadmiumCrypto::getSystemKeyHandle(uint32_t& systemKeyHandle) const
{
return impl_->getSystemKeyHandle(systemKeyHandle);
}
string toString(CadmiumCrypto::Algorithm algorithm)
{
switch (algorithm)
{
case CadmiumCrypto::HMAC: return "HMAC";
case CadmiumCrypto::AES_CBC: return "AES-CBC";
case CadmiumCrypto::AES_GCM: return "AES-GCM";
case CadmiumCrypto::AES_CTR: return "AES-CTR";
case CadmiumCrypto::RSAES_PKCS1_V1_5: return "RSAES-PKCS1-v1_5";
case CadmiumCrypto::RSASSA_PKCS1_V1_5: return "RSASSA-PKCS1-v1_5";
case CadmiumCrypto::RSA_OAEP: return "RSA-OAEP";
case CadmiumCrypto::SHA1: return "SHA-1";
case CadmiumCrypto::SHA224: return "SHA-224";
case CadmiumCrypto::SHA256: return "SHA-256";
case CadmiumCrypto::SHA384: return "SHA-384";
case CadmiumCrypto::SHA512: return "SHA-512";
case CadmiumCrypto::AES_KW: return "AES-KW";
case CadmiumCrypto::DH: return "DH";
case CadmiumCrypto::PBKDF2: return "PBKDF2";
case CadmiumCrypto::SYSTEM: return "SYSTEM";
case CadmiumCrypto::INVALID_ALGORITHM:
default: return "invalid";
}
}
string toString(const vector<CadmiumCrypto::KeyUsage>& kusage)
{
string output = "[ ";
vector<CadmiumCrypto::KeyUsage>::const_iterator it;
for (it = kusage.begin(); it != kusage.end(); ++it)
output += toString(*it) + " ";
output += "]";
return output;
}
string toString(CadmiumCrypto::KeyType keyType)
{
switch (keyType)
{
case CadmiumCrypto::SECRET: return "secret"; break;
case CadmiumCrypto::PUBLIC: return "public"; break;
case CadmiumCrypto::PRIVATE: return "private"; break;
}
return "invalid";
}
string toString(CadmiumCrypto::KeyUsage keyUsage)
{
switch (keyUsage)
{
case CadmiumCrypto::ENCRYPT: return "encrypt"; break;
case CadmiumCrypto::DECRYPT: return "decrypt"; break;
case CadmiumCrypto::SIGN: return "sign"; break;
case CadmiumCrypto::VERIFY: return "verify"; break;
case CadmiumCrypto::DERIVE: return "derive"; break;
case CadmiumCrypto::WRAP: return "wrap"; break;
case CadmiumCrypto::UNWRAP: return "unwrap"; break;
}
return "invalid";
}
string toString(CadmiumCrypto::JweEncMethod jweEncMethod)
{
switch (jweEncMethod)
{
case CadmiumCrypto::A128GCM: return "A128GCM"; break;
case CadmiumCrypto::A256GCM: return "A256GCM"; break;
}
return "invalid";
}
bool isAlgorithmRsa(CadmiumCrypto::Algorithm algorithm)
{
return ( algorithm == CadmiumCrypto::RSAES_PKCS1_V1_5 ||
algorithm == CadmiumCrypto::RSASSA_PKCS1_V1_5 ||
algorithm == CadmiumCrypto::RSA_OAEP );
}
bool isAlgorithmAes(CadmiumCrypto::Algorithm algorithm)
{
return ( algorithm == CadmiumCrypto::AES_CBC ||
algorithm == CadmiumCrypto::AES_GCM ||
algorithm == CadmiumCrypto::AES_CTR ||
algorithm == CadmiumCrypto::AES_KW );
}
bool isAlgorithmHmac(CadmiumCrypto::Algorithm algorithm)
{
return ( algorithm == CadmiumCrypto::HMAC );
}
bool isAlgorithmSha(CadmiumCrypto::Algorithm algorithm)
{
return ( algorithm == CadmiumCrypto::SHA1 ||
algorithm == CadmiumCrypto::SHA224 ||
algorithm == CadmiumCrypto::SHA256 ||
algorithm == CadmiumCrypto::SHA384 ||
algorithm == CadmiumCrypto::SHA512 );
}
bool isAlgorithmDh(CadmiumCrypto::Algorithm algorithm)
{
return ( algorithm == CadmiumCrypto::DH );
}
bool isAlgorithmPbkdf2(CadmiumCrypto::Algorithm algorithm)
{
return ( algorithm == CadmiumCrypto::PBKDF2 );
}
CadmiumCrypto::Algorithm toAlgorithm(const string& algorithmStr)
{
assert(gStr2AlgTab.size());
if (!gStr2AlgTab.count(algorithmStr))
return CadmiumCrypto::INVALID_ALGORITHM;
return gStr2AlgTab[algorithmStr];
}
}} // namespace cadmium::crypto
| 10,958 | 3,925 |
//
// Horista.hpp
// PolimorfismoEmpregados
//
// Created by Vini Cassol on 29/05/20.
// Copyright © 2020 Vini Cassol. All rights reserved.
//
#ifndef Horista_hpp
#define Horista_hpp
#include "Empregado.hpp"
class Horista : public Empregado
{
public:
Horista();
double vencimento();
private:
double precoHora;
double horasTrabalhadas;
};
#endif /* Horista_hpp */
| 398 | 163 |
#include <benchmark/benchmark.h>
#include "simdjson.h"
using namespace simdjson;
using namespace benchmark;
using namespace std;
const padded_string EMPTY_ARRAY("[]", 2);
SIMDJSON_PUSH_DISABLE_WARNINGS
SIMDJSON_DISABLE_DEPRECATED_WARNING
static void json_parse(State& state) {
ParsedJson pj;
if (!pj.allocate_capacity(EMPTY_ARRAY.length())) { return; }
for (auto _ : state) {
auto error = json_parse(EMPTY_ARRAY, pj);
if (error) { return; }
}
}
SIMDJSON_POP_DISABLE_WARNINGS
BENCHMARK(json_parse);
static void parser_parse_error_code(State& state) {
dom::parser parser;
if (parser.allocate(EMPTY_ARRAY.length())) { return; }
for (auto _ : state) {
auto [doc, error] = parser.parse(EMPTY_ARRAY);
if (error) { return; }
}
}
BENCHMARK(parser_parse_error_code);
static void parser_parse_exception(State& state) {
dom::parser parser;
if (parser.allocate(EMPTY_ARRAY.length())) { return; }
for (auto _ : state) {
try {
UNUSED dom::element doc = parser.parse(EMPTY_ARRAY);
} catch(simdjson_error &j) {
return;
}
}
}
BENCHMARK(parser_parse_exception);
SIMDJSON_PUSH_DISABLE_WARNINGS
SIMDJSON_DISABLE_DEPRECATED_WARNING
static void build_parsed_json(State& state) {
for (auto _ : state) {
dom::parser parser = simdjson::build_parsed_json(EMPTY_ARRAY);
if (!parser.valid) { return; }
}
}
SIMDJSON_POP_DISABLE_WARNINGS
BENCHMARK(build_parsed_json);
static void document_parse_error_code(State& state) {
for (auto _ : state) {
dom::parser parser;
auto [doc, error] = parser.parse(EMPTY_ARRAY);
if (error) { return; }
}
}
BENCHMARK(document_parse_error_code);
static void document_parse_exception(State& state) {
for (auto _ : state) {
try {
dom::parser parser;
UNUSED dom::element doc = parser.parse(EMPTY_ARRAY);
} catch(simdjson_error &j) {
return;
}
}
}
BENCHMARK(document_parse_exception);
BENCHMARK_MAIN(); | 1,929 | 749 |
//=============================================================================================================
/**
* @file hpifit.cpp
* @author Lorenz Esch <Lorenz.Esch@tu-ilmenau.de>;
* Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version 1.0
* @date March, 2017
*
* @section LICENSE
*
* Copyright (C) 2017, Lorenz Esch and Matti Hamalainen. 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 MNE-CPP authors 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.
*
*
* @brief HPIFit class defintion.
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "hpifit.h"
#include <fiff/fiff_dig_point_set.h>
#include <utils/ioutils.h>
#include <iostream>
#include <fiff/fiff_cov.h>
#include <fstream>
//*************************************************************************************************************
//=============================================================================================================
// Eigen INCLUDES
//=============================================================================================================
#include <Eigen/SVD>
#include <Eigen/Dense>
//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QFuture>
#include <QtConcurrent/QtConcurrent>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace Eigen;
using namespace INVERSELIB;
using namespace FIFFLIB;
//*************************************************************************************************************
//=============================================================================================================
// DEFINE GLOBAL METHODS
//=============================================================================================================
Eigen::MatrixXd pinv(Eigen::MatrixXd a)
{
double epsilon = std::numeric_limits<double>::epsilon();
Eigen::JacobiSVD< Eigen::MatrixXd > svd(a ,Eigen::ComputeThinU | Eigen::ComputeThinV);
double tolerance = epsilon * std::max(a.cols(), a.rows()) * svd.singularValues().array().abs()(0);
return svd.matrixV() * (svd.singularValues().array().abs() > tolerance).select(svd.singularValues().array().inverse(),0).matrix().asDiagonal() * svd.matrixU().adjoint();
}
/*********************************************************************************
* magnetic_dipole leadfield for a magnetic dipole in an infinite medium
* The function has been compared with matlab magnetic_dipole and it gives same output
*********************************************************************************/
Eigen::MatrixXd magnetic_dipole(Eigen::MatrixXd pos, Eigen::MatrixXd pnt, Eigen::MatrixXd ori) {
double u0 = 1e-7;
int nchan;
Eigen::MatrixXd r, r2, r5, x, y, z, mx, my, mz, Tx, Ty, Tz, lf;
nchan = pnt.rows();
// Shift the magnetometers so that the dipole is in the origin
pnt.array().col(0) -= pos(0);
pnt.array().col(1) -= pos(1);
pnt.array().col(2) -= pos(2);
r = pnt.array().square().rowwise().sum().sqrt();
r2 = r5 = x = y = z = mx = my = mz = Tx = Ty = Tz = lf = Eigen::MatrixXd::Zero(nchan,3);
for(int i = 0;i < nchan;i++) {
r2.row(i).array().fill(pow(r(i),2));
r5.row(i).array().fill(pow(r(i),5));
}
for(int i = 0;i < nchan;i++) {
x.row(i).array().fill(pnt(i,0));
y.row(i).array().fill(pnt(i,1));
z.row(i).array().fill(pnt(i,2));
}
mx.col(0).array().fill(1);
my.col(1).array().fill(1);
mz.col(2).array().fill(1);
Tx = 3 * x.cwiseProduct(pnt) - mx.cwiseProduct(r2);
Ty = 3 * y.cwiseProduct(pnt) - my.cwiseProduct(r2);
Tz = 3 * z.cwiseProduct(pnt) - mz.cwiseProduct(r2);
for(int i = 0;i < nchan;i++) {
lf(i,0) = Tx.row(i).dot(ori.row(i));
lf(i,1) = Ty.row(i).dot(ori.row(i));
lf(i,2) = Tz.row(i).dot(ori.row(i));
}
for(int i = 0;i < nchan;i++) {
for(int j = 0;j < 3;j++) {
lf(i,j) = u0 * lf(i,j)/(4 * M_PI * r5(i,j));
}
}
return lf;
}
/*********************************************************************************
* compute_leadfield computes a forward solution for a dipole in a a volume
* conductor model. The forward solution is expressed as the leadfield
* matrix (Nchan*3), where each column corresponds with the potential or field
* distributions on all sensors for one of the x,y,z-orientations of the dipole.
* The function has been compared with matlab ft_compute_leadfield and it gives
* same output
*********************************************************************************/
Eigen::MatrixXd compute_leadfield(const Eigen::MatrixXd& pos, const struct SensorInfo& sensors)
{
Eigen::MatrixXd pnt, ori, lf;
pnt = sensors.coilpos; // position of each coil
ori = sensors.coilori; // orientation of each coil
lf = magnetic_dipole(pos, pnt, ori);
lf = sensors.tra * lf;
return lf;
}
/*********************************************************************************
* dipfitError computes the error between measured and model data
* and can be used for non-linear fitting of dipole position.
* The function has been compared with matlab dipfit_error and it gives
* same output
*********************************************************************************/
DipFitError dipfitError(const Eigen::MatrixXd& pos, const Eigen::MatrixXd& data, const struct SensorInfo& sensors, const Eigen::MatrixXd& matProjectors)
{
// Variable Declaration
struct DipFitError e;
Eigen::MatrixXd lf, dif;
// Compute lead field for a magnetic dipole in infinite vacuum
lf = compute_leadfield(pos, sensors);
e.moment = pinv(lf) * data;
//dif = data - lf * e.moment;
dif = data - matProjectors * lf * e.moment;
e.error = dif.array().square().sum()/data.array().square().sum();
e.numIterations = 0;
return e;
}
/*********************************************************************************
* Compare function for sorting
*********************************************************************************/
bool compare(HPISortStruct a, HPISortStruct b)
{
return (a.base_arr < b.base_arr);
}
/*********************************************************************************
* fminsearch Multidimensional unconstrained nonlinear minimization (Nelder-Mead).
* X = fminsearch(X0, maxiter, maxfun, display, data, sensors) starts at X0 and
* attempts to find a local minimizer
*********************************************************************************/
Eigen::MatrixXd fminsearch(const Eigen::MatrixXd& pos,
int maxiter,
int maxfun,
int display,
const Eigen::MatrixXd& data,
const Eigen::MatrixXd& matProjectors,
const struct SensorInfo& sensors,
int &simplex_numitr)
{
double tolx, tolf, rho, chi, psi, sigma, func_evals, usual_delta, zero_term_delta, temp1, temp2;
std::string header, how;
int n, itercount, prnt;
Eigen::MatrixXd onesn, two2np1, one2n, v, y, v1, tempX1, tempX2, xbar, xr, x, xe, xc, xcc, xin, posCopy;
std::vector <double> fv, fv1;
std::vector <int> idx;
DipFitError tempdip, fxr, fxe, fxc, fxcc;
//tolx = tolf = 1e-4;
// Seok
tolx = tolf = 1e-9;
switch(display) {
case 0:
prnt = 0;
break;
default:
prnt = 1;
}
header = " Iteration Func-count min f(x) Procedure";
posCopy = pos;
n = posCopy.cols();
// Initialize parameters
rho = 1; chi = 2; psi = 0.5; sigma = 0.5;
onesn = Eigen::MatrixXd::Ones(1,n);
two2np1 = one2n = Eigen::MatrixXd::Zero(1,n);
for(int i = 0;i < n;i++) {
two2np1(i) = 1 + i;
one2n(i) = i;
}
v = v1 = Eigen::MatrixXd::Zero(n, n+1);
fv.resize(n+1);
idx.resize(n+1);
fv1.resize(n+1);
for(int i = 0;i < n; i++) {
v(i,0) = posCopy(i);
}
tempdip = dipfitError(posCopy, data, sensors, matProjectors);
fv[0] = tempdip.error;
func_evals = 1;
itercount = 0;
how = "";
// Continue setting up the initial simplex.
// Following improvement suggested by L.Pfeffer at Stanford
usual_delta = 0.05; // 5 percent deltas for non-zero terms
zero_term_delta = 0.00025; // Even smaller delta for zero elements of x
xin = posCopy.transpose();
for(int j = 0;j < n;j++) {
y = xin;
if(y(j) != 0) {
y(j) = (1 + usual_delta) * y(j);
} else {
y(j) = zero_term_delta;
}
v.col(j+1).array() = y;
posCopy = y.transpose();
tempdip = dipfitError(posCopy, data, sensors, matProjectors);
fv[j+1] = tempdip.error;
}
// Sort elements of fv
std::vector<HPISortStruct> vecSortStruct;
for (int i = 0; i < fv.size(); i++) {
HPISortStruct structTemp;
structTemp.base_arr = fv[i];
structTemp.idx = i;
vecSortStruct.push_back(structTemp);
}
sort (vecSortStruct.begin(), vecSortStruct.end(), compare);
for (int i = 0; i < vecSortStruct.size(); i++) {
idx[i] = vecSortStruct[i].idx;
}
for (int i = 0;i < n+1;i++) {
v1.col(i) = v.col(idx[i]);
fv1[i] = fv[idx[i]];
}
v = v1;fv = fv1;
how = "initial simplex";
itercount = itercount + 1;
func_evals = n + 1;
tempX1 = Eigen::MatrixXd::Zero(1,n);
while ((func_evals < maxfun) && (itercount < maxiter)) {
for (int i = 0;i < n;i++) {
tempX1(i) = abs(fv[0] - fv[i+1]);
}
temp1 = tempX1.maxCoeff();
tempX2 = Eigen::MatrixXd::Zero(n,n);
for(int i = 0;i < n;i++) {
tempX2.col(i) = v.col(i+1) - v.col(0);
}
tempX2 = tempX2.array().abs();
temp2 = tempX2.maxCoeff();
if((temp1 <= tolf) && (temp2 <= tolx)) {
break;
}
xbar = v.block(0,0,n,n).rowwise().sum();
xbar /= n;
xr = (1+rho) * xbar - rho * v.block(0,n,v.rows(),1);
x = xr.transpose();
//std::cout << "Iteration Count: " << itercount << ":" << x << std::endl;
fxr = dipfitError(x, data, sensors, matProjectors);
func_evals = func_evals+1;
if (fxr.error < fv[0]) {
// Calculate the expansion point
xe = (1 + rho * chi) * xbar - rho * chi * v.col(v.cols()-1);
x = xe.transpose();
fxe = dipfitError(x, data, sensors, matProjectors);
func_evals = func_evals+1;
if(fxe.error < fxr.error) {
v.col(v.cols()-1) = xe;
fv[n] = fxe.error;
how = "expand";
} else {
v.col(v.cols()-1) = xr;
fv[n] = fxr.error;
how = "reflect";
}
}
else {
if(fxr.error < fv[n-1]) {
v.col(v.cols()-1) = xr;
fv[n] = fxr.error;
how = "reflect";
} else { // fxr.error >= fv[:,n-1]
// Perform contraction
if(fxr.error < fv[n]) {
// Perform an outside contraction
xc = (1 + psi * rho) * xbar - psi * rho * v.col(v.cols()-1);
x = xc.transpose();
fxc = dipfitError(x, data, sensors, matProjectors);
func_evals = func_evals + 1;
if(fxc.error <= fxr.error) {
v.col(v.cols()-1) = xc;
fv[n] = fxc.error;
how = "contract outside";
} else {
// perform a shrink
how = "shrink";
}
} else {
xcc = (1 - psi) * xbar + psi * v.col(v.cols()-1);
x = xcc.transpose();
fxcc = dipfitError(x, data, sensors, matProjectors);
func_evals = func_evals+1;
if(fxcc.error < fv[n]) {
v.col(v.cols()-1) = xcc;
fv[n] = fxcc.error;
how = "contract inside";
} else {
// perform a shrink
how = "shrink";
}
}
if(how.compare("shrink") == 0) {
for(int j = 1;j < n+1;j++) {
v.col(j).array() = v.col(0).array() + sigma * (v.col(j).array() - v.col(0).array());
x = v.col(j).array().transpose();
tempdip = dipfitError(x,data, sensors, matProjectors);
fv[j] = tempdip.error;
}
}
}
}
// Sort elements of fv
vecSortStruct.clear();
for (int i = 0; i < fv.size(); i++) {
HPISortStruct structTemp;
structTemp.base_arr = fv[i];
structTemp.idx = i;
vecSortStruct.push_back(structTemp);
}
sort (vecSortStruct.begin(), vecSortStruct.end(), compare);
for (int i = 0; i < vecSortStruct.size(); i++) {
idx[i] = vecSortStruct[i].idx;
}
for (int i = 0;i < n+1;i++) {
v1.col(i) = v.col(idx[i]);
fv1[i] = fv[idx[i]];
}
v = v1;
fv = fv1;
itercount = itercount + 1;
}
x = v.col(0).transpose();
// Seok
simplex_numitr = itercount;
return x;
}
/*********************************************************************************
* dipfit function is adapted from Fieldtrip Software. It has been
* heavily edited for use with MNE Scan Software
*********************************************************************************/
void doDipfitConcurrent(FittingCoilData& lCoilData)
{
// Initialize variables
Eigen::RowVectorXd currentCoil = lCoilData.coilPos;
Eigen::VectorXd currentData = lCoilData.sensorData;
SensorInfo currentSensors = lCoilData.sensorPos;
int display = 0;
int maxiter = 500;
int simplex_numitr = 0;
lCoilData.coilPos = fminsearch(currentCoil,
maxiter,
2 * maxiter * currentCoil.cols(),
display,
currentData,
lCoilData.matProjector,
currentSensors,
simplex_numitr);
lCoilData.errorInfo = dipfitError(currentCoil, currentData, currentSensors, lCoilData.matProjector);
lCoilData.errorInfo.numIterations = simplex_numitr;
}
//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
HPIFit::HPIFit()
{
}
//*************************************************************************************************************
void HPIFit::fitHPI(const MatrixXd& t_mat,
const Eigen::MatrixXd& t_matProjectors,
FiffCoordTrans& transDevHead,
const QVector<int>& vFreqs,
QVector<double>& vGof,
FiffDigPointSet& fittedPointSet,
FiffInfo::SPtr pFiffInfo,
bool bDoDebug,
const QString& sHPIResourceDir)
{
//Check if data was passed
if(t_mat.rows() == 0 || t_mat.cols() == 0 ) {
std::cout<<std::endl<< "HPIFit::fitHPI - No data passed. Returning.";
}
//Check if projector was passed
if(t_matProjectors.rows() == 0 || t_matProjectors.cols() == 0 ) {
std::cout<<std::endl<< "HPIFit::fitHPI - No projector passed. Returning.";
}
vGof.clear();
struct SensorInfo sensors;
struct CoilParam coil;
int numCh = pFiffInfo->nchan;
int samF = pFiffInfo->sfreq;
int samLoc = t_mat.cols(); // minimum samples required to localize numLoc times in a second
//Get HPI coils from digitizers and set number of coils
int numCoils = 0;
QList<FiffDigPoint> lHPIPoints;
for(int i = 0; i < pFiffInfo->dig.size(); ++i) {
if(pFiffInfo->dig[i].kind == FIFFV_POINT_HPI) {
numCoils++;
lHPIPoints.append(pFiffInfo->dig[i]);
}
}
//Set coil frequencies
Eigen::VectorXd coilfreq(numCoils);
if(vFreqs.size() >= numCoils) {
for(int i = 0; i < numCoils; ++i) {
coilfreq[i] = vFreqs.at(i);
//std::cout<<std::endl << coilfreq[i] << "Hz";
}
} else {
std::cout<<std::endl<< "HPIFit::fitHPI - Not enough coil frequencies specified. Returning.";
return;
}
// Initialize HPI coils location and moment
coil.pos = Eigen::MatrixXd::Zero(numCoils,3);
coil.mom = Eigen::MatrixXd::Zero(numCoils,3);
coil.dpfiterror = Eigen::VectorXd::Zero(numCoils);
coil.dpfitnumitr = Eigen::VectorXd::Zero(numCoils);
// Generate simulated data
Eigen::MatrixXd simsig(samLoc,numCoils*2);
Eigen::VectorXd time(samLoc);
for (int i = 0; i < samLoc; ++i) {
time[i] = i*1.0/samF;
}
for(int i = 0; i < numCoils; ++i) {
for(int j = 0; j < samLoc; ++j) {
simsig(j,i) = sin(2*M_PI*coilfreq[i]*time[j]);
simsig(j,i+numCoils) = cos(2*M_PI*coilfreq[i]*time[j]);
}
}
// Create digitized HPI coil position matrix
Eigen::MatrixXd headHPI(numCoils,3);
// check the pFiffInfo->dig information. If dig is empty, set the headHPI is 0;
if (lHPIPoints.size() > 0) {
for (int i = 0; i < lHPIPoints.size(); ++i) {
headHPI(i,0) = lHPIPoints.at(i).r[0];
headHPI(i,1) = lHPIPoints.at(i).r[1];
headHPI(i,2) = lHPIPoints.at(i).r[2];
}
} else {
for (int i = 0; i < numCoils; ++i) {
headHPI(i,0) = 0;
headHPI(i,1) = 0;
headHPI(i,2) = 0;
}
}
// Get the indices of inner layer channels and exclude bad channels.
//TODO: Only supports babymeg and vectorview gradiometeres for hpi fitting.
QVector<int> innerind(0);
for (int i = 0; i < numCh; ++i) {
if(pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_BABY_MAG ||
pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_PLANAR_T1 ||
pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_PLANAR_T2 ||
pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_PLANAR_T3) {
// Check if the sensor is bad, if not append to innerind
if(!(pFiffInfo->bads.contains(pFiffInfo->ch_names.at(i)))) {
innerind.append(i);
}
}
}
//Create new projector based on the excluded channels, first exclude the rows then the columns
MatrixXd matProjectorsRows(innerind.size(),t_matProjectors.cols());
MatrixXd matProjectorsInnerind(innerind.size(),innerind.size());
for (int i = 0; i < matProjectorsRows.rows(); ++i) {
matProjectorsRows.row(i) = t_matProjectors.row(innerind.at(i));
}
for (int i = 0; i < matProjectorsInnerind.cols(); ++i) {
matProjectorsInnerind.col(i) = matProjectorsRows.col(innerind.at(i));
}
//UTILSLIB::IOUtils::write_eigen_matrix(matProjectorsInnerind, "matProjectorsInnerind.txt");
//UTILSLIB::IOUtils::write_eigen_matrix(t_matProjectors, "t_matProjectors.txt");
// Initialize inner layer sensors
sensors.coilpos = Eigen::MatrixXd::Zero(innerind.size(),3);
sensors.coilori = Eigen::MatrixXd::Zero(innerind.size(),3);
sensors.tra = Eigen::MatrixXd::Identity(innerind.size(),innerind.size());
for(int i = 0; i < innerind.size(); i++) {
sensors.coilpos(i,0) = pFiffInfo->chs[innerind.at(i)].chpos.r0[0];
sensors.coilpos(i,1) = pFiffInfo->chs[innerind.at(i)].chpos.r0[1];
sensors.coilpos(i,2) = pFiffInfo->chs[innerind.at(i)].chpos.r0[2];
sensors.coilori(i,0) = pFiffInfo->chs[innerind.at(i)].chpos.ez[0];
sensors.coilori(i,1) = pFiffInfo->chs[innerind.at(i)].chpos.ez[1];
sensors.coilori(i,2) = pFiffInfo->chs[innerind.at(i)].chpos.ez[2];
}
Eigen::MatrixXd topo(innerind.size(), numCoils*2);
Eigen::MatrixXd amp(innerind.size(), numCoils);
Eigen::MatrixXd ampC(innerind.size(), numCoils);
// Get the data from inner layer channels
Eigen::MatrixXd innerdata(innerind.size(), t_mat.cols());
for(int j = 0; j < innerind.size(); ++j) {
innerdata.row(j) << t_mat.row(innerind[j]);
}
// Calculate topo
topo = innerdata * pinv(simsig).transpose(); // topo: # of good inner channel x 8
// Select sine or cosine component depending on the relative size
amp = topo.leftCols(numCoils); // amp: # of good inner channel x 4
ampC = topo.rightCols(numCoils);
for(int j = 0; j < numCoils; ++j) {
float nS = 0.0;
float nC = 0.0;
for(int i = 0; i < innerind.size(); ++i) {
nS += amp(i,j)*amp(i,j);
nC += ampC(i,j)*ampC(i,j);
}
if(nC > nS) {
for(int i = 0; i < innerind.size(); ++i) {
amp(i,j) = ampC(i,j);
}
}
}
//Find good seed point/starting point for the coil position in 3D space
//Find biggest amplitude per pickup coil (sensor) and store corresponding sensor channel index
VectorXi chIdcs(numCoils);
for (int j = 0; j < numCoils; j++) {
double maxVal = 0;
int chIdx = 0;
for (int i = 0; i < amp.rows(); ++i) {
if(abs(amp(i,j)) > maxVal) {
maxVal = abs(amp(i,j));
if(chIdx < innerind.size()) {
chIdx = innerind.at(i);
}
}
}
chIdcs(j) = chIdx;
}
//Generate seed point by projection the found channel position 3cm inwards
Eigen::MatrixXd coilPos = Eigen::MatrixXd::Zero(numCoils,3);
for (int j = 0; j < chIdcs.rows(); ++j) {
int chIdx = chIdcs(j);
if(chIdx < pFiffInfo->chs.size()) {
double x = pFiffInfo->chs.at(chIdcs(j)).chpos.r0[0];
double y = pFiffInfo->chs.at(chIdcs(j)).chpos.r0[1];
double z = pFiffInfo->chs.at(chIdcs(j)).chpos.r0[2];
coilPos(j,0) = -1 * pFiffInfo->chs.at(chIdcs(j)).chpos.ez[0] * 0.03 + x;
coilPos(j,1) = -1 * pFiffInfo->chs.at(chIdcs(j)).chpos.ez[1] * 0.03 + y;
coilPos(j,2) = -1 * pFiffInfo->chs.at(chIdcs(j)).chpos.ez[2] * 0.03 + z;
}
//std::cout << "HPIFit::fitHPI - Coil " << j << " max value index " << chIdx << std::endl;
}
coil.pos = coilPos;
coil = dipfit(coil, sensors, amp, numCoils, matProjectorsInnerind);
Eigen::Matrix4d trans = computeTransformation(headHPI, coil.pos);
//Eigen::Matrix4d trans = computeTransformation(coil.pos, headHPI);
// Store the final result to fiff info
// Set final device/head matrix and its inverse to the fiff info
transDevHead.from = 1;
transDevHead.to = 4;
for(int r = 0; r < 4; ++r) {
for(int c = 0; c < 4 ; ++c) {
transDevHead.trans(r,c) = trans(r,c);
}
}
// Also store the inverse
transDevHead.invtrans = transDevHead.trans.inverse();
//Calculate GOF
MatrixXd temp = coil.pos;
temp.conservativeResize(coil.pos.rows(),coil.pos.cols()+1);
temp.block(0,3,numCoils,1).setOnes();
temp.transposeInPlace();
MatrixXd testPos = trans * temp;
MatrixXd diffPos = testPos.block(0,0,3,numCoils) - headHPI.transpose();
for(int i = 0; i < diffPos.cols(); ++i) {
vGof.append(diffPos.col(i).norm());
}
//Generate final fitted points and store in digitizer set
for(int i = 0; i < coil.pos.rows(); ++i) {
FiffDigPoint digPoint;
digPoint.kind = FIFFV_POINT_EEG;
digPoint.ident = i;
digPoint.r[0] = coil.pos(i,0);
digPoint.r[1] = coil.pos(i,1);
digPoint.r[2] = coil.pos(i,2);
fittedPointSet << digPoint;
}
if(bDoDebug) {
// DEBUG HPI fitting and write debug results
std::cout << std::endl << std::endl << "HPIFit::fitHPI - dpfiterror" << coil.dpfiterror << std::endl << coil.pos << std::endl;
std::cout << std::endl << std::endl << "HPIFit::fitHPI - Initial seed point for HPI coils" << std::endl << coil.pos << std::endl;
std::cout << std::endl << std::endl << "HPIFit::fitHPI - temp" << std::endl << temp << std::endl;
std::cout << std::endl << std::endl << "HPIFit::fitHPI - testPos" << std::endl << testPos << std::endl;
std::cout << std::endl << std::endl << "HPIFit::fitHPI - Diff fitted - original" << std::endl << diffPos << std::endl;
std::cout << std::endl << std::endl << "HPIFit::fitHPI - dev/head trans" << std::endl << trans << std::endl;
QString sTimeStamp = QDateTime::currentDateTime().toString("yyMMdd_hhmmss");
if(!QDir(sHPIResourceDir).exists()) {
QDir().mkdir(sHPIResourceDir);
}
UTILSLIB::IOUtils::write_eigen_matrix(coilPos, QString("%1/%2_coilPosSeed_mat").arg(sHPIResourceDir).arg(sTimeStamp));
UTILSLIB::IOUtils::write_eigen_matrix(coil.pos, QString("%1/%2_coilPos_mat").arg(sHPIResourceDir).arg(sTimeStamp));
UTILSLIB::IOUtils::write_eigen_matrix(headHPI, QString("%1/%2_headHPI_mat").arg(sHPIResourceDir).arg(sTimeStamp));
MatrixXd testPosCut = testPos.transpose();//block(0,0,3,4);
UTILSLIB::IOUtils::write_eigen_matrix(testPosCut, QString("%1/%2_testPos_mat").arg(sHPIResourceDir).arg(sTimeStamp));
MatrixXi idx_mat(chIdcs.rows(),1);
idx_mat.col(0) = chIdcs;
UTILSLIB::IOUtils::write_eigen_matrix(idx_mat, QString("%1/%2_idx_mat").arg(sHPIResourceDir).arg(sTimeStamp));
MatrixXd coilFreq_mat(coilfreq.rows(),1);
coilFreq_mat.col(0) = coilfreq;
UTILSLIB::IOUtils::write_eigen_matrix(coilFreq_mat, QString("%1/%2_coilFreq_mat").arg(sHPIResourceDir).arg(sTimeStamp));
UTILSLIB::IOUtils::write_eigen_matrix(diffPos, QString("%1/%2_diffPos_mat").arg(sHPIResourceDir).arg(sTimeStamp));
UTILSLIB::IOUtils::write_eigen_matrix(amp, QString("%1/%2_amp_mat").arg(sHPIResourceDir).arg(sTimeStamp));
}
}
//*************************************************************************************************************
CoilParam HPIFit::dipfit(struct CoilParam coil, struct SensorInfo sensors, const Eigen::MatrixXd& data, int numCoils, const Eigen::MatrixXd& t_matProjectors)
{
//Do this in conncurrent mode
//Generate QList structure which can be handled by the QConcurrent framework
QList<FittingCoilData> lCoilData;
for(qint32 i = 0; i < numCoils; ++i) {
FittingCoilData coilData;
coilData.coilPos = coil.pos.row(i);
coilData.sensorData = data.col(i);
coilData.sensorPos = sensors;
coilData.matProjector = t_matProjectors;
lCoilData.append(coilData);
}
//Do the concurrent filtering
if(!lCoilData.isEmpty()) {
//Do sequential
for(int l = 0; l < lCoilData.size(); ++l) {
doDipfitConcurrent(lCoilData[l]);
}
// //Do concurrent
// QFuture<void> future = QtConcurrent::map(lCoilData,
// doDipfitConcurrent);
// future.waitForFinished();
//Transform results to final coil information
for(qint32 i = 0; i < lCoilData.size(); ++i) {
coil.pos.row(i) = lCoilData.at(i).coilPos;
coil.mom = lCoilData.at(i).errorInfo.moment.transpose();
coil.dpfiterror(i) = lCoilData.at(i).errorInfo.error;
coil.dpfitnumitr(i) = lCoilData.at(i).errorInfo.numIterations;
//std::cout<<std::endl<< "HPIFit::dipfit - Itr steps for coil " << i << " =" <<coil.dpfitnumitr(i);
}
}
return coil;
}
//*************************************************************************************************************
Eigen::Matrix4d HPIFit::computeTransformation(Eigen::MatrixXd NH, Eigen::MatrixXd BT)
{
Eigen::MatrixXd xdiff, ydiff, zdiff, C, Q;
Eigen::Matrix4d transFinal = Eigen::Matrix4d::Identity(4,4);
Eigen::Matrix4d Rot = Eigen::Matrix4d::Zero(4,4);
Eigen::Matrix4d Trans = Eigen::Matrix4d::Identity(4,4);
double meanx,meany,meanz,normf;
for(int i = 0; i < 15; ++i) {
// Calcualte mean translation for all points -> centroid of both data sets
xdiff = NH.col(0) - BT.col(0);
ydiff = NH.col(1) - BT.col(1);
zdiff = NH.col(2) - BT.col(2);
meanx = xdiff.mean();
meany = ydiff.mean();
meanz = zdiff.mean();
// Apply translation -> bring both data sets to the same center location
for (int j = 0; j < BT.rows(); ++j) {
BT(j,0) = BT(j,0) + meanx;
BT(j,1) = BT(j,1) + meany;
BT(j,2) = BT(j,2) + meanz;
}
// Estimate rotation component
C = BT.transpose() * NH;
Eigen::JacobiSVD< Eigen::MatrixXd > svd(C ,Eigen::ComputeThinU | Eigen::ComputeThinV);
Q = svd.matrixU() * svd.matrixV().transpose();
//Handle special reflection case
if(Q.determinant() < 0) {
Q(0,2) = Q(0,2) * -1;
Q(1,2) = Q(1,2) * -1;
Q(2,2) = Q(2,2) * -1;
}
// Apply rotation on translated points
BT = BT * Q;
// Calculate GOF
normf = (NH.transpose()-BT.transpose()).norm();
// Store rotation part to transformation matrix
Rot(3,3) = 1;
for(int j = 0; j < 3; ++j) {
for(int k = 0; k < 3; ++k) {
Rot(j,k) = Q(k,j);
}
}
// Store translation part to transformation matrix
Trans(0,3) = meanx;
Trans(1,3) = meany;
Trans(2,3) = meanz;
// Safe rotation and translation to final matrix for next iteration step
transFinal = Rot * Trans * transFinal;
}
return transFinal;
}
| 32,725 | 11,315 |
#pragma once
#include <stdint.h>
#include <stddef.h>
#include "Colors.hpp"
#define UNREFERENCED_PARAMETER(name) do { (void)(name); } while (0)
namespace Tex
{
//-------------------------------------------------------------------------------------
// Constants
//-------------------------------------------------------------------------------------
const size_t NUM_PIXELS_PER_BLOCK = 16;
enum BC_FLAGS
{
BC_FLAGS_NONE = 0x0,
BC_FLAGS_DITHER_RGB = 0x10000, // Enables dithering for RGB colors for BC1-3
BC_FLAGS_DITHER_A = 0x20000, // Enables dithering for Alpha channel for BC1-3
BC_FLAGS_UNIFORM = 0x40000, // By default, uses perceptual weighting for BC1-3; this flag makes it a uniform weighting
BC_FLAGS_USE_3SUBSETS = 0x80000, // By default, BC7 skips mode 0 & 2; this flag adds those modes back
BC_FLAGS_FORCE_BC7_MODE6 = 0x100000, // BC7 should only use mode 6; skip other modes
};
//-------------------------------------------------------------------------------------
// Functions
//-------------------------------------------------------------------------------------
typedef void (*BC_DECODE)(HDRColorA *pColor, const uint8_t *pBC);
typedef void (*BC_ENCODE)(uint8_t *pDXT, const HDRColorA *pColor, uint32_t flags);
void DecodeBC1(HDRColorA *pColor, const uint8_t *pBC);
void DecodeBC2(HDRColorA *pColor, const uint8_t *pBC);
void DecodeBC3(HDRColorA *pColor, const uint8_t *pBC);
void DecodeBC4U(HDRColorA *pColor, const uint8_t *pBC);
void DecodeBC4S(HDRColorA *pColor, const uint8_t *pBC);
void DecodeBC5U(HDRColorA *pColor, const uint8_t *pBC);
void DecodeBC5S(HDRColorA *pColor, const uint8_t *pBC);
void DecodeBC6HU(HDRColorA *pColor, const uint8_t *pBC);
void DecodeBC6HS(HDRColorA *pColor, const uint8_t *pBC);
void DecodeBC7(HDRColorA *pColor, const uint8_t *pBC);
void EncodeBC1(uint8_t *pBC, const HDRColorA *pColor, uint32_t flags);
// BC1 may have one additional parameter, so it doesn't match signature of BC_ENCODE above
void EncodeBC1(uint8_t *pBC, const HDRColorA *pColor, float threshold, uint32_t flags);
void EncodeBC2(uint8_t *pBC, const HDRColorA *pColor, uint32_t flags);
void EncodeBC3(uint8_t *pBC, const HDRColorA *pColor, uint32_t flags);
void EncodeBC4U(uint8_t *pBC, const HDRColorA *pColor, uint32_t flags);
void EncodeBC4S(uint8_t *pBC, const HDRColorA *pColor, uint32_t flags);
void EncodeBC5U(uint8_t *pBC, const HDRColorA *pColor, uint32_t flags);
void EncodeBC5S(uint8_t *pBC, const HDRColorA *pColor, uint32_t flags);
void EncodeBC6HU(uint8_t *pBC, const HDRColorA *pColor, uint32_t flags);
void EncodeBC6HS(uint8_t *pBC, const HDRColorA *pColor, uint32_t flags);
void EncodeBC7(uint8_t *pBC, const HDRColorA *pColor, uint32_t flags);
}; // namespace
| 2,792 | 1,065 |
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 DiMS dev-team
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcserver.h"
#include "rpcclient.h"
#include "util.h"
#include "json/json_spirit_value.h"
#include <openssl/crypto.h>
#include "common/commandLine.h"
#include <boost/thread.hpp>
namespace common
{
CCommandLine * CCommandLine::ms_instance = NULL;
CCommandLine*
CCommandLine::getInstance()
{
if ( !ms_instance )
{
ms_instance = new CCommandLine();
};
return ms_instance;
}
void
CCommandLine::reply( CMessageClass::Enum _category, std::string const & _commandResponse )
{
std::string comandResponse;
switch( _category )
{
case CMessageClass::MC_ERROR:
comandResponse = "CODE ERROR: ";
break;
case CMessageClass::MC_DEBUG:
comandResponse = "CODE DEBUG: ";
break;
case CMessageClass::CMD_REQUEST:
comandResponse = "COMMAND REQUEST: ";
break;
case CMessageClass::CMD_REPLY:
comandResponse = "COMMAND REPLY: ";
break;
case CMessageClass::CMD_ERROR:
comandResponse = "COMMAND ERROR: ";
break;
default:
break;
}
addOutputMessage( comandResponse + _commandResponse );
}
void
CCommandLine::workLoop()
{
fd_set read_fds;
timeval waitTime;
waitTime.tv_sec = 0;
waitTime.tv_usec = 0;
bool promptPrinted = false;
while ( 1 )
{
if ( !promptPrinted )
{
promptPrinted = true;
std::cout << "PROMPT > ";
std::cout.flush();
}
std::string line;
FD_ZERO(&read_fds);
FD_SET( STDIN_FILENO, &read_fds );
int result = select( FD_SETSIZE, &read_fds, NULL, NULL, &waitTime );
if (result == -1 && errno != EINTR)
{
assert(!"Error in select");
}
else if (result == -1 && errno == EINTR)
{
assert(!"problem");
}
else
{
if (FD_ISSET(STDIN_FILENO, &read_fds))
{
promptPrinted = false;
std::getline(std::cin, line);
}
}
if ( !line.empty() )
{
request( line );
}
boost::lock_guard<boost::mutex> lock( m_lock );
BOOST_FOREACH( std::string const & out, m_outputs )
{
std::cout << out << "\n\n";
}
m_outputs.clear();
MilliSleep(10);
boost::this_thread::interruption_point();
}
}
bool
CCommandLine::parseCommandLine( std::vector<std::string> & _args, const std::string & _strCommand )
{
enum CmdParseState
{
STATE_EATING_SPACES,
STATE_ARGUMENT,
STATE_SINGLEQUOTED,
STATE_DOUBLEQUOTED,
STATE_ESCAPE_OUTER,
STATE_ESCAPE_DOUBLEQUOTED
} state = STATE_EATING_SPACES;
std::string curarg;
BOOST_FOREACH( char const & ch, _strCommand )
{
switch(state)
{
case STATE_ARGUMENT: // In or after argument
case STATE_EATING_SPACES: // Handle runs of whitespace
switch(ch)
{
case '"': state = STATE_DOUBLEQUOTED; break;
case '\'': state = STATE_SINGLEQUOTED; break;
case '\\': state = STATE_ESCAPE_OUTER; break;
case ' ': case '\n': case '\t':
if( state == STATE_ARGUMENT ) // Space ends argument
{
_args.push_back(curarg);
curarg.clear();
}
state = STATE_EATING_SPACES;
break;
default: curarg += ch; state = STATE_ARGUMENT;
}
break;
case STATE_SINGLEQUOTED: // Single-quoted string
switch(ch)
{
case '\'': state = STATE_ARGUMENT; break;
default: curarg += ch;
}
break;
case STATE_DOUBLEQUOTED: // Double-quoted string
switch(ch)
{
case '"': state = STATE_ARGUMENT; break;
case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break;
default: curarg += ch;
}
break;
case STATE_ESCAPE_OUTER: // '\' outside quotes
curarg += ch; state = STATE_ARGUMENT;
break;
case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text
if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself
curarg += ch; state = STATE_DOUBLEQUOTED;
break;
}
}
switch(state) // final state
{
case STATE_EATING_SPACES:
return true;
case STATE_ARGUMENT:
_args.push_back( curarg );
return true;
default: // ERROR to end in one of the other states
return false;
}
}
void
CCommandLine::request( std::string const & _command )
{
std::vector<std::string> args;
if( !parseCommandLine( args, _command ) )
{
reply( CMessageClass::CMD_ERROR, "Parse error: unbalanced ' or \"" );
return;
}
if(args.empty())
return; // Nothing to do
try
{
std::string strPrint;
// Convert argument list to JSON objects in method-dependent way,
// and pass it along with the method name to the dispatcher.
json_spirit::Value result = tableRPC.execute(
args[0],
RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end())));
// Format result reply
if (result.type() == json_spirit::null_type)
strPrint = "";
else if (result.type() == json_spirit::str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
reply( CMessageClass::CMD_REPLY, strPrint );
}
catch (json_spirit::Object& objError)
{
try // Nice formatting for standard-format error
{
int code = find_value(objError, "code").get_int();
std::string message = find_value(objError, "message").get_str();
std::ostringstream errorStream;
errorStream << code;
reply(CMessageClass::CMD_ERROR, message + " (code " + errorStream.str() + ")");
}
catch(std::runtime_error &) // raised when converting to invalid type, i.e. missing code or message
{ // Show raw JSON object
reply( CMessageClass::CMD_ERROR, write_string( json_spirit::Value(objError), false) );
}
}
catch (std::exception& e)
{
reply( CMessageClass::CMD_ERROR, std::string("Error: ") + e.what());
}
}
}
| 5,669 | 2,390 |
/*!
* @brief Simple camera program with OpenCV
* @author <+AUTHOR+>
* @date <+DATE+>
* @file <+FILE+>
* @version 0.1
*/
#include <iostream>
#include <opencv/cv.h>
#include <opencv/highgui.h>
/*!
* @brief Entry point of the program
* @param [in] argc A number of command-line arguments
* @param [in] argv Command line arguments
* @return Exit-status
*/
int
main(int argc, char *argv[])
{
static const char WINDOW_NAME[] = "<+FILEBASE+>";
static const int WAIT_TIME = 30;
static const int CAMERA_NR = 0;
cv::VideoCapture camera(CAMERA_NR);
if (!camera.isOpened()) {
std::cerr << "Unable to open camera device" << std::endl;
return EXIT_FAILURE;
}
cv::Mat frame;
cv::namedWindow(WINDOW_NAME, CV_WINDOW_AUTOSIZE);
for (int key = cv::waitKey(WAIT_TIME); key < 0; key = cv::waitKey(WAIT_TIME)) {
camera >> frame;
<+CURSOR+>
cv::imshow(WINDOW_NAME, frame);
}
}
| 919 | 368 |
#ifndef MITAMA_MANA_FUNCTIONAL_CHUNKIFY_HPP
#define MITAMA_MANA_FUNCTIONAL_CHUNKIFY_HPP
#include <mitama/mana/algorithm/chunk.hpp>
#include <mitama/mana/algorithm/klisli.hpp>
#include <mitama/mana/utility/apply.hpp>
#include <mitama/mana/utility/peel.hpp>
#include <mitama/mana/type_traits/is_tuple_like.hpp>
#include <mitama/mana/meta/repack.hpp>
#include <mitama/mana/core/view/view.hpp>
#include <tuple>
namespace mitama::mana::map_fn {
template <std::size_t N>
struct chunkify_map_fn {
template <class Tuple, std::size_t... Indices>
static constexpr auto element_type(Tuple&&, value_list<Indices...>) -> std::tuple<std::tuple_element_t<Indices, Tuple>...>;
template <class Tuple>
static constexpr std::size_t value = std::tuple_size_v<std::decay_t<Tuple>> / N;
template <std::size_t I, class Tuple>
using type = decltype(chunkify_map_fn::element_type(std::declval<Tuple>(), mana::iota<I*N, I*N + N>));
template <std::size_t I, class Tuple>
static constexpr auto get(Tuple&& t) {
return mana::apply([&t](auto... indices){
return std::tuple(std::get<mana::peel(indices)>(t)...);
}, mana::iota<I*N, I*N + N>);
}
};
}
namespace mitama::mana {
template <std::size_t N>
struct chunkify_fn {
template <class... Args>
auto operator()(Args&&... args) const {
return mana::apply([forwarded = std::forward_as_tuple(std::forward<Args>(args)...)](auto... chunk) mutable {
return std::tuple{mana::apply([&forwarded](auto... indices) mutable {
return std::tuple(std::get<mana::peel(indices)>(forwarded)...);
}, mana::peel(chunk))... };
}, mana::chunk<N>(mana::iota<0, sizeof...(Args)>));
}
template <class TupleLike, std::enable_if_t<mana::is_tuple_like_v<std::decay_t<TupleLike>>, bool> = false>
auto operator()(TupleLike&& t) const {
return mana::apply([t](auto... chunk) mutable {
return std::tuple{mana::apply([&t](auto... indices) mutable {
return std::tuple(std::get<mana::peel(indices)>(t)...);
}, mana::peel(chunk))... };
}, mana::chunk<N>(mana::iota<0, std::tuple_size_v<std::decay_t<TupleLike>>>));
}
template <class... Args>
auto view(Args&&... args) const {
return _view<fn::static_, mitama::mana::map_fn::chunkify_map_fn<N>, std::tuple<Args...>>{std::forward<Args>(args)...};
}
template <class TupleLike, std::enable_if_t<mana::is_tuple_like_v<std::decay_t<TupleLike>>, bool> = false>
auto view(TupleLike&& t) const {
return std::apply([](auto&&... args){
return _view<fn::static_, mitama::mana::map_fn::chunkify_map_fn<N>, std::tuple<decltype(args)...>>{std::forward<decltype(args)>(args)...};
}, std::forward<TupleLike>(t));
}
};
template <std::size_t N>
inline constexpr chunkify_fn<N> chunkify{};
}
#endif // !MITAMA_MANA_FUNCTIONAL_CHUNK_HPP
| 2,922 | 1,073 |
#include<iostream>
using namespace std;
bool isChildString(char* parent,char* child)
{
int j = -1;
int i = 0;
for(; child[i] != '\0';i++)
{
if(j != -1 && parent[j] == '\0')
break;
for(;parent[j] != '\0';)
{
j++;
if(parent[j] == child[i])
{
break;
}
}
}
if(child[i] == '\0')
return true;
else
return false;
}
int main(void)
{
/* 一个可能的输入程序 */
char* s1,* s2;
s1 = new char[100];
s2 = new char[100];
cout<<"输入s1串:";
cin.getline(s1,100);
cout<<"\n输入s2串:";
cin.getline(s2,100);
cout<<"\ns1";
isChildString(s1,s2) == true ? cout<<"是" : cout<<"不是";
cout<<"s2的子串";
}
| 757 | 321 |
#include <bits/stdc++.h>
#include "Time.cpp"
using namespace std;
int main()
{
Time t1;
t1.setHour(3);
t1.setMinutes(34);
t1.setSeconds(54);
Time t2;
t2.setHour(2);
t2.setMinutes(24);
t2.setSeconds(35);
Time t3;
t3 = t1.add(t2);
t1.print();
t2.print();
t3.print();
Time t4;
t4 = t2.subtract(t1);
t4.print();
} | 385 | 186 |
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2019-2020 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include <wpi/math>
#include "frc/geometry/Translation2d.h"
#include "frc/kinematics/MecanumDriveKinematics.h"
#include "gtest/gtest.h"
#include "units/angular_velocity.h"
using namespace frc;
class MecanumDriveKinematicsTest : public ::testing::Test {
protected:
Translation2d m_fl{12_m, 12_m};
Translation2d m_fr{12_m, -12_m};
Translation2d m_bl{-12_m, 12_m};
Translation2d m_br{-12_m, -12_m};
MecanumDriveKinematics kinematics{m_fl, m_fr, m_bl, m_br};
};
TEST_F(MecanumDriveKinematicsTest, StraightLineInverseKinematics) {
ChassisSpeeds speeds{5_mps, 0_mps, 0_rad_per_s};
auto moduleStates = kinematics.ToWheelSpeeds(speeds);
/*
By equation (13.12) of the state-space-guide, the wheel speeds should
be as follows:
velocities: fl 3.535534 fr 3.535534 rl 3.535534 rr 3.535534
*/
EXPECT_NEAR(3.536, moduleStates.frontLeft.to<double>(), 0.1);
EXPECT_NEAR(3.536, moduleStates.frontRight.to<double>(), 0.1);
EXPECT_NEAR(3.536, moduleStates.rearLeft.to<double>(), 0.1);
EXPECT_NEAR(3.536, moduleStates.rearRight.to<double>(), 0.1);
}
TEST_F(MecanumDriveKinematicsTest, StraightLineForwardKinematics) {
MecanumDriveWheelSpeeds wheelSpeeds{3.536_mps, 3.536_mps, 3.536_mps,
3.536_mps};
auto chassisSpeeds = kinematics.ToChassisSpeeds(wheelSpeeds);
/*
By equation (13.13) of the state-space-guide, the chassis motion from wheel
velocities: fl 3.535534 fr 3.535534 rl 3.535534 rr 3.535534 will be
[[5][0][0]]
*/
EXPECT_NEAR(5.0, chassisSpeeds.vx.to<double>(), 0.1);
EXPECT_NEAR(0.0, chassisSpeeds.vy.to<double>(), 0.1);
EXPECT_NEAR(0.0, chassisSpeeds.omega.to<double>(), 0.1);
}
TEST_F(MecanumDriveKinematicsTest, StrafeInverseKinematics) {
ChassisSpeeds speeds{0_mps, 4_mps, 0_rad_per_s};
auto moduleStates = kinematics.ToWheelSpeeds(speeds);
/*
By equation (13.12) of the state-space-guide, the wheel speeds should
be as follows:
velocities: fl -2.828427 fr 2.828427 rl 2.828427 rr -2.828427
*/
EXPECT_NEAR(-2.828427, moduleStates.frontLeft.to<double>(), 0.1);
EXPECT_NEAR(2.828427, moduleStates.frontRight.to<double>(), 0.1);
EXPECT_NEAR(2.828427, moduleStates.rearLeft.to<double>(), 0.1);
EXPECT_NEAR(-2.828427, moduleStates.rearRight.to<double>(), 0.1);
}
TEST_F(MecanumDriveKinematicsTest, StrafeForwardKinematics) {
MecanumDriveWheelSpeeds wheelSpeeds{-2.828427_mps, 2.828427_mps, 2.828427_mps,
-2.828427_mps};
auto chassisSpeeds = kinematics.ToChassisSpeeds(wheelSpeeds);
/*
By equation (13.13) of the state-space-guide, the chassis motion from wheel
velocities: fl 3.535534 fr 3.535534 rl 3.535534 rr 3.535534 will be
[[5][0][0]]
*/
EXPECT_NEAR(0.0, chassisSpeeds.vx.to<double>(), 0.1);
EXPECT_NEAR(4.0, chassisSpeeds.vy.to<double>(), 0.1);
EXPECT_NEAR(0.0, chassisSpeeds.omega.to<double>(), 0.1);
}
TEST_F(MecanumDriveKinematicsTest, RotationInverseKinematics) {
ChassisSpeeds speeds{0_mps, 0_mps,
units::radians_per_second_t(2 * wpi::math::pi)};
auto moduleStates = kinematics.ToWheelSpeeds(speeds);
/*
By equation (13.12) of the state-space-guide, the wheel speeds should
be as follows:
velocities: fl -106.629191 fr 106.629191 rl -106.629191 rr 106.629191
*/
EXPECT_NEAR(-106.62919, moduleStates.frontLeft.to<double>(), 0.1);
EXPECT_NEAR(106.62919, moduleStates.frontRight.to<double>(), 0.1);
EXPECT_NEAR(-106.62919, moduleStates.rearLeft.to<double>(), 0.1);
EXPECT_NEAR(106.62919, moduleStates.rearRight.to<double>(), 0.1);
}
TEST_F(MecanumDriveKinematicsTest, RotationForwardKinematics) {
MecanumDriveWheelSpeeds wheelSpeeds{-106.62919_mps, 106.62919_mps,
-106.62919_mps, 106.62919_mps};
auto chassisSpeeds = kinematics.ToChassisSpeeds(wheelSpeeds);
/*
By equation (13.13) of the state-space-guide, the chassis motion from wheel
velocities: fl -106.629191 fr 106.629191 rl -106.629191 rr 106.629191 should
be [[0][0][2pi]]
*/
EXPECT_NEAR(0.0, chassisSpeeds.vx.to<double>(), 0.1);
EXPECT_NEAR(0.0, chassisSpeeds.vy.to<double>(), 0.1);
EXPECT_NEAR(2 * wpi::math::pi, chassisSpeeds.omega.to<double>(), 0.1);
}
TEST_F(MecanumDriveKinematicsTest, MixedRotationTranslationInverseKinematics) {
ChassisSpeeds speeds{2_mps, 3_mps, 1_rad_per_s};
auto moduleStates = kinematics.ToWheelSpeeds(speeds);
/*
By equation (13.12) of the state-space-guide, the wheel speeds should
be as follows:
velocities: fl -17.677670 fr 20.506097 rl -13.435029 rr 16.263456
*/
EXPECT_NEAR(-17.677670, moduleStates.frontLeft.to<double>(), 0.1);
EXPECT_NEAR(20.506097, moduleStates.frontRight.to<double>(), 0.1);
EXPECT_NEAR(-13.435, moduleStates.rearLeft.to<double>(), 0.1);
EXPECT_NEAR(16.26, moduleStates.rearRight.to<double>(), 0.1);
}
TEST_F(MecanumDriveKinematicsTest, MixedRotationTranslationForwardKinematics) {
MecanumDriveWheelSpeeds wheelSpeeds{-17.677670_mps, 20.506097_mps,
-13.435_mps, 16.26_mps};
auto chassisSpeeds = kinematics.ToChassisSpeeds(wheelSpeeds);
/*
By equation (13.13) of the state-space-guide, the chassis motion from wheel
velocities: fl -17.677670 fr 20.506097 rl -13.435029 rr 16.263456 should be
[[2][3][1]]
*/
EXPECT_NEAR(2.0, chassisSpeeds.vx.to<double>(), 0.1);
EXPECT_NEAR(3.0, chassisSpeeds.vy.to<double>(), 0.1);
EXPECT_NEAR(1.0, chassisSpeeds.omega.to<double>(), 0.1);
}
TEST_F(MecanumDriveKinematicsTest, OffCenterRotationInverseKinematics) {
ChassisSpeeds speeds{0_mps, 0_mps, 1_rad_per_s};
auto moduleStates = kinematics.ToWheelSpeeds(speeds, m_fl);
/*
By equation (13.12) of the state-space-guide, the wheel speeds should
be as follows:
velocities: fl 0.000000 fr 16.970563 rl -16.970563 rr 33.941125
*/
EXPECT_NEAR(0, moduleStates.frontLeft.to<double>(), 0.1);
EXPECT_NEAR(16.971, moduleStates.frontRight.to<double>(), 0.1);
EXPECT_NEAR(-16.971, moduleStates.rearLeft.to<double>(), 0.1);
EXPECT_NEAR(33.941, moduleStates.rearRight.to<double>(), 0.1);
}
TEST_F(MecanumDriveKinematicsTest, OffCenterRotationForwardKinematics) {
MecanumDriveWheelSpeeds wheelSpeeds{0_mps, 16.971_mps, -16.971_mps,
33.941_mps};
auto chassisSpeeds = kinematics.ToChassisSpeeds(wheelSpeeds);
/*
By equation (13.13) of the state-space-guide, the chassis motion from the
wheel velocities should be [[12][-12][1]]
*/
EXPECT_NEAR(12.0, chassisSpeeds.vx.to<double>(), 0.1);
EXPECT_NEAR(-12, chassisSpeeds.vy.to<double>(), 0.1);
EXPECT_NEAR(1.0, chassisSpeeds.omega.to<double>(), 0.1);
}
TEST_F(MecanumDriveKinematicsTest,
OffCenterTranslationRotationInverseKinematics) {
ChassisSpeeds speeds{5_mps, 2_mps, 1_rad_per_s};
auto moduleStates = kinematics.ToWheelSpeeds(speeds, m_fl);
/*
By equation (13.12) of the state-space-guide, the wheel speeds should
be as follows:
velocities: fl 2.121320 fr 21.920310 rl -12.020815 rr 36.062446
*/
EXPECT_NEAR(2.12, moduleStates.frontLeft.to<double>(), 0.1);
EXPECT_NEAR(21.92, moduleStates.frontRight.to<double>(), 0.1);
EXPECT_NEAR(-12.02, moduleStates.rearLeft.to<double>(), 0.1);
EXPECT_NEAR(36.06, moduleStates.rearRight.to<double>(), 0.1);
}
TEST_F(MecanumDriveKinematicsTest,
OffCenterTranslationRotationForwardKinematics) {
MecanumDriveWheelSpeeds wheelSpeeds{2.12_mps, 21.92_mps, -12.02_mps,
36.06_mps};
auto chassisSpeeds = kinematics.ToChassisSpeeds(wheelSpeeds);
/*
By equation (13.13) of the state-space-guide, the chassis motion from the
wheel velocities should be [[17][-10][1]]
*/
EXPECT_NEAR(17.0, chassisSpeeds.vx.to<double>(), 0.1);
EXPECT_NEAR(-10, chassisSpeeds.vy.to<double>(), 0.1);
EXPECT_NEAR(1.0, chassisSpeeds.omega.to<double>(), 0.1);
}
TEST_F(MecanumDriveKinematicsTest, NormalizeTest) {
MecanumDriveWheelSpeeds wheelSpeeds{5_mps, 6_mps, 4_mps, 7_mps};
wheelSpeeds.Normalize(5.5_mps);
double kFactor = 5.5 / 7.0;
EXPECT_NEAR(wheelSpeeds.frontLeft.to<double>(), 5.0 * kFactor, 1E-9);
EXPECT_NEAR(wheelSpeeds.frontRight.to<double>(), 6.0 * kFactor, 1E-9);
EXPECT_NEAR(wheelSpeeds.rearLeft.to<double>(), 4.0 * kFactor, 1E-9);
EXPECT_NEAR(wheelSpeeds.rearRight.to<double>(), 7.0 * kFactor, 1E-9);
}
| 8,876 | 4,212 |
/*****************************************************************************
Copyright (c) 1996, 2014, Oracle and/or its affiliates. All Rights Reserved.
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; version 2 of the License.
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, Suite 500, Boston, MA 02110-1335 USA
*****************************************************************************/
/**************************************************//**
@file trx/trx0trx.cc
The transaction
Created 3/26/1996 Heikki Tuuri
*******************************************************/
#include "trx0trx.h"
#ifdef UNIV_NONINL
#include "trx0trx.ic"
#endif
#include "trx0undo.h"
#include "trx0rseg.h"
#include "log0log.h"
#include "que0que.h"
#include "lock0lock.h"
#include "trx0roll.h"
#include "usr0sess.h"
#include "read0read.h"
#include "srv0srv.h"
#include "srv0start.h"
#include "btr0sea.h"
#include "os0proc.h"
#include "trx0xa.h"
#include "trx0rec.h"
#include "trx0purge.h"
#include "ha_prototypes.h"
#include "srv0mon.h"
#include "ut0vec.h"
#include "btr0pcur.h"
#include<set>
/** Set of table_id */
typedef std::set<table_id_t> table_id_set;
/** Dummy session used currently in MySQL interface */
UNIV_INTERN sess_t* trx_dummy_sess = NULL;
#ifdef UNIV_PFS_MUTEX
/* Key to register the mutex with performance schema */
UNIV_INTERN mysql_pfs_key_t trx_mutex_key;
/* Key to register the mutex with performance schema */
UNIV_INTERN mysql_pfs_key_t trx_undo_mutex_key;
#endif /* UNIV_PFS_MUTEX */
/*************************************************************//**
Set detailed error message for the transaction. */
UNIV_INTERN
void
trx_set_detailed_error(
/*===================*/
trx_t* trx, /*!< in: transaction struct */
const char* msg) /*!< in: detailed error message */
{
ut_strlcpy(trx->detailed_error, msg, sizeof(trx->detailed_error));
}
/*************************************************************//**
Set detailed error message for the transaction from a file. Note that the
file is rewinded before reading from it. */
UNIV_INTERN
void
trx_set_detailed_error_from_file(
/*=============================*/
trx_t* trx, /*!< in: transaction struct */
FILE* file) /*!< in: file to read message from */
{
os_file_read_string(file, trx->detailed_error,
sizeof(trx->detailed_error));
}
/***************************************************************
It turns out to be very efficient for all of our trx_t structures to
be in contiguous memory; this forced locality results in significant
speedups when iterating over the open transactions. We achieve this
with trx_t blocks of contiguous memory, each holding TRX_PER_BLOCK
trx_t's. As we fill blocks, we allocate new ones.
TRX_PER_BLOCK is pretty arbitrary, but you want it to be large (so
that all transactions span only a handful of memory regions).
*/
#define TRX_PER_BLOCK (1024 * 1024 / sizeof(trx_t))
struct trx_block_struct {
struct trx_block_struct* next_block;
trx_t transactions[TRX_PER_BLOCK];
};
/* A linked list of our transaction blocks. */
static struct trx_block_struct* transaction_blocks = NULL;
/* Track the next free transaction (for fast allocation) */
static trx_t *next_free_transaction = NULL;
#ifdef UNIV_DEBUG_VALGRIND
/********************************************************************//**
Frees trx_t pool */
UNIV_INTERN
void
trx_free_trx_pool()
/*==============*/
{
trx_t* next;
/* Confirm that the list looks OK */
next = next_free_transaction;
while (next) {
ut_ad(next->magic_n == TRX_FREE_MAGIC_N);
next = next->next_free_trx;
}
next_free_transaction = NULL;
while (transaction_blocks) {
struct trx_block_struct *next_block =
transaction_blocks->next_block;
mem_free(transaction_blocks);
transaction_blocks = next_block;
}
}
#endif
trx_t*
trx_allocate()
{
uint i;
trx_t* ret = NULL;
mutex_enter(&trx_sys->trx_memory_mutex);
/* If we don't have a next_free_transaction -- either because
* this is the first allocation or because we are using every
* transaction in previous blocks -- allocate a new one, set
* all of the trx_t's next_free_trx pointer to the next trx_t
* in the block, and set next_free_transaction to be the first
* trx_t in the block. */
if (!next_free_transaction) {
struct trx_block_struct* block_tmp =
static_cast<struct trx_block_struct*>(
mem_zalloc(sizeof(struct trx_block_struct)));
block_tmp->next_block = transaction_blocks;
transaction_blocks = block_tmp;
for (i = 0; i < TRX_PER_BLOCK; ++i) {
trx_t* next = NULL;
if (i < TRX_PER_BLOCK - 1) {
next = &(block_tmp->transactions[i + 1]);
}
block_tmp->transactions[i].next_free_trx = next;
block_tmp->transactions[i].magic_n = TRX_FREE_MAGIC_N;
}
next_free_transaction = &(transaction_blocks->transactions[0]);
}
ut_a(next_free_transaction->magic_n == TRX_FREE_MAGIC_N);
/* We return the next free transaction and remove it from the list. */
ret = next_free_transaction;
next_free_transaction = ret->next_free_trx;
ret->next_free_trx = NULL;
mutex_exit(&trx_sys->trx_memory_mutex);
return ret;
}
void trx_deallocate(trx_t* t) {
mutex_enter(&trx_sys->trx_memory_mutex);
ut_a(t->magic_n == TRX_MAGIC_N);
memset(t, 0, sizeof(trx_t));
/* Place this transaction at the head of our free list. Note
* that if somehow this is the last used transaction in a
* transaction block, we do not free the block. This is a
* wasteful optimization as there are at most a few megabytes of
* blocks in an extremely busy system. */
t->next_free_trx = next_free_transaction;
t->magic_n = TRX_FREE_MAGIC_N;
next_free_transaction = t;
mutex_exit(&trx_sys->trx_memory_mutex);
}
/*************************************************************//**
Initialize data structures related to logical-read-ahead. */
void
trx_lra_init(
/*=============================*/
lra_t* lra) /*!< in: lra structure */
{
lra->lra_size = 0;
lra->lra_space_id = 0;
lra->lra_n_spaces = 0;
lra->lra_count_n_spaces = 0;
lra->lra_n_pages = 0;
lra->lra_n_pages_since = 0;
lra->lra_page_no = 0;
lra->lra_pages_before_sleep = 0;
lra->lra_sleep = 0;
lra->lra_tree_height = 0;
lra->lra_sort_arr = NULL;
lra->lra_ht = NULL;
lra->lra_ht1 = NULL;
lra->lra_ht2 = NULL;
lra->lra_arr1 = NULL;
lra->lra_arr2 = NULL;
lra->lra_cur = NULL;
}
/*************************************************************//**
Frees data structures related to logical-read-ahead. */
void
trx_lra_free(
/*=============================*/
lra_t* lra) /*!< in: lra structure */
{
if (lra->lra_ht) {
ut_a(lra->lra_ht1);
ut_a(lra->lra_ht2);
ut_a(lra->lra_sort_arr);
hash_table_free(lra->lra_ht1);
hash_table_free(lra->lra_ht2);
btr_pcur_close(lra->lra_cur);
ut_free(lra->lra_sort_arr);
#ifdef TARGET_OS_LINUX
if (cachedev_enabled) {
pid_t pid = syscall(SYS_gettid);
ioctl(cachedev_fd,
FLASHCACHEDELBLACKLIST,
&pid);
}
#endif /* TARGET_OS_LINUX */
} else {
ut_a(!lra->lra_ht1);
ut_a(!lra->lra_ht2);
ut_a(!lra->lra_sort_arr);
ut_a(!lra->lra_cur);
ut_a(!lra->lra_arr1);
ut_a(!lra->lra_arr2);
}
trx_lra_init(lra);
}
/*************************************************************//**
Creates or frees data structures related to logical-read-ahead.
based on the value of lra_size. */
UNIV_INTERN
void
trx_lra_reset(
/*=============================*/
trx_t* trx, /*!< in: transaction */
ulint lra_size, /*!< in: lra_size in MB. If 0, the fields that
are releated to logical-read-ahead will be freed
if they were initialized. */
ulint lra_pages_before_sleep,
/*!< in: The number of node pointer records
traversed while holding the index lock before
releasing the index lock and sleeping for a
short period of time so that the other threads
get a chance to x-latch the index lock. */
ulint lra_sleep, /*!< in: Sleep time in milliseconds. */
ulint lra_n_spaces, /*!< in: Number of space switches before lra is
disabled. */
bool reset_lra_count_n_spaces)
/*!< in: whether to reset lra_count_n_spaces. */
{
#ifndef TARGET_OS_LINUX
if (lra_size) {
ib_logf(IB_LOG_LEVEL_WARN,
"Logical read ahead is supported only on linux.");
lra_size = 0;
}
#else /* TARGET_OS_LINUX */
if (!srv_use_native_aio && lra_size) {
ib_logf(IB_LOG_LEVEL_WARN,
"In order to use logical read ahead please enable "
"native aio by setting innodb_use_native_aio=1 in "
"my.cnf and restarting the server.");
lra_size = 0;
}
#endif /* TARGET_OS_LINUX */
lra_t* lra = &(trx->lra);
if (lra_size == 0) {
trx_lra_free(lra);
return;
}
ulint n_pages_max =
(lra_size << 20L) / UNIV_ZIP_SIZE_MIN;
ulint mem = n_pages_max * (2 * sizeof(ulint)
+ 2 * sizeof(page_no_holder_t))
+ sizeof(btr_pcur_t);
lra->lra_size = lra_size;
lra->lra_n_spaces = lra_n_spaces;
lra->lra_space_id = 0;
lra->lra_n_pages = 0;
lra->lra_n_pages_since = 0;
lra->lra_page_no = 0;
lra->lra_pages_before_sleep = lra_pages_before_sleep;
lra->lra_sleep = lra_sleep;
lra->lra_tree_height = 0;
if (reset_lra_count_n_spaces) {
lra->lra_count_n_spaces = 0;
}
if (lra->lra_ht) {
ut_a(lra->lra_ht1);
ut_a(lra->lra_ht2);
ut_a(lra->lra_sort_arr);
ut_a(lra->lra_cur);
hash_table_clear(lra->lra_ht1);
hash_table_clear(lra->lra_ht2);
btr_pcur_reset(lra->lra_cur);
lra->lra_ht = lra->lra_ht1;
#ifdef UNIV_DEBUG
/* following resets lra_sort_arr, lra_arr1, lra_arr2,
and lra_cursor. */
memset(lra->lra_sort_arr, 0, mem);
#endif
btr_pcur_init(lra->lra_cur);
} else {
byte* alloc;
ut_a(!lra->lra_ht1);
ut_a(!lra->lra_ht2);
ut_a(!lra->lra_sort_arr);
ut_a(!lra->lra_cur);
lra->lra_ht1 = hash_create(16384);
lra->lra_ht2 = hash_create(16384);
lra->lra_ht = lra->lra_ht1;
alloc = (byte*)ut_malloc(mem);
#ifdef UNIV_DEBUG
memset(alloc, 0, mem);
#endif
lra->lra_sort_arr = (ulint*)alloc;
alloc += 2 * sizeof(ulint) * n_pages_max;
lra->lra_arr1 = (page_no_holder_t*) alloc;
alloc += sizeof(page_no_holder_t) * n_pages_max;
lra->lra_arr2 = (page_no_holder_t*) alloc;
alloc += sizeof(page_no_holder_t) * n_pages_max;
lra->lra_cur = (btr_pcur_t*) alloc;
btr_pcur_init(lra->lra_cur);
#ifdef TARGET_OS_LINUX
if (cachedev_enabled) {
pid_t pid = syscall(SYS_gettid);
ioctl(cachedev_fd,
FLASHCACHEADDBLACKLIST,
&pid);
}
#endif /* TARGET_OS_LINUX */
}
}
/****************************************************************//**
Creates and initializes a transaction object. It must be explicitly
started with trx_start_if_not_started() before using it. The default
isolation level is TRX_ISO_REPEATABLE_READ.
@return transaction instance, should never be NULL */
static
trx_t*
trx_create(void)
/*============*/
{
trx_t* trx;
mem_heap_t* heap;
ib_alloc_t* heap_alloc;
trx = trx_allocate();
mutex_create(trx_mutex_key, &trx->mutex, SYNC_TRX);
trx->magic_n = TRX_MAGIC_N;
trx->state = TRX_STATE_NOT_STARTED;
trx->isolation_level = TRX_ISO_REPEATABLE_READ;
trx->no = TRX_ID_MAX;
trx->support_xa = TRUE;
trx->check_foreigns = TRUE;
trx->check_unique_secondary = TRUE;
trx->dict_operation = TRX_DICT_OP_NONE;
mutex_create(trx_undo_mutex_key, &trx->undo_mutex, SYNC_TRX_UNDO);
trx->error_state = DB_SUCCESS;
trx->lock.que_state = TRX_QUE_RUNNING;
trx->lock.lock_heap = mem_heap_create_typed(
256, MEM_HEAP_FOR_LOCK_HEAP);
trx->search_latch_timeout = BTR_SEA_TIMEOUT;
trx->always_enter_innodb = FALSE;
trx->global_read_view_heap = mem_heap_create(256);
trx->xid.formatID = -1;
trx->op_info = "";
trx->api_trx = false;
trx->api_auto_commit = false;
trx->read_write = true;
memset(&trx->table_io_perf, 0, sizeof(trx->table_io_perf));
heap = mem_heap_create(sizeof(ib_vector_t) + sizeof(void*) * 8);
heap_alloc = ib_heap_allocator_create(heap);
/* Remember to free the vector explicitly in trx_free(). */
trx->autoinc_locks = ib_vector_create(heap_alloc, sizeof(void**), 4);
/* Remember to free the vector explicitly in trx_free(). */
heap = mem_heap_create(sizeof(ib_vector_t) + sizeof(void*) * 128);
heap_alloc = ib_heap_allocator_create(heap);
trx->lock.table_locks = ib_vector_create(
heap_alloc, sizeof(void**), 32);
trx_lra_init(&(trx->lra));
return(trx);
}
/********************************************************************//**
Creates a transaction object for background operations by the master thread.
@return own: transaction object */
UNIV_INTERN
trx_t*
trx_allocate_for_background(void)
/*=============================*/
{
trx_t* trx;
trx = trx_create();
trx->sess = trx_dummy_sess;
return(trx);
}
/********************************************************************//**
Creates a transaction object for MySQL.
@return own: transaction object */
UNIV_INTERN
trx_t*
trx_allocate_for_mysql(void)
/*========================*/
{
trx_t* trx;
trx = trx_allocate_for_background();
mutex_enter(&trx_sys->mutex);
ut_d(trx->in_mysql_trx_list = TRUE);
UT_LIST_ADD_FIRST(mysql_trx_list, trx_sys->mysql_trx_list, trx);
mutex_exit(&trx_sys->mutex);
return(trx);
}
/********************************************************************//**
Frees a transaction object. */
static
void
trx_free(
/*=====*/
trx_t* trx) /*!< in, own: trx object */
{
ut_a(trx->magic_n == TRX_MAGIC_N);
ut_ad(!trx->in_ro_trx_list);
ut_ad(!trx->in_rw_trx_list);
ut_ad(!trx->in_mysql_trx_list);
mutex_free(&trx->undo_mutex);
if (trx->undo_no_arr != NULL) {
trx_undo_arr_free(trx->undo_no_arr);
}
ut_a(trx->lock.wait_lock == NULL);
ut_a(trx->lock.wait_thr == NULL);
ut_a(!trx->has_search_latch);
ut_a(trx->dict_operation_lock_mode == 0);
if (trx->lock.lock_heap) {
mem_heap_free(trx->lock.lock_heap);
}
ut_a(UT_LIST_GET_LEN(trx->lock.trx_locks) == 0);
if (trx->global_read_view_heap) {
mem_heap_free(trx->global_read_view_heap);
}
ut_a(ib_vector_is_empty(trx->autoinc_locks));
/* We allocated a dedicated heap for the vector. */
ib_vector_free(trx->autoinc_locks);
if (trx->lock.table_locks != NULL) {
/* We allocated a dedicated heap for the vector. */
ib_vector_free(trx->lock.table_locks);
}
mutex_free(&trx->mutex);
trx_lra_free(&(trx->lra));
trx_deallocate(trx);
}
/********************************************************************//**
Frees a transaction object of a background operation of the master thread. */
UNIV_INTERN
void
trx_free_for_background(
/*====================*/
trx_t* trx) /*!< in, own: trx object */
{
if (trx->declared_to_be_inside_innodb) {
ib_logf(IB_LOG_LEVEL_ERROR,
"Freeing a trx (%p, " TRX_ID_FMT ") which is declared "
"to be processing inside InnoDB", trx, trx->id);
trx_print(stderr, trx, 600);
putc('\n', stderr);
/* This is an error but not a fatal error. We must keep
the counters like srv_conc_n_threads accurate. */
srv_conc_force_exit_innodb(trx);
}
if (trx->n_mysql_tables_in_use != 0
|| trx->mysql_n_tables_locked != 0) {
ib_logf(IB_LOG_LEVEL_ERROR,
"MySQL is freeing a thd though "
"trx->n_mysql_tables_in_use is %lu and "
"trx->mysql_n_tables_locked is %lu.",
(ulong) trx->n_mysql_tables_in_use,
(ulong) trx->mysql_n_tables_locked);
trx_print(stderr, trx, 600);
ut_print_buf(stderr, trx, sizeof(trx_t));
putc('\n', stderr);
}
ut_a(trx->state == TRX_STATE_NOT_STARTED);
ut_a(trx->insert_undo == NULL);
ut_a(trx->update_undo == NULL);
ut_a(trx->read_view == NULL);
trx_free(trx);
}
/********************************************************************//**
At shutdown, frees a transaction object that is in the PREPARED state. */
UNIV_INTERN
void
trx_free_prepared(
/*==============*/
trx_t* trx) /*!< in, own: trx object */
{
ut_ad(mutex_own(&trx_sys->mutex));
ut_a(trx_state_eq(trx, TRX_STATE_PREPARED));
ut_a(trx->magic_n == TRX_MAGIC_N);
trx_undo_free_prepared(trx);
assert_trx_in_rw_list(trx);
ut_a(!trx->read_only);
UT_LIST_REMOVE(trx_list, trx_sys->rw_trx_list, trx);
ut_d(trx->in_rw_trx_list = FALSE);
/* Undo trx_resurrect_table_locks(). */
UT_LIST_INIT(trx->lock.trx_locks);
trx_free(trx);
}
/********************************************************************//**
Frees a transaction object for MySQL. */
UNIV_INTERN
void
trx_free_for_mysql(
/*===============*/
trx_t* trx) /*!< in, own: trx object */
{
mutex_enter(&trx_sys->mutex);
ut_ad(trx->in_mysql_trx_list);
ut_d(trx->in_mysql_trx_list = FALSE);
UT_LIST_REMOVE(mysql_trx_list, trx_sys->mysql_trx_list, trx);
ut_ad(trx_sys_validate_trx_list());
mutex_exit(&trx_sys->mutex);
trx_free_for_background(trx);
}
/****************************************************************//**
Inserts the trx handle in the trx system trx list in the right position.
The list is sorted on the trx id so that the biggest id is at the list
start. This function is used at the database startup to insert incomplete
transactions to the list. */
static
void
trx_list_rw_insert_ordered(
/*=======================*/
trx_t* trx) /*!< in: trx handle */
{
trx_t* trx2;
ut_ad(!trx->read_only);
ut_d(trx->start_file = __FILE__);
ut_d(trx->start_line = __LINE__);
ut_a(srv_is_being_started);
ut_ad(!trx->in_ro_trx_list);
ut_ad(!trx->in_rw_trx_list);
ut_ad(trx->state != TRX_STATE_NOT_STARTED);
ut_ad(trx->is_recovered);
for (trx2 = UT_LIST_GET_FIRST(trx_sys->rw_trx_list);
trx2 != NULL;
trx2 = UT_LIST_GET_NEXT(trx_list, trx2)) {
assert_trx_in_rw_list(trx2);
if (trx->id >= trx2->id) {
ut_ad(trx->id > trx2->id);
break;
}
}
if (trx2 != NULL) {
trx2 = UT_LIST_GET_PREV(trx_list, trx2);
if (trx2 == NULL) {
UT_LIST_ADD_FIRST(trx_list, trx_sys->rw_trx_list, trx);
} else {
UT_LIST_INSERT_AFTER(
trx_list, trx_sys->rw_trx_list, trx2, trx);
}
} else {
UT_LIST_ADD_LAST(trx_list, trx_sys->rw_trx_list, trx);
}
#ifdef UNIV_DEBUG
if (trx->id > trx_sys->rw_max_trx_id) {
trx_sys->rw_max_trx_id = trx->id;
}
#endif /* UNIV_DEBUG */
ut_ad(!trx->in_rw_trx_list);
ut_d(trx->in_rw_trx_list = TRUE);
}
/****************************************************************//**
Resurrect the table locks for a resurrected transaction. */
static
void
trx_resurrect_table_locks(
/*======================*/
trx_t* trx, /*!< in/out: transaction */
const trx_undo_t* undo) /*!< in: undo log */
{
mtr_t mtr;
page_t* undo_page;
trx_undo_rec_t* undo_rec;
table_id_set tables;
ut_ad(undo == trx->insert_undo || undo == trx->update_undo);
if (trx_state_eq(trx, TRX_STATE_COMMITTED_IN_MEMORY)
|| undo->empty) {
return;
}
mtr_start(&mtr);
/* trx_rseg_mem_create() may have acquired an X-latch on this
page, so we cannot acquire an S-latch. */
undo_page = trx_undo_page_get(
undo->space, undo->zip_size, undo->top_page_no, &mtr);
undo_rec = undo_page + undo->top_offset;
do {
ulint type;
ulint cmpl_info;
bool updated_extern;
undo_no_t undo_no;
table_id_t table_id;
page_t* undo_rec_page = page_align(undo_rec);
if (undo_rec_page != undo_page) {
if (!mtr_memo_release(&mtr,
buf_block_align(undo_page),
MTR_MEMO_PAGE_X_FIX)) {
/* The page of the previous undo_rec
should have been latched by
trx_undo_page_get() or
trx_undo_get_prev_rec(). */
ut_ad(0);
}
undo_page = undo_rec_page;
}
trx_undo_rec_get_pars(
undo_rec, &type, &cmpl_info,
&updated_extern, &undo_no, &table_id);
tables.insert(table_id);
undo_rec = trx_undo_get_prev_rec(
undo_rec, undo->hdr_page_no,
undo->hdr_offset, false, &mtr);
} while (undo_rec);
mtr_commit(&mtr);
for (table_id_set::const_iterator i = tables.begin();
i != tables.end(); i++) {
if (dict_table_t* table = dict_table_open_on_id(
*i, FALSE, DICT_TABLE_OP_LOAD_TABLESPACE)) {
if (table->ibd_file_missing
|| dict_table_is_temporary(table)) {
mutex_enter(&dict_sys->mutex);
dict_table_close(table, TRUE, FALSE);
dict_table_remove_from_cache(table);
mutex_exit(&dict_sys->mutex);
continue;
}
lock_table_ix_resurrect(table, trx);
DBUG_PRINT("ib_trx",
("resurrect" TRX_ID_FMT
" table '%s' IX lock from %s undo",
trx->id, table->name,
undo == trx->insert_undo
? "insert" : "update"));
dict_table_close(table, FALSE, FALSE);
}
}
}
/****************************************************************//**
Resurrect the transactions that were doing inserts the time of the
crash, they need to be undone.
@return trx_t instance */
static
trx_t*
trx_resurrect_insert(
/*=================*/
trx_undo_t* undo, /*!< in: entry to UNDO */
trx_rseg_t* rseg) /*!< in: rollback segment */
{
trx_t* trx;
trx = trx_allocate_for_background();
trx->rseg = rseg;
trx->xid = undo->xid;
trx->id = undo->trx_id;
trx->insert_undo = undo;
trx->is_recovered = TRUE;
/* This is single-threaded startup code, we do not need the
protection of trx->mutex or trx_sys->mutex here. */
if (undo->state != TRX_UNDO_ACTIVE) {
/* Prepared transactions are left in the prepared state
waiting for a commit or abort decision from MySQL */
if (undo->state == TRX_UNDO_PREPARED) {
fprintf(stderr,
"InnoDB: Transaction " TRX_ID_FMT " was in the"
" XA prepared state.\n", trx->id);
if (srv_force_recovery == 0) {
trx->state = TRX_STATE_PREPARED;
trx_sys->n_prepared_trx++;
trx_sys->n_prepared_recovered_trx++;
} else {
fprintf(stderr,
"InnoDB: Since innodb_force_recovery"
" > 0, we will rollback it anyway.\n");
trx->state = TRX_STATE_ACTIVE;
}
} else {
trx->state = TRX_STATE_COMMITTED_IN_MEMORY;
}
/* We give a dummy value for the trx no; this should have no
relevance since purge is not interested in committed
transaction numbers, unless they are in the history
list, in which case it looks the number from the disk based
undo log structure */
trx->no = trx->id;
} else {
trx->state = TRX_STATE_ACTIVE;
/* A running transaction always has the number
field inited to TRX_ID_MAX */
trx->no = TRX_ID_MAX;
}
/* trx_start_low() is not called with resurrect, so need to initialize
start time here.*/
if (trx->state == TRX_STATE_ACTIVE
|| trx->state == TRX_STATE_PREPARED) {
trx->start_time = ut_time();
}
if (undo->dict_operation) {
trx_set_dict_operation(trx, TRX_DICT_OP_TABLE);
trx->table_id = undo->table_id;
}
if (!undo->empty) {
trx->undo_no = undo->top_undo_no + 1;
}
return(trx);
}
/****************************************************************//**
Prepared transactions are left in the prepared state waiting for a
commit or abort decision from MySQL */
static
void
trx_resurrect_update_in_prepared_state(
/*===================================*/
trx_t* trx, /*!< in,out: transaction */
const trx_undo_t* undo) /*!< in: update UNDO record */
{
/* This is single-threaded startup code, we do not need the
protection of trx->mutex or trx_sys->mutex here. */
if (undo->state == TRX_UNDO_PREPARED) {
fprintf(stderr,
"InnoDB: Transaction " TRX_ID_FMT
" was in the XA prepared state.\n", trx->id);
if (srv_force_recovery == 0) {
if (trx_state_eq(trx, TRX_STATE_NOT_STARTED)) {
trx_sys->n_prepared_trx++;
trx_sys->n_prepared_recovered_trx++;
} else {
ut_ad(trx_state_eq(trx, TRX_STATE_PREPARED));
}
trx->state = TRX_STATE_PREPARED;
} else {
fprintf(stderr,
"InnoDB: Since innodb_force_recovery"
" > 0, we will rollback it anyway.\n");
trx->state = TRX_STATE_ACTIVE;
}
} else {
trx->state = TRX_STATE_COMMITTED_IN_MEMORY;
}
}
/****************************************************************//**
Resurrect the transactions that were doing updates the time of the
crash, they need to be undone. */
static
void
trx_resurrect_update(
/*=================*/
trx_t* trx, /*!< in/out: transaction */
trx_undo_t* undo, /*!< in/out: update UNDO record */
trx_rseg_t* rseg) /*!< in/out: rollback segment */
{
trx->rseg = rseg;
trx->xid = undo->xid;
trx->id = undo->trx_id;
trx->update_undo = undo;
trx->is_recovered = TRUE;
/* This is single-threaded startup code, we do not need the
protection of trx->mutex or trx_sys->mutex here. */
if (undo->state != TRX_UNDO_ACTIVE) {
trx_resurrect_update_in_prepared_state(trx, undo);
/* We give a dummy value for the trx number */
trx->no = trx->id;
} else {
trx->state = TRX_STATE_ACTIVE;
/* A running transaction always has the number field inited to
TRX_ID_MAX */
trx->no = TRX_ID_MAX;
}
/* trx_start_low() is not called with resurrect, so need to initialize
start time here.*/
if (trx->state == TRX_STATE_ACTIVE
|| trx->state == TRX_STATE_PREPARED) {
trx->start_time = ut_time();
}
if (undo->dict_operation) {
trx_set_dict_operation(trx, TRX_DICT_OP_TABLE);
trx->table_id = undo->table_id;
}
if (!undo->empty && undo->top_undo_no >= trx->undo_no) {
trx->undo_no = undo->top_undo_no + 1;
}
}
/****************************************************************//**
Creates trx objects for transactions and initializes the trx list of
trx_sys at database start. Rollback segment and undo log lists must
already exist when this function is called, because the lists of
transactions to be rolled back or cleaned up are built based on the
undo log lists. */
UNIV_INTERN
void
trx_lists_init_at_db_start(void)
/*============================*/
{
ulint i;
ut_a(srv_is_being_started);
UT_LIST_INIT(trx_sys->ro_trx_list);
UT_LIST_INIT(trx_sys->rw_trx_list);
/* Look from the rollback segments if there exist undo logs for
transactions */
for (i = 0; i < TRX_SYS_N_RSEGS; ++i) {
trx_undo_t* undo;
trx_rseg_t* rseg;
rseg = trx_sys->rseg_array[i];
if (rseg == NULL) {
continue;
}
/* Resurrect transactions that were doing inserts. */
for (undo = UT_LIST_GET_FIRST(rseg->insert_undo_list);
undo != NULL;
undo = UT_LIST_GET_NEXT(undo_list, undo)) {
trx_t* trx;
trx = trx_resurrect_insert(undo, rseg);
trx_list_rw_insert_ordered(trx);
trx_resurrect_table_locks(trx, undo);
}
/* Ressurrect transactions that were doing updates. */
for (undo = UT_LIST_GET_FIRST(rseg->update_undo_list);
undo != NULL;
undo = UT_LIST_GET_NEXT(undo_list, undo)) {
trx_t* trx;
ibool trx_created;
/* Check the trx_sys->rw_trx_list first. */
mutex_enter(&trx_sys->mutex);
trx = trx_get_rw_trx_by_id(undo->trx_id);
mutex_exit(&trx_sys->mutex);
if (trx == NULL) {
trx = trx_allocate_for_background();
trx_created = TRUE;
} else {
trx_created = FALSE;
}
trx_resurrect_update(trx, undo, rseg);
if (trx_created) {
trx_list_rw_insert_ordered(trx);
}
trx_resurrect_table_locks(trx, undo);
}
}
}
/******************************************************************//**
Assigns a rollback segment to a transaction in a round-robin fashion.
@return assigned rollback segment instance */
static
trx_rseg_t*
trx_assign_rseg_low(
/*================*/
ulong max_undo_logs, /*!< in: maximum number of UNDO logs to use */
ulint n_tablespaces) /*!< in: number of rollback tablespaces */
{
ulint i;
trx_rseg_t* rseg;
static ulint latest_rseg = 0;
if (srv_read_only_mode) {
ut_a(max_undo_logs == ULONG_UNDEFINED);
return(NULL);
}
/* This breaks true round robin but that should be OK. */
ut_a(max_undo_logs > 0 && max_undo_logs <= TRX_SYS_N_RSEGS);
i = latest_rseg++;
i %= max_undo_logs;
/* Note: The assumption here is that there can't be any gaps in
the array. Once we implement more flexible rollback segment
management this may not hold. The assertion checks for that case. */
if (trx_sys->rseg_array[0] == NULL) {
return(NULL);
}
/* Skip the system tablespace if we have more than one tablespace
defined for rollback segments. We want all UNDO records to be in
the non-system tablespaces. */
do {
rseg = trx_sys->rseg_array[i];
ut_a(rseg == NULL || i == rseg->id);
i = (rseg == NULL) ? 0 : i + 1;
} while (rseg == NULL
|| (rseg->space == 0
&& n_tablespaces > 0
&& trx_sys->rseg_array[1] != NULL));
return(rseg);
}
/****************************************************************//**
Assign a read-only transaction a rollback-segment, if it is attempting
to write to a TEMPORARY table. */
UNIV_INTERN
void
trx_assign_rseg(
/*============*/
trx_t* trx) /*!< A read-only transaction that
needs to be assigned a RBS. */
{
ut_a(trx->rseg == 0);
ut_a(trx->read_only);
ut_a(!srv_read_only_mode);
ut_a(!trx_is_autocommit_non_locking(trx));
trx->rseg = trx_assign_rseg_low(srv_undo_logs, srv_undo_tablespaces);
}
/****************************************************************//**
Starts a transaction. */
static
void
trx_start_low(
/*==========*/
trx_t* trx) /*!< in: transaction */
{
ut_ad(trx->rseg == NULL);
ut_ad(trx->start_file != 0);
ut_ad(trx->start_line != 0);
ut_ad(!trx->is_recovered);
ut_ad(trx_state_eq(trx, TRX_STATE_NOT_STARTED));
ut_ad(UT_LIST_GET_LEN(trx->lock.trx_locks) == 0);
/* If is primary transaction,
should wait during buffer pool resizing. */
if (trx->is_primary
&& trx->buf_pool_reference == 0) {
if (buf_pool_resizing) {
if (trx->declared_to_be_inside_innodb) {
/* Exit not to block the another
active transaction's re-enter */
srv_conc_force_exit_innodb(trx);
}
DEBUG_SYNC_C("wait_for_buf_pool_resizing");
os_event_wait(buf_pool_resized_event);
}
/* block resizing buffer pool until set trx->state */
os_inc_counter(server_mutex, buf_pool_referenced);
}
/* Check whether it is an AUTOCOMMIT SELECT */
trx->auto_commit = (trx->api_trx && trx->api_auto_commit)
|| thd_trx_is_auto_commit(trx->mysql_thd);
trx->read_only =
(trx->api_trx && !trx->read_write)
|| (!trx->ddl && thd_trx_is_read_only(trx->mysql_thd))
|| srv_read_only_mode;
if (!trx->auto_commit) {
++trx->will_lock;
} else if (trx->will_lock == 0) {
trx->read_only = TRUE;
}
if (!trx->read_only) {
trx->rseg = trx_assign_rseg_low(
srv_undo_logs, srv_undo_tablespaces);
}
/* The initial value for trx->no: TRX_ID_MAX is used in
read_view_open_now: */
trx->no = TRX_ID_MAX;
ut_a(ib_vector_is_empty(trx->autoinc_locks));
ut_a(ib_vector_is_empty(trx->lock.table_locks));
mutex_enter(&trx_sys->mutex);
/* If this transaction came from trx_allocate_for_mysql(),
trx->in_mysql_trx_list would hold. In that case, the trx->state
change must be protected by the trx_sys->mutex, so that
lock_print_info_all_transactions() will have a consistent view. */
trx->state = TRX_STATE_ACTIVE;
trx->id = trx_sys_get_new_trx_id();
ut_ad(!trx->in_rw_trx_list);
ut_ad(!trx->in_ro_trx_list);
if (trx->read_only) {
/* Note: The trx_sys_t::ro_trx_list doesn't really need to
be ordered, we should exploit this using a list type that
doesn't need a list wide lock to increase concurrency. */
if (!trx_is_autocommit_non_locking(trx)) {
UT_LIST_ADD_FIRST(trx_list, trx_sys->ro_trx_list, trx);
ut_d(trx->in_ro_trx_list = TRUE);
}
} else {
ut_ad(trx->rseg != NULL
|| srv_force_recovery >= SRV_FORCE_NO_TRX_UNDO);
ut_ad(!trx_is_autocommit_non_locking(trx));
UT_LIST_ADD_FIRST(trx_list, trx_sys->rw_trx_list, trx);
ut_d(trx->in_rw_trx_list = TRUE);
#ifdef UNIV_DEBUG
if (trx->id > trx_sys->rw_max_trx_id) {
trx_sys->rw_max_trx_id = trx->id;
}
#endif /* UNIV_DEBUG */
}
ut_ad(trx_sys_validate_trx_list());
mutex_exit(&trx_sys->mutex);
if (trx->is_primary
&& trx->buf_pool_reference == 0) {
/* now trx is active and it blocks resizing buffer pool.
this atomic operation should work also as write barrier
for trx->state. */
os_dec_counter(server_mutex, buf_pool_referenced);
}
trx->start_time = ut_time();
MONITOR_INC(MONITOR_TRX_ACTIVE);
}
/****************************************************************//**
Set the transaction serialisation number. */
static
void
trx_serialisation_number_get(
/*=========================*/
trx_t* trx) /*!< in: transaction */
{
trx_rseg_t* rseg;
rseg = trx->rseg;
ut_ad(mutex_own(&rseg->mutex));
mutex_enter(&trx_sys->mutex);
trx->no = trx_sys_get_new_trx_id();
/* If the rollack segment is not empty then the
new trx_t::no can't be less than any trx_t::no
already in the rollback segment. User threads only
produce events when a rollback segment is empty. */
if (rseg->last_page_no == FIL_NULL) {
void* ptr;
rseg_queue_t rseg_queue;
rseg_queue.rseg = rseg;
rseg_queue.trx_no = trx->no;
mutex_enter(&purge_sys->bh_mutex);
/* This is to reduce the pressure on the trx_sys_t::mutex
though in reality it should make very little (read no)
difference because this code path is only taken when the
rbs is empty. */
mutex_exit(&trx_sys->mutex);
ptr = ib_bh_push(purge_sys->ib_bh, &rseg_queue);
ut_a(ptr);
mutex_exit(&purge_sys->bh_mutex);
} else {
mutex_exit(&trx_sys->mutex);
}
}
/****************************************************************//**
Assign the transaction its history serialisation number and write the
update UNDO log record to the assigned rollback segment. */
static __attribute__((nonnull))
void
trx_write_serialisation_history(
/*============================*/
trx_t* trx, /*!< in/out: transaction */
mtr_t* mtr) /*!< in/out: mini-transaction */
{
trx_rseg_t* rseg;
rseg = trx->rseg;
/* Change the undo log segment states from TRX_UNDO_ACTIVE
to some other state: these modifications to the file data
structure define the transaction as committed in the file
based domain, at the serialization point of the log sequence
number lsn obtained below. */
if (trx->update_undo != NULL) {
page_t* undo_hdr_page;
trx_undo_t* undo = trx->update_undo;
/* We have to hold the rseg mutex because update
log headers have to be put to the history list in the
(serialisation) order of the UNDO trx number. This is
required for the purge in-memory data structures too. */
mutex_enter(&rseg->mutex);
/* Assign the transaction serialisation number and also
update the purge min binary heap if this is the first
UNDO log being written to the assigned rollback segment. */
trx_serialisation_number_get(trx);
/* It is not necessary to obtain trx->undo_mutex here
because only a single OS thread is allowed to do the
transaction commit for this transaction. */
undo_hdr_page = trx_undo_set_state_at_finish(undo, mtr);
trx_undo_update_cleanup(trx, undo_hdr_page, mtr);
} else {
mutex_enter(&rseg->mutex);
}
if (trx->insert_undo != NULL) {
trx_undo_set_state_at_finish(trx->insert_undo, mtr);
}
mutex_exit(&rseg->mutex);
MONITOR_INC(MONITOR_TRX_COMMIT_UNDO);
srv_n_commit_with_undo++;
/* Update the latest MySQL binlog name and offset info
in trx sys header if MySQL binlogging is on or the database
server is a MySQL replication slave */
if (trx->mysql_log_file_name
&& trx->mysql_log_file_name[0] != '\0') {
trx_sys_update_mysql_binlog_offset(
trx->mysql_log_file_name,
trx->mysql_log_offset,
TRX_SYS_MYSQL_LOG_INFO, mtr,
trx->mysql_gtid);
trx->mysql_log_file_name = NULL;
trx->mysql_gtid = NULL;
}
}
/********************************************************************
Finalize a transaction containing updates for a FTS table. */
static __attribute__((nonnull))
void
trx_finalize_for_fts_table(
/*=======================*/
fts_trx_table_t* ftt) /* in: FTS trx table */
{
fts_t* fts = ftt->table->fts;
fts_doc_ids_t* doc_ids = ftt->added_doc_ids;
mutex_enter(&fts->bg_threads_mutex);
if (fts->fts_status & BG_THREAD_STOP) {
/* The table is about to be dropped, no use
adding anything to its work queue. */
mutex_exit(&fts->bg_threads_mutex);
} else {
mem_heap_t* heap;
mutex_exit(&fts->bg_threads_mutex);
ut_a(fts->add_wq);
heap = static_cast<mem_heap_t*>(doc_ids->self_heap->arg);
ib_wqueue_add(fts->add_wq, doc_ids, heap);
/* fts_trx_table_t no longer owns the list. */
ftt->added_doc_ids = NULL;
}
}
/******************************************************************//**
Finalize a transaction containing updates to FTS tables. */
static __attribute__((nonnull))
void
trx_finalize_for_fts(
/*=================*/
trx_t* trx, /*!< in/out: transaction */
bool is_commit) /*!< in: true if the transaction was
committed, false if it was rolled back. */
{
if (is_commit) {
const ib_rbt_node_t* node;
ib_rbt_t* tables;
fts_savepoint_t* savepoint;
savepoint = static_cast<fts_savepoint_t*>(
ib_vector_last(trx->fts_trx->savepoints));
tables = savepoint->tables;
for (node = rbt_first(tables);
node;
node = rbt_next(tables, node)) {
fts_trx_table_t** ftt;
ftt = rbt_value(fts_trx_table_t*, node);
if ((*ftt)->added_doc_ids) {
trx_finalize_for_fts_table(*ftt);
}
}
}
fts_trx_free(trx->fts_trx);
trx->fts_trx = NULL;
}
/**********************************************************************//**
If required, flushes the log to disk based on the value of
innodb_flush_log_at_trx_commit. */
static
void
trx_flush_log_if_needed_low(
/*========================*/
lsn_t lsn, /*!< in: lsn up to which logs are to be
flushed. */
ibool async) /*!< in: TRUE - don't sync log */
{
int flush_log_value = srv_flush_log_at_trx_commit;
if (async) {
flush_log_value = 2;
}
switch (flush_log_value) {
case 0:
/* Do nothing */
break;
case 1:
{
bool sync = srv_unix_file_flush_method != SRV_UNIX_NOSYNC;
/* Write the log and optionally flush it to disk */
log_write_up_to(lsn, LOG_WAIT_ONE_GROUP,
sync,
sync ? LOG_WRITE_FROM_COMMIT_SYNC :
LOG_WRITE_FROM_COMMIT_ASYNC
);
break;
}
case 2:
/* Write the log but do not flush it to disk */
log_write_up_to(lsn, LOG_WAIT_ONE_GROUP, FALSE,
LOG_WRITE_FROM_COMMIT_ASYNC);
break;
default:
ut_error;
}
}
/**********************************************************************//**
If required, flushes the log to disk based on the value of
innodb_flush_log_at_trx_commit. */
static __attribute__((nonnull))
void
trx_flush_log_if_needed(
/*====================*/
lsn_t lsn, /*!< in: lsn up to which logs are to be
flushed. */
trx_t* trx, /*!< in/out: transaction */
ibool async) /*!< in: TRUE - don't sync log */
{
trx->op_info = "flushing log";
trx_flush_log_if_needed_low(lsn, async);
trx->op_info = "";
}
/****************************************************************//**
Commits a transaction in memory. */
static __attribute__((nonnull))
void
trx_commit_in_memory(
/*=================*/
trx_t* trx, /*!< in/out: transaction */
lsn_t lsn, /*!< in: log sequence number of the mini-transaction
commit of trx_write_serialisation_history(), or 0
if the transaction did not modify anything */
ibool for_commit) /*!< in: for rollback when FALSE */
{
trx->must_flush_log_later = FALSE;
if (trx_is_autocommit_non_locking(trx)) {
ut_ad(trx->read_only);
ut_a(!trx->is_recovered);
ut_ad(trx->rseg == NULL);
ut_ad(!trx->in_ro_trx_list);
ut_ad(!trx->in_rw_trx_list);
/* Note: We are asserting without holding the lock mutex. But
that is OK because this transaction is not waiting and cannot
be rolled back and no new locks can (or should not) be added
becuase it is flagged as a non-locking read-only transaction. */
ut_a(UT_LIST_GET_LEN(trx->lock.trx_locks) == 0);
/* This state change is not protected by any mutex, therefore
there is an inherent race here around state transition during
printouts. We ignore this race for the sake of efficiency.
However, the trx_sys_t::mutex will protect the trx_t instance
and it cannot be removed from the mysql_trx_list and freed
without first acquiring the trx_sys_t::mutex. */
ut_ad(trx_state_eq(trx, TRX_STATE_ACTIVE));
trx->state = TRX_STATE_NOT_STARTED;
read_view_remove(trx->global_read_view, false);
MONITOR_INC(MONITOR_TRX_NL_RO_COMMIT);
if(for_commit) {
srv_n_commit_all++;
}
} else {
lock_trx_release_locks(trx);
/* Remove the transaction from the list of active
transactions now that it no longer holds any user locks. */
ut_ad(trx_state_eq(trx, TRX_STATE_COMMITTED_IN_MEMORY));
mutex_enter(&trx_sys->mutex);
assert_trx_in_list(trx);
if (trx->read_only) {
UT_LIST_REMOVE(trx_list, trx_sys->ro_trx_list, trx);
ut_d(trx->in_ro_trx_list = FALSE);
MONITOR_INC(MONITOR_TRX_RO_COMMIT);
if(for_commit) {
srv_n_commit_all++;
}
} else {
UT_LIST_REMOVE(trx_list, trx_sys->rw_trx_list, trx);
ut_d(trx->in_rw_trx_list = FALSE);
MONITOR_INC(MONITOR_TRX_RW_COMMIT);
if(for_commit) {
srv_n_commit_all++;
}
}
/* If this transaction came from trx_allocate_for_mysql(),
trx->in_mysql_trx_list would hold. In that case, the
trx->state change must be protected by trx_sys->mutex, so that
lock_print_info_all_transactions() will have a consistent
view. */
trx->state = TRX_STATE_NOT_STARTED;
/* We already own the trx_sys_t::mutex, by doing it here we
avoid a potential context switch later. */
read_view_remove(trx->global_read_view, true);
ut_ad(trx_sys_validate_trx_list());
mutex_exit(&trx_sys->mutex);
}
if (trx->global_read_view != NULL) {
mem_heap_empty(trx->global_read_view_heap);
trx->global_read_view = NULL;
}
trx->read_view = NULL;
if (lsn) {
if (trx->insert_undo != NULL) {
trx_undo_insert_cleanup(trx);
}
/* NOTE that we could possibly make a group commit more
efficient here: call os_thread_yield here to allow also other
trxs to come to commit! */
/*-------------------------------------*/
/* Depending on the my.cnf options, we may now write the log
buffer to the log files, making the transaction durable if
the OS does not crash. We may also flush the log files to
disk, making the transaction durable also at an OS crash or a
power outage.
The idea in InnoDB's group commit is that a group of
transactions gather behind a trx doing a physical disk write
to log files, and when that physical write has been completed,
one of those transactions does a write which commits the whole
group. Note that this group commit will only bring benefit if
there are > 2 users in the database. Then at least 2 users can
gather behind one doing the physical log write to disk.
If we are calling trx_commit() under prepare_commit_mutex, we
will delay possible log write and flush to a separate function
trx_commit_complete_for_mysql(), which is only called when the
thread has released the mutex. This is to make the
group commit algorithm to work. Otherwise, the prepare_commit
mutex would serialize all commits and prevent a group of
transactions from gathering. */
if (trx->flush_log_later) {
/* Do nothing yet */
trx->must_flush_log_later = TRUE;
} else if (srv_flush_log_at_trx_commit == 0
|| thd_requested_durability(trx->mysql_thd)
== HA_IGNORE_DURABILITY) {
/* Do nothing */
} else {
trx_flush_log_if_needed(lsn, trx, false);
}
trx->commit_lsn = lsn;
/* Tell server some activity has happened, since the trx
does changes something. Background utility threads like
master thread, purge thread or page_cleaner thread might
have some work to do. */
srv_active_wake_master_thread();
}
/* undo_no is non-zero if we're doing the final commit. */
bool not_rollback = trx->undo_no != 0;
/* Free all savepoints, starting from the first. */
trx_named_savept_t* savep = UT_LIST_GET_FIRST(trx->trx_savepoints);
trx_roll_savepoints_free(trx, savep);
trx->rseg = NULL;
trx->undo_no = 0;
trx->last_sql_stat_start.least_undo_no = 0;
trx->ddl = false;
#ifdef UNIV_DEBUG
ut_ad(trx->start_file != 0);
ut_ad(trx->start_line != 0);
trx->start_file = 0;
trx->start_line = 0;
#endif /* UNIV_DEBUG */
trx->will_lock = 0;
trx->read_only = FALSE;
trx->auto_commit = FALSE;
if (trx->fts_trx) {
trx_finalize_for_fts(trx, not_rollback);
}
ut_ad(trx->lock.wait_thr == NULL);
ut_ad(UT_LIST_GET_LEN(trx->lock.trx_locks) == 0);
ut_ad(!trx->in_ro_trx_list);
ut_ad(!trx->in_rw_trx_list);
trx->dict_operation = TRX_DICT_OP_NONE;
trx->error_state = DB_SUCCESS;
/* trx->in_mysql_trx_list would hold between
trx_allocate_for_mysql() and trx_free_for_mysql(). It does not
hold for recovered transactions or system transactions. */
}
/****************************************************************//**
Commits a transaction and a mini-transaction. */
UNIV_INTERN
void
trx_commit_low(
/*===========*/
trx_t* trx, /*!< in/out: transaction */
mtr_t* mtr, /*!< in/out: mini-transaction (will be committed),
or NULL if trx made no modifications */
ibool for_commit) /*!< in: for rollback when FALSE */
{
lsn_t lsn;
assert_trx_nonlocking_or_in_list(trx);
ut_ad(!trx_state_eq(trx, TRX_STATE_COMMITTED_IN_MEMORY));
ut_ad(!mtr || mtr->state == MTR_ACTIVE);
ut_ad(!mtr == !(trx->insert_undo || trx->update_undo));
/* undo_no is non-zero if we're doing the final commit. */
if (trx->fts_trx && trx->undo_no != 0) {
dberr_t error;
ut_a(!trx_is_autocommit_non_locking(trx));
error = fts_commit(trx);
/* FTS-FIXME: Temporarily tolerate DB_DUPLICATE_KEY
instead of dying. This is a possible scenario if there
is a crash between insert to DELETED table committing
and transaction committing. The fix would be able to
return error from this function */
if (error != DB_SUCCESS && error != DB_DUPLICATE_KEY) {
/* FTS-FIXME: once we can return values from this
function, we should do so and signal an error
instead of just dying. */
ut_error;
}
}
if (mtr) {
trx_write_serialisation_history(trx, mtr);
/* The following call commits the mini-transaction, making the
whole transaction committed in the file-based world, at this
log sequence number. The transaction becomes 'durable' when
we write the log to disk, but in the logical sense the commit
in the file-based data structures (undo logs etc.) happens
here.
NOTE that transaction numbers, which are assigned only to
transactions with an update undo log, do not necessarily come
in exactly the same order as commit lsn's, if the transactions
have different rollback segments. To get exactly the same
order we should hold the kernel mutex up to this point,
adding to the contention of the kernel mutex. However, if
a transaction T2 is able to see modifications made by
a transaction T1, T2 will always get a bigger transaction
number and a bigger commit lsn than T1. */
/*--------------*/
mtr_commit(mtr);
/*--------------*/
lsn = mtr->end_lsn;
} else {
lsn = 0;
}
trx_commit_in_memory(trx, lsn, for_commit);
}
/****************************************************************//**
Commits a transaction. */
UNIV_INTERN
void
trx_commit(
trx_t* trx, /*!< in/out: transaction */
ibool for_commit) /*!< in: for rollback when FALSE */
{
mtr_t local_mtr;
mtr_t* mtr;
if (trx->insert_undo || trx->update_undo) {
mtr = &local_mtr;
mtr_start(mtr);
} else {
mtr = NULL;
}
trx_commit_low(trx, mtr, for_commit);
}
/****************************************************************//**
Cleans up a transaction at database startup. The cleanup is needed if
the transaction already got to the middle of a commit when the database
crashed, and we cannot roll it back. */
UNIV_INTERN
void
trx_cleanup_at_db_startup(
/*======================*/
trx_t* trx) /*!< in: transaction */
{
ut_ad(trx->is_recovered);
if (trx->insert_undo != NULL) {
trx_undo_insert_cleanup(trx);
}
trx->rseg = NULL;
trx->undo_no = 0;
trx->last_sql_stat_start.least_undo_no = 0;
mutex_enter(&trx_sys->mutex);
ut_a(!trx->read_only);
UT_LIST_REMOVE(trx_list, trx_sys->rw_trx_list, trx);
assert_trx_in_rw_list(trx);
ut_d(trx->in_rw_trx_list = FALSE);
mutex_exit(&trx_sys->mutex);
/* Change the transaction state without mutex protection, now
that it no longer is in the trx_list. Recovered transactions
are never placed in the mysql_trx_list. */
ut_ad(trx->is_recovered);
ut_ad(!trx->in_ro_trx_list);
ut_ad(!trx->in_rw_trx_list);
ut_ad(!trx->in_mysql_trx_list);
trx->state = TRX_STATE_NOT_STARTED;
}
/********************************************************************//**
Assigns a read view for a consistent read query. All the consistent reads
within the same transaction will get the same read view, which is created
when this function is first called for a new started transaction.
@return consistent read view */
UNIV_INTERN
read_view_t*
trx_assign_read_view(
/*=================*/
trx_t* trx) /*!< in: active transaction */
{
ut_ad(trx->state == TRX_STATE_ACTIVE);
if (trx->read_view != NULL) {
return(trx->read_view);
}
if (!trx->read_view) {
trx->read_view = read_view_open_now(
trx->id, trx->global_read_view_heap);
trx->global_read_view = trx->read_view;
}
return(trx->read_view);
}
/****************************************************************//**
Prepares a transaction for commit/rollback. */
UNIV_INTERN
void
trx_commit_or_rollback_prepare(
/*===========================*/
trx_t* trx) /*!< in/out: transaction */
{
/* We are reading trx->state without holding trx_sys->mutex
here, because the commit or rollback should be invoked for a
running (or recovered prepared) transaction that is associated
with the current thread. */
switch (trx->state) {
case TRX_STATE_NOT_STARTED:
trx_start_low(trx);
/* fall through */
case TRX_STATE_ACTIVE:
case TRX_STATE_PREPARED:
/* If the trx is in a lock wait state, moves the waiting
query thread to the suspended state */
if (trx->lock.que_state == TRX_QUE_LOCK_WAIT) {
ut_a(trx->lock.wait_thr != NULL);
trx->lock.wait_thr->state = QUE_THR_SUSPENDED;
trx->lock.wait_thr = NULL;
trx->lock.que_state = TRX_QUE_RUNNING;
}
ut_a(trx->lock.n_active_thrs == 1);
return;
case TRX_STATE_COMMITTED_IN_MEMORY:
break;
}
ut_error;
}
/*********************************************************************//**
Creates a commit command node struct.
@return own: commit node struct */
UNIV_INTERN
commit_node_t*
trx_commit_node_create(
/*===================*/
mem_heap_t* heap) /*!< in: mem heap where created */
{
commit_node_t* node;
node = static_cast<commit_node_t*>(mem_heap_alloc(heap, sizeof(*node)));
node->common.type = QUE_NODE_COMMIT;
node->state = COMMIT_NODE_SEND;
return(node);
}
/***********************************************************//**
Performs an execution step for a commit type node in a query graph.
@return query thread to run next, or NULL */
UNIV_INTERN
que_thr_t*
trx_commit_step(
/*============*/
que_thr_t* thr) /*!< in: query thread */
{
commit_node_t* node;
node = static_cast<commit_node_t*>(thr->run_node);
ut_ad(que_node_get_type(node) == QUE_NODE_COMMIT);
if (thr->prev_node == que_node_get_parent(node)) {
node->state = COMMIT_NODE_SEND;
}
if (node->state == COMMIT_NODE_SEND) {
trx_t* trx;
node->state = COMMIT_NODE_WAIT;
trx = thr_get_trx(thr);
ut_a(trx->lock.wait_thr == NULL);
ut_a(trx->lock.que_state != TRX_QUE_LOCK_WAIT);
trx_commit_or_rollback_prepare(trx);
trx->lock.que_state = TRX_QUE_COMMITTING;
trx_commit(trx, TRUE);
ut_ad(trx->lock.wait_thr == NULL);
trx->lock.que_state = TRX_QUE_RUNNING;
thr = NULL;
} else {
ut_ad(node->state == COMMIT_NODE_WAIT);
node->state = COMMIT_NODE_SEND;
thr->run_node = que_node_get_parent(node);
}
return(thr);
}
/**********************************************************************//**
Does the transaction commit for MySQL.
@return DB_SUCCESS or error number */
UNIV_INTERN
dberr_t
trx_commit_for_mysql(
/*=================*/
trx_t* trx) /*!< in/out: transaction */
{
/* Because we do not do the commit by sending an Innobase
sig to the transaction, we must here make sure that trx has been
started. */
ut_a(trx);
switch (trx->state) {
case TRX_STATE_NOT_STARTED:
/* Update the info whether we should skip XA steps that eat
CPU time.
For the duration of the transaction trx->support_xa is
not reread from thd so any changes in the value take
effect in the next transaction. This is to avoid a
scenario where some undo log records generated by a
transaction contain XA information and other undo log
records, generated by the same transaction do not. */
trx->support_xa = thd_supports_xa(trx->mysql_thd);
ut_d(trx->start_file = __FILE__);
ut_d(trx->start_line = __LINE__);
trx_start_low(trx);
/* fall through */
case TRX_STATE_ACTIVE:
case TRX_STATE_PREPARED:
trx->op_info = "committing";
trx_commit(trx, TRUE);
MONITOR_DEC(MONITOR_TRX_ACTIVE);
trx->op_info = "";
return(DB_SUCCESS);
case TRX_STATE_COMMITTED_IN_MEMORY:
break;
}
ut_error;
return(DB_CORRUPTION);
}
/**********************************************************************//**
If required, flushes the log to disk if we called trx_commit_for_mysql()
with trx->flush_log_later == TRUE. */
UNIV_INTERN
void
trx_commit_complete_for_mysql(
/*==========================*/
trx_t* trx, /*!< in/out: transaction */
ibool async) /*!< in: TRUE - don't sync log */
{
ut_a(trx);
if (!trx->must_flush_log_later
|| thd_requested_durability(trx->mysql_thd)
== HA_IGNORE_DURABILITY) {
return;
}
trx_flush_log_if_needed(trx->commit_lsn, trx, async);
trx->must_flush_log_later = FALSE;
}
/**********************************************************************//**
Marks the latest SQL statement ended. */
UNIV_INTERN
void
trx_mark_sql_stat_end(
/*==================*/
trx_t* trx) /*!< in: trx handle */
{
ut_a(trx);
switch (trx->state) {
case TRX_STATE_PREPARED:
case TRX_STATE_COMMITTED_IN_MEMORY:
break;
case TRX_STATE_NOT_STARTED:
trx->undo_no = 0;
/* fall through */
case TRX_STATE_ACTIVE:
trx->last_sql_stat_start.least_undo_no = trx->undo_no;
if (trx->fts_trx) {
fts_savepoint_laststmt_refresh(trx);
}
return;
}
ut_error;
}
/**********************************************************************//**
Prints info about a transaction.
Caller must hold trx_sys->mutex. */
UNIV_INTERN
void
trx_print_low(
/*==========*/
FILE* f,
/*!< in: output stream */
const trx_t* trx,
/*!< in: transaction */
ulint max_query_len,
/*!< in: max query length to print,
or 0 to use the default max length */
ulint n_rec_locks,
/*!< in: lock_number_of_rows_locked(&trx->lock) */
ulint n_trx_locks,
/*!< in: length of trx->lock.trx_locks */
ulint heap_size)
/*!< in: mem_heap_get_size(trx->lock.lock_heap) */
{
ibool newline;
const char* op_info;
ut_ad(mutex_own(&trx_sys->mutex));
fprintf(f, "TRANSACTION " TRX_ID_FMT, trx->id);
/* trx->state cannot change from or to NOT_STARTED while we
are holding the trx_sys->mutex. It may change from ACTIVE to
PREPARED or COMMITTED. */
switch (trx->state) {
case TRX_STATE_NOT_STARTED:
fputs(", not started", f);
goto state_ok;
case TRX_STATE_ACTIVE:
fprintf(f, ", ACTIVE %lu sec",
(ulong) difftime(time(NULL), trx->start_time));
goto state_ok;
case TRX_STATE_PREPARED:
fprintf(f, ", ACTIVE (PREPARED) %lu sec",
(ulong) difftime(time(NULL), trx->start_time));
goto state_ok;
case TRX_STATE_COMMITTED_IN_MEMORY:
fputs(", COMMITTED IN MEMORY", f);
goto state_ok;
}
fprintf(f, ", state %lu", (ulong) trx->state);
ut_ad(0);
state_ok:
/* prevent a race condition */
op_info = trx->op_info;
if (*op_info) {
putc(' ', f);
fputs(op_info, f);
}
if (trx->is_recovered) {
fputs(" recovered trx", f);
}
if (trx->declared_to_be_inside_innodb) {
fprintf(f, ", thread declared inside InnoDB %lu",
(ulong) trx->n_tickets_to_enter_innodb);
}
putc('\n', f);
if (trx->n_mysql_tables_in_use > 0 || trx->mysql_n_tables_locked > 0) {
fprintf(f, "mysql tables in use %lu, locked %lu\n",
(ulong) trx->n_mysql_tables_in_use,
(ulong) trx->mysql_n_tables_locked);
}
newline = TRUE;
/* trx->lock.que_state of an ACTIVE transaction may change
while we are not holding trx->mutex. We perform a dirty read
for performance reasons. */
switch (trx->lock.que_state) {
case TRX_QUE_RUNNING:
newline = FALSE; break;
case TRX_QUE_LOCK_WAIT:
fputs("LOCK WAIT ", f); break;
case TRX_QUE_ROLLING_BACK:
fputs("ROLLING BACK ", f); break;
case TRX_QUE_COMMITTING:
fputs("COMMITTING ", f); break;
default:
fprintf(f, "que state %lu ", (ulong) trx->lock.que_state);
}
if (n_trx_locks > 0 || heap_size > 400) {
newline = TRUE;
fprintf(f, "%lu lock struct(s), heap size %lu,"
" %lu row lock(s)",
(ulong) n_trx_locks,
(ulong) heap_size,
(ulong) n_rec_locks);
}
if (trx->has_search_latch) {
newline = TRUE;
fputs(", holds adaptive hash latch", f);
}
if (trx->undo_no != 0) {
newline = TRUE;
fprintf(f, ", undo log entries " TRX_ID_FMT, trx->undo_no);
}
if (newline) {
putc('\n', f);
}
if (trx->mysql_thd != NULL) {
innobase_mysql_print_thd(
f, trx->mysql_thd, static_cast<uint>(max_query_len));
}
}
/**********************************************************************//**
Prints info about a transaction.
The caller must hold lock_sys->mutex and trx_sys->mutex.
When possible, use trx_print() instead. */
UNIV_INTERN
void
trx_print_latched(
/*==============*/
FILE* f, /*!< in: output stream */
const trx_t* trx, /*!< in: transaction */
ulint max_query_len) /*!< in: max query length to print,
or 0 to use the default max length */
{
ut_ad(lock_mutex_own());
ut_ad(mutex_own(&trx_sys->mutex));
trx_print_low(f, trx, max_query_len,
lock_number_of_rows_locked(&trx->lock),
UT_LIST_GET_LEN(trx->lock.trx_locks),
mem_heap_get_size(trx->lock.lock_heap));
}
/**********************************************************************//**
Prints info about a transaction.
Acquires and releases lock_sys->mutex and trx_sys->mutex. */
UNIV_INTERN
void
trx_print(
/*======*/
FILE* f, /*!< in: output stream */
const trx_t* trx, /*!< in: transaction */
ulint max_query_len) /*!< in: max query length to print,
or 0 to use the default max length */
{
ulint n_rec_locks;
ulint n_trx_locks;
ulint heap_size;
lock_mutex_enter();
n_rec_locks = lock_number_of_rows_locked(&trx->lock);
n_trx_locks = UT_LIST_GET_LEN(trx->lock.trx_locks);
heap_size = mem_heap_get_size(trx->lock.lock_heap);
lock_mutex_exit();
mutex_enter(&trx_sys->mutex);
trx_print_low(f, trx, max_query_len,
n_rec_locks, n_trx_locks, heap_size);
mutex_exit(&trx_sys->mutex);
}
#ifdef UNIV_DEBUG
/**********************************************************************//**
Asserts that a transaction has been started.
The caller must hold trx_sys->mutex.
@return TRUE if started */
UNIV_INTERN
ibool
trx_assert_started(
/*===============*/
const trx_t* trx) /*!< in: transaction */
{
ut_ad(mutex_own(&trx_sys->mutex));
/* Non-locking autocommits should not hold any locks and this
function is only called from the locking code. */
assert_trx_in_list(trx);
/* trx->state can change from or to NOT_STARTED while we are holding
trx_sys->mutex for non-locking autocommit selects but not for other
types of transactions. It may change from ACTIVE to PREPARED. Unless
we are holding lock_sys->mutex, it may also change to COMMITTED. */
switch (trx->state) {
case TRX_STATE_PREPARED:
return(TRUE);
case TRX_STATE_ACTIVE:
case TRX_STATE_COMMITTED_IN_MEMORY:
return(TRUE);
case TRX_STATE_NOT_STARTED:
break;
}
ut_error;
return(FALSE);
}
#endif /* UNIV_DEBUG */
/*******************************************************************//**
Compares the "weight" (or size) of two transactions. Transactions that
have edited non-transactional tables are considered heavier than ones
that have not.
@return TRUE if weight(a) >= weight(b) */
UNIV_INTERN
ibool
trx_weight_ge(
/*==========*/
const trx_t* a, /*!< in: the first transaction to be compared */
const trx_t* b) /*!< in: the second transaction to be compared */
{
ibool a_notrans_edit;
ibool b_notrans_edit;
/* If mysql_thd is NULL for a transaction we assume that it has
not edited non-transactional tables. */
a_notrans_edit = a->mysql_thd != NULL
&& thd_has_edited_nontrans_tables(a->mysql_thd);
b_notrans_edit = b->mysql_thd != NULL
&& thd_has_edited_nontrans_tables(b->mysql_thd);
if (a_notrans_edit != b_notrans_edit) {
return(a_notrans_edit);
}
/* Either both had edited non-transactional tables or both had
not, we fall back to comparing the number of altered/locked
rows. */
#if 0
fprintf(stderr,
"%s TRX_WEIGHT(a): %lld+%lu, TRX_WEIGHT(b): %lld+%lu\n",
__func__,
a->undo_no, UT_LIST_GET_LEN(a->lock.trx_locks),
b->undo_no, UT_LIST_GET_LEN(b->lock.trx_locks));
#endif
return(TRX_WEIGHT(a) >= TRX_WEIGHT(b));
}
/****************************************************************//**
Prepares a transaction. */
static
void
trx_prepare(
/*========*/
trx_t* trx, /*!< in/out: transaction */
ibool async) /*!< in: TRUE - don't sync log */
{
trx_rseg_t* rseg;
lsn_t lsn;
mtr_t mtr;
rseg = trx->rseg;
/* Only fresh user transactions can be prepared.
Recovered transactions cannot. */
ut_a(!trx->is_recovered);
if (trx->insert_undo != NULL || trx->update_undo != NULL) {
mtr_start(&mtr);
/* Change the undo log segment states from TRX_UNDO_ACTIVE
to TRX_UNDO_PREPARED: these modifications to the file data
structure define the transaction as prepared in the
file-based world, at the serialization point of lsn. */
mutex_enter(&rseg->mutex);
if (trx->insert_undo != NULL) {
/* It is not necessary to obtain trx->undo_mutex here
because only a single OS thread is allowed to do the
transaction prepare for this transaction. */
trx_undo_set_state_at_prepare(trx, trx->insert_undo,
&mtr);
}
if (trx->update_undo) {
trx_undo_set_state_at_prepare(
trx, trx->update_undo, &mtr);
}
mutex_exit(&rseg->mutex);
/*--------------*/
mtr_commit(&mtr); /* This mtr commit makes the
transaction prepared in the file-based
world */
/*--------------*/
lsn = mtr.end_lsn;
ut_ad(lsn);
} else {
lsn = 0;
}
/*--------------------------------------*/
ut_a(trx->state == TRX_STATE_ACTIVE);
mutex_enter(&trx_sys->mutex);
trx->state = TRX_STATE_PREPARED;
trx_sys->n_prepared_trx++;
mutex_exit(&trx_sys->mutex);
/*--------------------------------------*/
if (lsn) {
switch (thd_requested_durability(trx->mysql_thd)) {
case HA_IGNORE_DURABILITY:
/* We set the HA_IGNORE_DURABILITY during prepare phase of
binlog group commit to not flush redo log for every transaction
here. So that we can flush prepared records of transactions to
redo log in a group right before writing them to binary log
during flush stage of binlog group commit. */
thd_store_lsn(trx->mysql_thd, lsn, innobase_get_type());
break;
case HA_REGULAR_DURABILITY:
/* Depending on the my.cnf options, we may now write the log
buffer to the log files, making the prepared state of the
transaction durable if the OS does not crash. We may also
flush the log files to disk, making the prepared state of the
transaction durable also at an OS crash or a power outage.
The idea in InnoDB's group prepare is that a group of
transactions gather behind a trx doing a physical disk write
to log files, and when that physical write has been completed,
one of those transactions does a write which prepares the whole
group. Note that this group prepare will only bring benefit if
there are > 2 users in the database. Then at least 2 users can
gather behind one doing the physical log write to disk.
We must not be holding any mutexes or latches here. */
trx_flush_log_if_needed(lsn, trx, async);
break;
}
}
}
/**********************************************************************//**
Does the transaction prepare for MySQL. */
UNIV_INTERN
void
trx_prepare_for_mysql(
/*==================*/
trx_t* trx, /*!< in/out: trx handle */
ibool async) /*!< in: TRUE - don't sync log */
{
trx_start_if_not_started_xa(trx);
trx->op_info = "preparing";
trx_prepare(trx, async);
trx->op_info = "";
}
/**********************************************************************//**
This function is used to find number of prepared transactions and
their transaction objects for a recovery.
@return number of prepared transactions stored in xid_list */
UNIV_INTERN
int
trx_recover_for_mysql(
/*==================*/
XID* xid_list, /*!< in/out: prepared transactions */
ulint len) /*!< in: number of slots in xid_list */
{
const trx_t* trx;
ulint count = 0;
ut_ad(xid_list);
ut_ad(len);
/* We should set those transactions which are in the prepared state
to the xid_list */
mutex_enter(&trx_sys->mutex);
for (trx = UT_LIST_GET_FIRST(trx_sys->rw_trx_list);
trx != NULL;
trx = UT_LIST_GET_NEXT(trx_list, trx)) {
assert_trx_in_rw_list(trx);
/* The state of a read-write transaction cannot change
from or to NOT_STARTED while we are holding the
trx_sys->mutex. It may change to PREPARED, but not if
trx->is_recovered. It may also change to COMMITTED. */
if (trx_state_eq(trx, TRX_STATE_PREPARED)) {
xid_list[count] = trx->xid;
if (count == 0) {
ut_print_timestamp(stderr);
fprintf(stderr,
" InnoDB: Starting recovery for"
" XA transactions...\n");
}
ut_print_timestamp(stderr);
fprintf(stderr,
" InnoDB: Transaction " TRX_ID_FMT " in"
" prepared state after recovery\n",
trx->id);
ut_print_timestamp(stderr);
fprintf(stderr,
" InnoDB: Transaction contains changes"
" to " TRX_ID_FMT " rows\n",
trx->undo_no);
count++;
if (count == len) {
break;
}
}
}
mutex_exit(&trx_sys->mutex);
if (count > 0){
ut_print_timestamp(stderr);
fprintf(stderr,
" InnoDB: %d transactions in prepared state"
" after recovery\n",
int (count));
}
return(int (count));
}
/*******************************************************************//**
This function is used to find one X/Open XA distributed transaction
which is in the prepared state
@return trx on match, the trx->xid will be invalidated;
note that the trx may have been committed, unless the caller is
holding lock_sys->mutex */
static __attribute__((nonnull, warn_unused_result))
trx_t*
trx_get_trx_by_xid_low(
/*===================*/
const XID* xid) /*!< in: X/Open XA transaction
identifier */
{
trx_t* trx;
ut_ad(mutex_own(&trx_sys->mutex));
for (trx = UT_LIST_GET_FIRST(trx_sys->rw_trx_list);
trx != NULL;
trx = UT_LIST_GET_NEXT(trx_list, trx)) {
assert_trx_in_rw_list(trx);
/* Compare two X/Open XA transaction id's: their
length should be the same and binary comparison
of gtrid_length+bqual_length bytes should be
the same */
if (trx->is_recovered
&& trx_state_eq(trx, TRX_STATE_PREPARED)
&& xid->gtrid_length == trx->xid.gtrid_length
&& xid->bqual_length == trx->xid.bqual_length
&& memcmp(xid->data, trx->xid.data,
xid->gtrid_length + xid->bqual_length) == 0) {
/* Invalidate the XID, so that subsequent calls
will not find it. */
memset(&trx->xid, 0, sizeof(trx->xid));
trx->xid.formatID = -1;
break;
}
}
return(trx);
}
/*******************************************************************//**
This function is used to find one X/Open XA distributed transaction
which is in the prepared state
@return trx or NULL; on match, the trx->xid will be invalidated;
note that the trx may have been committed, unless the caller is
holding lock_sys->mutex */
UNIV_INTERN
trx_t*
trx_get_trx_by_xid(
/*===============*/
const XID* xid) /*!< in: X/Open XA transaction identifier */
{
trx_t* trx;
if (xid == NULL) {
return(NULL);
}
mutex_enter(&trx_sys->mutex);
/* Recovered/Resurrected transactions are always only on the
trx_sys_t::rw_trx_list. */
trx = trx_get_trx_by_xid_low(xid);
mutex_exit(&trx_sys->mutex);
return(trx);
}
/*************************************************************//**
Starts the transaction if it is not yet started. */
UNIV_INTERN
void
trx_start_if_not_started_xa_low(
/*============================*/
trx_t* trx) /*!< in: transaction */
{
switch (trx->state) {
case TRX_STATE_NOT_STARTED:
/* Update the info whether we should skip XA steps
that eat CPU time.
For the duration of the transaction trx->support_xa is
not reread from thd so any changes in the value take
effect in the next transaction. This is to avoid a
scenario where some undo generated by a transaction,
has XA stuff, and other undo, generated by the same
transaction, doesn't. */
#ifdef XTRABACKUP
trx->support_xa = trx->mysql_thd
? thd_supports_xa(trx->mysql_thd) : FALSE;
#else /* XTRABACKUP */
trx->support_xa = thd_supports_xa(trx->mysql_thd);
#endif /* XTRABACKUP */
trx_start_low(trx);
/* fall through */
case TRX_STATE_ACTIVE:
return;
case TRX_STATE_PREPARED:
case TRX_STATE_COMMITTED_IN_MEMORY:
break;
}
ut_error;
}
/*************************************************************//**
Starts the transaction if it is not yet started. */
UNIV_INTERN
void
trx_start_if_not_started_low(
/*=========================*/
trx_t* trx) /*!< in: transaction */
{
switch (trx->state) {
case TRX_STATE_NOT_STARTED:
trx_start_low(trx);
/* fall through */
case TRX_STATE_ACTIVE:
return;
case TRX_STATE_PREPARED:
case TRX_STATE_COMMITTED_IN_MEMORY:
break;
}
ut_error;
}
/*************************************************************//**
Starts the transaction for a DDL operation. */
UNIV_INTERN
void
trx_start_for_ddl_low(
/*==================*/
trx_t* trx, /*!< in/out: transaction */
trx_dict_op_t op) /*!< in: dictionary operation type */
{
switch (trx->state) {
case TRX_STATE_NOT_STARTED:
/* Flag this transaction as a dictionary operation, so that
the data dictionary will be locked in crash recovery. */
trx_set_dict_operation(trx, op);
/* Ensure it is not flagged as an auto-commit-non-locking
transation. */
trx->will_lock = 1;
trx->ddl = true;
trx_start_low(trx);
return;
case TRX_STATE_ACTIVE:
/* We have this start if not started idiom, therefore we
can't add stronger checks here. */
trx->ddl = true;
ut_ad(trx->dict_operation != TRX_DICT_OP_NONE);
ut_ad(trx->will_lock > 0);
return;
case TRX_STATE_PREPARED:
case TRX_STATE_COMMITTED_IN_MEMORY:
break;
}
ut_error;
}
| 70,728 | 29,295 |
/*************************************************************************
*
* Lavabo
*__________________
*
* Program.ViewDisplay2D_3D.cpp
*
* Clement Berthaud - Layl
* Please refer to LICENSE.TXT
*/
#include "Program.ViewDisplay2D_3D.h"
#include <QGraphicsItem>
#include <QGraphicsProxyWidget>
#include "ViewDisplay2D.h"
#include "ViewDisplay3D.h"
#include "Model3D.h"
#include "Shader3D.h"
namespace nProgram {
namespace nViewDisplay2D_3D {
//--------------------------------------------------------------------------------------
//----------------------------------------------------------- Construction / Destruction
cProgram_ViewDisplay2D_3D::~cProgram_ViewDisplay2D_3D()
{
Destroy();
}
cProgram_ViewDisplay2D_3D::cProgram_ViewDisplay2D_3D( QWidget* parent ) :
tSuperClass( parent ),
mViewDisplay2D( NULL ),
mViewDisplay3D( NULL ),
mProxyViewDisplay3D( NULL ),
mModel3D( NULL ),
mShader3D( NULL )
{
Init();
Build();
Compose();
}
//--------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------- Event
void
cProgram_ViewDisplay2D_3D::resizeEvent( QResizeEvent* event )
{
tSuperClass::resizeEvent( event );
Compose();
}
//--------------------------------------------------------------------------------------
//------------------------------------------------------------------------ GUI utilities
void
cProgram_ViewDisplay2D_3D::Init()
{
mViewDisplay2D = new cViewDisplay2D( this );
mViewDisplay3D = new cViewDisplay3D();
mProxyViewDisplay3D = new QGraphicsProxyWidget();
mModel3D = new cModel3D( "resources/obj3d/bunny.obj");
mShader3D = new cShader3D( "resources/shaders/ViewDisplay3D.vert", "resources/shaders/ViewDisplay3D.frag" );
}
void
cProgram_ViewDisplay2D_3D::Build()
{
mViewDisplay3D->SetModel3D( mModel3D );
mViewDisplay3D->SetShader3D( mShader3D );
mProxyViewDisplay3D->setWidget( mViewDisplay3D );
mViewDisplay2D->setCenterItem( mProxyViewDisplay3D );
//QObject::connect( mViewDisplay3D, SIGNAL( PaintCompleted() ), mViewDisplay2D, SLOT( update() ) );
}
void
cProgram_ViewDisplay2D_3D::Compose()
{
mViewDisplay3D->resize( size() );
mProxyViewDisplay3D->resize( size() );
mViewDisplay2D->resize( size() );
}
void
cProgram_ViewDisplay2D_3D::Destroy()
{
delete mViewDisplay2D;
}
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
// Registry Callback
QWidget* RegistryCallback()
{
return new cProgram_ViewDisplay2D_3D();
}
} // namespace nViewDisplay2D_3D
} // namespace nProgram
| 2,868 | 866 |
// Copyright (c) 2012-2014 Plenluno All rights reserved.
#include <libnode/buffer.h>
#include <libnode/detail/buffer.h>
namespace libj {
namespace node {
Buffer::Ptr Buffer::create(Size length) {
return Ptr(new detail::Buffer<Buffer>(length));
}
Buffer::Ptr Buffer::create(const void* data, Size length) {
if (!data) return null();
detail::Buffer<Buffer>* buf(new detail::Buffer<Buffer>(length));
const UByte* src = static_cast<const UByte*>(data);
UByte* dst = static_cast<UByte*>(const_cast<void*>(buf->data()));
std::copy(src, src + length, dst);
return Ptr(buf);
}
Buffer::Ptr Buffer::create(TypedJsArray<UByte>::CPtr array) {
if (!array) return null();
Size length = array->length();
detail::Buffer<Buffer>* buf(new detail::Buffer<Buffer>(length));
for (Size i = 0; i < length; i++) {
buf->writeUInt8(array->getTyped(i), i);
}
return Ptr(buf);
}
template<typename T>
static Buffer::Ptr createBuffer(T t, Buffer::Encoding enc) {
if (!t) return Buffer::null();
std::string s;
switch (enc) {
case Buffer::UTF8:
s = t->toStdString();
return Buffer::create(
reinterpret_cast<const UByte*>(s.c_str()),
s.length());
case Buffer::UTF16BE:
s = t->toStdString(String::UTF16BE);
return Buffer::create(
reinterpret_cast<const UByte*>(s.c_str()),
s.length() - 2); // delete the last null character
case Buffer::UTF16LE:
s = t->toStdString(String::UTF16LE);
return Buffer::create(
reinterpret_cast<const UByte*>(s.c_str()),
s.length() - 2); // delete the last null character
case Buffer::UTF32BE:
s = t->toStdString(String::UTF32BE);
return Buffer::create(
reinterpret_cast<const UByte*>(s.c_str()),
s.length() - 4); // delete the last null character
case Buffer::UTF32LE:
s = t->toStdString(String::UTF32LE);
return Buffer::create(
reinterpret_cast<const UByte*>(s.c_str()),
s.length() - 4); // delete the last null character
case Buffer::BASE64:
return util::base64Decode(t);
case Buffer::HEX:
return util::hexDecode(t);
default:
return Buffer::null();
}
}
Buffer::Ptr Buffer::create(String::CPtr str, Buffer::Encoding enc) {
return createBuffer<String::CPtr>(str, enc);
}
Buffer::Ptr Buffer::create(StringBuilder::CPtr sb, Buffer::Encoding enc) {
return createBuffer<StringBuilder::CPtr>(sb, enc);
}
} // namespace node
} // namespace libj
| 2,592 | 852 |
#include <AK/JsonArray.h>
#include <AK/JsonObject.h>
#include <AK/JsonValue.h>
#include <LibCore/CFile.h>
#include <LibCore/CProcessStatisticsReader.h>
#include <pwd.h>
#include <stdio.h>
HashMap<uid_t, String> CProcessStatisticsReader::s_usernames;
HashMap<pid_t, CProcessStatistics> CProcessStatisticsReader::get_all()
{
CFile file("/proc/all");
if (!file.open(CIODevice::ReadOnly)) {
fprintf(stderr, "CProcessStatisticsReader: Failed to open /proc/all: %s\n", file.error_string());
return {};
}
HashMap<pid_t, CProcessStatistics> map;
auto file_contents = file.read_all();
auto json = JsonValue::from_string({ file_contents.data(), file_contents.size() });
json.as_array().for_each([&](auto& value) {
const JsonObject& process_object = value.as_object();
CProcessStatistics process;
process.pid = process_object.get("pid").to_u32();
process.nsched = process_object.get("times_scheduled").to_u32();
process.uid = process_object.get("uid").to_u32();
process.username = username_from_uid(process.uid);
process.priority = process_object.get("priority").to_string();
process.syscalls = process_object.get("syscall_count").to_u32();
process.state = process_object.get("state").to_string();
process.name = process_object.get("name").to_string();
process.virtual_size = process_object.get("amount_virtual").to_u32();
process.physical_size = process_object.get("amount_resident").to_u32();
map.set(process.pid, process);
});
return map;
}
String CProcessStatisticsReader::username_from_uid(uid_t uid)
{
if (s_usernames.is_empty()) {
setpwent();
while (auto* passwd = getpwent())
s_usernames.set(passwd->pw_uid, passwd->pw_name);
endpwent();
}
auto it = s_usernames.find(uid);
if (it != s_usernames.end())
return (*it).value;
return String::number(uid);
}
| 1,977 | 670 |
// Copyright (c) 2012 The Chromium Embedded Framework 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 "tests/unittests/test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
void TestBinaryEqual(CefRefPtr<CefBinaryValue> val1,
CefRefPtr<CefBinaryValue> val2) {
EXPECT_TRUE(val1.get());
EXPECT_TRUE(val2.get());
size_t data_size = val1->GetSize();
EXPECT_EQ(data_size, val2->GetSize());
EXPECT_GT(data_size, (size_t)0);
char* data1 = new char[data_size+1];
char* data2 = new char[data_size+1];
EXPECT_EQ(data_size, val1->GetData(data1, data_size, 0));
data1[data_size] = 0;
EXPECT_EQ(data_size, val2->GetData(data2, data_size, 0));
data2[data_size] = 0;
EXPECT_STREQ(data1, data2);
delete [] data1;
delete [] data2;
}
void TestDictionaryEqual(CefRefPtr<CefDictionaryValue> val1,
CefRefPtr<CefDictionaryValue> val2) {
EXPECT_TRUE(val1.get());
EXPECT_TRUE(val2.get());
EXPECT_EQ(val1->GetSize(), val2->GetSize());
CefDictionaryValue::KeyList keys;
EXPECT_TRUE(val1->GetKeys(keys));
CefDictionaryValue::KeyList::const_iterator it = keys.begin();
for (; it != keys.end(); ++it) {
CefString key = *it;
EXPECT_TRUE(val2->HasKey(key));
CefValueType type = val1->GetType(key);
EXPECT_EQ(type, val2->GetType(key));
switch (type) {
case VTYPE_INVALID:
case VTYPE_NULL:
break;
case VTYPE_BOOL:
EXPECT_EQ(val1->GetBool(key), val2->GetBool(key));
break;
case VTYPE_INT:
EXPECT_EQ(val1->GetInt(key), val2->GetInt(key));
break;
case VTYPE_DOUBLE:
EXPECT_EQ(val1->GetDouble(key), val2->GetDouble(key));
break;
case VTYPE_STRING:
EXPECT_EQ(val1->GetString(key), val2->GetString(key));
break;
case VTYPE_BINARY:
TestBinaryEqual(val1->GetBinary(key), val2->GetBinary(key));
break;
case VTYPE_DICTIONARY:
TestDictionaryEqual(val1->GetDictionary(key), val2->GetDictionary(key));
break;
case VTYPE_LIST:
TestListEqual(val1->GetList(key), val2->GetList(key));
break;
}
}
}
void TestListEqual(CefRefPtr<CefListValue> val1,
CefRefPtr<CefListValue> val2) {
EXPECT_TRUE(val1.get());
EXPECT_TRUE(val2.get());
size_t size = val1->GetSize();
EXPECT_EQ(size, val2->GetSize());
for (size_t i = 0; i < size; ++i) {
CefValueType type = val1->GetType(i);
EXPECT_EQ(type, val2->GetType(i));
switch (type) {
case VTYPE_INVALID:
case VTYPE_NULL:
break;
case VTYPE_BOOL:
EXPECT_EQ(val1->GetBool(i), val2->GetBool(i));
break;
case VTYPE_INT:
EXPECT_EQ(val1->GetInt(i), val2->GetInt(i));
break;
case VTYPE_DOUBLE:
EXPECT_EQ(val1->GetDouble(i), val2->GetDouble(i));
break;
case VTYPE_STRING:
EXPECT_EQ(val1->GetString(i), val2->GetString(i));
break;
case VTYPE_BINARY:
TestBinaryEqual(val1->GetBinary(i), val2->GetBinary(i));
break;
case VTYPE_DICTIONARY:
TestDictionaryEqual(val1->GetDictionary(i), val2->GetDictionary(i));
break;
case VTYPE_LIST:
TestListEqual(val1->GetList(i), val2->GetList(i));
break;
}
}
}
void TestProcessMessageEqual(CefRefPtr<CefProcessMessage> val1,
CefRefPtr<CefProcessMessage> val2) {
EXPECT_TRUE(val1.get());
EXPECT_TRUE(val2.get());
EXPECT_EQ(val1->GetName(), val2->GetName());
TestListEqual(val1->GetArgumentList(), val2->GetArgumentList());
}
| 3,698 | 1,402 |
#include "manager.hpp"
#include <chrono>
#include <iostream>
#include <memory>
#include <opencv2/opencv.hpp>
#include <vector>
int main(int argc, char **argv) {
cv::Mat frame = cv::imread(argv[1]);
manager *tm = new manager();
int image_w = frame.cols;
int image_h = frame.rows;
cv::Mat origin;
frame.copyTo(origin);
origin = frame.clone();
tm->init();
std::vector<FaceDetectInfo> info;
tm->runDetect(origin.data, image_w, image_h, info);
std::vector<FaceLandmarkInfo> landmarkinfo;
tm->runLandmark2d(origin.data, image_w, image_h, info, landmarkinfo);
for (int i = 0; i < info.size(); i++) {
float x1 = info[i].face_box.x1;
float x2 = info[i].face_box.x2;
float y1 = info[i].face_box.y1;
float y2 = info[i].face_box.y2;
cv::Point pt1(x1 / 160.0f * image_w, y1 / 120.0f * image_h);
cv::Point pt2(x2 / 160.0f * image_w, y2 / 120.0f * image_h);
cv::rectangle(frame, pt1, pt2, cv::Scalar(255, 0, 0), 2);
}
for (int j = 0; j < landmarkinfo.size(); j++) {
float w = info[j].face_box.x2 - info[j].face_box.x1;
float h = info[j].face_box.y2 - info[j].face_box.y1;
for (int i = 0; i < 424; i = i + 2) {
float point_x = (landmarkinfo[j].landmarks[i] * w * 1.4f - w * 0.2f +
info[j].face_box.x1) /
160.0f * image_w;
float point_y = (landmarkinfo[j].landmarks[i + 1] * h * 1.4f - h * 0.2f +
info[j].face_box.y1) /
120.0f * image_h;
cv::Point pt(point_x, point_y);
cv::circle(frame, pt, 1, cv::Scalar(255, 0, 0), 1);
}
}
cv::imwrite("FaceOutput.jpg", frame);
return 0;
} | 1,658 | 726 |
// Copyright 2015-2018 RWTH Aachen University
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "ast.hh"
#include "policy_definition.hh"
#include <algorithm>
#include <boost/lexical_cast.hpp>
//Visitor that preprocesses the AST
class AstPreprocessorVisitor : public AstVisitor {
public:
//the policy definition is used to get the types of IDs, since they are initially unknown after the parsing
AstPreprocessorVisitor(const PolicyDefinition &policyDefinition) : policyDefinition(policyDefinition) {}
void visit(AstOperation &);
void visit(AstConstant &);
void visit(AstId &);
void visit(AstFunction &);
void visit(Ast &);
private:
const PolicyDefinition &policyDefinition;
const static uint64_t maxNumberOfChildren = 2;
//fields used to save results of a visit
AstValueType resultType; //used for type checking, IDs are replaced with their real value
AstOperationType parentType; //used to flip booleans with NOT parent
uint64_t nodeCounter;
bool flipMeaning; //used to eliminate NOTs by moving them into the relations
};
| 1,678 | 463 |
/*
* Copyright (c) 2016 Shanghai Jiao Tong University.
* 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.
*
*/
#pragma once
#include <boost/serialization/string.hpp>
#include <boost/serialization/vector.hpp>
#include <vector>
using namespace std;
using namespace boost::archive;
struct CS_Request {
string type;
bool use_file;
string content;
string cid;
template <typename Archive>
void serialize(Archive &ar, const unsigned int v) {
ar &type;
ar &use_file;
ar &content;
}
};
struct CS_Reply {
string type;
string content;
int column;
vector<int64_t> column_table;
vector<int> result_table;
string cid;
template <typename Archive>
void serialize(Archive &ar, const unsigned int v) {
ar &type;
ar &content;
ar &column;
ar &column_table;
ar &result_table;
}
};
| 1,349 | 454 |
/*
Copyright 2016 Massachusetts Institute of Technology
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 "global.h"
#include "table.h"
#include "catalog.h"
#include "row.h"
#include "txn.h"
#include "row_lock.h"
#include "row_ts.h"
#include "row_mvcc.h"
#include "row_occ.h"
#include "row_maat.h"
#include "mem_alloc.h"
#include "manager.h"
#define SIM_FULL_ROW true
RC
row_t::init(table_t * host_table, uint64_t part_id, uint64_t row_id) {
part_info = true;
_row_id = row_id;
_part_id = part_id;
this->table = host_table;
Catalog * schema = host_table->get_schema();
tuple_size = schema->get_tuple_size();
#if SIM_FULL_ROW
data = (char *) mem_allocator.alloc(sizeof(char) * tuple_size);
#else
data = (char *) mem_allocator.alloc(sizeof(uint64_t) * 1);
#endif
return RCOK;
}
RC
row_t::switch_schema(table_t * host_table) {
this->table = host_table;
return RCOK;
}
void row_t::init_manager(row_t * row) {
#if MODE==NOCC_MODE || MODE==QRY_ONLY_MODE
return;
#endif
DEBUG_M("row_t::init_manager alloc \n");
#if CC_ALG == NO_WAIT || CC_ALG == WAIT_DIE || CC_ALG == CALVIN
manager = (Row_lock *) mem_allocator.align_alloc(sizeof(Row_lock));
#elif CC_ALG == TIMESTAMP
manager = (Row_ts *) mem_allocator.align_alloc(sizeof(Row_ts));
#elif CC_ALG == MVCC
manager = (Row_mvcc *) mem_allocator.align_alloc(sizeof(Row_mvcc));
#elif CC_ALG == OCC
manager = (Row_occ *) mem_allocator.align_alloc(sizeof(Row_occ));
#elif CC_ALG == MAAT
manager = (Row_maat *) mem_allocator.align_alloc(sizeof(Row_maat));
#endif
#if CC_ALG != HSTORE && CC_ALG != HSTORE_SPEC
manager->init(this);
#endif
}
table_t * row_t::get_table() {
return table;
}
Catalog * row_t::get_schema() {
return get_table()->get_schema();
}
const char * row_t::get_table_name() {
return get_table()->get_table_name();
};
uint64_t row_t::get_tuple_size() {
return get_schema()->get_tuple_size();
}
uint64_t row_t::get_field_cnt() {
return get_schema()->field_cnt;
}
void row_t::set_value(int id, void * ptr) {
int datasize = get_schema()->get_field_size(id);
int pos = get_schema()->get_field_index(id);
DEBUG("set_value pos %d datasize %d -- %lx\n",pos,datasize,(uint64_t)this);
#if SIM_FULL_ROW
memcpy( &data[pos], ptr, datasize);
#else
char d[tuple_size];
memcpy( &d[pos], ptr, datasize);
#endif
}
void row_t::set_value(int id, void * ptr, int size) {
int pos = get_schema()->get_field_index(id);
#if SIM_FULL_ROW
memcpy( &data[pos], ptr, size);
#else
char d[tuple_size];
memcpy( &d[pos], ptr, size);
#endif
}
void row_t::set_value(const char * col_name, void * ptr) {
uint64_t id = get_schema()->get_field_id(col_name);
set_value(id, ptr);
}
SET_VALUE(uint64_t);
SET_VALUE(int64_t);
SET_VALUE(double);
SET_VALUE(UInt32);
SET_VALUE(SInt32);
GET_VALUE(uint64_t);
GET_VALUE(int64_t);
GET_VALUE(double);
GET_VALUE(UInt32);
GET_VALUE(SInt32);
char * row_t::get_value(int id) {
int pos __attribute__ ((unused));
pos = get_schema()->get_field_index(id);
DEBUG("get_value pos %d -- %lx\n",pos,(uint64_t)this);
#if SIM_FULL_ROW
return &data[pos];
#else
return data;
#endif
}
char * row_t::get_value(char * col_name) {
uint64_t pos __attribute__ ((unused));
pos = get_schema()->get_field_index(col_name);
#if SIM_FULL_ROW
return &data[pos];
#else
return data;
#endif
}
char * row_t::get_data() {
return data;
}
void row_t::set_data(char * data) {
int tuple_size = get_schema()->get_tuple_size();
#if SIM_FULL_ROW
memcpy(this->data, data, tuple_size);
#else
char d[tuple_size];
memcpy(d, data, tuple_size);
#endif
}
// copy from the src to this
void row_t::copy(row_t * src) {
assert(src->get_schema() == this->get_schema());
#if SIM_FULL_ROW
set_data(src->get_data());
#else
char d[tuple_size];
set_data(d);
#endif
}
void row_t::free_row() {
DEBUG_M("row_t::free_row free\n");
#if SIM_FULL
mem_allocator.free(data, sizeof(char) * get_tuple_size());
#else
mem_allocator.free(data, sizeof(uint64_t) * 1);
#endif
}
RC row_t::get_lock(access_t type, TxnManager * txn) {
RC rc = RCOK;
#if CC_ALG == CALVIN
lock_t lt = (type == RD || type == SCAN)? LOCK_SH : LOCK_EX;
rc = this->manager->lock_get(lt, txn);
#endif
return rc;
}
RC row_t::get_row(access_t type, TxnManager * txn, row_t *& row) {
RC rc = RCOK;
#if MODE==NOCC_MODE || MODE==QRY_ONLY_MODE
row = this;
return rc;
#endif
#if ISOLATION_LEVEL == NOLOCK
row = this;
return rc;
#endif
/*
#if ISOLATION_LEVEL == READ_UNCOMMITTED
if(type == RD) {
row = this;
return rc;
}
#endif
*/
#if CC_ALG == MAAT
DEBUG_M("row_t::get_row MAAT alloc \n");
txn->cur_row = (row_t *) mem_allocator.alloc(sizeof(row_t));
txn->cur_row->init(get_table(), get_part_id());
rc = this->manager->access(type,txn);
txn->cur_row->copy(this);
row = txn->cur_row;
assert(rc == RCOK);
goto end;
#endif
#if CC_ALG == WAIT_DIE || CC_ALG == NO_WAIT
//uint64_t thd_id = txn->get_thd_id();
lock_t lt = (type == RD || type == SCAN)? LOCK_SH : LOCK_EX;
rc = this->manager->lock_get(lt, txn);
if (rc == RCOK) {
row = this;
} else if (rc == Abort) {}
else if (rc == WAIT) {
ASSERT(CC_ALG == WAIT_DIE);
}
goto end;
#elif CC_ALG == TIMESTAMP || CC_ALG == MVCC
//uint64_t thd_id = txn->get_thd_id();
// For TIMESTAMP RD, a new copy of the row will be returned.
// for MVCC RD, the version will be returned instead of a copy
// So for MVCC RD-WR, the version should be explicitly copied.
// row_t * newr = NULL;
#if CC_ALG == TIMESTAMP
// TIMESTAMP makes a whole copy of the row before reading
DEBUG_M("row_t::get_row TIMESTAMP alloc \n");
txn->cur_row = (row_t *) mem_allocator.alloc(sizeof(row_t));
txn->cur_row->init(get_table(), this->get_part_id());
#endif
if (type == WR) {
rc = this->manager->access(txn, P_REQ, NULL);
if (rc != RCOK)
goto end;
}
if ((type == WR && rc == RCOK) || type == RD || type == SCAN) {
rc = this->manager->access(txn, R_REQ, NULL);
if (rc == RCOK ) {
row = txn->cur_row;
} else if (rc == WAIT) {
rc = WAIT;
goto end;
} else if (rc == Abort) {
}
if (rc != Abort) {
assert(row->get_data() != NULL);
assert(row->get_table() != NULL);
assert(row->get_schema() == this->get_schema());
assert(row->get_table_name() != NULL);
}
}
if (rc != Abort && CC_ALG == MVCC && type == WR) {
DEBUG_M("row_t::get_row MVCC alloc \n");
row_t * newr = (row_t *) mem_allocator.alloc(sizeof(row_t));
newr->init(this->get_table(), get_part_id());
newr->copy(row);
row = newr;
}
goto end;
#elif CC_ALG == OCC
// OCC always make a local copy regardless of read or write
DEBUG_M("row_t::get_row OCC alloc \n");
txn->cur_row = (row_t *) mem_allocator.alloc(sizeof(row_t));
txn->cur_row->init(get_table(), get_part_id());
rc = this->manager->access(txn, R_REQ);
row = txn->cur_row;
goto end;
#elif CC_ALG == HSTORE || CC_ALG == HSTORE_SPEC || CC_ALG == CALVIN
#if CC_ALG == HSTORE_SPEC
if(txn_table.spec_mode) {
DEBUG_M("row_t::get_row HSTORE_SPEC alloc \n");
txn->cur_row = (row_t *) mem_allocator.alloc(sizeof(row_t));
txn->cur_row->init(get_table(), get_part_id());
rc = this->manager->access(txn, R_REQ);
row = txn->cur_row;
goto end;
}
#endif
row = this;
goto end;
#else
assert(false);
#endif
end:
return rc;
}
// Return call for get_row if waiting
RC row_t::get_row_post_wait(access_t type, TxnManager * txn, row_t *& row) {
RC rc = RCOK;
assert(CC_ALG == WAIT_DIE || CC_ALG == MVCC || CC_ALG == TIMESTAMP);
#if CC_ALG == WAIT_DIE
assert(txn->lock_ready);
rc = RCOK;
//ts_t endtime = get_sys_clock();
row = this;
#elif CC_ALG == MVCC || CC_ALG == TIMESTAMP
assert(txn->ts_ready);
//INC_STATS(thd_id, time_wait, t2 - t1);
row = txn->cur_row;
assert(row->get_data() != NULL);
assert(row->get_table() != NULL);
assert(row->get_schema() == this->get_schema());
assert(row->get_table_name() != NULL);
if (CC_ALG == MVCC && type == WR) {
DEBUG_M("row_t::get_row_post_wait MVCC alloc \n");
row_t * newr = (row_t *) mem_allocator.alloc(sizeof(row_t));
newr->init(this->get_table(), get_part_id());
newr->copy(row);
row = newr;
}
#endif
return rc;
}
// the "row" is the row read out in get_row(). For locking based CC_ALG,
// the "row" is the same as "this". For timestamp based CC_ALG, the
// "row" != "this", and the "row" must be freed.
// For MVCC, the row will simply serve as a version. The version will be
// delete during history cleanup.
// For TIMESTAMP, the row will be explicity deleted at the end of access().
// (c.f. row_ts.cpp)
void row_t::return_row(RC rc, access_t type, TxnManager * txn, row_t * row) {
#if MODE==NOCC_MODE || MODE==QRY_ONLY_MODE
return;
#endif
#if ISOLATION_LEVEL == NOLOCK
return;
#endif
/*
#if ISOLATION_LEVEL == READ_UNCOMMITTED
if(type == RD) {
return;
}
#endif
*/
#if CC_ALG == WAIT_DIE || CC_ALG == NO_WAIT || CC_ALG == CALVIN
assert (row == NULL || row == this || type == XP);
if (CC_ALG != CALVIN && ROLL_BACK && type == XP) {// recover from previous writes. should not happen w/ Calvin
this->copy(row);
}
this->manager->lock_release(txn);
#elif CC_ALG == TIMESTAMP || CC_ALG == MVCC
// for RD or SCAN or XP, the row should be deleted.
// because all WR should be companied by a RD
// for MVCC RD, the row is not copied, so no need to free.
if (CC_ALG == TIMESTAMP && (type == RD || type == SCAN)) {
row->free_row();
DEBUG_M("row_t::return_row TIMESTAMP free \n");
mem_allocator.free(row, sizeof(row_t));
}
if (type == XP) {
row->free_row();
DEBUG_M("row_t::return_row XP free \n");
mem_allocator.free(row, sizeof(row_t));
this->manager->access(txn, XP_REQ, NULL);
} else if (type == WR) {
assert (type == WR && row != NULL);
assert (row->get_schema() == this->get_schema());
RC rc = this->manager->access(txn, W_REQ, row);
assert(rc == RCOK);
}
#elif CC_ALG == OCC
assert (row != NULL);
if (type == WR)
manager->write( row, txn->get_end_timestamp() );
row->free_row();
DEBUG_M("row_t::return_row OCC free \n");
mem_allocator.free(row, sizeof(row_t));
manager->release();
return;
#elif CC_ALG == MAAT
assert (row != NULL);
if (rc == Abort) {
manager->abort(type,txn);
} else {
manager->commit(type,txn,row);
}
row->free_row();
DEBUG_M("row_t::return_row Maat free \n");
mem_allocator.free(row, sizeof(row_t));
#elif CC_ALG == HSTORE || CC_ALG == HSTORE_SPEC
assert (row != NULL);
if (ROLL_BACK && type == XP) {// recover from previous writes.
this->copy(row);
}
return;
#else
assert(false);
#endif
}
| 11,131 | 4,737 |
#pragma once
#include "../Utils/event.hpp"
#include "MpPacketSerializer.hpp"
namespace MultiplayerCore::Networking {
struct MpNetworkingEvents {
static event<Networking::MpPacketSerializer*> RegisterPackets;
};
} | 233 | 74 |
// Copyright 2022 PingCAP, Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <Common/isLocalAddress.h>
#include <Core/Types.h>
#include <Poco/Net/NetworkInterface.h>
#include <Poco/Net/SocketAddress.h>
#include <Poco/Util/Application.h>
#include <cstring>
namespace DB
{
bool isLocalAddress(const Poco::Net::SocketAddress & address)
{
static auto interfaces = Poco::Net::NetworkInterface::list();
return interfaces.end() != std::find_if(interfaces.begin(), interfaces.end(), [&](const Poco::Net::NetworkInterface & interface) {
/** Compare the addresses without taking into account `scope`.
* Theoretically, this may not be correct - depends on `route` setting
* - through which interface we will actually access the specified address.
*/
return interface.address().length() == address.host().length()
&& 0 == memcmp(interface.address().addr(), address.host().addr(), address.host().length());
});
}
bool isLocalAddress(const Poco::Net::SocketAddress & address, UInt16 clickhouse_port)
{
return clickhouse_port == address.port() && isLocalAddress(address);
}
size_t getHostNameDifference(const std::string & local_hostname, const std::string & host)
{
size_t hostname_difference = 0;
for (size_t i = 0; i < std::min(local_hostname.length(), host.length()); ++i)
if (local_hostname[i] != host[i])
++hostname_difference;
return hostname_difference;
}
} // namespace DB
| 2,069 | 594 |
#define CATCH_CONFIG_MAIN
#include "catch2/catch.hpp"
#include "libtorus.hpp"
Torus<int> IntTorus(unsigned int x, unsigned int y) {
return Torus<int>(x, y);
}
TEST_CASE( "Torus need make sense", "[torus]") {
REQUIRE( IntTorus(1,1).get_x() == 0);
}
| 259 | 110 |
#include "core/queues.hpp"
#include <chrono>
#include <thread>
#include <iostream>
void client(abstract_queue<int>* queue, long& counter, bool is_provider, int sleep_milliseconds=100);
void test_queue(abstract_queue<int>*q, const int num_providers, const size_t num_consumers);
int main(int /*argc*/, char** /*argv*/) {
std::cout << "Running Infinite Queue" << std::endl;
infinite_queue<int> iq(1);
test_queue(&iq, 10, 20);
std::cout << "Running Thread Safe Queue" << std::endl;
thread_safe_queue<int> tsq;
test_queue(&tsq, 10, 20);
return 0;
}
void client(abstract_queue<int>* queue, long& counter, bool is_provider, int sleep_milliseconds) {
try {
while (true) {
if (is_provider) { queue->push(1); }
else { queue->pop(); }
counter ++;
std::this_thread::sleep_for(std::chrono::milliseconds(sleep_milliseconds));
}
} catch(queue_closed const&) {
}
}
void test_queue(abstract_queue<int>*q, const int num_providers, const size_t num_consumers) {
std::vector<std::thread*> providers(num_providers, nullptr),
consumers(num_consumers, nullptr);
std::vector<long> provider_data(num_providers, 0),
consumer_data(num_consumers, 0);
for (size_t i=0; i<num_consumers; ++i)
consumers[i] = new std::thread(client, std::ref(q), std::ref(consumer_data[i]), false, 100);
for (int i=0; i<num_providers; ++i)
providers[i] = new std::thread(client, std::ref(q), std::ref(provider_data[i]), true, 120);
std::this_thread::sleep_for(std::chrono::milliseconds(3000));
q->close();
for (size_t i=0; i<num_consumers; ++i) {
consumers[i] ->join();
delete consumers[i];
std::cout << "Consumer " << i << " updated its counter " << consumer_data[i] << " times." << std::endl;
}
for (int i=0; i<num_providers; ++i) {
providers[i] ->join();
delete providers[i];
std::cout << "Provider " << i << " updated its counter " << provider_data[i] << " times." << std::endl;
}
}
| 2,115 | 748 |
#include<bits/stdc++.h>
using namespace std;
#include <iostream> // for std::cout
#include <utility> // for std::pair
#include <algorithm> // for std::for_each
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/adjacency_matrix.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
using namespace boost;
#include "boost/graph/CND/cnd_function.hpp"
template<typename Graph>
void treesize_vertices(int cur,Graph &graph,bool visited[],int subtree_size[])
{
visited[cur] = true;
subtree_size[cur] = 1;
typedef typename graph_traits<Graph>::adjacency_iterator adj_itr;
adj_itr ai,ai_end;
for (boost::tie(ai, ai_end) = adjacent_vertices(cur,graph);ai != ai_end; ++ai)
{
if (!visited[*ai])
{
treesize_vertices(*ai,graph,visited,subtree_size);
subtree_size[cur]+=subtree_size[*ai];
}
}
}
template<typename Graph>
void check_centroid(int cur,Graph &graph,bool visited[],int subtree_size[],int *check)
{
visited[cur] = true;
typedef typename graph_traits<Graph>::adjacency_iterator adj_itr;
adj_itr ai,ai_end;
for (boost::tie(ai, ai_end) = adjacent_vertices(cur,graph);ai != ai_end; ++ai)
{
if (!visited[*ai])
{
if(subtree_size[*ai]>(subtree_size[cur]/2))
{
*check=0;
}
check_centroid(*ai,graph,visited,subtree_size,check);
}
}
}
int main()
{
int i,n,a,b;
scanf("%d",&n);
typedef adjacency_list<vecS, vecS, undirectedS> Graph_list;
Graph_list graph_list(n);
for(i=1;i<n;i++)
{
scanf("%d %d",&a,&b);
add_edge(a,b,graph_list);
}
pair<Graph_list,int> copy_graph;
copy_graph=CND(graph_list,0,n);
int root=copy_graph.second;
bool visited[1030];
int subtree_size[1030];
for(i=0;i<n;i++)
{
visited[i]=false;
subtree_size[i]=0;
}
treesize_vertices<Graph_list>(root,copy_graph.first,visited,subtree_size);
int check=1;
for(i=0;i<n;i++)
visited[i]=false;
check_centroid<Graph_list>(root,copy_graph.first,visited,subtree_size,&check);
if(check)
{
printf("Success\n");
}
return 0;
}
| 2,309 | 863 |
/*
CH08-320142
Problem 1.2.cpp
Digdarshan Kunwar
d.kunwar@jacobs-university.de
*/
#include <iostream>
#include <string>
using namespace std;
int main (int argc, char** argv){
int nr;
float val;
string s;
cin >> nr;
cin >> val;
cin.get();
getline(cin,s);
for (int i=0;i<nr;i++){
cout<< val <<" "<< s<<endl;
}
return 0;
}
| 381 | 164 |
////////////////////////////////////////////////////////////
// Nero Game Engine
// Copyright (c) 2016-2020 Sanou A. K. Landry
////////////////////////////////////////////////////////////
///////////////////////////HEADERS//////////////////////////
//NERO
#include <Nero/core/cpp/scene/SceneUtility.h>
////////////////////////////////////////////////////////////
namespace nero
{
////////////////////////////////////////////////////////////
//QueryCallback
QueryCallback::QueryCallback(const b2Vec2& point)
{
m_Point = point;
m_Fixture = nullptr;
}
bool QueryCallback::ReportFixture(b2Fixture* fixture)
{
b2Body* body = fixture->GetBody();
if (body->GetType() == b2_dynamicBody)
{
bool inside = fixture->TestPoint(m_Point);
if (inside)
{
m_Fixture = fixture;
//Clean pointer
body = nullptr;
//We are done, terminate the query.
return false;
}
}
//Clean pointer
body = nullptr;
//Continue the query.
return true;
}
QueryCallback::~QueryCallback()
{
m_Fixture = nullptr;
}
////////////////////////////////////////////////////////////
//SceneSetting
SceneSetting::SceneSetting()
{
hz = 40.0f;
viewCenter.Set(0.0f, 0.0f);
gravity.Set(0.f, 10.f);
velocityIterations = 8;
positionIterations = 3;
drawAxis = true;
drawGrid = true;
drawShapes = true;
drawJoints = true;
drawAABBs = false;
drawContactPoints = false;
drawContactNormals = false;
drawContactImpulse = false;
drawFrictionImpulse = false;
drawCOMs = false;
drawStats = false;
drawProfile = false;
enableWarmStarting = true;
enableContinuous = true;
enableSubStepping = false;
enableSleep = true;
pause = false;
singleStep = false;
}
nlohmann::json SceneSetting::toJson()
{
nlohmann::json scene_setting;
scene_setting["frequency"] = hz;
scene_setting["view_center"] = graphics::vectorToJson<b2Vec2>(viewCenter);
scene_setting["gravity"] = graphics::vectorToJson<b2Vec2>(gravity);
scene_setting["velocity_iterations"] = velocityIterations;
scene_setting["position_iterations"] = positionIterations;
scene_setting["enable_warm_starting"] = enableWarmStarting;
scene_setting["enable_continuous"] = enableContinuous;
scene_setting["enable_sub_stepping"] = enableSubStepping;
scene_setting["enable_sleep"] = enableSleep;
scene_setting["draw_axis"] = drawAxis;
scene_setting["draw_grid"] = drawGrid;
scene_setting["draw_shapes"] = drawShapes;
scene_setting["draw_joints"] = drawJoints;
scene_setting["draw_aabbs"] = drawAABBs;
scene_setting["draw_contact_points"] = drawContactPoints;
scene_setting["draw_contact_normals"] = drawContactNormals;
scene_setting["draw_contact_impulse"] = drawContactImpulse;
scene_setting["draw_coms"] = drawCOMs;
scene_setting["draw_stats"] = drawStats;
scene_setting["draw_profile"] = drawProfile;
return scene_setting;
}
SceneSetting SceneSetting::fromJson(nlohmann::json setting)
{
SceneSetting scene_setting;
scene_setting.hz = setting["frequency"];
scene_setting.gravity = graphics::vectorFromJson<b2Vec2>(setting["gravity"]);
scene_setting.viewCenter = graphics::vectorFromJson<b2Vec2>(setting["view_center"]);
scene_setting.velocityIterations = setting["velocity_iterations"];
scene_setting.positionIterations = setting["position_iterations"];
scene_setting.enableWarmStarting = setting["enable_warm_starting"];
scene_setting.enableContinuous = setting["enable_continuous"];
scene_setting.enableSubStepping = setting["enable_sub_stepping"];
scene_setting.enableSleep = setting["enable_sleep"];
scene_setting.drawAxis = setting["draw_axis"];
scene_setting.drawGrid = setting["draw_grid"];
scene_setting.drawShapes = setting["draw_shapes"];
scene_setting.drawJoints = setting["draw_joints"];
scene_setting.drawAABBs = setting["draw_aabbs"];
scene_setting.drawContactPoints = setting["draw_contact_points"];
scene_setting.drawContactNormals = setting["draw_contact_normals"];
scene_setting.drawContactImpulse = setting["draw_contact_impulse"];
scene_setting.drawCOMs = setting["draw_coms"];
scene_setting.drawStats = setting["draw_stats"];
scene_setting.drawProfile = setting["draw_profile"];
return scene_setting;
}
////////////////////////////////////////////////////////////
//CameraSetting
CameraSetting::CameraSetting()
{
defaultPosition.x = 0.f;
defaultPosition.y = 0.f;
defaultRotation = 0.f;
defaultZoom = 0.f;
position.x = 0.f;
position.y = 0.f;
rotation = 0.f;
zoom = 0.f;
};
nlohmann::json CameraSetting::toJson()
{
nlohmann::json camera_setting;
camera_setting["default_position"] = {{"x", defaultPosition.x}, {"y", defaultPosition.y}};
camera_setting["default_rotation"] = defaultRotation;
camera_setting["default_zoom"] = defaultZoom;
camera_setting["position"] = {{"x", position.x}, {"y", position.y}};
camera_setting["rotation"] = rotation;
camera_setting["zoom"] = zoom;
return camera_setting;
}
CameraSetting CameraSetting::fromJson(nlohmann::json setting)
{
CameraSetting camera_setting;
camera_setting.defaultPosition.x = setting["default_position"]["x"];
camera_setting.defaultPosition.y = setting["default_position"]["y"];
camera_setting.defaultRotation = setting["default_rotation"];
camera_setting.defaultZoom = setting["default_zoom"];
camera_setting.position.x = setting["position"]["x"];
camera_setting.position.y = setting["position"]["y"];
camera_setting.rotation = setting["rotation"];
camera_setting.zoom = setting["zoom"];
return camera_setting;
}
////////////////////////////////////////////////////////////
//Target
CameraTarget::CameraTarget()
{
target = nullptr;
offsetLeft = 150.f;
offsetRight = 0.f;
offsetUp = 250.f;
offsetDown = 0.f;
followTarget = false;
}
}
| 7,232 | 1,999 |
/* Sirikata Input Plugin -- plugins/input
* SDLInputDevice.cpp
*
* Copyright (c) 2009, Patrick Reiter Horn
* 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 Sirikata 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 <sirikata/core/util/Standard.hh>
#include <sirikata/ogre/input/SDLInputManager.hpp>
#include <sirikata/ogre/input/SDLInputDevice.hpp>
#include <sirikata/ogre/input/InputEvents.hpp>
#include <SDL.h>
#include <SDL_video.h>
#include <SDL_syswm.h>
#include <SDL_events.h>
#include <SDL_mouse.h>
#include <boost/lexical_cast.hpp>
#include <SDL_keysym.h>
namespace Sirikata {
namespace Input {
// HACK: Constant to convert uncalibrated axes to floating point.
// We need a way to set calibration values for each axis.
SDLMouse::SDLMouse(SDLInputManager *manager, unsigned int which) : mWhich(which) {
unsigned int wid,hei;
manager->getWindowSize(wid,hei);
float maxsize = sqrt((float)(wid*wid+hei*hei));
float drag_deadband (manager->dragDeadBand());
setDragDeadband(2*drag_deadband/maxsize);
setName(SDL_GetMouseName(which));
// SDL has no API to query the number of buttons. The exact value doesn't matter.
mNumButtons = 5; // left, middle, right, Back, Forward
}
SDLMouse::~SDLMouse() {
}
SDLInputManager* SDLMouse::inputManager() {
return static_cast<SDLInputManager*>(mManager);
}
int SDLMouse::getNumButtons() const {
return mNumButtons;
}
std::string SDLMouse::getButtonName(unsigned int button) const {
switch (button) {
case SDL_BUTTON_LEFT:
return "Left Button";
case SDL_BUTTON_MIDDLE:
return "Middle Button";
case SDL_BUTTON_RIGHT:
return "Right Button";
}
{
std::ostringstream os;
os << "Button " << button;
return os.str();
}
}
void SDLMouse::setRelativeMode(bool enabled) {
int oldmouse = SDL_SelectMouse(mWhich);
SDL_ShowCursor(enabled? 1 : 0);
SDL_SetRelativeMouseMode(mWhich, enabled ? SDL_TRUE : SDL_FALSE);
/*#if SIRIKATA_PLATFORM == SIRIKATA_PLATFORM_MAC
CGAssociateMouseAndMouseCursorPosition(!enabled);
#endif*/
SDL_SelectMouse(oldmouse);
}
void SDLMouse::fireMotion(const SDLMousePtr &thisptr,
const struct SDL_MouseMotionEvent &event) {
unsigned int screenwid, screenhei;
inputManager()->getWindowSize(screenwid, screenhei);
AxisValue xPctFromCenter = AxisValue::from01(event.x / float(screenwid));
AxisValue yPctFromCenter = AxisValue::from01(1-(event.y / float(screenhei)));
bool changedx = (getAxis(AXIS_CURSORX) != xPctFromCenter);
bool changedy = (getAxis(AXIS_CURSORY) != yPctFromCenter);
if (mRelativeMode) {
// negate y axis since coordinates start at bottom-left.
float to_axis(inputManager()->relativeMouseToAxis());
fireAxis(thisptr, AXIS_RELX, AxisValue::fromCentered(to_axis*event.xrel));
fireAxis(thisptr, AXIS_RELY, AxisValue::fromCentered(-to_axis*event.yrel));
// drag events still get fired...
firePointerMotion(thisptr, event.xrel/float(screenwid),
-event.yrel/float(screenhei), event.cursor,
event.pressure, event.pressure_min, event.pressure_max);
} else {
fireAxis(thisptr, AXIS_CURSORX, xPctFromCenter);
fireAxis(thisptr, AXIS_CURSORY, yPctFromCenter);
if (changedx || changedy) {
firePointerMotion(thisptr, xPctFromCenter.getCentered(),
yPctFromCenter.getCentered(), event.cursor,
event.pressure, event.pressure_min, event.pressure_max);
}
}
if (event.pressure_max) {
fireAxis(thisptr, PRESSURE, AxisValue::fromCentered((float)event.pressure / (float)event.pressure_max));
}
// "For future use"
//fireAxis(CURSORZ, event.z);
//fireAxis(TILT, event.pressure);
//fireAxis(ROTATION, event.pressure);
}
void SDLMouse::fireWheel(const SDLMousePtr &thisptr,
int xrel, int yrel) {
float to_axis (inputManager()->wheelToAxis());
SILOG(input,detailed,"WHEEL: " << xrel << "; " << yrel);
fireAxis(thisptr, WHEELX, AxisValue::fromCentered(to_axis*xrel));
fireAxis(thisptr, WHEELY, AxisValue::fromCentered(to_axis*yrel));
}
SDLJoystick::SDLJoystick(unsigned int whichDevice)
: mWhich(whichDevice) {
this->mJoy = SDL_JoystickOpen(whichDevice);
if (mJoy == NULL) {
// analog joystick?
mNumBalls = 0;
mNumButtons = 4;
mNumHats = 0;
mNumGeneralAxes = 4;
SILOG(input,error,"Unable to open joystick " << whichDevice << "!");
} else {
mNumGeneralAxes = SDL_JoystickNumAxes(mJoy);
mNumBalls = SDL_JoystickNumBalls(mJoy);
mNumButtons = SDL_JoystickNumButtons(mJoy);
mNumHats = SDL_JoystickNumHats(mJoy);
mButtonNames.resize(mNumButtons);
}
}
SDLJoystick::~SDLJoystick() {
if (mJoy) {
SDL_JoystickClose(mJoy);
}
}
SDLInputManager* SDLJoystick::inputManager() {
return static_cast<SDLInputManager*>(mManager);
}
int SDLJoystick::getNumButtons() const {
return mNumButtons + HAT_MAX*mNumHats;
}
unsigned int SDLJoystick::getNumAxes() const {
return mNumGeneralAxes + 2*mNumBalls;
}
std::string SDLJoystick::getAxisName(unsigned int axis) const {
if (axis == 0) {
return "X";
} else if (axis == 1) {
return "Y";
} else if (axis > mNumGeneralAxes) {
unsigned int ballaxis = axis - mNumGeneralAxes;
unsigned int ballnum = ballaxis/2;
const char *axisname = ((ballnum%2) == 0) ? " X" : " Y";
std::ostringstream os;
os << "Trackball " << ballnum << axisname;
return os.str();
} else {
std::ostringstream os;
os << "Axis " << axis;
return os.str();
}
}
void SDLJoystick::fireHat(const SDLJoystickPtr &thisptr,
unsigned int num, int val) {
this->fireButton(thisptr, mNumButtons + HAT_MAX*num + HAT_UP, !!(val & SDL_HAT_UP));
this->fireButton(thisptr, mNumButtons + HAT_MAX*num + HAT_RIGHT, !!(val & SDL_HAT_RIGHT));
this->fireButton(thisptr, mNumButtons + HAT_MAX*num + HAT_DOWN, !!(val & SDL_HAT_DOWN));
this->fireButton(thisptr, mNumButtons + HAT_MAX*num + HAT_LEFT, !!(val & SDL_HAT_LEFT));
}
void SDLJoystick::fireBall(const SDLJoystickPtr &thisptr,
unsigned int ballNumber, int xrel, int yrel) {
float to_axis (inputManager()->joyBallToAxis());
fireAxis(thisptr, mNumGeneralAxes + 2*ballNumber, AxisValue::fromCentered(to_axis*xrel));
fireAxis(thisptr, mNumGeneralAxes + 2*ballNumber + 1, AxisValue::fromCentered(to_axis*yrel));
}
std::string SDLJoystick::getButtonName(unsigned int button) const {
if (button < mButtonNames.size()) {
if (!mButtonNames[button].empty()) {
return mButtonNames[button];
}
}
std::ostringstream os;
if (button >= mNumButtons) {
int hatbutton = button - mNumButtons;
os << "Digital Hat " << (hatbutton/HAT_MAX) << " ";
int direction = hatbutton%HAT_MAX;
switch (hatbutton) {
case HAT_UP:
os << "Up";
break;
case HAT_DOWN:
os << "Up";
break;
case HAT_LEFT:
os << "Left";
break;
case HAT_RIGHT:
os << "Right";
break;
}
return os.str();
} else {
os << "Button " << button;
return os.str();
}
}
void SDLJoystick::setButtonName(unsigned int button, std::string name) {
if (button < mButtonNames.size()) {
mButtonNames[button] = name;
}
}
SDLKeyboard::SDLKeyboard(unsigned int which) : mWhich(which) {
if (which == 0) {
setName("Primary Keyboard");
} else {
std::ostringstream os;
os << "Keyboard " << which;
setName(os.str());
}
}
SDLKeyboard::~SDLKeyboard() {
}
SDLInputManager* SDLKeyboard::inputManager() {
return static_cast<SDLInputManager*>(mManager);
}
std::string SDLKeyboard::getButtonName(unsigned int button) const {
const char *keyname = SDL_GetScancodeName((SDL_scancode)button);
if (keyname) {
return keyname;
} else {
std::ostringstream ostr;
ostr << '#' << button;
return ostr.str();
}
}
static std::map<Input::KeyButton, String> ScancodesToStrings;
static std::map<String, Input::KeyButton> StringsToScancodes;
static void init_button_conversion_maps();
void ensure_initialized() {
static bool initialized = false;
if (!initialized) {
initialized = true;
init_button_conversion_maps();
}
}
#define INIT_SCANCODE_STRING_MAP(X, STR) \
ScancodesToStrings[SDL_SCANCODE_##X] = #STR; \
StringsToScancodes[#STR] = SDL_SCANCODE_##X
static void init_button_conversion_maps() {
INIT_SCANCODE_STRING_MAP(A, a); INIT_SCANCODE_STRING_MAP(B, b); INIT_SCANCODE_STRING_MAP(C, c);
INIT_SCANCODE_STRING_MAP(D, d); INIT_SCANCODE_STRING_MAP(E, e); INIT_SCANCODE_STRING_MAP(F, f);
INIT_SCANCODE_STRING_MAP(G, g); INIT_SCANCODE_STRING_MAP(H, h); INIT_SCANCODE_STRING_MAP(I, i);
INIT_SCANCODE_STRING_MAP(J, j); INIT_SCANCODE_STRING_MAP(K, k); INIT_SCANCODE_STRING_MAP(L, l);
INIT_SCANCODE_STRING_MAP(M, m); INIT_SCANCODE_STRING_MAP(N, n); INIT_SCANCODE_STRING_MAP(O, o);
INIT_SCANCODE_STRING_MAP(P, p); INIT_SCANCODE_STRING_MAP(Q, q); INIT_SCANCODE_STRING_MAP(R, r);
INIT_SCANCODE_STRING_MAP(S, s); INIT_SCANCODE_STRING_MAP(T, t); INIT_SCANCODE_STRING_MAP(U, u);
INIT_SCANCODE_STRING_MAP(V, v); INIT_SCANCODE_STRING_MAP(W, w); INIT_SCANCODE_STRING_MAP(X, X);
INIT_SCANCODE_STRING_MAP(Y, y); INIT_SCANCODE_STRING_MAP(Z, z); INIT_SCANCODE_STRING_MAP(0, 0);
INIT_SCANCODE_STRING_MAP(1, 1); INIT_SCANCODE_STRING_MAP(2, 2); INIT_SCANCODE_STRING_MAP(3, 3);
INIT_SCANCODE_STRING_MAP(4, 4); INIT_SCANCODE_STRING_MAP(5, 5); INIT_SCANCODE_STRING_MAP(6, 6);
INIT_SCANCODE_STRING_MAP(7, 7); INIT_SCANCODE_STRING_MAP(8, 8); INIT_SCANCODE_STRING_MAP(9, 9);
INIT_SCANCODE_STRING_MAP(LSHIFT, lshift);
INIT_SCANCODE_STRING_MAP(RSHIFT, rshift);
INIT_SCANCODE_STRING_MAP(LCTRL, lctrl);
INIT_SCANCODE_STRING_MAP(RCTRL, rctrl);
INIT_SCANCODE_STRING_MAP(LALT, lalt);
INIT_SCANCODE_STRING_MAP(RALT, ralt);
INIT_SCANCODE_STRING_MAP(LGUI, lsuper);
INIT_SCANCODE_STRING_MAP(RGUI, rsuper);
INIT_SCANCODE_STRING_MAP(RETURN, return);
INIT_SCANCODE_STRING_MAP(ESCAPE, escape);
INIT_SCANCODE_STRING_MAP(BACKSPACE, back);
INIT_SCANCODE_STRING_MAP(TAB, tab);
INIT_SCANCODE_STRING_MAP(SPACE, space);
INIT_SCANCODE_STRING_MAP(MINUS, minus);
INIT_SCANCODE_STRING_MAP(EQUALS, equals);
INIT_SCANCODE_STRING_MAP(LEFTBRACKET, [);
INIT_SCANCODE_STRING_MAP(RIGHTBRACKET, ]);
INIT_SCANCODE_STRING_MAP(BACKSLASH, backslash);
INIT_SCANCODE_STRING_MAP(SEMICOLON, semicolon);
INIT_SCANCODE_STRING_MAP(APOSTROPHE, apostrophe);
INIT_SCANCODE_STRING_MAP(GRAVE, OEM_3);
INIT_SCANCODE_STRING_MAP(COMMA, comma);
INIT_SCANCODE_STRING_MAP(PERIOD, period);
INIT_SCANCODE_STRING_MAP(SLASH, OEM_2);
INIT_SCANCODE_STRING_MAP(CAPSLOCK, CAPITAL);
INIT_SCANCODE_STRING_MAP(F1, F1);
INIT_SCANCODE_STRING_MAP(F2, F2);
INIT_SCANCODE_STRING_MAP(F3, F3);
INIT_SCANCODE_STRING_MAP(F4, F4);
INIT_SCANCODE_STRING_MAP(F5, F5);
INIT_SCANCODE_STRING_MAP(F6, F6);
INIT_SCANCODE_STRING_MAP(F7, F7);
INIT_SCANCODE_STRING_MAP(F8, F8);
INIT_SCANCODE_STRING_MAP(F9, F9);
INIT_SCANCODE_STRING_MAP(F10, F10);
INIT_SCANCODE_STRING_MAP(F11, F11);
INIT_SCANCODE_STRING_MAP(F12, F12);
INIT_SCANCODE_STRING_MAP(PRINTSCREEN, print);
INIT_SCANCODE_STRING_MAP(SCROLLLOCK, scroll);
INIT_SCANCODE_STRING_MAP(PAUSE, pause);
INIT_SCANCODE_STRING_MAP(INSERT, insert);
INIT_SCANCODE_STRING_MAP(HOME, home);
INIT_SCANCODE_STRING_MAP(PAGEUP, pageup);
INIT_SCANCODE_STRING_MAP(DELETE, delete);
INIT_SCANCODE_STRING_MAP(END, end);
INIT_SCANCODE_STRING_MAP(PAGEDOWN, pagedown);
INIT_SCANCODE_STRING_MAP(RIGHT, right);
INIT_SCANCODE_STRING_MAP(LEFT, left);
INIT_SCANCODE_STRING_MAP(DOWN, down);
INIT_SCANCODE_STRING_MAP(UP, up);
INIT_SCANCODE_STRING_MAP(KP_0, insert);
INIT_SCANCODE_STRING_MAP(KP_1, end);
INIT_SCANCODE_STRING_MAP(KP_2, down);
INIT_SCANCODE_STRING_MAP(KP_3, next);
INIT_SCANCODE_STRING_MAP(KP_4, left);
INIT_SCANCODE_STRING_MAP(KP_6, right);
INIT_SCANCODE_STRING_MAP(KP_7, home);
INIT_SCANCODE_STRING_MAP(KP_8, up);
INIT_SCANCODE_STRING_MAP(KP_9, prior);
}
bool keyIsModifier(Input::KeyButton b) {
return (b == SDL_SCANCODE_LSHIFT ||
b == SDL_SCANCODE_RSHIFT ||
b == SDL_SCANCODE_LCTRL ||
b == SDL_SCANCODE_RCTRL ||
b == SDL_SCANCODE_LALT ||
b == SDL_SCANCODE_RALT ||
b == SDL_SCANCODE_LGUI ||
b == SDL_SCANCODE_RGUI);
}
String keyButtonString(Input::KeyButton b) {
ensure_initialized();
if (ScancodesToStrings.find(b) != ScancodesToStrings.end())
return ScancodesToStrings[b];
return "";
}
String keyModifiersString(Input::Modifier m) {
if (m == Input::MOD_NONE)
return "";
String result;
if (m & MOD_SHIFT) {
result += "shift";
}
if (m & MOD_CTRL) {
if (!result.empty()) result += "-";
result += "ctrl";
}
if (m & MOD_ALT) {
if (!result.empty()) result += "-";
result += "alt";
}
if (m & MOD_GUI) {
if (!result.empty()) result += "-";
result += "super";
}
return result;
}
String mouseButtonString(Input::MouseButton b) {
return boost::lexical_cast<String>(b);
}
String axisString(Input::AxisIndex i) {
return boost::lexical_cast<String>(i);
}
Input::KeyButton keyButtonFromStrings(std::vector<String>& parts) {
ensure_initialized();
assert(!parts.empty());
const String& part = *parts.begin();
Input::KeyButton result = 0;
if (StringsToScancodes.find(part) != StringsToScancodes.end()) {
result = StringsToScancodes[part];
parts.erase(parts.begin());
}
return result;
}
Input::Modifier keyModifiersFromStrings(std::vector<String>& parts) {
bool more = true;
Input::Modifier result = Input::MOD_NONE;
while(more && !parts.empty()) {
const String& val = *parts.begin();
if (val == "shift")
result |= Input::MOD_SHIFT;
else if (val == "ctrl")
result |= Input::MOD_CTRL;
else if (val == "alt")
result |= Input::MOD_ALT;
else if (val == "super")
result |= Input::MOD_GUI;
else
more = false;
if (more) // We got something, so we need to remove it
parts.erase(parts.begin());
}
return result;
}
Input::MouseButton mouseButtonFromStrings(std::vector<String>& parts) {
assert(!parts.empty());
Input::MouseButton result = boost::lexical_cast<Input::MouseButton>(*parts.begin());
parts.erase( parts.begin() );
return result;
}
Input::AxisIndex axisFromStrings(std::vector<String>& parts) {
assert(!parts.empty());
Input::AxisIndex result = boost::lexical_cast<Input::AxisIndex>(*parts.begin());
parts.erase( parts.begin() );
return result;
}
}
}
| 16,835 | 6,238 |
#include <opencv/highgui.h>
#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>
#include <sstream>
using namespace cv;
using namespace std;
int main()
{
auto cap = VideoCapture( "../Documents/drop.avi" );
auto frame_counter = 0;
// не всегда можно получить
cout << "fps:" << cap.get( CV_CAP_PROP_FPS ) << endl;
while( cap.isOpened( ) ){
Mat frame;
auto success = cap.read( frame );
frame_counter += 1;
// If the last frame is reached, reset the capture and the frame_counter
if( frame_counter == cap.get( CV_CAP_PROP_FRAME_COUNT ) ){
frame_counter = 0; // Or whatever as long as it is the same as next line
cap.set( CV_CAP_PROP_POS_FRAMES, 0 );
}
Mat gray;
cvtColor( frame, gray, COLOR_BGR2GRAY );
// proc
Mat img = gray / 5;
circle( img, {100, 150}, 10, 255 );
auto font = FONT_HERSHEY_SIMPLEX;
stringstream s;
s << frame_counter;
string text = "marker:" + s.str();
putText( img, text, {5,200}, font, 0.4, (225),1 );
// play
imshow( "frame", img );
if( waitKey(1) >= 0 )
break;
}
cap.release();
destroyAllWindows();
return 0;
}
| 1,114 | 486 |
#include <iostream>
#define maxn 101
int main()
{
int n, m;
int a[maxn];
std::cin >> n >> m;
for (int i = 0; i < n; ++i) {
std::cin >> a[i];
}
m = m % n;
if (m == 0) {
std::cout << a[0];
for (int i = 1; i < n; ++i) {
std::cout << " " << a[i];
}
} else {
int start = n - m;
std::cout << a[start];
for (int i = 1; i < n; ++i) {
std::cout << " " << a[(start+i)%n];
}
}
std::cout << std::endl;
return 0;
}
| 538 | 224 |
#include "mainwindow.h"
#include "qfindedit.h"
#include "ui_mainwindow.h"
#include <QHBoxLayout>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QFindEdit* edit = new QFindEdit(this);
QHBoxLayout *pLayout = new QHBoxLayout(this);
pLayout->addWidget(edit);
centralWidget()->setLayout(pLayout);
}
MainWindow::~MainWindow()
{
delete ui;
}
| 432 | 162 |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "napitest.h"
#define Init test_number_init
#include "js-native-api/test_number/test_number.c"
using namespace napitest;
TEST_P(NapiTest, test_number) {
ExecuteNapi([](NapiTestContext *testContext, napi_env env) {
testContext->AddNativeModule(
"./build/x86/test_number",
[](napi_env env, napi_value exports) { return Init(env, exports); });
testContext->RunTestScript("test_number/test.js");
});
}
| 513 | 178 |
#include <iostream>
using namespace std;
void insert_sort(int a[], int n){
int temp, k;
for (int i = 1; i < n; i++){
k = i;
temp = a[k];
for (int j = i - 1; j >= 0; j--){
if (a[j] > temp){
a[k] = a[j];
k--;
}
}
a[k] = temp;
}
for (int i = 0; i < n; i++){
cout << a[i] << " ";
}
}
int main(){
int n;
cin >> n;
int a[n];
for (int i = 0; i < n; i++){
cin >> a[i];
}
insert_sort(a, n);
}
| 540 | 220 |
#include <boost/spirit/home/karma/action/action.hpp>
| 53 | 21 |
#include "Body.h"
#include "WebPage.h"
#include "WebPageManager.h"
Body::Body(WebPageManager *manager, QStringList &arguments, QObject *parent) : SocketCommand(manager, arguments, parent) {
}
void Body::start() {
QString result = page()->currentFrame()->toHtml();
emit finished(new Response(true, result));
}
| 315 | 100 |
// Copyright (c) Facebook, Inc. and its affiliates.
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
#include "AttributesBase.h"
namespace esp {
namespace metadata {
namespace attributes {
const std::map<std::string, ObjectInstanceShaderType> ShaderTypeNamesMap = {
{"material", ObjectInstanceShaderType::Material},
{"flat", ObjectInstanceShaderType::Flat},
{"phong", ObjectInstanceShaderType::Phong},
{"pbr", ObjectInstanceShaderType::PBR},
};
const std::map<std::string, SceneInstanceTranslationOrigin>
InstanceTranslationOriginMap = {
{"asset_local", SceneInstanceTranslationOrigin::AssetLocal},
{"com", SceneInstanceTranslationOrigin::COM},
};
std::string getShaderTypeName(int shaderTypeVal) {
if (shaderTypeVal <= static_cast<int>(ObjectInstanceShaderType::Unknown) ||
shaderTypeVal >=
static_cast<int>(ObjectInstanceShaderType::EndShaderType)) {
return "unspecified";
}
// Must always be valid value
ObjectInstanceShaderType shaderType =
static_cast<ObjectInstanceShaderType>(shaderTypeVal);
for (const auto& it : ShaderTypeNamesMap) {
if (it.second == shaderType) {
return it.first;
}
}
return "unspecified";
}
std::string getTranslationOriginName(int translationOrigin) {
if (translationOrigin <=
static_cast<int>(SceneInstanceTranslationOrigin::Unknown) ||
translationOrigin >=
static_cast<int>(SceneInstanceTranslationOrigin::EndTransOrigin)) {
return "default";
}
// Must always be valid value
SceneInstanceTranslationOrigin transOrigin =
static_cast<SceneInstanceTranslationOrigin>(translationOrigin);
for (const auto& it : InstanceTranslationOriginMap) {
if (it.second == transOrigin) {
return it.first;
}
}
return "default";
}
AbstractAttributes::AbstractAttributes(const std::string& attributesClassKey,
const std::string& handle)
: Configuration() {
// set up an existing subgroup for user_defined attributes
addSubgroup("user_defined");
AbstractAttributes::setClassKey(attributesClassKey);
AbstractAttributes::setHandle(handle);
// set initial vals, will be overwritten when registered
set("ID", 0);
set("fileDirectory", "");
}
} // namespace attributes
} // namespace metadata
} // namespace esp
| 2,413 | 675 |
//------------------------------------------------------------------------------
// \file Token_tests.cpp
//------------------------------------------------------------------------------
#include "DeskCalculator/Token.h"
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(DeskCalculator)
BOOST_AUTO_TEST_SUITE(Token_tests)
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(NumberOfBitsInAByteIs8)
{
BOOST_TEST(true);
}
BOOST_AUTO_TEST_SUITE_END() // Token_tests
BOOST_AUTO_TEST_SUITE_END() // DeskCalculator | 653 | 176 |
// RUN: %clang_cc1 -fno-rtti -emit-llvm-only -triple i686-pc-win32 -fms-extensions -fdump-record-layouts -fsyntax-only %s 2>/dev/null \
// RUN: | FileCheck %s --strict-whitespace
// RUN: %clang_cc1 -fno-rtti -emit-llvm-only -triple x86_64-pc-win32 -fms-extensions -fdump-record-layouts -fsyntax-only %s 2>/dev/null \
// RUN: | FileCheck %s -check-prefix CHECK-X64 --strict-whitespace
extern "C" int printf(const char *fmt, ...);
__declspec(align(4096)) char buffer[4096];
struct AT {};
struct V : AT {
char c;
V() {
printf("V - this: %d\n", (int)((char*)this - buffer));
}
};
struct AT0 {
union { struct { int a; AT t; } y; int b; } x;
char c;
AT0() {
printf("AT0 - this: %d\n", (int)((char*)this - buffer));
}
};
struct AT1 : V {
int a;
AT1() {
printf("AT1 - this: %d\n", (int)((char*)this - buffer));
}
};
struct AT2 {
AT0 t;
char AT2FieldName0;
AT2() {
printf("AT2 - this: %d\n", (int)((char*)this - buffer));
printf("AT2 - Fiel: %d\n", (int)((char*)&AT2FieldName0 - buffer));
}
};
struct AT3 : AT2, AT1 {
AT3() {
printf("AT3 - this: %d\n", (int)((char*)this - buffer));
}
};
// CHECK-LABEL: 0 | struct AT3{{$}}
// CHECK-NEXT: 0 | struct AT2 (base)
// CHECK-NEXT: 0 | struct AT0 t
// CHECK-NEXT: 0 | union AT0::(unnamed at {{.*}} x
// CHECK-NEXT: 0 | struct AT0::(unnamed at {{.*}} y
// CHECK-NEXT: 0 | int a
// CHECK-NEXT: 4 | struct AT t (empty)
// CHECK: 0 | int b
// CHECK: 8 | char c
// CHECK: 12 | char AT2FieldName0
// CHECK-NEXT: 20 | struct AT1 (base)
// CHECK-NEXT: 20 | struct V (base)
// CHECK-NEXT: 20 | struct AT (base) (empty)
// CHECK-NEXT: 20 | char c
// CHECK-NEXT: 24 | int a
// CHECK-NEXT: | [sizeof=28, align=4
// CHECK-NEXT: | nvsize=28, nvalign=4]
// CHECK-X64-LABEL: 0 | struct AT3{{$}}
// CHECK-X64-NEXT: 0 | struct AT2 (base)
// CHECK-X64-NEXT: 0 | struct AT0 t
// CHECK-X64-NEXT: 0 | union AT0::(unnamed at {{.*}} x
// CHECK-X64-NEXT: 0 | struct AT0::(unnamed at {{.*}} y
// CHECK-X64-NEXT: 0 | int a
// CHECK-X64-NEXT: 4 | struct AT t (empty)
// CHECK-X64: 0 | int b
// CHECK-X64: 8 | char c
// CHECK-X64: 12 | char AT2FieldName0
// CHECK-X64-NEXT: 20 | struct AT1 (base)
// CHECK-X64-NEXT: 20 | struct V (base)
// CHECK-X64-NEXT: 20 | struct AT (base) (empty)
// CHECK-X64-NEXT: 20 | char c
// CHECK-X64-NEXT: 24 | int a
// CHECK-X64-NEXT: | [sizeof=28, align=4
// CHECK-X64-NEXT: | nvsize=28, nvalign=4]
struct BT0 {
BT0() {
printf("BT0 - this: %d\n", (int)((char*)this - buffer));
}
};
struct BT2 : BT0 {
char BT2FieldName0;
BT2() {
printf("BT2 - this: %d\n", (int)((char*)this - buffer));
printf("BT2 - Fiel: %d\n", (int)((char*)&BT2FieldName0 - buffer));
}
};
struct BT3 : BT0, BT2 {
BT3() {
printf("BT3 - this: %d\n", (int)((char*)this - buffer));
}
};
// CHECK-LABEL: 0 | struct BT3{{$}}
// CHECK-NEXT: 0 | struct BT0 (base) (empty)
// CHECK-NEXT: 1 | struct BT2 (base)
// CHECK-NEXT: 1 | struct BT0 (base) (empty)
// CHECK-NEXT: 1 | char BT2FieldName0
// CHECK-NEXT: | [sizeof=2, align=1
// CHECK-NEXT: | nvsize=2, nvalign=1]
// CHECK-X64-LABEL: 0 | struct BT3{{$}}
// CHECK-X64-NEXT: 0 | struct BT0 (base) (empty)
// CHECK-X64-NEXT: 1 | struct BT2 (base)
// CHECK-X64-NEXT: 1 | struct BT0 (base) (empty)
// CHECK-X64-NEXT: 1 | char BT2FieldName0
// CHECK-X64-NEXT: | [sizeof=2, align=1
// CHECK-X64-NEXT: | nvsize=2, nvalign=1]
struct T0 : AT {
T0() {
printf("T0 (this) : %d\n", (int)((char*)this - buffer));
}
};
struct T1 : T0 {
char a;
T1() {
printf("T1 (this) : %d\n", (int)((char*)this - buffer));
printf("T1 (fiel) : %d\n", (int)((char*)&a - buffer));
}
};
struct T2 : AT {
char a;
T2() {
printf("T2 (this) : %d\n", (int)((char*)this - buffer));
printf("T2 (fiel) : %d\n", (int)((char*)&a - buffer));
}
};
struct __declspec(align(1)) T3 : virtual T1, virtual T2 {
T3() {
printf("T3 (this) : %d\n", (int)((char*)this - buffer));
}
};
// CHECK-LABEL: 0 | struct T3{{$}}
// CHECK-NEXT: 0 | (T3 vbtable pointer)
// CHECK-NEXT: 4 | struct T1 (virtual base)
// CHECK-NEXT: 4 | struct T0 (base) (empty)
// CHECK-NEXT: 4 | struct AT (base) (empty)
// CHECK-NEXT: 4 | char a
// CHECK-NEXT: 12 | struct T2 (virtual base)
// CHECK-NEXT: 12 | struct AT (base) (empty)
// CHECK-NEXT: 12 | char a
// CHECK-NEXT: | [sizeof=16, align=4
// CHECK-NEXT: | nvsize=4, nvalign=4]
// CHECK-X64-LABEL: 0 | struct T3{{$}}
// CHECK-X64-NEXT: 0 | (T3 vbtable pointer)
// CHECK-X64-NEXT: 8 | struct T1 (virtual base)
// CHECK-X64-NEXT: 8 | struct T0 (base) (empty)
// CHECK-X64-NEXT: 8 | struct AT (base) (empty)
// CHECK-X64-NEXT: 8 | char a
// CHECK-X64-NEXT: 16 | struct T2 (virtual base)
// CHECK-X64-NEXT: 16 | struct AT (base) (empty)
// CHECK-X64-NEXT: 16 | char a
// CHECK-X64-NEXT: | [sizeof=24, align=8
// CHECK-X64-NEXT: | nvsize=8, nvalign=8]
struct B {};
struct C { int a; };
struct D : B, virtual C { B b; };
struct E : D, B {};
// CHECK-LABEL: 0 | struct E{{$}}
// CHECK-NEXT: 0 | struct D (base)
// CHECK-NEXT: 4 | struct B (base) (empty)
// CHECK-NEXT: 0 | (D vbtable pointer)
// CHECK-NEXT: 4 | struct B b (empty)
// CHECK: 8 | struct B (base) (empty)
// CHECK-NEXT: 8 | struct C (virtual base)
// CHECK-NEXT: 8 | int a
// CHECK-NEXT: | [sizeof=12, align=4
// CHECK-NEXT: | nvsize=8, nvalign=4]
// CHECK-X64-LABEL: 0 | struct E{{$}}
// CHECK-X64-NEXT: 0 | struct D (base)
// CHECK-X64-NEXT: 8 | struct B (base) (empty)
// CHECK-X64-NEXT: 0 | (D vbtable pointer)
// CHECK-X64-NEXT: 8 | struct B b (empty)
// CHECK-X64: 16 | struct B (base) (empty)
// CHECK-X64-NEXT: 16 | struct C (virtual base)
// CHECK-X64-NEXT: 16 | int a
// CHECK-X64-NEXT: | [sizeof=24, align=8
// CHECK-X64-NEXT: | nvsize=16, nvalign=8]
struct F : virtual D, virtual B {};
// CHECK-LABEL: 0 | struct F{{$}}
// CHECK-NEXT: 0 | (F vbtable pointer)
// CHECK-NEXT: 4 | struct C (virtual base)
// CHECK-NEXT: 4 | int a
// CHECK-NEXT: 8 | struct D (virtual base)
// CHECK-NEXT: 12 | struct B (base) (empty)
// CHECK-NEXT: 8 | (D vbtable pointer)
// CHECK-NEXT: 12 | struct B b (empty)
// CHECK: 16 | struct B (virtual base) (empty)
// CHECK-NEXT: | [sizeof=16, align=4
// CHECK-NEXT: | nvsize=4, nvalign=4]
// CHECK-X64-LABEL: 0 | struct F{{$}}
// CHECK-X64-NEXT: 0 | (F vbtable pointer)
// CHECK-X64-NEXT: 8 | struct C (virtual base)
// CHECK-X64-NEXT: 8 | int a
// CHECK-X64-NEXT: 16 | struct D (virtual base)
// CHECK-X64-NEXT: 24 | struct B (base) (empty)
// CHECK-X64-NEXT: 16 | (D vbtable pointer)
// CHECK-X64-NEXT: 24 | struct B b (empty)
// CHECK-X64: 32 | struct B (virtual base) (empty)
// CHECK-X64-NEXT: | [sizeof=32, align=8
// CHECK-X64-NEXT: | nvsize=8, nvalign=8]
struct JC0 {
JC0() { printf("JC0 : %d\n", (int)((char*)this - buffer)); }
};
struct JC1 : JC0 {
virtual void f() {}
JC1() { printf("JC1 : %d\n", (int)((char*)this - buffer)); }
};
struct JC2 : JC1 {
JC2() { printf("JC2 : %d\n", (int)((char*)this - buffer)); }
};
struct JC4 : JC1, JC2 {
JC4() { printf("JC4 : %d\n", (int)((char*)this - buffer)); }
};
// CHECK-LABEL: 0 | struct JC4{{$}}
// CHECK-NEXT: 0 | struct JC1 (primary base)
// CHECK-NEXT: 0 | (JC1 vftable pointer)
// CHECK-NEXT: 4 | struct JC0 (base) (empty)
// CHECK-NEXT: 8 | struct JC2 (base)
// CHECK-NEXT: 8 | struct JC1 (primary base)
// CHECK-NEXT: 8 | (JC1 vftable pointer)
// CHECK-NEXT: 12 | struct JC0 (base) (empty)
// CHECK-NEXT: | [sizeof=12, align=4
// CHECK-NEXT: | nvsize=12, nvalign=4]
// CHECK-X64-LABEL: 0 | struct JC4{{$}}
// CHECK-X64-NEXT: 0 | struct JC1 (primary base)
// CHECK-X64-NEXT: 0 | (JC1 vftable pointer)
// CHECK-X64-NEXT: 8 | struct JC0 (base) (empty)
// CHECK-X64-NEXT: 16 | struct JC2 (base)
// CHECK-X64-NEXT: 16 | struct JC1 (primary base)
// CHECK-X64-NEXT: 16 | (JC1 vftable pointer)
// CHECK-X64-NEXT: 24 | struct JC0 (base) (empty)
// CHECK-X64-NEXT: | [sizeof=24, align=8
// CHECK-X64-NEXT: | nvsize=24, nvalign=8]
struct RA {};
struct RB { char c; };
struct RV {};
struct RW { char c; };
struct RY { RY() { printf("%Id\n", (char*)this - buffer); } };
struct RX0 : RB, RA {};
struct RX1 : RA, RB {};
struct RX2 : RA { char a; };
struct RX3 : RA { RB a; };
struct RX4 { RA a; char b; };
struct RX5 { RA a; RB b; };
struct RX6 : virtual RV { RB a; };
struct RX7 : virtual RW { RA a; };
struct RX8 : RA, virtual RW {};
struct RZ0 : RX0, RY {};
// CHECK-LABEL: 0 | struct RZ0{{$}}
// CHECK-NEXT: 0 | struct RX0 (base)
// CHECK-NEXT: 0 | struct RB (base)
// CHECK-NEXT: 0 | char c
// CHECK-NEXT: 1 | struct RA (base) (empty)
// CHECK-NEXT: 2 | struct RY (base) (empty)
// CHECK-NEXT: | [sizeof=2, align=1
// CHECK-NEXT: | nvsize=2, nvalign=1]
// CHECK-X64-LABEL: 0 | struct RZ0{{$}}
// CHECK-X64-NEXT: 0 | struct RX0 (base)
// CHECK-X64-NEXT: 0 | struct RB (base)
// CHECK-X64-NEXT: 0 | char c
// CHECK-X64-NEXT: 1 | struct RA (base) (empty)
// CHECK-X64-NEXT: 2 | struct RY (base) (empty)
// CHECK-X64-NEXT: | [sizeof=2, align=1
// CHECK-X64-NEXT: | nvsize=2, nvalign=1]
struct RZ1 : RX1, RY {};
// CHECK-LABEL: 0 | struct RZ1{{$}}
// CHECK-NEXT: 0 | struct RX1 (base)
// CHECK-NEXT: 0 | struct RA (base) (empty)
// CHECK-NEXT: 0 | struct RB (base)
// CHECK-NEXT: 0 | char c
// CHECK-NEXT: 1 | struct RY (base) (empty)
// CHECK-NEXT: | [sizeof=1, align=1
// CHECK-NEXT: | nvsize=1, nvalign=1]
// CHECK-X64-LABEL: 0 | struct RZ1{{$}}
// CHECK-X64-NEXT: 0 | struct RX1 (base)
// CHECK-X64-NEXT: 0 | struct RA (base) (empty)
// CHECK-X64-NEXT: 0 | struct RB (base)
// CHECK-X64-NEXT: 0 | char c
// CHECK-X64-NEXT: 1 | struct RY (base) (empty)
// CHECK-X64-NEXT: | [sizeof=1, align=1
// CHECK-X64-NEXT: | nvsize=1, nvalign=1]
struct RZ2 : RX2, RY {};
// CHECK-LABEL: 0 | struct RZ2{{$}}
// CHECK-NEXT: 0 | struct RX2 (base)
// CHECK-NEXT: 0 | struct RA (base) (empty)
// CHECK-NEXT: 0 | char a
// CHECK-NEXT: 2 | struct RY (base) (empty)
// CHECK-NEXT: | [sizeof=2, align=1
// CHECK-NEXT: | nvsize=2, nvalign=1]
// CHECK-X64-LABEL: 0 | struct RZ2{{$}}
// CHECK-X64-NEXT: 0 | struct RX2 (base)
// CHECK-X64-NEXT: 0 | struct RA (base) (empty)
// CHECK-X64-NEXT: 0 | char a
// CHECK-X64-NEXT: 2 | struct RY (base) (empty)
// CHECK-X64-NEXT: | [sizeof=2, align=1
// CHECK-X64-NEXT: | nvsize=2, nvalign=1]
struct RZ3 : RX3, RY {};
// CHECK-LABEL: 0 | struct RZ3{{$}}
// CHECK-NEXT: 0 | struct RX3 (base)
// CHECK-NEXT: 0 | struct RA (base) (empty)
// CHECK-NEXT: 0 | struct RB a
// CHECK-NEXT: 0 | char c
// CHECK-NEXT: 1 | struct RY (base) (empty)
// CHECK-NEXT: | [sizeof=1, align=1
// CHECK-NEXT: | nvsize=1, nvalign=1]
// CHECK-X64-LABEL: 0 | struct RZ3{{$}}
// CHECK-X64-NEXT: 0 | struct RX3 (base)
// CHECK-X64-NEXT: 0 | struct RA (base) (empty)
// CHECK-X64-NEXT: 0 | struct RB a
// CHECK-X64-NEXT: 0 | char c
// CHECK-X64-NEXT: 1 | struct RY (base) (empty)
// CHECK-X64-NEXT: | [sizeof=1, align=1
// CHECK-X64-NEXT: | nvsize=1, nvalign=1]
struct RZ4 : RX4, RY {};
// CHECK-LABEL: 0 | struct RZ4{{$}}
// CHECK-NEXT: 0 | struct RX4 (base)
// CHECK-NEXT: 0 | struct RA a (empty)
// CHECK-NEXT: 1 | char b
// CHECK-NEXT: 3 | struct RY (base) (empty)
// CHECK-NEXT: | [sizeof=3, align=1
// CHECK-NEXT: | nvsize=3, nvalign=1]
// CHECK-X64-LABEL: 0 | struct RZ4{{$}}
// CHECK-X64-NEXT: 0 | struct RX4 (base)
// CHECK-X64-NEXT: 0 | struct RA a (empty)
// CHECK-X64-NEXT: 1 | char b
// CHECK-X64-NEXT: 3 | struct RY (base) (empty)
// CHECK-X64-NEXT: | [sizeof=3, align=1
// CHECK-X64-NEXT: | nvsize=3, nvalign=1]
struct RZ5 : RX5, RY {};
// CHECK-LABEL: 0 | struct RZ5{{$}}
// CHECK-NEXT: 0 | struct RX5 (base)
// CHECK-NEXT: 0 | struct RA a (empty)
// CHECK-NEXT: 1 | struct RB b
// CHECK-NEXT: 1 | char c
// CHECK-NEXT: 2 | struct RY (base) (empty)
// CHECK-NEXT: | [sizeof=2, align=1
// CHECK-NEXT: | nvsize=2, nvalign=1]
// CHECK-X64-LABEL: 0 | struct RZ5{{$}}
// CHECK-X64-NEXT: 0 | struct RX5 (base)
// CHECK-X64-NEXT: 0 | struct RA a (empty)
// CHECK-X64-NEXT: 1 | struct RB b
// CHECK-X64-NEXT: 1 | char c
// CHECK-X64-NEXT: 2 | struct RY (base) (empty)
// CHECK-X64-NEXT: | [sizeof=2, align=1
// CHECK-X64-NEXT: | nvsize=2, nvalign=1]
struct RZ6 : RX6, RY {};
// CHECK-LABEL: 0 | struct RZ6{{$}}
// CHECK-NEXT: 0 | struct RX6 (base)
// CHECK-NEXT: 0 | (RX6 vbtable pointer)
// CHECK-NEXT: 4 | struct RB a
// CHECK-NEXT: 4 | char c
// CHECK-NEXT: 9 | struct RY (base) (empty)
// CHECK-NEXT: 12 | struct RV (virtual base) (empty)
// CHECK-NEXT: | [sizeof=12, align=4
// CHECK-NEXT: | nvsize=12, nvalign=4]
// CHECK-X64-LABEL: 0 | struct RZ6{{$}}
// CHECK-X64-NEXT: 0 | struct RX6 (base)
// CHECK-X64-NEXT: 0 | (RX6 vbtable pointer)
// CHECK-X64-NEXT: 8 | struct RB a
// CHECK-X64-NEXT: 8 | char c
// CHECK-X64-NEXT: 17 | struct RY (base) (empty)
// CHECK-X64-NEXT: 24 | struct RV (virtual base) (empty)
// CHECK-X64-NEXT: | [sizeof=24, align=8
// CHECK-X64-NEXT: | nvsize=24, nvalign=8]
struct RZ7 : RX7, RY {};
// CHECK-LABEL: 0 | struct RZ7{{$}}
// CHECK-NEXT: 0 | struct RX7 (base)
// CHECK-NEXT: 0 | (RX7 vbtable pointer)
// CHECK-NEXT: 4 | struct RA a (empty)
// CHECK-NEXT: 8 | struct RY (base) (empty)
// CHECK-NEXT: 8 | struct RW (virtual base)
// CHECK-NEXT: 8 | char c
// CHECK-NEXT: | [sizeof=9, align=4
// CHECK-NEXT: | nvsize=8, nvalign=4]
// CHECK-X64-LABEL: 0 | struct RZ7{{$}}
// CHECK-X64-NEXT: 0 | struct RX7 (base)
// CHECK-X64-NEXT: 0 | (RX7 vbtable pointer)
// CHECK-X64-NEXT: 8 | struct RA a (empty)
// CHECK-X64-NEXT: 16 | struct RY (base) (empty)
// CHECK-X64-NEXT: 16 | struct RW (virtual base)
// CHECK-X64-NEXT: 16 | char c
// CHECK-X64-NEXT: | [sizeof=24, align=8
// CHECK-X64-NEXT: | nvsize=16, nvalign=8]
struct RZ8 : RX8, RY {};
// CHECK-LABEL: 0 | struct RZ8{{$}}
// CHECK-NEXT: 0 | struct RX8 (base)
// CHECK-NEXT: 4 | struct RA (base) (empty)
// CHECK-NEXT: 0 | (RX8 vbtable pointer)
// CHECK-NEXT: 4 | struct RY (base) (empty)
// CHECK-NEXT: 4 | struct RW (virtual base)
// CHECK-NEXT: 4 | char c
// CHECK-NEXT: | [sizeof=5, align=4
// CHECK-NEXT: | nvsize=4, nvalign=4]
// CHECK-X64-LABEL: 0 | struct RZ8{{$}}
// CHECK-X64-NEXT: 0 | struct RX8 (base)
// CHECK-X64-NEXT: 8 | struct RA (base) (empty)
// CHECK-X64-NEXT: 0 | (RX8 vbtable pointer)
// CHECK-X64-NEXT: 8 | struct RY (base) (empty)
// CHECK-X64-NEXT: 8 | struct RW (virtual base)
// CHECK-X64-NEXT: 8 | char c
// CHECK-X64-NEXT: | [sizeof=16, align=8
// CHECK-X64-NEXT: | nvsize=8, nvalign=8]
struct JA {};
struct JB {};
struct JC : JA { virtual void f() {} };
struct JD : virtual JB, virtual JC { virtual void f() {} JD() {} };
// CHECK-LABEL: 0 | struct JD{{$}}
// CHECK-NEXT: 0 | (JD vbtable pointer)
// CHECK-NEXT: 4 | struct JB (virtual base) (empty)
// CHECK-NEXT: 4 | (vtordisp for vbase JC)
// CHECK-NEXT: 8 | struct JC (virtual base)
// CHECK-NEXT: 8 | (JC vftable pointer)
// CHECK-NEXT: 12 | struct JA (base) (empty)
// CHECK-NEXT: | [sizeof=12, align=4
// CHECK-NEXT: | nvsize=4, nvalign=4]
// CHECK-X64-LABEL: 0 | struct JD{{$}}
// CHECK-X64-NEXT: 0 | (JD vbtable pointer)
// CHECK-X64-NEXT: 8 | struct JB (virtual base) (empty)
// CHECK-X64-NEXT: 12 | (vtordisp for vbase JC)
// CHECK-X64-NEXT: 16 | struct JC (virtual base)
// CHECK-X64-NEXT: 16 | (JC vftable pointer)
// CHECK-X64-NEXT: 24 | struct JA (base) (empty)
// CHECK-X64-NEXT: | [sizeof=24, align=8
// CHECK-X64-NEXT: | nvsize=8, nvalign=8]
int a[
sizeof(AT3) +
sizeof(BT3) +
sizeof(T3) +
sizeof(E) +
sizeof(F) +
sizeof(JC4) +
sizeof(RZ0) +
sizeof(RZ1) +
sizeof(RZ2) +
sizeof(RZ3) +
sizeof(RZ4) +
sizeof(RZ5) +
sizeof(RZ6) +
sizeof(RZ7) +
sizeof(RZ8) +
sizeof(JD) +
0];
| 17,083 | 7,574 |
#pragma once
#include "common/types.hh"
#include "common/utf8/rune.hh"
#include "common/hex_formatter.hh"
#include <vector>
#include <string>
#include <iostream>
#include <tuple>
#include <fstream>
template <typename T>
std::vector<T> slice(std::vector<T>& v, std::size_t low, std::size_t high = -1) {
std::vector<T> vec;
if (high == -1) {
std::copy(v.begin() + low, v.end(), std::back_inserter(vec));
} else {
std::copy(v.begin() + low, v.begin() + high, std::back_inserter(vec));
}
return vec;
}
namespace syntax
{
int64_t nextSize(int64_t size);
typedef void (*err_handler)(uint line, uint col, std::string msg);
// The source buffer is accessed using three indices b (begin),
// r (read), and e (end):
//
// - If b >= 0, it points to the beginning of a segment of most
// recently read characters (typically a Go literal).
//
// - r points to the byte immediately following the most recently
// read character ch, which starts at r-chw.
//
// - e points to the byte immediately following the last byte that
// was read into the buffer.
//
// The buffer content is terminated at buf[e] with the sentinel
// character utf8.RuneSelf. This makes it possible to test for
// the common case of ASCII characters with a single 'if' (see
// nextch method).
//
// +------ content in use -------+
// v v
// buf [...read...|...segment...|ch|...unread...|s|...free...]
// ^ ^ ^ ^
// | | | |
// b r-chw r e
//
// Invariant: -1 <= b < r <= e < len(buf) && buf[e] == sentinel
struct source {
std::ifstream _ifs;
err_handler _errh{};
std::string _buf;
int64_t _b;
int64_t _r;
int64_t _e;
int _line;
int _col;
common::utf8::rune_t _ch;
int _chw;
void init(std::string file, err_handler errh);
std::pair<int, int> pos();
void error(std::string msg);
void start();
void stop();
// std::string segment() { return slice(buf, b, r - chw); }
std::string segment();
void rewind();
void nextch();
void fill();
};
} // namespace syntax
| 2,220 | 734 |
//<Snippet1>
#using <System.dll>
#using <System.Windows.Forms.dll>
#using <System.Drawing.dll>
using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;
public ref class ListViewInsertionMarkExample: public Form
{
private:
ListView^ myListView;
public:
//<Snippet2>
ListViewInsertionMarkExample()
{
// Initialize myListView.
myListView = gcnew ListView;
myListView->Dock = DockStyle::Fill;
myListView->View = View::LargeIcon;
myListView->MultiSelect = false;
myListView->ListViewItemSorter = gcnew ListViewIndexComparer;
// Initialize the insertion mark.
myListView->InsertionMark->Color = Color::Green;
// Add items to myListView.
myListView->Items->Add( "zero" );
myListView->Items->Add( "one" );
myListView->Items->Add( "two" );
myListView->Items->Add( "three" );
myListView->Items->Add( "four" );
myListView->Items->Add( "five" );
// Initialize the drag-and-drop operation when running
// under Windows XP or a later operating system.
if ( System::Environment::OSVersion->Version->Major > 5 || (System::Environment::OSVersion->Version->Major == 5 && System::Environment::OSVersion->Version->Minor >= 1) )
{
myListView->AllowDrop = true;
myListView->ItemDrag += gcnew ItemDragEventHandler( this, &ListViewInsertionMarkExample::myListView_ItemDrag );
myListView->DragEnter += gcnew DragEventHandler( this, &ListViewInsertionMarkExample::myListView_DragEnter );
myListView->DragOver += gcnew DragEventHandler( this, &ListViewInsertionMarkExample::myListView_DragOver );
myListView->DragLeave += gcnew EventHandler( this, &ListViewInsertionMarkExample::myListView_DragLeave );
myListView->DragDrop += gcnew DragEventHandler( this, &ListViewInsertionMarkExample::myListView_DragDrop );
}
// Initialize the form.
this->Text = "ListView Insertion Mark Example";
this->Controls->Add( myListView );
}
private:
//</Snippet2>
// Starts the drag-and-drop operation when an item is dragged.
void myListView_ItemDrag( Object^ /*sender*/, ItemDragEventArgs^ e )
{
myListView->DoDragDrop( e->Item, DragDropEffects::Move );
}
// Sets the target drop effect.
void myListView_DragEnter( Object^ /*sender*/, DragEventArgs^ e )
{
e->Effect = e->AllowedEffect;
}
//<Snippet3>
// Moves the insertion mark as the item is dragged.
void myListView_DragOver( Object^ /*sender*/, DragEventArgs^ e )
{
// Retrieve the client coordinates of the mouse pointer.
Point targetPoint = myListView->PointToClient( Point(e->X,e->Y) );
// Retrieve the index of the item closest to the mouse pointer.
int targetIndex = myListView->InsertionMark->NearestIndex( targetPoint );
// Confirm that the mouse pointer is not over the dragged item.
if ( targetIndex > -1 )
{
// Determine whether the mouse pointer is to the left or
// the right of the midpoint of the closest item and set
// the InsertionMark.AppearsAfterItem property accordingly.
Rectangle itemBounds = myListView->GetItemRect( targetIndex );
if ( targetPoint.X > itemBounds.Left + (itemBounds.Width / 2) )
{
myListView->InsertionMark->AppearsAfterItem = true;
}
else
{
myListView->InsertionMark->AppearsAfterItem = false;
}
}
// Set the location of the insertion mark. If the mouse is
// over the dragged item, the targetIndex value is -1 and
// the insertion mark disappears.
myListView->InsertionMark->Index = targetIndex;
}
//</Snippet3>
// Removes the insertion mark when the mouse leaves the control.
void myListView_DragLeave( Object^ /*sender*/, EventArgs^ /*e*/ )
{
myListView->InsertionMark->Index = -1;
}
// Moves the item to the location of the insertion mark.
void myListView_DragDrop( Object^ /*sender*/, DragEventArgs^ e )
{
// Retrieve the index of the insertion mark;
int targetIndex = myListView->InsertionMark->Index;
// If the insertion mark is not visible, exit the method.
if ( targetIndex == -1 )
{
return;
}
// If the insertion mark is to the right of the item with
// the corresponding index, increment the target index.
if ( myListView->InsertionMark->AppearsAfterItem )
{
targetIndex++;
}
// Retrieve the dragged item.
ListViewItem^ draggedItem = dynamic_cast<ListViewItem^>(e->Data->GetData( ListViewItem::typeid ));
// Insert a copy of the dragged item at the target index.
// A copy must be inserted before the original item is removed
// to preserve item index values.
myListView->Items->Insert( targetIndex, dynamic_cast<ListViewItem^>(draggedItem->Clone()) );
// Remove the original copy of the dragged item.
myListView->Items->Remove( draggedItem );
}
// Sorts ListViewItem objects by index.
ref class ListViewIndexComparer: public System::Collections::IComparer
{
public:
virtual int Compare( Object^ x, Object^ y )
{
return (dynamic_cast<ListViewItem^>(x))->Index - (dynamic_cast<ListViewItem^>(y))->Index;
}
};
};
[STAThread]
int main()
{
Application::EnableVisualStyles();
Application::Run( gcnew ListViewInsertionMarkExample );
}
//</Snippet1>
| 5,531 | 1,579 |
#include "estacaocarregamento.h"
/*===============================================
Construtores
===============================================*/
EstacaoCarregamento::EstacaoCarregamento() {
tempoMinimoFila = Relogio();
tempoMaximoFila = Relogio();
minimoEntidadesNaFila = 0;
maximoEntidadesNaFila = 0;
distTC = new RN::Constante( 1.0 );
}
//===============================================
EstacaoCarregamento::EstacaoCarregamento( RN::Distribuicao *distribuicaoProbabilidadeTC ) {
tempoMinimoFila = Relogio();
tempoMaximoFila = Relogio();
minimoEntidadesNaFila = 0;
maximoEntidadesNaFila = 0;
distTC = distribuicaoProbabilidadeTC;
}
/*===============================================
Eventos principais
===============================================*/
Evento *EstacaoCarregamento::enfileirarCaminhao( Caminhao *caminhao, Relogio horaAtual ) {
std::cout << "[Enfileirando caminhão carga]"<<std::endl;
Evento *eventoCarga;
if( temEstacaoLivre() ) {
eventoCarga = new Evento( Evento::carga,horaAtual,caminhao );
atualizaTemposFila( Relogio() );
return eventoCarga;
}
eventoCarga = new Evento( Evento::carga,proximoTempoLivre,caminhao );
Relogio tempoEmFila( proximoTempoLivre );
std::cout <<">Carregamento ocupado " << horaAtual.getSegundosSimulacao()<< " - " << proximoTempoLivre.getSegundosSimulacao()<<std::endl;
tempoEmFila -= horaAtual;
atualizaTemposFila( tempoEmFila );
aumentaNumeroNaFila();
return eventoCarga;
}
//===============================================
Evento *EstacaoCarregamento::carregarCaminhao( Caminhao *caminhao, Relogio horaAtual ) {
std::cout << "[Carregando caminhão]"<<std::endl;
int plataformaOcupando;
diminuiNumeroNaFila();
//Verifica qual plataforma está livre
plataformaOcupando = plataformaLivre();
livre[plataformaOcupando-1] = false;//ocupa a plataforma
caminhaoOcupandoPlataforma[plataformaOcupando-1] = caminhao;//Seta o caminhao que está ocupando essa plataforma
int TC = distTC->gerarVariavelAleatoria();//Gera o TC
std::cout<<"[TC = " << TC<< "]" << std::endl;
tempoTotalOcupacaoPlataforma[plataformaOcupando-1] += TC;//Aumenta o tempo total de ocupação desta plataforma
Relogio fimCarga( horaAtual );
Relogio relTC = Relogio();
relTC.adicionaSegundos( TC );
fimCarga << relTC;
horaLiberacaoPlataforma[plataformaOcupando-1] = fimCarga;
if( horaLiberacaoPlataforma[0] < horaLiberacaoPlataforma[1] ) {
proximoTempoLivre = horaLiberacaoPlataforma[0];
} else {
proximoTempoLivre = horaLiberacaoPlataforma[1];
}
jaUtilizada [plataformaOcupando-1] = true;
std::cout << "[Fim da carga "<< fimCarga.getSegundosSimulacao()<< "][Proximo Livre " << proximoTempoLivre.getSegundosSimulacao()<<"]" << std::endl;
return new Evento( Evento::chegadaPesagem,fimCarga,caminhao );
}
//===============================================
void EstacaoCarregamento::retirarCaminhao( Caminhao *caminhao ) {
std::cout << "[Retirando caminhão carregamento]"<<std::endl;
int plataformaRetirada;
if( *caminhaoOcupandoPlataforma[0]==*caminhao ) {
plataformaRetirada = 1;
} else {
plataformaRetirada = 2;
}
livre[plataformaRetirada-1] = true;
}
/*===============================================
Funções auxiliares (private)
===============================================*/
bool EstacaoCarregamento::plataformasVirgens() {
if( !jaUtilizada[0] )return true;
if( !jaUtilizada[1] )return true;
return false;
}
//===============================================
int EstacaoCarregamento::plataformaLivre() {
if( livre[0] ) {
return 1;
} else {
return 2;
}
}
//===============================================
void EstacaoCarregamento::modificarDistribuicaoTC( RN::Distribuicao *dist ) {
this->distTC = dist;
}
//===============================================
bool EstacaoCarregamento::temEstacaoLivre() {
return livre[0] || livre[1];
}
//===============================================
void EstacaoCarregamento::atualizaTemposFila( Relogio tempoFila ) {
Relogio zero = Relogio();
if ( tempoFila == zero ) {
temposDeFila.push_back( Relogio( tempoFila ) );
return;
}
//Atualiza a lista de tempos de fila
temposDeFila.push_back( Relogio( tempoFila ) );
//Atualiza o tempo mínimo em fila
if( tempoFila < tempoMinimoFila ) {
tempoMinimoFila = tempoFila;
}
//Atualiza o tempo máximo em fila
if ( tempoMaximoFila < tempoFila ) {
tempoMaximoFila = tempoFila;
}
}
//===============================================
void EstacaoCarregamento::aumentaNumeroNaFila() {
numeroEntidadesEnfileiradas++;
totalEntidadesEnfileiradas++;
somaFila.push_back( numeroEntidadesEnfileiradas );
if( maximoEntidadesNaFila < numeroEntidadesEnfileiradas ) {
maximoEntidadesNaFila = numeroEntidadesEnfileiradas;
}
}
//===============================================
void EstacaoCarregamento::diminuiNumeroNaFila() {
if( numeroEntidadesEnfileiradas >0 )
numeroEntidadesEnfileiradas--;
somaFila.push_back( numeroEntidadesEnfileiradas );
if( minimoEntidadesNaFila > numeroEntidadesEnfileiradas ) {
minimoEntidadesNaFila = numeroEntidadesEnfileiradas;
}
}
//===============================================
double EstacaoCarregamento::mediaFila() {
if( somaFila.empty() ) return 0;
int somaTotal = 0;
for( int numeroEmFila : somaFila ) {
//std::cout << "Media carregamento: somando " << numeroEmFila << std::endl;
somaTotal += numeroEmFila;
}
return ( double )somaTotal / somaFila.size();
}
//===============================================
void EstacaoCarregamento::atualizaEstatisticasTempoFila() {
//Organiza os tempos de fila
if( temposDeFila.size()==0 ) {tempoMinimoFila = Relogio(); tempoMaximoFila=Relogio(); return;}
tempoMinimoFila = *std::max_element( temposDeFila.begin(),temposDeFila.end() );
tempoMaximoFila = *std::min_element( temposDeFila.begin(),temposDeFila.end() );
}
//===============================================
double EstacaoCarregamento::getMediaTempoFila() {
if( temposDeFila.size()>0 ) {
int somaTemposFila;
for( Relogio tempoEmFila: temposDeFila ) {
somaTemposFila += tempoEmFila.getSegundosSimulacao();
}
return ( double ) somaTemposFila / ( double ) temposDeFila.size();
}
return 0;
}
| 6,326 | 2,308 |
/*
* Copyright (c) 2020 Inria
* Copyright (c) 2016 Georgia Institute of Technology
* Copyright (c) 2008 Princeton University
* 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 copyright holders 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 "mem/ruby/network/garnet2.0/InputUnit.hh"
#include "debug/RubyNetwork.hh"
#include "mem/ruby/network/garnet2.0/Credit.hh"
#include "mem/ruby/network/garnet2.0/Router.hh"
using namespace std;
InputUnit::InputUnit(int id, PortDirection direction, Router *router)
: Consumer(router), m_router(router), m_id(id), m_direction(direction),
m_vc_per_vnet(m_router->get_vc_per_vnet())
{
const int m_num_vcs = m_router->get_num_vcs();
m_num_buffer_reads.resize(m_num_vcs/m_vc_per_vnet);
m_num_buffer_writes.resize(m_num_vcs/m_vc_per_vnet);
for (int i = 0; i < m_num_buffer_reads.size(); i++) {
m_num_buffer_reads[i] = 0;
m_num_buffer_writes[i] = 0;
}
// Instantiating the virtual channels
virtualChannels.reserve(m_num_vcs);
for (int i=0; i < m_num_vcs; i++) {
virtualChannels.emplace_back();
}
}
/*
* The InputUnit wakeup function reads the input flit from its input link.
* Each flit arrives with an input VC.
* For HEAD/HEAD_TAIL flits, performs route computation,
* and updates route in the input VC.
* The flit is buffered for (m_latency - 1) cycles in the input VC
* and marked as valid for SwitchAllocation starting that cycle.
*
*/
void
InputUnit::wakeup()
{
flit *t_flit;
if (m_in_link->isReady(m_router->curCycle())) {
t_flit = m_in_link->consumeLink();
int vc = t_flit->get_vc();
t_flit->increment_hops(); // for stats
if ((t_flit->get_type() == HEAD_) ||
(t_flit->get_type() == HEAD_TAIL_)) {
assert(virtualChannels[vc].get_state() == IDLE_);
set_vc_active(vc, m_router->curCycle());
// Route computation for this vc
// int outport = m_router->route_compute(t_flit->get_route(),
// m_id, m_direction);
int outport = m_router->route_compute(t_flit->get_route(),
m_id, m_direction);
// Update output port in VC
// All flits in this packet will use this output port
// The output port field in the flit is updated after it wins SA
grant_outport(vc, outport);
} else {
assert(virtualChannels[vc].get_state() == ACTIVE_);
}
// Buffer the flit
virtualChannels[vc].insertFlit(t_flit);
int vnet = vc/m_vc_per_vnet;
// number of writes same as reads
// any flit that is written will be read only once
m_num_buffer_writes[vnet]++;
m_num_buffer_reads[vnet]++;
Cycles pipe_stages = m_router->get_pipe_stages();
if (pipe_stages == 1) {
// 1-cycle router
// Flit goes for SA directly
t_flit->advance_stage(SA_, m_router->curCycle());
} else {
assert(pipe_stages > 1);
// Router delay is modeled by making flit wait in buffer for
// (pipe_stages cycles - 1) cycles before going for SA
Cycles wait_time = pipe_stages - Cycles(1);
t_flit->advance_stage(SA_, m_router->curCycle() + wait_time);
// Wakeup the router in that cycle to perform SA
m_router->schedule_wakeup(Cycles(wait_time));
}
}
}
// Send a credit back to upstream router for this VC.
// Called by SwitchAllocator when the flit in this VC wins the Switch.
void
InputUnit::increment_credit(int in_vc, bool free_signal, Cycles curTime)
{
Credit *t_credit = new Credit(in_vc, free_signal, curTime);
creditQueue.insert(t_credit);
m_credit_link->scheduleEventAbsolute(m_router->clockEdge(Cycles(1)));
}
uint32_t
InputUnit::functionalWrite(Packet *pkt)
{
uint32_t num_functional_writes = 0;
for (auto& virtual_channel : virtualChannels) {
num_functional_writes += virtual_channel.functionalWrite(pkt);
}
return num_functional_writes;
}
void
InputUnit::resetStats()
{
for (int j = 0; j < m_num_buffer_reads.size(); j++) {
m_num_buffer_reads[j] = 0;
m_num_buffer_writes[j] = 0;
}
}
| 5,662 | 1,965 |
/*
Programa: cadastro02
Arquivo: cadastro02.cpp
*/
#include <iostream>
#include "parametros.h"
using namespace std;
struct Pessoa {
string nome;
int idade;
char sexo;
} ;
int main() {
Pessoa cadastro[N];
int x; // Variável de controle
for ( x = 0; x < N ; x++) {
cout << "Digite o nome: ";
cin >> cadastro[x].nome;
cout << "Digite a idade: ";
cin >> cadastro[x].idade;
cout << "Digite o sexo (m para masculino, f para feminino): ";
cin >> cadastro[x].sexo;
}
for ( x = 0; x < N ; x++) {
cout << cadastro[x].nome << " - "<< cadastro[x].idade ;
cout << " - "<< cadastro[x].sexo << endl;
}
return 0;
}
| 718 | 274 |
/*
* 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.
*
* The Original Code is Copyright (C) 2012 Blender Foundation.
* All rights reserved.
*/
#include <iostream>
#include <math.h>
#include <sstream>
#include <string.h>
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable : 4251 4275)
#endif
#include <OpenColorIO/OpenColorIO.h>
#ifdef _MSC_VER
# pragma warning(pop)
#endif
using namespace OCIO_NAMESPACE;
#include "MEM_guardedalloc.h"
#include "BLI_math_color.h"
#include "ocio_impl.h"
#if !defined(WITH_ASSERT_ABORT)
# define OCIO_abort()
#else
# include <stdlib.h>
# define OCIO_abort() abort()
#endif
#if defined(_MSC_VER)
# define __func__ __FUNCTION__
#endif
/* NOTE: This is because OCIO 1.1.0 has a bug which makes default
* display to be the one which is first alphabetically.
*
* Fix has been submitted as a patch
* https://github.com/imageworks/OpenColorIO/pull/638
*
* For until then we use first usable display instead. */
#define DEFAULT_DISPLAY_WORKAROUND
#ifdef DEFAULT_DISPLAY_WORKAROUND
# include <algorithm>
# include <map>
# include <mutex>
# include <set>
# include <string>
# include <vector>
using std::map;
using std::set;
using std::string;
using std::vector;
#endif
static void OCIO_reportError(const char *err)
{
std::cerr << "OpenColorIO Error: " << err << std::endl;
OCIO_abort();
}
static void OCIO_reportException(Exception &exception)
{
OCIO_reportError(exception.what());
}
OCIO_ConstConfigRcPtr *OCIOImpl::getCurrentConfig(void)
{
ConstConfigRcPtr *config = OBJECT_GUARDED_NEW(ConstConfigRcPtr);
try {
*config = GetCurrentConfig();
if (*config)
return (OCIO_ConstConfigRcPtr *)config;
}
catch (Exception &exception) {
OCIO_reportException(exception);
}
OBJECT_GUARDED_DELETE(config, ConstConfigRcPtr);
return NULL;
}
void OCIOImpl::setCurrentConfig(const OCIO_ConstConfigRcPtr *config)
{
try {
SetCurrentConfig(*(ConstConfigRcPtr *)config);
}
catch (Exception &exception) {
OCIO_reportException(exception);
}
}
OCIO_ConstConfigRcPtr *OCIOImpl::configCreateFromEnv(void)
{
ConstConfigRcPtr *config = OBJECT_GUARDED_NEW(ConstConfigRcPtr);
try {
*config = Config::CreateFromEnv();
if (*config)
return (OCIO_ConstConfigRcPtr *)config;
}
catch (Exception &exception) {
OCIO_reportException(exception);
}
OBJECT_GUARDED_DELETE(config, ConstConfigRcPtr);
return NULL;
}
OCIO_ConstConfigRcPtr *OCIOImpl::configCreateFromFile(const char *filename)
{
ConstConfigRcPtr *config = OBJECT_GUARDED_NEW(ConstConfigRcPtr);
try {
*config = Config::CreateFromFile(filename);
if (*config)
return (OCIO_ConstConfigRcPtr *)config;
}
catch (Exception &exception) {
OCIO_reportException(exception);
}
OBJECT_GUARDED_DELETE(config, ConstConfigRcPtr);
return NULL;
}
void OCIOImpl::configRelease(OCIO_ConstConfigRcPtr *config)
{
OBJECT_GUARDED_DELETE((ConstConfigRcPtr *)config, ConstConfigRcPtr);
}
int OCIOImpl::configGetNumColorSpaces(OCIO_ConstConfigRcPtr *config)
{
try {
return (*(ConstConfigRcPtr *)config)->getNumColorSpaces();
}
catch (Exception &exception) {
OCIO_reportException(exception);
}
return 0;
}
const char *OCIOImpl::configGetColorSpaceNameByIndex(OCIO_ConstConfigRcPtr *config, int index)
{
try {
return (*(ConstConfigRcPtr *)config)->getColorSpaceNameByIndex(index);
}
catch (Exception &exception) {
OCIO_reportException(exception);
}
return NULL;
}
OCIO_ConstColorSpaceRcPtr *OCIOImpl::configGetColorSpace(OCIO_ConstConfigRcPtr *config,
const char *name)
{
ConstColorSpaceRcPtr *cs = OBJECT_GUARDED_NEW(ConstColorSpaceRcPtr);
try {
*cs = (*(ConstConfigRcPtr *)config)->getColorSpace(name);
if (*cs)
return (OCIO_ConstColorSpaceRcPtr *)cs;
}
catch (Exception &exception) {
OCIO_reportException(exception);
}
OBJECT_GUARDED_DELETE(cs, ConstColorSpaceRcPtr);
return NULL;
}
int OCIOImpl::configGetIndexForColorSpace(OCIO_ConstConfigRcPtr *config, const char *name)
{
try {
return (*(ConstConfigRcPtr *)config)->getIndexForColorSpace(name);
}
catch (Exception &exception) {
OCIO_reportException(exception);
}
return -1;
}
const char *OCIOImpl::configGetDefaultDisplay(OCIO_ConstConfigRcPtr *config)
{
#ifdef DEFAULT_DISPLAY_WORKAROUND
if (getenv("OCIO_ACTIVE_DISPLAYS") == NULL) {
const char *active_displays = (*(ConstConfigRcPtr *)config)->getActiveDisplays();
if (active_displays[0] != '\0') {
const char *separator_pos = strchr(active_displays, ',');
if (separator_pos == NULL) {
return active_displays;
}
static std::string active_display;
/* NOTE: Configuration is shared and is never changed during
* runtime, so we only guarantee two threads don't initialize at the
* same. */
static std::mutex mutex;
mutex.lock();
if (active_display.empty()) {
active_display = active_displays;
active_display[separator_pos - active_displays] = '\0';
}
mutex.unlock();
return active_display.c_str();
}
}
#endif
try {
return (*(ConstConfigRcPtr *)config)->getDefaultDisplay();
}
catch (Exception &exception) {
OCIO_reportException(exception);
}
return NULL;
}
int OCIOImpl::configGetNumDisplays(OCIO_ConstConfigRcPtr *config)
{
try {
return (*(ConstConfigRcPtr *)config)->getNumDisplays();
}
catch (Exception &exception) {
OCIO_reportException(exception);
}
return 0;
}
const char *OCIOImpl::configGetDisplay(OCIO_ConstConfigRcPtr *config, int index)
{
try {
return (*(ConstConfigRcPtr *)config)->getDisplay(index);
}
catch (Exception &exception) {
OCIO_reportException(exception);
}
return NULL;
}
#ifdef DEFAULT_DISPLAY_WORKAROUND
namespace {
void splitStringEnvStyle(vector<string> *tokens, const string &str)
{
tokens->clear();
const int len = str.length();
int token_start = 0, token_length = 0;
for (int i = 0; i < len; ++i) {
const char ch = str[i];
if (ch != ',' && ch != ':') {
/* Append non-separator char to a token. */
++token_length;
}
else {
/* Append current token to the list (if any). */
if (token_length > 0) {
string token = str.substr(token_start, token_length);
tokens->push_back(token);
}
/* Re-set token pointers. */
token_start = i + 1;
token_length = 0;
}
}
/* Append token which might be at the end of the string. */
if (token_length != 0) {
string token = str.substr(token_start, token_length);
tokens->push_back(token);
}
}
string stringToLower(const string &str)
{
string lower = str;
std::transform(lower.begin(), lower.end(), lower.begin(), tolower);
return lower;
}
} // namespace
#endif
const char *OCIOImpl::configGetDefaultView(OCIO_ConstConfigRcPtr *config, const char *display)
{
#ifdef DEFAULT_DISPLAY_WORKAROUND
/* NOTE: We assume that first active view always exists for a default
* display. */
if (getenv("OCIO_ACTIVE_VIEWS") == NULL) {
ConstConfigRcPtr config_ptr = *((ConstConfigRcPtr *)config);
const char *active_views_encoded = config_ptr->getActiveViews();
if (active_views_encoded[0] != '\0') {
const string display_lower = stringToLower(display);
static map<string, string> default_display_views;
static std::mutex mutex;
mutex.lock();
/* Check if the view is already known. */
map<string, string>::const_iterator it = default_display_views.find(display_lower);
if (it != default_display_views.end()) {
mutex.unlock();
return it->second.c_str();
}
/* Active views. */
vector<string> active_views;
splitStringEnvStyle(&active_views, active_views_encoded);
/* Get all views supported by tge display. */
set<string> display_views;
const int num_display_views = config_ptr->getNumViews(display);
for (int view_index = 0; view_index < num_display_views; ++view_index) {
const char *view = config_ptr->getView(display, view_index);
display_views.insert(stringToLower(view));
}
/* Get first view which is supported by tge display. */
for (const string &view : active_views) {
const string view_lower = stringToLower(view);
if (display_views.find(view_lower) != display_views.end()) {
default_display_views[display_lower] = view;
mutex.unlock();
return default_display_views[display_lower].c_str();
}
}
mutex.unlock();
}
}
#endif
try {
return (*(ConstConfigRcPtr *)config)->getDefaultView(display);
}
catch (Exception &exception) {
OCIO_reportException(exception);
}
return NULL;
}
int OCIOImpl::configGetNumViews(OCIO_ConstConfigRcPtr *config, const char *display)
{
try {
return (*(ConstConfigRcPtr *)config)->getNumViews(display);
}
catch (Exception &exception) {
OCIO_reportException(exception);
}
return 0;
}
const char *OCIOImpl::configGetView(OCIO_ConstConfigRcPtr *config, const char *display, int index)
{
try {
return (*(ConstConfigRcPtr *)config)->getView(display, index);
}
catch (Exception &exception) {
OCIO_reportException(exception);
}
return NULL;
}
const char *OCIOImpl::configGetDisplayColorSpaceName(OCIO_ConstConfigRcPtr *config,
const char *display,
const char *view)
{
try {
return (*(ConstConfigRcPtr *)config)->getDisplayColorSpaceName(display, view);
}
catch (Exception &exception) {
OCIO_reportException(exception);
}
return NULL;
}
void OCIOImpl::configGetDefaultLumaCoefs(OCIO_ConstConfigRcPtr *config, float *rgb)
{
try {
(*(ConstConfigRcPtr *)config)->getDefaultLumaCoefs(rgb);
}
catch (Exception &exception) {
OCIO_reportException(exception);
}
}
void OCIOImpl::configGetXYZtoRGB(OCIO_ConstConfigRcPtr *config_, float xyz_to_rgb[3][3])
{
ConstConfigRcPtr config = (*(ConstConfigRcPtr *)config_);
/* Default to ITU-BT.709 in case no appropriate transform found. */
memcpy(xyz_to_rgb, OCIO_XYZ_TO_LINEAR_SRGB, sizeof(OCIO_XYZ_TO_LINEAR_SRGB));
/* Auto estimate from XYZ and scene_linear roles, assumed to be a linear transform. */
if (config->hasRole("XYZ") && config->hasRole("scene_linear")) {
ConstProcessorRcPtr to_rgb_processor = config->getProcessor("XYZ", "scene_linear");
if (to_rgb_processor) {
xyz_to_rgb[0][0] = 1.0f;
xyz_to_rgb[0][1] = 0.0f;
xyz_to_rgb[0][2] = 0.0f;
xyz_to_rgb[1][0] = 0.0f;
xyz_to_rgb[1][1] = 1.0f;
xyz_to_rgb[1][2] = 0.0f;
xyz_to_rgb[2][0] = 0.0f;
xyz_to_rgb[2][1] = 0.0f;
xyz_to_rgb[2][2] = 1.0f;
to_rgb_processor->applyRGB(xyz_to_rgb[0]);
to_rgb_processor->applyRGB(xyz_to_rgb[1]);
to_rgb_processor->applyRGB(xyz_to_rgb[2]);
}
}
}
int OCIOImpl::configGetNumLooks(OCIO_ConstConfigRcPtr *config)
{
try {
return (*(ConstConfigRcPtr *)config)->getNumLooks();
}
catch (Exception &exception) {
OCIO_reportException(exception);
}
return 0;
}
const char *OCIOImpl::configGetLookNameByIndex(OCIO_ConstConfigRcPtr *config, int index)
{
try {
return (*(ConstConfigRcPtr *)config)->getLookNameByIndex(index);
}
catch (Exception &exception) {
OCIO_reportException(exception);
}
return NULL;
}
OCIO_ConstLookRcPtr *OCIOImpl::configGetLook(OCIO_ConstConfigRcPtr *config, const char *name)
{
ConstLookRcPtr *look = OBJECT_GUARDED_NEW(ConstLookRcPtr);
try {
*look = (*(ConstConfigRcPtr *)config)->getLook(name);
if (*look)
return (OCIO_ConstLookRcPtr *)look;
}
catch (Exception &exception) {
OCIO_reportException(exception);
}
OBJECT_GUARDED_DELETE(look, ConstLookRcPtr);
return NULL;
}
const char *OCIOImpl::lookGetProcessSpace(OCIO_ConstLookRcPtr *look)
{
return (*(ConstLookRcPtr *)look)->getProcessSpace();
}
void OCIOImpl::lookRelease(OCIO_ConstLookRcPtr *look)
{
OBJECT_GUARDED_DELETE((ConstLookRcPtr *)look, ConstLookRcPtr);
}
int OCIOImpl::colorSpaceIsInvertible(OCIO_ConstColorSpaceRcPtr *cs_)
{
ConstColorSpaceRcPtr *cs = (ConstColorSpaceRcPtr *)cs_;
const char *family = (*cs)->getFamily();
if (!strcmp(family, "rrt") || !strcmp(family, "display")) {
/* assume display and rrt transformations are not invertible in fact some of them could be,
* but it doesn't make much sense to allow use them as invertible. */
return false;
}
if ((*cs)->isData()) {
/* data color spaces don't have transformation at all */
return true;
}
if ((*cs)->getTransform(COLORSPACE_DIR_TO_REFERENCE)) {
/* if there's defined transform to reference space,
* color space could be converted to scene linear. */
return true;
}
return true;
}
int OCIOImpl::colorSpaceIsData(OCIO_ConstColorSpaceRcPtr *cs)
{
return (*(ConstColorSpaceRcPtr *)cs)->isData();
}
static float compare_floats(float a, float b, float abs_diff, int ulp_diff)
{
/* Returns true if the absolute difference is smaller than abs_diff (for numbers near zero)
* or their relative difference is less than ulp_diff ULPs. Based on:
* https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ */
if (fabsf(a - b) < abs_diff) {
return true;
}
if ((a < 0.0f) != (b < 0.0f)) {
return false;
}
return (abs((*(int *)&a) - (*(int *)&b)) < ulp_diff);
}
void OCIOImpl::colorSpaceIsBuiltin(OCIO_ConstConfigRcPtr *config_,
OCIO_ConstColorSpaceRcPtr *cs_,
bool &is_scene_linear,
bool &is_srgb)
{
ConstConfigRcPtr *config = (ConstConfigRcPtr *)config_;
ConstColorSpaceRcPtr *cs = (ConstColorSpaceRcPtr *)cs_;
ConstProcessorRcPtr processor;
try {
processor = (*config)->getProcessor((*cs)->getName(), "scene_linear");
}
catch (Exception &) {
/* Silently ignore if no conversion possible, then it's not scene linear or sRGB. */
is_scene_linear = false;
is_srgb = false;
return;
}
is_scene_linear = true;
is_srgb = true;
for (int i = 0; i < 256; i++) {
float v = i / 255.0f;
float cR[3] = {v, 0, 0};
float cG[3] = {0, v, 0};
float cB[3] = {0, 0, v};
float cW[3] = {v, v, v};
processor->applyRGB(cR);
processor->applyRGB(cG);
processor->applyRGB(cB);
processor->applyRGB(cW);
/* Make sure that there is no channel crosstalk. */
if (fabsf(cR[1]) > 1e-5f || fabsf(cR[2]) > 1e-5f || fabsf(cG[0]) > 1e-5f ||
fabsf(cG[2]) > 1e-5f || fabsf(cB[0]) > 1e-5f || fabsf(cB[1]) > 1e-5f) {
is_scene_linear = false;
is_srgb = false;
break;
}
/* Make sure that the three primaries combine linearly. */
if (!compare_floats(cR[0], cW[0], 1e-6f, 64) || !compare_floats(cG[1], cW[1], 1e-6f, 64) ||
!compare_floats(cB[2], cW[2], 1e-6f, 64)) {
is_scene_linear = false;
is_srgb = false;
break;
}
/* Make sure that the three channels behave identically. */
if (!compare_floats(cW[0], cW[1], 1e-6f, 64) || !compare_floats(cW[1], cW[2], 1e-6f, 64)) {
is_scene_linear = false;
is_srgb = false;
break;
}
float out_v = (cW[0] + cW[1] + cW[2]) * (1.0f / 3.0f);
if (!compare_floats(v, out_v, 1e-6f, 64)) {
is_scene_linear = false;
}
if (!compare_floats(srgb_to_linearrgb(v), out_v, 1e-6f, 64)) {
is_srgb = false;
}
}
}
void OCIOImpl::colorSpaceRelease(OCIO_ConstColorSpaceRcPtr *cs)
{
OBJECT_GUARDED_DELETE((ConstColorSpaceRcPtr *)cs, ConstColorSpaceRcPtr);
}
OCIO_ConstProcessorRcPtr *OCIOImpl::configGetProcessorWithNames(OCIO_ConstConfigRcPtr *config,
const char *srcName,
const char *dstName)
{
ConstProcessorRcPtr *p = OBJECT_GUARDED_NEW(ConstProcessorRcPtr);
try {
*p = (*(ConstConfigRcPtr *)config)->getProcessor(srcName, dstName);
if (*p)
return (OCIO_ConstProcessorRcPtr *)p;
}
catch (Exception &exception) {
OCIO_reportException(exception);
}
OBJECT_GUARDED_DELETE(p, ConstProcessorRcPtr);
return 0;
}
OCIO_ConstProcessorRcPtr *OCIOImpl::configGetProcessor(OCIO_ConstConfigRcPtr *config,
OCIO_ConstTransformRcPtr *transform)
{
ConstProcessorRcPtr *p = OBJECT_GUARDED_NEW(ConstProcessorRcPtr);
try {
*p = (*(ConstConfigRcPtr *)config)->getProcessor(*(ConstTransformRcPtr *)transform);
if (*p)
return (OCIO_ConstProcessorRcPtr *)p;
}
catch (Exception &exception) {
OCIO_reportException(exception);
}
OBJECT_GUARDED_DELETE(p, ConstProcessorRcPtr);
return NULL;
}
void OCIOImpl::processorApply(OCIO_ConstProcessorRcPtr *processor, OCIO_PackedImageDesc *img)
{
try {
(*(ConstProcessorRcPtr *)processor)->apply(*(PackedImageDesc *)img);
}
catch (Exception &exception) {
OCIO_reportException(exception);
}
}
void OCIOImpl::processorApply_predivide(OCIO_ConstProcessorRcPtr *processor,
OCIO_PackedImageDesc *img_)
{
try {
PackedImageDesc *img = (PackedImageDesc *)img_;
int channels = img->getNumChannels();
if (channels == 4) {
float *pixels = img->getData();
int width = img->getWidth();
int height = img->getHeight();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
float *pixel = pixels + 4 * (y * width + x);
processorApplyRGBA_predivide(processor, pixel);
}
}
}
else {
(*(ConstProcessorRcPtr *)processor)->apply(*img);
}
}
catch (Exception &exception) {
OCIO_reportException(exception);
}
}
void OCIOImpl::processorApplyRGB(OCIO_ConstProcessorRcPtr *processor, float *pixel)
{
(*(ConstProcessorRcPtr *)processor)->applyRGB(pixel);
}
void OCIOImpl::processorApplyRGBA(OCIO_ConstProcessorRcPtr *processor, float *pixel)
{
(*(ConstProcessorRcPtr *)processor)->applyRGBA(pixel);
}
void OCIOImpl::processorApplyRGBA_predivide(OCIO_ConstProcessorRcPtr *processor, float *pixel)
{
if (pixel[3] == 1.0f || pixel[3] == 0.0f) {
(*(ConstProcessorRcPtr *)processor)->applyRGBA(pixel);
}
else {
float alpha, inv_alpha;
alpha = pixel[3];
inv_alpha = 1.0f / alpha;
pixel[0] *= inv_alpha;
pixel[1] *= inv_alpha;
pixel[2] *= inv_alpha;
(*(ConstProcessorRcPtr *)processor)->applyRGBA(pixel);
pixel[0] *= alpha;
pixel[1] *= alpha;
pixel[2] *= alpha;
}
}
void OCIOImpl::processorRelease(OCIO_ConstProcessorRcPtr *p)
{
OBJECT_GUARDED_DELETE(p, ConstProcessorRcPtr);
}
const char *OCIOImpl::colorSpaceGetName(OCIO_ConstColorSpaceRcPtr *cs)
{
return (*(ConstColorSpaceRcPtr *)cs)->getName();
}
const char *OCIOImpl::colorSpaceGetDescription(OCIO_ConstColorSpaceRcPtr *cs)
{
return (*(ConstColorSpaceRcPtr *)cs)->getDescription();
}
const char *OCIOImpl::colorSpaceGetFamily(OCIO_ConstColorSpaceRcPtr *cs)
{
return (*(ConstColorSpaceRcPtr *)cs)->getFamily();
}
OCIO_DisplayTransformRcPtr *OCIOImpl::createDisplayTransform(void)
{
DisplayTransformRcPtr *dt = OBJECT_GUARDED_NEW(DisplayTransformRcPtr);
*dt = DisplayTransform::Create();
return (OCIO_DisplayTransformRcPtr *)dt;
}
void OCIOImpl::displayTransformSetInputColorSpaceName(OCIO_DisplayTransformRcPtr *dt,
const char *name)
{
(*(DisplayTransformRcPtr *)dt)->setInputColorSpaceName(name);
}
void OCIOImpl::displayTransformSetDisplay(OCIO_DisplayTransformRcPtr *dt, const char *name)
{
(*(DisplayTransformRcPtr *)dt)->setDisplay(name);
}
void OCIOImpl::displayTransformSetView(OCIO_DisplayTransformRcPtr *dt, const char *name)
{
(*(DisplayTransformRcPtr *)dt)->setView(name);
}
void OCIOImpl::displayTransformSetDisplayCC(OCIO_DisplayTransformRcPtr *dt,
OCIO_ConstTransformRcPtr *t)
{
(*(DisplayTransformRcPtr *)dt)->setDisplayCC(*(ConstTransformRcPtr *)t);
}
void OCIOImpl::displayTransformSetLinearCC(OCIO_DisplayTransformRcPtr *dt,
OCIO_ConstTransformRcPtr *t)
{
(*(DisplayTransformRcPtr *)dt)->setLinearCC(*(ConstTransformRcPtr *)t);
}
void OCIOImpl::displayTransformSetLooksOverride(OCIO_DisplayTransformRcPtr *dt, const char *looks)
{
(*(DisplayTransformRcPtr *)dt)->setLooksOverride(looks);
}
void OCIOImpl::displayTransformSetLooksOverrideEnabled(OCIO_DisplayTransformRcPtr *dt,
bool enabled)
{
(*(DisplayTransformRcPtr *)dt)->setLooksOverrideEnabled(enabled);
}
void OCIOImpl::displayTransformRelease(OCIO_DisplayTransformRcPtr *dt)
{
OBJECT_GUARDED_DELETE((DisplayTransformRcPtr *)dt, DisplayTransformRcPtr);
}
OCIO_PackedImageDesc *OCIOImpl::createOCIO_PackedImageDesc(float *data,
long width,
long height,
long numChannels,
long chanStrideBytes,
long xStrideBytes,
long yStrideBytes)
{
try {
void *mem = MEM_mallocN(sizeof(PackedImageDesc), __func__);
PackedImageDesc *id = new (mem) PackedImageDesc(
data, width, height, numChannels, chanStrideBytes, xStrideBytes, yStrideBytes);
return (OCIO_PackedImageDesc *)id;
}
catch (Exception &exception) {
OCIO_reportException(exception);
}
return NULL;
}
void OCIOImpl::OCIO_PackedImageDescRelease(OCIO_PackedImageDesc *id)
{
OBJECT_GUARDED_DELETE((PackedImageDesc *)id, PackedImageDesc);
}
OCIO_GroupTransformRcPtr *OCIOImpl::createGroupTransform(void)
{
GroupTransformRcPtr *gt = OBJECT_GUARDED_NEW(GroupTransformRcPtr);
*gt = GroupTransform::Create();
return (OCIO_GroupTransformRcPtr *)gt;
}
void OCIOImpl::groupTransformSetDirection(OCIO_GroupTransformRcPtr *gt, const bool forward)
{
TransformDirection dir = forward ? TRANSFORM_DIR_FORWARD : TRANSFORM_DIR_INVERSE;
(*(GroupTransformRcPtr *)gt)->setDirection(dir);
}
void OCIOImpl::groupTransformPushBack(OCIO_GroupTransformRcPtr *gt, OCIO_ConstTransformRcPtr *tr)
{
(*(GroupTransformRcPtr *)gt)->push_back(*(ConstTransformRcPtr *)tr);
}
void OCIOImpl::groupTransformRelease(OCIO_GroupTransformRcPtr *gt)
{
OBJECT_GUARDED_DELETE((GroupTransformRcPtr *)gt, GroupTransformRcPtr);
}
OCIO_ColorSpaceTransformRcPtr *OCIOImpl::createColorSpaceTransform(void)
{
ColorSpaceTransformRcPtr *ct = OBJECT_GUARDED_NEW(ColorSpaceTransformRcPtr);
*ct = ColorSpaceTransform::Create();
(*ct)->setDirection(TRANSFORM_DIR_FORWARD);
return (OCIO_ColorSpaceTransformRcPtr *)ct;
}
void OCIOImpl::colorSpaceTransformSetSrc(OCIO_ColorSpaceTransformRcPtr *ct, const char *name)
{
(*(ColorSpaceTransformRcPtr *)ct)->setSrc(name);
}
void OCIOImpl::colorSpaceTransformRelease(OCIO_ColorSpaceTransformRcPtr *ct)
{
OBJECT_GUARDED_DELETE((ColorSpaceTransformRcPtr *)ct, ColorSpaceTransformRcPtr);
}
OCIO_ExponentTransformRcPtr *OCIOImpl::createExponentTransform(void)
{
ExponentTransformRcPtr *et = OBJECT_GUARDED_NEW(ExponentTransformRcPtr);
*et = ExponentTransform::Create();
return (OCIO_ExponentTransformRcPtr *)et;
}
void OCIOImpl::exponentTransformSetValue(OCIO_ExponentTransformRcPtr *et, const float *exponent)
{
(*(ExponentTransformRcPtr *)et)->setValue(exponent);
}
void OCIOImpl::exponentTransformRelease(OCIO_ExponentTransformRcPtr *et)
{
OBJECT_GUARDED_DELETE((ExponentTransformRcPtr *)et, ExponentTransformRcPtr);
}
OCIO_MatrixTransformRcPtr *OCIOImpl::createMatrixTransform(void)
{
MatrixTransformRcPtr *mt = OBJECT_GUARDED_NEW(MatrixTransformRcPtr);
*mt = MatrixTransform::Create();
return (OCIO_MatrixTransformRcPtr *)mt;
}
void OCIOImpl::matrixTransformSetValue(OCIO_MatrixTransformRcPtr *mt,
const float *m44,
const float *offset4)
{
(*(MatrixTransformRcPtr *)mt)->setValue(m44, offset4);
}
void OCIOImpl::matrixTransformRelease(OCIO_MatrixTransformRcPtr *mt)
{
OBJECT_GUARDED_DELETE((MatrixTransformRcPtr *)mt, MatrixTransformRcPtr);
}
void OCIOImpl::matrixTransformScale(float *m44, float *offset4, const float *scale4f)
{
MatrixTransform::Scale(m44, offset4, scale4f);
}
const char *OCIOImpl::getVersionString(void)
{
return GetVersion();
}
int OCIOImpl::getVersionHex(void)
{
return GetVersionHex();
}
| 25,528 | 9,014 |
/*
* Copyright (c) 2014-2020, Ilya Kotov <forkotov02@ya.ru>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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 <QSettings>
#include <QApplication>
#include <QDialogButtonBox>
#if (QT_VERSION >= QT_VERSION_CHECK(5, 9, 0))
#include <qpa/qplatformtheme.h>
#endif
#include "qt5ct.h"
#include "interfacepage.h"
#include "ui_interfacepage.h"
InterfacePage::InterfacePage(QWidget *parent) :
TabPage(parent),
m_ui(new Ui::InterfacePage)
{
m_ui->setupUi(this);
m_ui->buttonLayoutComboBox->addItem("Windows", QDialogButtonBox::WinLayout);
m_ui->buttonLayoutComboBox->addItem("Mac OS X", QDialogButtonBox::MacLayout);
m_ui->buttonLayoutComboBox->addItem("KDE", QDialogButtonBox::KdeLayout);
m_ui->buttonLayoutComboBox->addItem("GNOME", QDialogButtonBox::GnomeLayout);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 9, 0))
m_ui->keyboardSchemeComboBox->addItem("Windows", QPlatformTheme::WindowsKeyboardScheme);
m_ui->keyboardSchemeComboBox->addItem("Mac OS X", QPlatformTheme::MacKeyboardScheme);
m_ui->keyboardSchemeComboBox->addItem("X11", QPlatformTheme::X11KeyboardScheme);
m_ui->keyboardSchemeComboBox->addItem("KDE", QPlatformTheme::KdeKeyboardScheme);
m_ui->keyboardSchemeComboBox->addItem("GNOME", QPlatformTheme::GnomeKeyboardScheme);
m_ui->keyboardSchemeComboBox->addItem("CDE", QPlatformTheme::CdeKeyboardScheme);
#else
m_ui->keyboardSchemeComboBox->setVisible(false);
#endif
m_ui->toolButtonStyleComboBox->addItem(tr("Only display the icon"), Qt::ToolButtonIconOnly);
m_ui->toolButtonStyleComboBox->addItem(tr("Only display the text"), Qt::ToolButtonTextOnly);
m_ui->toolButtonStyleComboBox->addItem(tr("The text appears beside the icon"), Qt::ToolButtonTextBesideIcon);
m_ui->toolButtonStyleComboBox->addItem(tr("The text appears under the icon"), Qt::ToolButtonTextUnderIcon);
m_ui->toolButtonStyleComboBox->addItem(tr("Follow the application style"), Qt::ToolButtonFollowStyle);
readSettings();
}
InterfacePage::~InterfacePage()
{
delete m_ui;
}
void InterfacePage::writeSettings()
{
QSettings settings("qt5ct", "qt5ct");
settings.beginGroup("Interface");
settings.setValue("double_click_interval", m_ui->doubleClickIntervalSpinBox->value());
settings.setValue("cursor_flash_time", m_ui->cursorFlashTimeSpinBox->value());
settings.setValue("buttonbox_layout", m_ui->buttonLayoutComboBox->currentData());
#if (QT_VERSION >= QT_VERSION_CHECK(5, 9, 0))
settings.setValue("keyboard_scheme", m_ui->keyboardSchemeComboBox->currentData());
#endif
settings.setValue("menus_have_icons", m_ui->menuIconsCheckBox->isChecked());
settings.setValue("show_shortcuts_in_context_menus", m_ui->showShortcutsInMenusCheckBox->isChecked());
settings.setValue("underline_shortcut", m_ui->shortcutUnderlineCheckBox->checkState());
settings.setValue("activate_item_on_single_click", m_ui->singleClickCheckBox->checkState());
settings.setValue("dialog_buttons_have_icons", m_ui->dialogIconsCheckBox->checkState());
settings.setValue("toolbutton_style", m_ui->toolButtonStyleComboBox->currentData());
settings.setValue("wheel_scroll_lines", m_ui->wheelScrollLinesSpinBox->value());
QStringList effects;
if(m_ui->guiEffectsCheckBox->isChecked())
effects << "General";
if(m_ui->menuEffectComboBox->currentIndex() == 1)
effects << "AnimateMenu";
else if(m_ui->menuEffectComboBox->currentIndex() == 2)
effects << "FadeMenu";
if(m_ui->comboBoxEffectComboBox->currentIndex() == 1)
effects << "AnimateCombo";
if(m_ui->toolTipEffectComboBox->currentIndex() == 1)
effects << "AnimateTooltip";
else if(m_ui->toolTipEffectComboBox->currentIndex() == 2)
effects << "FadeTooltip";
if(m_ui->toolBoxEffectComboBox->currentIndex() == 1)
effects << "AnimateToolBox";
settings.setValue("gui_effects", effects);
settings.endGroup();
}
void InterfacePage::readSettings()
{
QSettings settings("qt5ct", "qt5ct");
settings.beginGroup("Interface");
m_ui->doubleClickIntervalSpinBox->setValue(qApp->doubleClickInterval());
m_ui->cursorFlashTimeSpinBox->setValue(qApp->cursorFlashTime());
m_ui->guiEffectsCheckBox->setChecked(qApp->isEffectEnabled(Qt::UI_General));
int layout = settings.value("buttonbox_layout", style()->styleHint(QStyle::SH_DialogButtonLayout)).toInt();
int index = m_ui->buttonLayoutComboBox->findData(layout);
if(index >= 0)
m_ui->buttonLayoutComboBox->setCurrentIndex(index);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 9, 0))
int scheme = settings.value("keyboard_scheme", QPlatformTheme::X11KeyboardScheme).toInt();
index = m_ui->keyboardSchemeComboBox->findData(scheme);
if(index >= 0)
m_ui->keyboardSchemeComboBox->setCurrentIndex(index);
#endif
if(qApp->isEffectEnabled(Qt::UI_AnimateMenu))
m_ui->menuEffectComboBox->setCurrentIndex(1);
else if(qApp->isEffectEnabled(Qt::UI_FadeMenu))
m_ui->menuEffectComboBox->setCurrentIndex(2);
if(qApp->isEffectEnabled(Qt::UI_AnimateCombo))
m_ui->comboBoxEffectComboBox->setCurrentIndex(1);
if(qApp->isEffectEnabled(Qt::UI_AnimateTooltip))
m_ui->toolTipEffectComboBox->setCurrentIndex(1);
else if(qApp->isEffectEnabled(Qt::UI_FadeTooltip))
m_ui->toolTipEffectComboBox->setCurrentIndex(2);
if(qApp->isEffectEnabled(Qt::UI_AnimateToolBox))
m_ui->toolBoxEffectComboBox->setCurrentIndex(1);
m_ui->singleClickCheckBox->setCheckState(Qt::CheckState(settings.value("activate_item_on_single_click", Qt::PartiallyChecked).toInt()));
m_ui->dialogIconsCheckBox->setCheckState(Qt::CheckState(settings.value("dialog_buttons_have_icons", Qt::PartiallyChecked).toInt()));
m_ui->shortcutUnderlineCheckBox->setCheckState(Qt::CheckState(settings.value("underline_shortcut", Qt::PartiallyChecked).toInt()));
m_ui->menuIconsCheckBox->setChecked(!qApp->testAttribute(Qt::AA_DontShowIconsInMenus));
m_ui->showShortcutsInMenusCheckBox->setChecked(settings.value("show_shortcuts_in_context_menus", true).toBool());
#if (QT_VERSION < QT_VERSION_CHECK(5, 9, 0))
m_ui->showShortcutsInMenusCheckBox->setVisible(false);
#endif
int toolbarStyle = settings.value("toolbutton_style", Qt::ToolButtonFollowStyle).toInt();
index = m_ui->toolButtonStyleComboBox->findData(toolbarStyle);
if(index >= 0)
m_ui->toolButtonStyleComboBox->setCurrentIndex(index);
m_ui->wheelScrollLinesSpinBox->setValue(settings.value("wheel_scroll_lines", 3).toInt());
settings.endGroup();
}
| 7,863 | 2,644 |
//=========================================================================
// Copyright (C) 2012 The Elastos 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 "elastos/droid/server/pm/dex/DexFileVerifier.h"
#include <zlib.h>
namespace Elastos {
namespace Droid {
namespace Server {
namespace Pm {
namespace Dex {
static uint32_t MapTypeToBitMask(uint32_t map_type)
{
switch (map_type) {
case DexFile::kDexTypeHeaderItem: return 1 << 0;
case DexFile::kDexTypeStringIdItem: return 1 << 1;
case DexFile::kDexTypeTypeIdItem: return 1 << 2;
case DexFile::kDexTypeProtoIdItem: return 1 << 3;
case DexFile::kDexTypeFieldIdItem: return 1 << 4;
case DexFile::kDexTypeMethodIdItem: return 1 << 5;
case DexFile::kDexTypeClassDefItem: return 1 << 6;
case DexFile::kDexTypeMapList: return 1 << 7;
case DexFile::kDexTypeTypeList: return 1 << 8;
case DexFile::kDexTypeAnnotationSetRefList: return 1 << 9;
case DexFile::kDexTypeAnnotationSetItem: return 1 << 10;
case DexFile::kDexTypeClassDataItem: return 1 << 11;
case DexFile::kDexTypeCodeItem: return 1 << 12;
case DexFile::kDexTypeStringDataItem: return 1 << 13;
case DexFile::kDexTypeDebugInfoItem: return 1 << 14;
case DexFile::kDexTypeAnnotationItem: return 1 << 15;
case DexFile::kDexTypeEncodedArrayItem: return 1 << 16;
case DexFile::kDexTypeAnnotationsDirectoryItem: return 1 << 17;
}
return 0;
}
static bool IsDataSectionType(uint32_t map_type)
{
switch (map_type) {
case DexFile::kDexTypeHeaderItem:
case DexFile::kDexTypeStringIdItem:
case DexFile::kDexTypeTypeIdItem:
case DexFile::kDexTypeProtoIdItem:
case DexFile::kDexTypeFieldIdItem:
case DexFile::kDexTypeMethodIdItem:
case DexFile::kDexTypeClassDefItem:
return FALSE;
}
return TRUE;
}
Boolean DexFileVerifier::Verify(
/* [in] */ const DexFile* dex_file,
/* [in] */ const Byte* begin,
/* [in] */ size_t size,
/* [in] */ const char* location,
/* [out] */ String* error_msg)
{
AutoPtr<DexFileVerifier> verifier = new DexFileVerifier(dex_file, begin, size, location);
if (!verifier->Verify()) {
*error_msg = verifier->FailureReason();
return FALSE;
}
return TRUE;
}
Boolean DexFileVerifier::CheckListSize(
/* [in] */ const void* start,
/* [in] */ size_t count,
/* [in] */ size_t elem_size,
/* [in] */ const char* label)
{
// Check that size is not 0.
assert(elem_size != 0U);
const byte* range_start = reinterpret_cast<const byte*>(start);
const byte* file_start = reinterpret_cast<const byte*>(mBegin);
// Check for overflow.
uintptr_t max = 0 - 1;
size_t available_bytes_till_end_of_mem = max - reinterpret_cast<uintptr_t>(start);
size_t max_count = available_bytes_till_end_of_mem / elem_size;
if (max_count < count) {
ErrorStringPrintf("Overflow in range for %s: %zx for %zu@%zu", label,
static_cast<size_t>(range_start - file_start),
count, elem_size);
return FALSE;
}
const byte* range_end = range_start + count * elem_size;
const byte* file_end = file_start + mSize;
if ((range_start < file_start) || (range_end > file_end)) {
// Note: these two tests are enough as we make sure above that there's no overflow.
ErrorStringPrintf("Bad range for %s: %zx to %zx", label,
static_cast<size_t>(range_start - file_start),
static_cast<size_t>(range_end - file_start));
return FALSE;
}
return TRUE;
}
Boolean DexFileVerifier::CheckValidOffsetAndSize(
/* [in] */ uint32_t offset,
/* [in] */ uint32_t size,
/* [in] */ const char* label)
{
if (size == 0) {
if (offset != 0) {
ErrorStringPrintf("Offset(%d) should be zero when size is zero for %s.", offset, label);
return FALSE;
}
}
if (mSize <= offset) {
ErrorStringPrintf("Offset(%d) should be within file size(%zu) for %s.", offset, mSize, label);
return FALSE;
}
return TRUE;
}
Boolean DexFileVerifier::CheckHeader()
{
// Check file size from the header.
uint32_t expected_size = mHeader->mFileSize;
if (mSize != expected_size) {
ErrorStringPrintf("Bad file size (%zd, expected %ud)", mSize, expected_size);
return FALSE;
}
// Compute and verify the checksum in the header.
uint32_t adler_checksum = adler32(0L, Z_NULL, 0);
const uint32_t non_sum = sizeof(mHeader->mMagic) + sizeof(mHeader->mChecksum);
const byte* non_sum_ptr = reinterpret_cast<const byte*>(mHeader) + non_sum;
adler_checksum = adler32(adler_checksum, non_sum_ptr, expected_size - non_sum);
if (adler_checksum != mHeader->mChecksum) {
ErrorStringPrintf("Bad checksum (%08x, expected %08x)", adler_checksum, mHeader->mChecksum);
return FALSE;
}
// Check the contents of the header.
if (mHeader->mEndianTag != DexFile::sDexEndianConstant) {
ErrorStringPrintf("Unexpected endian_tag: %x", mHeader->mEndianTag);
return FALSE;
}
if (mHeader->mHeaderSize != sizeof(DexFile::Header)) {
ErrorStringPrintf("Bad header size: %ud", mHeader->mHeaderSize);
return FALSE;
}
// Check that all offsets are inside the file.
Boolean result =
CheckValidOffsetAndSize(mHeader->mLinkOff, mHeader->mLinkSize, "link") &&
CheckValidOffsetAndSize(mHeader->mMapOff, mHeader->mMapOff, "map") &&
CheckValidOffsetAndSize(mHeader->mStringIdsOff, mHeader->mStringIdsSize, "string-ids") &&
CheckValidOffsetAndSize(mHeader->mTypeIdsOff, mHeader->mTypeIdsSize, "type-ids") &&
CheckValidOffsetAndSize(mHeader->mProtoIdsOff, mHeader->mProtoIdsSize, "proto-ids") &&
CheckValidOffsetAndSize(mHeader->mFieldIdsOff, mHeader->mFieldIdsSize, "field-ids") &&
CheckValidOffsetAndSize(mHeader->mMethodIdsOff, mHeader->mMethodIdsSize, "method-ids") &&
CheckValidOffsetAndSize(mHeader->mClassDefsOff, mHeader->mClassDefsSize, "class-defs") &&
CheckValidOffsetAndSize(mHeader->mDataOff, mHeader->mDataSize, "data");
return result;
}
Boolean DexFileVerifier::CheckMap()
{
const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(mBegin +
mHeader->mMapOff);
// Check that map list content is available.
if (!CheckListSize(map, 1, sizeof(DexFile::MapList), "maplist content")) {
return FALSE;
}
const DexFile::MapItem* item = map->mList;
uint32_t count = map->mSize;
uint32_t last_offset = 0;
uint32_t data_item_count = 0;
uint32_t data_items_left = mHeader->mDataSize;
uint32_t used_bits = 0;
// Sanity check the size of the map list.
if (!CheckListSize(item, count, sizeof(DexFile::MapItem), "map size")) {
return FALSE;
}
// Check the items listed in the map.
for (uint32_t i = 0; i < count; i++) {
if (last_offset >= item->mOffset && i != 0) {
ErrorStringPrintf("Out of order map item: %x then %x", last_offset, item->mOffset);
return FALSE;
}
if (item->mOffset >= mHeader->mFileSize) {
ErrorStringPrintf("Map item after end of file: %x, size %x",
item->mOffset, mHeader->mFileSize);
return FALSE;
}
if (IsDataSectionType(item->mType)) {
uint32_t icount = item->mSize;
if (icount > data_items_left) {
ErrorStringPrintf("Too many items in data section: %ud", data_item_count + icount);
return FALSE;
}
data_items_left -= icount;
data_item_count += icount;
}
uint32_t bit = MapTypeToBitMask(item->mType);
if (bit == 0) {
ErrorStringPrintf("Unknown map section type %x", item->mType);
return FALSE;
}
if ((used_bits & bit) != 0) {
ErrorStringPrintf("Duplicate map section of type %x", item->mType);
return FALSE;
}
used_bits |= bit;
last_offset = item->mOffset;
item++;
}
// Check for missing sections in the map.
if ((used_bits & MapTypeToBitMask(DexFile::kDexTypeHeaderItem)) == 0) {
ErrorStringPrintf("Map is missing header entry");
return FALSE;
}
if ((used_bits & MapTypeToBitMask(DexFile::kDexTypeMapList)) == 0) {
ErrorStringPrintf("Map is missing map_list entry");
return FALSE;
}
if ((used_bits & MapTypeToBitMask(DexFile::kDexTypeStringIdItem)) == 0 &&
((mHeader->mStringIdsOff != 0) || (mHeader->mStringIdsSize != 0))) {
ErrorStringPrintf("Map is missing string_ids entry");
return FALSE;
}
if ((used_bits & MapTypeToBitMask(DexFile::kDexTypeTypeIdItem)) == 0 &&
((mHeader->mTypeIdsOff != 0) || (mHeader->mTypeIdsSize != 0))) {
ErrorStringPrintf("Map is missing type_ids entry");
return FALSE;
}
if ((used_bits & MapTypeToBitMask(DexFile::kDexTypeProtoIdItem)) == 0 &&
((mHeader->mProtoIdsOff != 0) || (mHeader->mProtoIdsSize != 0))) {
ErrorStringPrintf("Map is missing proto_ids entry");
return FALSE;
}
if ((used_bits & MapTypeToBitMask(DexFile::kDexTypeFieldIdItem)) == 0 &&
((mHeader->mFieldIdsOff != 0) || (mHeader->mFieldIdsSize != 0))) {
ErrorStringPrintf("Map is missing field_ids entry");
return FALSE;
}
if ((used_bits & MapTypeToBitMask(DexFile::kDexTypeMethodIdItem)) == 0 &&
((mHeader->mMethodIdsOff != 0) || (mHeader->mMethodIdsSize != 0))) {
ErrorStringPrintf("Map is missing method_ids entry");
return FALSE;
}
if ((used_bits & MapTypeToBitMask(DexFile::kDexTypeClassDefItem)) == 0 &&
((mHeader->mClassDefsOff != 0) || (mHeader->mClassDefsSize != 0))) {
ErrorStringPrintf("Map is missing class_defs entry");
return FALSE;
}
return TRUE;
}
Boolean DexFileVerifier::CheckPadding(
/* [in] */ size_t offset,
/* [in] */ uint32_t aligned_offset)
{
if (offset < aligned_offset) {
if (!CheckListSize(mBegin + offset, aligned_offset - offset, sizeof(byte), "section")) {
return FALSE;
}
while (offset < aligned_offset) {
if (*mPtr != '\0') {
ErrorStringPrintf("Non-zero padding %x before section start at %zx", *mPtr, offset);
return FALSE;
}
mPtr++;
offset++;
}
}
return TRUE;
}
Boolean DexFileVerifier::CheckIntraSectionIterate(
/* [in] */ size_t offset,
/* [in] */ uint32_t section_count,
/* [in] */ uint16_t type)
{
// Get the right alignment mask for the type of section.
size_t alignment_mask;
switch (type) {
case DexFile::kDexTypeClassDataItem:
case DexFile::kDexTypeStringDataItem:
case DexFile::kDexTypeDebugInfoItem:
case DexFile::kDexTypeAnnotationItem:
case DexFile::kDexTypeEncodedArrayItem:
alignment_mask = sizeof(uint8_t) - 1;
break;
default:
alignment_mask = sizeof(uint32_t) - 1;
break;
}
// // Iterate through the items in the section.
// for (uint32_t i = 0; i < section_count; i++) {
// size_t aligned_offset = (offset + alignment_mask) & ~alignment_mask;
// // Check the padding between items.
// if (!CheckPadding(offset, aligned_offset)) {
// return FALSE;
// }
// // Check depending on the section type.
// switch (type) {
// case DexFile::kDexTypeStringIdItem: {
// if (!CheckListSize(mPtr, 1, sizeof(DexFile::StringId), "string_ids")) {
// return FALSE;
// }
// mPtr += sizeof(DexFile::StringId);
// break;
// }
// case DexFile::kDexTypeTypeIdItem: {
// if (!CheckListSize(mPtr, 1, sizeof(DexFile::TypeId), "type_ids")) {
// return FALSE;
// }
// mPtr += sizeof(DexFile::TypeId);
// break;
// }
// case DexFile::kDexTypeProtoIdItem: {
// if (!CheckListSize(mPtr, 1, sizeof(DexFile::ProtoId), "proto_ids")) {
// return FALSE;
// }
// mPtr += sizeof(DexFile::ProtoId);
// break;
// }
// case DexFile::kDexTypeFieldIdItem: {
// if (!CheckListSize(mPtr, 1, sizeof(DexFile::FieldId), "field_ids")) {
// return FALSE;
// }
// mPtr += sizeof(DexFile::FieldId);
// break;
// }
// case DexFile::kDexTypeMethodIdItem: {
// if (!CheckListSize(mPtr, 1, sizeof(DexFile::MethodId), "method_ids")) {
// return FALSE;
// }
// mPtr += sizeof(DexFile::MethodId);
// break;
// }
// case DexFile::kDexTypeClassDefItem: {
// if (!CheckListSize(mPtr, 1, sizeof(DexFile::ClassDef), "class_defs")) {
// return FALSE;
// }
// mPtr += sizeof(DexFile::ClassDef);
// break;
// }
// case DexFile::kDexTypeTypeList: {
// if (!CheckList(sizeof(DexFile::TypeItem), "type_list", &mPtr)) {
// return FALSE;
// }
// break;
// }
// case DexFile::kDexTypeAnnotationSetRefList: {
// if (!CheckList(sizeof(DexFile::AnnotationSetRefItem), "annotation_set_ref_list", &mPtr)) {
// return FALSE;
// }
// break;
// }
// case DexFile::kDexTypeAnnotationSetItem: {
// if (!CheckList(sizeof(uint32_t), "annotation_set_item", &mPtr)) {
// return FALSE;
// }
// break;
// }
// case DexFile::kDexTypeClassDataItem: {
// if (!CheckIntraClassDataItem()) {
// return FALSE;
// }
// break;
// }
// case DexFile::kDexTypeCodeItem: {
// if (!CheckIntraCodeItem()) {
// return FALSE;
// }
// break;
// }
// case DexFile::kDexTypeStringDataItem: {
// if (!CheckIntraStringDataItem()) {
// return FALSE;
// }
// break;
// }
// case DexFile::kDexTypeDebugInfoItem: {
// if (!CheckIntraDebugInfoItem()) {
// return FALSE;
// }
// break;
// }
// case DexFile::kDexTypeAnnotationItem: {
// if (!CheckIntraAnnotationItem()) {
// return FALSE;
// }
// break;
// }
// case DexFile::kDexTypeEncodedArrayItem: {
// if (!CheckEncodedArray()) {
// return FALSE;
// }
// break;
// }
// case DexFile::kDexTypeAnnotationsDirectoryItem: {
// if (!CheckIntraAnnotationsDirectoryItem()) {
// return FALSE;
// }
// break;
// }
// default:
// ErrorStringPrintf("Unknown map item type %x", type);
// return FALSE;
// }
// if (IsDataSectionType(type)) {
// offset_to_type_map_.Put(aligned_offset, type);
// }
// aligned_offset = mPtr - begin_;
// if (aligned_offset > size_) {
// ErrorStringPrintf("Item %d at ends out of bounds", i);
// return FALSE;
// }
// offset = aligned_offset;
// }
return TRUE;
}
Boolean DexFileVerifier::CheckIntraIdSection(
/* [in] */ size_t offset,
/* [in] */ uint32_t count,
/* [in] */ uint16_t type)
{
uint32_t expected_offset;
uint32_t expected_size;
// Get the expected offset and size from the header.
switch (type) {
case DexFile::kDexTypeStringIdItem:
expected_offset = mHeader->mStringIdsOff;
expected_size = mHeader->mStringIdsSize;
break;
case DexFile::kDexTypeTypeIdItem:
expected_offset = mHeader->mTypeIdsOff;
expected_size = mHeader->mTypeIdsSize;
break;
case DexFile::kDexTypeProtoIdItem:
expected_offset = mHeader->mProtoIdsOff;
expected_size = mHeader->mProtoIdsSize;
break;
case DexFile::kDexTypeFieldIdItem:
expected_offset = mHeader->mFieldIdsOff;
expected_size = mHeader->mFieldIdsSize;
break;
case DexFile::kDexTypeMethodIdItem:
expected_offset = mHeader->mMethodIdsOff;
expected_size = mHeader->mMethodIdsSize;
break;
case DexFile::kDexTypeClassDefItem:
expected_offset = mHeader->mClassDefsOff;
expected_size = mHeader->mClassDefsSize;
break;
default:
ErrorStringPrintf("Bad type for id section: %x", type);
return FALSE;
}
// Check that the offset and size are what were expected from the header.
if (offset != expected_offset) {
ErrorStringPrintf("Bad offset for section: got %zx, expected %x", offset, expected_offset);
return FALSE;
}
if (count != expected_size) {
ErrorStringPrintf("Bad size for section: got %x, expected %x", count, expected_size);
return FALSE;
}
return CheckIntraSectionIterate(offset, count, type);
}
Boolean DexFileVerifier::CheckIntraDataSection(
/* [in] */ size_t offset,
/* [in] */ uint32_t count,
/* [in] */ uint16_t type)
{
size_t data_start = mHeader->mDataOff;
size_t data_end = data_start + mHeader->mDataSize;
// Sanity check the offset of the section.
if ((offset < data_start) || (offset > data_end)) {
ErrorStringPrintf("Bad offset for data subsection: %zx", offset);
return false;
}
if (!CheckIntraSectionIterate(offset, count, type)) {
return FALSE;
}
size_t next_offset = mPtr - mBegin;
if (next_offset > data_end) {
ErrorStringPrintf("Out-of-bounds end of data subsection: %zx", next_offset);
return FALSE;
}
return TRUE;
}
Boolean DexFileVerifier::CheckIntraSection()
{
const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(mBegin + mHeader->mMapOff);
const DexFile::MapItem* item = map->mList;
uint32_t count = map->mSize;
size_t offset = 0;
mPtr = mBegin;
// Check the items listed in the map.
while (count--) {
uint32_t section_offset = item->mOffset;
uint32_t section_count = item->mSize;
uint16_t type = item->mType;
// Check for padding and overlap between items.
if (!CheckPadding(offset, section_offset)) {
return FALSE;
}
else if (offset > section_offset) {
ErrorStringPrintf("Section overlap or out-of-order map: %zx, %x", offset, section_offset);
return FALSE;
}
// Check each item based on its type.
switch (type) {
case DexFile::kDexTypeHeaderItem:
if (section_count != 1) {
ErrorStringPrintf("Multiple header items");
return FALSE;
}
if (section_offset != 0) {
ErrorStringPrintf("Header at %x, not at start of file", section_offset);
return FALSE;
}
mPtr = mBegin + mHeader->mHeaderSize;
offset = mHeader->mHeaderSize;
break;
case DexFile::kDexTypeStringIdItem:
case DexFile::kDexTypeTypeIdItem:
case DexFile::kDexTypeProtoIdItem:
case DexFile::kDexTypeFieldIdItem:
case DexFile::kDexTypeMethodIdItem:
case DexFile::kDexTypeClassDefItem:
if (!CheckIntraIdSection(section_offset, section_count, type)) {
return FALSE;
}
offset = mPtr - mBegin;
break;
case DexFile::kDexTypeMapList:
if (section_count != 1) {
ErrorStringPrintf("Multiple map list items");
return FALSE;
}
if (section_offset != mHeader->mMapOff) {
ErrorStringPrintf("Map not at header-defined offset: %x, expected %x",
section_offset, mHeader->mMapOff);
return FALSE;
}
mPtr += sizeof(uint32_t) + (map->mSize * sizeof(DexFile::MapItem));
offset = section_offset + sizeof(uint32_t) + (map->mSize * sizeof(DexFile::MapItem));
break;
case DexFile::kDexTypeTypeList:
case DexFile::kDexTypeAnnotationSetRefList:
case DexFile::kDexTypeAnnotationSetItem:
case DexFile::kDexTypeClassDataItem:
case DexFile::kDexTypeCodeItem:
case DexFile::kDexTypeStringDataItem:
case DexFile::kDexTypeDebugInfoItem:
case DexFile::kDexTypeAnnotationItem:
case DexFile::kDexTypeEncodedArrayItem:
case DexFile::kDexTypeAnnotationsDirectoryItem:
if (!CheckIntraDataSection(section_offset, section_count, type)) {
return FALSE;
}
offset = mPtr - mBegin;
break;
default:
ErrorStringPrintf("Unknown map item type %x", type);
return FALSE;
}
item++;
}
return TRUE;
}
Boolean DexFileVerifier::CheckInterSection()
{
const DexFile::MapList* map = reinterpret_cast<const DexFile::MapList*>(mBegin + mHeader->mMapOff);
const DexFile::MapItem* item = map->mList;
uint32_t count = map->mSize;
// Cross check the items listed in the map.
while (count--) {
uint32_t section_offset = item->mOffset;
uint32_t section_count = item->mSize;
uint16_t type = item->mType;
switch (type) {
case DexFile::kDexTypeHeaderItem:
case DexFile::kDexTypeMapList:
case DexFile::kDexTypeTypeList:
case DexFile::kDexTypeCodeItem:
case DexFile::kDexTypeStringDataItem:
case DexFile::kDexTypeDebugInfoItem:
case DexFile::kDexTypeAnnotationItem:
case DexFile::kDexTypeEncodedArrayItem:
break;
case DexFile::kDexTypeStringIdItem:
case DexFile::kDexTypeTypeIdItem:
case DexFile::kDexTypeProtoIdItem:
case DexFile::kDexTypeFieldIdItem:
case DexFile::kDexTypeMethodIdItem:
case DexFile::kDexTypeClassDefItem:
case DexFile::kDexTypeAnnotationSetRefList:
case DexFile::kDexTypeAnnotationSetItem:
case DexFile::kDexTypeClassDataItem:
case DexFile::kDexTypeAnnotationsDirectoryItem: {
// TODO:
// if (!CheckInterSectionIterate(section_offset, section_count, type)) {
// return FALSE;
// }
break;
}
default:
ErrorStringPrintf("Unknown map item type %x", type);
return FALSE;
}
item++;
}
return TRUE;
}
Boolean DexFileVerifier::Verify()
{
// Check the header.
if (!CheckHeader()) {
return FALSE;
}
// Check the map section.
if (!CheckMap()) {
return FALSE;
}
// Check structure within remaining sections.
if (!CheckIntraSection()) {
return FALSE;
}
// Check references from one section to another.
if (!CheckInterSection()) {
return FALSE;
}
return TRUE;
}
void DexFileVerifier::ErrorStringPrintf(const char* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
mFailureReason = "";
mFailureReason.AppendFormat("Failure to verify dex file '%s': ", mLocation);
mFailureReason.AppendFormat(fmt, ap);
va_end(ap);
}
} // namespace Dex
} // namespace Pm
} // namespace Server
} // namespace Droid
} // namespace Elastos
| 25,820 | 7,888 |
/*++
Copyright (c) 1991-2001 Microsoft Corporation
Module Name:
fatsachk.cxx
--*/
#include <pch.cxx>
#include "bitvect.hxx"
#include "error.hxx"
#include "rtmsg.h"
#include "ifsentry.hxx"
// Timeinfo is full of windows stuff.
#if !defined( _AUTOCHECK_ ) && !defined( _SETUP_LOADER_ ) && !defined( _EFICHECK_ )
#include "timeinfo.hxx"
#endif
#define UCHAR_SP ' '
typedef struct _VISIT_DIR *PVISIT_DIR;
typedef struct _VISIT_DIR {
PVISIT_DIR Next;
PWSTRING Path;
ULONG Cluster;
} VISIT_DIR;
#if !defined( _EFICHECK_ )
extern "C" {
#include <stdio.h>
}
#endif
extern VOID InsertSeparators(
LPCWSTR OutWNumber,
char * InANumber,
ULONG Width
);
VOID
dofmsg(
IN PMESSAGE Message,
IN OUT PBOOLEAN NeedErrorsMessage
)
{
if (*NeedErrorsMessage) {
Message->Set(MSG_CORRECTIONS_WILL_NOT_BE_WRITTEN, NORMAL_MESSAGE, TEXT_MESSAGE);
Message->Display();
*NeedErrorsMessage = FALSE;
}
}
BOOLEAN
CheckAndFixFileName(
PVOID DirEntry,
PBOOLEAN Changes
)
{
PUCHAR p = (PUCHAR)DirEntry;
#if 1
//
// Should not correct case error within file name because
// different language build translates differently. On a
// dual boot machine containing build of two different languages,
// the chkdsk from one build may not like what the second build
// put onto the disk.
//
return TRUE;
#else
memcpy(backup_copy, p, 11);
first_char_replaced = (0x5 == p[0]);
if (first_char_replaced)
p[0] = 0xe5;
ntstatus = RtlOemToUnicodeN(unicode_string,
sizeof(unicode_string),
&unicode_string_length,
(PCHAR)p,
11);
if (!NT_SUCCESS(ntstatus)) {
DebugPrintTrace(("UFAT: Error in RtlOemToUnicodeN, 0x%x\n", ntstatus));
memcpy(p, backup_copy, 11);
return FALSE;
}
ntstatus = RtlUpcaseUnicodeToOemN((PCHAR)p,
11,
NULL,
unicode_string,
unicode_string_length);
if (!NT_SUCCESS(ntstatus)) {
DebugPrintTrace(("UFAT: Error in RtlUpcaseUnicodeToOemN, 0x%x\n", ntstatus));
memcpy(p, backup_copy, 11);
return FALSE;
}
if (first_char_replaced) {
if (0xe5 == p[0]) {
p[0] = 0x5;
} else {
DebugPrintTrace(("UFAT: First byte changed to 0x%x unexpectedly\n", p[0]));
memcpy(p, backup_copy, 11);
return FALSE;
}
}
*Changes = (memcmp(p, backup_copy, 11) != 0);
return TRUE;
#endif
}
BOOLEAN
IsFileNameMatch(
PFATDIR Dir,
UCHAR FatType,
ULONG CurrentIndex,
ULONG MatchingIndexCount,
PULONG MatchingIndexArray
)
{
ULONG j;
for (j = 0; j < MatchingIndexCount; j++) {
FAT_DIRENT fd;
ULONG indx = MatchingIndexArray[j];
if (!fd.Initialize(Dir->GetDirEntry(indx), FatType) ||
fd.IsVolumeLabel()) {
continue;
}
if (!memcmp(Dir->GetDirEntry(indx), Dir->GetDirEntry(CurrentIndex), 11)) {
return TRUE; // there is a match
}
}
return FALSE; // no match
}
BOOLEAN
RenameFileName(
PULONG Positions,
PVOID DirEntry
)
{
PUCHAR p = (PUCHAR)DirEntry;
INT i;
if (*Positions == 0) { // if first rename
// find out the first char in the extension that is real
for (i = 10; i > 7; i--)
if (p[i] != UCHAR_SP)
break;
if (i >= 7 && i < 10) { // fill the unused extension space with dashes
for (i++; i < 10; i++)
p[i] = '-';
}
*Positions = 1;
if (p[10] != '0') {
p[10] = '0'; // the last char of the extension gets a zero
return TRUE;
}
}
// extension chars are all in use now
// check to see if renaming is already in progress
for (i=10; i>=0; i--) {
if (!(*Positions & (1 << (10-i)))) {
*Positions |= (1 << (10-i));
if (p[i] != '0') {
p[i] = '0';
return TRUE;
}
}
if (p[i] >= '0' && p[i] < '9') {
p[i]++;
return TRUE;
} else if (p[i] == '9') {
p[i] = '0';
}
}
// if we get here that means we have exhausted all possible name
// shouldn't be as there are more combination than the max number
// of files that can be in a FAT directory (65536)
return FALSE;
}
BOOLEAN
PushVisitDir(
IN OUT PVISIT_DIR *VisitDirStack,
IN ULONG Cluster,
IN PWSTRING DirectoryPath
)
{
PVISIT_DIR visit_dir;
visit_dir = (PVISIT_DIR)MALLOC( sizeof( VISIT_DIR ) );
if( visit_dir == NULL ){
return FALSE;
}
visit_dir->Path = DirectoryPath;
visit_dir->Cluster = Cluster;
visit_dir->Next = *VisitDirStack;
*VisitDirStack = visit_dir;
return TRUE;
}
BOOLEAN
PopVisitDir(
IN OUT PVISIT_DIR *VisitDirStack,
OUT PULONG Cluster OPTIONAL,
OUT PWSTRING *DirectoryPath OPTIONAL
)
{
PVISIT_DIR visit_dir;
visit_dir = *VisitDirStack;
if( visit_dir == NULL ){
return FALSE;
}
*VisitDirStack = visit_dir->Next;
if( ARGUMENT_PRESENT( Cluster ) ){
*Cluster = visit_dir->Cluster;
}
if( ARGUMENT_PRESENT( DirectoryPath ) ){
*DirectoryPath = visit_dir->Path;
}
FREE( visit_dir );
return TRUE;
}
STATIC VOID
EraseAssociatedLongName(
PFATDIR Dir,
INT FirstLongEntry,
INT ShortEntry
)
{
FAT_DIRENT dirent;
for (int j = FirstLongEntry; j < ShortEntry; ++j) {
dirent.Initialize(Dir->GetDirEntry(j));
dirent.SetErased();
}
}
STATIC BOOLEAN
IsString8Dot3(
PCWSTRING s
)
/*++
Routine Description:
This routine is used to ensure that lfn's legally correspond
to their short names. The given string is examined to see if it
is a legal fat 8.3 name.
Arguments:
s -- lfn to examine.
Return Value:
TRUE - The string is a legal 8.3 name.
FALSE - Not legal.
--*/
{
USHORT i;
BOOLEAN extension_present = FALSE;
WCHAR c;
//
// The name can't be more than 12 characters (including a single dot).
//
if (s->QueryChCount() > 12) {
return FALSE;
}
for (i = 0; i < s->QueryChCount(); ++i) {
c = s->QueryChAt(i);
#if 0
if (!FsRtlIsAnsiCharLegalFat(c, FALSE)) {
return FALSE;
}
#endif
if (c == '.') {
//
// We stepped onto a period. We require the following things:
//
// - it can't be the first character
// - there can be only one
// - there can't be more than 3 characters following it
// - the previous character can't be a space
//
if (i == 0 ||
extension_present ||
s->QueryChCount() - (i + 1) > 3 ||
s->QueryChAt(i - 1) == ' ') {
return FALSE;
}
extension_present = TRUE;
}
//
// The base part of the name can't be more than 8 characters long.
//
if (i >= 8 && !extension_present) {
return FALSE;
}
}
//
// The name cannot end in a space or a period.
//
if (c == ' ' || c == '.') {
return FALSE;
}
return TRUE;
}
STATIC PMESSAGE _pvfMessage = NULL;
STATIC BOOLEAN _Verbose = FALSE;
VOID
FreeSpaceInBitmap(
IN ULONG StartingCluster,
IN PCFAT Fat,
IN OUT PBITVECTOR FatBitMap
);
BOOLEAN
FAT_SA::VerifyAndFix(
IN FIX_LEVEL FixLevel,
IN OUT PMESSAGE Message,
IN ULONG Flags,
IN ULONG LogFileSize,
OUT PULONG ExitStatus,
IN PCWSTRING DriveLetter
)
/*++
Routine Description:
This routine verifies the FAT superarea and if neccessary fixes
it to a correct state.
Arguments:
FixLevel - Supplies the level of fixes that may be performed on
the disk.
Message - Supplies an outlet for messages.
Flags - Supplies flags to control the behavior of chkdsk
(see ulib\inc\ifsserv.hxx for details)
LogFileSize - ignored
ExitStatus - Returns an indication of the result of the check
DriveLetter - For autocheck, supplies the letter of the volume
being checked
Return Value:
FALSE - Failure.
TRUE - Success.
--*/
{
FAT_DIRENT eadent;
ULONG cluster_size;
ULONG ea_clus_num;
USHORT num_eas, save_num_eas;
PEA_INFO ea_infos;
ULONG cluster_count;
HMEM ea_header_mem;
EA_HEADER ea_header;
BOOLEAN changes = FALSE;
BITVECTOR fat_bitmap;
FATCHK_REPORT report;
PUSHORT p;
VOLID volid;
ULONG free_count, bad_count, total_count;
BOOLEAN fmsg;
DSTRING label;
DSTRING eafilename;
DSTRING eafilepath;
BOOLEAN tmp_bool;
ULONG tmp_ulong;
DSTRING date;
DSTRING time;
UCHAR dirty_byte, media_byte;
BOOLEAN Verbose = (BOOLEAN)(Flags & CHKDSK_VERBOSE);
BOOLEAN OnlyIfDirty = (BOOLEAN)(Flags & CHKDSK_CHECK_IF_DIRTY);
BOOLEAN EnableUpgrade = (BOOLEAN)(Flags & CHKDSK_ENABLE_UPGRADE);
BOOLEAN EnableDowngrade = (BOOLEAN)(Flags & CHKDSK_DOWNGRADE);
BOOLEAN RecoverFree = (BOOLEAN)(Flags & CHKDSK_RECOVER_FREE_SPACE);
BOOLEAN RecoverAlloc = (BOOLEAN)(Flags & CHKDSK_RECOVER_ALLOC_SPACE);
_pvfMessage = Message;
_Verbose = Verbose;
memset(&report, 0, sizeof(FATCHK_REPORT));
if (NULL == ExitStatus) {
ExitStatus = &report.ExitStatus;
}
report.ExitStatus = CHKDSK_EXIT_SUCCESS;
*ExitStatus = CHKDSK_EXIT_COULD_NOT_CHK;
fmsg = TRUE;
if (FixLevel != CheckOnly) {
fmsg = FALSE;
}
if (EnableUpgrade || EnableDowngrade) {
Message->Set(MSG_CHK_CANNOT_UPGRADE_DOWNGRADE_FAT);
Message->Display();
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
//
// Check to see if the dirty bit is set.
//
dirty_byte = QueryVolumeFlags();
if (OnlyIfDirty) {
if ((dirty_byte &
(FAT_BPB_RESERVED_DIRTY | FAT_BPB_RESERVED_TEST_SURFACE)) == 0) {
Message->Set(MSG_CHK_VOLUME_CLEAN);
Message->Display();
Message->SetLoggingEnabled(FALSE);
*ExitStatus = CHKDSK_EXIT_SUCCESS;
_Verbose = FALSE;
_pvfMessage = NULL;
return TRUE;
}
// We need to re-initialize the fatsa object to include the whole
// super area
if (!Initialize(_drive, Message, TRUE)) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
*ExitStatus = CHKDSK_EXIT_COULD_NOT_CHK;
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
if (!Read(Message)) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
*ExitStatus = CHKDSK_EXIT_COULD_NOT_CHK;
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
// If the second bit of the dirty byte is set then
// also perform a full recovery of the free and allocated
// space.
if (dirty_byte & FAT_BPB_RESERVED_TEST_SURFACE) {
RecoverFree = TRUE;
RecoverAlloc = TRUE;
}
}
//
// NOTE that this check must follow the above "if (OnlyIfDirty)" because in the
// OnlyIfDirty case only the first part of the FAT_SA object is in memory
// until the above if gets executed.
//
if (QueryLength() <= SecPerBoot()) {
Message->Set(MSG_NOT_FAT);
Message->Display();
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
//
// The volume is not clean, so if we're autochecking we want to
// make sure that we're printing real messages on the console
// instead of just dots.
//
#if defined(_AUTOCHECK_)
if (Message->SetDotsOnly(FALSE)) {
Message->SetLoggingEnabled(FALSE);
if (NULL != DriveLetter) {
Message->Set(MSG_CHK_RUNNING);
Message->Display("%W", DriveLetter);
}
Message->Set(MSG_FILE_SYSTEM_TYPE);
Message->Display("%s", _ft == LARGE32 ? "FAT32" : "FAT");
Message->SetLoggingEnabled();
}
if (Message->IsInAutoChk()) {
ULONG timeout;
if (!VOL_LIODPDRV::QueryAutochkTimeOut(&timeout)) {
timeout = AUTOCHK_TIMEOUT;
}
if (timeout > MAX_AUTOCHK_TIMEOUT_VALUE)
timeout = AUTOCHK_TIMEOUT;
if (timeout != 0) {
if (dirty_byte & (FAT_BPB_RESERVED_DIRTY | FAT_BPB_RESERVED_TEST_SURFACE))
Message->Set(MSG_CHK_AUTOCHK_SKIP_WARNING);
else
Message->Set(MSG_CHK_USER_AUTOCHK_SKIP_WARNING);
Message->Display();
if (Message->IsKeyPressed(MSG_CHK_ABORT_AUTOCHK, timeout)) {
Message->SetLoggingEnabled(FALSE);
Message->Set(MSG_CHK_AUTOCHK_ABORTED);
Message->Display();
*ExitStatus = CHKDSK_EXIT_SUCCESS;
return TRUE;
} else {
Message->Set(MSG_CHK_AUTOCHK_RESUMED);
Message->Display();
}
} else if ((dirty_byte & (FAT_BPB_RESERVED_DIRTY | FAT_BPB_RESERVED_TEST_SURFACE))) {
Message->Set(MSG_CHK_VOLUME_IS_DIRTY);
Message->Display();
}
} else {
DebugAssert(Message->IsInSetup());
if (dirty_byte & (FAT_BPB_RESERVED_DIRTY | FAT_BPB_RESERVED_TEST_SURFACE)) {
Message->Set(MSG_CHK_VOLUME_IS_DIRTY);
Message->Display();
}
}
#endif // _AUTOCHECK_
//
// The BPB's Media Byte must be in the set accepted
// by the file system.
//
media_byte = QueryMediaByte();
#if defined(FE_SB) && defined(_X86_)
if ((media_byte != 0x00) && /* FMR */
(media_byte != 0x01) && /* FMR */
(media_byte != 0xf0) &&
#else
if ((media_byte != 0xf0) &&
#endif
(media_byte != 0xf8) &&
(media_byte != 0xf9) &&
#if defined(FE_SB) && defined(_X86_)
(media_byte != 0xfa) && /* FMR */
(media_byte != 0xfb) && /* FMR */
#endif
(media_byte != 0xfc) &&
(media_byte != 0xfd) &&
(media_byte != 0xfe) &&
(media_byte != 0xff)) {
SetMediaByte(_drive->QueryMediaByte());
}
// First print out the label and volume serial number.
// We won't bother printing this message under autocheck.
#if !defined( _AUTOCHECK_ ) && !defined( _SETUP_LOADER_ ) && !defined( _EFICHECK_ )
TIMEINFO timeinfo;
if ((QueryLabel(&label, &timeinfo) || label.Initialize("")) &&
label.QueryChCount() &&
timeinfo.QueryDate(&date) &&
timeinfo.QueryTime(&time)) {
Message->Set(MSG_VOLUME_LABEL_AND_DATE);
Message->Display("%W%W%W", &label, &date, &time);
}
#else
#if defined(_EFICHECK_)
if (QueryLabel(&label) && label.QueryChCount() > 0) {
Message->Set(MSG_VOLUME_LABEL_AND_DATE); // date is !!not!! displayed for EFI, since timeinfo is not implemented.
Message->Display("%W", &label);
}
#endif
#endif // !_AUTOCHECK_ && !_SETUP_LOADER_
if (volid = QueryVolId()) {
p = (PUSHORT) &volid;
Message->Set(MSG_VOLUME_SERIAL_NUMBER);
Message->Display("%04X%04X", p[1], p[0]);
}
// Validate the FAT.
if (_dirF32 == NULL)
_fat->Scrub(&changes);
if (changes) {
dofmsg(Message, &fmsg);
Message->Set(MSG_CHK_ERRORS_IN_FAT);
Message->Display();
}
//
// Make sure that the media type in the BPB is the same as at
// the beginning of the FAT.
//
if (QueryMediaByte() != _fat->QueryMediaByte()) {
#if defined(FE_SB) // MO & OEM FAT Support
BOOLEAN bPrintError = TRUE;
#if defined(_X86_)
if (IsPC98_N()) {
// PC98 Nov.01.1994
// to help the early NEC DOS
if(_drive->QueryMediaType() == FixedMedia &&
QueryMediaByte() == 0xf8 && _fat->QueryMediaByte() == 0xfe) {
bPrintError = FALSE;
}
}
#endif
if (bPrintError == TRUE &&
(_drive->QueryMediaType() == F3_128Mb_512 ||
_drive->QueryMediaType() == F3_230Mb_512 )) {
// We won't to recognized as illegal in following case.
//
// Some OpticalDisk might have 0xf0 as media in BPB, but it also has 0xF8 in FAT.
//
if (QueryMediaByte() == 0xf0 && _fat->QueryMediaByte() == 0xf8) {
bPrintError = FALSE;
}
}
if( bPrintError ) {
#endif
dofmsg(Message, &fmsg);
Message->Set(MSG_PROBABLE_NON_DOS_DISK);
Message->Display();
if (!Message->IsYesResponse(FALSE)) {
report.ExitStatus = CHKDSK_EXIT_SUCCESS;
_Verbose = FALSE;
_pvfMessage = NULL;
return TRUE;
}
#if defined(FE_SB) // REAL_FAT_SA::Create():Optical disk support
//
// Here is a table of Optical Disk (MO) format on OEM DOS.
//
// 128MB | NEC | IBM | Fujitsu |
// -----------+-------+-------+---------+
// BPB.Media | 0xF0 | 0xF0 | 0xF0 |
// -----------+-------+-------+---------+
// FAT.DiskID | 0xF0 | 0xF8 | 0xF8 |
// -----------+-------+-------+---------+
//
// 230MB | NEC | IBM | Fujitsu |
// -----------+-------+-------+---------+
// BPB.Media | 0xF0 | 0xF0 | 0xF0 |
// -----------+-------+-------+---------+
// FAT.DiskID | 0xF8 | 0xF8 | 0xF8 |
// -----------+-------+-------+---------+
//
// We will take NEC's way....
if (_drive->QueryMediaType() == F3_230Mb_512) {
DebugAssert(QueryMediaByte() == (UCHAR) 0xF0);
_fat->SetEarlyEntries((UCHAR) 0xF8);
} else {
_fat->SetEarlyEntries(QueryMediaByte());
}
}
#else
_fat->SetEarlyEntries(QueryMediaByte());
#endif
}
// Compute the cluster size and the number of clusters on disk.
cluster_size = _drive->QuerySectorSize()*QuerySectorsPerCluster();
cluster_count = QueryClusterCount();
// No EAs have been detected yet.
ea_infos = NULL;
num_eas = 0;
// Create an EA file name string.
if (!eafilename.Initialize("EA DATA. SF") ||
!eafilepath.Initialize("\\EA DATA. SF")) {
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
//
// This bitmap will be reinitialized before 'WalkDirectoryTree'.
// Its contents will be ignored until then.
//
if (!fat_bitmap.Initialize(cluster_count)) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
// If there is an EA file on disk then...
// FAT32 volume does not support EA.
if (_dir != NULL && // <-- If this is not a FAT32 volume.
eadent.Initialize(_dir->SearchForDirEntry(&eafilename), FAT_TYPE_EAS_OKAY)) {
// Validate the EA file directory entry.
if (!ValidateDirent(&eadent, &eafilepath, FixLevel, FALSE, Message,
&fmsg, &fat_bitmap, &tmp_bool, &tmp_ulong,
ExitStatus)) {
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
// If the EA file directory entry was valid then...
// FATDIR::SearchForDirEntry will not return an erased dirent, but whatever...
if (!eadent.IsErased()) {
// The EA file should not have an EA handle.
if (eadent.QueryEaHandle()) {
dofmsg(Message, &fmsg);
Message->Set(MSG_CHK_EAFILE_HAS_HANDLE);
Message->Display();
eadent.SetEaHandle(0);
*ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
}
// Compute the EA file's starting cluster.
ea_clus_num = eadent.QueryStartingCluster();
//
// Perform any log operations recorded at the beginning
// of the EA file.
//
if (!PerformEaLogOperations(ea_clus_num, FixLevel,
Message, &fmsg)) {
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
//
// Validate the EA file's EA sets and return an array of
// information about them.
//
ea_infos = RecoverEaSets(ea_clus_num, &num_eas, FixLevel,
Message, &fmsg);
//
// If there are no valid EAs in the EA file then erase
// the EA file.
//
if (!ea_infos) {
if (num_eas) {
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
eadent.SetErased();
dofmsg(Message, &fmsg);
Message->Set(MSG_CHK_EMPTY_EA_FILE);
Message->Display();
*ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
}
}
}
// Initialize FAT bitmap to be used in detection of cross-links.
if (!fat_bitmap.Initialize(cluster_count)) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
// DELETE(ea_infos);
delete [] ea_infos; ea_infos = NULL;
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
if (!CheckSectorHeapAllocation(FixLevel, Message, &fmsg)) {
// DELETE(ea_infos);
delete [] ea_infos; ea_infos = NULL;
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
if (!VerifyFatExtensions(FixLevel, Message, &fmsg)) {
// DELETE(ea_infos);
delete [] ea_infos; ea_infos = NULL;
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
//
// Should probably add another function to perform the following task.
//
if (_dirF32 != NULL) {
if (!VerifyAndFixFat32RootDir( &fat_bitmap, Message, &report, &fmsg)) {
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
}
// Validate all of the files on the disk.
save_num_eas = num_eas;
if (!WalkDirectoryTree(ea_infos, &num_eas, &fat_bitmap, &report,
FixLevel, RecoverAlloc, Message, Verbose, &fmsg)) {
// DELETE(ea_infos);
delete [] ea_infos; ea_infos = NULL;
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
if (save_num_eas != num_eas && ea_infos) {
if (!EraseEaHandle(ea_infos, num_eas, save_num_eas, FixLevel, Message)) {
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
if (!num_eas) {
delete [] ea_infos;
ea_infos = NULL;
//
// Note that the following two steps cause the EA file chain to get recovered
// as a lost cluster chain since all this does is erase the dirent, not the
// cluster chain.
//
eadent.SetErased();
FreeSpaceInBitmap(eadent.QueryStartingCluster(), _fat,
&fat_bitmap);
dofmsg(Message, &fmsg);
Message->Set(MSG_CHK_EMPTY_EA_FILE);
Message->Display();
*ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
}
}
// If there are EAs on the disk then...
if (ea_infos) {
// Remove all unused EAs from EA file.
if (!PurgeEaFile(ea_infos, num_eas, &fat_bitmap, FixLevel, Message,
&fmsg)) {
// DELETE( ea_infos );
delete [] ea_infos; ea_infos = NULL;
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
// Rebuild header portion of EA file.
if (!ea_header_mem.Initialize() ||
!RebuildEaHeader(&ea_clus_num, ea_infos, num_eas,
&ea_header_mem, &ea_header, &fat_bitmap,
FixLevel, Message, &fmsg)) {
// DELETE( ea_infos );
delete [] ea_infos; ea_infos = NULL;
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
if (ea_clus_num) {
eadent.SetStartingCluster(ea_clus_num);
eadent.SetFileSize(cluster_size*
_fat->QueryLengthOfChain(ea_clus_num));
} else {
dofmsg(Message, &fmsg);
Message->Set(MSG_CHK_EMPTY_EA_FILE);
Message->Display();
//
// Note that the following two steps cause the EA file chain to get recovered
// as a lost cluster chain since all this does is erase the dirent, not the
// cluster chain.
//
eadent.SetErased();
FreeSpaceInBitmap(eadent.QueryStartingCluster(), _fat,
&fat_bitmap);
}
*ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
}
//
// If WalkDirectoryTree deleted any files, we need to sync the
// FAT_EXTENSIONS up with the FAT again.
//
if (!VerifyFatExtensions(FixLevel, Message, &fmsg)) {
// DELETE(ea_infos);
delete [] ea_infos; ea_infos = NULL;
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
if (!RecoverOrphans(&fat_bitmap, FixLevel, Message, &fmsg, &report, &changes)) {
// DELETE(ea_infos);
delete [] ea_infos; ea_infos = NULL;
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
//
// RecoverOrphans may have cleared faulty entries from the FAT,
// and now we need to sync the FAT_EXTENSIONS again.
//
if (!VerifyFatExtensions(FixLevel, Message, &fmsg)) {
// DELETE(ea_infos);
delete [] ea_infos; ea_infos = NULL;
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
// If requested, validate all of the free space on the volume.
if (RecoverFree && !RecoverFreeSpace(Message)) {
// DELETE(ea_infos);
delete [] ea_infos; ea_infos = NULL;
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
total_count = cluster_count - FirstDiskCluster;
if (changes) {
report.ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
}
*ExitStatus = report.ExitStatus;
switch (*ExitStatus) {
case CHKDSK_EXIT_SUCCESS:
Message->DisplayMsg(MSG_CHK_NO_PROBLEM_FOUND);
break;
case CHKDSK_EXIT_ERRS_FIXED:
Message->DisplayMsg((FixLevel != CheckOnly) ? MSG_CHK_ERRORS_FIXED : MSG_CHK_NEED_F_PARAMETER);
break;
case CHKDSK_EXIT_COULD_NOT_CHK:
// case CHKDSK_EXIT_ERRS_NOT_FIXED:
// case CHKDSK_EXIT_COULD_NOT_FIX:
Message->DisplayMsg(MSG_CHK_ERRORS_NOT_FIXED);
break;
}
BIG_INT temp_big_int;
ULONG temp_ulong;
MSGID message_id;
BOOLEAN KSize;
DSTRING wdNum1;
char wdAstr[14];
DSTRING wdNum2;
if (!wdNum1.Initialize(" ") ||
!wdNum2.Initialize(" ") ) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
temp_big_int = cluster_size;
temp_big_int = temp_big_int * total_count;
// NOTE: The magic number 4095MB comes from Win9x's GUI SCANDISK utility
if (temp_big_int.GetHighPart() || (temp_big_int.GetLowPart() > (4095ul*1024ul*1024ul))) {
temp_ulong = (temp_big_int / 1024ul).GetLowPart();
message_id = MSG_TOTAL_KILOBYTES;
KSize = TRUE;
} else {
temp_ulong = temp_big_int.GetLowPart();
message_id = MSG_TOTAL_DISK_SPACE;
KSize = FALSE;
}
Message->Set(message_id);
sprintf(wdAstr, "%u", temp_ulong);
InsertSeparators(wdNum1.GetWSTR(),wdAstr, 13);
Message->Display("%ws", wdNum1.GetWSTR());
if (report.HiddenEntriesCount) {
temp_big_int = cluster_size;
temp_big_int = temp_big_int * report.HiddenClusters;
if (KSize) {
temp_ulong = (temp_big_int / 1024ul).GetLowPart();
message_id = MSG_KILOBYTES_IN_HIDDEN_FILES;
} else {
temp_ulong = temp_big_int.GetLowPart();
message_id = MSG_HIDDEN_FILES;
}
Message->Set(message_id);
sprintf(wdAstr, "%u", temp_ulong);
InsertSeparators(wdNum1.GetWSTR(),wdAstr, 13);
sprintf(wdAstr, "%d", report.HiddenEntriesCount);
InsertSeparators(wdNum2.GetWSTR(),wdAstr, 0);
Message->Display("%ws%ws", wdNum1.GetWSTR(), wdNum2.GetWSTR());
}
if (report.DirEntriesCount) {
temp_big_int = cluster_size;
temp_big_int = temp_big_int * report.DirClusters;
if (KSize) {
temp_ulong = (temp_big_int / 1024ul).GetLowPart();
message_id = MSG_KILOBYTES_IN_DIRECTORIES;
} else {
temp_ulong = temp_big_int.GetLowPart();
message_id = MSG_DIRECTORIES;
}
Message->Set(message_id);
sprintf(wdAstr, "%u", temp_ulong);
InsertSeparators(wdNum1.GetWSTR(),wdAstr, 13);
sprintf(wdAstr, "%d", report.DirEntriesCount);
InsertSeparators(wdNum2.GetWSTR(),wdAstr, 0);
Message->Display("%ws%ws", wdNum1.GetWSTR(), wdNum2.GetWSTR());
}
if (report.FileEntriesCount) {
temp_big_int = cluster_size;
temp_big_int = temp_big_int * report.FileClusters;
if (KSize) {
temp_ulong = (temp_big_int / 1024ul).GetLowPart();
message_id = MSG_KILOBYTES_IN_USER_FILES;
} else {
temp_ulong = temp_big_int.GetLowPart();
message_id = MSG_USER_FILES;
}
Message->Set(message_id);
sprintf(wdAstr, "%u", temp_ulong);
InsertSeparators(wdNum1.GetWSTR(),wdAstr, 13);
sprintf(wdAstr, "%d", report.FileEntriesCount);
InsertSeparators(wdNum2.GetWSTR(),wdAstr, 0);
Message->Display("%ws%ws", wdNum1.GetWSTR(), wdNum2.GetWSTR());
}
if (bad_count = _fat->QueryBadClusters()) {
temp_big_int = bad_count;
temp_big_int = temp_big_int * cluster_size;
if (KSize) {
temp_ulong = (temp_big_int / 1024ul).GetLowPart();
message_id = MSG_CHK_NTFS_BAD_SECTORS_REPORT_IN_KB;
} else {
temp_ulong = temp_big_int.GetLowPart();
message_id = MSG_BAD_SECTORS;
}
Message->Set(message_id);
sprintf(wdAstr, "%u", temp_ulong);
InsertSeparators(wdNum1.GetWSTR(),wdAstr, 13);
Message->Display("%ws", wdNum1.GetWSTR());
}
if (ea_infos) {
Message->Set(MSG_CHK_EA_SIZE);
sprintf(wdAstr, "%u", cluster_size*_fat->QueryLengthOfChain(ea_clus_num));
InsertSeparators(wdNum1.GetWSTR(),wdAstr, 13);
Message->Display("%ws", wdNum1.GetWSTR());
}
free_count = _fat->QueryFreeClusters();
temp_big_int = free_count;
temp_big_int = temp_big_int * cluster_size;
if (KSize) {
temp_ulong = (temp_big_int / 1024ul).GetLowPart();
message_id = MSG_AVAILABLE_KILOBYTES;
} else {
temp_ulong = temp_big_int.GetLowPart();
message_id = MSG_AVAILABLE_DISK_SPACE;
}
Message->Set(message_id);
sprintf(wdAstr, "%u", temp_ulong);
InsertSeparators(wdNum1.GetWSTR(),wdAstr, 13);
Message->Display("%ws", wdNum1.GetWSTR());
Message->Set(MSG_ALLOCATION_UNIT_SIZE);
sprintf(wdAstr, "%u", cluster_size);
InsertSeparators(wdNum1.GetWSTR(),wdAstr, 13);
Message->Display("%ws", wdNum1.GetWSTR());
Message->Set(MSG_TOTAL_ALLOCATION_UNITS);
sprintf(wdAstr, "%u", total_count);
InsertSeparators(wdNum1.GetWSTR(),wdAstr, 13);
Message->Display("%ws", wdNum1.GetWSTR());
Message->Set(MSG_AVAILABLE_ALLOCATION_UNITS);
sprintf(wdAstr, "%u", free_count);
InsertSeparators(wdNum1.GetWSTR(),wdAstr, 13);
Message->Display("%ws", wdNum1.GetWSTR());
if (FixLevel != CheckOnly && ea_infos && !ea_header.Write()) {
// DELETE(ea_infos);
delete [] ea_infos; ea_infos = NULL;
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
// Clear the dirty bit.
//
if( RecoverAlloc ) {
SetVolumeFlags(FAT_BPB_RESERVED_DIRTY | FAT_BPB_RESERVED_TEST_SURFACE,
TRUE);
} else {
SetVolumeFlags(FAT_BPB_RESERVED_DIRTY, TRUE);
}
if (FixLevel != CheckOnly && !Write(Message)) {
// DELETE(ea_infos);
delete [] ea_infos; ea_infos = NULL;
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
// DELETE(ea_infos);
delete [] ea_infos; ea_infos = NULL;
_Verbose = FALSE;
_pvfMessage = NULL;
return TRUE;
}
BOOLEAN
FAT_SA::VerifyAndFixFat32RootDir (
IN OUT PBITVECTOR FatBitMap,
IN PMESSAGE Message,
IN OUT PFATCHK_REPORT Report,
IN OUT PBOOLEAN NeedErrorMessage
)
/*++
Routine Description:
This routine verifies the FAT32 root directory which is not an integral
part of the super area buffer. The method employed to verify and fix the
root directory is very similar to the one used to verify and fix regular
directory structure.
Arguments:
BitVector - Supplies a bit map for cross/bad links detection. The whole
map should be zeroed when it is passed in this method.
Message - Supplies an outlet for messages.
Report - Supplies the fat chkdsk report structures for storing the
actions performed by this method.
NeedErrorsMessage - Supplies whether or not an error has occurred
under check only conditions.
Return Values:
TRUE - Success.
FALSE - Failed.
--*/
{
BOOLEAN crosslink_detected = FALSE;
BOOLEAN changes_made = FALSE;
ULONG starting_cluster;
ULONG dummy;
starting_cluster = QueryFat32RootDirStartingCluster();
_fat->ScrubChain( starting_cluster,
FatBitMap,
&changes_made,
&crosslink_detected,
&dummy );
//
// Root dir is the only component marked in the
// bitmap so far.
//
DebugAssert(!crosslink_detected);
if (changes_made) {
dofmsg(Message, NeedErrorMessage);
Message->Set(MSG_BAD_LINK);
Message->Display("%s", "\\");
Report->ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
//
// We have to reinitialized the root directory.
//
if (!_hmem_F32->Initialize() ||
!_dirF32->Initialize( _hmem_F32, _drive, this,
_fat, starting_cluster)) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
//
// Force a re-reading of the root directory.
// We don't care if it fails, subsequent code can fix that.
//
_dirF32->Read();
}
//
// Validate the readability of the root chain
//
//
// We don't want replacement clusters becuase the replacement given
// by RecoverChain will be zeroed which, according to the spec., means
// it contains the end of the directory structure and WalkDirectoryTree
// will just go ahead and erase all the 'good' directory entries that comes
// after the replaced cluster. Not a really nice thing to do to the root
// directory IMHO.
//
if(!RecoverChain(&starting_cluster, &changes_made, 0, FALSE)){
dofmsg(Message, NeedErrorMessage);
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
if (changes_made) {
if ( starting_cluster ) {
if ( starting_cluster != _dirF32->QueryStartingCluster() ) {
SetFat32RootDirStartingCluster( starting_cluster );
}
//
// Should reinitialize the root directory
//
if (!_hmem_F32->Initialize() ||
!_dirF32->Initialize( _hmem_F32, _drive, this,
_fat, starting_cluster)) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
} else {
if(!RelocateNewFat32RootDirectory( Report, FatBitMap, Message )) {
return FALSE;
}
}
//
// Reread the root directory
//
if (!_dirF32->Read()) {
//
// Shouldn't fail.
//
DebugAbort("Failed to read the FAT32 root directory despite all the fixing.\n");
}
dofmsg(Message, NeedErrorMessage);
Message->Set(MSG_CHK_NTFS_CORRECTING_ERROR_IN_DIRECTORY);
Message->Display("%s", "\\");
//
// Erasing the root will totally destroy the disk
// so we just leave it partially corrupted and
// hopefully WalkDirectoryTree will be able to fix it.
//
Report->ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
}
return TRUE;
}
BOOLEAN
FAT_SA::RelocateNewFat32RootDirectory (
IN OUT PFATCHK_REPORT Report,
IN OUT PBITVECTOR FatBitMap,
IN PMESSAGE Message
)
/*++
Routine Description:
This routine relocates a FAT32 root directory
Arguments:
Report - Supplies the fat chkdsk report structure for storing
the fix status.
FatBitMap - Supplies a pointer to the bit map for cross-link
detection.
Message - Supplies an outlet for messages.
Return Values:
TRUE - Success.
FALSE - Failed.
--*/
{
SECRUN root_secrun; // Allocate one cluster for the
// new root directory.
ULONG root_clus; // New cluster number of the
// root directory
ULONG cluster_size;// Number of sectors in a cluster.
ULONG starting_data_lbn;
ULONG sector_size;
starting_data_lbn = QueryStartDataLbn();
cluster_size = QuerySectorsPerCluster();
sector_size = _drive->QuerySectorSize();
for (;;) {
root_clus = _fat->AllocChain(1, NULL);
if (!root_clus) {
//
// The disk is full, we have no choice but to bail out.
//
Message->Set(MSG_CHK_INSUFFICIENT_DISK_SPACE);
Message->Display();
return FALSE;
}
if ( !_hmem_F32->Initialize() ||
!root_secrun.Initialize( _hmem_F32,
_drive,
QuerySectorFromCluster(root_clus, NULL),
cluster_size)) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
memset(root_secrun.GetBuf(), 0, cluster_size * sector_size);
if (root_secrun.Write() && root_secrun.Read()) {
SetFat32RootDirStartingCluster(root_clus);
//
// Set the bit for the new root in the bit map.
//
FatBitMap->SetBit(root_clus);
//
// Reinitialize the FAT32 root directory
//
if ( !_hmem_F32->Initialize() ||
!_dirF32->Initialize( _hmem_F32, _drive, this,
_fat, root_clus)) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
Report->ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
return TRUE;
} else {
_fat->SetClusterBad(root_clus);
}
}
DebugPrintTrace(("FAT_SA::RelocateNewFat32RootDirectory: This line should not be reached.\n"));
return FALSE;
}
BOOLEAN
FAT_SA::PerformEaLogOperations(
IN ULONG EaFileCn,
IN FIX_LEVEL FixLevel,
IN OUT PMESSAGE Message,
IN OUT PBOOLEAN NeedErrorsMessage
)
/*++
Routine Description:
This routine reads the EA file log from the disk and then performs
any logged operations specified.
Arguments:
EaFileCn - Supplies the first cluster of the EA file.
FixLevel - Supplies the fix level.
Message - Supplies an outlet for messages.
NeedErrorsMessage - Supplies whether or not an error has occurred
under check only conditions.
Return Value:
FALSE - Failure.
TRUE - Success.
--*/
{
HMEM hmem;
EA_HEADER ea_header;
PEA_FILE_HEADER pea_header;
ULONG cluster_size;
ULONG num_clus;
cluster_size = _drive->QuerySectorSize()*QuerySectorsPerCluster();
num_clus = sizeof(EA_FILE_HEADER) + BaseTableSize*sizeof(USHORT);
if (num_clus%cluster_size) {
num_clus = (num_clus/cluster_size + 1);
} else {
num_clus = (num_clus/cluster_size);
}
if (!hmem.Initialize() ||
!ea_header.Initialize(&hmem, _drive, this, _fat, EaFileCn, num_clus) ||
!(pea_header = ea_header.GetEaFileHeader())) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
if (!ea_header.Read()) {
Message->Set(MSG_CHK_CANT_CHECK_EA_LOG);
Message->Display();
return TRUE;
}
if (pea_header->Signature != HeaderSignature ||
pea_header->FormatType ||
pea_header->LogType) {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_BAD_LOG, NORMAL_MESSAGE, TEXT_MESSAGE);
Message->Display();
if (Message->IsYesResponse(TRUE)) {
pea_header->Signature = HeaderSignature;
pea_header->Cluster1 = 0;
pea_header->Cluster2 = 0;
pea_header->Cluster3 = 0;
if (FixLevel != CheckOnly) {
ea_header.Write();
}
return TRUE;
} else {
return FALSE;
}
}
if (pea_header->Cluster1) {
if (_fat->IsInRange(pea_header->Cluster1) &&
_fat->IsInRange(pea_header->NewCValue1)) {
_fat->SetEntry(pea_header->Cluster1, pea_header->NewCValue1);
} else {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_ERROR_IN_LOG);
Message->Display();
}
}
if (pea_header->Cluster2) {
if (_fat->IsInRange(pea_header->Cluster2) &&
_fat->IsInRange(pea_header->NewCValue2)) {
_fat->SetEntry(pea_header->Cluster2, pea_header->NewCValue2);
} else {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_ERROR_IN_LOG);
Message->Display();
}
}
if (pea_header->Cluster3) {
if (_fat->IsInRange(pea_header->Cluster3) &&
_fat->IsInRange(pea_header->NewCValue3)) {
_fat->SetEntry(pea_header->Cluster3, pea_header->NewCValue3);
} else {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_ERROR_IN_LOG);
Message->Display();
}
}
return TRUE;
}
PEA_INFO
FAT_SA::RecoverEaSets(
IN ULONG EaFileCn,
OUT PUSHORT NumEas,
IN FIX_LEVEL FixLevel,
IN OUT PMESSAGE Message,
IN OUT PBOOLEAN NeedErrorsMessage
)
/*++
Routine Description:
This routine validates and if necessary recovers the EA file.
Arguments:
EaFileCn - Supplies the cluster number for the EA file.
NumEas - Returns the number of EA sets in the EA file.
FixLevel - Supplies the CHKDSK fix level.
Message - Supplies an outlet for messages.
NeedErrorsMessage - Supplies whether or not an error has occurred
under check only conditions.
Return Value:
An allocated array containing 'NumberOfEaSets' entries documenting
important information about the EA sets. If there are no EAs then
'NumberOfEaSets' is returned as 0 and NULL is returned. If there
is an error then NULL will be returned with a non-zero
'NumberOfEaSets'.
--*/
{
PEA_INFO ea_infos;
ULONG clus, prev;
USHORT num_eas;
ULONG i;
ULONG length;
DebugAssert(NumEas);
*NumEas = 1;
length = _fat->QueryLengthOfChain(EaFileCn);
ea_infos = NEW EA_INFO[length];
if (!ea_infos) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return NULL;
}
memset(ea_infos, 0, length*sizeof(EA_INFO));
//
// Scan file for EA sets and validate them while updating the
// array.
//
num_eas = 0;
prev = EaFileCn;
while (!_fat->IsEndOfChain(prev)) {
clus = VerifyAndFixEaSet(prev, &ea_infos[num_eas], FixLevel,
Message, NeedErrorsMessage);
if (clus) {
num_eas++;
} else {
clus = _fat->QueryEntry(prev);
}
prev = clus;
}
if (!num_eas) {
// All the ea sets are unused, the ea file is
// effectively empty.
// Should use array delete instead.
// DELETE( ea_infos );
delete [] ea_infos;
// Free the cluster chain occupied by the ea file
// so subsequent checking and fixing will not
// complain about the lost chain in the ea file.
_fat->FreeChain(EaFileCn);
ea_infos = NULL;
*NumEas = 0;
return NULL;
}
// Go through and remove unused portions of the EA file.
for (i = 0; i < (USHORT)(num_eas - 1); i++) {
if (ea_infos[i].LastCn != ea_infos[i + 1].PreceedingCn) {
_fat->RemoveChain(ea_infos[i].LastCn,
ea_infos[i + 1].PreceedingCn);
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_UNUSED_EA_PORTION);
Message->Display();
ea_infos[i + 1].PreceedingCn = ea_infos[i].LastCn;
}
}
if (!_fat->IsEndOfChain(ea_infos[num_eas - 1].LastCn)) {
_fat->SetEndOfChain(ea_infos[num_eas - 1].LastCn);
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_UNUSED_EA_PORTION);
Message->Display();
}
// Sort the EAs in the EA file.
if (!EaSort(ea_infos, num_eas, Message, NeedErrorsMessage)) {
return NULL;
}
*NumEas = num_eas;
return ea_infos;
}
ULONG
FAT_SA::VerifyAndFixEaSet(
IN ULONG PreceedingCluster,
OUT PEA_INFO EaInfo,
IN FIX_LEVEL FixLevel,
IN OUT PMESSAGE Message,
IN OUT PBOOLEAN NeedErrorsMessage
)
/*++
Routine Description:
This routine attempts to identify the clusters following the
'PreceedingCluster' as an EA set. If this routine does not
recognize these clusters as an EA set then it will return 0.
Otherwise, it will return the last cluster of the validated EA set.
Changes may be made to the clusters if they are recognized as an EA
set with errors.
Arguments:
PreceedingCluster - Supplies the cluster preceeding the EA set cluster.
Info - Returns information about the EA set.
FixLevel - Supplies the CHKDSK fix level.
Message - Supplies an outlet for messages.
NeedErrorsMessage - Supplies whether or not errors have occurred
under check only conditions.
Return Value:
The cluster number of the last cluster in the EA set or 0.
--*/
{
HMEM hmem;
EA_SET easet;
ULONG clus;
PEA_HDR eahdr;
LONG i;
ULONG j;
ULONG need_count;
LONG total_size;
LONG size;
ULONG length;
BOOLEAN need_write;
PEA pea;
BOOLEAN more;
ULONG chain_length;
clus = _fat->QueryEntry(PreceedingCluster);
chain_length = _fat->QueryLengthOfChain(clus);
length = 1;
need_write = FALSE;
if (!hmem.Initialize() ||
!easet.Initialize(&hmem, _drive, this, _fat, clus, length) ||
!(eahdr = easet.GetEaSetHeader())) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return 0;
}
if (!easet.Read()) {
return 0;
}
if (!easet.VerifySignature()) {
return 0;
}
need_count = 0;
total_size = 4;
for (i = 0; ; i++) {
for (j = 0; !(pea = easet.GetEa(i, &size, &more)) && more &&
length + j < chain_length; ) {
j++;
if (!hmem.Initialize() ||
!easet.Initialize(&hmem, _drive, this, _fat, clus, length + j)) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return 0;
}
if (!easet.Read()) {
return 0;
}
}
if (pea) {
length += j;
} else {
break;
}
total_size += size;
if (pea->Flag & NeedFlag) {
need_count++;
}
}
if (!i) {
return 0;
}
if (total_size != eahdr->TotalSize) {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_EASET_SIZE);
Message->Display("%d", clus);
eahdr->TotalSize = total_size;
need_write = TRUE;
}
if (need_count != eahdr->NeedCount) {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_EASET_NEED_COUNT);
Message->Display("%d", clus);
eahdr->NeedCount = need_count;
need_write = TRUE;
}
EaInfo->OwnHandle = eahdr->OwnHandle;
EaInfo->PreceedingCn = PreceedingCluster;
EaInfo->LastCn = _fat->QueryNthCluster(PreceedingCluster, length);
memcpy(EaInfo->OwnerFileName, eahdr->OwnerFileName, 14);
EaInfo->UsedCount = 0;
if (need_write) {
if (FixLevel != CheckOnly && !easet.Write()) {
return 0;
}
}
return EaInfo->LastCn;
}
BOOLEAN
FAT_SA::EaSort(
IN OUT PEA_INFO EaInfos,
IN ULONG NumEas,
IN OUT PMESSAGE Message,
IN OUT PBOOLEAN NeedErrorsMessage
)
/*++
Routine Description:
This routine sorts the EaInfos array by 'OwnHandle' into ascending order.
It also edits the FAT with the changes in the EAs order.
Arguments:
EaInfos - Supplies the array of EA_INFOs to sort.
NumEas - Supplies the number of elements in the array.
Message - Supplies an outlet for messages.
NeedErrorsMessage - Supplies whether or not errors have occurred
under check only conditions.
Return Value:
FALSE - Failure.
TRUE - Success.
--*/
{
BOOLEAN done;
EA_INFO tmp;
ULONG clus;
ULONG i;
BOOLEAN change;
done = FALSE;
change = FALSE;
while (!done) {
done = TRUE;
for (i = 0; i < NumEas - 1; i++) {
if (EaInfos[i].OwnHandle > EaInfos[i + 1].OwnHandle) {
done = FALSE;
clus = _fat->RemoveChain(EaInfos[i + 1].PreceedingCn,
EaInfos[i + 1].LastCn);
_fat->InsertChain(clus,
EaInfos[i + 1].LastCn,
EaInfos[i].PreceedingCn);
EaInfos[i + 1].PreceedingCn = EaInfos[i].PreceedingCn;
EaInfos[i].PreceedingCn = EaInfos[i + 1].LastCn;
if (i + 2 < NumEas) {
EaInfos[i + 2].PreceedingCn = EaInfos[i].LastCn;
}
change = TRUE;
tmp = EaInfos[i];
EaInfos[i] = EaInfos[i + 1];
EaInfos[i + 1] = tmp;
}
}
}
if (change) {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_UNORDERED_EA_SETS);
Message->Display();
}
return TRUE;
}
BOOLEAN
FAT_SA::RebuildEaHeader(
IN OUT PULONG StartingCluster,
IN OUT PEA_INFO EaInfos,
IN ULONG NumEas,
IN OUT PMEM EaHeaderMem,
OUT PEA_HEADER EaHeader,
IN OUT PBITVECTOR FatBitMap,
IN FIX_LEVEL FixLevel,
IN OUT PMESSAGE Message,
IN OUT PBOOLEAN NeedErrorsMessage
)
/*++
Routine Description:
This routine rebuilds the header and tables of the EA file base on the
information in the 'EaInfos' array. The header log is set to zero,
and the header itself is relocated if any of the clusters are bad.
The starting cluster may be relocated if there are bad clusters.
Arguments:
StartingCluster - Supplies the first cluster of the EA file.
EaInfos - Supplies an array containing information for every
EA set.
NumberOfEas - Supplies the total number of EA sets.
EaHeaderMem - Supplies the memory for the EA header.
EaHeader - Returns the EA header.
FatBitMap - Supplies the cross-links bitmap.
FixLevel - Supplies the CHKDSK fix level.
Message - Supplies an outlet for messages.
NeedErrorsMessage - Supplies whether or not errors have occurred
under check only conditions.
Return Value:
FALSE - Failure.
TRUE - Success.
--*/
{
ULONG length;
ULONG cluster_size;
ULONG actual_length;
ULONG new_chain;
ULONG last_cluster;
BOOLEAN changes;
LONG i, j, k;
PEA_MAP_TBL table;
PEA_FILE_HEADER header;
LONG tmp;
BOOLEAN empty_ea_file;
ULONG clus;
// Compute the number of clusters necessary for the header portion of
// the EA file.
length = sizeof(EA_FILE_HEADER) +
BaseTableSize*sizeof(USHORT) +
EaInfos[NumEas - 1].OwnHandle*sizeof(USHORT);
cluster_size = _drive->QuerySectorSize()*QuerySectorsPerCluster();
if (length%cluster_size) {
length = length/cluster_size + 1;
} else {
length = length/cluster_size;
}
//
// Make sure that the header contains enough clusters to accomodate
// the size of the offset table.
//
last_cluster = EaInfos[0].PreceedingCn;
actual_length = _fat->QueryLengthOfChain(*StartingCluster, last_cluster);
if (length > actual_length) {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_NEED_MORE_HEADER_SPACE);
Message->Display();
new_chain = _fat->AllocChain((length - actual_length),
&last_cluster);
if (!new_chain) {
Message->Set(MSG_CHK_INSUFFICIENT_DISK_SPACE);
Message->Display();
return FALSE;
}
if (IsCompressed() && !AllocSectorsForChain(new_chain)) {
_fat->FreeChain(new_chain);
Message->Set(MSG_CHK_INSUFFICIENT_DISK_SPACE);
Message->Display();
return FALSE;
}
for (clus = new_chain;
!_fat->IsEndOfChain(clus);
clus = _fat->QueryEntry(clus)) {
FatBitMap->SetBit(clus);
}
FatBitMap->SetBit(clus);
_fat->InsertChain(new_chain, last_cluster, EaInfos[0].PreceedingCn);
EaInfos[0].PreceedingCn = last_cluster;
} else if (length < actual_length) {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_UNUSED_EA_PORTION);
Message->Display();
last_cluster = _fat->QueryNthCluster(*StartingCluster,
length - 1);
clus = _fat->RemoveChain(last_cluster, EaInfos[0].PreceedingCn);
EaInfos[0].PreceedingCn = last_cluster;
for (;
!_fat->IsEndOfChain(clus);
clus = _fat->QueryEntry(clus)) {
FatBitMap->ResetBit(clus);
}
FatBitMap->ResetBit(clus);
}
// Verify the cluster chain containing the header.
changes = FALSE;
if (FixLevel != CheckOnly &&
!RecoverChain(StartingCluster, &changes, last_cluster, TRUE)) {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_INSUFFICIENT_DISK_SPACE);
Message->Display();
return FALSE;
}
if (changes) {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_RELOCATED_EA_HEADER);
Message->Display();
}
// Compute the tables.
if (!EaHeader->Initialize(EaHeaderMem, _drive, this, _fat,
*StartingCluster, (USHORT) length) ||
!(table = EaHeader->GetMapTable()) ||
!(header = EaHeader->GetEaFileHeader())) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
if (!EaHeader->Read()) {
if (FixLevel == CheckOnly) {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_RELOCATED_EA_HEADER);
Message->Display();
} else {
return FALSE;
}
}
// Set the log in the header to zero.
header->Signature = HeaderSignature;
header->FormatType = 0;
header->LogType = 0;
header->Cluster1 = 0;
header->NewCValue1 = 0;
header->Cluster2 = 0;
header->NewCValue2 = 0;
header->Cluster3 = 0;
header->NewCValue3 = 0;
header->Handle = 0;
header->NewHOffset = 0;
// Reconcile the tables with the EaInfo information.
changes = FALSE;
for (i = 0; i < BaseTableSize; i++) {
table->BaseTab[i] = 0;
}
j = 0;
empty_ea_file = TRUE;
for (i = 0; i < (LONG) NumEas; i++) {
if (EaInfos[i].UsedCount != 1) {
continue;
}
empty_ea_file = FALSE;
for (; j < (LONG) EaInfos[i].OwnHandle; j++) {
if (table->OffTab[j] != InvalidHandle) {
table->OffTab[j] = InvalidHandle;
changes = TRUE;
}
}
length = _fat->QueryLengthOfChain(*StartingCluster,
EaInfos[i].PreceedingCn);
for (k = j>>7; k >= 0 && !table->BaseTab[k]; k--) {
table->BaseTab[k] = (USHORT) length;
}
tmp = length - table->BaseTab[j>>7];
if ((LONG)table->OffTab[j] != tmp) {
table->OffTab[j] = (USHORT) tmp;
changes = TRUE;
}
j++;
}
if (empty_ea_file) {
for (clus = *StartingCluster;
!_fat->IsEndOfChain(clus);
clus = _fat->QueryEntry(clus)) {
FatBitMap->ResetBit(clus);
}
FatBitMap->ResetBit(clus);
*StartingCluster = 0;
return TRUE;
}
tmp = _fat->QueryLengthOfChain(*StartingCluster);
for (k = ((j - 1)>>7) + 1; k < BaseTableSize; k++) {
table->BaseTab[k] = (USHORT) tmp;
}
for (; j < (LONG) EaHeader->QueryOffTabSize(); j++) {
if (table->OffTab[j] != InvalidHandle) {
table->OffTab[j] = InvalidHandle;
changes = TRUE;
}
}
if (changes) {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_ERROR_IN_EA_HEADER);
Message->Display();
}
return TRUE;
}
VOID
FreeSpaceInBitmap(
IN ULONG StartingCluster,
IN PCFAT Fat,
IN OUT PBITVECTOR FatBitMap
)
{
if (!StartingCluster) {
return;
}
while (!Fat->IsEndOfChain(StartingCluster)) {
FatBitMap->ResetBit(StartingCluster);
StartingCluster = Fat->QueryEntry(StartingCluster);
}
FatBitMap->ResetBit(StartingCluster);
}
ULONG
ComputeFileNameHashValue(
IN PVOID FileName
)
{
ULONG h;
BYTE i;
PUCHAR p;
p = (PUCHAR) FileName;
h = 0;
for (i=0; i<11; i++) {
h = (h << 2) ^ p[i];
}
for (i=0; i<2; i++) {
h = (h << 2) ^ p[i];
}
return h;
}
STATIC ULONG _Twinkle = 0;
STATIC LONG64 _LastTwnkTime = 0;
STATIC ULONG _LastPercent = 0xFFFFFFFF;
BOOLEAN
DisplayTwnkPercent(
ULONG percent
)
{
BIG_INT currenttime;
#if !defined( _EFICHECK_ )
NtQuerySystemTime((_LARGE_INTEGER *)¤ttime);
#else
EfiQuerySystemTime((_LARGE_INTEGER *)¤ttime);
#endif
// The above clock counts in 1/10,000ths of a second
if((percent != _LastPercent) ||
((currenttime.GetQuadPart() - _LastTwnkTime) >= (6 * 100 * 10000)))
{
if(percent > 100) {
percent = 100;
}
if((_Twinkle > 5) || _Verbose) {
_Twinkle = 0;
}
if(_Verbose && (percent == _LastPercent)) {
return TRUE;
}
_LastPercent = percent;
_LastTwnkTime = currenttime.GetQuadPart();
if(_pvfMessage) {
STR dots[6];
dots[5] = '\0';
dots[4] = ' ';
dots[3] = ' ';
dots[2] = ' ';
dots[1] = ' ';
dots[0] = ' ';
switch(_Twinkle) {
case 5:
default:
dots[4] = '.';
case 4:
dots[3] = '.';
case 3:
dots[2] = '.';
case 2:
dots[1] = '.';
case 1:
dots[0] = '.';
case 0:
;
}
if(!_Verbose) {
_Twinkle++;
}
_pvfMessage->Set(MSG_PERCENT_COMPLETE2);
if (!_pvfMessage->Display("%d%s", percent, &dots[0])) {
return FALSE;
}
if(_Verbose) {
_pvfMessage->Set(MSG_BLANK_LINE);
_pvfMessage->Display();
}
}
}
return TRUE;
}
VOID DoTwinkle(
VOID
)
{
DisplayTwnkPercent(_LastPercent);
return;
}
VOID DoInsufMemory(
VOID
)
{
if(_pvfMessage) {
_pvfMessage->Set(MSG_CHK_NO_MEMORY);
_pvfMessage->Display();
}
return;
}
BOOLEAN
FAT_SA::WalkDirectoryTree(
IN OUT PEA_INFO EaInfos,
IN OUT PUSHORT NumEas,
IN OUT PBITVECTOR FatBitMap,
OUT PFATCHK_REPORT Report,
IN FIX_LEVEL FixLevel,
IN BOOLEAN RecoverAlloc,
IN OUT PMESSAGE Message,
IN BOOLEAN Verbose,
IN OUT PBOOLEAN NeedErrorsMessage
)
/*++
Routine Description:
This routine walks all of the files on the volume by traversing
the directory tree. In doing so it validates all of the
directory entries on the disk. It also verifies the proper
chaining of all file cluster chains. This routine also validates
the integrity of the EA handles for all of the directory entries
on the disk.
The FatBitMap is used to find and eliminate cross-links in the file
system.
Arguments:
EaInfos - Supplies the EA information.
NumEas - Supplies the number of EA sets.
FatBitMap - Supplies a bit map marking all of the clusters
currently in use.
Report - Returns a FAT CHKDSK report on the files of the disk.
FixLevel - Supplies the CHKDSK fix level.
Message - Supplies an outlet for messages.
Verbose - Supplies whether or not to be verbose.
NeedErrorsMessage - Supplies whether or not errors have occurred
under check only conditions.
Return Value:
FALSE - Failure.
TRUE - Success.
--*/
{
PVISIT_DIR visit_list;
ULONG current_dir;
PFATDIR dir;
FILEDIR filedir;
FAT_DIRENT dirent;
ULONG i, j;
ULONG clus, next;
DSTRING file_path;
PWSTRING new_path;
PWSTRING current_path;
ULONG new_dir;
DSTRING filename;
DSTRING long_name;
HMEM hmem;
CLUSTER_CHAIN cluster;
ULONG new_chain;
ULONG cluster_size;
ULONG length;
DSTRING backslash;
DSTRING eafilename;
DSTRING eafilename_path;
DSTRING tmp_string;
BOOLEAN cross_link_detected;
ULONG cross_link_prevclus;
HMEM tmphmem;
FILEDIR tmpfiledir;
FAT_DIRENT tmpdirent1;
FAT_DIRENT tmpdirent2;
BOOLEAN non_zero_dirents;
HASH_INDEX file_name_hash_table;
ULONG hash_value;
PULONG matching_index_array;
ULONG matching_index_count;
BOOLEAN has_long_entry = FALSE;
UCHAR chksum;
BOOLEAN broke;
ULONG first_long_entry;
FAT_DIRENT dirent2;
ULONG percent;
ULONG allocated_clusters;
BOOLEAN processing_ea_file;
ULONG old_clus;
ULONG new_clus;
UCHAR FatType;
USHORT numEasLeft = *NumEas;
DEBUG((D_INFO, (CHAR8*)"Sizeof(INT) %x\n", sizeof(INT)));
// find no clue for the following assert
// DebugAssert(sizeof(PUCHAR) <= sizeof(INT));
DebugAssert(sizeof(USHORT) <= sizeof(INT));
DebugAssert(sizeof(ULONG ) <= sizeof(INT));
visit_list = NULL;
cluster_size = _drive->QuerySectorSize()*QuerySectorsPerCluster();
if (!backslash.Initialize("\\") ||
!eafilename.Initialize("EA DATA. SF") ||
!eafilename_path.Initialize("\\EA DATA. SF")) {
return FALSE;
}
if (!(current_path = NEW DSTRING) ||
!current_path->Initialize(&backslash)) {
return FALSE;
}
if (!PushVisitDir( &visit_list, 0, current_path )) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
Message->Set(MSG_CHK_CHECKING_FILES);
Message->Display();
percent = 0;
if(!DisplayTwnkPercent(percent)) {
return FALSE;
}
for (;
PopVisitDir( &visit_list, ¤t_dir, ¤t_path );
DELETE( current_path )) {
DoTwinkle();
has_long_entry = FALSE;
if (current_dir) {
if (!hmem.Initialize() ||
!filedir.Initialize(&hmem, _drive, this, _fat, current_dir)) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
if (!filedir.Read()) {
Message->Set(MSG_BAD_DIR_READ);
Message->Display();
return FALSE;
}
dir = &filedir;
} else {
if ( _dir ) {
dir = _dir;
FatType = FAT_TYPE_EAS_OKAY;
} else {
dir = _dirF32;
FatType = FAT_TYPE_FAT32;
}
}
if (!file_name_hash_table.Initialize(dir->QueryNumberOfEntries(), 10)) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
for (i = (current_dir ? 2 : 0); ; i++) {
if (!dirent.Initialize(dir->GetDirEntry(i), FatType) ||
dirent.IsEndOfDirectory()) {
if (has_long_entry) {
//
// There was an orphaned lfn at the end of the
// directory. Erase it now.
//
Report->ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_BAD_LONG_NAME);
Message->Display( "%W", current_path );
EraseAssociatedLongName(dir, first_long_entry, i);
has_long_entry = FALSE;
}
//
// This code must make sure that all other directory
// entries are end of directory entries.
//
non_zero_dirents = FALSE;
for (; dirent.Initialize(dir->GetDirEntry(i),FatType); i++) {
if (!dirent.IsEndOfDirectory()) {
non_zero_dirents = TRUE;
dirent.SetEndOfDirectory();
}
}
if (non_zero_dirents) {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_TRAILING_DIRENTS);
Message->Display("%W", current_path);
Report->ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
}
break;
}
if (dirent.IsErased()) {
if (has_long_entry) {
//
// The preceding lfn is orphaned. Remove it.
//
Report->ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_BAD_LONG_NAME);
Message->Display( "%W", current_path );
EraseAssociatedLongName(dir, first_long_entry, i);
has_long_entry = FALSE;
}
continue;
}
if (dirent.IsLongEntry()) {
// skip long name entries; come back to them later
if (has_long_entry) {
// already amid long entry
continue;
}
// first long entry
has_long_entry = TRUE;
first_long_entry = i;
continue;
}
dirent.QueryName(&filename);
if (has_long_entry) {
DSTRING lfn;
//
// The current entry is short, and we've just finished
// skipping the associated long entry. Look back through
// the long entries, make sure they're okay.
//
broke = FALSE;
chksum = dirent.QueryChecksum();
for (j = i - 1; j >= first_long_entry; j--) {
dirent2.Initialize(dir->GetDirEntry(j),FatType);
if (!dirent2.IsLongNameEntry()) {
continue;
}
broke = (dirent2.QueryLongOrdinal() != i - j) ||
(dirent2.QueryChecksum() != chksum) ||
(LOUSHORT(dirent2.QueryStartingCluster()) != 0);
broke = broke || !dirent2.IsWellTerminatedLongNameEntry();
if (broke || dirent2.IsLastLongEntry()) {
break;
}
}
broke = broke || (!dirent2.IsLastLongEntry());
#if 0
// We'll elide this code because Win95 isn't this strict and we
// don't want to delete all their lfn's.
if (!broke && dir->QueryLongName(i, &lfn)) {
broke = !dirent.NameHasTilde() &&
(dirent.NameHasExtendedChars() ||
0 != filename.Stricmp(&lfn)) &&
!IsString8Dot3(&lfn);
}
#endif
if (broke) {
Report->ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
//
// Erase all the long name entries.
//
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_BAD_LONG_NAME);
Message->Display( "%W", current_path );
EraseAssociatedLongName(dir, first_long_entry, i);
has_long_entry = FALSE;
}
//
// Fall into code to check short name.
//
}
DoTwinkle();
dirent.QueryName(&filename);
if (!file_path.Initialize(current_path)) {
return FALSE;
}
if (current_dir) {
if (!file_path.Strcat(&backslash)) {
return FALSE;
}
}
if (dir->QueryLongName(i, &long_name) &&
long_name.QueryChCount() != 0) {
if (!file_path.Strcat(&long_name)) {
return FALSE;
}
} else {
if (!file_path.Strcat(&filename)) {
return FALSE;
}
}
if (Verbose && !dirent.IsVolumeLabel()) {
Message->Set(MSG_CHK_FILENAME);
Message->Display("%W", &file_path);
}
if (!ValidateDirent(&dirent, &file_path, FixLevel, RecoverAlloc,
Message, NeedErrorsMessage, FatBitMap,
&cross_link_detected, &cross_link_prevclus,
&Report->ExitStatus)) {
return FALSE;
}
DoTwinkle();
if (dirent.IsErased()) {
//
// ValidateDirent erased this entry, presumably because it's
// hosed. Remove corresponding long name, if any.
//
if (has_long_entry) {
EraseAssociatedLongName(dir, first_long_entry, i);
has_long_entry = FALSE;
}
continue;
}
//
// Analyze for duplicate names
//
if (!dirent.IsVolumeLabel()) {
BOOLEAN renamed = FALSE;
ULONG renaming_positions = 0;
FAT_DIRENT temp_dirent;
DSTRING new_filename;
BOOLEAN changes = FALSE;
if (!CheckAndFixFileName(dir->GetDirEntry(i), &changes)) {
Message->Set(MSG_CHK_UNHANDLED_INVALID_NAME);
Message->Display("%W%W", &filename, current_path);
}
for (;;) {
hash_value = ComputeFileNameHashValue(dir->GetDirEntry(i));
if (!file_name_hash_table.QueryAndAdd(hash_value,
i,
&matching_index_array,
&matching_index_count)) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
DebugAssert(matching_index_count >= 1);
matching_index_count--;
if (matching_index_count &&
IsFileNameMatch(dir, FatType, i, matching_index_count, matching_index_array)) {
file_name_hash_table.RemoveLastEntry(hash_value, i);
Report->ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
renamed = TRUE;
if (!RenameFileName(&renaming_positions, dir->GetDirEntry(i))) {
if (!temp_dirent.Initialize(dir->GetDirEntry(i), FatType)) {
if (!new_filename.Initialize(TEXT("????????.???"))) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
} else
temp_dirent.QueryName(&new_filename); // bugbug: should have return code
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_RENAMING_FAILURE);
Message->Display("%W%W%W", &filename, current_path, &new_filename);
if (!filename.Initialize(&new_filename)) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
if (!file_path.Initialize(current_path)) {
return FALSE;
}
if (current_dir) {
if (!file_path.Strcat(&backslash)) {
return FALSE;
}
}
if (dir->QueryLongName(i, &long_name) &&
long_name.QueryChCount() != 0) {
if (!file_path.Strcat(&long_name)) {
return FALSE;
}
} else {
if (!file_path.Strcat(&new_filename)) {
return FALSE;
}
}
break; // done
}
} else if (renamed) {
if (!temp_dirent.Initialize(dir->GetDirEntry(i), FatType)) {
if (!new_filename.Initialize(TEXT("????????.???"))) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
} else
temp_dirent.QueryName(&new_filename); // bugbug: should have return code
Report->ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_RENAMED_REPEATED_ENTRY);
Message->Display("%W%W%W", &filename, current_path, &new_filename);
if (!filename.Initialize(&new_filename)) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
if (!file_path.Initialize(current_path)) {
return FALSE;
}
if (current_dir) {
if (!file_path.Strcat(&backslash)) {
return FALSE;
}
}
if (dir->QueryLongName(i, &long_name) &&
long_name.QueryChCount() != 0) {
if (!file_path.Strcat(&long_name)) {
return FALSE;
}
} else {
if (!file_path.Strcat(&new_filename)) {
return FALSE;
}
}
break; // no more conflict, done
} else if (changes) {
Report->ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_INVALID_NAME_CORRECTED);
Message->Display("%W%W", &filename, current_path);
break; // done
} else
break; // done as there is no name conflict
DoTwinkle();
}
}
DoTwinkle();
//
// Analyze for cross-links.
//
if (cross_link_detected) { // CROSSLINK !!
Report->ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
// Identify cross linked cluster.
clus = cross_link_prevclus;
next = cross_link_prevclus ?
_fat->QueryEntry(cross_link_prevclus) :
dirent.QueryStartingCluster();
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CROSS_LINK);
Message->Display("%W%d", &file_path, next);
processing_ea_file = (eafilename_path == file_path);
if (dirent.IsDirectory()) {
DebugAssert(!processing_ea_file);
Message->Set(MSG_CHK_DIR_TRUNC);
Message->Display();
if (clus) {
_fat->SetEndOfChain(clus);
} else {
dirent.SetErased();
if (has_long_entry) {
EraseAssociatedLongName(dir, first_long_entry, i);
has_long_entry = FALSE;
}
continue;
}
} else {
if (!CopyClusters(next, &new_chain, FatBitMap,
FixLevel, Message)) {
return FALSE;
}
if (new_chain) {
Message->Set(MSG_CHK_CROSS_LINK_COPY);
Message->Display();
if (processing_ea_file) {
USHORT j;
old_clus = next;
new_clus = new_chain;
for(;;) {
for (j=0; j<*NumEas; j++) {
if (EaInfos[j].PreceedingCn == old_clus) {
EaInfos[j].PreceedingCn = new_clus;
} else if (EaInfos[j].LastCn == old_clus) {
EaInfos[j].LastCn = new_clus;
}
}
if (_fat->IsEndOfChain(new_clus) || _fat->IsEndOfChain(old_clus)) {
DebugAssert(_fat->IsEndOfChain(new_clus) &&
_fat->IsEndOfChain(old_clus));
break;
}
old_clus = _fat->QueryEntry(old_clus);
new_clus = _fat->QueryEntry(new_clus);
}
}
if (clus) {
_fat->SetEntry(clus, new_chain);
} else {
dirent.SetStartingCluster(new_chain);
}
} else {
Message->Set(MSG_CHK_CROSS_LINK_TRUNC);
Message->Display();
if (clus) {
if (processing_ea_file) {
USHORT j;
old_clus = next;
for(;;) {
for (j=0; j<*NumEas; j++) {
if (EaInfos[j].LastCn == old_clus) {
numEasLeft = j;
break;
}
}
if (_fat->IsEndOfChain(old_clus))
break;
old_clus = _fat->QueryEntry(old_clus);
}
}
_fat->SetEndOfChain(clus);
dirent.SetFileSize(
cluster_size*_fat->QueryLengthOfChain(
dirent.QueryStartingCluster()));
} else {
numEasLeft = 0;
dirent.SetErased();
if (has_long_entry) {
EraseAssociatedLongName(dir, first_long_entry,
i);
has_long_entry = FALSE;
}
}
}
}
}
DoTwinkle();
if (!ValidateEaHandle(&dirent, current_dir, i, EaInfos, *NumEas,
&file_path, FixLevel, Message,
NeedErrorsMessage)) {
return FALSE;
}
DoTwinkle();
//
// Do special stuff if the current entry is a directory.
//
if (dirent.IsDirectory()) {
new_dir = dirent.QueryStartingCluster();
//
// Validate the integrity of the directory.
//
// Very first make sure it actually has a valid starting clus (check for 0)
if(!(_fat->IsInRange(new_dir))) {
if (dirent.IsDot() ||
dirent.IsDotDot()) {
// If this happens on the . or .. entry just ignore it as it will
// get fixed up later.
continue;
}
Message->Set(MSG_CHK_ERROR_IN_DIR);
Message->Display("%W", &file_path);
Message->Set(MSG_CHK_CONVERT_DIR_TO_FILE, NORMAL_MESSAGE, TEXT_MESSAGE);
Message->Display();
if (Message->IsYesResponse(TRUE)) {
dirent.ResetDirectory();
dirent.SetStartingCluster(0);
dirent.SetFileSize(0);
}
continue;
}
// Read the directory.
if (!tmphmem.Initialize() ||
!tmpfiledir.Initialize(&tmphmem, _drive, this, _fat,
new_dir) ||
!tmpfiledir.Read()) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
// Check the . and .. entries.
if (!tmpdirent1.Initialize(tmpfiledir.GetDirEntry(0),FatType) ||
!tmpdirent2.Initialize(tmpfiledir.GetDirEntry(1),FatType)) {
DebugAbort("GetDirEntry of 0 and 1 failed!");
return FALSE;
}
if (!tmpdirent1.IsDot() ||
!tmpdirent2.IsDotDot() ||
!tmpdirent1.IsDirectory() ||
!tmpdirent2.IsDirectory()) {
Report->ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_ERROR_IN_DIR);
Message->Display("%W", &file_path);
Message->Set(MSG_CHK_CONVERT_DIR_TO_FILE, NORMAL_MESSAGE, TEXT_MESSAGE);
Message->Display();
if (Message->IsYesResponse(TRUE)) {
dirent.ResetDirectory();
dirent.SetFileSize(
_fat->QueryLengthOfChain(new_dir)*
cluster_size);
} else {
FreeSpaceInBitmap(dirent.QueryStartingCluster(),
_fat, FatBitMap);
dirent.SetErased();
if (has_long_entry) {
EraseAssociatedLongName(dir, first_long_entry, i);
has_long_entry = FALSE;
}
continue;
}
} else { // Directory looks valid.
if (tmpdirent1.QueryStartingCluster() != new_dir ||
tmpdirent2.QueryStartingCluster() != current_dir ||
tmpdirent1.QueryFileSize() ||
tmpdirent2.QueryFileSize()) {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_ERRORS_IN_DIR_CORR);
Message->Display("%W", &file_path);
Report->ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
tmpdirent1.SetStartingCluster(new_dir);
tmpdirent2.SetStartingCluster(current_dir);
tmpdirent1.SetFileSize(0);
tmpdirent2.SetFileSize(0);
if (FixLevel != CheckOnly && !tmpfiledir.Write()) {
DebugAbort("Could not write tmp file dir.");
return FALSE;
}
}
// Add the directory to the list of directories
// to validate.
if (!(new_path = NEW DSTRING) ||
!new_path->Initialize(&file_path)) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
if (!PushVisitDir( &visit_list, new_dir, new_path )) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
}
}
//
// Generate report stats.
//
if (current_dir || !(filename == eafilename)) {
length = _fat->QueryLengthOfChain(dirent.QueryStartingCluster());
if (dirent.IsHidden()) {
Report->HiddenEntriesCount++;
Report->HiddenClusters += length;
} else if (dirent.IsDirectory()) {
Report->DirEntriesCount++;
Report->DirClusters += length;
} else if (!dirent.IsVolumeLabel()) {
Report->FileEntriesCount++;
Report->FileClusters += length;
}
}
allocated_clusters = _fat->QueryAllocatedClusterCount();
if (0 == allocated_clusters) {
allocated_clusters++; // Prevent divide by 0
}
percent = (Report->HiddenClusters + Report->DirClusters +
Report->FileClusters) * 100 / allocated_clusters;
if(!DisplayTwnkPercent(percent)) {
return FALSE;
}
has_long_entry = FALSE;
}
file_name_hash_table.DumpHashTable();
#if 0
//
// The following line should be moved to REAL_FAT_SA::Write.
//
//
// The placement of the following line actually touches upon
// the philosophical dilemma of what makes a superarea a superarea.
// In the good old FAT16/12 days when the root directory is a fixed size
// structure and sitting right next to the fat and boot sector, it kind
// of makes sense to define the superarea as a run of sectors including the
// the root directory. But now that the FAT32 root directory is defined
// as a cluster chain, is the superarea still an area (or a run of sectors
// as a matter of fact) by including the FAT32 root directory?(Rhetorical
// question) Hence I can sort of understand why the following line
// is placed where it is originally (but this is an incomplete job
// considering the fact that the FAT32 root directory is still part of
// the superarea object). So in order to honor the fine tradition of
// totally embedding the root directory into the superarea, I have decided
// to move the following line to the Write method of the FAT superarea
// object. The proper way out of this dilemma is to define the superarea
// as a persistent object which is not necessarily a contagious run of
// sectors. (I think I get a little bit carried away.)
//
if((_dirF32) && !(current_dir)) { //root directory fix
if (FixLevel != CheckOnly && !_dirF32->Write()) {
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
}
#endif
if (current_dir) {
if (FixLevel != CheckOnly && !filedir.Write()) {
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
}
}
percent = 100;
if(!DisplayTwnkPercent(percent)) {
_Verbose = FALSE;
_pvfMessage = NULL;
return FALSE;
}
Message->Set(MSG_CHK_DONE_CHECKING);
Message->Display();
*NumEas = numEasLeft;
_Verbose = FALSE;
_pvfMessage = NULL;
return TRUE;
}
BOOLEAN
FAT_SA::ValidateDirent(
IN OUT PFAT_DIRENT Dirent,
IN PCWSTRING FilePath,
IN FIX_LEVEL FixLevel,
IN BOOLEAN RecoverAlloc,
IN OUT PMESSAGE Message,
IN OUT PBOOLEAN NeedErrorsMessage,
IN OUT PBITVECTOR FatBitMap,
OUT PBOOLEAN CrossLinkDetected,
OUT PULONG CrossLinkPreviousCluster,
OUT PULONG ExitStatus
)
/*++
Routine Description:
This routine verifies that all components of a directory entry are
correct. If the time stamps are invalid then they will be corrected
to the current time. If the filename is invalid then the directory
entry will be marked as deleted. If the cluster number is out of
disk range then the directory entry will be marked as deleted.
Otherwise, the cluster chain will be validated and the length of
the cluster chain will be compared against the file size. If there
is a difference then the file size will be corrected.
If there are any strange errors then FALSE will be returned.
Arguments:
Dirent - Supplies the directory entry to validate.
FilePath - Supplies the full path name for the directory
entry.
RecoverAlloc - Supplies whether or not to recover all
allocated space on the volume.
Message - Supplies an outlet for messages.
NeedErrorsMessage - Supplies whether or not an error has
occurred during check only mode.
FatBitMap - Supplies a bitmap marking in use all known
clusters.
CrossLinkDetected - Returns TRUE if the file is cross-linked with
another.
CrossLinkPreviousCluster - Returns the cluster previous to the
cross-linked one.
Return Value:
FALSE - Failure.
TRUE - Success.
--*/
{
ULONG start_clus;
BOOLEAN changes;
ULONG length;
ULONG min_file_size;
ULONG max_file_size;
ULONG clus;
BIG_INT tmp_big_int;
ULONG file_size;
ULONG cluster_size;
BOOLEAN recover_status;
DebugAssert(CrossLinkDetected);
DebugAssert(CrossLinkPreviousCluster);
*CrossLinkDetected = FALSE;
if (Dirent->IsErased()) {
return TRUE;
}
cluster_size = _drive->QuerySectorSize()*QuerySectorsPerCluster();
// Don't validate names or time stamps anymore.
#if 0
if (!Dirent->IsValidName()) {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_INVALID_NAME);
Message->Display("%W", FilePath);
Dirent->SetErased();
return TRUE;
}
if (!Dirent->IsValidTimeStamp()) {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_INVALID_TIME_STAMP);
Message->Display("%W", FilePath);
if (!Dirent->SetTimeStamp()) {
return FALSE;
}
}
#endif
if (Dirent->IsDirectory() && Dirent->QueryFileSize()) {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_DIR_HAS_FILESIZE);
Message->Display("%W", FilePath);
Dirent->SetFileSize( 0 );
*ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
}
if ((start_clus = Dirent->QueryStartingCluster()) != 0 ) {
if (!_fat->IsInRange(start_clus) || _fat->IsClusterFree(start_clus)) {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_BAD_FIRST_UNIT);
Message->Display("%W", FilePath);
Dirent->SetErased();
*ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
return TRUE;
}
if (Dirent->IsDirectory() || RecoverAlloc) {
_fat->ScrubChain(start_clus, &changes);
if (changes) {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_BAD_LINK);
Message->Display("%W", FilePath);
*ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
}
//
// Validate the readability of the directory or file
// in the case that 'RecoverAlloc' is TRUE.
//
if (Dirent->IsDirectory()) {
if (!(recover_status = RecoverChain(&start_clus, &changes))) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
} else if (FixLevel != CheckOnly) {
// If we check the recover status for directory, why shouldn't we check
// the recover status for file also? (I added the following check.)
if (!(recover_status = RecoverChain(&start_clus, &changes, 0, TRUE))) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
} else {
recover_status = TRUE;
changes = FALSE;
}
if (changes) {
*ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
dofmsg(Message, NeedErrorsMessage);
if (Dirent->IsDirectory()) {
if (!start_clus) {
Message->Set(MSG_CHK_BAD_DIR);
Message->Display("%W", FilePath);
Dirent->SetErased();
return TRUE;
} else {
Message->Set(MSG_CHK_BAD_CLUSTERS_IN_DIR);
Message->Display("%W", FilePath);
Dirent->SetStartingCluster(start_clus);
}
} else {
// In the file case, since we're replacing bad clusters
// with new ones, start_clus cannot be zero.
DebugAssert(start_clus);
if (recover_status) {
Message->Set(MSG_CHK_BAD_CLUSTERS_IN_FILE_SUCCESS);
Message->Display("%W", FilePath);
} else {
Message->Set(MSG_CHK_BAD_CLUSTERS_IN_FILE_FAILURE);
Message->Display();
}
Dirent->SetStartingCluster(start_clus);
}
}
}
_fat->ScrubChain(start_clus, FatBitMap, &changes,
CrossLinkDetected, CrossLinkPreviousCluster);
if (changes) {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_BAD_LINK);
Message->Display("%W", FilePath);
*ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
}
// Note here that we know here that start_clus != 0 so length will be
// at least 1.
tmp_big_int = length = _fat->QueryLengthOfChain(start_clus);
tmp_big_int = tmp_big_int * cluster_size;
if (tmp_big_int.GetHighPart()) {
if ((tmp_big_int.GetHighPart() != 1) || tmp_big_int.GetLowPart()) {
//
// Cluster chain is > 4GB in size, error. Max allowed is 4GB worth
// of clusters. Note that since cluster size is a power of 2 (since
// sec/clus and sector_size are both powers of 2) we KNOW that cluster_size
// evenly divides 4GB.
//
clus = start_clus;
tmp_big_int = cluster_size;
while(tmp_big_int.GetHighPart() == 0) {
clus = _fat->QueryEntry(clus);
tmp_big_int += cluster_size;
}
_fat->SetEndOfChain(clus);
// This message is not exactly correct, but saying that the file size
// is messed up is not totally unreasonable..........
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_BAD_FILE_SIZE);
Message->Display("%W", FilePath);
Dirent->SetFileSize(0xFFFFFFFF);
*ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
}
max_file_size = 0xFFFFFFFF;
min_file_size = (0xFFFFFFFF - cluster_size) + 2;
} else {
max_file_size = tmp_big_int.GetLowPart();
min_file_size = (max_file_size - cluster_size) + 1;
}
if (( file_size = Dirent->QueryFileSize()) != 0 ) {
if (file_size < min_file_size ||
file_size > max_file_size) {
//
// Note that no message is displayed if the
// file size is less than the allocation--it
// is just silently corrected.
//
if (file_size > max_file_size) {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_BAD_FILE_SIZE);
Message->Display("%W", FilePath);
}
Dirent->SetFileSize(max_file_size);
*ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
}
} else {
if (!Dirent->IsDirectory()) {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_BAD_FILE_SIZE);
Message->Display("%W", FilePath);
Dirent->SetFileSize(max_file_size);
*ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
}
}
} else {
if (Dirent->IsDirectory() && !Dirent->IsDotDot()) {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_BAD_LINK);
Message->Display("%W", FilePath);
Dirent->SetErased();
*ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
return TRUE;
}
if (Dirent->QueryFileSize()) {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_BAD_FILE_SIZE);
Message->Display("%W", FilePath);
Dirent->SetFileSize(0);
*ExitStatus = CHKDSK_EXIT_ERRS_FIXED;
}
}
return TRUE;
}
BOOLEAN
FAT_SA::EraseEaHandle(
IN PEA_INFO EaInfos,
IN USHORT NumEasLeft,
IN USHORT NumEas,
IN FIX_LEVEL FixLevel,
IN OUT PMESSAGE Message
)
/*++
Routine Description:
This routine erases the EA handle that references ea set beyond the
number of ea sets that should be left.
Arguments:
EaInfos - Supplies the list of current EA information.
NumEasLeft - Supplies the number of EA sets that should be in EaInfos.
NumEas - Supplies the total number of EA sets.
FixLevel - Supplies the fix up level.
Message - Supplies an outlet for messages.
Return Value:
FALSE - Failure.
TRUE - Success.
--*/
{
HMEM hmem;
FILEDIR filedir;
FAT_DIRENT other_dirent;
USHORT i;
for (i=NumEasLeft; i<NumEas; i++) {
if (EaInfos[i].UserFileEntryCn) {
if (!hmem.Initialize() ||
!filedir.Initialize(&hmem, _drive, this, _fat,
EaInfos[i].UserFileEntryCn) ||
!filedir.Read() ||
!other_dirent.Initialize(filedir.GetDirEntry(
EaInfos[i].UserFileEntryNumber), FAT_TYPE_EAS_OKAY)) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
} else {
if (!other_dirent.Initialize(_dir->GetDirEntry(
// Default _dir works because FAT 32 won't have EA's on it to validate
EaInfos[i].UserFileEntryNumber), FAT_TYPE_EAS_OKAY)) {
return FALSE;
}
}
//
// Do not follow an EA link to an LFN entry. Zeroing the EA handle in an LFN entry
// destroys name data. The link is probably just invalid
//
if (!other_dirent.IsLongNameEntry()) {
other_dirent.SetEaHandle(0);
if (EaInfos[i].UserFileEntryCn && FixLevel != CheckOnly &&
!filedir.Write()) {
return FALSE;
}
}
}
return TRUE;
}
BOOLEAN
FAT_SA::ValidateEaHandle(
IN OUT PFAT_DIRENT Dirent,
IN ULONG DirClusterNumber,
IN ULONG DirEntryNumber,
IN OUT PEA_INFO EaInfos,
IN USHORT NumEas,
IN PCWSTRING FilePath,
IN FIX_LEVEL FixLevel,
IN OUT PMESSAGE Message,
IN OUT PBOOLEAN NeedErrorsMessage
)
/*++
Routine Description:
This routine validates the EA handle in the directory entry 'Dirent'.
It ensures that it references an actual EA set. It also ensures
that it is the only directory entry which references the EA set.
If several entries try to reference the same EA set then ties will
be broken based on the 'OwnerFileName' entry in the EA set.
Arguments:
Dirent - Supplies the directory entry to validate.
DirClusterNumber - Supplies the cluster number of the directory
containing the dirent.
DirEntryNumber - Supplies the position of the directory entry in
the directory.
EaInfos - Supplies the list of current EA information.
NumEas - Supplies the number of EA sets.
FilePath - Supplies the full path name for the directory entry.
FixLevel - Supplies the fix up level.
Message - Supplies an outlet for messages.
NeedErrorsMessage - Supplies whether or not an error has occurred
during check only mode.
Return Value:
FALSE - Failure.
TRUE - Success.
--*/
{
ULONG i;
USHORT handle;
DSTRING wfilename;
STR filename[14];
BOOLEAN remove_other_handle;
HMEM hmem;
FILEDIR filedir;
FAT_DIRENT other_dirent;
if (!(handle = Dirent->QueryEaHandle())) {
return TRUE;
}
// The above should exclude any FAT 32 drive.
if (!EaInfos) {
NumEas = 0;
}
for (i = 0; i < NumEas; i++) {
if (handle == EaInfos[i].OwnHandle) {
break;
}
}
if (i == NumEas) {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_UNRECOG_EA_HANDLE);
Message->Display("%W", FilePath);
Dirent->SetEaHandle(0);
return TRUE;
}
if (EaInfos[i].UsedCount >= 2) {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_SHARED_EA);
Message->Display("%W", FilePath);
Dirent->SetEaHandle(0);
return TRUE;
}
Dirent->QueryName(&wfilename);
if (!wfilename.QuerySTR( 0, TO_END, filename, 14)) {
return FALSE;
}
if (EaInfos[i].UsedCount == 0) {
memcpy(EaInfos[i].UserFileName, filename, 14);
EaInfos[i].UserFileEntryCn = DirClusterNumber;
EaInfos[i].UserFileEntryNumber = DirEntryNumber;
EaInfos[i].UsedCount = 1;
return TRUE;
}
// UsedCount == 1.
remove_other_handle = FALSE;
if (!strcmp(filename, EaInfos[i].OwnerFileName)) {
remove_other_handle = TRUE;
if (!strcmp(EaInfos[i].UserFileName,
EaInfos[i].OwnerFileName)) {
EaInfos[i].UsedCount = 2;
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_SHARED_EA);
Message->Display("%W", FilePath);
Dirent->SetEaHandle(0);
}
} else {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_SHARED_EA);
Message->Display("%W", FilePath);
Dirent->SetEaHandle(0);
if (strcmp(EaInfos[i].UserFileName,
EaInfos[i].OwnerFileName)) {
EaInfos[i].UsedCount = 2;
remove_other_handle = TRUE;
}
}
if (remove_other_handle) {
if (EaInfos[i].UserFileEntryCn) {
if (!hmem.Initialize() ||
!filedir.Initialize(&hmem, _drive, this, _fat,
EaInfos[i].UserFileEntryCn) ||
!filedir.Read() ||
!other_dirent.Initialize(filedir.GetDirEntry(
EaInfos[i].UserFileEntryNumber), FAT_TYPE_EAS_OKAY)) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
} else {
if (!other_dirent.Initialize(_dir->GetDirEntry(
// Default _dir works because FAT 32 won't have EA's on it to validate
EaInfos[i].UserFileEntryNumber), FAT_TYPE_EAS_OKAY)) {
return FALSE;
}
}
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_SHARED_EA);
Message->Display("%W", FilePath);
//
// Do not follow an EA link to an LFN entry. Zeroing the EA handle in an LFN entry
// destroys name data. The link is probably just invalid
//
if (!other_dirent.IsLongNameEntry()) {
other_dirent.SetEaHandle(0);
if (EaInfos[i].UserFileEntryCn && FixLevel != CheckOnly &&
!filedir.Write()) {
return FALSE;
}
}
strcpy(EaInfos[i].UserFileName, filename);
EaInfos[i].UserFileEntryCn = DirClusterNumber;
EaInfos[i].UserFileEntryNumber = DirEntryNumber;
}
return TRUE;
}
BOOLEAN
FAT_SA::CopyClusters(
IN ULONG SourceChain,
OUT PULONG DestChain,
IN OUT PBITVECTOR FatBitMap,
IN FIX_LEVEL FixLevel,
IN OUT PMESSAGE Message
)
/*++
Routine Description:
This routine copies the cluster chain beginning at 'SourceChain'
to a free portion of the disk. The beginning of the copied chain
will be returned in 'DestChain'. If there isn't enough free space
on the disk to copy the chain then 'DestChain' will return 0.
Arguments:
SourceChain - Supplies the chain to copy.
DestChain - Returns the copy of the chain.
FatBitMap - Supplies the orphan and cross-link bitmap.
FixLevel - Supplies the CHKDSK fix level.
Message - Supplies an outlet for messages
Return Value:
FALSE - Failure.
TRUE - Success.
--*/
{
HMEM hmem;
CLUSTER_CHAIN cluster;
ULONG src, dst;
BOOLEAN changes;
ULONG clus;
if (!hmem.Initialize()) {
return FALSE;
}
if (!(*DestChain = _fat->AllocChain(
_fat->QueryLengthOfChain(SourceChain)))) {
return TRUE;
}
changes = FALSE;
if (FixLevel != CheckOnly && !RecoverChain(DestChain, &changes, 0, TRUE)) {
if (*DestChain) {
_fat->FreeChain(*DestChain);
}
*DestChain = 0;
return TRUE;
}
if (IsCompressed() && !AllocSectorsForChain(*DestChain)) {
_fat->FreeChain(*DestChain);
*DestChain = 0;
return TRUE;
}
// Mark the new chain as "used" in the FAT bitmap.
for (clus = *DestChain;
!_fat->IsEndOfChain(clus);
clus = _fat->QueryEntry(clus)) {
FatBitMap->SetBit(clus);
}
FatBitMap->SetBit(clus);
src = SourceChain;
dst = *DestChain;
for (;;) {
if (!cluster.Initialize(&hmem, _drive, this, _fat, src, 1)) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
cluster.Read();
if (!cluster.Initialize(&hmem, _drive, this, _fat, dst, 1)) {
return FALSE;
}
if (FixLevel != CheckOnly && !cluster.Write()) {
return FALSE;
}
if (_fat->IsEndOfChain(src)) {
break;
}
src = _fat->QueryEntry(src);
dst = _fat->QueryEntry(dst);
}
return TRUE;
}
BOOLEAN
FAT_SA::PurgeEaFile(
IN PEA_INFO EaInfos,
IN USHORT NumEas,
IN OUT PBITVECTOR FatBitMap,
IN FIX_LEVEL FixLevel,
IN OUT PMESSAGE Message,
IN OUT PBOOLEAN NeedErrorsMessage
)
/*++
Routine Description:
This routine is executed after the directory tree is walked. Stored,
in the EaInfos array, is information concerning which EAs get used
and by how many files.
If an EA set is not used, or is used by more than one file, then this
routine will eliminate it from the EA file.
Arguments:
EaInfos - Supplies an array of EA information.
NumEas - Supplies the number of EA sets.
FatBitMap - Supplies the FAT cross-link detection bitmap.
FixLevel - Supplies the CHKDSK fix level.
Message - Supplies an outlet for messages.
NeedErrorsMessage - Supplies whether or not an error has occured
in check only mode.
Return Value:
FALSE - Failure.
TRUE - Success.
--*/
{
LONG i;
EA_SET easet;
HMEM hmem;
PEA_HDR eahdr;
ULONG clus;
if (!hmem.Initialize()) {
return FALSE;
}
for (i = NumEas - 1; i >= 0; i--) {
if (EaInfos[i].UsedCount != 1) {
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_UNUSED_EA_SET);
Message->Display("%d", EaInfos[i].OwnHandle);
// Mark the FAT entries of the removed chain as "not claimed",
// for the purposes of orphan recovery.
for (clus = _fat->QueryEntry(EaInfos[i].PreceedingCn);
clus != EaInfos[i].LastCn;
clus = _fat->QueryEntry(clus)) {
FatBitMap->ResetBit(clus);
}
FatBitMap->ResetBit(clus);
//
// Remove the unused EA chain from the EA file. Here we also
// have to examine subsequent EaInfos; we may have to modify
// several PreceedingCn entries if several adjacent EA chains
// have been removed.
//
_fat->RemoveChain(EaInfos[i].PreceedingCn,
EaInfos[i].LastCn);
for (LONG j = i + 2; j < NumEas; j++) {
if (EaInfos[j].PreceedingCn == EaInfos[i + 1].PreceedingCn) {
EaInfos[j].PreceedingCn = EaInfos[i].PreceedingCn;
} else {
break;
}
}
EaInfos[i + 1].PreceedingCn = EaInfos[i].PreceedingCn;
} else if (strcmp(EaInfos[i].OwnerFileName,
EaInfos[i].UserFileName)) {
if (!easet.Initialize(&hmem, _drive, this, _fat,
_fat->QueryEntry(EaInfos[i].PreceedingCn),
1) ||
!easet.Read() ||
!(eahdr = easet.GetEaSetHeader())) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_NEW_OWNER_NAME);
Message->Display("%d%s%s", EaInfos[i].OwnHandle,
eahdr->OwnerFileName, EaInfos[i].UserFileName);
memcpy(eahdr->OwnerFileName, EaInfos[i].UserFileName, 14);
if (FixLevel != CheckOnly && !easet.Write()) {
return FALSE;
}
}
}
return TRUE;
}
BOOLEAN
FAT_SA::RecoverOrphans(
IN OUT PBITVECTOR FatBitMap,
IN FIX_LEVEL FixLevel,
IN OUT PMESSAGE Message,
IN OUT PBOOLEAN NeedErrorsMessage,
IN OUT PFATCHK_REPORT Report,
OUT PBOOLEAN Changes
)
/*++
Routine Description:
This routine examines the file system for cluster chains which are
not claimed by any file. These 'orphans' will then be recovered in
a subdirectory of the root or removed from the system.
Arguments:
FatBitMap - Supplies a bit map marking all currently used
clusters.
FixLevel - Supplies the CHKDSK fix level.
Message - Supplies an outlet for messages.
NeedErrorsMessage - Supplies whether or not an error has occured
in check only mode.
Return Value:
FALSE - Failure.
TRUE - Success.
--*/
{
//
// Why the below define placing an artificial limit on the number of orphans?
// 1.) The format for the file names is "FILE%04d.CHK" starting at 0 so we can
// do only 0-9999 before generating a duplicate file name.
// 2.) Since CHKDSK recovers all of the orphans into a single directory this prevents
// it from making a directory with a HUGE file count in it (which is a performance
// issue).
//
#if defined( _AUTOCHECK_ ) || defined( _EFICHECK_ )
// Due to memory constraints, the maximum number of orphans to
// recover is less for Autochk than for run-time Chkdsk.
//
// BUG BUG this is the old setting for this, the above comment makes no
// sense because there is no in memory allocation that I can find
// which is effected by this setting. This may have been a HACK fix
// for an overflow of the memory heap (which is fatal when there
// is no paging file). This problem no longer exists because of
// the paging memory heap tracking that has been added to AUTOCHK.
// ARR
//
// CONST ULONG maximum_orphans = 1000;
//
CONST ULONG maximum_orphans = 10000;
#else
CONST ULONG maximum_orphans = 10000;
#endif
ULONG i;
ULONG clus;
BOOLEAN changes;
HMEM hmem;
FILEDIR found_dir;
STR found_name[14];
DSTRING wfound_name;
STR filename[14];
FAT_DIRENT dirent;
ULONG found_cluster;
ULONG orphan_count;
ULONG orphan_rec_clus_cnt;
ULONG cluster_size;
ULONG found_length;
ULONG next;
PUCHAR orphan_track;
ULONG cluster_count;
ULONG num_orphans;
ULONG num_orphan_clusters;
DSTRING tmp_string;
BITVECTOR tmp_bitvector;
BOOLEAN tmp_bool;
ULONG tmp_ulong;
BIG_INT tmp_big_int;
MSGID message_id;
BOOLEAN KSize;
cluster_count = QueryClusterCount();
if (!(orphan_track = NEW UCHAR[cluster_count])) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
memset(orphan_track, 0, cluster_count);
if (!tmp_bitvector.Initialize(cluster_count)) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
cluster_size = _drive->QuerySectorSize()*QuerySectorsPerCluster();
num_orphans = 0;
num_orphan_clusters = 0;
for (i = FirstDiskCluster; _fat->IsInRange(i); i++) {
if (!_fat->IsClusterFree(i) &&
!FatBitMap->IsBitSet(i) &&
!_fat->IsClusterBad(i) &&
!_fat->IsClusterReserved(i)) {
num_orphans++;
tmp_bitvector.ResetAll();
_fat->ScrubChain(i, &tmp_bitvector, &changes,
&tmp_bool, &tmp_ulong);
if (changes) {
*Changes = TRUE;
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_BAD_LINKS_IN_ORPHANS);
Message->Display("%d", i);
}
num_orphan_clusters++;
clus = i;
while (!_fat->IsEndOfChain(clus)) {
next = _fat->QueryEntry(clus);
if (orphan_track[next] == 1) {
num_orphans--;
orphan_track[next] = 2;
break;
}
if (FatBitMap->IsBitSet(next)) { // CROSSLINK !!
*Changes = TRUE;
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CHK_CROSS_LINKED_ORPHAN);
Message->Display("%d", clus);
_fat->SetEndOfChain(clus);
break;
}
num_orphan_clusters++;
FatBitMap->SetBit(next);
orphan_track[next] = 2;
clus = next;
}
FatBitMap->SetBit(i);
orphan_track[i] = 1;
}
}
// Now scan through the secondary pointers in search of orphans.
changes = FALSE;
for (i = FirstDiskCluster; _fat->IsInRange(i); i++) {
if (orphan_track[i]) {
changes = TRUE;
break;
}
}
if (!changes) {
// No orphans to recover.
return TRUE;
}
// Compute whether reporting size in bytes or kilobytes
//
// NOTE: The magic number 4095MB comes from Win9x's GUI SCANDISK utility
//
tmp_ulong = cluster_count - FirstDiskCluster;
tmp_big_int = cluster_size;
tmp_big_int = tmp_big_int * tmp_ulong;
if (tmp_big_int.GetHighPart() || (tmp_big_int.GetLowPart() > (4095ul*1024ul*1024ul))) {
KSize = TRUE;
} else {
KSize = FALSE;
}
*Changes = TRUE;
dofmsg(Message, NeedErrorsMessage);
Message->Set(MSG_CONVERT_LOST_CHAINS, NORMAL_MESSAGE, TEXT_MESSAGE);
Message->Display();
if (!Message->IsYesResponse(TRUE)) {
if (FixLevel != CheckOnly) {
for (i = FirstDiskCluster; _fat->IsInRange(i); i++) {
if (orphan_track[i] == 1) {
_fat->FreeChain(i);
}
}
if (KSize) {
message_id = MSG_KILOBYTES_FREED;
} else {
message_id = MSG_BYTES_FREED;
}
} else {
if (KSize) {
message_id = MSG_KILOBYTES_WOULD_BE_FREED;
} else {
message_id = MSG_BYTES_WOULD_BE_FREED;
}
}
tmp_big_int = cluster_size;
tmp_big_int = tmp_big_int * num_orphan_clusters;
if (KSize) {
tmp_ulong = (tmp_big_int / 1024ul).GetLowPart();
} else {
tmp_ulong = tmp_big_int.GetLowPart();
}
Message->Set(message_id);
Message->Display("%d", tmp_ulong);
return TRUE;
}
// Set up for orphan recovery.
// Establish "FOUND.XXX" directory.
for (i = 0; i < 1000; i++) {
sprintf(found_name, "FOUND.%03d", i);
if (!wfound_name.Initialize(found_name)) {
return FALSE;
}
if (_dir && !_dir->SearchForDirEntry(&wfound_name)) {
break;
} else if (_dirF32 && !_dirF32->SearchForDirEntry(&wfound_name)) {
break;
}
}
if (i == 1000) {
tmp_big_int = cluster_size;
tmp_big_int = tmp_big_int * num_orphan_clusters;
if (KSize) {
tmp_ulong = (tmp_big_int / 1024ul).GetLowPart();
message_id = MSG_KILOBYTES_IN_WOULD_BE_RECOVERED_FILES;
} else {
tmp_ulong = tmp_big_int.GetLowPart();
message_id = MSG_WOULD_BE_RECOVERED_FILES;
}
Message->Set(message_id);
Message->Display("%d%d", tmp_ulong,
num_orphans);
return TRUE;
}
found_length = ((min(num_orphans,maximum_orphans)*BytesPerDirent - 1)/cluster_size + 1);
if (!(found_cluster = _fat->AllocChain(found_length)) &&
!(found_cluster = _fat->AllocChain(found_length = 1))) {
Message->Set(MSG_ORPHAN_DISK_SPACE);
Message->Display();
tmp_big_int = cluster_size;
tmp_big_int = tmp_big_int * num_orphan_clusters;
if (KSize) {
tmp_ulong = (tmp_big_int / 1024ul).GetLowPart();
message_id = MSG_KILOBYTES_IN_WOULD_BE_RECOVERED_FILES;
} else {
tmp_ulong = tmp_big_int.GetLowPart();
message_id = MSG_WOULD_BE_RECOVERED_FILES;
}
Message->Set(message_id);
Message->Display("%d%d", tmp_ulong,
num_orphans);
return TRUE;
}
// Check the chain.
changes = FALSE;
if (FixLevel != CheckOnly &&
!RecoverChain(&found_cluster, &changes, 0, TRUE)) {
Message->Set(MSG_ORPHAN_DISK_SPACE);
Message->Display();
Message->Set(MSG_WOULD_BE_RECOVERED_FILES);
Message->Display("%d%d", cluster_size*num_orphan_clusters,
num_orphans);
return TRUE;
}
if (!hmem.Initialize() ||
!found_dir.Initialize(&hmem, _drive, this, _fat, found_cluster)) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
DebugAbort( "Initialization failed" );
return FALSE;
}
// Allocate space for the cluster chain in the sector heap (fat_db)
if (IsCompressed() && !AllocSectorsForChain(found_cluster)) {
_fat->FreeChain(found_cluster);
Message->Set(MSG_ORPHAN_DISK_SPACE);
Message->Display();
return TRUE;
}
memset(hmem.GetBuf(), 0, (UINT) hmem.QuerySize());
PFATDIR _fat_dir;
UCHAR FatType;
if (_dir) {
_fat_dir = _dir;
FatType = FAT_TYPE_EAS_OKAY;
}
else {
_fat_dir = _dirF32;
FatType = FAT_TYPE_FAT32;
}
if (!dirent.Initialize(_fat_dir->GetFreeDirEntry(),FatType)) {
Message->Set(MSG_NO_ROOM_IN_ROOT);
Message->Display();
Message->Set(MSG_WOULD_BE_RECOVERED_FILES);
Message->Display("%d%d", cluster_size*num_orphan_clusters,
num_orphans);
return TRUE;
}
dirent.Clear();
if (!dirent.SetName(&wfound_name)) {
return FALSE;
}
dirent.SetDirectory();
if (!dirent.SetLastWriteTime() || !dirent.SetCreationTime() ||
!dirent.SetLastAccessTime()) {
return FALSE;
}
dirent.SetStartingCluster(found_cluster);
if(_dirF32) {
if (FixLevel != CheckOnly && !_dirF32->Write()) {
return FALSE;
}
}
if (!dirent.Initialize(found_dir.GetDirEntry(0),FatType)) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
dirent.Clear();
if (!tmp_string.Initialize(".")) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
if (!dirent.SetName(&tmp_string)) {
return FALSE;
}
dirent.SetDirectory();
if (!dirent.SetLastWriteTime() || !dirent.SetCreationTime() ||
!dirent.SetLastAccessTime()) {
return FALSE;
}
dirent.SetStartingCluster(found_cluster);
if (!dirent.Initialize(found_dir.GetDirEntry(1),FatType)) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
dirent.Clear();
if (!tmp_string.Initialize("..")) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
if (!dirent.SetName(&tmp_string)) {
return FALSE;
}
dirent.SetDirectory();
if (!dirent.SetLastWriteTime() || !dirent.SetCreationTime() ||
!dirent.SetLastAccessTime()) {
return FALSE;
}
dirent.SetStartingCluster(0);
// OK, now let's recover those orphans.
orphan_rec_clus_cnt = orphan_count = 0;
for (i = FirstDiskCluster; _fat->IsInRange(i); i++) {
if (orphan_track[i] != 1) {
continue;
}
if (orphan_count == maximum_orphans) {
Message->Set(MSG_TOO_MANY_ORPHANS);
Message->Display();
break;
}
if (!dirent.Initialize(found_dir.GetFreeDirEntry(), FatType)) {
if (_fat->ReAllocChain(found_cluster, ++found_length)
!= found_length) {
Message->Set(MSG_ORPHAN_DISK_SPACE);
Message->Display();
tmp_big_int = cluster_size;
tmp_big_int = tmp_big_int * num_orphan_clusters;
if (KSize) {
tmp_ulong = (tmp_big_int / 1024ul).GetLowPart();
message_id = MSG_KILOBYTES_IN_WOULD_BE_RECOVERED_FILES;
} else {
tmp_ulong = tmp_big_int.GetLowPart();
message_id = MSG_WOULD_BE_RECOVERED_FILES;
}
Message->Set(message_id);
Message->Display("%d%d", tmp_ulong,
num_orphans);
break;
}
//XXX: FATDB: need to get sectors for found_cluster + realloc.
changes = FALSE;
if (FixLevel != CheckOnly &&
!RecoverChain(&found_cluster, &changes, 0, TRUE)) {
Message->Set(MSG_ORPHAN_DISK_SPACE);
Message->Display();
tmp_big_int = cluster_size;
tmp_big_int = tmp_big_int * num_orphan_clusters;
if (KSize) {
tmp_ulong = (tmp_big_int / 1024ul).GetLowPart();
message_id = MSG_KILOBYTES_IN_WOULD_BE_RECOVERED_FILES;
} else {
tmp_ulong = tmp_big_int.GetLowPart();
message_id = MSG_WOULD_BE_RECOVERED_FILES;
}
Message->Set(message_id);
Message->Display("%d%d", tmp_ulong,
num_orphans);
return TRUE;
}
if (FixLevel != CheckOnly && !found_dir.Write()) {
return FALSE;
}
if (!hmem.Initialize() ||
!found_dir.Initialize(&hmem, _drive, this, _fat,
found_cluster) ||
!found_dir.Read()) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
Message->Set(MSG_WOULD_BE_RECOVERED_FILES);
Message->Display("%d%d", cluster_size*num_orphan_clusters,
num_orphans);
return TRUE;
}
if (!dirent.Initialize(found_dir.GetDirEntry(2 + orphan_count), FatType))
{
return FALSE;
}
dirent.SetEndOfDirectory();
if (!dirent.Initialize(found_dir.GetFreeDirEntry(),FatType))
{
return FALSE;
}
}
sprintf(filename, "FILE%04d.CHK", orphan_count);
if (!tmp_string.Initialize(filename)) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
return FALSE;
}
dirent.Clear();
if (!dirent.SetName(&tmp_string)) {
return FALSE;
}
if (!dirent.SetLastWriteTime() || !dirent.SetCreationTime() ||
!dirent.SetLastAccessTime()) {
return FALSE;
}
dirent.SetStartingCluster(i);
dirent.SetFileSize(cluster_size*_fat->QueryLengthOfChain(i));
orphan_count++;
orphan_rec_clus_cnt += _fat->QueryLengthOfChain(i);
}
// Set all dirents past the orphan count to end of directory.
for (i = 2 + orphan_count; dirent.Initialize(found_dir.GetDirEntry(i),FatType); i++)
{
dirent.SetEndOfDirectory();
}
if (FixLevel != CheckOnly && !found_dir.Write()) {
return FALSE;
}
if(FixLevel == CheckOnly) {
if (KSize) {
message_id = MSG_KILOBYTES_IN_WOULD_BE_RECOVERED_FILES;
} else {
message_id = MSG_WOULD_BE_RECOVERED_FILES;
}
} else {
if (KSize) {
message_id = MSG_KILOBYTES_IN_RECOVERED_FILES;
} else {
message_id = MSG_RECOVERED_FILES;
}
// Add the recovered data to the report totals
Report->FileClusters += orphan_rec_clus_cnt;
Report->FileEntriesCount += orphan_count;
Report->DirClusters += found_length;
Report->DirEntriesCount++;
}
tmp_big_int = cluster_size;
tmp_big_int = tmp_big_int * num_orphan_clusters;
if (KSize) {
tmp_ulong = (tmp_big_int / 1024ul).GetLowPart();
} else {
tmp_ulong = tmp_big_int.GetLowPart();
}
Message->Set(message_id);
Message->Display("%d%d", tmp_ulong,
num_orphans);
return TRUE;
}
BOOLEAN
FAT_SA::AllocSectorsForChain(
ULONG ChainHead
)
/*++
Routine Description:
When VerifyAndFix needs to allocate a cluster chain in order
to create a new directory (such as \FOUND.000), it also needs to
allocate space in the sector heap for data blocks for those
clusters. This routine does that.
Arguments:
ChainHead - a cluster chain; data blocks are allocated for each
cluster in this chain.
Return Value:
TRUE - Success.
FALSE - Failure - not enough disk space
--*/
{
ULONG clus;
ULONG next;
clus = ChainHead;
for (;;) {
if (!AllocateClusterData(clus,
(UCHAR)QuerySectorsPerCluster(),
FALSE,
(UCHAR)QuerySectorsPerCluster())) {
break;
}
if (_fat->IsEndOfChain(clus)) {
return TRUE;
}
clus = _fat->QueryEntry(clus);
}
// Error: not enough disk space. XXX
// Free the sectors we already allocated
while (ChainHead != clus) {
FreeClusterData(ChainHead);
next = _fat->QueryEntry(ChainHead);
_fat->SetClusterFree(ChainHead);
ChainHead = next;
}
return FALSE;
}
#if defined( _SETUP_LOADER_ )
BOOLEAN
FAT_SA::RecoverFreeSpace(
IN OUT PMESSAGE Message
)
{
return TRUE;
}
#else // _SETUP_LOADER_ not defined
BOOLEAN
FAT_SA::RecoverFreeSpace(
IN OUT PMESSAGE Message
)
/*++
Routine Description:
This routine checks all of the space marked free in the FAT for
bad clusters. If any clusters are bad they are marked bad in the
FAT.
Arguments:
Message - Supplies an outlet for messages.
Return Value:
FALSE - Failure.
TRUE - Success.
--*/
{
ULONG clus, length, max_length;
ULONG start_sector, num_sectors, i;
NUMBER_SET bad_sectors;
LBN lbn;
ULONG percent_complete;
ULONG num_checked, total_to_check;
Message->Set(MSG_CHK_RECOVERING_FREE_SPACE, PROGRESS_MESSAGE);
Message->Display();
_pvfMessage = Message;
percent_complete = 0;
if(!DisplayTwnkPercent(percent_complete)) {
_pvfMessage = NULL;
return FALSE;
}
num_checked = 0;
total_to_check = _fat->QueryFreeClusters();
max_length = QueryClusterCount()/20 + 1;
for (clus = FirstDiskCluster; _fat->IsInRange(clus); clus++) {
for (length = 0; _fat->IsInRange(clus + length) &&
_fat->IsClusterFree(clus + length) &&
length < max_length; length++) {
}
if (length) {
start_sector = QueryStartDataLbn() +
(clus - FirstDiskCluster)*QuerySectorsPerCluster();
num_sectors = length*QuerySectorsPerCluster();
if (!bad_sectors.Initialize() ||
!_drive->Verify(start_sector, num_sectors, &bad_sectors)) {
Message->Set(MSG_CHK_NO_MEMORY);
Message->Display();
_pvfMessage = NULL;
return FALSE;
}
for (i = 0; i < bad_sectors.QueryCardinality(); i++) {
lbn = bad_sectors.QueryNumber(i).GetLowPart();
_fat->SetClusterBad(((lbn - QueryStartDataLbn())/
QuerySectorsPerCluster()) +
FirstDiskCluster );
}
clus += length - 1;
num_checked += length;
if (100*num_checked/total_to_check > percent_complete) {
percent_complete = 100*num_checked/total_to_check;
}
if (!DisplayTwnkPercent(percent_complete)) {
_pvfMessage = NULL;
return FALSE;
}
}
}
percent_complete = 100;
if(!DisplayTwnkPercent(percent_complete)) {
_pvfMessage = NULL;
return FALSE;
}
Message->Set(MSG_CHK_DONE_RECOVERING_FREE_SPACE, PROGRESS_MESSAGE);
Message->Display();
_pvfMessage = NULL;
return TRUE;
}
#endif // _SETUP_LOADER_
| 144,164 | 45,745 |
// Copyright 2019 The Fuchsia 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/ui/scenic/lib/scheduling/delegating_frame_scheduler.h"
#include "src/lib/fxl/logging.h"
#include "src/ui/scenic/lib/scheduling/id.h"
namespace scheduling {
DelegatingFrameScheduler::DelegatingFrameScheduler(
std::shared_ptr<FrameScheduler> frame_scheduler) {
if (frame_scheduler) {
SetFrameScheduler(frame_scheduler);
}
}
void DelegatingFrameScheduler::SetFrameRenderer(fxl::WeakPtr<FrameRenderer> frame_renderer) {
CallWhenFrameSchedulerAvailable(
[frame_renderer = frame_renderer](FrameScheduler* frame_scheduler) {
frame_scheduler->SetFrameRenderer(frame_renderer);
});
};
void DelegatingFrameScheduler::AddSessionUpdater(fxl::WeakPtr<SessionUpdater> session_updater) {
CallWhenFrameSchedulerAvailable(
[session_updater = session_updater](FrameScheduler* frame_scheduler) {
frame_scheduler->AddSessionUpdater(session_updater);
});
};
void DelegatingFrameScheduler::SetRenderContinuously(bool render_continuously) {
CallWhenFrameSchedulerAvailable([render_continuously](FrameScheduler* frame_scheduler) {
frame_scheduler->SetRenderContinuously(render_continuously);
});
}
PresentId DelegatingFrameScheduler::RegisterPresent(
SessionId session_id, std::variant<OnPresentedCallback, Present2Info> present_information,
std::vector<zx::event> release_fences, PresentId present_id) {
// Assuming we never have several levels of delegating frame schedulers |present_id| should never
// be set.
FXL_CHECK(present_id == kInvalidPresentId);
present_id = scheduling::GetNextPresentId();
CallWhenFrameSchedulerAvailable([session_id, present_information = std::move(present_information),
release_fences = std::move(release_fences),
present_id](FrameScheduler* frame_scheduler) mutable {
frame_scheduler->RegisterPresent(session_id, std::move(present_information),
std::move(release_fences), present_id);
});
return present_id;
}
void DelegatingFrameScheduler::SetOnUpdateFailedCallbackForSession(
SessionId session_id, FrameScheduler::OnSessionUpdateFailedCallback update_failed_callback) {
CallWhenFrameSchedulerAvailable([session_id, callback = std::move(update_failed_callback)](
FrameScheduler* frame_scheduler) mutable {
frame_scheduler->SetOnUpdateFailedCallbackForSession(session_id, std::move(callback));
});
}
void DelegatingFrameScheduler::ScheduleUpdateForSession(zx::time presentation_time,
SchedulingIdPair id_pair) {
CallWhenFrameSchedulerAvailable([presentation_time, id_pair](FrameScheduler* frame_scheduler) {
frame_scheduler->ScheduleUpdateForSession(presentation_time, id_pair);
});
}
void DelegatingFrameScheduler::GetFuturePresentationInfos(
zx::duration requested_prediction_span, GetFuturePresentationInfosCallback callback) {
FXL_DCHECK(callback);
CallWhenFrameSchedulerAvailable([requested_prediction_span, callback = std::move(callback)](
FrameScheduler* frame_scheduler) mutable {
frame_scheduler->GetFuturePresentationInfos(requested_prediction_span, std::move(callback));
});
}
void DelegatingFrameScheduler::SetOnFramePresentedCallbackForSession(
SessionId session, OnFramePresentedCallback callback) {
if (callback) {
CallWhenFrameSchedulerAvailable(
[session, callback = std::move(callback)](FrameScheduler* frame_scheduler) mutable {
frame_scheduler->SetOnFramePresentedCallbackForSession(session, std::move(callback));
});
}
}
void DelegatingFrameScheduler::RemoveSession(SessionId session_id) {
CallWhenFrameSchedulerAvailable([session_id](FrameScheduler* frame_scheduler) {
frame_scheduler->RemoveSession(session_id);
});
}
void DelegatingFrameScheduler::CallWhenFrameSchedulerAvailable(
OnFrameSchedulerAvailableCallback callback) {
if (frame_scheduler_) {
callback(frame_scheduler_.get());
} else {
call_when_frame_scheduler_available_callbacks_.push_back(std::move(callback));
}
}
void DelegatingFrameScheduler::SetFrameScheduler(
const std::shared_ptr<FrameScheduler>& frame_scheduler) {
if (frame_scheduler_) {
FXL_LOG(ERROR) << "DelegatingFrameScheduler can only be set once.";
return;
}
if (!frame_scheduler) {
FXL_LOG(ERROR) << "DelegatingFrameScheduler cannot be set to a null value.";
return;
}
frame_scheduler_ = frame_scheduler;
for (auto& callback : call_when_frame_scheduler_available_callbacks_) {
callback(frame_scheduler_.get());
}
call_when_frame_scheduler_available_callbacks_.clear();
}
} // namespace scheduling
| 4,921 | 1,451 |
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <AzCore/Serialization/SerializeContext.h>
#include "EMotionFXConfig.h"
#include "BlendTreeConnection.h"
#include <MCore/Source/IDGenerator.h>
#include "AnimGraphNode.h"
#include "AnimGraph.h"
namespace EMotionFX
{
AZ_CLASS_ALLOCATOR_IMPL(BlendTreeConnection, AnimGraphAllocator, 0)
BlendTreeConnection::BlendTreeConnection()
: m_animGraph(nullptr)
, m_sourceNode(nullptr)
, mSourcePort(MCORE_INVALIDINDEX16)
, mTargetPort(MCORE_INVALIDINDEX16)
{
mId = MCore::GetIDGenerator().GenerateID();
#ifdef EMFX_EMSTUDIOBUILD
mVisited = false;
#endif
}
BlendTreeConnection::BlendTreeConnection(AnimGraphNode* sourceNode, AZ::u16 sourcePort, AZ::u16 targetPort)
: BlendTreeConnection()
{
if (sourceNode)
{
m_animGraph = sourceNode->GetAnimGraph();
}
mSourcePort = sourcePort;
mTargetPort = targetPort;
SetSourceNode(sourceNode);
}
BlendTreeConnection::~BlendTreeConnection()
{
}
void BlendTreeConnection::Reinit()
{
if (!m_animGraph)
{
return;
}
m_sourceNode = m_animGraph->RecursiveFindNodeById(GetSourceNodeId());
AZ_Error("EMotionFX", m_sourceNode, "Could not find node for id %s.", GetSourceNodeId().ToString().c_str());
}
bool BlendTreeConnection::InitAfterLoading(AnimGraph* animGraph)
{
if (!animGraph)
{
return false;
}
m_animGraph = animGraph;
Reinit();
return true;
}
void BlendTreeConnection::SetSourceNode(AnimGraphNode* node)
{
m_sourceNode = node;
if (m_sourceNode)
{
m_sourceNodeId = m_sourceNode->GetId();
}
}
// check if this connection is valid
bool BlendTreeConnection::GetIsValid() const
{
// make sure the node and input numbers are valid
if (!m_sourceNode || mSourcePort == MCORE_INVALIDINDEX16 || mTargetPort == MCORE_INVALIDINDEX16)
{
return false;
}
// the connection is valid
return true;
}
void BlendTreeConnection::Reflect(AZ::ReflectContext* context)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context);
if (!serializeContext)
{
return;
}
serializeContext->Class<BlendTreeConnection>()
->Version(1)
->Field("sourceNodeId", &BlendTreeConnection::m_sourceNodeId)
->Field("sourcePortNr", &BlendTreeConnection::mSourcePort)
->Field("targetPortNr", &BlendTreeConnection::mTargetPort);
}
} // namespace EMotionFX | 3,267 | 1,015 |
// This file is distributed under the BSD 3-Clause License. See LICENSE for details.
#include <ctype.h>
#include <algorithm>
#include "eprp.hpp"
void Eprp::eat_comments() {
while (scan_is_token(Token_id_comment) && !scan_is_end()) scan_next();
}
// rule_path = (\. | alnum | / | "asdad.." | \,)+
bool Eprp::rule_path(std::string &path) {
assert(!scan_is_end());
if (!(scan_is_token(Token_id_dot) || scan_is_token(Token_id_alnum) || scan_is_token(Token_id_string) ||
scan_is_token(Token_id_div)))
return false;
do {
absl::StrAppend(&path, scan_text());
ast->add(Eprp_rule_path, scan_token());
bool ok = scan_next();
if (!ok) break;
eat_comments();
if (scan_is_next_token(1, Token_id_colon))
break; // stop if file:foo is the next argument list
} while (scan_is_token(Token_id_dot) || scan_is_token(Token_id_alnum) || scan_is_token(Token_id_string) ||
scan_is_token(Token_id_comma) || scan_is_token(Token_id_div));
return true;
}
// rule_label_path = label path
bool Eprp::rule_label_path(const std::string &cmd_line, Eprp_var &next_var) {
if (!(scan_is_token(Token_id_alnum) && scan_is_next_token(1, Token_id_colon))) return false;
auto label = scan_text();
ast->add(Eprp_rule_label_path, scan_token());
scan_next(); // Skip alnum token
scan_next(); // Skip colon token
eat_comments();
if (scan_is_end()) {
scan_error("the {} field in {} command has no argument", label, cmd_line);
return false;
}
std::string path;
ast->down();
bool ok = rule_path(path);
ast->up(Eprp_rule_label_path);
if (!ok) {
if (scan_is_token(Token_id_register)) {
scan_error("could not pass a register {} to a method {}", scan_text(), cmd_line);
} else {
scan_error("field {} with invalid value in {} command", label, cmd_line);
}
return false;
}
next_var.add(label, path);
return true;
}
// rule_reg = reg+
bool Eprp::rule_reg(bool first) {
if (!scan_is_token(Token_id_register)) return false;
std::string var{scan_text()};
ast->add(Eprp_rule_reg, scan_token());
if (first) { // First in line #a |> ...
if (variables.find(var) == variables.end()) {
scan_error("variable {} is empty", var);
return false;
}
last_cmd_var = variables[var];
} else {
variables[var] = last_cmd_var;
}
scan_next();
eat_comments();
return true;
}
// rule_cmd_line = alnum (dot alnum)*
bool Eprp::rule_cmd_line(std::string &path) {
if (scan_is_end()) return false;
if (!scan_is_token(Token_id_alnum)) return false;
do {
absl::StrAppend(&path, scan_text()); // Add the Token_id_alnum
ast->add(Eprp_rule_cmd_line, scan_token());
bool ok1 = scan_next();
if (!ok1) break;
if (!scan_is_token(Token_id_dot))
break;
absl::StrAppend(&path, scan_text()); // Add the Token_id_dot
ast->add(Eprp_rule_cmd_line, scan_token());
bool ok2 = scan_next();
if (!ok2) break;
} while (scan_is_token(Token_id_alnum));
eat_comments();
return true;
}
// rule_cmd_full =rule_cmd_line rule_label_path*
bool Eprp::rule_cmd_full() {
std::string cmd_line;
Eprp_var next_var;
ast->down();
bool cmd_found = rule_cmd_line(cmd_line);
ast->up(Eprp_rule_cmd_full);
if (!cmd_found) return false;
bool path_found;
do {
ast->down();
path_found = rule_label_path(cmd_line, next_var);
ast->up(Eprp_rule_cmd_full);
} while (path_found);
ast->down();
run_cmd(cmd_line, next_var);
ast->up(Eprp_rule_cmd_full);
return true;
}
// rule_pipe = |> rule_cmd_or_reg
bool Eprp::rule_pipe() {
if (scan_is_end()) return false;
if (!scan_is_token(Token_id_pipe)) return false;
scan_next();
eat_comments();
ast->down();
bool try_either = rule_cmd_or_reg(false);
ast->up(Eprp_rule_pipe);
if (!try_either) {
scan_error("after a pipe there should be a register or a command");
return false;
}
return true;
}
// rule_cmd_or_reg = rule_reg | rule_cmd_full
bool Eprp::rule_cmd_or_reg(bool first) {
ast->down();
bool try_reg_rule = rule_reg(first);
ast->up(Eprp_rule_cmd_or_reg);
if (try_reg_rule) return true;
ast->down();
bool cmd_found = rule_cmd_full();
ast->up(Eprp_rule_cmd_or_reg);
return cmd_found;
}
// rule_top = rule_cmd_or_reg(first) rule_pipe*
bool Eprp::rule_top() {
ast->down();
bool try_either = rule_cmd_or_reg(true);
ast->up(Eprp_rule_top);
if (!try_either) {
scan_error("statements start with a register or a command");
return false;
}
// tree.add_lazy_child(1);
bool try_pipe = rule_pipe();
if (!try_pipe) {
if (scan_is_token(Token_id_or)) {
scan_error("eprp pipe is |> not |");
return false;
} else if (scan_is_end()) {
return true;
} else {
scan_error("invalid command");
return false;
}
}
// tree.add_lazy_child(1);
while (rule_pipe()) {
// tree.add_lazy_child(1);
;
}
return true;
}
// top = parse_top+
void Eprp::elaborate() {
ast = std::make_unique<Ast_parser>(get_memblock(), Eprp_rule);
ast->down();
while (!scan_is_end()) {
eat_comments();
if (scan_is_end()) return;
bool cmd = rule_top();
if (!cmd) return;
}
ast->up(Eprp_rule);
//process_ast();
ast = nullptr;
last_cmd_var.clear();
};
void Eprp::process_ast_handler(const mmap_lib::Tree_index &self, const Ast_parser_node &node) {
auto txt = scan_text(node.token_entry);
fmt::print("level:{} pos:{} te:{} rid:{} txt:{}\n", self.level, self.pos, node.token_entry, node.rule_id, txt);
if (node.rule_id == Eprp_rule_cmd_or_reg) {
std::string children_txt;
// HERE: Children should iterate FAST, over all the children recursively
// HERE: Move this iterate over children as a handle_command
for (const auto &ti : ast->children(self)) {
auto txt2 = scan_text(ast->get_data(ti).token_entry);
if (ast->get_data(ti).rule_id == Eprp_rule_label_path)
absl::StrAppend(&children_txt, " ", txt2, ":");
else
absl::StrAppend(&children_txt, txt2);
}
fmt::print(" children: {}\n", children_txt);
}
}
void Eprp::process_ast() {
for(const auto &ti:ast->depth_preorder(ast->get_root())) {
fmt::print("ti.level:{} ti.pos:{}\n", ti.level, ti.pos);
}
ast->each_bottom_up_fast(std::bind(&Eprp::process_ast_handler, this, std::placeholders::_1, std::placeholders::_2));
}
void Eprp::run_cmd(const std::string &cmd, Eprp_var &var) {
const auto &it = methods.find(cmd);
if (it == methods.end()) {
parser_error("method {} not registered", cmd);
return;
}
const auto &m = it->second;
last_cmd_var.add(var);
std::string err_msg;
bool err = m.check_labels(last_cmd_var, err_msg);
if (err) {
parser_error(err_msg);
return;
}
#if 0
for(const auto &v:var.dict) {
if (!m.has_label(v.first)) {
parser_warn("method {} does not have passed label {}", cmd, v.first);
}
}
#endif
for (const auto &label : m.labels) {
if (!label.second.default_value.empty() && !last_cmd_var.has_label(label.first))
last_cmd_var.add(label.first, label.second.default_value);
}
m.method(last_cmd_var);
}
const std::string &Eprp::get_command_help(const std::string &cmd) const {
const auto &it = methods.find(cmd);
if (it == methods.end()) {
static const std::string empty = "";
return empty;
}
return it->second.help;
}
void Eprp::get_commands(std::function<void(const std::string &, const std::string &)> fn) const {
for (const auto &v : methods) {
fn(v.first, v.second.help);
}
}
void Eprp::get_labels(const std::string & cmd,
std::function<void(const std::string &, const std::string &, bool required)> fn) const {
const auto &it = methods.find(cmd);
if (it == methods.end()) return;
for (const auto &v : it->second.labels) {
fn(v.first, v.second.help, v.second.required);
}
}
Eprp::Eprp() {}
| 7,992 | 3,068 |
#include <iostream>
using namespace std;
int a[6] = {[4] = 29, [2] = 15};
struct node
{
int data;
node *next;
node(int d) : data(d), next(NULL) {}
};
int add_node(void *data)
{
node *n = (node *)data;
cout << n->data << endl;
return 0;
}
int main(int argc, char const *argv[])
{
node *n1 = new node(1000);
add_node((void *)n1);
for (int i = 0; i < 6; ++i)
{
cout << a[i] << " ";
}
cout << endl;
return 0;
} | 449 | 214 |
#include <iostream>
#include <fstream>
#include "IntroScene.h"
#include "Textures.h"
#include "Utils.h"
#include "Brick.h"
#include "IntroGround.h"
#include "Leaf.h"
#include "MushRoom.h"
#include "Goomba.h"
#include "Koopas.h"
using namespace std;
CIntroScene::CIntroScene(int id, LPCWSTR filePath) :
CScene(id, filePath)
{
key_handler = new IntroSceneKeyHandler(this);
BackGround = nullptr;
Three = nullptr;
Arrow = nullptr;
//StartScrolling();
}
void CIntroScene::_ParseSection_TEXTURES(string line) {
vector<string> tokens = split(line);
if (tokens.size() < 5) return; // skip invalid lines
int texID = atoi(tokens[0].c_str());
wstring path = ToWSTR(tokens[1]);
int R = atoi(tokens[2].c_str());
int G = atoi(tokens[3].c_str());
int B = atoi(tokens[4].c_str());
CTextures::GetInstance()->Add(texID, path.c_str(), D3DCOLOR_XRGB(R, G, B));
}
void CIntroScene::_ParseSection_SPRITES(string line) {
vector<string> tokens = split(line);
if (tokens.size() < 6) return; // skip invalid lines
int ID = atoi(tokens[0].c_str());
int l = atoi(tokens[1].c_str());
int t = atoi(tokens[2].c_str());
int r = atoi(tokens[3].c_str());
int b = atoi(tokens[4].c_str());
int texID = atoi(tokens[5].c_str());
LPDIRECT3DTEXTURE9 tex = CTextures::GetInstance()->Get(texID);
if (tex == NULL)
{
DebugOut(L"[ERROR] Texture ID %d not found!\n", texID);
return;
}
CSprites::GetInstance()->Add(ID, l, t, r, b, tex);
}
void CIntroScene::_ParseSection_ANIMATIONS(string line) {
vector<string> tokens = split(line);
if (tokens.size() < 3) return; // skip invalid lines - an animation must at least has 1 frame and 1 frame time
//DebugOut(L"--> %s\n",ToWSTR(line).c_str());
LPANIMATION ani = new CAnimation();
int ani_id = atoi(tokens[0].c_str());
for (unsigned int i = 1; i < tokens.size(); i += 2) // why i+=2 ? sprite_id | frame_time
{
int sprite_id = atoi(tokens[i].c_str());
int frame_time = atoi(tokens[i + 1].c_str());
ani->Add(sprite_id, frame_time);
}
CAnimations::GetInstance()->Add(ani_id, ani);
if (ani_id == 800)
Three = ani;
}
void CIntroScene::_ParseSection_ANIMATION_SETS(string line) {
vector<string> tokens = split(line);
if (tokens.size() < 2) return; // skip invalid lines - an animation set must at least id and one animation id
//DebugOut(L"--> %s\n", ToWSTR(line).c_str());
int ani_set_id = atoi(tokens[0].c_str());
LPANIMATION_SET s;
if (CAnimationSets::GetInstance()->animation_sets[ani_set_id] != NULL)
s = CAnimationSets::GetInstance()->animation_sets[ani_set_id];
else
s = new CAnimationSet();
CAnimations* animations = CAnimations::GetInstance();
for (unsigned int i = 1; i < tokens.size(); i++)
{
int ani_id = atoi(tokens[i].c_str());
LPANIMATION ani = animations->Get(ani_id);
s->push_back(ani);
}
CAnimationSets::GetInstance()->Add(ani_set_id, s);
if (ani_set_id == ANISET_BACKGROUND_ID)
BackGround = s;
if (ani_set_id == ANISET_ARROW_ID)
Arrow = s;
}
void CIntroScene::_ParseSection_OBJECTS(string line) {
vector<string> tokens = split(line);
if (tokens.size() < 3) return; // skip invalid lines - an object set must have at least id, x, y
int tag = 0, option_tag_1 = 0, option_tag_2 = 0;
int object_type = atoi(tokens[0].c_str());
float x = (float)atof(tokens[1].c_str());
float y = (float)atof(tokens[2].c_str());
int ani_set_id = atoi(tokens[3].c_str());
if (tokens.size() >= 5)
tag = (int)atof(tokens[4].c_str());
if (tokens.size() >= 6)
option_tag_1 = (int)atof(tokens[5].c_str());
if (tokens.size() >= 7)
option_tag_2 = (int)atof(tokens[6].c_str());
CAnimationSets* animation_sets = CAnimationSets::GetInstance();
CGameObject* obj = NULL;
switch (object_type)
{
case OBJECT_TYPE_GROUND:
obj = new CIntroGround();
break;
default:
DebugOut(L"[ERR] Invalid object type: %d\n", object_type);
return;
}
obj->SetPosition(x, y);
LPANIMATION_SET ani_set = animation_sets->Get(ani_set_id);
obj->SetAnimationSet(ani_set);
objects.push_back(obj);
}
void CIntroScene::Update(DWORD dt) {
if (switchTimer.ElapsedTime() >= SWITCH_TIME && switchTimer.IsStarted()) {
CGame::GetInstance()->SwitchScene(WORLD_SCENE_ID);
}
}
void CIntroScene::Load() {
DebugOut(L"[INFO] Start loading scene resources from : %s \n", sceneFilePath);
ifstream f;
f.open(sceneFilePath);
// current resource section flag
int section = SCENE_SECTION_UNKNOWN;
DebugOut(L"%d", section);
char str[MAX_SCENE_LINE];
while (f.getline(str, MAX_SCENE_LINE))
{
string line(str);
if (line[0] == '#') continue; // skip comment lines
if (line == "[TEXTURES]") { section = SCENE_SECTION_TEXTURES; continue; }
if (line == "[SPRITES]") { section = SCENE_SECTION_SPRITES; continue; }
if (line == "[ANIMATIONS]") { section = SCENE_SECTION_ANIMATIONS; continue; }
if (line == "[ANIMATION_SETS]") { section = SCENE_SECTION_ANIMATION_SETS; continue; }
if (line == "[OBJECTS]") { section = SCENE_SECTION_OBJECTS; continue; }
if (line[0] == '[' || line == "") { section = SCENE_SECTION_UNKNOWN; continue; }
//
// data section
//
switch (section)
{
case SCENE_SECTION_TEXTURES: _ParseSection_TEXTURES(line); break;
case SCENE_SECTION_SPRITES: _ParseSection_SPRITES(line); break;
case SCENE_SECTION_ANIMATIONS: _ParseSection_ANIMATIONS(line); break;
case SCENE_SECTION_ANIMATION_SETS: _ParseSection_ANIMATION_SETS(line); break;
case SCENE_SECTION_OBJECTS: _ParseSection_OBJECTS(line); break;
}
}
f.close();
CTextures::GetInstance()->Add(ID_TEX_BBOX, L"Resources\\Textures\\bbox.png", D3DCOLOR_XRGB(255, 255, 255));
DebugOut(L"[INFO] Done loading scene resources %s\n", sceneFilePath);
}
void CIntroScene::Render() {
BackGround->at(3)->Render(0, 0);
Three->Render(THREE_X, THREE_Y);
for (size_t i = 0; i < objects.size(); i++)
objects[i]->Render();
if (switchTimer.IsStarted())
Arrow->at(0)->Render(ARROW_X, ARROW_Y);
else
Arrow->at(1)->Render(ARROW_X, ARROW_Y);
}
void CIntroScene::Unload() {
for (size_t i = 2; i < objects.size(); i++)
delete objects[i];
objects.clear();
BackGround = NULL;
Arrow = NULL;
Three = NULL;
switchTimer.Reset();
DebugOut(L"Unload Intro Scene\n");
}
void IntroSceneKeyHandler::OnKeyDown(int KeyCode)
{
CIntroScene* intro = ((CIntroScene*)CGame::GetInstance()->GetCurrentScene());
switch (KeyCode)
{
case DIK_RETURN:
intro->switchTimer.Start();
DebugOut(L"Enter");
break;
default:
break;
}
} | 6,413 | 2,705 |
////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2013 - 2015, Göteborg Bit Factory.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
#include <iostream>
#include <test.h>
#include <Variant.h>
#include <Context.h>
Context context;
#define EPSILON 0.001
////////////////////////////////////////////////////////////////////////////////
int main (int, char**)
{
UnitTest t (80);
Variant v0 (true);
Variant v1 (42);
Variant v2 (3.14);
Variant v3 ("foo");
Variant v4 (1234567890, Variant::type_date);
Variant v5 (1200, Variant::type_duration);
// boolean + boolean -> ERROR
try {Variant v00 = v0 + v0; t.fail ("true + true --> error");}
catch (...) {t.pass ("true + true --> error");}
// boolean + integer -> integer
Variant v01 = v0 + v1;
t.is (v01.type (), Variant::type_integer, "true + 42 --> integer");
t.is (v01.get_integer (), 43, "true + 42 --> 43");
// boolean + real -> real
Variant v02 = v0 + v2;
t.is (v02.type (), Variant::type_real, "true + 3.14 --> real");
t.is (v02.get_real (), 4.14, EPSILON, "true + 3.14 --> 4.14");
// boolean + string -> string
Variant v03 = v0 + v3;
t.is (v03.type (), Variant::type_string, "true + foo --> string");
t.is (v03.get_string (), "truefoo", "true + foo --> truefoo");
// boolean + date -> date
Variant v04 = v0 + v4;
t.is (v04.type (), Variant::type_date, "true + 1234567890 --> date");
t.is (v04.get_date (), "1234567891", "true + 1234567890 --> 1234567891");
// boolean + duration -> duration
Variant v05 = v0 + v5;
t.is (v05.type (), Variant::type_duration, "true + 1200 --> duration");
t.is (v05.get_duration (), "1201", "true + 1200 --> 1201");
// integer + boolean -> integer
Variant v10 = v1 + v0;
t.is (v10.type (), Variant::type_integer, "42 + true --> integer");
t.is (v10.get_integer (), 43, "42 + true --> 43");
// integer + integer -> integer
Variant v11 = v1 + v1;
t.is (v11.type (), Variant::type_integer, "42 + 42 --> integer");
t.is (v11.get_integer (), 84, "42 + 42 --> 84");
// integer + real -> real
Variant v12 = v1 + v2;
t.is (v12.type (), Variant::type_real, "42 + 3.14 --> real");
t.is (v12.get_real (), 45.14, EPSILON, "42 + 3.14 --> 45.14");
// integer + string -> string
Variant v13 = v1 + v3;
t.is (v13.type (), Variant::type_string, "42 + foo --> string");
t.is (v13.get_string (), "42foo", "42 + foo --> 42foo");
// integer + date -> date
Variant v14 = v1 + v4;
t.is (v14.type (), Variant::type_date, "42 + 1234567890 --> date");
t.is (v14.get_date (), 1234567932, "42 + 1234567890 --> 1234567932");
// integer + duration -> duration
Variant v15 = v1 + v5;
t.is (v15.type (), Variant::type_duration, "42 + 1200 --> duration");
t.is (v15.get_duration (), 1242, "42 + 1200 --> 1242");
// real + boolean -> real
Variant v20 = v2 + v0;
t.is (v20.type (), Variant::type_real, "3.14 + true --> real");
t.is (v20.get_real (), 4.14, EPSILON, "3.14 + true --> 4.14");
// real + integer -> real
Variant v21 = v2 + v1;
t.is (v21.type (), Variant::type_real, "3.14 + 42 --> real");
t.is (v21.get_real (), 45.14, EPSILON, "3.14 + 42 --> 45.14");
// real + real -> real
Variant v22 = v2 + v2;
t.is (v22.type (), Variant::type_real, "3.14 + 3.14 --> real");
t.is (v22.get_real (), 6.28, EPSILON, "3.14 + 3.14 --> 6.28");
// real + string -> string
Variant v23 = v2 + v3;
t.is (v23.type (), Variant::type_string, "3.14 + foo --> string");
t.is (v23.get_string (), "3.14foo", "3.14 + foo --> 3.14foo");
// real + date -> date
Variant v24 = v2 + v4;
t.is (v24.type (), Variant::type_date, "3.14 + 1234567890 --> date");
t.is (v24.get_date (), 1234567893, "3.14 + 1234567890 --> 1234567893");
// real + duration -> duration
Variant v25 = v2 + v5;
t.is (v25.type (), Variant::type_duration, "3.14 + 1200 --> duration");
t.is (v25.get_duration (), 1203, "3.14 + 1200 --> 1203");
// string + boolean -> string
Variant v30 = v3 + v0;
t.is (v30.type (), Variant::type_string, "foo + true --> string");
t.is (v30.get_string (), "footrue", "foo + true --> footrue");
// string + integer -> string
Variant v31 = v3 + v1;
t.is (v31.type (), Variant::type_string, "foo + 42 --> string");
t.is (v31.get_string (), "foo42", "foo + 42 --> foo42");
// string + real -> string
Variant v32 = v3 + v2;
t.is (v32.type (), Variant::type_string, "foo + 3.14 --> string");
t.is (v32.get_string (), "foo3.14", "foo + 3.14 --> foo3.14");
// string + string -> string
Variant v33 = v3 + v3;
t.is (v33.type (), Variant::type_string, "foo + foo --> string");
t.is (v33.get_string (), "foofoo", "foo + foo --> foofoo");
// string + date -> string
Variant v34 = v3 + v4;
t.is (v34.type (), Variant::type_string, "foo + 1234567890 --> string");
std::string s = v34.get_string ();
t.is ((int)s[7], (int)'-', "foo + 1234567890 --> fooYYYY-MM-DDThh:mm:ss");
t.is ((int)s[10], (int)'-', "foo + 1234567890 --> fooYYYY-MM-DDThh:mm:ss");
t.is ((int)s[13], (int)'T', "foo + 1234567890 --> fooYYYY-MM-DDThh:mm:ss");
t.is ((int)s[16], (int)':', "foo + 1234567890 --> fooYYYY-MM-DDThh:mm:ss");
t.is ((int)s[19], (int)':', "foo + 1234567890 --> fooYYYY-MM-DDThh:mm:ss");
t.is ((int)s.length (), 22, "foo + 1234567890 --> fooYYYY-MM-DDThh:mm:ss");
// string + duration -> string
Variant v35 = v3 + v5;
t.is (v35.type (), Variant::type_string, "foo + 1200 --> string");
t.is (v35.get_string (), "fooPT20M", "foo + 1200 --> fooPT20M");
// date + boolean -> date
Variant v40 = v4 + v0;
t.is (v40.type (), Variant::type_date, "1234567890 + true --> date");
t.is (v40.get_date (), 1234567891, "1234567890 + true --> 1234567891");
// date + integer -> date
Variant v41 = v4 + v1;
t.is (v41.type (), Variant::type_date, "1234567890 + 42 --> date");
t.is (v41.get_date (), 1234567932, "1234567890 + 42 --> 1234567932");
// date + real -> date
Variant v42 = v4 + v2;
t.is (v42.type (), Variant::type_date, "1234567890 + 3.14 --> date");
t.is (v42.get_date (), 1234567893, "1234567890 + 3.14 --> 1234567893");
// date + string -> string
Variant v43 = v4 + v3;
t.is (v43.type (), Variant::type_string, "1234567890 + foo --> string");
s = v43.get_string ();
t.is ((int)s[4], (int)'-', "1234567890 + foo --> YYYY-MM-DDThh:mm:ssfoo");
t.is ((int)s[7], (int)'-', "1234567890 + foo --> YYYY-MM-DDThh:mm:ssfoo");
t.is ((int)s[10], (int)'T', "1234567890 + foo --> YYYY-MM-DDThh:mm:ssfoo");
t.is ((int)s[13], (int)':', "1234567890 + foo --> YYYY-MM-DDThh:mm:ssfoo");
t.is ((int)s[16], (int)':', "1234567890 + foo --> YYYY-MM-DDThh:mm:ssfoo");
t.is ((int)s.length (), 22, "1234567890 + foo --> YYYY-MM-DDThh:mm:ssfoo");
// date + date -> ERROR
try {Variant v44 = v4 + v4; t.fail ("1234567890 + 1234567890 --> error");}
catch (...) {t.pass ("1234567890 + 1234567890 --> error");}
// date + duration -> date
Variant v45 = v4 + v5;
t.is (v45.type (), Variant::type_date, "1234567890 + 1200 --> date");
t.is (v45.get_date (), 1234569090, "1234567890 + 1200 --> 1234569090");
// duration + boolean -> duration
Variant v50 = v5 + v0;
t.is (v50.type (), Variant::type_duration, "1200 + true --> duration");
t.is (v50.get_duration (), 1201, "1200 + true --> 1201");
// duration + integer -> duration
Variant v51 = v5 + v1;
t.is (v51.type (), Variant::type_duration, "1200 + 42 --> duration");
t.is (v51.get_duration (), 1242, "1200 + 42 --> 1242");
// duration + real -> duration
Variant v52 = v5 + v2;
t.is (v52.type (), Variant::type_duration, "1200 + 3.14 --> duration");
t.is (v52.get_duration (), 1203, "1200 + 3.14 --> 1203");
// duration + string -> string
Variant v53 = v5 + v3;
t.is (v53.type (), Variant::type_string, "1200 + foo --> string");
t.is (v53.get_string (), "PT20Mfoo", "1200 + foo --> PT20Mfoo");
// duration + date -> date
Variant v54 = v5 + v4;
t.is (v54.type (), Variant::type_date, "1200 + 1234567890 --> date");
t.is (v54.get_date (), 1234569090, "1200 + 1234567890 --> 1234569090");
// duration + duration -> duration
Variant v55 = v5 + v5;
t.is (v55.type (), Variant::type_duration, "1200 + 1200 --> duration");
t.is (v55.get_duration (), 2400, "1200 + 1200 --> 2400");
return 0;
}
////////////////////////////////////////////////////////////////////////////////
| 10,153 | 4,626 |
/*++
Copyright (C) 2018 3MF Consortium
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.
Abstract:
NMR_ModelWriter_3MF_Native.cpp implements the platform independent 3MF Model Writer Class.
This model writer exports the in memory represenation into a 3MF file,
using LibZ and a native XML writer implementation.
--*/
#include "Model/Writer/NMR_ModelWriter_3MF_Native.h"
#include "Model/Classes/NMR_ModelConstants.h"
#include "Model/Classes/NMR_ModelAttachment.h"
#include "Model/Classes/NMR_ModelTextureAttachment.h"
#include "Model/Classes/NMR_ModelSliceResource.h"
#include "Common/Platform/NMR_ImportStream.h"
#include "Common/NMR_Exception.h"
#include "Common/Platform/NMR_XmlWriter.h"
#include "Common/Platform/NMR_XmlWriter_Native.h"
#include "Common/Platform/NMR_ImportStream_Unique_Memory.h"
#include "Common/Platform/NMR_ExportStream_Memory.h"
#include "Common/NMR_StringUtils.h"
#include "Common/3MF_ProgressMonitor.h"
#include <functional>
#include <sstream>
namespace NMR {
CModelWriter_3MF_Native::CModelWriter_3MF_Native(_In_ PModel pModel) : CModelWriter_3MF(pModel)
{
m_nRelationIDCounter = 0;
m_pModel = nullptr;
}
// These are OPC dependent functions
void CModelWriter_3MF_Native::createPackage(_In_ CModel * pModel)
{
__NMRASSERT(pModel != nullptr);
m_pModel = pModel;
m_nRelationIDCounter = 0;
}
void CModelWriter_3MF_Native::releasePackage()
{
m_pModel = nullptr;
}
void CModelWriter_3MF_Native::writePackageToStream(_In_ PExportStream pStream)
{
if (pStream.get() == nullptr)
throw CNMRException(NMR_ERROR_INVALIDPARAM);
if (m_pModel == nullptr)
throw CNMRException(NMR_ERROR_NOMODELTOWRITE);
// Write Model Stream
POpcPackageWriter pPackageWriter = std::make_shared<COpcPackageWriter>(pStream);
POpcPackagePart pModelPart = pPackageWriter->addPart(PACKAGE_3D_MODEL_URI);
PXmlWriter_Native pXMLWriter = std::make_shared<CXmlWriter_Native>(pModelPart->getExportStream());
if (!m_pProgressMonitor->Progress(0.01, ProgressIdentifier::PROGRESS_WRITEROOTMODEL))
throw CNMRException(NMR_USERABORTED);
writeModelStream(pXMLWriter.get(), m_pModel);
// add Root relationships
pPackageWriter->addRootRelationship(generateRelationShipID(), PACKAGE_START_PART_RELATIONSHIP_TYPE, pModelPart.get());
PModelAttachment pPackageThumbnail = m_pModel->getPackageThumbnail();
if (pPackageThumbnail.get() != nullptr)
{
// create Package Thumbnail Part
POpcPackagePart pThumbnailPart = pPackageWriter->addPart(pPackageThumbnail->getPathURI());
PExportStream pExportStream = pThumbnailPart->getExportStream();
// Copy data
PImportStream pPackageThumbnailStream = pPackageThumbnail->getStream();
pPackageThumbnailStream->seekPosition(0, true);
pExportStream->copyFrom(pPackageThumbnailStream.get(), pPackageThumbnailStream->retrieveSize(), MODELWRITER_NATIVE_BUFFERSIZE);
// add root relationship
pPackageWriter->addRootRelationship(generateRelationShipID(), pPackageThumbnail->getRelationShipType(), pThumbnailPart.get());
}
if (!m_pProgressMonitor->Progress(0.5, ProgressIdentifier::PROGRESS_WRITENONROOTMODELS))
throw CNMRException(NMR_USERABORTED);
// add slicestacks that reference other files
m_pProgressMonitor->PushLevel(0.5, 0.85);
addSlicerefAttachments(m_pModel);
m_pProgressMonitor->PopLevel();
// add Attachments
if (!m_pProgressMonitor->Progress(0.85, ProgressIdentifier::PROGRESS_WRITEATTACHMENTS))
throw CNMRException(NMR_USERABORTED);
m_pProgressMonitor->PushLevel(0.85, 0.99);
addAttachments(m_pModel, pPackageWriter, pModelPart);
m_pProgressMonitor->PopLevel();
if (!m_pProgressMonitor->Progress(0.99, ProgressIdentifier::PROGRESS_WRITECONTENTTYPES))
throw CNMRException(NMR_USERABORTED);
// add Content Types
pPackageWriter->addContentType(PACKAGE_3D_RELS_EXTENSION, PACKAGE_3D_RELS_CONTENT_TYPE);
pPackageWriter->addContentType(PACKAGE_3D_MODEL_EXTENSION, PACKAGE_3D_MODEL_CONTENT_TYPE);
pPackageWriter->addContentType(PACKAGE_3D_TEXTURE_EXTENSION, PACKAGE_TEXTURE_CONTENT_TYPE);
pPackageWriter->addContentType(PACKAGE_3D_PNG_EXTENSION, PACKAGE_PNG_CONTENT_TYPE);
pPackageWriter->addContentType(PACKAGE_3D_JPEG_EXTENSION, PACKAGE_JPG_CONTENT_TYPE);
pPackageWriter->addContentType(PACKAGE_3D_JPG_EXTENSION, PACKAGE_JPG_CONTENT_TYPE);
std::map<std::string, std::string> CustomContentTypes = m_pModel->getCustomContentTypes();
std::map<std::string, std::string>::iterator iContentTypeIterator;
for (iContentTypeIterator = CustomContentTypes.begin(); iContentTypeIterator != CustomContentTypes.end(); iContentTypeIterator++) {
if (!m_pModel->contentTypeIsDefault(iContentTypeIterator->first)) {
pPackageWriter->addContentType(iContentTypeIterator->first, iContentTypeIterator->second);
}
}
}
std::string CModelWriter_3MF_Native::generateRelationShipID()
{
// Create Unique ID String
std::stringstream sStream;
sStream << "rel" << m_nRelationIDCounter;
m_nRelationIDCounter++;
return sStream.str();
}
void CModelWriter_3MF_Native::addSlicerefAttachments(_In_ CModel *pModel) {
__NMRASSERT(pModel != nullptr);
nfUint32 nCount = pModel->getSliceStackCount();
if (nCount > 0) {
nfUint32 nIndex;
for (nIndex = 0; nIndex < nCount; nIndex++) {
if (!m_pProgressMonitor->Progress(double(nIndex) / nCount, ProgressIdentifier::PROGRESS_WRITENONROOTMODELS))
throw CNMRException(NMR_USERABORTED);
CModelSliceStackResource* pSliceStackResource = dynamic_cast<CModelSliceStackResource*>(pModel->getSliceStackResource(nIndex).get());
CSliceStack* pSliceStack = pSliceStackResource->getSliceStack().get();
if (pSliceStack->usesSliceRef()) {
PExportStreamMemory p = std::make_shared<CExportStreamMemory>();
PXmlWriter_Native pXMLWriter = std::make_shared<CXmlWriter_Native>(p);
writeSlicestackStream(pXMLWriter.get(), pModel, pSliceStackResource);
PImportStream pStream = std::make_shared<CImportStream_Unique_Memory>(p->getData(), p->getDataSize());
// check, whether that's already in here
PModelAttachment pSliceRefAttachment = m_pModel->findModelAttachment(pSliceStackResource->sliceRefPath());
if (pSliceRefAttachment.get() != nullptr) {
if (pSliceRefAttachment->getRelationShipType() != PACKAGE_START_PART_RELATIONSHIP_TYPE)
throw CNMRException(NMR_ERROR_DUPLICATEATTACHMENTPATH);
pSliceRefAttachment->setStream(pStream);
}
else
m_pModel->addAttachment(pSliceStackResource->sliceRefPath(), PACKAGE_START_PART_RELATIONSHIP_TYPE, pStream);
}
}
}
}
void CModelWriter_3MF_Native::addAttachments(_In_ CModel * pModel, _In_ POpcPackageWriter pPackageWriter, _In_ POpcPackagePart pModelPart)
{
__NMRASSERT(pModel != nullptr);
__NMRASSERT(pModelPart.get() != nullptr);
__NMRASSERT(pPackageWriter.get() != nullptr);
nfUint32 nCount = pModel->getAttachmentCount();
nfUint32 nIndex;
if (nCount > 0) {
for (nIndex = 0; nIndex < nCount; nIndex++) {
if (!m_pProgressMonitor->Progress(double(nIndex) / nCount, ProgressIdentifier::PROGRESS_WRITEATTACHMENTS))
throw CNMRException(NMR_USERABORTED);
PModelAttachment pAttachment = pModel->getModelAttachment(nIndex);
PImportStream pStream = pAttachment->getStream();
std::string sPath = fnIncludeLeadingPathDelimiter(pAttachment->getPathURI());
std::string sRelationShipType = pAttachment->getRelationShipType();
if (pStream.get() == nullptr)
throw CNMRException(NMR_ERROR_INVALIDPARAM);
// create Texture Part
POpcPackagePart pAttachmentPart = pPackageWriter->addPart(sPath);
PExportStream pExportStream = pAttachmentPart->getExportStream();
// Copy data
pStream->seekPosition(0, true);
pExportStream->copyFrom(pStream.get(), pStream->retrieveSize(), MODELWRITER_NATIVE_BUFFERSIZE);
// add relationships
pModelPart->addRelationship(generateRelationShipID(), sRelationShipType.c_str(), pAttachmentPart->getURI());
}
}
}
}
| 9,190 | 3,492 |
#include "action.h"
Action::Action(QString name, QKeySequence shortcut, bool terminal)
: m_name(name), m_shortcut(shortcut), m_terminal(terminal)
{}
QString Action::name() const
{
return m_name;
}
QKeySequence Action::shortcut() const
{
return m_shortcut;
}
bool Action::terminal() const
{
return m_terminal;
}
| 321 | 120 |
#include "souistd.h"
#include "control/SListCtrl.h"
#include <algorithm>
#pragma warning(disable : 4267 4018)
#define ITEM_MARGIN 4
namespace SOUI
{
//////////////////////////////////////////////////////////////////////////
// SListCtrl
SListCtrl::SListCtrl()
: m_nHeaderHeight(20)
, m_nItemHeight(20)
, m_pHeader(NULL)
, m_nSelectItem(-1)
, m_crItemBg(RGBA(255,255,255,255))
, m_crItemBg2(RGBA(226,226,226,255))
, m_crItemSelBg(RGBA(57,145,209,255))
, m_crItemHotBg(RGBA(57,145,209,128))
, m_crText(RGBA(0,0,0,255))
, m_crSelText(RGBA(255,255,0,255))
, m_pItemSkin(NULL)
, m_pIconSkin(NULL)
, m_pCheckSkin(GETBUILTINSKIN(SKIN_SYS_CHECKBOX))
, m_ptIcon(-1,-1)
, m_ptText(-1,-1)
, m_bHotTrack(FALSE)
, m_bCheckBox(FALSE)
, m_bMultiSelection(FALSE)
{
m_bClipClient = TRUE;
m_bFocusable = TRUE;
m_evtSet.addEvent(EVENTID(EventLCSelChanging));
m_evtSet.addEvent(EVENTID(EventLCSelChanged));
m_evtSet.addEvent(EVENTID(EventLCDbClick));
m_evtSet.addEvent(EVENTID(EventLCItemDeleted));
}
SListCtrl::~SListCtrl()
{
}
int SListCtrl::InsertColumn(int nIndex, LPCTSTR pszText, int nWidth, LPARAM lParam)
{
SASSERT(m_pHeader);
int nRet = m_pHeader->InsertItem(nIndex, pszText, nWidth, ST_NULL, lParam);
for(int i=0;i<GetItemCount();i++)
{
m_arrItems[i].arSubItems->SetCount(GetColumnCount());
}
UpdateScrollBar();
return nRet;
}
BOOL SListCtrl::CreateChildren(pugi::xml_node xmlNode)
{
// listctrl的子控件只能是一个header控件
if (!__super::CreateChildren(xmlNode))
return FALSE;
m_pHeader=NULL;
SWindow *pChild=GetWindow(GSW_FIRSTCHILD);
while(pChild)
{
if(pChild->IsClass(SHeaderCtrl::GetClassName()))
{
m_pHeader=(SHeaderCtrl*)pChild;
break;
}
pChild=pChild->GetWindow(GSW_NEXTSIBLING);
}
if(!m_pHeader) return FALSE;
SStringW strPos;
strPos.Format(L"0,0,-0,%d",m_nHeaderHeight);
m_pHeader->SetAttribute(L"pos",strPos,TRUE);
m_pHeader->GetEventSet()->subscribeEvent(EventHeaderItemChanging::EventID, Subscriber(&SListCtrl::OnHeaderSizeChanging,this));
m_pHeader->GetEventSet()->subscribeEvent(EventHeaderItemSwap::EventID, Subscriber(&SListCtrl::OnHeaderSwap,this));
return TRUE;
}
int SListCtrl::InsertItem(int nItem, LPCTSTR pszText, int nImage)
{
if(GetColumnCount()==0) return -1;
if (nItem<0 || nItem>GetItemCount())
nItem = GetItemCount();
DXLVITEM lvi;
lvi.dwData = 0;
lvi.arSubItems=new ArrSubItem();
lvi.arSubItems->SetCount(GetColumnCount());
DXLVSUBITEM &subItem=lvi.arSubItems->GetAt(0);
subItem.strText = _tcsdup(pszText);
subItem.cchTextMax = _tcslen(pszText);
subItem.nImage = nImage;
m_arrItems.InsertAt(nItem, lvi);
UpdateScrollBar();
return nItem;
}
BOOL SListCtrl::SetItemData(int nItem, LPARAM dwData)
{
if (nItem >= GetItemCount() || nItem<0)
return FALSE;
m_arrItems[nItem].dwData = dwData;
return TRUE;
}
LPARAM SListCtrl::GetItemData(int nItem)
{
if (nItem >= GetItemCount() || nItem<0)
return 0;
DXLVITEM& lvi = m_arrItems[nItem];
return lvi.dwData;
}
BOOL SListCtrl::SetSubItem(int nItem, int nSubItem, const DXLVSUBITEM* plv)
{
if (nItem>=GetItemCount() || nSubItem>=GetColumnCount() || nItem<0)
return FALSE;
DXLVSUBITEM & lvsi_dst=m_arrItems[nItem].arSubItems->GetAt(nSubItem);
if(plv->mask & S_LVIF_TEXT)
{
if(lvsi_dst.strText) free(lvsi_dst.strText);
lvsi_dst.strText=_tcsdup(plv->strText);
lvsi_dst.cchTextMax=_tcslen(plv->strText);
}
if(plv->mask&S_LVIF_IMAGE)
lvsi_dst.nImage=plv->nImage;
if(plv->mask&S_LVIF_INDENT)
lvsi_dst.nIndent=plv->nIndent;
RedrawItem(nItem);
return TRUE;
}
BOOL SListCtrl::GetSubItem(int nItem, int nSubItem, DXLVSUBITEM* plv) const
{
if (nItem>=GetItemCount() || nSubItem>=GetColumnCount() || nItem<0)
return FALSE;
const DXLVSUBITEM & lvsi_src=m_arrItems[nItem].arSubItems->GetAt(nSubItem);
if(plv->mask & S_LVIF_TEXT)
{
_tcscpy_s(plv->strText,plv->cchTextMax,lvsi_src.strText);
}
if(plv->mask&S_LVIF_IMAGE)
plv->nImage=lvsi_src.nImage;
if(plv->mask&S_LVIF_INDENT)
plv->nIndent=lvsi_src.nIndent;
return TRUE;
}
BOOL SListCtrl::SetSubItemText(int nItem, int nSubItem, LPCTSTR pszText)
{
if (nItem < 0 || nItem >= GetItemCount())
return FALSE;
if (nSubItem < 0 || nSubItem >= GetColumnCount())
return FALSE;
DXLVSUBITEM &lvi=m_arrItems[nItem].arSubItems->GetAt(nSubItem);
if(lvi.strText)
{
free(lvi.strText);
}
lvi.strText = _tcsdup(pszText);
lvi.cchTextMax= _tcslen(pszText);
CRect rcItem=GetItemRect(nItem,nSubItem);
InvalidateRect(rcItem);
return TRUE;
}
SStringT SListCtrl::GetSubItemText( int nItem, int nSubItem ) const
{
if (nItem>=GetItemCount() || nSubItem>=GetColumnCount() || nItem<0)
return _T("");
const DXLVSUBITEM & lvsi_src=m_arrItems[nItem].arSubItems->GetAt(nSubItem);
return lvsi_src.strText;
}
int SListCtrl::GetSelectedItem()
{
return m_nSelectItem;
}
void SListCtrl::SetSelectedItem(int nItem)
{
if (nItem != m_nSelectItem)
{
NotifySelChange(m_nSelectItem, nItem);
}
}
int SListCtrl::GetItemCount() const
{
if (GetColumnCount() <= 0)
return 0;
return m_arrItems.GetCount();
}
BOOL SListCtrl::SetItemCount( int nItems ,int nGrowBy)
{
int nOldCount=GetItemCount();
if(nItems<nOldCount) return FALSE;
BOOL bRet=m_arrItems.SetCount(nItems,nGrowBy);
if(bRet)
{
for(int i=nOldCount;i<nItems;i++)
{
DXLVITEM & lvi=m_arrItems[i];
lvi.arSubItems=new ArrSubItem;
lvi.arSubItems->SetCount(GetColumnCount());
}
}
UpdateScrollBar();
return bRet;
}
CRect SListCtrl::GetListRect()
{
CRect rcList;
GetClientRect(&rcList);
rcList.top += m_nHeaderHeight;
return rcList;
}
//////////////////////////////////////////////////////////////////////////
// 更新滚动条
void SListCtrl::UpdateScrollBar()
{
CSize szView;
szView.cx = m_pHeader->GetTotalWidth();
szView.cy = GetItemCount()*m_nItemHeight;
CRect rcClient;
SWindow::GetClientRect(&rcClient);//不计算滚动条大小
rcClient.top+=m_nHeaderHeight;
CSize size = rcClient.Size();
// 关闭滚动条
m_wBarVisible = SSB_NULL;
if (size.cy<szView.cy || (size.cy<szView.cy+GetSbWidth() && size.cx<szView.cx))
{
// 需要纵向滚动条
m_wBarVisible |= SSB_VERT;
m_siVer.nMin = 0;
m_siVer.nMax = szView.cy-1;
m_siVer.nPage = GetCountPerPage(FALSE)*m_nItemHeight;
if (size.cx-GetSbWidth() < szView.cx)
{
// 需要横向滚动条
m_wBarVisible |= SSB_HORZ;
m_siVer.nPage=size.cy-GetSbWidth() > 0 ? size.cy-GetSbWidth() : 0;//注意同时调整纵向滚动条page信息
m_siHoz.nMin = 0;
m_siHoz.nMax = szView.cx-1;
m_siHoz.nPage = size.cx-GetSbWidth() > 0 ? size.cx-GetSbWidth() : 0;
}
else
{
// 不需要横向滚动条
m_siHoz.nPage = size.cx;
m_siHoz.nMin = 0;
m_siHoz.nMax = m_siHoz.nPage-1;
m_siHoz.nPos = 0;
m_ptOrigin.x = 0;
}
}
else
{
// 不需要纵向滚动条
m_siVer.nPage = size.cy;
m_siVer.nMin = 0;
m_siVer.nMax = size.cy-1;
m_siVer.nPos = 0;
m_ptOrigin.y = 0;
if (size.cx < szView.cx)
{
// 需要横向滚动条
m_wBarVisible |= SSB_HORZ;
m_siHoz.nMin = 0;
m_siHoz.nMax = szView.cx-1;
m_siHoz.nPage = size.cx;
}
else
{
// 不需要横向滚动条
m_siHoz.nPage = size.cx;
m_siHoz.nMin = 0;
m_siHoz.nMax = m_siHoz.nPage-1;
m_siHoz.nPos = 0;
m_ptOrigin.x = 0;
}
}
SetScrollPos(TRUE, m_siVer.nPos, TRUE);
SetScrollPos(FALSE, m_siHoz.nPos, TRUE);
// 重新计算客户区及非客户区
SSendMessage(WM_NCCALCSIZE);
// 根据需要调整原点位置
if (HasScrollBar(FALSE) && m_ptOrigin.x+m_siHoz.nPage>szView.cx)
{
m_ptOrigin.x = szView.cx-m_siHoz.nPage;
}
if (HasScrollBar(TRUE) && m_ptOrigin.y+m_siVer.nPage>szView.cy)
{
m_ptOrigin.y = szView.cy-m_siVer.nPage;
}
Invalidate();
}
//更新表头位置
void SListCtrl::UpdateHeaderCtrl()
{
CRect rcClient;
GetClientRect(&rcClient);
CRect rcHeader(rcClient);
rcHeader.bottom=rcHeader.top+m_nHeaderHeight;
rcHeader.left-=m_ptOrigin.x;
if(m_pHeader) m_pHeader->Move(rcHeader);
}
void SListCtrl::DeleteItem(int nItem)
{
if (nItem>=0 && nItem < GetItemCount())
{
DXLVITEM &lvi=m_arrItems[nItem];
EventLCItemDeleted evt2(this);
evt2.nItem = nItem;
evt2.dwData = lvi.dwData;
FireEvent(evt2);
for(int i=0;i<GetColumnCount();i++)
{
DXLVSUBITEM &lvsi =lvi.arSubItems->GetAt(i);
if(lvsi.strText) free(lvsi.strText);
}
delete lvi.arSubItems;
m_arrItems.RemoveAt(nItem);
UpdateScrollBar();
}
}
void SListCtrl::DeleteColumn( int iCol )
{
if(m_pHeader->DeleteItem(iCol))
{
int nColumnCount = m_pHeader->GetItemCount();
for(int i=0;i<GetItemCount();i++)
{
DXLVITEM &lvi = m_arrItems[i];
if (0 == nColumnCount)
{
EventLCItemDeleted evt2(this);
evt2.nItem = i;
evt2.dwData = lvi.dwData;
FireEvent(evt2);
}
DXLVSUBITEM &lvsi=lvi.arSubItems->GetAt(iCol);
if(lvsi.strText) free(lvsi.strText);
m_arrItems[i].arSubItems->RemoveAt(iCol);
}
UpdateScrollBar();
}
}
void SListCtrl::DeleteAllItems()
{
m_nSelectItem = -1;
for(int i=0;i<GetItemCount();i++)
{
DXLVITEM &lvi = m_arrItems[i];
EventLCItemDeleted evt2(this);
evt2.nItem = i;
evt2.dwData = lvi.dwData;
FireEvent(evt2);
for(int j=0;j<GetColumnCount();j++)
{
DXLVSUBITEM &lvsi =lvi.arSubItems->GetAt(j);
if(lvsi.strText) free(lvsi.strText);
}
delete lvi.arSubItems;
}
m_arrItems.RemoveAll();
UpdateScrollBar();
}
CRect SListCtrl::GetItemRect(int nItem, int nSubItem)
{
if (!(nItem>=0 && nItem<GetItemCount() && nSubItem>=0 && nSubItem<GetColumnCount()))
return CRect();
CRect rcItem;
rcItem.top = m_nItemHeight*nItem;
rcItem.bottom = rcItem.top+m_nItemHeight;
rcItem.left = 0;
rcItem.right = 0;
for (int nCol = 0; nCol < GetColumnCount(); nCol++)
{
SHDITEM hdi;
hdi.mask = SHDI_WIDTH|SHDI_ORDER;
m_pHeader->GetItem(nCol, &hdi);
rcItem.left = rcItem.right;
rcItem.right = rcItem.left+hdi.cx.toPixelSize(GetScale());
if (hdi.iOrder == nSubItem)
break;
}
CRect rcList = GetListRect();
// 变换到窗口坐标
rcItem.OffsetRect(rcList.TopLeft());
// 根据原点坐标修正
rcItem.OffsetRect(-m_ptOrigin);
return rcItem;
}
//////////////////////////////////////////////////////////////////////////
// 自动修改pt的位置为相对当前项的偏移量
int SListCtrl::HitTest(const CPoint& pt)
{
CRect rcList = GetListRect();
CPoint pt2 = pt;
pt2.y -= rcList.top - m_ptOrigin.y;
int nRet = pt2.y / m_nItemHeight;
if (nRet >= GetItemCount())
{
nRet = -1;
}
return nRet;
}
void SListCtrl::RedrawItem(int nItem)
{
if (!IsVisible(TRUE))
return;
CRect rcList = GetListRect();
int nTopItem = GetTopIndex();
int nPageItems = (rcList.Height()+m_nItemHeight-1)/m_nItemHeight;
if (nItem>=nTopItem && nItem<GetItemCount() && nItem<=nTopItem+nPageItems)
{
CRect rcItem(0,0,rcList.Width(),m_nItemHeight);
rcItem.OffsetRect(0, m_nItemHeight*nItem-m_ptOrigin.y);
rcItem.OffsetRect(rcList.TopLeft());
CRect rcDC;
rcDC.IntersectRect(rcItem,rcList);
IRenderTarget *pRT = GetRenderTarget(&rcDC, OLEDC_PAINTBKGND);
SSendMessage(WM_ERASEBKGND, (WPARAM)pRT);
DrawItem(pRT, rcItem, nItem);
ReleaseRenderTarget(pRT);
}
}
int SListCtrl::GetCountPerPage(BOOL bPartial)
{
CRect rcClient = GetListRect();
// calculate number of items per control height (include partial item)
div_t divHeight = div(rcClient.Height(), m_nItemHeight);
// round up to nearest item count
return (std::max)((int)(bPartial && divHeight.rem > 0 ? divHeight.quot + 1 : divHeight.quot), 1);
}
BOOL SListCtrl::SortItems(
PFNLVCOMPAREEX pfnCompare,
void * pContext
)
{
qsort_s(m_arrItems.GetData(),m_arrItems.GetCount(),sizeof(DXLVITEM),pfnCompare,pContext);
m_nSelectItem=-1;
m_nHoverItem=-1;
InvalidateRect(GetListRect());
return TRUE;
}
void SListCtrl::OnPaint(IRenderTarget * pRT)
{
SPainter painter;
BeforePaint(pRT, painter);
CRect rcList = GetListRect();
int nTopItem = GetTopIndex();
pRT->PushClipRect(&rcList);
CRect rcItem(rcList);
rcItem.bottom = rcItem.top;
rcItem.OffsetRect(0,-(m_ptOrigin.y%m_nItemHeight));
for (int nItem = nTopItem; nItem <= (nTopItem+GetCountPerPage(TRUE)) && nItem<GetItemCount(); rcItem.top = rcItem.bottom, nItem++)
{
rcItem.bottom = rcItem.top + m_nItemHeight;
DrawItem(pRT, rcItem, nItem);
}
pRT->PopClip();
AfterPaint(pRT, painter);
}
BOOL SListCtrl::HitCheckBox(const CPoint& pt)
{
if (!m_bCheckBox)
return FALSE;
CRect rect = GetListRect();
rect.left += ITEM_MARGIN;
rect.OffsetRect(-m_ptOrigin.x,0);
CSize sizeSkin = m_pCheckSkin->GetSkinSize();
int nOffsetX = 3;
CRect rcCheck;
rcCheck.SetRect(0, 0, sizeSkin.cx, sizeSkin.cy);
rcCheck.OffsetRect(rect.left + nOffsetX, 0);
if (pt.x >= rcCheck.left && pt.x <= rcCheck.right)
return TRUE;
return FALSE;
}
void SListCtrl::DrawItem(IRenderTarget * pRT, CRect rcItem, int nItem)
{
BOOL bTextColorChanged = FALSE;
int nBgImg = 0;
COLORREF crOldText=RGBA(0xFF,0xFF,0xFF,0xFF);
COLORREF crItemBg = m_crItemBg;
COLORREF crText = m_crText;
DXLVITEM lvItem = m_arrItems[nItem];
CRect rcIcon, rcText;
if (nItem % 2)
{
// if (m_pItemSkin != NULL)
// nBgImg = 1;
// else if (CR_INVALID != m_crItemBg2)
// crItemBg = m_crItemBg2;
//上面的代码不要了,因为skin间隔效果没必要,只留下颜色间隔就好了
if (CR_INVALID != m_crItemBg2)
crItemBg = m_crItemBg2;
}
if ( lvItem.checked)
{//和下面那个if的条件分开,才会有sel和hot的区别
if (m_pItemSkin != NULL)
nBgImg = 2;
else if (CR_INVALID != m_crItemSelBg)
crItemBg = m_crItemSelBg;
if (CR_INVALID != m_crSelText)
crText = m_crSelText;
}
else if (m_bHotTrack && nItem == m_nHoverItem)
{
if (m_pItemSkin != NULL)
nBgImg = 1;
else if (CR_INVALID != m_crItemHotBg)
crItemBg = m_crItemHotBg;
if (CR_INVALID != m_crSelText)
crText = m_crSelText;
}
//绘制背景
// if (m_pItemSkin != NULL)
// m_pItemSkin->Draw(pRT, rc, nBgImg);
// else if (CR_INVALID != crItemBg)
// pRT->FillSolidRect( rc, crItemBg);
//上面的代码在某些时候,【指定skin的时候,会导致背景异常】,所以颠倒一下顺序
if (CR_INVALID != crItemBg)//先画背景
pRT->FillSolidRect( rcItem, crItemBg);
if (m_pItemSkin != NULL)//有skin,则覆盖背景
m_pItemSkin->Draw(pRT, rcItem, nBgImg);
// 左边加上空白
rcItem.left += ITEM_MARGIN;
if (CR_INVALID != crText)
{
bTextColorChanged = TRUE;
crOldText = pRT->SetTextColor(crText);
}
CRect rcCol(rcItem);
rcCol.right = rcCol.left;
rcCol.OffsetRect(-m_ptOrigin.x,0);
for (int nCol = 0; nCol < GetColumnCount(); nCol++)
{
CRect rcVisiblePart;
SHDITEM hdi;
hdi.mask=SHDI_WIDTH|SHDI_ORDER;
m_pHeader->GetItem(nCol,&hdi);
rcCol.left=rcCol.right;
rcCol.right = rcCol.left + hdi.cx.toPixelSize(GetScale());
rcVisiblePart.IntersectRect(rcItem, rcCol);
if (rcVisiblePart.IsRectEmpty())
continue;
// 绘制 checkbox
if (nCol == 0 && m_bCheckBox && m_pCheckSkin)
{
CSize sizeSkin = m_pCheckSkin->GetSkinSize();
int nOffsetX = 3;
int nOffsetY = (m_nItemHeight - sizeSkin.cy) / 2;
CRect rcCheck;
rcCheck.SetRect(0, 0, sizeSkin.cx, sizeSkin.cy);
rcCheck.OffsetRect(rcCol.left + nOffsetX, rcCol.top + nOffsetY);
m_pCheckSkin->Draw(pRT, rcCheck, lvItem.checked ? 4 : 0);
rcCol.left = sizeSkin.cx + 6 + rcCol.left;
}
DXLVSUBITEM& subItem = lvItem.arSubItems->GetAt(hdi.iOrder);
if (subItem.nImage != -1 && m_pIconSkin)
{
int nOffsetX = m_ptIcon.x;
int nOffsetY = m_ptIcon.y;
CSize sizeSkin = m_pIconSkin->GetSkinSize();
rcIcon.SetRect(0, 0, sizeSkin.cx, sizeSkin.cy);
if (m_ptIcon.x == -1)
nOffsetX = m_nItemHeight / 6;
if (m_ptIcon.y == -1)
nOffsetY = (m_nItemHeight - sizeSkin.cy) / 2;
rcIcon.OffsetRect(rcCol.left + nOffsetX, rcCol.top + nOffsetY);
m_pIconSkin->Draw(pRT, rcIcon, subItem.nImage);
}
UINT align = DT_SINGLELINE;
rcText = rcCol;
if (m_ptText.x == -1)
rcText.left = rcIcon.Width() > 0 ? rcIcon.right + m_nItemHeight / 6 : rcCol.left;
else
rcText.left = rcCol.left + m_ptText.x;
if (m_ptText.y == -1)
align |= DT_VCENTER;
else
rcText.top = rcCol.top + m_ptText.y;
pRT->DrawText(subItem.strText, subItem.cchTextMax, rcText, align);
}
if (bTextColorChanged)
pRT->SetTextColor(crOldText);
}
void SListCtrl::OnDestroy()
{
DeleteAllItems();
__super::OnDestroy();
}
int SListCtrl::GetColumnCount() const
{
if (!m_pHeader)
return 0;
return m_pHeader->GetItemCount();
}
int SListCtrl::GetTopIndex() const
{
return m_ptOrigin.y / m_nItemHeight;
}
void SListCtrl::NotifySelChange(int nOldSel, int nNewSel, BOOL checkBox)
{
EventLCSelChanging evt1(this);
evt1.bCancel = FALSE;
evt1.nOldSel=nOldSel;
evt1.nNewSel=nNewSel;
FireEvent(evt1);
if(evt1.bCancel) return;
if (checkBox) {
if (nNewSel != -1) {
DXLVITEM &newItem = m_arrItems[nNewSel];
newItem.checked = newItem.checked? FALSE:TRUE;
m_nSelectItem = nNewSel;
RedrawItem(nNewSel);
}
} else {
if ((m_bMultiSelection || m_bCheckBox) && GetKeyState(VK_CONTROL) < 0) {
if (nNewSel != -1) {
DXLVITEM &newItem = m_arrItems[nNewSel];
newItem.checked = newItem.checked? FALSE:TRUE;
m_nSelectItem = nNewSel;
RedrawItem(nNewSel);
}
} else if ((m_bMultiSelection || m_bCheckBox) && GetKeyState(VK_SHIFT) < 0) {
if (nNewSel != -1) {
if (nOldSel == -1)
nOldSel = 0;
int imax = (nOldSel > nNewSel) ? nOldSel : nNewSel;
int imin = (imax == nOldSel) ? nNewSel : nOldSel;
for (int i = 0; i < GetItemCount(); i++)
{
DXLVITEM &lvItem = m_arrItems[i];
BOOL last = lvItem.checked;
if (i >= imin && i<= imax) {
lvItem.checked = TRUE;
} else {
lvItem.checked = FALSE;
}
if (last != lvItem.checked)
RedrawItem(i);
}
}
} else {
m_nSelectItem = -1;
for (int i = 0; i < GetItemCount(); i++)
{
DXLVITEM &lvItem = m_arrItems[i];
if (i != nNewSel && lvItem.checked)
{
BOOL last = lvItem.checked;
lvItem.checked = FALSE;
if (last != lvItem.checked)
RedrawItem(i);
}
}
if (nNewSel != -1) {
DXLVITEM &newItem = m_arrItems[nNewSel];
newItem.checked = TRUE;
m_nSelectItem = nNewSel;
RedrawItem(nNewSel);
}
}
}
EventLCSelChanged evt2(this);
evt2.nOldSel=nOldSel;
evt2.nNewSel=nNewSel;
FireEvent(evt2);
}
BOOL SListCtrl::OnScroll(BOOL bVertical, UINT uCode, int nPos)
{
BOOL bRet = __super::OnScroll(bVertical, uCode, nPos);
if (bVertical)
{
m_ptOrigin.y = m_siVer.nPos;
}
else
{
m_ptOrigin.x = m_siHoz.nPos;
// 处理列头滚动
UpdateHeaderCtrl();
}
Invalidate();
if (uCode==SB_THUMBTRACK)
ScrollUpdate();
return bRet;
}
void SListCtrl::OnLButtonDown(UINT nFlags, CPoint pt)
{
__super::OnLButtonDown(nFlags,pt);
m_nHoverItem = HitTest(pt);
BOOL hitCheckBox = HitCheckBox(pt);
if (hitCheckBox)
NotifySelChange(m_nSelectItem, m_nHoverItem, TRUE);
else if (m_nHoverItem!=m_nSelectItem && !m_bHotTrack)
NotifySelChange(m_nSelectItem, m_nHoverItem);
else if (m_nHoverItem != -1 || m_nSelectItem != -1)
NotifySelChange(m_nSelectItem, m_nHoverItem);
}
void SListCtrl::OnLButtonDbClick(UINT nFlags, CPoint pt)
{
m_nHoverItem = HitTest(pt);
if (m_nHoverItem != m_nSelectItem)
NotifySelChange(m_nSelectItem, m_nHoverItem);
EventLCDbClick evt2(this);
evt2.nCurSel = m_nHoverItem;
FireEvent(evt2);
}
void SListCtrl::OnLButtonUp(UINT nFlags, CPoint pt)
{
__super::OnLButtonUp(nFlags,pt);
}
void SListCtrl::UpdateChildrenPosition()
{
__super::UpdateChildrenPosition();
UpdateHeaderCtrl();
}
void SListCtrl::OnSize(UINT nType, CSize size)
{
__super::OnSize(nType,size);
UpdateScrollBar();
UpdateHeaderCtrl();
}
bool SListCtrl::OnHeaderClick(EventArgs *pEvt)
{
return true;
}
bool SListCtrl::OnHeaderSizeChanging(EventArgs *pEvt)
{
UpdateScrollBar();
InvalidateRect(GetListRect());
return true;
}
bool SListCtrl::OnHeaderSwap(EventArgs *pEvt)
{
InvalidateRect(GetListRect());
return true;
}
void SListCtrl::OnMouseMove( UINT nFlags, CPoint pt )
{
int nHoverItem = HitTest(pt);
if(m_bHotTrack && nHoverItem != m_nHoverItem)
{
m_nHoverItem= nHoverItem;
Invalidate();
}
}
void SListCtrl::OnMouseLeave()
{
if(m_bHotTrack)
{
m_nHoverItem=-1;
Invalidate();
}
__super::OnMouseLeave();
}
BOOL SListCtrl::GetCheckState(int nItem)
{
if (nItem >= GetItemCount())
return FALSE;
const DXLVITEM lvItem = m_arrItems[nItem];
return lvItem.checked;
}
BOOL SListCtrl::SetCheckState(int nItem, BOOL bCheck)
{
if (!m_bCheckBox) return FALSE;
if (nItem >= GetItemCount())
return FALSE;
DXLVITEM &lvItem = m_arrItems[nItem];
lvItem.checked = bCheck;
return TRUE;
}
int SListCtrl::GetCheckedItemCount()
{
int ret = 0;
for (int i = 0; i < GetItemCount(); i++)
{
const DXLVITEM lvItem = m_arrItems[i];
if (lvItem.checked)
ret++;
}
return ret;
}
int SListCtrl::GetFirstCheckedItem()
{
int ret = -1;
for (int i = 0; i < GetItemCount(); i++)
{
const DXLVITEM lvItem = m_arrItems[i];
if (lvItem.checked) {
ret = i;
break;
}
}
return ret;
}
int SListCtrl::GetLastCheckedItem()
{
int ret = -1;
for (int i = GetItemCount() - 1; i >= 0; i--)
{
const DXLVITEM lvItem = m_arrItems[i];
if (lvItem.checked) {
ret = i;
break;
}
}
return ret;
}
}//end of namespace
| 23,864 | 9,852 |
#include "controls/menu_controls.h"
#include "DiabloUI/diabloui.h"
#include "controls/remap_keyboard.h"
#include "utils/sdl_compat.h"
namespace devilution {
MenuAction GetMenuAction(const SDL_Event &event)
{
if (event.type == SDL_KEYDOWN) {
auto sym = event.key.keysym.sym;
remap_keyboard_key(&sym);
switch (sym) {
case SDLK_UP:
return MenuAction_UP;
case SDLK_DOWN:
return MenuAction_DOWN;
case SDLK_TAB:
if ((SDL_GetModState() & KMOD_SHIFT) != 0)
return MenuAction_UP;
else
return MenuAction_DOWN;
case SDLK_PAGEUP:
return MenuAction_PAGE_UP;
case SDLK_PAGEDOWN:
return MenuAction_PAGE_DOWN;
case SDLK_RETURN: {
const Uint8 *state = SDLC_GetKeyState();
if (state[SDLC_KEYSTATE_LALT] == 0 && state[SDLC_KEYSTATE_RALT] == 0) {
return MenuAction_SELECT;
}
break;
}
case SDLK_KP_ENTER:
return MenuAction_SELECT;
case SDLK_SPACE:
if (!textInputActive) {
return MenuAction_SELECT;
}
break;
case SDLK_DELETE:
return MenuAction_DELETE;
case SDLK_LEFT:
return MenuAction_LEFT;
case SDLK_RIGHT:
return MenuAction_RIGHT;
case SDLK_ESCAPE:
return MenuAction_BACK;
default:
break;
}
}
return MenuAction_NONE;
} // namespace devilution
} // namespace devilution
| 1,325 | 603 |
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_CONFIG_CHECK_CORE_HPP
#define NAZARA_CONFIG_CHECK_CORE_HPP
/// This file is used to check the constant values defined in Config.hpp
#include <type_traits>
#define NazaraCheckTypeAndVal(name, type, op, val, err) static_assert(std::is_ ##type <decltype(name)>::value && name op val, #type err)
// We force the value of MANAGE_MEMORY in debug
#if defined(NAZARA_DEBUG) && !NAZARA_CORE_MANAGE_MEMORY
#undef NAZARA_CORE_MANAGE_MEMORY
#define NAZARA_CORE_MANAGE_MEMORY 0
#endif
NazaraCheckTypeAndVal(NAZARA_CORE_DECIMAL_DIGITS, integral, >, 0, " shall be a strictly positive integer");
NazaraCheckTypeAndVal(NAZARA_CORE_FILE_BUFFERSIZE, integral, >, 0, " shall be a strictly positive integer");
NazaraCheckTypeAndVal(NAZARA_CORE_WINDOWS_CS_SPINLOCKS, integral, >=, 0, " shall be a positive integer");
#undef NazaraCheckTypeAndVal
#endif // NAZARA_CONFIG_CHECK_CORE_HPP
| 1,075 | 417 |
#include <shogun/lib/Hash.h>
#include <stdio.h>
using namespace shogun;
int main(int argc, char** argv)
{
uint8_t array[4]={0,1,2,3};
printf("hash(0)=%0x\n", CHash::MurmurHash3(&array[0], 1, 0xDEADBEAF));
printf("hash(1)=%0x\n", CHash::MurmurHash3(&array[1], 1, 0xDEADBEAF));
printf("hash(2)=%0x\n", CHash::MurmurHash3(&array[0], 2, 0xDEADBEAF));
printf("hash(3)=%0x\n", CHash::MurmurHash3(&array[0], 4, 0xDEADBEAF));
uint32_t h = 0xDEADBEAF;
uint32_t carry = 0;
CHash::IncrementalMurmurHash3(&h, &carry, &array[0], 1);
printf("inc_hash(0)=%0x\n", h);
CHash::IncrementalMurmurHash3(&h, &carry, &array[1], 1);
printf("inc_hash(1)=%0x\n", h);
CHash::IncrementalMurmurHash3(&h, &carry, &array[2], 1);
printf("inc_hash(2)=%0x\n", h);
CHash::IncrementalMurmurHash3(&h, &carry, &array[3], 1);
printf("inc_hash(3)=%0x\n", h);
h = CHash::FinalizeIncrementalMurmurHash3(h, carry, 4);
printf("Final inc_hash(3)=%0x\n", h);
return 0;
}
| 956 | 487 |
#include "IgnoresPage.hpp"
#include "Application.hpp"
#include "controllers/accounts/AccountController.hpp"
#include "controllers/ignores/IgnoreController.hpp"
#include "controllers/ignores/IgnoreModel.hpp"
#include "providers/twitch/TwitchAccount.hpp"
#include "singletons/Settings.hpp"
#include "util/LayoutCreator.hpp"
#include "widgets/helper/EditableModelView.hpp"
#include <QCheckBox>
#include <QGroupBox>
#include <QHeaderView>
#include <QLabel>
#include <QListView>
#include <QPushButton>
#include <QTableView>
#include <QVBoxLayout>
// clang-format off
#define INFO "/ignore <user> in chat ignores a user.\n/unignore <user> in chat unignores a user.\nYou can also click on a user to open the usercard."
// clang-format on
namespace chatterino {
static void addPhrasesTab(LayoutCreator<QVBoxLayout> box);
static void addUsersTab(IgnoresPage &page, LayoutCreator<QVBoxLayout> box,
QStringListModel &model);
IgnoresPage::IgnoresPage()
{
LayoutCreator<IgnoresPage> layoutCreator(this);
auto layout = layoutCreator.setLayoutType<QVBoxLayout>();
auto tabs = layout.emplace<QTabWidget>();
addPhrasesTab(tabs.appendTab(new QVBoxLayout, "Messages"));
addUsersTab(*this, tabs.appendTab(new QVBoxLayout, "Users"),
this->userListModel_);
}
void addPhrasesTab(LayoutCreator<QVBoxLayout> layout)
{
layout.emplace<QLabel>("Ignore messages based certain patterns.");
EditableModelView *view =
layout
.emplace<EditableModelView>(
(new IgnoreModel(nullptr))
->initialized(&getSettings()->ignoredMessages))
.getElement();
view->setTitles(
{"Pattern", "Regex", "Case Sensitive", "Block", "Replacement"});
view->getTableView()->horizontalHeader()->setSectionResizeMode(
QHeaderView::Fixed);
view->getTableView()->horizontalHeader()->setSectionResizeMode(
0, QHeaderView::Stretch);
view->addRegexHelpLink();
QTimer::singleShot(1, [view] {
view->getTableView()->resizeColumnsToContents();
view->getTableView()->setColumnWidth(0, 200);
});
view->addButtonPressed.connect([] {
getSettings()->ignoredMessages.append(
IgnorePhrase{"my pattern", false, false,
getSettings()->ignoredPhraseReplace.getValue(), true});
});
}
void addUsersTab(IgnoresPage &page, LayoutCreator<QVBoxLayout> users,
QStringListModel &userModel)
{
auto label = users.emplace<QLabel>(INFO);
label->setWordWrap(true);
users.append(page.createCheckBox("Enable twitch ignored users",
getSettings()->enableTwitchIgnoredUsers));
auto anyways = users.emplace<QHBoxLayout>().withoutMargin();
{
anyways.emplace<QLabel>("Show messages from ignored users anyways:");
auto combo = anyways.emplace<QComboBox>().getElement();
combo->addItems(
{"Never", "If you are Moderator", "If you are Broadcaster"});
auto &setting = getSettings()->showIgnoredUsersMessages;
setting.connect(
[combo](const int value) { combo->setCurrentIndex(value); });
QObject::connect(combo,
QOverload<int>::of(&QComboBox::currentIndexChanged),
[&setting](int index) {
if (index != -1)
setting = index;
});
anyways->addStretch(1);
}
/*auto addremove = users.emplace<QHBoxLayout>().withoutMargin();
{
auto add = addremove.emplace<QPushButton>("Ignore user");
auto remove = addremove.emplace<QPushButton>("Unignore User");
addremove->addStretch(1);
}*/
users.emplace<QLabel>("List of ignored users:");
users.emplace<QListView>()->setModel(&userModel);
}
void IgnoresPage::onShow()
{
auto app = getApp();
auto user = app->accounts->twitch.getCurrent();
if (user->isAnon())
{
return;
}
QStringList users;
for (const auto &ignoredUser : user->getIgnores())
{
users << ignoredUser.name;
}
users.sort(Qt::CaseInsensitive);
this->userListModel_.setStringList(users);
}
} // namespace chatterino
| 4,279 | 1,283 |
/*
MIT License
Copyright (c) 2019 Zhehang Ding
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "core/film.h"
#include <math.h>
#include <fstream>
#include <sstream>
namespace qjulia {
CPU_AND_CUDA Point2f GenerateCameraCoords(Point2f src, Size size) {
Float c = src[1];
Float r= src[0];
Float ss = (Float)(size.width < size.height ? size.width : size.height - 1);
Float x = (c - (size.width - 1) * 0.5f) / ss;
Float y = ((size.height - 1) * 0.5f - r) / ss;
return {x, y};
}
/*
void SaveToPPM(const std::string &filename, const Film &film, Float scale) {
int w = film.Width();
int h = film.Height();
std::vector<unsigned char> buf(w * h * 3);
auto *p = buf.data();
for (int i = 0; i < (w * h); ++i) {
const auto &sp = film.At(i);
for (int ch = 0; ch < 3; ++ch) {
*(p++) = std::min(255, std::max(0, (int)std::round(sp[ch] * scale)));
}
}
std::ostringstream header_stream;
header_stream << "P6 " << w << ' ' << h << ' ' << 255 << '\n';
std::string header = header_stream.str();
std::ofstream file_stream(filename, std::ofstream::binary);
file_stream.write(header.c_str(), header.size());
file_stream.write(reinterpret_cast<const char*>(buf.data()), buf.size());
}*/
}
| 2,218 | 817 |
#include<iostream>
using namespace std;
int main()
{
int b[3][3];
int a [3] [3]={1,2,3,4,5,6,7,8,9};
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
b[i][j]=a[2-i] [2-j];
}
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
cout<<b[i][j]<<" ";
}
cout<<endl;
}
return 0;
} | 336 | 185 |
#include "keyboard.hpp"
#include <algorithm>
namespace town
{
Keyboard::KeyList Keyboard::_KeysUp;
Keyboard::KeyList Keyboard::_KeysDown;
bool Keyboard::isKeyPressed(sf::Keyboard::Key key)
{
return sf::Keyboard::isKeyPressed(key);
}
bool Keyboard::isKeyUp(sf::Keyboard::Key key)
{
return std::find(_KeysUp.begin(), _KeysUp.end(), key) != _KeysUp.end();
}
bool Keyboard::isKeyDown(sf::Keyboard::Key key)
{
return std::find(_KeysDown.begin(), _KeysDown.end(), key) != _KeysDown.end();
}
void Keyboard::resetKeys()
{
_KeysUp.clear();
_KeysDown.clear();
}
void Keyboard::setKeyUp(sf::Keyboard::Key key)
{
_KeysUp.push_back(key);
}
void Keyboard::setKeyDown(sf::Keyboard::Key key)
{
_KeysDown.push_back(key);
}
} | 851 | 301 |
#pragma once
#include "../Name.hpp"
#include <list>
template<typename T>
struct Ubpa::details::custom_type_name<std::list<T>> {
static constexpr auto get() noexcept {
return concat_seq(
TSTR("std::list<{"),
type_name<T>(),
TStrC_of<'}', '>'>{}
);
}
};
| 270 | 119 |
#pragma once
#include <QSet>
#include <QPointer>
#include <QAbstractItemModel>
#include <QItemSelectionModel>
#include <QPersistentModelIndex>
class TreeViewModelAdaptor : public QAbstractItemModel {
Q_OBJECT
Q_PROPERTY(QAbstractItemModel* model READ model WRITE setModel NOTIFY modelChanged)
Q_PROPERTY(QModelIndex rootIndex READ rootIndex WRITE setRootIndex RESET resetRootIndex NOTIFY rootIndexChanged)
struct TreeItem;
public:
explicit TreeViewModelAdaptor(QObject* parent = nullptr);
QAbstractItemModel* model() const;
const QModelIndex& rootIndex() const;
void setRootIndex(const QModelIndex& idx);
void resetRootIndex();
QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const;
QModelIndex parent(const QModelIndex& child) const;
int rowCount(const QModelIndex& parent = QModelIndex()) const;
int columnCount(const QModelIndex& parent = QModelIndex()) const;
enum {
DepthRole = Qt::UserRole - 5,
ExpandedRole,
HasChildrenRole,
HasSiblingRole,
ModelIndexRole,
};
QHash<int, QByteArray> roleNames() const;
QVariant data(const QModelIndex&, int role) const;
bool setData(const QModelIndex& index, const QVariant& value, int role);
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
void clearModelData();
bool isVisible(const QModelIndex& index);
bool childrenVisible(const QModelIndex& index);
QModelIndex mapToModel(const QModelIndex& index) const;
QModelIndex mapFromModel(const QModelIndex& index) const;
QModelIndex mapToModel(int row) const;
Q_INVOKABLE QItemSelection selectionForRowRange(const QModelIndex& fromIndex, const QModelIndex& toIndex) const;
void showModelTopLevelItems(bool doInsertRows = true);
void showModelChildItems(
const TreeItem& parent, int start, int end, bool doInsertRows = true, bool doExpandPendingRows = true);
int itemIndex(const QModelIndex& index) const;
void expandPendingRows(bool doInsertRows = true);
int lastChildIndex(const QModelIndex& index);
void removeVisibleRows(int startIndex, int endIndex, bool doRemoveRows = true);
void dump() const;
bool testConsistency(bool dumpOnFail = false) const;
using QAbstractItemModel::hasChildren;
signals:
void modelChanged(QAbstractItemModel* model);
void rootIndexChanged();
void expanded(const QModelIndex& index);
void collapsed(const QModelIndex& index);
public slots:
void expand(const QModelIndex&);
void collapse(const QModelIndex&);
void setModel(QAbstractItemModel* model);
bool isExpanded(const QModelIndex&) const;
bool isExpanded(int row) const;
bool hasChildren(int row) const;
bool hasSiblings(int row) const;
int depthAtRow(int row) const;
void expandRow(int n);
void collapseRow(int n);
private slots:
void modelHasBeenDestroyed();
void modelHasBeenReset();
void modelDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRigth, const QVector<int>& roles);
void modelLayoutAboutToBeChanged(
const QList<QPersistentModelIndex>& parents, QAbstractItemModel::LayoutChangeHint hint);
void modelLayoutChanged(const QList<QPersistentModelIndex>& parents, QAbstractItemModel::LayoutChangeHint hint);
void modelRowsAboutToBeInserted(const QModelIndex& parent, int start, int end);
void modelRowsAboutToBeMoved(const QModelIndex& sourceParent, int sourceStart, int sourceEnd,
const QModelIndex& destinationParent, int destinationRow);
void modelRowsAboutToBeRemoved(const QModelIndex& parent, int start, int end);
void modelRowsInserted(const QModelIndex& parent, int start, int end);
void modelRowsMoved(const QModelIndex& sourceParent, int sourceStart, int sourceEnd,
const QModelIndex& destinationParent, int destinationRow);
void modelRowsRemoved(const QModelIndex& parent, int start, int end);
private:
struct TreeItem {
QPersistentModelIndex index;
int depth;
bool expanded;
explicit TreeItem(const QModelIndex& idx = {}, int d = 0, int e = false)
: index(idx)
, depth(d)
, expanded(e) {}
inline bool operator==(const TreeItem& other) const {
return this->index == other.index;
}
};
struct DataChangedParams {
QModelIndex topLeft;
QModelIndex bottomRight;
QVector<int> roles;
};
struct SignalFreezer {
SignalFreezer(TreeViewModelAdaptor* parent)
: parent(parent) {
parent->enableSignalAggregation();
}
~SignalFreezer() {
parent->disableSignalAggregation();
}
private:
TreeViewModelAdaptor* parent;
};
void enableSignalAggregation();
void disableSignalAggregation();
bool isAggregatingSignals() const;
void queueDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight, const QVector<int>& roles);
void emitQueuedSignals();
QPointer<QAbstractItemModel> _model = nullptr;
QPersistentModelIndex _rootIndex;
QList<TreeItem> _items;
QSet<QPersistentModelIndex> _expandedItems;
QList<TreeItem*> _itemsToExpand;
mutable int _lastItemIndex = 0;
bool _visibleRowsMoved = false;
int _signalAggregatorStack = 0;
QVector<DataChangedParams> _queuedDataChanged;
int _column = 0;
};
| 5,032 | 1,638 |
//
// test_esdhttp.hpp
// EyeOfSauronDHTMonitor
//
// Created by shuaizhai on 4/25/16.
// Copyright © 2016 com.dhtMonitor.www. All rights reserved.
//
#ifndef test_esdhttp_hpp
#define test_esdhttp_hpp
#include <stdio.h>
#include "ESDHttpUtility.hpp"
#include "ESDHttpProtocol.hpp"
namespace test_esdhttp {
void test_esdhttp();
}
#endif /* test_esdhttp_hpp */
| 381 | 167 |
/*
Copyright (C) 2011 James Coliz, Jr. <maniacbug@ymail.com>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.
*/
#include "RF24Network_config.h"
#if defined (RF24_LINUX)
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#include <iostream>
#include <algorithm>
#include <RF24/RF24.h>
#include "RF24Network.h"
#else
#include "RF24.h"
#include "RF24Network.h"
#endif
#if defined (ENABLE_SLEEP_MODE) && !defined (RF24_LINUX) && !defined (__ARDUINO_X86__)
#include <avr/sleep.h>
#include <avr/power.h>
volatile byte sleep_cycles_remaining;
volatile bool wasInterrupted;
#endif
uint16_t RF24NetworkHeader::next_id = 1;
#if defined ENABLE_NETWORK_STATS
uint32_t RF24Network::nFails = 0;
uint32_t RF24Network::nOK = 0;
#endif
uint64_t pipe_address( uint16_t node, uint8_t pipe );
#if defined (RF24NetworkMulticast)
uint16_t levelToAddress( uint8_t level );
#endif
bool is_valid_address( uint16_t node );
/******************************************************************/
#if defined (RF24_LINUX)
#if !defined (DUAL_HEAD_RADIO)
RF24Network::RF24Network( RF24& _radio ): radio(_radio), frame_size(MAX_FRAME_SIZE)
#else
RF24Network::RF24Network( RF24& _radio, RF24& _radio1 ): radio(_radio), radio1(_radio1),frame_size(MAX_FRAME_SIZE)
#endif
{
}
#elif !defined (DUAL_HEAD_RADIO)
RF24Network::RF24Network( RF24& _radio ): radio(_radio), next_frame(frame_queue)
{
#if !defined ( DISABLE_FRAGMENTATION )
frag_queue.message_buffer=&frag_queue_message_buffer[0];
frag_ptr = &frag_queue;
#endif
}
#else
RF24Network::RF24Network( RF24& _radio, RF24& _radio1 ): radio(_radio), radio1(_radio1), next_frame(frame_queue)
{
#if !defined ( DISABLE_FRAGMENTATION )
frag_queue.message_buffer=&frag_queue_message_buffer[0];
frag_ptr = &frag_queue;
#endif
}
#endif
/******************************************************************/
void RF24Network::begin(uint8_t _channel, uint16_t _node_address )
{
if (! is_valid_address(_node_address) )
return;
node_address = _node_address;
if ( ! radio.isValid() ){
return;
}
// Set up the radio the way we want it to look
if(_channel != USE_CURRENT_CHANNEL){
radio.setChannel(_channel);
}
//radio.enableDynamicAck();
radio.setAutoAck(0,0);
#if defined (ENABLE_DYNAMIC_PAYLOADS)
radio.enableDynamicPayloads();
#endif
// Use different retry periods to reduce data collisions
uint8_t retryVar = (((node_address % 6)+1) *2) + 3;
radio.setRetries(retryVar, 5); // max about 85ms per attempt
txTimeout = 25;
routeTimeout = txTimeout*3; // Adjust for max delay per node within a single chain
#if defined (DUAL_HEAD_RADIO)
radio1.setChannel(_channel);
radio1.enableDynamicAck();
radio1.enableDynamicPayloads();
#endif
// Setup our address helper cache
setup_address();
// Open up all listening pipes
uint8_t i = 6;
while (i--){
radio.openReadingPipe(i,pipe_address(_node_address,i));
}
radio.startListening();
}
/******************************************************************/
#if defined ENABLE_NETWORK_STATS
void RF24Network::failures(uint32_t *_fails, uint32_t *_ok){
*_fails = nFails;
*_ok = nOK;
}
#endif
/******************************************************************/
uint8_t RF24Network::update(void)
{
// if there is data ready
uint8_t pipe_num;
uint8_t returnVal = 0;
// If bypass is enabled, continue although incoming user data may be dropped
// Allows system payloads to be read while user cache is full
// Incoming Hold prevents data from being read from the radio, preventing incoming payloads from being acked
#if !defined (RF24_LINUX)
if(!(networkFlags & FLAG_BYPASS_HOLDS)){
if( (networkFlags & FLAG_HOLD_INCOMING) || (next_frame-frame_queue) + 34 > MAIN_BUFFER_SIZE ){
if(!available()){
networkFlags &= ~FLAG_HOLD_INCOMING;
}else{
return 0;
}
}
}
#endif
while ( radio.isValid() && radio.available(&pipe_num) ){
#if defined (ENABLE_DYNAMIC_PAYLOADS)
if( (frame_size = radio.getDynamicPayloadSize() ) < sizeof(RF24NetworkHeader)){
delay(10);
continue;
}
#else
frame_size=32;
#endif
// Dump the payloads until we've gotten everything
// Fetch the payload, and see if this was the last one.
radio.read( frame_buffer, frame_size );
// Read the beginning of the frame as the header
RF24NetworkHeader *header = (RF24NetworkHeader*)(&frame_buffer);
#if defined (RF24_LINUX)
IF_SERIAL_DEBUG(printf_P("%u: MAC Received on %u %s\n\r",millis(),pipe_num,header->toString()));
if (frame_size) {
IF_SERIAL_DEBUG_FRAGMENTATION_L2(printf("%u: FRG Rcv frame size %i\n",millis(),frame_size););
IF_SERIAL_DEBUG_FRAGMENTATION_L2(printf("%u: FRG Rcv frame ",millis()); const char* charPtr = reinterpret_cast<const char*>(frame_buffer); for (uint16_t i = 0; i < frame_size; i++) { printf("%02X ", charPtr[i]); }; printf("\n\r"));
}
#else
IF_SERIAL_DEBUG(printf_P(PSTR("%lu: MAC Received on %u %s\n\r"),millis(),pipe_num,header->toString()));
IF_SERIAL_DEBUG(const uint16_t* i = reinterpret_cast<const uint16_t*>(frame_buffer + sizeof(RF24NetworkHeader));printf_P(PSTR("%lu: NET message %04x\n\r"),millis(),*i));
#endif
// Throw it away if it's not a valid address
if ( !is_valid_address(header->to_node) ){
continue;
}
uint8_t returnVal = header->type;
// Is this for us?
if ( header->to_node == node_address ){
if(header->type == NETWORK_PING){
continue;
}
if(header->type == NETWORK_ADDR_RESPONSE ){
uint16_t requester = 04444;
if(requester != node_address){
header->to_node = requester;
write(header->to_node,USER_TX_TO_PHYSICAL_ADDRESS);
delay(10);
write(header->to_node,USER_TX_TO_PHYSICAL_ADDRESS);
//printf("Fwd add response to 0%o\n",requester);
continue;
}
}
if(header->type == NETWORK_REQ_ADDRESS && node_address){
//printf("Fwd add req to 0\n");
header->from_node = node_address;
header->to_node = 0;
write(header->to_node,TX_NORMAL);
continue;
}
if( (returnSysMsgs && header->type > 127) || header->type == NETWORK_ACK ){
IF_SERIAL_DEBUG_ROUTING( printf_P(PSTR("%lu MAC: System payload rcvd %d\n"),millis(),returnVal); );
//if( (header->type < 148 || header->type > 150) && header->type != NETWORK_MORE_FRAGMENTS_NACK && header->type != EXTERNAL_DATA_TYPE && header->type!= NETWORK_LAST_FRAGMENT){
if( header->type != NETWORK_FIRST_FRAGMENT && header->type != NETWORK_MORE_FRAGMENTS && header->type != NETWORK_MORE_FRAGMENTS_NACK && header->type != EXTERNAL_DATA_TYPE && header->type!= NETWORK_LAST_FRAGMENT){
return returnVal;
}
}
if( enqueue(header) == 2 ){ //External data received
#if defined (SERIAL_DEBUG_MINIMAL)
printf("ret ext\n");
#endif
return EXTERNAL_DATA_TYPE;
}
}else{
#if defined (RF24NetworkMulticast)
if( header->to_node == 0100){
if(header->type == NETWORK_POLL && node_address != 04444 ){
if( !(networkFlags & FLAG_NO_POLL) ){
header->to_node = header->from_node;
header->from_node = node_address;
delay(parent_pipe);
write(header->to_node,USER_TX_TO_PHYSICAL_ADDRESS);
}
continue;
}
uint8_t val = enqueue(header);
if(multicastRelay){
IF_SERIAL_DEBUG_ROUTING( printf_P(PSTR("%u MAC: FWD multicast frame from 0%o to level %u\n"),millis(),header->from_node,multicast_level+1); );
write(levelToAddress(multicast_level)<<3,4);
}
if( val == 2 ){ //External data received
//Serial.println("ret ext multicast");
return EXTERNAL_DATA_TYPE;
}
}else{
write(header->to_node,1); //Send it on, indicate it is a routed payload
}
#else
write(header->to_node,1); //Send it on, indicate it is a routed payload
#endif
}
}
return returnVal;
}
#if defined (RF24_LINUX)
/******************************************************************/
uint8_t RF24Network::enqueue(RF24NetworkHeader* header) {
uint8_t result = false;
RF24NetworkFrame frame = RF24NetworkFrame(*header,frame_buffer+sizeof(RF24NetworkHeader),frame_size-sizeof(RF24NetworkHeader));
bool isFragment = ( frame.header.type == NETWORK_FIRST_FRAGMENT || frame.header.type == NETWORK_MORE_FRAGMENTS || frame.header.type == NETWORK_LAST_FRAGMENT || frame.header.type == NETWORK_MORE_FRAGMENTS_NACK);
// This is sent to itself
if (frame.header.from_node == node_address) {
if (isFragment) {
printf("Cannot enqueue multi-payload frames to self\n");
result = false;
}else{
frame_queue.push(frame);
result = true;
}
}else
if (isFragment)
{
//The received frame contains the a fragmented payload
//Set the more fragments flag to indicate a fragmented frame
IF_SERIAL_DEBUG_FRAGMENTATION_L2(printf("%u: FRG Payload type %d of size %i Bytes with fragmentID '%i' received.\n\r",millis(),frame.header.type,frame.message_size,frame.header.reserved););
//Append payload
result = appendFragmentToFrame(frame);
//The header.reserved contains the actual header.type on the last fragment
if ( result && frame.header.type == NETWORK_LAST_FRAGMENT) {
IF_SERIAL_DEBUG_FRAGMENTATION(printf("%u: FRG Last fragment received. \n",millis() ););
IF_SERIAL_DEBUG(printf_P(PSTR("%u: NET Enqueue assembled frame @%x "),millis(),frame_queue.size()));
RF24NetworkFrame *f = &(frameFragmentsCache[ frame.header.from_node ] );
result=f->header.type == EXTERNAL_DATA_TYPE ? 2 : 1;
//Load external payloads into a separate queue on linux
if(result == 2){
external_queue.push( frameFragmentsCache[ frame.header.from_node ] );
}else{
frame_queue.push( frameFragmentsCache[ frame.header.from_node ] );
}
frameFragmentsCache.erase( frame.header.from_node );
}
}else{// if (frame.header.type <= MAX_USER_DEFINED_HEADER_TYPE) {
//This is not a fragmented payload but a whole frame.
IF_SERIAL_DEBUG(printf_P(PSTR("%u: NET Enqueue @%x "),millis(),frame_queue.size()));
// Copy the current frame into the frame queue
result=frame.header.type == EXTERNAL_DATA_TYPE ? 2 : 1;
//Load external payloads into a separate queue on linux
if(result == 2){
external_queue.push( frame );
}else{
frame_queue.push( frame );
}
}/* else {
//Undefined/Unknown header.type received. Drop frame!
IF_SERIAL_DEBUG_MINIMAL( printf("%u: FRG Received unknown or system header type %d with fragment id %d\n",millis(),frame.header.type, frame.header.reserved); );
//The frame is not explicitly dropped, but the given object is ignored.
//FIXME: does this causes problems with memory management?
}*/
if (result) {
//IF_SERIAL_DEBUG(printf("ok\n\r"));
} else {
IF_SERIAL_DEBUG(printf("failed\n\r"));
}
return result;
}
/******************************************************************/
bool RF24Network::appendFragmentToFrame(RF24NetworkFrame frame) {
// This is the first of 2 or more fragments.
if (frame.header.type == NETWORK_FIRST_FRAGMENT){
if( frameFragmentsCache.count(frame.header.from_node) != 0 ){
RF24NetworkFrame *f = &(frameFragmentsCache[ frame.header.from_node ]);
//Already rcvd first frag
if (f->header.id == frame.header.id){
return false;
}
}
if(frame.header.reserved > (MAX_PAYLOAD_SIZE /24) + 1 ){
IF_SERIAL_DEBUG_FRAGMENTATION( printf("%u FRG Too many fragments in payload %u, dropping...",millis(),frame.header.reserved); );
// If there are more fragments than we can possibly handle, return
return false;
}
frameFragmentsCache[ frame.header.from_node ] = frame;
return true;
}else
if ( frame.header.type == NETWORK_MORE_FRAGMENTS || frame.header.type == NETWORK_MORE_FRAGMENTS_NACK ){
if( frameFragmentsCache.count(frame.header.from_node) < 1 ){
return false;
}
RF24NetworkFrame *f = &(frameFragmentsCache[ frame.header.from_node ]);
if( f->header.reserved - 1 == frame.header.reserved && f->header.id == frame.header.id){
// Cache the fragment
memcpy(f->message_buffer+f->message_size, frame.message_buffer, frame.message_size);
f->message_size += frame.message_size; //Increment message size
f->header = frame.header; //Update header
return true;
} else {
IF_SERIAL_DEBUG_FRAGMENTATION(printf("%u: FRG Dropping fragment for frame with header id:%d, out of order fragment(s).\n",millis(),frame.header.id););
return false;
}
}else
if ( frame.header.type == NETWORK_LAST_FRAGMENT ){
//We have received the last fragment
if(frameFragmentsCache.count(frame.header.from_node) < 1){
return false;
}
//Create pointer to the cached frame
RF24NetworkFrame *f = &(frameFragmentsCache[ frame.header.from_node ]);
if( f->message_size + frame.message_size > MAX_PAYLOAD_SIZE){
IF_SERIAL_DEBUG_FRAGMENTATION( printf("%u FRG Frame of size %u plus enqueued frame of size %u exceeds max payload size \n",millis(),frame.message_size,f->message_size); );
return false;
}
//Error checking for missed fragments and payload size
if ( f->header.reserved-1 != 1 || f->header.id != frame.header.id) {
IF_SERIAL_DEBUG_FRAGMENTATION(printf("%u: FRG Duplicate or out of sequence frame %d, expected %d. Cleared.\n",millis(),frame.header.reserved,f->header.reserved););
//frameFragmentsCache.erase( std::make_pair(frame.header.id,frame.header.from_node) );
return false;
}
//The user specified header.type is sent with the last fragment in the reserved field
frame.header.type = frame.header.reserved;
frame.header.reserved = 1;
//Append the received fragment to the cached frame
memcpy(f->message_buffer+f->message_size, frame.message_buffer, frame.message_size);
f->message_size += frame.message_size; //Increment message size
f->header = frame.header; //Update header
return true;
}
return false;
}
/******************************************************************/
/******************************************************************/
#else // Not defined RF24_Linux:
/******************************************************************/
/******************************************************************/
uint8_t RF24Network::enqueue(RF24NetworkHeader* header)
{
bool result = false;
uint8_t message_size = frame_size - sizeof(RF24NetworkHeader);
IF_SERIAL_DEBUG(printf_P(PSTR("%lu: NET Enqueue @%x "),millis(),next_frame-frame_queue));
#if !defined ( DISABLE_FRAGMENTATION )
bool isFragment = header->type == NETWORK_FIRST_FRAGMENT || header->type == NETWORK_MORE_FRAGMENTS || header->type == NETWORK_LAST_FRAGMENT || header->type == NETWORK_MORE_FRAGMENTS_NACK ;
if(isFragment){
if(header->type == NETWORK_FIRST_FRAGMENT){
// Drop frames exceeding max size and duplicates (MAX_PAYLOAD_SIZE needs to be divisible by 24)
if(header->reserved > (MAX_PAYLOAD_SIZE / max_frame_payload_size) ){
#if defined (SERIAL_DEBUG_FRAGMENTATION) || defined (SERIAL_DEBUG_MINIMAL)
printf_P(PSTR("Frag frame with %d frags exceeds MAX_PAYLOAD_SIZE or out of sequence\n"),header->reserved);
#endif
frag_queue.header.reserved = 0;
return false;
}else
if(frag_queue.header.id == header->id && frag_queue.header.from_node == header->from_node){
return true;
}
if( (header->reserved * 24) > (MAX_PAYLOAD_SIZE - (next_frame-frame_queue)) ){
networkFlags |= FLAG_HOLD_INCOMING;
radio.stopListening();
}
memcpy(&frag_queue,&frame_buffer,8);
memcpy(frag_queue.message_buffer,frame_buffer+sizeof(RF24NetworkHeader),message_size);
//IF_SERIAL_DEBUG_FRAGMENTATION( Serial.print(F("queue first, total frags ")); Serial.println(header->reserved); );
//Store the total size of the stored frame in message_size
frag_queue.message_size = message_size;
--frag_queue.header.reserved;
IF_SERIAL_DEBUG_FRAGMENTATION_L2( for(int i=0; i<frag_queue.message_size;i++){ Serial.println(frag_queue.message_buffer[i],HEX); } );
return true;
}else // NETWORK_MORE_FRAGMENTS
if(header->type == NETWORK_LAST_FRAGMENT || header->type == NETWORK_MORE_FRAGMENTS || header->type == NETWORK_MORE_FRAGMENTS_NACK){
if(frag_queue.message_size + message_size > MAX_PAYLOAD_SIZE){
#if defined (SERIAL_DEBUG_FRAGMENTATION) || defined (SERIAL_DEBUG_MINIMAL)
Serial.print(F("Drop frag ")); Serial.print(header->reserved);
Serial.println(F(" Size exceeds max"));
#endif
frag_queue.header.reserved=0;
return false;
}
if( frag_queue.header.reserved == 0 || (header->type != NETWORK_LAST_FRAGMENT && header->reserved != frag_queue.header.reserved ) || frag_queue.header.id != header->id ){
#if defined (SERIAL_DEBUG_FRAGMENTATION) || defined (SERIAL_DEBUG_MINIMAL)
Serial.print(F("Drop frag ")); Serial.print(header->reserved);
//Serial.print(F(" header id ")); Serial.print(header->id);
Serial.println(F(" Out of order "));
#endif
return false;
}
memcpy(frag_queue.message_buffer+frag_queue.message_size,frame_buffer+sizeof(RF24NetworkHeader),message_size);
frag_queue.message_size += message_size;
if(header->type != NETWORK_LAST_FRAGMENT){
--frag_queue.header.reserved;
return true;
}
frag_queue.header.reserved = 0;
frag_queue.header.type = header->reserved;
IF_SERIAL_DEBUG_FRAGMENTATION( printf_P(PSTR("fq 3: %d\n"),frag_queue.message_size); );
IF_SERIAL_DEBUG_FRAGMENTATION_L2(for(int i=0; i< frag_queue.message_size;i++){ Serial.println(frag_queue.message_buffer[i],HEX); } );
//Frame assembly complete, copy to main buffer if OK
if(frag_queue.header.type == EXTERNAL_DATA_TYPE){
return 2;
}
#if defined (DISABLE_USER_PAYLOADS)
return 0;
#endif
if(MAX_PAYLOAD_SIZE - (next_frame-frame_queue) >= frag_queue.message_size){
memcpy(next_frame,&frag_queue,10);
memcpy(next_frame+10,frag_queue.message_buffer,frag_queue.message_size);
next_frame += (10+frag_queue.message_size);
IF_SERIAL_DEBUG_FRAGMENTATION( printf_P(PSTR("enq size %d\n"),frag_queue.message_size); );
return true;
}else{
radio.stopListening();
networkFlags |= FLAG_HOLD_INCOMING;
}
IF_SERIAL_DEBUG_FRAGMENTATION( printf_P(PSTR("Drop frag payload, queue full\n")); );
return false;
}//If more or last fragments
}else //else is not a fragment
#endif // End fragmentation enabled
// Copy the current frame into the frame queue
#if !defined( DISABLE_FRAGMENTATION )
if(header->type == EXTERNAL_DATA_TYPE){
memcpy(&frag_queue,&frame_buffer,8);
frag_queue.message_buffer = frame_buffer+sizeof(RF24NetworkHeader);
frag_queue.message_size = message_size;
return 2;
}
#endif
#if defined (DISABLE_USER_PAYLOADS)
return 0;
}
#else
if(message_size + (next_frame-frame_queue) <= MAIN_BUFFER_SIZE){
memcpy(next_frame,&frame_buffer,8);
RF24NetworkFrame *f = (RF24NetworkFrame*)next_frame;
f->message_size = message_size;
memcpy(next_frame+10,frame_buffer+sizeof(RF24NetworkHeader),message_size);
//IF_SERIAL_DEBUG_FRAGMENTATION( for(int i=0; i<message_size;i++){ Serial.print(next_frame[i],HEX); Serial.print(" : "); } Serial.println(""); );
next_frame += (message_size + 10);
//IF_SERIAL_DEBUG_FRAGMENTATION( Serial.print("Enq "); Serial.println(next_frame-frame_queue); );//printf_P(PSTR("enq %d\n"),next_frame-frame_queue); );
result = true;
}else{
result = false;
IF_SERIAL_DEBUG(printf_P(PSTR("NET **Drop Payload** Buffer Full")));
}
return result;
}
#endif //USER_PAYLOADS_ENABLED
#endif //End not defined RF24_Linux
/******************************************************************/
bool RF24Network::available(void)
{
#if defined (RF24_LINUX)
return (!frame_queue.empty());
#else
// Are there frames on the queue for us?
return (next_frame > frame_queue);
#endif
}
/******************************************************************/
uint16_t RF24Network::parent() const
{
if ( node_address == 0 )
return -1;
else
return parent_node;
}
/******************************************************************/
/*uint8_t RF24Network::peekData(){
return frame_queue[0];
}*/
uint16_t RF24Network::peek(RF24NetworkHeader& header)
{
if ( available() )
{
#if defined (RF24_LINUX)
RF24NetworkFrame frame = frame_queue.front();
memcpy(&header,&frame.header,sizeof(RF24NetworkHeader));
return frame.message_size;
#else
RF24NetworkFrame *frame = (RF24NetworkFrame*)(frame_queue);
memcpy(&header,&frame->header,sizeof(RF24NetworkHeader));
return frame->message_size;
#endif
}
return 0;
}
/******************************************************************/
uint16_t RF24Network::read(RF24NetworkHeader& header,void* message, uint16_t maxlen)
{
uint16_t bufsize = 0;
#if defined (RF24_LINUX)
if ( available() ) {
RF24NetworkFrame frame = frame_queue.front();
// How much buffer size should we actually copy?
bufsize = rf24_min(frame.message_size,maxlen);
memcpy(&header,&(frame.header),sizeof(RF24NetworkHeader));
memcpy(message,frame.message_buffer,bufsize);
IF_SERIAL_DEBUG(printf("%u: FRG message size %i\n",millis(),frame.message_size););
IF_SERIAL_DEBUG(printf("%u: FRG message ",millis()); const char* charPtr = reinterpret_cast<const char*>(message); for (uint16_t i = 0; i < bufsize; i++) { printf("%02X ", charPtr[i]); }; printf("\n\r"));
IF_SERIAL_DEBUG(printf_P(PSTR("%u: NET read %s\n\r"),millis(),header.toString()));
frame_queue.pop();
}
#else
if ( available() )
{
memcpy(&header,frame_queue,8);
RF24NetworkFrame *f = (RF24NetworkFrame*)frame_queue;
bufsize = f->message_size;
if (maxlen > 0)
{
maxlen = rf24_min(maxlen,bufsize);
memcpy(message,frame_queue+10,maxlen);
IF_SERIAL_DEBUG(printf("%lu: NET message size %d\n",millis(),bufsize););
IF_SERIAL_DEBUG( uint16_t len = maxlen; printf_P(PSTR("%lu: NET r message "),millis());const uint8_t* charPtr = reinterpret_cast<const uint8_t*>(message);while(len--){ printf("%02x ",charPtr[len]);} printf_P(PSTR("\n\r") ) );
}
memmove(frame_queue,frame_queue+bufsize+10,sizeof(frame_queue)- bufsize);
next_frame-=bufsize+10;
//IF_SERIAL_DEBUG(printf_P(PSTR("%lu: NET Received %s\n\r"),millis(),header.toString()));
}
#endif
return bufsize;
}
#if defined RF24NetworkMulticast
/******************************************************************/
bool RF24Network::multicast(RF24NetworkHeader& header,const void* message, uint16_t len, uint8_t level){
// Fill out the header
header.to_node = 0100;
header.from_node = node_address;
return write(header, message, len, levelToAddress(level));
}
#endif
/******************************************************************/
bool RF24Network::write(RF24NetworkHeader& header,const void* message, uint16_t len){
return write(header,message,len,070);
}
/******************************************************************/
bool RF24Network::write(RF24NetworkHeader& header,const void* message, uint16_t len, uint16_t writeDirect){
//Allows time for requests (RF24Mesh) to get through between failed writes on busy nodes
while(millis()-txTime < 25){ if(update() > 127){break;} }
delayMicroseconds(200);
#if defined (DISABLE_FRAGMENTATION)
frame_size = rf24_min(len+sizeof(RF24NetworkHeader),MAX_FRAME_SIZE);
return _write(header,message,rf24_min(len,max_frame_payload_size),writeDirect);
#else
if(len <= max_frame_payload_size){
//Normal Write (Un-Fragmented)
frame_size = len + sizeof(RF24NetworkHeader);
if(_write(header,message,len,writeDirect)){
return 1;
}
txTime = millis();
return 0;
}
//Check payload size
if (len > MAX_PAYLOAD_SIZE) {
IF_SERIAL_DEBUG(printf("%u: NET write message failed. Given 'len' %d is bigger than the MAX Payload size %i\n\r",millis(),len,MAX_PAYLOAD_SIZE););
return false;
}
//Divide the message payload into chunks of max_frame_payload_size
uint8_t fragment_id = (len % max_frame_payload_size != 0) + ((len ) / max_frame_payload_size); //the number of fragments to send = ceil(len/max_frame_payload_size)
uint8_t msgCount = 0;
IF_SERIAL_DEBUG_FRAGMENTATION(printf("%lu: FRG Total message fragments %d\n\r",millis(),fragment_id););
if(header.to_node != 0100){
networkFlags |= FLAG_FAST_FRAG;
#if !defined (DUAL_HEAD_RADIO)
radio.stopListening();
#endif
}
uint8_t retriesPerFrag = 0;
uint8_t type = header.type;
bool ok = 0;
while (fragment_id > 0) {
//Copy and fill out the header
//RF24NetworkHeader fragmentHeader = header;
header.reserved = fragment_id;
if (fragment_id == 1) {
header.type = NETWORK_LAST_FRAGMENT; //Set the last fragment flag to indicate the last fragment
header.reserved = type; //The reserved field is used to transmit the header type
} else {
if (msgCount == 0) {
header.type = NETWORK_FIRST_FRAGMENT;
}else{
header.type = NETWORK_MORE_FRAGMENTS; //Set the more fragments flag to indicate a fragmented frame
}
}
uint16_t offset = msgCount*max_frame_payload_size;
uint16_t fragmentLen = rf24_min((uint16_t)(len-offset),max_frame_payload_size);
//Try to send the payload chunk with the copied header
frame_size = sizeof(RF24NetworkHeader)+fragmentLen;
ok = _write(header,((char *)message)+offset,fragmentLen,writeDirect);
if (!ok) {
delay(2);
++retriesPerFrag;
}else{
retriesPerFrag = 0;
fragment_id--;
msgCount++;
}
//if(writeDirect != 070){ delay(2); } //Delay 2ms between sending multicast payloads
if (!ok && retriesPerFrag >= 3) {
IF_SERIAL_DEBUG_FRAGMENTATION(printf("%lu: FRG TX with fragmentID '%d' failed after %d fragments. Abort.\n\r",millis(),fragment_id,msgCount););
break;
}
//Message was successful sent
#if defined SERIAL_DEBUG_FRAGMENTATION_L2
printf("%lu: FRG message transmission with fragmentID '%d' sucessfull.\n\r",millis(),fragment_id);
#endif
}
header.type = type;
#if !defined (DUAL_HEAD_RADIO)
if(networkFlags & FLAG_FAST_FRAG){
ok = radio.txStandBy(txTimeout);
radio.startListening();
radio.setAutoAck(0,0);
}
networkFlags &= ~FLAG_FAST_FRAG;
if(!ok){
return false;
}
#endif
//int frag_delay = uint8_t(len/48);
//delay( rf24_min(len/48,20));
//Return true if all the chunks where sent successfully
IF_SERIAL_DEBUG_FRAGMENTATION(printf("%u: FRG total message fragments sent %i. \n",millis(),msgCount); );
if(fragment_id > 0){
txTime = millis();
return false;
}
return true;
#endif //Fragmentation enabled
}
/******************************************************************/
bool RF24Network::_write(RF24NetworkHeader& header,const void* message, uint16_t len, uint16_t writeDirect)
{
// Fill out the header
header.from_node = node_address;
// Build the full frame to send
memcpy(frame_buffer,&header,sizeof(RF24NetworkHeader));
#if defined (RF24_LINUX)
IF_SERIAL_DEBUG(printf_P(PSTR("%u: NET Sending %s\n\r"),millis(),header.toString()));
#else
IF_SERIAL_DEBUG(printf_P(PSTR("%lu: NET Sending %s\n\r"),millis(),header.toString()));
#endif
if (len){
#if defined (RF24_LINUX)
memcpy(frame_buffer + sizeof(RF24NetworkHeader),message,rf24_min(frame_size-sizeof(RF24NetworkHeader),len));
IF_SERIAL_DEBUG(printf("%u: FRG frame size %i\n",millis(),frame_size););
IF_SERIAL_DEBUG(printf("%u: FRG frame ",millis()); const char* charPtr = reinterpret_cast<const char*>(frame_buffer); for (uint16_t i = 0; i < frame_size; i++) { printf("%02X ", charPtr[i]); }; printf("\n\r"));
#else
memcpy(frame_buffer + sizeof(RF24NetworkHeader),message,len);
IF_SERIAL_DEBUG(uint16_t tmpLen = len;printf_P(PSTR("%lu: NET message "),millis());const uint8_t* charPtr = reinterpret_cast<const uint8_t*>(message);while(tmpLen--){ printf("%02x ",charPtr[tmpLen]);} printf_P(PSTR("\n\r") ) );
#endif
}
// If the user is trying to send it to himself
/*if ( header.to_node == node_address ){
#if defined (RF24_LINUX)
RF24NetworkFrame frame = RF24NetworkFrame(header,message,rf24_min(MAX_FRAME_SIZE-sizeof(RF24NetworkHeader),len));
#else
RF24NetworkFrame frame(header,len);
#endif
// Just queue it in the received queue
return enqueue(frame);
}*/
// Otherwise send it out over the air
if(writeDirect != 070){
uint8_t sendType = USER_TX_TO_LOGICAL_ADDRESS; // Payload is multicast to the first node, and routed normally to the next
if(header.to_node == 0100){
sendType = USER_TX_MULTICAST;
}
if(header.to_node == writeDirect){
sendType = USER_TX_TO_PHYSICAL_ADDRESS; // Payload is multicast to the first node, which is the recipient
}
return write(writeDirect,sendType);
}
return write(header.to_node,TX_NORMAL);
}
/******************************************************************/
bool RF24Network::write(uint16_t to_node, uint8_t directTo) // Direct To: 0 = First Payload, standard routing, 1=routed payload, 2=directRoute to host, 3=directRoute to Route
{
bool ok = false;
bool isAckType = false;
if(frame_buffer[6] > 64 && frame_buffer[6] < 192 ){ isAckType=true; }
/*if( ( (frame_buffer[7] % 2) && frame_buffer[6] == NETWORK_MORE_FRAGMENTS) ){
isAckType = 0;
}*/
// Throw it away if it's not a valid address
if ( !is_valid_address(to_node) )
return false;
//Load info into our conversion structure, and get the converted address info
logicalToPhysicalStruct conversion = { to_node,directTo,0};
logicalToPhysicalAddress(&conversion);
#if defined (RF24_LINUX)
IF_SERIAL_DEBUG(printf_P(PSTR("%u: MAC Sending to 0%o via 0%o on pipe %x\n\r"),millis(),to_node,conversion.send_node,conversion.send_pipe));
#else
IF_SERIAL_DEBUG(printf_P(PSTR("%lu: MAC Sending to 0%o via 0%o on pipe %x\n\r"),millis(),to_node,conversion.send_node,conversion.send_pipe));
#endif
/**Write it*/
ok=write_to_pipe(conversion.send_node, conversion.send_pipe, conversion.multicast);
if(!ok){
#if defined (RF24_LINUX)
IF_SERIAL_DEBUG_ROUTING( printf_P(PSTR("%u: MAC Send fail to 0%o via 0%o on pipe %x\n\r"),millis(),to_node,conversion.send_node,conversion.send_pipe););
}
#else
IF_SERIAL_DEBUG_ROUTING( printf_P(PSTR("%lu: MAC Send fail to 0%o via 0%o on pipe %x\n\r"),millis(),to_node,conversion.send_node,conversion.send_pipe););
}
#endif
if( directTo == TX_ROUTED && ok && conversion.send_node == to_node && isAckType){
RF24NetworkHeader* header = (RF24NetworkHeader*)&frame_buffer;
header->type = NETWORK_ACK; // Set the payload type to NETWORK_ACK
header->to_node = header->from_node; // Change the 'to' address to the 'from' address
conversion.send_node = header->from_node;
conversion.send_pipe = TX_ROUTED;
conversion.multicast = 0;
logicalToPhysicalAddress(&conversion);
//Write the data using the resulting physical address
frame_size = sizeof(RF24NetworkHeader);
write_to_pipe(conversion.send_node, conversion.send_pipe, conversion.multicast);
//dynLen=0;
#if defined (RF24_LINUX)
IF_SERIAL_DEBUG_ROUTING( printf_P(PSTR("%u MAC: Route OK to 0%o ACK sent to 0%o\n"),millis(),to_node,header->from_node); );
#else
IF_SERIAL_DEBUG_ROUTING( printf_P(PSTR("%lu MAC: Route OK to 0%o ACK sent to 0%o\n"),millis(),to_node,header->from_node); );
#endif
}
if( ok && conversion.send_node != to_node && (directTo==0 || directTo==3) && isAckType){
#if !defined (DUAL_HEAD_RADIO)
// Now, continue listening
if(networkFlags & FLAG_FAST_FRAG){
radio.txStandBy(txTimeout);
networkFlags &= ~FLAG_FAST_FRAG;
radio.setAutoAck(0,0);
}
radio.startListening();
#endif
uint32_t reply_time = millis();
while( update() != NETWORK_ACK){
#if defined (RF24_LINUX)
delayMicroseconds(900);
#endif
if(millis() - reply_time > routeTimeout){
#if defined (RF24_LINUX)
IF_SERIAL_DEBUG_ROUTING( printf_P(PSTR("%u: MAC Network ACK fail from 0%o via 0%o on pipe %x\n\r"),millis(),to_node,conversion.send_node,conversion.send_pipe); );
#else
IF_SERIAL_DEBUG_ROUTING( printf_P(PSTR("%lu: MAC Network ACK fail from 0%o via 0%o on pipe %x\n\r"),millis(),to_node,conversion.send_node,conversion.send_pipe); );
#endif
ok=false;
break;
}
}
}
if( !(networkFlags & FLAG_FAST_FRAG) ){
#if !defined (DUAL_HEAD_RADIO)
// Now, continue listening
radio.startListening();
#endif
}
#if defined ENABLE_NETWORK_STATS
if(ok == true){
++nOK;
}else{ ++nFails;
}
#endif
return ok;
}
/******************************************************************/
// Provided the to_node and directTo option, it will return the resulting node and pipe
bool RF24Network::logicalToPhysicalAddress(logicalToPhysicalStruct *conversionInfo){
//Create pointers so this makes sense.. kind of
//We take in the to_node(logical) now, at the end of the function, output the send_node(physical) address, etc.
//back to the original memory address that held the logical information.
uint16_t *to_node = &conversionInfo->send_node;
uint8_t *directTo = &conversionInfo->send_pipe;
bool *multicast = &conversionInfo->multicast;
// Where do we send this? By default, to our parent
uint16_t pre_conversion_send_node = parent_node;
// On which pipe
uint8_t pre_conversion_send_pipe = parent_pipe %5;
if(*directTo > TX_ROUTED ){
pre_conversion_send_node = *to_node;
*multicast = 1;
//if(*directTo == USER_TX_MULTICAST || *directTo == USER_TX_TO_PHYSICAL_ADDRESS){
pre_conversion_send_pipe=0;
//}
}
// If the node is a direct child,
else
if ( is_direct_child(*to_node) )
{
// Send directly
pre_conversion_send_node = *to_node;
// To its listening pipe
pre_conversion_send_pipe = 5;
}
// If the node is a child of a child
// talk on our child's listening pipe,
// and let the direct child relay it.
else if ( is_descendant(*to_node) )
{
pre_conversion_send_node = direct_child_route_to(*to_node);
pre_conversion_send_pipe = 5;
}
*to_node = pre_conversion_send_node;
*directTo = pre_conversion_send_pipe;
return 1;
}
/********************************************************/
bool RF24Network::write_to_pipe( uint16_t node, uint8_t pipe, bool multicast )
{
bool ok = false;
uint64_t out_pipe = pipe_address( node, pipe );
#if !defined (DUAL_HEAD_RADIO)
// Open the correct pipe for writing.
// First, stop listening so we can talk
if(!(networkFlags & FLAG_FAST_FRAG)){
radio.stopListening();
}
if(multicast){ radio.setAutoAck(0,0);}else{radio.setAutoAck(0,1);}
radio.openWritingPipe(out_pipe);
ok = radio.writeFast(frame_buffer, frame_size,multicast);
if(!(networkFlags & FLAG_FAST_FRAG)){
ok = radio.txStandBy(txTimeout);
radio.setAutoAck(0,0);
}
#else
radio1.openWritingPipe(out_pipe);
radio1.writeFast(frame_buffer, frame_size);
ok = radio1.txStandBy(txTimeout,multicast);
#endif
#if defined (__arm__) || defined (RF24_LINUX)
IF_SERIAL_DEBUG(printf_P(PSTR("%u: MAC Sent on %x %s\n\r"),millis(),(uint32_t)out_pipe,ok?PSTR("ok"):PSTR("failed")));
#else
IF_SERIAL_DEBUG(printf_P(PSTR("%lu: MAC Sent on %lx %S\n\r"),millis(),(uint32_t)out_pipe,ok?PSTR("ok"):PSTR("failed")));
#endif
return ok;
}
/******************************************************************/
const char* RF24NetworkHeader::toString(void) const
{
static char buffer[45];
//snprintf_P(buffer,sizeof(buffer),PSTR("id %04x from 0%o to 0%o type %c"),id,from_node,to_node,type);
sprintf_P(buffer,PSTR("id %u from 0%o to 0%o type %d"),id,from_node,to_node,type);
return buffer;
}
/******************************************************************/
bool RF24Network::is_direct_child( uint16_t node )
{
bool result = false;
// A direct child of ours has the same low numbers as us, and only
// one higher number.
//
// e.g. node 0234 is a direct child of 034, and node 01234 is a
// descendant but not a direct child
// First, is it even a descendant?
if ( is_descendant(node) )
{
// Does it only have ONE more level than us?
uint16_t child_node_mask = ( ~ node_mask ) << 3;
result = ( node & child_node_mask ) == 0 ;
}
return result;
}
/******************************************************************/
bool RF24Network::is_descendant( uint16_t node )
{
return ( node & node_mask ) == node_address;
}
/******************************************************************/
void RF24Network::setup_address(void)
{
// First, establish the node_mask
uint16_t node_mask_check = 0xFFFF;
#if defined (RF24NetworkMulticast)
uint8_t count = 0;
#endif
while ( node_address & node_mask_check ){
node_mask_check <<= 3;
#if defined (RF24NetworkMulticast)
count++;
}
multicast_level = count;
#else
}
#endif
node_mask = ~ node_mask_check;
// parent mask is the next level down
uint16_t parent_mask = node_mask >> 3;
// parent node is the part IN the mask
parent_node = node_address & parent_mask;
// parent pipe is the part OUT of the mask
uint16_t i = node_address;
uint16_t m = parent_mask;
while (m)
{
i >>= 3;
m >>= 3;
}
parent_pipe = i;
IF_SERIAL_DEBUG( printf_P(PSTR("setup_address node=0%o mask=0%o parent=0%o pipe=0%o\n\r"),node_address,node_mask,parent_node,parent_pipe););
}
/******************************************************************/
uint16_t RF24Network::addressOfPipe( uint16_t node, uint8_t pipeNo )
{
//Say this node is 013 (1011), mask is 077 or (00111111)
//Say we want to use pipe 3 (11)
//6 bits in node mask, so shift pipeNo 6 times left and | into address
uint16_t m = node_mask >> 3;
uint8_t i=0;
while (m){ //While there are bits left in the node mask
m>>=1; //Shift to the right
i++; //Count the # of increments
}
return node | (pipeNo << i);
}
/******************************************************************/
uint16_t RF24Network::direct_child_route_to( uint16_t node )
{
// Presumes that this is in fact a child!!
uint16_t child_mask = ( node_mask << 3 ) | 0B111;
return node & child_mask;
}
/******************************************************************/
/*
uint8_t RF24Network::pipe_to_descendant( uint16_t node )
{
uint16_t i = node;
uint16_t m = node_mask;
while (m)
{
i >>= 3;
m >>= 3;
}
return i & 0B111;
}*/
/******************************************************************/
bool RF24Network::is_valid_address( uint16_t node )
{
bool result = true;
while(node)
{
uint8_t digit = node & 0B111;
#if !defined (RF24NetworkMulticast)
if (digit < 1 || digit > 5)
#else
if (digit < 0 || digit > 5) //Allow our out of range multicast address
#endif
{
result = false;
IF_SERIAL_DEBUG_MINIMAL(printf_P(PSTR("*** WARNING *** Invalid address 0%o\n\r"),node););
break;
}
node >>= 3;
}
return result;
}
/******************************************************************/
#if defined (RF24NetworkMulticast)
void RF24Network::multicastLevel(uint8_t level){
multicast_level = level;
//radio.stopListening();
radio.openReadingPipe(0,pipe_address(levelToAddress(level),0));
//radio.startListening();
}
uint16_t levelToAddress(uint8_t level){
uint16_t levelAddr = 1;
if(level){
levelAddr = levelAddr << ((level-1) * 3);
}else{
return 0;
}
return levelAddr;
}
#endif
/******************************************************************/
uint64_t pipe_address( uint16_t node, uint8_t pipe )
{
static uint8_t address_translation[] = { 0xc3,0x3c,0x33,0xce,0x3e,0xe3,0xec };
uint64_t result = 0xCCCCCCCCCCLL;
uint8_t* out = reinterpret_cast<uint8_t*>(&result);
// Translate the address to use our optimally chosen radio address bytes
uint8_t count = 1; uint16_t dec = node;
while(dec){
#if defined (RF24NetworkMulticast)
if(pipe != 0 || !node)
#endif
out[count]=address_translation[(dec % 8)]; // Convert our decimal values to octal, translate them to address bytes, and set our address
dec /= 8;
count++;
}
#if defined (RF24NetworkMulticast)
if(pipe != 0 || !node)
#endif
out[0] = address_translation[pipe];
#if defined (RF24NetworkMulticast)
else
out[1] = address_translation[count-1];
#endif
#if defined (RF24_LINUX)
IF_SERIAL_DEBUG(uint32_t* top = reinterpret_cast<uint32_t*>(out+1);printf_P(PSTR("%u: NET Pipe %i on node 0%o has address %x%x\n\r"),millis(),pipe,node,*top,*out));
#else
IF_SERIAL_DEBUG(uint32_t* top = reinterpret_cast<uint32_t*>(out+1);printf_P(PSTR("%lu: NET Pipe %i on node 0%o has address %lx%x\n\r"),millis(),pipe,node,*top,*out));
#endif
return result;
}
/************************ Sleep Mode ******************************************/
#if defined ENABLE_SLEEP_MODE
#if !defined(__arm__) && !defined(__ARDUINO_X86__)
void wakeUp(){
wasInterrupted=true;
sleep_cycles_remaining = 0;
}
ISR(WDT_vect){
--sleep_cycles_remaining;
}
bool RF24Network::sleepNode( unsigned int cycles, int interruptPin ){
sleep_cycles_remaining = cycles;
set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
sleep_enable();
if(interruptPin != 255){
wasInterrupted = false; //Reset Flag
attachInterrupt(interruptPin,wakeUp, LOW);
}
#if defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
WDTCR |= _BV(WDIE);
#else
WDTCSR |= _BV(WDIE);
#endif
while(sleep_cycles_remaining){
sleep_mode(); // System sleeps here
} // The WDT_vect interrupt wakes the MCU from here
sleep_disable(); // System continues execution here when watchdog timed out
detachInterrupt(interruptPin);
#if defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
WDTCR &= ~_BV(WDIE);
#else
WDTCSR &= ~_BV(WDIE);
#endif
return !wasInterrupted;
}
void RF24Network::setup_watchdog(uint8_t prescalar){
uint8_t wdtcsr = prescalar & 7;
if ( prescalar & 8 )
wdtcsr |= _BV(WDP3);
MCUSR &= ~_BV(WDRF); // Clear the WD System Reset Flag
#if defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
WDTCR = _BV(WDCE) | _BV(WDE); // Write the WD Change enable bit to enable changing the prescaler and enable system reset
WDTCR = _BV(WDCE) | wdtcsr | _BV(WDIE); // Write the prescalar bits (how long to sleep, enable the interrupt to wake the MCU
#else
WDTCSR = _BV(WDCE) | _BV(WDE); // Write the WD Change enable bit to enable changing the prescaler and enable system reset
WDTCSR = _BV(WDCE) | wdtcsr | _BV(WDIE); // Write the prescalar bits (how long to sleep, enable the interrupt to wake the MCU
#endif
}
#endif // not ATTiny
#endif // Enable sleep mode
| 43,845 | 16,635 |
// Generated by Haxe 4.1.5
#include <hxcpp.h>
#ifndef INCLUDED_Std
#include <Std.h>
#endif
#ifndef INCLUDED_haxe_Exception
#include <haxe/Exception.h>
#endif
#ifndef INCLUDED_haxe_IMap
#include <haxe/IMap.h>
#endif
#ifndef INCLUDED_haxe_ds_StringMap
#include <haxe/ds/StringMap.h>
#endif
#ifndef INCLUDED_haxe_io_Bytes
#include <haxe/io/Bytes.h>
#endif
#ifndef INCLUDED_haxe_io_Encoding
#include <haxe/io/Encoding.h>
#endif
#ifndef INCLUDED_polymod_backends_IBackend
#include <polymod/backends/IBackend.h>
#endif
#ifndef INCLUDED_polymod_backends_PolymodAssetLibrary
#include <polymod/backends/PolymodAssetLibrary.h>
#endif
#ifndef INCLUDED_polymod_format_ParseRules
#include <polymod/format/ParseRules.h>
#endif
#ifndef INCLUDED_polymod_fs_SysFileSystem
#include <polymod/fs/SysFileSystem.h>
#endif
#ifndef INCLUDED_polymod_util_Util
#include <polymod/util/Util.h>
#endif
#ifndef INCLUDED_sys_FileSystem
#include <sys/FileSystem.h>
#endif
#ifndef INCLUDED_sys_io_File
#include <sys/io/File.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_41154335dca776f0_63_new,"polymod.backends.PolymodAssetLibrary","new",0xd3ebdd3c,"polymod.backends.PolymodAssetLibrary.new","polymod/backends/PolymodAssetLibrary.hx",63,0xd1edfd94)
HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_88_destroy,"polymod.backends.PolymodAssetLibrary","destroy",0x1f3bd7d6,"polymod.backends.PolymodAssetLibrary.destroy","polymod/backends/PolymodAssetLibrary.hx",88,0xd1edfd94)
HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_95_mergeAndAppendText,"polymod.backends.PolymodAssetLibrary","mergeAndAppendText",0xf742862a,"polymod.backends.PolymodAssetLibrary.mergeAndAppendText","polymod/backends/PolymodAssetLibrary.hx",95,0xd1edfd94)
HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_101_getExtensionType,"polymod.backends.PolymodAssetLibrary","getExtensionType",0x9080a107,"polymod.backends.PolymodAssetLibrary.getExtensionType","polymod/backends/PolymodAssetLibrary.hx",101,0xd1edfd94)
HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_114_getTextDirectly,"polymod.backends.PolymodAssetLibrary","getTextDirectly",0x8a3e4055,"polymod.backends.PolymodAssetLibrary.getTextDirectly","polymod/backends/PolymodAssetLibrary.hx",114,0xd1edfd94)
HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_136_exists,"polymod.backends.PolymodAssetLibrary","exists",0xbb428280,"polymod.backends.PolymodAssetLibrary.exists","polymod/backends/PolymodAssetLibrary.hx",136,0xd1edfd94)
HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_137_getText,"polymod.backends.PolymodAssetLibrary","getText",0x1a32273f,"polymod.backends.PolymodAssetLibrary.getText","polymod/backends/PolymodAssetLibrary.hx",137,0xd1edfd94)
HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_138_getBytes,"polymod.backends.PolymodAssetLibrary","getBytes",0x81aeed99,"polymod.backends.PolymodAssetLibrary.getBytes","polymod/backends/PolymodAssetLibrary.hx",138,0xd1edfd94)
HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_139_getPath,"polymod.backends.PolymodAssetLibrary","getPath",0x178a4037,"polymod.backends.PolymodAssetLibrary.getPath","polymod/backends/PolymodAssetLibrary.hx",139,0xd1edfd94)
HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_141_list,"polymod.backends.PolymodAssetLibrary","list",0x99265002,"polymod.backends.PolymodAssetLibrary.list","polymod/backends/PolymodAssetLibrary.hx",141,0xd1edfd94)
HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_144_listModFiles,"polymod.backends.PolymodAssetLibrary","listModFiles",0x114a5677,"polymod.backends.PolymodAssetLibrary.listModFiles","polymod/backends/PolymodAssetLibrary.hx",144,0xd1edfd94)
HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_166_check,"polymod.backends.PolymodAssetLibrary","check",0x391094a4,"polymod.backends.PolymodAssetLibrary.check","polymod/backends/PolymodAssetLibrary.hx",166,0xd1edfd94)
HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_177_getType,"polymod.backends.PolymodAssetLibrary","getType",0x1a414d4c,"polymod.backends.PolymodAssetLibrary.getType","polymod/backends/PolymodAssetLibrary.hx",177,0xd1edfd94)
HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_187_checkDirectly,"polymod.backends.PolymodAssetLibrary","checkDirectly",0xba101aba,"polymod.backends.PolymodAssetLibrary.checkDirectly","polymod/backends/PolymodAssetLibrary.hx",187,0xd1edfd94)
HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_211_file,"polymod.backends.PolymodAssetLibrary","file",0x952f0220,"polymod.backends.PolymodAssetLibrary.file","polymod/backends/PolymodAssetLibrary.hx",211,0xd1edfd94)
HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_231__checkExists,"polymod.backends.PolymodAssetLibrary","_checkExists",0xbf011669,"polymod.backends.PolymodAssetLibrary._checkExists","polymod/backends/PolymodAssetLibrary.hx",231,0xd1edfd94)
HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_246_init,"polymod.backends.PolymodAssetLibrary","init",0x972e6eb4,"polymod.backends.PolymodAssetLibrary.init","polymod/backends/PolymodAssetLibrary.hx",246,0xd1edfd94)
HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_260_initExtensions,"polymod.backends.PolymodAssetLibrary","initExtensions",0x4b48d7e8,"polymod.backends.PolymodAssetLibrary.initExtensions","polymod/backends/PolymodAssetLibrary.hx",260,0xd1edfd94)
HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_287__extensionSet,"polymod.backends.PolymodAssetLibrary","_extensionSet",0x73b0841e,"polymod.backends.PolymodAssetLibrary._extensionSet","polymod/backends/PolymodAssetLibrary.hx",287,0xd1edfd94)
HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_294_initMod,"polymod.backends.PolymodAssetLibrary","initMod",0xc63f886e,"polymod.backends.PolymodAssetLibrary.initMod","polymod/backends/PolymodAssetLibrary.hx",294,0xd1edfd94)
namespace polymod{
namespace backends{
void PolymodAssetLibrary_obj::__construct( ::Dynamic params){
HX_STACKFRAME(&_hx_pos_41154335dca776f0_63_new)
HXLINE( 71) this->parseRules = null();
HXLINE( 70) this->ignoredFiles = null();
HXLINE( 69) this->dirs = null();
HXLINE( 76) this->backend = ::Dynamic(params->__Field(HX_("backend",14,bc,87,fb),::hx::paccDynamic));
HXLINE( 77) this->backend->__SetField(HX_("polymodLibrary",a5,49,05,cb),::hx::ObjectPtr<OBJ_>(this),::hx::paccDynamic);
HXLINE( 78) this->dirs = ( (::Array< ::String >)(params->__Field(HX_("dirs",86,66,69,42),::hx::paccDynamic)) );
HXLINE( 79) this->parseRules = ( ( ::polymod::format::ParseRules)(params->__Field(HX_("parseRules",c4,aa,37,1b),::hx::paccDynamic)) );
HXLINE( 80) ::Array< ::String > _hx_tmp;
HXDLIN( 80) if (::hx::IsNotNull( params->__Field(HX_("ignoredFiles",05,36,92,57),::hx::paccDynamic) )) {
HXLINE( 80) _hx_tmp = ( (::Array< ::String >)(params->__Field(HX_("ignoredFiles",05,36,92,57),::hx::paccDynamic)) )->copy();
}
else {
HXLINE( 80) _hx_tmp = ::Array_obj< ::String >::__new(0);
}
HXDLIN( 80) this->ignoredFiles = _hx_tmp;
HXLINE( 81) this->extensions = ( ( ::haxe::ds::StringMap)(params->__Field(HX_("extensionMap",5d,28,7a,23),::hx::paccDynamic)) );
HXLINE( 82) ::polymod::backends::IBackend_obj::clearCache(this->backend);
HXLINE( 83) this->init();
}
Dynamic PolymodAssetLibrary_obj::__CreateEmpty() { return new PolymodAssetLibrary_obj; }
void *PolymodAssetLibrary_obj::_hx_vtable = 0;
Dynamic PolymodAssetLibrary_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< PolymodAssetLibrary_obj > _hx_result = new PolymodAssetLibrary_obj();
_hx_result->__construct(inArgs[0]);
return _hx_result;
}
bool PolymodAssetLibrary_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x6eaea9ac;
}
void PolymodAssetLibrary_obj::destroy(){
HX_STACKFRAME(&_hx_pos_41154335dca776f0_88_destroy)
HXDLIN( 88) if (::hx::IsNotNull( this->backend )) {
HXLINE( 90) ::polymod::backends::IBackend_obj::destroy(this->backend);
}
}
HX_DEFINE_DYNAMIC_FUNC0(PolymodAssetLibrary_obj,destroy,(void))
::String PolymodAssetLibrary_obj::mergeAndAppendText(::String id,::String modText){
HX_STACKFRAME(&_hx_pos_41154335dca776f0_95_mergeAndAppendText)
HXLINE( 96) modText = ::polymod::util::Util_obj::mergeAndAppendText(modText,id,this->dirs,this->getTextDirectly_dyn(),this->parseRules);
HXLINE( 97) return modText;
}
HX_DEFINE_DYNAMIC_FUNC2(PolymodAssetLibrary_obj,mergeAndAppendText,return )
::String PolymodAssetLibrary_obj::getExtensionType(::String ext){
HX_STACKFRAME(&_hx_pos_41154335dca776f0_101_getExtensionType)
HXLINE( 102) ext = ext.toLowerCase();
HXLINE( 103) if ((this->extensions->exists(ext) == false)) {
HXLINE( 103) return HX_("BYTES",4b,40,86,3b);
}
HXLINE( 104) return this->extensions->get_string(ext);
}
HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,getExtensionType,return )
::String PolymodAssetLibrary_obj::getTextDirectly(::String id,::String __o_directory){
::String directory = __o_directory;
if (::hx::IsNull(__o_directory)) directory = HX_("",00,00,00,00);
HX_STACKFRAME(&_hx_pos_41154335dca776f0_114_getTextDirectly)
HXLINE( 115) ::haxe::io::Bytes bytes = null();
HXLINE( 116) if (this->checkDirectly(id,directory)) {
HXLINE( 118) ::String path = this->file(id,directory);
HXDLIN( 118) if (!(::sys::FileSystem_obj::exists(path))) {
HXLINE( 118) bytes = null();
}
else {
HXLINE( 118) bytes = ::sys::io::File_obj::getBytes(path);
}
}
else {
HXLINE( 122) bytes = ::polymod::backends::IBackend_obj::getBytes(this->backend,id);
}
HXLINE( 125) if (::hx::IsNull( bytes )) {
HXLINE( 127) return null();
}
else {
HXLINE( 131) return bytes->getString(0,bytes->length,null());
}
HXLINE( 125) return null();
}
HX_DEFINE_DYNAMIC_FUNC2(PolymodAssetLibrary_obj,getTextDirectly,return )
bool PolymodAssetLibrary_obj::exists(::String id){
HX_STACKFRAME(&_hx_pos_41154335dca776f0_136_exists)
HXDLIN( 136) return ::polymod::backends::IBackend_obj::exists(this->backend,id);
}
HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,exists,return )
::String PolymodAssetLibrary_obj::getText(::String id){
HX_STACKFRAME(&_hx_pos_41154335dca776f0_137_getText)
HXDLIN( 137) return ::polymod::backends::IBackend_obj::getText(this->backend,id);
}
HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,getText,return )
::haxe::io::Bytes PolymodAssetLibrary_obj::getBytes(::String id){
HX_STACKFRAME(&_hx_pos_41154335dca776f0_138_getBytes)
HXDLIN( 138) return ::polymod::backends::IBackend_obj::getBytes(this->backend,id);
}
HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,getBytes,return )
::String PolymodAssetLibrary_obj::getPath(::String id){
HX_STACKFRAME(&_hx_pos_41154335dca776f0_139_getPath)
HXDLIN( 139) return ::polymod::backends::IBackend_obj::getPath(this->backend,id);
}
HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,getPath,return )
::Array< ::String > PolymodAssetLibrary_obj::list(::String type){
HX_STACKFRAME(&_hx_pos_41154335dca776f0_141_list)
HXDLIN( 141) return ::polymod::backends::IBackend_obj::list(this->backend,type);
}
HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,list,return )
::Array< ::String > PolymodAssetLibrary_obj::listModFiles(::String type){
HX_STACKFRAME(&_hx_pos_41154335dca776f0_144_listModFiles)
HXLINE( 145) ::Array< ::String > items = ::Array_obj< ::String >::__new(0);
HXLINE( 147) {
HXLINE( 147) ::Dynamic id = this->type->keys();
HXDLIN( 147) while(( (bool)(id->__Field(HX_("hasNext",6d,a5,46,18),::hx::paccDynamic)()) )){
HXLINE( 147) ::String id1 = ( (::String)(id->__Field(HX_("next",f3,84,02,49),::hx::paccDynamic)()) );
HXLINE( 149) bool _hx_tmp;
HXDLIN( 149) if ((id1.indexOf(HX_("_append",79,f3,4a,fe),null()) != 0)) {
HXLINE( 149) _hx_tmp = (id1.indexOf(HX_("_merge",f9,e9,ad,01),null()) == 0);
}
else {
HXLINE( 149) _hx_tmp = true;
}
HXDLIN( 149) if (_hx_tmp) {
HXLINE( 149) continue;
}
HXLINE( 150) bool _hx_tmp1;
HXDLIN( 150) bool _hx_tmp2;
HXDLIN( 150) if (::hx::IsNotNull( type )) {
HXLINE( 150) _hx_tmp2 = (type == HX_("BYTES",4b,40,86,3b));
}
else {
HXLINE( 150) _hx_tmp2 = true;
}
HXDLIN( 150) if (!(_hx_tmp2)) {
HXLINE( 150) _hx_tmp1 = this->check(id1,type);
}
else {
HXLINE( 150) _hx_tmp1 = true;
}
HXDLIN( 150) if (_hx_tmp1) {
HXLINE( 152) items->push(id1);
}
}
}
HXLINE( 156) return items;
}
HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,listModFiles,return )
bool PolymodAssetLibrary_obj::check(::String id,::String type){
HX_STACKFRAME(&_hx_pos_41154335dca776f0_166_check)
HXLINE( 167) bool exists = this->_checkExists(id);
HXLINE( 168) bool _hx_tmp;
HXDLIN( 168) bool _hx_tmp1;
HXDLIN( 168) if (exists) {
HXLINE( 168) _hx_tmp1 = ::hx::IsNotNull( type );
}
else {
HXLINE( 168) _hx_tmp1 = false;
}
HXDLIN( 168) if (_hx_tmp1) {
HXLINE( 168) _hx_tmp = (type != HX_("BYTES",4b,40,86,3b));
}
else {
HXLINE( 168) _hx_tmp = false;
}
HXDLIN( 168) if (_hx_tmp) {
HXLINE( 170) ::String otherType = this->type->get_string(id);
HXLINE( 171) bool exists1;
HXDLIN( 171) bool exists2;
HXDLIN( 171) if ((otherType != type)) {
HXLINE( 171) exists2 = (otherType == HX_("BYTES",4b,40,86,3b));
}
else {
HXLINE( 171) exists2 = true;
}
HXDLIN( 171) if (!(exists2)) {
HXLINE( 171) exists1 = ::hx::IsNull( otherType );
}
else {
HXLINE( 171) exists1 = true;
}
HXDLIN( 171) if (!(exists1)) {
HXLINE( 171) exists = (otherType == HX_("",00,00,00,00));
}
else {
HXLINE( 171) exists = true;
}
}
HXLINE( 173) return exists;
}
HX_DEFINE_DYNAMIC_FUNC2(PolymodAssetLibrary_obj,check,return )
::String PolymodAssetLibrary_obj::getType(::String id){
HX_STACKFRAME(&_hx_pos_41154335dca776f0_177_getType)
HXLINE( 178) bool exists = this->_checkExists(id);
HXLINE( 179) if (exists) {
HXLINE( 181) return this->type->get_string(id);
}
HXLINE( 183) return null();
}
HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,getType,return )
bool PolymodAssetLibrary_obj::checkDirectly(::String id,::String dir){
HX_STACKFRAME(&_hx_pos_41154335dca776f0_187_checkDirectly)
HXLINE( 188) id = ::polymod::backends::IBackend_obj::stripAssetsPrefix(this->backend,id);
HXLINE( 189) bool _hx_tmp;
HXDLIN( 189) if (::hx::IsNotNull( dir )) {
HXLINE( 189) _hx_tmp = (dir == HX_("",00,00,00,00));
}
else {
HXLINE( 189) _hx_tmp = true;
}
HXDLIN( 189) if (_hx_tmp) {
HXLINE( 191) return ::sys::FileSystem_obj::exists(id);
}
else {
HXLINE( 195) ::String thePath = ::polymod::util::Util_obj::uCombine(::Array_obj< ::String >::__new(3)->init(0,dir)->init(1,::polymod::util::Util_obj::sl())->init(2,id));
HXLINE( 196) if (::sys::FileSystem_obj::exists(thePath)) {
HXLINE( 198) return true;
}
}
HXLINE( 201) return false;
}
HX_DEFINE_DYNAMIC_FUNC2(PolymodAssetLibrary_obj,checkDirectly,return )
::String PolymodAssetLibrary_obj::file(::String id,::String __o_theDir){
::String theDir = __o_theDir;
if (::hx::IsNull(__o_theDir)) theDir = HX_("",00,00,00,00);
HX_STACKFRAME(&_hx_pos_41154335dca776f0_211_file)
HXLINE( 212) id = ::polymod::backends::IBackend_obj::stripAssetsPrefix(this->backend,id);
HXLINE( 213) if ((theDir != HX_("",00,00,00,00))) {
HXLINE( 215) return ::polymod::util::Util_obj::pathJoin(theDir,id);
}
HXLINE( 218) ::String theFile = HX_("",00,00,00,00);
HXLINE( 219) {
HXLINE( 219) int _g = 0;
HXDLIN( 219) ::Array< ::String > _g1 = this->dirs;
HXDLIN( 219) while((_g < _g1->length)){
HXLINE( 219) ::String d = _g1->__get(_g);
HXDLIN( 219) _g = (_g + 1);
HXLINE( 221) ::String thePath = ::polymod::util::Util_obj::pathJoin(d,id);
HXLINE( 222) if (::sys::FileSystem_obj::exists(thePath)) {
HXLINE( 224) theFile = thePath;
}
}
}
HXLINE( 227) return theFile;
}
HX_DEFINE_DYNAMIC_FUNC2(PolymodAssetLibrary_obj,file,return )
bool PolymodAssetLibrary_obj::_checkExists(::String id){
HX_STACKFRAME(&_hx_pos_41154335dca776f0_231__checkExists)
HXLINE( 232) bool _hx_tmp;
HXDLIN( 232) if ((this->ignoredFiles->length > 0)) {
HXLINE( 232) _hx_tmp = (this->ignoredFiles->indexOf(id,null()) != -1);
}
else {
HXLINE( 232) _hx_tmp = false;
}
HXDLIN( 232) if (_hx_tmp) {
HXLINE( 232) return false;
}
HXLINE( 233) bool exists = false;
HXLINE( 234) id = ::polymod::backends::IBackend_obj::stripAssetsPrefix(this->backend,id);
HXLINE( 235) {
HXLINE( 235) int _g = 0;
HXDLIN( 235) ::Array< ::String > _g1 = this->dirs;
HXDLIN( 235) while((_g < _g1->length)){
HXLINE( 235) ::String d = _g1->__get(_g);
HXDLIN( 235) _g = (_g + 1);
HXLINE( 237) if (::sys::FileSystem_obj::exists(::polymod::util::Util_obj::pathJoin(d,id))) {
HXLINE( 239) exists = true;
}
}
}
HXLINE( 242) return exists;
}
HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,_checkExists,return )
void PolymodAssetLibrary_obj::init(){
HX_GC_STACKFRAME(&_hx_pos_41154335dca776f0_246_init)
HXLINE( 247) this->type = ::haxe::ds::StringMap_obj::__alloc( HX_CTX );
HXLINE( 248) this->initExtensions();
HXLINE( 249) if (::hx::IsNull( this->parseRules )) {
HXLINE( 249) this->parseRules = ::polymod::format::ParseRules_obj::getDefault();
}
HXLINE( 250) if (::hx::IsNotNull( this->dirs )) {
HXLINE( 252) int _g = 0;
HXDLIN( 252) ::Array< ::String > _g1 = this->dirs;
HXDLIN( 252) while((_g < _g1->length)){
HXLINE( 252) ::String d = _g1->__get(_g);
HXDLIN( 252) _g = (_g + 1);
HXLINE( 254) this->initMod(d);
}
}
}
HX_DEFINE_DYNAMIC_FUNC0(PolymodAssetLibrary_obj,init,(void))
void PolymodAssetLibrary_obj::initExtensions(){
HX_GC_STACKFRAME(&_hx_pos_41154335dca776f0_260_initExtensions)
HXLINE( 261) this->extensions = ::haxe::ds::StringMap_obj::__alloc( HX_CTX );
HXLINE( 262) this->_extensionSet(HX_("mp3",70,17,53,00),HX_("AUDIO_GENERIC",2e,f6,26,23));
HXLINE( 263) this->_extensionSet(HX_("ogg",4f,94,54,00),HX_("AUDIO_GENERIC",2e,f6,26,23));
HXLINE( 264) this->_extensionSet(HX_("wav",2c,a1,5a,00),HX_("AUDIO_GENERIC",2e,f6,26,23));
HXLINE( 265) this->_extensionSet(HX_("jpg",e1,d0,50,00),HX_("IMAGE",3b,57,57,3b));
HXLINE( 266) this->_extensionSet(HX_("png",a9,5c,55,00),HX_("IMAGE",3b,57,57,3b));
HXLINE( 267) this->_extensionSet(HX_("gif",04,84,4e,00),HX_("IMAGE",3b,57,57,3b));
HXLINE( 268) this->_extensionSet(HX_("tga",8e,5f,58,00),HX_("IMAGE",3b,57,57,3b));
HXLINE( 269) this->_extensionSet(HX_("bmp",45,bc,4a,00),HX_("IMAGE",3b,57,57,3b));
HXLINE( 270) this->_extensionSet(HX_("tif",51,61,58,00),HX_("IMAGE",3b,57,57,3b));
HXLINE( 271) this->_extensionSet(HX_("tiff",f5,c5,fc,4c),HX_("IMAGE",3b,57,57,3b));
HXLINE( 272) this->_extensionSet(HX_("txt",70,6e,58,00),HX_("TEXT",ad,94,ba,37));
HXLINE( 273) this->_extensionSet(HX_("xml",d7,6d,5b,00),HX_("TEXT",ad,94,ba,37));
HXLINE( 274) this->_extensionSet(HX_("json",28,42,68,46),HX_("TEXT",ad,94,ba,37));
HXLINE( 275) this->_extensionSet(HX_("csv",c6,83,4b,00),HX_("TEXT",ad,94,ba,37));
HXLINE( 276) this->_extensionSet(HX_("tsv",17,6a,58,00),HX_("TEXT",ad,94,ba,37));
HXLINE( 277) this->_extensionSet(HX_("mpf",a3,17,53,00),HX_("TEXT",ad,94,ba,37));
HXLINE( 278) this->_extensionSet(HX_("tsx",19,6a,58,00),HX_("TEXT",ad,94,ba,37));
HXLINE( 279) this->_extensionSet(HX_("tmx",df,64,58,00),HX_("TEXT",ad,94,ba,37));
HXLINE( 280) this->_extensionSet(HX_("vdf",78,e1,59,00),HX_("TEXT",ad,94,ba,37));
HXLINE( 281) this->_extensionSet(HX_("ttf",e6,6a,58,00),HX_("FONT",cf,25,81,2e));
HXLINE( 282) this->_extensionSet(HX_("otf",a1,9f,54,00),HX_("FONT",cf,25,81,2e));
}
HX_DEFINE_DYNAMIC_FUNC0(PolymodAssetLibrary_obj,initExtensions,(void))
void PolymodAssetLibrary_obj::_extensionSet(::String str,::String type){
HX_STACKFRAME(&_hx_pos_41154335dca776f0_287__extensionSet)
HXDLIN( 287) if ((this->extensions->exists(str) == false)) {
HXLINE( 289) this->extensions->set(str,type);
}
}
HX_DEFINE_DYNAMIC_FUNC2(PolymodAssetLibrary_obj,_extensionSet,(void))
void PolymodAssetLibrary_obj::initMod(::String d){
HX_STACKFRAME(&_hx_pos_41154335dca776f0_294_initMod)
HXLINE( 295) if (::hx::IsNull( d )) {
HXLINE( 295) return;
}
HXLINE( 297) ::Array< ::String > all = null();
HXLINE( 299) bool _hx_tmp;
HXDLIN( 299) if ((d != HX_("",00,00,00,00))) {
HXLINE( 299) _hx_tmp = ::hx::IsNull( d );
}
else {
HXLINE( 299) _hx_tmp = true;
}
HXDLIN( 299) if (_hx_tmp) {
HXLINE( 301) all = ::Array_obj< ::String >::__new(0);
}
HXLINE( 304) try {
HX_STACK_CATCHABLE( ::Dynamic, 0);
HXLINE( 306) if (::sys::FileSystem_obj::exists(d)) {
HXLINE( 308) all = ::polymod::fs::SysFileSystem_obj::readDirectoryRecursive(d);
}
else {
HXLINE( 312) all = ::Array_obj< ::String >::__new(0);
}
} catch( ::Dynamic _hx_e) {
if (_hx_e.IsClass< ::Dynamic >() ){
HX_STACK_BEGIN_CATCH
::Dynamic _g = _hx_e;
HXLINE( 1) {
HXLINE( 1) null();
}
HXDLIN( 1) ::Dynamic msg = ::haxe::Exception_obj::caught(_g)->unwrap();
HXLINE( 317) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown((((HX_("ModAssetLibrary._initMod(",b4,86,f3,80) + d) + HX_(") failed : ",72,52,be,0b)) + ::Std_obj::string(msg))));
}
else {
HX_STACK_DO_THROW(_hx_e);
}
}
HXLINE( 319) {
HXLINE( 319) int _g = 0;
HXDLIN( 319) while((_g < all->length)){
HXLINE( 319) ::String f = all->__get(_g);
HXDLIN( 319) _g = (_g + 1);
HXLINE( 321) int doti = ::polymod::util::Util_obj::uLastIndexOf(f,HX_(".",2e,00,00,00),null());
HXLINE( 322) ::String ext;
HXDLIN( 322) if ((doti != -1)) {
HXLINE( 322) ext = f.substring((doti + 1),null());
}
else {
HXLINE( 322) ext = HX_("",00,00,00,00);
}
HXLINE( 323) ext = ext.toLowerCase();
HXLINE( 324) ::String assetType = this->getExtensionType(ext);
HXLINE( 325) this->type->set(f,assetType);
}
}
}
HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,initMod,(void))
::hx::ObjectPtr< PolymodAssetLibrary_obj > PolymodAssetLibrary_obj::__new( ::Dynamic params) {
::hx::ObjectPtr< PolymodAssetLibrary_obj > __this = new PolymodAssetLibrary_obj();
__this->__construct(params);
return __this;
}
::hx::ObjectPtr< PolymodAssetLibrary_obj > PolymodAssetLibrary_obj::__alloc(::hx::Ctx *_hx_ctx, ::Dynamic params) {
PolymodAssetLibrary_obj *__this = (PolymodAssetLibrary_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(PolymodAssetLibrary_obj), true, "polymod.backends.PolymodAssetLibrary"));
*(void **)__this = PolymodAssetLibrary_obj::_hx_vtable;
__this->__construct(params);
return __this;
}
PolymodAssetLibrary_obj::PolymodAssetLibrary_obj()
{
}
void PolymodAssetLibrary_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(PolymodAssetLibrary);
HX_MARK_MEMBER_NAME(backend,"backend");
HX_MARK_MEMBER_NAME(type,"type");
HX_MARK_MEMBER_NAME(dirs,"dirs");
HX_MARK_MEMBER_NAME(ignoredFiles,"ignoredFiles");
HX_MARK_MEMBER_NAME(parseRules,"parseRules");
HX_MARK_MEMBER_NAME(extensions,"extensions");
HX_MARK_END_CLASS();
}
void PolymodAssetLibrary_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(backend,"backend");
HX_VISIT_MEMBER_NAME(type,"type");
HX_VISIT_MEMBER_NAME(dirs,"dirs");
HX_VISIT_MEMBER_NAME(ignoredFiles,"ignoredFiles");
HX_VISIT_MEMBER_NAME(parseRules,"parseRules");
HX_VISIT_MEMBER_NAME(extensions,"extensions");
}
::hx::Val PolymodAssetLibrary_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"type") ) { return ::hx::Val( type ); }
if (HX_FIELD_EQ(inName,"dirs") ) { return ::hx::Val( dirs ); }
if (HX_FIELD_EQ(inName,"list") ) { return ::hx::Val( list_dyn() ); }
if (HX_FIELD_EQ(inName,"file") ) { return ::hx::Val( file_dyn() ); }
if (HX_FIELD_EQ(inName,"init") ) { return ::hx::Val( init_dyn() ); }
break;
case 5:
if (HX_FIELD_EQ(inName,"check") ) { return ::hx::Val( check_dyn() ); }
break;
case 6:
if (HX_FIELD_EQ(inName,"exists") ) { return ::hx::Val( exists_dyn() ); }
break;
case 7:
if (HX_FIELD_EQ(inName,"backend") ) { return ::hx::Val( backend ); }
if (HX_FIELD_EQ(inName,"destroy") ) { return ::hx::Val( destroy_dyn() ); }
if (HX_FIELD_EQ(inName,"getText") ) { return ::hx::Val( getText_dyn() ); }
if (HX_FIELD_EQ(inName,"getPath") ) { return ::hx::Val( getPath_dyn() ); }
if (HX_FIELD_EQ(inName,"getType") ) { return ::hx::Val( getType_dyn() ); }
if (HX_FIELD_EQ(inName,"initMod") ) { return ::hx::Val( initMod_dyn() ); }
break;
case 8:
if (HX_FIELD_EQ(inName,"getBytes") ) { return ::hx::Val( getBytes_dyn() ); }
break;
case 10:
if (HX_FIELD_EQ(inName,"parseRules") ) { return ::hx::Val( parseRules ); }
if (HX_FIELD_EQ(inName,"extensions") ) { return ::hx::Val( extensions ); }
break;
case 12:
if (HX_FIELD_EQ(inName,"ignoredFiles") ) { return ::hx::Val( ignoredFiles ); }
if (HX_FIELD_EQ(inName,"listModFiles") ) { return ::hx::Val( listModFiles_dyn() ); }
if (HX_FIELD_EQ(inName,"_checkExists") ) { return ::hx::Val( _checkExists_dyn() ); }
break;
case 13:
if (HX_FIELD_EQ(inName,"checkDirectly") ) { return ::hx::Val( checkDirectly_dyn() ); }
if (HX_FIELD_EQ(inName,"_extensionSet") ) { return ::hx::Val( _extensionSet_dyn() ); }
break;
case 14:
if (HX_FIELD_EQ(inName,"initExtensions") ) { return ::hx::Val( initExtensions_dyn() ); }
break;
case 15:
if (HX_FIELD_EQ(inName,"getTextDirectly") ) { return ::hx::Val( getTextDirectly_dyn() ); }
break;
case 16:
if (HX_FIELD_EQ(inName,"getExtensionType") ) { return ::hx::Val( getExtensionType_dyn() ); }
break;
case 18:
if (HX_FIELD_EQ(inName,"mergeAndAppendText") ) { return ::hx::Val( mergeAndAppendText_dyn() ); }
}
return super::__Field(inName,inCallProp);
}
::hx::Val PolymodAssetLibrary_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"type") ) { type=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; }
if (HX_FIELD_EQ(inName,"dirs") ) { dirs=inValue.Cast< ::Array< ::String > >(); return inValue; }
break;
case 7:
if (HX_FIELD_EQ(inName,"backend") ) { backend=inValue.Cast< ::Dynamic >(); return inValue; }
break;
case 10:
if (HX_FIELD_EQ(inName,"parseRules") ) { parseRules=inValue.Cast< ::polymod::format::ParseRules >(); return inValue; }
if (HX_FIELD_EQ(inName,"extensions") ) { extensions=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; }
break;
case 12:
if (HX_FIELD_EQ(inName,"ignoredFiles") ) { ignoredFiles=inValue.Cast< ::Array< ::String > >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void PolymodAssetLibrary_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_("backend",14,bc,87,fb));
outFields->push(HX_("type",ba,f2,08,4d));
outFields->push(HX_("dirs",86,66,69,42));
outFields->push(HX_("ignoredFiles",05,36,92,57));
outFields->push(HX_("parseRules",c4,aa,37,1b));
outFields->push(HX_("extensions",14,7c,70,89));
super::__GetFields(outFields);
};
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo PolymodAssetLibrary_obj_sMemberStorageInfo[] = {
{::hx::fsObject /* ::Dynamic */ ,(int)offsetof(PolymodAssetLibrary_obj,backend),HX_("backend",14,bc,87,fb)},
{::hx::fsObject /* ::haxe::ds::StringMap */ ,(int)offsetof(PolymodAssetLibrary_obj,type),HX_("type",ba,f2,08,4d)},
{::hx::fsObject /* ::Array< ::String > */ ,(int)offsetof(PolymodAssetLibrary_obj,dirs),HX_("dirs",86,66,69,42)},
{::hx::fsObject /* ::Array< ::String > */ ,(int)offsetof(PolymodAssetLibrary_obj,ignoredFiles),HX_("ignoredFiles",05,36,92,57)},
{::hx::fsObject /* ::polymod::format::ParseRules */ ,(int)offsetof(PolymodAssetLibrary_obj,parseRules),HX_("parseRules",c4,aa,37,1b)},
{::hx::fsObject /* ::haxe::ds::StringMap */ ,(int)offsetof(PolymodAssetLibrary_obj,extensions),HX_("extensions",14,7c,70,89)},
{ ::hx::fsUnknown, 0, null()}
};
static ::hx::StaticInfo *PolymodAssetLibrary_obj_sStaticStorageInfo = 0;
#endif
static ::String PolymodAssetLibrary_obj_sMemberFields[] = {
HX_("backend",14,bc,87,fb),
HX_("type",ba,f2,08,4d),
HX_("dirs",86,66,69,42),
HX_("ignoredFiles",05,36,92,57),
HX_("parseRules",c4,aa,37,1b),
HX_("extensions",14,7c,70,89),
HX_("destroy",fa,2c,86,24),
HX_("mergeAndAppendText",86,bb,89,90),
HX_("getExtensionType",63,87,3c,56),
HX_("getTextDirectly",79,59,58,bb),
HX_("exists",dc,1d,e0,bf),
HX_("getText",63,7c,7c,1f),
HX_("getBytes",f5,17,6f,1d),
HX_("getPath",5b,95,d4,1c),
HX_("list",5e,1c,b3,47),
HX_("listModFiles",d3,de,44,5a),
HX_("check",c8,98,b6,45),
HX_("getType",70,a2,8b,1f),
HX_("checkDirectly",de,e2,4c,4c),
HX_("file",7c,ce,bb,43),
HX_("_checkExists",c5,9e,fb,07),
HX_("init",10,3b,bb,45),
HX_("initExtensions",44,2f,3b,ae),
HX_("_extensionSet",42,4c,ed,05),
HX_("initMod",92,dd,89,cb),
::String(null()) };
::hx::Class PolymodAssetLibrary_obj::__mClass;
void PolymodAssetLibrary_obj::__register()
{
PolymodAssetLibrary_obj _hx_dummy;
PolymodAssetLibrary_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("polymod.backends.PolymodAssetLibrary",4a,cf,f5,08);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(PolymodAssetLibrary_obj_sMemberFields);
__mClass->mCanCast = ::hx::TCanCast< PolymodAssetLibrary_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = PolymodAssetLibrary_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = PolymodAssetLibrary_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace polymod
} // end namespace backends
| 31,177 | 15,215 |
//===- ClassDefinitionDumper.cpp --------------------------------*- C++ -*-===//
//
// The LLVM37 Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "ClassDefinitionDumper.h"
#include "EnumDumper.h"
#include "FunctionDumper.h"
#include "LinePrinter.h"
#include "llvm37-pdbdump.h"
#include "TypedefDumper.h"
#include "VariableDumper.h"
#include "llvm37/DebugInfo/PDB/IPDBSession.h"
#include "llvm37/DebugInfo/PDB/PDBExtras.h"
#include "llvm37/DebugInfo/PDB/PDBSymbolData.h"
#include "llvm37/DebugInfo/PDB/PDBSymbolFunc.h"
#include "llvm37/DebugInfo/PDB/PDBSymbolTypeBaseClass.h"
#include "llvm37/DebugInfo/PDB/PDBSymbolTypeEnum.h"
#include "llvm37/DebugInfo/PDB/PDBSymbolTypePointer.h"
#include "llvm37/DebugInfo/PDB/PDBSymbolTypeTypedef.h"
#include "llvm37/DebugInfo/PDB/PDBSymbolTypeUDT.h"
#include "llvm37/DebugInfo/PDB/PDBSymbolTypeVTable.h"
#include "llvm37/Support/Format.h"
using namespace llvm37;
ClassDefinitionDumper::ClassDefinitionDumper(LinePrinter &P)
: PDBSymDumper(true), Printer(P) {}
void ClassDefinitionDumper::start(const PDBSymbolTypeUDT &Class) {
std::string Name = Class.getName();
WithColor(Printer, PDB_ColorItem::Keyword).get() << Class.getUdtKind() << " ";
WithColor(Printer, PDB_ColorItem::Type).get() << Class.getName();
auto Bases = Class.findAllChildren<PDBSymbolTypeBaseClass>();
if (Bases->getChildCount() > 0) {
Printer.Indent();
Printer.NewLine();
Printer << ":";
uint32_t BaseIndex = 0;
while (auto Base = Bases->getNext()) {
Printer << " ";
WithColor(Printer, PDB_ColorItem::Keyword).get() << Base->getAccess();
if (Base->isVirtualBaseClass())
WithColor(Printer, PDB_ColorItem::Keyword).get() << " virtual";
WithColor(Printer, PDB_ColorItem::Type).get() << " " << Base->getName();
if (++BaseIndex < Bases->getChildCount()) {
Printer.NewLine();
Printer << ",";
}
}
Printer.Unindent();
}
Printer << " {";
auto Children = Class.findAllChildren();
if (Children->getChildCount() == 0) {
Printer << "}";
return;
}
// Try to dump symbols organized by member access level. Public members
// first, then protected, then private. This might be slow, so it's worth
// reconsidering the value of this if performance of large PDBs is a problem.
// NOTE: Access level of nested types is not recorded in the PDB, so we have
// a special case for them.
SymbolGroupByAccess Groups;
Groups.insert(std::make_pair(0, SymbolGroup()));
Groups.insert(std::make_pair((int)PDB_MemberAccess::Private, SymbolGroup()));
Groups.insert(
std::make_pair((int)PDB_MemberAccess::Protected, SymbolGroup()));
Groups.insert(std::make_pair((int)PDB_MemberAccess::Public, SymbolGroup()));
while (auto Child = Children->getNext()) {
PDB_MemberAccess Access = Child->getRawSymbol().getAccess();
if (isa<PDBSymbolTypeBaseClass>(*Child))
continue;
auto &AccessGroup = Groups.find((int)Access)->second;
if (auto Func = dyn_cast<PDBSymbolFunc>(Child.get())) {
if (Func->isCompilerGenerated() && opts::ExcludeCompilerGenerated)
continue;
if (Func->getLength() == 0 && !Func->isPureVirtual() &&
!Func->isIntroVirtualFunction())
continue;
Child.release();
AccessGroup.Functions.push_back(std::unique_ptr<PDBSymbolFunc>(Func));
} else if (auto Data = dyn_cast<PDBSymbolData>(Child.get())) {
Child.release();
AccessGroup.Data.push_back(std::unique_ptr<PDBSymbolData>(Data));
} else {
AccessGroup.Unknown.push_back(std::move(Child));
}
}
int Count = 0;
Count += dumpAccessGroup((PDB_MemberAccess)0, Groups[0]);
Count += dumpAccessGroup(PDB_MemberAccess::Public,
Groups[(int)PDB_MemberAccess::Public]);
Count += dumpAccessGroup(PDB_MemberAccess::Protected,
Groups[(int)PDB_MemberAccess::Protected]);
Count += dumpAccessGroup(PDB_MemberAccess::Private,
Groups[(int)PDB_MemberAccess::Private]);
if (Count > 0)
Printer.NewLine();
Printer << "}";
}
int ClassDefinitionDumper::dumpAccessGroup(PDB_MemberAccess Access,
const SymbolGroup &Group) {
if (Group.Functions.empty() && Group.Data.empty() && Group.Unknown.empty())
return 0;
int Count = 0;
if (Access == PDB_MemberAccess::Private) {
Printer.NewLine();
WithColor(Printer, PDB_ColorItem::Keyword).get() << "private";
Printer << ":";
} else if (Access == PDB_MemberAccess::Protected) {
Printer.NewLine();
WithColor(Printer, PDB_ColorItem::Keyword).get() << "protected";
Printer << ":";
} else if (Access == PDB_MemberAccess::Public) {
Printer.NewLine();
WithColor(Printer, PDB_ColorItem::Keyword).get() << "public";
Printer << ":";
}
Printer.Indent();
for (auto iter = Group.Functions.begin(), end = Group.Functions.end();
iter != end; ++iter) {
++Count;
(*iter)->dump(*this);
}
for (auto iter = Group.Data.begin(), end = Group.Data.end(); iter != end;
++iter) {
++Count;
(*iter)->dump(*this);
}
for (auto iter = Group.Unknown.begin(), end = Group.Unknown.end();
iter != end; ++iter) {
++Count;
(*iter)->dump(*this);
}
Printer.Unindent();
return Count;
}
void ClassDefinitionDumper::dump(const PDBSymbolTypeBaseClass &Symbol) {}
void ClassDefinitionDumper::dump(const PDBSymbolData &Symbol) {
VariableDumper Dumper(Printer);
Dumper.start(Symbol);
}
void ClassDefinitionDumper::dump(const PDBSymbolFunc &Symbol) {
if (Printer.IsSymbolExcluded(Symbol.getName()))
return;
Printer.NewLine();
FunctionDumper Dumper(Printer);
Dumper.start(Symbol, FunctionDumper::PointerType::None);
}
void ClassDefinitionDumper::dump(const PDBSymbolTypeVTable &Symbol) {}
void ClassDefinitionDumper::dump(const PDBSymbolTypeEnum &Symbol) {
if (Printer.IsTypeExcluded(Symbol.getName()))
return;
Printer.NewLine();
EnumDumper Dumper(Printer);
Dumper.start(Symbol);
}
void ClassDefinitionDumper::dump(const PDBSymbolTypeTypedef &Symbol) {
if (Printer.IsTypeExcluded(Symbol.getName()))
return;
Printer.NewLine();
TypedefDumper Dumper(Printer);
Dumper.start(Symbol);
}
void ClassDefinitionDumper::dump(const PDBSymbolTypeUDT &Symbol) {}
| 6,521 | 2,197 |
#include <vtkActor.h>
#include <vtkCellData.h>
#include <vtkColorSeries.h>
#include <vtkFloatArray.h>
#include <vtkLookupTable.h>
#include <vtkNamedColors.h>
#include <vtkNew.h>
#include <vtkPlaneSource.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <map>
#include <string>
#include <vector>
namespace {
void CreateLookupTableVTKBlue(vtkLookupTable* lut, int tableSize = 0);
void CreateLookupTableVTKBrown(vtkLookupTable* lut, int tableSize = 0);
void CreateLookupTableVTKRed(vtkLookupTable* lu, int tableSize = 0);
void CreateLookupTableVTKOrange(vtkLookupTable* lu, int tableSize = 0);
void CreateLookupTableVTKWhite(vtkLookupTable* lu, int tableSize = 0);
void CreateLookupTableVTKGrey(vtkLookupTable* lu, int tableSize = 0);
void CreateLookupTableVTKMagenta(vtkLookupTable* lu, int tableSize = 0);
void CreateLookupTableVTKCyan(vtkLookupTable* lu, int tableSize = 0);
void CreateLookupTableVTKYellow(vtkLookupTable* lu, int tableSize = 0);
void CreateLookupTableVTKGreen(vtkLookupTable* lu, int tableSize = 0);
} // namespace
int main(int argc, char* argv[])
{
std::string seriesName = "Red";
if (argc > 1)
{
seriesName = argv[1];
}
// Provide some geometry
int resolution = 6;
vtkNew<vtkPlaneSource> aPlane;
aPlane->SetXResolution(resolution);
aPlane->SetYResolution(resolution);
// Create cell data
vtkNew<vtkFloatArray> cellData;
for (int i = 0; i < resolution * resolution; i++)
{
cellData->InsertNextValue(i);
}
aPlane->Update(); // Force an update so we can set cell data
aPlane->GetOutput()->GetCellData()->SetScalars(cellData);
vtkNew<vtkNamedColors> colors;
vtkNew<vtkLookupTable> lut;
if (seriesName == "Blue")
{
CreateLookupTableVTKBlue(lut, resolution * resolution + 1);
}
else if (seriesName == "Brown")
{
CreateLookupTableVTKBrown(lut, resolution * resolution + 1);
}
else if (seriesName == "Red")
{
CreateLookupTableVTKRed(lut, resolution * resolution + 1);
}
else if (seriesName == "Orange")
{
CreateLookupTableVTKOrange(lut, resolution * resolution + 1);
}
else if (seriesName == "White")
{
CreateLookupTableVTKWhite(lut, resolution * resolution + 1);
}
else if (seriesName == "Grey")
{
CreateLookupTableVTKGrey(lut, resolution * resolution + 1);
}
else if (seriesName == "Magenta")
{
CreateLookupTableVTKMagenta(lut, resolution * resolution + 1);
}
else if (seriesName == "Cyan")
{
CreateLookupTableVTKCyan(lut, resolution * resolution + 1);
}
else if (seriesName == "Yellow")
{
CreateLookupTableVTKYellow(lut, resolution * resolution + 1);
}
else if (seriesName == "Green")
{
CreateLookupTableVTKGreen(lut, resolution * resolution + 1);
}
else
{
std::cout << "Bad series name: " << seriesName << std::endl;
return EXIT_FAILURE;
}
// Setup actor and mapper
vtkNew<vtkPolyDataMapper> mapper;
mapper->SetLookupTable(lut);
mapper->SetInputConnection(aPlane->GetOutputPort());
mapper->SetScalarModeToUseCellData();
mapper->SetScalarRange(0, resolution * resolution + 1);
vtkNew<vtkActor> actor;
actor->SetMapper(mapper);
actor->GetProperty()->EdgeVisibilityOn();
// Setup render window, renderer, and interactor
vtkNew<vtkRenderer> renderer;
vtkNew<vtkRenderWindow> renderWindow;
renderWindow->AddRenderer(renderer);
renderWindow->SetWindowName("CreateColorSeriesDemo");
vtkNew<vtkRenderWindowInteractor> renderWindowInteractor;
renderWindowInteractor->SetRenderWindow(renderWindow);
renderer->AddActor(actor);
renderer->SetBackground(colors->GetColor3d("SlateGray").GetData());
renderWindow->Render();
renderWindowInteractor->Start();
return EXIT_SUCCESS;
}
namespace {
void CreateLookupTableVTKBlue(vtkLookupTable* lut, int size)
{
vtkNew<vtkColorSeries> myColors;
myColors->SetColorSchemeByName("VTKBlueColors");
vtkNew<vtkNamedColors> nc;
myColors->AddColor(nc->GetColor3ub("alice_blue"));
myColors->AddColor(nc->GetColor3ub("blue"));
myColors->AddColor(nc->GetColor3ub("blue_light"));
myColors->AddColor(nc->GetColor3ub("blue_medium"));
myColors->AddColor(nc->GetColor3ub("cadet"));
myColors->AddColor(nc->GetColor3ub("cobalt"));
myColors->AddColor(nc->GetColor3ub("cornflower"));
myColors->AddColor(nc->GetColor3ub("cerulean"));
myColors->AddColor(nc->GetColor3ub("dodger_blue"));
myColors->AddColor(nc->GetColor3ub("indigo"));
myColors->AddColor(nc->GetColor3ub("manganese_blue"));
myColors->AddColor(nc->GetColor3ub("midnight_blue"));
myColors->AddColor(nc->GetColor3ub("navy"));
myColors->AddColor(nc->GetColor3ub("peacock"));
myColors->AddColor(nc->GetColor3ub("powder_blue"));
myColors->AddColor(nc->GetColor3ub("royal_blue"));
myColors->AddColor(nc->GetColor3ub("slate_blue"));
myColors->AddColor(nc->GetColor3ub("slate_blue_dark"));
myColors->AddColor(nc->GetColor3ub("slate_blue_light"));
myColors->AddColor(nc->GetColor3ub("slate_blue_medium"));
myColors->AddColor(nc->GetColor3ub("sky_blue"));
myColors->AddColor(nc->GetColor3ub("sky_blue_deep"));
myColors->AddColor(nc->GetColor3ub("sky_blue_light"));
myColors->AddColor(nc->GetColor3ub("steel_blue"));
myColors->AddColor(nc->GetColor3ub("steel_blue_light"));
myColors->AddColor(nc->GetColor3ub("turquoise_blue"));
myColors->AddColor(nc->GetColor3ub("ultramarine"));
int numberOfColors = myColors->GetNumberOfColors();
std::cout << "Number of colors: " << numberOfColors << std::endl;
lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size);
lut->SetTableRange(0, lut->GetNumberOfTableValues());
for (int i = 0; i < lut->GetNumberOfTableValues(); ++i)
{
vtkColor3ub color = myColors->GetColorRepeating(i);
lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255.,
color.GetBlue() / 255., 1.);
}
}
void CreateLookupTableVTKBrown(vtkLookupTable* lut, int size)
{
vtkNew<vtkColorSeries> myColors;
myColors->SetColorSchemeByName("VTKBrownColors");
vtkNew<vtkNamedColors> nc;
myColors->AddColor(nc->GetColor3ub("beige"));
myColors->AddColor(nc->GetColor3ub("brown"));
myColors->AddColor(nc->GetColor3ub("brown_madder"));
myColors->AddColor(nc->GetColor3ub("brown_ochre"));
myColors->AddColor(nc->GetColor3ub("burlywood"));
myColors->AddColor(nc->GetColor3ub("burnt_sienna"));
myColors->AddColor(nc->GetColor3ub("burnt_umber"));
myColors->AddColor(nc->GetColor3ub("chocolate"));
myColors->AddColor(nc->GetColor3ub("deep_ochre"));
myColors->AddColor(nc->GetColor3ub("flesh"));
myColors->AddColor(nc->GetColor3ub("flesh_ochre"));
myColors->AddColor(nc->GetColor3ub("gold_ochre"));
myColors->AddColor(nc->GetColor3ub("greenish_umber"));
myColors->AddColor(nc->GetColor3ub("khaki"));
myColors->AddColor(nc->GetColor3ub("khaki_dark"));
myColors->AddColor(nc->GetColor3ub("light_beige"));
myColors->AddColor(nc->GetColor3ub("peru"));
myColors->AddColor(nc->GetColor3ub("rosy_brown"));
myColors->AddColor(nc->GetColor3ub("raw_sienna"));
myColors->AddColor(nc->GetColor3ub("raw_umber"));
myColors->AddColor(nc->GetColor3ub("sepia"));
myColors->AddColor(nc->GetColor3ub("sienna"));
myColors->AddColor(nc->GetColor3ub("saddle_brown"));
myColors->AddColor(nc->GetColor3ub("sandy_brown"));
myColors->AddColor(nc->GetColor3ub("tan"));
myColors->AddColor(nc->GetColor3ub("van_dyke_brown"));
int numberOfColors = myColors->GetNumberOfColors();
std::cout << "Number of colors: " << numberOfColors << std::endl;
lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size);
lut->SetTableRange(0, lut->GetNumberOfTableValues());
for (int i = 0; i < lut->GetNumberOfTableValues(); ++i)
{
vtkColor3ub color = myColors->GetColorRepeating(i);
lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255.,
color.GetBlue() / 255., 1.);
}
}
void CreateLookupTableVTKRed(vtkLookupTable* lut, int size)
{
vtkNew<vtkColorSeries> myColors;
myColors->SetColorSchemeByName("VTKRedColors");
vtkNew<vtkNamedColors> nc;
myColors->AddColor(nc->GetColor3ub("alizarin_crimson"));
myColors->AddColor(nc->GetColor3ub("brick"));
myColors->AddColor(nc->GetColor3ub("cadmium_red_deep"));
myColors->AddColor(nc->GetColor3ub("coral"));
myColors->AddColor(nc->GetColor3ub("coral_light"));
myColors->AddColor(nc->GetColor3ub("deep_pink"));
myColors->AddColor(nc->GetColor3ub("english_red"));
myColors->AddColor(nc->GetColor3ub("firebrick"));
myColors->AddColor(nc->GetColor3ub("geranium_lake"));
myColors->AddColor(nc->GetColor3ub("hot_pink"));
myColors->AddColor(nc->GetColor3ub("indian_red"));
myColors->AddColor(nc->GetColor3ub("light_salmon"));
myColors->AddColor(nc->GetColor3ub("madder_lake_deep"));
myColors->AddColor(nc->GetColor3ub("maroon"));
myColors->AddColor(nc->GetColor3ub("pink"));
myColors->AddColor(nc->GetColor3ub("pink_light"));
myColors->AddColor(nc->GetColor3ub("raspberry"));
myColors->AddColor(nc->GetColor3ub("red"));
myColors->AddColor(nc->GetColor3ub("rose_madder"));
myColors->AddColor(nc->GetColor3ub("salmon"));
myColors->AddColor(nc->GetColor3ub("tomato"));
myColors->AddColor(nc->GetColor3ub("venetian_red"));
int numberOfColors = myColors->GetNumberOfColors();
std::cout << "Number of colors: " << numberOfColors << std::endl;
lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size);
lut->SetTableRange(0, lut->GetNumberOfTableValues());
for (int i = 0; i < lut->GetNumberOfTableValues(); ++i)
{
vtkColor3ub color = myColors->GetColorRepeating(i);
lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255.,
color.GetBlue() / 255., 1.);
}
}
void CreateLookupTableVTKGrey(vtkLookupTable* lut, int size)
{
vtkNew<vtkColorSeries> myColors;
vtkNew<vtkNamedColors> nc;
myColors->SetColorSchemeByName("VTKGreyColors");
myColors->AddColor(nc->GetColor3ub("cold_grey"));
myColors->AddColor(nc->GetColor3ub("dim_grey"));
myColors->AddColor(nc->GetColor3ub("grey"));
myColors->AddColor(nc->GetColor3ub("light_grey"));
myColors->AddColor(nc->GetColor3ub("slate_grey"));
myColors->AddColor(nc->GetColor3ub("slate_grey_dark"));
myColors->AddColor(nc->GetColor3ub("slate_grey_light"));
myColors->AddColor(nc->GetColor3ub("warm_grey"));
int numberOfColors = myColors->GetNumberOfColors();
std::cout << "Number of colors: " << numberOfColors << std::endl;
lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size);
lut->SetTableRange(0, lut->GetNumberOfTableValues());
for (int i = 0; i < lut->GetNumberOfTableValues(); ++i)
{
vtkColor3ub color = myColors->GetColorRepeating(i);
lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255.,
color.GetBlue() / 255., 1.);
}
}
void CreateLookupTableVTKWhite(vtkLookupTable* lut, int size)
{
vtkNew<vtkColorSeries> myColors;
vtkNew<vtkNamedColors> nc;
myColors->SetColorSchemeByName("VTKWhiteColors");
myColors->AddColor(nc->GetColor3ub("antique_white"));
myColors->AddColor(nc->GetColor3ub("azure"));
myColors->AddColor(nc->GetColor3ub("bisque"));
myColors->AddColor(nc->GetColor3ub("blanched_almond"));
myColors->AddColor(nc->GetColor3ub("cornsilk"));
myColors->AddColor(nc->GetColor3ub("eggshell"));
myColors->AddColor(nc->GetColor3ub("floral_white"));
myColors->AddColor(nc->GetColor3ub("gainsboro"));
myColors->AddColor(nc->GetColor3ub("ghost_white"));
myColors->AddColor(nc->GetColor3ub("honeydew"));
myColors->AddColor(nc->GetColor3ub("ivory"));
myColors->AddColor(nc->GetColor3ub("lavender"));
myColors->AddColor(nc->GetColor3ub("lavender_blush"));
myColors->AddColor(nc->GetColor3ub("lemon_chiffon"));
myColors->AddColor(nc->GetColor3ub("linen"));
myColors->AddColor(nc->GetColor3ub("mint_cream"));
myColors->AddColor(nc->GetColor3ub("misty_rose"));
myColors->AddColor(nc->GetColor3ub("moccasin"));
myColors->AddColor(nc->GetColor3ub("navajo_white"));
myColors->AddColor(nc->GetColor3ub("old_lace"));
myColors->AddColor(nc->GetColor3ub("papaya_whip"));
myColors->AddColor(nc->GetColor3ub("peach_puff"));
myColors->AddColor(nc->GetColor3ub("seashell"));
myColors->AddColor(nc->GetColor3ub("snow"));
myColors->AddColor(nc->GetColor3ub("thistle"));
myColors->AddColor(nc->GetColor3ub("titanium_white"));
myColors->AddColor(nc->GetColor3ub("wheat"));
myColors->AddColor(nc->GetColor3ub("white"));
myColors->AddColor(nc->GetColor3ub("white_smoke"));
myColors->AddColor(nc->GetColor3ub("zinc_white"));
int numberOfColors = myColors->GetNumberOfColors();
std::cout << "Number of colors: " << numberOfColors << std::endl;
lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size);
lut->SetTableRange(0, lut->GetNumberOfTableValues());
for (int i = 0; i < lut->GetNumberOfTableValues(); ++i)
{
vtkColor3ub color = myColors->GetColorRepeating(i);
lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255.,
color.GetBlue() / 255., 1.);
}
}
void CreateLookupTableVTKOrange(vtkLookupTable* lut, int size)
{
vtkNew<vtkColorSeries> myColors;
myColors->SetColorSchemeByName("VTKOrangeColors");
vtkNew<vtkNamedColors> nc;
myColors->AddColor(nc->GetColor3ub("cadmium_orange"));
myColors->AddColor(nc->GetColor3ub("cadmium_red_light"));
myColors->AddColor(nc->GetColor3ub("carrot"));
myColors->AddColor(nc->GetColor3ub("dark_orange"));
myColors->AddColor(nc->GetColor3ub("mars_orange"));
myColors->AddColor(nc->GetColor3ub("mars_yellow"));
myColors->AddColor(nc->GetColor3ub("orange"));
myColors->AddColor(nc->GetColor3ub("orange_red"));
myColors->AddColor(nc->GetColor3ub("yellow_ochre"));
int numberOfColors = myColors->GetNumberOfColors();
std::cout << "Number of colors: " << numberOfColors << std::endl;
lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size);
lut->SetTableRange(0, lut->GetNumberOfTableValues());
for (int i = 0; i < lut->GetNumberOfTableValues(); ++i)
{
vtkColor3ub color = myColors->GetColorRepeating(i);
lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255.,
color.GetBlue() / 255., 1.);
}
}
void CreateLookupTableVTKMagenta(vtkLookupTable* lut, int size)
{
vtkNew<vtkColorSeries> myColors;
myColors->SetColorSchemeByName("VTKMagentaColors");
vtkNew<vtkNamedColors> nc;
myColors->AddColor(nc->GetColor3ub("blue_violet"));
myColors->AddColor(nc->GetColor3ub("cobalt_violet_deep"));
myColors->AddColor(nc->GetColor3ub("magenta"));
myColors->AddColor(nc->GetColor3ub("orchid"));
myColors->AddColor(nc->GetColor3ub("orchid_dark"));
myColors->AddColor(nc->GetColor3ub("orchid_medium"));
myColors->AddColor(nc->GetColor3ub("permanent_red_violet"));
myColors->AddColor(nc->GetColor3ub("plum"));
myColors->AddColor(nc->GetColor3ub("purple"));
myColors->AddColor(nc->GetColor3ub("purple_medium"));
myColors->AddColor(nc->GetColor3ub("ultramarine_violet"));
myColors->AddColor(nc->GetColor3ub("violet"));
myColors->AddColor(nc->GetColor3ub("violet_dark"));
myColors->AddColor(nc->GetColor3ub("violet_red"));
myColors->AddColor(nc->GetColor3ub("violet_red_medium"));
myColors->AddColor(nc->GetColor3ub("violet_red_pale"));
int numberOfColors = myColors->GetNumberOfColors();
std::cout << "Number of colors: " << numberOfColors << std::endl;
lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size);
lut->SetTableRange(0, lut->GetNumberOfTableValues());
for (int i = 0; i < lut->GetNumberOfTableValues(); ++i)
{
vtkColor3ub color = myColors->GetColorRepeating(i);
lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255.,
color.GetBlue() / 255., 1.);
}
}
void CreateLookupTableVTKCyan(vtkLookupTable* lut, int size)
{
vtkNew<vtkColorSeries> myColors;
myColors->SetColorSchemeByName("VTKCyanColors");
vtkNew<vtkNamedColors> nc;
myColors->AddColor(nc->GetColor3ub("aquamarine"));
myColors->AddColor(nc->GetColor3ub("aquamarine_medium"));
myColors->AddColor(nc->GetColor3ub("cyan"));
myColors->AddColor(nc->GetColor3ub("cyan_white"));
myColors->AddColor(nc->GetColor3ub("turquoise"));
myColors->AddColor(nc->GetColor3ub("turquoise_dark"));
myColors->AddColor(nc->GetColor3ub("turquoise_medium"));
myColors->AddColor(nc->GetColor3ub("turquoise_pale"));
int numberOfColors = myColors->GetNumberOfColors();
std::cout << "Number of colors: " << numberOfColors << std::endl;
lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size);
lut->SetTableRange(0, lut->GetNumberOfTableValues());
for (int i = 0; i < lut->GetNumberOfTableValues(); ++i)
{
vtkColor3ub color = myColors->GetColorRepeating(i);
lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255.,
color.GetBlue() / 255., 1.);
}
}
void CreateLookupTableVTKYellow(vtkLookupTable* lut, int size)
{
vtkNew<vtkColorSeries> myColors;
myColors->SetColorSchemeByName("VTKYellowColors");
vtkNew<vtkNamedColors> nc;
myColors->AddColor(nc->GetColor3ub("aureoline_yellow"));
myColors->AddColor(nc->GetColor3ub("banana"));
myColors->AddColor(nc->GetColor3ub("cadmium_lemon"));
myColors->AddColor(nc->GetColor3ub("cadmium_yellow"));
myColors->AddColor(nc->GetColor3ub("cadmium_yellow_light"));
myColors->AddColor(nc->GetColor3ub("gold"));
myColors->AddColor(nc->GetColor3ub("goldenrod"));
myColors->AddColor(nc->GetColor3ub("goldenrod_dark"));
myColors->AddColor(nc->GetColor3ub("goldenrod_light"));
myColors->AddColor(nc->GetColor3ub("goldenrod_pale"));
myColors->AddColor(nc->GetColor3ub("light_goldenrod"));
myColors->AddColor(nc->GetColor3ub("melon"));
myColors->AddColor(nc->GetColor3ub("naples_yellow_deep"));
myColors->AddColor(nc->GetColor3ub("yellow"));
myColors->AddColor(nc->GetColor3ub("yellow_light"));
int numberOfColors = myColors->GetNumberOfColors();
std::cout << "Number of colors: " << numberOfColors << std::endl;
lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size);
lut->SetTableRange(0, lut->GetNumberOfTableValues());
for (int i = 0; i < lut->GetNumberOfTableValues(); ++i)
{
vtkColor3ub color = myColors->GetColorRepeating(i);
lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255.,
color.GetBlue() / 255., 1.);
}
}
void CreateLookupTableVTKGreen(vtkLookupTable* lut, int size)
{
vtkNew<vtkColorSeries> myColors;
myColors->SetColorSchemeByName("VTKGreenColors");
vtkNew<vtkNamedColors> nc;
myColors->AddColor(nc->GetColor3ub("chartreuse"));
myColors->AddColor(nc->GetColor3ub("chrome_oxide_green"));
myColors->AddColor(nc->GetColor3ub("cinnabar_green"));
myColors->AddColor(nc->GetColor3ub("cobalt_green"));
myColors->AddColor(nc->GetColor3ub("emerald_green"));
myColors->AddColor(nc->GetColor3ub("forest_green"));
myColors->AddColor(nc->GetColor3ub("green"));
myColors->AddColor(nc->GetColor3ub("green_dark"));
myColors->AddColor(nc->GetColor3ub("green_pale"));
myColors->AddColor(nc->GetColor3ub("green_yellow"));
myColors->AddColor(nc->GetColor3ub("lawn_green"));
myColors->AddColor(nc->GetColor3ub("lime_green"));
myColors->AddColor(nc->GetColor3ub("mint"));
myColors->AddColor(nc->GetColor3ub("olive"));
myColors->AddColor(nc->GetColor3ub("olive_drab"));
myColors->AddColor(nc->GetColor3ub("olive_green_dark"));
myColors->AddColor(nc->GetColor3ub("permanent_green"));
myColors->AddColor(nc->GetColor3ub("sap_green"));
myColors->AddColor(nc->GetColor3ub("sea_green"));
myColors->AddColor(nc->GetColor3ub("sea_green_dark"));
myColors->AddColor(nc->GetColor3ub("sea_green_medium"));
myColors->AddColor(nc->GetColor3ub("sea_green_light"));
myColors->AddColor(nc->GetColor3ub("spring_green"));
myColors->AddColor(nc->GetColor3ub("spring_green_medium"));
myColors->AddColor(nc->GetColor3ub("terre_verte"));
myColors->AddColor(nc->GetColor3ub("viridian_light"));
myColors->AddColor(nc->GetColor3ub("yellow_green"));
int numberOfColors = myColors->GetNumberOfColors();
std::cout << "Number of colors: " << numberOfColors << std::endl;
lut->SetNumberOfTableValues(size == 0 ? numberOfColors : size);
lut->SetTableRange(0, lut->GetNumberOfTableValues());
for (int i = 0; i < lut->GetNumberOfTableValues(); ++i)
{
vtkColor3ub color = myColors->GetColorRepeating(i);
lut->SetTableValue(i, color.GetRed() / 255., color.GetGreen() / 255.,
color.GetBlue() / 255., 1.);
}
}
} // namespace
| 20,670 | 7,997 |
/*
// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
// component of the Texas A&M University System.
// All rights reserved.
// The information and source code contained herein is the exclusive
// property of TEES and may not be disclosed, examined or reproduced
// in whole or in part without explicit written authorization from TEES.
*/
#define STAPL_RUNTIME_TEST_MODULE lazy_storage
#include "utility.h"
#include <stapl/runtime/type_traits/lazy_storage.hpp>
template<typename T>
union wrapper
{
stapl::lazy_storage<T> storage;
int i;
};
struct empty
{ };
constexpr bool operator==(empty const&, empty const&) noexcept
{ return true; }
BOOST_AUTO_TEST_CASE( test_empty )
{
typedef empty value_type;
wrapper<value_type> u;
u.storage.construct(value_type());
value_type v = u.storage.moveout();
BOOST_CHECK( v==value_type() );
}
BOOST_AUTO_TEST_CASE( test_int )
{
typedef int value_type;
wrapper<value_type> u;
u.storage.construct(42);
value_type v = u.storage.moveout();
BOOST_CHECK_EQUAL( v, 42 );
}
class A
{
public:
static int constructed;
int i;
public:
A(void)
: i(42)
{ ++constructed; }
A(A const& other)
: i(other.i)
{ ++constructed; }
~A(void)
{ --constructed; }
};
int A::constructed = 0;
constexpr bool operator==(A const & a0, A const& a1)
{ return (a0.i==a1.i); }
BOOST_AUTO_TEST_CASE( test_A )
{
typedef A value_type;
BOOST_CHECK_EQUAL( A::constructed, 0 );
{
const value_type iv;
BOOST_CHECK_EQUAL( A::constructed, 1 );
wrapper<value_type> u;
BOOST_CHECK_EQUAL( A::constructed, 1 );
u.storage.construct(iv);
BOOST_CHECK_EQUAL( A::constructed, 2 );
value_type v = u.storage.moveout();
BOOST_CHECK_EQUAL( A::constructed, 2 );
BOOST_CHECK( v==iv );
}
BOOST_CHECK_EQUAL( A::constructed, 0 );
}
| 1,868 | 735 |