text
stringlengths 8
6.88M
|
|---|
#include <iostream> //Accessing system libary iostream.
using namespace std; //Abillity to use cin, cout, etc.
int main() { //Main body
cout << "Welcome to computer science!/n" << endl; //prints char in "".
return 0; //Return 0 if program works
}
|
#include<iostream>
using namespace std;
class sample{
private:
int i;
public:
virtual void display(){
cout<<"\n In the SAMPLE class \n";
}
//virtual void display()=0;
};
class example{
private:
int i;
public:
void display(){
cout<<"\n In the EXAMPLE class\n";
}
};
class trial{
public:
void display(){
cout<<"\n In the TRIAL class\n";
}
};
int main(){
sample s;
example e;
trial t;
cout<<"\n"<<sizeof(s)<<"\t"<<sizeof(e)<<"\t"<<sizeof(t)<<"\n";
return 0;
}
|
#include <array>
#include "gayboy.hpp"
namespace gb {
namespace {
bool compareLogo() {
std::array<unsigned char, 48> logo {
0xCE, 0xED, 0x66, 0x66, 0xCC, 0x0D, 0x00, 0x0B,
0x03, 0x73, 0x00, 0x83, 0x00, 0x0C, 0x00, 0x0D,
0x00, 0x08, 0x11, 0x1F, 0x88, 0x89, 0x00, 0x0E,
0xDC, 0xCC, 0x6E, 0xE6, 0xDD, 0xDD, 0xD9, 0x99,
0xBB, 0xBB, 0x67, 0x63, 0x6E, 0x0E, 0xEC, 0xCC,
0xDD, 0xDC, 0x99, 0x9F, 0xBB, 0xB9, 0x33, 0x3E
};
return std::equal(logo.begin(), logo.end(), rom.begin() + 0x104);
}
bool validateHeaderChecksum() {
unsigned short sum = 0;
for (int i = 0x134; i <= 0x14d; ++i)
sum += rom[i];
sum += 25;
return reinterpret_cast<unsigned char*>(&sum)[0] == 0;
}
}
void powerup() {
if (!compareLogo())
throw std::runtime_error("Logo comparison failed. Invalid or corrupted ROM.");
if (!validateHeaderChecksum())
throw std::runtime_error("Header checksum failed. Invalid or corrupted ROM.");
// Program execution begins at $100
cpu::pc = 0x100;
}
}
|
//
// Created by cirkul on 27.11.2020.
//
#ifndef UNTITLED3_SHEEP_H
#define UNTITLED3_SHEEP_H
#include "Herbivorous.h"
class Sheep : public Herbivorous {
Sheep(Playground& pg, int i, int j) : Herbivorous(pg, i, j) {
this->name = sheep;
this->size = middle;
this->escChance = 10;
this->defaultHp = 100;
this->hp = this->defaultHp;
this->maxSatisfaction = 100;
this->satietyInd = this->maxSatisfaction;
this->energyConsumption = 50;
this->lifeDuration = 4;
this->movPt = 3;
this->currMovPt = this->movPt;
}
Animal * spawn(Playground &pg, int i, int j) override;
friend class Model;
};
#endif //UNTITLED3_SHEEP_H
|
#include <iostream>
#include "queue.hpp"
Queue::Queue() {
int size = 0;
int* queue = nullptr;
int countForPop = 0;
std::cout << "Default constructor works!" << std::endl;
}
Queue::Queue(Queue& que) {
std::cout << "Copy constructor works!" << std::endl;
this->queue = new int[que.size+5];
this->size = que.size;
this->countForShift = que.countForShift;
this->countForPop = que.countForPop;
for(int i = 0; i < que.size; ++i) {
this->queue[i] = que.queue[i];
}
}
Queue::Queue(Queue&& que) {
std::cout << "Move constructor works!" << std::endl;
this->queue = que.queue;
this->size = que.size;
this->countForShift = que.countForShift;
this->countForPop = que.countForPop;
delete que.queue;
que.queue = nullptr;
que.size = 0;
que.countForShift = 0;
que.countForPop = 0;
}
Queue::~Queue() {
std::cout << "Destructor works!" << std::endl;
delete [] queue;
queue = nullptr;
}
Queue::Queue(int n, int fill) {
queue = new int[n+5];
size = n;
for(int i = 0; i < size; ++i) {
queue[i] = fill;
}
}
int Queue::getSize() {
return size;
}
int* Queue::getQueue() {
return queue;
}
void Queue::shift(int newElem) {
++size;
for(int i = size-1; 0 < i; --i) {
queue[i] = queue[i - 1];
}
queue[0] = newElem;
++countForShift;
if(0 == countForShift%5) {
int* tempQueue = new int[size + 5];
for(int i = 0; i < size; ++i) {
tempQueue[i] = queue[i];
}
delete queue;
queue = tempQueue;
std::cout << "We shifted more than 5 time" << std::endl;
}
}
void Queue::pop() {
if(0 < size) {
queue[size] = 0;
--size;
++countForPop;
if(0 == countForPop%5) {
int* tempQueue = new int[size + 5];
for(int i = 0; i < size; ++i) {
tempQueue[i] = queue[i];
}
delete queue;
queue = tempQueue;
std::cout << "We poped more than 5 time" << std::endl;
}
}
}
void Queue::printQueue() {
for(int i = 0; i < size; ++i) {
std::cout << queue[i] << " ";
}
std::cout << std::endl;
}
|
#include "stdafx.h"
#include "../MonsterBox/MonsterBox.h"
#include "DungeonGame.h"
#include "../GameData.h"
#include "DungeonSelect.h"
#include "../GameCursor.h"
#include "DungeonData.h"
#include "MonsterDrop.h"
#include <random>
#include "DropEgg.h"
#include "../Monster/Monsters/Armor.h"
#include "../Monster/Monsters/Book.h"
#include"..//Monster/Monsters/Uma.h"
#include "../Monster/Monsters/Fairy.h"
#include "../Monster/Monsters/Goblin.h"
DropEgg::DropEgg()
{
}
DropEgg::~DropEgg()
{
}
bool DropEgg::Start() {
m_egg = NewGO<SkinModelRender>(0);
m_egg->SetShadowReciever(false);
m_egg->SetDirLight({ 0, 0, -1, 0 }, 0);
m_egg->Init(L"Assets/modelData/egg.cmo", nullptr, 0, enFbxUpAxisY);
m_egg->SetPosition(m_eggPos);
//std::random_device rnd;
//m_monsterId = static_cast<MonsterID>(rnd() % enNumMonster);
IMonsterBox().GetMonster(m_monsterId);
auto se = NewGO<Sound>(0);
se->Init(L"Assets/sound/dungeon/puyon1.wav", false);
se->Play();
return true;
}
void DropEgg::OnDestroy() {
DeleteGO(m_monster);
DeleteGO(m_egg);
}
void DropEgg::Update() {
static float fixTiming = 5.f;
static float bigTiming = 5.f + fixTiming;
static float smallTiming = 5.9f + fixTiming;
static float effectTiming = 4.7f + fixTiming;
static float bkEffectTiming = 15.f + fixTiming;
static float monsterTiming = 20.f + fixTiming;
static float bigSpeed = 0.01f;
static float smallSpeed = 0.05f;
static float rotationParam = 10.f;
static float rotationSpeed = 0.2f;
if (m_egg == nullptr)
return;
m_timer += 0.1f;
//rotation
m_eggTime += rotationSpeed;
float x = sin(m_eggTime);
m_eggRot.SetRotationDeg(CVector3::AxisZ(), x * rotationParam);
m_egg->SetRotation(m_eggRot);
//scale
if (m_timer >= bigTiming && m_timer <= smallTiming) {
mf_eggSca += bigSpeed;
}
if (m_timer >= smallTiming && mf_eggSca >= 0.f) {
mf_eggSca -= smallSpeed;
}
m_eggSca *= mf_eggSca;
m_egg->SetScale(m_eggSca);
//effect
if (m_timer >= effectTiming && !m_isPlayedEffect) {
m_efk = NewGO<CEffect>(0);
//m_efk->SetScale({ 8.f,8.f,8.f });
m_efk->SetScale({ 9.f,9.f,9.f });
m_efk->SetPosition({ 0.f,-50.f,200.f });
m_efk->Play(L"Assets/effect/dropefk.efk", 2.5f);
m_isPlayedEffect = true;
auto se = NewGO<Sound>(0);
se->Init(L"Assets/sound/dungeon/light.wav", false);
se->Play();
}
if (m_timer >= bkEffectTiming && !m_isPlayedBackEffect) {
/* ef = NewGO<CEffect>(0, "DRB");
ef->SetScale(CVector3::One() * 10);
CQuaternion rot = CQuaternion::Identity();
ef->SetRotation(rot);
auto p = m_monsterPos;
p.z -= 10.f;
p.y += 100.f;
ef->SetPosition(p);
ef->Play(L"Assets/effect/drback.efk");
m_efk->Play(L"Assets/effect/dropefk.efk", 2.5f);*/
ef = NewGO<CEffect>(0, "DRB");
//m_efk->SetScale({ 8.f,8.f,8.f });
ef->SetScale({ 13.f,13.f,13.f });
auto p = m_monsterPos;
p.z -= 10.f;
p.y += 200.f;
//m_efk->SetPosition({ 0.f,0.f,-200.f });
ef->SetPosition(p);
ef->Play(L"Assets/effect/drback.efk");
m_isPlayedBackEffect = true;
}
//new monster
if (m_timer >= monsterTiming && !m_isDisplayMonster) {
NewMonster();
m_isDisplayMonster = true;
}
}
void DropEgg::NewMonster() {
m_monster = NewGO<SkinModelRender>(1);
m_monster->SetPosition(m_monsterPos);
m_monster->SetScale(CVector3::One() * 2);
m_monster->SetDirLight({ 0, 0, -1, 0}, 0);
auto se = NewGO<Sound>(0);
//se->Init(L"Assets/sound/dungeon/ban1.wav", false);
se->Init(L"Assets/sound/dungeon/newmon.wav", false);
se->Play();
{
auto se = NewGO<Sound>(0);
//se->Init(L"Assets/sound/dungeon/ban1.wav", false);
se->Init(L"Assets/sound/dungeon/newmon1.wav", false);
se->Play();
}
wcscpy(m_monsterName, GameData::GetMonsterName(m_monsterId));
switch (m_monsterId) {
case enUmataur:
{
m_animClip[0].Load(L"Assets/modelData/uma/anim_uma_idle.tka");
m_animClip[0].SetLoopFlag(true);
m_monster->Init(L"Assets/modelData/uma.cmo", m_animClip, 1);
m_monster->PlayAnimation(0);
break;
}
case enFairy:
{
m_animClip[0].Load(L"Assets/modelData/fairy/hnd_idle.tka");
m_animClip[0].SetLoopFlag(true);
m_monster->Init(L"Assets/modelData/hnd.cmo", m_animClip, 1);
m_monster->PlayAnimation(0);
break;
}
case enArmor:
{
m_animClip[0].Load(L"Assets/modelData/armor/armor_idle.tka");
m_animClip[0].SetLoopFlag(true);
m_monster->SetScale(m_modelScale * 0.3);
m_monster->Init(L"Assets/modelData/armor.cmo", m_animClip, 1,enFbxUpAxisZ, "PSMainBook");
m_monster->PlayAnimation(0);
break;
}
case enBook:
{
m_animClip[0].Load(L"Assets/modelData/book/book_idle.tka");
m_animClip[0].SetLoopFlag(true);
m_monster->Init(L"Assets/modelData/book.cmo", m_animClip, 1,enFbxUpAxisZ,"PSMainBook");
m_monster->PlayAnimation(0);
break;
}
case enGoblin:
{
m_animClip[0].Load(L"Assets/modelData/gob/gob_idle.tka");
m_animClip[0].SetLoopFlag(true);
m_monster->SetScale(m_modelScale * 30);
m_monster->Init(L"Assets/modelData/gob.cmo", m_animClip, 1);
m_monster->PlayAnimation(0);
break;
}
case enRedHead:
{
m_animClip[0].Load(L"Assets/modelData/RedHead/idle.tka");
m_animClip[0].SetLoopFlag(true);
m_monster->SetScale(m_modelScale * 1.5);
m_monster->Init(L"Assets/modelData/RedHead.cmo", m_animClip, 1);
m_monster->PlayAnimation(0);
break;
}
case enKikyo:
{
m_animClip[0].Load(L"Assets/modelData/kikyo_chan/hero_taiki_animation.tka");
m_animClip[0].SetLoopFlag(true);
m_monster->SetScale(m_modelScale * 2);
m_monster->Init(L"Assets/modelData/hero.cmo", m_animClip, 1,enFbxUpAxisY);
m_monster->PlayAnimation(0);
break;
}
case enShikoChu:
{
m_monster->SetScale(m_modelScale * 4);
m_monster->Init(L"Assets/modelData/si_bug.cmo");
break;
}
case enChris:
{
m_animClip[0].Load(L"Assets/modelData/chris/cri_idle.tka");
m_animClip[0].SetLoopFlag(true);
m_monster->SetScale(m_modelScale * 2);
m_monster->Init(L"Assets/modelData/cri.cmo", m_animClip, 1);
m_monster->PlayAnimation(0);
break;
}
default:
MessageBox(nullptr, "新しいモンスター実装してどうぞ", "HELLO", MB_OK);
/*case enRingo:
m_animClip[0].Load(L"Assets/modelData/RingoChan/idle.tka");
m_animClip[0].SetLoopFlag(true);
m_monster->SetScale(m_modelScale * 30);
m_monster->Init(L"Assets/modelData/ringo.cmo", m_animClip, 1);
wcscpy(m_monsterName, L"りんごちゃん");
m_monster->PlayAnimation(0);
break;*/
}
}
|
#include "mainwindow.h"
static const int windowSizeX = 650;
static const int windowSizeY = 300;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent), isChanged(false), isClosing(false)
{
try
{
settings = std::make_shared<Settings>();
settings->load();
notes = std::make_shared<Notebook>(settings);
}
catch(std::exception& e)
{
QMessageBox::critical(parent, "MainWindow::MainWindow", e.what());
}
this->setUI();
showTrayMessage();
}
void MainWindow::openEditWindow(Note * const note)
{
EditWindow *window = new EditWindow(settings);
window->setWindowFlags(window->windowFlags() | Qt::MSWindowsFixedSizeDialogHint);
window->setWindowModality(Qt::ApplicationModal);
window->setAttribute(Qt::WA_DeleteOnClose);
connect(window, SIGNAL(noteAdded(Note*const)), this, SLOT(addNote(Note*const)));
connect(window, SIGNAL(noteAdded(Note*const)), this, SLOT(showNotes()));
connect(window, SIGNAL(noteAdded(Note*const)), this, SLOT(showClosestNote()));
connect(window, SIGNAL(noteAdded(Note*const)), this, SLOT(switchButtons()));
connect(window, SIGNAL(noteEdited()), this, SIGNAL(noteEdited()));
connect(window, SIGNAL(noteEdited()), this, SLOT(showNotes()));
connect(window, SIGNAL(noteEdited()), this, SLOT(showClosestNote()));
connect(window, SIGNAL(noteEdited()), this, SLOT(setChanged()));
const QDate d = cal->selectedDate();
if(QObject::sender() == addButton)
{
window->loadNotes(d, nullptr);
}
else if(QObject::sender() == editButton)
{
window->loadNotes(d, notes->getNotesFromDate(d));
}
else //Edit button in NoteListWindow
{
window->loadNote(note);
}
window->show();
moveToCenter(window);
cal->setFocus();
}
void MainWindow::setUI()
{
mainLayout = new QHBoxLayout;
leftLayout = new QVBoxLayout;
this->createMenu();
this->createStatusBar();
this->createCalendar();
this->createButtonLayout();
this->createTrayIcon();
this->createScrollArea();
this->setWindowTitle("Note Keeper");
noteTextTitle = new QLabel("No notes on "+cal->selectedDate().toString(settings->dateFormat));
leftLayout->addWidget(cal);
leftLayout->addWidget(noteTextTitle);
leftLayout->addWidget(scrollArea);
mainLayout->addLayout(leftLayout);
mainLayout->addLayout(buttonsLayout);
QWidget *window = new QWidget;
window->setLayout(mainLayout);
this->setCentralWidget(window);
this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
this->setFixedSize(this->size());
this->setWindowFlags(this->windowFlags() | Qt::MSWindowsFixedSizeDialogHint);
MainWindow::moveToCenter(this);
this->setMinimumSize(windowSizeX,windowSizeY);
this->setMaximumSize(windowSizeX,windowSizeY*2);
this->setStyleSheet("QStatusBar::item { border: 0px solid black }; ");
this->switchButtons();
this->showNotes();
this->showClosestNote();
this->setWindowIcon(QIcon(":/images/icon"));
connect(this, SIGNAL(noteDeleted()), this, SLOT(switchButtons()));
}
void MainWindow::createMenu()
{
QMenuBar *menu = this->menuBar();
QMenu *fileMenu = menu->addMenu("File");
QMenu *helpMenu = menu->addMenu("Help");
QList<QAction *> fileActions;
fileActions.append(new QAction("Save",this));
fileActions.back()->setShortcut(Qt::CTRL | Qt::Key_S);
fileActions.append(new QAction("Show all notes...",this));
fileActions.append(new QAction("Delete outdated notes",this));
fileActions.append(new QAction("Delete all notes",this));
QAction *settings = new QAction("Settings...", this);
connect(fileActions.front(), SIGNAL(triggered()), this, SLOT(saveNotes()));
connect(fileActions.at(1), SIGNAL(triggered()), this, SLOT(openAllNotesWindow()));
connect(fileActions.at(2), SIGNAL(triggered()), this, SLOT(deleteOutdated()));
connect(fileActions.at(3), SIGNAL(triggered()), this, SLOT(deleteAll()));
connect(settings, SIGNAL(triggered()), this, SLOT(openSettingsWindow()));
fileMenu->addActions(fileActions);
fileMenu->addSeparator();
fileMenu->addAction(settings);
QAction *aboutAction = new QAction("About...",this);
helpMenu->addAction(aboutAction);
connect(aboutAction, SIGNAL(triggered()), this, SLOT(openAboutWindow()));
connect(this, SIGNAL(noteDeleted()), this, SLOT(showClosestNote()));
menu->show();
}
void MainWindow::createStatusBar()
{
QStatusBar *sBar = this->statusBar();
statusLabel = new QLabel("No noted dates in the future.");
sBar->setSizeGripEnabled(false);
sBar->addWidget(statusLabel);
sBar->setSizeGripEnabled(false);
}
void MainWindow::createTrayIcon()
{
notificationsAction = new QAction("Show today's notifications", this);
openAction = new QAction("Open Note Keeper", this);
quitAction = new QAction("Exit", this);
trayIconMenu = new QMenu(this);
trayIconMenu->addAction(notificationsAction);
trayIconMenu->addAction(openAction);
trayIconMenu->addAction(quitAction);
connect(notificationsAction, SIGNAL(triggered()), this, SLOT(showTrayMessage()));
connect(openAction, SIGNAL(triggered()), this, SLOT(showFromTray()));
openAction->setEnabled(false);
connect(quitAction, SIGNAL(triggered()), this, SLOT(closeProgram()));
trayIcon = new QSystemTrayIcon(this);
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
trayIcon->setContextMenu(trayIconMenu);
trayIcon->setToolTip("Note Keeper");
trayTimer = new QTimer(this);
trayTimer->setInterval(10000);
trayTimer->setSingleShot(true);
connect(trayTimer, SIGNAL(timeout()), this, SLOT(showTrayMessage()));
connect(trayIcon, SIGNAL(messageClicked()), this, SLOT(showTrayMessage()));
trayIcon->setIcon(QIcon(":/images/icon"));
trayIcon->show();
}
void MainWindow::createButtonLayout()
{
buttonsLayout = new QVBoxLayout();
addButton = new QPushButton("Add note");
editButton = new QPushButton("Edit note");
removeButton = new QPushButton("Delete note");
todayButton = new QPushButton("Go to current date");
quitButton = new QPushButton("Close");
connect(addButton, SIGNAL(clicked()), this, SLOT(openEditWindow()));
connect(editButton, SIGNAL(clicked()), this, SLOT(openEditWindow()));
connect(removeButton, SIGNAL(clicked()), this, SLOT(openDeleteDialogue()));
connect(todayButton, SIGNAL(clicked()), cal, SLOT(showToday()));
connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));
buttonsLayout->addWidget(addButton);
buttonsLayout->addWidget(editButton);
buttonsLayout->addWidget(removeButton);
buttonsLayout->addWidget(todayButton);
buttonsLayout->addWidget(quitButton);
buttonsLayout->setAlignment(Qt::AlignTop);
}
void MainWindow::createScrollArea()
{
scrollArea = new QScrollArea;
QWidget *scrollWidget = new QWidget;
scrollLayout = new QVBoxLayout;
scrollLayout->setMargin(5);
scrollLayout->setAlignment(Qt::AlignTop);
scrollWidget->setLayout(scrollLayout);
scrollArea->setWidget(scrollWidget);
scrollArea->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
scrollArea->setFixedWidth(cal->minimumWidth());
scrollArea->setMaximumHeight(500);
scrollArea->setMinimumHeight(0);
scrollArea->setFixedHeight(200);
scrollArea->setWidgetResizable(true);
scrollArea->hide();
}
void MainWindow::createCalendar()
{
cal = new Calendar(notes, settings);
cal->setMinimumSize(500, 250);
cal->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
connect(cal, SIGNAL(selectionChanged()), this, SLOT(switchButtons()));
connect(cal, SIGNAL(selectionChanged()), this, SLOT(showNotes()));
}
void MainWindow::moveToCenter(QWidget * const window)
{
QDesktopWidget *d = QApplication::desktop();
int ww = window->width();
int wh = window->height();
int dw = d->width();
int dh = d->height();
window->move(dw/2 - ww/2, dh/2 - wh/2);
}
void MainWindow::addNote(Note * const note)
{
notes->addNote(note);
isChanged = true;
}
void MainWindow::showNotes()
{
const QDate d = cal->selectedDate();
scrollArea->hide();
auto notesList = notes->getNotesFromDate(d);
const int notesCount = notesList->size();
int labelsSize = noteLabels.size();
if(notesCount != 0)
{
noteTextTitle->setText(d.toString(settings->dateFormat) + ": ("+QString::number(notesCount)+")");
while(notesCount > labelsSize)
{
addNoteLabel();
++labelsSize;
}
for(int i = 0; i < labelsSize; i++)
{
if(i < notesCount)
{
noteLabels[i]->setText(notesList->at(i)->text);
noteLabels[i]->setEnabled(true);
noteLabels[i]->show();
}
else
{
noteLabels[i]->setEnabled(false);
noteLabels[i]->hide();
}
}
}
else
{
noteTextTitle->setText("No notes on "+d.toString(settings->dateFormat));
}
cal->setFocus();
resizeTimer();
}
void MainWindow::addNoteLabel()
{
QLabel *label = new QLabel;
label->setFrameShape(QFrame::StyledPanel);
label->setContentsMargins(2, 0, 0, 2);
label->setMargin(5);
scrollLayout->addWidget(label);
noteLabels.append(label);
}
void MainWindow::switchButtons()
{
if(notes->contains(cal->selectedDate()))
{
editButton->show();
removeButton->show();
}
else
{
editButton->hide();
removeButton->hide();
}
}
void MainWindow::resizeMe()
{
if(noteTextTitle->text().left(8) != "No notes")
{
int scrollAreaHeight = 0;
for(auto label : noteLabels)
{
if(label->isEnabled())
{
label->adjustSize();
label->setFixedWidth(scrollArea->widget()->width() - scrollLayout->margin() * 2 - 20);
scrollAreaHeight += label->frameGeometry().height() + label->margin();
}
}
scrollAreaHeight += scrollLayout->margin() + 5;
if(scrollAreaHeight > cal->minimumHeight())
{
scrollAreaHeight = cal->minimumHeight();
}
scrollArea->setFixedHeight(scrollAreaHeight);
scrollArea->show();
}
this->resize(this->minimumSizeHint());
}
void MainWindow::resizeTimer()
{
QTimer::singleShot(1, this, SLOT(resizeMe()));
}
void MainWindow::saveNotes()
{
try
{
notes->saveNotes();
}
catch(std::exception& e)
{
QMessageBox::critical(this, "Notebook::saveNotes", QString::fromLocal8Bit(e.what()));
}
isChanged = false;
}
void MainWindow::openDeleteDialogue()
{
auto list = std::move(notes->getNotesFromDate(cal->selectedDate()));
if(list->size() == 1)
{
int i = showDeleteMessageBox(DeleteOption::One);
if(i == QMessageBox::Yes)
{
deleteNote(list->first());
}
}
else
{
DeleteDialogue *dialogue = new DeleteDialogue(std::move(list));
dialogue->setAttribute(Qt::WA_DeleteOnClose);
connect(dialogue, SIGNAL(deleteNotes(std::shared_ptr<QList<Note*>>)), this, SLOT(deleteNotes(std::shared_ptr<QList<Note*>>)));
dialogue->show();
moveToCenter(dialogue);
}
cal->setFocus();
}
void MainWindow::deleteNoteFromListWindow(Note * const note)
{
if(showDeleteMessageBox(DeleteOption::One) == QMessageBox::Yes)
{
deleteNote(note);
}
}
void MainWindow::deleteNote(Note * const note)
{
notes->deleteNote(note);
this->showNotes();
isChanged = true;
emit noteDeleted();
}
void MainWindow::deleteNotes(std::shared_ptr<QList<Note *>> noteList)
{
for(auto note : *noteList)
{
notes->deleteNote(note);
}
this->showNotes();
isChanged = true;
emit noteDeleted();
}
void MainWindow::deleteAll()
{
int i = showDeleteMessageBox(DeleteOption::All);
if(i == QMessageBox::Yes)
{
if(notes->deleteAll() > 0)
isChanged = true;
this->showNotes();
emit noteDeleted();
}
cal->setFocus();
}
void MainWindow::deleteOutdated()
{
int i = showDeleteMessageBox(DeleteOption::Outdated);
if(i == QMessageBox::Yes)
{
if(notes->deleteOutdated(QDate::currentDate()) > 0)
isChanged = true;
this->showNotes();
emit noteDeleted();
}
cal->setFocus();
}
int MainWindow::showDeleteMessageBox(const DeleteOption op)
{
QString title, text;
switch(op)
{
case DeleteOption::One:
title = "Delete note?";
text = "Are you sure you want to delete this note?";
break;
case DeleteOption::Outdated:
title = "Delete outdated notes?";
text = "Are you sure you want to delete all outdated notes?";
break;
case DeleteOption::All:
title = "Delete all notes?";
text = "Are you sure you want to delete all notes?";
break;
default:
break;
}
return QMessageBox::question(this, title, text, QMessageBox::Yes, QMessageBox::No);
}
int MainWindow::showExitWOSavingMessageBox()
{
QMessageBox mb(this);
mb.setWindowTitle("Some notes have been changed");
mb.setText("Do you want to save your changes before quitting?");
mb.setInformativeText("If you don't save your changes, they will be discarded.");
mb.setIcon(QMessageBox::Warning);
mb.setStandardButtons(QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
return mb.exec();
}
void MainWindow::closeEvent(QCloseEvent *event)
{
if(isClosing)
{
if(isChanged)
{
int i = showExitWOSavingMessageBox();
switch(i)
{
case QMessageBox::Yes:
saveNotes();
event->accept();
qApp->quit();
break;
case QMessageBox::No:
event->accept();
qApp->quit();
break;
case QMessageBox::Cancel:
isClosing = false;
event->ignore();
this->showFromTray();
break;
default:
break;
}
}
else
{
event->accept();
qApp->quit();
}
}
else
{
event->ignore();
this->hide();
openAction->setEnabled(true);
}
}
void MainWindow::showClosestNote()
{
int noteTextPieceSize = 25;
Note *n = notes->findClosest(QDate::currentDate());
if(n != nullptr)
{
QString statusText = "Closest noted date" + n->date.toString("("+settings->dateFormat+"):");
QString noteTextTrimmed = n->text.trimmed();
QString noteTextLine = noteTextTrimmed.section('\n',0,0);
if(noteTextLine.size() > noteTextPieceSize || noteTextTrimmed.size() > noteTextLine.size())
{
statusText += noteTextLine.left(noteTextPieceSize) + "...";
}
else
{
statusText += noteTextLine;
}
statusLabel->setText(statusText);
}
else
statusLabel->setText("No noted dates in the future.");
}
void MainWindow::closeProgram()
{
isClosing = true;
this->close();
}
void MainWindow::showFromTray()
{
this->show();
this->activateWindow();
cal->setFocus();
openAction->setEnabled(false);
}
void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
switch(reason)
{
case QSystemTrayIcon::Trigger:
if(!this->isVisible())
{
this->showFromTray();
}
break;
default:
break;
}
}
void MainWindow::showTrayMessage()
{
static int noteIndex = -1;
static std::unique_ptr<QList<Note*>> noteList;
trayTimer->stop();
if(noteIndex < 0)
{
noteList.reset(notes->getNotificationsFromDate(QDate::currentDate()).release());
if(!noteList->isEmpty())
{
noteIndex = 0;
}
else
{
if(QObject::sender() == notificationsAction)
trayIcon->showMessage("Note Keeper", "No notifications today", QSystemTrayIcon::Information, trayTimer->interval());
}
}
if(noteIndex >= 0)
{
if(noteIndex < noteList->size())
{
Note* note = noteList->at(noteIndex);
QString Title = note->date.toString(settings->dateFormat);
qint64 days = QDate::currentDate().daysTo(note->date);
switch(days)
{
case 0:
Title += " (Today) ";
break;
case 1:
Title += " (in "+QString::number(days)+" day):";
break;
default:
Title += " (in "+QString::number(days)+" days):";
break;
}
trayIcon->showMessage(Title, note->text, QSystemTrayIcon::Information, trayTimer->interval());
trayTimer->start();
++noteIndex;
}
else
{
trayIcon->hide();
trayIcon->show();
noteIndex = -1;
}
}
}
void MainWindow::openSettingsWindow()
{
SettingsWindow *window = new SettingsWindow(settings);
window->setWindowFlags(window->windowFlags() | Qt::MSWindowsFixedSizeDialogHint);
window->setWindowModality(Qt::ApplicationModal);
window->setAttribute(Qt::WA_DeleteOnClose);
connect(window, SIGNAL(dateFormatChanged()), this, SLOT(showNotes()));
connect(window, SIGNAL(dateFormatChanged()), this, SLOT(showClosestNote()));
connect(window, SIGNAL(rDisplayChanged()), this, SLOT(showNotes()));
window->loadSettings();
window->show();
}
void MainWindow::openAboutWindow()
{
QWidget *about = new QWidget;
QLabel *icon = new QLabel;
icon->setPixmap(QIcon(":/images/icon").pixmap(64,64));
QLabel *text = new QLabel("Note Keeper ver. 1.0\n\nMade by Fedor Rebenkov");
QFont font;
font.setPointSize(10);
text->setFont(font);
QPushButton *close = new QPushButton("Close");
QVBoxLayout *layout = new QVBoxLayout;
QHBoxLayout *textIcon = new QHBoxLayout;
textIcon->addWidget(icon);
textIcon->addWidget(text);
layout->addLayout(textIcon);
layout->addWidget(close,0,Qt::AlignRight);
connect(close, SIGNAL(clicked()), about, SLOT(close()));
about->setLayout(layout);
about->setWindowTitle("About Note Keeper");
about->setAttribute(Qt::WA_DeleteOnClose);
about->setWindowFlags(about->windowFlags() | Qt::MSWindowsFixedSizeDialogHint);
about->setWindowModality(Qt::ApplicationModal);
about->show();
int aw = about->width();
int ah = about->height();
int ww = this->width();
int wh = this->height();
about->move(ww/2 - aw/2 + this->x(), wh/2 - ah/2 + this->y());
}
void MainWindow::openAllNotesWindow()
{
NoteListWindow *window = new NoteListWindow(notes, settings);
window->setAttribute(Qt::WA_DeleteOnClose);
connect(window, SIGNAL(editNote(Note*const)), this, SLOT(openEditWindow(Note*const)));
connect(window, SIGNAL(deleteNote(Note*const)), this, SLOT(deleteNote(Note*const)));
connect(this, SIGNAL(noteDeleted()), window, SLOT(deleteItem()));
connect(this, SIGNAL(noteEdited()), window, SLOT(updateItem()));
window->show();
}
void MainWindow::setChanged()
{
isChanged = true;
}
|
// BEGIN CUT HERE
// PROBLEM STATEMENT
// Return the smallest positive integer that has exactly k
// divisors. If this number is greater than 1018, return -1
// instead.
//
// DEFINITION
// Class:NumberOfDivisors
// Method:smallestNumber
// Parameters:int
// Returns:long long
// Method signature:long long smallestNumber(int k)
//
//
// CONSTRAINTS
// -k will be between 1 and 50000, inclusive.
//
//
// EXAMPLES
//
// 0)
// 1
//
// Returns: 1
//
//
//
// 1)
// 2
//
// Returns: 2
//
//
//
// 2)
// 6
//
// Returns: 12
//
// The 6 divisors of 12 are: 1, 2, 3, 4, 6, 12.
//
// END CUT HERE
#line 44 "NumberOfDivisors.cpp"
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <functional>
#include <map>
#include <set>
#include <cassert>
#include <list>
#include <deque>
#include <iomanip>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <cctype>
using namespace std;
#define fi(n) for(int i=0;i<(n);i++)
#define fj(n) for(int j=0;j<(n);j++)
#define f(i,a,b) for(int (i)=(a);(i)<(b);(i)++)
typedef vector <int> VI;
typedef vector <string> VS;
typedef vector <VI> VVI;
typedef long long ll;
int div(ll no) {
int ret = 0;
ll s = sqrt(no);
if ((s+1) * (s+1) == no) {
s++;
}
f(i,1,s+1) {
if (no%i == 0) ret+=2;
}
ret -= (s *s == no);
return ret;
}
class NumberOfDivisors
{
public:
long long smallestNumber(int k)
{
ll n = 1;
while (1) {
if (div(n) == k) {
cout << n << endl;
break;
}
++n;
}
return n;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const long long &Expected, const long long &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arg0 = 12; long long Arg1 = 1LL; verify_case(0, Arg1, smallestNumber(Arg0)); }
void test_case_1() { int Arg0 = 14; long long Arg1 = 2LL; verify_case(1, Arg1, smallestNumber(Arg0)); }
void test_case_2() { int Arg0 = 16; long long Arg1 = 12LL; verify_case(2, Arg1, smallestNumber(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
NumberOfDivisors ___test;
___test.run_test(-1);
}
// END CUT HERE
|
#include "Upgrade.h"
#include "UnitType.h"
#include "Race.h"
#include "..\EnumMapping.h"
#include "..\Util.h"
using namespace BroodWar;
namespace BroodWar
{
namespace Api
{
Upgrade^ ConvertUpgrade(BWAPI::UpgradeType upgrade)
{
return gcnew Upgrade(upgrade);
}
BWAPI::UpgradeType ConvertUpgrade(Upgrade^ upgrade)
{
if(upgrade == nullptr)
return BWAPI::UpgradeType();
return BWAPI::UpgradeType(*(upgrade->instance));
}
BWAPI::UpgradeType ConvertUpgrade(Enum::UpgradeType upgrade)
{
return EnumMapping::UpgradeType->Native(upgrade);
}
Upgrade::Upgrade(Api::Enum::UpgradeType type)
{
instance = EnumMapping::UpgradeType->NativePointer(type);
dispose = true;
}
Upgrade::Upgrade(BWAPI::UpgradeType* type)
{
instance = type;
dispose = false;
}
Upgrade::Upgrade(BWAPI::UpgradeType type)
{
instance = new BWAPI::UpgradeType(type);
dispose = true;
}
Upgrade::~Upgrade()
{
if(dispose)
delete instance;
}
Upgrade::!Upgrade()
{
if(dispose)
delete instance;
}
Upgrade::Upgrade()
{
instance = new BWAPI::UpgradeType();
dispose = true;
}
Upgrade::Upgrade(int id)
{
instance = new BWAPI::UpgradeType(id);
dispose = true;
}
int Upgrade::Id::get()
{
return instance->getID();
}
Api::Enum::UpgradeType Upgrade::Type::get()
{
return EnumMapping::UpgradeType->Managed(instance);
}
bool Upgrade::TypeEquals(Api::Enum::UpgradeType type)
{
return Type == type;
}
Api::Race^ Upgrade::Race::get()
{
return ConvertRace(instance->getRace());
}
int Upgrade::MineralPrice(int level)
{
return instance->mineralPrice(level);
}
int Upgrade::MineralPriceFactor::get()
{
return instance->mineralPriceFactor();
}
int Upgrade::GasPrice(int level)
{
return instance->gasPrice(level);
}
int Upgrade::GasPriceFactor::get()
{
return instance->gasPriceFactor();
}
int Upgrade::UpgradeTime(int level)
{
return instance->upgradeTime(level);
}
int Upgrade::UpgradeTimeFactor::get()
{
return instance->upgradeTimeFactor();
}
int Upgrade::MaxRepeats::get()
{
return instance->maxRepeats();
}
Api::UnitType^ Upgrade::WhatUpgrades::get()
{
return ConvertUnitType(instance->whatUpgrades());
}
Api::UnitType^ Upgrade::WhatsRequired(int level)
{
return ConvertUnitType(instance->whatsRequired(level));
}
HashSet<Api::UnitType^>^ Upgrade::WhatUses::get()
{
return ToHashSet<BWAPI::UnitType, Api::UnitType^>(instance->whatUses(), &ConvertUnitType);
}
int Upgrade::GetHashCode()
{
return instance->getID();
}
bool Upgrade::Equals(Object^ o)
{
Upgrade^ other = dynamic_cast<Upgrade^>(o);
return this->Equals(other);
}
bool Upgrade::Equals(Upgrade^ other)
{
if(ReferenceEquals(nullptr, other))
return false;
if(ReferenceEquals(this, other))
return true;
return this->instance->getID() == other->instance->getID();
}
List<Upgrade^>^ Upgrade::AllUpgrades::get()
{
return ToList<BWAPI::UpgradeType, Upgrade^>(BWAPI::UpgradeTypes::allUpgradeTypes(), &ConvertUpgrade);
}
bool Upgrade::operator == (Upgrade^ first, Upgrade^ second)
{
if(ReferenceEquals(first, second))
return true;
if(ReferenceEquals(nullptr, first))
return false;
return first->Equals(second);
}
bool Upgrade::operator != (Upgrade^ first, Upgrade^ second)
{
return !(first == second);
}
}
}
|
// Copyright (c) 2007-2021 Hartmut Kaiser
//
// SPDX-License-Identifier: BSL-1.0
// 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)
#pragma once
#include <pika/config.hpp>
#include <pika/futures/traits/future_traits.hpp>
#include <pika/memory/intrusive_ptr.hpp>
#include <pika/type_support/unused.hpp>
#include <type_traits>
#include <utility>
#include <vector>
namespace pika {
template <typename R>
class future;
template <typename R>
class shared_future;
namespace lcos::detail {
template <typename Result>
struct future_data_base;
} // namespace lcos::detail
} // namespace pika
namespace pika::traits {
///////////////////////////////////////////////////////////////////////////
namespace detail {
struct future_data_void
{
};
///////////////////////////////////////////////////////////////////////
template <typename Result>
struct shared_state_ptr_result
{
using type = Result;
};
template <typename Result>
struct shared_state_ptr_result<Result&>
{
using type = Result&;
};
template <>
struct shared_state_ptr_result<void>
{
using type = future_data_void;
};
template <typename Future>
using shared_state_ptr_result_t = typename shared_state_ptr_result<Future>::type;
///////////////////////////////////////////////////////////////////////
template <typename R>
struct shared_state_ptr
{
using result_type = shared_state_ptr_result_t<R>;
using type = pika::intrusive_ptr<lcos::detail::future_data_base<result_type>>;
};
template <typename Future>
using shared_state_ptr_t = typename shared_state_ptr<Future>::type;
///////////////////////////////////////////////////////////////////////
template <typename Future, typename Enable = void>
struct shared_state_ptr_for : shared_state_ptr<typename traits::future_traits<Future>::type>
{
};
template <typename Future>
struct shared_state_ptr_for<Future const> : shared_state_ptr_for<Future>
{
};
template <typename Future>
struct shared_state_ptr_for<Future&> : shared_state_ptr_for<Future>
{
};
template <typename Future>
struct shared_state_ptr_for<Future&&> : shared_state_ptr_for<Future>
{
};
template <typename Future>
struct shared_state_ptr_for<std::vector<Future>>
{
using type = std::vector<typename shared_state_ptr_for<Future>::type>;
};
template <typename Future>
using shared_state_ptr_for_t = typename shared_state_ptr_for<Future>::type;
///////////////////////////////////////////////////////////////////////
template <typename SharedState, typename Allocator>
struct shared_state_allocator;
} // namespace detail
///////////////////////////////////////////////////////////////////////////
template <typename T, typename Enable = void>
struct is_shared_state : std::false_type
{
};
template <typename R>
struct is_shared_state<pika::intrusive_ptr<lcos::detail::future_data_base<R>>> : std::true_type
{
};
template <typename R>
inline constexpr bool is_shared_state_v = is_shared_state<R>::value;
///////////////////////////////////////////////////////////////////////////
namespace detail {
template <typename T, typename Enable = void>
struct future_access_customization_point;
}
template <typename T>
struct future_access : detail::future_access_customization_point<T>
{
};
template <typename R>
struct future_access<pika::future<R>>
{
template <typename SharedState>
static pika::future<R> create(pika::intrusive_ptr<SharedState> const& shared_state)
{
return pika::future<R>(shared_state);
}
template <typename T = void>
static pika::future<R>
create(detail::shared_state_ptr_for_t<pika::future<pika::future<R>>> const& shared_state)
{
return pika::future<pika::future<R>>(shared_state);
}
template <typename SharedState>
static pika::future<R> create(pika::intrusive_ptr<SharedState>&& shared_state)
{
return pika::future<R>(PIKA_MOVE(shared_state));
}
template <typename T = void>
static pika::future<R>
create(detail::shared_state_ptr_for_t<pika::future<pika::future<R>>>&& shared_state)
{
return pika::future<pika::future<R>>(PIKA_MOVE(shared_state));
}
template <typename SharedState>
static pika::future<R> create(SharedState* shared_state, bool addref = true)
{
return pika::future<R>(pika::intrusive_ptr<SharedState>(shared_state, addref));
}
PIKA_FORCEINLINE static traits::detail::shared_state_ptr_t<R> const& get_shared_state(
pika::future<R> const& f)
{
return f.shared_state_;
}
PIKA_FORCEINLINE static typename traits::detail::shared_state_ptr_t<R>::element_type*
detach_shared_state(pika::future<R>&& f)
{
return f.shared_state_.detach();
}
private:
template <typename Destination>
PIKA_FORCEINLINE static void
transfer_result_impl(pika::future<R>&& src, Destination& dest, std::false_type)
{
dest.set_value(src.get());
}
template <typename Destination>
PIKA_FORCEINLINE static void
transfer_result_impl(pika::future<R>&& src, Destination& dest, std::true_type)
{
src.get();
dest.set_value(util::detail::unused);
}
public:
template <typename Destination>
PIKA_FORCEINLINE static void transfer_result(pika::future<R>&& src, Destination& dest)
{
transfer_result_impl(PIKA_MOVE(src), dest, std::is_void<R>{});
}
};
template <typename R>
struct future_access<pika::shared_future<R>>
{
template <typename SharedState>
static pika::shared_future<R> create(pika::intrusive_ptr<SharedState> const& shared_state)
{
return pika::shared_future<R>(shared_state);
}
template <typename T = void>
static pika::shared_future<R>
create(detail::shared_state_ptr_for_t<pika::shared_future<pika::future<R>>> const&
shared_state)
{
return pika::shared_future<pika::future<R>>(shared_state);
}
template <typename SharedState>
static pika::shared_future<R> create(pika::intrusive_ptr<SharedState>&& shared_state)
{
return pika::shared_future<R>(PIKA_MOVE(shared_state));
}
template <typename T = void>
static pika::shared_future<R>
create(detail::shared_state_ptr_for_t<pika::shared_future<pika::future<R>>>&& shared_state)
{
return pika::shared_future<pika::future<R>>(PIKA_MOVE(shared_state));
}
template <typename SharedState>
static pika::shared_future<R> create(SharedState* shared_state, bool addref = true)
{
return pika::shared_future<R>(pika::intrusive_ptr<SharedState>(shared_state, addref));
}
PIKA_FORCEINLINE static traits::detail::shared_state_ptr_t<R> const& get_shared_state(
pika::shared_future<R> const& f)
{
return f.shared_state_;
}
PIKA_FORCEINLINE static typename traits::detail::shared_state_ptr_t<R>::element_type*
detach_shared_state(pika::shared_future<R> const& f)
{
return f.shared_state_.get();
}
private:
template <typename Destination>
PIKA_FORCEINLINE static void
transfer_result_impl(pika::shared_future<R>&& src, Destination& dest, std::false_type)
{
dest.set_value(src.get());
}
template <typename Destination>
PIKA_FORCEINLINE static void
transfer_result_impl(pika::shared_future<R>&& src, Destination& dest, std::true_type)
{
src.get();
dest.set_value(util::detail::unused);
}
public:
template <typename Destination>
PIKA_FORCEINLINE static void
transfer_result(pika::shared_future<R>&& src, Destination& dest)
{
transfer_result_impl(PIKA_MOVE(src), dest, std::is_void<R>{});
}
};
///////////////////////////////////////////////////////////////////////////
template <typename SharedState, typename Allocator>
struct shared_state_allocator : detail::shared_state_allocator<SharedState, Allocator>
{
};
template <typename SharedState, typename Allocator>
using shared_state_allocator_t = typename shared_state_allocator<SharedState, Allocator>::type;
} // namespace pika::traits
|
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
long long _count;
class graph
{
public:
int v;
list<int> *adj;
graph(int v)
{
this->v = v;
adj = new list<int>[v];
}
void dfs(int v, bool visited[])
{
_count++;
visited[v] = 1;
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); i++)
{
if (!visited[*i])
{
dfs(*i, visited);
}
}
}
void addEdge(int v, int w)
{
adj[v].push_back(w);
adj[w].push_back(v);
}
};
int main()
{
long long t, n, m, lib, road, city1, city2, ans;
cin >> t;
for (int i = 0; i < t; i++)
{
cin >> n >> m >> lib >> road;
if (lib > road)
{
bool visited[n];
for (int j = 0; j < n; j++)
visited[j] = 0;
graph g(n);
ans = 0;
for (int j = 0; j < m; j++)
{
cin >> city1 >> city2;
g.addEdge(city1 - 1, city2 - 1);
}
for (int j = 0; j < n; j++)
{
_count = 0;
if (!visited[j])
{
g.dfs(j, visited);
ans += ((_count - 1) * road + lib); //in each component one library
//and all roads are sufficient && count - 1 because 2 cities 1 road
}
}
cout << ans << endl;
}
else
{
for (int j = 0; j < m; j++) //temporary no use
cin >> city1 >> city2;
cout << n * lib << endl;
}
}
}
|
////////////INCLUDE COLOUR CODE///////////////////
#ifndef _COLORS_
#define _COLORS_
#define RST "\x1B[0m"
#define KRED "\x1B[31m"
#define KGRN "\x1B[32m"
#define KYEL "\x1B[33m"
#define KBLU "\x1B[34m"
#define KMAG "\x1B[35m"
#define KCYN "\x1B[36m"
#define KWHT "\x1B[37m"
#define FRED(x) KRED x RST
#define FGRN(x) KGRN x RST
#define FYEL(x) KYEL x RST
#define FBLU(x) KBLU x RST
#define FMAG(x) KMAG x RST
#define FCYN(x) KCYN x RST
#define FWHT(x) KWHT x RST
#define BOLD(x) "\x1B[1m" x RST
#define UNDL(x) "\x1B[4m" x RST
#endif /* _COLORS_ */
/////////////END OF INCLUDE COLOR CODE////////////////////
#include "cryptopp/secblock.h"
#include "cryptopp/sha.h"
#include "cryptopp/cryptlib.h"
#include "cryptopp/hex.h"
#include "cryptopp/modes.h"
#include "cryptopp/osrng.h"
#include "cryptopp/base64.h"
#include <cryptopp/hex.h>
#include "cryptopp/rsa.h"
#include <cryptopp/files.h>
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <fstream>
#include "cryptopp/seed.h"
#include "cryptopp/hex.h"
#include "cryptopp/modes.h"
#include "cryptopp/osrng.h"
#include "cryptopp/base64.h"
///////////////////END OF INCLUDE LIBRARY////////////////////////////
using namespace std;
using namespace CryptoPP;
using namespace CryptoPP;
using namespace std;
void Save(const string& filename, const BufferedTransformation& bt);
void SaveHex(const string& filename, const BufferedTransformation& bt);
void SaveHexPrivateKey(const string& filename, const PrivateKey& key);
void SaveHexPublicKey(const string& filename, const PublicKey& key);
void sendpacket(int new_socket,string message);
string received_dummy;
int socket()
{
cout<<"Enter Server IP ADDRESS"<<endl;
string ip;
cin>>ip;
int PORT;
do{
cout<<"Enter port number"<<endl;
cin>>PORT;
if(PORT > 65535 || PORT <1)
{
cout<<"are you dumb ? the port range is \"0 - 65535\" "<<endl;
}
}while(PORT > 65535 || PORT < 1);
int sock = 0, valread;
struct sockaddr_in serv_addr;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
exit(0);
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from text to binary form
if(inet_pton(AF_INET, ip.c_str(), &serv_addr.sin_addr)<=0)
{
printf("\nInvalid address/ Address not supported \n");
exit(0);
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\nConnection Failed \n");
exit(0);
return -1;
}
return sock;
}
void verify(string a, string b)
{
int result = strcmp(a.c_str(), b.c_str());
cout<<"Comparing the strings"<<endl;
if(result==0)
{
cout<<BOLD(FRED("Verified"));
}
else
{
cout<<a<<endl;
cout<<b<<endl;
cout<<BOLD(FRED("NOT MATCH!"))<<endl;
exit(0);
}
}
void keyGen()
{
AutoSeededRandomPool rng;
InvertibleRSAFunction privkey;
privkey.Initialize(rng, 1024);
// Generate Private Key
RSA::PrivateKey privateKey;
privateKey.GenerateRandomWithKeySize(rng, 1024);
// Generate Public Key
RSA::PublicKey publicKey;
publicKey.AssignFrom(privateKey);
system("rm -rf client_file");
system("mkdir client_file");
SaveHexPublicKey("client_file/client_publickey.txt", publicKey);
SaveHexPrivateKey("client_file/client_privatekey.txt", privateKey);
}
void Print(const std::string& label, const std::string& val)
{
std::string encoded;
StringSource(val, true,
new HexEncoder(
new StringSink(encoded)
) // HexEncoder
); // StringSource
std::cout << label << ": " << encoded << std::endl;
}
string grabfilecontent(string filename)
{
string inputdata,totaldata;
ifstream file (filename);
if (file.is_open())
{
int counter=0;
while(getline (file,inputdata))
{
totaldata=totaldata+inputdata+"\n";
}
file.close();
return totaldata;
}
}
void SaveContent(string content, string filename)
{
ofstream file;
file.open (filename);
file << content;
file.close();
}
string grabprivatekey(string filename)
{
string inputdata,totaldata;
ifstream file (filename);
if (file.is_open())
{
getline (file,inputdata);
file.close();
return inputdata;
}
}
string sha1string(string haha)
{
string digest="";
CryptoPP::SHA1 sha1;
CryptoPP::StringSource(haha, true, new CryptoPP::HashFilter(sha1, new CryptoPP::HexEncoder(new CryptoPP::StringSink(digest))));
return digest;
}
//code from stackoverflow
//https://stackoverflow.com/questions/29050575/how-would-i-load-a-private-public-key-from-a-string-byte-array-or-any-other
void Save(const string& filename, const BufferedTransformation& bt)
{
FileSink file(filename.c_str());
bt.CopyTo(file);
file.MessageEnd();
}
void SaveHex(const string& filename, const BufferedTransformation& bt)
{
HexEncoder encoder;
bt.CopyTo(encoder);
encoder.MessageEnd();
Save(filename, encoder);
}
void SaveHexPrivateKey(const string& filename, const PrivateKey& key)
{
ByteQueue queue;
key.Save(queue);
SaveHex(filename, queue);
}
void SaveHexPublicKey(const string& filename, const PublicKey& key)
{
ByteQueue queue;
key.Save(queue);
SaveHex(filename, queue);
}
string Decryption_PKI(string encryptedcontent,string privKey,string title)
{
AutoSeededRandomPool rng;
InvertibleRSAFunction parameters;
parameters.GenerateRandomWithKeySize(rng,1024);
RSA::PrivateKey privateKey(parameters);
string decodedPrivKey;
////Load Private Key
StringSource ss2(privKey,true,(new HexDecoder( new StringSink(decodedPrivKey)))); //decode the privkey from hex to symbol stuff
StringSource PrivKeySS(decodedPrivKey,true); //load it into bytes
privateKey.Load(PrivKeySS); //load the private key
RSAES_OAEP_SHA_Decryptor d(privateKey);
string plaintext;
StringSource ss3(encryptedcontent ,true,(new HexDecoder (new PK_DecryptorFilter(rng, d, (new StringSink(plaintext))))));
cout<<"---------------------------------Decryption is in progress-------------------"<<endl;
cout<<BOLD(FRED("[ **"<< title <<" found* ]"));
cout<<plaintext<<" |"<<" SHA-1 :";
cout<<sha1string(plaintext)<<endl;
cout<<"---------------------------------Process of decryption is completed-----------"<<endl<<endl;
return plaintext;
}
string send_recv(int socket, string message, string comments)
{
int valread;
char buffer[1024] = {0};
send(socket , message.c_str() , strlen(message.c_str())+1 , 0 );
cout<<"[ Successfully send to Server ] "<<comments<<endl;
valread = read(socket , buffer, 1024);
cout<<"[ Incoming message from server ] : ";
printf("%s\n",buffer );
return buffer;
}
string recv_send(int new_socket, string message, string comments)
{
int valread;
char buffer[1024] = {0};
valread = read( new_socket , buffer, 1024);
cout<<"[ Incoming message from server ] : "<<buffer<<endl;
send(new_socket , message.c_str() , strlen(message.c_str())+1 , 0 );
cout<<"[ Details ] "<<comments<<endl;
return buffer;
}
string convertToString(char* a, int size)
{
int i;
string s = "";
for (i = 0; i < size; i++) {
s = s + a[i];
}
return s;
}
string receivedummy(int new_socket)
{
char buffer[1024] = {0};
string compare;
int valread = read( new_socket , buffer, 1024);
int b_size = sizeof(buffer) / sizeof(char);
string s_b = convertToString(buffer, b_size);
received_dummy=s_b;
return s_b;
}
void sendpacket(int new_socket,string message)
{
send(new_socket , message.c_str() , strlen(message.c_str())+1 , 0 );
}
void AES_Encryption(string temp, string AESiv, string AESkey,int socket,bool haha)
{
string plain;
if(haha==false)
{
plain = temp;
}
else
{
do
{
cout<<"Enter message send to server"<<endl;
std::getline(std::cin, plain);
if(plain.size()>1024)
{
cout<<BOLD(FRED("Message is exceed the length"))<<endl;
}
}while(plain.size()>1024);
}
string recovered;
AutoSeededRandomPool prng;
string decodedkey,decodediv;
StringSource s(AESkey, true,(new HexDecoder(
new StringSink(decodedkey))
) // StreamTransformationFilter
); // StringSource
StringSource ss(AESiv, true,(new HexDecoder(
new StringSink(decodediv))
) // StreamTransformationFilter
); // StringSource
SecByteBlock key((const byte*)decodedkey.data(), decodedkey.size());
SecByteBlock iv((const byte*)decodediv.data(), decodediv.size());
string cipher,encoded;
/*********************************\
\*********************************/
try
{
cout << "plain text: " << plain << endl;
CFB_Mode<AES>::Encryption e;
e.SetKeyWithIV(key, sizeof(key), iv);
// CFB mode must not use padding. Specifying
// a scheme will result in an exception
StringSource(plain, true,
new StreamTransformationFilter(e,
new StringSink(cipher)) // StreamTransformationFilter
); // StringSource
}
catch (const CryptoPP::Exception &e)
{
cerr << e.what() << endl;
exit(1);
}
/*********************************\
\*********************************/
// Pretty print
encoded.clear();
StringSource(cipher, true,
new HexEncoder( new StringSink(encoded)
) // HexEncoder
); // StringSource
cout << "cipher text: " << encoded << endl;
cout<<"encoded length:" << encoded.length()<<endl;
if(haha==false)
{
send_recv(socket,encoded , "Client send \"Received\" to Server");
}
else
{
sendpacket(socket,encoded);
}
if(plain=="quit")
{
cout<<FRED(BOLD("PROGRAM TERMINAL GRACEFULLY"))<<endl;
exit(1);
}
}
string AES_Decryption(string cipher,string AESiv,string AESkey, int socket,bool haha)
{
AutoSeededRandomPool prng;
string decodedkey,decodediv;
StringSource s(AESkey, true,(new HexDecoder(
new StringSink(decodedkey))
) // StreamTransformationFilter
); // StringSource if(haha==false)
StringSource ss(AESiv, true,(new HexDecoder(
new StringSink(decodediv))
) // StreamTransformationFilter
); // StringSource
SecByteBlock key((const byte*)decodedkey.data(), decodedkey.size());
SecByteBlock iv((const byte*)decodediv.data(), decodediv.size());
if(haha==false)
{
cipher=recv_send(socket,"Client responed \"Received Ready\"", "Acknowledge send from Client");
// sendpacket(socket,"Client responed \"Received Ready\"");
}
else
{
int valread;
char buffer[1024] = {0};
string compare;
valread = read(socket , buffer, 1024);
cipher=buffer;
}
cout<<"Cipher Text : "<<cipher<<endl;
string rawcipher;
StringSource ss2(cipher, true,
new HexDecoder(
new StringSink(rawcipher)
) // HexEncoder
); // StringSource
string recovered;
try
{
CFB_Mode<AES>::Decryption d;
d.SetKeyWithIV(key, sizeof(key), iv);
// The StreamTransformationFilter removes
// padding as required.
StringSource s(rawcipher, true,
new StreamTransformationFilter(d,
new StringSink(recovered)) // StreamTransformationFilter
);
cout << FCYN(BOLD("Message Received: " << recovered<<""))<< endl;
if(recovered=="quit")
{
cout<<FRED(BOLD("PROGRAM TERMINAL GRACEFULLY"))<<endl;
exit(1);
}
}
catch (const CryptoPP::Exception &e)
{
cerr << e.what() << endl;
exit(1);
}
/*********************************\
\*********************************/
if(haha==false)
{
verify("Ready",recovered);
cout<<FGRN(BOLD("\nReady Recevied"))<<endl;
}
return recovered;
}
string NewAES(string value,string title){
string tmp,reverse;
cout<<"[OLD] ["<<title<<"] :"<<value<<endl;
for(int i=0; i <= value.length();i++)
{
tmp[i]=value[value.length()-i];
reverse= reverse+tmp[i];
}
cout<<"[NEW] ["<<title<<"] :"<<reverse<<endl<<endl;
return reverse;
}
int main()
{
int sock=socket(),valread;
char buffer[1024] = {0};
string receive="Received Winked From Client";
cout<<FRED(BOLD("[System] RSA Key is generating"))<<endl;
cout<<FRED(BOLD("---------------------Sending Public-Key and Checksum---------------------"))<<endl;
keyGen();
string privatekey=grabprivatekey("client_file/client_privatekey.txt");
string encoded;
StringSource ss(privatekey,true,
new Base64Encoder(
new StringSink(encoded)
) // Base64Encoder
); // StringSource
cout << "Private Key for Client in Base64"<<endl;
cout<<"----BEGIN RSA PRIVATE KEY----"<<endl;
cout << encoded;
cout<<"----END RSA PRIVATE KEY----\n"<<endl;
encoded= "";
string publickey=grabfilecontent("client_file/client_publickey.txt");
StringSource sss(publickey, true,
new Base64Encoder(
new StringSink(encoded)
) // Base64Encoder
); // StringSource
cout<<"----BEGIN PUBLIC KEY----"<<endl;
cout << encoded;
cout<<"----END PUBLIC KEY----\n"<<endl;
cout<<FRED(BOLD("Value of Public Key in Hex format"))<<endl;
cout<<publickey<<endl;
send_recv(sock, publickey, "Public Key have sent");
string publicmd5=sha1string(grabfilecontent("client_file/client_publickey.txt"));
cout<<FRED(BOLD("\n[SHA -1 ]PUBLIC KEY : "));
cout<<publicmd5<<"\n"<<endl;
send_recv(sock, publicmd5, "Hash value \"SHA - 1\" of public key sent");
cout<<"Waiting Integerity Verified from Server"<<endl;
string dummy="serene";
sendpacket(sock,dummy); // send 1 dummy value to balance it
cout<<"We recevied a response from Server"<<endl;
verify("Verified",receivedummy(sock));
cout<<""<<endl;
cout<<FRED(BOLD("\n---------------------Complete sending publickey---------------------"))<<endl;
cout<<FBLU(BOLD("---------------------RECEIVING SERVER PUBLIC KEY---------------------\n\n"));
string message="Send me your public key";
sendpacket(sock,message);
string serverpublickey=recv_send(sock, receive, "Public key from Server");//send received wink
cout<<""<<endl;
SaveContent(serverpublickey,"client_file/received_publickey.txt"); //store server public key
string hashvalue=recv_send(sock, receive, "Hash value from Client"); // send received wink
string contentofpublickeytoverify=grabfilecontent("client_file/received_publickey.txt");
cout<<FBLU(BOLD("[----------------------Received and Verifying the integrity---------------------]"))<<endl;
verify(hashvalue,sha1string(contentofpublickeytoverify));
cout<<"\nHold on, while we're sending our result to Server"<<endl;
receivedummy(sock);
sendpacket(sock,"Verified");
cout<<"Sent"<<endl;
cout<<FRED(BOLD("\n-------------------------------------------------------------------"))<<endl;
cout<<FBLU(BOLD("Receiving Encrypted AES Session Key from Server"))<<endl;
///////////////////////RECEIVE KEY/////////////////////////
string Encrypted_AES_SESS_KEY=recv_send(sock,receive,"Encrypted AES Session Key");
cout<<endl;
string sha1_AES_SESS_KEY=recv_send(sock,receive,"VALUE OF SHA - 1 FROM \"ENCRYPTED\" AES SESSION KEY");
cout<<endl;
string sha1_AES_PLAIN_SESS_KEY=recv_send(sock,receive,"VALUE OF SHA - 1 FROM \"PLAIN\" AES SESSION KEY");
cout<<endl;
///////////////////////////////////////////////////////
cout<<FBLU(BOLD("Receiving Encrypted AES IV from Server"))<<endl;
///////////////////////RECEIVE IV////////////////////
string Encrypted_AES_IV=recv_send(sock,receive,"Encrypted AES IV");
cout<<endl;
string sha1_AES_IV=recv_send(sock,receive,"SHA - 1 FROM \"ENCRYPTED\"AES IV");
cout<<endl;
string sha1_PLAIN_AES_IV=recv_send(sock,receive,"SHA - 1 FROM \"PLAIN\"AES IV");
cout<<endl;
/////////////////////////////////////////////////////
cout<<"Verifying the Intergrity of recieved content"<<endl;
cout<<"Verifiying integrity of Encrypted AES Session"<<endl;
verify(sha1_AES_SESS_KEY,sha1string(Encrypted_AES_SESS_KEY));
///VERFIYING ENCRYPTED AES IV
cout<<"\nVerifiying integrity of Encrypted AES IV"<<endl;
verify(sha1_AES_IV,sha1string(Encrypted_AES_IV));
cout<<endl;
cout<<FBLU(BOLD("Process of verifying is almost complete, 20% remaining left"))<<endl;
///START DECRYPT VERIFYING THE DECRYPTED HASH
cout<<"\nProcess of decryption is running and \"Verifying PLAIN's AES SESSION hash\""<<endl<<endl;
string HexSESSION=Decryption_PKI(Encrypted_AES_SESS_KEY,privatekey,"Session Key -->");
verify(sha1string(HexSESSION),sha1_AES_PLAIN_SESS_KEY);
///START DECRYPT IV TO VERIFYING THE DECRYPTED HASH
cout<<"\nProcess of decryption is running to \"Verifying PLAIN's AES IV\""<<endl<<endl;
string HexIV=Decryption_PKI(Encrypted_AES_IV,privatekey," AES IV -->");
verify(sha1string(HexIV),sha1_PLAIN_AES_IV);
cout<<"\nProcess of integrity checking is completed "<<endl<<endl;
cout<<FRED(BOLD("-------------------------------------------------------------------\n\nTRYING TO SEND ACKNOWLEDGE FLAG\n\n-------------------------------------------------------------------"))<<endl;
string nonevalue="";
AES_Encryption("Acknowledge",HexIV,HexSESSION,sock,false);
sendpacket(sock,dummy);
cout<<endl<<endl<<endl;
cout<<FRED(BOLD("-------------------------------------------------------------------\n\nTRYING TO RECEIVE READY FLAG FROM SERVER\n\n-------------------------------------------------------------------"))<<endl;
AES_Decryption(nonevalue,HexIV, HexSESSION, sock,false);
cout<<FMAG(BOLD("\n\n\nRE-CREATE new AES-SESSION KEY & IV"))<<endl;
cout<<FCYN(BOLD("-------------------------------------------------------------------\n\nHANDSHAKE ESTABLISHED\n\n-------------------------------------------------------------------"))<<endl;
string key=NewAES(HexSESSION,"AES-KEY");
string iv=NewAES(HexIV,"AES-IV");
cin.ignore();
do
{
AES_Encryption(nonevalue,iv,key,sock,true);
AES_Decryption(nonevalue,iv,key,sock,true);
}while(true);
}
|
/***************************************************************************
* Copyright (c) 2021, Thorsten Beier * *
* Copyright (c) 2021, QuantStack *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#include <vector>
#include <string>
#include <iostream>
#include "sol/sol.hpp"
#include "xeus-lua/xinterpreter.hpp"
#include "nlohmann/json.hpp"
namespace nl = nlohmann;
namespace xlua
{
void setup_json(
sol::state_view & lua,
interpreter & //interp
)
{
// get display table
sol::table ilua_table = lua["ilua"];
sol::table json_table = ilua_table["json"];
sol::table detail_table = json_table["detail"];
//auto self = &interp;
detail_table.set_function("string_encoder",[](
const std::string & unencoded
){
nl::json j = unencoded;
std::string s = j.dump();
return s;
});
detail_table.set_function("number_encoder",[](
const double & unencoded
){
nl::json j = unencoded;
std::string s = j.dump();
return s;
});
std::string script = R""""(
local is_array
local stringify_encoded_dict
local stringify_encoded_array
local key_to_string
local json_encoder_impl
local table_encoder
is_array = function(t)
local i = 0
for _ in pairs(t) do
i = i + 1
if t[i] == nil then return false end
end
return true
end
stringify_encoded_array = function(t)
return "[" .. table.concat(t, ",") .. "]"
end
stringify_encoded_dict = function(t)
return "{" .. table.concat(t, ",") .. "}"
end
key_to_string = function(key)
if type(key) ~= "string" then
error("json_encoder error: only string keys are allowed" .. type(key))
else
return key
end
end
encode_kv_pair = function(key, value, cycle_detection)
str_key = key_to_string(key)
return json_encoder_impl(str_key, cycle_detection) .. ":" .. json_encoder_impl(value, cycle_detection)
end
table_encoder = function(t, cycle_detection)
if cycle_detection[t] then
error("json_encoder error: detected cyclic reference")
end
cycle_detection[t] = true
local ret = {}
if is_array(t) then
for i, v in ipairs(t) do
table.insert(ret, json_encoder_impl(v, cycle_detection))
end
cycle_detection[t] = false
return stringify_encoded_array(ret)
else
for key,val in pairs(t) do
table.insert(ret, encode_kv_pair(key, val, cycle_detection))
end
cycle_detection[t] = false
return stringify_encoded_dict(ret)
end
end
local encoder_registry = {
boolean = tostring,
string = ilua.json.detail.string_encoder,
number = ilua.json.detail.number_encoder,
table = table_encoder
}
json_encoder_impl = function(object, cycle_detection)
cycle_detection = cycle_detection or {}
local type_of_object = type(object)
local encoder = encoder_registry[type_of_object]
if type_of_object == "table" then
return encoder(object, cycle_detection)
elseif encoder ~=nil then
return encoder(object)
else
error(string.format("cannot json_encode an object of type: %s",type_of_object))
end
end
function ilua.json.encode(object)
local cycle_detection = {}
return json_encoder_impl(object, cycle_detection)
end
)"""";
sol::protected_function_result code_result = lua.safe_script(script, &sol::script_pass_on_error);
if (!code_result.valid()) {
sol::error err = code_result;
std::cerr << "failed to load string-based script into the program for xjson" << err.what() << std::endl;
throw std::runtime_error(err.what());
}
}
}
|
/*********************************************************\
* Copyright (c) 2012-2018 The Unrimp Team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Header guard ]
//[-------------------------------------------------------]
#pragma once
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace Renderer
{
//[-------------------------------------------------------]
//[ Classes ]
//[-------------------------------------------------------]
/**
* @brief
* Abstract log interface
*
* @note
* - The implementation must be multi-threading safe since the renderer is allowed to internally use multiple threads
*/
class ILog
{
//[-------------------------------------------------------]
//[ Public definitions ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Log message type
*/
enum class Type
{
TRACE, ///< Trace
DEBUG, ///< Debug
INFORMATION, ///< Information
WARNING, ///< General warning
PERFORMANCE_WARNING, ///< Performance related warning
COMPATIBILITY_WARNING, ///< Compatibility related warning
CRITICAL ///< Critical
};
//[-------------------------------------------------------]
//[ Public virtual Renderer::ILog methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Print a formatted log message
*
* @param[in] type
* Log message type
* @param[in] attachment
* Optional attachment (for example build shader source code), can be a null pointer
* @param[in] file
* File as ASCII string
* @param[in] line
* Line number
* @param[in] format
* "sprintf"-style formatted UTF-8 log message
*
* @return
* "true" to request debug break, else "false"
*/
virtual bool print(Type type, const char* attachment, const char* file, uint32_t line, const char* format, ...) = 0;
//[-------------------------------------------------------]
//[ Protected methods ]
//[-------------------------------------------------------]
protected:
inline ILog();
inline virtual ~ILog();
explicit ILog(const ILog&) = delete;
ILog& operator=(const ILog&) = delete;
};
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // Renderer
//[-------------------------------------------------------]
//[ Macros & definitions ]
//[-------------------------------------------------------]
/**
* @brief
* Ease-of-use log macro
*
* @param[in] context
* Renderer context to ask for the log interface
* @param[in] type
* Log message type
* @param[in] format
* "sprintf"-style formatted UTF-8 log message
*
* @note
* - Example: RENDERER_LOG(mContext, DEBUG, "Direct3D 11 renderer backend startup")
* - See http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/ - "2. Wrap your macros in do { … } while(0)." for background information about the do-while wrap
*/
#define RENDERER_LOG(context, type, format, ...) \
do \
{ \
if ((context).getLog().print(Renderer::ILog::Type::type, nullptr, __FILE__, static_cast<uint32_t>(__LINE__), format, ##__VA_ARGS__)) \
{ \
DEBUG_BREAK; \
} \
} while (0);
//[-------------------------------------------------------]
//[ Implementation ]
//[-------------------------------------------------------]
#include "Renderer/ILog.inl"
|
#include <stdio.h>
#include<string.h>
#include<algorithm>
#define MAX 1000000000
using namespace std;
struct edge
{
int u,v,w;
};
edge e[250010];
int fa[510];
int m,n;
bool cmp(const edge &p1,const edge &p2)
{
return p1.w<p2.w;
}
int find(int x)
{
int fx,xx;
fx=x;
while(fa[fx]!=fx) fx=fa[fx];
while (x!=fx)
{
xx=fa[x];
fa[x]=fx;
x=xx;
}
return fx;
}
void kru()
{
int x,y;
int ans=-1;
for(int i=1;i<=n;++i)
fa[i]=i;
sort(e+1,e+m+1,cmp);
for(int i=1;i<=m;++i)
{
x=find(e[i].u);
y=find(e[i].v);
if (x!=y)
{
if (e[i].w>ans) ans=e[i].w;
fa[x]=y;
}
}
printf("%d\n",ans);
}
int main()
{
freopen("test.in","r",stdin);
int cs,tm;
scanf("%d",&cs);
while(cs--)
{
scanf("%d",&n);
m=0;
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j)
{
scanf("%d",&tm);
e[++m].u=i;e[m].v=j;e[m].w=tm;
e[++m].u=j;e[m].v=i;e[m].w=tm;
}
kru();
}
return 0;
}
|
#include "App.h"
#include <string>
#include <iostream>
#include "Magazine.h"
#include "Book.h"
#include "Schoolbook.h"
using namespace std;
Command App::string_to_command(string command)
{
if (command == "printAll")
{
return PRINT_ALL;
}
if (command == "add")
{
return ADD_PUBLICATION;
}
if (command == "delete")
{
return DELETE_PUBLICATION;
}
if (command == "printOne")
{
return PRINT_ONE;
}
if (command == "count")
{
return COUNT;
}
if (command == "help")
{
return HELP;
}
if (command == "exit")
{
return EXIT;
}
return NO_COMMAND;
}
Publication_type App::string_to_publication_type(std::string type)
{
if (type == "magazine")
{
return MAGAZINE;
}
if (type == "book")
{
return BOOK;
}
if (type == "schoolbook")
{
return SCHOOLBOOK;
}
return NO_TYPE;
}
App::App()
{
char* name = new char[]{ "Publisher name" };
publisher = new Publisher(name);
delete[] name;
}
App::~App() {
delete publisher;
}
void App::execute()
{
string command_from_input;
Command command = NO_COMMAND;
while (command != EXIT)
{
cin >> command_from_input;
command = string_to_command(command_from_input);
switch (command)
{
case PRINT_ALL:
print_all();
break;
case ADD_PUBLICATION:
add_publication();
break;
case DELETE_PUBLICATION:
delete_publication();
break;
case PRINT_ONE:
print_one();
break;
case COUNT:
count();
break;
case HELP:
help();
break;
case NO_COMMAND:
cout << "There is no such command, to see available commands enter \"help\"" << endl;
break;
}
}
}
void App::print_all()
{
publisher->print_publisher_information();
}
void App::add_publication()
{
string type_from_input;
cin >> type_from_input;
Publication_type type = string_to_publication_type(type_from_input);
char* a_name = new char[20];
int a_year;
int a_month;
char* a_author = new char[20];
int a_grade;
switch (type)
{
case MAGAZINE:
cin >> a_name;
cin >> a_year;
cin >> a_month;
publisher->add_publication(new Magazine(a_name, a_year, a_month));
break;
case BOOK:
cin >> a_name;
cin >> a_year;
cin >> a_author;
publisher->add_publication(new Book(a_name, a_year, a_author));
break;
case SCHOOLBOOK:
cin >> a_name;
cin >> a_year;
cin >> a_author;
cin >> a_grade;
publisher->add_publication(new Schoolbook(a_name, a_year, a_author, a_grade));
break;
case NO_TYPE:
cout << "There is no such type" << endl;
break;
}
delete[] a_author;
delete[] a_name;
}
void App::delete_publication()
{
int number;
cin >> number;
publisher->remove_and_delete_publication(publisher->get_by_number(number));
}
void App::print_one()
{
int number;
cin >> number;
Print_publication::print(publisher->get_by_number(number));
}
void App::count()
{
cout << publisher->count() << endl;
}
void App::help()
{
for (string s : HELP_TEXT)
{
cout << s << endl;
}
}
vector<string> App::HELP_TEXT = {
"List and templates of possible commands:",
"----------------------------------------",
"printAll",
"add",
" magazine name(string) year(int) month(int)",
" book name(string) year(int) author(string)",
" schoolbook name(string) year(int) author(string) grade(int)",
"delete number(int)",
"printOne number(int)",
"count",
"exit",
"----------------------------------------",
};
|
#include <iostream>
#include <string>
class Veggie {
public:
Veggie(const std::string& name);
~Veggie();
void tellUs();
protected:
std::string myName;
};
Veggie::Veggie(const std::string& name) {
myName = name;
}
Veggie::~Veggie() {
std::cout << myName << " - good bye!" << std::endl;
}
void Veggie::tellUs() {
std::cout << "I am a(n) '" << myName << "'." << std::endl;
}
typedef enum veggies {
VEGGIE_FIRST = 0,
APPLE,
BANANA,
CHERRY,
DATE,
EGGPLANT,
FIG,
GRAPE,
VEGGIE_LAST
} veggies_t;
typedef struct veggie_table_entry {
veggies_t kind;
Veggie* aVeggie;
} veggie_table_entry_t;
int main() {
veggie_table_entry_t veggies[] = {
{ APPLE, new Veggie("APPLE") },
{ BANANA, new Veggie("BANANA") },
{ CHERRY, new Veggie("CHERRY") },
{ DATE, new Veggie("DATE") },
{ EGGPLANT, new Veggie("EGGPLANT") },
{ FIG, new Veggie("FIG") },
{ GRAPE, new Veggie("GRAPE") }
};
const int vmax = sizeof(veggies) / sizeof(veggie_table_entry_t);
for(int v = 0; v < vmax; v++) {
std::cout << veggies[v].kind << ": ";
veggies[v].aVeggie->tellUs();
delete veggies[v].aVeggie;
}
return 0;
}
|
// Copyright 2019 Erik Teichmann <kontakt.teichmann@gmail.com>
#ifndef TEST_HELPER_HPP_
#define TEST_HELPER_HPP_
#include <vector>
#include <string>
void FillArgv(std::vector<std::string> args, char* argv[]) {
for (unsigned int i = 0; i < args.size(); ++i) {
// simply casting the data like
// argv[i] = const_cast<char*>(args[i].data());
// leads to freeing of args and the char* are dangling pointers
argv[i] = new char[args[i].size()+1];
args[i].copy(argv[i], args[i].size()+1);
argv[i][args[i].size()] = '\0';
}
argv[args.size()+1] = nullptr;
}
#endif // TEST_HELPER_HPP_
|
#include <initializer_list>
#include <iostream>
#ifndef MY_VECTOR_H
#define MY_VECTOR_H
namespace mvec {
using valueType = int;
using sizeType = size_t;
struct Count {
sizeType size;
};
class myVectorIterator;
class myVector
{
public:
// construction & clean-up
myVector(); //default constructor
myVector(Count size); //ordinary constructor
myVector(Count size, valueType defaultValue); //ordinary constructor
myVector(std::initializer_list<valueType>); //initializer list constructor
myVector(const myVector&); //copy constructor
myVector(myVector&&); //move contructor
myVector& operator=(const myVector&); //copy assignment
myVector& operator=(myVector&&); //move assignment
~myVector();
// iterator related
myVectorIterator begin();
myVectorIterator end(); // one past the last element
// comparision
bool operator==(const myVector&) const;
bool operator!=(const myVector&) const;
// index-access
valueType& operator[](sizeType) const;
// operations on the vector
void pop_back();
void push_back(valueType);
void reserve(sizeType); // m_capacity = m_size + <argument>
void resize(sizeType);
void erase(sizeType);
// exploring vector
sizeType size() const;
bool empty() const;
private:
sizeType m_capacity;
valueType* m_data{};
sizeType m_size;
static const sizeType DEFAULT_CAPACITY{ 8 };
friend std::ostream& operator<<(std::ostream&, const myVector&);
};
struct myVectorException {
virtual void what() const {
std::cout << "Vector exception\n";
}
};
struct popOnEmptyVector : public myVectorException {
virtual void what() const {
std::cout << "pop_back() is called on empty vector.\n";
}
};
struct outOfBounds : public myVectorException {
outOfBounds(sizeType index)
: myVectorException(),
m_index{ index }
{}
void what() const {
std::cout << "trying to acces element at positioon "
<< m_index << " which is out of bounds.\n";
}
private:
sizeType m_index;
};
enum iteratorCategories { input, bidirectional, random_access };
class myVectorIterator
{
public:
myVectorIterator() = default;
myVectorIterator(valueType* ptr)
: m_ptr{ ptr }
{}
valueType& operator*()
{
return *m_ptr;
}
valueType& operator[](size_t i)
{
return m_ptr[i];
}
myVectorIterator& operator++()
{
if (!m_ptr)
throw myVectorIteratorException{"operator++ used for uninitialized iterator\n"};
++m_ptr;
return *this;
}
myVectorIterator operator++(int)
{
if (!m_ptr)
throw myVectorIteratorException{ "operator++ used for uninitialized iterator\n" };
myVectorIterator tmp{ m_ptr };
++m_ptr;
return tmp;
}
myVectorIterator& operator--()
{
if (!m_ptr)
throw myVectorIteratorException{ "operator-- used for uninitialized iterator\n" };
--m_ptr;
return *this;
}
myVectorIterator operator--(int)
{
if (!m_ptr)
throw myVectorIteratorException{ "operator-- used for uninitialized iterator\n" };
myVectorIterator tmp{ m_ptr };
--m_ptr;
return tmp;
}
bool operator==(const myVectorIterator&it) { return m_ptr == it.m_ptr; }
bool operator!=(const myVectorIterator&it) { return m_ptr != it.m_ptr; }
bool operator<=(const myVectorIterator&it) { return m_ptr <= it.m_ptr; }
bool operator>=(const myVectorIterator&it) { return m_ptr >= it.m_ptr; }
bool operator<(const myVectorIterator& it) { return m_ptr < it.m_ptr; }
bool operator>(const myVectorIterator&it) { return m_ptr > it.m_ptr; }
bool operator+=(int i) { return m_ptr + i; }
bool operator-=(int i) { return m_ptr - i; }
iteratorCategories category() const
{
return random_access;
}
private:
valueType* m_ptr{ NULL };
public:
struct myVectorIteratorException {
myVectorIteratorException(const std::string& s)
: m_msg{ s }
{}
void what() const { std::cout << m_msg << std::endl; }
std::string m_msg{};
};
};
}
#endif // !MY_VECTOR_H
|
#include <iostream>
#include <cstdio>
using namespace std;
#define MAX 100005
#define min(a,b) ((a)<(b)?(a):(b))
int t, n, q;
int arr[MAX];
int tree[3*MAX];
void segment_tree(int root, int start, int last){
if( start == last){
tree[root] = arr[start];
return;
}
int mid = start + ((last-start)>>1);
int left = 2*root;
int right = 2*root + 1;
segment_tree(left, start, mid);
segment_tree(right, mid+1, last);
tree[root] = tree[left] + tree[right];
}
int query(int root, int start, int last, int lower, int upper){
if( last < lower || start > upper)
return 0;
if( start >= lower && last <= upper)
return tree[root];
int mid = start + ((last-start)>>1);
int left = 2*root;
int right = 2*root+1;
int min1 = query(left, start, mid, lower, upper);
int min2 = query(right, mid+1, last, lower, upper);
return min1+min2;
}
void update(int root, int start, int last, int index, int newValue) {
if (index > last || index < start) // if out of bound
return;
if (start >= index && last <= index) { // if in bound
tree[root] += newValue;
return;
}
// else on part of the bound
int left = 2 * root;
int right = 2 * root + 1;
int mid = start + ((last - start) >> 1);
update(left, start, mid, index, newValue);
update(right, mid + 1, last, index, newValue);
tree[root] = tree[left] + tree[right];
}
int give(int root, int start, int last, int index){
if( index < start || index > last)
return 0;
if(start >= index && last <= index){
int t = tree[root];
tree[root] = 0;
//update(1,1,n,index, 0);
return t;
}
int left = 2 * root;
int right = 2 * root + 1;
int mid = start + ((last - start) >> 1);
int v1 = give(left, start, mid, index);
int v2 = give(right, mid+1, last, index);
tree[root] = tree[left]+tree[right];
return v1+v2;
}
int main()
{
scanf("%d\n",&t);
int l, r, type, value;
for(int tc = 1 ; tc <= t ; tc++ ){
scanf("%d %d", &n, &q);
for(int i = 1; i <= n ; i++ )
scanf("%d",&arr[i]);
segment_tree(1,1,n);
printf("Case %d:\n",tc);
for(int i = 0; i < q ; i++){
scanf("%d",&type);
switch(type){
case 1:
scanf("%d",&l);
printf("%d\n",give(1,1,n,l+1));
break;
case 2:
scanf("%d %d",&l,&value);
update(1,1,n,l+1,value);
break;
case 3:
scanf("%d %d",&l,&r);
printf("%d\n",query(1,1,n,l+1,r+1));
break;
}
}
}
return 0;
}
|
#include <iostream>
using namespace std;
void insertionSort(int[], int);
int main() {
int myArray[] = { 24, 67, 50, 8, 29, 116, 125, 48, 110, 82, 145, 6, 63, 59, 80, 26, 105, 33, 15, 129 };
int arraySize = size(myArray);
insertionSort(myArray, arraySize);
cout << endl;
for (int i = 0; i < arraySize; i++) {
cout << myArray[i] << " ";
}
return 0;
}
void insertionSort(int myArray[], int size) {
// Iterate through entire array. We assume first element is sorted and start at i = 1
for (int i = 1; i < size; i++) {
int currentValue = myArray[i]; // Get value from array
int j = i - 1; // j is an index which decrements to see where currentValue should be inserted
// While j >= 0 and the value to left is greater than currentValue, shift value to right
while ((j >= 0) && (myArray[j] > currentValue)) {
myArray[j + 1] = myArray[j]; // Shifting value on left to right and then decrement
j--;
}
// Once while loop exits, j + 1 gives us position of where value should be inputted.
myArray[j + 1] = currentValue;
}
}
|
#ifndef uuid_guard_749f57a6_a1336058_14a62898_c4731a4a
#define uuid_guard_749f57a6_a1336058_14a62898_c4731a4a
#include <string>
namespace tul{
struct Uuid{
Uuid();
Uuid(const Uuid& obj);
Uuid(unsigned long first, unsigned long second);
bool operator ==(const Uuid& rhs) const;
bool operator !=(const Uuid& rhs) const;
//TODO implement the rest of the operators
bool operator <(const Uuid& rhs) const;
std::string serialize() const;
bool unserialize(const std::string& str);
unsigned long first;
unsigned long second;
};
}
#endif // uuid_guard_749f57a6_a1336058_14a62898_c4731a4a
|
/******<CODE NEVER DIE>******/
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define FastIO ios_base::sync_with_stdio(0)
#define IN cin.tie(0)
#define OUT cout.tie(0)
#define CIG cin.ignore()
#define pb push_back
#define pa pair<int,int>
#define f first
//#define s second
#define FOR(i,n,m) for(int i=n;i<m;i++)
#define FORD(i,n,m) for(int i=m;i>=n;i--)
#define reset(A) memset(A,0,sizeof(A))
#define FILEIN freopen("inputDTL.txt","r",stdin)
#define FILEOUT freopen("outputDTL.txt","w",stdout)
/**********DTL**********/
long long const mod=1e9+7;
int const MAX=1e5+5;
/**********DTL**********/
/**********DTL**********/
/**********main function**********/
int main(){
FastIO; IN; OUT;
//CIG;
//int test;
//cin >> test;
//while(test--){
vector<char> vt;
string s1;
getline(cin,s1);
int count=0;
FOR(i,0,s1.size()){
if(s1[i]>='A' && s1[i]<='Z'){
s1[i]=s1[i]+32;
}
if(s1[i]==' '){
count++;
}
}
vt.push_back(s1[0]);
FOR(i,0,s1.size()){
if(s1[i]==' ' && count>1){
vt.push_back(s1[i+1]);
count--;
}
}
int vtt;
FORD(i,0,s1.size()-1){
if(s1[i]==' '){
vtt=i;
break;
}
}
FOR(i,vtt+1,s1.size()){
vt.push_back(s1[i]);
}
FOR(i,0,vt.size()){
cout << vt[i];
}
cout << "@ptit.edu.vn";
//}
return 0;
}
|
#pragma warning (disable:4996)
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <ctime>
#include <cmath>
#include <string>
#include <cctype>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
const double EPS = 1e-9;
const double PI = 2 * asin(1);
const int INF = 0x7fffffff;
const LL LINF = 0x7fffffffffffffff;
const char CHAR[] = {'p', 'q', 'r', 'u', 'v', 'w', 'x', 'y', 'z'};
int num[10];
void pretreat() {}
bool input() {
for(int i = 0; i < 10; ++i) {
scanf(" %d", num + i);
}
return true;
}
void solve() {
bool f = true;
for(int i = 0; i < 10; ++i) {
if(f) {
if(i < 9) {
if(num[i] > 1) {
printf("%d%c", num[i], CHAR[i]);
f = false;
} else if(num[i] == 1) {
printf("%c", CHAR[i]);
f = false;
} else if(num[i] == -1) {
printf("-%c", CHAR[i]);
f = false;
} else if(num[i] < -1) {
printf("%d%c", num[i], CHAR[i]);
f = false;
}
} else {
if(num[i] > 0) {
printf("%d", num[i]);
f = false;
} else if(num[i] < 0) {
printf("%d", num[i]);
}
}
} else {
if(i < 9) {
if(num[i] > 1) {
printf("+%d%c", num[i], CHAR[i]);
} else if(num[i] == 1) {
printf("+%c", CHAR[i]);
} else if(num[i] == -1) {
printf("-%c", CHAR[i]);
} else if(num[i] < -1) {
printf("%d%c", num[i], CHAR[i]);
}
} else {
if(num[i] > 0) {
printf("+%d", num[i]);
f = false;
} else if(num[i] < 0) {
printf("%d", num[i]);
}
}
}
}
printf("\n");
}
int main() {
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
pretreat();
int t;
cin >> t;
for (int i = 1; i <= t; ++i) {
input();
solve();
}
return 0;
}
|
#ifndef TEXT_HPP_
#define TEXT_HPP_
#include <windows.h>
#include <string>
#include <vector>
#include <cstring>
inline std::wstring AnsiToWide(const std::string str)
{
std::wstring ret;
int src_len = int(str.size());
int dest_len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), src_len, NULL, 0);
ret.resize(dest_len);
MultiByteToWideChar(CP_ACP, 0, str.c_str(), src_len, &ret[0], dest_len);
return ret;
}
inline std::string WideToAnsi(const std::wstring str)
{
std::string ret;
int src_len = int(str.size());
int dest_len = WideCharToMultiByte(CP_ACP, 0, str.c_str(), src_len,
NULL, 0, NULL, NULL);
ret.resize(dest_len);
WideCharToMultiByte(CP_ACP, 0, str.c_str(), src_len, &ret[0], dest_len,
NULL, NULL);
return ret;
}
inline std::wstring Utf8ToWide(const std::string str)
{
std::wstring ret;
int src_len = int(str.size());
int dest_len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), src_len, NULL, 0);
ret.resize(dest_len);
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), src_len, &ret[0], dest_len);
return ret;
}
inline std::string WideToUtf8(const std::wstring str)
{
std::string ret;
int src_len = int(str.size());
int dest_len = WideCharToMultiByte(CP_UTF8, 0, str.c_str(), src_len,
NULL, 0, NULL, NULL);
ret.resize(dest_len);
WideCharToMultiByte(CP_UTF8, 0, str.c_str(), src_len, &ret[0], dest_len,
NULL, NULL);
return ret;
}
#define AnsiToAnsi(str) std::string(str)
#define WideToWide(str) std::wstring(str)
#ifdef UNICODE
#define AnsiToText(str) AnsiToWide(str)
#define WideToText(str) WideToWide(str)
#define TextToAnsi(str) WideToAnsi(str)
#define TextToWide(str) WideToWide(str)
#define TextToText(str) WideToWide(str)
#else
#define AnsiToText(str) AnsiToAnsi(str)
#define WideToText(str) WideToAnsi(str)
#define TextToAnsi(str) AnsiToAnsi(str)
#define TextToWide(str) AnsiToWide(str)
#define TextToText(str) AnsiToAnsi(str)
#endif
inline void
swap_endian(void *ptr, DWORD len)
{
BYTE *pb = (BYTE *)ptr;
len /= 2;
while (--len)
{
BYTE b = pb[0];
pb[0] = pb[1];
pb[1] = b;
++pb;
++pb;
}
}
inline void str_trim(std::string& str, const char *spaces = " \t\r\n")
{
size_t i = str.find_first_not_of(spaces);
size_t j = str.find_last_not_of(spaces);
if ((i == std::string::npos) || (j == std::string::npos))
{
str.clear();
}
else
{
str = str.substr(i, j - i + 1);
}
}
inline void str_trim(std::wstring& str, const wchar_t *spaces = L" \t\r\n")
{
size_t i = str.find_first_not_of(spaces);
size_t j = str.find_last_not_of(spaces);
if ((i == std::wstring::npos) || (j == std::wstring::npos))
{
str.clear();
}
else
{
str = str.substr(i, j - i + 1);
}
}
inline void str_trim(char *str, const char *spaces = " \t\r\n")
{
std::string s = str;
str_trim(s, spaces);
std::strcpy(str, s.c_str());
}
inline void str_trim(wchar_t *str, const wchar_t *spaces = L" \t\r\n")
{
std::wstring s = str;
str_trim(s, spaces);
std::wcscpy(str, s.c_str());
}
inline const char *skip_space(const char *pch)
{
using namespace std;
while (*pch && isspace(*pch))
{
++pch;
}
return pch;
}
inline const wchar_t *skip_space(const wchar_t *pch)
{
using namespace std;
while (*pch && iswspace(*pch))
{
++pch;
}
return pch;
}
inline const char *skip_word(const char *pch)
{
using namespace std;
while (*pch && isalpha(*pch) || isdigit(*pch) || *pch == '_')
{
++pch;
}
return pch;
}
inline const wchar_t *skip_word(const wchar_t *pch)
{
using namespace std;
while (*pch && iswalpha(*pch) || iswdigit(*pch) || *pch == L'_')
{
++pch;
}
return pch;
}
inline std::string str_repeat(const std::string& str, int count)
{
std::string ret;
for (int i = 0; i < count; ++i)
{
ret += str;
}
return ret;
}
inline std::wstring str_repeat(const std::wstring& str, int count)
{
std::wstring ret;
for (int i = 0; i < count; ++i)
{
ret += str;
}
return ret;
}
inline int str_repeat_count(const std::string& str1, const std::string& str2)
{
int count = 0;
for (size_t i = 0; i < str1.size(); i += str2.size())
{
if (str1.find(str2, i) != i)
break;
++count;
}
return count;
}
inline int str_repeat_count(const std::wstring& str1, const std::wstring& str2)
{
int count = 0;
for (size_t i = 0; i < str1.size(); i += str2.size())
{
if (str1.find(str2, i) != i)
break;
++count;
}
return count;
}
inline std::string str_escape(const std::string& str)
{
std::string ret;
for (size_t i = 0; i < str.size(); ++i)
{
char ch = str[i];
switch (ch)
{
case '\"': ret += "\"\""; break;
case '\\': ret += "\\\\"; break;
case '\0': ret += "\\0"; break;
case '\a': ret += "\\a"; break;
case '\b': ret += "\\b"; break;
case '\f': ret += "\\f"; break;
case '\n': ret += "\\n"; break;
case '\r': ret += "\\r"; break;
case '\t': ret += "\\t"; break;
case '\v': ret += "\\v"; break;
default:
if (ch < 0x20)
{
using namespace std;
char sz[32];
sprintf(sz, "\\x%02X", ch);
ret += sz;
}
else
{
ret += ch;
}
}
}
return ret;
}
inline std::wstring str_escape(const std::wstring& str)
{
std::wstring ret;
for (size_t i = 0; i < str.size(); ++i)
{
wchar_t ch = str[i];
switch (ch)
{
case L'\"': ret += L"\"\""; break;
case L'\\': ret += L"\\\\"; break;
case L'\0': ret += L"\\0"; break;
case L'\a': ret += L"\\a"; break;
case L'\b': ret += L"\\b"; break;
case L'\f': ret += L"\\f"; break;
case L'\n': ret += L"\\n"; break;
case L'\r': ret += L"\\r"; break;
case L'\t': ret += L"\\t"; break;
case L'\v': ret += L"\\v"; break;
default:
if (ch < 0x20)
{
using namespace std;
wchar_t sz[32];
wsprintfW(sz, L"\\x%02X", (BYTE)ch);
ret += sz;
}
else
{
ret += ch;
}
}
}
return ret;
}
inline bool guts_escape(std::string& str, const char*& pch)
{
using namespace std;
switch (*pch)
{
case '\\': str += '\\'; ++pch; break;
case '"': str += '\"'; ++pch; break;
case 'a': str += '\a'; ++pch; break;
case 'b': str += '\b'; ++pch; break;
case 'f': str += '\f'; ++pch; break;
case 'n': str += '\n'; ++pch; break;
case 'r': str += '\r'; ++pch; break;
case 't': str += '\t'; ++pch; break;
case 'v': str += '\v'; ++pch; break;
case 'x':
{
++pch;
std::string strNum;
if (isxdigit(*pch))
{
strNum += *pch;
++pch;
if (isxdigit(*pch))
{
strNum += *pch;
++pch;
}
}
str += (char)strtoul(strNum.c_str(), NULL, 16);
}
break;
case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7':
{
std::string strNum;
if ('0' <= *pch && *pch <= '7')
{
strNum += *pch;
++pch;
if ('0' <= *pch && *pch <= '7')
{
strNum += *pch;
++pch;
if ('0' <= *pch && *pch <= '7')
{
strNum += *pch;
++pch;
}
}
}
str += (char)strtoul(strNum.c_str(), NULL, 8);
}
break;
default:
str += *pch;
++pch;
return false;
}
return true;
}
inline bool guts_escape(std::wstring& str, const wchar_t*& pch)
{
using namespace std;
switch (*pch)
{
case L'\\': str += L'\\'; ++pch; break;
case L'"': str += L'\"'; ++pch; break;
case L'a': str += L'\a'; ++pch; break;
case L'b': str += L'\b'; ++pch; break;
case L'f': str += L'\f'; ++pch; break;
case L'n': str += L'\n'; ++pch; break;
case L'r': str += L'\r'; ++pch; break;
case L't': str += L'\t'; ++pch; break;
case L'v': str += L'\v'; ++pch; break;
case L'x':
{
++pch;
std::wstring strNum;
if (iswxdigit(*pch))
{
strNum += *pch;
++pch;
if (iswxdigit(*pch))
{
strNum += *pch;
++pch;
}
}
str += (wchar_t)wcstoul(strNum.c_str(), NULL, 16);
}
break;
case L'0': case L'1': case L'2': case L'3':
case L'4': case L'5': case L'6': case L'7':
{
std::wstring strNum;
if (L'0' <= *pch && *pch <= L'7')
{
strNum += *pch;
++pch;
if (L'0' <= *pch && *pch <= L'7')
{
strNum += *pch;
++pch;
if (L'0' <= *pch && *pch <= L'7')
{
strNum += *pch;
++pch;
}
}
}
str += (wchar_t)wcstoul(strNum.c_str(), NULL, 8);
}
break;
case 'u':
{
++pch;
std::wstring strNum;
if (iswxdigit(*pch))
{
strNum += *pch;
++pch;
if (iswxdigit(*pch))
{
strNum += *pch;
++pch;
if (iswxdigit(*pch))
{
strNum += *pch;
++pch;
if (iswxdigit(*pch))
{
strNum += *pch;
++pch;
}
}
}
}
str += (wchar_t)wcstoul(strNum.c_str(), NULL, 16);
}
break;
default:
str += *pch;
++pch;
return false;
}
return true;
}
inline bool guts_quote(std::string& str, const char*& pch)
{
using namespace std;
str.clear();
pch = skip_space(pch);
if (*pch != L'\"')
return false;
for (++pch; *pch; ++pch)
{
if (*pch == L'\\')
{
++pch;
guts_escape(str, pch);
--pch;
}
else if (*pch == L'\"')
{
++pch;
if (*pch == L'\"')
{
str += L'\"';
}
else
{
break;
}
}
else
{
str += *pch;
}
}
return true;
}
inline bool guts_quote(std::wstring& str, const wchar_t*& pch)
{
using namespace std;
str.clear();
pch = skip_space(pch);
if (*pch != L'\"')
return false;
for (++pch; *pch; ++pch)
{
if (*pch == L'\\')
{
++pch;
guts_escape(str, pch);
--pch;
}
else if (*pch == L'\"')
{
++pch;
if (*pch == L'\"')
{
str += L'\"';
}
else
{
break;
}
}
else
{
str += *pch;
}
}
return true;
}
inline std::wstring str_dec(UINT nID)
{
using namespace std;
wchar_t sz[32];
wsprintfW(sz, L"%u", nID);
std::wstring ret(sz);
return ret;
}
inline std::wstring str_hex(UINT nID)
{
std::wstring ret;
if (nID == 0)
{
ret = L"0";
}
else
{
using namespace std;
wchar_t sz[32];
wsprintfW(sz, L"0x%X", nID);
ret = sz;
}
return ret;
}
template <typename T_STR>
inline void
str_replace_all(T_STR& str, const T_STR& from, const T_STR& to)
{
size_t i = 0;
for (;;) {
i = str.find(from, i);
if (i == T_STR::npos)
break;
str.replace(i, from.size(), to);
i += to.size();
}
}
template <typename T_STR>
inline void
str_replace_all(T_STR& str,
const typename T_STR::value_type *from,
const typename T_STR::value_type *to)
{
str_replace_all(str, T_STR(from), T_STR(to));
}
template <typename T_STR>
inline bool is_ascii(const T_STR& str)
{
size_t i, count = str.size();
for (i = 0; i < count; ++i)
{
typename T_STR::value_type ch = str[i];
if (ch < 0x20 || 0x7F < ch)
return false;
}
return true;
}
inline std::wstring
BinaryToText(const std::vector<BYTE>& Data)
{
std::wstring ret;
if (Data.size() >= 2 && memcmp(&Data[0], "\xFF\xFE", 2) == 0)
{
// UTF-16 LE
ret.assign((const WCHAR *)&Data[0], Data.size() / sizeof(WCHAR));
}
else if (Data.size() >= 2 && memcmp(&Data[0], "\xFE\xFF", 2) == 0)
{
// UTF-16 BE
ret.assign((const WCHAR *)&Data[0], Data.size() / sizeof(WCHAR));
swap_endian(&ret[0], ret.size() * sizeof(WCHAR));
}
else if (Data.size() >= 3 && memcmp(&Data[0], "\xEF\xBB\xBF", 3) == 0)
{
// UTF-8
std::string str((const char *)&Data[3], Data.size() - 3);
ret = Utf8ToWide(str);
}
else
{
// ANSI
std::string str((const char *)&Data[0], Data.size());
ret = AnsiToWide(str);
}
str_replace_all(ret, L"\r\n", L"\n");
str_replace_all(ret, L"\r", L"\n");
str_replace_all(ret, L"\n", L"\r\n");
return ret;
}
inline std::string str_quote(const std::string& str)
{
std::string ret;
ret += "\"";
ret += str_escape(str);
ret += "\"";
return ret;
}
inline std::wstring str_quote(const std::wstring& str)
{
std::wstring ret;
ret += L"\"";
ret += str_escape(str);
ret += L"\"";
return ret;
}
inline bool str_unquote(std::string& str)
{
std::string str2 = str;
const char *pch = str2.c_str();
return guts_quote(str, pch);
}
inline bool str_unquote(std::wstring& str)
{
std::wstring str2 = str;
const wchar_t *pch = str2.c_str();
return guts_quote(str, pch);
}
inline bool str_unquote(char *str)
{
std::string s = str;
bool ret = str_unquote(s);
std::strcpy(str, s.c_str());
return ret;
}
inline bool str_unquote(wchar_t *str)
{
std::wstring s = str;
bool ret = str_unquote(s);
std::wcscpy(str, s.c_str());
return ret;
}
#endif // ndef TEXT_HPP_
|
/// "toString" : "struct myTemplate",
/// "kind" : "Type"
template<class T>
struct myTemplate {};
/// "toString" : "struct myTemplateChild",
/// "kind" : "Type"
struct myTemplateChild : myTemplate<int> { };
/*This example used to crash while building the type of Bar*/
/// "type" : { "toString" : "Bar" }
template <typename T>
class Bar
{
/// "type" : { "toString" : "function void (int)" }
void foo(UnknownType);
/// "returnType" : { "toString" : "int" }
UnknownType foo();
};
|
#pragma once
#include "math.h"
class Camera
{
public:
Vec3 pos; // Pozycja kamery
Vec3 dir; // Kierunek widzenia
Vec3 up; // Kierunek w górę
Vec3 right; // Kierunek w prawo
double width; // Wymiary rzutni
double height;
virtual void rotateX(double a) = 0;
virtual void rotateY(double a) = 0;
virtual Ray3 GetRay(double x , double y) = 0; // Zwraca promień przebiegający przez konkretny pixel
}; // Wartości < -1.0 ; 1.0 >
class Ortho : public Camera
{
public:
void rotateX(double a);
void rotateY(double a);
Ortho(double x , double y , Vec3 p , Vec3 d , Vec3 u);
Ray3 GetRay(double x , double y);
};
class Persp : public Camera
{
public:
double f; // Ogniskowa
void rotateX(double a);
void rotateY(double a);
Persp(double x , double y , double f , Vec3 p , Vec3 d , Vec3 u);
Ray3 GetRay(double x , double y);
};
|
#include "parser_main.h"
#ifndef __PARSER_TABLE__
#define __PARSER_TABLE__
/**
* An extension to the parser class designed for parsing Wikimarkup
* tables - specifically, for turning them into data.frames
* (and turning data.frames into wikimarkup tables!)
*/
class table_parser : public parser{
private:
/**
* A function for taking a wikitext table and splitting it
* into a vector - one string for each table row.
* @param table a string representing a wikitext table
*
* @see extract_fields for taking the extract_lines output
* and splitting into fields.
*
* @return a vector of strings, each one containing one
* row from the input table.
*/
std::vector < std::string > extract_rows(std::string table);
/**
* A function for taking a row from extract_rows and splitting
* it into individual fields. Used to construct data.frames out
* of MediaWiki tables.
*
* @param row a line from extract_rows.
*
* @return a vector of strings, each one containing one field
* from the input row.
*/
std::vector < std::string > extract_fields(std::string row);
public:
std::list < std::vector < std::string > > table_to_df(std::string table);
};
#endif
|
#ifndef MOUSECLICKED
#define MOUSECLICKED
#include "glut.h"
class MouseClicked
{
private:
bool isPunch = false;
public:
static MouseClicked* Instance();
bool getisPunch() { return isPunch; }
void mouse(int, int, int, int);
private:
MouseClicked()
{
}
virtual ~MouseClicked()
{
}
};
#endif
|
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage 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 "astra_camera/point_cloud_proc/point_cloud_xyz.h"
namespace astra_camera {
PointCloudXyzNode::PointCloudXyzNode(ros::NodeHandle &nh, ros::NodeHandle &nh_private)
: nh_(nh), nh_private_(nh_private) {
nh_private_.param<int>("queue_size", queue_size_, 5);
ros::SubscriberStatusCallback connect_cb = std::bind(&PointCloudXyzNode::connectCb, this);
ros::SubscriberStatusCallback disconnect_cb = std::bind(&PointCloudXyzNode::disconnectCb, this);
it_.reset(new image_transport::ImageTransport(nh));
std::lock_guard<decltype(connect_mutex_)> lock_(connect_mutex_);
pub_point_cloud_ = nh_.advertise<sensor_msgs::PointCloud2>("depth/points", queue_size_,
connect_cb, disconnect_cb);
save_point_cloud_srv_ = nh_.advertiseService<std_srvs::EmptyRequest, std_srvs::EmptyResponse>(
"save_point_cloud_xyz",
[this](auto &&req, auto &&res) { return this->SavePointCloudXyzCallback(req, res); });
}
PointCloudXyzNode::~PointCloudXyzNode() = default;
void PointCloudXyzNode::connectCb() {
std::lock_guard<std::mutex> lock(connect_mutex_);
if (!sub_depth_) {
image_transport::TransportHints hints("raw", ros::TransportHints(), nh_private_);
sub_depth_ = it_->subscribeCamera("depth/image_raw", queue_size_, &PointCloudXyzNode::depthCb,
this, hints);
}
}
void PointCloudXyzNode::disconnectCb() {
if (pub_point_cloud_.getNumSubscribers() == 0) {
sub_depth_.shutdown();
}
}
void PointCloudXyzNode::depthCb(const sensor_msgs::ImageConstPtr &depth_msg,
const sensor_msgs::CameraInfoConstPtr &info_msg) {
PointCloud2::Ptr cloud_msg(new PointCloud2);
cloud_msg->header = depth_msg->header;
cloud_msg->height = depth_msg->height;
cloud_msg->width = depth_msg->width;
cloud_msg->is_dense = false;
cloud_msg->is_bigendian = false;
sensor_msgs::PointCloud2Modifier pcd_modifier(*cloud_msg);
pcd_modifier.setPointCloud2FieldsByString(1, "xyz");
// Update camera model
model_.fromCameraInfo(info_msg);
if (depth_msg->encoding == enc::TYPE_16UC1 || depth_msg->encoding == enc::MONO16) {
convert<uint16_t>(depth_msg, cloud_msg, model_);
} else if (depth_msg->encoding == enc::TYPE_32FC1) {
convert<float>(depth_msg, cloud_msg, model_);
} else {
ROS_WARN_THROTTLE(5, "Depth image has unsupported encoding [%s]", depth_msg->encoding.c_str());
return;
}
if (save_cloud_) {
save_cloud_ = false;
auto now = std::time(nullptr);
std::stringstream ss;
ss << std::put_time(std::localtime(&now), "%Y%m%d_%H%M%S");
auto current_path = boost::filesystem::current_path().string();
std::string filename = current_path + "/point_cloud/points_xyz_" + ss.str() + ".ply";
if (!boost::filesystem::exists(current_path + "/point_cloud")) {
boost::filesystem::create_directory(current_path + "/point_cloud");
}
ROS_INFO_STREAM("Saving point cloud to " << filename);
savePointToPly(cloud_msg, filename);
}
pub_point_cloud_.publish(cloud_msg);
}
bool PointCloudXyzNode::SavePointCloudXyzCallback(std_srvs::Empty::Request &request,
std_srvs::Empty::Response &response) {
(void)request;
(void)response;
ROS_INFO("SavePointCloudXyzCallback");
save_cloud_ = true;
return true;
}
} // namespace astra_camera
|
#pragma once
#include "utils/ptts.hpp"
#include "proto/config_mail.pb.h"
using namespace std;
namespace pc = proto::config;
namespace nora {
namespace config {
using mail_ptts = ptts<pc::mail>;
mail_ptts& mail_ptts_instance();
void mail_ptts_set_funcs();
}
}
|
/* XMRig
* Copyright (c) 2018-2020 SChernykh <https://github.com/SChernykh>
* Copyright (c) 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "base/io/json/JsonRequest.h"
#include "3rdparty/rapidjson/document.h"
namespace xmrig {
const char *JsonRequest::k2_0 = "2.0";
const char *JsonRequest::kId = "id";
const char *JsonRequest::kJsonRPC = "jsonrpc";
const char *JsonRequest::kMethod = "method";
const char *JsonRequest::kOK = "OK";
const char *JsonRequest::kParams = "params";
const char *JsonRequest::kResult = "result";
const char *JsonRequest::kStatus = "status";
const char *JsonRequest::kParseError = "parse error";
const char *JsonRequest::kInvalidRequest = "invalid request";
const char *JsonRequest::kMethodNotFound = "method not found";
const char *JsonRequest::kInvalidParams = "invalid params";
const char *JsonRequest::kInternalError = "internal error";
static uint64_t nextId = 0;
} // namespace xmrig
rapidjson::Document xmrig::JsonRequest::create(const char *method)
{
return create(++nextId, method);
}
rapidjson::Document xmrig::JsonRequest::create(int64_t id, const char *method)
{
using namespace rapidjson;
Document doc(kObjectType);
auto &allocator = doc.GetAllocator();
doc.AddMember(StringRef(kId), id, allocator);
doc.AddMember(StringRef(kJsonRPC), StringRef(k2_0), allocator);
doc.AddMember(StringRef(kMethod), StringRef(method), allocator);
return doc;
}
uint64_t xmrig::JsonRequest::create(rapidjson::Document &doc, const char *method, rapidjson::Value ¶ms)
{
return create(doc, ++nextId, method, params);
}
uint64_t xmrig::JsonRequest::create(rapidjson::Document &doc, int64_t id, const char *method, rapidjson::Value ¶ms)
{
using namespace rapidjson;
auto &allocator = doc.GetAllocator();
doc.AddMember(StringRef(kId), id, allocator);
doc.AddMember(StringRef(kJsonRPC), StringRef(k2_0), allocator);
doc.AddMember(StringRef(kMethod), StringRef(method), allocator);
doc.AddMember(StringRef(kParams), params, allocator);
return id;
}
|
//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) Triad National Security, LLC. This file is part of the
// Tusas code (LA-CC-17-001) and is subject to the revised BSD license terms
// in the LICENSE file found in the top-level directory of this distribution.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef NOX_THYRA_MODEL_EVALUATOR_HEAT_DEF_HPP
#define NOX_THYRA_MODEL_EVALUATOR_HEAT_DEF_HPP
// Thyra support
//#include "Thyra_DefaultSpmdVectorSpace.hpp"
#include "Thyra_DefaultSerialDenseLinearOpWithSolveFactory.hpp"
#include "Thyra_DetachedMultiVectorView.hpp"
#include "Thyra_DetachedVectorView.hpp"
#include "Thyra_MultiVectorStdOps.hpp"
#include "Thyra_VectorStdOps.hpp"
#include "Thyra_PreconditionerBase.hpp"
#include "Thyra_MLPreconditionerFactory.hpp"
#include "Thyra_DetachedSpmdVectorView.hpp"
// NOX support
#include "NOX_Thyra_MatrixFreeJacobianOperator.hpp"
#include "NOX_MatrixFree_ModelEvaluatorDecorator.hpp"
// Epetra support
#include "Thyra_EpetraThyraWrappers.hpp"
#include "Thyra_get_Epetra_Operator.hpp"
#include "Epetra_Comm.h"
#include "Epetra_Map.h"
#include "Epetra_Vector.h"
#include "Epetra_Import.h"
#include "Epetra_CrsGraph.h"
#include "Epetra_CrsMatrix.h"
//teuchos support
#include <Teuchos_RCP.hpp>
// local support
#include "preconditioner.hpp"
#include "basis.hpp"
#include "ParamNames.h"
// Nonmember constuctors
template<class Scalar>
Teuchos::RCP<ModelEvaluatorHEAT<Scalar> >
modelEvaluatorHEAT(const Teuchos::RCP<const Epetra_Comm>& comm,
Mesh *mesh,
Teuchos::ParameterList plist)
{
return Teuchos::rcp(new ModelEvaluatorHEAT<Scalar>(comm,mesh,plist));
}
// Constructor
template<class Scalar>
ModelEvaluatorHEAT<Scalar>::
ModelEvaluatorHEAT(const Teuchos::RCP<const Epetra_Comm>& comm,
Mesh *mesh,
Teuchos::ParameterList plist) :
comm_(comm),
paramList(plist),
mesh_(mesh),
showGetInvalidArg_(false)
{
dt_ = paramList.get<double> (TusasdtNameString);
using Teuchos::RCP;
using Teuchos::rcp;
using ::Thyra::VectorBase;
typedef ::Thyra::ModelEvaluatorBase MEB;
typedef Teuchos::ScalarTraits<Scalar> ST;
TEUCHOS_ASSERT(nonnull(comm_));
if (comm_->NumProc() != 1) {
if (comm_->MyPID() == 0) std::cout<<std::endl<<"Only one processor supported"<<std::endl<<std::endl<<std::endl;
exit(0);
}
mesh_->compute_nodal_adj();
//const int num_nodes = num_global_elements_ + 1;
const int num_nodes = mesh_->get_num_nodes();
// owned space
x_owned_map_ = rcp(new Epetra_Map(num_nodes,0,*comm_));
//x_owned_map_->Print(std::cout);
x_space_ = ::Thyra::create_VectorSpace(x_owned_map_);
// residual space
f_owned_map_ = x_owned_map_;
f_space_ = x_space_;
x0_ = ::Thyra::createMember(x_space_);
V_S(x0_.ptr(), ST::zero());
// Initialize the graph for W CrsMatrix object
W_graph_ = createGraph();
P_ = rcp(new Epetra_CrsMatrix(Copy,*W_graph_));
prec_ = Teuchos::rcp(new preconditioner<Scalar>(P_, comm_, paramList.sublist("ML")));
u_old_ = rcp(new Epetra_Vector(*f_owned_map_));
MEB::InArgsSetup<Scalar> inArgs;
inArgs.setModelEvalDescription(this->description());
inArgs.setSupports(MEB::IN_ARG_x);
prototypeInArgs_ = inArgs;
MEB::OutArgsSetup<Scalar> outArgs;
outArgs.setModelEvalDescription(this->description());
outArgs.setSupports(MEB::OUT_ARG_f);
//outArgs.setSupports(MEB::OUT_ARG_W_op);
outArgs.setSupports(MEB::OUT_ARG_W_prec);
// outArgs.set_W_properties(DerivativeProperties(
// DERIV_LINEARITY_NONCONST
// ,DERIV_RANK_FULL
// ,true // supportsAdjoint
// ));
prototypeOutArgs_ = outArgs;
nominalValues_ = inArgs;
nominalValues_.set_x(x0_);
init_nox();
time_=0.;
}
// Initializers/Accessors
template<class Scalar>
Teuchos::RCP<Epetra_CrsGraph>
ModelEvaluatorHEAT<Scalar>::createGraph()
{
Teuchos::RCP<Epetra_CrsGraph> W_graph;
// Create the shell for the
W_graph = Teuchos::rcp(new Epetra_CrsGraph(Copy, *x_owned_map_, 5));
//nodes are numbered consecutively by nodeid
for (int i=0; i < mesh_->get_num_nodes(); i++) {
std::vector<int> column (mesh_->get_nodal_adj(i));
column.push_back(i);//cn put the diagonal in
//cn need something here for more than one pde (see 2dstokes ex)
W_graph->InsertGlobalIndices(i, column.size(), &column[0]);
}//i
W_graph->FillComplete();
//W_graph->Print(std::cout);
//exit(0);
return W_graph;
}
template<class Scalar>
void ModelEvaluatorHEAT<Scalar>::set_x0(const Teuchos::ArrayView<const Scalar> &x0_in)
{
#ifdef TEUCHOS_DEBUG
TEUCHOS_ASSERT_EQUALITY(x_space_->dim(), x0_in.size());
#endif
Thyra::DetachedVectorView<Scalar> x0(x0_);
x0.sv().values()().assign(x0_in);
}
template<class Scalar>
void ModelEvaluatorHEAT<Scalar>::setShowGetInvalidArgs(bool showGetInvalidArg)
{
showGetInvalidArg_ = showGetInvalidArg;
}
template<class Scalar>
void ModelEvaluatorHEAT<Scalar>::
set_W_factory(const Teuchos::RCP<const ::Thyra::LinearOpWithSolveFactoryBase<Scalar> >& W_factory)
{
W_factory_ = W_factory;
}
// Public functions overridden from ModelEvaulator
template<class Scalar>
Teuchos::RCP<const Thyra::VectorSpaceBase<Scalar> >
ModelEvaluatorHEAT<Scalar>::get_x_space() const
{
return x_space_;
}
template<class Scalar>
Teuchos::RCP<const Thyra::VectorSpaceBase<Scalar> >
ModelEvaluatorHEAT<Scalar>::get_f_space() const
{
return f_space_;
}
template<class Scalar>
Thyra::ModelEvaluatorBase::InArgs<Scalar>
ModelEvaluatorHEAT<Scalar>::getNominalValues() const
{
return nominalValues_;
}
template<class Scalar>
Teuchos::RCP<Thyra::LinearOpBase<Scalar> >
ModelEvaluatorHEAT<Scalar>::create_W_op() const
{
Teuchos::RCP<Epetra_CrsMatrix> W_epetra =
Teuchos::rcp(new Epetra_CrsMatrix(::Copy,*W_graph_));
return Thyra::nonconstEpetraLinearOp(W_epetra);
}
template<class Scalar>
Teuchos::RCP< ::Thyra::PreconditionerBase<Scalar> >
ModelEvaluatorHEAT<Scalar>::create_W_prec() const
{
const Teuchos::RCP<Thyra::LinearOpBase< Scalar > > P_op = prec_;
Teuchos::RCP<Thyra::DefaultPreconditioner<Scalar> > prec =
Teuchos::rcp(new Thyra::DefaultPreconditioner<Scalar>(Teuchos::null,P_op));
return prec;
// return Teuchos::null;
}
template<class Scalar>
Teuchos::RCP<const Thyra::LinearOpWithSolveFactoryBase<Scalar> >
ModelEvaluatorHEAT<Scalar>::get_W_factory() const
{
return W_factory_;
}
template<class Scalar>
Thyra::ModelEvaluatorBase::InArgs<Scalar>
ModelEvaluatorHEAT<Scalar>::createInArgs() const
{
return prototypeInArgs_;
}
// Private functions overridden from ModelEvaulatorDefaultBase
template<class Scalar>
Thyra::ModelEvaluatorBase::OutArgs<Scalar>
ModelEvaluatorHEAT<Scalar>::createOutArgsImpl() const
{
return prototypeOutArgs_;
}
template<class Scalar>
void ModelEvaluatorHEAT<Scalar>::evalModelImpl(
const Thyra::ModelEvaluatorBase::InArgs<Scalar> &inArgs,
const Thyra::ModelEvaluatorBase::OutArgs<Scalar> &outArgs
) const
{
using Teuchos::RCP;
using Teuchos::rcp;
using Teuchos::rcp_dynamic_cast;
TEUCHOS_ASSERT(nonnull(inArgs.get_x()));
const RCP<Thyra::VectorBase<Scalar> > f_out = outArgs.get_f();
//const RCP<Thyra::LinearOpBase<Scalar> > W_out = outArgs.get_W_op();
const RCP<Thyra::PreconditionerBase<Scalar> > W_prec_out = outArgs.get_W_prec();
if ( nonnull(f_out) || nonnull(W_prec_out) ) {
// ****************
// Get the underlying epetra objects
// ****************
RCP<Epetra_Vector> f;
if (nonnull(f_out)) {
f = Thyra::get_Epetra_Vector(*f_owned_map_,outArgs.get_f());//f_out?
//f->Print(std::cout);
}
if (nonnull(f_out))
f->PutScalar(0.0);
if (nonnull(W_prec_out))
P_->PutScalar(0.0);
RCP<const Epetra_Vector> u = (Thyra::get_Epetra_Vector(*x_owned_map_,inArgs.get_x()));
//const Epetra_Vector &u = *(Thyra::get_Epetra_Vector(*x_owned_map_,inArgs.get_x()));
double jac;
double *xx, *yy, *zz;
double *uu, *uu_old;
int n_nodes_per_elem;
Basis *ubasis;
int dim = mesh_->get_num_dim();
for(int blk = 0; blk < mesh_->get_num_elem_blks(); blk++){
n_nodes_per_elem = mesh_->get_num_nodes_per_elem_in_blk(blk);
std::string elem_type=mesh_->get_blk_elem_type(blk);
if( (0==elem_type.compare("QUAD4")) || (0==elem_type.compare("QUAD")) ){ // linear quad
ubasis = new BasisLQuad();
}
else if( (0==elem_type.compare("QUAD9")) || (0==elem_type.compare("quad9")) ){ // quadratic quad
ubasis = new BasisQQuad;
}
else if( (0==elem_type.compare("TRI3")) || (0==elem_type.compare("TRI")) ){ // linear triangle
ubasis = new BasisLTri();
}
else if( (0==elem_type.compare("TRI6")) || (0==elem_type.compare("tri6")) ){ // quadratic triangle
ubasis = new BasisQTri;
}
else if( (0==elem_type.compare("HEX8")) || (0==elem_type.compare("HEX")) ){ // linear hex
ubasis = new BasisLHex();
}
else if( (0==elem_type.compare("TETRA4")) || (0==elem_type.compare("TETRA")) ){ // linear tet
ubasis = new BasisLTet();
}
else {
std::cout<<"Unsupported element type"<<std::endl<<std::endl;
exit(0);
}
xx = new double[n_nodes_per_elem];
yy = new double[n_nodes_per_elem];
zz = new double[n_nodes_per_elem];
uu = new double[n_nodes_per_elem];
uu_old = new double[n_nodes_per_elem];
for (int ne=0; ne < mesh_->get_num_elem_in_blk(blk); ne++) {// Loop Over # of Finite Elements on Processor
for(int k = 0; k < n_nodes_per_elem; k++){
int nodeid = mesh_->get_node_id(blk, ne, k);
xx[k] = mesh_->get_x(nodeid);
yy[k] = mesh_->get_y(nodeid);
zz[k] = mesh_->get_z(nodeid);
//uu[k] = u[nodeid];
uu[k] = (*u)[nodeid]; // copy initial guess
//or old solution into local temp
uu_old[k] = (*u_old_)[nodeid];
}//k
for(int gp=0; gp < ubasis->ngp; gp++) {// Loop Over Gauss Points
// Calculate the basis function at the gauss point
if(3 == dim) {
ubasis->getBasis(gp, xx, yy, zz, uu, uu_old);
}else{
ubasis->getBasis(gp, xx, yy, zz, uu, uu_old,NULL);
}
// Loop over Nodes in Element
for (int i=0; i< n_nodes_per_elem; i++) {
int row = mesh_->get_node_id(blk, ne, i);
double dphidx = ubasis->dphidxi[i]*ubasis->dxidx
+ubasis->dphideta[i]*ubasis->detadx
+ubasis->dphidzta[i]*ubasis->dztadx;
double dphidy = ubasis->dphidxi[i]*ubasis->dxidy
+ubasis->dphideta[i]*ubasis->detady
+ubasis->dphidzta[i]*ubasis->dztady;
double dphidz = ubasis->dphidxi[i]*ubasis->dxidz
+ubasis->dphideta[i]*ubasis->detadz
+ubasis->dphidzta[i]*ubasis->dztadz;
if (nonnull(f_out)) {
double x = ubasis->xx;
double y = ubasis->yy;
double divgradu = ubasis->dudx*dphidx + ubasis->dudy*dphidy + ubasis->dudz*dphidz;//(grad u,grad phi)
double ut = (ubasis->uu-ubasis->uuold)/dt_*ubasis->phi[i];
double pi = 3.141592653589793;
//double ff = 2.*ubasis->phi[i];
//double ff = ((1. + 5.*dt_*pi*pi)*sin(pi*x)*sin(2.*pi*y)/dt_)*ubasis->phi[i];
//double val = ubasis->jac * ubasis->wt * (ut + divgradu - ff);
double val = ubasis->jac * ubasis->wt * (ut + divgradu);
f->SumIntoGlobalValues ((int) 1, &val, &row);
}
// Loop over Trial Functions
if (nonnull(W_prec_out)) {
for(int j=0;j < n_nodes_per_elem; j++) {
int column = mesh_->get_node_id(blk, ne, j);
double dtestdx = ubasis->dphidxi[j]*ubasis->dxidx
+ubasis->dphideta[j]*ubasis->detadx
+ubasis->dphidzta[j]*ubasis->dztadx;
double dtestdy = ubasis->dphidxi[j]*ubasis->dxidy
+ubasis->dphideta[j]*ubasis->detady
+ubasis->dphidzta[j]*ubasis->dztady;
double dtestdz = ubasis->dphidxi[j]*ubasis->dxidz
+ubasis->dphideta[j]*ubasis->detadz
+ubasis->dphidzta[j]*ubasis->dztadz;
double divgrad = dtestdx * dphidx + dtestdy * dphidy + dtestdz * dphidz;
double phi_t = ubasis->phi[i] * ubasis->phi[j]/dt_;
double jac = ubasis->jac*ubasis->wt*(phi_t + divgrad);
//std::cout<<row<<" "<<column<<" "<<jac<<std::endl;
P_->SumIntoGlobalValues(row, 1, &jac, &column);
}//j
}
}//i
}//gp
}//ne
if (nonnull(f_out)) {//cn double check the use of notnull throughout
for ( int j = 0; j < mesh_->get_node_set(1).size(); j++ ){
int row = mesh_->get_node_set_entry(1, j);
(*f)[row] =
(*u)[row] - 0.0; // Dirichlet BC of zero
}
for ( int j = 0; j < mesh_->get_node_set(2).size(); j++ ){
int row = mesh_->get_node_set_entry(2, j);
(*f)[row] =
(*u)[row] - 0.0; // Dirichlet BC of zero
}
for ( int j = 0; j < mesh_->get_node_set(3).size(); j++ ){
int row = mesh_->get_node_set_entry(3, j);
(*f)[row] =
(*u)[row] - 0.0; // Dirichlet BC of zero
}
for ( int j = 0; j < mesh_->get_node_set(0).size(); j++ ){
int row = mesh_->get_node_set_entry(0, j);
(*f)[row] =
(*u)[row] - 0.0; // Dirichlet BC of zero
}
}
if (nonnull(W_prec_out)) {
for ( int j = 0; j < mesh_->get_node_set(1).size(); j++ ){
int row = mesh_->get_node_set_entry(1, j);
//clear row and put 1 on diagonal
std::vector<int> column (mesh_->get_nodal_adj(row));
std::vector<double> vals (column.size(),0.);
column.push_back(row);
vals.push_back(1.);
P_->ReplaceGlobalValues (row, vals.size(), &vals[0],&column[0] );
}
for ( int j = 0; j < mesh_->get_node_set(2).size(); j++ ){
int row = mesh_->get_node_set_entry(2, j);
std::vector<int> column (mesh_->get_nodal_adj(row));
std::vector<double> vals (column.size(),0.);
column.push_back(row);
vals.push_back(1.);
P_->ReplaceGlobalValues (row, vals.size(), &vals[0],&column[0] );
}
for ( int j = 0; j < mesh_->get_node_set(3).size(); j++ ){
int row = mesh_->get_node_set_entry(3, j);
std::vector<int> column (mesh_->get_nodal_adj(row));
std::vector<double> vals (column.size(),0.);
column.push_back(row);
vals.push_back(1.);
P_->ReplaceGlobalValues (row, vals.size(), &vals[0],&column[0] );
}
for ( int j = 0; j < mesh_->get_node_set(0).size(); j++ ){
int row = mesh_->get_node_set_entry(0, j);
std::vector<int> column (mesh_->get_nodal_adj(row));
std::vector<double> vals (column.size(),0.);
column.push_back(row);
vals.push_back(1.);
P_->ReplaceGlobalValues (row, vals.size(), &vals[0],&column[0] );
}
}
}//blk
delete xx;
delete yy;
delete uu;
delete ubasis;
if (nonnull(f_out)){
//f->Print(std::cout);
}
if (nonnull(W_prec_out)) {
P_->FillComplete();
//P_->Print(std::cout);
//exit(0);
//std::cout<<" one norm P_ = "<<P_->NormOne()<<std::endl<<" inf norm P_ = "<<P_->NormInf()<<std::endl<<" fro norm P_ = "<<P_->NormFrobenius()<<std::endl;
//Epetra_Vector d(*f_owned_map_);P_->ExtractDiagonalCopy(d);d.Print(std::cout);
prec_->ReComputePreconditioner();
}
}
}
//====================================================================
template<class Scalar>
ModelEvaluatorHEAT<Scalar>::~ModelEvaluatorHEAT()
{
// if(!prec_.is_null()) prec_ = Teuchos::null;
}
template<class Scalar>
void ModelEvaluatorHEAT<Scalar>::init_nox()
{
::Stratimikos::DefaultLinearSolverBuilder builder;
Teuchos::RCP<Teuchos::ParameterList> lsparams =
Teuchos::rcp(new Teuchos::ParameterList);
#if 0
lsparams->set("Linear Solver Type", "Belos");
lsparams->sublist("Linear Solver Types").sublist("Belos").sublist("Solver Types").sublist("Pseudo Block GMRES").set("Num Blocks",1);
lsparams->sublist("Linear Solver Types").sublist("Belos").sublist("Solver Types").sublist("Pseudo Block GMRES").set("Maximum Restarts",200);
//lsparams->sublist("Linear Solver Types").sublist("Belos").sublist("Solver Types").sublist("Psuedo Block GMRES").set("Output Frequency",1);
#else
lsparams->set("Linear Solver Type", "AztecOO");
lsparams->sublist("Linear Solver Types").sublist("AztecOO").sublist("Forward Solve").sublist("AztecOO Settings").set("Output Frequency",1);
//lsparams->sublist("Linear Solver Types").sublist("AztecOO").sublist("Forward Solve").sublist("AztecOO Settings").sublist("AztecOO Preconditioner", "None");
#endif
lsparams->set("Preconditioner Type", "None");
builder.setParameterList(lsparams);
lsparams->print(std::cout);
builder.getParameterList()->print(std::cout);
Teuchos::RCP< ::Thyra::LinearOpWithSolveFactoryBase<double> >
lowsFactory = builder.createLinearSolveStrategy("");
// Setup output stream and the verbosity level
Teuchos::RCP<Teuchos::FancyOStream>
out = Teuchos::VerboseObjectBase::getDefaultOStream();
lowsFactory->setOStream(out);
lowsFactory->setVerbLevel(Teuchos::VERB_EXTREME);
this->set_W_factory(lowsFactory);
// Create the initial guess
Teuchos::RCP< ::Thyra::VectorBase<double> >
initial_guess = this->getNominalValues().get_x()->clone_v();
Thyra::V_S(initial_guess.ptr(),Teuchos::ScalarTraits<double>::one());
// Create the JFNK operator
Teuchos::ParameterList printParams;
Teuchos::RCP<Teuchos::ParameterList> jfnkParams = Teuchos::parameterList();
jfnkParams->set("Difference Type","Forward");
//jfnkParams->set("Perturbation Algorithm","KSP NOX 2001");
jfnkParams->set("lambda",1.0e-4);
Teuchos::RCP<NOX::Thyra::MatrixFreeJacobianOperator<double> > jfnkOp =
Teuchos::rcp(new NOX::Thyra::MatrixFreeJacobianOperator<double>(printParams));
jfnkOp->setParameterList(jfnkParams);
jfnkParams->print(std::cout);
Teuchos::RCP< ::Thyra::ModelEvaluator<double> > Model = Teuchos::rcpFromRef(*this);
// Wrap the model evaluator in a JFNK Model Evaluator
Teuchos::RCP< ::Thyra::ModelEvaluator<double> > thyraModel =
Teuchos::rcp(new NOX::MatrixFreeModelEvaluatorDecorator<double>(Model));
// Wrap the model evaluator in a JFNK Model Evaluator
// Teuchos::RCP< ::Thyra::ModelEvaluator<double> > thyraModel =
// Teuchos::rcp(new NOX::MatrixFreeModelEvaluatorDecorator<double>(this));
Teuchos::RCP< ::Thyra::PreconditionerBase<double> > precOp = thyraModel->create_W_prec();
// Create the NOX::Thyra::Group
bool precon = false;
Teuchos::RCP<NOX::Thyra::Group> nox_group;
if(precon){
nox_group =
Teuchos::rcp(new NOX::Thyra::Group(*initial_guess, thyraModel, jfnkOp, lowsFactory, precOp, Teuchos::null));
}
else {
nox_group =
Teuchos::rcp(new NOX::Thyra::Group(*initial_guess, thyraModel, jfnkOp, lowsFactory, Teuchos::null, Teuchos::null));
}
nox_group->computeF();
// VERY IMPORTANT!!! jfnk object needs base evaluation objects.
// This creates a circular dependency, so use a weak pointer.
jfnkOp->setBaseEvaluationToNOXGroup(nox_group.create_weak());
// Create the NOX status tests and the solver
// Create the convergence tests
Teuchos::RCP<NOX::StatusTest::NormF> absresid =
Teuchos::rcp(new NOX::StatusTest::NormF(1.0e-8));
Teuchos::RCP<NOX::StatusTest::NormF> relresid =
Teuchos::rcp(new NOX::StatusTest::NormF(*nox_group.get(), 1.0e-8));//1.0e-6 for paper
Teuchos::RCP<NOX::StatusTest::NormWRMS> wrms =
Teuchos::rcp(new NOX::StatusTest::NormWRMS(1.0e-2, 1.0e-8));
Teuchos::RCP<NOX::StatusTest::Combo> converged =
Teuchos::rcp(new NOX::StatusTest::Combo(NOX::StatusTest::Combo::AND));
//converged->addStatusTest(absresid);
converged->addStatusTest(relresid);
//converged->addStatusTest(wrms);
Teuchos::RCP<NOX::StatusTest::MaxIters> maxiters =
Teuchos::rcp(new NOX::StatusTest::MaxIters(20));
Teuchos::RCP<NOX::StatusTest::FiniteValue> fv =
Teuchos::rcp(new NOX::StatusTest::FiniteValue);
Teuchos::RCP<NOX::StatusTest::Combo> combo =
Teuchos::rcp(new NOX::StatusTest::Combo(NOX::StatusTest::Combo::OR));
combo->addStatusTest(fv);
combo->addStatusTest(converged);
combo->addStatusTest(maxiters);
// Create nox parameter list
Teuchos::RCP<Teuchos::ParameterList> nl_params =
Teuchos::rcp(new Teuchos::ParameterList);
nl_params->set("Nonlinear Solver", "Line Search Based");
//nl_params->sublist("Direction").sublist("Newton").sublist("Linear Solver").set("Tolerance", 1.0e-4);
Teuchos::ParameterList& nlPrintParams = nl_params->sublist("Printing");
nlPrintParams.set("Output Information",
NOX::Utils::OuterIteration +
// NOX::Utils::OuterIterationStatusTest +
NOX::Utils::InnerIteration +
NOX::Utils::Details +
NOX::Utils::LinearSolverDetails);
nl_params->set("Forcing Term Method", "Type 2");
nl_params->set("Forcing Term Initial Tolerance", 1.0e-1);
nl_params->set("Forcing Term Maximum Tolerance", 1.0e-2);
nl_params->set("Forcing Term Minimum Tolerance", 1.0e-5);//1.0e-6
// Create the solver
solver_ = NOX::Solver::buildSolver(nox_group, combo, nl_params);
}
template<class Scalar>
void ModelEvaluatorHEAT<Scalar>::advance()
{
Teuchos::RCP< VectorBase< double > > guess = Thyra::create_Vector(u_old_,x_space_);
NOX::Thyra::Vector thyraguess(*guess);//by sending the dereferenced pointer, we instigate a copy rather than a view
solver_->reset(thyraguess);
NOX::StatusTest::StatusType solvStatus = solver_->solve();
if( !(NOX::StatusTest::Converged == solvStatus)) {
std::cout<<" NOX solver failed to converge. Status = "<<solvStatus<<std::endl<<std::endl;
exit(0);
}
std::cout<<solver_->getList();
const Thyra::VectorBase<double> * sol =
&(dynamic_cast<const NOX::Thyra::Vector&>(
solver_->getSolutionGroup().getX()
).getThyraVector()
);
//u_old_ = get_Epetra_Vector (*f_owned_map_,Teuchos::rcp_const_cast< ::Thyra::VectorBase< double > >(Teuchos::rcpFromRef(*sol)) );
Thyra::ConstDetachedSpmdVectorView<double> x_vec(sol->col(0));
for (int nn=0; nn < mesh_->get_num_nodes(); nn++) {//cn figure out a better way here...
(*u_old_)[nn]=x_vec[nn];
}
//u_old_->Print(std::cout);
time_ +=dt_;
}
template<class Scalar>
void ModelEvaluatorHEAT<Scalar>::initialize()
{
double pi = 3.141592653589793;
for (int nn=0; nn < mesh_->get_num_nodes(); nn++) {
double x = mesh_->get_x(nn);
double y = mesh_->get_y(nn);
(*u_old_)[nn]=sin(pi*x)*sin(pi*y);
//std::cout<<nn<<" "<<x<<" "<<y<<std::endl;
}
//exit(0);
}
template<class Scalar>
void ModelEvaluatorHEAT<Scalar>::finalize()
{
double outputdata[mesh_->get_num_nodes()];
for (int nn=0; nn < mesh_->get_num_nodes(); nn++) {
outputdata[nn]=(*u_old_)[nn];
//std::cout<<nn<<" "<<outputdata[nn]<<" "<<std::endl;
}
//cout<<"norm = "<<sqrt(norm)<<endl;
const char *outfilename = "results.e";
mesh_->add_nodal_data("u", &outputdata[0]);
mesh_->write_exodus(outfilename);
compute_error(&outputdata[0]);
std::cout<<"finalize() completed"<<std::endl;
}
template<class Scalar>
void ModelEvaluatorHEAT<Scalar>::compute_error( double *u)
{
double error = 0.;
double jac;
double *xx, *yy;
double *uu;
int n_nodes_per_elem, nodeid;
Basis *ubasis;
for(int blk = 0; blk < mesh_->get_num_elem_blks(); blk++){
n_nodes_per_elem = mesh_->get_num_nodes_per_elem_in_blk(blk);
std::string elem_type=mesh_->get_blk_elem_type(blk);
if( (0==elem_type.compare("QUAD4")) || (0==elem_type.compare("QUAD")) ){ // linear quad
ubasis = new BasisLQuad;
}
else if( (0==elem_type.compare("TRI3")) || (0==elem_type.compare("TRI")) ){ // linear triangle
ubasis = new BasisLTri;
}
else if( (0==elem_type.compare("HEX8")) || (0==elem_type.compare("HEX")) ){ // linear hex
ubasis = new BasisLHex;
}
else if( (0==elem_type.compare("TETRA4")) || (0==elem_type.compare("TETRA")) ){ // linear tet
ubasis = new BasisLTet;
}
else if( (0==elem_type.compare("QUAD9")) || (0==elem_type.compare("quad9")) ){ // quadratic quad
ubasis = new BasisQQuad;
}
else if( (0==elem_type.compare("TRI6")) || (0==elem_type.compare("tri6")) ){ // quadratic triangle
ubasis = new BasisQTri;
}
else {
std::cout<<"Unsupported element type"<<std::endl<<std::endl;
exit(0);
}
xx = new double[n_nodes_per_elem];
yy = new double[n_nodes_per_elem];
uu = new double[n_nodes_per_elem];
// Loop Over # of Finite Elements on Processor
for (int ne=0; ne < mesh_->get_num_elem_in_blk(blk); ne++) {
for(int k = 0; k < n_nodes_per_elem; k++){
nodeid = mesh_->get_node_id(blk, ne, k);
xx[k] = mesh_->get_x(nodeid);
yy[k] = mesh_->get_y(nodeid);
uu[k] = u[nodeid]; // copy initial guess or old solution into local temp
//std::cout<<"u "<<uu[k]<<std::endl;
}//k
// Loop Over Gauss Points
for(int gp=0; gp < ubasis->ngp; gp++) {
// Calculate the basis function at the gauss point
ubasis->getBasis(gp, xx, yy, NULL, uu);
// Loop over Nodes in Element
double x = ubasis->xx;
double y = ubasis->yy;
//double divgradu = ubasis->dudx*dphidx + ubasis->dudy*dphidy;//(grad u,grad phi)
//double ut = (ubasis->uu)/dt_*ubasis->phi[i];
double pi = 3.141592653589793;
//double ff = 2.*ubasis->phi[i];
double u_ex = sin(pi*x)*sin(pi*y)*exp(-2.*pi*pi*time_);
//double u_ex = -x*(x-1.);
error += ubasis->jac * ubasis->wt * ( ((ubasis->uu)- u_ex)*((ubasis->uu)- u_ex));
//std::cout<<(ubasis->uu)<<" "<<u_ex<<" "<<(ubasis->uu)- u_ex<<std::endl;
}//gp
}//ne
}//blk
std::cout<<"num dofs "<<mesh_->get_num_nodes()<<" num elem "<<mesh_->get_num_elem()<<" error is "<<sqrt(error)<<std::endl;
delete xx;
delete yy;
delete uu;
delete ubasis;
}
#endif
|
//
// Created by tony on 2017/05/27.
//
#include <iostream>
#include "Player.h"
Player::Player(): _iHp(0), _iArmor(0), _sName(""), _sWeapon(""), _pY(0), _Px(0) {
std::cout << "A player was created\n";
}
Player::Player(std::string name, int hp, int armor, std::string weapon): _sName(name), _iHp(hp), _iArmor(armor), _sWeapon(weapon) {
std::cout << "A player was created\n";
}
Player::~Player() {
std::cout << "A Player Has Died\n";
}
int Player::get_iHp() const {
return _iHp;
}
void Player::set_iHp(int _iHp) {
Player::_iHp = _iHp;
}
int Player::get_iArmor() const {
return _iArmor;
}
void Player::set_iArmor(int _iArmor) {
Player::_iArmor = _iArmor;
}
const std::string &Player::get_sWeapon() const {
return _sWeapon;
}
void Player::set_sWeapon(const std::string &_sWeapon) {
Player::_sWeapon = _sWeapon;
}
const std::string &Player::get_sName() const {
return _sName;
}
void Player::set_sName(const std::string &_sName) {
Player::_sName = _sName;
}
int Player::get_Px() const {
return _Px;
}
void Player::set_Px(int _Px) {
Player::_Px = _Px;
}
int Player::get_pY() const {
return _pY;
}
void Player::set_pY(int _pY) {
Player::_pY = _pY;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2006 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#include "core/pch.h"
#include "modules/util/objfactory.h"
#include "modules/hardcore/mh/messages.h"
#include "modules/hardcore/mem/mem_man.h"
#include "modules/hardcore/mh/mh.h"
#include "modules/url/protocols/comm.h"
#include "modules/url/protocols/scomm.h"
template <class OBJECT>
OpObjectFactory<OBJECT>::OpObjectFactory()
: size(0),
capacity(0),
id(0),
refill_failed(FALSE),
oom_condition_raised(FALSE),
post_critical_section(FALSE)
{
}
template <class OBJECT>
OpObjectFactory<OBJECT>::~OpObjectFactory()
{
g_main_message_handler->RemoveDelayedMessage(MSG_OBJ_FACTORY_REFILL, id, 0);
g_main_message_handler->UnsetCallBack(this, MSG_OBJ_FACTORY_REFILL, id);
while (size > 0) {
OBJECT *obj = (OBJECT*)cache.First();
obj->Out();
delete obj;
size--;
}
}
template <class OBJECT>
void OpObjectFactory<OBJECT>::ConstructL( size_t requested_capacity )
{
OP_ASSERT( !id );
capacity = requested_capacity;
while (size < capacity)
{
OBJECT *obj = new OBJECT;
LEAVE_IF_NULL(obj);
obj->Into(&cache);
size++;
}
int tmpid = ++g_unique_id_counter;
LEAVE_IF_ERROR(g_main_message_handler->SetCallBack( this, MSG_OBJ_FACTORY_REFILL, tmpid));
// Now we're ready.
id = tmpid;
}
template <class OBJECT>
OBJECT *
OpObjectFactory<OBJECT>::Allocate()
{
OBJECT *obj;
OP_ASSERT( id );
if (refill_failed)
PostRefill();
obj = new OBJECT;
if (obj != NULL)
return obj;
if (size < capacity/2)
{
BOOL f = !oom_condition_raised;
oom_condition_raised = TRUE;
if (f)
g_memory_manager->RaiseCondition( OpStatus::ERR_NO_MEMORY );
}
if (size == 0)
return NULL;
size--; // Take the element now so that PostRefill() does not take it.
obj = (OBJECT*)cache.First();
obj->Out();
if (size == capacity-1)
PostRefill();
return obj;
}
template <class OBJECT>
void OpObjectFactory<OBJECT>::HandleCallback(OpMessage /*msg*/, MH_PARAM_1 /*par1*/, MH_PARAM_2 /*par2*/)
{
OP_ASSERT( id );
while (size < capacity)
{
OBJECT *obj = new OBJECT;
if (obj == NULL) {
PostRefill();
return;
}
obj->Into(&cache);
size++;
}
oom_condition_raised = FALSE; // Don't clear until we've managed to refill completely
}
template <class OBJECT>
void
OpObjectFactory<OBJECT>::PostRefill()
{
if (post_critical_section)
return;
post_critical_section = TRUE;
refill_failed = FALSE; // Clear the flag first to avoid a storm
if (!g_main_message_handler->PostDelayedMessage( MSG_OBJ_FACTORY_REFILL, id, 0, OBJFACTORY_REFILL_INTERVAL ))
refill_failed = TRUE;
post_critical_section = FALSE;
}
template class OpObjectFactory<CommWaitElm>;
template class OpObjectFactory<SCommWaitElm>;
|
/*
* =====================================================================================
*
* Filename: instructions.cpp
*
* Description: Instructions execution for MIPS Super-scalar processor
*
* Version: 1.0
* Created: Wednesday 14 November 2012 07:59:45 IST
* Revision: none
* Compiler: gcc
*
* Author: Vaibhav Agarwal , vaisci310@gmail.com
* Points Learnt :
*
* =====================================================================================
*/
#include <iostream>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "instructions.h"
#include "registerFile.h"
#include "storeBuffer.h"
using namespace std;
/* --------------------- Instruction class dummy instructions --------------------------------- */
Instruction::Instruction( unsigned int ins )
{
instruction = ins;
}
Instruction::Instruction ( )
{
instruction = -1;
}
insInfo Instruction::IDstage(int PC , RegisterFile & intRegisterFile , ROB & rob )
{
insInfo object;
object.branch = false;
object.nextPC = PC + 1 ;
return object;
}
int Instruction::execute ( int stage , int op1 , int op2 ,int PC )
{
return 0;
}
void Instruction::commit ( RegisterFile & intRegisterFile , int destination , StoreBuffer & storeBuffer , int * memory )
{
return;
}
bool Instruction::canExecute ( int stage , funcUnit & FUnit )
{
return true;
}
bool Instruction::lastStage ( int stage )
{
return false;
}
insInfo Instruction::getDetails()
{
return insSet;
}
int Instruction::computeValue ( int op1 , int op2 , int PC )
{
return 0;
}
int Instruction::random ()
{
return 1;
}
/* ---------------------- Instruction class dummy instructions end -------------------------------------- */
/* ---------------------- JInstruction class functions ------------------------------------------------ */
JInstruction::JInstruction ( unsigned int ins )
: Instruction(ins)
{
unsigned int base = pow(2,26);
offset = ins % base;
opcode = ins / base;
addFlag = 1;
}
int JInstruction::randomMax()
{
return 1;
}
JInstruction::JInstruction ()
{
value = 0;
}
insInfo JInstruction::IDstage( int PC , RegisterFile & intRegisterFile , ROB & rob )
{
insSet.branch = true;
if ( opcode == 2 )
{
insSet.doesWrite = false;
insSet.nextPC = offset;
insSet.op1tag = true;
insSet.op2tag = true;
return insSet;
}
else if ( opcode == 3 )
{
insSet.doesWrite = true;
insSet.nextPC = offset;
insSet.op1tag = true;
insSet.op2tag = true;
return insSet;
}
else
return insSet;
}
void JInstruction::commit( RegisterFile & intRegisterFile , int destination , StoreBuffer & storeBuffer , int * memory )
{
if ( opcode == 2 )
return;
else
{
intRegisterFile.updateRegisters ( 31 , offset );
return;
}
}
// Since the return address is always given at the ID stage itself , we just have to return -1 and not the next PC
int JInstruction::execute ( int stage , int op1 , int op2 , int PC )
{
return -1;
}
bool JInstruction::canExecute(int stage , funcUnit & FUnit)
{
return 1;
}
bool JInstruction::lastStage ( int stage )
{
return 1;
}
insInfo JInstruction::getDetails()
{
return insSet;
}
int JInstruction::computeValue ( int op1 , int op2 , int PC )
{
return offset;
}
/* ---------------------- JInstruction class functions end ------------------------------------------------ */
/* ---------------------- IInstruction class functions ------------------------------------------------ */
IInstruction::IInstruction ( unsigned int ins ) : Instruction ( ins )
{
int temp = ins;
unsigned int base = pow(2,16);
immediate = temp % base;
temp = temp / base;
second = temp % 32;
temp = temp / 32;
source = temp % 32;
temp = temp / 32;
opcode = temp;
addFlag = 1;
//cout << "I ins :" << opcode << " " << source << " " << second << " " << immediate << endl;
}
IInstruction::IInstruction()
{
value = 0;
}
insInfo IInstruction::IDstage ( int PC , RegisterFile & intRegisterFile , ROB & rob )
{
if ( opcode < 8 )
{
insSet.branch = true;
if ( intRegisterFile.isValid(source , rob) && intRegisterFile.isValid(second , rob) )
{
switch(opcode)
{
case 4:
if ( intRegisterFile.getValue(source, rob) == intRegisterFile.getValue(second, rob) )
insSet.nextPC = PC+immediate;
else
insSet.nextPC = PC+1;
case 5:
if ( intRegisterFile.getValue(source, rob) != intRegisterFile.getValue(second, rob) )
insSet.nextPC = PC+immediate;
else
insSet.nextPC = PC+1;
case 6:
if ( intRegisterFile.getValue(source, rob) <= 0 )
insSet.nextPC = PC+immediate;
else
insSet.nextPC = PC+1;
case 7:
if ( intRegisterFile.getValue(source, rob) >= 0 )
insSet.nextPC = PC+immediate;
else
insSet.nextPC = PC+1;
}
}
else
{
addFlag = false;
insSet.nextPC = -1769;
if ( intRegisterFile.isValid(source , rob) )
{
insSet.op1 = intRegisterFile.getValue(source, rob);
insSet.op2 = intRegisterFile.getTag(second);
insSet.op1tag = true;
insSet.op2tag = false;
}
else
{
insSet.op1 = intRegisterFile.getTag(source);
insSet.op1tag = false;
if ( intRegisterFile.isValid ( second , rob) )
{
insSet.op2 = intRegisterFile.getValue ( second , rob);
insSet.op2tag = true;
}
else
{
insSet.op2 = intRegisterFile.getTag(second);
insSet.op2tag = false;
}
}
insSet.doesWrite = false;
insSet.destination = -1;
}
}
else if ( opcode < 16 )
{
insSet.branch = false;
insSet.doesWrite = true;
insSet.destination = second;
if ( intRegisterFile.isValid ( source , rob) )
{
insSet.op1 = intRegisterFile.getValue(source, rob);
insSet.op1tag = true;
}
else
{
insSet.op1 = intRegisterFile.getTag ( source );
insSet.op1tag = false;
}
if ( intRegisterFile.isValid ( second , rob) )
{
insSet.op2 = intRegisterFile.getValue ( second , rob);
insSet.op2tag = true;
}
else
{
insSet.op2 = intRegisterFile.getTag(second);
insSet.op2tag = false;
}
insSet.nextPC = PC + 1;
}
else if ( opcode < 40 )
{
insSet.branch = false;
insSet.doesWrite = true;
if ( intRegisterFile.isValid( source , rob) )
{
insSet.op1 = intRegisterFile.getValue ( source , rob);
insSet.op1tag = true;
}
else
{
insSet.op1 = intRegisterFile.getTag ( source );
insSet.op1tag = false;
}
insSet.op2 = 0;
insSet.op2tag = true;
insSet.destination = second;
}
else
{
insSet.branch = false;
insSet.doesWrite = false;
if ( intRegisterFile.isValid( source , rob) )
{
insSet.op1 = intRegisterFile.getValue ( source , rob);
insSet.op1tag = true;
}
else
{
insSet.op1 = intRegisterFile.getTag ( source );
insSet.op1tag = false;
}
if ( intRegisterFile.isValid( second , rob) )
{
insSet.op2 = intRegisterFile.getValue ( second , rob);
insSet.op2tag = true;
}
else
{
insSet.op2 = intRegisterFile.getTag ( second );
insSet.op2tag = false;
}
}
return insSet;
}
int IInstruction::randomMax2()
{
return 1;
}
insInfo IInstruction::getDetails ( )
{
return insSet;
}
bool IInstruction::lastStage (int stage)
{
if ( opcode < 8 )
return true;
else if ( opcode < 10 )
{
if ( stage == ADD_LATENCY )
{
return true;
}
else
return false;
}
else if ( opcode < 16 )
{
if ( stage == BIT_LATENCY )
return true;
else
return false;
}
else
{
if ( stage == ADD_LATENCY )
return true;
else
return false;
}
}
bool IInstruction::canExecute(int stage , funcUnit & FUnit)
{
if ( opcode < 8 )
return true;
else if ( opcode < 10 )
{
for ( int i = 0 ; i < ADD_ALU ; i++ )
{
if ( FUnit.add[i][stage-1] == 0 )
{
FUnit.add[i][stage-1] = 1;
return true;
}
}
return false;
}
else if ( opcode < 16 )
{
for ( int i = 0 ; i < BIT_ALU ; i++ )
{
if ( FUnit.bitOp[i][stage-1] == 0 )
{
FUnit.bitOp[i][stage-1] = 1;
return true;
}
}
return false;
}
else
{
for ( int i = 0 ; i < ADD_ALU ; i++ )
{
if ( FUnit.add[i][stage-1] == 0 )
{
FUnit.add[i][stage-1] = 1;
return true;
}
}
return false;
}
}
int IInstruction::computeValue ( int op1 , int op2 , int PC )
{
switch(opcode)
{
case 4:
if ( op1 == op2 )
return immediate;
else
return PC+1;
case 5:
if ( op1 != op2 )
return immediate;
else
return PC+1;
case 6:
if ( op1 < 0 )
return immediate;
else
return PC+1;
case 7:
if ( op1 > 0 )
return PC+1;
case 8:
return op1+immediate;
case 9:
return op1+immediate;
case 10:
return op1 < op2;
case 11:
return op1 < op2;
case 12:
return op1 && immediate;
case 13:
return op1 || immediate;
case 14:
return op1 ^ immediate;
case 32:
case 33:
case 35:
case 36:
case 37:
case 40:
case 41:
case 43:
return op1 + immediate;
default:
{
cout << "Wrong opcode for I type instructions . Computing value of a opcode unknown";
exit(-1);
}
}
}
int IInstruction::execute ( int stage , int op1 , int op2 , int PC )
{
if ( ! lastStage(stage) )
return -1;
else
{
value = computeValue ( op1 , op2 , PC );
if ( opcode > 39 )
tempStore = op2;
if ( addFlag && opcode >= 8 )
return value;
else if ( addFlag && opcode < 8 )
return -1;
else if ( !addFlag )
return value;
else
return value;
}
}
void IInstruction::commit( RegisterFile & intRegisterFile , int destination , StoreBuffer & storeBuffer , int * memory )
{
if ( opcode < 8 )
return;
if ( opcode < 32 )
intRegisterFile.updateRegisters ( destination , value );
else if ( opcode == 32 )
{
if ( storeBuffer.isValueUpdated ( value ) )
{
intRegisterFile.updateRegisters ( destination , storeBuffer.loadForwardingValue ( value ) );
}
else
{
intRegisterFile.updateRegisters ( destination , memory[value/4] );
}
}
else if ( opcode == 34 )
{
int temp = 0;
for ( int i = 0 ; i < 4 ; i++ )
{
if ( storeBuffer.isValueUpdated ( value+i ) )
temp = temp *2+storeBuffer.loadForwardingValue ( value+i ) ;
else
temp = temp*2+ memory[value+i];
}
intRegisterFile.updateRegisters ( destination , temp );
}
else if ( opcode == 40 )
storeBuffer.addFinishedStore ( value/4 , tempStore );
else if ( opcode == 42 )
{
for ( int i = 0 ; i < 4 ; i++ )
storeBuffer.addFinishedStore ( value+i , tempStore );
}
}
/* ---------------------- IInstruction class functions end ------------------------------------------------ */
/* ---------------------- RInstruction class functions ------------------------------------------------ */
RInstruction::RInstruction ( unsigned int ins ): Instruction ( ins )
{
int temp = ins;
unsigned int base = pow(2,6);
func = ins % base;
temp = temp / base;
base = base/2;
shamt = temp % base;
temp = temp / base;
destination = temp % base;
temp = temp / base;
second = temp % base;
temp = temp / base;
source = temp % base;
opcode = temp / base;
//cout << " R Ins : " << opcode << " " << source << " " << second << " " << destination << " " << shamt << " " << func << endl;
}
RInstruction::RInstruction()
{
value = 0;
}
insInfo RInstruction::IDstage(int PC , RegisterFile & intRegisterFile , ROB & rob )
{
insSet.branch = false;
insSet.nextPC = PC + 1;
if ( func == 0 || func == 2 )
{
insSet.op1 = -1;
insSet.op1tag = true;
}
else
{
if ( intRegisterFile.isValid( source , rob) )
{
insSet.op1 = intRegisterFile.getValue ( source , rob);
insSet.op1tag = true;
}
else
{
insSet.op1tag = false;
insSet.op1 = intRegisterFile.getTag ( source );
}
}
if ( intRegisterFile.isValid( second , rob) )
{
insSet.op2 = intRegisterFile.getValue ( second , rob);
insSet.op2tag = true;
}
else
{
insSet.op2tag = false;
insSet.op2 = intRegisterFile.getTag ( second );
}
insSet.destination = destination;
insSet.doesWrite = true;
return insSet;
}
insInfo RInstruction::getDetails ()
{
return insSet;
}
bool RInstruction::canExecute(int stage , funcUnit & FUnit)
{
if ( func == 32 || func == 33 || func == 34 || func == 35 )
{
for ( int i = 0; i < ADD_ALU ; i++ )
{
if ( FUnit.add[i][stage-1] == 0 )
{
FUnit.add[i][stage-1] = 1;
return true;
}
}
return false;
}
else if ( func > 35 || func < 8 )
{
for ( int j = 0 ; j < BIT_ALU ; j++ )
{
if ( FUnit.bitOp[j][stage-1] == 0 )
{
FUnit.bitOp[j][stage-1] = 1;
return true;
}
}
return false;
}
else if ( func > 15 && func < 26 )
{
for ( int j = 0; j < MUL_ALU ; j++ )
{
if ( FUnit.mul[j][stage-1] == 0 )
{
FUnit.mul[j][stage-1] = 1;
return true;
}
}
return false;
}
else if ( func == 26 || func == 27 )
{
for ( int j = 0; j < DIV_ALU ; j++ )
{
if ( FUnit.div[j][stage-1] == 0 )
{
FUnit.div[j][stage-1] = 1;
return true;
}
}
return false;
}
cout << "Instruction not in any R type. Jr or Jalr found !! Not supported ";
exit(-1);
}
bool RInstruction::lastStage ( int stage )
{
if ( func < 8 || func > 35 )
{
if ( stage == BIT_LATENCY )
return true;
else
return false;
}
else if ( func >= 32 )
{
if ( stage == ADD_LATENCY )
return true;
else
return false;
}
else if ( func == 26 || func == 27 )
{
if ( stage == DIV_LATENCY )
return true;
else
return false;
}
else
{
if ( stage == MUL_LATENCY )
return true;
else
return false;
}
}
int RInstruction::computeValue ( int op1 , int op2 , int PC )
{
switch(func)
{
case 0:
return op2<<shamt;
case 2:
return op2>>shamt;
case 3:
return op2>>shamt;
case 4:
return op2<<op1;
case 6:
return op2>>op1;
case 7:
return op2>>op1;
case 8:
return -1;
case 9:
return op1;
case 17:
return op1;
case 19:
return op1;
case 24:
return op1*op2;
case 25:
return op1*op2;
case 26:
return op1/op2;
case 27:
return op1/op2;
case 32:
return op1+op2;
case 33:
return op1+op2;
case 34:
return op1-op2;
case 35:
return op1-op2;
case 36:
return op1&op2;
case 37:
return op1|op2;
case 38:
return op1^op2;
case 39:
return ~(op1|op2);
case 42:
return op1<op2;
case 43:
return op1<op2;
default:
cout << "Function opcode not found in the list . Wrong function code given : " << func << endl;
}
return -2;
}
int RInstruction::execute ( int stage , int op1 , int op2 , int PC )
{
if ( ! lastStage ( stage ) )
return 1;
else
{
value = computeValue ( op1 , op2 , PC );
return value;
}
}
void RInstruction::commit ( RegisterFile & intRegisterFile, int destination , StoreBuffer & storeBuffer , int * memory )
{
intRegisterFile.updateRegisters ( destination , value );
}
int RInstruction::randomDoubleMax()
{
return 1;
}
/* ---------------------- RInstruction class functions end ------------------------------------------------ */
|
#pragma once
#ifndef __WINDOWHEADER_H_
#define __WINDOWHEADER_H_
#include <windows.h>
#include <commctrl.h>
#include <olectl.h>
#include <ocidl.h>
#include <ole2.h>
#include <tchar.h>
#include <math.h>
#include <oleacc.h>
//#pragma comment(lib, "oleacc.lib")
////////////////////////////////////////////////////////////////
// 定义ATL
////////////////////////////////////////////////////////////////
// Change these values to use different versions
//#define WINVER 0x0500
//#define _WIN32_WINNT 0x0501
//#define _WIN32_IE 0x0501
//#define _RICHEDIT_VER 0x0500
#define _WTL_NO_CSTRING
#define _WTL_NO_WTYPES
#define _CSTRING_NS
#define _WTYPES_NS
#include <atlstr.h>
#include <atlbase.h>
#include <atlapp.h>
extern CAppModule _Module;
#include <atlwin.h>
#include <atlframe.h>
#include <atlctrls.h>
#include <atlctrlx.h>
#include <atldlgs.h>
#include <atlddx.h>
#include <atlcrack.h>
#include <atlctrlw.h>
#include <atlmisc.h>
#include <atltypes.h>
////////////////////////////////////////////////////////////////
#include <gdiplus.h>
//#pragma comment (lib, "gdiplus.lib")
#include <gl/gl.h>
//#pragma comment (lib, "opengl32.lib")
#include <map>
#include <vector>
#include "MACROS.h"
namespace PPSHUAI
{
namespace NearSideAutoHide{
#define NEAR_SIZE 1 //定义自动停靠有效距离
#define NEAR_SIDE 1 //窗体隐藏后在屏幕上保留的像素,以使鼠标可以触及
#define IDC_TIMER_NEARSIDEHIDE 0xFFFF
#define T_TIMEOUT_NEARSIDEHIDE 0xFF
enum {
ALIGN_NONE, //不停靠
ALIGN_TOP, //停靠上边
ALIGN_LEFT, //停靠左边
ALIGN_RIGHT //停靠右边
};
static int g_nScreenX = 0;
static int g_nScreenY = 0;
static int g_nAlignType = ALIGN_NONE; //全局变量,用于记录窗体停靠状态
__inline static void InitScreenSize()
{
g_nScreenX = ::GetSystemMetrics(SM_CXSCREEN);
g_nScreenY = ::GetSystemMetrics(SM_CYSCREEN);
}
//在窗体初始化是设定窗体状态,如果可以停靠,便停靠在边缘
//我本想寻求其他方法来解决初始化,而不是为它专一寻求一个函数,
//可是,窗体初始化时不发送WM_MOVING消息,我不得不重复类似任务.
__inline static void NearSide(HWND hWnd, LPRECT lpRect)
{
LONG Width = lpRect->right - lpRect->left;
LONG Height = lpRect->bottom - lpRect->top;
BOOL bChange = 0;
g_nAlignType = ALIGN_NONE;
if (lpRect->left < NEAR_SIZE)
{
g_nAlignType = ALIGN_LEFT;
if ((lpRect->left != 0) && lpRect->right != NEAR_SIDE)
{
lpRect->left = 0;
lpRect->right = Width;
bChange = FALSE;
}
}
else if (lpRect->right > g_nScreenX - NEAR_SIZE)
{
g_nAlignType = ALIGN_RIGHT;
if (lpRect->right != g_nScreenX && lpRect->left != g_nScreenX - NEAR_SIDE)
{
lpRect->right = g_nScreenX;
lpRect->left = g_nScreenX - Width;
bChange = FALSE;
}
}
//调整上
else if (lpRect->top < NEAR_SIZE)
{
g_nAlignType = ALIGN_TOP;
if (lpRect->top != 0 && lpRect->bottom != NEAR_SIDE)
{
lpRect->top = 0;
lpRect->bottom = Height;
bChange = FALSE;
}
}
if (bChange)
{
::MoveWindow(hWnd, lpRect->left, lpRect->top, lpRect->right - lpRect->left, lpRect->bottom - lpRect->top, bChange);
}
}
//窗体的显示隐藏由该函数完成,参数bHide决定显示还是隐藏.
__inline static void AutoHideProc(HWND hWnd, LPRECT lpRect, BOOL bHide)
{
int nStep = 20; //动画滚动窗体的步数,如果你觉得不够平滑,可以增大该值.
int xStep = 0, xEnd = 0;
int yStep = 0, yEnd = 0;
LONG Width = lpRect->right - lpRect->left;
LONG Height = lpRect->bottom - lpRect->top;
//下边判断窗体该如何移动,由停靠方式决定
switch (g_nAlignType)
{
case ALIGN_TOP:
{
//向上移藏
xStep = 0;
xEnd = lpRect->left;
if (bHide)
{
yStep = -lpRect->bottom / nStep;
yEnd = -Height + NEAR_SIDE;
}
else
{
yStep = -lpRect->top / nStep;
yEnd = 0;
}
break;
}
case ALIGN_LEFT:
{
//向左移藏
yStep = 0;
yEnd = lpRect->top;
if (bHide)
{
xStep = -lpRect->right / nStep;
xEnd = -Width + NEAR_SIDE;
}
else
{
xStep = -lpRect->left / nStep;
xEnd = 0;
}
break;
}
case ALIGN_RIGHT:
{
//向右移藏
yStep = 0;
yEnd = lpRect->top;
if (bHide)
{
xStep = (g_nScreenX - lpRect->left) / nStep;
xEnd = g_nScreenX - NEAR_SIDE;
}
else
{
xStep = (g_nScreenX - lpRect->right) / nStep;
xEnd = g_nScreenX - Width;
}
break;
}
default:
return;
}
//动画滚动窗体.
for (int i = 0; i < nStep; i++)
{
lpRect->left += xStep;
lpRect->top += yStep;
::SetWindowPos(hWnd, NULL, lpRect->left, lpRect->top, 0, 0, SWP_NOSIZE | SWP_NOSENDCHANGING);
::RedrawWindow(hWnd, NULL, NULL, RDW_INVALIDATE | RDW_UPDATENOW);
Sleep(3);
}
::SetWindowPos(hWnd, NULL, xEnd, yEnd, 0, 0, SWP_NOSIZE | SWP_NOSENDCHANGING);
if (!bHide) //如果窗体已被显示,设置定时器.监视鼠标.
{
::SetTimer(hWnd, WM_TIMER, WAIT_TIMEOUT, NULL);
}
}
// WM_TIMER
__inline static LRESULT OnTimer(HWND hWnd, UINT uTimerID)
{
LRESULT lResult = FALSE;
switch (uTimerID)
{
case IDC_TIMER_NEARSIDEHIDE:
{
RECT rc = { 0 };
POINT pt = { 0 };
::GetCursorPos(&pt);
::GetWindowRect(hWnd, &rc);
if (!PtInRect(&rc, pt)) //若鼠标不在窗体内,隐藏窗体.
{
::KillTimer(hWnd, uTimerID);
AutoHideProc(hWnd, &rc, TRUE);
}
lResult = TRUE;
}
break;
default:
{
//no-op
}
break;
}
return lResult;
}
// WM_NCMOUSEMOVE
__inline static LRESULT OnNcMouseMove(HWND hWnd)
{
RECT rc = { 0 };
::GetWindowRect(hWnd, &rc);
if (rc.left < 0 || rc.top < 0 || rc.right > g_nScreenX) //未显示
{
AutoHideProc(hWnd, &rc, FALSE);
}
else
{
::SetTimer(hWnd, IDC_TIMER_NEARSIDEHIDE, T_TIMEOUT_NEARSIDEHIDE, NULL);
}
return 0;
}
// WM_MOUSEMOVE
__inline static LRESULT OnMouseMove(HWND hWnd)
{
RECT rc = { 0 };
::GetWindowRect(hWnd, &rc);
if (rc.left < 0 || rc.top < 0 || rc.right > g_nScreenX) //未显示
{
AutoHideProc(hWnd, &rc, FALSE);
}
else
{
::SetTimer(hWnd, IDC_TIMER_NEARSIDEHIDE, T_TIMEOUT_NEARSIDEHIDE, NULL);
}
return 0;
}
// WM_ENTERSIZEMOVE
__inline static LRESULT OnEnterSizeMove(HWND hWnd)
{
::KillTimer(hWnd, IDC_TIMER_NEARSIDEHIDE);
return 0;
}
// WM_EXITSIZEMOVE
__inline static LRESULT OnExitSizeMove(HWND hWnd)
{
::SetTimer(hWnd, IDC_TIMER_NEARSIDEHIDE, T_TIMEOUT_NEARSIDEHIDE, NULL);
return 0;
}
/////////////////////////////////////////////////////////////
// WM_MOVING
//下面代码处理窗体消息WM_MOVING,lParam是参数RECT指针
__inline static LRESULT OnMoving(HWND hWnd, LPARAM lParam)
{
POINT pt = { 0 };
LPRECT lpRect = (LPRECT)lParam;
LONG Width = lpRect->right - lpRect->left;
LONG Height = lpRect->bottom - lpRect->top;
//未靠边界由pRect测试
if (g_nAlignType == ALIGN_NONE)
{
if (lpRect->left < NEAR_SIZE) //在左边有效距离内
{
g_nAlignType = ALIGN_LEFT;
lpRect->left = 0;
lpRect->right = Width;
}
if (lpRect->right + NEAR_SIZE > g_nScreenX) //在右边有效距离内,g_nScreenX为屏幕宽度,可由GetSystemMetrics(SM_CYSCREEN)得到。
{
g_nAlignType = ALIGN_RIGHT;
lpRect->right = g_nScreenX;
lpRect->left = g_nScreenX - Width;
}
if (lpRect->top < NEAR_SIZE) //在上边有效距离内,自动靠拢。
{
g_nAlignType = ALIGN_TOP;
lpRect->top = 0;
lpRect->bottom = Height;
}
}
else
{
//靠边界由鼠标控制
::GetCursorPos(&pt);
if (g_nAlignType == ALIGN_TOP)
{
lpRect->top = 0;
lpRect->bottom = Height;
if (pt.y > NEAR_SIZE) //鼠标在离开上边界解除上部停靠。
{
g_nAlignType = ALIGN_NONE;
}
else
{
if (lpRect->left < NEAR_SIZE) //在上部停靠时,我们也考虑左右边角。
{
lpRect->left = 0;
lpRect->right = Width;
}
else if (lpRect->right + NEAR_SIZE > g_nScreenX)
{
lpRect->right = g_nScreenX;
lpRect->left = g_nScreenX - Width;
}
}
}
if (g_nAlignType == ALIGN_LEFT)
{
lpRect->left = 0;
lpRect->right = Width;
if (pt.x > NEAR_SIZE) //鼠标在鼠标离开左边界时解除停靠。
{
g_nAlignType = ALIGN_NONE;
}
else
{
if (lpRect->top < NEAR_SIZE) //考虑左上角。
{
lpRect->top = 0;
lpRect->bottom = Height;
}
}
}
else if (g_nAlignType == ALIGN_RIGHT)
{
lpRect->left = g_nScreenX - Width;
lpRect->right = g_nScreenX;
if (pt.x < g_nScreenX - NEAR_SIZE) //当鼠标离开右边界时,解除停靠。
{
g_nAlignType = ALIGN_NONE;
}
else
{
if (lpRect->top < NEAR_SIZE) //考虑右上角。
{
lpRect->top = 0;
lpRect->bottom = Height;
}
}
}
}
return 0;
}
}
namespace GdiplusDisplay{
static ULONG_PTR gdiplusToken = 0;
void GdiplusInitialize()
{
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
Gdiplus::GdiplusStartupOutput gdiplusStartupOutput;
// START GDI+ SUB SYSTEM
Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, &gdiplusStartupOutput);
}
void GdiplusExitialize()
{
// Shutdown GDI+ subystem
Gdiplus::GdiplusShutdown(gdiplusToken);
}
}
namespace ShadowWindow{
#ifndef WS_EX_LAYERED
#define MY_WS_EX_LAYERED 0x00080000
#else
#define MY_WS_EX_LAYERED WS_EX_LAYERED
#endif
#ifndef AC_SRC_ALPHA
#define MY_AC_SRC_ALPHA 0x01
#else
#define MY_AC_SRC_ALPHA AC_SRC_ALPHA
#endif
#ifndef ULW_ALPHA
#define MY_ULW_ALPHA 0x00000002
#else
#define MY_ULW_ALPHA ULW_ALPHA
#endif
const _TCHAR * G_ptszWndClassName = _T("PPSHUAISHADOWWINDOW");
class CShadowBorder
{
public:
CShadowBorder(void)
: m_hWnd((HWND)INVALID_HANDLE_VALUE)
, m_OriginParentProc(NULL)
, m_nDarkness(150)
, m_nSharpness(5)
, m_nSize(0)
, m_nxOffset(5)
, m_nyOffset(5)
, m_Color(RGB(0, 0, 0))
, m_WndSize(0)
, m_bUpdateShadow(false)
{
}
public:
virtual ~CShadowBorder(void)
{
}
protected:
// Instance handle, used to register window class and create window
static HINSTANCE m_hInstance;
// Parent HWND and CShadowBorder object pares, in order to find CShadowBorder in ParentProc()
static std::map<HWND, PVOID> m_ShadowWindowMap;
//
typedef BOOL(WINAPI *pfnUpdateLayeredWindow)(HWND hWnd, HDC hdcDst, POINT *pptDst,
SIZE *psize, HDC hdcSrc, POINT *pptSrc, COLORREF crKey,
BLENDFUNCTION *pblend, DWORD dwFlags);
static pfnUpdateLayeredWindow m_pUpdateLayeredWindow;
HWND m_hWnd;
LONG_PTR m_OriginParentProc; // Original WndProc of parent window
enum ShadowStatus
{
SS_ENABLED = 1, // Shadow is enabled, if not, the following one is always false
SS_VISABLE = 1 << 1, // Shadow window is visible
SS_PARENTVISIBLE = 1 << 2 // Parent window is visible, if not, the above one is always false
};
BYTE m_Status;
unsigned char m_nDarkness; // Darkness, transparency of blurred area
unsigned char m_nSharpness; // Sharpness, width of blurred border of shadow window
signed char m_nSize; // Shadow window size, relative to parent window size
// The X and Y offsets of shadow window,
// relative to the parent window, at center of both windows (not top-left corner), signed
signed char m_nxOffset;
signed char m_nyOffset;
// Restore last parent window size, used to determine the update strategy when parent window is resized
LPARAM m_WndSize;
// Set this to true if the shadow should not be update until next WM_PAINT is received
bool m_bUpdateShadow;
COLORREF m_Color; // Color of shadow
public:
static bool Initialize(HINSTANCE hInstance)
{
// Should not initiate more than once
if (NULL != m_pUpdateLayeredWindow)
{
return false;
}
HMODULE hUser32 = GetModuleHandle(_T("USER32.DLL"));
m_pUpdateLayeredWindow =
(pfnUpdateLayeredWindow)GetProcAddress(hUser32,
("UpdateLayeredWindow"));
// If the import did not succeed, make sure your app can handle it!
if (NULL == m_pUpdateLayeredWindow)
{
return false;
}
// Store the instance handle
m_hInstance = hInstance;
// Register window class for shadow window
WNDCLASSEX wcex;
memset(&wcex, 0, sizeof(wcex));
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = DefWindowProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = NULL;
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = G_ptszWndClassName;
wcex.hIconSm = NULL;
RegisterClassEx(&wcex);
return true;
}
void Create(HWND hParentWnd)
{
// Do nothing if the system does not support layered windows
// Already initialized
if ((NULL != m_pUpdateLayeredWindow) && (m_hInstance != INVALID_HANDLE_VALUE))
{
// Add parent window - shadow pair to the map
//_ASSERT(m_ShadowWindowMap.find((unsigned long)hParentWnd) == m_ShadowWindowMap.end()); // Only one shadow for each window
//m_ShadowWindowMap[hParentWnd] = (unsigned long)(this);
std::map<HWND, PVOID>::iterator it = m_ShadowWindowMap.find(hParentWnd);
if (it != m_ShadowWindowMap.end())
{
it->second = (PVOID)(this);
}
else
{
m_ShadowWindowMap.insert(std::map<HWND, PVOID>::value_type(hParentWnd, (this)));
}
// Create the shadow window
m_hWnd = CreateWindowEx(MY_WS_EX_LAYERED | WS_EX_TRANSPARENT, G_ptszWndClassName, NULL,
WS_VISIBLE/* | WS_CAPTION | WS_POPUPWINDOW*/,
CW_USEDEFAULT, 0, 0, 0, hParentWnd, NULL, m_hInstance, NULL);
// Determine the initial show state of shadow according to parent window's state
LONG lParentStyle = GetWindowLong(hParentWnd, GWL_STYLE);
if (!(WS_VISIBLE & lParentStyle)) // Parent invisible
{
m_Status = SS_ENABLED;
}
else if ((WS_MAXIMIZE | WS_MINIMIZE) & lParentStyle) // Parent visible but does not need shadow
{
m_Status = SS_ENABLED | SS_PARENTVISIBLE;
}
else // Show the shadow
{
m_Status = SS_ENABLED | SS_VISABLE | SS_PARENTVISIBLE;
::ShowWindow(m_hWnd, SW_SHOWNA);
UpdateShadow(hParentWnd);
}
// Replace the original WndProc of parent window to steal messages
m_OriginParentProc = ::GetWindowLongPtr(hParentWnd, GWLP_WNDPROC);
#pragma warning(disable: 4311) // temporrarily disable the type_cast warning in Win32
::SetWindowLongPtr(hParentWnd, GWLP_WNDPROC, (LONG_PTR)ParentProc);
#pragma warning(default: 4311)
}
}
bool SetSize(int NewSize = 0)
{
if (NewSize > 20 || NewSize < -20)
return false;
m_nSize = (signed char)NewSize;
if (SS_VISABLE & m_Status)
{
UpdateShadow(GetParent(m_hWnd));
}
return true;
}
bool SetSharpness(unsigned int NewSharpness = 5)
{
if (NewSharpness > 20)
{
return false;
}
m_nSharpness = (unsigned char)NewSharpness;
if (SS_VISABLE & m_Status)
{
UpdateShadow(GetParent(m_hWnd));
}
return true;
}
bool SetDarkness(unsigned int NewDarkness = 200)
{
if (NewDarkness > 255)
{
return false;
}
m_nDarkness = (unsigned char)NewDarkness;
if (SS_VISABLE & m_Status)
{
UpdateShadow(GetParent(m_hWnd));
}
return true;
}
bool SetPosition(int NewXOffset = 5, int NewYOffset = 5)
{
if (NewXOffset > 20 || NewXOffset < -20 ||
NewYOffset > 20 || NewYOffset < -20)
{
return false;
}
m_nxOffset = (signed char)NewXOffset;
m_nyOffset = (signed char)NewYOffset;
if (SS_VISABLE & m_Status)
{
UpdateShadow(GetParent(m_hWnd));
}
return true;
}
bool SetColor(COLORREF NewColor = 0)
{
m_Color = NewColor;
if (SS_VISABLE & m_Status)
{
UpdateShadow(GetParent(m_hWnd));
}
return true;
}
protected:
//static LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
static LRESULT CALLBACK ParentProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
std::map<HWND, PVOID>::iterator it = m_ShadowWindowMap.find(hwnd);
// Shadow must have been attached
if (it != m_ShadowWindowMap.end())
{
CShadowBorder *pThis = (CShadowBorder *)it->second;
switch (uMsg)
{
case WM_MOVE:
if (pThis->m_Status & SS_VISABLE)
{
RECT WndRect;
GetWindowRect(hwnd, &WndRect);
SetWindowPos(pThis->m_hWnd, 0,
WndRect.left + pThis->m_nxOffset - pThis->m_nSize, WndRect.top + pThis->m_nyOffset - pThis->m_nSize,
0, 0, SWP_NOSIZE | SWP_NOACTIVATE);
}
break;
case WM_SIZE:
if (pThis->m_Status & SS_ENABLED)
{
if (SIZE_MAXIMIZED == wParam || SIZE_MINIMIZED == wParam)
{
::ShowWindow(pThis->m_hWnd, SW_HIDE);
pThis->m_Status &= ~SS_VISABLE;
}
else if (pThis->m_Status & SS_PARENTVISIBLE) // Parent maybe resized even if invisible
{
// Awful! It seems that if the window size was not decreased
// the window region would never be updated until WM_PAINT was sent.
// So do not Update() until next WM_PAINT is received in this case
if (LOWORD(lParam) > LOWORD(pThis->m_WndSize) || HIWORD(lParam) > HIWORD(pThis->m_WndSize))
{
pThis->m_bUpdateShadow = true;
}
else
{
pThis->UpdateShadow(hwnd);
}
if (!(pThis->m_Status & SS_VISABLE))
{
::ShowWindow(pThis->m_hWnd, SW_SHOWNA);
pThis->m_Status |= SS_VISABLE;
}
}
pThis->m_WndSize = lParam;
}
break;
case WM_PAINT:
{
if (pThis->m_bUpdateShadow)
{
pThis->UpdateShadow(hwnd);
pThis->m_bUpdateShadow = false;
}
}
break;
// In some cases of sizing, the up-right corner of the parent window region would not be properly updated
// UpdateShadow() again when sizing is finished
case WM_EXITSIZEMOVE:
{
if (pThis->m_Status & SS_VISABLE)
{
pThis->UpdateShadow(hwnd);
}
}
break;
case WM_SHOWWINDOW:
{
if (pThis->m_Status & SS_ENABLED)
{
if (!wParam) // the window is being hidden
{
::ShowWindow(pThis->m_hWnd, SW_HIDE);
pThis->m_Status &= ~(SS_VISABLE | SS_PARENTVISIBLE);
}
else if (!(pThis->m_Status & SS_PARENTVISIBLE))
{
//pThis->Update(hwnd);
pThis->m_bUpdateShadow = true;
::ShowWindow(pThis->m_hWnd, SW_SHOWNA);
pThis->m_Status |= SS_VISABLE | SS_PARENTVISIBLE;
}
}
}
break;
case WM_DESTROY:
{
DestroyWindow(pThis->m_hWnd); // Destroy the shadow
}
break;
case WM_NCDESTROY:
{
m_ShadowWindowMap.erase(it); // Remove this window and shadow from the map
}
break;
}
#pragma warning(disable: 4312) // temporrarily disable the type_cast warning in Win32
// Call the default(original) window procedure for other messages or messages processed but not returned
return ((WNDPROC)pThis->m_OriginParentProc)(hwnd, uMsg, wParam, lParam);
#pragma warning(default: 4312)
}
else
{
return DefWindowProc(hwnd, uMsg, wParam, lParam);
return FALSE;
}
}
// Redraw, resize and move the shadow
// called when window resized or shadow properties changed, but not only moved without resizing
void UpdateShadow(HWND hParent)
{
//int ShadowSize = 5;
//int Multi = 100 / ShadSize;
RECT rcParentWindow = { 0 };
GetWindowRect(hParent, &rcParentWindow);
int nShadowWindowWidth = rcParentWindow.right - rcParentWindow.left + m_nSize * 2;
int nShadowWindowHeight = rcParentWindow.bottom - rcParentWindow.top + m_nSize * 2;
// Create the alpha blending bitmap
BITMAPINFO bmi = { 0 }; // bitmap header
HDC hDC = GetDC(hParent);
WORD wBitsCount = GetDeviceCaps(hDC, BITSPIXEL) * GetDeviceCaps(hDC, PLANES);
if (wBitsCount <= 1)
{
wBitsCount = 1;
}
else if (wBitsCount <= 4)
{
wBitsCount = 4;
}
else if (wBitsCount <= 8)
{
wBitsCount = 8;
}
else if (wBitsCount <= 24)
{
wBitsCount = 24;
}
else
{
wBitsCount = 32;
}
ZeroMemory(&bmi, sizeof(BITMAPINFO));
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = nShadowWindowWidth;
bmi.bmiHeader.biHeight = nShadowWindowHeight;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = wBitsCount; // four 8-bit components
bmi.bmiHeader.biCompression = BI_RGB;
bmi.bmiHeader.biSizeImage = nShadowWindowWidth * nShadowWindowHeight * 4;
BYTE *pvBits; // pointer to DIB section
HBITMAP hbitmap = CreateDIBSection(NULL, &bmi, DIB_RGB_COLORS, (void **)&pvBits, NULL, 0);
ZeroMemory(pvBits, bmi.bmiHeader.biSizeImage);
MakeShadow((UINT32 *)pvBits, hParent, &rcParentWindow);
//SaveHBitmapToFile(hbitmap, TEXT("test.bmp"));
//PPSHUAI::GUIWND::HBitmapToFile(hbitmap, TEXT("temp.bmp"));
HDC hMemDC = CreateCompatibleDC(NULL);
HBITMAP hOriBmp = (HBITMAP)SelectObject(hMemDC, hbitmap);
POINT ptDst = { rcParentWindow.left + m_nxOffset - m_nSize, rcParentWindow.top + m_nyOffset - m_nSize };
POINT ptSrc = { 0, 0 };
SIZE WindowSize = { nShadowWindowWidth, nShadowWindowHeight };
BLENDFUNCTION blendPixelFunction = { AC_SRC_OVER, 0, 255, MY_AC_SRC_ALPHA };
MoveWindow(m_hWnd, ptDst.x, ptDst.y, nShadowWindowWidth, nShadowWindowHeight, FALSE);
BOOL bRet = m_pUpdateLayeredWindow(m_hWnd, NULL, &ptDst, &WindowSize, hMemDC,
&ptSrc, 0, &blendPixelFunction, MY_ULW_ALPHA);
//_ASSERT(bRet); // something was wrong....
// Delete used resources
SelectObject(hMemDC, hOriBmp);
DeleteObject(hbitmap);
DeleteDC(hMemDC);
}
// Fill in the shadow window alpha blend bitmap with shadow image pixels
void MakeShadow(UINT32 *pShadBits, HWND hParent, RECT *rcParent)
{
// The shadow algorithm:
// Get the region of parent window,
// Apply morphologic erosion to shrink it into the size (ShadowWndSize - Sharpness)
// Apply modified (with blur effect) morphologic dilation to make the blurred border
// The algorithm is optimized by assuming parent window is just "one piece" and without "wholes" on it
// Get the region of parent window,
HRGN hParentRgn = CreateRectRgn(0, 0, rcParent->right - rcParent->left, rcParent->bottom - rcParent->top);
GetWindowRgn(hParent, hParentRgn);
// Determine the Start and end point of each horizontal scan line
SIZE szParent = { rcParent->right - rcParent->left, rcParent->bottom - rcParent->top };
SIZE szShadow = { szParent.cx + 2 * m_nSize, szParent.cy + 2 * m_nSize };
// Extra 2 lines (set to be empty) in ptAnchors are used in dilation
int nAnchors = max(szParent.cy, szShadow.cy); // # of anchor points pares
int(*ptAnchors)[2] = new int[nAnchors + 2][2];
int(*ptAnchorsOri)[2] = new int[szParent.cy][2]; // anchor points, will not modify during erosion
ptAnchors[0][0] = szParent.cx;
ptAnchors[0][1] = 0;
ptAnchors[nAnchors + 1][0] = szParent.cx;
ptAnchors[nAnchors + 1][1] = 0;
if (m_nSize > 0)
{
// Put the parent window anchors at the center
for (int i = 0; i < m_nSize; i++)
{
ptAnchors[i + 1][0] = szParent.cx;
ptAnchors[i + 1][1] = 0;
ptAnchors[szShadow.cy - i][0] = szParent.cx;
ptAnchors[szShadow.cy - i][1] = 0;
}
ptAnchors += m_nSize;
}
for (int i = 0; i < szParent.cy; i++)
{
// find start point
int j = 0;
for (j = 0; j < szParent.cx; j++)
{
if (PtInRegion(hParentRgn, j, i))
{
ptAnchors[i + 1][0] = j + m_nSize;
ptAnchorsOri[i][0] = j;
break;
}
}
if (j >= szParent.cx) // Start point not found
{
ptAnchors[i + 1][0] = szParent.cx;
ptAnchorsOri[i][1] = 0;
ptAnchors[i + 1][0] = szParent.cx;
ptAnchorsOri[i][1] = 0;
}
else
{
// find end point
for (j = szParent.cx - 1; j >= ptAnchors[i + 1][0]; j--)
{
if (PtInRegion(hParentRgn, j, i))
{
ptAnchors[i + 1][1] = j + 1 + m_nSize;
ptAnchorsOri[i][1] = j + 1;
break;
}
}
}
}
if (m_nSize > 0)
{
ptAnchors -= m_nSize; // Restore pos of ptAnchors for erosion
}
int(*ptAnchorsTmp)[2] = new int[nAnchors + 2][2]; // Store the result of erosion
// First and last line should be empty
ptAnchorsTmp[0][0] = szParent.cx;
ptAnchorsTmp[0][1] = 0;
ptAnchorsTmp[nAnchors + 1][0] = szParent.cx;
ptAnchorsTmp[nAnchors + 1][1] = 0;
int nEroTimes = 0;
// morphologic erosion
for (int i = 0; i < m_nSharpness - m_nSize; i++)
{
nEroTimes++;
//ptAnchorsTmp[1][0] = szParent.cx;
//ptAnchorsTmp[1][1] = 0;
//ptAnchorsTmp[szParent.cy + 1][0] = szParent.cx;
//ptAnchorsTmp[szParent.cy + 1][1] = 0;
for (int j = 1; j < nAnchors + 1; j++)
{
ptAnchorsTmp[j][0] = max(ptAnchors[j - 1][0], max(ptAnchors[j][0], ptAnchors[j + 1][0])) + 1;
ptAnchorsTmp[j][1] = min(ptAnchors[j - 1][1], min(ptAnchors[j][1], ptAnchors[j + 1][1])) - 1;
}
// Exchange ptAnchors and ptAnchorsTmp;
int(*ptAnchorsXange)[2] = ptAnchorsTmp;
ptAnchorsTmp = ptAnchors;
ptAnchors = ptAnchorsXange;
}
// morphologic dilation
ptAnchors += (m_nSize < 0 ? -m_nSize : 0) + 1; // now coordinates in ptAnchors are same as in shadow window
// Generate the kernel
int nKernelSize = m_nSize > m_nSharpness ? m_nSize : m_nSharpness;
int nCenterSize = m_nSize > m_nSharpness ? (m_nSize - m_nSharpness) : 0;
UINT32 *pKernel = new UINT32[(2 * nKernelSize + 1) * (2 * nKernelSize + 1)];
UINT32 *pKernelIter = pKernel;
for (int i = 0; i <= 2 * nKernelSize; i++)
{
for (int j = 0; j <= 2 * nKernelSize; j++)
{
double dLength = sqrt((i - nKernelSize) * (i - nKernelSize) + (j - nKernelSize) * (double)(j - nKernelSize));
if (dLength < nCenterSize)
{
*pKernelIter = m_nDarkness << 24 | PreMultiply(m_Color, m_nDarkness);
}
else if (dLength <= nKernelSize)
{
UINT32 nFactor = ((UINT32)((1 - (dLength - nCenterSize) / (m_nSharpness + 1)) * m_nDarkness));
*pKernelIter = nFactor << 24 | PreMultiply(m_Color, nFactor);
}
else
{
*pKernelIter = 0;
}
pKernelIter++;
}
}
// Generate blurred border
for (int i = nKernelSize; i < szShadow.cy - nKernelSize; i++)
{
int j = 0;
if (ptAnchors[i][0] < ptAnchors[i][1])
{
// Start of line
for (j = ptAnchors[i][0];
j < min(max(ptAnchors[i - 1][0], ptAnchors[i + 1][0]) + 1, ptAnchors[i][1]);
j++)
{
for (int k = 0; k <= 2 * nKernelSize; k++)
{
UINT32 *pPixel = pShadBits +
(szShadow.cy - i - 1 + nKernelSize - k) * szShadow.cx + j - nKernelSize;
UINT32 *pKernelPixel = pKernel + k * (2 * nKernelSize + 1);
for (int l = 0; l <= 2 * nKernelSize; l++)
{
if (*pPixel < *pKernelPixel)
{
*pPixel = *pKernelPixel;
}
pPixel++;
pKernelPixel++;
}
}
} // for() start of line
// End of line
for (j = max(j, min(ptAnchors[i - 1][1], ptAnchors[i + 1][1]) - 1);
j < ptAnchors[i][1];
j++)
{
for (int k = 0; k <= 2 * nKernelSize; k++)
{
UINT32 *pPixel = pShadBits +
(szShadow.cy - i - 1 + nKernelSize - k) * szShadow.cx + j - nKernelSize;
UINT32 *pKernelPixel = pKernel + k * (2 * nKernelSize + 1);
for (int l = 0; l <= 2 * nKernelSize; l++)
{
if (*pPixel < *pKernelPixel)
{
*pPixel = *pKernelPixel;
}
pPixel++;
pKernelPixel++;
}
}
} // for() end of line
}
} // for() Generate blurred border
// Erase unwanted parts and complement missing
UINT32 clCenter = m_nDarkness << 24 | PreMultiply(m_Color, m_nDarkness);
for (int i = min(nKernelSize, max(m_nSize - m_nyOffset, 0));
i < max(szShadow.cy - nKernelSize, min(szParent.cy + m_nSize - m_nyOffset, szParent.cy + 2 * m_nSize));
i++)
{
UINT32 *pLine = pShadBits + (szShadow.cy - i - 1) * szShadow.cx;
if (i - m_nSize + m_nyOffset < 0 || i - m_nSize + m_nyOffset >= szParent.cy) // Line is not covered by parent window
{
for (int j = ptAnchors[i][0]; j < ptAnchors[i][1]; j++)
{
*(pLine + j) = clCenter;
}
}
else
{
for (int j = ptAnchors[i][0];
j < min(ptAnchorsOri[i - m_nSize + m_nyOffset][0] + m_nSize - m_nxOffset, ptAnchors[i][1]);
j++)
*(pLine + j) = clCenter;
for (int j = max(ptAnchorsOri[i - m_nSize + m_nyOffset][0] + m_nSize - m_nxOffset, 0);
j < min((long)ptAnchorsOri[i - m_nSize + m_nyOffset][1] + m_nSize - m_nxOffset, szShadow.cx);
j++)
*(pLine + j) = 0;
for (int j = max(ptAnchorsOri[i - m_nSize + m_nyOffset][1] + m_nSize - m_nxOffset, ptAnchors[i][0]);
j < ptAnchors[i][1];
j++)
*(pLine + j) = clCenter;
}
}
// Delete used resources
delete[](ptAnchors - (m_nSize < 0 ? -m_nSize : 0) - 1);
delete[] ptAnchorsTmp;
delete[] ptAnchorsOri;
delete[] pKernel;
DeleteObject(hParentRgn);
}
// Helper to calculate the alpha-premultiled value for a pixel
inline DWORD PreMultiply(COLORREF cl, unsigned char nAlpha)
{
// It's strange that the byte order of RGB in 32b BMP is reverse to in COLORREF
return (GetRValue(cl) * (DWORD)nAlpha / 255) << 16 |
(GetGValue(cl) * (DWORD)nAlpha / 255) << 8 |
(GetBValue(cl) * (DWORD)nAlpha / 255);
}
};
CShadowBorder::pfnUpdateLayeredWindow CShadowBorder::m_pUpdateLayeredWindow = NULL;
HINSTANCE CShadowBorder::m_hInstance = (HINSTANCE)INVALID_HANDLE_VALUE;
std::map<HWND, PVOID> CShadowBorder::m_ShadowWindowMap;
}
namespace GUI{
__inline static LONG_PTR SetWindowUserData(HWND hWnd, LONG_PTR lPtr)
{
return ::SetWindowLongPtr(hWnd, GWLP_USERDATA, lPtr);
}
__inline static LONG_PTR GetWindowUserData(HWND hWnd)
{
return GetWindowLongPtr(hWnd, GWLP_USERDATA);
}
typedef enum COLUMN_DATATYPE{
CDT_NULL = 0,
CDT_DEC = 1,
CDT_HEX = 2,
CDT_STRING = 3,
CDT_OTHERS,
};
typedef struct tagSortDataInfo{
HWND hWnd;//Master Window
HWND hListCtrlWnd;//ListCtrl Window
INT nColumnItem;//Column item index
bool bSortFlag;//Sort flag asc or desc
COLUMN_DATATYPE cdType;//Column sort type
}SORTDATAINFO, *PSORTDATAINFO;
// Sort the item in reverse alphabetical order.
__inline static int CALLBACK ListCtrlCompareProcess(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
{
// lParamSort contains a pointer to the list view control.
int nResult = 0;
LV_ITEM lvi = { 0 };
unsigned long ulX = 0;
unsigned long ulY = 0;
_TCHAR tzItem1[MAXWORD] = { 0 };
_TCHAR tzItem2[MAXWORD] = { 0 };
SORTDATAINFO * pSDI = (SORTDATAINFO *)lParamSort;
if (pSDI)
{
lvi.mask = LVIF_TEXT;
lvi.iSubItem = pSDI->nColumnItem;
lvi.cchTextMax = sizeof(tzItem1);
lvi.pszText = tzItem1;
lvi.iItem = lParam1;
ListView_GetItem(pSDI->hListCtrlWnd, &lvi);
lvi.cchTextMax = sizeof(tzItem2);
lvi.pszText = tzItem2;
lvi.iItem = lParam2;
ListView_GetItem(pSDI->hListCtrlWnd, &lvi);
}
switch (pSDI->cdType)
{
case CDT_NULL:
break;
case CDT_DEC:
ulX = _tcstoul(tzItem2, 0, 10);
ulY = _tcstoul(tzItem1, 0, 10);
nResult = ulX - ulY;
break;
case CDT_HEX:
ulX = _tcstoul(tzItem2, 0, 16);
ulY = _tcstoul(tzItem1, 0, 16);
nResult = ulX - ulY;
break;
case CDT_STRING:
nResult = lstrcmpi(tzItem2, tzItem1);
break;
case CDT_OTHERS:
break;
default:
break;
}
return ((pSDI->bSortFlag ? (nResult) : (-nResult)));
}
//图标索引列
#define IMAGEICONINDEX_NAME "IMAGEICONINDEX_NAME"
__inline static void ImageListInit(HIMAGELIST hImageList, TSTRINGVECTORMAP * pTVMAP, LPCTSTR lpIconColumn)
{
LONG lIdx = 0;
SIZE_T stRowIdx = 0;
SHFILEINFO shfi = { 0 };
std::map<TSTRING, LONG> tlmap;
std::map<TSTRING, LONG>::iterator itFinder;
if (hImageList)
{
ImageList_RemoveAll(hImageList);
pTVMAP->insert(TSTRINGVECTORMAP::value_type(_T(IMAGEICONINDEX_NAME), TSTRINGVECTOR()));
for (stRowIdx = 0; stRowIdx < pTVMAP->at(lpIconColumn).size(); stRowIdx++)
{
itFinder = tlmap.find(pTVMAP->at(lpIconColumn).at(stRowIdx));
if (itFinder != tlmap.end())
{
lIdx = itFinder->second;
}
else
{
memset(&shfi, 0, sizeof(shfi));
SHGetFileInfo(pTVMAP->at(lpIconColumn).at(stRowIdx).c_str(), 0, &shfi, sizeof(shfi), SHGFI_DISPLAYNAME | SHGFI_ICON);
lIdx = ImageList_AddIcon(hImageList, shfi.hIcon);
tlmap.insert(std::map<TSTRING, LONG>::value_type(pTVMAP->at(lpIconColumn).at(stRowIdx), lIdx));
}
pTVMAP->at(_T(IMAGEICONINDEX_NAME)).push_back(STRING_FORMAT(_T("%ld"), lIdx));
}
}
}
//////////////////////////////////////////////////////////////////////////////////////
// ListCtrl 操作
__inline static void ListCtrl_InsertColumn(HWND hListCtrlWnd, TSTRINGVECTOR *pSV, int nWidth)
{
if (pSV)
{
ListView_DeleteAllItems(hListCtrlWnd);
while (ListView_DeleteColumn(hListCtrlWnd, 0)){};
size_t stIdx = 0;
size_t stSize = pSV->size();
for (stIdx = 0; stIdx < stSize; stIdx++)
{
tstring tsText = pSV->at(stIdx);
LV_COLUMN lvc = { 0 };
lvc.mask = LVCF_WIDTH | LVCF_TEXT;
lvc.fmt = LVCFMT_CENTER;
lvc.cx = nWidth;
lvc.pszText = (_TCHAR *)tsText.c_str();
lvc.iSubItem = 0;
ListView_InsertColumn(hListCtrlWnd, stIdx, &lvc);
}
}
}
__inline static void ListCtrl_InsertRowData(HWND hListCtrlWnd, TSTRINGVECTORVECTOR *pSVV)
{
HWND hHeaderCtrlWnd = (HWND)ListView_GetHeader(hListCtrlWnd);
if (hHeaderCtrlWnd)
{
if (pSVV)
{
size_t stColumnCount = Header_GetItemCount(hHeaderCtrlWnd);
ListView_DeleteAllItems(hListCtrlWnd);
size_t stRowIdx = 0;
size_t stRowSize = pSVV->size();
for (stRowIdx = 0; stRowIdx < stRowSize; stRowIdx++)
{
TSTRINGVECTOR *pSV = &pSVV->at(stRowIdx);
if (pSV)
{
size_t stColIdx = 0;
size_t stColSize = pSV->size();
stColSize = stColSize > stColumnCount ? stColumnCount : stColSize;
if (stColSize)
{
tstring tsText = pSV->at(stColIdx);
LV_ITEM lvi = { 0 };
lvi.mask = LVIF_TEXT;
lvi.iItem = stRowIdx;
lvi.iSubItem = stColIdx;
lvi.pszText = (_TCHAR *)tsText.c_str();
ListView_InsertItem(hListCtrlWnd, &lvi);
for (++stColIdx; stColIdx < stColSize; stColIdx++)
{
tsText = pSV->at(stColIdx);
lvi.iSubItem = stColIdx;
lvi.pszText = (_TCHAR *)tsText.c_str();
ListView_SetItem(hListCtrlWnd, &lvi);
}
}
}
}
}
}
}
__inline static void ListCtrl_UpdateCellData(HWND hListCtrlWnd, size_t stRowIdx, size_t stColIdx, tstring tsText)
{
HWND hHeaderCtrlWnd = (HWND)ListView_GetHeader(hListCtrlWnd);
if (hHeaderCtrlWnd)
{
size_t stColCount = Header_GetItemCount(hHeaderCtrlWnd);
size_t stRowCount = ListView_GetItemCount(hListCtrlWnd);
if (stRowIdx >= 0 && stRowIdx < stRowCount &&
stColIdx >= 0 && stColIdx < stColCount)
{
LV_ITEM lvi = { 0 };
lvi.mask = LVIF_TEXT;
lvi.iItem = stRowIdx;
lvi.iSubItem = stColIdx;
lvi.pszText = (_TCHAR *)tsText.c_str();
ListView_SetItem(hListCtrlWnd, &lvi);
}
}
}
__inline static void ListCtrl_AutoColumnWidth(HWND hListCtrlWnd)
{
RECT rcListCtrlWnd = { 0 };
GetClientRect(hListCtrlWnd, &rcListCtrlWnd);
InvalidateRect(hListCtrlWnd, &rcListCtrlWnd, FALSE);
HWND hHeaderCtrlWnd = (HWND)ListView_GetHeader(hListCtrlWnd);
if (hHeaderCtrlWnd)
{
int nWidth = 0;
int nColumnWidth = 0;
int nHeaderWidth = 0;
int nColumnCount = Header_GetItemCount(hHeaderCtrlWnd);
for (int nIdx = 0; nIdx < nColumnCount; nIdx++)
{
ListView_SetColumnWidth(hListCtrlWnd, nIdx, LVSCW_AUTOSIZE);
nColumnWidth = ListView_GetColumnWidth(hListCtrlWnd, nIdx);
ListView_SetColumnWidth(hListCtrlWnd, nIdx, LVSCW_AUTOSIZE_USEHEADER);
nHeaderWidth = ListView_GetColumnWidth(hListCtrlWnd, nIdx);
nWidth = nColumnWidth > nHeaderWidth ? nColumnWidth : nHeaderWidth;
ListView_SetColumnWidth(hListCtrlWnd, nIdx, nWidth);
}
InvalidateRect(hListCtrlWnd, &rcListCtrlWnd, TRUE);
}
}
__inline static void ListCtrlDeleteAllColumns(HWND hListViewWnd)
{
while (ListView_DeleteColumn(hListViewWnd, ListView_GetHeader(hListViewWnd)));
}
__inline static void ListCtrlDeleteAllRows(HWND hListViewWnd)
{
ListView_DeleteAllItems(hListViewWnd);
}
__inline static void ListCtrlInsertHeaderData(TSTRINGVECTOR & tv, HWND hListViewWnd, UINT nWidth = 100)
{
LV_COLUMN lvc = { 0 };
lvc.iSubItem = 0;
lvc.cx = nWidth;
lvc.mask = LVCF_TEXT | LVCF_WIDTH;
for (auto it:tv)
{
lvc.pszText = (LPTSTR)it.c_str();
ListView_InsertColumn(hListViewWnd, lvc.iSubItem++, &lvc);
}
}
__inline static UINT ListCtrlInsertCellData(TSTRING ts, HWND hListViewWnd, UINT nColumnIndex = 0, UINT nRowIndex = 0)
{
LV_ITEM lvi = { 0 };
//if ((lvi.iSubItem < Header_GetItemCount(ListView_GetHeader(hListViewWnd))))
//{
lvi.mask = LVIF_TEXT;
//lvi.mask = LVIF_PARAM;
lvi.iItem = nRowIndex;
lvi.iSubItem = nColumnIndex;
//lvi.lParam = lvi.iSubItem;
lvi.pszText = (LPTSTR)ts.c_str();
if (lvi.iSubItem != (0))
{
ListView_SetItem(hListViewWnd, &lvi);
}
else
{
ListView_InsertItem(hListViewWnd, &lvi);
}
//}
return (lvi.iSubItem + 1);
}
__inline static UINT ListCtrlInsertItemData(TSTRINGVECTOR & tv, HWND hListViewWnd, UINT nColumnIndex = 0, UINT nRowIndex = 0)
{
for (auto it : tv)
{
nColumnIndex = ListCtrlInsertCellData(it, hListViewWnd, nColumnIndex, nRowIndex);
}
return (nRowIndex + 1);
}
__inline static void ListCtrlInsertItemsData(TSTRINGVECTORVECTOR & tvv, HWND hListViewWnd, UINT nColumnIndex = 0, UINT nRowIndex = 0)
{
for (auto it : tvv)
{
nRowIndex = ListCtrlInsertItemData(it, hListViewWnd, nColumnIndex, nRowIndex);
}
}
__inline static void ListCtrlInsertData(TSTRINGVECTORMAP * pTVMAP, HWND hListViewWnd, HIMAGELIST hImageList = NULL, LPCTSTR lpListCtrlText = _T(""), LPCTSTR lpHeaderText = _T("|3|3|3|3|3|3|3|3|3|3"))
{
SIZE_T stIndex = 0;
SIZE_T stCount = 0;
SIZE_T stRowIdx = 0;
SIZE_T stColIdx = 0;
LV_ITEM lvi = { 0 };
LV_COLUMN lvc = { 0 };
TSTRINGVECTORMAP::iterator itEnd;
TSTRINGVECTORMAP::iterator itIdx;
if (lpListCtrlText)
{
SetWindowText(hListViewWnd, lpListCtrlText);
}
if (lpHeaderText)
{
SetWindowText(ListView_GetHeader(hListViewWnd), lpHeaderText);
}
stColIdx = 0;
itEnd = pTVMAP->end();
itIdx = pTVMAP->begin();
lvc.mask = LVCF_TEXT | LVCF_WIDTH;
for (; itIdx != itEnd; itIdx++, stColIdx++)
{
if (!itIdx->first.compare(_T("图标文件")) || !itIdx->first.compare(_T(IMAGEICONINDEX_NAME)))
{
stColIdx--;
continue;
}
lvc.iSubItem = stColIdx;
lvc.pszText = (LPTSTR)itIdx->first.c_str();
lvc.cx = 120;
ListView_InsertColumn(hListViewWnd, stColIdx, &lvc);
stRowIdx = 0;
lvi.iSubItem = stColIdx;
lvi.mask = LVIF_TEXT;
stCount = itIdx->second.size();
for (stIndex = 0; stIndex < stCount; stIndex++, stRowIdx++)
{
if (hImageList && pTVMAP->find(_T(IMAGEICONINDEX_NAME)) != pTVMAP->end())
{
lvi.mask |= LVIF_IMAGE;
lvi.iImage = _ttol(pTVMAP->at(_T(IMAGEICONINDEX_NAME)).at(stIndex).c_str());
}
lvi.iItem = stRowIdx;
lvi.pszText = (LPTSTR)itIdx->second.at(stIndex).c_str();
if (!lvi.iSubItem)
{
ListView_InsertItem(hListViewWnd, &lvi);
}
else
{
ListView_SetItem(hListViewWnd, &lvi);
}
}
lvi.mask = LVIF_PARAM;
lvi.lParam = stRowIdx;
ListView_SetItem(hListViewWnd, &lvi);
}
}
typedef struct COLORVALUE
{
COLORREF clrText;//字体颜色
COLORREF clrTextBk;//字体背景颜色
}ColorValue;
static const ColorValue GLOBAL_COLORVALUEARRAY[] = {
#define SINGLE_LINE 0
{ RGB(0, 0, 0), RGB(255, 255, 0) },
#define DOUBLE_LINE 1
{ RGB(0, 0, 0), RGB(0, 255, 0) },
};
//排序结构
typedef struct SORTDATA
{
HWND hwnd;
int column;
int sortorder;
}SortData;
SortData Global_SortData = { 0 };
typedef LRESULT(CALLBACK * HEADERWNDPROC)(HWND, UINT, WPARAM, LPARAM);
typedef struct HEADERREDRAW
{
float gradient; // 画立体背景,渐变系数
float headerheight; //表头高度倍数
int fontheight; //字体高度
int fontwidth;//字体宽度
int bkmode;//背景模式
COLORREF clrbk;//背景颜色
COLORREF clrtext;//字体颜色
}HeaderRedraw;
HeaderRedraw Global_DlgHeaderRedraw = {
1.5,
1,
12,
0,
TRANSPARENT,
RGB(255, 0, 0),
RGB(0, 255, 0)
};
_TCHAR Global_AlignFormat[] = _T("1111");//对齐格式
_TCHAR *Global_ColumnContext[] = { _T("名称"), _T("句柄"), _T("状态"), _T("类名") };
// Message handler for header ctrl.
__inline static INT_PTR CALLBACK HeaderDlgProc(HWND hHeaderWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
PAINTSTRUCT ps;
HDC hdc;
switch (message)
{
case WM_PAINT:
{
hdc = BeginPaint(hHeaderWnd, &ps);
// TODO: Add any drawing code here...
int nItem;
nItem = Header_GetItemCount(hHeaderWnd);//得到有几个单元
float m_R = (float)((Global_DlgHeaderRedraw.clrbk & 0x000000ff) >> 0),
m_G = (float)((Global_DlgHeaderRedraw.clrbk & 0x0000ff00) >> 8),
m_B = (float)((Global_DlgHeaderRedraw.clrbk & 0x00ff0000) >> 16);
for (int i = 0; i<nItem; i++)
{
RECT tRect;
Header_GetItemRect(hHeaderWnd, i, &tRect);//得到Item的尺寸
float R = m_R, G = m_G, B = m_B;
RECT nRect;//拷贝尺寸到新的容器中
memcpy(&nRect, &tRect, sizeof(RECT));
nRect.left++;//留出分割线的地方
//绘制立体背景
for (int j = tRect.top; j <= tRect.bottom; j++)
{
nRect.bottom = nRect.top + 1;
HBRUSH hBrush;
hBrush = CreateSolidBrush(RGB(R, G, B));//创建画刷
FillRect(hdc, &nRect, hBrush); //填充背景
DeleteObject(hBrush); //释放画刷
R -= Global_DlgHeaderRedraw.gradient;
G -= Global_DlgHeaderRedraw.gradient;
B -= Global_DlgHeaderRedraw.gradient;
if (R<0)R = 0;
if (G<0)G = 0;
if (B<0)B = 0;
nRect.top = nRect.bottom;
}
SetBkMode(hdc, Global_DlgHeaderRedraw.bkmode);
HFONT hFont, hOldFont;
SetTextColor(hdc, Global_DlgHeaderRedraw.clrtext);
hFont = CreateFont(
Global_DlgHeaderRedraw.fontheight,
Global_DlgHeaderRedraw.fontwidth,
0,
0,
0,
FALSE,
FALSE,
0,
0,
0,
0,
0,
0,
_T("MS Shell Dlg"));//创建字体
hOldFont = (HFONT)SelectObject(hdc, hFont);
UINT nFormat = 1;
if (Global_AlignFormat[i] == _T('0'))
{
nFormat = DT_LEFT;
tRect.left += 3;
}
else if (Global_AlignFormat[i] == _T('1'))
{
nFormat = DT_CENTER;
}
else if (Global_AlignFormat[i] == _T('2'))
{
nFormat = DT_RIGHT;
tRect.right -= 3;
}
TEXTMETRIC metric;
GetTextMetrics(hdc, &metric);
int offset = 0;
offset = tRect.bottom - tRect.top - metric.tmHeight;
OffsetRect(&tRect, 0, offset / 2);
HD_ITEM hdi = { 0 };
_TCHAR tHeaderText[MAXBYTE] = { 0 };
hdi.mask = HDI_TEXT;
hdi.cchTextMax = MAXBYTE;
hdi.pszText = tHeaderText;
Header_GetItem(hHeaderWnd, i, &hdi);
DrawText(hdc, tHeaderText, lstrlen(tHeaderText), &tRect, nFormat);
SelectObject(hdc, hOldFont);
DeleteObject(hFont); //释放字体
}
//画头部剩余部分
RECT rtRect;
RECT clientRect;
Header_GetItemRect(hHeaderWnd, nItem - 1, &rtRect);
GetClientRect(hHeaderWnd, &clientRect);
rtRect.left = rtRect.right + 1;
rtRect.right = clientRect.right;
float R = m_R, G = m_G, B = m_B;
RECT nRect;
memcpy(&nRect, &rtRect, sizeof(RECT));
//绘制立体背景
for (int j = rtRect.top; j <= rtRect.bottom; j++)
{
nRect.bottom = nRect.top + 1;
HBRUSH hBrush;
hBrush = CreateSolidBrush(RGB(R, G, B));//创建画刷
FillRect(hdc, &nRect, hBrush); //填充背景
DeleteObject(hBrush); //释放画刷
R -= Global_DlgHeaderRedraw.gradient;
G -= Global_DlgHeaderRedraw.gradient;
B -= Global_DlgHeaderRedraw.gradient;
if (R<0)R = 0;
if (G<0)G = 0;
if (B<0)B = 0;
nRect.top = nRect.bottom;
}
EndPaint(hHeaderWnd, &ps);
}
break;
default:
return ::CallWindowProc((WNDPROC)::GetWindowLongPtr(hHeaderWnd, GWLP_USERDATA), hHeaderWnd, message, wParam, lParam);
}
return (INT_PTR)FALSE;
}
//重置窗口大小
int ResizeWindow(HWND hParentWnd, DWORD dwID)
{
int result = 0;
HWND hDataListCtrl = GetDlgItem(hParentWnd, dwID);
if (hDataListCtrl)
{
RECT rc = { 0 };
int column = 0;
HWND hHeaderWnd = 0;
GetClientRect(hParentWnd, &rc);
SetWindowPos(hDataListCtrl, HWND_TOP, rc.left, rc.top, rc.right, rc.bottom, SWP_NOMOVE | SWP_NOZORDER | SWP_NOREDRAW);
InvalidateRect(hParentWnd, &rc, FALSE);
hHeaderWnd = ListView_GetHeader(hDataListCtrl);
if (hHeaderWnd)
{
column = Header_GetItemCount(hHeaderWnd);
for (int i = 0; i < column; i++)
{
ListView_SetColumnWidth(hDataListCtrl, i, rc.right / column);
}
}
}
return result;
}
//对话框初始化ListCtrl控件
INT_PTR OnInitDataList(HWND hDlg, DWORD dwID, LPTSTR * pHeaderTitles, DWORD dwHeaderNumber)
{
INT_PTR iresult = 0;
HWND hDataListCtrl = GetDlgItem(hDlg, dwID);
if (hDataListCtrl)
{
int colnum = 0;
LV_COLUMN lvc = { 0 };
RECT rc = { 0 };
LONG lstyle = 0;
DWORD dwstyle = 0;
lstyle = GetWindowLong(hDataListCtrl, GWL_STYLE);//获取当前窗口style
lstyle &= ~LVS_TYPEMASK; //清除显示方式位
lstyle |= LVS_REPORT; //设置style
//lstyle |= LVS_SORTASCENDING; //设置排序
lstyle |= LVS_SINGLESEL; //设置单选
lstyle |= LVS_SHOWSELALWAYS; //设置一直选择
lstyle |= LVS_AUTOARRANGE; //设置自动浮动
SetWindowLong(hDataListCtrl, GWL_STYLE, lstyle);//设置style
dwstyle = ListView_GetExtendedListViewStyle(hDataListCtrl);
dwstyle |= LVS_EX_FULLROWSELECT;//选中某行使整行高亮(只适用与report风格的listctrl)
dwstyle |= LVS_EX_GRIDLINES;//网格线(只适用与report风格的listctrl)
dwstyle |= LVS_EX_CHECKBOXES;//item前生成checkbox控件
dwstyle |= LVS_EX_TRACKSELECT;//
dwstyle |= LVS_EX_HEADERDRAGDROP;//列头可拖拽
dwstyle |= LVS_EX_ONECLICKACTIVATE;//单击激活
dwstyle |= LVS_EX_FLATSB;//平滑进度条
dwstyle |= LVS_EX_REGIONAL;//
dwstyle |= LVS_EX_INFOTIP;//
dwstyle |= LVS_EX_UNDERLINEHOT;//下划线
dwstyle |= LVS_EX_LABELTIP;//
ListView_SetExtendedListViewStyle(hDataListCtrl, dwstyle); //设置扩展风格
GetClientRect(hDataListCtrl, &rc);
lvc.mask = LVCF_TEXT | LVCF_WIDTH;
for (DWORD dwColnum = 0; dwColnum < dwHeaderNumber; dwColnum++)
{
lvc.pszText = pHeaderTitles[dwColnum];
ListView_InsertColumn(hDataListCtrl, dwColnum++, &lvc);
}
for (int i = 0; i < ListView_GetItemCount(hDataListCtrl); i++)
{
ListView_RedrawItems(hDataListCtrl, i, i);
}
HWND hHeaderWnd = ListView_GetHeader(hDataListCtrl);
if (hHeaderWnd)
{
::SetWindowLongPtr(hHeaderWnd, GWLP_USERDATA, (LONG_PTR)(WNDPROC)::GetWindowLongPtr(hHeaderWnd, GWLP_WNDPROC));
::SetWindowLongPtr(hHeaderWnd, GWLP_WNDPROC, (LONG_PTR)(HeaderDlgProc));
}
ResizeWindow(hDlg, dwID);
}
return iresult;
}
__inline static LONG_PTR ListCtrlSetSortDataInfo(HWND hListCtrlWnd, SORTDATAINFO * pSDI)
{
return SetWindowUserData(ListView_GetHeader(hListCtrlWnd), (LONG_PTR)pSDI);
}
__inline static SORTDATAINFO * ListCtrlGetLSortDataInfo(HWND hListCtrlWnd)
{
return (SORTDATAINFO *)GetWindowUserData(ListView_GetHeader(hListCtrlWnd));
}
__inline static UINT ListCtrlGetSelectedRowCount(HWND hListViewWnd)
{
return ListView_GetSelectedCount(hListViewWnd);
}
__inline static void ListCtrlGetSelectedRow(std::map<UINT, UINT> * pssmap, HWND hListViewWnd)
{
UINT nSelectIndex = 0;
while ((nSelectIndex = ListView_GetNextItem(hListViewWnd, (-1), LVNI_SELECTED)) != (-1))
{
pssmap->insert(std::map<UINT, UINT>::value_type(nSelectIndex, nSelectIndex));
}
}
__inline static LRESULT ListCtrlOnNotify(HWND hListCtrlWnd, LPNMHDR lpNMHDR)
{
int nItemPos = 0;
switch (lpNMHDR->code)
{
case NM_RCLICK:
{
if ((nItemPos = ListView_GetNextItem(hListCtrlWnd, -1, LVNI_SELECTED)) != -1)
{
HMENU hMenu = NULL;
POINT point = { 0 };
GetCursorPos(&point);
//动态创建弹出式菜单对象
hMenu = CreatePopupMenu();
if (hMenu)
{
AppendMenu(hMenu, MF_STRING, (0), _T("选择"));
TrackPopupMenuEx(hMenu, TPM_RIGHTBUTTON | TPM_VERPOSANIMATION | TPM_LEFTALIGN | TPM_VERTICAL, point.x, point.y, hListCtrlWnd, NULL);
DestroyMenu(hMenu);
hMenu = NULL;
}
}
}
break;
case NM_DBLCLK:
{
if ((nItemPos = ListView_GetNextItem(hListCtrlWnd, -1, LVNI_SELECTED)) != -1)
{
}
}
break;
//case LVN_COLUMNCLICK:
case HDN_ITEMCLICK:
{
_TCHAR tzText[MAXWORD] = { 0 };
_TCHAR tzValue[MAXWORD] = { 0 };
tstring::size_type stIndexPos = 0;
tstring::size_type stStartPos = 0;
tstring::size_type stFinalPos = 0;
LPNMHEADER lpNMHEADER = (LPNMHEADER)lpNMHDR;
SORTDATAINFO * pSDI = (SORTDATAINFO *)GetWindowUserData(ListView_GetHeader(hListCtrlWnd));
if (pSDI)
{
pSDI->hListCtrlWnd = hListCtrlWnd;
if (pSDI->nColumnItem != lpNMHEADER->iItem)
{
pSDI->nColumnItem = lpNMHEADER->iItem;
pSDI->bSortFlag = true;
}
else
{
pSDI->bSortFlag = (!pSDI->bSortFlag);
}
GetWindowText(ListView_GetHeader(pSDI->hListCtrlWnd), tzText, sizeof(tzText));
for (stIndexPos = 0;
stIndexPos < lpNMHEADER->iItem
&& (stStartPos = tstring(tzText).find(_T("|"), stStartPos + 1));
stIndexPos++){
;
}
stFinalPos = tstring(tzText).find(_T("|"), stStartPos + 1);
lstrcpyn(tzValue, (LPCTSTR)tzText + stStartPos + 1, stFinalPos - stStartPos);
pSDI->cdType = (COLUMN_DATATYPE)_ttol(tzValue);
ListView_SortItemsEx(pSDI->hListCtrlWnd, &ListCtrlCompareProcess, pSDI);
}
}
break;
case LVN_ITEMCHANGED:
{
if ((nItemPos = ListView_GetNextItem(hListCtrlWnd, -1, LVNI_SELECTED)) != -1)
{
//
}
}
break;
default:
break;
}
return 0;
}
//对话框通知消息处理函数
__inline static INT_PTR OnListCtrlNotify(HWND hDlg, DWORD dwID, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
INT_PTR iresult = 0;
if (((NMHDR *)lParam)->idFrom == dwID)
{
switch (((NMHDR *)lParam)->code)
{
case NM_CLICK:
{
LVHITTESTINFO lvinfo = { 0 };
DWORD dwposition = GetMessagePos();
HWND hDataListCtrl = GetDlgItem(hDlg, dwID);
if (hDataListCtrl)
{
lvinfo.pt.x = LOWORD(dwposition);
lvinfo.pt.y = HIWORD(dwposition);
ScreenToClient(hDataListCtrl, &lvinfo.pt);
ListView_HitTest(hDataListCtrl, &lvinfo);
//判断是否点在CheckBox上
if (lvinfo.flags == LVHT_ONITEMSTATEICON)
{
//::MessageBox(hDlg, _T("点击ListCtrl中CheckBox"), _T("提示"), MB_OK);
if (ListView_GetCheckState(hDataListCtrl, lvinfo.iItem))
{
ListView_SetItemState(hDataListCtrl, lvinfo.iItem, 0, LVIS_SELECTED | LVIS_FOCUSED);
}
else
{
ListView_SetItemState(hDataListCtrl, lvinfo.iItem, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
}
}
else if (lvinfo.flags == LVHT_ONITEMLABEL)
{
}
else if (lvinfo.flags == (LVHT_ONITEMLABEL | LVHT_BELOW))
{
}
else
{
/*if (ListView_GetCheckState(hDataListCtrl, lvinfo.iItem))
{
ListView_SetCheckState(hDataListCtrl, lvinfo.iItem, FALSE);
ListView_SetItemState(hDataListCtrl, lvinfo.iItem, 0, LVIS_SELECTED | LVIS_FOCUSED);
}
else
{
ListView_SetCheckState(hDataListCtrl, lvinfo.iItem, TRUE);
ListView_SetItemState(hDataListCtrl, lvinfo.iItem, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
}*/
}
}
}
break;
case NM_CUSTOMDRAW:
{
HWND hDataListCtrl = GetDlgItem(hDlg, dwID);
if (hDataListCtrl)
{
NMLVCUSTOMDRAW * pnmlcd = (NMLVCUSTOMDRAW *)lParam;
iresult = CDRF_DODEFAULT;
switch (pnmlcd->nmcd.dwDrawStage)//判断步骤
{
case CDDS_PREPAINT:
{
iresult = CDRF_NOTIFYITEMDRAW;
}
break;
case CDDS_ITEMPREPAINT://如果为画ITEM之前就要进行颜色的改变
{
/*if(pnmlcd->nmcd.dwItemSpec % 2)
{
pnmlcd->clrText = GLOBAL_COLORVALUEARRAY[SINGLE_LINE].clrText;
pnmlcd->clrTextBk = GLOBAL_COLORVALUEARRAY[SINGLE_LINE].clrTextBk;
}
else
{
pnmlcd->clrText = GLOBAL_COLORVALUEARRAY[DOUBLE_LINE].clrText;
pnmlcd->clrTextBk = GLOBAL_COLORVALUEARRAY[DOUBLE_LINE].clrTextBk;
}
iresult = CDRF_DODEFAULT;//使用此代码,每行颜色可一致
*/
iresult = CDRF_NOTIFYSUBITEMDRAW;//使用此代码,每个单元格颜色可一致
}
break;
case CDDS_SUBITEM | CDDS_ITEMPREPAINT:
{
//printf("%d,%d\r\n", pnmlcd->nmcd.dwItemSpec, pnmlcd->iSubItem);
if (pnmlcd->nmcd.dwItemSpec % 2 && pnmlcd->iSubItem % 2)
{
pnmlcd->clrText = GLOBAL_COLORVALUEARRAY[DOUBLE_LINE].clrText;
pnmlcd->clrTextBk = GLOBAL_COLORVALUEARRAY[DOUBLE_LINE].clrTextBk;
}
else if (pnmlcd->nmcd.dwItemSpec % 2 && !(pnmlcd->iSubItem % 2))
{
pnmlcd->clrText = GLOBAL_COLORVALUEARRAY[SINGLE_LINE].clrText;
pnmlcd->clrTextBk = GLOBAL_COLORVALUEARRAY[SINGLE_LINE].clrTextBk;
}
else if (!(pnmlcd->nmcd.dwItemSpec % 2) && pnmlcd->iSubItem % 2)
{
pnmlcd->clrText = GLOBAL_COLORVALUEARRAY[SINGLE_LINE].clrText;
pnmlcd->clrTextBk = GLOBAL_COLORVALUEARRAY[SINGLE_LINE].clrTextBk;
}
else
{
pnmlcd->clrText = GLOBAL_COLORVALUEARRAY[DOUBLE_LINE].clrText;
pnmlcd->clrTextBk = GLOBAL_COLORVALUEARRAY[DOUBLE_LINE].clrTextBk;
}
/*if(pnmlcd->iSubItem % 2)
{
pnmlcd->clrTextBk = GLOBAL_COLORVALUEARRAY[SINGLE_LINE].clrTextBk;
}
else
{
pnmlcd->clrTextBk = GLOBAL_COLORVALUEARRAY[DOUBLE_LINE].clrTextBk;
}*/
iresult = CDRF_DODEFAULT;
}
break;
default:
{
iresult = CDRF_DODEFAULT;
}
break;
}
}
}
//SetWindowLong(hDlg, DWL_MSGRESULT, iresult);
SetWindowLongPtr(hDlg, DWLP_MSGRESULT, iresult);
break;
default:
{
switch (((NMLISTVIEW *)lParam)->hdr.code)
{
case LVN_COLUMNCLICK:
{
HWND hDataListCtrl = GetDlgItem(hDlg, dwID);
if (hDataListCtrl)
{
NM_LISTVIEW * pnmlv = (NM_LISTVIEW *)lParam;
//设置排序方式
if (pnmlv->iSubItem == Global_SortData.column)
{
Global_SortData.sortorder = !Global_SortData.sortorder;
}
else
{
Global_SortData.sortorder = 1;
Global_SortData.column = pnmlv->iSubItem;
}
Global_SortData.hwnd = hDataListCtrl;
//调用排序函数
ListView_SortItemsEx(hDataListCtrl, ListCtrlCompareProcess, (LPARAM)&Global_SortData);
}
}
break;
default:
{
}
break;
}
}
break;
}
}
return iresult;
}
__inline static void RegisterDropFilesEvent(HWND hWnd)
{
#ifndef WM_COPYGLOBALDATA
#define WM_COPYGLOBALDAYA 0x0049
#endif
#ifndef MSGFLT_ADD
#define MSGFLT_ADD 1
#endif
#ifndef MSGFLT_REMOVE
#define MSGFLT_REMOVE 2
#endif
SetWindowLong(hWnd, GWL_EXSTYLE, GetWindowLong(hWnd, GWL_EXSTYLE) | WS_EX_ACCEPTFILES);
typedef BOOL(WINAPI *LPFN_ChangeWindowMessageFilter)(__in UINT message, __in DWORD dwFlag);
LPFN_ChangeWindowMessageFilter pfnChangeWindowMessageFilter = (LPFN_ChangeWindowMessageFilter)GetProcAddress(GetModuleHandle(_T("USER32.DLL")), "ChangeWindowMessageFilter");
if (pfnChangeWindowMessageFilter)
{
pfnChangeWindowMessageFilter(WM_DROPFILES, MSGFLT_ADD);
pfnChangeWindowMessageFilter(WM_COPYDATA, MSGFLT_ADD);
pfnChangeWindowMessageFilter(WM_COPYGLOBALDAYA, MSGFLT_ADD);// 0x0049 == WM_COPYGLOBALDATA
}
}
__inline static size_t GetDropFiles(std::map<TSTRING, TSTRING> * pttmap, HDROP hDropInfo)
{
UINT nIndex = 0;
UINT nNumOfFiles = 0;
_TCHAR tszFilePathName[MAX_PATH + 1] = { 0 };
//得到文件个数
nNumOfFiles = DragQueryFile(hDropInfo, 0xFFFFFFFF, NULL, 0);
for (nIndex = 0; nIndex < nNumOfFiles; nIndex++)
{
//得到文件名
DragQueryFile(hDropInfo, nIndex, (LPTSTR)tszFilePathName, _MAX_PATH);
pttmap->insert(std::map<TSTRING, TSTRING>::value_type(tszFilePathName, tszFilePathName));
}
DragFinish(hDropInfo);
return nNumOfFiles;
}
__inline static size_t GetDropFiles(std::vector<TSTRING> * pttmap, HDROP hDropInfo)
{
UINT nIndex = 0;
UINT nNumOfFiles = 0;
_TCHAR tszFilePathName[MAX_PATH + 1] = { 0 };
//得到文件个数
nNumOfFiles = DragQueryFile(hDropInfo, 0xFFFFFFFF, NULL, 0);
for (nIndex = 0; nIndex < nNumOfFiles; nIndex++)
{
//得到文件名
DragQueryFile(hDropInfo, nIndex, (LPTSTR)tszFilePathName, _MAX_PATH);
pttmap->push_back(tszFilePathName);
}
DragFinish(hDropInfo);
return nNumOfFiles;
}
__inline static int OnRefreshTreelist(HWND hWndTreeList)
{
int nResult = 0;
_TCHAR tzWindowTitle[MAXBYTE] = { 0 };
_TCHAR tzWindowClass[MAXBYTE] = { 0 };
_TCHAR tzWindowBuffer[MAXBYTE] = { 0 };
//Tree控件操作变量
TVINSERTSTRUCT tvis = { 0 };
HWND hWndParent = NULL;
HTREEITEM hTreeItemParent = NULL;
HWND hWndDesktop = NULL;
HTREEITEM hTreeItemDesktop = NULL;
HWND hWndChildren = NULL;
HTREEITEM hTreeItemChildren = NULL;
//设置根窗口句柄
hWndParent = hWndTreeList;
//根节点数据
tvis.hParent = NULL;
tvis.hInsertAfter = NULL;
tvis.item.mask = TVIF_TEXT | TVIF_PARAM;
tvis.item.pszText = _T("窗口句柄");
tvis.item.lParam = 0;//设置项目个数
//删除全部节点
TreeView_DeleteAllItems(hWndParent);
//添加根节点
hTreeItemParent = TreeView_InsertItem(hWndParent, &tvis);
//获取桌面窗口句柄
hWndDesktop = ::GetDesktopWindow();
//取窗口标题
::GetWindowText(hWndDesktop, tzWindowTitle, sizeof(tzWindowTitle) / sizeof(_TCHAR));
_sntprintf(tzWindowTitle, sizeof(tzWindowClass) / sizeof(_TCHAR), _T("桌面"));
//取窗口类名
::GetClassName(hWndDesktop, tzWindowClass, sizeof(tzWindowClass) / sizeof(_TCHAR));
//把信息格式化
_sntprintf(tzWindowBuffer, sizeof(tzWindowBuffer) / sizeof(_TCHAR), _T("%s | %s | %d(0x%X)"), tzWindowTitle, tzWindowClass, hWndDesktop, hWndDesktop);
//节点数据
tvis.hParent = hTreeItemParent;
tvis.hInsertAfter = TVI_LAST;
tvis.item.mask = TVIF_TEXT | TVIF_PARAM | TVIF_CHILDREN;
tvis.item.pszText = tzWindowBuffer;
tvis.item.lParam = (int)hWndDesktop;
tvis.item.cChildren = ::GetWindow(hWndDesktop, GW_CHILD) ? 1 : 0;
//插入节点
hTreeItemDesktop = TreeView_InsertItem(hWndParent, &tvis);
//取子级窗口句柄
hWndChildren = ::GetWindow(hWndDesktop, GW_CHILD);
while (hWndChildren)
{
//窗口是否可视
if (::IsWindowVisible(hWndChildren))
{
memset(tzWindowTitle, 0, sizeof(tzWindowTitle));
memset(tzWindowClass, 0, sizeof(tzWindowClass));
memset(tzWindowBuffer, 0, sizeof(tzWindowBuffer));
//取窗口标题
::GetWindowText(hWndChildren, tzWindowTitle, sizeof(tzWindowTitle) / sizeof(_TCHAR));
//取窗口类名
::GetClassName(hWndChildren, tzWindowClass, sizeof(tzWindowClass) / sizeof(_TCHAR));
//把信息格式化
_sntprintf(tzWindowBuffer, sizeof(tzWindowBuffer) / sizeof(_TCHAR), _T("%s | %s | %d(0x%X)"), tzWindowTitle, tzWindowClass, hWndChildren, hWndChildren);
//节点数据
tvis.hParent = hTreeItemDesktop;
tvis.hInsertAfter = TVI_LAST;
tvis.item.mask = TVIF_TEXT | TVIF_PARAM | TVIF_CHILDREN;
tvis.item.pszText = tzWindowBuffer;
tvis.item.lParam = (int)hWndChildren;
tvis.item.cChildren = ::GetWindow(hWndChildren, GW_CHILD) ? 1 : 0;
//插入节点
hTreeItemChildren = TreeView_InsertItem(hWndParent, &tvis);
}
//取下一兄弟窗口
hWndChildren = ::GetWindow(hWndChildren, GW_HWNDNEXT);
}
//展开根节点
TreeView_Expand(hWndTreeList, hTreeItemParent, TVE_EXPAND);
//展开桌面节点
TreeView_Expand(hWndTreeList, hTreeItemDesktop, TVE_EXPAND);
return nResult;
}
//树响应函数,选择项目处理
__inline static void OnSelectedChangedTreeList(NMHDR * pNMHDR, LRESULT * pResult)
{
NMTREEVIEW * pNMTV = NULL;
_TCHAR tzWindowTitle[MAXBYTE] = { 0 };
_TCHAR tzWindowClass[MAXBYTE] = { 0 };
_TCHAR tzWindowBuffer[MAXBYTE] = { 0 };
//Tree控件操作变量
TVINSERTSTRUCT tvis = { 0 };
HWND hWndTreeList = NULL;
HWND hWndParent = NULL;
HTREEITEM hTreeItemParent = NULL;
HWND hWndChildren = NULL;
HTREEITEM hTreeItemChildren = NULL;
pNMTV = (NMTREEVIEW *)pNMHDR;
hWndTreeList = pNMTV->hdr.hwndFrom;
//::GetClassName(hWndTreeList, tzWindowClass, sizeof(tzWindowClass) / sizeof(_TCHAR));
//_tprintf(_T("%s\n"), tzWindowClass);
//hTreeItemParent = pNMTV->itemNew.hItem;
hTreeItemParent = TreeView_GetSelection(hWndTreeList);
tvis.item.hItem = hTreeItemParent;
tvis.item.mask = TVIF_PARAM;
TreeView_GetItem(hWndTreeList, &tvis.item);
hWndParent = (HWND)tvis.item.lParam;
//ItemHasChildren 是否有子节点
//GetChildItem 获取第一个子结点
//GetNextSiblingItem 获取下一个兄弟结点结点
//判断是否有子节点,已有子节点则不处理
if (TreeView_GetChild(hWndTreeList, hTreeItemParent))
{
return;
}
//遍历子窗口的所有控件
//取子级窗口句柄
hWndChildren = ::GetWindow(hWndParent, GW_CHILD);
while (hWndChildren)
{
//窗口是否可视
//if (::IsWindowVisible(hWndChildren))
{
memset(tzWindowTitle, 0, sizeof(tzWindowTitle));
memset(tzWindowClass, 0, sizeof(tzWindowClass));
memset(tzWindowBuffer, 0, sizeof(tzWindowBuffer));
//取窗口标题
::GetWindowText(hWndChildren, tzWindowTitle, sizeof(tzWindowTitle) / sizeof(_TCHAR));
//取窗口类名
::GetClassName(hWndChildren, tzWindowClass, sizeof(tzWindowClass) / sizeof(_TCHAR));
//把信息格式化
_sntprintf(tzWindowBuffer, sizeof(tzWindowBuffer) / sizeof(_TCHAR), _T("%s | %s | %d(0x%X)"), tzWindowTitle, tzWindowClass, hWndChildren, hWndChildren);
//_tprintf(_T("%s\n"), tzWindowBuffer);
//节点数据
tvis.hParent = hTreeItemParent;
tvis.hInsertAfter = TVI_LAST;
tvis.item.mask = TVIF_TEXT | TVIF_PARAM | TVIF_CHILDREN;
tvis.item.pszText = tzWindowBuffer;
tvis.item.lParam = (int)hWndChildren;
tvis.item.cChildren = ::GetWindow(hWndChildren, GW_CHILD) ? 1 : 0;
//插入节点
hTreeItemChildren = TreeView_InsertItem(hWndTreeList, &tvis);
}
//取下一兄弟窗口
hWndChildren = ::GetWindow(hWndChildren, GW_HWNDNEXT);
}
}
__inline static INT_PTR OnTreeNotify(HWND hWnd, DWORD dwID, LPARAM lParam)
{
INT_PTR nResult = (0);
NMHDR * pNMHDR = (NMHDR *)lParam;
switch (pNMHDR->code)
{
case NM_DBLCLK://双击操作
{
if (pNMHDR->idFrom == dwID)
{
OnSelectedChangedTreeList((NMHDR *)lParam, 0);
}
}
break;
}
return nResult;
}
//nAnimateType = 1 2 3 4 其它动画类型
__inline static BOOL DisplayAnimateWindows(HWND hWnd, unsigned long ulTime, bool bShow = true, bool bSlide = true, int nAnimateType = 0)
{
unsigned long ulFlags = (bShow ? AW_ACTIVATE : AW_HIDE) | (bSlide ? AW_SLIDE : AW_BLEND);
switch (nAnimateType)
{
case 1:
{
ulFlags |= AW_HOR_POSITIVE;
}
break;
case 2:
{
ulFlags |= AW_VER_POSITIVE;
}
break;
case 3:
{
ulFlags |= AW_HOR_NEGATIVE;
}
break;
case 4:
{
ulFlags |= AW_VER_NEGATIVE;
}
break;
default:
{
ulFlags |= AW_CENTER;
}
break;
}
return ::AnimateWindow(hWnd, ulTime, ulFlags);
}
//显示在屏幕中央
__inline static void CenterWindowInScreen(HWND hWnd)
{
RECT rcWindow = { 0 };
RECT rcScreen = { 0 };
SIZE szAppWnd = { 300, 160 };
POINT ptAppWnd = { 0, 0 };
// Get workarea rect.
BOOL fResult = SystemParametersInfo(SPI_GETWORKAREA, // Get workarea information
0, // Not used
&rcScreen, // Screen rect information
0); // Not used
GetWindowRect(hWnd, &rcWindow);
szAppWnd.cx = rcWindow.right - rcWindow.left;
szAppWnd.cy = rcWindow.bottom - rcWindow.top;
//居中显示
ptAppWnd.x = (rcScreen.right - rcScreen.left - szAppWnd.cx) / 2;
ptAppWnd.y = (rcScreen.bottom - rcScreen.top - szAppWnd.cy) / 2;
MoveWindow(hWnd, ptAppWnd.x, ptAppWnd.y, szAppWnd.cx, szAppWnd.cy, TRUE);
}
//显示在父窗口中央
__inline static void CenterWindowInParent(HWND hWnd, HWND hParentWnd)
{
RECT rcWindow = { 0 };
RECT rcParent = { 0 };
SIZE szAppWnd = { 300, 160 };
POINT ptAppWnd = { 0, 0 };
GetWindowRect(hParentWnd, &rcParent);
GetWindowRect(hWnd, &rcWindow);
szAppWnd.cx = rcWindow.right - rcWindow.left;
szAppWnd.cy = rcWindow.bottom - rcWindow.top;
//居中显示
ptAppWnd.x = (rcParent.right - rcParent.left - szAppWnd.cx) / 2;
ptAppWnd.y = (rcParent.bottom - rcParent.top - szAppWnd.cy) / 2;
MoveWindow(hWnd, ptAppWnd.x, ptAppWnd.y, szAppWnd.cx, szAppWnd.cy, TRUE);
}
__inline static void StaticSetIconImage(HWND hWndStatic, HICON hIcon)
{
HICON hLastIcon = NULL;
hLastIcon = (HICON)SendMessage(hWndStatic, STM_SETIMAGE, IMAGE_ICON, (LPARAM)hIcon);
if (hLastIcon)
{
DeleteObject(hLastIcon);
hLastIcon = NULL;
}
}
__inline static void StaticSetBitmapImage(HWND hWndStatic, HBITMAP hBitmap)
{
HBITMAP hLastBitmap = NULL;
hLastBitmap = (HBITMAP)SendMessage(hWndStatic, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hBitmap);
if (hLastBitmap)
{
DeleteObject(hLastBitmap);
hLastBitmap = NULL;
}
}
__inline static HICON HIconFromFile(LPCTSTR lpFileName, SIZE size = { 0, 0 })
{
return (HICON)LoadImage(GetModuleHandle(NULL),
lpFileName,
IMAGE_ICON,
size.cx,//GetSystemMetrics(SM_CXSMICON),
size.cy,//GetSystemMetrics(SM_CYSMICON),
LR_LOADFROMFILE);
}
__inline static HBITMAP HBitmapFromFile(LPCTSTR lpFileName, SIZE size = { 0, 0 })
{
return (HBITMAP)LoadImage(GetModuleHandle(NULL),
lpFileName,
IMAGE_BITMAP,
size.cx,//GetSystemMetrics(SM_CXSMICON),
size.cy,//GetSystemMetrics(SM_CYSMICON),
LR_LOADFROMFILE);
}
__inline static HCURSOR HCursorFromFile(LPCTSTR lpFileName, SIZE size = { 0, 0 })
{
return (HCURSOR)LoadImage(GetModuleHandle(NULL),
lpFileName,
IMAGE_CURSOR,
size.cx,//GetSystemMetrics(SM_CXSMICON),
size.cy,//GetSystemMetrics(SM_CYSMICON),
LR_LOADFROMFILE);
}
__inline static
void NotifyUpdate(HWND hWnd, RECT *pRect = NULL, BOOL bErase = TRUE)
{
RECT rcWnd = { 0 };
::GetClientRect(hWnd, &rcWnd);
if (pRect)
{
if (memcmp(pRect, &rcWnd, sizeof(RECT)))
{
::InvalidateRect(hWnd, &rcWnd, bErase);
memcpy(pRect, &rcWnd, sizeof(RECT));
}
}
else
{
::InvalidateRect(hWnd, &rcWnd, bErase);
}
}
__inline static
bool SaveBitmapToFile(HDC hDC, HBITMAP hBitmap, LPCTSTR ptFileName)
{
// HDC hDC;
//设备描述表
int iBits;
//当前显示分辨率下每个像素所占字节数
WORD wBitCount;
//位图中每个像素所占字节数
//定义调色板大小, 位图中像素字节大小 , 位图文件大小 , 写入文件字节数
DWORD dwPaletteSize = 0, dwBmBitsSize, dwDIBSize, dwWritten;
BITMAP Bitmap;
//位图属性结构
BITMAPFILEHEADER bmfHdr;
//位图文件头结构
BITMAPINFOHEADER bi;
//位图信息头结构
LPBITMAPINFOHEADER lpbi;
//指向位图信息头结构
HANDLE fh, hDib, hPal;
HPALETTE hOldPal = NULL;
//定义文件,分配内存句柄,调色板句柄
//计算位图文件每个像素所占字节数
//hDC = CreateDC(_T("DISPLAY"), NULL, NULL, NULL);
iBits = GetDeviceCaps(hDC, BITSPIXEL) * GetDeviceCaps(hDC, PLANES);
//DeleteDC(hDC);
if (iBits <= 1)
{
wBitCount = 1;
}
else if (iBits <= 4)
{
wBitCount = 4;
}
else if (iBits <= 8)
{
wBitCount = 8;
}
else if (iBits <= 24)
{
wBitCount = 24;
}
else
{
wBitCount = 32;
}
//计算调色板大小
if (wBitCount <= 8)
{
dwPaletteSize = (1 << wBitCount)*sizeof(RGBQUAD);
}
//设置位图信息头结构
GetObject(hBitmap, sizeof(BITMAP), (LPSTR)&Bitmap);
bi.biSize = sizeof(BITMAPINFOHEADER);
bi.biWidth = Bitmap.bmWidth;
bi.biHeight = Bitmap.bmHeight;
bi.biPlanes = 1;
bi.biBitCount = wBitCount;
bi.biCompression = BI_RGB;
bi.biSizeImage = 0;
bi.biXPelsPerMeter = 0;
bi.biYPelsPerMeter = 0;
bi.biClrUsed = 0;
bi.biClrImportant = 0;
dwBmBitsSize = ((Bitmap.bmWidth*wBitCount + 31) / 32) * 4 * Bitmap.bmHeight;
//为位图内容分配内存
hDib = GlobalAlloc(GHND, dwBmBitsSize + dwPaletteSize + sizeof(BITMAPINFOHEADER));
lpbi = (LPBITMAPINFOHEADER)GlobalLock(hDib);
*lpbi = bi;
// 处理调色板
hPal = GetStockObject(DEFAULT_PALETTE);
if (hPal)
{
hDC = ::GetDC(NULL);
hOldPal = SelectPalette(hDC, (HPALETTE)hPal, FALSE);
RealizePalette(hDC);
}
// 获取该调色板下新的像素值
GetDIBits(hDC, hBitmap, 0, (UINT)Bitmap.bmHeight, (LPSTR)lpbi + sizeof(BITMAPINFOHEADER) + dwPaletteSize, (BITMAPINFO *)lpbi, DIB_RGB_COLORS);
//恢复调色板
if (hOldPal)
{
SelectPalette(hDC, hOldPal, TRUE);
RealizePalette(hDC);
::ReleaseDC(NULL, hDC);
}
//创建位图文件
fh = CreateFile(ptFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL);
if (fh == INVALID_HANDLE_VALUE)
{
GlobalUnlock(hDib);
GlobalFree(hDib);
return FALSE;
}
//设置位图文件头
bmfHdr.bfType = 0x4D42; // "BM"
dwDIBSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + dwPaletteSize + dwBmBitsSize;
bmfHdr.bfSize = dwDIBSize;
bmfHdr.bfReserved1 = 0;
bmfHdr.bfReserved2 = 0;
bmfHdr.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + (DWORD)sizeof(BITMAPINFOHEADER) + dwPaletteSize;
WriteFile(fh, (LPSTR)&bmfHdr, sizeof(BITMAPFILEHEADER), &dwWritten, NULL);
WriteFile(fh, (LPSTR)lpbi, sizeof(BITMAPINFOHEADER) + dwPaletteSize + dwBmBitsSize, &dwWritten, NULL);
GlobalUnlock(hDib);
GlobalFree(hDib);
CloseHandle(fh);
return false;
}
__inline static
bool SaveBitmapToFile(HBITMAP hBitmap, LPCTSTR ptFileName)
{
HDC hDC;
//设备描述表
int iBits;
//当前显示分辨率下每个像素所占字节数
WORD wBitCount;
//位图中每个像素所占字节数
//定义调色板大小, 位图中像素字节大小 , 位图文件大小 , 写入文件字节数
DWORD dwPaletteSize = 0, dwBmBitsSize, dwDIBSize, dwWritten;
BITMAP Bitmap;
//位图属性结构
BITMAPFILEHEADER bmfHdr;
//位图文件头结构
BITMAPINFOHEADER bi;
//位图信息头结构
LPBITMAPINFOHEADER lpbi;
//指向位图信息头结构
HANDLE fh, hDib, hPal;
HPALETTE hOldPal = NULL;
//定义文件,分配内存句柄,调色板句柄
//计算位图文件每个像素所占字节数
hDC = CreateDC(_T("DISPLAY"), NULL, NULL, NULL);
iBits = GetDeviceCaps(hDC, BITSPIXEL) * GetDeviceCaps(hDC, PLANES);
DeleteDC(hDC);
if (iBits <= 1)
{
wBitCount = 1;
}
else if (iBits <= 4)
{
wBitCount = 4;
}
else if (iBits <= 8)
{
wBitCount = 8;
}
else if (iBits <= 24)
{
wBitCount = 24;
}
else
{
wBitCount = 32;
}
//计算调色板大小
if (wBitCount <= 8)
{
dwPaletteSize = (1 << wBitCount)*sizeof(RGBQUAD);
}
//设置位图信息头结构
GetObject(hBitmap, sizeof(BITMAP), (LPSTR)&Bitmap);
bi.biSize = sizeof(BITMAPINFOHEADER);
bi.biWidth = Bitmap.bmWidth;
bi.biHeight = Bitmap.bmHeight;
bi.biPlanes = 1;
bi.biBitCount = wBitCount;
bi.biCompression = BI_RGB;
bi.biSizeImage = 0;
bi.biXPelsPerMeter = 0;
bi.biYPelsPerMeter = 0;
bi.biClrUsed = 0;
bi.biClrImportant = 0;
dwBmBitsSize = ((Bitmap.bmWidth*wBitCount + 31) / 32) * 4 * Bitmap.bmHeight;
//为位图内容分配内存
hDib = GlobalAlloc(GHND, dwBmBitsSize + dwPaletteSize + sizeof(BITMAPINFOHEADER));
lpbi = (LPBITMAPINFOHEADER)GlobalLock(hDib);
*lpbi = bi;
// 处理调色板
hPal = GetStockObject(DEFAULT_PALETTE);
if (hPal)
{
hDC = ::GetDC(NULL);
hOldPal = SelectPalette(hDC, (HPALETTE)hPal, FALSE);
RealizePalette(hDC);
}
// 获取该调色板下新的像素值
GetDIBits(hDC, hBitmap, 0, (UINT)Bitmap.bmHeight, (LPSTR)lpbi + sizeof(BITMAPINFOHEADER) + dwPaletteSize, (BITMAPINFO *)lpbi, DIB_RGB_COLORS);
//恢复调色板
if (hOldPal)
{
SelectPalette(hDC, hOldPal, TRUE);
RealizePalette(hDC);
::ReleaseDC(NULL, hDC);
}
//创建位图文件
fh = CreateFile(ptFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL);
if (fh == INVALID_HANDLE_VALUE)
{
GlobalUnlock(hDib);
GlobalFree(hDib);
return FALSE;
}
//设置位图文件头
bmfHdr.bfType = 0x4D42; // "BM"
dwDIBSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + dwPaletteSize + dwBmBitsSize;
bmfHdr.bfSize = dwDIBSize;
bmfHdr.bfReserved1 = 0;
bmfHdr.bfReserved2 = 0;
bmfHdr.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + (DWORD)sizeof(BITMAPINFOHEADER) + dwPaletteSize;
WriteFile(fh, (LPSTR)&bmfHdr, sizeof(BITMAPFILEHEADER), &dwWritten, NULL);
WriteFile(fh, (LPSTR)lpbi, sizeof(BITMAPINFOHEADER) + dwPaletteSize + dwBmBitsSize, &dwWritten, NULL);
GlobalUnlock(hDib);
GlobalFree(hDib);
CloseHandle(fh);
return false;
}
__inline static
HBITMAP GetBitmapFromDC(HDC hDC, RECT rc, RECT rcMemory = { 0 })
{
HDC hMemoryDC = NULL;
HBITMAP hBitmap = NULL;
HBITMAP hBitmapTemp = NULL;
//创建设备上下文(HDC)
hMemoryDC = CreateCompatibleDC(hDC);
//创建HBITMAP
hBitmap = CreateCompatibleBitmap(hDC, rc.right - rc.left, rc.bottom - rc.top);
hBitmapTemp = (HBITMAP)SelectObject(hMemoryDC, hBitmap);
if (rcMemory.right <= rcMemory.left)
{
rcMemory.right = rcMemory.left + rc.right - rc.left;
}
if (rcMemory.bottom <= rcMemory.top)
{
rcMemory.bottom = rcMemory.top + rc.bottom - rc.top;
}
//得到位图缓冲区
StretchBlt(hMemoryDC, rcMemory.left, rcMemory.top, rcMemory.right - rcMemory.left, rcMemory.bottom - rcMemory.top,
hDC, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, SRCCOPY);
//得到最终的位图信息
hBitmap = (HBITMAP)SelectObject(hMemoryDC, hBitmapTemp);
//释放内存
DeleteObject(hBitmapTemp);
hBitmapTemp = NULL;
::DeleteDC(hMemoryDC);
hMemoryDC = NULL;
return hBitmap;
}
__inline static TSTRING HResultToTString(HRESULT hInResult)
{
HRESULT hResult = S_FALSE;
TSTRING tsDescription(_T(""));
IErrorInfo * pErrorInfo = NULL;
BSTR pbstrDescription = NULL;
hResult = ::GetErrorInfo(NULL, &pErrorInfo);
if (SUCCEEDED(hResult) && pErrorInfo)
{
hResult = pErrorInfo->GetDescription(&pbstrDescription);
if (SUCCEEDED(hResult) && pbstrDescription)
{
tsDescription = Convert::WToT(pbstrDescription);
}
}
return tsDescription;
}
///////////////////////////////////////////////////////////
//如下代码段实现的功能是从指定的路径中读取图片,并显示出来
//
__inline static void ImagesRenderDisplay(HDC hDC, RECT * pRect, const _TCHAR * tImagePath)
{
HANDLE hFile = NULL;
HRESULT hResult = S_FALSE;
DWORD dwReadedSize = 0; //保存实际读取的文件大小
IStream *pIStream = NULL;//创建一个IStream接口指针,用来保存图片流
IPicture *pIPicture = NULL;//创建一个IPicture接口指针,表示图片对象
VOID * pImageMemory = NULL;
HGLOBAL hImageMemory = NULL;
OLE_XSIZE_HIMETRIC hmWidth = 0;
OLE_YSIZE_HIMETRIC hmHeight = 0;
LARGE_INTEGER liFileSize = { 0, 0 };
hFile = ::CreateFile(tImagePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);//从指定的路径szImagePath中读取文件句柄
if (hFile != INVALID_HANDLE_VALUE)
{
liFileSize.LowPart = ::GetFileSize(hFile, (DWORD *)&liFileSize.HighPart); //获得图片文件的大小,用来分配全局内存
hImageMemory = ::GlobalAlloc(GMEM_MOVEABLE, liFileSize.QuadPart); //给图片分配全局内存
if (hImageMemory)
{
pImageMemory = ::GlobalLock(hImageMemory); //锁定内存
::ReadFile(hFile, pImageMemory, liFileSize.QuadPart, &dwReadedSize, NULL); //读取图片到全局内存当中
hResult = ::CreateStreamOnHGlobal(hImageMemory, FALSE, &pIStream); //用全局内存初使化IStream接口指针
if (SUCCEEDED(hResult) && pIStream)
{
//用OleLoadPicture获得IPicture接口指针
hResult = ::OleLoadPicture(pIStream, 0, FALSE, IID_IPicture, (LPVOID*)&(pIPicture));
//TSTRING tsError = HResultToTString(hResult);
//得到IPicture COM接口对象后,就可以进行获得图片信息、显示图片等操作
if (SUCCEEDED(hResult) && pIPicture)
{
pIPicture->get_Width(&hmWidth); //用接口方法获得图片的宽和高
pIPicture->get_Height(&hmHeight); //用接口方法获得图片的宽和高
pIPicture->Render(hDC, pRect->left, pRect->top, pRect->right - pRect->left, pRect->bottom - pRect->top, 0, hmHeight, hmWidth, -hmHeight, NULL); //在指定的DC上绘出图片
}
}
}
}
if (hImageMemory)
{
::GlobalUnlock(hImageMemory); //解锁内存
::GlobalFree(hImageMemory); //释放全局内存
hImageMemory = NULL;
}
if (pIPicture)
{
pIPicture->Release(); //释放pIPicture
pIPicture = NULL;
}
if (pIStream)
{
pIStream->Release(); //释放pIStream
pIStream = NULL;
}
if (hFile != INVALID_HANDLE_VALUE)
{
::CloseHandle(hFile); //关闭文件句柄
hFile = INVALID_HANDLE_VALUE;
}
}
///////////////////////////////////////////////////////////
//如下代码段实现的功能是从指定的路径中读取图片,并显示出来
//
__inline static void ImagesDisplayScreen(SIZE & szImageSize, const _TCHAR * tImagePath)
{
HANDLE hFile = NULL;
DWORD dwReadedSize = 0; //保存实际读取的文件大小
IStream *pIStream = NULL;//创建一个IStream接口指针,用来保存图片流
IPicture *pIPicture = NULL;//创建一个IPicture接口指针,表示图片对象
VOID * pImageMemory = NULL;
HGLOBAL hImageMemory = NULL;
OLE_XSIZE_HIMETRIC hmWidth = 0;
OLE_YSIZE_HIMETRIC hmHeight = 0;
LARGE_INTEGER liFileSize = { 0, 0 };
hFile = ::CreateFile(tImagePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);//从指定的路径szImagePath中读取文件句柄
if (hFile != INVALID_HANDLE_VALUE)
{
liFileSize.LowPart = ::GetFileSize(hFile, (DWORD *)&liFileSize.HighPart); //获得图片文件的大小,用来分配全局内存
hImageMemory = ::GlobalAlloc(GMEM_MOVEABLE, liFileSize.QuadPart); //给图片分配全局内存
if (hImageMemory)
{
pImageMemory = ::GlobalLock(hImageMemory); //锁定内存
::ReadFile(hFile, pImageMemory, liFileSize.QuadPart, &dwReadedSize, NULL); //读取图片到全局内存当中
::CreateStreamOnHGlobal(hImageMemory, false, &pIStream); //用全局内存初使化IStream接口指针
if (pIStream)
{
::OleLoadPicture(pIStream, 0, false, IID_IPicture, (LPVOID*)&(pIPicture));//用OleLoadPicture获得IPicture接口指针
if (pIPicture) //得到IPicture COM接口对象后,就可以进行获得图片信息、显示图片等操作
{
pIPicture->get_Width(&hmWidth); //用接口方法获得图片的宽和高
pIPicture->get_Height(&hmHeight); //用接口方法获得图片的宽和高
szImageSize.cx = hmWidth;
szImageSize.cy = hmHeight;
}
}
}
}
if (hImageMemory)
{
::GlobalUnlock(hImageMemory); //解锁内存
::GlobalFree(hImageMemory); //释放全局内存
hImageMemory = NULL;
}
if (pIPicture)
{
pIPicture->Release(); //释放pIPicture
pIPicture = NULL;
}
if (pIStream)
{
pIStream->Release(); //释放pIStream
pIStream = NULL;
}
if (hFile != INVALID_HANDLE_VALUE)
{
::CloseHandle(hFile); //关闭文件句柄
hFile = INVALID_HANDLE_VALUE;
}
}
__inline static
void DrawMemoryBitmap(HDC &dc, HWND hWnd, LONG lWidth, LONG lHeight, HBITMAP hBitmap)
{
RECT rect;
HBITMAP hOldBitmap;
int disHeight, disWidth;
GetClientRect(hWnd, &rect);//获取客户区大小
disHeight = rect.bottom - rect.top;
disWidth = rect.right - rect.left;
HDC mDc = ::CreateCompatibleDC(dc);//创建当前上下文的兼容dc(内存DC)
hOldBitmap = (HBITMAP)::SelectObject(mDc, hBitmap);//将位图加载到内存DC
//拷贝内存DC数据块到当前DC,自动拉伸
::StretchBlt(dc, 0, 0, disWidth, disHeight, mDc, 0, 0, lWidth, lHeight, SRCCOPY);
//恢复内存原始数据
::SelectObject(mDc, hOldBitmap);
//删除资源,防止泄漏
::DeleteObject(hBitmap);
::DeleteDC(mDc);
}
__inline static
void DrawImage(HDC &dc, HWND hWnd, LONG lWidth, LONG lHeight, LPCTSTR ptFileName)
{
RECT rect;
HBITMAP hOrgBitmap;
HBITMAP hOldBitmap;
int disHeight, disWidth;
GetClientRect(hWnd, &rect);//获取客户区大小
disHeight = rect.bottom - rect.top;
disWidth = rect.right - rect.left;
//加载图片
hOrgBitmap = (HBITMAP)::LoadImage(GetModuleHandle(NULL), ptFileName, IMAGE_BITMAP, lWidth, lHeight, LR_LOADFROMFILE);
HDC mDc = ::CreateCompatibleDC(dc);//创建当前上下文的兼容dc(内存DC)
hOldBitmap = (HBITMAP)::SelectObject(mDc, hOrgBitmap);//将位图加载到内存DC
//拷贝内存DC数据块到当前DC,自动拉伸
::StretchBlt(dc, 0, 0, disWidth, disHeight, mDc, 0, 0, lWidth, lHeight, SRCCOPY);
//恢复内存原始数据
::SelectObject(mDc, hOldBitmap);
//删除资源,防止泄漏
::DeleteObject(hOrgBitmap);
::DeleteDC(mDc);
mDc = NULL;
}
__inline static
HBITMAP DrawAlphaBlend(HWND hWnd, HDC hDCWnd)
{
typedef struct _ALPHABLENDRECT {
HDC HDCDST;
RECT RCDST;
HDC HDCSRC;
RECT RCSRC;
BLENDFUNCTION BF;// structure for alpha blending
}ALPHABLENDRECT, *PALPHABLENDRECT;
UINT32 x = 0;// stepping variables
UINT32 y = 0;// stepping variables
HDC hDC = NULL;// handle of the DC we will create
UCHAR uA = 0x00;// used for doing transparent gradient
UCHAR uR = 0x00;
UCHAR uG = 0x00;
UCHAR uB = 0x00;
float fAF = 0.0f;// used to do premultiply
VOID * pvBits = 0;// pointer to DIB section
RECT rcWnd = { 0 };// used for getting window dimensions
HBITMAP hBitmap = NULL;// bitmap handle
BITMAPINFO bmi = { 0 };// bitmap header
ULONG ulWindowWidth = 0;// window width/height
ULONG ulBitmapWidth = 0;// bitmap width/height
ULONG ulWindowHeight = 0;// window width/height
ULONG ulBitmapHeight = 0;// bitmap width/height
ALPHABLENDRECT abrc = { 0 };
// get dest dc
abrc.HDCDST = hDCWnd;
// get window dimensions
::GetClientRect(hWnd, &rcWnd);
// calculate window width/height
ulWindowWidth = rcWnd.right - rcWnd.left;
ulWindowHeight = rcWnd.bottom - rcWnd.top;
// make sure we have at least some window size
if ((!ulWindowWidth) || (!ulWindowHeight))
{
return NULL;
}
// divide the window into 3 horizontal areas
ulWindowHeight = ulWindowHeight / 3;
// create a DC for our bitmap -- the source DC for AlphaBlend
abrc.HDCSRC = ::CreateCompatibleDC(abrc.HDCDST);
// zero the memory for the bitmap info
::ZeroMemory(&bmi, sizeof(BITMAPINFO));
// setup bitmap info
// set the bitmap width and height to 60% of the width and height of each of the three horizontal areas. Later on, the blending will occur in the center of each of the three areas.
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = ulBitmapWidth = ulWindowWidth;// -(ulWindowWidth / 5) * 2;
bmi.bmiHeader.biHeight = ulBitmapHeight = ulWindowHeight - (ulWindowHeight / 5) * 2;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;// four 8-bit components
bmi.bmiHeader.biCompression = BI_RGB;
bmi.bmiHeader.biSizeImage = ulBitmapWidth * ulBitmapHeight * 4;
// create our DIB section and select the bitmap into the dc
hBitmap = ::CreateDIBSection(abrc.HDCSRC, &bmi, DIB_RGB_COLORS, &pvBits, NULL, 0x00);
::SelectObject(abrc.HDCSRC, hBitmap);
// in top window area, constant alpha = 50%, but no source alpha
// the color format for each pixel is 0xaarrggbb
// set all pixels to blue and set source alpha to zero
for (y = 0; y < ulBitmapHeight; y++)
{
for (x = 0; x < ulBitmapWidth; x++)
{
((UINT32 *)pvBits)[x + y * ulBitmapWidth] = 0x0000FF00;// 0x000000FF;
}
}
abrc.RCDST.left = 0;// ulWindowWidth / 5;
abrc.RCDST.top = ulWindowHeight / 5;
abrc.RCDST.right = ulBitmapWidth + abrc.RCDST.left;
abrc.RCDST.bottom = ulBitmapHeight + abrc.RCDST.top;
abrc.RCSRC.left = 0;
abrc.RCSRC.top = 0;
abrc.RCSRC.right = ulBitmapWidth + abrc.RCSRC.left;
abrc.RCSRC.bottom = ulBitmapHeight + abrc.RCSRC.top;
abrc.BF.BlendOp = AC_SRC_OVER;
abrc.BF.BlendFlags = 0;
abrc.BF.AlphaFormat = 0;// ignore source alpha channel
abrc.BF.SourceConstantAlpha = 0x7F;// half of 0x7F = 50% transparency
if (!AlphaBlend(abrc.HDCDST,
abrc.RCDST.left, abrc.RCDST.top,
abrc.RCDST.right - abrc.RCDST.left,
abrc.RCDST.bottom - abrc.RCDST.top,
abrc.HDCSRC,
abrc.RCSRC.left, abrc.RCSRC.top,
abrc.RCSRC.right - abrc.RCSRC.left,
abrc.RCSRC.bottom - abrc.RCSRC.top,
abrc.BF))
{
return NULL;// alpha blend failed
}
// in middle window area, constant alpha = 100% (disabled), source
// alpha is 0 in middle of bitmap and opaque in rest of bitmap
for (y = 0; y < ulBitmapHeight; y++)
{
for (x = 0; x < ulBitmapWidth; x++)
{
if ((x > (int)(ulBitmapWidth / 5)) && (x < (ulBitmapWidth - ulBitmapWidth / 5)) &&
(y >(int)(ulBitmapHeight / 5)) && (y < (ulBitmapHeight - ulBitmapHeight / 5)))
{
//in middle of bitmap: source alpha = 0 (transparent).
// This means multiply each color component by 0x00.
// Thus, after AlphaBlend, we have A, 0x00 * R,
// 0x00 * G,and 0x00 * B (which is 0x00000000)
// for now, set all pixels to red
((UINT32 *)pvBits)[x + y * ulBitmapWidth] = 0x00FF0000;
}
else
{
// in the rest of bitmap, source alpha = 0xFF (opaque)
// and set all pixels to blue
((UINT32 *)pvBits)[x + y * ulBitmapWidth] = 0xFF00FF00;// 0xFF0000FF;
}
}
}
abrc.RCDST.left = 0;// ulWindowWidth / 5;
abrc.RCDST.top = ulWindowHeight / 5 + ulWindowHeight;
abrc.RCDST.right = ulBitmapWidth + abrc.RCDST.left;
abrc.RCDST.bottom = ulBitmapHeight + abrc.RCDST.top;
abrc.RCSRC.left = 0;
abrc.RCSRC.top = 0;
abrc.RCSRC.right = ulBitmapWidth + abrc.RCSRC.left;
abrc.RCSRC.bottom = ulBitmapHeight + abrc.RCSRC.top;
abrc.BF.BlendOp = AC_SRC_OVER;
abrc.BF.BlendFlags = 0;
abrc.BF.AlphaFormat = MY_AC_SRC_ALPHA;// ignore source alpha channel
abrc.BF.SourceConstantAlpha = 0xFF;// half of 0xFF = 50% transparency
if (!AlphaBlend(abrc.HDCDST,
abrc.RCDST.left, abrc.RCDST.top,
abrc.RCDST.right - abrc.RCDST.left,
abrc.RCDST.bottom - abrc.RCDST.top,
abrc.HDCSRC,
abrc.RCSRC.left, abrc.RCSRC.top,
abrc.RCSRC.right - abrc.RCSRC.left,
abrc.RCSRC.bottom - abrc.RCSRC.top,
abrc.BF))
{
return NULL;// alpha blend failed
}
// bottom window area, use constant alpha = 75% and a changing
// source alpha. Create a gradient effect using source alpha, and
// then fade it even more with constant alpha
uR = 0x00;
uG = 0xFF;// 0x00;
uB = 0x00;// 0xFF;
for (y = 0; y < ulBitmapHeight; y++)
{
for (x = 0; x < ulBitmapWidth; x++)
{
// for a simple gradient, base the alpha value on the x
// value of the pixel
uA = (UCHAR)((float)x / (float)ulBitmapWidth * 0xFF);
//calculate the factor by which we multiply each component
fAF = (float)uA / (float)0xFF;
// multiply each pixel by fAlphaFactor, so each component
// is less than or equal to the alpha value.
((UINT32 *)pvBits)[x + y * ulBitmapWidth] =
((UCHAR)(uA * 0x1) << 0x18) | //0xAA000000
((UCHAR)(uR * fAF) << 0x10) | //0x00RR0000
((UCHAR)(uG * fAF) << 0x08) | //0x0000GG00
((UCHAR)(uB * fAF) << 0x00); //0x000000BB
}
}
abrc.RCDST.left = 0;// ulWindowWidth / 5;
abrc.RCDST.top = ulWindowHeight / 5 + 2 * ulWindowHeight;
abrc.RCDST.right = ulBitmapWidth + abrc.RCDST.left;
abrc.RCDST.bottom = ulBitmapHeight + abrc.RCDST.top;
abrc.RCSRC.left = 0;
abrc.RCSRC.top = 0;
abrc.RCSRC.right = ulBitmapWidth + abrc.RCSRC.left;
abrc.RCSRC.bottom = ulBitmapHeight + abrc.RCSRC.top;
abrc.BF.BlendOp = AC_SRC_OVER;
abrc.BF.BlendFlags = 0;
abrc.BF.AlphaFormat = MY_AC_SRC_ALPHA;// ignore source alpha channel
abrc.BF.SourceConstantAlpha = 0xBF;// use constant alpha, with 75% opaqueness
if (!AlphaBlend(abrc.HDCDST,
abrc.RCDST.left, abrc.RCDST.top,
abrc.RCDST.right - abrc.RCDST.left,
abrc.RCDST.bottom - abrc.RCDST.top,
abrc.HDCSRC,
abrc.RCSRC.left, abrc.RCSRC.top,
abrc.RCSRC.right - abrc.RCSRC.left,
abrc.RCSRC.bottom - abrc.RCSRC.top,
abrc.BF))
{
return NULL;// alpha blend failed
}
// do cleanup
DeleteObject(hBitmap);
DeleteDC(hDC);
hDC = NULL;
return hBitmap;
}
__inline static
HBITMAP DrawAlphaBlendRect(HWND hWnd, HDC hDCWnd, RECT * pRect)
{
typedef struct _ALPHABLENDRECT {
HDC HDCDST;
RECT RCDST;
HDC HDCSRC;
RECT RCSRC;
BLENDFUNCTION BF;// structure for alpha blending
}ALPHABLENDRECT, *PALPHABLENDRECT;
UINT32 x = 0;// stepping variables
UINT32 y = 0;// stepping variables
UCHAR uA = 0x00;// used for doing transparent gradient
UCHAR uR = 0x00;
UCHAR uG = 0x00;
UCHAR uB = 0x00;
float fAF = 0.0f;// used to do premultiply
VOID * pvBits = 0;// pointer to DIB section
RECT rcWnd = { 0 };// used for getting window dimensions
HBITMAP hBitmap = NULL;// bitmap handle
BITMAPINFO bmi = { 0 };// bitmap header
ULONG ulWindowWidth = 0;// window width/height
ULONG ulBitmapWidth = 0;// bitmap width/height
ULONG ulWindowHeight = 0;// window width/height
ULONG ulBitmapHeight = 0;// bitmap width/height
ALPHABLENDRECT abrc = { 0 };
// get dest dc
abrc.HDCDST = hDCWnd;
// get window dimensions
::GetClientRect(hWnd, &rcWnd);
// calculate window width/height
ulWindowWidth = rcWnd.right - rcWnd.left;
ulWindowHeight = rcWnd.bottom - rcWnd.top;
// make sure we have at least some window size
if ((!ulWindowWidth) || (!ulWindowHeight))
{
return NULL;
}
// create a DC for our bitmap -- the source DC for AlphaBlend
abrc.HDCSRC = ::CreateCompatibleDC(abrc.HDCDST);
// zero the memory for the bitmap info
::ZeroMemory(&bmi, sizeof(BITMAPINFO));
// setup bitmap info
// set the bitmap width and height to 60% of the width and height of each of the three horizontal areas. Later on, the blending will occur in the center of each of the three areas.
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = ulBitmapWidth = ulWindowWidth;
bmi.bmiHeader.biHeight = ulBitmapHeight = ulWindowHeight;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;// four 8-bit components
bmi.bmiHeader.biCompression = BI_RGB;
bmi.bmiHeader.biSizeImage = ulBitmapWidth * ulBitmapHeight * 4;
// create our DIB section and select the bitmap into the dc
hBitmap = ::CreateDIBSection(abrc.HDCSRC, &bmi, DIB_RGB_COLORS, &pvBits, NULL, 0x00);
::SelectObject(abrc.HDCSRC, hBitmap);
// in middle window area, constant alpha = 100% (disabled), source
// alpha is 0 in middle of bitmap and opaque in rest of bitmap
for (y = 0; y < ulBitmapHeight; y++)
{
for (x = 0; x < ulBitmapWidth; x++)
{
if ((x > (int)(pRect->left)) && (x < (ulBitmapWidth - pRect->right - 1)) &&
(y >(int)(pRect->top)) && (y < (ulBitmapHeight - pRect->bottom - 1)))
{
//in middle of bitmap: source alpha = 0 (transparent).
// This means multiply each color component by 0x00.
// Thus, after AlphaBlend, we have A, 0x00 * R,
// 0x00 * G,and 0x00 * B (which is 0x00000000)
// for now, set all pixels to red
((UINT32 *)pvBits)[x + y * ulBitmapWidth] = 0x7F0000FF;// 0x00FF0000;
}
else
{
// in the rest of bitmap, source alpha = 0xFF (opaque)
// and set all pixels to blue
((UINT32 *)pvBits)[x + y * ulBitmapWidth] = 0x7F00FF00;// 0xFF0000FF;
}
}
}
abrc.RCDST.left = 0;
abrc.RCDST.top = 0;
abrc.RCDST.right = ulBitmapWidth + abrc.RCDST.left;
abrc.RCDST.bottom = ulBitmapHeight + abrc.RCDST.top;
abrc.RCSRC.left = 0;
abrc.RCSRC.top = 0;
abrc.RCSRC.right = ulBitmapWidth + abrc.RCSRC.left;
abrc.RCSRC.bottom = ulBitmapHeight + abrc.RCSRC.top;
abrc.BF.BlendOp = AC_SRC_OVER;
abrc.BF.BlendFlags = 0;
abrc.BF.AlphaFormat = MY_AC_SRC_ALPHA;// ignore source alpha channel
abrc.BF.SourceConstantAlpha = 0xFF;// use constant alpha, with 75% opaqueness
if (!AlphaBlend(abrc.HDCDST,
abrc.RCDST.left, abrc.RCDST.top,
abrc.RCDST.right - abrc.RCDST.left,
abrc.RCDST.bottom - abrc.RCDST.top,
abrc.HDCSRC,
abrc.RCSRC.left, abrc.RCSRC.top,
abrc.RCSRC.right - abrc.RCSRC.left,
abrc.RCSRC.bottom - abrc.RCSRC.top,
abrc.BF))
{
return NULL;// alpha blend failed
}
SaveBitmapToFile(abrc.HDCDST, hBitmap, _T("d:\\test.bmp"));
// do cleanup
DeleteObject(hBitmap);
DeleteDC(abrc.HDCSRC);
abrc.HDCSRC = NULL;
return hBitmap;
}
#define ARGB(uA,uR,uG,uB) ((UCHAR)(uA) << 0x18) | ((UCHAR)(uR) << 0x10) | ((UCHAR)(uG) << 0x08) | ((UCHAR)(uB) << 0x00)
__inline static
HBITMAP DrawAlphaBlendRect(HWND hWnd, ULONG(&uARGB)[2], HDC hDCWnd, RECT * pRect)
{
typedef struct _ALPHABLENDRECT {
HDC HDCDST;
RECT RCDST;
HDC HDCSRC;
RECT RCSRC;
BLENDFUNCTION BF;// structure for alpha blending
}ALPHABLENDRECT, *PALPHABLENDRECT;
UINT32 x = 0;// stepping variables
UINT32 y = 0;// stepping variables
UCHAR uA = 0x00;// used for doing transparent gradient
UCHAR uR = 0x00;
UCHAR uG = 0x00;
UCHAR uB = 0x00;
float fAF = 0.0f;// used to do premultiply
VOID * pvBits = 0;// pointer to DIB section
RECT rcWnd = { 0 };// used for getting window dimensions
HBITMAP hBitmap = NULL;// bitmap handle
BITMAPINFO bmi = { 0 };// bitmap header
ULONG ulWindowWidth = 0;// window width/height
ULONG ulBitmapWidth = 0;// bitmap width/height
ULONG ulWindowHeight = 0;// window width/height
ULONG ulBitmapHeight = 0;// bitmap width/height
ALPHABLENDRECT abrc = { 0 };
// get dest dc
abrc.HDCDST = hDCWnd;
// get window dimensions
::GetClientRect(hWnd, &rcWnd);
// calculate window width/height
ulWindowWidth = rcWnd.right - rcWnd.left;
ulWindowHeight = rcWnd.bottom - rcWnd.top;
// make sure we have at least some window size
if ((!ulWindowWidth) || (!ulWindowHeight))
{
return NULL;
}
// create a DC for our bitmap -- the source DC for AlphaBlend
abrc.HDCSRC = ::CreateCompatibleDC(abrc.HDCDST);
// zero the memory for the bitmap info
::ZeroMemory(&bmi, sizeof(BITMAPINFO));
// setup bitmap info
// set the bitmap width and height to 60% of the width and height of each of the three horizontal areas. Later on, the blending will occur in the center of each of the three areas.
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = ulBitmapWidth = ulWindowWidth;
bmi.bmiHeader.biHeight = ulBitmapHeight = ulWindowHeight;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;// four 8-bit components
bmi.bmiHeader.biCompression = BI_RGB;
bmi.bmiHeader.biSizeImage = ulBitmapWidth * ulBitmapHeight * 4;
// create our DIB section and select the bitmap into the dc
hBitmap = ::CreateDIBSection(abrc.HDCSRC, &bmi, DIB_RGB_COLORS, &pvBits, NULL, 0x00);
::SelectObject(abrc.HDCSRC, hBitmap);
// in middle window area, constant alpha = 100% (disabled), source
// alpha is 0 in middle of bitmap and opaque in rest of bitmap
for (x = 0; x < ulBitmapWidth; x++)
{
for (y = 0; y < ulBitmapHeight; y++)
{
if ((x >(int)(pRect->right)) && (x < (ulBitmapWidth - pRect->left - 1)) &&
(y >(int)(pRect->bottom)) && (y < (ulBitmapHeight - pRect->top - 1)))
{
//in middle of bitmap: source alpha = 0 (transparent).
// This means multiply each color component by 0x00.
// Thus, after AlphaBlend, we have A, 0x00 * R,
// 0x00 * G,and 0x00 * B (which is 0x00000000)
// for now, set all pixels to red
((UINT32 *)pvBits)[x + y * ulBitmapWidth] = uARGB[0];//0x7F0000FF;// 0x00FF0000;
}
else
{
// in the rest of bitmap, source alpha = 0xFF (opaque)
// and set all pixels to blue
((UINT32 *)pvBits)[x + y * ulBitmapWidth] = uARGB[1];//0x7F00FF00;// 0xFF0000FF;
}
}
}
abrc.RCDST.left = 0;
abrc.RCDST.top = 0;
abrc.RCDST.right = ulBitmapWidth + abrc.RCDST.left;
abrc.RCDST.bottom = ulBitmapHeight + abrc.RCDST.top;
abrc.RCSRC.left = 0;
abrc.RCSRC.top = 0;
abrc.RCSRC.right = ulBitmapWidth + abrc.RCSRC.left;
abrc.RCSRC.bottom = ulBitmapHeight + abrc.RCSRC.top;
abrc.BF.BlendOp = AC_SRC_OVER;
abrc.BF.BlendFlags = 0;
abrc.BF.AlphaFormat = AC_SRC_ALPHA;// ignore source alpha channel
abrc.BF.SourceConstantAlpha = 0xFF;// use constant alpha, with 75% opaqueness
if (!AlphaBlend(abrc.HDCDST,
abrc.RCDST.left, abrc.RCDST.top,
abrc.RCDST.right - abrc.RCDST.left,
abrc.RCDST.bottom - abrc.RCDST.top,
abrc.HDCSRC,
abrc.RCSRC.left, abrc.RCSRC.top,
abrc.RCSRC.right - abrc.RCSRC.left,
abrc.RCSRC.bottom - abrc.RCSRC.top,
abrc.BF))
{
return NULL;// alpha blend failed
}
//SaveBitmapToFile(abrc.HDCDST, hBitmap, _T("d:\\test.bmp"));
// do cleanup
DeleteObject(hBitmap);
DeleteDC(abrc.HDCSRC);
abrc.HDCSRC = NULL;
return hBitmap;
}
__inline static
HFONT CreatePaintFont(LPCTSTR ptszFaceName = _T("宋体"),
LONG lfHeight = 12,
LONG lfWidth = 0,
LONG lfEscapement = 0,
LONG lfOrientation = 0,
LONG lfWeight = FW_NORMAL,
BYTE lfItalic = FALSE,
BYTE lfUnderline = FALSE,
BYTE lfStrikeOut = FALSE,
BYTE lfCharSet = ANSI_CHARSET,
BYTE lfOutPrecision = OUT_DEFAULT_PRECIS,
BYTE lfClipPrecision = CLIP_DEFAULT_PRECIS,
BYTE lfQuality = DEFAULT_QUALITY,
BYTE lfPitchAndFamily = DEFAULT_PITCH | FF_SWISS)
{
return CreateFont(lfHeight, lfWidth,
lfEscapement,
lfOrientation,
lfWeight,
lfItalic,
lfUnderline,
lfStrikeOut,
lfCharSet,
lfOutPrecision,
lfClipPrecision,
lfQuality,
lfPitchAndFamily,
ptszFaceName);
}
__inline static
void RectDrawText(HDC hDC, RECT * pRect, LPCTSTR ptszText, COLORREF clrTextColor = COLOR_WINDOWTEXT, HFONT hFont = NULL, UINT uFormat = DT_LEFT | DT_WORDBREAK)
{
HFONT hFontOld = NULL;
if (hFont)
{
hFontOld = (HFONT)SelectObject(hDC, hFont);
SetBkMode(hDC, TRANSPARENT);
SetTextColor(hDC, clrTextColor);
DrawText(hDC, ptszText, lstrlen(ptszText), pRect, uFormat);
(HFONT)SelectObject(hDC, hFontOld);
}
}
__inline static
HGLOBAL OpenResource(LPVOID & lpData, DWORD & dwSize, LPCTSTR lpName, LPCTSTR lpType, HMODULE hModule = ::GetModuleHandle(NULL))
{
BOOL bResult = FALSE;
HRSRC hRsrcRes = NULL;// handle/ptr. to res. info. in hSource
HGLOBAL hGLOBAL = NULL;// handle to loaded resource
// Locate the resource in the source image file.
hRsrcRes = ::FindResource(hModule, lpName, lpType);
if (hRsrcRes == NULL)
{
goto __LEAVE_CLEAN__;
}
////////////////////////////////////////////////////////////////////////////////////////////
// See:https://msdn.microsoft.com/en-us/library/windows/desktop/ms648047(v=vs.85).aspx
// A handle to the resource to be accessed. The LoadResource function returns this handle.
//Note that this parameter is listed as an HGLOBAL variable only for backward compatibility.
//Do not pass any value as a parameter other than a successful return value
//from the LoadResource function.
// Load the resource into global memory.
hGLOBAL = ::LoadResource(hModule, hRsrcRes);
if (hGLOBAL == NULL)
{
goto __LEAVE_CLEAN__;
}
// Lock the resource into global memory.
lpData = ::LockResource(hGLOBAL);
if (lpData == NULL)
{
FreeResource(hGLOBAL);
hGLOBAL = NULL;
goto __LEAVE_CLEAN__;
}
dwSize = ::SizeofResource(hModule, hRsrcRes);
__LEAVE_CLEAN__:
return hGLOBAL;
}
__inline static
BOOL ParseResrc(LPCTSTR ptszFileName, UINT uResourceID, LPCTSTR ptszTypeName, HMODULE hModule = ::GetModuleHandle(NULL))
{
DWORD dwSize = 0;
HANDLE hFile = NULL;
BOOL bResult = FALSE;
LPVOID lpData = NULL;
HGLOBAL hGlobal = NULL;
DWORD dwNumberOfBytesWritten = 0;
hGlobal = OpenResource(lpData, dwSize, MAKEINTRESOURCE(uResourceID), ptszTypeName, hModule);
//我们用刚才得到的pBuffer和dwSize来做一些需要的事情。可以直接在内存中使
//用,也可以写入到硬盘文件。这里我们简单的写入到硬盘文件,如果我们的自定
//义资源是作为嵌入DLL来应用,情况可能要复杂一些。
hFile = CreateFile(ptszFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile && hGlobal && dwSize > 0)
{
WriteFile(hFile, hGlobal, dwSize, &dwNumberOfBytesWritten, NULL);
CloseHandle(hFile);
bResult = TRUE;
}
return bResult;
}
__inline static
BOOL DragMove(HWND hWnd, RECT * pRect)
{
POINT pt = { 0 };
BOOL bResult = FALSE;
RECT rcWndOuter = { 0 };
RECT rcWndInner = { 0 };
GetCursorPos(&pt);
::GetWindowRect(hWnd, &rcWndOuter);
rcWndInner.left = rcWndOuter.left + pRect->left;
rcWndInner.top = rcWndOuter.top + pRect->top;
rcWndInner.right = rcWndOuter.right - pRect->right;
rcWndInner.bottom = rcWndOuter.bottom - pRect->bottom;
if ((PtInRect(&rcWndOuter, pt) && !PtInRect(&rcWndInner, pt)))
{
#ifndef _SYSCOMMAND_SC_DRAGMOVE
#define _SYSCOMMAND_SC_DRAGMOVE 0xF012
#endif // !_SYSCOMMAND_SC_DRAGMOVE
::SystemParametersInfo(SPI_SETDRAGFULLWINDOWS, TRUE, NULL, 0);
::SendMessage(hWnd, WM_SYSCOMMAND, _SYSCOMMAND_SC_DRAGMOVE, 0);
bResult = TRUE;
#ifdef _SYSCOMMAND_SC_DRAGMOVE
#undef _SYSCOMMAND_SC_DRAGMOVE
#endif // !_SYSCOMMAND_SC_DRAGMOVE
}
return bResult;
}
__inline static
BOOL DragMoveFull(HWND hWnd)
{
#ifndef _SYSCOMMAND_SC_DRAGMOVE
#define _SYSCOMMAND_SC_DRAGMOVE 0xF012
#endif // !_SYSCOMMAND_SC_DRAGMOVE
::SystemParametersInfo(SPI_SETDRAGFULLWINDOWS, TRUE, NULL, 0);
::SendMessage(hWnd, WM_SYSCOMMAND, _SYSCOMMAND_SC_DRAGMOVE, 0);
//RECT rc = { 0 };
//::GetClientRect(hWnd, &rc);
//::SystemParametersInfo(SPI_SETDRAGFULLWINDOWS, FALSE, NULL, 0);
//::PostMessage(hWnd, WM_NCLBUTTONDOWN, HTCAPTION, MAKELPARAM(rc.left, rc.top));
#ifdef _SYSCOMMAND_SC_DRAGMOVE
#undef _SYSCOMMAND_SC_DRAGMOVE
#endif // !_SYSCOMMAND_SC_DRAGMOVE
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//函数功能:设置圆角窗口
//函数参数:
// hWnd 要设置的窗口句柄
// pstEllipse 要设置圆角的横向半径和纵向半径
// prcExcepted 要排除圆角的左上右下侧大小
//返回值:无返回
__inline static void SetWindowEllispeFrame(HWND hWnd, SIZE * pszEllipse = 0, RECT * prcExcepted = 0, BOOL bErase = TRUE)
{
HRGN hRgnWindow = 0;
POINT ptPosition = { 0, 0 };
RECT rcWindow = { 0, 0, 0, 0 };
::GetWindowRect(hWnd, &rcWindow);
if (prcExcepted)
{
ptPosition.x = prcExcepted->left;
ptPosition.y = prcExcepted->top;
rcWindow.left += prcExcepted->left;
rcWindow.top += prcExcepted->top;
rcWindow.right -= prcExcepted->right;
rcWindow.bottom -= prcExcepted->bottom;
}
hRgnWindow = ::CreateRoundRectRgn(ptPosition.x, ptPosition.y, \
rcWindow.right - rcWindow.left, rcWindow.bottom - rcWindow.top, pszEllipse->cx, pszEllipse->cy);
if (hRgnWindow)
{
::SetWindowRgn(hWnd, hRgnWindow, bErase);
}
}
//////////////////////////////////////////////////////////////////////////
// 函数说明:不失真模式获取HWND的HBITMAP
// 参 数:窗口句柄
// 返 回 值:返回HBITMAP
// 编 写 者: ppshuai 20141126
//////////////////////////////////////////////////////////////////////////
__inline static HBITMAP HBITMAPFromHWND(HWND hWnd)
{
INT nX = 0;
INT nY = 0;
INT nWidth = 0;
INT nHeight = 0;
RECT rect = { 0 };
INT nMode = 0;
HDC hWndDC = NULL;
HDC hMemDC = NULL;
HBITMAP hOldBitmap = NULL;
HBITMAP hNewBitmap = NULL;
GetClientRect(hWnd, &rect);
nX = rect.left;
nY = rect.top;
nWidth = rect.right - rect.left;
nHeight = rect.bottom - rect.top;
hWndDC = GetDC(hWnd);
// 为屏幕设备描述表创建兼容的内存设备描述表
hMemDC = CreateCompatibleDC(hWndDC);
// 创建一个与屏幕设备描述表兼容的位图
hNewBitmap = CreateCompatibleBitmap(hWndDC, nWidth, nHeight);
// 把新位图选到内存设备描述表中
hOldBitmap = (HBITMAP)SelectObject(hMemDC, hNewBitmap);
// 设置不失真模式
nMode = SetStretchBltMode(hWndDC, COLORONCOLOR);
// 把屏幕设备描述表拷贝到内存设备描述表中
//BitBlt(hMemDC, 0, 0, nWidth, nHeight, hWndDC, nX, nY, SRCCOPY);
StretchBlt(hMemDC, 0, 0, nWidth, nHeight, hWndDC, nX, nY, nWidth, nHeight, SRCCOPY);
// 设置不失真模式
SetStretchBltMode(hMemDC, nMode);
// 得到屏幕位图的句柄
hNewBitmap = (HBITMAP)SelectObject(hMemDC, hOldBitmap);
// 清除DC
DeleteDC(hMemDC);
hMemDC = NULL;
DeleteDC(hWndDC);
hWndDC = NULL;
// 释放DC
ReleaseDC(hWnd, hWndDC);
return hNewBitmap;
}
//////////////////////////////////////////////////////////////////////////
// 函数说明:不失真模式获取HWND的HBITMAP
// 参 数:窗口句柄,指定坐标位置及大小
// 返 回 值:返回HBITMAP
// 编 写 者: ppshuai 20141126
//////////////////////////////////////////////////////////////////////////
__inline static HBITMAP HBITMAPFromHWND(HWND hWnd, int nX, int nY,
int nWidth, int nHeight)
{
INT nMode = 0;
HDC hWndDC = NULL;
HDC hMemDC = NULL;
HBITMAP hOldBitmap = NULL;
HBITMAP hNewBitmap = NULL;
hWndDC = GetDC(hWnd);
// 为屏幕设备描述表创建兼容的内存设备描述表
hMemDC = CreateCompatibleDC(hWndDC);
// 创建一个与屏幕设备描述表兼容的位图
hNewBitmap = CreateCompatibleBitmap(hWndDC, nWidth, nHeight);
// 把新位图选到内存设备描述表中
hOldBitmap = (HBITMAP)SelectObject(hMemDC, hNewBitmap);
// 设置不失真模式
nMode = SetStretchBltMode(hWndDC, COLORONCOLOR);
// 把屏幕设备描述表拷贝到内存设备描述表中
//BitBlt(hMemDC, 0, 0, nWidth, nHeight, hWndDC, nX, nY, SRCCOPY);
StretchBlt(hMemDC, 0, 0, nWidth, nHeight, hWndDC, nX, nY, nWidth, nHeight, SRCCOPY);
// 设置不失真模式
SetStretchBltMode(hMemDC, nMode);
// 得到屏幕位图的句柄
hNewBitmap = (HBITMAP)SelectObject(hMemDC, hOldBitmap);
// 清除DC
DeleteDC(hMemDC);
hMemDC = NULL;
DeleteDC(hWndDC);
hWndDC = NULL;
// 释放DC
ReleaseDC(hWnd, hWndDC);
return hNewBitmap;
}
//////////////////////////////////////////////////////////////////////////
// 函数说明:不失真模式获取HWND的HBITMAP
// 参 数:窗口句柄,指定坐标位置及大小
// 返 回 值:返回HBITMAP
// 编 写 者: ppshuai 20141126
//////////////////////////////////////////////////////////////////////////
__inline static HBITMAP HBITMAPFromHWND(HWND hWnd, int nX, int nY,
int nWidth, int nHeight,
HGDIOBJ * phGdiObj)
{
INT nMode = 0;
HDC hWndDC = NULL;
HDC hMemDC = NULL;
HBITMAP hOldBitmap = NULL;
HBITMAP hNewBitmap = NULL;
hWndDC = GetDC(hWnd);
// 为屏幕设备描述表创建兼容的内存设备描述表
hMemDC = CreateCompatibleDC(hWndDC);
// 创建一个与屏幕设备描述表兼容的位图
hNewBitmap = CreateCompatibleBitmap(hWndDC, nWidth, nHeight);
// 把新位图选到内存设备描述表中
hOldBitmap = (HBITMAP)SelectObject(hMemDC, hNewBitmap);
// 设置不失真模式
nMode = SetStretchBltMode(hWndDC, COLORONCOLOR);
// 把屏幕设备描述表拷贝到内存设备描述表中
//BitBlt(hMemDC, 0, 0, nWidth, nHeight, hWndDC, nX, nY, SRCCOPY);
StretchBlt(hMemDC, 0, 0, nWidth, nHeight, hWndDC, nX, nY, nWidth, nHeight, SRCCOPY);
// 设置不失真模式
SetStretchBltMode(hMemDC, nMode);
// 得到屏幕位图的句柄
hNewBitmap = (HBITMAP)SelectObject(hMemDC, hOldBitmap);
// 清除DC
DeleteDC(hMemDC);
hMemDC = NULL;
DeleteDC(hWndDC);
hWndDC = NULL;
// 释放DC
ReleaseDC(hWnd, hWndDC);
if (phGdiObj)
{
if ((*phGdiObj))
{
DeleteObject((*phGdiObj));
(*phGdiObj) = NULL;
}
(*phGdiObj) = hNewBitmap;
}
return hNewBitmap;
}
//////////////////////////////////////////////////////////////////////////
// 函数说明:不失真模式获取HDC的HBITMAP
// 参 数:设备DC,大小
// 返 回 值:返回HBITMAP
// 编 写 者: ppshuai 20141126
//////////////////////////////////////////////////////////////////////////
__inline static HBITMAP HBitmapFromHdc(HDC hDC, DWORD BitWidth, DWORD BitHeight)
{
HDC hMemDC;
INT nMode = 0;
HBITMAP hBitmap, hBitTemp;
//创建设备上下文(HDC)
hMemDC = CreateCompatibleDC(hDC);
//创建HBITMAP
hBitmap = CreateCompatibleBitmap(hDC, BitWidth, BitHeight);
hBitTemp = (HBITMAP)SelectObject(hMemDC, hBitmap);
nMode = SetStretchBltMode(hDC, COLORONCOLOR);//设置不失真模式
//得到位图缓冲区
StretchBlt(hMemDC, 0, 0, BitWidth, BitHeight, hDC, 0, 0, BitWidth, BitHeight, SRCCOPY);
SetStretchBltMode(hDC, nMode);
//得到最终的位图信息
hBitmap = (HBITMAP)SelectObject(hMemDC, hBitTemp);
//释放内存
DeleteObject(hBitTemp);
DeleteDC(hMemDC);
return hBitmap;
}
//////////////////////////////////////////////////////////////////////////
// 函数说明:获取HWND到IStream数据流,返回内存句柄(使用完毕需手动释放ReleaseGlobalHandle)
// 参 数:窗口句柄,输出IStream流
// 返 回 值:返回HANDLE.(使用完毕需手动释放ReleaseGlobalHandle)
// 编 写 者: ppshuai 20141126
//////////////////////////////////////////////////////////////////////////
__inline static HANDLE HWNDToIStream(HWND hWnd, IStream ** ppStream)
{
BITMAP bmp = { 0 };
HANDLE hFile = NULL;
DWORD dwDataSize = 0;
DWORD dwFileSize = 0;
BITMAPFILEHEADER bfh;
BITMAPINFOHEADER bih;
HANDLE hMemoryDIB = 0;
BYTE *lpBitmap = NULL;
DWORD dwBytesWritten = 0;
IStream * pStream = NULL;
HDC hWndDC = GetDC(hWnd);
HBITMAP hWndBitmap = HBITMAPFromHWND(hWnd);
// Get the BITMAP from the HBITMAP
GetObject(hWndBitmap, sizeof(BITMAP), &bmp);
bih.biSize = sizeof(BITMAPINFOHEADER);
bih.biWidth = bmp.bmWidth;
bih.biHeight = bmp.bmHeight;
bih.biPlanes = 1;
bih.biBitCount = 32;
bih.biCompression = BI_RGB;
bih.biSizeImage = 0;
bih.biXPelsPerMeter = 0;
bih.biYPelsPerMeter = 0;
bih.biClrUsed = 0;
bih.biClrImportant = 0;
dwDataSize = ((bmp.bmWidth * bih.biBitCount + 31) / 32) * 4 * bmp.bmHeight;
//Offset to where the actual bitmap bits start.
bfh.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + (DWORD)sizeof(BITMAPINFOHEADER);
//Size of the file
bfh.bfSize = dwDataSize;
//bfType must always be BM for Bitmaps
bfh.bfType = 0x4D42; //BM
// Add the size of the headers to the size of the bitmap to get the total file size
dwFileSize = bfh.bfOffBits + dwDataSize;
// Starting with 32-bit Windows, GlobalAlloc and LocalAlloc are implemented as wrapper functions that
// call HeapAlloc using a handle to the process's default heap. Therefore, GlobalAlloc and LocalAlloc
// have greater overhead than HeapAlloc.
hMemoryDIB = GlobalAlloc(GHND, dwFileSize);
if (hMemoryDIB)
{
lpBitmap = (BYTE *)GlobalLock(hMemoryDIB);
memcpy(lpBitmap, &bfh, sizeof(BITMAPFILEHEADER));
memcpy(lpBitmap + sizeof(BITMAPFILEHEADER), &bih, sizeof(BITMAPINFOHEADER));
// Gets the "bits" from the bitmap and copies them into a buffer
// which is pointed to by lpBitmap.
GetDIBits(hWndDC,
hWndBitmap,
0,
(UINT)bmp.bmHeight,
lpBitmap + bfh.bfOffBits,
(BITMAPINFO *)&bih, DIB_RGB_COLORS);
CreateStreamOnHGlobal(lpBitmap, FALSE, ppStream);
}
return hMemoryDIB;
}
//////////////////////////////////////////////////////////////////////////
// 函数说明:获取HWND到IStream数据流,返回内存句柄(使用完毕需手动释放ReleaseGlobalHandle)
// 参 数:窗口句柄,指定坐标及大小,输出IStream流
// 返 回 值:返回HANDLE.(使用完毕需手动释放ReleaseGlobalHandle)
// 编 写 者: ppshuai 20141126
//////////////////////////////////////////////////////////////////////////
__inline static HANDLE HWNDToIStream(HWND hWnd, int nX, int nY,
int nWidth, int nHeight, IStream ** ppStream)
{
BITMAP bmp = { 0 };
HANDLE hFile = NULL;
DWORD dwDataSize = 0;
DWORD dwFileSize = 0;
BITMAPFILEHEADER bfh;
BITMAPINFOHEADER bih;
HANDLE hMemoryDIB = 0;
BYTE *lpBitmap = NULL;
DWORD dwBytesWritten = 0;
IStream * pStream = NULL;
HDC hWndDC = GetDC(hWnd);
HBITMAP hWndBitmap = HBITMAPFromHWND(hWnd, nX, nY, nWidth, nHeight);
// Get the BITMAP from the HBITMAP
GetObject(hWndBitmap, sizeof(BITMAP), &bmp);
bih.biSize = sizeof(BITMAPINFOHEADER);
bih.biWidth = bmp.bmWidth;
bih.biHeight = bmp.bmHeight;
bih.biPlanes = 1;
bih.biBitCount = 32;
bih.biCompression = BI_RGB;
bih.biSizeImage = 0;
bih.biXPelsPerMeter = 0;
bih.biYPelsPerMeter = 0;
bih.biClrUsed = 0;
bih.biClrImportant = 0;
dwDataSize = ((bmp.bmWidth * bih.biBitCount + 31) / 32) * 4 * bmp.bmHeight;
//Offset to where the actual bitmap bits start.
bfh.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + (DWORD)sizeof(BITMAPINFOHEADER);
//Size of the file
bfh.bfSize = dwDataSize;
//bfType must always be BM for Bitmaps
bfh.bfType = 0x4D42; //BM
// Add the size of the headers to the size of the bitmap to get the total file size
dwFileSize = bfh.bfOffBits + dwDataSize;
// Starting with 32-bit Windows, GlobalAlloc and LocalAlloc are implemented as wrapper functions that
// call HeapAlloc using a handle to the process's default heap. Therefore, GlobalAlloc and LocalAlloc
// have greater overhead than HeapAlloc.
hMemoryDIB = GlobalAlloc(GHND, dwFileSize);
if (hMemoryDIB)
{
lpBitmap = (BYTE *)GlobalLock(hMemoryDIB);
memcpy(lpBitmap, &bfh, sizeof(BITMAPFILEHEADER));
memcpy(lpBitmap + sizeof(BITMAPFILEHEADER), &bih, sizeof(BITMAPINFOHEADER));
// Gets the "bits" from the bitmap and copies them into a buffer
// which is pointed to by lpBitmap.
GetDIBits(hWndDC,
hWndBitmap,
0,
(UINT)bmp.bmHeight,
lpBitmap + bfh.bfOffBits,
(BITMAPINFO *)&bih, DIB_RGB_COLORS);
CreateStreamOnHGlobal(lpBitmap, FALSE, ppStream);
}
return hMemoryDIB;
}
//////////////////////////////////////////////////////////////////////////
// 函数说明:释放内存句柄
// 参 数:窗口句柄,输出IStream流
// 返 回 值:无返回值
// 编 写 者: ppshuai 20141126
//////////////////////////////////////////////////////////////////////////
__inline static void ReleaseGlobalHandle(HANDLE * hMemoryHandle)
{
if (hMemoryHandle && (*hMemoryHandle))
{
GlobalUnlock((*hMemoryHandle));
(*hMemoryHandle) = NULL;
}
}
//////////////////////////////////////////////////////////////////////////
// 函数说明:保存HBITMAP到BMP图片文件
// 参 数:窗口句柄,要保存文件名称
// 返 回 值:bool类型。成功返回true;失败返回false;
// 编 写 者: ppshuai 20141126
//////////////////////////////////////////////////////////////////////////
__inline static bool HBitmapToFile(HBITMAP hBitmap, const TCHAR *pFileName)
{
BITMAP bmp = { 0 };
WORD wBitCount = 0;
HANDLE hFile = NULL;
DWORD dwDataSize = 0;
DWORD dwFileSize = 0;
BYTE *lpBitmap = NULL;
HANDLE hDIBData = NULL;
DWORD dwBytesWritten = 0;
BITMAPFILEHEADER bfh = { 0 };
BITMAPINFOHEADER bih = { 0 };
HDC hDC = GetWindowDC(NULL);
//计算位图文件每个像素所占字节数
wBitCount = GetDeviceCaps(hDC, BITSPIXEL) * GetDeviceCaps(hDC, PLANES);
if (wBitCount <= 1)
{
wBitCount = 1;
}
else if (wBitCount <= 4)
{
wBitCount = 4;
}
else if (wBitCount <= 8)
{
wBitCount = 8;
}
else
{
wBitCount = 24;
}
// Get the BITMAP from the HBITMAP
GetObject(hBitmap, sizeof(BITMAP), &bmp);
bih.biSize = sizeof(BITMAPINFOHEADER);
bih.biWidth = bmp.bmWidth;
bih.biHeight = bmp.bmHeight;
bih.biPlanes = 1;
bih.biBitCount = wBitCount;
bih.biCompression = BI_RGB;
bih.biSizeImage = 0;
bih.biXPelsPerMeter = 0;
bih.biYPelsPerMeter = 0;
bih.biClrUsed = 0;
bih.biClrImportant = 0;
dwDataSize = ((bmp.bmWidth * bih.biBitCount + 31) / 32) * 4 * bmp.bmHeight;
//Offset to where the actual bitmap bits start.
bfh.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + (DWORD)sizeof(BITMAPINFOHEADER);
//Size of the file
bfh.bfSize = dwDataSize;
//bfType must always be BM for Bitmaps
bfh.bfType = 0x4D42; //BM
// Add the size of the headers to the size of the bitmap to get the total file size
dwFileSize = bfh.bfOffBits + dwDataSize;
// Starting with 32-bit Windows, GlobalAlloc and LocalAlloc are implemented as wrapper functions that
// call HeapAlloc using a handle to the process's default heap. Therefore, GlobalAlloc and LocalAlloc
// have greater overhead than HeapAlloc.
hDIBData = GlobalAlloc(GHND, dwFileSize);
if (!hDIBData)
{
return false;
}
lpBitmap = (BYTE *)GlobalLock(hDIBData);
memcpy(lpBitmap, &bfh, sizeof(BITMAPFILEHEADER));
memcpy(lpBitmap + sizeof(BITMAPFILEHEADER), &bih, sizeof(BITMAPINFOHEADER));
// Gets the "bits" from the bitmap and copies them into a buffer
// which is pointed to by lpBitmap.
GetDIBits(hDC,
hBitmap,
0,
(UINT)bmp.bmHeight,
lpBitmap + bfh.bfOffBits,
(BITMAPINFO *)&bih, DIB_RGB_COLORS);
// A file is created, this is where we will save the screen capture.
hFile = CreateFile(pFileName,
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
return false;
}
WriteFile(hFile, (LPSTR)lpBitmap, dwFileSize, &dwBytesWritten, NULL);
//Unlock and Free the DIB from the heap
GlobalUnlock(hDIBData);
GlobalFree(hDIBData);
hDIBData = NULL;
//Close the handle for the file that was created
CloseHandle(hFile);
hFile = NULL;
return true;
}
//////////////////////////////////////////////////////////////////////////
// 函数说明:保存HBITMAP到BMP图片文件
// 参 数:位图句柄,要保存文件名称
// 返 回 值:bool类型。成功返回true;失败返回false;
// 编 写 者: ppshuai 20141126
//////////////////////////////////////////////////////////////////////////
__inline static bool HBitmapToFileEx(HBITMAP hBitmap, const TCHAR * ptFileName)
{
HDC hDC = NULL;
BITMAP bmp = { 0 };
WORD wBitsCount = 0;
bool result = false;
HANDLE hFile = NULL;
HANDLE hDIBData = 0;
DWORD dwDataSize = 0;
DWORD dwFileSize = 0;
BITMAPFILEHEADER bfh;
BITMAPINFOHEADER bih;
BYTE *lpByteData = NULL;
DWORD dwBytesWritten = 0;
HPALETTE hPalette = NULL;
HPALETTE hPaletteBackup = NULL;
//计算位图文件每个像素所占字节数
hDC = CreateDC(TEXT("DISPLAY"), NULL, NULL, NULL);
wBitsCount = GetDeviceCaps(hDC, BITSPIXEL) * GetDeviceCaps(hDC, PLANES);
if (wBitsCount <= 1)
{
wBitsCount = 1;
}
else if (wBitsCount <= 4)
{
wBitsCount = 4;
}
else if (wBitsCount <= 8)
{
wBitsCount = 8;
}
else
{
wBitsCount = 24;
}
// Get the BITMAP from the HBITMAP
GetObject(hBitmap, sizeof(BITMAP), &bmp);
bih.biSize = sizeof(BITMAPINFOHEADER);
bih.biWidth = bmp.bmWidth;
bih.biHeight = bmp.bmHeight;
bih.biPlanes = 1;
bih.biBitCount = wBitsCount;
bih.biCompression = BI_RGB;
bih.biSizeImage = 0;
bih.biXPelsPerMeter = 0;
bih.biYPelsPerMeter = 0;
bih.biClrUsed = 0;
bih.biClrImportant = 0;
dwDataSize = ((bmp.bmWidth * bih.biBitCount + 31) / 32) * 4 * bmp.bmHeight;
//Offset to where the actual bitmap bits start.
bfh.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + (DWORD)sizeof(BITMAPINFOHEADER);
//Size of the file
bfh.bfSize = dwDataSize;
//bfType must always be BM for Bitmaps
bfh.bfType = 0x4D42; //BM
// Add the size of the headers to the size of the bitmap to get the total file size
dwFileSize = bfh.bfOffBits + dwDataSize;
// Starting with 32-bit Windows, GlobalAlloc and LocalAlloc are implemented as wrapper functions that
// call HeapAlloc using a handle to the process's default heap. Therefore, GlobalAlloc and LocalAlloc
// have greater overhead than HeapAlloc.
hDIBData = GlobalAlloc(GHND, dwFileSize);
if (hDIBData)
{
lpByteData = (BYTE *)GlobalLock(hDIBData);
memcpy(lpByteData, &bfh, sizeof(BITMAPFILEHEADER));
memcpy(lpByteData + sizeof(BITMAPFILEHEADER), &bih, sizeof(BITMAPINFOHEADER));
// Gets default palette
hPalette = (HPALETTE)GetStockObject(DEFAULT_PALETTE);
if (hPalette)
{
hDC = ::GetDC(NULL);
hPaletteBackup = ::SelectPalette(hDC, (HPALETTE)hPalette, FALSE);
::RealizePalette(hDC);
}
// Gets the "bits" from the bitmap and copies them into a buffer
// which is pointed to by lpByteData.
GetDIBits(hDC,
hBitmap,
0,
(UINT)bmp.bmHeight,
lpByteData + bfh.bfOffBits,
(BITMAPINFO *)&bih, DIB_RGB_COLORS);
// Recover original palette
if (hPaletteBackup)
{
::SelectPalette(hDC, (HPALETTE)hPaletteBackup, TRUE);
::RealizePalette(hDC);
::ReleaseDC(NULL, hDC);
}
// A file is created, this is where we will save the screen capture.
hFile = CreateFile(ptFileName,
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
WriteFile(hFile, (void *)lpByteData, dwFileSize, &dwBytesWritten, NULL);
//Close the handle for the file that was created
CloseHandle(hFile);
hFile = NULL;
result = true;
}
//Unlock and Free the DIB from the heap
GlobalUnlock(hDIBData);
GlobalFree(hDIBData);
hDIBData = NULL;
}
return result;
}
//////////////////////////////////////////////////////////////////////////
// 函数说明:保存HWND到BMP图片文件
// 参 数:窗口句柄,要保存文件名称
// 返 回 值:bool类型。成功返回true;失败返回false;
// 编 写 者: ppshuai 20141126
//////////////////////////////////////////////////////////////////////////
__inline static bool HWNDToFile(HWND hWnd, TCHAR * ptFileName)
{
BITMAP bmp = { 0 };
bool result = false;
HANDLE hFile = NULL;
HANDLE hDIBData = 0;
DWORD dwDataSize = 0;
DWORD dwFileSize = 0;
BITMAPFILEHEADER bfh;
BITMAPINFOHEADER bih;
BYTE *lpByteData = NULL;
DWORD dwBytesWritten = 0;
HDC hWndDC = GetDC(hWnd);
HBITMAP hBitmap = HBITMAPFromHWND(hWnd);
// Get the BITMAP from the HBITMAP
GetObject(hBitmap, sizeof(BITMAP), &bmp);
bih.biSize = sizeof(BITMAPINFOHEADER);
bih.biWidth = bmp.bmWidth;
bih.biHeight = bmp.bmHeight;
bih.biPlanes = 1;
bih.biBitCount = 32;
bih.biCompression = BI_RGB;
bih.biSizeImage = 0;
bih.biXPelsPerMeter = 0;
bih.biYPelsPerMeter = 0;
bih.biClrUsed = 0;
bih.biClrImportant = 0;
dwDataSize = ((bmp.bmWidth * bih.biBitCount + 31) / 32) * 4 * bmp.bmHeight;
//Offset to where the actual bitmap bits start.
bfh.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + (DWORD)sizeof(BITMAPINFOHEADER);
//Size of the file
bfh.bfSize = dwDataSize;
//bfType must always be BM for Bitmaps
bfh.bfType = 0x4D42; //BM
// Add the size of the headers to the size of the bitmap to get the total file size
dwFileSize = bfh.bfOffBits + dwDataSize;
// Starting with 32-bit Windows, GlobalAlloc and LocalAlloc are implemented as wrapper functions that
// call HeapAlloc using a handle to the process's default heap. Therefore, GlobalAlloc and LocalAlloc
// have greater overhead than HeapAlloc.
hDIBData = GlobalAlloc(GHND, dwFileSize);
if (hDIBData)
{
lpByteData = (BYTE *)GlobalLock(hDIBData);
memcpy(lpByteData, &bfh, sizeof(BITMAPFILEHEADER));
memcpy(lpByteData + sizeof(BITMAPFILEHEADER), &bih, sizeof(BITMAPINFOHEADER));
// Gets the "bits" from the bitmap and copies them into a buffer
// which is pointed to by lpByteData.
GetDIBits(hWndDC,
hBitmap,
0,
(UINT)bmp.bmHeight,
lpByteData + bfh.bfOffBits,
(BITMAPINFO *)&bih, DIB_RGB_COLORS);
// A file is created, this is where we will save the screen capture.
hFile = CreateFile(ptFileName,
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
WriteFile(hFile, (void *)lpByteData, dwFileSize, &dwBytesWritten, NULL);
//Close the handle for the file that was created
CloseHandle(hFile);
hFile = NULL;
result = true;
}
//Unlock and Free the DIB from the heap
GlobalUnlock(hDIBData);
GlobalFree(hDIBData);
hDIBData = NULL;
}
return result;
}
//////////////////////////////////////////////////////////////////////////
// 函数说明:显示HBITMAP到HWND上
// 参 数:窗口句柄,HBITMAP位图句柄
// 返 回 值:bool类型。成功返回true;失败返回false;
// 编 写 者: ppshuai 20141126
//////////////////////////////////////////////////////////////////////////
__inline static HBITMAP showBitmap(HWND hStaticWnd, HBITMAP hStaticBitmap)
{
INT nMode = 0;
RECT rect = { 0 };
BITMAP bmp = { 0 };
HDC hParentDC = NULL;
HDC hStaticDC = NULL;
HDC hMemoryDC = NULL;
HWND hParentWnd = NULL;
HBITMAP hOldBitmap = NULL;
HBITMAP hNewBitmap = NULL;
hParentWnd = GetParent(hStaticWnd);
//获取图片显示框的大小
GetClientRect(hStaticWnd, &rect);
//获取位图的大小信息
GetObject(hStaticBitmap, sizeof(bmp), &bmp);
if ((rect.right - rect.left) >= bmp.bmWidth &&
(rect.bottom - rect.top) >= bmp.bmHeight)
{
return hNewBitmap;
}
hParentDC = GetDC(hParentWnd);
hStaticDC = GetDC(hStaticWnd);
hMemoryDC = CreateCompatibleDC(hParentDC);
hOldBitmap = (HBITMAP)SelectObject(hMemoryDC, hStaticBitmap);
//设置不失真模式
nMode = SetStretchBltMode(hStaticDC, COLORONCOLOR);
StretchBlt(hStaticDC, rect.left, rect.top, rect.right - rect.left,
rect.bottom - rect.top, hMemoryDC, 0, 0, bmp.bmWidth, bmp.bmHeight, SRCCOPY);
SetStretchBltMode(hStaticDC, nMode);
DeleteDC(hMemoryDC);
ReleaseDC(hStaticWnd, hStaticDC);
ReleaseDC(hParentWnd, hParentDC);
return hNewBitmap;
}
//////////////////////////////////////////////////////////////////////////
// 函数说明:显示HBITMAP到HWND上
// 参 数:主窗口句柄,源子控件ID,目标子控件ID
// 返 回 值:无返回值;
// 编 写 者: ppshuai 20141126
//////////////////////////////////////////////////////////////////////////
__inline static void showPicture(HWND hWnd, INT nSrcID, INT nDstID)
{
RECT rect = { 0 };
HGDIOBJ hOldBitmap = NULL;
HGDIOBJ hNewBitmap = NULL;
hNewBitmap = HBITMAPFromHWND(GetDlgItem(hWnd, nSrcID));
if (hNewBitmap)
{
hOldBitmap = (HGDIOBJ)SendDlgItemMessage(hWnd, nDstID, STM_SETIMAGE,
(WPARAM)IMAGE_BITMAP, (LPARAM)hNewBitmap);
if (hOldBitmap)
{
DeleteObject(hOldBitmap);
hOldBitmap = NULL;
}
}
}
//////////////////////////////////////////////////////////////////////////
// 函数说明:显示HBITMAP到HWND上
// 参 数:主窗口句柄,HBITMAP句柄,目标子控件ID
// 返 回 值:无返回值;
// 编 写 者: ppshuai 20141126
//////////////////////////////////////////////////////////////////////////
__inline static void showPicture(HWND hWnd, HGDIOBJ hBitmap, INT nDstID)
{
RECT rect = { 0 };
HGDIOBJ hOldBitmap = NULL;
if (hBitmap)
{
hOldBitmap = (HGDIOBJ)SendDlgItemMessage(hWnd, nDstID, STM_SETIMAGE,
(WPARAM)IMAGE_BITMAP, (LPARAM)hBitmap);
if (hOldBitmap)
{
DeleteObject(hOldBitmap);
hOldBitmap = NULL;
}
}
}
// Helper to calculate the alpha-premultiled value for a pixel
__inline static DWORD PreMultiply(COLORREF cl, unsigned char nAlpha)
{
// It's strange that the byte order of RGB in 32b BMP is reverse to in COLORREF
return (GetRValue(cl) * (DWORD)nAlpha / 255) << 16 |
(GetGValue(cl) * (DWORD)nAlpha / 255) << 8 |
(GetBValue(cl) * (DWORD)nAlpha / 255);
}
__inline static void MakeShadow(UINT32 *pShadBits, HWND hParent, RECT *rcParent,
INT nDarkness = 150,
INT nSharpness = 5,
INT nSize = 12,
INT nxOffset = 5,
INT nyOffset = 5,
COLORREF Color = RGB(255, 0, 0))
{
// The shadow algorithm:
// Get the region of parent window,
// Apply morphologic erosion to shrink it into the size (ShadowWndSize - Sharpness)
// Apply modified (with blur effect) morphologic dilation to make the blurred border
// The algorithm is optimized by assuming parent window is just "one piece" and without "wholes" on it
RECT rcRegion = { 0, 0, rcParent->right - rcParent->left, rcParent->bottom - rcParent->top };
// Get the region of parent window,
HRGN hParentRgn = CreateRectRgn(rcRegion.left, rcRegion.top, rcRegion.right, rcRegion.bottom);
GetWindowRgn(hParent, hParentRgn);
// Determine the Start and end point of each horizontal scan line
SIZE szParent = { rcParent->right - rcParent->left, rcParent->bottom - rcParent->top };
SIZE szShadow = { szParent.cx + 2 * nSize, szParent.cy + 2 * nSize };
// Extra 2 lines (set to be empty) in ptAnchors are used in dilation
int nAnchors = max(szParent.cy, szShadow.cy); // # of anchor points pares
int(*ptAnchors)[2] = new int[nAnchors + 2][2];
int(*ptAnchorsOri)[2] = new int[szParent.cy][2]; // anchor points, will not modify during erosion
ptAnchors[0][0] = szParent.cx;
ptAnchors[0][1] = 0;
ptAnchors[nAnchors + 1][0] = szParent.cx;
ptAnchors[nAnchors + 1][1] = 0;
if (nSize > 0)
{
// Put the parent window anchors at the center
for (int i = 0; i < nSize; i++)
{
ptAnchors[i + 1][0] = szParent.cx;
ptAnchors[i + 1][1] = 0;
ptAnchors[szShadow.cy - i][0] = szParent.cx;
ptAnchors[szShadow.cy - i][1] = 0;
}
ptAnchors += nSize;
}
for (int i = 0; i < szParent.cy; i++)
{
// find start point
int j;
for (j = 0; j < szParent.cx; j++)
{
if (PtInRegion(hParentRgn, j, i))
{
ptAnchors[i + 1][0] = j + nSize;
ptAnchorsOri[i][0] = j;
break;
}
}
if (j >= szParent.cx) // Start point not found
{
ptAnchors[i + 1][0] = szParent.cx;
ptAnchorsOri[i][1] = 0;
ptAnchors[i + 1][0] = szParent.cx;
ptAnchorsOri[i][1] = 0;
}
else
{
// find end point
for (j = szParent.cx - 1; j >= ptAnchors[i + 1][0]; j--)
{
if (PtInRegion(hParentRgn, j, i))
{
ptAnchors[i + 1][1] = j + nSize;
ptAnchorsOri[i][1] = j + 1;
break;
}
}
}
}
if (nSize > 0)
{
ptAnchors -= nSize; // Restore pos of ptAnchors for erosion
}
int(*ptAnchorsTmp)[2] = new int[nAnchors + 2][2]; // Store the result of erosion
// First and last line should be empty
ptAnchorsTmp[0][0] = szParent.cx;
ptAnchorsTmp[0][1] = 0;
ptAnchorsTmp[nAnchors + 1][0] = szParent.cx;
ptAnchorsTmp[nAnchors + 1][1] = 0;
int nEroTimes = 0;
// morphologic erosion
for (int i = 0; i < nSharpness - nSize; i++)
{
nEroTimes++;
//ptAnchorsTmp[1][0] = szParent.cx;
//ptAnchorsTmp[1][1] = 0;
//ptAnchorsTmp[szParent.cy + 1][0] = szParent.cx;
//ptAnchorsTmp[szParent.cy + 1][1] = 0;
for (int j = 1; j < nAnchors + 1; j++)
{
ptAnchorsTmp[j][0] = max(ptAnchors[j - 1][0], max(ptAnchors[j][0], ptAnchors[j + 1][0])) + 1;
ptAnchorsTmp[j][1] = min(ptAnchors[j - 1][1], min(ptAnchors[j][1], ptAnchors[j + 1][1])) - 1;
}
// Exchange ptAnchors and ptAnchorsTmp;
int(*ptAnchorsXange)[2] = ptAnchorsTmp;
ptAnchorsTmp = ptAnchors;
ptAnchors = ptAnchorsXange;
}
// morphologic dilation
ptAnchors += (nSize < 0 ? -nSize : 0) + 1; // now coordinates in ptAnchors are same as in shadow window
// Generate the kernel
int nKernelSize = nSize > nSharpness ? nSize : nSharpness;
int nCenterSize = nSize > nSharpness ? (nSize - nSharpness) : 0;
UINT32 *pKernel = new UINT32[(2 * nKernelSize + 1) * (2 * nKernelSize + 1)];
UINT32 *pKernelIter = pKernel;
for (int i = 0; i <= 2 * nKernelSize; i++)
{
for (int j = 0; j <= 2 * nKernelSize; j++)
{
double dLength = sqrt((i - nKernelSize) * (i - nKernelSize) + (j - nKernelSize) * (double)(j - nKernelSize));
if (dLength < nCenterSize)
{
*pKernelIter = nDarkness << 24 | PreMultiply(Color, nDarkness);
}
else if (dLength <= nKernelSize)
{
UINT32 nFactor = ((UINT32)((1 - (dLength - nCenterSize) / (nSharpness + 1)) * nDarkness));
*pKernelIter = nFactor << 24 | PreMultiply(Color, nFactor);
}
else
{
*pKernelIter = 0;
}
pKernelIter++;
}
}
// Generate blurred border
for (int i = nKernelSize; i < szShadow.cy - nKernelSize; i++)
{
int j = 0;
if (ptAnchors[i][0] < ptAnchors[i][1])
{
// Start of line
for (j = ptAnchors[i][0];
j < min(max(ptAnchors[i - 1][0], ptAnchors[i + 1][0]) + 1, ptAnchors[i][1]);
j++)
{
for (int k = 0; k <= 2 * nKernelSize; k++)
{
UINT32 *pPixel = pShadBits +
(szShadow.cy - i - 1 + nKernelSize - k) * szShadow.cx + j - nKernelSize;
UINT32 *pKernelPixel = pKernel + k * (2 * nKernelSize + 1);
for (int l = 0; l <= 2 * nKernelSize; l++)
{
if (*pPixel < *pKernelPixel)
{
*pPixel = *pKernelPixel;
}
pPixel++;
pKernelPixel++;
}
}
} // for() start of line
// End of line
for (j = max(j, min(ptAnchors[i - 1][1], ptAnchors[i + 1][1]) - 1);
j < ptAnchors[i][1];
j++)
{
for (int k = 0; k <= 2 * nKernelSize; k++)
{
UINT32 *pPixel = pShadBits +
(szShadow.cy - i - 1 + nKernelSize - k) * szShadow.cx + j - nKernelSize;
UINT32 *pKernelPixel = pKernel + k * (2 * nKernelSize + 1);
for (int l = 0; l <= 2 * nKernelSize; l++)
{
if (*pPixel < *pKernelPixel)
{
*pPixel = *pKernelPixel;
}
pPixel++;
pKernelPixel++;
}
}
} // for() end of line
}
} // for() Generate blurred border
// Erase unwanted parts and complement missing
UINT32 clCenter = nDarkness << 24 | PreMultiply(Color, nDarkness);
for (int i = min(nKernelSize, max(nSize - nyOffset, 0));
i < max(szShadow.cy - nKernelSize, min(szParent.cy + nSize - nyOffset, szParent.cy + 2 * nSize));
i++)
{
UINT32 *pLine = pShadBits + (szShadow.cy - i - 1) * szShadow.cx;
if (i - nSize + nyOffset < 0 || i - nSize + nyOffset >= szParent.cy) // Line is not covered by parent window
{
for (int j = ptAnchors[i][0]; j < ptAnchors[i][1]; j++)
{
*(pLine + j) = clCenter;
}
}
else
{
for (int j = ptAnchors[i][0];
j < min(ptAnchorsOri[i - nSize + nyOffset][0] + nSize - nxOffset, ptAnchors[i][1]);
j++)
*(pLine + j) = clCenter;
for (int j = max(ptAnchorsOri[i - nSize + nyOffset][0] + nSize - nxOffset, 0);
j < min((long)ptAnchorsOri[i - nSize + nyOffset][1] + nSize - nxOffset, szShadow.cx);
j++)
*(pLine + j) = 0;
for (int j = max(ptAnchorsOri[i - nSize + nyOffset][1] + nSize - nxOffset, ptAnchors[i][0]);
j < ptAnchors[i][1];
j++)
*(pLine + j) = clCenter;
}
}
// Delete used resources
delete[](ptAnchors - (nSize < 0 ? -nSize : 0) - 1);
delete[] ptAnchorsTmp;
delete[] ptAnchorsOri;
delete[] pKernel;
DeleteObject(hParentRgn);
}
__inline static HBITMAP CreateShadowBitmap(HWND hParent,
INT nDarkness = 150,
INT nSharpness = 5,
INT nSize = 12,
INT nxOffset = 5,
INT nyOffset = 5,
COLORREF Color = RGB(255, 0, 0))
{
RECT rc = { 0 };
BYTE *pvBits = NULL; // pointer to DIB section
HBITMAP hBitmap = NULL;
int nShadowWindowWidth = 0;
int nShadowWindowHeight = 0;
// Create the alpha blending bitmap
BITMAPINFO bmi = { 0 }; // bitmap header
HDC hDC = GetDC(hParent);
WORD wBitsCount = GetDeviceCaps(hDC, BITSPIXEL) * GetDeviceCaps(hDC, PLANES);
if (wBitsCount <= 1)
{
wBitsCount = 1;
}
else if (wBitsCount <= 4)
{
wBitsCount = 4;
}
else if (wBitsCount <= 8)
{
wBitsCount = 8;
}
else if (wBitsCount <= 24)
{
wBitsCount = 24;
}
else
{
wBitsCount = 32;
}
GetWindowRect(hParent, &rc);
nShadowWindowWidth = rc.right - rc.left + nSize * 2;
nShadowWindowHeight = rc.bottom - rc.top + nSize * 2;
ZeroMemory(&bmi, sizeof(BITMAPINFO));
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = nShadowWindowWidth;
bmi.bmiHeader.biHeight = nShadowWindowHeight;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = wBitsCount; // four 8-bit components
bmi.bmiHeader.biCompression = BI_RGB;
bmi.bmiHeader.biSizeImage = nShadowWindowWidth * nShadowWindowHeight * 4;
hBitmap = CreateDIBSection(NULL, &bmi, DIB_RGB_COLORS, (void **)&pvBits, NULL, 0);
ZeroMemory(pvBits, bmi.bmiHeader.biSizeImage);
MakeShadow((UINT32 *)pvBits, hParent, &rc,
nDarkness, nSharpness, nSize, nxOffset,
nyOffset, Color);
return hBitmap;
}
__inline static BOOL SaveHBitmapToFile(HBITMAP hBitmap, const TCHAR *pFileName)
{
HDC hDC = NULL;
//当前分辨率下每象素所占字节数
WORD wDPIBits = 0;
//位图中每象素所占字节数
WORD wBitCount = 0;
//定义调色板大小
DWORD dwPaletteSize = 0;
//位图中像素字节大小
DWORD dwBmBitsSize = 0;
//位图文件大小
DWORD dwDibBitSize = 0;
//写入文件字节数
DWORD dwWritten = 0;
//位图属性结构
BITMAP bmp = { 0 };
//位图文件头结构
BITMAPFILEHEADER bmpfh = { 0 };
//位图信息头结构
BITMAPINFOHEADER bmpih = { 0 };
//指向位图信息头结构
BITMAPINFOHEADER * pbmpih = NULL;
//定义文件
HANDLE hFile = NULL;
//分配内存句柄
HGLOBAL hDibBit = NULL;
//当前调色板句柄
HPALETTE hPaltte = NULL;
//备份调色板句柄
HPALETTE hPaltteBackup = NULL;
//计算位图文件每个像素所占字节数
hDC = CreateDC(_T("DISPLAY"), NULL, NULL, NULL);
wDPIBits = GetDeviceCaps(hDC, BITSPIXEL) * GetDeviceCaps(hDC, PLANES);
if (wDPIBits <= 1)
{
wBitCount = 1;
}
else if (wDPIBits <= 4)
{
wBitCount = 4;
}
else if (wDPIBits <= 8)
{
wBitCount = 8;
}
else if (wDPIBits <= 24)
{
wBitCount = 24;
}
else
{
wBitCount = 32;
}
GetObject(hBitmap, sizeof(bmp), (LPSTR)&bmp);
bmpih.biSize = sizeof(BITMAPINFOHEADER);
bmpih.biWidth = bmp.bmWidth;
bmpih.biHeight = bmp.bmHeight;
bmpih.biPlanes = 1;
bmpih.biBitCount = wBitCount;
bmpih.biCompression = BI_RGB;
bmpih.biSizeImage = 0;
bmpih.biXPelsPerMeter = 0;
bmpih.biYPelsPerMeter = 0;
bmpih.biClrImportant = 0;
bmpih.biClrUsed = 0;
dwBmBitsSize = ((bmp.bmWidth * bmpih.biBitCount + 31) / 32) * 4 * bmp.bmHeight;
//为位图内容分配内存
hDibBit = GlobalAlloc(GHND, dwBmBitsSize + dwPaletteSize + sizeof(BITMAPINFOHEADER));
pbmpih = (LPBITMAPINFOHEADER)GlobalLock(hDibBit);
*pbmpih = bmpih;
//处理调色板
hPaltte = (HPALETTE)GetStockObject(DEFAULT_PALETTE);
if (hPaltte)
{
hDC = ::GetDC(NULL);
hPaltteBackup = ::SelectPalette(hDC, (HPALETTE)hPaltte, FALSE);
::RealizePalette(hDC);
}
//获取该调色板下新的像素值
GetDIBits(hDC,
hBitmap,
0,
(UINT)bmp.bmHeight,
((BYTE *)pbmpih + sizeof(BITMAPINFOHEADER) + dwPaletteSize),
(BITMAPINFO *)pbmpih,
DIB_RGB_COLORS);
//恢复调色板
if (hPaltteBackup)
{
::SelectPalette(hDC, (HPALETTE)hPaltteBackup, TRUE);
::RealizePalette(hDC);
::ReleaseDC(NULL, hDC);
}
//创建位图文件
hFile = CreateFile((LPCTSTR)pFileName,
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
//设置位图文件头
bmpfh.bfType = 0x4D42; //"BM"
bmpfh.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + dwPaletteSize + dwBmBitsSize;
bmpfh.bfReserved1 = 0;
bmpfh.bfReserved2 = 0;
bmpfh.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + (DWORD)sizeof(BITMAPINFOHEADER) + dwPaletteSize;
dwDibBitSize = bmpfh.bfSize;
//写入位图文件头
WriteFile(hFile, (void *)&bmpfh, sizeof(BITMAPFILEHEADER), &dwWritten, NULL);
//写入位图文件其余内容
WriteFile(hFile, (void *)pbmpih, dwDibBitSize, &dwWritten, NULL);
//清除
GlobalUnlock(hDibBit);
GlobalFree(hDibBit);
hDibBit = NULL;
//关闭文件
CloseHandle(hFile);
hFile = NULL;
}
DeleteDC(hDC);
hDC = NULL;
return TRUE;
}
///////////////////////////////////////////////////////////////////////////////
__inline static std::wstring GetName(__in CComPtr<IAccessible> pAcc, __in CComVariant varChild)
{
if (!pAcc)
return L"";
CComBSTR bstrName;
HRESULT hr = pAcc->get_accName(varChild, &bstrName);
if (FAILED(hr))
return L"";
if (!bstrName.m_str)
return L"<NULL>";
return bstrName.m_str;
}
__inline static std::wstring GetRole(__in CComPtr<IAccessible> pAcc, __in CComVariant varChild)
{
if (!pAcc)
return L"";
CComVariant varRoleID;
HRESULT hr = pAcc->get_accRole(varChild, &varRoleID);
if (FAILED(hr))
return L"";
WCHAR sRoleBuff[1024] = { 0 };
hr = ::GetRoleTextW(varRoleID.lVal, sRoleBuff, 1024);
if (FAILED(hr))
return L"";
return sRoleBuff;
}
__inline static std::wstring GetValue(__in CComPtr<IAccessible> pAcc, __in CComVariant varChild)
{
if (!pAcc)
return L"";
CComBSTR bstrName;
HRESULT hr = pAcc->get_accValue(varChild, &bstrName);
if (FAILED(hr))
return L"";
if (!bstrName.m_str)
return L"<NULL>";
return bstrName.m_str;
}
__inline static std::wstring GetDescription(__in CComPtr<IAccessible> pAcc, __in CComVariant varChild)
{
if (!pAcc)
return L"";
CComBSTR bstrName;
HRESULT hr = pAcc->get_accDescription(varChild, &bstrName);
if (FAILED(hr))
return L"";
if (!bstrName.m_str)
return L"<NULL>";
return bstrName.m_str;
}
__inline static HRESULT WalkTreeWithAccessibleChildren(__in CComPtr<IAccessible> pAcc, __in int depth)
{
long childCount = 0;
long returnCount = 0;
HRESULT hr = pAcc->get_accChildCount(&childCount);
if (childCount == 0)
return S_FALSE;
CComVariant* pArray = new CComVariant[childCount];
hr = ::AccessibleChildren(pAcc, 0L, childCount, pArray, &returnCount);
if (FAILED(hr))
return hr;
// Iterate through children.
for (int x = 0; x < returnCount; x++)
{
CComVariant vtChild = pArray[x];
// If it's an accessible object, get the IAccessible, and recurse.
if (vtChild.vt == VT_DISPATCH)
{
CComPtr<IDispatch> pDisp = vtChild.pdispVal;
CComQIPtr<IAccessible> pAccChild = pDisp;
if (!pAccChild)
continue;
// Print current accessible element
std::wcout << std::endl;
for (int y = 0; y < depth; y++)
{
std::wcout << L" ";
}
std::wcout << L"* " << GetName(pAccChild, CHILDID_SELF).data() << L" | " << GetRole(pAccChild, CHILDID_SELF).data() << L" (Object) | " << GetValue(pAccChild, CHILDID_SELF).data() << L" | " << GetDescription(pAccChild, CHILDID_SELF).data();
WalkTreeWithAccessibleChildren(pAccChild, depth + 1);
}
// Else it's a child element so we have to call accNavigate on the parent,
// and we do not recurse because child elements can't have children.
else
{
// Print current accessible element
std::wcout << std::endl;
for (int y = 0; y < depth; y++)
{
std::wcout << L" ";
}
std::wcout << L"* " << GetName(pAcc, vtChild.lVal).data() << L" | " << GetRole(pAcc, vtChild.lVal).data() << " (Child) | " << GetValue(pAcc, vtChild.lVal).data() << L" | " << GetDescription(pAcc, vtChild.lVal).data();
}
}
delete[] pArray;
return S_OK;
}
__inline static int Explorer(HWND hWnd)
{
int result = 0;
CComPtr<IAccessible> pAccMain;
if (hWnd)
{
_tsetlocale(LC_ALL, _T("chs"));
CoInitializeEx(NULL, COINIT_MULTITHREADED);
::AccessibleObjectFromWindow(hWnd, OBJID_CLIENT, IID_IAccessible, (void**)(&pAccMain));
WalkTreeWithAccessibleChildren(pAccMain, 0);
CoUninitialize();
}
return result;
}
///////////////////////////////////////////////////////////////////////////////
__inline static INT_PTR CALLBACK DlgWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_INITDIALOG:
{
}
break;
case WM_COMMAND:
{
switch (LOWORD(wParam))
{
case IDOK:
{
EndDialog(hWnd, LOWORD(wParam));
}
break;
case IDCANCEL:
{
EndDialog(hWnd, LOWORD(wParam));
}
break;
default:
break;
}
}
break;
default:
break;
}
return FALSE;
}
class CDlgItemTemplate
{
public:
CDlgItemTemplate(DWORD _dwStyle, DWORD _dwExStyle, WORD _wX, WORD _wY, WORD _wCX, WORD _wCY, WORD _wID, LPCTSTR _tCN, LPCTSTR _tTN, WORD _wCDAIT)
{
this->Initialize(_dwStyle, _dwExStyle, _wX, _wY, _wCX, _wCY, _wID, _tCN, _tTN, _wCDAIT);
}
void Initialize(DWORD _dwStyle, DWORD _dwExStyle, WORD _wX, WORD _wY, WORD _wCX, WORD _wCY, WORD _wID, LPCTSTR _tCN, LPCTSTR _tTN, WORD _wCDAIT)
{
this->dit.style = _dwStyle;
this->dit.dwExtendedStyle = _dwExStyle;
this->dit.x = _wX;
this->dit.y = _wY;
this->dit.cx = _wCX;
this->dit.cy = _wCY;
this->dit.id = _wID;
this->tCN = _tCN;
this->tTN = _tTN;
this->wCDAIT = _wCDAIT;
this->dwSize = sizeof(DLGITEMTEMPLATE) + sizeof(wCDAIT) + (this->tCN.length() + this->tTN.length() + 2) * sizeof(WCHAR);
}
public:
DWORD dwSize;
DLGITEMTEMPLATE dit;
TSTRING tCN;
TSTRING tTN;
WORD wCDAIT;
};
class CDlgTemplate
{
public:
CDlgTemplate(DWORD _dwStyle, DWORD _dwExStyle, WORD _wCDIT, WORD _wX, WORD _wY, WORD _wCX, WORD _wCY, WORD _wMENU, LPCTSTR _tCN, LPCTSTR _tTN, WORD _wFS, LPCTSTR _tFN, std::vector<CDlgItemTemplate> & _SDITVECTOR)
{
this->Initialize(_dwStyle, _dwExStyle, _wCDIT, _wX, _wY, _wCX, _wCY, _wMENU, _tCN, _tTN, _wFS, _tFN, _SDITVECTOR);
}
void Initialize(DWORD _dwStyle, DWORD _dwExStyle, WORD _wCDIT, WORD _wX, WORD _wY, WORD _wCX, WORD _wCY, WORD _wMENU, LPCTSTR _tCN, LPCTSTR _tTN, WORD _wFS, LPCTSTR _tFN, std::vector<CDlgItemTemplate> & _SDITVECTOR)
{
this->dt.style = _dwStyle;
this->dt.dwExtendedStyle = _dwExStyle;
this->dt.cdit = _wCDIT;
this->dt.x = _wX;
this->dt.y = _wY;
this->dt.cx = _wCX;
this->dt.cy = _wCY;
this->wMENU = _wMENU;
this->tCN = _tCN;
this->tTN = _tTN;
this->wFS = _wFS;
this->tFN = _tFN;
this->dwSize = sizeof(DLGTEMPLATE) + sizeof(wMENU) + sizeof(wFS) + (tCN.length() + tTN.length() + tFN.length() + 3) * sizeof(WCHAR);
this->dt.cdit = 0;
std::for_each(_SDITVECTOR.begin(), _SDITVECTOR.end(), [&, this](const std::vector<CDlgItemTemplate>::value_type & it){
this->dwSize += it.dwSize;
this->dt.cdit++;
SDITVECTOR.push_back(it);
});
}
public:
DWORD dwSize;
DLGTEMPLATE dt;
WORD wMENU;
TSTRING tCN;
TSTRING tTN;
WORD wFS;
TSTRING tFN;
std::vector<CDlgItemTemplate> SDITVECTOR;
};
__inline static BYTE * AllocDlgData(CDlgTemplate * pCDT)
{
BYTE * pbData = NULL;
DWORD dwNext = (0L);
pbData = (BYTE *)malloc(pCDT->dwSize * sizeof(BYTE)); memset(pbData, 0, pCDT->dwSize);
memcpy(pbData + dwNext, &pCDT->dt, sizeof(pCDT->dt)); dwNext += sizeof(pCDT->dt);
memcpy(pbData + dwNext, &pCDT->wMENU, sizeof(pCDT->wMENU)); dwNext += sizeof(pCDT->wMENU);
memcpy(pbData + dwNext, Convert::TToW(pCDT->tCN).c_str(), (pCDT->tCN.length() + 1) * sizeof(WCHAR)); dwNext += (pCDT->tCN.length() + 1) * sizeof(WCHAR);
memcpy(pbData + dwNext, Convert::TToW(pCDT->tTN).c_str(), (pCDT->tTN.length() + 1) * sizeof(WCHAR)); dwNext += (pCDT->tTN.length() + 1) * sizeof(WCHAR);
memcpy(pbData + dwNext, &pCDT->wFS, sizeof(pCDT->wFS)); dwNext += sizeof(pCDT->wFS);
memcpy(pbData + dwNext, Convert::TToW(pCDT->tFN).c_str(), (pCDT->tFN.length() + 1) * sizeof(WCHAR)); dwNext += (pCDT->tFN.length() + 1) * sizeof(WCHAR);
for (auto it : pCDT->SDITVECTOR)
{
memcpy(pbData + dwNext, &it.dit, sizeof(it.dit)); dwNext += sizeof(it.dit);
memcpy(pbData + dwNext, Convert::TToW(it.tCN).c_str(), (it.tCN.length() + 1) * sizeof(WCHAR)); dwNext += (it.tCN.length() + 1) * sizeof(WCHAR);
memcpy(pbData + dwNext, Convert::TToW(it.tTN).c_str(), (it.tTN.length() + 1) * sizeof(WCHAR)); dwNext += (it.tTN.length() + 1) * sizeof(WCHAR);
memcpy(pbData + dwNext, &it.wCDAIT, sizeof(it.wCDAIT)); dwNext += sizeof(it.wCDAIT);
}
return pbData;
}
__inline static VOID FreeDlgData(BYTE ** pData)
{
if (pData && *pData)
{
free((*pData));
(*pData) = NULL;
}
}
LPWORD lpwAlign(LPWORD lpIn)
{
ULONG ul;
ul = (ULONG)lpIn;
ul++;
ul >>= 1;
ul <<= 1;
return (LPWORD)ul;
}
__inline static std::string InitDlgData(CDlgTemplate & cdt)
{
std::string strData((""));
strData.append((const char *)&cdt.dt, sizeof(cdt.dt));
strData.append((const char *)&cdt.wMENU, sizeof(cdt.wMENU));
strData.append((const char *)Convert::TToW(cdt.tCN).c_str(), (cdt.tCN.length() + 1) * sizeof(WCHAR));
strData.append((const char *)Convert::TToW(cdt.tTN).c_str(), (cdt.tTN.length() + 1) * sizeof(WCHAR));
strData.append((const char *)&cdt.wFS, sizeof(cdt.wFS));
strData.append((const char *)Convert::TToW(cdt.tFN).c_str(), (cdt.tFN.length() + 1) * sizeof(WCHAR));
for (auto it : cdt.SDITVECTOR)
{
strData.append((const char *)&it.dit, sizeof(it.dit));
strData.append((const char *)Convert::TToW(it.tCN).c_str(), (it.tCN.length() + 1) * sizeof(WCHAR));
strData.append((const char *)Convert::TToW(it.tTN).c_str(), (it.tTN.length() + 1) * sizeof(WCHAR));
strData.append((const char *)&it.wCDAIT, sizeof(it.wCDAIT));
}
return strData;
}
__inline static void * InitParams()
{
DLGTEMPLATE dt = { 0 };
DLGITEMTEMPLATE dit = { 0 };
BYTE * pbData = NULL;
SIZE_T stSize = 0L;
SIZE_T stPlusSize = 0L;
WORD wMenu = 0;
WORD wFontSize = 0;
WORD wCdit = 0;
WCHAR wClassName[MAX_PATH] = { 0 };
WCHAR wTitleName[MAX_PATH] = { 0 };
WCHAR wFontName[MAX_PATH] = { 0 };
WORD stChildControlsNum = 2;
stSize = 0;
stPlusSize = sizeof(DLGTEMPLATE);
pbData = (BYTE *)realloc(pbData, (stSize + stPlusSize) * sizeof(BYTE));
dt.style = DS_MODALFRAME | DS_3DLOOK | DS_SETFONT | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_VISIBLE;
dt.dwExtendedStyle = 0;
dt.cdit = stChildControlsNum;
dt.x = 0;
dt.y = 0;
dt.cx = 278;
dt.cy = 54;
memcpy(pbData + stSize, &dt, stPlusSize);
stSize += stPlusSize;
wMenu = 0;
stPlusSize = sizeof(wMenu);
pbData = (BYTE *)realloc(pbData, (stSize + stPlusSize) * sizeof(BYTE));
memcpy(pbData + stSize, &wMenu, stPlusSize);
stSize += stPlusSize;
wcscpy(wClassName, L"");
stPlusSize = (wcslen(wClassName) + 1) * sizeof(WCHAR);
pbData = (BYTE *)realloc(pbData, (stSize + stPlusSize) * sizeof(BYTE));
memcpy(pbData + stSize, wClassName, stPlusSize);
stSize += stPlusSize;
wcscpy(wTitleName, L"Zipping");
stPlusSize = (wcslen(wTitleName) + 1) * sizeof(WCHAR);
pbData = (BYTE *)realloc(pbData, (stSize + stPlusSize) * sizeof(BYTE));
memcpy(pbData + stSize, wTitleName, stPlusSize);
stSize += stPlusSize;
wFontSize = 8;
stPlusSize = sizeof(wFontSize);
pbData = (BYTE *)realloc(pbData, (stSize + stPlusSize) * sizeof(BYTE));
memcpy(pbData + stSize, &wFontSize, stPlusSize);
stSize += stPlusSize;
wcscpy(wFontName, L"MS Sans Serif");
stPlusSize = (wcslen(wFontName) + 1) * sizeof(WCHAR);
pbData = (BYTE *)realloc(pbData, (stSize + stPlusSize) * sizeof(BYTE));
memcpy(pbData + stSize, wFontName, stPlusSize);
stSize += stPlusSize;
dit.style = BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE;
dit.dwExtendedStyle = 0;
dit.x = 113;
dit.y = 32;
dit.cx = 50;
dit.cy = 14;
dit.id = IDCANCEL;
stPlusSize = sizeof(dit);
pbData = (BYTE *)realloc(pbData, (stSize + stPlusSize) * sizeof(BYTE));
memcpy(pbData + stSize, &dit, stPlusSize);
stSize += stPlusSize;
wcscpy(wClassName, L"Button");
stPlusSize = (wcslen(wClassName) + 1) * sizeof(WCHAR);
pbData = (BYTE *)realloc(pbData, (stSize + stPlusSize) * sizeof(BYTE));
memcpy(pbData + stSize, wClassName, stPlusSize);
stSize += stPlusSize;
wcscpy(wTitleName, L"Cancel");
stPlusSize = (wcslen(wTitleName) + 1) * sizeof(WCHAR);
pbData = (BYTE *)realloc(pbData, (stSize + stPlusSize) * sizeof(BYTE));
memcpy(pbData + stSize, wTitleName, stPlusSize);
stSize += stPlusSize;
wCdit = 0;
stPlusSize = sizeof(wCdit);
pbData = (BYTE *)realloc(pbData, (stSize + stPlusSize) * sizeof(BYTE));
memcpy(pbData + stSize, &wCdit, stPlusSize);
stSize += stPlusSize;
dit.style = WS_CHILD | WS_VISIBLE;
dit.dwExtendedStyle = 0;
dit.x = 7;
dit.y = 7;
dit.cx = 264;
dit.cy = 18;
dit.id = 1;
stPlusSize = sizeof(dit);
pbData = (BYTE *)realloc(pbData, (stSize + stPlusSize) * sizeof(BYTE));
memcpy(pbData + stSize, &dit, stPlusSize);
stSize += stPlusSize;
wcscpy(wClassName, L"msctls_progress32");
stPlusSize = (wcslen(wClassName) + 1) * sizeof(WCHAR);
pbData = (BYTE *)realloc(pbData, (stSize + stPlusSize) * sizeof(BYTE));
memcpy(pbData + stSize, wClassName, stPlusSize);
stSize += stPlusSize;
wcscpy(wTitleName, L"");
stPlusSize = (wcslen(wTitleName) + 1) * sizeof(WCHAR);
pbData = (BYTE *)realloc(pbData, (stSize + stPlusSize) * sizeof(BYTE));
memcpy(pbData + stSize, wTitleName, stPlusSize);
stSize += stPlusSize;
wCdit = 0;
stPlusSize = sizeof(wCdit);
pbData = (BYTE *)realloc(pbData, (stSize + stPlusSize) * sizeof(BYTE));
memcpy(pbData + stSize, &wCdit, stPlusSize);
stSize += stPlusSize;
return pbData;
}
__inline static INT_PTR ShowDialogBoxSample1()
{
HINSTANCE hInstance = NULL;
#pragma pack(push,1)
struct TDlgItemTemplate { DWORD s, ex; short x, y, cx, cy; WORD id; };
struct TDlgTemplate { DWORD s, ex; WORD cdit; short x, y, cx, cy; };
struct TDlgItem1 { TDlgItemTemplate dli; WCHAR wclass[7]; WCHAR title[7]; WORD cdat; };
struct TDlgItem2 { TDlgItemTemplate dli; WCHAR wclass[18]; WCHAR title[25]; WORD cdat; };
struct TDlgData { TDlgTemplate dlt; WORD menu; WCHAR wclass[1]; WCHAR title[8]; WORD fontsize; WCHAR font[14]; TDlgItem1 i1; TDlgItem2 i2; };
TDlgData dtp = {
{ DS_MODALFRAME | DS_3DLOOK | DS_SETFONT | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_VISIBLE, 0, 2, 0, 0, 278, 54 },
0, L"", L"Zipping", 8, L"MS Sans Serif",
{ { BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE, 0, 113, 32, 50, 14, IDCANCEL }, L"BUTTON", L"Cancel", 0 },
{ { WS_CHILD | WS_VISIBLE, 0, 7, 7, 264, 18, 1 }, L"msctls_progress32", L"WeChatMmopen,Version1.01", 0 } };
#pragma pack(pop)
hInstance = GetModuleHandle(NULL);
InitCommonControls();
int nsize = sizeof(dtp);
int res = DialogBoxIndirectParam(hInstance, (DLGTEMPLATE*)&dtp, 0, (DLGPROC)DlgWindowProc, (LPARAM)NULL);
if (res == IDCANCEL) return 0;
return DialogBoxIndirectParam(hInstance, (DLGTEMPLATE*)&dtp, 0, (DLGPROC)DlgWindowProc, (LPARAM)NULL);
}
__inline static INT_PTR ShowDialogBoxSample2()
{
INT_PTR nRet = 0;
SIZE_T stSize = 0;
BYTE * pbData = NULL;
HINSTANCE hInstance = NULL;
CDlgTemplate cdt(DS_MODALFRAME | DS_3DLOOK | DS_SETFONT | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_MAXIMIZEBOX | WS_VISIBLE, 0,
2, 0, 0, 278, 54, 0, _T(""), _T("Zipping"), 8, _T("MS Sans Serif"),
std::vector<CDlgItemTemplate>{
CDlgItemTemplate(BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE, 0,
113, 32, 50, 14, IDCANCEL, WC_BUTTON, _T("Cancel"), 0),
CDlgItemTemplate(WS_CHILD | WS_VISIBLE, 0,
7, 7, 264, 18, 1, PROGRESS_CLASS, _T("ProgressBar"), 0),
});
pbData = AllocDlgData(&cdt);
hInstance = GetModuleHandle(NULL);
InitCommonControls();
nRet = DialogBoxIndirectParam(hInstance, (DLGTEMPLATE*)pbData, 0, (DLGPROC)DlgWindowProc, (LPARAM)NULL);
FreeDlgData(&pbData);
return nRet;
}
__inline static INT_PTR ShowDialogBoxSample3()
{
INT_PTR nResult = 0;
HINSTANCE hInstance = NULL;
std::string strDlgData((""));
strDlgData = InitDlgData(
CDlgTemplate(DS_MODALFRAME | DS_3DLOOK | DS_SETFONT | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_VISIBLE, 0,
2, 0, 0, 278, 54, 0, _T(""), _T("Zipping"), 8, _T("MS Sans Serif"),
std::vector<CDlgItemTemplate>({
CDlgItemTemplate(BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE, 0,
63, 32, 50, 14, IDOK, WC_BUTTON, _T("Ok"), 0),
CDlgItemTemplate(BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE, 0,
113, 32, 50, 14, IDCANCEL, WC_BUTTON, _T("Cancel"), 0),
CDlgItemTemplate(WS_CHILD | WS_VISIBLE, 0,
7, 7, 264, 18, 1, PROGRESS_CLASS, _T("ProgressBar"), 0)
})));
hInstance = GetModuleHandle(NULL);
InitCommonControls();
nResult = DialogBoxIndirectParam(hInstance, (DLGTEMPLATE*)strDlgData.c_str(), 0, (DLGPROC)DlgWindowProc, (LPARAM)NULL);
if (nResult != IDCANCEL)
{
//nResult = DialogBoxIndirectParam(hInstance, (DLGTEMPLATE*)strDlgData.c_str(), 0, (DLGPROC)DlgWindowProc, (LPARAM)NULL);
}
return nResult;
}
__inline static INT_PTR ShowDialogBoxSample4(DLGPROC dlgproc = DlgWindowProc)
{
INT_PTR nRet = 0;
SIZE_T stSize = 0;
BYTE * pbData = NULL;
HINSTANCE hInstance = NULL;
CDlgTemplate cdt(DS_MODALFRAME | DS_3DLOOK | DS_SETFONT | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_MAXIMIZEBOX | WS_VISIBLE, 0,
2, 0, 0, 278, 54, 0, _T(""), _T("Zipping"), 8, _T("MS Sans Serif"),
std::vector<CDlgItemTemplate>({
CDlgItemTemplate(BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE, 0,
113, 32, 50, 14, IDCANCEL, WC_BUTTON, _T("Cancel"), 0),
CDlgItemTemplate(WS_CHILD | WS_VISIBLE, 0,
7, 7, 264, 18, 1, PROGRESS_CLASS, _T("ProgressBar"), 0),
}));
InitCommonControls();
pbData = AllocDlgData(&cdt);
hInstance = GetModuleHandle(NULL);
InitCommonControls();
nRet = DialogBoxIndirectParam(hInstance, (DLGTEMPLATE*)pbData, 0, (DLGPROC)dlgproc, (LPARAM)NULL);
FreeDlgData(&pbData);
return nRet;
}
__inline static INT_PTR ShowDialogBoxSample5(DLGPROC dlgproc = DlgWindowProc)
{
INT_PTR nResult = 0;
HINSTANCE hInstance = NULL;
std::string strDlgData((""));
InitCommonControls();
strDlgData = InitDlgData(
CDlgTemplate(DS_MODALFRAME | DS_3DLOOK | DS_SETFONT | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_VISIBLE, 0,
2, 0, 0, 278, 54, 0, _T(""), _T("Zipping"), 8, _T("MS Sans Serif"),
std::vector<CDlgItemTemplate>({
CDlgItemTemplate(BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE, 0,
63, 32, 50, 14, IDOK, WC_BUTTON, _T("Ok"), 0),
CDlgItemTemplate(BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE, 0,
113, 32, 50, 14, IDCANCEL, WC_BUTTON, _T("Cancel"), 0),
CDlgItemTemplate(WS_CHILD | WS_VISIBLE, 0,
7, 7, 264, 18, 1, PROGRESS_CLASS, _T("ProgressBar"), 0)
})));
hInstance = GetModuleHandle(NULL);
InitCommonControls();
nResult = DialogBoxIndirectParam(hInstance, (DLGTEMPLATE*)strDlgData.c_str(), 0, (DLGPROC)dlgproc, (LPARAM)NULL);
if (nResult != IDCANCEL)
{
//nResult = DialogBoxIndirectParam(hInstance, (DLGTEMPLATE*)strDlgData.c_str(), 0, (DLGPROC)dlgproc, (LPARAM)NULL);
}
return nResult;
}
__inline static INT_PTR DisplayDialogBox(DLGTEMPLATE * pdlgtemplate, DLGPROC dlgproc = DlgWindowProc, HWND hWndParent = NULL, LPARAM lparam = NULL, HINSTANCE hInstance = GetModuleHandle(NULL))
{
return ::DialogBoxIndirectParam((HINSTANCE)hInstance, (DLGTEMPLATE*)pdlgtemplate, (HWND)hWndParent, (DLGPROC)dlgproc, (LPARAM)lparam);
}
__inline static INT_PTR DisplayDialogBox(CDlgTemplate & cdt, DLGPROC dlgproc = DlgWindowProc, HWND hWndParent = NULL, LPARAM lparam = NULL, HINSTANCE hInstance = GetModuleHandle(NULL))
{
return DisplayDialogBox((DLGTEMPLATE*)InitDlgData(cdt).c_str(), (DLGPROC)dlgproc, (HWND)hWndParent, (LPARAM)lparam, (HINSTANCE)hInstance);
}
__inline static HWND CreateDialogBox(DLGTEMPLATE * pdlgtemplate, DLGPROC dlgproc = DlgWindowProc, HWND hWndParent = NULL, LPARAM lparam = NULL, HINSTANCE hInstance = GetModuleHandle(NULL))
{
return ::CreateDialogIndirectParam((HINSTANCE)hInstance, (DLGTEMPLATE*)pdlgtemplate, (HWND)hWndParent, (DLGPROC)dlgproc, (LPARAM)lparam);
}
__inline static HWND CreateDialogBox(CDlgTemplate & cdt, DLGPROC dlgproc = DlgWindowProc, HWND hWndParent = NULL, LPARAM lparam = NULL, HINSTANCE hInstance = GetModuleHandle(NULL))
{
return CreateDialogBox((DLGTEMPLATE*)InitDlgData(cdt).c_str(), (DLGPROC)dlgproc, (HWND)hWndParent, (LPARAM)lparam, (HINSTANCE)hInstance);
}
__inline static BOOL WindowClassesRegister(HINSTANCE hInstance,
LPCTSTR lpClassName,
WNDPROC lpfnWndProc,
LPCTSTR lpszMenuName = NULL,
HBRUSH hbrBackground = (HBRUSH)COLOR_BACKGROUND,
HICON hIcon = LoadIcon(NULL, IDI_APPLICATION),
HICON hIconSm = LoadIcon(NULL, IDI_APPLICATION),
HICON hCursor = LoadCursor(NULL, IDC_ARROW),
UINT uStyle = CS_DBLCLKS,
INT cbClsExtra = 0,
INT cbWndExtra = 0
)
{
//Data structure for the windowclass
WNDCLASSEX wcex = { 0 };
wcex.cbSize = sizeof(WNDCLASSEX);
// The Window structure
wcex.hInstance = hInstance;
wcex.lpszClassName = lpClassName;
//This function is called by windows
wcex.lpfnWndProc = lpfnWndProc;
//Catch double-clicks
wcex.style = uStyle;
// Use default icon and mouse-pointer
wcex.hIcon = hIcon;
wcex.hIconSm = hIconSm;
wcex.hCursor = hCursor;
//No menu
wcex.lpszMenuName = lpszMenuName;
//No extra bytes after the window class
wcex.cbClsExtra = cbClsExtra;
//structure or the window instance
wcex.cbWndExtra = cbWndExtra;
// Use Windows's default colour as the background of the window
wcex.hbrBackground = hbrBackground;
// Register the window class, and if it fails quit the program
return RegisterClassEx(&wcex);
}
__inline static HWND CreateCustomWindow(HINSTANCE hInstance,
LPCTSTR lpszClassName,
LPCTSTR lpszTitleName = _T("TemplateWindowsApplication"),
DWORD dwStyle = WS_OVERLAPPEDWINDOW,
DWORD dwExtendStyle = 0,
RECT rcRect = { CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT + 300, CW_USEDEFAULT + 200 },
HWND hWndParent = HWND_DESKTOP,
HMENU hMenu = NULL,
LPVOID lpCreationData = NULL)
{
// The class is registered, let's create the program
return CreateWindowEx(
dwExtendStyle,// Extended possibilites for variation
lpszClassName,// Classname
lpszTitleName,//Title Text
dwStyle,//default window
rcRect.left,//Windows decides the position
rcRect.top,//where the window ends up on the screen
rcRect.right - rcRect.left,//The programs width
rcRect.bottom - rcRect.top,//and height in pixels
hWndParent,//The window is a child-window to desktop
hMenu,//No menu */
hInstance,//Program Instance handler
lpCreationData//No Window Creation data
);
}
__inline static UINT_PTR StartupWindows(HWND hWnd, INT nCmdShow)
{
MSG msg = { 0 };
// Make the window visible on the screen
::ShowWindow(hWnd, nCmdShow);
// Update the window visible on the screen
::UpdateWindow(hWnd);
// Run the message loop. It will run until GetMessage() returns 0
while (::GetMessage(&msg, NULL, 0, 0))
{
// Translate virtual-key messages into character messages
::TranslateMessage(&msg);
// Send message to WindowProcedure
::DispatchMessage(&msg);
}
// The program return-value is 0 - The value that PostQuitMessage() gave
return msg.wParam;
}
__inline static UINT_PTR StartupWindowsAsynchromous(HWND hWnd, INT nCmdShow)
{
MSG msg = { 0 };
// Make the window visible on the screen
::ShowWindow(hWnd, nCmdShow);
// Update the window visible on the screen
::UpdateWindow(hWnd);
// Run the message loop. It will run until PeekMessage() returns 0
while (1)
{
if (::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
// Translate virtual-key messages into character messages
::TranslateMessage(&msg);
// Send message to WindowProcedure
::DispatchMessage(&msg);
}
else
{
// Do something
}
}
// The program return-value is 0 - The value that PostQuitMessage() gave
return msg.wParam;
}
typedef struct tagEnumWindowInfo
{
HWND hWnd;
DWORD dwPid;
}ENUMWINDOWINFO, *PENUMWINDOWINFO;
__inline static BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam)
{
ENUMWINDOWINFO* pInfo = (ENUMWINDOWINFO*)lParam;
DWORD dwProcessId = 0;
GetWindowThreadProcessId(hWnd, &dwProcessId);
if (dwProcessId == pInfo->dwPid)
{
pInfo->hWnd = hWnd;
return FALSE;
}
return TRUE;
}
__inline static void ShowAbout(HWND hWnd = NULL, WORD wIconResId = (0L), LPCTSTR lpWindowInfo = _T("About"), LPCTSTR lpVersionInfo = _T("Version1.0"), LPCTSTR lpCopyrightInfo = _T("Copyright (C) 2018"), LPCTSTR lpContactInfo = _T("Contact:xingyun86"), LPCTSTR lpButtonInfo = _T("确定"))
{
#define TTMAP_KEY_ICONID "ICON_ID"
#define TTMAP_KEY_WINDOWINFO "WINDOW_INFO"
#define TTMAP_KEY_VERSIONINFO "VERSION_INFO"
#define TTMAP_KEY_COPYRIGHTINFO "COPYRIGHT_INFO"
#define TTMAP_KEY_CONTACTINFO "CONTACT_INFO"
#define TTMAP_KEY_OKBUTTON_INFO "OKBUTTON_INFO"
TSTRINGTSTRINGMAP ttmap = {
{ _T(TTMAP_KEY_ICONID), STRING_FORMAT(_T("0x%08X"), wIconResId) },
{ _T(TTMAP_KEY_WINDOWINFO), lpWindowInfo },
{ _T(TTMAP_KEY_VERSIONINFO), lpVersionInfo },
{ _T(TTMAP_KEY_COPYRIGHTINFO), lpCopyrightInfo },
{ _T(TTMAP_KEY_CONTACTINFO), lpContactInfo },
{ _T(TTMAP_KEY_OKBUTTON_INFO), lpButtonInfo },
};
// 通用控件 初始化
InitCommonControls();
DisplayDialogBox(
CDlgTemplate(DS_MODALFRAME | DS_FIXEDSYS | DS_3DLOOK | DS_SETFONT | DS_CENTER | WS_BORDER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0, \
2, 0, 0, 200, 100, 0, _T(""), _T("ABOUT"), 8, _T("MS Sans Serif"), \
std::vector<CDlgItemTemplate>{ \
CDlgItemTemplate(WS_CHILD | WS_VISIBLE | SS_ICON | SS_CENTERIMAGE, 0, \
14, 14, 21, 20, 100, WC_STATIC, WC_STATIC, 0), \
CDlgItemTemplate(WS_CHILD | WS_VISIBLE | SS_LEFT | SS_NOPREFIX, 0, \
42, 14, 198, 8, 101, WC_STATIC, WC_STATIC, 0), \
CDlgItemTemplate(WS_CHILD | WS_VISIBLE | ES_LEFT | ES_MULTILINE | ES_READONLY, 0, \
42, 26, 198, 24, 102, WC_EDIT, WC_EDIT, 0), \
CDlgItemTemplate(WS_CHILD | WS_VISIBLE | SS_LEFT, 0, \
41, 51, 198, 8, 103, WC_STATIC, WC_STATIC, 0), \
CDlgItemTemplate(WS_CHILD | WS_VISIBLE | WS_GROUP | BS_DEFPUSHBUTTON, 0, \
114, 72, 50, 14, IDOK, WC_BUTTON, WC_BUTTON, 0), \
}),
(DLGPROC)[](HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)->INT_PTR
{
switch (uMsg)
{
case WM_INITDIALOG:
{
HICON hIcon = NULL;
TSTRINGTSTRINGMAP * pTTMAP = (TSTRINGTSTRINGMAP*)lParam;
WORD wIconId = _tcstoul(pTTMAP->at(_T(TTMAP_KEY_ICONID)).c_str(), 0, 16);
if (IsWindow(GetParent(hWnd)))
{
hIcon = (HICON)SendMessage(GetParent(hWnd), WM_GETICON, ICON_BIG, (LPARAM)0L);
if (!hIcon)
{
hIcon = (HICON)SendMessage(GetParent(hWnd), WM_GETICON, ICON_SMALL, (LPARAM)0L);
if (!hIcon)
{
hIcon = (HICON)SendMessage(GetParent(hWnd), WM_GETICON, ICON_SMALL2, (LPARAM)0L);
}
}
}
else if (wIconId)
{
hIcon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(wIconId));
}
else
{
}
if (hIcon)
{
SNDMSG(hWnd, WM_SETICON, ICON_BIG, (LPARAM)hIcon);
SNDMSG(hWnd, WM_SETICON, ICON_SMALL, (LPARAM)hIcon);
SNDMSG(hWnd, WM_SETICON, ICON_SMALL2, (LPARAM)hIcon);
SNDMSG(GetDlgItem(hWnd, 100), STM_SETIMAGE, IMAGE_ICON, (LPARAM)hIcon);
}
SetWindowText(hWnd, pTTMAP->at(_T(TTMAP_KEY_WINDOWINFO)).c_str());
SetDlgItemText(hWnd, 101, pTTMAP->at(_T(TTMAP_KEY_VERSIONINFO)).c_str());
SetDlgItemText(hWnd, 102, pTTMAP->at(_T(TTMAP_KEY_COPYRIGHTINFO)).c_str());
SetDlgItemText(hWnd, 103, pTTMAP->at(_T(TTMAP_KEY_CONTACTINFO)).c_str());
SetDlgItemText(hWnd, IDOK, pTTMAP->at(_T(TTMAP_KEY_OKBUTTON_INFO)).c_str());
}
break;
case WM_SETFONT:
{
}
break;
case WM_COMMAND:
{
switch (LOWORD(wParam))
{
case IDOK:
case IDCANCEL:
{
EndDialog(hWnd, LOWORD(wParam));
}
break;
default:
break;
}
}
break;
//case WM_CLOSE:
//{
// PostQuitMessage(LOWORD(wParam));
//}
//break;
default:
break;
}
return FALSE;
}, hWnd, (LPARAM)&ttmap);
}
__inline static void SelectColor()
{
CHOOSECOLOR cc; // common dialog box structure
static COLORREF acrCustClr[16]; // array of custom colors
HWND hwnd; // owner window
HBRUSH hbrush; // brush handle
static DWORD rgbCurrent; // initial color selection
// Initialize CHOOSECOLOR
ZeroMemory(&cc, sizeof(cc));
cc.lStructSize = sizeof(cc);
cc.hwndOwner = hwnd;
cc.lpCustColors = (LPDWORD)acrCustClr;
cc.rgbResult = rgbCurrent;
cc.Flags = CC_FULLOPEN | CC_RGBINIT;
if (ChooseColor(&cc) == TRUE)
{
hbrush = CreateSolidBrush(cc.rgbResult);
rgbCurrent = cc.rgbResult;
}
}
__inline static void SelectFont()
{
HWND hwnd; // owner window
HDC hdc; // display device context of owner window
CHOOSEFONT cf; // common dialog box structure
static LOGFONT lf; // logical font structure
static DWORD rgbCurrent; // current text color
HFONT hfont, hfontPrev;
DWORD rgbPrev;
// Initialize CHOOSEFONT
ZeroMemory(&cf, sizeof(cf));
cf.lStructSize = sizeof(cf);
cf.hwndOwner = hwnd;
cf.lpLogFont = &lf;
cf.rgbColors = rgbCurrent;
cf.Flags = CF_SCREENFONTS | CF_EFFECTS;
if (ChooseFont(&cf) == TRUE)
{
hfont = CreateFontIndirect(cf.lpLogFont);
hfontPrev = (HFONT)SelectObject(hdc, hfont);
rgbCurrent = cf.rgbColors;
rgbPrev = SetTextColor(hdc, rgbCurrent);
}
}
//显示打印对话框
__inline static void ShowPrintDlg(HWND hwnd = NULL)
{
PRINTDLG pd;
//HWND hwnd = NULL;
// Initialize PRINTDLG
ZeroMemory(&pd, sizeof(pd));
pd.lStructSize = sizeof(pd);
pd.hwndOwner = hwnd;
pd.hDevMode = NULL; // Don't forget to free or store hDevMode.
pd.hDevNames = NULL; // Don't forget to free or store hDevNames.
pd.Flags = PD_USEDEVMODECOPIESANDCOLLATE | PD_RETURNDC;
pd.nCopies = 1;
pd.nFromPage = 0xFFFF;
pd.nToPage = 0xFFFF;
pd.nMinPage = 1;
pd.nMaxPage = 0xFFFF;
if (PrintDlg(&pd) == TRUE)
{
// GDI calls to render output.
// Delete DC when done.
DeleteDC(pd.hDC);
}
}
// hWnd is the window that owns the property sheet.
__inline static HRESULT DisplayPrintPropertySheet(HWND hWnd)
{
HRESULT hResult;
PRINTDLGEX pdx = { 0 };
LPPRINTPAGERANGE pPageRanges = NULL;
// Allocate an array of PRINTPAGERANGE structures.
pPageRanges = (LPPRINTPAGERANGE)GlobalAlloc(GPTR, 10 * sizeof(PRINTPAGERANGE));
if (!pPageRanges)
return E_OUTOFMEMORY;
// Initialize the PRINTDLGEX structure.
pdx.lStructSize = sizeof(PRINTDLGEX);
pdx.hwndOwner = hWnd;
pdx.hDevMode = NULL;
pdx.hDevNames = NULL;
pdx.hDC = NULL;
pdx.Flags = PD_RETURNDC | PD_COLLATE;
pdx.Flags2 = 0;
pdx.ExclusionFlags = 0;
pdx.nPageRanges = 0;
pdx.nMaxPageRanges = 10;
pdx.lpPageRanges = pPageRanges;
pdx.nMinPage = 1;
pdx.nMaxPage = 1000;
pdx.nCopies = 1;
pdx.hInstance = 0;
pdx.lpPrintTemplateName = NULL;
pdx.lpCallback = NULL;
pdx.nPropertyPages = 0;
pdx.lphPropertyPages = NULL;
pdx.nStartPage = START_PAGE_GENERAL;
pdx.dwResultAction = 0;
// Invoke the Print property sheet.
hResult = PrintDlgEx(&pdx);
if ((hResult == S_OK) && pdx.dwResultAction == PD_RESULT_PRINT)
{
// User clicked the Print button, so use the DC and other information returned in the
// PRINTDLGEX structure to print the document.
}
if (pdx.hDevMode != NULL)
GlobalFree(pdx.hDevMode);
if (pdx.hDevNames != NULL)
GlobalFree(pdx.hDevNames);
if (pdx.lpPageRanges != NULL)
GlobalFree(pPageRanges);
if (pdx.hDC != NULL)
DeleteDC(pdx.hDC);
return hResult;
}
__inline static UINT_PTR CALLBACK PaintHook(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
LPRECT lprc;
COLORREF crMargRect;
HDC hdc, hdcOld;
switch (uMsg)
{
// Draw the margin rectangle.
case WM_PSD_MARGINRECT:
hdc = (HDC)wParam;
lprc = (LPRECT)lParam;
// Get the system highlight color.
crMargRect = GetSysColor(COLOR_HIGHLIGHT);
// Create a dash-dot pen of the system highlight color and
// select it into the DC of the sample page.
hdcOld = (HDC)SelectObject(hdc, CreatePen(PS_DASHDOT, .5, crMargRect));
// Draw the margin rectangle.
Rectangle(hdc, lprc->left, lprc->top, lprc->right, lprc->bottom);
// Restore the previous pen to the DC.
SelectObject(hdc, hdcOld);
return TRUE;
default:
return FALSE;
}
return TRUE;
}
__inline static void SettingUpPaintPage(LPPAGESETUPHOOK lpPageSetupHook = NULL, LPPAGEPAINTHOOK lpPagePaintHook = &PaintHook)
{
PAGESETUPDLG psd; // common dialog box structure
HWND hwnd; // owner window
// Initialize PAGESETUPDLG
ZeroMemory(&psd, sizeof(psd));
psd.lStructSize = sizeof(psd);
psd.hwndOwner = hwnd;
psd.hDevMode = NULL; // Don't forget to free or store hDevMode.
psd.hDevNames = NULL; // Don't forget to free or store hDevNames.
psd.Flags = PSD_INTHOUSANDTHSOFINCHES | PSD_MARGINS |
PSD_ENABLEPAGEPAINTHOOK;
psd.rtMargin.top = 1000;
psd.rtMargin.left = 1250;
psd.rtMargin.right = 1250;
psd.rtMargin.bottom = 1000;
psd.lpfnPageSetupHook = lpPageSetupHook;
psd.lpfnPagePaintHook = lpPagePaintHook;
if (PageSetupDlg(&psd) == TRUE)
{
// check paper size and margin values here.
}
}
__inline static void ShowFindTextDlg(HWND hWnd = NULL, LPCTSTR lpWindowInfo = _T("About"))
{
#define TTMAP_KEY_WINDOWINFO "WINDOW_INFO"
static UINT uFindReplaceMsg; // message identifier for FINDMSGSTRING
static HWND hdlg = NULL; // handle to Find dialog box
SORTDATAINFO m_sdi;
static SORTDATAINFO * pSDI = &m_sdi;
TSTRINGTSTRINGMAP ttmap = {
{ _T(TTMAP_KEY_WINDOWINFO), lpWindowInfo },
};
// 通用控件 初始化
InitCommonControls();
INITCOMMONCONTROLSEX iccex = { 0 };
iccex.dwSize = sizeof(iccex);
// 将它设置为包括所有要在应用程序中使用的公共控件类。
iccex.dwICC = ICC_WIN95_CLASSES;
::InitCommonControlsEx(&iccex);
DisplayDialogBox(
CDlgTemplate(DS_MODALFRAME | DS_FIXEDSYS | DS_3DLOOK | DS_SETFONT | DS_CENTER | WS_BORDER | WS_POPUP | WS_MAXIMIZEBOX | WS_CAPTION | WS_SYSMENU | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0, \
2, 0, 0, 200, 100, 0, _T(""), _T("About"), 8, _T("MS Sans Serif"), \
std::vector<CDlgItemTemplate>{ \
//CDlgItemTemplate(WS_CHILD | WS_VISIBLE | SS_ICON | SS_CENTERIMAGE, 0, \
//14, 14, 21, 20, 100, WC_STATIC, _T(""), 0),
CDlgItemTemplate(WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | LVS_REPORT | LVS_SINGLESEL, LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT, \
42, 14, 198, 8, 101, WC_LISTVIEW, _T("ListVi"), 0),
//CDlgItemTemplate(WS_CHILD | WS_VISIBLE | WS_GROUP | BS_DEFPUSHBUTTON, 0, \
//114, 72, 50, 14, IDOK, WC_BUTTON, _T("确定"), 0),
}),
(DLGPROC)[](HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)->INT_PTR
{
switch (uMsg)
{
case WM_INITDIALOG:
{
//启动查找时打开
//uFindReplaceMsg = RegisterWindowMessage(FINDMSGSTRING);
FINDREPLACE fr; // common dialog box structure
//HWND hwnd; // owner window
_TCHAR szFindWhat[MAXBYTE] = { 0 }; // buffer receiving string
//HWND hdlg = NULL; // handle to Find dialog box
// Initialize FINDREPLACE
ZeroMemory(&fr, sizeof(fr));
fr.lStructSize = sizeof(fr);
fr.hwndOwner = GetDlgItem(hWnd, 101);
fr.lpstrFindWhat = szFindWhat;
fr.wFindWhatLen = MAXBYTE;
fr.Flags = 0;
//hdlg = FindText(&fr);
HICON hIcon = NULL;
TSTRINGTSTRINGMAP * pTTMAP = (TSTRINGTSTRINGMAP*)lParam;
if (IsWindow(GetParent(hWnd)))
{
hIcon = (HICON)SendMessage(GetParent(hWnd), WM_GETICON, ICON_BIG, (LPARAM)0L);
if (!hIcon)
{
hIcon = (HICON)SendMessage(GetParent(hWnd), WM_GETICON, ICON_SMALL, (LPARAM)0L);
if (!hIcon)
{
hIcon = (HICON)SendMessage(GetParent(hWnd), WM_GETICON, ICON_SMALL2, (LPARAM)0L);
}
}
}
else
{
}
if (hIcon)
{
SNDMSG(hWnd, WM_SETICON, ICON_BIG, (LPARAM)hIcon);
SNDMSG(hWnd, WM_SETICON, ICON_SMALL, (LPARAM)hIcon);
SNDMSG(hWnd, WM_SETICON, ICON_SMALL2, (LPARAM)hIcon);
SNDMSG(GetDlgItem(hWnd, 100), STM_SETIMAGE, IMAGE_ICON, (LPARAM)hIcon);
}
SetWindowText(hWnd, pTTMAP->at(_T(TTMAP_KEY_WINDOWINFO)).c_str());
//RECT rc = { 0 };
//HWND hListWnd = CreateCustomWindow(GetModuleHandle(NULL), WC_LISTVIEW, _T(""), WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | LVS_REPORT | LVS_SINGLESEL, LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT, rc, hWnd, (HMENU)101);
TSTRINGVECTOR tv;
TSTRINGVECTORMAP tvmap = {
{ _T("进程名称"), tv },
{ _T("进程ID"), tv },
{ _T("图标文件"), tv },
};
std::map<DWORD, PROCESSENTRY32> pemap;
std::map<DWORD, PROCESSENTRY32>::iterator itEnd;
std::map<DWORD, PROCESSENTRY32>::iterator itIdx;
SystemKernel::EnumProcess_R3(&pemap);
itEnd = pemap.end();
itIdx = pemap.begin();
HIMAGELIST hImageList = ImageList_Create(32, 32, ILC_COLOR8 | ILC_MASK, 3, 1);
for (; itIdx != itEnd; itIdx++)
{
/*TSTRING tsName = _T("");
_TCHAR tF[MAX_PATH] = { 0 };
GetProcessFullPath(itIdx->second.th32ProcessID, tF);
HANDLE h_Process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, itIdx->second.th32ProcessID);
if (h_Process)
{
_TCHAR tFilePath[MAX_PATH] = { 0 };
::GetModuleFileName((HMODULE)h_Process, tFilePath, MAX_PATH + 1);
CloseHandle(h_Process);
}*/
TSTRING tsFileName = _T("");
std::map<DWORD, MODULEENTRY32> memap;
SystemKernel::EnumModules_R3(&memap, itIdx->second.th32ProcessID);
if (memap.size() && lstrlen(memap.begin()->second.szExePath))
{
tsFileName = memap.begin()->second.szExePath;
}
else
{
if (FilePath::IsFileExistEx((PPSHUAI::FilePath::GetSystemPath() + itIdx->second.szExeFile).c_str()))
{
tsFileName = (PPSHUAI::FilePath::GetSystemPath() + itIdx->second.szExeFile);
}
else
{
tsFileName = itIdx->second.szExeFile;
}
}
tvmap.at(_T("进程名称")).push_back(itIdx->second.szExeFile);
tvmap.at(_T("进程ID")).push_back(PPSHUAI::STRING_FORMAT(_T("%ld"), itIdx->second.th32ProcessID));
tvmap.at(_T("图标文件")).push_back(tsFileName);
}
GUI::ImageListInit(hImageList, &tvmap, _T("图标文件"));
ListView_SetImageList(GetDlgItem(hWnd, 101), hImageList, LVSIL_NORMAL);
ListView_SetImageList(GetDlgItem(hWnd, 101), hImageList, LVSIL_SMALL);
ListCtrlSetSortDataInfo(GetDlgItem(hWnd, 101), pSDI);
ListCtrlDeleteAllRows(GetDlgItem(hWnd, 101));
ListCtrlDeleteAllColumns(GetDlgItem(hWnd, 101));
ListCtrlInsertData(&tvmap,GetDlgItem(hWnd, 101), hImageList);
MoveWindow(GetDlgItem(hWnd, 101), 0, 0, 200, 100, FALSE);
}
break;
case WM_SETFONT:
{
}
break;
case WM_SIZE:
{
RECT rcWin = { 0 };
GetClientRect(hWnd, &rcWin);
HWND hListViewWnd = GetDlgItem(hWnd, 101);
if (hListViewWnd)
{
MoveWindow(hListViewWnd, rcWin.left, rcWin.top, rcWin.right - rcWin.left, rcWin.bottom - rcWin.top, FALSE);
}
RedrawWindow(hWnd, &rcWin, NULL, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN | RDW_ERASE);
}
break;
case WM_COMMAND:
{
switch (LOWORD(wParam))
{
case IDOK:
case IDCANCEL:
{
EndDialog(hWnd, LOWORD(wParam));
}
break;
default:
break;
}
}
break;
//case WM_CLOSE:
//{
// PostQuitMessage(LOWORD(wParam));
//}
//break;
default:
{
LPFINDREPLACE lpfr;
if (uMsg == uFindReplaceMsg)
{
// Get pointer to FINDREPLACE structure from lParam.
lpfr = (LPFINDREPLACE)lParam;
// If the FR_DIALOGTERM flag is set,
// invalidate the handle that identifies the dialog box.
if (lpfr->Flags & FR_DIALOGTERM)
{
hdlg = NULL;
return 0;
}
// If the FR_FINDNEXT flag is set,
// call the application-defined search routine
// to search for the requested string.
if (lpfr->Flags & FR_FINDNEXT)
{
//SearchFile(lpfr->lpstrFindWhat, \
(BOOL)(lpfr->Flags & FR_DOWN), \
(BOOL)(lpfr->Flags & FR_MATCHCASE));
}
return 0;
}
}
break;
}
return FALSE;
}, hWnd, (LPARAM)&ttmap);
}
/*******************************************************
*函数功能:按照进程ID获取主窗口句柄
*函数参数:参数1:进程ID
*函数返回:HWND
*注意事项:无
*最后修改时间:2017/5/13
*******************************************************/
__inline static HWND GetHwndByProcessId(DWORD dwProcessId)
{
ENUMWINDOWINFO info = { 0 };
info.hWnd = NULL;
info.dwPid = dwProcessId;
EnumWindows(EnumWindowsProc, (LPARAM)&info);
return info.hWnd;
}
/////////////////////////////////////////////////////////////////////////////////////////////
//
__inline static LONG GetDWORDRegKey(HKEY hKey, const TSTRING &strValueName, DWORD &nValue, DWORD nDefaultValue) {
nValue = nDefaultValue;
DWORD dwBufferSize(sizeof(DWORD));
DWORD nResult(0);
LONG nError = ::RegQueryValueEx(hKey, strValueName.c_str(), 0, NULL, reinterpret_cast<LPBYTE>(&nResult), &dwBufferSize);
if (ERROR_SUCCESS == nError) {
nValue = nResult;
}
return nError;
}
__inline static LONG GetStringRegKey(HKEY hKey, const TSTRING &strValueName, TSTRING &strValue, TSTRING &strDefaultValue) {
strValue = strDefaultValue;
_TCHAR szBuffer[512];
DWORD dwBufferSize = sizeof(szBuffer);
ULONG nError;
nError = RegQueryValueEx(hKey, strValueName.c_str(), 0, NULL, (LPBYTE)szBuffer, &dwBufferSize);
if (ERROR_SUCCESS == nError) {
strValue = szBuffer;
}
return nError;
}
__inline static bool SetBrowserFeatureControlKey(TSTRING feature, _TCHAR *appName, DWORD value) {
HKEY key;
bool success = true;
TSTRING featuresPath(_T("Software\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\"));
TSTRING path(featuresPath + feature);
LONG nError = RegCreateKeyEx(HKEY_CURRENT_USER, path.c_str(), 0, NULL, REG_OPTION_VOLATILE, KEY_WRITE, NULL, &key, NULL);
if (nError != ERROR_SUCCESS) {
success = false;
}
else {
nError = RegSetValueEx(key, appName, 0, REG_DWORD, (const BYTE*)&value, sizeof(value));
if (nError != ERROR_SUCCESS) {
success = false;
}
nError = RegCloseKey(key);
if (nError != ERROR_SUCCESS) {
success = false;
}
}
return success;
}
__inline static DWORD GetBrowserEmulationMode() {
long browserVersion = 8;
TSTRING sBrowserVersion;
HKEY key;
bool success = true;
TSTRING path(_T("SOFTWARE\\Microsoft\\Internet Explorer"));
LONG nError = RegOpenKeyEx(HKEY_LOCAL_MACHINE, path.c_str(), 0, KEY_QUERY_VALUE, &key);
DWORD mode = 11000; // Internet Explorer 11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 Standards mode. Default value for Internet Explorer 11.
if (nError != ERROR_SUCCESS) {
success = false;
}
else {
nError = GetStringRegKey(key, _T("svcVersion"), sBrowserVersion, TSTRING(_T("8")));
if (nError != ERROR_SUCCESS) {
nError = GetStringRegKey(key, _T("version"), sBrowserVersion, TSTRING(_T("8")));
if (nError != ERROR_SUCCESS) {
success = false;
}
}
if (RegCloseKey(key) != ERROR_SUCCESS) {
success = false;
}
}
if (success) {
TSTRINGVECTOR splittedBrowserVersion;
PPSHUAI::String::TSTRING_SPLIT_TO_VECTOR(splittedBrowserVersion, sBrowserVersion, _T("."));
browserVersion = _ttol(splittedBrowserVersion.at(0).c_str()); // convert base 16 number in s to int
/////////////////////////////////////////////////////////
// 11001(0×2af9) IE11 忽略html5
// 11000(0×2af8) IE11
// 10001(0×2711) IE10 忽略html5
// 10000(0×2710) IE10
// 9999 (0x270F) IE9 忽略html5
// 9000 (0×2328) IE9
// 8888 (0x22B8) IE8 忽略html5
// 8000 (0x1F40) IE8
// 7000 (0x1B58) IE7
switch (browserVersion) {
case 7:
mode = 7000; // Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode. Default value for applications hosting the WebBrowser Control.
break;
case 8:
mode = 8000; // Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode. Default value for Internet Explorer 8
break;
case 9:
mode = 9000; // Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode. Default value for Internet Explorer 9.
break;
case 10:
mode = 10000; // Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 mode. Default value for Internet Explorer 10.
break;
case 11:
mode = 11000; // Internet Explorer 11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 mode. Default value for Internet Explorer 11.
break;
default:
// use IE8 mode by default
mode = 8000; // Internet Explorer 8. Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode. Default value for Internet Explorer 8.
break;
}
}
else {
mode = -1;
}
return mode;
}
__inline static void SetBrowserFeatureControl() {
// http://msdn.microsoft.com/en-us/library/ee330720(v=vs.85).aspx
DWORD emulationMode = GetBrowserEmulationMode();
if (emulationMode > 0) {
// FeatureControl settings are per-process
_TCHAR fileName[MAX_PATH + 1] = { 0 };
ZeroMemory(fileName, (MAX_PATH + 1) * sizeof(_TCHAR));
GetModuleFileName(NULL, fileName, 256);
TSTRINGVECTOR splittedFileName;
PPSHUAI::String::TSTRING_SPLIT_TO_VECTOR(splittedFileName, fileName, _T("\\"));
ZeroMemory(fileName, (MAX_PATH + 1) * sizeof(_TCHAR));
TSTRING exeName = splittedFileName.at(splittedFileName.size() - 1);
memcpy(fileName, exeName.c_str(), sizeof(_TCHAR) * exeName.length());
// make the control is not running inside Visual Studio Designer
//if (String.Compare(fileName, "devenv.exe", true) == 0 || String.Compare(fileName, "XDesProc.exe", true) == 0) {
// return;
//}
// Windows Internet Explorer 8 and later. The FEATURE_BROWSER_EMULATION feature defines the default emulation mode for Internet
// Explorer and supports the following values.
// Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode.
SetBrowserFeatureControlKey(_T("FEATURE_BROWSER_EMULATION"), fileName, emulationMode);
// Internet Explorer 8 or later. The FEATURE_AJAX_CONNECTIONEVENTS feature enables events that occur when the value of the online
// property of the navigator object changes, such as when the user chooses to work offline. For more information, see the ononline
// and onoffline events.
// Default: DISABLED
SetBrowserFeatureControlKey(_T("FEATURE_AJAX_CONNECTIONEVENTS"), fileName, 1);
// Internet Explorer 9. Internet Explorer 9 optimized the performance of window-drawing routines that involve clipping regions associated
// with child windows. This helped improve the performance of certain window drawing operations. However, certain applications hosting the
// WebBrowser Control rely on the previous behavior and do not function correctly when these optimizations are enabled. The
// FEATURE_ENABLE_CLIPCHILDREN_OPTIMIZATION feature can disable these optimizations.
// Default: ENABLED
// SetBrowserFeatureControlKey(_T("FEATURE_ENABLE_CLIPCHILDREN_OPTIMIZATION"), fileName, 1);
// Internet Explorer 8 and later. By default, Internet Explorer reduces memory leaks caused by circular references between Internet Explorer
// and the Microsoft JScript engine, especially in scenarios where a webpage defines an expando and the page is refreshed. If a legacy
// application no longer functions with these changes, the FEATURE_MANAGE_SCRIPT_CIRCULAR_REFS feature can disable these improvements.
// Default: ENABLED
// SetBrowserFeatureControlKey(_T("FEATURE_MANAGE_SCRIPT_CIRCULAR_REFS"), fileName, 1);
// Windows Internet Explorer 8. When enabled, the FEATURE_DOMSTORAGE feature allows Internet Explorer and applications hosting the WebBrowser
// Control to use the Web Storage API. For more information, see Introduction to Web Storage.
// Default: ENABLED
// SetBrowserFeatureControlKey(_T("FEATURE_DOMSTORAGE"), fileName, 1);
// Internet Explorer 9. The FEATURE_GPU_RENDERING feature enables Internet Explorer to use a graphics processing unit (GPU) to render content.
// This dramatically improves performance for webpages that are rich in graphics.
// Default: DISABLED
SetBrowserFeatureControlKey(_T("FEATURE_GPU_RENDERING"), fileName, 1);
// Internet Explorer 9. By default, the WebBrowser Control uses Microsoft DirectX to render webpages, which might cause problems for
// applications that use the Draw method to create bitmaps from certain webpages. In Internet Explorer 9, this method returns a bitmap
// (in a Windows Graphics Device Interface (GDI) wrapper) instead of a GDI metafile representation of the webpage. When the
// FEATURE_IVIEWOBJECTDRAW_DMLT9_WITH_GDI feature is enabled, the following conditions cause the Draw method to use GDI instead of DirectX
// to create the resulting representation. The GDI representation will contain text records and vector data, but is not guaranteed to be
// similar to the same represenation returned in earlier versions of the browser:
// The device context passed to the Draw method points to an enhanced metafile.
// The webpage is not displayed in IE9 Standards mode.
// By default, this feature is ENABLED for applications hosting the WebBrowser Control. This feature is ignored by Internet Explorer and
// Windows Explorer. To enable this feature by using the registry, add the name of your executable file to the following setting.
SetBrowserFeatureControlKey(_T("FEATURE_IVIEWOBJECTDRAW_DMLT9_WITH_GDI"), fileName, 0);
// Windows 8 introduces a new input model that is different from the Windows 7 input model. In order to provide the broadest compatibility
// for legacy applications, the WebBrowser Control for Windows 8 emulates the Windows 7 mouse, touch, and pen input model (also known as the
// legacy input model). When the legacy input model is in effect, the following conditions are true:
// Windows pointer messages are not processed by the Trident rendering engine (mshtml.dll).
// Document Object Model (DOM) pointer and gesture events do not fire.
// Mouse and touch messages are dispatched according to the Windows 7 input model.
// Touch selection follows the Windows 7 model ("drag to select") instead of the Windows 8 model ("tap to select").
// Hardware accelerated panning and zooming is disabled.
// The Zoom and Pan Cascading Style Sheets (CSS) properties are ignored.
// The FEATURE_NINPUT_LEGACYMODE feature control determines whether the legacy input model is enabled
// Default: ENABLED
SetBrowserFeatureControlKey(_T("FEATURE_NINPUT_LEGACYMODE"), fileName, 0);
// Internet Explorer 7 consolidated HTTP compression and data manipulation into a centralized component in order to improve performance and
// to provide greater consistency between transfer encodings (such as HTTP no-cache headers). For compatibility reasons, the original
// implementation was left in place. When the FEATURE_DISABLE_LEGACY_COMPRESSION feature is disabled, the original compression implementation
// is used.
// Default: ENABLED
// SetBrowserFeatureControlKey(_T("FEATURE_DISABLE_LEGACY_COMPRESSION"), fileName, 1);
// When the FEATURE_LOCALMACHINE_LOCKDOWN feature is enabled, Internet Explorer applies security restrictions on content loaded from the
// user's local machine, which helps prevent malicious behavior involving local files:
// Scripts, Microsoft ActiveX controls, and binary behaviors are not allowed to run.
// Object safety settings cannot be overridden.
// Cross-domain data actions require confirmation from the user.
// Default: DISABLED
// SetBrowserFeatureControlKey(_T("FEATURE_LOCALMACHINE_LOCKDOWN"), fileName, 0);
// Internet Explorer 7 and later. When enabled, the FEATURE_BLOCK_LMZ_??? feature allows ??? stored in the Local Machine zone to be
// loaded only by webpages loaded from the Local Machine zone or by webpages hosted by sites in the Trusted Sites list. For more information,
// see Security and Compatibility in Internet Explorer 7.
// Default: DISABLED
// FEATURE_BLOCK_LMZ_IMG can block images that try to load from the user's local file system. To opt in, add your process name and set
// the value to 0x00000001.
// FEATURE_BLOCK_LMZ_OBJECT can block objects that try to load from the user's local file system. To opt in, add your process name and
// set the value to 0x00000001.
// FEATURE_BLOCK_LMZ_SCRIPT can block script access from the user's local file system. To opt in, add your process name and set the value
// to 0x00000001.
// SetBrowserFeatureControlKey(_T("FEATURE_BLOCK_LMZ_OBJECT"), fileName, 0);
// SetBrowserFeatureControlKey(_T("FEATURE_BLOCK_LMZ_OBJECT"), fileName, 0);
// SetBrowserFeatureControlKey(_T("FEATURE_BLOCK_LMZ_SCRIPT"), fileName, 0);
// Internet Explorer 8 and later. When enabled, the FEATURE_DISABLE_NAVIGATION_SOUNDS feature disables the sounds played when you open a
// link in a webpage.
// Default: DISABLED
SetBrowserFeatureControlKey(_T("FEATURE_DISABLE_NAVIGATION_SOUNDS"), fileName, 1);
// Windows Internet Explorer 7 and later. Prior to Internet Explorer 7, href attributes of a objects supported the javascript prototcol;
// this allowed webpages to execute script when the user clicked a link. For security reasons, this support was disabled in Internet
// Explorer 7. For more information, see Event 1034 - Cross-Domain Barrier and Script URL Mitigation.
// When enabled, the FEATURE_SCRIPTURL_MITIGATION feature allows the href attribute of a objects to support the javascript prototcol.
// Default: DISABLED
SetBrowserFeatureControlKey(_T("FEATURE_SCRIPTURL_MITIGATION"), fileName, 1);
// For Windows 8 and later, the FEATURE_SPELLCHECKING feature controls this behavior for Internet Explorer and for applications hosting
// the web browser control (WebOC). When fully enabled, this feature automatically corrects grammar issues and identifies misspelled words
// for the conditions described earlier.
// (DWORD) 00000000 - Features are disabled.
// (DWORD) 00000001 - Features are enabled for the conditions described earlier. (This is the default value.)
// (DWORD) 00000002 - Features are enabled, but only for elements that specifically set the spellcheck attribute to true.
SetBrowserFeatureControlKey(_T("FEATURE_SPELLCHECKING"), fileName, 0);
// When enabled, the FEATURE_STATUS_BAR_THROTTLING feature limits the frequency of status bar updates to one update every 200 milliseconds.
// Default: DISABLED
SetBrowserFeatureControlKey(_T("FEATURE_STATUS_BAR_THROTTLING"), fileName, 1);
// Internet Explorer 7 or later. When enabled, the FEATURE_TABBED_BROWSING feature enables tabbed browsing navigation shortcuts and
// notifications. For more information, see Tabbed Browsing for Developers.
// Default: DISABLED
// SetBrowserFeatureControlKey(_T("FEATURE_TABBED_BROWSING"), fileName, 1);
// When enabled, the FEATURE_VALIDATE_NAVIGATE_URL feature control prevents Windows Internet Explorer from navigating to a badly formed URL.
// Default: DISABLED
SetBrowserFeatureControlKey(_T("FEATURE_VALIDATE_NAVIGATE_URL"), fileName, 1);
// When enabled,the FEATURE_WEBOC_DOCUMENT_ZOOM feature allows HTML dialog boxes to inherit the zoom state of the parent window.
// Default: DISABLED
SetBrowserFeatureControlKey(_T("FEATURE_WEBOC_DOCUMENT_ZOOM"), fileName, 1);
// The FEATURE_WEBOC_POPUPMANAGEMENT feature allows applications hosting the WebBrowser Control to receive the default Internet Explorer
// pop-up window management behavior.
// Default: ENABLED
SetBrowserFeatureControlKey(_T("FEATURE_WEBOC_POPUPMANAGEMENT"), fileName, 0);
// Applications hosting the WebBrowser Control should ensure that window resizing and movement events are handled appropriately for the
// needs of the application. By default, these events are ignored if the WebBrowser Control is not hosted in a proper container. When enabled,
// the FEATURE_WEBOC_MOVESIZECHILD feature allows these events to affect the parent window of the application hosting the WebBrowser Control.
// Because this can lead to unpredictable results, it is not considered desirable behavior.
// Default: DISABLED
// SetBrowserFeatureControlKey(_T("FEATURE_WEBOC_MOVESIZECHILD"), fileName, 0);
// The FEATURE_ADDON_MANAGEMENT feature enables applications hosting the WebBrowser Control
// to respect add-on management selections made using the Add-on Manager feature of Internet Explorer.
// Add-ons disabled by the user or by administrative group policy will also be disabled in applications that enable this feature.
SetBrowserFeatureControlKey(_T("FEATURE_ADDON_MANAGEMENT"), fileName, 0);
// Internet Explorer 10. When enabled, the FEATURE_WEBSOCKET feature allows script to create and use WebSocket objects.
// The WebSocketobject allows websites to request data across domains from your browser by using the WebSocket protocol.
// Default: ENABLED
SetBrowserFeatureControlKey(_T("FEATURE_WEBSOCKET"), fileName, 1);
// When enabled, the FEATURE_WINDOW_RESTRICTIONS feature adds several restrictions to the size and behavior of popup windows:
// Popup windows must appear in the visible display area.
// Popup windows are forced to have status and address bars.
// Popup windows must have minimum sizes.
// Popup windows cannot cover important areas of the parent window.
// When enabled, this feature can be configured differently for each security zone by using the URLACTION_FEATURE_WINDOW_RESTRICTIONS URL
// action flag.
// Default: ENABLED
SetBrowserFeatureControlKey(_T("FEATURE_WINDOW_RESTRICTIONS"), fileName, 0);
// Internet Explorer 7 and later. The FEATURE_XMLHTTP feature enables or disables the native XMLHttpRequest object.
// Default: ENABLED
// SetBrowserFeatureControlKey(_T("FEATURE_XMLHTTP"), fileName, 1);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
__inline static CThreadHelper * StartHttpServer(DWORD & dwHttpServPort, LPCSTR lpHttpServPath = ("."), INT nDelayMilliSeconds = 10000 , LPCSTR lpHttp404Pages = ("HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nNo data found!\r\n"))
{
#define THREAD_HTTP_SERV_PATH "THREAD_HTTP_SERV_PATH"
#define THREAD_HTTP_SERV_PORT "THREAD_HTTP_SERV_PORT"
#define THREAD_HTTP_404_ERROR "THREAD_HTTP_404_ERROR"
#define THREAD_HTTP_TIMEDELAY "THREAD_HTTP_TIMEDELAY"
static std::map<std::string, std::string> ssmap = {
{ (THREAD_HTTP_SERV_PATH), lpHttpServPath },
{ (THREAD_HTTP_SERV_PORT), STRING_FORMAT_A("%ld", (dwHttpServPort = GenerateRandom(10000, 60000))).c_str() }, //(rand() % ((60000 - 10000) + 1) + 10000);
};
putenv(std::string(std::string(THREAD_HTTP_404_ERROR) + "=" + lpHttp404Pages).c_str());
putenv(std::string(std::string(THREAD_HTTP_TIMEDELAY) + "=" + PPSHUAI::STRING_FORMAT_A(("%d"), nDelayMilliSeconds)).c_str());
static CThreadHelper threadhelper_httpserver((LPTHREAD_START_ROUTINE)[](LPVOID lpParams)->DWORD
{
CThreadHelper * pTH = (CThreadHelper *)lpParams;
std::map<std::string, std::string> * pSSMAP = (std::map<std::string, std::string> *)pTH->GetThreadParameters();
struct shttpd_ctx * ctx = 0;
char cRoots[USHRT_MAX] = { 0 };
char cPorts[8] = { 0 };
strcpy(cRoots, (PPSHUAI::Convert::TToA(PPSHUAI::FilePath::GetTempPath()) + pSSMAP->at(THREAD_HTTP_SERV_PATH)).c_str());
strcpy(cPorts, pSSMAP->at(THREAD_HTTP_SERV_PORT).c_str());
char *argv[] = { "",
"-root", cRoots,
"-ports", cPorts,
"-dir_list", "no",
"-index_files", "index.html,index.htm,index.php,index.cgi",
"-cgi_ext", "cgi,pl,php",
"-ssi_ext", "shtml,shtm", "-auth_realm", "mydomain.com",
"-systray", "no",
"-threads", "1",
NULL };
int argc = sizeof(argv) / sizeof(argv[0]) - 1;
if ((ctx = shttpd_init(argc, argv)) != NULL)
{
/////////////////////////////////////////////////////////////////
// This callback function is used to show how to handle 404 error
//
shttpd_handle_error(ctx, 404,
[](struct shttpd_arg *arg)->void
{
shttpd_printf(arg, "%s", getenv(THREAD_HTTP_404_ERROR));
arg->flags |= SHTTPD_END_OF_OUTPUT;
}, NULL);
while (pTH->IsThreadRunning())
{
shttpd_poll(ctx, atoi(getenv(THREAD_HTTP_TIMEDELAY)));
}
shttpd_fini(ctx);
ctx = 0;
}
return (EXIT_SUCCESS);
}, (LPVOID)&ssmap);
threadhelper_httpserver.Start();
return &threadhelper_httpserver;
}
__inline static void StopHttpServer(CThreadHelper * pTH)
{
pTH->Close();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////
// 全局宏定义声明区域
//////////////////////////////////////////////////////////////////////////
#define AX_WINDOWS_CONTAINER_NAME OLESTR("SHELL.EXPLORER.2")
//////////////////////////////////////////////////////////////////////////
// 全局变量声明区域
//////////////////////////////////////////////////////////////////////////
CComModule _Module; //使用CComDispatchDriver ATL的智能指针,此处必须声明
class CWebBrowser{
public:
CWebBrowser()
{
}
~CWebBrowser()
{
}
__inline static void ATL_INIT()
{
// 初始化
AtlAxWinInit();
}
__inline static void ATL_TERM()
{
// 释放
AtlAxWinTerm();
}
__inline HRESULT Create(HWND hParentWnd, LPRECT lpRect, LPCTSTR lpWindowName = _T(""), DWORD dwStyles = 0L, DWORD dwExStyles = 0L, HMENU hMenu = (0L), HINSTANCE hInstance = GetModuleHandle(NULL), LPVOID lpCreateParams = NULL)
{
HRESULT hResult = S_FALSE;
// 创建容器
m_hWnd = CreateWindowEx(dwExStyles, _T(ATLAXWIN_CLASS), lpWindowName, dwStyles, lpRect->left, lpRect->top, lpRect->right, lpRect->bottom, hParentWnd, hMenu, hInstance, lpCreateParams);
// 创建容器控件
hResult = CreateControlEx(m_hWnd, AX_WINDOWS_CONTAINER_NAME);
if (hResult != 0)
{
MessageBox(NULL, __TEXT("创建容器控件失败!"), __TEXT("错误"), MB_ICONERROR);
return hResult;
}
// 获取容器控件可用句柄
hResult = QueryControl(m_hWnd, __uuidof(IWebBrowser2), (LPVOID*)&m_IWebBrowser2);
if (hResult != 0)
{
MessageBox(NULL, __TEXT("获取容器控件可用句柄失败!"), __TEXT("错误"), MB_ICONERROR);
return hResult;
}
//m_IWebBrowser2->put_Silent(TRUE);
//DisplayWebpage(_T("http://localhost:8888/"));
return hResult;
}
__inline HRESULT SetWebBrowserProperty(DWORD dwFlags = (DOCHOSTUIFLAG_NO3DBORDER | DOCHOSTUIFLAG_ENABLE_FORMS_AUTOCOMPLETE | DOCHOSTUIFLAG_THEME | DOCHOSTUIFLAG_SCROLL_NO | DOCHOSTUIFLAG_DIALOG), VARIANT_BOOL bAllowContextMenu = VARIANT_FALSE)
{
CComPtr<IAxWinAmbientDispatch> axAmbientDispatch;
HRESULT hResult = QueryHost(m_hWnd, IID_IAxWinAmbientDispatch, (LPVOID*)&axAmbientDispatch);
if (SUCCEEDED(hResult))
{
//////////////////////////////////////////////////////////////////////////////////////////
//禁止右键菜单
axAmbientDispatch->put_AllowContextMenu(bAllowContextMenu);
//////////////////////////////////////////////////////////////////////////////////////////
//DOCHOSTUIFLAG_SCROLL_NO 没有滚动条
//DOCHOSTUIFLAG_DIALOG 像对话框一样,网页上的东西不可选择
//DOCHOSTUIFLAG_THEME XP风格
axAmbientDispatch->put_DocHostFlags(dwFlags);
axAmbientDispatch.Release();
}
return hResult;
}
__inline HRESULT GetWebBrowserProperty(DWORD & dwFlags, VARIANT_BOOL * pbAllowContextMenu = NULL)
{
CComPtr<IAxWinAmbientDispatch> axAmbientDispatch;
HRESULT hResult = QueryHost(m_hWnd, IID_IAxWinAmbientDispatch, (LPVOID*)&axAmbientDispatch);
if (SUCCEEDED(hResult))
{
if (pbAllowContextMenu)
{
//////////////////////////////////////////////////////////////////////////////////////////
//获取右键菜单可用状态
axAmbientDispatch->get_AllowContextMenu(pbAllowContextMenu);
}
//////////////////////////////////////////////////////////////////////////////////////////
//DOCHOSTUIFLAG_SCROLL_NO 没有滚动条
//DOCHOSTUIFLAG_DIALOG 像对话框一样,网页上的东西不可选择
//DOCHOSTUIFLAG_THEME XP风格
axAmbientDispatch->get_DocHostFlags(&dwFlags);
axAmbientDispatch.Release();
}
return hResult;
}
//显示网页
__inline HRESULT DisplayWebpage(LPCTSTR lpUrl)
{
HRESULT hResult = S_FALSE;
VARIANT l_varMyURL = { 0 };
VariantInit(&l_varMyURL);
l_varMyURL.vt = VT_BSTR;
l_varMyURL.bstrVal = SysAllocString(PPSHUAI::Convert::TToW(lpUrl).c_str());
if (l_varMyURL.bstrVal)
{
hResult = m_IWebBrowser2->Navigate2(&l_varMyURL, 0, 0, 0, 0);
SysFreeString(l_varMyURL.bstrVal);
}
hResult = VariantClear(&l_varMyURL);
return hResult;
}
__inline HWND GetHwnd()
{
return m_hWnd;
}
__inline CComPtr<IWebBrowser2> GetIWebBrowser2Ptr()
{
return m_IWebBrowser2;
}
private:
__inline HRESULT QueryHost(_In_ HWND hWnd,
_In_ REFIID iid,
_Outptr_ void** ppUnk)
{
ATLASSERT(ppUnk != NULL);
if (ppUnk == NULL)
return E_POINTER;
HRESULT hr;
*ppUnk = NULL;
CComPtr<IUnknown> spUnk;
hr = AtlAxGetHost(hWnd, &spUnk);
if (SUCCEEDED(hr))
hr = spUnk->QueryInterface(iid, ppUnk);
return hr;
}
template <class Q>
__inline HRESULT QueryHost(HWND hWnd, _Outptr_ Q** ppUnk)
{
return QueryHost(hWnd, __uuidof(Q), (void**)ppUnk);
}
__inline HRESULT QueryControl(
HWND hWnd,
_In_ REFIID iid,
_Outptr_ void** ppUnk)
{
ATLASSERT(ppUnk != NULL);
if (ppUnk == NULL)
return E_POINTER;
HRESULT hr;
*ppUnk = NULL;
CComPtr<IUnknown> spUnk;
hr = AtlAxGetControl(hWnd, &spUnk);
if (SUCCEEDED(hr))
hr = spUnk->QueryInterface(iid, ppUnk);
return hr;
}
template <class Q>
__inline HRESULT QueryControl(HWND hWnd, _Outptr_ Q** ppUnk)
{
return QueryControl(hWnd, __uuidof(Q), (void**)ppUnk);
}
__inline HRESULT SetExternalDispatch(HWND hWnd, _Inout_ IDispatch* pDisp)
{
HRESULT hr;
CComPtr<IAxWinHostWindow> spHost;
hr = QueryHost(hWnd, __uuidof(IAxWinHostWindow), (void**)&spHost);
if (SUCCEEDED(hr))
hr = spHost->SetExternalDispatch(pDisp);
return hr;
}
__inline HRESULT SetExternalUIHandler(HWND hWnd, _Inout_ IDocHostUIHandlerDispatch* pUIHandler)
{
HRESULT hr;
CComPtr<IAxWinHostWindow> spHost;
hr = QueryHost(hWnd, __uuidof(IAxWinHostWindow), (void**)&spHost);
if (SUCCEEDED(hr))
hr = spHost->SetExternalUIHandler(pUIHandler);
return hr;
}
__inline HRESULT CreateControlEx(
HWND hWnd,
_In_z_ LPCOLESTR lpszName,
_Inout_opt_ IStream* pStream = NULL,
_Outptr_opt_ IUnknown** ppUnkContainer = NULL,
_Outptr_opt_ IUnknown** ppUnkControl = NULL,
_In_ REFIID iidSink = IID_NULL,
_Inout_opt_ IUnknown* punkSink = NULL)
{
//ATLASSERT(::IsWindow(m_hWnd));
// We must have a valid window!
// Get a pointer to the container object connected to this window
CComPtr<IAxWinHostWindow> spWinHost;
HRESULT hr = QueryHost(hWnd, &spWinHost);
// If QueryHost failed, there is no host attached to this window
// We assume that the user wants to create a new host and subclass the current window
if (FAILED(hr))
return AtlAxCreateControlEx(lpszName, hWnd, pStream, ppUnkContainer, ppUnkControl, iidSink, punkSink);
// Create the control requested by the caller
CComPtr<IUnknown> pControl;
if (SUCCEEDED(hr))
hr = spWinHost->CreateControlEx(lpszName, hWnd, pStream, &pControl, iidSink, punkSink);
// Send back the necessary interface pointers
if (SUCCEEDED(hr))
{
if (ppUnkControl)
*ppUnkControl = pControl.Detach();
if (ppUnkContainer)
{
hr = spWinHost.QueryInterface(ppUnkContainer);
ATLASSERT(SUCCEEDED(hr)); // This should not fail!
}
}
return hr;
}
private:
HWND m_hWnd;//IWebBrowser2句柄
CComPtr<IWebBrowser2> m_IWebBrowser2;//IWebBrowser2句柄
};
}
}
#endif //#ifndef __WINDOWHEADER_H_
|
#include "../precomp.hpp"
#if defined(ENABLE_TORCH_IMPORTER) && ENABLE_TORCH_IMPORTER
#if defined(TH_DISABLE_HEAP_TRACKING)
#elif (defined(__unix) || defined(_WIN32))
#include <malloc.h>
#elif defined(__APPLE__)
#include <malloc/malloc.h>
#endif
#include "THGeneral.h"
#endif
|
/*
* This file is part of OctoMap - An Efficient Probabilistic 3D Mapping
* Framework Based on Octrees
* http://octomap.github.io
*
* Copyright (c) 2009-2014, K.M. Wurm and A. Hornung, University of Freiburg
* All rights reserved. License for the viewer octovis: GNU GPL v2
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt
*
*
* 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, see http://www.gnu.org/licenses/.
*/
#include <octovis/ViewerSettingsPanel.h>
ViewerSettingsPanel::ViewerSettingsPanel(QWidget *parent)
: QWidget(parent), m_currentScan(0), m_numberScans(0), m_treeDepth(_TREE_MAX_DEPTH), m_resolution(0.1)
{
ui.setupUi(this);
connect(ui.treeDepth, SIGNAL(valueChanged(int)), this, SLOT(setTreeDepth(int)));
scanProgressChanged();
leafSizeChanged();
}
ViewerSettingsPanel::~ViewerSettingsPanel()
{
}
void ViewerSettingsPanel::on_nextScanButton_clicked(){
if (m_currentScan < m_numberScans){
m_currentScan++;
scanProgressChanged();
emit addNextScans(1);
}
}
void ViewerSettingsPanel::on_fastFwdScanButton_clicked(){
unsigned increase = int(m_numberScans)-int(m_currentScan);
if (increase > 5) increase = 5;
m_currentScan += increase;
scanProgressChanged();
emit addNextScans(increase);
}
void ViewerSettingsPanel::on_lastScanButton_clicked(){
unsigned increase = int(m_numberScans)-int(m_currentScan);
m_currentScan += increase;
scanProgressChanged();
emit addNextScans(increase);
}
void ViewerSettingsPanel::on_firstScanButton_clicked(){
m_currentScan = 1;
scanProgressChanged();
emit gotoFirstScan();
}
void ViewerSettingsPanel::scanProgressChanged(){
if (int(m_numberScans) > 1)
ui.scanProgressBar->setMaximum(int(m_numberScans));
else
ui.scanProgressBar->setMaximum(1);
if (m_currentScan == m_numberScans){
ui.nextScanButton->setEnabled(false);
ui.fastFwdScanButton->setEnabled(false);
ui.lastScanButton->setEnabled(false);
} else{
ui.nextScanButton->setEnabled(true);
ui.fastFwdScanButton->setEnabled(true);
ui.lastScanButton->setEnabled(true);
}
if (m_currentScan < 2){
ui.firstScanButton->setEnabled(false);
} else{
ui.firstScanButton->setEnabled(true);
}
ui.scanProgressBar->setValue(m_currentScan);
// queue a redraw:
ui.scanProgressBar->update();
}
void ViewerSettingsPanel::setNumberOfScans(unsigned scans){
m_numberScans = scans;
scanProgressChanged();
}
void ViewerSettingsPanel::setCurrentScan(unsigned scan){
m_currentScan = scan;
scanProgressChanged();
}
void ViewerSettingsPanel::setResolution(double resolution){
m_resolution = resolution;
leafSizeChanged();
}
void ViewerSettingsPanel::setTreeDepth(int depth){
emit treeDepthChanged(depth);
m_treeDepth = depth;
ui.treeDepth->setValue(depth);
ui.treeDepthSlider->setValue(depth);
leafSizeChanged();
}
void ViewerSettingsPanel::leafSizeChanged(){
double leafSize = m_resolution * pow(2.0, (int) (_TREE_MAX_DEPTH-m_treeDepth));
ui.leafSize->setText(QString::number(leafSize)+" m");
}
|
#include <Servo.h>
#include <NewPing.h>
#include <SoftwareSerial.h>
Servo leftServo;
Servo rightServo;
Servo topServo; //mini servo for hc-04
#define TRIGGER_PIN 6
#define ECHO_PIN 7
#define MAX_DISTANCE 100 //max distance hc-04 will display
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
unsigned int time;
int triggerDistance = 20; //20 cm then it will turn if detected
int distance; //distance from hc-04
int pos; //position of hc-04
char command; //command from serial data to control movement
void setup() {
leftServo.attach(10); //next few lines instantiating servos
leftServo.write(92); //92 makes this servo stay still, not convential 90
rightServo.attach(9);
rightServo.write(91); //91 makes still servo stay still
topServo.attach(8);
topServo.write(90);
Serial.begin(9600);
Serial.println("Type Commands");
}
void loop() {
command = '0'; //make sure command is instantiated
if (Serial.available() > 0)
{
command = Serial.read();
switch(command) //apply serial data to commands for robot
{
case 'w':
moveForward();
delay(100);
Serial.println("Moving forward");
Serial.println("--------------");
break;
case 'a':
turnLeft();
delay(100);
Serial.println("Turning left");
Serial.println("--------------");
break;
case 's':
moveBackward();
delay(100);
Serial.println("Moving backward");
Serial.println("--------------");
break;
case 'd':
turnRight();
delay(100);
Serial.println("Turn right");
Serial.println("--------------");
break;
case '1':
while(true)
{
scan();
autoRun();
}
Serial.println("In auto mode");
Serial.println("--------------");
break;
case '0':
stopMoving();
delay(100);
default:
moveForward();
delay(100);
break;
}
}
}
void autoRun() //run autonomously with hc-04
{
moveForward();
for (pos = 50; pos < 140; pos += 5)
automatic(pos);
for (pos = 140; pos > 50; pos -= 5)
automatic(pos);
delay(1);
}
void scan() //hc-04 scan area to make sure distance is not less than trigger distance
{
time = sonar.ping();
distance = time / US_ROUNDTRIP_CM;
if (distance == 0) {
distance = 100;
}
}
void automatic(int pos) { //part of autoRun() to move hc-04 back and forth to detect obstructions
topServo.write(pos);
delay(40);
scan();
if (distance < triggerDistance) {
moveBackward();
delay(1000);
if (pos > 90){
turnRight();
delay (1000);
moveForward();
} else if (pos < 90) {
turnLeft();
delay(1000);
moveForward();
} else if (pos == 90) {
turnRight();
delay(1000);
moveForward();
} else {
moveForward();
}
}
}
void moveForward()
{
leftServo.write(180);
rightServo.write(0);
}
void moveBackward()
{
leftServo.write(0);
rightServo.write(180);
}
void turnRight()
{
leftServo.write(180);
rightServo.write(180);
}
void turnLeft()
{
leftServo.write(0);
rightServo.write(0);
}
void stopMoving()
{
leftServo.write(92);
rightServo.write(91);
}
|
// Created on: 1991-04-03
// Created by: Remi GILET
// Copyright (c) 1991-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _GccAna_Circ2dBisec_HeaderFile
#define _GccAna_Circ2dBisec_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Boolean.hxx>
#include <Standard_Integer.hxx>
#include <gp_Circ2d.hxx>
class GccInt_Bisec;
//! This class describes functions for building bisecting curves between two 2D circles.
//! A bisecting curve between two circles is a curve such
//! that each of its points is at the same distance from the
//! two circles. It can be an ellipse, hyperbola, circle or line,
//! depending on the relative position of the two circles.
//! The algorithm computes all the elementary curves which
//! are solutions. There is no solution if the two circles are coincident.
//! A Circ2dBisec object provides a framework for:
//! - defining the construction of the bisecting curves,
//! - implementing the construction algorithm, and consulting the result.
class GccAna_Circ2dBisec
{
public:
DEFINE_STANDARD_ALLOC
//! Constructs bisecting curves between the two circles Circ1 and Circ2.
Standard_EXPORT GccAna_Circ2dBisec(const gp_Circ2d& Circ1, const gp_Circ2d& Circ2);
//! This method returns True if the construction algorithm succeeded.
Standard_EXPORT Standard_Boolean IsDone() const;
//! This method returns the number of solutions.
//! Raises NotDone if the construction algorithm didn't succeed.
Standard_EXPORT Standard_Integer NbSolutions() const;
//! Returns the solution number Index
//! Raises OutOfRange exception if Index is greater than
//! the number of solutions.
//! It raises NotDone if the construction algorithm
//! didn't succeed.
Standard_EXPORT Handle(GccInt_Bisec) ThisSolution (const Standard_Integer Index) const;
protected:
private:
Standard_Boolean WellDone;
Standard_Integer NbrSol;
Standard_Integer intersection;
Standard_Boolean sameradius;
gp_Circ2d circle1;
gp_Circ2d circle2;
};
#endif // _GccAna_Circ2dBisec_HeaderFile
|
#include<iostream>
#include"execute.hpp"
#include"main_control.hpp"
#include"alu.hpp"
#include"myARMSim.h"
using namespace std;
extern inter_stage_buffer_EX_MEM B3;
extern inter_stage_buffer_ID_EX B2;
void execute()
{
string opcode=B2.opcode;
//cout<<"helllllllllllllllooooooooooin execute"<<endl;
//cout<<"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"<<opcode<<endl;
//cout<<instruction_word<<endl;
if(opcode=="0010111"||opcode=="0110111"||opcode=="1101111")
{
if(opcode=="1101111")
{
PCSRC=1;
cout<<"No operation in ALU"<<endl;
}
//return;
}
B3.RZ=ALU(B2.alu_cntrl_sgnl);
//cout<<"B3.RZ"<<B3.RZ<<endl;
B3.opcode=B2.opcode;
B3.func3=B2.func3;
B3.instruction_wrd=B2.inst_wrd;
B3.RB=B2.RB;
//cout<<"after control unit"<<B3.reg_write<<endl;
B3.reg_write=B2.reg_write;
B3.mem_Read=B2.mem_Read;
B3.mem_write=B2.mem_write;
B3.Rd_address=B2.iRd;
B3.PC=B2.PC;
}
|
#include <iostream>
#include <conio.h>
#include "list_relasi.h"
#include "list_child.h"
#include "list_parent.h"
#include "aplikasi.h"
using namespace std;
address_child PC = nil;
address_child Pcari;
infotype_child XC;
infotype_child x;
List_child LC;
address_parent PP = nil;
address_parent cariP;
infotype_parent XP;
infotype_parent xx;
List_parent LP;
address_relasi PR = nil;
List_relasi LR;
address_child caric;
address_parent carip;
void menupilihan()
{
createList(LR);
createList(LC);
createList(LP);
int pil;
do
{
cout<<"-----------TUBES ASD----------"<<endl;
cout<<"----JADWAL FILM DI BIOSKOP----"<<endl;
cout<<endl;
cout<<"(1.) Insert Bioskop "<<endl;
cout<<"(2.) Insert Jadwal Film "<<endl;
cout<<"(3.) Lihat Daftar Bioskop "<<endl;
cout<<"(4.) Lihat Daftar Film "<<endl;
cout<<"(5.) Search Bioskop"<<endl;
cout<<"(6.) Search Film"<<endl;
cout<<"(7.) Relasikan Bioskop <-> film"<<endl;
cout<<"(8.) Lihat Relasi "<<endl;
cout<<"(9.) Cari Relasi "<<endl;
cout<<"(10.) Putus Relasi "<<endl;
cout<<"(11.) Hapus Bioskop "<<endl;
cout<<"(12.) Hapus Film "<<endl;
cout<<"(13.) Sort Relasi "<<endl;
cout<<"(0.) EXIT "<<endl;
cout<<endl;
cout<<"Pilih : ";
cin>>pil;
switch(pil)
{
case 1:
insert_parent();
break;
case 2:
insert_child();
break;
case 3:
view_parent();
break;
case 4:
view_child();
break;
case 5:
search_parent();
break;
case 6:
search_child();
break;
case 7:
relasikan();
break;
case 8:
view_relasi();
break;
case 9:
search_relasi();
break;
case 10:
putus_relasi();
break;
case 11:
delete_parent();
break;
case 12:
delete_child();
break;
case 13:
sortrelasi(LR);
printInfo(LR);
break;
case 0:
cout<<"Terima Kasih"<<endl;
break;
default:
cout<<"wrong input"<<endl;
break;
}
cout<<"Press [ENTER] to continue.."<<endl;
getche();
system("cls");
cout<<endl;
}
while(pil != 0);
}
void insert_child()
{
stuff_child(&XC);
insertngurut(LC,XC);
}
void view_child()
{
printInfo(LC);
}
void insert_parent()
{
stuff_parent(&XP);
insertngurut(LP,XP);
}
void view_parent()
{
printInfo(LP);
}
void search_parent()
{
cout<<"Masukkan ID Bioskop: "<<endl;
cin>>xx.id;
printsatuan(LP,xx);
}
void search_child()
{
cout<<"Masukkan ID Film: :"<<endl;
cin>>x.id;
printsatuan(LC,x);
}
void relasikan()
{
cout<<"Merelasikan Bioskop dengan Film"<<endl;
cout<<"Masukkan ID Bioskop: ";
cin>>xx.id;
cout<<"Masukkan ID Film: :";
cin>>x.id;
carip = findElm(LP,xx);
caric = findElm(LC,x);
if(carip != nil && caric != nil)
{
PR = alokasi(carip,caric);
insertLast(LR,PR);
cout<<"ID Bioskop : "<<info(carip).id<<" dengan id Film : "<<info(caric).id<<" berhasil direlasikan "<<endl;
}
else
{
cout<<"ID Film / Bioskop Tidak Ditemukan!!"<<endl;
}
}
void view_relasi()
{
printInfo(LR);
}
void search_relasi()
{
cout<<"Masukkan ID Bioskop: "<<endl;
cin>>xx.id;
cout<<"Masukkan ID Film: :"<<endl;
cin>>x.id;
carip = findElm(LP,xx);
caric = findElm(LC,x);
if(carip != nil && caric != nil)
{
PR=searchrelasi(LR,carip,caric);
if(PR != nil)
{
cout<<"ID Bioskop: "<<info(carip).id<<" dengan ID Film : "<<info(caric).id<<" berelasi"<<endl;
}
else
{
cout<<"ID Bioskop: "<<info(carip).id<<" dengan ID Film : "<<info(caric).id<<" tidak berelasi"<<endl;
}
}
else
{
cout<<"ID Bioskop / Film Tidak Ditemukan"<<endl;
}
}
void putus_relasi()
{
cout<<"Masukkan ID Bioskop: "<<endl;
cin>>xx.id;
cout<<"Masukkan ID Film: :"<<endl;
cin>>x.id;
carip = findElm(LP,xx);
caric = findElm(LC,x);
if(carip != nil && caric != nil)
{
PR=searchrelasi(LR,carip,caric);
if(PR != nil)
{
cout<<"ID Bioskop: "<<info(carip).id<<" dengan ID Film : "<<info(caric).id<<" berelasi"<<endl;
deletebyrelasi(LR,PR);
deleterelasi(LR,PR);
cout<<"Relasi Berhasil Dihapus"<<endl;
}
else
{
cout<<"ID Bioskop: "<<info(carip).id<<" dengan ID Film : "<<info(caric).id<<" tidak berelasi"<<endl;
}
}
else
{
cout<<"ID Bioskop / Film Tidak Ditemukan"<<endl;
}
}
void delete_parent()
{
cout<<"Masukkan ID Bioskop: "<<endl;
cin>>xx.id;
carip = deletebyIDPARENT(LP,xx);
if(carip != nil)
{
cout<<"Bioskop ID : "<<info(carip).id<<" Berhasil dihapus "<<endl;
PR = searchrelasiparent(LR, carip);
dealokasi(carip);
if(PR != nil)
{
deletebyrelasi(LR,PR);
deleterelasi(LR,PR);
}
else
{
cout<<"List Tidak Berelasi"<<endl;
}
}
else
{
cout<<"ID Tidak Ditemukan"<<endl;
}
}
void delete_child()
{
cout<<"Masukkan ID Film: :"<<endl;
cin>>x.id;
caric = deletebyIDCHILD(LC,x);
if (caric != nil)
{
cout<<"Film ID : "<<info(caric).id<<" berhasil dihapus"<<endl;
PR = searchrelasichild(LR,caric);
dealokasi(caric);
if(PR != nil)
{
deletebyrelasi(LR,PR);
deleterelasi(LR,PR);
}
else
{
cout<<"List Tidak Berelasi"<<endl;
}
}
else
{
cout<<"ID Tidak Ditemukan"<<endl;
}
}
|
/** Copyright (c) 2018 Mozart Alexander Louis. All rights reserved. */
#ifndef __IVORY_HXX__
#define __IVORY_HXX__
/**
* Entity File for Ivory
*/
#define __IVORY_ENTITY_FILE__ "entities/llumas/ivory.plist"
/**
* Includes
*/
#include "entities/llumas/base_lluma.hxx"
class Ivory : public BaseLluma {
public:
/**
* Constructor.
*
* @param scene ~ Pointer to the active game layer.
* @param id ~ The id of the lluma to load.
* @param gesture ~ Pointer to the active swipe gesture pointer on the game scene.
* @param tmx_layer ~ The layer to set as a current layer for walls and traversal
*/
explicit Ivory(BaseGameScene* scene, SwipeGesture* gesture, const string& id, const string& tmx_layer);
/**
* Destructor
*/
~Ivory();
protected:
/**
* @link BaseLluma::generateStats();
*/
ValueMap generateStats(const string& id) override;
private:
/**
* __DISALLOW_COPY_AND_ASSIGN__
*/
__DISALLOW_COPY_AND_ASSIGN__(Ivory)
};
#endif // __IVORY_HXX__
|
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
int i,j,m,n,k=0,l;
int mo[100],no[100];
int **outar[100]={};
int **out;
char **in;
while(1)
{
cin>>n>>m;
if(m==0&&n==0)
break;
in=(char**)calloc(n,sizeof(char*));
out=(int**)calloc(n,sizeof(int*));
for(i=0;i<n;i++)
{ in[i]=(char*)calloc(m,sizeof(char));
out[i]=(int*)calloc(m,sizeof(int));
}
outar[k]=out;
mo[k]=m;
no[k]=n;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
cin>>in[i][j];
}
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{ if(in[i][j]!='*')
{
out[i][j]==0;
if(j-1>=0)
{
if(in[i][j-1]=='*')
out[i][j]++;
}
if(j+1<m)
{
if(in[i][j+1]=='*')
out[i][j]++;
}
if(i-1>=0)
{
if(in[i-1][j]=='*')
out[i][j]++;
if(j-1>=0)
{
if(in[i-1][j-1]=='*')
out[i][j]++;
}
if(j+1<m)
{
if(in[i-1][j+1]=='*')
out[i][j]++;
}
}
if(i+1<n)
{
if(in[i+1][j]=='*')
out[i][j]++;
if(j-1>=0)
{
if(in[i+1][j-1]=='*')
out[i][j]++;
}
if(j+1<m)
{
if(in[i+1][j+1]=='*')
out[i][j]++;
}
}
}
else
out[i][j]=-1;
}
}
k++;
}
for(l=0;l<k;l++)
{
cout<<"Field #"<<l+1<<":"<<"\n";
for(i=0;i<no[l];i++)
{
for(j=0;j<mo[l];j++)
{
if(outar[l][i][j]!=-1)
cout<<outar[l][i][j];
else
cout<<'*';
}
cout<<"\n";
}
if(l!=k-1)
cout<<"\n";
}
return 0;
}
|
#include "lock.h"
#include "RPCServer.hpp"
extern RPCServer *server;
LockService::LockService(uint64_t _MetaDataBaseAddress)
: MetaDataBaseAddress(_MetaDataBaseAddress){}
LockService::~LockService(){}
uint64_t LockService::WriteLock(uint16_t NodeID, uint64_t Address) {
int workerid = server->getIDbyTID();
uint16_t ID = __sync_fetch_and_add(&WriteID, 1ULL);
uint64_t key = (uint64_t)NodeID;
uint64_t LockAddress = MetaDataBaseAddress + Address;
key = key << 16;
key += ID;
key = key << 32;
while (true) {
if (__sync_bool_compare_and_swap((uint64_t *)LockAddress, 0ULL, key))
break;
//if (workerid == 0) {
server->RequestPoller(workerid);
//}
}
return key;
}
bool LockService::WriteUnlock(uint64_t key, uint16_t NodeID, uint64_t Address) {
uint64_t LockAddress = MetaDataBaseAddress + Address;
uint32_t *p = (uint32_t *)(LockAddress + 4);
*p = 0;
return true;
}
uint64_t LockService::ReadLock(uint16_t NodeID, uint64_t Address) {
uint64_t LockAddress = MetaDataBaseAddress + Address;
uint64_t preNumber = __sync_fetch_and_add((uint64_t*)LockAddress, 1ULL);
preNumber = preNumber >> 32;
if (preNumber == 0) {
return 1;
} else {
while (true) {
if (__sync_bool_compare_and_swap((uint32_t*)(LockAddress + 4), 0, 0))
break;
usleep(1);
}
}
return 1;
}
bool LockService::ReadUnlock(uint64_t key, uint16_t NodeID, uint64_t Address) {
uint64_t LockAddress = MetaDataBaseAddress + Address;
__sync_fetch_and_sub((uint64_t *)LockAddress, 1);
return true;
}
|
/****************************************************************************
** Meta object code from reading C++ file 'CSystemTrayIcon.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.3.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "StdAfx.h"
#include "../../CSystemTrayIcon.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'CSystemTrayIcon.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.3.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_CSystemTrayIcon_t {
QByteArrayData data[11];
char stringdata[135];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_CSystemTrayIcon_t, stringdata) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_CSystemTrayIcon_t qt_meta_stringdata_CSystemTrayIcon = {
{
QT_MOC_LITERAL(0, 0, 15),
QT_MOC_LITERAL(1, 16, 20),
QT_MOC_LITERAL(2, 37, 0),
QT_MOC_LITERAL(3, 38, 5),
QT_MOC_LITERAL(4, 44, 15),
QT_MOC_LITERAL(5, 60, 16),
QT_MOC_LITERAL(6, 77, 16),
QT_MOC_LITERAL(7, 94, 8),
QT_MOC_LITERAL(8, 103, 14),
QT_MOC_LITERAL(9, 118, 9),
QT_MOC_LITERAL(10, 128, 6)
},
"CSystemTrayIcon\0trayIconStateChanged\0"
"\0state\0quitApplication\0aboutApplication\0"
"hideOrShowWidget\0setState\0SMonitor::Type\0"
"setHidden\0hidden"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_CSystemTrayIcon[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
6, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
4, // signalCount
// signals: name, argc, parameters, tag, flags
1, 1, 44, 2, 0x06 /* Public */,
4, 0, 47, 2, 0x06 /* Public */,
5, 0, 48, 2, 0x06 /* Public */,
6, 0, 49, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
7, 1, 50, 2, 0x0a /* Public */,
9, 1, 53, 2, 0x0a /* Public */,
// signals: parameters
QMetaType::Void, QMetaType::Int, 3,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
// slots: parameters
QMetaType::Void, 0x80000000 | 8, 3,
QMetaType::Void, QMetaType::Bool, 10,
0 // eod
};
void CSystemTrayIcon::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
CSystemTrayIcon *_t = static_cast<CSystemTrayIcon *>(_o);
switch (_id) {
case 0: _t->trayIconStateChanged((*reinterpret_cast< int(*)>(_a[1]))); break;
case 1: _t->quitApplication(); break;
case 2: _t->aboutApplication(); break;
case 3: _t->hideOrShowWidget(); break;
case 4: _t->setState((*reinterpret_cast< SMonitor::Type(*)>(_a[1]))); break;
case 5: _t->setHidden((*reinterpret_cast< bool(*)>(_a[1]))); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
void **func = reinterpret_cast<void **>(_a[1]);
{
typedef void (CSystemTrayIcon::*_t)(int );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&CSystemTrayIcon::trayIconStateChanged)) {
*result = 0;
}
}
{
typedef void (CSystemTrayIcon::*_t)();
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&CSystemTrayIcon::quitApplication)) {
*result = 1;
}
}
{
typedef void (CSystemTrayIcon::*_t)();
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&CSystemTrayIcon::aboutApplication)) {
*result = 2;
}
}
{
typedef void (CSystemTrayIcon::*_t)();
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&CSystemTrayIcon::hideOrShowWidget)) {
*result = 3;
}
}
}
}
const QMetaObject CSystemTrayIcon::staticMetaObject = {
{ &QSystemTrayIcon::staticMetaObject, qt_meta_stringdata_CSystemTrayIcon.data,
qt_meta_data_CSystemTrayIcon, qt_static_metacall, 0, 0}
};
const QMetaObject *CSystemTrayIcon::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *CSystemTrayIcon::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_CSystemTrayIcon.stringdata))
return static_cast<void*>(const_cast< CSystemTrayIcon*>(this));
return QSystemTrayIcon::qt_metacast(_clname);
}
int CSystemTrayIcon::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QSystemTrayIcon::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 6)
qt_static_metacall(this, _c, _id, _a);
_id -= 6;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 6)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 6;
}
return _id;
}
// SIGNAL 0
void CSystemTrayIcon::trayIconStateChanged(int _t1)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
// SIGNAL 1
void CSystemTrayIcon::quitApplication()
{
QMetaObject::activate(this, &staticMetaObject, 1, 0);
}
// SIGNAL 2
void CSystemTrayIcon::aboutApplication()
{
QMetaObject::activate(this, &staticMetaObject, 2, 0);
}
// SIGNAL 3
void CSystemTrayIcon::hideOrShowWidget()
{
QMetaObject::activate(this, &staticMetaObject, 3, 0);
}
QT_END_MOC_NAMESPACE
|
/*
* Copyright (c) 2016, The Regents of the University of California (Regents).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Please contact the author(s) of this library if you have any questions.
* Author: Erik Nelson ( eanelson@eecs.berkeley.edu )
*/
#include <lens/lens.h>
#include <shading/material_handler.h>
#include <iostream>
Lens::Lens()
: r1_(0.0),
r2_(0.0),
t_(0.0),
w_(0.0),
n_(0.0),
lens_index_size_(0),
outline_index_size_(0) {
// Initialize position and orientation to zero.
position_ = glm::vec3(0.f);
orientation_ = glm::vec3(0.f);
}
Lens::~Lens() {
// Free buffer objects.
GLuint buffers[4] = {vertex_buffer_object_,
normal_buffer_object_,
lens_index_buffer_object_,
outline_index_buffer_object_};
glDeleteBuffers(4, buffers);
}
void Lens::Initialize() {
// Initialize buffer objects.
GLuint buffers[4];
glGenBuffers(4, buffers);
vertex_buffer_object_ = buffers[0];
normal_buffer_object_ = buffers[1];
lens_index_buffer_object_ = buffers[2];
outline_index_buffer_object_ = buffers[3];
}
double Lens::GetRadius1() const {
return r1_;
}
double Lens::GetRadius2() const {
return r2_;
}
double Lens::GetThickness() const {
return t_;
}
double Lens::GetWidth() const {
return w_;
}
double Lens::GetIndexOfRefraction() const {
return n_;
}
const glm::vec3& Lens::GetPosition() const {
return position_;
}
double Lens::GetX() const {
return position_.x;
}
double Lens::GetY() const {
return position_.y;
}
double Lens::GetZ() const {
return position_.z;
}
const glm::vec3& Lens::GetOrientation() const {
return orientation_;
}
double Lens::GetRoll() const {
return orientation_.x;
}
double Lens::GetPitch() const {
return orientation_.y;
}
double Lens::GetYaw() const {
return orientation_.z;
}
void Lens::SetRadius1(double r1) {
r1_ = r1;
}
void Lens::SetRadius2(double r2) {
r2_ = r2;
}
void Lens::SetThickness(double t) {
t_ = t;
}
void Lens::SetWidth(double w) {
w_ = w;
}
void Lens::SetIndexOfRefraction(double n) {
n_ = n;
}
void Lens::SetX(double x) {
position_.x = x;
}
void Lens::SetY(double y) {
position_.y = y;
}
void Lens::SetZ(double z) {
position_.z = z;
}
void Lens::SetRoll(double roll) {
orientation_.x = roll;
}
void Lens::SetPitch(double pitch) {
orientation_.y = pitch;
}
void Lens::SetYaw(double yaw) {
orientation_.z = yaw;
}
void Lens::MakeBufferObjects() {
// Vertex, normal, and index containers.
std::vector<GLfloat> vertices;
std::vector<GLfloat> normals;
std::vector<GLuint> indices;
std::vector<GLuint> cylinder_indices1, cylinder_indices2;
// Create the lens geometry.
PopulateLensBufferObjects(true /*1st lens*/, &vertices, &normals,
&indices, &cylinder_indices1);
PopulateLensBufferObjects(false /*2nd lens*/, &vertices, &normals,
&indices, &cylinder_indices2);
PopulateCylinderBufferObject(cylinder_indices1, cylinder_indices2, &indices);
// Pack vertex data into a buffer object.
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_object_);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(GLfloat),
&vertices.front(), GL_STATIC_DRAW);
// Pack normal data into a buffer object.
glBindBuffer(GL_ARRAY_BUFFER, normal_buffer_object_);
glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(GLfloat),
&normals.front(), GL_STATIC_DRAW);
// Pack lens index data into a buffer object.
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, lens_index_buffer_object_);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint),
&indices.front(), GL_STATIC_DRAW);
lens_index_size_ = indices.size() * sizeof(GLuint);
// Create a buffer containing the lens outline.
std::vector<GLuint> outline_indices;
for (size_t ii = 0; ii < cylinder_indices1.size() - 1; ++ii) {
outline_indices.push_back(cylinder_indices1[ii]);
outline_indices.push_back(cylinder_indices1[ii+1]);
}
outline_indices.push_back(cylinder_indices1.back());
outline_indices.push_back(cylinder_indices1.front());
for (size_t ii = 0; ii < cylinder_indices2.size() - 1; ++ii) {
outline_indices.push_back(cylinder_indices2[ii]);
outline_indices.push_back(cylinder_indices2[ii+1]);
}
outline_indices.push_back(cylinder_indices2.back());
outline_indices.push_back(cylinder_indices2.front());
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, outline_index_buffer_object_);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, outline_indices.size() * sizeof(GLuint),
&outline_indices.front(), GL_STATIC_DRAW);
outline_index_size_ = outline_indices.size() * sizeof(GLuint);
}
bool Lens::PopulateLensBufferObjects(bool lens1, std::vector<GLfloat>* vertices,
std::vector<GLfloat>* normals,
std::vector<GLuint>* lens_indices,
std::vector<GLuint>* cylinder_indices) {
if (!vertices || !normals || !lens_indices || !cylinder_indices) {
std::cout << "At least one input container is a null pointer." << std::endl;
return false;
}
// The lens surface is made of rings of varying vertical angle.
// We will put all of the vertex and normal data into 'vertices' and
// 'normals', but will also store indices in 'lens_rings' to determine how
// vertices are connected into faces that we can render.
std::vector<Ring> lens_rings;
const double radius = lens1 ? r1_ : r2_;
const double sign = lens1 ? 1.0 : -1.0;
// Figure out how many rings we need for the this surface.
double alpha = 0.0;
if (std::isinf(radius)) {
alpha = 0.5 * M_PI - std::acos(0.5 * w_);
} else {
alpha = 0.5 * M_PI - std::acos(0.5 * w_ / std::abs(radius));
}
const unsigned int n_rings = std::floor(alpha / vertical_increment_);
// Store vertical angles to iterate over.
std::vector<double> v_angles, h_angles;
for (unsigned int ii = 0; ii < n_rings; ++ii)
v_angles.push_back(vertical_increment_ * static_cast<double>(ii));
v_angles.push_back(alpha);
for (unsigned int ii = 0; ii < 2.0 * M_PI / horizontal_increment_; ++ii)
h_angles.push_back(horizontal_increment_ * static_cast<double>(ii));
// Set an offset for vertex z position.
const double offset = 0.5 * t_;
// Check for lens feasibility.
if (w_ > 2.0 * std::abs(radius)) {
std::cout << "Lens parameters generate an infeasible lens." << std::endl;
return false;
}
// The first vertex (at the top or bottom of the lens) can be handled
// separately.
const int first_index = vertices->size() / 3;
int index_counter = first_index;
vertices->push_back(position_.x);
vertices->push_back(position_.y);
vertices->push_back(sign * offset + position_.z);
normals->push_back(0.0);
normals->push_back(0.0);
normals->push_back(sign);
index_counter++;
// Iterate around the surface of the first lens vertically from the top out.
for (size_t ii = 1; ii < v_angles.size(); ++ii) {
double va = v_angles[ii];
// Iterate around the surface horizontally, storing vertices in a ring.
Ring ring;
for (size_t jj = 0; jj < h_angles.size(); ++jj) {
const double ha = h_angles[jj];
// Handle lenses with infinite radius separately.
Vertex v;
if (std::isinf(radius)) {
const double r = std::sin(va);
v.x = r * std::cos(ha);
v.y = r * std::sin(ha);
v.z = 0.0;
} else {
v = SphericalToCartesian(radius, va, ha);
v.z *= sign;
}
// Rotate the vertex to the desired orientation.
// TODO
// Store the vertex's normal before translating it.
if (std::isinf(radius)) {
normals->push_back(0.0);
normals->push_back(0.0);
normals->push_back(sign);
} else {
const double norm = sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
const double flip = radius < 0.0 ? -1.0 : 1.0;
normals->push_back(flip * v.x / norm);
normals->push_back(flip * v.y / norm);
normals->push_back(flip * v.z / norm);
}
// Translate the vertex to the desired position.
v.z += sign * offset;
if (!std::isinf(radius))
v.z -= sign * radius;
v.x += position_.x;
v.y += position_.y;
v.z += position_.z;
// Store the vertex and normal.
vertices->push_back(v.x);
vertices->push_back(v.y);
vertices->push_back(v.z);
// If this is the outside ring, store indices to draw the cylinder
// connecting the two lens faces.
if (ii == v_angles.size() - 1) {
cylinder_indices->push_back(index_counter);
}
// Store the index of this vertex/normal pair.
ring.push_back(index_counter++);
}
lens_rings.push_back(ring);
}
// Now figure out how to connect lens vertices into triangles.
// The very top vertices on the lens can be handled separately since they are
// connected by a single vertex.
if (lens_rings.size() != 0) {
for (size_t ii = 0; ii < lens_rings[0].size() - 1; ++ii) {
lens_indices->push_back(first_index);
lens_indices->push_back(lens_rings[0][ii]);
lens_indices->push_back(lens_rings[0][ii + 1]);
}
lens_indices->push_back(first_index);
lens_indices->push_back(lens_rings[0].back());
lens_indices->push_back(lens_rings[0].front());
}
// Connect vertices on the lens that are not a part of the very top circle.
for (int ii = 0; ii < static_cast<int>(lens_rings.size()) - 1; ++ii) {
Ring inner_ring = lens_rings[ii];
Ring outer_ring = lens_rings[ii + 1];
for (int jj = 0; jj < static_cast<int>(inner_ring.size()) - 1; ++jj) {
// Each set of 4 vertices (inner, outer, inner+1, outer+1) gives 2 faces.
lens_indices->push_back(inner_ring[jj]);
lens_indices->push_back(outer_ring[jj]);
lens_indices->push_back(outer_ring[jj + 1]);
lens_indices->push_back(inner_ring[jj]);
lens_indices->push_back(outer_ring[jj + 1]);
lens_indices->push_back(inner_ring[jj + 1]);
}
// Handle the wrap around vertices.
lens_indices->push_back(inner_ring.back());
lens_indices->push_back(outer_ring.back());
lens_indices->push_back(outer_ring.front());
lens_indices->push_back(inner_ring.back());
lens_indices->push_back(outer_ring.front());
lens_indices->push_back(inner_ring.front());
}
return true;
}
bool Lens::PopulateCylinderBufferObject(
const std::vector<GLuint>& cylinder_indices1,
const std::vector<GLuint>& cylinder_indices2,
std::vector<GLuint>* indices) {
if (!indices) {
std::cout << "Index container is a null pointer." << std::endl;
return false;
}
for (size_t ii = 0; ii < cylinder_indices1.size() - 1; ++ii) {
indices->push_back(cylinder_indices1[ii]);
indices->push_back(cylinder_indices1[ii + 1]);
indices->push_back(cylinder_indices2[ii]);
indices->push_back(cylinder_indices1[ii + 1]);
indices->push_back(cylinder_indices2[ii + 1]);
indices->push_back(cylinder_indices2[ii]);
}
indices->push_back(cylinder_indices1.back());
indices->push_back(cylinder_indices1.front());
indices->push_back(cylinder_indices2.back());
indices->push_back(cylinder_indices1.front());
indices->push_back(cylinder_indices2.front());
indices->push_back(cylinder_indices2.back());
return true;
}
void Lens::Render() const {
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_object_);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, normal_buffer_object_);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, NULL);
// Set material properties to opaque black with no phong shading.
MaterialHandler::Instance()->SetAmbient(0.0, 0.0, 0.0);
MaterialHandler::Instance()->SetDiffuse(1.0, 1.0, 1.0);
MaterialHandler::Instance()->SetSpecular(1.0, 1.0, 1.0);
MaterialHandler::Instance()->SetAlpha(1.0);
MaterialHandler::Instance()->SetPhongShading(false);
// Draw lens outline.
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, outline_index_buffer_object_);
glDrawElements(GL_LINES, outline_index_size_, GL_UNSIGNED_INT, 0);
// Set material properties to transparent light blue with phong shading.
MaterialHandler::Instance()->SetAmbient(0.0, 0.1, 0.3);
MaterialHandler::Instance()->SetDiffuse(0.0, 0.2, 0.7);
MaterialHandler::Instance()->SetSpecular(0.0, 0.0, 0.0);
MaterialHandler::Instance()->SetAlpha(0.5);
MaterialHandler::Instance()->SetPhongShading(true);
// Draw lens geometry.
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, lens_index_buffer_object_);
glDrawElements(GL_TRIANGLES, lens_index_size_, GL_UNSIGNED_INT, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
}
void Lens::Print(const std::string& prefix) const {
if (!prefix.empty())
std::cout << prefix << std::endl;
std::cout << "r1: " << r1_ << std::endl
<< "r2: " << r2_ << std::endl
<< "t: " << t_ << std::endl
<< "w: " << w_ << std::endl
<< "n: " << n_ << std::endl
<< "position: ("
<< position_.x << ", "
<< position_.y << ", "
<< position_.z << ")" << std::endl
<< "orientation: ("
<< orientation_.x << ", "
<< orientation_.y << ", "
<< orientation_.z << ")" << std::endl << std::endl;
}
Lens::Vertex Lens::SphericalToCartesian(double radius, double vertical_angle,
double horizontal_angle) {
Vertex vertex;
vertex.x = std::abs(radius) * sin(vertical_angle) * cos(horizontal_angle);
vertex.y = std::abs(radius) * sin(vertical_angle) * sin(horizontal_angle);
vertex.z = radius * cos(vertical_angle);
return vertex;
}
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "AttributeSet.h"
#include "CSAttributeSet.generated.h"
/**
*
*/
UCLASS()
class UE4COOP_API UCSAttributeSet : public UAttributeSet
{
GENERATED_BODY()
public:
UCSAttributeSet();
UPROPERTY(Category = "Character Attributes", EditAnywhere, BlueprintReadWrite)
FGameplayAttributeData Health;
UPROPERTY(Category = "Character Attributes", EditAnywhere, BlueprintReadWrite)
FGameplayAttributeData MaxHealth;
public:
virtual void PreAttributeBaseChange(const FGameplayAttribute& Attribute, float& NewValue) const override;
virtual void PostGameplayEffectExecute(const struct FGameplayEffectModCallbackData &Data) override;
static FGameplayAttribute HealthAttribute();
};
|
/**
* @file matmul.cc
* @author Gerbrand De Laender
* @date 24/01/2020
* @version 1.0
*
* @brief E091103, Master thesis, HLS testing
*
* @section DESCRIPTION
*
* Matrix multiplication.
*
*/
#include <hls_stream.h>
#include <ap_axi_sdata.h>
#include "matmul.h"
#include "stream.h"
#define MAT_DIM 32
#define MAT_SIZE (MAT_DIM * MAT_DIM)
typedef float T;
typedef ap_axiu<8 * sizeof(T), 1, 1, 1> T_SIDE;
void matmul_(hls::stream<T_SIDE> &in_stream, hls::stream<T_SIDE> &out_stream, T a[MAT_DIM][MAT_DIM])
{
#pragma HLS DATAFLOW
T b[MAT_DIM][MAT_DIM];
T c[MAT_DIM][MAT_DIM];
stream_in_matrix_column_wise<T, T_SIDE, MAT_DIM>(b, in_stream);
matmul_hw<T, MAT_DIM>(a, b, c);
stream_out_matrix_column_wise<T, T_SIDE, MAT_DIM>(c, out_stream);
}
void matmul(hls::stream<T_SIDE> &in_stream, hls::stream<T_SIDE> &out_stream)
{
#pragma HLS INTERFACE s_axilite port=return
#pragma HLS INTERFACE axis port=in_stream
#pragma HLS INTERFACE axis port=out_stream
T a[MAT_DIM][MAT_DIM];
stream_in_matrix_row_wise<T, T_SIDE, MAT_DIM>(a, in_stream);
matmul_(in_stream, out_stream, a);
}
|
#include "rvlight.h"
RVLight::RVLight(QVector3D position, QColor ambient, QColor diffuse, QColor specular):
m_position(position), m_ambient(ambient), m_diffuse(diffuse), m_specular(specular)
{
}
QVector3D RVLight::position() const
{
return m_position;
}
void RVLight::setPosition(const QVector3D &position)
{
m_position = position;
}
QColor RVLight::ambient() const
{
return m_ambient;
}
void RVLight::setAmbient(const QColor &ambient)
{
m_ambient = ambient;
}
QColor RVLight::diffuse() const
{
return m_diffuse;
}
void RVLight::setDiffuse(const QColor &diffuse)
{
m_diffuse = diffuse;
}
QColor RVLight::specular() const
{
return m_specular;
}
void RVLight::setSpecular(const QColor &specular)
{
m_specular = specular;
}
|
/*
UTF-8 managing tools.
2013, Tivins <https://github.com/tivins>
*/
#include "unicode.h"
#include <cstdlib>
namespace v {
/**
* @brief Gets the char length in bytes.
* byte must be the first char of an ASCII or UTF-8 sequence.
*/
int utf8_char_len(char byte) {
unsigned char uc = (unsigned char) byte ;
if (uc < 0x80) { return 1 ; } // ascii char
else if (uc >= 0x80 && uc <= 0xBF) { return 0 ; } // continuation byte
else if (uc == 0xC0 || uc == 0xC1) { return 0 ; } // overlong encoding of an ASCII byte
else if (uc >= 0xC2 && uc <= 0xDF) { return 2 ; }
else if (uc >= 0xE0 && uc <= 0xEF) { return 3 ; } // if [0]=E0, [1]=A0..BF & if [0]=ED, [1]=80..9F
else if (uc >= 0xF0 && uc <= 0xF4) { return 4 ; } // if [0]=F0, [1]=90..BF & if [0]=F4, [1]=80..8F
else { return 0 ; } // u >= 0xF5 : Restricted.
}
/**
* @brief Gets the UTF-8 codepoint for the char.
* @param buffer (in) The buffer (eg: ptr + idx)
* @param size (in) Number of bytes to read (depends of char_len)
* @param codepoint (out) The codepoint of the utf8 char.
* @return 1 on success, 0 on failure.
*/
int utf8_build_char(const char *buffer, int size, int32_t *codepoint) {
int it ;
int32_t value = 0;
unsigned char uc = (unsigned char)buffer[0];
if (size == 2) { value = uc & 0x1F; }
else if (size == 3) { value = uc & 0xF; }
else if (size == 4) { value = uc & 0x7; }
else return 0;
for (it = 1; it < size; it++) {
uc = (unsigned char)buffer[it] ;
if (uc < 0x80 || uc > 0xBF) { return 0 ; } // not a continuation byte
value = (value << 6) + (uc & 0x3F) ;
}
// not in Unicode range
if (value > 0x10FFFF) { return 0 ; }
// invalid code point (UTF-16 surrogate halves)
else if (0xD800 <= value && value <= 0xDFFF) { return 0 ; }
// check overlong encoding
else if((size == 2 && value < 0x80) ||
(size == 3 && value < 0x800) ||
(size == 4 && value < 0x10000)) { return 0 ; }
if (codepoint)
*codepoint = value;
return 1;
}
} // namespace
|
// Created on: 1995-12-08
// Created by: Jacques GOUSSARD
// Copyright (c) 1995-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _BRepCheck_Analyzer_HeaderFile
#define _BRepCheck_Analyzer_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <TopoDS_Shape.hxx>
#include <BRepCheck_IndexedDataMapOfShapeResult.hxx>
#include <TopAbs_ShapeEnum.hxx>
class BRepCheck_Result;
//! A framework to check the overall
//! validity of a shape. For a shape to be valid in Open
//! CASCADE, it - or its component subshapes - must respect certain
//! criteria. These criteria are checked by the function IsValid.
//! Once you have determined whether a shape is valid or not, you can
//! diagnose its specific anomalies and correct them using the services of
//! the ShapeAnalysis, ShapeUpgrade, and ShapeFix packages.
class BRepCheck_Analyzer
{
public:
DEFINE_STANDARD_ALLOC
//! Constructs a shape validation object defined by the shape S.
//! <S> is the shape to control. <GeomControls> If
//! False only topological informaions are checked.
//! The geometricals controls are
//! For a Vertex :
//! BRepCheck_InvalidToleranceValue NYI
//! For an Edge :
//! BRepCheck_InvalidCurveOnClosedSurface,
//! BRepCheck_InvalidCurveOnSurface,
//! BRepCheck_InvalidSameParameterFlag,
//! BRepCheck_InvalidToleranceValue NYI
//! For a face :
//! BRepCheck_UnorientableShape,
//! BRepCheck_IntersectingWires,
//! BRepCheck_InvalidToleranceValue NYI
//! For a wire :
//! BRepCheck_SelfIntersectingWire
BRepCheck_Analyzer (const TopoDS_Shape& S,
const Standard_Boolean GeomControls = Standard_True,
const Standard_Boolean theIsParallel = Standard_False,
const Standard_Boolean theIsExact = Standard_False)
: myIsParallel(theIsParallel),
myIsExact(theIsExact)
{
Init (S, GeomControls);
}
//! <S> is the shape to control. <GeomControls> If
//! False only topological informaions are checked.
//! The geometricals controls are
//! For a Vertex :
//! BRepCheck_InvalidTolerance NYI
//! For an Edge :
//! BRepCheck_InvalidCurveOnClosedSurface,
//! BRepCheck_InvalidCurveOnSurface,
//! BRepCheck_InvalidSameParameterFlag,
//! BRepCheck_InvalidTolerance NYI
//! For a face :
//! BRepCheck_UnorientableShape,
//! BRepCheck_IntersectingWires,
//! BRepCheck_InvalidTolerance NYI
//! For a wire :
//! BRepCheck_SelfIntersectingWire
Standard_EXPORT void Init (const TopoDS_Shape& S,
const Standard_Boolean GeomControls = Standard_True);
//! Sets method to calculate distance: Calculating in finite number of points (if theIsExact
//! is false, faster, but possible not correct result) or exact calculating by using
//! BRepLib_CheckCurveOnSurface class (if theIsExact is true, slowly, but more correctly).
//! Exact method is used only when edge is SameParameter.
//! Default method is calculating in finite number of points
void SetExactMethod(const Standard_Boolean theIsExact)
{
myIsExact = theIsExact;
}
//! Returns true if exact method selected
Standard_Boolean IsExactMethod()
{
return myIsExact;
}
//! Sets parallel flag
void SetParallel(const Standard_Boolean theIsParallel)
{
myIsParallel = theIsParallel;
}
//! Returns true if parallel flag is set
Standard_Boolean IsParallel()
{
return myIsParallel;
}
//! <S> is a subshape of the original shape. Returns
//! <STandard_True> if no default has been detected on
//! <S> and any of its subshape.
Standard_EXPORT Standard_Boolean IsValid (const TopoDS_Shape& S) const;
//! Returns true if no defect is
//! detected on the shape S or any of its subshapes.
//! Returns true if the shape S is valid.
//! This function checks whether a given shape is valid by checking that:
//! - the topology is correct
//! - parameterization of edges in particular is correct.
//! For the topology to be correct, the following conditions must be satisfied:
//! - edges should have at least two vertices if they are not
//! degenerate edges. The vertices should be within the range of
//! the bounding edges at the tolerance specified in the vertex,
//! - edges should share at least one face. The representation of
//! the edges should be within the tolerance criterion assigned to them.
//! - wires defining a face should not self-intersect and should be closed,
//! - there should be one wire which contains all other wires inside a face,
//! - wires should be correctly oriented with respect to each of the edges,
//! - faces should be correctly oriented, in particular with
//! respect to adjacent faces if these faces define a solid,
//! - shells defining a solid should be closed. There should
//! be one enclosing shell if the shape is a solid;
//! To check parameterization of edge, there are 2 approaches depending on
//! the edge?s contextual situation.
//! - if the edge is either single, or it is in the context
//! of a wire or a compound, its parameterization is defined by
//! the parameterization of its 3D curve and is considered as valid.
//! - If the edge is in the context of a face, it should
//! have SameParameter and SameRange flags set to Standard_True. To
//! check these flags, you should call the function
//! BRep_Tool::SameParameter and BRep_Tool::SameRange for an
//! edge. If at least one of these flags is set to Standard_False,
//! the edge is considered as invalid without any additional check.
//! If the edge is contained by a face, and it has SameParameter and
//! SameRange flags set to Standard_True, IsValid checks
//! whether representation of the edge on face, in context of which the
//! edge is considered, has the same parameterization up to the
//! tolerance value coded on the edge. For a given parameter t on the edge
//! having C as a 3D curve and one PCurve P on a surface S (base
//! surface of the reference face), this checks that |C(t) - S(P(t))|
//! is less than or equal to tolerance, where tolerance is the tolerance
//! value coded on the edge.
Standard_Boolean IsValid() const
{
return IsValid (myShape);
}
const Handle(BRepCheck_Result)& Result (const TopoDS_Shape& theSubS) const
{
return myMap.FindFromKey (theSubS);
}
private:
Standard_EXPORT void Put (const TopoDS_Shape& S,
const Standard_Boolean Gctrl);
Standard_EXPORT void Perform();
Standard_EXPORT Standard_Boolean ValidSub (const TopoDS_Shape& S, const TopAbs_ShapeEnum SubType) const;
private:
TopoDS_Shape myShape;
BRepCheck_IndexedDataMapOfShapeResult myMap;
Standard_Boolean myIsParallel;
Standard_Boolean myIsExact;
};
#endif // _BRepCheck_Analyzer_HeaderFile
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2009 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
/**
* @file OpSecurityInfoParser.h
**/
#ifndef OPSECURITY_INFO_PARSER_H
# define OPSECURITY_INFO_PARSER_H
# ifdef SECURITY_INFORMATION_PARSER
/**
* Class used for keeping the data structures and strings that make up the security information that is relevant for display in the dialog.
* The purpose is to avoid a large number of loose strings in different classes making it hard to avoid memory leaks and null pointers. Also contains access functions
* that can create some of these structures from other members where that is desirable.
*
* Modify strings by using the getters that returns pointers to them, and then perform the action on the strings.
*
* Members are generally kept public for easy access without the need for setters and getters.
*/
class OpSecurityInformationContainer
{
private:
OpString m_server_url; ///< The url of the secure server.
OpString m_server_port; ///< The port of the secure server.
OpString m_protocol; ///< The communication protocol details.
OpString m_certificate_servername; ///< Validated name of the server.
OpString m_issued; ///< The time of issue.
OpString m_expires; ///< The expiry date.
OpString m_subject_common_name; ///< The common name of the subject
OpString m_subject_organization; ///< The subject organization
OpString m_subject_organizational_unit; ///< The subject organizational unit
OpString m_subject_locality; ///< The subject locality
OpString m_subject_province; ///< The subject province
OpString m_subject_country; ///< The subject country
OpString m_issuer_common_name; ///< The common name of the issuer
OpString m_issuer_organization; ///< The issuer organization
OpString m_issuer_organizational_unit; ///< The issuer organizational unit
OpString m_issuer_locality; ///< The issuer locality
OpString m_issuer_province; ///< The issuer province
OpString m_issuer_country; ///< The issuer country
OpString m_button_text; ///< The "organization (country)" string that is displayed in the address bar.
OpString m_subject_summary; ///< The cn, o, ou string that is used on the summary pages of information/warning dialogs.
OpString m_issuer_summary; ///< The cn, o, ou string that is used on the summary pages of information/warning dialogs.
OpString m_formatted_expiry_date; ///< The date of expiry formatted in the locale's time format.
BOOL user_confirmed_certificate; ///< Set true if the certificate is user approved
BOOL permanently_confirmed_certificate; ///< Set true if the certificate is permanently user approved
BOOL anonymous_connection; ///< Set true if the server has not provided a certificate
BOOL unknown_ca; ///< Set true if the certificate is signed by an untrusted CA
BOOL certexpired; ///< Set true if the expiry date of the certificate has passed
BOOL cert_not_yet_valid; ///< Set true if the issued date has not passed yet
BOOL configured_warning; ///< Set true if the user has asked for warnings from this issuer
BOOL authentication_only_no_encryption; ///< Set true if the cert info indicates that no encryption is taking place
BOOL low_encryptionlevel; ///< Set true if the encryption is weak
BOOL servername_mismatch; ///< Set true when the server name in the cert is a mismatch.
BOOL ocsp_request_failed; ///< Set true when the ocsp request failed
BOOL ocsp_response_failed; ///< Set true when the ocsp response failed
BOOL reneg_extension_unsupported; ///< Set true when the server does not support the TLS Renegotiation Indication Extension
/**
* Used to help making subject/issuer summary strings
* @param src source string to append. If empty, nothing will happen.
* @param trg target string to append to. Will be modified if src is not empty
* @return TRUE if trg was modified, false otherwise (src was empty)
*/
BOOL AppendCommaSeparated(const OpString &src, OpString &trg);
/**
* Used to help making tm structs from the strings in the info, which can then
* be used to format the time according to locale.
* Example expected format of time string:
*
* 03.02.2008 12:19:19 GMT
*
* @param src The string that needs to be converted to a tm
* @param tm to fill with the info
* @return OK if ok, ERR if problem detected.
*/
OP_STATUS GetTMStructTime(const OpString &src, tm &trg);
public:
/** Constructor. */
OpSecurityInformationContainer() : user_confirmed_certificate(FALSE),
permanently_confirmed_certificate(FALSE),
anonymous_connection(FALSE),
unknown_ca(FALSE),
certexpired(FALSE),
cert_not_yet_valid(FALSE),
configured_warning(FALSE),
authentication_only_no_encryption(FALSE),
low_encryptionlevel(FALSE),
servername_mismatch(FALSE),
ocsp_request_failed(FALSE),
ocsp_response_failed(FALSE),
reneg_extension_unsupported(FALSE)
{
}
/**
* Setter for the security issue booleans.
* @param the text of the corresponding security info document tag
* @return OK if the tag was found and set, ERROR if the tag wasn't found.
*/
OP_STATUS SetSecurityIssue(const uni_char* tag);
// Getters
OpString* GetServerURLPtr() {return &m_server_url;}
OpString* GetServerPortNumberPtr() {return &m_server_port;}
OpString* GetProtocolPtr() {return &m_protocol;}
OpString* GetCertificateServerNamePtr() {return &m_certificate_servername;}
OpString* GetIssuedPtr() {return &m_issued;}
OpString* GetExpiresPtr() {return &m_expires;}
OpString* GetSubjectCommonNamePtr() {return &m_subject_common_name;}
OpString* GetSubjectOrganizationPtr() {return &m_subject_organization;}
OpString* GetSubjectOrganizationalUnitPtr() {return &m_subject_organizational_unit;}
OpString* GetSubjectLocalityPtr() {return &m_subject_locality;}
OpString* GetSubjectProvincePtr() {return &m_subject_province;}
OpString* GetSubjectCountryPtr() {return &m_subject_country;}
OpString* GetIssuerCommonNamePtr() {return &m_issuer_common_name;}
OpString* GetIssuerOrganizationPtr() {return &m_issuer_organization;}
OpString* GetIssuerOrganizationalUnitPtr() {return &m_issuer_organizational_unit;}
OpString* GetIssuerLocalityPtr() {return &m_issuer_locality;}
OpString* GetIssuerProvincePtr() {return &m_issuer_province;}
OpString* GetIssuerCountryPtr() {return &m_issuer_country;}
BOOL GetUserConfirmedCertificate() {return user_confirmed_certificate;}
BOOL GetPermanentlyConfirmedCertificate() {return permanently_confirmed_certificate;}
BOOL GetAnonymousConnection() {return anonymous_connection;}
BOOL GetUnknownCA() {return unknown_ca;}
BOOL GetCertExpired() {return certexpired;}
BOOL GetCertNotYetValid() {return cert_not_yet_valid;}
BOOL GetConfiguredWarning() {return configured_warning;}
BOOL GetAuthenticationOnlyNoEncryption() {return authentication_only_no_encryption;}
BOOL GetLowEncryptionLevel() {return low_encryptionlevel;}
BOOL GetServernameMismatch() {return servername_mismatch;}
BOOL GetOcspRequestFailed() {return ocsp_request_failed;}
BOOL GetOcspResponseFailed() {return ocsp_response_failed;}
BOOL GetOCSPProblem() {return (ocsp_request_failed || ocsp_response_failed);}
BOOL GetRenegotiationExtensionUnsupported() {return reneg_extension_unsupported;}
/**
* Fetch the text for the security button text.
*/
OpString* GetButtonTextPtr();
/**
* Fetch comma separated subject summary string to display in information/warning dialogs
*/
OpString* GetSubjectSummaryString();
/**
* Fetch comma separated issuer summary string to display in information/warning dialogs
*/
OpString* GetIssuerSummaryString();
/**
* Get locale formated expiry date string
*/
OpString* GetFormattedExpiryDate();
};
class OpSecurityInformationParser
{
public:
virtual ~OpSecurityInformationParser(){}
/**
* Get a tree model from the parsed information.
*
* If the tree model has not been created already, then MakeTreeModel will be called, but that will only happen once.
* A member pointer will keep track of the model, and it will be deleted on deletion of the parser.
*
* @return A pointer to a treemodel that represents the contents of the security information. If some error occurs, it returns NULL.
*
* @see MakeTreeModel()
*/
virtual SimpleTreeModel* GetServerTreeModelPtr() = 0;
/**
*
*/
virtual SimpleTreeModel* GetClientTreeModelPtr() = 0;
/**
*
*/
virtual SimpleTreeModel* GetValidatedTreeModelPtr() = 0;
virtual OpSecurityInformationContainer* GetSecurityInformationContainterPtr() = 0;
};
# endif // SECURITY_INFORMATION_PARSER
#endif /*OPSECURITY_INFO_PARSER_H*/
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <Eigen/Core>
#include <Eigen/Geometry>
using namespace std;
using namespace Eigen;
int main(int argc, char** argv) {
Quaterniond q1(0.35, 0.2, 0.3, 0.1), q2(-0.5, 0.4, -0.1, 0.2);
q1.normalize();
q2.normalize();
Vector3d t1(0.3, 0.1, 0.1), t2(-0.1, 0.5, 0.3);
Vector3d p1(0.5, 0, 0.2);
Isometry3d T1w(q1), T2w(q2);
T1w.pretranslate(t1);
T2w.pretranslate(t2);
Vector3d p2 = T2w * T1w.inverse() * p1;
cout << endl << p2.transpose() << endl;
return 0;
}
|
#ifndef SHADER_H
#define SHADER_H
#include <iostream>
#include <string>
#include <unordered_map>
#include <glm/glm.hpp>
#include "commun.h"
#include "resource.h"
class shader
{
uint _id;
public:
shader(std::string path);
~shader();
void use();
void set_float(const std::string& name,const float f);
void set_int(const std::string& name,const int i);
void set_texture(const std::string& name,const uint texture,uint i);
void set_matrix4(const std::string& name,const glm::mat4& mat);
void set_matrix3(const std::string& name,const glm::mat3& mat);
void set_vec3(const std::string& name,const glm::vec3& vec);
void set_vec2(const std::string& name,const glm::vec2& vec);
inline const uint get_id(){return _id;}
};
extern library<shader> shader_library;
#endif //!SHADER_H
|
#include "stdafx.h"
#include "CalProteinProbSiblingSP.h"
CCalProteinProbSiblingSP::~CCalProteinProbSiblingSP(void)
{
}
void CCalProteinProbSiblingSP::calculateProteinProbability()
{
double dProbability=1.0;
for (CMassPeptideXcorr* pPeptideXcorr:m_pProtein->m_vSupportPeptide)//Loop SupportPeptide
{
int iPeptideSharedProtein=1;
double dOriginPeptideSP=1.0;
if (pPeptideXcorr->m_bUnique==false)//shared peptide
{
double dOtherProteinPeptideValue=0.0;
dOriginPeptideSP=getSameMassSPValue( pPeptideXcorr);//get the peptide sigma sp value, mass match to peptide
vector<double> vdPeptideSP(pPeptideXcorr->m_vProtein.size(),0.0);//save the sibling peptide value
for (int j=0;j<pPeptideXcorr->m_vProtein.size();j++)//Loop share peptide to Protein
{
vector<CMassPeptideXcorr*> vMassPeptide = m_pListProtein->getSupportPeptideFromProteinStr(pPeptideXcorr->m_vProtein[j]);
double dPeptideSP=0.0;
for (int j1=0;j1<vMassPeptide.size();j1++)//every protein has some peptides
{
if (vMassPeptide[j1]->m_strPeptideSequence!=pPeptideXcorr->m_strPeptideSequence)//except for the original peptideSequence
{
dPeptideSP += getSameMassSPValue( vMassPeptide[j1]);
}
}
dPeptideSP/=(pPeptideXcorr->m_vProtein.size()-1);
vdPeptideSP.push_back(dPeptideSP);
if (pPeptideXcorr->m_vProtein[j]!=m_pProtein->m_strIPIName)
{
dOtherProteinPeptideValue+=dPeptideSP;
}
}
dOriginPeptideSP=abs(dOriginPeptideSP-dOtherProteinPeptideValue)/dOriginPeptideSP;
}
dProbability=dProbability*(1-dOriginPeptideSP);//no exist probability
}
m_pProtein->m_dProbability=pow((1-dProbability),-log(m_pProtein->m_vSupportPeptide.size()/m_pProtein->m_ivalidTheoryPeptideCount));
}
|
#ifndef SDUZH_BASE_DATETIME_H
#define SDUZH_BASE_DATETIME_H
#include <string>
#include <time.h>
namespace reactor {
class Timestamp
{
public:
static const int kMicroSecondsPerSecond = 1000000; // 10^6
Timestamp(int64_t microseconds): microseconds_(microseconds) {}
int64_t microseconds() const { return microseconds_; }
const char *to_string() const;
static Timestamp current();
Timestamp add(const Timestamp &rhs) const {
return add_microseconds(rhs.microseconds());
}
Timestamp add_seconds(int64_t s) const {
return add_microseconds(s * kMicroSecondsPerSecond);
}
Timestamp add_microseconds(int64_t us) const {
return Timestamp(microseconds_ + us);
}
Timestamp operator + (const Timestamp &rhs) const {
return add(rhs);
}
void operator += (const Timestamp &rhs) {
*this = *this + rhs;
}
private:
static const char *kFormat;
int64_t microseconds_; // micro seconds(us)
mutable char stime_[32];
};
inline bool operator == (const Timestamp &lhs, const Timestamp &rhs) {
return lhs.microseconds() == rhs.microseconds();
}
inline bool operator != (const Timestamp &lhs, const Timestamp &rhs) {
return !(lhs == rhs);
}
inline bool operator < (const Timestamp &lhs, const Timestamp &rhs) {
return lhs.microseconds() < rhs.microseconds();
}
inline bool operator <= (const Timestamp &lhs, const Timestamp &rhs) {
return (lhs < rhs) || (lhs == rhs);
}
inline bool operator > (const Timestamp &lhs, const Timestamp &rhs) {
return !(lhs <= rhs);
}
inline bool operator >= (const Timestamp &lhs, const Timestamp &rhs) {
return (lhs > rhs) || (lhs == rhs);
}
} // namespace reactor
#endif //
|
// Sharna Hossain
// CSC 111
// Lab 20 | linear_search.cpp
#include <iostream>
using namespace std;
void output(int, int);
int linearSearch(int arr[], int size, int query)
{
for (int index = 0; index < size; index++)
{
if (arr[index] == query) return index;
}
return -1;
}
int main()
{
// Initialize values
int size, query;
cout << "Enter the size of the array of numbers: ";
cin >> size;
int arr[size];
for (int i = 0; i < size; i++)
{
cout << "Enter number #" << i + 1 << ": ";
cin >> arr[i];
}
cout << "Enter the number you're searching for: ";
cin >> query;
// Output values
output(query, linearSearch(arr, size, query));
return 0;
}
void output(int query, int index)
{
if (index == -1)
{
cout << query << " cannot be found in array";
}
else
{
cout << query << " is the #" << index + 1;
cout << " element and can be found at ";
cout << "array[" << index << "]\n";
}
}
|
#ifndef WINDOW_H
#define WINDOW_H
#include <Common.h>
class CWindow
{
public:
CWindow(int width, int height, const std::wstring &title);
CWindow(CWindow &&other) = default;
virtual ~CWindow() = default;
virtual void Init();
virtual void Update(float deltaTime);
virtual void Render();
virtual void Resize(int width, int height);
virtual void Key(int key, int action, int mods);
virtual void Cursor(float xpos, float ypos);
void Process();
bool Running()
{
return glfwWindowShouldClose( _window.get() ) != 1;
}
void Destroy()
{
glfwSetWindowShouldClose(_window.get(), 1);
}
bool operator==(const CWindow &other) const
{
return _window.get() == other._window.get();
}
bool operator!=(const CWindow &other) const
{
return !(*this == other);
}
protected:
int GetKeyState(int key)
{
return glfwGetKey(_window.get(), key);
}
void SetCursorPosition(float x, float y)
{
glfwSetCursorPos(_window.get(), static_cast<double>(x), static_cast<double>(y));
}
float _width;
float _height;
private:
// Callbacks
static void FramebufferSizeCallback(GLFWwindow *target_window, int width, int height);
static void KeyCallback(GLFWwindow *target_window, int key, int scancode, int action, int mods);
static void CursorPosCallback(GLFWwindow *target_window, double xpos, double ypos);
class GLFWwindowDestroy
{
public:
void operator()(GLFWwindow *window)
{
glfwDestroyWindow(window);
}
};
std::unique_ptr<GLFWwindow, GLFWwindowDestroy> _window;
};
#endif // WINDOW_H
|
#ifndef SPAN_HPP
# define SPAN_HPP
# include <iostream>
# include <vector>
# include <exception>
# include <algorithm>
class Span
{
private:
unsigned int _size;
std::vector<unsigned int> _numVec;
Span();
public:
class ValuesPoolAreFool : public std::exception
{
public:
virtual const char *what() const throw();
};
class InvalidSizeForThatFuction : public std::exception
{
public:
virtual const char *what() const throw();
};
class AppendedVectorTooBig : public std::exception
{
public:
virtual const char *what() const throw();
};
void appendVector(std::vector<unsigned int> &vec);
void addNumber(unsigned int number);
unsigned int shortestSpan();
unsigned int longestSpan();
Span(unsigned int size);
Span(const Span &toCopy);
Span &operator=(const Span &toCopy);
Span &operator-(const Span &toCopy);
~Span();
};
#endif
|
#include "check-co-call.h"
#include "diagnostic-core.h"
#include <string>
std::string funcNameStr(function* f) {
const char* name = function_name(f);
std::string callName(name);
return callName;
}
int is_funcall(std::string funcName, gimple stmt) {
if (is_gimple_call(stmt)) {
tree fn_decl = gimple_call_fndecl(stmt);
if (!fn_decl) {
return 0;
}
const char* name = function_name(DECL_STRUCT_FUNCTION(fn_decl));
std::string callName(name);
return callName == funcName;
}
return 0;
}
int calls_fn(std::string fnName, function* fun) {
basic_block bb;
gimple stmt;
gimple_stmt_iterator gsi;
FOR_EACH_BB_FN(bb, fun) {
for (gsi = gsi_start_bb(bb); !gsi_end_p(gsi); gsi_next(&gsi)) {
stmt = gsi_stmt(gsi);
if (is_funcall(fnName, stmt)) {
return 1;
}
}
}
return 0;
}
int co_call_violation(std::string fnName1, std::string fnName2, function* fun) {
int locks = calls_fn(fnName1, fun);
int unlocks = calls_fn(fnName2, fun);
return locks && !unlocks;
}
unsigned int check_for_co_call_violations(function* fun) {
if (co_call_violation("rcu_read_lock", "rcu_read_unlock", fun)) {
std::string warnSuffix = " calls rcu_read_lock, but does not call rcu_read_unlock";
std::string warningStr = funcNameStr(fun) + warnSuffix;
warning_at(0, 0, warningStr.c_str());
}
return 0;
}
|
#include "SimSystems.hh"
#include "SimState.hh"
#include "SimComponents.hh"
#include "util/Print.hh"
static bool waterInteraction(SimState &state, PhysicsState::Handle physicsState, const fvec3 &shipPoint, fixed tickLengthS) {
const Map &map(state.getMap());
Water &water(state.getWater());
if (shipPoint.x < 0 || shipPoint.x > water.getSizeX()-1 ||
shipPoint.y < 0 || shipPoint.y > water.getSizeY()-1) {
physicsState->applyForce(tickLengthS * fvec3(0, 0, fixed(500)), shipPoint);
return false;
}
glm::ivec3 gridPosition(fixedToInt(shipPoint));
const GridPoint &gridPoint(map.point(Map::Pos(gridPosition)));
WaterPoint &waterPoint(water.point(Map::Pos(gridPosition)));
fixed waterHeight(water.fpoint(fvec2(shipPoint.x, shipPoint.y)).height);
fixed waterVelocity(water.fpoint(fvec2(shipPoint.x, shipPoint.y)).velocity);
fixed delta = (shipPoint.z - (fixed(gridPoint.height) + waterHeight)) / physicsState->size.z;
if (delta < -1) delta = -1;
// Float up as soon as partially under water
if (delta < 0) {
//physicsState->momentum.z -= delta * fixed(80);
//std::cout << "applying force " << -delta << " at point " << shipPoint << std::endl;
physicsState->applyForce(tickLengthS * fvec3(0, 0, -delta * fixed(1000)), shipPoint);
//std::cout << "-> " << physicsState->angularMomentum << std::endl;
}
// Accelerate upwards slightly with waves
if (delta <= 0 && waterVelocity > 0) {
//physicsState->momentum.z += waterPoint.acceleration * fixed(150);
//physicsState->applyForce(fvec3(0, 0, waterVelocity / fixed(500)), shipPoint);
}
// Cause ripples in the water when falling down and hitting water
if (physicsState->velocity.z < 0 && delta <= 0) {
fixed spread = fixed(1)/fixed(10);
waterPoint.velocity -= spread * physicsState->velocity.z;
//physicsState->momentum.z += -delta * spread * physicsState->velocity.z;
// ... and decrease momentum
//physicsState->momentum.z -= fixed(10)/fixed(50) * physicsState->momentum.z;
physicsState->applyForce(fvec3(0, 0, -fixed(10)/fixed(50) * tickLengthS * physicsState->momentum.z), shipPoint);
}
return delta <= 0;
}
void PhysicsSystem::tick(SimState &state, fixed tickLengthS) {
// Playground for now
const Map &map(state.getMap());
Water &water(state.getWater());
PhysicsState::Handle physicsState;
for (auto entity : state.entities.entities_with_components(physicsState)) {
// Friction
physicsState->momentum -= tickLengthS * fixed(2)/fixed(5) * physicsState->momentum;
physicsState->angularMomentum -= tickLengthS * fixed(9)/fixed(10) * physicsState->angularMomentum;
// Float on water, gravitation
glm::ivec3 gridPosition(fixedToInt(physicsState->position));
const GridPoint &gridPoint(map.point(Map::Pos(gridPosition)));
WaterPoint &waterPoint(water.point(Map::Pos(gridPosition)));
fmat3 m(glm::mat3_cast(physicsState->orientation));
fvec3 shipAxis(normalize(m * fvec3(1,0,0))),
orthAxis(normalize(m * fvec3(0,1,0)));
fvec3 normalAxis(normalize(cross(shipAxis, orthAxis)));
fvec3 base = physicsState->position - (fixed(physicsState->size.z) / 2) * normalAxis;
//std::cout << "SHIP AXIS: " << shipAxis << ", ORTH AXIS: " << orthAxis << std::endl;
//std::cout << "NORMAL: " << normalAxis << std::endl;
physicsState->applyForce(tickLengthS * fvec3(0, 0, -1000),
physicsState->position - (fixed(physicsState->size.x) / 4) * shipAxis
- physicsState->size.z * normalAxis);
physicsState->applyForce(tickLengthS * fvec3(0, 0, -1000),
physicsState->position + (fixed(physicsState->size.x) / 4) * shipAxis
- physicsState->size.z * normalAxis);
size_t inWater = 0;
inWater += waterInteraction(state, physicsState, base + fixed(1)/fixed(2) * shipAxis * physicsState->size.x, tickLengthS);
inWater += waterInteraction(state, physicsState, base - fixed(1)/fixed(2) * shipAxis * physicsState->size.x, tickLengthS);
inWater += waterInteraction(state, physicsState, base + fixed(1)/fixed(2) * orthAxis * physicsState->size.y, tickLengthS);
inWater += waterInteraction(state, physicsState, base - fixed(1)/fixed(2) * orthAxis * physicsState->size.y, tickLengthS);
// Move
physicsState->recalculate();
physicsState->position += physicsState->velocity * tickLengthS;
physicsState->orientation += physicsState->spin * tickLengthS;
physicsState->recalculate();
fixed waterSpeed(sqrt(physicsState->velocity.x * physicsState->velocity.x + physicsState->velocity.y * physicsState->velocity.y));
if (inWater && waterSpeed > fixed(1)/fixed(10)) {
waterPoint.velocity += fixed(2)/fixed(3) * inWater * (waterSpeed > 3 ? 3 : waterSpeed) * tickLengthS;
}
// Clip to map size
gridPosition = fixedToInt(physicsState->position);
if (gridPosition.x < 0) {
physicsState->position.x = 0;
physicsState->momentum.x = 0;
}
if (gridPosition.x > (int)map.getSizeX()-1) {
physicsState->position.x = map.getSizeX()-1;
physicsState->momentum.x = 0;
}
if (gridPosition.y < 0) {
physicsState->position.y = 0;
physicsState->momentum.y = 0;
}
if (gridPosition.y > (int)map.getSizeY()-1) {
physicsState->position.y = map.getSizeY()-1;
physicsState->momentum.y = 0;
}
gridPosition = fixedToInt(physicsState->position);
assert(gridPosition.x >= 0 && gridPosition.x < map.getSizeX());
assert(gridPosition.y >= 0 && gridPosition.y < map.getSizeY());
}
}
void ShipSystem::accelerate(SimState &state, PlayerId player, Direction direction) {
Entity shipEntity(state.getPlayer(player).ship);
PhysicsState::Handle physicsState(shipEntity.component<PhysicsState>());
fmat3 m(glm::mat3_cast(physicsState->orientation));
fvec3 shipAxis(m * fvec3(1,0,0)), orthAxis(m * fvec3(0,1,0));
fvec3 normalAxis(normalize(cross(shipAxis, orthAxis)));
fvec3 base = physicsState->position - (fixed(physicsState->size.z) / 2) * normalAxis;
switch (direction) {
case DIRECTION_FORWARD:
physicsState->momentum += fixed(10) * shipAxis;
break;
case DIRECTION_BACKWARD:
physicsState->momentum -= fixed(10) * shipAxis;
break;
case DIRECTION_LEFT:
physicsState->angularMomentum.z += fixed(100);
break;
case DIRECTION_RIGHT:
physicsState->angularMomentum.z += -fixed(100);
break;
}
}
void CopyPhysicsStateSystem::tick(SimState &state) {
PreviousPhysicsState::Handle previousPhysicsState;
PhysicsState::Handle physicsState;
for (auto entity : state.entities.entities_with_components(previousPhysicsState, physicsState)) {
previousPhysicsState->state = *physicsState.get();
}
}
void ShipSystem::tick(SimState &state, fixed tickLengthS) {
}
|
// An interface for stack implementation
#ifndef HOH_STACK_INTERFACE_H_
#define HOH_STACK_INTERFACE_H_
#include <stdint.h>
namespace hoh_data_structure {
// Exception class thrown by Push() when stack is full
class FullStack {};
// Exception class thrown by Pop() when stack is empty
class EmptyStack {};
template <typename ItemType>
class StackInterface {
public:
virtual bool IsFull() const = 0;
virtual bool IsEmpty() const = 0;
virtual void Push(const ItemType in_item) = 0;
virtual ItemType Pop() = 0;
virtual void Pop(ItemType& out_item) = 0;
virtual ItemType Top() = 0;
virtual void Top(ItemType& out_item) = 0;
virtual int32_t GetCapacity() = 0;
virtual int32_t GetSize() = 0;
private:
};
}
#endif
|
#include <iostream>
#include <math.h>
#include <stdio.h>
using namespace std;
int main() {
double a, b, c, res, res1, res2;
cin >> a >> b >> c;
res = (b*b)-4*a*c;
if (res < 0 || a == 0) {
cout << "Impossivel calcular" << endl;
return 0;
}
res1 = (-b+sqrt(res))/(2*a);
res2 = (-b-sqrt(res))/(2*a);
printf ("R1 = %.5f\n", res1);
printf ("R2 = %.5f\n", res2);
return 0;
}
|
#include <stdio.h>
#include "Camera.hpp"
#include "Matrix.hpp"
bool DEBUG = false;
Camera::Camera() {
setDefaultCamera();
}
void Camera::setDefaultCamera(void) { // make default camera
eye.x = -10, eye.y = 0, eye.z = 0.0;
ref.x = 10, ref.y = 0, ref.z = 0.0;
viewup.x = 0.0, viewup.y = 1.0, viewup.z = 0.0;
aspect = 1.0, viewAngle = 40.0, nearDist = 0.1, farDist = 10000.0;
}
void Camera::set(Point Eye, Point Look, Vector Up) {
eye.set(Eye);
ref.set(Look);
viewup.set(Up);
aspect = 1.0, viewAngle = 40.0, nearDist = 0.1, farDist = 10000.0;
//setModelViewMatrix();
}
void Camera::rotate(GLfloat rx, GLfloat ry, GLfloat rz, GLfloat angle) { //w.r.p.t WC
Matrix m;
m.rotate(rx, ry, rz, angle);
GLfloat v[4];
v[0] = eye.x;
v[1] = eye.y;
v[2] = eye.z;
v[3] = 1;
m.multiply_vector(v);
eye.x = v[0];
eye.y = v[1];
eye.z = v[2];
//std::cout << v[0] << ", " << v[1] << ", " << v[2] << std::endl;
}
void Camera::translate(GLfloat tx, GLfloat ty, GLfloat tz) { //w.r.p.t WC
eye.x += tx;
eye.y += ty;
eye.z += tz;
}
void Camera::setProjectionMatrix() {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(viewAngle, aspect, nearDist, farDist);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(eye.x, eye.y, eye.z, ref.x, ref.y, ref.z, viewup.x, viewup.y, viewup.z);
}
void Camera::setViewVolume(float viewAngle, float aspect, float Near, float Far) {
this->viewAngle = viewAngle;
this->aspect = aspect;
nearDist = Near > 0 ? Near : 0.01; // should never be set to 0 according to documentation
farDist = Far > 0 ? Far : 0;
}
void Camera::rotateViewUp(GLfloat rx, GLfloat rz, GLfloat ry, GLfloat angle) {
Matrix m;
m.rotate(rx, ry, rz, angle);
GLfloat v[4];
v[0] = viewup.x;
v[1] = viewup.y;
v[2] = viewup.z;
v[3] = 1;
m.multiply_vector(v);
viewup.x = v[0];
viewup.y = v[1];
viewup.z = v[2];
}
Vector Camera::getViewVector() {
Vector v;
v.set(ref.x - eye.x, ref.y - eye.y, ref.z - eye.z);
return v;
}
|
#pragma once
#include "Commonheader.h"
#include "InputManager.h"
//シーケンスの元クラス(派生クラスのUpdateを更新していく)
class Boot
{
public:
virtual ~Boot(){} //なにもしないのでこれでいい
virtual Boot* Update(Boot*) = 0;
};
|
#include <vector>
class Triangle {
private:
class Node {
private:
int value;
Node* left;
Node* right;
public:
Node(int);
void set_left(Node* l) { left = l; }
void set_right(Node* r) { right = r; }
int get_value() { return value; }
Node* get_left() { return left; }
Node* get_right() { return right; }
};
std::vector<Node> nodes;
int find_max_subpath(Node*);
public:
Triangle();
Triangle(const std::vector<int>::iterator&, const std::vector<int>::iterator&);
int find_max_path();
};
|
#include <iostream>
#include <cstdio>
#include <math.h>
using namespace std;
int main(){
double A,B,C;
scanf("%lf %lf %lf",&A,&B,&C);
double aTri = (A * C)/2;
double aCir = 3.14159 * pow(C,2);
double aTrap = (A + B)/2 * C;
double aSq = pow(B,2);
double aRect = A * B;
printf("TRIANGULO: %.3lf\n",aTri);
printf("CIRCULO: %.3lf\n",aCir);
printf("TRAPEZIO: %.3lf\n",aTrap);
printf("QUADRADO: %.3lf\n",aSq);
printf("RETANGULO: %.3lf\n",aRect);
return 0;
}
|
#pragma once
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include "Application.h"
using glm::vec2;
using glm::vec3;
using glm::vec4;
using glm::mat4;
class Camera
{
// camera pos and rot in world space
mat4 worldTransform;
// inverse of world transform;
mat4 viewTransform;
// near and far planes
mat4 projectionTransform;
// view * projection
mat4 projectionViewTransform;
public:
Camera();
~Camera();
vec4 worldPos;
Camera(float windowHeight, float windowLength);
void Start();
void Start(float windowHeight, float windowWidth);
virtual void Update(float deltaTime) = 0;
void SetPerspective(float fieldOfView, float aspectRatio, float near, float far);
void SetLookAt(vec3 from, vec3 to, vec3 up);
void SetPos(vec3 pos);
vec3 GetPos();
void SetWorldTransform(mat4 transform);
mat4 GetWorldTransform();
mat4 GetView();
mat4 GetProjection();
mat4 GetProjectionView();
vec3 GetRow(int row);
void getFrustumPlanes(const glm::mat4& transform, glm::vec4* planes);
protected:
void UpdateProjectionViewMatrix();
};
|
#ifndef AD_GRAPHSWRITERSTRATEGY_H
#define AD_GRAPHSWRITERSTRATEGY_H
#include "FileWriterStrategy.h"
#include <iostream>
#include <fstream>
using namespace std;
class GraphsWriterStrategy : public FileWriterStrategy {
private:
ofstream *file = nullptr;
public:
~GraphsWriterStrategy() override;
void closeFile() override;
void openFile() override;
void write(const double &x, const double &y) override;
};
#endif //AD_GRAPHSWRITERSTRATEGY_H
|
template <typename... TArgs>
struct ComponentList
{
public:
static ComponentMap get_map()
{
ComponentMap map;
auto ids = { id<TArgs>()... };
for (auto&& x : ids)
{
if(x >= 0) map.set(x);
}
return map;
}
private:
template <typename T> static enable_if_component<T,int> id() { return T::ID; }
template <typename T> static enable_if_resource<T,int> id() { return -1; }
};
|
/*
* CharLogin.cpp
*
* Created on: Jun 29, 2017
* Author: root
*/
#include "CharLogin.h"
#include "Log/Logger.h"
#include "Network/Message_Facade.h"
#include "MessageCommonRet.h"
#include "../MessageBuild.h"
#include "MessageStruct/ServerReturnInt.pb.h"
#include "MessageStruct/ServerReturn2Int.pb.h"
#include "MessageStruct/ServerReturn4Int.pb.h"
#include "MessageStruct/ServerReturnChar.pb.h"
#include "../CharMemCache/PlayerDBManager.h"
#include "../CharMemCache/CharMemCache.h"
#include "CharDefine.h"
#include "util.h"
#include <time.h>
#include "SvrConfig.h"
#include "MessageStruct/ServerReturnBool.pb.h"
#include "MessageStruct/CharLogin/PlayerInfo.pb.h"
CCharLogin * CCharLogin::m_instance = 0;
CCharLogin::CCharLogin()
{
// DEF_MSG_REQUEST_REG_FUN(eDBServer, MSG_REQ_LS2DB_GETROLEID);
// DEF_MSG_REQUEST_REG_FUN(eDBServer, MSG_REQ_LS2DB_CREATEROLE);
DEF_MSG_REQUEST_REG_FUN(eDBServer, MSG_REQ_GM2DB_PLAYERINFO);
DEF_MSG_SIMPLE_REG_FUN(eDBServer, MSG_SIM_GT2GM_SAVE_PLAYERINFO);
DEF_MSG_REQUEST_REG_FUN(eDBServer, MSG_REQ_GS2DB_SAVE_PLAYERDATA);
// InitCharTemplate();
}
CCharLogin::~CCharLogin()
{
}
void CCharLogin::Handle_Request(Safe_Smart_Ptr<Message> &message)
{
DEF_SWITCH_TRY_DISPATCH_BEGIN
// DEF_MSG_REQUEST_DISPATCH_FUN(MSG_REQ_LS2DB_GETROLEID);
// DEF_MSG_REQUEST_DISPATCH_FUN(MSG_REQ_LS2DB_CREATEROLE);
DEF_MSG_REQUEST_DISPATCH_FUN(MSG_REQ_GM2DB_PLAYERINFO);
DEF_MSG_REQUEST_DISPATCH_FUN(MSG_REQ_GS2DB_SAVE_PLAYERDATA);
DEF_SWITCH_TRY_DISPATCH_END
}
void CCharLogin::Handle_Message(Safe_Smart_Ptr<Message> &message)
{
DEF_SWITCH_TRY_DISPATCH_BEGIN
DEF_MSG_SIMPLE_DISPATCH_FUN(MSG_SIM_GT2GM_SAVE_PLAYERINFO);
DEF_SWITCH_TRY_DISPATCH_END
}
DEF_MSG_REQUEST_DEFINE_FUN(CCharLogin, MSG_REQ_GM2DB_PLAYERINFO)
{
LOG_DEBUG(FILEINFO, "gameserver request dbserver player info");
#ifdef DEBUG
int64 betime = CUtil::GetNowSecond();
#endif
ServerReturn::ServerRetInt req;
Smart_Ptr<PlayerInfo::PlayerInfo> content = new PlayerInfo::PlayerInfo();
char * str;
int len = 0;
str = message->GetBuffer(len);
req.ParseFromArray(str, len);
if(!CCharMemCache::GetInstance()->IsPlayerInCache(GET_PLAYER_CHARID(req.ret())))
{
Smart_Ptr<PlayerDBMgr> tempPlayer = new PlayerDBMgr();
try
{
CMysqlInterface tempMysqlInterface;
getRoleInfo(req.ret(),tempPlayer,tempMysqlInterface);
CCharMemCache::GetInstance()->AddNewPlayer(GET_PLAYER_CHARID(req.ret()), tempPlayer);
}
catch(exception &e)
{
LOG_ERROR(FILEINFO, "[messageid = %d]Get player cache error , errormsg [%s]", MSG_REQ_GM2DB_PLAYERINFO, e.what());
return;
}
catch(...)
{
LOG_ERROR(FILEINFO, "[messageid = %d]Get player cache unknown error", MSG_REQ_GM2DB_PLAYERINFO);
return;
}
}
CCharMemCache::GetInstance()->GetPlayerInfo(req.ret(),content.Get());
if(!content)
{
LOG_ERROR(FILEINFO, "[messageid = %d]Get player cache error", MSG_REQ_GM2DB_PLAYERINFO);
return;
}
if(content->ByteSize() >= 32 * 1024)
{
LOG_FATAL(FILEINFO, "[messageid = %d]Get player cache but player info size > 32 * 1024", MSG_REQ_GM2DB_PLAYERINFO);
return;
}
Safe_Smart_Ptr<CommBaseOut::Message> messRet = build_message(MSG_REQ_GM2DB_PLAYERINFO, message, content.Get(), Ack);
Message_Facade::Send(messRet);
#ifdef DEBUG
int64 endTime = CUtil::GetNowSecond();
if(endTime - betime > 10 || (GET_PLAYER_CHARID(req.ret())) == 37143)
{
LOG_FATAL(FILEINFO, "%s and too more time[%lld] player[%lld]", __FUNCTION__, endTime - betime,GET_PLAYER_CHARID(req.ret()));
}
#endif
}
//玩家基础信息
void CCharLogin::getRoleInfo(int64 playerID,Smart_Ptr<PlayerDBMgr> player,CMysqlInterface& mysqlInterface)
{
try
{
mysqlInterface.Select("select * from RoleInfo where CharID=%lld",GET_PLAYER_CHARID(playerID));
if(!mysqlInterface.IsHaveRecord())
return ;
Smart_Ptr<PlayerInfo::BaseInfo> baseInfo = new PlayerInfo::BaseInfo();
baseInfo->set_charid(mysqlInterface.GetInt64Name("CharID"));
baseInfo->set_charname(mysqlInterface.GetStringName("CharName"));
baseInfo->set_wchatname(mysqlInterface.GetStringName("wchatname"));
baseInfo->set_head(mysqlInterface.GetStringName("head"));
baseInfo->set_sex(mysqlInterface.GetIntName("sex"));
baseInfo->set_country(mysqlInterface.GetIntName("country"));
baseInfo->set_province(mysqlInterface.GetIntName("province"));
baseInfo->set_city(mysqlInterface.GetIntName("city"));
baseInfo->set_signature(mysqlInterface.GetStringName("signature"));
baseInfo->set_money(mysqlInterface.GetIntName("money"));
baseInfo->set_turnmoney(mysqlInterface.GetIntName("turnmoney"));
baseInfo->set_qrcode(mysqlInterface.GetStringName("qrcode"));
baseInfo->set_phone(mysqlInterface.GetStringName("phone"));
baseInfo->set_year(mysqlInterface.GetIntName("year"));
baseInfo->set_month(mysqlInterface.GetIntName("month"));
baseInfo->set_day(mysqlInterface.GetIntName("day"));
player->AddStruct(eBaseInfo, baseInfo);
}
catch(exception &e)
{
LOG_ERROR(FILEINFO, "getRoleInfo error,errormsg [%s]",e.what());
}
catch(...)
{
LOG_ERROR(FILEINFO, "getRoleInfo unknown error");
}
return ;
}
DEF_MSG_SIMPLE_DEFINE_FUN(CCharLogin, MSG_SIM_GT2GM_SAVE_PLAYERINFO)
{
LOG_DEBUG(FILEINFO, "[messageid = %d] save player info", MSG_SIM_GT2GM_SAVE_PLAYERINFO);
PlayerInfo::SaveTypeInfo meContent;
char *str;
int len = 0;
str = message->GetBuffer(len);
meContent.ParseFromArray(str, len);
CCharMemCache::GetInstance()->SaveToCache(&meContent);
}
DEF_MSG_REQUEST_DEFINE_FUN(CCharLogin, MSG_REQ_GS2DB_SAVE_PLAYERDATA)
{
PlayerInfo::SaveTypeInfo meContent;
char *str;
int len = 0;
str = message->GetBuffer(len);
meContent.ParseFromArray(str, len);
CCharMemCache::GetInstance()->SaveToCache(&meContent);
ServerReturn::ServerRetInt ret;
ret.set_ret(meContent.id());
Safe_Smart_Ptr<Message> messRet = build_message(MSG_REQ_GS2DB_SAVE_PLAYERDATA,message, &ret);
Message_Facade::Send(messRet);
}
|
#include <iostream>
#include "vector_sort.h"
#include "vector_erase.h"
#include "lower_bound.h"
#include "maps.h"
#include "sets.h"
int main() {
sets();
return 0;
}
|
#include "ray.h"
ray::ray(const vector3 origin, const vector3 direction) :
_origin(origin),
_direction(direction),
_distance_traveled(0)
{}
ray::ray(const ray&& r) noexcept
{
_origin = r._origin;
_direction = r._direction;
}
auto ray::operator=(ray&& r) noexcept -> ray&
{
_origin = r._origin;
_direction = r._direction;
return *this;
}
auto ray::origin() const -> const vector3&
{
return _origin;
}
auto ray::direction() const -> const vector3&
{
return _direction;
}
auto ray::distance_traveled() -> double&
{
return _distance_traveled;
}
|
#pragma once
#include <Allocator.h>
namespace breakout
{
class LinearAllocator : public Allocator
{
public:
LinearAllocator(const size_t size);
~LinearAllocator() override;
void* allocate(const size_t size) override;
void deallocate(void* p) override final;
virtual void Clear();
protected:
void* m_memoryStart = nullptr;
void* m_currentPosition = nullptr;
};
}
|
//------------------------------------------------------------------------------
// Author: Mr. Lynn Barnett
// Student ID: *20360727
// E-Mail: barnettlynn@gmail.com
// Course: CMSC 2613, Programming II
// CRN: 21256, Spring, 2014
// Project: p01
// Due: January 24, 2014
// Account: tt044
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Files:
// p01.cpp
// List01.cpp ***
// List01.h
// p01make
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
#include "List01.h"
#include <iostream>
#include <fstream>
#include <string.h>
#include <iomanip>
using namespace std;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// ARRAY OVERFLOW MESSAGE
struct OverflowException
{
OverflowException()
{
cout << "Array is too small to hold input file size of array needs to be increased" << endl;
}
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// CONSTRUCTOR AND DECONSTRUCTOR
List01::List01(char* input_file_name, char* output_file_name):input(input_file_name), output(output_file_name), size(100){
my_list = new int[size];
};
List01::~List01(){
delete[] my_list;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// READ OR SCAN METHOD, PUTS DATA INTO ARRAY
void List01::read(void){
int i = 0;
ifstream input_data (input);
while(true)
{
int s;
input_data >> s;
if(input_data.eof())
{
break;
}
if (i >= size - 1)
{
throw OverflowException();
}
my_list[i] = s;
i++;
}
size = i; // SETS THE AMOUNT OF THE ARRAY USED
input_data.close();
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// SORT ARRAY
void List01::sort(void){
int eol = size - 1;
while(eol >= 1)
{
int iom = 0;
int i = 1;
while(i <= eol)
{
if(my_list[i] > my_list[iom])
{
iom = i;
}
i++;
}
swap(eol, iom);
eol --;
}
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Swap numbers in array
void List01::swap(int a, int b){
int c = my_list[a];
my_list[a] = my_list[b];
my_list[b] = c;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// METHOD USED TO WRITE DATA TO FILE
void List01::write(const char* message){
o.open(output, ofstream::out | ofstream::app); // OUTPUT OR APPEND TO FILE
o << message << endl;
for(int i = 0; i <= size - 1; i++)
{
if(i % 10 == 0) o << endl;
o << right << setw(5) << my_list[i] << " ";
}
o << endl;
o << endl;
o.close();
};
//------------------------------------------------------------------------------
|
//
// Created by biega on 19.03.2018.
//
#include <iostream>
#include "inputvalidator.h"
int InputValidator::symbolTest(std::vector <std::string> tab){
for(int i=0;i<tab.size();i++){
for(int j=0;j<tab[i].length();j++){
if(tab[i][j]!='U' && tab[i][j]!='#' && tab[i][j]!='H' && tab[i][j]!='O' && tab[i][j]!='@' && tab[i][j]!='M'){
std::cout<<"Error (symbols)"<<std::endl;
return 0;
}
}
}
return 1;
}
int InputValidator::sizeTest(std::vector <std::string> tab){
for(int i=1;i<tab.size();i++){
if(tab[i-1].length()!=tab[i].length()){
std::cout<<"Error (size)"<<std::endl;
return 0;
}
}
return 1;
}
int InputValidator::numberTest(int a, int b, int in) {
if(in<a || in>b){
std::cout<<"Wrong number"<<std::endl;
return 0;
}
return 1;
}
int InputValidator::numberTest(int a, int in) {
if(in<a){
std::cout<<"Wrong number"<<std::endl;
return 0;
}
return 1;
}
int InputValidator::fileTest(std::fstream& file, std::string name){
file.open(name,std::ios::in);
if(file.good()){
file.close();
return 1;
}
else{
std::cout<<"File error"<<std::endl;
file.close();
return 0;
}
}
int InputValidator::singleSymbolTest(char a) {
if(a!='U' && a!='#' && a!='H' && a!='O' && a!='@' && a!='M'){
std::cout<<"Incorrect symbol"<<std::endl;
return 0;
}
return 1;
}
int InputValidator::isMap(Map* m) {
if(m== nullptr){
std::cout<<"Can't do anything, because there's no map!"<<std::endl;
return 0;
}
return 1;
}
|
/*
Copyright 2021 University of Manchester
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 <memory>
#include <string>
#include "execution_plan_graph_interface.hpp"
using orkhestrafs::core_interfaces::ExecutionPlanGraphInterface;
namespace orkhestrafs::dbmstodspi {
/**
* @brief Factory for creating query plan graphs.
*/
class GraphCreatorInterface {
public:
virtual ~GraphCreatorInterface() = default;
/**
* @brief Read the given input_def file and make the query plan graph object.
* @param graph_def_filename File containing the query plan information.
* @return Query plan graph created form the given JSON.
*/
virtual auto MakeGraph(std::string graph_def_filename,
std::unique_ptr<ExecutionPlanGraphInterface> graph)
-> std::unique_ptr<ExecutionPlanGraphInterface> = 0;
};
} // namespace orkhestrafs::dbmstodspi
|
// Copyright Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/ObjectMacros.h"
#include "UObject/ScriptMacros.h"
PRAGMA_DISABLE_DEPRECATION_WARNINGS
#ifdef DUNGEONESCAPE_OpenDoor_generated_h
#error "OpenDoor.generated.h already included, missing '#pragma once' in OpenDoor.h"
#endif
#define DUNGEONESCAPE_OpenDoor_generated_h
#define DungeonEscape_Source_DungeonEscape_OpenDoor_h_14_SPARSE_DATA
#define DungeonEscape_Source_DungeonEscape_OpenDoor_h_14_RPC_WRAPPERS
#define DungeonEscape_Source_DungeonEscape_OpenDoor_h_14_RPC_WRAPPERS_NO_PURE_DECLS
#define DungeonEscape_Source_DungeonEscape_OpenDoor_h_14_INCLASS_NO_PURE_DECLS \
private: \
static void StaticRegisterNativesUOpenDoor(); \
friend struct Z_Construct_UClass_UOpenDoor_Statics; \
public: \
DECLARE_CLASS(UOpenDoor, UActorComponent, COMPILED_IN_FLAGS(0 | CLASS_Config), CASTCLASS_None, TEXT("/Script/DungeonEscape"), NO_API) \
DECLARE_SERIALIZER(UOpenDoor)
#define DungeonEscape_Source_DungeonEscape_OpenDoor_h_14_INCLASS \
private: \
static void StaticRegisterNativesUOpenDoor(); \
friend struct Z_Construct_UClass_UOpenDoor_Statics; \
public: \
DECLARE_CLASS(UOpenDoor, UActorComponent, COMPILED_IN_FLAGS(0 | CLASS_Config), CASTCLASS_None, TEXT("/Script/DungeonEscape"), NO_API) \
DECLARE_SERIALIZER(UOpenDoor)
#define DungeonEscape_Source_DungeonEscape_OpenDoor_h_14_STANDARD_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API UOpenDoor(const FObjectInitializer& ObjectInitializer); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UOpenDoor) \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UOpenDoor); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UOpenDoor); \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API UOpenDoor(UOpenDoor&&); \
NO_API UOpenDoor(const UOpenDoor&); \
public:
#define DungeonEscape_Source_DungeonEscape_OpenDoor_h_14_ENHANCED_CONSTRUCTORS \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API UOpenDoor(UOpenDoor&&); \
NO_API UOpenDoor(const UOpenDoor&); \
public: \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UOpenDoor); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UOpenDoor); \
DEFINE_DEFAULT_CONSTRUCTOR_CALL(UOpenDoor)
#define DungeonEscape_Source_DungeonEscape_OpenDoor_h_14_PRIVATE_PROPERTY_OFFSET \
FORCEINLINE static uint32 __PPO__TargetYaw() { return STRUCT_OFFSET(UOpenDoor, TargetYaw); } \
FORCEINLINE static uint32 __PPO__OpenActivator() { return STRUCT_OFFSET(UOpenDoor, OpenActivator); } \
FORCEINLINE static uint32 __PPO__DoorCloseDelay() { return STRUCT_OFFSET(UOpenDoor, DoorCloseDelay); } \
FORCEINLINE static uint32 __PPO__MassToOpenDoor() { return STRUCT_OFFSET(UOpenDoor, MassToOpenDoor); } \
FORCEINLINE static uint32 __PPO__AudioComponent() { return STRUCT_OFFSET(UOpenDoor, AudioComponent); }
#define DungeonEscape_Source_DungeonEscape_OpenDoor_h_11_PROLOG
#define DungeonEscape_Source_DungeonEscape_OpenDoor_h_14_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
DungeonEscape_Source_DungeonEscape_OpenDoor_h_14_PRIVATE_PROPERTY_OFFSET \
DungeonEscape_Source_DungeonEscape_OpenDoor_h_14_SPARSE_DATA \
DungeonEscape_Source_DungeonEscape_OpenDoor_h_14_RPC_WRAPPERS \
DungeonEscape_Source_DungeonEscape_OpenDoor_h_14_INCLASS \
DungeonEscape_Source_DungeonEscape_OpenDoor_h_14_STANDARD_CONSTRUCTORS \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define DungeonEscape_Source_DungeonEscape_OpenDoor_h_14_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
DungeonEscape_Source_DungeonEscape_OpenDoor_h_14_PRIVATE_PROPERTY_OFFSET \
DungeonEscape_Source_DungeonEscape_OpenDoor_h_14_SPARSE_DATA \
DungeonEscape_Source_DungeonEscape_OpenDoor_h_14_RPC_WRAPPERS_NO_PURE_DECLS \
DungeonEscape_Source_DungeonEscape_OpenDoor_h_14_INCLASS_NO_PURE_DECLS \
DungeonEscape_Source_DungeonEscape_OpenDoor_h_14_ENHANCED_CONSTRUCTORS \
private: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
template<> DUNGEONESCAPE_API UClass* StaticClass<class UOpenDoor>();
#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID DungeonEscape_Source_DungeonEscape_OpenDoor_h
PRAGMA_ENABLE_DEPRECATION_WARNINGS
|
/* UVA374 Big Mod */
#include<iostream>
using namespace std;
int pow(int b,int exp, int m)
{
if(exp == 0)
return 1%m;
if(exp == 1)
return b%m;
if(exp % 2 == 0)
return pow(b*b % m, exp/2 ,m);
else
return b*pow(b, exp-1, m)%m;
}
int main()
{
int b,p,m;
while(cin>>b>>p>>m)
{
cout<<pow(b%m,p,m)<<endl;
}
}
|
// Copyright (c) 2021 ETH Zurich
//
// SPDX-License-Identifier: BSL-1.0
// 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)
#pragma once
#include <pika/config.hpp>
#if defined(PIKA_HAVE_GPU_SUPPORT)
# include <pika/async_cuda/cuda_stream.hpp>
# include <pika/async_cuda/custom_lapack_api.hpp>
# include <fmt/format.h>
# include <whip.hpp>
# include <string>
namespace pika::cuda::experimental {
/// RAII wrapper for a cuSOLVER handle.
class cusolver_handle
{
private:
int device;
whip::stream_t stream{};
cusolverDnHandle_t handle{};
static PIKA_EXPORT cusolverDnHandle_t create_handle(int device, whip::stream_t stream);
public:
PIKA_EXPORT cusolver_handle();
PIKA_EXPORT explicit cusolver_handle(cuda_stream const& stream);
PIKA_EXPORT ~cusolver_handle();
PIKA_EXPORT cusolver_handle(cusolver_handle&&) noexcept;
PIKA_EXPORT cusolver_handle& operator=(cusolver_handle&&) noexcept;
PIKA_EXPORT cusolver_handle(cusolver_handle const&);
PIKA_EXPORT cusolver_handle& operator=(cusolver_handle const&);
PIKA_EXPORT cusolverDnHandle_t get() const noexcept;
PIKA_EXPORT int get_device() const noexcept;
PIKA_EXPORT whip::stream_t get_stream() const noexcept;
PIKA_EXPORT void set_stream(cuda_stream const& stream);
/// \cond NOINTERNAL
friend bool operator==(cusolver_handle const& lhs, cusolver_handle const& rhs) noexcept
{
return lhs.handle == rhs.handle;
}
friend bool operator!=(cusolver_handle const& lhs, cusolver_handle const& rhs) noexcept
{
return !(lhs == rhs);
}
/// \endcond
};
} // namespace pika::cuda::experimental
template <>
struct fmt::formatter<pika::cuda::experimental::cusolver_handle> : fmt::formatter<std::string>
{
template <typename FormatContext>
auto format(pika::cuda::experimental::cusolver_handle const& handle, FormatContext& ctx)
{
return fmt::formatter<std::string>::format(
fmt::format("cusolver_handle({})", fmt::ptr(handle.get())), ctx);
}
};
#endif
|
#include "qmlqmqtt_plugin.h"
#include "qmlqmqtt.h"
#include <qqml.h>
void QmlQmqttPlugin::registerTypes(const char *uri)
{
// @uri QmlQmqtt
qmlRegisterType<QmlQmqtt>(uri, 1, 0, "QmlQmqtt");
}
|
#include <stdio.h>
#include <windows.h>
int main()
{
int i = 0, i2 = 0;
int arr[5];
char buff[3];
FILE *fr, *fw;
if ((fr = fopen("INPUT.txt", "r")) == NULL)
{
puts("Couldn't open file\n");
system("pause");
exit(1);
}
while(feof(fr)==0)
{
buff[i++] = getc(fr);
if(buff[i-1]==' '||feof(fr)!=0)
{
arr[i2++] = atoi(buff);
buff[1] = ' ';
i=0;
}
}
fclose(fr);
int unic_cards[5];
unic_cards[0] = arr[0];
int N_unic_cards=1, not_unic;
for(i=1; i < 5; i++)
{
not_unic=0;
for(int i1=0; i1<N_unic_cards; i1++)
if(arr[i]!=unic_cards[i1]) not_unic++;
if(not_unic==N_unic_cards) unic_cards[N_unic_cards++]=arr[i];
}
if ((fw = fopen("OUTPUT.txt", "w")) == NULL)
{
puts("Couldn't open file\n");
system("pause");
exit(1);
}
int Nrepeats;
switch (N_unic_cards)
{
case 1:
fputs("Impossible", fw);
break;
case 2:
Nrepeats=0;
for(i=0; i<5; i++)
if(arr[i]==unic_cards[0]) Nrepeats++;
if(Nrepeats==2||Nrepeats==3) fputs("Full House", fw);
else fputs("Four of a Kind", fw);
break;
case 3:
for(int i1=0; i1<N_unic_cards; i1++)
{
Nrepeats = 0;
for(i=0; i<5; i++)
if(arr[i]==unic_cards[i1]) Nrepeats++;
if(Nrepeats==2) {fputs("Two Pairs", fw);break;}
else if(Nrepeats==3) {fputs("Three of a Kind", fw);break;}
}
break;
case 4:
fputs("One Pair", fw);
break;
case 5:
int min=arr[0];
for(i=1; i<5; i++)
{
if(arr[i]<min) min=arr[i];
}
bool is_more_1;
for(i=1; i<5; i++)
{
is_more_1=false;
for(int i1=0; i1<5; i1++)
{
if(arr[i1]==min+1) {is_more_1=true; min=arr[i1]; break;}
}
if(is_more_1==false) {fputs("Nothing", fw); break;}
}
if(is_more_1==true) fputs("Straight", fw);
break;
}
fclose(fw);
return 0;
}
|
// Copyright (c) 2020 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Aspect_XRAction_HeaderFile
#define _Aspect_XRAction_HeaderFile
#include <Aspect_XRActionType.hxx>
#include <NCollection_IndexedDataMap.hxx>
#include <Standard_Transient.hxx>
#include <Standard_Type.hxx>
#include <TCollection_AsciiString.hxx>
//! XR action definition.
class Aspect_XRAction : public Standard_Transient
{
DEFINE_STANDARD_RTTIEXT(Aspect_XRAction, Standard_Transient)
public:
//! Return action id.
const TCollection_AsciiString& Id() const { return myId; }
//! Return action type.
Aspect_XRActionType Type() const { return myType; }
//! Return TRUE if action is defined.
bool IsValid() const { return myRawHandle != 0; }
//! Return action handle.
uint64_t RawHandle() const { return myRawHandle; }
//! Set action handle.
void SetRawHandle (uint64_t theHande) { myRawHandle = theHande; }
//! Main constructor.
Aspect_XRAction (const TCollection_AsciiString& theId,
const Aspect_XRActionType theType)
: myId (theId), myRawHandle (0), myType (theType) {}
protected:
TCollection_AsciiString myId; //!< action id
uint64_t myRawHandle; //!< action handle
Aspect_XRActionType myType; //!< action type
};
//! Map of actions with action Id as a key.
typedef NCollection_IndexedDataMap<TCollection_AsciiString, Handle(Aspect_XRAction), TCollection_AsciiString> Aspect_XRActionMap;
#endif // _Aspect_XRAction_HeaderFile
|
//
// EPITECH PROJECT, 2018
// zappy
// File description:
// ScrollBar.hpp
//
#ifndef ScrollBar_HPP
#define ScrollBar_HPP
#include "include.hpp"
#include <vector>
class ScrollBar
{
public:
ScrollBar(irr::gui::IGUIScrollBar *ScrollBar, int id);
ScrollBar();
~ScrollBar();
void setPos(int pos);
int getPos(void) const;
int getId() const;
void setVisible(bool id);
private:
int _id;
long _idx;
int _pos;
irr::gui::IGUIScrollBar *_scrollBar;
};
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#include "modules/windowcommander/src/WindowCommanderManager.h"
#include "modules/windowcommander/src/WindowCommander.h"
#include "modules/windowcommander/src/TransferManager.h"
#include "modules/hardcore/base/opstatus.h"
#include "modules/hardcore/mem/mem_man.h"
#include "modules/media/media_module.h"
#include "modules/url/url_man.h"
#include "modules/gadgets/OpGadgetManager.h"
#include "modules/dochand/winman.h"
#include "modules/dochand/win.h"
#include "modules/dom/domenvironment.h"
#include "modules/security_manager/include/security_manager.h"
#include "modules/prefs/prefsmanager/prefsmanager.h"
#ifdef SUPPORT_GENERATE_THUMBNAILS
# include "modules/thumbnails/thumbnailmanager.h"
#endif // SUPPORT_GENERATE_THUMBNAILS
#ifdef HISTORY_SUPPORT
# include "modules/history/OpHistoryModel.h"
#endif // HISTORY_SUPPORT
#ifdef DIRECT_HISTORY_SUPPORT
# include "modules/history/direct_history.h"
#endif //DIRECT_HISTORY_SUPPORT
#ifndef HAS_COMPLEX_GLOBALS
extern void init_wic_charsets();
#endif // !HAS_COMPLEX_GLOBALS
#ifdef APPLICATION_CACHE_SUPPORT
# include "modules/applicationcache/application_cache_manager.h"
#endif // APPLICATION_CACHE_SUPPORT
#ifdef PREFS_GETOVERRIDDENHOSTS
# include "modules/util/opstrlst.h"
#endif // PREFS_GETOVERRIDDENHOSTS
#ifdef OPERA_CONSOLE
# include "modules/console/opconsoleengine.h"
#endif // OPERA_CONSOLE
#ifdef _PLUGIN_SUPPORT_
# include "modules/ns4plugins/src/pluginhandler.h"
# include "modules/ns4plugins/src/pluginlibhandler.h"
#endif // _PLUGIN_SUPPORT_
WindowCommanderManager::WindowCommanderManager()
: m_uiWindowListener(&m_nullUiWindowListener),
#if defined _SSL_SUPPORT_ && defined _NATIVE_SSL_SUPPORT_ || defined WIC_USE_SSL_LISTENER
m_sslListener(&m_nullSslListener),
#endif // _SSL_SUPPORT_ && _NATIVE_SSL_SUPPORT_ || WIC_USE_SSL_LISTENER
#ifdef WINDOW_COMMANDER_TRANSFER
m_transferManager(NULL),
#endif // WINDOW_COMMANDER_TRANSFER
m_authenticationListener(&m_nullAuthenticationListener),
#if defined SUPPORT_DATA_SYNC && defined CORE_BOOKMARKS_SUPPORT
m_dataSyncListener(&m_nullDataSyncListener),
#endif // SUPPORT_DATA_SYNC && CORE_BOOKMARKS_SUPPORT
#ifdef WEB_TURBO_MODE
m_webTurboUsageListener(&m_nullWebTurboUsageListener),
#endif // WEB_TURBO_MODE
#ifdef PI_SENSOR
m_sensorCalibrationListener(&m_nullSensorCalibrationListener),
#endif // PI_SENSOR
#ifdef GADGET_SUPPORT
m_gadgetListener(&m_nullGadgetListener),
#endif
#ifdef SEARCH_PROVIDER_QUERY_SUPPORT
m_searchProviderListener(&m_nullSearchProviderListener),
#endif //SEARCH_PROVIDER_QUERY_SUPPORT
m_idleStateChangedListener(&m_nullIdleStateChangedListener),
#ifdef WIC_TAB_API_SUPPORT
m_tab_api_listener(&m_null_tab_api_listener),
#endif // WIC_TAB_API_SUPPORT
m_oomListener(&m_nullOomListener)
{
CONST_ARRAY_INIT(wic_charsets);
}
WindowCommanderManager::~WindowCommanderManager()
{
#ifdef WINDOW_COMMANDER_TRANSFER
OP_DELETE(m_transferManager);
#endif // WINDOW_COMMANDER_TRANSFER
g_idle_detector->RemoveListener(this);
}
OP_STATUS WindowCommanderManager::GetWindowCommander(OpWindowCommander** windowCommander)
{
WindowCommander* wc = OP_NEW(WindowCommander, ());
if (wc == NULL)
{
g_memory_manager->RaiseCondition(OpStatus::ERR_NO_MEMORY);
return OpStatus::ERR_NO_MEMORY;
}
OP_STATUS status = wc->Init();
if (OpStatus::IsError(status))
{
if (status == OpStatus::ERR_NO_MEMORY)
{
g_memory_manager->RaiseCondition(status);
}
OP_DELETE(wc);
return status;
}
*windowCommander = (OpWindowCommander*)wc;
return OpStatus::OK;
}
void WindowCommanderManager::ReleaseWindowCommander(OpWindowCommander* windowCommander)
{
OP_DELETE(windowCommander);
}
void WindowCommanderManager::SetUiWindowListener(OpUiWindowListener* listener)
{
if (listener == NULL)
{
m_uiWindowListener = &m_nullUiWindowListener;
}
else
{
m_uiWindowListener = listener;
}
}
#ifdef APPLICATION_CACHE_SUPPORT
OP_STATUS WindowCommanderManager::GetAllApplicationCacheEntries(OpVector<OpApplicationCacheEntry>& all_app_caches)
{
if (g_application_cache_manager)
return g_application_cache_manager->GetAllApplicationCacheEntries(all_app_caches);
return OpStatus::OK;
}
OP_STATUS WindowCommanderManager::DeleteApplicationCache(const uni_char *manifest_url)
{
if (g_application_cache_manager)
return g_application_cache_manager->DeleteApplicationCacheGroup(manifest_url);
return OpStatus::OK;
}
OP_STATUS WindowCommanderManager::DeleteAllApplicationCaches()
{
if (g_application_cache_manager)
return g_application_cache_manager->DeleteAllApplicationCacheGroups();
return OpStatus::OK;
}
#endif // APPLICATION_CACHE_SUPPORT
#if defined _SSL_SUPPORT_ && defined _NATIVE_SSL_SUPPORT_ || defined WIC_USE_SSL_LISTENER
void WindowCommanderManager::SetSSLListener(OpSSLListener* listener)
{
if (listener == NULL)
{
m_sslListener = &m_nullSslListener;
}
else
{
m_sslListener = listener;
}
// Set the listener for all windows
for(Window* win = g_windowManager->FirstWindow(); win; win = win->Suc())
{
if (win->GetWindowCommander())
{
win->GetWindowCommander()->SetSSLListener(m_sslListener);
}
}
}
#endif // _SSL_SUPPORT_ && _NATIVE_SSL_SUPPORT_ || WIC_USE_SSL_LISTENER
#ifdef WINDOW_COMMANDER_TRANSFER
OpTransferManager* WindowCommanderManager::GetTransferManager()
{
if (m_transferManager == NULL)
{
m_transferManager = OP_NEW(TransferManager, ());
if (m_transferManager == NULL)
{
g_memory_manager->RaiseCondition(OpStatus::ERR_NO_MEMORY);
}
}
return m_transferManager;
}
#endif // WINDOW_COMMANDER_TRANSFER
void WindowCommanderManager::SetAuthenticationListener(OpAuthenticationListener* listener)
{
m_authenticationListener = listener;
if (m_authenticationListener == NULL)
{
m_authenticationListener = &m_nullAuthenticationListener;
}
}
void WindowCommanderManager::SetIdleStateChangedListener(OpIdleStateChangedListener* listener)
{
g_idle_detector->RemoveListener(this);
if (listener == NULL)
{
m_idleStateChangedListener = &m_nullIdleStateChangedListener;
}
else
{
m_idleStateChangedListener = listener;
g_idle_detector->AddListener(this);
}
}
/* virtual */ OP_STATUS
WindowCommanderManager::OnActivityStateChanged(OpActivityState state)
{
if (state == ACTIVITY_STATE_IDLE)
m_idleStateChangedListener->OnIdle();
else if (state == ACTIVITY_STATE_BUSY)
m_idleStateChangedListener->OnNotIdle();
return OpStatus::OK;
}
void WindowCommanderManager::SetOomListener(OpOomListener* listener)
{
if (listener == NULL)
{
m_oomListener = &m_nullOomListener;
}
else
{
m_oomListener = listener;
}
}
#if defined SUPPORT_DATA_SYNC && defined CORE_BOOKMARKS_SUPPORT
void WindowCommanderManager::SetDataSyncListener(OpDataSyncListener* listener)
{
m_dataSyncListener = listener ? listener : &m_nullDataSyncListener;
}
#endif // SUPPORT_DATA_SYNC && CORE_BOOKMARKS_SUPPORT
#ifdef WEB_TURBO_MODE
void WindowCommanderManager::SetWebTurboUsageListener(OpWebTurboUsageListener* listener)
{
m_webTurboUsageListener = listener ? listener : &m_nullWebTurboUsageListener;
}
#endif // WEB_TURBO_MODE
#ifdef PI_SENSOR
void WindowCommanderManager::SetSensorCalibrationListener(OpSensorCalibrationListener *listener)
{
m_sensorCalibrationListener = listener ? listener : &m_nullSensorCalibrationListener;
}
#endif //PI_SENSOR
#ifdef GADGET_SUPPORT
void WindowCommanderManager::SetGadgetListener(OpGadgetListener* listener)
{
if (m_gadgetListener && m_gadgetListener != &m_nullGadgetListener)
g_gadget_manager->DetachListener(m_gadgetListener);
m_gadgetListener = listener ? listener : &m_nullGadgetListener;
if (listener)
OpStatus::Ignore(g_gadget_manager->AttachListener(listener));
}
#endif // GADGET_SUPPORT
#ifdef SEARCH_PROVIDER_QUERY_SUPPORT
void WindowCommanderManager::SetSearchProviderListener(OpSearchProviderListener* listener)
{
m_searchProviderListener = listener ? listener : &m_nullSearchProviderListener;
}
#endif // SEARCH_PROVIDER_QUERY_SUPPORT
#ifdef WIC_TAB_API_SUPPORT
/* virtual */ void
WindowCommanderManager::SetTabAPIListener(OpTabAPIListener* listener)
{
m_tab_api_listener = listener ? listener : &m_null_tab_api_listener;
}
#endif // WIC_TAB_API_SUPPORT
/* static */
OpWindowCommanderManager* OpWindowCommanderManager::CreateL()
{
return OP_NEW_L(WindowCommanderManager, ());
}
#ifdef DATABASE_MODULE_MANAGER_SUPPORT
#include "modules/database/ps_commander.h"
/*virtual*/PersistentStorageCommander*
WindowCommanderManager::GetPersistentStorageCommander()
{
return PersistentStorageCommander::GetInstance();
}
#endif //DATABASE_MODULE_MANAGER_SUPPORT
/*virtual*/
void WindowCommanderManager::ClearPrivateData(int option_flags)
{
if (option_flags & WIC_OPERA_CLEAR_MEMORY_CACHE)
{
extern void NondestructiveOutOfMemoryFlush();
NondestructiveOutOfMemoryFlush();
}
if (option_flags & WIC_OPERA_CLEAR_IMAGE_CACHE && imgManager && g_memory_manager)
{
// Clear the image cache by setting the cache size to 0 and
// back again.
// FIXME: We need a proper api for this.
imgManager->SetCacheSize(0, IMAGE_CACHE_POLICY_SOFT);
imgManager->SetCacheSize(g_memory_manager->GetMaxImgMemory(), IMAGE_CACHE_POLICY_SOFT);
}
#ifdef SUPPORT_GENERATE_THUMBNAILS
if (option_flags & WIC_OPERA_CLEAR_THUMBNAILS)
OpStatus::Ignore(g_thumbnail_manager->Purge());
#endif // SUPPORT_GENERATE_THUMBNAILS
BOOL visited_links = option_flags & WIC_OPERA_CLEAR_VISITED_LINKS ?TRUE:FALSE;
BOOL disk_cache = option_flags & WIC_OPERA_CLEAR_DISK_CACHE ?TRUE:FALSE;
BOOL sensitive_data = option_flags & WIC_OPERA_CLEAR_SENSITIVE_DATA ?TRUE:FALSE;
BOOL cookies = option_flags & WIC_OPERA_CLEAR_ALL_COOKIES ?TRUE:FALSE;
BOOL session_cookies= option_flags & WIC_OPERA_CLEAR_SESSION_COOKIES?TRUE:FALSE;
BOOL memory_cache = option_flags & WIC_OPERA_CLEAR_MEMORY_CACHE ?TRUE:FALSE;
if (option_flags & (WIC_OPERA_CLEAR_VISITED_LINKS
| WIC_OPERA_CLEAR_DISK_CACHE
| WIC_OPERA_CLEAR_SENSITIVE_DATA
| WIC_OPERA_CLEAR_ALL_COOKIES
| WIC_OPERA_CLEAR_SESSION_COOKIES)
&& g_url_api)
{
if (visited_links || disk_cache)
g_url_api->CleanUp(); // close all connections
g_url_api->PurgeData(visited_links,
disk_cache,
sensitive_data,
session_cookies,
cookies,
FALSE, /* certificate */
memory_cache);
}
if (option_flags & WIC_OPERA_CLEAR_GLOBAL_HISTORY)
{
#ifdef HISTORY_SUPPORT
g_globalHistory->DeleteAllItems();
#endif
#ifdef DIRECT_HISTORY_SUPPORT
g_directHistory->DeleteAllItems();
#endif
}
#ifdef OPERA_CONSOLE
if (option_flags & WIC_OPERA_CLEAR_CONSOLE)
g_console->Clear();
#endif
#ifdef DATABASE_MODULE_MANAGER_SUPPORT
if (GetPersistentStorageCommander())
{
if (option_flags & WIC_OPERA_CLEAR_WEBDATABASES)
GetPersistentStorageCommander()->DeleteWebDatabases(PersistentStorageCommander::ALL_CONTEXT_IDS);
if (option_flags & WIC_OPERA_CLEAR_WEBSTORAGE)
GetPersistentStorageCommander()->DeleteWebStorage(PersistentStorageCommander::ALL_CONTEXT_IDS);
if (option_flags & WIC_OPERA_CLEAR_EXTENSION_STORAGE)
GetPersistentStorageCommander()->DeleteExtensionData(PersistentStorageCommander::ALL_CONTEXT_IDS);
}
#endif //DATABASE_MODULE_MANAGER_SUPPORT
#ifdef APPLICATION_CACHE_SUPPORT
if (option_flags & WIC_OPERA_CLEAR_APPCACHE && g_application_cache_manager)
{
OpStatus::Ignore(g_application_cache_manager->DeleteAllApplicationCacheGroups());
}
#endif // APPLICATION_CACHE_SUPPORT
#ifdef GEOLOCATION_SUPPORT
if (option_flags & WIC_OPERA_CLEAR_GEOLOCATION_PERMISSIONS)
{
g_secman_instance->ClearUserConsentPermissions(OpSecurityManager::PERMISSION_TYPE_GEOLOCATION);
}
#endif // GEOLOCATION_SUPPORT
#ifdef DOM_STREAM_API_SUPPORT
if (option_flags & WIC_OPERA_CLEAR_CAMERA_PERMISSIONS)
{
g_secman_instance->ClearUserConsentPermissions(OpSecurityManager::PERMISSION_TYPE_CAMERA);
}
#endif // DOM_STREAM_API_SUPPORT
#if defined(PREFS_GETOVERRIDDENHOSTS) && defined(PREFS_WRITE)
if (option_flags & WIC_OPERA_CLEAR_SITE_PREFS)
{
TRAPD(err, g_prefsManager->RemoveOverridesAllHostsL(TRUE));
}
#endif // defined(PREFS_GETOVERRIDDENHOSTS) && defined(PREFS_WRITE)
#ifdef _PLUGIN_SUPPORT_
if (option_flags & WIC_OPERA_CLEAR_PLUGIN_DATA)
OpStatus::Ignore(g_pluginhandler->GetPluginLibHandler()->ClearAllSiteData());
#endif // _PLUGIN_SUPPORT_
#ifdef CORS_SUPPORT
if (sensitive_data || (option_flags & WIC_OPERA_CLEAR_CORS_PREFLIGHT))
g_secman_instance->ClearCrossOriginPreflightCache();
#endif // CORS_SUPPORT
}
#ifdef MEDIA_PLAYER_SUPPORT
BOOL WindowCommanderManager::IsAssociatedWithVideo(OpMediaHandle handle)
{
return g_media_module.IsAssociatedWithVideo(handle);
}
#endif //MEDIA_PLAYER_SUPPORT
|
/********************************************************
Scene4 : debugging camera path
(free roaming to watch historical pos)
*******************************************************/
#include "Qwerty3D-PC.h"
using namespace Noise3D;
void Qwerty::Scene_DebuggingCameraPos::Init(Noise3D::IScene* pScene, Noise3D::Ut::IInputEngine* pInputE)
{
m_pRenderer = pScene->GetRenderer();
m_pAtmos = pScene->GetAtmosphere();
m_pCamera = pScene->GetCamera();
m_pGraphicObjMgr = pScene->GetGraphicObjMgr();
m_pChessboard = m_pGraphicObjMgr->CreateGraphicObj("scene4GO");
m_pRefInputE = pInputE;
}
void Qwerty::Scene_DebuggingCameraPos::UpdateAndRender()
{
mFunction_InputProcess();
m_pRenderer->ClearBackground();
//add to render list
m_pRenderer->SetActiveAtmosphere(m_pAtmos);
m_pRenderer->AddToRenderQueue(m_pChessboard);
m_pRenderer->Render();
m_pRenderer->PresentToScreen();
}
/********************************************************
PRIVATE
*******************************************************/
void Qwerty::Scene_DebuggingCameraPos::mFunction_InputProcess()
{
m_pRefInputE->Update();
if (m_pRefInputE->IsKeyPressed(Ut::NOISE_KEY_A))
{
m_pCamera->fps_MoveRight(-0.5f, FALSE);
}
if (m_pRefInputE->IsKeyPressed(Ut::NOISE_KEY_D))
{
m_pCamera->fps_MoveRight(0.5f, FALSE);
}
if (m_pRefInputE->IsKeyPressed(Ut::NOISE_KEY_W))
{
m_pCamera->fps_MoveForward(0.5f, FALSE);
}
if (m_pRefInputE->IsKeyPressed(Ut::NOISE_KEY_S))
{
m_pCamera->fps_MoveForward(-0.5f, FALSE);
}
if (m_pRefInputE->IsKeyPressed(Ut::NOISE_KEY_SPACE))
{
m_pCamera->fps_MoveUp(0.5f);
}
if (m_pRefInputE->IsKeyPressed(Ut::NOISE_KEY_LCONTROL))
{
m_pCamera->fps_MoveUp(-0.5f);
}
if (m_pRefInputE->IsMouseButtonPressed(Ut::NOISE_MOUSEBUTTON_LEFT))
{
m_pCamera->RotateY_Yaw((float)m_pRefInputE->GetMouseDiffX() / 200.0f);
m_pCamera->RotateX_Pitch((float)m_pRefInputE->GetMouseDiffY() / 200.0f);
}
}
|
#pragma once
#include "utils/ptts.hpp"
#include "proto/config_sundries.pb.h"
using namespace std;
namespace pc = proto::config;
namespace nora {
namespace config {
using sundries_ptts = ptts<pc::sundries>;
sundries_ptts& sundries_ptts_instance();
void sundries_ptts_set_funcs();
}
}
|
int64_t pow_Mod(int64_t x, int64_t n)
{
int64_t answer = 1;
int64_t now_pow = x;
while(n > 0)
{
if((n & 1 )== 1)
{
answer *= now_pow;
answer %= MODULO;
}
now_pow *= now_pow;
now_pow %= MODULO;
n >>= 1;
}
return answer;
}
int64_t fact(int64_t x)
{
int64_t answer = 1;
while(x > 0)
{
answer *= x;
answer %= MODULO;
x--;
}
return answer;
}
int64_t comb(int64_t n, int64_t k)
// $n C $k (mod $MODULO)
{
int64_t numerator = fact(n);
int64_t denominator_n = pow_Mod(fact(n-k), MODULO - 2);
int64_t denominator_k = pow_Mod(fact(k), MODULO - 2);
numerator = numerator * denominator_n % MODULO;
numerator = numerator * denominator_k % MODULO;
return numerator;
}
|
#include <stdio.h>
#include<stdlib.h>
/*programa que usa una funcion para almacenar numeros en un arrglo dinamico
posteriormente en otra funcion buscar un numero en particular*/
void leer_arreglo();
void buscar();
int *v1;
int num;
int main() {
leer_arreglo();
return 0;
}
void leer_arreglo(){
printf("Ingrese Tamaņo del Arreglo: ");
scanf("%d",&num);
v1=new int[num];
printf("\nIngrese Elementos del Arreglo: \n");
for(int i=0;i<num;i++){
scanf("%d",&v1[i]);
}
printf("\nMostrando Arreglo: \n");
for(int i=0;i<num;i++){
printf("%d ",*(v1+i));
}
buscar();
delete[]v1;
}
void buscar(){
int inf,sup,dato,mitad;
char band = 'F';
printf ("\nIngrese Elemento a buscar: \n");
scanf ("%d",&dato);
inf = 0;
sup = num;
while((inf <= sup) && (band == 'F')) {
mitad =((inf+sup)/2);
if(v1[mitad]==dato){
band = 'V';
}
else
if(v1[mitad]>dato){
sup = mitad - 1;
}
else{
inf = mitad + 1;
}
}
if(band == 'F'){
printf("\nEl Elemento no esta en el Arreglo.\n");
}
else if(band=='V'){
printf("\nElemento encontrado, en la pos: %i",mitad+1);
}
}
|
#include"iostream"
using namespace std;
int main()
{
int a,b,c[100],i;
cout<<" enter two numbers : ";
cin>>a>>b;
cout<<"Enter array values: ";
for(i=0;i<a;i++)
{
cin>>c[i];
}
cout<<c[b-1];
}
|
#include <iostream>
#include <vector>
#include <list>
#include <set>
#include <algorithm>
#include <sequtils.h>
using namespace std;
void print(int elem)
{
cout << elem << ' ';
}
int square(int x) { return x * x; }
int main(int argc, char *argv[])
{
vector<int> col;
set<int> v;
cout << "For each testing " << endl;
for (int i=0; i < 10; i++)
col.push_back(i);
for_each(col.begin(), col.end(), print);
cout << endl;
cout << "transform testing " << endl;
transform(col.begin(), col.end(),
inserter(v, v.end()),
square);
print_seq(v, "after\t");
col.erase(col.begin(), col.end());
v.erase(v.begin(), v.end());
list<int> lst;
for(int i=24; i <= 30; i++) lst.push_back(i);
print_seq(lst, "list\t");
list<int>::iterator pos;
pos = find_if (lst.begin(), lst.end(),
[](int x) {
int i = 2;
while (i < x / 2) {
if ((x % i) == 0) return false;
++i;
}
return true;
});
if (pos != lst.end()) {
cout << "prime number found " << *pos << endl;
} else {
cout << "No prime found in the given range " << endl;
}
return 0;
}
|
#include "RenderObject.h"
namespace Game
{
bool RenderObject::load(const char *path)
{
mObjLoader.loadObj(path, mMeshTransform);
}
MeshTransform &RenderObject::getMesh()
{
return mMeshTransform;
}
}
|
//Nanthana Thanonklin
//countHits.h
// countHits.h includes the prototype of countHits function so we
// can include from our main program,
// includes asteroid.h so we can use our definition(Asteroid)
#ifndef countHits_h
#define countHits_h
#include "asteroid.h"
#include <vector>
int countHits(std::vector<Asteroid> a);
#endif
|
#ifndef CLIENT_H
#define CLIENT_H
#include <QWidget>
#include <QAbstractSocket>
class QTcpSocket;
class QFile;
namespace Ui {
class Client;
}
class Client : public QWidget
{
Q_OBJECT
public:
explicit Client(QWidget *parent = 0);
~Client();
private slots:
void on_loginButton_clicked();
void on_exitButton_clicked();
void readMessage();
void disPlayError(QAbstractSocket::SocketError);
void on_regiButton_clicked();
void on_openButton_clicked();
void on_upButton_clicked();
void startUpload();
void updateUploadProgress(qint64 numBytes);
void on_searchButton_clicked();
void on_downButton_clicked();
void on_unDownButton_clicked();
private:
Ui::Client *ui;
QFile *qssFile;
//常量
const QString LOGOUT = "0"; //登出标记
const QString LOGINREQ = "1"; //登录标记
const QString REGIREQ = "2"; //注册标记
const QString LOGINSUCCESS = "01"; //登录成功
const QString LOGINPASSERROR = "02"; //登录密码错误
const QString LOGINIDNON = "03"; //登录用户名不存在
const QString REGISUCCESS = "11"; //注册成功
const QString REGIIDBLANKERROR = "12"; //注册时ID为空错误
const QString REGIPASSBLANKERROR = "13"; //注册时密码为空错误
const QString REGIIDEXIT = "14"; //注册用户名已存在
const QString UPDATE = "20"; //上传文件请求
const QString UPSTART = "21"; //开始上传消息
const QString UPREJ = "22"; //文件已存在,拒绝上传
const QString SEARCH = "30"; //查找文件
const QString FILEEXIST = "31"; //文件存在
const QString FILENONEXIST = "32"; //文件不存在
const QString FILENAMENON = "33"; //查找文件名为空
const QString DOWNSTART = "34"; //开始下载
const QString EXITAPP = "40"; //退出应用程序
const QString MESSNULL = "-1"; //空信息
//布局变量
void setMyLayout(); //栅格化初始布局
void loginView(); //登录界面
void actView(); //操作界面
void closeEvent(QCloseEvent *event); //点击x按钮
void openFile(); //打开要上传的文件
//网络文件变量
QTcpSocket *tcpClient;
qint64 messageSize; //接收到的信息大小
QString upFileName; //要上传文件名
qint64 upPerSize; //传送文件时每次传送的大小
qint64 upTotalBytes; //上传的文件总大小
qint64 upBytesWritten; //已上传大小
qint64 upBytesToWrite; //要上传的大小
bool isUploadingFile; //上传标记
QFile *fileToUpdate; //上传的文件
QByteArray upBlock; //上传缓冲区
QString downFileName; //下载文件的文件名
QString showDownFileName; //下载文件的文件名
bool isDownloadingFile; //下载状态
qint64 downTotalBytes; //总共下载大小
qint64 downBytesReceived; //已下载大小
qint64 downFileNameSize; //下载文件名大小
QFile *downLocalFile; //下载文件名
QByteArray downBlock; //下载缓冲区
void sendMessToServer(QString Mess, QString str1, QString str2); //发送请求到服务器
signals:
void startUploadSignal(); //开始上传的信号
};
#endif // CLIENT_H
|
/* Copyright 2015-2016 Whitewood Encryption Systems, Inc. */
#include "stdafx.h"
#include "config_parse.h"
#include "networksource.h"
#include "filesource.h"
#ifdef WNR_QRNG
#include "qrngsource.h"
#endif
#include "drbg.h"
#include "utilities.h"
#include "internal.h"
#include "wnr.h"
#include <libconfig.h>
#include <string.h>
static instream_default *
_build_instream_struct(config_setting_t *instream)
{
instream_default *rtnval = NULL;
enum t_instream type;
const char *type_str = NULL;
config_setting_lookup_string(instream, "type", &type_str);
CHECK(type_str, "Error parsing \"type\" for %s source.", instream->name);
type = get_instream_enum(type_str);
CHECK(type != -1, "Invalid %s type: %s.", instream->name, type_str);
int buffer_size = 0;
CHECK(config_setting_lookup_int(instream, "buffer_size", &buffer_size),
"Must set buffer size for %s source.", instream->name);
CHECK(buffer_size > 0,
"Buffer size of input stream must be greater than 0 for %s source.", instream->name);
int buffer_threshold = 0;
CHECK(config_setting_lookup_int(instream, "buffer_threshold", &buffer_threshold),
"Must set buffer threshold for %s source.", instream->name);
CHECK(buffer_threshold > 0,
"Buffer threshold of input stream must be greater than 0 for %s source.", instream->name);
CHECK(buffer_size > buffer_threshold,
"Buffer size must be greater than buffer threshold for %s source.", instream->name);
switch (type) {
case NETWORK:;
const char *client_id = NULL;
CHECK(config_setting_lookup_string(instream, "client_id", &client_id),
"Must set network entropy source client_id");
const char *address = NULL;
const char *hostname = NULL;
config_setting_lookup_string(instream, "address", &address);
if (!config_setting_lookup_string(instream, "hostname", &hostname)) {
CHECK(address != NULL,
"Must set network entropy source address");
hostname = address;
} else if (address == NULL) {
address = hostname;
}
int port;
CHECK(config_setting_lookup_int(instream, "port", &port),
"Must set networn entropy source port");
const char *uri = NULL;
CHECK(config_setting_lookup_string(instream, "URI", &uri),
"Must set networn entropy source URI");
char *hmac_key = NULL;
int static_key = config_setting_lookup_string(instream, "hmac_key", (const char**)&hmac_key);
int max_reconnects;
if (!config_setting_lookup_int(instream, "max_reconnects", &max_reconnects))
{
max_reconnects = 5; // default
}
wnr_hmac_key get_hmac_key = NULL;
rtnval = wnr_netsrc_create(client_id, address, hostname,
port, uri, get_hmac_key, max_reconnects,
buffer_size, buffer_threshold);
CHECK(rtnval, "Error creating network entropy source struct");
if (static_key == CONFIG_TRUE) {
unsigned char *hmac_key_bin = NULL;
size_t hmac_key_bin_len;
CHECK(base64_decode(hmac_key, strlen(hmac_key), &hmac_key_bin, &hmac_key_bin_len)
== WNR_ERROR_NONE,
"Error base64 decoding static HMAC key");
if (wnr_netsrc_set_static_hmac_key(rtnval, hmac_key_bin, hmac_key_bin_len)
!= WNR_ERROR_NONE) {
LOGERROR("Failed to set static HMAC key for instream source");
free(hmac_key_bin);
goto cleanup;
}
free(hmac_key_bin);
}
break;
case FILEPATH:;
const char *filepath = NULL;
CHECK(config_setting_lookup_string(instream, "path", &filepath),
"Must set file entropy source path");
rtnval = wnr_filesrc_create(filepath, buffer_size, buffer_threshold);
CHECK(rtnval, "Error creating file entropy source struct");
break;
#ifdef WNR_QRNG
case QRNG:;
const char *instance_name = NULL;
if (!config_setting_lookup_string(instream, "instance_name", &instance_name))
{
instance_name = "QRNG_DEFAULT";
}
rtnval = wnr_qrngsrc_create(instance_name, buffer_size, buffer_threshold);
CHECK(rtnval, "Error creating QRNG entropy source struct");
break;
#endif
default:
LOGERROR("Invalid entropy source specified");
goto cleanup;
}
return rtnval;
cleanup:
if (rtnval)
rtnval->destroy(rtnval);
return NULL;
}
static int
_wnr_parse_config(wnr_context *ctx, config_t *cfg)
{
config_setting_t *seed;
config_setting_t *stream;
enum t_drbg type;
const char *tmp;
long long itmp;
// NOTE: libconfig uses 1 as success and 0 as failure
CHECK(config_lookup_string(cfg, "WnrClient.dir.working", &(tmp)),
"Error parsing \"WnrClient.dir.working\".");
ctx->working_dir = strdup(tmp);
CHECK_MEM(ctx->working_dir);
CHECK(config_lookup_string(cfg, "WnrClient.dir.socket", &(tmp)),
"Error parsing \"WnrClient.dir.socket\".");
ctx->socket_dir = strdup(tmp);
CHECK_MEM(ctx->socket_dir);
CHECK(config_lookup_string(cfg, "WnrClient.drbg.type", &(tmp)),
"Error parsing \"WnrClient.drbg.spec\".");
type = get_drbg_enum(tmp);
switch(type) {
case SHA256:
((wnr_drbg_context*)ctx->drbg_cfg)->drbg_type = WNR_DRBG_SHA256;
break;
default:
LOGERROR("Invalid drbg type.");
goto cleanup;
}
CHECK(config_lookup_int64(cfg, "WnrClient.drbg.reseed_interval", &(itmp)),
"Error parsing \"WnrClient.drbg.reseed_rate\".");
if (itmp <= 0) {
LOGWARN(
"DRBG reseed interval was less than 1. Set reseed interval to 1.");
((wnr_drbg_context*)ctx->drbg_cfg)->reseed_interval = 1;
}
else {
((wnr_drbg_context*)ctx->drbg_cfg)->reseed_interval = itmp;
}
if(config_lookup_int64(cfg, "WnrClient.drbg.security_strength", &(itmp))) {
CHECK(itmp >= 0,
"DRBG security strength must be greater than or equal to zero.");
((wnr_drbg_context*)ctx->drbg_cfg)->security_strength = itmp;
}
else {
((wnr_drbg_context*)ctx->drbg_cfg)->security_strength = 256;
}
if (config_lookup_int64(cfg, "WnrClient.buffer.size", &(itmp))) {
CHECK(itmp <= MAXIMUM_ENTROPY_REQUEST && itmp >= 1024,
"Entropy buffer size must be less than or equal to %d and greater "
"than or equal to 1024",
MAXIMUM_ENTROPY_REQUEST);
ctx->_buf_size = itmp;
}
else {
ctx->_buf_size = MAXIMUM_ENTROPY_REQUEST;
}
if (config_lookup_int64(cfg, "WnrClient.buffer.threshold", &(itmp))) {
CHECK(itmp <= ctx->_buf_size && itmp > 0,
"Entropy buffer threshold level must be less than or equal to "
"entropy buffer size");
ctx->_buf_threshold = itmp;
}
else {
ctx->_buf_threshold = DEFAULT_ENTROPY_THRESHOLD;
}
if (config_lookup_int64(cfg, "WnrClient.polling.interval", &(itmp))) {
CHECK(itmp <= MAXIMUM_POLLING_INTERVAL && itmp >= MINIMUM_POLLING_INTERVAL,
"Polling interval must be at least 5 ms and at most 1 hour");
ctx->poll_interval = itmp;
}
else {
ctx->poll_interval = MINIMUM_POLLING_INTERVAL;
}
seed = config_lookup(cfg, "WnrClient.source.seed");
stream = config_lookup(cfg, "WnrClient.source.stream");
CHECK(seed || stream, "Must configure at least one entropy source");
if (seed) {
ctx->seed_source = _build_instream_struct(seed);
CHECK(ctx->seed_source, "Failed to build seed entropy source");
ctx->_generate_mode |= SEED_SOURCE;
}
if (stream) {
ctx->stream_source = _build_instream_struct(stream);
CHECK(ctx->stream_source, "Failed to build stream entropy source");
ctx->_generate_mode |= STREAM_SOURCE;
}
return WNR_ERROR_NONE;
cleanup:
return WNR_ERROR_GENERAL;
}
int
wnr_config_loadf(wnr_context *ctx, char *ctxfile)
{
FILE *fp = NULL;
fp = fopen(ctxfile, "r");
CHECK(fp, "Error opening \"%s\": %s.", ctxfile, strerror(errno));
CHECK(wnr_config_loadfp(ctx, fp) == WNR_ERROR_NONE,
"Error parsing configuration file.");
fclose(fp);
return WNR_ERROR_NONE;
cleanup:
if (fp) {
fclose(fp);
}
return WNR_ERROR_GENERAL;
}
int
wnr_config_loadfp(wnr_context *ctx, FILE *fp)
{
config_t cfg = {0};
config_init(&cfg);
CHECK(config_read(&cfg, fp),
"Error reading configuration file \"%s:%d\" - %s.",
config_error_file(&cfg),
config_error_line(&cfg),
config_error_text(&cfg));
CHECK(_wnr_parse_config(ctx, &cfg) == WNR_ERROR_NONE,
"Error parsing configuration file.");
config_destroy(&cfg);
return WNR_ERROR_NONE;
cleanup:
config_destroy(&cfg);
return WNR_ERROR_GENERAL;
}
int
wnr_config_loads(wnr_context *ctx, char *ctxstr)
{
config_t cfg = {0};
config_init(&cfg);
CHECK(config_read_string(&cfg, ctxstr),
"Error reading configuraton string at line %d: %s.",
config_error_line(&cfg),
config_error_text(&cfg));
CHECK(_wnr_parse_config(ctx, &cfg) == WNR_ERROR_NONE,
"Error parsing configuration text.");
config_destroy(&cfg);
return WNR_ERROR_NONE;
cleanup:
config_destroy(&cfg);
return WNR_ERROR_GENERAL;
}
|
/*
ID: stevenh6
TASK: preface
LANG: C++
*/
#include <string>
#include <fstream>
using namespace std;
ofstream fout ("preface.out");
ifstream fin ("preface.in");
int n;
int I, V, X, L, C, D, M = 0;
int main()
{
fin >> n;
int Im10[] = {0, 1, 2, 3, 1, 0, 1, 2, 3, 1};
int Vm10[] = {0, 0, 0, 0, 1, 1, 1, 1, 1, 0};
int Xm10[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
for (int i = 1; i <= n; i++) {
int mod10 = i % 10;
int mod100 = (i % 100) / 10;
int mod1000 = (i % 1000) / 100;
I += Im10[mod10];
V += Vm10[mod10];
X += Xm10[mod10] + Im10[mod100];
L += Vm10[mod100];
C += Xm10[mod100] + Im10[mod1000];
D += Vm10[mod1000];
M += Im10[i / 1000] + Xm10[mod1000];
}
if (I > 0) { fout << "I " << I << endl; }
if (V > 0) { fout << "V " << V << endl; }
if (X > 0) { fout << "X " << X << endl; }
if (L > 0) { fout << "L " << L << endl; }
if (C > 0) { fout << "C " << C << endl; }
if (D > 0) { fout << "D " << D << endl; }
if (M > 0) { fout << "M " << M << endl; }
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-1999 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#include "core/pch.h"
#include "modules/dom/src/domenvironmentimpl.h"
#include "modules/dom/src/domobj.h"
#include "modules/dom/src/domcore/domlocator.h"
#include "modules/dom/src/domcore/node.h"
/* static */ OP_STATUS
DOM_DOMLocator::Make(ES_Object *&location, DOM_EnvironmentImpl *environment, unsigned line, unsigned column, unsigned byteOffset, unsigned charOffset, DOM_Node *relatedNode, const uni_char *uri)
{
DOM_Runtime *runtime = environment->GetDOMRuntime();
ES_Value value;
DOM_Object *dom_location;
RETURN_IF_ERROR(DOM_Object::DOMSetObjectRuntime(dom_location = OP_NEW(DOM_Object, ()), runtime, runtime->GetObjectPrototype(), "DOMLocator"));
location = *dom_location;
DOM_Object::DOMSetNumber(&value, line);
RETURN_IF_ERROR(runtime->PutName(location, UNI_L("lineNumber"), value, PROP_READ_ONLY));
DOM_Object::DOMSetNumber(&value, column);
RETURN_IF_ERROR(runtime->PutName(location, UNI_L("columnNumber"), value, PROP_READ_ONLY));
DOM_Object::DOMSetNumber(&value, byteOffset);
RETURN_IF_ERROR(runtime->PutName(location, UNI_L("byteOffset"), value, PROP_READ_ONLY));
DOM_Object::DOMSetNumber(&value, charOffset);
RETURN_IF_ERROR(runtime->PutName(location, UNI_L("utf16Offset"), value, PROP_READ_ONLY));
DOM_Object::DOMSetObject(&value, relatedNode);
RETURN_IF_ERROR(runtime->PutName(location, UNI_L("relatedNode"), value, PROP_READ_ONLY));
DOM_Object::DOMSetString(&value, uri);
RETURN_IF_ERROR(runtime->PutName(location, UNI_L("uri"), value, PROP_READ_ONLY));
return OpStatus::OK;
}
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<cmath>
#define INF 0x3f3f3f3f
#define eps 1e-8
#define pi acos(-1.0)
using namespace std;
int f[10100],v[510],p[510];
int main() {
int t;
scanf("%d",&t);
while (t--) {
int v2,v1,n;
scanf("%d%d",&v1,&v2);
v2 -= v1;
scanf("%d",&n);
memset(f,INF,sizeof(f));f[0] = 0;
for (int i = 1;i <= n; i++) {
scanf("%d%d",&p[i],&v[i]);
for (int j = v[i];j <= v2; j++)
f[j] = min(f[j],f[j-v[i]] + p[i]);
}
if (f[v2] != INF) printf("The minimum amount of money in the piggy-bank is %d.\n",f[v2]);
else printf("This is impossible.\n");
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.