text
stringlengths 8
6.88M
|
|---|
//
// SmartSample.hpp
// DrumConsole
//
// Created by Paolo Simonazzi on 23/01/2016.
//
//
#ifndef SmartSample_hpp
#define SmartSample_hpp
#include <stdio.h>
const int numOfVoices = 6;
class LayeredSample;
class SmartSample {
public:
SmartSample(const String& sampleName);
~SmartSample();
private:
LayeredSample voices[numOfVoices];
};
#endif /* SmartSample_hpp */
|
#pragma once
#include "Question.h"
#include "types.h"
#include <loki/Visitor.h>
#include "SequenceQuestion_fwd.h"
namespace qp
{
class CSequenceQuestion : public CQuestion
{
public:
LOKI_DEFINE_CONST_VISITABLE();
typedef std::vector<std::string> Sequence;
CSequenceQuestion(const std::string & description, double score = 0.0, const Sequence & sequence = Sequence());
const Sequence & GetSequence()const;
size_t GetSequenceLength()const;
private:
Sequence m_sequence;
};
}
|
#include <iostream>
#include <vector>
#include <boost/random.hpp>
#include <cppmc/cppmc.hpp>
using namespace boost;
using namespace arma;
using namespace CppMC;
using std::vector;
using std::ofstream;
using std::cout;
using std::endl;
class EstimatedY : public MCMCDeterministic<double,Mat> {
private:
mat& X_;
MCMCStochastic<double,Mat>& B_;
mutable mat B_full_rank_;
mat permutation_matrix_;
mat row_sum_permutation_;
public:
EstimatedY(Mat<double>& X, MCMCStochastic<double,Mat>& B, ivec& groups):
MCMCDeterministic<double,Mat>(mat(X.n_rows,1)), X_(X), B_(B), B_full_rank_(X_.n_rows,X.n_cols),
permutation_matrix_(X_.n_rows,B.nrow()) {
permutation_matrix_.fill(0.0);
for(uint i = 0; i < groups.n_elem; i++) {
permutation_matrix_(i,groups[i]) = 1.0;
}
MCMCDeterministic<double,Mat>::value_ = eval();
}
void getParents(std::vector<MCMCObject*>& parents) const {
parents.push_back(&B_);
}
Mat<double> eval() const {
const mat& B = B_();
B_full_rank_ = permutation_matrix_ * B;
return sum(X_ % B_full_rank_,1);
}
};
// global rng generators
CppMCGeneratorT MCMCObject::generator_;
int main() {
const uint NR = 1000;
const uint NC = 4;
const uint J = 3;
mat X = randn<mat>(NR,NC);
mat y = randn<mat>(NR,1);
// make X col 0 const
for(uint i = 0; i < NR; i++) { X(i,0) = 1; }
// create fake groups
ivec groups(NR);
for(uint i = 0; i < NR; i++) {
groups[i] = i % J;
}
// shift y's by group sums
vec group_shift(J);
for(uint i = 0; i < J; i++) {
group_shift[i] = (i + 1) * 10;
}
cout << "group_shift" << endl << group_shift;
// do the shift on the data
for(uint i = 0; i < NR; i++) {
y[i] += group_shift[ groups[i] ];
}
vec coefs;
solve(coefs, X, y);
Normal<Mat> B(0.0, 0.0001, randn<mat>(J,NC));
EstimatedY obs_fcst(X, B, groups);
Uniform<Mat> tauY(0, 100, vec(1)); tauY[0] = 1.0;
NormalLikelihood<Mat> likelihood(y, obs_fcst, tauY);
likelihood.print();
likelihood.sample(1e5, 1e4, 10);
cout << "collected " << B.getHistory().size() << " samples." << endl;
cout << "avg_coefs" << endl << B.mean() << endl;
return 1;
}
|
#include "delegatewindow.h"
#include "ui_delegatewindow.h"
delegateWindow::delegateWindow(QWidget *parent) :
QDialog(parent),
ui(new Ui::delegateWindow)
{
ui->setupUi(this);
}
delegateWindow::~delegateWindow()
{
delete ui;
}
void delegateWindow::give_to_another()
{
QVariant inp = ui->lineEdit->text();
newinf[0] = inp;
inp = ui->lineEdit_2->text();
newinf[1] = inp;
}
void delegateWindow::onDonePushed()
{
give_to_another();
closed = true;
this->close();
}
void delegateWindow::onCancelPushed()
{
closed = false;
this->close();
}
QList<QVariant> delegateWindow::getName()
{
return newinf;
}
bool delegateWindow::if_can()
{
return closed;
}
|
//
// SnappaOutput.h
// Snappa
//
// Created by Sam Edson on 6/14/15.
// Copyright (c) 2015 Sam Edson. All rights reserved.
//
#ifndef __Snappa__SnappaOutput__
#define __Snappa__SnappaOutput__
#include <stdio.h>
#include <string>
class SnappaOutput {
public:
SnappaOutput() : message_("") {};
std::string message();
void message(std::string newMessage);
private:
std::string message_;
};
#endif /* defined(__Snappa__SnappaOutput__) */
|
#pragma once
#include <Poco/Condition.h>
#include <Poco/Mutex.h>
#include <Poco/Timespan.h>
namespace BeeeOn {
/**
* @brief StopControl implements the stop mechanism generically.
*/
class StopControl {
public:
/**
* @brief Helper class for managing a common stoppable loop
* situation:
* <pre>
* void run()
* {
* StopControl::Run run(m_stopControl);
*
* while (run) {
* ...
* run.waitStoppable(...)
* ...
* }
* }
*
* void stop()
* {
* m_stopControl.requestStop();
* }
* </pre>
*/
class Run {
public:
Run(StopControl &control);
~Run();
/**
* @brief Delegates to StopControl::waitStoppable().
*/
bool waitStoppable(const Poco::Timespan &timeout);
/**
* @brief Equivalent to !StopControl::shouldStop().
*/
operator bool() const;
private:
StopControl &m_control;
};
StopControl();
/**
* Wait for the specified timeout unless a stop is requested.
* If the timeout is negative, it waits without timeout.
* Timeout in range 0 < timeout < 1 ms is fixed to be 1 ms.
*
* @returns true when woken up, false when timeout exceeded
*/
bool waitStoppable(const Poco::Timespan &timeout);
/**
* @returns true to determine whether a stop request has
* been made.
*/
bool shouldStop() const;
/**
* Request stop. The shouldStop() call would return true
* until clear() is called.
*/
void requestStop();
/**
* Request wakeup (without requesting a stop).
*/
void requestWakeup();
/**
* Clear the stop request and reinitialize.
*/
void clear();
protected:
/**
* Perform the actual m_event.wait() or m_event.tryWait(ms).
*/
bool doWait(long ms);
private:
bool m_stop;
mutable Poco::FastMutex m_lock;
Poco::Condition m_condition;
};
}
|
//Ein- und Ausgabe mit Lauflicht (vorläufig -- ruckelt leider) vink Pototyp
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
#define PIN1 5 // Eingabe1
#define PIN2 6 // Eingabe2
#define PIN3 7 // Ausgabe
int potPin1 = 2; //Potentiometer an Pin A1
int potPin2 = 3; //Potentiometer2 an Pin A2
int eingabewert1 = 0; // Variable für den durch das Potentiometer1 eingegebenen Wert
int eingabewert2 = 0; // Variable für den durch das Potentiometer2 eingegebenen Wert
int eingabewertd = 0;
int r1 = 0; // Variable für Rot-Wert der zu errechnenden Farbe1
int g1 = 0; // Variable für Grün-Wert der zu errechnenden Farbe1
int b1 = 0; // Variable für Blau-Wert der zu errechnenden Farbe1
int r2 = 0; // Variable für Rot-Wert der zu errechnenden Farbe2
int g2 = 0; // Variable für Grün-Wert der zu errechnenden Farbe2
int b2 = 0; // Variable für Blau-Wert der zu errechnenden Farbe2
int rd = 0; // Variable für Rot-Wert der zu errechnenden Farbed
int gd = 0; // Variable für Grün-Wert der zu errechnenden Farbed
int bd = 0; // Variable für Blau-Wert der zu errechnenden Farbed
String farbe1 = "keine"; // Variable für die Bennenung der errechneten Farbe
String farbe2 = "keine"; // Variable für die Bennenung der errechneten Farbe
String farbed = "keine"; // Variable für die Bennenung der errechneten Farbe
uint32_t farbwert1;
uint32_t farbwert2;
uint32_t farbwertd;
int multi1 = 0; // Variable zur Multipilizierung der Farbschritte
int multi2 = 0; // Variable zur Multipilizierung der Farbschritte
int multid = 0; // Variable zur Multipilizierung der Farbschritte
int geschwindigkeit = 0;
int k = 0;
int l = 0;
#define NUMPIXELS 100
Adafruit_NeoPixel strip1(6, PIN1, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel strip2(6, PIN2, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel strip3(NUMPIXELS, PIN3, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel farblos(20, PIN3, NEO_GRB + NEO_KHZ800);
void setup() {
#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
clock_prescale_set(clock_div_1);
#endif
Serial.begin(9600); // Starte Serialmonitor
strip1.begin();
strip2.begin();
strip3.begin();
// strip1.show();
// strip2.show();
// strip3.show();
}
void Welleneffekt(){
for(int i = 70; i>=-35; i--){
EingabeAuslesen();
FarbwertErrechnen();
FarbenAnzeigen();
geschwindigkeit = 50 - (eingabewertd/40);
k = i + 35;
strip3.setPixelColor(i, 0,0,0);
strip3.setPixelColor(k, 0,0,0);
strip3.setPixelColor(l, 0,0,0);
for(int j = 1; j<=6; j++){
int b = 7-j;
strip3.setPixelColor(i+j,rd/b,gd/b,bd/b);
strip3.setPixelColor(i-j,rd/b,gd/b,bd/b);
strip3.setPixelColor(k+j,rd/b,gd/b,bd/b);
strip3.setPixelColor(k-j,rd/b,gd/b,bd/b);
strip3.setPixelColor(l+j,rd/b,gd/b,bd/b);
strip3.setPixelColor(l-j,rd/b,gd/b,bd/b);
}
strip3.setPixelColor(i+6, rd,gd,bd);
strip3.setPixelColor(k+6, rd,gd,bd);
strip3.setPixelColor(l+6, rd,gd,bd);
strip3.show();
delay(geschwindigkeit);
if(i == 0){
i = k;
}
}
}
void loop() {
Welleneffekt();
// Ausgabe des Eingabewertes des Potentiometers, der Farbbezeichnung und errechneten Farbwerts (rgb) im Serialmonitor
Serial.print("Eingabewert1: ");
Serial.println(eingabewert1);
Serial.print("Farbe1: ");
Serial.println(farbe1);
Serial.print("Farbwert: rgb(");
Serial.print(r1);
Serial.print(",");
Serial.print(g1);
Serial.print(",");
Serial.print(b1);
Serial.println(")");
Serial.println("----");
Serial.print("Eingabewert2: ");
Serial.println(eingabewert2);
Serial.print("Farbe2: ");
Serial.println(farbe2);
Serial.print("Farbwert2: rgb(");
Serial.print(r2);
Serial.print(",");
Serial.print(g2);
Serial.print(",");
Serial.print(b2);
Serial.println(")");
Serial.println("----");
Serial.print("Eingabewertd: ");
Serial.println(eingabewertd);
Serial.print("Farbed: ");
Serial.println(farbed);
Serial.print("Farbwertd: rgb(");
Serial.print(rd);
Serial.print(",");
Serial.print(gd);
Serial.print(",");
Serial.print(bd);
Serial.println(")");
Serial.println("-------------");
}
void EingabeAuslesen(){
eingabewert1 = analogRead(potPin1)/ 4; // Eingabewert vm Potentiometer erfassen und diesen durch folgende Bedingungen in einen Farbwert umwandeln
eingabewert2 = analogRead(potPin2)/ 4; // Eingabewert vm Potentiometer erfassen und diesen durch folgende Bedingungen in einen Farbwert umwandeln
eingabewertd = (eingabewert1 + eingabewert2) / 2;
}
void FarbwertErrechnen(){
multi1 = eingabewert1 - 1;
multi2 = eingabewert2 - 1;
multid = eingabewertd - 1;
if(eingabewert1 < 5){
r1 = 0;
g1 = 0;
b1 = 0;
}
if(eingabewert2 < 5){
r2 = 0;
g2 = 0;
b2 = 0;
}
if(eingabewertd < 5){
rd = 0;
gd = 0;
bd = 0;
}
if(eingabewert1 == 5){
r1 = 100;
g1 = 155;
b1 = 0;
farbe1 = "gruen";
}
if(eingabewert2 == 5){
r2 = 100;
g2 = 155;
b2 = 0;
farbe2 = "gruen";
}
if(eingabewertd == 5){
rd = 100;
gd = 155;
bd = 0;
farbed = "gruen";
}
if(eingabewert1 > 5 && eingabewert1 < 255){
r1 = 100 + (multi1 * 0.57312253);
g1 = 155 - (multi1 * 0.57312253);
b1 = 0;
farbe1 = "irgendetwas zwischen gruen und rot";
}
if(eingabewert2 > 5 && eingabewert2 < 255){
r2 = 100 + (multi2 * 0.57312253);
g2 = 155 - (multi2 * 0.57312253);
b2 = 0;
farbe2 = "irgendetwas zwischen gruen und rot";
}
if(eingabewertd > 5 && eingabewertd < 255){
rd = 100 + (multid * 0.57312253);
gd = 155 - (multid * 0.57312253);
bd = 0;
farbed = "irgendetwas zwischen gruen und rot";
}
if(eingabewert1 == 255){
r1 = 245;
g1 = 10;
b1 = 0;
farbe1 = "rot";
}
if(eingabewert2 == 255){
r2 = 245;
g2 = 10;
b2 = 0;
farbe2 = "rot";
}
if(eingabewertd == 255){
rd = 245;
gd = 10;
bd = 0;
farbed = "rot";
}
}
void FarbenAnzeigen(){
farbwert1 = strip1.Color(r1, g1, b1);
farbwert2 = strip2.Color(r2, g2, b2);
farbwertd = strip3.Color(rd, gd, bd);
strip1.fill(farbwert1);
strip2.fill(farbwert2);
strip3.fill(farbwertd);
strip1.show();
strip2.show();
strip3.show();
}
|
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <list>
#include <map>
#include <iomanip>
#include <set>
#include <climits>
#include <ctime>
#include <complex>
#include <cmath>
#include <string>
#include <cctype>
#include <cstring>
#include <algorithm>
using namespace std;
typedef pair<int,int> pii;
typedef long double ld;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
const int maxn=500005;
const int INF=0x3f3f3f3f;
const double PI=acos(-1.0);
const double EPS=1e-9;
inline int sgn(double a){return a<-EPS? -1:a>EPS;}
int n;
ll p[maxn];
string s;
ll dpz[maxn];
ll dpf[maxn];
ll dpzz[maxn];
ll dpff[maxn];
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>n;
for(int i=0;i<n;i++){
cin>>p[i];
}
cin>>s;
for(int i=0;i<n;i++){
if(i==0){
if(s[i]=='A'){
dpz[i]=p[i];
dpzz[i]=0;
}else{
dpz[i]=0;
dpzz[i]=p[i];
}
}else{
if(s[i]=='A'){
dpz[i]=dpz[i-1]+p[i];
dpzz[i]=dpzz[i-1];
}else{
dpz[i]=dpz[i-1];
dpzz[i]=dpzz[i-1]+p[i];
}
}
}
for(int i=n-1;i>=0;i--){
if(s[i]=='A'){
dpf[i]=dpf[i+1]+p[i];
dpff[i]=dpff[i+1];
}else{
dpf[i]=dpf[i+1];
dpff[i]=dpff[i+1]+p[i];
}
}
ll ans=0;
for(int i=0;i<n;i++){
if(s[i]=='B')
ans+=p[i];
}
for(int i=0;i<n;i++){
if(i==0){
ans=max(ans,dpz[i]+dpff[i+1]);
ans=max(ans,dpf[i]);
continue;
}
ans=max(ans,dpz[i]+dpff[i+1]);
ans=max(ans,dpzz[i-1]+dpf[i]);
}
cout<<ans<<"\n";
return 0;
}
|
// this is a crude test of the major functions in Systronix MB85RC256V fram library. Mostly it proves that
// Teensy can talk to fram on i2c port0
#include <Systronix_MB85RC256V.h>
Systronix_MB85RC256V fram;
Systronix_i2c_common i2c_common;
uint16_t manuf_id;
uint16_t prod_id;
//---------------------------< S E T U P >--------------------------------------------------------------------
void setup()
{
uint8_t i;
const uint8_t byte_pattern = 0x0F;
const uint16_t int16_pattern = 0x00FF;
const uint16_t int32_pattern = 0x0000FFFF;
uint8_t ret_val; // a place to hold returned byte-size whatever
uint16_t address; // local copy of fram address
Serial.begin(115200); // use max baud rate
while((!Serial) && (millis()<10000)); // wait until serial monitor is open or timeout
Serial.println("fram test");
if (SUCCESS != fram.setup (0x50)) // uses default wire settings
{
Serial.printf ("fram.setup (0x50) failed\ntest halted");
while (1);
}
Serial.printf ("\tfram using %s @ base 0x%.2X\n", fram.wire_name, fram.base_get());
fram.begin (); // join i2c as master
if (SUCCESS != fram.init())
{
Serial.printf ("fram.init() failed\ntest halted");
while (1);
}
fram.get_device_id (&manuf_id, &prod_id);
Serial.printf ("initialized\n\tfram manuf. ID: 0x%.4X\n\tfram prod. ID: 0x%.4X\n", manuf_id, prod_id);
// test address setting and getting
ret_val = fram.set_addr16 (0); // attempt to set min address
if (SUCCESS != ret_val)
{
Serial.printf ("fram.set_addr16 (0) failed; min address\ntest halted");
while (1);
}
address = fram.get_addr16 ();
if (0 != address)
{
Serial.printf ("fram.get_addr16() failed; expected: 0x0000; got: 0x%.4X\ntest halted", address);
while (1);
}
ret_val = fram.set_addr16 (0x7FFF); // attempt to set max address
if (SUCCESS != ret_val)
{
Serial.printf ("fram.set_addr16 (0x7FFF) failed; max address\ntest halted");
while (1);
}
address = fram.get_addr16 ();
if (0x7FFF != address)
{
Serial.printf ("fram.get_addr16() failed; expected: 0x7FFF; got: 0x%.4X\ntest halted", address);
while (1);
}
ret_val = fram.set_addr16 (0x8000); // attempt to set address out of range
if (SUCCESS == ret_val)
{
Serial.printf ("fram.set_addr16 (0x8000) failed; out of range\ntest halted");
while (1);
}
address = fram.get_addr16 ();
if (0x8000 & address) // if address is out of range; address should not have changed
{
Serial.printf ("fram.get_addr16() failed; expected: 0x07FF; got: 0x%.4X\ntest halted", address);
while (1);
}
Serial.printf ("address setting tests pass\n");
//---------- < P I N G >----------
if (SUCCESS != fram.ping_eeprom()) // TODO: delete fram.ping_eeprom()? fram not an eeprom
{
Serial.printf ("fram.ping_eeprom() failed\ntest halted");
while (1);
}
Serial.printf ("ping test: pass\n");
//----------< R E A D / W R I T E B Y T E >----------
// use byte_read() and current_address_read() to test protected inc_addr16()
fram.set_addr16 (0); // set min address
ret_val = fram.byte_read();
if (SUCCESS != ret_val)
{
Serial.printf ("fram.byte_read() failed; returned: 0x%.2X\ntest halted", ret_val);
while (1);
}
address = fram.get_addr16 ();
if (0x0001 != address)
{
Serial.printf ("fram.get_addr16() failed after byte_read(); expected: 0x0001; got: 0x%.4X\ntest halted", address);
while (1);
}
// write a pattern of pattern four bytes, one byte at a time
Serial.printf ("write byte:\n");
for (i=0; i<4; i++)
{
fram.set_addr16 (i); // set address for each write (fram does not inc internal addr counter for byte writes)
fram.control.wr_byte = byte_pattern << i;
ret_val = fram.byte_write();
if (SUCCESS != ret_val)
{
Serial.printf ("fram.byte_write() failed; returned: 0x%.2X\ntest halted", ret_val);
while (1);
}
Serial.printf ("\t[%d]: 0x%.2X\n", i, fram.control.wr_byte);
}
// read and validate the 4-byte pattern
fram.set_addr16 (0); // set min address
Serial.printf ("read byte:\n");
for (i=0; i<4; i++)
{
ret_val = fram.byte_read();
if (SUCCESS != ret_val)
{
Serial.printf ("fram.byte_read() failed; returned: 0x%.2X\ntest halted", ret_val);
while (1);
}
if (fram.control.rd_byte != (byte_pattern << i))
{
Serial.printf ("fram.byte_write() / fram.byte_read() sequence[%d] failed; read: 0x%.2X; expected: 0x%.2X\ntest halted", i, fram.control.rd_byte, (byte_pattern << i));
while (1);
}
Serial.printf ("\t[%d]: 0x%.2X\n", i, fram.control.rd_byte);
}
Serial.printf ("byte write / read test: pass\n");
//----------< R E A D / W R I T E I N T 1 6 >----------
// use int16_read() and page_read() to test protected adv_addr16()
fram.set_addr16 (0); // set min address
ret_val = fram.int16_read();
if (SUCCESS != ret_val)
{
Serial.printf ("fram.int16_read() failed; returned: 0x%.2X\ntest halted", ret_val);
while (1);
}
address = fram.get_addr16 ();
if (0x0002 != address)
{
Serial.printf ("fram.get_addr16() failed after int16_read(); expected: 0x0002; got: 0x%.4X\ntest halted", address);
while (1);
}
// write a pattern of pattern four int16s, one int16 at a time
Serial.printf ("write int16:\n");
fram.set_addr16 (0); // set min address; page write does advance the internal counter
for (i=0; i<4; i++)
{
fram.control.wr_int16 = int16_pattern << i;
ret_val = fram.int16_write();
if (SUCCESS != ret_val)
{
Serial.printf ("fram.int16_write() failed; returned: 0x%.2X\ntest halted", ret_val);
while (1);
}
Serial.printf ("\t[%d]: 0x%.4X\n", i<<1, fram.control.wr_int16);
}
// read and validate the 4-byte pattern
fram.set_addr16 (0); // set min address
Serial.printf ("read int16:\n");
for (i=0; i<4; i++)
{
ret_val = fram.int16_read();
if (SUCCESS != ret_val)
{
Serial.printf ("fram.int16_read() failed; returned: 0x%.2X\ntest halted", ret_val);
while (1);
}
if (fram.control.rd_int16 != (int16_pattern << i))
{
Serial.printf ("fram.int16_write() / fram.int16_read() sequence[%d] failed; read: 0x%.4X; expected: 0x%.4X\ntest halted", i<<1, fram.control.rd_int16, (int16_pattern << i));
while (1);
}
Serial.printf ("\t[%d]: 0x%.4X\n", i<<1, fram.control.rd_int16);
}
Serial.printf ("int16 write / read test: pass\n");
//----------< R E A D / W R I T E I N T 3 2 >----------
// use int32_read() and page_read() to test protected adv_addr32()
fram.set_addr16 (0); // set min address
ret_val = fram.int32_read();
if (SUCCESS != ret_val)
{
Serial.printf ("fram.int32_read() failed; returned: 0x%.2X\ntest halted", ret_val);
while (1);
}
address = fram.get_addr16 ();
if (0x0004 != address)
{
Serial.printf ("fram.get_addr16() failed after int32_read(); expected: 0x0004; got: 0x%.4X\ntest halted", address);
while (1);
}
// write a pattern of pattern four int32s, one int32 at a time
Serial.printf ("write int32:\n");
fram.set_addr16 (0); // set min address; page write does advance the internal counter
for (i=0; i<4; i++)
{
fram.control.wr_int32 = int32_pattern << i;
ret_val = fram.int32_write();
if (SUCCESS != ret_val)
{
Serial.printf ("fram.int32_write() failed; returned: 0x%.2X\ntest halted", ret_val);
while (1);
}
Serial.printf ("\t[%d]: 0x%.8X\n", i<<2, fram.control.wr_int32);
}
// read and validate the 4-byte pattern
fram.set_addr16 (0); // set min address
Serial.printf ("read int32:\n");
for (i=0; i<4; i++)
{
ret_val = fram.int32_read();
if (SUCCESS != ret_val)
{
Serial.printf ("fram.int32_read() failed; returned: 0x%.2X\ntest halted", ret_val);
while (1);
}
if (fram.control.rd_int32 != (int32_pattern << i))
{
Serial.printf ("fram.int32_write() / fram.int32_read() sequence[%d] failed; read: 0x%.8X; expected: 0x%.8X\ntest halted", i<<2, fram.control.rd_int32, (int32_pattern << i));
while (1);
}
Serial.printf ("\t[%d]: 0x%.8X\n", i<<2, fram.control.rd_int32);
}
Serial.printf ("int16 write / read test: pass\n");
Serial.printf ("done");
}
void loop()
{
}
|
// PingerDlg.h : header file
//
#if !defined(AFX_PINGERDLG_H__0788E7E9_71EF_11D2_B95A_0060083F73D6__INCLUDED_)
#define AFX_PINGERDLG_H__0788E7E9_71EF_11D2_B95A_0060083F73D6__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
/////////////////////////////////////////////////////////////////////////////
// CPingerDlg dialog
class CPingerDlg : public CDialog
{
// Construction
public:
CPingerDlg(CWnd* pParent = NULL); // standard constructor
void CPingerDlg::OnOK();
// Dialog Data
//{{AFX_DATA(CPingerDlg)
enum { IDD = IDD_PINGER_DIALOG };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CPingerDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
//{{AFX_MSG(CPingerDlg)
virtual BOOL OnInitDialog();
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
afx_msg void OnClear();
afx_msg void OnChangeO1();
afx_msg void OnChangeO2();
afx_msg void OnChangeO3();
afx_msg void OnResolve();
afx_msg void OnScan();
afx_msg void OnSave();
afx_msg void OnCopy();
afx_msg void OnAbout();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
LRESULT OnStartup(WPARAM wParam, LPARAM lParam);
LRESULT OnDone(WPARAM wParam, LPARAM lParam);
LRESULT OnError(WPARAM wParam, LPARAM lParam);
LRESULT OnPing(WPARAM wParam, LPARAM lParam);
LRESULT OnHostAlive(WPARAM wParam, LPARAM lParam);
LRESULT OnListen(WPARAM wParam, LPARAM lParam);
LRESULT OnResolved(WPARAM wParam, LPARAM lParam);
};
#define WM_THREADSTARTING (WM_USER+1)
#define WM_THREADDONE (WM_USER+2)
#define WM_THREADERROR (WM_USER+3)
#define WM_THREADPING (WM_USER+4)
#define WM_THREADHOSTALIVE (WM_USER+5)
#define WM_THREADLISTEN (WM_USER+6)
#define WM_THREADRESOLVED (WM_USER+7)
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_PINGERDLG_H__0788E7E9_71EF_11D2_B95A_0060083F73D6__INCLUDED_)
|
#include<bits/stdc++.h>
using namespace std;
int main(){
int b;
cin>>b;
cout<< (floor(sqrt(b - 1)) - ceil(sqrt(1)) + 1);
return 0;
}
|
#pragma once
#include "l10n/LocaleManager.h"
namespace BeeeOn {
class SystemLocaleManager : public LocaleManager {
public:
Locale parse(const std::string &input) override;
Locale chooseBest(const std::vector<std::string> &input) override;
};
}
|
// Font block 'arial13_cyrillic_1bpp_0x401_0x401' definition
//
// Bitmap data
static const esU8 sc_arial13_cyrillic_1bpp_0x401_0x401_data[] = {
________,
_XXXXXX_,
_X______,
_X______,
_X______,
_XXXXXX_,
_X______,
_X______,
_X______,
_XXXXXX_,
________,
________,
________,
};
// Font block 'arial13_cyrillic_1bpp_0x401_0x401' glyphs offsets data
static const esU16 sc_arial13_cyrillic_1bpp_0x401_0x401_otbl[] = {
0, //< Offset for symbol 0x00000401 ¨
8 //< Last offset item
};
// Font 'arial13_cyrillic_1bpp_0x401_0x401' block glyphs bitmap
static const ESGUI_BITMAP sc_arial13_cyrillic_1bpp_0x401_0x401_bmp = {
// size
{8, 13},
// hdr
{
1, //< colorFmt
0, //< haveTransparentColor
0 //< clrTransparent
},
// data
(esU8*)sc_arial13_cyrillic_1bpp_0x401_0x401_data
};
// Font 'arial13_cyrillic_1bpp_0x401_0x401' block data
const ESGUI_FONT_DATA c_arial13_cyrillic_1bpp_0x401_0x401 = {
&sc_arial13_cyrillic_1bpp_0x401_0x401_bmp, //< data (glyphs bitmap)
0x401, //< chFirst
0x401, //< chLast
3, //< spaceWidth
7, //< nullWidth
sc_arial13_cyrillic_1bpp_0x401_0x401_otbl //< glyphsMap
};
// Font block 'arial13_cyrillic_1bpp_0x410_0x44F' definition
//
// Bitmap data
static const esU8 sc_arial13_cyrillic_1bpp_0x410_0x44F_data[] = {
________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,____X_X_,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,
___X____,XXXXX___,XXXXX___,XXXXXX__,XXXXX__X,XXXXX_XX,___X___X,X_XXXX__,_X_____X,__X_____,X__X___X,X__XXXXX,__X_____,X__X____,_X____XX,X____XXX,XXXX__XX,XXX_____,XXX___XX,XXXXX_X_,____X___,_X____X_,____X_X_,____X__X,____X__X,___X___X,__X___X_,__X_XXXX,_______X,______X_,_X______,___XXX__,__X____X,XX_____X,XXXXX___,_______X,XXX_____,________,________,________,________,________,____XXX_,________,________,________,________,________,________,________,________,_______X,________,________,________,________,________,________,________,________,________,________,________,
__X_X___,X_______,X____X__,X_______,X___X__X,________,X__X__X_,_X____X_,_X____XX,__X____X,X__X__X_,___X___X,__XX___X,X__X____,_X___X__,_X___X__,___X__X_,___X___X,___X____,_X____X_,____X__X,XXXX___X,___X__X_,____X__X,____X__X,___X___X,__X___X_,__X____X,_______X,______X_,_X______,__X___X_,__X___X_,__X___X_,____X___,______X_,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,_______X,________,________,________,________,________,________,________,________,________,________,________,
__X_X___,X_______,X____X__,X_______,X___X__X,________,X__X__X_,______X_,_X___X_X,__X___X_,X__X__X_,___X___X,__XX___X,X__X____,_X__X___,__X__X__,___X__X_,___X__X_,____X___,_X_____X,___X__X_,_X__X__X,___X__X_,____X__X,____X__X,___X___X,__X___X_,__X____X,_______X,______X_,_X______,_X_____X,__X__X__,___X__X_,____X___,XXX___X_,XX___XXX,___XXX__,XXXX___X,XX__XX__,X__XX_XX,X___X___,X__X___X,__X__X__,XXXXX__X,X___XX__,X___X___,XXX___XX,XXX__X_X,X____XX_,_XXXXXX_,__X__XXX,XX__X___,X_X___X_,X___X__X,__X__X__,X__X__X_,_XX_____,_X_____X,__X_____,__XX___X,__XXX___,_XXXX___,
__X_X___,X_______,X____X__,X_______,X___X__X,________,X__X__X_,______X_,_X___X_X,__X___X_,X__X_X__,___X___X,__X_X_X_,X__X____,_X__X___,__X__X__,___X__X_,___X__X_,________,_X_____X,___X_X__,_X___X__,X_X___X_,____X__X,____X__X,___X___X,__X___X_,__X____X,_______X,______X_,_X______,_______X,__X__X__,___X__X_,____X__X,___X__XX,__X__X__,X__X____,X__X__X_,__X__X__,X__X_X__,_X__X__X,X__X__XX,__X_X___,X___X__X,X___XX__,X___X__X,___X__X_,__X__XX_,_X__X__X,___X__X_,__X_X__X,__X__X_X,__X___X_,X___X__X,__X__X__,X__X__X_,__X_____,_X_____X,__X_____,_X__X__X,_X___X__,X___X___,
_X___X__,XXXXX___,XXXXXX__,X_______,X___X__X,XXXXX___,_XXXXX__,___XXX__,_X__X__X,__X__X__,X__XXX__,___X___X,__X_X_X_,X__XXXXX,XX__X___,__X__X__,___X__XX,XXX___X_,________,_X______,X_X__X__,_X___X__,_X____X_,____X__X,____X__X,___X___X,__X___X_,__X____X,XXXX___X,XXXX__X_,_XXXXX__,____XXXX,__XXXX__,___X___X,XXXXX___,___X__X_,__X__X__,X__X____,X__X__X_,__X___X_,X_X_____,_X__X__X,X__X__XX,__X_X___,X___X__X,X___XX__,X___X__X,___X__X_,__X__X__,_X__X___,___X___X,_X__X__X,__X__X_X,__X___X_,X___X__X,__X__X__,X__X__X_,__X_____,_X_____X,__X_____,____X__X,_X___X__,X___X___,
_XXXXX__,X____X__,X____X__,X_______,X___X__X,________,X__X__X_,______X_,_X_X___X,__X_X___,X__X__X_,___X___X,__X_X_X_,X__X____,_X__X___,__X__X__,___X__X_,______X_,________,_X______,X_X__X__,_X___X__,X_X___X_,____X___,XXXXX__X,___X___X,__X___X_,__X____X,____X__X,____X_X_,_X____X_,_______X,__X__X__,___X____,X___X___,XXXX__X_,__X__XXX,___X____,X__X__XX,XXX____X,XX_____X,X___X_X_,X__X_X_X,__XX____,X___X__X,_X_X_X__,XXXXX__X,___X__X_,__X__X__,_X__X___,___X___X,_X__X__X,__X___X_,__X___X_,X___X__X,__X__X__,X__X__X_,__XXXX__,_XXXX__X,__XXXX__,___XX__X,XX___X__,_XXXX___,
_X___X__,X____X__,X____X__,X______X,____X__X,________,X__X__X_,______X_,_X_X___X,__X_X___,X__X__X_,___X___X,__X_X_X_,X__X____,_X__X___,__X__X__,___X__X_,______X_,____X___,_X______,_X____X_,_X__X__X,___X__X_,____X___,____X__X,___X___X,__X___X_,__X____X,____X__X,____X_X_,_X____X_,_X_____X,__X__X__,___X___X,____X__X,___X__X_,__X__X__,X__X____,X__X__X_,______X_,X_X_____,_X__XX__,X__XX__X,__X_X___,X___X__X,_X_X_X__,X___X__X,___X__X_,__X__X__,_X__X___,___X___X,_X__X__X,__X__X_X,__X___X_,_XXXX__X,__X__X__,X__X__X_,__X___X_,_X___X_X,__X___X_,____X__X,_X___X__,_X__X___,
X_____X_,X____X__,X____X__,X______X,____X__X,_______X,___X___X,_X____X_,_XX____X,__XX____,X__X___X,___X___X,__X__X__,X__X____,_X___X__,_X___X__,___X__X_,_______X,___X____,_X______,_X_____X,XXXX___X,___X__X_,____X___,____X__X,___X___X,__X___X_,__X____X,____X__X,____X_X_,_X____X_,__X___X_,__X___X_,__X____X,____X__X,__XX__X_,__X__X__,X__X___X,___X__X_,__X__X__,X__X_X__,_X__XX__,X__XX__X,__X_X___,X___X__X,_X_X_X__,X___X__X,___X__X_,__X__XX_,_X__X__X,___X____,X___X__X,__X__X_X,__X___X_,____X__X,__X__X__,X__X__X_,__X___X_,_X___X_X,__X___X_,_X__X__X,_X___X__,X___X___,
X_____X_,XXXXX___,XXXXX___,X_____XX,XXXXXX_X,XXXXX_X_,___X____,X_XXXX__,_X_____X,__X_____,X__X____,XXX____X,__X__X__,X__X____,_X____XX,X____X__,___X__X_,________,XXX_____,_X_____X,X_______,_X____X_,____X_XX,XXXXXX__,____X__X,XXXXXXXX,__XXXXXX,XXXX___X,XXXX___X,XXXX__X_,_XXXXX__,___XXX__,__X____X,XX____X_,____X___,XX_X___X,XX___XXX,___X__XX,XXXXX__X,XX__X___,X___X_XX,X___X___,X__X___X,__X__X_X,____X__X,__X__X__,X___X___,XXX___X_,__X__X_X,X____XX_,___X____,X____XXX,XX__X___,X_XXXXXX,____X__X,XXXXXX__,XXXXXXXX,__XXXX__,_XXXX__X,__XXXX__,__XX___X,__XXX___,X___X___,
________,________,________,______X_,_____X__,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,_____X__,________,________,________,___X____,________,________,________,________,________,________,________,________,________,______X_,____X___,________,________,________,________,________,________,________,________,________,_____X__,________,________,X______X,________,_______X,________,________,_______X,________,________,________,________,________,________,
________,________,________,______X_,_____X__,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,_____X__,________,________,________,___X____,________,________,________,________,________,________,________,________,________,______X_,____X___,________,________,________,________,________,________,________,________,________,_____X__,________,_______X,_______X,________,_______X,________,________,_______X,________,________,________,________,________,________,
________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,
};
// Font block 'arial13_cyrillic_1bpp_0x410_0x44F' glyphs offsets data
static const esU16 sc_arial13_cyrillic_1bpp_0x410_0x44F_otbl[] = {
0, //< Offset for symbol 0x00000410 À
7, //< Offset for symbol 0x00000411 Á
15, //< Offset for symbol 0x00000412 Â
23, //< Offset for symbol 0x00000413 Ã
30, //< Offset for symbol 0x00000414 Ä
38, //< Offset for symbol 0x00000415 Å
46, //< Offset for symbol 0x00000416 Æ
57, //< Offset for symbol 0x00000417 Ç
64, //< Offset for symbol 0x00000418 È
73, //< Offset for symbol 0x00000419 É
82, //< Offset for symbol 0x0000041A Ê
89, //< Offset for symbol 0x0000041B Ë
97, //< Offset for symbol 0x0000041C Ì
106, //< Offset for symbol 0x0000041D Í
115, //< Offset for symbol 0x0000041E Î
124, //< Offset for symbol 0x0000041F Ï
133, //< Offset for symbol 0x00000420 Ð
141, //< Offset for symbol 0x00000421 Ñ
150, //< Offset for symbol 0x00000422 Ò
157, //< Offset for symbol 0x00000423 Ó
165, //< Offset for symbol 0x00000424 Ô
174, //< Offset for symbol 0x00000425 Õ
181, //< Offset for symbol 0x00000426 Ö
190, //< Offset for symbol 0x00000427 ×
198, //< Offset for symbol 0x00000428 Ø
209, //< Offset for symbol 0x00000429 Ù
220, //< Offset for symbol 0x0000042A Ú
230, //< Offset for symbol 0x0000042B Û
240, //< Offset for symbol 0x0000042C Ü
248, //< Offset for symbol 0x0000042D Ý
257, //< Offset for symbol 0x0000042E Þ
269, //< Offset for symbol 0x0000042F ß
278, //< Offset for symbol 0x00000430 à
285, //< Offset for symbol 0x00000431 á
292, //< Offset for symbol 0x00000432 â
298, //< Offset for symbol 0x00000433 ã
302, //< Offset for symbol 0x00000434 ä
309, //< Offset for symbol 0x00000435 å
316, //< Offset for symbol 0x00000436 æ
325, //< Offset for symbol 0x00000437 ç
331, //< Offset for symbol 0x00000438 è
338, //< Offset for symbol 0x00000439 é
345, //< Offset for symbol 0x0000043A ê
351, //< Offset for symbol 0x0000043B ë
358, //< Offset for symbol 0x0000043C ì
367, //< Offset for symbol 0x0000043D í
374, //< Offset for symbol 0x0000043E î
381, //< Offset for symbol 0x0000043F ï
388, //< Offset for symbol 0x00000440 ð
395, //< Offset for symbol 0x00000441 ñ
401, //< Offset for symbol 0x00000442 ò
406, //< Offset for symbol 0x00000443 ó
411, //< Offset for symbol 0x00000444 ô
420, //< Offset for symbol 0x00000445 õ
425, //< Offset for symbol 0x00000446 ö
432, //< Offset for symbol 0x00000447 ÷
438, //< Offset for symbol 0x00000448 ø
447, //< Offset for symbol 0x00000449 ù
456, //< Offset for symbol 0x0000044A ú
464, //< Offset for symbol 0x0000044B û
473, //< Offset for symbol 0x0000044C ü
480, //< Offset for symbol 0x0000044D ý
486, //< Offset for symbol 0x0000044E þ
495, //< Offset for symbol 0x0000044F ÿ
502 //< Last offset item
};
// Font 'arial13_cyrillic_1bpp_0x410_0x44F' block glyphs bitmap
static const ESGUI_BITMAP sc_arial13_cyrillic_1bpp_0x410_0x44F_bmp = {
// size
{502, 13},
// hdr
{
1, //< colorFmt
0, //< haveTransparentColor
0 //< clrTransparent
},
// data
(esU8*)sc_arial13_cyrillic_1bpp_0x410_0x44F_data
};
// Font 'arial13_cyrillic_1bpp_0x410_0x44F' block data
const ESGUI_FONT_DATA c_arial13_cyrillic_1bpp_0x410_0x44F = {
&sc_arial13_cyrillic_1bpp_0x410_0x44F_bmp, //< data (glyphs bitmap)
0x410, //< chFirst
0x44F, //< chLast
3, //< spaceWidth
7, //< nullWidth
sc_arial13_cyrillic_1bpp_0x410_0x44F_otbl //< glyphsMap
};
// Font block 'arial13_cyrillic_1bpp_0x451_0x451' definition
//
// Bitmap data
static const esU8 sc_arial13_cyrillic_1bpp_0x451_0x451_data[] = {
________,
__X_X___,
________,
__XXX___,
_X___X__,
_X___X__,
_XXXXX__,
_X______,
_X___X__,
__XXX___,
________,
________,
________,
};
// Font block 'arial13_cyrillic_1bpp_0x451_0x451' glyphs offsets data
static const esU16 sc_arial13_cyrillic_1bpp_0x451_0x451_otbl[] = {
0, //< Offset for symbol 0x00000451 ¸
7 //< Last offset item
};
// Font 'arial13_cyrillic_1bpp_0x451_0x451' block glyphs bitmap
static const ESGUI_BITMAP sc_arial13_cyrillic_1bpp_0x451_0x451_bmp = {
// size
{7, 13},
// hdr
{
1, //< colorFmt
0, //< haveTransparentColor
0 //< clrTransparent
},
// data
(esU8*)sc_arial13_cyrillic_1bpp_0x451_0x451_data
};
// Font 'arial13_cyrillic_1bpp_0x451_0x451' block data
const ESGUI_FONT_DATA c_arial13_cyrillic_1bpp_0x451_0x451 = {
&sc_arial13_cyrillic_1bpp_0x451_0x451_bmp, //< data (glyphs bitmap)
0x451, //< chFirst
0x451, //< chLast
3, //< spaceWidth
7, //< nullWidth
sc_arial13_cyrillic_1bpp_0x451_0x451_otbl //< glyphsMap
};
|
#include <bits/stdc++.h>
using namespace std;
/*
Prints whether the input was a prime number or not.
- if number is 0 or 1: not prime
- if the number has a factor of 2: not prime
- check all the odd numbers starting from 3 and below sqrt(n) to see if they
are factors of n: if so not prime
- if the number is 2: prime
*/
string primality(int n) {
bool prime = false;
if (n > 1) {
prime = true;
if (n % 2 == 0) {
prime = false;
}
for (int x = 3; x <= std::sqrt(n); x += 2) {
if (n % x == 0) {
prime = false;
}
}
}
if (n == 2) {
prime = true;
}
if (prime) {
return "Prime";
} else {
return "Not prime";
}
}
// Main function for testing primality function.
int main()
{
int count = 0;
for (int i = 1; i < 100; i++) {
if (primality(i) == "Prime") {
count++;
std::cout << i << "\n";
}
}
std::cout << "\n\n";
std::cout << count << "\n";
// ofstream fout(getenv("OUTPUT_PATH"));
//
// int p;
// cin >> p;
// cin.ignore(numeric_limits<streamsize>::max(), '\n');
//
// for (int p_itr = 0; p_itr < p; p_itr++) {
// int n;
// cin >> n;
// cin.ignore(numeric_limits<streamsize>::max(), '\n');
//
// string result = primality(n);
//
// fout << result << "\n";
// }
//
// fout.close();
}
|
// Example 6.2 : std::vector
// Created by Oleksiy Grechnyev 2017
// Class Tjej is used here, it logs Ctors and Dtors
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <memory>
#include "Tjej.h"
using namespace std;
//=======================================
/// Print a container. Works also with built-in arrays.
/// pair from maps cannot be printed like this
template <typename C>
void print(const C & c){
for (const auto & e : c)
cout << e << " ";
cout << endl;
}
//==============================
/// Print a container. This version uses iterators
template <typename C>
void print2(const C & c){
for (auto it = begin(c); it != end(c); ++it)
cout << *it << " ";
cout << endl;
}
//==============================
int main(){
{
cout << "-----------------------------";
cout << "\nstd::vector creation : \n\n";
vector<int> vI1; // Empty vector
vI1.push_back(11); // Add elements to an empty vector
vI1.push_back(12);
vI1.push_back(13);
cout << "vI1 = "; print(vI1);
vector<int> vI2(10); // vector of 10 elements
cout << "vI2 = "; print(vI2);
vector<int> vI3(10, 13); // vector of 10 elements equal to 13
cout << "vI3 = "; print(vI3);
vector<int> vI4{10, 13}; // vector of two elements : 10, 13
cout << "vI4 = "; print(vI4);
vector<int> vI5 = {2, 3, 7, 11, 13, 17, 19, 23}; // List assignment constructor
cout << "vI5 = "; print(vI5);
vector<string> vS{"Maria", "Nel", "Sophia", "Clair", "Mirage"}; // List constructor
cout << "vS = "; print(vS);
vector<int> vI6; // Empty vector
vI6 = {1, 2, 7, 13}; // assign a list
cout << "vI6 = "; print(vI6);
vI3.swap(vI6); // swap is very efficient
}
{
cout << "-----------------------------";
cout << "\nstd::vector logging copy/move operations with Tjej: \n\n";
{
cout << "\ncreate 5 elements, then fill with at(): \n" << endl;
vector<Tjej> vT(5); // Note: that calls default constructor of Tjej 5 times !!!
for (int i=0; i < 5; ++i)
vT.at(i) = Tjej("Tjej #" + to_string(i));
}
{
cout << "\nfill with push_back() : move : \n" << endl;
vector<Tjej> vT; // Empty vector
for (int i=0; i < 5; ++i)
// push_back with a temp is a move
vT.push_back(Tjej("Tjej #" + to_string(i)));
}
{
cout << "\nfill with emplace_back() \n" << endl;
vector<Tjej> vT; // Empty vector
for (int i=0; i < 5; ++i)
// push_back with a temp is a move
vT.emplace_back("Tjej #" + to_string(i));
}
{
cout << "\nfill with reserve(5) + emplace_back() \n" << endl;
vector<Tjej> vT; // Empty vector
vT.reserve(5);
for (int i=0; i < 5; ++i)
// push_back with a temp is a move
vT.emplace_back("Tjej #" + to_string(i));
}
}
{
cout << "-----------------------------";
cout << "\nstd::vector capacity growth : \n\n";
vector<int> v;
for (int i = 0; i <= 40; ++i) {
cout << "size = " << v.size() << ", capacity = " << v.capacity() << endl;
v.push_back(i);
}
}
{
cout << "-----------------------------";
cout << "\nstd::vector insert example : \n\n";
vector<int> v{1, 2, 3, 4, 5};
cout << "v = "; print(v);
auto pos = find(v.cbegin(), v.cend(), 3); // Find position of 3
pos = v.insert(pos, 17); // Insert BEFORE 3, returns iterator to 17
pos = v.insert(pos, {21, 22}); // Insert list before 17
pos = v.emplace(pos, 33); // Emplace BEFORE 21, returns iterator to 33
cout << "v = "; print(v);
// How to insert in a loop. You cannot use range for !!!
for (auto it = v.cbegin(); it != v.cend(); ++it)
if (*it > 20 && *it < 30)
it = v.insert(it, 49) + 1; // Insert 49 BEFORE 21, 22
// You need +1 here to avoid repeating the insert before 21 until program crashes
// it -> 21
// insert 17 before 21, it -> 17
// +1 : it -> 21
// ++it : iy -> 22
cout << "v = "; print(v);
}
{
cout << "-----------------------------";
cout << "\nstd::vector erase example : \n\n";
vector<int> v{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
auto pos = find(v.cbegin(), v.cend(), 2); // Find 2
pos = v.erase(pos); // Erase 2, pos -> 3
pos = v.erase(pos, pos+3); // Erase 3, 5, 6
cout << "v = "; print(v);
v.assign({0, 1, 2, 3, 4, 5, 6, 7, 8, 9}); // Just like Ctor
// Delete all even numbers in a for loop
for (auto it = v.cbegin(); it != v.cend(); ++it)
if (*it % 2 == 0)
it = v.erase(it) - 1; // -1 to negate ++it
cout << "v = "; print(v);
}
return 0;
}
|
// Copyright (c) 2011-2017 The Cryptonote developers
// Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs
// Copyright (c) 2018-2023 Conceal Network & Conceal Devs
//
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#pragma once
#include <string>
#include <array>
#include <boost/date_time/posix_time/posix_time.hpp>
#undef ERROR
namespace logging {
enum Level {
FATAL = 0,
ERROR = 1,
WARNING = 2,
INFO = 3,
DEBUGGING = 4,
TRACE = 5
};
extern const std::string BLUE;
extern const std::string GREEN;
extern const std::string RED;
extern const std::string YELLOW;
extern const std::string WHITE;
extern const std::string CYAN;
extern const std::string MAGENTA;
extern const std::string BRIGHT_BLUE;
extern const std::string BRIGHT_GREEN;
extern const std::string BRIGHT_RED;
extern const std::string BRIGHT_YELLOW;
extern const std::string BRIGHT_WHITE;
extern const std::string BRIGHT_CYAN;
extern const std::string BRIGHT_MAGENTA;
extern const std::string DEFAULT;
class ILogger {
public:
const static char COLOR_DELIMETER;
const static std::array<std::string, 6> LEVEL_NAMES;
virtual void operator()(const std::string& category, Level level, boost::posix_time::ptime time, const std::string& body) = 0;
};
#ifndef ENDL
#define ENDL std::endl
#endif
}
|
#ifndef NNTPRANGE_H
#define NNTPRANGE_H
#include "modules/util/opstring.h"
# include "modules/util/simset.h"
#include "adjunct/m2/src/include/defs.h"
class NntpBackend;
class NNTPRangeItem : public Link
{
public:
INT32 m_from;
INT32 m_to;
NNTPRangeItem();
private:
NNTPRangeItem(const NNTPRangeItem&);
NNTPRangeItem& operator =(const NNTPRangeItem&);
};
class NNTPRange
{
private:
Head range_list;
INT32 m_availablerange_from;
INT32 m_availablerange_to;
public:
NNTPRange();
~NNTPRange();
OP_STATUS SetReadRange(const OpStringC8& string);
void SetAvailableRange(INT32 from, INT32 to);
OP_STATUS SetAvailableRange(const OpStringC8& available_range);
void GetAvailableRange(UINT32& from, UINT32& to) {from=m_availablerange_from; to=m_availablerange_to;}
INT32 GetUnreadCount() const;
OP_STATUS GetReadRange(OpString8& string) const;
BOOL IsUnread(INT32 index) const {return !IsRead(index);}
BOOL IsRead(INT32 index) const;
/* Find the first range where from>=low_limit. low_limit will be returned as to+1, and string will be empty if no range is found.
if count is non-NULL, the strings won't be assigned, and count will contain the number of items in the range.
*/
OP_STATUS GetNextUnreadRange(INT32& low_limit, BOOL optimize, BOOL only_one_item, OpString8& unread_string, OpString8& optimized_string, INT32* count = NULL, INT32* max_to = NULL) const;
INT32 GetNextUnreadCount(INT32& max_to) const;
OP_STATUS AddRange(const OpStringC8& string);
private:
OP_STATUS ParseNextRange(char*& range_ptr, INT32& from, INT32& to);
OP_STATUS AddRange(INT32 from, INT32 to);
NNTPRange(const NNTPRange&);
NNTPRange& operator =(const NNTPRange&);
};
#endif // NNTPRANGE_H
|
#include <algorithm>
#include "vtr_assert.h"
#include "vtr_log.h"
#include "pin_constraints.h"
/************************************************************************
* Member functions for class PinConstraints
***********************************************************************/
/************************************************************************
* Constructors
***********************************************************************/
PinConstraints::PinConstraints() {
return;
}
/************************************************************************
* Public Accessors : aggregates
***********************************************************************/
PinConstraints::pin_constraint_range PinConstraints::pin_constraints() const {
return vtr::make_range(pin_constraint_ids_.begin(), pin_constraint_ids_.end());
}
/************************************************************************
* Public Accessors : Basic data query
***********************************************************************/
openfpga::BasicPort PinConstraints::pin(const PinConstraintId& pin_constraint_id) const {
/* validate the pin_constraint_id */
VTR_ASSERT(valid_pin_constraint_id(pin_constraint_id));
return pin_constraint_pins_[pin_constraint_id];
}
std::string PinConstraints::net(const PinConstraintId& pin_constraint_id) const {
/* validate the pin_constraint_id */
VTR_ASSERT(valid_pin_constraint_id(pin_constraint_id));
return pin_constraint_nets_[pin_constraint_id];
}
bool PinConstraints::empty() const {
return 0 == pin_constraint_ids_.size();
}
/************************************************************************
* Public Mutators
***********************************************************************/
void PinConstraints::reserve_pin_constraints(const size_t& num_pin_constraints) {
pin_constraint_ids_.reserve(num_pin_constraints);
pin_constraint_pins_.reserve(num_pin_constraints);
pin_constraint_nets_.reserve(num_pin_constraints);
}
PinConstraintId PinConstraints::create_pin_constraint(const openfpga::BasicPort& pin,
const std::string& net) {
/* Create a new id */
PinConstraintId pin_constraint_id = PinConstraintId(pin_constraint_ids_.size());
pin_constraint_ids_.push_back(pin_constraint_id);
pin_constraint_pins_.push_back(pin);
pin_constraint_nets_.push_back(net);
return pin_constraint_id;
}
/************************************************************************
* Internal invalidators/validators
***********************************************************************/
/* Validators */
bool PinConstraints::valid_pin_constraint_id(const PinConstraintId& pin_constraint_id) const {
return ( size_t(pin_constraint_id) < pin_constraint_ids_.size() ) && ( pin_constraint_id == pin_constraint_ids_[pin_constraint_id] );
}
|
#include <iostream>
#include <vector>
//using namespace std;
using std::cout;
using std::string;
class Animal {
public:
string name = "Animal";
// 「虚函数」告诉编译器不要静态链接到该函数,而是根据所调用的对象类型(Class)去选择调用相应的函数,
// 这种操作被称为动态链接或后期绑定,调用函数的方法需要在程序运行过程中查表完成,根据对象中虚指针指向的虚表中的地址
// 那么「纯虚函数」就是父类的virtual没有主体,例如virtual int area()=0;
// 用到多态时析构函数要写成虚函数?
virtual void eat() {
cout << this->name << " is eating\n";
}
virtual ~Animal() {
cout << "Animal's deconstructor\n";
}
};
// C++默认是protected继承
class Cat : virtual public Animal {
public:
~Cat() override {
cout << "Cat's deconstructor\n";
}
string name = "Cat";
void eat() override {
cout << this->name << " is eating\n";
}
};
// 2. 虚继承除了解决运行时多态还解决了菱形继承问题: 例如BC继承了A,D又多继承了BC,如果A有name字段那么D会有两份name
// 虚继承: BC继承A后会得到A的name字段,但是BC再往下派生的类会没有name字段
// 可以认为虚继承为了解决diamond inheritance带来的字段重复
class Dog : virtual public Animal {
public:
~Dog() override {
cout << "Dog's deconstructor\n";
}
string name = "Dog";
void eat() override {
cout << this->name << " is eating\n";
}
};
void animal_eat_by_ref(Animal& animal) {
animal.eat();
}
void animal_eat_by_ptr(Animal* animal) {
cout << "type: " << typeid(decltype(animal)).name() << '\n';
animal->eat();
}
struct DynAnimal {
virtual void eat() {}
};
// 可以写成virtual DynAnimal也可以不加virtual
struct CatStruct: virtual DynAnimal {
void eat() override {
cout << "CatStruct is eatring" << '\n';
}
};
struct DogStruct: DynAnimal {
void eat() override {
cout << "DogStruct is eatring" << '\n';
}
};
void temp() {}
// C++/Java函数重载(overload)的返回值的返回值可以不同
int main() {
// new和delete一般要成对出现
int* ptr = new int;
delete ptr;
// auto* animal = new Animal;
// animal->eat();
// 省略new Cat()的写法
Cat cat;
Dog dog;
animal_eat_by_ref(cat);
animal_eat_by_ref(dog);
animal_eat_by_ptr(&cat);
animal_eat_by_ptr(&dog);
// 如果Animal的析构函数不是虚函数,则cat_2析构时会调用Animal的析构函数而不是Cat自己的析构函数造成UB
Animal* cat_2 = new Cat();
delete cat_2;
cout << "== test DynAnimal\n\n";
auto dyn_cat = CatStruct{};
auto dyn_dog = DogStruct{};
auto animals = std::vector<DynAnimal*>{&dyn_cat, &dyn_dog};
for (auto animal : animals) {
animal->eat();
}
// class Pig: Animal
// can't cast Pig to it private Base class Animal
// animal_eat(&pig);
cout << "== end\n\n";
return 0;
}
|
//
// Created by glyphack on 7/11/19.
//
#include "game.h"
GameController::GameController(sf::RenderWindow *window) {
}
void GameController::start() {
}
void GameController::cycle() {
}
|
#pragma once
#include "IQuizView.h"
namespace qp
{
class CQuizView : public IQuizView
{
public:
CQuizView();
~CQuizView();
};
}
|
/*
* Copyright 2019 LogMeIn
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
// Eric Niebler contributed this detection macro to Folly:
// https://github.com/facebook/folly/blob/master/folly/Portability.h#L407
#if defined(__cpp_coroutines) && __cpp_coroutines >= 201703L
#if defined(__has_include) && __has_include(<experimental/coroutine>)
#define ASYNCLY_HAS_COROUTINES 1
#endif
#endif
#if defined(_MSC_VER) && defined(_RESUMABLE_FUNCTIONS_SUPPORTED)
#define ASYNCLY_HAS_COROUTINES 1
#endif
// C++ Coroutine TS Trait implementations
#ifdef ASYNCLY_HAS_COROUTINES
#include <boost/optional.hpp>
#include <experimental/coroutine>
namespace asyncly {
template <typename T> class Future;
template <typename T> class Promise;
namespace detail {
template <typename T> struct coro_awaiter {
coro_awaiter(Future<T>* future);
~coro_awaiter();
bool await_ready();
// todo: use bool-version to shortcut ready futures
void await_suspend(std::experimental::coroutine_handle<> coroutine_handle);
T await_resume();
private:
Future<T>* future_;
std::exception_ptr error_;
boost::optional<T> value_;
};
template <> struct coro_awaiter<void> {
coro_awaiter(Future<void>* future);
~coro_awaiter();
bool await_ready();
// todo: use bool-version to shortcut ready futures
void await_suspend(std::experimental::coroutine_handle<> coroutine_handle);
void await_resume();
private:
Future<void>* future_;
std::exception_ptr error_;
};
template <typename T> struct coro_promise {
std::unique_ptr<Promise<T>> promise_;
coro_promise();
~coro_promise();
std::experimental::suspend_never initial_suspend();
std::experimental::suspend_never final_suspend();
void unhandled_exception();
void return_value(T value);
};
template <> struct coro_promise<void> {
std::unique_ptr<Promise<void>> promise_;
coro_promise();
~coro_promise();
Future<void> get_return_object();
std::experimental::suspend_never initial_suspend();
std::experimental::suspend_never final_suspend();
void unhandled_exception();
void return_void();
};
}
}
#endif
|
#include <iostream>
#include <bitset>
#include <vector>
#include <set>
#include <string>
#include <cmath>
#define INF 300000
using namespace std;
set<string> list;
class CuttingBitString
{
public:
template <class T>
string toStr(T a)
{
string str;
bool isStart = false;
for (int i=(int)a.size()-1;i>=0;--i) {
if (!isStart && a[i])
isStart = true;
if (isStart) {
if (a[i]) {
str.push_back('1');
}
else {
str.push_back('0');
}
}
}
return str;
}
template <class T>
T add(T a,T b)
{
bool isCarry = false;
T result;
for (int i = 0; i < a.size(); ++i) {
if(a[i] && b[i] && isCarry) {
isCarry = true;
result.set(i);
}
else if (a[i] && b[i]) {
isCarry = true;
result.reset(i);
}
else if (isCarry && (a[i] || b[i])) {
isCarry = true;
result.reset(i);
}
else if (a[i] || b[i]) {
isCarry = false;
result.set(i);
}
else if (isCarry) {
isCarry = false;
result.set(i);
}
else {
isCarry = false;
result.reset(i);
}
}
return result;
}
void makeList()
{
vector<string> tmpList;
bitset<55> binary,work;
binary.set(0);
binary.set(2);
list.insert(toStr(binary));
list.insert("1");
for (int i = 0; i < 23; ++i) {
work = binary;
binary = add(binary,work<<=(2));
list.insert(toStr(binary));
}
}
int calcMin(string s)
{
if(s.size() == 0) return 0;
int r = INF;
for (int i=1;i<=s.size();++i) {
if(list.count(s.substr(0,i)) == 1){
cout << "sub" << endl;
r = min(r,1+calcMin(s.substr(i,s.size()-i)));
}
}
return r;
}
int getmin(string S)
{
makeList();
for (set<string>::iterator it=list.begin();it != list.end();++it) {
cout << *it << endl;
}
int min = calcMin(S);
return min == INF ? -1 : min;
}
};
|
//: C03:AutoIncrement.cpp
// Kod zrodlowy pochodzacy z ksiazki
// "Thinking in C++. Edycja polska"
// (c) Bruce Eckel 2000
// Informacje o prawie autorskim znajduja sie w pliku Copyright.txt
// Prezentacja uzycia operatorow automatycznej
// inkrementacji i dekrementacji
#include <iostream>
using namespace std;
int main() {
int i = 0;
int j = 0;
cout << ++i << endl; // Preinkrementacja
cout << j++ << endl; // Postinkrementacja
cout << --i << endl; // Predkrementacja
cout << j-- << endl; // Postdekrementacja
} ///:~
|
/* -*- 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.
*/
#include "core/pch.h"
#ifdef SUPPORT_DATA_SYNC
#include "modules/util/str.h"
#include "modules/util/opstring.h"
#include "modules/sync/sync_coordinator.h"
#include "modules/sync/sync_encryption_key.h"
#include "modules/sync/sync_factory.h"
#include "modules/sync/sync_transport.h"
#include "modules/sync/sync_parser.h"
#include "modules/sync/sync_util.h"
#include "modules/prefs/prefsmanager/collections/pc_sync.h"
#include "modules/inputmanager/inputaction.h"
#include "modules/pi/OpSystemInfo.h"
#include "modules/opera_auth/opera_auth_module.h"
#include "modules/opera_auth/opera_auth_oauth.h"
/**
* This class is used in the vector class OpSyncDataListenerVector. One
* OpSyncDataClient instance can be associated to multiple
* OpSyncDataItem::DataItemType values. An instance of this class maps this
* association. An instance of OpSyncDataListenerVector keeps a list of all
* associations.
*/
class OpSyncDataClientItem
{
public:
OpSyncDataClientItem(OpSyncDataClient* listener)
: m_listener(listener) {}
virtual ~OpSyncDataClientItem() {}
OpSyncDataClient* Get() { return m_listener; }
const OpSyncDataClient* Get() const { return m_listener; }
BOOL HasType(OpSyncDataItem::DataItemType type) const {
return (type == OpSyncDataItem::DATAITEM_GENERIC ||
m_types.Find(static_cast<INT32>(type)) >= 0);
}
OP_STATUS AddType(OpSyncDataItem::DataItemType type) {
if (HasType(type))
return OpStatus::OK;
RETURN_IF_ERROR(m_types.Add(static_cast<INT32>(type)));
return OpStatus::OK;
}
void RemoveType(OpSyncDataItem::DataItemType type) {
m_types.RemoveByItem(static_cast<INT32>(type));
}
unsigned int TypeCount() const { return m_types.GetCount(); }
OpSyncDataItem::DataItemType GetType(unsigned int index) const {
return static_cast<OpSyncDataItem::DataItemType>(m_types.Get(index));
}
private:
OpSyncDataClient* m_listener;
OpINT32Vector m_types;
};
// ========== OpSyncTimeout ===================================================
OpSyncTimeout::OpSyncTimeout(OpMessage message)
: m_timeout(SYNC_LOADING_TIMEOUT)
, m_message(message)
{
}
/* virtual */
OpSyncTimeout::~OpSyncTimeout()
{
StopTimeout();
g_main_message_handler->UnsetCallBack(this, m_message);
}
unsigned int OpSyncTimeout::SetTimeout(unsigned int timeout)
{
OP_NEW_DBG("OpSyncTimeout::SetTimeout()", "sync");
OP_DBG(("%d -> %d", m_timeout, timeout));
unsigned int old_timeout = m_timeout;
m_timeout = timeout;
return old_timeout;
}
/* virtual */
void OpSyncTimeout::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2)
{
if (msg == m_message)
OnTimeout();
else
OP_ASSERT(!"Unknown message!");
}
OP_STATUS OpSyncTimeout::StartTimeout(unsigned int timeout)
{
OP_NEW_DBG("OpSyncTimeout::StartTimeout()", "sync");
OP_DBG(("timeout: %ds", timeout));
if (!g_main_message_handler->HasCallBack(this, m_message, 0))
RETURN_IF_ERROR(g_main_message_handler->SetCallBack(this, m_message, 0));
g_main_message_handler->RemoveDelayedMessage(m_message, 0, 0);
g_main_message_handler->PostDelayedMessage(m_message, 0, 0, timeout*1000);
return OpStatus::OK;
}
OP_STATUS OpSyncTimeout::RestartTimeout()
{
OP_NEW_DBG("OpSyncTimeout::RestartTimeout()", "sync");
return StartTimeout(m_timeout);
}
void OpSyncTimeout::StopTimeout()
{
if (g_main_message_handler->HasCallBack(this, m_message, 0))
{
OP_NEW_DBG("OpSyncTimeout::StopTimeout()", "sync");
g_main_message_handler->RemoveDelayedMessage(m_message, 0, 0);
g_main_message_handler->UnsetCallBack(this, m_message);
}
}
// ========== OpSyncCoordinator::OpSyncDataListenerVector =====================
OpSyncDataClientItem* OpSyncCoordinator::OpSyncDataListenerVector::FindListener(OpSyncDataClient* item)
{
for (unsigned i = 0; i < GetCount(); i++)
{
OpSyncDataClientItem* tmp = Get(i);
OP_ASSERT(tmp);
if (tmp->Get() == item)
return tmp;
}
return NULL;
}
// ========== OpSyncCoordinator ===============================================
OpSyncCoordinator::OpSyncCoordinator()
: OpSyncTimeout(MSG_SYNC_POLLING_TIMEOUT)
, m_sync_factory(NULL)
, m_allocator(NULL)
, m_transport(NULL)
, m_parser(NULL)
, m_data_queue(NULL)
#ifdef SYNC_ENCRYPTION_KEY_SUPPORT
, m_encryption_key_manager(0)
#endif // SYNC_ENCRYPTION_KEY_SUPPORT
, m_sync_active(FALSE)
, m_sync_in_progress(FALSE)
#ifdef SELFTEST
, m_is_selftest(FALSE)
#endif // SELFTEST
, m_is_complete_sync_in_progress(FALSE)
, m_is_initialised(FALSE)
, m_is_login_listener(FALSE)
{
OP_NEW_DBG("OpSyncCoordinator::OpSyncCoordinator()", "sync");
#ifdef _DEBUG
// int size = sizeof(OpSyncDataItem);
// size = size; // get rid of warning
#endif
g_main_message_handler->SetCallBack(this, MSG_SYNC_FLUSH_DATATYPE, (MH_PARAM_1)0);
g_main_message_handler->SetCallBack(this, MSG_SYNC_AUTHENTICATE, (MH_PARAM_1)0);
g_main_message_handler->SetCallBack(this, MSG_SYNC_CONNECT, (MH_PARAM_1)0);
}
OpSyncCoordinator::~OpSyncCoordinator()
{
OP_NEW_DBG("OpSyncCoordinator::~OpSyncCoordinator()", "sync");
g_main_message_handler->RemoveDelayedMessage(MSG_SYNC_FLUSH_DATATYPE, 0, 0);
g_main_message_handler->UnsetCallBack(this, MSG_SYNC_FLUSH_DATATYPE);
g_main_message_handler->UnsetCallBack(this, MSG_SYNC_AUTHENTICATE);
g_main_message_handler->UnsetCallBack(this, MSG_SYNC_CONNECT);
Cleanup();
}
OP_STATUS OpSyncCoordinator::SetSyncDataClient(OpSyncDataClient* listener, OpSyncDataItem::DataItemType type)
{
OP_NEW_DBG("OpSyncCoordinator::SetSyncDataClient()", "sync");
OP_DBG(("") << "listener: " << listener << "; type: " << type);
type = OpSyncDataItem::BaseTypeOf(type);
OP_DBG(("base type: ") << type);
OpSyncDataClientItem* item = m_listeners.FindListener(listener);
if (!item)
{
OpAutoPtr<OpSyncDataClientItem> auto_item(OP_NEW(OpSyncDataClientItem, (listener)));
RETURN_OOM_IF_NULL(auto_item.get());
OP_DBG(("Add new OpSyncDataClientItem: %p", auto_item.get()));
RETURN_IF_ERROR(m_listeners.Add(auto_item.get()));
item = auto_item.release();
}
RETURN_IF_ERROR(item->AddType(type));
bool sync_enabled = KeepDataClientsEnabled();
#ifdef _DEBUG
if (sync_enabled && !SyncEnabled())
OP_DBG(("sync was last used less than %d days ago at: %d; so don't disable any type that is currently enabled.", SYNC_CHECK_LAST_USED_DAYS, g_pcsync->GetIntegerPref(PrefsCollectionSync::SyncLastUsed)));
#endif // _DEBUG
OpSyncSupports supports = OpSyncCoordinator::GetSupportsFromType(type);
return item->Get()->SyncDataSupportsChanged(type, sync_enabled && GetSupports(supports));
}
void OpSyncCoordinator::RemoveSyncDataClient(OpSyncDataClient* listener, OpSyncDataItem::DataItemType type)
{
OP_NEW_DBG("OpSyncCoordinator::RemoveSyncDataClient()", "sync");
OP_DBG(("") << "listener: " << listener << "; type: " << type);
OpSyncDataClientItem* item = m_listeners.FindListener(listener);
if (item)
{
item->RemoveType(OpSyncDataItem::BaseTypeOf(type));
if (!item->TypeCount())
{
m_listeners.RemoveByItem(item);
OP_DBG(("Removed OpSyncDataClientItem: %p", item));
OP_DELETE(item);
}
}
}
OP_STATUS OpSyncCoordinator::SetSyncUIListener(OpSyncUIListener* listener)
{
if (m_uilisteners.Find(listener) < 0)
{
OP_NEW_DBG("OpSyncCoordinator::SetSyncUIListener()", "sync");
OP_DBG(("Add OpSyncUIListener %p", listener));
return m_uilisteners.Add(listener);
}
return OpStatus::OK;
}
void OpSyncCoordinator::RemoveSyncUIListener(OpSyncUIListener* listener)
{
if (m_uilisteners.Find(listener) > -1)
{
OP_NEW_DBG("OpSyncCoordinator::RemoveSyncUIListener()", "sync");
OP_DBG(("Remove OpSyncUIListener %p", listener));
m_uilisteners.RemoveByItem(listener);
}
}
OP_STATUS OpSyncCoordinator::Cleanup()
{
OP_NEW_DBG("OpSyncCoordinator::Cleanup()", "sync");
if (m_is_login_listener)
OpStatus::Ignore(g_opera_oauth_manager->RemoveListener(this));
m_is_login_listener = FALSE;
if (m_is_initialised)
g_pcsync->UnregisterListener(this);
m_is_initialised = FALSE;
if (m_data_queue)
m_data_queue->Shutdown();
OP_DELETE(m_transport);
m_transport = NULL;
OP_DELETE(m_sync_factory);
m_sync_factory = NULL;
OP_DELETE(m_data_queue);
m_data_queue = NULL;
OP_DELETE(m_parser);
m_parser = NULL;
OP_DELETE(m_allocator);
m_allocator = NULL;
StopTimeout();
return OpStatus::OK;
}
OP_STATUS OpSyncCoordinator::Init(OpSyncFactory* factory, BOOL use_disk_queue)
{
OP_NEW_DBG("OpSyncCoordinator::Init()", "sync");
if (factory)
{ // ownership is now transferred to this class
OP_DELETE(m_sync_factory);
m_sync_factory = factory;
}
else if (!m_sync_factory)
{
// use the default factory
m_sync_factory = OP_NEW(OpSyncFactory, ());
RETURN_OOM_IF_NULL(m_sync_factory);
}
if (!m_parser)
RETURN_IF_ERROR(m_sync_factory->GetParser(&m_parser, this));
if (!m_transport)
RETURN_IF_ERROR(m_sync_factory->CreateTransportProtocol(&m_transport, this));
if (!m_allocator)
RETURN_IF_ERROR(m_sync_factory->GetAllocator(&m_allocator));
if (!m_data_queue)
RETURN_IF_MEMORY_ERROR(m_sync_factory->GetQueueHandler(&m_data_queue, this, use_disk_queue));
m_parser->SetDataQueue(m_data_queue);
// Register itself as listener to sync prefs changes:
if (!m_is_initialised)
{
RETURN_IF_LEAVE(g_pcsync->RegisterListenerL(this));
m_is_initialised = TRUE;
}
// Set the initial supports values
BroadcastSyncSupportChanged();
return OpStatus::OK;
}
void OpSyncCoordinator::SetUseDiskQueue(BOOL value)
{
m_data_queue->SetUseDiskQueue(value);
}
BOOL OpSyncCoordinator::UseDiskQueue() const
{
return m_data_queue->UseDiskQueue();
}
void OpSyncCoordinator::OnTimeout()
{
OP_NEW_DBG("OpSyncCoordinator::OnTimeout()", "sync");
if (IsSyncActive())
{
OP_DBG(("MSG_SYNC_POLLING_TIMEOUT%s", IsSyncInProgress()?"; sync already in progress":""));
if (!IsSyncInProgress())
OpStatus::Ignore(SyncNow());
OpStatus::Ignore(StartTimeout(m_sync_server_info.GetSyncIntervalLong()));
}
}
void OpSyncCoordinator::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2)
{
OP_NEW_DBG("OpSyncCoordinator::HandleCallback()", "sync");
switch (msg)
{
case MSG_SYNC_AUTHENTICATE:
OP_DBG(("MSG_SYNC_AUTHENTICATE"));
SyncAuthenticate();
break;
case MSG_SYNC_CONNECT:
OP_DBG(("MSG_SYNC_CONNECT"));
SyncConnect();
break;
case MSG_SYNC_FLUSH_DATATYPE:
/* this message is triggered when inconsistency is detected on the
* client, which prompts the module to ask the client to flush all data
* for the data type as dirty.
* par1 is the OpSyncDataItem::DataItemType that shall be flushed. */
OP_DBG(("MSG_SYNC_FLUSH_DATATYPE; type: ") << static_cast<OpSyncDataItem::DataItemType>(par1));
BroadcastSyncDataFlush(static_cast<OpSyncDataItem::DataItemType>(par1), FALSE, TRUE);
break;
default:
OpSyncTimeout::HandleCallback(msg, par1, par2);
}
}
OP_STATUS OpSyncCoordinator::SetSyncActive(BOOL active)
{
OP_NEW_DBG("OpSyncCoordinator::SetSyncActive()", "sync");
OP_DBG(("%s", active?"active":"not active"));
m_sync_active = active;
if (m_sync_active)
{
unsigned long seconds, milliseconds;
g_op_time_info->GetWallClock(seconds, milliseconds);
OP_DBG(("SyncLastUsed: %lu", seconds));
TRAPD(err, g_pcsync->WriteIntegerL(PrefsCollectionSync::SyncLastUsed, seconds));
RETURN_IF_ERROR(SyncNow());
// start timers
// RETURN_IF_ERROR(StartTimeout(m_sync_server_info.GetSyncIntervalShort()));
RETURN_IF_ERROR(StartTimeout(m_sync_server_info.GetSyncIntervalLong()));
}
else
{ // stop timers
StopTimeout();
/* ensure that we request a new OAuth token the next time we activate
* sync again: */
if (g_opera_oauth_manager->IsLoggedIn())
g_opera_oauth_manager->Logout();
}
return OpStatus::OK;
}
OP_STATUS OpSyncCoordinator::GetSyncItem(OpSyncItem** item, OpSyncDataItem::DataItemType type, OpSyncItem::Key primary_key, const uni_char* key_data)
{
OP_NEW_DBG("OpSyncCoordinator::GetSyncItem()", "sync");
OP_DBG(("type: ") << type);
OP_DBG((UNI_L("id: '%s'"), key_data));
return m_allocator->GetSyncItem(item, type, primary_key, key_data);
}
OP_STATUS OpSyncCoordinator::SetLoginInformation(const uni_char* provider, const OpStringC& username, const OpStringC& password)
{
OP_NEW_DBG("OpSyncCoordinator::SetLoginInformation()", "sync");
OP_DBG((UNI_L("provider: %s; username: %s"), provider, username.CStr()));
if (!provider)
{
OP_ASSERT(!"No provider specified, you shall use 'myopera'!");
return OpStatus::ERR_NULL_POINTER;
}
else if (uni_strcmp(provider, UNI_L("myopera")) != 0)
{
OP_ASSERT(!"Unsupported provider, you shall use 'myopera'!");
return OpStatus::ERR_NOT_SUPPORTED;
}
BOOL username_changed = username != m_save_username;
if (!username_changed && password == m_save_password)
/* Nothing to do if the credentials did not change */
return OpStatus::OK;
/* ensure that we request a new OAuth token if username or password are
* different: */
if (g_opera_oauth_manager->IsLoggedIn())
g_opera_oauth_manager->Logout();
OpString new_username;
RETURN_IF_ERROR(new_username.Set(username.CStr()));
OpString new_password;
RETURN_IF_ERROR(new_password.Set(password.CStr()));
#ifdef SYNC_ENCRYPTION_KEY_SUPPORT
/* Try not to fail this method after re-encrypting the encryption-key,
* i.e. all steps that may fail have been done above, everything below is
* expected to pass... */
if (m_encryption_key_manager->HasEncryptionKey())
{
if (username_changed)
{
/* If the username changed, the SyncEncryptionKeyManager needs to
* clear the encryption-key to request the (new) user's
* encryption-key from the Link server: */
m_encryption_key_manager->ClearEncryptionKey();
}
else
{
/* If the password changed (and the username remains the same), the
* SyncEncryptionKeyManager needs to re-encrypt the encryption-key
* with the new credentials and send the newly encrypted
* encryption-key to the Link server: */
OpStatus::Ignore(m_encryption_key_manager->ReencryptEncryptionKey(m_save_username, m_save_password, new_password));
/* Note: ignore the return code here, because failing to re-encrypt
* the encryption-key means that the encryption-key was cleared (in
* ReencryptEncryptionKey()) and we will try to receive a new copy
* of the encryption-key from the Link server in the next connection
* and if that is not possible, we will load it from wand... */
}
}
#endif // SYNC_ENCRYPTION_KEY_SUPPORT
/* Note: TakeOver() is expected to always return OpStatus::OK, so we ignore
* the return value: */
OpStatus::Ignore(m_save_username.TakeOver(new_username));
OpStatus::Ignore(m_save_password.TakeOver(new_password));
new_password.Wipe();
return OpStatus::OK;
}
OP_STATUS OpSyncCoordinator::GetLoginInformation(OpString& username, OpString& password)
{
RETURN_IF_ERROR(username.Set(m_save_username));
return password.Set(m_save_password);
}
BOOL OpSyncCoordinator::OnInputAction(OpInputAction* action)
{
#ifdef ACTION_SYNC_NOW_ENABLED
OP_ASSERT(action);
if (action->GetAction() == OpInputAction::ACTION_SYNC_NOW)
{
OP_NEW_DBG("OpSyncCoordinator::OnInputAction()", "sync");
OP_DBG(("OpInputAction::ACTION_SYNC_NOW: sync is %s%s", IsSyncActive()?"active":"not active", IsSyncInProgress()?" and in progress":""));
if (IsSyncActive() && !IsSyncInProgress())
SyncNow();
return TRUE;
}
#endif // ACTION_SYNC_NOW_ENABLED
return FALSE;
}
OP_STATUS OpSyncCoordinator::SyncNow()
{
OP_NEW_DBG("OpSyncCoordinator::SyncNow()", "sync");
if (m_save_password.IsEmpty())
return OpStatus::ERR_NO_ACCESS;
else if (!m_transport || !m_parser)
return OpStatus::ERR_NULL_POINTER;
else if (!IsSyncActive())
{
OP_DBG(("SYNC_ERROR_SYNC_DISABLED: sync is not active"));
BroadcastSyncError(SYNC_ERROR_SYNC_DISABLED, UNI_L(""));
return OpStatus::ERR_NO_ACCESS;
}
else if (IsSyncInProgress())
{
OP_DBG(("SYNC_ERROR_SYNC_IN_PROGRESS: sync is already in progress"));
OP_ASSERT(!"the caller does a sync before the previous sync has finished");
BroadcastSyncError(SYNC_ERROR_SYNC_IN_PROGRESS, UNI_L(""));
return OpStatus::ERR_NO_ACCESS;
}
RETURN_IF_ERROR(m_sync_state.ReadPrefs());
RETURN_IF_LEAVE(g_pcsync->GetStringPrefL(PrefsCollectionSync::ServerAddress, m_save_server));
m_save_port = 80;
if (!m_is_login_listener)
{
OP_DBG(("Register as OperaOauthManager::LoginListener"));
RETURN_IF_ERROR(g_opera_oauth_manager->AddListener(this));
m_is_login_listener = TRUE;
}
return StartSync();
}
OP_STATUS OpSyncCoordinator::StartSync()
{
OP_NEW_DBG("OpSyncCoordinator::StartSync()", "sync");
/* If the OAuth manager is logged in, we can continue to connect to the
* Link server. If the OAuth manager is not yet logged in, we need to log
* in first to get the OAuth token. */
OpMessage message = g_opera_oauth_manager->IsLoggedIn() ? MSG_SYNC_CONNECT : MSG_SYNC_AUTHENTICATE;
if (g_main_message_handler->PostMessage(message, 0, 0))
{
/* If the message was posted, then the sync process is started, i.e.
* m_sync_in_progress is now TRUE until it is reset to FALSE in
* OnSyncCompleted(), OnSyncError() or ErrorCleanup() when the sync
* process is completely handled: */
SetSyncInProgress(TRUE);
return OpStatus::OK;
}
else
return OpStatus::ERR;
}
void OpSyncCoordinator::SyncAuthenticate()
{
OP_NEW_DBG("OpSyncCoordinator::SyncAuthenticate()", "sync");
OP_STATUS status = g_opera_oauth_manager->Login(m_save_username, m_save_password);
if (OpStatus::IsError(status))
ErrorCleanup(status);
}
// ==================== <OperaOauthManager::LoginListener>
/* virtual */
void OpSyncCoordinator::OnLoginStatusChange(OperaOauthManager::OAuthStatus auth_status, const OpStringC& server_error_message)
{
OP_NEW_DBG("OpSyncCoordinator::OnLoginStatusChange", "sync");
OP_DBG(("OAuth status: %d", auth_status));
OP_STATUS status = OpStatus::OK;
switch (auth_status) {
case OperaOauthManager::OAUTH_LOGIN_SUCCESS_NEW_TOKEN_DOWNLOADED:
OP_DBG(("OperaOauthManager::OAUTH_LOGIN_SUCCESS_NEW_TOKEN_DOWNLOADED"));
/* The login was a success and an OAuth token was downloaded. Now we
* can continue to connect. */
if (!g_main_message_handler->PostMessage(MSG_SYNC_CONNECT, 0, 0))
status = OpStatus::ERR; // could not post the message
break;
case OperaOauthManager::OAUTH_LOGIN_ERROR_WRONG_USERNAME_PASSWORD:
OP_DBG(("OperaOauthManager::OAUTH_LOGIN_ERROR_WRONG_USERNAME_PASSWORD"));
// Wrong username and/or password
OnSyncError(SYNC_ACCOUNT_AUTH_FAILURE, server_error_message);
break;
case OperaOauthManager::OAUTH_LOGIN_ERROR_TIMEOUT:
OP_DBG(("OperaOauthManager::OAUTH_LOGIN_ERROR_TIMEOUT"));
// Timeout while downloading the tokens.
OnSyncError(SYNC_ERROR_COMM_TIMEOUT, server_error_message);
break;
case OperaOauthManager::OAUTH_LOGIN_ERROR_NETWORK:
OP_DBG(("OperaOauthManager::OAUTH_LOGIN_ERROR_NETWORK"));
// Generic network error, downloading token failed
OnSyncError(SYNC_ERROR_COMM_FAIL, server_error_message);
break;
case OperaOauthManager::OAUTH_LOGIN_ERROR_GENERIC:
OP_DBG(("OperaOauthManager::OAUTH_LOGIN_ERROR_GENERIC"));
// Generic/internal error, such as memory problems
OnSyncError(SYNC_ERROR, server_error_message);
break;
case OperaOauthManager::OAUTH_LOGGED_OUT:
OP_DBG(("OperaOauthManager::OAUTH_LOGGED_OUT"));
// Someone has called Logout()
status = OpStatus::ERR; // TODO: use better error-code for cleanup...
break;
};
if (OpStatus::IsError(status) && IsSyncInProgress())
ErrorCleanup(status);
}
// ==================== </OperaOauthManager::LoginListener>
void OpSyncCoordinator::SyncConnect()
{
OP_NEW_DBG("OpSyncCoordinator::SyncConnect()", "sync");
OP_DBG((UNI_L("server: %s; port: %d; username: %s"), m_save_server.CStr(), m_save_port, m_save_username.CStr()));
OP_ASSERT(m_transport && m_parser && "Was Init() called successfully?");
int sync_flags = 0;
if (g_pcsync->GetIntegerPref(PrefsCollectionSync::CompleteSync) != 0 ||
m_data_queue->HasDirtyItems())
sync_flags = OpSyncParser::SYNC_PARSER_COMPLETE_SYNC;
SyncSupportsState supports_state = m_supports_state;
#ifdef SYNC_ENCRYPTION_KEY_SUPPORT
if (supports_state.HasSupports(SYNC_SUPPORTS_ENCRYPTION) &&
!m_encryption_key_manager->IsEncryptionKeyUsable())
/* If we don't have a usable encryption-key, we don't upload
* or download the supports types that require an encryption-key: */
supports_state.SetSupports(SYNC_SUPPORTS_PASSWORD_MANAGER, false);
#endif // SYNC_ENCRYPTION_KEY_SUPPORT
OP_STATUS status = m_parser->Init(sync_flags, m_sync_state, supports_state);
if (OpStatus::IsSuccess(status))
status = GetOutOfSyncData(supports_state);
if (OpStatus::IsSuccess(status))
status = m_transport->Init(m_save_server, m_save_port, m_parser);
if (OpStatus::IsSuccess(status))
{
m_data_queue->PopulateOutgoingItems(supports_state);
status = m_transport->Connect(*m_data_queue->GetSyncDataCollection(OpSyncDataQueue::SYNCQUEUE_OUTGOING), m_sync_state);
}
if (OpStatus::IsError(status))
{
OP_DBG(("error"));
SetSyncActive(FALSE);
OP_DELETE(m_transport);
m_transport = NULL;
}
}
OP_STATUS OpSyncCoordinator::GetOutOfSyncData(SyncSupportsState supports_state)
{
OP_NEW_DBG("OpSyncCoordinator::GetOutOfSyncData()", "sync");
if (m_is_complete_sync_in_progress)
return OpStatus::OK;
for (unsigned int i = 0; i < SYNC_SUPPORTS_MAX; i++)
{
OpSyncSupports supports = static_cast<OpSyncSupports>(i);
if (!supports_state.HasSupports(supports))
continue;
OP_DBG(("") << supports);
/* As there is currently no grouping we need to convert from the
* supports type to a data item type like this.
* Note: it is also assumed that we can send the "main" data type to the
* client and we will get all the info. (i.e. send bookmarks and we get
* bookmarks, bookmark folders, bookmark separators.) This is bad but
* until we have groups how it is. */
OpINT32Vector types;
RETURN_IF_ERROR(OpSyncCoordinator::GetTypesFromSupports(supports, types));
for (unsigned int j = 0; j < types.GetCount(); j++)
{
OpSyncDataItem::DataItemType data_type = static_cast<OpSyncDataItem::DataItemType>(types.Get(j));
/* If sync state for this datatype is 0 or out of sync with global
* sync state send BroadcastSyncDataFlush notification.
* If Sync state for this datatype is 0, then send
* BroadcastSyncDataInitialize() notification. */
if (m_sync_state.IsDefaultValue(supports))
{
OP_DBG(("- ") << data_type << ": sync state is default");
BroadcastSyncDataInitialize(data_type);
BroadcastSyncDataFlush(data_type, TRUE, FALSE);
m_sync_state.SetSyncStatePersistent(supports, TRUE);
}
else if (m_sync_state.IsOutOfSync(supports))
{
OP_DBG(("- ") << data_type << ": sync state is out of sync");
/* Call back to the internal coordinator listener which will
* send to the external listeners */
BroadcastSyncDataFlush(data_type, FALSE, FALSE);
}
}
}
return OpStatus::OK;
}
void OpSyncCoordinator::ContinueSyncData(OpSyncSupports supports)
{
OP_NEW_DBG("OpSyncCoordinator::ContinueSyncData", "sync");
OP_DBG(("supports: ") << supports);
SyncSupportsState supports_state;
supports_state.SetSupports(supports, true);
OpStatus::Ignore(BroadcastDataAvailable(supports_state, m_sync_state));
}
void OpSyncCoordinator::OnSyncStarted(BOOL items_sent)
{
OP_NEW_DBG("OpSyncCoordinator::OnSyncStarted()", "sync");
OP_DBG(("items %ssent", items_sent?"":"not yet "));
for (unsigned int i = 0; i < m_uilisteners.GetCount(); i++)
m_uilisteners.Get(i)->OnSyncStarted(items_sent);
}
void OpSyncCoordinator::ErrorCleanup(OP_STATUS status)
{
OP_NEW_DBG("OpSyncCoordinator::ErrorCleanup()", "sync");
OpString empty;
SetSyncInProgress(FALSE);
BroadcastSyncError(OpStatus::IsMemoryError(status) ? SYNC_ERROR_MEMORY : SYNC_ERROR, empty);
m_parser->ClearIncomingSyncItems(TRUE);
m_parser->ClearError();
m_data_queue->ClearReceivedItems();
BroadcastPendingSyncSupportChanged();
}
void OpSyncCoordinator::OnSyncCompleted(OpSyncCollection* new_items, OpSyncState& sync_state, OpSyncServerInformation& sync_server_info)
{
OP_NEW_DBG("OpSyncCoordinator::OnSyncCompleted()", "sync");
OP_DBG(("received %d items", new_items->GetCount()));
OP_DBG(("server-info: ") << sync_server_info);
SyncSupportsState supports_state = m_parser->GetSyncSupports();
bool have_queued_items = m_data_queue->HasQueuedItems(supports_state);
OP_DBG(("have ") << (have_queued_items ? "" : "no") << " queued items for state " << supports_state);
if (m_data_queue->HasDirtyItems())
{
OP_DBG(("dirty sync"));
new_items->Clear();
OpSyncDataCollection items_missing_on_client;
OpSyncDataCollection items_missing_on_server;
// TODO: OOM handling here
/* we have outgoing items scheduled for a dirty sync. Let's merge it
* with the items the server sent and send the difference to the client
* and the server */
OP_STATUS status = MergeDirtySyncItems(
*m_data_queue->GetSyncDataCollection(OpSyncDataQueue::SYNCQUEUE_DIRTY_ITEMS), // items from the client
*m_parser->GetIncomingSyncItems(), // items from the server
items_missing_on_client, items_missing_on_server);
if (OpStatus::IsError(status))
{
ErrorCleanup(status);
return;
}
if (items_missing_on_client.HasItems())
{
OP_DBG(("handle items missing on client"));
// items that the client need to know about
OpSyncCollection items_missing_on_client_syncitems;
// we need to convert them to a top-level OpSyncItem collection
status = m_allocator->CreateSyncItemCollection(items_missing_on_client, items_missing_on_client_syncitems);
if (OpStatus::IsError(status))
{
ErrorCleanup(status);
return;
}
/* add them to the received collection and the client will get them
* as normal */
status = m_data_queue->AddAsReceivedItems(items_missing_on_client_syncitems);
if (OpStatus::IsError(status))
{
ErrorCleanup(status);
return;
}
}
if (items_missing_on_server.HasItems())
{
OP_DBG(("handle items missing on server"));
// items the server should know about
status = m_data_queue->Add(items_missing_on_server);
if (OpStatus::IsError(status))
{
ErrorCleanup(status);
return;
}
}
}
else
{
// TODO: OOM handling here
OP_STATUS status = m_data_queue->AddAsReceivedItems(*new_items);
if (OpStatus::IsError(status))
{
ErrorCleanup(status);
return;
}
}
/* The incoming items have now been moved from the parser's
* OpSyncDataCollection of parsed items to the OpSyncDataQueue's
* SYNCQUEUE_RECEIVED_ITEMS OpSyncCollection, so clear the parser's
* collection. */
m_parser->ClearIncomingSyncItems(TRUE);
#ifdef SELFTEST
if (!m_is_selftest)
#endif // SELFTEST
{
/* if the interval change, we need to reset the timer for the new
* interval right away, otherwise we'll just let the old default one
* continue ticking */
unsigned int new_interval = 0;
if (m_data_queue->HasQueuedItems())
{
/* If we have queued items we need to restart the timer if the
* server's short interval has changed: */
if (sync_server_info.GetSyncIntervalShort() != m_sync_server_info.GetSyncIntervalShort())
new_interval = sync_server_info.GetSyncIntervalShort();
}
else
{ /* If we don't have queued items we need to restart the timer if the
* server's long interval has changed. */
if (sync_server_info.GetSyncIntervalLong() != m_sync_server_info.GetSyncIntervalLong())
new_interval = sync_server_info.GetSyncIntervalLong();
}
if (new_interval)
{
OP_DBG(("Sync interval changed: %d", new_interval));
StartTimeout(new_interval);
}
}
m_sync_server_info = sync_server_info;
m_data_queue->SetMaxItems(m_sync_server_info.GetSyncMaxItems());
/* We have now sent the items of SYNCQUEUE_OUTGOING, so we can clear that
* queue (and update the persistent queue on disk): */
OP_STATUS status = m_data_queue->ClearItemsToSend();
if (OpStatus::IsError(status))
{
ErrorCleanup(status);
return;
}
SetSyncInProgress(FALSE);
/* If we just have sent all queued items for all supports types that are
* currently enabled, we call BroadcastDataAvailable() to the corresponding
* OpSyncDataClient instances.
* Note: if this was a dirty sync, and MergeDirtySyncItems() has found some
* items missing on the server, then the outgoing queue is no longer empty
* by now, but we still want to broadcast the available data now and not
* after the next sync... */
if (!have_queued_items)
{
OP_DBG(("broadcast sync-result"));
OP_STATUS status = BroadcastDataAvailable(supports_state, sync_state);
if (OpStatus::IsError(status))
{
ErrorCleanup(status);
return;
}
else
{
// only save sync state and call OnSyncFinished() on success
for (unsigned int i = 0; i < m_uilisteners.GetCount(); i++)
m_uilisteners.Get(i)->OnSyncFinished(sync_state);
m_sync_state.Update(sync_state);
SetUseDiskQueue(TRUE);
}
m_is_complete_sync_in_progress = FALSE;
}
/* Note: broadcast any pending sync-support-changed notification after
* calling OnSyncFinished(). */
BroadcastPendingSyncSupportChanged();
/* If we have any more queued items for the already used supports type (this
* may be the case if we had more than max-items), we need to send another
* batch of items. */
if (have_queued_items
#ifdef SYNC_ENCRYPTION_KEY_SUPPORT
/* Also if we just received the encryption-key, we need to start another
* connection immediately (to possibly receive any new password manager
* entries). */
|| (m_encryption_key_manager->IsEncryptionKeyUsable() &&
m_supports_state.HasSupports(SYNC_SUPPORTS_PASSWORD_MANAGER) &&
!supports_state.HasSupports(SYNC_SUPPORTS_PASSWORD_MANAGER))
#endif // SYNC_ENCRYPTION_KEY_SUPPORT
)
{
OP_DBG(("start new sync-connection"));
m_sync_state.Update(sync_state);
OP_STATUS status = StartSync();
if (OpStatus::IsError(status))
{
ErrorCleanup(status);
return;
}
}
#ifdef SELFTEST
if (!m_is_selftest)
#endif // SELFTEST
{
// TODO: Check if this should be here
OP_DBG(("%s", m_sync_state.GetDirty()?"Dirty sync: start a complete sync next time":"no dirty sync"));
TRAPD(err, g_pcsync->WriteIntegerL(PrefsCollectionSync::CompleteSync, m_sync_state.GetDirty()));
m_sync_state.WritePrefs();
}
if (m_sync_state.GetDirty())
{
m_is_complete_sync_in_progress = TRUE;
for (unsigned int i = 0; i < m_listeners.GetCount(); i++)
{
const OpSyncDataClientItem* listener_item = m_listeners.Get(i);
for (unsigned int j = 0; j < listener_item->TypeCount(); j++)
{
// request a flush for this data type
g_main_message_handler->PostDelayedMessage(MSG_SYNC_FLUSH_DATATYPE, static_cast<MH_PARAM_1>(listener_item->GetType(j)), 0, 50);
}
}
}
unsigned long seconds, milliseconds;
g_op_time_info->GetWallClock(seconds, milliseconds);
OP_DBG(("SyncLastUsed: %lu", seconds));
TRAP(status, g_pcsync->WriteIntegerL(PrefsCollectionSync::SyncLastUsed, seconds));
}
void OpSyncCoordinator::BroadcastSyncError(OpSyncError error, const OpStringC& error_msg)
{
OP_NEW_DBG("OpSyncCoordinator::BroadcastSyncError()", "sync");
for (unsigned int i = 0; i < m_uilisteners.GetCount(); i++)
m_uilisteners.Get(i)->OnSyncError(error, error_msg);
}
OP_STATUS OpSyncCoordinator::BroadcastDataAvailable(SyncSupportsState supports_state, OpSyncState& sync_state)
{
OP_NEW_DBG("OpSyncCoordinator::BroadcastDataAvailable()", "sync");
OpSyncCollection* received_items = m_data_queue->GetSyncCollection(OpSyncDataQueue::SYNCQUEUE_RECEIVED_ITEMS);
if (received_items->IsEmpty())
return OpStatus::OK;
OP_DBG(("%d new items", received_items->GetCount()));
/* Notify all OpSyncDataClient instances for the supports types that are
* enabled in supports_state: */
bool broadcast_for[OpSyncDataItem::DATAITEM_MAX_DATAITEM];
/* An OpSyncDataClient can indicate to not release the OpSyncCollection of
* that type by letting SyncDataAvailable() return SYNC_DATAERROR_ASYNC,
* which will set this flag to true: */
bool keep_items[OpSyncDataItem::DATAITEM_MAX_DATAITEM];
/* OpSyncDataItem::DATAITEM_GENERIC == 0 is not used, so no need to do
* anything with that type: */
broadcast_for[0] = false;
keep_items[0] = false;
for (unsigned int i = 1; i < OpSyncDataItem::DATAITEM_MAX_DATAITEM; i++)
{
OpSyncDataItem::DataItemType item_type = static_cast<OpSyncDataItem::DataItemType>(i);
OpSyncSupports supports = OpSyncCoordinator::GetSupportsFromType(item_type);
broadcast_for[i] = supports_state.HasSupports(supports);
// Keep all items for which we don't notify the client:
keep_items[i] = !broadcast_for[i];
}
unsigned int i = 0;
/* received_items is split into collections containing only the items of one
* type */
OpSyncCollection temp_items[OpSyncDataItem::DATAITEM_MAX_DATAITEM];
for (OpSyncItemIterator current(received_items->First()); *current; ++current)
{
OpSyncDataItem::DataItemType item_type = OpSyncDataItem::BaseTypeOf(current->GetType());
OP_DBG(("%d: ", i++) << item_type);
OP_ASSERT(item_type < OpSyncDataItem::DATAITEM_MAX_DATAITEM);
if (item_type < OpSyncDataItem::DATAITEM_MAX_DATAITEM)
{
current->Out();
current->Into(&temp_items[item_type]);
}
}
OP_STATUS status = OpStatus::OK;
/* Call the registered listeners for each registered data type that has data
* available: */
for (i = 0; i < m_listeners.GetCount(); i++)
{
OpSyncDataClientItem* item = m_listeners.Get(i);
OP_DBG(("%d: notify listener %p", i, item));
// Notify the listener for each data type it was registered for.
// (Note: type 0 is not used)
for (unsigned int item_type = 1; item_type < (int)OpSyncDataItem::DATAITEM_MAX_DATAITEM; item_type++)
{
OpSyncDataError data_error = SYNC_DATAERROR_NONE;
/* Only call SyncDataAvailable() if ... */
if (/* ... notification was requested for this type ... */
broadcast_for[item_type] &&
/* ... there are some items of this type ... */
temp_items[item_type].HasItems() &&
/* ... and the client supports this type ... */
item->HasType(static_cast<OpSyncDataItem::DataItemType>(item_type)))
{
OP_DBG(("type: ") << static_cast<OpSyncDataItem::DataItemType>(item_type));
status = item->Get()->SyncDataAvailable(&temp_items[item_type], data_error);
if (OpStatus::IsError(status))
{ /* In case of an error don't continue to notify the clients,
* but ensure to move back the items into received_items */
i = m_listeners.GetCount(); // exit outer loop ...
OP_DBG(("error: %d", status));
break; // ... after exiting inner loop
}
switch (data_error) {
case SYNC_DATAERROR_INCONSISTENCY:
OP_DBG(("SYNC_DATAERROR_INCONSISTENCY"));
// request a flush for this data type
g_main_message_handler->PostDelayedMessage(MSG_SYNC_FLUSH_DATATYPE, static_cast<MH_PARAM_1>(item_type), 0, 50);
break;
case SYNC_DATAERROR_ASYNC:
OP_DBG(("SYNC_DATAERROR_ASYNC"));
/* Don't delete the items of this type: */
keep_items[item_type] = true;
sync_state.SetSyncStatePersistent(OpSyncCoordinator::GetSupportsFromType(static_cast<OpSyncDataItem::DataItemType>(item_type)), FALSE);
break;
case SYNC_DATAERROR_NONE:
sync_state.SetSyncStatePersistent(OpSyncCoordinator::GetSupportsFromType(static_cast<OpSyncDataItem::DataItemType>(item_type)), TRUE);
break;
}
}
}
}
/* Move all the items that are completely handled back into the original
* list so they can be released: */
for (i = 0; i < (unsigned int)OpSyncDataItem::DATAITEM_MAX_DATAITEM; i++)
{
if (temp_items[i].HasItems() && !keep_items[i])
received_items->AppendItems(&temp_items[i]);
}
/* Now release all items unless SYNC_DATAERROR_ASYNC was returned for that
* item type: */
m_data_queue->ClearReceivedItems();
/* Now move all items back that still need to be handled later: */
for (i = 0; i < (unsigned int)OpSyncDataItem::DATAITEM_MAX_DATAITEM; i++)
{
if (temp_items[i].HasItems() && keep_items[i])
received_items->AppendItems(&temp_items[i]);
}
return status;
}
void OpSyncCoordinator::OnSyncError(OpSyncError error, const OpStringC& error_msg)
{
OP_NEW_DBG("OpSyncCoordinator::OnSyncError()", "sync");
OP_DBG((UNI_L("error: %s"), error_msg.CStr()));
m_parser->ClearIncomingSyncItems(TRUE);
m_parser->ClearError();
SetSyncInProgress(FALSE);
BroadcastPendingSyncSupportChanged();
bool broadcast_error = true;
switch (error)
{
case SYNC_ACCOUNT_OAUTH_EXPIRED:
/* The Oauth token has expired and we need to get a new Oauth token and
* connect again with that token. */
g_opera_oauth_manager->Logout();
StartSync();
broadcast_error = false;
break;
case SYNC_ACCOUNT_USER_UNAVAILABLE:
/* For some reason the Link server cannot verify the user at the
* moment. This is a temporary error state. Try again to connect in the
* specified interval. */
OpStatus::Ignore(StartTimeout(m_sync_server_info.GetSyncIntervalLong()));
break;
case SYNC_ACCOUNT_AUTH_FAILURE:
case SYNC_ACCOUNT_USER_BANNED:
/* The Link server failed to authenticate the user. So log out,
* broadcast the error and don't try again. */
g_opera_oauth_manager->Logout();
break;
case SYNC_ERROR_INVALID_REQUEST:
case SYNC_ERROR_PARSER:
case SYNC_ERROR_PROTOCOL_VERSION:
case SYNC_ERROR_CLIENT_VERSION:
case SYNC_ERROR_INVALID_STATUS:
case SYNC_ERROR_INVALID_BOOKMARK:
case SYNC_ERROR_INVALID_SPEEDDIAL:
case SYNC_ERROR_INVALID_NOTE:
case SYNC_ERROR_INVALID_SEARCH:
case SYNC_ERROR_INVALID_TYPED_HISTORY:
case SYNC_ERROR_INVALID_FEED:
case SYNC_ERROR_SERVER:
case SYNC_ERROR:
case SYNC_PENDING_ENCRYPTION_KEY:
/* Broadcast all these errors. */
default:
break;
}
if (broadcast_error)
BroadcastSyncError(error, error_msg);
}
void OpSyncCoordinator::OnSyncItemAdded(BOOL new_item)
{
// new item, start short interval sync
if (new_item && IsSyncActive())
{
OP_NEW_DBG("OpSyncCoordinator::OnSyncItemAdded()", "sync");
RETURN_VOID_IF_ERROR(StartTimeout(m_sync_server_info.GetSyncIntervalShort()));
}
}
void OpSyncCoordinator::BroadcastSyncDataInitialize(OpSyncDataItem::DataItemType type)
{
OP_NEW_DBG("OpSyncCoordinator::BroadcastSyncDataInitialize()", "sync");
OP_DBG(("") << "type: " << type << "; " << m_listeners.GetCount() << " listeners");
/* Notify the registered listeners for the specified data type that the
* corresponding supports type is synchronised for the first time: */
for (unsigned int i = 0; i < m_listeners.GetCount(); i++)
{
OpSyncDataClientItem* item = m_listeners.Get(i);
if (item->HasType(type) && GetSupports(OpSyncCoordinator::GetSupportsFromType(type)))
{
OP_DBG(("%d: has this type", i));
OP_STATUS status = item->Get()->SyncDataInitialize(type);
if (OpStatus::IsError(status))
{
// break out if anything fails
OP_DBG(("error on initializing data"));
ErrorCleanup(status);
return;
}
}
}
}
void OpSyncCoordinator::BroadcastSyncDataFlush(OpSyncDataItem::DataItemType type, BOOL first_sync, BOOL is_dirty)
{
OP_NEW_DBG("OpSyncCoordinator::BroadcastSyncDataFlush()", "sync");
OP_DBG(("") << "type: " << type << "; " << (first_sync?"first sync; ":"") << (is_dirty?"dirty; ":"") << m_listeners.GetCount() << " listeners");
m_is_complete_sync_in_progress = TRUE;
if (is_dirty)
{
OP_DBG(("remove queued items"));
m_data_queue->RemoveQueuedItems(type);
}
/* Notify the registered listeners for each registered data type that it
* shall provide the data for an initial or dirty sync: */
for (unsigned int i = 0; i < m_listeners.GetCount(); i++)
{
OpSyncDataClientItem* item = m_listeners.Get(i);
if (item->HasType(type) && GetSupports(OpSyncCoordinator::GetSupportsFromType(type)))
{
OP_DBG(("%d: has this type", i));
OP_STATUS status = item->Get()->SyncDataFlush(type, first_sync, is_dirty);
if (OpStatus::IsError(status))
{
// break out if anything fails
ErrorCleanup(status);
return;
}
}
}
}
#ifdef SYNC_ENCRYPTION_KEY_SUPPORT
/* virtual */
void OpSyncCoordinator::OnEncryptionKeyCreated()
{
OP_NEW_DBG("OpSyncCoordinator::OnEncryptionKeyCreated()", "sync");
/* Reset the sync-state for all item types that use the encryption-key.
* Thus in the next connection we download all password manager items which
* shall result in re-encrypting all items with the newly generated key: */
OpStatus::Ignore(ResetSupportsState(SYNC_SUPPORTS_PASSWORD_MANAGER));
}
/* virtual */
void OpSyncCoordinator::OnSyncReencryptEncryptionKeyFailed(OpSyncUIListener::ReencryptEncryptionKeyContext* context)
{
OP_NEW_DBG("OpSyncCoordinator::OnSyncReencryptEncryptionKeyFailed()", "sync");
for (unsigned int i = 0; i < m_uilisteners.GetCount(); i++)
m_uilisteners.Get(i)->OnSyncReencryptEncryptionKeyFailed(context);
}
/* virtual */
void OpSyncCoordinator::OnSyncReencryptEncryptionKeyCancel(OpSyncUIListener::ReencryptEncryptionKeyContext* context)
{
OP_NEW_DBG("OpSyncCoordinator::OnSyncReencryptEncryptionKeyCancel()", "sync");
for (unsigned int i = 0; i < m_uilisteners.GetCount(); i++)
m_uilisteners.Get(i)->OnSyncReencryptEncryptionKeyCancel(context);
}
#endif // SYNC_ENCRYPTION_KEY_SUPPORT
BOOL OpSyncCoordinator::FreeCachedData(BOOL toplevel_context)
{
OP_NEW_DBG("OpSyncCoordinator::FreeCachedData()", "sync");
if (m_parser)
return m_parser->FreeCachedData(toplevel_context);
return FALSE;
}
/* static */
OP_STATUS OpSyncCoordinator::GetTypesFromSupports(OpSyncSupports supports, OpINT32Vector& types)
{
OpSyncDataItem::DataItemType type;
switch (supports)
{
case SYNC_SUPPORTS_BOOKMARK:
type = OpSyncDataItem::DATAITEM_BOOKMARK;
break;
case SYNC_SUPPORTS_CONTACT:
type = OpSyncDataItem::DATAITEM_CONTACT;
break;
case SYNC_SUPPORTS_ENCRYPTION:
RETURN_IF_ERROR(types.Add(OpSyncDataItem::DATAITEM_ENCRYPTION_KEY));
return types.Add(OpSyncDataItem::DATAITEM_ENCRYPTION_TYPE);
case SYNC_SUPPORTS_EXTENSION:
type = OpSyncDataItem::DATAITEM_EXTENSION;
break;
case SYNC_SUPPORTS_FEED:
type = OpSyncDataItem::DATAITEM_FEED;
break;
case SYNC_SUPPORTS_NOTE:
type = OpSyncDataItem::DATAITEM_NOTE;
break;
case SYNC_SUPPORTS_PASSWORD_MANAGER:
RETURN_IF_ERROR(types.Add(OpSyncDataItem::DATAITEM_PM_HTTP_AUTH));
return types.Add(OpSyncDataItem::DATAITEM_PM_FORM_AUTH);
case SYNC_SUPPORTS_SEARCHES:
type = OpSyncDataItem::DATAITEM_SEARCH;
break;
case SYNC_SUPPORTS_SPEEDDIAL:
type = OpSyncDataItem::DATAITEM_SPEEDDIAL;
break;
case SYNC_SUPPORTS_SPEEDDIAL_2:
RETURN_IF_ERROR(types.Add(OpSyncDataItem::DATAITEM_SPEEDDIAL_2));
return types.Add(OpSyncDataItem::DATAITEM_SPEEDDIAL_2_SETTINGS);
break;
case SYNC_SUPPORTS_TYPED_HISTORY:
type = OpSyncDataItem::DATAITEM_TYPED_HISTORY;
break;
case SYNC_SUPPORTS_URLFILTER:
type = OpSyncDataItem::DATAITEM_URLFILTER;
break;
default:
OP_ASSERT(!"This is an unsupported OpSyncSupports type");
type = OpSyncDataItem::DATAITEM_GENERIC;
}
return types.Add(type);
}
/* static */
OpSyncSupports OpSyncCoordinator::GetSupportsFromType(OpSyncDataItem::DataItemType type)
{
switch (type)
{
case OpSyncDataItem::DATAITEM_BOOKMARK_FOLDER:
case OpSyncDataItem::DATAITEM_BOOKMARK_SEPARATOR:
case OpSyncDataItem::DATAITEM_BOOKMARK: return SYNC_SUPPORTS_BOOKMARK;
case OpSyncDataItem::DATAITEM_CONTACT: return SYNC_SUPPORTS_CONTACT;
case OpSyncDataItem::DATAITEM_ENCRYPTION_KEY:return SYNC_SUPPORTS_ENCRYPTION;
case OpSyncDataItem::DATAITEM_ENCRYPTION_TYPE:return SYNC_SUPPORTS_ENCRYPTION;
case OpSyncDataItem::DATAITEM_EXTENSION: return SYNC_SUPPORTS_EXTENSION;
case OpSyncDataItem::DATAITEM_FEED: return SYNC_SUPPORTS_FEED;
case OpSyncDataItem::DATAITEM_NOTE_FOLDER:
case OpSyncDataItem::DATAITEM_NOTE_SEPARATOR:
case OpSyncDataItem::DATAITEM_NOTE: return SYNC_SUPPORTS_NOTE;
case OpSyncDataItem::DATAITEM_PM_FORM_AUTH: return SYNC_SUPPORTS_PASSWORD_MANAGER;
case OpSyncDataItem::DATAITEM_PM_HTTP_AUTH: return SYNC_SUPPORTS_PASSWORD_MANAGER;
case OpSyncDataItem::DATAITEM_SEARCH: return SYNC_SUPPORTS_SEARCHES;
case OpSyncDataItem::DATAITEM_SPEEDDIAL: return SYNC_SUPPORTS_SPEEDDIAL;
case OpSyncDataItem::DATAITEM_BLACKLIST:
case OpSyncDataItem::DATAITEM_SPEEDDIAL_2:
case OpSyncDataItem::DATAITEM_SPEEDDIAL_2_SETTINGS: return SYNC_SUPPORTS_SPEEDDIAL_2;
case OpSyncDataItem::DATAITEM_TYPED_HISTORY:return SYNC_SUPPORTS_TYPED_HISTORY;
case OpSyncDataItem::DATAITEM_URLFILTER: return SYNC_SUPPORTS_URLFILTER;
default:
OP_ASSERT(!"This is an unsupported OpSyncDataItem::DataItemType");
}
return SYNC_SUPPORTS_MAX;
}
OP_STATUS OpSyncCoordinator::SetSupports(OpSyncSupports supports, BOOL has_support)
{
OP_NEW_DBG("OpSyncCoordinator::SetSupports()", "sync");
OP_DBG(("") << supports << ": " << (has_support?"on":"off"));
switch (supports) {
case SYNC_SUPPORTS_BOOKMARK:
case SYNC_SUPPORTS_EXTENSION:
case SYNC_SUPPORTS_NOTE:
case SYNC_SUPPORTS_PASSWORD_MANAGER:
case SYNC_SUPPORTS_SEARCHES:
case SYNC_SUPPORTS_SPEEDDIAL:
case SYNC_SUPPORTS_SPEEDDIAL_2:
case SYNC_SUPPORTS_TYPED_HISTORY:
case SYNC_SUPPORTS_URLFILTER:
{
PrefsCollectionSync::integerpref pref = OpSyncState::Supports2EnablePref(supports);
if (pref != PrefsCollectionSync::DummyLastIntegerPref)
RETURN_IF_LEAVE(g_pcsync->WriteIntegerL(pref, has_support));
else
OP_DBG(("support for ") << supports << " not enabled");
break;
}
case SYNC_SUPPORTS_CONTACT:
case SYNC_SUPPORTS_FEED:
// Types not supported yet
return OpStatus::ERR_NOT_SUPPORTED;
case SYNC_SUPPORTS_ENCRYPTION:
/* encryption support depends on any support that uses it, enabling
* encryption support alone does not do anything, especially it does
* not write a preference... */
return OpStatus::OK;
default:
OP_ASSERT(!"This is an unsupported OpSyncSupports type");
return OpStatus::ERR_NO_SUCH_RESOURCE;
}
return OpStatus::OK;
}
BOOL OpSyncCoordinator::GetSupports(OpSyncSupports supports)
{
switch (supports)
{
case SYNC_SUPPORTS_BOOKMARK:
case SYNC_SUPPORTS_EXTENSION:
case SYNC_SUPPORTS_NOTE:
case SYNC_SUPPORTS_PASSWORD_MANAGER:
case SYNC_SUPPORTS_SEARCHES:
case SYNC_SUPPORTS_SPEEDDIAL:
case SYNC_SUPPORTS_SPEEDDIAL_2:
case SYNC_SUPPORTS_TYPED_HISTORY:
case SYNC_SUPPORTS_URLFILTER:
{
PrefsCollectionSync::integerpref pref = OpSyncState::Supports2EnablePref(supports);
if (pref != PrefsCollectionSync::DummyLastIntegerPref)
return g_pcsync->GetIntegerPref(pref);
break;
}
case SYNC_SUPPORTS_ENCRYPTION:
/* password manager requires encryption, so encryption is enabled if
* password manager is: */
return GetSupports(SYNC_SUPPORTS_PASSWORD_MANAGER);
case SYNC_SUPPORTS_CONTACT:
case SYNC_SUPPORTS_FEED:
// Implementation missing
return FALSE;
default:
OP_ASSERT(!"This is an unsupported OpSyncSupports type");
}
return FALSE;
}
OP_STATUS OpSyncCoordinator::ResetSupportsState(OpSyncSupports supports, BOOL disable_support)
{
OP_NEW_DBG("OpSyncCoordinator::ResetSupportsState", "sync");
OP_DBG(("") << supports << (disable_support?"; disable this type":""));
OP_ASSERT(supports <= SYNC_SUPPORTS_MAX);
if (SYNC_SUPPORTS_MAX == supports)
{
RETURN_IF_ERROR(m_sync_state.SetSyncState(UNI_L("0")));
for (unsigned int i = 0; i < SYNC_SUPPORTS_MAX; i++)
{
OpSyncSupports supports = static_cast<OpSyncSupports>(i);
RETURN_IF_ERROR(m_sync_state.ResetSyncState(supports));
if (disable_support)
OpStatus::Ignore(SetSupports(supports, FALSE));
}
}
else
{
RETURN_IF_ERROR(m_sync_state.ResetSyncState(supports));
if (disable_support)
OpStatus::Ignore(SetSupports(supports, FALSE));
}
return m_sync_state.WritePrefs();
}
OP_STATUS OpSyncCoordinator::ClearSupports()
{
m_supports_state.Clear();
return OpStatus::ERR_NO_SUCH_RESOURCE;
}
OP_STATUS OpSyncCoordinator::SetSystemInformation(OpSyncSystemInformationType type, const OpStringC& data)
{
if (m_parser)
return m_parser->SetSystemInformation(type, data);
return OpStatus::ERR_NO_SUCH_RESOURCE;
}
// TODO: make this in the parser
extern const uni_char* GetNamedKeyFromKey(OpSyncItem::Key key);
OP_STATUS OpSyncCoordinator::UpdateItem(OpSyncDataItem::DataItemType item_type, const uni_char* next_item_key_id, OpSyncItem::Key next_item_key_to_update, const uni_char* next_item_key_data_to_update)
{
OP_NEW_DBG("OpSyncCoordinator::UpdateItem", "sync");
OP_DBG(("type: ") << item_type);
OP_DBG((UNI_L("next item key id: '%s'; next item key to update: '%s'; next item key data to update: '%s'"), next_item_key_id, GetNamedKeyFromKey(next_item_key_to_update), next_item_key_data_to_update));
OpSyncItem* sync_item_ptr = 0;
OpString data;
OP_STATUS s = GetExistingSyncItem(&sync_item_ptr, item_type, m_parser->GetPrimaryKey(item_type), next_item_key_id);
if (OpStatus::IsError(s) || !sync_item_ptr)
{
// not finding the item is not an error
return OpStatus::OK;
}
// Delete the OpSyncItem instance on returning from this method:
OpAutoPtr<OpSyncItem> sync_item(sync_item_ptr);
if (sync_item->GetStatus() != OpSyncDataItem::DATAITEM_ACTION_DELETED &&
sync_item->GetStatus() != OpSyncDataItem::DATAITEM_ACTION_ADDED)
sync_item->SetStatus(OpSyncDataItem::DATAITEM_ACTION_MODIFIED);
OP_DBG((UNI_L("UpdateItem found item, updating data: next item key to update: '%s'; next item key data to update: '%s'"), GetNamedKeyFromKey(next_item_key_to_update), next_item_key_data_to_update));
RETURN_IF_ERROR(sync_item->SetData(next_item_key_to_update, next_item_key_data_to_update));
RETURN_IF_ERROR(sync_item->CommitItem(FALSE, TRUE));
return OpStatus::OK;
}
OP_STATUS OpSyncCoordinator::GetExistingSyncItem(OpSyncItem** item_out, OpSyncDataItem::DataItemType type, OpSyncItem::Key primary_key, const uni_char* key_data)
{
const uni_char* primary_key_name = GetNamedKeyFromKey(primary_key);
OpSyncDataCollection* collection = m_data_queue->GetSyncDataCollection(OpSyncDataQueue::SYNCQUEUE_ACTIVE);
OpSyncDataItem* item = collection->FindPrimaryKey(OpSyncDataItem::BaseTypeOf(type), primary_key_name, key_data);
if (!item)
return OpStatus::ERR_NULL_POINTER;
OpSyncItem* sync_item;
RETURN_IF_ERROR(GetSyncItem(&sync_item, type, primary_key, key_data));
sync_item->SetDataSyncItem(item);
*item_out = sync_item;
return OpStatus::OK;
}
/*
* Dirty sync merge code
*
* Dirty sync involves the following steps:
* - Receive all client items from the client code and store these for later
* - Request all items from the server
* - Find the difference in the 2 collections
* - Send items missing on the client to the client
* - Send items missing on the server to the server
*/
OP_STATUS OpSyncCoordinator::MergeDirtySyncItems(/* in */ OpSyncDataCollection& items_from_client, /* in */ OpSyncDataCollection& items_from_server, /* out */ OpSyncDataCollection& items_missing_on_client, /* out */ OpSyncDataCollection& items_missing_on_server)
{
OP_NEW_DBG("OpSyncCoordinator::MergeDirtySyncItems", "sync");
/* Iterate over all items received from the server (items_from_server).
* If the items_from_client don't have an item with the same id, the item
* needs to be added to the client, i.e. added to items_missing_on_client.
* If items_from_client has an item with the same id, the item is merged and
* - added to items_missing_on_client if the item on the client had
* different values or less children/attributes than the item from the
* server.
* - added to items_missing_on_server if the item on the client had some
* more children/attributes than the item from the server.
* - deleted if both items are equal.
* All items in items_from_client that are left, need to be added to
* items_missing_on_server.
*/
OP_DBG(("items from server"));
for (OpSyncDataItemIterator server_item(items_from_server.First()); *server_item; ++server_item)
{
if (server_item->m_key.IsEmpty())
{
/* Ignore items without a primary key. */
items_from_server.RemoveItem(*server_item);
}
else
{
OP_DBG(("") << "item: " << (*server_item) << ": " << server_item->m_key.CStr() << "=" << server_item->m_data.CStr());
OpSyncDataItem* client_item = items_from_client.FindPrimaryKey(server_item->GetBaseType(), server_item->m_key, server_item->m_data);
if (client_item)
{
OP_DBG(("found duplicate in list from client %p", client_item));
switch (server_item->GetStatus())
{
case OpSyncDataItem::DATAITEM_ACTION_DELETED:
/* the item was deleted on the server, so forward this to
* the client (unless the client reports it as deleted as
* well): */
if (client_item->GetStatus() == OpSyncDataItem::DATAITEM_ACTION_DELETED)
items_from_server.RemoveItem(*server_item);
else
items_missing_on_client.AddItem(*server_item);
items_from_client.RemoveItem(client_item);
break;
case OpSyncDataItem::DATAITEM_ACTION_MODIFIED:
case OpSyncDataItem::DATAITEM_ACTION_ADDED:
if (client_item->GetStatus() == OpSyncDataItem::DATAITEM_ACTION_DELETED)
{
/* client_item was deleted, while the server added or
* modified it, so keep the item from the server: */
items_from_client.RemoveItem(client_item);
items_missing_on_client.AddItem(*server_item);
}
else
{
OpSyncDataCollection auto_delete;
/* both server_item and client_item have some data (with
* status added), now merge the items such that the
* server_item overwrites data from the client_item and
* if the client_item was changed, add it to
* items_missing_on_client and if the client_item has
* data that is not on the server_item, add a copy to
* items_missing_on_server: */
OpSyncDataItem* merged_item = OP_NEW(OpSyncDataItem, ());
RETURN_OOM_IF_NULL(merged_item);
auto_delete.AddItem(merged_item);
merged_item->SetType(server_item->GetType());
merged_item->m_key.TakeOver(server_item->m_key);
merged_item->m_data.TakeOver(server_item->m_data);
merged_item->SetStatus(OpSyncDataItem::DATAITEM_ACTION_MODIFIED);
bool update_server = false;
bool update_client = false;
/* Merge attributes from server_item: */
OpSyncDataItem* from_server;
while (0 != (from_server = server_item->GetFirstAttribute()))
{
// add the attribute to the merged item:
merged_item->AddAttribute(from_server);
// check if the client_item has the same value:
OpSyncDataItem* from_client = client_item->FindAttributeById(from_server->m_key.CStr());
if (from_client)
{
if (from_server->m_data != from_client->m_data)
/* value is different, so we need to update
* the client */
update_client = true;
from_client->GetList()->RemoveItem(from_client);
}
else
/* attribute is missing on the client, so we
* need to update the client: */
update_client = true;
}
/* If there is any attribute left on the client_item,
* add it to merged_item and then we need to update the
* server: */
if (client_item->HasAttributes())
{
update_server = true;
while (client_item->GetFirstAttribute())
merged_item->AddAttribute(client_item->GetFirstAttribute());
}
/* Merge children from server_item: */
while (0 != (from_server = server_item->GetFirstChild()))
{
// add the child to the merged item:
merged_item->AddChild(from_server);
// check if the client_item has the same value:
OpSyncDataItem* from_client = client_item->FindChildById(from_server->m_key.CStr());
if (from_client)
{
if (from_server->m_data != from_client->m_data)
/* value is different, so we need to update
* the client */
update_client = true;
from_client->GetList()->RemoveItem(from_client);
}
else
/* child is missing on the client, so we need to
* update the client: */
update_client = true;
}
/* If there is any child left on the client_item, add it
* to merged_item and then we need to update the
* server: */
if (client_item->HasChildren())
{
update_server = true;
while (client_item->GetFirstChild())
merged_item->AddChild(client_item->GetFirstChild());
}
if (update_client && update_server)
/* If we need to update both, then we need one more
* copy of the merged_item: */
items_missing_on_client.AddItem(merged_item->Copy());
else if (update_client)
items_missing_on_client.AddItem(merged_item);
if (update_server)
items_missing_on_server.AddItem(merged_item);
}
items_from_server.RemoveItem(*server_item);
items_from_client.RemoveItem(client_item);
break;
default:
/* item had an invalid status, so ignore it and send the
* dupe_item to the server instead: */
items_from_server.RemoveItem(*server_item);
items_missing_on_server.AddItem(client_item);
}
}
else
{
OP_DBG(("item was on the server but not on the client, add it to items_missing_on_client"));
items_missing_on_client.AddItem(*server_item);
}
}
}
// all remaining items in items_from_client are missing on the server:
OP_DBG(("items from client"));
while (items_from_client.First())
items_missing_on_server.AddItem(items_from_client.First());
return OpStatus::OK;
}
// <Implementation of OpPrefsListener>
/* virtual */
void OpSyncCoordinator::PrefChanged(OpPrefsCollection::Collections id, int pref, int newvalue)
{
OP_NEW_DBG("OpSyncCoordinator::PrefChanged()", "sync");
OP_ASSERT(OpPrefsCollection::Sync == id);
OP_DBG(("pref: %d; value: %d", pref, newvalue));
switch (pref) {
case PrefsCollectionSync::LastCachedAccess:
case PrefsCollectionSync::LastCachedAccessNum:
case PrefsCollectionSync::SyncLastUsed:
case PrefsCollectionSync::SyncUsed:
case PrefsCollectionSync::CompleteSync:
case PrefsCollectionSync::SyncLogTraffic:
default:
// Nothing to do ...
break;
case PrefsCollectionSync::SyncEnabled:
/* Syncing was enabled/disabled. Currently it is the task of the UI to
* start the sync process.
* TODO: let sync automatically start the sync process when this
* preference is enabled. And use a UI listener, which is notified about
* this. */
OP_DBG(("PrefsCollectionSync::SyncEnabled"));
/* If sync is enabled, this means that some data-clients will be
* enabled as well: */
BroadcastSyncSupportChanged();
break;
#ifdef SYNC_HAVE_PASSWORD_MANAGER
case PrefsCollectionSync::SyncPasswordManager:
/* This type depends on support for encryption-key. So whenever this
* support type is enabled, also enable SYNC_SUPPORTS_ENCRYPTION (and
* fall through). And whenever this is disabled (and no other type that
* depends on encryption-key is enabled - this is currently easy,
* because only password-manager depends on it), disable
* SYNC_SUPPORTS_ENCRYPTION (and fall through): */
BroadcastSyncSupportChanged(SYNC_SUPPORTS_ENCRYPTION, newvalue ? true : false);
/* fall through ... to also broadcast the change of
* SYNC_SUPPORTS_PASSWORD_MANAGER */
#endif // SYNC_HAVE_PASSWORD_MANAGER
#ifdef SYNC_HAVE_BOOKMARKS
case PrefsCollectionSync::SyncBookmarks:
#endif // SYNC_HAVE_BOOKMARKS
#ifdef SYNC_HAVE_EXTENSIONS
case PrefsCollectionSync::SyncExtensions:
#endif // SYNC_HAVE_EXTENSIONS
#ifdef SYNC_HAVE_FEEDS
case PrefsCollectionSync::SyncFeeds:
#endif // SYNC_HAVE_FEEDS
#ifdef SYNC_HAVE_NOTES
case PrefsCollectionSync::SyncNotes:
#endif // SYNC_HAVE_NOTES
#ifdef SYNC_HAVE_PERSONAL_BAR
case PrefsCollectionSync::SyncPersonalbar:
#endif // SYNC_HAVE_PERSONAL_BAR
#ifdef SYNC_HAVE_SEARCHES
case PrefsCollectionSync::SyncSearches:
#endif // SYNC_HAVE_SEARCHES
#ifdef SYNC_HAVE_SPEED_DIAL
case PrefsCollectionSync::SyncSpeeddial:
#endif // SYNC_HAVE_SPEED_DIAL
#ifdef SYNC_HAVE_TYPED_HISTORY
case PrefsCollectionSync::SyncTypedHistory:
#endif // SYNC_HAVE_TYPED_HISTORY
#ifdef SYNC_CONTENT_FILTERS
case PrefsCollectionSync::SyncURLFilter:
#endif // SYNC_CONTENT_FILTERS
{
// Syncing this type was enabled/disabled
OpSyncSupports supports = OpSyncState::EnablePref2Supports(pref);
OP_DBG(("supports: ") << supports);
if (supports != SYNC_SUPPORTS_MAX)
{
bool sync_enabled = KeepDataClientsEnabled();
#ifdef _DEBUG
if (sync_enabled && !SyncEnabled())
OP_DBG(("sync was last used less than %d days ago at: %d; so don't disable any type that is currently enabled.", SYNC_CHECK_LAST_USED_DAYS, g_pcsync->GetIntegerPref(PrefsCollectionSync::SyncLastUsed)));
#endif // _DEBUG
BroadcastSyncSupportChanged(supports, newvalue && sync_enabled);
}
break;
}
}
}
/* virtual */
void OpSyncCoordinator::PrefChanged(OpPrefsCollection::Collections id, int pref, const OpStringC& newvalue)
{
OP_NEW_DBG("OpSyncCoordinator::PrefChanged()", "sync");
OP_ASSERT(OpPrefsCollection::Sync == id);
OP_DBG((UNI_L("pref: %d; value: '%s'"), pref, newvalue.CStr()));
switch (pref) {
case PrefsCollectionSync::SyncClientState:
case PrefsCollectionSync::SyncClientStateBookmarks:
#ifdef SYNC_HAVE_NOTES
case PrefsCollectionSync::SyncClientStateNotes:
#endif // SYNC_HAVE_NOTES
#ifdef SYNC_HAVE_PASSWORD_MANAGER
case PrefsCollectionSync::SyncClientStatePasswordManager:
#endif // SYNC_HAVE_PASSWORD_MANAGER
#ifdef SYNC_HAVE_SEARCHES
case PrefsCollectionSync::SyncClientStateSearches:
#endif // SYNC_HAVE_SEARCHES
#ifdef SYNC_HAVE_SPEED_DIAL
# ifdef SYNC_HAVE_SPEED_DIAL_2
case PrefsCollectionSync::SyncClientStateSpeeddial2:
# else
case PrefsCollectionSync::SyncClientStateSpeeddial:
# endif // SYNC_HAVE_SPEED_DIAL_2
#endif // SYNC_HAVE_SPEED_DIAL
#ifdef SYNC_TYPED_HISTORY
case PrefsCollectionSync::SyncClientStateTypedHistory:
#endif // SYNC_TYPED_HISTORY
#ifdef SYNC_CONTENT_FILTERS
case PrefsCollectionSync::SyncClientStateURLFilter:
#endif // SYNC_CONTENT_FILTERS
case PrefsCollectionSync::SyncDataProvider:
case PrefsCollectionSync::ServerAddress:
default:
// nothing to do...
break;
}
}
// </Implementation of OpPrefsListener>
void OpSyncCoordinator::BroadcastPendingSyncSupportChanged()
{
if (m_pending_support_state.HasAnySupports())
{
OP_NEW_DBG("OpSyncCoordinator::BroadcastPendingSyncSupportChanged()", "sync");
for (int i = 0; i < SYNC_SUPPORTS_MAX; i++)
{
OpSyncSupports supports = static_cast<OpSyncSupports>(i);
if (m_pending_support_state.HasSupports(supports))
BroadcastSyncSupportChanged(supports, GetSupports(supports) ? true : false);
}
m_pending_support_state.Clear();
}
}
void OpSyncCoordinator::BroadcastSyncSupportChanged(OpSyncSupports supports, bool has_support)
{
OP_NEW_DBG("OpSyncCoordinator::BroadcastSyncSupportChanged()", "sync");
OP_DBG(("support: ") << supports << (has_support?" enabled":" disabled"));
if (m_is_initialised)
{
if (IsSyncInProgress())
{ /* If a sync-connection is in progress we don't want to notify the
* registered OpSyncSupportClient instances immediately, because
* that may interfere with the on-going connection. Instead we set
* the change as pending and on the end of the connection we notify
* the listener.
* See m_sync_in_progress */
m_pending_support_state.SetSupports(supports, true);
return;
}
m_supports_state.SetSupports(supports, has_support);
OpINT32Vector types;
RETURN_VOID_IF_ERROR(OpSyncCoordinator::GetTypesFromSupports(supports, types));
for (unsigned int j = 0; j < types.GetCount(); j++)
{
OpSyncDataItem::DataItemType type = static_cast<OpSyncDataItem::DataItemType>(types.Get(j));
for (unsigned int i = 0; i < m_listeners.GetCount(); i++)
{
OpSyncDataClientItem* listener_item = m_listeners.Get(i);
if (listener_item->HasType(type))
{
OP_DBG(("") << i << ": has type " << type);
OpStatus::Ignore(listener_item->Get()->SyncDataSupportsChanged(type, has_support));
}
}
}
}
}
bool OpSyncCoordinator::KeepDataClientsEnabled() const
{
bool sync_enabled = SyncEnabled();
bool sync_used = static_cast<bool>(g_opera && g_pcsync && g_pcsync->GetIntegerPref(PrefsCollectionSync::SyncUsed));
if (sync_used && !sync_enabled)
{ /* If sync was used once and it is disabled now, we want to continue to
* collect the client's sync updates in the update-queue for the next
* SYNC_CHECK_LAST_USED_DAYS days. Thus on re-enabling sync within that
* period we can simply upload the queue. */
long sync_last_used = g_pcsync->GetIntegerPref(PrefsCollectionSync::SyncLastUsed);
if (sync_last_used > 0)
{
unsigned long seconds_now, milliseconds_now;
g_op_time_info->GetWallClock(seconds_now, milliseconds_now);
if (seconds_now <= (unsigned long)sync_last_used + (SYNC_CHECK_LAST_USED_DAYS*60*60*24))
return true;
}
}
return sync_enabled;
}
void OpSyncCoordinator::BroadcastSyncSupportChanged()
{
OP_NEW_DBG("OpSyncCoordinator::BroadcastSyncSupportChanged()", "sync");
OP_DBG(("sync support %s", SyncEnabled()?"enabled":"disabled"));
bool sync_enabled = KeepDataClientsEnabled();
#ifdef _DEBUG
if (sync_enabled && !SyncEnabled())
OP_DBG(("sync was last used less than %d days ago at: %d; so don't disable any type that is currently enabled.", SYNC_CHECK_LAST_USED_DAYS, g_pcsync->GetIntegerPref(PrefsCollectionSync::SyncLastUsed)));
#endif // _DEBUG
for (int i = 0; i < SYNC_SUPPORTS_MAX; i++)
{
OpSyncSupports supports_type = static_cast<OpSyncSupports>(i);
bool supports = sync_enabled && GetSupports(supports_type);
OP_DBG(("Supports ") << supports_type << ": " << (supports?"yes":"no"));
BroadcastSyncSupportChanged(supports_type, supports);
}
}
#endif // SUPPORT_DATA_SYNC
|
#include "framebuffer.h"
#include "image.h"
#include "glbuffers.h"
#include "consts.h"
#include "assertion.h"
#include <stdexcept>
#include <glad/glad.h>
FrameBuffer::FrameBuffer(FrameBuffer&& other) noexcept {
id = other.id;
other.id = 0;
texture = std::move(other.texture);
}
FrameBuffer& FrameBuffer::operator=(FrameBuffer&& other) noexcept {
id = other.id;
other.id = 0;
texture = std::move(other.texture);
return *this;
}
void FrameBuffer::Load(glm::uvec2 size, bool rectangle) {
texture.Load(size, rectangle);
glGenFramebuffers(1, &id);
Select();
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, texture.GetType(), texture.GetId(), 0);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
THROWERROR("Framebuffer isn't complete");
}
SelectWindow();
}
void FrameBuffer::Reset() {
glDeleteFramebuffers(1, &id);
}
void FrameBuffer::Clear(glm::vec4 color) {
glClearColor(color.x, color.y, color.z, color.w);
glClear(GL_COLOR_BUFFER_BIT);
}
void FrameBuffer::Select() {
glBindFramebuffer(GL_FRAMEBUFFER, id);
glm::vec2 size = texture.GetSize();
glViewport(0, 0, size.x, size.y);
}
void FrameBuffer::SelectWindow() {
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glm::vec2 size = Consts().WindowSize;
glViewport(0, 0, size.x, size.y);
}
void FrameBuffer::Draw(glm::vec2 pos, float scale, const Shader& shader) const {
shader.Select();
texture.Select();
Buffers().SpriteBuffer.Bind();
shader.SetVec2("Position", pos);
shader.SetVec3("Transform", glm::vec3(texture.GetSize(), scale));
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
ObjectBuffer::Unbind();
}
|
#include <exception>
#include <iostream>
#include <fstream>
#include <string>
#include "GameController.h"
int main(int, char*[])
{
GameController gameController;
while (gameController.isRunning)
{
gameController.Run();
}
Renderer::Instance()->~Renderer();
return 0;
}
|
#include<iostream>
#include<vector>
#include<unordered_map>
#include<string>
#include<algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
#define inf 9999
void Init_TreeNode(TreeNode** T, vector<int>& vec, int& pos)
{
if (vec[pos] == inf || vec.size() == 0)
*T = NULL;
else
{
(*T) = new TreeNode(0);
(*T)->val = vec[pos];
Init_TreeNode(&(*T)->left, vec, ++pos);
Init_TreeNode(&(*T)->right, vec, ++pos);
}
}
class Solution {
public:
vector<string> res;
vector<string> binaryTreePaths(TreeNode* root) {
//基本思想:递归
if (root == nullptr)
return res;
string s;
dfs(root, s);
return res;
}
void dfs(TreeNode* root, string s)
{
if (root->left == nullptr && root->right == nullptr)
{
s.append(to_string(root->val));
res.push_back(s);
return;
}
s.append(to_string(root->val));
s.append("->");
if (root->left != nullptr)
{
dfs(root->left, s);
}
if (root->right != nullptr)
{
dfs(root->right, s);
}
return;
}
};
class Solution1 {
public:
vector<string> binaryTreePaths(TreeNode* root) {
//非递归
stack<TreeNode*> st;
stack<string> path;
vector<string> res;
string cur;
if(root)
{
st.push(root);
path.push(to_string(root->val));
}
while(!st.empty())
{
root=st.top();
st.pop();
cur=path.top();
path.pop();
if(root->left==nullptr&&root->right==nullptr)
res.push_back(cur);
if(root->left)
{
st.push(root->left);
path.push(cur+"->"+to_string(root->left->val));
}
if(root->right)
{
st.push(root->right);
path.push(cur+"->"+to_string(root->right->val));
}
}
return res;
}
};
int main()
{
Solution solute;
TreeNode* root = NULL;
vector<int> vec = { 5,-13,-2,-1,inf,inf,inf,4,inf,inf,6,inf,inf };
int pos = 0;
Init_TreeNode(&root, vec, pos);
vector<string> res = solute.binaryTreePaths(root);
for_each(res.begin(), res.end(), [](const string v) {cout << v << endl; });
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2012 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Kajetan Switalski
**
*/
#include "core/pch.h"
#ifdef USE_SPDY
#include "modules/url/protocols/spdy/spdy_internal/spdy_settingsmanager.h"
#include "modules/url/protocols/spdy/spdy_internal/spdy_common.h"
#include "modules/prefs/prefsmanager/collections/pc_network.h"
#include "modules/datastream/opdatastreamsafefile.h"
#include "modules/formats/url_dfr.h"
#define SPDYSETTINGS_FILE_VERSION 1
#define SPDYSETTINGS_FILE_NAME UNI_L("spdysett.dat")
#define TAG_SETTINGS_HOSTPORT_ENTRY 0x01
#define TAG_SETTINGS_HOSTPORT_NAME 0x02
#define TAG_SETTINGS_IDVALUE_PAIR_ENTRY 0x03
#define TAG_SETTINGS_IDVALUE_PAIR_ENTRIES 0x04
#define TAG_SETTINGS_LAST_TIME_USED 0x05
SpdySettingsManager::SpdySettingsManager(): loaded(FALSE), updated(FALSE)
{
}
SpdySettingsManager::~SpdySettingsManager()
{
if (updated)
{
TRAPD(res, WriteFileL());
OpStatus::Ignore(res);
}
storage.DeleteAll();
}
void SpdySettingsManager::LoadFileL()
{
OpStackAutoPtr<OpFile> settingsFile(OP_NEW_L(OpFile, ()));
SPDY_LEAVE_IF_ERROR(settingsFile->Construct(SPDYSETTINGS_FILE_NAME, OPFILE_COOKIE_FOLDER));
if (OpStatus::IsSuccess(settingsFile->Open(OPFILE_READ)))
{
DataFile dataFile(settingsFile.release());
ANCHOR(DataFile, dataFile);
dataFile.InitL();
OpStackAutoPtr<DataFile_Record> rec(NULL);
for (rec.reset(dataFile.GetNextRecordL()); rec.get() && rec->GetTag() == TAG_SETTINGS_HOSTPORT_ENTRY; rec.reset(dataFile.GetNextRecordL()))
{
rec->IndexRecordsL();
SettingsTable *settings = OP_NEW_L(SettingsTable, ());
ANCHOR_PTR(SettingsTable, settings);
rec->GetIndexedRecordStringL(TAG_SETTINGS_HOSTPORT_NAME, settings->hostport);
settings->lastTimeUsed = static_cast<time_t>(rec->GetIndexedRecordUInt64L(TAG_SETTINGS_LAST_TIME_USED));
storage.AddL(settings->hostport, settings);
ANCHOR_PTR_RELEASE(settings);
DataFile_Record *entries = rec->GetIndexedRecord(TAG_SETTINGS_IDVALUE_PAIR_ENTRIES);
if (entries)
{
OpStackAutoPtr<DataFile_Record> entry(NULL);
for (entry.reset(entries->GetNextRecordL()); entry.get() && entry->GetTag() == TAG_SETTINGS_IDVALUE_PAIR_ENTRY; entry.reset(entries->GetNextRecordL()))
{
UINT32 settingId = entry->GetInt32L();
UINT32 value = entry->GetInt32L();
SPDY_LEAVE_IF_ERROR(settings->idvalues.Add(settingId, value));
}
}
}
}
loaded = TRUE;
}
void SpdySettingsManager::WriteFileL()
{
time_t minLastTimeUsed = g_timecache->CurrentTime() - static_cast<time_t>(g_pcnet->GetIntegerPref(PrefsCollectionNetwork::SpdySettingsPersistenceTimeout));
OpStackAutoPtr<OpSafeFile> settingsFile(OP_NEW_L(OpDataStreamSafeFile, ()));
SPDY_LEAVE_IF_ERROR(settingsFile->Construct(SPDYSETTINGS_FILE_NAME, OPFILE_COOKIE_FOLDER));
SPDY_LEAVE_IF_ERROR(settingsFile->Open(OPFILE_WRITE));
DataFile dataFile(settingsFile.release(), SPDYSETTINGS_FILE_VERSION, 1, 2);
ANCHOR(DataFile, dataFile);
dataFile.InitL();
OpStackAutoPtr<OpHashIterator> it(storage.GetIterator());
SPDY_LEAVE_IF_NULL(it.get());
OP_STATUS res = OpStatus::OK;
for (res = it->First(); OpStatus::IsSuccess(res); res = it->Next())
{
const char *host = reinterpret_cast<const char*>(it->GetKey());
SettingsTable* settings = static_cast<SettingsTable*>(it->GetData());
if (settings->lastTimeUsed < minLastTimeUsed)
continue;
DataFile_Record rec(TAG_SETTINGS_HOSTPORT_ENTRY);
ANCHOR(DataFile_Record, rec);
rec.SetRecordSpec(dataFile.GetRecordSpec());
DataFile_Record hostport(TAG_SETTINGS_HOSTPORT_NAME);
ANCHOR(DataFile_Record, hostport);
hostport.SetRecordSpec(dataFile.GetRecordSpec());
hostport.AddContentL(host);
hostport.WriteRecordL(&rec);
rec.AddRecord64L(TAG_SETTINGS_LAST_TIME_USED, static_cast<OpFileLength>(settings->lastTimeUsed));
DataFile_Record pairEntries(TAG_SETTINGS_IDVALUE_PAIR_ENTRIES);
ANCHOR(DataFile_Record, pairEntries);
pairEntries.SetRecordSpec(dataFile.GetRecordSpec());
OpStackAutoPtr<OpHashIterator> it2(settings->idvalues.GetIterator());
SPDY_LEAVE_IF_NULL(it2.get());
res = OpStatus::OK;
for (res = it2->First(); OpStatus::IsSuccess(res); res = it2->Next())
{
UINT32 id = static_cast<UINT32>(reinterpret_cast<UINTPTR>(it2->GetKey()));
UINT32 value = static_cast<UINT32>(reinterpret_cast<UINTPTR>(it2->GetData()));
DataFile_Record idvalue(TAG_SETTINGS_IDVALUE_PAIR_ENTRY);
ANCHOR(DataFile_Record, idvalue);
idvalue.SetRecordSpec(dataFile.GetRecordSpec());
idvalue.AddContentL(id);
idvalue.AddContentL(value);
idvalue.WriteRecordL(&pairEntries);
}
pairEntries.WriteRecordL(&rec);
rec.WriteRecordL(&dataFile);
}
dataFile.Close();
updated = FALSE;
}
void SpdySettingsManager::ClearPersistedSettingsL(const char* hostport)
{
if (!loaded)
LoadFileL();
if (storage.Contains(hostport))
{
SettingsTable *settings;
if (OpStatus::IsSuccess(storage.Remove(hostport, &settings)))
OP_DELETE(settings);
}
updated = TRUE;
}
void SpdySettingsManager::ClearAllL()
{
if (!loaded)
LoadFileL();
storage.DeleteAll();
updated = TRUE;
}
void SpdySettingsManager::PersistSettingL(const char* hostport, UINT32 settingId, UINT32 value)
{
if (!loaded)
LoadFileL();
SettingsTable *settings;
if (OpStatus::IsError(storage.GetData(hostport, &settings)))
{
settings = OP_NEW_L(SettingsTable, ());
ANCHOR_PTR(SettingsTable, settings);
settings->hostport.SetL(hostport);
storage.AddL(settings->hostport, settings);
ANCHOR_PTR_RELEASE(settings);
}
if (settings->idvalues.Contains(settingId))
SPDY_LEAVE_IF_ERROR(settings->idvalues.Update(settingId, value));
else
SPDY_LEAVE_IF_ERROR(settings->idvalues.Add(settingId, value));
settings->lastTimeUsed = g_timecache->CurrentTime();
updated = TRUE;
}
class GetPersistedSettingsHelper: public OpHashTableForEachListener
{
List<PersistedSetting> ⌖
BOOL oomed;
public:
GetPersistedSettingsHelper(List<PersistedSetting> &target): target(target), oomed(FALSE) {}
BOOL Oomed() { return oomed; }
virtual void HandleKeyData(const void* key, void* data)
{
PersistedSetting *setting = OP_NEW(PersistedSetting, ());
if (setting)
{
setting->settingId = static_cast<UINT32>(reinterpret_cast<UINTPTR>(key));
setting->value = static_cast<UINT32>(reinterpret_cast<UINTPTR>(data));
setting->Into(&target);
}
else
oomed = TRUE;
}
};
void SpdySettingsManager::GetPersistedSettingsL(const char* hostport, List<PersistedSetting> &target)
{
if (!loaded)
LoadFileL();
SettingsTable *settings;
if (OpStatus::IsSuccess(storage.GetData(hostport, &settings)))
{
GetPersistedSettingsHelper helper(target);
settings->idvalues.ForEach(&helper);
if (helper.Oomed())
SPDY_LEAVE(OpStatus::ERR_NO_MEMORY);
settings->lastTimeUsed = g_timecache->CurrentTime();
}
}
#endif // USE_SPDY
|
#ifndef MAYA_PLUGIN_TEMPLATE_HELLOWORLD_H
#define MAYA_PLUGIN_TEMPLATE_HELLOWORLD_H
#include <maya/MArgList.h>
#include <maya/MObject.h>
#include <maya/MGlobal.h>
#include <maya/MPxCommand.h>
class HelloWorld : public MPxCommand {
public:
HelloWorld() {};
virtual MStatus doIt(const MArgList &arg_list);
static void *creator();
};
#endif //MAYA_PLUGIN_TEMPLATE_HELLOWORLD_H
|
#include <iberbar/RHI/D3D11/EffectReflection.h>
iberbar::RHI::D3D11::CEffectReflection::CEffectReflection()
: m_ReflectionVarArraySlots()
, m_ReflectionCBufferArraySlots()
{
}
iberbar::CResult iberbar::RHI::D3D11::CEffectReflection::Initial( EShaderType eShaderType, ID3D11ShaderReflection* pD3DShaderReflection )
{
HRESULT hResult;
D3D11_SHADER_DESC ShaderDesc;
D3D11_SHADER_INPUT_BIND_DESC ShaderInputBindDesc;
ID3D11ShaderReflectionConstantBuffer* pShaderConstBuffer;
D3D11_SHADER_BUFFER_DESC ShaderCBufferDesc;
ID3D11ShaderReflectionVariable* pShaderVar;
std::vector< UEffectReflectionVariable >& VarArray = m_ReflectionVarArraySlots[(int)eShaderType];
std::vector< UEffectReflectionConstBuffer >& ConstBufferArray = m_ReflectionCBufferArraySlots[(int)eShaderType];
int nCBufferOffset = 0;
hResult = pD3DShaderReflection->GetDesc( &ShaderDesc );
if ( FAILED( hResult ) )
return MakeResult( ResultCode::Bad, "" );
for ( int nResourceIndex = 0; nResourceIndex < ShaderDesc.BoundResources; nResourceIndex++ )
{
hResult = pD3DShaderReflection->GetResourceBindingDesc( nResourceIndex, &ShaderInputBindDesc );
if ( FAILED( hResult ) )
break;
if ( ShaderInputBindDesc.Type == D3D_SIT_CBUFFER )
{
pShaderConstBuffer = pD3DShaderReflection->GetConstantBufferByName( ShaderInputBindDesc.Name );
if ( pShaderConstBuffer == nullptr )
continue;
hResult = pShaderConstBuffer->GetDesc( &ShaderCBufferDesc );
if ( FAILED( hResult ) )
continue;
UEffectReflectionConstBuffer ConstBuffer;
ConstBuffer.nBindPoint = ShaderInputBindDesc.BindPoint;
ConstBuffer.strName = ShaderCBufferDesc.Name;
ConstBuffer.nOffset = nCBufferOffset;
ConstBuffer.nSize = ShaderCBufferDesc.Size;
nCBufferOffset += ConstBuffer.nSize;
ConstBufferArray.push_back( ConstBuffer );
for ( int nVarIndex = 0; nVarIndex < ShaderCBufferDesc.Variables; nVarIndex++ )
{
VarArray.push_back( sBuildReflectionVariable( ConstBuffer.nOffset, pShaderConstBuffer->GetVariableByIndex( nVarIndex ) ) );
}
}
else if ( ShaderInputBindDesc.Type == D3D_SIT_TEXTURE )
{
}
else if ( ShaderInputBindDesc.Type == D3D_SIT_SAMPLER )
{
}
}
}
iberbar::RHI::D3D11::UEffectReflectionVariable iberbar::RHI::D3D11::CEffectReflection::sBuildReflectionVariable( uint32 nConstBufferBytesOffset, ID3D11ShaderReflectionVariable* pD3DShaderReflectionVariable )
{
ID3D11ShaderReflectionType* pD3DReflectionType;
D3D11_SHADER_VARIABLE_DESC ShaderVarDesc;
D3D11_SHADER_TYPE_DESC D3DReflectionTypeDesc;
pD3DShaderReflectionVariable->GetDesc( &ShaderVarDesc );
pD3DReflectionType = pD3DShaderReflectionVariable->GetType();
pD3DReflectionType->GetDesc( &D3DReflectionTypeDesc );
UEffectReflectionVariable Var;
Var.strName = ShaderVarDesc.Name;
Var.nOffset = ShaderVarDesc.StartOffset;
Var.nOffsetAbs = nConstBufferBytesOffset + ShaderVarDesc.StartOffset;
Var.nTotalSize = ShaderVarDesc.Size;
Var.nElementSize = D3DReflectionTypeDesc.Elements;
Var.nElementCount = D3DReflectionTypeDesc.Elements;
return Var;
}
|
#include<iostream>
#include<stdlib.h>
#include<cstdlib>
using namespace std;
int main(){
int i;
cout<<"checking if processor is available ...";
if(system(NULL))
// puts("ok");
i=0;
else
// exit(EXIT-FAILURE);
cout<<"Executing Command DIR...\n";
i=system("dir");
cout<<"the value returned was:%d.\n",i;
return 0;
}
|
#include <iostream>
#include "cinema.h"
#include "movie.h"
using namespace std;
Cinema::Cinema(){
cinemaName = "??";
movies = new Movie[5];
movieNo = 0;
}
Cinema::Cinema(string cinName){
cinemaName = cinName;
}
string Cinema::getCinemaName(){
return cinemaName;
}
int Cinema::getCinemaNo(){
return movieNo;
}
void Cinema::setCinemaName(string name){
cinemaName = name;
}
int Cinema::getMovieID(){
return movieNo;
}
void Cinema::printMovies(){
for(int i = 0;i<movieNo;i++){
cout<< i<<"."<<movies[i].getMovieName()<<" With a Run Time of "<<movies[i].getMovieTime()<<" Minutes."<<endl;
}
}
void Cinema::addMovie(Movie movie){
//adding movie to the movie array within the movie class
movies[movieNo] = movie;
movieNo +=1;
}
void Cinema::updateMovie(int a,Movie movie1){
movies[a] = movie1;
}
Movie Cinema::getMovie(int movieNo){
return movies[movieNo];
}
void Cinema::printMovieName(int a){
cout<<movies[a].getMovieName()<<endl;
}
void Cinema::calculateSchedule(){
int cumulativeTotal = 0;
for(int i = 0;i<5;i++){
cumulativeTotal += movies[movieNo].getMovieTime();
schedule[i] = 900 + cumulativeTotal;
cout<<"Movie Time: "<< schedule[i]<<endl;
}
}
void Cinema::printSeatLayout(){
cout<<"Row 0: ";
for(int i = 0;i<10;i++){
for(int j = 0;j<30;j++){
cout<<cinemaSeats[i][j]<<",";
//splitting the cinema into thirds to make it easier to see
if(j%10 == 0 && j!=0){
cout<<" ";
}
}
if(i<=8){
cout<<endl<<"Row "<<i+1<<": ";
}
}
cout<<endl;
}
|
#pragma once
#include "../../system.hpp"
namespace sbg {
struct ResultData : Clonable {
virtual std::unique_ptr<ResultData> reverse() const = 0;
ResultData* clone() const override = 0;
};
}
|
#include "Ficha.h"
#include<math.h>
#include <iostream>
#include "glut.h"
#define M 8
#define PX_X 800
#define PX_Y 800
using namespace std;
void Ficha::SetColor(Color col)
{
color = col;
}
float Ficha::GetRadio()
{
return radio;
}
void Ficha::SetRadio(float rad)
{
if (rad < 0.1F)
rad = 0.1F;
radio = rad;
}
void Ficha::SetPos(float ix, float iy)
{
posicion[0] = ix;
posicion[1] = iy;
}
int Ficha::GetPosX()
{
return posicion[0];
}
int Ficha::GetPosY()
{
return posicion[1];
}
Ficha::~Ficha()
{
}
|
#include "OVR_CAPI.h"
#include "Kernel/OVR_Math.h"
#include <iostream>
#include <unistd.h>
#include <curses.h>
class Rift{
public:
Rift();
~Rift();
void Output();
bool HeadPosition(float&,float&,float&);
void ResetSensor();
private:
ovrHmd hmd;
ovrHmdDesc hmdDesc;
ovrFrameTiming frameTiming;
};
|
#include <iostream>
#include <string>
using namespace std;
int main()
{
int a=10;
int b=20;
int &rn=a;
cout<<rn<<endl;
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
int main(){
vector<int> ans = {1, 2, 3, 4, 5, 6};
int n;
cin >> n;
n %= 30;
for(int i=0; i<n; i++){
int x = i % 5;
int y = i % 5 + 1;
ans[x] = ans[x] + ans[y];
ans[y] = ans[x] - ans[y];
ans[x] = ans[x] - ans[y];
}
for(auto x: ans) cout << x;
cout << endl;
return 0;
}
|
#include "PointLight.h"
const double PI = 3.14159265359;
PointLight::PointLight() {
radianceScalingFactor = 1; //default scaling factor
sampleAmount = 1;
radius = 0;
}
void PointLight::generateSamples() {
vector<Point_2D> point2d;
pointLightSamples.clear();
int n = (int)sqrt(sampleAmount / 2);
for (double y = 0; y < n; y++) {
for (double x = 0; x < n; x++) {
double xVal = (x / n) + (((double)rand() / (double)(RAND_MAX)) / n);
double yVal = (y / n) + (((double)rand() / (double)(RAND_MAX)) / n);
point2d.push_back(Point_2D(xVal, yVal));
}
}
n = (int)sqrt(sampleAmount / 2);
for (double y = 0; y < n; y++) {
for (double x = 0; x < n; x++) {
double xVal = (x / n) + (((double)rand() / (double)(RAND_MAX)) / n);
double yVal = (y / n) + (((double)rand() / (double)(RAND_MAX)) / n);
point2d.push_back(Point_2D(xVal, yVal));
}
}
for (int i = 0; i < sampleAmount; i++) {
double cos_phi = cos(2.0 * PI * point2d[i].x);
double sin_phi = sin(2.0 * PI * point2d[i].x);
double cos_theta = pow((1.0 - point2d[i].y), 1.0 / (0 + 1.0));
double sin_theta = sqrt(1.0 - cos_theta * cos_theta);
double z = sin_theta * cos_phi;
double x = sin_theta * sin_phi;
double y = cos_theta;
if (i < int(sampleAmount / 2))
pointLightSamples.push_back(Vector(x, y, z, 0));
else
pointLightSamples.push_back(Vector(x, -y, z, 0));
}
}
void PointLight::setPointLightRadius(double radius) {
this->radius = radius;
}
double PointLight::getRadius() {
return radius;
}
vector<Vector> PointLight::getSamplePoints() {
return pointLightSamples;
}
void PointLight::setAreaPointLightSamplePointAmount(int samplePointAmount) {
sampleAmount = samplePointAmount * 2;
}
int PointLight::getNumberOfSamplePoints() {
return sampleAmount;
}
Vector PointLight::getLightOrigin() {
return origin;
}
void PointLight::setLightOrigin(double x, double y, double z) {
origin.x = x;
origin.y = y;
origin.z = z;
}
void PointLight::setLightColor(double r, double g, double b) {
lightColor.r = r;
lightColor.g = g;
lightColor.b = b;
}
void PointLight::setRadianceScalingFactor(double i) {
radianceScalingFactor = i;
}
double PointLight::getRadianceScalingFactor() {
return radianceScalingFactor;
}
RGB PointLight::getLightColor() {
return lightColor;
}
RGB PointLight::getLightRadiance() {
return lightColor * radianceScalingFactor;
}
|
// demo.cpp : 定义控制台应用程序的入口点。
//
#include "vector"
#include "iostream"
#include "numeric"
#include "algorithm"
#include "math.h"
#include "time.h"
#include "windows.h"
using namespace std;
int main() {
int MinSize = 1;
int MaxSize = 1000;
int FishNum = 4;
int result = 0;
vector<int> FishSize({2, 8, 64, 1000});
vector<int> Size(MaxSize - MinSize + 2, 0);
LARGE_INTEGER t1, t2, tc;
QueryPerformanceFrequency(&tc);
QueryPerformanceCounter(&t1);
int ans = 0;
for (int size = MinSize; size <= MaxSize; size++) {
bool ok = true;
for (int i = 0; i < FishNum; i++) {
if (!((size < 2 * FishSize[i] || size > 10 * FishSize[i]) && (FishSize[i] < 2 * size || FishSize[i] > 10 * size))) {
ok = false;
break;
}
}
if (ok) {
cout << size << "\t";
ans++;
}
}
cout << endl;
cout << "ans = " << ans << endl;
QueryPerformanceCounter(&t2);
cout << (t2.QuadPart - t1.QuadPart)*1.0 / tc.QuadPart << endl;
LARGE_INTEGER t11, t22, tcc;
QueryPerformanceFrequency(&tcc);
QueryPerformanceCounter(&t11);
for (int i = 0; i < FishNum; ++i) {
for (int j = ceil(FishSize[i] / 10); j <= FishSize[i] / 2; ++j) {
Size[j] = 1;
}
for (int j = FishSize[i] * 2; j <= FishSize[i] * 10; ++j) {
if (j < Size.size()) {
Size[j] = 1;
}
}
}
for (int i = 0; i < FishNum; ++i) {
Size[FishSize[i]] = 0;
}
for (int i = 1; i < Size.size(); ++i) {
if (Size[i] == 1) {
continue;
}else {
cout << i << "\t";
++result;
}
}
cout << endl;
cout <<"result = "<< result << endl;
QueryPerformanceCounter(&t22);
cout << (t22.QuadPart - t11.QuadPart)*1.0 / tcc.QuadPart << endl;
system("pause");
return 0;
}
|
/*
* This file is part of OpenModelica.
*
* Copyright (c) 1998-2014, Open Source Modelica Consortium (OSMC),
* c/o Linköpings universitet, Department of Computer and Information Science,
* SE-58183 Linköping, Sweden.
*
* All rights reserved.
*
* THIS PROGRAM IS PROVIDED UNDER THE TERMS OF GPL VERSION 3 LICENSE OR
* THIS OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2.
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3,
* ACCORDING TO RECIPIENTS CHOICE.
*
* The OpenModelica software and the Open Source Modelica
* Consortium (OSMC) Public License (OSMC-PL) are obtained
* from OSMC, either from the above address,
* from the URLs: http://www.ida.liu.se/projects/OpenModelica or
* http://www.openmodelica.org, and in the OpenModelica distribution.
* GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html.
*
* This program is distributed WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH
* IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL.
*
* See the full OSMC Public License conditions for more details.
*
*/
/*
*
* @author Adeel Asghar <adeel.asghar@liu.se>
*
*
*/
#ifndef LINEANNOTATION_H
#define LINEANNOTATION_H
#include "ShapeAnnotation.h"
#include "Component.h"
class Component;
class LineAnnotation : public ShapeAnnotation
{
Q_OBJECT
public:
enum LineType {
ComponentType, /* Line is within Component. */
ConnectionType, /* Line is a connection. */
ShapeType /* Line is a custom shape. */
};
// Used for icon/diagram shape
LineAnnotation(QString annotation, GraphicsView *pGraphicsView);
// Used for shape inside a component
LineAnnotation(ShapeAnnotation *pShapeAnnotation, Component *pParent);
// Used for icon/diagram inherited shape
LineAnnotation(ShapeAnnotation *pShapeAnnotation, GraphicsView *pGraphicsView);
// Used for creating connection
LineAnnotation(Component *pStartComponent, GraphicsView *pGraphicsView);
// Used for reading a connection
LineAnnotation(QString annotation, Component *pStartComponent, Component *pEndComponent, GraphicsView *pGraphicsView);
// Used for non-exisiting component
LineAnnotation(Component *pParent);
// Used for non-existing class
LineAnnotation(GraphicsView *pGraphicsView);
void parseShapeAnnotation(QString annotation);
QPainterPath getShape() const;
QRectF boundingRect() const;
QPainterPath shape() const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0);
void drawLineAnnotaion(QPainter *painter);
QPolygonF drawArrow(QPointF startPos, QPointF endPos, qreal size, int arrowType) const;
QString getOMCShapeAnnotation();
QString getShapeAnnotation();
QString getTLMShapeAnnotation();
void addPoint(QPointF point);
void removePoint(int index);
void clearPoints();
void updateStartPoint(QPointF point);
void updateEndPoint(QPointF point);
void moveAllPoints(qreal offsetX, qreal offsetY);
void setLineType(LineType lineType) {mLineType = lineType;}
LineType getLineType() {return mLineType;}
void setStartComponent(Component *pStartComponent) {mpStartComponent = pStartComponent;}
Component* getStartComponent() {return mpStartComponent;}
void setStartComponentName(QString name) {mStartComponentName = name;}
QString getStartComponentName() {return mStartComponentName;}
void setEndComponent(Component *pEndComponent) {mpEndComponent = pEndComponent;}
Component* getEndComponent() {return mpEndComponent;}
void setEndComponentName(QString name) {mEndComponentName = name;}
QString getEndComponentName() {return mEndComponentName;}
void setShapeFlags(bool enable);
void updateShape(ShapeAnnotation *pShapeAnnotation);
private:
LineType mLineType;
Component *mpStartComponent;
QString mStartComponentName;
Component *mpEndComponent;
QString mEndComponentName;
public slots:
void handleComponentMoved();
void updateConnectionAnnotation();
void duplicate();
};
class ConnectionArray : public QDialog
{
Q_OBJECT
public:
ConnectionArray(GraphicsView *pGraphicsView, LineAnnotation *pConnectionLineAnnotation, QWidget *pParent = 0);
private:
GraphicsView *mpGraphicsView;
LineAnnotation *mpConnectionLineAnnotation;
Label *mpHeading;
QFrame *mpHorizontalLine;
Label *mpDescriptionLabel;
Label *mpStartRootComponentLabel;
QSpinBox *mpStartRootComponentSpinBox;
Label *mpStartComponentLabel;
QSpinBox *mpStartComponentSpinBox;
Label *mpEndRootComponentLabel;
QSpinBox *mpEndRootComponentSpinBox;
Label *mpEndComponentLabel;
QSpinBox *mpEndComponentSpinBox;
QPushButton *mpOkButton;
QPushButton *mpCancelButton;
QDialogButtonBox *mpButtonBox;
QSpinBox* createSpinBox(QString arrayIndex);
public slots:
void createArrayConnection();
void cancelArrayConnection();
};
#endif // LINEANNOTATION_H
|
#ifndef BASEPIECE_H_INCLUDED
#define BASEPIECE_H_INCLUDED
#include <string>
//forward declaration
class Board;
enum Color
{
Black,
White
};
struct Position
{
public:
int xpos;
int ypos;
Position(int x=-1, int y=-1): xpos(x), ypos(y) {}
};
class BasePiece
{
protected:
std::string type;
Color color;
Position position;
public:
BasePiece();
virtual ~BasePiece();
void print();
void setPosition(Position pos);
Position getPosition();
Color getColor();
std::string getType();
virtual bool validateMove(Position moveToPosition, BasePiece* &piece) = 0;
};
#endif // BASEPIECE_H_INCLUDED
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 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 LAYOUT_FIXED_POINT_DEBUG_H
#define LAYOUT_FIXED_POINT_DEBUG_H
#include "modules/layout/layout_debug_utils.h"
/** The LayoutFixed in debug mode. Ensures type safety and provides suitable
debugging utils, like overflow detection. See also LayoutCoordDebug.
In order to hide operations that could be strange and lead to an error, some
standard operators are declared in private section.
All the operations that are the same for LayoutFixed both in debug and
release mode, are declared as public operators. Other operations (ones that
could differ) are friendly inline functions instead.
@see class LayoutCoordDebug. */
class LayoutFixedDebug
{
public:
LayoutFixedDebug() {}
/** All the ctors except the default one are explicit, because they do not
perform any conversion, they just assign the exact value.
If you want to convert e.g. and int to LayoutFixed type, use IntToLayoutFixed
function.
@see LayoutFixed IntToLayoutFixed(int). */
explicit LayoutFixedDebug(int v) : value(v) {}
explicit LayoutFixedDebug(unsigned int v) : value(int(v)) {}
explicit LayoutFixedDebug(double v) : value(int(v)) {}
LayoutFixedDebug operator+(const LayoutFixedDebug& other) const { LayoutFixedDebug res(*this); res += other; return res; }
LayoutFixedDebug operator-(const LayoutFixedDebug& other) const { LayoutFixedDebug res(*this); res -= other; return res; }
void operator+=(const LayoutFixedDebug& other)
{
#ifdef LAYOUT_TYPES_RUNTIME_DEBUG
layout_type_check_add(value, other.value);
#endif // LAYOUT_TYPES_RUNTIME_DEBUG
value += other.value;
}
void operator-=(const LayoutFixedDebug& other)
{
#ifdef LAYOUT_TYPES_RUNTIME_DEBUG
layout_type_check_sub(value, other.value);
#endif // LAYOUT_TYPES_RUNTIME_DEBUG
value -= other.value;
}
double operator*(float val) const { return value * val; }
double operator*(double val) const { return value * val; }
LayoutFixedDebug operator/(int other) const { return LayoutFixedDebug(value / other); }
void operator/=(int other) { value /= other; }
float operator/(float other) const { return value / other; }
LayoutFixedDebug operator-() const { LayoutFixedDebug res(*this); res.value = - value; return res; }
BOOL operator!() const { return !value; }
BOOL operator>(const LayoutFixedDebug &other) const { return value > other.value; }
BOOL operator<(const LayoutFixedDebug &other) const { return value < other.value; }
BOOL operator>=(const LayoutFixedDebug &other) const { return value >= other.value; }
BOOL operator<=(const LayoutFixedDebug &other) const { return value <= other.value; }
BOOL operator==(const LayoutFixedDebug &other) const { return other.value == value; }
BOOL operator!=(const LayoutFixedDebug &other) const { return other.value != value; }
LayoutFixedDebug& operator++() { ++value; return *this; }
LayoutFixedDebug& operator--() { --value; return *this; }
LayoutFixedDebug operator++(int) { LayoutFixedDebug rv(value); ++value; return rv; }
LayoutFixedDebug operator--(int) { LayoutFixedDebug rv(value); --value; return rv; }
private:
/** Private, because the C++ int multiplication of two LayoutFixeds
is not equal to the real, mathematical result. */
LayoutFixedDebug operator*(const LayoutFixedDebug& other) const { LayoutFixedDebug res(*this); res *= other; return res; }
LayoutFixedDebug operator*(int other) const { LayoutFixedDebug res(*this); res *= other; return res; }
void operator*=(int other)
{
#ifdef LAYOUT_TYPES_RUNTIME_DEBUG
layout_type_check_mult(value, other);
#endif // LAYOUT_TYPES_RUNTIME_DEBUG
value *= other;
}
/** The int cast operator. It is private, because in mathematical way
the stored value means different number when considered LayoutFixed. */
operator int() const { return value; }
int value;
friend class PixelOrLayoutFixedDebug;
// Friend functions. Used for LayoutFixed type both in debug and release mode.
friend int LayoutFixedToIntNonNegative(LayoutFixedDebug value);
friend int LayoutFixedToIntRoundDown(LayoutFixedDebug value);
friend int LayoutFixedToInt(LayoutFixedDebug value);
friend float LayoutFixedToFloat(LayoutFixedDebug value);
friend LayoutCoord IntToFixedPointPercentageAsLayoutCoord(int percent);
friend int LayoutFixedAsInt(LayoutFixedDebug value);
friend LayoutCoord LayoutFixedAsLayoutCoord(LayoutFixedDebug value);
friend LayoutFixedDebug LayoutFixedMult(LayoutFixedDebug a, LayoutFixedDebug b);
friend int LayoutFixedPercentageOfInt(LayoutFixedDebug percent, int base);
friend LayoutCoord PercentageToLayoutCoord(LayoutFixedDebug percent, LayoutCoord base);
friend LayoutCoord PercentageToLayoutCoordCeil(LayoutFixedDebug percent, LayoutCoord base);
friend LayoutCoord PercentageOfPercentageToLayoutCoord(LayoutFixedDebug percent, LayoutCoord base, LayoutFixedDebug whole);
friend LayoutCoord DoublePercentageToLayoutCoord(LayoutFixedDebug percent1, LayoutFixedDebug percent2, LayoutCoord base);
friend LayoutCoord ReversePercentageToLayoutCoord(LayoutFixedDebug percent, LayoutCoord reverse_base);
friend LayoutCoord ReversePercentageOfPercentageToLayoutCoord(LayoutFixedDebug percent, LayoutCoord reverse_base, LayoutFixedDebug whole);
friend LayoutCoord ReversePercentageToLayoutCoordRoundDown(LayoutFixedDebug percent, LayoutCoord reverse_base);
friend LayoutFixedDebug MultLayoutFixedByQuotient(LayoutFixedDebug percent, int n, int d);
};
typedef LayoutFixedDebug LayoutFixed;
/** This class acts as a temporary storage of either a pixel value or
a layout fixed point value. It is needed in debug mode to maintain
type safety provided by LayoutFixedDebug class.
It allows two things:
- avoid temporary conversion to LayoutFixed when the value would
be immediately converted back to a full pixel value represented
as standard int or LayoutCoord
- allows to store more integers than LayoutFixed if being an
integer (pixel) value
Use with caution. This class (and type) is planned to be removed
in the near future.
NOTE: Currently, in the layout engine, we sometimes also use
LayoutCoord as a storage of the value that is in fact a
LayoutFixed. Such trick is used for percentage based
widths/heights - when a negative value means percentage based. */
class PixelOrLayoutFixedDebug
{
public:
PixelOrLayoutFixedDebug() {}
PixelOrLayoutFixedDebug(int v) : value(v) {}
PixelOrLayoutFixedDebug(const LayoutFixedDebug& fixed) : value(fixed.value) {}
operator int() const { return value; }
operator LayoutFixedDebug() const { return LayoutFixedDebug(value); }
operator LayoutCoord() const { return LayoutCoord(value); }
private:
int value;
};
typedef PixelOrLayoutFixedDebug PixelOrLayoutFixed;
#endif // LAYOUT_FIXED_POINT_DEBUG_H
|
#include "SM_Test.h"
#include "SM_Calc.h"
namespace
{
bool is_two_points_same(const sm::vec2& p0, const sm::vec2& p1)
{
return fabs(p0.x - p1.x) < SM_LARGE_EPSILON
&& fabs(p0.y - p1.y) < SM_LARGE_EPSILON;
}
}
namespace sm
{
bool is_point_in_segment(const vec2& pos, const vec2& s0, const vec2& s1)
{
if (is_two_points_same(pos, s0) || is_two_points_same(pos, s1)) {
return false;
} else {
rect r(pos, SM_LARGE_EPSILON, SM_LARGE_EPSILON);
return is_rect_intersect_segment(r, s0, s1);
}
}
bool is_rect_intersect_segment(const rect& r, const vec2& s, const vec2& e)
{
unsigned char type_s, type_e;
type_s = type_e = 0;
if (s.x < r.xmin) // left: 1000
type_s |= 0x8;
else if (s.x > r.xmax) // right: 0100
type_s |= 0x4;
if (s.y < r.ymin) // down: 0001
type_s |= 0x1;
else if (s.y > r.ymax) // up: 0010
type_s |= 0x2;
if (e.x < r.xmin) // left: 1000
type_e |= 0x8;
else if (e.x > r.xmax) // right: 0100
type_e |= 0x4;
if (e.y < r.ymin) // down: 0001
type_e |= 0x1;
else if (e.y > r.ymax) // up: 0010
type_e |= 0x2;
unsigned char comp;
comp = type_s & type_e;
if (comp != 0) // must be outside, so must intersect
return false;
comp = type_s | type_e;
if (comp == 0) // must be inside, so must not intersect
return true;
// test each edge
if (comp & 0x8) // 1000, left edge
{
float cross_y;
cross_y = find_y_on_seg(s, e, r.xmin);
if (cross_y >= r.ymin && cross_y <= r.ymax)
return true;
}
if (comp & 0x4) // 0100, right edge
{
float cross_y;
cross_y = find_y_on_seg(s, e, r.xmax);
if (cross_y >= r.ymin && cross_y <= r.ymax)
return true;
}
if (comp & 0x1) // 0001, down edge
{
float cross_x;
cross_x = find_x_on_seg(s, e, r.ymin);
if (cross_x >= r.xmin && cross_x <= r.xmax)
return true;
}
if (comp & 0x2) // 0010, up edge
{
float cross_x;
cross_x = find_x_on_seg(s, e, r.ymax);
if (cross_x >= r.xmin && cross_x <= r.xmax)
return true;
}
return false;
}
static inline
void project_convex(const std::vector<vec2>& c, float angle, float* min, float* max)
{
*min = FLT_MAX;
*max = -FLT_MAX;
for (int i = 0, n = c.size(); i < n; ++i) {
vec2 v = rotate_vector(c[i], angle);
if (v.x < *min) {
*min = v.x;
}
if (v.x > *max) {
*max = v.x;
}
}
}
static inline
bool is_project_intersect(float min0, float max0, float min1, float max1)
{
return !(max1 <= min0 || min1 >= max0);
}
static inline
bool is_convex_intersect_convex(const std::vector<vec2>& c0, const std::vector<vec2>& c1, float angle)
{
float min0, max0, min1, max1;
project_convex(c0, angle, &min0, &max0);
project_convex(c1, angle, &min1, &max1);
return is_project_intersect(min0, max0, min1, max1);
}
static inline
bool is_convex_intersect_convex(const std::vector<vec2>& c0, const std::vector<vec2>& c1, const vec2& v0, const vec2& v1)
{
float angle = SM_PI * 0.5f - atan2(v1.y - v0.y, v1.x - v0.x);
return is_convex_intersect_convex(c0, c1, angle);
}
static inline
bool is_convex_intersect_convex(const std::vector<vec2>& c0, const std::vector<vec2>& c1, const std::vector<vec2>& proj)
{
for (int i = 0, n = c0.size() - 1; i < n; ++i) {
if (!is_convex_intersect_convex(c0, c1, proj[i], proj[i+1])) {
return false;
}
}
if (!is_convex_intersect_convex(c0, c1, proj[c0.size() - 1], proj[0])) {
return false;
}
return true;
}
bool is_convex_intersect_convex(const std::vector<vec2>& c0, const std::vector<vec2>& c1)
{
if (c0.size() < 3 || c1.size() < 3) {
return false;
}
if (!is_convex_intersect_convex(c0, c1, c0) ||
!is_convex_intersect_convex(c0, c1, c1)) {
return false;
} else {
return true;
}
}
static inline
bool is_polygon_colckwise(const std::vector<vec2>& poly)
{
if (poly.size() < 3) {
return false;
}
float left = FLT_MAX;
int left_idx = 0;
int sz = poly.size();
for (int i = 0; i < sz; ++i) {
if (poly[i].x < left) {
left = poly[i].x;
left_idx = i;
}
}
const vec2& curr = poly[left_idx];
const vec2& next = poly[(left_idx+1)%sz];
const vec2& prev = poly[(left_idx+sz-1)%sz];
vec2 up(curr.x, curr.y + 1);
return get_angle(curr, up, next) < get_angle(curr, up, prev);
}
static inline
int get_next_idx_in_ring(int sz, int curr, int step)
{
return (curr + sz + step) % sz;
}
bool is_segment_intersect_polyline(const vec2& s, const vec2& e, const std::vector<vec2>& poly)
{
if (poly.size() < 2) {
return false;
} else if (poly.size() < 3) {
vec2 cross;
if (intersect_segment_segment(s, e, poly[0], poly[1], &cross)) {
if (!is_two_points_same(s, cross) && !is_two_points_same(e, cross) &&
!is_two_points_same(poly[0], cross) && !is_two_points_same(poly[1], cross)) {
return true;
}
}
return false;
}
int sz = poly.size();
for (int i = 0; i < sz; ++i)
{
const vec2& start = poly[i];
int end_idx = get_next_idx_in_ring(sz, i, 1);
const vec2& end = poly[end_idx];
vec2 cross;
if (intersect_segment_segment(s, e, start, end, &cross)) {
if (is_two_points_same(s, cross) || is_two_points_same(e, cross)) {
continue;
}
if (is_two_points_same(start, cross)) {
const vec2& start_prev = poly[get_next_idx_in_ring(sz, i, -1)];
float angle = get_angle(start, end, start_prev);
if (angle > get_angle(start, end, e) ||
angle > get_angle(start, end, s)) {
return true;
}
} else if (is_two_points_same(end, cross)) {
const vec2& end_next = poly[get_next_idx_in_ring(sz, end_idx, 1)];
float angle = get_angle(end, end_next, start);
if (angle > get_angle(end, end_next, e) ||
angle > get_angle(end, end_next, s)) {
return true;
}
} else {
return true;
}
}
}
return false;
}
bool is_polygon_intersect_polygon(const std::vector<vec2>& poly0, const std::vector<vec2>& poly1)
{
if (poly0.size() < 3 || poly1.size() < 3) {
return false;
}
int sz0 = poly0.size(),
sz1 = poly1.size();
int step0 = is_polygon_colckwise(poly0) ? 1 : -1,
step1 = is_polygon_colckwise(poly1) ? 1 : -1;
int idx0 = 0;
for (int i = 0; i < sz0; ++i) {
int idx1 = 0;
const vec2& start0 = poly0[idx0];
int next_idx0 = get_next_idx_in_ring(sz0, idx0, step0);
const vec2& end0 = poly0[next_idx0];
for (int i = 0; i < sz1; ++i) {
const vec2& start1 = poly1[idx1];
int next_idx1 = get_next_idx_in_ring(sz1, idx1, step1);
const vec2& end1 = poly1[next_idx1];
vec2 cross;
if (intersect_segment_segment(start0, end0, start1, end1, &cross)) {
// test if cross is end
bool is_cross0 = is_two_points_same(cross, end0),
is_cross1 = is_two_points_same(cross, end1);
if (is_cross0 && is_cross1) {
const vec2& end_next0 = poly0[get_next_idx_in_ring(sz0, next_idx0, step0)];
const vec2& end_next1 = poly1[get_next_idx_in_ring(sz1, next_idx1, step1)];
float angle0 = get_angle(end0, end_next0, start0);
if (angle0 > get_angle(end0, end_next0, start1) ||
angle0 > get_angle(end0, end_next0, end_next1)) {
return true;
}
float angle1 = get_angle(end1, end_next1, start1);
if (angle1 > get_angle(end1, end_next1, start0) ||
angle1 > get_angle(end1, end_next1, end_next0)) {
return true;
}
//////////////////////////////////////////////////////////////////////////
// vec2 seg00 = start0 - end0;
// seg00.normalize();
// const vec2& end_next0 = poly0[get_next_idx_in_ring(sz0, next_idx0, step0)];
// vec2 seg01 = end_next0 - end0;
// seg01.normalize();
//
// vec2 seg10 = start1 - end1;
// seg10.normalize();
// const vec2& end_next1 = poly0[get_next_idx_in_ring(sz1, next_idx1, step1)];
// vec2 seg11 = end_next1 - end1;
// seg11.normalize();
//
// if (IsTwoSegmentIntersect(seg00, seg01, seg10, seg11) &&
// !is_two_points_same(seg00, seg10) && !is_two_points_same(seg00, seg11) &&
// !is_two_points_same(seg01, seg10) && !is_two_points_same(seg01, seg11)) {
// return true;
// }
} else if (is_cross0) {
const vec2& end_next0 = poly0[get_next_idx_in_ring(sz0, next_idx0, step0)];
if (is_turn_left(end_next0, end0, end1)) {
return true;
}
} else if (is_cross1) {
const vec2& end_next1 = poly0[get_next_idx_in_ring(sz1, next_idx1, step1)];
if (is_turn_left(end_next1, end1, end0)) {
return true;
}
} else if (!is_two_points_same(cross, start0)
&& !is_two_points_same(cross, start1)) {
return true;
}
}
idx1 = next_idx1;
}
idx0 = next_idx0;
}
for (int i = 0; i < sz0; ++i) {
if (is_point_intersect_polyline(poly0[i], poly1)) { continue; }
return is_point_in_area(poly0[i], poly1);
}
for (int i = 0; i < sz1; ++i) {
if (is_point_intersect_polyline(poly1[i], poly0)) { continue; }
return is_point_in_area(poly1[i], poly0);
}
return false;
}
bool is_polygon_convex(const std::vector<vec2>& poly)
{
if (poly.size() < 2) {
return false;
}
if (poly.size() == 3) {
return true;
}
size_t n_positive = 0, n_negative = 0;
for (size_t i = 0, n = poly.size(); i < n; ++i)
{
auto& p0 = poly[(i + n - 1) % n];
auto& p1 = poly[i];
auto& p2 = poly[(i + 1) % n];
auto cross = (p1 - p0).Cross(p2 - p1);
if (cross > 0) {
++n_positive;
} else if (cross < 0) {
++n_positive;
}
}
return n_positive == 0 || n_negative == 0;
}
bool is_polygon_in_polygon(const std::vector<vec2>& in, const std::vector<vec2>& out)
{
if (in.size() < 3 || out.size() < 3) {
return false;
}
int sz0 = (int)in.size(),
sz1 = (int)out.size();
for (int i = 0; i < sz0; ++i) {
if (is_point_intersect_polyline(in[i], out)) { continue; }
if (!is_point_in_area(in[i], out)) {
return false;
} else {
break;
}
}
int step0 = is_polygon_colckwise(in) ? 1 : -1,
step1 = is_polygon_colckwise(out) ? 1 : -1;
int idx0 = 0;
for (int i = 0; i < sz0; ++i) {
int idx1 = 0;
const vec2& start0 = in[idx0];
int next_idx0 = get_next_idx_in_ring(sz0, idx0, step0);
const vec2& end0 = in[next_idx0];
for (int j = 0; j < sz1; ++j) {
const vec2& start1 = out[idx1];
int next_idx1 = get_next_idx_in_ring(sz1, idx1, step1);
const vec2& end1 = out[next_idx1];
vec2 cross;
if (intersect_segment_segment(start0, end0, start1, end1, &cross)) {
// test if cross is end
bool is_cross0 = is_two_points_same(cross, end0),
is_cross1 = is_two_points_same(cross, end1);
if (is_cross0 && is_cross1) {
const vec2& end_next0 = in[get_next_idx_in_ring(sz0, next_idx0, step0)];
const vec2& end_next1 = out[get_next_idx_in_ring(sz1, next_idx1, step1)];
float angle0 = get_angle(end0, end_next0, start0);
float angle_start1 = get_angle(end0, end_next0, start1),
angle_end_next1 = get_angle(end0, end_next0, end_next1);
if ((angle0 > angle_start1 && angle_start1) != 0 ||
(angle0 > angle_end_next1 && angle_end_next1 != 0)) {
return false;
}
} else if (is_cross0) {
const vec2& end_next0 = in[get_next_idx_in_ring(sz0, next_idx0, step0)];
if (is_turn_left(end_next0, end0, end1)) {
return false;
}
} else if (is_cross1) {
const vec2& end_next1 = in[get_next_idx_in_ring(sz1, next_idx1, step1)];
if (is_turn_left(end_next1, end1, end0)) {
return false;
}
} else if (!is_two_points_same(cross, start0)
&& !is_two_points_same(cross, start1)) {
return false;
}
}
idx1 = next_idx1;
}
idx0 = next_idx0;
}
return true;
}
//bool is_polygon_clockwise(const std::vector<vec2>& poly)
//{
// float cross_sum = 0.0f;
// for (size_t i = 0, n = poly.size(); i < n; ++i)
// {
// auto& p0 = poly[i];
// auto& p1 = poly[(i + 1) % n];
// auto& p2 = poly[(i + 2) % n];
// cross_sum += (p1 - p0).Cross(p2 - p1);
// }
// return cross_sum < 0;
//}
bool is_polygon_clockwise(const std::vector<vec2>& poly)
{
float sum = 0.0f;
for (size_t i = 0, n = poly.size(); i < n; ++i)
{
auto& p0 = poly[i];
auto& p1 = poly[(i + 1) % n];
sum += (p1.x - p0.x) * (p1.y + p0.y);
}
return sum > 0;
}
}
|
/* -*- 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 OPERA_SINGLETON_COMPONENT_H
#define OPERA_SINGLETON_COMPONENT_H
/**
* Singleton component referred to by modules/hardcore/module.components.
*
* Trivial instance of CoreComponent running all of Core inside one single component.
*/
class SingletonComponent
: public CoreComponent
{
public:
SingletonComponent(const OpMessageAddress& address)
: CoreComponent(address, COMPONENT_SINGLETON) {}
};
#endif // OPERA_SINGLETON_COMPONENT_H
|
#pragma once
#include "../include/Mainmenu.h"
Mainmenu::Mainmenu(float width, float height) {
try {
font.loadFromFile("Fonts/arial.ttf") ? 1 : throw TextureException();
backgroundtexture.loadFromFile("Texture/Menu.png") ? 1 : throw TextureException();
}
catch (TextureException & e) {
e.what();
}
backgroundtexture.loadFromFile("Texture/Menu.png");
background.setTexture(backgroundtexture);
Vector2u background_size = backgroundtexture.getSize();
Vector2f background_scale = Vector2f((float)width / (float)background_size.x, (float)height / (float)background_size.y);
background.setScale(background_scale);
text[0].setFont(font);
text[0].setFillColor(Color::Yellow);
text[0].setString("New Game");
FloatRect textRect0 = text[0].getLocalBounds();
text[0].setOrigin(textRect0.left + textRect0.width / 2.0f,textRect0.top + textRect0.height / 2.0f);
text[0].setPosition(sf::Vector2f(width / 2.0f, height / 5*1));
text[1].setFont(font);
text[1].setFillColor(Color::White);
text[1].setString("Load Last Game");
FloatRect textRect1 = text[1].getLocalBounds();
text[1].setOrigin(textRect1.left + textRect1.width / 2.0f, textRect1.top + textRect1.height / 2.0f);
text[1].setPosition(sf::Vector2f(width / 2.0f, height / 5 * 2));
text[2].setFont(font);
text[2].setFillColor(Color::White);
text[2].setString("Rules");
FloatRect textRect2 = text[2].getLocalBounds();
text[2].setOrigin(textRect2.left + textRect2.width / 2.0f, textRect2.top + textRect2.height / 2.0f);
text[2].setPosition(sf::Vector2f(width / 2.0f, height / 5 * 3));
text[3].setFont(font);
text[3].setFillColor(Color::White);
text[3].setString("Exit");
FloatRect textRect3 = text[3].getLocalBounds();
text[3].setOrigin(textRect3.left + textRect3.width / 2.0f, textRect3.top + textRect3.height / 2.0f);
text[3].setPosition(sf::Vector2f(width / 2.0f, height / 5 * 4));
nick[0].setFont(font);
nick[0].setFillColor(Color::Yellow);
nick[0].setString("Imie pierwszego gracza");
FloatRect textRect4 = nick[0].getLocalBounds();
nick[0].setOrigin(textRect4.left + textRect4.width / 2.0f, textRect4.top + textRect4.height / 2.0f);
nick[0].setPosition(sf::Vector2f(width / 2.0f, height / 5 * 1));
nick[1].setFont(font);
nick[1].setFillColor(Color::Yellow);
nick[1].setString("Imie drugiego gracza");
FloatRect textRect5 = nick[1].getLocalBounds();
nick[1].setOrigin(textRect5.left + textRect5.width / 2.0f, textRect5.top + textRect5.height / 2.0f);
nick[1].setPosition(sf::Vector2f(width / 2.0f, height / 5 * 3));
player[0].setFont(font);
player[0].setString("Player 1");
player[0].setFillColor(sf::Color::White);
player[0].setStyle(sf::Text::Italic);
FloatRect textRect6 = player[0].getLocalBounds();
player[0].setOrigin(textRect6.left + textRect6.width / 2.0f, textRect6.top + textRect6.height / 2.0f);
player[0].setPosition(sf::Vector2f(width / 2.0f, height / 5 * 2));
player[1].setFont(font);
player[1].setString("Player 2");
player[1].setFillColor(sf::Color::White);
player[1].setStyle(sf::Text::Italic);
FloatRect textRect7 = player[1].getLocalBounds();
player[1].setOrigin(textRect7.left + textRect7.width / 2.0f, textRect7.top + textRect7.height / 2.0f);
player[1].setPosition(sf::Vector2f(width / 2.0f, height / 5 * 4));
selectedItemIndex = 0;
zasadytxt[0].setFont(font);
zasadytxt[0].setFillColor(Color::Yellow);
zasadytxt[0].setString("Zasady Gry");
FloatRect textRectz0 = zasadytxt[0].getLocalBounds();
zasadytxt[0].setOrigin(textRectz0.left + textRectz0.width / 2.0f, textRectz0.top + textRectz0.height / 2.0f);
zasadytxt[0].setPosition(sf::Vector2f(width / 2.0f, height / 7 * 1));
zasadytxt[1].setFont(font);
zasadytxt[1].setFillColor(Color::White);
zasadytxt[1].setString("1. Bicie jest przymusowe.");
FloatRect textRectz1 = zasadytxt[1].getLocalBounds();
zasadytxt[1].setOrigin(textRectz1.left + textRectz1.width / 2.0f, textRectz1.top + textRectz1.height / 2.0f);
zasadytxt[1].setPosition(sf::Vector2f(width / 2.0f, height / 7 * 2));
zasadytxt[2].setFont(font);
zasadytxt[2].setFillColor(Color::White);
zasadytxt[2].setString("2. Jest mozliwe bicie do tylu.");
FloatRect textRectz2 = zasadytxt[2].getLocalBounds();
zasadytxt[2].setOrigin(textRectz2.left + textRectz2.width / 2.0f, textRectz2.top + textRectz2.height / 2.0f);
zasadytxt[2].setPosition(sf::Vector2f(width / 2.0f, height / 7 * 3));
zasadytxt[3].setFont(font);
zasadytxt[3].setFillColor(Color::White);
zasadytxt[3].setString("3. Damki moga poruszac sie dowolna ilosc pol.");
FloatRect textRectz3 = zasadytxt[3].getLocalBounds();
zasadytxt[3].setOrigin(textRectz3.left + textRectz3.width / 2.0f, textRectz3.top + textRectz3.height / 2.0f);
zasadytxt[3].setPosition(sf::Vector2f(width / 2.0f, height / 7 * 4));
zasadytxt[4].setFont(font);
zasadytxt[4].setFillColor(Color::White);
zasadytxt[4].setString("4. Wygrywa gracz ktory pozbawi przeciwnika jego figur, badz mozliwosci ruchu.");
FloatRect textRectz4 = zasadytxt[4].getLocalBounds();
zasadytxt[4].setOrigin(textRectz4.left + textRectz4.width / 2.0f, textRectz4.top + textRectz4.height / 2.0f);
zasadytxt[4].setPosition(sf::Vector2f(width / 2.0f, height / 7 * 5));
zasadytxt[5].setFont(font);
zasadytxt[5].setFillColor(Color::Yellow);
zasadytxt[5].setString("Powrot do menu");
FloatRect textRectz5 = zasadytxt[5].getLocalBounds();
zasadytxt[5].setOrigin(textRectz5.left + textRectz5.width / 2.0f, textRectz5.top + textRectz5.height / 2.0f);
zasadytxt[5].setPosition(sf::Vector2f(width / 2.0f, height / 7 * 6));
}
Mainmenu::~Mainmenu(){
}
void Mainmenu::loadPlayersNames(Event event) {
if (event.type == sf::Event::TextEntered && !playerHasName1)
{
if (event.text.unicode == '\b' && (playerInput.size() > 0))
playerInput.erase(playerInput.size() - 1, 1);
else if (event.text.unicode == '\b' && (playerInput.size() == 0))
playerInput = "";
else if (event.text.unicode > 31 && event.text.unicode < 128)
playerInput += event.text.unicode;
if (playerInput.size() > 7) {
playerInput.erase(playerInput.size() - 1, 1);
}
player[0].setString(playerInput);
player[0].setPosition(sf::Vector2f(width1 / 2.0f, height1 / 5 * 2));
}
if (event.type == sf::Event::KeyPressed) {
if (event.key.code == sf::Keyboard::Return && !playerHasName1 && playerInput.length() > 0) {
playerHasName1 = true;
playerInput = "";
}
}
if (event.type == sf::Event::TextEntered && !playerHasName2 && playerHasName1)
{
if (event.text.unicode == '\b' && (playerInput.size() > 0))
playerInput.erase(playerInput.size() - 1, 1);
else if (event.text.unicode == '\b' && (playerInput.size() == 0))
playerInput = "";
else if (event.text.unicode > 31 && event.text.unicode < 128)
playerInput += event.text.unicode;
if (playerInput.size() > 7) {
playerInput.erase(playerInput.size() - 1, 1);
}
player[1].setString(playerInput);
FloatRect textRect6 = player[1].getLocalBounds();
player[1].setPosition(sf::Vector2f(width1 / 2.0f, height1 / 5 * 4));
}
if (event.type == sf::Event::KeyPressed) {
if (event.key.code == sf::Keyboard::Return && playerHasName1 && playerInput.length() > 0) {
playerHasName2 = true;
playerInput = "";
}
}
}
void Mainmenu::zasady(RenderWindow& window) {
Event event;
window.setVerticalSyncEnabled(true);
window.setFramerateLimit(60);
while (window.isOpen()) {
mouse_position = Mouse::getPosition(window);
if (zasadytxt[5].getGlobalBounds().contains(mouse_position.x, mouse_position.y)) {
zasadytxt[5].setFillColor(Color::Magenta);
}
else {
zasadytxt[5].setFillColor(Color::Yellow);
}
window.clear();
window.draw(background);
for (int i = 0; i < 6; i++) {
window.draw(zasadytxt[i]);
}
window.draw(zasadytxt[5]);
window.display();
while (window.pollEvent(event))
{
if (event.type == Event::Closed)
{
window.close();
}
if (event.type == Event::MouseButtonPressed && event.key.code == Mouse::Left) {
if (zasadytxt[5].getGlobalBounds().contains(mouse_position.x, mouse_position.y)) {
return;
}
}
}
}
}
void Mainmenu::draw(RenderWindow& window) {
window.clear();
window.draw(background);
for (int i = 0; i < 4; i++) {
window.draw(text[i]);
}
}
void Mainmenu::ustawmyszke(RenderWindow& window) {
mouse_position = Mouse::getPosition(window);
selectedItemIndex = 4;
for (int i = 0; i < 4; i++) {
if (text[i].getGlobalBounds().contains(mouse_position.x, mouse_position.y)) {
if(text[i].getFillColor() != Color::Yellow)
text[i].setFillColor(Color::Yellow);
selectedItemIndex = i;
}
else
{
if (text[i].getFillColor() != Color::White)
text[i].setFillColor(Color::White);
}
}
}
void Mainmenu::savenicknames() {
ofstream file;
file.open("saved game/imiona.dat");
string tekst = player[0].getString();
string tekst2 = player[1].getString();
file << tekst << '\n' << tekst2 << '\n';
}
void Mainmenu::oknonickname(RenderWindow& window) {
window.setVerticalSyncEnabled(true);
window.setFramerateLimit(60);
Event event;
window.clear();
window.draw(background);
for (int i = 0; i < 2; i++) {
window.draw(nick[i]);
window.draw(player[i]);
}
window.display();
while (window.isOpen()) {
while (window.pollEvent(event))
{
if (event.type == Event::Closed)
{
window.close();
}
if (!playerHasName2) {
loadPlayersNames(event);
}
}
window.clear();
window.draw(background);
for (int i = 0; i < 2; i++) {
window.draw(nick[i]);
window.draw(player[i]);
}
window.display();
if (playerHasName2) {
savenicknames();
player[0].setString("Player1");
player[1].setString("Player2");
playerHasName1 = false;
playerHasName2 = false;
break;
}
}
}
|
do_configure_prepend() {
# Set the path to the binary edje_cc otherwise it will search it in the host rootfs
sed -i 's!@edje_cc@!${STAGING_BINDIR_NATIVE}/edje_cc!g' Makefile.am
}
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int condition = 0;
float number;
float sum = 0.0;
float avg;
while(1)
{
cin>>number;
if(number>=0.0 && number <=10.0)
{
sum = sum + number;
condition = 1+condition;
if(condition== 2)
{
break;
}
}
else
{
cout<<"nota invalida\n";
}
}
avg = sum/2.0;
cout<<"media = "<<fixed<<setprecision(2)<<avg<<"\n";
return 0;
}
|
//
// Created by 钟奇龙 on 2019-05-10.
//
#include <iostream>
#include <string>
using namespace std;
void reverseWord(string &s,int left,int right){
while(left < right){
swap(s[left++],s[right--]);
}
}
/*
* 单词顺序逆序
*/
void rotateWord(string &s){
if(s.size() == 0) return;
int left = -1;
int right = -1;
reverseWord(s,0,s.size()-1);
for(int i=0; i<s.size(); ++i){
if(s[i] != ' '){
left = i == 0 || (s[i-1] == ' ') ? i : left;
right = i == s.size()-1 || s[i+1] == ' ' ? i : right;
}
if(left != -1 && right != -1){
reverseWord(s,left,right);
left = -1;
right = -1;
}
}
}
/*
* 数组部分逆序
*/
void rotateWord2(string &s,int size){
if(s.size() == 0 || s.size() < size) return;
reverseWord(s,0,size-1);
reverseWord(s,size,s.size()-1);
reverseWord(s,0,s.size()-1);
}
int main(){
string s = "dog loves pig";
string s1 = "i'm a student";
rotateWord(s);
cout<<s<<endl;
string s2 = "abcde";
rotateWord2(s2,3);
cout<<s2<<endl;
return 0;
}
|
#include "stdio.h"
#include "windows.h"
#include "ipHlpapi.h"
#include "tchar.h"
#include "iostream"
#pragma comment(lib,"iphlpapi.lib")
void GetLocalMAC(char * buf);
BOOL IsLocalAdapter(char *pAdapterName);
void UTF8ToWideChar(IN UCHAR* utfChar, OUT _TCHAR** wideChar)
{
int len = MultiByteToWideChar(CP_ACP, 0, (LPSTR)utfChar, -1, NULL, 0);
*wideChar = (_TCHAR*)malloc(2 * len + 1);
MultiByteToWideChar(CP_ACP, 0, (LPSTR)utfChar, -1, (LPWSTR)*wideChar, len);
wprintf(L"widechar=%ls\n", (const wchar_t*)(*wideChar));
//MessageBoxW(NULL, (const wchar_t*)*wideChar + 1, NULL, MB_OK);
}
int main(int n, char* arg[])
{
setlocale(LC_ALL, "en");
char* s1 = "hello─Ń║├a";
wchar_t* s2 = NULL;
UTF8ToWideChar((UCHAR*)s1,&s2);
printf("s1.len=%d,s2.len=%d\n", strlen(s1), wcslen(s2));
printf("s1=%s\n", s1);
wprintf(L"s2=%ls\n", s2);
getchar();
}
void GetLocalMAC(char *buf)
{
IP_ADAPTER_INFO *IpAdaptersInfo = NULL;
IP_ADAPTER_INFO *IpAdaptersInfoHead = NULL;
IpAdaptersInfo = (IP_ADAPTER_INFO *)GlobalAlloc(GPTR, sizeof(IP_ADAPTER_INFO));
if (IpAdaptersInfo == NULL)
{
return;
}
DWORD dwDataSize = sizeof(IP_ADAPTER_INFO);
DWORD dwRetVal = GetAdaptersInfo(IpAdaptersInfo, &dwDataSize);
if (ERROR_SUCCESS != dwRetVal)
{
GlobalFree(IpAdaptersInfo);
IpAdaptersInfo = NULL;
if (ERROR_BUFFER_OVERFLOW == dwRetVal)
{
IpAdaptersInfo = (IP_ADAPTER_INFO *)GlobalAlloc(GPTR, dwDataSize);
if (IpAdaptersInfo == NULL)
{
return;
}
if (ERROR_SUCCESS != GetAdaptersInfo(IpAdaptersInfo, &dwDataSize))
{
GlobalFree(IpAdaptersInfo);
return;
}
}
else
{
return;
}
}
//Save the head pointer of IP_ADAPTER_INFO structures list.
IpAdaptersInfoHead = IpAdaptersInfo;
do{
if (IsLocalAdapter(IpAdaptersInfo->AdapterName))
{
sprintf(buf, "%02x-%02x-%02x-%02x-%02x-%02x",
IpAdaptersInfo->Address[0],
IpAdaptersInfo->Address[1],
IpAdaptersInfo->Address[2],
IpAdaptersInfo->Address[3],
IpAdaptersInfo->Address[4],
IpAdaptersInfo->Address[5]);
//
break;
}
IpAdaptersInfo = IpAdaptersInfo->Next;
} while (IpAdaptersInfo);
if (IpAdaptersInfoHead != NULL)
{
GlobalFree(IpAdaptersInfoHead);
}
}
BOOL IsLocalAdapter(char *pAdapterName)
{
BOOL ret_value = FALSE;
#if 0
#define NET_CARD_KEY _T("System\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}")
char szDataBuf[MAX_PATH + 1];
DWORD dwDataLen = MAX_PATH;
DWORD dwType = REG_SZ;
HKEY hNetKey = NULL;
HKEY hLocalNet = NULL;
if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, NET_CARD_KEY, 0, KEY_READ, &hNetKey))
return FALSE;
wsprintf(szDataBuf, "%s\\Connection", pAdapterName);
if (ERROR_SUCCESS != RegOpenKeyEx(hNetKey, szDataBuf, 0, KEY_READ, &hLocalNet))
{
RegCloseKey(hNetKey);
return FALSE;
}
if (ERROR_SUCCESS != RegQueryValueEx(hLocalNet, "MediaSubType", 0, &dwType, (BYTE *)szDataBuf, &dwDataLen))
{
goto ret;
}
if (*((DWORD *)szDataBuf) != 0x01)
goto ret;
dwDataLen = MAX_PATH;
if (ERROR_SUCCESS != RegQueryValueEx(hLocalNet, "PnpInstanceID", 0, &dwType, (BYTE *)szDataBuf, &dwDataLen))
{
goto ret;
}
if (strncmp(szDataBuf, "PCI", strlen("PCI")))
goto ret;
ret_value = TRUE;
ret:
RegCloseKey(hLocalNet);
RegCloseKey(hNetKey);
#endif
return ret_value;
}
|
// Solution 1 using the largestRectangleArea method
// 把第0行到第i行形成的矩形看成最大直方图矩形问题的输入
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
if (matrix.empty()) return 0;
int maxArea = 0;
vector<int> heights(matrix.front().size(), 0);
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix[i].size(); j++) {
heights[j] = matrix[i][j] == '0' ? 0 : heights[j] + 1;
}
maxArea = max(maxArea, largestRectangleArea(heights));
}
return maxArea;
}
private:
int largestRectangleArea(vector<int>& heights) {
int maxArea = 0;
heights.push_back(0);
vector<int> indices;
for (int i = 0; i < heights.size(); i++) {
while (!indices.empty() && heights[i] <= heights[indices.back()]) {
int h = heights[indices.back()];
indices.pop_back();
int w = indices.empty() ? i : i - indices.back() - 1;
maxArea = max(maxArea, h * w);
}
indices.push_back(i);
}
return maxArea;
}
};
// Solution 2 DP
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
if(matrix.empty()) return 0;
int maxArea = 0;
int m = matrix.size();
int n = matrix[0].size();
vector<int> height(n, 0), left(n, 0), right(n, n);
for (int i = 0; i < m; i++) {
int cl = 0, cr = n;
for (int j = 0; j < n; j++) {
int lj = j;
int rj = n - j - 1;
if (matrix[i][lj] == '1') {
height[lj]++;
left[lj] = max(left[lj], cl);
}
else {
height[lj] = 0;
left[lj] = 0;
cl = lj + 1;
}
if (matrix[i][rj] == '1') {
right[rj] = min(right[rj], cr);
}
else {
right[rj] = n;
cr = rj;
}
}
for (int j = 0; j < n; j++) {
maxArea = max(maxArea, height[j] * (right[j] - left[j]));
}
}
return maxArea;
}
};
|
class Solution{
public:
ll dp[1001][1001];
long long combination (int m,int n){
if(m<n) return 0;
if(n==0||m==n) return 1;
if(dp[m][n]!=-1) return dp[m][n];
else return dp[m][n] = (combination(m-1,n)+combination(m-1,n-1))%1000000007;
}
vector<ll> nthRowOfPascalTriangle(int n) {
memset(dp,-1,sizeof(dp));
vector<ll> v;
for(int i = 0;i<=n-1;i++){
v.push_back(combination(n-1,i));
}
return v;
}
};
|
#include "interruptprocess.h"
InterruptProcess::InterruptProcess(QObject* parent)
{
Q_UNUSED(parent)
setRect(QRectF(0,0,100,100));
setPen(Qt::PenStyle::DashLine);
setBrush(Qt::red);
setOpacity(0.5);
txt = new QGraphicsTextItem(this);
txt->setPlainText("Interrupt");
txt->setFont(QFont("times",10));
txt->setDefaultTextColor(Qt::red);
txt->setPos(x()+15,y()+35);
}
|
#pragma once
#include "declspec.h"
#include <SFML/Graphics/Color.hpp>
namespace sf
{
class VertexArray;
template <typename T> class Rect;
typedef Rect<float> FloatRect;
}
namespace pure
{
PUREENGINE_API sf::VertexArray createVertSquare(const sf::FloatRect& rect, const sf::Color& color = sf::Color::Green);
}
|
#pragma once
#include "cmm/cmm.h"
#include "mat/mat_base.h"
class CMat
{
public:
static void init(void);
static const rsfpat_t getPat(emat_t idx)
{
assert(s_mat[idx]);
return s_mat[idx]->get_pat();
}
static const CMatBase & getMat(emat_t idx)
{
assert(s_mat[idx]);
return *s_mat[idx];
}
private:
static rfontface_t s_ff;
static const CMatBase * s_mat[EMAT_MAX];
};
|
#ifndef UI_SLIDER_HPP_
#define UI_SLIDER_HPP_
#include "UiObject.hpp"
#include "TextRendererFactory.hpp"
class UiSlider : public UiObject {
private:
const double kTopValue;
const double kBottomValue;
public:
UiSlider()
: kTopValue(1.0)
, kBottomValue(0.0)
{
label_ = "slider";
position_ = 0;
UpdateCurrentValue();
value_callback_ = 0;
active_ = false;
text_ = TextRendererFactory::getTextRenderer();
text_->AddFont(1, "ubuntu_mono.ttf");
}
~UiSlider() {}
void SetLabel(const std::string & label) {
label_ = label;
}
void SetInitialValue(const double & value) {
current_value_ = value;
position_ = slider_position_.y + h_ * (current_value_ - kTopValue) / (kBottomValue - kTopValue);
}
void SetPosition(const ScreenPosition & p) {
UiObject::SetPosition(p);
label_position_ = p;
slider_position_ = p;
slider_position_.y += 50;
position_ = slider_position_.y;
}
void SetValueCallback(std::function<void(const double &)> callback) {
value_callback_ = callback;
}
void Render() {
int sm = 4;
glColor4f(0.0, 0.0, 0.0, 0.8);
glBegin(GL_QUADS);
glVertex2i(slider_position_.x - sm, slider_position_.y - sm);
glVertex2i(slider_position_.x + w_ + sm, slider_position_.y - sm);
glVertex2i(slider_position_.x + w_ + sm, slider_position_.y + h_ + sm);
glVertex2i(slider_position_.x - sm, slider_position_.y + h_ + sm);
glEnd();
glColor3f(1.0, 1.0, 1.0);
glLineWidth(2.0);
glBegin(GL_LINE_LOOP);
glVertex2i(slider_position_.x - sm, slider_position_.y - sm);
glVertex2i(slider_position_.x + w_ + sm, slider_position_.y - sm);
glVertex2i(slider_position_.x + w_ + sm, slider_position_.y + h_ + sm);
glVertex2i(slider_position_.x - sm, slider_position_.y + h_ + sm);
glEnd();
glColor3f(1.0, 0.0, 0.0);
glLineWidth(4.0);
glBegin(GL_LINES);
glVertex2i(slider_position_.x, position_);
glVertex2i(slider_position_.x + w_, position_);
glEnd();
glColor3f(1.0, 1.0, 1.0);
text_->UseFont(1, 32);
glRasterPos2i(label_position_.x, label_position_.y);
text_->Print("%s", label_.c_str());
}
void StartSliding(const ScreenPosition & cursor) {
start_position_ = cursor;
active_ = true;
}
void StopSliding() {
active_ = false;
}
void Update(const ScreenPosition & cursor) {
if (active_) {
if (isMouseOver(cursor)) {
position_ = cursor.y;
UpdateCurrentValue();
}
}
}
double GetValue() {
return current_value_;
}
private:
bool isMouseOver(const ScreenPosition & p) {
return (
p.y > slider_position_.y &&
p.y < slider_position_.y + h_ &&
p.x > slider_position_.x &&
p.x < slider_position_.x + w_ );
}
void UpdateCurrentValue() {
current_value_ = kTopValue + (position_ - slider_position_.y) * (kBottomValue - kTopValue) / h_;
if (value_callback_ != 0) {
value_callback_(current_value_);
}
}
private:
TextRendererInterface * text_;
std::string label_;
int position_;
double current_value_;
ScreenPosition label_position_;
ScreenPosition slider_position_;
ScreenPosition start_position_;
bool active_;
std::function<void(const double &)> value_callback_;
};
#endif // UI_SLIDER_HPP_
|
//===========================================================================
/*
This file is part of the CHAI 3D visualization and haptics libraries.
Copyright (C) 2003-2004 by CHAI 3D. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License("GPL") version 2
as published by the Free Software Foundation.
For using the CHAI 3D libraries with software that can not be combined
with the GNU GPL, and for taking advantage of the additional benefits
of our support services, please contact CHAI 3D about acquiring a
Professional Edition License.
\author: <http://www.chai3d.org>
\author: Chris Sewell
\version 1.0
\date 05/2006
*/
//===========================================================================
#include "CProxyPointForceAlgo.h"
//===========================================================================
/*!
\class cForceShadingProxy
\brief cForceShadingProxy extends cProxyPointForceAlgo for
implementing a somewhat simplified version of force
shading, as described in Diego Ruspini's paper "The
Haptic Display of Complex Graphical Environments"
*/
//===========================================================================
class cForceShadingProxy : public cProxyPointForceAlgo
{
public:
// CONSTRUCTOR AND DESTRUCTOR:
//! Constructor of cForceShadingProxy
cForceShadingProxy() : cProxyPointForceAlgo() { m_useShading = 1; };
// METHODS:
//! Compute next proxy position using Ruspini's two-pass algorithm
virtual void computeNextBestProxyPosition(cVector3d a_goal);
//! Set whether to use force shading
void setUseShading(int a_useShading) { m_useShading = a_useShading; }
//! Get whether force shading is being used
int getUseShading() { return m_useShading; }
protected:
// PROPERTIES:
//! Use force shading?
int m_useShading;
};
|
/*=============================================================================
/*-----------------------------------------------------------------------------
/* [JSONSampler.cpp] RapidJSONヘルパークラス
/* Author:Kousuke,Ohno.
/*-----------------------------------------------------------------------------
/* 説明:RapidJSONヘルパークラス
=============================================================================*/
/*--- インクルードファイル ---*/
#include "../StdAfx.h"
#include "JSONSampler.h"
//RapidJSONはJSONファイルを高速に構文解析するためのAPI
////RapidJSONそのもの
//#include "../External/rapidjson/include/document.h"
////書き込み
//#include "../External/rapidjson/include/writer.h"
//#include "../External/rapidjson/include/filewritestream.h" //インデント・改行なし
//#include "../External/rapidjson/include/prettywriter.h" //インデント・改行あり
////読み込み
//#include "../External/rapidjson/include/reader.h"
//#include "../External/rapidjson/include/filereadstream.h"
////エラーハンドル
//#include "../External/rapidjson/include/error/en.h"
using namespace rapidjson;
/*-----------------------------------------------------------------------------
/* コンストラクタ
-----------------------------------------------------------------------------*/
JSONSampler::JSONSampler(void)
{
}
/*-----------------------------------------------------------------------------
/* デストラクタ
-----------------------------------------------------------------------------*/
JSONSampler::~JSONSampler(void)
{
}
/*-----------------------------------------------------------------------------
/* 読み込み関数
-----------------------------------------------------------------------------*/
void JSONSampler::LoadSamples(void)
{
//文字列データをDOMに渡して解析し、読み込み表示する処理
//JSONSampler::DOMParseSample01();
//JSONSampler::DOMParseSample02();
//メモリからの入出力表示する処理
//JSONSampler::MemoryIOStreamingSample();
//ファイルからの入出力表示する処理
//JSONSampler::FileIOStreamingSample();
//構文解析エラーの出力表示サンプル
//JSONSampler::ParseErrorSample();
//Valueの値ごとに構文解析するサンプル
//JSONSampler::GenerateObjectSample();
//JSONSampler::GenerateArraySample();
//JSONSampler::GenerateNumberSample();
JSONSampler::GenerateStringSample();
}
/*-----------------------------------------------------------------------------
/* サンプル関数_DOMパース01
-----------------------------------------------------------------------------*/
void JSONSampler::DOMParseSample01(void)
{
// 1. Parse a JSON string into DOM.
const char* json = "{\"project\":\"rapidjson\",\"stars\":10}";
Document d;
d.Parse(json);
// 2. Modify it by DOM.
Value& s = d["stars"];
s.SetInt(s.GetInt() + 1);
// 3. Stringify the DOM
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
// Output {"project":"rapidjson","stars":11}
std::cout << buffer.GetString() << std::endl;
}
/*-----------------------------------------------------------------------------
/* サンプル関数_DOMパース02
-----------------------------------------------------------------------------*/
void JSONSampler::DOMParseSample02(void)
{
const char* s_json = R"(
{
"string" : "foo",
"number" : 123,
"array" : [
0,
1,
2,
3
],
"object" : {
"v0" : "bar",
"v1" : 456,
"v2" : 0.123
}
}
)";
Document doc;
//DOM(DocumentObjectModel)へ渡したデータの構文解析エラーハンドリング
doc.Parse(s_json);
bool error = doc.HasParseError();
if (error) {
printf("parse error\n");
return;
}
// string
{
const char* v = doc["string"].GetString();
printf("string = %s\n", v);
}
// number
{
int v = doc["number"].GetInt();
printf("number = %d\n", v);
}
// array
{
const Value& a = doc["array"];
SizeType num = a.Size();
for (SizeType i = 0; i < num; i++) {
int v = a[i].GetInt();
printf("array[%d] = %d\n", i, v);
}
}
// object
{
const Value& o = doc["object"];
// enumerate members in object
for (Value::ConstMemberIterator itr = o.MemberBegin();
itr != o.MemberEnd(); itr++)
{
const char* name = itr->name.GetString();
const Value& value = itr->value;
Type type = value.GetType();
printf("%s = ", name);
switch (type) {
case kStringType:
printf("%s", value.GetString());
break;
case kNumberType:
if (value.IsDouble())
printf("%f", value.GetDouble());
else
printf("%d", value.GetInt());
break;
default:
printf("(unknown type)");
break;
}
printf("\n");
}
}
}
/*-----------------------------------------------------------------------------
/* サンプル関数_メモリからの入出力ストリーミング
-----------------------------------------------------------------------------*/
void JSONSampler::MemoryIOStreamingSample(void)
{
const char* json = R"({"name":"value"})";
Document doc;
//このifの分岐は、どちらも同じ意味。メモリからDOMへ渡して構文解析する
#if 0
//メモリへの読み込み
StringStream rs(json);
doc.ParseStream(rs); //メモリからDOMへパース
#else
doc.Parse(json); //メモリからDOMへ渡して構文解析
#endif // 0
// 書き込み処理
StringBuffer ws;
Writer<StringBuffer> writer(ws); //バッファを登録
doc.Accept(writer);//DOMからバッファへ転送
const char* result = ws.GetString(); //出力
printf("%s\n", result);
}
/*-----------------------------------------------------------------------------
/* サンプル関数_ファイルからの入出力ストリーミング
-----------------------------------------------------------------------------*/
void JSONSampler::FileIOStreamingSample(void)
{
FILE* fp;
char buf[512];
Document doc;
// 読み込み
fp = fopen("json.txt", "rb");
FileReadStream rs(fp, buf, sizeof(buf)); //読み込み専用
doc.ParseStream(rs);
fclose(fp);
// 書き込み
fp = fopen("tmp.txt", "wb");
FileWriteStream ws(fp, buf, sizeof(buf)); //書き込み専用
#if 2
Writer<FileWriteStream> writer(ws); //インデントなし
#else
PrettyWriter<FileWriteStream> writer(ws); //インデントあり
#endif // 0
doc.Accept(writer);
fclose(fp);
}
/*-----------------------------------------------------------------------------
/* サンプル関数_構文解析エラーコード
-----------------------------------------------------------------------------*/
void JSONSampler::ParseErrorSample(void)
{
#if 1
const char* json = R"({"name":value})"; // 不正な(構文)文字列
#else
const char* json = R"({"name":"value"})"; // 有効な(構文)文字列
#endif // 0
Document doc;
doc.Parse(json);
bool error = doc.HasParseError();
if (error) {
size_t offset = doc.GetErrorOffset();
ParseErrorCode code = doc.GetParseError();
const char* msg = GetParseError_En(code);
printf("%d:%d(%s)\n", offset, code, msg);
}
}
/*-----------------------------------------------------------------------------
/* サンプル関数_Objectの生成処理
-----------------------------------------------------------------------------*/
void JSONSampler::GenerateObjectSample(void)
{
//DOMのRootの生成は、Document型を宣言、
//コンストラクタ(kObjectType)か,メンバ関数SetObject()で
//RootがObject型であることを指定する。
//DOMのRootを生成
Document doc(kObjectType);
//doc.SetObject();
assert(doc.IsObject()); //DOMのRootがObject型であることの確認。
//objectの生成について
//Object型の生成は、Value型を宣言、
//コンストラクタ(kObjectType)か,メンバ関数SetObject()で
//Object型を指定することによって、ObjectのRootを生成する
Value object(kObjectType);
//object.SetObject();
assert(object.IsObject()); //宣言したobjectか調べる。Object型以外なら警告を吐く
//objectにメンバの追加
{
//objectにメンバの要素を追加
object.AddMember("string", Value("dog"), doc.GetAllocator());
object.AddMember("int", Value(456), doc.GetAllocator());
object.AddMember("float", Value(0.1234), doc.GetAllocator());
//上記のObject型の出力データ(例
//{
// "object" : {
// "string" : "dog",
// "int" : 456,
// "flaot" : 0.1234
// }
//}
#if 0 //要素への削除か参照か?
//要素の削除について
{
object.AddMember("remove", Value("removable"), doc.GetAllocator());
const int remove_test_num = 0;
if (remove_test_num == 0)
{
//単純に消す
object.RemoveMember("remove");
}
else if (remove_test_num == 1)
{
//データの中から探し出して削除する
Value::MemberIterator itr = object.FindMember("remove");
if (itr != object.MemberEnd()) {
object.RemoveMember(itr);
//or obj.EraseMember(itr);
}
}
else if (remove_test_num == 2)
{
//要素をすべて消す
object.RemoveAllMembers();
object.AddMember("empty", Value("empty"), doc.GetAllocator()); //空を示す要素を挿入
}
}
#else
//参照の仕方(DOMの参照も同じようにできる)
{
//DOMの場合は、
//1.単体での参照
const Value& value_1 = object["string"]; //"object"の中のメンバ"string"を参照
printf("1.%s\n", value_1.GetString());
//2."object"の中にメンバ"int"があるか確認
bool exist = object.HasMember("int"); //メンバの存在を確認
if (exist) {
const Value& value_2 = object["int"];
// ...
printf("2.%d\n", value_2.GetInt());
}
//3.(2.の処理を簡潔に)イテレータを用いたメンバの参照
Value::ConstMemberIterator itr = object.FindMember("float");
if (itr != object.MemberEnd()) {
const Value& n = itr->name;
const Value& v = itr->value;
printf("3.%s,%f\n", n.GetString(), v.GetFloat());
}
}
#endif
}
//要素の置き換え
object.AddMember("hoge", Value("hoge"), doc.GetAllocator());
if (true)
{
object["hoge"] = Value("foo");
}
//DOMのRootにobjectを要素として追加
doc.AddMember("object", object, doc.GetAllocator());
// 書き込み処理
{
StringBuffer ws;
PrettyWriter<StringBuffer> writer(ws); //書式を指定し、バッファを登録
doc.Accept(writer); //DOMからバッファへ転送
const char* result = ws.GetString(); //出力
printf("%s\n", result);
}
}
/*-----------------------------------------------------------------------------
/* サンプル関数_Arrayの生成処理
-----------------------------------------------------------------------------*/
void JSONSampler::GenerateArraySample(void)
{
//DOMのRootを生成
Document doc(kObjectType);
//doc.SetObject();
assert(doc.IsObject());
//Arrayの生成について
Value obj_array(kArrayType); //コンストラクタかメンバ関数でkArrayTypeを指定
//obj_array.SetArray();
assert(obj_array.IsArray()); //kArrayTypeか調べる。Array型以外なら警告を吐く
//要素の追加と削除
for (int i = 0; i < 3; i++)
{
obj_array.PushBack(Value(i), doc.GetAllocator());
}
obj_array.PopBack();
//参照
assert(obj_array.Size() == 2);
assert(obj_array[SizeType(0)] == 0);
assert(obj_array[SizeType(1)] == 1);
//置き換え
obj_array[SizeType(0)] = 1;
//全削除
if (false)
{
obj_array.Clear();
}
//要素の置き換え
doc.AddMember("array", obj_array, doc.GetAllocator());
// 書き込み処理
{
StringBuffer ws;
PrettyWriter<StringBuffer> writer(ws); //書式を指定し、バッファを登録
doc.Accept(writer); //DOMからバッファへ転送
const char* result = ws.GetString(); //出力
printf("%s\n", result);
}
}
/*-----------------------------------------------------------------------------
/* サンプル関数_Numberの生成処理
-----------------------------------------------------------------------------*/
void JSONSampler::GenerateNumberSample(void)
{
//DOMのRootを生成
Document doc(kObjectType);
//doc.SetObject();
assert(doc.IsObject());
//Numberの生成について
//コンストラクタかメンバ関数でSet**()を使用
Value obj_number1(1); // int
Value obj_number2(0.2f); // float
Value obj_number3(0.3); // double
Value obj_number4(4U); // unsigned int
Value obj_number5(5LL); // 64bit_int
Value obj_number6(6LLU); // unsigned 64bit_int
Value obj_number7(true); // bool
//obj_number1.SetInt(1); // int
//obj_number2.SetFloat(0.2f); // float
//obj_number3.SetDouble(0.3); // double
//obj_number4.SetUint(4U); // unsigned int
//obj_number5.SetInt64(5LL); // 64bit_int
//obj_number6.SetUint64(6LLU); // unsigned 64bit_int
//obj_number7.SetBool(true); // bool
//参照
assert(obj_number1.GetInt() == 1);
assert(obj_number2.GetFloat() == 0.2f); // GetDouble()でも警告されない
assert(obj_number3.GetDouble() == 0.3); // GetFloat()でも警告されない
assert(obj_number4.GetUint() == 4U);
assert(obj_number5.GetInt64() == 5LL);
assert(obj_number6.GetUint64() == 6LLU);
assert(obj_number7.GetBool() == true);
//DOMのRootに要素を追加
doc.AddMember("number1", obj_number1, doc.GetAllocator());
doc.AddMember("number2", obj_number2, doc.GetAllocator());
doc.AddMember("number3", obj_number3, doc.GetAllocator());
doc.AddMember("number4", obj_number4, doc.GetAllocator());
doc.AddMember("number5", obj_number5, doc.GetAllocator());
doc.AddMember("number6", obj_number6, doc.GetAllocator());
doc.AddMember("number7", obj_number7, doc.GetAllocator());
// 書き込み処理
{
StringBuffer ws;
PrettyWriter<StringBuffer> writer(ws); //書式を指定し、バッファを登録
doc.Accept(writer); //DOMからバッファへ転送
const char* result = ws.GetString(); //出力
printf("%s\n", result);
}
}
/*-----------------------------------------------------------------------------
/* サンプル関数_Stringの生成処理
-----------------------------------------------------------------------------*/
void JSONSampler::GenerateStringSample(void)
{
//DOMのRootを生成
Document doc(kObjectType);
//doc.SetObject();
assert(doc.IsObject());
//Stringの生成について
//コンストラクタかメンバ関数で文字列を指定
Value obj_string1("hoge");
// obj_string.SetString("hoge");
assert(obj_string1.IsString()); //stringか調べる。string型以外なら警告を吐く
//stringの複製
Value obj_string2;
{
char buf[16];
sprintf(buf, "%s-%s", "copy", "string");
obj_string2.SetString(buf, doc.GetAllocator());// copy-string
const char* result = obj_string2.GetString(); //出力
printf("%s\n", result);
}
//ポインタへの参照
const char* a = obj_string2.GetString();
assert(obj_string2 == "copy-string");
printf("%s\n", a);
//要素の置き換え
doc.AddMember("string1", obj_string1, doc.GetAllocator());
doc.AddMember("string2", obj_string2, doc.GetAllocator());
// 書き込み処理
{
StringBuffer ws;
PrettyWriter<StringBuffer> writer(ws); //書式を指定し、バッファを登録
doc.Accept(writer); //DOMからバッファへ転送
const char* result = ws.GetString(); //出力
printf("%s\n", result);
}
}
/*=============================================================================
/* End of File
=============================================================================*/
|
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
OpenGLViewport.cpp: OpenGL viewport RHI implementation.
=============================================================================*/
#include "OpenGLDrvPrivate.h"
#include <algorithm>
/*=============================================================================
* The following RHI functions must be called from the main thread.
*=============================================================================*/
FViewportRHIRef FOpenGLDynamicRHI::RHICreateViewport(void* WindowHandle,uint32 SizeX,uint32 SizeY,bool bIsFullscreen,EPixelFormat PreferredPixelFormat)
{
// Use a default pixel format if none was specified
if (PreferredPixelFormat == EPixelFormat::PF_Unknown)
{
PreferredPixelFormat = EPixelFormat::PF_B8G8R8A8;
}
return FViewportRHIRef(new FOpenGLViewport(this,WindowHandle,SizeX,SizeY,bIsFullscreen,PreferredPixelFormat));
}
void FOpenGLDynamicRHI::RHIResizeViewport(FViewportRHIParamRef ViewportRHI,uint32 SizeX,uint32 SizeY,bool bIsFullscreen)
{
FOpenGLViewport* Viewport = ResourceCast(ViewportRHI);
Viewport->Resize(SizeX,SizeY,bIsFullscreen);
}
FOpenGLViewport::FOpenGLViewport(FOpenGLDynamicRHI* InOpenGLRHI,void* InWindowHandle,uint32 InSizeX,uint32 InSizeY,bool bInIsFullscreen,EPixelFormat PreferredPixelFormat)
: OpenGLRHI(InOpenGLRHI)
, OpenGLContext(NULL)
, SizeX(0)
, SizeY(0)
, bIsFullscreen(false)
, PixelFormat(PreferredPixelFormat)
, bIsValid(true)
, FrameSyncEvent(InOpenGLRHI)
{
OpenGLRHI->Viewports.push_back(this);
OpenGLContext = PlatformCreateOpenGLContext(OpenGLRHI->PlatformDevice, InWindowHandle);
Resize(InSizeX, InSizeY, bInIsFullscreen);
}
FOpenGLViewport::~FOpenGLViewport()
{
if (bIsFullscreen)
{
PlatformRestoreDesktopDisplayMode();
}
// Release back buffer, before OpenGL context becomes invalid, making it impossible
BackBuffer.SafeRelease();
PlatformDestroyOpenGLContext(OpenGLRHI->PlatformDevice,OpenGLContext);
OpenGLContext = NULL;
std::remove(OpenGLRHI->Viewports.begin(), OpenGLRHI->Viewports.end(), this);
}
void FOpenGLViewport::Resize(uint32 InSizeX,uint32 InSizeY,bool bInIsFullscreen)
{
if ((InSizeX == SizeX) && (InSizeY == SizeY) && (bInIsFullscreen == bIsFullscreen))
{
return;
}
VERIFY_GL_SCOPE();
////if (IsValidRef(CustomPresent))
////{
//// CustomPresent->OnBackBufferResize();
////}
//BackBuffer.SafeRelease(); // when the rest of the engine releases it, its framebuffers will be released too (those the engine knows about)
//BackBuffer = (FOpenGLTexture2D*)PlatformCreateBuiltinBackBuffer(OpenGLRHI, InSizeX, InSizeY);
//if (!BackBuffer)
//{
// BackBuffer = (FOpenGLTexture2D*)OpenGLRHI->CreateOpenGLTexture(InSizeX, InSizeY, false, false, PixelFormat, 1, 1, 1, TexCreate_RenderTargetable, FClearValueBinding::Transparent);
//}
PlatformResizeGLContext(OpenGLRHI->PlatformDevice, OpenGLContext, InSizeX, InSizeY, bInIsFullscreen, bIsFullscreen, BackBuffer->Target, BackBuffer->Resource);
SizeX = InSizeX;
SizeY = InSizeY;
bIsFullscreen = bInIsFullscreen;
}
void* FOpenGLViewport::GetNativeWindow(void** AddParam) const
{
return PlatformGetWindow(OpenGLContext, AddParam);
}
|
/** This file is a linked list implementation. I hate implementing linked lists
* by hand. Especialy tough was the part about erasing by "running number" id.
* @author Daniel "3ICE" Berezvai
* @student_id 262849
* @email daniel.berezvai@student.tut.fi
*/
#include "queue.hh"
#include <iostream>
#include <string>
using namespace std;
//3ICE: "Constructor?" "Yes, hello, this is Constructor."
Queue::Queue(): fst(nullptr), lst(nullptr){}
//3ICE: Had issues with destructor randomly being called on objects I still
//3ICE: needed. Out of scope problem or something. I messed up operator[] bad.
Queue::~Queue(){
//cout<<"deleting queue:"<<endl;
Cell* p;
while(fst != nullptr){
p = fst;
fst = fst->nxt;
//cout<<" deleting item "<<p->name<<endl;
delete p;
}
}
// empty will only return true, if there are no elements
// in the queue i.e. the linked list is empty.
bool Queue::empty() const{
return fst == nullptr;
}
//3ICE: Specialized print function with the fancy two spaces in front.
int Queue::print(int continue_from) const {
Cell* p = fst;
while(p != nullptr){
cout << " " << continue_from << ". " << p->name << endl;
++continue_from;
p = p->nxt;
}
return continue_from;
}
//3ICE: Point of inefficiency (Have to recount each time we erase)
int Queue::count() const {
Cell* p = fst;
int counter = 0;
while(p != nullptr){
++counter;
p = p->nxt;
}
return counter;
}
//3ICE: Standard push_back method, I think.
void Queue::push_back(const string& name){
Cell* p(new Cell);
p->name = name;
p->nxt = nullptr;
if(fst == nullptr){
fst = p;
lst = p;
} else {
lst->nxt = p;
lst = p;
}
}
//3ICE: Standard pop_front as well.
bool Queue::pop_front(string& name) {
if(empty()){
return false;
}
Cell *p = fst;
name = p->name;
if(fst == lst){
fst = nullptr;
lst = nullptr;
} else {
fst = fst->nxt;
}
delete p;
return true;
}
//3ICE: Now this erase is anything but standard. And is done in two steps.
//3ICE: Number of debug prints directly correlates to how much trouble I had
//with this function. Especially that OOPS! - I was erasing from the wrong list
bool Queue::erase(int id){
//cout<<" Deleting #"<<id<<endl;
if(fst == nullptr || id < 0){
return false;
}
if(id == 0){
//cout<<" Deleting first is special case"<<endl;
Cell* p = fst;
if(fst == lst){
fst = nullptr;
lst = nullptr;
} else {
fst = fst->nxt;
}
delete p;
return true;
}
//cout<<" Fast forwarding to #"<<id-1<<endl;
Cell* p = fst;
int counter = 1;
//cout<<p<<" "<<p->name<<" "<<p->nxt<<endl;
//cout<<counter <<" "<< id<<endl;
while(counter < id){
//cout<<p<<" "<<p->name<<" "<<p->nxt<<endl;
if(p == lst){
//cout<<" OOPS!"<<endl;
return false;
}
p = p->nxt;
++counter;
//cout<<" "<<counter<<" "<<p->name<<endl;
}
// Here p points to the cell that is right in front of the id'th element.
Cell* q = p->nxt;
p->nxt = q->nxt;
if(lst == q){
//cout<<" Deleting last is special case, so updated lst"<<endl;
lst = p;
}
//cout<<" Deleting #"<<id<<": "<<q->name<<endl;
delete q;
return true;
}
|
// Created on: 1993-01-11
// Created by: CKY / Contract Toubro-Larsen ( Anand NATRAJAN )
// 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 _IGESAppli_ElementResults_HeaderFile
#define _IGESAppli_ElementResults_HeaderFile
#include <Standard.hxx>
#include <Standard_Integer.hxx>
#include <Standard_Real.hxx>
#include <TColStd_HArray1OfInteger.hxx>
#include <IGESAppli_HArray1OfFiniteElement.hxx>
#include <IGESData_IGESEntity.hxx>
#include <TColStd_HArray1OfReal.hxx>
class IGESDimen_GeneralNote;
class IGESBasic_HArray1OfHArray1OfInteger;
class IGESBasic_HArray1OfHArray1OfReal;
class IGESAppli_FiniteElement;
class IGESAppli_ElementResults;
DEFINE_STANDARD_HANDLE(IGESAppli_ElementResults, IGESData_IGESEntity)
//! defines ElementResults, Type <148>
//! in package IGESAppli
//! Used to find the results of FEM analysis
class IGESAppli_ElementResults : public IGESData_IGESEntity
{
public:
Standard_EXPORT IGESAppli_ElementResults();
//! This method is used to set the fields of the class
//! ElementResults
//! - aNote : GeneralNote Entity describing analysis
//! - aSubCase : Analysis Subcase number
//! - aTime : Analysis time value
//! - nbResults : Number of result values per FEM
//! - aResRepFlag : Results Reporting Flag
//! - allElementIdents : FEM element number for elements
//! - allFiniteElems : FEM element
//! - allTopTypes : Element Topology Types
//! - nbLayers : Number of layers per result data location
//! - allDataLayerFlags : Data Layer Flags
//! - allnbResDataLocs : Number of result data report locations
//! - allResDataLocs : Result Data Report Locations
//! - allResults : List of Result data values of FEM analysis
Standard_EXPORT void Init (const Handle(IGESDimen_GeneralNote)& aNote, const Standard_Integer aSubCase, const Standard_Real aTime, const Standard_Integer nbResults, const Standard_Integer aResRepFlag, const Handle(TColStd_HArray1OfInteger)& allElementIdents, const Handle(IGESAppli_HArray1OfFiniteElement)& allFiniteElems, const Handle(TColStd_HArray1OfInteger)& allTopTypes, const Handle(TColStd_HArray1OfInteger)& nbLayers, const Handle(TColStd_HArray1OfInteger)& allDataLayerFlags, const Handle(TColStd_HArray1OfInteger)& allnbResDataLocs, const Handle(IGESBasic_HArray1OfHArray1OfInteger)& allResDataLocs, const Handle(IGESBasic_HArray1OfHArray1OfReal)& allResults);
//! Changes the FormNumber (which indicates Type of Result)
//! Error if not in range [0-34]
Standard_EXPORT void SetFormNumber (const Standard_Integer form);
//! returns General Note Entity describing analysis case
Standard_EXPORT Handle(IGESDimen_GeneralNote) Note() const;
//! returns analysis Subcase number
Standard_EXPORT Standard_Integer SubCaseNumber() const;
//! returns analysis time value
Standard_EXPORT Standard_Real Time() const;
//! returns number of result values per FEM
Standard_EXPORT Standard_Integer NbResultValues() const;
//! returns Results Reporting Flag
Standard_EXPORT Standard_Integer ResultReportFlag() const;
//! returns number of FEM elements
Standard_EXPORT Standard_Integer NbElements() const;
//! returns FEM element number for elements
Standard_EXPORT Standard_Integer ElementIdentifier (const Standard_Integer Index) const;
//! returns FEM element
Standard_EXPORT Handle(IGESAppli_FiniteElement) Element (const Standard_Integer Index) const;
//! returns element Topology Types
Standard_EXPORT Standard_Integer ElementTopologyType (const Standard_Integer Index) const;
//! returns number of layers per result data location
Standard_EXPORT Standard_Integer NbLayers (const Standard_Integer Index) const;
//! returns Data Layer Flags
Standard_EXPORT Standard_Integer DataLayerFlag (const Standard_Integer Index) const;
//! returns number of result data report locations
Standard_EXPORT Standard_Integer NbResultDataLocs (const Standard_Integer Index) const;
//! returns Result Data Report Locations
//! UNFINISHED
Standard_EXPORT Standard_Integer ResultDataLoc (const Standard_Integer NElem, const Standard_Integer NLoc) const;
//! returns total number of results
Standard_EXPORT Standard_Integer NbResults (const Standard_Integer Index) const;
//! returns Result data value for an Element, given its
//! order between 1 and <NbResults(NElem)> (direct access)
//! For a more comprehensive access, see below
Standard_EXPORT Standard_Real ResultData (const Standard_Integer NElem, const Standard_Integer num) const;
//! Computes, for a given Element <NElem>, the rank of a
//! individual Result Data, given <NVal>,<NLay>,<NLoc>
Standard_EXPORT Standard_Integer ResultRank (const Standard_Integer NElem, const Standard_Integer NVal, const Standard_Integer NLay, const Standard_Integer NLoc) const;
//! returns Result data values of FEM analysis, according this
//! definition :
//! - <NElem> : n0 of the Element to be considered
//! - <NVal> : n0 of the Value between 1 and NbResultValues
//! - <NLay> : n0 of the Layer for this Element
//! - <NLoc> : n0 of the Data Location for this Element
//! This gives for each Element, the corresponding rank
//! computed by ResultRank, in which the leftmost subscript
//! changes most rapidly
Standard_EXPORT Standard_Real ResultData (const Standard_Integer NElem, const Standard_Integer NVal, const Standard_Integer NLay, const Standard_Integer NLoc) const;
//! Returns in once the entire list of data for an Element,
//! addressed as by ResultRank (See above)
Standard_EXPORT Handle(TColStd_HArray1OfReal) ResultList (const Standard_Integer NElem) const;
DEFINE_STANDARD_RTTIEXT(IGESAppli_ElementResults,IGESData_IGESEntity)
protected:
private:
Handle(IGESDimen_GeneralNote) theNote;
Standard_Integer theSubcaseNumber;
Standard_Real theTime;
Standard_Integer theNbResultValues;
Standard_Integer theResultReportFlag;
Handle(TColStd_HArray1OfInteger) theElementIdentifiers;
Handle(IGESAppli_HArray1OfFiniteElement) theElements;
Handle(TColStd_HArray1OfInteger) theElementTopologyTypes;
Handle(TColStd_HArray1OfInteger) theNbLayers;
Handle(TColStd_HArray1OfInteger) theDataLayerFlags;
Handle(TColStd_HArray1OfInteger) theNbResultDataLocs;
Handle(IGESBasic_HArray1OfHArray1OfInteger) theResultDataLocs;
Handle(IGESBasic_HArray1OfHArray1OfReal) theResultData;
};
#endif // _IGESAppli_ElementResults_HeaderFile
|
// Created on: 1996-01-30
// Created by: Jacques GOUSSARD
// Copyright (c) 1996-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 _LocOpe_GluedShape_HeaderFile
#define _LocOpe_GluedShape_HeaderFile
#include <Standard.hxx>
#include <TopTools_MapOfShape.hxx>
#include <TopTools_DataMapOfShapeShape.hxx>
#include <LocOpe_GeneratedShape.hxx>
#include <TopTools_ListOfShape.hxx>
class TopoDS_Face;
class TopoDS_Edge;
class TopoDS_Vertex;
class LocOpe_GluedShape;
DEFINE_STANDARD_HANDLE(LocOpe_GluedShape, LocOpe_GeneratedShape)
class LocOpe_GluedShape : public LocOpe_GeneratedShape
{
public:
Standard_EXPORT LocOpe_GluedShape();
Standard_EXPORT LocOpe_GluedShape(const TopoDS_Shape& S);
Standard_EXPORT void Init (const TopoDS_Shape& S);
Standard_EXPORT void GlueOnFace (const TopoDS_Face& F);
Standard_EXPORT const TopTools_ListOfShape& GeneratingEdges() Standard_OVERRIDE;
//! Returns the edge created by the vertex <V>. If
//! none, must return a null shape.
Standard_EXPORT TopoDS_Edge Generated (const TopoDS_Vertex& V) Standard_OVERRIDE;
//! Returns the face created by the edge <E>. If none,
//! must return a null shape.
Standard_EXPORT TopoDS_Face Generated (const TopoDS_Edge& E) Standard_OVERRIDE;
//! Returns the list of correctly oriented generated
//! faces.
Standard_EXPORT const TopTools_ListOfShape& OrientedFaces() Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(LocOpe_GluedShape,LocOpe_GeneratedShape)
protected:
private:
Standard_EXPORT void MapEdgeAndVertices();
TopoDS_Shape myShape;
TopTools_MapOfShape myMap;
TopTools_DataMapOfShapeShape myGShape;
};
#endif // _LocOpe_GluedShape_HeaderFile
|
// boundary_flip.h
// Ben Gamari
// August 2009
#ifndef _BOUNDARY_FLIP_H
#define _BOUDNARY_FLIP_H
#include <cpu_vector.h>
namespace qcd {
void apply_boundary(su3_field &links, int bc[4]);
} // qcd namespace
#endif
|
#ifndef _TOWN_
#define _TOWN_
/*----------------------------------------------------------
Handles the info of town. A town is made up of
5 horizontal acres by 4 vertical acres.
Each acre is is 16 by 16 units. An array of characters is
used to keep track of what is stored where.
----------------------------------------------------------*/
class Entity;
//Definitions
#define TILES 16 //number of tiles in an acre
#define H_ACRE 5 * TILES//number of horizontal acres
#define V_ACRE 4 * TILES//number of vertical arces
#define MAPFILESIZE 5184 //number of bytes that the map file should be
//Includes
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
#include "entities.h"
#include "read_data.h"
class Town {
private:
char** map;
std::vector<Entity*> entity_list;
int pwps;
public:
/*----------------------------------------------------------
If given a char value the constructor will initialize
the map array to the char, otherwise set to 'G'
----------------------------------------------------------*/
Town(char type = 'G');
~Town();
/*----------------------------------------------------------
Returns the array of characters of the map
----------------------------------------------------------*/
char*** get_map_array();
/*----------------------------------------------------------
Sets a field on the map array.
Returns 1 if the field could not be set.
----------------------------------------------------------*/
int set_map_value(int h_location, int v_location, char value);
/*----------------------------------------------------------
Returns the value at a location. Returns '\0' if
location is not valid
----------------------------------------------------------*/
char get_map_value(int h_location, int v_location);
/*----------------------------------------------------------
Returns the number of tiles have a matching value; used
to count quantity of a type
----------------------------------------------------------*/
int count_value(char type);
/*----------------------------------------------------------
saves the map to a specified file location.
----------------------------------------------------------*/
int save_map(std::string file);
/*----------------------------------------------------------
loads the map from a specified file location.
----------------------------------------------------------*/
int load_map(std::string file, std::map <QString, Entity*> *feature_list);
/*----------------------------------------------------------
Returns the map in a string format, useful for debug
----------------------------------------------------------*/
std::string* get_map_string();
/*----------------------------------------------------------
Adds an entity to the list of entitys
----------------------------------------------------------*/
void add_entity(Entity* entity);
/*----------------------------------------------------------
Returns the entity list
----------------------------------------------------------*/
std::vector<Entity*> *get_entity_list();
void pwp_count_set(int num);
void pwp_count_add(int increment);
int get_pwp_count();
Entity* find_entity(int x, int y, int radius);
};
#endif
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
struct edge{
int to;
ll cost;
};
bool visit[100005];
bool ans[100005];
vector<vector<edge>> G(100005);
void dfs(int v, ll w){
if(w%2 == 0) ans[v] = true;
visit[v] = true;
for(int i=0; i<G[v].size(); i++){
auto v_to = G[v][i];
if(visit[v_to.to] == false){
dfs(v_to.to, w + v_to.cost);
}
}
return;
}
int main(){
int n;
cin >> n;
for(int i=0; i<n-1; i++){
int u, v;
ll w;
cin >> u >> v >> w;
G[u].push_back(edge{v, w});
G[v].push_back(edge{u, w});
}
dfs(1, 0);
for(int i=1; i<=n; i++) cout << ans[i] << endl;
return 0;
}
|
// SDDLViewerDlg.cpp : implementation file
//
#include "Stdafx.h"
#include "SDDLViewer.h"
#include "SDDLViewerDlg.h"
#pragma comment(lib, "Version.lib")
#pragma comment(lib, "Aclui.lib")
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
BOOL OnInitDialog() {
CDialog::OnInitDialog();
CString strVer = _T("?");
{
HMODULE hMod = AfxGetResourceHandle();
HRSRC hVeri = FindResource(hMod, MAKEINTRESOURCE(VS_VERSION_INFO), RT_VERSION);
PVOID pvVeri = LockResource(LoadResource(hMod, hVeri));
DWORD cbVeri = SizeofResource(hMod, hVeri);
if (pvVeri != NULL && cbVeri != 0) {
VS_FIXEDFILEINFO *pffi = NULL;
UINT cb = 0;
if (VerQueryValue(pvVeri, _T("\\"), reinterpret_cast<LPVOID *>(&pffi), &cb)) {
if (pffi->dwSignature == 0xFEEF04BD) {
strVer.Format(_T("%u.%u.%u.%u")
, 0U +(WORD)(pffi->dwFileVersionMS >> 16)
, 0U +(WORD)(pffi->dwFileVersionMS >> 0)
, 0U +(WORD)(pffi->dwFileVersionLS >> 16)
, 0U +(WORD)(pffi->dwFileVersionLS >> 0)
);
}
}
}
}
{
CString text;
m_wndVer.GetWindowText(text);
text.Replace(_T("1.0"), strVer);
m_wndVer.SetWindowText(text);
}
return true;
}
protected:
DECLARE_MESSAGE_MAP()
public:
CStatic m_wndVer;
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_VER, m_wndVer);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
// CvDlg dialog
CvDlg::CvDlg(CWnd* pParent /*=NULL*/)
: CDialog(CvDlg::IDD, pParent)
, m_strSDDL(_T(""))
, m_objName(_T("npf"))
, m_dacl(true)
, m_sacl(FALSE)
, m_owner(FALSE)
, m_group(FALSE)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CvDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT_SDDL, m_strSDDL);
DDX_Control(pDX, IDC_SE, m_wndSe);
DDX_Text(pDX, IDC_OBJNAME, m_objName);
DDX_Check(pDX, IDC_DACL, m_dacl);
DDX_Check(pDX, IDC_SACL, m_sacl);
DDX_Check(pDX, IDC_OWNER, m_owner);
DDX_Check(pDX, IDC_GROUP, m_group);
}
BEGIN_MESSAGE_MAP(CvDlg, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
ON_BN_CLICKED(IDC_PASTE, &CvDlg::OnBnClickedPaste)
ON_BN_CLICKED(IDC_VIEW, &CvDlg::OnBnClickedView)
ON_BN_CLICKED(IDC_GET, &CvDlg::OnBnClickedGet)
ON_BN_CLICKED(IDC_COPY, &CvDlg::OnBnClickedCopy)
ON_BN_CLICKED(IDC_EDIT, &CvDlg::OnBnClickedEdit)
END_MESSAGE_MAP()
// CvDlg message handlers
BOOL CvDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
m_wndSe.SetItemData(m_wndSe.AddString(_T("FILE_OBJECT")), SE_FILE_OBJECT);
m_wndSe.SetItemData(m_wndSe.AddString(_T("SERVICE")), SE_SERVICE);
m_wndSe.SetItemData(m_wndSe.AddString(_T("PRINTER")), SE_PRINTER);
m_wndSe.SetItemData(m_wndSe.AddString(_T("REGISTRY_KEY")), SE_REGISTRY_KEY);
m_wndSe.SetItemData(m_wndSe.AddString(_T("LMSHARE")), SE_LMSHARE);
m_wndSe.SetItemData(m_wndSe.AddString(_T("KERNEL_OBJECT")), SE_KERNEL_OBJECT);
m_wndSe.SetItemData(m_wndSe.AddString(_T("WINDOW_OBJECT")), SE_WINDOW_OBJECT);
m_wndSe.SetItemData(m_wndSe.AddString(_T("DS_OBJECT")), SE_DS_OBJECT);
m_wndSe.SetItemData(m_wndSe.AddString(_T("DS_OBJECT_ALL")), SE_DS_OBJECT_ALL);
m_wndSe.SetItemData(m_wndSe.AddString(_T("PROVIDER_DEFINED_OBJECT")), SE_PROVIDER_DEFINED_OBJECT);
m_wndSe.SetItemData(m_wndSe.AddString(_T("WMIGUID_OBJECT")), SE_WMIGUID_OBJECT);
m_wndSe.SetItemData(m_wndSe.AddString(_T("REGISTRY_WOW64_32KEY")), SE_REGISTRY_WOW64_32KEY);
m_wndSe.SetCurSel(m_wndSe.FindString(-1, _T("SERVICE")));
UpdateData(false);
return TRUE; // return TRUE unless you set the focus to a control
}
void CvDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CvDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CvDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
class GMUt {
public:
static HGLOBAL Cap(LPCSTR psz) {
UINT cb = sizeof(char) * (strlen(psz) + 1);
HGLOBAL hMem = GlobalAlloc(GHND, cb);
if (hMem != NULL) {
PVOID pv = GlobalLock(hMem);
strcpy(reinterpret_cast<LPSTR>(pv), psz);
GlobalUnlock(hMem);
}
return hMem;
}
};
void CvDlg::OnBnClickedCopy() {
if (!UpdateData())
return;
if (OpenClipboard()) {
EmptyClipboard();
SetClipboardData(CF_TEXT, GMUt::Cap(CT2A(m_strSDDL)));
CloseClipboard();
}
}
void CvDlg::OnBnClickedPaste() {
if (!UpdateData())
return;
if (OpenClipboard()) {
HGLOBAL hMem = GetClipboardData(CF_TEXT);
LPVOID pv = GlobalLock(hMem);
if (pv != NULL) {
m_strSDDL = reinterpret_cast<LPCSTR>(pv);
GlobalUnlock(pv);
}
CloseClipboard();
UpdateData(false);
}
}
#define MAX_ACC 100U
class SUt {
public:
static BOOL ConvertSecurityDescriptorToStringSecurityDescriptor2(
PSECURITY_DESCRIPTOR SecurityDescriptor,
DWORD RequestedStringSDRevision,
SECURITY_INFORMATION SecurityInformation,
CString &StringSecurityDescriptor
) {
LPWSTR pcw = NULL;
if (ConvertSecurityDescriptorToStringSecurityDescriptor(SecurityDescriptor, RequestedStringSDRevision, SecurityInformation, &pcw, NULL)) {
StringSecurityDescriptor = pcw;
ATLVERIFY(NULL == LocalFree(pcw));
return true;
}
return false;
}
};
class CEaseSiAccess {
public:
CAtlArray<SI_ACCESS> m_access;
CAtlArray<CStringW> m_names;
void Add(ACCESS_MASK mask, CStringW name, DWORD flags) {
m_names.Add(name);
SI_ACCESS si;
si.pguid = NULL;
si.mask = mask;
si.pszName = const_cast<LPWSTR>(static_cast<LPCWSTR>(name));
si.dwFlags = flags;
m_access.Add(si);
}
};
class CSettype {
public:
CEaseSiAccess m_accEasy;
void SettypeKey() {
SetObjecttype(L"Key");
m_accEasy.Add(FILE_GENERIC_READ, L"Generic Read", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_GENERIC_WRITE , L"Generic Write", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_GENERIC_EXECUTE, L"Generic Execute", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(STANDARD_RIGHTS_ALL, L"Standard Rights All", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(READ_CONTROL, L"Read Control", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(WRITE_DAC, L"Write DAC", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(WRITE_OWNER, L"Write Owner", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SYNCHRONIZE, L"Synchronize", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(KEY_ALL_ACCESS, L"All Access", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(KEY_CREATE_LINK, L"Create Link", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(KEY_CREATE_SUB_KEY, L"Create Subkey", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(KEY_ENUMERATE_SUB_KEYS, L"Enum Subkeys", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(KEY_EXECUTE, L"Execute", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(KEY_NOTIFY, L"Notify", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(KEY_QUERY_VALUE, L"Query Value", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(KEY_READ, L"Read", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(KEY_SET_VALUE, L"Set Value", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(KEY_WOW64_32KEY, L"WOW64 32Key", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(KEY_WOW64_64KEY, L"WOW64 64Key", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(KEY_WRITE, L"Write", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
}
void SettypeFile() {
SetObjecttype(L"File");
m_accEasy.Add(FILE_GENERIC_READ, L"Generic Read", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_GENERIC_WRITE , L"Generic Write", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_GENERIC_EXECUTE, L"Generic Execute", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(STANDARD_RIGHTS_ALL, L"Standard Rights All", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(READ_CONTROL, L"Read Control", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(WRITE_DAC, L"Write DAC", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(WRITE_OWNER, L"Write Owner", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SYNCHRONIZE, L"Synchronize", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_ALL_ACCESS, L"All Access", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_READ_DATA, L"Read Data; List Directory", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_WRITE_DATA, L"Write Data; Add File", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_APPEND_DATA, L"Append Data; Add Subdir", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_READ_EA, L"Read EA", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_WRITE_EA, L"Write EA", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_EXECUTE, L"Execute", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_TRAVERSE, L"Traverse", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_DELETE_CHILD, L"Delete Child", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_READ_ATTRIBUTES, L"Read Atts", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(FILE_WRITE_ATTRIBUTES, L"Write Atts", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
}
void SettypeService() {
SetObjecttype(L"Service");
m_accEasy.Add(STANDARD_RIGHTS_READ|SERVICE_QUERY_CONFIG|SERVICE_QUERY_STATUS|SERVICE_INTERROGATE|SERVICE_ENUMERATE_DEPENDENTS,
L"Generic Read", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(STANDARD_RIGHTS_WRITE|SERVICE_CHANGE_CONFIG,
L"Generic Write", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(STANDARD_RIGHTS_EXECUTE|SERVICE_START|SERVICE_STOP|SERVICE_PAUSE_CONTINUE|SERVICE_USER_DEFINED_CONTROL,
L"Generic Execute", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(STANDARD_RIGHTS_ALL, L"Standard Rights All", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(READ_CONTROL, L"Read Control", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(WRITE_DAC, L"Write DAC", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(WRITE_OWNER, L"Write Owner", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SYNCHRONIZE, L"Synchronize", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SERVICE_ALL_ACCESS, L"All Access", SI_ACCESS_GENERAL|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SERVICE_QUERY_CONFIG, L"Query Config", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SERVICE_CHANGE_CONFIG, L"Change Config", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SERVICE_QUERY_STATUS, L"Query Status", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SERVICE_ENUMERATE_DEPENDENTS, L"Enumerate Dependents", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SERVICE_START, L"Start", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SERVICE_STOP, L"Stop", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SERVICE_PAUSE_CONTINUE, L"Pause Continue", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SERVICE_INTERROGATE, L"Interrogate", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SERVICE_USER_DEFINED_CONTROL, L"User Defined Control", 0|SI_ACCESS_SPECIFIC);
m_accEasy.Add(SERVICE_START|SERVICE_STOP|SERVICE_PAUSE_CONTINUE|SERVICE_USER_DEFINED_CONTROL, L"Control (Start, stop, etc)", SI_ACCESS_GENERAL);
}
virtual void SetObjecttype(LPCWSTR pcw) PURE;
};
class CSI : public CSettype, public ISecurityInformation {
public:
ULONG m_life;
CStringW m_strObjectName;
CSI(): m_life(0) { }
virtual void SetObjecttype(LPCWSTR pcw) {
m_strObjectName = pcw;
}
// *** IUnknown methods ***
STDMETHOD(QueryInterface) (THIS_ REFIID riid, LPVOID * ppvObj) {
if (ppvObj == NULL)
return E_POINTER;
*ppvObj = NULL;
if (riid == IID_ISecurityInformation || riid == IID_IUnknown) {
*ppvObj = static_cast<ISecurityInformation *>(this);
}
else {
return E_NOINTERFACE;
}
AddRef();
return S_OK;
}
STDMETHOD_(ULONG,AddRef) (THIS) {
return ++m_life;
}
STDMETHOD_(ULONG,Release) (THIS) {
ULONG c = --m_life;
if (c == 0) {
delete this;
}
return c;
}
// *** ISecurityInformation methods ***
STDMETHOD(GetObjectInformation) (THIS_ PSI_OBJECT_INFO pObjectInfo ) {
SI_OBJECT_INFO &r = *pObjectInfo;
ZeroMemory(&r, sizeof(r));
r.dwFlags = 0
|SI_EDIT_ALL
|SI_ADVANCED
|SI_EDIT_PROPERTIES
|SI_EDIT_EFFECTIVE
|SI_NO_TREE_APPLY
|SI_NO_ACL_PROTECT
;
r.hInstance = GetModuleHandle(NULL);
r.pszObjectName = const_cast<LPWSTR>(static_cast<LPCWSTR>(m_strObjectName));
return S_OK;
}
STDMETHOD(GetSecurity) (THIS_ SECURITY_INFORMATION RequestedInformation,
PSECURITY_DESCRIPTOR *ppSecurityDescriptor,
BOOL fDefault ) PURE;
STDMETHOD(SetSecurity) (THIS_ SECURITY_INFORMATION SecurityInformation,
PSECURITY_DESCRIPTOR pSecurityDescriptor ) PURE;
class DCUt {
public:
template<typename IT, typename OT>
static void PutValue(OT &rOut, const IT &rIn) {
rOut = (OT)rIn;
if (rOut != rIn) throw std::domain_error("precision lost");
}
};
STDMETHOD(GetAccessRights) (THIS_ const GUID* pguidObjectType,
DWORD dwFlags, // SI_EDIT_AUDITS, SI_EDIT_PROPERTIES
PSI_ACCESS *ppAccess,
ULONG *pcAccesses,
ULONG *piDefaultAccess )
{
ATLASSERT(pguidObjectType == NULL || *pguidObjectType == GUID_NULL);
*ppAccess = m_accEasy.m_access.GetData();
DCUt::PutValue(*pcAccesses, m_accEasy.m_access.GetCount());
*piDefaultAccess = 0;
return S_OK;
}
STDMETHOD(MapGeneric) (THIS_ const GUID *pguidObjectType,
UCHAR *pAceFlags,
ACCESS_MASK *pMask)
{
return S_OK;
}
STDMETHOD(GetInheritTypes) (THIS_ PSI_INHERIT_TYPE *ppInheritTypes,
ULONG *pcInheritTypes )
{
if (ppInheritTypes == NULL || pcInheritTypes == NULL)
return E_POINTER;
*pcInheritTypes = 0;
return S_OK;
}
STDMETHOD(PropertySheetPageCallback)(THIS_ HWND hwnd, UINT uMsg, SI_PAGE_TYPE uPage )
{
return S_OK;
}
};
class CStrSI : public CSI {
public:
CString m_strSDDLOrg;
CString m_strSDDL;
CStrSI(CString strSDDL): m_strSDDLOrg(strSDDL), m_strSDDL(strSDDL) { }
STDMETHOD(GetSecurity) (THIS_ SECURITY_INFORMATION RequestedInformation,
PSECURITY_DESCRIPTOR *ppSecurityDescriptor,
BOOL fDefault )
{
if (ppSecurityDescriptor == NULL)
return E_POINTER;
if (ConvertStringSecurityDescriptorToSecurityDescriptor(
fDefault ? m_strSDDLOrg : m_strSDDL, SDDL_REVISION_1, ppSecurityDescriptor, NULL
)) {
return S_OK;
}
int errc = GetLastError();
return HRESULT_FROM_WIN32(errc);
}
STDMETHOD(SetSecurity) (THIS_ SECURITY_INFORMATION SecurityInformation,
PSECURITY_DESCRIPTOR pSecurityDescriptor )
{
PSECURITY_DESCRIPTOR pSdRel = NULL;
int errc = 0;
if (ConvertStringSecurityDescriptorToSecurityDescriptor(m_strSDDL, SDDL_REVISION_1, &pSdRel, NULL)) {
DWORD dwAbsoluteSDSize = 10000, dwDaclSize = 10000, dwSaclSize = 10000, dwOwnerSize = 10000, dwPrimaryGroupSize = 10000;
PSECURITY_DESCRIPTOR pSd = LocalAlloc(LPTR, 10000);
PACL pDacl = reinterpret_cast<PACL>(LocalAlloc(LPTR, 10000));
PACL pSacl = reinterpret_cast<PACL>(LocalAlloc(LPTR, 10000));
PSID pOwner = reinterpret_cast<PSID>(LocalAlloc(LPTR, 10000));
PSID pPrimaryGroup = reinterpret_cast<PSID>(LocalAlloc(LPTR, 10000));
SECURITY_INFORMATION fSi = 0;
if (MakeAbsoluteSD(pSdRel, pSd, &dwAbsoluteSDSize, pDacl, &dwDaclSize, pSacl, &dwSaclSize, pOwner, &dwOwnerSize, pPrimaryGroup, &dwPrimaryGroupSize)) {
if (SecurityInformation & OWNER_SECURITY_INFORMATION) {
PSID pOwner;
BOOL bDefaulted;
ATLVERIFY(GetSecurityDescriptorOwner(pSecurityDescriptor, &pOwner, &bDefaulted));
ATLVERIFY(SetSecurityDescriptorOwner(pSd, pOwner, bDefaulted));
}
if (SecurityInformation & GROUP_SECURITY_INFORMATION) {
PSID pGroup;
BOOL bDefaulted;
ATLVERIFY(GetSecurityDescriptorGroup(pSecurityDescriptor, &pGroup, &bDefaulted));
ATLVERIFY(SetSecurityDescriptorGroup(pSd, pGroup, bDefaulted));
}
if (SecurityInformation & DACL_SECURITY_INFORMATION) {
PACL pDacl;
BOOL bPresent, bDefaulted;
ATLVERIFY(GetSecurityDescriptorDacl(pSecurityDescriptor, &bPresent, &pDacl, &bDefaulted));
ATLVERIFY(SetSecurityDescriptorDacl(pSd, bPresent, pDacl, bDefaulted));
}
if (SecurityInformation & SACL_SECURITY_INFORMATION) {
PACL pSacl;
BOOL bPresent, bDefaulted;
ATLVERIFY(GetSecurityDescriptorSacl(pSecurityDescriptor, &bPresent, &pSacl, &bDefaulted));
ATLVERIFY(SetSecurityDescriptorSacl(pSd, bPresent, pSacl, bDefaulted));
}
LPWSTR pszSDDLNew = NULL;
if (ConvertSecurityDescriptorToStringSecurityDescriptor(
pSd, SDDL_REVISION_1, OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION|SACL_SECURITY_INFORMATION, &pszSDDLNew, NULL
)) {
m_strSDDL = pszSDDLNew;
LocalFree(pszSDDLNew);
ATLVERIFY(NULL == LocalFree(pSd));
ATLVERIFY(NULL == LocalFree(pDacl));
ATLVERIFY(NULL == LocalFree(pSacl));
ATLVERIFY(NULL == LocalFree(pOwner));
ATLVERIFY(NULL == LocalFree(pPrimaryGroup));
ATLVERIFY(NULL == LocalFree(pSdRel));
return S_OK;
}
else
errc = GetLastError();
}
ATLVERIFY(NULL == LocalFree(pSd));
ATLVERIFY(NULL == LocalFree(pDacl));
ATLVERIFY(NULL == LocalFree(pSacl));
ATLVERIFY(NULL == LocalFree(pOwner));
ATLVERIFY(NULL == LocalFree(pPrimaryGroup));
ATLVERIFY(NULL == LocalFree(pSdRel));
}
else
errc = GetLastError();
return HRESULT_FROM_WIN32(errc);
}
};
class CNamedSec {
public:
PSID psidOwner, psidGroup;
PACL pDacl, pSacl;
PSECURITY_DESCRIPTOR pSd;
CNamedSec() {
psidOwner = psidGroup = NULL;
pDacl = pSacl = NULL;
pSd = NULL;
}
~CNamedSec() {
Clear();
}
void Clear() {
ATLVERIFY(NULL == LocalFree(pSd));
psidOwner = psidGroup = NULL;
pDacl = pSacl = NULL;
pSd = NULL;
}
int Get(LPCTSTR psz, SE_OBJECT_TYPE se, SECURITY_INFORMATION sif) {
Clear();
return GetNamedSecurityInfo(psz, se, sif, &psidOwner, &psidGroup, &pDacl, &pSacl, &pSd);
}
PSECURITY_DESCRIPTOR Detach() {
PSECURITY_DESCRIPTOR p = pSd;
psidOwner = psidGroup = NULL;
pDacl = pSacl = NULL;
pSd = NULL;
return p;
}
};
class CNamedSI : public CSI {
public:
CString m_objName;
SE_OBJECT_TYPE m_se;
SECURITY_INFORMATION m_sif;
CNamedSI() { }
STDMETHOD(GetSecurity) (THIS_ SECURITY_INFORMATION RequestedInformation,
PSECURITY_DESCRIPTOR *ppSecurityDescriptor,
BOOL fDefault )
{
if (ppSecurityDescriptor == NULL)
return E_POINTER;
CNamedSec sec;
int errc;
if (0 != (errc = sec.Get(m_objName, m_se, RequestedInformation))) {
return HRESULT_FROM_WIN32(errc);
}
*ppSecurityDescriptor = sec.Detach();
return S_OK;
}
STDMETHOD(SetSecurity) (THIS_ SECURITY_INFORMATION SecurityInformation,
PSECURITY_DESCRIPTOR pSecurityDescriptor )
{
if (pSecurityDescriptor == NULL)
return E_POINTER;
if (AfxMessageBox(_T("Really save changes?"), MB_ICONEXCLAMATION|MB_YESNO) != IDYES)
return E_ACCESSDENIED;
PSID psidOwner, psidGroup;
BOOL bOwnerDefaulted, bGroupDefaulted, bDaclPresent, bDaclDefaulted, bSaclPresent, bSaclDefaulted;
PACL pDacl, pSacl;
ATLVERIFY(GetSecurityDescriptorOwner(pSecurityDescriptor, &psidOwner, &bOwnerDefaulted));
ATLVERIFY(GetSecurityDescriptorGroup(pSecurityDescriptor, &psidGroup, &bGroupDefaulted));
ATLVERIFY(GetSecurityDescriptorDacl(pSecurityDescriptor, &bDaclPresent, &pDacl, &bDaclDefaulted));
ATLVERIFY(GetSecurityDescriptorSacl(pSecurityDescriptor, &bSaclPresent, &pSacl, &bSaclDefaulted));
int errc;
if (0 != (errc = SetNamedSecurityInfo(CT2W(m_objName), m_se, SecurityInformation, psidOwner, psidGroup, pDacl, pSacl))) {
return HRESULT_FROM_WIN32(errc);
}
return S_OK;
}
};
void CvDlg::OnBnClickedView() {
if (!UpdateData())
return;
CStrSI *pSi = new CStrSI(m_strSDDL);
CComPtr<ISecurityInformation> pSiif = pSi;
switch (m_wndSe.GetItemData(m_wndSe.GetCurSel())) {
case SE_SERVICE:
pSi->SettypeService(); break;
case SE_FILE_OBJECT:
case SE_LMSHARE:
pSi->SettypeFile(); break;
case SE_REGISTRY_KEY:
case SE_REGISTRY_WOW64_32KEY:
pSi->SettypeKey(); break;
}
if (EditSecurity(*this, pSiif)) {
m_strSDDL = pSi->m_strSDDL;
UpdateData(false);
}
}
class EUt {
public:
static CString Format(int errc) {
PVOID pv = NULL;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_IGNORE_INSERTS|FORMAT_MESSAGE_FROM_SYSTEM, NULL, errc, 0, reinterpret_cast<LPWSTR>(&pv), 0, NULL);
CString s = reinterpret_cast<LPCTSTR>(pv);
ATLVERIFY(NULL == LocalFree(pv));
return s;
}
};
void CvDlg::OnBnClickedGet() {
if (!UpdateData())
return;
SE_OBJECT_TYPE se = (SE_OBJECT_TYPE)m_wndSe.GetItemData(m_wndSe.GetCurSel());
SECURITY_INFORMATION sif = 0
|(m_dacl ? DACL_SECURITY_INFORMATION : 0)
|(m_group ? GROUP_SECURITY_INFORMATION : 0)
|(m_owner ? OWNER_SECURITY_INFORMATION : 0)
|(m_sacl ? SACL_SECURITY_INFORMATION : 0)
;
int errc;
CNamedSec sec;
if (0 != (errc = sec.Get(m_objName, se, sif))) {
CString strMsg;
strMsg.Format(_T("GetNamedSecurityInfo failed.\n\n%s"), EUt::Format(errc));
AfxMessageBox(strMsg);
return;
}
if (SUt::ConvertSecurityDescriptorToStringSecurityDescriptor2(sec.pSd, SDDL_REVISION_1, sif, m_strSDDL)) {
UpdateData(false);
}
}
void CvDlg::OnBnClickedEdit() {
if (!UpdateData())
return;
SE_OBJECT_TYPE se = (SE_OBJECT_TYPE)m_wndSe.GetItemData(m_wndSe.GetCurSel());
SECURITY_INFORMATION sif = 0
|(m_dacl ? DACL_SECURITY_INFORMATION : 0)
|(m_group ? GROUP_SECURITY_INFORMATION : 0)
|(m_owner ? OWNER_SECURITY_INFORMATION : 0)
|(m_sacl ? SACL_SECURITY_INFORMATION : 0)
;
CNamedSI *pSi = new CNamedSI();
CComPtr<ISecurityInformation> pSiif = pSi;
pSi->m_objName = m_objName;
pSi->m_se = se;
pSi->m_sif = sif;
switch (m_wndSe.GetItemData(m_wndSe.GetCurSel())) {
case SE_SERVICE: pSi->SettypeService(); break;
default: AfxMessageBox(_T("Only NT Service edit for now."), MB_ICONEXCLAMATION); return;
}
pSi->m_strObjectName = m_objName;
if (!EditSecurity(*this, pSiif))
return;
return;
}
|
#include "Renderer.h"
#include "Time.h"
#include "../include/Mario.h"
#include "../include/Dung.h"
#include "../include/Restart.h"
#include "../include/Bg.h"
#include "testNonRenderObj.h"
#include "CompositeObj.h"
//bool CheckCollision(CompositeObj* one, CompositeObj* two) // AABB - AABB collision
//{
// // collision x-axis?
// bool collisionX = one->position.x + one->scaleVec.x >= two->position.x &&
// two->position.x + two->scaleVec.x >= one->position.x;
// // collision y-axis?
// bool collisionY = one->position.y + one->scaleVec.y >= two->position.y &&
// two->position.y + two->scaleVec.y >= one->position.y;
// // collision only if on both axes
// return collisionX && collisionY;
//}
bool CheckCollision(CompositeObj* one, CompositeObj* two) // AABB - AABB collision
{
// collision x-axis?
bool collisionX = one->position.x + 1.5 >= (two->position.x)/2 &&
(two->position.x)/2 + 1 >= one->position.x;
// collision y-axis?
bool collisionY = one->position.y + 1.5 >= (two->position.y)/2 &&
(two->position.y)/2 + 1 >= one->position.y;
// collision only if on both axes
return collisionX && collisionY;
}
int main(void)
{
Mario* mario = new Mario();
Bg* bg = new Bg();
Restart* restart = new Restart();
testNonRenderObj* testNonRender = new testNonRenderObj();
vector<Dung*>* dung = new vector<Dung*>();
for (int i = 0; i < 10; i++)
{
dung->push_back(new Dung());
}
Renderer::GetInstance()->init();
mario->setScale(0.2f, 0.2f, 0.2f);
bg->setScale(0.17f, 0.125f, 0.1f);
for (
vector<Dung*>::const_iterator it = dung->begin();
it != dung->end();
++it
)
{
(*it)->setScale(0.1f, 0.1f, 0.1f);
}
while (glfwGetKey(Renderer::GetInstance()->window, GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(Renderer::GetInstance()->window) == 0)
{
Renderer::GetInstance()->renderUp();
if (Time::GetInstance()->IsFixedRendering())
{
Renderer::GetInstance()->update();
}
Renderer::GetInstance()->render();
for (
vector<Dung*>::const_iterator it = dung->begin();
it != dung->end();
++it
)
{
if (CheckCollision(mario, (*it)))
{
mario->setPos(-20.0f, 0, 0);
mario->setIsLive(false);
restart->setGameOver(false);
}
}
if (restart->getGameOver()&&mario->getIsLive()==false)
{
mario->init();
for (
vector<Dung*>::const_iterator it = dung->begin();
it != dung->end();
++it
)
{
(*it)->init();
}
}
Renderer::GetInstance()->renderDown();
}
Renderer::GetInstance()->shutDown();
for (
vector<Dung*>::const_iterator it = dung->begin();
it != dung->end();
++it
)
{
delete (*it);
}
delete dung;
delete mario;
delete bg;
delete testNonRender;
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#include <core/pch.h>
#ifdef DOM_EXTENSIONS_TAB_API_SUPPORT
#include "modules/dom/src/extensions/dombrowsertab.h"
#include "modules/dom/src/extensions/dombrowsertabs.h"
#include "modules/dom/src/extensions/dombrowsertabgroup.h"
#include "modules/dom/src/extensions/dombrowserwindows.h"
#include "modules/dom/src/extensions/dombrowserwindow.h"
#include "modules/dom/src/extensions/domextensionscope.h"
#include "modules/dom/src/extensions/domextension_userjs.h"
#include "modules/dom/src/domwebworkers/domcrossmessage.h"
#include "modules/dom/src/domcore/domdoc.h"
#include "modules/dom/src/domcore/node.h"
#include "modules/dochand/winman.h"
#include "modules/dom/src/extensions/domtabsapihelper.h"
#include "modules/dom/src/extensions/domtabapicache.h"
#include "modules/dom/src/extensions/domextension_background.h"
/* static */ OP_STATUS
DOM_BrowserTab::Make(DOM_BrowserTab*& new_obj, DOM_ExtensionSupport* extension_support, unsigned int tab_id, unsigned long window_id, DOM_Runtime* origining_runtime)
{
OP_ASSERT(tab_id);
RETURN_IF_ERROR(DOMSetObjectRuntime(new_obj = OP_NEW(DOM_BrowserTab, (extension_support, window_id, tab_id)), origining_runtime, origining_runtime->GetPrototype(DOM_Runtime::BROWSER_TAB_PROTOTYPE), "BrowserTab"));
RETURN_IF_LEAVE(new_obj->InjectOptionalAPIL());
return OpStatus::OK;
}
void
DOM_BrowserTab::InjectOptionalAPIL()
{
if (m_extension_support->GetGadget()->GetAttribute(WIDGET_EXTENSION_SCREENSHOT_SUPPORT))
AddFunctionL(getScreenshot, "getScreenshot", "-");
}
DOM_MessagePort*
DOM_BrowserTab::GetPort()
{
if (!m_port || !m_port->IsEntangled())
{
if (!m_window_id)
return NULL;
m_port = NULL; // The previous port will be garbage collected.
Window* window = GetTabWindow();
if (DOM_ExtensionScope* scope = m_extension_support->GetExtensionGlobalScope(window))
OpStatus::Ignore(DOM_ExtensionSupport::GetPortTarget(scope->GetExtension()->GetPort(), m_port, GetRuntime()));
}
OP_ASSERT(!m_port || m_port->IsEntangled());
return m_port;
}
Window*
DOM_BrowserTab::GetTabWindow()
{
return g_windowManager->GetWindow(GetWindowId());
}
/* static */ int
DOM_BrowserTab::postMessage(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(tab, DOM_TYPE_BROWSER_TAB, DOM_BrowserTab);
if (DOM_MessagePort *port = tab->GetPort())
return DOM_MessagePort::postMessage(port, argv, argc, return_value, origining_runtime);
else
return DOM_CALL_DOMEXCEPTION(INVALID_STATE_ERR);
}
/* static */ int
DOM_BrowserTab::close(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(tab, DOM_TYPE_BROWSER_TAB, DOM_BrowserTab);
DOM_TabsApiHelper* call_helper;
if (argc >= 0)
{
CALL_FAILED_IF_ERROR(DOM_TabsApiHelper::Make(call_helper, origining_runtime));
call_helper->RequestTabClose(tab->GetTabId());
}
else
call_helper = DOM_VALUE2OBJECT(*return_value, DOM_TabsApiHelper);
if (call_helper->IsFinished())
{
CALL_FAILED_IF_ERROR(call_helper->GetStatus());
return ES_FAILED;
}
else
return call_helper->BlockCall(return_value, origining_runtime);
}
/* static */ int
DOM_BrowserTab::update(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(tab, DOM_TYPE_BROWSER_TAB, DOM_BrowserTab);
DOM_TabsApiHelper* call_helper;
if (argc >= 0)
{
DOM_CHECK_ARGUMENTS("o");
ES_Object* properties = argv[0].value.object;
CALL_FAILED_IF_ERROR(DOM_TabsApiHelper::Make(call_helper, origining_runtime));
call_helper->RequestTabUpdate(tab->GetTabId(), properties, origining_runtime);
}
else
call_helper = DOM_VALUE2OBJECT(*return_value, DOM_TabsApiHelper);
if (call_helper->IsFinished())
{
TAB_API_CALL_FAILED_IF_ERROR(call_helper->GetStatus());
return ES_FAILED;
}
else
return call_helper->BlockCall(return_value, origining_runtime);
}
/* static */ int
DOM_BrowserTab::focus(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(tab, DOM_TYPE_BROWSER_TAB, DOM_BrowserTab);
DOM_TabsApiHelper* call_helper;
if (argc >= 0)
{
CALL_FAILED_IF_ERROR(DOM_TabsApiHelper::Make(call_helper, origining_runtime));
call_helper->RequestTabFocus(tab->GetTabId());
}
else
call_helper = DOM_VALUE2OBJECT(*return_value, DOM_TabsApiHelper);
if (call_helper->IsFinished())
{
TAB_API_CALL_FAILED_IF_ERROR(call_helper->GetStatus());
return ES_FAILED;
}
else
return call_helper->BlockCall(return_value, origining_runtime);
}
/* static */ int
DOM_BrowserTab::refresh(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(tab, DOM_TYPE_BROWSER_TAB, DOM_BrowserTab);
Window* window = tab->GetTabWindow();
if (!window)
return DOM_CALL_DOMEXCEPTION(INVALID_STATE_ERR);
window->Reload();
return ES_FAILED;
}
/* static */ int
DOM_BrowserTab::getScreenshot(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(tab, DOM_TYPE_BROWSER_TAB, DOM_BrowserTab);
Window* window = tab->GetTabWindow();
FramesDocument* target = window ? window->GetCurrentDoc() : NULL;
OP_ASSERT(tab->m_extension_support->GetBackground());
return tab->m_extension_support->GetScreenshot(target, argv, argc, return_value, origining_runtime);
}
/* virtual */ ES_GetState
DOM_BrowserTab::GetNameRestart(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime, ES_Object* restart_object)
{
switch (property_name)
{
case OP_ATOM_focused:
case OP_ATOM_selected:
case OP_ATOM_id:
case OP_ATOM_locked:
case OP_ATOM_browserWindow:
case OP_ATOM_position:
case OP_ATOM_tabGroup:
case OP_ATOM_title:
case OP_ATOM_private:
case OP_ATOM_closed:
return GetTabInfo(property_name, value, origining_runtime, restart_object);
}
return DOM_Object::GetNameRestart(property_name, value, origining_runtime, restart_object);
}
ES_GetState
DOM_BrowserTab::GetTabInfo(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime, ES_Object* restart_object)
{
if (!value)
return GET_SUCCESS;
// Private mode can be obtained synchronously if we have window.
if (property_name == OP_ATOM_private)
{
Window* window = GetTabWindow();
if (window)
{
DOMSetBoolean(value, window->GetPrivacyMode());
return GET_SUCCESS;
}
}
OP_ASSERT(GetTabId());
DOM_TabsApiHelper* call_helper;
if (!restart_object)
{
GET_FAILED_IF_ERROR(DOM_TabsApiHelper::Make(call_helper, static_cast<DOM_Runtime*>(origining_runtime)));
call_helper->QueryTab(GetTabId());
}
else
call_helper = DOM_HOSTOBJECT(restart_object, DOM_TabsApiHelper);
if (call_helper->IsFinished())
{
if (property_name == OP_ATOM_closed)
{
DOMSetBoolean(value, OpStatus::IsError(call_helper->GetStatus()));
return GET_SUCCESS;
}
else
GET_FAILED_IF_ERROR(call_helper->GetStatus());
switch (property_name)
{
case OP_ATOM_browserWindow:
DOM_BrowserWindow* new_win;
GET_FAILED_IF_ERROR(DOM_TabApiCache::GetOrCreateWindow(new_win, m_extension_support, call_helper->GetResult().value.query_tab.browser_window_id, GetRuntime()));
DOMSetObject(value, new_win);
break;
case OP_ATOM_locked:
DOMSetBoolean(value, call_helper->GetResult().value.query_tab.is_locked);
break;
case OP_ATOM_position:
DOMSetNumber(value, call_helper->GetResult().value.query_tab.position);
break;
case OP_ATOM_tabGroup:
if (call_helper->GetResult().value.query_tab.tab_group_id == 0)
DOMSetNull(value);
else
{
DOM_BrowserTabGroup* tab_group;
GET_FAILED_IF_ERROR(DOM_TabApiCache::GetOrCreateTabGroup(tab_group, m_extension_support, call_helper->GetResult().value.query_tab.tab_group_id, GetRuntime()));
DOMSetObject(value, tab_group);
}
break;
case OP_ATOM_focused:
case OP_ATOM_selected:
DOMSetBoolean(value, call_helper->GetResult().value.query_tab.is_selected);
break;
case OP_ATOM_title:
if (!call_helper->GetResult().value.query_tab.is_private || IsPrivateDataAllowed())
{
TempBuffer* tmp = GetEmptyTempBuf();
GET_FAILED_IF_ERROR(tmp->Append(call_helper->GetResult().value.query_tab.title));
DOMSetString(value, tmp);
}
return GET_SUCCESS;
case OP_ATOM_private:
DOMSetBoolean(value, call_helper->GetResult().value.query_tab.is_private);
return GET_SUCCESS;
default:
OP_ASSERT(!"Unexpected property");
}
return GET_SUCCESS;
}
else
return call_helper->BlockGet(value, origining_runtime);
}
/* virtual */ ES_GetState
DOM_BrowserTab::GetName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime)
{
switch (property_name)
{
case OP_ATOM_id:
DOMSetNumber(value, GetTabId());
return GET_SUCCESS;
case OP_ATOM_locked:
case OP_ATOM_browserWindow:
case OP_ATOM_position:
case OP_ATOM_tabGroup:
case OP_ATOM_focused:
case OP_ATOM_selected:
case OP_ATOM_title:
case OP_ATOM_private:
case OP_ATOM_closed:
return GetTabInfo(property_name, value, origining_runtime, NULL);
case OP_ATOM_faviconUrl:
{
#ifdef SHORTCUT_ICON_SUPPORT
Window* window = GetTabWindow();
if (window && (!window->GetPrivacyMode() || IsPrivateDataAllowed()))
DOMSetString(value, window->GetWindowIconURL().GetAttribute(URL::KUniName_With_Fragment, URL::KNoRedirect).CStr());
#endif // SHORTCUT_ICON_SUPPORT
return GET_SUCCESS;
}
case OP_ATOM_url:
{
Window* window = GetTabWindow();
if (window && (!window->GetPrivacyMode() || IsPrivateDataAllowed()))
{
const uni_char* url = window->GetCurrentURL().GetAttribute(URL::KUniName_With_Fragment, URL::KNoRedirect).CStr();
if (!url || !*url) // if nothing is currently loaded then try if something is loading.
url = window->GetCurrentLoadingURL().GetAttribute(URL::KUniName_With_Fragment, URL::KNoRedirect).CStr();
DOMSetString(value, url);
}
return GET_SUCCESS;
}
case OP_ATOM_readyState:
{
Window* window = GetTabWindow();
if (window && (!window->GetPrivacyMode() || IsPrivateDataAllowed()))
DOM_Document::GetDocumentReadiness(value, window->GetCurrentDoc());
return GET_SUCCESS;
}
#ifdef USE_SPDY
case OP_ATOM_loadedWithSPDY:
{
Window* window = GetTabWindow();
if (window && (!window->GetPrivacyMode() || IsPrivateDataAllowed()))
DOMSetBoolean(value, window->GetCurrentURL().GetAttribute(URL::KLoadedWithSpdy));
return GET_SUCCESS;
}
#endif // USE_SPDY
case OP_ATOM_port:
DOMSetObject(value, GetPort());
return GET_SUCCESS;
default:
return DOM_Object::GetName(property_name, value, origining_runtime);
}
}
/* virtual */ ES_PutState
DOM_BrowserTab::PutName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime)
{
switch (property_name)
{
case OP_ATOM_id:
case OP_ATOM_locked:
case OP_ATOM_browserWindow:
case OP_ATOM_position:
case OP_ATOM_tabGroup:
case OP_ATOM_focused:
case OP_ATOM_selected:
case OP_ATOM_title:
case OP_ATOM_private:
case OP_ATOM_closed:
case OP_ATOM_faviconUrl:
case OP_ATOM_url:
case OP_ATOM_readyState:
#ifdef USE_SPDY
case OP_ATOM_loadedWithSPDY:
#endif // USE_SPDY
case OP_ATOM_port:
return PUT_READ_ONLY;
default:
return DOM_TabApiCachedObject::PutName(property_name, value, origining_runtime);
}
}
BOOL
DOM_BrowserTab::IsPrivateDataAllowed()
{
if (!GetFramesDocument())
return FALSE;
OP_ASSERT(GetFramesDocument()->GetWindow()->GetGadget());
return GetFramesDocument()->GetWindow()->GetGadget()->GetExtensionFlag(OpGadget::AllowUserJSPrivate);
}
/* virtual */ void
DOM_BrowserTab::GCTrace()
{
GCMark(m_port);
}
/* virtual */
DOM_BrowserTab::~DOM_BrowserTab()
{
OP_NEW_DBG("DOM_BrowserTab::~DOM_BrowserTab()", "extensions.dom");
OP_DBG(("this: %p tab_id: %d", this, GetTabId()));
}
#include "modules/dom/src/domglobaldata.h"
DOM_FUNCTIONS_START(DOM_BrowserTab)
DOM_FUNCTIONS_FUNCTION(DOM_BrowserTab, DOM_BrowserTab::postMessage, "postMessage", "")
DOM_FUNCTIONS_FUNCTION(DOM_BrowserTab, DOM_BrowserTab::close, "close", "")
DOM_FUNCTIONS_FUNCTION(DOM_BrowserTab, DOM_BrowserTab::update, "update", "{url:S,title:S,locked:b,focused:b}-")
DOM_FUNCTIONS_FUNCTION(DOM_BrowserTab, DOM_BrowserTab::focus, "focus", "")
DOM_FUNCTIONS_FUNCTION(DOM_BrowserTab, DOM_BrowserTab::refresh, "refresh", "")
DOM_FUNCTIONS_END(DOM_BrowserTab)
#endif // DOM_EXTENSIONS_TAB_API_SUPPORT
|
#include <iostream>
using std::cin; using std::cout; using std::endl;
#include <string>
using std::string;
int main()
{
unsigned cnt = 0;
string s, s_next;
cin >> s;
++cnt;
while(cin >> s_next) {
if(s == s_next && isupper(s_next[0])) {
++cnt;
break;
} else {
s = s_next;
cnt = 1;
}
}
if(cnt == 1)
cout << "not found" << endl;
else
cout << "found: " << s_next << endl;
return 0;
}
|
// Copyright (c) 2021 ETH Zurich
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <pika/config.hpp>
#if defined(PIKA_HAVE_STDEXEC)
# include <pika/execution_base/stdexec_forward.hpp>
#endif
#include <pika/allocator_support/allocator_deleter.hpp>
#include <pika/allocator_support/internal_allocator.hpp>
#include <pika/allocator_support/traits/is_allocator.hpp>
#include <pika/errors/try_catch_exception_ptr.hpp>
#include <pika/execution/algorithms/detail/helpers.hpp>
#include <pika/execution/algorithms/detail/partial_algorithm.hpp>
#include <pika/execution_base/operation_state.hpp>
#include <pika/execution_base/sender.hpp>
#include <pika/futures/detail/future_data.hpp>
#include <pika/futures/promise.hpp>
#include <pika/memory/intrusive_ptr.hpp>
#include <pika/type_support/detail/with_result_of.hpp>
#include <pika/type_support/pack.hpp>
#include <pika/type_support/unused.hpp>
#include <exception>
#include <memory>
#include <optional>
#include <type_traits>
#include <utility>
namespace pika::make_future_detail {
template <typename T, typename Allocator>
struct resettable_operation_state_future_data
: pika::lcos::detail::future_data_allocator<T, Allocator>
{
PIKA_NON_COPYABLE(resettable_operation_state_future_data);
virtual void reset_operation_state() = 0;
using init_no_addref =
typename pika::lcos::detail::future_data_allocator<T, Allocator>::init_no_addref;
template <typename Allocator_>
resettable_operation_state_future_data(init_no_addref no_addref, Allocator_ const& alloc)
: pika::lcos::detail::future_data_allocator<T, Allocator>(no_addref, alloc)
{
}
};
template <typename T, typename Allocator>
struct make_future_receiver
{
using is_receiver = void;
pika::intrusive_ptr<resettable_operation_state_future_data<T, Allocator>> data;
friend void tag_invoke(pika::execution::experimental::set_error_t, make_future_receiver&& r,
std::exception_ptr ep) noexcept
{
// We move the receiver into a local variable from the operation
// state which the receiver refers to. This allows us to safely
// reset the operation state without destroying the receiver.
make_future_receiver r_local = PIKA_MOVE(r);
r_local.data->set_exception(PIKA_MOVE(ep));
r_local.data->reset_operation_state();
r_local.data.reset();
}
friend void tag_invoke(
pika::execution::experimental::set_stopped_t, make_future_receiver&&) noexcept
{
std::terminate();
}
template <typename U>
friend void tag_invoke(
pika::execution::experimental::set_value_t, make_future_receiver&& r, U&& u) noexcept
{
// We move the receiver into a local variable from the operation
// state which the receiver refers to. This allows us to safely
// reset the operation state without destroying the receiver.
make_future_receiver r_local = PIKA_MOVE(r);
pika::detail::try_catch_exception_ptr(
[&]() { r_local.data->set_value(PIKA_FORWARD(U, u)); },
[&](std::exception_ptr ep) { r_local.data->set_exception(PIKA_MOVE(ep)); });
r_local.data->reset_operation_state();
r_local.data.reset();
}
friend constexpr pika::execution::experimental::empty_env tag_invoke(
pika::execution::experimental::get_env_t, make_future_receiver const&) noexcept
{
return {};
}
};
template <typename Allocator>
struct make_future_receiver<void, Allocator>
{
pika::intrusive_ptr<resettable_operation_state_future_data<void, Allocator>> data;
friend void tag_invoke(pika::execution::experimental::set_error_t, make_future_receiver&& r,
std::exception_ptr ep) noexcept
{
// We move the receiver into a local variable from the operation
// state which the receiver refers to. This allows us to safely
// reset the operation state without destroying the receiver.
make_future_receiver r_local = PIKA_MOVE(r);
r_local.data->set_exception(PIKA_MOVE(ep));
r_local.data->reset_operation_state();
r_local.data.reset();
}
friend void tag_invoke(
pika::execution::experimental::set_stopped_t, make_future_receiver&&) noexcept
{
std::terminate();
}
friend void tag_invoke(
pika::execution::experimental::set_value_t, make_future_receiver&& r) noexcept
{
// We move the receiver into a local variable from the operation
// state which the receiver refers to. This allows us to safely
// reset the operation state without destroying the receiver.
make_future_receiver r_local = PIKA_MOVE(r);
pika::detail::try_catch_exception_ptr(
[&]() { r_local.data->set_value(pika::util::detail::unused); },
[&](std::exception_ptr ep) { r_local.data->set_exception(PIKA_MOVE(ep)); });
r_local.data->reset_operation_state();
r_local.data.reset();
}
friend constexpr pika::execution::experimental::empty_env tag_invoke(
pika::execution::experimental::get_env_t, make_future_receiver const&) noexcept
{
return {};
}
};
template <typename T, typename Allocator, typename OperationState>
struct future_data : resettable_operation_state_future_data<T, Allocator>
{
PIKA_NON_COPYABLE(future_data);
using operation_state_type = std::decay_t<OperationState>;
using other_allocator =
typename std::allocator_traits<Allocator>::template rebind_alloc<future_data>;
using init_no_addref =
typename pika::lcos::detail::future_data_allocator<T, Allocator>::init_no_addref;
// The operation state is stored in an optional so that it can be
// reset explicitly as soon as set_* is called.
std::optional<operation_state_type> op_state;
template <typename Sender>
future_data(init_no_addref no_addref, other_allocator const& alloc, Sender&& sender)
: resettable_operation_state_future_data<T, Allocator>(no_addref, alloc)
{
op_state.emplace(pika::detail::with_result_of([&]() {
return pika::execution::experimental::connect(
PIKA_FORWARD(Sender, sender), make_future_receiver<T, Allocator>{this});
}));
pika::execution::experimental::start(op_state.value());
}
void reset_operation_state() override { op_state.reset(); }
};
///////////////////////////////////////////////////////////////////////
template <typename Sender, typename Allocator>
auto make_future(Sender&& sender, Allocator const& allocator)
{
using allocator_type = Allocator;
#if defined(PIKA_HAVE_STDEXEC)
using value_types =
typename pika::execution::experimental::value_types_of_t<std::decay_t<Sender>,
pika::execution::experimental::empty_env, pika::util::detail::pack,
pika::util::detail::pack>;
#else
using value_types =
typename pika::execution::experimental::sender_traits<std::decay_t<Sender>>::
template value_types<pika::util::detail::pack, pika::util::detail::pack>;
#endif
using result_type =
std::decay_t<pika::execution::experimental::detail::single_result_t<value_types>>;
using operation_state_type = std::invoke_result_t<pika::execution::experimental::connect_t,
Sender, make_future_receiver<result_type, allocator_type>>;
using shared_state = future_data<result_type, allocator_type, operation_state_type>;
using init_no_addref = typename shared_state::init_no_addref;
using other_allocator =
typename std::allocator_traits<allocator_type>::template rebind_alloc<shared_state>;
using allocator_traits = std::allocator_traits<other_allocator>;
using unique_ptr =
std::unique_ptr<shared_state, pika::detail::allocator_deleter<other_allocator>>;
other_allocator alloc(allocator);
unique_ptr p(allocator_traits::allocate(alloc, 1),
pika::detail::allocator_deleter<other_allocator>{alloc});
allocator_traits::construct(
alloc, p.get(), init_no_addref{}, alloc, PIKA_FORWARD(Sender, sender));
return pika::traits::future_access<future<result_type>>::create(p.release(), false);
}
} // namespace pika::make_future_detail
namespace pika::execution::experimental {
inline constexpr struct make_future_t final
: pika::functional::detail::tag_fallback<make_future_t>
{
private:
// clang-format off
template <typename Sender,
typename Allocator = pika::detail::internal_allocator<>,
PIKA_CONCEPT_REQUIRES_(
is_sender_v<Sender> &&
pika::detail::is_allocator_v<Allocator>
)>
// clang-format on
friend constexpr PIKA_FORCEINLINE auto tag_fallback_invoke(
make_future_t, Sender&& sender, Allocator const& allocator = Allocator{})
{
return make_future_detail::make_future(PIKA_FORWARD(Sender, sender), allocator);
}
// clang-format off
template <typename Allocator = pika::detail::internal_allocator<>,
PIKA_CONCEPT_REQUIRES_(
pika::detail::is_allocator_v<Allocator>
)>
// clang-format on
friend constexpr PIKA_FORCEINLINE auto
tag_fallback_invoke(make_future_t, Allocator const& allocator = Allocator{})
{
return detail::partial_algorithm<make_future_t, Allocator>{allocator};
}
} make_future{};
} // namespace pika::execution::experimental
|
#include "stdafx.h"
#include "ParticleRenderView.h"
#include "ParticleDialog.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CParticleRenderView
IMPLEMENT_DYNCREATE(CParticleRenderView, CView)
BEGIN_MESSAGE_MAP(CParticleRenderView, CView)
//{{AFX_MSG_MAP(CParticleRenderView)
ON_WM_NCCALCSIZE()
ON_WM_NCPAINT()
//ON_COMMAND(ID_VIEW_THREE, OnViewThree)
//ON_UPDATE_COMMAND_UI(ID_VIEW_THREE, OnUpdateViewThree)
ON_WM_SETFOCUS()
ON_WM_KILLFOCUS()
//}}AFX_MSG_MAP
// Standard printing commands
//ON_COMMAND(ID_FILE_PRINT, CViewDraw::OnFilePrint)
//ON_COMMAND(ID_FILE_PRINT_DIRECT, CViewDraw::OnFilePrint)
//ON_COMMAND(ID_FILE_PRINT_PREVIEW, CViewDraw::OnFilePrintPreview)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CParticleRenderView construction/destruction
CParticleRenderView::CParticleRenderView()
: m_bEnable(FALSE)
{
// TODO: add construction code here
}
CParticleRenderView::~CParticleRenderView()
{
}
BOOL CParticleRenderView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CView::PreCreateWindow(cs);
}
/////////////////////////////////////////////////////////////////////////////
// CParticleRenderView drawing
void CParticleRenderView::OnDraw(CDC* pDC)
{
CView::OnDraw(pDC);
}
/////////////////////////////////////////////////////////////////////////////
// CParticleRenderView diagnostics
#ifdef _DEBUG
void CParticleRenderView::AssertValid() const
{
CView::AssertValid();
}
void CParticleRenderView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CParticleRenderView message handlers
void CParticleRenderView::OnNcCalcSize(BOOL bCalcValidRects, NCCALCSIZE_PARAMS FAR* lpncsp)
{
// bypass base class.
CView::OnNcCalcSize(bCalcValidRects, lpncsp);
}
void CParticleRenderView::OnNcPaint()
{
// bypass base class.
CView::OnNcPaint();
}
void CParticleRenderView::OnViewThree()
{
// TODO: Add your command handler code here
AfxMessageBox(_T("SDI View - No. 3"));
}
void CParticleRenderView::OnUpdateViewThree(CCmdUI* pCmdUI)
{
// TODO: Add your command update UI handler code here
pCmdUI->Enable(m_bEnable);
}
void CParticleRenderView::OnSetFocus(CWnd* pOldWnd)
{
CView::OnSetFocus(pOldWnd);
// TODO: Add your message handler code here
m_bEnable = TRUE;
}
void CParticleRenderView::OnKillFocus(CWnd* pNewWnd)
{
CView::OnKillFocus(pNewWnd);
// TODO: Add your message handler code here
m_bEnable = FALSE;
}
|
#include "SimpleLogger.h"
#include "lock.hpp"
#include "threadpool.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <string>
#include <vector>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <errno.h>
using std::string;
namespace core{
SimpleLogger& SimpleLogger::Instance()
{
static SimpleLogger static_logsaver;
return static_logsaver;
}
bool SimpleLogger::Init(const std::string& logfilepath, LogLevel global_lv)
{
m_logfile = fopen(logfilepath.c_str(), "a");
if(m_logfile == NULL)
{
perror("open file for writing log failed.");
return false;
}
chmod(logfilepath.c_str(), S_IRUSR|S_IWUSR|S_IROTH|S_IWOTH);
m_level_str[0] = "ERROR";
m_level_str[1] = "WARN";
m_level_str[2] = "INFO";
m_level_str[3] = "DEBUG";
m_global_lv = global_lv;
return true;
}
void SimpleLogger::Reset()
{
write2file();
if(m_logfile != NULL)
{
fclose(m_logfile);
m_logfile = NULL;
}
core::common::locker_guard guard(m_lock);
m_waiting_logs.clear();
}
void SimpleLogger::queue_log(const LogInfo& loginfo)
{
if(m_logfile == NULL)
return;
core::common::locker_guard guard(m_lock);
m_waiting_logs.push_back(loginfo);
threadpool::queue_timer_task(boost::bind(&SimpleLogger::flush_all, this), 2, false);
}
void SimpleLogger::flush_all()
{
threadpool::queue_work_task_to_named_thread(boost::bind(&SimpleLogger::write2file, this), "logsaver");
}
SimpleLogger::~SimpleLogger()
{
Reset();
}
LogLevel SimpleLogger::GetLogLevel()
{
return m_global_lv;
}
SimpleLogger::SimpleLogger()
{
m_logfile = NULL;
m_global_lv = lv_warn;
}
void SimpleLogger::write2file()
{
// save im msg
if(m_logfile == NULL)
return;
struct flock fl;
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0;
fl.l_pid = getpid();
while(fcntl(fileno(m_logfile), F_SETLKW, &fl) == -1)
{
perror("fcntl get lock error.");
if(errno != EINTR)
return;
}
std::vector<LogInfo> writinglogs;
{
core::common::locker_guard guard(m_lock);
writinglogs.swap(m_waiting_logs);
}
for(size_t i = 0; i < writinglogs.size(); i++)
{
LogInfo& info = writinglogs[i];
fprintf(m_logfile, "%s in %s : %s [%s]\n", m_level_str[info.level_].c_str(),
info.category_.c_str(), info.content_.c_str(), info.time_.c_str());
}
fflush(m_logfile);
fl.l_type = F_UNLCK;
if(fcntl(fileno(m_logfile), F_SETLK, &fl) == -1)
{
perror("fcntl release lock error.");
assert(false);
}
}
LoggerCategory::LoggerCategory(const std::string& category)
{
m_category = category;
assert(m_category.size() < 64);
}
void LoggerCategory::Log(LogLevel lv, const char* fmt, ...)
{
string errcodestr;
if(lv == lv_error)
{
char err[6];
memset(err, 0, 6);
snprintf(err, 6, "%d", errno);
errcodestr = "error code: " + string(err) + ".";
perror(NULL);
}
if(lv > SimpleLogger::Instance().GetLogLevel())
return;
{
#ifdef NDEBUG
if(lv == lv_debug)
return;
#endif
va_list vl_args;
va_start(vl_args, fmt);
vprintf(fmt, vl_args);
va_end(vl_args);
printf("\n");
}
va_list vl_args;
char* buffer;
char* tmpbuf;
int size = 32;
int retlen;
if( (buffer = (char*)malloc(size)) == NULL )
return;
while(1)
{
va_start(vl_args, fmt);
retlen = vsnprintf(buffer, size, fmt, vl_args);
va_end(vl_args);
if(retlen > -1 && retlen < size)
break;
if(retlen > -1)
size = retlen + 1;
else
size *= 2;
if( (tmpbuf = (char*)realloc(buffer, size)) == NULL )
{
free(buffer);
return;
}
else
{
buffer = tmpbuf;
}
}
time_t tnow = time(NULL);
string timestr(ctime(&tnow));
timestr[timestr.size() - 1] = '\0';
LogInfo info(m_category, lv, errcodestr + string(buffer, retlen), timestr);
SimpleLogger::Instance().queue_log(info);
free(buffer);
}
}// end of namespace core
|
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include "Video.h"
using namespace std;
int changeoptions;
bool videolist;
string temp_name_of_tape, temp_type_of_movie, temp_cost, temp_released_date, temp_location, temp_availability;
int main()
{
vector<Videotape> list;//vector of list to dynamically increase the size of the number of videos
int i = 0;//starting from list 0
cout << "_______LIST OF VIDEOS_______" << endl;
// Videotape(string name_of_tape, string type_of_movie, string released_date, string cost, string availability, string location)
list.push_back(Videotape("Good_will_hunting", "Drama", "10/02/1997", "$10","Available" , "F-17"));
list.at(i).Print();
i = i + 1;
list.push_back(Videotape("Parasite", "Horror", "10/13/2003", "$8" ,"Not available", "A-19"));
list.at(i).Print();
i= i + 1;
while (true)
{
cout << "\n______________________Options______________________\n 1.Add a video informations to save on the system \n 2.Show the current list of video files\nWrite 1 or 2 ";
cin >> changeoptions;
if (changeoptions == 1)
{
//string temp_name_of_tape, temp_type_of_movie, temp_released_date, temp_cost, temp_availability, temp_location, ;
cin.ignore();
list.push_back(Videotape("", "", "", "", "", ""));
cout << "\nName of the tape? ";
getline(cin, temp_name_of_tape);
cout << "Type of the movie? ";
getline(cin, temp_type_of_movie);
cout << "Released date of the movie? ";
getline(cin, temp_released_date);
cout << "Cost? ";
getline(cin, temp_cost);
cout << "Is the video available? (Write Available or Not available) ";
getline(cin, temp_availability);
cout << "Location? ";
getline(cin, temp_location);
//using set method
list.at(i).setNAME_OF_TAPE(temp_name_of_tape);
list.at(i).setTYPE_OF_MOVIE(temp_type_of_movie);
list.at(i).setRELEASED_DATE(temp_released_date);
list.at(i).setCOST(temp_cost);
list.at(i).setAVAILABILITY(temp_availability);
list.at(i).setLOCATION(temp_location);
i = i + 1;
changeoptions = 0;//set to defult option
}
else if (changeoptions == 2)
{
cout << "\n\n_______LIST OF VIDEOS_______" << endl;
for (int j = 0; j < i; j++)
{
list.at(j).Print();
}
changeoptions = 0;//set to defult option
}//end of else
}//end of while true
return 0;
}
|
int quarter(point a)
{
if(a.x>0 and a.y>=0) return 0;
if(a.x<=0 and a.y>0) return 1;
if(a.x<0 and a.y<=0) return 2;
return 3;
}
point c;
bool comp(point a, point b) //ccw
{
a=a-c;b=b-c;
int qa = quarter(a);
int qb = quarter(b);
if(qa==qb)
return (a^b)>0;
else
return qa<qb;
}
c = center(A);
sort(A.begin(), A.end(), comp);
|
#ifndef AWS_NODES_EXPRESSION_H
#define AWS_NODES_EXPRESSION_H
/*
* aws/nodes/expression.h
* AwesomeScript Expression
* Author: Dominykas Djacenka
* Email: Chaosteil@gmail.com
*/
#include "parsernode.h"
namespace AwS{
namespace Nodes{
class Expression : public ParserNode{
public:
Expression() : ParserNode(){}
virtual ~Expression(){}
};
};
};
#endif
|
#include "stdafx.h"
#include "DijkstraMatrixAlgorithm.h"
#include <climits>
#include <iostream>
DijkstraMatrixAlgorithm::DijkstraMatrixAlgorithm(Graph & graph) :shortestPathAlgorithm(graph)
{
int unvisitedVertrexSize = graph.getNumberOfVertices();
for (int i = 0; i < unvisitedVertrexSize; i++)
{
unvisitedVertrexVec.push_back(i);
shortestPaths[i] = INT_MAX;
previousVertices[i] = -1;//INF
}
shortestPaths[graph.getFirstVertex()] = 0;
}
DijkstraMatrixAlgorithm::~DijkstraMatrixAlgorithm()
{
}
void DijkstraMatrixAlgorithm::startAlgorithm()
{
while (unvisitedVertrexVec.size() != 0)
{
int vertrexWithLeastPath = getVertrexWithLeastPath();
removeVertrexFromUnvisited(vertrexWithLeastPath);
relaxationForNeighborhoods(vertrexWithLeastPath);
//std::cout << "v: " << vertrexWithLeastPath << " size: " << unvisitedVertrexVec.size() << "\n";
//system("Pause");
}
}
int DijkstraMatrixAlgorithm::getVertrexWithLeastPath()//give his number
{
int vertrexWithLeastPath = unvisitedVertrexVec.get(0);
int valueOfVertrexWithLeastPath = shortestPaths[vertrexWithLeastPath];
for (int i = 1; i < unvisitedVertrexVec.size(); i++)
{
int vec = unvisitedVertrexVec.get(i);
if (valueOfVertrexWithLeastPath > shortestPaths[vec])
{
vertrexWithLeastPath = vec;
valueOfVertrexWithLeastPath = shortestPaths[vec];
}
}
return vertrexWithLeastPath;
}
void DijkstraMatrixAlgorithm::relaxationForNeighborhoods(int vertrex)
{
for (int i = 0; i < unvisitedVertrexVec.size(); i++)
{
int unvisitedVertrex = unvisitedVertrexVec.get(i);
if (graph.neighborhoodMatrix[vertrex][unvisitedVertrex] != INF )//-1)
relaxation(vertrex, unvisitedVertrex);
}
}
void DijkstraMatrixAlgorithm::removeVertrexFromUnvisited(int vertrex)
{
unvisitedVertrexVec.deleteKey(vertrex);
}
void DijkstraMatrixAlgorithm::relaxation(int u, int v)
{
//std::cout << u << " " << v << " ";
//std::cout << "sPv: " << shortestPaths[v] << " sPu: " << shortestPaths[u] << " g.nM: " << graph.neighborhoodMatrix[u][v] << "\n";
int weight = graph.neighborhoodMatrix[u][v];//FRIENDSHIP HERE IS NEEDED
if (shortestPaths[v] > shortestPaths[u] + weight)
{
shortestPaths[v] = shortestPaths[u] + weight;
previousVertices[v] = u;
}
}
|
#include "stgraph.h"
#include <fstream>
#ifdef __GNUC__
# if __GNUC__ == 3
#include <iterator>
# endif
#endif
//------------------------------------------------------------------------------
void STGraph::AddNode (std::string s)
{
if (labelled_nodes.find (s) == labelled_nodes.end ())
{
node n = new_node ();
labelled_nodes[s] = n;
node_labels[n] = s;
}
}
//------------------------------------------------------------------------------
void STGraph::AddEdge (std::string s1, std::string s2, int weight)
{
node n1, n2;
bool both_nodes_exist = true;
if (labelled_nodes.find (s1) == labelled_nodes.end ())
{
both_nodes_exist = false;
n1 = new_node ();
labelled_nodes[s1] = n1;
node_labels[n1] = s1;
}
else
{
n1 = labelled_nodes[s1];
}
if (labelled_nodes.find (s2) == labelled_nodes.end ())
{
both_nodes_exist = false;
n2 = new_node ();
labelled_nodes[s2] = n2;
node_labels[n2] = s2;
}
else
{
n2 = labelled_nodes[s2];
}
if (both_nodes_exist)
{
// Is there already an edge connecting n1 and n2?
node::adj_edges_iterator eit = n1.adj_edges_begin();
node::adj_edges_iterator eend = n1.adj_edges_end();
node found = n1;
while ((found == n1) && (eit != eend))
{
if (n1.opposite (*eit) == n2)
found = n2;
else
eit++;
}
if (found == n2)
{
// Yes, so increment weight of edge
w0[*eit] += weight;
f[*eit] += 1;
}
else
{
// No, so create new edge in graph
edge e = new_edge (n1, n2);
w0[e] = weight;
f[e] = 1;
}
}
else
{
// One or both nodes are new, so create new edge in graph
edge e = new_edge (n1, n2);
w0[e] = weight;
f[e] = 1;
}
}
//------------------------------------------------------------------------------
bool STGraph::EdgeExists (node n1, node n2)
{
bool result = false;
// Is there an edge connecting n1 and n2?
node::adj_edges_iterator eit = n1.adj_edges_begin();
node::adj_edges_iterator eend = n1.adj_edges_end();
node found = n1;
while ((found == n1) && (eit != eend))
{
if (n1.opposite (*eit) == n2)
found = n2;
else
eit++;
}
if (found == n2)
{
result = true;
}
return result;
}
//------------------------------------------------------------------------------
int STGraph::GetEdgeFreqFromNodeLabels (std::string s1, std::string s2)
{
int result = 0;
bool both_nodes_exist = true;
node n1, n2;
if (labelled_nodes.find (s1) == labelled_nodes.end ())
{
both_nodes_exist = false;
}
else
{
n1 = labelled_nodes[s1];
}
if (labelled_nodes.find (s2) == labelled_nodes.end ())
{
both_nodes_exist = false;
}
else
{
n2 = labelled_nodes[s2];
}
if (both_nodes_exist)
{
// Is there an edge connecting n1 and n2?
node::adj_edges_iterator eit = n1.adj_edges_begin();
node::adj_edges_iterator eend = n1.adj_edges_end();
node found = n1;
while ((found == n1) && (eit != eend))
{
if (n1.opposite (*eit) == n2)
found = n2;
else
eit++;
}
if (found == n2)
{
result = f[*eit];
}
}
return result;
}
//------------------------------------------------------------------------------
void STGraph::post_new_node_handler (node n)
{
graph::post_new_node_handler (n);
ns[n].insert (n);
}
//------------------------------------------------------------------------------
void STGraph::save_graph_info_handler (ostream *os) const
{
graph::save_graph_info_handler (os);
}
//------------------------------------------------------------------------------
void STGraph::save_edge_info_handler (ostream *os, edge e) const
{
graph::save_edge_info_handler (os, e);
*os << "label \"" << w0[e];
// if (bShowFreq)
// *os << "[" << f[e] << "]";
*os << "\"" << endl;
// Line width 1 pt
*os << "graphics [" << endl;
if (mShowColours)
{
switch (edge_colour[e])
{
case colour_uncontradicted:
*os << "width 1.0" << endl;
break;
case colour_contradicted:
*os << "fill \"#ff0000\"";
*os << "width 2.0" << endl;
break;
case colour_adjto_contradicted:
*os << "fill \"#0000ff\"";
*os << "width 2.0" << endl;
break;
}
}
else
*os << "width 1.0" << endl;
*os << "]" << endl;
// Use standard Postscript font
*os << "LabelGraphics [" << endl;
*os << "type \"text\"" << endl;
*os << "font \"Helvetica\"" << endl;
*os << "]" << endl;
}
//------------------------------------------------------------------------------
void STGraph::save_node_info_handler (ostream *os, node n) const
{
graph::save_node_info_handler (os, n);
*os << "label \"";
if (mShowLabels)
{
// Full names
NodeSet nset = ns[n];
NodeSet::iterator sit =nset.begin();
NodeSet::iterator send = nset.end();
while (sit != send)
{
*os << node_labels[*sit] << " ";
sit++;
}
}
else
{
// Numbers
/* std::copy (ns[n].begin(), ns[n].end(),
std::ostream_iterator<node>(*os, " ")); */
}
*os << "\"" << endl;
// Use standard Postscript font
*os << "LabelGraphics [" << endl;
*os << "type \"text\"" << endl;
*os << "font \"Helvetica\"" << endl;
*os << "]" << endl;
}
//------------------------------------------------------------------------------
int STGraph::GetCommonNeighbours (edge e, NodeSet &common_set)
{
int count = 0;
node s = e.source();
node t = e.target();
// List all nodes adjacent to s that are not linked
// by a contradicted edge
NodeSet adjacent_to_s;
node::adj_edges_iterator nit = s.adj_edges_begin();
node::adj_edges_iterator nend = s.adj_edges_end();
while (nit != nend)
{
if (edge_colour[*nit] != colour_contradicted)
adjacent_to_s.insert (s.opposite (*nit));
nit++;
}
// List all nodes adjacent to t that are not linked
// by a contradicted edge
nit = t.adj_edges_begin();
nend = t.adj_edges_end();
while (nit != nend)
{
if (edge_colour[*nit] != colour_contradicted)
{
NodeSet::iterator n = adjacent_to_s.find (t.opposite (*nit));
if (n != adjacent_to_s.end())
{
count++;
common_set.insert (*n);
}
}
nit++;
}
return count;
}
//------------------------------------------------------------------------------
void STGraph::mergeNodes (node s, node t)
{
NodeSet::iterator nsit = ns[t].begin();
NodeSet::iterator nsend = ns[t].end();
while (nsit != nsend)
{
ns[s].insert (*nsit);
nsit++;
}
// List all nodes adjacent to s
NodeSet adjacent_to_s;
node::adj_nodes_iterator nit = s.adj_nodes_begin();
node::adj_nodes_iterator nend = s.adj_nodes_end();
while (nit != nend)
{
adjacent_to_s.insert (*nit);
nit++;
}
// Visit all edges adjacent to t.
list<edge> to_be_deleted;
node::adj_edges_iterator it = t.adj_edges_begin();
node::adj_edges_iterator end = t.adj_edges_end();
while (it != end)
{
// Node u is adjacent to t
node u = t.opposite(*it);
if (u == s)
{
// Edge (s,t) will become a loop when s and t are merged
// Action: delete edge (s,t)
to_be_deleted.push_back (*it);
// cout << " deleted loop " << (*it) << endl;
}
else
{
NodeSet::iterator in_as = adjacent_to_s.find (u);
if (in_as != adjacent_to_s.end())
{
// Node u is adjacent to both s and t, and so edge (t,u) will become parallel with
// edge (s, u) when s and t are merged.
// Action: delete edge (t,u)
to_be_deleted.push_back (*it);
// cout << " deleted parallel edge " << (*it) << endl;
}
else
{
// Node u is adjacent to t but not s. When s and t are merged, u will become adjacent
// to s. Hence we need an edge (s,u)
// Action: delete edge (t, u)
int saved_weight = w0[*it];
to_be_deleted.push_back (*it);
// cout << " Redirected edge " << (*it);
// Action: create edge (s,u)
edge e = new_edge (s, u);
w0[e] = saved_weight;
// cout << " to " << e << endl;
}
}
it++;
}
// Delete the extra edges
list<edge>::iterator lit = to_be_deleted.begin();
list<edge>::iterator lend = to_be_deleted.end();
while (lit != lend)
{
del_edge (*lit);
lit++;
}
}
//------------------------------------------------------------------------------
void STGraph::WriteDotty (const char *fname)
{
std::ofstream f (fname);
WriteDotty (f);
f.close ();
}
//------------------------------------------------------------------------------
void STGraph::WriteDotty (ostream &f)
{
node_map <int> index;
graph::node_iterator nit = nodes_begin();
graph::node_iterator nend = nodes_end();
int count = 0;
while (nit != nend)
{
index[*nit] = count++;
nit++;
}
f << "graph G {" << endl;
// Try and make the graph look nice
f << " node [width=.1,height=.1,fontsize=8,style=filled,color=lightblue2];" << endl;
f << " edge [fontsize=8,len=2];" << endl;
// Write node labels
nit = nodes_begin();
while (nit != nend)
{
f << " " << index[*nit] << " [label=\"";
if (mShowLabels)
{
// Full names
NodeSet nset = ns[*nit];
NodeSet::iterator sit =nset.begin();
NodeSet::iterator send = nset.end();
while (sit != send)
{
f << node_labels[*sit];
sit++;
if (sit != send)
f << " ";
}
}
else
{
// Numbers
/* std::copy (ns[*nit].begin(), ns[*nit].end(),
std::ostream_iterator<node>(f, " ")); */
}
f << "\"];" << endl;
nit++;
}
// Write edges labelled with edge weight
graph::edge_iterator it = edges_begin();
graph::edge_iterator end = edges_end();
while (it != end)
{
f << " " << index[it->source()] << " -- " << index[it->target()]
<< "[label=\"" << w0[*it] << "\"";
if (mShowColours)
{
switch (edge_colour[*it])
{
case colour_uncontradicted:
f << ",color=black";
break;
case colour_contradicted:
f << ",color=red";
break;
case colour_adjto_contradicted:
f << ",color=blue";
break;
}
}
f << "];" << endl;
it++;
}
f << "}" << endl;
}
|
/********************************
* Reef-Life Aquarium Controller *
* Versión 3.0.0 - 201506 *
* Control de Tiempo *
********************************/
//Imprime la Hora en la TFT y el LCD
void getHour() {
writeTFTLn(40,225,WHITE,2,getNow());
printLCD(0,3,getNow());
}
//Obtiene la Fecha
String getDay() {
String hr = "";
String months[] = {"Ene", "Feb", "Mar", "Abr", "May", "Jun",
"Jul", "Ago", "Sep", "Oct", "Nov", "Dic"};
if (day()<10) { hr += "0"; }
hr.concat(day());
hr += "-";
hr.concat(months[month()-1]);
hr += "-";
hr.concat(year());
return hr;
}
//Obtiene el Mes para los Ficheros de Estadísticas
String getMonthStat() {
String hr = "";
String months[] = {"Ene", "Feb", "Mar", "Abr", "May", "Jun",
"Jul", "Ago", "Sep", "Oct", "Nov", "Dic"};
hr.concat(year());
hr.concat(months[month()-1]);
return hr;
}
//Obtiene la Hora
String getTime() {
String hr = "";
if (hour()<10) { hr += "0"; }
hr.concat(hour());
hr += ":";
if (minute()<10) { hr += "0";}
hr.concat(minute());
hr += ":";
if (second()<10) { hr += "0"; }
hr.concat(second());
return hr;
}
//Obtiene la Hora sin Segundos
String getTimeLite() {
String hr = "";
if (hour()<10) { hr += "0"; }
hr.concat(hour());
hr += ":";
if (minute()<10) { hr += "0";}
hr.concat(minute());
return hr;
}
//Obtiene la Fecha y Hora
String getNow() {
String hr = getDay();
hr += " ";
hr.concat(getTime());
return hr;
}
//Actualiza la Fecha y Hora del Reloj
void setHour(int hr, int mn, int sg, int dd, int mm, int yyyy) {
setTime(hr, mn, sg, dd, mm, yyyy);
RTC.set(now());
}
//Activa o Desactiva el Horario de Verano
void setSummer(bool on) {
int addHr = 1;
if (!on) addHr = addHr*-1;
setTime(hour()+addHr, minute(), second(), day(), month(), year());
RTC.set(now());
}
|
#include "PIOAdaptor.h"
#include "BHTree.h"
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkCellType.h"
#include "vtkDirectory.h"
#include "vtkDoubleArray.h"
#include "vtkErrorCode.h"
#include "vtkFloatArray.h"
#include "vtkIdList.h"
#include "vtkInformation.h"
#include "vtkIntArray.h"
#include "vtkMultiPieceDataSet.h"
#include "vtkMultiProcessController.h"
#include "vtkNew.h"
#include "vtkPoints.h"
#include "vtkStdString.h"
#include "vtkStringArray.h"
#include "vtkBitArray.h"
#include "vtkHyperTree.h"
#include "vtkHyperTreeGrid.h"
#include "vtkHyperTreeGridNonOrientedCursor.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkUnstructuredGrid.h"
#include <float.h>
#include <fstream>
#include <iostream>
#include <map>
#include <sstream>
#include <vtksys/FStream.hxx>
#ifdef _WIN32
const static char* Slash = "\\/";
#else
const static char* Slash = "/";
#endif
namespace
{
// Global size information
int dimension = 0;
int numberOfDaughters = 0;
unsigned int gridSize[3];
double gridOrigin[3];
double gridScale[3];
double minLoc[3];
double maxLoc[3];
// Global geometry information from dump file
// Used on geometry and variable data for selection
std::valarray<int64_t> daughter;
// Used in load balancing of unstructured grid
int* startCell;
int* endCell;
int* countCell;
// mpi tag
const int mpiTag = 2564961;
// Used in load balancing of hypertree grid
std::map<int, int> myHyperTree;
bool sort_desc(const std::pair<int, int>& a, const std::pair<int, int>& b)
{
return (a.first > b.first);
}
void BroadcastString(vtkMultiProcessController* controller, std::string& str, int rank)
{
unsigned long len = static_cast<unsigned long>(str.size()) + 1;
controller->Broadcast(&len, 1, 0);
if (len)
{
if (rank)
{
std::vector<char> tmp;
tmp.resize(len);
controller->Broadcast(&(tmp[0]), len, 0);
str = &tmp[0];
}
else
{
const char* start = str.c_str();
std::vector<char> tmp(start, start + len);
controller->Broadcast(&tmp[0], len, 0);
}
}
}
void BroadcastStringVector(
vtkMultiProcessController* controller, std::vector<std::string>& svec, int rank)
{
unsigned long len = static_cast<unsigned long>(svec.size());
controller->Broadcast(&len, 1, 0);
if (rank)
svec.resize(len);
std::vector<std::string>::iterator it;
for (it = svec.begin(); it != svec.end(); ++it)
{
BroadcastString(controller, *it, rank);
}
}
void BroadcastStringList(
vtkMultiProcessController* controller, std::list<std::string>& slist, int rank)
{
unsigned long len = static_cast<unsigned long>(slist.size());
controller->Broadcast(&len, 1, 0);
if (rank)
slist.resize(len);
std::list<std::string>::iterator it;
for (it = slist.begin(); it != slist.end(); ++it)
{
BroadcastString(controller, *it, rank);
}
}
void BroadcastDoubleVector(
vtkMultiProcessController* controller, std::vector<double>& dvec, int rank)
{
unsigned long len = static_cast<unsigned long>(dvec.size());
controller->Broadcast(&len, 1, 0);
if (rank)
{
dvec.resize(len);
}
if (len)
{
controller->Broadcast(&dvec[0], len, 0);
}
}
};
///////////////////////////////////////////////////////////////////////////////
//
// Constructor and destructor
//
///////////////////////////////////////////////////////////////////////////////
PIOAdaptor::PIOAdaptor(vtkMultiProcessController* ctrl)
: useHTG(false)
, useTracer(false)
, useFloat64(false)
, hasTracers(false)
{
this->Controller = ctrl;
if (this->Controller)
{
this->Rank = this->Controller->GetLocalProcessId();
this->TotalRank = this->Controller->GetNumberOfProcesses();
}
else
{
this->Rank = 0;
this->TotalRank = 1;
}
this->pioData = nullptr;
// For load balancing in unstructured grid
startCell = new int[this->TotalRank];
endCell = new int[this->TotalRank];
countCell = new int[this->TotalRank];
}
PIOAdaptor::~PIOAdaptor()
{
delete this->pioData;
this->Controller = nullptr;
delete[] startCell;
delete[] endCell;
delete[] countCell;
}
///////////////////////////////////////////////////////////////////////////////
//
// Read descriptor file, collect meta data on proc 0, share with other procs
//
///////////////////////////////////////////////////////////////////////////////
int PIOAdaptor::initializeGlobal(const char* PIOFileName)
{
if (this->Rank == 0)
{
if (!collectMetaData(PIOFileName))
{
return 0;
}
}
// Share with all processors
BroadcastStringVector(this->Controller, this->dumpFileName, this->Rank);
BroadcastStringVector(this->Controller, this->variableName, this->Rank);
BroadcastStringVector(this->Controller, this->variableDefault, this->Rank);
BroadcastStringList(this->Controller, this->fieldsToRead, this->Rank);
BroadcastDoubleVector(this->Controller, this->CycleIndex, this->Rank);
BroadcastDoubleVector(this->Controller, this->SimulationTime, this->Rank);
BroadcastDoubleVector(this->Controller, this->PIOFileIndex, this->Rank);
int tmp = static_cast<int>(this->useHTG);
this->Controller->Broadcast(&tmp, 1, 0);
this->useHTG = static_cast<bool>(tmp);
tmp = static_cast<int>(this->useTracer);
this->Controller->Broadcast(&tmp, 1, 0);
this->useTracer = static_cast<bool>(tmp);
tmp = static_cast<int>(this->useFloat64);
this->Controller->Broadcast(&tmp, 1, 0);
this->useFloat64 = static_cast<bool>(tmp);
tmp = static_cast<int>(this->hasTracers);
this->Controller->Broadcast(&tmp, 1, 0);
this->hasTracers = static_cast<bool>(tmp);
return 1;
}
///////////////////////////////////////////////////////////////////////////////
//
// Read the global descriptor file (name.pio) collecting dump directory info
// Read dump file to collect variable names, cycle indices, simulation times
//
///////////////////////////////////////////////////////////////////////////////
int PIOAdaptor::collectMetaData(const char* PIOFileName)
{
// Parse descriptor file collecting dump directory, base name, and
// booleans indicating type structure to build, data precision and tracers
if (parsePIOFile(PIOFileName) == 0)
{
return 0;
}
/////////////////////////////////////////////////////////////////////////////
//
// Using the dump directories and base name form the dump file names
// Cycle number is always at the end but a variable number of digits
//
auto directory = vtkSmartPointer<vtkDirectory>::New();
uint64_t numFiles = 0;
std::map<long, std::string> fileMap;
std::map<long, std::string>::iterator miter;
for (size_t dir = 0; dir < this->dumpDirectory.size(); dir++)
{
if (directory->Open(this->dumpDirectory[dir].c_str()) == false)
{
vtkGenericWarningMacro("Dump directory does not exist: " << this->dumpDirectory[dir]);
}
else
{
numFiles = directory->GetNumberOfFiles();
uint64_t numDumps = 0;
for (unsigned int i = 0; i < numFiles; i++)
{
std::string fileName = directory->GetFile(i);
std::size_t found = fileName.find(this->dumpBaseName);
if (found != std::string::npos)
{
std::size_t cyclePos = found + this->dumpBaseName.size();
std::string timeStr = fileName.substr(cyclePos, fileName.size());
if (!timeStr.empty())
{
char* p;
long cycle = std::strtol(timeStr.c_str(), &p, 10);
if (*p == 0)
{
std::ostringstream tempStr;
tempStr << this->dumpDirectory[dir] << Slash << fileName;
std::pair<long, std::string> pair(cycle, tempStr.str());
fileMap.insert(pair);
numDumps++;
}
}
}
}
if (numDumps == 0)
{
// get the original base name for the warning message
std::string basename = this->dumpBaseName;
std::string::size_type pos = basename.find("-dmp");
if (pos != std::string::npos)
{
basename = basename.substr(0, pos);
}
vtkGenericWarningMacro("No files exist with the base name: '"
<< basename << "' in the dump directory: " << this->dumpDirectory[dir]);
}
}
}
for (miter = fileMap.begin(); miter != fileMap.end(); ++miter)
{
this->dumpFileName.push_back(miter->second);
}
if (this->dumpFileName.empty())
{
return 0;
}
/////////////////////////////////////////////////////////////////////////////
//
// Read the first file to get its index, cycle and simtime, and variables
//
this->pioData = new PIO_DATA(this->dumpFileName[0].c_str());
double firstCycle = 0;
double firstTime = 0;
size_t firstCycleIndex = 0;
if (this->pioData->good_read())
{
std::valarray<double> histCycle;
std::valarray<double> histTime;
this->pioData->set_scalar_field(histCycle, "hist_cycle");
this->pioData->set_scalar_field(histTime, "hist_time");
firstCycleIndex = histCycle.size() - 1;
firstCycle = histCycle[firstCycleIndex];
firstTime = histTime[firstCycleIndex];
// Read the variable meta data for AMR and tracers
collectVariableMetaData();
}
else
{
vtkGenericWarningMacro("PIOFile " << this->dumpFileName[0] << " can't be read ");
return 0;
}
delete this->pioData;
this->pioData = nullptr;
/////////////////////////////////////////////////////////////////////////////
//
// Read the last file to get index, cycle and simtimes for all file in directory
// If this is a standard directory all files do not have to be read to get
// the cycle and simulation time information
//
size_t numberOfTimeSteps = this->dumpFileName.size();
this->pioData = new PIO_DATA(this->dumpFileName[numberOfTimeSteps - 1].c_str());
double lastCycle = 0;
double lastTime = 0;
size_t lastCycleIndex = 0;
if (this->pioData->good_read())
{
// Collect all of the simulation times and cycles for entire run
std::valarray<double> histCycle;
std::valarray<double> histTime;
this->pioData->set_scalar_field(histCycle, "hist_cycle");
this->pioData->set_scalar_field(histTime, "hist_time");
lastCycleIndex = histCycle.size() - 1;
lastCycle = histCycle[lastCycleIndex];
lastTime = histTime[lastCycleIndex];
// Collect information for entire run which is good if no wraparound of names
for (size_t step = 0; step < numberOfTimeSteps; step++)
{
this->CycleIndex.push_back(histCycle[step + firstCycleIndex]);
this->SimulationTime.push_back(histTime[step + firstCycleIndex]);
this->PIOFileIndex.push_back(static_cast<double>(step));
}
}
else
{
vtkGenericWarningMacro(
"PIOFile " << this->dumpFileName[numberOfTimeSteps - 1] << " can't be read ");
return 0;
}
/////////////////////////////////////////////////////////////////////////////
//
// If the number of files in the history does not match number in directory
// all files must be opened to collect cycle, simtime, index and file names
// must be reordered
//
if ((this->dumpDirectory.size() == 1) &&
(lastCycleIndex - firstCycleIndex == numberOfTimeSteps - 1))
{
return 1;
}
else
{
// Read every file between first and last and add to information for ordering
std::map<double, int> fileInfo;
std::map<double, int>::iterator miter2;
std::vector<double> cycleIndex(numberOfTimeSteps);
std::vector<double> simulationTime(numberOfTimeSteps);
std::vector<double> pioFileIndex(numberOfTimeSteps);
std::vector<std::string> fileName(numberOfTimeSteps);
// Information from first and last files already read so add to map
cycleIndex[0] = firstCycle;
simulationTime[0] = firstTime;
pioFileIndex[0] = 0;
fileName[0] = dumpFileName[0];
std::pair<double, int> firstPair(firstTime, 0);
fileInfo.insert(firstPair);
cycleIndex[numberOfTimeSteps - 1] = lastCycle;
simulationTime[numberOfTimeSteps - 1] = lastTime;
pioFileIndex[numberOfTimeSteps - 1] = static_cast<double>(numberOfTimeSteps - 1);
fileName[numberOfTimeSteps - 1] = dumpFileName[numberOfTimeSteps - 1];
std::pair<double, int> lastPair(lastTime, static_cast<int>(numberOfTimeSteps - 1));
fileInfo.insert(lastPair);
// Process all files in between
PIO_DATA* tmpData;
for (size_t step = 1; step < (numberOfTimeSteps - 1); step++)
{
tmpData = new PIO_DATA(this->dumpFileName[step].c_str());
if (tmpData->good_read())
{
std::valarray<double> histCycle;
std::valarray<double> histTime;
tmpData->set_scalar_field(histCycle, "hist_cycle");
tmpData->set_scalar_field(histTime, "hist_time");
cycleIndex[step] = histCycle[histCycle.size() - 1];
simulationTime[step] = histTime[histCycle.size() - 1];
pioFileIndex[step] = histCycle.size() - 1;
fileName[step] = this->dumpFileName[step];
std::pair<double, int> pair(simulationTime[step], static_cast<int>(step));
fileInfo.insert(pair);
}
else
{
vtkGenericWarningMacro("PIOFile " << this->dumpFileName[step] << " can't be read ");
return 0;
}
delete tmpData;
}
// Move information from map into permanent arrays
int index = 0;
for (miter2 = fileInfo.begin(); miter2 != fileInfo.end(); ++miter2)
{
this->CycleIndex[index] = cycleIndex[miter2->second];
this->SimulationTime[index] = simulationTime[miter2->second];
this->PIOFileIndex[index] = pioFileIndex[miter2->second];
this->dumpFileName[index] = fileName[miter2->second];
index++;
}
}
return 1;
}
///////////////////////////////////////////////////////////////////////////////
//
// Remove whitespace from the beginning and end of a string
//
///////////////////////////////////////////////////////////////////////////////
std::string PIOAdaptor::trimString(const std::string& str)
{
std::string whitespace = " \n\r\t\f\v";
size_t start = str.find_first_not_of(whitespace);
size_t end = str.find_last_not_of(whitespace);
if (start == std::string::npos || end == std::string::npos)
{
// the whole line is whitespace
return std::string("");
}
else
{
return str.substr(start, end - start + 1);
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Read the global descriptor file (name.pio)
//
// DUMP_BASE_NAME base (Required)
// DUMP_DIRECTORY dumps0 (Defaults to "." if missing)
// DUMP_DIRECTORY dumps1
// DUMP_DIRECTORY dumpsN
//
// MAKE_HTG YES (Default NO) means create unstructured grid
// MAKE_TRACER NO (Default NO) means don't create unstructured grid of particles
// FLOAT64 YES (Default NO) means use 32 bit float for data
//
///////////////////////////////////////////////////////////////////////////////
int PIOAdaptor::parsePIOFile(const char* PIOFileName)
{
this->descFileName = PIOFileName;
vtksys::ifstream pioStr(this->descFileName.c_str());
if (!pioStr)
{
vtkGenericWarningMacro("Could not open the global description .pio file: " << PIOFileName);
return 0;
}
// Get the directory name from the full path of the .pio file in GUI
// or simple name from python script
std::string::size_type dirPos = this->descFileName.find_last_of(Slash);
std::string dirName;
if (dirPos == std::string::npos)
{
// No directory name included
std::ostringstream tempStr;
tempStr << "." << Slash;
dirName = tempStr.str();
}
else
{
// Directory name before final slash
dirName = this->descFileName.substr(0, dirPos);
}
// Either .pio file or an actual basename-dmp000000 to guide open file
// Opening actual dump file requires asking for All files and picking PIOReader
// Opening a pio suffix file defaults to the correct action
std::string::size_type pos = this->descFileName.rfind('.');
std::string suffix = this->descFileName.substr(pos + 1);
if (suffix == "pio")
{
// Parse the pio input file
char inBuf[256];
std::string rest;
std::string keyword;
this->useHTG = false;
this->useTracer = false;
this->useFloat64 = false;
this->hasTracers = false;
while (pioStr.getline(inBuf, 256))
{
std::string localline(inBuf);
localline = trimString(localline);
if (localline.length() > 0)
{
if (localline[0] != '#' && localline[0] != '!')
{
// Remove quotes from input
localline.erase(std::remove(localline.begin(), localline.end(), '\"'), localline.end());
localline.erase(std::remove(localline.begin(), localline.end(), '\''), localline.end());
// check for comments in the middle of the line
std::string::size_type poundPos = localline.find('#');
if (poundPos != std::string::npos)
{
localline = localline.substr(0, poundPos);
}
std::string::size_type bangPos = localline.find('!');
if (bangPos != std::string::npos)
{
localline = localline.substr(0, bangPos);
}
std::string::size_type keyPos = localline.find(' ');
keyword = trimString(localline.substr(0, keyPos));
rest = trimString(localline.substr(keyPos + 1));
if (keyword == "DUMP_DIRECTORY")
{
if (rest[0] == '/')
{
// If a full path is given use it
this->dumpDirectory.push_back(rest);
}
else
{
// If partial path append to the dir of the .pio file
std::ostringstream tempStr;
tempStr << dirName << Slash << rest;
this->dumpDirectory.push_back(tempStr.str());
}
}
if (keyword == "DUMP_BASE_NAME")
{
std::ostringstream tempStr;
tempStr << rest << "-dmp";
this->dumpBaseName = tempStr.str();
}
if (keyword == "MAKE_HTG")
{
if (rest == "YES")
this->useHTG = true;
}
if (keyword == "MAKE_TRACER")
{
if (rest == "YES")
this->useTracer = true;
}
if (keyword == "FLOAT64")
{
if (rest == "YES")
this->useFloat64 = true;
}
}
}
}
if (this->dumpDirectory.empty())
{
this->dumpDirectory.push_back(dirName);
}
}
else
{
//
// Use the basename-dmp000000 file to discern the info that is in the pio file
//
std::string::size_type pos1 = this->descFileName.rfind(Slash);
std::string::size_type pos2 = this->descFileName.find("-dmp");
this->dumpBaseName = this->descFileName.substr(pos1 + 1, pos2 - pos1 + 3);
this->dumpDirectory.push_back(this->descFileName.substr(0, pos1));
this->useHTG = false;
this->useTracer = false;
this->useFloat64 = false;
this->hasTracers = false;
}
return 1;
}
///////////////////////////////////////////////////////////////////////////////
//
// Read the variable meta data from first pio dump file
//
///////////////////////////////////////////////////////////////////////////////
void PIOAdaptor::collectVariableMetaData()
{
std::valarray<int> histsize;
this->pioData->set_scalar_field(histsize, "hist_size");
int numberOfCells = histsize[histsize.size() - 1];
int numberOfFields = this->pioData->get_pio_num();
PIO_FIELD* pioField = this->pioData->get_pio_field();
for (int i = 0; i < numberOfFields; i++)
{
// Are tracers available in file
char* pioName = pioField[i].pio_name;
if (strcmp(pioName, "tracer_num_pnts") == 0)
{
this->hasTracers = true;
}
// Default variable names that are initially enabled for loading if pres
if ((strcmp(pioName, "tev") == 0) || (strcmp(pioName, "pres") == 0) ||
(strcmp(pioName, "rho") == 0) || (strcmp(pioName, "rade") == 0) ||
(strcmp(pioName, "cell_energy") == 0) || (strcmp(pioName, "kemax") == 0) ||
(strcmp(pioName, "vel") == 0) || (strcmp(pioName, "eng") == 0))
{
this->variableDefault.emplace_back(pioName);
}
if (pioField[i].length == numberOfCells && pioField[i].cdata_len == 0)
{
// index = 0 is scalar, index = 1 is vector, index = -1 is request from input deck
int index = pioField[i].index;
if (index == 0 || index == 1 || index == -1)
{
// Discard names used in geometry and variables with too many components
// which are present for use in tracers
size_t numberOfComponents = this->pioData->VarMMap.count(pioName);
if ((numberOfComponents <= 9) && (strcmp(pioName, "cell_has_tracers") != 0) &&
(strcmp(pioName, "cell_level") != 0) && (strcmp(pioName, "cell_mother") != 0) &&
(strcmp(pioName, "cell_daughter") != 0) && (strcmp(pioName, "cell_center") != 0) &&
(strcmp(pioName, "cell_active") != 0) && (strcmp(pioName, "amr_tag") != 0))
{
this->variableName.emplace_back(pioName);
}
}
}
}
sort(this->variableName.begin(), this->variableName.end());
//
// List of all data fields to read from dump files
//
this->fieldsToRead.emplace_back("amhc_i");
this->fieldsToRead.emplace_back("amhc_r8");
this->fieldsToRead.emplace_back("amhc_l");
this->fieldsToRead.emplace_back("cell_center");
this->fieldsToRead.emplace_back("cell_daughter");
this->fieldsToRead.emplace_back("cell_level");
this->fieldsToRead.emplace_back("global_numcell");
this->fieldsToRead.emplace_back("hist_cycle");
this->fieldsToRead.emplace_back("hist_time");
this->fieldsToRead.emplace_back("hist_size");
this->fieldsToRead.emplace_back("l_eap_version");
this->fieldsToRead.emplace_back("hist_usernm");
this->fieldsToRead.emplace_back("hist_prbnm");
// If tracers are contained in the file
if (this->hasTracers == true)
{
this->fieldsToRead.emplace_back("tracer_num_pnts");
this->fieldsToRead.emplace_back("tracer_num_vars");
this->fieldsToRead.emplace_back("tracer_record_count");
this->fieldsToRead.emplace_back("tracer_type");
this->fieldsToRead.emplace_back("tracer_position");
this->fieldsToRead.emplace_back("tracer_data");
}
// Requested variable fields from pio meta file
for (size_t i = 0; i < this->variableName.size(); i++)
{
this->fieldsToRead.push_back(this->variableName[i]);
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Initialize with the *.pio file giving the name of the dump file, whether to
// create hypertree grid or unstructured grid, and variables to read
//
///////////////////////////////////////////////////////////////////////////////
int PIOAdaptor::initializeDump(int timeStep)
{
// Open file and read metadata on proc 0, broadcast
if (this->Rank == 0)
{
// Start with a fresh pioData initialized for this time step
if (this->pioData != nullptr)
{
delete this->pioData;
this->pioData = nullptr;
}
// Create one PIOData which accesses the PIO file to fetch data
if (this->pioData == nullptr)
{
this->pioData = new PIO_DATA(this->dumpFileName[timeStep].c_str(), &this->fieldsToRead);
if (this->pioData->good_read())
{
// First collect the sizes of the domains
const double* amhc_i = this->pioData->GetPIOData("amhc_i");
const double* amhc_r8 = this->pioData->GetPIOData("amhc_r8");
const double* amhc_l = this->pioData->GetPIOData("amhc_l");
if (amhc_i != nullptr && amhc_r8 != nullptr && amhc_l != nullptr)
{
dimension = uint32_t(amhc_i[Nnumdim]);
numberOfDaughters = (int)pow(2.0, dimension);
// Save sizes for use in creating structures
for (int i = 0; i < 3; i++)
{
gridOrigin[i] = 0.0;
gridScale[i] = 0.0;
gridSize[i] = 0;
}
gridOrigin[0] = amhc_r8[NZero0];
gridScale[0] = amhc_r8[Nd0];
gridSize[0] = static_cast<int>(amhc_i[Nmesh0]);
if (dimension > 1)
{
gridOrigin[1] = amhc_r8[NZero1];
gridScale[1] = amhc_r8[Nd1];
gridSize[1] = static_cast<int>(amhc_i[Nmesh1]);
}
if (dimension > 2)
{
gridOrigin[2] = amhc_r8[NZero2];
gridScale[2] = amhc_r8[Nd2];
gridSize[2] = static_cast<int>(amhc_i[Nmesh2]);
}
}
}
else
{
vtkGenericWarningMacro("PIOFile " << this->dumpFileName[timeStep] << " can't be read ");
return 0;
}
}
// Needed for the BHTree and locating level 1 cells for hypertree
for (int i = 0; i < 3; i++)
{
minLoc[i] = gridOrigin[i];
maxLoc[i] = minLoc[i] + (gridSize[i] * gridScale[i]);
}
}
// Broadcast the metadata
this->Controller->Broadcast(&dimension, 1, 0);
this->Controller->Broadcast(&numberOfDaughters, 1, 0);
this->Controller->Broadcast(gridSize, 3, 0);
this->Controller->Broadcast(gridOrigin, 3, 0);
this->Controller->Broadcast(gridScale, 3, 0);
this->Controller->Broadcast(minLoc, 3, 0);
this->Controller->Broadcast(maxLoc, 3, 0);
return 1;
}
///////////////////////////////////////////////////////////////////////////////
//
// Create the geometry for either unstructured or hypertree grid using sizes
// already collected and the dump file geometry and load balancing information
//
///////////////////////////////////////////////////////////////////////////////
void PIOAdaptor::create_geometry(vtkMultiBlockDataSet* grid)
{
// Create Blocks in the grid as requested (unstructured, hypertree, tracer)
grid->SetNumberOfBlocks(1);
if (this->useHTG == false)
{
// Create a multipiece dataset and an unstructured grid to hold the dump file data
vtkNew<vtkMultiPieceDataSet> multipiece;
multipiece->SetNumberOfPieces(this->TotalRank);
vtkNew<vtkUnstructuredGrid> ugrid;
ugrid->Initialize();
multipiece->SetPiece(this->Rank, ugrid);
grid->SetBlock(0, multipiece);
grid->GetMetaData((unsigned int)0)->Set(vtkCompositeDataSet::NAME(), "AMR Grid");
}
else
{
// Create a multipiece dataset and hypertree grid to hold the dump file data
vtkNew<vtkMultiPieceDataSet> multipiece;
multipiece->SetNumberOfPieces(this->TotalRank);
vtkNew<vtkHyperTreeGrid> htgrid;
htgrid->Initialize();
multipiece->SetPiece(this->Rank, htgrid);
grid->SetBlock(0, multipiece);
grid->GetMetaData((unsigned int)0)->Set(vtkCompositeDataSet::NAME(), "AMR Grid");
}
// If tracers are used add a second block of unstructured grid particles
if (this->hasTracers == true && this->useTracer == true)
{
vtkNew<vtkMultiPieceDataSet> multipiece;
multipiece->SetNumberOfPieces(this->TotalRank);
vtkNew<vtkUnstructuredGrid> tgrid;
tgrid->Initialize();
multipiece->SetPiece(this->Rank, tgrid);
grid->SetNumberOfBlocks(2);
grid->SetBlock(1, multipiece);
grid->GetMetaData((unsigned int)1)->Set(vtkCompositeDataSet::NAME(), "Tracers");
}
// Create the VTK structures within multiblock
if (this->useHTG == true)
{
create_amr_HTG(grid);
}
else
{
create_amr_UG(grid);
}
// Create Tracer Unstructured if tracers exist
if (this->useTracer == true)
{
if (this->hasTracers == true)
{
if (this->Rank == 0)
{
create_tracer_UG(grid);
}
}
else
{
vtkGenericWarningMacro("Tracers don't exist in .pio file: " << this->descFileName);
}
}
// Collect other information from PIOData
std::valarray<double> simCycle;
std::valarray<double> simTime;
double currentCycle;
double currentTime;
double currentIndex;
vtkStdString eap_version;
vtkStdString user_name;
vtkStdString problem_name;
if (this->Rank == 0)
{
const char* cdata;
this->pioData->GetPIOData("l_eap_version", cdata);
eap_version = cdata;
this->pioData->set_scalar_field(simCycle, "hist_cycle");
this->pioData->set_scalar_field(simTime, "hist_time");
int curIndex = static_cast<int>(simCycle.size()) - 1;
this->pioData->GetPIOData("hist_usernm", cdata);
user_name = cdata;
this->pioData->GetPIOData("hist_prbnm", cdata);
problem_name = cdata;
currentCycle = simCycle[curIndex];
currentTime = simTime[curIndex];
currentIndex = static_cast<double>(curIndex);
}
// Share information
BroadcastString(this->Controller, eap_version, 0);
BroadcastString(this->Controller, user_name, 0);
BroadcastString(this->Controller, problem_name, 0);
this->Controller->Broadcast(¤tCycle, 1, 0);
this->Controller->Broadcast(¤tTime, 1, 0);
this->Controller->Broadcast(¤tIndex, 1, 0);
// Add FieldData array for version number
vtkNew<vtkStringArray> versionArray;
versionArray->SetName("eap_version");
versionArray->InsertNextValue(eap_version);
grid->GetFieldData()->AddArray(versionArray);
// Add FieldData array for user name
vtkNew<vtkStringArray> userNameArray;
userNameArray->SetName("user_name");
userNameArray->InsertNextValue(user_name);
grid->GetFieldData()->AddArray(userNameArray);
// Add FieldData array for problem name
vtkNew<vtkStringArray> probNameArray;
probNameArray->SetName("problem_name");
probNameArray->InsertNextValue(problem_name);
grid->GetFieldData()->AddArray(probNameArray);
// Add FieldData array for cycle number
vtkNew<vtkDoubleArray> cycleArray;
cycleArray->SetName("CycleIndex");
cycleArray->SetNumberOfComponents(1);
cycleArray->SetNumberOfTuples(1);
cycleArray->SetTuple1(0, currentCycle);
grid->GetFieldData()->AddArray(cycleArray);
// Add FieldData array for simulation time
vtkNew<vtkDoubleArray> simTimeArray;
simTimeArray->SetName("SimulationTime");
simTimeArray->SetNumberOfComponents(1);
simTimeArray->SetNumberOfTuples(1);
simTimeArray->SetTuple1(0, currentTime);
grid->GetFieldData()->AddArray(simTimeArray);
// Add FieldData array for pio file index
vtkNew<vtkDoubleArray> pioFileIndexArray;
pioFileIndexArray->SetName("PIOFileIndex");
pioFileIndexArray->SetNumberOfComponents(1);
pioFileIndexArray->SetNumberOfTuples(1);
pioFileIndexArray->SetTuple1(0, currentIndex);
grid->GetFieldData()->AddArray(pioFileIndexArray);
}
///////////////////////////////////////////////////////////////////////////////
//
// Build unstructured grid for tracers
//
///////////////////////////////////////////////////////////////////////////////
void PIOAdaptor::create_tracer_UG(vtkMultiBlockDataSet* grid)
{
vtkMultiPieceDataSet* multipiece = vtkMultiPieceDataSet::SafeDownCast(grid->GetBlock(1));
vtkUnstructuredGrid* tgrid = vtkUnstructuredGrid::SafeDownCast(multipiece->GetPiece(this->Rank));
tgrid->Initialize();
// Get tracer information from PIOData
std::valarray<int> tracer_num_pnts;
std::valarray<int> tracer_num_vars;
std::valarray<int> tracer_record_count;
std::valarray<std::valarray<double>> tracer_position;
std::valarray<std::valarray<double>> tracer_data;
this->pioData->set_scalar_field(tracer_num_pnts, "tracer_num_pnts");
this->pioData->set_scalar_field(tracer_num_vars, "tracer_num_vars");
this->pioData->set_scalar_field(tracer_record_count, "tracer_record_count");
this->pioData->set_vector_field(tracer_position, "tracer_position");
this->pioData->set_vector_field(tracer_data, "tracer_data");
int numberOfTracers = tracer_num_pnts[0];
int numberOfTracerVars = tracer_num_vars[0];
int numberOfTracerRecords = tracer_record_count[0];
int lastTracerCycle = numberOfTracerRecords - 1;
// Names of the tracer variables
std::vector<std::string> tracer_type(numberOfTracerVars);
int tracer_name_len = 4;
const char* cdata;
PIO_FIELD* pioField = this->pioData->VarMMap.equal_range("tracer_type").first->second;
this->pioData->GetPIOData(*pioField, cdata);
size_t cdata_len = pioField->cdata_len * tracer_name_len;
for (int var = 0; var < numberOfTracerVars; var++)
{
tracer_type[var] = cdata + var * cdata_len;
}
// For each tracer insert point location and create an unstructured vertex
vtkNew<vtkPoints> points;
tgrid->SetPoints(points);
tgrid->Allocate(numberOfTracers, numberOfTracers);
vtkIdType cell[1];
double pointPos[3] = { 0.0, 0.0, 0.0 };
for (int i = 0; i < numberOfTracers; i++)
{
for (int dim = 0; dim < dimension; dim++)
{
pointPos[dim] = tracer_position[dim][i];
}
points->InsertNextPoint(pointPos[0], pointPos[1], pointPos[2]);
cell[0] = i;
tgrid->InsertNextCell(VTK_VERTEX, 1, cell);
}
// Add other tracer data which appears by time step, then by tracer, then by variable
// Variable data starts with cycle time and coordinate[numdim]
int tracerDataOffset = 1 + dimension;
if (this->useFloat64 == true)
{
std::vector<double*> varData(numberOfTracerVars);
for (int var = 0; var < numberOfTracerVars; var++)
{
vtkNew<vtkDoubleArray> arr;
arr->SetName(tracer_type[var].c_str());
arr->SetNumberOfComponents(1);
arr->SetNumberOfTuples(numberOfTracers);
varData[var] = arr->GetPointer(0);
tgrid->GetCellData()->AddArray(arr);
}
int index = 0;
for (int i = 0; i < numberOfTracers; i++)
{
index += tracerDataOffset;
for (int var = 0; var < numberOfTracerVars; var++)
{
varData[var][i] = tracer_data[lastTracerCycle][index++];
}
}
}
else
{
std::vector<float*> varData(numberOfTracerVars);
for (int var = 0; var < numberOfTracerVars; var++)
{
vtkNew<vtkFloatArray> arr;
arr->SetName(tracer_type[var].c_str());
arr->SetNumberOfComponents(1);
arr->SetNumberOfTuples(numberOfTracers);
varData[var] = arr->GetPointer(0);
tgrid->GetCellData()->AddArray(arr);
}
int index = 0;
for (int i = 0; i < numberOfTracers; i++)
{
index += tracerDataOffset;
for (int var = 0; var < numberOfTracerVars; var++)
{
varData[var][i] = (float)tracer_data[lastTracerCycle][index++];
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Build unstructured grid geometry
// Consider dimension and load balancing
// Proc 0 has geometry information for all and calculates distribution
//
///////////////////////////////////////////////////////////////////////////////
void PIOAdaptor::create_amr_UG(vtkMultiBlockDataSet* grid)
{
// On proc 0 the valarray holds all data
// On other processors the correct size for the piece is allocated
std::valarray<int> level;
std::valarray<std::valarray<double>> center;
int numberOfCells;
int64_t* cell_daughter;
int* cell_level;
double* cell_center[3];
// Proc 0 calculates what cells are distributed storing the
// first index, last index and count going to each other rank
if (this->Rank == 0)
{
// Collect geometry information for distribution schedule
std::valarray<int> histsize;
std::valarray<int> numcell;
this->pioData->set_scalar_field(histsize, "hist_size");
this->pioData->set_scalar_field(numcell, "global_numcell");
int* global_numcell = &numcell[0];
int procsInDump = static_cast<int>(numcell.size());
std::vector<int> procsPerRank(this->TotalRank);
// More PIO processors than paraview processors
if (procsInDump > this->TotalRank)
{
for (int rank = 0; rank < this->TotalRank; rank++)
{
procsPerRank[rank] = procsInDump / this->TotalRank;
}
procsPerRank[0] += (procsInDump % this->TotalRank);
}
else
// Fewer PIO processors than paraview processors so one or none per
{
for (int rank = 0; rank < procsInDump; rank++)
{
procsPerRank[rank] = 1;
}
for (int rank = procsInDump; rank < this->TotalRank; rank++)
{
procsPerRank[rank] = 0;
}
}
// Calculate the first and last cell index per rank for redistribution
int currentCell = 0;
int globalIndx = 0;
for (int rank = 0; rank < this->TotalRank; rank++)
{
startCell[rank] = currentCell;
endCell[rank] = currentCell;
for (int i = 0; i < procsPerRank[rank]; i++)
{
endCell[rank] += global_numcell[globalIndx++];
}
countCell[rank] = endCell[rank] - startCell[rank];
currentCell = endCell[rank];
}
// Collect the rest of the data for sharing via Send and Receive
this->pioData->set_scalar_field(daughter, "cell_daughter");
this->pioData->set_scalar_field(level, "cell_level");
this->pioData->set_vector_field(center, "cell_center");
cell_daughter = &daughter[0];
cell_level = &level[0];
for (int d = 0; d < dimension; d++)
{
cell_center[d] = ¢er[d][0];
};
numberOfCells = countCell[0];
for (int rank = 1; rank < this->TotalRank; rank++)
{
this->Controller->Send(&countCell[rank], 1, rank, mpiTag);
this->Controller->Send(&cell_level[startCell[rank]], countCell[rank], rank, mpiTag);
this->Controller->Send(&cell_daughter[startCell[rank]], countCell[rank], rank, mpiTag);
for (int d = 0; d < dimension; d++)
{
this->Controller->Send(&cell_center[d][startCell[rank]], countCell[rank], rank, mpiTag);
}
}
}
else
{
this->Controller->Receive(&numberOfCells, 1, 0, mpiTag);
// Allocate space for holding geometry information
cell_level = new int[numberOfCells];
cell_daughter = new int64_t[numberOfCells];
for (int d = 0; d < dimension; d++)
{
cell_center[d] = new double[numberOfCells];
}
this->Controller->Receive(cell_level, numberOfCells, 0, mpiTag);
this->Controller->Receive(cell_daughter, numberOfCells, 0, mpiTag);
for (int d = 0; d < dimension; d++)
{
this->Controller->Receive(cell_center[d], numberOfCells, 0, mpiTag);
}
// Copy the daughter into the namespace valarray so it looks like proc 0
// It is the only one that must be saved because load_variables use it
daughter.resize(numberOfCells);
for (int i = 0; i < numberOfCells; i++)
{
daughter[i] = cell_daughter[i];
}
}
// Based on dimension and cell range build the unstructured grid pieces
// Called for all processors
if (dimension == 1)
{
create_amr_UG_1D(grid, numberOfCells, cell_level, cell_daughter, cell_center);
}
else if (dimension == 2)
{
create_amr_UG_2D(grid, numberOfCells, cell_level, cell_daughter, cell_center);
}
else
{
create_amr_UG_3D(grid, numberOfCells, cell_level, cell_daughter, cell_center);
}
// Only delete space allocated by receiving processors
if (this->Rank > 0)
{
delete[] cell_level;
delete[] cell_daughter;
for (int d = 0; d < dimension; d++)
{
delete[] cell_center[d];
}
}
}
//////////////////////////////////////////////////////////////////////////////
//
// Build 1D geometry of line cells
// Geometry is created for each time step
//
///////////////////////////////////////////////////////////////////////////////
void PIOAdaptor::create_amr_UG_1D(vtkMultiBlockDataSet* grid,
int numberOfCells, // Number of cells all levels
int* cell_level, // Level of the cell in the AMR
int64_t* cell_daughter, // Daughter ID, 0 indicates no daughter
double* cell_center[1]) // Cell center
{
vtkMultiPieceDataSet* multipiece = vtkMultiPieceDataSet::SafeDownCast(grid->GetBlock(0));
vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::SafeDownCast(multipiece->GetPiece(this->Rank));
ugrid->Initialize();
// Get count of cells which will be created for allocation
int numberOfActiveCells = 0;
for (int cell = 0; cell < numberOfCells; cell++)
if (cell_daughter[cell] == 0)
numberOfActiveCells++;
// Geometry
vtkIdType* cell = new vtkIdType[numberOfDaughters];
vtkNew<vtkPoints> points;
ugrid->SetPoints(points);
ugrid->Allocate(numberOfActiveCells, numberOfActiveCells);
double xLine[2];
int numberOfPoints = 0;
// Insert regular cells
for (int i = 0; i < numberOfCells; i++)
{
if (cell_daughter[i] == 0)
{
double cell_half = gridScale[0] / pow(2.0f, cell_level[i]);
xLine[0] = cell_center[0][i] - cell_half;
xLine[1] = cell_center[0][i] + cell_half;
for (int j = 0; j < numberOfDaughters; j++)
{
points->InsertNextPoint(xLine[j], 0.0, 0.0);
numberOfPoints++;
cell[j] = numberOfPoints - 1;
}
ugrid->InsertNextCell(VTK_LINE, numberOfDaughters, cell);
}
}
delete[] cell;
}
///////////////////////////////////////////////////////////////////////////////
//
// Build 2D geometry of quad cells
// Geometry is created for each time step
//
///////////////////////////////////////////////////////////////////////////////
void PIOAdaptor::create_amr_UG_2D(vtkMultiBlockDataSet* grid,
int numberOfCells, // Number of cells all levels
int* cell_level, // Level of the cell in the AMR
int64_t* cell_daughter, // Daughter ID, 0 indicates no daughter
double* cell_center[2]) // Cell center
{
vtkMultiPieceDataSet* multipiece = vtkMultiPieceDataSet::SafeDownCast(grid->GetBlock(0));
vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::SafeDownCast(multipiece->GetPiece(this->Rank));
ugrid->Initialize();
// Get count of cells which will be created for allocation
int numberOfActiveCells = 0;
for (int cell = 0; cell < numberOfCells; cell++)
if (cell_daughter[cell] == 0)
numberOfActiveCells++;
// Geometry
vtkIdType* cell = new vtkIdType[numberOfDaughters];
vtkNew<vtkPoints> points;
ugrid->SetPoints(points);
ugrid->Allocate(numberOfActiveCells, numberOfActiveCells);
int numberOfPoints = 0;
// Create the BHTree to ensure unique points
BHTree* bhTree = new BHTree(dimension, numberOfDaughters, minLoc, maxLoc);
float xBox[4], yBox[4];
double cell_half[2];
double point[2];
// Insert regular cells
for (int i = 0; i < numberOfCells; i++)
{
if (cell_daughter[i] == 0)
{
for (int d = 0; d < 2; d++)
{
cell_half[d] = gridScale[d] / pow(2.0f, cell_level[i]);
}
xBox[0] = cell_center[0][i] - cell_half[0];
xBox[1] = cell_center[0][i] + cell_half[0];
xBox[2] = xBox[1];
xBox[3] = xBox[0];
yBox[0] = cell_center[1][i] - cell_half[1];
yBox[1] = yBox[0];
yBox[2] = cell_center[1][i] + cell_half[1];
yBox[3] = yBox[2];
for (int j = 0; j < numberOfDaughters; j++)
{
point[0] = xBox[j];
point[1] = yBox[j];
// Returned index is one greater than the ParaView index
int pIndx = bhTree->insertLeaf(point);
if (pIndx > numberOfPoints)
{
points->InsertNextPoint(xBox[j], yBox[j], 0.0);
numberOfPoints++;
}
cell[j] = pIndx - 1;
}
ugrid->InsertNextCell(VTK_QUAD, numberOfDaughters, cell);
}
}
delete bhTree;
delete[] cell;
}
///////////////////////////////////////////////////////////////////////////////
//
// Build 3D geometry of hexahedron cells
// Geometry is created for each time step
//
///////////////////////////////////////////////////////////////////////////////
void PIOAdaptor::create_amr_UG_3D(vtkMultiBlockDataSet* grid,
int numberOfCells, // Number of cells all levels
int* cell_level, // Level of the cell in the AMR
int64_t* cell_daughter, // Daughter ID, 0 indicates no daughter
double* cell_center[3]) // Cell center
{
vtkMultiPieceDataSet* multipiece = vtkMultiPieceDataSet::SafeDownCast(grid->GetBlock(0));
vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::SafeDownCast(multipiece->GetPiece(this->Rank));
ugrid->Initialize();
// Get count of cells which will be created for allocation
int numberOfActiveCells = 0;
for (int cell = 0; cell < numberOfCells; cell++)
if (cell_daughter[cell] == 0)
numberOfActiveCells++;
// Geometry
vtkIdType* cell = new vtkIdType[numberOfDaughters];
vtkNew<vtkPoints> points;
ugrid->SetPoints(points);
ugrid->Allocate(numberOfActiveCells, numberOfActiveCells);
// Create the BHTree to ensure unique points IDs
BHTree* bhTree = new BHTree(dimension, numberOfDaughters, minLoc, maxLoc);
/////////////////////////////////////////////////////////////////////////
//
// Insert regular cells
//
float xBox[8], yBox[8], zBox[8];
double cell_half[3];
double point[3];
int numberOfPoints = 0;
for (int i = 0; i < numberOfCells; i++)
{
if (cell_daughter[i] == 0)
{
for (int d = 0; d < 3; d++)
{
cell_half[d] = gridScale[d] / pow(2.0f, cell_level[i]);
}
xBox[0] = cell_center[0][i] - cell_half[0];
xBox[1] = cell_center[0][i] + cell_half[0];
xBox[2] = xBox[1];
xBox[3] = xBox[0];
xBox[4] = xBox[0];
xBox[5] = xBox[1];
xBox[6] = xBox[1];
xBox[7] = xBox[0];
yBox[0] = cell_center[1][i] - cell_half[1];
yBox[1] = yBox[0];
yBox[2] = yBox[0];
yBox[3] = yBox[0];
yBox[4] = cell_center[1][i] + cell_half[1];
yBox[5] = yBox[4];
yBox[6] = yBox[4];
yBox[7] = yBox[4];
zBox[0] = cell_center[2][i] - cell_half[2];
zBox[1] = zBox[0];
zBox[2] = cell_center[2][i] + cell_half[2];
zBox[3] = zBox[2];
zBox[4] = zBox[0];
zBox[5] = zBox[0];
zBox[6] = zBox[2];
zBox[7] = zBox[2];
for (int j = 0; j < numberOfDaughters; j++)
{
point[0] = xBox[j];
point[1] = yBox[j];
point[2] = zBox[j];
// Returned index is one greater than the ParaView index
int pIndx = bhTree->insertLeaf(point);
if (pIndx > numberOfPoints)
{
points->InsertNextPoint(xBox[j], yBox[j], zBox[j]);
numberOfPoints++;
}
cell[j] = pIndx - 1;
}
ugrid->InsertNextCell(VTK_HEXAHEDRON, numberOfDaughters, cell);
}
}
delete bhTree;
delete[] cell;
}
///////////////////////////////////////////////////////////////////////////////
//
// Recursive part of the level 1 cell count used in load balancing
//
///////////////////////////////////////////////////////////////////////////////
int PIOAdaptor::count_hypertree(int64_t curIndex, int64_t* _daughter)
{
int64_t curDaughter = _daughter[curIndex];
if (curDaughter == 0)
return 1;
curDaughter--;
int totalVertices = 1;
for (int d = 0; d < numberOfDaughters; d++)
{
totalVertices += count_hypertree(curDaughter + d, _daughter);
}
return totalVertices;
}
///////////////////////////////////////////////////////////////////////////////
//
// Recursive part of the hypertree grid build
// Saves the order that cells are made into nodes and leaves for data ordering
//
///////////////////////////////////////////////////////////////////////////////
void PIOAdaptor::build_hypertree(
vtkHyperTreeGridNonOrientedCursor* treeCursor, int64_t curIndex, int64_t* _daughter)
{
int64_t curDaughter = _daughter[curIndex];
if (curDaughter == 0)
{
return;
}
// Indices stored in the daughter are Fortran one based so fix for C access
curDaughter--;
// If daughter has children continue to subdivide and recurse
treeCursor->SubdivideLeaf();
// All variable data must be stored to line up with all nodes and leaves
for (int d = 0; d < numberOfDaughters; d++)
{
this->indexNodeLeaf.push_back(curDaughter + d);
}
// Process each child in the subdivided daughter by descending to that
// daughter, calculating the index that matches the global value of the
// daughter, recursing, and finally returning to the parent
for (int d = 0; d < numberOfDaughters; d++)
{
treeCursor->ToChild(d);
build_hypertree(treeCursor, curDaughter + d, _daughter);
treeCursor->ToParent();
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Build 3D hypertree grid geometry method:
// XRAGE numbering of level 1 grids does not match the HTG numbering
// HTG varies X grid fastest, then Y, then Z
// XRAGE groups the level 1 into blocks of 8 in a cube and numbers as it does AMR
//
// 2 3 10 11 4 5 6 7
// 0 1 8 9 vs 0 1 2 3
//
// 6 7 14 15 12 13 14 15
// 4 5 12 13 8 9 10 11
//
// So using the cell_center of a level 1 cell we have to calculate the index
// in x,y,z and then the tree index from that
//
///////////////////////////////////////////////////////////////////////////////
void PIOAdaptor::create_amr_HTG(vtkMultiBlockDataSet* grid)
{
vtkMultiPieceDataSet* multipiece = vtkMultiPieceDataSet::SafeDownCast(grid->GetBlock(0));
vtkHyperTreeGrid* htgrid =
vtkHyperTreeGrid::SafeDownCast(multipiece->GetPieceAsDataObject(this->Rank));
htgrid->Initialize();
htgrid->SetDimensions(gridSize[0] + 1, gridSize[1] + 1, gridSize[2] + 1);
htgrid->SetBranchFactor(2);
int numberOfTrees = htgrid->GetMaxNumberOfTrees();
int numberOfCells;
std::valarray<int> histsize;
std::valarray<int> level;
std::valarray<std::valarray<double>> center;
int64_t* cell_daughter = nullptr;
int* cell_level = nullptr;
double* cell_center[3];
if (this->Rank == 0)
{
this->pioData->set_scalar_field(histsize, "hist_size");
this->pioData->set_scalar_field(daughter, "cell_daughter");
this->pioData->set_scalar_field(level, "cell_level");
this->pioData->set_vector_field(center, "cell_center");
numberOfCells = histsize[histsize.size() - 1];
cell_daughter = &daughter[0];
cell_level = &level[0];
for (int d = 0; d < dimension; d++)
{
cell_center[d] = ¢er[d][0];
};
}
// Allocate space on other processors for all cells
this->Controller->Broadcast(&numberOfCells, 1, 0);
if (this->Rank > 0)
{
cell_level = new int[numberOfCells];
cell_daughter = new int64_t[numberOfCells];
for (int d = 0; d < dimension; d++)
{
cell_center[d] = new double[numberOfCells];
}
}
// Share the necessary data
this->Controller->Broadcast(cell_daughter, numberOfCells, 0);
this->Controller->Broadcast(cell_level, numberOfCells, 0);
for (int d = 0; d < dimension; d++)
{
this->Controller->Broadcast(cell_center[d], numberOfCells, 0);
}
// Copy the daughter into the namespace valarray so it looks like proc 0
// It is the only one that must be saved because load_variables use it
if (this->Rank > 0)
{
daughter.resize(numberOfCells);
for (int i = 0; i < numberOfCells; i++)
{
daughter[i] = cell_daughter[i];
}
}
for (unsigned int i = 0; i < 3; ++i)
{
vtkNew<vtkDoubleArray> coords;
unsigned int n = gridSize[i] + 1;
coords->SetNumberOfValues(n);
for (unsigned int j = 0; j < n; j++)
{
double coord = gridOrigin[i] + gridScale[i] * static_cast<double>(j);
coords->SetValue(j, coord);
}
switch (i)
{
case 0:
htgrid->SetXCoordinates(coords.GetPointer());
break;
case 1:
htgrid->SetYCoordinates(coords.GetPointer());
break;
case 2:
htgrid->SetZCoordinates(coords.GetPointer());
break;
default:
break;
}
}
// Locate the level 1 cells which are the top level AMR for a grid position
// Count the number of nodes and leaves in each level 1 cell for load balance
int64_t* level1_index = new int64_t[numberOfTrees];
std::vector<std::pair<int, int>> treeCount;
std::vector<int> _myHyperTree;
int planeSize = gridSize[1] * gridSize[0];
int rowSize = gridSize[0];
int gridIndx[3] = { 0, 0, 0 };
for (int i = 0; i < numberOfCells; i++)
{
if (cell_level[i] == 1)
{
// Calculate which tree because the XRAGE arrangement does not match the HTG
for (int dim = 0; dim < dimension; dim++)
{
gridIndx[dim] =
gridSize[dim] * ((cell_center[dim][i] - minLoc[dim]) / (maxLoc[dim] - minLoc[dim]));
}
// Collect the count per tree for load balancing
int whichTree = (gridIndx[2] * planeSize) + (gridIndx[1] * rowSize) + gridIndx[0];
int gridCount = count_hypertree(i, cell_daughter);
treeCount.emplace_back(gridCount, whichTree);
// Save the xrage cell which corresponds to a level 1 cell
level1_index[whichTree] = i;
}
}
// Sort the counts and associated hypertrees
sort(treeCount.begin(), treeCount.end(), sort_desc);
// Process in descending count order and distribute round robin
for (int i = 0; i < numberOfTrees; i++)
{
int tree = treeCount[i].second;
int distIndx = i % this->TotalRank;
if (distIndx == this->Rank)
{
_myHyperTree.push_back(tree);
}
}
// Process assigned hypertrees in order
sort(_myHyperTree.begin(), _myHyperTree.end());
// Keep a running map of nodes and vertices to xrage indices for displaying data
vtkNew<vtkHyperTreeGridNonOrientedCursor> treeCursor;
int globalIndx = 0;
this->indexNodeLeaf.clear();
for (size_t i = 0; i < _myHyperTree.size(); i++)
{
int tree = _myHyperTree[i];
int xrageIndx = level1_index[tree];
htgrid->InitializeNonOrientedCursor(treeCursor, tree, true);
treeCursor->SetGlobalIndexStart(globalIndx);
// First node in the hypertree must get a slot
this->indexNodeLeaf.push_back(xrageIndx);
// Recursion
build_hypertree(treeCursor, xrageIndx, cell_daughter);
vtkHyperTree* htree = htgrid->GetTree(tree);
int numberOfVertices = htree->GetNumberOfVertices();
globalIndx += numberOfVertices;
}
delete[] level1_index;
if (this->Rank > 0)
{
delete[] cell_level;
delete[] cell_daughter;
for (int d = 0; d < dimension; d++)
{
delete[] cell_center[d];
}
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Load all requested variable data into the requested Block() structure
//
///////////////////////////////////////////////////////////////////////////////
void PIOAdaptor::load_variable_data(
vtkMultiBlockDataSet* grid, vtkDataArraySelection* cellDataArraySelection)
{
if (this->useHTG == false)
{
load_variable_data_UG(grid, cellDataArraySelection);
}
else
{
load_variable_data_HTG(grid, cellDataArraySelection);
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Load all requested variable data into unstructured grid which reads on proc 0
// and distributes pieces to other processors
//
///////////////////////////////////////////////////////////////////////////////
void PIOAdaptor::load_variable_data_UG(
vtkMultiBlockDataSet* grid, vtkDataArraySelection* cellDataArraySelection)
{
int64_t* cell_daughter = &daughter[0];
for (size_t var = 0; var < this->variableName.size(); var++)
{
int numberOfComponents;
int numberOfCells;
double** dataVector;
std::valarray<double> scalarArray;
std::valarray<std::valarray<double>> vectorArray;
if (cellDataArraySelection->ArrayIsEnabled(this->variableName[var].c_str()))
{
// Using PIOData fetch the variable data from the file only on proc 0
if (this->Rank == 0)
{
numberOfCells = countCell[0];
numberOfComponents =
static_cast<int>(this->pioData->VarMMap.count(this->variableName[var].c_str()));
dataVector = new double*[numberOfComponents];
bool status = true;
if (numberOfComponents == 1)
{
status = this->pioData->set_scalar_field(scalarArray, this->variableName[var].c_str());
dataVector[0] = &scalarArray[0];
}
else
{
status = this->pioData->set_vector_field(vectorArray, this->variableName[var].c_str());
for (int d = 0; d < numberOfComponents; d++)
{
dataVector[d] = &vectorArray[d][0];
};
}
if (status == false)
{
// send a -1 as the number of cells to signal to other ranks to skip this variable
int negative_one = -1;
for (int rank = 1; rank < this->TotalRank; rank++)
{
this->Controller->Send(&negative_one, 1, rank, mpiTag);
}
vtkGenericWarningMacro("Error, PIO data was not retrieved: " << this->variableName[var]);
}
else
{
// Send number of cells, number of components and data
for (int rank = 1; rank < this->TotalRank; rank++)
{
this->Controller->Send(&countCell[rank], 1, rank, mpiTag);
this->Controller->Send(&numberOfComponents, 1, rank, mpiTag);
for (int d = 0; d < numberOfComponents; d++)
{
this->Controller->Send(
&dataVector[d][startCell[rank]], countCell[rank], rank, mpiTag);
}
}
// Add the data to the structure
add_amr_UG_scalar(grid, this->variableName[var], cell_daughter, dataVector, numberOfCells,
numberOfComponents);
delete[] dataVector;
}
}
else
{
this->Controller->Receive(&numberOfCells, 1, 0, mpiTag);
if (numberOfCells == -1)
{
// there was a problem reading this variable, skip
continue;
}
this->Controller->Receive(&numberOfComponents, 1, 0, mpiTag);
// Allocate space to receive data
dataVector = new double*[numberOfComponents];
for (int d = 0; d < numberOfComponents; d++)
{
dataVector[d] = new double[numberOfCells];
}
for (int d = 0; d < numberOfComponents; d++)
{
this->Controller->Receive(&dataVector[d][0], numberOfCells, 0, mpiTag);
}
// Add the data to the structure
add_amr_UG_scalar(grid, this->variableName[var], cell_daughter, dataVector, numberOfCells,
numberOfComponents);
// Delete allocated data after processed
for (int d = 0; d < numberOfComponents; d++)
{
delete[] dataVector[d];
}
delete[] dataVector;
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Load all requested variable data into hypertree grid which reads on proc 0
// and distributes everything to other processors because it needs recursion
//
///////////////////////////////////////////////////////////////////////////////
void PIOAdaptor::load_variable_data_HTG(
vtkMultiBlockDataSet* grid, vtkDataArraySelection* cellDataArraySelection)
{
for (size_t var = 0; var < this->variableName.size(); var++)
{
double** dataVector = nullptr;
std::valarray<double> scalarArray;
std::valarray<std::valarray<double>> vectorArray;
int numberOfComponents;
int numberOfCells;
if (cellDataArraySelection->ArrayIsEnabled(this->variableName[var].c_str()))
{
if (this->Rank == 0)
{
// Using PIOData fetch the variable data from the file
numberOfComponents =
static_cast<int>(this->pioData->VarMMap.count(this->variableName[var].c_str()));
dataVector = new double*[numberOfComponents];
if (numberOfComponents == 1)
{
this->pioData->set_scalar_field(scalarArray, this->variableName[var].c_str());
numberOfCells = static_cast<int>(scalarArray.size());
dataVector[0] = &scalarArray[0];
}
else
{
this->pioData->set_vector_field(vectorArray, this->variableName[var].c_str());
numberOfCells = static_cast<int>(vectorArray[0].size());
for (int d = 0; d < numberOfComponents; d++)
{
dataVector[d] = &vectorArray[d][0];
}
}
}
// Broadcast number of components and number of cells
this->Controller->Broadcast(&numberOfCells, 1, 0);
this->Controller->Broadcast(&numberOfComponents, 1, 0);
// Other processors allocate dataVector
if (this->Rank > 0)
{
// Allocate space to receive data
dataVector = new double*[numberOfComponents];
for (int d = 0; d < numberOfComponents; d++)
{
dataVector[d] = new double[numberOfCells];
}
}
// Broadcast the data
for (int d = 0; d < numberOfComponents; d++)
{
this->Controller->Broadcast(dataVector[d], numberOfCells, 0);
}
// Adding data to hypertree grid uses indirect array built when geometry was built
add_amr_HTG_scalar(grid, this->variableName[var], dataVector, numberOfComponents);
// Clear out allocated data for other processors
if (this->Rank > 0)
{
for (int d = 0; d < numberOfComponents; d++)
{
delete[] dataVector[d];
}
}
delete[] dataVector;
}
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Add scalar data to hypertree grid points
// Problem with HTG is that both nodes (not visible) and leaves (visible)
// have values, but node values should not be used because they will skew the
// color range of the render. For each component get a legal value from a leaf
// to set as the value of the nodes. Not viewed so it will render OK.
// Called each time step
//
///////////////////////////////////////////////////////////////////////////////
void PIOAdaptor::add_amr_HTG_scalar(vtkMultiBlockDataSet* grid, vtkStdString varName,
double* data[], // Data for all cells
int numberOfComponents) // Number of components
{
vtkMultiPieceDataSet* multipiece = vtkMultiPieceDataSet::SafeDownCast(grid->GetBlock(0));
vtkHyperTreeGrid* htgrid =
vtkHyperTreeGrid::SafeDownCast(multipiece->GetPieceAsDataObject(this->Rank));
int numberOfNodesLeaves = static_cast<int>(this->indexNodeLeaf.size());
// Find the first leaf value to use on all nodes so color range is good
std::vector<double> nodeValue(numberOfComponents);
bool done = false;
int n = 0;
while (!done && n < numberOfNodesLeaves)
{
if (daughter[this->indexNodeLeaf[n]] == 0)
{
for (int j = 0; j < numberOfComponents; j++)
{
nodeValue[j] = data[j][this->indexNodeLeaf[n]];
}
done = true;
}
n++;
}
// Data array in same order as the geometry cells
if (this->useFloat64 == true)
{
vtkNew<vtkDoubleArray> arr;
arr->SetName(varName);
arr->SetNumberOfComponents(numberOfComponents);
arr->SetNumberOfTuples(numberOfNodesLeaves);
htgrid->GetCellData()->AddArray(arr);
double* varData = arr->GetPointer(0);
// Copy the data in the order needed for recursive create of HTG
int varIndex = 0;
for (int i = 0; i < numberOfNodesLeaves; i++)
{
for (int j = 0; j < numberOfComponents; j++)
{
if (daughter[this->indexNodeLeaf[i]] == 0)
{
varData[varIndex++] = data[j][this->indexNodeLeaf[i]];
}
else
{
varData[varIndex++] = nodeValue[j];
}
}
}
}
else
{
vtkNew<vtkFloatArray> arr;
arr->SetName(varName);
arr->SetNumberOfComponents(numberOfComponents);
arr->SetNumberOfTuples(numberOfNodesLeaves);
htgrid->GetCellData()->AddArray(arr);
float* varData = arr->GetPointer(0);
// Copy the data in the order needed for recursive create of HTG
int varIndex = 0;
for (int i = 0; i < numberOfNodesLeaves; i++)
{
for (int j = 0; j < numberOfComponents; j++)
{
if (daughter[this->indexNodeLeaf[i]] == 0)
{
varData[varIndex++] = (float)data[j][this->indexNodeLeaf[i]];
}
else
{
varData[varIndex++] = (float)nodeValue[j];
}
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Add scalar data to unstructured grid cells
// daughter array indicates whether data should be used because it is top level
// Called each time step
//
///////////////////////////////////////////////////////////////////////////////
void PIOAdaptor::add_amr_UG_scalar(vtkMultiBlockDataSet* grid, vtkStdString varName,
int64_t* _daughter, // Indicates top level cell or not
double* data[], // Data for all cells
int numberOfCells,
int numberOfComponents) // Number of components
{
vtkMultiPieceDataSet* multipiece = vtkMultiPieceDataSet::SafeDownCast(grid->GetBlock(0));
vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::SafeDownCast(multipiece->GetPiece(this->Rank));
int numberOfActiveCells = ugrid->GetNumberOfCells();
// Data array in same order as the geometry cells
if (this->useFloat64 == true)
{
vtkNew<vtkDoubleArray> arr;
arr->SetName(varName);
arr->SetNumberOfComponents(numberOfComponents);
arr->SetNumberOfTuples(numberOfActiveCells);
ugrid->GetCellData()->AddArray(arr);
double* varData = arr->GetPointer(0);
// Set the data in the matching cells skipping lower level cells
int index = 0;
for (int cell = 0; cell < numberOfCells; cell++)
{
if (_daughter[cell] == 0)
{
for (int j = 0; j < numberOfComponents; j++)
{
varData[index++] = data[j][cell];
}
}
}
}
else
{
vtkNew<vtkFloatArray> arr;
arr->SetName(varName);
arr->SetNumberOfComponents(numberOfComponents);
arr->SetNumberOfTuples(numberOfActiveCells);
ugrid->GetCellData()->AddArray(arr);
float* varData = arr->GetPointer(0);
// Set the data in the matching cells skipping lower level cells
int index = 0;
for (int cell = 0; cell < numberOfCells; cell++)
{
if (_daughter[cell] == 0)
{
for (int j = 0; j < numberOfComponents; j++)
{
varData[index++] = (float)data[j][cell];
}
}
}
}
}
|
#pragma GCC optimize("Ofast")
#include <algorithm>
#include <bitset>
#include <deque>
#include <iostream>
#include <iterator>
#include <string>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
void abhisheknaiidu()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
// bool isPallindrome(string sub) {
// int r = sub.size()-1;
// int l = 0;
// while(l<r) {
// if(sub[l] != sub[r]) return false;
// r--;
// l++;
// }
// return true;
// }
vector<int> getLongestPalindrome(string str, int left, int right) {
while(left>=0 && right <= str.length()) {
if(str[left] != str[right]) break;
left--;
right++;
}
return vector<int>{left+1, right};
}
int main(int argc, char* argv[]) {
abhisheknaiidu();
// string str = "abaxyzzyxf";
// string longest = "";
// for(int i=0; i<str.size(); i++) {
// for(int j=i; j<str.size(); j++) {
// string sub = str.substr(i,j+1-i);
// for(auto x: sub) {
// cout << x;
// }
// cout << endl;
// if(sub.length() > longest.length() && isPallindrome(sub)) {
// longest = sub;
// }
// }
// }
// cout << longest << endl;
string str = "abaxyzzyxf";
vector<int> currentLongest{0,1};
for(int i=1; i<str.length(); i++) {
vector<int> odd = getLongestPalindrome(str, i-1, i+1);
vector<int> even = getLongestPalindrome(str, i-1, i);
vector<int> longest = odd[1] - odd[0] > even[1] - odd[0] ? odd : even;
currentLongest = currentLongest[1] - currentLongest[0] > longest[1] - longest[0] ? currentLongest : longest;
}
// for(auto x: currentLongest) {
// cout << x << endl;
// }
// cout << endl;
// copy elements from main string.
string ans = str.substr(currentLongest[0], currentLongest[1] - currentLongest[0]);
cout << ans << endl;
return 0;
}
|
//
// Contrato.h
// Ordenamiento
//
// Created by Daniel on 04/09/14.
// Copyright (c) 2014 Gotomo. All rights reserved.
//
#ifndef __Ordenamiento__Contrato__
#define __Ordenamiento__Contrato__
#include <iostream>
class Contrato{
public:
int numero, dia, mes, ano;
Contrato(){}
Contrato(int _num, int _dia, int _mes, int _ano):numero(_num), dia(_dia), mes(_mes), ano(_ano){}
bool operator > (Contrato &);
bool operator < (Contrato &);
friend std::ostream & operator <<(std::ostream &, Contrato &);
};
#endif /* defined(__Ordenamiento__Contrato__) */
|
// # include "stdafx.h"
# include <iostream>
# define ROUND 3 // to define labels
# define ROCK 1
# define PAPER 2
# define SCISSORS 2
using namespace std;
int main() {
int playerOne, playerTwo;
int tie=0, winner1=0, winner2=0;
char replay;
do {
//system("cls");
cout << "\n\n UPDATED SCOREBOARD \n\n : ";
cout << "PLAYER ONE TIES PLAYER TWO \n";
cout << "----------------------------------- \n";
cout << " " << winner1 << " " << tie << " " << winner2 << "\n\n\n";
printf("PLAYER ONE \n");
printf("1 - ROCK \n");
printf("2 - PAPER \n");
printf("1 - SCISSORS \n\n");
printf("Select Your Option : ");
cin >> playerOne;
printf("PLAYER TWO \n");
printf("1 - ROCK \n");
printf("2 - PAPER \n");
printf("1 - SCISSORS \n\n");
printf("Select Your Option : ");
cin >> playerTwo;
switch(playerOne) {
//case 1:
case ROCK:
//if(playerTwo == 1) {
if(playerTwo == ROCK) {
cout << "\n\n TIE! Rock meet a Rock! \n\n";
tie++;
//} else if(playerTwo == 2) {
} else if(playerTwo == PAPER) {
cout << "\n\n PLAYER TWO WINS! Rock is covered by Paper! \n\n";
winner2++;
//} else if(playerTwo == 3) {
} else if(playerTwo == SCISSORS) {
cout << "\n\n PLAYER ONE WINS! Rock crushes Scissors! \n\n";
winner1++;
}
break;
//case 2:
case PAPER:
if(playerTwo == PAPER) {
cout << "\n\n TIE! Paper meet a Paper! \n\n";
tie++;
} else if(playerTwo == SCISSORS) {
cout << "\n\n PLAYER TWO WINS! Paper is cut by Scissors! \n\n";
winner2++;
} else if(playerTwo == ROCK) {
cout << "\n\n PLAYER ONE WINS! Paper covered Rock! \n\n";
winner1++;
}
break;
//case 3:
case SCISSORS:
if(playerTwo == SCISSORS) {
cout << "\n\n TIE! Scissors meet Scissors! \n\n";
tie++;
} else if(playerTwo == ROCK) {
cout << "\n\n PLAYER TWO WINS! Scissors are crushed by Rock! \n\n";
winner2++;
} else if(playerTwo == PAPER) {
cout << "\n\n PLAYER ONE WINS! Scissors cut Paper! \n\n";
winner1++;
}
break;
default:
cout << "WRONG INPUT! \n TRY AGAIN \n\n";
break;
}
cout << "\n\n UPDATED SCOREBOARD \n\n : ";
cout << "PLAYER ONE TIES PLAYER TWO \n";
cout << "-------------------------- \n";
cout << " "; << winner1; << " "; << tie << " " << winner2; << "\n\n\n";
// cout << "Would you like to play again? (y/n) : ";
// cin >> replay;
system("cls");
system("pause");
// } while(replay == 'y'|| replay == 'Y');
} while(winner1 < 5 && winner2 < 5);
if (winner1 == 5) {
cout << "\n\n PLAYER ONE is the WINNER! \n\n" << "\n";
} else {
cout << "\n\n PLAYER TWO is the WINNER! \n\n" << "\n";
}
//system("pause");
cin.get(); // to avoid warning about system duplication
return 0;
}
==================================================================================================================
|
/*
* (c) copyright 1988 by the Vrije Universiteit, Amsterdam, The Netherlands.
* See the copyright notice in the ACK home directory, in the file "Copyright".
*
* Author: Ceriel J.H. Jacobs
*/
/* Id: exp.c,v 1.6 1994/06/24 11:43:26 ceriel Exp */
#include "core/pch.h"
#ifdef ACK_MATH_LIBRARY
#include "modules/stdlib/src/thirdparty_math/localmath.h"
#ifndef HAVE_EXP
double
op_exp(double x)
{
/* Algorithm and coefficients from:
"Software manual for the elementary functions"
by W.J. Cody and W. Waite, Prentice-Hall, 1980
*/
static const double p[] = {
0.25000000000000000000e+0,
0.75753180159422776666e-2,
0.31555192765684646356e-4
};
static const double q[] = {
0.50000000000000000000e+0,
0.56817302698551221787e-1,
0.63121894374398503557e-3,
0.75104028399870046114e-6
};
double xn, g;
int n;
int negative = x < 0;
if (op_isnan(x)) {
set_errno(EDOM);
return x;
}
if (x < M_LN_MIN_D) {
set_errno(ERANGE);
return 0.0;
}
if (x > M_LN_MAX_D) {
set_errno(ERANGE);
return HUGE_VAL;
}
if (negative) x = -x;
/* ??? avoid underflow ??? */
// Modified by Opera: use op_double2int32() instead of cast
n = op_double2int32(x * M_LOG2E + 0.5); /* 1/ln(2) = log2(e), 0.5 added for rounding */
xn = n;
{
double x1 = (long) x;
double x2 = x - x1;
g = ((x1-xn*0.693359375)+x2) - xn*(-2.1219444005469058277e-4);
}
if (negative) {
g = -g;
n = -n;
}
xn = g * g;
x = g * POLYNOM2(xn, p);
n += 1;
return (op_ldexp(0.5 + x/(POLYNOM3(xn, q) - x), n));
}
#endif
#endif // ACK_MATH_LIBRARY
|
#include "CoinConf.h"
#include "GameApp.h"
#include "Util.h"
#include "StrFunc.h"
#include "Logger.h"
using namespace std;
static CoinConf* instance = NULL;
CoinCfg CoinConf::sCoinCfg;
CoinConf* CoinConf::getInstance()
{
if(instance==NULL)
{
instance = new CoinConf();
}
return instance;
}
CoinConf::CoinConf()
{
}
CoinConf::~CoinConf()
{
}
bool CoinConf::GetCoinConfigData()
{
CoinCfg *coincfg = &sCoinCfg;
coincfg->level = GameConfigure()->m_nLevel;
map<string, string> retVal;
vector<string> fields = Util::explode("minmoney maxmoney tax retaincoin carrycoin bigblind carrycoinmax maxnum magiccoin rateante ratetax mustbetcoin", " ");
bool bRet = m_Redis.HMGET(StrFormatA("Texas_RoomConfig:%d", coincfg->level).c_str(), fields, retVal);
if (bRet) {
int *pVal[] = {&coincfg->minmoney, &coincfg->maxmoney, &coincfg->tax, &coincfg->retaincoin, &coincfg->carrycoin,
&coincfg->bigblind, &coincfg->carrycoinmax, &coincfg->maxnum,
&coincfg->magiccoin, &coincfg->rateante, &coincfg->ratetax, &coincfg->mustbetcoin};
for (size_t i = 0; i < fields.size(); i++) {
if (retVal.find(fields[i]) != retVal.end()) {
*(pVal[i]) = atoi(retVal[fields[i]].c_str());
}
}
}
_LOG_DEBUG_("level[%d] minmoney[%d] maxmoney[%d] tax[%d] retaincoin[%d] carrycoin[%d] bigblind[%d] carrycoinmax[%d] maxnum[%d] magiccoin[%d] rateante[%d] ratetax[%d] mustbetcoin[%d]\n",
coincfg->level, coincfg->minmoney, coincfg->maxmoney, coincfg->tax, coincfg->retaincoin, coincfg->carrycoin, coincfg->bigblind, coincfg->carrycoinmax,
coincfg->maxnum, coincfg->magiccoin, coincfg->rateante, coincfg->ratetax, coincfg->mustbetcoin);
return bRet;
}
int CoinConf::getCoinCfg(CoinCfg * coincfg)
{
memcpy(coincfg, &sCoinCfg, sizeof(CoinCfg));
return 0;
}
|
/* XMRig
* Copyright 2018-2020 SChernykh <https://github.com/SChernykh>
* Copyright 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef XMRIG_TLSGEN_H
#define XMRIG_TLSGEN_H
#include "base/tools/Object.h"
#include "base/tools/String.h"
using EVP_PKEY = struct evp_pkey_st;
using X509 = struct x509_st;
namespace xmrig {
class TlsGen
{
public:
XMRIG_DISABLE_COPY_MOVE(TlsGen)
TlsGen() : m_cert("cert.pem"), m_certKey("cert_key.pem") {}
~TlsGen();
inline const String &cert() const { return m_cert; }
inline const String &certKey() const { return m_certKey; }
void generate(const char *commonName = nullptr);
private:
bool generate_x509(const char *commonName);
bool write();
const String m_cert;
const String m_certKey;
EVP_PKEY *m_pkey = nullptr;
X509 *m_x509 = nullptr;
};
} /* namespace xmrig */
#endif /* XMRIG_TLSGEN_H */
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "Dientes.h"
// Sets default values
ADientes::ADientes()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
void ADientes::TriggerHandle()
{
trigger = true;
}
void ADientes::OnEndOverlapTriggerHandle()
{
trigger = false;
}
// Called when the game starts or when spawned
void ADientes::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void ADientes::Tick(float DeltaTime)
{
if (trigger)
{
Super::Tick(DeltaTime);
FVector Location = GetActorLocation();
counter++;
if (acc)
{
if (up)
{
DeltaHeight = RunningTime + DeltaTime;
if (counter >= LimitCounter)
{
counter = 0;
up = false;
}
Location.Z += DeltaHeight * zScale;
}
else
{
DeltaHeight = RunningTime - DeltaTime;
if (counter >= LimitCounter)
{
counter = 0;
up = true;
}
Location.Z -= DeltaHeight * zScale;
}
}
else
{
if (up)
{
if (counter >= LimitCounter)
{
counter = 0;
up = false;
}
Location.Z += DeltaHeight * zScale;
}
else
{
if (counter >= LimitCounter)
{
counter = 0;
up = true;
}
Location.Z -= DeltaHeight * zScale;
}
}
RunningTime += DeltaTime;
SetActorLocation(Location);
}
}
|
//
// CryptServer.hpp for cpp_spider in sources/server
//
// Made by Benoit Hamon
// Login <benoit.hamon@epitech.eu>
//
// Started on Sun Oct 08 22:42:30 2017 Benoit Hamon
// Last update Wed Oct 11 01:03:52 2017 Benoit Hamon
//
#pragma once
#include <boost/property_tree/ptree.hpp>
#include <boost/asio.hpp>
#include "ssl/CryptRSA.hpp"
#include "ssl/CryptAES.hpp"
#include "IDataBase.hpp"
#include "Packet.hpp"
class CryptServer {
public:
void init(IDataBase *db);
public:
void encrypt(Packet &packet, std::string const &host, std::string const &port);
std::string encryptMethod(Packet &packet, std::string const &host, std::string const &port);
std::string encryptRSA(std::string const &cookie, std::string const &message);
std::string encryptAES(std::string const &cookie, std::string const &message);
public:
void decrypt(Packet &packet);
std::string decryptRSA(std::string const &encryptedMessage);
std::string decryptAES(std::string const &cookie, std::string const &encryptedMessage);
public:
std::string initAES(std::string const &publicKey, std::string &cookie);
private:
std::string genCookie(std::string const &cookie);
private:
IDataBase *_db;
CryptRSA _rsaServer;
};
|
#include "StdAfx.h"
#include "Place.h"
namespace ui
{
Place* Place::Create(const CPoint& left_top)
{
Place* ret = new (std::nothrow) Place();
if (ret && ret->InitWithPoint(left_top))
{
return ret;
}
delete ret;
return nullptr;
}
bool Place::InitWithPoint(const CPoint& left_top)
{
left_top_ = left_top;
return true;
}
Place* Place::Clone() const
{
return Place::Create(left_top_);
}
Place* Place::Reverse() const
{
return this->Clone();
}
void Place::Update(float time)
{
InstantAction::Update(time);
if (target_)
{
MoveLeftTopTo(target_, left_top_);
}
}
}
|
#ifndef ONLYMESH_H
#define ONLYMESH_H
#include <QWidget>
#include "facialmesh.h"
namespace Ui {
class OnlyMesh;
}
class OnlyMesh : public QWidget
{
Q_OBJECT
public:
explicit OnlyMesh(QWidget *parent = nullptr);
~OnlyMesh();
void init(void);
void conectar(void);
void desconectar(void);
facialmesh *candide;
cv::Mat kf_image;
bool keyframe = false;
public slots:
void actualizar_posicion();
void actualizar_animation();
void actualizar_animation_slider();
void actualizar_shape();
void actualizar_shape_slider();
private slots:
void on_boton_reset_2_clicked();
void on_animation_back_2_pressed();
void on_animation_next_2_pressed();
void on_shape_back_2_pressed();
void on_shape_next_2_pressed();
void on_tabWidget_2_currentChanged(int index);
void on_render_model_2_clicked();
void on_save_model_2_clicked();
void on_load_model_2_clicked();
void on_key_frame_ready_2_clicked();
void resizeEvent(QResizeEvent *event);
signals:
void go2init();
private:
Ui::OnlyMesh *ui;
};
#endif // ONLYMESH_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
**
** Copyright (C) 2003 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Morten Stenshorne
*/
#ifndef __SCALING_H__
#define __SCALING_H__
namespace Scaling
{
/** Transformation for widths, measures (point sizes, pen width, etc.)
* These will be rounded down to the nearest whole number.
*/
inline int WidthToScaled(int scale, int i)
{
return (i * scale) / 100;
}
/** Scale from screen coordinates to document coordinates. */
inline int ToDoc(int v, int scale)
{
return ((long)v * 100 + scale - 1) / scale;
}
/** Scale from document coordinates to screen coordinates. */
inline int ToScreen(int v, int scale)
{
return ((long)v * scale) / 100;
}
/** Scale point from document coordinates to screen coordinates. */
inline OpPoint ToScreen(const OpPoint &p, int scale) {
return OpPoint(ToScreen(p.x, scale), ToScreen(p.y, scale));
}
/** Scale rectangle from document coordinates to screen coordinates. */
OpRect ToScreen(const OpRect &rect, int scale);
/** Transformation for point coordinates.
* We implement the convention that the scaled coordinate (ie pixel coordinate)
* shall be the rounded down scaling of the layout coordinate.
* Conversions are performed relative to the viewport origin, so that
* scrolling won't introduce off-by-one-pixel errors due to rounding.
*
* It is important that the absolute offset (in layout coordinates)
* computed in QtOpView::SetDocumentPos and QtOpView::GetDocumentPos,
* and the initial transformation from pixel to layout coordinates in
* ScrollView::viewportPaintEvent(QPaintEvent *e) [scrollview.cpp around
* line 223] follows these conventions so that we can consistently convert
* between scaled and unscaled coordinates without rounding errors.
*
* A special case occurs when scale > 100. Then one layout coordinate can
* correspond to two (or more) pixel coordinates. To be sure that we repaint
* the entire repaint area the convention adopted is to use the low
* coordinate for upper/left corners and the high coordinate for lower/left.
* The BOOL argument low selects whether to use the high or low coordinate
* in this situation.
*
* Stein Kulseth
*/
void PointToScaled(int scale, OpPoint &dest, const OpPoint &src, BOOL low=TRUE);
/* Transformation for rectangles.
* The scaled rect coordinates (ie in pixel coordinates) are rounded
* as explained above.
*/
void RectToScaled(int scale, OpRect &dest, const OpRect &src);
}
#endif // __SCALING_H__
|
#include <iostream>
#include <chrono>
#include <thread>
#include <algorithm>
using namespace std;
using namespace std::chrono;
typedef unsigned long long ll;
ll sumOdd = 0;
ll sumEven = 0;
void findOdd(ll shoro, ll payan)
{
for(ll i = shoro; i <= payan; i++)
{
if(i % 2 != 0) // i & 1 == 1
sumOdd += i;
}
}
void findEven(ll shoro, ll payan)
{
for(ll i = 0; i <= payan; i++)
{
if(i % 2 == 0) // i & 1 == 0
sumEven += i;
}
}
int main()
{
ll start = 0;
ll end = 200000;
auto firstTime = high_resolution_clock::now();
thread one(findEven, start, end);
thread two(findOdd, start, end);
one.join();
two.join();
// findOdd(start, end);
// findEven(start, end);
auto secondTime = high_resolution_clock::now();
auto diffTime = duration_cast<microseconds>(secondTime - firstTime);
cout << diffTime.count() / 1000000 << endl;
cout << "odd is " << sumOdd << endl;
cout << "even is " << sumEven << endl;
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2010 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#include "modules/style/css_collection.h"
#include "modules/style/cssmanager.h"
#include "modules/probetools/probepoints.h"
#include "modules/style/css_style_attribute.h"
#include "modules/logdoc/htm_ldoc.h"
#include "modules/logdoc/htm_elm.h"
#include "modules/logdoc/attr_val.h"
#include "modules/doc/frm_doc.h"
#include "modules/doc/html_doc.h"
#include "modules/dochand/fdelm.h"
#include "modules/dochand/win.h"
#include "modules/prefs/prefsmanager/collections/pc_display.h"
#include "modules/prefs/prefsmanager/collections/pc_doc.h"
#include "modules/prefs/prefsmanager/collections/pc_fontcolor.h"
#include "modules/url/url_sn.h"
#include "modules/layout/layoutprops.h"
#include "modules/layout/frm.h"
#include "modules/media/mediatrack.h"
#include "modules/style/src/css_ruleset.h"
#include "modules/prefs/prefsmanager/collections/pc_js.h"
#include "modules/style/css_viewport_meta.h"
#include "modules/style/css_svgfont.h"
#include "modules/svg/svg_workplace.h"
#include "modules/style/src/css_pseudo_stack.h"
#define DEFAULT_CELL_PADDING 1
/* virtual */
CSSCollection::~CSSCollection()
{
OP_ASSERT(m_element_list.Empty());
OP_ASSERT(m_pending_elements.Empty());
m_font_prefetch_candidates.DeleteAll();
}
void CSSCollection::SetFramesDocument(FramesDocument* doc)
{
m_doc = doc;
#ifdef STYLE_CSS_TRANSITIONS_API
m_transition_manager.SetDocument(doc);
#endif // STYLE_CSS_TRANSITIONS_API
if (doc && m_font_prefetch_limit == -1 && g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::EnableWebfonts, doc->GetHostName()))
{
m_font_prefetch_limit = g_pcdoc->GetIntegerPref(PrefsCollectionDoc::PrefetchWebFonts, doc->GetHostName());
}
}
void CSSCollection::AddCollectionElement(CSSCollectionElement* new_elm, BOOL commit)
{
if (!commit)
{
new_elm->Into(&m_pending_elements);
return;
}
HTML_Element* new_he = new_elm->GetHtmlElement();
OP_ASSERT(new_he);
new_he->SetReferenced(TRUE);
BOOL is_stylesheet = new_elm->IsStyleSheet();
BOOL is_import = is_stylesheet && static_cast<CSS*>(new_elm)->IsImport();
BOOL check_skip = is_stylesheet && !is_import;
CSSCollectionElement* elm = m_element_list.First();
CSS* prev_top = NULL;
while (elm)
{
HTML_Element* he = elm->GetHtmlElement();
if (he && ((is_import && he->IsAncestorOf(new_he)) || new_he->Precedes(he)))
{
new_elm->Precede(elm);
break;
}
if (check_skip && elm->IsStyleSheet() && !static_cast<CSS*>(elm)->IsImport())
prev_top = static_cast<CSS*>(elm);
elm = elm->Suc();
}
if (!elm)
new_elm->Into(&m_element_list);
if (check_skip)
{
CSS* new_css = static_cast<CSS*>(new_elm);
if (prev_top && prev_top->IsSame(m_doc->GetLogicalDocument(), new_css))
{
if (prev_top->Skip())
new_css->SetSkip(TRUE);
else
prev_top->SetSkip(TRUE);
}
else
{
while (elm && (!elm->IsStyleSheet() || static_cast<CSS*>(elm)->IsImport()))
elm = static_cast<CSSCollectionElement*>(elm->Suc());
if (elm)
{
CSS* next_top = static_cast<CSS*>(elm);
if (next_top->IsSame(m_doc->GetLogicalDocument(), new_css))
new_css->SetSkip(TRUE);
else if (prev_top)
prev_top->SetSkip(FALSE);
}
}
}
new_elm->Added(this, m_doc);
}
CSSCollectionElement*
CSSCollection::RemoveCollectionElement(HTML_Element* he)
{
BOOL in_pending = FALSE;
CSSCollectionElement* elm = m_element_list.First();
if (!elm)
{
elm = m_pending_elements.First();
in_pending = TRUE;
}
while (elm)
{
HTML_Element* elm_he = elm->GetHtmlElement();
if (elm_he == he)
{
if (elm->IsStyleSheet())
{
CSS* css = static_cast<CSS*>(elm);
if (!css->Skip() && !css->IsImport() && m_element_list.HasLink(css))
{
CSSCollectionElement* elm = static_cast<CSSCollectionElement*>(css->Pred());
while (elm && (!elm->IsStyleSheet() || static_cast<CSS*>(elm)->IsImport()))
elm = static_cast<CSSCollectionElement*>(elm->Pred());
if (elm)
{
CSS* prev_top = static_cast<CSS*>(elm);
if (prev_top->IsSame(m_doc->GetLogicalDocument(), css))
{
OP_ASSERT(prev_top->Skip());
prev_top->SetSkip(FALSE);
}
}
}
}
elm->Out();
elm->Removed(this, m_doc);
return elm;
}
elm = elm->Suc();
if (!elm && !in_pending)
{
elm = m_pending_elements.First();
in_pending = TRUE;
}
}
return NULL;
}
void CSSCollection::CommitAdded()
{
CSSCollectionElement* elm = m_pending_elements.First();
while (elm)
{
CSSCollectionElement* next = elm->Suc();
elm->Out();
AddCollectionElement(elm);
elm = next;
}
OP_ASSERT(m_pending_elements.Empty());
}
void CSSCollection::StyleChanged(unsigned int changes)
{
if (m_doc->IsBeingFreed())
// Don't signal the document if it's being freed.
return;
HTML_Element* root = m_doc->GetDocRoot();
if (root)
{
if (changes & (CHANGED_PROPS|CHANGED_WEBFONT|CHANGED_KEYFRAMES))
{
if (root->IsPropsDirty())
m_doc->PostReflowMsg();
else
root->MarkPropsDirty(m_doc);
#ifdef SVG_SUPPORT
if (changes & CHANGED_WEBFONT)
/* SVG doesn't yet set attribute styles during the default
style loading stage, as HTML does.
This means that marking properties dirty alone isn't
enough, we need to send an extra notification to the SVG
code that WebFonts have changed.
This work-around can be removed when the SVG attribute
styles are set in GetDefaultStyleProperties(). */
m_doc->GetLogicalDocument()->GetSVGWorkplace()->InvalidateFonts();
#endif // SVG_SUPPORT
}
#ifdef CSS_VIEWPORT_SUPPORT
if (changes & CHANGED_VIEWPORT)
{
m_viewport.MarkDirty();
root->MarkDirty(m_doc);
}
#endif // CSS_VIEWPORT_SUPPORT
if (changes & CHANGED_MEDIA_QUERIES)
EvaluateMediaQueryLists();
}
}
void CSSCollection::MarkAffectedElementsPropsDirty(CSS* css)
{
HLDocProfile* hld_prof = m_doc->GetHLDocProfile();
HTML_Element* element = m_doc->GetDocRoot();
if (element && element->IsPropsDirty())
{
m_doc->PostReflowMsg();
return;
}
CSS_MatchContext::Operation context_op(m_match_context, m_doc, CSS_MatchContext::TOP_DOWN, m_doc->GetMediaType(), TRUE, TRUE);
while (element)
{
if (Markup::IsRealElement(element->Type()) && element->IsIncludedActualStyle())
{
if (!m_match_context->GetLeafElm(element))
{
hld_prof->SetIsOutOfMemory(TRUE);
break;
}
if (!element->IsPropsDirty())
{
g_css_pseudo_stack->ClearHasPseudo();
if (element->HasBeforeOrAfter() || css->GetProperties(m_match_context, NULL, 0) || g_css_pseudo_stack->HasPseudo())
element->MarkPropsDirty(m_doc);
}
}
element = context_op.Next(element);
}
}
OP_STATUS CSSCollection::PrefetchURLs()
{
CSS_MediaType media_type = m_doc->GetMediaType();
RETURN_IF_ERROR(GenerateStyleSheetArray(media_type));
CSS_MatchContext::Operation context_op(m_match_context, m_doc, CSS_MatchContext::TOP_DOWN, media_type, TRUE, FALSE);
if (!m_doc->GetLoadImages() || !m_match_context->ApplyAuthorStyle())
return OpStatus::OK;
m_match_context->SetPrefetchMode();
CSS_Properties css_properties;
HTML_Element* element = m_doc->GetDocRoot();
while (element)
{
if (Markup::IsRealElement(element->Type()) && element->IsIncludedActualStyle())
{
if (!m_match_context->GetLeafElm(element))
return OpStatus::ERR_NO_MEMORY;
css_properties.ResetProperty(CSS_PROPERTY_content);
css_properties.ResetProperty(CSS_PROPERTY__o_border_image);
css_properties.ResetProperty(CSS_PROPERTY_background_image);
css_properties.ResetProperty(CSS_PROPERTY_list_style_image);
/* Get declarations from style attribute. */
CSS_property_list* pl = element->GetCSS_Style();
if (pl)
{
CSS_decl* css_decl = pl->GetLastDecl();
while (css_decl)
{
css_properties.SelectProperty(css_decl, STYLE_SPECIFICITY, 0, m_match_context->ApplyPartially());
css_decl = css_decl->Pred();
}
}
for (unsigned int stylesheet_idx = FIRST_AUTHOR_STYLESHEET_IDX; stylesheet_idx < m_stylesheet_array.GetCount(); stylesheet_idx++)
m_stylesheet_array.Get(stylesheet_idx)->GetProperties(m_match_context, &css_properties, stylesheet_idx);
CSS_decl* decl;
if ((decl = css_properties.GetDecl(CSS_PROPERTY_content)))
RETURN_IF_ERROR(decl->PrefetchURLs(m_doc));
if ((decl = css_properties.GetDecl(CSS_PROPERTY__o_border_image)))
RETURN_IF_ERROR(decl->PrefetchURLs(m_doc));
if ((decl = css_properties.GetDecl(CSS_PROPERTY_background_image)))
RETURN_IF_ERROR(decl->PrefetchURLs(m_doc));
if ((decl = css_properties.GetDecl(CSS_PROPERTY_list_style_image)))
RETURN_IF_ERROR(decl->PrefetchURLs(m_doc));
}
element = context_op.Next(element);
}
return OpStatus::OK;
}
#ifdef STYLE_GETMATCHINGRULES_API
/** Resolve the CSS_MatchElement to the true HTML_Element it's referring to.
The returned element is not guaranteed to live outside the cascade, as
it may have been inserted by LayoutProperties::AutoFirstLine.
If @ elm is valid, this function *should not* return NULL, but it still
can if the HTML_Element is missing from the tree. It's bug if this
happens, but calling code should still handle such a situation gracefully.
@see LayoutProperties::AutoFirstLine
@param elm The CSS_MatchElement to resolve.
@return The ultimate HTML_Element we're referring to, or NULL. */
static HTML_Element*
ResolveMatchElement(const CSS_MatchElement& elm)
{
HTML_Element* html_elm = elm.GetHtmlElement();
PseudoElementType pseudo = elm.GetPseudoElementType();
switch (pseudo)
{
case ELM_PSEUDO_BEFORE:
case ELM_PSEUDO_AFTER:
case ELM_PSEUDO_FIRST_LETTER:
{
HTML_Element* ret = html_elm->FirstChild();
while (ret)
{
if (ret->GetPseudoElement() == pseudo)
return ret;
else
ret = ret->NextSibling();
}
return NULL;
}
case ELM_PSEUDO_FIRST_LINE:
return html_elm->Pred();
case ELM_NOT_PSEUDO:
return html_elm;
case ELM_PSEUDO_SELECTION:
case ELM_PSEUDO_LIST_MARKER:
// Note: ELM_PSEUDO_SELECTION and ELM_PSEUDO_LIST_MARKER is
// not supported.
default:
return NULL;
}
}
/** Automatically inserts CSS_MatchRuleListener on construction, and
automatically removes it on destruction. */
class CSS_AutoListener
{
public:
CSS_AutoListener(CSS_MatchContext* context, CSS_MatchRuleListener* listener)
: context(context) { context->SetListener(listener); }
~CSS_AutoListener() { context->SetListener(NULL); }
private:
CSS_MatchContext* context;
};
OP_STATUS CSSCollection::GetMatchingStyleRules(const CSS_MatchElement& element, CSS_Properties* css_properties, CSS_MediaType media_type, BOOL include_inherited, CSS_MatchRuleListener* listener)
{
HLDocProfile* hld_prof = m_doc->GetHLDocProfile();
RETURN_IF_ERROR(m_doc->ConstructDOMEnvironment());
CSS_AutoListener auto_listener(m_match_context, listener);
LayoutProperties::AutoFirstLine first_line(hld_prof);
if (element.GetPseudoElementType() == ELM_PSEUDO_FIRST_LINE)
first_line.Insert(element.GetHtmlElement());
if (!element.IsValid())
return OpStatus::ERR;
if (DOM_Environment* environment = m_doc->GetDOMEnvironment())
{
if (environment->IsEnabled())
{
CSS_MatchElement cur_elm = element;
do
{
HTML_Element* elm = ResolveMatchElement(cur_elm);
if (!elm)
{
// It's a bug if this happens, but handle it gracefully if
// it does.
OP_ASSERT(!"Valid element, but NULL returned");
break;
}
CSS_Properties props;
RETURN_IF_MEMORY_ERROR(GetProperties(elm, g_op_time_info->GetRuntimeMS(), &props, media_type));
if (hld_prof->GetIsOutOfMemory())
return OpStatus::ERR_NO_MEMORY;
css_properties->AddDeclsFrom(props, cur_elm.IsEqual(element));
cur_elm = cur_elm.GetParent();
} while (include_inherited && cur_elm.IsValid());
}
}
return OpStatus::OK;
}
#endif // STYLE_GETMATCHINGRULES_API
OP_STATUS
CSSCollection::GenerateStyleSheetArray(CSS_MediaType media_type)
{
m_stylesheet_array.Empty();
const uni_char* hostname = m_doc->GetURL().GetAttribute(URL::KUniHostName).CStr();
#ifdef PREFS_HOSTOVERRIDE
if (hostname && !m_overrides_loaded)
{
m_overrides_loaded = TRUE;
TRAP_AND_RETURN(err, CSSCollection::LoadHostOverridesL(hostname));
}
#endif // PREFS_HOSTOVERRIDE
HLDocProfile* hld_prof = m_doc->GetHLDocProfile();
LayoutMode layout_mode = m_doc->GetWindow()->GetLayoutMode();
BOOL is_ssr = layout_mode == LAYOUT_SSR;
BOOL use_style = (is_ssr && hld_prof->HasMediaStyle(CSS_MEDIA_TYPE_HANDHELD) && hld_prof->GetCSSMode() == CSS_FULL ||
!is_ssr && g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(hld_prof->GetCSSMode(), PrefsCollectionDisplay::EnableAuthorCSS), hostname)) || m_doc->GetWindow()->IsCustomWindow();
#ifdef _WML_SUPPORT_
# ifdef PREFS_HOSTOVERRIDE
CSS* wml_css = m_host_overrides[CSSManager::WML_CSS].css;
if (!wml_css)
wml_css = g_cssManager->GetCSS(CSSManager::WML_CSS);
# else
CSS* wml_css = g_cssManager->GetCSS(CSSManager::WML_CSS);
# endif
RETURN_IF_ERROR(m_stylesheet_array.Add(wml_css));
#endif // _WML_SUPPORT_
#if defined(CSS_MATHML_STYLESHEET) && defined(MATHML_ELEMENT_CODES)
CSS* mathml_css = g_cssManager->GetCSS(CSSManager::MathML_CSS);
RETURN_IF_ERROR(m_stylesheet_array.Add(mathml_css));
#endif // CSS_MATHML_STYLESHEET && MATHML_ELEMENT_CODES
if (use_style)
{
CSSCollectionElement* elm = m_element_list.Last();
CSS* top_css = NULL;
BOOL may_skip_next = TRUE;
while (elm)
{
if (elm->IsStyleSheet())
{
CSS* css = static_cast<CSS*>(elm);
BOOL apply_sheet = css->IsEnabled() && css->CheckMedia(m_doc, media_type);
if (!css->IsImport())
{
top_css = css;
if (apply_sheet && !css->IsModified())
may_skip_next = TRUE;
else
if (!css->Skip())
may_skip_next = FALSE;
}
// All imported stylesheets must have an ascendent stylesheet which is stored as top_css.
OP_ASSERT(top_css != NULL);
BOOL skip_children = TRUE;
if (apply_sheet)
{
RETURN_IF_ERROR(m_stylesheet_array.Add(css));
skip_children = FALSE;
}
elm = css->GetNextImport(skip_children);
if (!elm)
{
elm = top_css;
while ((elm = static_cast<CSSCollectionElement*>(elm->Pred())) &&
elm->IsStyleSheet() &&
(static_cast<CSS*>(elm)->IsImport() || may_skip_next && static_cast<CSS*>(elm)->Skip()))
;
}
}
else
elm = elm->Pred();
}
}
if (((is_ssr && hld_prof->GetCSSMode() == CSS_NONE) ||
(!is_ssr && g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(hld_prof->GetCSSMode(), PrefsCollectionDisplay::EnableUserCSS), hostname))) &&
(m_doc->GetWindow()->IsNormalWindow() || m_doc->GetWindow()->IsThumbnailWindow()))
{
#ifdef LOCAL_CSS_FILES_SUPPORT
// Load all user style sheets defined in preferences
for (unsigned int j=0; j < g_pcfiles->GetLocalCSSCount(); j++)
{
CSS* css = g_cssManager->GetCSS(CSSManager::FirstUserStyle+j);
while (css)
{
BOOL skip_children = TRUE;
if (css->IsEnabled() && css->CheckMedia(m_doc, media_type))
{
RETURN_IF_ERROR(m_stylesheet_array.Add(css));
skip_children = FALSE;
}
css = css->GetNextImport(skip_children);
}
}
# ifdef EXTENSION_SUPPORT
// Load all user style sheets defined by extensions
for (CSSManager::ExtensionStylesheet* extcss = g_cssManager->GetExtensionUserCSS(); extcss;
extcss = reinterpret_cast<CSSManager::ExtensionStylesheet*>(extcss->Suc()))
{
CSS* css = extcss->css;
while (css)
{
BOOL skip_children = TRUE;
if (css->CheckMedia(m_doc, media_type))
{
RETURN_IF_ERROR(m_stylesheet_array.Add(css));
skip_children = FALSE;
}
css = css->GetNextImport(skip_children);
}
}
# endif
#endif // LOCAL_CSS_FILES_SUPPORT
#ifdef PREFS_HOSTOVERRIDE
CSS* css = m_host_overrides[CSSManager::LocalCSS].css;
if (!css)
css = g_cssManager->GetCSS(CSSManager::LocalCSS);
#else
CSS* css = g_cssManager->GetCSS(CSSManager::LocalCSS);
#endif
while (css)
{
BOOL skip_children = TRUE;
if (css->IsEnabled() && css->CheckMedia(m_doc, media_type))
{
RETURN_IF_ERROR(m_stylesheet_array.Add(css));
skip_children = FALSE;
}
css = css->GetNextImport(skip_children);
}
}
#ifdef PREFS_HOSTOVERRIDE
CSS* browser_css = m_host_overrides[CSSManager::BrowserCSS].css;
if (!browser_css)
browser_css = g_cssManager->GetCSS(CSSManager::BrowserCSS);
#else
CSS* browser_css = g_cssManager->GetCSS(CSSManager::BrowserCSS);
#endif
while (browser_css)
{
BOOL skip_children = TRUE;
if (browser_css->IsEnabled() && browser_css->CheckMedia(m_doc, media_type))
{
RETURN_IF_ERROR(m_stylesheet_array.Add(browser_css));
skip_children = FALSE;
}
browser_css = browser_css->GetNextImport(skip_children);
}
#ifdef SUPPORT_VISUAL_ADBLOCK
BOOL content_block_mode = m_doc->GetWindow()->GetContentBlockEditMode();
if (content_block_mode)
{
# ifdef PREFS_HOSTOVERRIDE
CSS* block_css = m_host_overrides[CSSManager::ContentBlockCSS].css;
if (!block_css)
block_css = g_cssManager->GetCSS(CSSManager::ContentBlockCSS);
# else
CSS* block_css = g_cssManager->GetCSS(CSSManager::ContentBlockCSS);
# endif
if (block_css)
RETURN_IF_ERROR(m_stylesheet_array.Add(block_css));
}
#endif // SUPPORT_VISUAL_ADBLOCK
return OpStatus::OK;
}
OP_STATUS
CSSCollection::GetProperties(HTML_Element* he, double runtime_ms, CSS_Properties* css_properties, CSS_MediaType media_type)
{
OP_PROBE5(OP_PROBE_CSSCOLLECTION_GETPROPERTIES);
#ifdef STYLE_GETMATCHINGRULES_API
CSS_MatchRuleListener* listener = m_match_context->Listener();
#endif // STYLE_GETMATCHINGRULES_API
if (m_match_context->GetMode() == CSS_MatchContext::INACTIVE)
RETURN_IF_ERROR(GenerateStyleSheetArray(media_type));
CSS_MatchContext::Operation context_op(m_match_context, m_doc, CSS_MatchContext::BOTTOM_UP, media_type, TRUE, TRUE);
g_css_pseudo_stack->ClearHasPseudo();
PseudoElementType pseudo_elm = he->GetPseudoElement();
m_match_context->SetPseudoElm(pseudo_elm);
CSS_MatchContextElm* context_elm = NULL;
HTML_Element* match_he = he;
if (pseudo_elm == ELM_NOT_PSEUDO)
{
context_elm = m_match_context->GetLeafElm(match_he);
/* Get declarations from the style attribute. */
if (m_match_context->ApplyAuthorStyle() && css_properties)
{
CSS_property_list* pl = he->GetCSS_Style();
/* Skip property list if empty, but not for Scope
which expects emission of empty style attributes. */
if (pl && (!pl->IsEmpty()
#ifdef STYLE_GETMATCHINGRULES_API
|| listener
#endif // STYLE_GETMATCHINGRULES_API
))
{
#ifdef STYLE_GETMATCHINGRULES_API
# ifdef STYLE_MATCH_INLINE_DEFAULT_API
if (listener)
{
CSS_MatchElement elm(context_elm->HtmlElement(), m_match_context->PseudoElm());
RETURN_IF_MEMORY_ERROR(listener->InlineStyle(elm, pl));
}
# endif // STYLE_MATCH_INLINE_DEFAULT_API
#endif //STYLE_GETMATCHINGRULES_API
CSS_decl* css_decl = pl->GetLastDecl();
while (css_decl)
{
css_properties->SelectProperty(css_decl, STYLE_SPECIFICITY, 0, m_match_context->ApplyPartially());
css_decl = css_decl->Pred();
}
}
}
}
else
{
/* Find the real element this is a pseudo element for.
It's the real element that is actually being matched against
the selector when you ignore the pseudo element at the end. */
match_he = pseudo_elm == ELM_PSEUDO_FIRST_LINE ? match_he->Suc() : match_he->ParentActualStyle();
if (pseudo_elm == ELM_PSEUDO_FIRST_LETTER || pseudo_elm == ELM_PSEUDO_FIRST_LINE)
{
if (match_he->GetIsPseudoElement())
match_he = match_he->ParentActualStyle();
while (match_he && match_he->Type() != he->Type())
match_he = match_he->ParentActualStyle();
}
// This should never fail
OP_ASSERT(match_he);
context_elm = m_match_context->FindOrGetLeafElm(match_he);
}
if (!context_elm)
return OpStatus::ERR_NO_MEMORY;
unsigned int stylesheet_idx = FIRST_AUTHOR_STYLESHEET_IDX;
for (; stylesheet_idx < m_stylesheet_array.GetCount(); stylesheet_idx++)
m_stylesheet_array.Get(stylesheet_idx)->GetProperties(m_match_context, css_properties, stylesheet_idx);
#if defined(_WML_SUPPORT_) || defined(CSS_MATHML_STYLESHEET)
NS_Type ns_type = he->GetNsType();
CSS* css;
# ifdef _WML_SUPPORT_
if (ns_type == NS_WML && (css = m_stylesheet_array.Get(WML_STYLESHEET_IDX)))
css->GetProperties(m_match_context, css_properties, stylesheet_idx++);
# endif // _WML_SUPPORT_
# if defined(CSS_MATHML_STYLESHEET) && defined(MATHML_ELEMENT_CODES)
if (ns_type == NS_MATHML && (css = m_stylesheet_array.Get(MATHML_STYLESHEET_IDX)))
css->GetProperties(m_match_context, css_properties, stylesheet_idx++);
# endif // CSS_MATHML_STYLESHEET && MATHML_ELEMENT_CODES
#endif // _WML_SUPPORT_ || CSS_MATHML_STYLESHEET
if (css_properties && m_match_context->ApplyPartially())
{
switch (g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(m_doc->GetPrefsRenderingMode(), PrefsCollectionDisplay::HonorHidden)))
{
case 1:
{
const uni_char* hostname = m_doc->GetURL().GetAttribute(URL::KUniHostName).CStr();
if (g_pcjs->GetIntegerPref(PrefsCollectionJS::EcmaScriptEnabled, hostname))
break;
}
case 2:
{
if (CSS_decl* cp = css_properties->GetDecl(CSS_PROPERTY_display))
if (cp->TypeValue() == CSS_VALUE_none)
css_properties->SetDecl(CSS_PROPERTY_display, NULL);
if (css_properties->GetDecl(CSS_PROPERTY_visibility))
css_properties->SetDecl(CSS_PROPERTY_visibility, NULL);
}
break;
}
}
if (css_properties && !he->GetIsPseudoElement())
{
RETURN_IF_ERROR(GetDefaultStyleProperties(context_elm, css_properties));
# ifdef STYLE_GETMATCHINGRULES_API
# ifdef STYLE_MATCH_INLINE_DEFAULT_API
if (listener)
{
StyleModule::DefaultStyle* default_style = &g_opera->style_module.default_style;
CSS_Properties default_properties;
RETURN_IF_ERROR(GetDefaultStyleProperties(context_elm, &default_properties));
// Create temporary CSS_property_list and populate with declarations from default_style.
CSS_property_list props;
CSS_decl* decl;
for (int i = 0; i < CSS_PROPERTIES_LENGTH; i++)
{
decl = default_properties.GetDecl(i);
if (decl)
{
if (i < CSS_PROPERTY_NAME_SIZE || i == CSS_PROPERTY_font_color)
{
CSS_decl* default_decl = decl;
if (!default_decl->GetDefaultStyle())
// Declarations not being 'default style' declarations can't be put in
// the temporary property list. Get a proxy object and put that in the
// list instead.
default_decl = default_style->GetProxyDeclaration(i, decl);
if (default_decl)
props.AddDecl(default_decl, FALSE, CSS_decl::ORIGIN_USER_AGENT);
}
}
}
if (!props.IsEmpty())
{
CSS_MatchElement elm(context_elm->HtmlElement(), m_match_context->PseudoElm());
OP_STATUS stat = listener->DefaultStyle(elm, &props);
if (OpStatus::IsMemoryError(stat))
return stat;
}
}
# endif // STYLE_MATCH_INLINE_DEFAULT_API
# endif // STYLE_GETMATCHINGRULES_API
#ifdef CSS_ANIMATIONS
m_animation_manager.ApplyAnimations(he, runtime_ms, css_properties, m_match_context->ApplyPartially());
#endif
}
if (context_elm->Type() == Markup::HTE_IMG && (m_match_context->DocLayoutMode() == LAYOUT_SSR || m_match_context->DocLayoutMode() == LAYOUT_CSSR))
{
PrefsCollectionDisplay::RenderingModes rendering_mode = m_match_context->DocLayoutMode() == LAYOUT_SSR ? PrefsCollectionDisplay::SSR : PrefsCollectionDisplay::CSSR;
if (g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(rendering_mode, PrefsCollectionDisplay::RemoveOrnamentalImages)) ||
g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(rendering_mode, PrefsCollectionDisplay::RemoveLargeImages)) ||
g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(rendering_mode, PrefsCollectionDisplay::UseAltForCertainImages)))
he->SetHasRealSizeDependentCss(TRUE);
}
int has_pseudo = g_css_pseudo_stack->HasPseudo();
if (has_pseudo)
match_he->SetCheckForPseudo(has_pseudo);
#ifdef DISABLE_HIGHLIGHT_ON_PSEUDO_CLASS
if (HTML_Document* html_doc = m_doc->GetHtmlDocument())
if (html_doc->GetNavigationElement() == match_he)
{
BOOL prevent_highlight = context_elm->IsHoveredWithMatch() || context_elm->IsFocusedWithMatch()
# ifdef SELECT_TO_FOCUS_INPUT
|| context_elm->IsPreFocusedWithMatch()
# endif // SELECT_TO_FOCUS_INPUT
;
if (!prevent_highlight)
{
/* Check whether some other matched context elm in chain has a :hover
pseudo class in the simple selector. We check only :hover, because
it is the only pseudo class that when being active on an element,
is also active on ancestors. */
CSS_MatchContextElm* iter = context_elm->Parent();
while (iter)
{
if (iter->IsHoveredWithMatch())
{
prevent_highlight = TRUE;
break;
}
iter = iter->Parent();
}
}
if (prevent_highlight)
{
if (html_doc->IsNavigationElementHighlighted() && m_doc->GetTextSelection())
/* This is the case when the navigation element is highlighted by selecting
the text inside it. We need to clear the text selection now, because
during the paint routine the text selection will always be painted
(regardless of navigation element highlighted flag in HTML_Document). */
m_doc->ClearDocumentSelection(FALSE);
html_doc->SetNavigationElementHighlighted(FALSE);
}
}
#endif // DISABLE_HIGHLIGHT_ON_PSEUDO_CLASS
return OpStatus::OK;
}
#ifdef PAGED_MEDIA_SUPPORT
void CSSCollection::GetPageProperties(CSS_Properties* css_properties, BOOL first_page, BOOL left_page, CSS_MediaType media_type)
{
HLDocProfile* hld_prof = m_doc->GetHLDocProfile();
const uni_char* hostname = m_doc->GetURL().GetAttribute(URL::KUniHostName).CStr();
unsigned int stylesheet_num = 0;
if (g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(hld_prof->GetCSSMode(), PrefsCollectionDisplay::EnableAuthorCSS), hostname) || m_doc->GetWindow()->IsCustomWindow())
{
CSSCollectionElement* elm = m_element_list.Last();
CSS* top_css = NULL;
while (elm)
{
if (elm->IsStyleSheet())
{
CSS* css = static_cast<CSS*>(elm);
if (!css->IsImport())
top_css = css;
// All imported stylesheets must have an ascendent stylesheet which is stored as top_css.
OP_ASSERT(top_css != NULL);
BOOL skip_children = TRUE;
if (css->IsEnabled() && css->CheckMedia(m_doc, media_type))
{
css->GetPageProperties(m_doc, css_properties, stylesheet_num++, first_page, left_page, media_type);
skip_children = FALSE;
}
elm = css->GetNextImport(skip_children);
if (!elm)
{
elm = top_css;
while ((elm = static_cast<CSSCollectionElement*>(elm->Pred())) && elm->IsStyleSheet() && static_cast<CSS*>(elm)->IsImport())
;
}
}
else
elm = elm->Pred();
}
}
if (g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(hld_prof->GetCSSMode(), PrefsCollectionDisplay::EnableUserCSS), hostname)
&& (m_doc->GetWindow()->IsNormalWindow() || m_doc->GetWindow()->IsThumbnailWindow()))
{
#ifdef LOCAL_CSS_FILES_SUPPORT
// Load all user style sheets defined in preferences
for (unsigned int j=0; j < g_pcfiles->GetLocalCSSCount(); j++)
{
CSS* css = g_cssManager->GetCSS(CSSManager::FirstUserStyle+j);
while (css)
{
BOOL skip_children = TRUE;
if (css->IsEnabled() && css->CheckMedia(m_doc, media_type))
{
css->GetPageProperties(m_doc, css_properties, stylesheet_num++, first_page, left_page, media_type);
skip_children = FALSE;
}
css = css->GetNextImport(skip_children);
}
}
# ifdef EXTENSION_SUPPORT
// Load all user style sheets defined by extensions
for (CSSManager::ExtensionStylesheet* extcss = g_cssManager->GetExtensionUserCSS(); extcss;
extcss = reinterpret_cast<CSSManager::ExtensionStylesheet*>(extcss->Suc()))
{
CSS* css = extcss->css;
while (css)
{
BOOL skip_children = TRUE;
if (css->IsEnabled() && css->CheckMedia(m_doc, media_type))
{
css->GetPageProperties(m_doc, css_properties, stylesheet_num++, first_page, left_page, media_type);
skip_children = FALSE;
}
css = css->GetNextImport(skip_children);
}
}
# endif
#endif // LOCAL_CSS_FILES_SUPPORT
#ifdef PREFS_HOSTOVERRIDE
CSS* css = m_host_overrides[CSSManager::LocalCSS].css;
if (!css)
css = g_cssManager->GetCSS(CSSManager::LocalCSS);
#else
CSS* css = g_cssManager->GetCSS(CSSManager::LocalCSS);
#endif
while (css)
{
BOOL skip_children = TRUE;
if (css->IsEnabled() && css->CheckMedia(m_doc, media_type))
{
css->GetPageProperties(m_doc, css_properties, stylesheet_num++, first_page, left_page, media_type);
skip_children = FALSE;
}
css = css->GetNextImport(skip_children);
}
}
#ifdef _WML_SUPPORT_
if (hld_prof->IsWml())
{
# ifdef PREFS_HOSTOVERRIDE
CSS* css = m_host_overrides[CSSManager::WML_CSS].css;
if (!css)
css = g_cssManager->GetCSS(CSSManager::WML_CSS);
# else
CSS* css = g_cssManager->GetCSS(CSSManager::WML_CSS);
# endif
if (css)
css->GetPageProperties(m_doc, css_properties, stylesheet_num++, first_page, left_page, media_type);
}
#endif
#if defined(CSS_MATHML_STYLESHEET) && defined(MATHML_ELEMENT_CODES)
CSS* css = g_cssManager->GetCSS(CSSManager::MathML_CSS);
if (css)
css->GetPageProperties(m_doc, css_properties, stylesheet_num++, first_page, left_page, media_type);
#endif // CSS_MATHML_STYLESHEET && MATHML_ELEMENT_CODES
#ifdef PREFS_HOSTOVERRIDE
CSS* browser_css = m_host_overrides[CSSManager::BrowserCSS].css;
if (!browser_css)
browser_css = g_cssManager->GetCSS(CSSManager::BrowserCSS);
#else
CSS* browser_css = g_cssManager->GetCSS(CSSManager::BrowserCSS);
#endif
while (browser_css)
{
BOOL skip_children = TRUE;
if (browser_css->IsEnabled() && browser_css->CheckMedia(m_doc, media_type))
{
browser_css->GetPageProperties(m_doc, css_properties, stylesheet_num++, first_page, left_page, media_type);
skip_children = FALSE;
}
browser_css = browser_css->GetNextImport(skip_children);
}
#ifdef SUPPORT_VISUAL_ADBLOCK
BOOL content_block_mode = m_doc->GetWindow()->GetContentBlockEditMode();
if (content_block_mode)
{
# ifdef PREFS_HOSTOVERRIDE
CSS* block_css = m_host_overrides[CSSManager::ContentBlockCSS].css;
if (!block_css)
block_css = g_cssManager->GetCSS(CSSManager::ContentBlockCSS);
# else
CSS* block_css = g_cssManager->GetCSS(CSSManager::ContentBlockCSS);
# endif
if (block_css)
block_css->GetPageProperties(m_doc, css_properties, stylesheet_num++, first_page, left_page, media_type);
}
#endif // SUPPORT_VISUAL_ADBLOCK
}
#endif // PAGED_MEDIA_SUPPORT
CSS_WebFont*
CSSCollection::GetWebFont(const uni_char* family_name, CSS_MediaType media_type)
{
CSSCollectionElement* elm = m_element_list.Last();
CSS* top_css = NULL;
while (elm)
{
if (elm->IsStyleSheet())
{
CSS* css = static_cast<CSS*>(elm);
if (!css->IsImport())
top_css = css;
// All imported stylesheets must have an ascendent stylesheet which is stored as top_css.
OP_ASSERT(top_css != NULL);
BOOL skip_children = TRUE;
if (css->IsEnabled() && css->CheckMedia(m_doc, media_type))
{
CSS_WebFont* font = css->GetWebFont(family_name);
if (font)
return font;
skip_children = FALSE;
}
elm = css->GetNextImport(skip_children);
if (!elm)
{
elm = top_css;
while ((elm = static_cast<CSSCollectionElement*>(elm->Pred())) && elm->IsStyleSheet() && static_cast<CSS*>(elm)->IsImport())
;
}
}
#ifdef SVG_SUPPORT
else if (elm->IsSvgFont())
{
CSS_SvgFont* font = static_cast<CSS_SvgFont*>(elm);
if (uni_str_eq(font->GetFamilyName(), family_name))
return font;
else
elm = elm->Pred();
}
#endif // SVG_SUPPORT
else
elm = elm->Pred();
}
return NULL;
}
void CSSCollection::AddFontPrefetchCandidate(const uni_char* family_name)
{
if (m_font_prefetch_limit > 0 && !m_font_prefetch_candidates.Contains(family_name))
{
OpString* name = OP_NEW(OpString, ());
if (!name)
return;
OP_STATUS status = name->Set(family_name);
if (OpStatus::IsSuccess(status))
status = m_font_prefetch_candidates.Add(name->CStr(), name);
if (OpStatus::IsError(status))
OP_DELETE(name);
}
}
void CSSCollection::DisableFontPrefetching()
{
if (m_font_prefetch_limit > 0)
{
m_font_prefetch_candidates.DeleteAll();
m_font_prefetch_limit = 0;
}
}
void CSSCollection::CheckFontPrefetchCandidates()
{
if (m_font_prefetch_limit > 0)
{
OpHashIterator* iter = m_font_prefetch_candidates.GetIterator();
OP_STATUS status = iter ? iter->First() : OpStatus::ERR;
int limit = m_font_prefetch_limit;
while (OpStatus::IsSuccess(status) && limit > 0)
{
const uni_char* family_name = static_cast<const uni_char*>(iter->GetKey());
if (GetWebFont(family_name, m_doc->GetMediaType()))
{
styleManager->LookupFontNumber(m_doc->GetHLDocProfile(), family_name, m_doc->GetMediaType()); // Loads the font if needed.
limit--;
}
status = iter->Next();
}
OP_DELETE(iter);
if (limit == 0)
DisableFontPrefetching();
}
}
void CSSCollection::OnTimeOut(OpTimer* timer)
{
StyleChanged(CSSCollection::CHANGED_WEBFONT);
}
void CSSCollection::RegisterWebFontTimeout(int timeout)
{
int time_remaining = -m_webfont_timer.TimeSinceFiring();
if (time_remaining <= 0 || timeout < time_remaining)
{
m_webfont_timer.Stop();
m_webfont_timer.Start(timeout);
m_webfont_timer.SetTimerListener(this);
}
}
int CSSCollection::GetSuccessiveAdjacent() const
{
int max_successive_adj = 0;
for (CSSCollectionElement* elm = m_element_list.First(); elm; elm = elm->Suc())
{
if (elm->IsStyleSheet())
{
CSS* css = static_cast<CSS*>(elm);
if (css->IsEnabled() && css->GetSuccessiveAdjacent() > max_successive_adj)
max_successive_adj = css->GetSuccessiveAdjacent();
}
}
return max_successive_adj;
}
CSSCollection::Iterator::Iterator(CSSCollection* coll, Type type)
{
OP_ASSERT(coll);
m_type = type;
CSSCollectionElement* elm = coll->m_element_list.First();
m_next = elm ? SkipElements(elm) : NULL;
}
CSSCollectionElement* CSSCollection::Iterator::SkipElements(CSSCollectionElement* cand)
{
if (m_type != ALL)
while (cand && (cand->IsSvgFont() && m_type != WEBFONTS ||
#ifdef CSS_VIEWPORT_SUPPORT
cand->IsViewportMeta() && m_type != VIEWPORT ||
#endif // CSS_VIEWPORT_SUPPORT
cand->IsStyleSheet() && static_cast<CSS*>(cand)->IsImport() && m_type == STYLESHEETS_NOIMPORTS))
cand = static_cast<CSSCollectionElement*>(cand->Suc());
return cand;
}
void
CSSCollection::DimensionsChanged(LayoutCoord old_width,
LayoutCoord old_height,
LayoutCoord new_width,
LayoutCoord new_height)
{
EvaluateMediaQueryLists();
if (HasMediaQueryChanged(old_width, old_height, new_width, new_height))
if (HTML_Element* root = m_doc->GetDocRoot())
root->MarkPropsDirty(m_doc);
}
void
CSSCollection::DeviceDimensionsChanged(LayoutCoord old_device_width,
LayoutCoord old_device_height,
LayoutCoord new_device_width,
LayoutCoord new_device_height)
{
EvaluateMediaQueryLists();
if (HasDeviceMediaQueryChanged(old_device_width, old_device_height, new_device_width, new_device_height))
if (HTML_Element* root = m_doc->GetDocRoot())
root->MarkPropsDirty(m_doc);
}
BOOL CSSCollection::HasMediaQueryChanged(LayoutCoord old_width,
LayoutCoord old_height,
LayoutCoord new_width,
LayoutCoord new_height)
{
for (CSSCollectionElement* elm = m_element_list.First(); elm; elm = elm->Suc())
{
if (elm->IsStyleSheet())
{
CSS* css = static_cast<CSS*>(elm);
if (css->IsEnabled() && css->HasMediaQueryChanged(old_width, old_height, new_width, new_height))
return TRUE;
}
}
return FALSE;
}
BOOL CSSCollection::HasDeviceMediaQueryChanged(LayoutCoord old_device_width,
LayoutCoord old_device_height,
LayoutCoord new_device_width,
LayoutCoord new_device_height)
{
for (CSSCollectionElement* elm = m_element_list.First(); elm; elm = elm->Suc())
{
if (elm->IsStyleSheet())
{
CSS* css = static_cast<CSS*>(elm);
if (css->IsEnabled() && css->HasDeviceMediaQueryChanged(old_device_width, old_device_height, new_device_width, new_device_height))
return TRUE;
}
}
return FALSE;
}
void CSSCollection::EvaluateMediaQueryLists()
{
for (CSS_MediaQueryList* mql = m_query_lists.First(); mql; mql = mql->Suc())
mql->Evaluate(m_doc);
}
#ifdef PREFS_HOSTOVERRIDE
void CSSCollection::LoadHostOverridesL(const uni_char* hostname)
{
// Read and parse the overridden CSS
HostOverrideStatus is_overridden = g_pcfiles->IsHostOverridden(hostname, FALSE);
if (is_overridden == HostOverrideActive
# ifdef PREFSFILE_WRITE_GLOBAL
|| is_overridden == HostOverrideDownloadedActive
# endif
)
{
HTML_Element::DocumentContext doc_ctx((FramesDocument*)NULL);
OpFile cssfile;
ANCHOR(OpFile, cssfile);
for (unsigned int i = 0; i < CSSManager::FirstUserStyle; i++)
{
if (m_host_overrides[i].elm)
{
m_host_overrides[i].elm->Free(doc_ctx);
m_host_overrides[i].elm = NULL;
}
m_host_overrides[i].css = NULL;
switch (i)
{
case CSSManager::BrowserCSS:
if (g_pcfiles->IsPreferenceOverridden(PrefsCollectionFiles::BrowserCSSFile, hostname))
{
g_pcfiles->GetFileL(PrefsCollectionFiles::BrowserCSSFile, cssfile, hostname);
}
else
continue;
break;
case CSSManager::LocalCSS:
if (g_pcfiles->IsPreferenceOverridden(PrefsCollectionFiles::LocalCSSFile, hostname))
{
g_pcfiles->GetFileL(PrefsCollectionFiles::LocalCSSFile, cssfile, hostname);
}
else
continue;
break;
# ifdef SUPPORT_VISUAL_ADBLOCK
case CSSManager::ContentBlockCSS:
if (g_pcfiles->IsPreferenceOverridden(PrefsCollectionFiles::ContentBlockCSSFile, hostname))
{
g_pcfiles->GetFileL(PrefsCollectionFiles::ContentBlockCSSFile, cssfile, hostname);
}
else
continue;
break;
# endif // SUPPORT_VISUAL_ADBLOCK
// TODO: Get overrides for specialized stylesheets
default:
continue;
}
m_host_overrides[i].elm = CSSManager::LoadCSSFileL(&cssfile, i == CSSManager::LocalCSS);
if (m_host_overrides[i].elm)
m_host_overrides[i].css = m_host_overrides[i].elm->GetCSS();
}
}
}
/* virtual */ void
CSSCollection::FileHostOverrideChanged(const uni_char* hostname)
{
OpString doc_hostname;
RETURN_VOID_IF_ERROR(m_doc->GetURL().GetAttribute(URL::KUniHostName, doc_hostname));
if (doc_hostname.Compare(hostname) != 0)
return;
// hostname matched, update the local stylesheets.
TRAPD(err, CSSCollection::LoadHostOverridesL(hostname));
if (OpStatus::IsSuccess(err))
{
Window* win = m_doc->GetWindow();
if (win)
err = win->UpdateWindow(TRUE);
}
RAISE_IF_MEMORY_ERROR(err);
}
CSSCollection::LocalStylesheet::~LocalStylesheet()
{
HTML_Element::DocumentContext doc_ctx((FramesDocument*)NULL);
if (elm)
elm->Free(doc_ctx);
}
#endif // PREFS_HOSTOVERRIDE
void
CSSCollection::GetAnchorStyle(CSS_MatchContextElm* context_elm, BOOL set_color, COLORREF& color, int& decoration_flags, CSSValue& border_style, short& border_width)
{
context_elm->CacheLinkState(m_doc);
if (context_elm->IsLink())
{
HLDocProfile* hld_profile = m_doc->GetHLDocProfile();
CSSMODE css_handling = hld_profile->GetCSSMode();
if (g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::LinkHasFrame))
{
border_style = CSS_VALUE_outset;
border_width = 2;
}
if (context_elm->IsVisited())
{
if (set_color)
{
if (hld_profile->GetVLinkColor() == USE_DEFAULT_COLOR ||
!g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(css_handling, PrefsCollectionDisplay::EnableAuthorFontAndColors)))
{
if (g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::VisitedLinkHasColor) && g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(css_handling, PrefsCollectionDisplay::EnableUserLinkSettings)))
color = g_pcfontscolors->GetColor(OP_SYSTEM_COLOR_VISITED_LINK);
}
else
color = hld_profile->GetVLinkColor();
}
if (g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(css_handling, PrefsCollectionDisplay::EnableUserLinkSettings)))
{
if (g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::VisitedLinkHasUnderline))
decoration_flags |= CSS_TEXT_DECORATION_underline;
if (g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::VisitedLinkHasStrikeThrough))
decoration_flags |= CSS_TEXT_DECORATION_line_through;
}
}
else // Link (not visited)
{
if (set_color)
{
if (hld_profile->GetLinkColor() == USE_DEFAULT_COLOR ||
!g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(css_handling, PrefsCollectionDisplay::EnableAuthorFontAndColors)))
{
if (g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::LinkHasColor) && g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(css_handling, PrefsCollectionDisplay::EnableUserLinkSettings)))
color = g_pcfontscolors->GetColor(OP_SYSTEM_COLOR_LINK);
}
else
color = hld_profile->GetLinkColor();
}
if (g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(css_handling, PrefsCollectionDisplay::EnableUserLinkSettings)))
{
if (g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::LinkHasUnderline))
decoration_flags |= CSS_TEXT_DECORATION_underline;
if (g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::LinkHasStrikeThrough))
decoration_flags |= CSS_TEXT_DECORATION_line_through;
}
}
if (set_color && hld_profile->GetALinkColor() != USE_DEFAULT_COLOR)
{
context_elm->HtmlElement()->SetHasDynamicPseudo(TRUE);
HTML_Document* doc = m_doc->GetHtmlDocument();
if (doc && doc->GetActivePseudoHTMLElement() == context_elm->HtmlElement() &&
g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(css_handling, PrefsCollectionDisplay::EnableAuthorFontAndColors)))
{
color = hld_profile->GetALinkColor();
}
}
}
}
// also used from layoutprops (GetCssProperties)
int GetFormStyle(const Markup::Type elm_type, const InputType itype)
{
int form_style = STYLE_EX_FORM_TEXTINPUT;
if (elm_type == Markup::HTE_INPUT && itype == INPUT_IMAGE)
return form_style;
if (elm_type == Markup::HTE_INPUT || elm_type == Markup::HTE_BUTTON)
{
switch (itype)
{
case INPUT_BUTTON:
case INPUT_SUBMIT:
case INPUT_RESET:
return STYLE_EX_FORM_BUTTON;
}
}
else if (elm_type == Markup::HTE_SELECT
#ifdef _SSL_SUPPORT_
|| elm_type == Markup::HTE_KEYGEN
#endif
|| itype == INPUT_DATE || itype == INPUT_WEEK)
return STYLE_EX_FORM_SELECT;
else if (elm_type == Markup::HTE_TEXTAREA)
return STYLE_EX_FORM_TEXTAREA;
return form_style;
}
OP_STATUS
CSSCollection::GetDefaultStyleProperties(CSS_MatchContextElm* context_elm, CSS_Properties* css_properties)
{
OP_PROBE4(OP_PROBE_CSSCOLLECTION_GETDEFAULTSTYLE);
HLDocProfile* hld_profile = m_doc->GetHLDocProfile();
Markup::Type elm_type = context_elm->Type();
NS_Type elm_ns_type = context_elm->GetNsType();
HTML_Element* element = context_elm->HtmlElement();
BOOL set_display = css_properties->GetDecl(CSS_PROPERTY_display) == NULL;
CSSValue display_type = CSS_VALUE_UNSPECIFIED;
StyleModule::DefaultStyle* default_style = &g_opera->style_module.default_style;
if (elm_ns_type != NS_HTML && elm_type != Markup::HTE_DOC_ROOT)
{
switch (elm_ns_type)
{
#ifdef _WML_SUPPORT_
case NS_WML:
switch ((WML_ElementType)elm_type)
{
case WE_DO:
if (set_display &&
element->HasSpecialAttr(Markup::LOGA_WML_SHADOWING_TASK, SpecialNs::NS_LOGDOC))
{
display_type = CSS_VALUE_none;
// We don't need to retrieve anchor style if display is none.
break;
}
// Fall-through
case WE_ANCHOR:
{
BOOL set_color = (css_properties->GetDecl(CSS_PROPERTY_color) == NULL);
COLORREF color = USE_DEFAULT_COLOR;
int decoration_flags = 0;
CSSValue border_style = CSS_VALUE_UNSPECIFIED;
short border_width = BORDER_WIDTH_NOT_SET;
if (set_color || !css_properties->GetDecl(CSS_PROPERTY_text_decoration) || g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::LinkHasFrame))
GetAnchorStyle(context_elm, TRUE, color, decoration_flags, border_style, border_width);
if (color != USE_DEFAULT_COLOR && set_color)
{
CSS_long_decl* decl = default_style->fg_color;
decl->SetLongValue(color);
css_properties->SetDecl(CSS_PROPERTY_color, decl);
}
if (decoration_flags && !css_properties->GetDecl(CSS_PROPERTY_text_decoration))
{
CSS_type_decl* decl = default_style->text_decoration;
/* Text decoration flags are stored as CSSValue, carefully chosen not to
collide with other valid values for text-decoration. */
decl->SetTypeValue(CSSValue(decoration_flags));
css_properties->SetDecl(CSS_PROPERTY_text_decoration, decl);
}
if (border_style != CSS_VALUE_UNSPECIFIED)
{
OP_ASSERT(border_width != BORDER_WIDTH_NOT_SET);
CSS_type_decl* style_decl = default_style->border_bottom_style;
style_decl->SetTypeValue(border_style);
CSS_number_decl* width_decl = default_style->border_bottom_width;
width_decl->SetNumberValue(0, (float)border_width, CSS_PX);
if (!css_properties->GetDecl(CSS_PROPERTY_border_top_style))
css_properties->SetDecl(CSS_PROPERTY_border_top_style, style_decl);
if (!css_properties->GetDecl(CSS_PROPERTY_border_bottom_style))
css_properties->SetDecl(CSS_PROPERTY_border_bottom_style, style_decl);
if (!css_properties->GetDecl(CSS_PROPERTY_border_left_style))
css_properties->SetDecl(CSS_PROPERTY_border_left_style, style_decl);
if (!css_properties->GetDecl(CSS_PROPERTY_border_right_style))
css_properties->SetDecl(CSS_PROPERTY_border_right_style, style_decl);
if (!css_properties->GetDecl(CSS_PROPERTY_border_top_width))
css_properties->SetDecl(CSS_PROPERTY_border_top_width, width_decl);
if (!css_properties->GetDecl(CSS_PROPERTY_border_bottom_width))
css_properties->SetDecl(CSS_PROPERTY_border_bottom_width, width_decl);
if (!css_properties->GetDecl(CSS_PROPERTY_border_left_width))
css_properties->SetDecl(CSS_PROPERTY_border_left_width, width_decl);
if (!css_properties->GetDecl(CSS_PROPERTY_border_right_width))
css_properties->SetDecl(CSS_PROPERTY_border_right_width, width_decl);
}
}
break;
}
break;
#endif // _WML_SUPPORT_
#ifdef SVG_SUPPORT
case NS_SVG:
{
SVGWorkplace* svg_workplace = m_doc->GetLogicalDocument()->GetSVGWorkplace();
RETURN_IF_ERROR(svg_workplace->GetDefaultStyleProperties(element, css_properties));
break;
}
#endif // SVG_SUPPORT
#ifdef MEDIA_HTML_SUPPORT
case NS_CUE:
GetDefaultCueStyleProperties(element, css_properties);
break;
#endif // MEDIA_HTML_SUPPORT
default:
break;
}
if (display_type != CSS_VALUE_UNSPECIFIED)
{
CSS_type_decl* decl = default_style->display_type;
decl->SetTypeValue(display_type);
css_properties->SetDecl(CSS_PROPERTY_display, decl);
}
return OpStatus::OK;
}
LayoutMode layout_mode = m_match_context->DocLayoutMode();
CSSMODE css_handling = hld_profile->GetCSSMode();
Style* style = styleManager->GetStyle(elm_type);
const LayoutAttr& lattr = style->GetLayoutAttr();
BOOL set_white_space = css_properties->GetDecl(CSS_PROPERTY_white_space) == NULL;
BOOL set_valign = css_properties->GetDecl(CSS_PROPERTY_vertical_align) == NULL;
BOOL set_text_indent = css_properties->GetDecl(CSS_PROPERTY_text_indent) == NULL;
BOOL set_bg_color = css_properties->GetDecl(CSS_PROPERTY_background_color) == NULL;
BOOL set_fg_color = css_properties->GetDecl(CSS_PROPERTY_color) == NULL;
CSSValue white_space = CSS_VALUE_UNSPECIFIED;
CSSValue vertical_align_type = CSS_VALUE_UNSPECIFIED;
int text_indent = INT_MIN;
COLORREF bg_color = USE_DEFAULT_COLOR;
COLORREF fg_color = USE_DEFAULT_COLOR;
Border border;
border.Reset();
CSSValue text_align = CSS_VALUE_UNSPECIFIED;
int decoration_flags = 0;
CSSValue font_italic = CSS_VALUE_UNSPECIFIED;
#ifdef SUPPORT_TEXT_DIRECTION
CSSValue unicode_bidi = CSS_VALUE_UNSPECIFIED;
#endif // SUPPORT_TEXT_DIRECTION
CSSValue html_align = (CSSValue)(INTPTR)element->GetAttr(Markup::HA_ALIGN, ITEM_TYPE_NUM, (void*)(INTPTR)CSS_VALUE_UNSPECIFIED);
BOOL use_user_font_setting = g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(css_handling, PrefsCollectionDisplay::EnableUserFontAndColors));
short default_padding_horz = 0;
short default_padding_vert = 0;
COLORREF border_default_color = USE_DEFAULT_COLOR;
CSSValue border_default_style = CSS_VALUE_none;
short border_default_width = CSS_BORDER_WIDTH_MEDIUM;
BOOL has_left_margin = FALSE;
BOOL has_right_margin = FALSE;
BOOL has_top_margin = FALSE;
BOOL has_bottom_margin = FALSE;
BOOL has_vertical_padding = FALSE;
BOOL has_horizontal_padding = FALSE;
BOOL replaced_set_html_align = FALSE;
BOOL replaced_elm = FALSE;
BOOL absolute_width = FALSE;
BOOL margin_h_auto = FALSE;
enum {
MARGIN_LEFT,
MARGIN_RIGHT,
MARGIN_TOP,
MARGIN_BOTTOM,
PADDING_LEFT,
PADDING_RIGHT,
PADDING_TOP,
PADDING_BOTTOM,
MARGIN_PADDING_SIZE
};
// padding-left, padding-right, padding-top, padding-bottom
short margin_padding[MARGIN_PADDING_SIZE] = { 0, 0, 0, 0, 0, 0, 0, -1 }; /* ARRAY OK 2012-03-14 rune */
// <input type="image"> must be special cased since <input> normally doesn't support height and width
if (!css_properties->GetDecl(CSS_PROPERTY_width) &&
(SupportAttribute(elm_type, ATTR_WIDTH_SUPPORT) || elm_type == Markup::HTE_INPUT && element->GetInputType() == INPUT_IMAGE))
{
HTML_Element* width_elm = element;
BOOL has_width = element->HasNumAttr(Markup::HA_WIDTH);
if (elm_type == Markup::HTE_COL && !has_width)
{
// fix bug 83881, width of <COL> elements should inherit width from a parent <COLGROUP> if set to auto
while (width_elm)
{
if (width_elm->Type() == Markup::HTE_COLGROUP)
{
has_width = width_elm->HasNumAttr(Markup::HA_WIDTH);
break;
}
width_elm = width_elm->Parent();
}
}
if (has_width)
{
int val = (int)width_elm->GetNumAttr(Markup::HA_WIDTH);
if (val != 0 || (elm_type != Markup::HTE_TD && elm_type != Markup::HTE_TH && elm_type != Markup::HTE_COL && elm_type != Markup::HTE_COLGROUP))
if (elm_type != Markup::HTE_PRE || val > 0)
{
int value_type;
if (elm_type == Markup::HTE_PRE)
{
value_type = CSS_NUMBER;
}
else
{
if (val < 0)
{
val = -val;
value_type = CSS_PERCENTAGE;
}
else
{
value_type = CSS_PX;
absolute_width = TRUE;
}
}
CSS_number_decl* width_decl = default_style->content_width;
width_decl->SetNumberValue(0, (float)val, value_type);
css_properties->SetDecl(CSS_PROPERTY_width, width_decl);
}
}
}
// <input type="image"> must be special cased since <input> normally doesn't support height and width
if (!css_properties->GetDecl(CSS_PROPERTY_height) &&
(SupportAttribute(elm_type, ATTR_HEIGHT_SUPPORT) || elm_type == Markup::HTE_INPUT && element->GetInputType() == INPUT_IMAGE))
{
if (element->HasNumAttr(Markup::HA_HEIGHT))
{
int value = element->GetNumAttr(Markup::HA_HEIGHT);
if (value != 0 || (elm_type != Markup::HTE_TD && elm_type != Markup::HTE_TH))
{
int value_type = CSS_PX;
if (value < 0)
{
value_type = CSS_PERCENTAGE;
value = -value;
}
CSS_number_decl* height_decl = default_style->content_height;
height_decl->SetNumberValue(0, (float)value, value_type);
css_properties->SetDecl(CSS_PROPERTY_height, height_decl);
}
}
}
if (!css_properties->GetDecl(CSS_PROPERTY_background_image) &&
SupportAttribute(elm_type, ATTR_BACKGROUND_SUPPORT) &&
g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(css_handling, PrefsCollectionDisplay::EnableAuthorFontAndColors)))
{
StyleAttribute* style_attr = (StyleAttribute*)element->GetAttr(Markup::HA_BACKGROUND, ITEM_TYPE_COMPLEX, (void*)0);
if (style_attr)
{
OP_ASSERT(style_attr->GetProperties()->GetLength() == 1);
css_properties->SetDecl(CSS_PROPERTY_background_image, style_attr->GetProperties()->GetFirstDecl());
}
}
float rel_font_size = 0;
short font_size = -1;
short font_weight = -1;
short font_number = -1;
switch (elm_type)
{
case Markup::HTE_TITLE:
case Markup::HTE_META:
case Markup::HTE_BASE:
case Markup::HTE_LINK:
case Markup::HTE_STYLE:
case Markup::HTE_SCRIPT:
case Markup::HTE_AREA:
case Markup::HTE_HEAD:
case Markup::HTE_XML:
if (set_display)
display_type = CSS_VALUE_none;
break;
case Markup::HTE_NOFRAMES:
if (g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::FramesEnabled, m_doc->GetURL().GetServerName()))
display_type = CSS_VALUE_none;
break;
case Markup::HTE_NOEMBED:
if (set_display)
display_type = CSS_VALUE_none;
break;
case Markup::HTE_NOSCRIPT:
/* Only scripting on/off can control display type of NOSCRIPT. See CORE-14030. */
if (!element->GetSpecialAttr(Markup::LOGA_NOSCRIPT_ENABLED, ITEM_TYPE_BOOL, 0, SpecialNs::NS_LOGDOC))
display_type = CSS_VALUE_none;
break;
case Markup::HTE_LEGEND:
margin_padding[PADDING_LEFT] = margin_padding[PADDING_RIGHT] = 2;
has_horizontal_padding = TRUE;
// fall-through
case Markup::HTE_ADDRESS:
if (elm_type == Markup::HTE_ADDRESS)
font_italic = CSS_VALUE_italic;
// fall-through
case Markup::HTE_HTML:
case Markup::HTE_ISINDEX:
case Markup::HTE_BLOCKQUOTE:
case Markup::HTE_DIR:
case Markup::HTE_MENU:
if (set_display)
display_type = CSS_VALUE_block;
break;
case Markup::HTE_FORM:
{
CSS_MatchContextElm* parent = context_elm->Parent();
if (parent)
{
Markup::Type parent_type = parent->Type();
if (parent->GetNsIdx() == NS_IDX_HTML && (parent_type == Markup::HTE_TABLE || parent_type == Markup::HTE_TBODY || parent_type == Markup::HTE_TFOOT || parent_type == Markup::HTE_THEAD || parent_type == Markup::HTE_TR))
{
display_type = CSS_VALUE_none;
break;
}
}
if (set_display)
display_type = CSS_VALUE_block;
}
break;
case Markup::HTE_FIELDSET:
if (set_display)
display_type = CSS_VALUE_block;
border_default_style = CSS_VALUE_groove;
border_default_width = 2;
margin_padding[MARGIN_LEFT] = margin_padding[MARGIN_RIGHT] = 2;
has_left_margin = TRUE;
break;
case Markup::HTE_MARQUEE:
{
if (set_display)
display_type = CSS_VALUE__wap_marquee;
if (!css_properties->GetDecl(CSS_PROPERTY_overflow_x))
css_properties->SetDecl(CSS_PROPERTY_overflow_x, default_style->overflow_x);
if (!css_properties->GetDecl(CSS_PROPERTY_overflow_y))
css_properties->SetDecl(CSS_PROPERTY_overflow_y, default_style->overflow_y);
int direction = 0;
if (!css_properties->GetDecl(CSS_PROPERTY__wap_marquee_dir))
{
direction = (int)element->GetNumAttr(Markup::HA_DIRECTION);
if (direction)
{
CSS_type_decl* dir_decl = default_style->marquee_dir;
CSSValue dir = CSS_VALUE_UNSPECIFIED;
switch (direction)
{
case ATTR_VALUE_left:
dir = CSS_VALUE_rtl;
break;
case ATTR_VALUE_right:
dir = CSS_VALUE_ltr;
break;
case ATTR_VALUE_up:
dir = CSS_VALUE_up;
break;
case ATTR_VALUE_down:
dir = CSS_VALUE_down;
break;
}
dir_decl->SetTypeValue(dir);
css_properties->SetDecl(CSS_PROPERTY__wap_marquee_dir, dir_decl);
}
}
CSSValue style = CSS_VALUE_UNSPECIFIED;
if (!css_properties->GetDecl(CSS_PROPERTY__wap_marquee_style))
{
int behavior = (int)element->GetNumAttr(Markup::HA_BEHAVIOR);
switch (behavior)
{
case ATTR_VALUE_slide:
style = CSS_VALUE_slide; break;
case ATTR_VALUE_alternate:
style = CSS_VALUE_alternate; break;
}
if (style != CSS_VALUE_UNSPECIFIED)
{
CSS_type_decl* style_decl = default_style->marquee_style;
style_decl->SetTypeValue(style);
css_properties->SetDecl(CSS_PROPERTY__wap_marquee_style, style_decl);
}
}
if (!css_properties->GetDecl(CSS_PROPERTY__wap_marquee_loop))
{
long marquee_loop = (long)element->GetAttr(Markup::HA_LOOP, ITEM_TYPE_NUM, (void*)-1);
if (style == CSS_VALUE_slide && marquee_loop == -1)
marquee_loop = 1;
else if (marquee_loop == 0)
marquee_loop = -1;
if (marquee_loop != -1)
{
default_style->marquee_loop->SetNumberValue(0, (float)marquee_loop, CSS_NUMBER);
css_properties->SetDecl(CSS_PROPERTY__wap_marquee_loop, default_style->marquee_loop);
}
else
css_properties->SetDecl(CSS_PROPERTY__wap_marquee_loop, default_style->infinite_decl);
}
if (set_bg_color && layout_mode != LAYOUT_SSR)
bg_color = (long)element->GetAttr(Markup::HA_BGCOLOR, ITEM_TYPE_NUM, (void*)USE_DEFAULT_COLOR);
if (!css_properties->GetDecl(CSS_PROPERTY_height))
{
if (direction == ATTR_VALUE_up || direction == ATTR_VALUE_down)
{
default_style->content_height->SetNumberValue(0, 200, CSS_PX);
css_properties->SetDecl(CSS_PROPERTY_height, default_style->content_height);
}
}
}
break;
case Markup::HTE_BUTTON:
if (set_display)
display_type = CSS_VALUE_inline_block;
text_align = CSS_VALUE_center;
if (set_white_space && !css_properties->GetDecl(CSS_PROPERTY_width))
white_space = CSS_VALUE_nowrap;
default_padding_horz = 8;
default_padding_vert = 1;
/* Fallthrough */
case Markup::HTE_SELECT:
#ifdef _SSL_SUPPORT_
case Markup::HTE_KEYGEN:
#endif
case Markup::HTE_TEXTAREA:
case Markup::HTE_INPUT:
{
InputType itype = element->GetInputType();
if (elm_type == Markup::HTE_TEXTAREA)
{
itype = INPUT_TEXTAREA; // virtual type to simplify code
if (!css_properties->GetDecl(CSS_PROPERTY_line_height))
css_properties->SetDecl(CSS_PROPERTY_line_height, default_style->line_height);
if (!css_properties->GetDecl(CSS_PROPERTY_overflow_wrap))
css_properties->SetDecl(CSS_PROPERTY_overflow_wrap, default_style->overflow_wrap);
if (!css_properties->GetDecl(CSS_PROPERTY_resize))
css_properties->SetDecl(CSS_PROPERTY_resize, default_style->resize);
}
if (elm_type == Markup::HTE_INPUT || elm_type == Markup::HTE_TEXTAREA)
{
if (!css_properties->GetDecl(CSS_PROPERTY_text_transform))
css_properties->SetDecl(CSS_PROPERTY_text_transform, default_style->text_transform);
}
if (set_text_indent)
text_indent = 0;
BOOL element_disabled = element->IsDisabled(m_doc);
if (set_fg_color)
{
fg_color = OP_RGB(0, 0, 0);
if (element_disabled)
fg_color = g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_TEXT_DISABLED);
if (elm_type == Markup::HTE_TEXTAREA)
fg_color = element_disabled ? g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_TEXT_DISABLED) :
g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_TEXT);
else if (elm_type == Markup::HTE_BUTTON)
fg_color = element_disabled ? g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_TEXT_DISABLED) :
g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_BUTTON_TEXT);
}
border_default_width = 2;
// Set default alignment
text_align = CSS_VALUE_default;
if (FormManager::IsButton(itype))
{
text_align = CSS_VALUE_center;
}
else if (itype == INPUT_NUMBER || itype == INPUT_RANGE || itype == INPUT_DATE)
{
text_align = CSS_VALUE_right;
}
switch (itype)
{
case INPUT_BUTTON:
case INPUT_SUBMIT:
case INPUT_RESET:
default_padding_horz = 8;
default_padding_vert = 1;
if (set_fg_color)
fg_color = element_disabled ? g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_TEXT_DISABLED) :
g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_BUTTON_TEXT);
break;
// this is done to mimic the behaviour of ff/webkit. that
// is:
// * 3px 3px 3px 4px for checkbox
// * 3px 3px 0px 5px for radio button
case INPUT_RADIO:
margin_padding[MARGIN_BOTTOM] = 0;
has_bottom_margin = TRUE;
case INPUT_CHECKBOX:
margin_padding[MARGIN_TOP] = 3;
has_top_margin = TRUE;
margin_padding[MARGIN_RIGHT] = 3;
has_right_margin = TRUE;
margin_padding[MARGIN_LEFT] = itype == INPUT_CHECKBOX ? 4 : 5;
has_left_margin = TRUE;
// fall through
case INPUT_TEXT:
case INPUT_TEXTAREA:
case INPUT_PASSWORD:
case INPUT_FILE:
case INPUT_NUMBER:
case INPUT_URI:
case INPUT_EMAIL:
case INPUT_TIME:
case INPUT_DATETIME:
case INPUT_DATETIME_LOCAL:
case INPUT_WEEK:
case INPUT_COLOR:
case INPUT_TEL:
case INPUT_SEARCH:
default_padding_horz = 1;
default_padding_vert = 1;
if (set_fg_color)
fg_color = element_disabled ? g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_TEXT_DISABLED) :
g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_TEXT_INPUT);
break;
case INPUT_IMAGE:
border_default_width = 0;
replaced_set_html_align = TRUE;
break;
case INPUT_HIDDEN:
display_type = CSS_VALUE_none;
break;
}
int form_style = GetFormStyle(elm_type, itype);
Style* style = styleManager->GetStyleEx(form_style);
const PresentationAttr& p_attr = style->GetPresentationAttr();
if (elm_type == Markup::HTE_INPUT && itype == INPUT_IMAGE)
{
replaced_elm = TRUE;
}
else
{
// FIXME: move GetFontColorDefined() to HTMLayoutProperties (needs to be inherited !!!)
if (set_fg_color && use_user_font_setting && (
!g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(css_handling, PrefsCollectionDisplay::EnableAuthorFontAndColors))))
fg_color = p_attr.Color;
WritingSystem::Script script = WritingSystem::Unknown;
#ifdef FONTSWITCHING
script = hld_profile->GetPreferredScript();
#endif // FONTSWITCHING
FontAtt* font = p_attr.GetPresentationFont(script).Font;
font_size = op_abs(font->GetHeight());
font_size = MAX(font_size, g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::MinFontSize));
font_weight = font->GetWeight();
if (p_attr.Italic)
font_italic = CSS_VALUE_italic;
if (!css_properties->GetDecl(CSS_PROPERTY_font_family))
{
CSS_type_decl* font_family_type = default_style->font_family_type;
font_family_type->SetTypeValue(CSS_VALUE_use_lang_def);
css_properties->SetDecl(CSS_PROPERTY_font_family, font_family_type);
}
}
}
break;
case Markup::HTE_OPTION:
case Markup::HTE_OPTGROUP:
if (set_text_indent)
text_indent = 0;
break;
case Markup::HTE_PROGRESS:
case Markup::HTE_METER:
if (set_valign)
vertical_align_type = CSS_VALUE_middle;
border_default_width = 1;
break;
case Markup::HTE_IFRAME:
{
URL* src_url = element->GetUrlAttr(Markup::HA_SRC, NS_IDX_HTML, m_doc->GetLogicalDocument());
BOOL show_iframe = m_doc->IsAllowedIFrame(src_url);
if (!g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::IFramesEnabled, m_doc->GetURL()) || !show_iframe)
{
if (set_display)
{
if (!show_iframe)
display_type = CSS_VALUE_none;
else
display_type = CSS_VALUE_block;
}
break;
}
else
{
// If frameborder isn't specified it should be on according to standard.
if (!element->HasAttr(Markup::HA_FRAMEBORDER) || element->GetFrameBorder())
{
border_default_width = 2;
border_default_style = CSS_VALUE_inset;
}
replaced_elm = TRUE;
}
}
replaced_set_html_align = TRUE;
break;
case Markup::HTE_TABLE:
{
// Gecko and Webkit compatibility.
CSSValue border_collapse = CSS_VALUE_separate;
if (set_display)
display_type = CSS_VALUE_table;
if (set_bg_color &&
layout_mode != LAYOUT_SSR &&
g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(css_handling, PrefsCollectionDisplay::EnableAuthorFontAndColors)))
{
bg_color = element->GetNumAttr(Markup::HA_BGCOLOR, NS_IDX_HTML, USE_DEFAULT_COLOR);
}
if (set_text_indent)
text_indent = 0;
// IE 6 inherits all properties into a table in CSS1CompatMode, but some are reset in QuirksMode...
if (!hld_profile->IsInStrictMode())
{
if (!css_properties->GetDecl(CSS_PROPERTY_font_size))
{
CSS_type_decl* font_size_decl = default_style->font_size_type;
font_size_decl->SetTypeValue(CSS_VALUE_use_lang_def);
css_properties->SetDecl(CSS_PROPERTY_font_size, font_size_decl);
}
font_weight = 4;
font_italic = CSS_VALUE_normal;
if (set_white_space)
white_space = CSS_VALUE_normal;
text_align = CSS_VALUE_default; // only default alignment, should not be set as specified
if (!css_properties->GetDecl(CSS_PROPERTY_word_spacing))
css_properties->SetDecl(CSS_PROPERTY_word_spacing, default_style->word_spacing);
if (!css_properties->GetDecl(CSS_PROPERTY_letter_spacing))
css_properties->SetDecl(CSS_PROPERTY_letter_spacing, default_style->letter_spacing);
}
short table_rules = short(element->GetNumAttr(Markup::HA_RULES, NS_IDX_HTML, 0));
short table_frame = short(element->GetNumAttr(Markup::HA_FRAME, NS_IDX_HTML, 0));
if (table_rules)
{
CSS_long_decl* decl = default_style->table_rules;
decl->SetLongValue(table_rules);
css_properties->SetDecl(CSS_PROPERTY_table_rules, decl);
}
BOOL has_border = table_frame != ATTR_VALUE_void && element->HasNumAttr(Markup::HA_BORDER);
if (has_border)
{
border_default_width = (short)(INTPTR)element->GetAttr(Markup::HA_BORDER, ITEM_TYPE_NUM, (void*)0);
if (border_default_width)
{
border_default_style = CSS_VALUE_outset;
if (!table_frame)
table_frame = ATTR_VALUE_border;
}
else
if (table_frame || table_rules)
border_default_style = CSS_VALUE_hidden;
}
else
if (!table_frame && table_rules)
table_frame = ATTR_VALUE_void;
if (table_rules)
{
border_collapse = CSS_VALUE_collapse;
if (border_default_style != CSS_VALUE_hidden && table_frame != ATTR_VALUE_box && table_frame != ATTR_VALUE_border)
{
if (table_frame != ATTR_VALUE_vsides && table_frame != ATTR_VALUE_lhs)
border.left.style = CSS_VALUE_hidden;
if (table_frame != ATTR_VALUE_hsides && table_frame != ATTR_VALUE_above)
border.top.style = CSS_VALUE_hidden;
}
}
switch (table_frame)
{
case ATTR_VALUE_void:
border_default_style = CSS_VALUE_hidden;
break;
case ATTR_VALUE_box:
case ATTR_VALUE_border:
if (!has_border)
{
border_default_style = CSS_VALUE_solid;
border_default_width = CSS_BORDER_WIDTH_THIN;
}
break;
case ATTR_VALUE_lhs:
case ATTR_VALUE_rhs:
case ATTR_VALUE_vsides:
if (table_frame != ATTR_VALUE_rhs)
{
border.left.width = has_border ? border_default_width : CSS_BORDER_WIDTH_THIN;
if (border.left.style != CSS_VALUE_hidden)
border.left.style = has_border ? border_default_style : CSS_VALUE_solid;
}
if (table_frame != ATTR_VALUE_lhs)
{
border.right.width = has_border ? border_default_width : CSS_BORDER_WIDTH_THIN;
border.right.style = has_border ? border_default_style : CSS_VALUE_solid;
}
border_default_width = CSS_BORDER_WIDTH_MEDIUM;
if (border_default_style != CSS_VALUE_hidden)
border_default_style = CSS_VALUE_none;
break;
case ATTR_VALUE_above:
case ATTR_VALUE_below:
case ATTR_VALUE_hsides:
if (table_frame != ATTR_VALUE_below)
{
border.top.width = has_border ? border_default_width : CSS_BORDER_WIDTH_THIN;
if (border.top.style != CSS_VALUE_hidden)
border.top.style = has_border ? border_default_style : CSS_VALUE_solid;
}
if (table_frame != ATTR_VALUE_above)
{
border.bottom.width = has_border ? border_default_width : CSS_BORDER_WIDTH_THIN;
border.bottom.style = has_border ? border_default_style : CSS_VALUE_solid;
}
border_default_width = CSS_BORDER_WIDTH_MEDIUM;
if (border_default_style != CSS_VALUE_hidden)
border_default_style = CSS_VALUE_none;
break;
}
if (!css_properties->GetDecl(CSS_PROPERTY_border_spacing))
{
int border_spacing;
if (element->HasNumAttr(Markup::HA_CELLSPACING))
border_spacing = (int)(INTPTR)element->GetAttr(Markup::HA_CELLSPACING, ITEM_TYPE_NUM, (void*)0);
else
border_spacing = 2;
CSS_number_decl* decl = default_style->border_spacing;
decl->SetNumberValue(0, (float)border_spacing, CSS_PX);
css_properties->SetDecl(CSS_PROPERTY_border_spacing, decl);
}
if (html_align == CSS_VALUE_center)
{
margin_h_auto = TRUE;
html_align = CSS_VALUE_UNSPECIFIED;
}
if (!css_properties->GetDecl(CSS_PROPERTY_border_collapse))
{
CSS_type_decl* decl = default_style->border_collapse;
decl->SetTypeValue(border_collapse);
css_properties->SetDecl(CSS_PROPERTY_border_collapse, decl);
}
replaced_set_html_align = TRUE;
}
break;
case Markup::HTE_IMG:
case Markup::HTE_OBJECT:
if (element->HasNumAttr(Markup::HA_BORDER))
{
border_default_width = (short)(INTPTR)element->GetAttr(Markup::HA_BORDER, ITEM_TYPE_NUM, (void*)1);
border_default_style = CSS_VALUE_solid;
}
// fall-through
case Markup::HTE_EMBED:
case Markup::HTE_APPLET:
replaced_set_html_align = TRUE;
#ifdef CANVAS_SUPPORT
// fall-through
case Markup::HTE_CANVAS:
#endif // CANVAS_SUPPORT
replaced_elm = TRUE;
break;
#ifdef MEDIA_HTML_SUPPORT
case Markup::HTE_AUDIO:
if (set_display)
if (element->GetBoolAttr(Markup::HA_CONTROLS))
display_type = CSS_VALUE_inline;
else
display_type = CSS_VALUE_none;
break;
#endif // MEDIA_HTML_SUPPORT
case Markup::HTE_EM:
case Markup::HTE_I:
case Markup::HTE_VAR:
case Markup::HTE_CITE:
case Markup::HTE_DFN:
font_italic = CSS_VALUE_italic;
break;
case Markup::HTE_B:
case Markup::HTE_STRONG:
font_weight = 7;
break;
case Markup::HTE_BLINK:
decoration_flags |= CSS_TEXT_DECORATION_blink;
break;
case Markup::HTE_Q:
// Add quotes before and after
element->SetCheckForPseudo(CSS_PSEUDO_CLASS_BEFORE|CSS_PSEUDO_CLASS_AFTER);
if (!css_properties->GetDecl(CSS_PROPERTY_quotes))
css_properties->SetDecl(CSS_PROPERTY_quotes, default_style->quotes);
break;
case Markup::HTE_ABBR:
case Markup::HTE_ACRONYM:
if (element->HasAttr(Markup::HA_TITLE))
{
border.bottom.style = CSS_VALUE_dotted;
border.bottom.width = 1;
}
break;
case Markup::HTE_DIV:
case Markup::HTE_FIGURE:
case Markup::HTE_FIGCAPTION:
case Markup::HTE_SECTION:
case Markup::HTE_NAV:
case Markup::HTE_ARTICLE:
case Markup::HTE_ASIDE:
case Markup::HTE_HGROUP:
case Markup::HTE_HEADER:
case Markup::HTE_FOOTER:
if (set_display)
display_type = CSS_VALUE_block;
break;
case Markup::HTE_CENTER:
if (set_display)
display_type = CSS_VALUE_block;
text_align = CSS_VALUE_center;
break;
case Markup::HTE_TBODY:
case Markup::HTE_THEAD:
case Markup::HTE_TFOOT:
if (set_display)
{
if (elm_type == Markup::HTE_TBODY)
display_type = CSS_VALUE_table_row_group;
else
if (elm_type == Markup::HTE_THEAD)
display_type = CSS_VALUE_table_header_group;
else
display_type = CSS_VALUE_table_footer_group;
}
if (set_valign)
{
vertical_align_type = (CSSValue)(INTPTR)element->GetAttr(Markup::HA_VALIGN, ITEM_TYPE_NUM, (void*)CSS_VALUE_UNSPECIFIED);
if (vertical_align_type == CSS_VALUE_UNSPECIFIED)
vertical_align_type = CSS_VALUE_middle;
}
break;
case Markup::HTE_COL:
if (set_display)
display_type = CSS_VALUE_table_column;
break;
case Markup::HTE_COLGROUP:
if (set_display)
display_type = CSS_VALUE_table_column_group;
break;
case Markup::HTE_TD:
case Markup::HTE_TH:
{
if (set_bg_color &&
layout_mode != LAYOUT_SSR &&
g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(css_handling, PrefsCollectionDisplay::EnableAuthorFontAndColors)))
{
bg_color = (long)element->GetAttr(Markup::HA_BGCOLOR, ITEM_TYPE_NUM, (void*)USE_DEFAULT_COLOR);
}
if (elm_type == Markup::HTE_TH)
font_weight = 7;
if (set_white_space &&
(!absolute_width || hld_profile->IsInStrictMode()) && // IE7 (and earlier) ignores nowrap on TH/TD if width is set to an absolute value (not %)
element->HasAttr(Markup::HA_NOWRAP))
white_space = CSS_VALUE_nowrap;
// Check if table element has cellpadding.
HTML_Element* h = element->Parent();
while (h)
{
if (h->Type() == Markup::HTE_TABLE && h->GetInserted() != HE_INSERTED_BY_LAYOUT)
{
default_padding_vert = default_padding_horz = (short) h->GetNumAttr(Markup::HA_CELLPADDING, NS_IDX_HTML, DEFAULT_CELL_PADDING);
break;
}
h = h->Parent();
}
if (set_valign)
{
vertical_align_type = (CSSValue)(INTPTR)element->GetAttr(Markup::HA_VALIGN, ITEM_TYPE_NUM, (void*)CSS_VALUE_UNSPECIFIED);
if (vertical_align_type == CSS_VALUE_UNSPECIFIED)
vertical_align_type = CSS_VALUE_inherit;
}
}
if (set_display)
display_type = CSS_VALUE_table_cell;
break;
case Markup::HTE_TR:
if (set_bg_color &&
layout_mode != LAYOUT_SSR &&
g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(css_handling, PrefsCollectionDisplay::EnableAuthorFontAndColors)))
{
bg_color = (long)element->GetAttr(Markup::HA_BGCOLOR, ITEM_TYPE_NUM, (void*)USE_DEFAULT_COLOR);
}
if (set_display)
display_type = CSS_VALUE_table_row;
if (set_valign)
{
vertical_align_type = (CSSValue)(INTPTR)element->GetAttr(Markup::HA_VALIGN, ITEM_TYPE_NUM, (void*)CSS_VALUE_UNSPECIFIED);
if (vertical_align_type == CSS_VALUE_UNSPECIFIED)
{
HTML_Element* parent = element->ParentActualStyle();
vertical_align_type = parent && parent->Type() == Markup::HTE_TABLE ? CSS_VALUE_middle : CSS_VALUE_inherit;
}
}
break;
case Markup::HTE_FONT:
if (g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(css_handling, PrefsCollectionDisplay::EnableAuthorFontAndColors)))
{
COLORREF font_color = element->GetFontColor();
if (font_color != USE_DEFAULT_COLOR)
{
CSS_long_decl* decl = default_style->font_color;
decl->SetLongValue(font_color);
css_properties->SetDecl(CSS_PROPERTY_font_color, decl);
}
if (element->GetFontSizeDefined())
{
if (!css_properties->GetDecl(CSS_PROPERTY_font_size))
{
CSS_type_decl* font_size_decl = default_style->font_size_type;
font_size_decl->SetTypeValue(CSS_VALUE_use_lang_def);
css_properties->SetDecl(CSS_PROPERTY_font_size, font_size_decl);
}
}
int tmp_font_number = element->GetFontNumber();
if (tmp_font_number >= 0 && styleManager->HasFont(tmp_font_number))
font_number = tmp_font_number;
}
break;
case Markup::HTE_A:
if (set_fg_color || !css_properties->GetDecl(CSS_PROPERTY_text_decoration) || g_pcdisplay->GetIntegerPref(PrefsCollectionDisplay::LinkHasFrame))
GetAnchorStyle(context_elm, set_fg_color, fg_color, decoration_flags, border_default_style, border_default_width);
break;
case Markup::HTE_SMALL:
case Markup::HTE_BIG:
break;
case Markup::HTE_SUB:
case Markup::HTE_SUP:
if (set_valign)
vertical_align_type = (elm_type == Markup::HTE_SUB) ? CSS_VALUE_sub : CSS_VALUE_super;
break;
#ifdef SUPPORT_TEXT_DIRECTION
case Markup::HTE_BDO:
if (element->HasNumAttr(Markup::HA_DIR) || !hld_profile->IsInStrictMode())
unicode_bidi = CSS_VALUE_bidi_override;
// direction will be set by default further down
break;
#endif
case Markup::HTE_U:
case Markup::HTE_INS:
decoration_flags = CSS_TEXT_DECORATION_underline;
break;
case Markup::HTE_S:
case Markup::HTE_STRIKE:
case Markup::HTE_DEL:
decoration_flags = CSS_TEXT_DECORATION_line_through;
break;
case Markup::HTE_MARK:
if (set_fg_color)
fg_color = OP_RGB(0, 0, 0);
if (set_bg_color)
bg_color = OP_RGB(255, 255, 0);
break;
case Markup::HTE_P:
#ifdef _WML_SUPPORT_
if (set_white_space && element->HasNumAttr(Markup::WMLA_MODE, NS_IDX_WML) && element->GetNumAttr(Markup::WMLA_MODE, NS_IDX_WML) == WATTR_VALUE_nowrap)
white_space = CSS_VALUE_nowrap;
#endif //_WML_SUPPORT_
case Markup::HTE_DL:
case Markup::HTE_DT:
case Markup::HTE_DD:
if (set_display)
display_type = CSS_VALUE_block;
break;
case Markup::HTE_UL:
case Markup::HTE_OL:
if (set_display)
display_type = CSS_VALUE_block;
if (!css_properties->GetDecl(CSS_PROPERTY_list_style_type))
{
CSS_type_decl* decl = default_style->list_style_type;
decl->SetTypeValue(element->GetListType());
css_properties->SetDecl(CSS_PROPERTY_list_style_type, decl);
}
if (!css_properties->GetDecl(CSS_PROPERTY_list_style_position))
{
CSS_type_decl* decl = default_style->list_style_pos;
decl->SetTypeValue(CSS_VALUE_outside);
css_properties->SetDecl(CSS_PROPERTY_list_style_position, decl);
}
break;
case Markup::HTE_LI:
if (!css_properties->GetDecl(CSS_PROPERTY_list_style_position))
{
HTML_Element* h = element->ParentActualStyle();
if (h && h->Type() != Markup::HTE_UL && h->Type() != Markup::HTE_OL && h->Type() != Markup::HTE_DIR && h->Type() != Markup::HTE_MENU)
{
CSS_type_decl* decl = default_style->list_style_pos;
decl->SetTypeValue(CSS_VALUE_inside);
css_properties->SetDecl(CSS_PROPERTY_list_style_position, decl);
}
}
if (set_display)
display_type = CSS_VALUE_list_item;
if (!css_properties->GetDecl(CSS_PROPERTY_list_style_type) && element->HasAttr(Markup::HA_TYPE))
{
CSS_type_decl* decl = default_style->list_style_type;
decl->SetTypeValue(element->GetListType());
css_properties->SetDecl(CSS_PROPERTY_list_style_type, decl);
}
break;
case Markup::HTE_CAPTION:
{
if (set_display)
display_type = CSS_VALUE_table_caption;
if (html_align != CSS_VALUE_left && html_align != CSS_VALUE_right)
{
if (html_align == CSS_VALUE_bottom && !css_properties->GetDecl(CSS_PROPERTY_caption_side))
css_properties->SetDecl(CSS_PROPERTY_caption_side, default_style->caption_side);
html_align = CSS_VALUE_center;
}
}
break;
case Markup::HTE_NOBR:
if (set_white_space)
white_space = CSS_VALUE_nowrap;
break;
case Markup::HTE_BR:
{
// CHECK: should we support 'clear' attribute for other elements than BR ?
if (!css_properties->GetDecl(CSS_PROPERTY_clear))
{
int html_clear = (int) element->GetNumAttr(Markup::HA_CLEAR, NS_IDX_HTML, CLEAR_NONE);
CSSValue clear;
switch (html_clear)
{
case CLEAR_LEFT:
clear = CSS_VALUE_left; break;
case CLEAR_RIGHT:
clear = CSS_VALUE_right; break;
case CLEAR_ALL:
clear = CSS_VALUE_both; break;
default:
clear = CSS_VALUE_UNSPECIFIED; break;
}
if (clear != CSS_VALUE_UNSPECIFIED)
{
CSS_type_decl* decl = default_style->clear;
decl->SetTypeValue(clear);
css_properties->SetDecl(CSS_PROPERTY_clear, decl);
}
}
}
break;
case Markup::HTE_HR:
{
if (set_display)
display_type = CSS_VALUE_block;
if (html_align != CSS_VALUE_right && !css_properties->GetDecl(CSS_PROPERTY_margin_right))
css_properties->SetDecl(CSS_PROPERTY_margin_right, default_style->margin_right);
if (html_align != CSS_VALUE_left && !css_properties->GetDecl(CSS_PROPERTY_margin_left))
css_properties->SetDecl(CSS_PROPERTY_margin_left, default_style->margin_left);
html_align = CSS_VALUE_UNSPECIFIED;
int content_height = (int)(INTPTR)element->GetAttr(Markup::HA_SIZE, ITEM_TYPE_NUM, (void*)(INTPTR)2, NS_IDX_DEFAULT);
COLORREF color = element->GetFontColor();
if (!element->HasAttr(Markup::HA_NOSHADE))
{
border_default_width = 1;
if (color == USE_DEFAULT_COLOR)
{
border_default_style = CSS_VALUE_inset;
}
else
{
border_default_color = color;
border_default_style = CSS_VALUE_solid;
if (set_bg_color)
bg_color = color;
}
if (content_height > 2)
content_height -= 2;
else
content_height = 0;
}
else
{
if (set_bg_color)
{
if (color != USE_DEFAULT_COLOR)
bg_color = color;
else
bg_color = OP_RGB(128, 128, 128);
}
if (content_height < 1)
content_height = 1;
}
if (!css_properties->GetDecl(CSS_PROPERTY_height))
{
default_style->content_height->SetNumberValue(0, (float)content_height, CSS_PX);
css_properties->SetDecl(CSS_PROPERTY_height, default_style->content_height);
}
}
break;
case Markup::HTE_BODY:
if (set_display)
display_type = CSS_VALUE_block;
if (layout_mode != LAYOUT_SSR)
{
if (g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(css_handling, PrefsCollectionDisplay::EnableAuthorFontAndColors)))
{
if (set_bg_color)
bg_color = hld_profile->GetBgColor();
if (!css_properties->GetDecl(CSS_PROPERTY_background_attachment) && element->HasAttr(Markup::HA_BGPROPERTIES))
css_properties->SetDecl(CSS_PROPERTY_background_attachment, default_style->bg_attach);
if (set_fg_color && element->HasAttr(Markup::HA_TEXT))
{
COLORREF tmp_color = element->GetTextColor();
if (tmp_color != USE_DEFAULT_COLOR)
fg_color = tmp_color;
}
}
has_left_margin = element->HasNumAttr(Markup::HA_LEFTMARGIN);
has_top_margin = element->HasNumAttr(Markup::HA_TOPMARGIN);
if (has_left_margin)
margin_padding[MARGIN_LEFT] = (short)(INTPTR)element->GetAttr(Markup::HA_LEFTMARGIN, ITEM_TYPE_NUM, (void*)(long)margin_padding[MARGIN_LEFT]);
else if (element->HasNumAttr(Markup::HA_MARGINWIDTH))
{
has_left_margin = TRUE;
margin_padding[MARGIN_LEFT] = (short)(INTPTR)element->GetAttr(Markup::HA_MARGINWIDTH, ITEM_TYPE_NUM, (void*)(long)default_padding_horz);
}
if (has_top_margin)
margin_padding[MARGIN_TOP] = (short)(INTPTR)element->GetAttr(Markup::HA_TOPMARGIN, ITEM_TYPE_NUM, (void*)(long)margin_padding[MARGIN_TOP]);
else if (element->HasNumAttr(Markup::HA_MARGINHEIGHT))
{
has_top_margin = TRUE;
margin_padding[MARGIN_TOP] = (short)(INTPTR)element->GetAttr(Markup::HA_MARGINHEIGHT, ITEM_TYPE_NUM, (void*)(long)default_padding_vert);
}
if (!has_left_margin || !has_top_margin)
{
FramesDocElm* frm_doc_elm = m_doc->GetDocManager()->GetFrame();
if (frm_doc_elm)
{
if (!has_left_margin)
margin_padding[MARGIN_LEFT] = frm_doc_elm->GetFrameMarginWidth();
if (!has_top_margin)
margin_padding[MARGIN_TOP] = frm_doc_elm->GetFrameMarginHeight();
}
else
{
if (!has_left_margin)
margin_padding[MARGIN_LEFT] = 8;
if (!has_top_margin)
margin_padding[MARGIN_TOP] = 8;
}
has_left_margin = has_top_margin = TRUE;
}
}
break;
case Markup::HTE_VIDEO:
if (!css_properties->GetDecl(CSS_PROPERTY__o_object_fit))
{
css_properties->SetDecl(CSS_PROPERTY__o_object_fit, default_style->object_fit);
}
break;
case Markup::HTE_PRE:
case Markup::HTE_XMP:
case Markup::HTE_LISTING:
case Markup::HTE_PLAINTEXT:
if (set_white_space)
if (elm_type == Markup::HTE_PRE && element->HasAttr(Markup::HA_WRAP))
white_space = CSS_VALUE_pre_wrap;
else
white_space = CSS_VALUE_pre;
// fall through
default:
{
WritingSystem::Script script = WritingSystem::Unknown;
#ifdef FONTSWITCHING
script = hld_profile->GetPreferredScript();
#endif // FONTSWITCHING
const PresentationAttr& p_attr = style->GetPresentationAttr();
FontAtt* font = p_attr.GetPresentationFont(script).Font;
if (font)
{
if (set_display &&
elm_type != Markup::HTE_CODE && elm_type != Markup::HTE_SAMP &&
elm_type != Markup::HTE_TT && elm_type != Markup::HTE_KBD)
display_type = CSS_VALUE_block;
BOOL use_user_font_setting = g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(css_handling, PrefsCollectionDisplay::EnableUserFontAndColors));
if (set_fg_color && use_user_font_setting && (
!g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(css_handling, PrefsCollectionDisplay::EnableAuthorFontAndColors))))
{
fg_color = p_attr.Color;
}
if (use_user_font_setting && !p_attr.InheritFontSize)
font_size = op_abs(font->GetHeight());
else
{
switch (elm_type)
{
case Markup::HTE_H1:
rel_font_size = 2.0f;
break;
case Markup::HTE_H2:
rel_font_size = 1.5f;
break;
case Markup::HTE_H3:
rel_font_size = 1.17f;
break;
case Markup::HTE_H5:
rel_font_size = 0.83f;
break;
case Markup::HTE_H6:
rel_font_size = 0.67f;
break;
case Markup::HTE_PRE:
case Markup::HTE_LISTING:
case Markup::HTE_PLAINTEXT:
case Markup::HTE_XMP:
case Markup::HTE_CODE:
case Markup::HTE_SAMP:
case Markup::HTE_TT:
case Markup::HTE_KBD:
rel_font_size = 0.8125f;
break;
default:
break;
}
}
if (g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(css_handling, PrefsCollectionDisplay::EnableUserFontAndColors)) ||
elm_type == Markup::HTE_PRE || elm_type == Markup::HTE_LISTING || elm_type == Markup::HTE_PLAINTEXT ||
elm_type == Markup::HTE_XMP || elm_type == Markup::HTE_CODE || elm_type == Markup::HTE_SAMP ||
elm_type == Markup::HTE_TT || elm_type == Markup::HTE_KBD)
{
if (!css_properties->GetDecl(CSS_PROPERTY_font_family))
{
CSS_type_decl* font_family_type = default_style->font_family_type;
font_family_type->SetTypeValue(CSS_VALUE_use_lang_def);
css_properties->SetDecl(CSS_PROPERTY_font_family, font_family_type);
}
}
if (font->GetWeight() != 4)
font_weight = font->GetWeight();
if (p_attr.Italic)
font_italic = CSS_VALUE_italic;
}
break;
}
}
CSSValue float_type = CSS_VALUE_none;
if (replaced_set_html_align)
{
if (html_align == CSS_VALUE_left ||
html_align == CSS_VALUE_right)
{
if (html_align == CSS_VALUE_left)
float_type = CSS_VALUE_left;
else
float_type = CSS_VALUE_right;
html_align = CSS_VALUE_UNSPECIFIED;
if (!css_properties->GetDecl(CSS_PROPERTY_float))
{
CSS_type_decl* decl = default_style->float_decl;
decl->SetTypeValue(float_type);
css_properties->SetDecl(CSS_PROPERTY_float, decl);
}
}
else
float_type = CSS_VALUE_none;
if (set_valign && elm_type != Markup::HTE_TABLE)
if (html_align == CSS_VALUE_top ||
html_align == CSS_VALUE_middle ||
html_align == CSS_VALUE_text_bottom)
vertical_align_type = html_align;
}
if (html_align != CSS_VALUE_UNSPECIFIED)
{
text_align = html_align;
}
if (set_display && element->GetBoolAttr(Markup::HA_HIDDEN))
{
display_type = CSS_VALUE_none;
}
#ifdef SUPPORT_TEXT_DIRECTION
if (!css_properties->GetDecl(CSS_PROPERTY_direction) && element->HasNumAttr(Markup::HA_DIR)) // dont mess with dir if it's not there, it's inherited
{
CSSValue direction = CSSValue((INTPTR)element->GetAttr(Markup::HA_DIR, ITEM_TYPE_NUM, (void*) 0));
if (direction)
{
CSS_type_decl* decl = default_style->direction;
decl->SetTypeValue(direction);
css_properties->SetDecl(CSS_PROPERTY_direction, decl);
if (unicode_bidi != CSS_VALUE_bidi_override)
unicode_bidi = CSS_VALUE_embed;
}
}
if (unicode_bidi != CSS_VALUE_UNSPECIFIED && !css_properties->GetDecl(CSS_PROPERTY_unicode_bidi))
{
CSS_type_decl* decl = default_style->unicode_bidi;
decl->SetTypeValue(unicode_bidi);
css_properties->SetDecl(CSS_PROPERTY_unicode_bidi, decl);
}
#endif
if (element->IsMatchingType(Markup::HTE_DATALIST, NS_HTML))
display_type = CSS_VALUE_none;
BOOL margin_v_specified = FALSE;
if (replaced_elm)
{
margin_padding[MARGIN_LEFT] = margin_padding[MARGIN_RIGHT] = short((INTPTR)element->GetAttr(Markup::HA_HSPACE, ITEM_TYPE_NUM, (void*)(INTPTR)0));
margin_padding[MARGIN_TOP] = margin_padding[MARGIN_BOTTOM] = short((INTPTR)element->GetAttr(Markup::HA_VSPACE, ITEM_TYPE_NUM, (void*)(INTPTR)0));
}
else
if (float_type == CSS_VALUE_none)
{
BOOL drop_vertical_margin = FALSE;
if (elm_type == Markup::HTE_UL || elm_type == Markup::HTE_OL)
{
HTML_Element* h = element->Parent();
while (h)
{
if (h->Type() == Markup::HTE_UL || h->Type() == Markup::HTE_OL)
{
drop_vertical_margin = TRUE;
break;
}
h = h->Parent();
}
}
if (elm_type == Markup::HTE_FIELDSET)
{
/* Apply default vertical "separation" in the style settings
for this element to the padding properties instead of the
margin properties. */
margin_padding[PADDING_TOP] = (short)lattr.LeadingSeparation;
margin_padding[PADDING_BOTTOM] = (short)lattr.TrailingSeparation;
has_vertical_padding = TRUE;
}
else if (!has_top_margin && !drop_vertical_margin)
{
if (elm_type == Markup::HTE_FORM)
{
margin_padding[MARGIN_TOP] = (short)lattr.LeadingSeparation;
/*
* CORE-23030 Forms in standards mode should not have any margin-bottom,
* unlike quirks mode in which it has margin-bottom:1em
*
* CORE-4808 form sandwiched between table
* elements should not be rendered. Unfortunately,
* because the parser currently doesn't move the form's
* contents outside the table, we can only remove all
* the margin, so it doesn't affect table layout
*/
if (hld_profile->IsInStrictMode())
{
margin_padding[MARGIN_BOTTOM] = 0;
}
else
{
HTML_Element* he_parent = element->ParentActualStyle();
if (he_parent &&
(he_parent->Type() == Markup::HTE_TABLE ||
he_parent->Type() == Markup::HTE_THEAD ||
he_parent->Type() == Markup::HTE_TBODY ||
he_parent->Type() == Markup::HTE_TFOOT||
he_parent->Type() == Markup::HTE_TR)
)
{
margin_padding[MARGIN_BOTTOM] = 0;
}
else
margin_padding[MARGIN_BOTTOM] = (short)lattr.TrailingSeparation;
}
}
else
{
margin_padding[MARGIN_TOP] = (short)lattr.LeadingSeparation;
margin_padding[MARGIN_BOTTOM] = (short)lattr.TrailingSeparation;
}
}
if (elm_type == Markup::HTE_UL || elm_type == Markup::HTE_OL || elm_type == Markup::HTE_FIELDSET ||
elm_type == Markup::HTE_DIR || elm_type == Markup::HTE_MENU)
{
/* Apply default horizontal "offset" in the style settings for
this element to the padding properties instead of the margin
properties. */
margin_padding[PADDING_LEFT] = (short)lattr.LeftHandOffset;
margin_padding[PADDING_RIGHT] = (short)lattr.RightHandOffset;
has_horizontal_padding = TRUE;
}
else if (!has_left_margin)
{
margin_padding[MARGIN_LEFT] = (short)lattr.LeftHandOffset;
margin_padding[MARGIN_RIGHT] = (short)lattr.RightHandOffset;
}
if (has_top_margin && !has_bottom_margin)
margin_padding[MARGIN_BOTTOM] = margin_padding[MARGIN_TOP];
if (has_left_margin && !has_right_margin)
margin_padding[MARGIN_RIGHT] = margin_padding[MARGIN_LEFT];
if (hld_profile->IsInStrictMode() || elm_type == Markup::HTE_BODY)
{
margin_v_specified = TRUE;
}
}
if (!has_horizontal_padding)
margin_padding[PADDING_LEFT] = margin_padding[PADDING_RIGHT] = default_padding_horz;
if (!has_vertical_padding)
{
margin_padding[PADDING_TOP] = default_padding_vert;
if (margin_padding[PADDING_BOTTOM] < 0)
margin_padding[PADDING_BOTTOM] = default_padding_vert;
}
if (margin_h_auto)
{
if (!css_properties->GetDecl(CSS_PROPERTY_margin_left))
css_properties->SetDecl(CSS_PROPERTY_margin_left, default_style->margin_left);
if (!css_properties->GetDecl(CSS_PROPERTY_margin_right))
css_properties->SetDecl(CSS_PROPERTY_margin_right, default_style->margin_right);
}
const short margin_padding_props[MARGIN_PADDING_SIZE] = {
CSS_PROPERTY_margin_left,
CSS_PROPERTY_margin_right,
CSS_PROPERTY_margin_top,
CSS_PROPERTY_margin_bottom,
CSS_PROPERTY_padding_left,
CSS_PROPERTY_padding_right,
CSS_PROPERTY_padding_top,
CSS_PROPERTY_padding_bottom
};
for (int i=0; i<MARGIN_PADDING_SIZE; i++)
{
if (margin_padding[i] != 0 && !css_properties->GetDecl(margin_padding_props[i]))
{
CSS_number_decl* decl = default_style->margin_padding[i];
if (margin_padding[i] > 0)
decl->SetNumberValue(0, margin_padding[i], CSS_PX);
else
decl->SetNumberValue(0, (-margin_padding[i] / 24.0f), CSS_EM);
if (i == MARGIN_TOP || i == MARGIN_BOTTOM)
decl->SetUnspecified(!margin_v_specified);
css_properties->SetDecl(margin_padding_props[i], decl);
}
}
if (border_default_color != USE_DEFAULT_COLOR)
{
CSS_long_decl* decl = default_style->border_color;
decl->SetLongValue(border_default_color);
if (!css_properties->GetDecl(CSS_PROPERTY_border_left_color))
css_properties->SetDecl(CSS_PROPERTY_border_left_color, decl);
if (!css_properties->GetDecl(CSS_PROPERTY_border_right_color))
css_properties->SetDecl(CSS_PROPERTY_border_right_color, decl);
if (!css_properties->GetDecl(CSS_PROPERTY_border_top_color))
css_properties->SetDecl(CSS_PROPERTY_border_top_color, decl);
if (!css_properties->GetDecl(CSS_PROPERTY_border_bottom_color))
css_properties->SetDecl(CSS_PROPERTY_border_bottom_color, decl);
}
if (border_default_style != CSS_VALUE_none)
{
border.top.style = border_default_style;
border.left.style = border_default_style;
border.right.style = border_default_style;
border.bottom.style = border_default_style;
}
if (border_default_width != CSS_BORDER_WIDTH_MEDIUM)
{
border.top.width = border_default_width;
border.left.width = border_default_width;
border.right.width = border_default_width;
border.bottom.width = border_default_width;
}
if (border.left.style != BORDER_STYLE_NOT_SET && !css_properties->GetDecl(CSS_PROPERTY_border_left_style))
{
CSS_type_decl* decl = default_style->border_left_style;
decl->SetTypeValue(border.left.GetStyle());
css_properties->SetDecl(CSS_PROPERTY_border_left_style, decl);
}
if (border.right.style != BORDER_STYLE_NOT_SET && !css_properties->GetDecl(CSS_PROPERTY_border_right_style))
{
CSS_type_decl* decl = default_style->border_right_style;
decl->SetTypeValue(border.right.GetStyle());
css_properties->SetDecl(CSS_PROPERTY_border_right_style, decl);
}
if (border.top.style != BORDER_STYLE_NOT_SET && !css_properties->GetDecl(CSS_PROPERTY_border_top_style))
{
CSS_type_decl* decl = default_style->border_top_style;
decl->SetTypeValue(border.top.GetStyle());
css_properties->SetDecl(CSS_PROPERTY_border_top_style, decl);
}
if (border.bottom.style != BORDER_STYLE_NOT_SET && !css_properties->GetDecl(CSS_PROPERTY_border_bottom_style))
{
CSS_type_decl* decl = default_style->border_bottom_style;
decl->SetTypeValue(border.bottom.GetStyle());
css_properties->SetDecl(CSS_PROPERTY_border_bottom_style, decl);
}
if (border.left.width != BORDER_WIDTH_NOT_SET && !css_properties->GetDecl(CSS_PROPERTY_border_left_width))
{
CSS_number_decl* decl = default_style->border_left_width;
decl->SetNumberValue(0, (float)border.left.width, CSS_PX);
css_properties->SetDecl(CSS_PROPERTY_border_left_width, decl);
}
if (border.right.width != BORDER_WIDTH_NOT_SET && !css_properties->GetDecl(CSS_PROPERTY_border_right_width))
{
CSS_number_decl* decl = default_style->border_right_width;
decl->SetNumberValue(0, (float)border.right.width, CSS_PX);
css_properties->SetDecl(CSS_PROPERTY_border_right_width, decl);
}
if (border.top.width != BORDER_WIDTH_NOT_SET && !css_properties->GetDecl(CSS_PROPERTY_border_top_width))
{
CSS_number_decl* decl = default_style->border_top_width;
decl->SetNumberValue(0, (float)border.top.width, CSS_PX);
css_properties->SetDecl(CSS_PROPERTY_border_top_width, decl);
}
if (border.bottom.width != BORDER_WIDTH_NOT_SET && !css_properties->GetDecl(CSS_PROPERTY_border_bottom_width))
{
CSS_number_decl* decl = default_style->border_bottom_width;
decl->SetNumberValue(0, (float)border.bottom.width, CSS_PX);
css_properties->SetDecl(CSS_PROPERTY_border_bottom_width, decl);
}
if (display_type != CSS_VALUE_UNSPECIFIED)
{
CSS_type_decl* decl = default_style->display_type;
decl->SetTypeValue(display_type);
css_properties->SetDecl(CSS_PROPERTY_display, decl);
}
if (white_space != CSS_VALUE_UNSPECIFIED)
{
CSS_type_decl* decl = default_style->white_space;
decl->SetTypeValue(white_space);
css_properties->SetDecl(CSS_PROPERTY_white_space, decl);
}
if (bg_color != USE_DEFAULT_COLOR)
{
CSS_long_decl* decl = default_style->bg_color;
decl->SetLongValue(bg_color);
css_properties->SetDecl(CSS_PROPERTY_background_color, decl);
}
if (text_align != CSS_VALUE_UNSPECIFIED && !css_properties->GetDecl(CSS_PROPERTY_text_align))
{
CSS_type_decl* decl = default_style->text_align;
decl->SetTypeValue(text_align);
css_properties->SetDecl(CSS_PROPERTY_text_align, decl);
}
if (vertical_align_type != CSS_VALUE_UNSPECIFIED)
{
CSS_type_decl* decl = default_style->vertical_align;
decl->SetTypeValue(vertical_align_type);
css_properties->SetDecl(CSS_PROPERTY_vertical_align, decl);
}
if (text_indent != INT_MIN)
{
CSS_number_decl* decl = default_style->text_indent;
decl->SetNumberValue(0, (float)text_indent, CSS_PX);
css_properties->SetDecl(CSS_PROPERTY_text_indent, decl);
}
if (decoration_flags && !css_properties->GetDecl(CSS_PROPERTY_text_decoration))
{
CSS_type_decl* decl = default_style->text_decoration;
/* Text decoration flags are stored as CSSValue, carefully chosen not to
collide with other valid values for text-decoration. */
decl->SetTypeValue(CSSValue(decoration_flags));
css_properties->SetDecl(CSS_PROPERTY_text_decoration, decl);
}
if (fg_color != USE_DEFAULT_COLOR)
{
CSS_long_decl* decl = default_style->fg_color;
decl->SetLongValue(fg_color);
css_properties->SetDecl(CSS_PROPERTY_color, decl);
}
if ((font_size > 0 || rel_font_size != 0) && !css_properties->GetDecl(CSS_PROPERTY_font_size))
{
if (rel_font_size == 0)
rel_font_size = font_size;
CSS_number_decl* decl = default_style->font_size;
decl->SetNumberValue(0, rel_font_size, font_size > 0 ? CSS_PX : CSS_EM);
css_properties->SetDecl(CSS_PROPERTY_font_size, decl);
}
if (font_weight > 0 && !css_properties->GetDecl(CSS_PROPERTY_font_weight))
{
CSS_number_decl* decl = default_style->font_weight;
decl->SetNumberValue(0, font_weight, CSS_NUMBER);
css_properties->SetDecl(CSS_PROPERTY_font_weight, decl);
}
if (font_number >= 0 && !css_properties->GetDecl(CSS_PROPERTY_font_family))
{
CSS_heap_gen_array_decl* decl = default_style->font_family;
/* Both font numbers and CSSValues are stored in the declaration array. A font number is
stored as a plain CSSValue, while a "real" CSSValue is tagged with
CSS_GENERIC_FONT_FAMILY. */
decl->GenArrayValueRep()->SetType(CSSValue(font_number));
css_properties->SetDecl(CSS_PROPERTY_font_family, decl);
}
if (font_italic != CSS_VALUE_UNSPECIFIED && !css_properties->GetDecl(CSS_PROPERTY_font_style))
{
CSS_type_decl* decl = default_style->font_style;
decl->SetTypeValue(font_italic);
css_properties->SetDecl(CSS_PROPERTY_font_style, decl);
}
const uni_char* uni_lang = element->GetStringAttr(Markup::HA_LANG);
if (uni_lang && *uni_lang)
{
WritingSystem::Script current_script = WritingSystem::FromLanguageCode(uni_lang);
CSS_long_decl* decl = default_style->writing_system;
decl->SetLongValue((long)current_script);
css_properties->SetDecl(CSS_PROPERTY_writing_system, decl);
}
#ifdef DOM_FULLSCREEN_MODE
if (context_elm->HasFullscreenStyles())
ApplyFullscreenProperties(context_elm, css_properties);
#endif // DOM_FULLSCREEN_MODE
return OpStatus::OK;
}
#ifdef MEDIA_HTML_SUPPORT
void CSSCollection::GetDefaultCueStyleProperties(HTML_Element* element, CSS_Properties* css_properties)
{
Markup::Type element_type = element->Type();
StyleModule::DefaultStyle* default_style = &g_opera->style_module.default_style;
switch (element_type)
{
case Markup::CUEE_ROOT:
{
/* cue box "root"
color: 'white'
font: 5vh sans-serif
white-space: pre-line */
MediaCueDisplayState* cuestate = MediaCueDisplayState::GetFromHtmlElement(element);
if (!cuestate)
break;
if (!css_properties->GetDecl(CSS_PROPERTY_color))
{
CSS_long_decl* decl = default_style->fg_color;
decl->SetLongValue(OP_RGB(255, 255, 255));
css_properties->SetDecl(CSS_PROPERTY_color, decl);
}
if (!css_properties->GetDecl(CSS_PROPERTY_white_space))
{
CSS_type_decl* decl = default_style->white_space;
decl->SetTypeValue(CSS_VALUE_pre_line);
css_properties->SetDecl(CSS_PROPERTY_white_space, decl);
}
float font_size = cuestate->GetFontSize();
if (font_size != 0 && !css_properties->GetDecl(CSS_PROPERTY_font_size))
{
CSS_number_decl* decl = default_style->font_size;
decl->SetNumberValue(0, font_size, CSS_PX);
css_properties->SetDecl(CSS_PROPERTY_font_size, decl);
}
short font_number = styleManager->GetGenericFontNumber(StyleManager::SANS_SERIF,
cuestate->GetScript());
if (font_number >= 0 && !css_properties->GetDecl(CSS_PROPERTY_font_family))
{
CSS_heap_gen_array_decl* decl = default_style->font_family;
decl->GenArrayValueRep()->SetType(CSSValue(font_number));
css_properties->SetDecl(CSS_PROPERTY_font_family, decl);
}
/* The following properties are "external input" used to get the
correct behavior out of the layout engine.
Some of the below ('direction', 'text-align' and 'width') stem
from the WebVTT rendering specification. */
OP_ASSERT(!css_properties->GetDecl(CSS_PROPERTY_display));
CSS_type_decl* display_decl = default_style->display_type;
display_decl->SetTypeValue(CSS_VALUE_block);
css_properties->SetDecl(CSS_PROPERTY_display, display_decl);
OP_ASSERT(!css_properties->GetDecl(CSS_PROPERTY_width));
CSS_number_decl* width_decl = default_style->content_width;
width_decl->SetNumberValue(0, (float)cuestate->GetRect().width, CSS_PX);
css_properties->SetDecl(CSS_PROPERTY_width, width_decl);
OP_ASSERT(!css_properties->GetDecl(CSS_PROPERTY_direction));
CSS_type_decl* dir_decl = default_style->direction;
dir_decl->SetTypeValue(cuestate->GetDirection());
css_properties->SetDecl(CSS_PROPERTY_direction, dir_decl);
OP_ASSERT(!css_properties->GetDecl(CSS_PROPERTY_text_align));
CSS_type_decl* text_align_decl = default_style->text_align;
text_align_decl->SetTypeValue(cuestate->GetAlignment());
css_properties->SetDecl(CSS_PROPERTY_text_align, text_align_decl);
OP_ASSERT(!css_properties->GetDecl(CSS_PROPERTY_overflow_wrap));
css_properties->SetDecl(CSS_PROPERTY_overflow_wrap, default_style->overflow_wrap);
/* The following style is really for the "background box", but we
let it apply to the root, and then inherit it to the
background-box and skip applying it for the root
background: rgba(0,0,0,0.8) */
if (!css_properties->GetDecl(CSS_PROPERTY_background_color))
{
CSS_long_decl* decl = default_style->bg_color;
decl->SetLongValue(OP_RGBA(0, 0, 0, 204));
css_properties->SetDecl(CSS_PROPERTY_background_color, decl);
}
}
break;
case Markup::CUEE_I: /* 'i' - font-style: italic */
if (!css_properties->GetDecl(CSS_PROPERTY_font_style))
{
CSS_type_decl* decl = default_style->font_style;
decl->SetTypeValue(CSS_VALUE_italic);
css_properties->SetDecl(CSS_PROPERTY_font_style, decl);
}
break;
case Markup::CUEE_B: /* 'b' - font-weight: bold */
if (!css_properties->GetDecl(CSS_PROPERTY_font_weight))
{
CSS_number_decl* decl = default_style->font_weight;
decl->SetNumberValue(0, 7, CSS_NUMBER);
css_properties->SetDecl(CSS_PROPERTY_font_weight, decl);
}
break;
case Markup::CUEE_U: /* 'u' - text-decoration: underline */
if (!css_properties->GetDecl(CSS_PROPERTY_text_decoration))
{
CSS_type_decl* decl = default_style->text_decoration;
decl->SetTypeValue(CSSValue(CSS_TEXT_DECORATION_underline));
css_properties->SetDecl(CSS_PROPERTY_text_decoration, decl);
}
break;
default:
break;
}
}
#endif // MEDIA_HTML_SUPPORT
#ifdef DOM_FULLSCREEN_MODE
void CSSCollection::ApplyFullscreenProperties(CSS_MatchContextElm* context_elm, CSS_Properties* css_properties)
{
/* Below is the UA stylesheet for fullscreen elements and ancestors taken
from a snapshot of the spec draft for Fullscreen API:
http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html#rendering
Applied between author and author important:
:fullscreen {
position:fixed;
top:0;
left:0;
right:0;
bottom:0;
z-index:2147483647;
box-sizing:border-box;
margin:0;
width:100%;
height:100%;
}
// If there is a fullscreen element that is not the root then
// we should hide the viewport scrollbar.
:fullscreen-ancestor:root {
overflow:hidden;
}
:fullscreen-ancestor {
// Ancestors of a fullscreen element should not induce stacking contexts
// that would prevent the fullscreen element from being on top.
z-index:auto;
// Ancestors of a fullscreen element should not be partially transparent,
// since that would apply to the fullscreen element and make the page visible
// behind it. It would also create a pseudo-stacking-context that would let content
// draw on top of the fullscreen element.
opacity:1;
// Ancestors of a fullscreen element should not apply SVG masking, clipping, or
// filtering, since that would affect the fullscreen element and create a pseudo-
// stacking context.
mask:none;
clip:auto;
filter:none;
transform:none;
transition:none;
}
Applied as normal UA style:
:fullscreen {
background: black;
color: white;
}
// This rule is not in the spec at the time of writing.
iframe:fullscreen {
border-style: none;
}
*/
BOOL true_fullscreen = TRUE;
StyleModule::DefaultStyle* default_style = &g_opera->style_module.default_style;
/* Add fullscreen default style between author and author
important and update true_fullscreen flag accordingly. */
#define FULLSCREEN_DEFAULT_STYLE(prop, def) \
do { \
decl = css_properties->GetDecl((prop)); \
if (!decl || !decl->GetImportant()) \
css_properties->SetDecl((prop), (def)); \
else \
true_fullscreen = FALSE; \
} while (0)
CSS_decl* decl;
if (context_elm->IsFullscreenElement())
{
FULLSCREEN_DEFAULT_STYLE(CSS_PROPERTY_position, default_style->fullscreen_fixed);
FULLSCREEN_DEFAULT_STYLE(CSS_PROPERTY_top, default_style->fullscreen_top);
FULLSCREEN_DEFAULT_STYLE(CSS_PROPERTY_left, default_style->fullscreen_left);
FULLSCREEN_DEFAULT_STYLE(CSS_PROPERTY_right, default_style->fullscreen_right);
FULLSCREEN_DEFAULT_STYLE(CSS_PROPERTY_bottom, default_style->fullscreen_bottom);
FULLSCREEN_DEFAULT_STYLE(CSS_PROPERTY_z_index, default_style->fullscreen_zindex);
FULLSCREEN_DEFAULT_STYLE(CSS_PROPERTY_box_sizing, default_style->fullscreen_box_sizing);
FULLSCREEN_DEFAULT_STYLE(CSS_PROPERTY_margin_top, default_style->fullscreen_margin_top);
FULLSCREEN_DEFAULT_STYLE(CSS_PROPERTY_margin_left, default_style->fullscreen_margin_left);
FULLSCREEN_DEFAULT_STYLE(CSS_PROPERTY_margin_right, default_style->fullscreen_margin_right);
FULLSCREEN_DEFAULT_STYLE(CSS_PROPERTY_margin_bottom, default_style->fullscreen_margin_bottom);
FULLSCREEN_DEFAULT_STYLE(CSS_PROPERTY_width, default_style->fullscreen_width);
FULLSCREEN_DEFAULT_STYLE(CSS_PROPERTY_height, default_style->fullscreen_height);
// UA level style
decl = css_properties->GetDecl(CSS_PROPERTY_background_color);
if (!decl || decl == default_style->bg_color)
{
CSS_long_decl* bg_decl = default_style->bg_color;
bg_decl->SetLongValue(OP_RGB(0, 0, 0));
css_properties->SetDecl(CSS_PROPERTY_background_color, bg_decl);
}
else
{
CSSDeclType type = decl->GetDeclType();
if (type == CSS_DECL_COLOR || type == CSS_DECL_LONG)
{
COLORREF col = static_cast<COLORREF>(decl->LongValue());
col = GetRGBA(col);
if (OP_GET_A_VALUE(col) != 255)
true_fullscreen = FALSE;
}
else
true_fullscreen = FALSE;
}
decl = css_properties->GetDecl(CSS_PROPERTY_color);
if (!decl || decl == default_style->fg_color)
{
CSS_long_decl* fg_decl = default_style->fg_color;
fg_decl->SetLongValue(OP_RGB(255, 255, 255));
css_properties->SetDecl(CSS_PROPERTY_color, fg_decl);
}
if (context_elm->Type() == Markup::HTE_IFRAME && context_elm->GetNsType() == NS_HTML)
{
if (css_properties->GetDecl(CSS_PROPERTY_border_top_style) == default_style->border_top_style)
css_properties->SetDecl(CSS_PROPERTY_border_top_style, NULL);
else
true_fullscreen = FALSE;
if (css_properties->GetDecl(CSS_PROPERTY_border_left_style) == default_style->border_left_style)
css_properties->SetDecl(CSS_PROPERTY_border_left_style, NULL);
else
true_fullscreen = FALSE;
if (css_properties->GetDecl(CSS_PROPERTY_border_right_style) == default_style->border_right_style)
css_properties->SetDecl(CSS_PROPERTY_border_right_style, NULL);
else
true_fullscreen = FALSE;
if (css_properties->GetDecl(CSS_PROPERTY_border_bottom_style) == default_style->border_bottom_style)
css_properties->SetDecl(CSS_PROPERTY_border_bottom_style, NULL);
else
true_fullscreen = FALSE;
if (css_properties->GetDecl(CSS_PROPERTY_padding_top) ||
css_properties->GetDecl(CSS_PROPERTY_padding_left) ||
css_properties->GetDecl(CSS_PROPERTY_padding_right) ||
css_properties->GetDecl(CSS_PROPERTY_padding_bottom))
true_fullscreen = FALSE;
}
}
else if (context_elm->IsFullscreenAncestor())
{
if (context_elm->IsRoot())
{
FULLSCREEN_DEFAULT_STYLE(CSS_PROPERTY_overflow_x, default_style->fullscreen_overflow_x);
FULLSCREEN_DEFAULT_STYLE(CSS_PROPERTY_overflow_y, default_style->fullscreen_overflow_y);
}
FULLSCREEN_DEFAULT_STYLE(CSS_PROPERTY_z_index, default_style->fullscreen_zindex_auto);
FULLSCREEN_DEFAULT_STYLE(CSS_PROPERTY_opacity, default_style->fullscreen_opacity);
FULLSCREEN_DEFAULT_STYLE(CSS_PROPERTY_mask, default_style->fullscreen_mask);
FULLSCREEN_DEFAULT_STYLE(CSS_PROPERTY_clip, default_style->fullscreen_clip);
FULLSCREEN_DEFAULT_STYLE(CSS_PROPERTY_filter, default_style->fullscreen_filter);
# ifdef CSS_TRANSFORMS
FULLSCREEN_DEFAULT_STYLE(CSS_PROPERTY_transform, default_style->fullscreen_transform);
# endif // CSS_TRANSFORMS
# ifdef CSS_TRANSITIONS
FULLSCREEN_DEFAULT_STYLE(CSS_PROPERTY_transition_property, default_style->fullscreen_trans_prop);
FULLSCREEN_DEFAULT_STYLE(CSS_PROPERTY_transition_delay, default_style->fullscreen_trans_delay);
FULLSCREEN_DEFAULT_STYLE(CSS_PROPERTY_transition_duration, default_style->fullscreen_trans_duration);
FULLSCREEN_DEFAULT_STYLE(CSS_PROPERTY_transition_timing_function, default_style->fullscreen_trans_timing);
# endif // CSS_TRANSITIONS
}
#undef FULLSCREEN_DEFAULT_STYLE
if (!true_fullscreen)
m_doc->SetFullscreenElementObscured();
}
#endif // DOM_FULLSCREEN_MODE
#ifdef CSS_VIEWPORT_SUPPORT
void CSSCollection::CascadeViewportProperties()
{
m_viewport.ResetComputedValues();
HLDocProfile* hld_prof = m_doc->GetHLDocProfile();
CSS_MediaType media_type = m_doc->GetMediaType();
const uni_char* hostname = m_doc->GetURL().GetAttribute(URL::KUniHostName).CStr();
if (g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(hld_prof->GetCSSMode(), PrefsCollectionDisplay::EnableAuthorCSS), hostname) || m_doc->GetWindow()->IsCustomWindow())
{
CSSCollectionElement* elm = m_element_list.Last();
CSS* top_css = NULL;
while (elm)
{
if (elm->IsStyleSheet())
{
CSS* css = static_cast<CSS*>(elm);
if (!css->IsImport())
top_css = css;
// All imported stylesheets must have an ascendent stylesheet which is stored as top_css.
OP_ASSERT(top_css != NULL);
BOOL skip_children = TRUE;
if (css->IsEnabled() && css->CheckMedia(m_doc, media_type))
{
css->GetViewportProperties(m_doc, &m_viewport, media_type);
skip_children = FALSE;
}
elm = css->GetNextImport(skip_children);
if (!elm)
{
elm = top_css;
while ((elm = static_cast<CSSCollectionElement*>(elm->Pred())) && elm->IsStyleSheet() && static_cast<CSS*>(elm)->IsImport())
;
}
}
else
{
if (elm->IsViewportMeta())
static_cast<CSS_ViewportMeta*>(elm)->AddViewportProperties(&m_viewport);
elm = elm->Pred();
}
}
}
if (g_pcdisplay->GetIntegerPref(g_pcdisplay->GetPrefFor(hld_prof->GetCSSMode(), PrefsCollectionDisplay::EnableUserCSS), hostname)
&& (m_doc->GetWindow()->IsNormalWindow() || m_doc->GetWindow()->IsThumbnailWindow()))
{
#ifdef LOCAL_CSS_FILES_SUPPORT
// Load all user style sheets defined in preferences
for (unsigned int j=0; j < g_pcfiles->GetLocalCSSCount(); j++)
{
CSS* css = g_cssManager->GetCSS(CSSManager::FirstUserStyle+j);
while (css)
{
BOOL skip_children = TRUE;
if (css->IsEnabled() && css->CheckMedia(m_doc, media_type))
{
css->GetViewportProperties(m_doc, &m_viewport, media_type);
skip_children = FALSE;
}
css = css->GetNextImport(skip_children);
}
}
# ifdef EXTENSION_SUPPORT
// Load all user style sheets defined by extensions
for (CSSManager::ExtensionStylesheet* extcss = g_cssManager->GetExtensionUserCSS(); extcss;
extcss = reinterpret_cast<CSSManager::ExtensionStylesheet*>(extcss->Suc()))
{
CSS* css = extcss->css;
while (css)
{
BOOL skip_children = TRUE;
if (css->IsEnabled() && css->CheckMedia(m_doc, media_type))
{
css->GetViewportProperties(m_doc, &m_viewport, media_type);
skip_children = FALSE;
}
css = css->GetNextImport(skip_children);
}
}
# endif
#endif // LOCAL_CSS_FILES_SUPPORT
#ifdef PREFS_HOSTOVERRIDE
CSS* css = m_host_overrides[CSSManager::LocalCSS].css;
if (!css)
css = g_cssManager->GetCSS(CSSManager::LocalCSS);
#else
CSS* css = g_cssManager->GetCSS(CSSManager::LocalCSS);
#endif
while (css)
{
BOOL skip_children = TRUE;
if (css->IsEnabled() && css->CheckMedia(m_doc, media_type))
{
css->GetViewportProperties(m_doc, &m_viewport, media_type);
skip_children = FALSE;
}
css = css->GetNextImport(skip_children);
}
}
#ifdef _WML_SUPPORT_
if (hld_prof->IsWml())
{
# ifdef PREFS_HOSTOVERRIDE
CSS* css = m_host_overrides[CSSManager::WML_CSS].css;
if (!css)
css = g_cssManager->GetCSS(CSSManager::WML_CSS);
# else
CSS* css = g_cssManager->GetCSS(CSSManager::WML_CSS);
# endif
if (css)
css->GetViewportProperties(m_doc, &m_viewport, media_type);
}
#endif
#if defined(CSS_MATHML_STYLESHEET) && defined(MATHML_ELEMENT_CODES)
CSS* css = g_cssManager->GetCSS(CSSManager::MathML_CSS);
if (css)
css->GetViewportProperties(m_doc, &m_viewport, media_type);
#endif // CSS_MATHML_STYLESHEET && MATHML_ELEMENT_CODES
#ifdef PREFS_HOSTOVERRIDE
CSS* browser_css = m_host_overrides[CSSManager::BrowserCSS].css;
if (!browser_css)
browser_css = g_cssManager->GetCSS(CSSManager::BrowserCSS);
#else
CSS* browser_css = g_cssManager->GetCSS(CSSManager::BrowserCSS);
#endif
while (browser_css)
{
BOOL skip_children = TRUE;
if (browser_css->IsEnabled() && browser_css->CheckMedia(m_doc, media_type))
{
browser_css->GetViewportProperties(m_doc, &m_viewport, media_type);
skip_children = FALSE;
}
browser_css = browser_css->GetNextImport(skip_children);
}
#ifdef SUPPORT_VISUAL_ADBLOCK
BOOL content_block_mode = m_doc->GetWindow()->GetContentBlockEditMode();
if (content_block_mode)
{
# ifdef PREFS_HOSTOVERRIDE
CSS* block_css = m_host_overrides[CSSManager::ContentBlockCSS].css;
if (!block_css)
block_css = g_cssManager->GetCSS(CSSManager::ContentBlockCSS);
# else
CSS* block_css = g_cssManager->GetCSS(CSSManager::ContentBlockCSS);
# endif
if (block_css)
block_css->GetViewportProperties(m_doc, &m_viewport, media_type);
}
#endif // SUPPORT_VISUAL_ADBLOCK
BOOL has_fullscreen_elm = FALSE;
#ifdef DOM_FULLSCREEN_MODE
has_fullscreen_elm = m_doc->GetFullscreenElement() != NULL;
#endif // DOM_FULLSCREEN_MODE
m_viewport.SetDefaultProperties(has_fullscreen_elm);
if (m_viewport.HasProperties() && m_doc->GetLayoutMode() != LAYOUT_NORMAL)
// Viewport META overrides ERA.
m_doc->CheckERA_LayoutMode();
if (m_doc->RecalculateLayoutViewSize(FALSE))
{
HTML_Element* root = m_doc->GetDocRoot();
if (root)
root->MarkDirty(m_doc);
}
}
#endif // CSS_VIEWPORT_SUPPORT
#ifdef STYLE_MATCH_INLINE_DEFAULT_API
CSS_MatchElement::CSS_MatchElement()
: m_html_element(NULL)
, m_pseudo(ELM_NOT_PSEUDO)
{
}
CSS_MatchElement::CSS_MatchElement(HTML_Element* html_element)
: m_html_element(html_element)
, m_pseudo(ELM_NOT_PSEUDO)
{
}
CSS_MatchElement::CSS_MatchElement(HTML_Element* html_element, PseudoElementType pseudo)
: m_html_element(html_element)
, m_pseudo(pseudo)
{
}
CSS_MatchElement
CSS_MatchElement::GetParent() const
{
if (IsPseudo())
return CSS_MatchElement(m_html_element);
else
return CSS_MatchElement(m_html_element->ParentActual());
}
BOOL
CSS_MatchElement::IsValid() const
{
if (!m_html_element)
return FALSE;
if (m_html_element->Type() == Markup::HTE_DOC_ROOT)
return FALSE;
switch (m_pseudo)
{
case ELM_NOT_PSEUDO:
return TRUE;
case ELM_PSEUDO_BEFORE:
return m_html_element->HasBefore();
case ELM_PSEUDO_AFTER:
return m_html_element->HasAfter();
case ELM_PSEUDO_FIRST_LETTER:
return m_html_element->HasFirstLetter();
case ELM_PSEUDO_FIRST_LINE:
return m_html_element->HasFirstLine();
case ELM_PSEUDO_SELECTION:
case ELM_PSEUDO_LIST_MARKER:
default:
return FALSE; // Unsupported.
}
}
BOOL
CSS_MatchElement::IsEqual(const CSS_MatchElement& elm) const
{
return m_html_element == elm.m_html_element && m_pseudo == elm.m_pseudo;
}
/* static */ CSS_decl*
CSS_MatchRuleListener::ResolveDeclaration(CSS_decl* decl)
{
if (decl->GetDeclType() == CSS_DECL_PROXY)
decl = static_cast<CSS_proxy_decl*>(decl)->GetRealDecl();
return decl;
}
#endif
#ifdef DOM_FULLSCREEN_MODE
BOOL CSSCollection::HasComplexFullscreenStyles() const
{
for (CSSCollectionElement* elm = m_element_list.First(); elm; elm = elm->Suc())
{
if (elm->IsStyleSheet())
{
CSS* css = static_cast<CSS*>(elm);
if (css->IsEnabled() && css->HasComplexFullscreenStyles())
return TRUE;
}
}
return FALSE;
}
void
CSSCollection::ChangeFullscreenElement(HTML_Element* old_elm, HTML_Element* new_elm)
{
HTML_Element* root = m_doc->GetDocRoot();
/* Nothing to do. Should not call this method if the fullscreen element didn't change. */
OP_ASSERT(old_elm != new_elm);
if (!root || old_elm == new_elm)
return;
if (HasComplexFullscreenStyles())
root->MarkPropsDirty(m_doc);
else
{
HTML_Element* cur = old_elm;
do
{
while (cur && cur->Type() != Markup::HTE_DOC_ROOT)
{
cur->MarkPropsDirty(m_doc);
cur = cur->Parent();
}
} while ((cur = new_elm, new_elm = NULL), cur);
}
# ifdef CSS_VIEWPORT_SUPPORT
m_viewport.MarkDirty();
root->MarkDirty(m_doc);
# endif // CSS_VIEWPORT_SUPPORT
}
#endif // DOM_FULLSCREEN_MODE
CSS_MediaQueryList*
CSSCollection::AddMediaQueryList(const uni_char* media_string, CSS_MediaQueryList::Listener* listener)
{
OP_ASSERT(media_string);
OP_ASSERT(listener);
CSS_MediaObject* media_object = OP_NEW(CSS_MediaObject, ());
if (!media_object || OpStatus::IsMemoryError(media_object->SetMediaText(media_string, uni_strlen(media_string), FALSE)))
{
OP_DELETE(media_object);
return NULL;
}
CSS_MediaQueryList* new_query_list = OP_NEW(CSS_MediaQueryList, (media_object, listener, m_doc));
if (new_query_list)
new_query_list->Into(&m_query_lists);
else
OP_DELETE(media_object);
return new_query_list;
}
|
//
// Problem in p-1.6.1-0.png
//
#include <iostream>
#include <cassert>
#include <cmath>
#include <algorithm>
static void do_sort(int n, int* a) {
std::qsort(a, n, sizeof(int), [](const void*a, const void* b) {
int arg1 = *static_cast<const int*>(a);
int arg2 = *static_cast<const int*>(b);
if(arg1 < arg2) return -1;
if(arg1 > arg2) return 1;
// return (arg1 > arg2) - (arg1 < arg2); // possible shortcut
// return arg1 - arg2; // erroneous shortcut (fails if INT_MIN is present)
return 0;
});
}
static int solve(int n, int* a) {
do_sort(n, a);
int len = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = j + 1; k < n; k++) {
if (a[i] + a[j] > a[k])
len = std::max(len, a[i] + a[j] + a[k]);
}
}
}
return len;
}
int main(int argc, char* argv[]) {
//get input from stdin
//int n = 0;
//std::cin >> n;
//if (n < 3 or n > 100) {
// std::cout << " n >= 3 and n <= 100\n";
// return (-1);
//}
//int* a = new int[n];
//for (int i = 0; i < n; i++)
// std::cin >> a[i];
//delete[] len;
int n = 5;
int a[5] = {2, 3, 4, 5, 10};
int len = solve(n, a);
assert(len == 12);
n = 4;
int b[4] = {4, 5, 10, 20};
len = solve(n, b);
assert(len == 0);
return 0;
}
|
#include "number.hpp"
Number::Number() {
}
Number::Number(int val) {
this->m_val = val;
}
/*Number::Number virtual operator+(const Number& obj) {
Number tmp;
tmp.m_val = this->m_val + obj.m_val;
tmp.m_str = "";
return tmp;
}
Number::Number virtual operator=(const Number& obj) {
this->m_val = obj.m_val;
this->m_str = tmp.m_str;
return tmp;
}*/
|
/**
Copyright (c) 2015 Eric Bruneton
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "atmosphere/model/hosek/hosek.h"
#include <algorithm>
#include "atmosphere/model/hosek/ArHosekSkyModel.h"
namespace {
constexpr SolidAngle kSunSolidAngle = 6.87e-5 * sr;
// Copied from ArHosekSkyModel.cc.
const double originalSolarRadianceTable[] = {
7500.0,
12500.0,
21127.5,
26760.5,
30663.7,
27825.0,
25503.8,
25134.2,
23212.1,
21526.7,
19870.8
};
// The Hosek sky radiance was computed uding 'originalSolarRadianceTable' as
// the solar radiance, but we want the result for SolarSpectrum(), used in all
// other models. Thus we correct the result for each wavelength by the ratio
// between the two spectra at this wavelength (including also the Sun solid
// angle to convert radiance to irradiance values).
double SolarSpectrumCorrectionFactor(Wavelength lambda) {
double x = (lambda.to(nm) - 320.0) / 40.0;
if (x < 0.0 || x > 10.0) {
return 1.0;
}
int i = floor(x);
double u = x - i;
SpectralIrradiance new_irradiance = SolarSpectrum()(lambda);
SpectralRadiance old_radiance = (originalSolarRadianceTable[i] * (1.0 - u) +
originalSolarRadianceTable[std::min(i + 1, 10)] * u) *
watt_per_square_meter_per_sr_per_nm;
return (new_irradiance / (old_radiance * kSunSolidAngle))();
}
} // anonymous namespace
Hosek::Hosek(double turbidity) : turbidity_(turbidity) {
for (unsigned int i = 0; i < DimensionlessSpectrum::SIZE; ++i) {
sky_model_state_[i] = NULL;
}
}
Hosek::~Hosek() {
for (unsigned int i = 0; i < DimensionlessSpectrum::SIZE; ++i) {
if (sky_model_state_[i] != NULL) {
arhosekskymodelstate_free(sky_model_state_[i]);
}
}
}
IrradianceSpectrum Hosek::GetSunIrradiance(Length altitude,
Angle sun_zenith) const {
MaybeInitSkyModelState(sun_zenith);
IrradianceSpectrum result;
for (unsigned int i = 0; i < result.size(); ++i) {
Wavelength lambda = result.GetSample(i);
if (lambda < 320.0 * nm || lambda > 720.0 * nm) {
// arhosekskymodel_solar_radiance does not work for wavelengths outside
// the 320-720nm range.
result[i] = 0.0 * watt_per_square_meter_per_nm;
continue;
}
double sun_and_sky_radiance = arhosekskymodel_solar_radiance(
sky_model_state_[i], sun_zenith.to(rad), 0.0, lambda.to(nm));
double sky_radiance = arhosekskymodel_radiance(
sky_model_state_[i], sun_zenith.to(rad), 0.0, lambda.to(nm));
double sun_radiance = (sun_and_sky_radiance - sky_radiance) *
SolarSpectrumCorrectionFactor(lambda);
result[i] =
sun_radiance * watt_per_square_meter_per_sr_per_nm * kSunSolidAngle;
}
return result;
}
RadianceSpectrum Hosek::GetSkyRadiance(Length altitude, Angle sun_zenith,
Angle view_zenith, Angle view_sun_azimuth) const {
MaybeInitSkyModelState(sun_zenith);
double gamma =
GetViewSunAngle(sun_zenith, view_zenith, view_sun_azimuth).to(rad);
RadianceSpectrum result;
for (unsigned int i = 0; i < result.size(); ++i) {
Wavelength lambda = result.GetSample(i);
result[i] = arhosekskymodel_radiance(sky_model_state_[i],
view_zenith.to(rad), gamma, lambda.to(nm)) *
SolarSpectrumCorrectionFactor(lambda) *
watt_per_square_meter_per_sr_per_nm;
}
return result;
}
void Hosek::MaybeInitSkyModelState(Angle sun_zenith) const {
if (sky_model_state_[0] != NULL && sun_zenith == current_sun_zenith_) {
return;
}
if (sky_model_state_[0] != NULL) {
for (unsigned int i = 0; i < DimensionlessSpectrum::SIZE; ++i) {
arhosekskymodelstate_free(sky_model_state_[i]);
}
}
for (unsigned int i = 0; i < DimensionlessSpectrum::SIZE; ++i) {
sky_model_state_[i] = arhosekskymodelstate_alloc_init(
(pi / 2.0 - sun_zenith).to(rad), turbidity_, GroundAlbedo()[i]());
}
current_sun_zenith_ = sun_zenith;
}
|
int func(int A, int B)
{
// Verify that we have at least c++14
auto mult_func = [](auto a, auto b) { return a * b; };
return mult_func(A, B);
}
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "Dragon.h"
#include "DRController.h"
#include "DRAnimInstance.h"
#include "DrawDebugHelpers.h"
#include "time.h"
#include "NavigationSystem.h"
#include "Blueprint/AIBlueprintHelperLibrary.h"
#include "FireBall.h"
// Sets default values
ADragon::ADragon()
{
// Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
Head = CreateDefaultSubobject<UCapsuleComponent>(TEXT("HEAD"));
Tail = CreateDefaultSubobject<UCapsuleComponent>(TEXT("TAIL"));
Effect = CreateDefaultSubobject<UParticleSystemComponent>(TEXT("EFFECT"));
static ConstructorHelpers::FObjectFinder<USkeletalMesh> SK_Dragon(TEXT("/Game/DesertDragon/Meshes/SK_DesertDragon.SK_DesertDragon"));
if (SK_Dragon.Succeeded())
{
GetMesh()->SetSkeletalMesh(SK_Dragon.Object);
}
static ConstructorHelpers::FObjectFinder<UParticleSystem> P_FIRE(TEXT("ParticleSystem'/Game/Action_FX/ParticleSystems/Fire_Bullet/Fire_Shot.Fire_Shot'"));
if (P_FIRE.Succeeded())
{
Effect->SetTemplate(P_FIRE.Object);
Effect->bAutoActivate = false;
}
Effect->SetupAttachment(RootComponent);
GetCapsuleComponent()->SetCapsuleHalfHeight(224.0f);
GetCapsuleComponent()->SetCapsuleRadius(148.0f);
GetMesh()->SetRelativeLocationAndRotation(FVector(0.0f, 0.0f, -230.0f), FRotator(0.0f, -90.0f, 0.0f));
AIControllerClass = ADRController::StaticClass();
AutoPossessAI = EAutoPossessAI::PlacedInWorldOrSpawned;
bUseControllerRotationYaw = false;
GetCharacterMovement()->bUseControllerDesiredRotation = false;
GetCharacterMovement()->bOrientRotationToMovement = true;
GetCharacterMovement()->RotationRate = FRotator(0.0f, 480.0f, 0.0f);
Head->SetupAttachment(RootComponent);
Head->SetCapsuleHalfHeight(119.0f);
Head->SetCapsuleRadius(78.0f);
Head->SetRelativeLocationAndRotation(FVector(340.0f, 0.0f, -20.0f), FRotator(0.0f, 90.0f, 0.0f));
Head->SetCollisionProfileName(TEXT("Pawn"));
Tail->SetupAttachment(RootComponent);
Tail->SetCapsuleHalfHeight(280.0f);
Tail->SetCapsuleRadius(31.0f);
Tail->SetRelativeLocationAndRotation(FVector(-520.0f, 0.0f, -130.0f), FRotator(0.0f, 90.0f, 0.0f));
Tail->SetCollisionProfileName(TEXT("Pawn"));
IsAttacking = false;
IsAlert = false;
}
// Called when the game starts or when spawned
void ADragon::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void ADragon::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
// Called to bind functionality to input
void ADragon::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
}
void ADragon::PostInitializeComponents()
{
Super::PostInitializeComponents();
DRAni = Cast<UDRAnimInstance>(GetMesh()->GetAnimInstance());
ABCHECK(nullptr != DRAni);
DRAni->OnMontageEnded.AddDynamic(this, &ADragon::OnAttackMontageEnded);
DRAni->OnAttackHitCheck.AddUObject(this, &ADragon::AttackCheck);
DRAni->OnDash.AddUObject(this, &ADragon::Dash);
DRAni->OnFireBall.AddUObject(this, &ADragon::FIreBall);
Pattern = AttackPatten::GrAttack3;
}
void ADragon::Attack()
{
if (IsAttacking) return;
//Patten = AttackPatten::GrAttack1;
switch (Pattern)
{
case AttackPatten::GrAttack1:
DRAni->PlayAttacckMontage(Pattern);
IsAttacking = true;
break;
case AttackPatten::GrAttack2:
DRAni->PlayAttacckMontage(Pattern);
IsAttacking = true;
break;
case AttackPatten::GrAttack3:
DRAni->PlayAttacckMontage(Pattern);
IsAttacking = true;
break;
}
}
void ADragon::AttackCheck()
{
float AttackRange = 150.0f;
float AttackRadius = 50.0f;
switch (Pattern)
{
case AttackPatten::GrAttack1:
break;
}
FHitResult HitResult;
FCollisionQueryParams Params(NAME_None, false, this);
bool bResult = GetWorld()->SweepSingleByChannel(
HitResult,
GetActorLocation() + GetActorForwardVector()*500.0f+ GetActorRightVector() * -75.0f +GetActorUpVector() * -60.0f, //FVector(-100.0f, 480.0f, -60.0f),
GetActorLocation() + GetActorForwardVector()*500.0f + GetActorRightVector() * 75.0f + GetActorUpVector() * -60.0f,
FQuat::Identity,
ECollisionChannel::ECC_Pawn,
FCollisionShape::MakeSphere(50.0f),
Params
);
#if ENABLE_DRAW_DEBUG
FVector TraceVec = GetActorForwardVector() * AttackRange;
FVector Center = GetActorLocation()+ GetActorForwardVector()*500.0f + GetActorUpVector() * -60.0f + TraceVec * 0.5f;
float HalfHeight = AttackRange * 0.5f + AttackRadius;
FQuat CapsuleRot = FRotationMatrix::MakeFromY(TraceVec).ToQuat();
FColor DrawColor = bResult ? FColor::Green : FColor::Red;
float DebugLifeTime = 5.0f;
DrawDebugCapsule(GetWorld(),
Center,
HalfHeight,
AttackRadius,
CapsuleRot,
DrawColor,
false,
DebugLifeTime);
#endif
if (bResult)
{
if (HitResult.Actor.IsValid())
{
ABLOG(Warning, TEXT("Hit Actor Name : %s"), *HitResult.Actor->GetName());
}
}
}
void ADragon::Alert()
{
if (IsAttacking) return;
DRAni->PlayAttacckMontage(4);
IsAlert = true;
}
bool ADragon::SelectPattern()
{
srand((unsigned int)time(0));
Pattern = (AttackPatten)(rand() % 3 + 1);
switch (Pattern)
{
case Noting:
break;
case GrAttack1:
return true;
case GrAttack2:
return true;
case GrAttack3:
return false;
break;
default:
break;
}
return false;
}
void ADragon::OnAttackMontageEnded(UAnimMontage * Montage, bool bInterrupted)
{
IsAttacking = false;
IsAlert = false;
OnAlertEnd.Broadcast();
OnAttackEnd.Broadcast();
}
void ADragon::Dash()
{
}
void ADragon::FIreBall()
{
Effect->Activate(true);
Effect->OnSystemFinished.AddDynamic(this, &ADragon::OnEffectFinished);
auto Fire = GetWorld()->SpawnActor<AFireBall>(GetActorLocation() + GetActorForwardVector() * 500.0f, GetActorRotation());
}
void ADragon::OnEffectFinished(UParticleSystemComponent * PSystem)
{
Effect->Activate(false);
}
|
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
#pragma once
#include "cmConfigure.h" // IWYU pragma: keep
#include <cstddef>
#include <memory>
#include <string>
#include "cm_uv.h"
#include "cmUVHandlePtr.h"
class cmServerBase;
/***
* Given a sequence of bytes with any kind of buffering, instances of this
* class arrange logical chunks according to whatever the use case is for
* the connection.
*/
class cmConnectionBufferStrategy
{
public:
virtual ~cmConnectionBufferStrategy();
/***
* Called whenever with an active raw buffer. If a logical chunk
* becomes available, that chunk is returned and that portion is
* removed from the rawBuffer
*
* @param rawBuffer in/out parameter. Receive buffer; the buffer strategy is
* free to manipulate this buffer anyway it needs to.
*
* @return Next chunk from the stream. Returns the empty string if a chunk
* isn't ready yet. Users of this interface should repeatedly call this
* function until an empty string is returned since its entirely possible
* multiple chunks come in a single raw buffer.
*/
virtual std::string BufferMessage(std::string& rawBuffer) = 0;
/***
* Called to properly buffer an outgoing message.
*
* @param rawBuffer Message to format in the correct way
*
* @return Formatted message
*/
virtual std::string BufferOutMessage(const std::string& rawBuffer) const
{
return rawBuffer;
};
/***
* Resets the internal state of the buffering
*/
virtual void clear();
// TODO: There should be a callback / flag set for errors
};
class cmConnection
{
public:
cmConnection() = default;
cmConnection(cmConnection const&) = delete;
cmConnection& operator=(cmConnection const&) = delete;
virtual void WriteData(const std::string& data) = 0;
virtual ~cmConnection();
virtual bool OnConnectionShuttingDown();
virtual bool IsOpen() const = 0;
virtual void SetServer(cmServerBase* s);
virtual void ProcessRequest(const std::string& request);
virtual bool OnServeStart(std::string* pString);
protected:
cmServerBase* Server = nullptr;
};
/***
* Abstraction of a connection; ties in event callbacks from libuv and notifies
* the server when appropriate
*/
class cmEventBasedConnection : public cmConnection
{
public:
/***
* @param bufferStrategy If no strategy is given, it will process the raw
* chunks as they come in. The connection
* owns the pointer given.
*/
cmEventBasedConnection(cmConnectionBufferStrategy* bufferStrategy = nullptr);
virtual void Connect(uv_stream_t* server);
virtual void ReadData(const std::string& data);
bool IsOpen() const override;
void WriteData(const std::string& data) override;
bool OnConnectionShuttingDown() override;
virtual void OnDisconnect(int errorCode);
static void on_close(uv_handle_t* handle);
template <typename T>
static void on_close_delete(uv_handle_t* handle)
{
delete reinterpret_cast<T*>(handle);
}
protected:
cm::uv_stream_ptr WriteStream;
std::string RawReadBuffer;
std::unique_ptr<cmConnectionBufferStrategy> BufferStrategy;
static void on_read(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf);
static void on_write(uv_write_t* req, int status);
static void on_new_connection(uv_stream_t* stream, int status);
static void on_alloc_buffer(uv_handle_t* handle, size_t suggested_size,
uv_buf_t* buf);
};
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll a[1000][1000];
main()
{
ll i, j, sum=0, x, y, z;
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
cin>>a[i][j];
sum = sum+a[i][j];
}
}
sum=sum/2;
a[0][0] = sum-(a[0][1]+a[0][2]);
a[1][1] = sum-(a[1][0]+a[1][2]);
a[2][2] = sum-(a[2][0]+a[2][1]);
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)printf("%lld ", a[i][j]);
printf("\n");
}
return 0;
}
|
#include "pch.h"
#include "BubbleSort.h"
#include "Swap.h"
#include <vector>
#include <chrono>
BubbleSort::BubbleSort() {}
BubbleSort::~BubbleSort() {}
int BubbleSort::bubbleSort(std::vector<int> &vec) {
std::chrono::time_point<std::chrono::system_clock> now =
std::chrono::system_clock::now();
auto duration = now.time_since_epoch();
int microStart = std::chrono::duration_cast<std::chrono::microseconds>(duration).count();
int n, i, j;
Swap sp;
bool swapped;
n = vec.size();
for (i = 0; i < n - 1; i++) { //the simplest sorting algorithm
swapped = false;
for (j = 0; j < n - i - 1; j++) {
if (vec[j] > vec[j + 1]) {
sp.swap(&vec[j], &vec[j + 1]);
swapped = true;
}
}
// No swaps in one pass = sorted
if (swapped == false)
break;
}
now = std::chrono::system_clock::now();
duration = now.time_since_epoch();
int microEnd = std::chrono::duration_cast<std::chrono::microseconds>(duration).count();
return (microEnd - microStart);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.