text
stringlengths
8
6.88M
#include "../include/Responses.h" void Responses::Start(TgBot::Bot tgbot, TgBot::Message::Ptr message){ saveAdminId(std::to_string(message->chat->id), tgbot, message); } void Responses::Temperature(TgBot::Bot tgbot, TgBot::Message::Ptr message){ tgbot.getApi().sendMessage(message->chat->id, getPiTemperature()); } void Responses::Ip(TgBot::Bot tgbot, TgBot::Message::Ptr message){ tgbot.getApi().sendMessage(message->chat->id, getPiIp()); } void Responses::Restart(TgBot::Bot tgbot, TgBot::Message::Ptr message, std::string adminId){ if(checkAdmin(adminId, std::to_string(message->chat->id))){ tgbot.getApi().sendMessage(message->chat->id, "The server will restart"); std::string command = "sudo touch systemReboot.txt"; system(command.c_str()); } else{ tgbot.getApi().sendMessage(message->chat->id, "Only the administrator can execute this command"); } } void Responses::Shutdown(TgBot::Bot tgbot, TgBot::Message::Ptr message, std::string adminId){ if(checkAdmin(adminId, std::to_string(message->chat->id))){ tgbot.getApi().sendMessage(message->chat->id, "The server will shutdown"); std::string command = "sudo touch systemShutdown.txt"; system(command.c_str()); } else{ tgbot.getApi().sendMessage(message->chat->id, "Only the administrator can execute this command"); } } void Responses::Speedtest(TgBot::Bot tgbot, TgBot::Message::Ptr message){ tgbot.getApi().sendMessage(message->chat->id, "Testing network speed..."); tgbot.getApi().sendMessage(message->chat->id, piSpeedTest()); } void Responses::Upgrade(TgBot::Bot tgbot, TgBot::Message::Ptr message){ tgbot.getApi().sendMessage(message->chat->id, "System upgrade..."); std::string systemUpgrade = piUpgrade(); tgbot.getApi().sendMessage(message->chat->id, systemUpgrade); } void Responses::Logs(TgBot::Bot tgbot, TgBot::Message::Ptr message){ Transfer transfer; tgbot.getApi().sendMessage(message->chat->id, "Converting logs file..."); transfer.convert("logs.txt"); tgbot.getApi().sendMessage(message->chat->id, "File converted"); tgbot.getApi().sendMessage(message->chat->id, "Uploading logs file..."); std::string fileUrl = transfer.upload(); tgbot.getApi().sendMessage(message->chat->id, "File uploaded"); const boost::variant< TgBot::InputFile::Ptr, std::string > filename = fileUrl; tgbot.getApi().sendDocument(message->chat->id, filename); } void Responses::Sms(TgBot::Bot tgbot, TgBot::Message::Ptr message){ Text text; std::cout << "Starting smsBomber...\n"; std::string str = (message->text.c_str()); text.split(str, " ", "data/split.txt"); std::vector<std::string> parameters; parameters = txtToVector("data/split.txt"); remove("data/split.txt"); std::vector<std::string> prohibitedNumbers; prohibitedNumbers = txtToVector("data/prohibitedNumbers.txt"); if(parameters.size() == 1){ tgbot.getApi().sendMessage(message->chat->id, "This function can perform an SMS bombing"); tgbot.getApi().sendMessage(message->chat->id, "You can use it by typing /sms + phone number + bombing time + threads"); tgbot.getApi().sendMessage(message->chat->id, "Example: /sms 15554443333 15 10"); } // If parameters are more or less than necessary than don't execute the script but output a warning else if(parameters.size()>4||parameters.size()<4){ tgbot.getApi().sendMessage(message->chat->id, "Wrong number of parameters"); tgbot.getApi().sendMessage(message->chat->id, "You have to use the following ones: phone number, time, threads"); } else if(text.checkSame(prohibitedNumbers, parameters[1])==true){ tgbot.getApi().sendMessage(message->chat->id, "Prohibited number"); } else{ std::string command = ("quack --tool SMS --target " + parameters[1] + " --time " + parameters[2] + " --threads " + parameters[3] + " >> data/smsBomb.txt"); tgbot.getApi().sendMessage(message->chat->id, "Started SMS bombing..."); system(command.c_str()); std::vector<std::string> smsOutput; smsOutput = txtToVector("data/smsBomb.txt"); // Finds how many messages were sent int smsSent = 0; for(int i=0; i<smsOutput.size(); i++){ std::string str = smsOutput[i]; str = str[8]; if(str=="+"){ smsSent++; } } remove("data/smsBomb.txt"); tgbot.getApi().sendMessage(message->chat->id, std::to_string(smsSent) + " messages sent"); tgbot.getApi().sendMessage(message->chat->id, "Bombing completed"); } }
#include <iostream> #include <cstring> #include <string> using namespace std; // const int maxn = 1000 + 10; // char ch[maxn]; int convert(string str, int len){ int sum = 0; for (int i = 0; i < len; ++i) sum = 10*sum + (str[i] - '0');// key!!! return sum; } int main(){ int a; string symb; string t; string str; getline(cin, t); getline(cin, str); a = convert( t.substr(0, t.size() - 2), t.size() - 2); symb = t[t.size()-1]; int len = str.size(); if ( a >= len){ for (int i = 0; i < a-len; ++i) cout << symb; cout << str; } else cout << str.substr(len - a, a); return 0; }
#pragma once #include "Object.h" #include <time.h> class Ghost : public Object { protected: Vec2 initialPosition; int lastAnimation; int lastAnimationPowerUP; bool dead; float deltaTime; clock_t lastTime; float timeDown; float deltaTimeRespawn; clock_t lastTimeRespawn; float timeDownRespawn; public: int direction; // 0 -> left, 1 -> right, 2 -> up, 3 -> down int points; int lastDirection; Vec2 actualPosition; Ghost(); virtual void Update(); virtual void Respawn(); virtual void SetInitialPosition(int _x, int _y); virtual void Draw(); ~Ghost(); };
// Copyright (c) 2020 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ProcessesDataView.h" #include <utility> #include "App.h" #include "Callstack.h" #include "ModulesDataView.h" #include "Params.h" #include "absl/strings/str_format.h" using orbit_grpc_protos::ProcessInfo; ProcessesDataView::ProcessesDataView() : DataView(DataViewType::kProcesses), selected_process_id_(-1) {} const std::vector<DataView::Column>& ProcessesDataView::GetColumns() { static const std::vector<Column> columns = [] { std::vector<Column> columns; columns.resize(kNumColumns); columns[kColumnPid] = {"PID", .2f, SortingOrder::kAscending}; columns[kColumnName] = {"Name", .6f, SortingOrder::kAscending}; columns[kColumnCpu] = {"CPU", .0f, SortingOrder::kDescending}; return columns; }(); return columns; } std::string ProcessesDataView::GetValue(int row, int col) { const ProcessInfo& process = GetProcess(row); switch (col) { case kColumnPid: return std::to_string(process.pid()); case kColumnName: return process.name(); case kColumnCpu: return absl::StrFormat("%.1f", process.cpu_usage()); default: return ""; } } std::string ProcessesDataView::GetToolTip(int row, int /*column*/) { return GetProcess(row).command_line(); } #define ORBIT_PROC_SORT(Member) \ [&](int a, int b) { \ return OrbitUtils::Compare(processes[a].Member, processes[b].Member, ascending); \ } void ProcessesDataView::DoSort() { bool ascending = sorting_orders_[sorting_column_] == SortingOrder::kAscending; std::function<bool(int a, int b)> sorter = nullptr; const std::vector<ProcessInfo>& processes = process_list_; switch (sorting_column_) { case kColumnPid: sorter = ORBIT_PROC_SORT(pid()); break; case kColumnName: sorter = ORBIT_PROC_SORT(name()); break; case kColumnCpu: sorter = ORBIT_PROC_SORT(cpu_usage()); break; default: break; } if (sorter) { std::stable_sort(indices_.begin(), indices_.end(), sorter); } SetSelectedItem(); } #undef ORBIT_PROC_SORT void ProcessesDataView::OnSelect(int index) { const ProcessInfo& selected_process = GetProcess(index); selected_process_id_ = selected_process.pid(); SetSelectedItem(); if (selection_listener_) { selection_listener_(selected_process_id_); } } int32_t ProcessesDataView::GetSelectedProcessId() const { return selected_process_id_; } int32_t ProcessesDataView::GetFirstProcessId() const { if (indices_.empty()) { return -1; } return process_list_[indices_[0]].pid(); } void ProcessesDataView::SetSelectedItem() { for (size_t i = 0; i < GetNumElements(); ++i) { if (GetProcess(i).pid() == selected_process_id_) { selected_index_ = i; return; } } // This happens when selected process disappears from the list. selected_index_ = -1; } bool ProcessesDataView::SelectProcess(const std::string& process_name) { for (size_t i = 0; i < GetNumElements(); ++i) { const ProcessInfo& process = GetProcess(i); // TODO: What if there are multiple processes with the same substring? if (process.full_path().find(process_name) != std::string::npos) { OnSelect(i); return true; } } return false; } bool ProcessesDataView::SelectProcess(int32_t process_id) { for (size_t i = 0; i < GetNumElements(); ++i) { const ProcessInfo& process = GetProcess(i); if (process.pid() == process_id) { OnSelect(i); return true; } } return false; } void ProcessesDataView::DoFilter() { std::vector<uint32_t> indices; const std::vector<ProcessInfo>& processes = process_list_; std::vector<std::string> tokens = absl::StrSplit(ToLower(filter_), ' '); for (size_t i = 0; i < processes.size(); ++i) { const ProcessInfo& process = processes[i]; std::string name = ToLower(process.name()); std::string type = process.is_64_bit() ? "64" : "32"; bool match = true; for (std::string& filter_token : tokens) { if (!(name.find(filter_token) != std::string::npos || type.find(filter_token) != std::string::npos)) { match = false; break; } } if (match) { indices.push_back(i); } } indices_ = indices; } void ProcessesDataView::UpdateProcessList() { size_t num_processes = process_list_.size(); indices_.resize(num_processes); for (size_t i = 0; i < num_processes; ++i) { indices_[i] = i; } } void ProcessesDataView::SetProcessList(const std::vector<ProcessInfo>& process_list) { process_list_ = process_list; UpdateProcessList(); OnDataChanged(); SetSelectedItem(); } const ProcessInfo& ProcessesDataView::GetProcess(uint32_t row) const { return process_list_[indices_[row]]; } void ProcessesDataView::SetSelectionListener( const std::function<void(int32_t)>& selection_listener) { selection_listener_ = selection_listener; }
// // Created by Nikita Kruk on 03.12.17. // #include "AbcSmcEngineSynthetic.hpp" #include "SimulationEngineForSyntheticData.hpp" #include <iostream> #include <sstream> #include <algorithm> // std::for_each #include <boost/math/distributions/uniform.hpp> #include <boost/math/distributions/normal.hpp> AbcSmcEngineSynthetic::AbcSmcEngineSynthetic() : synthetic_parameter_set_(), pbc_config_(synthetic_parameter_set_.Get_L(), synthetic_parameter_set_.Get_L()), synthetic_data_(std::vector<Real>(kS * synthetic_parameter_set_.Get_N(), 0.0)), candidate_data_(std::vector<Real>(kS * synthetic_parameter_set_.Get_N(), 0.0)) { std::cout << "Approximate Bayesian Computation - Sequential Monte Carlo Started" << std::endl; } AbcSmcEngineSynthetic::~AbcSmcEngineSynthetic() { std::cout << "Approximate Bayesian Computation - Sequential Monte Carlo Complete" << std::endl; } void AbcSmcEngineSynthetic::PrepareSyntheticData() { SimulationEngineForSyntheticData simulation_engine(synthetic_parameter_set_, pbc_config_); simulation_engine.GenerateSyntheticDataWithArbitraryStationaryVelocity(); } void AbcSmcEngineSynthetic::RunAbcTowardsSyntheticData() { std::ostringstream synthetic_data_file_name_buffer; synthetic_data_file_name_buffer << synthetic_parameter_set_.GetSyntheticDataFolderName() << "/spr_simulation_N_" << synthetic_parameter_set_.Get_N() << "_phi_" << synthetic_parameter_set_.Get_phi() << "_a_" << synthetic_parameter_set_.Get_a() << "_U0_" << synthetic_parameter_set_.Get_U_0() << "_k_" << synthetic_parameter_set_.Get_kappa() << ".bin"; synthetic_parameter_set_.Set_t_0(0.0); synthetic_parameter_set_.Set_t_1(1.0); // Initialize tolerances int number_of_populations = 4; std::vector<Real> tolerances(number_of_populations); tolerances[0] = 12.5 * 1e-6; tolerances[1] = 12 * 1e-6; tolerances[2] = 11.5 * 1e-6; tolerances[3] = 11.4 * 1e-6; int population_size = 25; std::uniform_real_distribution<Real> unif_rnd(0.0, 1e-19); boost::math::uniform_distribution<Real> unif_pdf(0.0, 1e-19); std::vector<Real> sampled_parameters(population_size); std::vector<Real> weights(population_size, 1.0 / population_size); int population_idx = 0; while (population_idx < number_of_populations) { std::vector<Real> new_sampled_parameters(sampled_parameters); std::vector<Real> new_weights(weights); int particle_idx = 0; while (particle_idx < population_size) { // S2.1 Sample new parameters/particles Real new_parameter = 0; SampleParameterFromPreviousPopulation(population_idx, unif_rnd, weights, sampled_parameters, new_parameter); // if \pi(\theta^{**})=0, return to S2.1 if (boost::math::pdf(unif_pdf, new_parameter) == 0.0) { continue; } // simulate candidate dataset int number_of_simulations = 1; int number_of_successful_simulations = 0; for (int simulation_idx = 0; simulation_idx < number_of_simulations; ++simulation_idx) { synthetic_parameter_set_.Set_U_0(new_parameter); SimulationEngineForSyntheticData simulation_engine(synthetic_parameter_set_, pbc_config_); std::string candidate_dataset_file_name; simulation_engine.SimulateCandidateDataset(population_idx, synthetic_data_file_name_buffer.str(), candidate_dataset_file_name); Real distance = 0.0; ComputeDistanceBetweenSyntheticAndCandidateDatasets(synthetic_data_file_name_buffer.str(), candidate_dataset_file_name, distance); if (distance <= tolerances[population_idx]) { ++number_of_successful_simulations; } } // simulation_idx if (number_of_successful_simulations == 0) { continue; } std::cout << "population:" << population_idx << ", particle:" << particle_idx << std::endl; // set the new particle new_sampled_parameters[particle_idx] = new_parameter; // calculate the weight for that particle Real weight = 0.0; if (population_idx == 0) { weight = number_of_successful_simulations; } else { for (int j = 0; j < population_size; ++j) { boost::math::normal_distribution<Real> perturbation_kernel(sampled_parameters[j], synthetic_parameter_set_.Get_U_0() / 3.0); weight += weights[j] * boost::math::pdf(perturbation_kernel, new_parameter); } weight = boost::math::pdf(unif_pdf, new_parameter) * number_of_successful_simulations / weight; } new_weights[particle_idx] = weight; ++particle_idx; } // particle_idx sampled_parameters = new_sampled_parameters; weights = new_weights; NormalizeWeights(weights); SaveAcceptedParameters(population_idx, sampled_parameters, weights); ++population_idx; } // population_idx } void AbcSmcEngineSynthetic::ComputeDistanceBetweenSyntheticAndCandidateDatasets(const std::string &synthetic_data_file_name, const std::string &candidate_dataset_file_name, Real &distance) { std::ifstream synthetic_data_file(synthetic_data_file_name, std::ios::binary | std::ios::in); assert(synthetic_data_file.is_open()); synthetic_data_file.seekg(synthetic_parameter_set_.Get_t_0() * (1 + kS * synthetic_parameter_set_.Get_N()) * sizeof(Real), std::ios::beg); std::ifstream candidate_dataset_file(candidate_dataset_file_name, std::ios::binary | std::ios::in); assert(candidate_dataset_file.is_open()); Real t = synthetic_parameter_set_.Get_t_0(); Real root_mean_square_error = 0.0; Vector2D r_alpha, r_beta, dr_alpha_beta; std::mt19937 mersenne_twister_generator(std::random_device{}()); std::normal_distribution<Real> norm_dist(0.0, synthetic_parameter_set_.Get_lambda() / 3.0); int time_count = 0; while (t <= synthetic_parameter_set_.Get_t_1()) { Real tmp = 0.0; synthetic_data_file.read((char *) &tmp, sizeof(Real)); candidate_dataset_file.read((char *) &tmp, sizeof(Real)); synthetic_data_file.read((char *) &synthetic_data_[0], kS * synthetic_parameter_set_.Get_N() * sizeof(Real)); // exert observational noise std::for_each(synthetic_data_.begin(), synthetic_data_.end(), [&](Real &n) { n += norm_dist(mersenne_twister_generator); }); candidate_dataset_file.read((char *) &candidate_data_[0], kS * synthetic_parameter_set_.Get_N() * sizeof(Real)); Real mean_square_error_per_time_unit = 0.0; for (int alpha = 0; alpha < synthetic_parameter_set_.Get_N(); ++alpha) { r_alpha.x = synthetic_data_[kS * alpha]; r_alpha.y = synthetic_data_[kS * alpha + 1]; r_beta.x = candidate_data_[kS * alpha]; r_beta.y = candidate_data_[kS * alpha + 1]; pbc_config_.ClassAEffectiveParticleDistance(r_alpha, r_beta, dr_alpha_beta); mean_square_error_per_time_unit += NormSquared(dr_alpha_beta); // mean_square_error_per_time_unit += (synthetic_parameter_set_.Get_L() / 2.0 * M_SQRT2) * (synthetic_parameter_set_.Get_L() / 2.0 * M_SQRT2); // mean_square_error_per_time_unit += std::pow(synthetic_parameter_set_.Get_L() / 2.0 * M_SQRT2, -1.0); } // alpha root_mean_square_error += mean_square_error_per_time_unit / synthetic_parameter_set_.Get_N(); t += synthetic_parameter_set_.Get_delta_t() * synthetic_parameter_set_.Get_output_interval(); ++time_count; } // t distance = std::sqrt(root_mean_square_error / time_count); // distance = std::pow(root_mean_square_error / time_count, -1.0); std::cout << "RMSE:" << distance << std::endl; } void AbcSmcEngineSynthetic::SaveAcceptedParameters(int population, const std::vector<Real> &sampled_parameters, const std::vector<Real> &weights) { std::ostringstream accepted_parameters_file_name_buffer; accepted_parameters_file_name_buffer << synthetic_parameter_set_.GetAbcFolderName() << synthetic_parameter_set_.GetPosteriorDistributionsSubfolderName() << "accepted_parameters_" << population << ".txt"; std::remove(accepted_parameters_file_name_buffer.str().c_str()); std::ofstream accepted_parameters_file(accepted_parameters_file_name_buffer.str(), std::ios::out | std::ios::app); for (int particle_idx = 0; particle_idx < sampled_parameters.size(); ++particle_idx) { accepted_parameters_file << sampled_parameters[particle_idx] << '\t' << weights[particle_idx] << std::endl; } accepted_parameters_file.close(); } void AbcSmcEngineSynthetic::SampleParameterFromPreviousPopulation(int population_indicator, std::uniform_real_distribution<Real> &unif_rnd, const std::vector<Real> &weights, const std::vector<Real> &sampled_parameters, Real &new_parameter) { std::mt19937 mersenne_twister_generator(std::random_device{}()); if (population_indicator == 0) { new_parameter = unif_rnd(mersenne_twister_generator); } else { std::discrete_distribution<int> previous_population_distribution(weights.begin(), weights.end()); int new_parameter_index = previous_population_distribution(mersenne_twister_generator); new_parameter = sampled_parameters[new_parameter_index]; std::normal_distribution<Real> perturbation_kernel(new_parameter, synthetic_parameter_set_.Get_U_0() / 3.0); new_parameter = perturbation_kernel(mersenne_twister_generator); } } void AbcSmcEngineSynthetic::NormalizeWeights(std::vector<Real> &weights) { Real sum = std::accumulate(weights.begin(), weights.end(), 0.0); for (Real &w : weights) { w /= sum; } }
// 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 <future> #include <map> #include <mutex> #include "crypto/hash.h" #include "IWalletLegacy.h" namespace cn { namespace WalletHelper { class SaveWalletResultObserver : public cn::IWalletLegacyObserver { public: std::promise<std::error_code> saveResult; virtual void saveCompleted(std::error_code result) override { saveResult.set_value(result); } }; class InitWalletResultObserver : public cn::IWalletLegacyObserver { public: std::promise<std::error_code> initResult; virtual void initCompleted(std::error_code result) override { initResult.set_value(result); } }; class SendCompleteResultObserver : public cn::IWalletLegacyObserver { public: virtual void sendTransactionCompleted(cn::TransactionId transactionId, std::error_code result) override; std::error_code wait(cn::TransactionId transactionId); private: std::mutex m_mutex; std::condition_variable m_condition; std::map<cn::TransactionId, std::error_code> m_finishedTransactions; std::error_code m_result; }; class IWalletRemoveObserverGuard { public: IWalletRemoveObserverGuard(cn::IWalletLegacy& wallet, cn::IWalletLegacyObserver& observer); ~IWalletRemoveObserverGuard(); void removeObserver(); private: cn::IWalletLegacy& m_wallet; cn::IWalletLegacyObserver& m_observer; bool m_removed; }; void prepareFileNames(const std::string& file_path, std::string& keys_file, std::string& wallet_file); void storeWallet(cn::IWalletLegacy& wallet, const std::string& walletFilename); } }
// Created on: 1994-03-14 // Created by: s: Christophe GUYOT & Frederic UNTEREINER // Copyright (c) 1994-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 _IGESToBRep_CurveAndSurface_HeaderFile #define _IGESToBRep_CurveAndSurface_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Standard_Integer.hxx> #include <Message_ProgressRange.hxx> class Geom_Surface; class IGESData_IGESModel; class Transfer_TransientProcess; class TopoDS_Shape; class IGESData_IGESEntity; class Message_Msg; //! Provides methods to transfer CurveAndSurface from IGES to CASCADE. class IGESToBRep_CurveAndSurface { public: DEFINE_STANDARD_ALLOC //! Creates a tool CurveAndSurface ready to run, with //! epsilons set to 1.E-04, myModeTopo to True, the //! optimization of the continuity to False. Standard_EXPORT IGESToBRep_CurveAndSurface(); //! Creates a tool CurveAndSurface ready to run. Standard_EXPORT IGESToBRep_CurveAndSurface(const Standard_Real eps, const Standard_Real epsGeom, const Standard_Real epsCoeff, const Standard_Boolean mode, const Standard_Boolean modeapprox, const Standard_Boolean optimized); //! Initializes the field of the tool CurveAndSurface with //! default creating values. Standard_EXPORT void Init(); //! Changes the value of "myEps" void SetEpsilon (const Standard_Real eps); //! Returns the value of "myEps" Standard_Real GetEpsilon() const; //! Changes the value of "myEpsCoeff" void SetEpsCoeff (const Standard_Real eps); //! Returns the value of "myEpsCoeff" Standard_Real GetEpsCoeff() const; //! Changes the value of "myEpsGeom" Standard_EXPORT void SetEpsGeom (const Standard_Real eps); //! Returns the value of "myEpsGeom" Standard_Real GetEpsGeom() const; //! Changes the value of "myMinTol" void SetMinTol (const Standard_Real mintol); //! Changes the value of "myMaxTol" void SetMaxTol (const Standard_Real maxtol); //! Sets values of "myMinTol" and "myMaxTol" as follows //! myMaxTol = Max ("read.maxprecision.val", myEpsGeom * myUnitFactor) //! myMinTol = Precision::Confusion() //! Remark: This method is automatically invoked each time the values //! of "myEpsGeom" or "myUnitFactor" are changed Standard_EXPORT void UpdateMinMaxTol(); //! Returns the value of "myMinTol" Standard_Real GetMinTol() const; //! Returns the value of "myMaxTol" Standard_Real GetMaxTol() const; //! Changes the value of "myModeApprox" void SetModeApprox (const Standard_Boolean mode); //! Returns the value of "myModeApprox" Standard_Boolean GetModeApprox() const; //! Changes the value of "myModeIsTopo" void SetModeTransfer (const Standard_Boolean mode); //! Returns the value of "myModeIsTopo" Standard_Boolean GetModeTransfer() const; //! Changes the value of "myContIsOpti" void SetOptimized (const Standard_Boolean optimized); //! Returns the value of "myContIsOpti" Standard_Boolean GetOptimized() const; //! Returns the value of " myUnitFactor" Standard_Real GetUnitFactor() const; //! Changes the value of "mySurfaceCurve" void SetSurfaceCurve (const Standard_Integer ival); //! Returns the value of " mySurfaceCurve" 0 = value in //! file , 2 = kepp 2d and compute 3d 3 = keep 3d and //! compute 2d Standard_Integer GetSurfaceCurve() const; //! Set the value of "myModel" Standard_EXPORT void SetModel (const Handle(IGESData_IGESModel)& model); //! Returns the value of "myModel" Handle(IGESData_IGESModel) GetModel() const; //! Changes the value of "myContinuity" //! if continuity = 0 do nothing else //! if continuity = 1 try C1 //! if continuity = 2 try C2 void SetContinuity (const Standard_Integer continuity); //! Returns the value of "myContinuity" Standard_Integer GetContinuity() const; //! Set the value of "myMsgReg" void SetTransferProcess (const Handle(Transfer_TransientProcess)& TP); //! Returns the value of "myMsgReg" Handle(Transfer_TransientProcess) GetTransferProcess() const; //! Returns the result of the transfert of any IGES Curve //! or Surface Entity. If the transfer has failed, this //! member return a NullEntity. Standard_EXPORT TopoDS_Shape TransferCurveAndSurface (const Handle(IGESData_IGESEntity)& start, const Message_ProgressRange& theProgress = Message_ProgressRange()); //! Returns the result of the transfert the geometry of //! any IGESEntity. If the transfer has failed, this //! member return a NullEntity. Standard_EXPORT TopoDS_Shape TransferGeometry (const Handle(IGESData_IGESEntity)& start, const Message_ProgressRange& theProgress = Message_ProgressRange()); //! Records a new Fail message void SendFail (const Handle(IGESData_IGESEntity)& start, const Message_Msg& amsg); //! Records a new Warning message void SendWarning (const Handle(IGESData_IGESEntity)& start, const Message_Msg& amsg); //! Records a new Information message from the definition //! of a Msg (Original+Value) void SendMsg (const Handle(IGESData_IGESEntity)& start, const Message_Msg& amsg); //! Returns True if start was already treated and has a result in "myMap" //! else returns False. Standard_EXPORT Standard_Boolean HasShapeResult (const Handle(IGESData_IGESEntity)& start) const; //! Returns the result of the transfer of the IGESEntity "start" contained //! in "myMap" . (if HasShapeResult is True). Standard_EXPORT TopoDS_Shape GetShapeResult (const Handle(IGESData_IGESEntity)& start) const; //! set in "myMap" the result of the transfer of the IGESEntity "start". Standard_EXPORT void SetShapeResult (const Handle(IGESData_IGESEntity)& start, const TopoDS_Shape& result); //! Returns the number of shapes results contained in "myMap" for the //! IGESEntity start ( type VertexList or EdgeList). Standard_EXPORT Standard_Integer NbShapeResult (const Handle(IGESData_IGESEntity)& start) const; //! Returns the numth result of the IGESEntity start (type VertexList or //! EdgeList) in "myMap". (if NbShapeResult is not null). Standard_EXPORT TopoDS_Shape GetShapeResult (const Handle(IGESData_IGESEntity)& start, const Standard_Integer num) const; //! set in "myMap" the result of the transfer of the entity of the //! IGESEntity start ( type VertexList or EdgeList). Standard_EXPORT void AddShapeResult (const Handle(IGESData_IGESEntity)& start, const TopoDS_Shape& result); Standard_EXPORT void SetSurface (const Handle(Geom_Surface)& theSurface); Standard_EXPORT Handle(Geom_Surface) Surface() const; Standard_EXPORT Standard_Real GetUVResolution(); protected: private: Standard_Real myEps; Standard_Real myEpsCoeff; Standard_Real myEpsGeom; Standard_Real myMinTol; Standard_Real myMaxTol; Standard_Boolean myModeIsTopo; Standard_Boolean myModeApprox; Standard_Boolean myContIsOpti; Standard_Real myUnitFactor; Standard_Integer mySurfaceCurve; Standard_Integer myContinuity; Handle(Geom_Surface) mySurface; Standard_Real myUVResolution; Standard_Boolean myIsResolCom; Handle(IGESData_IGESModel) myModel; Handle(Transfer_TransientProcess) myTP; }; #include <IGESToBRep_CurveAndSurface.lxx> #endif // _IGESToBRep_CurveAndSurface_HeaderFile
#include<cstdio> #include<iostream> #include<algorithm> using namespace std; const int maxn = 1e6 + 7; int flag[maxn],cnt = 0; int find(int l,int r,int tar){ int i; for(i = l;i < r;i++){ if(flag[i]>=tar) break; } if(i==r||(i==l&&flag[l]>tar)){ return tar; } if(flag[i]==tar){ if(i+1<r) find(i+1,r,tar+1); else return tar+1; } else{ return tar; } } bool cmp(int x,int y){ return x>y; } int main() { int n,q; scanf("%d%d",&n,&q); for(int i = 1;i <= q;i++){ int op,num; scanf("%d%d",&op,&num); if(op==1){ flag[cnt++] = num; sort(flag,flag+cnt,cmp); } else{ int ans = find(0,cnt,num); printf("%d\n",ans); } } return 0; }
#include "pch.h" #include <iostream> #include <thread> #include <fstream> #include <vector> #include <string> #include <future> #include "Quicksort.h" #include "BubbleSort.h" #include "Heapsort.h" #include "InsertionSort.h" #include "MergeSort.h" #include "Swap.h" //sortTest() will add all the scores into here, main will average it and reset it float qsAverageScore; float bsAverageScore; float hsAverageScore; float isAverageScore; float msAverageScore; //a score that tells you how well your computer did float finalScore; std::vector<int> getList(int n, int to, int testNum) { //puts values from a text file into a vector std::ifstream in; in.open("Lists\\" + std::to_string(n) + '_' + std::to_string(to) + '_' + std::to_string(testNum) + ".txt"); std::vector<int> v; int element; if (in.is_open()) { int i = 0; while (in >> element) { v.push_back(element); } } in.close(); return v; } void sortTest(int n, int to, int testNum) { //runs test on all 5 algorithms on their own threads std::vector<int> sortThis = getList(n, to, testNum); Quicksort qs; BubbleSort bs; Heapsort hs; InsertionSort is; MergeSort ms; //copies of the unsorted vector for each to work on std::vector<int> qs_vec = sortThis; std::vector<int> bs_vec = sortThis; std::vector<int> hs_vec = sortThis; std::vector<int> is_vec = sortThis; std::vector<int> ms_vec = sortThis; std::future<int> qsFtr = std::async(std::launch::async, &Quicksort::quickSort, qs, std::ref(qs_vec), 0, n - 1); std::future<int> bsFtr = std::async(std::launch::async, &BubbleSort::bubbleSort, bs, std::ref(bs_vec)); std::future<int> hsFtr = std::async(std::launch::async, &Heapsort::heapSort, hs, std::ref(hs_vec)); std::future<int> isFtr = std::async(std::launch::async, &InsertionSort::insertionSort, is, std::ref(is_vec)); std::future<int> msFtr = std::async(std::launch::async, &MergeSort::mergeSort, ms, std::ref(ms_vec)); //when all threads are complete, get the time taken from each if (qsFtr.valid() || bsFtr.valid() || hsFtr.valid() || isFtr.valid() || msFtr.valid()) { qsAverageScore += qsFtr.get(); bsAverageScore += bsFtr.get(); hsAverageScore += hsFtr.get(); isAverageScore += isFtr.get(); msAverageScore += msFtr.get(); } } //Large inputs take too long with Bubble and Insetion Sort void sortTestFast(int n, int to, int testNum) { std::vector<int> sortThis = getList(n, to, testNum); Quicksort qs; Heapsort hs; MergeSort ms; //copies of the unsorted vector for each to work on std::vector<int> qs_vec = sortThis; std::vector<int> hs_vec = sortThis; std::vector<int> ms_vec = sortThis; std::future<int> qsFtr = std::async(std::launch::async, &Quicksort::quickSort, qs, std::ref(qs_vec), 0, n - 1); std::future<int> hsFtr = std::async(std::launch::async, &Heapsort::heapSort, hs, std::ref(hs_vec)); std::future<int> msFtr = std::async(std::launch::async, &MergeSort::mergeSort, ms, std::ref(ms_vec)); //when all threads are complete, get the time taken from each if (qsFtr.valid() || hsFtr.valid() || msFtr.valid()) { qsAverageScore += qsFtr.get(); hsAverageScore += hsFtr.get(); msAverageScore += msFtr.get(); } } //for running multiple tests and outputing the results void runTest(int n, int to) { std::cout << std::to_string(n) + " Numbers, 1 to " + std::to_string(to) + "..." << '\n' << '\n'; for (int i = 1; i <= 3; ++i) { sortTest(n, to, i); } //runs the test with 3 different data sets std::cout << "Quicksort: " + std::to_string(qsAverageScore / 3) + "us" << '\n'; std::cout << "Bubble Sort: " + std::to_string(bsAverageScore / 3) + "us" << '\n'; std::cout << "Heapsort: " + std::to_string(hsAverageScore / 3) + "us" << '\n'; std::cout << "Insertion Sort: " + std::to_string(isAverageScore / 3) + "us" << '\n'; std::cout << "Merge Sort: " + std::to_string(msAverageScore / 3) + "us" << '\n' << '\n'; std::cout << "====================================================" << '\n' << '\n'; if (n == 2000 && to == 50) { finalScore += (qsAverageScore / (559 * 3)); //values obtained by averaging 5 runs on my PC finalScore += (bsAverageScore / (3711 * 3)); finalScore += (hsAverageScore / (530 * 3)); finalScore += (isAverageScore / (956 * 3)); finalScore += (msAverageScore / (860 * 3)); } else { //n == 2000, to == 250 finalScore += (qsAverageScore / (119 * 3)); finalScore += (bsAverageScore / (3193 * 3)); finalScore += (hsAverageScore / (195 * 3)); finalScore += (isAverageScore / (837 * 3)); finalScore += (msAverageScore / (802 * 3)); } //reset them for the next run qsAverageScore = 0; bsAverageScore = 0; hsAverageScore = 0; isAverageScore = 0; msAverageScore = 0; } //version for the 3 fastest algorithms void runTestFast(int n, int to) { std::cout << std::to_string(n) + " Numbers, 1 to " + std::to_string(to) + "..." << '\n' << '\n'; for (int i = 1; i <= 3; ++i) { sortTestFast(n, to, i); } //runs the test with 3 different data sets std::cout << "Quicksort: " + std::to_string(qsAverageScore / 3) + "us" << '\n'; std::cout << "Heapsort: " + std::to_string(hsAverageScore / 3) + "us" << '\n'; std::cout << "Merge Sort: " + std::to_string(msAverageScore / 3) + "us" << '\n' << '\n'; std::cout << "====================================================" << '\n' << '\n'; if (n == 10000 && to == 100) { finalScore += (qsAverageScore / (981 * 3)); finalScore += (hsAverageScore / (1042 * 3)); finalScore += (msAverageScore / (3399 * 3)); } else if (n == 10000 && to == 500) { finalScore += (qsAverageScore / (545 * 3)); finalScore += (hsAverageScore / (1005 * 3)); finalScore += (msAverageScore / (3323 * 3)); } else { //n == 50000, to == 250 finalScore += (qsAverageScore / (7968 * 3)); finalScore += (hsAverageScore / (5839 * 3)); finalScore += (msAverageScore / (17540 * 3)); } //reset them for the next run qsAverageScore = 0; hsAverageScore = 0; msAverageScore = 0; } int main() { int n, to; std::cout << "Start! (\"us\" = microseconds)" << '\n' << '\n'; //these will sort a total of 690,000 elements runTest(2000, 50); runTest(2000, 250); runTestFast(10000, 100); runTestFast(10000, 500); runTestFast(50000, 250); finalScore = (1/(finalScore / 19)) * 1000; //larger score = better PC std::cout << "Hardware score: " + std::to_string((int)(round(finalScore))) << '\n'; std::cin.get(); //keeps the window open return 0; }
#include <stdio.h> // basic I/O #include <stdlib.h> #include <sys/types.h> // standard system types #include <netinet/in.h> // Internet address structures #include <sys/socket.h> // socket API #include <arpa/inet.h> #include <netdb.h> // host to IP resolution #include <string.h> #include <unistd.h> #include <iostream> using namespace std; #define HOSTNAMELEN 40 // maximal host name length; can make it variable if you want #define BUFLEN 1024 // maximum response size; can make it variable if you want int main(int argc, char *argv[]) { // check that there are enough parameters if (argc != 2) { fprintf(stderr, "Usage: mydns <hostname>\n"); exit(-1); } struct hostent *srv; // Address resolution stage by using gethostbyname() srv = gethostbyname(argv[1]); // Write your code here! if (srv == NULL) { cout << "Error : Resolving hostname\n"; return 1; } // Print to standard output struct in_addr **ip_list = (struct in_addr **)srv->h_addr_list; for (int i = 0; ip_list[i] != NULL; i++) { cout << inet_ntoa(*ip_list[i]) << endl; } return 0; }
#include "BaseSprite.h" BaseSprite::BaseSprite() { } BaseSprite::~BaseSprite() { } void BaseSprite::run() { _isRunFinish = false; auto callback = CallFunc::create([=](){ _isRunFinish = true; }); auto move = MoveTo::create(_speed, getTagPosition()); auto act = Sequence::create(move, callback, NULL); this->runAction(act); } bool BaseSprite::isRunFinish() { return _isRunFinish; }
#ifndef GRAPHICSTEST_CIRCLE_H #define GRAPHICSTEST_CIRCLE_H #include "object.h" class Circle : public Object { public: float radius; Circle(int mass, vector2d start_pos, vector2d start_vel, float radius) : radius(radius), Object(mass, start_pos, start_vel) { this->collider = new CircleCollider(); } virtual void draw(SDL_Renderer* renderer) { SDL_SetRenderDrawColor(renderer, 43, 44, 45, SDL_ALPHA_OPAQUE); SDL_Point points[360]; for(int i = 0; i < 360; i++) { double rad = (PI / 180) * i; points[i] = { (int)(this->position.x + radius * cos(rad)), (int)(this->position.y + radius * sin(rad)) }; } SDL_RenderDrawPoints(renderer, points, 360); } virtual void update_collider() { CircleCollider *collider_n = (CircleCollider *)collider; collider_n->pos = this->position; collider_n->radius = radius; //position.print(); //collider_n->pos.print(); } virtual double get_moment_inertia() { // TODO: Do } virtual vector2d get_arm_vector() { // TODO: Do } }; #endif
// Created on: 1991-04-24 // Created by: Remi GILET // Copyright (c) 1991-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Geom2dGcc_Lin2dTanOblIter_HeaderFile #define _Geom2dGcc_Lin2dTanOblIter_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <gp_Lin2d.hxx> #include <GccEnt_Position.hxx> #include <gp_Pnt2d.hxx> class Geom2dGcc_QCurve; //! This class implements the algorithms used to //! create 2d line tangent to a curve QualifiedCurv and //! doing an angle Angle with a line TheLin. //! The angle must be in Radian. class Geom2dGcc_Lin2dTanOblIter { public: DEFINE_STANDARD_ALLOC //! This class implements the algorithm used to //! create 2d line tangent to a curve and doing an //! angle Angle with the line TheLin. //! Angle must be in Radian. //! Param2 is the initial guess on the curve QualifiedCurv. //! Tolang is the angular tolerance. Standard_EXPORT Geom2dGcc_Lin2dTanOblIter(const Geom2dGcc_QCurve& Qualified1, const gp_Lin2d& TheLin, const Standard_Real Param1, const Standard_Real TolAng, const Standard_Real Angle = 0); //! This method returns true when there is a solution //! and false in the other cases. Standard_EXPORT Standard_Boolean IsDone() const; Standard_EXPORT gp_Lin2d ThisSolution() const; Standard_EXPORT void WhichQualifier (GccEnt_Position& Qualif1) const; Standard_EXPORT void Tangency1 (Standard_Real& ParSol, Standard_Real& ParArg, gp_Pnt2d& PntSol) const; Standard_EXPORT void Intersection2 (Standard_Real& ParSol, Standard_Real& ParArg, gp_Pnt2d& PntSol) const; Standard_EXPORT Standard_Boolean IsParallel2() const; protected: private: Standard_Boolean WellDone; Standard_Boolean Paral2; gp_Lin2d linsol; GccEnt_Position qualifier1; gp_Pnt2d pnttg1sol; gp_Pnt2d pntint2sol; Standard_Real par1sol; Standard_Real par2sol; Standard_Real pararg1; Standard_Real pararg2; }; #endif // _Geom2dGcc_Lin2dTanOblIter_HeaderFile
/******************************************************************************** This is a library for converting images already located in RAM to lower bit-depth versions with different kinds of dithering algorithms. WARNING: These algorithms operate on the microcontroller's RAM buffer in order to apply changes, so a fair amount of RAM (at least as big as the image buffer itself) is required to avoid crashes. Copyright (c) 2021 Leopoldo Perizzolo - Deep Tronix Find me @ https://rebrand.ly/deeptronix Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ********************************************************************************/ #if (ARDUINO >= 100) #include "Arduino.h" #else #include "WProgram.h" #endif #define END (-32) #define is_2s_pow(number) !((number) & ((number) - 1)) class Dither { public: Dither(uint16_t width = 0, uint16_t height = 0, bool invert_output = false); void updateDimensions(uint16_t new_width, uint16_t new_height); uint16_t getWidth(); uint16_t getHeight(); void reRandomizeBuffer(); int8_t FSDither(uint8_t *IMG_pixel, uint8_t quant_bits = 1); int8_t JJNDither(uint8_t *IMG_pixel, uint8_t quant_bits = 1); int8_t StuckiDither(uint8_t *IMG_pixel, uint8_t quantization_bits = 1); int8_t BurkesDither(uint8_t *IMG_pixel, uint8_t quantization_bits = 1); int8_t Sierra3Dither(uint8_t *IMG_pixel, uint8_t quantization_bits = 1); int8_t Sierra2Dither(uint8_t *IMG_pixel, uint8_t quantization_bits = 1); int8_t Sierra24ADither(uint8_t *IMG_pixel, uint8_t quantization_bits = 1); int8_t AtkinsonDither(uint8_t *IMG_pixel, uint8_t quantization_bits = 1); int8_t PersonalFilterDither(uint8_t *IMG_pixel, uint8_t quantization_bits = 1); void fastEDDither(uint8_t *IMG_pixel); // Time complexity is O(3n), but also optimized for faster calculations and array accesses (especially on low-end uCs). #define fastEDDither_remove_artifacts false // making this true will make the above algorithm O(4n), but will reduce artifacts visible when images are bigger than roughly 8000 pixels (x*y). void buildClusteredPattern(); // Time complexity is O(1). void buildBayerPattern(); // Time complexity is O(1). int8_t patternDither(uint8_t *IMG_pixel, int8_t thresh = 0); // Time complexity is O(n). int8_t randomDither(uint8_t *IMG_pixel, bool time_consistency = true, int8_t thresh = 0); // time-consistency enabled by default (faster speed); Time complexity is O(n). void thresholding(uint8_t *IMG_pixel, uint8_t thresh = 128); // Time complexity is Theta(n). // void thresholding(uint8_t *IMG_pixel); // Overloaded function - No longer implemented // Helping functions (public) uint32_t index(int x, int y); uint32_t index(int x, int y, uint8_t pix_len); uint8_t color888ToGray256(uint8_t r, uint8_t g, uint8_t b); void colorGray256To888(uint8_t color, uint8_t &r, uint8_t &g, uint8_t &b); bool colorGray256ToBool(uint8_t gs); inline void quantize(uint8_t quant_bits, uint8_t &r, uint8_t &g, uint8_t &b); inline void quantize_BW(uint8_t &c); void color565To888(uint16_t color565, uint8_t &r, uint8_t &g, uint8_t &b); uint16_t color888To565(uint8_t r, uint8_t g, uint8_t b); void color332To888(uint8_t color332, uint8_t &r, uint8_t &g, uint8_t &b); uint8_t color888To332(uint8_t r, uint8_t g, uint8_t b); void colorBoolTo888(bool color1, uint8_t &r, uint8_t &g, uint8_t &b); bool color888ToBool(uint8_t r, uint8_t g, uint8_t b); private: uint16_t _img_width, _img_height; bool _invert_output; // For Error Distribution algorithms int8_t _GPEDDither(uint8_t *IMG_pixel, uint8_t quantization_bits, uint8_t filter_index); // GPED (dithering) : General Purpose Error Distribution (dithering) #define max_filter_entries 16 // Max filter entries per line; this parameter is needed due to limitations in C++, that cannot recognize on its own when a line ends. #define filter_types 9 const int8_t _filters[filter_types][max_filter_entries] = { // when -n, that's the number of columns we have to go back from the current pixel, on the next row. {16, 7, -1, 3, 5, 1, END}, // Floyd-Steinberg filter {48, 7, 5, -2, 3, 5, 7, 5, 3, -2, 1, 3, 5, 3, 1, END}, // Jarvis, Judice and Ninke filter {42, 8, 4, -2, 2, 4, 8, 4, 2, -2, 1, 2, 4, 2, 1, END}, // Stucki filter {32, 8, 4, -2, 2, 4, 8, 4, 2, END}, // Burkes filter {32, 5, 3, -2, 2, 4, 5, 4, 2, -1, 2, 3, 2, END}, // Sierra3 filter {16, 4, 3, -2, 1, 2, 3, 2, 1, END}, // Sierra2 filter {4, 2, -1, 1, 1, END}, // Sierra-2-4A filter {8, 1, 1, -1, 1, 1, 1, -1, 0, 1, END}, // Atkinson filter {8, 1, 1, -1, 0, 1, 1, END}, // Personal filter }; #define FSf 0 #define JJNf 1 #define STUf 2 #define BURf 3 #define SIE3f 4 #define SIE2f 5 #define SIE24f 6 #define ATKf 7 #define PERf 8 // For Halftoning algorithms #define _size 2 // Halftoning pattern size (square convolutional matrix); minimum is 1. The number of output gray shades obtainable is [1 + (_size)^2]. Values of _size powers of 2 are recommended on non-math enhanced or slow processors. uint8_t _pattern[_size][_size] = {{0}}; // Halftoning pattern array // For Thresholding and Random dithering #define _rnd_frame_width 1024 // use ONLY powers of 2 ; recommended a value twice as big as the image width (see documentation) uint8_t _rnd_frame[_rnd_frame_width]; #define _use_low_amplitude_noise true // Usually, low amplitude noise is best (resembles more Gaussian distribution). Only sometimes high amplitude noise will result in a more pleasing image. // Helping functions (private) uint8_t _Rnd(uint8_t seed = 150); inline uint8_t _twos_power(uint16_t number); inline uint8_t _clamp(int16_t v, uint8_t min, uint8_t max); };
//: C16:Array2.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 // Definicja szablonu funkcji, // niebedacej funkcja inline #include "../require.h" template<class T> class Array { enum { size = 100 }; T A[size]; public: T& operator[](int index); }; template<class T> T& Array<T>::operator[](int index) { require(index >= 0 && index < size, "Indeks poza zakresem"); return A[index]; } int main() { Array<float> fa; fa[0] = 1.414; } ///:~
// C++ program for implementation of Heap Sort #include <iostream> #include <algorithm> using namespace std; // A - tablica indeksowana od 0 // n -dlugosc tablicy A // k - ilość liczb w przedziale [0,największa_liczba_w_A], UWAGA k = max_element(A)+1 void counting_sort(int A[],int n,int k){ int B[n], C[k]; for(int i=0;i<k;i++) C[i]=0; for(int i=0;i<n;i++) C[A[i]]++; for(int i=1;i<k;i++) C[i] = C[i]+C[i-1]; for(int i=n-1;i>=0;i--){ //musi byc od tyłu zeby bylo stabilne B[C[A[i]]-1] = A[i]; // to -1 jest poniewaz tablica A indeksowana jest od 0. C[A[i]]--; } for(int i=0;i<n;i++) A[i]=B[i]; } int main() { int A[]={2,5,3,0,2,3,0,3,6,0}; int n=sizeof(A)/sizeof(A[0]); int k = (*max_element(A,A+n))+1; counting_sort(A,n,k); for (int i : A) { cout << i << ", "; } }
/* * The MIT License (MIT) * * Copyright (c) 2014 Matt Olan, Prajjwal Bhandari * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <parsed.h> #include <catch.h> #include <vector> #include <string> TEST_CASE("Parsed::of returns a 'valid' Parsed Object", "[Parsed]") { std::vector<int> test {1, 2, 3}; Parsed< std::vector<int> > &p = Parsed< std::vector<int> >::of(test); SECTION("It should be valid,") { REQUIRE(p.is_valid()); } SECTION("value() should return a copy of the object passed in.") { REQUIRE(p.value() == test); SECTION("The object that was passed in should be deep copied.") { std::vector<int> backup = test; test.push_back(4); REQUIRE(p.value() == backup); } } SECTION("failure_reason() should be empty.") { REQUIRE(p.failure_reason() == ""); } } TEST_CASE("Parsed::invalid returns an 'invalid' Parsed Object", "[Parsed]") { std::string reason = "reasons"; Parsed<int> &p = Parsed<int>::invalid(reason); SECTION("It should not be valid,") { REQUIRE_FALSE(p.is_valid()); } SECTION("value() should throw an exception") { REQUIRE_THROWS_AS(p.value(), std::string); SECTION("exception message should be the same as it's failure reason") { try { p.value(); } catch (std::string exception) { REQUIRE(p.failure_reason() == exception); } } } SECTION("failure_reason() returns a copy of the string passed in.") { REQUIRE(p.failure_reason() == reason); SECTION("The object that was passed in should be deep copied.") { std::string backup_reason = reason; reason += "foo"; REQUIRE(p.failure_reason() == backup_reason); } } }
#include <bits/stdc++.h> using namespace std; // Definition for singly-linked list. struct ListNode { int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {} }; class Solution { public: ListNode *swapNodes(ListNode *head, int k) { ListNode *first = head; ListNode *second = head; int i = k - 1; while (i-- && first) { first = first->next; } ListNode *temp = first; while (first->next) { first = first->next; second = second->next; } swap(temp->val, second->val); return head; } };
#include <stdio.h> #include <stdlib.h> #include <string> #include <fstream> #include <iostream> #include "document.h" #include "lda.h" #include <jni.h> #include <android/log.h> using namespace std; struct corpus* read_corpus(char* corpus_name,int doc_num) { ifstream infile(corpus_name); string line; //corpus* cps = (corpus*)malloc(sizeof(struct corpus)); corpus* cps = new corpus; cps->docs = NULL; //不加这句后面的realloc会出问题 int d; // var show how many documents(lines) we've read d = 0; if ( !infile ) { cout << "unable to open input file" << endl; return 0; } cps->num_terms = 0; cps->docs = new document[doc_num]; // read one line per time, one line stands for one document while (getline(infile,line)) { //cps->docs = (struct document*)realloc(cps->docs,sizeof(struct document) * (d+1)); if (cps->docs == NULL) { cout << "out of memory" << endl; exit(1); } // create a document model cps->docs[d].id = d; create_document(&cps->docs[d],&cps->num_terms,line); d++; } __android_log_print(ANDROID_LOG_INFO, "ldaApply.cpp", "cps->docs[1].num_term is %d",cps->docs[1].num_term); cps->num_docs = d; infile.close(); return cps; } void save_model(struct corpus* cps, struct est_param* p, string model_name,double alpha, double beta, int topic_num, int sample_num) { string file_name; // model_name.other contains: alpha,beta,topic_num,sample_num file_name = model_name+".other"; ofstream other_out(file_name.c_str()); other_out << "alpha: " << alpha << endl; other_out << "beta: " << beta << endl; other_out << "topic_num: " << topic_num << endl; other_out << "sample_num: " << sample_num << endl; other_out.close(); // modeal_name.phi contains a matrix represents phi[k][v] file_name = model_name + ".phi"; ofstream phi_out(file_name.c_str()); for (int k=0; k<topic_num; k++) { int v; for (v=0; v<cps->num_terms-1; v++) { phi_out << p->phi[k][v] << "+"; } phi_out << p->phi[k][v]; phi_out << endl; } phi_out.close(); //model_name.theta contains a matrix represents theta[m][k] file_name = model_name + ".theta"; ofstream theta_out(file_name.c_str()); for (int m=0; m<cps->num_docs; m++) { int k; for (k=0; k<topic_num-1; k++) { theta_out << p->theta[m][k] << " "; } theta_out << p->theta[m][k]; theta_out << endl; } theta_out.close(); // model_name.topic_assgin contains a matrix represents z[m][n] file_name = model_name + ".topic_assgin"; ofstream tassgin_out(file_name.c_str()); for (int m=0; m<cps->num_docs; m++) { int n; for (n=0; n<cps->docs[m].num_term-1; n++) { tassgin_out << p->z[m][n] << " "; } tassgin_out << p->z[m][n]; tassgin_out << endl; } tassgin_out.close(); }
#pragma once #include <memory> #include "QuestionViewController.h" namespace qp { class IQuestionViewControllerFactory { public: virtual std::unique_ptr<CQuestionViewController> CreateViewControllerForState(IQuestionStatePtr const& state) = 0; virtual ~IQuestionViewControllerFactory(){}; }; }
// This file was generated based on /Users/r0xstation/18app/src/.uno/ux13/app18.unoproj.g.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.UX.PropertyAccessor.h> namespace g{namespace Uno{namespace UX{struct PropertyObject;}}} namespace g{namespace Uno{namespace UX{struct Selector;}}} namespace g{struct app18_accessor_Tab_Text;} namespace g{ // internal sealed class app18_accessor_Tab_Text :261 // { ::g::Uno::UX::PropertyAccessor_type* app18_accessor_Tab_Text_typeof(); void app18_accessor_Tab_Text__ctor_1_fn(app18_accessor_Tab_Text* __this); void app18_accessor_Tab_Text__GetAsObject_fn(app18_accessor_Tab_Text* __this, ::g::Uno::UX::PropertyObject* obj, uObject** __retval); void app18_accessor_Tab_Text__get_Name_fn(app18_accessor_Tab_Text* __this, ::g::Uno::UX::Selector* __retval); void app18_accessor_Tab_Text__New1_fn(app18_accessor_Tab_Text** __retval); void app18_accessor_Tab_Text__get_PropertyType_fn(app18_accessor_Tab_Text* __this, uType** __retval); void app18_accessor_Tab_Text__SetAsObject_fn(app18_accessor_Tab_Text* __this, ::g::Uno::UX::PropertyObject* obj, uObject* v, uObject* origin); void app18_accessor_Tab_Text__get_SupportsOriginSetter_fn(app18_accessor_Tab_Text* __this, bool* __retval); struct app18_accessor_Tab_Text : ::g::Uno::UX::PropertyAccessor { static ::g::Uno::UX::Selector _name_; static ::g::Uno::UX::Selector& _name() { return _name_; } static uSStrong< ::g::Uno::UX::PropertyAccessor*> Singleton_; static uSStrong< ::g::Uno::UX::PropertyAccessor*>& Singleton() { return Singleton_; } void ctor_1(); static app18_accessor_Tab_Text* New1(); }; // } } // ::g
#ifndef TREEFACE_IMAGE_MANAGER_H #define TREEFACE_IMAGE_MANAGER_H #include "treeface/base/Common.h" #include <treecore/Result.h> #include <treecore/RefCountObject.h> #include <treecore/RefCountSingleton.h> #include <treecore/Identifier.h> namespace treeface { class Image; class ImageManager: public treecore::RefCountObject, public treecore::RefCountSingleton<ImageManager> { friend class treecore::RefCountSingleton<ImageManager>; public: TREECORE_DECLARE_NON_COPYABLE( ImageManager ); TREECORE_DECLARE_NON_MOVABLE( ImageManager ); Image* get_image( const treecore::Identifier& name ); bool image_is_cached( const treecore::Identifier& name ) const; bool release_image_hold( const treecore::Identifier& name ); protected: struct Impl; ImageManager(); ~ImageManager(); Impl* m_impl = nullptr; }; } // namespace treeface #endif // TREEFACE_IMAGE_MANAGER_H
int row[101] = {0}; int ld[101] = {0}; int rd[101] = {0}; bool isValid(int i, int j, int n) { if (row[i] || ld[i + j] || rd[i - j + n - 1]) return 0; return 1; } void nextQueen(int n, int col, vector<string> board, vector<vector<string> > &ans) { if (col == n) { ans.push_back(board); return; } for (int i = 0; i < n; i++) { if (isValid(i, col, n)) { board[i][col] = 'Q'; row[i] = 1; ld[i + col] = 1; rd[i - col + n - 1] = 1; nextQueen(n, col + 1, board, ans); board[i][col] = '.'; row[i] = 0; ld[i + col] = 0; rd[i - col + n - 1] = 0; } } } vector<vector<string> > Solution::solveNQueens(int n) { // Do not write main() function. // Do not read input, instead use the arguments to the function. // Do not print the output, instead return values as specified // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details vector<string> board(n, string(n, '.')); vector<vector<string> > ans; nextQueen(n, 0, board, ans); return ans; } // or /* C/C++ program to solve N Queen Problem using backtracking */ #define N 4 #include <stdbool.h> #include <stdio.h> /* ld is an array where its indices indicate row-col+N-1 (N-1) is for shifting the difference to store negative indices */ int ld[30] = { 0 }; /* rd is an array where its indices indicate row+col and used to check whether a queen can be placed on right diagonal or not*/ int rd[30] = { 0 }; /*column array where its indices indicates column and used to check whether a queen can be placed in that row or not*/ int cl[30] = { 0 }; /* A utility function to print solution */ void printSolution(int board[N][N]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf(" %d ", board[i][j]); printf("\n"); } } /* A recursive utility function to solve N Queen problem */ bool solveNQUtil(int board[N][N], int col) { /* base case: If all queens are placed then return true */ if (col >= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if the queen can be placed on board[i][col] */ /* A check if a queen can be placed on board[row][col].We just need to check ld[row-col+n-1] and rd[row+coln] where ld and rd are for left and right diagonal respectively*/ if ((ld[i - col + N - 1] != 1 && rd[i + col] != 1) && cl[i] != 1) { /* Place this queen in board[i][col] */ board[i][col] = 1; ld[i - col + N - 1] = rd[i + col] = cl[i] = 1; /* recur to place rest of the queens */ if (solveNQUtil(board, col + 1)) return true; /* If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col] */ board[i][col] = 0; // BACKTRACK ld[i - col + N - 1] = rd[i + col] = cl[i] = 0; } } /* If the queen cannot be placed in any row in this colum col then return false */ return false; } /* This function solves the N Queen problem using Backtracking. It mainly uses solveNQUtil() to solve the problem. It returns false if queens cannot be placed, otherwise, return true and prints placement of queens in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ bool solveNQ() { int board[N][N] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveNQUtil(board, 0) == false) { printf("Solution does not exist"); return false; } printSolution(board); return true; } // driver program to test above function int main() { solveNQ(); return 0; }
#include <tr1/array> #include <tr1/memory> #include <iostream> #include "Hyperbolic2d.h" #include "Assert.h" #include <Eigen/Dense> #include <utility> #include <algorithm> using Eigen::Vector2d; using Eigen::Matrix2d; Hyperbolic2d::Point::Point(double x, double y) { assert(y > 0.00000001); coordinates[0] = x; coordinates[1] = y; } Hyperbolic2d::Point::Point() { coordinates[1] = 1; } std::tr1::array<double,2> Hyperbolic2d::Point::getCoordinates(){return coordinates;} void Hyperbolic2d::Point::setCoordinates(double x, double y) { coordinates[0] = x; coordinates[1] = y; } Vector2d Hyperbolic2d::Point::vectorFromPoint(Hyperbolic2d::Point point) { return this->getGeodesic(point)->getVector(); } Vector2d Hyperbolic2d::Line::getVector() { return z; } Vector2d Hyperbolic2d::Circle::getVector() { return z; } std::tr1::shared_ptr<Hyperbolic2d::Geodesic> Hyperbolic2d::Point::getGeodesic(Hyperbolic2d::Point point) { std::tr1::array<double,2> x = this->getCoordinates(); std::tr1::array<double,2> y = point.getCoordinates(); assert(x[1] > 0); if(fabs(x[0] - y[0]) < 0.00001) { return std::tr1::shared_ptr<Hyperbolic2d::Geodesic>(new Hyperbolic2d::Line(this, point, Vector2d(0.,log(y[1]/x[1])))); } //std::cout << "fabs(x[0] - y[0]) >= 0.00001\n"; double c = ((x[0]*x[0]+x[1]*x[1])-(y[0]*y[0]+y[1]*y[1]))/(2*(x[0]-y[0])); double r = sqrt(x[1]*x[1]+(x[0]-c)*(x[0]-c)); double dir0 = x[1]/r; double dir1 = (c-x[0])/r; double dist = log((x[1]*(r+y[0]-c))/(y[1]*(r+x[0]-c))); Vector2d z(dir0*dist,dir1*dist); #ifndef NDEBUG std::tr1::array<double,2> yy = getGeodesic(z)->getEndPoint().getCoordinates(); assert(fabs(yy[0] - y[0]) < EPSILON); assert(fabs(yy[1] - y[1]) < EPSILON); #endif //assert(fabs(fabs(log((x[1]*(r+y[0]-c))/(y[1]*(r+x[0]-c)))) - z.norm()) < EPSILON); /*std::cout << "y: (" << y[0] << ", " << y[1] << ")\n"; std::cout << "c: " << c << "\n"; std::cout << "r: " << r << "\n"; std::cout << "dir0: " << dir0 << "\n"; std::cout << "dir1: " << dir1 << "\n"; std::cout << "dist: " << dist << "\n"; std::cout << "(r+x[0]-c): " << (r+x[0]-c) << "\n"; std::cout << "(r+y[0]-c): " << (r+y[0]-c) << "\n"; std::cout << "x[1]: " << x[1] << "\n"; std::cout << "y[1]: " << y[1] << "\n"; std::cout << "(y[1]*(r+x[0]-c))/(x[1]*(r+y[0]-c)): " << (y[1]*(r+x[0]-c))/(x[1]*(r+y[0]-c)) << "\n";*/ assert(z[0] == z[0]); assert(z[1] == z[1]); /*std::cout << "pointFromVector(out).coordinates[0]: " << pointFromVector(out).coordinates[0] << "\n"; std::cout << "pointFromVector(out).coordinates[1]: " << pointFromVector(out).coordinates[1] << "\n"; std::cout << "point.coordinates[0]: " << point.coordinates[0] << "\n"; std::cout << "point.coordinates[1]: " << point.coordinates[1] << "\n";*/ //assert(fabs(this->pointFromVector(z).getCoordinates()[0] - point.getCoordinates()[0]) < 0.000001); //assert(fabs(this->pointFromVector(z).getCoordinates()[1] - point.getCoordinates()[1]) < 0.000001); return std::tr1::shared_ptr<Hyperbolic2d::Geodesic>(new Hyperbolic2d::Circle(this, point, z, c, r)); } Hyperbolic2d::Point Hyperbolic2d::Point::pointFromVector(Vector2d z) { return this->getGeodesic(z)->getEndPoint(); } std::tr1::shared_ptr<Hyperbolic2d::Geodesic> Hyperbolic2d::Point::getGeodesic(Vector2d z) { //std::cout << "Hyperbolic2d::Point::getGeodesic(z) z:\n" << z << std::endl; assert(z == z); std::tr1::array<double,2> x = this->getCoordinates(); assert(x[1] > EPSILON); if(fabs(z[0]) < EPSILON) { return std::tr1::shared_ptr<Hyperbolic2d::Geodesic>(new Hyperbolic2d::Line(this, Hyperbolic2d::Point(x[0],x[1]*exp(z[1])), z)); } //std::cout << "fabs(z[0]) >= 0.000001\n"; double c = x[0]+x[1]*z[1]/z[0]; double r = sqrt(x[1]*x[1]+(x[0]-c)*(x[0]-c)); double dist = sqrt(z[0]*z[0]+z[1]*z[1]); if(z[0] > 0) { dist *= -1; //std::cout << "z[0] > 0\n"; } else { //std::cout << "z[0] <= 0\n"; } double rx0c2 = r+x[0]-c; rx0c2 *= rx0c2; double x12e2d = x[1]*x[1]*exp(2*dist); double y0 = ((r+c)*rx0c2-x12e2d*(r-c))/(x12e2d+rx0c2); double y1 = sqrt(r*r-(y0-c)*(y0-c)); //std::cout << "z: (" << z[0] << ", " << z[1] << ")" << std::endl; //std::cout << "|z|:\t" << sqrt(z[0]*z[0]+z[1]*z[1]) << std::endl; //std::cout << "y1:\t" << y1 << std::endl; assert(y1 > EPSILON); /*std::cout << "point: (" << x[0] << ", " << x[1] << ")\n"; std::cout << "2d vector: (" << z[0] << ", " << z[1] << ")\n"; std::cout << "2d point: (" << y0 << ", " << y1 << ")\n"; Vector2d difference = this->getGeodesic(Hyperbolic2d::Point(y0,y1))->getVector(); std::cout << "difference: (" << difference[0] << ", " << difference[1] << ")\n";*/ /*std::cout << "z:\n" << z << "\n"; std::cout << "c: " << c << "\n"; std::cout << "r: " << r << "\n";*/ //assert(fabs(log((y1*(r+x[0]-c))/(x[1]*(r+y0-c))) - dist) < 0.000001); Hyperbolic2d::Point end(y0,y1); return std::tr1::shared_ptr<Hyperbolic2d::Geodesic>(new Hyperbolic2d::Circle(this, end, z, c, r)); } Hyperbolic2d::Point Hyperbolic2d::Line::getStartPoint() { return start; } Hyperbolic2d::Point Hyperbolic2d::Circle::getStartPoint() { return start; } Hyperbolic2d::Point Hyperbolic2d::Line::getEndPoint() { return end; } Hyperbolic2d::Point Hyperbolic2d::Circle::getEndPoint() { return end; } std::pair<Hyperbolic2d::Point, double> Hyperbolic2d::Point::pointAndRotFromVector(Vector2d z) { std::tr1::shared_ptr<Hyperbolic2d::Geodesic> geodesic = this->getGeodesic(z); return std::pair<Hyperbolic2d::Point, double>(geodesic->getEndPoint(), geodesic->getRot()); } double Hyperbolic2d::Line::getRot() { return 0; } double Hyperbolic2d::Circle::getRot() { std::tr1::array<double,2> x = start.getCoordinates(); std::tr1::array<double,2> y = end.getCoordinates(); double angle0 = atan2(x[1],x[0]-c); //This is pointing towards the center. Since I'm just looking at the difference, it doesn't really matter. double angle1 = atan2(y[1],y[0]-c); //std::cout << "2d:" << std::endl; //std::cout << "x[1]: " << x[1] << std::endl; //std::cout << "x[0]-c: " << x[0]-c << "\nangle0: " << angle0 << "\nangle1: " << angle1 << std::endl; //This could be optimized by taking the arccos of the dot product. return angle1-angle0; } double Hyperbolic2d::Line::wormholeIntersectionDistance(double portal) { //std::cout << "Hyperbolic2d.cpp Line" << std::endl; double edist = (start.getCoordinates()[1])/(start.getCoordinates()[0]*portal); if(edist < EPSILON || edist == INFINITY) { return INFINITY; } double dist = log(edist); if(z[1] < 0) { dist = -dist; } if(dist < EPSILON) { return INFINITY; } else { #ifndef NDEBUG if(z.squaredNorm() > EPSILON) { std::tr1::array<double,2> intersection = start.getGeodesic(z.normalized()*dist)->getEndPoint().getCoordinates(); assert(intersection[1]/intersection[0] == portal); } #endif return dist; } } double Hyperbolic2d::Circle::wormholeIntersectionDistance(double portal) { //std::cout << "Hyperbolic2d.cpp Circle" << std::endl; /*std::cout << "Hyperbolic2d.cpp c:\t" << c << std::endl; std::cout << "Hyperbolic2d.cpp r:\t" << r << std::endl; std::cout << "Hyperbolic2d.cpp portal:\t" << portal << std::endl;*/ //std::cout << "Hyperbolic2d.cpp (c > 0) ^ (portal > 0):\t" << ((c > 0) ^ (portal > 0)) << std::endl; if(c > r) { if((c > 0) ^ (portal > 0)) { //If c and portal are not on the same side, so the circle could only intersect the line on the negative half of the plane return INFINITY; } } double c2 = c*c; //Center, but also happens to be the hypotenuse of a right triangle. Lucky. double a2 = c2*portal*portal/(portal*portal+1); double b2 = c2-a2; double d2 = r*r-b2; if(d2 < EPSILON) { return INFINITY; } double a = sqrt(a2); double d = sqrt(d2); std::tr1::array<double,2> x = start.getCoordinates(); //assert(fabs((x[0]-c)*(x[0]-c)+x[1]*x[1] - r*r) < EPSILON); //Theoretically this should be true, but the error doesn't seem to be a problem. Vector2d dir; dir << portal, 1; dir.normalize(); Vector2d y0 = (a-d)*dir; //It's a point, but since I'm finding it like that, I thought Vector2d would be easier. //std::cout << "(y0 - (Vector2d() << c,0).finished()).squaredNorm()/(r*r)-1\t" << (y0 - (Vector2d() << c,0).finished()).squaredNorm()/(r*r)-1 << std::endl; /*std::cout << "c\t:" << c << std::endl; std::cout << "(y0 - (c,0)).norm():\t" << (y0 - (Vector2d() << c,0).finished()).norm() << std::endl; std::cout << "r\t:" << r << std::endl;*/ //assert(fabs((y0 - (Vector2d() << c,0).finished()).squaredNorm()/(r*r)-1) < EPSILON); //This assertion is about right. The program seems to run okay. But it's off by more than EPSILON, and since I'm squaring everything, it should be within EPSILON^2. double dist = INFINITY; if(y0[1] > 0 && !((z[0] > 0) ^ (y0[0] > x[0]))) { dist = fabs(log((x[1]*(r+y0[0]-c))/(y0[1]*(r+x[0]-c)))); if(dist < EPSILON) { dist = INFINITY; } //std::cout << "Hyperbolic2d.cpp dist:\t" << dist << std::endl; if(dist < INFINITY) { assert(fabs(dist - start.getGeodesic(Hyperbolic2d::Point(y0[0],y0[1]))->getVector().norm()) < EPSILON); assert((dist*z.normalized() - start.getGeodesic(Hyperbolic2d::Point(y0[0],y0[1]))->getVector()).norm() < EPSILON); } } Vector2d y1 = (a+d)*dir; //assert(fabs((y1 - (Vector2d() << c,0).finished()).squaredNorm()/(r*r)-1) < EPSILON); if(y1[1] > 0 && !((z[0] > 0) ^ (y1[0] > x[0]))) { double dist2 = fabs(log((x[1]*(r+y1[0]-c))/(y1[1]*(r+x[0]-c)))); /*std::cout << "Hyperbolic2d.cpp (y1[1]*(r+x[0]-c)):\t" << (y1[1]*(r+x[0]-c)) << std::endl; std::cout << "Hyperbolic2d.cpp (x[1]*(r+y1[0]-c)):\t" << (x[1]*(r+y1[0]-c)) << std::endl; std::cout << "Hyperbolic2d.cpp dist2:\t" << dist2 << std::endl;*/ /*#ifndef NDEBUG assert(fabs(dist2 - start.getGeodesic(Hyperbolic2d::Point(y1[0],y1[1]))->getVector().norm()) < EPSILON); assert((dist2*z.normalized() - start.getGeodesic(Hyperbolic2d::Point(y1[0],y1[1]))->getVector()).norm() < EPSILON); if(dist2 < INFINITY) { std::tr1::array<double,2> intersection = start.getGeodesic(z.normalized()*dist2)->getEndPoint().getCoordinates(); std::tr1::array<double,2> intersection2 = start.getGeodesic(-z.normalized()*dist2)->getEndPoint().getCoordinates(); assert(intersection[0]/intersection[1] == portal || intersection2[0]/intersection2[1]); //This assert passes if the distance is right but the direction is wrong. assert(intersection[0]/intersection[1] == portal); //This assert only passes if both are correct. } #endif*/ if(dist2 > EPSILON) { dist = std::min(dist,dist2); } } #ifndef NDEBUG if(dist <= 0) { std::cout << "Hyperbolic2d.cpp dist:\t" << dist << std::endl; } assert(dist > 0); if(dist < INFINITY && z.squaredNorm() > EPSILON) { //std::cout << "Hyperbolic2d::Circle::wormholeIntersectionDistance() dist:\t" << dist << std::endl; std::tr1::array<double,2> intersection = start.getGeodesic(z.normalized()*dist)->getEndPoint().getCoordinates(); assert(fabs(intersection[0]/intersection[1] - portal) < EPSILON); } #endif return dist; } Intersection2d Hyperbolic2d::Line::wormholeGetIntersection(double portal) { double dist = wormholeIntersectionDistance(portal); Vector2d vector; vector << 1, portal; vector.normalize(); if(z[1] > 0) { vector *= z[1]-dist; } else { vector *= z[1]+dist; } return Intersection2d(log(start.getCoordinates()[1]),0,vector); } Intersection2d Hyperbolic2d::Circle::wormholeGetIntersection(double portal) { double c2 = c*c; //Center, but also happens to be the hypotenuse of a right triangle. Lucky. double a2 = c2*portal*portal/(portal*portal+1); double b2 = c*c-a2; double d2 = r*r-b2; double a = sqrt(a2); double d = sqrt(d2); std::tr1::array<double,2> x = start.getCoordinates(); Vector2d dir; dir << portal, 1; dir.normalize(); Vector2d y; Vector2d y0 = (a-d)*dir; double dist = INFINITY; bool flag; if((z[0] > 0) ^ (y0[0] < x[0])) { dist = log((x[1]*(r+y0[0]-c))/(y0[1]*(r+x[0]-c))); y = y0; //d = a-d; //Redefining d flag = false; } Vector2d y1 = (a+d)*dir; if((z[0] > 0) ^ (y1[0] < x[0])) { double dist2 = log((x[1]*(r+y1[0]-c))/(y1[1]*(r+x[0]-c))); if(dist2 < dist) { dist = dist2; y = y1; //d = a+d; //Redefining d flag = true; } } /*double cos = (d*d+r*r-c*c)/(2*d*r); double sin = sqrt(1-cos*cos); if(c < 0) { sin = -sin; } Vector2d vector(dist*sin,dist*cos); //I mixed up the two curves again.*/ /*double dist = wormholeIntersectionDistance(portal); Vector2d dir(portal,1); dir.normalize();*/ double sin = asin((dir[0]*c*dir-(Vector2d() << c,0).finished()).norm()/r); double cos = sqrt(1-sin); Vector2d vector = (z.norm()-dist)*Vector2d(sin,cos); if(flag) { vector[1] *= -1; } double rot = asin(y[0]-c)-asin(start.getCoordinates()[0]-c) - (atan(y[0]/y[1]) - atan(start.getCoordinates()[0]/start.getCoordinates()[1])); Intersection2d intersection(log(y.squaredNorm())/2,rot,vector); #ifndef NDEBUG Hyperbolic2d::GeodesicPtr geodesic = wormholeGetGeodesic(intersection, portal); assert(abs(geodesic->getStartPoint().getCoordinates()[0]-start.getCoordinates()[0]) < EPSILON); assert(abs(geodesic->getStartPoint().getCoordinates()[1]-start.getCoordinates()[1]) < EPSILON); #endif return intersection; } Hyperbolic2d::Circle::Circle(Hyperbolic2d::Point* start, Hyperbolic2d::Point end, Vector2d z, double c, double r) { this->start = *start; this->end = end; this->c = c; this->r = r; this->z = z; } Hyperbolic2d::Line::Line(Hyperbolic2d::Point* start, Hyperbolic2d::Point end, Vector2d z) { this->start = *start; this->end = end; this->z = z; assert(fabs(z[0]) < EPSILON); } Hyperbolic2d::GeodesicPtr Hyperbolic2d::wormholeGetGeodesic(Intersection2d intersection, double portal) { Matrix2d rot; rot << portal,1,-1,portal; rot /= sqrt(portal*portal+1); Vector2d vector = rot*intersection.getVector(); Vector2d dir; dir << portal, 1; dir.normalize(); dir *= intersection.getPosition(); Hyperbolic2d::Point start(dir[0],dir[1]); return start.getGeodesic(vector); }
// Created on: 2002-04-23 // Created by: Alexander KARTOMIN (akm) // Copyright (c) 2002-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 NCollection_Map_HeaderFile #define NCollection_Map_HeaderFile #include <NCollection_DataMap.hxx> #include <NCollection_TListNode.hxx> #include <NCollection_StlIterator.hxx> #include <NCollection_DefaultHasher.hxx> #include <Standard_NoSuchObject.hxx> /** * Purpose: Single hashed Map. This Map is used to store and * retrieve keys in linear time. * * The ::Iterator class can be used to explore the * content of the map. It is not wise to iterate and * modify a map in parallel. * * To compute the hashcode of the key the function * ::HashCode must be defined in the global namespace * * To compare two keys the function ::IsEqual must be * defined in the global namespace. * * The performance of a Map is conditioned by its * number of buckets that should be kept greater to * the number of keys. This map has an automatic * management of the number of buckets. It is resized * when the number of Keys becomes greater than the * number of buckets. * * If you have a fair idea of the number of objects * you can save on automatic resizing by giving a * number of buckets at creation or using the ReSize * method. This should be consider only for crucial * optimisation issues. */ template < class TheKeyType, class Hasher = NCollection_DefaultHasher<TheKeyType> > class NCollection_Map : public NCollection_BaseMap { public: //! STL-compliant typedef for key type typedef TheKeyType key_type; public: //! Adaptation of the TListNode to the map notations class MapNode : public NCollection_TListNode<TheKeyType> { public: //! Constructor with 'Next' MapNode (const TheKeyType& theKey, NCollection_ListNode* theNext) : NCollection_TListNode<TheKeyType> (theKey, theNext) {} //! Key const TheKeyType& Key (void) { return this->Value(); } }; public: //! Implementation of the Iterator interface. class Iterator : public NCollection_BaseMap::Iterator { public: //! Empty constructor Iterator (void) : NCollection_BaseMap::Iterator() {} //! Constructor Iterator (const NCollection_Map& theMap) : NCollection_BaseMap::Iterator(theMap) {} //! Query if the end of collection is reached by iterator Standard_Boolean More(void) const { return PMore(); } //! Make a step along the collection void Next(void) { PNext(); } //! Value inquiry const TheKeyType& Value(void) const { Standard_NoSuchObject_Raise_if (!More(), "NCollection_Map::Iterator::Value"); return ((MapNode *) myNode)->Value(); } //! Key const TheKeyType& Key (void) const { Standard_NoSuchObject_Raise_if (!More(), "NCollection_Map::Iterator::Key"); return ((MapNode *) myNode)->Value(); } }; //! Shorthand for a constant iterator type. typedef NCollection_StlIterator<std::forward_iterator_tag, Iterator, TheKeyType, true> const_iterator; //! Returns a const iterator pointing to the first element in the map. const_iterator cbegin() const { return Iterator (*this); } //! Returns a const iterator referring to the past-the-end element in the map. const_iterator cend() const { return Iterator(); } public: // ---------- PUBLIC METHODS ------------ //! Empty constructor. NCollection_Map() : NCollection_BaseMap (1, Standard_True, Handle(NCollection_BaseAllocator)()) {} //! Constructor explicit NCollection_Map (const Standard_Integer theNbBuckets, const Handle(NCollection_BaseAllocator)& theAllocator = 0L) : NCollection_BaseMap (theNbBuckets, Standard_True, theAllocator) {} //! Copy constructor NCollection_Map (const NCollection_Map& theOther) : NCollection_BaseMap (theOther.NbBuckets(), Standard_True, theOther.myAllocator) { *this = theOther; } //! Exchange the content of two maps without re-allocations. //! Notice that allocators will be swapped as well! void Exchange (NCollection_Map& theOther) { this->exchangeMapsData (theOther); } //! Assign. //! This method does not change the internal allocator. NCollection_Map& Assign (const NCollection_Map& theOther) { if (this == &theOther) return *this; Clear(); int anExt = theOther.Extent(); if (anExt) { ReSize (anExt-1); Iterator anIter(theOther); for (; anIter.More(); anIter.Next()) Add (anIter.Key()); } return *this; } //! Assign operator NCollection_Map& operator= (const NCollection_Map& theOther) { return Assign(theOther); } //! ReSize void ReSize (const Standard_Integer N) { NCollection_ListNode** newdata = 0L; NCollection_ListNode** dummy = 0L; Standard_Integer newBuck; if (BeginResize (N, newBuck, newdata, dummy)) { if (myData1) { MapNode** olddata = (MapNode**) myData1; MapNode *p, *q; Standard_Integer i,k; for (i = 0; i <= NbBuckets(); i++) { if (olddata[i]) { p = olddata[i]; while (p) { k = Hasher::HashCode(p->Key(),newBuck); q = (MapNode*) p->Next(); p->Next() = newdata[k]; newdata[k] = p; p = q; } } } } EndResize (N, newBuck, newdata, dummy); } } //! Add Standard_Boolean Add(const TheKeyType& K) { if (Resizable()) ReSize(Extent()); MapNode** data = (MapNode**)myData1; Standard_Integer k = Hasher::HashCode(K,NbBuckets()); MapNode* p = data[k]; while (p) { if (Hasher::IsEqual(p->Key(),K)) return Standard_False; p = (MapNode *) p->Next(); } data[k] = new (this->myAllocator) MapNode(K,data[k]); Increment(); return Standard_True; } //! Added: add a new key if not yet in the map, and return //! reference to either newly added or previously existing object const TheKeyType& Added(const TheKeyType& K) { if (Resizable()) ReSize(Extent()); MapNode** data = (MapNode**)myData1; Standard_Integer k = Hasher::HashCode(K,NbBuckets()); MapNode* p = data[k]; while (p) { if (Hasher::IsEqual(p->Key(),K)) return p->Key(); p = (MapNode *) p->Next(); } data[k] = new (this->myAllocator) MapNode(K,data[k]); Increment(); return data[k]->Key(); } //! Contains Standard_Boolean Contains(const TheKeyType& K) const { if (IsEmpty()) return Standard_False; MapNode** data = (MapNode**) myData1; MapNode* p = data[Hasher::HashCode(K,NbBuckets())]; while (p) { if (Hasher::IsEqual(p->Key(),K)) return Standard_True; p = (MapNode *) p->Next(); } return Standard_False; } //! Remove Standard_Boolean Remove(const TheKeyType& K) { if (IsEmpty()) return Standard_False; MapNode** data = (MapNode**) myData1; Standard_Integer k = Hasher::HashCode(K,NbBuckets()); MapNode* p = data[k]; MapNode* q = NULL; while (p) { if (Hasher::IsEqual(p->Key(),K)) { Decrement(); if (q) q->Next() = p->Next(); else data[k] = (MapNode*) p->Next(); p->~MapNode(); this->myAllocator->Free(p); return Standard_True; } q = p; p = (MapNode*) p->Next(); } return Standard_False; } //! Clear data. If doReleaseMemory is false then the table of //! buckets is not released and will be reused. void Clear(const Standard_Boolean doReleaseMemory = Standard_True) { Destroy (MapNode::delNode, doReleaseMemory); } //! Clear data and reset allocator void Clear (const Handle(NCollection_BaseAllocator)& theAllocator) { Clear(); this->myAllocator = ( ! theAllocator.IsNull() ? theAllocator : NCollection_BaseAllocator::CommonBaseAllocator() ); } //! Destructor virtual ~NCollection_Map (void) { Clear(); } //! Size Standard_Integer Size(void) const { return Extent(); } public: //!@name Boolean operations with maps as sets of keys //!@{ //! @return true if two maps contains exactly the same keys Standard_Boolean IsEqual (const NCollection_Map& theOther) const { return Extent() == theOther.Extent() && Contains (theOther); } //! @return true if this map contains ALL keys of another map. Standard_Boolean Contains (const NCollection_Map& theOther) const { if (this == &theOther || theOther.IsEmpty()) { return Standard_True; } else if (Extent() < theOther.Extent()) { return Standard_False; } for (Iterator anIter (theOther); anIter.More(); anIter.Next()) { if (!Contains (anIter.Key())) { return Standard_False; } } return Standard_True; } //! Sets this Map to be the result of union (aka addition, fuse, merge, boolean OR) operation between two given Maps //! The new Map contains the values that are contained either in the first map or in the second map or in both. //! All previous content of this Map is cleared. //! This map (result of the boolean operation) can also be passed as one of operands. void Union (const NCollection_Map& theLeft, const NCollection_Map& theRight) { if (&theLeft == &theRight) { Assign (theLeft); return; } if (this != &theLeft && this != &theRight) { Clear(); } if (this != &theLeft) { for (Iterator anIter (theLeft); anIter.More(); anIter.Next()) { Add (anIter.Key()); } } if (this != &theRight) { for (Iterator anIter (theRight); anIter.More(); anIter.Next()) { Add (anIter.Key()); } } } //! Apply to this Map the boolean operation union (aka addition, fuse, merge, boolean OR) with another (given) Map. //! The result contains the values that were previously contained in this map or contained in the given (operand) map. //! This algorithm is similar to method Union(). //! Returns True if contents of this map is changed. Standard_Boolean Unite (const NCollection_Map& theOther) { if (this == &theOther) { return Standard_False; } const Standard_Integer anOldExtent = Extent(); Union (*this, theOther); return anOldExtent != Extent(); } //! Returns true if this and theMap have common elements. Standard_Boolean HasIntersection (const NCollection_Map& theMap) const { const NCollection_Map* aMap1 = this; const NCollection_Map* aMap2 = &theMap; if (theMap.Size() < Size()) { aMap1 = &theMap; aMap2 = this; } for (NCollection_Map::Iterator aIt(*aMap1); aIt.More(); aIt.Next()) { if (aMap2->Contains(aIt.Value())) { return Standard_True; } } return Standard_False; } //! Sets this Map to be the result of intersection (aka multiplication, common, boolean AND) operation between two given Maps. //! The new Map contains only the values that are contained in both map operands. //! All previous content of this Map is cleared. //! This same map (result of the boolean operation) can also be used as one of operands. void Intersection (const NCollection_Map& theLeft, const NCollection_Map& theRight) { if (&theLeft == &theRight) { Assign (theLeft); return; } if (this == &theLeft) { NCollection_Map aCopy (1, this->myAllocator); Exchange (aCopy); Intersection (aCopy, theRight); return; } else if (this == &theRight) { NCollection_Map aCopy (1, this->myAllocator); Exchange (aCopy); Intersection (theLeft, aCopy); return; } Clear(); if (theLeft.Extent() < theRight.Extent()) { for (Iterator anIter (theLeft); anIter.More(); anIter.Next()) { if (theRight.Contains (anIter.Key())) { Add (anIter.Key()); } } } else { for (Iterator anIter (theRight); anIter.More(); anIter.Next()) { if (theLeft.Contains (anIter.Key())) { Add (anIter.Key()); } } } } //! Apply to this Map the intersection operation (aka multiplication, common, boolean AND) with another (given) Map. //! The result contains only the values that are contained in both this and the given maps. //! This algorithm is similar to method Intersection(). //! Returns True if contents of this map is changed. Standard_Boolean Intersect (const NCollection_Map& theOther) { if (this == &theOther || IsEmpty()) { return Standard_False; } const Standard_Integer anOldExtent = Extent(); Intersection (*this, theOther); return anOldExtent != Extent(); } //! Sets this Map to be the result of subtraction (aka set-theoretic difference, relative complement, //! exclude, cut, boolean NOT) operation between two given Maps. //! The new Map contains only the values that are contained in the first map operands and not contained in the second one. //! All previous content of this Map is cleared. void Subtraction (const NCollection_Map& theLeft, const NCollection_Map& theRight) { if (this == &theLeft) { Subtract (theRight); return; } else if (this == &theRight) { NCollection_Map aCopy (1, this->myAllocator); Exchange (aCopy); Subtraction (theLeft, aCopy); return; } Assign (theLeft); Subtract (theRight); } //! Apply to this Map the subtraction (aka set-theoretic difference, relative complement, //! exclude, cut, boolean NOT) operation with another (given) Map. //! The result contains only the values that were previously contained in this map and not contained in this map. //! This algorithm is similar to method Subtract() with two operands. //! Returns True if contents of this map is changed. Standard_Boolean Subtract (const NCollection_Map& theOther) { if (this == &theOther) { if (IsEmpty()) { return Standard_False; } Clear(); return Standard_True; } const Standard_Integer anOldExtent = Extent(); for (Iterator anIter (theOther); anIter.More(); anIter.Next()) { Remove (anIter.Key()); } return anOldExtent != Extent(); } //! Sets this Map to be the result of symmetric difference (aka exclusive disjunction, boolean XOR) operation between two given Maps. //! The new Map contains the values that are contained only in the first or the second operand maps but not in both. //! All previous content of this Map is cleared. This map (result of the boolean operation) can also be used as one of operands. void Difference (const NCollection_Map& theLeft, const NCollection_Map& theRight) { if (&theLeft == &theRight) { Clear(); return; } else if (this == &theLeft) { NCollection_Map aCopy (1, this->myAllocator); Exchange (aCopy); Difference (aCopy, theRight); return; } else if (this == &theRight) { NCollection_Map aCopy (1, this->myAllocator); Exchange (aCopy); Difference (theLeft, aCopy); return; } Clear(); for (Iterator anIter (theLeft); anIter.More(); anIter.Next()) { if (!theRight.Contains (anIter.Key())) { Add (anIter.Key()); } } for (Iterator anIter (theRight); anIter.More(); anIter.Next()) { if (!theLeft.Contains (anIter.Key())) { Add (anIter.Key()); } } } //! Apply to this Map the symmetric difference (aka exclusive disjunction, boolean XOR) operation with another (given) Map. //! The result contains the values that are contained only in this or the operand map, but not in both. //! This algorithm is similar to method Difference(). //! Returns True if contents of this map is changed. Standard_Boolean Differ (const NCollection_Map& theOther) { if (this == &theOther) { if (IsEmpty()) { return Standard_False; } Clear(); return Standard_True; } const Standard_Integer anOldExtent = Extent(); Difference (*this, theOther); return anOldExtent != Extent(); } //!@} }; #endif
#include "ValueSymbolTable.h" #include "llvm/ADT/StringRef.h" #include "Value.h" #include <msclr/marshal.h> using namespace LLVM; ValueSymbolTable::ValueSymbolTable(llvm::ValueSymbolTable *base) : base(base) , constructed(false) { } inline ValueSymbolTable ^ValueSymbolTable::_wrap(llvm::ValueSymbolTable *base) { return base ? gcnew ValueSymbolTable(base) : nullptr; } ValueSymbolTable::!ValueSymbolTable() { if (constructed) { delete base; } } ValueSymbolTable::~ValueSymbolTable() { this->!ValueSymbolTable(); } ValueSymbolTable::ValueSymbolTable() : base(new llvm::ValueSymbolTable()) , constructed(true) { } Value ^ValueSymbolTable::lookup(System::String ^Name) { msclr::interop::marshal_context ctx; return Value::_wrap(base->lookup(ctx.marshal_as<const char *>(Name))); } inline bool ValueSymbolTable::empty() { return base->empty(); } inline unsigned ValueSymbolTable::size() { return base->size(); } void ValueSymbolTable::dump() { base->dump(); }
#include <cstdlib> void Bar() { } void Foo() { std::atexit(Bar); } int main() { std::atexit(Foo); }
#include <iostream> using namespace std; int num_of_possible_paths(int m, int n) { if (m == 1 || n == 1) return 1; return num_of_possible_paths(m - 1, n) + num_of_possible_paths(m, n - 1); } int main() { int m,n; cout<<"Enter the dimension of the matrix M X N: "<<endl; cout<<"M --> "; cin>>m; cout<<"N --> "; cin>>n; cout<<"The total number of paths: "; cout << num_of_possible_paths(m, n); return 0; }
#include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <string.h> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; int n, m, a[111][111]; int main() { freopen("in", "r", stdin); freopen("out", "w", stdout); int T; cin >> T; for (int __it = 1; __it <= T; ++__it) { cin >> n >> m; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) scanf("%d", &a[i][j]); } bool ok = true; for (int i = 0; i < n && ok; ++i) for (int j = 0; j < m && ok; ++j) { bool ok1 = true, ok2 = true; for (int k = 0; k < n; ++k) if (a[i][j] < a[k][j]) { ok1 = false; break; } for (int k = 0; k < m; ++k) if (a[i][j] < a[i][k]) { ok2 = false; break; } if (!ok1 && !ok2) ok = false; } printf("Case #%d: ", __it); puts(ok ? "YES" : "NO"); } return 0; }
#include "RootUnit.h" #include <QDebug> #include <QApplication> #include <QStackedWidget> #include <QVBoxLayout> int main(int argc, char * argv[]) { QApplication application(argc, argv); RootUnit unit; unit.resize(975, 1100); unit.show(); return application.exec(); }
/* * Copyright 2016 Freeman Zhang <zhanggyb@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <skland/egl/display.hpp> #include <EGL/eglext.h> #include <skland/wayland/display.hpp> #include <skland/core/defines.hpp> #include <malloc.h> #ifndef ARRAY_LENGTH #define ARRAY_LENGTH(a) (sizeof (a) / sizeof (a)[0]) #endif namespace skland { namespace egl { PFNEGLSWAPBUFFERSWITHDAMAGEEXTPROC Display::kSwapBuffersWithDamageAPI = NULL; static bool weston_check_egl_extension(const char *extensions, const char *extension) { size_t extlen = strlen(extension); const char *end = extensions + strlen(extensions); while (extensions < end) { size_t n = 0; /* Skip whitespaces, if any */ if (*extensions == ' ') { extensions++; continue; } n = strcspn(extensions, " "); /* Compare strings */ if (n == extlen && strncmp(extension, extensions, n) == 0) return true; /* Found */ extensions += n; } /* Not found */ return false; } void Display::Setup(const wayland::Display &wl_display) { Destroy(); EGLint count, n, size; EGLBoolean ret; EGLint config_attribs[] = { EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_NONE }; static const EGLint context_attribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; egl_display_ = GetEGLDisplay(EGL_PLATFORM_WAYLAND_KHR, wl_display.wl_display_, NULL); DBG_ASSERT(egl_display_); ret = eglInitialize(egl_display_, &major_, &minor_); DBG_ASSERT(ret == EGL_TRUE); ret = eglBindAPI(EGL_OPENGL_ES_API); DBG_ASSERT(ret == EGL_TRUE); eglGetConfigs(egl_display_, NULL, 0, &count); EGLConfig *configs = (EGLConfig *) calloc((size_t) count, sizeof(EGLConfig)); eglChooseConfig(egl_display_, config_attribs, configs, count, &n); for (int i = 0; i < n; i++) { eglGetConfigAttrib(egl_display_, configs[i], EGL_BUFFER_SIZE, &size); if (32 == size) { // TODO: config buffer size egl_config_ = configs[i]; break; } } free(configs); DBG_ASSERT(egl_config_); egl_context_ = eglCreateContext(egl_display_, egl_config_, EGL_NO_CONTEXT, context_attribs); DBG_ASSERT(egl_context_); static const struct { const char *extension, *entrypoint; } swap_damage_ext_to_entrypoint[] = { { .extension = "EGL_EXT_swap_buffers_with_damage", .entrypoint = "eglSwapBuffersWithDamageEXT", }, { .extension = "EGL_KHR_swap_buffers_with_damage", .entrypoint = "eglSwapBuffersWithDamageKHR", }, }; const char *extensions; extensions = eglQueryString(egl_display_, EGL_EXTENSIONS); if (extensions && weston_check_egl_extension(extensions, "EGL_EXT_buffer_age")) { // int len = (int) ARRAY_LENGTH(swap_damage_ext_to_entrypoint); int i = 0; for (i = 0; i < 2; i++) { if (weston_check_egl_extension(extensions, swap_damage_ext_to_entrypoint[i].extension)) { /* The EXTPROC is identical to the KHR one */ kSwapBuffersWithDamageAPI = (PFNEGLSWAPBUFFERSWITHDAMAGEEXTPROC) eglGetProcAddress(swap_damage_ext_to_entrypoint[i].entrypoint); break; } } if (kSwapBuffersWithDamageAPI) printf("has EGL_EXT_buffer_age and %s\n", swap_damage_ext_to_entrypoint[i].extension); } } void Display::Destroy() { if (egl_display_) { eglMakeCurrent(egl_display_, (::EGLSurface) 0, (::EGLSurface) 0, (::EGLContext) 0); eglTerminate(egl_display_); eglReleaseThread(); egl_display_ = nullptr; egl_context_ = nullptr; egl_config_ = nullptr; major_ = 0; minor_ = 0; } } void Display::MakeSwapBufferNonBlock() const { EGLint a = EGL_MIN_SWAP_INTERVAL; EGLint b = EGL_MAX_SWAP_INTERVAL; if (!eglGetConfigAttrib(egl_display_, egl_config_, a, &a) || !eglGetConfigAttrib(egl_display_, egl_config_, b, &b)) { fprintf(stderr, "warning: swap interval range unknown\n"); } else if (a > 0) { fprintf(stderr, "warning: minimum swap interval is %d, " "while 0 is required to not deadlock on resize.\n", a); } /* * We rely on the Wayland compositor to sync to vblank anyway. * We just need to be able to call eglSwapBuffers() without the * risk of waiting for a frame callback in it. */ if (!eglSwapInterval(egl_display_, 0)) { fprintf(stderr, "error: eglSwapInterval() failed.\n"); } } EGLDisplay Display::GetEGLDisplay(EGLenum platform, void *native_display, const EGLint *attrib_list) { static PFNEGLGETPLATFORMDISPLAYEXTPROC get_platform_display = NULL; if (!get_platform_display) { get_platform_display = (PFNEGLGETPLATFORMDISPLAYEXTPROC) GetEGLProcAddress("eglGetPlatformDisplayEXT"); } if (get_platform_display) return get_platform_display(platform, native_display, attrib_list); return eglGetDisplay((EGLNativeDisplayType) native_display); } void *Display::GetEGLProcAddress(const char *address) { const char *extensions = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS); if (extensions && (CheckEGLExtension(extensions, "EGL_EXT_platform_wayland") || CheckEGLExtension(extensions, "EGL_KHR_platform_wayland"))) { return (void *) eglGetProcAddress(address); } return NULL; } bool Display::CheckEGLExtension(const char *extensions, const char *extension) { size_t extlen = strlen(extension); const char *end = extensions + strlen(extensions); while (extensions < end) { size_t n = 0; /* Skip whitespaces, if any */ if (*extensions == ' ') { extensions++; continue; } n = strcspn(extensions, " "); /* Compare strings */ if (n == extlen && strncmp(extension, extensions, n) == 0) return true; /* Found */ extensions += n; } /* Not found */ return false; } } }
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int N,x,a,b; cin>>N; vector<int> v(N); for(int i = 0; i < N ; i++) cin>>v[i]; cin>>x>>a>>b; v.erase(v.begin()-1+x); v.erase(v.begin()-1+a,v.begin()-1+b); cout<<v.size()<<endl; for(int i = 0 ; i <v.size() ; i++) cout<<v[i]<<" "; return 0; }
#pragma once #include "../../src/entity/gameobject.h" namespace sge { namespace entity{ class Robot: public GameObject { public: enum class State { IDLE, WALKING_RIGHT, WALKING_LEFT, WALKING_DOWN, WALKING_UP }; private: State m_State; public: Robot(graphics::Sprite *sprite); ~Robot(){} void init() override; void onUpdate() override; void onEvent(events::Event& event) override; bool onKeyPressed(events::KeyPressedEvent& e) override; bool onKeyReleased(events::KeyReleasedEvent& e) override; }; } }
#pragma once //本来、ヘッダにインクルードするのはだめだが //継承する場合は防げない //これが継承のだめなところ #include"Scene.hpp" namespace game { //タイトル画面のシーン class TitleScene:public Scene{ public: //Updateをオーバーライドする //overrideは付けなくても動くが //付けたほうが美味しい //理由はhttps://www.google.co.jpを参照 virtual void Update()final override; }; }
string multiply(string str1, string str2) { int m= str1.length(); int n= str2.length(); int v[m+n]; for(int i=0 ; i<m+n ;i++) v[i]=0; for(int i= m-1 ; i>=0; i--) { for(int j= n-1; j>=0; --j) { int mul = (str1[i] - '0') * (str2[j]-'0'); int sum= v[i+j+1] + mul; v[i+j]+=sum/10; v[i+j+1]=sum%10; } } string str3; for(int i=0 ; i<m+n ;i++) { if(str3.length()!=0 || v[i]!=0) str3+=to_string(v[i]); } if(str3.length()==0) return "0"; return str3; }
#include<vector> using std::vector; #include<algorithm> #include<memory> using std::shared_ptr; #include<string> using std::string; #include<stack> using std::stack; /* Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. Seen this question in a real interview before? */ class Solution { public: bool isValid(string s) { stack<char> m_stack; for (auto& schar : s) { if (m_stack.empty()) { if (isright(schar))return false; m_stack.push(schar); } else { if (isright(schar)) { if (!match(m_stack.top(), schar)) { return false; } else { m_stack.pop(); } } else { m_stack.push(schar); } } } return m_stack.empty(); } bool isleft(char c) { return c == '[' || c == '(' || c == '{'; } bool isright(char c) { return !isleft(c); } bool match(char l, char r) { return (l == '[' & r == ']') || (l == '(' & r == ')' || (l == '{' & r == '}')); } }; int main() { Solution s; return 0; }
#pragma once #include "StateMachine.h" #include "Enums.h" /* PlayerStateMachine represents the various states the player can be in as well as its transitions. */ class Orientation; class PlayerStateMachine : public StateMachine { public: PlayerStateMachine(); ~PlayerStateMachine(); void Start(GameObject* aOwner) override; private: void OrientationChanged(PossibleOrientation aNewOrientation); static std::vector<State> m_possibleStates; Orientation* m_orientation; EventIndex m_OrientationChangedIndex = -2; };
/* This file is part of KDevelop Copyright 2013 Olivier de Gaalon <olivier.jg@gmail.com> Copyright 2013 Milian Wolff <mail@milianw.de> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "valatypes.h" #include <QFileInfo> #include <QReadLocker> #include <language/editor/documentcursor.h> #include <language/editor/documentrange.h> #include <util/path.h> using namespace KDevelop; namespace { template<typename T> inline T cursorForCXSrcLoc(CXSourceLocation loc) { uint line = 0; uint column = 0; clang_getFileLocation(loc, 0, &line, &column, 0); return {static_cast<int>(line-1), static_cast<int>(column-1)}; } } ValaString::ValaString(CXString string) : string(string) { } ValaString::~ValaString() { clang_disposeString(string); } const char* ValaString::c_str() const { return clang_getCString(string); } bool ValaString::isEmpty() const { return !static_cast<const char*>(*this)[0]; } ValaString::operator const char*() const { const char *data = clang_getCString(string); return data ? data : ""; } QString ValaString::toString() const { return QString::fromUtf8(clang_getCString(string)); } ValaLocation::ValaLocation(CXSourceLocation location) : location(location) { } ValaLocation::operator DocumentCursor() const { uint line = 0; uint column = 0; CXFile file; clang_getFileLocation(location, &file, &line, &column, 0); ValaString fileName(clang_getFileName(file)); return {IndexedString(fileName), {static_cast<int>(line-1), static_cast<int>(column-1)}}; } ValaLocation::operator KTextEditor::Cursor() const { return cursorForCXSrcLoc<KTextEditor::Cursor>(location); } ValaLocation::operator CursorInRevision() const { return cursorForCXSrcLoc<CursorInRevision>(location); } ValaLocation::operator CXSourceLocation() const { return location; } ValaLocation::~ValaLocation() { } ValaRange::ValaRange(CXSourceRange range) : m_range(range) { } ValaLocation ValaRange::start() const { return {clang_getRangeStart(m_range)}; } ValaLocation ValaRange::end() const { return {clang_getRangeEnd(m_range)}; } CXSourceRange ValaRange::range() const { return m_range; } DocumentRange ValaRange::toDocumentRange() const { auto start = clang_getRangeStart(m_range); CXFile file; clang_getFileLocation(start, &file, 0, 0, 0); ValaString fileName(clang_getFileName(file)); return {IndexedString(fileName), toRange()}; } KTextEditor::Range ValaRange::toRange() const { return {start(), end()}; } RangeInRevision ValaRange::toRangeInRevision() const { return {start(), end()}; } ValaRange::~ValaRange() { }
/** * Peripheral Definition File * * WWDG - Independent watchdog * * MCUs containing this peripheral: * - STM32F7xx */ #pragma once #include <cstdint> #include <cstddef> #include "io/reg/stm32/_common/wwdg.hpp" namespace io { namespace base { static constexpr size_t WWDG = 0x40002c00; } static Wwdg &WWDG = *reinterpret_cast<Wwdg *>(base::WWDG); }
//一眼看上去感觉很简单,试试 做完发现果然很简单. 刚开始还考虑了一下动态规划来着 还好没朝着动态规划做下去 // 50 ms 28.04 % class Solution { public: int findUnsortedSubarray(vector<int>& nums) { if(nums.size()==0){ return 0; } vector<int> sorted = nums; sort(sorted.begin(),sorted.end()); int low=0; while(low<nums.size()&&nums[low]==sorted[low]){ ++low; } if(low==nums.size()){ //忘记考虑这种情况了 return 0; } int high = nums.size()-1; while(nums[high]==sorted[high]){ --high; } return high-low+1; } };
#pragma once namespace Прокект { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; using namespace System::IO; using namespace System::Xml; /// <summary> /// Сводка для MyForm /// </summary> public ref class MyForm : public System::Windows::Forms::Form { private: System::Windows::Forms::Button^ button1; protected: private: System::Windows::Forms::DataGridView^ dataGridView1; private: System::Windows::Forms::Button^ button2; private: System::Windows::Forms::DataGridViewTextBoxColumn^ Column1; private: System::Windows::Forms::DataGridViewTextBoxColumn^ Column2; private: System::Windows::Forms::DataGridViewTextBoxColumn^ Column3; private: /// <summary> XmlDocument ^ xd; void GetTableRow(XmlNode^ node_2_, int count){ if( (dataGridView1->Rows[count]->Cells[2]->Value) != nullptr) node_2_->InnerText = dataGridView1->Rows[count]->Cells[2]->Value->ToString(); else node_2_->InnerText= nullptr; } void GetTableAttribute(XmlAttribute^ yo, int count){ if ((dataGridView1->Rows[count]->Cells[2]->Value) != nullptr) yo->InnerText = dataGridView1->Rows[count]->Cells[2]->Value->ToString(); else yo->Value = nullptr; } void ParseDom(XmlDocument^ xdoc){ int count = 0; XmlNodeList ^ np = xdoc->ChildNodes; for each(XmlNode^ node in np) { count++; XmlNodeList ^ node_2 = node->ChildNodes; for each(XmlNode^ node_2_ in node_2) { GetTableRow(node_2_, count); count++; XmlAttributeCollection ^atr = node_2_->Attributes; for each(XmlAttribute^yo in atr) { if (yo != nullptr) GetTableAttribute(yo,count); count++; } } } } void AddTableAttrib(XmlAttribute ^atr){ dataGridView1->DefaultCellStyle->BackColor = Color::LightGreen; int index = dataGridView1->Rows->Add(atr); DataGridViewCell^ cell = dataGridView1->Rows[index]->Cells[0]; cell->Value = index; cell = dataGridView1->Rows[index]->Cells[1]; cell->Value = atr->Name; cell->ToolTipText = "Имя атрибута"; cell = dataGridView1->Rows[index]->Cells[2]; cell->Value = atr->InnerText; cell->ToolTipText = "Значение атрибута"; /* dataGridView1->AllowUserToAddRows; dataGridView1->AllowUserToDeleteRows;*/ } void AddTableRow(XmlNode^ xd, bool rflag){ DataGridViewRow ^tmp=gcnew DataGridViewRow; if (rflag) tmp->DefaultCellStyle->BackColor = Color::LightGray; /*= Color::FromArgb(1, 1, 111, 0);*/ else tmp->DefaultCellStyle->BackColor = Color::LightBlue; if (xd->Name == "#text") return; int index = dataGridView1->Rows->Add(tmp); DataGridViewCell^ cell = dataGridView1->Rows[index]->Cells[0]; cell->Value = index; cell = dataGridView1->Rows[index]->Cells[1]; cell->Value = xd->Name; cell->ToolTipText=xd->ParentNode->Name; cell = dataGridView1->Rows[index]->Cells[2]; cell->ReadOnly=(rflag); if (rflag) cell->ToolTipText = "Нередактируемое поле"; else cell->ToolTipText = "Редактируемое поле"; cell->Value = xd->InnerText; /*dataGridView1->AllowUserToAddRows; dataGridView1->AllowUserToDeleteRows;*/ } void ProcessDom(XmlNode^xdoc) { if (xdoc == nullptr)return; AddTableRow(xdoc, 1); XmlAttributeCollection ^atr = xdoc->Attributes; if (atr != nullptr) for each(XmlAttribute^yo in atr) { AddTableAttrib(yo); } if (xdoc->FirstChild!=nullptr) ProcessDom(xdoc->FirstChild); if (xdoc->NextSibling != nullptr) ProcessDom(xdoc->NextSibling); // ProcessDom(node->ChildNodes /*for each(XmlNode^ node_2_ in node_2) { AddTableRow(node_2_, 0); XmlAttributeCollection ^atr = node_2_->Attributes; for each(XmlAttribute^yo in atr) { if (yo != nullptr) AddTableAttrib(yo); } }*/ } /// Требуется переменная конструктора. /// </summary> System::ComponentModel::Container ^components; #pragma region Windows Form Designer generated code /// <summary> /// Обязательный метод для поддержки конструктора - не изменяйте /// содержимое данного метода при помощи редактора кода. /// </summary> void InitializeComponent(void) { System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(MyForm::typeid)); this->button1 = (gcnew System::Windows::Forms::Button()); this->dataGridView1 = (gcnew System::Windows::Forms::DataGridView()); this->Column1 = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn()); this->Column2 = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn()); this->Column3 = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn()); this->button2 = (gcnew System::Windows::Forms::Button()); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->dataGridView1))->BeginInit(); this->SuspendLayout(); // // button1 // this->button1->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Bottom | System::Windows::Forms::AnchorStyles::Right)); this->button1->BackColor = System::Drawing::Color::Lavender; this->button1->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"button1.BackgroundImage"))); this->button1->BackgroundImageLayout = System::Windows::Forms::ImageLayout::None; this->button1->Cursor = System::Windows::Forms::Cursors::Hand; this->button1->FlatAppearance->BorderSize = 0; this->button1->Font = (gcnew System::Drawing::Font(L"Segoe UI", 8.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(204))); this->button1->ForeColor = System::Drawing::SystemColors::ActiveCaptionText; this->button1->Location = System::Drawing::Point(462, 218); this->button1->Margin = System::Windows::Forms::Padding(0); this->button1->Name = L"button1"; this->button1->Size = System::Drawing::Size(130, 25); this->button1->TabIndex = 0; this->button1->Text = L" Загрузить XML"; this->button1->UseVisualStyleBackColor = false; this->button1->Click += gcnew System::EventHandler(this, &MyForm::button1_Click); this->button1->MouseMove += gcnew System::Windows::Forms::MouseEventHandler(this, &MyForm::button1_MouseMove); // // dataGridView1 // this->dataGridView1->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Bottom) | System::Windows::Forms::AnchorStyles::Left) | System::Windows::Forms::AnchorStyles::Right)); this->dataGridView1->AutoSizeColumnsMode = System::Windows::Forms::DataGridViewAutoSizeColumnsMode::AllCells; this->dataGridView1->AutoSizeRowsMode = System::Windows::Forms::DataGridViewAutoSizeRowsMode::AllCells; this->dataGridView1->BackgroundColor = System::Drawing::SystemColors::ControlLightLight; this->dataGridView1->BorderStyle = System::Windows::Forms::BorderStyle::None; this->dataGridView1->CellBorderStyle = System::Windows::Forms::DataGridViewCellBorderStyle::Raised; this->dataGridView1->ColumnHeadersBorderStyle = System::Windows::Forms::DataGridViewHeaderBorderStyle::Single; this->dataGridView1->ColumnHeadersHeightSizeMode = System::Windows::Forms::DataGridViewColumnHeadersHeightSizeMode::AutoSize; this->dataGridView1->Columns->AddRange(gcnew cli::array< System::Windows::Forms::DataGridViewColumn^ >(3) { this->Column1, this->Column2, this->Column3 }); this->dataGridView1->Location = System::Drawing::Point(12, 12); this->dataGridView1->Name = L"dataGridView1"; this->dataGridView1->Size = System::Drawing::Size(580, 199); this->dataGridView1->TabIndex = 1; this->dataGridView1->CellContentClick += gcnew System::Windows::Forms::DataGridViewCellEventHandler(this, &MyForm::dataGridView1_CellContentClick); // // Column1 // this->Column1->AutoSizeMode = System::Windows::Forms::DataGridViewAutoSizeColumnMode::Fill; this->Column1->DividerWidth = 1; this->Column1->HeaderText = L"Номер"; this->Column1->Name = L"Column1"; this->Column1->ReadOnly = true; // // Column2 // this->Column2->AutoSizeMode = System::Windows::Forms::DataGridViewAutoSizeColumnMode::Fill; this->Column2->HeaderText = L"Название"; this->Column2->Name = L"Column2"; this->Column2->ReadOnly = true; // // Column3 // this->Column3->AutoSizeMode = System::Windows::Forms::DataGridViewAutoSizeColumnMode::Fill; this->Column3->HeaderText = L"Значение"; this->Column3->Name = L"Column3"; this->Column3->ToolTipText = L"Информация содержащаяся в тэге"; // // button2 // this->button2->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((System::Windows::Forms::AnchorStyles::Bottom | System::Windows::Forms::AnchorStyles::Right)); this->button2->BackColor = System::Drawing::SystemColors::Control; this->button2->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"button2.BackgroundImage"))); this->button2->BackgroundImageLayout = System::Windows::Forms::ImageLayout::None; this->button2->Cursor = System::Windows::Forms::Cursors::Hand; this->button2->Font = (gcnew System::Drawing::Font(L"Segoe UI", 8.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(204))); this->button2->ForeColor = System::Drawing::SystemColors::ActiveCaptionText; this->button2->Location = System::Drawing::Point(342, 217); this->button2->Margin = System::Windows::Forms::Padding(0); this->button2->Name = L"button2"; this->button2->Size = System::Drawing::Size(114, 26); this->button2->TabIndex = 2; this->button2->Text = L" Сохранить XML"; this->button2->UseVisualStyleBackColor = false; this->button2->Click += gcnew System::EventHandler(this, &MyForm::button2_Click); // // MyForm // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->BackColor = System::Drawing::SystemColors::GradientActiveCaption; this->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"$this.BackgroundImage"))); this->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch; this->ClientSize = System::Drawing::Size(604, 255); this->Controls->Add(this->button2); this->Controls->Add(this->dataGridView1); this->Controls->Add(this->button1); this->MinimumSize = System::Drawing::Size(400, 200); this->Name = L"MyForm"; this->Text = L"XmlRead"; this->Load += gcnew System::EventHandler(this, &MyForm::MyForm_Load); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->dataGridView1))->EndInit(); this->ResumeLayout(false); } #pragma endregion public: MyForm(void) { InitializeComponent(); // //TODO: добавьте код конструктора // } protected: /// <summary> /// Освободить все используемые ресурсы. /// </summary> ~MyForm() { if (components) { delete components; } } private: System::Void dataGridView1_CellContentClick(System::Object^ sender, System::Windows::Forms::DataGridViewCellEventArgs^ e) { } private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) { OpenFileDialog ^dlg = gcnew OpenFileDialog(); Stream^ myStream; dlg->Title = "Open XML"; dlg->Filter = "Xml files(*.xml) | *.xml | All files(*.*) | *.*"; dlg->InitialDirectory = "D:\\"; if (dlg->ShowDialog() == System::Windows::Forms::DialogResult::OK) { if ((myStream = dlg->OpenFile()) != nullptr) { FileInfo^ finfo = gcnew FileInfo(dlg->FileName); if (!((finfo->Exists) && (finfo->Length != 0))) { MessageBox::Show("()()"); return; } FileStream^ fs = File::OpenRead(dlg->FileName); XmlReader ^xr = XmlReader::Create(fs); xd = nullptr; xd = gcnew XmlDocument; xd->Load(xr); dataGridView1->Rows->Clear(); ProcessDom(xd->ChildNodes->Item(0)); // Insert code to read the stream here. myStream->Close(); fs->Close(); } } } private: System::Void button1_MouseMove(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) { } private: System::Void MyForm_Load(System::Object^ sender, System::EventArgs^ e) { }; private: System::Void webBrowser1_DocumentCompleted(System::Object^ sender, System::Windows::Forms::WebBrowserDocumentCompletedEventArgs^ e) { } private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) { if (xd == nullptr){ MessageBox::Show("&&?"); Close(); } SaveFileDialog^ sd = gcnew SaveFileDialog; sd->Title = "Save Xml file"; sd->Filter = "Text files(*.xml) | *.xml | All files(*.*) | *.*"; sd->InitialDirectory = "D:\\"; if (sd->ShowDialog() == System::Windows::Forms::DialogResult::OK) { FileInfo^ finfo = gcnew FileInfo(sd->FileName); FileStream^ fs = File::OpenWrite(sd->FileName); XmlWriter ^xr = XmlWriter::Create(fs); ParseDom(xd); xd->Save(xr); fs->Close(); }; } }; }
#ifndef BASIC_ARRAY_2D_H #define BASIC_ARRAY_2D_H #include <iostream> #include <iomanip> #include <assert.h> #include <stdlib.h> using namespace std; template <class T> class BasicArray2D { inline unsigned int index(unsigned int, unsigned int); public: unsigned int rows, cols; T *data=NULL; BasicArray2D(unsigned int, unsigned int); void init(unsigned int, unsigned int); ~BasicArray2D(void); T get_data(unsigned int, unsigned int); T *get_data_ptr(unsigned int, unsigned int); }; template <class T> inline unsigned int BasicArray2D<T>::index(unsigned int i1, unsigned int i2) { return this->cols*i1 + i2; } template <class T> BasicArray2D<T>::BasicArray2D(unsigned int rows, unsigned int cols) { this->init(rows, cols); } template <class T> void BasicArray2D<T>::init(unsigned int rows, unsigned int cols) { this->rows = rows; this->cols = cols; if(this->data) free(this->data); this->data = (T *)calloc((size_t)rows*cols, sizeof(T)); } template <class T> BasicArray2D<T>::~BasicArray2D(void) { if(this->data) free(this->data); this->data = NULL; } template <class T> T BasicArray2D<T>::get_data(unsigned int i1, unsigned int i2) { return this->data[this->index(i1, i2)]; } template <class T> T *BasicArray2D<T>::get_data_ptr(unsigned int i1, unsigned int i2) { return &this->data[this->index(i1, i2)]; } #endif //BASIC_ARRAY_2D_H
//2018研究生上机测试 #include <iostream> #include <algorithm> #include <vector> #include <string> using namespace std; bool check_like(vector<int> &num) { int length = num.size(); for (int i = 0; i < length / 2; i++) { if (num[i] != num[length - i - 1]) { return false; } } int sum = 0; for (auto iter = num.begin(); iter != num.end(); iter++) { sum += *iter; } // check length length = 1; int temp = sum; while ((temp /= 10) != 0) { length++; } for (int i = 0; i < length / 2; i++) { int lsb = int(sum / pow(10, i)) % 10; int msb = sum / pow(10, length - 1 - i); if (lsb != msb) { return false; } } return true; } int main() { int k; cin >> k; vector<string> num_string(k); vector<vector<int>> nums(k); for (int i = 0; i < k; i++) { cin >> num_string[i]; int len = num_string[i].length(); nums[i].resize(len); for (int j = 0; j < len; j++) { nums[i][j] = num_string[i][j] - '0'; } } int number_of_like = 0; for (int i = 0; i < k; i++) { if (check_like(nums[i])) { number_of_like++; } } cout << number_of_like; //system("pause"); return 0; }
/***************************************** * (This comment block is added by the Judge System) * Submission ID: 16595 * Submitted at: 2015-05-09 11:49:57 * * User ID: 94 * Username: 53064064 * Problem ID: 178 * Problem Name: The Problem with the Problem Setter(Easy ver.) */ #include<iostream> #include<queue> #include<stack> #include<vector> #include<stdio.h> #include<algorithm> #include<string> #include<string.h> #include<sstream> #include<math.h> #include<iomanip> #include<map> #define maxn 1025 #define INF 2000 using namespace std; struct Edge{ int from, to, cap, flow; Edge(int a, int b, int c, int d){from=a; to=b; cap=c; flow=d;} }; int n,m,s,t; //no. of nodes/edge/start/des vector<Edge> edges; vector<int> G[maxn]; //G[i][j]->the idx of the j-th edge of node i in edges bool vis[maxn]; //for bfs int d[maxn]; //dist of s to i int cur[maxn]; //cur edge void AddEdge(int from, int to, int cap) { edges.push_back(Edge(from,to,cap,0)); edges.push_back(Edge(to,from,0,0)); m=edges.size(); G[from].push_back(m-2); G[to].push_back(m-1); } void init(){ edges.clear(); for(int i=0; i<n; i++) G[i].clear(); memset(d,0,sizeof(d)); memset(cur,-1,sizeof(cur)); } bool BFS(){ memset(vis,0,sizeof(vis)); queue<int> q; q.push(s); d[s]=0; vis[s]=1; while(!q.empty()){ int x=q.front(); q.pop(); for(int i=0; i<G[x].size(); i++){ Edge& e=edges[G[x][i]]; if(!vis[e.to] &&e.cap>e.flow){//only consider edge in residual network vis[e.to]=1; d[e.to]=d[x]+1; q.push(e.to); } } } return vis[t]; } int DFS(int x, int a){ if(x==t||a==0) return a; int flow=0,f; for(int& i=cur[x]; i<G[x].size(); i++) {//from last considered edge Edge& e = edges[G[x][i]]; if(d[x]+1==d[e.to] && (f=DFS(e.to, min(a, e.cap-e.flow)))>0){ e.flow+=f; edges[G[x][i]^1].flow=-f; flow+=f; a-=f; if(a==0) break; } } return flow; } int maxflow(){ int flow =0; while(BFS()){ memset(cur,0,sizeof(cur)); flow+=DFS(s,INF); } return flow; } int main(){ int total,nk,np,len,x,y; while(scanf("%d %d", &nk, &np)){ if(nk == 0 && np==0) break; init(); s=0; t=nk+np+1; n=t+1; total = 0; for(int i=1; i<=nk; i++){ scanf("%d", &len); AddEdge(np+i,t,len); total += len; } for(int i=1; i<=np; i++){ AddEdge(0,i,1); scanf("%d", &x); for(int j=1; j<=x; j++){ scanf("%d", &y); AddEdge(i,np+y,1); } } if(total-maxflow()) puts("0"); else puts("1"); } return 0; }
#pragma once #include <SFML/Window.hpp> #include <atomic> #include "modules/graphics/DrawModule.h" #include "modules/physics/PhysicsModule.h" #include "modules/input/EventModule.h" #include "modules/entities/EntitiesModule.h" #include "modules/ModuleManager.h" #include "time/GTime.h" #include "input/implementation/GameWindowListener.h" namespace Game { class GameWindowListener; class GameCore { public: void init(); void stopGame(); sf::Window& getWindow(); Entity* addEntity(); template<class T> T* getModule() { return mModuleManager.get<T>(); } static GameCore& get() { static GameCore instance; return instance; } GameCore(GameCore const &) = delete; void operator=(GameCore const &) = delete; private: GameCore(); ~GameCore(); sf::Thread mRenderThread; sf::Window mWindow; std::atomic<bool> mRunning; GameWindowListener *mWindowListener; ModuleManager mModuleManager; void gameLoop(); void onRender(); void onUpdate(); }; }
#ifndef _CRegGetLdCode_h_ #define _CRegGetLdCode_h_ #pragma once #include <string> #include "CHttpRequestHandler.h" class CRegGetLdCode : public CHttpRequestHandler { public: CRegGetLdCode(){} ~CRegGetLdCode(){} virtual int do_request(const Json::Value& root, char *client_ip, HttpResult& out); private: }; #endif
#include "CDialogUtils.h" ofstream infile; //---------------------------------------------------------------------------------------------------------------------- LRESULT CALLBACK _HyperlinkParentProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) { WNDPROC pfnOrigProc = (WNDPROC)GetProp(hWnd, PROP_ORIGINAL_PROC); switch(Message) { case WM_CTLCOLORSTATIC: { HDC hDC = (HDC)wParam; HWND hWndCtl = (HWND)lParam; BOOL fHyperlink = (GetProp(hWndCtl, PROP_STATIC_HYPERLINK) != NULL); if(fHyperlink) { LRESULT lr = CallWindowProc(pfnOrigProc, hWnd, Message, wParam, lParam); SetTextColor(hDC, RGB(0, 0, 192)); return lr; } } break; case WM_DESTROY: { SetWindowLong(hWnd, GWLP_WNDPROC, (LONG)pfnOrigProc); RemoveProp(hWnd, PROP_ORIGINAL_PROC); } break; } return CallWindowProc(pfnOrigProc, hWnd, Message, wParam, lParam); } LRESULT CALLBACK _HyperlinkProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) { WNDPROC pfnOrigProc = (WNDPROC)GetProp(hWnd, PROP_ORIGINAL_PROC); switch(Message) { case WM_DESTROY: { SetWindowLong(hWnd, GWLP_WNDPROC, (LONG)pfnOrigProc); RemoveProp(hWnd, PROP_ORIGINAL_PROC); HFONT hOrigFont = (HFONT)GetProp(hWnd, PROP_ORIGINAL_FONT); SendMessage(hWnd, WM_SETFONT, (WPARAM)hOrigFont, 0); RemoveProp(hWnd, PROP_ORIGINAL_FONT); HFONT hFont = (HFONT)GetProp(hWnd, PROP_UNDERLINE_FONT); DeleteObject(hFont); RemoveProp(hWnd, PROP_UNDERLINE_FONT); RemoveProp(hWnd, PROP_STATIC_HYPERLINK); } break; case WM_MOUSEMOVE: { if(GetCapture() != hWnd) { HFONT hFont = (HFONT)GetProp(hWnd, PROP_UNDERLINE_FONT); SendMessage(hWnd, WM_SETFONT, (WPARAM)hFont, FALSE); InvalidateRect(hWnd, NULL, FALSE); SetCapture(hWnd); } else { RECT rect; GetWindowRect(hWnd, &rect); POINT pt = {LOWORD(lParam), HIWORD(lParam)}; ClientToScreen(hWnd, &pt); if(!PtInRect(&rect, pt)) { HFONT hFont = (HFONT)GetProp(hWnd, PROP_ORIGINAL_FONT); SendMessage(hWnd, WM_SETFONT, (WPARAM)hFont, FALSE); InvalidateRect(hWnd, NULL, FALSE); ReleaseCapture(); } } } break; case WM_SETCURSOR: { // Since IDC_HAND is not available on all operating systems, // we will load the arrow cursor if IDC_HAND is not present. HCURSOR hCursor = LoadCursor(NULL, MAKEINTRESOURCE(IDC_HAND)); if(NULL == hCursor) hCursor = LoadCursor(NULL, MAKEINTRESOURCE(IDC_ARROW)); SetCursor(hCursor); return TRUE; } } return CallWindowProc(pfnOrigProc, hWnd, Message, wParam, lParam); } //---------------------------------------------------------------------------------------------------------------------- void CDialogUtils::SetFont(HWND &hDlg, LOGFONT &lf, HFONT &hFont, HDC &hDC, int nIDDlgItem, const TCHAR *cchFontName, int nPoint, bool isBold) { hDC = GetDC(NULL); lf.lfHeight = MulDiv(nPoint, GetDeviceCaps(hDC, LOGPIXELSY), 72); lf.lfWeight = (isBold) ? FW_BOLD : FW_NORMAL; ReleaseDC(NULL, hDC); lstrcpy(lf.lfFaceName, cchFontName); hFont = CreateFontIndirect (&lf); SendDlgItemMessage(hDlg, nIDDlgItem, WM_SETFONT, (WPARAM)hFont, 0); } BOOL CDialogUtils::ConvertStaticToHyperlink(HWND hWndCtl) { // Subclass the parent so we can color the controls as we desire. HWND hWndParent = GetParent(hWndCtl); if(NULL != hWndParent) { WNDPROC pfnOrigProc = (WNDPROC)GetWindowLong(hWndParent, GWLP_WNDPROC); if(pfnOrigProc != _HyperlinkParentProc) { SetProp(hWndParent, PROP_ORIGINAL_PROC, (HANDLE)pfnOrigProc); SetWindowLong(hWndParent, GWLP_WNDPROC, (LONG)(WNDPROC)_HyperlinkParentProc); } } // Make sure the control will send notifications. DWORD dwStyle = GetWindowLong(hWndCtl, GWL_STYLE); SetWindowLong(hWndCtl, GWL_STYLE, dwStyle | SS_NOTIFY); // Subclass the existing control. WNDPROC pfnOrigProc = (WNDPROC)GetWindowLong(hWndCtl, GWLP_WNDPROC); SetProp(hWndCtl, PROP_ORIGINAL_PROC, (HANDLE)pfnOrigProc); SetWindowLong(hWndCtl, GWLP_WNDPROC, (LONG)(WNDPROC)_HyperlinkProc); // Create an updated font by adding an underline. HFONT hOrigFont = (HFONT)SendMessage(hWndCtl, WM_GETFONT, 0, 0); SetProp(hWndCtl, PROP_ORIGINAL_FONT, (HANDLE)hOrigFont); LOGFONT lf; GetObject(hOrigFont, sizeof(lf), &lf); lf.lfUnderline = TRUE; //lf.lfWeight = FW_BOLD; HFONT hFont = CreateFontIndirect(&lf); SetProp(hWndCtl, PROP_UNDERLINE_FONT, (HANDLE)hFont); // Set a flag on the control so we know what color it should be. SetProp(hWndCtl, PROP_STATIC_HYPERLINK, (HANDLE)1); return TRUE; } BOOL CDialogUtils::ConvertStaticToHyperlink(HWND hWndParent, UINT uiCtlId) { return ConvertStaticToHyperlink(GetDlgItem(hWndParent, uiCtlId)); } void CDialogUtils::ToClipboard(HWND hWnd, const string &s) { OpenClipboard(hWnd); EmptyClipboard(); HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, s.size() + 1); if(!hg) { CloseClipboard(); return; } memcpy(GlobalLock(hg), s.c_str(), s.size()+1); GlobalUnlock(hg); SetClipboardData(CF_TEXT, hg); CloseClipboard(); GlobalFree(hg); }
#pragma once #ifndef AUSTRIA_HPP #define AUSTRIA_HPP #include "Country.hpp" /************************************************************************* * class Austria * This is a derived class from Country. *************************************************************************/ class Austria : public Country { private: bool ticketFound; bool opera; bool stephansDom; bool moveOn; public: Austria(); ~Austria(); virtual void explore(Player *p); char menu1(); char menu2(); virtual void hostel(Player *p); }; #endif
#ifndef _PATCH_H_ #define _PATCH_H_ #include "Mesh.h" class Patch { public: Patch() : mesh(patch_vertices, patch_faces, new_vertex_boundary_markers, new_part_of_original_stroke, new_mapped_indices, new_sharp_edge, -1) { parent_vertices = Eigen::VectorXi(); parent_faces = Eigen::VectorXi(); new_vertex_boundary_markers = Eigen::VectorXi(); new_part_of_original_stroke = Eigen::VectorXi(); new_mapped_indices = Eigen::VectorXi(); patch_vertex_is_init = Eigen::VectorXi(); patch_edge_indices = Eigen::VectorXi(); patch_edge_is_init = Eigen::VectorXi(); new_sharp_edge = Eigen::VectorXi(); patch_vertices = Eigen::MatrixXd(); patch_faces = Eigen::MatrixXi(); mesh_to_patch_indices = Eigen::VectorXi(); ; }; // ~Patch(); //Patch& operator=(Patch other); static std::vector<Patch*> init_patches(Mesh& h); static void propagate_patch(Patch* patch, int face, Eigen::VectorXi& faces, std::vector<Patch*> &face_patch_map, Eigen::VectorXi& sharp_edge); void update_parent_vertex_positions(Eigen::MatrixXd& base_V); void update_patch_vertex_positions(Eigen::MatrixXd& base_V); void update_patch_boundary_markers(Eigen::VectorXi& base_boundary_markers); Mesh get_mesh() { return mesh; }; Mesh mesh; private: void create_mesh_structure(Mesh& m, Eigen::VectorXi& faces); void get_patch_edge(int edge, Eigen::VectorXi & patch_edge_is_init, Eigen::VectorXi & patch_vertex_is_init, int face, Eigen::MatrixXd & patch_vertices, Eigen::VectorXi & sharp_edge, Eigen::VectorXi & new_sharp_edge, Eigen::MatrixXd & V_orig, Eigen::VectorXi & boundary_markers_orig, Eigen::VectorXi & part_of_original_orig, Eigen::VectorXi & new_mapped_indices_orig, Eigen::VectorXi & mesh_to_patch_indices); void get_patch_vertex(int v_idx, int face, Eigen::MatrixXd & patch_vertices, Eigen::VectorXi & patch_vertex_is_init, Eigen::MatrixXd & V_orig, Eigen::VectorXi & boundary_markers_orig, Eigen::VectorXi & part_of_original_orig, Eigen::VectorXi & new_mapped_indices_orig, Eigen::VectorXi & mesh_to_patch_indices); Eigen::VectorXi parent_vertices, parent_faces, new_vertex_boundary_markers, new_part_of_original_stroke, new_mapped_indices; Eigen::MatrixXd patch_vertices; //Will form mesh.V Eigen::VectorXi patch_vertex_is_init; Eigen::MatrixXi patch_faces; //Will form mesh.f Eigen::VectorXi patch_edge_indices; Eigen::VectorXi patch_edge_is_init; Eigen::VectorXi new_sharp_edge; //Will form mesh.sharp_edge Eigen::VectorXi mesh_to_patch_indices; }; #endif
// // EPITECH PROJECT, 2018 // nanotekspice // File description: // simulate chipsets // #include <iostream> #include <stdio.h> #include <stdlib.h> #include <fstream> #include <vector> #include "../include/Parser.hpp" #include "../include/Link.hpp" #include "../include/ErrorManage.hpp" Parser::Parser(std::string path) : _path(path) { this->_state = 0; this->_my_comps = Components(); this->_file.open(this->_path.c_str()); if (!this->_file.is_open()) exit(84); while (std::getline(this->_file, this->_str)) { if (find_match() == 1) _in.push_back(_str); else if (find_match() == 2) _out.push_back(_str); } _file.close(); this->clean_tab(); this->make_pair_vector(); this->check_names_in_vector(); this->find_links(); this->check_links(); } Parser::~Parser() { _file.close(); } void Parser::set_state() { this->_state = this->_state + 1; if (this->_state >= 2) this->_state = 2; } int Parser::get_state() { return (this->_state); } void Parser::show_vector() { unsigned long i = 0; std::cout << "Voici le vecteur in:" << std::endl; while (i < _in.size()) { std::cout << this->_in[i] << std::endl; i = i + 1; } i = 0; std::cout << "\nVoici le vecteur out:" << std::endl; while (i < _out.size()) { std::cout << this->_out[i] << std::endl; i = i + 1; } } void Parser::show_pair() { unsigned long i = 0; while (i < _comps.size()) { std::cout << this->_comps[i].first << ": " << this->_comps[i].second << std::endl; i = i + 1; } } int Parser::find_match() { if (_str.find(".chipsets") != std::string::npos) return (0); if (_str.find("input") != std::string::npos) return (1); if (_str.find("output") != std::string::npos) return (2); return (-1); } void Parser::clean_tab() { unsigned long i = 0; while (i < _in.size()) { _in[i].erase(_in[i].begin(), _in[i].begin() + 6); i = i + 1; } i = 0; while (i < _out.size()) { _out[i].erase(_out[i].begin(), _out[i].begin() + 7); i = i + 1; } } std::vector<std::pair<std::string, std::string> > Parser::get_comps() { return _comps; } std::vector<Link> Parser::getLinks() { return _my_links; } void Parser::make_pair_vector() { unsigned long i = 0; while (i < this->_in.size()) { this->_comps.push_back(std::make_pair("input", this->_in[i])); i = i + 1; } i = 0; while (i < this->_out.size()) { this->_comps.push_back(std::make_pair("output", this->_out[i])); i = i + 1; } this->_file.close(); this->_file.open(this->_path.c_str()); while (std::getline(this->_file, this->_str)) if (this->_my_comps.find_in_component_tab(this->_str) != -1) this->_comps.push_back(std::make_pair(this->_str.substr(0, 4), this->_str.substr(5, this->_str.size()))); } void Parser::check_names_in_vector() { int i = 0; int j = 0; while (i < this->_comps.size()) { j = i + 1; while (j < this->_comps.size()) { if (this->_comps[i].second == this->_comps[j].second ||this->_comps[i].second.find("input") != std::string::npos || this->_comps[i].second.find("output") != std::string::npos || this->_comps[i].second.find(".chipsets") != std::string::npos || this->_comps[i].second.find(".link") != std::string::npos) exit(84); j = j + 1; } i = i + 1; } } void Parser::find_links() { int i = 0; this->_file.close(); this->_file.open(this->_path.c_str()); if (!this->_file.is_open()) exit(84); while (std::getline(this->_file, this->_str) && this->_str.find(".links") == std::string::npos) ; while (std::getline(this->_file, this->_str)) { this->fill_map(); i = i + 1; } } void Parser::fill_map() { std::string tmp; std::string name_comp1; unsigned long pos = this->_str.find(":"); std::string name_comp = this->_str.substr(0, pos); std::string nb_pin; Link l; tmp = this->_str.substr(pos + 1, this->_str.size() - pos - 1); pos = tmp.find(" "); nb_pin = tmp.substr(0, pos); tmp = tmp.substr(pos + 1, tmp.size() - pos - 1); pos = tmp.find(":"); name_comp1 = tmp.substr(0, pos); tmp = tmp.substr(pos + 1, tmp.size() - pos - 1); l = Link(name_comp, nb_pin, name_comp1, tmp); this->_my_links.push_back(l); } void Parser::check_links() { int i = 0; int j; while (i < this->_my_links.size()) { j = 0; while (j < this->_out.size()) { if (this->_my_links[i]._comp == this->_out[j]) this->_my_links[i] = this->reverse_link(this->_my_links[i]); j = j + 1; } i = i + 1; } } Link Parser::reverse_link(Link l) { std::string tmp_name; std::string tmp_pin; tmp_name = l._comp; tmp_pin = l._pin; l._comp = l._comp1; l._pin = l._pin1; l._comp1 = tmp_name; l._pin1 = tmp_pin; return (l); } void Parser::show_killing_death_vector() { unsigned long i = 0; while (i < this->_my_links.size()) { std::cout << "Lien " << i << " : " << this->_my_links[i]._comp << "->" << this->_my_links[i]._pin << "\t\t#--------#\t" << this->_my_links[i]._comp1 << "->" << this->_my_links[i]._pin1 << std::endl; i = i + 1; } } std::vector<std::string> Parser::get_out() { return _out; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*- * * Copyright (C) 2010-2011 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #ifndef MEDIA_ELEMENT_STATE_H #define MEDIA_ELEMENT_STATE_H #ifdef MEDIA_HTML_SUPPORT /** HTMLMediaElement.preload. */ class MediaPreload { public: enum State { NONE, METADATA, INVOKED, AUTO }; MediaPreload() { /* uninitialized */ } MediaPreload(State state) : state(state) {} #ifdef _DEBUG BOOL operator==(const MediaPreload& other) const { return state == other.state; } BOOL operator!=(const MediaPreload& other) const { return state != other.state; } BOOL operator<(const MediaPreload& other) const { return state < other.state; } BOOL operator<=(const MediaPreload& other) const { return state <= other.state; } BOOL operator>(const MediaPreload& other) const { return state > other.state; } BOOL operator>=(const MediaPreload& other) const { return state >= other.state; } #else MediaPreload(unsigned char state) : state((State)state) {} operator unsigned char() const { return state; } #endif /** Convert attribute value to preload state. */ explicit MediaPreload(const uni_char* attrval) { state = MEDIA_PRELOAD_DEFAULT; if (attrval) { if (uni_stricmp(attrval, "none") == 0) state = NONE; else if (uni_stricmp(attrval, "metadata") == 0) state = METADATA; else if (uni_stricmp(attrval, "") == 0 || uni_stricmp(attrval, "auto") == 0) state = AUTO; } } /** Convert preload state to attribute value. */ const uni_char* DOMValue() const { switch(state) { case NONE: return UNI_L("none"); case METADATA: return UNI_L("metadata"); case AUTO: return UNI_L("auto"); } OP_ASSERT(!"unserializable state"); return NULL; } #ifdef _DEBUG const char* CStr() const { switch(state) { case INVOKED: return "INVOKED"; case NONE: return "NONE"; case METADATA: return "METADATA"; case AUTO: return "AUTO"; } OP_ASSERT(FALSE); return NULL; } #endif // _DEBUG private: State state; }; /** HTMLMediaElement.networkState. */ class MediaNetwork { public: enum State { EMPTY = 0, IDLE, LOADING, NO_SOURCE }; MediaNetwork(State state) : state(state) {} #ifdef _DEBUG BOOL operator==(const MediaNetwork& other) const { return state == other.state; } BOOL operator!=(const MediaNetwork& other) const { return state != other.state; } #else MediaNetwork(unsigned char state) : state((State)state) {} operator unsigned char() const { return state; } #endif unsigned short DOMValue() { return state; } #ifdef _DEBUG const char* CStr() const { switch(state) { case EMPTY: return "EMPTY"; case IDLE: return "IDLE"; case LOADING: return "LOADING"; case NO_SOURCE: return "NO_SOURCE"; } OP_ASSERT(FALSE); return NULL; } #endif // _DEBUG private: State state; }; /** HTMLMediaElement.readyState. */ class MediaReady { public: enum State { NOTHING = 0, METADATA, CURRENT_DATA, FUTURE_DATA, ENOUGH_DATA }; MediaReady(State state) : state(state) {} #ifdef _DEBUG BOOL operator==(const MediaReady& other) const { return state == other.state; } BOOL operator!=(const MediaReady& other) const { return state != other.state; } BOOL operator<(const MediaReady& other) const { return state < other.state; } BOOL operator<=(const MediaReady& other) const { return state <= other.state; } BOOL operator>(const MediaReady& other) const { return state > other.state; } BOOL operator>=(const MediaReady& other) const { return state >= other.state; } MediaReady& operator++() { OP_ASSERT(state < ENOUGH_DATA); state = (State)((int)state + 1); return *this; } MediaReady& operator--() { OP_ASSERT(state > NOTHING); state = (State)((int)state - 1); return *this; } #else MediaReady(unsigned char state) : state((State)state) {} operator unsigned char() const { return state; } #endif unsigned short DOMValue() { return state; } #ifdef _DEBUG const char* CStr() const { switch(state) { case NOTHING: return "NOTHING"; case METADATA: return "METADATA"; case CURRENT_DATA: return "CURRENT_DATA"; case FUTURE_DATA: return "FUTURE_DATA"; case ENOUGH_DATA: return "ENOUGH_DATA"; } OP_ASSERT(FALSE); return NULL; } #endif // _DEBUG private: State state; }; /** MediaState encapsulates preload, networkState and readyState. * * Not all combinations of the 3 states make sense, so what is * reported via the getters is coerced in certain ways. Some changes * to made via the setters result in no transitions, while others can * result in multiple transitions. */ class MediaState { public: MediaPreload GetPreload() const { return coerced_preload; } void SetPreload(MediaPreload state) { OP_NEW_DBG("SetPreload", "MediaState"); OP_DBG((state.CStr())); current_preload = state; } void ResetPreload() { OP_NEW_DBG("ResetPreload", "MediaState"); OP_DBG(("")); coerced_preload = current_preload = MediaPreload::NONE; } MediaNetwork GetNetwork() const { return coerced_network; } void SetNetwork(MediaNetwork state) { OP_NEW_DBG("SetNetwork", "MediaState"); OP_DBG((state.CStr())); current_network = state; } MediaReady GetReady() const { return coerced_ready; } void SetReady(MediaReady state) { OP_NEW_DBG("SetReady", "MediaState"); OP_DBG((state.CStr())); current_ready = state; } void SetPendingReady(MediaReady state) { OP_NEW_DBG("SetPendingReady", "MediaState"); OP_DBG((state.CStr())); pending_ready = state; } BOOL Transition(); MediaState() : coerced_preload(MediaPreload::NONE), coerced_network(MediaNetwork::EMPTY), coerced_ready(MediaReady::NOTHING), current_preload(MediaPreload::NONE), current_network(MediaNetwork::EMPTY), current_ready(MediaReady::NOTHING), pending_ready(MediaReady::NOTHING) {} #ifdef SELFTEST MediaState(MediaPreload coerced_preload, MediaNetwork coerced_network, MediaReady coerced_ready, MediaPreload current_preload, MediaNetwork current_network, MediaReady current_ready, MediaReady pending_ready) : coerced_preload(coerced_preload), coerced_network(coerced_network), coerced_ready(coerced_ready), current_preload(current_preload), current_network(current_network), current_ready(current_ready), pending_ready(pending_ready) {} #endif // SELFTEST #ifdef _DEBUG /** coerced state */ MediaPreload coerced_preload; MediaNetwork coerced_network; MediaReady coerced_ready; /** current state */ MediaPreload current_preload; MediaNetwork current_network; MediaReady current_ready; /** pending state */ MediaReady pending_ready; #else unsigned char coerced_preload:2; // 4 states unsigned char coerced_network:2; // 4 states unsigned char coerced_ready:3; // 5 states unsigned char current_preload:2; // 4 states unsigned char current_network:2; // 4 states unsigned char current_ready:3; // 5 states unsigned char pending_ready:3; // 5 states #endif }; #endif // MEDIA_HTML_SUPPORT #endif // MEDIA_ELEMENT_STATE_H
// // Created by drunkgranny on 11.04.16. // #include <iostream> using namespace std; void usenew() { int nights = 1001; int *pt = new int; //Выделение пространства для int *pt = 1001; //Сохранение в нем значения cout << "nights value = "; cout << nights << ": location " << &nights << endl; cout << "int "; cout << "value " << *pt << ": location = " << pt << endl; double *pd = new double; *pd = 100000001.0; cout << "double "; cout << "value = " << *pd << ": location = " << pd << endl; cout << "location of pointer pd: " << &pd << endl; cout << "-------SIZEOF-------" << endl; cout << "pt = " << sizeof(pt) << endl; cout << "*pt = " << sizeof(*pt) << endl; cout << "pd = " << sizeof(pd) << endl; cout << "*pd = " << sizeof(*pd) << endl; delete pt; delete pd; cout << "----------VALUE AFTER DELETE----------" << endl; cout << "nights value = "; cout << nights << ": location " << &nights << endl; cout << "int "; cout << "value " << *pt << ": location = " << pt << endl; cout << "double "; cout << "value = " << *pd << ": location = " << pd << endl; cout << "location of pointer pd: " << &pd << endl; cout << "-------SIZEOF AFTER DELETE-------" << endl; cout << "pt = " << sizeof(pt) << endl; cout << "*pt = " << sizeof(*pt) << endl; cout << "pd = " << sizeof(pd) << endl; cout << "*pd = " << sizeof(*pd) << endl; }
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Author: jefftk@google.com (Jeff Kaufman) /* * Usage: * server { * pagespeed on|off; * } */ #include "ngx_pagespeed.h" #include <vector> #include <set> #include "ngx_base_fetch.h" #include "ngx_caching_headers.h" #include "ngx_list_iterator.h" #include "ngx_message_handler.h" #include "ngx_request_context.h" #include "ngx_rewrite_driver_factory.h" #include "ngx_rewrite_options.h" #include "ngx_server_context.h" #include "ngx_thread_system.h" #include "apr_time.h" #include "net/instaweb/rewriter/public/rewrite_stats.h" #include "net/instaweb/apache/in_place_resource_recorder.h" #include "net/instaweb/automatic/public/proxy_fetch.h" #include "net/instaweb/http/public/content_type.h" #include "net/instaweb/http/public/request_context.h" #include "net/instaweb/rewriter/public/experiment_matcher.h" #include "net/instaweb/rewriter/public/experiment_util.h" #include "net/instaweb/rewriter/public/process_context.h" #include "net/instaweb/rewriter/public/resource_fetch.h" #include "net/instaweb/rewriter/public/rewrite_driver.h" #include "net/instaweb/rewriter/public/static_asset_manager.h" #include "net/instaweb/system/public/handlers.h" #include "net/instaweb/public/global_constants.h" #include "net/instaweb/public/version.h" #include "net/instaweb/util/public/google_message_handler.h" #include "net/instaweb/util/public/google_url.h" #include "net/instaweb/util/public/gzip_inflater.h" #include "pthread_shared_mem.h" #include "net/instaweb/util/public/null_message_handler.h" #include "net/instaweb/util/public/query_params.h" #include "net/instaweb/util/public/statistics_logger.h" #include "net/instaweb/util/public/stdio_file_system.h" #include "net/instaweb/util/public/string.h" #include "net/instaweb/util/public/string_writer.h" #include "net/instaweb/util/public/time_util.h" #include "net/instaweb/util/stack_buffer.h" #include "net/instaweb/http/public/cache_url_async_fetcher.h" #include "pagespeed/kernel/html/html_keywords.h" extern ngx_module_t ngx_pagespeed; // Hacks for debugging. #define DBG(r, args...) \ ngx_log_error(NGX_LOG_DEBUG, (r)->connection->log, 0, args) #define PDBG(ctx, args...) \ ngx_log_error(NGX_LOG_DEBUG, (ctx)->r->connection->log, 0, args) #define CDBG(cf, args...) \ ngx_conf_log_error(NGX_LOG_DEBUG, cf, 0, args) // Unused flag, see // http://lxr.evanmiller.org/http/source/http/ngx_http_request.h#L130 #define NGX_HTTP_PAGESPEED_BUFFERED 0x08 namespace ngx_psol { const char* kInternalEtagName = "@psol-etag"; StringPiece str_to_string_piece(ngx_str_t s) { return StringPiece(reinterpret_cast<char*>(s.data), s.len); } char* string_piece_to_pool_string(ngx_pool_t* pool, StringPiece sp) { // Need space for the final null. ngx_uint_t buffer_size = sp.size() + 1; char* s = static_cast<char*>(ngx_palloc(pool, buffer_size)); if (s == NULL) { LOG(ERROR) << "string_piece_to_pool_string: ngx_palloc() returned NULL"; DCHECK(false); return NULL; } sp.copy(s, buffer_size /* max to copy */); s[buffer_size-1] = '\0'; // Null terminate it. return s; } ngx_int_t string_piece_to_buffer_chain( ngx_pool_t* pool, StringPiece sp, ngx_chain_t** link_ptr, bool send_last_buf) { // Below, *link_ptr will be NULL if we're starting the chain, and the head // chain link. *link_ptr = NULL; // If non-null, the current last link in the chain. ngx_chain_t* tail_link = NULL; // How far into sp we're currently working on. ngx_uint_t offset; // Other modules seem to default to ngx_pagesize. ngx_uint_t max_buffer_size = ngx_pagesize; for (offset = 0 ; offset < sp.size() || // If we need to send the last buffer bit and there's no data, we // should send a single empty buffer. Otherwise we shouldn't // generate empty buffers. (offset == 0 && sp.size() == 0); offset += max_buffer_size) { // Prepare a new nginx buffer to put our buffered writes into. ngx_buf_t* b = static_cast<ngx_buf_t*>(ngx_calloc_buf(pool)); if (b == NULL) { return NGX_ERROR; } if (sp.size() == 0) { CHECK(offset == 0); // NOLINT b->pos = b->start = b->end = b->last = NULL; // The purpose of this buffer is just to pass along last_buf. b->sync = 1; } else { CHECK(sp.size() > offset); ngx_uint_t b_size = sp.size() - offset; if (b_size > max_buffer_size) { b_size = max_buffer_size; } b->start = b->pos = static_cast<u_char*>(ngx_palloc(pool, b_size)); if (b->pos == NULL) { return NGX_ERROR; } // Copy our writes over. We're copying from sp[offset] up to // sp[offset + b_size] into b which has size b_size. sp.copy(reinterpret_cast<char*>(b->pos), b_size, offset); b->last = b->end = b->pos + b_size; b->temporary = 1; // Identify this buffer as in-memory and mutable. } // Prepare a chain link. ngx_chain_t* cl = static_cast<ngx_chain_t*>(ngx_alloc_chain_link(pool)); if (cl == NULL) { return NGX_ERROR; } cl->buf = b; cl->next = NULL; if (*link_ptr == NULL) { // This is the first link in the returned chain. *link_ptr = cl; } else { // Link us into the chain. CHECK(tail_link != NULL); tail_link->next = cl; } tail_link = cl; } CHECK(tail_link != NULL); if (send_last_buf) { tail_link->buf->last_buf = true; } return NGX_OK; } // modify from NgxBaseFetch::CopyHeadersFromTable() namespace { template<class Headers> void copy_headers_from_table(const ngx_list_t &from, Headers* to) { // Standard nginx idiom for iterating over a list. See ngx_list.h ngx_uint_t i; const ngx_list_part_t* part = &from.part; const ngx_table_elt_t* header = static_cast<ngx_table_elt_t*>(part->elts); for (i = 0 ; /* void */; i++) { if (i >= part->nelts) { if (part->next == NULL) { break; } part = part->next; header = static_cast<ngx_table_elt_t*>(part->elts); i = 0; } // Make sure we don't copy over headers that are unset. if (header[i].hash == 0) { continue; } StringPiece key = ngx_psol::str_to_string_piece(header[i].key); StringPiece value = ngx_psol::str_to_string_piece(header[i].value); to->Add(key, value); } } } // namespace void copy_response_headers_from_ngx(const ngx_http_request_t* r, net_instaweb::ResponseHeaders* headers) { headers->set_major_version(r->http_version / 1000); headers->set_minor_version(r->http_version % 1000); copy_headers_from_table(r->headers_out.headers, headers); headers->set_status_code(r->headers_out.status); // Manually copy over the content type because it's not included in // request_->headers_out.headers. headers->Add(net_instaweb::HttpAttributes::kContentType, ngx_psol::str_to_string_piece(r->headers_out.content_type)); // TODO(oschaaf): ComputeCaching should be called in setupforhtml()? headers->ComputeCaching(); } void copy_request_headers_from_ngx(const ngx_http_request_t* r, net_instaweb::RequestHeaders* headers) { // TODO(chaizhenhua): only allow RewriteDriver::kPassThroughRequestAttributes? headers->set_major_version(r->http_version / 1000); headers->set_minor_version(r->http_version % 1000); copy_headers_from_table(r->headers_in.headers, headers); } ngx_int_t copy_response_headers_to_ngx( ngx_http_request_t* r, const net_instaweb::ResponseHeaders& pagespeed_headers, bool modify_caching_headers) { ngx_http_headers_out_t* headers_out = &r->headers_out; headers_out->status = pagespeed_headers.status_code(); ngx_int_t i; for (i = 0 ; i < pagespeed_headers.NumAttributes() ; i++) { const GoogleString& name_gs = pagespeed_headers.Name(i); const GoogleString& value_gs = pagespeed_headers.Value(i); if (!modify_caching_headers) { if ( net_instaweb::StringCaseEqual(name_gs, "Cache-Control") || net_instaweb::StringCaseEqual(name_gs, "ETag") || net_instaweb::StringCaseEqual(name_gs, "Expires") || net_instaweb::StringCaseEqual(name_gs, "Date") || net_instaweb::StringCaseEqual(name_gs, "Last-Modified")) { continue; } } ngx_str_t name, value; // To prevent the gzip module from clearing weak etags, we output them // using a different name here. The etag header filter module runs behind // the gzip compressors header filter, and will rename it to 'ETag' if (net_instaweb::StringCaseEqual(name_gs, "etag") && net_instaweb::StringCaseStartsWith(value_gs, "W/")) { name.len = strlen(kInternalEtagName); name.data = reinterpret_cast<u_char*>( const_cast<char*>(kInternalEtagName)); } else { name.len = name_gs.length(); name.data = reinterpret_cast<u_char*>(const_cast<char*>(name_gs.data())); } value.len = value_gs.length(); value.data = reinterpret_cast<u_char*>(const_cast<char*>(value_gs.data())); // TODO(jefftk): If we're setting a cache control header we'd like to // prevent any downstream code from changing it. Specifically, if we're // serving a cache-extended resource the url will change if the resource // does and so we've given it a long lifetime. If the site owner has done // something like set all css files to a 10-minute cache lifetime, that // shouldn't apply to our generated resources. See Apache code in // net/instaweb/apache/header_util:AddResponseHeadersToRequest // Make copies of name and value to put into headers_out. u_char* value_s = ngx_pstrdup(r->pool, &value); if (value_s == NULL) { return NGX_ERROR; } if (STR_EQ_LITERAL(name, "Content-Type")) { // Unlike all the other headers, content_type is just a string. headers_out->content_type.data = value_s; headers_out->content_type.len = value.len; // We should not include the charset when determining content_type_len, so // scan for the ';' that marks the start of the charset part. for (ngx_uint_t i = 0; i < value.len; i++) { if (value_s[i] == ';') break; headers_out->content_type_len = i + 1; } // In ngx_http_test_content_type() nginx will allocate and calculate // content_type_lowcase if we leave it as null. headers_out->content_type_lowcase = NULL; continue; // TODO(oschaaf): are there any other headers we should not try to // copy here? } else if (STR_EQ_LITERAL(name, "Connection")) { continue; } else if (STR_EQ_LITERAL(name, "Vary")) { continue; } else if (STR_EQ_LITERAL(name, "Keep-Alive")) { continue; } else if (STR_EQ_LITERAL(name, "Transfer-Encoding")) { continue; } else if (STR_EQ_LITERAL(name, "Server")) { continue; } u_char* name_s = ngx_pstrdup(r->pool, &name); if (name_s == NULL) { return NGX_ERROR; } ngx_table_elt_t* header = static_cast<ngx_table_elt_t*>( ngx_list_push(&headers_out->headers)); if (header == NULL) { return NGX_ERROR; } header->hash = 1; // Include this header in the output. header->key.len = name.len; header->key.data = name_s; header->value.len = value.len; header->value.data = value_s; // Populate the shortcuts to commonly used headers. if (STR_EQ_LITERAL(name, "Date")) { headers_out->date = header; } else if (STR_EQ_LITERAL(name, "Etag")) { headers_out->etag = header; } else if (STR_EQ_LITERAL(name, "Expires")) { headers_out->expires = header; } else if (STR_EQ_LITERAL(name, "Last-Modified")) { headers_out->last_modified = header; } else if (STR_EQ_LITERAL(name, "Location")) { headers_out->location = header; } else if (STR_EQ_LITERAL(name, "Server")) { headers_out->server = header; } else if (STR_EQ_LITERAL(name, "Content-Length")) { int64 len; CHECK(pagespeed_headers.FindContentLength(&len)); headers_out->content_length_n = len; headers_out->content_length = header; } } return NGX_OK; } namespace { typedef struct { net_instaweb::NgxRewriteDriverFactory* driver_factory; net_instaweb::MessageHandler* handler; } ps_main_conf_t; typedef struct { // If pagespeed is configured in some server block but not this one our // per-request code will be invoked but server context will be null. In those // cases we neet to short circuit, not changing anything. Currently our // header filter, body filter, and content handler all do this, but if anyone // adds another way for nginx to give us a request to process we need to check // there as well. net_instaweb::NgxServerContext* server_context; net_instaweb::ProxyFetchFactory* proxy_fetch_factory; // Only used while parsing config. After we merge cfg_s and cfg_m you most // likely want cfg_s->server_context->config() as options here will be NULL. net_instaweb::NgxRewriteOptions* options; net_instaweb::MessageHandler* handler; } ps_srv_conf_t; typedef struct { net_instaweb::NgxRewriteOptions* options; net_instaweb::MessageHandler* handler; } ps_loc_conf_t; void* ps_create_srv_conf(ngx_conf_t* cf); char* ps_merge_srv_conf(ngx_conf_t* cf, void* parent, void* child); char* ps_merge_loc_conf(ngx_conf_t* cf, void* parent, void* child); void ps_release_request_context(void* data); void ps_set_buffered(ngx_http_request_t* r, bool on); GoogleString ps_determine_url(ngx_http_request_t* r); ps_request_ctx_t* ps_get_request_context(ngx_http_request_t* r); void ps_initialize_server_context(ps_srv_conf_t* cfg); ngx_int_t ps_update(ps_request_ctx_t* ctx, ngx_event_t* ev); void ps_connection_read_handler(ngx_event_t* ev); ngx_int_t ps_create_connection(ps_request_ctx_t* ctx, int fd); namespace CreateRequestContext { enum Response { kError, kNotUnderstood, kStaticContent, kInvalidUrl, kPagespeedDisabled, kBeacon, kStatistics, kConsole, kMessages, kPagespeedSubrequest, kNotHeadOrGet, kErrorResponse, kResource, }; } // namespace CreateRequestContext CreateRequestContext::Response ps_create_request_context( ngx_http_request_t* r, bool is_resource_fetch); void ps_send_to_pagespeed(ngx_http_request_t* r, ps_request_ctx_t* ctx, ps_srv_conf_t* cfg_s, ngx_chain_t* in); ngx_int_t ps_init(ngx_conf_t* cf); char* ps_srv_configure(ngx_conf_t* cf, ngx_command_t* cmd, void* conf); char* ps_loc_configure(ngx_conf_t* cf, ngx_command_t* cmd, void* conf); void ps_ignore_sigpipe(); void ps_write_handler_response(const StringPiece& output, ngx_http_request_t* r, net_instaweb::ContentType content_type, const StringPiece& cache_control, net_instaweb::Timer* timer); ngx_command_t ps_commands[] = { { ngx_string("pagespeed"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_CONF_TAKE1| NGX_CONF_TAKE2|NGX_CONF_TAKE3|NGX_CONF_TAKE4|NGX_CONF_TAKE5, ps_srv_configure, NGX_HTTP_SRV_CONF_OFFSET, 0, NULL }, { ngx_string("pagespeed"), NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1| NGX_CONF_TAKE2|NGX_CONF_TAKE3|NGX_CONF_TAKE4|NGX_CONF_TAKE5, ps_loc_configure, NGX_HTTP_SRV_CONF_OFFSET, 0, NULL }, ngx_null_command }; void ps_ignore_sigpipe() { struct sigaction act; ngx_memzero(&act, sizeof(act)); act.sa_handler = SIG_IGN; sigemptyset(&act.sa_mask); act.sa_flags = 0; sigaction(SIGPIPE, &act, NULL); } namespace PsConfigure { enum OptionLevel { kServer, kLocation, }; } // namespace PsConfigure // These options are copied from mod_instaweb.cc, where // APACHE_CONFIG_OPTIONX indicates that they can not be set at the // directory/location level. They are not alphabetized on purpose, // but rather left in the same order as in mod_instaweb.cc in case // we end up needing te compare. // TODO(oschaaf): this duplication is a short term solution. const char* const global_only_options[] = { "BlockingRewriteKey", "CacheFlushFilename", "CacheFlushPollIntervalSec", "DangerPermitFetchFromUnknownHosts", "CriticalImagesBeaconEnabled", "ExperimentalFetchFromModSpdy", "FetcherTimeoutMs", "FetchHttps", "FetchWithGzip", "FileCacheCleanIntervalMs", "FileCacheInodeLimit", "FileCachePath", "FileCacheSizeKb", "ForceCaching", "ImageMaxRewritesAtOnce", "ImgMaxRewritesAtOnce", "InheritVHostConfig", "InstallCrashHandler", "LRUCacheByteLimit", "LRUCacheKbPerProcess", "MaxCacheableContentLength", "MemcachedServers", "MemcachedThreads", "MemcachedTimeoutUs", "MessageBufferSize", "NumRewriteThreads", "NumExpensiveRewriteThreads", "RateLimitBackgroundFetches", "ReportUnloadTime", "RespectXForwardedProto", "SharedMemoryLocks", "SlurpDirectory", "SlurpFlushLimit", "SlurpReadOnly", "SupportNoScriptEnabled", "StatisticsLoggingChartsCSS", "StatisticsLoggingChartsJS", "TestProxy", "TestProxySlurp", "TrackOriginalContentLength", "UsePerVHostStatistics", "XHeaderValue", "LoadFromFile", "LoadFromFileMatch", "LoadFromFileRule", "LoadFromFileRuleMatch", "UseNativeFetcher" }; bool ps_is_global_only_option(const StringPiece& option_name) { ngx_uint_t i; ngx_uint_t size = sizeof(global_only_options) / sizeof(char*); for (i = 0; i < size; i++) { if (net_instaweb::StringCaseEqual(global_only_options[i], option_name)) { return true; } } return false; } char* ps_init_dir(const StringPiece& directive, const StringPiece& path, ngx_conf_t* cf) { if (path.size() == 0 || path[0] != '/') { return string_piece_to_pool_string( cf->pool, net_instaweb::StrCat(directive, " ", path, " must start with a slash")); } net_instaweb::StdioFileSystem file_system; net_instaweb::NullMessageHandler message_handler; GoogleString gs_path; path.CopyToString(&gs_path); if (!file_system.IsDir(gs_path.c_str(), &message_handler).is_true()) { if (!file_system.RecursivelyMakeDir(path, &message_handler)) { return string_piece_to_pool_string( cf->pool, net_instaweb::StrCat( directive, " path ", path, " does not exist and could not be created.")); } // Directory created, but may not be readable by the worker processes. } if (geteuid() != 0) { return NULL; // We're not root, so we're staying whoever we are. } ngx_core_conf_t* ccf = (ngx_core_conf_t*)(ngx_get_conf(cf->cycle->conf_ctx, ngx_core_module)); CHECK(ccf != NULL); if (chown(gs_path.c_str(), ccf->user, ccf->group) != 0) { return string_piece_to_pool_string( cf->pool, net_instaweb::StrCat( directive, " ", path, " unable to set permissions")); } return NULL; } #define NGX_PAGESPEED_MAX_ARGS 10 char* ps_configure(ngx_conf_t* cf, net_instaweb::NgxRewriteOptions** options, net_instaweb::MessageHandler* handler, PsConfigure::OptionLevel option_level) { // args[0] is always "pagespeed"; ignore it. ngx_uint_t n_args = cf->args->nelts - 1; // In ps_commands we only register 'pagespeed' as taking up to // five arguments, so this check should never fire. CHECK(n_args <= NGX_PAGESPEED_MAX_ARGS); StringPiece args[NGX_PAGESPEED_MAX_ARGS]; ngx_str_t* value = static_cast<ngx_str_t*>(cf->args->elts); ngx_uint_t i; for (i = 0 ; i < n_args ; i++) { args[i] = str_to_string_piece(value[i+1]); } if (net_instaweb::StringCaseEqual("UseNativeFetcher", args[0])) { if (option_level != PsConfigure::kServer) { return const_cast<char*>( "UseNativeFetcher can only be set in the http{} block."); } } if (option_level == PsConfigure::kLocation && n_args > 1) { if (ps_is_global_only_option(args[0])) { return string_piece_to_pool_string(cf->pool, net_instaweb::StrCat( "\"", args[0], "\" cannot be set at location scope")); } } // Some options require the worker process to be able to read and write to // a specific directory. Generally the master process is root while the // worker is nobody, so we need to change permissions and create the directory // if necessary. if (n_args == 2 && (net_instaweb::StringCaseEqual("LogDir", args[0]) || net_instaweb::StringCaseEqual("FileCachePath", args[0]))) { char* error_message = ps_init_dir(args[0], args[1], cf); if (error_message != NULL) { return error_message; } // The directory has been prepared, but we haven't actually parsed the // directive yet. That happens below in ParseAndSetOptions(). } ps_main_conf_t* cfg_m = static_cast<ps_main_conf_t*>( ngx_http_cycle_get_module_main_conf(cf->cycle, ngx_pagespeed)); if (*options == NULL) { *options = new net_instaweb::NgxRewriteOptions( cfg_m->driver_factory->thread_system()); } const char* status = (*options)->ParseAndSetOptions( args, n_args, cf->pool, handler, cfg_m->driver_factory); // nginx expects us to return a string literal but doesn't mark it const. return const_cast<char*>(status); } char* ps_srv_configure(ngx_conf_t* cf, ngx_command_t* cmd, void* conf) { ps_srv_conf_t* cfg_s = static_cast<ps_srv_conf_t*>( ngx_http_conf_get_module_srv_conf(cf, ngx_pagespeed)); return ps_configure(cf, &cfg_s->options, cfg_s->handler, PsConfigure::kServer); } char* ps_loc_configure(ngx_conf_t* cf, ngx_command_t* cmd, void* conf) { ps_loc_conf_t* cfg_l = static_cast<ps_loc_conf_t*>( ngx_http_conf_get_module_loc_conf(cf, ngx_pagespeed)); return ps_configure(cf, &cfg_l->options, cfg_l->handler, PsConfigure::kLocation); } void ps_cleanup_loc_conf(void* data) { ps_loc_conf_t* cfg_l = static_cast<ps_loc_conf_t*>(data); delete cfg_l->handler; cfg_l->handler = NULL; delete cfg_l->options; cfg_l->options = NULL; } bool factory_deleted = false; void ps_cleanup_srv_conf(void* data) { ps_srv_conf_t* cfg_s = static_cast<ps_srv_conf_t*>(data); // destroy the factory on the first call, causing all worker threads // to be shut down when we destroy any proxy_fetch_factories. This // will prevent any queued callbacks to destroyed proxy fetch factories // from being executed if (!factory_deleted && cfg_s->server_context != NULL) { delete cfg_s->server_context->factory(); factory_deleted = true; } if (cfg_s->proxy_fetch_factory != NULL) { delete cfg_s->proxy_fetch_factory; cfg_s->proxy_fetch_factory = NULL; } delete cfg_s->handler; cfg_s->handler = NULL; delete cfg_s->options; cfg_s->options = NULL; } void ps_cleanup_main_conf(void* data) { ps_main_conf_t* cfg_m = static_cast<ps_main_conf_t*>(data); delete cfg_m->handler; cfg_m->handler = NULL; net_instaweb::NgxRewriteDriverFactory::Terminate(); net_instaweb::NgxRewriteOptions::Terminate(); // reset the factory deleted flag, so we will clean up properly next time, // in case of a configuration reload. // TODO(oschaaf): get rid of the factory_deleted flag factory_deleted = false; } template <typename ConfT> ConfT* ps_create_conf(ngx_conf_t* cf) { ConfT* cfg = static_cast<ConfT*>(ngx_pcalloc(cf->pool, sizeof(ConfT))); if (cfg == NULL) { return NULL; } cfg->handler = new net_instaweb::GoogleMessageHandler(); return cfg; } void ps_set_conf_cleanup_handler( ngx_conf_t* cf, void (func)(void*), void* data) { // NOLINT ngx_pool_cleanup_t* cleanup_m = ngx_pool_cleanup_add(cf->pool, 0); if (cleanup_m == NULL) { ngx_conf_log_error( NGX_LOG_ERR, cf, 0, "failed to register a cleanup handler"); } else { cleanup_m->handler = func; cleanup_m->data = data; } } void* ps_create_main_conf(ngx_conf_t* cf) { ps_main_conf_t* cfg_m = ps_create_conf<ps_main_conf_t>(cf); if (cfg_m == NULL) { return NGX_CONF_ERROR; } CHECK(!factory_deleted); net_instaweb::NgxRewriteOptions::Initialize(); net_instaweb::NgxRewriteDriverFactory::Initialize(); cfg_m->driver_factory = new net_instaweb::NgxRewriteDriverFactory( new net_instaweb::NgxThreadSystem()); ps_set_conf_cleanup_handler(cf, ps_cleanup_main_conf, cfg_m); return cfg_m; } void* ps_create_srv_conf(ngx_conf_t* cf) { ps_srv_conf_t* cfg_s = ps_create_conf<ps_srv_conf_t>(cf); if (cfg_s == NULL) { return NGX_CONF_ERROR; } ps_set_conf_cleanup_handler(cf, ps_cleanup_srv_conf, cfg_s); return cfg_s; } void* ps_create_loc_conf(ngx_conf_t* cf) { ps_loc_conf_t* cfg_l = ps_create_conf<ps_loc_conf_t>(cf); if (cfg_l == NULL) { return NGX_CONF_ERROR; } ps_set_conf_cleanup_handler(cf, ps_cleanup_loc_conf, cfg_l); return cfg_l; } // nginx has hierarchical configuration. It maintains configurations at many // levels. At various points it needs to merge configurations from different // levels, and then it calls this. First it creates the configuration at the // new level, parsing any pagespeed directives, then it merges in the // configuration from the level above. This function should merge the parent // configuration into the child. It's more complex than options->Merge() both // because of the cases where the parent or child didn't have any pagespeed // directives and because merging is order-dependent in the opposite way we'd // like. void ps_merge_options(net_instaweb::NgxRewriteOptions* parent_options, net_instaweb::NgxRewriteOptions** child_options) { if (parent_options == NULL) { // Nothing to do. } else if (*child_options == NULL) { *child_options = parent_options->Clone(); } else { // Both non-null. // Unfortunately, merging configuration options is order dependent. We'd // like to just do (*child_options)->Merge(*parent_options) // but then if we had: // pagespeed RewriteLevel PassThrough // server { // pagespeed RewriteLevel CoreFilters // } // it would always be stuck on PassThrough. net_instaweb::NgxRewriteOptions* child_specific_options = *child_options; *child_options = parent_options->Clone(); (*child_options)->Merge(*child_specific_options); delete child_specific_options; } } // Called exactly once per server block to merge the main configuration with the // configuration for this server. char* ps_merge_srv_conf(ngx_conf_t* cf, void* parent, void* child) { ps_srv_conf_t* parent_cfg_s = static_cast<ps_srv_conf_t*>(parent); ps_srv_conf_t* cfg_s = static_cast<ps_srv_conf_t*>(child); ps_merge_options(parent_cfg_s->options, &cfg_s->options); if (cfg_s->options == NULL) { return NGX_CONF_OK; // No pagespeed options; don't do anything. } ps_main_conf_t* cfg_m = static_cast<ps_main_conf_t*>( ngx_http_conf_get_module_main_conf(cf, ngx_pagespeed)); cfg_m->driver_factory->set_main_conf(parent_cfg_s->options); cfg_s->server_context = cfg_m->driver_factory->MakeNgxServerContext(); // The server context sets some options when we call global_options(). So // let it do that, then merge in options we got from the config file. // Once we do that we're done with cfg_s->options. cfg_s->server_context->global_options()->Merge(*cfg_s->options); delete cfg_s->options; cfg_s->options = NULL; if (cfg_s->server_context->global_options()->enabled()) { // Validate FileCachePath net_instaweb::GoogleMessageHandler handler; const char* file_cache_path = cfg_s->server_context->config()->file_cache_path().c_str(); if (file_cache_path[0] == '\0') { return const_cast<char*>("FileCachePath must be set"); } else if (!cfg_m->driver_factory->file_system()->IsDir( file_cache_path, &handler).is_true()) { return const_cast<char*>( "FileCachePath must be an nginx-writeable directory"); } } return NGX_CONF_OK; } char* ps_merge_loc_conf(ngx_conf_t* cf, void* parent, void* child) { ps_loc_conf_t* parent_cfg_l = static_cast<ps_loc_conf_t*>(parent); // The variant of the pagespeed directive that is acceptable in location // blocks is only acceptable in location blocks, so we should never be merging // in options from a server or main block. CHECK(parent_cfg_l->options == NULL); ps_loc_conf_t* cfg_l = static_cast<ps_loc_conf_t*>(child); if (cfg_l->options == NULL) { // No directory specific options. return NGX_CONF_OK; } ps_srv_conf_t* cfg_s = static_cast<ps_srv_conf_t*>( ngx_http_conf_get_module_srv_conf(cf, ngx_pagespeed)); if (cfg_s->server_context == NULL) { // Pagespeed options cannot be defined only in location blocks. There must // be at least a single "pagespeed off" in the main block or a server // block. return NGX_CONF_OK; } // If we get here we have parent options ("global options") from cfg_s, child // options ("directory specific options") from cfg_l, and no options from // parent_cfg_l. Rebase the directory specific options on the global options. ps_merge_options(cfg_s->server_context->config(), &cfg_l->options); return NGX_CONF_OK; } // _ef_ is a shorthand for ETag Filter ngx_http_output_header_filter_pt ngx_http_ef_next_header_filter; // Tell nginx whether we have network activity we're waiting for so that it sets // a write handler. See src/http/ngx_http_request.c:2083. void ps_set_buffered(ngx_http_request_t* r, bool on) { if (on) { r->buffered |= NGX_HTTP_PAGESPEED_BUFFERED; } else { r->buffered &= ~NGX_HTTP_PAGESPEED_BUFFERED; } } bool ps_is_https(ngx_http_request_t* r) { // Based on ngx_http_variable_scheme. #if (NGX_HTTP_SSL) return r->connection->ssl; #endif return false; } int ps_determine_port(ngx_http_request_t* r) { // Return -1 if the port isn't specified, the port number otherwise. // // If a Host header was provided, get the host from that. Otherwise fall back // to the local port of the incoming connection. int port = -1; ngx_table_elt_t* host = r->headers_in.host; if (host != NULL) { // Host headers can look like: // // www.example.com // normal // www.example.com:8080 // port specified // 127.0.0.1 // IPv4 // 127.0.0.1:8080 // IPv4 with port // [::1] // IPv6 // [::1]:8080 // IPv6 with port // // The IPv6 ones are the annoying ones, but the square brackets allow us to // disambiguate. To find the port number, we can say: // // 1) Take the text after the final colon. // 2) If all of those characters are digits, that's your port number // // In the case of a plain IPv6 address with no port number, the text after // the final colon will include a ']', so we'll stop processing. StringPiece host_str = str_to_string_piece(host->value); size_t colon_index = host_str.rfind(":"); if (colon_index == host_str.npos) { return -1; } // Strip everything up to and including the final colon. host_str.remove_prefix(colon_index + 1); bool ok = StringToInt(host_str, &port); if (!ok) { // Might be malformed port, or just IPv6 with no port specified. return -1; } return port; } // Based on ngx_http_variable_server_port. #if (NGX_HAVE_INET6) if (r->connection->local_sockaddr->sa_family == AF_INET6) { port = ntohs(reinterpret_cast<struct sockaddr_in6*>( r->connection->local_sockaddr)->sin6_port); } #endif if (port == -1 /* still need port */) { port = ntohs(reinterpret_cast<struct sockaddr_in*>( r->connection->local_sockaddr)->sin_port); } return port; } GoogleString ps_determine_url(ngx_http_request_t* r) { int port = ps_determine_port(r); GoogleString port_string; if ((ps_is_https(r) && (port == 443 || port == -1)) || (!ps_is_https(r) && (port == 80 || port == -1))) { // No port specifier needed for requests on default ports. port_string = ""; } else { port_string = net_instaweb::StrCat( ":", net_instaweb::IntegerToString(port)); } StringPiece host = str_to_string_piece(r->headers_in.server); if (host.size() == 0) { // If host is unspecified, perhaps because of a pure HTTP 1.0 "GET /path", // fall back to server IP address. Based on ngx_http_variable_server_addr. ngx_str_t s; u_char addr[NGX_SOCKADDR_STRLEN]; s.len = NGX_SOCKADDR_STRLEN; s.data = addr; ngx_int_t rc = ngx_connection_local_sockaddr(r->connection, &s, 0); if (rc != NGX_OK) { s.len = 0; } host = str_to_string_piece(s); } return net_instaweb::StrCat( ps_is_https(r) ? "https://" : "http://", host, port_string, str_to_string_piece(r->unparsed_uri)); } // Get the context for this request. ps_create_request_context // should already have been called to create it. ps_request_ctx_t* ps_get_request_context(ngx_http_request_t* r) { return static_cast<ps_request_ctx_t*>( ngx_http_get_module_ctx(r, ngx_pagespeed)); } void ps_release_base_fetch(ps_request_ctx_t* ctx); // we are still at pagespeed phase ngx_int_t ps_decline_request(ngx_http_request_t* r) { ps_request_ctx_t* ctx = ps_get_request_context(r); CHECK(ctx != NULL); // re init ctx ctx->fetch_done = false; ctx->write_pending = false; ps_release_base_fetch(ctx); ps_set_buffered(r, false); r->count++; r->phase_handler++; r->write_event_handler = ngx_http_core_run_phases; ngx_http_core_run_phases(r); ngx_http_run_posted_requests(r->connection); return NGX_DONE; } ngx_int_t ps_async_wait_response(ngx_http_request_t* r) { ps_request_ctx_t* ctx = ps_get_request_context(r); CHECK(ctx != NULL); r->count++; r->write_event_handler = ngx_http_request_empty_handler; ps_set_buffered(r, true); // We don't need to add a timer here, as it will be set by nginx. return NGX_DONE; } // TODO(chaizhenhua): use anonymous namespace or move to another file namespace base_fetch { ngx_http_output_header_filter_pt ngx_http_next_header_filter; ngx_http_output_body_filter_pt ngx_http_next_body_filter; ngx_int_t ps_base_fetch_filter(ngx_http_request_t* r, ngx_chain_t* in) { ps_request_ctx_t* ctx = ps_get_request_context(r); if (ctx == NULL || ctx->base_fetch == NULL) { return ngx_http_next_body_filter(r, in); } ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "http pagespeed write filter \"%V\"", &r->uri); // send response body if (in || ctx->write_pending) { ngx_int_t rc = ngx_http_next_body_filter(r, in); ctx->write_pending = (rc == NGX_AGAIN); if (rc == NGX_OK && !ctx->fetch_done) { return NGX_AGAIN; } return rc; } return ctx->fetch_done ? NGX_OK : NGX_AGAIN; } ngx_int_t ps_base_fetch_handler(ngx_http_request_t* r) { ps_request_ctx_t* ctx = ps_get_request_context(r); ngx_int_t rc; ngx_chain_t* cl = NULL; ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "ps fetch handler: %V", &r->uri); if (!r->header_sent) { if (!ctx->modify_caching_headers) { ngx_table_elt_t* header; net_instaweb::NgxListIterator it(&(r->headers_out.headers.part)); while ((header = it.Next()) != NULL) { // We need to remember a few headers when ModifyCachingHeaders is off, // so we can send them unmodified in copy_response_headers_to_ngx(). // This just sets the hash to 0 for all other headers. That way, we // avoid some relatively complicated code to reconstruct these headers. if (!(STR_CASE_EQ_LITERAL(header->key, "Cache-Control") || STR_CASE_EQ_LITERAL(header->key, "Etag") || STR_CASE_EQ_LITERAL(header->key, "Date") || STR_CASE_EQ_LITERAL(header->key, "Last-Modified") || STR_CASE_EQ_LITERAL(header->key, "Expires"))) { header->hash = 0; } } } else { ngx_http_clean_header(r); } // collect response headers from pagespeed rc = ctx->base_fetch->CollectHeaders(&r->headers_out); if (rc == NGX_ERROR) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } // send response headers rc = ngx_http_next_header_filter(r); // standard nginx send header check see ngx_http_send_response if (rc == NGX_ERROR || rc > NGX_OK) { return ngx_http_filter_finalize_request(r, NULL, rc); } // for in_place_check_header_filter if (rc < NGX_OK && rc != NGX_AGAIN) { CHECK(rc == NGX_DONE); return rc; } ctx->write_pending = (rc == NGX_AGAIN); if (r->header_only) { ctx->fetch_done = true; return rc; } ps_set_buffered(r, true); } // collect response body from pagespeed // Pass the optimized content along to later body filters. // From Weibin: This function should be called mutiple times. Store the // whole file in one chain buffers is too aggressive. It could consume // too much memory in busy servers. rc = ctx->base_fetch->CollectAccumulatedWrites(&cl); PDBG(ctx, "CollectAccumulatedWrites, %d", rc); if (rc == NGX_ERROR) { ps_set_buffered(r, false); return NGX_HTTP_INTERNAL_SERVER_ERROR; } if (rc == NGX_AGAIN && cl == NULL) { // there is no body buffer to send now. return NGX_AGAIN; } if (rc == NGX_OK) { ps_set_buffered(r, false); ctx->fetch_done = true; } return ps_base_fetch_filter(r, cl); } void ps_base_fetch_filter_init() { ngx_http_next_header_filter = ngx_http_top_header_filter; ngx_http_next_body_filter = ngx_http_top_body_filter; ngx_http_top_body_filter = ps_base_fetch_filter; } } // namespace base_fetch using base_fetch::ps_base_fetch_filter_init; using base_fetch::ps_base_fetch_handler; void ps_connection_read_handler(ngx_event_t* ev) { CHECK(ev != NULL); ngx_connection_t* c = static_cast<ngx_connection_t*>(ev->data); CHECK(c != NULL); int rc; // request has been finalized, do nothing just clear the pipe if (c->error) { do { char chr[256]; rc = read(c->fd, chr, 256); } while (rc > 0 || (rc == -1 && errno == EINTR)); // Retry on EINTR. if (rc == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) { return; } // write peer close or error occur ngx_close_connection(c); return; } ps_request_ctx_t* ctx = static_cast<ps_request_ctx_t*>(c->data); CHECK(ctx != NULL); ngx_http_request_t* r = ctx->r; CHECK(r != NULL); // clear the pipe do { char chr[256]; rc = read(c->fd, chr, 256); } while (rc > 0 || (rc == -1 && errno == EINTR)); // Retry on EINTR. if (rc == -1 && errno != EAGAIN && errno != EWOULDBLOCK) { ctx->pagespeed_connection = NULL; ngx_close_connection(c); return ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR); } // AGAIN or rc == 0 if (rc == 0) { // Close the pipe here to avoid SIGPIPE // Done will be check in RequestCollection. ctx->pagespeed_connection = NULL; ngx_close_connection(c); } if (ctx->fetch_done) { return; } ngx_http_finalize_request(r, ps_base_fetch_handler(r)); } ngx_int_t ps_create_connection(ps_request_ctx_t* ctx, int pipe_fd) { ngx_connection_t* c = ngx_get_connection(pipe_fd, ctx->r->connection->log); if (c == NULL) { return NGX_ERROR; } c->recv = ngx_recv; c->send = ngx_send; c->recv_chain = ngx_recv_chain; c->send_chain = ngx_send_chain; c->log_error = ctx->r->connection->log_error; c->read->log = c->log; c->write->log = c->log; ctx->pagespeed_connection = c; // Tell nginx to monitor this pipe and call us back when there's data. c->data = ctx; c->read->handler = ps_connection_read_handler; ngx_add_event(c->read, NGX_READ_EVENT, 0); return NGX_OK; } // Populate cfg_* with configuration information for this // request. Thin wrappers around ngx_http_get_module_*_conf and cast. ps_main_conf_t* ps_get_main_config(ngx_http_request_t* r) { return static_cast<ps_main_conf_t*>( ngx_http_get_module_main_conf(r, ngx_pagespeed)); } ps_srv_conf_t* ps_get_srv_config(ngx_http_request_t* r) { return static_cast<ps_srv_conf_t*>( ngx_http_get_module_srv_conf(r, ngx_pagespeed)); } ps_loc_conf_t* ps_get_loc_config(ngx_http_request_t* r) { return static_cast<ps_loc_conf_t*>( ngx_http_get_module_loc_conf(r, ngx_pagespeed)); } // Wrapper around GetQueryOptions() net_instaweb::RewriteOptions* ps_determine_request_options( ngx_http_request_t* r, net_instaweb::RequestHeaders* request_headers, net_instaweb::ResponseHeaders* response_headers, ps_srv_conf_t* cfg_s, net_instaweb::GoogleUrl* url) { // Stripping ModPagespeed query params before the property cache lookup to // make cache key consistent for both lookup and storing in cache. // // Sets option from request headers and url. net_instaweb::ServerContext::OptionsBoolPair query_options_success = cfg_s->server_context->GetQueryOptions(url, request_headers, response_headers); bool get_query_options_success = query_options_success.second; if (!get_query_options_success) { // Failed to parse query params or request headers. Treat this as if there // were no query params given. ngx_log_error(NGX_LOG_INFO, r->connection->log, 0, "ps_create_request_context: " "parsing headers or query params failed."); return NULL; } // Will be NULL if there aren't any options set with query params or in // headers. return query_options_success.first; } // Check whether this visitor is already in an experiment. If they're not, // classify them into one by setting a cookie. Then set options appropriately // for their experiment. // // See InstawebContext::SetExperimentStateAndCookie() bool ps_set_experiment_state_and_cookie(ngx_http_request_t* r, net_instaweb::RequestHeaders* request_headers, net_instaweb::RewriteOptions* options, const StringPiece& host) { CHECK(options->running_experiment()); ps_srv_conf_t* cfg_s = ps_get_srv_config(r); bool need_cookie = cfg_s->server_context->experiment_matcher()-> ClassifyIntoExperiment(*request_headers, options); if (need_cookie && host.length() > 0) { int64 time_now_us = apr_time_now(); int64 expiration_time_ms = (time_now_us/1000 + options->experiment_cookie_duration_ms()); // TODO(jefftk): refactor SetExperimentCookie to expose the value we want to // set on the cookie. int state = options->experiment_id(); GoogleString expires; net_instaweb::ConvertTimeToString(expiration_time_ms, &expires); GoogleString value = StringPrintf( "%s=%s; Expires=%s; Domain=.%s; Path=/", net_instaweb::experiment::kExperimentCookie, net_instaweb::experiment::ExperimentStateToCookieString(state).c_str(), expires.c_str(), host.as_string().c_str()); // Set the PagespeedExperiment cookie. ngx_table_elt_t* cookie = static_cast<ngx_table_elt_t*>( ngx_list_push(&r->headers_out.headers)); if (cookie == NULL) { return false; } cookie->hash = 1; // Include this header in the response. ngx_str_set(&cookie->key, "Set-Cookie"); // It's not safe to use value.c_str here because cookie header only keeps a // pointer to the string data. cookie->value.data = reinterpret_cast<u_char*>( string_piece_to_pool_string(r->pool, value)); cookie->value.len = value.size(); } return true; } // There are many sources of options: // - the request (query parameters and headers) // - location block // - global server options // - experiment framework // Consider them all, returning appropriate options for this request, of which // the caller takes ownership. If the only applicable options are global, // set options to NULL so we can use server_context->global_options(). bool ps_determine_options(ngx_http_request_t* r, net_instaweb::RequestHeaders* request_headers, net_instaweb::ResponseHeaders* response_headers, net_instaweb::RewriteOptions** options, net_instaweb::GoogleUrl* url) { ps_srv_conf_t* cfg_s = ps_get_srv_config(r); ps_loc_conf_t* cfg_l = ps_get_loc_config(r); // Global options for this server. Never null. net_instaweb::RewriteOptions* global_options = cfg_s->server_context->global_options(); // Directory-specific options, usually null. They've already been rebased off // of the global options as part of the configuration process. net_instaweb::RewriteOptions* directory_options = cfg_l->options; // Request-specific options, nearly always null. If set they need to be // rebased on the directory options or the global options. net_instaweb::RewriteOptions* request_options = ps_determine_request_options(r, request_headers, response_headers, cfg_s, url); // Because the caller takes memory ownership of any options we return, the // only situation in which we can avoid allocating a new RewriteOptions is if // the global options are ok as are. if (directory_options == NULL && request_options == NULL && !global_options->running_experiment()) { return true; } // Start with directory options if we have them, otherwise request options. if (directory_options != NULL) { *options = directory_options->Clone(); } else { *options = global_options->Clone(); } // Modify our options in response to request options or experiment settings, // if we need to. If there are request options then ignore the experiment // because we don't want experiments to be contaminated with unexpected // settings. if (request_options != NULL) { (*options)->Merge(*request_options); delete request_options; } else if ((*options)->running_experiment()) { bool ok = ps_set_experiment_state_and_cookie( r, request_headers, *options, url->Host()); if (!ok) { if (*options != NULL) { delete *options; *options = NULL; } return false; } } return true; } // Fix URL based on X-Forwarded-Proto. // http://code.google.com/p/modpagespeed/issues/detail?id=546 For example, if // Apache gives us the URL "http://www.example.com/" and there is a header: // "X-Forwarded-Proto: https", then we update this base URL to // "https://www.example.com/". This only ever changes the protocol of the url. // // Returns true if it modified url, false otherwise. bool ps_apply_x_forwarded_proto(ngx_http_request_t* r, GoogleString* url) { // First check for an X-Forwarded-Proto header. const ngx_str_t* x_forwarded_proto_header = NULL; ngx_table_elt_t* header; net_instaweb::NgxListIterator it(&(r->headers_in.headers.part)); while ((header = it.Next()) != NULL) { if (STR_CASE_EQ_LITERAL(header->key, "X-Forwarded-Proto")) { x_forwarded_proto_header = &header->value; break; } } if (x_forwarded_proto_header == NULL) { return false; // No X-Forwarded-Proto header found. } StringPiece x_forwarded_proto = str_to_string_piece(*x_forwarded_proto_header); if (!STR_CASE_EQ_LITERAL(*x_forwarded_proto_header, "http") && !STR_CASE_EQ_LITERAL(*x_forwarded_proto_header, "https")) { LOG(WARNING) << "Unsupported X-Forwarded-Proto: " << x_forwarded_proto << " for URL " << url << " protocol not changed."; return false; } StringPiece url_sp(*url); StringPiece::size_type colon_pos = url_sp.find(":"); if (colon_pos == StringPiece::npos) { return false; // URL appears to have no protocol; give up. } // Replace URL protocol with that specified in X-Forwarded-Proto. *url = net_instaweb::StrCat(x_forwarded_proto, url_sp.substr(colon_pos)); return true; } bool is_pagespeed_subrequest(ngx_http_request_t* r) { ngx_table_elt_t* user_agent_header = r->headers_in.user_agent; if (user_agent_header == NULL) { return false; } StringPiece user_agent = str_to_string_piece(user_agent_header->value); return (user_agent.find(kModPagespeedSubrequestUserAgent) != user_agent.npos); } // TODO(jud): Reuse the version in proxy_interface.cc. bool UrlMightHavePropertyCacheEntry(const net_instaweb::GoogleUrl& url) { const net_instaweb::ContentType* type = net_instaweb::NameExtensionToContentType(url.LeafSansQuery()); if (type == NULL) { return true; // http://www.example.com/ -- no extension; could be HTML. } // Use a complete switch-statement rather than type()->IsHtmlLike() // so that every time we add a new content-type we make an explicit // decision about whether it should induce a pcache read. // // TODO(jmarantz): currently this returns false for ".txt". Thus we will // do no optimizations relying on property-cache on HTML files ending with // ".txt". We should determine whether this is the right thing or not. switch (type->type()) { case net_instaweb::ContentType::kHtml: case net_instaweb::ContentType::kXhtml: case net_instaweb::ContentType::kCeHtml: return true; case net_instaweb::ContentType::kJavascript: case net_instaweb::ContentType::kCss: case net_instaweb::ContentType::kText: case net_instaweb::ContentType::kXml: case net_instaweb::ContentType::kPng: case net_instaweb::ContentType::kGif: case net_instaweb::ContentType::kJpeg: case net_instaweb::ContentType::kSwf: case net_instaweb::ContentType::kWebp: case net_instaweb::ContentType::kIco: case net_instaweb::ContentType::kPdf: case net_instaweb::ContentType::kOther: case net_instaweb::ContentType::kJson: case net_instaweb::ContentType::kVideo: case net_instaweb::ContentType::kOctetStream: return false; } LOG(DFATAL) << "URL " << url.Spec() << ": unexpected type:" << type->type() << "; " << type->mime_type() << "; " << type->file_extension(); return false; } // TODO(jud): Reuse ProxyInterface::InitiatePropertyCacheLookup. net_instaweb::ProxyFetchPropertyCallbackCollector* ps_initiate_property_cache_lookup( net_instaweb::ServerContext* server_context, bool is_resource_fetch, const net_instaweb::GoogleUrl& request_url, net_instaweb::RewriteOptions* options, net_instaweb::AsyncFetch* async_fetch, bool* added_page_property_callback) { net_instaweb::RequestContextPtr request_ctx = async_fetch->request_context(); StringPiece user_agent = async_fetch->request_headers()->Lookup1( net_instaweb::HttpAttributes::kUserAgent); net_instaweb::UserAgentMatcher::DeviceType device_type = server_context->user_agent_matcher()->GetDeviceTypeForUA(user_agent); scoped_ptr<net_instaweb::ProxyFetchPropertyCallbackCollector> callback_collector(new net_instaweb::ProxyFetchPropertyCallbackCollector( server_context, request_url.Spec(), request_ctx, options, device_type)); bool added_callback = false; net_instaweb::PropertyPageStarVector property_callbacks; net_instaweb::ProxyFetchPropertyCallback* property_callback = NULL; net_instaweb::ProxyFetchPropertyCallback* fallback_property_callback = NULL; net_instaweb::PropertyCache* page_property_cache = server_context->page_property_cache(); if (!is_resource_fetch && server_context->page_property_cache()->enabled() && UrlMightHavePropertyCacheEntry(request_url) && async_fetch->request_headers()->method() == net_instaweb::RequestHeaders::kGet) { if (options != NULL) { server_context->ComputeSignature(options); } net_instaweb::AbstractMutex* mutex = server_context->thread_system()->NewMutex(); const StringPiece& device_type_suffix = net_instaweb::UserAgentMatcher::DeviceTypeSuffix(device_type); GoogleString page_key = server_context->GetPagePropertyCacheKey( request_url.Spec(), options, device_type_suffix); property_callback = new net_instaweb::ProxyFetchPropertyCallback( net_instaweb::ProxyFetchPropertyCallback::kPropertyCachePage, page_property_cache, page_key, device_type, callback_collector.get(), mutex); callback_collector->AddCallback(property_callback); added_callback = true; if (added_page_property_callback != NULL) { *added_page_property_callback = true; } // Trigger property cache lookup for the requests which contains query param // as cache key without query params. The result of this lookup will be used // if actual property page does not contains property value. GoogleString fallback_page_key; if (options != NULL && options->use_fallback_property_cache_values() && request_url.has_query() && request_url.PathAndLeaf() != "/" && !request_url.PathAndLeaf().empty()) { // Don't bother looking up fallback properties for the root, "/", since // there is nothing to fall back to. fallback_page_key = server_context->GetFallbackPagePropertyCacheKey( request_url, options, device_type_suffix); } if (!fallback_page_key.empty()) { fallback_property_callback = new net_instaweb::ProxyFetchPropertyCallback( net_instaweb::ProxyFetchPropertyCallback::kPropertyCacheFallbackPage, page_property_cache, fallback_page_key, device_type, callback_collector.get(), server_context->thread_system()->NewMutex()); callback_collector->AddCallback(fallback_property_callback); } } // All callbacks need to be registered before Reads to avoid race. if (property_callback != NULL) { page_property_cache->Read(property_callback); } if (fallback_property_callback != NULL) { page_property_cache->Read(fallback_property_callback); } if (!added_callback) { callback_collector.reset(NULL); } return callback_collector.release(); } // TODO(chaizhenhua): merge into NgxBaseFetch::Release() void ps_release_base_fetch(ps_request_ctx_t* ctx) { // In the normal flow BaseFetch doesn't delete itself in HandleDone() because // we still need to receive notification via pipe and call // CollectAccumulatedWrites. If there's an error and we're cleaning up early // then HandleDone() hasn't been called yet and we need the base fetch to wait // for that and then delete itself. if (ctx->base_fetch != NULL) { ctx->base_fetch->Release(); ctx->base_fetch = NULL; } if (ctx->pagespeed_connection != NULL) { // Tell pagespeed connection ctx has been released. ctx->pagespeed_connection->error = 1; ctx->pagespeed_connection = NULL; } } // TODO(chaizhenhua): merge into NgxBaseFetch ctor ngx_int_t ps_create_base_fetch(ps_request_ctx_t* ctx) { ngx_http_request_t* r = ctx->r; ps_srv_conf_t* cfg_s = ps_get_srv_config(r); int file_descriptors[2]; int rc = pipe(file_descriptors); if (rc != 0) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "pipe() failed"); return NGX_ERROR; } if (ngx_nonblocking(file_descriptors[0]) == -1) { ngx_log_error(NGX_LOG_EMERG, r->connection->log, ngx_socket_errno, ngx_nonblocking_n " pipe[0] failed"); close(file_descriptors[0]); close(file_descriptors[1]); return NGX_ERROR; } if (ngx_nonblocking(file_descriptors[1]) == -1) { ngx_log_error(NGX_LOG_EMERG, r->connection->log, ngx_socket_errno, ngx_nonblocking_n " pipe[1] failed"); close(file_descriptors[0]); close(file_descriptors[1]); return NGX_ERROR; } rc = ps_create_connection(ctx, file_descriptors[0]); if (rc != NGX_OK) { close(file_descriptors[0]); close(file_descriptors[1]); ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "ps_create_request_context: " "no pagespeed connection."); return NGX_ERROR; } // Handles its own deletion. We need to call Release() when we're done with // it, and call Done() on the associated parent (Proxy or Resource) fetch. If // we fail before creating the associated fetch then we need to call Done() on // the BaseFetch ourselves. ctx->base_fetch = new net_instaweb::NgxBaseFetch( r, file_descriptors[1], cfg_s->server_context, net_instaweb::RequestContextPtr(new net_instaweb::NgxRequestContext( cfg_s->server_context->thread_system()->NewMutex(), cfg_s->server_context->timer(), r)), ctx->modify_caching_headers); return NGX_OK; } void ps_release_request_context(void* data) { ps_request_ctx_t* ctx = static_cast<ps_request_ctx_t*>(data); // proxy_fetch deleted itself if we called Done(), but if an error happened // before then we need to tell it to delete itself. // // If this is a resource fetch then proxy_fetch was never initialized. if (ctx->proxy_fetch != NULL) { ctx->proxy_fetch->Done(false /* failure */); ctx->proxy_fetch = NULL; } if (ctx->inflater_ != NULL) { delete ctx->inflater_; ctx->inflater_ = NULL; } if (ctx->driver != NULL) { ctx->driver->Cleanup(); ctx->driver = NULL; } ps_release_base_fetch(ctx); delete ctx; } // TODO(chaizhenhua): rename to ps_request_router // Set us up for processing a request. CreateRequestContext::Response ps_create_request_context( ngx_http_request_t* r, bool is_resource_fetch) { ps_srv_conf_t* cfg_s = ps_get_srv_config(r); if (!cfg_s->server_context->global_options()->enabled()) { // Not enabled for this server block. return CreateRequestContext::kPagespeedDisabled; } if (r->err_status != 0) { return CreateRequestContext::kErrorResponse; } GoogleString url_string = ps_determine_url(r); net_instaweb::GoogleUrl url(url_string); if (!url.is_valid()) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "invalid url"); // Let nginx deal with the error however it wants; we will see a NULL ctx in // the body filter or content handler and do nothing. return CreateRequestContext::kInvalidUrl; } if (is_pagespeed_subrequest(r)) { return CreateRequestContext::kPagespeedSubrequest; } if (url.PathSansLeaf() == net_instaweb::NgxRewriteDriverFactory::kStaticAssetPrefix) { return CreateRequestContext::kStaticContent; } if (url.PathSansQuery() == "/ngx_pagespeed_statistics" || url.PathSansQuery() == "/ngx_pagespeed_global_statistics" ) { return CreateRequestContext::kStatistics; } if (url.PathSansQuery() == "/pagespeed_console") { return CreateRequestContext::kConsole; } if (url.PathSansQuery() == "/ngx_pagespeed_message") { return CreateRequestContext::kMessages; } net_instaweb::RewriteOptions* global_options = cfg_s->server_context->global_options(); const GoogleString* beacon_url; if (ps_is_https(r)) { beacon_url = &(global_options->beacon_url().https); } else { beacon_url = &(global_options->beacon_url().http); } if (url.PathSansQuery() == StringPiece(*beacon_url)) { return CreateRequestContext::kBeacon; } return CreateRequestContext::kResource; } ngx_int_t ps_resource_handler(ngx_http_request_t* r, bool html_rewrite) { if (r != r->main) { return NGX_DECLINED; } ps_srv_conf_t* cfg_s = ps_get_srv_config(r); ps_request_ctx_t* ctx = ps_get_request_context(r); CHECK(!(html_rewrite && (ctx == NULL || ctx->html_rewrite == false))); if (!html_rewrite && r->method != NGX_HTTP_GET && r->method != NGX_HTTP_HEAD) { return NGX_DECLINED; } GoogleString url_string = ps_determine_url(r); net_instaweb::GoogleUrl url(url_string); CHECK(url.is_valid()); scoped_ptr<net_instaweb::RequestHeaders> request_headers( new net_instaweb::RequestHeaders); scoped_ptr<net_instaweb::ResponseHeaders> response_headers( new net_instaweb::ResponseHeaders); copy_request_headers_from_ngx(r, request_headers.get()); copy_response_headers_from_ngx(r, response_headers.get()); net_instaweb::RewriteOptions* options = NULL; if (!ps_determine_options(r, request_headers.get(), response_headers.get(), &options, &url)) { return NGX_ERROR; } // Take the ownership of custom_options scoped_ptr<net_instaweb::RewriteOptions> custom_options(options); if (options == NULL) { options = cfg_s->server_context->global_options(); } if (!options->enabled()) { // Disabled via query params or request headers. return NGX_DECLINED; } // ps_determine_options modified url, removing any ModPagespeedFoo=Bar query // parameters. Keep url_string in sync with url. url.Spec().CopyToString(&url_string); if (options->respect_x_forwarded_proto()) { bool modified_url = ps_apply_x_forwarded_proto(r, &url_string); if (modified_url) { url.Reset(url_string); CHECK(url.is_valid()) << "The output of ps_apply_x_forwarded_proto should" << " always be a valid url because it only changes" << " the scheme between http and https."; } } if (html_rewrite) { ps_release_base_fetch(ctx); } else { // create reuqest ctx CHECK(ctx == NULL); ctx = new ps_request_ctx_t(); ctx->r = r; ctx->write_pending = false; ctx->html_rewrite = false; ctx->in_place = false; ctx->pagespeed_connection = NULL; // See build_context_for_request() in mod_instaweb.cc ctx->modify_caching_headers = options->modify_caching_headers(); // Set up a cleanup handler on the request. ngx_http_cleanup_t* cleanup = ngx_http_cleanup_add(r, 0); if (cleanup == NULL) { ps_release_request_context(ctx); return NGX_ERROR; } cleanup->handler = ps_release_request_context; cleanup->data = ctx; ngx_http_set_ctx(r, ctx, ngx_pagespeed); } if (ps_create_base_fetch(ctx)!= NGX_OK) { // Do not need to release request context. // http_pool_cleanup will call ps_release_request_context return NGX_ERROR; } ctx->base_fetch->SetRequestHeadersTakingOwnership(request_headers.release()); bool page_callback_added = false; scoped_ptr<net_instaweb::ProxyFetchPropertyCallbackCollector> property_callback(ps_initiate_property_cache_lookup( cfg_s->server_context, !html_rewrite, url, options, ctx->base_fetch, &page_callback_added)); if (!html_rewrite && cfg_s->server_context->IsPagespeedResource(url)) { // TODO(jefftk): Set using_spdy appropriately. See // ProxyInterface::ProxyRequestCallback net_instaweb::ResourceFetch::Start( url, custom_options.release() /* null if there aren't custom options */, false /* using_spdy */, cfg_s->server_context, ctx->base_fetch); return ps_async_wait_response(r); } if (html_rewrite) { // Do not store driver in request_context, it's not safe. net_instaweb::RewriteDriver* driver; // If we don't have custom options we can use NewRewriteDriver which reuses // rewrite drivers and so is faster because there's no wait to construct // them. Otherwise we have to build a new one every time. if (custom_options.get() == NULL) { driver = cfg_s->server_context->NewRewriteDriver( ctx->base_fetch->request_context()); } else { // NewCustomRewriteDriver takes ownership of custom_options. driver = cfg_s->server_context->NewCustomRewriteDriver( custom_options.release(), ctx->base_fetch->request_context()); } StringPiece user_agent = ctx->base_fetch->request_headers()->Lookup1( net_instaweb::HttpAttributes::kUserAgent); if (!user_agent.empty()) { driver->SetUserAgent(user_agent); } driver->SetRequestHeaders(*ctx->base_fetch->request_headers()); // TODO(jefftk): FlushEarlyFlow would go here. // Will call StartParse etc. The rewrite driver will take care of deleting // itself if necessary. ctx->proxy_fetch = cfg_s->proxy_fetch_factory->CreateNewProxyFetch( url_string, ctx->base_fetch, driver, property_callback.release(), NULL /* original_content_fetch */); return NGX_OK; } if (options->in_place_rewriting_enabled() && options->enabled() && options->IsAllowed(url.Spec())) { // Do not store driver in request_context, it's not safe. net_instaweb::RewriteDriver* driver; if (custom_options.get() == NULL) { driver = cfg_s->server_context->NewRewriteDriver( ctx->base_fetch->request_context()); } else { // NewCustomRewriteDriver takes ownership of custom_options. driver = cfg_s->server_context->NewCustomRewriteDriver( custom_options.release(), ctx->base_fetch->request_context()); } StringPiece user_agent = ctx->base_fetch->request_headers()->Lookup1( net_instaweb::HttpAttributes::kUserAgent); if (!user_agent.empty()) { driver->SetUserAgent(user_agent); } driver->SetRequestHeaders(*ctx->base_fetch->request_headers()); ctx->driver = driver; cfg_s->server_context->message_handler()->Message(net_instaweb::kInfo, "Trying to serve rewritten resource in-place: %s", url_string.c_str()); ctx->in_place = true; ctx->base_fetch->set_handle_error(false); ctx->driver->FetchInPlaceResource( url, false /* proxy_mode */, ctx->base_fetch); return ps_async_wait_response(r); } // NOTE: We are using the below debug message as is for some of our system // tests. So, be careful about test breakages caused by changing or // removing this line. DBG(r, "Passing on content handling for non-pagespeed resource '%s'", url_string.c_str()); ctx->base_fetch->Done(false); ps_release_base_fetch(ctx); // set html_rewrite flag. ctx->html_rewrite = true; return NGX_DECLINED; } // Send each buffer in the chain to the proxy_fetch for optimization. // Eventually it will make it's way, optimized, to base_fetch. void ps_send_to_pagespeed(ngx_http_request_t* r, ps_request_ctx_t* ctx, ps_srv_conf_t* cfg_s, ngx_chain_t* in) { ngx_chain_t* cur; int last_buf = 0; for (cur = in; cur != NULL; cur = cur->next) { last_buf = cur->buf->last_buf; // Buffers are not really the last buffer until they've been through // pagespeed. cur->buf->last_buf = 0; CHECK(ctx->proxy_fetch != NULL); if (ctx->inflater_ == NULL) { ctx->proxy_fetch->Write( StringPiece(reinterpret_cast<char*>(cur->buf->pos), cur->buf->last - cur->buf->pos), cfg_s->handler); } else { char buf[net_instaweb::kStackBufferSize]; ctx->inflater_->SetInput(reinterpret_cast<char*>(cur->buf->pos), cur->buf->last - cur->buf->pos); while (ctx->inflater_->HasUnconsumedInput()) { int num_inflated_bytes = ctx->inflater_->InflateBytes( buf, net_instaweb::kStackBufferSize); if (num_inflated_bytes < 0) { cfg_s->handler->Message(net_instaweb::kWarning, "Corrupted inflation"); } else if (num_inflated_bytes > 0) { ctx->proxy_fetch->Write(StringPiece(buf, num_inflated_bytes), cfg_s->handler); } } } // We're done with buffers as we pass them through, so mark them as sent as // we go. cur->buf->pos = cur->buf->last; } if (last_buf) { ctx->proxy_fetch->Done(true /* success */); ctx->proxy_fetch = NULL; // ProxyFetch deletes itself on Done(). } else { // TODO(jefftk): Decide whether Flush() is warranted here. ctx->proxy_fetch->Flush(cfg_s->handler); } } #ifndef ngx_http_clear_etag // The ngx_http_clear_etag(r) macro was added in 1.3.3. Backport it if it's not // present. #define ngx_http_clear_etag(r) \ if (r->headers_out.etag) { \ r->headers_out.etag->hash = 0; \ r->headers_out.etag = NULL; \ } #endif // Based on ngx_http_add_cache_control. ngx_int_t ps_set_cache_control(ngx_http_request_t* r, char* cache_control) { // First strip existing cache-control headers. ngx_table_elt_t* header; net_instaweb::NgxListIterator it(&(r->headers_out.headers.part)); while ((header = it.Next()) != NULL) { if (STR_CASE_EQ_LITERAL(header->key, "Cache-Control")) { // Response headers with hash of 0 are excluded from the response. header->hash = 0; } } // Now add our new cache control header. if (r->headers_out.cache_control.elts == NULL) { ngx_int_t rc = ngx_array_init(&r->headers_out.cache_control, r->pool, 1, sizeof(ngx_table_elt_t *)); if (rc != NGX_OK) { return NGX_ERROR; } } ngx_table_elt_t** cache_control_headers = static_cast<ngx_table_elt_t**>( ngx_array_push(&r->headers_out.cache_control)); if (cache_control_headers == NULL) { return NGX_ERROR; } cache_control_headers[0] = static_cast<ngx_table_elt_t*>( ngx_list_push(&r->headers_out.headers)); if (cache_control_headers[0] == NULL) { return NGX_ERROR; } cache_control_headers[0]->hash = 1; ngx_str_set(&cache_control_headers[0]->key, "Cache-Control"); cache_control_headers[0]->value.len = strlen(cache_control); cache_control_headers[0]->value.data = reinterpret_cast<u_char*>(cache_control); return NGX_OK; } void ps_strip_html_headers(ngx_http_request_t* r) { // We're modifying content, so switch to 'Transfer-Encoding: chunked' and // calculate on the fly. ngx_http_clear_content_length(r); ngx_table_elt_t* header; net_instaweb::NgxListIterator it(&(r->headers_out.headers.part)); while ((header = it.Next()) != NULL) { // We also need to strip: // Accept-Ranges // - won't work because our html changes // Vary: Accept-Encoding // - our gzip filter will add this later if (STR_CASE_EQ_LITERAL(header->key, "Accept-Ranges") || (STR_CASE_EQ_LITERAL(header->key, "Vary") && STR_CASE_EQ_LITERAL(header->value, "Accept-Encoding"))) { // Response headers with hash of 0 are excluded from the response. header->hash = 0; } } } // Returns true, if the the response headers indicate there are multiple // content encodings. bool ps_has_stacked_content_encoding(ngx_http_request_t* r) { ngx_uint_t i; ngx_list_part_t* part = &(r->headers_out.headers.part); ngx_table_elt_t* header = static_cast<ngx_table_elt_t*>(part->elts); int field_count = 0; for (i = 0 ; /* void */; i++) { if (i >= part->nelts) { if (part->next == NULL) { break; } part = part->next; header = static_cast<ngx_table_elt_t*>(part->elts); i = 0; } // Inspect Content-Encoding headers, checking all value fields // If an origin returns gzip,foo, that is what we will get here. if (STR_CASE_EQ_LITERAL(header[i].key, "Content-Encoding")) { if (header[i].value.data != NULL && header[i].value.len > 0) { char* p = reinterpret_cast<char*>(header[i].value.data); ngx_uint_t j; for (j = 0; j < header[i].value.len; j++) { if (p[j] == ',' || j == header[i].value.len - 1) { field_count++; } } if (field_count > 1) { return true; } } } } return false; } ngx_int_t ps_etag_header_filter(ngx_http_request_t* r) { u_char* etag = reinterpret_cast<u_char*>( const_cast<char*>(kInternalEtagName)); ngx_table_elt_t* header; net_instaweb::NgxListIterator it(&(r->headers_out.headers.part)); while ((header = it.Next()) != NULL) { if (header->key.len == strlen(kInternalEtagName) && !ngx_strncasecmp(header->key.data, etag, header->key.len)) { header->key.data = reinterpret_cast<u_char*>(const_cast<char*>("ETag")); header->key.len = 4; r->headers_out.etag = header; break; } } return ngx_http_ef_next_header_filter(r); } namespace html_rewrite { ngx_http_output_header_filter_pt ngx_http_next_header_filter; ngx_http_output_body_filter_pt ngx_http_next_body_filter; ngx_int_t ps_html_rewrite_header_filter(ngx_http_request_t* r) { ps_srv_conf_t* cfg_s = ps_get_srv_config(r); if (cfg_s->server_context == NULL) { // Pagespeed is on for some server block but not this one. return ngx_http_next_header_filter(r); } if (r != r->main) { // Don't handle subrequests. return ngx_http_next_header_filter(r); } // Poll for cache flush on every request (polls are rate-limited). cfg_s->server_context->FlushCacheIfNecessary(); ps_request_ctx_t* ctx = ps_get_request_context(r); if (ctx == NULL || ctx->html_rewrite == false) { return ngx_http_next_header_filter(r); } if (r->err_status != 0) { ctx->html_rewrite = false; return ngx_http_next_header_filter(r); } ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "http pagespeed html rewrite header filter \"%V\"", &r->uri); // We don't know what this request is, but we only want to send html through // to pagespeed. Check the content type header and find out. const net_instaweb::ContentType* content_type = net_instaweb::MimeTypeToContentType( str_to_string_piece(r->headers_out.content_type)); if (content_type == NULL || !content_type->IsHtmlLike()) { // Unknown or otherwise non-html content type: skip it. ctx->html_rewrite = false; return ngx_http_next_header_filter(r); } ngx_table_elt_t* header; net_instaweb::NgxListIterator it(&(r->headers_out.headers.part)); while ((header = it.Next()) != NULL) { // If there is a proxy_cache configured in front of this ngx server, // we expect it to add a X-Cache header with the value of the cache // status (one of HIT, MISS, EXPIRED). if (STR_CASE_EQ_LITERAL(header->key, "X-Cache") && STR_CASE_EQ_LITERAL(header->value, "HIT")) { // Bypass content handling by pagespeed modules if this is a cache hit. ctx->html_rewrite = false; return ngx_http_next_header_filter(r); } } ngx_int_t rc = ps_resource_handler(r, true); if (rc != NGX_OK) { ctx->html_rewrite = false; return ngx_http_next_header_filter(r); } if (r->headers_out.content_encoding && r->headers_out.content_encoding->value.len) { // headers_out.content_encoding will be set to the exact last // Content-Encoding response header value that nginx receives. To // check if there were multiple (aka stacked) encodings in the // response headers, we must iterate them all. if (!ps_has_stacked_content_encoding(r)) { StringPiece content_encoding = str_to_string_piece(r->headers_out.content_encoding->value); net_instaweb::GzipInflater::InflateType inflate_type; bool is_encoded = false; if (net_instaweb::StringCaseEqual(content_encoding, "deflate")) { is_encoded = true; inflate_type = net_instaweb::GzipInflater::kDeflate; } else if (net_instaweb::StringCaseEqual(content_encoding, "gzip")) { is_encoded = true; inflate_type = net_instaweb::GzipInflater::kGzip; } if (is_encoded) { r->headers_out.content_encoding->hash = 0; r->headers_out.content_encoding = NULL; ctx->inflater_ = new net_instaweb::GzipInflater(inflate_type); ctx->inflater_->Init(); } } } ps_strip_html_headers(r); // TODO(jefftk): is this thread safe? copy_response_headers_from_ngx(r, ctx->base_fetch->response_headers()); ps_set_buffered(r, true); r->filter_need_in_memory = 1; return NGX_AGAIN; } ngx_int_t ps_html_rewrite_body_filter(ngx_http_request_t* r, ngx_chain_t* in) { ps_srv_conf_t* cfg_s = ps_get_srv_config(r); if (cfg_s->server_context == NULL) { // Pagespeed is on for some server block but not this one. return ngx_http_next_body_filter(r, in); } if (r != r->main) { // Don't handle subrequests. return ngx_http_next_body_filter(r, in); } // Don't need to check for a cache flush; // already did in ps_html_rewrite_header_filter. ps_request_ctx_t* ctx = ps_get_request_context(r); if (ctx == NULL || ctx->html_rewrite == false) { // ctx is null iff we've decided to pass through this request unchanged. return ngx_http_next_body_filter(r, in); } // We don't want to handle requests with errors, but we should be dealing with // that in the header filter and not initializing ctx. CHECK(r->err_status == 0); // NOLINT ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "http pagespeed html rewrite body filter \"%V\"", &r->uri); if (in != NULL) { // Send all input data to the proxy fetch. ps_send_to_pagespeed(r, ctx, cfg_s, in); } return ngx_http_next_body_filter(r, NULL); } void ps_html_rewrite_filter_init() { ngx_http_next_header_filter = ngx_http_top_header_filter; ngx_http_top_header_filter = ps_html_rewrite_header_filter; ngx_http_next_body_filter = ngx_http_top_body_filter; ngx_http_top_body_filter = ps_html_rewrite_body_filter; } } // namespace html_rewrite using html_rewrite::ps_html_rewrite_filter_init; namespace in_place { ngx_http_output_header_filter_pt ngx_http_next_header_filter; ngx_http_output_body_filter_pt ngx_http_next_body_filter; ngx_int_t ps_in_place_check_header_filter(ngx_http_request_t* r) { ps_request_ctx_t* ctx = ps_get_request_context(r); if (ctx == NULL || !ctx->in_place) { return ngx_http_next_header_filter(r); } ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "ps in place check header filter: %V", &r->uri); int status_code = r->headers_out.status; bool status_ok = (status_code != 0) && (status_code < 400); ps_srv_conf_t* cfg_s = ps_get_srv_config(r); net_instaweb::NgxServerContext* server_context = cfg_s->server_context; net_instaweb::MessageHandler* message_handler = cfg_s->handler; GoogleString url = ps_determine_url(r); // continue process if (status_ok) { ctx->in_place = false; server_context->rewrite_stats()->ipro_served()->Add(1); message_handler->Message( net_instaweb::kInfo, "Serving rewritten resource in-place: %s", url.c_str()); return ngx_http_next_header_filter(r); } if (status_code == net_instaweb::CacheUrlAsyncFetcher::kNotInCacheStatus) { server_context->rewrite_stats()->ipro_not_in_cache()->Add(1); server_context->message_handler()->Message(net_instaweb::kInfo, "Could not rewrite resource in-place " "because URL is not in cache: %s", url.c_str()); scoped_ptr<net_instaweb::RequestHeaders> request_headers( new net_instaweb::RequestHeaders); copy_request_headers_from_ngx(r, request_headers.get()); // This URL was not found in cache (neither the input resource nor // a ResourceNotCacheable entry) so we need to get it into cache // (or at least a note that it cannot be cached stored there). // We do that using an Apache output filter. ctx->recorder = new net_instaweb::InPlaceResourceRecorder( url, request_headers.release(), ctx->driver->options()->respect_vary(), server_context->http_cache(), server_context->statistics(), message_handler); // set in memory flag for in place_body_filter r->filter_need_in_memory = 1; } else { server_context->rewrite_stats()->ipro_not_rewritable()->Add(1); message_handler->Message(net_instaweb::kInfo, "Could not rewrite resource in-place: %s", url.c_str()); } ctx->driver->Cleanup(); ctx->driver = NULL; // enable html_rewrite ctx->html_rewrite = true; ctx->in_place = false; return ps_decline_request(r); } ngx_int_t ps_in_place_body_filter(ngx_http_request_t* r, ngx_chain_t* in) { ps_request_ctx_t* ctx = ps_get_request_context(r); if (ctx == NULL || ctx->recorder == NULL) { return ngx_http_next_body_filter(r, in); } ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "ps in place body filter: %V", &r->uri); net_instaweb::InPlaceResourceRecorder* recorder = ctx->recorder; for (ngx_chain_t* cl = in; cl; cl = cl->next) { if (ngx_buf_size(cl->buf)) { CHECK(ngx_buf_in_memory(cl->buf)); StringPiece contents(reinterpret_cast<char *>(cl->buf->pos), ngx_buf_size(cl->buf)); recorder->Write(contents, recorder->handler()); } if (cl->buf->flush) { recorder->Flush(recorder->handler()); } if (cl->buf->last_buf) { net_instaweb::ResponseHeaders headers; // TODO(oschaaf): We don't get a Date response header here. // Currently, we invent one and set it to the current date/time. // We need to investigate why we don't receive it. headers.set_major_version(r->http_version / 1000); headers.set_minor_version(r->http_version % 1000); copy_headers_from_table(r->headers_out.headers, &headers); headers.set_status_code(r->headers_out.status); headers.Add(net_instaweb::HttpAttributes::kContentType, ngx_psol::str_to_string_piece(r->headers_out.content_type)); if (r->headers_out.location != NULL) { headers.Add(net_instaweb::HttpAttributes::kLocation, ngx_psol::str_to_string_piece( r->headers_out.location->value)); } StringPiece date = headers.Lookup1(net_instaweb::HttpAttributes::kDate); if (date.empty()) { headers.SetDate(ngx_current_msec); } headers.ComputeCaching(); ctx->recorder->DoneAndSetHeaders(&headers); ctx->recorder = NULL; break; } } return ngx_http_next_body_filter(r, in); } void ps_in_place_filter_init() { ngx_http_next_header_filter = ngx_http_top_header_filter; ngx_http_top_header_filter = ps_in_place_check_header_filter; ngx_http_next_body_filter = ngx_http_top_body_filter; ngx_http_top_body_filter = ps_in_place_body_filter; } } // namespace in_place using in_place::ps_in_place_filter_init; ngx_int_t ps_static_handler(ngx_http_request_t* r) { ps_srv_conf_t* cfg_s = ps_get_srv_config(r); StringPiece request_uri_path = str_to_string_piece(r->uri); // Strip out the common prefix url before sending to // StaticJavascriptManager. StringPiece file_name = request_uri_path.substr( strlen(net_instaweb::NgxRewriteDriverFactory::kStaticAssetPrefix)); StringPiece file_contents; StringPiece cache_header; net_instaweb::ContentType content_type; bool found = cfg_s->server_context->static_asset_manager()->GetAsset( file_name, &file_contents, &content_type, &cache_header); if (!found) { return NGX_DECLINED; } ps_write_handler_response(file_contents, r, content_type, cache_header, cfg_s->server_context->factory()->timer()); return NGX_OK; } ngx_int_t send_out_headers_and_body( ngx_http_request_t* r, const net_instaweb::ResponseHeaders& response_headers, const GoogleString& output) { ngx_int_t rc = copy_response_headers_to_ngx( r, response_headers, true /* modify caching headers */); if (rc != NGX_OK) { return NGX_ERROR; } rc = ngx_http_send_header(r); if (rc != NGX_OK) { return NGX_ERROR; } // Send the body. ngx_chain_t* out; rc = string_piece_to_buffer_chain( r->pool, output, &out, true /* send_last_buf */); if (rc == NGX_ERROR) { return NGX_ERROR; } CHECK(rc == NGX_OK); return ngx_http_output_filter(r, out); } // Write response headers and send out headers and output, including the option // for a custom Content-Type. void ps_write_handler_response(const StringPiece& output, ngx_http_request_t* r, net_instaweb::ContentType content_type, const StringPiece& cache_control, net_instaweb::Timer* timer) { net_instaweb::ResponseHeaders response_headers; response_headers.SetStatusAndReason(net_instaweb::HttpStatus::kOK); response_headers.set_major_version(1); response_headers.set_minor_version(1); response_headers.Add(net_instaweb::HttpAttributes::kContentType, content_type.mime_type()); // http://msdn.microsoft.com/en-us/library/ie/gg622941(v=vs.85).aspx // Script and styleSheet elements will reject responses with // incorrect MIME types if the server sends the response header // "X-Content-Type-Options: nosniff". This is a security feature // that helps prevent attacks based on MIME-type confusion. response_headers.Add("X-Content-Type-Options", "nosniff"); int64 now_ms = timer->NowMs(); response_headers.SetDate(now_ms); response_headers.SetLastModified(now_ms); response_headers.Add(net_instaweb::HttpAttributes::kCacheControl, cache_control); char* cache_control_s = string_piece_to_pool_string(r->pool, cache_control); if (cache_control_s != NULL) { if (net_instaweb::FindIgnoreCase(cache_control, "private") == static_cast<int>(StringPiece::npos)) { response_headers.Add(net_instaweb::HttpAttributes::kEtag, "W/\"0\""); } } send_out_headers_and_body(r, response_headers, output.as_string()); } void ps_write_handler_response(const StringPiece& output, ngx_http_request_t* r, net_instaweb::ContentType content_type, net_instaweb::Timer* timer) { ps_write_handler_response(output, r, net_instaweb::kContentTypeHtml, net_instaweb::HttpAttributes::kNoCache, timer); } void ps_write_handler_response(const StringPiece& output, ngx_http_request_t* r, net_instaweb::Timer* timer) { ps_write_handler_response(output, r, net_instaweb::kContentTypeHtml, timer); } ngx_int_t ps_console_handler( ngx_http_request_t* r, net_instaweb::NgxServerContext* server_context) { net_instaweb::NgxRewriteDriverFactory* factory = static_cast<net_instaweb::NgxRewriteDriverFactory*>( server_context->factory()); net_instaweb::MessageHandler* message_handler = factory->message_handler(); GoogleString output; net_instaweb::StringWriter writer(&output); ConsoleHandler(server_context->config(), &writer, message_handler); ps_write_handler_response(output, r, factory->timer()); return NGX_OK; } // TODO(oschaaf): port SPDY specific functionality, shmcache stats // TODO(oschaaf): refactor this with the apache code to share this code ngx_int_t ps_statistics_handler( ngx_http_request_t* r, net_instaweb::NgxServerContext* server_context) { StringPiece request_uri_path = str_to_string_piece(r->uri); bool general_stats_request = net_instaweb::StringCaseStartsWith( request_uri_path, "/ngx_pagespeed_statistics"); bool global_stats_request = net_instaweb::StringCaseStartsWith( request_uri_path, "/ngx_pagespeed_global_statistics"); net_instaweb::NgxRewriteDriverFactory* factory = static_cast<net_instaweb::NgxRewriteDriverFactory*>( server_context->factory()); net_instaweb::MessageHandler* message_handler = factory->message_handler(); int64 start_time, end_time, granularity_ms; std::set<GoogleString> var_titles; std::set<GoogleString> hist_titles; if (general_stats_request && !factory->use_per_vhost_statistics()) { global_stats_request = true; } // Choose the correct statistics. net_instaweb::Statistics* statistics = global_stats_request ? factory->statistics() : server_context->statistics(); net_instaweb::QueryParams params; StringPiece query_string = StringPiece( reinterpret_cast<char*>(r->args.data), r->args.len); params.Parse(query_string); // Parse various mode query params. bool print_normal_config = params.Has("config"); // JSON statistics handling is done only if we have a console logger. bool json = false; if (statistics->console_logger() != NULL) { // Default values for start_time, end_time, and granularity_ms in case the // query does not include these parameters. start_time = 0; end_time = server_context->timer()->NowMs(); // Granularity is the difference in ms between data points. If it is not // specified by the query, the default value is 3000 ms, the same as the // default logging granularity. granularity_ms = 3000; for (int i = 0; i < params.size(); ++i) { const GoogleString value = (params.value(i) == NULL) ? "" : *params.value(i); const char* name = params.name(i); if (strcmp(name, "json") == 0) { json = true; } else if (strcmp(name, "start_time") == 0) { net_instaweb::StringToInt64(value, &start_time); } else if (strcmp(name, "end_time") == 0) { net_instaweb::StringToInt64(value, &end_time); } else if (strcmp(name, "var_titles") == 0) { std::vector<StringPiece> variable_names; net_instaweb::SplitStringPieceToVector( value, ",", &variable_names, true); for (size_t i = 0; i < variable_names.size(); ++i) { var_titles.insert(variable_names[i].as_string()); } } else if (strcmp(name, "hist_titles") == 0) { std::vector<StringPiece> histogram_names; net_instaweb::SplitStringPieceToVector( value, ",", &histogram_names, true); for (size_t i = 0; i < histogram_names.size(); ++i) { // TODO(morlovich): Cleanup & publicize UrlToFileNameEncoder::Unescape // and use it here, instead of this GlobalReplaceSubstring hack. GoogleString name = histogram_names[i].as_string(); net_instaweb::GlobalReplaceSubstring("%20", " ", &(name)); hist_titles.insert(name); } } else if (strcmp(name, "granularity") == 0) { net_instaweb::StringToInt64(value, &granularity_ms); } } } GoogleString output; net_instaweb::StringWriter writer(&output); if (json) { statistics->console_logger()->DumpJSON(var_titles, start_time, end_time, granularity_ms, &writer, message_handler); } else { // Generate some navigational links to the right to help // our users get to other modes. writer.Write( "<div style='float:right'>View " "<a href='?config'>Configuration</a>, " "<a href='?'>Statistics</a> " "(<a href='?memcached'>with memcached Stats</a>). " "</div>", message_handler); // Only print stats or configuration, not both. if (!print_normal_config) { writer.Write(global_stats_request ? "Global Statistics" : "VHost-Specific Statistics", message_handler); // TODO(oschaaf): for when refactoring this with the apache code, // this note is a reminder that this is different in nginx: // we prepend the host identifier here if (!global_stats_request) { writer.Write( net_instaweb::StrCat("[", server_context->hostname_identifier(), "]"), message_handler); } GoogleString stats; net_instaweb::StringWriter stats_writer(&stats); statistics->Dump(&stats_writer, message_handler); net_instaweb::HtmlKeywords::WritePre(stats, &writer, message_handler); statistics->RenderHistograms(&writer, message_handler); if (params.Has("memcached")) { GoogleString memcached_stats; factory->PrintMemCacheStats(&memcached_stats); if (!memcached_stats.empty()) { net_instaweb::HtmlKeywords::WritePre( memcached_stats, &writer, message_handler); } } } if (print_normal_config) { writer.Write("Configuration:<br>", message_handler); net_instaweb::HtmlKeywords::WritePre( server_context->config()->OptionsToString(), &writer, message_handler); } } if (json) { ps_write_handler_response(output, r, net_instaweb::kContentTypeJson, factory->timer()); } else { ps_write_handler_response(output, r, factory->timer()); } return NGX_OK; } ngx_int_t ps_messages_handler( ngx_http_request_t* r, net_instaweb::NgxServerContext* server_context) { GoogleString output; net_instaweb::StringWriter writer(&output); net_instaweb::NgxRewriteDriverFactory* factory = server_context->ngx_rewrite_driver_factory(); net_instaweb::NgxMessageHandler* message_handler = factory->ngx_message_handler(); GoogleString log; net_instaweb::StringWriter log_writer(&log); if (!message_handler->Dump(&log_writer)) { writer.Write("Writing to ngx_pagespeed_message failed. \n" "Please check if it's enabled in pagespeed.conf.\n", message_handler); } else { net_instaweb::HtmlKeywords::WritePre(log, &writer, message_handler); } ps_write_handler_response(output, r, factory->timer()); return NGX_OK; } void ps_beacon_handler_helper(ngx_http_request_t* r, StringPiece beacon_data) { ngx_log_debug(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "ps_beacon_handler_helper: beacon[%d] %*s", beacon_data.size(), beacon_data.size(), beacon_data.data()); StringPiece user_agent; if (r->headers_in.user_agent != NULL) { user_agent = str_to_string_piece(r->headers_in.user_agent->value); } ps_srv_conf_t* cfg_s = ps_get_srv_config(r); CHECK(cfg_s != NULL); cfg_s->server_context->HandleBeacon( beacon_data, user_agent, net_instaweb::RequestContextPtr(new net_instaweb::NgxRequestContext( cfg_s->server_context->thread_system()->NewMutex(), cfg_s->server_context->timer(), r))); ps_set_cache_control(r, const_cast<char*>("max-age=0, no-cache")); // TODO(jefftk): figure out how to insert Content-Length:0 as a response // header so wget doesn't hang. } // Load the request body into out. ngx_http_read_client_request_body must // already have been called. Return false on failure, true on success. bool ps_request_body_to_string_piece( ngx_http_request_t* r, StringPiece* out) { if (r->request_body == NULL || r->request_body->bufs == NULL) { ngx_log_error(NGX_LOG_WARN, r->connection->log, 0, "ps_request_body_to_string_piece: " "empty request body."); return false; } if (r->request_body->temp_file) { // For now raise an error instead of figuring out how to read temporary // files. ngx_log_error(NGX_LOG_WARN, r->connection->log, 0, "ps_request_body_to_string_piece: " "request body in temporary file unsupported." "Increase client_body_buffer_size."); return false; } else if (r->request_body->bufs->next == NULL) { // There's just one buffer, so we can simply return a StringPiece pointing // to this buffer. ngx_buf_t* buffer = r->request_body->bufs->buf; CHECK(!buffer->in_file); int len = buffer->last - buffer->pos; ngx_log_debug(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "ngx_pagespeed beacon: single buffer of %d", len); *out = StringPiece(reinterpret_cast<char*>(buffer->pos), len); return true; } else { // There are multiple buffers, so we need to allocate memory for a string to // hold the whole result. This should only happen when the POST is sent // with "Transfer-Encoding: Chunked". // First determine how much data there is. int len = 0; int buffers = 0; ngx_chain_t* chain_link; for (chain_link = r->request_body->bufs; chain_link != NULL; chain_link = chain_link->next) { len += chain_link->buf->last - chain_link->buf->pos; buffers++; } ngx_log_debug(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "ngx_pagespeed beacon: %d buffers totalling %d", len); // Allocate a string to store the combined result. u_char* s = static_cast<u_char*>(ngx_palloc(r->pool, len)); if (s == NULL) { ngx_log_error(NGX_LOG_WARN, r->connection->log, 0, "ps_request_body_to_string_piece: " "failed to allocate memory"); return false; } // Copy the data into the combined string. u_char* current_position = s; int i; for (chain_link = r->request_body->bufs, i = 0; chain_link != NULL; chain_link = chain_link->next, i++) { ngx_buf_t* buffer = chain_link->buf; CHECK(!buffer->in_file); current_position = ngx_copy(current_position, buffer->pos, buffer->last - buffer->pos); } CHECK_EQ(current_position, s + len); *out = StringPiece(reinterpret_cast<char*>(s), len); return true; } } // Parses out query params from the request. void ps_query_params_handler(ngx_http_request_t* r, StringPiece* data) { StringPiece unparsed_uri = str_to_string_piece(r->unparsed_uri); stringpiece_ssize_type question_mark_index = unparsed_uri.find("?"); if (question_mark_index == StringPiece::npos) { *data = ""; } else { *data = unparsed_uri.substr( question_mark_index+1, unparsed_uri.size() - (question_mark_index+1)); } } // Called after nginx reads the request body from the client. For another // example processing request buffers, see ngx_http_form_input_module.c void ps_beacon_body_handler(ngx_http_request_t* r) { // Even if the beacon is a POST, the originating url should be in the query // params, not the POST body. StringPiece query_param_beacon_data; ps_query_params_handler(r, &query_param_beacon_data); StringPiece request_body; bool ok = ps_request_body_to_string_piece(r, &request_body); GoogleString beacon_data = net_instaweb::StrCat( query_param_beacon_data, "&", request_body); if (ok) { ps_beacon_handler_helper(r, beacon_data.c_str()); ngx_http_finalize_request(r, NGX_HTTP_NO_CONTENT); } else { ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR); } } ngx_int_t ps_beacon_handler(ngx_http_request_t* r) { if (r->method == NGX_HTTP_POST) { // Use post body. Handler functions are called before the request body has // been read from the client, so we need to ask nginx to read it from the // client and then call us back. Control flow continues in // ps_beacon_body_handler unless there's an error reading the request body. // // See: http://forum.nginx.org/read.php?2,31312,31312 ngx_int_t rc = ngx_http_read_client_request_body(r, ps_beacon_body_handler); if (rc >= NGX_HTTP_SPECIAL_RESPONSE) { return rc; } return NGX_DONE; } else { // Use query params. StringPiece query_param_beacon_data; ps_query_params_handler(r, &query_param_beacon_data); ps_beacon_handler_helper(r, query_param_beacon_data); return NGX_HTTP_NO_CONTENT; } } // Handle requests for resources like example.css.pagespeed.ce.LyfcM6Wulf.css // and for static content like /ngx_pagespeed_static/js_defer.q1EBmcgYOC.js ngx_int_t ps_content_handler(ngx_http_request_t* r) { ps_srv_conf_t* cfg_s = ps_get_srv_config(r); if (cfg_s->server_context == NULL) { // Pagespeed is on for some server block but not this one. return NGX_DECLINED; } // Poll for cache flush on every request (polls are rate-limited). cfg_s->server_context->FlushCacheIfNecessary(); ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "http pagespeed handler \"%V\"", &r->uri); switch (ps_create_request_context( r, true /* is a resource fetch */)) { case CreateRequestContext::kError: return NGX_ERROR; case CreateRequestContext::kNotUnderstood: case CreateRequestContext::kPagespeedDisabled: case CreateRequestContext::kInvalidUrl: case CreateRequestContext::kPagespeedSubrequest: case CreateRequestContext::kNotHeadOrGet: case CreateRequestContext::kErrorResponse: return NGX_DECLINED; case CreateRequestContext::kBeacon: return ps_beacon_handler(r); case CreateRequestContext::kStaticContent: return ps_static_handler(r); case CreateRequestContext::kStatistics: return ps_statistics_handler(r, cfg_s->server_context); case CreateRequestContext::kConsole: return ps_console_handler(r, cfg_s->server_context); case CreateRequestContext::kMessages: return ps_messages_handler(r, cfg_s->server_context); case CreateRequestContext::kResource: return ps_resource_handler(r, false); } CHECK(0); return NGX_ERROR; } ngx_int_t ps_phase_handler(ngx_http_request_t* r, ngx_http_phase_handler_t* ph) { ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "pagespeed phase: %ui", r->phase_handler); r->write_event_handler = ngx_http_request_empty_handler; ngx_int_t rc = ps_content_handler(r); // Warning: this requires ps_content_handler to always return NGX_DECLINED // directly if it's not going to handle the request. It is not ok for // ps_content_handler to asynchronously determine whether to handle the // request, returning NGX_DONE here. if (rc == NGX_DECLINED) { r->write_event_handler = ngx_http_core_run_phases; r->phase_handler++; return NGX_AGAIN; } ngx_http_finalize_request(r, rc); return NGX_OK; } namespace fix_headers { ngx_http_output_header_filter_pt ngx_http_next_header_filter; ngx_int_t ps_html_rewrite_fix_headers_filter(ngx_http_request_t* r) { ps_request_ctx_t* ctx = ps_get_request_context(r); if (r != r->main || ctx == NULL || !ctx->html_rewrite || !ctx->modify_caching_headers) { return ngx_http_next_header_filter(r); } // Don't cache html. See mod_instaweb:instaweb_fix_headers_filter. net_instaweb::NgxCachingHeaders caching_headers(r); ps_set_cache_control(r, string_piece_to_pool_string( r->pool, caching_headers.GenerateDisabledCacheControl())); // Pagespeed html doesn't need etags: it should never be cached. ngx_http_clear_etag(r); // An html page may change without the underlying file changing, because of // how resources are included. Pagespeed adds cache control headers for // resources instead of using the last modified header. ngx_http_clear_last_modified(r); // Clear expires if (r->headers_out.expires) { r->headers_out.expires->hash = 0; r->headers_out.expires = NULL; } return ngx_http_next_header_filter(r); } void ps_html_rewrite_fix_headers_filter_init() { ngx_http_next_header_filter = ngx_http_top_header_filter; ngx_http_top_header_filter = ps_html_rewrite_fix_headers_filter; } } // namespace fix_headers using fix_headers::ps_html_rewrite_fix_headers_filter_init; // preaccess_handler should be at generic phase before try_files ngx_int_t ps_preaccess_handler(ngx_http_request_t* r) { ngx_http_core_main_conf_t* cmcf; ngx_http_phase_handler_t* ph; ngx_uint_t i; cmcf = static_cast<ngx_http_core_main_conf_t*>( ngx_http_get_module_main_conf(r, ngx_http_core_module)); ph = cmcf->phase_engine.handlers; i = r->phase_handler; // move handlers before try_files && content phase while (ph[i + 1].checker != ngx_http_core_try_files_phase && ph[i + 1].checker != ngx_http_core_content_phase) { ph[i] = ph[i + 1]; ph[i].next--; i++; } // insert ps phase handler ph[i].checker = ps_phase_handler; ph[i].handler = NULL; ph[i].next = i + 1; // next preaccess handler r->phase_handler--; return NGX_DECLINED; } ngx_int_t ps_etag_filter_init(ngx_conf_t* cf) { ps_main_conf_t* cfg_m = static_cast<ps_main_conf_t*>( ngx_http_conf_get_module_main_conf(cf, ngx_pagespeed)); if (cfg_m->driver_factory != NULL) { ngx_http_ef_next_header_filter = ngx_http_top_header_filter; ngx_http_top_header_filter = ps_etag_header_filter; } return NGX_OK; } ngx_int_t ps_init(ngx_conf_t* cf) { // Only put register pagespeed code to run if there was a "pagespeed" // configuration option set in the config file. With "pagespeed off" we // consider every request and choose not to do anything, while with no // "pagespeed" directives we won't have any effect after nginx is done loading // its configuration. ps_main_conf_t* cfg_m = static_cast<ps_main_conf_t*>( ngx_http_conf_get_module_main_conf(cf, ngx_pagespeed)); // The driver factory is on the main config and is non-NULL iff there is a // pagespeed configuration option in the main config or a server block. Note // that if any server block has pagespeed 'on' then our header filter, body // filter, and content handler will run in every server block. This is ok, // because they will notice that the server context is NULL and do nothing. if (cfg_m->driver_factory != NULL) { // The filter init order is important. ps_in_place_filter_init(); ps_html_rewrite_fix_headers_filter_init(); ps_base_fetch_filter_init(); ps_html_rewrite_filter_init(); ngx_http_core_main_conf_t* cmcf = static_cast<ngx_http_core_main_conf_t*>( ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module)); ngx_http_handler_pt* h = static_cast<ngx_http_handler_pt*>( ngx_array_push(&cmcf->phases[NGX_HTTP_PREACCESS_PHASE].handlers)); if (h == NULL) { return NGX_ERROR; } *h = ps_preaccess_handler; } return NGX_OK; } ngx_http_module_t ps_etag_filter_module = { NULL, // preconfiguration ps_etag_filter_init, // postconfiguration NULL, NULL, // initialize main configuration NULL, NULL, NULL, NULL }; ngx_http_module_t ps_module = { NULL, // preconfiguration ps_init, // postconfiguration ps_create_main_conf, NULL, // initialize main configuration ps_create_srv_conf, ps_merge_srv_conf, ps_create_loc_conf, ps_merge_loc_conf }; // called after configuration is complete, but before nginx starts forking ngx_int_t ps_init_module(ngx_cycle_t* cycle) { ps_main_conf_t* cfg_m = static_cast<ps_main_conf_t*>( ngx_http_cycle_get_module_main_conf(cycle, ngx_pagespeed)); ngx_http_core_main_conf_t* cmcf = static_cast<ngx_http_core_main_conf_t*>( ngx_http_cycle_get_module_main_conf(cycle, ngx_http_core_module)); ngx_http_core_srv_conf_t** cscfp = static_cast<ngx_http_core_srv_conf_t**>( cmcf->servers.elts); ngx_uint_t s; bool have_server_context = false; net_instaweb::Statistics* statistics = NULL; // Iterate over all configured server{} blocks, and find out if we have // an enabled ServerContext. for (s = 0; s < cmcf->servers.nelts; s++) { ps_srv_conf_t* cfg_s = static_cast<ps_srv_conf_t*>( cscfp[s]->ctx->srv_conf[ngx_pagespeed.ctx_index]); if (cfg_s->server_context != NULL) { have_server_context = true; net_instaweb::NgxRewriteOptions* config = cfg_s->server_context->config(); // Lazily create shared-memory statistics if enabled in any // config, even when ngx_pagespeed is totally disabled. This // allows statistics to work if ngx_pagespeed gets turned on via // .htaccess or query param. if ((statistics == NULL) && config->statistics_enabled()) { statistics = \ cfg_m->driver_factory->MakeGlobalSharedMemStatistics(*config); } // The hostname identifier is used by the shared memory statistics // to allocate a segment, and should be unique name per server GoogleString hostname_identifier = net_instaweb::StrCat( "Host[", base::IntToString(static_cast<int>(s)), "]"); cfg_s->server_context->set_hostname_identifier(hostname_identifier); // If config has statistics on and we have per-vhost statistics on // as well, then set it up. if (config->statistics_enabled() && cfg_m->driver_factory->use_per_vhost_statistics()) { cfg_s->server_context->CreateLocalStatistics(statistics); } } } if (have_server_context) { // TODO(oschaaf): this ignores sigpipe messages from memcached. // however, it would be better to not have those signals generated // in the first place, as suppressing them this way may interfere // with other modules that actually are interested in these signals ps_ignore_sigpipe(); // If no shared-mem statistics are enabled, then init using the default // NullStatistics. if (statistics == NULL) { statistics = cfg_m->driver_factory->statistics(); net_instaweb::NgxRewriteDriverFactory::InitStats(statistics); } ngx_http_core_loc_conf_t* clcf = static_cast<ngx_http_core_loc_conf_t*>( ngx_http_conf_get_module_loc_conf((*cscfp), ngx_http_core_module)); cfg_m->driver_factory->set_resolver(clcf->resolver); cfg_m->driver_factory->set_resolver_timeout(clcf->resolver_timeout); if (!cfg_m->driver_factory->CheckResolver()) { cfg_m->handler->Message( net_instaweb::kError, "UseNativeFetcher is on, please configure a resolver."); return NGX_ERROR; } cfg_m->driver_factory->RootInit(cycle->log); } else { delete cfg_m->driver_factory; cfg_m->driver_factory = NULL; } return NGX_OK; } // Called when nginx forks worker processes. No threads should be started // before this. ngx_int_t ps_init_child_process(ngx_cycle_t* cycle) { ps_main_conf_t* cfg_m = static_cast<ps_main_conf_t*>( ngx_http_cycle_get_module_main_conf(cycle, ngx_pagespeed)); if (cfg_m->driver_factory == NULL) { return NGX_OK; } // ChildInit() will initialise all ServerContexts, which we need to // create ProxyFetchFactories below cfg_m->driver_factory->ChildInit(cycle->log); ngx_http_core_main_conf_t* cmcf = static_cast<ngx_http_core_main_conf_t*>( ngx_http_cycle_get_module_main_conf(cycle, ngx_http_core_module)); ngx_http_core_srv_conf_t** cscfp = static_cast<ngx_http_core_srv_conf_t**>( cmcf->servers.elts); ngx_uint_t s; // Iterate over all configured server{} blocks, and find our context in it, // so we can create and set a ProxyFetchFactory for it. for (s = 0; s < cmcf->servers.nelts; s++) { ps_srv_conf_t* cfg_s = static_cast<ps_srv_conf_t*>( cscfp[s]->ctx->srv_conf[ngx_pagespeed.ctx_index]); // Some server{} blocks may not have a ServerContext in that case we must // not instantiate a ProxyFetchFactory. if (cfg_s->server_context != NULL) { cfg_s->proxy_fetch_factory = new net_instaweb::ProxyFetchFactory(cfg_s->server_context); ngx_http_core_loc_conf_t* clcf = static_cast<ngx_http_core_loc_conf_t*>( cscfp[s]->ctx->loc_conf[ngx_http_core_module.ctx_index]); cfg_m->driver_factory->SetServerContextMessageHandler( cfg_s->server_context, clcf->error_log); } } if (!cfg_m->driver_factory->InitNgxUrlAsyncFetcher()) { return NGX_ERROR; } cfg_m->driver_factory->StartThreads(); return NGX_OK; } } // namespace } // namespace ngx_psol ngx_module_t ngx_pagespeed_etag_filter = { NGX_MODULE_V1, &ngx_psol::ps_etag_filter_module, NULL, NGX_HTTP_MODULE, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NGX_MODULE_V1_PADDING }; ngx_module_t ngx_pagespeed = { NGX_MODULE_V1, &ngx_psol::ps_module, ngx_psol::ps_commands, NGX_HTTP_MODULE, NULL, ngx_psol::ps_init_module, ngx_psol::ps_init_child_process, NULL, NULL, NULL, NULL, NGX_MODULE_V1_PADDING };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2012 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/prefs/prefsmanager/prefsmanager.h" #include "modules/display/vis_dev.h" #include "modules/layout/cssprops.h" #include "modules/logdoc/htm_elm.h" #include "modules/logdoc/xmlenum.h" #include "modules/display/styl_man.h" #include "modules/style/css.h" #include "modules/style/css_media.h" #include "modules/style/src/css_parser.h" #include "modules/style/src/css_import_rule.h" #include "modules/doc/frm_doc.h" #include "modules/dochand/win.h" #include "modules/dochand/winman.h" #include "modules/pi/OpScreenInfo.h" #include "modules/util/gen_math.h" #include "modules/prefs/prefsmanager/collections/pc_fontcolor.h" #include "modules/windowcommander/OpWindowCommander.h" #include "modules/style/src/css_aliases.h" #ifdef SCOPE_SUPPORT # include "modules/probetools/probetimeline.h" #endif // SCOPE_SUPPORT #define CSS_MAX_ARR_SIZE 32 /** Anchors a bunch of heap arrays or strings to the stack. The anchor will take responsibility for deleting objects that are added to it. @author rune */ template<class T> class CSS_anchored_heap_arrays { private: T* m_initial_objects[CSS_MAX_ARR_SIZE]; T** m_objects; int m_objects_size; int m_count; /** Check that there's room for adding another array */ void CheckSizeL() { if (m_count + 1 == m_objects_size) { int new_size = m_objects_size * 2; T** new_array = OP_NEWA_L(T*, new_size); for (int i=0; i<m_count; i++) new_array[i] = m_objects[i]; if (m_objects != m_initial_objects) OP_DELETEA(m_objects); m_objects_size = new_size; m_objects = new_array; } } public: CSS_anchored_heap_arrays() : m_objects(m_initial_objects), m_objects_size(CSS_MAX_ARR_SIZE), m_count(0) {} /** Deletes all anchored arrays. */ ~CSS_anchored_heap_arrays() { for (int i=0; i<m_count; i++) OP_DELETEA(m_objects[i]); if (m_objects != m_initial_objects) OP_DELETEA(m_objects); } /** Add object to list of anchored objects. @param obj Heap allocated T* array. This anchor takes over the responsibility for deleting the array - even if this method should leave. @return Leaves on OOM. */ void AddArrayL(T* obj) { // Anchor the object using OpHeapArrayAnchor while doing CheckSizeL in case it leaves ANCHOR_ARRAY(T, obj); CheckSizeL(); ANCHOR_ARRAY_RELEASE(obj); // Now we're insured against OOM, so release the other anchor m_objects[m_count++] = obj; } }; /** Anchors a bunch of heap objects to the stack. The anchor will take responsibility for deleting objects that are added to it. @author lstorset */ template<class T> class CSS_anchored_heap_objects { private: T* m_initial_objects[CSS_MAX_ARR_SIZE]; T** m_objects; int m_objects_size; int m_count; /** Check that there's room for adding another object */ void CheckSizeL() { if (m_count + 1 == m_objects_size) { int new_size = m_objects_size * 2; T** new_array = OP_NEWA_L(T*, new_size); for (int i=0; i<m_count; i++) new_array[i] = m_objects[i]; if (m_objects != m_initial_objects) OP_DELETEA(m_objects); m_objects_size = new_size; m_objects = new_array; } } public: CSS_anchored_heap_objects() : m_objects(m_initial_objects), m_objects_size(CSS_MAX_ARR_SIZE), m_count(0) {} /** Deletes all anchored objects. */ ~CSS_anchored_heap_objects() { for (int i=0; i<m_count; i++) OP_DELETE(m_objects[i]); if (m_objects != m_initial_objects) OP_DELETEA(m_objects); } /** Add object to list of anchored objects. @param obj Heap allocated T* object. This anchor takes over the responsibility for deleting the object - even if this method should leave. @return Leaves on OOM. */ void AddObjectL(T* obj) { // Anchor the object using OpHeapAnchor while doing CheckSizeL in case it leaves ANCHOR_PTR(T, obj); CheckSizeL(); ANCHOR_PTR_RELEASE(obj); // Now we're insured against OOM, so release the other anchor m_objects[m_count++] = obj; } }; class CSS_TransformFunctionInfo { public: CSS_TransformFunctionInfo(CSSValue t) : type(t), n_args(1), allow_short_form(FALSE) { switch (type) { case CSS_VALUE_matrix: n_args = 6; break; case CSS_VALUE_scale: case CSS_VALUE_translate: case CSS_VALUE_skew: n_args = 2; allow_short_form = TRUE; break; } } BOOL IsValidUnit(BOOL allow_implicit_unit, short& unit) { switch (type) { case CSS_VALUE_matrix: case CSS_VALUE_scale: case CSS_VALUE_scaleX: case CSS_VALUE_scaleY: return unit == CSS_NUMBER; case CSS_VALUE_translate: case CSS_VALUE_translateX: case CSS_VALUE_translateY: if (unit == CSS_NUMBER && allow_implicit_unit) { unit = CSS_PX; return TRUE; } else return CSS_is_length_number_ext(unit) || unit == CSS_PERCENTAGE; case CSS_VALUE_skew: case CSS_VALUE_skewX: case CSS_VALUE_skewY: case CSS_VALUE_rotate: return unit == CSS_RAD; default: OP_ASSERT(!"Not reached"); return FALSE; } } int MaxArgCount() { return n_args; } BOOL ValidArgCount(int i) { return i == n_args || allow_short_form && i == 1; } private: CSSValue type; int n_args; BOOL allow_short_form; }; /** Helper class for parsing a background shorthand declaration. */ class CSS_BackgroundShorthandInfo { public: CSS_BackgroundShorthandInfo(const CSS_Parser& p, CSS_anchored_heap_arrays<uni_char>& s #ifdef CSS_GRADIENT_SUPPORT , CSS_anchored_heap_objects<CSS_Gradient>& g #endif // CSS_GRADIENT_SUPPORT ); /** Does the value array represent 'inherit'? */ BOOL IsInherit() const; /** After ExtractLayerL() has returned FALSE for the first time, this function returns whether there was any error detected during parsing. Before ExtractLayerL() has returned FALSE, this function always returns FALSE. */ BOOL IsInvalid() const { return !m_is_valid; } /** Extract next layer from the value array into separate arrays. Returns FALSE when there are no more layers to extract. */ BOOL ExtractLayerL(CSS_generic_value_list& bg_attachment_arr, CSS_generic_value_list& bg_repeat_arr, CSS_generic_value_list& bg_image_arr, CSS_generic_value_list& bg_pos_arr, CSS_generic_value_list& bg_size_arr, CSS_generic_value_list& bg_origin_arr, CSS_generic_value_list& bg_clip_arr, COLORREF& bg_color_value, BOOL& bg_color_is_keyword, CSSValue& bg_color_keyword); private: struct Layer { void Reset(); CSSValue bg_attachment; BOOL bg_attachment_set; CSSValue bg_repeat[2]; int n_bg_repeat; const uni_char* bg_image; #ifdef CSS_GRADIENT_SUPPORT CSS_Gradient* bg_gradient; #endif // CSS_GRADIENT_SUPPORT BOOL bg_image_set; BOOL bg_image_is_skin; CSS_generic_value bg_size[2]; int n_bg_size; COLORREF bg_color_value; CSSValue bg_color_keyword; BOOL bg_color_set; BOOL bg_color_is_keyword; float bg_pos[2]; CSSValueType bg_pos_type[2]; CSSValue bg_pos_ref[2]; BOOL bg_pos_set; BOOL bg_pos_has_ref_point; CSSValue bg_origin; BOOL bg_origin_and_clip_set; CSSValue bg_clip; BOOL bg_clip_set; BOOL last_layer; }; BOOL ParseLayer(Layer& layer); BOOL Invalid() { m_is_valid = FALSE; return FALSE; } const CSS_Parser& m_parser; CSS_anchored_heap_arrays<uni_char>& m_strings; #ifdef CSS_GRADIENT_SUPPORT CSS_anchored_heap_objects<CSS_Gradient>& m_gradients; #endif //CSS_GRADIENT_SUPPORT const CSS_Parser::ValueArray& m_val_array; CSS_Buffer* m_input_buffer; BOOL m_is_valid; int m_i; }; CSS_BackgroundShorthandInfo::CSS_BackgroundShorthandInfo(const CSS_Parser& p, CSS_anchored_heap_arrays<uni_char>& s #ifdef CSS_GRADIENT_SUPPORT , CSS_anchored_heap_objects<CSS_Gradient>& g #endif //CSS_GRADIENT_SUPPORT ) : m_parser(p), m_strings(s), #ifdef CSS_GRADIENT_SUPPORT m_gradients(g), #endif //CSS_GRADIENT_SUPPORT m_val_array(p.m_val_array), m_input_buffer(p.m_input_buffer), m_is_valid(TRUE), m_i(0) { } void CSS_BackgroundShorthandInfo::Layer::Reset() { bg_attachment = CSS_VALUE_scroll; bg_attachment_set = FALSE; bg_repeat[0] = CSS_VALUE_repeat; bg_repeat[1] = CSS_VALUE_repeat; n_bg_repeat = 0; bg_image = NULL; #ifdef CSS_GRADIENT_SUPPORT bg_gradient = NULL; #endif //CSS_GRADIENT_SUPPORT bg_image_set = FALSE; bg_image_is_skin = FALSE; bg_size[0].SetValueType(CSS_IDENT); bg_size[0].SetType(CSS_VALUE_auto); bg_size[1].SetValueType(CSS_IDENT); bg_size[1].SetType(CSS_VALUE_auto); n_bg_size = 0; bg_color_value = USE_DEFAULT_COLOR; bg_color_keyword = CSS_VALUE_transparent; bg_color_set = FALSE; bg_color_is_keyword = FALSE; bg_pos[0] = 0; bg_pos[1] = 0; bg_pos_type[0] = CSS_PERCENTAGE; bg_pos_type[1] = CSS_PERCENTAGE; bg_pos_set = FALSE; bg_pos_ref[0] = CSS_VALUE_left; bg_pos_ref[1] = CSS_VALUE_top; bg_pos_has_ref_point = FALSE; bg_origin = CSS_VALUE_padding_box; bg_origin_and_clip_set = FALSE; bg_clip = CSS_VALUE_border_box; bg_clip_set = FALSE; last_layer = TRUE; } BOOL CSS_BackgroundShorthandInfo::IsInherit() const { if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); return (keyword == CSS_VALUE_inherit); } else return FALSE; } BOOL CSS_BackgroundShorthandInfo::ParseLayer(CSS_BackgroundShorthandInfo::Layer& layer) { if (m_i >= m_val_array.GetCount()) return FALSE; BOOL quirks_mode = m_parser.m_hld_prof && !m_parser.m_hld_prof->IsInStrictMode(); enum { STATE_START, STATE_REPEAT, STATE_AFTER_POSITION } state = STATE_START; layer.Reset(); while (m_i < m_val_array.GetCount()) { if (m_val_array[m_i].token == CSS_IDENT) { // attachment, color, position, repeat CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[m_i].value.str.start_pos, m_val_array[m_i].value.str.str_len); if (CSS_is_bg_attachment_val(keyword)) { if (layer.bg_attachment_set) return Invalid();; layer.bg_attachment = keyword; layer.bg_attachment_set = TRUE; state = STATE_START; } else if (CSS_is_bg_repeat_val(keyword)) { if (layer.n_bg_repeat == 0) { layer.bg_repeat[layer.n_bg_repeat++] = keyword; if (keyword != CSS_VALUE_repeat_x && keyword != CSS_VALUE_repeat_y) state = STATE_REPEAT; } else if (layer.n_bg_repeat == 1 && state == STATE_REPEAT && (keyword != CSS_VALUE_repeat_x && keyword != CSS_VALUE_repeat_y)) { layer.bg_repeat[layer.n_bg_repeat++] = keyword; state = STATE_START; } else return Invalid(); } else if (CSS_is_position_val(keyword)) { if (layer.bg_pos_set) return Invalid(); CSS_Parser::DeclStatus ret = m_parser.SetPosition(m_i, layer.bg_pos, layer.bg_pos_type, TRUE, layer.bg_pos_ref, layer.bg_pos_has_ref_point); if (ret != CSS_Parser::OK) return Invalid(); else layer.bg_pos_set = TRUE; --m_i; // already incremented in SetPosition state = STATE_AFTER_POSITION; } else if (keyword >= 0 && CSS_is_color_val(keyword) || m_input_buffer->GetNamedColorIndex(m_val_array[m_i].value.str.start_pos, m_val_array[m_i].value.str.str_len) != USE_DEFAULT_COLOR) { if (layer.bg_color_set) return Invalid(); if (CSS_is_ui_color_val(keyword)) { layer.bg_color_value = keyword | CSS_COLOR_KEYWORD_TYPE_ui_color; layer.bg_color_is_keyword = TRUE; } else { layer.bg_color_value = m_input_buffer->GetNamedColorIndex(m_val_array[m_i].value.str.start_pos, m_val_array[m_i].value.str.str_len); layer.bg_color_is_keyword = TRUE; } layer.bg_color_set = TRUE; state = STATE_START; } else if (keyword == CSS_VALUE_transparent || keyword == CSS_VALUE_currentColor) { if (layer.bg_color_set) return Invalid(); layer.bg_color_keyword = keyword; layer.bg_color_set = TRUE; state = STATE_START; } else if (keyword == CSS_VALUE_none) { if (layer.bg_image_set) return Invalid(); layer.bg_image_set = TRUE; layer.bg_image = NULL; state = STATE_START; } else if (CSS_is_background_clip_or_origin_val(keyword)) { if (!layer.bg_origin_and_clip_set) { layer.bg_origin = keyword; layer.bg_clip = keyword; layer.bg_origin_and_clip_set = TRUE; } else if (!layer.bg_clip_set) { layer.bg_clip = keyword; layer.bg_clip_set = TRUE; } else return Invalid(); state = STATE_START; } else if (keyword < 0 && quirks_mode) { if (layer.bg_color_set) return Invalid(); COLORREF col = m_input_buffer->GetColor(m_val_array[m_i].value.str.start_pos, m_val_array[m_i].value.str.str_len); if (col == USE_DEFAULT_COLOR) return Invalid(); layer.bg_color_value = col; layer.bg_color_set = TRUE; state = STATE_START; } else return Invalid(); } else if (state == STATE_AFTER_POSITION && m_val_array[m_i].token == '/') { /* bg-size */ BOOL done = FALSE; OP_ASSERT(layer.n_bg_size == 0); if (++m_i >= m_val_array.GetCount()) return Invalid(); if (m_val_array[m_i].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[m_i].value.str.start_pos, m_val_array[m_i].value.str.str_len); if (keyword == CSS_VALUE_cover || keyword == CSS_VALUE_contain || keyword == CSS_VALUE_auto) { layer.bg_size[layer.n_bg_size].SetValueType(CSS_IDENT); layer.bg_size[layer.n_bg_size++].SetType(keyword); if (keyword == CSS_VALUE_cover || keyword == CSS_VALUE_contain) done = TRUE; } else return Invalid(); } else if (m_val_array[m_i].token == CSS_NUMBER || m_val_array[m_i].token == CSS_PERCENTAGE || CSS_is_length_number_ext(m_val_array[m_i].token)) { short type = m_val_array[m_i].token; if (type == CSS_NUMBER) type = CSS_PX; layer.bg_size[layer.n_bg_size].SetValueType(type); layer.bg_size[layer.n_bg_size++].SetReal(float(m_val_array[m_i].value.number.number)); } else return Invalid(); if (!done && (m_i+1) < m_val_array.GetCount()) { // Try next token m_i++; if (m_val_array[m_i].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[m_i].value.str.start_pos, m_val_array[m_i].value.str.str_len); if (keyword == CSS_VALUE_auto) { layer.bg_size[layer.n_bg_size].SetValueType(CSS_IDENT); layer.bg_size[layer.n_bg_size++].SetType(keyword); } else --m_i; } else if (m_val_array[m_i].token == CSS_NUMBER || m_val_array[m_i].token == CSS_PERCENTAGE || CSS_is_length_number_ext(m_val_array[m_i].token)) { short type = m_val_array[m_i].token; if (type == CSS_NUMBER) type = CSS_PX; layer.bg_size[layer.n_bg_size].SetValueType(type); layer.bg_size[layer.n_bg_size++].SetReal(float(m_val_array[m_i].value.number.number)); } else --m_i; } state = STATE_START; } else if (m_val_array[m_i].token == CSS_HASH) { /* bg-color */ layer.bg_color_value = m_input_buffer->GetColor(m_val_array[m_i].value.str.start_pos, m_val_array[m_i].value.str.str_len); if (layer.bg_color_set || layer.bg_color_value == USE_DEFAULT_COLOR) return Invalid(); layer.bg_color_set = TRUE; state = STATE_START; } else if (m_val_array[m_i].token == CSS_FUNCTION_RGB || m_parser.SupportsAlpha() && m_val_array[m_i].token == CSS_FUNCTION_RGBA) { /* bg-color */ layer.bg_color_value = m_val_array[m_i].value.color; layer.bg_color_set = TRUE; state = STATE_START; } else if (m_val_array[m_i].token == CSS_FUNCTION_URL) { /* bg-image */ if (layer.bg_image_set) return Invalid(); layer.bg_image = m_input_buffer->GetURLL(m_parser.m_base_url, m_val_array[m_i].value.str.start_pos, m_val_array[m_i].value.str.str_len).GetAttribute(URL::KUniName_Username_Password_NOT_FOR_UI).CStr(); layer.bg_image_set = TRUE; state = STATE_START; } #ifdef SKIN_SUPPORT else if (m_val_array[m_i].token == CSS_FUNCTION_SKIN) { if (layer.bg_image_set) return Invalid(); uni_char* skin_image = m_input_buffer->GetSkinString(m_val_array[m_i].value.str.start_pos, m_val_array[m_i].value.str.str_len); layer.bg_image = skin_image; if (!layer.bg_image) LEAVE(OpStatus::ERR_NO_MEMORY); m_strings.AddArrayL(skin_image); layer.bg_image_set = TRUE; layer.bg_image_is_skin = TRUE; state = STATE_START; } #endif // SKIN_SUPPORT #ifdef CSS_GRADIENT_SUPPORT else if (CSS_is_gradient(m_val_array[m_i].token)) { if (layer.bg_image_set) return Invalid(); CSSValueType type = (CSSValueType) m_val_array[m_i].token; CSS_Gradient* gradient = m_parser.SetGradientL(/* inout */ m_i, /* inout */ type); if (!gradient) return Invalid(); m_gradients.AddObjectL(gradient); layer.bg_gradient = gradient; layer.bg_image_set = TRUE; } #endif // CSS_GRADIENT_SUPPORT else if (CSS_is_number(m_val_array[m_i].token)) { CSS_Parser::DeclStatus ret = layer.bg_pos_set ? CSS_Parser::INVALID : m_parser.SetPosition(m_i, layer.bg_pos, layer.bg_pos_type, TRUE, layer.bg_pos_ref, layer.bg_pos_has_ref_point); if (ret == CSS_Parser::INVALID) { if (quirks_mode && !layer.bg_color_set) { COLORREF col = m_input_buffer->GetColor(m_val_array[m_i].value.number.start_pos, m_val_array[m_i].value.number.str_len); if (col == USE_DEFAULT_COLOR) return Invalid(); layer.bg_color_value = col; layer.bg_color_set = TRUE; } else return Invalid(); } else { --m_i; // already incremented in SetPosition layer.bg_pos_set = TRUE; } state = STATE_AFTER_POSITION; } else if (m_val_array[m_i].token == CSS_COMMA) { m_i++; layer.last_layer = FALSE; break; } else { return Invalid(); } m_i++; } if (layer.bg_color_set && !layer.last_layer) /* background color only allowed on the last layer */ return Invalid(); return TRUE; } BOOL CSS_BackgroundShorthandInfo::ExtractLayerL(CSS_generic_value_list& bg_attachment_arr, CSS_generic_value_list& bg_repeat_arr, CSS_generic_value_list& bg_image_arr, CSS_generic_value_list& bg_pos_arr, CSS_generic_value_list& bg_size_arr, CSS_generic_value_list& bg_origin_arr, CSS_generic_value_list& bg_clip_arr, COLORREF& bg_color_value, BOOL& bg_color_is_keyword, CSSValue& bg_color_keyword) { Layer layer; if (ParseLayer(layer)) { /* background-attachment */ bg_attachment_arr.PushIdentL(layer.bg_attachment); /* background-repeat */ bg_repeat_arr.PushIdentL(layer.bg_repeat[0]); if (layer.n_bg_repeat > 1) bg_repeat_arr.PushIdentL(layer.bg_repeat[1]); if (!layer.last_layer) bg_repeat_arr.PushValueTypeL(CSS_COMMA); /* background-image */ if (layer.bg_image) { uni_char* url_str = OP_NEWA_L(uni_char, uni_strlen(layer.bg_image)+1); m_strings.AddArrayL(url_str); uni_strcpy(url_str, layer.bg_image); bg_image_arr.PushStringL(layer.bg_image_is_skin ? CSS_FUNCTION_SKIN : CSS_FUNCTION_URL, url_str); } #ifdef CSS_GRADIENT_SUPPORT else if (layer.bg_gradient) { CSS_Gradient* gradient = layer.bg_gradient->CopyL(); m_gradients.AddObjectL(gradient); bg_image_arr.PushGradientL(gradient->GetCSSValueType(), gradient); } #endif // CSS_GRADIENT_SUPPORT else bg_image_arr.PushIdentL(CSS_VALUE_none); /* background-position */ if (layer.bg_pos_has_ref_point) bg_pos_arr.PushIdentL(layer.bg_pos_ref[0]); bg_pos_arr.PushNumberL(layer.bg_pos_type[0], layer.bg_pos[0]); if (layer.bg_pos_has_ref_point) bg_pos_arr.PushIdentL(layer.bg_pos_ref[1]); bg_pos_arr.PushNumberL(layer.bg_pos_type[1], layer.bg_pos[1]); if (!layer.last_layer) bg_pos_arr.PushValueTypeL(CSS_COMMA); /* background-size */ bg_size_arr.PushGenericValueL(layer.bg_size[0]); if (layer.n_bg_size > 1) bg_size_arr.PushGenericValueL(layer.bg_size[1]); if (!layer.last_layer) bg_size_arr.PushValueTypeL(CSS_COMMA); if (layer.bg_color_set) { if (!layer.last_layer) return Invalid(); bg_color_value = layer.bg_color_value; bg_color_is_keyword = layer.bg_color_is_keyword; bg_color_keyword = layer.bg_color_keyword; } /* background-origin */ bg_origin_arr.PushIdentL(layer.bg_origin); /* background-clip */ bg_clip_arr.PushIdentL(layer.bg_clip); return TRUE; } return FALSE; } void CSS_Parser::ValueArray::CommitToL(ValueArray& dest) { for (int i = 0; i < m_val_count; i++) dest.AddValueL(m_val_array[i]); ResetValCount(); } extern int cssparse(void* parm); CSS_Parser::CSS_Parser(CSS* css, CSS_Buffer* buf, const URL& base_url, HLDocProfile* hld_profile, unsigned start_line_number) : m_lexer(buf), m_stylesheet(css), m_input_buffer(buf), m_hld_prof(hld_profile), m_val_array(CSS_VAL_ARRAY_SIZE, m_default_val_array), m_current_props(0), m_base_url(base_url), m_allow_min(ALLOW_CHARSET), m_allow_max(ALLOW_STYLE), m_decl_type(DECL_RULESET), m_next_token(0), #ifdef MEDIA_HTML_SUPPORT m_saved_current_selector(0), m_in_cue(FALSE), #endif // MEDIA_HTML_SUPPORT m_current_selector(0), #ifdef CSS_ANIMATIONS m_current_keyframes_rule(NULL), #endif m_current_conditional_rule(0), m_current_media_object(0), m_current_media_query(0), m_replace_rule(FALSE), m_dom_rule(0), m_dom_property(-1), m_current_ns_idx(NS_IDX_ANY_NAMESPACE), m_error_occurred(CSSParseStatus::OK), m_last_decl(NULL), m_document_line(start_line_number), m_condition_list(NULL) { m_yystack[0] = m_yystack[1] = NULL; m_user = css && css->GetUserDefined(); #ifdef SCOPE_CSS_RULE_ORIGIN m_rule_line_no = 0; #endif // SCOPE_CSS_RULE_ORIGIN } CSS_Parser::~CSS_Parser() { m_selector_list.Clear(); #ifdef MEDIA_HTML_SUPPORT m_cue_selector_list.Clear(); #endif // MEDIA_HTML_SUPPORT m_simple_selector_stack.Clear(); if (m_current_props) m_current_props->Unref(); OP_DELETE(m_current_selector); OP_DELETE(m_current_media_object); OP_DELETE(m_current_media_query); if (m_yystack[0]) op_free(m_yystack[0]); if (m_yystack[1]) op_free(m_yystack[1]); OP_ASSERT(!m_condition_list); } // From yyexhaustedlab in css_grammar.cpp #define YY_OOM_VAL 2 void CSS_Parser::ParseL() { #ifdef SCOPE_PROFILER OpPropertyProbe probe; ANCHOR(OpPropertyProbe, probe); if (HLDProfile() && HLDProfile()->GetFramesDocument()->GetTimeline()) { OpProbeTimeline* t = HLDProfile()->GetFramesDocument()->GetTimeline(); const URL& url = GetBaseURL(); OpPropertyProbe::Activator<1> act(probe); ANCHOR(OpPropertyProbe::Activator<1>, act); LEAVE_IF_FATAL(act.Activate(t, PROBE_EVENT_CSS_PARSING, url.GetRep())); LEAVE_IF_FATAL(act.AddURL("url", const_cast<URL*>(&url))); } #endif // SCOPE_PROFILER int ret = cssparse(this); #ifdef CSS_ERROR_SUPPORT if (m_lexer.GetTruncationBits() != CSS_Lexer::TRUNC_NONE) EmitErrorL(UNI_L("Unexpected end of file"), OpConsoleEngine::Error); #endif // CSS_ERROR_SUPPORT if (ret == 0 && m_error_occurred == CSSParseStatus::OK) return; else if (ret == YY_OOM_VAL) LEAVE(CSSParseStatus::ERR_NO_MEMORY); else if (m_error_occurred != CSSParseStatus::OK) LEAVE(m_error_occurred); else LEAVE(CSSParseStatus::SYNTAX_ERROR); } int CSS_Parser::Lex(YYSTYPE* value) { if (m_next_token) { int ret = m_next_token; m_next_token = 0; if (ret == CSS_TOK_DOM_MEDIA_LIST || ret == CSS_TOK_DOM_MEDIUM) m_lexer.ForceInMediaRule(); return ret; } return m_lexer.Lex(value); } static short ResolveFontWeight(CSSValue keyword) { short fweight = 0; if (keyword == CSS_VALUE_normal) fweight = 4; else if (keyword == CSS_VALUE_bold) fweight = 7; else if (keyword != CSS_VALUE_bolder && keyword != CSS_VALUE_lighter && keyword != CSS_VALUE_inherit) fweight = -1; return fweight; } /** Return TRUE if the value is a valid value for the flex-direction property. */ static BOOL IsFlexDirectionValue(CSSValue value) { switch (value) { case CSS_VALUE_inherit: case CSS_VALUE_row: case CSS_VALUE_row_reverse: case CSS_VALUE_column: case CSS_VALUE_column_reverse: return TRUE; default: return FALSE; } } /** Return TRUE if the value is a valid value for the flex-wrap property. */ static BOOL IsFlexWrapValue(CSSValue value) { switch (value) { case CSS_VALUE_inherit: case CSS_VALUE_nowrap: case CSS_VALUE_wrap: case CSS_VALUE_wrap_reverse: return TRUE; default: return FALSE; } } CSS_Parser::ColorValueType CSS_Parser::SetColorL(COLORREF& color, CSSValue& keyword, uni_char*& skin_color, const PropertyValue& color_value) const { color = USE_DEFAULT_COLOR; if (color_value.token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(color_value.value.str.start_pos, color_value.value.str.str_len); if (keyword == CSS_VALUE_transparent || keyword == CSS_VALUE_inherit || keyword == CSS_VALUE_invert || keyword == CSS_VALUE_currentColor) return COLOR_KEYWORD; } #ifdef SKIN_SUPPORT if (color_value.token == CSS_FUNCTION_SKIN) { skin_color = m_input_buffer->GetSkinString(color_value.value.str.start_pos, color_value.value.str.str_len); if (skin_color) { return COLOR_SKIN; } else LEAVE(OpStatus::ERR_NO_MEMORY); } #endif // SKIN_SUPPORT // We found no special keyword and no skin color; look for a color if (color_value.token == CSS_HASH) { color = m_input_buffer->GetColor(color_value.value.str.start_pos, color_value.value.str.str_len); } else if (color_value.token == CSS_FUNCTION_RGB || SupportsAlpha() && color_value.token == CSS_FUNCTION_RGBA) { color = color_value.value.color; } else if (color_value.token == CSS_IDENT && CSS_is_ui_color_val(keyword)) { color = keyword | CSS_COLOR_KEYWORD_TYPE_ui_color; return COLOR_NAMED; } else if (color_value.token == CSS_IDENT) { color = m_input_buffer->GetNamedColorIndex(color_value.value.str.start_pos, color_value.value.str.str_len); if (color == USE_DEFAULT_COLOR) { if (m_hld_prof && !m_hld_prof->IsInStrictMode()) color = m_input_buffer->GetColor(color_value.value.str.start_pos, color_value.value.str.str_len); } else return COLOR_NAMED; } else if (CSS_is_number(color_value.token) && m_hld_prof && !m_hld_prof->IsInStrictMode()) { color = m_input_buffer->GetColor(color_value.value.number.start_pos, color_value.value.number.str_len); } if (color == USE_DEFAULT_COLOR) return COLOR_INVALID; // We found no keyword (whether a named color or a keyword); 'color' is set return COLOR_RGBA; } #ifdef CSS_GRADIENT_SUPPORT CSS_Gradient* CSS_Parser::SetGradientL(int& pos, CSSValueType& type) const { CSS_Gradient* gradient; switch (type) { case CSS_FUNCTION_LINEAR_GRADIENT: case CSS_FUNCTION_WEBKIT_LINEAR_GRADIENT: case CSS_FUNCTION_O_LINEAR_GRADIENT: case CSS_FUNCTION_REPEATING_LINEAR_GRADIENT: gradient = SetLinearGradientL(/* inout */ pos, type == CSS_FUNCTION_WEBKIT_LINEAR_GRADIENT || type == CSS_FUNCTION_O_LINEAR_GRADIENT ); break; case CSS_FUNCTION_RADIAL_GRADIENT: case CSS_FUNCTION_REPEATING_RADIAL_GRADIENT: gradient = SetRadialGradientL(/* inout */ pos); break; case CSS_FUNCTION_DOUBLE_RAINBOW: gradient = SetDoubleRainbowL(/* inout */ pos); type = CSS_FUNCTION_RADIAL_GRADIENT; break; default: OP_ASSERT(!"Invalid gradient type"); return NULL; } if (gradient) { if (type == CSS_FUNCTION_REPEATING_LINEAR_GRADIENT || type == CSS_FUNCTION_REPEATING_RADIAL_GRADIENT) gradient->repeat = TRUE; if (type == CSS_FUNCTION_WEBKIT_LINEAR_GRADIENT) gradient->webkit_prefix = TRUE; else if (type == CSS_FUNCTION_O_LINEAR_GRADIENT) gradient->o_prefix = TRUE; } return gradient; } CSS_LinearGradient* CSS_Parser::SetLinearGradientL(int& pos, BOOL legacy_syntax) const { pos++; CSS_LinearGradient gradient; BOOL expect_comma = FALSE; if (m_val_array[pos].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[pos].value.str.start_pos, m_val_array[pos].value.str.str_len); if (!legacy_syntax) { if ( keyword == CSS_VALUE_to) { gradient.line.to = TRUE; if (m_val_array[++pos].token == CSS_IDENT) keyword = m_input_buffer->GetValueSymbol(m_val_array[pos].value.str.start_pos, m_val_array[pos].value.str.str_len); else return NULL; } else goto parse_color_stops; } else if (legacy_syntax && keyword == CSS_VALUE_to) return NULL; switch (keyword) { case CSS_VALUE_top: case CSS_VALUE_bottom: gradient.line.y = keyword; gradient.line.end_set = TRUE; expect_comma = TRUE; if (m_val_array[++pos].token == CSS_IDENT) { // We have two identifiers CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[pos].value.str.start_pos, m_val_array[pos].value.str.str_len); switch (keyword) { case CSS_VALUE_left: case CSS_VALUE_right: gradient.line.x = keyword; break; default: // But the second keyword does not refer to an edge return NULL; } pos++; } else gradient.line.x = CSS_VALUE_center; break; case CSS_VALUE_left: case CSS_VALUE_right: gradient.line.x = keyword; gradient.line.end_set = TRUE; expect_comma = TRUE; if (m_val_array[++pos].token == CSS_IDENT) { // We have two identifiers CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[pos].value.str.start_pos, m_val_array[pos].value.str.str_len); switch (keyword) { case CSS_VALUE_top: case CSS_VALUE_bottom: gradient.line.y = keyword; break; default: // But the second keyword does not refer to an edge return NULL; } pos++; } else gradient.line.y = CSS_VALUE_center; break; // default: eat nothing, try reparsing as color (below) } } // Angle else if (m_val_array[pos].token == CSS_RAD || m_val_array[pos].token == CSS_NUMBER && m_val_array[pos].value.number.number == 0) { gradient.line.angle_set = TRUE; gradient.line.angle = float(m_val_array[pos].value.number.number); pos++; expect_comma = TRUE; } parse_color_stops: // Use default line ('to bottom') if neither edge nor angle is set. if (!gradient.line.end_set && !gradient.line.angle_set) { gradient.line.end_set = TRUE; gradient.line.x = CSS_VALUE_center; gradient.line.y = CSS_VALUE_bottom; gradient.line.to = TRUE; } // Keyword(s) or angle must be followed by a comma if (expect_comma && m_val_array[pos++].token != CSS_COMMA) return NULL; if (!SetColorStops(pos, gradient)) return NULL; return gradient.CopyL(); } CSS_RadialGradient* CSS_Parser::SetDoubleRainbowL(int& pos) const { pos++; CSS_RadialGradient gradient; BOOL has_ref; // <position> (required) if (SetPosition(pos, gradient.pos.pos, gradient.pos.pos_unit, TRUE, gradient.pos.ref, has_ref) == OK) { gradient.pos.is_set = TRUE; gradient.pos.has_ref = !!has_ref; } else return NULL; // <length> | <percentage> | <size> // defaults gradient.form.shape = CSS_VALUE_circle; gradient.form.size = CSS_VALUE_farthest_side; if (m_val_array[pos].token == CSS_COMMA) { pos++; // <size> if (m_val_array[pos].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol( m_val_array[pos].value.str.start_pos, m_val_array[pos].value.str.str_len); switch (keyword) { case CSS_VALUE_contain: keyword = CSS_VALUE_closest_side; break; case CSS_VALUE_cover: keyword = CSS_VALUE_farthest_corner; break; } switch (keyword) { case CSS_VALUE_closest_side: case CSS_VALUE_closest_corner: case CSS_VALUE_farthest_side: case CSS_VALUE_farthest_corner: gradient.form.shape = keyword; pos++; break; // default (INVALID): try parsing the rest. If there is an invalid <size> it will quickly be caught when parsing color stops. } } // <length> | <percentage> else if ((CSS_is_length_number_ext(m_val_array[pos].token) || m_val_array[pos].token == CSS_PERCENTAGE) && m_val_array[pos].value.number.number > 0) { gradient.form.has_explicit_size = TRUE; gradient.form.explicit_size[0] = gradient.form.explicit_size[1] = float(m_val_array[pos].value.number.number); gradient.form.explicit_size_unit[0] = gradient.form.explicit_size_unit[1] = static_cast<CSSValueType>(CSS_get_number_ext(m_val_array[pos].token)); if (m_val_array[pos].token == CSS_PERCENTAGE) // Special signal to CSS_RadialGradient::CalculateShape to maintain circle shape gradient.form.explicit_size[1] = -1.0; pos++; } } // Function must contain no more arguments if (m_val_array[pos].token != CSS_FUNCTION_END) return NULL; // Color stops const int stop_count = 19; gradient.stop_count = stop_count; COLORREF stops[stop_count] = { static_cast<COLORREF>(CSS_COLOR_transparent), // 50% opacity 0x20d2fafa, // lightgoldenrodyellow 63% 0x20d30094, // darkviolet 0x20800000, // navy 0x20ff0000, // blue 0x20008000, // green 0x2000ffff, // yellow 0x2000a5ff, // orange 0x200000ff, // red static_cast<COLORREF>(CSS_COLOR_transparent), // 67% static_cast<COLORREF>(CSS_COLOR_transparent), // 90% // 25% opacity 0x100000ff, // red 0x1000a5ff, // orange 0x1000ffff, // yellow 0x10008000, // green 0x10ff0000, // blue 0x10800000, // navy 0x10d30094, // darkviolet static_cast<COLORREF>(CSS_COLOR_transparent) // 100% }; gradient.stops = OP_NEWA_L(CSS_Gradient::ColorStop, gradient.stop_count); for (int i = 0; i < gradient.stop_count; i++) { gradient.stops[i].color = stops[i]; if (i == 1 || i == 9 || i == 10 || i == 18) { gradient.stops[i].has_length = TRUE; gradient.stops[i].unit = CSS_PERCENTAGE; switch (i) { case 1: gradient.stops[i].length = 63; break; case 9: gradient.stops[i].length = 67; break; case 10: gradient.stops[i].length = 90; break; case 18: gradient.stops[i].length = 100; break; } } } // Epilogue return gradient.CopyL(); } BOOL CSS_Parser::SetRadialGradientPos(int& pos, CSS_RadialGradient& gradient) const { if (m_val_array[pos].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[pos].value.str.start_pos, m_val_array[pos].value.str.str_len); if (keyword == CSS_VALUE_at) { pos++; BOOL has_ref; DeclStatus res = SetPosition(pos, gradient.pos.pos, gradient.pos.pos_unit, TRUE, gradient.pos.ref, has_ref); gradient.pos.is_set = TRUE; gradient.pos.has_ref = !!has_ref; return res == OK; } } return TRUE; } CSS_RadialGradient* CSS_Parser::SetRadialGradientL(int& pos) const { pos++; BOOL expect_comma = FALSE; CSS_RadialGradient gradient; if (m_val_array[pos].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[pos].value.str.start_pos, m_val_array[pos].value.str.str_len); switch (keyword) { case CSS_VALUE_at: expect_comma = TRUE; if (!SetRadialGradientPos(pos, gradient)) return NULL; break; case CSS_VALUE_circle: case CSS_VALUE_ellipse: expect_comma = TRUE; pos++; gradient.form.shape = keyword; if (m_val_array[pos].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[pos].value.str.start_pos, m_val_array[pos].value.str.str_len); if (keyword == CSS_VALUE_closest_side || keyword == CSS_VALUE_closest_corner || keyword == CSS_VALUE_farthest_side || keyword == CSS_VALUE_farthest_corner) { pos++; gradient.form.size = keyword; } } // ellipse and circle can be followed by a length or 0, and ellipse // (but not circle) can also be followed by a percentage else if ((CSS_is_length_number_ext(m_val_array[pos].token) || (m_val_array[pos].token == CSS_PERCENTAGE && gradient.form.shape == CSS_VALUE_ellipse)) && m_val_array[pos].value.number.number >= 0 || (m_val_array[pos].token == CSS_NUMBER && m_val_array[pos].value.number.number == 0)) { gradient.form.has_explicit_size = TRUE; gradient.form.explicit_size[0] = float(m_val_array[pos].value.number.number); gradient.form.explicit_size_unit[0] = static_cast<CSSValueType>(CSS_get_number_ext(m_val_array[pos].token)); pos++; // an ellipse must have a second length percentage or 0 if (gradient.form.shape == CSS_VALUE_ellipse) { if ((CSS_is_length_number_ext(m_val_array[pos].token) || m_val_array[pos].token == CSS_PERCENTAGE) && m_val_array[pos].value.number.number >= 0 || (m_val_array[pos].token == CSS_NUMBER && m_val_array[pos].value.number.number == 0)) { gradient.form.explicit_size[1] = float(m_val_array[pos].value.number.number); gradient.form.explicit_size_unit[1] = static_cast<CSSValueType>(CSS_get_number_ext(m_val_array[pos].token)); pos++; } else return NULL; } else // Special signal to CSS_RadialGradient::CalculateShape to maintain circle shape gradient.form.explicit_size[1] = -1.0; } if (!SetRadialGradientPos(pos, gradient)) return NULL; break; case CSS_VALUE_closest_side: case CSS_VALUE_closest_corner: case CSS_VALUE_farthest_side: case CSS_VALUE_farthest_corner: expect_comma = TRUE; pos++; gradient.form.size = keyword; if (m_val_array[pos].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[pos].value.str.start_pos, m_val_array[pos].value.str.str_len); if (keyword == CSS_VALUE_circle || keyword == CSS_VALUE_ellipse) { pos++; gradient.form.shape = keyword; } if (!SetRadialGradientPos(pos, gradient)) return NULL; } break; } } // Explicit size begins with a length or a percentage or 0 else if ((CSS_is_length_number_ext(m_val_array[pos].token) || m_val_array[pos].token == CSS_PERCENTAGE) && m_val_array[pos].value.number.number >= 0 || (m_val_array[pos].token == CSS_NUMBER && m_val_array[pos].value.number.number == 0) ) { expect_comma = TRUE; gradient.form.has_explicit_size = TRUE; gradient.form.explicit_size[0] = float(m_val_array[pos].value.number.number); gradient.form.explicit_size_unit[0] = static_cast<CSSValueType>(CSS_get_number_ext(m_val_array[pos].token)); pos++; // Another length or percentage or 0 means an ellipse if ((CSS_is_length_number_ext(m_val_array[pos].token) || m_val_array[pos].token == CSS_PERCENTAGE) && m_val_array[pos].value.number.number >= 0 || (m_val_array[pos].token == CSS_NUMBER && m_val_array[pos].value.number.number == 0) ) { gradient.form.explicit_size[1] = float(m_val_array[pos].value.number.number); gradient.form.explicit_size_unit[1] = static_cast<CSSValueType>(CSS_get_number_ext(m_val_array[pos].token)); pos++; // The shape is optional, but if it is mentioned it must be ellipse if (m_val_array[pos].token == CSS_IDENT && m_input_buffer->GetValueSymbol(m_val_array[pos].value.str.start_pos, m_val_array[pos].value.str.str_len) == CSS_VALUE_ellipse) pos++; } // A single non percentage length is allowed, and means circle else if (gradient.form.explicit_size_unit[0] != CSS_PERCENTAGE) { // Special signal to CSS_RadialGradient::CalculateShape to maintain circle shape gradient.form.explicit_size[1] = -1.0; // The shape is optional, but if it is mentioned it must be circle if (m_val_array[pos].token == CSS_IDENT && m_input_buffer->GetValueSymbol(m_val_array[pos].value.str.start_pos, m_val_array[pos].value.str.str_len) == CSS_VALUE_circle) pos++; } else return NULL; if (!SetRadialGradientPos(pos, gradient)) return NULL; } if (expect_comma && m_val_array[pos++].token != CSS_COMMA) return NULL; if (!SetColorStops(pos, gradient)) return NULL; return gradient.CopyL(); } BOOL CSS_Parser::SetColorStops(int& pos, CSS_Gradient& gradient) const { // Find the end of the gradient function and count color stops int stop_count = 0; for (int i = pos; i != CSS_FUNCTION_END; i++) { OP_ASSERT(i < m_val_array.GetCount()); // The parser should have inserted CSS_FUNCTION_END at the end. if (m_val_array[i].token == CSS_COMMA || m_val_array[i].token == CSS_FUNCTION_END) { stop_count++; if (m_val_array[i].token == CSS_FUNCTION_END) break; } } if (stop_count < 2) return FALSE; gradient.stop_count = stop_count; gradient.stops = OP_NEWA_L(CSS_Gradient::ColorStop, stop_count); for (int i = 0; i < stop_count; i++) { OP_ASSERT(pos < m_val_array.GetCount()); if (m_val_array[pos].token == CSS_FUNCTION_END) return FALSE; // Color COLORREF color; CSSValue keyword; uni_char* dummy = NULL; // Skin colors are not supported. switch (SetColorL(color, keyword, dummy, m_val_array[pos])) { case COLOR_KEYWORD: if (keyword == CSS_VALUE_transparent) gradient.stops[i].color = COLORREF(CSS_COLOR_transparent); else if (keyword == CSS_VALUE_currentColor) gradient.stops[i].color = COLORREF(CSS_COLOR_current_color); else return FALSE; break; case COLOR_RGBA: case COLOR_NAMED: gradient.stops[i].color = color; break; case COLOR_SKIN: case COLOR_INVALID: return FALSE; } pos++; if (m_val_array[pos].token == CSS_COMMA) // Comma pos++; else if (m_val_array[pos].token == CSS_FUNCTION_END) // End ; else if (CSS_is_length_number_ext(m_val_array[pos].token) || m_val_array[pos].token == CSS_PERCENTAGE || m_val_array[pos].token == CSS_NUMBER && m_val_array[pos].value.number.number == 0) { // Length gradient.stops[i].has_length = TRUE; gradient.stops[i].length = float(m_val_array[pos].value.number.number); gradient.stops[i].unit = CSS_get_number_ext(m_val_array[pos].token); pos++; if (m_val_array[pos].token == CSS_COMMA) pos++; // else: End } else // Invalid return FALSE; } // End up at the end of this item so caller can increment pos. if (m_val_array[pos].token != CSS_FUNCTION_END) return FALSE; return TRUE; } #endif // CSS_GRADIENT_SUPPORT CSS_Parser::DeclStatus CSS_Parser::AddFontfaceDeclL(short prop) { CSS_property_list* prop_list = m_current_props; int i = 0; switch (prop) { case CSS_PROPERTY_font_family: { if (m_val_array.GetCount() > 0) { CSS_generic_value value; if (SetFamilyNameL(value, i, FALSE, FALSE) == OK) { uni_char* family_name = value.GetString(); OP_ASSERT(value.GetValueType() == CSS_STRING_LITERAL && family_name); if (i == m_val_array.GetCount()) prop_list->AddDeclL(CSS_PROPERTY_font_family, family_name, FALSE, GetCurrentOrigin(), CSS_string_decl::StringDeclString, m_hld_prof == NULL); else { OP_DELETEA(family_name); return INVALID; } } else return INVALID; } else return INVALID; } break; case CSS_PROPERTY_font_style: if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (!CSS_is_font_style_val(keyword) && keyword != CSS_VALUE_inherit) return INVALID; prop_list->AddTypeDeclL(prop, keyword, FALSE, GetCurrentOrigin()); } break; case CSS_PROPERTY_font_weight: if (m_val_array.GetCount() == 1) { if (m_val_array[0].token == CSS_IDENT) { short fweight = 0; CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); fweight = ResolveFontWeight(keyword); if (fweight > 0) prop_list->AddDeclL(prop, fweight, CSS_NUMBER, FALSE, GetCurrentOrigin()); else if (fweight == 0) prop_list->AddTypeDeclL(prop, keyword, FALSE, GetCurrentOrigin()); else return INVALID; } else if (CSS_is_number(m_val_array[0].token) && CSS_get_number_ext(m_val_array[0].token) == CSS_NUMBER) { double fval = m_val_array[0].value.number.number; if (fval >= 100 && fval <= 900) { int fweight = (int)fval; if ((fweight/100)*100 == fval) prop_list->AddDeclL(prop, (short) (fweight/100), CSS_NUMBER, FALSE, GetCurrentOrigin()); else return INVALID; } else return INVALID; } else return INVALID; } else return INVALID; break; case CSS_PROPERTY_src: { CSS_generic_value_list gen_arr; ANCHOR(CSS_generic_value_list, gen_arr); CSS_anchored_heap_arrays<uni_char> strings; ANCHOR(CSS_anchored_heap_arrays<uni_char>, strings); while (i < m_val_array.GetCount()) { if (m_val_array[i].token == CSS_FUNCTION_URL) { int url_pos = i++; CSS_WebFont::Format format = CSS_WebFont::FORMAT_UNKNOWN; if (i < m_val_array.GetCount() && m_val_array[i].token == CSS_FUNCTION_FORMAT) format = static_cast<CSS_WebFont::Format>(m_val_array[i++].value.shortint); if (format != CSS_WebFont::FORMAT_UNSUPPORTED) { if (!gen_arr.Empty()) gen_arr.PushValueTypeL(CSS_COMMA); URL url = m_input_buffer->GetURLL(m_base_url, m_val_array[url_pos].value.str.start_pos, m_val_array[url_pos].value.str.str_len); ANCHOR(URL, url); const uni_char* url_name = url.GetAttribute(URL::KUniName_With_Fragment_Username_Password_NOT_FOR_UI).CStr(); uni_char* url_str = OP_NEWA_L(uni_char, uni_strlen(url_name)+1); strings.AddArrayL(url_str); uni_strcpy(url_str, url_name); gen_arr.PushStringL(CSS_FUNCTION_URL, url_str); if (format != CSS_WebFont::FORMAT_UNKNOWN) gen_arr.PushIntegerL(CSS_FUNCTION_FORMAT, format); } } else if (m_val_array[i++].token == CSS_FUNCTION_LOCAL_START) { CSS_generic_value value; if (i < m_val_array.GetCount() && SetFamilyNameL(value, i, FALSE, FALSE) == OK) { OP_ASSERT(value.GetValueType() == CSS_STRING_LITERAL); strings.AddArrayL(value.GetString()); if (i < m_val_array.GetCount() && m_val_array[i].token == CSS_FUNCTION_END) { i++; if (!gen_arr.Empty()) gen_arr.PushValueTypeL(CSS_COMMA); gen_arr.PushStringL(CSS_FUNCTION_LOCAL, value.GetString()); } else return INVALID; } else return INVALID; } else return INVALID; /* We're either finished, or there has to be a comma followed by something that's presumably the next source. */ if (i < m_val_array.GetCount() && (m_val_array[i++].token != CSS_COMMA || i == m_val_array.GetCount())) return INVALID; } if (!gen_arr.Empty()) prop_list->AddDeclL(prop, gen_arr, 0, FALSE, GetCurrentOrigin()); } break; default: return INVALID; } return OK; } CSS_Parser::DeclStatus CSS_Parser::AddViewportDeclL(short prop, BOOL important) { CSS_property_list* prop_list = m_current_props; int val_count = m_val_array.GetCount(); switch (prop) { case CSS_PROPERTY_height: case CSS_PROPERTY_width: if (val_count == 1 || val_count == 2) { short shorthand_props[2]; /* ARRAY OK 2010-12-10 rune */ CSSValue shorthand_keywords[2] = { CSS_VALUE_UNSPECIFIED, CSS_VALUE_UNSPECIFIED }; /* ARRAY OK 2010-12-10 rune */ short shorthand_units[2] = { CSS_NUMBER, CSS_NUMBER }; /* ARRAY OK 2010-12-10 rune */ float shorthand_numbers[2] = { 0, 0 }; /* ARRAY OK 2010-12-10 rune */ if (prop == CSS_PROPERTY_width) { shorthand_props[0] = CSS_PROPERTY_min_width; shorthand_props[1] = CSS_PROPERTY_max_width; } else { shorthand_props[0] = CSS_PROPERTY_min_height; shorthand_props[1] = CSS_PROPERTY_max_height; } int j; for (j = 0; j < 2; j++) { int i = val_count == 2 ? j : 0; if (m_val_array[i].token == CSS_IDENT) { shorthand_keywords[j] = m_input_buffer->GetValueSymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (!CSS_is_viewport_length_val(shorthand_keywords[j])) return INVALID; } else if ((CSS_is_length_number_ext(m_val_array[i].token) || m_val_array[i].token == CSS_PERCENTAGE) && m_val_array[i].value.number.number > 0) { shorthand_numbers[j] = float(m_val_array[i].value.number.number); shorthand_units[j] = m_val_array[i].token; } else return INVALID; } for (j = 0; j < 2; j++) { if (shorthand_keywords[j] != CSS_VALUE_UNSPECIFIED) prop_list->AddTypeDeclL(shorthand_props[j], shorthand_keywords[j], important, GetCurrentOrigin()); else prop_list->AddDeclL(shorthand_props[j], shorthand_numbers[j], shorthand_units[j], important, GetCurrentOrigin()); } } else return INVALID; break; case CSS_PROPERTY_max_width: case CSS_PROPERTY_min_width: case CSS_PROPERTY_max_height: case CSS_PROPERTY_min_height: if (val_count == 1) { if (m_val_array[0].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (CSS_is_viewport_length_val(keyword)) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else if ((CSS_is_length_number_ext(m_val_array[0].token) || m_val_array[0].token == CSS_PERCENTAGE) && m_val_array[0].value.number.number > 0) { short length_type = m_val_array[0].token; prop_list->AddDeclL(prop, float(m_val_array[0].value.number.number), length_type, important, GetCurrentOrigin()); } else return INVALID; } else return INVALID; break; case CSS_PROPERTY_zoom: case CSS_PROPERTY_min_zoom: case CSS_PROPERTY_max_zoom: if (m_val_array.GetCount() == 1) { if ((m_val_array[0].token == CSS_NUMBER || m_val_array[0].token == CSS_PERCENTAGE) && m_val_array[0].value.number.number > 0) prop_list->AddDeclL(prop, float(m_val_array[0].value.number.number), m_val_array[0].token, important, GetCurrentOrigin()); else if (m_val_array[0].token == CSS_IDENT && m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len) == CSS_VALUE_auto) prop_list->AddTypeDeclL(prop, CSS_VALUE_auto, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; break; case CSS_PROPERTY_user_zoom: if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (CSS_is_user_zoom_val(keyword)) prop_list->AddTypeDeclL(CSS_PROPERTY_user_zoom, keyword, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; break; case CSS_PROPERTY_orientation: if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_auto || keyword == CSS_VALUE_portrait || keyword == CSS_VALUE_landscape) prop_list->AddTypeDeclL(CSS_PROPERTY_orientation, keyword, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; break; default: return INVALID; } return OK; } #ifdef CSS_ANIMATIONS void CSS_Parser::BeginKeyframesL(uni_char* name) { if (m_replace_rule) { OP_ASSERT(m_current_keyframes_rule); m_current_keyframes_rule->SetName(name); m_current_keyframes_rule->ClearRules(); } else { OP_ASSERT(m_decl_type == DECL_RULESET); m_current_keyframes_rule = OP_NEW_L(CSS_KeyframesRule, (name)); AddRuleL(m_current_keyframes_rule); m_current_keyframe_selectors.Clear(); } BeginKeyframes(); } void CSS_Parser::AddKeyframeRuleL() { OP_ASSERT(m_current_keyframes_rule); if (m_current_props) m_current_props->PostProcess(TRUE, FALSE); if (m_replace_rule && m_dom_rule->GetType() == CSS_Rule::KEYFRAME) { CSS_KeyframeRule* keyframe_rule = static_cast<CSS_KeyframeRule*>(m_dom_rule); keyframe_rule->Replace(m_current_keyframe_selectors, m_current_props); } else { CSS_KeyframeRule* keyframe_rule = OP_NEW_L(CSS_KeyframeRule, (m_current_keyframes_rule, m_current_keyframe_selectors, m_current_props)); m_current_keyframes_rule->Add(keyframe_rule); } } #endif // CSS_ANIMATIONS CSS_Parser::DeclStatus CSS_Parser::AddPageDeclL(short prop, BOOL important) { switch (prop) { case CSS_PROPERTY_size: case CSS_PROPERTY_margin: case CSS_PROPERTY_margin_top: case CSS_PROPERTY_margin_left: case CSS_PROPERTY_margin_right: case CSS_PROPERTY_margin_bottom: case CSS_PROPERTY_width: case CSS_PROPERTY_height: case CSS_PROPERTY_max_width: case CSS_PROPERTY_max_height: case CSS_PROPERTY_min_width: case CSS_PROPERTY_min_height: return AddRulesetDeclL(prop, important); default: return INVALID; } } CSS_Parser::DeclStatus CSS_Parser::AddRulesetDeclL(short prop, BOOL important) { CSS_property_list* prop_list = m_current_props; int i = 0; int level = 0; CSSValue keyword = CSS_VALUE_UNKNOWN; #ifdef CSS_GRADIENT_SUPPORT CSS_anchored_heap_objects<CSS_Gradient> gradients; ANCHOR(CSS_anchored_heap_objects<CSS_Gradient>, gradients); #endif // CSS_GRADIENT_SUPPORT BOOL auto_allowed = FALSE; prop = GetAliasedProperty(prop); switch (prop) { case CSS_PROPERTY_top: case CSS_PROPERTY_left: case CSS_PROPERTY_right: case CSS_PROPERTY_bottom: case CSS_PROPERTY_width: case CSS_PROPERTY_height: case CSS_PROPERTY_margin_top: case CSS_PROPERTY_margin_left: case CSS_PROPERTY_margin_right: case CSS_PROPERTY_margin_bottom: case CSS_PROPERTY_column_width: case CSS_PROPERTY_column_gap: case CSS_PROPERTY_min_width: case CSS_PROPERTY_min_height: auto_allowed = TRUE; // fall-through is intended case CSS_PROPERTY_max_width: case CSS_PROPERTY_max_height: case CSS_PROPERTY_padding_top: case CSS_PROPERTY_padding_left: case CSS_PROPERTY_padding_right: case CSS_PROPERTY_padding_bottom: case CSS_PROPERTY_line_height: case CSS_PROPERTY_font_size: if (m_val_array.GetCount() == 1) { if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword < 0) return INVALID; if (keyword == CSS_VALUE_inherit || (keyword == CSS_VALUE_auto && auto_allowed) || (prop == CSS_PROPERTY_font_size && CSS_is_fontsize_val(keyword)) || (keyword == CSS_VALUE_none && (prop == CSS_PROPERTY_max_width || prop == CSS_PROPERTY_max_height)) || (prop == CSS_PROPERTY_column_gap && keyword == CSS_VALUE_normal)) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else if (keyword == CSS_VALUE_normal && prop == CSS_PROPERTY_line_height) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else if ((prop == CSS_PROPERTY_height || prop == CSS_PROPERTY_width) && (keyword == CSS_VALUE__o_skin || keyword == CSS_VALUE__o_content_size)) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE__o_skin || keyword == CSS_VALUE__o_content_size) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); } else return INVALID; } else if (CSS_is_number(m_val_array[0].token) && m_val_array[0].token != CSS_DIMEN) { float length = float(m_val_array[0].value.number.number); int length_type = CSS_get_number_ext(m_val_array[0].token); if (length <= 0) { switch (prop) { case CSS_PROPERTY_font_size: case CSS_PROPERTY_line_height: case CSS_PROPERTY_padding_top: case CSS_PROPERTY_padding_left: case CSS_PROPERTY_padding_right: case CSS_PROPERTY_padding_bottom: case CSS_PROPERTY_width: case CSS_PROPERTY_height: case CSS_PROPERTY_min_width: case CSS_PROPERTY_max_width: case CSS_PROPERTY_max_height: case CSS_PROPERTY_min_height: case CSS_PROPERTY_column_gap: if (length < 0) return INVALID; break; case CSS_PROPERTY_column_width: return INVALID; default: break; } } if (length_type == CSS_PERCENTAGE && (prop == CSS_PROPERTY_column_width || prop == CSS_PROPERTY_column_gap)) return INVALID; if (prop == CSS_PROPERTY_line_height && length_type != CSS_PERCENTAGE && length_type != CSS_NUMBER && !CSS_is_length_number_ext(length_type)) return INVALID; else if (prop != CSS_PROPERTY_line_height && length_type != CSS_PERCENTAGE && !CSS_is_length_number_ext(length_type)) { if (length_type == CSS_NUMBER && (length == 0 || (m_hld_prof && !m_hld_prof->IsInStrictMode()))) length_type = CSS_PX; else return INVALID; } prop_list->AddDeclL(prop, length, length_type, important, GetCurrentOrigin()); } else return INVALID; } else return INVALID; break; case CSS_PROPERTY_border_top_right_radius: case CSS_PROPERTY_border_bottom_right_radius: case CSS_PROPERTY_border_bottom_left_radius: case CSS_PROPERTY_border_top_left_radius: return SetIndividualBorderRadiusL(prop_list, prop, important); case CSS_PROPERTY_border_radius: return SetShorthandBorderRadiusL(prop_list, important); case CSS_PROPERTY_border_style: case CSS_PROPERTY_border_width: case CSS_PROPERTY_padding: case CSS_PROPERTY_margin: case CSS_PROPERTY_border_color: if (m_val_array.GetCount() <= 4) { BOOL is_keyword[4] = { FALSE, FALSE, FALSE, FALSE }; BOOL is_color[4] = { FALSE, FALSE, FALSE, FALSE }; COLORREF value_col[4] = { USE_DEFAULT_COLOR, USE_DEFAULT_COLOR, USE_DEFAULT_COLOR, USE_DEFAULT_COLOR }; float value[4]; int value_type[4]; CSSValue value_keyword[4]; short property[4]; if (prop == CSS_PROPERTY_margin) { property[0] = CSS_PROPERTY_margin_top; property[1] = CSS_PROPERTY_margin_right; property[2] = CSS_PROPERTY_margin_bottom; property[3] = CSS_PROPERTY_margin_left; } else if (prop == CSS_PROPERTY_padding) { property[0] = CSS_PROPERTY_padding_top; property[1] = CSS_PROPERTY_padding_right; property[2] = CSS_PROPERTY_padding_bottom; property[3] = CSS_PROPERTY_padding_left; } else if (prop == CSS_PROPERTY_border_width) { property[0] = CSS_PROPERTY_border_top_width; property[1] = CSS_PROPERTY_border_right_width; property[2] = CSS_PROPERTY_border_bottom_width; property[3] = CSS_PROPERTY_border_left_width; } else if (prop == CSS_PROPERTY_border_color) { property[0] = CSS_PROPERTY_border_top_color; property[1] = CSS_PROPERTY_border_right_color; property[2] = CSS_PROPERTY_border_bottom_color; property[3] = CSS_PROPERTY_border_left_color; } else { property[0] = CSS_PROPERTY_border_top_style; property[1] = CSS_PROPERTY_border_right_style; property[2] = CSS_PROPERTY_border_bottom_style; property[3] = CSS_PROPERTY_border_left_style; } while (i < m_val_array.GetCount()) { if (m_val_array[i].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (prop == CSS_PROPERTY_border_color && (keyword >= 0 && CSS_is_color_val(keyword) || m_input_buffer->GetNamedColorIndex(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len) != USE_DEFAULT_COLOR)) { is_color[i] = TRUE; is_keyword[i] = TRUE; if (CSS_is_ui_color_val(keyword)) value_col[i] = CSS_COLOR_KEYWORD_TYPE_ui_color | keyword; else value_col[i] = m_input_buffer->GetNamedColorIndex(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); } else if ( (m_val_array.GetCount() == 1 && keyword == CSS_VALUE_inherit) || (prop == CSS_PROPERTY_border_color && (keyword == CSS_VALUE_transparent || keyword == CSS_VALUE_currentColor)) || (keyword == CSS_VALUE_auto && prop == CSS_PROPERTY_margin) ) { value_keyword[i] = keyword; is_keyword[i] = TRUE; } else if (prop == CSS_PROPERTY_border_style && (CSS_is_border_style_val(keyword) || keyword == CSS_VALUE_none)) { value_keyword[i] = keyword; is_keyword[i] = TRUE; } else if (prop == CSS_PROPERTY_border_width && CSS_is_border_width_val(keyword)) { value_keyword[i] = keyword; is_keyword[i] = TRUE; } else if (prop == CSS_PROPERTY_border_color && m_hld_prof && !m_hld_prof->IsInStrictMode()) { value_col[i] = m_input_buffer->GetColor(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (value_col[i] == USE_DEFAULT_COLOR) return INVALID; is_color[i] = TRUE; } else return INVALID; } else if (prop == CSS_PROPERTY_border_color) { is_color[i] = TRUE; if (m_val_array[i].token == CSS_FUNCTION_RGB || SupportsAlpha() && m_val_array[i].token == CSS_FUNCTION_RGBA) value_col[i] = m_val_array[i].value.color; else if (m_val_array[i].token == CSS_HASH) value_col[i] = m_input_buffer->GetColor(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); else if (CSS_is_number(m_val_array[i].token) && m_hld_prof && !m_hld_prof->IsInStrictMode()) { if (m_val_array[i].value.number.str_len == 3 || m_val_array[i].value.number.str_len == 6) value_col[i] = m_input_buffer->GetColor(m_val_array[i].value.number.start_pos, m_val_array[i].value.number.str_len); } if (value_col[i] == USE_DEFAULT_COLOR) return INVALID; } else if (CSS_is_number(m_val_array[i].token) && prop != CSS_PROPERTY_border_style) { if (m_val_array[i].token == CSS_PERCENTAGE && prop == CSS_PROPERTY_border_width) return INVALID; value[i] = float(m_val_array[i].value.number.number); value_type[i] = CSS_get_number_ext(m_val_array[i].token); if (value[i] < 0) { switch (prop) { case CSS_PROPERTY_border_width: case CSS_PROPERTY_padding: return INVALID; default: break; } } //units are required if not 0 if (value_type[i] == CSS_NUMBER) { // Accept unspecified unit for borders since i have seen a lot of pages which get the default // borderwidth (3) instead of the given value. (emil@opera.com) // Added margin and padding. (rune@opera.com) // Added check for strict mode. if (value[i] == 0 || (m_hld_prof && !m_hld_prof->IsInStrictMode() && (prop == CSS_PROPERTY_border_width || prop == CSS_PROPERTY_margin || prop == CSS_PROPERTY_padding))) value_type[i] = CSS_PX; else return INVALID; } if (value_type[i] == CSS_DIMEN) { switch (prop) { case CSS_PROPERTY_border_width: case CSS_PROPERTY_padding: case CSS_PROPERTY_margin: return INVALID; // we encountered a unit that we didn't recognize, for example "border-width: 50zu;" default: break; } } } else return INVALID; i++; } int right_idx = 0; int bottom_idx = 0; int left_idx = 0; if (m_val_array.GetCount() == 2) { left_idx = right_idx = 1; } else if (m_val_array.GetCount() == 3) { left_idx = right_idx = 1; bottom_idx = 2; } else if (m_val_array.GetCount() == 4) { right_idx = 1; bottom_idx = 2; left_idx = 3; } if (is_color[0]) { if (is_keyword[0]) prop_list->AddColorDeclL(property[0], value_col[0], important, GetCurrentOrigin()); else prop_list->AddLongDeclL(property[0], (long)value_col[0], important, GetCurrentOrigin()); } else if (is_keyword[0]) { prop_list->AddTypeDeclL(property[0], value_keyword[0], important, GetCurrentOrigin()); } else { prop_list->AddDeclL(property[0], value[0], value_type[0], important, GetCurrentOrigin()); } if (is_color[right_idx]) { if (is_keyword[right_idx]) prop_list->AddColorDeclL(property[1], value_col[right_idx], important, GetCurrentOrigin()); else prop_list->AddLongDeclL(property[1], (long)value_col[right_idx], important, GetCurrentOrigin()); } else if (is_keyword[right_idx]) { prop_list->AddTypeDeclL(property[1], value_keyword[right_idx], important, GetCurrentOrigin()); } else { prop_list->AddDeclL(property[1], value[right_idx], value_type[right_idx], important, GetCurrentOrigin()); } if (is_color[bottom_idx]) { if (is_keyword[bottom_idx]) prop_list->AddColorDeclL(property[2], value_col[bottom_idx], important, GetCurrentOrigin()); else prop_list->AddLongDeclL(property[2], (long)value_col[bottom_idx], important, GetCurrentOrigin()); } else if (is_keyword[bottom_idx]) { prop_list->AddTypeDeclL(property[2], value_keyword[bottom_idx], important, GetCurrentOrigin()); } else { prop_list->AddDeclL(property[2], value[bottom_idx], value_type[bottom_idx], important, GetCurrentOrigin()); } if (is_color[left_idx]) { if (is_keyword[left_idx]) prop_list->AddColorDeclL(property[3], value_col[left_idx], important, GetCurrentOrigin()); else prop_list->AddLongDeclL(property[3], (long)value_col[left_idx], important, GetCurrentOrigin()); } else if (is_keyword[left_idx]) { prop_list->AddTypeDeclL(property[3], value_keyword[left_idx], important, GetCurrentOrigin()); } else { prop_list->AddDeclL(property[3], value[left_idx], value_type[left_idx], important, GetCurrentOrigin()); } return OK; } break; case CSS_PROPERTY_font_family: return SetFontFamilyL(prop_list, 0, important, m_val_array.GetCount() == 1); case CSS_PROPERTY_font_size_adjust: if (m_val_array.GetCount() == 1) { if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword != CSS_VALUE_none && keyword != CSS_VALUE_inherit) return INVALID; prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); } else if (CSS_is_number(m_val_array[0].token)) prop_list->AddDeclL(prop, float(m_val_array[0].value.number.number), CSS_get_number_ext(m_val_array[0].token), important, GetCurrentOrigin()); else return INVALID; } else return INVALID; break; case CSS_PROPERTY_font_style: if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (!CSS_is_font_style_val(keyword) && keyword != CSS_VALUE_inherit) return INVALID; prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); } else return INVALID; break; case CSS_PROPERTY_font_variant: if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword != CSS_VALUE_normal && keyword != CSS_VALUE_small_caps && keyword != CSS_VALUE_inherit) return INVALID; prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); } else return INVALID; break; case CSS_PROPERTY_font_weight: if (m_val_array.GetCount() == 1) { if (m_val_array[0].token == CSS_IDENT) { short fweight = 0; keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); fweight = ResolveFontWeight(keyword); if (fweight > 0) prop_list->AddDeclL(prop, fweight, CSS_NUMBER, important, GetCurrentOrigin()); else if (fweight == 0) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else if (CSS_is_number(m_val_array[0].token) && CSS_get_number_ext(m_val_array[0].token) == CSS_NUMBER) { double fval = m_val_array[0].value.number.number; if (fval >= 100 && fval <= 900) { int fweight = (int)fval; if ((fweight/100)*100 == fval) prop_list->AddDeclL(prop, (short) (fweight/100), CSS_NUMBER, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; } else return INVALID; } else return INVALID; break; case CSS_PROPERTY_font: { CSS_Parser::DeclStatus font_family = INVALID; CSSValue font_style = CSS_VALUE_UNSPECIFIED; short font_weight = 0; CSSValue font_variant = CSS_VALUE_UNSPECIFIED; CSSValue font_size = CSS_VALUE_UNSPECIFIED; float font_size_val = -1; short font_size_val_type = 0; CSSValue line_height_keyword = CSS_VALUE_UNSPECIFIED; float line_height = -1; short line_height_type = 0; BOOL next_is_line_height = FALSE; while (i < m_val_array.GetCount()) { if (m_val_array[i].token == CSS_IDENT && !next_is_line_height) { BOOL value_used = FALSE; keyword = m_input_buffer->GetValueSymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (keyword >= 0) { value_used = TRUE; if (m_val_array.GetCount() == 1 && (CSS_is_font_system_val(keyword) || keyword == CSS_VALUE_inherit)) { if (keyword == CSS_VALUE_Menu) keyword = CSS_VALUE_menu; prop_list->AddTypeDeclL(CSS_PROPERTY_font_style, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_font_variant, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_font_weight, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_font_size, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_line_height, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_font_family, keyword, important, GetCurrentOrigin()); return OK; } if (font_size || font_size_val >= 0) { value_used = FALSE; // let the font-family code below handle the value (only font-family is valid after font-size) } else if (!font_style && (keyword == CSS_VALUE_normal || keyword == CSS_VALUE_italic || keyword == CSS_VALUE_oblique || keyword == CSS_VALUE_inherit)) { font_style = keyword; } else if (font_style == CSS_VALUE_normal && (!font_variant || !font_weight) && (keyword == CSS_VALUE_italic || keyword == CSS_VALUE_oblique)) { if (!font_variant) font_variant = CSS_VALUE_normal; else font_weight = CSS_VALUE_normal; font_style = keyword; } else if (!font_variant && (keyword == CSS_VALUE_normal || keyword == CSS_VALUE_small_caps || keyword == CSS_VALUE_inherit)) { font_variant = keyword; } else if (font_variant == CSS_VALUE_normal && (!font_style || !font_weight) && keyword == CSS_VALUE_small_caps) { if (!font_style) font_style = CSS_VALUE_normal; else font_weight = CSS_VALUE_normal; font_variant = keyword; } else if (!font_weight && (keyword == CSS_VALUE_normal || keyword == CSS_VALUE_bold || keyword == CSS_VALUE_bolder || keyword == CSS_VALUE_lighter || keyword == CSS_VALUE_inherit)) { /* Relevant keywords have values greater than 9, the largest legal numeric value. */ font_weight = keyword; if (keyword == CSS_VALUE_normal) font_weight = 4; else if (keyword == CSS_VALUE_bold) font_weight = 7; } else if (font_weight == CSS_VALUE_normal && (!font_style || !font_variant) && (keyword == CSS_VALUE_bold || keyword == CSS_VALUE_bolder || keyword == CSS_VALUE_lighter)) { if (!font_style) font_style = CSS_VALUE_normal; else font_variant = CSS_VALUE_normal; /* Relevant keywords have values greater than 9, the largest legal numeric value. */ font_weight = keyword; if (keyword == CSS_VALUE_normal) font_weight = 4; else if (keyword == CSS_VALUE_bold) font_weight = 7; } else if (!font_size && font_size_val < 0 && CSS_is_fontsize_val(keyword)) { font_size = keyword; } else value_used = FALSE; } if (!value_used && (font_size || font_size_val >= 0)) { font_family = SetFontFamilyL(prop_list, i, important, FALSE); break; // font family is always last } else if (!value_used) return INVALID; } else if (CSS_is_number(m_val_array[i].token)) { double fval = m_val_array[i].value.number.number; int ftype = CSS_get_number_ext(m_val_array[i].token); if (next_is_line_height) { next_is_line_height = FALSE; line_height = float(fval); line_height_type = ftype; if (line_height < 0) return INVALID; } else if (!font_weight && CSS_get_number_ext(m_val_array[i].token) == CSS_NUMBER && fval >= 100 && fval <= 900 && ((int(fval)/100)*100 == fval)) { int fweight = (int) fval; font_weight = (short) (fweight/100); } else if (!font_size && font_size_val < 0) { if (ftype == CSS_NUMBER) { if ((!m_hld_prof || m_hld_prof->IsInStrictMode()) && fval != 0) return INVALID; else ftype = CSS_PX; } if (ftype == CSS_PERCENTAGE || CSS_is_length_number_ext(ftype)) { font_size_val = float(fval); font_size_val_type = ftype; } else return INVALID; } else return INVALID; } else if (m_val_array[i].token == CSS_SLASH && !next_is_line_height) { next_is_line_height = TRUE; } else if ((font_size || font_size_val >= 0) && m_val_array[i].token == CSS_STRING_LITERAL) { font_family = SetFontFamilyL(prop_list, i, important, FALSE); break; // font family is always last } else if (m_val_array[i].token == CSS_IDENT && next_is_line_height) { keyword = m_input_buffer->GetValueSymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (keyword < 0) return INVALID; if (keyword == CSS_VALUE_inherit) line_height_keyword = keyword; else if (keyword == CSS_VALUE_normal) line_height_keyword = keyword; else return INVALID; next_is_line_height = FALSE; } else return INVALID; i++; } if ((font_family == OK || m_hld_prof && !m_hld_prof->IsInStrictMode()) && (font_size || font_size_val >= 0)) { if (!font_style) font_style = CSS_VALUE_normal; prop_list->AddTypeDeclL(CSS_PROPERTY_font_style, font_style, important, GetCurrentOrigin()); if (!font_variant) font_variant = CSS_VALUE_normal; prop_list->AddTypeDeclL(CSS_PROPERTY_font_variant, font_variant, important, GetCurrentOrigin()); if (!font_weight) font_weight = 4; if (font_weight <= 9) prop_list->AddDeclL(CSS_PROPERTY_font_weight, font_weight, CSS_NUMBER, important, GetCurrentOrigin()); else /* Relevant keywords have values greater than 9, the largest legal numeric value. */ prop_list->AddTypeDeclL(CSS_PROPERTY_font_weight, CSSValue(font_weight), important, GetCurrentOrigin()); if (font_size) prop_list->AddTypeDeclL(CSS_PROPERTY_font_size, font_size, important, GetCurrentOrigin()); else prop_list->AddDeclL(CSS_PROPERTY_font_size, font_size_val, font_size_val_type, important, GetCurrentOrigin()); if (line_height_keyword) prop_list->AddTypeDeclL(CSS_PROPERTY_line_height, line_height_keyword, important, GetCurrentOrigin()); else if (line_height < 0) prop_list->AddTypeDeclL(CSS_PROPERTY_line_height, CSS_VALUE_normal, important, GetCurrentOrigin()); else prop_list->AddDeclL(CSS_PROPERTY_line_height, line_height, line_height_type, important, GetCurrentOrigin()); return OK; } else return INVALID; } break; case CSS_PROPERTY_caption_side: if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_top || keyword == CSS_VALUE_left || keyword == CSS_VALUE_right || keyword == CSS_VALUE_bottom || keyword == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; break; case CSS_PROPERTY_visibility: if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_visible || keyword == CSS_VALUE_hidden || keyword == CSS_VALUE_collapse || keyword == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; break; case CSS_PROPERTY_box_decoration_break: if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_clone || keyword == CSS_VALUE_slice || keyword == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; break; case CSS_PROPERTY_clear: if (m_val_array.GetCount() == 1) { if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_left || keyword == CSS_VALUE_right || keyword == CSS_VALUE_none || keyword == CSS_VALUE_inherit || keyword == CSS_VALUE_both) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; } else return INVALID; break; case CSS_PROPERTY_float: if (m_val_array.GetCount() == 1) { if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); switch (keyword) { case CSS_VALUE_none: case CSS_VALUE_inherit: case CSS_VALUE_left: case CSS_VALUE_right: case CSS_VALUE__o_top: case CSS_VALUE__o_bottom: case CSS_VALUE__o_top_corner: case CSS_VALUE__o_bottom_corner: case CSS_VALUE__o_top_next_page: case CSS_VALUE__o_bottom_next_page: case CSS_VALUE__o_top_corner_next_page: case CSS_VALUE__o_bottom_corner_next_page: prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); break; default: return INVALID; } } else return INVALID; } else return INVALID; break; case CSS_PROPERTY_display: if (m_val_array.GetCount() == 1) { if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (CSS_is_display_val(keyword) || keyword == CSS_VALUE_none || keyword == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; } else return INVALID; break; case CSS_PROPERTY_text_align: if (m_val_array.GetCount() == 1) { if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (CSS_is_text_align_val(keyword) || keyword == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; } else return INVALID; break; case CSS_PROPERTY_text_transform: if (m_val_array.GetCount() == 1) { if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (CSS_is_text_transform_val(keyword) || keyword == CSS_VALUE_inherit || keyword == CSS_VALUE_none) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; } else return INVALID; break; case CSS_PROPERTY_text_decoration: { short value = 0; while (i < m_val_array.GetCount()) { if (m_val_array[i].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); switch (keyword) { case CSS_VALUE_underline: value |= CSS_TEXT_DECORATION_underline; break; case CSS_VALUE_overline: value |= CSS_TEXT_DECORATION_overline; break; case CSS_VALUE_line_through: value |= CSS_TEXT_DECORATION_line_through; break; case CSS_VALUE_blink: value |= CSS_TEXT_DECORATION_blink; break; case CSS_VALUE_inherit: case CSS_VALUE_none: if (m_val_array.GetCount() == 1) { prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); return OK; } // fall-through is intended default: return INVALID; } } else return INVALID; i++; } if (value) { /* Text decoration flags are stored as CSSValue, carefully chosen not to collide with other valid values for text-decoration. */ prop_list->AddTypeDeclL(prop, CSSValue(value), important, GetCurrentOrigin()); return OK; } } break; case CSS_PROPERTY_text_shadow: case CSS_PROPERTY_box_shadow: return SetShadowL(prop_list, prop, important); case CSS_PROPERTY__o_border_image: return SetBorderImageL(prop_list, important); case CSS_PROPERTY_vertical_align: case CSS_PROPERTY_text_indent: case CSS_PROPERTY_word_spacing: case CSS_PROPERTY_letter_spacing: if (m_val_array.GetCount() == 1) { if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit || (prop == CSS_PROPERTY_vertical_align && CSS_is_vertical_align_val(keyword)) || (keyword == CSS_VALUE_normal && (prop == CSS_PROPERTY_letter_spacing || prop == CSS_PROPERTY_word_spacing))) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else if (CSS_is_number(m_val_array[0].token) && m_val_array[0].token != CSS_DIMEN) { float length = float(m_val_array[0].value.number.number); int length_type = CSS_get_number_ext(m_val_array[0].token); if ((prop != CSS_PROPERTY_letter_spacing && prop != CSS_PROPERTY_word_spacing) || length_type != CSS_PERCENTAGE) { if (length_type == CSS_NUMBER && (length == 0 || (m_hld_prof && !m_hld_prof->IsInStrictMode()))) length_type = CSS_PX; if (length_type == CSS_PERCENTAGE || CSS_is_length_number_ext(length_type)) prop_list->AddDeclL(prop, length, length_type, important, GetCurrentOrigin()); else return INVALID; } } else return INVALID; } else return INVALID; break; case CSS_PROPERTY_list_style_position: if (m_val_array.GetCount() == 1) { if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inside || keyword == CSS_VALUE_outside || keyword == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; } else return INVALID; break; case CSS_PROPERTY_list_style_type: if (m_val_array.GetCount() == 1) { if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (CSS_is_list_style_type_val(keyword) || keyword == CSS_VALUE_none || keyword == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; } else return INVALID; break; case CSS_PROPERTY_list_style_image: #ifdef CSS_GRADIENT_SUPPORT if (CSS_is_gradient(m_val_array[i].token)) { CSS_generic_value gen_value; CSSValueType type = (CSSValueType) m_val_array[i].token; CSS_Gradient* gradient = SetGradientL(/* inout */ i, /* inout */ type); if (!gradient) return INVALID; gradients.AddObjectL(gradient); gen_value.SetValueType(type); gen_value.SetGradient(gradient); prop_list->AddDeclL(prop, &gen_value, 1, 0, important, GetCurrentOrigin()); } else #endif // CSS_GRADIENT_SUPPORT if (m_val_array.GetCount() == 1) { if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_none || keyword == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else if (m_val_array[0].token == CSS_FUNCTION_URL) { // image const uni_char* url_name = m_input_buffer->GetURLL(m_base_url, m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len).GetAttribute(URL::KUniName_Username_Password_NOT_FOR_UI).CStr(); if (url_name) prop_list->AddDeclL(prop, url_name, uni_strlen(url_name), important, GetCurrentOrigin(), CSS_string_decl::StringDeclUrl, m_hld_prof == NULL); } #ifdef SKIN_SUPPORT else if (m_val_array[0].token == CSS_FUNCTION_SKIN) { uni_char* skin_img = m_input_buffer->GetSkinString(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (skin_img) { prop_list->AddDeclL(prop, skin_img, important, GetCurrentOrigin(), CSS_string_decl::StringDeclSkin, m_hld_prof == NULL); } else LEAVE(OpStatus::ERR_NO_MEMORY); } #endif // SKIN_SUPPORT else return INVALID; } else return INVALID; break; case CSS_PROPERTY_background_image: return SetBackgroundImageL(prop_list, important); case CSS_PROPERTY_list_style: { CSSValue list_style_pos = CSS_VALUE_UNSPECIFIED; CSSValue list_style_type = CSS_VALUE_UNSPECIFIED; const uni_char* list_style_image = 0; BOOL list_style_image_is_gradient = FALSE; #ifdef CSS_GRADIENT_SUPPORT CSS_generic_value gradient_value; #endif // CSS_GRADIENT_SUPPORT uni_char* heap_list_img = 0; ANCHOR_ARRAY(uni_char, heap_list_img); // only used for skin image strings. CSS_string_decl::StringType img_type = CSS_string_decl::StringDeclUrl; BOOL inherit_list_style_image = FALSE; int seen_none = 0; while (i < m_val_array.GetCount()) { if (m_val_array[i].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (keyword == CSS_VALUE_inherit && m_val_array.GetCount() == 1) { list_style_pos = CSS_VALUE_inherit; list_style_type = CSS_VALUE_inherit; inherit_list_style_image = TRUE; } else if (!list_style_pos && (keyword == CSS_VALUE_inside || keyword == CSS_VALUE_outside)) list_style_pos = keyword; else if (!list_style_type && CSS_is_list_style_type_val(keyword)) list_style_type = keyword; else if (keyword == CSS_VALUE_none) seen_none++; else return INVALID; } else if (m_val_array[i].token == CSS_FUNCTION_URL && !list_style_image && !list_style_image_is_gradient) { // image list_style_image = m_input_buffer->GetURLL(m_base_url, m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len).GetAttribute(URL::KUniName_Username_Password_NOT_FOR_UI).CStr(); if (!list_style_image) return INVALID; } #ifdef SKIN_SUPPORT else if (m_val_array[i].token == CSS_FUNCTION_SKIN && !list_style_image && !list_style_image_is_gradient) { heap_list_img = m_input_buffer->GetSkinString(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (heap_list_img) { ANCHOR_ARRAY_RESET(heap_list_img); list_style_image = heap_list_img; img_type = CSS_string_decl::StringDeclSkin; } else LEAVE(OpStatus::ERR_NO_MEMORY); } #endif // SKIN_SUPPORT #ifdef CSS_GRADIENT_SUPPORT else if (CSS_is_gradient(m_val_array[i].token) && !list_style_image && !list_style_image_is_gradient) { list_style_image_is_gradient = TRUE; CSSValueType type = (CSSValueType) m_val_array[i].token; CSS_Gradient* gradient = SetGradientL(/* inout */ i, /* inout */ type); if (!gradient) return INVALID; gradients.AddObjectL(gradient); gradient_value.SetValueType(type); gradient_value.SetGradient(gradient); } #endif // CSS_GRADIENT_SUPPORT else return INVALID; i++; } if (seen_none) { if (!list_style_type) { list_style_type = CSS_VALUE_none; --seen_none; } if (!list_style_image && !list_style_image_is_gradient) --seen_none; if (seen_none > 0) return INVALID; } if (list_style_pos || list_style_type || list_style_image || list_style_image_is_gradient || inherit_list_style_image) { if (list_style_pos) prop_list->AddTypeDeclL(CSS_PROPERTY_list_style_position, list_style_pos, important, GetCurrentOrigin()); else prop_list->AddTypeDeclL(CSS_PROPERTY_list_style_position, CSS_VALUE_outside, important, GetCurrentOrigin()); if (list_style_type) prop_list->AddTypeDeclL(CSS_PROPERTY_list_style_type, list_style_type, important, GetCurrentOrigin()); else prop_list->AddTypeDeclL(CSS_PROPERTY_list_style_type, CSS_VALUE_disc, important, GetCurrentOrigin()); if (list_style_image) prop_list->AddDeclL(CSS_PROPERTY_list_style_image, list_style_image, uni_strlen(list_style_image), important, GetCurrentOrigin(), img_type, m_hld_prof == NULL); #ifdef CSS_GRADIENT_SUPPORT else if (list_style_image_is_gradient) prop_list->AddDeclL(CSS_PROPERTY_list_style_image, &gradient_value, 1, 0, important, GetCurrentOrigin()); #endif // CSS_GRADIENT_SUPPORT else prop_list->AddTypeDeclL(CSS_PROPERTY_list_style_image, (inherit_list_style_image ? CSS_VALUE_inherit : CSS_VALUE_none), important, GetCurrentOrigin()); return OK; } else return INVALID; } break; case CSS_PROPERTY_page: if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_auto) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else { uni_char* str = m_input_buffer->GetString(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (str) { prop_list->AddDeclL(prop, str, important, GetCurrentOrigin(), CSS_string_decl::StringDeclString, m_hld_prof == NULL); } else LEAVE(OpStatus::ERR_NO_MEMORY); } } else return INVALID; break; case CSS_PROPERTY_size: if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_auto || keyword == CSS_VALUE_portrait || keyword == CSS_VALUE_landscape || keyword == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else if (m_val_array.GetCount() == 2 && CSS_is_number(m_val_array[0].token) && CSS_is_number(m_val_array[1].token)) prop_list->AddDeclL(prop, float(m_val_array[0].value.number.number), float(m_val_array[1].value.number.number), CSS_get_number_ext(m_val_array[0].token), CSS_get_number_ext(m_val_array[1].token), important, GetCurrentOrigin()); else if (m_val_array.GetCount() == 1 && CSS_is_number(m_val_array[0].token)) prop_list->AddDeclL(prop, float(m_val_array[0].value.number.number), float(m_val_array[0].value.number.number), CSS_get_number_ext(m_val_array[0].token), CSS_get_number_ext(m_val_array[0].token), important, GetCurrentOrigin()); else return INVALID; break; case CSS_PROPERTY_clip: if (m_val_array.GetCount() > 0) { if (m_val_array.GetCount() == 6 && m_val_array[0].token == CSS_FUNCTION_RECT && m_val_array[5].token == CSS_FUNCTION_RECT) { short clip_rect_typ[4]; float clip_rect_val[4]; while (++i < m_val_array.GetCount()-1) { if (m_val_array[i].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (keyword == CSS_VALUE_auto) { clip_rect_typ[i-1] = CSS_VALUE_auto; } else return INVALID; } else if (CSS_is_number(m_val_array[i].token)) { if (!CSS_is_length_number_ext(m_val_array[i].token)) { if ((m_val_array[i].token == CSS_NUMBER && m_hld_prof && !m_hld_prof->IsInStrictMode()) || m_val_array[i].value.number.number == 0) clip_rect_typ[i-1] = CSS_PX; else return INVALID; } else clip_rect_typ[i-1] = m_val_array[i].token; clip_rect_val[i-1] = float(m_val_array[i].value.number.number); } else return INVALID; } prop_list->AddDeclL(prop, clip_rect_typ, clip_rect_val, important, GetCurrentOrigin()); } else if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_auto || keyword == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; } else return INVALID; break; case CSS_PROPERTY_cursor: if (m_val_array.GetCount() > 0 && m_val_array.GetCount()%2 == 1) { if (m_val_array[m_val_array.GetCount()-1].token != CSS_IDENT) return INVALID; for (int j=0; j<m_val_array.GetCount()-1; j++) if (j%2 == 0 && m_val_array[j].token != CSS_FUNCTION_URL || j%2 == 1 && m_val_array[j].token != CSS_COMMA) return INVALID; keyword = m_input_buffer->GetValueSymbol(m_val_array[m_val_array.GetCount()-1].value.str.start_pos, m_val_array[m_val_array.GetCount()-1].value.str.str_len); if (keyword < 0) { if (m_val_array[m_val_array.GetCount()-1].value.str.str_len == 4) { uni_char cursor_str[5]; /* ARRAY OK 2009-02-12 rune */ uni_char* string = m_input_buffer->GetString(cursor_str, m_val_array[m_val_array.GetCount()-1].value.str.start_pos, m_val_array[m_val_array.GetCount()-1].value.str.str_len); if (string) { if (uni_strni_eq_upper(string, "HAND", m_val_array[m_val_array.GetCount()-1].value.str.str_len)) keyword = CSS_VALUE_pointer; else return INVALID; } else return INVALID; } else return INVALID; } else if (!CSS_is_cursor_val(keyword) && keyword != CSS_VALUE_inherit) return INVALID; if (m_val_array.GetCount() == 1) { prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); break; } else if (keyword != CSS_VALUE_inherit) { CSS_generic_value gen_arr[CSS_MAX_ARR_SIZE]; CSS_anchored_heap_arrays<uni_char> strings; ANCHOR(CSS_anchored_heap_arrays<uni_char>, strings); int j=0; for (; i < m_val_array.GetCount()-1 && i < CSS_MAX_ARR_SIZE-1; i++) { if ((i % 2) == 1) continue; const uni_char* url_name = m_input_buffer->GetURLL(m_base_url, m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len).GetAttribute(URL::KUniName_Username_Password_NOT_FOR_UI).CStr(); gen_arr[j].value_type = CSS_FUNCTION_URL; gen_arr[j].value.string = OP_NEWA_L(uni_char, uni_strlen(url_name)+1); strings.AddArrayL(gen_arr[j].value.string); uni_strcpy(gen_arr[j++].value.string, url_name); } gen_arr[j].value_type = CSS_IDENT; gen_arr[j++].value.type = keyword; prop_list->AddDeclL(prop, gen_arr, j, 0, important, GetCurrentOrigin()); } else return INVALID; } else return INVALID; break; case CSS_PROPERTY_direction: #ifdef SUPPORT_TEXT_DIRECTION if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit || keyword == CSS_VALUE_rtl || keyword == CSS_VALUE_ltr) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; #endif break; case CSS_PROPERTY_unicode_bidi: #ifdef SUPPORT_TEXT_DIRECTION if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit || keyword == CSS_VALUE_normal || keyword == CSS_VALUE_embed || keyword == CSS_VALUE_bidi_override) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; #endif break; case CSS_PROPERTY_overflow: level++; // fall-through is intended case CSS_PROPERTY_overflow_x: case CSS_PROPERTY_overflow_y: if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); switch (keyword) { case CSS_VALUE_inherit: case CSS_VALUE_auto: case CSS_VALUE_hidden: case CSS_VALUE_visible: case CSS_VALUE_scroll: #ifdef PAGED_MEDIA_SUPPORT case CSS_VALUE__o_paged_x_controls: case CSS_VALUE__o_paged_x: case CSS_VALUE__o_paged_y_controls: case CSS_VALUE__o_paged_y: #endif // PAGED_MEDIA_SUPPORT if (level) { prop_list->AddTypeDeclL(CSS_PROPERTY_overflow_x, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_overflow_y, keyword, important, GetCurrentOrigin()); } else prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); break; default: return INVALID; } } else return INVALID; break; case CSS_PROPERTY_counter_reset: case CSS_PROPERTY_counter_increment: case CSS_PROPERTY_quotes: case CSS_PROPERTY_content: { CSS_generic_value_list gen_arr; ANCHOR(CSS_generic_value_list, gen_arr); CSS_anchored_heap_arrays<uni_char> strings; ANCHOR(CSS_anchored_heap_arrays<uni_char>, strings); while (i < m_val_array.GetCount()) { if (m_val_array[i].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (prop == CSS_PROPERTY_content && keyword >= 0 && CSS_is_quote_val(keyword)) gen_arr.PushIdentL(keyword); else if (i == 0 && m_val_array.GetCount() == 1 && (keyword == CSS_VALUE_inherit || (prop == CSS_PROPERTY_content && keyword == CSS_VALUE_normal) || keyword == CSS_VALUE_none)) { prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); return OK; } else if (prop == CSS_PROPERTY_counter_reset || prop == CSS_PROPERTY_counter_increment) { uni_char* string = m_input_buffer->GetString(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (!string) LEAVE(OpStatus::ERR_NO_MEMORY); strings.AddArrayL(string); gen_arr.PushStringL(CSS_STRING_LITERAL, string); } else return INVALID; } else if (prop == CSS_PROPERTY_quotes && m_val_array[i].token == CSS_STRING_LITERAL || (prop == CSS_PROPERTY_content && ( m_val_array[i].token == CSS_STRING_LITERAL || m_val_array[i].token == CSS_FUNCTION_COUNTER || m_val_array[i].token == CSS_FUNCTION_COUNTERS || m_val_array[i].token == CSS_FUNCTION_ATTR))) { uni_char* string = m_input_buffer->GetString(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (!string) LEAVE(OpStatus::ERR_NO_MEMORY); strings.AddArrayL(string); gen_arr.PushStringL(CSSValueType(m_val_array[i].token), string); } else if (m_val_array[i].token == CSS_NUMBER && (prop == CSS_PROPERTY_counter_reset || prop == CSS_PROPERTY_counter_increment)) { double num_val = m_val_array[i].value.number.number; if (gen_arr.Last() && gen_arr.Last()->value.GetValueType() == CSS_STRING_LITERAL && num_val == op_floor(num_val)) { int int_val; if (num_val >= INT_MAX) int_val = INT_MAX; else if (num_val <= INT_MIN) int_val = INT_MIN; else int_val = int(num_val); gen_arr.PushIntegerL(CSS_INT_NUMBER, int_val); } else return INVALID; } else if (m_val_array[i].token == CSS_FUNCTION_URL && prop == CSS_PROPERTY_content) { const uni_char* url_name = m_input_buffer->GetURLL(m_base_url, m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len).GetAttribute(URL::KUniName_Username_Password_NOT_FOR_UI).CStr(); if (url_name != NULL) { uni_char* string = OP_NEWA_L(uni_char, uni_strlen(url_name)+1); uni_strcpy(string, url_name); strings.AddArrayL(string); gen_arr.PushStringL(CSS_FUNCTION_URL, string); } } #ifdef SKIN_SUPPORT else if (m_val_array[i].token == CSS_FUNCTION_SKIN && prop == CSS_PROPERTY_content) { uni_char* skin_img = m_input_buffer->GetSkinString(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (!skin_img) LEAVE(OpStatus::ERR_NO_MEMORY); strings.AddArrayL(skin_img); gen_arr.PushStringL(CSS_FUNCTION_SKIN, skin_img); } #endif // SKIN_SUPPORT else if (m_val_array[i].token == CSS_FUNCTION_LANGUAGE_STRING && prop == CSS_PROPERTY_content) { gen_arr.PushIntegerL(CSS_FUNCTION_LANGUAGE_STRING, m_val_array[i].value.integer.integer); } else return INVALID; i++; } if (gen_arr.First() && (prop != CSS_PROPERTY_quotes || gen_arr.Cardinal() % 2 == 0)) { prop_list->AddDeclL(prop, gen_arr, 0, important, GetCurrentOrigin()); return OK; } else return INVALID; } break; #ifdef _CSS_LINK_SUPPORT_ case CSS_PROPERTY__o_link: if (i < m_val_array.GetCount()) { if (m_val_array[i].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (keyword == CSS_VALUE_none) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else if (m_val_array[i].token == CSS_FUNCTION_URL) { const uni_char* url_name = m_input_buffer->GetURLL(m_base_url, m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len).GetAttribute(URL::KUniName_Username_Password_NOT_FOR_UI).CStr(); if (url_name) prop_list->AddDeclL(prop, url_name, uni_strlen(url_name), important, GetCurrentOrigin(), CSS_string_decl::StringDeclUrl, m_hld_prof == NULL); } else if (m_val_array[i].token == CSS_STRING_LITERAL || m_val_array[i].token == CSS_FUNCTION_ATTR) { CSS_generic_value gen_arr[1]; gen_arr[0].value_type = m_val_array[i].token; gen_arr[0].value.string = m_input_buffer->GetString(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (!gen_arr[0].value.string) LEAVE(OpStatus::ERR_NO_MEMORY); uni_char* str = gen_arr[0].value.string; ANCHOR_ARRAY(uni_char, str); prop_list->AddDeclL(prop, gen_arr, 1, 0, important, GetCurrentOrigin()); } else return INVALID; } break; case CSS_PROPERTY__o_link_source: if (i < m_val_array.GetCount() && m_val_array[i].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (keyword != CSS_VALUE_none && keyword != CSS_VALUE_current && keyword != CSS_VALUE_next) return INVALID; prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); } break; #endif // _CSS_LINK_SUPPORT_ case CSS_PROPERTY_white_space: if (m_val_array.GetCount() == 1) { if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit || CSS_is_whitespace_value(keyword)) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; } else return INVALID; break; case CSS_PROPERTY_table_layout: if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit || keyword == CSS_VALUE_fixed || keyword == CSS_VALUE_auto) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; break; case CSS_PROPERTY_border_collapse: if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit || keyword == CSS_VALUE_collapse || keyword == CSS_VALUE_separate) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; break; case CSS_PROPERTY_border_spacing: if (m_val_array.GetCount() < 1 || m_val_array.GetCount() > 2) return INVALID; if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else if (CSS_is_length_number_ext(m_val_array[0].token) || m_val_array[0].token == CSS_NUMBER) { float length_val_1 = float(m_val_array[0].value.number.number); int length_type_1 = CSS_get_number_ext(m_val_array[0].token); if (length_val_1 < 0) return INVALID; if (length_type_1 == CSS_NUMBER) { if (length_val_1 == 0 || m_hld_prof && !m_hld_prof->IsInStrictMode()) length_type_1 = CSS_PX; else return INVALID; } if (m_val_array.GetCount() == 2) { if (CSS_is_length_number_ext(m_val_array[1].token) || m_val_array[1].token == CSS_NUMBER) { float length_val_2 = float(m_val_array[1].value.number.number); int length_type_2 = CSS_get_number_ext(m_val_array[1].token); if (length_val_2 < 0) return INVALID; if (length_type_2 == CSS_NUMBER && (length_val_2 == 0 || m_hld_prof && !m_hld_prof->IsInStrictMode())) { if (length_val_2 == 0 || m_hld_prof && !m_hld_prof->IsInStrictMode()) length_type_2 = CSS_PX; else return INVALID; } prop_list->AddDeclL(prop, length_val_1, length_val_2, length_type_1, length_type_2, important, GetCurrentOrigin()); } else return INVALID; } else prop_list->AddDeclL(prop, length_val_1, length_type_1, important, GetCurrentOrigin()); } else return INVALID; break; case CSS_PROPERTY_empty_cells: if (m_val_array.GetCount() == 1 && m_val_array[i].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (keyword == CSS_VALUE_inherit || keyword == CSS_VALUE_show || keyword == CSS_VALUE_hide) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; break; case CSS_PROPERTY_z_index: case CSS_PROPERTY_order: #ifdef WEBKIT_OLD_FLEXBOX case CSS_PROPERTY__webkit_box_ordinal_group: #endif // WEBKIT_OLD_FLEXBOX if (m_val_array.GetCount() != 1) return INVALID; if (m_val_array[0].token == CSS_IDENT) { keyword = GetKeyword(0); if (keyword == CSS_VALUE_inherit || keyword == CSS_VALUE_auto && prop == CSS_PROPERTY_z_index) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else if (CSS_is_number(m_val_array[0].token) && CSS_get_number_ext(m_val_array[0].token) == CSS_NUMBER) { int num; if (m_val_array[0].value.number.number >= INT_MAX) num = INT_MAX; else if (m_val_array[0].value.number.number <= INT_MIN) num = INT_MIN; else num = int(m_val_array[0].value.number.number); prop_list->AddLongDeclL(prop, (long)num, important, GetCurrentOrigin()); } else return INVALID; break; case CSS_PROPERTY_justify_content: case CSS_PROPERTY_align_content: if (m_val_array.GetCount() != 1 || m_val_array[0].token != CSS_IDENT) return INVALID; keyword = GetKeyword(0); switch (keyword) { case CSS_VALUE_stretch: if (prop != CSS_PROPERTY_align_content) return INVALID; // fall-through case CSS_VALUE_inherit: case CSS_VALUE_flex_start: case CSS_VALUE_flex_end: case CSS_VALUE_center: case CSS_VALUE_space_between: case CSS_VALUE_space_around: prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); break; default: return INVALID; } break; case CSS_PROPERTY_align_items: case CSS_PROPERTY_align_self: if (m_val_array.GetCount() != 1 || m_val_array[0].token != CSS_IDENT) return INVALID; keyword = GetKeyword(0); switch (keyword) { case CSS_VALUE_auto: if (prop != CSS_PROPERTY_align_self) return INVALID; // fall-through case CSS_VALUE_inherit: case CSS_VALUE_flex_start: case CSS_VALUE_flex_end: case CSS_VALUE_center: case CSS_VALUE_baseline: case CSS_VALUE_stretch: prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); break; default: return INVALID; } break; #ifdef WEBKIT_OLD_FLEXBOX case CSS_PROPERTY__webkit_box_flex: #endif // WEBKIT_OLD_FLEXBOX case CSS_PROPERTY_flex_grow: case CSS_PROPERTY_flex_shrink: if (m_val_array.GetCount() != 1) return INVALID; if (m_val_array[0].token == CSS_IDENT) { keyword = GetKeyword(0); if (keyword == CSS_VALUE_inherit || keyword == CSS_VALUE_initial && (prop == CSS_PROPERTY_flex_grow || prop == CSS_PROPERTY_flex_shrink)) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else if (CSS_is_number(m_val_array[0].token) && CSS_get_number_ext(m_val_array[0].token) == CSS_NUMBER) { float value = float(m_val_array[0].value.number.number); if (value < 0.0) return INVALID; prop_list->AddDeclL(prop, value, CSS_NUMBER, important, GetCurrentOrigin()); } else return INVALID; break; case CSS_PROPERTY_flex_flow: { if (m_val_array.GetCount() < 1 || m_val_array.GetCount() > 2) return INVALID; CSSValue direction = CSS_VALUE_UNSPECIFIED; CSSValue wrap = CSS_VALUE_UNSPECIFIED; // First verify that the declaration is valid. for (int i = 0; i < m_val_array.GetCount(); i++) if (m_val_array[i].token == CSS_IDENT) { keyword = GetKeyword(i); if (keyword == CSS_VALUE_inherit) { if (m_val_array.GetCount() == 1) { // Value is inherit. Add it right away and return. prop_list->AddTypeDeclL(CSS_PROPERTY_flex_direction, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_flex_wrap, keyword, important, GetCurrentOrigin()); return OK; } else return INVALID; } else if (IsFlexDirectionValue(CSSValue(keyword))) if (direction == CSS_VALUE_UNSPECIFIED) direction = CSSValue(keyword); else return INVALID; else if (IsFlexWrapValue(CSSValue(keyword))) if (wrap == CSS_VALUE_UNSPECIFIED) wrap = CSSValue(keyword); else return INVALID; else return INVALID; } else return INVALID; // All OK. Add declarations. if (direction == CSS_VALUE_UNSPECIFIED) direction = CSS_VALUE_row; if (wrap == CSS_VALUE_UNSPECIFIED) wrap = CSS_VALUE_nowrap; prop_list->AddTypeDeclL(CSS_PROPERTY_flex_direction, direction, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_flex_wrap, wrap, important, GetCurrentOrigin()); } break; case CSS_PROPERTY_flex_direction: if (m_val_array.GetCount() != 1 || m_val_array[0].token != CSS_IDENT) return INVALID; keyword = GetKeyword(0); if (IsFlexDirectionValue(CSSValue(keyword))) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; break; case CSS_PROPERTY_flex_wrap: if (m_val_array.GetCount() != 1 || m_val_array[0].token != CSS_IDENT) return INVALID; keyword = GetKeyword(0); if (IsFlexWrapValue(CSSValue(keyword))) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; break; case CSS_PROPERTY_flex_basis: { CSS_generic_value preferred_size; if (CSS_is_number(m_val_array[i].token)) { if (m_val_array[i].token == CSS_DIMEN) return INVALID; preferred_size.value_type = m_val_array[i].token; preferred_size.value.real = float(m_val_array[i].value.number.number); } else if (m_val_array[i].token == CSS_IDENT) { keyword = GetKeyword(i); if (keyword != CSS_VALUE_inherit && keyword != CSS_VALUE_initial && keyword != CSS_VALUE_auto && keyword != CSS_VALUE__o_skin && keyword != CSS_VALUE__o_content_size) return INVALID; preferred_size.value_type = CSS_IDENT; preferred_size.value.type = keyword; } else return INVALID; if (preferred_size.value_type == CSS_IDENT) prop_list->AddTypeDeclL(CSS_PROPERTY_flex_basis, CSSValue(preferred_size.value.type), important, GetCurrentOrigin()); else prop_list->AddDeclL(CSS_PROPERTY_flex_basis, preferred_size.value.real, preferred_size.value_type, important, GetCurrentOrigin()); break; } case CSS_PROPERTY_flex: { int val_count = m_val_array.GetCount(); if (val_count < 1 || val_count > 3) return INVALID; if (val_count == 1 && m_val_array[0].token == CSS_IDENT) { keyword = GetKeyword(0); if (keyword == CSS_VALUE_inherit || keyword == CSS_VALUE_initial) { prop_list->AddTypeDeclL(CSS_PROPERTY_flex_grow, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_flex_shrink, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_flex_basis, keyword, important, GetCurrentOrigin()); break; } else if (keyword == CSS_VALUE_none) { prop_list->AddDeclL(CSS_PROPERTY_flex_grow, float(0.0), CSS_NUMBER, important, GetCurrentOrigin()); prop_list->AddDeclL(CSS_PROPERTY_flex_shrink, float(0.0), CSS_NUMBER, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_flex_basis, CSS_VALUE_auto, important, GetCurrentOrigin()); break; } // Other keywords than the above will be attempted parsed as <flex-basis>. } int flexcount = 0; float flex_grow = 1.0; float flex_shrink = 1.0; CSS_generic_value preferred_size; BOOL has_preferred_size = FALSE; preferred_size.value_type = CSS_PX; preferred_size.value.real = 0.0; for (int i = 0; i < val_count; i++) if (m_val_array[i].token == CSS_NUMBER) { /* <flex-grow> or <flex-shrink>, or zero <flex-basis> preceded by both <flex-grow> and <flex-shrink> */ float number = float(m_val_array[i].value.number.number); if (number < 0.0) return INVALID; if (flexcount >= 2) { /* This is a unit-less number, but two have already been supplied. That means that this one has be treated as flex-basis, i.e. a length. The only valid unit-less length is 0. */ if (number == 0.0) { preferred_size.value_type = CSS_PX; preferred_size.value.real = number; has_preferred_size = TRUE; } else return INVALID; } else if (flexcount++ == 0) flex_grow = number; else flex_shrink = number; } else { // <flex-basis> (or something illegal) if (flexcount == 1) /* We have parsed <flex-grow>, but not <flex-shrink>. <flex-grow> and <flex-shrink> must be specified next to each other (and in that order) if one wants to specify both. This means that the opportunity to specify <flex-shrink> was waived. */ flexcount = 2; if (has_preferred_size) return INVALID; if (CSS_is_number(m_val_array[i].token)) { if (m_val_array[i].token == CSS_DIMEN) return INVALID; preferred_size.value_type = m_val_array[i].token; preferred_size.value.real = float(m_val_array[i].value.number.number); } else if (m_val_array[i].token == CSS_IDENT) { keyword = GetKeyword(i); if (keyword != CSS_VALUE_auto && keyword != CSS_VALUE__o_skin && keyword != CSS_VALUE__o_content_size) return INVALID; preferred_size.value_type = CSS_IDENT; preferred_size.value.type = keyword; } else return INVALID; has_preferred_size = TRUE; } prop_list->AddDeclL(CSS_PROPERTY_flex_grow, flex_grow, CSS_NUMBER, important, GetCurrentOrigin()); prop_list->AddDeclL(CSS_PROPERTY_flex_shrink, flex_shrink, CSS_NUMBER, important, GetCurrentOrigin()); if (preferred_size.value_type == CSS_IDENT) prop_list->AddTypeDeclL(CSS_PROPERTY_flex_basis, CSSValue(preferred_size.value.type), important, GetCurrentOrigin()); else prop_list->AddDeclL(CSS_PROPERTY_flex_basis, preferred_size.value.real, preferred_size.value_type, important, GetCurrentOrigin()); break; } #ifdef WEBKIT_OLD_FLEXBOX case CSS_PROPERTY__webkit_box_pack: if (m_val_array.GetCount() != 1 || m_val_array[0].token != CSS_IDENT) return INVALID; keyword = GetKeyword(0); if (keyword == CSS_VALUE_inherit || keyword == CSS_VALUE_start || keyword == CSS_VALUE_end || keyword == CSS_VALUE_center || keyword == CSS_VALUE_justify) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; break; case CSS_PROPERTY__webkit_box_align: if (m_val_array.GetCount() != 1 || m_val_array[0].token != CSS_IDENT) return INVALID; keyword = GetKeyword(0); if (keyword == CSS_VALUE_inherit || keyword == CSS_VALUE_start || keyword == CSS_VALUE_end || keyword == CSS_VALUE_center || keyword == CSS_VALUE_baseline || keyword == CSS_VALUE_stretch) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; break; case CSS_PROPERTY__webkit_box_orient: if (m_val_array.GetCount() != 1 || m_val_array[0].token != CSS_IDENT) return INVALID; keyword = GetKeyword(0); if (keyword == CSS_VALUE_horizontal || keyword == CSS_VALUE_vertical || keyword == CSS_VALUE_inline_axis || keyword == CSS_VALUE_block_axis || keyword == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; break; case CSS_PROPERTY__webkit_box_direction: if (m_val_array.GetCount() != 1 || m_val_array[0].token != CSS_IDENT) return INVALID; keyword = GetKeyword(0); if (keyword == CSS_VALUE_normal || keyword == CSS_VALUE_reverse || keyword == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; break; case CSS_PROPERTY__webkit_box_lines: if (m_val_array.GetCount() != 1 || m_val_array[0].token != CSS_IDENT) return INVALID; keyword = GetKeyword(0); if (keyword == CSS_VALUE_single || keyword == CSS_VALUE_multiple || keyword == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; break; #endif // WEBKIT_OLD_FLEXBOX case CSS_PROPERTY_columns: { if (m_val_array.GetCount() < 1 || m_val_array.GetCount() > 2) return INVALID; long column_count = LONG_MIN; float column_width = -1.0; short column_width_ext = 0; // First verify that the declaration is valid. for (int i = 0; i < m_val_array.GetCount(); i++) { if (CSS_is_number(m_val_array[i].token) && CSS_get_number_ext(m_val_array[i].token) == CSS_NUMBER && m_val_array[i].value.number.number > 0) if (column_count > 0) return INVALID; else column_count = (long)MIN(m_val_array[i].value.number.number, SHRT_MAX); else if (CSS_is_length_number_ext(m_val_array[i].token) && m_val_array[i].value.number.number > 0 && CSS_get_number_ext(m_val_array[i].token) != CSS_PERCENTAGE) if (column_width > 0) return INVALID; else { column_width = (float)m_val_array[i].value.number.number; column_width_ext = CSS_get_number_ext(m_val_array[i].token); } else if (m_val_array[i].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (keyword == CSS_VALUE_inherit) if (m_val_array.GetCount() == 1) { // Value is inherit. Add it right away and return. prop_list->AddTypeDeclL(CSS_PROPERTY_column_width, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_column_count, keyword, important, GetCurrentOrigin()); return OK; } else return INVALID; else if (keyword != CSS_VALUE_auto) return INVALID; } else return INVALID; } // All OK. Add declaration(s). if (column_width > 0) prop_list->AddDeclL(CSS_PROPERTY_column_width, column_width, column_width_ext, important, GetCurrentOrigin()); else prop_list->AddTypeDeclL(CSS_PROPERTY_column_width, CSS_VALUE_auto, important, GetCurrentOrigin()); if (column_count > 0) prop_list->AddLongDeclL(CSS_PROPERTY_column_count, column_count, important, GetCurrentOrigin()); else prop_list->AddTypeDeclL(CSS_PROPERTY_column_count, CSS_VALUE_auto, important, GetCurrentOrigin()); } break; case CSS_PROPERTY_column_count: if (m_val_array.GetCount() != 1) return INVALID; if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit || keyword == CSS_VALUE_auto) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else if (CSS_is_number(m_val_array[0].token) && CSS_get_number_ext(m_val_array[0].token) == CSS_NUMBER && m_val_array[0].value.number.number > 0) { int num = int(m_val_array[0].value.number.number); prop_list->AddLongDeclL(prop, (long)MIN(num, SHRT_MAX), important, GetCurrentOrigin()); } else return INVALID; break; case CSS_PROPERTY_column_fill: if (m_val_array.GetCount() != 1) return INVALID; if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit || keyword == CSS_VALUE_auto || keyword == CSS_VALUE_balance) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; break; case CSS_PROPERTY_column_span: if (m_val_array.GetCount() != 1) return INVALID; if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit || keyword == CSS_VALUE_all || keyword == CSS_VALUE_none) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else if (m_val_array[0].token == CSS_FUNCTION_INTEGER && m_val_array[0].value.integer.integer > 0) prop_list->AddLongDeclL(prop, (long)MIN(m_val_array[0].value.integer.integer, SHRT_MAX), important, GetCurrentOrigin()); else return INVALID; break; case CSS_PROPERTY_position: if (m_val_array.GetCount() != 1) return INVALID; if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit || keyword == CSS_VALUE_static || keyword == CSS_VALUE_absolute || keyword == CSS_VALUE_relative || keyword == CSS_VALUE_fixed) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } break; case CSS_PROPERTY_widows: case CSS_PROPERTY_orphans: if (m_val_array.GetCount() != 1) return INVALID; if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else if (CSS_is_number(m_val_array[0].token) && CSS_get_number_ext(m_val_array[0].token) == CSS_NUMBER) { int num = (int)m_val_array[0].value.number.number; if (num >= 0) prop_list->AddLongDeclL(prop, (long)num, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; break; case CSS_PROPERTY_page_break_after: case CSS_PROPERTY_page_break_before: case CSS_PROPERTY_page_break_inside: if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_avoid || keyword == CSS_VALUE_auto || keyword == CSS_VALUE_inherit || (prop != CSS_PROPERTY_page_break_inside && (keyword == CSS_VALUE_always || keyword == CSS_VALUE_left || keyword == CSS_VALUE_right))) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; break; case CSS_PROPERTY_break_after: case CSS_PROPERTY_break_before: case CSS_PROPERTY_break_inside: if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); switch (keyword) { case CSS_VALUE_always: case CSS_VALUE_left: case CSS_VALUE_right: case CSS_VALUE_page: case CSS_VALUE_column: if (prop == CSS_PROPERTY_break_inside) return INVALID; // fall-through case CSS_VALUE_avoid: case CSS_VALUE_avoid_page: case CSS_VALUE_avoid_column: case CSS_VALUE_auto: case CSS_VALUE_inherit: prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); break; default: return INVALID; } } else return INVALID; break; #ifdef SVG_SUPPORT case CSS_PROPERTY_fill: case CSS_PROPERTY_stroke: if (m_val_array.GetCount() >= 1 && m_val_array[0].token == CSS_FUNCTION_URL) return SetPaintUriL(prop_list, prop, important); // fall-through is intended case CSS_PROPERTY_stop_color: case CSS_PROPERTY_flood_color: case CSS_PROPERTY_lighting_color: case CSS_PROPERTY_solid_color: case CSS_PROPERTY_viewport_fill: if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit || keyword == CSS_VALUE_none || keyword == CSS_VALUE_currentColor) { prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); return OK; } } // fall-through is intended #endif case CSS_PROPERTY_color: case CSS_PROPERTY_outline_color: case CSS_PROPERTY_column_rule_color: case CSS_PROPERTY_background_color: case CSS_PROPERTY_border_top_color: case CSS_PROPERTY_border_left_color: case CSS_PROPERTY_border_right_color: case CSS_PROPERTY_border_bottom_color: case CSS_PROPERTY_scrollbar_base_color: case CSS_PROPERTY_scrollbar_face_color: case CSS_PROPERTY_scrollbar_arrow_color: case CSS_PROPERTY_scrollbar_track_color: case CSS_PROPERTY_scrollbar_shadow_color: case CSS_PROPERTY_scrollbar_3dlight_color: case CSS_PROPERTY_scrollbar_highlight_color: case CSS_PROPERTY_scrollbar_darkshadow_color: if (m_val_array.GetCount() == 1) { COLORREF color; uni_char* skin_color = NULL; switch (SetColorL(color, keyword, skin_color, m_val_array[0])) { case COLOR_KEYWORD: if (keyword == CSS_VALUE_transparent || (keyword == CSS_VALUE_invert && prop == CSS_PROPERTY_outline_color) || keyword == CSS_VALUE_inherit || keyword == CSS_VALUE_currentColor) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); return OK; case COLOR_RGBA: prop_list->AddLongDeclL(prop, (long)color, important, GetCurrentOrigin()); return OK; case COLOR_NAMED: prop_list->AddColorDeclL(prop, color, important, GetCurrentOrigin()); return OK; #ifdef SKIN_SUPPORT case COLOR_SKIN: prop_list->AddDeclL(prop, skin_color, important, GetCurrentOrigin(), CSS_string_decl::StringDeclSkin, FALSE); return OK; #endif // SKIN_SUPPORT case COLOR_INVALID: return INVALID; } } return INVALID; case CSS_PROPERTY_background_position: return SetPositionL(prop_list, important, prop); case CSS_PROPERTY_background_repeat: return SetBackgroundRepeatL(prop_list, important); case CSS_PROPERTY_background_attachment: case CSS_PROPERTY_background_origin: case CSS_PROPERTY_background_clip: return SetBackgroundListL(prop_list, prop, important); case CSS_PROPERTY_background: return SetBackgroundShorthandL(prop_list, important); case CSS_PROPERTY_background_size: return SetBackgroundSizeL(prop_list, important); case CSS_PROPERTY__o_object_fit: if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (CSS_is_object_fit_val(keyword) || keyword == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; break; case CSS_PROPERTY__o_object_position: return SetPositionL(prop_list, important, prop); case CSS_PROPERTY_border: case CSS_PROPERTY_outline: case CSS_PROPERTY_column_rule: level++; // fall-through is intended case CSS_PROPERTY_border_top: case CSS_PROPERTY_border_left: case CSS_PROPERTY_border_right: case CSS_PROPERTY_border_bottom: level++; // fall-through is intended case CSS_PROPERTY_outline_style: case CSS_PROPERTY_column_rule_style: case CSS_PROPERTY_border_top_style: case CSS_PROPERTY_border_left_style: case CSS_PROPERTY_border_right_style: case CSS_PROPERTY_border_bottom_style: case CSS_PROPERTY_outline_width: case CSS_PROPERTY_column_rule_width: case CSS_PROPERTY_border_top_width: case CSS_PROPERTY_border_left_width: case CSS_PROPERTY_border_right_width: case CSS_PROPERTY_border_bottom_width: case CSS_PROPERTY_outline_offset: { CSSValue style_value = CSS_VALUE_UNSPECIFIED; CSSValue invert_keyword = CSS_VALUE_none; COLORREF col = USE_DEFAULT_COLOR; BOOL set_color = FALSE; float width = 0.0f; int width_type = CSS_DIM_TYPE; BOOL set_width = FALSE; BOOL set_keyword_width = TRUE; CSSValue width_keyword = CSS_VALUE_medium; BOOL is_color_keyword = FALSE; CSSValue transparent_keyword = CSS_VALUE_none; while (i < m_val_array.GetCount()) { if (m_val_array[i].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (keyword < 0) { if (!level) return INVALID; col = m_input_buffer->GetNamedColorIndex(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (col != USE_DEFAULT_COLOR) set_color = TRUE; else if (m_hld_prof && !m_hld_prof->IsInStrictMode()) { col = m_input_buffer->GetNamedColorIndex(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (col == USE_DEFAULT_COLOR) col = m_input_buffer->GetColor(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (col == USE_DEFAULT_COLOR) return INVALID; set_color = TRUE; } else return INVALID; } else if (keyword == CSS_VALUE_inherit && m_val_array.GetCount() == 1) { if (!level) { prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); } else { if (prop == CSS_PROPERTY_border || prop == CSS_PROPERTY_border_top) { prop_list->AddTypeDeclL(CSS_PROPERTY_border_top_color, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_border_top_style, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_border_top_width, keyword, important, GetCurrentOrigin()); } if (prop == CSS_PROPERTY_border || prop == CSS_PROPERTY_border_left) { prop_list->AddTypeDeclL(CSS_PROPERTY_border_left_color, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_border_left_style, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_border_left_width, keyword, important, GetCurrentOrigin()); } if (prop == CSS_PROPERTY_border || prop == CSS_PROPERTY_border_right) { prop_list->AddTypeDeclL(CSS_PROPERTY_border_right_color, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_border_right_style, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_border_right_width, keyword, important, GetCurrentOrigin()); } if (prop == CSS_PROPERTY_border || prop == CSS_PROPERTY_border_bottom) { prop_list->AddTypeDeclL(CSS_PROPERTY_border_bottom_color, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_border_bottom_style, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_border_bottom_width, keyword, important, GetCurrentOrigin()); } if (prop == CSS_PROPERTY_outline) { prop_list->AddTypeDeclL(CSS_PROPERTY_outline_color, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_outline_style, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_outline_width, keyword, important, GetCurrentOrigin()); } if (prop == CSS_PROPERTY_column_rule) { prop_list->AddTypeDeclL(CSS_PROPERTY_column_rule_color, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_column_rule_style, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_column_rule_width, keyword, important, GetCurrentOrigin()); } } return OK; } else if (CSS_is_border_style_val(keyword) || keyword == CSS_VALUE_none) { if (style_value || (prop == CSS_PROPERTY_outline_style && keyword == CSS_VALUE_hidden)) return INVALID; if (!level && prop != CSS_PROPERTY_border_top_style && prop != CSS_PROPERTY_border_left_style && prop != CSS_PROPERTY_border_right_style && prop != CSS_PROPERTY_border_bottom_style && prop != CSS_PROPERTY_outline_style && prop != CSS_PROPERTY_column_rule_style) return INVALID; style_value = keyword; } else if (CSS_is_color_val(keyword)) { if (set_color || !level) return INVALID; if (CSS_is_ui_color_val(keyword)) col = keyword | CSS_COLOR_KEYWORD_TYPE_ui_color; else col = m_input_buffer->GetNamedColorIndex(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); set_color = TRUE; is_color_keyword = TRUE; } else if (CSS_is_border_width_val(keyword) && prop != CSS_PROPERTY_outline_offset) { if (set_width) return INVALID; set_width = TRUE; set_keyword_width = TRUE; width_keyword = keyword; } else if (keyword == CSS_VALUE_invert) { if (set_color || !level) return INVALID; set_color = TRUE; invert_keyword = keyword; } else if (keyword == CSS_VALUE_transparent || keyword == CSS_VALUE_currentColor) { if (set_color || !level) return INVALID; set_color = TRUE; transparent_keyword = keyword; } else return INVALID; } else if (m_val_array[i].token == CSS_FUNCTION_RGB || SupportsAlpha() && m_val_array[i].token == CSS_FUNCTION_RGBA) { // color if (set_color || !level) return INVALID; col = m_val_array[i].value.color; set_color = TRUE; } else if (m_val_array[i].token == CSS_HASH) { col = m_input_buffer->GetColor(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (set_color || !level || col == USE_DEFAULT_COLOR) return INVALID; set_color = TRUE; } else if (m_val_array[i].token == CSS_DIMEN) { // hack for supporting hex-colors without # if (set_color || !level || !m_hld_prof || m_hld_prof->IsInStrictMode()) return INVALID; if (m_val_array[i].value.number.str_len == 3 || m_val_array[i].value.number.str_len == 6) col = m_input_buffer->GetColor(m_val_array[i].value.number.start_pos, m_val_array[i].value.number.str_len); if (col == USE_DEFAULT_COLOR) return INVALID; set_color = TRUE; } else if (CSS_is_length_number_ext(m_val_array[i].token) || m_val_array[i].token == CSS_NUMBER) { width = float(m_val_array[i].value.number.number); width_type = CSS_get_number_ext(m_val_array[i].token); if (set_width || width < 0 && prop != CSS_PROPERTY_outline_offset || width > 0 && width_type == CSS_NUMBER && (!m_hld_prof || m_hld_prof->IsInStrictMode())) return INVALID; //units are required if not 0 if (width_type == CSS_NUMBER) width_type = CSS_PX; set_width = TRUE; set_keyword_width = FALSE; } else return INVALID; i++; } if (set_width && !level && prop != CSS_PROPERTY_border_top_width && prop != CSS_PROPERTY_border_left_width && prop != CSS_PROPERTY_border_right_width && prop != CSS_PROPERTY_border_bottom_width && prop != CSS_PROPERTY_outline_width && prop != CSS_PROPERTY_outline_offset && prop != CSS_PROPERTY_column_rule_width) return INVALID; // Don't return INVALID below this point for these cases. if (set_color || level) { if (invert_keyword != CSS_VALUE_none) { prop_list->AddTypeDeclL(CSS_PROPERTY_outline_color, invert_keyword, important, GetCurrentOrigin()); } else if (transparent_keyword != CSS_VALUE_none || !is_color_keyword && col == USE_DEFAULT_COLOR) { if (transparent_keyword == CSS_VALUE_none) transparent_keyword = CSS_VALUE_currentColor; if (prop == CSS_PROPERTY_border || prop == CSS_PROPERTY_border_top) prop_list->AddTypeDeclL(CSS_PROPERTY_border_top_color, transparent_keyword, important, GetCurrentOrigin()); if (prop == CSS_PROPERTY_border || prop == CSS_PROPERTY_border_left) prop_list->AddTypeDeclL(CSS_PROPERTY_border_left_color, transparent_keyword, important, GetCurrentOrigin()); if (prop == CSS_PROPERTY_border || prop == CSS_PROPERTY_border_right) prop_list->AddTypeDeclL(CSS_PROPERTY_border_right_color, transparent_keyword, important, GetCurrentOrigin()); if (prop == CSS_PROPERTY_border || prop == CSS_PROPERTY_border_bottom) prop_list->AddTypeDeclL(CSS_PROPERTY_border_bottom_color, transparent_keyword, important, GetCurrentOrigin()); if (prop == CSS_PROPERTY_outline) prop_list->AddTypeDeclL(CSS_PROPERTY_outline_color, transparent_keyword, important, GetCurrentOrigin()); } else if (is_color_keyword) { if (prop == CSS_PROPERTY_border || prop == CSS_PROPERTY_border_top) prop_list->AddColorDeclL(CSS_PROPERTY_border_top_color, col, important, GetCurrentOrigin()); if (prop == CSS_PROPERTY_border || prop == CSS_PROPERTY_border_left) prop_list->AddColorDeclL(CSS_PROPERTY_border_left_color, col, important, GetCurrentOrigin()); if (prop == CSS_PROPERTY_border || prop == CSS_PROPERTY_border_right) prop_list->AddColorDeclL(CSS_PROPERTY_border_right_color, col, important, GetCurrentOrigin()); if (prop == CSS_PROPERTY_border || prop == CSS_PROPERTY_border_bottom) prop_list->AddColorDeclL(CSS_PROPERTY_border_bottom_color, col, important, GetCurrentOrigin()); if (prop == CSS_PROPERTY_outline) prop_list->AddColorDeclL(CSS_PROPERTY_outline_color, col, important, GetCurrentOrigin()); if (prop == CSS_PROPERTY_column_rule) prop_list->AddColorDeclL(CSS_PROPERTY_column_rule_color, col, important, GetCurrentOrigin()); } else { if (prop == CSS_PROPERTY_border || prop == CSS_PROPERTY_border_top) prop_list->AddLongDeclL(CSS_PROPERTY_border_top_color, (long)col, important, GetCurrentOrigin()); if (prop == CSS_PROPERTY_border || prop == CSS_PROPERTY_border_left) prop_list->AddLongDeclL(CSS_PROPERTY_border_left_color, (long)col, important, GetCurrentOrigin()); if (prop == CSS_PROPERTY_border || prop == CSS_PROPERTY_border_right) prop_list->AddLongDeclL(CSS_PROPERTY_border_right_color, (long)col, important, GetCurrentOrigin()); if (prop == CSS_PROPERTY_border || prop == CSS_PROPERTY_border_bottom) prop_list->AddLongDeclL(CSS_PROPERTY_border_bottom_color, (long)col, important, GetCurrentOrigin()); if (prop == CSS_PROPERTY_outline) prop_list->AddLongDeclL(CSS_PROPERTY_outline_color, (long)col, important, GetCurrentOrigin()); if (prop == CSS_PROPERTY_column_rule) prop_list->AddLongDeclL(CSS_PROPERTY_column_rule_color, (long)col, important, GetCurrentOrigin()); } } if (set_width || level) { if (prop == CSS_PROPERTY_border || prop == CSS_PROPERTY_border_top || prop == CSS_PROPERTY_border_top_width) { if (set_keyword_width) prop_list->AddTypeDeclL(CSS_PROPERTY_border_top_width, width_keyword, important, GetCurrentOrigin()); else prop_list->AddDeclL(CSS_PROPERTY_border_top_width, width, width_type, important, GetCurrentOrigin()); } if (prop == CSS_PROPERTY_border || prop == CSS_PROPERTY_border_left || prop == CSS_PROPERTY_border_left_width) { if (set_keyword_width) prop_list->AddTypeDeclL(CSS_PROPERTY_border_left_width, width_keyword, important, GetCurrentOrigin()); else prop_list->AddDeclL(CSS_PROPERTY_border_left_width, width, width_type, important, GetCurrentOrigin()); } if (prop == CSS_PROPERTY_border || prop == CSS_PROPERTY_border_right || prop == CSS_PROPERTY_border_right_width) { if (set_keyword_width) prop_list->AddTypeDeclL(CSS_PROPERTY_border_right_width, width_keyword, important, GetCurrentOrigin()); else prop_list->AddDeclL(CSS_PROPERTY_border_right_width, width, width_type, important, GetCurrentOrigin()); } if (prop == CSS_PROPERTY_border || prop == CSS_PROPERTY_border_bottom || prop == CSS_PROPERTY_border_bottom_width) { if (set_keyword_width) prop_list->AddTypeDeclL(CSS_PROPERTY_border_bottom_width, width_keyword, important, GetCurrentOrigin()); else prop_list->AddDeclL(CSS_PROPERTY_border_bottom_width, width, width_type, important, GetCurrentOrigin()); } if (prop == CSS_PROPERTY_outline || prop == CSS_PROPERTY_outline_width) { if (set_keyword_width) prop_list->AddTypeDeclL(CSS_PROPERTY_outline_width, width_keyword, important, GetCurrentOrigin()); else prop_list->AddDeclL(CSS_PROPERTY_outline_width, width, width_type, important, GetCurrentOrigin()); } else if (prop == CSS_PROPERTY_outline_offset) prop_list->AddDeclL(CSS_PROPERTY_outline_offset, width, width_type, important, GetCurrentOrigin()); if (prop == CSS_PROPERTY_column_rule || prop == CSS_PROPERTY_column_rule_width) { if (set_keyword_width) prop_list->AddTypeDeclL(CSS_PROPERTY_column_rule_width, width_keyword, important, GetCurrentOrigin()); else prop_list->AddDeclL(CSS_PROPERTY_column_rule_width, width, width_type, important, GetCurrentOrigin()); } } if (!style_value && level) style_value = CSS_VALUE_none; if (style_value) { if (prop == CSS_PROPERTY_border || prop == CSS_PROPERTY_border_top || prop == CSS_PROPERTY_border_top_style) prop_list->AddTypeDeclL(CSS_PROPERTY_border_top_style, style_value, important, GetCurrentOrigin()); if (prop == CSS_PROPERTY_border || prop == CSS_PROPERTY_border_left || prop == CSS_PROPERTY_border_left_style) prop_list->AddTypeDeclL(CSS_PROPERTY_border_left_style, style_value, important, GetCurrentOrigin()); if (prop == CSS_PROPERTY_border || prop == CSS_PROPERTY_border_right || prop == CSS_PROPERTY_border_right_style) prop_list->AddTypeDeclL(CSS_PROPERTY_border_right_style, style_value, important, GetCurrentOrigin()); if (prop == CSS_PROPERTY_border || prop == CSS_PROPERTY_border_bottom || prop == CSS_PROPERTY_border_bottom_style) prop_list->AddTypeDeclL(CSS_PROPERTY_border_bottom_style, style_value, important, GetCurrentOrigin()); if (prop == CSS_PROPERTY_outline || prop == CSS_PROPERTY_outline_style) prop_list->AddTypeDeclL(CSS_PROPERTY_outline_style, style_value, important, GetCurrentOrigin()); if (prop == CSS_PROPERTY_column_rule || prop == CSS_PROPERTY_column_rule_style) prop_list->AddTypeDeclL(CSS_PROPERTY_column_rule_style, style_value, important, GetCurrentOrigin()); } } break; case CSS_PROPERTY_box_sizing: { if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); switch (keyword) { case CSS_VALUE_content_box: case CSS_VALUE_border_box: case CSS_VALUE_inherit: prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); break; default: return INVALID; } } else return INVALID; } break; #ifdef SVG_SUPPORT case CSS_PROPERTY_stop_opacity: case CSS_PROPERTY_stroke_opacity: case CSS_PROPERTY_fill_opacity: case CSS_PROPERTY_flood_opacity: case CSS_PROPERTY_viewport_fill_opacity: case CSS_PROPERTY_solid_opacity: #endif case CSS_PROPERTY_opacity: if (m_val_array.GetCount() == 1) { if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit) { prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); } else return INVALID; } else if (m_val_array[0].token == CSS_NUMBER) { float opacity = float(m_val_array[0].value.number.number); if (opacity < 0.0f) opacity = 0.0f; else if (opacity > 1.0f) opacity = 1.0f; prop_list->AddDeclL(prop, opacity, CSS_NUMBER, important, GetCurrentOrigin()); } else return INVALID; } else return INVALID; break; case CSS_PROPERTY__wap_accesskey: { int gi = 0; CSS_generic_value gen_arr[CSS_MAX_ARR_SIZE]; CSS_anchored_heap_arrays<uni_char> strings; ANCHOR(CSS_anchored_heap_arrays<uni_char>, strings); while (i < m_val_array.GetCount() && gi < CSS_MAX_ARR_SIZE) { if (m_val_array[i].token == CSS_IDENT) { if (m_val_array.GetCount() == 1) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_none || keyword == CSS_VALUE_inherit) { prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); return OK; } } uni_char* access_key = m_input_buffer->GetString(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); strings.AddArrayL(access_key); // *** Handle accesskey parsing here *** gen_arr[gi].value_type = CSS_STRING_LITERAL; gen_arr[gi++].value.string = access_key; } else if (m_val_array[i].token == CSS_NUMBER) { int start_pos = m_val_array[i].value.number.start_pos; int str_len = 0; float number_value = float(m_val_array[i].value.number.number); BOOL valid = number_value >= 0.0 && number_value < 10.0 && number_value == op_floor(number_value); while (i+1 < m_val_array.GetCount() && (m_val_array[i+1].token == CSS_NUMBER) && (m_val_array[i+1].value.number.number < 0)) { if (m_val_array[i+1].value.number.number <= -10.0 || m_val_array[i+1].value.number.number != op_floor(m_val_array[i+1].value.number.number)) valid = FALSE; i++; } if (valid) { str_len = m_val_array[i].value.number.start_pos - start_pos + 1; uni_char* access_key = m_input_buffer->GetString(start_pos, str_len); strings.AddArrayL(access_key); // *** Handle accesskey parsing here *** gen_arr[gi].value_type = CSS_STRING_LITERAL; gen_arr[gi++].value.string = access_key; } } else if (m_val_array[i].token == CSS_HASH_CHAR || m_val_array[i].token == CSS_ASTERISK_CHAR) { uni_char* access_key = OP_NEWA_L(uni_char, 2); access_key[0] = m_val_array[i].token; access_key[1] = 0; strings.AddArrayL(access_key); gen_arr[gi].value_type = CSS_STRING_LITERAL; gen_arr[gi++].value.string = access_key; } else if (m_val_array[i].token == CSS_COMMA) gen_arr[gi++].value_type = CSS_COMMA; i++; } if (gi > 0) { prop_list->AddDeclL(prop, gen_arr, gi, 0, important, GetCurrentOrigin()); return OK; } else return INVALID; } break; case CSS_PROPERTY__wap_input_format: if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_STRING_LITERAL) { uni_char* input_format = m_input_buffer->GetString(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (!input_format) LEAVE(OpStatus::ERR_NO_MEMORY); prop_list->AddDeclL(prop, input_format, important, GetCurrentOrigin(), CSS_string_decl::StringDeclString, m_hld_prof == NULL); } else return INVALID; break; case CSS_PROPERTY__wap_input_required: if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_true || keyword == CSS_VALUE_false) { prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); } else return INVALID; } else return INVALID; break; case CSS_PROPERTY__wap_marquee_dir: if (m_val_array.GetCount() == 1) { if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_rtl || keyword == CSS_VALUE_ltr) { prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); } else return INVALID; } else return INVALID; } else return INVALID; break; case CSS_PROPERTY__wap_marquee_loop: if (m_val_array.GetCount() == 1) { if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_infinite) { prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); } else return INVALID; } else if (m_val_array[0].token == CSS_NUMBER) { prop_list->AddDeclL(prop, float(m_val_array[i].value.number.number), CSS_NUMBER, important, GetCurrentOrigin()); } else return INVALID; } else return INVALID; break; case CSS_PROPERTY__wap_marquee_speed: if (m_val_array.GetCount() == 1) { if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_slow || keyword == CSS_VALUE_normal || keyword == CSS_VALUE_fast) { prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); } else return INVALID; } else return INVALID; } else return INVALID; break; case CSS_PROPERTY__wap_marquee_style: if (m_val_array.GetCount() == 1) { if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_scroll || keyword == CSS_VALUE_slide || keyword == CSS_VALUE_alternate) { prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); } else return INVALID; } else return INVALID; } else return INVALID; break; #ifdef CSS_MINI_EXTENSIONS // -o-mini-fold case CSS_PROPERTY__o_mini_fold: if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword != CSS_VALUE_none && keyword != CSS_VALUE_folded && keyword != CSS_VALUE_unfolded) return INVALID; prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); } else return INVALID; break; // -o-focus-opacity case CSS_PROPERTY__o_focus_opacity: if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_NUMBER) { float opacity = static_cast<float>(m_val_array[0].value.number.number); if (opacity < 0.0f) opacity = 0.0f; else if (opacity > 1.0f) opacity = 1.0f; prop_list->AddDeclL(prop, opacity, CSS_NUMBER, important, GetCurrentOrigin()); } else return INVALID; break; #endif // CSS_MINI_EXTENSIONS #ifdef CSS_CHARACTER_TYPE_SUPPORT case CSS_PROPERTY_character_type: #endif // CSS_CHARACTER_TYPE_SUPPORT case CSS_PROPERTY_input_format: if (m_val_array.GetCount() == 1 && (m_val_array[0].token == CSS_STRING_LITERAL || m_val_array[0].token == CSS_IDENT)) { uni_char* input_format = m_input_buffer->GetString(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (!input_format) LEAVE(OpStatus::ERR_NO_MEMORY); prop_list->AddDeclL(prop, input_format, important, GetCurrentOrigin(), CSS_string_decl::StringDeclString, m_hld_prof == NULL); } else return INVALID; break; case CSS_PROPERTY_text_overflow: if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { CSSValue val = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (val == CSS_VALUE_clip || val == CSS_VALUE_ellipsis || val == CSS_VALUE__o_ellipsis_lastline || val == CSS_VALUE_inherit) { prop_list->AddTypeDeclL(prop, val, important, GetCurrentOrigin()); break; } } return INVALID; case CSS_PROPERTY_overflow_wrap: if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { CSSValue val = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (val == CSS_VALUE_break_word || val == CSS_VALUE_normal || val == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, val, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; break; case CSS_PROPERTY_nav_up: case CSS_PROPERTY_nav_down: case CSS_PROPERTY_nav_left: case CSS_PROPERTY_nav_right: { if (m_val_array.GetCount() > 0) { if (m_val_array[0].token == CSS_IDENT && m_val_array.GetCount() == 1) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_auto || keyword == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else if (m_val_array[0].token == CSS_HASH && m_val_array.GetCount() <= 2) { CSS_anchored_heap_arrays<uni_char> strings; ANCHOR(CSS_anchored_heap_arrays<uni_char>, strings); CSS_generic_value gen_arr[2]; if (m_val_array.GetCount() == 2) { if (m_val_array[1].token == CSS_STRING_LITERAL) { gen_arr[1].value_type = CSS_STRING_LITERAL; gen_arr[1].value.string = m_input_buffer->GetString(m_val_array[1].value.str.start_pos, m_val_array[1].value.str.str_len); if (!gen_arr[1].value.string) LEAVE(OpStatus::ERR_NO_MEMORY); strings.AddArrayL(gen_arr[1].value.string); } else if (m_val_array[1].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[1].value.str.start_pos, m_val_array[1].value.str.str_len); if (keyword == CSS_VALUE_current || keyword == CSS_VALUE_root) { gen_arr[1].value_type = CSS_IDENT; gen_arr[1].value.type = keyword; } else return INVALID; } else return INVALID; } gen_arr[0].value_type = CSS_HASH; gen_arr[0].value.string = m_input_buffer->GetString(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (!gen_arr[0].value.string) LEAVE(OpStatus::ERR_NO_MEMORY); strings.AddArrayL(gen_arr[0].value.string); prop_list->AddDeclL(prop, gen_arr, m_val_array.GetCount(), 0, important, GetCurrentOrigin()); } else return INVALID; } else return INVALID; } break; case CSS_PROPERTY_nav_index: if (m_val_array.GetCount() == 1) { if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_auto || keyword == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); } else if (m_val_array[0].token == CSS_NUMBER && m_val_array[0].value.number.number > 0) prop_list->AddDeclL(prop, float(m_val_array[0].value.number.number), CSS_NUMBER, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; break; case CSS_PROPERTY__o_table_baseline: if (m_val_array.GetCount() != 1) return INVALID; if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else if (m_val_array[0].token == CSS_NUMBER) prop_list->AddLongDeclL(prop, (long)m_val_array[0].value.number.number, important, GetCurrentOrigin()); else return INVALID; break; case CSS_PROPERTY__o_tab_size: if (m_val_array.GetCount() != 1) return INVALID; if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit || keyword == CSS_VALUE_auto) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else if (CSS_is_number(m_val_array[0].token) && CSS_get_number_ext(m_val_array[0].token) == CSS_NUMBER) { if (m_val_array[0].value.number.number < 0) return INVALID; int num; if (m_val_array[0].value.number.number >= INT_MAX) num = INT_MAX; else num = int(m_val_array[0].value.number.number); prop_list->AddLongDeclL(prop, (long)num, important, GetCurrentOrigin()); } else return INVALID; break; #ifdef SVG_SUPPORT case CSS_PROPERTY_alignment_baseline: case CSS_PROPERTY_clip_rule: case CSS_PROPERTY_fill_rule: case CSS_PROPERTY_color_interpolation: case CSS_PROPERTY_color_interpolation_filters: case CSS_PROPERTY_color_rendering: case CSS_PROPERTY_image_rendering: case CSS_PROPERTY_dominant_baseline: case CSS_PROPERTY_pointer_events: case CSS_PROPERTY_shape_rendering: case CSS_PROPERTY_stroke_linejoin: case CSS_PROPERTY_stroke_linecap: case CSS_PROPERTY_text_anchor: case CSS_PROPERTY_text_rendering: case CSS_PROPERTY_vector_effect: case CSS_PROPERTY_writing_mode: case CSS_PROPERTY_display_align: case CSS_PROPERTY_buffered_rendering: if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); BOOL goodKeyword = (keyword == CSS_VALUE_inherit); if (!goodKeyword) { switch (prop) { case CSS_PROPERTY_buffered_rendering: goodKeyword = CSS_is_bufferedrendering_val(keyword); break; case CSS_PROPERTY_alignment_baseline: goodKeyword = CSS_is_alignmentbaseline_val(keyword); break; case CSS_PROPERTY_clip_rule: // fall-through is intended case CSS_PROPERTY_fill_rule: goodKeyword = CSS_is_fillrule_val(keyword); break; case CSS_PROPERTY_color_interpolation: // fall-through is intended case CSS_PROPERTY_color_interpolation_filters: goodKeyword = CSS_is_colorinterpolation_val(keyword); break; case CSS_PROPERTY_color_rendering: goodKeyword = CSS_is_colorrendering_val(keyword); break; case CSS_PROPERTY_image_rendering: goodKeyword = CSS_is_imagerendering_val(keyword); break; case CSS_PROPERTY_dominant_baseline: goodKeyword = CSS_is_dominantbaseline_val(keyword); break; case CSS_PROPERTY_pointer_events: goodKeyword = CSS_is_pointerevents_val(keyword); break; case CSS_PROPERTY_shape_rendering: goodKeyword = CSS_is_shaperendering_val(keyword); break; case CSS_PROPERTY_stroke_linecap: goodKeyword = CSS_is_strokelinecap_val(keyword); break; case CSS_PROPERTY_stroke_linejoin: goodKeyword = CSS_is_strokelinejoin_val(keyword); break; case CSS_PROPERTY_text_anchor: goodKeyword = CSS_is_textanchor_val(keyword); break; case CSS_PROPERTY_text_rendering: goodKeyword = CSS_is_textrendering_val(keyword); break; case CSS_PROPERTY_vector_effect: goodKeyword = CSS_is_vectoreffect_val(keyword); break; case CSS_PROPERTY_writing_mode: goodKeyword = CSS_is_writingmode_val(keyword); break; case CSS_PROPERTY_display_align: goodKeyword = CSS_is_displayalign_val(keyword); break; } } if (goodKeyword) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; break; case CSS_PROPERTY_color_profile: if (m_val_array.GetCount() == 1) { if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (CSS_VALUE_sRGB == keyword || CSS_VALUE_auto == keyword || keyword == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); return OK; } else if (m_val_array[0].token == CSS_FUNCTION_URL) { URL url = m_input_buffer->GetURLL(m_base_url, m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); ANCHOR(URL, url); const uni_char* url_name = url.GetAttribute(URL::KUniName_With_Fragment_Username_Password_NOT_FOR_UI).CStr(); if (url_name) prop_list->AddDeclL(prop, url_name, uni_strlen(url_name), important, GetCurrentOrigin(), CSS_string_decl::StringDeclUrl, m_hld_prof == NULL); else return INVALID; return OK; } else if (m_val_array[0].token == CSS_STRING_LITERAL) { uni_char* str = m_input_buffer->GetString(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (str) { prop_list->AddDeclL(prop, str, important, GetCurrentOrigin(), CSS_string_decl::StringDeclString, m_hld_prof == NULL); } else LEAVE(OpStatus::ERR_NO_MEMORY); return OK; } return INVALID; } else return INVALID; break; case CSS_PROPERTY_glyph_orientation_horizontal: // fall-through is intended case CSS_PROPERTY_glyph_orientation_vertical: if (m_val_array.GetCount() == 1) { if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if ((prop == CSS_PROPERTY_glyph_orientation_vertical && CSS_VALUE_auto == keyword) || keyword == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else if (m_val_array[0].token == CSS_DEG || m_val_array[0].token == CSS_RAD || m_val_array[0].token == CSS_GRAD || m_val_array[0].token == CSS_NUMBER) { prop_list->AddDeclL(prop, float(m_val_array[0].value.number.number), m_val_array[0].token, important, GetCurrentOrigin()); } else return INVALID; } else return INVALID; break; case CSS_PROPERTY_baseline_shift: if (m_val_array.GetCount() == 1) { if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (CSS_is_baselineshift_val(keyword) || keyword == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else if (CSS_is_number(m_val_array[0].token)) { float length = float(m_val_array[0].value.number.number); int length_type = CSS_get_number_ext(m_val_array[0].token); if (length && !CSS_is_length_number_ext(length_type) && (length_type != CSS_PERCENTAGE)) { length_type = CSS_PX; } prop_list->AddDeclL(prop, length, length_type, important, GetCurrentOrigin()); } else return INVALID; } else return INVALID; break; case CSS_PROPERTY_clip_path: case CSS_PROPERTY_filter: case CSS_PROPERTY_marker: case CSS_PROPERTY_marker_end: case CSS_PROPERTY_marker_mid: case CSS_PROPERTY_marker_start: case CSS_PROPERTY_mask: // <uri> | none | inherit if (m_val_array.GetCount() == 1) { if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_none || keyword == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else if (m_val_array[0].token == CSS_FUNCTION_URL) { URL url = m_input_buffer->GetURLL(m_base_url, m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); ANCHOR(URL, url); const uni_char* url_name = url.GetAttribute(URL::KUniName_With_Fragment_Username_Password_NOT_FOR_UI).CStr(); if (url_name) prop_list->AddDeclL(prop, url_name, uni_strlen(url_name), important, GetCurrentOrigin(), CSS_string_decl::StringDeclUrl, m_hld_prof == NULL); else return INVALID; return OK; } else return INVALID; } else return INVALID; break; case CSS_PROPERTY_enable_background: if (m_val_array.GetCount() == 1) { if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_accumulate || keyword == CSS_VALUE_new || keyword == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } } else if (m_val_array.GetCount() == 5) { if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword != CSS_VALUE_new) { return INVALID; } } else return INVALID; int gi; CSS_generic_value gen_arr[CSS_MAX_ARR_SIZE]; for (gi = 0; gi < m_val_array.GetCount(); gi++) { if (CSS_is_number(m_val_array[gi].token)) { float length = float(m_val_array[gi].value.number.number); int length_type = CSS_get_number_ext(m_val_array[gi].token); if (length && !CSS_is_length_number_ext(length_type) && (length_type != CSS_PERCENTAGE)) { length_type = CSS_PX; } gen_arr[gi].value_type = length_type; gen_arr[gi].value.real = length; } else { return INVALID; } } prop_list->AddDeclL(prop, gen_arr, gi, 0, important, GetCurrentOrigin()); } else return INVALID; break; case CSS_PROPERTY_kerning: case CSS_PROPERTY_stroke_width: case CSS_PROPERTY_stroke_miterlimit: case CSS_PROPERTY_stroke_dashoffset: case CSS_PROPERTY_audio_level: case CSS_PROPERTY_line_increment: if (m_val_array.GetCount() == 1) { if (CSS_is_number(m_val_array[0].token)) { float length = float(m_val_array[0].value.number.number); int length_type = CSS_get_number_ext(m_val_array[0].token); if (length && !CSS_is_length_number_ext(length_type) && (length_type != CSS_PERCENTAGE)) { length_type = CSS_PX; } prop_list->AddDeclL(prop, length, length_type, important, GetCurrentOrigin()); } else if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit || ((prop == CSS_PROPERTY_kerning || prop == CSS_PROPERTY_line_increment) && keyword == CSS_VALUE_auto)) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; } break; case CSS_PROPERTY_stroke_dasharray: if (m_val_array.GetCount() > 0) { if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_none || keyword == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else { int gi = 0; CSS_generic_value gen_arr[CSS_MAX_ARR_SIZE]; for (int i = 0; i < m_val_array.GetCount(); i++) { if (CSS_is_number(m_val_array[i].token)) { float length = float(m_val_array[i].value.number.number); int length_type = CSS_get_number_ext(m_val_array[i].token); if (length && !CSS_is_length_number_ext(length_type) && (length_type != CSS_PERCENTAGE)) { length_type = CSS_PX; } gen_arr[gi].value_type = length_type; gen_arr[gi].value.real = length; gi++; } else if (m_val_array[i].token != CSS_COMMA) { return INVALID; } } prop_list->AddDeclL(prop, gen_arr, gi, 0, important, GetCurrentOrigin()); } } else return INVALID; break; #endif // SVG_SUPPORT #ifdef GADGET_SUPPORT case CSS_PROPERTY__apple_dashboard_region: if (m_val_array.GetCount() == 7 && m_val_array[0].token == CSS_FUNCTION_DASHBOARD_REGION && m_val_array[5].token == CSS_IDENT && m_input_buffer->GetValueSymbol(m_val_array[5].value.str.start_pos, m_val_array[5].value.str.str_len) == CSS_VALUE_control && m_val_array[6].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[6].value.str.start_pos, m_val_array[6].value.str.str_len); if (keyword == CSS_VALUE_circle || keyword == CSS_VALUE_rectangle) { CSS_generic_value gen_arr[5]; int gi=0; gen_arr[gi].value_type = CSS_IDENT; gen_arr[gi++].value.type = keyword; for (int i = 1; i < 5; i++) { float length = float(m_val_array[i].value.number.number); int length_type = CSS_get_number_ext(m_val_array[i].token); if (m_val_array[i].token == CSS_NUMBER && length == 0 || length >= 0 && CSS_is_length_number_ext(length_type)) { if (length_type == CSS_NUMBER) length_type = CSS_PX; gen_arr[gi].value_type = length_type; gen_arr[gi].value.real = length; gi++; } else return INVALID; } prop_list->AddDeclL(prop, gen_arr, 5, 0, important, GetCurrentOrigin()); } else return INVALID; } else return INVALID; break; #endif // GADGET_SUPPORT #ifdef CSS_TRANSITIONS case CSS_PROPERTY_transition: { if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit) { prop_list->AddTypeDeclL(CSS_PROPERTY_transition_delay, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_transition_duration, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_transition_property, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_transition_timing_function, keyword, important, GetCurrentOrigin()); return OK; } } int i=0; int gi=0; short prop_arr[CSS_MAX_ARR_SIZE]; CSSValue property_keyword = CSS_VALUE_UNSPECIFIED; CSS_generic_value_list dur_arr; ANCHOR(CSS_generic_value_list, dur_arr); CSS_generic_value_list del_arr; ANCHOR(CSS_generic_value_list, del_arr); CSS_generic_value_list time_arr; ANCHOR(CSS_generic_value_list, time_arr); while (i < m_val_array.GetCount()) { BOOL property_set = FALSE; BOOL delay_set = FALSE; BOOL duration_set = FALSE; BOOL timing_set = FALSE; int start_i = i; while (i < m_val_array.GetCount() && m_val_array[i].token != CSS_COMMA) { short tok = m_val_array[i].token; if (tok == CSS_SECOND || tok == CSS_NUMBER && m_val_array[i].value.number.number == 0) { if (!duration_set) { duration_set = TRUE; dur_arr.PushNumberL(CSS_SECOND, float(m_val_array[i].value.number.number)); } else if (!delay_set) { delay_set = TRUE; del_arr.PushNumberL(CSS_SECOND, float(m_val_array[i].value.number.number)); } else return INVALID; } else if (tok == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (CSS_is_timing_func_val(keyword) && !timing_set) { timing_set = TRUE; SetTimingKeywordL(keyword, time_arr); } else if (!property_set && (keyword == CSS_VALUE_all || keyword == CSS_VALUE_none)) { // Not allowed to set property to "all" or "none" after other properties if (gi > 0) return INVALID; property_keyword = keyword; property_set = TRUE; prop_arr[0] = -1; } else if (!property_set) { // Not allowed to set property after "all" or "none" if (gi > 0 && prop_arr[0] == -1) return INVALID; short val_prop = m_input_buffer->GetPropertySymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (val_prop != -1) { property_set = TRUE; if (gi < CSS_MAX_ARR_SIZE) { prop_arr[gi] = val_prop; } } else return INVALID; } else return INVALID; } else if (tok == CSS_FUNCTION_CUBIC_BEZ && !timing_set) { timing_set = TRUE; if (i+4 >= m_val_array.GetCount()) { OP_ASSERT(FALSE); // If this happens, the grammar outputs wrong values for cubic-bezier functions. return INVALID; } for (int j=0; j<4; j++) { ++i; OP_ASSERT(m_val_array[i].token == CSS_NUMBER); float param = float(m_val_array[i].value.number.number); if ((j % 2) == 0 || param >= 0 && param <= 1.0) // even values are y-values and can exceed [0,1]. x-values cannot. time_arr.PushNumberL(CSS_NUMBER, param); else return INVALID; } } else if (!timing_set && tok == CSS_FUNCTION_STEPS && m_val_array[i].value.steps.steps > 0) { timing_set = TRUE; time_arr.PushIntegerL(CSS_INT_NUMBER, m_val_array[i].value.steps.steps); time_arr.PushIdentL(m_val_array[i].value.steps.start ? CSS_VALUE_start : CSS_VALUE_end); time_arr.PushValueTypeL(CSS_IDENT); // dummy time_arr.PushValueTypeL(CSS_IDENT); // dummy } else return INVALID; i++; } if (start_i == i || ++i == m_val_array.GetCount()) return INVALID; if (gi < CSS_MAX_ARR_SIZE) { if (!duration_set) dur_arr.PushNumberL(CSS_NUMBER, 0); if (!delay_set) del_arr.PushNumberL(CSS_NUMBER, 0); if (!property_set) { if (gi > 0 || i < m_val_array.GetCount()) return INVALID; property_keyword = CSS_VALUE_all; prop_arr[gi] = -1; } gi++; } if (!timing_set) { time_arr.PushNumberL(CSS_NUMBER, 0.25f); time_arr.PushNumberL(CSS_NUMBER, 0.1f); time_arr.PushNumberL(CSS_NUMBER, 0.25f); time_arr.PushNumberL(CSS_NUMBER, 1.0f); } } prop_list->AddDeclL(CSS_PROPERTY_transition_delay, del_arr, 0, important, GetCurrentOrigin()); prop_list->AddDeclL(CSS_PROPERTY_transition_duration, dur_arr, 0, important, GetCurrentOrigin()); if (gi == 1 && prop_arr[0] == -1) { OP_ASSERT(property_keyword != CSS_VALUE_UNSPECIFIED); prop_list->AddTypeDeclL(CSS_PROPERTY_transition_property, property_keyword, important, GetCurrentOrigin()); } else prop_list->AddDeclL(CSS_PROPERTY_transition_property, prop_arr, gi, important, GetCurrentOrigin()); prop_list->AddDeclL(CSS_PROPERTY_transition_timing_function, time_arr, 0, important, GetCurrentOrigin()); } break; case CSS_PROPERTY_transition_delay: case CSS_PROPERTY_transition_duration: #ifdef CSS_ANIMATIONS case CSS_PROPERTY_animation_delay: case CSS_PROPERTY_animation_duration: #endif // CSS_ANIMATIONS { if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit) { prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); return OK; } } if (m_val_array.GetCount() > 0 && m_val_array.GetCount()%2 == 1) { CSS_generic_value gen_arr[CSS_MAX_ARR_SIZE]; int gi=0; for (int i=0; i<m_val_array.GetCount(); i++) { short tok = m_val_array[i].token; if ((i%2) == 1) { if (tok == CSS_COMMA) continue; else return INVALID; } else if (tok == CSS_SECOND || tok == CSS_NUMBER && m_val_array[i].value.number.number == 0) { if (gi < CSS_MAX_ARR_SIZE) { gen_arr[gi].SetValueType(CSS_SECOND); gen_arr[gi++].SetReal(float(m_val_array[i].value.number.number)); } } else return INVALID; } prop_list->AddDeclL(prop, gen_arr, gi, 0, important, GetCurrentOrigin()); } else return INVALID; } break; case CSS_PROPERTY_transition_property: { if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit) { prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); return OK; } } if (m_val_array.GetCount() > 0 && m_val_array.GetCount()%2 == 1) { short prop_array[CSS_MAX_ARR_SIZE]; int ai=0; for (int i=0; i<m_val_array.GetCount(); i++) { short tok = m_val_array[i].token; if ((i%2) == 1) { if (tok == CSS_COMMA) continue; else return INVALID; } if (tok != CSS_IDENT) return INVALID; if (i == 0 && m_val_array.GetCount() == 1) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_all || keyword == CSS_VALUE_none) { prop_list->AddTypeDeclL(CSS_PROPERTY_transition_property, keyword, important, GetCurrentOrigin()); return OK; } } short val_prop = m_input_buffer->GetPropertySymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (val_prop == -1) return INVALID; else if (ai < CSS_MAX_ARR_SIZE) prop_array[ai++] = val_prop; } prop_list->AddDeclL(CSS_PROPERTY_transition_property, prop_array, ai, important, GetCurrentOrigin()); } else return INVALID; } break; #ifdef CSS_ANIMATIONS case CSS_PROPERTY_animation_timing_function: #endif // CSS_ANIMATIONS case CSS_PROPERTY_transition_timing_function: { if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit) { prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); return OK; } } CSS_generic_value_list gen_arr; ANCHOR(CSS_generic_value_list, gen_arr); BOOL expect_comma = FALSE; for (int i=0; i<m_val_array.GetCount(); i++) { if (expect_comma && m_val_array[i].token == CSS_COMMA) { expect_comma = FALSE; continue; } if (m_val_array[i].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (CSS_is_timing_func_val(keyword)) SetTimingKeywordL(keyword, gen_arr); else return INVALID; } else if (m_val_array[i].token == CSS_FUNCTION_CUBIC_BEZ) { OP_ASSERT(i+4 < m_val_array.GetCount()); i++; for (int j=0; j<4; j++, i++) { OP_ASSERT(m_val_array[i].token == CSS_NUMBER); float param = float(m_val_array[i].value.number.number); if ((i % 2) == 0 || param >= 0 && param <= 1.0) // even values are y-values and can exceed [0,1]. x-values cannot. gen_arr.PushNumberL(CSS_NUMBER, param); else return INVALID; } } else if (m_val_array[i].token == CSS_FUNCTION_STEPS && m_val_array[i].value.steps.steps > 0) { gen_arr.PushIntegerL(CSS_INT_NUMBER, m_val_array[i].value.steps.steps); gen_arr.PushIdentL(m_val_array[i].value.steps.start ? CSS_VALUE_start : CSS_VALUE_end); gen_arr.PushValueTypeL(CSS_IDENT); // dummy gen_arr.PushValueTypeL(CSS_IDENT); // dummy } else return INVALID; expect_comma = TRUE; } if (expect_comma) prop_list->AddDeclL(prop, gen_arr, 0, important, GetCurrentOrigin()); else return INVALID; } break; #endif // CSS_TRANSITIONS #ifdef CSS_ANIMATIONS case CSS_PROPERTY_animation: { if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit) { prop_list->AddTypeDeclL(CSS_PROPERTY_animation_name, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_animation_duration, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_animation_timing_function, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_animation_iteration_count, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_animation_direction, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_animation_delay, keyword, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_animation_fill_mode, keyword, important, GetCurrentOrigin()); return OK; } } CSS_generic_value_list animation_name; ANCHOR(CSS_generic_value_list, animation_name); CSS_generic_value_list animation_duration; ANCHOR(CSS_generic_value_list, animation_duration); CSS_generic_value_list animation_timing; ANCHOR(CSS_generic_value_list, animation_timing); CSS_generic_value_list animation_iteration_count; ANCHOR(CSS_generic_value_list, animation_iteration_count); CSS_generic_value_list animation_direction; ANCHOR(CSS_generic_value_list, animation_direction); CSS_generic_value_list animation_delay; ANCHOR(CSS_generic_value_list, animation_delay); CSS_generic_value_list animation_fill_mode; ANCHOR(CSS_generic_value_list, animation_fill_mode); CSS_anchored_heap_arrays<uni_char> strings; ANCHOR(CSS_anchored_heap_arrays<uni_char>, strings); const uni_char* default_name = UNI_L("none"); int start_i = i; while (i < m_val_array.GetCount()) { BOOL name_set = FALSE; BOOL delay_set = FALSE; BOOL duration_set = FALSE; BOOL timing_set = FALSE; BOOL direction_set = FALSE; BOOL iteration_count_set = FALSE; BOOL fill_mode_set = FALSE; for (;i < m_val_array.GetCount() && m_val_array[i].token != CSS_COMMA; i++) { short tok = m_val_array[i].token; if (m_val_array[i].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (!timing_set && CSS_is_timing_func_val(keyword)) { timing_set = TRUE; SetTimingKeywordL(keyword, animation_timing); } else if (!direction_set && CSS_is_animation_direction_val(keyword)) { direction_set = TRUE; animation_direction.PushIdentL(keyword); } else if (!fill_mode_set && CSS_is_animation_fill_mode_value(keyword)) { fill_mode_set = TRUE; animation_fill_mode.PushIdentL(keyword); } else if (!iteration_count_set && keyword == CSS_VALUE_infinite) { iteration_count_set = TRUE; animation_iteration_count.PushNumberL(CSS_NUMBER, -1); } else if (!name_set) { if (uni_char* str = m_input_buffer->GetString(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len)) { name_set = TRUE; animation_name.PushStringL(CSS_STRING_LITERAL, str); strings.AddArrayL(str); } else LEAVE(OpStatus::ERR_NO_MEMORY); } else return INVALID; } else if (!duration_set && tok == CSS_SECOND || tok == CSS_NUMBER && m_val_array[i].value.number.number == 0) { duration_set = TRUE; animation_duration.PushNumberL(CSS_SECOND, float(m_val_array[i].value.number.number)); } else if (!iteration_count_set && tok == CSS_NUMBER) { iteration_count_set = TRUE; animation_iteration_count.PushNumberL(CSS_NUMBER, float(m_val_array[i].value.number.number)); } else if (!delay_set && tok == CSS_SECOND || tok == CSS_NUMBER && m_val_array[i].value.number.number == 0) { delay_set = TRUE; animation_delay.PushNumberL(CSS_SECOND, float(m_val_array[i].value.number.number)); } else if (tok == CSS_FUNCTION_CUBIC_BEZ && !timing_set) { timing_set = TRUE; if (i+4 >= m_val_array.GetCount()) { OP_ASSERT(FALSE); // If this happens, the grammar outputs wrong values for cubic-bezier functions. return INVALID; } for (int j=0; j<4; j++) { ++i; OP_ASSERT(m_val_array[i].token == CSS_NUMBER); float param = float(m_val_array[i].value.number.number); if ((j % 2) == 0 || param >= 0 && param <= 1.0) // even values are y-values and can exceed [0,1]. x-values cannot. animation_timing.PushNumberL(CSS_NUMBER, param); else return INVALID; } } else if (!timing_set && tok == CSS_FUNCTION_STEPS && m_val_array[i].value.steps.steps > 0) { timing_set = TRUE; animation_timing.PushIntegerL(CSS_INT_NUMBER, m_val_array[i].value.steps.steps); animation_timing.PushIdentL(m_val_array[i].value.steps.start ? CSS_VALUE_start : CSS_VALUE_end); animation_timing.PushValueTypeL(CSS_IDENT); // dummy animation_timing.PushValueTypeL(CSS_IDENT); // dummy } else { return INVALID; } } if (start_i == i || ++i == m_val_array.GetCount()) return INVALID; if (!name_set) animation_name.PushStringL(CSS_STRING_LITERAL, const_cast<uni_char*>(default_name)); if (!delay_set) animation_delay.PushNumberL(CSS_SECOND, 0.0); if (!duration_set) animation_duration.PushNumberL(CSS_SECOND, 0.0); if (!iteration_count_set) animation_iteration_count.PushNumberL(CSS_NUMBER, 1.0); if (!fill_mode_set) animation_fill_mode.PushIdentL(CSS_VALUE_none); if (!direction_set) animation_direction.PushIdentL(CSS_VALUE_normal); if (!timing_set) { animation_timing.PushNumberL(CSS_NUMBER, 0.25f); animation_timing.PushNumberL(CSS_NUMBER, 0.1f); animation_timing.PushNumberL(CSS_NUMBER, 0.25f); animation_timing.PushNumberL(CSS_NUMBER, 1.0f); } } if (i > 0) { prop_list->AddDeclL(CSS_PROPERTY_animation_name, animation_name, 0, important, GetCurrentOrigin()); prop_list->AddDeclL(CSS_PROPERTY_animation_duration, animation_duration, 0, important, GetCurrentOrigin()); prop_list->AddDeclL(CSS_PROPERTY_animation_timing_function, animation_timing, 0, important, GetCurrentOrigin()); prop_list->AddDeclL(CSS_PROPERTY_animation_iteration_count, animation_iteration_count, 0, important, GetCurrentOrigin()); prop_list->AddDeclL(CSS_PROPERTY_animation_direction, animation_direction, 0, important, GetCurrentOrigin()); prop_list->AddDeclL(CSS_PROPERTY_animation_delay, animation_delay, 0, important, GetCurrentOrigin()); prop_list->AddDeclL(CSS_PROPERTY_animation_fill_mode, animation_fill_mode, 0, important, GetCurrentOrigin()); return OK; } else return INVALID; } break; case CSS_PROPERTY_animation_name: { if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit) { prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); return OK; } } CSS_generic_value_list gen_arr; ANCHOR(CSS_generic_value_list, gen_arr); CSS_anchored_heap_arrays<uni_char> strings; ANCHOR(CSS_anchored_heap_arrays<uni_char>, strings); for (i=0; i < m_val_array.GetCount(); i++) { short tok = m_val_array[i].token; if ((i%2) == 1) { if (tok == CSS_COMMA) continue; else return INVALID; } else if (m_val_array[i].token == CSS_IDENT) { uni_char* str = m_input_buffer->GetString(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (str) { gen_arr.PushStringL(CSS_STRING_LITERAL, str); strings.AddArrayL(str); } else LEAVE(OpStatus::ERR_NO_MEMORY); } } if (!gen_arr.Empty()) { prop_list->AddDeclL(prop, gen_arr, 0, important, GetCurrentOrigin()); return OK; } else return INVALID; } break; case CSS_PROPERTY_animation_iteration_count: { if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit) { prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); return OK; } } CSS_generic_value_list gen_arr; ANCHOR(CSS_generic_value_list, gen_arr); for (i=0; i < m_val_array.GetCount(); i++) { short tok = m_val_array[i].token; if ((i%2) == 1) { if (tok == CSS_COMMA) continue; else return INVALID; } else if (m_val_array[i].token == CSS_NUMBER) gen_arr.PushNumberL(CSS_NUMBER, float(m_val_array[i].value.number.number)); else if (m_val_array[i].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (keyword == CSS_VALUE_infinite) gen_arr.PushNumberL(CSS_NUMBER, -1); else return INVALID; } } if (!gen_arr.Empty()) { prop_list->AddDeclL(prop, gen_arr, 0, important, GetCurrentOrigin()); return OK; } else return INVALID; } break; case CSS_PROPERTY_animation_direction: case CSS_PROPERTY_animation_fill_mode: case CSS_PROPERTY_animation_play_state: { if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit) { prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); return OK; } } CSS_generic_value_list gen_arr; ANCHOR(CSS_generic_value_list, gen_arr); for (i=0; i < m_val_array.GetCount(); i++) { short tok = m_val_array[i].token; if ((i%2) == 1) { if (tok == CSS_COMMA) continue; else return INVALID; } else if (m_val_array[i].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); BOOL valid_value = (prop == CSS_PROPERTY_animation_direction && CSS_is_animation_direction_val(keyword)) || (prop == CSS_PROPERTY_animation_fill_mode && (keyword == CSS_VALUE_none || keyword == CSS_VALUE_forwards || keyword == CSS_VALUE_backwards || keyword == CSS_VALUE_both)) || (prop == CSS_PROPERTY_animation_play_state && (keyword == CSS_VALUE_running || keyword == CSS_VALUE_paused)); if (valid_value) gen_arr.PushIdentL(keyword); else return INVALID; } } if (!gen_arr.Empty()) { prop_list->AddDeclL(prop, gen_arr, 0, important, GetCurrentOrigin()); return OK; } else return INVALID; } break; #endif // CSS_ANIMATIONS #ifdef CSS_TRANSFORMS case CSS_PROPERTY_transform: return SetTransformListL(prop_list, important); case CSS_PROPERTY_transform_origin: return SetTransformOriginL(prop_list, important); #endif case CSS_PROPERTY_resize: if (m_val_array.GetCount() == 1) { if (m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (CSS_is_resize_val(keyword) || keyword == CSS_VALUE_inherit) prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); else return INVALID; } else return INVALID; } else return INVALID; break; default: return INVALID; } return OK; } #ifdef SVG_SUPPORT CSS_Parser::DeclStatus CSS_Parser::SetPaintUriL(CSS_property_list* prop_list, short prop, BOOL important) { OP_ASSERT(prop == CSS_PROPERTY_fill || prop == CSS_PROPERTY_stroke); OP_ASSERT(m_val_array.GetCount() >= 1); OP_ASSERT(m_val_array[0].token == CSS_FUNCTION_URL); if (m_val_array.GetCount() > 2) return INVALID; // <uri> [none | currentColor | <color> ] URL url = m_input_buffer->GetURLL(m_base_url, m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); ANCHOR(URL, url); const uni_char* url_name = url.GetAttribute(URL::KUniName_With_Fragment_Username_Password_NOT_FOR_UI).CStr(); if (!url_name) return INVALID; if (m_val_array.GetCount() == 2) { CSS_generic_value gen_arr[2]; BOOL recognized_keyword = FALSE; if (m_val_array[1].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[1].value.str.start_pos, m_val_array[1].value.str.str_len); if (keyword == CSS_VALUE_none || keyword == CSS_VALUE_currentColor) { gen_arr[1].SetValueType(CSS_IDENT); gen_arr[1].SetType(keyword); recognized_keyword = TRUE; } } if (!recognized_keyword) { COLORREF color; CSSValue keyword; uni_char* dummy = NULL; switch (SetColorL(color, keyword, dummy, m_val_array[1])) { case COLOR_KEYWORD: case COLOR_SKIN: case COLOR_INVALID: return INVALID; case COLOR_RGBA: case COLOR_NAMED: break; } gen_arr[1].SetValueType(CSS_DECL_COLOR); gen_arr[1].value.color = color; } uni_char* url = OP_NEWA_L(uni_char, uni_strlen(url_name)+1); CSS_anchored_heap_arrays<uni_char> strings; ANCHOR(CSS_anchored_heap_arrays<uni_char>, strings); strings.AddArrayL(url); uni_strcpy(url, url_name); gen_arr[0].SetValueType(CSS_FUNCTION_URL); gen_arr[0].SetString(url); prop_list->AddDeclL(prop, gen_arr, 2, 0, important, GetCurrentOrigin()); } else { prop_list->AddDeclL(prop, url_name, uni_strlen(url_name), important, GetCurrentOrigin(), CSS_string_decl::StringDeclUrl, m_hld_prof == NULL); } return OK; } #endif #ifdef CSS_TRANSFORMS CSS_Parser::DeclStatus CSS_Parser::SetTransformOriginL(CSS_property_list* prop_list, BOOL important) { if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit) { prop_list->AddTypeDeclL(CSS_PROPERTY_transform_origin, keyword, important, GetCurrentOrigin()); return OK; } } int i = 0; float pos[2]; CSSValueType pos_type[2]; CSSValue dummy[2]; BOOL dummy2; DeclStatus ret = SetPosition(i, pos, pos_type, FALSE, dummy, dummy2); if (ret == INVALID) return INVALID; if (i != m_val_array.GetCount()) return INVALID; if (ret == OK) prop_list->AddDeclL(CSS_PROPERTY_transform_origin, pos[0], pos[1], pos_type[0], pos_type[1], important, GetCurrentOrigin()); return ret; } CSS_Parser::DeclStatus CSS_Parser::SetTransformListL(CSS_property_list* prop_list, BOOL important) { CSSValue keyword; if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit || keyword == CSS_VALUE_none) { prop_list->AddTypeDeclL(CSS_PROPERTY_transform, keyword, important, GetCurrentOrigin()); return OK; } else return INVALID; } else if (m_val_array.GetCount() > 0) { int i = 0; CSS_transform_list* transform_list = OP_NEW_L(CSS_transform_list, (CSS_PROPERTY_transform)); for (i=0; i < m_val_array.GetCount(); i++) { keyword = CSSValue(m_val_array[i].token); if (!CSS_is_transform_function(keyword)) { OP_DELETE(transform_list); return INVALID; } CSS_TransformFunctionInfo transform_info(keyword); i++; if (OpStatus::IsMemoryError(transform_list->StartTransformFunction(keyword))) { OP_DELETE(transform_list); LEAVE(OpStatus::ERR_NO_MEMORY); } int j = 0; for (;i < m_val_array.GetCount(); j++, i++) { if (CSS_is_transform_function(m_val_array[i].token)) { i--; break; } if (!CSS_is_number(m_val_array[i].token)) { OP_DELETE(transform_list); return INVALID; } float length = float(m_val_array[i].value.number.number); short length_type = CSS_get_number_ext(m_val_array[i].token); BOOL allow_implicit_unit = (m_hld_prof && !m_hld_prof->IsInStrictMode()); if (length != 0 && !transform_info.IsValidUnit(allow_implicit_unit, length_type)) { OP_DELETE(transform_list); return INVALID; } transform_list->AppendValue(length, length_type); } if (!transform_info.ValidArgCount(j)) { OP_DELETE(transform_list); return INVALID; } } prop_list->AddDecl(transform_list, important, GetCurrentOrigin()); return OK; } else return INVALID; } #endif /** Helper for handling a CSS_generic_value array of arbitrary size */ class CSS_generic_value_handler { public: /** First phase constructor. Initializes an empty handler. Use ConstructL() as a second step. */ CSS_generic_value_handler() : generic_value_array(NULL) {} /** Destructor */ ~CSS_generic_value_handler() { if (static_generic_value != generic_value_array) OP_DELETEA(generic_value_array); } /** Read/write operator. */ CSS_generic_value* operator()() { return generic_value_array; } /** Read-only index operator */ CSS_generic_value operator[](int index) const { return generic_value_array[index]; } /** Read/write index operator */ CSS_generic_value& operator[](int index) { return generic_value_array[index]; } /** Second phase constructor. Specifies maximum size. Leaves on out-of-memory. */ void ConstructL(unsigned int max_size); private: CSS_generic_value static_generic_value[CSS_MAX_ARR_SIZE]; CSS_generic_value* generic_value_array; }; void CSS_generic_value_handler::ConstructL(unsigned int max_size) { CSS_generic_value* p; if (max_size < CSS_MAX_ARR_SIZE) p = static_generic_value; else p = OP_NEWA_L(CSS_generic_value, max_size); generic_value_array = p; } CSS_Parser::DeclStatus CSS_Parser::SetBackgroundListL(CSS_property_list* prop_list, short prop, BOOL important) { int i = 0, j = 0; if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit) { prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); return OK; } } CSS_generic_value_handler gen_arr; ANCHOR(CSS_generic_value_handler, gen_arr); gen_arr.ConstructL(m_val_array.GetCount()); for (i=0; i < m_val_array.GetCount(); i++) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (keyword >= 0) if (((prop == CSS_PROPERTY_background_clip || prop == CSS_PROPERTY_background_origin) && CSS_is_background_clip_or_origin_val(keyword)) || (prop == CSS_PROPERTY_background_attachment && CSS_is_bg_attachment_val(keyword))) { gen_arr[j].SetValueType(CSS_IDENT); gen_arr[j++].SetType(keyword); } } if (j > 0) { prop_list->AddDeclL(prop, gen_arr(), j, j, important, GetCurrentOrigin()); return OK; } else return INVALID; } CSS_Parser::DeclStatus CSS_Parser::SetPositionL(CSS_property_list* prop_list, BOOL important, short prop) { OP_ASSERT(prop == CSS_PROPERTY_background_position || prop == CSS_PROPERTY__o_object_position); // Inheritance if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit) { prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); return OK; } } int i = 0; CSS_generic_value_list gen_arr; ANCHOR(CSS_generic_value_list, gen_arr); int layers = 0; for (;i < m_val_array.GetCount(); i++) { float pos[2]; CSSValueType pos_type[2]; CSSValue reference_point[2]; BOOL has_reference_point; DeclStatus ret = SetPosition(i, pos, pos_type, TRUE, reference_point, has_reference_point); if (ret == INVALID) return INVALID; if (has_reference_point) gen_arr.PushIdentL(reference_point[0]); gen_arr.PushNumberL(pos_type[0], pos[0]); if (has_reference_point) gen_arr.PushIdentL(reference_point[1]); gen_arr.PushNumberL(pos_type[1], pos[1]); layers++; if (i == m_val_array.GetCount()) break; if (m_val_array[i].token == CSS_COMMA) gen_arr.PushValueTypeL(CSS_COMMA); else return INVALID; } if (layers > 1 && prop == CSS_PROPERTY__o_object_position) // Only a single item for object-position return INVALID; if (layers > 0) { prop_list->AddDeclL(prop, gen_arr, layers, important, GetCurrentOrigin()); return OK; } else return INVALID; } CSS_Parser::DeclStatus CSS_Parser::SetBackgroundShorthandL(CSS_property_list* prop_list, BOOL important) { /* Memory management note: m_{strings,gradients} holds the ownership of the data during parsing and cleans up afterwards. The data is also held in CSS_generic_value_list structures, but without ownership. If parsing goes well, that data is then copied to the property list when the CSS_generic_value_list is added. See CSS_property_list::AddDeclL(...) */ CSS_anchored_heap_arrays<uni_char> strings; ANCHOR(CSS_anchored_heap_arrays<uni_char>, strings); #ifdef CSS_GRADIENT_SUPPORT CSS_anchored_heap_objects<CSS_Gradient> gradients; ANCHOR(CSS_anchored_heap_objects<CSS_Gradient>, gradients); #endif // CSS_GRADIENT_SUPPORT CSS_BackgroundShorthandInfo shorthand_info(*this, strings #ifdef CSS_GRADIENT_SUPPORT , gradients #endif // CSS_GRADIENT_SUPPORT ); if (shorthand_info.IsInherit()) { prop_list->AddTypeDeclL(CSS_PROPERTY_background_attachment, CSS_VALUE_inherit, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_background_repeat, CSS_VALUE_inherit, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_background_image, CSS_VALUE_inherit, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_background_position, CSS_VALUE_inherit, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_background_size, CSS_VALUE_inherit, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_background_color, CSS_VALUE_inherit, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_background_origin, CSS_VALUE_inherit, important, GetCurrentOrigin()); prop_list->AddTypeDeclL(CSS_PROPERTY_background_clip, CSS_VALUE_inherit, important, GetCurrentOrigin()); return OK; } else { CSS_generic_value_list bg_attachment_list; ANCHOR(CSS_generic_value_list, bg_attachment_list); CSS_generic_value_list bg_repeat_list; ANCHOR(CSS_generic_value_list, bg_repeat_list); CSS_generic_value_list bg_image_list; ANCHOR(CSS_generic_value_list, bg_image_list); CSS_generic_value_list bg_pos_list; ANCHOR(CSS_generic_value_list, bg_pos_list); CSS_generic_value_list bg_size_list; ANCHOR(CSS_generic_value_list, bg_size_list); CSS_generic_value_list bg_origin_list; ANCHOR(CSS_generic_value_list, bg_origin_list); CSS_generic_value_list bg_clip_list; ANCHOR(CSS_generic_value_list, bg_clip_list); COLORREF bg_color_value = USE_DEFAULT_COLOR; BOOL bg_color_is_keyword = FALSE; CSSValue bg_color_keyword = CSS_VALUE_transparent; int nlayers = 0; while (shorthand_info.ExtractLayerL(bg_attachment_list, bg_repeat_list, bg_image_list, bg_pos_list, bg_size_list, bg_origin_list, bg_clip_list, bg_color_value, bg_color_is_keyword, bg_color_keyword)) nlayers++; if (shorthand_info.IsInvalid()) return INVALID; prop_list->AddDeclL(CSS_PROPERTY_background_attachment, bg_attachment_list, nlayers, important, GetCurrentOrigin()); prop_list->AddDeclL(CSS_PROPERTY_background_repeat, bg_repeat_list, nlayers, important, GetCurrentOrigin()); prop_list->AddDeclL(CSS_PROPERTY_background_image, bg_image_list, nlayers, important, GetCurrentOrigin()); prop_list->AddDeclL(CSS_PROPERTY_background_position, bg_pos_list, nlayers, important, GetCurrentOrigin()); prop_list->AddDeclL(CSS_PROPERTY_background_size, bg_size_list, nlayers, important, GetCurrentOrigin()); prop_list->AddDeclL(CSS_PROPERTY_background_origin, bg_origin_list, nlayers, important, GetCurrentOrigin()); prop_list->AddDeclL(CSS_PROPERTY_background_clip, bg_clip_list, nlayers, important, GetCurrentOrigin()); if (bg_color_value != USE_DEFAULT_COLOR) { if (bg_color_is_keyword) prop_list->AddColorDeclL(CSS_PROPERTY_background_color, bg_color_value, important, GetCurrentOrigin()); else prop_list->AddLongDeclL(CSS_PROPERTY_background_color, (long)bg_color_value, important, GetCurrentOrigin()); } else if (bg_color_keyword >= 0) prop_list->AddTypeDeclL(CSS_PROPERTY_background_color, bg_color_keyword, important, GetCurrentOrigin()); return OK; } } CSS_Parser::DeclStatus CSS_Parser::SetBackgroundSizeL(CSS_property_list* prop_list, BOOL important) { int i = 0, j = 0; int item_count = 1; if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit) { prop_list->AddTypeDeclL(CSS_PROPERTY_background_size, keyword, important, GetCurrentOrigin()); return OK; } } CSS_generic_value_handler gen_arr; ANCHOR(CSS_generic_value_handler, gen_arr); gen_arr.ConstructL(m_val_array.GetCount()); enum { EXPECT_NEXT, EXPECT_SECOND_LENGTH_OR_COMMA, EXPECT_COMMA } state = EXPECT_NEXT; for (i=0; i < m_val_array.GetCount(); i++) { if (m_val_array[i].token == CSS_IDENT && (state == EXPECT_NEXT || state == EXPECT_SECOND_LENGTH_OR_COMMA)) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (keyword == CSS_VALUE_cover || keyword == CSS_VALUE_contain) { gen_arr[j].SetValueType(CSS_IDENT); gen_arr[j++].SetType(keyword); state = (state == EXPECT_NEXT) ? EXPECT_SECOND_LENGTH_OR_COMMA : EXPECT_COMMA; } else if (keyword == CSS_VALUE_auto) { gen_arr[j].SetValueType(CSS_IDENT); gen_arr[j++].SetType(keyword); state = (state == EXPECT_NEXT) ? EXPECT_SECOND_LENGTH_OR_COMMA : EXPECT_COMMA; } else return INVALID; } else if (m_val_array[i].token == CSS_NUMBER || m_val_array[i].token == CSS_PERCENTAGE || CSS_is_length_number_ext(m_val_array[i].token) && (state == EXPECT_NEXT || state == EXPECT_SECOND_LENGTH_OR_COMMA)) { short type = m_val_array[i].token; if (type == CSS_NUMBER) type = CSS_PX; gen_arr[j].SetValueType(type); gen_arr[j++].SetReal(float(m_val_array[i].value.number.number)); state = (state == EXPECT_NEXT) ? EXPECT_SECOND_LENGTH_OR_COMMA : EXPECT_COMMA; } else if (m_val_array[i].token == CSS_COMMA && (state == EXPECT_SECOND_LENGTH_OR_COMMA || state == EXPECT_COMMA)) { gen_arr[j++].SetValueType(CSS_COMMA); state = EXPECT_NEXT; item_count++; } else return INVALID; } if (state == EXPECT_COMMA || state == EXPECT_SECOND_LENGTH_OR_COMMA) { prop_list->AddDeclL(CSS_PROPERTY_background_size, gen_arr(), j, item_count, important, GetCurrentOrigin()); return OK; } else return INVALID; } CSS_Parser::DeclStatus CSS_Parser::SetBackgroundRepeatL(CSS_property_list* prop_list, BOOL important) { int i = 0, j = 0; if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit) { prop_list->AddTypeDeclL(CSS_PROPERTY_background_repeat, keyword, important, GetCurrentOrigin()); return OK; } } CSS_generic_value_handler gen_arr; ANCHOR(CSS_generic_value_handler, gen_arr); gen_arr.ConstructL(m_val_array.GetCount()); int item_count = 1; enum { EXPECT_FIRST, EXPECT_SECOND_OR_COMMA, EXPECT_COMMA } state = EXPECT_FIRST; for (i=0; i < m_val_array.GetCount(); i++) { if (m_val_array[i].token == CSS_IDENT && (state == EXPECT_FIRST || state == EXPECT_SECOND_OR_COMMA)) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (CSS_is_bg_repeat_val(keyword) && (state == EXPECT_FIRST || (keyword != CSS_VALUE_repeat_x && keyword != CSS_VALUE_repeat_y))) { gen_arr[j].SetValueType(CSS_IDENT); gen_arr[j++].SetType(keyword); if (state == EXPECT_FIRST && keyword != CSS_VALUE_repeat_x && keyword != CSS_VALUE_repeat_y) state = EXPECT_SECOND_OR_COMMA; else state = EXPECT_COMMA; } else return INVALID; } else if (m_val_array[i].token == CSS_COMMA && (state == EXPECT_SECOND_OR_COMMA || state == EXPECT_COMMA)) { gen_arr[j++].SetValueType(CSS_COMMA); state = EXPECT_FIRST; item_count++; } else return INVALID; } if (state == EXPECT_COMMA || state == EXPECT_SECOND_OR_COMMA) { prop_list->AddDeclL(CSS_PROPERTY_background_repeat, gen_arr(), j, item_count, important, GetCurrentOrigin()); return OK; } else return INVALID; } CSS_Parser::DeclStatus CSS_Parser::SetBackgroundImageL(CSS_property_list* prop_list, BOOL important) { CSSValue keyword = CSS_VALUE_UNKNOWN; int i = 0, j = 0; BOOL expect_comma = FALSE; int item_count = 1; if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit) { prop_list->AddTypeDeclL(CSS_PROPERTY_background_image, CSS_VALUE_inherit, important, GetCurrentOrigin()); return OK; } } CSS_generic_value_handler gen_arr; ANCHOR(CSS_generic_value_handler, gen_arr); gen_arr.ConstructL(m_val_array.GetCount()); // Anchor new objects to these when adding them to gen_arr. // AddDeclL at the end of this method will copy them elsewhere before the anchor is destroyed. CSS_anchored_heap_arrays<uni_char> strings; ANCHOR(CSS_anchored_heap_arrays<uni_char>, strings); #ifdef CSS_GRADIENT_SUPPORT CSS_anchored_heap_objects<CSS_Gradient> gradients; ANCHOR(CSS_anchored_heap_objects<CSS_Gradient>, gradients); #endif // CSS_GRADIENT_SUPPORT for (i=0; i < m_val_array.GetCount(); i++) { if (m_val_array[i].token == CSS_IDENT && !expect_comma) { keyword = m_input_buffer->GetValueSymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (keyword == CSS_VALUE_none) { gen_arr[j].value_type = CSS_IDENT; gen_arr[j++].value.type = keyword; expect_comma = TRUE; } else return INVALID; } else if (m_val_array[i].token == CSS_FUNCTION_URL && !expect_comma) { // image const uni_char* url_name = m_input_buffer->GetURLL(m_base_url, m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len).GetAttribute(URL::KUniName_Username_Password_Escaped_NOT_FOR_UI).CStr(); if (!url_name) return INVALID; uni_char* url_str = OP_NEWA_L(uni_char, uni_strlen(url_name)+1); strings.AddArrayL(url_str); uni_strcpy(url_str, url_name); gen_arr[j].value_type = CSS_FUNCTION_URL; gen_arr[j++].value.string = url_str; expect_comma = TRUE; } #ifdef CSS_GRADIENT_SUPPORT else if (CSS_is_gradient(m_val_array[i].token) && !expect_comma) { CSSValueType type = (CSSValueType) m_val_array[i].token; CSS_Gradient* gradient = SetGradientL(/* inout */ i, /* inout */ type); if (!gradient) return INVALID; gradients.AddObjectL(gradient); gen_arr[j].SetValueType(type); gen_arr[j++].SetGradient(gradient); expect_comma = TRUE; } #endif // CSS_GRADIENT_SUPPORT #ifdef SKIN_SUPPORT else if (m_val_array[i].token == CSS_FUNCTION_SKIN && !expect_comma) { uni_char* skin_name = m_input_buffer->GetSkinString(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (!skin_name) return INVALID; strings.AddArrayL(skin_name); gen_arr[j].value_type = CSS_FUNCTION_SKIN; gen_arr[j++].value.string = skin_name; expect_comma = TRUE; } #endif // SKIN_SUPPORT else if (m_val_array[i].token == CSS_COMMA && expect_comma) { expect_comma = FALSE; item_count++; } else return INVALID; } if (j > 0 && expect_comma) { prop_list->AddDeclL(CSS_PROPERTY_background_image, gen_arr(), j, item_count, important, GetCurrentOrigin()); return OK; } else return INVALID; } void CSS_Parser::FindPositionValues(int i, CSS_generic_value values[4], int& n_values) const { int j = i; for (; j < i+4 && j < m_val_array.GetCount(); j++) { // If the CSS value is an identifier, retrieve the position values. if (m_val_array[j].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[j].value.str.start_pos, m_val_array[j].value.str.str_len); if (CSS_is_position_val(keyword)) { values[j-i].SetValueType(CSS_IDENT); values[j-i].SetType(keyword); } else break; } else if (CSS_is_length_number_ext(m_val_array[j].token) || m_val_array[j].token == CSS_PERCENTAGE || (m_val_array[j].token == CSS_NUMBER && (m_val_array[j].value.number.number == 0 || m_hld_prof && !m_hld_prof->IsInStrictMode()))) { /* If the CSS value is a percentage or a length, set the positions to the given value. Also, if we are in quirks mode on an author stylesheet, convert raw numbers (including 0) to pixel lengths. */ short ext = CSS_get_number_ext(m_val_array[j].token); if (ext == CSS_NUMBER) ext = CSS_PX; values[j-i].SetValueType(ext); values[j-i].SetReal(float(m_val_array[j].value.number.number)); } else break; } n_values = j - i; } CSS_Parser::DeclStatus CSS_Parser::SetPosition(int& i, float pos[2], CSSValueType pos_type[2], BOOL allow_reference_point, CSSValue reference_point[2], BOOL& has_reference_point) const { pos[0] = pos[1] = 0; pos_type[0] = pos_type[1] = CSS_PERCENTAGE; reference_point[0] = CSS_VALUE_left; reference_point[1] = CSS_VALUE_top; has_reference_point = FALSE; int n_values; CSS_generic_value values[4]; FindPositionValues(i, values, n_values); if (n_values == 0) // No accepted values found: invalid CSS. return INVALID; else if (n_values == 1) { // Only one value found: assume 'center'/50% for the other. if (values[0].GetValueType() == CSS_IDENT) { CSSValue keyword = values[0].GetType(); // A single keyword switch (keyword) { case CSS_VALUE_top: pos[0] = 50; pos[1] = 0; break; case CSS_VALUE_left: pos[0] = 0; pos[1] = 50; break; case CSS_VALUE_center: pos[0] = 50; pos[1] = 50; break; case CSS_VALUE_right: pos[0] = 100; pos[1] = 50; break; case CSS_VALUE_bottom: pos[0] = 50; pos[1] = 100; break; default: OP_ASSERT(!"Invalid keyword found."); } } else { // A single value. pos[0] = values[0].GetReal(); pos_type[0] = (CSSValueType)values[0].GetValueType(); pos[1] = 50; } } else if (n_values == 2) { // Two values found. if (values[0].GetValueType() == CSS_IDENT && values[1].GetValueType() == CSS_IDENT) { // Both values are keywords. Set percentage values. CSSValue keywords[2] = { values[0].GetType(), values[1].GetType() }; if ((keywords[0] == CSS_VALUE_left && keywords[1] == CSS_VALUE_top) || (keywords[1] == CSS_VALUE_left && keywords[0] == CSS_VALUE_top)) { pos[0] = pos[1] = 0; } else if ((keywords[0] == CSS_VALUE_center && keywords[1] == CSS_VALUE_top) || (keywords[1] == CSS_VALUE_center && keywords[0] == CSS_VALUE_top)) { pos[0] = 50; pos[1] = 0; } else if ((keywords[0] == CSS_VALUE_right && keywords[1] == CSS_VALUE_top) || (keywords[1] == CSS_VALUE_right && keywords[0] == CSS_VALUE_top)) { pos[0] = 100; pos[1] = 0; } else if ((keywords[0] == CSS_VALUE_center && keywords[1] == CSS_VALUE_left) || (keywords[1] == CSS_VALUE_center && keywords[0] == CSS_VALUE_left)) { pos[0] = 0; pos[1] = 50; } else if (keywords[0] == CSS_VALUE_center && keywords[1] == CSS_VALUE_center) { pos[0] = 50; pos[1] = 50; } else if ((keywords[0] == CSS_VALUE_center && keywords[1] == CSS_VALUE_right) || (keywords[1] == CSS_VALUE_center && keywords[0] == CSS_VALUE_right)) { pos[0] = 100; pos[1] = 50; } else if ((keywords[0] == CSS_VALUE_bottom && keywords[1] == CSS_VALUE_left) || (keywords[1] == CSS_VALUE_bottom && keywords[0] == CSS_VALUE_left)) { pos[0] = 0; pos[1] = 100; } else if ((keywords[0] == CSS_VALUE_bottom && keywords[1] == CSS_VALUE_center) || (keywords[1] == CSS_VALUE_bottom && keywords[0] == CSS_VALUE_center)) { pos[0] = 50; pos[1] = 100; } else if ((keywords[0] == CSS_VALUE_bottom && keywords[1] == CSS_VALUE_right) || (keywords[1] == CSS_VALUE_bottom && keywords[0] == CSS_VALUE_right)) { pos[0] = 100; pos[1] = 100; } else return INVALID; } else if (values[0].GetValueType() == CSS_IDENT) { // The first value is a keyword. Convert it to an x position. CSSValue keyword = values[0].GetType(); if (keyword == CSS_VALUE_center) pos[0] = 50; else if (keyword == CSS_VALUE_right) pos[0] = 100; else if (keyword != CSS_VALUE_left) return INVALID; pos[1] = values[1].GetReal(); pos_type[1] = (CSSValueType)values[1].GetValueType(); } else if (values[1].GetValueType() == CSS_IDENT) { // The second value is a keyword. Convert it to a y position. CSSValue keyword = values[1].GetType(); if (keyword == CSS_VALUE_center) pos[1] = 50; else if (keyword == CSS_VALUE_bottom) pos[1] = 100; else if (keyword != CSS_VALUE_top) return INVALID; pos[0] = values[0].GetReal(); pos_type[0] = (CSSValueType)values[0].GetValueType(); } else { pos[0] = values[0].GetReal(); pos_type[0] = (CSSValueType)values[0].GetValueType(); pos[1] = values[1].GetReal(); pos_type[1] = (CSSValueType)values[1].GetValueType(); } } else if (allow_reference_point) { // three or four values OP_ASSERT(n_values == 3 || n_values == 4); float tmp_pos[2] = { 0, 0 }; CSSValueType tmp_pos_type[2] = { CSS_PERCENTAGE, CSS_PERCENTAGE }; CSSValue keywords[2]; if (values[0].GetValueType() != CSS_IDENT) return INVALID; keywords[0] = (CSSValue)values[0].GetType(); int j = 1; if (keywords[0] != CSS_VALUE_center) if (values[j].GetValueType() != CSS_IDENT) { tmp_pos[0] = values[j].GetReal(); tmp_pos_type[0] = (CSSValueType)values[j++].GetValueType(); } if (values[j].GetValueType() != CSS_IDENT) return INVALID; keywords[1] = (CSSValue)values[j++].GetType(); if (keywords[1] != CSS_VALUE_center) if (j < n_values && values[j].GetValueType() != CSS_IDENT) { tmp_pos[1] = values[j].GetReal(); tmp_pos_type[1] = (CSSValueType)values[j++].GetValueType(); } if (j < n_values) return INVALID; if (keywords[0] == CSS_VALUE_left || keywords[0] == CSS_VALUE_right) { reference_point[0] = keywords[0]; pos[0] = tmp_pos[0]; pos_type[0] = tmp_pos_type[0]; if (keywords[1] == CSS_VALUE_top || keywords[1] == CSS_VALUE_bottom) { reference_point[1] = keywords[1]; pos[1] = tmp_pos[1]; pos_type[1] = tmp_pos_type[1]; } else if (keywords[1] == CSS_VALUE_center) { reference_point[1] = CSS_VALUE_top; pos[1] = 50; } else return INVALID; } else if (keywords[0] == CSS_VALUE_top || keywords[0] == CSS_VALUE_bottom) { reference_point[1] = keywords[0]; pos[1] = tmp_pos[0]; pos_type[1] = tmp_pos_type[0]; if (keywords[1] == CSS_VALUE_left || keywords[1] == CSS_VALUE_right) { reference_point[0] = keywords[1]; pos[0] = tmp_pos[1]; pos_type[0] = tmp_pos_type[1]; } else if (keywords[1] == CSS_VALUE_center) { reference_point[0] = CSS_VALUE_left; pos[0] = 50; } else return INVALID; } else if (keywords[0] == CSS_VALUE_center) { if (keywords[1] == CSS_VALUE_left || keywords[1] == CSS_VALUE_right) { reference_point[1] = CSS_VALUE_top; pos[1] = 50; reference_point[0] = keywords[1]; pos[0] = tmp_pos[1]; pos_type[0] = tmp_pos_type[1]; } else if (keywords[1] == CSS_VALUE_top || keywords[1] == CSS_VALUE_bottom) { reference_point[0] = CSS_VALUE_left; pos[0] = 50; reference_point[1] = keywords[1]; pos[1] = tmp_pos[1]; pos_type[1] = tmp_pos_type[1]; } else return INVALID; } else return INVALID; has_reference_point = TRUE; } else return INVALID; i += n_values; return OK; } void CSS_Parser::SetTimingKeywordL(CSSValue keyword, CSS_generic_value_list& time_arr) { BOOL steps = FALSE; BOOL step_start = FALSE; float preset[4] = { 0, 0, 1, 1 }; switch (keyword) { case CSS_VALUE_ease: preset[0] = 0.25f; preset[1] = 0.1f; preset[2] = 0.25f; break; case CSS_VALUE_ease_in: case CSS_VALUE_ease_in_out: preset[0] = 0.42f; if (keyword == CSS_VALUE_ease_in) break; case CSS_VALUE_ease_out: preset[2] = 0.58f; break; case CSS_VALUE_step_start: step_start = TRUE; /* fall-through */ case CSS_VALUE_step_end: steps = TRUE; break; } if (steps) { time_arr.PushIntegerL(CSS_INT_NUMBER, 1); time_arr.PushIdentL(step_start ? CSS_VALUE_start : CSS_VALUE_end); time_arr.PushValueTypeL(CSS_IDENT); // dummy time_arr.PushValueTypeL(CSS_IDENT); // dummy } else for (int j=0; j<4; j++) time_arr.PushNumberL(CSS_NUMBER, preset[j]); } CSS_Parser::DeclStatus CSS_Parser::SetFamilyNameL(CSS_generic_value& value, int& pos, BOOL allow_inherit, BOOL allow_generic) { if (m_val_array[pos].token == CSS_STRING_LITERAL) { uni_char* family_str = m_input_buffer->GetString(m_val_array[pos].value.str.start_pos, m_val_array[pos].value.str.str_len); if (family_str) { value.SetValueType(CSS_STRING_LITERAL); value.SetString(family_str); pos++; } else LEAVE(OpStatus::ERR_NO_MEMORY); } else { int start = pos; int total_len = 0; while (pos < m_val_array.GetCount() && m_val_array[pos].token == CSS_IDENT) { /* Add extra character for space separator or null-termination. */ total_len += m_val_array[pos].value.str.str_len + 1; pos++; } int ident_count = pos - start; if (ident_count > 0) { if (ident_count == 1) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[start].value.str.start_pos, m_val_array[start].value.str.str_len); if (keyword > CSS_VALUE_UNSPECIFIED) { if (allow_inherit && keyword == CSS_VALUE_inherit || allow_generic && CSS_is_font_generic_val(keyword)) { int font_type = keyword; if (font_type != CSS_VALUE_inherit) font_type |= CSS_GENERIC_FONT_FAMILY; /* 'font_type' is a CSSValue, but tagged with CSS_GENERIC_FONT_FAMILY to separate it from plain font numbers. The receiver of this value must check for CSS_GENERIC_FONT_FAMILY and mask with CSS_GENERIC_FONT_FAMILY_mask to access the CSSValue. */ value.SetValueType(CSS_IDENT); value.SetType(CSSValue(font_type)); return OK; } else if (keyword == CSS_VALUE_inherit || CSS_is_font_generic_val(keyword)) return INVALID; } } uni_char* family_str = OP_NEWA_L(uni_char, total_len); uni_char* dst = family_str; for (int i=start; i<start+ident_count; i++) { dst = m_input_buffer->GetString(dst, m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); *dst++ = ' '; } *--dst = 0; value.SetValueType(CSS_STRING_LITERAL); value.SetString(family_str); } else return INVALID; } return OK; } CSS_Parser::DeclStatus CSS_Parser::SetFontFamilyL(CSS_property_list* prop_list, int pos, BOOL important, BOOL allow_inherit) { CSS_anchored_heap_arrays<uni_char> strings; ANCHOR(CSS_anchored_heap_arrays<uni_char>, strings); CSS_generic_value_list gen_arr; ANCHOR(CSS_generic_value_list, gen_arr); BOOL expect_comma = FALSE; while (pos < m_val_array.GetCount()) { if (expect_comma) { if (m_val_array[pos++].token != CSS_COMMA) return INVALID; expect_comma = FALSE; } else { CSS_generic_value value; if (SetFamilyNameL(value, pos, allow_inherit, TRUE) == OK) { if (value.GetValueType() == CSS_IDENT && value.GetType() == CSS_VALUE_inherit) { OP_ASSERT(pos == m_val_array.GetCount()); prop_list->AddTypeDeclL(CSS_PROPERTY_font_family, CSS_VALUE_inherit, important, GetCurrentOrigin()); return OK; } if (value.GetValueType() == CSS_STRING_LITERAL) { strings.AddArrayL(value.GetString()); if (m_hld_prof) m_hld_prof->GetCSSCollection()->AddFontPrefetchCandidate(value.GetString()); } gen_arr.PushGenericValueL(value); expect_comma = TRUE; } else return INVALID; } } if (gen_arr.Empty()) return INVALID; prop_list->AddDeclL(CSS_PROPERTY_font_family, gen_arr, 0, important, GetCurrentOrigin()); return OK; } CSS_Parser::DeclStatus CSS_Parser::SetShadowL(CSS_property_list* prop_list, short prop, BOOL important) { const int max_length_count = (prop == CSS_PROPERTY_box_shadow) ? 4 : 3; if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { // Check for none/inherit CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_none || keyword == CSS_VALUE_inherit) { prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); return OK; } else return INVALID; } else if (m_val_array.GetCount() > 1) { int i=0, j=0; CSS_generic_value_handler gen_arr; ANCHOR(CSS_generic_value_handler, gen_arr); gen_arr.ConstructL(m_val_array.GetCount()); while (i < m_val_array.GetCount()) { COLORREF color = USE_DEFAULT_COLOR; int length_count = 0; // The value is a list of shadow lengths with colors. while (i < m_val_array.GetCount()) { short tok = m_val_array[i].token; CSSValue keyword = CSS_VALUE_UNKNOWN; if (tok == CSS_NUMBER && (m_val_array[i].value.number.number == 0 || m_hld_prof && !m_hld_prof->IsInStrictMode())) tok = CSS_PX; if (tok == CSS_IDENT) keyword = m_input_buffer->GetValueSymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (CSS_is_length_number_ext(tok) && length_count > -1 && length_count < max_length_count) { float num = float(m_val_array[i].value.number.number); if (length_count == 2 && num < 0) /* "The third length is a blur radius. Negative values are not allowed." */ return INVALID; gen_arr[j].value_type = tok; gen_arr[j++].value.real = num; length_count++; } else if (tok == CSS_COMMA) { if (length_count != 0 && length_count != 1 && i+1 < m_val_array.GetCount()) { gen_arr[j++].value_type = tok; break; } else return INVALID; } else if (prop == CSS_PROPERTY_box_shadow && tok == CSS_IDENT && keyword == CSS_VALUE_inset) { gen_arr[j].value_type = CSS_IDENT; gen_arr[j++].SetType(CSS_VALUE_inset); } else if (color == USE_DEFAULT_COLOR && length_count != 1) { if (tok == CSS_FUNCTION_RGB || SupportsAlpha() && tok == CSS_FUNCTION_RGBA) color = m_val_array[i].value.color; else if (tok == CSS_HASH) { color = m_input_buffer->GetColor(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); } else if (tok == CSS_IDENT) { if (CSS_is_ui_color_val(keyword)) color = keyword | CSS_COLOR_KEYWORD_TYPE_ui_color; else if (keyword == CSS_VALUE_currentColor) color = COLORREF(CSS_COLOR_current_color); else if (keyword == CSS_VALUE_transparent) color = COLORREF(CSS_COLOR_transparent); else color = m_input_buffer->GetNamedColorIndex(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); } if (color == USE_DEFAULT_COLOR) return INVALID; if (length_count > 0) length_count = -1; gen_arr[j].value_type = CSS_DECL_COLOR; gen_arr[j++].value.color = color; } else return INVALID; i++; } if (length_count == 0 || length_count == 1) return INVALID; i++; } prop_list->AddDeclL(prop, gen_arr(), j, 0, important, GetCurrentOrigin()); return OK; } return INVALID; } CSS_Parser::DeclStatus CSS_Parser::SetIndividualBorderRadiusL(CSS_property_list* prop_list, short prop, BOOL important) { if (m_val_array.GetCount() == 1) { if (CSS_is_number(m_val_array[0].token) && m_val_array[0].token != CSS_DIMEN) { float length = float(m_val_array[0].value.number.number); int length_type = CSS_get_number_ext(m_val_array[0].token); if (!CSS_is_length_number_ext(length_type) && (length_type != CSS_PERCENTAGE)) length_type = CSS_PX; if (length >= 0) { prop_list->AddDeclL(prop, length, length, length_type, length_type, important, GetCurrentOrigin()); return OK; } } else if (m_val_array[0].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit) { prop_list->AddTypeDeclL(prop, keyword, important, GetCurrentOrigin()); return OK; } } } else if (m_val_array.GetCount() == 2) { if (CSS_is_number(m_val_array[0].token) && m_val_array[0].token != CSS_DIMEN && CSS_is_number(m_val_array[1].token) && m_val_array[1].token != CSS_DIMEN) { float length1 = float(m_val_array[0].value.number.number); int length1_type = CSS_get_number_ext(m_val_array[0].token); float length2 = float(m_val_array[1].value.number.number); int length2_type = CSS_get_number_ext(m_val_array[1].token); if (!CSS_is_length_number_ext(length1_type) && (length1_type != CSS_PERCENTAGE)) length1_type = CSS_PX; if (!CSS_is_length_number_ext(length2_type) && (length2_type != CSS_PERCENTAGE)) length2_type = CSS_PX; if (length1 >= 0 && length2 >= 0) { prop_list->AddDeclL(prop, length1, length2, length1_type, length2_type, important, GetCurrentOrigin()); return OK; } } } return INVALID; } static void CompleteBorderRadiusArray(int code, float* radius, int* type) { if (code < 2) { radius[1] = radius[0]; type[1] = type[0]; } if (code < 3) { radius[2] = radius[0]; type[2] = type[0]; } if (code < 4) { radius[3] = radius[1]; type[3] = type[1]; } } CSS_Parser::DeclStatus CSS_Parser::SetShorthandBorderRadiusL(CSS_property_list* prop_list, BOOL important) { int i = 0, j = 0; float horiz_radius[4]; int horiz_radius_type[4]; float vert_radius[4]; int vert_radius_type[4]; short props[4] = {CSS_PROPERTY_border_top_left_radius, CSS_PROPERTY_border_top_right_radius, CSS_PROPERTY_border_bottom_right_radius, CSS_PROPERTY_border_bottom_left_radius}; // Check for 'inherit'. if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_inherit) { for (; i < 4; i++) prop_list->AddTypeDeclL(props[i], keyword, important, GetCurrentOrigin()); return OK; } else return INVALID; } while (i < m_val_array.GetCount() && CSS_is_number(m_val_array[i].token) && m_val_array[i].token != CSS_DIMEN && j < 4) { horiz_radius[j] = float(m_val_array[i].value.number.number); horiz_radius_type[j] = CSS_get_number_ext(m_val_array[i].token); if (!CSS_is_length_number_ext(horiz_radius_type[j]) && (horiz_radius_type[j] != CSS_PERCENTAGE)) horiz_radius_type[j] = CSS_PX; i++; j++; } CompleteBorderRadiusArray(j, horiz_radius, horiz_radius_type); if (i < m_val_array.GetCount() && m_val_array[i].token == CSS_SLASH) { j = 0; i++; while (i < m_val_array.GetCount() && CSS_is_number(m_val_array[i].token) && m_val_array[i].token != CSS_DIMEN && j < 4) { vert_radius[j] = float(m_val_array[i].value.number.number); vert_radius_type[j] = CSS_get_number_ext(m_val_array[i].token); if (!CSS_is_length_number_ext(vert_radius_type[j]) && (horiz_radius_type[j] != CSS_PERCENTAGE)) vert_radius_type[j] = CSS_PX; i++; j++; } CompleteBorderRadiusArray(j, vert_radius, vert_radius_type); } else for (j=0;j<4;j++) { vert_radius[j] = horiz_radius[j]; vert_radius_type[j] = horiz_radius_type[j]; } if (i == m_val_array.GetCount()) { // Check that no values are negative for (j=0; j<4 && horiz_radius[j] >= 0 && vert_radius[j] >= 0; j++) {} if (j < 4) return INVALID; for (j=0; j<4; j++) prop_list->AddDeclL(props[j], horiz_radius[j], vert_radius[j], horiz_radius_type[j], vert_radius_type[j], important, GetCurrentOrigin()); return OK; } else return INVALID; } /* Parse `none | <image> [ <number> | <percentage> ]{1,4} [ / <border-width>{1,4} ]? [ stretch | repeat | round ]{0,2}' into a corresponding list of CSS_generic_value's. */ CSS_Parser::DeclStatus CSS_Parser::SetBorderImageL(CSS_property_list* prop_list, BOOL important) { CSS_anchored_heap_arrays<uni_char> strings; ANCHOR(CSS_anchored_heap_arrays<uni_char>, strings); #ifdef CSS_GRADIENT_SUPPORT CSS_anchored_heap_objects<CSS_Gradient> gradients; ANCHOR(CSS_anchored_heap_objects<CSS_Gradient>, gradients); #endif // CSS_GRADIENT_SUPPORT if (m_val_array.GetCount() == 0) return INVALID; /* Check for `none' and `inherit' */ if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_none || keyword == CSS_VALUE_inherit) { prop_list->AddTypeDeclL(CSS_PROPERTY__o_border_image, keyword, important, GetCurrentOrigin()); return OK; } else return INVALID; } enum { STATE_IMAGE, STATE_CUTS, STATE_WIDTHS, STATE_SCALE, STATE_INVALID, STATE_DONE } state = STATE_IMAGE; CSS_generic_value gen_arr[CSS_MAX_ARR_SIZE]; int j = 0, i = 0; if (state == STATE_IMAGE) { /* <image> is really an <uri> */ if (m_val_array[i].token == CSS_FUNCTION_URL) { const uni_char* border_image = m_input_buffer->GetURLL(m_base_url, m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len).GetAttribute(URL::KUniName_Username_Password_NOT_FOR_UI).CStr(); OP_ASSERT(border_image != NULL); uni_char* url = OP_NEWA_L(uni_char, uni_strlen(border_image)+1); strings.AddArrayL(url); uni_strcpy(url, border_image); gen_arr[j].SetValueType(CSS_FUNCTION_URL); gen_arr[j++].SetString(url); i++; state = STATE_CUTS; } #ifdef CSS_GRADIENT_SUPPORT else if (CSS_is_gradient(m_val_array[i].token)) { CSSValueType type = (CSSValueType) m_val_array[i].token; CSS_Gradient* gradient = SetGradientL(/* inout */ i, /* inout */ type); if (!gradient) return INVALID; gradients.AddObjectL(gradient); gen_arr[j].SetValueType(type); gen_arr[j++].SetGradient(gradient); i++; state = STATE_CUTS; } #endif else state = STATE_INVALID; } if (state == STATE_CUTS) { const int cuts_start = i; while (i - cuts_start < 4 && i < m_val_array.GetCount() && CSS_is_number(m_val_array[i].token) && state == STATE_CUTS) { int length_type = CSS_get_number_ext(m_val_array[i].token); if (length_type == CSS_PERCENTAGE || length_type == CSS_NUMBER) { gen_arr[j].SetValueType(length_type); gen_arr[j++].SetReal(float(m_val_array[i].value.number.number)); i++; } else state = STATE_INVALID; } if (i - cuts_start) state = i < m_val_array.GetCount() ? STATE_WIDTHS : STATE_DONE; else state = STATE_INVALID; } if (state == STATE_WIDTHS) { if (m_val_array[i].token == CSS_SLASH) { gen_arr[j++].SetValueType(CSS_SLASH); i++; const int widths_start = i; while (i - widths_start < 4 && i < m_val_array.GetCount() && (CSS_is_number(m_val_array[i].token) || m_val_array[i].token == CSS_IDENT) && state == STATE_WIDTHS) { if (m_val_array[i].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); gen_arr[j].SetValueType(CSS_IDENT); if (keyword == CSS_VALUE_thin || keyword == CSS_VALUE_medium || keyword == CSS_VALUE_thick) gen_arr[j++].SetType(keyword); else break; } else if (CSS_is_number(m_val_array[i].token) && m_val_array[i].token != CSS_DIMEN) { int length_type = CSS_get_number_ext(m_val_array[i].token); gen_arr[j].SetValueType(length_type); gen_arr[j++].SetReal(float(m_val_array[i].value.number.number)); } else state = STATE_INVALID; i++; } if (state != STATE_INVALID) { if (i - widths_start) state = i < m_val_array.GetCount() ? STATE_SCALE : STATE_DONE; else state = STATE_INVALID; } } else state = STATE_SCALE; } if (state == STATE_SCALE) { int scale_start = i; while (i - scale_start < 2 && i < m_val_array.GetCount() && state == STATE_SCALE) { if (m_val_array[i].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[i].value.str.start_pos, m_val_array[i].value.str.str_len); if (CSS_is_scale_val(keyword)) { gen_arr[j].SetValueType(CSS_IDENT); gen_arr[j++].SetType(keyword); } else { state = STATE_INVALID; } } else state = STATE_INVALID; i++; } if (state != STATE_INVALID) state = STATE_DONE; } if (state == STATE_DONE) { prop_list->AddDeclL(CSS_PROPERTY__o_border_image, gen_arr, j, 1, important, GetCurrentOrigin()); return OK; } else return INVALID; } bool CSS_Parser::AddCurrentSimpleSelector(short combinator) { if (m_simple_selector_stack.Last() && m_current_selector) { BOOL is_last = (m_current_selector->LastSelector() == NULL); CSS_SimpleSelector* sel = (CSS_SimpleSelector*)m_simple_selector_stack.Last(); sel->Out(); m_current_selector->AddSimpleSelector(sel, combinator); if (!is_last) { CSS_SelectorAttribute* last_attr = sel->GetLastAttr(); if ( last_attr && last_attr->GetType() == CSS_SEL_ATTR_TYPE_PSEUDO_CLASS && IsPseudoElement(last_attr->GetPseudoClass())) { #ifdef CSS_ERROR_SUPPORT EmitErrorL(UNI_L("A pseudo element must be the last part of the selector."), OpConsoleEngine::Error); #endif // CSS_ERROR_SUPPORT return false; } } } return true; } void CSS_Parser::DiscardRuleset() { m_selector_list.Clear(); #ifdef MEDIA_HTML_SUPPORT m_cue_selector_list.Clear(); #endif // MEDIA_HTML_SUPPORT m_simple_selector_stack.Clear(); #ifdef CSS_ANIMATIONS m_current_keyframe_selectors.Clear(); #endif // CSS_ANIMATIONS } bool CSS_Parser::AddSelectorAttributeL(CSS_SelectorAttribute* sel_attr) { CSS_SimpleSelector* cur_simple = GetCurrentSimpleSelector(); OP_ASSERT(cur_simple); CSS_SelectorAttribute* prev_sel_attr = cur_simple->GetLastAttr(); cur_simple->AddAttribute(sel_attr); if ( prev_sel_attr && prev_sel_attr->GetType() == CSS_SEL_ATTR_TYPE_PSEUDO_CLASS && IsPseudoElement(prev_sel_attr->GetPseudoClass())) { #ifdef CSS_ERROR_SUPPORT EmitErrorL(UNI_L("A pseudo element must be the last part of the selector."), OpConsoleEngine::Error); #endif // CSS_ERROR_SUPPORT return false; } else return true; } bool CSS_Parser::AddClassSelectorL(int start_pos, int length) { CSS_SelectorAttribute* sel_attr = NULL; uni_char* text = m_input_buffer->GetString(start_pos, length); if (text) { if (m_hld_prof) { ReferencedHTMLClass* class_ref = m_hld_prof->GetLogicalDocument()->GetClassReference(text); if (class_ref) { sel_attr = OP_NEW(CSS_SelectorAttribute, (CSS_SEL_ATTR_TYPE_CLASS, class_ref)); if (!sel_attr) class_ref->UnRef(); } } else { sel_attr = OP_NEW(CSS_SelectorAttribute, (CSS_SEL_ATTR_TYPE_CLASS, 0, text)); if (!sel_attr) OP_DELETEA(text); } } if (!sel_attr) LEAVE(OpStatus::ERR_NO_MEMORY); return AddSelectorAttributeL(sel_attr); } void CSS_Parser::AddCurrentSelectorL() { OP_ASSERT(m_current_selector); #ifdef MEDIA_HTML_SUPPORT if (m_in_cue) { m_current_selector->Into(&m_cue_selector_list); m_current_selector = NULL; return; } // If we have parsed a ::cue sub-selector: // 1) Rewrite the sub-selector(s), // 2) expand them into N selectors, and // 3) add them to the selector list. if (!m_cue_selector_list.Empty()) { LEAVE_IF_ERROR(ApplyCueSelectors()); return; } // If the current selector ends with a ::cue, we need to add an // additional simple selector to make it match the actual root // element. if (CSS_SimpleSelector* cur_simple = m_current_selector->LastSelector()) if (CSS_SelectorAttribute* sel_attr = cur_simple->GetLastAttr()) if (sel_attr->GetType() == CSS_SEL_ATTR_TYPE_PSEUDO_CLASS && sel_attr->GetPseudoClass() == PSEUDO_CLASS_CUE) AddCueRootSelectorL(); #endif // MEDIA_HTML_SUPPORT m_current_selector->CalculateSpecificity(); m_current_selector->Into(&m_selector_list); m_current_selector = NULL; #ifdef SCOPE_CSS_RULE_ORIGIN m_rule_line_no = m_lexer.GetCurrentLineNo(); #endif // SCOPE_CSS_RULE_ORIGIN } bool CSS_Parser::AddMediaFeatureExprL(CSS_MediaFeature feature) { CSS_MediaFeatureExpr* feature_expr = NULL; switch (feature) { case MEDIA_FEATURE_width: case MEDIA_FEATURE_height: case MEDIA_FEATURE_device_width: case MEDIA_FEATURE_device_height: if (m_val_array.GetCount() == 0) { feature_expr = OP_NEW_L(CSS_MediaFeatureExpr, (feature)); break; } /* Fall-through */ case MEDIA_FEATURE_max_width: case MEDIA_FEATURE_min_width: case MEDIA_FEATURE_max_height: case MEDIA_FEATURE_min_height: case MEDIA_FEATURE_max_device_width: case MEDIA_FEATURE_min_device_width: case MEDIA_FEATURE_max_device_height: case MEDIA_FEATURE_min_device_height: if (m_val_array.GetCount() == 1) { // non-negative <length> float length = 0; short unit = CSS_PX; if (CSS_is_length_number_ext(m_val_array[0].token) && m_val_array[0].value.number.number >= 0) { unit = m_val_array[0].token; length = static_cast<float>(m_val_array[0].value.number.number); } else if (!(m_val_array[0].token == CSS_NUMBER && m_val_array[0].value.number.number == 0 || m_val_array[0].token == CSS_INT_NUMBER && m_val_array[0].value.integer.integer == 0)) break; feature_expr = OP_NEW_L(CSS_MediaFeatureExpr, (feature, unit, length)); } break; case MEDIA_FEATURE_grid: case MEDIA_FEATURE_color: case MEDIA_FEATURE_monochrome: case MEDIA_FEATURE_color_index: case MEDIA_FEATURE__o_paged: if (m_val_array.GetCount() == 0) { feature_expr = OP_NEW_L(CSS_MediaFeatureExpr, (feature)); break; } /* Fall-through */ case MEDIA_FEATURE_max_color: case MEDIA_FEATURE_min_color: case MEDIA_FEATURE_max_monochrome: case MEDIA_FEATURE_min_monochrome: case MEDIA_FEATURE_max_color_index: case MEDIA_FEATURE_min_color_index: if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_INT_NUMBER && m_val_array[0].value.integer.integer >= 0 && (feature != MEDIA_FEATURE_grid || m_val_array[0].value.integer.integer <= 1)) { // <integer> feature_expr = OP_NEW_L(CSS_MediaFeatureExpr, (feature, m_val_array[0].value.integer.integer)); } break; case MEDIA_FEATURE_scan: if (m_val_array.GetCount() == 0) feature_expr = OP_NEW_L(CSS_MediaFeatureExpr, (feature)); else if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_progressive || keyword == CSS_VALUE_interlace) feature_expr = OP_NEW_L(CSS_MediaFeatureExpr, (feature, CSS_IDENT, keyword)); } break; case MEDIA_FEATURE_view_mode: if (m_val_array.GetCount() == 0) feature_expr = OP_NEW_L(CSS_MediaFeatureExpr, (feature)); else if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (CSS_is_viewmode_val(keyword)) { feature_expr = OP_NEW_L(CSS_MediaFeatureExpr, (feature, CSS_IDENT, keyword)); if (HLDProfile()) HLDProfile()->GetFramesDocument()->SetViewModeSupported(static_cast<WindowViewMode>(CSS_ValueToWindowViewMode(keyword))); } } break; case MEDIA_FEATURE_orientation: if (m_val_array.GetCount() == 0) feature_expr = OP_NEW_L(CSS_MediaFeatureExpr, (feature)); else if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (keyword == CSS_VALUE_portrait || keyword == CSS_VALUE_landscape) feature_expr = OP_NEW_L(CSS_MediaFeatureExpr, (feature, CSS_IDENT, keyword)); } break; case MEDIA_FEATURE__o_widget_mode: if (m_val_array.GetCount() == 0) feature_expr = OP_NEW_L(CSS_MediaFeatureExpr, (feature)); else if (m_val_array.GetCount() == 1 && m_val_array[0].token == CSS_IDENT) { CSSValue keyword = m_input_buffer->GetValueSymbol(m_val_array[0].value.str.start_pos, m_val_array[0].value.str.str_len); if (CSS_is_widgetmode_val(keyword)) feature_expr = OP_NEW_L(CSS_MediaFeatureExpr, (feature, CSS_IDENT, keyword)); } break; case MEDIA_FEATURE_resolution: if (m_val_array.GetCount() == 0) { feature_expr = OP_NEW_L(CSS_MediaFeatureExpr, (feature)); break; } /* Fall-through */ case MEDIA_FEATURE_max_resolution: case MEDIA_FEATURE_min_resolution: if (m_val_array.GetCount() == 1 && CSS_is_resolution_ext(m_val_array[0].token) && m_val_array[0].value.number.number > 0) { // <resolution> feature_expr = OP_NEW_L(CSS_MediaFeatureExpr, (feature, m_val_array[0].token, static_cast<float>(m_val_array[0].value.number.number))); } break; case MEDIA_FEATURE_aspect_ratio: case MEDIA_FEATURE_device_aspect_ratio: case MEDIA_FEATURE__o_device_pixel_ratio: if (m_val_array.GetCount() == 0) { feature_expr = OP_NEW_L(CSS_MediaFeatureExpr, (feature)); break; } /* Fall-through */ case MEDIA_FEATURE_max_aspect_ratio: case MEDIA_FEATURE_min_aspect_ratio: case MEDIA_FEATURE_max_device_aspect_ratio: case MEDIA_FEATURE_min_device_aspect_ratio: case MEDIA_FEATURE__o_max_device_pixel_ratio: case MEDIA_FEATURE__o_min_device_pixel_ratio: if (m_val_array.GetCount() == 3 && m_val_array[0].token == CSS_INT_NUMBER && m_val_array[0].value.integer.integer > 0 && m_val_array[1].token == CSS_SLASH && m_val_array[2].token == CSS_INT_NUMBER && m_val_array[2].value.integer.integer > 0) { feature_expr = OP_NEW_L(CSS_MediaFeatureExpr, (feature, CSS_RATIO, MIN(m_val_array[0].value.integer.integer, SHRT_MAX), MIN(m_val_array[2].value.integer.integer, SHRT_MAX))); } break; default: break; } if (feature_expr) { m_current_media_query->AddFeatureExpr(feature_expr); return true; } else return false; } void CSS_Parser::AddRuleL(CSS_Rule* rule) { if (m_dom_rule || m_current_conditional_rule && m_current_conditional_rule->Suc()) { if (m_replace_rule && m_dom_rule) m_stylesheet->ReplaceRule(m_hld_prof, m_dom_rule, rule, m_current_conditional_rule); else m_stylesheet->InsertRule(m_hld_prof, m_dom_rule, rule, m_current_conditional_rule); } else { LEAVE_IF_ERROR(m_stylesheet->AddRule(m_hld_prof, rule, m_current_conditional_rule)); } if (rule->GetType() == CSS_Rule::MEDIA) { m_dom_rule = NULL; m_current_conditional_rule = static_cast<CSS_ConditionalRule*>(rule); if (m_hld_prof) { m_hld_prof->SetHasMediaStyle(static_cast<CSS_MediaRule*>(rule)->GetMediaTypes()); } } else if (rule->GetType() == CSS_Rule::SUPPORTS) { m_dom_rule = NULL; m_current_conditional_rule = static_cast<CSS_ConditionalRule*>(rule); } } void CSS_Parser::AddImportL(const uni_char* url_str) { OpStackAutoPtr<CSS_MediaObject> media_obj(m_current_media_object); m_current_media_object = NULL; URL url = g_url_api->GetURL(m_base_url, url_str); if (url.IsEmpty() || GetBaseURL().Id(TRUE) == url.Id(TRUE) /* Avoid recursive imports */ || !m_hld_prof && url.Type() != URL_FILE /* Only allow file imports for user stylesheets */) return; const uni_char* base_url_str = m_base_url.GetAttribute(URL::KUniName_Username_Password_NOT_FOR_UI).CStr(); const uni_char* url_attr_str = base_url_str ? url_str : NULL; if (!url_attr_str) return; /* Handle ERA SSR where stylesheets should not be loaded unless they have handheld media. */ BOOL is_ssr = m_hld_prof && m_hld_prof->GetFramesDocument()->GetWindow()->GetLayoutMode() == LAYOUT_SSR; if (is_ssr && m_hld_prof && (m_hld_prof->GetCSSMode() == CSS_FULL) && !m_hld_prof->HasMediaStyle(CSS_MEDIA_TYPE_HANDHELD)) { if (media_obj.get() && media_obj->GetMediaTypes() & CSS_MEDIA_TYPE_HANDHELD) m_hld_prof->SetHasMediaStyle(CSS_MEDIA_TYPE_HANDHELD); return; } /* Create inserted LINK element for the import rule. */ HTML_Element* new_elm = NULL; HTML_Element* src_html_elm = m_stylesheet->GetHtmlElement(); if (m_hld_prof) { HtmlAttrEntry ha_list[6]; ha_list[0].ns_idx = NS_IDX_DEFAULT; ha_list[0].attr = Markup::HA_HREF; ha_list[0].value = const_cast<uni_char*>(url_attr_str); ha_list[0].value_len = uni_strlen(url_attr_str); int idx = 1; ha_list[idx].ns_idx = NS_IDX_XML; ha_list[idx].attr = XMLA_BASE; ha_list[idx].value = base_url_str; ha_list[idx++].value_len = uni_strlen(base_url_str); const uni_char* rel_val = src_html_elm->GetStringAttr(Markup::HA_REL); if (rel_val == NULL) rel_val = UNI_L("stylesheet"); ha_list[idx].ns_idx = NS_IDX_DEFAULT; ha_list[idx].attr = Markup::HA_REL; ha_list[idx].value = rel_val; ha_list[idx++].value_len = uni_strlen(rel_val); const uni_char* title_val = src_html_elm->GetStringAttr(Markup::HA_TITLE); if (title_val) { ha_list[idx].ns_idx = NS_IDX_DEFAULT; ha_list[idx].attr = Markup::HA_TITLE; ha_list[idx].value = title_val; ha_list[idx++].value_len = uni_strlen(title_val); } ha_list[idx].attr = Markup::HA_NULL; new_elm = NEW_HTML_Element(); if (!new_elm || OpStatus::IsMemoryError(new_elm->Construct(m_hld_prof, NS_IDX_HTML, Markup::HTE_LINK, ha_list, HE_INSERTED_BY_CSS_IMPORT))) { DELETE_HTML_Element(new_elm); LEAVE(OpStatus::ERR_NO_MEMORY); } } else { /* Local style sheet. */ new_elm = g_cssManager->NewLinkElementL(url.GetAttribute(URL::KUniName_Username_Password_NOT_FOR_UI).CStr()); } /* Set media from @import rule as a media attribute. */ if (media_obj.get()) new_elm->SetLinkStyleMediaObject(media_obj.release()); /* Add the import link element into the dom tree under the parent stylesheet element. */ new_elm->Under(src_html_elm); /* Insert the import rule into the stylesheet. */ CSS_ImportRule* import_rule = OP_NEW_L(CSS_ImportRule, (new_elm)); AddRuleL(import_rule); #ifdef SCOPE_CSS_RULE_ORIGIN import_rule->SetLineNumber(m_lexer.GetCurrentLineNo()); #endif // SCOPE_CSS_RULE_ORIGIN /* No charset rules allowed after imports. */ SetAllowLevel(ALLOW_IMPORT); /* Start loading the stylesheet. */ if (m_hld_prof) LEAVE_IF_FATAL(m_hld_prof->HandleLink(new_elm)); else LEAVE_IF_FATAL(g_cssManager->LoadCSS_URL(new_elm, m_stylesheet->GetUserDefined())); } void CSS_Parser::EndRulesetL() { OP_ASSERT(m_current_props); CSS_StyleRule* style_rule = OP_NEW_L(CSS_StyleRule, ()); #ifdef SCOPE_CSS_RULE_ORIGIN style_rule->SetLineNumber(m_rule_line_no); #endif // SCOPE_CSS_RULE_ORIGIN CSS_Selector* sel; while ((sel = static_cast<CSS_Selector*>(m_selector_list.First()))) { sel->Out(); style_rule->AddSelector(sel); } style_rule->SetPropertyList(m_hld_prof, m_current_props, TRUE); AddRuleL(style_rule); SetAllowLevel(ALLOW_STYLE); } void CSS_Parser::EndPageRulesetL(uni_char* name) { OP_ASSERT(m_current_props); CSS_PageRule* page_rule = OP_NEW(CSS_PageRule, ()); if (!page_rule) { OP_DELETEA(name); LEAVE(OpStatus::ERR_NO_MEMORY); } page_rule->SetName(name); CSS_Selector* sel; while ((sel = static_cast<CSS_Selector*>(m_selector_list.First()))) { sel->Out(); page_rule->AddSelector(sel); } page_rule->SetPropertyList(m_hld_prof, m_current_props, TRUE); AddRuleL(page_rule); SetAllowLevel(ALLOW_STYLE); } void CSS_Parser::AddSupportsRuleL() { OP_ASSERT(m_condition_list && !m_condition_list->next); CSS_SupportsRule* rule = OP_NEW_L(CSS_SupportsRule, (m_condition_list)); m_condition_list = NULL; AddRuleL(rule); SetAllowLevel(ALLOW_STYLE); } void CSS_Parser::AddMediaRuleL() { CSS_MediaRule* rule = OP_NEW_L(CSS_MediaRule, (m_current_media_object)); m_current_media_object = NULL; AddRuleL(rule); SetAllowLevel(ALLOW_STYLE); } void CSS_Parser::TerminateLastDecl() { if (m_last_decl && m_current_props) { CSS_decl* decl; while ((decl = m_current_props->GetLastDecl()) && decl != m_last_decl) { decl->Out(); OP_DELETE(decl); } } } void CSS_Parser::EndSelectorL(uni_char* page_name) { OP_ASSERT(m_dom_rule); CSS_Rule::Type type = m_dom_rule->GetType(); OP_ASSERT(type == CSS_Rule::STYLE || type == CSS_Rule::PAGE); CSS_StyleRule* rule = static_cast<CSS_StyleRule*>(m_dom_rule); if (m_stylesheet) m_stylesheet->RuleRemoved(m_hld_prof, rule); rule->DeleteSelectors(); CSS_Selector* sel; CSS_property_list* pl = rule->GetPropertyList(); unsigned int flags = CSS_property_list::HAS_NONE; if (pl && type == CSS_Rule::STYLE) flags = pl->PostProcess(FALSE, TRUE); while ((sel = static_cast<CSS_Selector*>(m_selector_list.First()))) { sel->Out(); if (flags & CSS_property_list::HAS_CONTENT) sel->SetHasContentProperty(TRUE); if (flags & CSS_property_list::HAS_URL_PROPERTY) sel->SetMatchPrefetch(TRUE); rule->AddSelector(sel); } if (page_name) { OP_ASSERT(rule->GetType() == CSS_Rule::PAGE); static_cast<CSS_PageRule*>(rule)->SetName(page_name); } if (m_stylesheet) LEAVE_IF_ERROR(m_stylesheet->RuleInserted(m_hld_prof, rule)); } #ifdef MEDIA_HTML_SUPPORT void CSS_Parser::BeginCueSelector() { OP_ASSERT(m_cue_selector_list.Empty()); m_saved_current_selector = m_current_selector; m_current_selector = NULL; m_in_cue = TRUE; } void CSS_Parser::EndCueSelector() { OP_ASSERT(m_in_cue); m_current_selector = m_saved_current_selector; m_saved_current_selector = NULL; m_in_cue = FALSE; } void CSS_Parser::AddCueRootSelectorL() { OP_ASSERT(m_current_selector); CSS_SimpleSelector* simple_sel = OP_NEW_L(CSS_SimpleSelector, (Markup::CUEE_ROOT)); simple_sel->SetNameSpaceIdx(NS_IDX_CUE); simple_sel->SetSerialize(FALSE); m_current_selector->PrependSimpleSelector(simple_sel); } static bool IsValidCueElementType(Markup::Type elm_type) { switch (elm_type) { case Markup::CUEE_B: case Markup::CUEE_C: case Markup::CUEE_I: case Markup::CUEE_U: case Markup::CUEE_V: return true; case Markup::HTE_ANY: return true; } return false; } static bool RewriteCueRoot(CSS_SimpleSelector* simple_sel) { OP_ASSERT(simple_sel && simple_sel->Pred() == NULL); // Does this simple selector match '*|*:root'? if (simple_sel->Suc() != NULL || simple_sel->GetElm() != Markup::HTE_ANY || simple_sel->GetNameSpaceIdx() != NS_IDX_ANY_NAMESPACE) return false; CSS_SelectorAttribute* sel_attr = simple_sel->GetFirstAttr(); if (!sel_attr || sel_attr->Suc() != NULL) return false; if (sel_attr->GetType() != CSS_SEL_ATTR_TYPE_PSEUDO_CLASS || sel_attr->GetPseudoClass() != PSEUDO_CLASS_ROOT) return false; // It matched, so rewrite it. if (sel_attr->IsNegated()) { sel_attr->SetType(CSS_SEL_ATTR_TYPE_ELM); sel_attr->SetAttr(Markup::CUEE_ROOT); sel_attr->SetNsIdx(NS_IDX_CUE); } else { simple_sel->RemoveAttrs(); simple_sel->SetElm(Markup::CUEE_ROOT); } simple_sel->SetNameSpaceIdx(NS_IDX_CUE); simple_sel->SetSerialize(FALSE); return true; } static void RewriteCueSelector(CSS_Selector* selector) { CSS_SimpleSelector* simple_sel = selector->FirstSelector(); // Match and rewrite :root to 'cue'|'root' (the 'root' element in // the CUE namespace). if (RewriteCueRoot(simple_sel)) return; while (simple_sel) { // Force matching in the cue namespace and filter out any // invalid element references. if ((simple_sel->GetNameSpaceIdx() == NS_IDX_ANY_NAMESPACE || simple_sel->GetNameSpaceIdx() == NS_IDX_DEFAULT) && IsValidCueElementType(simple_sel->GetElm())) simple_sel->SetNameSpaceIdx(NS_IDX_CUE); else simple_sel->SetNameSpaceIdx(NS_IDX_NOT_FOUND); // Disable serialization. simple_sel->SetSerialize(FALSE); simple_sel = simple_sel->Suc(); } } // Clone all the simple selectors sel and put them in the cloned_simple_sels. static OP_STATUS CloneSimpleSelectors(CSS_Selector* sel, Head& cloned_simple_sels) { CSS_SimpleSelector* simple_sel = sel->FirstSelector(); while (simple_sel) { CSS_SimpleSelector* simple_sel_clone = simple_sel->Clone(); if (!simple_sel_clone) return OpStatus::ERR_NO_MEMORY; simple_sel_clone->Into(&cloned_simple_sels); simple_sel = simple_sel->Suc(); } return OpStatus::OK; } OP_STATUS CSS_Parser::ApplyCueSelectors() { OP_ASSERT(m_current_selector); OpAutoPtr<CSS_Selector> selector_cleaner(m_current_selector); CSS_Selector* cue_prefix = m_current_selector; m_current_selector = NULL; AutoDeleteHead cue_selector_list; cue_selector_list.Append(&m_cue_selector_list); CSS_SimpleSelector* cue_sel = NULL; BOOL is_first_selector = TRUE; TempBuffer serialized_selector; // "Prefix" (using the descendant combinator) the selectors with // the cue prefix selector: // // <prefix>::cue(a, b) => <prefix> a, <prefix> b // while (CSS_Selector* sel = static_cast<CSS_Selector*>(cue_selector_list.First())) { if (!is_first_selector) RETURN_IF_ERROR(serialized_selector.Append(", ")); RETURN_IF_ERROR(sel->GetSelectorText(m_stylesheet, &serialized_selector)); RewriteCueSelector(sel); AutoDeleteHead cloned_simple_sels; RETURN_IF_ERROR(CloneSimpleSelectors(cue_prefix, cloned_simple_sels)); if (is_first_selector) cue_sel = static_cast<CSS_SimpleSelector*>(cloned_simple_sels.Last()); sel->Out(); // Prepend the prefix. sel->Prepend(cloned_simple_sels); // Only the first selector of the resulting N should be // serialized. sel->SetSerialize(is_first_selector); if (is_first_selector) is_first_selector = FALSE; sel->CalculateSpecificity(); sel->Into(&m_selector_list); } // Set the serialization of the cue selectors on the ::cue // CSS_SelectorAttribute. uni_char* serialized_cue_str = UniSetNewStr(serialized_selector.GetStorage()); cue_sel->GetLastAttr()->SetCueString(serialized_cue_str); return OpStatus::OK; } #endif // MEDIA_HTML_SUPPORT #if defined(CSS_ERROR_SUPPORT) void CSS_Parser::EmitErrorL(const uni_char* message, OpConsoleEngine::Severity severity) { if (!g_console->IsLogging()) return; // Maximum length of source text in error message const int max_src_length = 80; const int max_css_errors = 100; OpConsoleEngine::Message cmessage(OpConsoleEngine::CSS, severity); ANCHOR(OpConsoleEngine::Message, cmessage); // Set the window id. if (m_hld_prof && m_hld_prof->GetFramesDocument() && m_hld_prof->GetFramesDocument()->GetWindow()) cmessage.window = m_hld_prof->GetFramesDocument()->GetWindow()->Id(); HTML_Element* src_elm = m_stylesheet ? m_stylesheet->GetHtmlElement() : NULL; const URL* sheet_url = NULL; // Set the context. if (!m_stylesheet) { if (m_hld_prof) { if (m_hld_prof->GetCssErrorCount() >= max_css_errors) return; m_hld_prof->IncCssErrorCount(); } if (GetDOMProperty() == -1) cmessage.context.SetL("HTML style attribute"); else cmessage.context.SetL("DOM style property"); } else if (!src_elm || src_elm->IsStyleElement()) { cmessage.context.SetL("Inlined stylesheet"); } else if (src_elm->IsLinkElement()) { cmessage.context.SetL("Linked-in stylesheet"); } // Set the url of the stylesheet. Use the document url if inlined. if (!src_elm || src_elm->IsStyleElement()) { sheet_url = &m_base_url; } else if (src_elm->IsLinkElement()) sheet_url = m_stylesheet->GetHRef(m_hld_prof ? m_hld_prof->GetLogicalDocument() : NULL); if (sheet_url) sheet_url->GetAttribute(URL::KUniName, cmessage.url); // Set the error message itself. cmessage.message.SetL(message); LEAVE_IF_ERROR(cmessage.message.AppendFormat(UNI_L("\n\nLine %d:\n "), m_document_line + m_lexer.GetCurrentLineNo() - 1)); int line_pos = m_lexer.GetCurrentLinePos(); if (line_pos > max_src_length) line_pos = max_src_length; uni_char* current_line = m_lexer.GetCurrentLineString(max_src_length); if (!current_line) LEAVE(OpStatus::ERR_NO_MEMORY); uni_char* tmp = current_line; while (*tmp) if (*tmp == '\t') *tmp++ = ' '; else tmp++; ANCHOR_ARRAY(uni_char, current_line); cmessage.message.AppendL(current_line); ANCHOR_ARRAY_DELETE(current_line); cmessage.message.AppendL("\n "); cmessage.message.ReserveL(cmessage.message.Length()+line_pos+1); for (int i=0; i<line_pos; i++) { cmessage.message.AppendL("-"); } cmessage.message.AppendL("^"); g_console->PostMessageL(&cmessage); if (!m_stylesheet && m_hld_prof && m_hld_prof->GetCssErrorCount() >= max_css_errors) { cmessage.message.SetL("Too many CSS errors... bailing out."); g_console->PostMessageL(&cmessage); } } void CSS_Parser::InvalidDeclarationL(DeclStatus error, short property) { const char* prop_name; prop_name = GetCSS_PropertyName(property); OP_ASSERT(prop_name); OpString msg; ANCHOR(OpString, msg); msg.SetL(prop_name); msg.MakeLower(); LEAVE_IF_ERROR(msg.Insert(0, "Invalid value for property: ")); EmitErrorL(msg.CStr(), OpConsoleEngine::Error); } #endif // CSS_ERROR_SUPPORT void CSS_Parser::InvalidBlockHit() { if (m_stylesheet && !m_stylesheet->HasRules()) m_stylesheet->SetHasSyntacticallyValidCSSHeader(FALSE); } CSS_decl::DeclarationOrigin CSS_Parser::GetCurrentOrigin() const { #ifdef CSS_ANIMATIONS if (m_decl_type == DECL_KEYFRAMES) return CSS_decl::ORIGIN_ANIMATIONS; else #endif if (m_user) return CSS_decl::ORIGIN_USER; else return CSS_decl::ORIGIN_AUTHOR; }
// Copyright 2011 Yandex #include <gtest/gtest.h> #include "ltr/data/data_set.h" #include "ltr/data/object.h" #include "ltr/data/feature_info.h" #include "ltr/utility/numerical.h" #include "ltr/parameters_container/parameters_container.h" #include "ltr/learners/composition_learner/composition_learner.h" #include "ltr/scorers/composition_scorers/linear_composition_scorer.h" #include "ltr/scorers/composition_scorers/max_weight_composition_scorer.h" #include "ltr/scorers/composition_scorers/median_composition_scorer.h" #include "ltr/scorers/composition_scorers/order_statistic_composition_scorer.h" #include "ltr/learners/best_feature_learner/best_feature_learner.h" #include "ltr/measures/abs_error.h" #include "ltr/measures/true_point.h" using ltr::Object; using ltr::DataSet; using ltr::FeatureInfo; using ltr::utility::DoubleEqual; using ltr::ParametersContainer; using ltr::composition::LinearCompositionScorer; using ltr::composition::MaxWeightCompositionScorer; using ltr::composition::MedianCompositionScorer; using ltr::composition::OrderStatisticCompositionScorer; using ltr::composition::CompositionLearner; using ltr::BestFeatureLearner; using ltr::AbsError; using ltr::TruePoint; const int data_size = 11; class CompositionLearnerTest : public ::testing::Test { public: CompositionLearnerTest() : data(FeatureInfo(4)) {} protected: virtual void SetUp() { for (int i = 0; i < data_size; ++i) { Object object; object << i << data_size - i << i * i << i * (data_size - i); object.set_actual_label(i); object.set_predicted_label(data_size - i); data.add(object); } } DataSet<Object> data; }; TEST_F(CompositionLearnerTest, LinearCompositionLearnerTest) { CompositionLearner<Object, LinearCompositionScorer> linear_composition_learner(9); AbsError::Ptr abs_error(new AbsError); BestFeatureLearner<Object>::Ptr best_feature_learner(new BestFeatureLearner<Object>(abs_error)); linear_composition_learner.set_weak_learner(best_feature_learner); linear_composition_learner.learn(data); LinearCompositionScorer::Ptr linear_composition_scorer = linear_composition_learner.makeSpecific(); EXPECT_EQ(9, linear_composition_scorer->size()); for (int i = 0; i < linear_composition_scorer->size(); ++i) { linear_composition_scorer->at(i).scorer->predict(data); EXPECT_TRUE(DoubleEqual(0.0, abs_error->average(data))) << abs_error->average(data); } } TEST_F(CompositionLearnerTest, MaxWeightCompositionLearnerTest) { CompositionLearner<Object, MaxWeightCompositionScorer> composition_learner(9); AbsError::Ptr abs_error(new AbsError); BestFeatureLearner<Object>::Ptr best_feature_learner(new BestFeatureLearner<Object>(abs_error)); composition_learner.set_weak_learner(best_feature_learner); composition_learner.learn(data); MaxWeightCompositionScorer::Ptr composition_scorer = composition_learner.makeSpecific(); EXPECT_EQ(9, composition_scorer->size()); for (int i = 0; i < composition_scorer->size(); ++i) { composition_scorer->at(i).scorer->predict(data); EXPECT_TRUE(DoubleEqual(0.0, abs_error->average(data))) << abs_error->average(data); } } TEST_F(CompositionLearnerTest, MedianCompositionLearnerTest) { CompositionLearner<Object, MedianCompositionScorer> composition_learner(9); AbsError::Ptr abs_error(new AbsError); BestFeatureLearner<Object>::Ptr best_feature_learner(new BestFeatureLearner<Object>(abs_error)); composition_learner.set_weak_learner(best_feature_learner); composition_learner.learn(data); MedianCompositionScorer::Ptr composition_scorer = composition_learner.makeSpecific(); EXPECT_EQ(9, composition_scorer->size()); for (int i = 0; i < composition_scorer->size(); ++i) { composition_scorer->at(i).scorer->predict(data); EXPECT_TRUE(DoubleEqual(0.0, abs_error->average(data))) << abs_error->average(data); } } TEST_F(CompositionLearnerTest, OrderStaticticCompositionLearnerTest) { OrderStatisticCompositionScorer os_composition_scorer(0.3); CompositionLearner<Object, OrderStatisticCompositionScorer> composition_learner(9); composition_learner.setInitialScorer(os_composition_scorer); AbsError::Ptr abs_error(new AbsError); BestFeatureLearner<Object>::Ptr best_feature_learner(new BestFeatureLearner<Object>(abs_error)); composition_learner.set_weak_learner(best_feature_learner); composition_learner.learn(data); OrderStatisticCompositionScorer::Ptr composition_scorer = composition_learner.makeSpecific(); EXPECT_EQ(9, composition_scorer->size()); for (int i = 0; i < composition_scorer->size(); ++i) { composition_scorer->at(i).scorer->predict(data); EXPECT_TRUE(DoubleEqual(0.0, abs_error->average(data))) << abs_error->average(data); } }
#include <algorithm> #include "../chapter2-sorting-basic/SortTestHelper.h" using namespace std; template <typename T> int partition(T arr[], int l, int r) { int v = arr[l]; int i = l; int j = r + 1; while (true) { while (arr[++i] < v) if (i >= r) break; while (arr[--j] > v) if (j <= l) break; if (i >= j) break; swap(arr[i], arr[j]); } swap(arr[l], arr[j]); return j; } template <typename T> void __quickSort(T arr[], int l, int r) { if (l >= r) return; int p = partition(arr, l, r); __quickSort(arr, l, p - 1); __quickSort(arr, p + 1, r); } template <typename T> void quickSort(T arr[], int n) { return __quickSort(arr, 0, n - 1); } template <typename T> void _quickSort3Ways(T arr[], int l, int r) { if (l >= r) return; T v = arr[l]; int lt = l; int gt = r + 1; int i = l + 1; while (i < gt) { if (arr[i] < v) { swap(arr[lt + 1], arr[i]); ++lt; ++i; } else if (arr[i] > v) { swap(arr[i], arr[gt - 1]); --gt; } else { ++i; } } swap(arr[l], arr[lt]); _quickSort3Ways(arr, l, lt - 1); _quickSort3Ways(arr, gt, r); } template <typename T> void quickSort3Ways(T arr[], int n) { _quickSort3Ways(arr, 0, n - 1); } int main() { int n = 1e6; int *arr = SortTestHelper::generateRandomArray(n, 0, n); assert(SortTestHelper::isSorted(arr, n) == false); quickSort(arr, n); assert(SortTestHelper::isSorted(arr, n) == true); int *arr2 = SortTestHelper::generateRandomArray(n, 0, n); SortTestHelper::testSort("quickSort", quickSort, arr2, n); int *arr3 = SortTestHelper::generateRandomArray(n, 0, n); assert(SortTestHelper::isSorted(arr3, n) == false); delete[] arr; delete[] arr2; delete[] arr3; }
#pragma once #include <Vector> #include "Person.h" class region //change this to individual based rather than floats. { private: std::vector<Person*> populationList; float density; int population; int x; //position on the grid. int y; public: region(int pop, float d, int x_n, int y_n ); ~region(); void update(float transmission); void update(int strainNum, float transmission); void update(float* transmission); void infectNIndividuals(int N); int getTotalInfected(); int getStrainInfected(int strain); };
#include "WidgetRecognitionText.hh" #include "WidgetContainer.hh" #include "AudioStream.hh" #include <pglabel.h> WidgetRecognitionText::WidgetRecognitionText(PG_Widget *parent, const PG_Rect &rect, AudioInputController *audio_input, RecognizerStatus *recognition, unsigned int pixels_per_second) : WidgetScrollArea(parent, rect), m_pixels_per_second(pixels_per_second) { this->m_audio_input = audio_input; this->m_recognition = recognition; this->initialize(); } WidgetRecognitionText::~WidgetRecognitionText() { this->terminate(); } void WidgetRecognitionText::initialize() { this->m_last_recognition_count = 0; this->m_last_recog_word = NULL; this->m_last_recog_morph = NULL; this->m_last_recognition_frame = 0; } void WidgetRecognitionText::terminate() { this->RemoveAllChilds(); this->m_hypothesis_widgets.clear(); } void WidgetRecognitionText::update() { this->m_recognition->lock(); unsigned long frame = this->m_recognition->get_recognition_frame(); if (frame > this->m_last_recognition_frame || m_recognition->m_message_result_true_called) { this->update_recognition(); this->update_hypothesis(); this->m_last_recognition_frame = frame; } this->m_recognition->unlock(); } void WidgetRecognitionText::reset() { this->terminate(); this->initialize(); } PG_Widget* WidgetRecognitionText::add_morpheme_widget(const Morpheme &morpheme, const PG_Color &color, PG_Widget *&word_widget, Sint32 min_x) { // Calculate recognizer pixels per recognizer frame. double multiplier = this->m_pixels_per_second / (double)RecognizerStatus::frames_per_second; unsigned int w = (int)(morpheme.duration * multiplier); Sint32 x = (Sint32)(morpheme.time * multiplier); // Word break. if (morpheme.data == " " || morpheme.data == "." || morpheme.data == "") word_widget = NULL; //* min_x is used to force word breaks. // These lines may be commented out if forcing is undesired. Note that // then sentence breaks will most likely be then hidden. if (x < min_x) { // Cut width. if ((Sint32)w + x > min_x) w = (long)(w + x) - min_x; else w = 1; // Set new position. x = min_x; } //*/ PG_Rect rect(0, 0, w, this->my_height); PG_Widget *morph_widget = NULL; if (morpheme.data != " " && morpheme.data != "") { if (morpheme.data == ".") { // One pixel wide separator for sentence breaks. rect.w = 1; morph_widget = new PG_Widget(NULL, rect, true); SDL_FillRect(morph_widget->GetWidgetSurface(), NULL, color.MapRGB(morph_widget->GetWidgetSurface()->format)); // We need to use this for x coordinate. (See WidgetScrollArea for more // information. morph_widget->SetUserData(&x, sizeof(Sint32)); this->AddChild(morph_widget); morph_widget->SetVisible(true); } else { if (word_widget == NULL) { word_widget = new WidgetContainer(NULL, 0, 0, PG_Color(90, 90, 90)); // We need to use this for x coordinate. (See WidgetScrollArea for more // information. word_widget->SetUserData(&x, sizeof(Sint32)); this->AddChild(word_widget); word_widget->SetVisible(true); } Sint32 word_x; word_widget->GetUserData(&word_x); rect.x = x - word_x; morph_widget = new PG_Label(word_widget, rect, morpheme.data.data()); ((PG_Label*)morph_widget)->SetAlignment(PG_Label::CENTER); morph_widget->SetFontColor(color); morph_widget->sigMouseButtonUp.connect(slot(*this, &WidgetRecognitionText::handle_morpheme_widget), NULL); morph_widget->SetVisible(true); } } return morph_widget; } void WidgetRecognitionText::update_recognition() { const MorphemeList &morphemes = this->m_recognition->get_recognized(); Sint32 min_x = 0; // Update if new morphemes has been recognized. if (morphemes.size() > this->m_last_recognition_count) { MorphemeList::const_iterator iter = morphemes.begin(); // Find the position of last recognized morpheme. for (unsigned int ind = 0; ind < this->m_last_recognition_count; ind++) iter++; // Add new recognized morphemes. for (; iter != morphemes.end(); iter++) { // Force at least 2 pixels between words/separators. if (!this->m_last_recog_word && this->m_last_recog_morph) { this->m_last_recog_morph->GetUserData(&min_x); min_x += this->m_last_recog_morph->my_width + 2; } PG_Widget *current_morph = this->add_morpheme_widget(*iter, PG_Color(255, 255, 255), this->m_last_recog_word, min_x); // Save latest non-null widget (word/separator). if (this->m_last_recog_word) this->m_last_recog_morph = this->m_last_recog_word; else if (current_morph) this->m_last_recog_morph = current_morph; } } this->m_last_recognition_count = morphemes.size(); } void WidgetRecognitionText::update_hypothesis() { PG_Widget *nonnull, *current_morph, *previous_word, *current_word; const MorphemeList &morphemes = this->m_recognition->get_hypothesis(); Sint32 min_x = 0; this->remove_hypothesis(); // Start where recognition ends. nonnull = NULL; current_morph = this->m_last_recog_morph; current_word = this->m_last_recog_word; for (MorphemeList::const_iterator iter = morphemes.begin(); iter != morphemes.end(); iter++) { // Save latest non-null widget (word/separator). if (current_word) nonnull = current_word; else if (current_morph) nonnull = current_morph; if (!current_word && nonnull) { nonnull->GetUserData(&min_x); min_x += nonnull->my_width + 2; } previous_word = current_word; // Add the morpheme. current_morph = this->add_morpheme_widget(*iter, PG_Color(255, 255, 0), current_word, min_x); // Handle three different possibilities for the hypothesis morpheme. if (current_word == NULL) { // Possible sentence break widget. if (current_morph) this->m_hypothesis_widgets.push_back(current_morph); } else { if (current_word == this->m_last_recog_word) { // Hypothesis morpheme continues recognized word. if (current_morph) this->m_hypothesis_widgets.push_back(current_morph); } else if (current_word != previous_word) { // New word, completely hypothesis. this->m_hypothesis_widgets.push_back(current_word); } } } } void WidgetRecognitionText::remove_hypothesis() { for (unsigned int i = 0; i < this->m_hypothesis_widgets.size(); i++) { // Set visibility to false to fix the destructor bug which otherwise // updates the screen area. this->m_hypothesis_widgets.at(i)->SetVisible(false); delete this->m_hypothesis_widgets.at(i); } this->m_hypothesis_widgets.clear(); } bool WidgetRecognitionText::handle_morpheme_widget(PG_MessageObject *widget, const SDL_MouseButtonEvent *event, void *user_data) { double multiplier = (double)audio::audio_sample_rate / this->m_pixels_per_second; unsigned long x = ((PG_Widget*)widget)->my_xpos; unsigned long w = ((PG_Widget*)widget)->my_width; x += this->get_scroll_position(); x = (unsigned long)(x * multiplier); w = (unsigned long)(w * multiplier); this->m_audio_input->stop_playback(); this->m_audio_input->start_playback(x, w); return true; }
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #include "ClearScreenGrid.h" #include "view/openGl/OpenGl.h" #include "Platform.h" #include "util/Config.h" #include <vector> namespace View { ClearScreenGrid::ClearScreenGrid () : density (20), gridVertsCount (0) { glGenBuffers (1, &gridBuffer); glGenBuffers (1, &axesBuffer); GLfloat w = config ()->projectionWidth; GLfloat h = config ()->projectionHeight; GLfloat w2 = w / 2; GLfloat h2 = h / 2; std::vector <GLfloat> verts; int numX = w / density + 0.5; int numY = h / density + 0.5; // Pionowe kreski for (int i = 1; i < numX; ++i) { GLfloat x = -w2 + i * density; verts.push_back (x); verts.push_back (h2 + 1); verts.push_back (x); verts.push_back (-h2 - 1); } // Poziome kreski for (int i = 1; i < numY; ++i) { GLfloat y = -h2 + i * density; verts.push_back (w2 + 1); verts.push_back (y); verts.push_back (-w2 - 1); verts.push_back (y); } gridVertsCount = verts.size () / 2u; glBindBuffer (GL_ARRAY_BUFFER, gridBuffer); glBufferData (GL_ARRAY_BUFFER, verts.size () * sizeof (GLfloat), &verts.front (), GL_STATIC_DRAW); glBindBuffer (GL_ARRAY_BUFFER, 0); GLfloat verts1[] = { -w2 - 1, 0, w2 + 1, 0, 0, -h2 - 1, 0, h2 + 1 }; glBindBuffer (GL_ARRAY_BUFFER, axesBuffer); glBufferData (GL_ARRAY_BUFFER, 8 * sizeof (GLfloat), verts1, GL_STATIC_DRAW); glBindBuffer (GL_ARRAY_BUFFER, 0); } /****************************************************************************/ ClearScreenGrid::~ClearScreenGrid () { glDeleteBuffers (1, &gridBuffer); glDeleteBuffers (1, &axesBuffer); } /****************************************************************************/ void ClearScreenGrid::update (Model::IModel *, Event::UpdateEvent *e, View::GLContext *ctx) { glClearColor (color.r, color.g, color.b, color.a); glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (gridColor.getA () <= 0) { return; } glLineWidth (1); glBindBuffer (GL_ARRAY_BUFFER, gridBuffer); glEnableVertexAttribArray (ctx->positionAttribLocation); glVertexAttribPointer (ctx->positionAttribLocation, 2, GL_FLOAT, GL_FALSE, 0, 0); glUniform4f (ctx->colorUniformLocation, gridColor.r, gridColor.g, gridColor.b, gridColor.a); glDrawArrays (GL_LINES, 0, gridVertsCount); glBindBuffer (GL_ARRAY_BUFFER, axesBuffer); glEnableVertexAttribArray (ctx->positionAttribLocation); glVertexAttribPointer (ctx->positionAttribLocation, 2, GL_FLOAT, GL_FALSE, 0, 0); glUniform4f (ctx->colorUniformLocation, gridColor.r - 0.1, gridColor.g - 0.1, gridColor.b - 0.1, gridColor.a); glDrawArrays (GL_LINES, 0, 4); glBindBuffer (GL_ARRAY_BUFFER, 0); } } /* namespace View */
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * @author Arjan van Leeuwen (arjanl) */ #ifndef X11_INPUT_CONTEXT #define X11_INPUT_CONTEXT #include "platforms/utilix/x11_all.h" #include "platforms/quix/utils/DebugLogger.h" class OpInputMethodListener; class OpInputMethodString; class X11Widget; struct IM_WIDGETINFO; class X11InputMethod; /** @brief Represents an X11 input context (XIC) and operations that can be executed on it */ class X11InputContext { public: /** Constructor */ X11InputContext(); ~X11InputContext(); /** Initialize this input context. * @param im Input method parameters to use when creating the XIC. * @param window Window to handle input events for. * @return OpStatus::OK on success, error codes otherwise */ OP_STATUS Init(X11InputMethod * im, X11Widget * window=0); /** Activate this input context and send IM events * @param listener Listener to send IM events to */ void Activate(OpInputMethodListener* listener); /** Deactivate this input context and stop sending IM events * @param listener Listener to stop sending IM events to */ void Deactivate(OpInputMethodListener* listener); /** Abort ongoing text compose */ void Abort(); /** Set focus window for this input context * @param window Window that has input focus */ void SetFocusWindow(X11Widget * window); /** Give the input context focus if this X11InputContext is * currently activated. This should typically be called to undo * the effect of UnsetFocus(). */ void SetFocusIfActive(); /** * Give the input context focus. */ void SetFocus(); /** Take away the input context focus. The focus should be unset * when the window it belongs to loses ordinary keyboard focus. */ void UnsetFocus(); /** Decode the key event in 'event', in the context of this input * context. * * @param event Keypress event to decode. * * @param keysym Keysym of the key press, NoSymbol if the event * does not represent a valid keysym. But see return value. * * @param text The text generated by the key press, empty if no * text is generated. But see return value. * * @return true on successful decoding, false on error. If this * method returns true and produces the keysym NoSymbol and an * empty 'text', the key event has been handled and should be * dropped. If this method returns false, 'keysym' and 'text' are * undefined. */ bool GetKeyPress(XEvent* event, KeySym& keysym, OpString& text); /** Informs this object that the X11InputMethod object that was * used in Init() is no longer valid and should not be accessed * any more. */ void InputMethodIsDeleted(); /** Informs this object that the XIM passed to Init() has been * destroyed. The X11InputMethod object is still alive, but the * XIM and all XICs created from it have been deleted and should * not be accessed any more. They should not even be closed by * calling XCloseIM() or XDestroyIC(). */ void XIMHasBeenDestroyed(); private: struct CallbackList { XVaNestedList list; OpAutoVector<XIMCallback> callbacks; CallbackList() : list(0) {} ~CallbackList() { if (list) XFree(list); } }; OP_STATUS CreatePreeditList(CallbackList& list); OP_STATUS CreateStatusList(CallbackList& status); OP_STATUS AddToCallbacks(CallbackList& list, XIMProc callback_func); /** Tell the input method where the text input area is. */ void SetTextArea(const IM_WIDGETINFO & wi); /** Remove all indications about where the currently active text * input area is. */ void ResetTextArea(); /** Sets up Opera to be in compose mode (if it isn't already) * @return whether this was successful */ bool StartComposing(); /** Exits compose mode in Opera. * * If cancel is false, the current pre-edit string will be * committed, otherwise the current pre-edit string will be * cleared. */ void StopComposing(bool cancel=false); /** Whether Opera is in compose mode */ bool IsComposing() { return m_listener && m_string; } void PreeditStart(); void PreeditDone(); void PreeditDraw(XIMPreeditDrawCallbackStruct* data); void DeleteFromPreedit(int pos, int length); void InsertIntoPreedit(int pos, const uni_char* string, int length); void InsertIntoPreedit(int pos, const char* string, int length); void DeterminePreeditUnderline(XIMFeedback* feedback, unsigned length); void PreeditCaret(XIMPreeditCaretCallbackStruct* data); void StatusStart(); void StatusDone(); void StatusDraw(XIMStatusDrawCallbackStruct* data); // Callbacks passed to XIC static int PreeditStartCallback(XIC ic, X11InputContext* input_context, XPointer call_data) { input_context->PreeditStart(); return 1024; } static void PreeditDoneCallback(XIC ic, X11InputContext* input_context, XPointer call_data) { input_context->PreeditDone(); } static void PreeditDrawCallback(XIC ic, X11InputContext* input_context, XIMPreeditDrawCallbackStruct* call_data) { input_context->PreeditDraw(call_data); } static void PreeditCaretCallback(XIC ic, X11InputContext* input_context, XIMPreeditCaretCallbackStruct* call_data) { input_context->PreeditCaret(call_data); } static void StatusStartCallback(XIC ic, X11InputContext* input_context, XPointer call_data) { input_context->StatusStart(); } static void StatusDoneCallback(XIC ic, X11InputContext* input_context, XPointer call_data) { input_context->StatusDone(); } static void StatusDrawCallback(XIC ic, X11InputContext* input_context, XIMStatusDrawCallbackStruct* call_data) { input_context->StatusDraw(call_data); } XIC m_xic; X11InputMethod * m_im; OpString8 m_keybuf; OpInputMethodListener* m_listener; OpInputMethodString* m_string; X11Widget * m_focus_window; DebugLogger m_logger; }; #endif // X11_INPUT_CONTEXT
#include<iostream> #include<fstream> #include<vector> #include<queue> #include<sys/time.h> using namespace std; struct timeval start, endf; struct nodeComponent{ int node; int componentId; }; class Comparator { public: bool operator()(nodeComponent& n1, nodeComponent& n2) { if (n1.componentId > n2.componentId) return true; else return false; } }; int main(int argc, char **argv){ bool output = false; if(argc < 2){ std::cout << "No input name given." << std::endl; exit(0); } if(argc > 2){ output = true; } char *filename = argv[1]; int vCount, nEdges; ifstream read(filename); read >> vCount >> nEdges; int source, destination; /*Vector to store outgoing edges.*/ vector< vector<int> > outgoingVertices(vCount); vector<int> componentId(vCount); //Declaring Priority queue priority_queue< nodeComponent, vector< nodeComponent >, Comparator> worklist; while(read >> source >> destination){ outgoingVertices[source].push_back(destination); outgoingVertices[destination].push_back(source); } gettimeofday(&start, NULL); //start time of the actual page rank algorithm /*initalizing the component ids and worklist*/ for (int i = 0; i < vCount; i++) { nodeComponent nd; nd.node = i; nd.componentId = i; componentId[i] = i; worklist.push(nd); } while(!worklist.empty()){ nodeComponent node_component = worklist.top(); worklist.pop(); int vertex = node_component.node; for (int i = 0; i < outgoingVertices[vertex].size(); i++) { if(componentId[vertex] < componentId[outgoingVertices[vertex][i]]){ componentId[outgoingVertices[vertex][i]] = componentId[vertex]; nodeComponent nd; nd.node = outgoingVertices[vertex][i]; nd.componentId = componentId[vertex]; worklist.push(nd); } } } gettimeofday(&endf, NULL); //page rank ends here if(output){ for (int i = 0; i < componentId.size(); i++) { std::cout << i << " " << componentId[i] << std::endl; } } cout << "Time taken by sequential fifo queue implementation on " << vCount << " nodes is " << (((endf.tv_sec - start.tv_sec) * 1000000u + endf.tv_usec - start.tv_usec) / 1.e6) << endl; }
/* -*- 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. */ #ifndef DOM_EXTENSIONS_TABAPICACHE_H #define DOM_EXTENSIONS_TABAPICACHE_H #ifdef DOM_EXTENSIONS_TAB_API_SUPPORT #include "modules/dom/src/extensions/domextensionsupport.h" #include "modules/windowcommander/OpTabAPIListener.h" class DOM_Runtime; class DOM_TabApiCachedObject; class DOM_BrowserTab; class DOM_BrowserTabGroup; class DOM_BrowserWindow; class DOM_TabApiCache : OpTabAPIListener::ExtensionWindowTabActionListener , public OpHashTableForEachListener { friend class DOM_TabApiCachedObject; public: ~DOM_TabApiCache(); static OP_STATUS Make(DOM_TabApiCache*& new_obj, DOM_ExtensionSupport* extension_support); static OP_STATUS GetOrCreateTab(DOM_BrowserTab*& new_obj, DOM_ExtensionSupport* extension_support, OpTabAPIListener::TabAPIItemId tab_id, unsigned long window_id, DOM_Runtime* origining_runtime); static OP_STATUS GetOrCreateTabGroup(DOM_BrowserTabGroup*& new_obj, DOM_ExtensionSupport* extension_support, OpTabAPIListener::TabAPIItemId tab_group_id, DOM_Runtime* origining_runtime); static OP_STATUS GetOrCreateWindow(DOM_BrowserWindow*& new_obj, DOM_ExtensionSupport* extension_support, OpTabAPIListener::TabAPIItemId win_id, DOM_Runtime* origining_runtime); virtual void OnBrowserWindowAction(ActionType action, OpTabAPIListener::TabAPIItemId window_id, ActionData* data); virtual void OnTabAction(ActionType action, OpTabAPIListener::TabAPIItemId tab_id, unsigned int tab_window_id, ActionData* data); virtual void OnTabGroupAction(ActionType action, OpTabAPIListener::TabAPIItemId tab_group_id, ActionData* data); void GCTrace(); // OpHashTableForEachListener implementation. virtual void HandleKeyData(const void* key, void* data); private: DOM_TabApiCache(DOM_ExtensionSupport* extension_support); OP_STATUS Construct(); void OnCachedObjectDestroyed(DOM_TabApiCachedObject* object); /**< Called by DOM_TabApiCachedObject destructor. */ OpINT32HashTable<DOM_TabApiCachedObject> m_cached_objects; OpSmartPointerWithDelete<DOM_ExtensionSupport> m_extension_support; }; #endif // DOM_EXTENSIONS_TAB_API_SUPPORT #endif // DOM_EXTENSIONS_TABAPICACHE_H
/* Copyright © 2006, Drollic All rights reserved. http://www.drollic.com Redistribution of this software in source or binary forms, with or without modification, is expressly prohibited. You may not reverse-assemble, reverse-compile, or otherwise reverse-engineer this software in any way. THIS SOFTWARE ("SOFTWARE") IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "stdafx.h" #include "WaveletNativeMomentPainterWrapper.h" #include "ImageConversion.h" #include "NativeStroke.h" #include "ComputationProgress.h" #include "WaveletNativeMomentsPainter.h" #include <list> #include <vector> #include <queue> #pragma managed using namespace System; using namespace System::Collections; using namespace com::drollic::util; using namespace com::drollic::graphics::painting::native::processing; namespace com { namespace drollic { namespace graphics { namespace painting { namespace native { namespace wrapper { int WaveletNativeMomentPainterWrapper::GetPercentComplete() { return ComputationProgress::Instance()->percentComplete; } UnsafeBitmap^ WaveletNativeMomentPainterWrapper::CreatePaintingV2(int width, int height, array<UnsafeBitmap^>^ originals, array<UnsafeBitmap^>^ transformed, array<UnsafeBitmap^>^ strokes, int S) { array<UnsafeBitmap^>^ garbage; return CreatePaintingV2(width, height, originals, transformed, strokes, S, false, garbage); } UnsafeBitmap^ WaveletNativeMomentPainterWrapper::CreatePaintingV2(int width, int height, array<UnsafeBitmap^>^ originals, array<UnsafeBitmap^>^ transformed, array<UnsafeBitmap^>^ strokes, int S, bool generateMovie, array<UnsafeBitmap^>^ introFrames) { // Sanity check inputs if (originals->Length != transformed->Length) { ComputationProgress::Instance()->percentComplete = 100; UnsafeBitmap^ dummy; return dummy; } ComputationProgress::Instance()->percentComplete = 0; std::vector<FastRawImage*> inputOriginals; std::vector<FastRawImage*> inputTransformed; static std::vector<FastRawImage*> faststrokes; float percentWorkForAllConversion = 5.0; // Five percent float percentWorkDonePerConversion = percentWorkForAllConversion / (originals->Length * 2); for (int i=0; i < originals->Length; i++) { ComputationProgress::Instance()->percentComplete += 1; inputOriginals.push_back(ImageConversion::Unsafe2FastRaw(originals[i])); // Update percentage work done ComputationProgress::Instance()->percentComplete += static_cast<int>(percentWorkDonePerConversion); inputTransformed.push_back(ImageConversion::Unsafe2FastRaw(transformed[i])); // Update percentage work done ComputationProgress::Instance()->percentComplete += static_cast<int>(percentWorkDonePerConversion); } // The faststrokes collection is static, so this // work only needs to be done once. if (faststrokes.size() == 0) { for (int i=0; i < strokes->Length; i++) { faststrokes.push_back(ImageConversion::Unsafe2FastRaw(strokes[i])); } } WaveletNativeMomentsPainter painter(width, height, inputOriginals, inputTransformed, faststrokes, S); // Convert intro movie frames, if movie generation has been enabled std::vector<FastRawImage*> inputIntroMovieFrames; if (generateMovie) { // Convert intro movie frames for (int i=0; i < introFrames->Length; i++) { inputIntroMovieFrames.push_back(ImageConversion::Unsafe2FastRaw(introFrames[i])); } // Pass movie frames, and enable movie generation painter.EnableMovieGeneration(inputIntroMovieFrames, "junk"); } FastRawImage* painting = painter.CreatePaintingV2(); UnsafeBitmap^ result = ImageConversion::FastRaw2Unsafe(painting); for (unsigned int i=0; i < inputOriginals.size(); i++) { delete inputOriginals[i]; delete inputTransformed[i]; inputOriginals[i] = NULL; inputTransformed[i] = NULL; } // The faststrokes colleciton is static, so we DO NOT delete the // contents of the collection. // Delete title movie frame, if it was created for (unsigned int i=0; i < inputIntroMovieFrames.size(); i++) { delete inputIntroMovieFrames[i]; } delete painting; return result; } UnsafeBitmap^ WaveletNativeMomentPainterWrapper::CreatePainting(int width, int height, array<UnsafeBitmap^>^ originals, array<UnsafeBitmap^>^ transformed, array<UnsafeBitmap^>^ strokes, int S) { array<UnsafeBitmap^>^ garbage; return CreatePainting(width, height, originals, transformed, strokes, S, false, garbage); } UnsafeBitmap^ WaveletNativeMomentPainterWrapper::CreatePainting(int width, int height, array<UnsafeBitmap^>^ originals, array<UnsafeBitmap^>^ transformed, array<UnsafeBitmap^>^ strokes, int S, bool generateMovie, array<UnsafeBitmap^>^ introFrames) { // Sanity check inputs if (originals->Length != transformed->Length) { ComputationProgress::Instance()->percentComplete = 100; UnsafeBitmap^ dummy; return dummy; } ComputationProgress::Instance()->percentComplete = 0; std::vector<FastRawImage*> inputOriginals; std::vector<FastRawImage*> inputTransformed; static std::vector<FastRawImage*> faststrokes; float percentWorkForAllConversion = 5.0; // Five percent float percentWorkDonePerConversion = percentWorkForAllConversion / (originals->Length * 2); for (int i=0; i < originals->Length; i++) { ComputationProgress::Instance()->percentComplete += 1; inputOriginals.push_back(ImageConversion::Unsafe2FastRaw(originals[i])); // Update percentage work done ComputationProgress::Instance()->percentComplete += static_cast<int>(percentWorkDonePerConversion); inputTransformed.push_back(ImageConversion::Unsafe2FastRaw(transformed[i])); // Update percentage work done ComputationProgress::Instance()->percentComplete += static_cast<int>(percentWorkDonePerConversion); } // The faststrokes collection is static, so this // work only needs to be done once. if (faststrokes.size() == 0) { for (int i=0; i < strokes->Length; i++) { faststrokes.push_back(ImageConversion::Unsafe2FastRaw(strokes[i])); } } WaveletNativeMomentsPainter painter(width, height, inputOriginals, inputTransformed, faststrokes, S); // Convert intro movie frames, if movie generation has been enabled std::vector<FastRawImage*> inputIntroMovieFrames; if (generateMovie) { // Convert intro movie frames for (int i=0; i < introFrames->Length; i++) { inputIntroMovieFrames.push_back(ImageConversion::Unsafe2FastRaw(introFrames[i])); } // Pass movie frames, and enable movie generation painter.EnableMovieGeneration(inputIntroMovieFrames, "junk"); } FastRawImage* painting = painter.CreatePainting(); UnsafeBitmap^ result = ImageConversion::FastRaw2Unsafe(painting); for (unsigned int i=0; i < inputOriginals.size(); i++) { delete inputOriginals[i]; delete inputTransformed[i]; inputOriginals[i] = NULL; inputTransformed[i] = NULL; } // The faststrokes colleciton is static, so we DO NOT delete the // contents of the collection. // Delete title movie frame, if it was created for (unsigned int i=0; i < inputIntroMovieFrames.size(); i++) { delete inputIntroMovieFrames[i]; } delete painting; return result; } WaveletNativeMomentPainterWrapperResult^ WaveletNativeMomentPainterWrapper::CreatePainting2(int width, int height, array<UnsafeBitmap^>^ originals, array<UnsafeBitmap^>^ transformed, array<UnsafeBitmap^>^ strokes, int S) { array<UnsafeBitmap^>^ garbage; return CreatePainting2(width, height, originals, transformed, strokes, S, false, garbage); } WaveletNativeMomentPainterWrapperResult^ WaveletNativeMomentPainterWrapper::CreatePainting2(int width, int height, array<UnsafeBitmap^>^ originals, array<UnsafeBitmap^>^ transformed, array<UnsafeBitmap^>^ strokes, int S, bool generateMovie, array<UnsafeBitmap^>^ introFrames) { // Sanity check inputs if (originals->Length != transformed->Length) { ComputationProgress::Instance()->percentComplete = 100; WaveletNativeMomentPainterWrapperResult^ dummy; return dummy; } ComputationProgress::Instance()->percentComplete = 0; std::vector<FastRawImage*> inputOriginals; std::vector<FastRawImage*> inputTransformed; static std::vector<FastRawImage*> faststrokes; float percentWorkForAllConversion = 5.0; // Five percent float percentWorkDonePerConversion = percentWorkForAllConversion / (originals->Length * 2); for (int i=0; i < originals->Length; i++) { ComputationProgress::Instance()->percentComplete += 1; inputOriginals.push_back(ImageConversion::Unsafe2FastRaw(originals[i])); // Update percentage work done ComputationProgress::Instance()->percentComplete += static_cast<int>(percentWorkDonePerConversion); inputTransformed.push_back(ImageConversion::Unsafe2FastRaw(transformed[i])); // Update percentage work done ComputationProgress::Instance()->percentComplete += static_cast<int>(percentWorkDonePerConversion); } // The faststrokes collection is static, so this // work only needs to be done once. if (faststrokes.size() == 0) { for (int i=0; i < strokes->Length; i++) { faststrokes.push_back(ImageConversion::Unsafe2FastRaw(strokes[i])); } } WaveletNativeMomentsPainter painter(width, height, inputOriginals, inputTransformed, faststrokes, S); // Convert intro movie frames, if movie generation has been enabled std::vector<FastRawImage*> inputIntroMovieFrames; if (generateMovie) { // Convert intro movie frames for (int i=0; i < introFrames->Length; i++) { inputIntroMovieFrames.push_back(ImageConversion::Unsafe2FastRaw(introFrames[i])); } // Pass movie frames, and enable movie generation painter.EnableMovieGeneration(inputIntroMovieFrames, "junk"); } WaveletNativeMomentsPainterResult* result = painter.CreatePainting2(); WaveletNativeMomentPainterWrapperResult^ retValue = gcnew WaveletNativeMomentPainterWrapperResult(); retValue->image = ImageConversion::FastRaw2Unsafe(result->painting); //List< List< System::Drawing::Rectangle for (unsigned int i=0; i < inputOriginals.size(); i++) { delete inputOriginals[i]; delete inputTransformed[i]; inputOriginals[i] = NULL; inputTransformed[i] = NULL; } // The faststrokes colleciton is static, so we DO NOT delete the // contents of the collection. // Delete title movie frame, if it was created for (unsigned int i=0; i < inputIntroMovieFrames.size(); i++) { delete inputIntroMovieFrames[i]; } delete result->painting; return retValue; } } } } } } }
#include "PlayerManager.h" #include "Actor/Controller/PlayerController/BasePlayerController.h" #include "Actor/Character/PlayerCharacter/PlayerCharacter.h" #include "Struct/CharacterClassInfo/CharacterClassInfo.h" #include "Struct/EquipItemInfo/EquipItemInfo.h" UPlayerManager::UPlayerManager() { static ConstructorHelpers::FObjectFinder<UDataTable> DT_CHARACTER_CLASS_INFO( TEXT("DataTable'/Game/Resources/DataTables/DT_CharacterClassInfo.DT_CharacterClassInfo'")); if (DT_CHARACTER_CLASS_INFO.Succeeded()) DT_CharacterClassInfo = DT_CHARACTER_CLASS_INFO.Object; static ConstructorHelpers::FObjectFinder<UDataTable> DT_EQUIP_ITEM_INFO( TEXT("DataTable'/Game/Resources/DataTables/DT_EquipItemInfo.DT_EquipItemInfo'")); if (DT_EQUIP_ITEM_INFO.Succeeded()) DT_EquipItemInfo = DT_EQUIP_ITEM_INFO.Object; } void UPlayerManager::RegisterPlayer(ABasePlayerController* newPlayerController, APlayerCharacter* newPlayerCharacter) { PlayerController = newPlayerController; PlayerCharacter = newPlayerCharacter; } void UPlayerManager::InitManagerClass() { PlayerInventory = NewObject<UPlayerInventory>(this, UPlayerInventory::StaticClass(), NAME_None, EObjectFlags::RF_MarkAsRootSet); } void UPlayerManager::ShutdownManagerClass() { if (!PlayerInventory->IsValidLowLevel()) return; PlayerInventory->ConditionalBeginDestroy(); } void UPlayerManager::InitializePlayerCharacter() { // 캐릭터 정보 FPlayerCharacterInfo* playerCharacterInfo = GetPlayerInfo(); // 클래스 정보를 얻습니다. FName classKey = FName(*FString::FromInt( static_cast<uint32>(playerCharacterInfo->CharacterClass))); FString contextString; FCharacterClassInfo * newClassInfo = DT_CharacterClassInfo->FindRow<FCharacterClassInfo>(classKey, contextString); // 기본 장비 초기화 playerCharacterInfo->InitializeDefaultEquipmentItems( newClassInfo->DefaultEquipItemCodes, DT_EquipItemInfo); // 장착된 모든 파츠 Mesh 를 비웁니다. for (TPair<EPartsType, USkeletalMeshComponent*> partsInfo : GetPlayerCharacter()->GetParts()) { if (partsInfo.Key == EPartsType::PT_LGlove || partsInfo.Key == EPartsType::PT_RGlove) { playerCharacterInfo->PartsInfos[EPartsType::PT_Glove].Clear(); } else playerCharacterInfo->PartsInfos[partsInfo.Key].Clear(); partsInfo.Value->SetSkeletalMesh(nullptr); } GetPlayerInventory()->UpdateCharacterVisual(); GetPlayerCharacter()->InitializeMeshs(); }
// Created on: 1996-09-25 // Created by: Christian CAILLET // 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 _IFSelect_SelectExplore_HeaderFile #define _IFSelect_SelectExplore_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <Standard_Integer.hxx> #include <IFSelect_SelectDeduct.hxx> class Interface_EntityIterator; class Interface_Graph; class Standard_Transient; class TCollection_AsciiString; class IFSelect_SelectExplore; DEFINE_STANDARD_HANDLE(IFSelect_SelectExplore, IFSelect_SelectDeduct) //! A SelectExplore determines from an input list of Entities, //! a list obtained by a way of exploration. This implies the //! possibility of recursive exploration : the output list is //! itself reused as input, etc... //! Examples : Shared Entities, can be considered at one level //! (immediate shared) or more, or max level //! //! Then, for each input entity, if it is not rejected, it can be //! either taken itself, or explored : it then produces a list. //! According to a level, either the produced lists or taken //! entities give the result (level one), or lists are themselves //! considered and for each item, is it taken or explored. //! //! Remark that rejection is just a safety : normally, an input //! entity is, either taken itself, or explored //! A maximum level can be specified. Else, the process continues //! until all entities have been either taken or rejected class IFSelect_SelectExplore : public IFSelect_SelectDeduct { public: //! Returns the required exploring level Standard_EXPORT Standard_Integer Level() const; //! Returns the list of selected entities. Works by calling the //! method Explore on each input entity : it can be rejected, //! taken for output, or to explore. If the maximum level has not //! yet been attained, or if no max level is specified, entities //! to be explored are themselves used as if they were input Standard_EXPORT Interface_EntityIterator RootResult (const Interface_Graph& G) const Standard_OVERRIDE; //! Analyses and, if required, Explores an entity, as follows : //! The explored list starts as empty, it has to be filled by this //! method. //! If it returns False, <ent> is rejected for result (this is to //! be used only as safety) //! If it returns True and <explored> remains empty, <ent> is //! taken itself for result, not explored //! If it returns True and <explored> is not empty, the content //! of this list is considered : //! If maximum level is attained, it is taken for result //! Else (or no max), each of its entity will be itself explored Standard_EXPORT virtual Standard_Boolean Explore (const Standard_Integer level, const Handle(Standard_Transient)& ent, const Interface_Graph& G, Interface_EntityIterator& explored) const = 0; //! Returns a text saying "(Recursive)" or "(Level nn)" plus //! specific criterium returned by ExploreLabel (see below) Standard_EXPORT TCollection_AsciiString Label() const Standard_OVERRIDE; //! Returns a text defining the way of exploration Standard_EXPORT virtual TCollection_AsciiString ExploreLabel() const = 0; DEFINE_STANDARD_RTTIEXT(IFSelect_SelectExplore,IFSelect_SelectDeduct) protected: //! Initializes a SelectExplore : the level must be specified on //! starting. 0 means all levels, 1 means level one only, etc... Standard_EXPORT IFSelect_SelectExplore(const Standard_Integer level); private: Standard_Integer thelevel; }; #endif // _IFSelect_SelectExplore_HeaderFile
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 1995-2007 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * Arjan van Leeuwen (arjanl) */ #include "core/pch.h" #include "adjunct/quick_toolkit/widgets/OpHoverButton.h" /*********************************************************************************** ** Construction function ** ** OpHoverButton::Construct ** ***********************************************************************************/ OP_STATUS OpHoverButton::Construct(OpHoverButton** obj, UINT32 hover_color, ButtonType button_type, ButtonStyle button_style) { *obj = OP_NEW(OpHoverButton, (hover_color, button_type, button_style)); if (!*obj) return OpStatus::ERR_NO_MEMORY; if (OpStatus::IsError((*obj)->init_status)) { OP_DELETE(*obj); return OpStatus::ERR_NO_MEMORY; } return OpStatus::OK; } /*********************************************************************************** ** Called when mouse is moved on this widget ** ** OpHoverButton::OnMouseMove ** ***********************************************************************************/ void OpHoverButton::OnMouseMove(const OpPoint & point) { if (m_color.use_default_foreground_color) { m_color.use_default_foreground_color = FALSE; m_color.foreground_color = m_hover_color; InvalidateAll(); } } /*********************************************************************************** ** Called when mouse leaves this widget ** ** OpHoverButton::OnMouseLeave ** ***********************************************************************************/ void OpHoverButton::OnMouseLeave() { if (!m_color.use_default_foreground_color) { m_color.use_default_foreground_color = TRUE; InvalidateAll(); } }
#ifndef _CDL_TCP_Handler_H_ #define _CDL_TCP_Handler_H_ #include "poller.h" class CDL_TCP_Handler : public CPollerObject { public: CDL_TCP_Handler(){}; virtual ~CDL_TCP_Handler(){}; public: virtual int OnClose()=0; // 连接断开后调用 注意:如果返回1则不会删除对象只会关闭连接 virtual int OnConnected()=0; // 连接成功建立后调用 virtual int OnPacketComplete(const char * data, int len)=0; // 需解析完整数据包时调用 public: inline int GetIP(){return this->_ip;}; inline void SetIP(int ip){ this->_ip = ip;}; inline uint16_t GetPort(){return this->_port;}; inline void SetPort(uint16_t port){ this->_port = port;}; inline int GetNetfd(){return this->netfd;}; inline void SetNetfd(int netfd){ this->netfd = netfd;}; protected: in_addr_t _ip; uint16_t _port; }; #endif
// Copyright 2014-2018 The Monero Developers // Copyright (c) 2018-2023 Conceal Network & Conceal Devs // // Please see the included LICENSE file for more information. #include "CryptoNote.h" #include <vector> namespace mnemonics { crypto::SecretKey mnemonicToPrivateKey(const std::string &words); crypto::SecretKey mnemonicToPrivateKey(const std::vector<std::string> &words); std::string privateKeyToMnemonic(const crypto::SecretKey &privateKey); bool hasValidChecksum(const std::vector<std::string> &words); std::string getChecksumWord(const std::vector<std::string> &words); std::vector<int> getWordIndexes(const std::vector<std::string> &words); }
/* A county collects property taxes on the assessment value of property, which is 60% of the property's actual value. If an acre of land is valued at $10,000, its assessment value is $60,000. The property tax is then 64 cents for each $100 of the assessment value. The tax for the acre assessed at $6,000 will be $38.40. Write a program that asks for the actual value of a piece of property and displays the assessment value and property tax. Author: Aaron Maynard */ #include<iostream> #include<iomanip> using namespace std; int main(){ // Declare variables double propertyValue, propertyTax, propertyAssessment; // User input cout << "Enter the actual value of the property: "; cin >> propertyValue; // Do the math propertyAssessment = propertyValue * 0.60; propertyTax = (propertyAssessment/100) * 0.64; // Print to screen cout << setprecision(2) << fixed; cout <<"The assessment value is: " << propertyAssessment << endl; cout << "The property tax is: " << propertyTax << endl; return 0; }
#include <QPainter> #include <QBrush> #include <QPen> #include <QMessageBox> #include <QString> #include <QMouseEvent> #include <QDialog> #include <algorithm> #include "plotter.h" #include "dialog.h" #include "mainwindow.h" #include "ui_mainwindow.h" #include "sculptor.h" Plotter::Plotter(QWidget *parent) : QWidget(parent){ dimX = 30; dimY = 30; dimZ = 30; s = new Sculptor(dimX, dimY, dimZ); boxSizeX = 0; boxSizeY = 0; boxSizeZ = 0; radius = 0; radiusX = 0; radiusY = 0; radiusZ = 0; slice = 0; r = 0; g = 0; b = 0; a = 255; action = 0; } void Plotter::paintEvent(QPaintEvent *event){ QPainter painter(this); QBrush brush; QPen pen; brush.setColor(QColor(255, 255, 255)); brush.setStyle(Qt::SolidPattern); pen.setColor(QColor(0, 0, 0)); pen.setWidth(2); if(dimX == dimY){ painter.translate(0, height()); painter.scale(1.0, -1.0); } painter.setBrush(brush); painter.setPen(pen); v.clear(); v = s->createGrid(slice); int dim1 = width() / v[0].size(); int dim2 = height() / v.size(); if(dim1 > dim2){ cellSize = dim2; } else { cellSize = dim1; } for(unsigned int x = 0; x < v.size(); x++){ for(unsigned int y = 0; y < v[0].size(); y++){ painter.drawRect(x * cellSize, y * cellSize, cellSize, cellSize); } } for(unsigned int x = 0; x < v.size(); x++){ for(unsigned int y = 0; y < v[0].size(); y++){ if(v[x][y].isOn){ brush.setColor(QColor(v[x][y].r, v[x][y].g, v[x][y].b, v[x][y].a)); brush.setStyle(Qt::SolidPattern); painter.setBrush(brush); painter.drawEllipse(x * cellSize, y * cellSize, cellSize, cellSize); } } } } void Plotter::mouseMoveEvent(QMouseEvent *event){ mouseX = (event->x()) / cellSize; mouseY = (event->y()) / cellSize; if(dimX == dimY){ posX = mouseX; posY = dimY - mouseY - 1; posZ = slice; } else { posX = mouseX; posY = mouseY; posZ = slice; } draw(action, mousePressed); } void Plotter::mousePressEvent(QMouseEvent *event){ if(event->button() == Qt::LeftButton){ mousePressed = true; mouseX = (event->x()) / cellSize; mouseY = (event->y()) / cellSize; if(dimX == dimY){ posX = mouseX; posY = dimY - mouseY - 1; posZ = slice; } else { posX = mouseX; posY = mouseY; posZ = slice; } draw(action, mousePressed); } } void Plotter::mouseReleaseEvent(QMouseEvent *event){ if(event->button() == Qt::LeftButton){ mousePressed = false; } } void Plotter::draw(int action, bool mousePressed){ if(mousePressed){ switch(action){ case 1: // putVoxel s->setColor(r, g, b, a); s->putVoxel(posX, posY, posZ); break; case 2: // cutVoxel s->cutVoxel(posX, posY, posZ); break; case 3: // putBox if(boxSizeX > 0 && boxSizeY > 0 && boxSizeZ > 0) { s->setColor(r, g, b, a); s->putBox(posX, (posX + boxSizeX) - 1, posY, (posY - boxSizeY) - 1, posZ, (posZ + boxSizeZ) - 1); } break; case 4: // cutBox if(boxSizeX > 0 && boxSizeY > 0 && boxSizeZ > 0){ s->cutBox(posX, (posX + boxSizeX) - 1, posY, (posY - boxSizeY) - 1, posZ, (posZ + boxSizeZ) - 1); } break; case 5: // putSphere if(radius > 0){ s->setColor(r, g, b, a); s->putSphere(posX, posY, posZ, radius); } break; case 6: // cutSphere if(radius > 0){ s->cutSphere(posX, posY, posZ, radius); } break; case 7: // putEllipsoid if(radiusX > 0 && radiusY > 0 && radiusZ > 0){ s->setColor(r, g, b, a); s->putEllipsoid(posX, posY, posZ, radiusX, radiusY, radiusZ); } break; case 8: // cutEllipsoid if(radiusX > 0 && radiusY > 0 && radiusZ > 0){ s->cutEllipsoid(posX, posY, posZ, radiusX, radiusY, radiusZ); } } repaint(); } } int Plotter::getDimX(){ return dimX; } int Plotter::getDimY(){ return dimY; } int Plotter::getDimZ(){ return dimZ; } int Plotter::getMinDim(){ return std::min(std::min(dimX, dimY), dimZ); } void Plotter::changeDimensionX(int x){ boxSizeX = x; } void Plotter::changeDimensionY(int y){ boxSizeY = y; } void Plotter::changeDimensionZ(int z){ boxSizeZ = z; } void Plotter::changeRadius(int r){ radius = r; } void Plotter::changeRadiusX(int rx){ radiusX = rx; } void Plotter::changeRadiusY(int ry){ radiusY = ry; } void Plotter::changeRadiusZ(int rz){ radiusZ = rz; } void Plotter::putVoxel(){ action = 1; } void Plotter::cutVoxel(){ action = 2; } void Plotter::putBox(){ action = 3; } void Plotter::cutBox(){ action = 4; } void Plotter::putSphere(){ action = 5; } void Plotter::cutSphere(){ action = 6; } void Plotter::putEllipsoid(){ action = 7; } void Plotter::cutEllipsoid(){ action = 8; } void Plotter::changeRed(int red){ r = red; } void Plotter::changeGreen(int green){ g = green; } void Plotter::changeBlue(int blue){ b = blue; } void Plotter::changeAlpha(int alpha){ a = alpha; } void Plotter::changeDepth(int depth){ slice = depth; repaint(); } void Plotter::newSculptor(){ Dialog d; QMessageBox msgBox; QString mensagem = "O antigo escultor será descartado."; QString pergunta = "Deseja continuar?"; QString titulo = "Novo escultor - Escultor 3D"; msgBox.setWindowTitle(titulo); msgBox.setIcon(QMessageBox::Question); msgBox.setText(mensagem); msgBox.setInformativeText(pergunta); msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); msgBox.setDefaultButton(QMessageBox::Cancel); if(msgBox.exec() == QMessageBox::Ok){ if(d.exec() == QDialog::Accepted){ s->~Sculptor(); dimX = d.getDimX(); dimY = d.getDimY(); dimZ = d.getDimZ(); s = new Sculptor(dimX, dimY, dimZ); slice = 0; repaint(); } } } void Plotter::saveFile(){ QMessageBox msgBox; QString mensagem = "Arquivo salvo com sucesso!"; QString titulo = "Salvar arquivo - Escultor 3D"; msgBox.setWindowTitle(titulo); msgBox.setIcon(QMessageBox::Information); msgBox.setText(mensagem); msgBox.exec(); s->writeOFF("C:/Users/Lucas/Documents/Projetos/Escultor3/arquivo.off"); }
/* ***** BEGIN LICENSE BLOCK ***** * FW4SPL - Copyright (C) IRCAD, 2012-2013. * Distributed under the terms of the GNU Lesser General Public License (LGPL) as * published by the Free Software Foundation. * ****** END LICENSE BLOCK ****** */ #ifndef _GDCMIO_DICOMINSTANCEWRITER_HXX_ #define _GDCMIO_DICOMINSTANCEWRITER_HXX_ #include <gdcmAttribute.h> #include <gdcmUIDGenerator.h> #include "gdcmIO/writer/DicomFileWriter.hxx" #include "gdcmIO/DicomInstance.hpp" #include "gdcmIO/helper/GdcmHelper.hpp" namespace gdcmIO { namespace writer { /** * @brief This class defines a writer of a DICOM instance storage. * * It is a base for all DICOM writers. * It writes common needed attributes for all DICOM storage. * * @class DicomInstanceWriter. * @author IRCAD (Research and Development Team). * @date 2011. */ template < class DATATYPE > class GDCMIO_CLASS_API DicomInstanceWriter : public DicomFileWriter< DATATYPE > { public: GDCMIO_API DicomInstanceWriter() { SLM_TRACE_FUNC(); } GDCMIO_API virtual ~DicomInstanceWriter() { SLM_TRACE_FUNC(); } GDCMIO_API ::boost::shared_ptr< DicomInstance > getDicomInstance(); GDCMIO_API virtual void setDicomInstance( ::boost::shared_ptr< DicomInstance > a_dicomInstance); protected : /** * @brief Write some ::gdcmIO::DicomInstance members. * * This method write SOP Common Module, modality and instance number. * * @note setDicomInstance() have to be called before this method. * * @see PS 3.3 C.12.1 */ virtual void write(); private : /** * @brief Write SOP Common Module. * * @see PS 3.3 C.12.1 */ void writeSOPCommon(); ::boost::weak_ptr< DicomInstance > m_dicomInstance; ///< Store data on current instance and image instance. }; //------------------------------------------------------------------------------ template < class DATATYPE > void DicomInstanceWriter< DATATYPE >::write() { SLM_TRACE_FUNC(); ::boost::shared_ptr< DicomInstance > dicomInstance = this->getDicomInstance(); // Get the data set ::gdcm::DataSet & gDsRoot = this->getWriter()->GetFile().GetDataSet(); // Remove previous attributes if necessary to insert new ones if (gDsRoot.FindDataElement( ::gdcm::Attribute<0x0008,0x0060>::GetTag() )) { gDsRoot.Remove( ::gdcm::Attribute<0x0008,0x0060>::GetTag() ); OSLM_TRACE("Modality was removed"); } if (gDsRoot.FindDataElement( ::gdcm::Attribute<0x0020,0x0013>::GetTag() )) { gDsRoot.Remove( ::gdcm::Attribute<0x0020,0x0013>::GetTag() ); OSLM_TRACE("Instance number was removed"); } // Modality helper::GdcmData::setTagValue<0x0008,0x0060>( dicomInstance->getModality(), gDsRoot); OSLM_TRACE("Modality : " << dicomInstance->getModality()); // Instance Number helper::GdcmData::setTagValue<int,0x0020,0x0013>( atoi(dicomInstance->getInstanceNumber().c_str()), gDsRoot); OSLM_TRACE("Instance number : " << dicomInstance->getInstanceNumber()); //***** Handled SOP common module *****// // Insert SOP UIDs (can generate them) this->writeSOPCommon(); //***** Write the file *****// DicomFileWriter< DATATYPE >::write(); } //------------------------------------------------------------------------------ template < class DATATYPE > void DicomInstanceWriter< DATATYPE >::writeSOPCommon() { SLM_TRACE_FUNC(); // Get the data set ::gdcm::DataSet & gDsRoot = this->getWriter()->GetFile().GetDataSet(); ::boost::shared_ptr< DicomInstance > dicomInstance = this->getDicomInstance(); // SOP Class UID must not be empty ( Type 1 ) if (dicomInstance->getSOPClassUID().empty()) { ::gdcm::UIDGenerator gUIDgen; dicomInstance->setSOPClassUID( gUIDgen.GetRoot() ); // Set to GDCM one (eurk!) } // SOP Class UID ::gdcm::Attribute<0x0008,0x0016> gSOPClassUIDAt; gSOPClassUIDAt.SetValue(dicomInstance->getSOPClassUID()); gDsRoot.Replace(gSOPClassUIDAt.GetAsDataElement()); OSLM_TRACE("SOP Class UID : " << dicomInstance->getSOPClassUID()); // SOP Instance UID must not be empty ( Type 1 ) if (dicomInstance->getSOPInstanceUID().empty()) { ::gdcm::UIDGenerator gUIDgen; dicomInstance->setSOPClassUID( gUIDgen.Generate() ); } // SOP Instance UID ::gdcm::Attribute<0x0008,0x0018> gSOPInstanceUIDAt; gSOPInstanceUIDAt.SetValue(dicomInstance->getSOPInstanceUID()); gDsRoot.Replace(gSOPInstanceUIDAt.GetAsDataElement()); OSLM_TRACE("SOP Instance UID : "<< dicomInstance->getSOPInstanceUID()); } //------------------------------------------------------------------------------ template < class DATATYPE > ::boost::shared_ptr< DicomInstance > DicomInstanceWriter< DATATYPE >::getDicomInstance() { assert( !m_dicomInstance.expired() ); return m_dicomInstance.lock(); } //------------------------------------------------------------------------------ template < class DATATYPE > void DicomInstanceWriter< DATATYPE >::setDicomInstance( ::boost::shared_ptr< DicomInstance > a_dicomInstance ) { assert ( a_dicomInstance ); m_dicomInstance = a_dicomInstance; } } // namespace writer } // namespace gdcmIO #endif /* _GDCMIO_DICOMINSTANCEWRITER_HXX_ */
#pragma once class Frame { private: bool m_bHardWare; //고성능 타이머 지원 여부 __int64 m_nPreriodTime; //1초에 몇번카운트 하는가? __int64 m_nLastTime; //마지막 프레임 시간 __int64 m_nCurTime; //현제 시간 __int64 m_nDeltaTime; //이전 프레임과 지난시간 double m_TimeScaleSec; //1카운트 당초. double m_FrameDeltaSec; //한프레임 경과 초 double m_TotalSec; //프로그램 시작후 경과시간. double m_FrameCountSec; //프레임 갱신 시간 DWORD m_FrameCount; //프레임 카운트 DWORD m_FramePerSec; //초당 프레임 private: Frame( void ); ~Frame( void ); static Frame* instance; public: static Frame* Get(); static void Delete(); HRESULT Init( void ); void Release( void ); //매업데이트 물려준다. void UpdateTime( float frameLock = 0.0f ); //타임정보를 출력한다 void DrawTimeInfo( HDC hdc ); //프레임간의 지난 초시간을 얻는다. double GetFrameDeltaSec( void ) { return m_FrameDeltaSec; } void DrawShadowText( HDC hdc, int x, int y, char* szText, COLORREF textColor ); double GetNowRealTimeSec(); }; #define FRAME Frame::Get()
/****************************************************/ // Datastream Template instantiations /****************************************************/ #ifdef _NATIVE_SSL_SUPPORT_ #endif
#include "http/Http.hpp" // Handle the new request and cut the body to be processed separately void Http::handleNewRequest() { std::string* buff = _read_chain.getFirst(); // OPTIMIMZATION strchr _requestBuffer.append(*buff); delete buff; _read_chain.popFirst(); size_t pos; // If the end of headers are reached if ((pos = _requestBuffer.find("\r\n\r\n")) != _requestBuffer.npos) { std::string request; request.append(_requestBuffer, 0, pos); // if pos is before that, then there's some body left if (pos < _requestBuffer.size() - 4) { std::string* leftovers = new std::string(_requestBuffer, pos + 4); _read_chain.pushFront(leftovers); } _requestBuffer.clear(); // Instantiate new request try { _req = HttpRequest::parseRequest(request); } catch(const std::exception& e) { _req = new HttpRequest(); } // Instantiate a new response from that request _resp = HttpResponse::newResponse(_req, _config->getServerUnit(_req->getPort(), _req->getHost()), _write_chain); // Adding streams in select fd sets _connection.setStreamWrite(_resp->getStreamWriteFd()); _connection.setStreamRead(_resp->getStreamReadFd()); } }
#include "StaticObjectController.h" StaticObjectController::StaticObjectController() { } StaticObjectController::~StaticObjectController() { } void StaticObjectController::init(LevelModel* levelModel, StaticObjectView* staticObjectView, StaticObjectLogicCalculator* staticObjectLogicCalculator, int key) { m_staticObjectModel = levelModel->getStaticObjectModel(key); m_staticObjectLogicCalculator = staticObjectLogicCalculator; m_staticObjectView = staticObjectView; m_staticObjectView->initView(m_staticObjectModel); } void StaticObjectController::update(const float elapsedTime) { updateBasicObjectMeasurements(); m_staticObjectLogicCalculator->computeLogic(); } void StaticObjectController::updateBasicObjectMeasurements() { //set rect float pixelWidth = m_staticObjectView->getPixelWidth(); float pixelHeight = m_staticObjectView->getPixelHeight(); StaticObjectModel::Rect rect; rect.top = m_staticObjectModel->getTerrainPosition()[1] + pixelHeight/PIXELS_PER_METER/2.0f; rect.bottom = m_staticObjectModel->getTerrainPosition()[1] - pixelHeight/PIXELS_PER_METER/2.0f; rect.left =m_staticObjectModel->getTerrainPosition()[0] - pixelWidth /PIXELS_PER_METER/2.0f ; rect.right = m_staticObjectModel->getTerrainPosition()[0] + pixelWidth /PIXELS_PER_METER/2.0f; m_staticObjectModel->setRect(rect); m_staticObjectModel->setPixelWidth(pixelWidth); m_staticObjectModel->setPixelHeight(pixelHeight); }
#pragma once namespace ServerEngine { class NetModule : public IModuleInterface { private: virtual void StartModule() override; virtual void ShutdownModule() override; }; }
#ifndef NODE_H #define NODE_H #include <stdio.h> #include <math.h> #define USE_CONFIG_FILE 0 //if config files are used #define TIERED_COMMUNITY 1 //if the communities are tiered or randomly assigned #define TORUS_BOUNDARY 0 //if the community boundaries are torus or reflective #define TRACE_FORMAT 0 //0: (t x y) format, 1: NS-2 format #define PERIOD 3 //number of unique time periods #define COMMTIER 6 //number of community tiers (or communities) #define STRUCTURE 100 //longest structure you can have #define XDIM 1500.0 //size of simulation area #define YDIM 1500.0 //size of simulation area #define TIER_LENGTH 25.0 // 1/2 of edge length of communities #define TIME_STEP 1 //time interval to update node locations static const double state_prob[PERIOD][COMMTIER] = {{0.9,0.05,0.025,0.015,0.005,0.005},{0.6,0.2,0.10,0.08,0.015,0.005},{0.5,0.3,0.10,0.08,0.015,0.005}}; static const double time_period_dur[PERIOD]={43200,28800,14400}; static const int time_period_structure[STRUCTURE]={0,1,2}; static const int number_of_item_in_structure = 3; static const double pause_max[PERIOD][COMMTIER]={{21600,2400,1200,900,600,60},{3600,2400,2400,2000,2000,1000},{3600,2400,1200,900,600,60}}; static const double l_avg[PERIOD][COMMTIER] = {{300,500,500,800,1000,1000},{400,600,700,900,1000,1000},{300,500,500,800,1000,1000}}; static double vmin[PERIOD][COMMTIER] = {{1,1,1,1,1,1},{1,1,1,1,1,1},{1,1,1,1,1,1}}; static double vavg[PERIOD][COMMTIER] = {{1.25,1.25,1.25,1.25,1.25,1.25},{1.25,1.25,1.25,1.25,1.25,1.25},{1.25,1.25,1.25,1.25,1.25,1.25}}; static double vmax[PERIOD][COMMTIER] = {{1.5,1.5,1.5,1.5,1.5,1.5},{1.5,1.5,1.5,1.5,1.5,1.5},{1.5,1.5,1.5,1.5,1.5,1.5}}; class Node{ public: Node(); ~Node(); void Initialize(int nodeid); double ExecuteEvent(double sim_time); void PrintTrace(char *filename); void CloseTraceFile(); double currentx, currenty; double next_event_time; FILE *outfile; bool keeptrace; double nextx, nexty; //location to move after the pause int next_event_type; int state; //0,1,2,...,n-1 (n-1=roaming) int period; //0,1,2,...,t-1 double travel_speed; double travel_dir; double travel_duration; double travel_stop_time; double dur_mean; //double comm_x, comm_y, comm_xupper, comm_yupper; double next_period_start; double center_x[PERIOD], center_y[PERIOD]; //variables used for NS-2 compatible trace generation double anchor_t, anchor_x, anchor_y; double tempx, tempy; int nid; double comm_x[PERIOD][COMMTIER]; double comm_y[PERIOD][COMMTIER]; double comm_xupper[PERIOD][COMMTIER]; double comm_yupper[PERIOD][COMMTIER]; int time_period_counter; }; #endif
/* Generated from orogen/lib/orogen/templates/tasks/Task.cpp */ #include "Task.hpp" using namespace camera; using namespace camera_ids; using namespace base::samples; Task::Task(std::string const& name) : TaskBase(name) { } Task::Task(std::string const& name, RTT::ExecutionEngine* engine) : TaskBase(name, engine) { } Task::~Task() { } bool Task::configureHook() { if (! TaskBase::configureHook()) return false; unsigned long camera_id; std::stringstream ss(_camera_id.value()); ss >> camera_id; std::string modeString = _mode.value(); if(modeString == "Master") { this->camera_access_mode = Master; } else if (modeString == "Monitor") { this->camera_access_mode = Monitor; } else if (modeString == "MasterMulticast") { this->camera_access_mode = MasterMulticast; } else { RTT::log(RTT::Error) << "unsupported camera mode: " << _mode.value() << RTT::endlog(); return false; } try { std::auto_ptr<camera::CamIds> camera(new camera::CamIds()); RTT::log(RTT::Info) << "opening camera" << RTT::endlog(); CamInfo cam_info; cam_info.unique_id = camera_id; camera->open(cam_info, this->camera_access_mode); if (camera->isOpen() == false) { RTT::log(RTT::Error) << "camera not found" << RTT::endlog(); return false; } cam_interface = camera.release(); } catch (std::runtime_error e) { RTT::log(RTT::Error) << "failed to initialize camera: " << e.what() << RTT::endlog(); return false; } double period = 1. / _fps.get(); RTT::log(RTT::Info) << "period is " << period << " s" << RTT::endlog(); camera::CamIds* cids_ptr = static_cast<camera::CamIds*>(cam_interface); cids_ptr->setEventTimeout(int(_timeout_periods.get() * period * 1000.)); if (_enable_api_log.get()) cids_ptr->setErrorReport(true); cids_ptr->setGetEveryFrame(_get_every_frame.get()); // set the gain boost if applicable // the camera instance is accessed directly as the interface does not support the gain boost feature if(!cids_ptr->setGainBoost(_gain_boost.get())) { return false; } if(_gain_red.get() > 0) if(!cids_ptr->setGainRed(_gain_red.get())) return false; if(_gain_green.get() > 0) if(!cids_ptr->setGainGreen(_gain_green.get())) return false; if(_gain_blue.get() > 0) if(!cids_ptr->setGainBlue(_gain_blue.get())) return false; return true; } bool Task::startHook() { if (! TaskBase::startHook()) return false; RTT::log(RTT::Info) << "Start camera " << _camera_id.value() << RTT::endlog(); return true; } void Task::updateHook() { static base::Time tlast = base::Time::now(); static unsigned int counter = 0; if ( counter % _capture_status_divider.get() == 0 ) _capture_status.write( static_cast<camera::CamIds*>(cam_interface)->getCaptureStatus()); counter++; base::Time tstart = base::Time::now(); if (!cam_interface->isFrameAvailable()) { RTT::log(RTT::Error) << "No frame received during timeout period." << RTT::endlog(); report(TIMEOUT_ERROR); } base::Time there = base::Time::now(); RTT::log(RTT::Debug) << "time for triggering: " << (tstart-tlast).toSeconds() << "; time to wait: " << (there - tstart).toSeconds() << RTT::endlog(); if(getFrame()) { base::samples::frame::Frame *frame_ptr = camera_frame.write_access(); camera_frame.reset(frame_ptr); _frame.write(camera_frame); } else { RTT::log(RTT::Warning) << "Error during frame retrieval!" << RTT::endlog(); } tlast = base::Time::now(); this->getActivity()->trigger(); } void Task::errorHook() { TaskBase::errorHook(); } // void Task::stopHook() // { // TaskBase::stopHook(); // } void Task::cleanupHook() { TaskBase::cleanupHook(); } bool Task::configureCamera() { // Pixelclock cam_interface->setAttrib(int_attrib::PixelClock, _pixel_clock.get()); // set mirrors if( cam_interface->isAttribAvail(enum_attrib::MirrorXToOn) && cam_interface->isAttribAvail(enum_attrib::MirrorXToOff) ) { if ( _mirror_x.get() ) cam_interface->setAttrib(enum_attrib::MirrorXToOn); else cam_interface->setAttrib(enum_attrib::MirrorXToOff); } if( cam_interface->isAttribAvail(enum_attrib::MirrorYToOn) && cam_interface->isAttribAvail(enum_attrib::MirrorYToOff) ) { if ( _mirror_y.get() ) cam_interface->setAttrib(enum_attrib::MirrorYToOn); else cam_interface->setAttrib(enum_attrib::MirrorYToOff); } // auto gain if( cam_interface->isAttribAvail(enum_attrib::GainModeToAuto) && cam_interface->isAttribAvail(enum_attrib::GainModeToManual) ) { if ( _gain_mode_auto.get() ) cam_interface->setAttrib(enum_attrib::GainModeToAuto); else cam_interface->setAttrib(enum_attrib::GainModeToManual); } // call the configureCamera method of the super class to apply the remaining settings TaskBase::configureCamera(); return true; }
#pragma once #include <wrl\client.h> #include <d3d11.h> #include <SpriteFont.h> #include "Camera.h" #include "Sky.h" #include "GameEntity.h" #include "Lights.h" class Renderer { public: Renderer( Microsoft::WRL::ComPtr<ID3D11Device> device, Microsoft::WRL::ComPtr<ID3D11DeviceContext> context, Microsoft::WRL::ComPtr<IDXGISwapChain> swapChain, Microsoft::WRL::ComPtr<ID3D11RenderTargetView> backBufferRTV, Microsoft::WRL::ComPtr<ID3D11DepthStencilView> depthBufferDSV, unsigned int windowWidth, unsigned int windowHeight, Sky* sky, const std::vector<GameEntity*>& entities, const std::vector<Light>& lights, SimpleVertexShader* lightVS, SimplePixelShader* lightPS); void PostResize( unsigned int windowWidth, unsigned int windowHeight, Microsoft::WRL::ComPtr<ID3D11RenderTargetView> backBufferRTV, Microsoft::WRL::ComPtr<ID3D11DepthStencilView> depthBufferDSV); void Render( Camera* camera, Mesh* lightMesh, DirectX::SpriteFont* arial, DirectX::SpriteBatch* spriteBatch); private: Microsoft::WRL::ComPtr<ID3D11Device> device; Microsoft::WRL::ComPtr<ID3D11DeviceContext> context; Microsoft::WRL::ComPtr<IDXGISwapChain> swapChain; Microsoft::WRL::ComPtr<ID3D11RenderTargetView> backBufferRTV; Microsoft::WRL::ComPtr<ID3D11DepthStencilView> depthBufferDSV; unsigned int windowWidth; unsigned int windowHeight; Sky* sky; const std::vector<GameEntity*>& entities; const std::vector<Light>& lights; SimpleVertexShader* lightVS; SimplePixelShader* lightPS; void DrawPointLights( Camera* camera, Mesh* lightMesh); void DrawUI( DirectX::SpriteFont* arial, DirectX::SpriteBatch* spriteBatch); };
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #ifndef TABLEGROUPPROPERTIES_H_ #define TABLEGROUPPROPERTIES_H_ #include "LinearGroupProperties.h" namespace Model { class TableGroupProperties : public LinearGroupProperties { public: C__ (void) b_ ("LinearGroupProperties") virtual ~TableGroupProperties () {} E_ (TableGroupProperties) }; } /* namespace Model */ #endif /* TABLEGROUPPROPERTIES_H_ */
/************************************************************************************ CHSWAVEReader Class - WAVE File Reader Class header- Copyright (C) 2014 HiroakiSoftware. All rights reserved. ************************************************************************************/ #pragma once #include "CHSRIFFReader.hpp" class CHSWAVEReader : public CHSRIFFReader{ private: bool OpenedCallBack(void); bool BeforeCloseCallBack(void); UINT32 dataChunkPos; public: CHSWAVEReader(TCHAR *lpszWaveFilePath = nullptr); ~CHSWAVEReader(); //フォーマット取得 bool GetFormat(PCMWAVEFORMAT *lpFormat); bool GetFormat(WAVEFORMAT *lpFormat); bool GetFormat(WAVEFORMATEX *lpFormat); UINT32 GetFormat(void *lpFormat , UINT32 Size); UINT32 GetFormatSize(void); //再生データのサイズをバイト単位で取得 UINT32 GetPlayDataSize(void); //再生サンプル数を取得 UINT32 GetPlaySamples(void); //再生時間を取得 UINT32 GetPlayTimeSeconds(void); UINT32 GetPlayTimeMilliSeconds(void); //全再生データを取得 bool ReadAllPlayData(void *lpData , UINT32 *lpNumberOfSamplesByRead = nullptr); //再生データを取得 bool ReadPlayData(void *lpData , UINT32 NumberOfReadPositionSamples , UINT32 NumberOfReadSamples , UINT32 *lpNumberOfSamplesByRead); bool ReadPlayDataIsInSeconds(void *lpData , UINT32 NumberOfReadPositionSeconds , UINT32 NumberOfReadSeconds , UINT32 *lpNumberOfSamplesByRead); bool ReadPlayDataIsInMilliSeconds(void *lpData , UINT32 NumberOfReadPositionMilliSeconds , UINT32 NumberOfReadMilliSeconds , UINT32 *lpNumberOfSamplesByRead); //必要なメモリサイズを計算する UINT32 CalculateMemorySize(UINT32 Samples); UINT32 CalculateMemorySizeIsInSeconds(UINT32 Seconds); UINT32 CalculateMemorySizeIsInMilliSeconds(UINT32 MilliSeconds); //時間からサンプル数を取得(秒単位とミリ秒単位の2種類用意) UINT32 CalculateNumberOfSamplesIsInSeconds(UINT32 Seconds); UINT32 CalculateNumberOfSamplesIsInMilliSeconds(UINT32 MilliSeconds); //曲名取得 UINT32 GetSongName(char *lpName , UINT32 size); //曲名のサイズを取得 UINT32 GetSongNameLength(void); //アーティスト名 UINT32 GetSongArtistName(char *lpArtistName , UINT32 size); //アーティスト名のサイズを取得 UINT32 GetSongArtistNameLength(void); //プロダクト名 UINT32 GetSongProductName(char *lpProductName , UINT32 size); //プロダクト名のサイズを取得 UINT32 GetSongProductNameLength(void); //ジャンル UINT32 GetSongGenreText(char *lpGenreText , UINT32 size); //ジャンルのサイズを取得 UINT32 GetSongGenreTextLength(void); };
/****************************************************************************** * Merge k sorted linked lists and return it as one sorted list. Analyze and * describe its complexity. ******************************************************************************/ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ ListNode *mergeKLists(vector<ListNode *> &lists) { multimap<int,ListNode *> myMap; for(int i=0; i<lists.size(); i++) { while(lists[i]) { myMap.insert(pair<int, ListNode *>(lists[i]->val,lists[i])); lists[i]=lists[i]->next; } } if(myMap.size()==0) { return NULL; } for(multimap<int,ListNode *>::iterator it=myMap.begin();; it++) { multimap<int,ListNode *>::iterator it_next=it; it_next++; if(it_next==myMap.end()) { it->second->next=NULL; break; } it->second->next=it_next->second; } return myMap.begin()->second; }
/* Author : AMAN JAIN DATE: 04-07-2020 PROGRAM -> Horspool algorithm O(n/m) time in the best case. O(mn) time in worst case The worst case occurs when all characters of the text and pattern are same. For example, txt[] = “AAAAAAAAAAAAAAAAAA” and pat[] = “AAAAA”. */ #include<bits/stdc++.h> using namespace std; #define MAX 500 //declaring the size of the index table int index_table[MAX]; //global array for shift table void shift_table(string ptr){ //function to find the position of each character in the shift table int length=ptr.length(); for(int i=0; i<MAX ;i++){ index_table[i]=length; //initializing the value of shift table with the length of pattern } for(int i=0 ;i<length-1 ; i++){ //calculating the position of each character using the formula length-index-1 index_table[ptr[i]]=length-i-1; } } int horspool(string str,string ptr){ int str_length=str.length(); int pat_length=ptr.length(); int index=pat_length-1; int k; while(index<str_length)//continue the search until we match the last index of pattern with the { k=0; while(k<pat_length && ptr[pat_length-k-1] == str[index-k]) { k++; } if(k==pat_length) return (index-pat_length+1); //return the first index else index+=index_table[str[index]];//if char doesnt match we will increase the index using the shift table } return -1; } int main() { string str,pat; int pos; getline(cin,str); getline(cin,pat); shift_table(pat); int position= horspool(str,pat); if(horspool(str,pat)==-1) cout<<"Pattern Not found"<<endl; else cout<<"Pattern Found at "<<position+1; }
/* Copyright 2021 University of Manchester Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http: // www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "ila.hpp" #include <iostream> using orkhestrafs::dbmstodspi::ILA; void ILA::StartILAs() { ILA::WriteToModule(0x10000000, 1); ILA::WriteToModule(0x10000004, 3); ILA::WriteToModule(0x12000000, 1); ILA::WriteToModule(0x12000004, 3); ILA::WriteToModule(0x14000000, 1); } void ILA::StartAxiILA() { ILA::WriteToModule(0x14000000, 1); } auto ILA::GetValues(int clock_cycle, int location, ILADataTypes data_type) -> uint32_t { return ILA::ReadFromModule( ILA::CalcAddress(clock_cycle, location, static_cast<int>(data_type))); } auto ILA::CalcAddress(int clock, int ila_id, int offset) -> int { int base_address = 0; if (ila_id == 0) { base_address = 0x10000000; } else if (ila_id == 1) { base_address = 0x12000000; } else if (ila_id == 2) { base_address = 0x14000000; } else { throw std::runtime_error("Wrong ILA core ID given!"); } return (base_address + (clock << 11) + (offset << 2)); } void ILA::WriteToModule(int module_internal_address, uint32_t write_data) { volatile uint32_t* register_address = memory_manager_->GetVirtualRegisterAddress(module_internal_address); *register_address = write_data; } auto ILA::ReadFromModule(int module_internal_address) -> uint32_t { volatile uint32_t* register_address = memory_manager_->GetVirtualRegisterAddress(module_internal_address); return *register_address; } void ILA::PrintILAData(int ila_id, int max_clock) { for (int clock = 0; clock < max_clock; clock++) { std::cout << "ILA " << ila_id << " CLOCK " << clock << ":" << "CLOCK_CYCLE " << GetValues(clock, ila_id, ILADataTypes::kClockCycle) << "; " << "TYPE " << GetValues(clock, ila_id, ILADataTypes::kType) << "; " << "STREAMID " << GetValues(clock, ila_id, ILADataTypes::kStreamID) << "; " << "CHUNKID " << GetValues(clock, ila_id, ILADataTypes::kChunkID) << "; " << "STATE " << GetValues(clock, ila_id, ILADataTypes::kState) << "; " << "CHANNELID " << GetValues(clock, ila_id, ILADataTypes::kChannelID) << "; " << "LAST " << GetValues(clock, ila_id, ILADataTypes::kLast) << "; " << "DATA_15 " << GetValues(clock, ila_id, ILADataTypes::kDataAtPos15) << "; " << "INSTR_CHANNELID " << GetValues(clock, ila_id, ILADataTypes::kInstrChannelID) << "; " << "INSTR_PARAM " << GetValues(clock, ila_id, ILADataTypes::kInstrParam) << "; " << "INSTR_STREAMID " << GetValues(clock, ila_id, ILADataTypes::kInstrStreamID) << "; " << "INSTR_TYPE " << GetValues(clock, ila_id, ILADataTypes::kInstrType) << "; " << "JOIN_STATE " << GetValues(clock, ila_id, ILADataTypes::kJoinState) << "; " << std::endl; } } void ILA::PrintAxiILAData(int max_clock) { for (int clock = 0; clock < max_clock; clock++) { std::cout << "ILA " << 2 << " CLOCK " << clock << ":" << "kAxiClockCycle " << GetValues(clock, 2, ILADataTypes::kAxiClockCycle) << "; " << "kAxiAWV " << GetValues(clock, 2, ILADataTypes::kAxiAWV) << "; " << "kAxiAWR " << GetValues(clock, 2, ILADataTypes::kAxiAWR) << "; " << "kAxiAWA " << GetValues(clock, 2, ILADataTypes::kAxiAWA) << "; " << "kAxiWV " << GetValues(clock, 2, ILADataTypes::kAxiWV) << "; " << "kAxiWR " << GetValues(clock, 2, ILADataTypes::kAxiWR) << "; " << "kAxiWD " << GetValues(clock, 2, ILADataTypes::kAxiWD) << "; " << "kAxiWS " << GetValues(clock, 2, ILADataTypes::kAxiWS) << "; " << "kAxiBV " << GetValues(clock, 2, ILADataTypes::kAxiBV) << "; " << "kAxiBR " << GetValues(clock, 2, ILADataTypes::kAxiBR) << "; " << "kAxiBRESP " << GetValues(clock, 2, ILADataTypes::kAxiBRESP) << "; " << "kAxiARV " << GetValues(clock, 2, ILADataTypes::kAxiARV) << "; " << "kAxiARR " << GetValues(clock, 2, ILADataTypes::kAxiARR) << "; " << "kAxiARA " << GetValues(clock, 2, ILADataTypes::kAxiARA) << "; " << "kAxiRV " << GetValues(clock, 2, ILADataTypes::kAxiRV) << "; " << "kAxiRR " << GetValues(clock, 2, ILADataTypes::kAxiRR) << "; " << "kAxiRD " << GetValues(clock, 2, ILADataTypes::kAxiRD) << "; " << "kAxiRRESP " << GetValues(clock, 2, ILADataTypes::kAxiRRESP) << "; " << std::endl; } } void ILA::PrintDMAILAData(int max_clock) { for (int clock = 0; clock < max_clock; clock++) { std::cout << std::hex << "ILA " << 2 << " CLOCK " << clock << ":" << "IC_S " << GetValues(clock, 2, ILADataTypes::kIcS) << "; " << "IC_CH " << GetValues(clock, 2, ILADataTypes::kIcCh) << "; " << "IC_I " << GetValues(clock, 2, ILADataTypes::kIcI) << "; " << "IC_IP " << GetValues(clock, 2, ILADataTypes::kIcIp) << "; " << "IC_V " << GetValues(clock, 2, ILADataTypes::kIcV) << "; " << "IC_P " << GetValues(clock, 2, ILADataTypes::kIcP) << "; " << "ICD_BUSY " << GetValues(clock, 2, ILADataTypes::kIcdBusy) << "; " << "ICD_S " << GetValues(clock, 2, ILADataTypes::kIcdS) << "; " << "ICD_B " << GetValues(clock, 2, ILADataTypes::kIcdB) << "; " << "ICD_E " << GetValues(clock, 2, ILADataTypes::kIcdE) << "; " << "ICD_CH " << GetValues(clock, 2, ILADataTypes::kIcdCh) << "; " << "ICD_BU " << GetValues(clock, 2, ILADataTypes::kIcdBu) << "; " << "DR_A " << GetValues(clock, 2, ILADataTypes::kDrA) << "; " << "DR_L " << GetValues(clock, 2, ILADataTypes::kDrL) << "; " << "DR_S " << GetValues(clock, 2, ILADataTypes::kDrS) << "; " << "DR_B " << GetValues(clock, 2, ILADataTypes::kDrB) << "; " << "DR_E " << GetValues(clock, 2, ILADataTypes::kDrE) << "; " << "DR_CH " << GetValues(clock, 2, ILADataTypes::kDrCh) << "; " << "DR_BU " << GetValues(clock, 2, ILADataTypes::kDrBu) << "; " << "DR_AR " << GetValues(clock, 2, ILADataTypes::kDrAr) << "; " << "DR_AV " << GetValues(clock, 2, ILADataTypes::kDrAv) << "; " << "DRC_ARV " << GetValues(clock, 2, ILADataTypes::kDrcArv) << "; " << "DRC_ARB " << GetValues(clock, 2, ILADataTypes::kDrcArb) << "; " << "DRC_ARA " << GetValues(clock, 2, ILADataTypes::kDrcAra) << "; " << "DRC_ARL " << GetValues(clock, 2, ILADataTypes::kDrcArl) << "; " << "DRC_RD " << GetValues(clock, 2, ILADataTypes::kDrcRd) << "; " << "DRC_RV " << GetValues(clock, 2, ILADataTypes::kDrcRv) << "; " << "DRC_RR " << GetValues(clock, 2, ILADataTypes::kDrcRr) << "; " << "DRC_RL " << GetValues(clock, 2, ILADataTypes::kDrcRl) << "; " << "IB_D " << GetValues(clock, 2, ILADataTypes::kIbD) << "; " << "IB_V " << GetValues(clock, 2, ILADataTypes::kIbV) << "; " << "IB_S " << GetValues(clock, 2, ILADataTypes::kIbS) << "; " << "IB_B " << GetValues(clock, 2, ILADataTypes::kIbB) << "; " << "IB_CH " << GetValues(clock, 2, ILADataTypes::kIbCh) << "; " << "IB_CL " << GetValues(clock, 2, ILADataTypes::kIbCl) << "; " << "IB_L " << GetValues(clock, 2, ILADataTypes::kIbL) << "; " << "IB_SI " << GetValues(clock, 2, ILADataTypes::kIbSi) << "; " << "IB_VS " << GetValues(clock, 2, ILADataTypes::kIbVs) << "; " << "IB_BU " << GetValues(clock, 2, ILADataTypes::kIbBu) << "; " << "U_NA_DIN " << GetValues(clock, 2, ILADataTypes::kUNaDin) << "; " << "U_NA_DOUT " << GetValues(clock, 2, ILADataTypes::kUNaDout) << "; " << "U_NA_WADD " << GetValues(clock, 2, ILADataTypes::kUNaWadd) << "; " << "U_NA_RADD " << GetValues(clock, 2, ILADataTypes::kUNaRadd) << "; " << "U_NA_WEN " << GetValues(clock, 2, ILADataTypes::kUNaWen) << "; " << "U_RR_DIN " << GetValues(clock, 2, ILADataTypes::kURrDin) << "; " << "U_RR_DOUT " << GetValues(clock, 2, ILADataTypes::kURrDout) << "; " << "U_RR_WADD " << GetValues(clock, 2, ILADataTypes::kURrWadd) << "; " << "U_RR_RADD " << GetValues(clock, 2, ILADataTypes::kURrRadd) << "; " << "U_RR_WEN " << GetValues(clock, 2, ILADataTypes::kURrWen) << "; " << "U_RPB " << GetValues(clock, 2, ILADataTypes::kURpb) << "; " << "U_BS " << GetValues(clock, 2, ILADataTypes::kUBs) << "; " << std::endl; } }
#include <maya/MGlobal.h> #include <maya/MFnPlugin.h> #include "hi_maya.h" MStatus initializePlugin(MObject obj) { MFnPlugin plugin(obj, "kingmax_res@163.com | 184327932@qq.com | iJasonLee@WeChat", "2018.07.23.01"); MStatus status; status = plugin.registerCommand("HiMaya", HiMaya::creator); CHECK_MSTATUS_AND_RETURN_IT(status); return status; } MStatus uninitializePlugin(MObject obj) { MFnPlugin plugin(obj); MStatus status; status = plugin.deregisterCommand("HiMaya"); CHECK_MSTATUS_AND_RETURN_IT(status); return status; }
// Copyright (c) 2013-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 _Graphic3d_TextureParams_HeaderFile #define _Graphic3d_TextureParams_HeaderFile #include <Graphic3d_LevelOfTextureAnisotropy.hxx> #include <Graphic3d_Vec2.hxx> #include <Graphic3d_Vec4.hxx> #include <Graphic3d_TextureUnit.hxx> #include <Graphic3d_TypeOfTextureFilter.hxx> #include <Graphic3d_TypeOfTextureMode.hxx> #include <Standard.hxx> #include <Standard_ShortReal.hxx> #include <Standard_Type.hxx> #include <Standard_Transient.hxx> //! This class describes texture parameters. class Graphic3d_TextureParams : public Standard_Transient { DEFINE_STANDARD_RTTIEXT(Graphic3d_TextureParams, Standard_Transient) public: //! Default constructor. Standard_EXPORT Graphic3d_TextureParams(); //! Destructor. Standard_EXPORT virtual ~Graphic3d_TextureParams(); //! Default texture unit to be used, default is Graphic3d_TextureUnit_BaseColor. Graphic3d_TextureUnit TextureUnit() const { return myTextureUnit; } //! Setup default texture unit. void SetTextureUnit (Graphic3d_TextureUnit theUnit) { myTextureUnit = theUnit; } //! @return TRUE if the texture is modulate. //! Default value is FALSE. Standard_Boolean IsModulate() const { return myToModulate; } //! @param theToModulate turn modulation on/off. Standard_EXPORT void SetModulate (const Standard_Boolean theToModulate); //! @return TRUE if the texture repeat is enabled. //! Default value is FALSE. Standard_Boolean IsRepeat() const { return myToRepeat; } //! @param theToRepeat turn texture repeat mode ON or OFF (clamping). Standard_EXPORT void SetRepeat (const Standard_Boolean theToRepeat); //! @return texture interpolation filter. //! Default value is Graphic3d_TOTF_NEAREST. Graphic3d_TypeOfTextureFilter Filter() const { return myFilter; } //! @param theFilter texture interpolation filter. Standard_EXPORT void SetFilter (const Graphic3d_TypeOfTextureFilter theFilter); //! @return level of anisontropy texture filter. //! Default value is Graphic3d_LOTA_OFF. Graphic3d_LevelOfTextureAnisotropy AnisoFilter() const { return myAnisoLevel; } //! @param theLevel level of anisontropy texture filter. Standard_EXPORT void SetAnisoFilter (const Graphic3d_LevelOfTextureAnisotropy theLevel); //! Return rotation angle in degrees; 0 by default. //! Complete transformation matrix: Rotation -> Translation -> Scale. Standard_ShortReal Rotation() const { return myRotAngle; } //! @param theAngleDegrees rotation angle. Standard_EXPORT void SetRotation (const Standard_ShortReal theAngleDegrees); //! Return scale factor; (1.0; 1.0) by default, which means no scaling. //! Complete transformation matrix: Rotation -> Translation -> Scale. const Graphic3d_Vec2& Scale() const { return myScale; } //! @param theScale scale factor. Standard_EXPORT void SetScale (const Graphic3d_Vec2 theScale); //! Return translation vector; (0.0; 0.0), which means no translation. //! Complete transformation matrix: Rotation -> Translation -> Scale. const Graphic3d_Vec2& Translation() const { return myTranslation; } //! @param theVec translation vector. Standard_EXPORT void SetTranslation (const Graphic3d_Vec2 theVec); //! @return texture coordinates generation mode. //! Default value is Graphic3d_TOTM_MANUAL. Graphic3d_TypeOfTextureMode GenMode() const { return myGenMode; } //! @return texture coordinates generation plane S. const Graphic3d_Vec4& GenPlaneS() const { return myGenPlaneS; } //! @return texture coordinates generation plane T. const Graphic3d_Vec4& GenPlaneT() const { return myGenPlaneT; } //! Setup texture coordinates generation mode. Standard_EXPORT void SetGenMode (const Graphic3d_TypeOfTextureMode theMode, const Graphic3d_Vec4 thePlaneS, const Graphic3d_Vec4 thePlaneT); //! @return base texture mipmap level; 0 by default. Standard_Integer BaseLevel() const { return myBaseLevel; } //! Return maximum texture mipmap array level; 1000 by default. //! Real rendering limit will take into account mipmap generation flags and presence of mipmaps in loaded image. Standard_Integer MaxLevel() const { return myMaxLevel; } //! Setups texture mipmap array levels range. //! The lowest value will be the base level. //! The remaining one will be the maximum level. void SetLevelsRange (Standard_Integer theFirstLevel, Standard_Integer theSecondLevel = 0) { myMaxLevel = theFirstLevel > theSecondLevel ? theFirstLevel : theSecondLevel; myBaseLevel = theFirstLevel > theSecondLevel ? theSecondLevel : theFirstLevel; } //! Return modification counter of parameters related to sampler state. unsigned int SamplerRevision() const { return mySamplerRevision; } private: //! Increment revision. void updateSamplerRevision() { ++mySamplerRevision; } private: Graphic3d_Vec4 myGenPlaneS; //!< texture coordinates generation plane S Graphic3d_Vec4 myGenPlaneT; //!< texture coordinates generation plane T Graphic3d_Vec2 myScale; //!< texture coordinates scale factor vector; (1,1) by default Graphic3d_Vec2 myTranslation; //!< texture coordinates translation vector; (0,0) by default unsigned int mySamplerRevision; //!< modification counter of parameters related to sampler state Graphic3d_TextureUnit myTextureUnit; //!< default texture unit to bind texture; Graphic3d_TextureUnit_BaseColor by default Graphic3d_TypeOfTextureFilter myFilter; //!< texture filter, Graphic3d_TOTF_NEAREST by default Graphic3d_LevelOfTextureAnisotropy myAnisoLevel; //!< level of anisotropy filter, Graphic3d_LOTA_OFF by default Graphic3d_TypeOfTextureMode myGenMode; //!< texture coordinates generation mode, Graphic3d_TOTM_MANUAL by default Standard_Integer myBaseLevel; //!< base texture mipmap level (0 by default) Standard_Integer myMaxLevel; //!< maximum texture mipmap array level (1000 by default) Standard_ShortReal myRotAngle; //!< texture coordinates rotation angle in degrees, 0 by default Standard_Boolean myToModulate; //!< flag to modulate texture with material color, FALSE by default Standard_Boolean myToRepeat; //!< flag to repeat (true) or wrap (false) texture coordinates out of [0,1] range }; DEFINE_STANDARD_HANDLE(Graphic3d_TextureParams, Standard_Transient) #endif // _Graphic3d_TextureParams_HeaderFile
#define _CRT_SECURE_NO_WARNINGS #include <iostream> using namespace std; class Fraction;//Объявление класса (Class declaration) Fraction operator*(Fraction left, Fraction right);//прототип ф-ии class Fraction { int integer; //целая часть int numerator; int denominator; public: int get_integer()const { return integer; } int get_numerator()const { return numerator; } int get_denominator()const { return denominator; } void set_integer(int integer) { this->integer = integer; } void set_numerator(int numerator) { this->numerator = numerator; } void set_denominator(int denominator) { if (denominator == 0) denominator = 1; //фильтрация данных this->denominator = denominator; } //constructors: Fraction() { this->integer = 0; this->numerator = 0; this->denominator = 1; cout << "defaultconstructor:\t" << this << endl; } explicit Fraction(int integer) { this->integer = integer; this->numerator = 0; this->denominator = 1; cout << "1argconstructor:\t" << this << endl; } Fraction(double decimal) { integer = decimal; decimal -= integer; denominator = 1e+9; numerator= decimal * denominator; reduce(); } Fraction(int numerator, int denominator) { this->integer = 0; this->numerator = numerator; this->set_denominator(denominator); cout << "constructor:\t" << this << endl; } Fraction(int integer, int numerator, int denominator) { this->integer = integer; this->numerator = numerator; this->set_denominator(denominator); cout << "constructor:\t" << this << endl; } Fraction(const Fraction& other) { this->integer = other.integer; this->numerator = other.numerator; this->denominator = other.denominator; cout << "CopyConstructor:\t" << this << endl; } ~Fraction() { cout << "Destructor:\t" << this << endl; } // operators Fraction& operator=(const Fraction& other) { this->integer = other.integer; this->numerator = other.numerator; this->denominator = other.denominator; cout << "CopyAssignment:\t" << this << endl; return *this; } Fraction& operator *=(const Fraction& other) { return *this= *this*other; } // инкремент - декремент Fraction& operator++() //префикс инкремент { integer++; return *this; } Fraction operator++(int) //постфикс(суффикс) инкремент { Fraction old = *this; //сохраняем старое значение integer++; return old; } Fraction& operator--() //префикс декремент { integer--; return *this; } Fraction operator--(int) //постфикс(суффикс) декремент { Fraction old = *this; //сохраняем старое значение integer--; return old; } // Type-cast operators explicit operator int()const { return integer; } explicit operator double()const { return integer + (double)numerator / denominator; } // methods Fraction& to_improper() { numerator += integer * denominator; integer = 0; return *this; } Fraction& to_proper() { integer += numerator / denominator; numerator %= denominator; return *this; } Fraction inverted()//Обращает дробь - меняет местами числитель и знаменатель { /*to_improper(); int buf = numerator; numerator = denominator; denominator = buf; return *this;*/ to_improper(); return Fraction(denominator, numerator); } //сокращение дроби Fraction& reduce() //сокращение дроби по алгоритму Евклида { // my code /* this->to_improper(); if (numerator > denominator) { int NOD = numerator % denominator; int buf; while (NOD != 0){ buf = NOD; NOD = denominator % NOD; } this->set_numerator(numerator / buf); this->set_denominator(denominator / buf); } else { int NOD = denominator % numerator; int buf; while (NOD != 0){ buf = NOD; NOD = numerator % NOD; } this->set_numerator(numerator / buf); this->set_denominator(denominator / buf); } return *this;*/ int more, less, rest; if (numerator > denominator) { more = numerator; less = denominator; }else{ more = denominator; less = numerator; } do { rest = more % less; more = less; less = rest; } while (rest); int GSD = more; //наибольший общий делитель numerator /= GSD; denominator /= GSD; return *this; } void print() { if (integer) cout << integer; if (integer && numerator) cout << "("; if (numerator) cout << numerator << "/" << denominator; if (integer && numerator) cout << ")"; if (integer==0 && numerator==0) cout << 0; cout << endl; } }; // общий знаменатель int commondenominator(Fraction left, Fraction right) { return left.get_denominator() * right.get_denominator(); } // arithmetical operators: +, -, *, /; Fraction operator+(Fraction left, Fraction right) { left.to_improper(); right.to_improper(); /*int commonnumerator; commonnumerator = left.get_numerator() * right.get_denominator() + right.get_numerator() * left.get_denominator(); //общий числитель Fraction result(commonnumerator, commondenominator(left, right)); result.to_proper(); return result;*/ return Fraction( left.get_numerator() * right.get_denominator() + right.get_numerator() * left.get_denominator(), left.get_denominator() * right.get_denominator() ).to_proper(); } Fraction operator-(Fraction left, Fraction right) { left.to_improper(); right.to_improper(); int commonnumerator; if (left.get_numerator() < right.get_numerator()) { commonnumerator = right.get_numerator() * left.get_denominator() - left.get_numerator() * right.get_denominator(); } else { commonnumerator = left.get_numerator() * right.get_denominator() - right.get_numerator() * left.get_denominator(); } Fraction result(commonnumerator, commondenominator(left,right)); result.to_proper(); return result; } Fraction operator*(Fraction left, Fraction right) { left.to_improper(); right.to_improper(); //через конструктор /*Fraction result(left.get_numerator() * right.get_numerator(), left.get_denominator() * right.get_denominator());*/ /*через set-методы result.set_numerator(left.get_numerator() * right.get_numerator()); result.set_denominator(left.get_denominator() * right.get_denominator());*/ //return result; //третий способ //через явный вызов конструктора, к-й создает безымянный об-т с нужным результатом return Fraction ( left.get_numerator() * right.get_numerator(), left.get_denominator() * right.get_denominator()); } Fraction operator/(Fraction left, Fraction right) { /*left.to_improper(); right.to_improper(); Fraction result; result.set_numerator(left.get_numerator() * right.get_denominator()); result.set_denominator(right.get_numerator() * left.get_denominator()); result.to_proper(); return result;*/ return left * right.inverted(); } // arithmetical operators: +, -, *, /; // comparison operators : == , != , > , < , >= , <= bool operator==(const Fraction& left, const Fraction& right) { /*left.to_improper(); right.to_improper(); if (left.get_numerator() == right.get_numerator() && left.get_denominator() == right.get_denominator()) { return true; } else { return false; }*/ //left.to_improper(); //right.to_improper(); /*if (left.get_numerator() * right.get_denominator() == left.get_denominator() * right.get_numerator()) return true; else return false;*/ //return left.get_numerator() * right.get_denominator() == left.get_denominator() * right.get_numerator(); return (double)left == (double) right; } bool operator!=(const Fraction& left, const Fraction& right) { //left.to_improper(); //right.to_improper(); /*if (left.get_numerator() != right.get_numerator() && left.get_denominator() != right.get_denominator()) { return true; } else { return false; }*/ //return left.get_numerator() * right.get_denominator() != left.get_denominator() * right.get_numerator(); return !(left == right); } bool operator<(const Fraction& left, const Fraction& right) { /*left.to_improper(); right.to_improper(); if (left.get_numerator() * right.get_denominator() < left.get_denominator()*right.get_numerator()) { return true; } else { return false; }*/ return (double)left < (double)right; } bool operator<=(const Fraction& left, const Fraction& right) { /*left.to_improper(); right.to_improper(); if (left.get_numerator() * right.get_denominator() <= left.get_denominator() * right.get_numerator()) { return true; } else { return false; }*/ return left < right || left == right; //return !(left > right); } bool operator>(const Fraction& left, const Fraction& right) { /*left.to_improper(); right.to_improper(); if (left.get_numerator() * right.get_denominator() > left.get_denominator() * right.get_numerator()) { return true; } else { return false; }*/ return (double)left > (double)right; } bool operator>=(const Fraction& left, const Fraction& right) { /*left.to_improper(); right.to_improper(); if (left.get_numerator() * right.get_denominator() > left.get_denominator() * right.get_numerator()) { return true; } else { return false; }*/ //return left > right || left == right; return !(left < right); } // comparison operators : == , != , > , < , >= , <= ostream& operator<<(ostream& os, const Fraction& obj) { if (obj.get_integer()) os << obj.get_integer(); if (obj.get_integer() && obj.get_numerator()) os << "("; if (obj.get_numerator()) os << obj.get_numerator() << "/" << obj.get_denominator(); if (obj.get_integer() && obj.get_numerator()) os << ")"; if (obj.get_integer() == 0 && obj.get_numerator() == 0) os << 0; return os; } istream& operator>>(istream& is, Fraction& obj) { /*int integer, numerator, denominator; is >> integer >> numerator >> denominator; obj.set_integer(integer); obj.set_numerator(numerator); obj.set_denominator(denominator); */ const int n = 32; char buffer[n] = {}; char delimiters[] = "(/) +"; char* number[5] = {}; cin.getline(buffer, n); int i = 0; /*while (pch) { cout << pch << "\t"; pch = strtok(NULL, delimiters); number[i++] = pch;// atoi(pch); }*/ for (char* pch = strtok(buffer, delimiters); pch; pch = strtok(NULL, delimiters), i++) { number[i] = pch; } //for (i = 0; i < 5; i++) cout << number[i] << "\t"<< endl; switch (i) { case 1: obj.set_integer(atoi(number[0])); break; case 2: obj.set_numerator(atoi(number[0])); obj.set_denominator(atoi(number[1])); break; case 3: obj.set_integer(atoi(number[0])); obj.set_numerator(atoi(number[1])); obj.set_denominator(atoi(number[2])); break; default: cout << "Error!" << endl; } return is; } int dva_plus_dva() { return 2 + 2; } //#define CONSTRUCTORS_CHECK //#define ARITHMETICALS_OPERATORS_CHECK //#define COMPARISON_OPERATORS #define TYPE_CONVERTIONS_HOME_WORK //#define OUTPUT_CHECK //#define INPUT_CHECK void main() { setlocale(LC_ALL, "Russian"); #ifdef CONSTRUCTORS_CHECK Fraction A; //default constructor A.print(); Fraction B = 3;//single argument constructor B.print(); Fraction C(3, 4); C.print(); Fraction D(2, 3, 4); D.print(); Fraction E = D; //copyconstructor E.print(); Fraction F; //defaultconstructor F = E; //copyassignment F.print(); cout << dva_plus_dva() << endl; #endif CONSTRUCTORS_CHECK //Fraction A(2, 3, 4); /*A.print(); A.to_improper(); A.print(); A.to_proper(); A.print();*/ //Fraction B(3, 4, 5); /*B.print(); B.to_improper(); B.print(); B.to_proper(); B.print();*/ #ifdef ARITHMETICALS_OPERATORS_CHECK Fraction C = A * B; C.print(); /*префикс инкремент for (Fraction I(1,4); I.get_integer() < 10; ++I ) { I.print(); }*/ /*постфикс инкремент for (Fraction I(1, 4); I.get_integer() < 10; I++) { I.print(); }*/ cout << "префикс декремент: " << endl; for (Fraction I(2, 1, 4); I.get_integer() != 0; --I) { I.print(); } cout << endl; cout << "постфикс декремент: " << endl; for (Fraction I(2, 1, 4); I.get_integer() != 0; I--) { I.print(); } cout << endl; //Fraction D = A + B; //cout << "Сложение: "; (A+B).print(); Fraction E = A - B; cout << "Вычитание: "; E.print(); Fraction F = A / B; cout << "Деление: "; F.print(); #endif ARITHMETICALS_OPERATORS_CHECK #ifdef COMPARISON_OPERATORS Fraction A(1,2), B(5,10); Fraction X(1, 4), Y(5, 4); /*A.to_improper(), B.to_improper(); X.to_improper(), Y.to_improper(); if (A > B) { cout << "A > B" << endl; }else { cout << "B > A" << endl; } if (A < B) { cout << "A < B" << endl; }else { cout << "B < A" << endl; } if (X >= Y) { cout << "X >= Y" << endl; }else { cout << "Y >= X" << endl; } if (X <= Y) { cout << "X <= Y" << endl; }else { cout << "Y <= X" << endl; } /*if (A == B) { cout << "A == B" << endl; }else { cout << "A != B" << endl; } if (X != Y){ cout << "X != Y" << endl; }else { cout << "X == Y" << endl; }*/ cout << (A == B) << endl; cout << (A != B) << endl; cout << (A > B) << endl; cout << (A >= B) << endl; cout << (A < B) << endl; cout << (A <= B) << endl; #endif //COMPARISON_OPERATORS #ifdef OUTPUT_CHECK Fraction A; cout << A << endl; Fraction B(5); cout << B << endl; Fraction C(1,2); cout << C << endl; Fraction D(2,3,4); cout << D << endl; #endif //OUTPUT_CHECK #ifdef INPUT_CHECK Fraction A; cout << "Введите простую дробь: "; cin >> A; cout << "Вы ввели: " << A<< endl; cout << "Сокращенная дробь: " << A.reduce()<< endl; #endif //INPUT_CHECK //A *= B; //A.print(); /*int a = 2; Fraction A = (Fraction)5; //From int to Fraction (from less to more) A.print(); Fraction B; B = (Fraction)3;//явное преобразование B.print();*/ /*//сокращение дроби Fraction R(14,21); R.print(); R.reduce(); R.print();*/ #ifdef TYPE_CONVERTIONS_HOME_WORK /*//Task1 Fraction A(2, 3, 4); double a = A; cout << a << endl;*/ //Task2 double b = 3.14; Fraction B = b; B.print(); #endif //TYPE_CONVERTIONS_HOME_WORK }
#ifndef _PLAYER_H_ #define _PLAYER_H_ #include "cocos2d.h" #include "extensions/cocos-ext.h" #include "cocostudio/CocoStudio.h" #include "ui/CocosGUI.h" #include "AppMacros.h" #include "FootBallCommon.h" #include "BaseSprite.h" USING_NS_CC; USING_NS_CC_EXT; using namespace ui; using namespace cocostudio; enum PlayerStatus { Normal, Passed }; class Player : public BaseSprite { protected: CCRect _homeRegion; Vec2 _startPosition; LabelTTF *_title; public: Player(); ~Player(); static Player* create(int num); virtual bool initWithNum(int num); CC_SYNTHESIZE(PlayerStatus, _playerStatus, PlayerStatus); CC_SYNTHESIZE(CCRect, _ground, Ground); CC_SYNTHESIZE(bool, _onBall, OnBall); CC_SYNTHESIZE_READONLY(Armature*,_armature,Armature); virtual void setStartPosition(Vec2 var) = 0; virtual Vec2 getStartPosition(void); virtual void setHomeRegion(CCRect var) = 0; virtual CCRect getHomeRegion(void); virtual void changeTagPostion(); virtual void initAnimate(); virtual void setColor(const Color3B &color); }; #endif //_PLAYER_H_
#include "applicationmanager.h" ApplicationManager::ApplicationManager(QQmlApplicationEngine& app_engine, QObject* parent) : QObject(parent), engine(app_engine) { app_engine.rootContext()->setContextProperty("app_man", this); app_engine.load(QUrl("qrc:/app.qml")); for (const auto obj : app_engine.rootObjects()) { for (QQuickItem* item : obj->findChildren<QQuickItem*>("undirected_graph", Qt::FindChildrenRecursively)) { undirected_qangraph = qobject_cast<CustomGraph*>(item); break; } if (undirected_qangraph != nullptr) break; } for (const auto obj : app_engine.rootObjects()) { for (QQuickItem* item : obj->findChildren<QQuickItem*>("undirected_graphView", Qt::FindChildrenRecursively)) { undirected_graphView = qobject_cast<qan::GraphView*>(item); break; } if (undirected_graphView != nullptr) break; } if (undirected_qangraph == nullptr) { qDebug() << "undirected_qangraph not found"; exit(-1); } for (const auto obj : app_engine.rootObjects()) { for (QQuickItem* item : obj->findChildren<QQuickItem*>("tab_bar", Qt::FindChildrenRecursively)) { tab_bar = item; break; } if (tab_bar != nullptr) break; } if (tab_bar == nullptr) { qDebug() << "tab_bar not found"; exit(-1); } for (const auto obj : app_engine.rootObjects()) { for (QQuickItem* item : obj->findChildren<QQuickItem*>("tsp_path_cost", Qt::FindChildrenRecursively)) { tsp_solution_cost_label = item; break; } if (tsp_solution_cost_label != nullptr) break; } for (const auto obj : app_engine.rootObjects()) { for (QQuickItem* item : obj->findChildren<QQuickItem*>("tsp_compute_duration", Qt::FindChildrenRecursively)) { tsp_duration_label = item; break; } if (tsp_duration_label != nullptr) break; } for (const auto obj : app_engine.rootObjects()) { for (QQuickItem* item : obj->findChildren<QQuickItem*>("applied_algorithm", Qt::FindChildrenRecursively)) { applied_algorithm_label = item; break; } if (applied_algorithm_label != nullptr) break; } for (const auto obj : app_engine.rootObjects()) { for (QQuickItem* item : obj->findChildren<QQuickItem*>("node_creation_menu", Qt::FindChildrenRecursively)) { node_creation_menu_item = item; break; } if (node_creation_menu_item != nullptr) break; } if (node_creation_menu_item == nullptr) { qDebug() << "couldn\'t load node_creation_menu_item"; exit(-1); } undirected_graph = new Graph; undirected_graph->setType(Graph::GraphType::Undirected); QQuickItem* container = undirected_graphView->getContainerItem(); graphView_container_changed(); QObject::connect(container, SIGNAL(xChanged()), this, SLOT(graphView_container_changed())); QObject::connect(container, SIGNAL(yChanged()), this, SLOT(graphView_container_changed())); QObject::connect(container, SIGNAL(scaleChanged()), this, SLOT(graphView_container_changed())); // QObject::connect(undirected_graphView, SIGNAL(scaleChanged()), this, SLOT(zoom_origin_changed())); //QObject::connect(undirected_graphView, SIGNAL(zoom_changed()), this, SLOT(zoom_changed())); //QObject::connect(undirected_graphView, SIGNAL(navigableChanged()), this, SLOT(undirected_graph_view_navigableChanged())); }
#pragma once #include "moves.h" class specialMove :public moves { public: specialMove(); std::string specialAbility; void stun(); void setConfuseRay(); ~specialMove(); };
// Copyright (c) 2012-2017 The Cryptonote developers // 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 <system_error> #include <INode.h> namespace Tests { class TestNode { public: virtual bool startMining(size_t threadsCount, const std::string& address) = 0; virtual bool stopMining() = 0; virtual bool stopDaemon() = 0; virtual bool getBlockTemplate(const std::string& minerAddress, cn::Block& blockTemplate, uint64_t& difficulty) = 0; virtual bool submitBlock(const std::string& block) = 0; virtual bool getTailBlockId(crypto::Hash& tailBlockId) = 0; virtual bool makeINode(std::unique_ptr<cn::INode>& node) = 0; virtual uint64_t getLocalHeight() = 0; std::unique_ptr<cn::INode> makeINode() { std::unique_ptr<cn::INode> node; if (!makeINode(node)) { throw std::runtime_error("Failed to create INode interface"); } return node; } virtual ~TestNode() {} }; }
#include <iostream> #include <ctime> #include <string> #include <array> #include <vector> #include <cmath> #include <cstdlib> using namespace std; long long solve(); int main() { clock_t start = clock(); long long result = solve(); clock_t end = clock(); cout << result << ' ' << (static_cast<double>(end) - start) / CLOCKS_PER_SEC << endl; system("PAUSE"); } long long solve() { long long sum = 9999999; const size_t size = 10000000; const size_t width = 8; const size_t primeFactorsSize = ((size/2) + 1) * width; int* primeFactors = new int[primeFactorsSize]; bool* seen = new bool[size + 1]; for (size_t i = 0; i <= size / 2; ++i) { primeFactors[i * width] = 0; } array<long long, 3840> possible; long long target = 2; long long increase = 2; for (size_t i = 2, j = 2 * width, k = 1, m = width; i <= size/2; ++i, j += width, ++k, m += width) { if (primeFactors[j] == 0) { for (size_t n = j; n < primeFactorsSize; n += i * width) { ++primeFactors[n]; primeFactors[n + primeFactors[n]] = i; } } if (target <= size && seen[target]) { seen[target] = false; sum += target - i; } possible[0] = 1; size_t index = 1; size_t max = 1; for (size_t n = m + 1; n <= m + primeFactors[m]; ++n) { int prime = primeFactors[n]; int limit = 1; int temp = k/prime; while (temp%prime == 0) { ++limit; temp /= prime; } for (size_t p = 0; p < max; ++p) { int count = 0; long long newNumber = possible[p]; while (count < limit && (newNumber *= prime) < i) { ++count; possible[index] = newNumber; long long inverse = target / newNumber; if (inverse <= size) { if (seen[inverse]) { seen[inverse] = false; sum += inverse - i; } } ++index; } } max = index; } for (size_t n = j + 1; n <= j + primeFactors[j]; ++n) { int prime = primeFactors[n]; int limit = 1; int temp = i/prime; while (temp%prime == 0) { ++limit; temp /= prime; } for (size_t p = 0; p < max; ++p) { int count = 0; long long newNumber = possible[p]; while (count < limit && (newNumber *= prime) < i) { ++count; possible[index] = newNumber; long long inverse = target / newNumber; if (inverse <= size) { if (seen[inverse]) { seen[inverse] = false; sum += inverse - i; } } ++index; } } max = index; } target += increase += 2; } delete[] primeFactors; delete[] seen; return sum; }
/** * Write a program to implement first-fit, best-fit and * worst-fit allocation strategies. * */ #include <cstring> #include <iostream> #define MAX_SIZE 100 using namespace std; void firstFit(int blockSize[], int m, int processSize[], int n) { int allocation[n]; for (int i = 0; i < n; i++) allocation[i] = -1; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (blockSize[j] >= processSize[i]) { allocation[i] = j; blockSize[j] -= processSize[i]; break; } } } cout << "\nFirst-Fit Allocation Strategy\n"; cout << "=========================================\n"; cout << "\nProcess No.\tProcess Size\tBlock No.\n"; cout << "=========================================\n"; for (int i = 0; i < n; i++) { cout << " " << i + 1 << "\t\t" << processSize[i] << "\t\t"; if (allocation[i] != -1) cout << allocation[i] + 1; else cout << "Not Allocated"; cout << endl; } } int main() { int holes, processes; int holeSizes[MAX_SIZE], processSizes[MAX_SIZE]; cout << "\nEnter Number of Holes: "; cin >> holes; cout << "Enter Number of Processes: "; cin >> processes; for (int i = 0; i < holes; i++) { cout << "Enter Size of Hole " << (i + 1) << ": "; cin >> holeSizes[i]; } for (int i = 0; i < processes; i++) { cout << "Enter Size of Process " << (i + 1) << ": "; cin >> processSizes[i]; } firstFit(holeSizes, holes, processSizes, processes); cout << endl; return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** Copyright (C) 2003-2006 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 __X11_WINDOWWIDGET_H__ #define __X11_WINDOWWIDGET_H__ #include "x11_widget.h" class X11WindowWidget : public X11Widget { public: enum EventType { DELAYED_RESIZE, DELAYED_SHOW, VALIDATE_MDE_SCREEN, }; X11WindowWidget(class X11OpWindow* op_window); ~X11WindowWidget(); virtual void Show(); virtual void ShowBehind(); virtual void Hide(); virtual bool HandleEvent(XEvent *event); virtual void HandleResize(); virtual void HandleCallBack(INTPTR ev); BOOL ConfirmClose(); class X11OpWindow *GetOpWindow() const { return m_op_window; } // Implementation specific methods: /** @return The currently focused window widget */ static X11WindowWidget* GetActiveWindowWidget(); /** @return The topmost widget of an entire widget chain (without a parent). * See also X11Widget::GetTopLevel(). */ static X11Widget* GetActiveToplevelWidget(); /** @return X11 window handle of the topmost widget */ static X11Types::Window GetActiveTopWindowHandle(); protected: class X11OpWindow* m_op_window; X11Types::Window m_return_focus_to; static X11WindowWidget* m_active_window_widget; static X11Types::Window m_active_topwindow_handle; }; #endif // __X11_WINDOWWIDGET_H__
#include<iostream> #include<conio.h> #include<math.h> using namespace std; int main() { int a; int n; cout<<"Enter the number of digits :"; cin>>n; cout<<"Enter the number :"; cin>>a; int sum=0; int i,p,d; int u=pow(a%10,n); for(i=1;i<n;i++) { int z=pow(10,i); int f=a/z%10; p=pow(f,n-i); sum=sum+p; } d=sum+u; if(a==d) { cout<<"Its a disarium number"; } else { cout<<"Its not a disarium number"; } return 0; }
#include "deleteconfirmation.h" #include "ui_deleteconfirmation.h" deleteConfirmation::deleteConfirmation(QWidget *parent) : QDialog(parent), ui(new Ui::deleteConfirmation) { ui->setupUi(this); } deleteConfirmation::~deleteConfirmation() { delete ui; } void deleteConfirmation::onYesButtonClicked() { yes_or_no = true; this->close(); } void deleteConfirmation::onNoButtonClicked() { yes_or_no = false; this->close(); } bool deleteConfirmation::if_not_canceled() { return yes_or_no; }
// // ColorDetector.cpp // RubikSolver // // Created by rhcpfan on 15/01/17. // Copyright © 2017 HomeApps. All rights reserved. // #include "stdafx.h" #include "ColorDetector.hpp" /** Extracts the feature vector for the SVM (6 floats: B G R H S V) */ std::vector<float> ColorDetector::GetPixelFeatures(const cv::Mat &bgrImage, const cv::Mat &hsvImage, const cv::Point &location) { std::vector<float> features(6); auto bgrPixel = bgrImage.at<cv::Vec3b>(location); auto hsvPixel = hsvImage.at<cv::Vec3b>(location); features[0] = bgrPixel.val[0]; features[1] = bgrPixel.val[1]; features[2] = bgrPixel.val[2]; features[3] = hsvPixel.val[0]; features[4] = hsvPixel.val[1]; features[5] = hsvPixel.val[2]; return features; } /// Returns the array of feature vectors extracted for a sample patch std::vector<std::vector<float>> ColorDetector::GetFaceFeatures(const cv::Mat &bgrImage, const cv::Mat &hsvImage) { std::vector<std::vector<float>> features; for (int i = 0; i < bgrImage.rows; i++) { for (int j = 0; j < bgrImage.cols; j++) { auto bgrPixel = bgrImage.at<cv::Vec3b>(i, j); auto hsvPixel = hsvImage.at<cv::Vec3b>(i, j); features.push_back(std::vector<float> { static_cast<float>(bgrPixel.val[0]), static_cast<float>(bgrPixel.val[1]), static_cast<float>(bgrPixel.val[2]), static_cast<float>(hsvPixel.val[0]), static_cast<float>(hsvPixel.val[1]), static_cast<float>(hsvPixel.val[2]) }); } } return features; } ColorDetector::ColorDetector() { } ColorDetector::~ColorDetector() { } /** Loads a pre-trained SVM classifier from a file @param filePath The location of the YML file containing the SVM */ void ColorDetector::LoadSVMFromFile(const std::string& filePath) { _svmClassifier = cv::Algorithm::load<cv::ml::SVM>(filePath); } /** Applies the color recognition algorithm @param The cube face image extracted by EdgeBasedCubeDetector::ApplyPerspectiveTransform @return A vector of 9 strings containing the color of each cubie (ex. "Y", "R", "R", "G", "B", "O", "W", "W", "Y") */ std::vector<std::string> ColorDetector::RecognizeColors(const cv::Mat& cubeFaceImage) { cv::Mat inputImage = cubeFaceImage.clone(); // Draw some helper lines on the image (for visualisation only) cv::line(inputImage, cv::Point(inputImage.cols / 3, 0), cv::Point(inputImage.cols / 3, inputImage.rows), cv::Scalar(0, 0, 255), 5); cv::line(inputImage, cv::Point((inputImage.cols / 3) * 2, 0), cv::Point((inputImage.cols / 3) * 2, inputImage.rows), cv::Scalar(0, 0, 255), 5); cv::line(inputImage, cv::Point(0, inputImage.rows / 3), cv::Point(inputImage.cols, inputImage.rows / 3), cv::Scalar(0, 0, 255), 5); cv::line(inputImage, cv::Point(0, (inputImage.rows / 3) * 2), cv::Point(inputImage.cols, (inputImage.rows / 3) * 2), cv::Scalar(0, 0, 255), 5); // Select the sample size as 5% of the image width auto sampleSize = cubeFaceImage.cols * 0.05; auto sampleDistance = (inputImage.cols / 3.0) / 2 - (sampleSize / 2); // Take samples from the image cv::Rect sampleRectangle = cv::Rect(sampleDistance, sampleDistance, sampleSize, sampleSize); std::vector<cv::Mat> faceSamples; for (size_t j = 0; j < 3; j++) { for (size_t i = 0; i < 3; i++) { sampleRectangle.x = sampleDistance + (i * cubeFaceImage.cols / 3); sampleRectangle.y = sampleDistance + (j * cubeFaceImage.rows / 3); cv::rectangle(inputImage, sampleRectangle, cv::Scalar(255, 255, 0), 2); faceSamples.push_back(cubeFaceImage(sampleRectangle)); } } // Process each image from faceSamples std::vector<std::string> stringResults; for (size_t sampleIndex = 0; sampleIndex < faceSamples.size(); sampleIndex++) { // Convert the image to HSV for feature extraction cv::Mat hsvImage; cv::cvtColor(faceSamples[sampleIndex], hsvImage, CV_BGR2HSV_FULL); // Get the face features auto faceFeatures = GetFaceFeatures(faceSamples[sampleIndex], hsvImage); // Prepare the faceFeatures to be fed to the SVM (every sample on a row, 6 columns, type CV_32f [float]) cv::Mat detectionData = cv::Mat((int)faceFeatures.size(), 6, CV_32F); for (int i = 0; i < faceFeatures.size(); i++) { for (int featureIndex = 0; featureIndex < 6; featureIndex++) { detectionData.at<float>(i, featureIndex) = faceFeatures[i][featureIndex]; } } // Apply the recognition algorithm cv::Mat svmResults; _svmClassifier->predict(detectionData, svmResults); // Compute a histogram based on the recognition results (this counts how many samples from the same cubie have been classified as "Y", "R", etc.) // By using this approach we may elliminate issues coming from illumination, etc. cv::Mat svmHistogram; int histSize = 6; float range[] = { 0, 6 }; const float* histRange = { range }; cv::calcHist(&svmResults, 1, 0, cv::Mat(), svmHistogram, 1, &histSize, &histRange, true, false); // Take the max value from the histogram (this says that, for example, most of the features have been classified as yellow) double maxValue; cv::Point maxLocation; cv::minMaxLoc(svmHistogram, (double*)0, &maxValue, 0, &maxLocation); if (maxLocation.y == 0) stringResults.push_back("Y"); if (maxLocation.y == 1) stringResults.push_back("R"); if (maxLocation.y == 2) stringResults.push_back("B"); if (maxLocation.y == 3) stringResults.push_back("G"); if (maxLocation.y == 4) stringResults.push_back("W"); if (maxLocation.y == 5) stringResults.push_back("O"); } /* SVM Classes: 0 - yellow 1 - red 2 - white 3 - green 4 - blue 5 - orange */ return stringResults; }
#include<bits/stdc++.h> using namespace std; #define maxn 1005 int n,m; bool vis[maxn][maxn]; int ans; int main(){ ios::sync_with_stdio(false); cin.tie(0); cin>>n>>m; if(n>m) swap(n,m); if(n==1) cout<<m; else if(n==2){ int ans=0; ans+=m/4*4; if(m%4==0) cout<<ans; else if(m%4==1) cout<<ans+2; else cout<<ans+4; } else cout<<n*m-n*m/2; return EXIT_SUCCESS; }
#include<iostream> #include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<string.h> #include<sys/types.h> #include<sys/time.h> #include"lru_clock.cc" #include"lru_stack.cc" #include"fifo.cc" #include"lru_ref8.cc" #include"optimal.cc" #include"lfu.cc" using namespace std; int main(int argc, char *argv[]) { system("clear"); timeval tv,tv1,tv2,tv3,tv4,tv5,tv6; int frames=5; unsigned int opt_time=0,fif_time=0,lru_c_time=0,lru_s_time=0,lru_r_time=0,lfu_time=0; int fif_rep=0,lfu_rep=0,lru_s_rep=0,lru_c_rep=0,lru_r_rep=0,opt_rep=0; char *r,ch,c; int prev_ind,flag=0,ibuf[BUFSIZ],option=0,sc_op=1,temp=0,len=0,flag1=0,flag2=0,flag3=0; char buf[BUFSIZ]; while(prev_ind = optind, (c = getopt(argc, argv, ":h:f:r:i:")) != EOF) { if ( optind == prev_ind + 2 && *optarg == '-' ) { c = ':'; -- optind; } switch (c) { case 'h': option=1; break; case 'f': frames=atoi(optarg); break; case 'r': if(*optarg=='F') sc_op=1; else if(*optarg=='L' && *(optarg+1)=='F') sc_op=2; else if(*(optarg+4)=='S') sc_op=3; else if(*(optarg+4)=='C') sc_op=4; else if(*(optarg+4)=='R') sc_op=5; else sc_op=6; break; case 'i': flag1=1; r=optarg; for(int t=0;t<100;t++) { if(*(r+t)=='.') { flag=1; } } if(flag==1) { FILE *file; file=fopen(optarg,"r"); if(!file) { cout<<"cannot open file"<<optarg; break; } fgets(buf,sizeof(buf),file); int r=0; while(buf[r]!='\n') { temp=0; if(isspace(buf[r])) { r=r+1; } else if(buf[r] >='0' && buf[r]<='9') { while(!isspace(buf[r])) { temp=temp*10 + (buf[r]-'0'); r=r+1; } ibuf[len]=temp; len=len+1; } else { cout<<"invalid sequence"; flag2=1; break; } } } break; case ':': cerr << "Missing option." << endl; exit(1); break; } } if(flag1!=1) { cout<<"enter page sequence"<<endl; ch=getchar(); while(ch!='\n') { temp=0; flag=0; if(isspace(ch)) { ch=getchar(); } else if(ch >='0' && ch<='9') { while(!isspace(ch) && ch!='\n') { if(!(ch >='0' && ch<='9')) { cout<<endl<<"invalid sequence"<<endl; flag3=1; break; } temp=temp*10 + (ch-'0'); ch=getchar(); } if(flag3==1) { break; } ibuf[len]=temp; len=len+1; } else { cout<<"invalid sequence"<<endl; break; } } } gettimeofday(&tv, NULL); opt_rep=optimal(ibuf,len,frames); gettimeofday(&tv1, NULL); opt_time=tv1.tv_usec-tv.tv_usec; if(flag2!=1 && flag3!=1) { if(option==1) { gettimeofday(&tv, NULL); fif_rep=fifo(ibuf,len,frames); gettimeofday(&tv1, NULL); fif_time=tv1.tv_usec-tv.tv_usec; cout<<endl<<"Page replacement with FIFO "<<fif_rep; cout<<endl<<"Page replacement with optimal "<<opt_rep; cout<<endl<<"%page replacement penalty using FIFO "<<(float(fif_rep-opt_rep)/opt_rep)*100<<"%"; cout<<endl<<"Total time to run FIFO "<<fif_time<<" msec"; cout<<endl<<"Total time to run optimal algo "<<opt_time<<" msec"; if(fif_time>opt_time) { cout<<endl<<"FIFO is "<<(float(fif_time-opt_time)/opt_time)*100<<"% slower than optimal algorithm"; } else { cout<<endl<<"FIFO is "<<(float(opt_time-fif_time)/opt_time)*100<<"% faster than optimal algorithm"; } gettimeofday(&tv, NULL); lfu_rep=lfu(ibuf,len,frames); gettimeofday(&tv1, NULL); lfu_time=tv1.tv_usec-tv.tv_usec; cout<<"\n\nPage replacement with LFU "<<lfu_rep; cout<<"\nPage replacement with optimal "<<opt_rep; cout<<"\npage replacement penalty using LFU "<<(float(lfu_rep-opt_rep)/opt_rep)*100<<"%"; cout<<"\nTotal time to run LFU "<<lfu_time<<" msec"; cout<<"\nTotal time to run optimal algo "<<opt_time<<" msec"; if(lfu_time>opt_time) { cout<<"\nLFU is "<<(float(lfu_time-opt_time)/opt_time)*100<<"% slower than optimal algorithm"; } else { cout<<"\nLFU is "<<(float(opt_time-lfu_time)/opt_time)*100<<"% faster than optimal algorithm"; } gettimeofday(&tv, NULL); lru_s_rep=lru_stack(ibuf,len,frames); gettimeofday(&tv1, NULL); lru_s_time=tv1.tv_usec-tv.tv_usec; cout<<"\n\nPage replacement with LRU Stack "<<lru_s_rep; cout<<"\nPage replacement with optimal "<<opt_rep; cout<<"\npage replacement penalty using LRU Stack "<<(float(lru_s_rep-opt_rep)/opt_rep)*100<<"%"; cout<<"\nTotal time to run LRU Stack "<<lru_s_time<<" msec"; cout<<"\nTotal time to run optimal algo "<<opt_time<<" msec"; if(lru_s_time>opt_time) { cout<<"\nLRU Stack is "<<(float(lru_s_time-opt_time)/opt_time)*100<<"% slower than optimal algorithm"; } else { cout<<"\nLRU Stack is "<<(float(opt_time-lru_s_time)/opt_time)*100<<"% faster than optimal algorithm"; } gettimeofday(&tv, NULL); lru_c_rep=lru_clock(ibuf,len,frames); gettimeofday(&tv1, NULL); lru_c_time=tv1.tv_usec-tv.tv_usec; cout<<"\n\nPage replacement with LRU Clock "<<lru_c_rep; cout<<"\nPage replacement with optimal "<<opt_rep; cout<<"\npage replacement penalty using LRU Clock "<<(float(lru_c_rep-opt_rep)/opt_rep)*100<<"%"; cout<<"\nTotal time to run LRU Clock "<<lru_c_time<<" msec"; cout<<"\nTotal time to run optimal algo "<<opt_time<<" msec"; if(lru_c_time>opt_time) { cout<<"\nLRU Clock is "<<(float(lru_c_time-opt_time)/opt_time)*100<<"% slower than optimal algorithm"; } else { cout<<"\nLRU Clock is "<<(float(opt_time-lru_c_time)/opt_time)*100<<"% faster than optimal algorithm"; } gettimeofday(&tv, NULL); lru_r_rep=lru_ref8(ibuf,len,frames); gettimeofday(&tv1, NULL); lru_r_time=tv1.tv_usec-tv.tv_usec; cout<<"\n\nPage replacement with LRU ref8 "<<lru_r_rep; cout<<"\nPage replacement with optimal "<<opt_rep; cout<<"\npage replacement penalty using LRU ref8 "<<(float(lru_r_rep-opt_rep)/opt_rep)*100<<"%"; cout<<"\nTotal time to run LRU ref8 "<<lru_r_time<<" msec"; cout<<"\nTotal time to run optimal algo "<<opt_time<<" msec"; if(lru_r_time>opt_time) { cout<<"\nLRU ref8 is "<<(float(lru_r_time-opt_time)/opt_time)*100<<"% slower than optimal algorithm"; } else { cout<<"\nLRU ref8 is "<<(float(opt_time-lru_r_time)/opt_time)*100<<"% faster than optimal algorithm"; } } else { switch(sc_op) { case 1: gettimeofday(&tv, NULL); fif_rep=fifo(ibuf,len,frames); gettimeofday(&tv1, NULL); fif_time=tv1.tv_usec-tv.tv_usec; cout<<endl<<"Page replacement with FIFO "<<fif_rep; cout<<endl<<"Page replacement with optimal "<<opt_rep; cout<<endl<<"%page replacement penalty using FIFO "<<(float(fif_rep-opt_rep)/opt_rep)*100<<"%"; cout<<endl<<"Total time to run FIFO "<<fif_time<<" msec"; cout<<endl<<"Total time to run optimal algo "<<opt_time<<" msec"; if(fif_time>opt_time) { cout<<endl<<"FIFO is "<<(float(fif_time-opt_time)/opt_time)*100<<"% slower than optimal algorithm"; } else { cout<<endl<<"FIFO is "<<(float(opt_time-fif_time)/opt_time)*100<<"% faster than optimal algorithm"; } break; case 2: gettimeofday(&tv, NULL); lfu_rep=lfu(ibuf,len,frames); gettimeofday(&tv1, NULL); lfu_time=tv1.tv_usec-tv.tv_usec; cout<<"\n\nPage replacement with LFU "<<lfu_rep; cout<<"\nPage replacement with optimal "<<opt_rep; cout<<"\npage replacement penalty using LFU "<<(float(lfu_rep-opt_rep)/opt_rep)*100<<"%"; cout<<"\nTotal time to run LFU "<<lfu_time<<" msec"; cout<<"\nTotal time to run optimal algo "<<opt_time<<" msec"; if(lfu_time>opt_time) { cout<<"\nLFU is "<<(float(lfu_time-opt_time)/opt_time)*100<<"% slower than optimal algorithm"; } else { cout<<"\nLFU is "<<(float(opt_time-lfu_time)/opt_time)*100<<"% faster than optimal algorithm"; } break; case 3: gettimeofday(&tv, NULL); lru_s_rep=lru_stack(ibuf,len,frames); gettimeofday(&tv1, NULL); lru_s_time=tv1.tv_usec-tv.tv_usec; cout<<"\n\nPage replacement with LRU Stack "<<lru_s_rep; cout<<"\nPage replacement with optimal "<<opt_rep; cout<<"\npage replacement penalty using LRU Stack "<<(float(lru_s_rep-opt_rep)/opt_rep)*100<<"%"; cout<<"\nTotal time to run LRU Stack "<<lru_s_time<<" msec"; cout<<"\nTotal time to run optimal algo "<<opt_time<<" msec"; if(lru_s_time>opt_time) { cout<<"\nLRU Stack is "<<(float(lru_s_time-opt_time)/opt_time)*100<<"% slower than optimal algorithm"; } else { cout<<"\nLRU Stack is "<<(float(opt_time-lru_s_time)/opt_time)*100<<"% faster than optimal algorithm"; } break; case 4: gettimeofday(&tv, NULL); lru_c_rep=lru_clock(ibuf,len,frames); gettimeofday(&tv1, NULL); lru_c_time=tv1.tv_usec-tv.tv_usec; cout<<"\n\nPage replacement with LRU Clock "<<lru_c_rep; cout<<"\nPage replacement with optimal "<<opt_rep; cout<<"\npage replacement penalty using LRU Clock "<<(float(lru_c_rep-opt_rep)/opt_rep)*100<<"%"; cout<<"\nTotal time to run LRU Clock "<<lru_c_time<<" msec"; cout<<"\nTotal time to run optimal algo "<<opt_time<<" msec"; if(lru_c_time>opt_time) { cout<<"\nLRU Clock is "<<(float(lru_c_time-opt_time)/opt_time)*100<<"% slower than optimal algorithm"; } else { cout<<"\nLRU Clock is "<<(float(opt_time-lru_c_time)/opt_time)*100<<"% faster than optimal algorithm"; } break; case 5: gettimeofday(&tv, NULL); lru_r_rep=lru_ref8(ibuf,len,frames); gettimeofday(&tv1, NULL); lru_r_time=tv1.tv_usec-tv.tv_usec; cout<<"\n\nPage replacement with LRU ref8 "<<lru_r_rep; cout<<"\nPage replacement with optimal "<<opt_rep; cout<<"\npage replacement penalty using LRU ref8 "<<(float(lru_r_rep-opt_rep)/opt_rep)*100<<"%"; cout<<"\nTotal time to run LRU ref8 "<<lru_r_time<<" msec"; cout<<"\nTotal time to run optimal algo "<<opt_time<<" msec"; if(lru_r_time>opt_time) { cout<<"\nLRU ref8 is "<<(float(lru_r_time-opt_time)/opt_time)*100<<"% slower than optimal algorithm"; } else { cout<<"\nLRU ref8 is "<<(float(opt_time-lru_r_time)/opt_time)*100<<"% faster than optimal algorithm"; } break; default: cout<<"invalid algo name"; break; } } } cout<<"\n\n"; return 0; }
#include "CDistributeMessage.h" #include "Markup.h" #include "CMessageEventMediator.h" #include "NetClass.h" CDistributeMessage::CDistributeMessage(CMessageEventMediator* pMessageEventMediator, QObject *parent) : CMessage(pMessageEventMediator, parent) { } CDistributeMessage::~CDistributeMessage() { } bool CDistributeMessage::packedSendMessage(NetMessage& netMessage) { return false; } bool CDistributeMessage::treatMessage(const NetMessage& netMessage, CNetClt* pNet) { CMarkup xml; if(xml.SetDoc(netMessage.msgBuffer)) { int errCode = 0; QString errorInfo = ""; if(checkError(&xml, errCode, errorInfo)) { if(0 != errCode) { ClientLogger->AddLog(QString::fromLocal8Bit("DistributeMessage [%1] : \r\n[%2]").arg(errorInfo).arg(netMessage.msgBuffer)); emit NetClass->m_pMessageEventMediator->sigError(netMessage.msgHead, errorInfo); return true; } } if(xml.FindChildElem("Info")) { xml.IntoElem(); QString strMsg = QString::fromStdString(xml.GetAttrib("Msg")); QString strTime = QString::fromStdString(xml.GetAttrib("Time")); xml.OutOfElem(); ClientLogger->AddLog(QString::fromLocal8Bit("服务器 推送通知[%1] 推送时间[%2]").arg(strMsg).arg(strTime)); emit NetClass->m_pMessageEventMediator->sigServerDistributeMsg(strMsg, strTime); } else { ClientLogger->AddLog(QString::fromLocal8Bit("DistributeMessage收到的消息错误, 无法被正确解析 : [%1]").arg(netMessage.msgBuffer)); emit NetClass->m_pMessageEventMediator->sigError(netMessage.msgHead, QString::fromLocal8Bit("收到的消息错误, 无法被正确解析")); } } else { ClientLogger->AddLog(QString::fromLocal8Bit("DistributeMessage收到的消息错误, 无法被正确解析 : [%1]").arg(netMessage.msgBuffer)); emit NetClass->m_pMessageEventMediator->sigError(netMessage.msgHead, QString::fromLocal8Bit("收到的消息错误, 无法被正确解析")); } return true; }