text
stringlengths 8
6.88M
|
|---|
#include "githabic.h"
#include <iostream>
using namespace std;
int task3(){
int x,y;
cout << "Used task 21 (IF) from Abramyan book" << endl;
cout << "Enter your coordinates (x,y):" << endl;
cin >> x >> y;
if ((x == 0) && (y == 0)){
cout << 0;
}
else {
if (x != 0){
if (y != 0) cout << 3;
else cout << 2;
}
else{
cout << 1;
}
}
}
|
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <cassert>
#include <list>
#include <boost/type_traits.hpp>
#include <boost/lambda/lambda.hpp>
#include "../util/Math.h"
BOOST_AUTO_TEST_SUITE (UtilTest);
BOOST_AUTO_TEST_CASE (testBasic)
{
BOOST_CHECK (Util::Math::nextSqr (1) == 1);
BOOST_CHECK (Util::Math::nextSqr (2) == 2);
BOOST_CHECK (Util::Math::nextSqr (3) == 4);
BOOST_CHECK (Util::Math::nextSqr (5) == 8);
BOOST_CHECK (Util::Math::nextSqr (9) == 16);
BOOST_CHECK (Util::Math::nextSqr (1000) == 1024);
BOOST_CHECK (Util::Math::nextSqr (1024) == 1024);
}
BOOST_AUTO_TEST_SUITE_END ();
|
#include "precompiled.h"
#include "script/script.h"
#include "input/jsinput.h"
#include "input/input.h"
#include "input/bind.h"
#include "script/jsfunction.h"
namespace jsinput
{
typedef jsscript::jsfunction<void(int, int)> JSBindFunctionCall;
void init(void);
void release(void);
JSBool jsbind(JSContext *cx, uintN argc, jsval *vp);
JSBool jsunbind(JSContext *cx, uintN argc, jsval *vp);
}
REGISTER_STARTUP_FUNCTION(jsinput, jsinput::init, 10);
void jsinput::init()
{
script::gScriptEngine->AddFunction("bind", 2, jsinput::jsbind);
script::gScriptEngine->AddFunction("unbind", 1, jsinput::jsunbind);
}
JSBool jsinput::jsbind(JSContext *cx, uintN argc, jsval *vp)
{
if (argc < 2)
{
script::gScriptEngine->ReportError("bind() takes 2+ arguments");
return JS_FALSE;
}
int key;
char* function;
input::KEY_STATE state = input::STATE_PRESSED;
JS_ValueToInt32(cx, JS_ARGV(cx,vp)[0], (int32*)&key);
if (JSVAL_IS_OBJECT(JS_ARGV(cx,vp)[1]) && JS_ObjectIsFunction(cx, JSVAL_TO_OBJECT(JS_ARGV(cx,vp)[1])))
{
if (argc == 3)
JS_ValueToInt32(cx, JS_ARGV(cx,vp)[2], (int32*)&state);
shared_ptr<JSBindFunctionCall> call(new JSBindFunctionCall(cx, NULL, JS_ARGV(cx,vp)[1]));
input::bindKey(key, bind(&JSBindFunctionCall::operator(), call, _1, _2), state);
}
else if ((argc >= 3) && JSVAL_IS_OBJECT(JS_ARGV(cx,vp)[1]) && JSVAL_IS_OBJECT(JS_ARGV(cx,vp)[2]) && JS_ObjectIsFunction(cx, JSVAL_TO_OBJECT(JS_ARGV(cx,vp)[2])))
{
if (argc == 4)
JS_ValueToInt32(cx, JS_ARGV(cx,vp)[3], (int32*)&state);
shared_ptr<JSBindFunctionCall> call(new JSBindFunctionCall(cx, JSVAL_TO_OBJECT(JS_ARGV(cx,vp)[1]), JS_ARGV(cx,vp)[2]));
input::bindKey(key, bind(&JSBindFunctionCall::operator(), call, _1, _2), state);
}
else
{
char* function = JS_GetStringBytes(JS_ValueToString(cx, JS_ARGV(cx,vp)[1]));
input::bindKey(key, function);
}
return JS_TRUE;
}
JSBool jsinput::jsunbind(JSContext *cx, uintN argc, jsval *vp)
{
if (argc != 1)
{
script::gScriptEngine->ReportError("unbind() takes 1 argument");
return JS_FALSE;
}
int key;
JS_ValueToInt32(cx, JS_ARGV(cx,vp)[0], (int32*)&key);
input::unbind(key);
return JS_TRUE;
}
|
#ifndef _validity_h_
#define _validity_h_
#include "clustering.h"
#include "AbstractMetric.h"
struct ThreadDistanceData {
public:
ThreadDistanceData(Cluster *, Cluster *, AbstractMetric *);
static void* threaded_distance(void*);
float distance();
Cluster* pCluster1;
Cluster* pCluster2;
AbstractMetric *pMetric;
private:
float _distance;
};
class Validity {
public:
static float dunn(Clustering &, AbstractMetric *);
static float bezderk(Clustering &, AbstractMetric *);
};
#endif
|
// StatusDialog.cpp : 实现文件
//
#include "stdafx.h"
#include "OgreEditor.h"
#include "Editor.h"
#include "StatusDialog.h"
// CStatusDialog 对话框
IMPLEMENT_DYNAMIC(CStatusDialog, CDialog)
CStatusDialog::CStatusDialog(CWnd* pParent /*=NULL*/)
: CDialog(CStatusDialog::IDD, pParent), mX(0.0f), mY(0.0f), mZ(0.0f), mfTopSpeed(180.0f)
{
mToolName = "";
}
CStatusDialog::~CStatusDialog()
{
}
void CStatusDialog::SetToolName( const CString& name )
{
mToolName = name;
UpdateData(FALSE);
}
void CStatusDialog::SetEditPos( Vector3& pos )
{
mX = pos.x;
mY = pos.y;
mZ = pos.z;
UpdateData(FALSE);
}
void CStatusDialog::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDITTOOL_NAME, mToolName);
DDX_Text(pDX, IDC_X_EDIT, mX);
DDX_Text(pDX, IDC_Y_EDIT, mY);
DDX_Text(pDX, IDC_Z_EDIT, mZ);
DDX_Control(pDX, IDC_SPIN, mSpeedSpinButton);
DDX_Control(pDX, IDC_EDIT_SPIN, mSpeedEdit);
DDX_Text(pDX, IDC_EDIT_SPIN, mfTopSpeed);
}
BOOL CStatusDialog::OnInitDialog()
{
CDialog::OnInitDialog();
//mSpeedSpinButton.SetBuddy( &mSpeedEdit );
return TRUE;
}
void CStatusDialog::OnOK()
{
UpdateData();
mfTopSpeed = Math::Clamp(mfTopSpeed, 1.0f, 500.0f);
UpdateData(FALSE);
SetEditorTopSpeed(mfTopSpeed);
}
void CStatusDialog::OnCancel()
{
}
BEGIN_MESSAGE_MAP(CStatusDialog, CDialog)
ON_WM_CREATE()
ON_NOTIFY(UDN_DELTAPOS, IDC_SPIN, &CStatusDialog::OnDeltaposSpin)
ON_EN_CHANGE(IDC_EDIT_SPIN, &CStatusDialog::OnEnChangeEditSpin)
END_MESSAGE_MAP()
// CStatusDialog 消息处理程序
int CStatusDialog::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
// TODO: Remove this lihe if you don't want intelligent menus.
if (CDialog::OnCreate(lpCreateStruct) == -1)
return -1;
GetEditor()->SetStatusDialog( this );
return 0;
}
void CStatusDialog::OnDeltaposSpin(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMUPDOWN pNMUpDown = reinterpret_cast<LPNMUPDOWN>(pNMHDR);
// TODO: 在此添加控件通知处理程序代码
if(pNMUpDown->iDelta > 0)
{
mfTopSpeed -= pNMUpDown->iDelta * 1.0f;
}
else if(pNMUpDown->iDelta < 0)
{
mfTopSpeed -= pNMUpDown->iDelta * 1.0f;
}
mfTopSpeed = Math::Clamp(mfTopSpeed, 1.0f, 500.0f);
CString log;
log.Format( "Delta = %d", pNMUpDown->iDelta );
GetEditor()->Log(log);
UpdateData(FALSE);
*pResult = 0;
}
void CStatusDialog::OnEnChangeEditSpin()
{
// TODO: 如果该控件是 RICHEDIT 控件,则它将不会
// 发送该通知,除非重写 CDialog::OnInitDialog()
// 函数并调用 CRichEditCtrl().SetEventMask(),
// 同时将 ENM_CHANGE 标志“或”运算到掩码中。
// TODO: 在此添加控件通知处理程序代码
UpdateData();
mfTopSpeed = Math::Clamp(mfTopSpeed, 1.0f, 500.0f);
SetEditorTopSpeed(mfTopSpeed);
}
void CStatusDialog::SetEditorTopSpeed( Ogre::Real speed )
{
GetEditor()->SetTopSpeed(speed);
}
|
#include "stdafx.h"
#include "cutBoneGroupDlg.h"
#include "afxdialogex.h"
#include "groupCutManager.h"
#include "MainControl.h"
IMPLEMENT_DYNAMIC(cutBoneGroupDlg, CDialogEx)
cutBoneGroupDlg::cutBoneGroupDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(cutBoneGroupDlg::IDD, pParent)
{
}
cutBoneGroupDlg::~cutBoneGroupDlg()
{
}
void cutBoneGroupDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_COMBO1, boneGoupListBox);
DDX_Control(pDX, IDC_EDIT1, poseCurIdxText);
DDX_Control(pDX, IDC_EDIT2, PoseTotalText);
DDX_Control(pDX, IDC_EDIT3, curIdxInPoseText);
DDX_Control(pDX, IDC_EDIT4, totalIdxInPoseText);
DDX_Control(pDX, IDC_EDIT6, weightVolume);
DDX_Control(pDX, IDC_EDIT8, weightHash);
DDX_Control(pDX, IDC_EDIT5, weightCB);
DDX_Control(pDX, IDC_EDIT9, volumeError);
DDX_Control(pDX, IDC_EDIT10, CBError);
DDX_Control(pDX, IDC_EDIT11, hashError);
DDX_Control(pDX, IDC_EDIT12, overallError);
}
BEGIN_MESSAGE_MAP(cutBoneGroupDlg, CDialogEx)
ON_CBN_SELENDOK(IDC_COMBO1, &cutBoneGroupDlg::OnCbnSelchangeBoneGoup)
ON_BN_CLICKED(IDC_BUTTON1, &cutBoneGroupDlg::previousPose)
ON_BN_CLICKED(IDC_BUTTON2, &cutBoneGroupDlg::nextPoseClick)
ON_BN_CLICKED(IDC_BUTTON3, &cutBoneGroupDlg::previousConfigureClick)
ON_BN_CLICKED(IDC_BUTTON4, &cutBoneGroupDlg::NextCongifureClick)
ON_BN_CLICKED(IDC_BUTTON5, &cutBoneGroupDlg::AcceptClick)
ON_BN_CLICKED(IDC_BUTTON7, &cutBoneGroupDlg::OnSort)
ON_BN_CLICKED(IDOK, &cutBoneGroupDlg::OnBnClickedOk)
END_MESSAGE_MAP()
void cutBoneGroupDlg::OnCbnSelchangeBoneGoup()
{
std::cout << "bone index: " << boneGoupListBox.GetCurSel() << std::endl;
changeBoneSlect(boneGoupListBox.GetCurSel());
}
void cutBoneGroupDlg::previousPose()
{
CString stext;
poseCurIdxText.GetWindowText(stext);
int poseIndex = _ttoi(stext) - 1;
if (setPoseSelection(poseIndex)){
currentPoseIndex = poseIndex;
}
}
void cutBoneGroupDlg::nextPoseClick()
{
CString stext;
poseCurIdxText.GetWindowText(stext);
int poseIndex = _ttoi(stext) + 1;
if (setPoseSelection(poseIndex)){
currentPoseIndex = poseIndex;
}
}
void cutBoneGroupDlg::previousConfigureClick()
{
CString stext;
curIdxInPoseText.GetWindowText(stext);
int curIdx = StrToInt(stext) - 1;
if (setselectIdxInPose(curIdx)){
currentConfigIndex = curIdx;
stext.Format(_T("%d"), currentConfigIndex);
curIdxInPoseText.SetWindowText(stext);
}
}
void cutBoneGroupDlg::NextCongifureClick()
{
CString stext;
curIdxInPoseText.GetWindowText(stext);
int curIdx = StrToInt(stext) + 1;
if (setselectIdxInPose(curIdx)){
currentConfigIndex = curIdx;
stext.Format(_T("%d"), currentConfigIndex);
curIdxInPoseText.SetWindowText(stext);
}
}
void cutBoneGroupDlg::updateDisplay(){
CString stext;
poseCurIdxText.GetWindowText(stext);
int curPoseIdx = _ttoi(stext);
curIdxInPoseText.GetWindowText(stext);
int curIdxInPose = StrToInt(stext);
int boneIdx = boneGoupListBox.GetCurSel();
}
void cutBoneGroupDlg::AcceptClick()
{
CString stext;
poseCurIdxText.GetWindowText(stext);
int curPoseIdx = _ttoi(stext);
curIdxInPoseText.GetWindowText(stext);
int curIdxInPose = StrToInt(stext);
int boneIdx = boneGoupListBox.GetCurSel();
idxChoosen[boneIdx] = Vec2i(curPoseIdx, curIdxInPose);
groupCutMngr->updateAcceptedIndexes(idxChoosen);
}
void cutBoneGroupDlg::Init(groupCutManager* _groupCutMngr)
{
groupCutMngr = _groupCutMngr;
std::vector<groupCut> *groupBoneArray = &groupCutMngr->boneGroupArray;
for (int i = 0; i < groupBoneArray->size(); i++){
idxChoosen.push_back(Vec2i(-1, -1));
boneGoupListBox.AddString(groupBoneArray->at(i).sourcePiece->boneName);
}
boneGoupListBox.ResetContent();
for (int i = 0; i < groupBoneArray->size(); i++){
CString name = groupBoneArray->at(i).sourcePiece->boneName;
boneGoupListBox.AddString(name);
}
boneGoupListBox.SetCurSel(0);
changeBoneSlect(0);
CString a;
a.Format(_T("%d"), 1);
weightVolume.SetWindowText(a);
a.Format(_T("%d"), 0);
weightHash.SetWindowText(a);
weightCB.SetWindowText(a);
currentPoseIndex = 0;
currentConfigIndex = 0;
}
void cutBoneGroupDlg::changeBoneSlect(int boneIdx)
{
// Refresh list box
std::vector<groupCut> *groupBoneArray = &groupCutMngr->boneGroupArray;
groupCut *curG = &groupBoneArray->at(boneIdx);
Vec2i selected = idxChoosen[boneIdx];
// pose
CString a;
a.Format(_T("%d"), curG->boxPose.poseMap.size()-1);
PoseTotalText.SetWindowText(a);
// int selectPoseIdx = selected[0] == -1 ? 0 : selected[0];
a.Format(_T("%d"), 0);
poseCurIdxText.SetWindowText(a);
// configuration
//int configInPoseIdx = selected[1] == -1 ? 0 : selected[1];
neighborPose* curP = curG->boxPose.sortedPoseMap.at(0);
a.Format(_T("%d"), curP->nodeGroupBoneCut.size()-1);
totalIdxInPoseText.SetWindowText(a);
a.Format(_T("%d"), 0);
curIdxInPoseText.SetWindowText(a);
// Update index
groupCutMngr->idx1 = 0;
groupCutMngr->idx2 = 0;
groupCutMngr->curBoneIdx = boneIdx;
}
bool cutBoneGroupDlg::setPoseSelection(int poseIdx)
{
std::vector<groupCut> *groupBoneArray = &groupCutMngr->boneGroupArray;
groupCut *curG = &groupBoneArray->at(boneGoupListBox.GetCurSel());
int configIndex = groupCutMngr->updatePoseConfigurationIdx(poseIdx, -1);
if (configIndex == -1){
return false;
}
else {
currentConfigIndex = configIndex;
}
neighborPose* pp = curG->boxPose.sortedPoseMap.at(poseIdx);
// Update text
CString a;
a.Format(_T("%d"), poseIdx);
poseCurIdxText.SetWindowText(a);
a.Format(_T("%d"), currentConfigIndex);
curIdxInPoseText.SetWindowText(a);
a.Format(_T("%d"), pp->nodeGroupBoneCut.size());
totalIdxInPoseText.SetWindowTextW(a);
return true;
}
bool cutBoneGroupDlg::setselectIdxInPose(int nodeIdxInPose)
{
std::vector<groupCut> *groupBoneArray = &groupCutMngr->boneGroupArray;
int boneIdxIdx = boneGoupListBox.GetCurSel();
groupCut *curG = &groupBoneArray->at(boneIdxIdx);
neighborPose* curP = curG->boxPose.sortedPoseMap.at(currentPoseIndex);
if (nodeIdxInPose < 0 || nodeIdxInPose >= curP->nodeGroupBoneCut.size()){
return false;
}
else {
currentConfigIndex = nodeIdxInPose;
}
int stubReceiveNodeIdx = groupCutMngr->updatePoseConfigurationIdx(currentPoseIndex, nodeIdxInPose);
return true;
}
void cutBoneGroupDlg::OnBnClickedOk()
{
// Check coord first
for (auto i : idxChoosen){
if (i[0] == -1 || i[1] == -1){
AfxMessageBox(_T("Not all bone groups configurations are locked."));
return;
}
}
groupCutMngr->updateAcceptedIndexes(idxChoosen);
CDialogEx::OnOK();
doc->changeState();
}
void cutBoneGroupDlg::OnSort(){
// Recalculate weight ratios and scores
CString csText;
GetDlgItemText(IDC_EDIT6, csText);
weights[0] = _tstof((LPCTSTR)csText);
GetDlgItemText(IDC_EDIT8, csText);
weights[1] = _tstof((LPCTSTR)csText);
GetDlgItemText(IDC_EDIT5, csText);
weights[2] = _tstof((LPCTSTR)csText);
groupCutMngr->updateSortEvaluations();
groupCutMngr->updatePoseConfigurationIdx(currentPoseIndex, currentConfigIndex);
}
void cutBoneGroupDlg::updateDisplayedOverallError(float value){
CString a;
a.Format(_T("%.2f"), value);
overallError.SetWindowText(a);
}
void cutBoneGroupDlg::updateDisplayedVolumeError(float value){
CString a;
a.Format(_T("%.2f"), value);
volumeError.SetWindowText(a);
}
void cutBoneGroupDlg::updateDisplayedHashError(float value){
CString a;
a.Format(_T("%.2f"), value);
hashError.SetWindowText(a);
}
void cutBoneGroupDlg::updateDisplayedCBError(float value){
CString a;
a.Format(_T("%.2f"), value);
CBError.SetWindowText(a);
}
|
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <memory.h>
#include <cmath>
#include <string>
#include <cstring>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
#include <complex>
#include <cassert>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
const int N = 1000111;
int buf[22];
int b[N];
int a[N];
LL f[N];
int main() {
//freopen(".in", "r", stdin);
//freopen(".out", "w", stdout);
int n;
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf("%d", &a[i]);
}
b[0] = b[1] = b[2] = 1;
for (int i = 2; i < n; ++i) {
if ( (a[i] <= a[i - 1] && a[i-1]>=a[i - 2]) || (a[i]>=a[i-1] && a[i-1]<=a[i-2])) {
if (a[i] == a[i - 1] && a[i-1] == a[i -2]) {
// No ok
} else {
b[i] = b[i - 1] = b[i-2] = 1;
}
}
}
b[n - 1] = b[n - 2] = b[n- 3] = 1;
int nn = 0;
for (int i = 0; i < n; ++i) if (b[i])
a[nn++] = a[i];
n = nn;
for (int i = 0; i < n; ++i) {
int mi = a[i];
int mx = a[i];
for (int j = i, it = 0; j >= 0 && it < 25; --j, ++it) {
mi = min(mi, a[j]);
mx = max(mx, a[j]);
f[i] = max(f[i], (j > 0 ? f[j - 1] : LL(0)) + (mx - mi));
}
}
cout << f[n - 1] << endl;
return 0;
}
|
#pragma once
#include "InetAddress.h"
#include <cassert>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
static const in_addr_t kInAddrAny = INADDR_ANY;
assert(sizeof(InetAddress) == sizeof(struct sockaddr_in));
InetAddress::InetAddress(uint16_t port)
{
bzero(&addr_, sizeof addr_);
addr_.sin_familiy = PF_INET:
addr_.sin_addr.s_addr =
}
|
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <cstring>
int n, m, ID[100000], indegree[100001], group[100001], ID_indexing;
std::vector<int> link[100000];
bool finished[100000];
std::vector<std::vector<int>> SCC;
std::stack<int> stk;
std::queue<int> q;
int dfs(int idx)
{
ID[idx] = ++ID_indexing;
stk.push(idx);
int parent = ID[idx];
for(auto next : link[idx])
{
if(ID[next] == 0)
{
parent = std::min(parent, dfs(next));
}
else if(!finished[next])
{
parent = std::min(parent, ID[next]);
}
}
if(parent == ID[idx])
{
std::vector<int> C;
int grp = SCC.size() + 1;
while(!stk.empty())
{
int top = stk.top();
stk.pop();
finished[top] = true;
C.push_back(top);
group[top] = grp;
if(top == idx)
{
break;
}
}
SCC.push_back(C);
}
return parent;
}
int main()
{
std::cin.sync_with_stdio(false);
std::cin.tie(NULL);
int t;
std::cin >> t;
while(t--)
{
std::cin >> n >> m;
std::memset(ID, 0, sizeof(ID));
std::memset(indegree, 0, sizeof(indegree));
std::memset(group, 0, sizeof(group));
for(int i = 0; i < 100000; i++)
{
link[i].clear();
}
std::memset(finished, 0, sizeof(finished));
SCC.clear();
while(!q.empty())
{
q.pop();
}
for(int i = 0; i < m; i++)
{
int A, B;
std::cin >> A >> B;
link[A].push_back(B);
}
for(int i = 0; i < n; i++)
{
if(ID[i] == 0)
{
dfs(i);
}
}
for(int i = 0; i < n; i++)
{
for(auto next : link[i])
{
if(group[i] != group[next])
{
indegree[group[next]]++;
}
}
}
int ans = -1;
for(int i = 1; i <= (int)SCC.size(); i++)
{
if(indegree[i] == 0)
{
ans = i;
q.push(i);
}
}
if(q.size() == 1)
{
while(!q.empty())
{
int front = q.front();
q.pop();
for(auto now : SCC[front - 1])
{
for(auto next : link[now])
{
if(group[now] != group[next])
{
indegree[group[next]]--;
if(indegree[group[next]] == 0)
{
q.push(group[next]);
}
}
}
}
}
for(int i = 1; i <= (int)SCC.size(); i++)
{
if(indegree[i] > 0)
{
ans = -1;
}
}
if(ans == -1)
{
std::cout << "Confused\n";
}
else
{
std::sort(SCC[ans - 1].begin(), SCC[ans - 1].end());
for(auto x : SCC[ans - 1])
{
std::cout << x << '\n';
}
}
}
else
{
std::cout << "Confused\n";
}
std::cout << '\n';
}
return 0;
}
|
#ifndef I2CMOTOR_H
#define I2CMOTOR_H
#include <Phantom.h>
#include <MotorBase.h>
#include "I2CRemoteIO.h"
class I2CMotor: public Phantom::MotorBase {
public:
I2CRemoteIO io;
I2CMotor(uint8_t address, uint8_t pinPWM, uint8_t pinDirA, uint8_t pinDirB);
void set(float speed);
void setMin(uint8_t min);
void setMax(uint8_t max);
void setBounds(uint8_t min, uint8_t max);
void disable();
private:
uint8_t pinPWM, pinDirA, pinDirB;
uint8_t min = 0, max = 255;
};
#endif
|
#include "player.hpp"
#include <cstdlib>
#include <algorithm>
#include <iterator>
#include <math.h>
#include <limits>
const int NUM_COLUMNS = 4;
const int NUM_ROWS = 4;
const int MAX_DEPTH = 3;
namespace TICTACTOE
{
int sumCols(const GameState &state, uint8_t player){
int sum = 0;
int counter = 0;
uint8_t opponent = (player == CELL_X) ? CELL_O : CELL_X;
bool isopponent = false;
bool me = false;
int counter_en = 0;
int counter_me = 0;
for(int i=0; i<NUM_COLUMNS; i++){
int tmp = 0;
counter_en = 0;
counter_me = 0;
isopponent = false;
me = false;
for(int j=0; j<NUM_ROWS; j++){
if(state.at(j,i) == opponent){ // there is already one opponent in the column
counter_en = counter_en+1;
tmp = -1*pow(10, counter_en);
isopponent = true;
}else if(state.at(j,i) == player){
me = true;
counter_me = counter_me+1;
tmp = pow(10, counter_me);
}
if (isopponent == true && me == true){
tmp = 0;
break;
}
}
sum += tmp;
}
return sum;
}
int sumRows(const GameState &state, uint8_t player){
int sum = 0;
uint8_t opponent = (player == CELL_X) ? CELL_O : CELL_X;
bool isopponent = false;
bool me = false;
int counter_en = 0;
int counter_me = 0;
for(int i=0;i<NUM_ROWS;i++){
int counter = 0;
counter_en = 0;
counter_me = 0;
int tmp = 0;
isopponent = false;
me = false;
for(int j=0;j<NUM_COLUMNS;j++){
if(state.at(i,j) == opponent){
counter_en = counter_en+1;
tmp = -1*pow(10, counter_en);
isopponent = true;
}else if(state.at(i,j) == player){ //I have one mark in the column
me = true;
counter_me = counter_me+1;
tmp = pow(10, counter_me);
}
if (isopponent == true && me == true){
tmp = 0;
break;
}
}
sum += tmp;
}
return sum;
}
int sumDiags(const GameState &state, uint8_t player){
int sum = 0;
uint8_t opponent = (player == CELL_X) ? CELL_O : CELL_X;
int counter_en = 0;
int counter_me = 0;
//1st diagonal
bool isopponent = false;
bool me = false;
int tmp = 0;
for(int i=0; i<NUM_COLUMNS; i++){
if(state.at(i,i) == opponent){
counter_en = counter_en+1;
tmp = -1*pow(10, counter_en);
isopponent = true;
}else if(state.at(i,i) == player){
me = true;
counter_me = counter_me+1;
tmp = pow(10, counter_me);
}
if (isopponent == true && me == true){
tmp = 0;
break;
}
}
sum += tmp;
//Second diagonal
isopponent = false;
counter_en = 0;
counter_me = 0;
me = false;
tmp = 0;
for(int i=0; i<NUM_COLUMNS; i++){
if(state.at(i,3-i) == opponent){
counter_en = counter_en+1;
tmp = -1*pow(10, counter_en);
isopponent = true;
}else if(state.at(i,3-i) == player){
me = true;
counter_me = counter_me+1;
tmp = pow(10, counter_me);
}
if (isopponent == true && me == true){
tmp = 0;
break;
}
}
sum += tmp;
return sum;
}
int gamma_function(const GameState &pState, uint8_t player)
{
//std::cerr << pState.toString(player) << std::endl;
if( pState.isXWin() == true ){
return 10000;
}else if( pState.isOWin() == true ){
return -10000;
}else if( pState.isDraw() == true){
return 0;
}else{
int value1 = sumDiags(pState, player);
int value2 = sumRows(pState, player);
int value3 = sumCols(pState, player);
std::cerr << " for diag: " << value1 << " for col: " << value3 << " for row: " << value2 << std::endl << std::endl;
return value1 + value2 + value3;
}
}
int algorithm(const GameState &pState, int alpha, int beta, uint8_t player, int depth)
{
int v = 0;
std::vector<GameState> lNextStates;
pState.findPossibleMoves(lNextStates); // returns a list of valid future states
if (lNextStates.size()==0 || depth==0) // TODO: Add another condition?
{
v = gamma_function(pState, player);
return v;
}
else{
if (player == CELL_X) // TODO: Check real uint8 assigned to A
{
//std::cerr << "NEXT POSSIBLE STATES PLAYER: " << lNextStates.size() << std::endl;
v = std::numeric_limits<int>::min();
for (int i=0; i<lNextStates.size(); i++){
v = std::max(v, algorithm(lNextStates[i], alpha, beta, CELL_O, depth-1));
alpha = std::max(v, alpha);
if (alpha >= beta)
{
break;
}
}
}
else { // Player B
//std::cerr << "NEXT POSSIBLE STATES ENEMY: " << lNextStates.size() << std::endl;
v = std::numeric_limits<int>::max();
for (int i=0; i<lNextStates.size(); i++){
v = std::min(v, algorithm(pState, alpha, beta, CELL_X, depth-1));
beta = std::min(beta,v);
if (alpha >= beta)
{
//std::cerr << "MIN B PLAYER: " << v << std::endl;
break;
}
}
}
}
return v;
}
GameState Player::play(const GameState &pState,const Deadline &pDue)
{
//std::cerr << "Processing " << pState.toMessage() << std::std::endl;
std::vector<GameState> lNextStates;
pState.findPossibleMoves(lNextStates); // returns a list of valid future states
//std::cerr << "NEXT POSSIBLE STATES: " << lNextStates.size() << std::endl;
// The initial depth is 0 and we set a variable MAX_DEPTH to the leaves of the tree we want to consider
if (lNextStates.size() == 0) return GameState(pState, Move());
/*
* Here you should write your clever algorithms to get the best next move, ie the best
* next state. This skeleton returns a random move instead.
*/
int values_childs = 0; // the evaluation of each of the childs, we will move to the one with the highest
//std::cerr << "CURRENT PLAYER: " << pState.getNextPlayer() << std::endl;
uint8_t next_player_id = (pState.getNextPlayer() == CELL_X) ? CELL_O : CELL_X;
//std::cerr << "NEXT PLAYER: " << next_player_id << std::endl;
int alpha = std::numeric_limits<int>::min();
int beta = std::numeric_limits<int>::max();
int max = std::numeric_limits<int>::min();
//int depth = 0;
int best_state = 0;
GameState wantedState;
for (GameState iter : lNextStates) //Iterate over possible future states
{
//std::cerr << "CHILD " << i << " of player "<< unsigned(pState.getNextPlayer()) << " has values: " << std::endl;
values_childs = algorithm(iter, alpha, beta, next_player_id, MAX_DEPTH); // current depth of the childs is 1 (0 for the parent)
//std::cerr << "CHILD " << i << " of player "<< unsigned(pState.getNextPlayer()) << " has value " << values_childs << std::endl <<std::endl;
if( values_childs > max){
max = values_childs;
wantedState = iter;
}
}
//return lNextStates[rand() % lNextStates.size()];
//std::cerr << "MOVE CHOOSEN: " << best_state.getMove() << std::endl;
std::cerr << pState.toString(pState.getNextPlayer()) << std::endl;
return wantedState;
}
/*namespace TICTACTOE*/ }
|
#ifndef AMVK_CMD_PASS_H
#define AMVK_CMD_PASS_H
#include "vulkan.h"
class CmdPass {
public:
CmdPass(const VkDevice& vkDevice, const VkCommandPool& vkCommandPool, const VkQueue& vkQueue);
~CmdPass();
VkCommandBuffer buffer;
private:
const VkDevice& mVkDevice;
const VkCommandPool& mVkCommandPool;
const VkQueue& mVkQueue;
};
#endif
|
#ifndef MENUITEM_H
#define MENUITEM_H
#include <Windows.h>
#include <string>
#include "..\Caller.h"
// base class from which all items in a menu are derived
class MenuItem
{
public:
MenuItem(std::string itemText, UINT id = 0);
virtual ~MenuItem();
const std::string text;
const UINT id;
virtual void onClick() = 0;
virtual bool insertControl(HMENU insertInto, UINT index) = 0;
virtual bool updateControl(HMENU updateFrom, UINT index) = 0;
private:
MenuItem();
};
#endif // MENUITEM_H
|
/*
Write a program that asks the user to enter the monthly costs for the following
expenses incurred from operating his or her automobile: loan payment, insurance,
gas, oil, tires, and maintenance. The program should then display the total
monthly cost of these expenses, and the total annual cost of these expenses.
Author: Aaron Maynard
*/
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
double loanPayment, insurance, gas, oil, tires, maintenance;
double monthlyTotal, annualTotal;
cout << "Enter your monthly loan payment: ";
cin >> loanPayment;
cout << "Enter your monthly insurance: ";
cin >> insurance;
cout << "Enter your monthly gas expense: ";
cin >> gas;
cout << "Enter your monthly oil expenses: ";
cin >> oil;
cout << "Enter your monthly tires expenses: ";
cin >> tires;
cout << "Enter your monthly maintenance expenses: ";
cin >> maintenance;
monthlyTotal = loanPayment + insurance + gas + oil + tires + maintenance;
annualTotal = monthlyTotal * 12;
cout << setprecision(2) << fixed;
cout << endl;
cout << "Your total monthly expenses are: $" << monthlyTotal << endl;
cout << "Your total annual expenses are: $" << annualTotal << endl << endl;
return 0;
}
|
#ifndef _AllinProc_H_
#define _AllinProc_H_
#include "BaseProcess.h"
class Table;
class Player;
class AllinProc :public BaseProcess
{
public:
AllinProc();
virtual ~AllinProc();
int doRequest(CDLSocketHandler* clientHandler, InputPacket* inputPacket, Context* pt);
int doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket, Context* pt);
private:
int sendAllinInfoToPlayers(Player* player, Table* table, Player* betcallplayer, int64_t betmoney,Player* nextplayer,short seq);
};
#endif
|
/*********************************************************\
* 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include "OpenGLRenderer/Texture/TextureCubeDsa.h"
#include "OpenGLRenderer/Mapping.h"
#include "OpenGLRenderer/Extensions.h"
#include "OpenGLRenderer/OpenGLRenderer.h"
#include "OpenGLRenderer/OpenGLRuntimeLinking.h"
#include <Renderer/IAssert.h>
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace OpenGLRenderer
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
TextureCubeDsa::TextureCubeDsa(OpenGLRenderer& openGLRenderer, uint32_t width, uint32_t height, Renderer::TextureFormat::Enum textureFormat, const void* data, uint32_t flags) :
TextureCube(openGLRenderer, width, height)
{
// Sanity checks
RENDERER_ASSERT(openGLRenderer.getContext(), 0 == (flags & Renderer::TextureFlag::DATA_CONTAINS_MIPMAPS) || nullptr != data, "Invalid OpenGL texture parameters")
RENDERER_ASSERT(openGLRenderer.getContext(), (flags & Renderer::TextureFlag::RENDER_TARGET) == 0 || nullptr == data, "OpenGL render target textures can't be filled using provided data")
#ifndef OPENGLRENDERER_NO_STATE_CLEANUP
// Backup the currently set alignment
GLint openGLAlignmentBackup = 0;
glGetIntegerv(GL_UNPACK_ALIGNMENT, &openGLAlignmentBackup);
#endif
// Set correct unpack alignment
glPixelStorei(GL_UNPACK_ALIGNMENT, (Renderer::TextureFormat::getNumberOfBytesPerElement(textureFormat) & 3) ? 1 : 4);
// Calculate the number of mipmaps
const bool dataContainsMipmaps = (flags & Renderer::TextureFlag::DATA_CONTAINS_MIPMAPS);
const bool generateMipmaps = (!dataContainsMipmaps && (flags & Renderer::TextureFlag::GENERATE_MIPMAPS));
const uint32_t numberOfMipmaps = (dataContainsMipmaps || generateMipmaps) ? getNumberOfMipmaps(width, height) : 1;
mGenerateMipmaps = (generateMipmaps && (flags & Renderer::TextureFlag::RENDER_TARGET));
// Create the OpenGL texture instance
// TODO(co) "GL_ARB_direct_state_access" AMD graphics card driver bug ahead
// -> AMD graphics card: 13.02.2017 using Radeon software 17.1.1 on MS Windows: Looks like "GL_ARB_direct_state_access" is broken when trying to use "glCompressedTextureSubImage3D()" for upload
// -> Describes the same problem: https://community.amd.com/thread/194748 - "Upload data to GL_TEXTURE_CUBE_MAP with glTextureSubImage3D (DSA) broken ?"
#ifdef WIN32
const bool isArbDsa = false;
#else
const bool isArbDsa = openGLRenderer.getExtensions().isGL_ARB_direct_state_access();
#endif
if (isArbDsa)
{
glCreateTextures(GL_TEXTURE_CUBE_MAP, 1, &mOpenGLTexture);
}
else
{
glGenTextures(1, &mOpenGLTexture);
}
// Upload the texture data
if (Renderer::TextureFormat::isCompressed(textureFormat))
{
// Did the user provided data containing mipmaps from 0-n down to 1x1 linearly in memory?
if (dataContainsMipmaps)
{
// Allocate storage for all levels
if (isArbDsa)
{
glTextureStorage2D(mOpenGLTexture, static_cast<GLsizei>(numberOfMipmaps), Mapping::getOpenGLInternalFormat(textureFormat), static_cast<GLsizei>(width), static_cast<GLsizei>(height));
}
// Data layout: The renderer interface provides: CRN and KTX files are organized in mip-major order, like this:
// Mip0: Face0, Face1, Face2, Face3, Face4, Face5
// Mip1: Face0, Face1, Face2, Face3, Face4, Face5
// etc.
// Upload all mipmaps of all faces
const uint32_t format = Mapping::getOpenGLFormat(textureFormat);
for (uint32_t mipmap = 0; mipmap < numberOfMipmaps; ++mipmap)
{
const GLsizei numberOfBytesPerSlice = static_cast<GLsizei>(Renderer::TextureFormat::getNumberOfBytesPerSlice(textureFormat, width, height));
if (isArbDsa)
{
// With ARB DSA cube maps are a special form of a cube map array so we can upload all 6 faces at once per mipmap
// See https://www.khronos.org/opengl/wiki/Direct_State_Access (Last paragraph in "Changes from EXT")
// We know that "data" must be valid when we're in here due to the "Renderer::TextureFlag::DATA_CONTAINS_MIPMAPS"-flag
glCompressedTextureSubImage3D(mOpenGLTexture, static_cast<GLint>(mipmap), 0, 0, 0, static_cast<GLsizei>(width), static_cast<GLsizei>(height), 6, format, numberOfBytesPerSlice * 6, data);
// Move on to the next mipmap
data = static_cast<const uint8_t*>(data) + numberOfBytesPerSlice * 6;
}
else
{
for (uint32_t face = 0; face < 6; ++face)
{
// Upload the current face
glCompressedTextureImage2DEXT(mOpenGLTexture, GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, static_cast<GLint>(mipmap), format, static_cast<GLsizei>(width), static_cast<GLsizei>(height), 0, numberOfBytesPerSlice, data);
// Move on to the next face
data = static_cast<const uint8_t*>(data) + numberOfBytesPerSlice;
}
}
// Move on to the next mipmap
width = std::max(width >> 1, 1u); // /= 2
height = std::max(height >> 1, 1u); // /= 2
}
}
else
{
// The user only provided us with the base texture, no mipmaps
if (isArbDsa)
{
// Allocate storage for all levels
glTextureStorage2D(mOpenGLTexture, 1, Mapping::getOpenGLInternalFormat(textureFormat), static_cast<GLsizei>(width), static_cast<GLsizei>(height));
if (nullptr != data)
{
glCompressedTextureSubImage3D(mOpenGLTexture, 0, 0, 0, 0, static_cast<GLsizei>(width), static_cast<GLsizei>(height), 6, Mapping::getOpenGLFormat(textureFormat), static_cast<GLsizei>(Renderer::TextureFormat::getNumberOfBytesPerSlice(textureFormat, width, height)) * 6, data);
}
}
else
{
const GLsizei numberOfBytesPerSlice = static_cast<GLsizei>(Renderer::TextureFormat::getNumberOfBytesPerSlice(textureFormat, width, height));
const uint32_t openGLInternalFormat = Mapping::getOpenGLInternalFormat(textureFormat);
for (uint32_t face = 0; face < 6; ++face)
{
// Upload the current face
glCompressedTextureImage2DEXT(mOpenGLTexture, GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, openGLInternalFormat, static_cast<GLsizei>(width), static_cast<GLsizei>(height), 0, numberOfBytesPerSlice, data);
// Move on to the next face
data = static_cast<const uint8_t*>(data) + numberOfBytesPerSlice;
}
}
}
}
else
{
// Texture format is not compressed
// Did the user provided data containing mipmaps from 0-n down to 1x1 linearly in memory?
if (dataContainsMipmaps)
{
// Data layout: The renderer interface provides: CRN and KTX files are organized in mip-major order, like this:
// Mip0: Face0, Face1, Face2, Face3, Face4, Face5
// Mip1: Face0, Face1, Face2, Face3, Face4, Face5
// etc.
// Allocate storage for all levels
if (isArbDsa)
{
glTextureStorage2D(mOpenGLTexture, static_cast<GLsizei>(numberOfMipmaps), Mapping::getOpenGLInternalFormat(textureFormat), static_cast<GLsizei>(width), static_cast<GLsizei>(height));
}
// Upload all mipmaps of all faces
const GLint internalFormat = static_cast<GLint>(Mapping::getOpenGLInternalFormat(textureFormat));
const uint32_t format = Mapping::getOpenGLFormat(textureFormat);
const uint32_t type = Mapping::getOpenGLType(textureFormat);
for (uint32_t mipmap = 0; mipmap < numberOfMipmaps; ++mipmap)
{
const GLsizei numberOfBytesPerSlice = static_cast<GLsizei>(Renderer::TextureFormat::getNumberOfBytesPerSlice(textureFormat, width, height));
for (uint32_t face = 0; face < 6; ++face)
{
// Upload the current face
if (isArbDsa)
{
// We know that "data" must be valid when we're in here due to the "Renderer::TextureFlag::DATA_CONTAINS_MIPMAPS"-flag
glTextureSubImage3D(mOpenGLTexture, static_cast<GLint>(mipmap), 0, 0, static_cast<GLint>(face), static_cast<GLsizei>(width), static_cast<GLsizei>(height), 1, format, type, data);
}
else
{
glTextureImage2DEXT(mOpenGLTexture, GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, static_cast<GLint>(mipmap), internalFormat, static_cast<GLsizei>(width), static_cast<GLsizei>(height), 0, format, type, data);
}
// Move on to the next face
data = static_cast<const uint8_t*>(data) + numberOfBytesPerSlice;
}
// Move on to the next mipmap
width = std::max(width >> 1, 1u); // /= 2
height = std::max(height >> 1, 1u); // /= 2
}
}
else
{
// The user only provided us with the base texture, no mipmaps
if (isArbDsa)
{
// Allocate storage for all levels
glTextureStorage2D(mOpenGLTexture, static_cast<GLsizei>(numberOfMipmaps), Mapping::getOpenGLInternalFormat(textureFormat), static_cast<GLsizei>(width), static_cast<GLsizei>(height));
if (nullptr != data)
{
glTextureSubImage3D(mOpenGLTexture, 0, 0, 0, 0, static_cast<GLsizei>(width), static_cast<GLsizei>(height), 6, Mapping::getOpenGLFormat(textureFormat), Mapping::getOpenGLType(textureFormat), data);
}
}
else
{
const uint32_t numberOfBytesPerSlice = Renderer::TextureFormat::getNumberOfBytesPerSlice(textureFormat, width, height);
const GLint openGLInternalFormat = static_cast<GLint>(Mapping::getOpenGLInternalFormat(textureFormat));
const uint32_t openGLFormat = Mapping::getOpenGLFormat(textureFormat);
const uint32_t openGLType = Mapping::getOpenGLType(textureFormat);
for (uint32_t face = 0; face < 6; ++face)
{
glTextureImage2DEXT(mOpenGLTexture, GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, openGLInternalFormat, static_cast<GLsizei>(width), static_cast<GLsizei>(height), 0, openGLFormat, openGLType, data);
data = static_cast<const uint8_t*>(data) + numberOfBytesPerSlice;
}
}
}
}
// Build mipmaps automatically on the GPU? (or GPU driver)
if (flags & Renderer::TextureFlag::GENERATE_MIPMAPS)
{
if (isArbDsa)
{
glGenerateTextureMipmap(mOpenGLTexture);
glTextureParameteri(mOpenGLTexture, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
}
else
{
glGenerateTextureMipmapEXT(mOpenGLTexture, GL_TEXTURE_CUBE_MAP);
glTextureParameteriEXT(mOpenGLTexture, GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
}
}
else
{
if (isArbDsa)
{
glTextureParameteri(mOpenGLTexture, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}
else
{
glTextureParameteriEXT(mOpenGLTexture, GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}
}
if (isArbDsa)
{
glTextureParameteri(mOpenGLTexture, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
else
{
glTextureParameteriEXT(mOpenGLTexture, GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
#ifndef OPENGLRENDERER_NO_STATE_CLEANUP
// Restore previous alignment
glPixelStorei(GL_UNPACK_ALIGNMENT, openGLAlignmentBackup);
#endif
}
TextureCubeDsa::~TextureCubeDsa()
{
// Nothing here
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // OpenGLRenderer
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* Copyright (C) 2000-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* Yngve Pettersen
*/
#include "core/pch.h"
#if defined(_NATIVE_SSL_SUPPORT_)
#include "modules/libssl/sslbase.h"
#include "modules/libssl/keyex/certverify.h"
#include "modules/libssl/protocol/sslstat.h"
#include "modules/libssl/options/sslopt.h"
#include "modules/libssl/certs/certhandler.h"
#include "modules/cache/url_stream.h"
#include "modules/upload/upload.h"
#include "modules/formats/uri_escape.h"
#include "modules/formats/encoder.h"
#include "modules/prefs/prefsmanager/collections/pc_network.h"
#include "modules/pi/OpSystemInfo.h"
SSL_CertificateVerifier::VerifyStatus SSL_CertificateVerifier::CheckOCSP()
{
OpString ocsp_url_name;
SSL_varvector32 ocsp_challenge;
//SSL_ConnectionState *commstate = AccessConnectionState();
if(
!g_pcnet->GetIntegerPref(PrefsCollectionNetwork::UseOCSPValidation) ||
!cert_handler
)
return SSL_CertificateVerifier::Verify_TaskCompleted;
cert_handler->ResetError();
OpString_list ocsp_urls;
SSL_varvector32 ocsp_request;
if(OpStatus::IsError(cert_handler->GetOCSP_Request(ocsp_urls, ocsp_request
#ifndef TLS_NO_CERTSTATUS_EXTENSION
, sent_ocsp_extensions
#endif
)))
return SSL_CertificateVerifier::Verify_TaskCompleted;
#ifndef TLS_NO_CERTSTATUS_EXTENSION
if(sent_ocsp_extensions.GetLength() || ocsp_extensions_sent)
{
if(OpStatus::IsError(cert_handler->VerifyOCSP_Response(received_ocsp_response)) || Error())
{
RaiseAlert(cert_handler);
CancelPendingLoad();
return SSL_CertificateVerifier::Verify_Failed;
}
return SSL_CertificateVerifier::Verify_TaskCompleted;
}
#endif
URL ocsp_url_candidate;
unsigned long i,n;
n = ocsp_urls.Count();
if(n == 0 || ocsp_request.GetLength() == 0)
return SSL_CertificateVerifier::Verify_TaskCompleted;
// Build POST version
OpAutoPtr<Upload_BinaryBuffer> buffer(OP_NEW(Upload_BinaryBuffer, ()));
if(buffer.get() == NULL)
return SSL_CertificateVerifier::Verify_TaskCompleted;
OP_STATUS op_err = OpStatus::OK;
TRAP_AND_RETURN_VALUE_IF_ERROR(op_err, buffer->InitL(ocsp_request.GetDirect(), ocsp_request.GetLength(),
UPLOAD_COPY_BUFFER, "application/ocsp-request"), SSL_CertificateVerifier::Verify_TaskCompleted);
TRAP_AND_RETURN_VALUE_IF_ERROR(op_err, buffer->PrepareUploadL(UPLOAD_BINARY_NO_CONVERSION), SSL_CertificateVerifier::Verify_TaskCompleted);
// Build GET version
OpString escaped_query;
OpString encoded_query;
char *b64_ocsp = NULL;
int b64_ocsp_len = 0;
MIME_Encode_SetStr(b64_ocsp, b64_ocsp_len, (const char *) ocsp_request.GetDirect(), ocsp_request.GetLength(), NULL, GEN_BASE64_ONELINE);
if(b64_ocsp == NULL || b64_ocsp_len == 0)
{
OP_DELETEA(b64_ocsp);
return SSL_CertificateVerifier::Verify_TaskCompleted;
}
encoded_query.Set(b64_ocsp, b64_ocsp_len);
uni_char *target = escaped_query.Reserve(b64_ocsp_len*3+10);
if(!target)
{
OP_DELETEA(b64_ocsp);
return SSL_CertificateVerifier::Verify_TaskCompleted;
}
target += UriEscape::Escape(target, b64_ocsp, b64_ocsp_len, UriEscape::AllUnsafe);
*(target++) = '\0';
OP_DELETEA(b64_ocsp);
// Find URL
for(i=0;i<n;i++)
{
OpString temp_url;
int len = ocsp_urls[i].Length();
BOOL use_post = FALSE;
{
OpStringC temp_ocsp(ocsp_urls[i]);
for(unsigned long j = 0; j< g_securityManager->ocsp_override_list.Count(); j++)
{
if(temp_ocsp.Compare(g_securityManager->ocsp_override_list[j]) == 0)
{
use_post = TRUE;
break;
}
}
}
if(OpStatus::IsError(temp_url.SetConcat(ocsp_urls[i], (use_post || ocsp_urls[i][len-1] == '/' ? (const uni_char *) NULL : UNI_L("/")), (use_post ? (const uni_char *) NULL : escaped_query.CStr()))))
continue;
ocsp_url_candidate = g_url_api->GetURL(temp_url, g_revocation_context);
URLType ocsp_type = (URLType) ocsp_url_candidate.GetAttribute(URL::KType);
if(ocsp_url_candidate.IsEmpty() || (ocsp_type != URL_HTTP && ocsp_type != URL_HTTPS) ||
ocsp_url_candidate.GetAttribute(URL::KHostName).FindFirstOf('.') == KNotFound)
{
ocsp_url_candidate = URL();
continue;
}
unsigned short port_num = ocsp_url_candidate.GetAttribute(URL::KResolvedPort);
ServerName *ocsp_sn = (ServerName *) ocsp_url_candidate.GetAttribute(URL::KServerName, (const void*) 0);
if(server_info != NULL && ocsp_sn == server_info->GetServerName() &&
port_num == server_info->Port())
{
// same host, try another one
ocsp_url_candidate = URL();
continue;
}
if(use_post)
{
g_url_api->MakeUnique(ocsp_url_candidate);
ocsp_url_candidate.SetAttribute(URL::KHTTP_Method, HTTP_METHOD_POST);
ocsp_url_candidate.SetHTTP_Data(buffer.release(), TRUE);
}
ocsp_url_candidate.SetAttribute(URL::KHTTP_Managed_Connection, TRUE);
break;
}
if(ocsp_url_candidate.IsEmpty())
{
low_security_reason |= SECURITY_LOW_REASON_UNABLE_TO_OCSP_VALIDATE;
if(security_rating >SECURITY_STATE_HALF)
{
security_rating=SECURITY_STATE_HALF;
}
return SSL_CertificateVerifier::Verify_TaskCompleted;
}
pending_url = OP_NEW(URL, (ocsp_url_candidate));
if(pending_url == NULL)
return SSL_CertificateVerifier::Verify_TaskCompleted;
url_loading_mode = Loading_CRL_Or_OCSP;
pending_url_ref.SetURL(*pending_url);
#ifndef TLS_ADD_OCSP_NONCE
if(ocsp_url_candidate.Status(FALSE) == URL_LOADED)
{
time_t expires = 0;
ocsp_url_candidate.GetAttribute(URL::KVHTTP_ExpirationDate, &expires);
if(expires && expires > (time_t) (g_op_time_info->GetTimeUTC()/1000.0))
return ValidateOCSP(TRUE);
}
#endif
return SSL_CertificateVerifier::Verify_Started;
}
SSL_CertificateVerifier::VerifyStatus SSL_CertificateVerifier::ValidateOCSP(BOOL full_check_if_fail)
{
if(!cert_handler || url_loading_mode != Loading_CRL_Or_OCSP || pending_url == NULL || pending_url->IsEmpty())
{
CancelPendingLoad();
return SSL_CertificateVerifier::Verify_TaskCompleted;
}
URL_InUse ocsp_url(pending_url_ref);
pending_url_ref.UnsetURL();
OP_DELETE(pending_url);
pending_url= NULL;
OpFileLength len = 0;
ocsp_url->GetAttribute(URL::KContentLoaded, &len,URL::KFollowRedirect);
if((URLStatus) ocsp_url->GetAttribute(URL::KLoadStatus, URL::KFollowRedirect) != URL_LOADED ||
ocsp_url->GetAttribute(URL::KHTTP_Response_Code,URL::KFollowRedirect) != HTTP_OK ||
len == 0 ||
ocsp_url->GetAttribute(URL::KMIME_Type,URL::KFollowRedirect).CompareI("application/ocsp-response") != 0
)
{
low_security_reason |= SECURITY_LOW_REASON_UNABLE_TO_OCSP_VALIDATE;
if(security_rating >SECURITY_STATE_HALF)
{
security_rating=SECURITY_STATE_HALF;
}
CancelPendingLoad();
goto finished_ocsp;
}
{
URL_DataStream ocsp_reader(*ocsp_url);
SSL_varvector32 ocsp_response;
TRAPD(op_err, ocsp_response.AddContentL(&ocsp_reader));
if(OpStatus::IsError(op_err) || ocsp_response.Error() || ocsp_response.GetLength() == 0)
{
if(full_check_if_fail)
return SSL_CertificateVerifier::Verify_Started; // Caller is ready to send this request
#ifdef SECURITY_LOW_REASON_OCSP_FAILED
low_security_reason |= SECURITY_LOW_REASON_OCSP_FAILED;
#endif
if(security_rating >SECURITY_STATE_HALF)
{
security_rating = SECURITY_STATE_HALF;
}
CancelPendingLoad();
goto finished_ocsp;
}
if(OpStatus::IsError(cert_handler->VerifyOCSP_Response(ocsp_response)) || Error())
{
SSL_Alert msg;
cert_handler->Error(&msg);
if(msg.GetDescription() == SSL_Certificate_OCSP_error || msg.GetDescription() == SSL_Certificate_OCSP_Verify_failed)
{
if(full_check_if_fail)
return SSL_CertificateVerifier::Verify_Started;
ocsp_fail_reason.Set(msg.GetReason());
cert_handler->ResetError();
low_security_reason |= SECURITY_LOW_REASON_OCSP_FAILED;
if(security_rating >SECURITY_STATE_HALF)
{
security_rating= SECURITY_STATE_HALF;
}
CancelPendingLoad();
goto finished_ocsp;
}
else
{
if(msg.GetDescription() == SSL_Certificate_Revoked)
{
SSL_varvector16 fingerprint;
cert_handler->GetFingerPrint(0, fingerprint);
OpStatus::Ignore(g_revoked_certificates.AddRevoked(fingerprint, Certificate[0]));
}
RaiseAlert(cert_handler);
if(!Error())
RaiseAlert(SSL_Internal, SSL_InternalError);
CancelPendingLoad();
return SSL_CertificateVerifier::Verify_Failed;
}
}
}
finished_ocsp:;
if (pending_url)
{
OP_DELETE(pending_url);
pending_url = NULL;
}
return SSL_CertificateVerifier::Verify_TaskCompleted;
}
#endif
|
#pragma once
#include "DrawGraph.h"
class DrawRectangle : public DrawGraph
{
public:
DrawRectangle();
~DrawRectangle();
virtual void initBuffer() override;
virtual void drawGraph() override;
private:
float vertices[12] = { // 矩形的4个顶点
0.5f, 0.5f, 0.0f, // 右上角
0.5f, -0.5f, 0.0f, // 右下角
-0.5f, -0.5f, 0.0f, // 左下角
-0.5f, 0.5f, 0.0f // 左上角
};
unsigned int indeices[6] = { // 矩形是由三角形组成的,opengl不会绘制矩形,但是会绘制三角形 所以矩形由2个三角形组成
0, 1, 3, // 使用vects的哪几个点 组成第一个三角形
1, 2, 3 // 组成第二个三角形
};
};
|
/*
Copyright (c) 2014 Mircea Daniel Ispas
This file is part of "Push Game Engine" released under zlib license
For conditions of distribution and use, see copyright notice in Push.hpp
*/
#pragma once
#include "Serialization/Serialize.hpp"
#include <cstdint>
namespace Push
{
struct Color
{
Color();
Color(float rr, float gg, float bb, float aa);
float r;
float g;
float b;
float a;
template<typename Serializer>
void Serialize(Serializer& serializer);
};
template<typename Serializer>
void Color::Serialize(Serializer& serializer)
{
Push::Serialize(serializer, "r", r);
Push::Serialize(serializer, "g", g);
Push::Serialize(serializer, "b", b);
Push::Serialize(serializer, "a", a);
}
inline Color::Color()
: r(1.f)
, g(1.f)
, b(1.f)
, a(1.f)
{
}
inline Color::Color(float rr, float gg, float bb, float aa)
: r(rr)
, g(gg)
, b(bb)
, a(aa)
{
}
}
|
#include<iostream>
#include<queue>
#include<algorithm>
#include<vector>
#include<cstring>
#include<stdio.h>
using namespace std;
int N;
int arr[102][102];
int MAX = 0;
struct is {
int y;
int x;
};
is worm[2][5];
int dx[] = { -1, 0, 1, 0 }; // ¼ ºÏ µ¿ ³²
int dy[] = { 0,-1,0,1 };
void func(int cy, int cx, int dir, int cnt) {
int y = cy;
int x = cx;
int gap = 1;
while (true) {
int ny = y + gap * dy[dir];
int nx = x + gap * dx[dir];
if (1 <= ny && ny <= N && 1 <= nx && nx <= N) {
if (cy == ny && cx == nx) {
MAX = max(MAX, cnt);
return;
}
else if (arr[ny][nx] == -1) {
MAX = max(MAX, cnt);
return;
}
if (arr[ny][nx] > 5) {
int temp = arr[ny][nx] - 5;
gap = 0;
if (worm[0][temp].y == ny && worm[0][temp].x == nx) {
y = worm[1][temp].y;
x = worm[1][temp].x;
}
else {
y = worm[0][temp].y;
x = worm[0][temp].x;
}
}
else if (1 <= arr[ny][nx] && arr[ny][nx] <= 5) {
if (arr[ny][nx] == 1) {
if (dir == 0) dir = 1;
else if (dir == 3) dir = 2;
else dir = (dir + 2) % 4;
}
else if (arr[ny][nx] == 2) {
if (dir == 0) dir = 3;
else if (dir == 1) dir = 2;
else dir = (dir + 2) % 4;
}
else if (arr[ny][nx] == 3) {
if (dir == 2) dir = 3;
else if (dir == 1) dir = 0;
else dir = (dir + 2) % 4;
}
else if (arr[ny][nx] == 4) {
if (dir == 2) dir = 1;
else if (dir == 3) dir = 0;
else dir = (dir + 2) % 4;
}
else if (arr[ny][nx] == 5) dir = (dir + 2) % 4;
cnt++;
gap = 0;
y = ny;
x = nx;
}
}
else {
dir = (dir + 2) % 4;
gap = 0;
y = ny;
x = nx;
cnt++;
}
gap++;
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int T;
cin >> T;
for (int p = 1; p <= T; p++) {
MAX = 0;
memset(worm, false, sizeof(worm));
cin >> N;
for (int y = 1; y <= N; y++) {
for (int x = 1; x <= N; x++) {
cin >> arr[y][x];
if (arr[y][x] > 5) {
if (worm[0][arr[y][x] - 5].y == 0 && worm[0][arr[y][x] - 5].x == 0) {
worm[0][arr[y][x] - 5] = { y,x };
}
else worm[1][arr[y][x] - 5] = { y,x };
}
}
}
for (int y = 1; y <= N; y++) {
for (int x = 1; x <= N; x++) {
if (arr[y][x] == 0) {
for (int i = 0; i < 4; i++) {
func(y, x, i, 0);
}
}
}
}
cout << "#" << p << " " << MAX << endl;
}
}
|
#ifndef __SettingsDialog__
#define __SettingsDialog__
#include "gui.h"
class SettingsDialog: public SettingsDialog1
{
private:
wxFont settingsFont;
void setFont(wxFont& font);
protected:
void FontChanged(wxFontPickerEvent& event);
public:
SettingsDialog(wxWindow* parent, wxFont& font);
wxFont getFont();
};
#endif // __SettingsDialog__
|
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
#define MOD 1000000007
using namespace std;
struct object
{
int s1,s2;
};
vector<object> a;
bool myfunction (object i,object j)
{
return (i.s1<j.s1);
}
bool myfunction1 (object i,object j)
{
if(i.s1==j.s1)
return (i.s2<j.s2);
}
int main()
{
int t,n,k;
object temp;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&k);
for(int i=0,p,q;i<n;i++)
{
scanf("%d%d",&p,&q);
temp.s1=p;
temp.s2=q;
a.push_back(temp);
}
sort(a,a+n,myfunction);
sort(a,a+n,myfunction1);
}
return 0;
}
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXTITL 40
#define MAXBKS 10
char * s_gets(char st, int n); //函数声明
char * s_gets(char st, int n) //函数定义
{
char * ret_val;
char * find;
ret_val = fgets(st, n, stdin); //从标准输入流(键盘)获取数据
printf("ret_val = %s\n", ret_val);
if(ret_val != NULL)
{
find = strchr(st, '\n'); //待查找文本, 查找的字符
if(find != NULL)
*find = '\0';
else
while(getc(stdin) != '\0') //输入流(缓冲区)中获取字符,并舍去(没有接收getc()函数的返回值)
continue;
}
return ret_val;
}
struct book {
char title[MAXTITL];
};
int main(void)
{
struct book library[MAXBKS]; /* 结构数组 */
int count = 0;
int index, filename;
FILE * fp;
int size = sizeof(struct book); /* 得到结构体类型大小,用作读写文件函数的参数 */
if((fp = fopen("books.dat", "a+b")) == NULL)
fputs("打开文件失败!\n", stderr), exit(1);
rewind(fp); /* 文件位置指示器移动到文件开始字节 0字节的位置 */
// fseek(fp, 0L, SEEK_SET); //同上语句 469页
return 0;
}
|
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
class Solution {
public:
int rob(vector<int>& nums) {
//基本思想:动态规划,一维动态规划dp[i]表示如果小偷到当前房屋,在当前房屋下最大偷窃值
//所以dp[i]=dp[i]+max(dp[i-2],dp[i-3]),可以用nums当dp数组这样就不用申请额外空间
//或者dp[i]表示截止当前房屋小偷最大偷窃值,dp[i]=max(dp[i-1],dp[i-2]+nums[i])
if (nums.size() == 0)
return 0;
if (nums.size() > 2)
nums[2] += nums[0];
for (int i = 3; i < nums.size(); i++)
nums[i] += max(nums[i - 2], nums[i - 3]);
return *max_element(nums.begin(), nums.end());
}
};
class Solution1 {
public:
int rob(vector<int>& nums) {
//基本思想:动态规划优化,nums是引用尽量不要改变引用值
if (nums.size() == 0)
return 0;
if (nums.size() == 1)
return nums[0];
int first = nums[0], second = max(nums[0], nums[1]);
for (int i = 2; i < nums.size(); i++)
{
int temp = second;
second = max(second, first + nums[i]);
first = temp;
}
return second;
}
};
int main()
{
Solution solute;
vector<int> nums = { 1,2,3,1,1,6,10 };
cout << solute.rob(nums) << endl;
return 0;
}
|
#pragma once
class MonsterSelectBack :public GameObject
{
public:
MonsterSelectBack();
void OnDestroy();
void Update();
private:
SpriteRender* m_back = nullptr; //黒い後ろのやつ
std::vector<SpriteRender*> m_hexs; //hex no kazari
float m_addrot[2] = { 0.5,0.7 };
float m_rot[2] = { 0,0 };
};
|
#include <nan.h>
void requestReview(const Nan::FunctionCallbackInfo<v8::Value> &info);
static void InitModule(v8::Local<v8::Object> exports) {
v8::Isolate *isolate = exports->GetIsolate();
v8::Local<v8::Context> context = isolate->GetCurrentContext();
exports->Set(context, Nan::New("requestReview").ToLocalChecked(),
Nan::New<v8::FunctionTemplate>(requestReview)->GetFunction(context).ToLocalChecked());
}
NODE_MODULE(request_review, InitModule)
|
#include "sample_module.h"
#include <memory>
#include <string>
#include "shell.h"
namespace microshell {
namespace modules {
namespace sample_module {
using namespace microshell::core;
using namespace std;
void SampleModule::initialize(const Shell&) {
}
vector<shared_ptr<BuiltinFactory>> SampleModule::get_builtins() {
return vector<shared_ptr<BuiltinFactory>> {
make_shared<TypedBuiltinFactory<MooBuiltin>>(
TypedBuiltinFactory<MooBuiltin>("moo")
)
};
}
int MooBuiltin::invoke(Shell *shell) {
shell->out("Moo!");
return 0;
}
} // namespace sample_module
} // namespace modules
} // namespace microshell
|
#include "message.h"
Message::Message()
{
}
Message::Message(const Message &other)
{
m_body = other.m_body;
m_headers = other.m_headers;
}
Message::~Message()
{
}
Message::Message(const QString &body, const QStringList &headers)
{
m_body = body;
m_headers = headers;
qDebug() << "C'est :" << m_headers<<" le header \n Et :" <<m_body<<" le corps \n" ;
}
QString Message::body() const
{
return m_body;
}
QStringList Message::headers() const
{
return m_headers;
}
|
#include "ResourceSystem.h"
#include "Keng/ResourceSystem/IResource.h"
#include "Keng/ResourceSystem/IResourceFabric.h"
#include "Keng/ResourceSystem/IDevice.h"
#include "Keng/Base/Serialization/OpenArchiveJSON.h"
#include "Keng/Base/Serialization/SerializeMandatory.h"
#include "Keng/FileSystem/ReadFileToBuffer.h"
#include "Keng/Core/IApplication.h"
#include "Keng/Core/SystemEvent.h"
#include "EverydayTools/Array/ArrayViewVector.h"
#include "EverydayTools/Exception/CallAndRethrow.h"
#include "EverydayTools/Exception/CheckedCast.h"
#include "EverydayTools/UnusedVar.h"
#include <algorithm>
#include <chrono>
#include <fstream>
#include "yasli/JSONOArchive.h"
#include "yasli/JSONIArchive.h"
#include "yasli/STL.h"
namespace keng::resource
{
ResourceSystem::ResourceSystem() = default;
ResourceSystem::~ResourceSystem() = default;
void ResourceSystem::Initialize(const core::IApplicationPtr& app) {
CallAndRethrowM + [&] {
StoreDependencies(*app);
m_parameters = ReadDefaultParams();
};
}
bool ResourceSystem::Update() {
return CallAndRethrowM + [&] {
using namespace std::chrono;
using namespace std::chrono_literals;
high_resolution_clock::time_point zero(0ms);
auto dt = high_resolution_clock::now() - zero;
auto now = duration_cast<milliseconds>(dt).count();
float nowMs = edt::CheckedCast<float>(now);
for (auto& deviceResources : m_devicesResources) {
deviceResources->Update(nowMs);
}
return true;
};
}
void ResourceSystem::Shutdown() {
m_devicesResources.clear();
m_fabrics.clear();
}
IResourcePtr ResourceSystem::GetResource(const char* filename) {
return GetResource(filename, nullptr);
}
void ResourceSystem::AddRuntimeResource(const IResourcePtr& resource) {
AddRuntimeResource(resource, nullptr);
}
IResourcePtr ResourceSystem::GetResource(const char* filename, const IDevicePtr& device) {
return GetDeviceResources(device).GetResource(*this, filename);
}
void ResourceSystem::AddRuntimeResource(const IResourcePtr& resource, const IDevicePtr& device) {
GetDeviceResources(device).AddRuntimeResource(*this, resource);
}
void ResourceSystem::RegisterResourceFabric(const IResourceFabricPtr& fabric) {
CallAndRethrowM + [&] {
auto resourceTypeName = fabric->GetResourceType();
auto res = m_fabrics.insert(std::make_pair(std::string(resourceTypeName), fabric));
edt::ThrowIfFailed(res.second, "Fabric \"", resourceTypeName, "\" already registered");
};
}
void ResourceSystem::UnregisterFabric(const IResourceFabricPtr& fabric) {
CallAndRethrowM + [&] {
auto resourceTypeName = fabric->GetResourceType();
auto eraseCount = m_fabrics.erase(std::string(resourceTypeName));
edt::ThrowIfFailed(eraseCount > 0, "Fabric \"", resourceTypeName, "\" not found");
};
}
IResourceFabricPtr ResourceSystem::GetFabric(const std::string& resourceType) {
return CallAndRethrowM + [&] {
auto fabric_it = m_fabrics.find(resourceType);
edt::ThrowIfFailed(
fabric_it != m_fabrics.end(),
"Fabric \"", resourceType, "\" is not registered");
return fabric_it->second;
};
}
DeviceResources& ResourceSystem::GetDeviceResources(const IDevicePtr& device) {
auto it = std::lower_bound(m_devicesResources.begin(), m_devicesResources.end(), device,
[](const DeviceResourcesPtr& pDeviceResources, const IDevicePtr& device) {
return device < pDeviceResources->device;
});
if (it == m_devicesResources.end() || (*it)->device != device) {
it = m_devicesResources.insert(it, std::make_unique<DeviceResources>(device));
}
return **it;
}
void SystemParams::serialize(Archive& ar) {
ar(defaultResourceParams, "resource");
}
SystemParams ResourceSystem::ReadDefaultParams() {
return CallAndRethrowM + [&] {
struct ConfigFile {
void serialize(Archive& ar) {
ar(params, "resource_system");
}
SystemParams params;
};
ConfigFile config {};
try {
auto filename = "Configs/resource_system.json";
using FileView = edt::DenseArrayView<const uint8_t>;
auto onFileRead = [&](FileView fileView) {
yasli::JSONIArchive ar;
OpenArchiveJSON(fileView, ar);
SerializeMandatory(ar, config);
};
edt::Delegate<void(FileView)> delegate;
delegate.Bind(onFileRead);
filesystem::HandleFileData(GetSystem<filesystem::IFileSystem>(), filename, delegate);
} catch (...) {
}
return config.params;
};
}
keng::filesystem::IFileSystem& ResourceSystem::GetFileSystem()
{
return GetSystem<filesystem::IFileSystem>();
}
void ResourceSystem::OnSystemEvent(const keng::core::IApplicationPtr& app, const keng::core::SystemEvent& e)
{
CallAndRethrowM + [&] {
switch (e)
{
case core::SystemEvent::Initialize:
Initialize(app);
break;
case core::SystemEvent::Update:
Update();
break;
case core::SystemEvent::Shutdown:
Shutdown();
break;
}
};
}
}
|
/*
* Copyright (c) 2016 Morwenn
* SPDX-License-Identifier: MIT
*/
#ifndef CPPSORT_DETAIL_FLOATING_POINT_WEIGHT_H_
#define CPPSORT_DETAIL_FLOATING_POINT_WEIGHT_H_
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <cmath>
namespace cppsort
{
namespace detail
{
//
// Helpers for floating point comparison, mostly
// to implement simple comparators from P0100 by
// Lawrence Crowl
//
template<typename FloatingPoint>
auto weak_weight(FloatingPoint value)
-> int
{
// Weak order for floating point numbers proposed by Lawrence Crowl:
// * all positive NaNs equivalent
// * positive infinity
// * positive reals
// * all zeros equivalent
// * negative reals
// * negative infinity
// * all negative NaNs equivalent
// Only matters for NaN and infinity
int res = std::signbit(value) ? -1 : 1;
switch (std::fpclassify(value))
{
case FP_NAN:
return res * 2;
case FP_INFINITE:
return res;
default:
return 0;
}
}
template<typename FloatingPoint>
auto total_weight(FloatingPoint value)
-> int
{
// IEEE 754 totalOrder for floating point numbers:
// * positive quiet NaNs
// * positive signaling NaNs
// * positive infinity
// * positive reals
// * positive zero
// * negative zero
// * negative reals
// * negative infinity
// * negative signaling NaNs
// * negative quiet NaNs
// Only matters for NaN and infinity
int res = std::signbit(value) ? -1 : 1;
switch (std::fpclassify(value))
{
case FP_NAN:
// TODO: discriminate quiet and signaling NaNs
return res * 2;
case FP_INFINITE:
return res;
default:
return 0;
}
}
}}
#endif // CPPSORT_DETAIL_FLOATING_POINT_WEIGHT_H_
|
//Copyright 2011-2016 Tyler Gilbert; All Rights Reserved
#include <stratify/stratify.h>
#include <iface/link.h>
#include "hal.hpp"
#include "sys/Kernel.hpp"
using namespace sys;
Kernel::Kernel() {
// TODO Auto-generated constructor stub
m_current_task = 0;
}
int Kernel::launch(const char * path, char * exec_path, const char * args, int options, int ram_size, int (*update_progress)(int, int), char *const envp[]){
#if defined __link
return -1;
#endif
return ::launch(path, exec_path, args, options, ram_size, update_progress, envp);
}
int Kernel::free_ram(const char * path, link_transport_mdriver_t * driver){
int fd;
int ret;
#if defined __link
if( (fd = link_open(driver, path, O_RDONLY)) < 0 ){
return -1;
}
ret = link_ioctl(driver, fd, I_APPFS_FREE_RAM);
link_close(driver, fd);
#else
if( (fd = ::open(path, O_RDONLY)) < 0 ){
return -1;
}
driver = 0;
ret = ::ioctl(fd, I_APPFS_FREE_RAM);
::close(fd);
#endif
return ret;
}
int Kernel::reclaim_ram(const char * path, link_transport_mdriver_t * driver){
int fd;
int ret;
#if defined __link
if( (fd = link_open(driver, path, O_RDONLY)) < 0 ){
return -1;
}
ret = link_ioctl(driver, fd, I_APPFS_RECLAIM_RAM);
link_close(driver, fd);
#else
if( (fd = ::open(path, O_RDONLY)) < 0 ){
return -1;
}
driver = 0;
ret = ::ioctl(fd, I_APPFS_RECLAIM_RAM);
::close(fd);
#endif
return ret;
}
#if !defined __link
void Kernel::powerdown(int count){
powerdown(count);
}
int Kernel::hibernate(int count){
return hibernate(count);
}
int Kernel::request(int req, void * arg){
return kernel_request(req, arg);
}
void Kernel::reset(){
Core core(0);
core.open();
core.reset();
}
int Kernel::get_board_config(stratify_board_config_t & config){
return ioctl(I_SYS_GETBOARDCONFIG, &config);
}
#endif
int Kernel::get_attr(sys_attr_t & attr){
return ioctl(I_SYS_GETATTR, &attr);
}
int Kernel::get_taskattr(sys_taskattr_t * attr, int task){
if( task == -1 ){
task = m_current_task;
} else {
m_current_task = task;
}
attr->tid = m_current_task;
m_current_task++;
return ioctl(I_SYS_GETTASK, attr);
}
|
/*
* Copyright (c) 2015-2020 Morwenn
* SPDX-License-Identifier: MIT
*/
#include <forward_list>
#include <iterator>
#include <list>
#include <type_traits>
#include <vector>
#include <catch2/catch.hpp>
#include <cpp-sort/adapters/hybrid_adapter.h>
#include <cpp-sort/sorter_facade.h>
#include <cpp-sort/sorter_traits.h>
namespace
{
enum struct sorter_type
{
foo,
bar
};
struct foo_sorter_impl
{
template<typename Iterator>
auto operator()(Iterator, Iterator) const
-> sorter_type
{
return sorter_type::foo;
}
using iterator_category = std::forward_iterator_tag;
};
struct bar_sorter_impl
{
template<typename Iterator>
auto operator()(Iterator, Iterator) const
-> sorter_type
{
return sorter_type::bar;
}
using iterator_category = std::forward_iterator_tag;
};
struct foo_sorter:
cppsort::sorter_facade<foo_sorter_impl>
{};
struct bar_sorter:
cppsort::sorter_facade<bar_sorter_impl>
{};
}
TEST_CASE( "iterator category rebinder",
"[rebind_iterator_category][hybrid_adapter]" )
{
SECTION( "simple case" )
{
using sorter1 = cppsort::rebind_iterator_category<
foo_sorter,
std::bidirectional_iterator_tag
>;
using sorter2 = cppsort::rebind_iterator_category<
bar_sorter,
std::random_access_iterator_tag
>;
CHECK( (std::is_same<cppsort::iterator_category<sorter1>, std::bidirectional_iterator_tag>::value) );
CHECK( (std::is_same<cppsort::iterator_category<sorter2>, std::random_access_iterator_tag>::value) );
}
SECTION( "with hybrid_adapter" )
{
cppsort::hybrid_adapter<
foo_sorter,
cppsort::rebind_iterator_category<
bar_sorter,
std::bidirectional_iterator_tag
>
> sorter;
std::forward_list<float> collection1(3);
sorter_type res1 = sorter(collection1);
CHECK( res1 == sorter_type::foo );
std::list<float> collection2(3);
sorter_type res2 = sorter(collection2);
CHECK( res2 == sorter_type::bar );
std::vector<float> collection3(3);
sorter_type res3 = sorter(collection3);
CHECK( res3 == sorter_type::bar );
}
}
|
#include <iostream>
#include <string>
#include <fstream>
#include <cstdio>
#include <cstdlib>
void print(const std::string& str) {
std::cout << str << "\n";
}
void show() {
std::cout << "input names & dates \n";
std::cout << "Meliq 11/02/2018 12:25, \nMiqael 12/05/2008 13:05, \nAnush 24/04/2007 15:00, \nArman 21/12/2006 13:00, \nKaren 14/04/2006 11:10 \n";
std::cout << "Your request_";
}
int main() {
std::string path = "info.txt";
std::ifstream fin;
fin.open("info.txt");
if(!fin.is_open()) {
std::cout << "file is not open";
} else {
std::string str;
std::string request;
std::string mem;
show();
int counter=0;
std::getline(std::cin, request);
while(!fin.eof()) {
++counter;
std::getline(fin, str);
if(str == request) {
if(0 != counter % 2) {
std::getline(fin, str);
print(str);
exit(1);
} else if(0 == counter % 2) {
print(mem);
exit(1);
}
}
mem=str;
}
std::cout << "please input correct \n " ;
}
fin.close();
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*
* @author Manuela Hutter (manuelah)
*/
#ifndef WEBSERVER_STATUS_DIALOG_H
#define WEBSERVER_STATUS_DIALOG_H
#ifdef WEBSERVER_SUPPORT
#include "adjunct/quick_toolkit/widgets/Dialog.h"
#include "modules/hardcore/timer/optimer.h"
class WebServerController;
/***********************************************************************************
** @class WebServerStatusDialog
** @brief Dialog to show the state of Unite (running/error etc)
************************************************************************************/
class WebServerStatusDialog
: public Dialog
{
public:
static const INT32 S_NUM_MIN = 5; // show stats for the last 5 minutes
WebServerStatusDialog(WebServerController & controller);
virtual ~WebServerStatusDialog();
//===== OpInputContext implementations =====
virtual Type GetType() { return DIALOG_TYPE_WEBSERVER_STATUS; }
virtual BOOL OnInputAction(OpInputAction* action);
//===== Dialog implementations =====
virtual void OnInit();
virtual DialogType GetDialogType() {return TYPE_OK;}
//===== DesktopWindow implementations =====
virtual const char* GetWindowName() { return "Webserver Status Dialog"; }
//===== OpTimerListener implementations =====
virtual void OnTimeOut(OpTimer* timer);
private:
void UpdateStatus();
private:
WebServerController & m_controller;
OpTimer * m_timer;
};
#endif // WEBSERVER_SUPPORT
#endif // WEBSERVER_STATUS_DIALOG_H
|
#include "UCC.h"
enum State
{
ST_WAITING_ITEM_REQUEST,
ST_WAITING_ITEM_CONSTRAINT,
ST_NEGOTIATION_FINISHED
};
UCC::UCC(Node *node, uint16_t contributedItemId, uint16_t constraintItemId) :
Agent(node),
_contributedItemId(contributedItemId),
_constraintItemId(constraintItemId),
_negotiationAgreement(false)
{
setState(ST_WAITING_ITEM_REQUEST);
}
UCC::~UCC()
{
}
void UCC::update()
{
// Nothing to do
}
void UCC::finalize()
{
finish();
}
void UCC::OnPacketReceived(TCPSocketPtr socket, const PacketHeader &packetHeader, InputMemoryStream &stream)
{
PacketType packetType = packetHeader.packetType;
if (state() == ST_WAITING_ITEM_REQUEST && packetType == PacketType::RequestItem) {
PacketRequestItem iPacketData;
iPacketData.Read(stream);
if (iPacketData.requestedItemId != _contributedItemId) {
// Should send error...
}
// Send back PacketType::RequestItemResponse with the constraint
PacketHeader oPacketHead;
oPacketHead.packetType = PacketType::RequestItemResponse;
oPacketHead.srcAgentId = id();
oPacketHead.dstAgentId = packetHeader.srcAgentId;
PacketRequestItemResponse oPacketData;
oPacketData.constraintItemId = _constraintItemId;
OutputMemoryStream ostream;
oPacketHead.Write(ostream);
oPacketData.Write(ostream);
socket->SendPacket(ostream.GetBufferPtr(), ostream.GetSize());
if (_constraintItemId == NULL_ITEM_ID) {
_negotiationAgreement = true;
setState(ST_NEGOTIATION_FINISHED);
}
else {
setState(ST_WAITING_ITEM_CONSTRAINT);
}
}
if (state() == ST_WAITING_ITEM_CONSTRAINT && packetType == PacketType::SendConstraint) {
PacketSendConstraint iPacketData;
iPacketData.Read(stream);
if (iPacketData.constraintItemId != _constraintItemId) {
// Should send an error...
}
// Send back PacketType::RequestItemResponse with the constraint
PacketHeader oPacketHead;
oPacketHead.packetType = PacketType::RequestItemResponse;
oPacketHead.srcAgentId = id();
oPacketHead.dstAgentId = packetHeader.srcAgentId;
OutputMemoryStream ostream;
oPacketHead.Write(ostream);
socket->SendPacket(ostream.GetBufferPtr(), ostream.GetSize());
_negotiationAgreement = true;
setState(ST_NEGOTIATION_FINISHED);
}
}
bool UCC::negotiationFinished() const {
return state() == ST_NEGOTIATION_FINISHED;
}
bool UCC::negotiationAgreement() const {
return _negotiationAgreement;
}
|
class Solution {
public:
string simplifyPath(string path) {
vector<string> stack;
string res, temp;
stringstream p(path);
while (getline(p, temp, '/')) {
if (temp == "" or temp == ".") continue;
if (!stack.empty() && temp == "..")
stack.pop_back();
// edge case - "/.." => "/"
else if(temp != ".."){
stack.push_back(temp);
}
}
for (auto s : stack)
res += "/" + s;
return stack.empty() ? "/" : res;
}
};
|
//
// TSP.hpp
// ADT
//
// Created by Jalor on 2020/12/11.
// Copyright © 2020 Jalor. All rights reserved.
//
#ifndef TSP_hpp
#define TSP_hpp
#include <iostream>
using namespace std;
const int TSP_MAX = 1;
class TSP{
private:
int vert[TSP_MAX];//顶点集合
int edge[TSP_MAX][TSP_MAX];//对应地图
int vertNum = 0,edgeNum = 0;
int ans = 0;
bool found = false;
int start = 0;
public:
TSP(int[],int,int);
void setMap(int* ,int);
void setStart(int s);
void outSolution(int s,int f[]);
};
#endif /* TSP_hpp */
|
#ifndef EVENT_HPP
#define EVENT_HPP
/*
* @author: Grzegorz Mirek
*/
class Event {
public:
virtual void trigger() = 0;
};
#endif
|
#pragma once
#include <QDialog>
#include "ui_ChangePwdDialog.h"
#include "SQLiteOperator.h"
class ChangePwdDialog : public QDialog
{
Q_OBJECT
public:
ChangePwdDialog(User* user, QWidget* parent = Q_NULLPTR);
~ChangePwdDialog();
signals:
void changePwd(QString);
private slots:
void onCkbChecked(int);
void onBtnChangeClicked();
void onBtnBackClicked();
private:
Ui::ChangePwdDialog ui;
User* m_user;
bool isDigitString(const QString&);
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2010 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_system_includes.h"
#ifdef VEGA_BACKEND_DIRECT3D10
#include <d3d10_1.h>
// If WebGL is enabled we need both the DXSDK and the D3DCompiler header. To find out if we
// have both we include the D3DCompiler header here. If the header isn't installed we will
// fall back and include our dummy D3DCompiler header which will define NO_DXSDK. That will
// in turn disable compilation of the DX backend.
#ifdef CANVAS3D_SUPPORT
#include <D3DCompiler.h>
#endif //CANVAS3D_SUPPORT
#ifndef NO_DXSDK
#include "platforms/vega_backends/d3d10/vegad3d10fbo.h"
#include "platforms/vega_backends/d3d10/vegad3d10texture.h"
VEGAD3d10RenderbufferObject::VEGAD3d10RenderbufferObject(unsigned int w, unsigned int h, ColorFormat fmt, unsigned int quality) :
m_width(w), m_height(h), m_format(fmt), m_samples(quality),
m_rtView(NULL), m_dsView(NULL), m_texture(NULL)
#ifdef VEGA_BACKEND_D2D_INTEROPERABILITY
, m_activeD2DFBO(NULL)
#endif // VEGA_BACKEND_D2D_INTEROPERABILITY
{}
VEGAD3d10RenderbufferObject::~VEGAD3d10RenderbufferObject()
{
if (m_rtView)
m_rtView->Release();
if (m_dsView)
m_dsView->Release();
if (m_texture)
m_texture->Release();
}
OP_STATUS VEGAD3d10RenderbufferObject::Construct(ID3D10Device1* d3dDevice)
{
if (m_width == 0 || m_height == 0)
return OpStatus::OK;
D3D10_TEXTURE2D_DESC texDesc;
op_memset(&texDesc, 0, sizeof(D3D10_TEXTURE2D_DESC));
texDesc.Width = m_width;
texDesc.Height = m_height;
texDesc.MipLevels = 1;
texDesc.ArraySize = 1;
texDesc.SampleDesc.Count = 1;
texDesc.SampleDesc.Quality = 0;
texDesc.Usage = D3D10_USAGE_DEFAULT;
texDesc.BindFlags = D3D10_BIND_RENDER_TARGET;
texDesc.CPUAccessFlags = 0;
texDesc.MiscFlags = 0;
switch (m_format)
{
case FORMAT_RGBA8:
case FORMAT_RGBA4:
case FORMAT_RGB5_A1:
texDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
break;
case FORMAT_RGB565:
texDesc.Format = DXGI_FORMAT_B8G8R8X8_UNORM;
break;
case FORMAT_DEPTH16:
texDesc.Format = DXGI_FORMAT_D16_UNORM;
texDesc.BindFlags = D3D10_BIND_DEPTH_STENCIL;
break;
case FORMAT_STENCIL8:
case FORMAT_DEPTH16_STENCIL8:
texDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
texDesc.BindFlags = D3D10_BIND_DEPTH_STENCIL;
break;
default:
return OpStatus::ERR;
}
if (m_samples > 1)
{
UINT quality = 0;
while (m_samples > 1 && quality == 0)
{
d3dDevice->CheckMultisampleQualityLevels(texDesc.Format, m_samples, &quality);
if (quality == 0)
--m_samples;
}
if (m_samples > 1)
{
texDesc.SampleDesc.Count = m_samples;
texDesc.SampleDesc.Quality = quality-1;
}
}
if (FAILED(d3dDevice->CreateTexture2D(&texDesc, NULL, &m_texture)))
return OpStatus::ERR;
if (texDesc.BindFlags == D3D10_BIND_DEPTH_STENCIL)
{
D3D10_DEPTH_STENCIL_VIEW_DESC dsvDesc;
op_memset(&dsvDesc, 0, sizeof(D3D10_DEPTH_STENCIL_VIEW_DESC));
dsvDesc.Format = texDesc.Format;
dsvDesc.ViewDimension = D3D10_DSV_DIMENSION_TEXTURE2D;
if (m_samples > 1)
{
dsvDesc.ViewDimension = D3D10_DSV_DIMENSION_TEXTURE2DMS;
}
else
{
dsvDesc.ViewDimension = D3D10_DSV_DIMENSION_TEXTURE2D;
dsvDesc.Texture2D.MipSlice = 0;
}
if (FAILED(d3dDevice->CreateDepthStencilView(m_texture, &dsvDesc, &m_dsView)))
return OpStatus::ERR;
}
else
{
D3D10_RENDER_TARGET_VIEW_DESC rtvDesc;
op_memset(&rtvDesc, 0, sizeof(D3D10_RENDER_TARGET_VIEW_DESC));
rtvDesc.Format = texDesc.Format;
if (m_samples > 1)
{
rtvDesc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2DMS;
}
else
{
rtvDesc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2D;
rtvDesc.Texture2D.MipSlice = 0;
}
if (FAILED(d3dDevice->CreateRenderTargetView(m_texture, &rtvDesc, &m_rtView)))
return OpStatus::ERR;
}
return OpStatus::OK;
}
#ifdef VEGA_BACKEND_D2D_INTEROPERABILITY
void VEGAD3d10RenderbufferObject::setActiveD2DFBO(VEGAD3d10FramebufferObject* fbo)
{
if (fbo == m_activeD2DFBO)
return;
VEGAD3d10FramebufferObject* oldfbo = m_activeD2DFBO;
m_activeD2DFBO = NULL;
if (oldfbo)
oldfbo->StopDrawingD2D();
m_activeD2DFBO = fbo;
}
#endif // VEGA_BACKEND_D2D_INTEROPERABILITY
unsigned int VEGAD3d10RenderbufferObject::getRedBits()
{
switch (m_format)
{
case FORMAT_RGBA8:
case FORMAT_RGBA4:
return 8;
case FORMAT_RGB565:
case FORMAT_RGB5_A1:
return 5;
default:
return 0;
}
}
unsigned int VEGAD3d10RenderbufferObject::getGreenBits()
{
switch (m_format)
{
case FORMAT_RGBA8:
case FORMAT_RGBA4:
return 8;
case FORMAT_RGB565:
return 6;
case FORMAT_RGB5_A1:
return 5;
default:
return 0;
}
}
unsigned int VEGAD3d10RenderbufferObject::getBlueBits()
{
switch (m_format)
{
case FORMAT_RGBA8:
case FORMAT_RGBA4:
return 8;
case FORMAT_RGB565:
case FORMAT_RGB5_A1:
return 5;
default:
return 0;
}
}
unsigned int VEGAD3d10RenderbufferObject::getAlphaBits()
{
switch (m_format)
{
case FORMAT_RGBA8:
case FORMAT_RGBA4:
return 8;
case FORMAT_RGB5_A1:
return 1;
default:
return 0;
}
}
unsigned int VEGAD3d10RenderbufferObject::getDepthBits()
{
switch (m_format)
{
case FORMAT_DEPTH16:
return 16;
case FORMAT_DEPTH16_STENCIL8:
case FORMAT_STENCIL8:
return 24;
default:
return 0;
}
}
unsigned int VEGAD3d10RenderbufferObject::getStencilBits()
{
switch (m_format)
{
case FORMAT_DEPTH16_STENCIL8:
case FORMAT_STENCIL8:
return 8;
default:
return 0;
}
}
VEGAD3d10FramebufferObject::VEGAD3d10FramebufferObject(ID3D10Device1* d3dDevice
#ifdef VEGA_BACKEND_D2D_INTEROPERABILITY
, ID2D1Factory* d2dFactory, D2D1_FEATURE_LEVEL flevel, D2D1_TEXT_ANTIALIAS_MODE textMode
#endif
, bool featureLevel9
) : m_attachedColorTex(NULL), m_attachedColorBuf(NULL), m_attachedDepthStencilBuf(NULL), m_texRTView(NULL), m_d3dDevice(d3dDevice)
#ifdef VEGA_BACKEND_D2D_INTEROPERABILITY
, m_d2dFactory(d2dFactory), m_d2dFLevel(flevel), m_d2dRenderTarget(NULL), m_isDrawingD2D(false), m_textMode(textMode), m_fontFlushListener(NULL)
#endif
,m_featureLevel9(featureLevel9)
{}
VEGAD3d10FramebufferObject::~VEGAD3d10FramebufferObject()
{
if (g_vegaGlobals.vega3dDevice && g_vegaGlobals.vega3dDevice->getRenderTarget() == this)
g_vegaGlobals.vega3dDevice->setRenderTarget(NULL);
#ifdef VEGA_BACKEND_D2D_INTEROPERABILITY
StopDrawingD2D();
if (m_d2dRenderTarget)
m_d2dRenderTarget->Release();
#endif // VEGA_BACKEND_D2D_INTEROPERABILITY
if (m_texRTView)
m_texRTView->Release();
VEGARefCount::DecRef(m_attachedColorTex);
VEGARefCount::DecRef(m_attachedColorBuf);
VEGARefCount::DecRef(m_attachedDepthStencilBuf);
}
unsigned int VEGAD3d10FramebufferObject::getWidth()
{
if (m_attachedColorTex)
return m_attachedColorTex->getWidth();
if (m_attachedColorBuf)
return m_attachedColorBuf->getWidth();
if (m_attachedDepthStencilBuf)
return m_attachedDepthStencilBuf->getWidth();
return 0;
}
unsigned int VEGAD3d10FramebufferObject::getHeight()
{
if (m_attachedColorTex)
return m_attachedColorTex->getHeight();
if (m_attachedColorBuf)
return m_attachedColorBuf->getHeight();
if (m_attachedDepthStencilBuf)
return m_attachedDepthStencilBuf->getHeight();
return 0;
}
OP_STATUS VEGAD3d10FramebufferObject::attachColor(VEGA3dTexture* color, VEGA3dTexture::CubeSide side)
{
VEGARefCount::IncRef(color);
VEGARefCount::DecRef(m_attachedColorTex);
m_attachedColorTex = color;
VEGARefCount::DecRef(m_attachedColorBuf);
m_attachedColorBuf = NULL;
#ifdef VEGA_BACKEND_D2D_INTEROPERABILITY
StopDrawingD2D();
if (m_d2dRenderTarget)
m_d2dRenderTarget->Release();
m_d2dRenderTarget = NULL;
#endif // VEGA_BACKEND_D2D_INTEROPERABILITY
if (m_texRTView)
m_texRTView->Release();
m_texRTView = NULL;
if (color)
{
D3D10_RENDER_TARGET_VIEW_DESC rtvDesc;
op_memset(&rtvDesc, 0, sizeof(D3D10_RENDER_TARGET_VIEW_DESC));
switch (color->getFormat())
{
case VEGA3dTexture::FORMAT_RGBA8888:
case VEGA3dTexture::FORMAT_RGBA4444:
rtvDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
break;
case VEGA3dTexture::FORMAT_RGB888:
rtvDesc.Format = DXGI_FORMAT_B8G8R8X8_UNORM;
break;
case VEGA3dTexture::FORMAT_RGBA5551:
rtvDesc.Format = DXGI_FORMAT_B5G5R5A1_UNORM;
break;
case VEGA3dTexture::FORMAT_RGB565:
rtvDesc.Format = DXGI_FORMAT_B5G6R5_UNORM;
break;
case VEGA3dTexture::FORMAT_ALPHA8:
rtvDesc.Format = m_featureLevel9?DXGI_FORMAT_B8G8R8A8_UNORM:DXGI_FORMAT_A8_UNORM;
break;
case VEGA3dTexture::FORMAT_LUMINANCE8:
// Wastes memory, but there is no luminance texture in d3d 10 and we cannot rely on shaders since the shaders can come from webgl
rtvDesc.Format = DXGI_FORMAT_B8G8R8X8_UNORM;
break;
case VEGA3dTexture::FORMAT_LUMINANCE8_ALPHA8:
// Wastes memory, but there is no luminance alpha texture in d3d 10 and we cannot rely on shaders since the shaders can come from webgl
rtvDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
break;
default:
OP_ASSERT(false);
break;
}
switch (side)
{
case VEGA3dTexture::CUBE_SIDE_NEG_X:
rtvDesc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2DARRAY;
rtvDesc.Texture2DArray.MipSlice = 0;
rtvDesc.Texture2DArray.FirstArraySlice = D3D10_TEXTURECUBE_FACE_NEGATIVE_X;
rtvDesc.Texture2DArray.ArraySize = 1;
break;
case VEGA3dTexture::CUBE_SIDE_POS_X:
rtvDesc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2DARRAY;
rtvDesc.Texture2DArray.MipSlice = 0;
rtvDesc.Texture2DArray.FirstArraySlice = D3D10_TEXTURECUBE_FACE_POSITIVE_X;
rtvDesc.Texture2DArray.ArraySize = 1;
break;
case VEGA3dTexture::CUBE_SIDE_NEG_Y:
rtvDesc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2DARRAY;
rtvDesc.Texture2DArray.MipSlice = 0;
rtvDesc.Texture2DArray.FirstArraySlice = D3D10_TEXTURECUBE_FACE_NEGATIVE_Y;
rtvDesc.Texture2DArray.ArraySize = 1;
break;
case VEGA3dTexture::CUBE_SIDE_POS_Y:
rtvDesc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2DARRAY;
rtvDesc.Texture2DArray.MipSlice = 0;
rtvDesc.Texture2DArray.FirstArraySlice = D3D10_TEXTURECUBE_FACE_POSITIVE_Y;
rtvDesc.Texture2DArray.ArraySize = 1;
break;
case VEGA3dTexture::CUBE_SIDE_NEG_Z:
rtvDesc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2DARRAY;
rtvDesc.Texture2DArray.MipSlice = 0;
rtvDesc.Texture2DArray.FirstArraySlice = D3D10_TEXTURECUBE_FACE_NEGATIVE_Z;
rtvDesc.Texture2DArray.ArraySize = 1;
break;
case VEGA3dTexture::CUBE_SIDE_POS_Z:
rtvDesc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2DARRAY;
rtvDesc.Texture2DArray.MipSlice = 0;
rtvDesc.Texture2DArray.FirstArraySlice = D3D10_TEXTURECUBE_FACE_POSITIVE_Z;
rtvDesc.Texture2DArray.ArraySize = 1;
break;
default:
rtvDesc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2D;
rtvDesc.Texture2D.MipSlice = 0;
break;
}
HRESULT res = m_d3dDevice->CreateRenderTargetView(static_cast<VEGAD3d10Texture*>(color)->getTextureResource(), &rtvDesc, &m_texRTView);
if (FAILED(res))
{
m_texRTView = NULL;
VEGARefCount::DecRef(m_attachedColorTex);
m_attachedColorTex = NULL;
return (res == E_OUTOFMEMORY)?OpStatus::ERR_NO_MEMORY:OpStatus::ERR;
}
}
return OpStatus::OK;
}
OP_STATUS VEGAD3d10FramebufferObject::attachColor(VEGA3dRenderbufferObject* color)
{
VEGARefCount::IncRef(color);
VEGARefCount::DecRef(m_attachedColorTex);
m_attachedColorTex = NULL;
#ifdef VEGA_BACKEND_D2D_INTEROPERABILITY
StopDrawingD2D();
if (m_d2dRenderTarget)
m_d2dRenderTarget->Release();
m_d2dRenderTarget = NULL;
#endif // VEGA_BACKEND_D2D_INTEROPERABILITY
if (m_texRTView)
m_texRTView->Release();
m_texRTView = NULL;
VEGARefCount::DecRef(m_attachedColorBuf);
m_attachedColorBuf = color;
return OpStatus::OK;
}
OP_STATUS VEGAD3d10FramebufferObject::attachDepth(VEGA3dRenderbufferObject* depth)
{
VEGARefCount::IncRef(depth);
VEGARefCount::DecRef(m_attachedDepthStencilBuf);
m_attachedDepthStencilBuf = depth;
return OpStatus::OK;
}
OP_STATUS VEGAD3d10FramebufferObject::attachStencil(VEGA3dRenderbufferObject* stencil)
{
VEGARefCount::IncRef(stencil);
VEGARefCount::DecRef(m_attachedDepthStencilBuf);
m_attachedDepthStencilBuf = stencil;
return OpStatus::OK;
}
OP_STATUS VEGAD3d10FramebufferObject::attachDepthStencil(VEGA3dRenderbufferObject* depthStencil)
{
VEGARefCount::IncRef(depthStencil);
VEGARefCount::DecRef(m_attachedDepthStencilBuf);
m_attachedDepthStencilBuf = depthStencil;
return OpStatus::OK;
}
VEGA3dTexture* VEGAD3d10FramebufferObject::getAttachedColorTexture()
{
return m_attachedColorTex;
}
VEGA3dRenderbufferObject* VEGAD3d10FramebufferObject::getAttachedColorBuffer()
{
return m_attachedColorBuf;
}
VEGA3dRenderbufferObject* VEGAD3d10FramebufferObject::getAttachedDepthStencilBuffer()
{
return m_attachedDepthStencilBuf;
}
unsigned int VEGAD3d10FramebufferObject::getRedBits()
{
if (m_attachedColorBuf)
return m_attachedColorBuf->getRedBits();
if (m_attachedColorTex)
{
switch (m_attachedColorTex->getFormat())
{
case VEGA3dTexture::FORMAT_RGBA8888:
case VEGA3dTexture::FORMAT_RGB888:
case VEGA3dTexture::FORMAT_RGBA4444:
return 8;
case VEGA3dTexture::FORMAT_RGBA5551:
case VEGA3dTexture::FORMAT_RGB565:
return 5;
default:
break;
}
}
return 0;
}
unsigned int VEGAD3d10FramebufferObject::getGreenBits()
{
if (m_attachedColorBuf)
return m_attachedColorBuf->getGreenBits();
if (m_attachedColorTex)
{
switch (m_attachedColorTex->getFormat())
{
case VEGA3dTexture::FORMAT_RGBA8888:
case VEGA3dTexture::FORMAT_RGB888:
case VEGA3dTexture::FORMAT_RGBA4444:
return 8;
case VEGA3dTexture::FORMAT_RGBA5551:
return 5;
case VEGA3dTexture::FORMAT_RGB565:
return 6;
default:
break;
}
}
return 0;
}
unsigned int VEGAD3d10FramebufferObject::getBlueBits()
{
if (m_attachedColorBuf)
return m_attachedColorBuf->getBlueBits();
if (m_attachedColorTex)
{
switch (m_attachedColorTex->getFormat())
{
case VEGA3dTexture::FORMAT_RGBA8888:
case VEGA3dTexture::FORMAT_RGB888:
case VEGA3dTexture::FORMAT_RGBA4444:
return 8;
case VEGA3dTexture::FORMAT_RGBA5551:
case VEGA3dTexture::FORMAT_RGB565:
return 5;
default:
break;
}
}
return 0;
}
unsigned int VEGAD3d10FramebufferObject::getAlphaBits()
{
if (m_attachedColorBuf)
return m_attachedColorBuf->getAlphaBits();
if (m_attachedColorTex)
{
switch (m_attachedColorTex->getFormat())
{
case VEGA3dTexture::FORMAT_RGBA8888:
case VEGA3dTexture::FORMAT_RGBA4444:
return 8;
case VEGA3dTexture::FORMAT_RGBA5551:
return 1;
default:
break;
}
}
return 0;
}
unsigned int VEGAD3d10FramebufferObject::getDepthBits()
{
if (m_attachedDepthStencilBuf)
m_attachedDepthStencilBuf->getDepthBits();
return 0;
}
unsigned int VEGAD3d10FramebufferObject::getStencilBits()
{
if (m_attachedDepthStencilBuf)
m_attachedDepthStencilBuf->getStencilBits();
return 0;
}
unsigned int VEGAD3d10FramebufferObject::getSubpixelBits()
{
return D3D10_SUBPIXEL_FRACTIONAL_BIT_COUNT;
}
unsigned int VEGAD3d10FramebufferObject::getSampleBuffers()
{
if (m_attachedColorBuf)
return (m_attachedColorBuf->getNumSamples()>1)?1:0;
return 0;
}
unsigned int VEGAD3d10FramebufferObject::getSamples()
{
if (m_attachedColorBuf)
return m_attachedColorBuf->getNumSamples();
return 0;
}
ID3D10RenderTargetView* VEGAD3d10FramebufferObject::getRenderTargetView()
{
if (m_attachedColorBuf)
return static_cast<VEGAD3d10RenderbufferObject*>(m_attachedColorBuf)->getRenderTargetView();
return m_texRTView;
}
ID3D10DepthStencilView* VEGAD3d10FramebufferObject::getDepthStencilView()
{
if (m_attachedDepthStencilBuf)
return static_cast<VEGAD3d10RenderbufferObject*>(m_attachedDepthStencilBuf)->getDepthStencilView();
return NULL;
}
ID3D10Texture2D* VEGAD3d10FramebufferObject::getColorResource()
{
if (m_attachedColorTex)
return static_cast<VEGAD3d10Texture*>(m_attachedColorTex)->getTextureResource();
if (m_attachedColorBuf)
return static_cast<VEGAD3d10RenderbufferObject*>(m_attachedColorBuf)->getTextureResource();
return NULL;
}
#ifdef VEGA_BACKEND_D2D_INTEROPERABILITY
ID2D1RenderTarget* VEGAD3d10FramebufferObject::getD2DRenderTarget(bool requireDestAlpha, FontFlushListener* fontFlushListener)
{
if (!m_d2dRenderTarget)
{
HRESULT hr = S_OK;
IDXGISurface *pDxgiSurface = NULL;
if (m_attachedColorTex)
hr = static_cast<VEGAD3d10Texture*>(m_attachedColorTex)->getTextureResource()->QueryInterface(&pDxgiSurface);
else if (m_attachedColorBuf)
hr = static_cast<VEGAD3d10RenderbufferObject*>(m_attachedColorBuf)->getTextureResource()->QueryInterface(&pDxgiSurface);
else
return NULL;
if (FAILED(hr))
return NULL;
D2D1_RENDER_TARGET_PROPERTIES rtProps;
rtProps.type = D2D1_RENDER_TARGET_TYPE_DEFAULT;
rtProps.pixelFormat.format = DXGI_FORMAT_UNKNOWN;
rtProps.pixelFormat.alphaMode = requireDestAlpha?D2D1_ALPHA_MODE_PREMULTIPLIED:D2D1_ALPHA_MODE_IGNORE;
rtProps.dpiX = 0;
rtProps.dpiY = 0;
rtProps.usage = D2D1_RENDER_TARGET_USAGE_NONE;
rtProps.minLevel = m_d2dFLevel;
hr = m_d2dFactory->CreateDxgiSurfaceRenderTarget(pDxgiSurface, &rtProps, &m_d2dRenderTarget);
pDxgiSurface->Release();
if (FAILED(hr))
m_d2dRenderTarget = NULL;
else
m_d2dRenderTarget->SetTextAntialiasMode(m_textMode);
}
if (!m_isDrawingD2D && m_d2dRenderTarget)
{
m_fontFlushListener = fontFlushListener;
m_d2dRenderTarget->BeginDraw();
m_isDrawingD2D = true;
if (m_attachedColorTex)
static_cast<VEGAD3d10Texture*>(m_attachedColorTex)->setActiveD2DFBO(this);
else
static_cast<VEGAD3d10RenderbufferObject*>(m_attachedColorBuf)->setActiveD2DFBO(this);
}
return m_d2dRenderTarget;
}
void VEGAD3d10FramebufferObject::StopDrawingD2D()
{
if (m_isDrawingD2D)
{
m_isDrawingD2D = false;
m_fontFlushListener->flushFontBatch();
m_d2dRenderTarget->EndDraw();
if (m_attachedColorTex)
static_cast<VEGAD3d10Texture*>(m_attachedColorTex)->setActiveD2DFBO(NULL);
else
static_cast<VEGAD3d10RenderbufferObject*>(m_attachedColorBuf)->setActiveD2DFBO(NULL);
}
}
# ifdef VEGA_NATIVE_FONT_SUPPORT
void VEGAD3d10FramebufferObject::flushFonts()
{
if (m_isDrawingD2D)
{
m_fontFlushListener->flushFontBatch();
m_d2dRenderTarget->Flush();
}
}
# endif // VEGA_NATIVE_FONT_SUPPORT
#endif // VEGA_BACKEND_D2D_INTEROPERABILITY
#endif //NO_DXSDK
#endif // VEGA_BACKEND_DIRECT3D10
|
#include <stdio.h>
#include <string.h>
int main() {
char str[1007];
int length;
int sum = 0;
while (gets(str) != NULL) {
length = strlen(str);
sum = 0;
for(int i = 0; i < length; i++) {
if (str[i] == ')')
sum--;
else if(str[i] == '(')
sum++;
if(sum < 0) {
break;
}
}
if(sum == 0)
printf("Yes\n");
else
printf("No\n");
}
return 0;
}
|
#include <fstream>
#include <getopt.h>
#include <iostream>
#include "Messages/Messages.h"
#include "ProgramLogic/ProgramLogic.h"
int main(int argc, char** argv) {
ProgramLogic* programme = new ProgramLogic();
int opt;
opterr = 0;
unsigned options = 0;
while((opt=getopt(argc, argv, "a:bcd")) != -1){
switch (opt){
case 'a':
programme->setMode(ProgramLogic::Mode::inputFromFile);
programme->setFileName(optarg);
break;
case 'b':
programme->setMode(ProgramLogic::Mode::inputFromCommandLine);
break;
case 'c':
programme->setMode(ProgramLogic::Mode::generateInput);
break;
case 'd':
programme->setMode(ProgramLogic::Mode::generateInputAndMeasureTime);
break;
case '?':
if(optopt == 'a'){
std::cerr << "Option 'a' requires an argument (file name)" << NEWLINE;
return 1;
}
else{
std::cerr << "Uknown option: " << char(optopt) << NEWLINE;
return 1;
}
}
++options;
}
if(options != 1){
std::cerr << BADFLAGS << NEWLINE;
return 1;
}
programme->execute();
delete programme;
return 0;
}
|
#include "leg_detector/leg_detector_lib.h"
LegDetector::LegDetector(const std::string& model_path) :
mask_count_(0),
feat_count_(0),
next_p_id_(0),
no_observation_timeout_s_(0.5),
max_second_leg_age_s_(2.0),
max_track_jump_m_(3.0),
max_meas_jump_m_(3.0),
leg_pair_separation_m_(2.0),
fixed_frame_("odom"),
kal_p_(4),
kal_q_(0.002),
kal_r_(10),
use_filter_(true),
connected_thresh_(0.1),
min_points_per_group(5),
leg_reliability_limit_(0.4)
{
forest = cv::ml::StatModel::load<cv::ml::RTrees>(model_path);
feat_count_ = forest->getVarCount();
printf("Loaded forest with %d features: %s\n", feat_count_, model_path.c_str());
feature_id_ = 0;
}
LegDetector::~LegDetector()
{
}
double LegDetector::distance(std::list<std::shared_ptr<SavedFeature>>::iterator it1, std::list<std::shared_ptr<SavedFeature>>::iterator it2) const
{
const tf::Stamped<tf::Point> one = (*it1)->position_, two = (*it2)->position_;
const double dx = one[0] - two[0], dy = one[1] - two[1], dz = one[2] - two[2];
return sqrt(dx * dx + dy * dy + dz * dz);
}
void LegDetector::pairLegs()
{
// Deal With legs that already have ids
std::list<std::shared_ptr<SavedFeature>>::iterator begin = saved_features_.begin();
std::list<std::shared_ptr<SavedFeature>>::iterator end = saved_features_.end();
std::list<std::shared_ptr<SavedFeature>>::iterator leg1, leg2, best, it;
for (leg1 = begin; leg1 != end; ++leg1)
{
// If this leg has no id, skip
if ((*leg1)->object_id == "")
continue;
leg2 = end;
best = end;
double closest_dist = leg_pair_separation_m_;
for (it = begin; it != end; ++it)
{
if (it == leg1) continue;
if ((*it)->object_id == (*leg1)->object_id)
{
leg2 = it;
break;
}
if ((*it)->object_id != "")
continue;
double d = distance(it, leg1);
if (((*it)->getLifetime() <= max_second_leg_age_s_)
&& (d < closest_dist))
{
closest_dist = d;
best = it;
}
}
if (leg2 != end)
{
double dist_between_legs = distance(leg1, leg2);
if (dist_between_legs > leg_pair_separation_m_)
{
(*leg1)->object_id = "";
(*leg1)->other = NULL;
(*leg2)->object_id = "";
(*leg2)->other = NULL;
}
else
{
(*leg1)->other = *leg2;
(*leg2)->other = *leg1;
}
}
else if (best != end)
{
(*best)->object_id = (*leg1)->object_id;
(*leg1)->other = *best;
(*best)->other = *leg1;
}
}
// Attempt to pair up legs with no id
for (;;)
{
std::list<std::shared_ptr<SavedFeature>>::iterator best1 = end, best2 = end;
double closest_dist = leg_pair_separation_m_;
for (leg1 = begin; leg1 != end; ++leg1)
{
// If this leg has an id or low reliability, skip
if ((*leg1)->object_id != ""
|| (*leg1)->getReliability() < leg_reliability_limit_)
continue;
for (leg2 = begin; leg2 != end; ++leg2)
{
if (((*leg2)->object_id != "")
|| ((*leg2)->getReliability() < leg_reliability_limit_)
|| (leg1 == leg2)) continue;
double d = distance(leg1, leg2);
if (d < closest_dist)
{
best1 = leg1;
best2 = leg2;
}
}
}
if (best1 != end)
{
std::string object_id_str = "Person" + std::to_string(next_p_id_++);
(*best1)->object_id = object_id_str;
(*best2)->object_id = object_id_str;
(*best1)->other = *best2;
(*best2)->other = *best1;
}
else
{
break;
}
}
}
std::vector<people_msgs::PersonPositionMeasurement> LegDetector::processLaserScan(const sensor_msgs::LaserScan& scan, tf::TransformListener& tfl)
{
laser_processor::ScanProcessor processor(scan, mask_);
processor.splitConnected(connected_thresh_);
processor.removeLessThan(5);
cv::Mat tmp_mat = cv::Mat(1, feat_count_, CV_32FC1);
// if no measurement matches to a tracker in the last <no_observation_timeout> seconds: erase tracker
ros::Time purge = scan.header.stamp + ros::Duration().fromSec(-no_observation_timeout_s_);
std::list<std::shared_ptr<SavedFeature>>::iterator sf_iter = saved_features_.begin();
while (sf_iter != saved_features_.end())
{
if ((*sf_iter)->meas_time_ < purge)
{
if ((*sf_iter)->other)
(*sf_iter)->other->other = NULL;
sf_iter = saved_features_.erase(sf_iter);
}
else
++sf_iter;
}
// System update of trackers, and copy updated ones in propagate list
std::list<std::shared_ptr<SavedFeature>> propagated;
for (auto& sf : saved_features_)
{
sf->propagate(scan.header.stamp);
propagated.push_back(sf);
}
// Detection step: build up the set of "candidate" clusters
// For each candidate, find the closest tracker (within threshold) and add to the match list
// If no tracker is found, start a new one
BFL::multiset<MatchedFeature> matches;
for (std::list<laser_processor::SampleSet*>::iterator i = processor.getClusters().begin();
i != processor.getClusters().end();
i++)
{
std::vector<float> f = calcLegFeatures(*i, scan);
for (int k = 0; k < feat_count_; k++)
tmp_mat.data[k] = (float)(f[k]);
float probability = 0.5 - forest->predict(tmp_mat, cv::noArray(), cv::ml::RTrees::PREDICT_SUM) / forest->getRoots().size();
tf::Stamped<tf::Point> loc((*i)->center(), scan.header.stamp, scan.header.frame_id);
try
{
tfl.transformPoint(fixed_frame_, loc, loc);
}
catch (...)
{
ROS_WARN("TF exception spot 3.");
}
std::list<std::shared_ptr<SavedFeature>>::iterator closest = propagated.end();
float closest_dist = max_track_jump_m_;
for (std::list<std::shared_ptr<SavedFeature>>::iterator pf_iter = propagated.begin();
pf_iter != propagated.end();
pf_iter++)
{
// find the closest distance between candidate and trackers
float dist = loc.distance((*pf_iter)->position_);
if (dist < closest_dist)
{
closest = pf_iter;
closest_dist = dist;
}
}
// Nothing close to it, start a new track
if (closest == propagated.end())
{
std::list<std::shared_ptr<SavedFeature>>::iterator new_saved = saved_features_.insert(saved_features_.end(), std::make_shared<SavedFeature>(loc, tfl, fixed_frame_, use_filter_, kal_p_, kal_q_, kal_r_));
}
// Add the candidate, the tracker and the distance to a match list
else
matches.insert(MatchedFeature(*i, *closest, closest_dist, probability));
}
// loop through _sorted_ matches list
// find the match with the shortest distance for each tracker
while (!matches.empty())
{
BFL::multiset<MatchedFeature>::iterator matched_iter = matches.begin();
bool found = false;
std::list<std::shared_ptr<SavedFeature>>::iterator pf_iter = propagated.begin();
while (pf_iter != propagated.end())
{
// update the tracker with this candidate
if (matched_iter->closest_ == *pf_iter)
{
// Transform candidate to fixed frame
tf::Stamped<tf::Point> loc(matched_iter->candidate_->center(), scan.header.stamp, scan.header.frame_id);
try
{
tfl.transformPoint(fixed_frame_, loc, loc);
}
catch (...)
{
ROS_WARN("TF exception spot 4.");
}
// Update the tracker with the candidate location
matched_iter->closest_->update(loc, matched_iter->probability_);
// remove this match and
matches.erase(matched_iter);
propagated.erase(pf_iter++);
found = true;
break;
}
// still looking for the tracker to update
else
{
pf_iter++;
}
}
// didn't find tracker to update, because it was deleted above
// try to assign the candidate to another tracker
if (!found)
{
tf::Stamped<tf::Point> loc(matched_iter->candidate_->center(), scan.header.stamp, scan.header.frame_id);
try
{
tfl.transformPoint(fixed_frame_, loc, loc);
}
catch (...)
{
ROS_WARN("TF exception spot 5.");
}
std::list<std::shared_ptr<SavedFeature>>::iterator closest = propagated.end();
float closest_dist = max_track_jump_m_;
for (std::list<std::shared_ptr<SavedFeature>>::iterator remain_iter = propagated.begin();
remain_iter != propagated.end();
remain_iter++)
{
float dist = loc.distance((*remain_iter)->position_);
if (dist < closest_dist)
{
closest = remain_iter;
closest_dist = dist;
}
}
// no tracker is within a threshold of this candidate
// so create a new tracker for this candidate
if (closest == propagated.end())
std::list<std::shared_ptr<SavedFeature>>::iterator new_saved = saved_features_.insert(saved_features_.end(), std::make_shared<SavedFeature>(loc, tfl, fixed_frame_, use_filter_, kal_p_, kal_q_, kal_r_));
else
matches.insert(MatchedFeature(matched_iter->candidate_, *closest, closest_dist, matched_iter->probability_));
matches.erase(matched_iter);
}
}
pairLegs();
// Publish Data!
int i = 0;
std::vector<people_msgs::PersonPositionMeasurement> people;
std::vector<people_msgs::PositionMeasurement> legs;
for (std::list<std::shared_ptr<SavedFeature>>::iterator sf_iter = saved_features_.begin();
sf_iter != saved_features_.end();
sf_iter++, i++)
{
// reliability
double reliability = (*sf_iter)->getReliability();
if ((*sf_iter)->getReliability() > leg_reliability_limit_)
{
people_msgs::PositionMeasurement pos;
pos.header.stamp = scan.header.stamp;
pos.header.frame_id = fixed_frame_;
pos.name = "leg_detector";
pos.object_id = (*sf_iter)->id_;
pos.pos.x = (*sf_iter)->position_[0];
pos.pos.y = (*sf_iter)->position_[1];
pos.pos.z = (*sf_iter)->position_[2];
pos.reliability = reliability;
pos.covariance[0] = pow(0.3 / reliability, 2.0);
pos.covariance[1] = 0.0;
pos.covariance[2] = 0.0;
pos.covariance[3] = 0.0;
pos.covariance[4] = pow(0.3 / reliability, 2.0);
pos.covariance[5] = 0.0;
pos.covariance[6] = 0.0;
pos.covariance[7] = 0.0;
pos.covariance[8] = 10000.0;
pos.initialization = 0;
legs.push_back(pos);
}
std::shared_ptr<SavedFeature> other = (*sf_iter)->other;
if (other != NULL && other < (*sf_iter))
{
double dx = ((*sf_iter)->position_[0] + other->position_[0]) / 2,
dy = ((*sf_iter)->position_[1] + other->position_[1]) / 2,
dz = ((*sf_iter)->position_[2] + other->position_[2]) / 2;
reliability = reliability * other->reliability;
people_msgs::PersonPositionMeasurement pos;
pos.header.stamp = (*sf_iter)->time_;
pos.header.frame_id = fixed_frame_;
pos.name = (*sf_iter)->object_id;;
pos.object_id = (*sf_iter)->id_ + "|" + other->id_;
pos.pos.x = dx;
pos.pos.y = dy;
pos.pos.z = dz;
pos.leg1_pos.x = (*sf_iter)->position_[0];
pos.leg1_pos.y = (*sf_iter)->position_[1];
pos.leg1_pos.z = (*sf_iter)->position_[2];
pos.leg2_pos.x = other->position_[0];
pos.leg2_pos.y = other->position_[1];
pos.leg2_pos.z = other->position_[2];
pos.reliability = reliability;
pos.covariance[0] = pow(0.3 / reliability, 2.0);
pos.covariance[1] = 0.0;
pos.covariance[2] = 0.0;
pos.covariance[3] = 0.0;
pos.covariance[4] = pow(0.3 / reliability, 2.0);
pos.covariance[5] = 0.0;
pos.covariance[6] = 0.0;
pos.covariance[7] = 0.0;
pos.covariance[8] = 10000.0;
pos.initialization = 0;
people.push_back(pos);
}
}
return people;
}
|
#include "BurrowsWheelerTransform.h"
#include "SuffixArray.h"
#include <string>
BurrowsWheelerTransform::BurrowsWheelerTransform()
{
}
BurrowsWheelerTransform::~BurrowsWheelerTransform()
{
}
char* BurrowsWheelerTransform::transform(char* str, int strlength)
{
//int strlength = strlen(str);
SuffixArray* suffixArr = new SuffixArray(str, strlength);
char* result = new char[strlength + 1];
result[strlength] = '\0';
for (int i = 0; i < strlength; i++)
{
result[i] = str[(suffixArr->sfArr[i] - 1 + strlength) % strlength];
}
delete suffixArr;
return result;
}
template<typename T>
int BurrowsWheelerTransform::findIndex(T* arr, int arrSize, T elm)
{
for (int i = 0; i < arrSize; i++)
{
if (arr[i] == elm) return i;
}
return -1;
}
int BurrowsWheelerTransform::preProcessStr(char* str, int** apbLog, int apbSize)
{
if (*apbLog)
{
delete[] * apbLog;
}
*apbLog = new int[apbSize]();
int strlength = 0;
int curChar = str[strlength];
while (curChar != '\0')
{
(*apbLog)[(unsigned char)curChar]++;
strlength++;
curChar = str[strlength];
}
return strlength;
}
char* BurrowsWheelerTransform::inverseTransform(char* str)
{
int* apbLog = nullptr;
int apbSize = 300;
int strlength = preProcessStr(str, &apbLog, apbSize);
int sum = 0;
int* apbIndex = new int[apbSize]();
for (int i = 0; i < apbSize; i++)
{
apbIndex[i] = sum;
sum += apbLog[i];
}
delete[] apbLog;
char* result = new char[strlength + 1];
result[strlength] = '\0';
int* nextStr = new int[strlength];
for (int i = 0; i < strlength; i++)
{
unsigned char curChar = str[i];
nextStr[apbIndex[(unsigned char)curChar]] = i;
apbIndex[curChar]++;
}
int index = findIndex<char>(str, strlength, END_OF_STR);
for (int i = 0; i < strlength; i++)
{
result[i] = str[nextStr[index]];
index = nextStr[index];
}
delete[] nextStr;
delete[] apbIndex;
return result;
}
//void BurrowsWheelerTransform::doTransform(char* str, int strlength, char** outBuffer, int index)
//{
// outBuffer[index] = transform(str, strlength);
//}
|
#include <iostream>
#include <cstdio>
#include <cassert>
#include <cstring>
using namespace std;
int Hash[27][27][27][27][27];
int main(){
int n;
int count = 0;
char str[10];
int a,b,c,d,e;
//cin >> n;
scanf("%d",&n);
for(int i = 0; i < n; i++){
//cin >> str;
scanf("%s",str);
a = 0,b = 0, c= 0, d= 0, e=0;
for(int j = 0; j<strlen(str);i++){
if(j == 0){
a = str[j] - 'a' + 1;
}
if(j == 1){
b = str[j] - 'a' + 1;
}
if(j == 2){
c = str[j] - 'a' + 1;
}
if(j == 3){
d = str[j] - 'a' + 1;
}
if(j == 4){
e = str[j] - 'a' + 1;
}
}
if(!Hash[a][b][c][d][e]){
count ++;
}
Hash[a][b][c][d][e] = 1;
}
printf("%d\n",count);
for(a = 0; a< 27; a++){
for(b = 0; b<27;b++){
for(c = 0; c < 27; c++){
for(d = 0; d < 27; d++){
for(e = 0; e < 27; e++){
if(Hash[a][b][c][d][e]){
printf("%c",a+'a'-1);
if(b){
printf("%c",b+'a'-1);
}
if(c){
printf("%c",c+'a'-1);
}
if(d){
printf("%c",d+'a'-1);
}
if(e){
printf("%c",e+'a'-1);
}
printf("\n");
}
}
}
}
}
}
return 0;
}
|
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <list>
#include <algorithm>
#include <sstream>
#include <set>
#include <cmath>
#include <map>
#include <stack>
#include <queue>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <numeric>
using namespace std;
#define INF (1<<29)
class VacationTime {
public:
int
bestSchedule(int N, int K, vector <int> workingDays)
{
int res = INF;
for (int s=1; s+K-1<=N; ++s) {
int t = 0;
for (int i=0; i<K; ++i) {
int d = s+i;
for (int j=0; j<workingDays.size(); ++j) {
if (workingDays[j] == d) {
++t;
break;
}
}
}
res = min(res,t);
}
return res;
}
// 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(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
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 int &Expected, const int &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 = 3; int Arg1 = 3; int Arr2[] = {2}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 1; verify_case(0, Arg3, bestSchedule(Arg0, Arg1, Arg2)); }
void test_case_1() { int Arg0 = 4; int Arg1 = 3; int Arr2[] = {3, 1, 2}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 2; verify_case(1, Arg3, bestSchedule(Arg0, Arg1, Arg2)); }
void test_case_2() { int Arg0 = 5; int Arg1 = 3; int Arr2[] = {4, 1}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 1; verify_case(2, Arg3, bestSchedule(Arg0, Arg1, Arg2)); }
void test_case_3() { int Arg0 = 9; int Arg1 = 2; int Arr2[] = {7, 4, 5, 6, 2}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 0; verify_case(3, Arg3, bestSchedule(Arg0, Arg1, Arg2)); }
void test_case_4() { int Arg0 = 1000; int Arg1 = 513; int Arr2[] = {808, 459, 792, 863, 715, 70, 336, 731}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 2; verify_case(4, Arg3, bestSchedule(Arg0, Arg1, Arg2)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
VacationTime ___test;
___test.run_test(-1);
}
// END CUT HERE
|
#include <iostream>
using namespace std;
int main()
{
int n, cur = 0;
string s;
cin >> n >> s;
for (int i = 0; i + cur <= n; i += 1)
{
cout << s[i + cur];
cur++;
}
}
|
//---------------------------------------------------------------------------
//更新记录
#ifndef srvthreadH
#define srvthreadH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <ScktComp.hpp>
class CServerSocket;
enum ThreadState{tsWAIT,tsCLIENT_CONNECT,tsSERVERCONNECT,tsPROCESS_CLIENT,tsPROCESS_SERVER,tsCLOSE};
//---------------------------------------------------------------------------
class CServerThread : public TThread
{
private:
SOCKET m_ClientSocket;
CServerSocket * m_ServerSocket;
bool m_ClientConnect; //客户端是否连接中
String m_ClientIP;
String m_LastError;
protected:
void __fastcall Execute();
public:
void * lpUserData; //用户自定义数据
int State;
int RecvLen();
void __fastcall Log();
void __fastcall ErrLog();
public:
__fastcall CServerThread(bool CreateSuspended,CServerSocket * ServerSocket);
int Recv(char * lpBuffer,int Len);
int Send(char * lpBuffer,int Len);
void CloseSocket();
void ShowLog(String LogStr);
void ShowErrLog(String LogStr);
String GetClientIP(){return m_ClientIP;}
SOCKET GetSocket(){return m_ClientSocket;}
};
//---------------------------------------------------------------------------
#endif
|
/*
* Given a binary tree and a sum, find all root-to-leaf paths
* where each path's sum equals the given sum.
*
* For example:
* Given the below binary tree and sum = 22,
* 5
* / \
* 4 8
* / / \
* 11 13 4
* / \ / \
* 7 2 5 1
* return
* [
* [5,4,11,2],
* [5,8,4,5]
* ]
*/
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > pathSum(TreeNode *root, int sum) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<vector<int> > ret;
if (root == nullptr) {
return ret;
}
do_pathsum(root, sum, ret);
return ret;
}
void do_pathsum(TreeNode *root, const int sum, vector<vector<int> > &ret) {
static int cur = 0;
static vector<int> s;
cur += root->val; // update current sum
s.push_back(root->val);
if (root->left != nullptr)
do_pathsum(root->left, sum, ret);
if (root->right != nullptr)
do_pathsum(root->right, sum, ret);
if (root->left == nullptr && root->right == nullptr) { // base case
if (sum == cur) {
ret.push_back(s);
}
}
s.pop_back(); // backtracking
cur -= root->val;
}
};
|
#pragma once
#include "Vector.h"
#include "windows.h"
class Vertex
{
public:
Vertex();
Vertex(float, float, float);
Vertex(const Vertex&);
// Accessors
float GetX() const;
void SetX(const float);
float GetY() const;
void SetY(const float);
void SetZ(const float);
float GetZ() const;
float GetW() const;
void SetW(const float);
void Dehomogenise();
void SetNormal(const Vector);
Vector GetNormal() const;
void SetColour(const COLORREF);
COLORREF GetColour() const;
void SetCount(const int);
int GetCount() const;
void IncreaseCount();
void DivideNormalByCount();
// Assignment operator
Vertex& operator= (const Vertex& rhs);
bool operator== (const Vertex& rhs) const;
const Vertex operator+ (const Vertex& rhs) const;
const Vector SubstractVertexToVector (const Vertex& ) const;
private:
Vertex& Copy(const Vertex&);
float _x;
float _y;
float _z;
float _w;
Vector _normal;
COLORREF _colour;
// Number of times a Vertex is used in a polygon
int _count;
};
|
// 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_DungeonEscapeGameModeBase_generated_h
#error "DungeonEscapeGameModeBase.generated.h already included, missing '#pragma once' in DungeonEscapeGameModeBase.h"
#endif
#define DUNGEONESCAPE_DungeonEscapeGameModeBase_generated_h
#define DungeonEscape_Source_DungeonEscape_DungeonEscapeGameModeBase_h_15_SPARSE_DATA
#define DungeonEscape_Source_DungeonEscape_DungeonEscapeGameModeBase_h_15_RPC_WRAPPERS
#define DungeonEscape_Source_DungeonEscape_DungeonEscapeGameModeBase_h_15_RPC_WRAPPERS_NO_PURE_DECLS
#define DungeonEscape_Source_DungeonEscape_DungeonEscapeGameModeBase_h_15_INCLASS_NO_PURE_DECLS \
private: \
static void StaticRegisterNativesADungeonEscapeGameModeBase(); \
friend struct Z_Construct_UClass_ADungeonEscapeGameModeBase_Statics; \
public: \
DECLARE_CLASS(ADungeonEscapeGameModeBase, AGameModeBase, COMPILED_IN_FLAGS(0 | CLASS_Transient | CLASS_Config), CASTCLASS_None, TEXT("/Script/DungeonEscape"), NO_API) \
DECLARE_SERIALIZER(ADungeonEscapeGameModeBase)
#define DungeonEscape_Source_DungeonEscape_DungeonEscapeGameModeBase_h_15_INCLASS \
private: \
static void StaticRegisterNativesADungeonEscapeGameModeBase(); \
friend struct Z_Construct_UClass_ADungeonEscapeGameModeBase_Statics; \
public: \
DECLARE_CLASS(ADungeonEscapeGameModeBase, AGameModeBase, COMPILED_IN_FLAGS(0 | CLASS_Transient | CLASS_Config), CASTCLASS_None, TEXT("/Script/DungeonEscape"), NO_API) \
DECLARE_SERIALIZER(ADungeonEscapeGameModeBase)
#define DungeonEscape_Source_DungeonEscape_DungeonEscapeGameModeBase_h_15_STANDARD_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API ADungeonEscapeGameModeBase(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(ADungeonEscapeGameModeBase) \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, ADungeonEscapeGameModeBase); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ADungeonEscapeGameModeBase); \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API ADungeonEscapeGameModeBase(ADungeonEscapeGameModeBase&&); \
NO_API ADungeonEscapeGameModeBase(const ADungeonEscapeGameModeBase&); \
public:
#define DungeonEscape_Source_DungeonEscape_DungeonEscapeGameModeBase_h_15_ENHANCED_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API ADungeonEscapeGameModeBase(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()) : Super(ObjectInitializer) { }; \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API ADungeonEscapeGameModeBase(ADungeonEscapeGameModeBase&&); \
NO_API ADungeonEscapeGameModeBase(const ADungeonEscapeGameModeBase&); \
public: \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, ADungeonEscapeGameModeBase); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ADungeonEscapeGameModeBase); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(ADungeonEscapeGameModeBase)
#define DungeonEscape_Source_DungeonEscape_DungeonEscapeGameModeBase_h_15_PRIVATE_PROPERTY_OFFSET
#define DungeonEscape_Source_DungeonEscape_DungeonEscapeGameModeBase_h_12_PROLOG
#define DungeonEscape_Source_DungeonEscape_DungeonEscapeGameModeBase_h_15_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
DungeonEscape_Source_DungeonEscape_DungeonEscapeGameModeBase_h_15_PRIVATE_PROPERTY_OFFSET \
DungeonEscape_Source_DungeonEscape_DungeonEscapeGameModeBase_h_15_SPARSE_DATA \
DungeonEscape_Source_DungeonEscape_DungeonEscapeGameModeBase_h_15_RPC_WRAPPERS \
DungeonEscape_Source_DungeonEscape_DungeonEscapeGameModeBase_h_15_INCLASS \
DungeonEscape_Source_DungeonEscape_DungeonEscapeGameModeBase_h_15_STANDARD_CONSTRUCTORS \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define DungeonEscape_Source_DungeonEscape_DungeonEscapeGameModeBase_h_15_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
DungeonEscape_Source_DungeonEscape_DungeonEscapeGameModeBase_h_15_PRIVATE_PROPERTY_OFFSET \
DungeonEscape_Source_DungeonEscape_DungeonEscapeGameModeBase_h_15_SPARSE_DATA \
DungeonEscape_Source_DungeonEscape_DungeonEscapeGameModeBase_h_15_RPC_WRAPPERS_NO_PURE_DECLS \
DungeonEscape_Source_DungeonEscape_DungeonEscapeGameModeBase_h_15_INCLASS_NO_PURE_DECLS \
DungeonEscape_Source_DungeonEscape_DungeonEscapeGameModeBase_h_15_ENHANCED_CONSTRUCTORS \
private: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
template<> DUNGEONESCAPE_API UClass* StaticClass<class ADungeonEscapeGameModeBase>();
#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID DungeonEscape_Source_DungeonEscape_DungeonEscapeGameModeBase_h
PRAGMA_ENABLE_DEPRECATION_WARNINGS
|
#include <vector>
#include <iostream>
#include <algorithm>
#include "BinaryTree.h"
int main()
{
std::vector<int> v = {5, 4, 1, 3, 7, 6, 8};
BinaryTree<int> tree;
tree.Create(v.begin(), v.end());
tree.MideOrder([](int x) {std::cout << x << std::endl; });
std::cout << std::endl;
tree.PreOrder([](int x) {std::cout << x << std::endl; });
std::cout << std::endl;
tree.BackOrder([](int x) {std::cout << x << std::endl; });
std::cout << std::endl;
tree.Find(1);
tree.Remove(1);
tree.MideOrder([](int x) {std::cout << x << std::endl; });
std::cout << std::endl;
tree.Remove(3);
tree.MideOrder([](int x) {std::cout << x << std::endl; });
std::cout << std::endl;
tree.Remove(4);
tree.MideOrder([](int x) {std::cout << x << std::endl; });
std::cout << std::endl;
tree.Remove(5);
tree.MideOrder([](int x) {std::cout << x << std::endl; });
std::cout << std::endl;
tree.Remove(6);
tree.MideOrder([](int x) {std::cout << x << std::endl; });
std::cout << std::endl;
tree.Remove(7);
tree.MideOrder([](int x) {std::cout << x << std::endl; });
std::cout << std::endl;
tree.Remove(8);
tree.MideOrder([](int x) {std::cout << x << std::endl; });
std::cout << std::endl;
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*-
**
** Copyright (C) 1995-2003 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/logdoc/datasrcelm.h"
#include "modules/util/str.h"
DataSrcElm* DataSrcElm::Create(const uni_char* val, int val_len, BOOL copy)
{
DataSrcElm* de = OP_NEW(DataSrcElm, (val_len, copy));
if (!de)
return NULL;
if (copy)
{
de->m_src = NULL;
if (val)
{
de->m_src = OP_NEWA(uni_char, val_len);
if (de->m_src)
{
op_memcpy(de->m_src, val, val_len * sizeof(uni_char) ); // Must not use uni_strncpy, data can contain NULs
REPORT_MEMMAN_INC(val_len * sizeof(uni_char) + sizeof(DataSrcElm));
}
}
}
else
de->m_src = const_cast<uni_char*>(val);
if (!de->m_src)
{
OP_DELETE(de);
return NULL;
}
return de;
}
DataSrcElm::~DataSrcElm()
{
if (m_src && m_owns_src)
{
REPORT_MEMMAN_DEC(m_src_len * sizeof(uni_char) + sizeof(DataSrcElm));
OP_DELETEA(m_src);
}
}
/*static*/ OP_STATUS
DataSrc::AddSrc(const uni_char* src, int src_len, const URL& origin, BOOL copy /* = TRUE */)
{
if (!First())
m_origin = origin;
else
OP_ASSERT(m_origin == origin); // Or we mix data from different sources
DataSrcElm *s = DataSrcElm::Create(src, src_len, copy);
if (!s)
return OpStatus::ERR_NO_MEMORY;
s->Into(&m_list);
return OpStatus::OK;
}
/* virtual */ OP_STATUS
DataSrc::CreateCopy(ComplexAttr **copy_to)
{
// Just create the shell, the clone will have to fill it itself
DataSrc* clone = OP_NEW(DataSrc, ());
if (!clone)
return OpStatus::ERR_NO_MEMORY;
*copy_to = clone;
return OpStatus::OK;
}
|
#ifndef __VPROPCTRLPANEL_H
#define __VPROPCTRLPANEL_H
#include "TViewCtrlPanel.h"
#include "DPropEditor.h"
//-------------------------------------------------------------------------------------------------
namespace wh{
namespace view{
typedef TViewCtrlPanel<CtrlTool::All, DPropEditor, true> VPropCtrlPanel;
//-------------------------------------------------------------------------------------------------
}//namespace view
}//namespace wh
#endif // __****_H
|
#include <iostream>
#include<memory>
using namespace std;
class A
{
public:
~A() //소멸자에서는 throw를 하지 않는것이 좋음(필수권장사항!!!!)
{
throw "error";
}
};
int main()
{
try
{
int* i = new int[1000000];
unique_ptr<int> up_i(i);
throw "error";
//delete[] i; // unique_ptr덕분에 필요 없음, 영역을 벗어나면(try, throw) unique_pointer가 메모리를 제거해줌
//A a;
}
catch (...)
{
cout << "Catch" << endl;
}
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); ++i) {
if (i != 0 && nums[i] == nums[i-1])
continue;
int lo = i + 1, hi = nums.size() - 1;
int target = -nums[i];
while (lo < hi) {
int left = nums[lo], right = nums[hi];
int sum = left + right;
if (sum < target) {
while (lo < hi && nums[lo] == left)
++lo;
}
else if (sum > target) {
while (lo < hi && nums[hi] == right)
--hi;
}
else {
result.push_back({nums[i], nums[lo], nums[hi]});
while (lo < hi && nums[lo] == left)
++lo;
while (lo < hi && nums[hi] == right)
--hi;
}
}
}
return result;
}
};
int main() {
Solution sol;
vector<int> in{-1,0,1,2,-1,-4};
auto ans = sol.threeSum(in);
for (auto a : ans) {
for (auto b : a)
cout << b << " ";
cout << endl;
}
}
|
#include "Buffer.h"
#include "google/protobuf/message.h"
#include "protocol.pb.h"
#include "Poco/Net/SocketReactor.h"
#include "Poco/Net/SocketAcceptor.h"
#include "Poco/Net/SocketNotification.h"
#include "Poco/Net/StreamSocket.h"
#include "Poco/Net/ServerSocket.h"
#include "Poco/Net/NetException.h"
#include "Poco/NObserver.h"
#include "Poco/Exception.h"
#include "Poco/Thread.h"
#include "Poco/LocalDateTime.h"
#include "Poco/DateTimeFormat.h"
#include "Poco/DateTimeFormatter.h"
#include <iostream>
#include <map>
#include <vector>
using Poco::Net::SocketReactor;
using Poco::Net::SocketAcceptor;
using Poco::Net::SocketNotification;
using Poco::Net::ReadableNotification;
using Poco::Net::ShutdownNotification;
using Poco::Net::ServerSocket;
using Poco::Net::StreamSocket;
using Poco::NObserver;
using Poco::AutoPtr;
using Poco::Thread;
using Poco::LocalDateTime;
using Poco::DateTimeFormat;
using Poco::DateTimeFormatter;
using namespace Protobuf_net;
using namespace std;
static int g_sessionId = 0;
const int kIntLen = sizeof(int);
const unsigned long sendToAllUserSequence= 0xffffffff;
struct User
{
User()
:login(false),sessionId(-1),userName("")
{
}
Buffer inputBuffer;
Buffer outputBuffer;
StreamSocket socket;
std::string userName;
int sessionId;
bool login;
};
static vector<User*> s_users;
class ChatServiceHandler
{
public:
ChatServiceHandler(StreamSocket& socket, SocketReactor& reactor)
:_reactor(reactor)
{
_user.socket = socket;
_user.login = false;
_user.sessionId = ++g_sessionId;
_reactor.addEventHandler(_user.socket, NObserver<ChatServiceHandler, ReadableNotification>(*this, &ChatServiceHandler::onReadable));
_reactor.addEventHandler(_user.socket, NObserver<ChatServiceHandler, ShutdownNotification>(*this, &ChatServiceHandler::onShutdown));
s_users.push_back(&_user);
}
~ChatServiceHandler()
{
vector<User*>::iterator it = find(s_users.begin(), s_users.end(), &_user);
if (it != s_users.end())
s_users.erase(it);
_reactor.removeEventHandler(_user.socket, NObserver<ChatServiceHandler, ReadableNotification>(*this, &ChatServiceHandler::onReadable));
_reactor.removeEventHandler(_user.socket, NObserver<ChatServiceHandler, ShutdownNotification>(*this, &ChatServiceHandler::onShutdown));
}
void onReadable(const AutoPtr<ReadableNotification>& pNf)
{
try
{
int n = _user.inputBuffer.receiveBytes(_user.socket);
if (n <= 0)
{
cout << "delete this" << endl;
delete this;
}
}
catch (Poco::Exception& exc)
{
cerr << "[ChatServiceHandler][onReadable]: " << exc.displayText() << endl;
// notify to other users
chat::Message* friendNotification = BuildFriendNotification(false);
sendMessageToOthers(*friendNotification);
delete friendNotification;
// delete the disconnected-user connection
delete this;
}
onBufferMessage();
}
void sendMessage(chat::Message& msg)
{
std::string result;
result.resize(kIntLen); //Reserved 4 bytes for head
int len;
bool succeed = msg.AppendToString(&result);
if (succeed)
{
len = result.length() - kIntLen;
char buf[kIntLen];
buf[0] = (len >> 24) & 0x000000ff;
buf[1] = (len >> 16) & 0x000000ff;
buf[2] = (len >> 8) & 0x000000ff;
buf[3] = (len) & 0x000000ff;
std::copy(buf, buf + kIntLen, result.begin());
_user.outputBuffer.append(result);
internalSendMessage();
}
}
void sendMessageToSpecial(chat::Message& msg, User* user)
{
std::string result;
result.resize(kIntLen); //Reserved 4 bytes for head
int len;
bool succeed = msg.AppendToString(&result);
if (succeed)
{
len = result.length() - kIntLen;
char buf[kIntLen];
buf[0] = (len >> 24) & 0x000000ff;
buf[1] = (len >> 16) & 0x000000ff;
buf[2] = (len >> 8) & 0x000000ff;
buf[3] = (len) & 0x000000ff;
std::copy(buf, buf + kIntLen, result.begin());
user->outputBuffer.append(result);
int sended = 0;
while (user->outputBuffer.readableBytes() > 0)
{
sended = user->socket.sendBytes(user->outputBuffer.peek(), user->outputBuffer.readableBytes());
user->outputBuffer.retrieve(sended);
}
}
}
void sendMessageToOthers(chat::Message& msg)
{
std::string result;
result.resize(kIntLen); //Reserved 4 bytes for head
int len;
bool succeed = msg.AppendToString(&result);
if (succeed)
{
len = result.length() - kIntLen;
char buf[kIntLen];
buf[0] = (len >> 24) & 0x000000ff;
buf[1] = (len >> 16) & 0x000000ff;
buf[2] = (len >> 8) & 0x000000ff;
buf[3] = (len) & 0x000000ff;
std::copy(buf, buf + kIntLen, result.begin());
for (vector<User*>::const_iterator it = s_users.begin();
it != s_users.end();
++it)
{
if ((*it)->sessionId == this->_user.sessionId || !this->_user.login)
continue;
(*it)->outputBuffer.append(result);
int sended = 0;
while ((*it)->outputBuffer.readableBytes() > 0)
{
sended = (*it)->socket.sendBytes((*it)->outputBuffer.peek(), (*it)->outputBuffer.readableBytes());
(*it)->outputBuffer.retrieve(sended);
}
}
}
}
void internalSendMessage()
{
int sended = 0;
while (_user.outputBuffer.readableBytes() > 0)
{
sended = _user.socket.sendBytes(_user.outputBuffer.peek(), _user.outputBuffer.readableBytes());
_user.outputBuffer.retrieve(sended);
}
}
chat::Message* BuildFriendNotification(bool online)
{
chat::FriendNotification* friendNotification = chat::FriendNotification::default_instance().New();
friendNotification->set_name(_user.userName);
friendNotification->set_online(online);
chat::Notification* notification = chat::Notification::default_instance().New();
notification->set_allocated_friend_(friendNotification);
chat::Message* friend_notification_msg = chat::Message::default_instance().New();
friend_notification_msg->set_msg_type(chat::Friend_Notification);
friend_notification_msg->set_sequence(sendToAllUserSequence);
friend_notification_msg->set_allocated_notification(notification);
return friend_notification_msg;
}
void onLogin_Request(chat::Message& recv_msg)
{
_user.userName = recv_msg.request().login().username();
chat::LoginResponse* loginResponse = chat::LoginResponse::default_instance().New();
loginResponse->set_ttl(10);
chat::Response* resopnse = chat::Response::default_instance().New();
resopnse->set_result(true);
resopnse->set_last_response(true);
resopnse->set_allocated_login(loginResponse);
chat::Message* login_rsp = chat::Message::default_instance().New();
login_rsp->set_msg_type(chat::Login_Response);
login_rsp->set_sequence(recv_msg.sequence());
login_rsp->set_session_id(this->_user.sessionId);
login_rsp->set_allocated_response(resopnse);
_user.login = true;
sendMessage(*login_rsp);
delete login_rsp;
chat::Message* friendNotification = BuildFriendNotification(true);
sendMessageToOthers(*friendNotification);
delete friendNotification;
}
void onLogout_Request(chat::Message& recv_msg)
{
chat::Response* resopnse = chat::Response::default_instance().New();
resopnse->set_result(true);
resopnse->set_last_response(true);
chat::Message* logout_rsp = chat::Message::default_instance().New();
logout_rsp->set_msg_type(chat::Logout_Response);
logout_rsp->set_sequence(recv_msg.sequence());
logout_rsp->set_session_id(this->_user.sessionId);
logout_rsp->set_allocated_response(resopnse);
_user.login = true;
sendMessage(*logout_rsp);
delete logout_rsp;
chat::Message* friendNotification = BuildFriendNotification(false);
sendMessageToOthers(*friendNotification);
delete friendNotification;
delete this;
}
void onKeepalive_Request(chat::Message& recv_msg)
{
chat::Response* resopnse = chat::Response::default_instance().New();
resopnse->set_result(true);
resopnse->set_last_response(true);
chat::Message* rsp_msg = chat::Message::default_instance().New();
rsp_msg->set_msg_type(chat::Keepalive_Response);
rsp_msg->set_sequence(recv_msg.sequence());
rsp_msg->set_session_id(this->_user.sessionId);
rsp_msg->set_allocated_response(resopnse);
sendMessage(*rsp_msg);
delete rsp_msg;
}
void onGet_Friends_Request(chat::Message& recv_msg)
{
chat::GetFriendsResponse* friends = chat::GetFriendsResponse::default_instance().New();
for (vector<User*>::const_iterator it = s_users.begin();
it != s_users.end();
++it)
{
chat::Friend* onefriend = friends->add_friends();
onefriend->set_name((*it)->userName);
onefriend->set_online((*it)->login);
}
chat::Response* resopnse = chat::Response::default_instance().New();
resopnse->set_result(true);
resopnse->set_last_response(true);
resopnse->set_allocated_get_friends(friends);
chat::Message* rsp_msg = chat::Message::default_instance().New();
rsp_msg->set_msg_type(chat::Get_Friends_Response);
rsp_msg->set_sequence(recv_msg.sequence());
rsp_msg->set_session_id(this->_user.sessionId);
rsp_msg->set_allocated_response(resopnse);
sendMessage(*rsp_msg);
delete rsp_msg;
}
void onSend_Message_Request(chat::Message& recv_msg)
{
chat::Response* resopnse = chat::Response::default_instance().New();
resopnse->set_result(true);
resopnse->set_last_response(true);
chat::Message* rsp_msg = chat::Message::default_instance().New();
rsp_msg->set_msg_type(chat::Send_Message_Response);
rsp_msg->set_sequence(recv_msg.sequence());
rsp_msg->set_session_id(this->_user.sessionId);
rsp_msg->set_allocated_response(resopnse);
sendMessage(*rsp_msg);
delete rsp_msg;
chat::MessageNotification* messageNotification = chat::MessageNotification::default_instance().New();
messageNotification->set_sender(this->_user.userName);
std::string text = recv_msg.request().send_message().text();
messageNotification->set_text(text);
LocalDateTime now;
std::string str = DateTimeFormatter::format(now, DateTimeFormat::SORTABLE_FORMAT);
str = " " + str;
messageNotification->set_timestamp(str);
chat::Notification* notification = chat::Notification::default_instance().New();
notification->set_allocated_msg(messageNotification);
chat::Message* text_msg = chat::Message::default_instance().New();
text_msg->set_msg_type(chat::Message_Notification);
text_msg->set_sequence(sendToAllUserSequence);
text_msg->set_allocated_notification(notification);
if (recv_msg.request().send_message().has_receiver())
{
string receiver = recv_msg.request().send_message().receiver();
for (vector<User*>::const_iterator it = s_users.begin();
it != s_users.end();
++it)
{
if ((*it)->userName == receiver)
{
sendMessageToSpecial(*text_msg, *it);
}
break;
}
}
else
{
sendMessageToOthers(*text_msg);
}
delete text_msg;
}
void onBufferMessage()
{
const int kIntLen = sizeof(int);
while (_user.inputBuffer.readableBytes() >= kIntLen)
{
const void* data = _user.inputBuffer.peek();
const char* tmp = static_cast<const char*>(data);
int len = (*tmp & 0x000000ff) << 24
| (*(tmp + 1) & 0x000000ff) << 16
| (*(tmp + 2) & 0x000000ff) << 8
| (*(tmp + 3) & 0x000000ff);
if (len > 65536 || len < 0)
{
// "Invalid length "
cout << "Invalid receive message length " << endl;
_user.inputBuffer.retrieveAll();
break;
}
else if (_user.inputBuffer.readableBytes() >= len + kIntLen)
{
_user.inputBuffer.retrieve(kIntLen);
string message(_user.inputBuffer.peek(), len);
_user.inputBuffer.retrieve(len);
chat::Message recv_msg;
recv_msg.ParseFromString(message);
cout << "[ChatServiceHandler][onBufferMessage]recv_msg:" << endl
<< recv_msg.Utf8DebugString() << endl;
switch (recv_msg.msg_type())
{
case chat::Login_Request:
{
onLogin_Request(recv_msg);
}
break;
case chat::Logout_Request:
{
onLogout_Request(recv_msg);
}
break;
case chat::Keepalive_Request:
{
onKeepalive_Request(recv_msg);
}
break;
case chat::Get_Friends_Request:
{
onGet_Friends_Request(recv_msg);
}
break;
case chat::Send_Message_Request:
{
onSend_Message_Request(recv_msg);
}
break;
}
}
else
{
break;
}
}
}
void onShutdown(const AutoPtr<ShutdownNotification>& pNf)
{
cout << "[ChatServiceHandler][onShutdown]" << endl;
delete this;
}
private:
SocketReactor& _reactor;
User _user;
};
int main(int argc, char** argv)
{
unsigned short port = 9977;
// set-up a server socket
ServerSocket svs(port);
// set-up a SocketReactor...
SocketReactor reactor;
// ... and a SocketAcceptor
SocketAcceptor<ChatServiceHandler> acceptor(svs, reactor);
// run the reactor in its own thread so that we can wait for
// a termination request
Thread thread;
thread.start(reactor);
char c(' ');
while (c != 'q' && c != 'Q')
{
cout << "Press q then enter to quit: \n";
cin >> c;
}
// Stop the SocketReactor
reactor.stop();
thread.join();
google::protobuf::ShutdownProtobufLibrary();
return 0;
}
|
#include <iostream>
#include "log4cplus/logger.h"
#include <unistd.h>
#include "Dip.h"
using namespace log4cplus;
class pubErrorHandler: public DipPublicationErrorHandler {
public:
~pubErrorHandler() {
}
inline void handleException(DipPublication* pub, DipException& ex) throw (DipException) {
throw ex;
}
};
class GeneralDataListener: public DipSubscriptionListener {
private:
public:
void handleMessage(DipSubscription* subscription, DipData& message) {
try {
std::cout << "[CLIENT] Received message: " << message.extractDouble("Iteration") << std::endl;
} catch (TypeMismatch* e) {
std::cout << "[CLIENT] Error message type mismatch!" << std::endl;
}
}
void handleException(DipSubscription* subscription, DipException& ex) throw (DipException) {
throw ex;
}
void disconnected(DipSubscription* subscription, char* reason) {
std::cout << "[CLIENT] Warning client disconnected!" << std::endl;
}
void connected(DipSubscription* subscription) {
std::cout << "[CLIENT] Subscribed to DIP server. " << std::endl;
}
};
class Client {
public:
Client(const char* sub_tag) {
GeneralDataListener* handler = new GeneralDataListener();
DipFactory* dip = Dip::create("DCU_DIP");
dip->setDNSNode("cmsdimns1.cern.ch,cmsdimns2.cern.ch");
dip->createDipSubscription(sub_tag, handler);
}
};
void manual() {
std::cout << "Manual sending selected. Creating dip factory." << std::endl;
DipFactory* dip = Dip::create("DCU_DIP");
dip->setDNSNode("cmsdimns1.cern.ch,cmsdimns2.cern.ch");
std::string path = "dip/CMS/DCU";
std::cout << "Create the listener." << std::endl;
Client(path.c_str());
DipData* data = dip->createDipData();
std::cout << "Creating data." << std::endl;
pubErrorHandler* errHandle = new pubErrorHandler();
std::cout << "Creating publication." << std::endl;
DipPublication* pub = dip->createDipPublication(path.c_str(), errHandle);
unsigned int ms = 600000;
for (DipInt i = 0; i < 600; i++) {
data->insert((DipDouble) i, "Iteration");
std::cout << "Sending data: " << data->extractDouble("Iteration") << std::endl;
pub->send(*data, DipTimestamp());
usleep(ms);
}
std::cout << "Data sent. Exit." << std::endl;
delete data;
try {
if (dip != NULL && pub != NULL) {
dip->destroyDipPublication(pub);
}
} catch (const DipInternalError &) {
}
delete errHandle;
return;
}
int main(int argv, const char* argc[]) {
manual();
return 0;
}
|
// -*- LSST-C++ -*-
/*
* LSST Data Management System
* Copyright 2013 LSST Corporation.
*
* This product includes software developed by the
* LSST Project (http://www.lsst.org/).
*
* 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 LSST License Statement and
* the GNU General Public License along with this program. If not,
* see <http://www.lsstcorp.org/LegalNotices/>.
*/
#ifndef LSST_QSERV_WSCHED_CHUNKSTATE_H
#define LSST_QSERV_WSCHED_CHUNKSTATE_H
/**
*
* @brief ChunkState is a way to track which chunks are being scanned
* and which are cached.
*
* @author Daniel L. Wang, SLAC
*/
// System headers
#include <iosfwd>
#include <set>
namespace lsst {
namespace qserv {
namespace wsched {
/// This class tracks current scans for a ChunkDisk.
class ChunkState {
public:
typedef std::set<int> IntSet;
ChunkState() {}
void addScan(int chunkId) {
_scan.insert(chunkId);
_last = chunkId;
}
/// @Return true if the chunkId was erased from _scan.
bool markComplete(int chunkId) {
return _scan.erase(chunkId) > 0;
}
bool isScan(int chunkId) const {
return _scan.end() != _scan.find(chunkId);
}
bool empty() const {
return _scan.empty();
}
bool hasScan() const {
return !_scan.empty();
}
int lastScan() const {
return _last;
}
friend std::ostream& operator<<(std::ostream& os, ChunkState const& cs);
private:
IntSet _scan;
int _last{-1};
};
}}} // namespace lsst::qserv::wsched
#endif // LSST_QSERV_WSCHED_CHUNKSTATE_H
|
#pragma once
#include "GameSeaquence.h"
class GameSeaquenceController;
class Clear:public GameSeaquence
{
public:
Clear();
~Clear();
Boot* Update(GameSeaquenceController*);
private:
//クリア画面のイメージ
int mCount;
};
|
/*
* TODO: put your own comments here. Also you should leave comments on
* each of your methods.@wwyqianqian
*/
#include <math.h>
#include "recursion.h"
#include "map.h"
#include "vector.h"
#include "set.h"
#include "gwindow.h"
#include "gobjects.h"
#include "tokenscanner.h"
using namespace std;
//Milestone 1: Greatest Common Denominator
// 第一题,最大公约数,辗转相除法。
//(24,7)->(7,3)->(3,1)->(1,0) b == 0 -> a = 1; endl
int gcd(int a, int b) {
if ( b == 0 ){
cout << "gcd(" << a << "," << b << ") = " << a << endl;
return a;
}
else{
cout << "gcd(" << a << "," << b << ") = " << "gcd(" << b << "," << a%b << ")" << endl;
return gcd( b, a%b );
}
return 0;
}
//Milestone 2: Serpinskii Fractal
//第二题,画三角形,左上角点作为大基点,计算size(边长)和高度,重复画三角形,可以重复描边。
void serpinskii(GWindow &w, int leftX, int leftY, int size, int order) {
if (order == 1){
w.drawLine (leftX, leftY, size + leftX, leftY); //左上,右上连线函数。
w.drawLine (size + leftX, leftY, size / 2.0 + leftX, size * sqrt( 3 ) / 2.0 + leftY); //右上,下连线函数
w.drawLine (size / 2.0 + leftX, size * sqrt( 3 ) / 2.0 + leftY, leftX, leftY); //下,左上连线函数。
}
if (order == 0){
return;
}
if (order < 0){
throw ("error!");
return;
}
else{
serpinskii(w, leftX, leftY, size / 2.0, order - 1); //以左上点为基点,相对父元素为 1/4 的小三角形。两条边重复。
serpinskii(w, leftX + size / 2.0, leftY, size / 2.0, order - 1); //以上线中点为基点
serpinskii(w, leftX + size / 4.0, leftY + size * sqrt( 3 ) / 4.0, size / 2.0, order - 1); //以左线中点为基点
}
}
//Milestone 3: Flood Fill
//第三题,填充颜色。分别检查,改变上下左右像素的RGB。
//image.getRGB(x, y); 返回像素颜色
//image.setRGB(x, y, color); 给像素上色
//image.getWidth(); image.getHeight(); 返回图形的宽高 单位px
//image.inBounds(x, y); pixel (x, y)在界内,返回TRUE
int fillColor(GBufferedImage& image, int x, int y, int newColor, int oldColor) {
int count;
if(image.inBounds(x, y) && oldColor == image.getRGB(x, y)){
image.setRGB(x, y, newColor);
count++;
fillColor(image, x-1, y, newColor, oldColor);
fillColor(image, x+1, y, newColor, oldColor);
fillColor(image, x, y+1, newColor, oldColor);
fillColor(image, x, y-1, newColor, oldColor);
}
return count;
}
int floodFill(GBufferedImage& image, int x, int y, int newColor) {
int oldColor = image.getRGB(x, y);
if(oldColor != newColor){
return fillColor(image, x, y, newColor, oldColor);
}
return 0;
}
//Milestone 4: Personalized Curriculum
//第四题,找出他所包含的私有课程,直到打印出自己personalCurriculum。
void betterCurriculum(Map<string, Vector<string>> & prereqMap, string goal, Set<string> & alreadymentioned){
if (prereqMap.get(goal).isEmpty()){
return;
}
else{
for (string classname: prereqMap.get( goal )){
betterCurriculum(prereqMap , classname , alreadymentioned);
if(!alreadymentioned.contains( classname )){
cout << classname << endl;
}
alreadymentioned.add(classname);
}
}
}
void personalCurriculum(Map<string, Vector<string>> & prereqMap,string goal){
Set <string> alreadymentioned;
alreadymentioned.add(goal);
betterCurriculum(prereqMap, goal, alreadymentioned);
cout << goal << endl;
}
//Milestone 5: Generate Question
//第五题,组个句子
string generateHelper(Map<string, Vector<string> > & grammar, string symbol, string result){
if(!grammar.containsKey(symbol)){
return symbol;
}
else{
//randomly pick a string within the vector and use TokenScanner to seperate the objects within it.
string randomString = grammar.get(symbol).get(randomInteger(0, grammar.get(symbol).size() - 1));
TokenScanner scanner(randomString);
while(scanner.hasMoreTokens()){
string token = scanner.nextToken();
result += generate(grammar, token);
}
}
return result;
}
string generate(Map<string, Vector<string> > & grammar, string symbol)
{
string out = " ";
return generateHelper (grammar , symbol , out);
}
|
class Solution {
public:
bool dfs(vector<int>& arr, vector<int>& vis, int curr){
vis[curr] = true;
if(arr[curr] == 0) return true;
int left = curr - arr[curr];
int right = curr + arr[curr];
bool ans = false;
if(left >= 0 && vis[left] == false){
ans = ans || dfs(arr, vis, left);
}
if(right < arr.size() && vis[right] == false){
ans = ans || dfs(arr, vis, right);
}
return ans;
}
bool canReach(vector<int>& arr, int start) {
int n = arr.size();
vector<int> vis(n, false);
return dfs(arr, vis, start);
}
};
|
// KC Text Adventure Framework - (c) Rachel J. Morris, 2012 - 2013. zlib license. Moosader.com
#ifndef _MISSION
#define _MISSION
#include "../LuaWrappers/MissionWrapper.h"
class Mission
{
public:
void Init( lua_State* state );
int DisplayMissionList();
bool SelectMission( int episode );
void DisplayMissionIntroduction();
std::string GetBadCommandResponse();
std::string GetWhatsNextPrompt();
bool HandleMissionSwitch();
private:
MissionWrapper m_wMission;
};
#endif
|
#include "Weapon.h"
int Weapon::increment = 1000;
Weapon::Weapon(string name, int damages, int hit, int range, int crit, int worth, int uses, WeaponType type):TYPE(type)
{
id = new int(increment++);
this->name = name;
this->damages = damages;
this->hit = hit;
this->range = range;
this->crit = crit;
this->worth = worth;
this->uses = uses;
}
Weapon::~Weapon()
{
delete id;
}
Weapon::Weapon(const Weapon& other):TYPE(other.TYPE)
{
this->name = other.name;
this->damages = other.damages;
this->hit = other.hit;
this->range = other.range;
this->crit = other.crit;
this->worth = other.worth;
this->uses = other.uses;
this->id = new int(*other.id);
}
Weapon& Weapon::operator=(const Weapon& rhs)
{
if (this == &rhs)
return *this; // handle self assignment
this->name = rhs.name;
this->damages = rhs.damages;
this->hit = rhs.hit;
this->range = rhs.range;
this->crit = rhs.crit;
this->worth = rhs.worth;
this->uses = rhs.uses;
delete id;
this->id = new int(*rhs.id);
//assignment operator
return *this;
}
bool Weapon::operator==(const Weapon& w)const
{
if(this->name == w.name)
return true;
return false;
}
int Weapon::getId()const
{
return *id;
}
string Weapon::getName()const
{
return name;
}
int Weapon::getDamages()const
{
return damages;
}
int Weapon::getHit()const
{
return hit;
}
int Weapon::getRange()const
{
return range;
}
int Weapon::getCrit()const
{
return crit;
}
int Weapon::getWorth()const
{
return worth;
}
int Weapon::getDurability()const
{
return uses;
}
void Weapon::setName(const string name)
{
this->name = name;
}
void Weapon::setHit(const int hit)
{
if(hit>=0)
this->hit = hit;
}
void Weapon::setRange(const int range)
{
if(range>0)
this->range = range;
}
void Weapon::setCrit(const int crit)
{
if(crit>=0)
this->crit = crit;
}
void Weapon::setWorth(const int worth)
{
if(worth>0)
this->worth = worth;
}
void Weapon::setDurability(const int uses)
{
if(uses >= 0)
this->uses = uses;
}
//Methode qui gere la durabilité de l'arme
void Weapon::decrement()
{
this->uses--;
}
string Weapon::str()const
{
stringstream strs;
strs << name << endl << "HIT : " << hit << endl << "RANGE : " << range << endl << "CRIT : " << crit << endl << "WORTH : " << worth << endl;
return strs.str();
}
|
#include "MapSelection.h"
#include "MenuGameMode.h"
#include "ModeShipVSTower.h"
#include "TutorialShipVSTower.h"
//#include ""
//#include "GamePlayDemo.h"
//
//#include "cocos-ext.h"
//#include "UIScene.h"
//#include "UISceneManager.h"
//#include "editor-support/cocostudio/CCSGUIReader.h"
//#include "CocosGUIScene.h"
#define MAP1 "TileMap/ProtectYourTower1/map1.tmx"
#define MAP2 "TileMap/ProtectYourTower1/map2.tmx"
#define MAP3 "TileMap/ProtectYourTower1/map3.tmx"
#define MAP4 "TileMap/ProtectYourTower1/map4.tmx"
#define MAP5 "TileMap/ProtectYourTower1/map5.tmx"
#define MAP6 "TileMap/ProtectYourTower1/map6.tmx"
#define MAP7 "TileMap/ProtectYourTower1/map7.tmx"
#define MAPTEST "TileMap/ProtectYourTower1/map8.tmx"
//#include "CCPointExtension.h"
std::string MapSelection::m_sSelectedMap = MAP1;
//-------------ctor---------------
//
//--------------------------------
MapSelection::MapSelection():
AbstractMenu(),
m_iSelected(1)
{
//Start();
setToInactive();
}
//--------------------dtor-------------------------
//
//-------------------------------------------------
MapSelection::~MapSelection()
{
}
//--------------------------- Instance ----------------------------------------
//
// this class is a singleton
//-----------------------------------------------------------------------------
MapSelection* MapSelection::getInstance()
{
static MapSelection instance;
return &instance;
}
void MapSelection::Start()
{
if (isInactive())
{
setToPlaying();
auto label = CCLabelTTF::create("Select a Map","Arial", 48);
label->setPosition(CCPointMake(800,1000));
addChild(label);
auto item1 = MenuItemFont::create("Map1", this,menu_selector (MapSelection::SelectItem1));
item1->setFontSizeObj(40);
item1->setFontName("fonts/Marker Felt.ttf");
item1->setTag(1);
// auto color_action = TintBy::create(0.5f, 0, -255, -255);
// auto color_back = color_action->reverse();
// auto seq = Sequence::create(color_action, color_back, NULL);
//// item1->runAction(RepeatForever::create(seq));
// ship movement test
auto item2 = MenuItemFont::create("Map2", this, menu_selector(MapSelection::SelectItem2));
item2->setFontSizeObj(40);
item2->setFontName("fonts/Marker Felt.ttf");
item2->setTag(2);
// ship movement test
auto item3 = MenuItemFont::create("Map3", this, menu_selector(MapSelection::SelectItem3));
item3->setFontSizeObj(40);
item3->setFontName("fonts/Marker Felt.ttf");
item3->setTag(3);
// ship movement test
auto item4 = MenuItemFont::create("Map4", this, menu_selector(MapSelection::SelectItem4));
item4->setFontSizeObj(40);
item4->setFontName("fonts/Marker Felt.ttf");
item4->setTag(4);
auto item5 = MenuItemFont::create("Start",CC_CALLBACK_1(MapSelection::onEnterMap,this));
item5->setFontSizeObj(40);
item5->setFontName("fonts/Marker Felt.ttf");
item5->setTag(5);
//CCLayer::addChild(item5);
auto item6 = MenuItemFont::create("Exit", this, menu_selector(MapSelection::onBack));
item6->setFontSizeObj(40);
item6->setFontName("fonts/Marker Felt.ttf");
item6->setTag(6);
//CCLayer::addChild(item6);
/*auto button1 = Button::create("cocosui/animationbuttonnormal.png",
"cocosui/animationbuttonpressed.png");
button1->setPosition(Vec2(900,100));
addChild(button1);
button1->setTitleText("Launch");
button1->addTouchEventListener(CC_CALLBACK_2(MapSelection::onEnterMap,this));
auto button2 = Button::create("cocosui/animationbuttonnormal.png",
"cocosui/animationbuttonpressed.png");
button2->setPosition(Vec2(25,100));
addChild(button2);
button2->setTitleText("Back");
button2->addTouchEventListener(CC_CALLBACK_2(MapSelection::onBack,this));
*/
auto menu = CCMenu::create( item1, item2, item3,item4,item5,item6,NULL);
menu->alignItemsVertically();
addChild(menu);
menu->setTag(1000);
//item5->setPosition(CCPointMake(50, 30));
//item6->setPosition(CCPointMake(1800, 30));
}
else
{
if (isExited())
{
setToPlaying();
}
}
// dont forget to add schedule update
this->scheduleUpdate();
}
void MapSelection::update(float dt)
{
if (!isPlaying())
return ;
updateSelectedMap(dt);
}
void MapSelection::updateSelectedMap(float dt)
{
auto b = static_cast<MenuItemFont*>( getChildByTag(1000)->getChildByTag(m_iSelected));
if (b)
b->setColor(Color3B::GREEN);
//if (m_bItemTouched1)
//{
// // get the selected item and change its color
// auto b = static_cast<Button*>(getChildByTag(1));
// b->setColor(Color3B::GREEN);
//}
//if (m_bItemTouched2)
//{
//
// auto b = static_cast<Button*>(getChildByTag(2));
// b->setColor(Color3B::GREEN);
//}
//if (m_bItemTouched3)
//{
//
//}
//if (m_bItemTouched4)
//{
//
//}
//if (m_bItemTouched5)
//{
//
//}
}
void MapSelection::SelectItem1(Ref *pSender)
{
//auto item1 = static_cast<MenuItemFont*>( getChildByTag(0));
//auto b = static_cast<MenuItemFont*>( getChildByTag(1000)->getChildByTag(1));
//b->setColor(Color3B::GREEN);
//m_bItemTouched1 = true;
// change the color of the selected item to white
auto b = static_cast<MenuItemFont*>( getChildByTag(1000)->getChildByTag(m_iSelected));
if (b)
b->setColor(Color3B::WHITE);
m_iSelected = 1;
m_sSelectedMap = MAP1;
}
void MapSelection:: SelectItem2(Ref *pSender)
{
auto b = static_cast<MenuItemFont*>( getChildByTag(1000)->getChildByTag(m_iSelected));
if (b)
b->setColor(Color3B::WHITE);
m_bItemTouched2 = true;
m_iSelected = 2;
m_sSelectedMap = MAP2;
}
void MapSelection:: SelectItem3(Ref *pSender)
{
auto b = static_cast<MenuItemFont*>( getChildByTag(1000)->getChildByTag(m_iSelected));
if (b)
b->setColor(Color3B::WHITE);
m_bItemTouched3 = true;
m_iSelected = 3;
m_sSelectedMap = MAP3;
}
void MapSelection:: SelectItem4(Ref *pSender)
{
auto b = static_cast<MenuItemFont*>( getChildByTag(1000)->getChildByTag(m_iSelected));
if (b)
b->setColor(Color3B::WHITE);
m_bItemTouched4 = true;
m_iSelected = 4;
m_sSelectedMap = MAP4;
}
void MapSelection::SelectItem5(Ref *pSender)
{
auto b = static_cast<MenuItemFont*>(getChildByTag(1000)->getChildByTag(m_iSelected));
if (b)
b->setColor(Color3B::WHITE);
m_bItemTouched4 = true;
m_iSelected = 5;
m_sSelectedMap = MAP5;
}
void MapSelection::SelectItem6(Ref *pSender)
{
auto b = static_cast<MenuItemFont*>(getChildByTag(1000)->getChildByTag(m_iSelected));
if (b)
b->setColor(Color3B::WHITE);
m_bItemTouched4 = true;
m_iSelected = 5;
m_sSelectedMap = MAP6;
}
// choose a map
void MapSelection::onEnterMap(Ref *pSender/*, Widget::TouchEventType type*/)
{
setToExited();
/*if (theModeShipVsTower)
theModeShipVsTower->Start();*/
//auto layer = ( CCLayerMultiplex*) getChildByTag(1000) ;
//if (layer)
//{
// auto g = layer->getChildByTag(4);
// if (g)
// {
// auto game1 = static_cast<ModeShipVSTower*> (g);
// //g->Start();
// if (game1)
// {
// auto label = CCLabelTTF::create("tag", "Arial", 48);
// //std::string s = std::to_string(((CCLayerMultiplex*)m_pParent)->getTag());
// //const char* out = s.c_str();
// label->setString(/*out*/"bonjour");
// label->setPosition(CCPointMake(100, 1000));
// addChild(label);
// game1->Start();
// //((CCLayerMultiplex*)m_pParent)->switchTo(3);
// }
// }
//}
if (getModeShipVSTower())
getModeShipVSTower()->Start();
((LayerMultiplex*)_parent)->switchTo(3);
}
// go back
void MapSelection::onBack(Ref *pSender/*, Widget::TouchEventType type*/)
{
setToExited();
if (TheMenuGameMode)
TheMenuGameMode->Start();
((LayerMultiplex*)_parent)->switchTo(1);
}
|
#include <iostream>
using namespace std;
int main(){
int tc;
int sc;
int min;
int max;
int temp;
cin >> tc;
while(tc--){
cin >> sc;
min = 100;
max = -1;
while(sc--){
cin >> temp;
if(temp > max){
max = temp;
}
if(temp < min){
min = temp;
}
}
cout << (max - min) * 2 << endl;
}
}
|
// Copyright (c) 2019 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 _XCAFDoc_VisMaterialPBR_HeaderFile
#define _XCAFDoc_VisMaterialPBR_HeaderFile
#include <Graphic3d_Vec.hxx>
#include <Image_Texture.hxx>
#include <Quantity_ColorRGBA.hxx>
#include <Standard_Dump.hxx>
//! Metallic-roughness PBR material definition.
struct XCAFDoc_VisMaterialPBR
{
Handle(Image_Texture) BaseColorTexture; //!< RGB texture for the base color
Handle(Image_Texture) MetallicRoughnessTexture; //!< RG texture packing the metallic and roughness properties together
Handle(Image_Texture) EmissiveTexture; //!< RGB emissive map controls the color and intensity of the light being emitted by the material
Handle(Image_Texture) OcclusionTexture; //!< R occlusion map indicating areas of indirect lighting
Handle(Image_Texture) NormalTexture; //!< normal map
Quantity_ColorRGBA BaseColor; //!< base color (or scale factor to the texture); [1.0, 1.0, 1.0, 1.0] by default
Graphic3d_Vec3 EmissiveFactor; //!< emissive color; [0.0, 0.0, 0.0] by default
Standard_ShortReal Metallic; //!< metalness (or scale factor to the texture) within range [0.0, 1.0]; 1.0 by default
Standard_ShortReal Roughness; //!< roughness (or scale factor to the texture) within range [0.0, 1.0]; 1.0 by default
Standard_ShortReal RefractionIndex; //!< IOR (index of refraction) within range [1.0, 3.0]; 1.5 by default
Standard_Boolean IsDefined; //!< defined flag; TRUE by default
//! Empty constructor.
XCAFDoc_VisMaterialPBR()
: BaseColor (1.0f, 1.0f, 1.0f, 1.0f),
EmissiveFactor (0.0f, 0.0f, 0.0f),
Metallic (1.0f),
Roughness (1.0f),
RefractionIndex (1.5f),
IsDefined (Standard_True) {}
//! Compare two materials.
Standard_Boolean IsEqual (const XCAFDoc_VisMaterialPBR& theOther) const
{
if (&theOther == this)
{
return true;
}
else if (theOther.IsDefined != IsDefined)
{
return false;
}
else if (!IsDefined)
{
return true;
}
return theOther.BaseColorTexture == BaseColorTexture
&& theOther.MetallicRoughnessTexture == MetallicRoughnessTexture
&& theOther.EmissiveTexture == EmissiveTexture
&& theOther.OcclusionTexture == OcclusionTexture
&& theOther.NormalTexture == NormalTexture
&& theOther.BaseColor == BaseColor
&& theOther.EmissiveFactor == EmissiveFactor
&& theOther.Metallic == Metallic
&& theOther.Roughness == Roughness
&& theOther.RefractionIndex == RefractionIndex;
}
//! Dumps the content of me into the stream
void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const
{
OCCT_DUMP_CLASS_BEGIN (theOStream, XCAFDoc_VisMaterialPBR)
OCCT_DUMP_FIELD_VALUES_DUMPED (theOStream, theDepth, BaseColorTexture.get())
OCCT_DUMP_FIELD_VALUES_DUMPED (theOStream, theDepth, MetallicRoughnessTexture.get())
OCCT_DUMP_FIELD_VALUES_DUMPED (theOStream, theDepth, EmissiveTexture.get())
OCCT_DUMP_FIELD_VALUES_DUMPED (theOStream, theDepth, OcclusionTexture.get())
OCCT_DUMP_FIELD_VALUES_DUMPED (theOStream, theDepth, NormalTexture.get())
OCCT_DUMP_FIELD_VALUES_DUMPED (theOStream, theDepth, &BaseColor)
OCCT_DUMP_FIELD_VALUES_DUMPED (theOStream, theDepth, &EmissiveFactor)
OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, Metallic)
OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, Roughness)
OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, RefractionIndex)
OCCT_DUMP_FIELD_VALUE_NUMERICAL (theOStream, IsDefined)
}
};
#endif // _XCAFDoc_VisMaterialPBR_HeaderFile
|
//
// Created by Dustin Tracy on 7/1/15.
//
#ifndef PROJECTEULER_VECFUNC_H
#define PROJECTEULER_VECFUNC_H
#include <vector>
#include <iostream>
template<class T>
class vecFunc {
public:
vecFunc(std::vector<T> &list) {
setVector(list);
}
// The constructor, requiring a vector
void setVector(std::vector<T> &w) {
list = w;
}
// Prints a vector
void vectorPrint() {
for (T i : list) {
std::cout << i << std::endl;
}
}
// Selects only the even numbers in a vector
std::vector<T> evenFinder() {
std::vector<T> evenList;
for (T i : list) {
if (!(i % 2)) {
evenList.push_back(i);
}
}
return evenList;
}
// Provides the max value in a vector
T max() {
T value = list[0];
for (T i : list) {
if (i > value) { value = i; }
}
return value;
}
private:
std::vector<T> list;
};
#endif //PROJECTEULER_VECFUNC_H
|
class Solution {
public:
void sortColors(vector<int>& nums) {
int n = nums.size();
int zeroIndex = 0, twoIndex = n-1;
for(int i=zeroIndex;i<=twoIndex;i++){
if(nums[i] == 0){
swap(nums[i], nums[zeroIndex]);
zeroIndex++;
}
else if(nums[i] == 2){
swap(nums[i], nums[twoIndex]);
twoIndex--;
i--;
}
}
}
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2011 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef EXTENSIONS_MODEL_H
#define EXTENSIONS_MODEL_H
#include "adjunct/quick/extensions/ExtensionButtonComposite.h"
#include "adjunct/quick/models/ExtensionsModelItem.h"
#include "adjunct/desktop_util/adt/hashiterator.h"
#include "modules/util/adt/oplisteners.h"
#include "modules/util/OpHashTable.h"
#include "modules/windowcommander/OpWindowCommander.h"
/**
* @brief Model for Desktop Extensions.
*
* This class is a wrapper around core's OpGadgetManager.
* It gathers all gadgets that are extensions, manages their UI buttons,
* provides useful operations on extensions, notifies about changes.
* Listeners of this model can be notified about (normal or developer)
* extensions installation, uninstallation, disabling, enabling etc.
*/
class ExtensionsModel
{
public:
struct RefreshInfo
{
RefreshInfo() : m_dev_count(0), m_normal_count(0) { }
/**
* Count of developer extensions in the model.
*/
unsigned m_dev_count;
/**
* Count of non-developer extensions in the model.
*/
unsigned m_normal_count;
};
class Listener
{
public:
virtual ~Listener() {}
/**
* When Extensions Model is about to be "refreshed" this
* event occurs. For the listener it means all data in the
* model has become out-of-date. New data will arrive soon.
*/
virtual void OnBeforeExtensionsModelRefresh(
const RefreshInfo& info) = 0;
/**
* When Extensions Model is done with "refreshing" itself
* this event occurs. For the listener it means all data in the
* model is valid and it can be processed.
*/
virtual void OnAfterExtensionsModelRefresh() = 0;
/**
* Notify listener about new normal extension that has been
* added to the model.
*
* @param model_item Extensions model item.
*/
virtual void OnNormalExtensionAdded(
const ExtensionsModelItem& model_item) = 0;
/**
* Notify listener about new developer extension that has been
* added to the model.
*
* @param model_item Extensions model item.
*/
virtual void OnDeveloperExtensionAdded(
const ExtensionsModelItem& model_item) = 0;
/**
* Event occurs when extension described by extension
* model item is about to be removed (so in this event
* it is perfectly safe to use it).
*
* @param model_item Extensions model item.
*/
virtual void OnExtensionUninstall(
const ExtensionsModelItem& model_item) = 0;
/**
* Notify listener that existing extension was started.
*
* @param model_item Extensions model item.
*/
virtual void OnExtensionEnabled(
const ExtensionsModelItem& model_item) = 0;
/**
* Notify listener that existing extension was stopped.
*
* @param model_item Extensions model item.
*/
virtual void OnExtensionDisabled(
const ExtensionsModelItem& model_item) = 0;
/**
* Notify listener that status of update availability has changed
*
* @param model_item Extensions model item.
*/
virtual void OnExtensionUpdateAvailable(
const ExtensionsModelItem& model_item) = 0;
/**
* Notify listener that extended name for extension has been changed
*/
virtual void OnExtensionExtendedNameUpdate(
const ExtensionsModelItem& model_item) = 0;
};
~ExtensionsModel();
OP_STATUS Init();
/**
* Starts extensions, which have been configured to
* start with browser startup
*/
void StartAutoStartServices();
/**
* Notify listeners about incoming refresh. Delete all old data,
* create new model items, send notifications.
*
* @see ExtensionsModel::OnBeforeExtensionsModelRefresh
* @see ExtensionsModel::OnAfterExtensionsModelRefresh
*
* @return Status.
*/
OP_STATUS Refresh();
/**
* Listeners handling functions.
*/
OP_STATUS AddListener(Listener* listener);
OP_STATUS RemoveListener(Listener* listener);
/**
* Uninstall functions.
*/
OP_STATUS UninstallExtension(const OpStringC& extension_id);
OP_STATUS UninstallExtension(ExtensionsModelItem* item);
/**
* Enable/Disable functions.
*/
OP_STATUS EnableExtension(const OpStringC& extension_id);
OP_STATUS EnableExtension(ExtensionsModelItem* item);
OP_STATUS DisableExtension(const OpStringC& extension_id, BOOL user_requested = FALSE, BOOL notify_listeners = TRUE);
OP_STATUS DisableExtension(ExtensionsModelItem* item, BOOL user_requested = FALSE, BOOL notify_listeners = TRUE);
/**
* Reload extension data (eg. js, html, window).
*
* @param extension_id Extension id.
* @return Status.
*/
OP_STATUS ReloadExtension(const OpStringC& extension_id);
/**
* When extension is running and update is available
*
* @param extension_id Extension id.
* @return Status.
*/
OP_STATUS UpdateAvailable(const OpStringC& extension_id);
/**
* Extension can have additional part of the name, set for example from SD cell title
*
* @param extension_id Extension id.
* @param name new extension extended name.
*/
OP_STATUS UpdateExtendedName(const OpStringC& extension_id,const OpStringC& name);
/**
* When extension update has been made
*
* @param extension_id Extension id.
* @return Status.
*/
OP_STATUS UpdateFinished(const OpStringC& extension_id);
/**
* @param extension_id Extension id.
* @return TRUE iff extension is enabled on CORE's side.
*/
BOOL IsEnabled(const OpStringC& extension_id);
/**
* @param extension_id Extension id.
* @return TRUE iff extension options page can be used/showed.
*/
BOOL CanShowOptionsPage(const OpStringC& extension_id);
/**
* Send request to core that we want to open this extension's
* options page.
*
* @param extension_id Extension id.
* @return Status.
*/
OP_STATUS OpenExtensionOptionsPage(const OpStringC& extension_id);
/**
* @param extension_id Extension id (wuid).
* @return ExtensionsModelItem* for extension or NULL if there's
* no extension with this extension_id.
*/
ExtensionsModelItem* FindExtensionById(const OpStringC& extension_id) const;
/**
* By usage of this function you can open any url, including internal gadget url
* which is not working via g_application->GoToPage(..)
*
* @param extension_id Extension id.
* @return Status.
*/
OP_STATUS OpenExtensionUrl(const OpStringC& url,const OpStringC& extension_id);
typedef OpExtensionUIListener::ExtensionId ExtensionId;
/**
* @return NULL iff ExtensionButton with such id doesn't exist.
*/
ExtensionButtonComposite* GetButton(ExtensionId id);
OP_STATUS CreateButton(ExtensionId id);
OP_STATUS DeleteButton(ExtensionId id);
/**
* Called after OpExtensionButton has been removed from composite.
* @param id extension id
*/
void OnButtonRemovedFromComposite(INT32 id);
/**
* Returns number of extension model items.
*/
unsigned GetCount() const
{ OP_ASSERT(m_extensions.GetCount() >= 0); return m_extensions.GetCount(); }
/**
* Retrieve all installed speed dial extensions.
*
* @param[out] extensions vector of all installed speed dial extensions
* @return status of operation. If any error is returned @a extensions should not be used
*/
OP_STATUS GetAllSpeedDialExtensions(OpVector<OpGadget>& extensions);
/**
* Reloads all running developer mode extensions.
*/
void ReloadDevModeExtensions();
protected:
OpAutoStringHashTable<ExtensionsModelItem> m_extensions;
OpAutoINT32HashTable<ExtensionButtonComposite> m_extension_buttons;
// buttons to be deleted after all associated UI elements are destroyed
OpAutoINT32HashTable<ExtensionButtonComposite> m_zombie_buttons;
OpListeners<Listener> m_listeners;
static int CompareItems(const ExtensionsModelItem** a, const ExtensionsModelItem** b);
/**
* If extension is running close it's Window, and destroy
* platform OpWindow also. Make it not running :)
*
* @param extension_id Extension id.
* @return Status.
*/
OP_STATUS CloseExtensionWindows(OpGadget* extension);
// Helper functions for propagating notifications.
void NotifyAboutBeforeRefresh(const ExtensionsModel::RefreshInfo& info);
void NotifyAboutAfterRefresh();
void NotifyAboutNormalExtensionAdded(const ExtensionsModelItem& item);
void NotifyAboutDeveloperExtensionAdded(const ExtensionsModelItem& item);
void NotifyAboutUninstall(const ExtensionsModelItem& item);
void NotifyAboutEnable(const ExtensionsModelItem& item);
void NotifyAboutDisable(const ExtensionsModelItem& item);
void NotifyAboutUpdateAvailable(const ExtensionsModelItem& item);
void NotifyAboutExtendedNameUpdate(const ExtensionsModelItem& item);
private:
OP_STATUS DisableAllExtensions();
OP_STATUS DestroyDeletedExtensions();
};
#endif // EXTENSIONS_MODEL_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
*
* 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"
// FIXME: clean up these == 96 includes!
#include "modules/dochand/win.h"
#include "modules/dochand/winman.h"
#include "modules/dochand/docman.h"
#include "modules/dochand/viewportcontroller.h"
#include "modules/doc/html_doc.h"
#include "modules/doc/documentorigin.h"
#include "modules/url/url2.h"
#include "modules/url/url_man.h"
#include "modules/encodings/detector/charsetdetector.h"
#include "modules/inputmanager/inputaction.h"
#include "modules/inputmanager/inputmanager.h"
#include "modules/logdoc/urlimgcontprov.h"
#include "modules/logdoc/savewithinline.h"
#include "modules/forms/formmanager.h"
#ifdef USE_OP_THREAD_TOOLS
#include "modules/pi/OpThreadTools.h"
#endif
#include "modules/hardcore/mh/messages.h"
#include "modules/locale/oplanguagemanager.h"
#include "modules/locale/locale-enum.h"
#include "modules/util/timecache.h"
#include "modules/prefs/prefsmanager/collections/pc_core.h"
#include "modules/prefs/prefsmanager/collections/pc_display.h"
#include "modules/prefs/prefsmanager/collections/pc_doc.h"
#include "modules/prefs/prefsmanager/collections/pc_network.h"
#include "modules/prefs/prefsmanager/collections/pc_ui.h"
#include "modules/prefs/prefsmanager/collections/pc_print.h"
#include "modules/prefs/prefsmanager/collections/pc_fontcolor.h"
#include "modules/display/prn_info.h"
#include "modules/ecmascript/ecmascript.h"
#include "modules/ecmascript_utils/essched.h"
#include "modules/layout/layout_workplace.h"
#include "modules/logdoc/htm_elm.h"
#include "modules/logdoc/htm_ldoc.h"
#include "modules/doc/frm_doc.h"
#include "modules/util/gen_str.h"
#include "modules/util/winutils.h"
#include "modules/util/filefun.h"
#include "modules/display/vis_dev.h"
#include "modules/display/coreview/coreview.h"
#include "modules/util/handy.h"
#ifdef QUICK
# include "adjunct/quick/Application.h"
# include "adjunct/quick/managers/KioskManager.h"
# include "adjunct/quick/dialogs/DownloadDialog.h"
# include "adjunct/quick/hotlist/HotlistManager.h"
#endif
#include "modules/windowcommander/OpWindowCommander.h"
#include "modules/windowcommander/src/WindowCommander.h"
#ifdef DRAG_SUPPORT
#include "modules/dragdrop/dragdrop_manager.h"
#endif
#include "modules/history/OpHistoryModel.h"
#include "modules/display/prn_dev.h"
#include "modules/pi/OpWindow.h"
#include "modules/dochand/windowlistener.h"
#include "modules/windowcommander/OpWindowCommanderManager.h"
#if defined(_MACINTOSH_)
# include "platforms/mac/File/FileUtils_Mac.h"
#endif // macintosh latest
#ifdef _PLUGIN_SUPPORT_
#include "modules/ns4plugins/opns4pluginhandler.h"
#endif // _PLUGIN_SUPPORT_
#include "modules/display/VisDevListeners.h"
#ifdef GTK_DOWNLOAD_EXTENSION
# include <gtk/gtk.h>
# include "base/gdk/GdkOpWindow.h"
# include "product/sdk/src/documentwindow.h"
# include "product/sdk/src/bookmarkitemmanager.h"
#endif // GTK_DOWNLOAD_EXTENSION
#include "modules/url/protocols/comm.h"
#ifdef LINK_SUPPORT
#include "modules/logdoc/link.h"
#endif // LINK_SUPPORT
#ifdef NEARBY_ELEMENT_DETECTION
# include "modules/widgets/finger_touch/element_of_interest.h"
#endif // NEARBY_ELEMENT_DETECTION
#ifndef _NO_GLOBALS_
extern HTML_Element *curr_img_element;
#endif
#include "modules/olddebug/timing.h"
#ifdef OBML_COMM_FORCE_CONFIG_FILE
#include "modules/obml_comm/obml_config.h"
#endif // OBML_COMM_FORCE_CONFIG_FILE
extern BOOL ScrollDocument(FramesDocument* doc, OpInputAction::Action action, int times = 1, OpInputAction::ActionMethod method = OpInputAction::METHOD_OTHER);
#ifdef _SPAT_NAV_SUPPORT_
#include "modules/spatial_navigation/sn_handler.h"
#endif // _SPAT_NAV_SUPPORT_
#ifdef SVG_SUPPORT
#include "modules/svg/svg_workplace.h"
#include "modules/svg/svg_image.h"
#endif // SVG_SUPPORT
#ifdef SEARCH_MATCHES_ALL
# include "modules/doc/searchinfo.h"
#endif
#ifdef SEARCH_ENGINES
#include "modules/searchmanager/searchmanager.h"
#endif // SEARCH_ENGINES
#ifdef WAND_SUPPORT
#include "modules/wand/wandmanager.h"
#endif // WAND_SUPPORT
#ifndef HAS_NOTEXTSELECTION
# include "modules/dochand/fdelm.h"
# include "modules/documentedit/OpDocumentEdit.h"
#endif //!HAS_NOTEXTSELECTION
#ifdef CORE_BOOKMARKS_SUPPORT
#include "modules/bookmarks/bookmark_item.h"
#include "modules/bookmarks/bookmark_manager.h"
#endif // CORE_BOOKMARKS_SUPPORT
#define DOC_WINDOW_MAX_TITLE_LENGTH 128
#ifdef SCOPE_WINDOW_MANAGER_SUPPORT
# include "modules/scope/scope_window_listener.h"
#endif // SCOPE_WINDOW_MANAGER_SUPPORT
#ifdef GADGET_SUPPORT
# include "modules/gadgets/OpGadget.h"
#endif // GADGET_SUPPORT
#ifdef APPLICATION_CACHE_SUPPORT
# include "modules/applicationcache/application_cache_manager.h"
#endif // APPLICATION_CACHE_SUPPORT
#ifdef CSS_VIEWPORT_SUPPORT
# include "modules/style/css_viewport.h"
#endif // CSS_VIEWPORT_SUPPORT
#ifdef DEBUG_LOAD_STATUS
# include "modules/olddebug/tstdump.h"
#endif
#ifdef USE_OP_CLIPBOARD
# include "modules/pi/OpClipboard.h"
# ifdef SVG_SUPPORT
# include "modules/svg/SVGManager.h"
# endif // SVG_SUPPORT
# include "modules/forms/piforms.h"
# include "modules/widgets/OpWidget.h"
#endif // USE_OP_CLIPBOARD
OpenUrlInNewWindowInfo::OpenUrlInNewWindowInfo(URL& url, DocumentReferrer refurl, const uni_char* win_name, BOOL open_in_bg_win, BOOL user_init, unsigned long open_win_id,
int open_sub_win_id, BOOL open_in_new_page)
: new_url(url),
ref_url(refurl),
open_in_background_window(open_in_bg_win),
user_initiated(user_init),
opener_id(open_win_id),
opener_sub_win_id(open_sub_win_id),
open_in_page(open_in_new_page)
{
window_name = UniSetNewStr(win_name);//FIXME:OOM
}
const OpMessage g_Window_messages[] =
{
MSG_PROGRESS_START,
MSG_PROGRESS_END,
#ifdef _PRINT_SUPPORT_
DOC_START_PRINTING,
DOC_PRINT_FORMATTED,
DOC_PAGE_PRINTED,
DOC_PRINTING_FINISHED,
DOC_PRINTING_ABORTED,
#endif // _PRINT_SUPPORT_
MSG_SELECTION_SCROLL,
MSG_ES_CLOSE_WINDOW,
MSG_UPDATE_PROGRESS_TEXT,
MSG_UPDATE_WINDOW_TITLE,
MSG_HISTORY_CLEANUP,
WM_OPERA_SCALEDOC,
MSG_HISTORY_BACK
};
void Window::ConstructL()
{
forceEncoding.SetL(g_pcdisplay->GetForceEncoding());
homePage.Empty();
doc_manager = OP_NEW_L(DocumentManager, (this, NULL, NULL)); // must be set before VisualDevice constructor
LEAVE_IF_ERROR(doc_manager->Construct());
msg_handler = OP_NEW_L(MessageHandler, (this));
LEAVE_IF_ERROR(msg_handler->SetCallBackList(this, 0, g_Window_messages, sizeof g_Window_messages / sizeof g_Window_messages[0]));
#ifdef EPOC
// Fix for 'hidden' transfer window.
if (type==WIN_TYPE_DOWNLOAD)
return;
#endif
vis_device = VisualDevice::Create(m_opWindow, doc_manager,
bShowScrollbars ? VisualDevice::VD_SCROLLING_AUTO : VisualDevice::VD_SCROLLING_NO);
if (!vis_device)
LEAVE(OpStatus::ERR_NO_MEMORY);
doc_manager->SetVisualDevice(vis_device);
UINT32 rendering_width, rendering_height;
m_opWindow->GetRenderingBufferSize(&rendering_width, &rendering_height);
vis_device->SetRenderingViewGeometryScreenCoords(OpRect(0, 0, rendering_width, rendering_height));
viewportcontroller = OP_NEW_L(ViewportController, (this));
windowlistener = OP_NEW_L(WindowListener, (this));
m_opWindow->SetWindowListener(windowlistener);
}
Window::Window(unsigned long nid, OpWindow* opWindow, OpWindowCommander* opWindowCommander)
: m_features(0)
, m_online_mode(Window::ONLINE)
, m_frames_policy(FRAMES_POLICY_DEFAULT)
#ifdef SUPPORT_VISUAL_ADBLOCK
, m_content_block_edit_mode(FALSE)
, m_content_block_enabled(TRUE)
, m_content_block_server_name(NULL)
#endif // SUPPORT_VISUAL_ADBLOCK
, m_windowCommander(static_cast<WindowCommander*>(opWindowCommander))
, vis_device(NULL)
, doc_manager(NULL)
, msg_handler(NULL)
, current_message(NULL)
, current_default_message(NULL)
, progress_state(WAITING)
, state(NOT_BUSY)
#ifndef MOUSELESS
, current_cursor(CURSOR_DEFAULT_ARROW)
, m_pending_cursor(CURSOR_AUTO)
, cursor_set_by_doc(CURSOR_DEFAULT_ARROW)
, has_cursor_set_by_doc(FALSE)
#endif // !MOUSELESS
// active_link_url unset
, m_fullscreen_state(OpWindowCommander::FULLSCREEN_NONE)
// m_previous_fullscreen_state
, m_is_background_transparent(FALSE)
// m_old_* unset
// m_* others: see function body
, m_is_explicit_suppress_window(FALSE)
, m_is_implicit_suppress_window(FALSE)
, m_is_scriptable_window(TRUE)
, m_is_visible_on_screen(TRUE)
#ifdef _SPAT_NAV_SUPPORT_
, sn_handler(0)
#endif /* _SPAT_NAV_SUPPORT */
# if defined SN_LEAVE_SUPPORT
, sn_listener(0)
# endif // SN_LEAVE_SUPPORT
, m_draw_highlight_rects(TRUE)
, bCanSelfClose(TRUE) // JS is known to close windows that are in use by others
#ifdef SELFTEST
, m_is_about_to_close(FALSE)
#endif // SELFTEST
, m_url_came_from_address_field(FALSE)
, show_img(FALSE) // may be adjusted in body
#ifdef FIT_LARGE_IMAGES_TO_WINDOW_WIDTH
, fit_img(FALSE) // may be adjusted in body
#endif // FIT_LARGE_IMAGES_TO_WINDOW_WIDTH
, load_img(FALSE) // may be adjusted in body
// is_ssr_mode, era_mode, layout_mode: see body
, limit_paragraph_width(g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::LimitParagraphWidth))
, flex_root_max_width(0)
, scale(100)
, m_text_scale(100)
, progress_count(0)
, doc_progress_count(0)
, upload_total_bytes(0) // Uploading watch
, phase_uploading(FALSE)
, start_time(0)
// progress_mess* arrays - see function body
, OutputAssociatedWindow(0)
, bShowScrollbars(g_pcdoc->GetIntegerPref(PrefsCollectionDoc::ShowScrollbars))
// bShow* - see function body
, id(nid)
, loading(FALSE)
, end_progress_message_sent(TRUE)
, history_cleanup_message_sent(FALSE)
, user_load_from_cache(FALSE)
, pending_unlock_all_painting(FALSE)
//, name(NULL)
, CSSMode((CSSMODE) g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::DocumentMode))
, forceColors(FALSE)
, truezoom(FALSE)
, truezoom_base_scale(100)
, is_something_hovered(FALSE)
, ecmascript_disabled(FALSE)
, ecmascript_paused(NOT_PAUSED)
, viewportcontroller(NULL)
, SecurityState(SECURITY_STATE_UNKNOWN)
, SecurityState_signalled(SECURITY_STATE_UNKNOWN)
, SecurityState_changed_by_inline(FALSE)
, SecurityState_signal_delayed(FALSE)
, m_privacy_mode(FALSE)
// SecurityTextName unset
#ifdef TRUST_RATING
, m_trust_rating(Not_Set)
#endif
#ifdef WEB_TURBO_MODE
, m_turbo_mode(FALSE)
#endif // WEB_TURBO_MODE
, currWinHistoryLength(0)
, current_history_number(0)
, min_history_number(1)
, max_history_number(0)
, check_history(FALSE)
, is_canceling_loading(FALSE)
, title_update_title_posted(FALSE)
// , title(NULL)
, generated_title(FALSE)
#ifdef SHORTCUT_ICON_SUPPORT
, shortcut_icon_provider(NULL)
#endif // SHORTCUT_ICON_SUPPORT
, lastUserName(NULL)
, lastProxyUserName(NULL)
, type(WIN_TYPE_NORMAL)
, default_background_color(USE_DEFAULT_COLOR)
#ifdef _PRINT_SUPPORT_
, printer_info(NULL)
, preview_printer_info(NULL)
, preview_mode(FALSE)
, print_mode(FALSE)
, frames_print_type(PRINT_ALL_FRAMES)
, is_formatting_print_doc(FALSE)
, is_printing(FALSE)
#endif // _PRINT_SUPPORT_
// m_userAutoReload unset
#ifdef _AUTO_WIN_RELOAD_SUPPORT_
, m_userAutoReload(this)
#endif // _AUTO_WIN_RELOAD_SUPPORT_
, opener(NULL)
, opener_sub_win_id(-1)
, is_available_to_script(FALSE)
, opener_origin(NULL)
, can_be_closed_by_script(FALSE)
#if defined SEARCH_MATCHES_ALL
, m_search_data(NULL)
#endif // SEARCH_MATCHES_ALL
, always_load_from_cache(FALSE)
#ifdef LIBOPERA
, m_lastReqUserInitiated(FALSE)
#endif
, m_opWindow(opWindow)
, windowlistener(0)
// m_bWasInFullscreen unset
#ifdef ACCESS_KEYS_SUPPORT
// FIXME: Change this when/if your platform has the ability to change this value
, in_accesskey_mode(FALSE)
#endif // ACCESS_KEYS_SUPPORT
, window_locked(0)
, window_closed(FALSE)
, use_already_requested_urls(TRUE)
, forced_java_disabled(FALSE)
, forced_plugins_disabled(FALSE)
, document_word_wrap_forced(FALSE)
#ifdef WAND_SUPPORT
, m_wand_in_progress_count(0)
#endif // WAND_SUPPORT
#ifdef HISTORY_SUPPORT
, m_global_history_enabled(TRUE)
#endif // HISTORY_SUPPORT
#ifdef NEARBY_ELEMENT_DETECTION
, element_expander(NULL)
#endif // NEARBY_ELEMENT_DETECTION
#ifdef GRAB_AND_SCROLL
, scroll_is_pan_overridden(FALSE)
, scroll_is_pan(FALSE)
#endif // GRAB_AND_SCROLL
, recently_cancelled_keydown(OP_KEY_INVALID)
, has_shown_unsolicited_download_dialog(FALSE)
#ifdef DOM_JIL_API_SUPPORT
, m_screen_props_listener(NULL)
#endif // DOM_JIL_API_SUPPORT
, m_oom_occurred(FALSE)
, m_next_doclistelm_id(1)
#ifdef SCOPE_PROFILER
, m_profiling_session(NULL)
#endif // SCOPE_PROFILER
#ifdef KEYBOARD_SELECTION_SUPPORT
, m_current_keyboard_selection_mode(FALSE)
#endif // KEYBOARD_SELECTION_SUPPORT
{
OP_ASSERT(opWindowCommander);
switch ((SHOWIMAGESTATE) g_pcdoc->GetIntegerPref(PrefsCollectionDoc::ShowImageState))
{
case FIGS_OFF: break;
case FIGS_ON: load_img = TRUE; /* fall through */
case FIGS_SHOW: show_img = TRUE; break;
}
int rm = g_pcdoc->GetIntegerPref(PrefsCollectionDoc::RenderingMode);
if (rm < 0)
{
era_mode = TRUE;
rm = 0;
}
else
era_mode = FALSE;
layout_mode = (LayoutMode) rm;
is_ssr_mode = layout_mode == LAYOUT_SSR;
SetFlexRootMaxWidth(g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::FlexRootMaxWidth), FALSE);
progress_mess[0] = 0;
progress_mess_low[0] = 0;
SetFeatures(type);
default_background_color = colorManager->GetBackgroundColor();
}
BOOL Window::Close()
{
if (window_locked)
{
window_closed = TRUE;
#ifdef SELFTEST
// Signal to the selftest system that this window is about to close and
// shouldn't be reused.
SetIsAboutToClose(TRUE);
#endif // SELFTEST
}
else
{
m_windowCommander->GetDocumentListener()->OnClose(m_windowCommander);
g_windowCommanderManager->GetUiWindowListener()->CloseUiWindow(m_windowCommander);
}
return TRUE;
}
void Window::SetOpener(Window* opened_by, int sub_win_id, BOOL make_available_to_script, BOOL from_window_open)
{
opener = opened_by;
opener_sub_win_id = sub_win_id;
is_available_to_script = make_available_to_script;
if (!can_be_closed_by_script && from_window_open)
can_be_closed_by_script = TRUE;
if (FramesDocument *document = GetOpener())
{
OP_ASSERT(!opener_origin);
opener_origin = document->GetMutableOrigin();
opener_origin->IncRef();
}
#ifdef CLIENTSIDE_STORAGE_SUPPORT
if (opened_by)
DocManager()->SetStorageManager(opened_by->DocManager()->GetStorageManager(FALSE));
#endif // CLIENTSIDE_STORAGE_SUPPORT
}
FramesDocument* Window::GetOpener(BOOL is_script/*=TRUE*/)
{
FramesDocument* doc = NULL;
if (opener && (is_available_to_script || !is_script))
{
DocumentManager* doc_man = opener->GetDocManagerById(opener_sub_win_id);
if (!doc_man)
doc_man = opener->DocManager();
doc = doc_man->GetCurrentDoc();
}
return doc;
}
URL Window::GetOpenerSecurityContext()
{
if (opener_origin)
return opener_origin->security_context;
return URL();
}
#ifndef MOUSELESS
CursorType Window::GetCurrentCursor()
{
if (has_cursor_set_by_doc)
return cursor_set_by_doc;
switch (state)
{
case BUSY:
return IsNormalWindow() ? CURSOR_WAIT : CURSOR_DEFAULT_ARROW;
case CLICKABLE:
return IsNormalWindow() ? CURSOR_ARROW_WAIT : CURSOR_DEFAULT_ARROW;
default: // There should be no other states.
OP_ASSERT(0);
/* fall through */
case NOT_BUSY:
case RESERVED: // The RESERVED state is currently unused.
return CURSOR_DEFAULT_ARROW;
}
}
CursorType Window::GetCurrentArrowCursor()
{
// Disable the doc cursor and ask what the cursor would be in that case
BOOL doc_cursor = has_cursor_set_by_doc;
has_cursor_set_by_doc = FALSE;
CursorType arrow_cursor = GetCurrentCursor();
has_cursor_set_by_doc = doc_cursor;
return arrow_cursor;
}
#endif // !MOUSELESS
void Window::SetState(WinState s)
{
state = s;
#ifndef MOUSELESS
SetCursor(GetCurrentCursor());
#endif // !MOUSELESS
}
Window::~Window()
{
#if defined _PRINT_SUPPORT_
if (is_printing)
StopPrinting();
#endif // _PRINT_SUPPORT_
#ifdef NEARBY_ELEMENT_DETECTION
SetElementExpander(NULL);
#endif // NEARBY_ELEMENT_DETECTION
#ifdef WAND_SUPPORT
if (m_wand_in_progress_count)
{
g_wand_manager->UnreferenceWindow(this);
OP_ASSERT(m_wand_in_progress_count == 0);
}
#endif // WAND_SUPPORT
if (opener_origin)
{
opener_origin->DecRef();
opener_origin = NULL;
}
if (GetPrivacyMode())
g_windowManager->RemoveWindowFromPrivacyModeContext();
// Remove all references to msg_handler from urlManager
// Must be done before deleting the doc_manager because it may call back to our listener where we use it.
if (urlManager && msg_handler)
urlManager->RemoveMessageHandler(msg_handler);
loading = FALSE;
if (doc_manager) // Can be NULL if Construct failed and we're deleting a half-created object
{
doc_manager->Clear();
OP_DELETE(doc_manager);
}
if (vis_device)
{
vis_device->SetDocumentManager(NULL);
OP_DELETE(vis_device);
}
if (msg_handler)
{
msg_handler->UnsetCallBacks(this);
OP_DELETE(msg_handler);
}
OP_DELETEA(current_default_message);
OP_DELETEA(current_message);
if (urlManager)
urlManager->FreeUnusedResources(FALSE);
if (m_opWindow)
m_opWindow->SetWindowListener(NULL);
OP_DELETE(windowlistener); windowlistener=NULL;
#ifdef _SPAT_NAV_SUPPORT_
OP_DELETE(sn_handler); sn_handler=NULL;
#endif // _SPAT_NAV_SUPPORT_
#ifdef SHORTCUT_ICON_SUPPORT
if (shortcut_icon_provider)
shortcut_icon_provider->DecRef(NULL);
#endif
#if defined SEARCH_MATCHES_ALL
OP_DELETE(m_search_data);
#endif // SEARCH_MATCHES_ALL
#ifdef FONTCACHE_PER_WINDOW
g_font_cache->ClearForWindow(this);
#endif // FONTCACHE_PER_WINDOW
OP_DELETE(viewportcontroller);
#ifdef USE_OP_CLIPBOARD
g_clipboard_manager->UnregisterListener(this);
#endif // USE_OP_CLIPBOARD
}
void Window::EnsureHistoryLimits()
{
if (GetHistoryLen() > g_pccore->GetIntegerPref(PrefsCollectionCore::MaxWindowHistory))
SetMaxHistory(g_pccore->GetIntegerPref(PrefsCollectionCore::MaxWindowHistory));
}
OP_STATUS Window::UpdateTitle(BOOL delay)
{
if (delay)
{
if (!title_update_title_posted)
{
msg_handler->PostMessage(MSG_UPDATE_WINDOW_TITLE, 0 , 0);
title_update_title_posted = TRUE;
}
return OpStatus::OK;
}
URL url = GetCurrentURL();
FramesDocument* doc = doc_manager->GetCurrentDoc();
if (!doc)
return OpStatus::ERR;
OpString title;
BOOL generated = FALSE;
TempBuffer buffer;
const uni_char* str = doc->Title(&buffer);
URL& origurl = url;
if (str && *str)
RETURN_IF_ERROR(title.Set(str));
else
{
// Might be nice to send an unescaped string to the UI but then we have to know the charset
// and decode it correctly. Bug 250545.
RETURN_IF_ERROR(origurl.GetAttribute(URL::KUniName_Username_Password_Hidden_Escaped,title));
generated = TRUE;
}
RETURN_IF_ERROR(SetWindowTitle(title, FALSE, generated));
RETURN_IF_ERROR(SetProgressText(url));
#ifdef HISTORY_SUPPORT
// Update the title in the entry in global history
if (doc_manager->GetCurrentDoc())
RETURN_IF_ERROR(AddToGlobalHistory(doc_manager->GetCurrentDoc()->GetURL(), title.CStr()));
#endif // HISTORY_SUPPORT
#ifdef CPUUSAGETRACKING
TempBuffer cpuusage_display_name;
switch (type)
{
case WIN_TYPE_NORMAL:
case WIN_TYPE_GADGET:
{
OpString prefix;
OpStatus::Ignore(g_languageManager->GetString(
type == WIN_TYPE_NORMAL ? Str::S_OPERACPU_WINDOW_SOURCE_PREFIX : Str::S_OPERACPU_WIDGET_SOURCE_PREFIX,
prefix));
OpStatus::Ignore(cpuusage_display_name.Append(prefix.CStr(), prefix.Length()));
OpStatus::Ignore(cpuusage_display_name.Append(' '));
break;
}
default:
; // No prefix
}
OpStatus::Ignore(cpuusage_display_name.Append(title.CStr()));
OpStatus::Ignore(cpu_usage_tracker.SetDisplayName(cpuusage_display_name.GetStorage()));
if (type == WIN_TYPE_NORMAL)
cpu_usage_tracker.SetActivatable();
#endif // CPUUSAGETRACKING
return OpStatus::OK;
}
void Window::SetLoading(BOOL set)
{
loading = set;
}
OP_STATUS Window::StartProgressDisplay(BOOL bReset, BOOL bResetSecurityState, BOOL bSubResourcesOnly)
{
if (!end_progress_message_sent)
{
// If we start loading a document, make sure UI is told about it.
if (!m_loading_information.hasRequestedDocument && !bSubResourcesOnly)
{
m_loading_information.hasRequestedDocument = TRUE;
m_windowCommander->GetLoadingListener()->OnLoadingProgress(m_windowCommander, &m_loading_information);
}
return OpStatus::OK;
}
start_time = g_timecache->CurrentTime();
if (bResetSecurityState)
ResetSecurityStateToUnknown();
if (bReset)
ResetProgressDisplay();
m_loading_information.hasRequestedDocument |= !bSubResourcesOnly;
#ifdef DOCHAND_CLEAR_RAMCACHE_ON_STARTPROGRESS
if( bReset )
urlManager->CheckRamCacheSize( 0 );
#endif
msg_handler->PostMessage(MSG_PROGRESS_START, 0, 0);
end_progress_message_sent = FALSE; // If there was one earlier, that will be for an earlier progress and we should not care more about that one
return OpStatus::OK;
}
void Window::EndProgressDisplay()
{
SetState(NOT_BUSY);
CSSCollection* coll = GetCSSCollection();
CSS* css = NULL;
if (coll)
{
CSSCollection::Iterator iter(coll, CSSCollection::Iterator::STYLESHEETS);
do {
css = static_cast<CSS *>(iter.Next());
} while (css && css->GetKind() == CSS::STYLE_PERSISTENT);
}
if (css != NULL)
{
m_windowCommander->GetLinkListener()->OnAlternateCssAvailable(m_windowCommander);
}
#ifdef LINK_SUPPORT
const LinkElement* linkElt = GetLinkList();
if (linkElt != NULL)
{
m_windowCommander->GetLinkListener()->OnLinkElementAvailable(m_windowCommander);
}
#endif // LINK_SUPPORT
if (!end_progress_message_sent)
{
URL url = doc_manager->GetCurrentURL();
OpLoadingListener::LoadingFinishStatus status;
// FIXME: backstrom, are there more status to report?
if (doc_manager->ErrorPageShown()) // If we've shown an error page instead of the page itself loading failed
status = OpLoadingListener::LOADING_COULDNT_CONNECT;
else if(url.Status(TRUE) == URL_LOADED)
status = OpLoadingListener::LOADING_SUCCESS;
else if(url.Status(TRUE) == URL_LOADING_FAILURE)
status = OpLoadingListener::LOADING_COULDNT_CONNECT;
else
status = OpLoadingListener::LOADING_UNKNOWN;
msg_handler->PostMessage(MSG_PROGRESS_END, 0, status);
end_progress_message_sent = TRUE;
pending_unlock_all_painting = TRUE;
}
else if (!pending_unlock_all_painting)
{
// Normally this is done on the MSG_PROGRESS_END message (and changing that
// causes performance regressions which are not fully understood yet) but in case
// we locked painting and then never started a progress bar (think javascript
// urls and bookmarklets) we need to unlock it somewhere else, i.e. here.
UnlockPaintLock();
}
#ifdef HTTP_BENCHMARK
EndBenchmark();
#endif
}
void Window::ResetProgressDisplay()
{
SetProgressCount(0);
SetDocProgressCount(0);
m_loading_information.Reset();
SetProgressState(WAITING, NULL, NULL, 0, NULL);
SetUploadTotal(0);
}
void Window::SetTrueZoom(BOOL status)
{
truezoom = status;
if (scale != 100)
SetScale(scale);
}
void Window::SetTrueZoomBaseScale(UINT32 scale)
{
if (scale == truezoom_base_scale)
return;
truezoom_base_scale = scale;
DocumentTreeIterator it(doc_manager);
it.SetIncludeThis();
it.SetIncludeEmpty();
while (it.Next())
{
VisualDevice* vd = it.GetDocumentManager()->GetVisualDevice();
FramesDocument* doc = it.GetFramesDocument();
#ifdef CSS_VIEWPORT_SUPPORT
if (doc && doc->GetHLDocProfile())
{
doc->RecalculateLayoutViewSize(TRUE);
if (doc->IsTopDocument())
doc->RequestSetViewportToInitialScale(VIEWPORT_CHANGE_REASON_BASE_SCALE);
}
#endif // CSS_VIEWPORT_SUPPORT
// Can it be null?
if (vd)
{
vd->SetLayoutScale(scale);
if (doc && doc->GetDocRoot())
doc->GetDocRoot()->RemoveCachedTextInfo(doc);
}
}
OpViewportInfoListener* info_listener = viewportcontroller->GetViewportInfoListener();
info_listener->OnTrueZoomBaseScaleChanged(viewportcontroller, scale);
}
void Window::SetScale(INT32 sc)
{
if (sc < DOCHAND_MIN_DOC_ZOOM)
sc = DOCHAND_MIN_DOC_ZOOM;
else if (sc > DOCHAND_MAX_DOC_ZOOM)
sc = DOCHAND_MAX_DOC_ZOOM;
BOOL changed = (scale != sc);
scale = sc;
#ifdef PAGED_MEDIA_SUPPORT
if (changed && IsFullScreen())
if (FramesDocument *current_doc = GetCurrentDoc())
if (LogicalDocument* logdoc = current_doc->GetLogicalDocument())
current_doc->SetRestoreCurrentPageNumber(logdoc->GetLayoutWorkplace()->GetCurrentPageNumber());
#endif // PAGED_MEDIA_SUPPORT
doc_manager->SetScale( scale );
// A subdocument may now have individual scalefactor. That's why we call doc_manager->SetScale always. But we don't tell windowcommander
// if the window scale didn't change.
if (!changed)
return;
m_windowCommander->GetDocumentListener()->OnScaleChanged(m_windowCommander, scale);
}
void Window::SetTextScale(int sc)
{
if (sc < DOCHAND_MIN_DOC_ZOOM)
sc = DOCHAND_MIN_DOC_ZOOM;
else if (sc > DOCHAND_MAX_DOC_ZOOM)
sc = DOCHAND_MAX_DOC_ZOOM;
m_text_scale = sc;
if (doc_manager->GetCurrentDoc())
doc_manager->GetCurrentDoc()->SetTextScale(m_text_scale);
if (doc_manager->GetVisualDevice())
doc_manager->GetVisualDevice()->SetTextScale(m_text_scale);
}
#ifdef PIXEL_SCALE_RENDERING_SUPPORT
int Window::GetPixelScale()
{
return m_opWindow->GetPixelScale();
}
#endif // PIXEL_SCALE_RENDERING_SUPPORT
const uni_char* Window::GetProgressMessage()
{
if(progress_mess[0] == 0)
{
uni_strcpy(progress_mess, progress_mess_low);
progress_mess_low[0] = 0;
}
return progress_mess;
}
void Window::SetUploadTotal(OpFileLength progress_info1)
{
upload_total_bytes = progress_info1;
}
void Window::SetUploadFileCount(int total, int loaded)
{
upload_file_count = total;
upload_file_loaded_count = loaded;
}
void Window::SetProgressState(ProgressState state, const uni_char* extrainfo, MessageHandler *mh, long bytes, URL *loading_url)
{
OP_MEMORY_VAR BOOL upload_started = FALSE;
OP_MEMORY_VAR BOOL upload_ended = FALSE;
if (state == REQUEST_FINISHED)
{
msg_handler->PostMessage(MSG_REFRESH_PROGRESS, 0 , 0);
if (*progress_mess_low)
return;
progress_mess[0] = 0;
}
if (state != progress_state || extrainfo)
{
progress_state = state;
Str::LocaleString string_number = Str::NOT_A_STRING;
OP_MEMORY_VAR BOOL use_numeric_syntax = FALSE; /* Use %1 %2 instead of %s etc. */
switch (state)
{
case WAITING_FOR_COOKIES:
string_number = Str::SI_MPAR_URL_WAITING_FOR_COOKIES;
break;
case WAITING_FOR_COOKIES_DNS:
string_number = Str::SI_MPAR_URL_WAITING_FOR_COOKIES_DNS;
break;
case REQUEST_QUEUED:
string_number = Str::SI_MPAR_URL_REQUEST_QUEUED_STRING;
break;
case START_NAME_LOOKUP:
string_number = Str::SI_MPAR_URL_START_NAME_LOOKUP_STRING;
break;
case START_NAME_COMPLETION:
string_number = Str::SI_MPAR_URL_START_NAME_COMPLETION_STRING;
break;
case START_SECURE_CONNECTION:
string_number = Str::SI_MPAR_URL_START_SECURE_CONNECTION_STRING;
break;
case START_CONNECT_PROXY:
string_number = Str::SI_MPAR_URL_START_CONNECT_PROXY_STRING;
break;
case WAITING_FOR_CONNECTION:
string_number = Str::SI_MPAR_URL_WAITING_FOR_CONNECTION_STRING;
use_numeric_syntax = TRUE;
break;
case START_CONNECT:
string_number = Str::SI_MPAR_URL_START_CONNECT_STRING;
break;
case START_REQUEST:
string_number = Str::SI_MPAR_URL_START_REQUEST_STRING;
break;
case STARTED_40SECOND_TIMEOUT:
string_number = Str::SI_MPAR_URL_STARTED_40SECOND_TIMEOUT;
break;
case UPLOADING_FILES:
upload_started = TRUE;
string_number = Str::SI_UPLOADING_FILES_STRING;
#ifdef PROGRESS_EVENTS_SUPPORT
if (mh && loading_url && bytes > 0)
UpdateUploadProgress(mh, *loading_url, static_cast<unsigned long>(bytes));
#endif // PROGRESS_EVENTS_SUPPORT
break;
case FETCHING_DOCUMENT:
string_number = Str::SI_FETCHING_DOCUMENT_STRING;
break;
case EXECUTING_ECMASCRIPT:
string_number = Str::SI_EXECUTING_ECMASCRIPT_STRING;
break;
case REQUEST_FINISHED:
string_number = Str::SI_MPAR_URL_REQUEST_FINISHED_STRING;
break;
case UPLOADING_FINISHED:
upload_ended = TRUE;
break;
}
if (state == WAITING || string_number == Str::NOT_A_STRING)
{
ClearMessage();
progress_mess_low[0] = '\0';
progress_mess[0] = '\0';
}
else
{
OpString extra;
OpString string;
OpString message;
TRAPD(err, message.ReserveL(MAX_PROGRESS_MESS_LENGTH));
if (OpStatus::IsMemoryError(err))
{
RaiseCondition(err);
return;
}
TRAP(err, g_languageManager->GetStringL(string_number, string));
if (OpStatus::IsMemoryError(err))
{
RaiseCondition(err);
return;
}
if (extrainfo)
OpStatus::Ignore(extra.Set(extrainfo));
if (string.CStr())
{
if (!use_numeric_syntax)
{
uni_snprintf(message.CStr(), message.Capacity(), string.CStr(), (extra.Length() ? extra.CStr() : UNI_L("")));
}
else //Uses %1
{
uni_snprintf_si(message.CStr(), message.Capacity(), string.CStr(), (extra.Length() ? extra.CStr() : UNI_L("")),
(state == WAITING_FOR_CONNECTION ? Comm::CountWaitingComm(COMM_WAIT_STATUS_LOAD) : 0)
);
}
}
if (uni_strncmp(progress_mess, message.CStr(), MAX_PROGRESS_MESS_LENGTH) == 0)
return;
if(state == REQUEST_FINISHED)
{
uni_strlcpy(progress_mess_low, message.CStr(), MAX_PROGRESS_MESS_LENGTH);
}
else
{
uni_strlcpy(progress_mess, message.CStr(), MAX_PROGRESS_MESS_LENGTH);
}
}
#ifdef EPOC
// Certain windows are not prepared for interaction with WindowCommander.
if (type==WIN_TYPE_DOWNLOAD)
return;
#endif
m_loading_information.loadingMessage = GetProgressMessage();
FramesDocument* doc = GetCurrentDoc();
if (doc &&
(doc_manager->GetLoadStatus() == NOT_LOADING || doc_manager->GetLoadStatus() == DOC_CREATED) &&
!upload_started &&
!phase_uploading)
{
DocLoadingInfo info;
doc->GetDocLoadingInfo(info);
m_loading_information.loadedImageCount = info.images.loaded_count;
m_loading_information.totalImageCount = info.images.total_count;
m_loading_information.loadedBytes = info.loaded_size;
m_loading_information.totalBytes = info.total_size;
m_loading_information.loadedBytesRootDocument = GetDocProgressCount();
m_loading_information.totalBytesRootDocument = DocManager()->GetCurrentURL().GetContentSize();
#ifdef WEB_TURBO_MODE
m_loading_information.turboTransferredBytes = info.turbo_transferred_bytes + info.images.turbo_transferred_bytes;
m_loading_information.turboOriginalTransferredBytes = info.turbo_original_transferred_bytes + info.images.turbo_original_transferred_bytes;
#endif // WEB_TURBO_MODE
}
m_loading_information.isUploading = ((state == UPLOADING_FILES) || (state == UPLOADING_FINISHED));
if(upload_started && !phase_uploading)
{
OpFileLength upload_total;
DocManager()->GetCurrentURL().GetAttribute(URL::KHTTP_Upload_TotalBytes, &upload_total, URL::KFollowRedirect);
SetUploadTotal(upload_total);
phase_uploading = TRUE;
m_loading_information.totalBytes = upload_total_bytes;
m_windowCommander->GetLoadingListener()->OnStartUploading(m_windowCommander);
}
if (m_loading_information.isUploading)
{
m_loading_information.totalImageCount = upload_file_count;
m_loading_information.loadedImageCount = upload_file_loaded_count;
}
m_windowCommander->GetLoadingListener()->OnLoadingProgress(m_windowCommander, &m_loading_information);
if(upload_ended && phase_uploading)
{
phase_uploading = FALSE;
m_windowCommander->GetLoadingListener()->OnUploadingFinished(m_windowCommander, OpLoadingListener::LOADING_SUCCESS);
#ifdef PROGRESS_EVENTS_SUPPORT
if (mh && loading_url)
UpdateUploadProgress(mh, *loading_url, 0);
#endif // PROGRESS_EVENTS_SUPPORT
}
}
}
#ifdef PROGRESS_EVENTS_SUPPORT
void Window::UpdateUploadProgress(MessageHandler *mh, const URL &loading_url, unsigned long bytes)
{
mh->PostMessage(MSG_DOCHAND_UPLOAD_PROGRESS, loading_url.Id(), bytes);
}
#endif // PROGRESS_EVENTS_SUPPORT
Window* Window::GetOutputAssociatedWindow()
{
return g_windowManager->GetWindow(OutputAssociatedWindow);
}
void Window::SetFeature(Window_Feature feature)
{
m_features |= feature;
}
void Window::SetFeatures(Window_Type type)
{
m_features = 0;
switch (type)
{
case WIN_TYPE_JS_CONSOLE:
case WIN_TYPE_HISTORY:
case WIN_TYPE_NORMAL:
case WIN_TYPE_CACHE:
case WIN_TYPE_PLUGINS:
case WIN_TYPE_NORMAL_HIDDEN:
SetFeature(WIN_FEATURE_ALERTS);
SetFeature(WIN_FEATURE_PROGRESS);
SetFeature(WIN_FEATURE_NAVIGABLE);
SetFeature(WIN_FEATURE_PRINTABLE);
SetFeature(WIN_FEATURE_RELOADABLE);
SetFeature(WIN_FEATURE_FOCUSABLE);
SetFeature(WIN_FEATURE_HOMEABLE);
SetFeature(WIN_FEATURE_BOOKMARKABLE);
break;
#ifndef _NO_HELP_
case WIN_TYPE_HELP:
SetFeature(WIN_FEATURE_NAVIGABLE);
SetFeature(WIN_FEATURE_PRINTABLE);
SetFeature(WIN_FEATURE_RELOADABLE);
SetFeature(WIN_FEATURE_FOCUSABLE);
SetFeature(WIN_FEATURE_OUTSIDE);
SetFeature(WIN_FEATURE_BOOKMARKABLE);
break;
#endif // !_NO_HELP_
case WIN_TYPE_DOWNLOAD:
SetFeature(WIN_FEATURE_FOCUSABLE); // NOT for mswin
break;
case WIN_TYPE_MAIL_COMPOSE:
SetFeature(WIN_FEATURE_FOCUSABLE);
break;
case WIN_TYPE_MAIL_VIEW:
case WIN_TYPE_NEWSFEED_VIEW:
SetFeature(WIN_FEATURE_PRINTABLE);
SetFeature(WIN_FEATURE_FOCUSABLE);
break;
case WIN_TYPE_IM_VIEW:
SetFeature(WIN_FEATURE_PRINTABLE);
SetFeature(WIN_FEATURE_FOCUSABLE);
break;
case WIN_TYPE_BRAND_VIEW:
SetFeature(WIN_FEATURE_FOCUSABLE);
SetFeature(WIN_FEATURE_BOOKMARKABLE);
SetFeature(WIN_FEATURE_RELOADABLE);
break;
case WIN_TYPE_GADGET:
case WIN_TYPE_CONTROLLER:
SetFeature(WIN_FEATURE_FOCUSABLE);
SetFeature(WIN_FEATURE_RELOADABLE);
break;
case WIN_TYPE_INFO:
// no features
break;
#ifdef _PRINT_SUPPORT_
case WIN_TYPE_PRINT_SELECTION:
SetFeature(WIN_FEATURE_PRINTABLE);
break;
#endif // _PRINT_SUPPORT_
case WIN_TYPE_DIALOG:
SetFeature(WIN_FEATURE_NAVIGABLE);
SetFeature(WIN_FEATURE_FOCUSABLE);
break;
case WIN_TYPE_THUMBNAIL:
SetFeature(WIN_FEATURE_RELOADABLE);
break;
case WIN_TYPE_DEVTOOLS:
SetFeature(WIN_FEATURE_ALERTS);
SetFeature(WIN_FEATURE_PRINTABLE);
SetFeature(WIN_FEATURE_RELOADABLE);
SetFeature(WIN_FEATURE_FOCUSABLE);
break;
default:
// if this happens, add more window types or correct your code!
OP_ASSERT(true == false);
}
}
void Window::RemoveFeature(Window_Feature feature)
{
m_features &= ~feature;
}
BOOL Window::HasFeature(Window_Feature feature)
{
if (m_features & feature)
return TRUE;
else
return FALSE;
}
BOOL Window::HasAllFeatures(Window_Feature feature)
{
if ((m_features & feature) == (unsigned long) feature)
return TRUE;
else
return FALSE;
}
OP_STATUS Window::SetFullScreenState(OpWindowCommander::FullScreenState state)
{
if (m_fullscreen_state == state)
return OpStatus::OK;
FramesDocument *doc = doc_manager->GetCurrentDoc();
/* Store the new state before calling DOMExitFullscreen() so it does not notify the platform
* about turning fullscreen off (the platform is the one which turned it off).
*/
m_fullscreen_state = state;
if (doc)
{
#ifdef DOM_FULLSCREEN_MODE
if (state == OpWindowCommander::FULLSCREEN_NONE)
{
// Fullscreen was disabled.
RETURN_IF_MEMORY_ERROR(doc->DOMExitFullscreen(NULL));
}
#endif // DOM_FULLSCREEN_MODE
// Try to keep the scroll positions
doc_manager->StoreViewport(doc_manager->CurrentDocListElm());
}
vis_device->SetScrollType(m_fullscreen_state != OpWindowCommander::FULLSCREEN_PROJECTION && bShowScrollbars ? VisualDevice::VD_SCROLLING_AUTO : VisualDevice::VD_SCROLLING_NO);
if (doc)
{
RETURN_IF_MEMORY_ERROR(UpdateWindow()); // cause reformat because stylesheets may be different
BOOL make_fit = doc->IsLocalDocFinished();
doc_manager->RestoreViewport(TRUE, TRUE, make_fit);
}
return OpStatus::OK;
}
void Window::SetOutputAssociatedWindow(Window* ass)
{
OutputAssociatedWindow = ass ? ass->Id() : 0;
}
void Window::SetShowScrollbars(BOOL show)
{
bShowScrollbars = show;
vis_device->SetScrollType(bShowScrollbars ? VisualDevice::VD_SCROLLING_AUTO : VisualDevice::VD_SCROLLING_NO);
if (FramesDocument *doc = doc_manager->GetCurrentDoc())
{
doc->RecalculateScrollbars();
doc->RecalculateLayoutViewSize(TRUE);
}
}
void Window::SetName(const uni_char *n)
{
OP_STATUS ret = name.Set(n);
if (OpStatus::IsError(ret))
{
RaiseCondition(ret);
}
}
void Window::SetNextCSSMode()
{
switch (CSSMode)
{
case CSS_FULL:
SetCSSMode(CSS_NONE);
break;
default:
SetCSSMode(CSS_FULL);
break;
}
}
void Window::SetCSSMode(CSSMODE f)
{
CSSMode = f;
OpDocumentListener::CssDisplayMode mode;
if (CSSMode == CSS_FULL)
{
mode = OpDocumentListener::CSS_AUTHOR_MODE;
}
else
{
mode = OpDocumentListener::CSS_USER_MODE;
}
m_windowCommander->GetDocumentListener()->OnCssModeChanged(m_windowCommander, mode);
OP_STATUS ret = UpdateWindow();
if (OpStatus::IsMemoryError(ret))
{
RaiseCondition(ret);//FIXME:OOM - Can't return OOM err.
}
}
void Window::SetForceEncoding(const char *encoding, BOOL isnewwin)
{
OP_STATUS ret = forceEncoding.Set(encoding);
if (OpStatus::IsMemoryError(ret))
{
RaiseCondition(ret);//FIXME:OOM - Can't return OOM err.
}
// Update document in window
if (!isnewwin)
{
ret = doc_manager->UpdateCurrentDoc(FALSE, FALSE, FALSE);
if (OpStatus::IsMemoryError(ret))
{
RaiseCondition(ret);//FIXME:OOM - Can't return OOM err.
}
}
}
void Window::UpdateVisitedLinks(const URL& url)
{
doc_manager->UpdateVisitedLinks(url);
}
#ifdef SHORTCUT_ICON_SUPPORT
# ifdef ASYNC_IMAGE_DECODERS
void Window::OnPortionDecoded()
{
if (shortcut_icon_provider && shortcut_icon_provider->GetImage().ImageDecoded())
{
m_windowCommander->GetDocumentListener()->OnDocumentIconAdded(m_windowCommander);
}
}
# endif // ASYNC_IMAGE_DECODERS
#ifdef SVG_SUPPORT
OP_STATUS Window::SetSVGAsWindowIcon(SVGImageRef* ref)
{
if(!shortcut_icon_provider)
{
URL* url = ref->GetUrl();
shortcut_icon_provider = UrlImageContentProvider::FindImageContentProvider(*url);
if (shortcut_icon_provider == NULL)
{
shortcut_icon_provider = OP_NEW(UrlImageContentProvider, (*url));
if (shortcut_icon_provider == NULL)
return OpStatus::ERR_NO_MEMORY;
}
}
shortcut_icon_provider->SetSVGImageRef(ref);
shortcut_icon_provider->IncRef(NULL);
return OpStatus::OK;
}
void Window::RemoveSVGWindowIcon(SVGImageRef* ref)
{
if (shortcut_icon_provider && shortcut_icon_provider->GetSVGImageRef() == ref)
{
shortcut_icon_provider->DecRef(NULL);
shortcut_icon_provider = NULL;
}
}
#endif // SVG_SUPPORT
OP_STATUS Window::SetWindowIcon(URL* url)
{
// proposal:
// make core passive and let ui query document (via Window) each
// time a page is loaded?
if (url)
{
if (url->Status(TRUE) != URL_LOADED)
{
url = NULL;
if (FramesDocument *frm_doc = GetCurrentDoc())
{
URL *icon = frm_doc->Icon();
HTML_Element *he = frm_doc->GetDocRoot();
if (icon && he)
{
OP_BOOLEAN loading = frm_doc->LoadIcon(icon, he);
if (OpStatus::IsMemoryError(loading))
return loading;
}
return OpStatus::OK;
}
}
else if (url->Type() == URL_HTTP || url->Type() == URL_HTTPS)
{
int response = url->GetAttribute(URL::KHTTP_Response_Code);
if (response != HTTP_OK && response != HTTP_NOT_MODIFIED)
url = NULL;
}
}
#ifdef SVG_SUPPORT
SVGImageRef* ref = NULL;
if (url && url->ContentType() == URL_SVG_CONTENT)
{
ref = shortcut_icon_provider ? shortcut_icon_provider->GetSVGImageRef() : NULL;
if(ref)
{
shortcut_icon_provider->SetSVGImageRef(NULL); // detach for a moment
}
else
{
OP_STATUS status = OpStatus::ERR;
if (FramesDocument* frm_doc = GetCurrentDoc())
if (LogicalDocument* logdoc = frm_doc->GetLogicalDocument())
{
status = logdoc->GetSVGWorkplace()->GetSVGImageRef(*url, &ref);
if (OpStatus::IsSuccess(status))
SetSVGAsWindowIcon(ref);
}
return status;
}
}
// Need to render the SVG icon if we have a ref parameter...
if(!ref)
#endif // SVG_SUPPORT
{
if (url ? *url == m_shortcut_icon_url : m_shortcut_icon_url.IsEmpty())
return OpStatus::OK;
}
if (url)
m_shortcut_icon_url = URL(*url);
else
m_shortcut_icon_url = URL();
#ifndef ASYNC_IMAGE_DECODERS
if (shortcut_icon_provider)
{
// shortcut_icon_provider->GetImage().DecVisible(null_image_listener);
shortcut_icon_provider->DecRef(NULL);
shortcut_icon_provider = NULL;
}
#else // !ASYNC_IMAGE_DECODERS
if (shortcut_icon_provider && (shortcut_icon_provider->GetImage().ImageDecoded() || !url))
{
shortcut_icon_provider->GetImage().DecVisible(this);
shortcut_icon_provider->DecRef(NULL);
shortcut_icon_provider = NULL;
}
#endif // ASYNC_IMAGE_DECODERS
if (url)
{
shortcut_icon_provider = UrlImageContentProvider::FindImageContentProvider(*url);
if (shortcut_icon_provider == NULL)
{
shortcut_icon_provider = OP_NEW(UrlImageContentProvider, (*url));
if (shortcut_icon_provider == NULL)
{
#ifdef SVG_SUPPORT
if (ref != NULL)
OpStatus::Ignore(ref->Free());
#endif // SVG_SUPPORT
return OpStatus::ERR_NO_MEMORY;
}
// Changing contenttype to an image - if it seems like it is a favicon
if(!url->GetAttribute(URL::KIsImage))
{
OpString ext;
OP_STATUS ret_val = url->GetAttribute(URL::KSuggestedFileNameExtension_L, ext);
if (OpStatus::IsSuccess(ret_val))
{
const char* data;
INT32 data_len;
BOOL more;
ret_val = shortcut_icon_provider->GetData(data, data_len, more);
// If it contains the magic sequence (copied from modules/img/src/decoderfactoryico.cpp
// method DecoderFactoryIco::CheckType) and if urls suggested extension is ico :
// Force content type to be image/x-icon
// This will result in it being accepted as an image by the image module. [psmaas 27-01-2006]
if (OpStatus::IsSuccess(ret_val) && data_len >= 4 && op_memcmp(data, "\0\0\1\0", 4) == 0 && ext.Compare("ico") == 0)
{
ret_val = url->SetAttribute(URL::KMIME_ForceContentType, "image/x-icon");
}
}
if(OpStatus::IsMemoryError(ret_val))
{
#ifdef SVG_SUPPORT
if (ref != NULL)
OpStatus::Ignore(ref->Free());
#endif // SVG_SUPPORT
OP_DELETE(shortcut_icon_provider);
shortcut_icon_provider = NULL;
return OpStatus::ERR_NO_MEMORY;
}
}
}
#ifdef SVG_SUPPORT
if (ref && url->ContentType() == URL_SVG_CONTENT)
{
int desired_width = 16; // FIXME: Is 16x16 a good default?
int desired_height = 16;
#ifdef PIXEL_SCALE_RENDERING_SUPPORT
const PixelScaler& scaler = vis_device->GetVPScale();
desired_width = TO_DEVICE_PIXEL(scaler, desired_width);
desired_height = TO_DEVICE_PIXEL(scaler, desired_height);
#endif // PIXEL_SCALE_RENDERING_SUPPORT
SVGImage* svgimage = ref->GetSVGImage();
if (!svgimage)
{
#ifdef SVG_SUPPORT
OpStatus::Ignore(ref->Free());
#endif // SVG_SUPPORT
OP_DELETE(shortcut_icon_provider);
shortcut_icon_provider = NULL;
return OpStatus::OK;
}
Image img = shortcut_icon_provider->GetImage();
if (img.IsFailed() ||
img.Width() != (unsigned int) desired_width ||
img.Height() != (unsigned int) desired_height)
{
OpBitmap* res;
if (OpStatus::IsSuccess(svgimage->PaintToBuffer(res, 0, desired_width, desired_height)))
{
if(OpStatus::IsError(img.ReplaceBitmap(res)))
{
OP_DELETE(res);
}
else
{
shortcut_icon_provider->SetSVGImageRef(ref);
ref = NULL;
}
}
}
if (ref)
{
OpStatus::Ignore(ref->Free());
OP_DELETE(shortcut_icon_provider);
shortcut_icon_provider = NULL;
return OpStatus::OK;
}
}
#endif // SVG_SUPPORT
shortcut_icon_provider->IncRef(NULL);
#ifdef ASYNC_IMAGE_DECODERS
shortcut_icon_provider->GetImage().IncVisible(this);
#endif
}
Image icon;
if (shortcut_icon_provider)
icon = shortcut_icon_provider->GetImage();
// to force loading
#ifndef ASYNC_IMAGE_DECODERS
RETURN_IF_ERROR(icon.IncVisible(null_image_listener));
if (shortcut_icon_provider)
icon.OnMoreData(shortcut_icon_provider);
#endif // ASYNC_IMAGE_DECODERS
// We need this call when running ASYNC_IMAGE_DECODERS as well in order
// to get notified about it when doing a reload..
m_windowCommander->GetDocumentListener()->OnDocumentIconAdded(m_windowCommander);
#ifndef ASYNC_IMAGE_DECODERS
icon.DecVisible(null_image_listener);
#endif
return OpStatus::OK;
}
Image Window::GetWindowIcon() const
{
if (shortcut_icon_provider)
return shortcut_icon_provider->GetImage(); // CAN BE DANGEROUS IF KEEPT WHILE shortcut_icon_provider is deleted.
return Image();
}
BOOL Window::HasWindowIcon() const
{
if (shortcut_icon_provider)
return !shortcut_icon_provider->GetImage().IsEmpty();
return FALSE;
}
OP_STATUS Window::DecodeWindowIcon()
{
if (!HasWindowIcon() || shortcut_icon_provider->GetImage().ImageDecoded())
return OpStatus::OK;
Image icon = shortcut_icon_provider->GetImage();
RETURN_IF_ERROR(icon.IncVisible(null_image_listener));
icon.OnMoreData(shortcut_icon_provider);
icon.DecVisible(null_image_listener);
return OpStatus::OK;
}
#endif // SHORTCUT_ICON_SUPPORT
#ifdef HISTORY_SUPPORT
OP_STATUS Window::AddToGlobalHistory(URL& url, const uni_char *title)
{
if (g_globalHistory && !m_privacy_mode && m_global_history_enabled && g_url_api->GlobalHistoryPermitted(url) )
if (HasFeature(WIN_FEATURE_NAVIGABLE))
{
OpString url_string;
RETURN_IF_ERROR(url.GetAttribute(URL::KUniName_With_Fragment_Username, url_string));
return g_globalHistory->Add(url_string, title, g_timecache->CurrentTime());
}
return OpStatus::OK;
}
#endif // HISTORY_SUPPORT
/* Limited length of window titles. Apparently there's a Internet
Explorer extension that can't handle long window titles. This
patch works around the problem, and at the same time looks nice. */
OP_STATUS Window::SetWindowTitle(const OpString& nstr, BOOL force, BOOL generated)
{
generated_title = generated;
const uni_char *str = nstr.CStr();
if (!str)
str = UNI_L("...");
BOOL titleChanged = title.IsEmpty() || !uni_str_eq(str, title.CStr());
// Reset defaultStatus only when title changes and force is not set
if(titleChanged && !force)
{
RETURN_IF_ERROR(SetDefaultMessage(UNI_L("")));
}
// Only set window title if it changed or we are forced to do an update
if (titleChanged || force)
{
if (titleChanged)
RETURN_IF_ERROR(title.Set(str));
int strLen = uni_strlen(str) + 1;
uni_char *newTitle = OP_NEWA(uni_char, strLen);
if (newTitle == NULL)
{
return OpStatus::ERR_NO_MEMORY;
}
uni_strcpy(newTitle, str);
if (strLen > DOC_WINDOW_MAX_TITLE_LENGTH)
uni_strcpy(newTitle + DOC_WINDOW_MAX_TITLE_LENGTH - 4, UNI_L("..."));
m_windowCommander->GetDocumentListener()->OnTitleChanged(m_windowCommander, newTitle);
#ifdef SCOPE_WINDOW_MANAGER_SUPPORT
OpScopeWindowListener::OnWindowTitleChanged(this);
#endif // SCOPE_WINDOW_MANAGER_SUPPORT
OP_DELETEA(newTitle);
}
return OpStatus::OK;
}
void Window::SignalSecurityState(BOOL changed)
{
switch (doc_manager->GetLoadStatus())
{
case NOT_LOADING:
case DOC_CREATED:
case WAIT_MULTIPART_RELOAD:
break;
default:
/* Don't signal new security state to UI while loading URL until we've
created a new document. If we do, we'll be reporting a security
state that doesn't match the currently displayed document in the
window, which could possibly be the cause of spoofing bugs.
One exception though: if we for some reason have already reported a
specific security state and are now about to lower it we don't want
to delay the lowering. */
if (!(SecurityState < SecurityState_signalled && SecurityState_signalled != SECURITY_STATE_UNKNOWN || SecurityState == SECURITY_STATE_UNKNOWN))
{
if (changed)
SecurityState_signal_delayed = TRUE;
return;
}
}
if (changed || SecurityState_signal_delayed)
{
OpDocumentListener::SecurityMode mode = m_windowCommander->GetSecurityModeFromState(SecurityState);
m_windowCommander->GetDocumentListener()->OnSecurityModeChanged(m_windowCommander, mode, SecurityState_changed_by_inline);
SecurityState_signalled = SecurityState;
SecurityState_signal_delayed = FALSE;
}
}
void Window::ResetSecurityStateToUnknown()
{
LowLevelSetSecurityState(SECURITY_STATE_UNKNOWN, FALSE, NULL);
}
void Window::SetSecurityState(BYTE sec, BOOL is_inline, const uni_char *name, URL *url)
{
if (sec != SECURITY_STATE_UNKNOWN)
LowLevelSetSecurityState(sec, is_inline, name, url);
}
void Window::LowLevelSetSecurityState(BYTE sec, BOOL is_inline, const uni_char *name, URL *url)
{
if (sec < SecurityState || sec == SECURITY_STATE_UNKNOWN)
{
BOOL state_changed = FALSE;
if (SecurityState != sec)
{
// Before core-2.3 we didn't let the UI know about changes between UNKNOWN and NONE
// but as always it turned out to be better to tell the whole truth.
state_changed = TRUE;
#ifdef SSL_CHECK_EXT_VALIDATION_POLICY
if(SecurityState >= SECURITY_STATE_SOME_EXTENDED &&
SecurityState <= SECURITY_STATE_FULL_EXTENDED &&
sec >= SECURITY_STATE_FULL && sec <SECURITY_STATE_FULL_EXTENDED &&
!(BOOL) g_pcnet->GetIntegerPref(PrefsCollectionNetwork::StrictEVMode))
{
if (SecurityState == SECURITY_STATE_SOME_EXTENDED && SecurityTextName.Compare(name) == 0)
return;
else
sec = SECURITY_STATE_SOME_EXTENDED;
}
#endif // SSL_CHECK_EXT_VALIDATION_POLICY
}
SecurityState = sec;
if (SecurityTextName.Set(sec && sec != SECURITY_STATE_UNKNOWN ? name : NULL) == OpStatus::ERR_NO_MEMORY)
RaiseCondition(OpStatus::ERR_NO_MEMORY);
if (state_changed)
{
SecurityState_changed_by_inline = is_inline;
SignalSecurityState(TRUE);
}
}
}
#ifdef TRUST_RATING
void Window::SetTrustRating(TrustRating rating, BOOL force)
{
OP_ASSERT(rating != Untrusted_Ask_Advisory);
if (force || m_trust_rating < rating)
{
m_trust_rating = rating;
m_windowCommander->GetDocumentListener()->OnTrustRatingChanged(m_windowCommander, rating);
}
}
OP_STATUS Window::CheckTrustRating(BOOL force, BOOL offline)
{
DocumentTreeIterator iter(doc_manager);
iter.SetIncludeThis();
while (iter.Next())
{
if (FramesDocument* doc = iter.GetFramesDocument())
RETURN_IF_MEMORY_ERROR(iter.GetDocumentManager()->CheckTrustRating(doc->GetURL(), offline, force));
}
return OpStatus::OK;
}
#endif // TRUST_RATING
void Window::SetType(DocType doc_type)
{
/* Not entirely sure this function serves much of a purpose anymore. */
if (type != WIN_TYPE_DOWNLOAD && IsCustomWindow())
return;
if (type == WIN_TYPE_JS_CONSOLE ) // console is a custom window (maybe it should not be that)
return;
SetType(WIN_TYPE_NORMAL);
}
BOOL Window::CloneWindow(Window**return_window,BOOL open_in_background)
{
if (IsCustomWindow())
return FALSE;
BOOL3 open_in_new_window = YES;
BOOL3 in_background = open_in_background?YES:NO;
Window* new_window = g_windowManager->GetAWindow(TRUE, open_in_new_window, in_background);
if (!new_window)
return FALSE;
new_window->SetCSSMode(CSSMode);
new_window->SetScale(GetScale());
new_window->SetTextScale(GetTextScale());
new_window->SetForceEncoding(GetForceEncoding(), TRUE);
if (load_img && show_img)
{
new_window->SetImagesSetting(FIGS_ON);
}
else if (show_img)
{
new_window->SetImagesSetting(FIGS_SHOW);
}
else
{
new_window->SetImagesSetting(FIGS_OFF);
}
#ifdef FIT_LARGE_IMAGES_TO_WINDOW_WIDTH
new_window->fit_img = fit_img;
#endif // FIT_LARGE_IMAGES_TO_WINDOW_WIDTH
DocumentManager* doc_man1 = DocManager();
DocumentManager* doc_man2 = new_window->DocManager();
short pos = GetCurrentHistoryNumber();
DocListElm* doc_elm = doc_man1->FirstDocListElm();
while (doc_elm)
{
FramesDocument* doc = doc_elm->Doc();
if (doc)
{
URL docurl = doc->GetURL();
DocumentReferrer referrer(doc->GetRefURL());
RAISE_IF_MEMORY_ERROR(doc_man2->AddNewHistoryPosition(docurl, referrer, doc_elm->Number(), doc_elm->Title(), FALSE, doc->IsPluginDoc()));
}
doc_elm = doc_elm->Suc();
}
new_window->min_history_number = min_history_number;
new_window->max_history_number = max_history_number;
new_window->current_history_number = pos;
new_window->SetCurrentHistoryPos(pos, TRUE, TRUE);
if(return_window)
*return_window=new_window;
return FALSE;
}
// Returns NULL on OOM
uni_char* Window::ComposeLinkInformation(const uni_char* hlink, const uni_char* rel_name)
{
const uni_char *empty = UNI_L("");
uni_char* link = NULL;
if (!hlink)
hlink = empty;
// FIXME(?): The non-configurable DisplayRelativeLink() has been removed
if (rel_name)
{
unsigned int len = uni_strlen(hlink) + uni_strlen(rel_name) + 2;
link = OP_NEWA(uni_char, len);
if (link)
uni_snprintf(link, len, UNI_L("%s#%s"), hlink, rel_name);
}
else
OpStatus::Ignore(UniSetStr_NotEmpty(link, hlink)); // link remains NULL if it fails
return link;
}
OP_STATUS Window::SetProgressText(URL& url, BOOL unused /* = FALSE */)
{
// In case we have a URL that is redirecting to another page, we have to call Access to mark it visited.
// Otherwise the original link won't be marked as visited (since the redirecting url isn't a document)
if (!GetPrivacyMode())
url.Access(TRUE);
return OpStatus::OK;
}
BOOL Window::HandleMessage(UINT message, int id, long user_data)
{
return FALSE;
}
OP_STATUS Window::OpenURL(const char* in_url_str, BOOL check_if_expired, BOOL user_initiated, BOOL reload, BOOL is_hotlist_url, BOOL open_in_background, EnteredByUser entered_by_user, BOOL called_externally)
{
OpString16 tmp_str;
RETURN_IF_ERROR(tmp_str.SetFromUTF8(in_url_str));
return OpenURL(tmp_str.CStr(), check_if_expired, user_initiated, reload, is_hotlist_url,open_in_background,entered_by_user, called_externally);
}
OP_STATUS Window::OpenURL(const uni_char* in_url_str, BOOL check_if_expired, BOOL user_initiated, BOOL reload, BOOL is_hotlist_url, BOOL open_in_background, EnteredByUser entered_by_user, BOOL called_externally, URL_CONTEXT_ID context_id)
{
if (!in_url_str)
return OpStatus::OK;
OpString search_url;
#ifdef AB_ERROR_SEARCH_FORM
//The following text will be used to present back to the user
//in the search field in error pages. More than a few hundred
//chars is already information overload
if(entered_by_user == WasEnteredByUser)
OpStatus::Ignore(m_typed_in_url.Set(in_url_str, 200));
#endif // AB_ERROR_SEARCH_FORM
#ifdef SEARCH_ENGINES
if (uni_isalpha(in_url_str[0]) && uni_isspace(in_url_str[1]) && in_url_str[2])
{
OpString key;
key.Set(in_url_str, 1);
SearchElement* search_element = g_search_manager->GetSearchByKey(key);
if (search_element)
{
OpString search_query;
OpString post_query;
search_query.Set(in_url_str+2);
if (search_element->MakeSearchString(search_url, post_query, search_query) != OpStatus::OK)
search_url.Empty();
}
}
#endif // SEARCH_ENGINES
const uni_char* new_in_url_str=in_url_str;
while (uni_isspace(*new_in_url_str))
new_in_url_str++;
OpString acpUrlStr;
#ifdef SLASHDOT_EASTEREGG
if (uni_strcmp(new_in_url_str, "/.") == 0)
{
RETURN_IF_ERROR(acpUrlStr.Set(UNI_L("http://slashdot.org/")));
}
else
#endif // SLASHDOT_EASTEREGG
{
if (search_url.HasContent())
{
RETURN_IF_ERROR(acpUrlStr.Set(search_url));
}
else
RETURN_IF_ERROR(acpUrlStr.Set(new_in_url_str));
}
#ifdef CORE_BOOKMARKS_SUPPORT
// Nickname ?
if (!uni_strpbrk((const OpChar *) acpUrlStr.CStr(), UNI_L(".:/?\\")))
{
BookmarkAttribute attr;
RETURN_IF_ERROR(attr.SetTextValue(acpUrlStr.CStr()));
BookmarkItem *bookmark = g_bookmark_manager->GetFirstByAttribute(BOOKMARK_SHORTNAME, &attr);
if (bookmark && bookmark->GetFolderType() == FOLDER_NO_FOLDER)
{
RETURN_IF_ERROR(bookmark->GetAttribute(BOOKMARK_URL, &attr));
RETURN_IF_ERROR(attr.GetTextValue(acpUrlStr));
}
}
#endif // CORE_BOOKMARKS_SUPPORT
OpString acpUrlNameResolved;
OP_STATUS r;
BOOL res = FALSE;
TRAP(r,res=g_url_api->ResolveUrlNameL(acpUrlStr, acpUrlNameResolved, entered_by_user == WasEnteredByUser));
RETURN_IF_ERROR(r);
if (!res)
return OpStatus::OK;
if (acpUrlNameResolved.CStr() == NULL)
return OpStatus::OK;
URL url;
#ifdef AB_ERROR_SEARCH_FORM
//set for OpIllegalHost page to have access to the raw text
g_windowManager->SetLastTypedUserText(&m_typed_in_url);
#endif // AB_ERROR_SEARCH_FORM
URL_CONTEXT_ID id = 0;
# ifdef GADGET_SUPPORT
/* Checking for the gadget context id first was seemingly done on purpose here, so i left it
* like that when i moved the search for a suitable context id to GetUrlContextId(), if the
* order is not really important the GADGET_SUPPORT section here can be safely removed
* since this case is covered in GetUrlContextId() */
if (GetGadget())
id = GetGadget()->UrlContextId();
else
# endif // GADGET_SUPPORT
id = (context_id != static_cast<URL_CONTEXT_ID>(-1)) ? context_id : GetUrlContextId(acpUrlNameResolved.CStr());
url = g_url_api->GetURL(acpUrlNameResolved.CStr(), id);
#ifdef SUPPORT_VISUAL_ADBLOCK
// cache the server name so it's faster to do a lookup to check if the content blocker is enabled or not
m_content_block_server_name = url.GetServerName();
if(m_content_block_server_name)
m_content_block_enabled = g_pcnet->GetIntegerPref(PrefsCollectionNetwork::EnableContentBlocker, m_content_block_server_name) != 0;
#endif // SUPPORT_VISUAL_ADBLOCK
if (!url.IsEmpty())
{
URL dummy;
if(is_hotlist_url && (url.Type() == URL_HTTP || url.Type() == URL_HTTPS))
{
OpStringC8 name = url.GetAttribute(URL::KUserName).CStr();
if(name.CStr() == NULL && url.GetAttribute(URL::KPassWord).CStr() != NULL)
name = "";
ServerName *sn = (ServerName *) url.GetAttribute(URL::KServerName, NULL);
if(name.CStr() != NULL && !sn->GetPassUserNameURLsAutomatically(name))
{
RETURN_IF_ERROR(sn->SetPassUserNameURLsAutomatically(name));
}
}
#ifdef REDIRECT_ON_ERROR
//This partially resolved url will be used to redirect the user directly to a search engine
//See PrefsCollectionNetwork::HostNameWebLookupAddress
//The typed url value being set above in this same function, if any,
//was used in the call to g_url_api->GetURL(acpUrlNameResolved.CStr());
//which could have generated an OpIllegalHostPage in case the url was malformed.
//This would present the url in a clearly visible text field to the user
//Now the url is sabed again, this time to be used for the automatic redirect.
//The new url needs to be stored because any username and password info have been removed
//and we cannot automatically upload that information to a 3rd party server
if(entered_by_user == WasEnteredByUser &&
g_pcnet->GetIntegerPref(PrefsCollectionNetwork::EnableHostNameWebLookup))
m_typed_in_url.Set(in_url_str);
#endif // REDIRECT_ON_ERROR
SetFlexRootMaxWidth(g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::FlexRootMaxWidth, url));
r = OpenURL(url, DocumentReferrer(dummy), check_if_expired, reload, -1, user_initiated, open_in_background, entered_by_user, called_externally);
}
#ifdef AB_ERROR_SEARCH_FORM
g_windowManager->SetLastTypedUserText(NULL);
#endif // AB_ERROR_SEARCH_FORM
return r;
}
OP_STATUS Window::OpenURL
(
OpenUrlInNewWindowInfo *info,
BOOL check_if_expired,
BOOL reload,
EnteredByUser entered_by_user,
BOOL called_externally
)
{
return OpenURL(info->new_url,
info->ref_url,
check_if_expired,
reload,
info->opener_sub_win_id,
info->user_initiated,
#if defined(QUICK)
KioskManager::GetInstance()->GetEnabled() && !KioskManager::GetInstance()->GetKioskWindows() ? FALSE :
#endif
info->open_in_background_window,
entered_by_user,
called_externally);
}
OP_STATUS Window::OpenURL(URL& url, DocumentReferrer ref_url, BOOL check_if_expired, BOOL reload, short sub_win_id,
BOOL user_initiated, BOOL open_in_background, EnteredByUser entered_by_user, BOOL called_externally)
{
DocumentManager* doc_man = GetDocManagerById(sub_win_id);
if (doc_man)
{
doc_man->ResetRequestThreadInfo();
#if defined REDIRECT_ON_ERROR || defined AB_ERROR_SEARCH_FORM
if(entered_by_user != WasEnteredByUser)
{
//it's better to wipe from memory because one never knows if
//some bug could criple in and store an url with username+password here
m_typed_in_url.Wipe();
m_typed_in_url.Empty();
}
#endif // defined REDIRECT_ON_ERROR || defined AB_ERROR_SEARCH_FORM
#ifdef _PRINT_SUPPORT_
if (print_mode)
StopPrinting();
#endif // _PRINT_SUPPORT_
DocumentManager::OpenURLOptions options;
options.user_initiated = user_initiated;
options.entered_by_user = entered_by_user;
options.called_externally = called_externally;
doc_man->OpenURL(url, DocumentReferrer(ref_url), check_if_expired, reload, options);
}
return OpStatus::OK;
}
void Window::HandleDocumentProgress(long bytes_read)
{
URL url = doc_manager->GetCurrentURL();
SetDocProgressCount(url.ContentLoaded());
m_loading_information.totalBytes = url.GetContentSize();
m_loading_information.loadedBytes = GetProgressCount();
m_loading_information.totalBytesRootDocument = m_loading_information.totalBytes;
m_loading_information.loadedBytesRootDocument = GetDocProgressCount();
FramesDocument* doc = GetCurrentDoc();
if (doc)
{
if (doc_manager->GetLoadStatus() == NOT_LOADING ||
doc_manager->GetLoadStatus() == DOC_CREATED)
{
DocLoadingInfo info;
doc->GetDocLoadingInfo(info);
m_loading_information.loadedImageCount = info.images.loaded_count;
m_loading_information.totalImageCount = info.images.total_count;
m_loading_information.loadedBytes = info.loaded_size;
m_loading_information.totalBytes = info.total_size;
#ifdef WEB_TURBO_MODE
m_loading_information.turboTransferredBytes = info.turbo_transferred_bytes + info.images.turbo_transferred_bytes;
m_loading_information.turboOriginalTransferredBytes = info.turbo_original_transferred_bytes + info.images.turbo_original_transferred_bytes;
#endif // WEB_TURBO_MODE
}
}
m_loading_information.loadingMessage = GetProgressMessage();
m_loading_information.isUploading = FALSE;
m_windowCommander->GetLoadingListener()->OnLoadingProgress(m_windowCommander, &m_loading_information);
}
void Window::HandleDataProgress(long bytes, BOOL upload_progress, const uni_char* extrainfo, MessageHandler *mh, URL *url)
{
// Since the same counter is used for both uploading and downloading we need to reset it
// when the direction changes
if (GetProgressState() == UPLOADING_FINISHED && !upload_progress)
SetProgressCount(0);
SetProgressCount(progress_count+bytes);
m_loading_information.loadedBytes = progress_count;
m_loading_information.isUploading = upload_progress;
// We need this to avoid calling OnLoadingProgress() before OnStartUploading().
// Both OnStartUploading() and OnLoadingProgress() will be called in SetProgressState().
if ( !upload_progress || phase_uploading )
m_windowCommander->GetLoadingListener()->OnLoadingProgress(m_windowCommander, &m_loading_information);
SetProgressState(upload_progress ? UPLOADING_FILES : FETCHING_DOCUMENT, extrainfo, mh, bytes, url);
}
void Window::UpdateLoadingInformation(int loaded_inlines, int total_inlines)
{
m_loading_information.loadedImageCount = loaded_inlines;
m_loading_information.totalImageCount = total_inlines;
m_loading_information.loadedBytesRootDocument = GetProgressCount();
m_loading_information.totalBytesRootDocument = DocManager()->GetCurrentURL().GetContentSize();
FramesDocument* doc = GetCurrentDoc();
if (doc && (doc_manager->GetLoadStatus() == NOT_LOADING || doc_manager->GetLoadStatus() == DOC_CREATED))
{
DocLoadingInfo info;
doc->GetDocLoadingInfo(info);
m_loading_information.loadedImageCount = info.images.loaded_count;
m_loading_information.totalImageCount = info.images.total_count;
m_loading_information.loadedBytes = info.loaded_size;
m_loading_information.totalBytes = info.total_size;
#ifdef WEB_TURBO_MODE
m_loading_information.turboTransferredBytes = info.turbo_transferred_bytes + info.images.turbo_transferred_bytes;
m_loading_information.turboOriginalTransferredBytes = info.turbo_original_transferred_bytes + info.images.turbo_original_transferred_bytes;
#endif // WEB_TURBO_MODE
}
m_loading_information.isUploading = FALSE;
m_windowCommander->GetLoadingListener()->OnLoadingProgress(m_windowCommander, &m_loading_information);
}
void Window::LoadPendingUrl(URL_ID url_id, int sub_win_id, BOOL user_initiated)
{
if (sub_win_id == -2)
{
// "LoadPendingURL with sub_win_id == -2 *cannot* work"
BOOL3 open_in_new_window = MAYBE;
BOOL3 open_in_background = MAYBE;
g_windowManager->GetAWindow(TRUE, open_in_new_window, open_in_background)->LoadPendingUrl(url_id, -1, user_initiated);
return;
}
DocumentManager* doc_man = GetDocManagerById(sub_win_id);
if (doc_man)
doc_man->LoadPendingUrl(url_id, user_initiated);
}
BOOL Window::HandleLoadingFailed(Str::LocaleString msg_id, URL url)
{
OpString url_name;
if (OpStatus::IsMemoryError(url.GetAttribute(URL::KUniName_Username_Password_Hidden_Escaped, url_name, FALSE)))
RaiseCondition(OpStatus::ERR_NO_MEMORY);
else if (m_windowCommander->GetLoadingListener()->OnLoadingFailed(m_windowCommander, msg_id, url_name.CStr()))
/* Event was handled by the listener. */
return TRUE;
return FALSE;
}
#ifndef NO_EXTERNAL_APPLICATIONS
BOOL Window::RunApplication(const OpStringC& application,const OpStringC& filename)
{
RETURN_VALUE_IF_ERROR(Execute(application.CStr(), filename.CStr()), FALSE);
return TRUE;
}
#endif // !NO_EXTERNAL_APPLICATIONS
#ifndef NO_EXTERNAL_APPLICATIONS
BOOL Window::ShellExecute(const uni_char* filename)
{
if (filename && *filename)
g_op_system_info->ExecuteApplication(filename, NULL);
return FALSE;
}
#endif // !NO_EXTERNAL_APPLICATIONS
////////////////////////////////////////////////////
void Window::AskAboutUnknownDoc(URL& url, int sub_win_id)
{
#ifndef WIC_USE_DOWNLOAD_CALLBACK
#ifdef USE_DOWNLOAD_API
TRAPD(err, g_DownloadManager->DelegateL(url, m_windowCommander));
if( OpStatus::IsMemoryError(err) )
RaiseCondition(OpStatus::ERR_NO_MEMORY);
#elif defined(DOCHAND_USE_ONDOWNLOADREQUEST)
OpString suggested_filename;
OpString8 mimetype_str;
if (OpStatus::IsMemoryError(url.GetAttribute(URL::KSuggestedFileName_L, suggested_filename)) ||
OpStatus::IsMemoryError(url.GetAttribute(URL::KMIME_Type, mimetype_str, TRUE)) )
{
RaiseCondition(OpStatus::ERR_NO_MEMORY);
return;
}
char *mimetype = mimetype_str.CStr();
OpFileLength size = url.GetContentSize();
m_windowCommander->GetDocumentListener()->OnDownloadRequest(m_windowCommander, url.GetAttribute(URL::KUniName_Username_Password_Hidden_Escaped).CStr(), suggested_filename.CStr(),
mimetype, size, OpDocumentListener::UNKNOWN);
#elif defined(QUICK)
BOOL no_download_dialog = KioskManager::GetInstance()->GetNoDownload();
if(no_download_dialog || IsThumbnailWindow())
{
url.StopLoading(NULL);
url.Unload();
return;
}
DownloadDialog* dialog = OP_NEW(DownloadDialog, (&url, this));
#ifdef QUICK
dialog->Init(g_application->GetDesktopWindowFromWindow(this), sub_win_id);
#else // QUICK
dialog->Init(g_application->GetDesktopWindowFromWindow(this));
#endif // QUICK
#elif defined(LIBOPERA)
OpString suggested_filename_str;
OpString8 mimetype_str;
if (OpStatus::IsMemoryError(url.GetAttribute(URL::KSuggestedFileName_L, suggested_filename_str, TRUE)) || OpStatus::IsMemoryError(mimetype_str.Set(url.GetAttribute(URL::KMIME_Type))))
{
RaiseCondition(OpStatus::ERR_NO_MEMORY);
return;
}
uni_char *suggested_filename = suggested_filename_str.CStr();
char *mimetype = mimetype_str.CStr();
OpFileLength size = url.GetContentSize();
#ifdef TCP_PAUSE_DOWNLOAD_EXTENSION
url.PauseLoading();
#endif // TCP_PAUSE_DOWNLOAD_EXTENSION
#if !defined GTK_DOWNLOAD_EXTENSION && !defined TCP_PAUSE_DOWNLOAD_EXTENSION
url.StopLoading(NULL);
url.Unload();
#endif // !GTK_DOWNLOAD_EXTENSION && !TCP_PAUSE_DOWNLOAD_EXTENSION
# ifdef _OPL_
// OPL: IMPLEMENTME
# elif defined(SDK) || defined(POWERPARTS)
# ifdef GTK_DOWNLOAD_EXTENSION
url.PauseLoading();
OP_STATUS status = GetWindowCommander()->InitiateTransfer(doc_manager, url, OpTransferItem::ACTION_SAVE, NULL);
if (OpStatus::IsError(status))
{
if (status == OpStatus::ERR_NO_MEMORY)
{
RaiseCondition(status);
}
return;
}
# endif // GTK_DOWNLOAD_EXTENSION
# else // _OPL_
OperaEmbeddedInternal::instance->signalDownloadFile(url.GetUniName(FALSE, PASSWORD_HIDDEN), suggested_filename,
mimetype, size);
# endif // _OPL_
#endif // misc platforms
#endif // !WIC_USE_DOWNLOAD_CALLBACK
}
int Window::SetNewHistoryNumber()
{
doc_manager->RemoveFromHistory(current_history_number + 1);
current_history_number++;
max_history_number = current_history_number;
if (!history_cleanup_message_sent)
{
msg_handler->PostMessage(MSG_HISTORY_CLEANUP, 0, 0);
history_cleanup_message_sent = TRUE;
}
return current_history_number;
}
void Window::SetLastHistoryPos(int pos)
{
if (pos < min_history_number || pos > max_history_number)
return;
current_history_number = pos;
max_history_number = current_history_number;
doc_manager->RemoveFromHistory(current_history_number + 1);
FramesDocument* doc = GetCurrentDoc();
if (doc)
doc->RemoveFromHistory(current_history_number + 1);
}
void Window::SetCurrentHistoryPos(int pos, BOOL update_doc_man, BOOL is_user_initiated)
{
if (pos < min_history_number)
pos = min_history_number;
else if (pos > max_history_number)
pos = max_history_number;
current_history_number = pos;
if (update_doc_man)
{
doc_manager->SetCurrentHistoryPos(pos, FALSE, is_user_initiated);
UpdateWindowIfLayoutChanged();
}
}
int Window::GetNextDocListElmId()
{
return m_next_doclistelm_id++;
}
OP_STATUS Window::SetHistoryUserData(int history_ID, OpHistoryUserData* user_data)
{
return doc_manager->SetHistoryUserData(history_ID, user_data);
}
OP_STATUS Window::GetHistoryUserData(int history_ID, OpHistoryUserData** user_data) const
{
return doc_manager->GetHistoryUserData(history_ID, user_data);
}
void Window::SetMaxHistory(int len)
{
int remove_len = GetHistoryLen() - len - 1;
if (remove_len > 0)
{
if (current_history_number - min_history_number > remove_len)
min_history_number += remove_len;
else
min_history_number = current_history_number;
doc_manager->RemoveUptoHistory(min_history_number);
}
remove_len = GetHistoryLen() - len - 1;
if (remove_len > 0)
{
if (max_history_number - current_history_number > remove_len)
max_history_number += remove_len;
else
max_history_number = current_history_number;
doc_manager->RemoveFromHistory(max_history_number+1);
}
}
#ifdef DOCHAND_HISTORY_MANIPULATION_SUPPORT
void Window::RemoveElementFromHistory(int pos)
{
if((pos < min_history_number) || (pos > max_history_number))
return;
if(pos == current_history_number)
{
if(current_history_number > min_history_number)
SetCurrentHistoryPos(current_history_number - 1, TRUE, FALSE);
else if(current_history_number < max_history_number)
SetCurrentHistoryPos(current_history_number + 1, TRUE, FALSE);
}
if(pos == max_history_number)
{
doc_manager->RemoveElementFromHistory(max_history_number--, TRUE); // Unlink from history list
//doc_manager->RemoveFromHistory(max_history_number--, TRUE); // Unlink from history list
if(min_history_number > max_history_number)
{
min_history_number = 1;
max_history_number = current_history_number = 0;
}
}
else if(pos == min_history_number)
{
doc_manager->RemoveUptoHistory(++min_history_number, TRUE); // Unlink from history list
}
else
doc_manager->RemoveElementFromHistory(pos);
CheckHistory();
}
void Window::InsertElementInHistory(int pos, DocListElm * elm)
{
if (pos < min_history_number)
pos = min_history_number;
else if (pos > (max_history_number+1))
pos = max_history_number+1;
doc_manager->InsertElementInHistory(pos, elm);
max_history_number += 1;
if(pos <= current_history_number)
SetCurrentHistoryPos(current_history_number + 1, TRUE, FALSE);
CheckHistory();
}
void Window::RemoveAllElementsFromHistory(BOOL unlink)
{
int pos = min_history_number;
while (pos <= max_history_number)
doc_manager->RemoveElementFromHistory(pos++, unlink);
CheckHistory();
}
#endif // DOCHAND_HISTORY_MANIPULATION_SUPPORT
void Window::RemoveAllElementsExceptCurrent()
{
doc_manager->RemoveFromHistory(current_history_number+1);
doc_manager->RemoveUptoHistory(current_history_number);
CheckHistory();
}
// Handles OOM locally by setting the flag on the window.
void Window::GetClickedURL(URL url, DocumentReferrer& ref_url, short sub_win_id, BOOL user_initiated, BOOL open_in_background_window)
{
DocumentManager* doc_man = GetDocManagerById(sub_win_id);
if (!doc_man)
return;
URL current_url = doc_man->GetCurrentURL();
if (sub_win_id == -2 &&
(!g_pcdoc->GetIntegerPref(PrefsCollectionDoc::IgnoreTarget) &&
!g_pcdoc->GetIntegerPref(PrefsCollectionDoc::SingleWindowBrowsing)))
{
BOOL3 open_in_new_window = MAYBE;
BOOL3 open_in_background = open_in_background_window?YES:MAYBE;
Window* window = g_windowManager->GetAWindow(TRUE, open_in_new_window, open_in_background);
if (window)
{
if (window->OpenURL(url, ref_url, TRUE, FALSE, -1, user_initiated, open_in_background==YES) == OpStatus::ERR_NO_MEMORY)
window->RaiseCondition( OpStatus::ERR_NO_MEMORY );
}
}
else
{
doc_man->StopLoading(FALSE, FALSE, FALSE);
if (OpenURL(url, ref_url, !(url==current_url), FALSE, sub_win_id, user_initiated, open_in_background_window) == OpStatus::ERR_NO_MEMORY)
g_memory_manager->RaiseCondition( OpStatus::ERR_NO_MEMORY );
}
}
#ifdef LINK_SUPPORT
const LinkElement*
Window::GetLinkList() const
{
FramesDocument* frames_doc = doc_manager->GetCurrentDoc();
if (frames_doc)
{
HLDocProfile* profile = frames_doc->GetHLDocProfile();
if (profile)
return profile->GetLinkList();
}
return NULL;
}
const LinkElementDatabase*
Window::GetLinkDatabase() const
{
if (FramesDocument* frames_doc = doc_manager->GetCurrentDoc())
{
if (HLDocProfile* profile = frames_doc->GetHLDocProfile())
return profile->GetLinkDatabase();
}
return NULL;
}
#endif // LINK_SUPPORT
/** Return the CSSCollection object for the current document. */
CSSCollection* Window::GetCSSCollection() const
{
FramesDocument* frames_doc = doc_manager->GetCurrentVisibleDoc();
if (frames_doc)
{
HLDocProfile* profile = frames_doc->GetHLDocProfile();
if (profile)
return profile->GetCSSCollection();
}
return NULL;
}
URL Window::GetCurrentShownURL()
{
return doc_manager->GetCurrentDocURL();
}
URL Window::GetCurrentLoadingURL()
{
switch (doc_manager->GetLoadStatus())
{
case NOT_LOADING:
case DOC_CREATED:
case WAIT_MULTIPART_RELOAD:
return doc_manager->GetCurrentDocURL();
default:
URL url = doc_manager->GetCurrentURL();
URL target = url.GetAttribute(URL::KMovedToURL, TRUE);
if (!target.IsEmpty())
return target;
else
return url;
}
}
URL Window::GetCurrentURL()
{
return doc_manager->GetCurrentDocURL();
}
URL_CONTEXT_ID Window::GetMainUrlContextId(URL_CONTEXT_ID base_id)
{
// If you edit this, please see Window::GetUrlContextId()
#if defined WEB_TURBO_MODE || defined APPLICATION_CACHE_SUPPORT
if (base_id != 0 && (
# ifdef WEB_TURBO_MODE
base_id == g_windowManager->GetTurboModeContextId() ||
# endif // WEB_TURBO_MODE
# ifdef APPLICATION_CACHE_SUPPORT
g_application_cache_manager->GetCacheFromContextId(base_id) != NULL ||
# endif // APPLICATION_CACHE_SUPPORT
FALSE))
{
#ifdef GADGET_SUPPORT
if (GetGadget())
return GetGadget()->UrlContextId();
else
#endif // GADGET_SUPPORT
if (GetPrivacyMode())
return g_windowManager->GetPrivacyModeContextId();
else
return 0;
}
else
#endif // defined WEB_TURBO_MODE || defined APPLICATION_CACHE_SUPPORT
return base_id;
}
URL_CONTEXT_ID Window::GetUrlContextId(const uni_char *url)
{
// If you edit this, please see Window::GetMainUrlContextId()
URL_CONTEXT_ID id = 0;
#ifdef GADGET_SUPPORT
if (GetGadget())
id = GetGadget()->UrlContextId();
else
#endif // GADGET_SUPPORT
if (GetPrivacyMode())
{
id = g_windowManager->GetPrivacyModeContextId();
OP_ASSERT(id);
}
#ifdef WEB_TURBO_MODE
else if (GetTurboMode())
{
id = g_windowManager->GetTurboModeContextId();
OP_ASSERT(id);
}
#endif // WEB_TURBO_MODE
#ifdef APPLICATION_CACHE_SUPPORT
else if (url && g_application_cache_manager)
{
URL_CONTEXT_ID appcache_context_id = g_application_cache_manager->GetMostAppropriateCache(url);
if (appcache_context_id)
id = appcache_context_id;
}
#endif // APPLICATION_CACHE_SUPPORT
return id;
}
DocumentManager* Window::GetDocManagerById(int sub_win_id)
{
if (sub_win_id < 0)
return doc_manager;
else
return doc_manager->GetDocManagerById(sub_win_id);
}
void Window::CheckHistory()
{
check_history = FALSE;
int minhist = current_history_number;
int maxhist = current_history_number;
doc_manager->CheckHistory(0, minhist, maxhist);
if (minhist > min_history_number)
min_history_number = minhist;
if (maxhist < max_history_number)
max_history_number = maxhist;
}
void Window::UpdateWindowIfLayoutChanged()
{
// The session handling in desktop can change
// the history position on an empty doc_manager. Don't ask.
if (!doc_manager->GetCurrentDoc())
return;
LayoutMode doc_layout_mode = doc_manager->GetCurrentDoc()->GetLayoutMode();
LayoutMode& win_layout_mode = layout_mode;
BOOL doc_era_mode = doc_manager->GetCurrentDoc()->GetERA_Mode();
BOOL& win_era_mode = era_mode;
if (!win_era_mode && (doc_layout_mode != win_layout_mode ||
doc_manager->GetCurrentDoc()->GetMediaHandheldResponded()) ||
win_era_mode && !doc_era_mode)
{
// the ssr status of window and doc were not in sync
UpdateWindow();
}
}
void Window::UnlockPaintLock()
{
DocumentTreeIterator iterator(this);
iterator.SetIncludeThis();
while (iterator.Next())
iterator.GetDocumentManager()->GetVisualDevice()->StopLoading();
}
void Window::SetHistoryNext(BOOL /* unused = FALSE */)
{
if (HasFeature(WIN_FEATURE_NAVIGABLE))
{
// Assuming user initiated (or we'll have to tweak this code). Allow a new download dialog after the user has moved in history
SetHasShownUnsolicitedDownloadDialog(FALSE);
if (current_history_number < max_history_number)
doc_manager->SetCurrentHistoryPos(++current_history_number, FALSE, TRUE);
UpdateWindowIfLayoutChanged();
}
}
void Window::SetHistoryPrev(BOOL /* unused = FALSE */)
{
if (HasFeature(WIN_FEATURE_NAVIGABLE))
{
if (current_history_number > min_history_number)
{
// Assuming user initiated (or we'll have to tweak this code). Allow a new download dialog after the user has moved in history
SetHasShownUnsolicitedDownloadDialog(FALSE);
FramesDocument* doc = GetCurrentDoc();
URL url;
if (doc)
{
url = GetCurrentDoc()->GetURL();
}
doc_manager->SetCurrentHistoryPos(--current_history_number, FALSE, TRUE);
if (doc)
{
UpdateVisitedLinks(url);
UpdateWindowIfLayoutChanged();
}
}
}
}
BOOL Window::IsLoading() const
{
return loading && !doc_manager->IsCurrentDocLoaded();
}
void Window::DisplayLinkInformation(const URL &link_url, ST_MESSAGETYPE msType/* = ST_ASTRING*/, const uni_char *title/* = NULL*/)
{
OpString link_str;
OpStatus::Ignore(link_url.GetAttribute(URL::KUniName_With_Fragment_Username_Password_Hidden_Escaped, link_str));
DisplayLinkInformation(link_str.CStr(), msType, title);
}
void Window::DisplayLinkInformation(const uni_char* link, ST_MESSAGETYPE mt/*=ST_ASTRING*/, const uni_char *title/*=NULL*/)
{
if (!link)
link = UNI_L("");
if (*link || (title && *title))
{
m_windowCommander->GetDocumentListener()->OnHover(m_windowCommander, link, title, FALSE);
is_something_hovered = TRUE;
}
else
{
if (is_something_hovered)
{
m_windowCommander->GetDocumentListener()->OnNoHover(m_windowCommander);
is_something_hovered = FALSE;
}
m_windowCommander->GetDocumentListener()->OnStatusText(m_windowCommander, current_message ? current_message : current_default_message);
}
g_windowManager->SetPopupMessage(link, FALSE, mt);
}
void Window::DisplayLinkInformation(const uni_char* hlink, const uni_char* rel_name, ST_MESSAGETYPE msType/* = ST_ASTRING*/, const uni_char *title/* = NULL*/)
{
uni_char* full_tag = Window::ComposeLinkInformation(hlink, rel_name);
DisplayLinkInformation(full_tag, msType, title);
OP_DELETEA(full_tag);
}
#ifdef _PRINT_SUPPORT_
OP_STATUS Window::SetFramesPrintType(DM_PrintType fptype, BOOL update)
{
FramesDocument* doc = GetCurrentDoc();
if (doc && (!doc->IsFrameDoc() || (fptype == PRINT_ACTIVE_FRAME && !doc->GetActiveDocManager())))
fptype = PRINT_ALL_FRAMES;
if (frames_print_type != fptype)
{
frames_print_type = fptype;
if (update)
return doc_manager->UpdatePrintPreview();
}
return OpStatus::OK;
}
BOOL Window::TogglePrintMode(BOOL preview)
{
PrintDevice* tmpPrintDev = NULL;
if (preview)
preview_mode = !preview_mode;
else
print_mode = !print_mode;
if (preview_mode || print_mode)
ecmascript_paused |= PAUSED_PRINTING;
else
{
ecmascript_paused &= ~PAUSED_PRINTING;
ResumeEcmaScriptIfNotPaused();
}
OP_STATUS result = OpStatus::OK;
if (!preview_printer_info && !print_mode && preview_mode)
{
preview_printer_info = OP_NEW(PrinterInfo, ());
if (!preview_printer_info)
result = OpStatus::ERR_NO_MEMORY;
else
#ifdef PRINT_SELECTION_USING_DUMMY_WINDOW
result = preview_printer_info->GetPrintDevice(tmpPrintDev, preview, FALSE, this, NULL); //if this fails, we don't have any printer device to work towards
#else // !PRINT_SELECTION_USING_DUMMY_WINDOW
result = preview_printer_info->GetPrintDevice(tmpPrintDev, preview, FALSE, this); //if this fails, we don't have any printer device to work towards
#endif // !PRINT_SELECTION_USING_DUMMY_WINDOW
}
else
if (!preview)
#ifdef PRINT_SELECTION_USING_DUMMY_WINDOW
result = printer_info->GetPrintDevice(tmpPrintDev, preview, FALSE, this, NULL);
#else // !PRINT_SELECTION_USING_DUMMY_WINDOW
result = printer_info->GetPrintDevice(tmpPrintDev, preview, FALSE, this);
#endif
if (result == OpStatus::ERR)
{
/* We could for example not get a connection to the printer.
We're not necessarily out of memory, though. */
if (preview)
preview_mode = !preview_mode;
else
print_mode = !print_mode;
}
else
if (result == OpStatus::ERR_NO_MEMORY ||
(result = doc_manager->SetPrintMode(print_mode || preview_mode, NULL, preview)) != OpBoolean::IS_TRUE)
{
// undo
if (preview)
preview_mode = !preview_mode;
else
print_mode = !print_mode;
if (result == OpStatus::ERR_NO_MEMORY)
{
RaiseCondition(result);
if (preview)
{
OP_DELETE(preview_printer_info);
preview_printer_info = NULL;
}
else
{
OP_DELETE(printer_info);
printer_info = NULL;
}
vis_device->Show(NULL);
vis_device->SetFocus(FOCUS_REASON_OTHER);
return FALSE;
}
}
#ifdef KEYBOARD_SELECTION_SUPPORT
if (preview_mode || print_mode)
{
DocumentTreeIterator it(this);
while (it.Next())
it.GetFramesDocument()->SetKeyboardSelectable(FALSE);
}
#endif // KEYBOARD_SELECTION_SUPPORT
if (printer_info && !print_mode)
{
OP_DELETE(printer_info);
printer_info = NULL;
}
if (preview_printer_info && !preview_mode)
{
OP_DELETE(preview_printer_info);
preview_printer_info = NULL;
}
if (preview)
{
OpDocumentListener::PrintPreviewMode mode;
if (preview_mode)
mode = OpDocumentListener::PRINT_PREVIEW_ON;
else
mode = OpDocumentListener::PRINT_PREVIEW_OFF;
m_windowCommander->GetDocumentListener()->OnPrintPreviewModeChanged(m_windowCommander, mode);
}
return tmpPrintDev ? TRUE : FALSE;
}
BOOL Window::StartPrinting(PrinterInfo* pinfo, int from_page, BOOL selected_only)
{
if (!print_mode)
LockWindow();
//rg this variable is uses to save the state of the global flag that shows if we are in full screen.
// we have to temporarily reset the flag (not the fullscreen mode state, though) to make documents print even
// though we are in fullscreen mode. I'm not saying it's beautiful -- m_fullscreen_state is mis-used!
m_previous_fullscreen_state = m_fullscreen_state;
m_fullscreen_state = OpWindowCommander::FULLSCREEN_NONE;
/* if (GetPreviewMode())
{
// check printer_info
}
else */
{
printer_info = pinfo;
OP_NEW_DBG("Window::StartPrinting", "async_print");
OP_DBG(("SetPrinting(TRUE)"));
SetPrinting(TRUE);
TogglePrintMode(FALSE); // Will delete printer_info/pinfo if failing
if (!printer_info)
{
// TogglePrintMode failed & printer_info invalid, better quit now...
StopPrinting();
return FALSE;
}
}
OP_ASSERT(printer_info == pinfo);
print_mode = TRUE;
#ifndef _MACINTOSH_
printer_info->next_page = from_page;
#endif
printer_info->print_selected_only = selected_only;
FramesDocument* doc = doc_manager->GetPrintDoc();
if (!doc)
{
StopPrinting();
OP_ASSERT(!printer_info);
return FALSE;
}
PrintDevice* pd = printer_info->GetPrintDevice();
pd->StartOutput();
return TRUE;
}
void Window::PrintNextPage(PrinterInfo* pinfo)
{
PrintDevice* pd = pinfo->GetPrintDevice();
OP_STATUS ret_val = doc_manager->PrintPage(pd, pinfo->next_page, pinfo->print_selected_only);
pinfo->next_page++;
if (ret_val != DocStatus::DOC_CANNOT_PRINT &&
ret_val != DocStatus::DOC_PAGE_OUT_OF_RANGE &&
(!pinfo->print_selected_only ||
ret_val != DocStatus::DOC_PRINTED) &&
pinfo->next_page <= pinfo->last_page &&
// Check if there are more pages left to print before advancing to the next page:
doc_manager->PrintPage(pd, pinfo->next_page, pinfo->print_selected_only, TRUE) == OpStatus::OK)
{
BOOL cont = pd->NewPage();
if (cont)
{
#if defined (GENERIC_PRINTING)
msg_handler->PostDelayedMessage(DOC_PAGE_PRINTED, 0, pinfo->next_page - 1, 100);
#else // !GENERIC_PRINTING
msg_handler->PostMessage(DOC_PAGE_PRINTED, 0, pinfo->next_page - 1);
#endif // !GENERIC_PRINTING
}
else
{
#if defined (GENERIC_PRINTING)
msg_handler->PostDelayedMessage(DOC_PRINTING_ABORTED, 0, 0, 100);
#else // !GENERIC_PRINTING
msg_handler->PostMessage(DOC_PRINTING_ABORTED, 0, 0);
StopPrinting();
#endif // !GENERIC_PRINTING
}
}
else
{
#if defined (GENERIC_PRINTING)
msg_handler->PostDelayedMessage(DOC_PRINTING_FINISHED, 0, 0, 100);
#else // !GENERIC_PRINTING
msg_handler->PostMessage(DOC_PRINTING_FINISHED, 0, 0);
StopPrinting();
#endif // !GENERIC_PRINTING
}
}
void Window::StopPrinting()
{
m_fullscreen_state = m_previous_fullscreen_state;
if (print_mode)
{
OpStatus::Ignore(doc_manager->SetPrintMode(FALSE, NULL, FALSE));
if (!preview_mode)
TogglePrintMode(FALSE);
ecmascript_paused &= ~PAUSED_PRINTING;
ResumeEcmaScriptIfNotPaused();
}
if (!preview_mode)
{
#if defined (GENERIC_PRINTING)
OP_DELETE(printer_info);
#endif // GENERIC_PRINTING
printer_info = NULL;
}
if (print_mode)
UnlockWindow();
print_mode = FALSE;
}
#endif // _PRINT_SUPPORT_
void Window::GenericMailToAction(const URL& url, BOOL called_externally, BOOL mailto_from_form, const OpStringC8& servername)
{
m_windowCommander->GetDocumentListener()->OnMailTo(m_windowCommander, url.GetAttribute(URL::KName_With_Fragment_Escaped, URL::KNoRedirect), called_externally, mailto_from_form, servername);
if (doc_manager->GetCurrentURL().IsEmpty())
Close();
}
void Window::ToggleImageState()
{
BOOL load_images = LoadImages();
BOOL show_images = ShowImages();
if (show_images)
if (load_images)
SetImagesSetting(FIGS_OFF);
else
SetImagesSetting(FIGS_ON);
else
SetImagesSetting(FIGS_SHOW);
}
#ifdef _AUTO_WIN_RELOAD_SUPPORT_
// ___________________________________________________________________________
//
// AutoWinReloadParam
// ___________________________________________________________________________
AutoWinReloadParam::AutoWinReloadParam(Window* win)
: m_fEnabled(FALSE),
m_secUserSetting(0),
m_secRemaining(0),
m_fOnlyIfExpired(FALSE),
m_timer(NULL),
m_win(win)
{
if (g_pcdoc)
m_secUserSetting = g_pcdoc->GetIntegerPref(PrefsCollectionDoc::LastUsedAutoWindowReloadTimeout);
if (m_secUserSetting<=0)
m_secUserSetting = 5;
}
AutoWinReloadParam::~AutoWinReloadParam()
{
OP_DELETE(m_timer);
}
// ----------------------------------------------------------------------------
void AutoWinReloadParam::Enable( BOOL fEnable)
{
m_fEnabled = fEnable;
if (fEnable)
{
if (!m_timer)
{
OP_STATUS status = OpStatus::OK;
m_timer = OP_NEW(OpTimer, ());
if (!m_timer)
status = OpStatus::ERR_NO_MEMORY;
if (OpStatus::IsError(status))
{
OP_ASSERT(FALSE);
// Now the page won't reload automatically
g_memory_manager->RaiseCondition(status);//FIXME:OOM At least we can
//tell the memory manager
m_timer = NULL;
}
else
m_timer->SetTimerListener(this);
}
if (m_timer)
m_timer->Start(1000); // Every second. This is not optimal
// but is the same as it was when
// this code piggy backed on the
// comm cleaner.
m_secRemaining = m_secUserSetting;
m_win->DocManager()->CancelRefresh();
}
else if (m_timer)
{
m_timer->Stop();
// document refresh has been disabeled as long as user defined reload is
// active, but now we have to activate refresh again (in all sub documents)
DocumentTreeIterator iter(m_win);
iter.SetIncludeThis();
while (iter.Next())
iter.GetFramesDocument()->CheckRefresh();
}
}
void AutoWinReloadParam::Toggle( )
{
Enable(!m_fEnabled);
}
void AutoWinReloadParam::SetSecUserSetting ( int secUserSetting)
{
SetParams( m_fEnabled, secUserSetting, m_fOnlyIfExpired, TRUE);
}
void AutoWinReloadParam::SetParams( BOOL fEnable, int secUserSetting, BOOL fOnlyIfExpired, BOOL fUpdatePrefsManager)
{
m_secUserSetting = secUserSetting;
if (m_secUserSetting<=0)
m_secUserSetting = 1;
m_fOnlyIfExpired = fOnlyIfExpired;
Enable( fEnable);
if (fUpdatePrefsManager)
{
TRAPD(err, g_pcdoc->WriteIntegerL(PrefsCollectionDoc::LastUsedAutoWindowReloadTimeout, m_secUserSetting));
}
}
BOOL AutoWinReloadParam::OnSecTimer()
{
BOOL fReload = FALSE;
if (m_fEnabled)
{
if (m_secUserSetting > 0)
{
--m_secRemaining;
OP_ASSERT(m_secRemaining >= 0);
if (m_secRemaining <= 0)
{
m_secRemaining = m_secUserSetting;
fReload = TRUE;
}
}
}
return fReload;
}
/* virtual */
void AutoWinReloadParam::OnTimeOut(OpTimer* timer)
{
OP_ASSERT(timer);
OP_ASSERT(timer == m_timer);
if (m_fEnabled)
{
//
// Auto user reload ?
//
DocumentManager *doc_manager = m_win->DocManager();
if (doc_manager->GetLoadStatus() == NOT_LOADING
&& OnSecTimer())
{
// DEBUG_Beep();
doc_manager->Reload(NotEnteredByUser, GetOptOnlyIfExpired(), TRUE, TRUE);
}
m_timer->Start(1000); // Every second. Not optimal. See code in Enable()
}
}
#endif // _AUTO_WIN_RELOAD_SUPPORT_
FramesDocument* Window::GetActiveFrameDoc()
{
FramesDocument* activeDoc = NULL;
FramesDocument* currentDoc = GetCurrentDoc();
if (currentDoc)
{
// The active frame document can always be found through the root
// document (GetCurrentDoc) because all frame activations are done
// directly on that document.
DocumentManager* activeDocMan = currentDoc->GetActiveDocManager();
if (!activeDocMan)
activeDocMan = DocManager();
activeDoc = activeDocMan->GetCurrentDoc();
}
return activeDoc;
}
OP_STATUS Window::SetLastUserName(const char *_name)
{
return SetStr(lastUserName, _name);
}
OP_STATUS Window::SetLastProxyUserName(const char *_name)
{
return SetStr(lastProxyUserName, _name);
}
OP_STATUS Window::SetHomePage(const OpStringC& url)
{
return homePage.Set(url);
}
void Window::SetAlwaysLoadFromCache(BOOL from_cache)
{
always_load_from_cache = from_cache;
}
#ifndef HAS_NO_SEARCHTEXT
BOOL Window::SearchText(const uni_char* key, BOOL forward, BOOL matchcase, BOOL word, BOOL next, BOOL wrap, BOOL only_links)
{
if( !key )
{
return FALSE;
}
FramesDocument* doc = doc_manager->GetCurrentVisibleDoc();
if (doc && doc->IsFrameDoc())
doc = doc->GetActiveSubDoc();
if (!doc)
return FALSE;
int left_x, right_x;
long top_y, bottom_y;
OP_BOOLEAN result = doc->SearchText(key, uni_strlen(key), forward, matchcase, word, next, wrap,
left_x, top_y, right_x, bottom_y, only_links);
if (result == OpStatus::ERR_NO_MEMORY)
RaiseCondition(result);
else if (result == OpBoolean::IS_TRUE)
{
doc->RequestScrollIntoView(
OpRect(left_x, top_y, right_x - left_x + 1, bottom_y - top_y + 1),
SCROLL_ALIGN_CENTER, FALSE, VIEWPORT_CHANGE_REASON_FIND_IN_PAGE);
return TRUE;
}
return FALSE;
}
# ifdef SEARCH_MATCHES_ALL
void
Window::ResetSearch()
{
if (m_search_data)
{
m_search_data->SetIsNewSearch(TRUE);
m_search_data->SetMatchingDoc(NULL);
}
}
BOOL
Window::HighlightNextMatch(const uni_char* key,
BOOL match_case, BOOL match_words,
BOOL links_only, BOOL forward, BOOL wrap,
BOOL &wrapped, OpRect& rect)
{
wrapped = FALSE;
FramesDocument* doc = doc_manager->GetCurrentVisibleDoc();
if (!doc)
return FALSE;
if (!m_search_data)
{
m_search_data = OP_NEW(SearchData, (match_case, match_words, links_only, forward, wrap));
if (!m_search_data || OpStatus::IsMemoryError(m_search_data->SetSearchText(key)))
return FALSE;
}
else
{
m_search_data->SetMatchCase(match_case);
m_search_data->SetMatchWords(match_words);
m_search_data->SetLinksOnly(links_only);
m_search_data->SetForward(forward);
m_search_data->SetWrap(wrap);
m_search_data->SetSearchText(key);
}
SetState(BUSY);
OP_BOOLEAN found = doc->HighlightNextMatch(m_search_data, rect);
if (wrap && m_search_data->GetMatchingDoc() == NULL && !m_search_data->IsNewSearch())
{
found = doc->HighlightNextMatch(m_search_data, rect);
wrapped = TRUE;
}
if (found == OpBoolean::IS_TRUE)
{
if (!doc->IsTopDocument())
{
FramesDocElm* frame = doc->GetDocManager() ? doc->GetDocManager()->GetFrame() : NULL;
if (frame && doc->GetVisualDevice())
{
rect.x += frame->GetAbsX() - doc->GetVisualDevice()->GetRenderingViewX();
rect.y += frame->GetAbsY() - doc->GetVisualDevice()->GetRenderingViewY();
}
}
}
SetState(NOT_BUSY);
m_search_data->SetIsNewSearch(FALSE);
return m_search_data->GetMatchingDoc() != NULL;
}
void Window::EndSearch(BOOL activate_current_match, int modifiers)
{
if (activate_current_match && m_search_data)
{
if (FramesDocument *match_doc = m_search_data->GetMatchingDoc())
{
HTML_Document *html_doc = match_doc->GetHtmlDocument();
if (html_doc)
html_doc->ActivateElement(html_doc->GetNavigationElement(), modifiers);
}
}
}
# endif // SEARCH_MATCHES_ALL
#endif // !HAS_NO_SEARCHTEXT
#ifdef ABSTRACT_CERTIFICATES
const OpCertificate *Window::GetCertificate()
{
return static_cast <const OpCertificate *> (doc_manager->GetCurrentURL().GetAttribute(URL::KRequestedCertificate, NULL));
}
#endif // ABSTRACT_CERTIFICATES
void Window::Activate( BOOL fActivate/*=TRUE*/)
{
}
void Window::GotoHistoryPos()
{
if (current_history_number < max_history_number && current_history_number >= 0)
SetCurrentHistoryPos(current_history_number, TRUE, FALSE);
else
SetCurrentHistoryPos(max_history_number, TRUE, FALSE);
}
/** Flushes pending drawoperations so that things wouldn't lag behind, if we do something agressive. */
void Window::Sync()
{
VisualDev()->view->Sync();
}
void Window::SetWindowSize(int wWin, int hWin)
{
m_windowCommander->GetDocumentListener()->OnOuterSizeRequest(m_windowCommander, wWin, hWin);
}
void Window::SetWindowPos(int xWin, int yWin)
{
m_windowCommander->GetDocumentListener()->OnMoveRequest(m_windowCommander, xWin, yWin);
}
void Window::GetWindowSize(int& wWin, int& hWin)
{
m_windowCommander->GetDocumentListener()->OnGetOuterSize(m_windowCommander, (UINT32*) &wWin, (UINT32*) &hWin);
}
void Window::GetWindowPos(int& xWin, int& yWin)
{
m_windowCommander->GetDocumentListener()->OnGetPosition(m_windowCommander, &xWin, &yWin);
}
// Set the size of the client area (space available for doc content)
void Window::SetClientSize ( int cx, int cy)
{
m_windowCommander->GetDocumentListener()->OnInnerSizeRequest(m_windowCommander, cx, cy);
}
void Window::GetClientSize(int &cx, int &cy)
{
UINT32 tmpw=0, tmph=0;
m_windowCommander->GetDocumentListener()->OnGetInnerSize(m_windowCommander, &tmpw, &tmph);
cx = tmpw;
cy = tmph;
}
void Window::GetCSSViewportSize(unsigned int& viewport_width, unsigned int& viewport_height)
{
UINT32 tmpw = 0;
UINT32 tmph = 0;
m_windowCommander->GetDocumentListener()->OnGetInnerSize(m_windowCommander, &tmpw, &tmph);
if (GetTrueZoom())
{
viewport_width = VisualDev()->LayoutScaleToDoc(tmpw);
viewport_height = VisualDev()->LayoutScaleToDoc(tmph);
}
else
{
viewport_width = VisualDev()->ScaleToDoc(tmpw);
viewport_height = VisualDev()->ScaleToDoc(tmph);
}
}
void Window::HandleNewWindowSize(unsigned int width, unsigned int height)
{
VisualDevice* normal_vis_dev = VisualDev();
FramesDocument* doc;
#ifdef _PRINT_SUPPORT_
VisualDevice* print_preview_vis_dev = NULL;
if (GetPreviewMode())
{
print_preview_vis_dev = doc_manager->GetPrintPreviewVD();
doc = doc_manager->GetPrintDoc();
}
else
#endif // _PRINT_SUPPORT_
doc = doc_manager->GetCurrentDoc();
// Update with new rendering buffer size as well.
UINT32 rendering_width, rendering_height;
OpRect rendering_rect;
m_opWindow->GetRenderingBufferSize(&rendering_width, &rendering_height);
rendering_rect.width = rendering_width;
rendering_rect.height = rendering_height;
normal_vis_dev->SetRenderingViewGeometryScreenCoords(rendering_rect);
#ifdef DEBUG
// We assume that OpWindow tells us the correct (new) window size. Let's verify it's true.
{
UINT32 window_width, window_height;
m_opWindow->GetInnerSize(&window_width, &window_height);
OP_ASSERT(window_width == width && window_height == height);
}
#endif // DEBUG
#ifdef _PRINT_SUPPORT_
if (print_preview_vis_dev)
print_preview_vis_dev->SetRenderingViewGeometryScreenCoords(rendering_rect);
#endif // _PRINT_SUPPORT_
if (doc)
{
doc->RecalculateScrollbars();
doc->RecalculateLayoutViewSize(TRUE);
doc->RequestSetViewportToInitialScale(VIEWPORT_CHANGE_REASON_WINDOW_SIZE);
}
#if defined SCROLL_TO_ACTIVE_ELM_ON_RESIZE && defined SCROLL_TO_ACTIVE_ELM
if (FramesDocument* active_frame = GetActiveFrameDoc())
active_frame->ScrollToActiveElement();
#endif // SCROLL_TO_ACTIVE_ELM_ON_RESIZE && SCROLL_TO_ACTIVE_ELM
}
OP_STATUS Window::UpdateWindow(BOOL /* unused = FALSE */)
{
// Set expirytype temporary to never, and then change back after the UpdateWindow.
// Prevents expired images from getting reloaded when we change layoutmode.
CheckExpiryType old_expiry_type = doc_manager->GetCheckExpiryType();
doc_manager->SetCheckExpiryType(CHECK_EXPIRY_NEVER);
if (doc_manager->ReformatCurrentDoc() == OpStatus::ERR_NO_MEMORY)
return OpStatus::ERR_NO_MEMORY;
doc_manager->SetCheckExpiryType(old_expiry_type);
return OpStatus::OK;
}
OP_STATUS Window::UpdateWindowAllDocuments(BOOL /* unused = FALSE */)
{
if (doc_manager)
{
// Set expirytype temporary to never, and then change back after the UpdateWindowAllDocuments.
// Prevents expired images from getting reloaded when we change layoutmode.
CheckExpiryType old_expiry_type = doc_manager->GetCheckExpiryType();
doc_manager->SetCheckExpiryType(CHECK_EXPIRY_NEVER);
DocListElm* elm = doc_manager->FirstDocListElm();
while (elm)
{
FramesDocument* frm_doc = elm->Doc();
if (frm_doc)
doc_manager->ReformatDoc(frm_doc);
elm = elm->Suc();
}
doc_manager->SetCheckExpiryType(old_expiry_type);
}
return OpStatus::OK;
}
OP_STATUS Window::UpdateWindowDefaults(BOOL scroll, BOOL progress, BOOL news, WORD scale, BOOL size)
{
SetShowScrollbars(scroll);
SetScale(scale);
return SetWindowTitle(title, TRUE, generated_title);
}
#ifndef MOUSELESS
void
Window::UseDefaultCursor()
{
has_cursor_set_by_doc = FALSE;
current_cursor = GetCurrentCursor();
SetCurrentCursor();
}
void
Window::CommitPendingCursor()
{
if(m_pending_cursor == CURSOR_AUTO)
UseDefaultCursor();
else
SetCursor(m_pending_cursor, TRUE);
m_pending_cursor = CURSOR_AUTO;
}
void
Window::SetCurrentCursor()
{
m_opWindow->SetCursor(current_cursor);
}
void Window::SetCursor(CursorType cursor, BOOL set_by_document/*=FALSE*/)
{
if (set_by_document)
{
has_cursor_set_by_doc = TRUE;
cursor_set_by_doc = cursor;
}
// Only allow cursor changes in case the cursor either comes from
// a trusted source (page load) or the window currently has
// no page load cursor.
if (!set_by_document || !IsNormalWindow() || state != BUSY)
{
if (cursor != current_cursor)
{
current_cursor = cursor;
SetCurrentCursor();
}
}
}
#endif // !MOUSELESS
void Window::ClearMessage()
{
OP_DELETEA(current_message);
current_message = NULL;
m_windowCommander->GetDocumentListener()->OnNoHover(m_windowCommander);
}
void Window::SetMessageInternal()
{
m_windowCommander->GetDocumentListener()->OnStatusText(m_windowCommander, current_message ? current_message : current_default_message);
}
OP_STATUS Window::SetMessage(const uni_char* msg)
{
if (!msg)
{
OP_DELETEA(current_message);
current_message = NULL;
}
else if (current_message && uni_strcmp(current_message, msg) == 0)
{
// Nothing changed, bail out
if (current_default_message)
{
g_windowManager->SetPopupMessage(current_message);
}
return OpStatus::OK;
}
else
{
RETURN_IF_ERROR(UniSetStr(current_message, msg));
}
SetMessageInternal();
return OpStatus::OK;
}
OP_STATUS Window::SetDefaultMessage(const uni_char* msg)
{
if (!msg)
{
OP_DELETEA(current_default_message);
current_default_message = NULL;
}
else
if (current_default_message && uni_strcmp(current_default_message, msg) == 0)
// Nothing changed, bail out
return OpStatus::OK;
else
RETURN_IF_ERROR(UniSetStr(current_default_message, msg));
m_windowCommander->GetDocumentListener()->OnStatusText(m_windowCommander, current_message ? current_message : current_default_message);
return OpStatus::OK;
}
void Window::SetActiveLinkURL(const URL& url, HTML_Document* doc)
{
const uni_char* title = NULL;
if (g_pcdoc->GetIntegerPref(PrefsCollectionDoc::DisplayLinkTitle) && doc)
{
// Find the title string for this link.
HTML_Element *el = doc->GetActiveHTMLElement();
for (; el; el = el->Parent())
{
title = el->GetStringAttr(ATTR_TITLE);
if (title || el->Type() == HE_A) break;
}
}
if (title)
DisplayLinkInformation(url, ST_ATITLE, title);
else
DisplayLinkInformation(url, ST_ALINK);
#ifndef MOUSELESS
SetCursor(CURSOR_CUR_POINTER);
#endif // !MOUSELESS
active_link_url = url;
}
void Window::ClearActiveLinkURL()
{
ClearMessage();
SetState(GetState()); // Reset the mouse cursor.
URL empty;
active_link_url = empty;
}
void Window::SetImagesSetting(SHOWIMAGESTATE set)
{
#ifdef GADGET_SUPPORT
if (GetGadget())
{
load_img = TRUE;
show_img = TRUE;
}
else
#endif
{
switch (set)
{
case FIGS_OFF:
load_img = FALSE;
show_img = FALSE;
break;
case FIGS_SHOW:
load_img = FALSE;
show_img = TRUE;
break;
default:
load_img = TRUE;
show_img = TRUE;
break;
}
}
doc_manager->SetShowImg(show_img);
/*{
FramesDocument *doc = doc_manager->GetCurrentDoc();
if (doc)
{
doc->SetShowImg(show_img);
/ *if (doc->SetShowImg(show_img) == DOC_NEED_IMAGE_RELOAD)
{
if (load_img)
{
StartProgressDisplay(TRUE, TRUE, TRUE);
SetState(BUSY);
SetState(CLICKABLE);
}
}* /
}
}*/
OpDocumentListener::ImageDisplayMode mode;
#ifdef GADGET_SUPPORT
if (GetGadget())
{
mode = OpDocumentListener::ALL_IMAGES;
}
else
#endif
{
switch (set)
{
case FIGS_OFF:
mode = OpDocumentListener::NO_IMAGES;
break;
case FIGS_SHOW:
mode = OpDocumentListener::LOADED_IMAGES;
break;
default:
mode = OpDocumentListener::ALL_IMAGES;
break;
}
}
m_windowCommander->GetDocumentListener()->OnImageModeChanged(m_windowCommander, mode);
}
LayoutMode Window::GetLayoutMode() const
{
if (era_mode)
if (FramesDocument* doc = GetCurrentDoc())
return doc->GetLayoutMode();
return layout_mode;
}
void Window::SetLayoutMode(LayoutMode mode)
{
if (layout_mode != mode)
{
LayoutMode old_layout_mode = layout_mode;
layout_mode = mode;
is_ssr_mode = (mode == LAYOUT_SSR || mode == LAYOUT_CSSR); // use handheld until obsolete
FramesDocument* frames_doc = doc_manager->GetCurrentDoc();
int old_iframe_policy = SHOW_IFRAMES_ALL;
if (frames_doc)
old_iframe_policy = frames_doc->GetShowIFrames();
HLDocProfile *hldoc = frames_doc ? frames_doc->GetHLDocProfile() : NULL;
if (hldoc && old_layout_mode == LAYOUT_SSR)
hldoc->LoadAllCSS();
OP_STATUS ret = UpdateWindow(); // cause reformat because stylesheets may be different
if (OpStatus::IsError(ret))
{
RaiseCondition(ret);
}
if (frames_doc)
{
int iframe_policy = frames_doc->GetShowIFrames();
if (iframe_policy != SHOW_IFRAMES_NONE && old_iframe_policy != iframe_policy)
{
//FIXME SHOW_IFRAMES_SOME
frames_doc->LoadAllIFrames();
}
frames_doc->RecalculateLayoutViewSize(TRUE);
}
}
}
void Window::SetFramesPolicy(INT32 value)
{
if (m_frames_policy != value)
{
m_frames_policy = value;
UpdateWindow();
}
}
void Window::SetERA_Mode(BOOL value)
{
#ifdef GADGET_SUPPORT
if (GetGadget() && value == TRUE)
return;
#endif
if (era_mode != value)
{
era_mode = value;
DocumentTreeIterator iter(this);
iter.SetIncludeThis();
while (iter.Next())
iter.GetFramesDocument()->ERA_ModeChanged();
UpdateWindow(); // reformat
}
}
void Window::Reload(EnteredByUser entered_by_user, BOOL conditionally_request_document, BOOL conditionally_request_inlines)
{
#ifdef _PRINT_SUPPORT_
if (print_mode)
StopPrinting();
#endif // _PRINT_SUPPORT_
doc_manager->Reload(entered_by_user, conditionally_request_document, conditionally_request_inlines, FALSE);
}
BOOL Window::CancelLoad(BOOL oom)
{
is_canceling_loading = TRUE;
doc_manager->StopLoading(!oom, TRUE, TRUE);
if (oom)
SetOOMOccurred(TRUE);
SetState(NOT_BUSY);
EndProgressDisplay();
EnsureHistoryLimits();
phase_uploading = FALSE;
is_canceling_loading = FALSE;
return TRUE;
}
void Window::Raise()
{
m_windowCommander->GetDocumentListener()->OnRaiseRequest(m_windowCommander);
}
void Window::Lower()
{
m_windowCommander->GetDocumentListener()->OnLowerRequest(m_windowCommander);
}
FramesDocument *Window::GetCurrentDoc() const
{
return doc_manager->GetCurrentDoc();
}
void Window::HighlightURL(BOOL forward)
{
FramesDocument* doc = GetActiveFrameDoc();
if (doc)
{
if (doc->HighlightNextElm(HE_A, HE_A, forward, TRUE /*ignore lower/upper - get next anchor elm */))
{
#ifdef DISPLAY_CLICKINFO_SUPPORT
// Save link title for bookmark purposes
MouseListener::GetClickInfo().SetTitleElement(doc, doc->GetCurrentHTMLElement());
#endif // DISPLAY_CLICKINFO_SUPPORT
const uni_char* window_name = 0;
URL url = doc->GetCurrentURL(window_name);
if (!url.IsEmpty())
{
// Eventually it would be nice to unescape the url to make it more readable, but then we need to
// get the decoding to do it correctly with respect to charset encodings. See bug 250545
OpStringC hlink = url.GetAttribute(URL::KUniName_With_Fragment_Escaped);
if (hlink.HasContent())
g_windowManager->SetPopupMessage(hlink.CStr(), FALSE, ST_ALINK);
}
}
}
}
#ifdef _SPAT_NAV_SUPPORT_
/**
* Returns a pointer to the Window's Spatial Navigation handler.
* If the handler does not exist it is constructed and initialized.
* If memory allocation fails, then the function returns 0.
*
* @return Pointer to the SnHandler or 0 on failure.
*
*/
OpSnHandler* Window::GetSnHandlerConstructIfNeeded ()
{
if (sn_handler == NULL)
{
#ifdef PHONE_SN_HANDLER
sn_handler = OP_NEW(PhoneSnHandler, ());
#else
sn_handler = OP_NEW(SnHandler, ());
#endif
if (sn_handler == NULL) // Out om memory!
{
return 0;
}
if (OpStatus::IsError(sn_handler->Init(this)))
{
OP_DELETE(sn_handler);
sn_handler = NULL;
return 0;
}
}
return sn_handler;
}
BOOL Window::MarkNextLinkInDirection(INT32 direction, POINT* startingPoint, BOOL scroll)
{
OpSnHandler* handler = GetSnHandlerConstructIfNeeded();
if (handler && handler->MarkNextLinkInDirection(direction, startingPoint, scroll))
return TRUE;
#ifdef SN_LEAVE_SUPPORT
else
LeaveInDirection(direction);
#endif // SN_LEAVE_SUPPORT
return FALSE;
}
BOOL Window::MarkNextImageInDirection(INT32 direction, POINT* startingPoint, BOOL scroll)
{
OpSnHandler* handler = GetSnHandlerConstructIfNeeded();
if (handler)
return handler->MarkNextImageInDirection(direction, startingPoint, scroll);
return FALSE;
}
BOOL Window::MarkNextItemInDirection(INT32 direction, POINT* startingPoint, BOOL scroll)
{
OpSnHandler* handler = GetSnHandlerConstructIfNeeded();
#ifdef SN_LEAVE_SUPPORT
if (!handler || !handler->MarkNextItemInDirection(direction, startingPoint, scroll))
LeaveInDirection(direction);
return TRUE;
#else // SN_LEAVE_SUPPORT
if (handler)
{
BOOL state = handler->MarkNextItemInDirection(direction, startingPoint, scroll);
#ifdef DISPLAY_CLICKINFO_SUPPORT
FramesDocument* doc = GetActiveFrameDoc();
if (doc)
{
// Save link title for bookmark purposes
MouseListener::GetClickInfo().SetTitleElement(doc, doc->GetCurrentHTMLElement());
}
#endif // DISPLAY_CLICKINFO_SUPPORT
return state;
}
return FALSE;
#endif // SN_LEAVE_SUPPORT
}
#ifdef SN_LEAVE_SUPPORT
//OBS! This is a temporary hack!
// It should probably be moved to some better place.
void Window::LeaveInDirection(INT32 direction)
{
if (sn_listener == NULL) return;
FramesDocument *doc = GetActiveFrameDoc();
if (!doc)
{
sn_listener->LeaveInDirection(direction);
return;
}
HTML_Document *hdoc = doc->GetHtmlDocument();
if (!hdoc)
{
sn_listener->LeaveInDirection(direction);
return;
}
HTML_Element *helm = hdoc->GetNavigationElement();
if (!helm)
{
sn_listener->LeaveInDirection(direction);
return;
}
LogicalDocument *logdoc = doc->GetLogicalDocument();
if (!logdoc)
{
sn_listener->LeaveInDirection(direction);
return;
}
RECT rect;
if (!logdoc->GetBoxRect(helm, rect))
{
sn_listener->LeaveInDirection(direction);
return;
}
VisualDevice *visdev = doc->GetVisualDevice();
if (visdev == NULL)
{
sn_listener->LeaveInDirection(direction);
return;
}
// Calculate the "leave point"
int x = 0;
int y = 0;
switch ((direction % 360) / 90)
{
case 0: // Right
x = rect.right;
y = (rect.top + rect.bottom) / 2;
break;
case 1: // Up
x = (rect.right + rect.left) / 2;
y = rect.top;
break;
case 2: // Left
x = rect.left;
y = (rect.top + rect.bottom) / 2;
break;
case 3: // Down
x = (rect.right + rect.left) / 2;
y = rect.bottom;
break;
}
sn_listener->LeaveInDirection(direction, x, y, visdev->GetOpView());
return;
}
void Window::SetSnLeaveListener(SnLeaveListener *listener)
{
sn_listener = listener;
}
void Window::SnMarkSelection()
{
SnHandler* handler = static_cast<SnHandler *>(GetSnHandler());
if (handler) handler->HighlightCurrentElement();
}
#endif //SN_LEAVE_SUPPORTED
#endif // _SPAT_NAV_SUPPORT_
void Window::HighlightHeading(BOOL forward)
{
if (FramesDocument* doc = GetActiveFrameDoc())
doc->HighlightNextElm(HE_H1, HE_H6, forward, FALSE);
}
void Window::HighlightItem(BOOL forward)
{
if (FramesDocument* doc = GetActiveFrameDoc())
doc->HighlightNextElm(Markup::HTE_FIRST, Markup::HTE_LAST, forward, FALSE);
}
OP_STATUS Window::GetHighlightedURL(uint16 key, BOOL bNewWindow, BOOL bOpenInBackground)
{
FramesDocument* doc = GetCurrentDoc();
if (doc)
{
FramesDocument *sub_doc = doc->GetActiveSubDoc();
{
#ifdef _WML_SUPPORT_
if (doc->GetDocManager()->WMLHasWML())
{
if (!FormManager::ValidateWMLForm(doc))
return OpStatus::OK;
}
#endif // _WML_SUPPORT_
int sub_win_id = -1;
const uni_char* window_name = NULL;
URL url = doc->GetCurrentURL(window_name);
if (!url.IsEmpty())
return g_windowManager->OpenURLNamedWindow(url, this, doc, sub_doc ? sub_doc->GetSubWinId() : sub_win_id, window_name, TRUE, bNewWindow, bOpenInBackground, TRUE);
else if (key==OP_KEY_SPACE)
{
if (doc->IsFrameDoc())
doc = doc->GetActiveSubDoc();
ScrollDocument(doc, bNewWindow ? (bOpenInBackground? OpInputAction::ACTION_GO_TO_START : OpInputAction::ACTION_PAGE_UP)
: (bOpenInBackground? OpInputAction::ACTION_GO_TO_END : OpInputAction::ACTION_PAGE_DOWN));
}
}
}
return OpStatus::OK;
}
void Window::RaiseCondition( OP_STATUS type )
{
if (type == OpStatus::ERR_NO_MEMORY)
GetMessageHandler()->PostOOMCondition(TRUE);
else if (type == OpStatus::ERR_SOFT_NO_MEMORY)
GetMessageHandler()->PostOOMCondition(FALSE);
else if (type == OpStatus::ERR_NO_DISK)
GetMessageHandler()->PostOODCondition();
else
OP_ASSERT(0);
}
Window::OnlineMode Window::GetOnlineMode()
{
if (m_online_mode == Window::ONLINE || m_online_mode == Window::OFFLINE)
m_online_mode = g_pcnet->GetIntegerPref(PrefsCollectionNetwork::OfflineMode) ? OFFLINE : ONLINE;
return m_online_mode;
}
OP_STATUS Window::QueryGoOnline(URL *url)
{
if (m_online_mode == Window::OFFLINE)
{
OpString url_name;
OpString message;
RETURN_IF_ERROR(url->GetAttribute(URL::KUniName_Username_Password_Hidden, url_name, TRUE));
if (url_name.Length() > 100)
url_name.Delete(90).Append(UNI_L("..."));
OpString warning;
TRAPD(err, g_languageManager->GetStringL(Str::SI_MSG_OFFLINE_WARNING, warning));
if (OpStatus::IsMemoryError(err))
{
return err;
}
RETURN_IF_ERROR(message.AppendFormat(warning.CStr(), url_name.CStr()));
m_online_mode = Window::USER_RESPONDING;
WindowCommander* wc = GetWindowCommander();
OP_ASSERT(wc);
OpDocumentListener *listener = wc->GetDocumentListener();
listener->OnQueryGoOnline(wc, message.CStr(), this);
}
return OpStatus::OK;
}
void Window::OnDialogReply(DialogCallback::Reply reply)
{
if (reply == DialogCallback::REPLY_YES)
{
m_online_mode = Window::ONLINE;
if (UpdateOfflineMode(FALSE) == OpBoolean::IS_TRUE)
UpdateOfflineMode(TRUE);
}
else
{
m_online_mode = Window::DENIED;
if (OpStatus::IsMemoryError(DocManager()->OnlineModeChanged()))
RaiseCondition(OpStatus::ERR_NO_MEMORY);
}
}
void
Window::LockWindow()
{
window_locked++;
}
void
Window::UnlockWindow()
{
OP_ASSERT(window_locked);
window_locked--;
if (window_locked == 0 && window_closed)
{
g_main_message_handler->PostMessage(MSG_ES_CLOSE_WINDOW, 0, id);
window_closed = FALSE;
}
}
BOOL
Window::IsURLAlreadyRequested(const URL &url)
{
return loading && use_already_requested_urls && already_requested_urls.Contains(url.Id());
}
void
Window::SetURLAlreadyRequested(const URL &url)
{
if (loading && use_already_requested_urls)
if (OpStatus::IsMemoryError(already_requested_urls.Add(url.Id())))
{
already_requested_urls.RemoveAll();
use_already_requested_urls = FALSE;
}
}
void
Window::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2)
{
#ifdef LOCALE_CONTEXTS
if (doc_manager && doc_manager->GetCurrentDoc())
g_languageManager->SetContext(doc_manager->GetCurrentDoc()->GetURL().GetContextId());
#endif
switch (msg)
{
case MSG_PROGRESS_START:
if (!loading)
{
#ifdef DEBUG_LOAD_STATUS
PrintfTofile("loading.txt","================================%lu\n", (unsigned long) g_op_time_info->GetWallClockMS());
#endif
SetLoading(TRUE);
already_requested_urls.RemoveAll();
use_already_requested_urls = TRUE;
#if defined(EPOC)
if (m_windowCommander) // Check in case this Window is the "hidden transfer window"
{
Window* epocWindow = m_windowCommander ? m_windowCommander->GetWindow() : 0;
if((epocWindow->m_loading_information).isUploading)
m_windowCommander->GetLoadingListener()->OnStartUploading(m_windowCommander);
else
m_windowCommander->GetLoadingListener()->OnStartLoading(m_windowCommander);
}
#else // EPOC
m_windowCommander->GetLoadingListener()->OnStartLoading(m_windowCommander);
#endif // EPOC
}
break;
case MSG_PROGRESS_END:
if (loading)
{
#ifdef DEBUG_LOAD_STATUS
PrintfTofile("loading.txt","================================%lu\n", (unsigned long) g_op_time_info->GetWallClockMS());
#endif
SetLoading(FALSE);
UnlockPaintLock();
pending_unlock_all_painting = FALSE;
already_requested_urls.RemoveAll();
use_already_requested_urls = TRUE;
OpLoadingListener::LoadingFinishStatus status = static_cast<OpLoadingListener::LoadingFinishStatus>(par2);
m_windowCommander->GetLoadingListener()->OnLoadingFinished(m_windowCommander, status);
if (m_online_mode == Window::DENIED)
m_online_mode = Window::OFFLINE;
#ifdef _SPAT_NAV_SUPPORT_
OpSnHandler* handler = GetSnHandlerConstructIfNeeded();
if (handler)
handler->OnLoadingFinished();
#endif // _SPAT_NAV_SUPPORT_
OP_STATUS oom = doc_manager->UpdateWindowHistoryAndTitle();
if (OpStatus::IsMemoryError(oom))
RaiseCondition(oom);
}
break;
#ifdef _PRINT_SUPPORT_
case DOC_START_PRINTING:
# ifdef GENERIC_PRINTING
{
PrinterInfo * prnInfo = OP_NEW(PrinterInfo, ());
int start_page = 1;
if (prnInfo == NULL)
{
RaiseCondition(OpStatus::ERR_NO_MEMORY);
break;
}
PrintDevice * printDevice;
# ifdef PRINT_SELECTION_USING_DUMMY_WINDOW
Window * selection_window = 0;
OP_STATUS result = prnInfo->GetPrintDevice(printDevice, FALSE, FALSE, this, &selection_window);
# else
OP_STATUS result = prnInfo->GetPrintDevice(printDevice, FALSE, FALSE, this);
# endif
if (OpStatus::IsError(result) || !printDevice->StartPage())
{
OP_DELETE(prnInfo);
break;
}
SetFramesPrintType((DM_PrintType)g_pcprint->GetIntegerPref(PrefsCollectionPrint::DefaultFramesPrintType), TRUE);
Window * window = this;
# ifdef PRINT_SELECTION_USING_DUMMY_WINDOW
if (selection_window != 0)
window = selection_window;
# endif
window->StartPrinting(prnInfo, start_page, FALSE);
}
# endif // GENERIC_PRINTING
break;
case DOC_PRINT_FORMATTED:
# if defined GENERIC_PRINTING
if (printer_info)
printer_info->GetPrintDevice()->GetPrinterController()->PrintDocFormatted(printer_info);
else if (preview_printer_info)
preview_printer_info->GetPrintDevice()->GetPrinterController()->PrintDocFormatted(preview_printer_info);
{
OpPrintingListener::PrintInfo info; //rg fixme
info.status = OpPrintingListener::PrintInfo::PRINTING_STARTED;
m_windowCommander->GetPrintingListener()->OnPrintStatus(m_windowCommander, &info);
}
# elif defined MSWIN
{
OP_NEW_DBG("Window::HandleMessage", "async_print");
OP_DBG(("Will enter ucPrintFormatted"));
ucPrintDocFormatted();
}
# elif defined _X11_ || defined _MACINTOSH_
PrintNextPage(printer_info ? printer_info : preview_printer_info);
# endif // GENERIC_PRINTING
break;
case DOC_PAGE_PRINTED:
# if defined GENERIC_PRINTING
if (printer_info)
printer_info->GetPrintDevice()->GetPrinterController()->PrintPagePrinted(printer_info);
else if (preview_printer_info)
preview_printer_info->GetPrintDevice()->GetPrinterController()->PrintPagePrinted(preview_printer_info);
{
OpPrintingListener::PrintInfo info; //rg fixme
info.status = OpPrintingListener::PrintInfo::PAGE_PRINTED;
info.currentPage = par2;
m_windowCommander->GetPrintingListener()->OnPrintStatus(m_windowCommander, &info);
}
# else // GENERIC_PRINTING
{
OpPrintingListener::PrintInfo info; //rg fixme
info.status = OpPrintingListener::PrintInfo::PAGE_PRINTED;
info.currentPage = par2;
m_windowCommander->GetPrintingListener()->OnPrintStatus(m_windowCommander, &info);
}
# endif // GENERIC_PRINTING
break;
case DOC_PRINTING_FINISHED:
# ifdef GENERIC_PRINTING
if (printer_info)
printer_info->GetPrintDevice()->GetPrinterController()->PrintDocFinished();
else if (preview_printer_info)
preview_printer_info->GetPrintDevice()->GetPrinterController()->PrintDocFinished();
StopPrinting();
{
OpPrintingListener::PrintInfo info;
info.status = OpPrintingListener::PrintInfo::PRINTING_DONE;
m_windowCommander->GetPrintingListener()->OnPrintStatus(m_windowCommander, &info);
}
# else // GENERIC_PRINTING
{
OpPrintingListener::PrintInfo info;
info.status = OpPrintingListener::PrintInfo::PRINTING_DONE;
m_windowCommander->GetPrintingListener()->OnPrintStatus(m_windowCommander, &info);
}
# endif // GENERIC_PRINTING
break;
case DOC_PRINTING_ABORTED:
# ifdef GENERIC_PRINTING
if (printer_info)
printer_info->GetPrintDevice()->GetPrinterController()->PrintDocAborted();
else if (preview_printer_info)
preview_printer_info->GetPrintDevice()->GetPrinterController()->PrintDocAborted();
StopPrinting();
{
OpPrintingListener::PrintInfo info; //rg fixme
info.status = OpPrintingListener::PrintInfo::PRINTING_ABORTED;
m_windowCommander->GetPrintingListener()->OnPrintStatus(m_windowCommander, &info);
}
# else // GENERIC_PRINTING
{
OpPrintingListener::PrintInfo info; //rg fixme
info.status = OpPrintingListener::PrintInfo::PRINTING_ABORTED;
m_windowCommander->GetPrintingListener()->OnPrintStatus(m_windowCommander, &info);
}
# endif // GENERIC_PRINTING
break;
#endif // _PRINTING_SUPPORT_
#if !defined MOUSELESS && !defined HAS_NOTEXTSELECTION
case MSG_SELECTION_SCROLL:
#ifdef DRAG_SUPPORT
if (!g_drag_manager->IsDragging())
#endif
{
if (!selection_scroll_active)
break;
const int fudge = 5;
BOOL button_pressed = FALSE;
OpInputContext* ic = NULL;
FramesDocument* doc = GetActiveFrameDoc();
while(doc)
{
VisualDevice* vis_dev = doc->GetVisualDevice();
CoreView *view = vis_dev->GetView();
BOOL retry = FALSE;
if (view)
{
OpRect bounding_rect(doc->GetVisualViewport());
if (!ic && g_input_manager->GetKeyboardInputContext())
{
ic = g_input_manager->GetKeyboardInputContext();
// First try with the focused inputcontext. It may be a scrollable container in page layout.
if (ic->GetBoundingRect(bounding_rect))
{
bounding_rect.x += vis_dev->GetRenderingViewX();
bounding_rect.y += vis_dev->GetRenderingViewY();
}
// Retry, scrolling the document (if not the document).
retry = ic != vis_dev;
}
else
ic = vis_dev;
INT32 xpos, ypos;
if(!view->GetMouseButton(MOUSE_BUTTON_1) &&
!view->GetMouseButton(MOUSE_BUTTON_2) &&
!view->GetMouseButton(MOUSE_BUTTON_3))
break;
button_pressed = TRUE;
view->GetMousePos(&xpos, &ypos);
xpos = vis_dev->GetRenderingViewX() + vis_dev->ScaleToDoc(xpos);
ypos = vis_dev->GetRenderingViewY() + vis_dev->ScaleToDoc(ypos);
BOOL handled = FALSE;
if(xpos < bounding_rect.x + fudge)
{
OpInputAction action(OpInputAction::ACTION_SCROLL_LEFT);
handled |= ic->OnInputAction(&action);
}
else if(xpos > bounding_rect.x + bounding_rect.width - fudge)
{
OpInputAction action(OpInputAction::ACTION_SCROLL_RIGHT);
handled |= ic->OnInputAction(&action);
}
if(ypos < bounding_rect.y + fudge)
{
OpInputAction action(OpInputAction::ACTION_SCROLL_UP);
handled |= ic->OnInputAction(&action);
}
else if(ypos > bounding_rect.y + bounding_rect.height - fudge)
{
OpInputAction action(OpInputAction::ACTION_SCROLL_DOWN);
handled |= ic->OnInputAction(&action);
}
if (handled)
break;
}
if (!retry)
doc = doc->GetParentDoc();
}
if (button_pressed)
//Keep the scroll running...
if (!GetMessageHandler()->PostDelayedMessage(MSG_SELECTION_SCROLL, 0, 0, 75))
g_memory_manager->RaiseCondition(OpStatus::ERR_NO_MEMORY);
}
break;
#endif // !MOUSELESS && !HAS_NOTEXTSELECTION
case MSG_ES_CLOSE_WINDOW:
g_main_message_handler->PostMessage(MSG_ES_CLOSE_WINDOW, 0, Id());
break;
case MSG_UPDATE_PROGRESS_TEXT:
{
OP_STATUS ret = SetProgressText(doc_manager->GetCurrentURL(), TRUE);
if (ret == OpStatus::ERR_NO_MEMORY)
{
RaiseCondition(ret);
}
}
break;
case MSG_UPDATE_WINDOW_TITLE:
{
title_update_title_posted = FALSE;
OP_STATUS ret = UpdateTitle(FALSE);
if (ret == OpStatus::ERR_NO_MEMORY)
{
RaiseCondition(ret);
}
}
break;
case WM_OPERA_SCALEDOC:
{
// wParam = Window to scale.
// HIWORD( lParam) = (BOOL) bIsAbsolute
// LOWORD( lParam) = New scale or adjustment (depending on the highword)
short scale;
if (HIWORD(par2)) // absolute (=TRUE) or relative (=FALSE)
scale = LOWORD(par2);
else
scale = GetScale() + static_cast<short>(LOWORD(par2));
ViewportController* controller = GetViewportController();
controller->GetViewportRequestListener()->
OnZoomLevelChangeRequest(controller, (MIN((short)DOCHAND_MAX_DOC_ZOOM, scale)) / 100.0
// don't specify a priority rectangle, though the input action might
// have had one:
// TODO: pass the priority rectangle in the message parameter as well.
, 0,
// this message is a result of an input action (e.g. CTRL+mouse-wheel
// or definition in input.ini):
VIEWPORT_CHANGE_REASON_INPUT_ACTION
);
}
break;
case MSG_URL_MOVED:
{
URL cu = doc_manager->GetCurrentURL();
if (cu.Id(TRUE) == static_cast<URL_ID>(par2))
{
URL moved_to = cu.GetAttribute(URL::KMovedToURL, TRUE);
if (!moved_to.IsEmpty())
{
URLLink *url_ref = OP_NEW(URLLink, (moved_to));
url_ref->Into(&moved_urls);
}
}
}
break;
case MSG_HISTORY_BACK:
if (HasHistoryPrev())
SetHistoryPrev(FALSE);
break;
case MSG_HISTORY_CLEANUP:
history_cleanup_message_sent = FALSE;
EnsureHistoryLimits();
break;
}
if (check_history)
CheckHistory();
}
BOOL Window::GetLimitParagraphWidth()
{
return limit_paragraph_width
#ifndef LIMIT_PARA_WIDTH_IGNORE_MODES
&& !era_mode && (GetLayoutMode() == LAYOUT_NORMAL)
#endif
;
}
void Window::SetLimitParagraphWidth(BOOL set)
{
limit_paragraph_width = set;
if (FramesDocument *frm_doc = doc_manager->GetCurrentDoc())
frm_doc->MarkContainersDirty();
}
void Window::SetFlexRootMaxWidth(int max_width, BOOL reformat)
{
if (flex_root_max_width != max_width)
{
// max_width == 0 means disable flex-root
flex_root_max_width = max_width;
if (doc_manager)
if (FramesDocument* doc = doc_manager->GetCurrentDoc())
doc->RecalculateLayoutViewSize(TRUE);
if (reformat)
UpdateWindow();
}
}
void Window::ResumeEcmaScriptIfNotPaused()
{
if (ecmascript_paused == NOT_PAUSED)
{
DocumentTreeIterator iterator(this);
iterator.SetIncludeThis();
while (iterator.Next())
{
if (ES_ThreadScheduler *scheduler = iterator.GetFramesDocument()->GetESScheduler())
scheduler->ResumeIfNeeded();
}
}
}
void Window::SetEcmaScriptPaused(BOOL value)
{
if (value)
ecmascript_paused |= PAUSED_OTHER;
else
{
ecmascript_paused &= ~PAUSED_OTHER;
ResumeEcmaScriptIfNotPaused();
}
}
void Window::CancelAllEcmaScriptTimeouts()
{
DocumentTreeIterator iterator(this);
iterator.SetIncludeThis();
while (iterator.Next())
if (ES_ThreadScheduler *scheduler = iterator.GetFramesDocument()->GetESScheduler())
scheduler->CancelAllTimeouts(TRUE, TRUE);
}
#if defined GRAB_AND_SCROLL
BOOL Window::GetScrollIsPan() const
{
return scroll_is_pan_overridden ? scroll_is_pan : g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::ScrollIsPan);
}
void Window::OverrideScrollIsPan()
{
if (scroll_is_pan_overridden)
scroll_is_pan = scroll_is_pan ? FALSE : TRUE;
else
{
scroll_is_pan_overridden = TRUE;
scroll_is_pan = g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::ScrollIsPan) ? FALSE : TRUE;
}
}
#endif // GRAB_AND_SCROLL
#ifdef SAVE_SUPPORT
void Window::GetSuggestedSaveFileName(URL *url, uni_char *szName, int maxSize)
{
}
OP_BOOLEAN Window::SaveAs(URL& url, BOOL load_to_file, BOOL save_inline, BOOL frames_only)
{
return OpBoolean::IS_FALSE;
}
OP_BOOLEAN Window::SaveAs(URL& url, BOOL load_to_file, BOOL save_inline, const uni_char* szSaveToFolder, BOOL fCreateDirectory, BOOL fExecute, BOOL hasfilename, const uni_char* handlerapplication, BOOL frames_only)
{
return OpBoolean::IS_FALSE;
}
#endif // SAVE_SUPPORT
#ifdef NEARBY_ELEMENT_DETECTION
void Window::SetElementExpander(ElementExpander* expander)
{
ElementExpander* old_element_expander = element_expander;
// Assign expander member variable before deleting old_element_expander because
// ElementExpander destructor may call WindowCommander::HideFingertouchElements, and then Window::SetElementExpander
// that can lead to a double free (crash)
element_expander = expander;
OP_DELETE(old_element_expander);
}
#endif // NEARBY_ELEMENT_DETECTION
void Window::SetPrivacyMode(BOOL privacy_mode)
{
if (privacy_mode != m_privacy_mode)
{
m_privacy_mode = privacy_mode;
if (m_privacy_mode)
g_windowManager->AddWindowToPrivacyModeContext();
else
{
g_windowManager->RemoveWindowFromPrivacyModeContext();
doc_manager->UnloadCurrentDoc();
RemoveAllElementsExceptCurrent();
}
}
}
#ifdef WEB_TURBO_MODE
void Window::SetTurboMode(BOOL turbo_mode)
{
if (turbo_mode)
{
if (type != WIN_TYPE_NORMAL) // Turbo Mode only available for normal windows.
return;
#ifdef GADGET_SUPPORT
if(GetGadget())
return;
#endif // GADGET_SUPPORT
#ifdef OBML_COMM_FORCE_CONFIG_FILE
if (g_obml_config->GetExpired()) // Absence of correct and valid config file means no Turbo support
{
urlManager->SetWebTurboAvailable(FALSE);
return;
}
#endif // OBML_COMM_FORCE_CONFIG_FILE
}
if (turbo_mode != m_turbo_mode)
{
if (turbo_mode)
{
if (OpStatus::IsSuccess(g_windowManager->CheckTuboModeContext()))
m_turbo_mode = turbo_mode;
}
else
m_turbo_mode = turbo_mode;
if (turbo_mode == m_turbo_mode)
{
if (doc_manager)
doc_manager->UpdateTurboMode();
}
}
}
#endif // WEB_TURBO_MODE
void Window::ScreenPropertiesHaveChanged(){
//iter all doc-managers, and inform visual devices that
//the screen properties have changed
DocumentTreeIterator it(this);
it.SetIncludeThis();
while (it.Next())
{
if(it.GetDocumentManager()->GetVisualDevice())
{
it.GetDocumentManager()->GetVisualDevice()->ScreenPropertiesHaveChanged();
if (FramesDocument* doc = it.GetFramesDocument())
doc->RecalculateDeviceMediaQueries();
}
}
#ifdef DOM_JIL_API_SUPPORT
if(m_screen_props_listener)
m_screen_props_listener->OnScreenPropsChanged();
#endif // DOM_JIL_API_SUPPORT
}
#ifdef GADGET_SUPPORT
void Window::SetGadget(OpGadget* gadget)
{
m_windowCommander->SetGadget(gadget);
era_mode = FALSE;
show_img = TRUE;
load_img = TRUE;
}
OpGadget* Window::GetGadget() const
{
return m_windowCommander->GetGadget();
}
#endif // GADGET_SUPPORT
WindowViewMode Window::GetViewMode()
{
#ifdef GADGET_SUPPORT
if (GetType() == WIN_TYPE_GADGET)
return GetGadget()->GetMode();
#endif // GADGET_SUPPORT
if (IsThumbnailWindow())
return WINDOW_VIEW_MODE_MINIMIZED;
if (IsFullScreen())
return WINDOW_VIEW_MODE_FULLSCREEN;
return WINDOW_VIEW_MODE_WINDOWED;
}
#ifdef SCOPE_PROFILER
OP_STATUS
Window::StartProfiling(OpProfilingSession *session)
{
if (m_profiling_session != NULL)
return OpStatus::ERR;
m_profiling_session = session;
DocumentTreeIterator i(this);
i.SetIncludeThis();
i.SetIncludeEmpty();
while (i.Next())
{
DocumentManager *docman = i.GetDocumentManager();
OP_STATUS status = docman->StartProfiling(session);
if (OpStatus::IsMemoryError(status))
{
StopProfiling();
m_profiling_session = NULL;
return status;
}
}
return OpStatus::OK;
}
void
Window::StopProfiling()
{
if (m_profiling_session == NULL)
return;
m_profiling_session = NULL;
DocumentTreeIterator i(this);
i.SetIncludeThis();
i.SetIncludeEmpty();
while (i.Next())
i.GetDocumentManager()->StopProfiling();
}
#endif // SCOPE_PROFILER
#ifdef GEOLOCATION_SUPPORT
void
Window::NotifyGeolocationAccess()
{
DocumentTreeIterator it(DocManager());
it.SetIncludeThis();
OpAutoStringHashSet hosts_set;
OpVector<uni_char> hosts;
while (it.Next())
{
if (FramesDocument* doc = it.GetFramesDocument())
{
if (doc->GetGeolocationUseCount() == 0)
continue;
const uni_char* hostname = OpSecurityManager::GetHostName(doc->GetURL());
uni_char* hostname_copy = UniSetNewStr(hostname); // Copy because this might use temporary URL buffers.
if (!hostname_copy)
return;
OP_STATUS status = hosts_set.Add(hostname_copy);
if (OpStatus::IsError(status))
{
OP_DELETEA(hostname_copy);
if (status != OpStatus::ERR)
return;
}
}
}
RETURN_VOID_IF_ERROR(hosts_set.CopyAllToVector(hosts));
GetWindowCommander()->GetDocumentListener()->OnGeolocationAccess(GetWindowCommander(), static_cast<OpVector<uni_char>*>(&hosts));
}
#endif // GEOLOCATION_SUPPORT
#ifdef MEDIA_CAMERA_SUPPORT
void
Window::NotifyCameraAccess()
{
DocumentTreeIterator it(DocManager());
it.SetIncludeThis();
OpAutoStringHashSet hosts_set;
OpVector<uni_char> hosts;
while (it.Next())
{
if (FramesDocument* doc = it.GetFramesDocument())
{
if (doc->GetCameraUseCount() == 0)
continue;
const uni_char* hostname = OpSecurityManager::GetHostName(doc->GetURL());
uni_char* hostname_copy = UniSetNewStr(hostname); // Copy because this might use temporary URL buffers.
if (!hostname_copy)
return;
OP_STATUS status = hosts_set.Add(hostname_copy);
if (OpStatus::IsError(status))
{
OP_DELETEA(hostname_copy);
if (status != OpStatus::ERR)
return;
}
}
}
RETURN_VOID_IF_ERROR(hosts_set.CopyAllToVector(hosts));
GetWindowCommander()->GetDocumentListener()->OnCameraAccess(GetWindowCommander(), static_cast<OpVector<uni_char>*>(&hosts));
}
#endif // MEDIA_CAMERA_SUPPORT
#ifdef USE_OP_CLIPBOARD
void Window::OnCopy(OpClipboard* clipboard)
{
FramesDocument* doc = GetActiveFrameDoc();
if (doc)
{
HTML_Document* html_doc = doc->GetHtmlDocument();
#ifdef DOCUMENT_EDIT_SUPPORT
OpDocumentEdit* docedit = doc->GetDocumentEdit();
#endif // DOCUMENT_EDIT_SUPPORT
if (html_doc)
{
if (HTML_Element* elm_with_sel = html_doc->GetElementWithSelection())
{
if (elm_with_sel->IsFormElement())
{
if (FormObject* form_object = elm_with_sel->GetFormObject())
form_object->GetWidget()->OnCopy(clipboard);
}
#ifdef SVG_SUPPORT
else
{
g_svg_manager->Copy(elm_with_sel, clipboard);
}
#endif // SVG_SUPPORT
}
#ifdef DOCUMENT_EDIT_SUPPORT
else if (docedit && docedit->IsFocused())
docedit->OnCopy(clipboard);
#endif // DOCUMENT_EDIT_SUPPORT
else
{
#ifndef HAS_NOTEXTSELECTION
INT32 sel_text_len = html_doc->GetSelectedTextLen();
if (sel_text_len > 0)
{
uni_char* text = OP_NEWA(uni_char, sel_text_len + 1);
if (text && doc->GetSelectedText(text, sel_text_len + 1))
{
clipboard->PlaceText(text, GetUrlContextId());
}
OP_DELETEA(text);
return;
}
#endif // HAS_NOTEXTSELECTION
#ifdef SVG_SUPPORT
if (LogicalDocument* logdoc = doc->GetLogicalDocument())
{
SVGWorkplace* svg_wp = logdoc->GetSVGWorkplace();
if (svg_wp->HasSelectedText())
{
SelectionBoundaryPoint start, end;
if (svg_wp->GetSelection(start, end) && start.GetElement())
{
TempBuffer buffer;
if (g_svg_manager->GetTextSelection(start.GetElement()->ParentActual(), buffer))
{
clipboard->PlaceText(buffer.GetStorage(), GetUrlContextId());
}
}
}
}
#endif // SVG_SUPPORT
}
}
}
}
void Window::OnCut(OpClipboard* clipboard)
{
FramesDocument* doc = GetActiveFrameDoc();
if (doc)
{
HTML_Document* html_doc = doc->GetHtmlDocument();
if (html_doc)
{
if (HTML_Element* elm_with_sel = html_doc->GetElementWithSelection())
{
if (elm_with_sel->IsFormElement())
{
if (FormObject* form_object = elm_with_sel->GetFormObject())
form_object->GetWidget()->OnCut(clipboard);
}
#ifdef SVG_SUPPORT
else
{
g_svg_manager->Cut(elm_with_sel, clipboard);
}
#endif // SVG_SUPPORT
}
#ifdef DOCUMENT_EDIT_SUPPORT
else if (OpDocumentEdit* docedit = doc->GetDocumentEdit())
docedit->OnCut(clipboard);
#endif // DOCUMENT_EDIT_SUPPORT
}
}
}
void Window::OnPaste(OpClipboard* clipboard)
{
FramesDocument* doc = GetActiveFrameDoc();
if (doc)
{
HTML_Document* html_doc = doc->GetHtmlDocument();
if (html_doc)
{
if (HTML_Element* elm_with_sel = html_doc->GetElementWithSelection())
{
if (elm_with_sel->IsFormElement())
{
if (FormObject* form_object = elm_with_sel->GetFormObject())
form_object->GetWidget()->OnPaste(clipboard);
}
#ifdef SVG_SUPPORT
else
{
g_svg_manager->Paste(elm_with_sel, clipboard);
}
#endif // SVG_SUPPORT
}
#ifdef DOCUMENT_EDIT_SUPPORT
else if (OpDocumentEdit* docedit = doc->GetDocumentEdit())
docedit->OnPaste(clipboard);
#endif // DOCUMENT_EDIT_SUPPORT
}
}
}
void Window::OnEnd()
{
FramesDocument* doc = GetActiveFrameDoc();
if (doc)
{
HTML_Document* html_doc = doc->GetHtmlDocument();
if (html_doc)
{
if (HTML_Element* elm_with_sel = html_doc->GetElementWithSelection())
{
if (elm_with_sel->IsFormElement())
{
if (FormObject* form_object = elm_with_sel->GetFormObject())
form_object->GetWidget()->OnEnd();
}
#ifdef SVG_SUPPORT
else
{
g_svg_manager->ClipboardOperationEnd(elm_with_sel);
}
#endif // SVG_SUPPORT
}
#ifdef DOCUMENT_EDIT_SUPPORT
else if (OpDocumentEdit* docedit = doc->GetDocumentEdit())
docedit->OnEnd();
#endif // DOCUMENT_EDIT_SUPPORT
}
}
}
#endif // USE_OP_CLIPBOARD
#ifdef KEYBOARD_SELECTION_SUPPORT
void Window::UpdateKeyboardSelectionMode(BOOL enabled)
{
if (enabled != m_current_keyboard_selection_mode)
{
GetWindowCommander()->GetDocumentListener()->OnKeyboardSelectionModeChanged(GetWindowCommander(), enabled);
m_current_keyboard_selection_mode = enabled;
}
}
#endif // KEYBOARD_SELECTION_SUPPORT
#ifdef EXTENSION_SUPPORT
OP_STATUS
Window::GetDisallowedScreenshotVisualDevices(FramesDocument* target_document, FramesDocument* source_document, OpVector<VisualDevice>& visdevs_to_hide)
{
OpGadget* source_gadget = source_document->GetWindow()->GetGadget();
OP_ASSERT(source_gadget); // only extensions have access to taking a screenshot atm.
DocumentTreeIterator it(target_document);
for (BOOL have_more = it.Next(); have_more; have_more = it.Next())
{
FramesDocElm* elem = it.GetFramesDocElm();
VisualDevice* visdev = elem->GetVisualDevice();
BOOL allowed;
OpSecurityState state;
RETURN_IF_ERROR(g_secman_instance->CheckSecurity(OpSecurityManager::DOM_EXTENSION_ALLOW,
OpSecurityContext(elem->GetCurrentDoc()),
OpSecurityContext(elem->GetCurrentDoc()->GetSecurityContext(), source_gadget),
allowed, state));
OP_ASSERT(!state.suspended);
if (!allowed)
RETURN_IF_ERROR(visdevs_to_hide.Add(visdev));
}
return OpStatus::OK;
}
OP_STATUS
Window::PerformScreenshot(FramesDocument* target_document, FramesDocument* source_document, OpBitmap*& out_bitmap)
{
VisualDevice* vis_dev = target_document->GetVisualDevice();
if (!vis_dev)
return OpStatus::ERR;
OpVector<VisualDevice> visdevs_to_hide;
RETURN_IF_ERROR(GetDisallowedScreenshotVisualDevices(target_document, source_document, visdevs_to_hide));
OpRect rendering_rect = OpRect(0, 0, vis_dev->GetRenderingViewWidth(), vis_dev->GetRenderingViewHeight());
OpBitmap* bitmap = NULL;
RETURN_IF_ERROR(OpBitmap::Create(&bitmap, rendering_rect.width, rendering_rect.height,
FALSE, FALSE, 0, 0, TRUE));
OpPainter* painter = bitmap->GetPainter();
if (painter)
{
painter->SetColor(0, 0, 0, 0);
painter->ClearRect(rendering_rect);
vis_dev->PaintWithExclusion(painter, rendering_rect, visdevs_to_hide);
bitmap->ReleasePainter();
out_bitmap = bitmap;
return OpStatus::OK;
}
else
{
OP_DELETE(bitmap);
return OpStatus::ERR;
}
}
#endif // EXTENSION_SUPPORT
|
#include <QtWidgets/QApplication>
#include "mainwidget.h"
#include "loginwidget.h"
int main(int argc, char **argv)
{
QApplication app(argc, argv);
Window w;
LoginWidget login;
QObject::connect(&login, SIGNAL(authSucceeded(QString)), &w, SLOT(saveToken(QString)));
login.show();
return app.exec();
}
|
/* -*- Mode: c++; tab-width: 4; 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.
*
* @author Arjan van Leeuwen (arjanl)
*/
group "quick_toolkit.widgetcreator";
require init;
include "adjunct/quick_toolkit/widgets/WidgetCreator.h";
global
{
const uni_char* button_widget = UNI_L("Button, SI_OPEN_BUTTON_TEXT, OpenButton, 20, 30, 40, 23, Move right");
class DummyParentWidget : public OpWidget
{
};
};
test("Creates correct button widget when requested")
{
WidgetCreator creator;
creator.SetWidgetData(button_widget);
DummyParentWidget parent;
creator.SetParent(&parent);
OpWidget* widget = creator.CreateWidget();
verify(widget);
verify(widget->GetType() == OpTypedObject::WIDGET_TYPE_BUTTON);
verify(widget->GetStringID() == Str::SI_OPEN_BUTTON_TEXT);
verify(widget->GetName().Compare("OpenButton") == 0);
verify(widget->GetRect().Equals(OpRect(20, 30, 40, 23)));
verify(widget->GetXResizeEffect() == RESIZE_MOVE);
verify(widget->GetYResizeEffect() == RESIZE_FIXED);
};
test("Creates correct checkbox widget when requested")
{
const uni_char* checkbox_widget = UNI_L("Checkbox, DI_ID_OK, OkCheckbox, 10, 15, 20, 25, Size");
WidgetCreator creator;
creator.SetWidgetData(checkbox_widget);
DummyParentWidget parent;
creator.SetParent(&parent);
OpWidget* widget = creator.CreateWidget();
verify(widget);
verify(widget->GetType() == OpTypedObject::WIDGET_TYPE_CHECKBOX);
verify(widget->GetStringID() == Str::DI_ID_OK);
verify(widget->GetName().Compare("OkCheckbox") == 0);
verify(widget->GetRect().Equals(OpRect(10, 15, 20, 25)));
verify(widget->GetXResizeEffect() == RESIZE_SIZE);
verify(widget->GetYResizeEffect() == RESIZE_SIZE);
}
test("Check all widget types")
{
}
test("Assigns actions to widget")
{
const uni_char* button_action = UNI_L("Open");
WidgetCreator creator;
creator.SetWidgetData(button_widget);
creator.SetActionData(button_action);
DummyParentWidget parent;
creator.SetParent(&parent);
OpWidget* widget = creator.CreateWidget();
verify(widget);
verify(widget->GetAction());
verify(widget->GetAction()->GetAction() == OpInputAction::ACTION_OPEN);
};
|
#include "stratified_resample.h" // import file to test
#include <cmath>
#include "ut.hpp"
using namespace boost::ut;
using namespace boost::ut::bdd;
int main() {
srand(1994);
"stratified_resample"_test = [] {
given("Working stratified_random function and calling with w, N_w, Neff, keep") = [] {
const size_t N_w = 5;
double w[N_w] = {2,4,6,8,10}; //unnormalized weights
double Neff = 10.0; //Just written to this variable
size_t keep[N_w] = {100,100,100,100,100}; //Just written to this variable
when("I call stratified_resample(w, N_w, &Neff, keep) with a fixed seed") = [&] {
stratified_resample(w, N_w, &Neff, keep);
then("I get the the outputs w, Neff and keep I want") = [=] {
double exact_Neff = 4.090909090909;
double target_w[N_w] = {2,4,6,8,10};
size_t exact_keep[N_w] = {1,2,3,4,4};
for (int i = 0; i < N_w; i++) {
double error_w = fabs(w[i]-target_w[i]);
expect(that % error_w < 1e-12) << i;
expect(that % keep[i] == exact_keep[i]) << i;
}
expect(that % fabs(Neff - exact_Neff) < 1.0e-12) <<"Neff error";
};
};
};
};
};
|
#pragma once
class AIEditMode;
class AIEditNode;
class AIEditNodeInequ;
class AIEditNodeNum;
class AIEditNodeClick;
class AIEditLine;
class GameCursor;
class AIEditNodeTarget;
class AIEditNodeProcess;
class AIEditNodeTechnique;
class AIEditNodeAbnormalState;
class AIEditNodeSelectFonts;
class AIEditNodeDeleteKey;
enum eTarget {
enme = 100,
enbaddy,
enenemy,
enTAnull = 0,
};
enum eNode {
enHp = 200,
enMp,
enAb,
enTechnique,
enNonull = 0,
};
enum eInequ {
enDainari = 300,
enShowers,
enINnull = 0,
};
enum eNum {
en1 = 400,
en10,
en30,
en50,
en70,
en90,
en100,
enNUnull = 0
};
enum eTechnique {
enAttak = 500,
enLeav,
enCase,
enProtect,
enHeel,
enSpecial1,
enSpecial2,
enTEnull = 0,
};
enum eAbnormal {
endoku = 600,
enyakedo,
enhyouketu,
ensutan,
enABnull = 0,
};
struct sOrder
{
eTarget tar = enTAnull;
eNode nod = enNonull;
eInequ ine = enINnull;
eNum num = enNUnull;
eTechnique tec = enTEnull;
eAbnormal abn = enABnull;
};
class AIEditNodeOrder :public GameObject
{
public:
~AIEditNodeOrder();
void OnDestroy();
bool Start() override final;
void Update() override final;
void DeleteGOs();
void Fonts();
void makeOrder(int l,int o,sOrder* order,bool isEnd=false);
void makeFonts(sOrder* order);
AIEditNodeDeleteKey* CreateDeleteKey();
bool GetTec()
{
return Technique;
}
void SetTec(bool a)
{
Technique = a;
}
CVector3 GetPos()
{
return m_pos;
}
bool isTechniqueOrder()
{
return techniqueOrder;
}
bool GetNextClickFlag()
{
return NextClickFlag;
}
void SetNextClickFlag(bool a)
{
NextClickFlag = a;
}
private:
int num = 1;
int fonttimer = 25; //上に表示されている確認用のfontを
bool Technique = false; //技を選択したときtrueになる。
bool techniqueOrder = false;
bool timer = false;
bool key = false; //deletekeyに何かが入ったらtrueになる。
bool NextClickFlag = false; //Deletekeyを使って列をDeleteしたと気にtrueになる。
bool m_isMakeOrder = false; //makeOrderした場合はStart等を無視するためのフラグ
float scale = 0.7; //fontのスケール。
CVector2 SetShadowPos = { 5.f,-5.f }; //フォントの影の座標。
CVector3 m_pos = CVector3::Zero();
AIEditNodeDeleteKey* m_keepdelete[8];
std::vector<FontRender*> m_fonts;
SpriteRender* m_spriteRender = nullptr;
GameCursor * m_gamecursor = nullptr;
AIEditMode * m_aieditmode = nullptr;
AIEditNode * m_aieditnode = nullptr;
AIEditNodeInequ * m_aieditnodeinequ = nullptr;
AIEditNodeNum * m_aieditnodenum = nullptr;
AIEditNodeClick* m_aieditnodeclick = nullptr;
AIEditLine * m_aieditline = nullptr;
AIEditNodeTarget* m_aieditnodetarget = nullptr;
AIEditNodeProcess* m_aieditnodeprocess = nullptr;
AIEditNodeTechnique* m_aieditnodetechnique = nullptr;
AIEditNodeAbnormalState* m_aieditnodeabnormalstate = nullptr;
AIEditNodeSelectFonts* m_aieditonodeselectfonts = nullptr;
AIEditNodeDeleteKey* m_aieditnodedeletekey = nullptr;
};
|
/*
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.
*/
#include "multiplication_setup.hpp"
#include "logger.hpp"
#include "multiplication.hpp"
#include "multiplication_interface.hpp"
using orkhestrafs::dbmstodspi::MultiplicationSetup;
using orkhestrafs::dbmstodspi::Multiplication;
using orkhestrafs::dbmstodspi::MultiplicationInterface;
using orkhestrafs::dbmstodspi::logging::Log;
using orkhestrafs::dbmstodspi::logging::LogLevel;
void MultiplicationSetup::SetupModule(
AccelerationModule& acceleration_module,
const AcceleratedQueryNode& module_parameters) {
Log(LogLevel::kInfo,
"Configuring multiplication on pos " +
std::to_string(module_parameters.operation_module_location));
MultiplicationSetup::SetupMultiplicationModule(
dynamic_cast<MultiplicationInterface&>(acceleration_module),
{module_parameters.input_streams[0].stream_id},
module_parameters.operation_parameters);
}
auto MultiplicationSetup::CreateModule(MemoryManagerInterface* memory_manager,
int module_postion)
-> std::unique_ptr<AccelerationModule> {
return std::make_unique<Multiplication>(memory_manager, module_postion);
}
void MultiplicationSetup::SetupMultiplicationModule(
MultiplicationInterface& multiplication_module,
const std::vector<int>& active_stream_ids,
const std::vector<std::vector<int>>& operation_parameters) {
std::bitset<16> active_streams;
for (const auto& active_stream_id : active_stream_ids) {
active_streams.set(active_stream_id, true);
}
multiplication_module.DefineActiveStreams(active_streams);
if (active_stream_ids.size() == 1 && active_stream_ids.front() == 15) {
// skip
} else {
for (const auto& multiplication_selections : operation_parameters) {
std::bitset<8> selected_positions;
for (int position = 0; position < 8; position++) {
selected_positions.set(position,
multiplication_selections.at(8 - position) != 0);
}
multiplication_module.ChooseMultiplicationResults(
multiplication_selections.at(0), selected_positions);
}
}
}
|
#include <cstdio>
#include <cstdlib>
int main(int argc, const char *argv[])
{
const int N = atoi(argv[1]);
FILE *f = fopen(argv[2], "rb");
int *x = new int[2147483647];
for (int i = 0; i < N; i++) {
int x;
fread(&x, sizeof(int), 1, f);
printf("Origin : %d\n", x);
}
delete [] x ;
fclose(f);
return 0;
}
|
#pragma once
#include "stdafx.h"
#include "skeleton.h"
#include "MeshCutting.h"
#include "TransformerSkeleton.h"
enum AnimationStep{
CONNECTING_BONE_ROTATION,
CONNECTING_BONE_LENGTH,
BONE_SHELL_ROTATION,
DONE,
NUM_ANIMATION_STEPS
};
enum AnimationMode{
PLAY_ANIMATION,
PAUSE_ANIMATION,
RESTART_ANIMATION,
ANIMATION_MODE_SIZE
};
class TransformerAnimation
{
public:
TransformerAnimation();
~TransformerAnimation();
MeshCutting * m_mesh;
skeleton *m_skel;
TransformerSkeleton *transformer;
private:
bool startAnimation;
bool pauseAnimation;
bool animationDone;
float animationAmt;
float speed;
int currentBoneIdx;
AnimationStep boneAnimationStage;
bool showSkeleton;
bool showMesh;
public:
TransformerBone *currentBone;
bool posAnimated[NUM_ANIMATION_STEPS];
// Animation methods to set animation status
void stopAnimation();
void playAnimation();
void restartAnimation();
// Animation control
void animateTransformer(bool displayMode[2], float spd);
private:
void unfoldTransformer(TransformerBone *target, TransformerBone *node, float amt);
void drawBoneBasedOnDisplayMode(TransformerBone *node, float boneLength);
void drawConnectingBoneBasedOnDisplayMode(TransformerBone *node, float boneLength);
void setDisplayMode(bool mode[2]);
};
|
#include "../Solution.h"
Node *Solution::connect(Node *root)
{
}
|
#include "widget.h"
Widget::Widget(QWidget *parent) : QWidget(parent)
{
layout_main = new QGridLayout(this);
layout_vehicule = new QBoxLayout(QBoxLayout::TopToBottom);
layout_main->addLayout(layout_vehicule, 0, 0);
layout_aboutIt = new QBoxLayout(QBoxLayout::TopToBottom);
layout_main->addLayout(layout_vehicule, 0, 1);
vehicule_vector_info = new vector<VehiculeWidget*>;
for (unsigned i=0;i<5 ;i++ ) {
vehicule_vector_info->push_back(new VehiculeWidget);
layout_vehicule->addWidget(vehicule_vector_info->at(i));
}
QLabel* test001 = new QLabel(QString("012154\n59741"));
layout_aboutIt->addWidget(test001);
}
Widget::~Widget()
{
//delete layout_main;
//delete vehicule_vector_info[0];
/*
for (unsigned int i = 0; i < vehicule_vector_info.size(); i++) //clean
{
delete vehicule_vector_info[i];
vehicule_vector_info[i] = nullptr;
vehicule_vector_info.pop_back();
}
*/
}
void Widget::update_layout_vehicule()
{
//for (unsigned i=0, i < )
}
|
#include "moves.h"
#include <iostream>
#include <string>
moves::moves()
{
moveName;
moveType;
moveDamage;
}
void moves::setFireSpin()
{
moveName = "Fire Spin";
moveType = "Fire";
moveDamage = 4;
}
void moves::setFlamethrower()
{
moveName = "Flamethrower";
moveType = "Fire";
moveDamage = 10;
}
void moves::setBubbleBeam()
{
moveName = "Bubble Beam";
moveType = "Water";
moveDamage = 6;
}
void moves::setQuickAttack()
{
moveName = "Quick Attack";
moveType = "Normal";
moveDamage = 6;
}
void moves::setHyperBeam()
{
moveName = "Hyper Beam";
moveType = "Normal";
moveDamage = 15;
}
void moves::setThunderPunch()
{
moveName = "Thunder Punch";
moveType = "Electric";
moveDamage = 6;
}
void moves::setRazorLeaf()
{
moveName = "Razor Leaf";
moveType = "Grass";
moveDamage = 8;
}
void moves::setScratch()
{
moveName = "Scratch";
moveType = "Normal";
moveDamage = 6;
}
void moves::setVineWhip()
{
moveName = "Vine Whip";
moveType = "Grass";
moveDamage = 6;
}
void moves::setSolarBeam()
{
moveName = "Solar Beam";
moveType = "Grass";
moveDamage = 15;
}
void moves::setRockThrow()
{
moveName = "Rock Throw";
moveType = "Rock";
moveDamage = 8;
}
void moves::setStoneEdge()
{
moveName = "Stone Edge";
moveType = "Rock";
moveDamage = 15;
}
void moves::setThunder()
{
moveName = "Thunder";
moveType = "Electric";
moveDamage = 15;
}
void moves::setHydropump()
{
moveName = "HydroPump";
moveType = "Water";
moveDamage = 15;
}
|
#pragma once
#include <string>
#include <tuple>
#include <span>
#include "ShaderCommon.h"
#include <VeritasMath.h>
struct DumbVertex
{
dx::XMVECTOR data[16];
SV_VertexID SV_VertexID;
};
struct DumbVSOut
{
dx::XMVECTOR attributes[16];
uint32_t reserved; //not in use
};
struct DumbPSOut
{
uint32_t SV_Target;
};
template<class...>struct types { using type = types; };
template<class out, class...Args>struct xtypes { using type = types<Args...>; using Out_t = out; };
template<class Sig> struct args;
template<class Out, class M, class...Args>
struct args<Out(M::*)(Args...)> :xtypes<Out, Args...> {};
template<class Sig> using args_t = typename args<Sig>::type;
template<class Sig> using out_t = typename args<Sig>::Out_t;
template<class T, class C>
constexpr T determine(const dx::XMVECTOR target, SV_VertexID vid)
{
if constexpr (std::is_same_v<T, C>)
{
return vid;
}
else
{
return target;
}
}
template <class... Formats, size_t N, size_t... Is>
constexpr std::tuple<Formats...> as_tuple(std::span<const dx::XMVECTOR, N> arr, SV_VertexID vid,
std::index_sequence<Is...>)
{
return std::make_tuple(std::forward<Formats>(determine<Formats, SV_VertexID>(arr[Is], vid))...);
}
template <class... Formats, size_t N>
constexpr std::tuple<Formats...> as_tuple(types<Formats...>, std::span<const dx::XMVECTOR, N> arr, SV_VertexID vid = 0)
{
return as_tuple<Formats...>(arr, vid, std::make_index_sequence<sizeof...(Formats)>{});
}
struct ShaderBase : public wrl::RuntimeClass<wrl::RuntimeClassFlags<wrl::ClassicCom>, IVShader>
{
};
template<class T>
struct VertexShader : public ShaderBase
{
public:
VertexShader() = default;
public:
void __stdcall Invoke(const void* vs_in, void* _out_vertex)override
{
using RQVSOutT = out_t<decltype(&T::main)>;
const auto& in = *static_cast<const DumbVertex*>(vs_in);
auto& out = *static_cast<DumbVSOut*>(_out_vertex);
RQVSOutT x = std::apply(&T::main,
std::tuple_cat(std::make_tuple(reinterpret_cast<T*>(this)), as_tuple(args_t<decltype(&T::main)>{}, std::span(in.data), in.SV_VertexID)));
std::copy((std::byte*)&x, (std::byte*)&x + sizeof(x), (std::byte*)&out.attributes);
}
constexpr void __stdcall GetShaderPrivateData(ShaderPrivateData* _out_pdata)override
{
using RQVSOutT = out_t<decltype(&T::main)>;
_out_pdata->VertexSize = sizeof(RQVSOutT) / 16;
if constexpr (sizeof(RQVSOutT) == sizeof(float4A))
{
_out_pdata->PositionIndex = 0;
}
else
{
static_assert(alignof(decltype(RQVSOutT::SV_Position)) == alignof(float4A));
static_assert(sizeof(RQVSOutT::SV_Position) == sizeof(float4A));
_out_pdata->PositionIndex = offsetof(RQVSOutT, SV_Position) / 16;
}
}
};
template<class T>
struct PixelShader : public ShaderBase
{
public:
PixelShader() = default;
public:
void __stdcall Invoke(const void* ps_in, void* _out_vertex)override
{
using RQPSOutT = out_t<decltype(&T::main)>;
const DumbVSOut& in = *static_cast<const DumbVSOut*>(ps_in);
DumbPSOut& out = *static_cast<DumbPSOut*>(_out_vertex);
static_assert(sizeof(RQPSOutT) == sizeof(float4));
RQPSOutT x = std::apply(&T::main,
std::tuple_cat(std::make_tuple(reinterpret_cast<T*>(this)), as_tuple(args_t<decltype(&T::main)>{}, std::span(in.attributes))));
dx::PackedVector::XMStoreColor((dx::PackedVector::XMCOLOR*)&out.SV_Target, x);
}
constexpr void __stdcall GetShaderPrivateData(ShaderPrivateData* _out_pdata)override
{
_out_pdata->VertexSize = 1;
}
};
|
//
// ThreadManager.hpp
// Fishnap
//
// Created by 山内一祥 on 2019/09/04.
// Copyright © 2019 Crux One. All rights reserved.
//
#ifndef ThreadManager_hpp
#define ThreadManager_hpp
#include <iostream>
#include <stdio.h>
#include <thread>
#include <vector>
class ThreadManager {
public:
void run(std::vector<std::thread>& threads);
ThreadManager();
~ThreadManager() = default;
};
#endif /* ThreadManager_hpp */
|
#include <iostream>
#include <exception>
class DocElementVisitor;
class DocElement {
public:
virtual void Accept(DocElementVisitor&) = 0;
virtual ~DocElement() {}
};
class Paragraph : public DocElement {
public:
void Accept(DocElementVisitor& v) override;
unsigned int NumChars() const { return 1; }
unsigned int NumWords() const { return 5; }
void SetFontSize(int);
int GetFontSize();
private:
int fontSize_;
};
class RasterBitmap : public DocElement {
public:
void Accept(DocElementVisitor& v) override;
};
class DocElementVisitor {
public:
virtual void Visit(Paragraph&) = 0;
virtual void Visit(RasterBitmap&) = 0;
virtual void Visit(DocElement&) = 0;
};
class DocStats : public DocElementVisitor {
public:
void Visit(Paragraph& par) override {
chars_ += par.NumChars();
words_ += par.NumWords();
}
void Visit(RasterBitmap&) override {
++images_;
}
void Print() const {
std::cout << chars_ << " " << words_ << " " << images_ << std::endl;
}
void Visit(DocElement&) override {
throw std::runtime_error{"unimplemented"};
}
private:
unsigned int chars_{0},
words_{0},
images_{0};
};
void Paragraph::Accept(DocElementVisitor& v) {
v.Visit(*this);
}
void Paragraph::SetFontSize(int size) {
fontSize_ = size;
}
int Paragraph::GetFontSize() {
return fontSize_;
}
void RasterBitmap::Accept(DocElementVisitor& v) {
v.Visit(*this);
}
class IncrementFontSize : public DocElementVisitor {
public:
void Visit(Paragraph& par) override {
par.SetFontSize(par.GetFontSize() + 1);
}
void Visit(RasterBitmap&) override {
// do nothing
}
};
|
/*---------------------------------------------------------------------------------------*
* *
* Library name: (M)otor 28BYJ48 Vs 1 *
* Author: Marco Palladino - marck.palladino@gmail.com *
* Start date: 04.02.2018 (first beta version) *
* Last Update: 11.03.2018 *
* *
* This work is licensed under the Creative Commons Attribution- *
* Attribution-ShareAlike 4.0 International (CC BY-SA 4.0). *
* To view a copy of this license, *
* visit http://creativecommons.org/licenses/by-sa/4.0/ or send a *
* letter to Creative Commons, 171 Second Street, Suite 300, *
* San Francisco, California, 94105, USA. *
* *
* *
* Step Command IN4 IN3 IN2 IN1 *
* A 01H 0 0 0 1 *
* AB 03H 0 0 1 1 *
* B 02H 0 0 1 0 *
* BC 06H 0 1 1 0 *
* C 04H 0 1 0 0 *
* CD 0CH 1 1 0 0 *
* D 08H 1 0 0 0 *
* DA 09H 1 0 0 1 *
* *
* *
*---------------------------------------------------------------------------------------*/
#ifndef M28BYJ48_h
#define M28BYJ48_h
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
typedef enum Motor {A, AB, B, BC, C, CD, D, DA, MOTOR_OFF};
typedef enum m_dir {CW, CCW};
// library interface description
class M28BYJ48 {
public:
// constructor:
M28BYJ48(int steps_for_rev, int pin_1, int pin_2,
int pin_3, int pin_4);
// mover method:
void tuning (unsigned int rpm); // set rpm
// don't set rpm if your add code generate a step pulse and acceleratoon curve (ex grbl)
void moveSteps (unsigned long steps, m_dir direction); // move in steps
void moveDeg (float deg, m_dir direction); // move in degree
void moveMm (float mm, m_dir direction); // next upgrade move in mm
void motorStop (void); // stop motor
int version(void);
private:
void logicOut( int pin_4,int pin_3,int pin_2,int pin_1);
void step(Motor phase);
int steps_for_rev;
m_dir direction;
unsigned long step_pulse;
unsigned long last_time;
Motor phase;
// motor pin numbers:
int pin_1;
int pin_2;
int pin_3;
int pin_4;
};
#endif // M28BYJ48_h
|
// You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
// Merge nums1 and nums2 into a single array sorted in non-decreasing order.
// The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
// Example 1:
// Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
// Output: [1,2,2,3,5,6]
// Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
// The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
// Example 2:
// Input: nums1 = [1], m = 1, nums2 = [], n = 0
// Output: [1]
// Explanation: The arrays we are merging are [1] and [].
// The result of the merge is [1].
// Example 3:
// Input: nums1 = [0], m = 0, nums2 = [1], n = 1
// Output: [1]
// Explanation: The arrays we are merging are [] and [1].
// The result of the merge is [1].
// Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
// Constraints:
// nums1.length == m + n
// nums2.length == n
// 0 <= m, n <= 200
// 1 <= m + n <= 200
// -109 <= nums1[i], nums2[j] <= 109
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int i,j;
for(i=m,j=0;i<(m+n);i++,j++){
nums1[i]=nums2[j]; // num2 is added to num1
}
sort(nums1.begin(),nums1.end()); // now just simply sort it
}
};
|
// Created on: 1993-03-24
// Created by: JCV
// Copyright (c) 1993-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 _Geom2d_TrimmedCurve_HeaderFile
#define _Geom2d_TrimmedCurve_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <Geom2d_BoundedCurve.hxx>
#include <GeomAbs_Shape.hxx>
#include <Standard_Integer.hxx>
class Geom2d_Curve;
class gp_Pnt2d;
class gp_Vec2d;
class gp_Trsf2d;
class Geom2d_Geometry;
class Geom2d_TrimmedCurve;
DEFINE_STANDARD_HANDLE(Geom2d_TrimmedCurve, Geom2d_BoundedCurve)
//! Defines a portion of a curve limited by two values of
//! parameters inside the parametric domain of the curve.
//! The trimmed curve is defined by:
//! - the basis curve, and
//! - the two parameter values which limit it.
//! The trimmed curve can either have the same
//! orientation as the basis curve or the opposite orientation.
class Geom2d_TrimmedCurve : public Geom2d_BoundedCurve
{
public:
//! Creates a trimmed curve from the basis curve C limited between
//! U1 and U2.
//!
//! . U1 can be greater or lower than U2.
//! . The returned curve is oriented from U1 to U2.
//! . If the basis curve C is periodic there is an ambiguity
//! because two parts are available. In this case by default
//! the trimmed curve has the same orientation as the basis
//! curve (Sense = True). If Sense = False then the orientation
//! of the trimmed curve is opposite to the orientation of the
//! basis curve C.
//! If the curve is closed but not periodic it is not possible
//! to keep the part of the curve including the junction point
//! (except if the junction point is at the beginning or
//! at the end of the trimmed curve) because you could lose the
//! fundamental characteristics of the basis curve which are
//! used for example to compute the derivatives of the trimmed
//! curve. So for a closed curve the rules are the same as for
//! a open curve.
//! Warnings :
//! In this package the entities are not shared. The TrimmedCurve is
//! built with a copy of the curve C. So when C is modified the
//! TrimmedCurve is not modified
//! Warnings :
//! If <C> is periodic and <theAdjustPeriodic> is True, parametrics
//! bounds of the TrimmedCurve, can be different to [<U1>;<U2>},
//! if <U1> or <U2> are not in the principal period.
//! Include :
//! For more explanation see the scheme given with this class.
//! Raises ConstructionError the C is not periodic and U1 or U2 are out of
//! the bounds of C.
//! Raised if U1 = U2.
Standard_EXPORT Geom2d_TrimmedCurve(const Handle(Geom2d_Curve)& C, const Standard_Real U1, const Standard_Real U2, const Standard_Boolean Sense = Standard_True, const Standard_Boolean theAdjustPeriodic = Standard_True);
//! Changes the direction of parametrization of <me>. The first and
//! the last parametric values are modified. The "StartPoint"
//! of the initial curve becomes the "EndPoint" of the reversed
//! curve and the "EndPoint" of the initial curve becomes the
//! "StartPoint" of the reversed curve.
//! Example - If the trimmed curve is defined by:
//! - a basis curve whose parameter range is [ 0.,1. ], and
//! - the two trim values U1 (first parameter) and U2 (last parameter),
//! the reversed trimmed curve is defined by:
//! - the reversed basis curve, whose parameter range is still [ 0.,1. ], and
//! - the two trim values 1. - U2 (first parameter)
//! and 1. - U1 (last parameter).
Standard_EXPORT void Reverse() Standard_OVERRIDE;
//! Returns the parameter on the reversed curve for
//! the point of parameter U on <me>.
//!
//! returns UFirst + ULast - U
Standard_EXPORT Standard_Real ReversedParameter (const Standard_Real U) const Standard_OVERRIDE;
//! Changes this trimmed curve, by redefining the
//! parameter values U1 and U2, which limit its basis curve.
//! Note: If the basis curve is periodic, the trimmed curve
//! has the same orientation as the basis curve if Sense
//! is true (default value) or the opposite orientation if Sense is false.
//! Warning
//! If the basis curve is periodic and theAdjustPeriodic is True,
//! the bounds of the trimmed curve may be different from U1 and U2 if the
//! parametric origin of the basis curve is within the arc
//! of the trimmed curve. In this case, the modified
//! parameter will be equal to U1 or U2 plus or minus the period.
//! If theAdjustPeriodic is False, parameters U1 and U2 will stay unchanged.
//! Exceptions
//! Standard_ConstructionError if:
//! - the basis curve is not periodic, and either U1 or U2
//! are outside the bounds of the basis curve, or
//! - U1 is equal to U2.
Standard_EXPORT void SetTrim (const Standard_Real U1, const Standard_Real U2, const Standard_Boolean Sense = Standard_True, const Standard_Boolean theAdjustPeriodic = Standard_True);
//! Returns the basis curve.
//! Warning
//! This function does not return a constant reference.
//! Consequently, any modification of the returned value
//! directly modifies the trimmed curve.
Standard_EXPORT Handle(Geom2d_Curve) BasisCurve() const;
//! Returns the global continuity of the basis curve of this trimmed curve.
//! C0 : only geometric continuity,
//! C1 : continuity of the first derivative all along the Curve,
//! C2 : continuity of the second derivative all along the Curve,
//! C3 : continuity of the third derivative all along the Curve,
//! CN : the order of continuity is infinite.
Standard_EXPORT GeomAbs_Shape Continuity() const Standard_OVERRIDE;
//! --- Purpose
//! Returns True if the order of continuity of the
//! trimmed curve is N. A trimmed curve is at least "C0" continuous.
//! Warnings :
//! The continuity of the trimmed curve can be greater than
//! the continuity of the basis curve because you consider
//! only a part of the basis curve.
//! Raised if N < 0.
Standard_EXPORT Standard_Boolean IsCN (const Standard_Integer N) const Standard_OVERRIDE;
//! Returns the end point of <me>. This point is the
//! evaluation of the curve for the "LastParameter".
Standard_EXPORT gp_Pnt2d EndPoint() const Standard_OVERRIDE;
//! Returns the value of the first parameter of <me>.
//! The first parameter is the parameter of the "StartPoint"
//! of the trimmed curve.
Standard_EXPORT Standard_Real FirstParameter() const Standard_OVERRIDE;
//! Returns True if the distance between the StartPoint and
//! the EndPoint is lower or equal to Resolution from package
//! gp.
Standard_EXPORT Standard_Boolean IsClosed() const Standard_OVERRIDE;
//! Always returns FALSE (independently of the type of basis curve).
Standard_EXPORT Standard_Boolean IsPeriodic() const Standard_OVERRIDE;
//! Returns the period of the basis curve of this trimmed curve.
//! Exceptions
//! Standard_NoSuchObject if the basis curve is not periodic.
Standard_EXPORT virtual Standard_Real Period() const Standard_OVERRIDE;
//! Returns the value of the last parameter of <me>.
//! The last parameter is the parameter of the "EndPoint" of the
//! trimmed curve.
Standard_EXPORT Standard_Real LastParameter() const Standard_OVERRIDE;
//! Returns the start point of <me>.
//! This point is the evaluation of the curve from the
//! "FirstParameter".
//! value and derivatives
//! Warnings :
//! The returned derivatives have the same orientation as the
//! derivatives of the basis curve.
Standard_EXPORT gp_Pnt2d StartPoint() const Standard_OVERRIDE;
//! If the basis curve is an OffsetCurve sometimes it is not
//! possible to do the evaluation of the curve at the parameter
//! U (see class OffsetCurve).
Standard_EXPORT void D0 (const Standard_Real U, gp_Pnt2d& P) const Standard_OVERRIDE;
//! Raised if the continuity of the curve is not C1.
Standard_EXPORT void D1 (const Standard_Real U, gp_Pnt2d& P, gp_Vec2d& V1) const Standard_OVERRIDE;
//! Raised if the continuity of the curve is not C2.
Standard_EXPORT void D2 (const Standard_Real U, gp_Pnt2d& P, gp_Vec2d& V1, gp_Vec2d& V2) const Standard_OVERRIDE;
//! Raised if the continuity of the curve is not C3.
Standard_EXPORT void D3 (const Standard_Real U, gp_Pnt2d& P, gp_Vec2d& V1, gp_Vec2d& V2, gp_Vec2d& V3) const Standard_OVERRIDE;
//! For the point of parameter U of this trimmed curve,
//! computes the vector corresponding to the Nth derivative.
//! Warning
//! The returned derivative vector has the same
//! orientation as the derivative vector of the basis curve,
//! even if the trimmed curve does not have the same
//! orientation as the basis curve.
//! Exceptions
//! Standard_RangeError if N is less than 1.
//! geometric transformations
Standard_EXPORT gp_Vec2d DN (const Standard_Real U, const Standard_Integer N) const Standard_OVERRIDE;
//! Applies the transformation T to this trimmed curve.
//! Warning The basis curve is also modified.
Standard_EXPORT void Transform (const gp_Trsf2d& T) Standard_OVERRIDE;
//! Returns the parameter on the transformed curve for
//! the transform of the point of parameter U on <me>.
//!
//! me->Transformed(T)->Value(me->TransformedParameter(U,T))
//!
//! is the same point as
//!
//! me->Value(U).Transformed(T)
//!
//! This methods calls the basis curve method.
Standard_EXPORT virtual Standard_Real TransformedParameter (const Standard_Real U, const gp_Trsf2d& T) const Standard_OVERRIDE;
//! Returns a coefficient to compute the parameter on
//! the transformed curve for the transform of the
//! point on <me>.
//!
//! Transformed(T)->Value(U * ParametricTransformation(T))
//!
//! is the same point as
//!
//! Value(U).Transformed(T)
//!
//! This methods calls the basis curve method.
Standard_EXPORT virtual Standard_Real ParametricTransformation (const gp_Trsf2d& T) const Standard_OVERRIDE;
//! Creates a new object, which is a copy of this trimmed curve.
Standard_EXPORT Handle(Geom2d_Geometry) Copy() const Standard_OVERRIDE;
//! Dumps the content of me into the stream
Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(Geom2d_TrimmedCurve,Geom2d_BoundedCurve)
protected:
private:
Handle(Geom2d_Curve) basisCurve;
Standard_Real uTrim1;
Standard_Real uTrim2;
};
#endif // _Geom2d_TrimmedCurve_HeaderFile
|
#pragma once
class Date
{
public:
Date();
bool isequal(char*, char*);
int dateraznost(char*);
int raznost(char*, char*);
bool compare(char*, char*);
~Date();
};
|
// Created on: 2009-04-06
// Created by: Sergey ZARITCHNY
// Copyright (c) 2009-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 _TDataXtd_Presentation_HeaderFile
#define _TDataXtd_Presentation_HeaderFile
#include <Standard.hxx>
#include <Standard_GUID.hxx>
#include <gp_Pnt.hxx>
#include <TDF_Attribute.hxx>
#include <Quantity_NameOfColor.hxx>
#include <TColStd_ListOfInteger.hxx>
class TDF_Label;
class TDF_RelocationTable;
class TDataXtd_Presentation;
DEFINE_STANDARD_HANDLE(TDataXtd_Presentation, TDF_Attribute)
//! Attribute containing parameters of presentation of the shape,
//! e.g. the shape attached to the same label and displayed using
//! TPrsStd tools (see TPrsStd_AISPresentation).
class TDataXtd_Presentation : public TDF_Attribute
{
public:
//!@name Attribute mechanics
//! Empty constructor
Standard_EXPORT TDataXtd_Presentation();
//! Create if not found the TDataXtd_Presentation attribute and set its driver GUID
Standard_EXPORT static Handle(TDataXtd_Presentation) Set(const TDF_Label& theLabel, const Standard_GUID& theDriverId);
//! Remove attribute of this type from the label
Standard_EXPORT static void Unset(const TDF_Label& theLabel);
//! Returns the ID of the attribute.
Standard_EXPORT const Standard_GUID& ID() const Standard_OVERRIDE;
//! Returns the ID of the attribute.
Standard_EXPORT static const Standard_GUID& GetID();
//! Restores the contents from <anAttribute> into this
//! one. It is used when aborting a transaction.
Standard_EXPORT virtual void Restore (const Handle(TDF_Attribute)& anAttribute) Standard_OVERRIDE;
//! Returns an new empty attribute from the good end
//! type. It is used by the copy algorithm.
Standard_EXPORT virtual Handle(TDF_Attribute) NewEmpty() const Standard_OVERRIDE;
//! This method is different from the "Copy" one,
//! because it is used when copying an attribute from
//! a source structure into a target structure. This
//! method pastes the current attribute to the label
//! corresponding to the insertor. The pasted
//! attribute may be a brand new one or a new version
//! of the previous one.
Standard_EXPORT virtual void Paste (const Handle(TDF_Attribute)& intoAttribute,
const Handle(TDF_RelocationTable)& aRelocTationable) const Standard_OVERRIDE;
Standard_EXPORT Handle(TDF_Attribute) BackupCopy() const Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(TDataXtd_Presentation,TDF_Attribute)
public:
//!@name Access to data
//! Returns the GUID of the driver managing display of associated AIS object
Standard_EXPORT Standard_GUID GetDriverGUID() const;
//! Sets the GUID of the driver managing display of associated AIS object
Standard_EXPORT void SetDriverGUID(const Standard_GUID& theGUID);
Standard_EXPORT Standard_Boolean IsDisplayed() const;
Standard_EXPORT Standard_Boolean HasOwnMaterial() const;
Standard_EXPORT Standard_Boolean HasOwnTransparency() const;
Standard_EXPORT Standard_Boolean HasOwnColor() const;
Standard_EXPORT Standard_Boolean HasOwnWidth() const;
Standard_EXPORT Standard_Boolean HasOwnMode() const;
Standard_EXPORT Standard_Boolean HasOwnSelectionMode() const;
Standard_EXPORT void SetDisplayed(const Standard_Boolean theIsDisplayed);
Standard_EXPORT void SetMaterialIndex(const Standard_Integer theMaterialIndex);
Standard_EXPORT void SetTransparency(const Standard_Real theValue);
Standard_EXPORT void SetColor(const Quantity_NameOfColor theColor);
Standard_EXPORT void SetWidth(const Standard_Real theWidth);
Standard_EXPORT void SetMode(const Standard_Integer theMode);
//! Returns the number of selection modes of the attribute.
//! It starts with 1 .. GetNbSelectionModes().
Standard_EXPORT Standard_Integer GetNbSelectionModes() const;
//! Sets selection mode.
//! If "theTransaction" flag is OFF, modification of the attribute doesn't influence the transaction mechanism
//! (the attribute doesn't participate in undo/redo because of this modification).
//! Certainly, if any other data of the attribute is modified (display mode, color, ...),
//! the attribute will be included into undo/redo.
Standard_EXPORT void SetSelectionMode(const Standard_Integer theSelectionMode, const Standard_Boolean theTransaction = Standard_True);
Standard_EXPORT void AddSelectionMode(const Standard_Integer theSelectionMode, const Standard_Boolean theTransaction = Standard_True);
Standard_EXPORT Standard_Integer MaterialIndex() const;
Standard_EXPORT Standard_Real Transparency() const;
Standard_EXPORT Quantity_NameOfColor Color() const;
Standard_EXPORT Standard_Real Width() const;
Standard_EXPORT Standard_Integer Mode() const;
Standard_EXPORT Standard_Integer SelectionMode(const int index = 1) const;
Standard_EXPORT void UnsetMaterial();
Standard_EXPORT void UnsetTransparency();
Standard_EXPORT void UnsetColor();
Standard_EXPORT void UnsetWidth();
Standard_EXPORT void UnsetMode();
Standard_EXPORT void UnsetSelectionMode();
public:
//! Convert values of old Quantity_NameOfColor to new enumeration for reading old documents
//! after #0030969 (Coding Rules - refactor Quantity_Color.cxx color table definition).
Standard_EXPORT static Quantity_NameOfColor getColorNameFromOldEnum (Standard_Integer theOld);
//! Convert Quantity_NameOfColor to old enumeration value for writing documents in compatible format.
Standard_EXPORT static Standard_Integer getOldColorNameFromNewEnum (Quantity_NameOfColor theNew);
private:
Standard_GUID myDriverGUID;
Quantity_NameOfColor myColor;
Standard_Integer myMaterialIndex;
Standard_Integer myMode;
TColStd_ListOfInteger mySelectionModes;
Standard_Real myTransparency;
Standard_Real myWidth;
Standard_Boolean myIsDisplayed;
Standard_Boolean myHasOwnColor;
Standard_Boolean myHasOwnMaterial;
Standard_Boolean myHasOwnTransparency;
Standard_Boolean myHasOwnWidth;
Standard_Boolean myHasOwnMode;
Standard_Boolean myHasOwnSelectionMode;
//! Checks a list of selection modes.
Standard_Boolean HasSelectionMode(const Standard_Integer theSelectionMode) const;
};
#endif // _TDataXtd_Presentation_HeaderFile
|
#include "BattleTimeManager.h"
BattleTimeManager::BattleTimeManager()
: ManagerModule(eBattleMgr_Time)
{
}
BattleTimeManager::~BattleTimeManager()
{
}
bool BattleTimeManager::Awake()
{
return true;
}
bool BattleTimeManager::AfterAwake()
{
return true;
}
bool BattleTimeManager::Execute()
{
m_CurTime.Now();
m_TimeMgr.Run();
return true;
}
bool BattleTimeManager::BeforeShutDown()
{
return true;
}
bool BattleTimeManager::ShutDown()
{
return true;
}
|
#include <iostream>
#include <ctime>
#include <vector>
#include <string>
#include <array>
#include <algorithm>
#include <sstream>
#include <map>
using namespace std;
unsigned long long solve(unsigned long long);
unsigned long long solve(size_t depth, size_t branch);
unsigned long long search(unsigned long long);
void setUp();
unsigned long long solveSlow(unsigned long long);
vector<string> powersOfEleven;
vector<vector<size_t>> tree;
array<unsigned long long, 20> powers;
array<array<bool, 1400>, 20> seen;
array<array<unsigned long long, 1400>, 20> results;
int main() {
clock_t start = clock();
setUp();
unsigned long long result = search(1000000000000000000ULL);
clock_t end = clock();
cout << result << ' ' << (static_cast<double>(end)-start) / CLOCKS_PER_SEC << endl;
system("PAUSE");
}
void setUp() {
powersOfEleven.push_back("11");
powersOfEleven.push_back("121");
powersOfEleven.push_back("1331");
powersOfEleven.push_back("14641");
powersOfEleven.push_back("161051");
powersOfEleven.push_back("1771561");
powersOfEleven.push_back("19487171");
powersOfEleven.push_back("214358881");
powersOfEleven.push_back("2357947691");
powersOfEleven.push_back("25937424601");
powersOfEleven.push_back("3138428376721");
powersOfEleven.push_back("379749833583241");
powersOfEleven.push_back("4177248169415651");
powersOfEleven.push_back("45949729863572161");
powersOfEleven.push_back("505447028499293771");
powersOfEleven.push_back("5559917313492231481");
powers[0] = 1;
for (size_t i = 1; i < powers.size(); ++i) {
powers[i] = powers[i - 1] * 10;
}
for (size_t i = 0; i < seen.size(); ++i) {
for (size_t j = 0; j < seen[i].size(); ++j) {
seen[i][j] = false;
}
}
array<string, 10> charStrings;
charStrings[0] = "0";
charStrings[1] = "1";
charStrings[2] = "2";
charStrings[3] = "3";
charStrings[4] = "4";
charStrings[5] = "5";
charStrings[6] = "6";
charStrings[7] = "7";
charStrings[8] = "8";
charStrings[9] = "9";
map<string, size_t, less<string>> prefixIdexes;
vector<string> prefixes;
prefixes.push_back("0");
prefixes.push_back("1");
prefixes.push_back("2");
prefixes.push_back("3");
prefixes.push_back("4");
prefixes.push_back("5");
prefixes.push_back("6");
prefixes.push_back("7");
prefixes.push_back("8");
prefixes.push_back("9");
prefixIdexes.insert(make_pair("0", 0));
prefixIdexes.insert(make_pair("1", 1));
prefixIdexes.insert(make_pair("2", 2));
prefixIdexes.insert(make_pair("3", 3));
prefixIdexes.insert(make_pair("4", 4));
prefixIdexes.insert(make_pair("5", 5));
prefixIdexes.insert(make_pair("6", 6));
prefixIdexes.insert(make_pair("7", 7));
prefixIdexes.insert(make_pair("8", 8));
prefixIdexes.insert(make_pair("9", 9));
size_t index = prefixes.size();
for (size_t i = 0; i < prefixes.size(); ++i) {
int place = -1;
bool complete = false;
string prefix = prefixes[i];
for (size_t j = 0; j < prefix.size() && place == -1; ++j) {
string prefixSub = prefix.substr(j);
for (size_t k = 0; k < powersOfEleven.size() && place == -1; ++k) {
int location = powersOfEleven[k].find(prefixSub);
if (location == 0) {
place = j;
if (prefixSub.size() == powersOfEleven[k].size()) {
complete = true;
}
}
}
}
vector<size_t> branch;
if (complete) {
branch.push_back(1);
} else {
branch.push_back(0);
}
if (!complete) {
if (place != -1) {
string newPrefix = prefix.substr(place);
for (size_t j = 0; j <= 9; ++j) {
string newKey = newPrefix + charStrings[j];
if (prefixIdexes.find(newKey) != prefixIdexes.end()) {
branch.push_back(prefixIdexes[newKey]);
} else {
prefixIdexes.insert(make_pair(newKey, index));
branch.push_back(index);
++index;
prefixes.push_back(newKey);
}
}
} else {
for (size_t j = 0; j <= 9; ++j) {
branch.push_back(j);
}
}
}
tree.push_back(branch);
}
}
unsigned long long search(unsigned long long goal) {
unsigned long long result = goal;
unsigned long long current = solve(result);
while (current != goal) {
result += goal - current;
current = solve(result);
}
return result;
}
unsigned long long solve(unsigned long long limit) {
ostringstream convert;
convert << limit;
unsigned long long result = limit;
string stringLimit = convert.str();
for (char i = '0'; i < stringLimit[0]; ++i) {
result -= solve(stringLimit.length() - 1, i - '0');
}
size_t edge = stringLimit[0] - '0';
size_t index = stringLimit.length() - 1;
reverse(stringLimit.begin(), stringLimit.end());
bool done = false;
while (0 != index-- && !done) {
vector<size_t> branch = tree[edge];
if (branch[0] == 1) {
done = true;
result -= limit%powers[index + 1] + 1;
} else {
for (char i = '0'; i < stringLimit[index]; ++i) {
result -= solve(index, branch[1 + (i - '0')]);
}
edge = branch[1 + (stringLimit[index] - '0')];
}
}
return result;
}
unsigned long long solve(size_t depth, size_t branchID) {
if (seen[depth][branchID]) {
return results[depth][branchID];
}
vector<size_t> branch = tree[branchID];
unsigned long long result = 0;
if (branch[0] == 1) {
result = powers[depth];
} else {
if (depth != 0) {
for (size_t i = 1; i < branch.size(); ++i) {
result += solve(depth - 1, branch[i]);
}
}
}
seen[depth][branchID] = true;
results[depth][branchID] = result;
return result;
}
unsigned long long solveSlow(unsigned long long target) {
vector<string> powersOfEleven;
powersOfEleven.push_back("11");
powersOfEleven.push_back("121");
powersOfEleven.push_back("1331");
powersOfEleven.push_back("14641");
powersOfEleven.push_back("161051");
powersOfEleven.push_back("1771561");
powersOfEleven.push_back("19487171");
powersOfEleven.push_back("214358881");
powersOfEleven.push_back("2357947691");
powersOfEleven.push_back("25937424601");
//powersOfEleven.push_back("285311670611");
powersOfEleven.push_back("3138428376721");
//powersOfEleven.push_back("34522712143931");
powersOfEleven.push_back("379749833583241");
powersOfEleven.push_back("4177248169415651");
powersOfEleven.push_back("45949729863572161");
powersOfEleven.push_back("505447028499293771");
powersOfEleven.push_back("5559917313492231481");
unsigned long long result = 0;
for (unsigned long long i = 1; i <= target; ++i) {
ostringstream convert;
convert << i;
string stringNumber = convert.str();
bool found = false;
for (size_t j = 0; j < powersOfEleven.size() && !found; ++j) {
int location = stringNumber.find(powersOfEleven[j]);
if (location != string::npos) {
found = true;
}
}
if (!found) {
++result;
}
}
return result;
}
|
#include "precompiled.h"
#include "game/jsgame.h"
#include "game/game.h"
#include "script/script.h"
#include "window/appwindow.h"
namespace jsgame
{
JSBool jsstartMap(JSContext *cx, uintN argc, jsval *vp);
JSBool jsquit(JSContext *cx, uintN argc, jsval *vp);
JSBool jstimestamp(JSContext *cx, uintN argc, jsval *vp);
}
REGISTER_STARTUP_FUNCTION(jsgame, jsgame::init, 10);
void jsgame::init()
{
script::gScriptEngine->AddFunction("game.startMap", 1, jsgame::jsstartMap);
script::gScriptEngine->AddFunction("quit", 0, jsgame::jsquit);
script::gScriptEngine->AddFunction("timestamp", 0, jsgame::jstimestamp);
}
JSBool jsgame::jsstartMap(JSContext *cx, uintN argc, jsval *vp)
{
if (argc != 1)
{
script::gScriptEngine->ReportError("startMap() takes 1 argument");
return JS_FALSE;
}
game::startMap(JS_GetStringBytes(JS_ValueToString(cx, JS_ARGV(cx,vp)[0])));
return JS_TRUE;
}
JSBool jsgame::jsquit(JSContext *cx, uintN argc, jsval *vp)
{
PostMessage(eXistenZ::g_appWindow->getHwnd(), WM_QUIT, 0, 0);
return JS_TRUE;
}
JSBool jsgame::jstimestamp(JSContext *cx, uintN argc, jsval *vp)
{
SYSTEMTIME now;
GetLocalTime(&now);
char timestamp[64];
sprintf(timestamp, "%04d-%02d-%02d-%02d-%02d-%02d-%04d",
now.wYear,
now.wMonth,
now.wDay,
now.wHour,
now.wMinute,
now.wSecond,
now.wMilliseconds);
JS_RVAL(cx,vp) = STRING_TO_JSVAL(JS_NewStringCopyZ(cx, timestamp));
return JS_TRUE;
}
|
#pragma once
/****************************************************************************
* Copyright (c) 2011 GeoMind Srl. www.geomind.it
* All rights reserved.
*
*---------------------------------------------------------------------------
* This software is part of the GeoTree library by GeoMind Srl;
* it is not allowed to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of software in parts or as a whole,
* in source and binary forms, without a written permission of GeoMind Srl.
*
****************************************************************************/
#ifndef CMeshTile_h
#define CMeshTile_h
#include "CGeoTile.h"
// ==========================================================================
// CMeshTile
// ==========================================================================
/**
* \brief unitary terrain mesh object
*
* \internal
**/
// forward declaration
class CMeshTile : public CGeoTile
{
public:
// bool original;
// constructor and destructor
CMeshTile( CGeoTerrain* inTerrain );
virtual ~CMeshTile();
// initialization
protected:
// implementation data
private:
void InitCommon();
}; // class CMeshTile
#endif // CMeshTile_h
|
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Portions of this file are from JUCE.
Copyright (c) 2013 - Raw Material Software Ltd.
Please visit http://www.juce.com
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef BEAST_HIGHRESOLUTIONTIMER_H_INCLUDED
#define BEAST_HIGHRESOLUTIONTIMER_H_INCLUDED
/**
A high-resolution periodic timer.
This provides accurately-timed regular callbacks. Unlike the normal Timer
class, this one uses a dedicated thread, not the message thread, so is
far more stable and precise.
You should only use this class in situations where you really need accuracy,
because unlike the normal Timer class, which is very lightweight and cheap
to start/stop, the HighResolutionTimer will use far more resources, and
starting/stopping it may involve launching and killing threads.
@see Timer
*/
class BEAST_API HighResolutionTimer : LeakChecked <HighResolutionTimer>, public Uncopyable
{
protected:
/** Creates a HighResolutionTimer.
When created, the timer is stopped, so use startTimer() to get it going.
*/
HighResolutionTimer();
public:
/** Destructor. */
virtual ~HighResolutionTimer();
//==============================================================================
/** The user-defined callback routine that actually gets called periodically.
This will be called on a dedicated timer thread, so make sure your
implementation is thread-safe!
It's perfectly ok to call startTimer() or stopTimer() from within this
callback to change the subsequent intervals.
*/
virtual void hiResTimerCallback() = 0;
//==============================================================================
/** Starts the timer and sets the length of interval required.
If the timer is already started, this will reset its counter, so the
time between calling this method and the next timer callback will not be
less than the interval length passed in.
@param intervalInMilliseconds the interval to use (any values less than 1 will be
rounded up to 1)
*/
void startTimer (int intervalInMilliseconds);
/** Stops the timer.
This method may block while it waits for pending callbacks to complete. Once it
returns, no more callbacks will be made. If it is called from the timer's own thread,
it will cancel the timer after the current callback returns.
*/
void stopTimer();
/** Checks if the timer has been started.
@returns true if the timer is running.
*/
bool isTimerRunning() const noexcept;
/** Returns the timer's interval.
@returns the timer's interval in milliseconds if it's running, or 0 if it's not.
*/
int getTimerInterval() const noexcept;
private:
struct Pimpl;
friend struct Pimpl;
friend class ScopedPointer<Pimpl>;
ScopedPointer<Pimpl> pimpl;
};
#endif // BEAST_HIGHRESOLUTIONTIMER_H_INCLUDED
|
#include "Noise.hpp"
namespace rlrpg
{
noise_t noise(noise_coord_t n)
{
n = n ^ (n << 13);
return n * (n * n * 15731 + 789221) + 1376312589;
}
noisef_t noisef(noise_coord_t n)
{
return noise(n) / (noisef_t) ~(noise_t)0;
}
}
|
#include<iostream>
using namespace std;
int getBit(int n,int pos);//O(1)
int setBit(int n,int pos);//O(1)
int clearBit(int n,int pos);//O(1)
int updateBit(int n,int pos,int val);//O(1);
bool isPowerOf2(int n);//O(1)
int twosComplement(int n);//O(1)
int numberOfOnes(int n); //O(1)
void printSubsets(int A[],int n );//O(n)
int main()
{
int A[]={1,2,3};
printSubsets(A,3);
return 0;
}
int getBit(int n,int pos)
{
return (n&(1<<pos))!=0;
}
int setBit(int n,int pos)
{
return n|(1<<pos);
}
int clearBit(int n,int pos)
{
int mask=~(1<<pos);
return n&mask;
}
int updateBit(int n,int pos,int val)
{
int mask=~(1<<pos);
n=n&mask;
return n|(val<<pos);
}
bool isPowerOf2(int n)
{
return (n&&!(n&(n-1)));
}
int twosComplement(int n)
{
return (~n)+1;
}
int numberOfOnes(int n)
{
int count=0;
while(n)
{
n=n&(n-1);
++count;
}
return count;
}
void printSubsets(int A[],int n )
{
for(int i=0;i<(1<<n);i++)
{
for(int j=0;j<n;j++)
{
if(i&(1<<j))
{
cout<<A[j]<<"\t";
}
}
cout<<endl;
}
}
|
#include <iostream>
#include <algorithm>
#include <numeric>
using namespace std;
int main() {
int N;
cin >> N;
int a[N];
for (int i = 0; i < N; ++i) cin >> a[i];
sort(a, a + N);
int sum = accumulate(a, a + N, 0);
int ans = sum;
for (int x = 2; x <= 100; ++x) {
int b = 0;
for (int i = 0; i < N; ++i) {
if (a[i] % x == 0) b = a[i] / x;
}
ans = min(ans, sum - (b - a[0]) * (x - 1));
}
cout << ans << endl;
return 0;
}
|
//
// Created by dwb on 2019-07-22.
//
#include "AnimalFactory.h"
int AnimalFactory::size = 0;
void AnimalFactory::addAnimal(Animal &animal) {
animal.m_name = "Monkey";
animal.m_weight = 80;
}
|
#include "CommandProcessor.h"
CommandProcessor::CommandProcessor(string _commandFile,string _logFile):
commandFile(_commandFile),logFile(_logFile),UNDERLINE("------------------------------------------------------------------------------------------")
{
log = Logger::getLog(logFile);
}
CommandProcessor:: ~CommandProcessor(){}
vector<vector<string> > CommandProcessor::readCommandFile(){
vector<vector<string> > list;
vector<vector<string> > listA;
vector<string> test;
string line;
file.open(commandFile);
if(file.is_open()){
while(getline(file, line)){
if(line[0]!= ';' ){
istringstream iss(line);
string token;
string quit = "quit";
vector<string> temp;
//while(getline(iss, token)){
while(iss>>token){
temp.push_back(token);
}
listA.push_back(temp);
}
}
}
int pos;
for(int i =0; i<listA.size(); i++){
if(listA[i][0] == "quit"){
pos = i+1;
}
}
for(int j=0; j< pos;j++){
list.push_back(listA[j]);
}
return list;
}
void CommandProcessor::debugHash(int cmdNum){
int tableSize = nameIndex->getTableSize();
int elements = gisRecordList.size()-1;
log->out("Command "+to_string(cmdNum)+ ": debug hash\n"
+ "\nFormat of display is"
+ "\nSlot number: data record\nCurrent table size is "
+ to_string(tableSize)+
+ "\nNumber of elements in table is "+to_string(elements)+"\n");
log->out("\n"+UNDERLINE);
}
void CommandProcessor::import(int cmdNum, string dataFile){
getGISRecord(dataFile);
int total =0;
int size = gisRecordList.size();
for(auto a: gisRecordList){
total += a.getFeatureName().size();
}
int aveNameLength = total/size;
log->out("Command " + to_string(cmdNum)+ ": import " + dataFile);
log->out("Imported Features by name: "+to_string(size-1));
//log->out("Longest probe sequence: 3");
createHashtable(gisRecordList);
log->out("Imported Location: " + to_string(size-1));
log->out("Average name length: " + to_string(aveNameLength));
// int i=1;
// for(auto gis:list){
// log->out(to_string(i)+": Prime latitude = "+gis.getPrimeLatDms());
// i++;
// }
log->out(UNDERLINE);
}
//vector<GISRecord> CommandProcessor::getGISRecord(string dataFile){
void CommandProcessor::getGISRecord(string dataFile){
buffer = new BufferPool(dataFile);
gisRecordList = buffer->readDataFile();
}
//vector<Hash> CommandProcessor::createHashtable(vector<GISRecord> list){
void CommandProcessor::createHashtable(vector<GISRecord> list){
nameIndex = new NameIndex();
Hash hash;
string key;
unsigned int hashVal;
for(int i =0; i<list.size();i++){
key = list[i].getFeatureName()+ " " + list[i].getStateAlpha();
//hashVal = nameIndex->insert(key);
hash.featureName = list[i].getFeatureName();
hash.state = list[i].getStateAlpha();
hash.offset = i;
if(hashVal != -1){
hash.index = nameIndex->insert(key);
hashTable.push_back(hash);
}
}
unsigned int maxProbe = nameIndex->getProbe();
log->out("Longest probe sequence: " + to_string(maxProbe));
}
void CommandProcessor::quit(int cmdNum,string cmd){
log->out("Command " + to_string(cmdNum)+ ": "+cmd);
log->printEnd();
}
void CommandProcessor::printHeader(string dataFile){
log->printHeader(dataFile,commandFile,logFile);
}
void CommandProcessor::world(string west, string east, string south, string north){
int westL = toDec(west);
int eastL = toDec(east);
int northL = toDec(north);
int southL = toDec(south);
log->out("world " + west + " " + east +" " + north + " " + south+ "\n"+UNDERLINE);
string header="\nLatitude/longitude values in index entries are shown as signed integers, in total seconds\n"+UNDERLINE
+"\nWorld boundaries are set to:\n";
string output = header+space(48)+to_string(northL)+"\n"
+space(38)+to_string(westL)+space(10)+to_string(eastL)+"\n"
+space(48)+to_string(southL)+"\n"+UNDERLINE+"\n";
log->out(output);
}
int CommandProcessor::toDec(string input){
int decResult;
int degree;
int min;
int second;
string::size_type sz;
int size = input.size();
char end = input[size-1];
switch(end){
case 'N':
degree = stoi(input.substr(0,2));
min = stoi(input.substr(2,2));
second = stoi(input.substr(4,2));
decResult = (degree*3600+min*60+second);
break;
case 'W':
if(input[0]=='0'){
degree = stoi(input.substr(1,2));
}else{
degree = stoi(input.substr(0,3));
}
min = stoi(input.substr(3,2));
second = stoi(input.substr(5,2));
decResult = -(degree*3600+min*60+second);
break;
default:
break;
}
return decResult;
}
string CommandProcessor::space(int n){
string spaces=" ";
for(int i=0; i <n;i++){
spaces +=" ";
}
return spaces;
}
|
#include "engine/graphics/PhysicsObject.hpp"
pair<int,int> CollisionRect::getVertex(int i){
double diag = sqrt(1.0*w*w+h*h)/2;
// if(w==36){
// cout << w << " " << h << " " <<uw << " " << uh << endl;
// }
double dangle = atan2(h,w);
switch (i)
{
case 0:
dangle -= PI;
break;
case 1:
dangle = - dangle;
break;
case 3:
dangle = PI - dangle;
break;
default:
break;
}
double x1 = 1.0*x+uw/2 + diag * cos(dangle + angle);
double y1 = 1.0*y+uh/2 + diag * sin(dangle + angle);
return {(int) x1,(int) y1};
}
bool CollisionRect::intersects(CollisionRect* collider){
for (int x=0; x<2; x++)
{
CollisionRect* polygon = (x==0) ? this : collider;
for (int i1=0; i1<4; i1++)
{
int i2 = (i1 + 1) % 4;
pair<int,int> p1 = polygon->getVertex(i1);
pair<int,int> p2 = polygon->getVertex(i2);
pair<int,int> normal(p2.second - p1.second, p1.first - p2.first);
double minA = __DBL_MAX__;
double maxA = - __DBL_MAX__;
for (int i = 0; i< 4;i++)
{
pair<int,int> p = this->getVertex(i);
double projected = normal.first * p.first + normal.second * p.second;
if (projected < minA)
minA = projected;
if (projected > maxA)
maxA = projected;
}
double minB = __DBL_MAX__;
double maxB = - __DBL_MAX__;
for (int i = 0; i< 4;i++)
{
pair<int,int> p = collider->getVertex(i);
double projected = normal.first * p.first + normal.second * p.second;
if (projected < minB)
minB = projected;
if (projected > maxB)
maxB = projected;
}
if (maxA < minB || maxB < minA)
return false;
}
}
return true;
}
void CollisionRect::render(){
if((x < gEngine->camera->x - TILE_SIZE) || (x > gEngine->camera->x + gEngine->camera->w + TILE_SIZE)){
return;
}
if((y < gEngine->camera->y - TILE_SIZE) || (y > gEngine->camera->y + gEngine->camera->h + TILE_SIZE)){
return;
}
for(int i =0;i<4;i++){
pair<int,int> p1 = getVertex(i);
pair<int,int> p2 = getVertex((i+1)%4);
p1 = getPosOnCamera(p1);
p2 = getPosOnCamera(p2);
SDL_RenderDrawLine( gEngine->gRenderer, p1.first,p1.second,p2.first,p2.second );
}
}
void CollisionRect::shift(int px,int py){
x = px;
y = py;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.