blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
622b21e4d2d561723df65ff67b041881278eb5b6
90d6f3f2379aea59a9c3466d40d4879bbb3f84f7
/Heather_Key_Game_4/RenderManager.h
2ffb36b7ae75a2349685b541538c405fb2709dea
[]
no_license
hmkey/Game_4_Repo
67bed8497b01f0f1eb5db29cae0901413f933eab
ffd6d693f9536fc110a91b72d2aac8ed10f70303
refs/heads/master
2020-05-19T14:06:19.056829
2015-04-07T04:22:29
2015-04-07T04:22:29
33,517,572
0
0
null
null
null
null
UTF-8
C++
false
false
4,114
h
#if !defined RENDER_MANAGER #define RENDER_MANAGER #include "GameHeader.h" #include "Ogre.h" #include "RenderListener.h" #include "CSC2110/ListArray.h" #include "tinyxml.h" class GameManager; class GUIManager; //class ScriptManager; class RenderManager { private: Ogre::SceneNode* selected_node; ListArray<Ogre::AnimationState>* animation_states; Ogre::Root* root; Ogre::RenderWindow* window; Ogre::SceneManager* scene_manager; Ogre::Camera* camera; Ogre::Viewport* viewport; //ScriptManager* script_manager; GUIManager* gui_manager; GameManager* game_manager; RenderListener* render_listener; uint32 currBgMusicID; void init(); size_t window_handle; Ogre::Real time_since_last_frame; bool bgMusicChosen; std::string loaded_group; void addSceneNodeChildren(TiXmlNode* xml_node, Ogre::SceneNode* parent_node, float* values); void addSceneNodeAnimation(TiXmlNode* animation_node_xml, Ogre::SceneNode* child_scene_node, std::string animation_name_text, float* values); /* void buildSubmarineAnimation(Ogre::SceneNode* submarine_animation_node); void buildRudderAnimation(Ogre::SceneNode* rudder_animation_node); void buildPeriscopeAnimation(Ogre::SceneNode* periscope_animation_node); void buildPropellerAnimation(Ogre::SceneNode* propeller_animation_node); void buildXWingAnimationScene(); void buildRobotAnimation(Ogre::SceneNode* robot_node); void buildStarShipAnimation(Ogre::SceneNode* starShip); void buildURWingAnimation(Ogre::SceneNode* URWing); void buildLRWingAnimation(Ogre::SceneNode* LRWing); void buildULWingAnimation(Ogre::SceneNode* ULWing); void buildLLWingAnimation(Ogre::SceneNode* ULWing); void buildCannonSceneGraph(); void buildBarrelAnimation(Ogre::SceneNode* barrel_animation_node); void buildWheelAnimation(Ogre::SceneNode* wheel_animation_node); void buildCannonballAnimation(Ogre::SceneNode* cannonball_animation_node); void buildCannonAnimation(Ogre::SceneNode* cannon_animation_node); */ public: RenderManager(GameManager* game_manager); virtual ~RenderManager(); void updateAudio(); void mousePressed(uint32 mouse_x, uint32 mouse_y, uint32 game_mouse); void mouseReleased(uint32 mouse_x, uint32 mouse_y, uint32 game_mouse); void mouseMoved(uint32 mouse_x, uint32 mouse_y, int mouse_rel_x, int mouse_rel_y); void joystickAxisMoved(int* amount); size_t getRenderWindowHandle(); int getRenderWindowWidth(); int getRenderWindowHeight(); void checkForInput(float time_step); void addPathResource(std::string file_name, std::string path_type, std::string group_name); void addMeshResource(std::string file_name, std::string mesh_str, std::string group_name); void loadResourceGroup(std::string section_name); void unloadResourceGroup(std::string group_name); void initialiseResourceGroup(std::string group_name); //void loadOgreResourcesFromXML(std::string file_name, std::string section_name); //void unloadOgreResources(); void buildSceneFromXML(std::string file_name); void setTimeSinceLastFrame(Ogre::Real time_since_last_frame); Ogre::RenderWindow* getRenderWindow(); Ogre::SceneManager* getSceneManager(); void startRendering(); void stopRendering(); void processAnimations(float time_step); void setSelectedNode(std::string item); void logComment(std::string comment_message); void executeScript(std::string file_name, std::string script_name, std::string object_name); void setCurrBgMusicID(uint32 id); uint32 getCurrBgMusicID(); void processGUIButton(std::string btn_name); void processComboBox(std::string item_name); void enableBoatAnimation(std::string ani_name); void enableWindAnimation(std::string ani_name); void playRandomAudioSample(); // add if have time //void changeBgMusic()// if have time add this. }; #endif
[ "hmkchan0327@gmail.com" ]
hmkchan0327@gmail.com
a985e0135b795045f3f86ba0d08db4c00b83aa1d
40efe206e2a2050f852fe8e51b25962da8de58a3
/acex_draw_test/AppBase.cpp
7b712b9a0d3a2643a4df07850828652e066c4787
[ "MIT" ]
permissive
fstabin/acex_draw
47778d766a5f84f4af9963f3d85e33628fcc78d6
4ae949fea7aff2a7e5fb7d62c87f66d819d7732d
refs/heads/master
2021-04-06T20:23:46.664569
2018-03-16T07:27:15
2018-03-16T07:27:15
125,228,614
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
6,439
cpp
#include "stdafx.h" #define CRTDBG_MAP_ALLOC #include <crtdbg.h> #include <thread> #include <atomic> #include <combaseapi.h> #include <shared_mutex> #include <mutex> #include <WindowsX.h> #include "resource.h" #include "AppBase.h" #include "Main.h" #define MAX_LOADSTRING 100 #define WM_USER_SCREEN_SETUP ( WM_USER + 1 ) #define WM_USER_SCREEN_SETSIZE ( WM_USER_SCREEN_SETUP + 1 ) // グローバル変数: HINSTANCE AppBase::hInstance; HWND AppBase::hMainWindow; //std::mutex WindowGuard; AppBase::SCREEN_SIZE Screen; WCHAR szTitle[MAX_LOADSTRING]; // タイトル バーのテキスト WCHAR szWindowClass[MAX_LOADSTRING]; // メイン ウィンドウ クラス名 std::shared_mutex mutCursor; POINT pCursor; std::atomic_bool bWindowClosed = false; std::atomic_bool bLClick = false; std::atomic_bool bRClick = false; std::atomic_bool bKeyStates[255]; LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); ATOM RegisterWindowClass(HINSTANCE hInstance, WNDPROC proc); HWND CreateMyWindow(HINSTANCE, int); void MainThreadFunc(); int WindowThreadFunc(); using AppBase::hMainWindow; int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { _CrtDumpMemoryLeaks(); _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // グローバル文字列を初期化 LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadStringW(hInstance, IDC_WNDCLASS, szWindowClass, MAX_LOADSTRING); if (FAILED( CoInitializeEx(nullptr, COINIT_MULTITHREADED))) { return FALSE; } AppBase::hInstance = hInstance; //初期化 { //ウィンドウ作成 auto a = RegisterWindowClass(hInstance, WndProc); if (NULL == (hMainWindow = CreateMyWindow(hInstance, nCmdShow))) { return FALSE; } } for (size_t i = 0; i < 255; i++) { bKeyStates[i] = false; } int RenderResult; { std::thread thAppMain; thAppMain = std::thread(MainThreadFunc); RenderResult = WindowThreadFunc(); thAppMain.join(); } CoUninitialize(); return RenderResult; } void MainThreadFunc() { CoInitializeEx(nullptr, COINIT_MULTITHREADED); std::unique_ptr<App::Main> main = std::make_unique<App::Main>(); try { main->Func(); } catch (const std::exception& except) { MessageBoxA(hMainWindow, except.what(), "Err", MB_ICONINFORMATION); } PostMessage(hMainWindow, WM_CLOSE, 0, 0); CoUninitialize(); } int WindowThreadFunc() { MSG msg; HACCEL hAccelTable = LoadAccelerators(AppBase::hInstance, MAKEINTRESOURCE(IDC_ACCELERATORS)); while (true) { if (GetMessage(&msg, nullptr, 0, 0) > 0) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } else break; } bWindowClosed = true; return (int)msg.wParam; } ATOM RegisterWindowClass(HINSTANCE hInstance, WNDPROC proc) { WNDCLASSEXW wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = proc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = 0; wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.lpszMenuName = NULL; wcex.lpszClassName = szWindowClass; wcex.hIconSm = 0; return RegisterClassExW(&wcex); } HWND CreateMyWindow(HINSTANCE hInstance, int nCmdShow) { HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_MINIMIZEBOX | WS_CAPTION | WS_SYSMENU, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr); if (!hWnd) { return nullptr; } return hWnd; } void SetBestWindowSize(HWND hWnd) { RECT rClient; RECT rWindow; ::GetClientRect(hWnd, &rClient); ::GetWindowRect(hWnd, &rWindow); int newWidth = (rWindow.right - rWindow.left) - (rClient.right - rClient.left) + Screen.width; int newHeight = (rWindow.bottom - rWindow.top) - (rClient.bottom - rClient.top) + Screen.height; ::SetWindowPos(hWnd, nullptr, 0, 0, newWidth, newHeight, SWP_NOMOVE | SWP_NOZORDER); } void SetWindowMode(HWND hWnd) { ::ShowWindow(hWnd, SW_SHOWDEFAULT); ::UpdateWindow(hWnd); } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_MOUSEMOVE: { std::lock_guard<std::shared_mutex>(std::ref(mutCursor)); pCursor.x = GET_X_LPARAM(lParam); pCursor.y = GET_Y_LPARAM(lParam); } break; case WM_LBUTTONDOWN: bLClick = true; break; case WM_RBUTTONDOWN: bRClick = true; break; case WM_KEYDOWN: if (wParam > 255)break; bKeyStates[wParam] = true;; break; case WM_KEYUP: if (wParam > 255)break; bKeyStates[wParam] = false; break; case WM_KILLFOCUS: for (size_t i = 0; i < 255; i++) { bKeyStates[i] = false; } break; case WM_DESTROY: PostQuitMessage(0); break; case WM_USER_SCREEN_SETUP: SetWindowMode(hWnd); break; case WM_USER_SCREEN_SETSIZE: SetBestWindowSize(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; } bool AppBase::AppWait(acs::ulong dwMillisec) { //ウィンドウが閉じられたかどうかを返す for (DWORD i = 0; i <= dwMillisec; i++) { if (bWindowClosed)return false; SleepEx(1, false); } return true; } void AppBase::StartLClickCheck() { bLClick = false; } bool AppBase::CheckLClicked() { return bLClick; } void AppBase::StartRClickCheck() { bRClick = false; } bool AppBase::CheckRClicked() { return bRClick; } bool AppBase::CheckKeyDown(unsigned char code) { return bKeyStates[code]; } bool AppBase::GetScreenSize(AppBase::SCREEN_SIZE& size) { size = Screen; return true; } bool AppBase::ScreenSetup() { ::PostMessageW(hMainWindow, WM_USER_SCREEN_SETUP, 0, 0); return true; } bool AppBase::ScreenSetSize(const AppBase::SCREEN_SIZE& size) { Screen = size; ::PostMessageW(hMainWindow, WM_USER_SCREEN_SETSIZE, 0, 0); return true; }
[ "tabibito_1500@yahoo.co.jp" ]
tabibito_1500@yahoo.co.jp
b3396d994146ab6806d67538bac4c3df07852e52
91604aa0369c53e8c76f48039ef4f72b994160dd
/InitBall/main.cpp
bc9726c5e593221dd93e0d8a01192fb8e22e7cfc
[]
no_license
Devang-25/dev_cpp
391a32baa1ddf765849e945a616f783f2fca56cf
6847f85e5b35b7c2d23acad935d4ae752f1c5b56
refs/heads/master
2023-01-30T16:32:56.134960
2020-09-05T00:55:39
2020-09-05T00:55:39
308,292,954
0
0
null
2020-12-18T18:32:04
2020-10-29T10:27:28
null
UTF-8
C++
false
false
926
cpp
#include <string> #include <iostream> class Ball { private: std::string m_color{"black"}; double m_radius{10.0}; public: // Default constructor with no parameters Ball()//: m_color{"black"}, m_radius{10.0} { } // Constructor with only color parameter (radius will use default value) Ball(const std::string &color) : m_color{color} { } // Constructor with only radius parameter (color will use default value) Ball(double radius) : m_radius{radius} { } // Constructor with both color and radius parameters Ball(const std::string &color, double radius) : m_color{color}, m_radius{radius} { } void print() { std::cout << "color: " << m_color << ", radius: " << m_radius << '\n'; } }; int main() { Ball def; def.print(); Ball blue{ "blue" }; blue.print(); Ball twenty{ 20.0 }; twenty.print(); Ball blueTwenty{ "blue", 20.0 }; blueTwenty.print(); return 0; }
[ "nsikanikpoh@gmail.com" ]
nsikanikpoh@gmail.com
936141bbd3b4f20817d48b4a4ca98d3aa7b6aeb0
c4a93788c29ba1600802a618d13b566791cf29d6
/QtPriority/myclass.h
fe48c3986e70820eca2a3b3d6638ca73fdada230
[]
no_license
linshunzong/qt
f297bcad91452fbbcab3ddd2f602e8b4c1ea67a4
3a33d9d8c2b43380ce1b11e7cad340d46e1896e8
refs/heads/master
2021-01-13T01:49:25.092907
2015-02-09T15:48:38
2015-02-09T15:48:38
30,252,409
0
0
null
null
null
null
UTF-8
C++
false
false
632
h
#ifndef MYCLASS_H #define MYCLASS_H #include <QObject> class MyClass : public QObject { Q_OBJECT Q_ENUMS(Priority) Q_PROPERTY(Priority priority READ priority WRITE setPriority) Q_PROPERTY(QString version READ version WRITE setVersion) public: enum Priority{High,Low,VeryHigh,VeryLow}; explicit MyClass(QObject *parent = 0); void setPriority(Priority priority); Priority priority() const; QString version()const; void setVersion(QString version); public: QString toString(); signals: public slots: private: Priority m_priority; QString m_version; }; #endif // MYCLASS_H
[ "linsz@163.com" ]
linsz@163.com
f65cd307754826fa923f655f42c04e698221959e
9bae8aacd764665af615619cb99f516d24003d70
/src/blockchain_utilities/blockchain_prune_known_spent_data.cpp
e3627dd0f06945c98504085f3faf21b4e27ca6f9
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
txchangecoin-project/txchangecoin
624dfb0d38d3588a9de52fe4fbb6a63f01e9e841
0d9f95db55386cb40ed0326cbeba8ed19a15b075
refs/heads/master
2020-05-17T14:24:51.491958
2019-09-14T11:53:58
2019-09-14T11:53:58
183,763,255
3
3
NOASSERTION
2019-07-10T21:08:28
2019-04-27T11:16:57
C++
UTF-8
C++
false
false
10,568
cpp
// Copyright (c) 2014-2019, The Monero Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <boost/algorithm/string.hpp> #include "common/command_line.h" #include "serialization/crypto.h" #include "cryptonote_core/tx_pool.h" #include "cryptonote_core/cryptonote_core.h" #include "cryptonote_core/blockchain.h" #include "blockchain_db/blockchain_db.h" #include "blockchain_db/db_types.h" #include "version.h" #undef MONERO_DEFAULT_LOG_CATEGORY #define MONERO_DEFAULT_LOG_CATEGORY "bcutil" namespace po = boost::program_options; using namespace epee; using namespace cryptonote; static std::map<uint64_t, uint64_t> load_outputs(const std::string &filename) { std::map<uint64_t, uint64_t> outputs; uint64_t amount = std::numeric_limits<uint64_t>::max(); FILE *f; f = fopen(filename.c_str(), "r"); if (!f) { MERROR("Failed to load outputs from " << filename << ": " << strerror(errno)); return {}; } while (1) { char s[256]; if (!fgets(s, sizeof(s), f)) break; if (feof(f)) break; const size_t len = strlen(s); if (len > 0 && s[len - 1] == '\n') s[len - 1] = 0; if (!s[0]) continue; std::pair<uint64_t, uint64_t> output; uint64_t offset, num_offsets; if (sscanf(s, "@%" PRIu64, &amount) == 1) { continue; } if (amount == std::numeric_limits<uint64_t>::max()) { MERROR("Bad format in " << filename); continue; } if (sscanf(s, "%" PRIu64 "*%" PRIu64, &offset, &num_offsets) == 2 && num_offsets < std::numeric_limits<uint64_t>::max() - offset) { outputs[amount] += num_offsets; } else if (sscanf(s, "%" PRIu64, &offset) == 1) { outputs[amount] += 1; } else { MERROR("Bad format in " << filename); continue; } } fclose(f); return outputs; } int main(int argc, char* argv[]) { TRY_ENTRY(); epee::string_tools::set_module_name_and_folder(argv[0]); std::string default_db_type = "lmdb"; std::string available_dbs = cryptonote::blockchain_db_types(", "); available_dbs = "available: " + available_dbs; uint32_t log_level = 0; tools::on_startup(); po::options_description desc_cmd_only("Command line options"); po::options_description desc_cmd_sett("Command line options and settings options"); const command_line::arg_descriptor<std::string> arg_log_level = {"log-level", "0-4 or categories", ""}; const command_line::arg_descriptor<std::string> arg_database = { "database", available_dbs.c_str(), default_db_type }; const command_line::arg_descriptor<bool> arg_verbose = {"verbose", "Verbose output", false}; const command_line::arg_descriptor<bool> arg_dry_run = {"dry-run", "Do not actually prune", false}; const command_line::arg_descriptor<std::string> arg_input = {"input", "Path to the known spent outputs file"}; command_line::add_arg(desc_cmd_sett, cryptonote::arg_data_dir); command_line::add_arg(desc_cmd_sett, cryptonote::arg_testnet_on); command_line::add_arg(desc_cmd_sett, cryptonote::arg_stagenet_on); command_line::add_arg(desc_cmd_sett, arg_log_level); command_line::add_arg(desc_cmd_sett, arg_database); command_line::add_arg(desc_cmd_sett, arg_verbose); command_line::add_arg(desc_cmd_sett, arg_dry_run); command_line::add_arg(desc_cmd_sett, arg_input); command_line::add_arg(desc_cmd_only, command_line::arg_help); po::options_description desc_options("Allowed options"); desc_options.add(desc_cmd_only).add(desc_cmd_sett); po::variables_map vm; bool r = command_line::handle_error_helper(desc_options, [&]() { auto parser = po::command_line_parser(argc, argv).options(desc_options); po::store(parser.run(), vm); po::notify(vm); return true; }); if (! r) return 1; if (command_line::get_arg(vm, command_line::arg_help)) { std::cout << "Txchangecoin '" << MONERO_RELEASE_NAME << "' (v" << MONERO_VERSION_FULL << ")" << ENDL << ENDL; std::cout << desc_options << std::endl; return 1; } mlog_configure(mlog_get_default_log_path("txchangecoin-blockchain-prune-known-spent-data.log"), true); if (!command_line::is_arg_defaulted(vm, arg_log_level)) mlog_set_log(command_line::get_arg(vm, arg_log_level).c_str()); else mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str()); LOG_PRINT_L0("Starting..."); std::string opt_data_dir = command_line::get_arg(vm, cryptonote::arg_data_dir); bool opt_testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on); bool opt_stagenet = command_line::get_arg(vm, cryptonote::arg_stagenet_on); network_type net_type = opt_testnet ? TESTNET : opt_stagenet ? STAGENET : MAINNET; bool opt_verbose = command_line::get_arg(vm, arg_verbose); bool opt_dry_run = command_line::get_arg(vm, arg_dry_run); std::string db_type = command_line::get_arg(vm, arg_database); if (!cryptonote::blockchain_valid_db_type(db_type)) { std::cerr << "Invalid database type: " << db_type << std::endl; return 1; } const std::string input = command_line::get_arg(vm, arg_input); LOG_PRINT_L0("Initializing source blockchain (BlockchainDB)"); std::unique_ptr<Blockchain> core_storage; tx_memory_pool m_mempool(*core_storage); core_storage.reset(new Blockchain(m_mempool)); BlockchainDB *db = new_db(db_type); if (db == NULL) { LOG_ERROR("Attempted to use non-existent database type: " << db_type); throw std::runtime_error("Attempting to use non-existent database type"); } LOG_PRINT_L0("database: " << db_type); const std::string filename = (boost::filesystem::path(opt_data_dir) / db->get_db_name()).string(); LOG_PRINT_L0("Loading blockchain from folder " << filename << " ..."); try { db->open(filename, 0); } catch (const std::exception& e) { LOG_PRINT_L0("Error opening database: " << e.what()); return 1; } r = core_storage->init(db, net_type); CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize source blockchain storage"); LOG_PRINT_L0("Source blockchain storage initialized OK"); std::map<uint64_t, uint64_t> known_spent_outputs; if (input.empty()) { std::map<uint64_t, std::pair<uint64_t, uint64_t>> outputs; LOG_PRINT_L0("Scanning for known spent data..."); db->for_all_transactions([&](const crypto::hash &txid, const cryptonote::transaction &tx){ const bool miner_tx = tx.vin.size() == 1 && tx.vin[0].type() == typeid(txin_gen); for (const auto &in: tx.vin) { if (in.type() != typeid(txin_to_key)) continue; const auto &txin = boost::get<txin_to_key>(in); if (txin.amount == 0) continue; outputs[txin.amount].second++; } for (const auto &out: tx.vout) { uint64_t amount = out.amount; if (miner_tx && tx.version >= 2) amount = 0; if (amount == 0) continue; if (out.target.type() != typeid(txout_to_key)) continue; outputs[amount].first++; } return true; }, true); for (const auto &i: outputs) { known_spent_outputs[i.first] = i.second.second; } } else { LOG_PRINT_L0("Loading known spent data..."); known_spent_outputs = load_outputs(input); } LOG_PRINT_L0("Pruning known spent data..."); bool stop_requested = false; tools::signal_handler::install([&stop_requested](int type) { stop_requested = true; }); db->batch_start(); size_t num_total_outputs = 0, num_prunable_outputs = 0, num_known_spent_outputs = 0, num_eligible_outputs = 0, num_eligible_known_spent_outputs = 0; for (auto i = known_spent_outputs.begin(); i != known_spent_outputs.end(); ++i) { uint64_t num_outputs = db->get_num_outputs(i->first); num_total_outputs += num_outputs; num_known_spent_outputs += i->second; if (i->first == 0 || is_valid_decomposed_amount(i->first)) { if (opt_verbose) MINFO("Ignoring output value " << i->first << ", with " << num_outputs << " outputs"); continue; } num_eligible_outputs += num_outputs; num_eligible_known_spent_outputs += i->second; if (opt_verbose) MINFO(i->first << ": " << i->second << "/" << num_outputs); if (num_outputs > i->second) continue; if (num_outputs && num_outputs < i->second) { MERROR("More outputs are spent than known for amount " << i->first << ", not touching"); continue; } if (opt_verbose) MINFO("Pruning data for " << num_outputs << " outputs"); if (!opt_dry_run) db->prune_outputs(i->first); num_prunable_outputs += i->second; } db->batch_stop(); MINFO("Total outputs: " << num_total_outputs); MINFO("Known spent outputs: " << num_known_spent_outputs); MINFO("Eligible outputs: " << num_eligible_outputs); MINFO("Eligible known spent outputs: " << num_eligible_known_spent_outputs); MINFO("Prunable outputs: " << num_prunable_outputs); LOG_PRINT_L0("Blockchain known spent data pruned OK"); core_storage->deinit(); return 0; CATCH_ENTRY("Error", 1); }
[ "o.aphunu@gmail.com" ]
o.aphunu@gmail.com
59a9e90f7547337ed4caac0dbcd0ff894a96eb39
8c8ea056e5c38abe04c70c1a89fcd610613777de
/module04/ex01/PlasmaRifle.cpp
be3941b19ece92cc22f5b9d4df012723d8227f86
[]
no_license
1337hunter/cpp_modules
96992f7a000323ffee98fa7ee95bd5ce0686c381
b8cce9989c3092d878654799b390c0ab23d44e6e
refs/heads/master
2023-03-22T09:26:28.061684
2021-03-12T07:11:21
2021-03-12T07:11:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,350
cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* PlasmaRifle.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gbright <gbright@student.21-school.ru> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/09/17 12:30:08 by gbright #+# #+# */ /* Updated: 2020/09/21 23:24:35 by gbright ### ########.fr */ /* */ /* ************************************************************************** */ #include "PlasmaRifle.hpp" PlasmaRifle::PlasmaRifle(void): AWeapon("Plasma Rifle", 5, 21) {} PlasmaRifle &PlasmaRifle::operator=(const PlasmaRifle &obj) { this->name = obj.getName(); this->damage = obj.getDamage(); this->apcost = obj.getAPCost(); return *this; } PlasmaRifle::PlasmaRifle(const PlasmaRifle &obj) { *this = obj; } PlasmaRifle::~PlasmaRifle(void) {} void PlasmaRifle::attack(void) const { std::cout << "* piouuu piouuu piouuu *\n"; }
[ "ant.sergy@gmail.com" ]
ant.sergy@gmail.com
8d064452e60cc5cea2dda385a0aa4074e9513f65
254bf7d275384ed462a49b81e4930e9bd5ab29d7
/P4/HEAP_1/MinHeap.h
e2201ef6d3bb3c2647d16214d4b6b49b4811f064
[ "WTFPL" ]
permissive
leRoderic/ED2018
74dfc20183c17ef152df12f770eb9976a78a8c3a
a1663fc7b1ce8ae29ba5d9c004a0ddcf32d6c2aa
refs/heads/master
2021-06-02T09:07:30.053040
2019-11-07T18:06:20
2019-11-07T18:06:20
123,178,244
1
1
null
null
null
null
UTF-8
C++
false
false
7,104
h
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: MinHeap.h * Author: Tropped * * Created on May 19, 2018, 11:12 AM */ #ifndef MINHEAP_H #define MINHEAP_H #include "Entry.h" #include <vector> #include <stdexcept> using namespace std; template <class Type> class MinHeap { public: MinHeap(); MinHeap(const MinHeap& orig); virtual ~MinHeap(); const int size() const; bool empty() const; void insert(int key, const Type& value); int min() const; const vector<Type> minValues() const; void removeMin(); void printHeap(); const vector<Type> search(int key) const; void inPrint(const int i) const; private: int left(const int parent) const; int right(const int right) const; int parent(const int child) const; bool hasLeft(const int parent) const; bool hasRight(const int parent) const; bool hasParent(const int child) const; //void minValues(const int i, vector<Type>& values) const; void upHeap(const int i); void downHeap(const int i); void swap(const int i, const int j); void search(const int key, const int parent, vector<Type>& values) const; vector<Entry<Type>> heap; }; // ============================================= // CONSTRUCTORS // ============================================ /** * Constructor */ template <class Type> MinHeap<Type>::MinHeap(){ } /** * Constructor copia */ template <class Type> MinHeap<Type>::MinHeap(const MinHeap& orig){ this->heap = orig.heap; } /** * Destructor */ template <class Type> MinHeap<Type>::~MinHeap(){ } // =============================== // CONSULTORES // ============================== /** * Retorna el número de nodos del minHeap * @return */ template <class Type> const int MinHeap<Type>::size() const{ return heap.size(); } /** * Retorna true si está vacío, de lo contrario false * @return */ template <class Type> bool MinHeap<Type>::empty() const{ return heap.empty(); } /** * Retorna la key más pequeña * @return */ template <class Type> int MinHeap<Type>::min() const{ if(empty()) throw out_of_range("El heap está vacío"); return heap[0].key(); } // ================================== // MIN VALUES // ================================== /** * Retorna un vector con los valores con key más pequeña * @return */ template <class Type> const vector<Type> MinHeap<Type>::minValues() const{ if(empty()) throw out_of_range("El heap está vacío"); vector<Type> values; search(min(), 0, values); return values; } // //template <class Type> //void MinHeap<Type>::minValues(int i, vector<Type>& values) const{ // values.push_back(heap[i].value()); // if(heap[left(i)].key() == min()) // minValues(left(i), values); // if(heap[right(i)].key() == min()) // minValues(right(i), values); //} // // =============================== // LEFT RIGHT PARENT // =============================== /** * Retorna el índice del hijo izquierdo */ template <class Type> int MinHeap<Type>::left(const int parent) const{ return parent * 2 + 1; } /** * Retorna el indice del hijo derecho */ template <class Type> int MinHeap<Type>::right(const int parent) const{ return 2 * (parent + 1); } /** * Retorna el indice del padre */ template <class Type> int MinHeap<Type>::parent(const int child) const{ if(child % 2 == 0) return (child - 2)/2; else return (child - 1)/2; } /** * Retorna true si tiene hijo izquierdo */ template <class Type> bool MinHeap<Type>::hasLeft(const int parent) const{ return left(parent) < size(); } /** * Retorna true si tiene hijo derecho */ template <class Type> bool MinHeap<Type>::hasRight(const int parent) const{ return right(parent) < size(); } /** * Retorna true si tiene padre */ template <class Type> bool MinHeap<Type>::hasParent(const int child) const{ return parent(child) >= 0; } // ================================== // INSERT AND REMOVE // ================================== /** * Inserta una entrada en el heap */ template <class Type> void MinHeap<Type>::insert(int key, const Type& value){ heap.push_back(Entry<Type>(key, value)); upHeap(size() - 1); } /** * Reordena el heap para mantener la propiedad de orden */ template <class Type> void MinHeap<Type>::upHeap(const int i){ if(hasParent(i)) if(heap[parent(i)].key() > heap[i].key()){ swap(i, parent(i)); upHeap(parent(i)); } } /** * Elimina el nodo con la clave mas pequeña */ template <class Type> void MinHeap<Type>::removeMin(){ if(empty()) throw out_of_range("El heap está vacío"); int n = size(); heap[0] = heap[n - 1]; heap.pop_back(); downHeap(0); } /** * Reordena el heap para mantener la propiedad de orden * @param parent */ template <class Type> void MinHeap<Type>::downHeap(const int parent){ int child; if(hasLeft(parent)) child = left(parent); if(hasRight(parent)){ if(heap[right(parent)].key() < heap[left(parent)].key()) child = right(parent); } if(heap[child].key() < heap[parent].key()){ swap(parent, child); downHeap(child); } } /** * Intercambia la llave y el valor de los nodos i y j */ template <class Type> void MinHeap<Type>::swap(const int i, const int j){ Entry<Type> aux = heap[i]; heap[i] = heap[j]; heap[j] = aux; } // ========================== // PRINT // =========================== /** * Imprime el heap */ template <class Type> void MinHeap<Type>::printHeap(){ if(empty()) throw out_of_range("El heap está vacío"); cout << "Heap: " << endl; for(auto it=heap.begin(); it!=heap.end(); it++){ cout << (*it).value() << ", "; } cout << endl; } // ========================= // SEARCH // =========================== /** * Retorna un vector con los valores con una clave determinada */ template <class Type> const vector<Type> MinHeap<Type>::search(int key) const{ if(empty()) throw out_of_range("El heap está vacío"); vector<Type> values; search(key, 0, values); return values; } /** * Retorna un vector con los valores con una clave determinada */ template <class Type> void MinHeap<Type>::search(const int key, const int parent, vector<Type>& values) const{ if(heap[parent].key() == key) values.push_back(heap[parent].value()); if(hasLeft(parent) && heap[left(parent)].key() <= key) search(key, left(parent), values); if(hasRight(parent) && heap[right(parent)].key() <= key) search(key, right(parent), values); } #endif /* MINHEAP_H */
[ "rcmikado@gmail.com" ]
rcmikado@gmail.com
466623722bb16f3469694bcb446470bb5eda07cf
23092a0b775419403d3bfd7eb6e9d2baa84e34a6
/test/move_eval_test.cc
77874246a4071140017ed752a6c5557e398ffdd4
[]
no_license
felixguendling/chessbot
709f15f9ac7093260c709620fbd0dd1fef185ee3
a65d0fff1723deae2cd001491c7f8a9eae04eee2
refs/heads/master
2023-05-10T13:22:53.655589
2021-06-21T15:15:47
2021-06-21T15:15:47
336,854,945
1
0
null
null
null
null
UTF-8
C++
false
false
1,237
cc
#include "chessbot/stockfish_evals.h" #include "doctest/doctest.h" using namespace chessbot; TEST_CASE("move eval comparison") { SUBCASE("mate vs cp") { auto const e1 = move_eval{.mate_ = -2, .cp_ = 0}; auto const e2 = move_eval{.mate_ = 0, .cp_ = 100}; CHECK(e1 < e2); } SUBCASE("mate vs mate negative") { auto const e1 = move_eval{.mate_ = -2, .cp_ = 0}; auto const e2 = move_eval{.mate_ = -3, .cp_ = 0}; CHECK(!(e1 < e2)); CHECK(e2 < e1); } SUBCASE("mate vs mate positive") { auto const e1 = move_eval{.mate_ = 2, .cp_ = 0}; auto const e2 = move_eval{.mate_ = 3, .cp_ = 0}; CHECK(!(e1 < e2)); CHECK(e2 < e1); } SUBCASE("cp vs cp") { auto const e1 = move_eval{.mate_ = 0, .cp_ = 100}; auto const e2 = move_eval{.mate_ = 0, .cp_ = 50}; CHECK(!(e1 < e2)); CHECK(e2 < e1); } SUBCASE("cp vs cp") { auto const e1 = move_eval{.mate_ = 0, .cp_ = 50}; auto const e2 = move_eval{.mate_ = 0, .cp_ = 0}; CHECK(!(e1 < e2)); CHECK(e2 < e1); } SUBCASE("mate vs mate pos vs neg") { auto const e1 = move_eval{.mate_ = 5, .cp_ = 0}; auto const e2 = move_eval{.mate_ = -5, .cp_ = 0}; CHECK(!(e1 < e2)); CHECK(e2 < e1); } }
[ "felix.guendling@gmail.com" ]
felix.guendling@gmail.com
3ce47cbca3779ce640262c5b401decb196e97a2d
dd2bcd6e829347eef6ab8020bd8e31a18c335acc
/ThisIsASoftRenderer/Editor/XTP/Source/ReportControl/XTPReportBehavior.h
3bb76e0c762b8482af0fd3363b46e86d2d8dc915
[]
no_license
lai3d/ThisIsASoftRenderer
4dab4cac0e0ee82ac4f7f796aeafae40a4cb478a
a8d65af36f11a079e754c739a37803484df05311
refs/heads/master
2021-01-22T17:14:03.064181
2014-03-24T16:02:16
2014-03-24T16:02:16
56,359,042
1
0
null
2016-04-16T01:19:22
2016-04-16T01:19:20
null
UTF-8
C++
false
false
5,201
h
// XTPReportBehavior.h: Declaration of the CXTPReportBehavior class. // // This file is a part of the XTREME REPORTCONTROL MFC class library. // (c)1998-2011 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // support@codejock.com // http://www.codejock.com // ///////////////////////////////////////////////////////////////////////////// #if !defined(__XTPREPORTBEHAVIOR_H__) #define __XTPREPORTBEHAVIOR_H__ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 enum XTPReportMouseButton { xtpReportMouseButtonNone, xtpReportMouseButtonLeft, xtpReportMouseButtonMiddle, xtpReportMouseButtonRight }; enum XTPReportMouseEvent { xtpReportMouseEventButtonDown, xtpReportMouseEventButtonUp }; enum XTPReportBehavior { xtpReportBehaviorOutlook2003 = 0x00001100, // 11.0 xtpReportBehaviorOutlook2007 = 0x00001200, // 12.0 xtpReportBehaviorOutlook2010 = 0x00001400, // 14.0 xtpReportBehaviorExcel2003 = 0x10001100, // 11.0 xtpReportBehaviorExcel2007 = 0x10001200, // 12.0 xtpReportBehaviorExcel2010 = 0x10001400, // 14.0 //xtpReportBehaviorCodejock1300 = 0x20001300, // 13.0.0 //xtpReportBehaviorCodejock1321 = 0x20001321, // 13.2.1 //xtpReportBehaviorCodejock1330 = 0x20001330, // 13.3.0 //xtpReportBehaviorCodejock1331 = 0x20001331, // 13.3.1 xtpReportBehaviorCodejock1340 = 0x20001340, // 13.4.0 xtpReportBehaviorCodejock1341 = 0x20001341, // 13.4.1 xtpReportBehaviorCodejock1342 = 0x20001342, // 13.4.2 xtpReportBehaviorCodejock1501 = 0x20001501, // 15.0.1 xtpReportBehaviorCodejock1502 = 0x20001502, // 15.0.2 xtpReportBehaviorCodejockDefault = 0x20000000 }; ///////////////////////////////////////////////////////////////////////////// // Key events ///////////////////////////////////////////////////////////////////////////// class _XTP_EXT_CLASS CXTPReportBehaviorRowKeyDown { }; class _XTP_EXT_CLASS CXTPReportBehaviorRowKeyUp { }; ///////////////////////////////////////////////////////////////////////////// // Mouse events ///////////////////////////////////////////////////////////////////////////// class _XTP_EXT_CLASS CXTPReportBehaviorRowModifier : public CXTPCmdTarget { public: CXTPReportBehaviorRowModifier(); void Reset(); BOOL bFocusRow; // TRUE if the row gets the focus BOOL bFocusRowTemporarily; // TRUE if the row gets the focus temporarily BOOL bSelectRow; // TRUE if the row gets selected BOOL bSelectRowTemporarily; // TRUE if the row gets selected temporarily BOOL bMultipleSelection; // TRUE to enable multiple selection BOOL bKeepSelection; // TRUE if multiple rows stay selected BOOL bKeepFocus; // protected: }; class _XTP_EXT_CLASS CXTPReportBehaviorRowMouseButton : public CXTPCmdTarget { public: CXTPReportBehaviorRowMouseButton( XTPReportMouseButton button, XTPReportMouseEvent event ); virtual ~CXTPReportBehaviorRowMouseButton(); void Reset(); public: CXTPReportBehaviorRowModifier *None; CXTPReportBehaviorRowModifier *Control; CXTPReportBehaviorRowModifier *Shift; BOOL bFocusColumn; // TRUE if the column gets the focus BOOL bEnsureVisible; // TRUE if the row gets visible BOOL bClick; // TRUE BOOL bContextMenu; // TRUE if OnContextMenu / NM_RCLICK gets called. BOOL bCheckSelectedRows; // TRUE BOOL bDragBegin; // TRUE to begin drag BOOL bDragEnd; // TRUE to end drag BOOL bDragSelectGroup; // TRUE to select the entire group on drag public: const XTPReportMouseButton m_button; const XTPReportMouseEvent m_event; protected: }; class _XTP_EXT_CLASS CXTPReportBehaviorRowMouse : public CXTPCmdTarget { public: CXTPReportBehaviorRowMouse(XTPReportMouseEvent event); virtual ~CXTPReportBehaviorRowMouse(); CXTPReportBehaviorRowMouseButton *Left; CXTPReportBehaviorRowMouseButton *Right; protected: }; class _XTP_EXT_CLASS CXTPReportBehaviorRow : public CXTPCmdTarget { public: CXTPReportBehaviorRow(); virtual ~CXTPReportBehaviorRow(); public: CXTPReportBehaviorRowMouse *MouseDown; CXTPReportBehaviorRowMouse *MouseUp; }; class _XTP_EXT_CLASS CXTPReportBehavior : public CXTPCmdTarget { public: CXTPReportBehavior(XTPReportBehavior behavior); virtual ~CXTPReportBehavior(); void SetScheme(XTPReportBehavior behavior); public: CXTPReportBehaviorRow *Row; CXTPReportBehaviorRow *GroupRow; private: void SetSchemeOutlook(); void SetSchemeExcel(); void SetSchemeCodejock134x(); void SetSchemeCodejock1501(); void SetSchemeCodejock1502(); void SetSchemeCodejockDefault(); XTPReportBehavior m_scheme; // The last set scheme }; #endif //#if !defined(__XTPREPORTBEHAVIOR_H__)
[ "54639976@qq.com" ]
54639976@qq.com
d3ef052b3c731122e7124a18700d02dd91337aca
ac1c4815ab47858919140edbf193f24ae4fb3118
/src/rosserial/rosserial_server/include/rosserial_server/serial_session.h
5ca707586560fd2de8dc243f0351889f0d93d844
[]
no_license
DavidHan008/Autonomous-RC-Car
c13e3816efc4a8d8112f9b71e44d4cb15a465fa3
443dadc48c8bbbe30811fa18b110deffa2daf998
refs/heads/master
2021-01-23T14:13:57.875181
2017-04-12T17:59:33
2017-04-12T17:59:33
102,679,239
1
0
null
2017-09-07T02:04:39
2017-09-07T02:04:39
null
UTF-8
C++
false
false
3,989
h
/** * * \file * \brief Single, reconnecting class for a serial rosserial session. * \author Mike Purvis <mpurvis@clearpathrobotics.com> * \copyright Copyright (c) 2013, Clearpath Robotics, Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Clearpath Robotics, Inc. nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CLEARPATH ROBOTICS, INC. BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Please send comments, questions, or patches to code@clearpathrobotics.com * */ #ifndef ROSSERIAL_SERVER_SERIAL_SESSION_H #define ROSSERIAL_SERVER_SERIAL_SESSION_H #include <iostream> #include <boost/bind.hpp> #include <boost/asio.hpp> #include <ros/ros.h> #include "rosserial_server/session.h" namespace rosserial_server { class SerialSession : public Session<boost::asio::serial_port> { public: SerialSession(boost::asio::io_service& io_service, std::string port, int baud) : Session(io_service), port_(port), baud_(baud), timer_(io_service) { ROS_INFO_STREAM("rosserial_server session configured for " << port_ << " at " << baud << "bps."); failed_connection_attempts_ = 0; check_connection(); } private: void check_connection() { if (!is_active()) { attempt_connection(); } // Every second, check again if the connection should be reinitialized, // if the ROS node is still up. if (ros::ok()) { timer_.expires_from_now(boost::posix_time::milliseconds(1000)); timer_.async_wait(boost::bind(&SerialSession::check_connection, this)); } } void attempt_connection() { ROS_DEBUG("Opening serial port."); boost::system::error_code ec; socket().open(port_, ec); if (ec) { failed_connection_attempts_++; if (failed_connection_attempts_ == 1) { ROS_ERROR_STREAM("Unable to open port " << port_ << ": " << ec); } else { ROS_DEBUG_STREAM("Unable to open port " << port_ << " (" << failed_connection_attempts_ << "): " << ec); } return; } ROS_INFO_STREAM("Opened " << port_); failed_connection_attempts_ = 0; typedef boost::asio::serial_port_base serial; socket().set_option(serial::baud_rate(baud_)); socket().set_option(serial::character_size(8)); socket().set_option(serial::stop_bits(serial::stop_bits::one)); socket().set_option(serial::parity(serial::parity::none)); socket().set_option(serial::flow_control(serial::flow_control::none)); // Kick off the session. start(); } std::string port_; int baud_; boost::asio::deadline_timer timer_; int failed_connection_attempts_; }; } // namespace #endif // ROSSERIAL_SERVER_SERIAL_SESSION_H
[ "muthiyanbhushan@gmail.com" ]
muthiyanbhushan@gmail.com
b1ad91dda21a2d68c22351dcb8c54de9d7988a5c
07074962be026c67519a0ccfb3d48bd95ede38ed
/DbData/dbusers.h
3453f5a0629f4623625acab0e5708f32308d5020
[]
no_license
End1-1/Cafe5
2fa65c62f395c186e2204f3fb941a2f93fd3a653
ba2b695c627cf59260a3ac1134927198c004fe53
refs/heads/master
2023-08-17T02:39:29.224396
2023-08-14T06:37:55
2023-08-14T06:37:55
151,380,276
2
1
null
null
null
null
UTF-8
C++
false
false
201
h
#ifndef DBUSERS_H #define DBUSERS_H #include "dbdata.h" class DbUsers : public DbData { public: DbUsers(); QString fullName(int id); QString fullShort(int id); }; #endif // DBUSERS_H
[ "end1_1@yahoo.com" ]
end1_1@yahoo.com
b039eaa3680630d7067f92ccd3e092cc721a06fa
ba86ba2b42cd85e8faca5d323f499005e7340f2b
/include/goofit/Registry.hpp
b09050ea4dbf38ea354443c1af08720e9b269dec
[]
no_license
henryiii/GooFitX
db3c0a9440ce62e1e3d03ac0c4aa40c895d48a12
ac28739f0f17a1529afe5a6faf32c7bce3a3bf5a
refs/heads/master
2021-03-27T10:08:11.113420
2018-05-16T14:40:06
2018-05-16T14:40:06
103,797,489
0
0
null
null
null
null
UTF-8
C++
false
false
949
hpp
#pragma once #include "RegistryNoInl.hpp" #include "PDFs/PDF.hpp" #include "Variable.hpp" namespace GooFit { namespace experimental { inline Registry::Registry(PDF* source) : source(source), values(std::make_shared<std::vector<fptype>>(source->size())) {} inline void Registry::calculate() { if(source != nullptr) source->calculate(); } inline std::set<Variable> Registry::get_variables_recursive() { if(source != nullptr) return source->get_variables_recursive(); else return {}; } inline std::set<PDF*> Registry::get_pdfs_recursive() { if(source != nullptr) { std::set<PDF*> values = source->get_pdfs_recursive(); values.insert(source); return values; } else return {}; } inline void Registry::set_changed_recursive(bool value) { std::set<Variable> vars = get_variables_recursive(); for(Variable x : vars) x.set_changed(value); } } }
[ "henry.fredrick.schreiner@cern.ch" ]
henry.fredrick.schreiner@cern.ch
dbd009c1f6828caac6276e6a7d7ad05e69444d52
9ee1a4445e7efc786d0206959f6c97f8caa66154
/LOJ-1149.cpp
b51bd35d13166621505a504e93d9356c4df9f8ce
[]
no_license
Jackal1586/LightOJ
d6877adf4af82e32f96aa869b63bb8699259d3b7
6c008e8fe1c02f3d97171324ba4eca3e94d24133
refs/heads/master
2021-01-12T00:49:19.482962
2017-01-28T16:09:53
2017-01-28T16:09:53
80,295,122
2
2
null
null
null
null
UTF-8
C++
false
false
1,866
cpp
#include<bits/stdc++.h> using namespace std; vector<int>g[250]; int cap[250][250],source=230,sink=231,pr[250]; inline int cn(int a) { return (a+102); } bool bfs(){ memset(pr,-1,sizeof(pr)); pr[source]=-2; queue<int>q; q.push(source); while(!q.empty()){ int src=q.front(); q.pop(); for(int i=0;i<g[src].size();i++){ if(pr[g[src][i]]==-1 && cap[src][g[src][i]]>0){ pr[g[src][i]]=src; if(g[src][i]==sink)return 1; q.push(g[src][i]); } } } return 0; } int main() { int t; scanf("%d",&t); for(int z=1; z<=t; z++) { for(int i=0; i<250; i++)g[i].clear(); memset(cap,0,sizeof(cap)); int n,m; scanf("%d",&n); int a[n]; for(int i=0; i<n; i++)scanf("%d",&a[i]); scanf("%d",&m); int b[m]; for(int i=0; i<m; i++)scanf("%d",&b[i]); bool f=1; for(int i=0; i<n; i++) { g[source].push_back(i); g[i].push_back(source); cap[source][i]=1; for(int j=0; j<m; j++) { if(f) { g[cn(j)].push_back(sink); g[sink].push_back(cn(j)); cap[cn(j)][sink]=1; } if(b[j]%a[i]==0) { //cout<<"OK "<<i<<" "<<j<<"\n"; g[i].push_back(cn(j)); g[cn(j)].push_back(i); cap[i][cn(j)]=1; } } f=0; } int ans=0; while(bfs()){ ans++; int y=sink; while(pr[y]!=-2){ cap[pr[y]][y]--; cap[y][pr[y]]++; y=pr[y]; } } cout<<"Case "<<z<<": "<<ans<<"\n"; } return 0; }
[ "Zarzis Khan" ]
Zarzis Khan
eb4066ada86e28ab717bb4920a80fd90874cab11
a06a9ae73af6690fabb1f7ec99298018dd549bb7
/_Library/_Include/boost/graph/exterior_property.hpp
27d4ceb4694506af0b15e91502856e691657d432
[]
no_license
longstl/mus12
f76de65cca55e675392eac162dcc961531980f9f
9e1be111f505ac23695f7675fb9cefbd6fa876e9
refs/heads/master
2021-05-18T08:20:40.821655
2020-03-29T17:38:13
2020-03-29T17:38:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,656
hpp
//////////////////////////////////////////////////////////////////////////////// // exterior_property.hpp // (C) Copyright 2007-2009 Andrew Sutton // // Use, modification and distribution are subject to the // Boost Software License, Version 1.0 (See accompanying file // LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GRAPH_EXTERIOR_PROPERTY_HPP #define BOOST_GRAPH_EXTERIOR_PROPERTY_HPP #include <vector> #include <boost/graph/property_maps/container_property_map.hpp> #include <boost/graph/property_maps/matrix_property_map.hpp> namespace boost { namespace detail { // The vector matrix provides a little abstraction over vector // types that makes matrices easier to work with. Note that it's // non-copyable, meaning you should be passing it by value. template <typename Value> struct vector_matrix { typedef std::vector<Value> container_type; typedef std::vector<container_type> matrix_type; typedef container_type value_type; typedef container_type& reference; typedef const container_type const_reference; typedef container_type* pointer; typedef typename matrix_type::size_type size_type; // Instantiate the matrix over n elements (creates an nxn matrix). // The graph has to be passed in order to ensure the index maps // are constructed correctly when returning indexible elements. inline vector_matrix(size_type n) : m_matrix(n, container_type(n)) { } inline reference operator [](size_type n) { return m_matrix[n]; } inline const_reference operator [](size_type n) const { return m_matrix[n]; } matrix_type m_matrix; }; } /* namespace detail */ /** * The exterior_property metafunction defines an appropriate set of types for * creating an exterior property. An exterior property is comprised of a both * a container and a property map that acts as its abstraction. An extension * of this metafunction will select an appropriate "matrix" property that * records values for pairs of vertices. * * @todo This does not currently support the ability to define exterior * properties for graph types that do not model the IndexGraph concepts. A * solution should not be especially difficult, but will require an extension * of type traits to affect the type selection. */ template <typename Graph, typename Key, typename Value> struct exterior_property { typedef Key key_type; typedef Value value_type; typedef std::vector<Value> container_type; typedef container_property_map<Graph, Key, container_type> map_type; typedef detail::vector_matrix<Value> matrix_type; typedef matrix_property_map<Graph, Key, matrix_type> matrix_map_type; private: exterior_property() { } exterior_property(const exterior_property&) { } }; /** * Define a the container and property map types requried to create an exterior * vertex property for the given value type. The Graph parameter is required to * model the VertexIndexGraph concept. */ template <typename Graph, typename Value> struct exterior_vertex_property { typedef exterior_property< Graph, typename graph_traits<Graph>::vertex_descriptor, Value > property_type; typedef typename property_type::key_type key_type; typedef typename property_type::value_type value_type; typedef typename property_type::container_type container_type; typedef typename property_type::map_type map_type; typedef typename property_type::matrix_type matrix_type; typedef typename property_type::matrix_map_type matrix_map_type; }; /** * Define a the container and property map types requried to create an exterior * edge property for the given value type. The Graph parameter is required to * model the EdgeIndexGraph concept. */ template <typename Graph, typename Value> struct exterior_edge_property { typedef exterior_property< Graph, typename graph_traits<Graph>::edge_descriptor, Value > property_type; typedef typename property_type::key_type key_type; typedef typename property_type::value_type value_type; typedef typename property_type::container_type container_type; typedef typename property_type::map_type map_type; typedef typename property_type::matrix_type matrix_type; typedef typename property_type::matrix_map_type matrix_map_type; }; } /* namespace boost */ #endif ///////////////////////////////////////////////// // vnDev.Games - Trong.LIVE - DAO VAN TRONG // ////////////////////////////////////////////////////////////////////////////////
[ "adm.fael.hs@gmail.com" ]
adm.fael.hs@gmail.com
6ed3d92c313083028334fce6ca745c8c731c6d8f
4b98867fa02f72c3c7c76f2f54c18d0dd03ff59a
/Deck.h
741970417b54164666ec91b977b0769d69a60627
[]
no_license
TylerMayxonesing/Uno
45c1dc626cce1eb32b4e752e33b11b2e69e592cb
f96916b2e9a56680bd88d00b2058c72fe5dc1cf1
refs/heads/master
2022-03-07T23:06:07.787045
2019-11-05T00:58:04
2019-11-05T00:58:04
219,626,398
0
0
null
null
null
null
UTF-8
C++
false
false
180
h
// // Created by T Alpha 1 on 11/2/2019. // #ifndef UNO__DECK_H_ #define UNO__DECK_H_ #include "Card.h" class Deck{ private: //std::vector <Card*> ; }; #endif //UNO__DECK_H_
[ "theofficial.vibe.studios@gmail.com" ]
theofficial.vibe.studios@gmail.com
ffffb0f37073f119f76cf26e44998da502b8fcfe
1d928c3f90d4a0a9a3919a804597aa0a4aab19a3
/c++/libtorrent/2016/12/random.cpp
cd4cc28e3d763803461947e143b2501b609bed3f
[]
no_license
rosoareslv/SED99
d8b2ff5811e7f0ffc59be066a5a0349a92cbb845
a062c118f12b93172e31e8ca115ce3f871b64461
refs/heads/main
2023-02-22T21:59:02.703005
2021-01-28T19:40:51
2021-01-28T19:40:51
306,497,459
1
1
null
2020-11-24T20:56:18
2020-10-23T01:18:07
null
UTF-8
C++
false
false
3,824
cpp
/* Copyright (c) 2011-2016, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/config.hpp" #include "libtorrent/random.hpp" #include "libtorrent/error_code.hpp" #include "libtorrent/aux_/openssl.hpp" #include "libtorrent/aux_/disable_warnings_push.hpp" #if TORRENT_USE_CRYPTOAPI #include <windows.h> #include <wincrypt.h> #elif defined TORRENT_USE_LIBCRYPTO extern "C" { #include <openssl/rand.h> #include <openssl/err.h> } #endif #include "libtorrent/aux_/disable_warnings_pop.hpp" #if TORRENT_USE_CRYPTOAPI namespace { HCRYPTPROV make_crypt_provider() { using namespace libtorrent; HCRYPTPROV ret; if (CryptAcquireContext(&ret, nullptr, nullptr, PROV_RSA_FULL , CRYPT_VERIFYCONTEXT) == false) { #ifndef BOOST_NO_EXCEPTIONS throw system_error(error_code(GetLastError(), system_category())); #else std::terminate(); #endif } return ret; } HCRYPTPROV get_crypt_provider() { static HCRYPTPROV prov = make_crypt_provider(); return prov; } } #endif namespace libtorrent { namespace aux { std::mt19937& random_engine() { #ifdef TORRENT_BUILD_SIMULATOR // make sure random numbers are deterministic. Seed with a fixed number static std::mt19937 rng(0x82daf973); #else static std::random_device dev; static std::mt19937 rng(dev()); #endif return rng; } void random_bytes(span<char> buffer) { #if TORRENT_USE_CRYPTOAPI if (!CryptGenRandom(get_crypt_provider(), int(buffer.size()) , reinterpret_cast<BYTE*>(buffer.data()))) { #ifndef BOOST_NO_EXCEPTIONS throw system_error(error_code(GetLastError(), system_category())); #else std::terminate(); #endif } #elif defined TORRENT_USE_LIBCRYPTO #ifdef TORRENT_MACOS_DEPRECATED_LIBCRYPTO #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" #endif int r = RAND_bytes(reinterpret_cast<unsigned char*>(buffer.data()) , int(buffer.size())); if (r != 1) { #ifndef BOOST_NO_EXCEPTIONS throw system_error(error_code(int(::ERR_get_error()), system_category())); #else std::terminate(); #endif } #ifdef TORRENT_MACOS_DEPRECATED_LIBCRYPTO #pragma clang diagnostic pop #endif #else for (auto& b : buffer) b = char(random(0xff)); #endif } } std::uint32_t random(std::uint32_t max) { return std::uniform_int_distribution<std::uint32_t>(0, max)(aux::random_engine()); } }
[ "rodrigosoaresilva@gmail.com" ]
rodrigosoaresilva@gmail.com
0bde9607e6bff2a9a6fb086e8c868dc06af65dc7
2e60fb76c3fa2f208babe7f18a95e3b01e5ce631
/GameConsole.h
92550892d749f9b9161011e7f25fce32124a1bde
[]
no_license
Ddimk/battleships
56492866871dbc0b6c9283af3df85fb9253f3f78
ab2d289ee202c52fcf8822e000a290ca2d35f306
refs/heads/main
2023-05-25T05:49:44.105125
2021-06-09T16:07:40
2021-06-09T16:07:40
359,141,457
0
0
null
null
null
null
UTF-8
C++
false
false
256
h
#pragma once #include "Player.h" class GameConsole : public Player { public: void on_win(); void on_loose(); void start_place_ships(ship_def ships[10]); void on_step(const bf_tile my[20][20], const bf_tile enemy[20][20], pos2d *result); };
[ "ddimysek@yandex.ru" ]
ddimysek@yandex.ru
a2d4bc1debbce7b7f7290859d9b85f4c434d6a3f
cff366a360ad7d0e17ad0ab13831fa7203ed1b2d
/.fail/challenge_encoder/main.cpp
4330228414e85df5775e97d74cd763289bd08210
[]
no_license
tcstrength/projects
c2bf6c4dfc5023483eff939a9860bf3f66833205
995fae7d94e8e2ec3e3cf40d04d43121f3cbaa02
refs/heads/master
2021-10-25T11:43:03.781429
2019-04-03T23:39:10
2019-04-03T23:39:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
571
cpp
#include <iostream> std::string encode(std::string str) { std::string buf; int len = str.length(); buf.push_back(len + 42); for (int i = 0; i < len; ++i) buf.push_back(str[len - i - 1] + i + 1); return buf; } std::string decode(std::string str) { std::string buf; int len = str[0] - 42; for (int i = 0; i < len; ++i) buf.push_back(str[len - i] - len + i); return buf; } int main() { std::cout << encode("159487asd") << std::endl; //std::cout << decode(encode("159487asd")) << std::endl; return 0; }
[ "thai.cuong1404@gmail.com" ]
thai.cuong1404@gmail.com
516e2c2f793551b8201283c8651e0f98923b1631
de7e771699065ec21a340ada1060a3cf0bec3091
/spatial3d/src/java/org/apache/lucene/spatial3d/geom/GeoDegenerateVerticalLine.h
18c4f600e92030c61d944b2d2584245b0ffc2a0f
[]
no_license
sraihan73/Lucene-
0d7290bacba05c33b8d5762e0a2a30c1ec8cf110
1fe2b48428dcbd1feb3e10202ec991a5ca0d54f3
refs/heads/master
2020-03-31T07:23:46.505891
2018-12-08T14:57:54
2018-12-08T14:57:54
152,020,180
7
0
null
null
null
null
UTF-8
C++
false
false
4,794
h
#pragma once #include "stringhelper.h" #define _USE_MATH_DEFINES #include <any> #include <cmath> #include <memory> #include <stdexcept> #include <string> #include <deque> // C++ NOTE: Forward class declarations: #include "core/src/java/org/apache/lucene/spatial3d/geom/GeoPoint.h" #include "core/src/java/org/apache/lucene/spatial3d/geom/SidedPlane.h" #include "core/src/java/org/apache/lucene/spatial3d/geom/Plane.h" #include "core/src/java/org/apache/lucene/spatial3d/geom/PlanetModel.h" #include "core/src/java/org/apache/lucene/spatial3d/geom/GeoBBox.h" #include "core/src/java/org/apache/lucene/spatial3d/geom/Membership.h" #include "core/src/java/org/apache/lucene/spatial3d/geom/GeoShape.h" #include "core/src/java/org/apache/lucene/spatial3d/geom/Bounds.h" #include "core/src/java/org/apache/lucene/spatial3d/geom/DistanceStyle.h" /* * Licensed to the Syed Mamun Raihan (sraihan.com) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * sraihan.com licenses this file to You under GPLv3 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 * * https://www.gnu.org/licenses/gpl-3.0.en.html * * 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. */ namespace org::apache::lucene::spatial3d::geom { /** * Degenerate bounding box limited on two sides (top lat, bottom lat). * * @lucene.internal */ class GeoDegenerateVerticalLine : public GeoBaseBBox { GET_CLASS_NAME(GeoDegenerateVerticalLine) /** Top latitude of the vertical line */ protected: const double topLat; /** Bottom latitude of the vertical line */ const double bottomLat; /** Longitude of the vertical line */ const double longitude; /** Point at the upper end of the vertical line */ const std::shared_ptr<GeoPoint> UHC; /** Point at the lower end of the vertical line */ const std::shared_ptr<GeoPoint> LHC; /** Top end cutoff plane */ const std::shared_ptr<SidedPlane> topPlane; /** Bottom end cutoff plane */ const std::shared_ptr<SidedPlane> bottomPlane; /** Back-side cutoff plane */ const std::shared_ptr<SidedPlane> boundingPlane; /** The vertical line plane */ const std::shared_ptr<Plane> plane; /** Notable points for the line (end points) */ std::deque<std::shared_ptr<GeoPoint>> const planePoints; /** A computed center point for the line */ const std::shared_ptr<GeoPoint> centerPoint; /** A point that's on the line */ std::deque<std::shared_ptr<GeoPoint>> const edgePoints; /** * Accepts only values in the following ranges: lat: {@code -PI/2 -> PI/2}, * longitude: {@code -PI -> PI} */ public: GeoDegenerateVerticalLine(std::shared_ptr<PlanetModel> planetModel, double const topLat, double const bottomLat, double const longitude); /** * Constructor for deserialization. * @param planetModel is the planet model. * @param inputStream is the input stream. */ GeoDegenerateVerticalLine( std::shared_ptr<PlanetModel> planetModel, std::shared_ptr<InputStream> inputStream) ; void write(std::shared_ptr<OutputStream> outputStream) override; std::shared_ptr<GeoBBox> expand(double const angle) override; bool isWithin(double const x, double const y, double const z) override; double getRadius() override; std::shared_ptr<GeoPoint> getCenter() override; std::deque<std::shared_ptr<GeoPoint>> getEdgePoints() override; bool intersects(std::shared_ptr<Plane> p, std::deque<std::shared_ptr<GeoPoint>> &notablePoints, std::deque<Membership> &bounds) override; bool intersects(std::shared_ptr<GeoShape> geoShape) override; void getBounds(std::shared_ptr<Bounds> bounds) override; int getRelationship(std::shared_ptr<GeoShape> path) override; protected: double outsideDistance(std::shared_ptr<DistanceStyle> distanceStyle, double const x, double const y, double const z) override; public: virtual bool equals(std::any o); virtual int hashCode(); virtual std::wstring toString(); protected: std::shared_ptr<GeoDegenerateVerticalLine> shared_from_this() { return std::static_pointer_cast<GeoDegenerateVerticalLine>( GeoBaseBBox::shared_from_this()); } }; } // #include "core/src/java/org/apache/lucene/spatial3d/geom/
[ "smamunr@fedora.localdomain" ]
smamunr@fedora.localdomain
fdeb2787dc7688cb88e92c8d49a72814da1c6068
e9e6ce520a2abae5e13363b47fbd6e9ebfc6c73f
/simulations/robocop_racetrack/src/robocop_racetrack_node.cpp
cafdaed58705e3762ecea92ec7462b4800938188
[]
no_license
Lizzylizard/ReinforcementLearningByElisabeth
755b5fff13f06f3f452e12a7eb6b48722e3bf3c2
10d612d454864028462e85d5349d4440833a3797
refs/heads/main
2022-12-29T07:52:47.828097
2020-10-16T13:04:07
2020-10-16T13:04:07
304,057,676
0
0
null
null
null
null
UTF-8
C++
false
false
221
cpp
#include <ros/ros.h> #include <robocop_racetrack/RobocopRacetrack.hpp> int main(int argc, char **argv) { ros::init(argc, argv, "robocop_racetrack"); ros::NodeHandle nh("~"); RobocopRacetrack robocopRacetrack(nh); }
[ "elisabeth.milde@informatik.hs-fulda.de" ]
elisabeth.milde@informatik.hs-fulda.de
a8ade01db9e308d7c263f3097ba3e4984dd96ad9
4883f47cbce6b5930df81948c38c6a3668109d4a
/SDL/sudoku/test/test_set_permutation.cpp
fc6fe3b82a2421f0b7a4c9bd78cbbae8e0561955
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
hildeth/free
247eb80bb1517b539e133aea3ea0319ddab4c81a
97f21b2e2088849119e129c0a5d58da70a18f1f0
refs/heads/master
2023-07-07T19:29:15.161888
2023-06-28T23:54:38
2023-06-28T23:54:38
23,742,544
0
0
null
null
null
null
UTF-8
C++
false
false
173
cpp
#include "Set.h" int main() { for (Set bit_perm = Set::perm_begin(3); bit_perm.perm_more(); bit_perm.perm_next()) std::cout << bit_perm << std::endl; return 0; }
[ "t.hilebrandt@comcast.net" ]
t.hilebrandt@comcast.net
7fe12539cb1dbf4b21dd18004e24f00ac7875f69
3f4cebcffe9d5beb7d288600ceed2b8448f6afea
/packages/CefSharp.Common.63.0.3/src/CefSharp.BrowserSubprocess.Core/JavascriptPropertyWrapper.cpp
3233f390ed6665f44d752636445536c20789852e
[ "MIT" ]
permissive
kevinlau2015/CEFSharp.wpf.H.264
7276cbd2bb21533bbed44ed0c536ccd67ac34ca6
dc05d6960f644b331be56dedeb081c02395b55fe
refs/heads/master
2022-09-15T00:44:28.479862
2020-06-04T01:11:44
2020-06-04T01:11:44
269,229,294
0
0
MIT
2020-06-04T01:10:04
2020-06-04T01:10:04
null
UTF-8
C++
false
false
1,247
cpp
// Copyright © 2010-2017 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #pragma once #include "Stdafx.h" #include "JavascriptPropertyWrapper.h" #include "JavascriptObjectWrapper.h" using namespace System; namespace CefSharp { void JavascriptPropertyWrapper::Bind(JavascriptProperty^ javascriptProperty, const CefRefPtr<CefV8Value>& v8Value, JavascriptCallbackRegistry^ callbackRegistry) { auto propertyName = StringUtils::ToNative(javascriptProperty->JavascriptName); auto clrPropertyName = javascriptProperty->JavascriptName; if (javascriptProperty->IsComplexType) { auto javascriptObjectWrapper = gcnew JavascriptObjectWrapper(_browserProcess); javascriptObjectWrapper->Bind(javascriptProperty->JsObject, v8Value, callbackRegistry); _javascriptObjectWrapper = javascriptObjectWrapper; } else { auto propertyAttribute = javascriptProperty->IsReadOnly ? V8_PROPERTY_ATTRIBUTE_READONLY : V8_PROPERTY_ATTRIBUTE_NONE; v8Value->SetValue(propertyName, V8_ACCESS_CONTROL_DEFAULT, propertyAttribute); } }; }
[ "renhanlinbsl@163.com" ]
renhanlinbsl@163.com
366c64fa152bb635ebab7ddd8678a0179c1c644e
48b0e84c810154e02ee494e43b643678fc425e05
/intro.cpp
467536b29cb7d4a929a74edc0e0c6e5cba1de34f
[]
no_license
sudip10028/auv_summer_2k19
b5459a64a8129e589f8d87a40b95372b3559d99a
539cdb4baffb96f1b969349a27501332cadc7a49
refs/heads/master
2022-03-28T00:53:06.138140
2019-12-05T16:20:01
2019-12-05T16:20:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,745
cpp
#include<bits/stdc++.h> using namespace std; #define fast ios_base::sync_with_stdio(0);cin.tie(NULL) #define fm_t int t;cin>>t;while(t--) #define fr(i,a,b) for( int i=a;i<b;i++) #define fr1(i,n,a) for( int i=n-1;i>=a;i--) #define fri(itr,flag) for( auto itr = flag.begin();itr!=flag.end();itr++) #define max(a,b) (a>b)?a:b #define min(a,b) (a<b)?a:b #define pb push_back #define ff first #define ss second #define sz(x) (int)(x).size() #define mod 1000000007 typedef long long ll; typedef long double ld; //setprecision(10) //greater<int>() /*bool compare(pt i1, pt i2) { return (i1.start < i2.start); }*/ ll mpow(ll x, ll n) { ll ans = 1; while(n != 0){ if(n&1) ans = ans*x % mod; x = x*x % mod; n = n >> 1; } return ans; } template<typename ForwardIterator, typename T> ForwardIterator first_less_than (ForwardIterator first, ForwardIterator last, T value) { auto it = std::lower_bound (first, last, value); return (it == first ? last : --it); } int main() { fast; fm_t { int m,n; cin>>n>>m; int arr[n]; int sum=0; fr(i,0,n) { cin>>arr[i]; sum+=arr[i]; } if(m<n||n<=2) cout<<"-1"<<endl; else { cout<<2*sum<<endl; for(int i=0;i<n-1;i++) { cout<<(i+1)<<" "<<i+2<<endl; } cout<<n<<" "<<"1"<<endl; } } //cerr << "Time elapsed: " << clock() / (double)CLOCKS_PER_SEC << endl; return 0; }
[ "sudipchak4@gmail.com" ]
sudipchak4@gmail.com
dc7fa7ba0731a1f2af4a2685a8bccd4de28117f4
18a3f93e4b94f4f24ff17280c2820497e019b3db
/BOSS/TrkExtAlg/ExtBesCrystalParameterisation.h
83109d382970ada7ccaa2714b538e27f420c0611
[]
no_license
jjzhang166/BOSS_ExternalLibs
0e381d8420cea17e549d5cae5b04a216fc8a01d7
9b3b30f7874ed00a582aa9526c23ca89678bf796
refs/heads/master
2023-03-15T22:24:21.249109
2020-11-22T15:11:45
2020-11-22T15:11:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,661
h
//---------------------------------------------------------------------------// // BOOST --- BESIII Object_Oreiented Simulation Tool // //---------------------------------------------------------------------------// //Descpirtion: EMC detector //Author: Fu Chengdong //Created: Sep 4, 2003 //Comment: //---------------------------------------------------------------------------// // #ifndef ExtBesCrystalParameterisation_H #define ExtBhesCrystalParameterisation_H 1 #include "globals.hh" #include "G4VPVParameterisation.hh" //class G4VphysicalVolume; //class G4Trap; //class G4VSolid; //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... class ExtBesEmcGeometry; class ExtBesCrystalParameterisation : public G4VPVParameterisation { public: ExtBesCrystalParameterisation( const G4int , const G4int , const G4int , ExtBesEmcGeometry*, const G4int); virtual ~ExtBesCrystalParameterisation(); void ComputeTransformation ( const G4int , G4VPhysicalVolume* )const; void ComputeDimensions (G4Trap & , const G4int , const G4VPhysicalVolume* )const; G4Material* ComputeMaterial(const G4int,G4VPhysicalVolume *); G4VSolid* ComputeSolid(const G4int,G4VPhysicalVolume *); void ComputeIDAndSide(const G4VPhysicalVolume*)const; inline void SetVerboseLevel(G4int val){fVerboseLevel=val;}; private: G4int fCrystalID; G4int fVerboseLevel; G4int fStartID; G4int fAllCrystals; G4bool fFlagLeft; ExtBesEmcGeometry* fBesEmcGeometry; }; //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... #endif
[ "r.e.deboer@students.uu.nl" ]
r.e.deboer@students.uu.nl
85648aee6fa5be4c1d3a6c072d6eaa2cb8d64309
7cffa9b29f855c68ec5efcf049f596dc7be6bff6
/src/color/yiq/make/salmon.hpp
076aaa8f31d9a4c15022cb18e3957e7298af3314
[ "Apache-2.0" ]
permissive
lzs4073/color
c4e12e26cfe96022e0a5e6736a7abaadf9912c14
290c2c1550c499465f814ba89a214cbec19a72df
refs/heads/master
2020-04-03T07:16:33.120894
2016-02-02T16:18:25
2016-02-02T16:18:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,914
hpp
#ifndef color_yiq_make_salmon #define color_yiq_make_salmon // ::color::make::salmon( c ) namespace color { namespace make { //RGB equivalents: std::array<double,3>( { 0.726247, 0.0656535, 0.125012 } ) - rgb(221,160,221) - #dda0dd inline void salmon( ::color::_internal::model< ::color::category::yiq_uint8 > & color_parameter ) { color_parameter.container() = std::array< std::uint8_t, 3 >( { 0xb9, 0x8d, 0x9e } ); } inline void salmon( ::color::_internal::model< ::color::category::yiq_uint16 > & color_parameter ) { color_parameter.container() = std::array< std::uint16_t, 3 >( { 0xb9ea, 0x8e1a, 0x9e9e } ); } inline void salmon( ::color::_internal::model< ::color::category::yiq_uint32 > & color_parameter ) { color_parameter.container() = std::array< std::uint32_t, 3 >( { 0xb9eb5646, 0x8e1b5757, 0x9e9ea13f } ); } inline void salmon( ::color::_internal::model< ::color::category::yiq_uint64 > & color_parameter ) { color_parameter.container() = std::array< std::uint64_t, 3 >( { 0xb9eb56472bdaf000ull, 0x8e1b575871f3d000ull, 0x9e9ea14057082800ull } ); } inline void salmon( ::color::_internal::model< ::color::category::yiq_float > & color_parameter ) { color_parameter.container() = std::array<float,3>( { 0.726247, 0.0656535, 0.125012 } ); } inline void salmon( ::color::_internal::model< ::color::category::yiq_double> & color_parameter ) { color_parameter.container() = std::array<double,3>( { 0.726247, 0.0656535, 0.125012 } ); } inline void salmon( ::color::_internal::model< ::color::category::yiq_ldouble> & color_parameter ) { color_parameter.container() = std::array<long double,3>( { 0.726247, 0.0656535, 0.125012 } ); } } } #endif
[ "dmilos@gmail.com" ]
dmilos@gmail.com
a33a1366ab9ad23291f947e2b437d00c42b005dd
d7f5938376fc232b3066a8a51005b9c7c6ab3dc5
/Online Judge/UVa/10591 - Happy Number.cpp
3375c9f52e525f706199914af727ecaee1d8ae96
[]
no_license
NurenDurdanaAbha/Nuren
a0384e167256a051c224298444f6f75d58a709b6
a2680693c8ccfc32268c05f816030098d16865c6
refs/heads/master
2021-01-09T16:19:45.805936
2020-02-22T15:55:19
2020-02-22T15:55:19
242,368,663
0
0
null
null
null
null
UTF-8
C++
false
false
932
cpp
#include<bits/stdc++.h> using namespace std; int main() { freopen("output.txt","w",stdout); long long int r,n,i,j,a[100000],p,m,test,t,k,flag,f,check[100000]; scanf("%lld",&test); for(t=1; t<=test; t++) { scanf("%lld",&n); m=n; while(1) { // cout<<"m: "<<m<<endl; i=1; r=0; while(m!=0) { r=m%10; m=m/10; a[i++]=r; } p=i-1; // printf("p: %lld\n",p); // // for(i=1; i<=p; i++) // printf("%lld ",a[i]); k=0; for(i=1; i<=p; i++) { k+=(a[i]*a[i]); } m=k; if(k<=9) { break; } // printf("\nm: %lld\n",m); } if(k==1 || k==7) { printf("Case #%lld: %lld is a Happy number.\n",t,n); } else { printf("Case #%lld: %lld is an Unhappy number.\n",t,n); } } system("notepad output.txt"); return 0; }
[ "48055810+NurenDurdanaAbha@users.noreply.github.com" ]
48055810+NurenDurdanaAbha@users.noreply.github.com
2e8bf7e52f20c104cff1083256d38bcd26760629
63a27c3b09cec84533cd4300be96eb625bbd566f
/knapsack/Code/main.cpp
6a40912035feff7969850367555f826b62c0a13d
[ "Apache-2.0" ]
permissive
derekmpeterson/knapsack
0db751d1378df3c3041d323540ddbc55da55356f
bc96ba50e4a44c8649f9f52376991e3f05b4968e
refs/heads/master
2020-05-18T11:19:49.043797
2015-07-21T05:22:03
2015-07-21T05:22:03
39,353,326
0
0
null
null
null
null
UTF-8
C++
false
false
4,924
cpp
// // main.cpp // knapsack // // Created by Derek Peterson on 5/6/15. // Copyright (c) 2015 Derek Peterson. All rights reserved. // #include "SDL2/SDL.h" #include "SDL2_Image/SDL_Image.h" #include "SDL2_ttf/SDL_ttf.h" #include <stdio.h> #include "Systems/ActorSystem.h" #include "Systems/CollisionSystem.h" #include "main.h" #include <iostream> #include "DEFINES.H" #include "Gadgets/CollisionGadget.h" #include "ext/RotMat.h" #ifdef DEBUG #include "Debug/DebugText.h" #endif int main( int argc, char* args[] ) { g_lastFrame = 0; SDL_Init( SDL_INIT_VIDEO ); //SDL_CreateWindowAndRenderer( SCREEN_WIDTH, SCREEN_HEIGHT, 0, &g_gameWindow, &g_gameRenderer ); g_gameWindow = SDL_CreateWindow("knapsack", -SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0 ); g_gameRenderer = SDL_CreateRenderer( g_gameWindow, 0, SDL_RENDERER_PRESENTVSYNC ); if( !g_gameWindow ) { printf( "Could not create window: %s\n", SDL_GetError() ); return 1; } g_gameSurface = SDL_GetWindowSurface( g_gameWindow ); SDL_SetRenderDrawColor( g_gameRenderer, 0, 0, 0, 255 ); SDL_RenderClear( g_gameRenderer ); if(TTF_Init()==-1) { printf("TTF_Init: %s\n", TTF_GetError()); exit(2); } ActorSystem::CreateActor( "Background", Vector2d( 96.0f, 0.0f ) ); // create some temporary actors for spatial reference //ActorSystem::CreateActor( "Avatar", Vector2d( 40.0f, 0.0f ) ); ActorSystem::CreateActor( "Tree", Vector2d( 50.0f, 0.0f ) ); ActorSystem::CreateActor( "Tree", Vector2d( 60.0f, 0.0f ) ); ActorSystem::CreateActor( "Tree", Vector2d( 70.0f, 0.0f ) ); g_player = new Player( ActorSystem::CreateActor( "Avatar", Vector2d( 25.0f, 20.0f ) ) ); ActorSystem::CreateActor( "Crate", Vector2d( 10.0f, 0.0f ) ); g_camera = new Camera( g_player->GetActor(), RotMat( Vector2d( -1, 0 ), Vector2d( 0, -1 ) ) ); CollisionSystem::Init(); loop(); return 0; } void loop() { while( !g_quitTriggered ) { unsigned int pTime = SDL_GetTicks(); unsigned int delta = pTime - g_lastFrame; g_lastFrame = pTime; float dt = (float) delta / 1000.0f; #ifdef DEBUG float frameRate = 1000.0f / (float ) delta; char buf[16]; sprintf( buf, "FPS: %0.2f", frameRate ); if ( frameRate > 30.0f ) DebugText::WriteText( buf, DebugText::COLOR_GREEN ); else if ( frameRate > 20.0f ) DebugText::WriteText( buf, DebugText::COLOR_YELLOW ); else DebugText::WriteText( buf, DebugText::COLOR_RED ); #endif // DEBUG processInput(); g_player->Update( dt ); for (std::map<ActorHandle,Actor*>::iterator it=ActorSystem::m_actors.begin(); it!=ActorSystem::m_actors.end(); ++it) it->second->Update( dt ); CollisionSystem::Update( dt ); g_camera->Update( dt ); render( dt ); } } void render( float dt ) { SDL_SetRenderDrawColor( g_gameRenderer, 0, 0, 0, 255 ); SDL_RenderClear( g_gameRenderer ); for (std::map<ActorHandle,Actor*>::iterator it=ActorSystem::m_actors.begin(); it!=ActorSystem::m_actors.end(); ++it) it->second->Draw(); DebugText::Render(); SDL_RenderPresent( g_gameRenderer ); } void quit() { SDL_DestroyRenderer( g_gameRenderer ); SDL_DestroyWindow( g_gameWindow ); SDL_Quit(); } void processInput() { while( SDL_PollEvent( &g_event ) != 0 ) { if( g_event.type == SDL_QUIT ) { g_quitTriggered = true; } else if ( g_event.type == SDL_KEYDOWN ) { switch( g_event.key.keysym.sym ) { case SDLK_ESCAPE: g_quitTriggered = true; break; case SDLK_w: g_player->SetJumpPressed( true ); break; case SDLK_s: g_player->SetDownPressed( true ); break; case SDLK_a: g_player->SetLeftPressed( true ); break; case SDLK_d: g_player->SetRightPressed( true ); break; } } else if ( g_event.type == SDL_KEYUP ) { switch( g_event.key.keysym.sym ) { case SDLK_w: g_player->SetJumpPressed( false ); break; case SDLK_s: g_player->SetDownPressed( false ); break; case SDLK_a: g_player->SetLeftPressed( false ); break; case SDLK_d: g_player->SetRightPressed( false ); break; } } } }
[ "derek@derekp.com" ]
derek@derekp.com
c545e3dcf2aa75206d5d5acaf7feaf5a5f4240b0
b9091c9bc70ec93d461de20351c1baf2c7a47939
/add-binary/main.cpp
1e64b3ebe364eebe0474bd6575b2fa50258ac3b4
[]
no_license
Amit1150/LeetCode
355df25aaf387ed8722a1a847d4088e554a22748
f46a58047df6abc4ef6294e39ace4db85121e3c5
refs/heads/master
2022-12-01T19:18:29.147251
2020-08-18T03:41:50
2020-08-18T03:41:50
284,210,918
0
0
null
null
null
null
UTF-8
C++
false
false
1,200
cpp
#include <iostream> #include <string> #include <vector> using namespace std; string addBinary(string a, string b) { int lenA = a.length() - 1; int lenB = b.length() - 1; bool carry = false; string output = ""; while(lenA >= 0 || lenB >=0){ char firstChar = '0'; char secondChar = '0'; if(lenA >=0) { firstChar = a[lenA]; } if(lenB >= 0) { secondChar = b[lenB]; } if(firstChar == secondChar) { if(carry) { output = '1' + output; carry = firstChar == '1' ? carry : !carry; } else { output = '0' + output; carry = firstChar == '1' ? !carry : carry; } } else { output = carry ? '0' + output : '1' + output; } lenA--; lenB--; } return carry ? '1' + output : output; } int main() { cout << addBinary("11", "1") << endl; cout << addBinary("1", "111") << endl; cout << addBinary("1010", "1011") << endl; cout << addBinary("110010", "100") << endl; cout << addBinary("100", "110010") << endl; return 0; }
[ "amit.kumar12@nagarro.com" ]
amit.kumar12@nagarro.com
bef610cc405f173b7fe263b67c4ed750fabb330b
c4cfdbd5ea943125e2ece2efc55ae60d326bed4c
/acBitmapFont.h
645601162ef4a9cea76e20d28575c4bca2deba8b
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
blackaller/acu
fe2fde82ee3d9ff6545bfb422c160fa421a4f399
c6f6b4007f83c1d9ea1f60ed79a11a8d43bae3b1
refs/heads/master
2020-04-06T04:39:46.603150
2001-11-02T20:19:28
2001-11-02T20:19:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,010
h
#ifndef _AC_BITMAP_FONT_H_ #define _AC_BITMAP_FONT_H_ #include "acu.h" #include "acFont.h" class acBitmapFont : public acFont { public: acBitmapFont() { } // for subclasses.. grr. acBitmapFont(const char *filename); float getDescent(); float getHeight(); float charWidth(unsigned char c); float charHeight(unsigned char c); boolean charExists(unsigned char c); void drawChar(unsigned char c, float x, float y); int getFormat(); unsigned char* getCharData(unsigned char c, float *x, float *y, float *w, float *h); //protected: int numChars; int numBits; int mboxX; int mboxY; int baseHt; // per character int *value; int *height; int *width; int *setWidth; int *topExtent; int *leftExtent; unsigned char **images; GLuint *texNames; float charBitmapWidth(unsigned char c); float charBitmapHeight(unsigned char c); float charTop(unsigned char c); float charTopExtent(unsigned char c); float charLeftExtent(unsigned char c); }; #endif
[ "ben@media.mit.edu" ]
ben@media.mit.edu
91b0e551b1ecf834ca995cc6e991856814cd567f
637fa6d1057e3906bc7fc788d63ac49458587f13
/example.cpp
47c89f82b9473c4eefe416cfb51e5329fa7d4a62
[]
no_license
yuzhangbit/utils
41f354d462e91028d2cc12a79f241f2781bd1b19
0be82e0cb726bafda50fe48981738bcae866297b
refs/heads/master
2020-04-29T06:39:47.045839
2019-03-16T07:45:59
2019-03-16T07:45:59
175,924,495
1
0
null
null
null
null
UTF-8
C++
false
false
316
cpp
#include "time.hpp" #include <iostream> int main() { auto start = utils::now(); for (std::size_t i = 0; i < 100000; i++) { std::cout << "."; } std::cout << std::endl; auto end = utils::now(); std::cout << "duration:" << utils::getDurationInSecs(start, end) << " seconds" << std::endl; return 0; }
[ "yu2.zhang@uisee.com" ]
yu2.zhang@uisee.com
19095a151422846410d031a13c92d58b19ec5287
5456502f97627278cbd6e16d002d50f1de3da7bb
/chrome/browser/media/router/media_router_dialog_controller.cc
2b2279055acd0200ef240c184b27b2a1ba61fa16
[ "BSD-3-Clause" ]
permissive
TrellixVulnTeam/Chromium_7C66
72d108a413909eb3bd36c73a6c2f98de1573b6e5
c8649ab2a0f5a747369ed50351209a42f59672ee
refs/heads/master
2023-03-16T12:51:40.231959
2017-12-20T10:38:26
2017-12-20T10:38:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,156
cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/media/router/media_router_dialog_controller.h" #include <utility> #include "chrome/browser/media/router/media_router_metrics.h" #include "chrome/common/features.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_delegate.h" #if BUILDFLAG(ANDROID_JAVA_UI) #include "chrome/browser/media/android/router/media_router_dialog_controller_android.h" #else #include "chrome/browser/ui/webui/media_router/media_router_dialog_controller_impl.h" #endif namespace media_router { // static MediaRouterDialogController* MediaRouterDialogController::GetOrCreateForWebContents( content::WebContents* contents) { #if BUILDFLAG(ANDROID_JAVA_UI) return MediaRouterDialogControllerAndroid::GetOrCreateForWebContents( contents); #else return MediaRouterDialogControllerImpl::GetOrCreateForWebContents(contents); #endif } class MediaRouterDialogController::InitiatorWebContentsObserver : public content::WebContentsObserver { public: InitiatorWebContentsObserver( content::WebContents* web_contents, MediaRouterDialogController* dialog_controller) : content::WebContentsObserver(web_contents), dialog_controller_(dialog_controller) { DCHECK(dialog_controller_); } private: void WebContentsDestroyed() override { // NOTE: |this| is deleted after CloseMediaRouterDialog() returns. dialog_controller_->CloseMediaRouterDialog(); } void NavigationEntryCommitted( const content::LoadCommittedDetails& load_details) override { // NOTE: |this| is deleted after CloseMediaRouterDialog() returns. dialog_controller_->CloseMediaRouterDialog(); } void RenderProcessGone(base::TerminationStatus status) override { // NOTE: |this| is deleted after CloseMediaRouterDialog() returns. dialog_controller_->CloseMediaRouterDialog(); } MediaRouterDialogController* const dialog_controller_; }; MediaRouterDialogController::MediaRouterDialogController( content::WebContents* initiator) : initiator_(initiator) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(initiator_); } MediaRouterDialogController::~MediaRouterDialogController() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); } bool MediaRouterDialogController::ShowMediaRouterDialogForPresentation( std::unique_ptr<CreatePresentationConnectionRequest> request) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); bool dialog_needs_creation = !IsShowingMediaRouterDialog(); if (dialog_needs_creation) { create_connection_request_ = std::move(request); MediaRouterMetrics::RecordMediaRouterDialogOrigin( MediaRouterDialogOpenOrigin::PAGE); } FocusOnMediaRouterDialog(dialog_needs_creation); return dialog_needs_creation; } bool MediaRouterDialogController::ShowMediaRouterDialog() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); bool dialog_needs_creation = !IsShowingMediaRouterDialog(); FocusOnMediaRouterDialog(dialog_needs_creation); return dialog_needs_creation; } void MediaRouterDialogController::HideMediaRouterDialog() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); CloseMediaRouterDialog(); Reset(); } void MediaRouterDialogController::FocusOnMediaRouterDialog( bool dialog_needs_creation) { if (dialog_needs_creation) { initiator_observer_.reset( new InitiatorWebContentsObserver(initiator_, this)); CreateMediaRouterDialog(); } initiator_->GetDelegate()->ActivateContents(initiator_); } std::unique_ptr<CreatePresentationConnectionRequest> MediaRouterDialogController::TakeCreateConnectionRequest() { return std::move(create_connection_request_); } void MediaRouterDialogController::Reset() { initiator_observer_.reset(); create_connection_request_.reset(); } } // namespace media_router
[ "lixiaodonglove7@aliyun.com" ]
lixiaodonglove7@aliyun.com
b9c6ee0f9cced28268418611e6102dfbff4b5fca
0494c9caa519b27f3ed6390046fde03a313d2868
/src/ui/app_list/views/app_list_view.cc
863e25e55df8ed22c06c2754746e4cb85b65f187
[ "BSD-3-Clause" ]
permissive
mhcchang/chromium30
9e9649bec6fb19fe0dc2c8b94c27c9d1fa69da2c
516718f9b7b95c4280257b2d319638d4728a90e1
refs/heads/master
2023-03-17T00:33:40.437560
2017-08-01T01:13:12
2017-08-01T01:13:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,309
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/app_list/views/app_list_view.h" #include "base/command_line.h" #include "base/strings/string_util.h" #include "ui/app_list/app_list_constants.h" #include "ui/app_list/app_list_model.h" #include "ui/app_list/app_list_view_delegate.h" #include "ui/app_list/pagination_model.h" #include "ui/app_list/signin_delegate.h" #include "ui/app_list/views/app_list_background.h" #include "ui/app_list/views/app_list_main_view.h" #include "ui/app_list/views/search_box_view.h" #include "ui/app_list/views/signin_view.h" #include "ui/base/ui_base_switches.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/insets.h" #include "ui/gfx/path.h" #include "ui/gfx/skia_util.h" #include "ui/views/bubble/bubble_frame_view.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/widget/widget.h" #if defined(USE_AURA) #include "ui/aura/window.h" #if defined(OS_WIN) #include "ui/base/win/shell.h" #endif #endif namespace app_list { namespace { // The distance between the arrow tip and edge of the anchor view. const int kArrowOffset = 10; } // namespace //////////////////////////////////////////////////////////////////////////////// // AppListView: AppListView::AppListView(AppListViewDelegate* delegate) : model_(new AppListModel), delegate_(delegate), app_list_main_view_(NULL), signin_view_(NULL) { if (delegate_) delegate_->SetModel(model_.get()); if (GetSigninDelegate()) GetSigninDelegate()->AddObserver(this); } AppListView::~AppListView() { if (GetSigninDelegate()) GetSigninDelegate()->RemoveObserver(this); // Models are going away, ensure their references are cleared. RemoveAllChildViews(true); } void AppListView::InitAsBubble(gfx::NativeView parent, PaginationModel* pagination_model, views::View* anchor, const gfx::Point& anchor_point, views::BubbleBorder::Arrow arrow, bool border_accepts_events) { app_list_main_view_ = new AppListMainView(delegate_.get(), model_.get(), pagination_model, anchor); AddChildView(app_list_main_view_); #if defined(USE_AURA) app_list_main_view_->SetPaintToLayer(true); app_list_main_view_->SetFillsBoundsOpaquely(false); app_list_main_view_->layer()->SetMasksToBounds(true); #endif signin_view_ = new SigninView( GetSigninDelegate(), app_list_main_view_->GetPreferredSize().width()); AddChildView(signin_view_); OnSigninStatusChanged(); set_anchor_view(anchor); set_anchor_rect(gfx::Rect(anchor_point, gfx::Size())); set_color(kContentsBackgroundColor); set_margins(gfx::Insets()); set_move_with_anchor(true); set_parent_window(parent); set_close_on_deactivate(false); set_close_on_esc(false); set_anchor_view_insets(gfx::Insets(kArrowOffset, kArrowOffset, kArrowOffset, kArrowOffset)); set_border_accepts_events(border_accepts_events); set_shadow(views::BubbleBorder::BIG_SHADOW); #if defined(USE_AURA) && defined(OS_WIN) if (!ui::win::IsAeroGlassEnabled() || CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableDwmComposition)) { set_shadow(views::BubbleBorder::NO_SHADOW_OPAQUE_BORDER); } #endif views::BubbleDelegateView::CreateBubble(this); SetBubbleArrow(arrow); #if defined(USE_AURA) GetWidget()->GetNativeWindow()->layer()->SetMasksToBounds(true); GetBubbleFrameView()->set_background(new AppListBackground( GetBubbleFrameView()->bubble_border()->GetBorderCornerRadius(), app_list_main_view_)); set_background(NULL); #else set_background(new AppListBackground( GetBubbleFrameView()->bubble_border()->GetBorderCornerRadius(), app_list_main_view_)); // On non-aura the bubble has two widgets, and it's possible for the border // to be shown independently in odd situations. Explicitly hide the bubble // widget to ensure that any WM_WINDOWPOSCHANGED messages triggered by the // window manager do not have the SWP_SHOWWINDOW flag set which would cause // the border to be shown. See http://crbug.com/231687 . GetWidget()->Hide(); #endif } void AppListView::SetBubbleArrow(views::BubbleBorder::Arrow arrow) { GetBubbleFrameView()->bubble_border()->set_arrow(arrow); SizeToContents(); // Recalcuates with new border. GetBubbleFrameView()->SchedulePaint(); } void AppListView::SetAnchorPoint(const gfx::Point& anchor_point) { set_anchor_rect(gfx::Rect(anchor_point, gfx::Size())); SizeToContents(); // Repositions view relative to the anchor. } void AppListView::SetDragAndDropHostOfCurrentAppList( app_list::ApplicationDragAndDropHost* drag_and_drop_host) { app_list_main_view_->SetDragAndDropHostOfCurrentAppList(drag_and_drop_host); } void AppListView::ShowWhenReady() { app_list_main_view_->ShowAppListWhenReady(); } void AppListView::Close() { app_list_main_view_->Close(); if (delegate_) delegate_->Dismiss(); else GetWidget()->Close(); } void AppListView::UpdateBounds() { SizeToContents(); } gfx::Size AppListView::GetPreferredSize() { return app_list_main_view_->GetPreferredSize(); } bool AppListView::ShouldHandleSystemCommands() const { return true; } void AppListView::Prerender() { app_list_main_view_->Prerender(); } void AppListView::OnSigninStatusChanged() { const bool needs_signin = GetSigninDelegate() && GetSigninDelegate()->NeedSignin(); signin_view_->SetVisible(needs_signin); app_list_main_view_->SetVisible(!needs_signin); app_list_main_view_->search_box_view()->InvalidateMenu(); } views::View* AppListView::GetInitiallyFocusedView() { return app_list_main_view_->search_box_view()->search_box(); } gfx::ImageSkia AppListView::GetWindowIcon() { if (delegate_) return delegate_->GetWindowIcon(); return gfx::ImageSkia(); } bool AppListView::WidgetHasHitTestMask() const { return true; } void AppListView::GetWidgetHitTestMask(gfx::Path* mask) const { DCHECK(mask); mask->addRect(gfx::RectToSkRect( GetBubbleFrameView()->GetContentsBounds())); } bool AppListView::AcceleratorPressed(const ui::Accelerator& accelerator) { // The accelerator is added by BubbleDelegateView. if (accelerator.key_code() == ui::VKEY_ESCAPE) { if (app_list_main_view_->search_box_view()->HasSearch()) { app_list_main_view_->search_box_view()->ClearSearch(); } else { GetWidget()->Deactivate(); Close(); } return true; } return false; } void AppListView::Layout() { const gfx::Rect contents_bounds = GetContentsBounds(); app_list_main_view_->SetBoundsRect(contents_bounds); signin_view_->SetBoundsRect(contents_bounds); } void AppListView::OnWidgetDestroying(views::Widget* widget) { BubbleDelegateView::OnWidgetDestroying(widget); if (delegate_ && widget == GetWidget()) delegate_->ViewClosing(); } void AppListView::OnWidgetActivationChanged(views::Widget* widget, bool active) { // Do not called inherited function as the bubble delegate auto close // functionality is not used. if (delegate_ && widget == GetWidget()) delegate_->ViewActivationChanged(active); } void AppListView::OnWidgetVisibilityChanged(views::Widget* widget, bool visible) { BubbleDelegateView::OnWidgetVisibilityChanged(widget, visible); if (widget != GetWidget()) return; // We clear the search when hiding so the next time the app list appears it is // not showing search results. if (!visible) app_list_main_view_->search_box_view()->ClearSearch(); // Whether we need to signin or not may have changed since last time we were // shown. Layout(); } void AppListView::OnSigninSuccess() { OnSigninStatusChanged(); } SigninDelegate* AppListView::GetSigninDelegate() { return delegate_ ? delegate_->GetSigninDelegate() : NULL; } } // namespace app_list
[ "1990zhaoshuang@163.com" ]
1990zhaoshuang@163.com
96673b3bd728d23b9f90bdd9cb92b90a2a6f120a
d6dbac2e16d2b3ea0e0dd8354723abe78c4e2345
/include/jnipp/marshaling/NativeTypeTraits.ToJava.inl
a3994c1b01b99bd8a45465885769af3c8809ca4a
[ "Apache-2.0" ]
permissive
liuxuanhai/jnipp
5377a88012ce7a669046071c27ab54fb8ea9ec86
99f0f73f4a8aeb6cc614cfb82051c14ba7ab73e4
refs/heads/master
2021-06-20T08:54:08.082753
2017-07-25T12:36:51
2017-07-25T12:36:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,243
inl
// Copyright since 2016 : Evgenii Shatunov (github.com/FrankStain/jnipp) // Apache 2.0 License #pragma once namespace Jni { namespace Marshaling { inline void NativeTypeTraits<bool>::ToJava( const NativeType& source, JavaType& destination ) { destination = ( source )? JNI_TRUE : JNI_FALSE; } inline void NativeTypeTraits<const char*>::ToJava( const NativeType& source, JavaType& destination ) { auto local_env = VirtualMachine::GetLocalEnvironment(); destination = local_env->NewStringUTF( source ); } inline void NativeTypeTraits<const char16_t*>::ToJava( const NativeType& source, JavaType& destination ) { auto local_env = VirtualMachine::GetLocalEnvironment(); destination = local_env->NewString( reinterpret_cast<const jchar*>( source ), std::char_traits<char16_t>::length( source ) ); } inline void NativeTypeTraits<std::string>::ToJava( const NativeType& source, JavaType& destination ) { NativeTypeTraits<const char*>::ToJava( source.c_str(), destination ); } inline void NativeTypeTraits<std::u16string>::ToJava( const NativeType& source, JavaType& destination ) { NativeTypeTraits<const char16_t*>::ToJava( source.c_str(), destination ); } inline void NativeTypeTraits<float>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; } inline void NativeTypeTraits<double>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; } inline void NativeTypeTraits<int8_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; } inline void NativeTypeTraits<char16_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; } inline void NativeTypeTraits<int16_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; } inline void NativeTypeTraits<int32_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; } inline void NativeTypeTraits<int64_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; } inline void NativeTypeTraits<uint8_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; } inline void NativeTypeTraits<uint16_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; } inline void NativeTypeTraits<uint32_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = source; } inline void NativeTypeTraits<uint64_t>::ToJava( const NativeType& source, JavaType& destination ) { destination = reinterpret_cast<const int64_t&>( source ); } template< typename TNativeElementType, typename TAllocatorType > inline void NativeTypeTraits<std::vector<TNativeElementType, TAllocatorType>>::ToJava( const NativeType& source, JavaType& destination ) { using ElementTraits = NativeTypeTraits<TNativeElementType>; using JavaArrayType = typename ElementTraits::JavaArrayType; using TranslationTraits = ArrayTranslationTraits<ElementTraits>; TranslationTraits::ToJava( source, reinterpret_cast<JavaArrayType&>( destination ) ); } } }
[ "dr.frank.stain@gmail.com" ]
dr.frank.stain@gmail.com
408a4a5c8c059034c6785237b5c13b7ce036137a
3b32bbad87674bda1be504f9de3ad3024fcfe0a2
/CharacterAttributesSubject.cpp
a6216dac743a5867ea93ca5ccab26bb943aa0ea3
[]
no_license
dkeohane/Drow-Engine
e6c5ace77ab677e3ad010d59a60cfc38ee0bf43f
18512157de00c86b33bb5911e95be32db67a6bb0
refs/heads/master
2021-05-01T10:25:31.790730
2014-03-16T11:37:50
2014-03-16T11:37:50
15,901,287
0
0
null
null
null
null
UTF-8
C++
false
false
471
cpp
#include "CharacterAttributesSubject.h" void CharacterAttributesSubject::attach(CharacterAttributesObserver* o) { this->observers.push_back(o); } void CharacterAttributesSubject::detach(CharacterAttributesObserver* o) { observers.erase(std::remove(observers.begin(), observers.end(), o), observers.end()); } void CharacterAttributesSubject::notify() { std::for_each(observers.begin(), observers.end(), [&](CharacterAttributesObserver *o) { o->Update(this); }); }
[ "danielkeohane4823@gmail.com" ]
danielkeohane4823@gmail.com
ae41e6468c42b571395827b21e565a6c31ac9fb9
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_patch_hunk_2302.cpp
bd8ad46025ca57f046b4576d5dfe96f71ddcae91
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
535
cpp
subcache->idx_used -= loop; subcache->idx_pos = new_idx_pos; /* Adjust the data area */ subcache->data_used -= diff; subcache->data_pos = idx->data_pos; } - header->stat_expiries += loop; + header->stat_expiries += expired; ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, "we now have %u socache entries", subcache->idx_used); } static int shmcb_subcache_store(server_rec *s, SHMCBHeader *header, SHMCBSubcache *subcache,
[ "993273596@qq.com" ]
993273596@qq.com
3683360d884f7229722916d60f6aa323f6e8eb3b
bee8758799e64d4d759ffd3e9bd757a69678e878
/src/StupidClockFilter.cpp
21a2748cf5d8121f45f8066b5519c2ef6cf8c150
[]
no_license
soenkelange/imp-clock-detection
41fe2297d75f5c7f2d38f3bc5787afc748b7176e
2bb044b4a90a5ff00cc9cdfb7c9c331add4cfd86
refs/heads/master
2021-01-17T10:58:15.342457
2016-01-22T09:13:41
2016-01-22T09:13:41
48,763,783
0
0
null
null
null
null
UTF-8
C++
false
false
557
cpp
#include "StupidClockFilter.hpp" #include <opencv/highgui.h> StupidClockFilter::~StupidClockFilter() { } void StupidClockFilter::process(const cv::Mat& input) { cv::imshow("Debug", input); } cv::Point StupidClockFilter::getBigHandPosition() const { return cv::Point(4,0); } cv::Point StupidClockFilter::getSmallHandPosition() const { return cv::Point(-4,0); } cv::Point StupidClockFilter::getClockCenterPosition() const { return cv::Point(0,0); } cv::Point StupidClockFilter::getClockTopPosition() const { return cv::Point(0,-6); }
[ "s.lange@mytaxi.com" ]
s.lange@mytaxi.com
c8a9d4e2c670ee64790724a4b716abe4650cd5b7
ab97a8915347c76d05d6690dbdbcaf23d7f0d1fd
/third_party/blink/renderer/core/layout/ng/inline/ng_fragment_item.cc
82c8462c40de9e88af37bbf194b455fcec74ec01
[ "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "MIT", "Apache-2.0" ]
permissive
laien529/chromium
c9eb243957faabf1b477939e3b681df77f083a9a
3f767cdd5c82e9c78b910b022ffacddcb04d775a
refs/heads/master
2022-11-28T00:28:58.669067
2020-08-20T08:37:31
2020-08-20T08:37:31
288,961,699
1
0
BSD-3-Clause
2020-08-20T09:21:57
2020-08-20T09:21:56
null
UTF-8
C++
false
false
24,129
cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/layout/ng/inline/ng_fragment_item.h" #include "third_party/blink/renderer/core/editing/inline_box_traversal.h" #include "third_party/blink/renderer/core/editing/position_with_affinity.h" #include "third_party/blink/renderer/core/layout/ng/inline/ng_caret_position.h" #include "third_party/blink/renderer/core/layout/ng/inline/ng_fragment_items_builder.h" #include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_cursor.h" #include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_item.h" #include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_item_result.h" #include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h" #include "third_party/blink/renderer/platform/wtf/size_assertions.h" namespace blink { namespace { struct SameSizeAsNGFragmentItem { struct { void* pointer; NGTextOffset text_offset; } type_data; PhysicalRect rect; NGInkOverflow ink_overflow; void* pointer; wtf_size_t sizes[2]; unsigned flags; }; ASSERT_SIZE(NGFragmentItem, SameSizeAsNGFragmentItem); } // namespace NGFragmentItem::NGFragmentItem(const NGPhysicalTextFragment& text) : layout_object_(text.GetLayoutObject()), text_({text.TextShapeResult(), text.TextOffset()}), rect_({PhysicalOffset(), text.Size()}), type_(kText), sub_type_(static_cast<unsigned>(text.TextType())), style_variant_(static_cast<unsigned>(text.StyleVariant())), is_hidden_for_paint_(text.IsHiddenForPaint()), text_direction_(static_cast<unsigned>(text.ResolvedDirection())), ink_overflow_type_(NGInkOverflow::kNotSet), is_dirty_(false), is_last_for_node_(true) { #if DCHECK_IS_ON() if (text_.shape_result) { DCHECK_EQ(text_.shape_result->StartIndex(), StartOffset()); DCHECK_EQ(text_.shape_result->EndIndex(), EndOffset()); } #endif if (text.TextType() == NGTextType::kLayoutGenerated) { type_ = kGeneratedText; // Note: Because of |text_| and |generated_text_| are in same union and // we initialize |text_| instead of |generated_text_|, we should construct // |generated_text_.text_| instead copying, |generated_text_.text = ...|. new (&generated_text_.text) String(text.Text().ToString()); } DCHECK(!IsFormattingContextRoot()); } NGFragmentItem::NGFragmentItem( const NGInlineItem& inline_item, scoped_refptr<const ShapeResultView> shape_result, const NGTextOffset& text_offset, const PhysicalSize& size, bool is_hidden_for_paint) : layout_object_(inline_item.GetLayoutObject()), text_({std::move(shape_result), text_offset}), rect_({PhysicalOffset(), size}), type_(kText), sub_type_(static_cast<unsigned>(inline_item.TextType())), style_variant_(static_cast<unsigned>(inline_item.StyleVariant())), is_hidden_for_paint_(is_hidden_for_paint), text_direction_(static_cast<unsigned>(inline_item.Direction())), ink_overflow_type_(NGInkOverflow::kNotSet), is_dirty_(false), is_last_for_node_(true) { #if DCHECK_IS_ON() if (text_.shape_result) { DCHECK_EQ(text_.shape_result->StartIndex(), StartOffset()); DCHECK_EQ(text_.shape_result->EndIndex(), EndOffset()); } #endif DCHECK_NE(TextType(), NGTextType::kLayoutGenerated); DCHECK(!IsFormattingContextRoot()); } NGFragmentItem::NGFragmentItem( const NGInlineItem& inline_item, scoped_refptr<const ShapeResultView> shape_result, const String& text_content, const PhysicalSize& size, bool is_hidden_for_paint) : layout_object_(inline_item.GetLayoutObject()), generated_text_({std::move(shape_result), text_content}), rect_({PhysicalOffset(), size}), type_(kGeneratedText), sub_type_(static_cast<unsigned>(inline_item.TextType())), style_variant_(static_cast<unsigned>(inline_item.StyleVariant())), is_hidden_for_paint_(is_hidden_for_paint), text_direction_(static_cast<unsigned>(inline_item.Direction())), ink_overflow_type_(NGInkOverflow::kNotSet), is_dirty_(false), is_last_for_node_(true) { #if DCHECK_IS_ON() if (text_.shape_result) { DCHECK_EQ(text_.shape_result->StartIndex(), StartOffset()); DCHECK_EQ(text_.shape_result->EndIndex(), EndOffset()); } #endif DCHECK_EQ(TextType(), NGTextType::kLayoutGenerated); DCHECK(!IsFormattingContextRoot()); } NGFragmentItem::NGFragmentItem(const NGPhysicalLineBoxFragment& line) : layout_object_(line.ContainerLayoutObject()), line_({&line, /* descendants_count */ 1}), rect_({PhysicalOffset(), line.Size()}), type_(kLine), sub_type_(static_cast<unsigned>(line.LineBoxType())), style_variant_(static_cast<unsigned>(line.StyleVariant())), is_hidden_for_paint_(false), text_direction_(static_cast<unsigned>(line.BaseDirection())), ink_overflow_type_(NGInkOverflow::kNotSet), is_dirty_(false), is_last_for_node_(true) { DCHECK(!IsFormattingContextRoot()); } NGFragmentItem::NGFragmentItem(const NGPhysicalBoxFragment& box, TextDirection resolved_direction) : layout_object_(box.GetLayoutObject()), box_({&box, /* descendants_count */ 1}), rect_({PhysicalOffset(), box.Size()}), type_(kBox), style_variant_(static_cast<unsigned>(box.StyleVariant())), is_hidden_for_paint_(box.IsHiddenForPaint()), text_direction_(static_cast<unsigned>(resolved_direction)), ink_overflow_type_(NGInkOverflow::kNotSet), is_dirty_(false), is_last_for_node_(true) { DCHECK_EQ(IsFormattingContextRoot(), box.IsFormattingContextRoot()); } NGFragmentItem::NGFragmentItem(NGLogicalLineItem&& line_item, WritingMode writing_mode) { DCHECK(line_item.CanCreateFragmentItem()); if (line_item.fragment) { new (this) NGFragmentItem(*line_item.fragment); return; } if (line_item.inline_item) { if (UNLIKELY(line_item.text_content)) { new (this) NGFragmentItem( *line_item.inline_item, std::move(line_item.shape_result), line_item.text_content, ToPhysicalSize(line_item.MarginSize(), writing_mode), line_item.is_hidden_for_paint); return; } new (this) NGFragmentItem(*line_item.inline_item, std::move(line_item.shape_result), line_item.text_offset, ToPhysicalSize(line_item.MarginSize(), writing_mode), line_item.is_hidden_for_paint); return; } if (line_item.layout_result) { const NGPhysicalBoxFragment& box_fragment = To<NGPhysicalBoxFragment>(line_item.layout_result->PhysicalFragment()); new (this) NGFragmentItem(box_fragment, line_item.ResolvedDirection()); return; } // CanCreateFragmentItem() NOTREACHED(); CHECK(false); } NGFragmentItem::NGFragmentItem(const NGFragmentItem& source) : layout_object_(source.layout_object_), rect_(source.rect_), fragment_id_(source.fragment_id_), delta_to_next_for_same_layout_object_( source.delta_to_next_for_same_layout_object_), type_(source.type_), sub_type_(source.sub_type_), style_variant_(source.style_variant_), is_hidden_for_paint_(source.is_hidden_for_paint_), text_direction_(source.text_direction_), ink_overflow_type_(NGInkOverflow::kNotSet), is_dirty_(source.is_dirty_), is_last_for_node_(source.is_last_for_node_) { switch (Type()) { case kText: new (&text_) TextItem(source.text_); break; case kGeneratedText: new (&generated_text_) GeneratedTextItem(source.generated_text_); break; case kLine: new (&line_) LineItem(source.line_); break; case kBox: new (&box_) BoxItem(source.box_); break; } // Copy |ink_overflow_| only for text items, because ink overflow for other // items may be chnaged even in simplified layout or when reusing lines, and // that they need to be re-computed anyway. if (IsText() && source.IsInkOverflowComputed()) { ink_overflow_type_ = source.InkOverflowType(); new (&ink_overflow_) NGInkOverflow(source.InkOverflowType(), source.ink_overflow_); } } NGFragmentItem::NGFragmentItem(NGFragmentItem&& source) : layout_object_(source.layout_object_), rect_(source.rect_), ink_overflow_(source.InkOverflowType(), std::move(source.ink_overflow_)), fragment_id_(source.fragment_id_), delta_to_next_for_same_layout_object_( source.delta_to_next_for_same_layout_object_), type_(source.type_), sub_type_(source.sub_type_), style_variant_(source.style_variant_), is_hidden_for_paint_(source.is_hidden_for_paint_), text_direction_(source.text_direction_), ink_overflow_type_(source.ink_overflow_type_), is_dirty_(source.is_dirty_), is_last_for_node_(source.is_last_for_node_) { switch (Type()) { case kText: new (&text_) TextItem(std::move(source.text_)); break; case kGeneratedText: new (&generated_text_) GeneratedTextItem(std::move(source.generated_text_)); break; case kLine: new (&line_) LineItem(std::move(source.line_)); break; case kBox: new (&box_) BoxItem(std::move(source.box_)); break; } } NGFragmentItem::~NGFragmentItem() { switch (Type()) { case kText: text_.~TextItem(); break; case kGeneratedText: generated_text_.~GeneratedTextItem(); break; case kLine: line_.~LineItem(); break; case kBox: box_.~BoxItem(); break; } ink_overflow_.Reset(InkOverflowType()); } bool NGFragmentItem::IsInlineBox() const { if (Type() == kBox) { if (const NGPhysicalBoxFragment* box = BoxFragment()) return box->IsInlineBox(); NOTREACHED(); } return false; } bool NGFragmentItem::IsAtomicInline() const { if (Type() != kBox) return false; if (const NGPhysicalBoxFragment* box = BoxFragment()) return box->IsAtomicInline(); return false; } bool NGFragmentItem::IsFloating() const { if (const NGPhysicalBoxFragment* box = BoxFragment()) return box->IsFloating(); return false; } bool NGFragmentItem::IsEmptyLineBox() const { return LineBoxType() == NGLineBoxType::kEmptyLineBox; } bool NGFragmentItem::IsGeneratedText() const { if (Type() == kGeneratedText) { DCHECK_EQ(TextType(), NGTextType::kLayoutGenerated); return true; } DCHECK_NE(TextType(), NGTextType::kLayoutGenerated); if (Type() == kText) return GetLayoutObject()->IsStyleGenerated(); NOTREACHED(); return false; } bool NGFragmentItem::IsListMarker() const { return layout_object_ && layout_object_->IsLayoutNGOutsideListMarker(); } bool NGFragmentItem::HasOverflowClip() const { if (const NGPhysicalBoxFragment* fragment = BoxFragment()) return fragment->HasOverflowClip(); return false; } bool NGFragmentItem::HasSelfPaintingLayer() const { if (const NGPhysicalBoxFragment* fragment = BoxFragment()) return fragment->HasSelfPaintingLayer(); return false; } const NGPhysicalBoxFragment* NGFragmentItem::BoxItem::PostLayout() const { if (box_fragment) return box_fragment->PostLayout(); return nullptr; } void NGFragmentItem::LayoutObjectWillBeDestroyed() const { const_cast<NGFragmentItem*>(this)->layout_object_ = nullptr; if (const NGPhysicalBoxFragment* fragment = BoxFragment()) fragment->LayoutObjectWillBeDestroyed(); } void NGFragmentItem::LayoutObjectWillBeMoved() const { // When |Layoutobject| is moved out from the current IFC, we should not clear // the association with it in |ClearAssociatedFragments|, because the // |LayoutObject| may be moved to a different IFC and is already laid out // before clearing this IFC. This happens e.g., when split inlines moves // inline children into a child anonymous block. const_cast<NGFragmentItem*>(this)->layout_object_ = nullptr; } inline const LayoutBox* NGFragmentItem::InkOverflowOwnerBox() const { if (Type() == kBox) return ToLayoutBoxOrNull(GetLayoutObject()); return nullptr; } inline LayoutBox* NGFragmentItem::MutableInkOverflowOwnerBox() { if (Type() == kBox) return ToLayoutBoxOrNull(const_cast<LayoutObject*>(layout_object_)); return nullptr; } PhysicalRect NGFragmentItem::SelfInkOverflow() const { if (const LayoutBox* box = InkOverflowOwnerBox()) return box->PhysicalSelfVisualOverflowRect(); if (!HasInkOverflow()) return LocalRect(); return ink_overflow_.Self(InkOverflowType(), Size()); } PhysicalRect NGFragmentItem::InkOverflow() const { if (const LayoutBox* box = InkOverflowOwnerBox()) return box->PhysicalVisualOverflowRect(); if (!HasInkOverflow()) return LocalRect(); if (!IsContainer() || HasOverflowClip()) return ink_overflow_.Self(InkOverflowType(), Size()); return ink_overflow_.SelfAndContents(InkOverflowType(), Size()); } const ShapeResultView* NGFragmentItem::TextShapeResult() const { if (Type() == kText) return text_.shape_result.get(); if (Type() == kGeneratedText) return generated_text_.shape_result.get(); NOTREACHED(); return nullptr; } NGTextOffset NGFragmentItem::TextOffset() const { if (Type() == kText) return text_.text_offset; if (Type() == kGeneratedText) return {0, generated_text_.text.length()}; NOTREACHED(); return {}; } StringView NGFragmentItem::Text(const NGFragmentItems& items) const { if (Type() == kText) { return StringView(items.Text(UsesFirstLineStyle()), text_.text_offset.start, text_.text_offset.Length()); } if (Type() == kGeneratedText) return GeneratedText(); NOTREACHED(); return StringView(); } NGTextFragmentPaintInfo NGFragmentItem::TextPaintInfo( const NGFragmentItems& items) const { if (Type() == kText) { return {items.Text(UsesFirstLineStyle()), text_.text_offset.start, text_.text_offset.end, text_.shape_result.get()}; } if (Type() == kGeneratedText) { return {generated_text_.text, 0, generated_text_.text.length(), generated_text_.shape_result.get()}; } NOTREACHED(); return {}; } TextDirection NGFragmentItem::BaseDirection() const { DCHECK_EQ(Type(), kLine); return static_cast<TextDirection>(text_direction_); } TextDirection NGFragmentItem::ResolvedDirection() const { DCHECK(Type() == kText || Type() == kGeneratedText || IsAtomicInline()); return static_cast<TextDirection>(text_direction_); } String NGFragmentItem::ToString() const { // TODO(yosin): Once |NGPaintFragment| is removed, we should get rid of // following if-statements. // For ease of rebasing, we use same |DebugName()| as |NGPaintFrgment|. if (Type() == NGFragmentItem::kBox) { StringBuilder name; name.Append("NGPhysicalBoxFragment "); name.Append(layout_object_->DebugName()); return name.ToString(); } if (Type() == NGFragmentItem::kText) { StringBuilder name; name.Append("NGPhysicalTextFragment '"); const NGFragmentItems* fragment_items = nullptr; if (const LayoutBlockFlow* block_flow = layout_object_->FragmentItemsContainer()) { for (unsigned i = 0; i < block_flow->PhysicalFragmentCount(); ++i) { const NGPhysicalBoxFragment* containing_fragment = block_flow->GetPhysicalFragment(i); fragment_items = containing_fragment->Items(); if (fragment_items) break; } } if (fragment_items) name.Append(Text(*fragment_items)); else name.Append("(container not found)"); name.Append('\''); return name.ToString(); } if (Type() == NGFragmentItem::kLine) return "NGPhysicalLineBoxFragment"; return "NGFragmentItem"; } PhysicalRect NGFragmentItem::LocalVisualRectFor( const LayoutObject& layout_object) { DCHECK(RuntimeEnabledFeatures::LayoutNGFragmentItemEnabled()); DCHECK(layout_object.IsInLayoutNGInlineFormattingContext()); PhysicalRect visual_rect; NGInlineCursor cursor; for (cursor.MoveTo(layout_object); cursor; cursor.MoveToNextForSameLayoutObject()) { DCHECK(cursor.Current().Item()); const NGFragmentItem& item = *cursor.Current().Item(); if (UNLIKELY(item.IsHiddenForPaint())) continue; PhysicalRect child_visual_rect = item.SelfInkOverflow(); child_visual_rect.offset += item.OffsetInContainerBlock(); visual_rect.Unite(child_visual_rect); } return visual_rect; } PhysicalRect NGFragmentItem::RecalcInkOverflowForCursor( NGInlineCursor* cursor) { DCHECK(cursor); DCHECK(!cursor->Current() || cursor->IsAtFirst()); PhysicalRect contents_ink_overflow; while (*cursor) { const NGFragmentItem* item = cursor->CurrentItem(); DCHECK(item); if (UNLIKELY(item->IsLayoutObjectDestroyedOrMoved())) { // TODO(crbug.com/1099613): This should not happen, as long as it is // layout-clean. It looks like there are cases where the layout is dirty. NOTREACHED(); cursor->MoveToNextSkippingChildren(); continue; } PhysicalRect child_rect; item->GetMutableForPainting().RecalcInkOverflow(cursor, &child_rect); if (item->HasSelfPaintingLayer()) continue; if (!child_rect.IsEmpty()) { child_rect.offset += item->OffsetInContainerBlock(); contents_ink_overflow.Unite(child_rect); } } return contents_ink_overflow; } void NGFragmentItem::RecalcInkOverflow( NGInlineCursor* cursor, PhysicalRect* self_and_contents_rect_out) { DCHECK_EQ(this, cursor->CurrentItem()); if (UNLIKELY(IsLayoutObjectDestroyedOrMoved())) { // TODO(crbug.com/1099613): This should not happen, as long as it is really // layout-clean. It looks like there are cases where the layout is dirty. NOTREACHED(); cursor->MoveToNextSkippingChildren(); return; } if (IsText()) { cursor->MoveToNext(); // Re-computing text item is not necessary, because all changes that needs // to re-compute ink overflow invalidate layout. if (IsInkOverflowComputed()) { *self_and_contents_rect_out = SelfInkOverflow(); return; } NGTextFragmentPaintInfo paint_info = TextPaintInfo(cursor->Items()); if (paint_info.shape_result) { ink_overflow_type_ = ink_overflow_.SetTextInkOverflow( InkOverflowType(), paint_info, Style(), Size(), self_and_contents_rect_out); return; } ink_overflow_type_ = ink_overflow_.Reset(InkOverflowType()); *self_and_contents_rect_out = LocalRect(); return; } // If this item has an owner |LayoutBox|, let it compute. It will call back NG // to compute and store the result to |LayoutBox|. Pre-paint requires ink // overflow to be stored in |LayoutBox|. if (LayoutBox* owner_box = MutableInkOverflowOwnerBox()) { DCHECK(!HasChildren()); cursor->MoveToNextSkippingChildren(); owner_box->RecalcNormalFlowChildVisualOverflowIfNeeded(); *self_and_contents_rect_out = owner_box->PhysicalVisualOverflowRect(); return; } // Re-compute descendants, then compute the contents ink overflow from them. NGInlineCursor descendants_cursor = cursor->CursorForDescendants(); cursor->MoveToNextSkippingChildren(); PhysicalRect contents_rect = RecalcInkOverflowForCursor(&descendants_cursor); // |contents_rect| is relative to the inline formatting context. Make it // relative to |this|. contents_rect.offset -= OffsetInContainerBlock(); if (Type() == kLine) { // Line boxes don't have self overflow. Compute content overflow only. *self_and_contents_rect_out = contents_rect; ink_overflow_type_ = ink_overflow_.SetContents(InkOverflowType(), contents_rect, Size()); return; } if (const NGPhysicalBoxFragment* box_fragment = BoxFragment()) { DCHECK(box_fragment->IsInlineBox()); // Compute the self ink overflow. PhysicalRect self_rect = box_fragment->ComputeSelfInkOverflow(); *self_and_contents_rect_out = UnionRect(self_rect, contents_rect); ink_overflow_type_ = ink_overflow_.Set(InkOverflowType(), self_rect, contents_rect, Size()); return; } NOTREACHED(); } void NGFragmentItem::SetDeltaToNextForSameLayoutObject(wtf_size_t delta) const { DCHECK_NE(Type(), kLine); delta_to_next_for_same_layout_object_ = delta; } PositionWithAffinity NGFragmentItem::PositionForPointInText( const PhysicalOffset& point, const NGInlineCursor& cursor) const { DCHECK_EQ(Type(), kText); DCHECK_EQ(cursor.CurrentItem(), this); if (IsGeneratedText()) return PositionWithAffinity(); const unsigned text_offset = TextOffsetForPoint(point, cursor.Items()); const NGCaretPosition unadjusted_position{ cursor, NGCaretPositionType::kAtTextOffset, text_offset}; if (RuntimeEnabledFeatures::BidiCaretAffinityEnabled()) return unadjusted_position.ToPositionInDOMTreeWithAffinity(); if (text_offset > StartOffset() && text_offset < EndOffset()) return unadjusted_position.ToPositionInDOMTreeWithAffinity(); return BidiAdjustment::AdjustForHitTest(unadjusted_position) .ToPositionInDOMTreeWithAffinity(); } unsigned NGFragmentItem::TextOffsetForPoint( const PhysicalOffset& point, const NGFragmentItems& items) const { DCHECK_EQ(Type(), kText); const ComputedStyle& style = Style(); const LayoutUnit& point_in_line_direction = style.IsHorizontalWritingMode() ? point.left : point.top; if (const ShapeResultView* shape_result = TextShapeResult()) { // TODO(layout-dev): Move caret logic out of ShapeResult into separate // support class for code health and to avoid this copy. return shape_result->CreateShapeResult()->CaretOffsetForHitTest( point_in_line_direction.ToFloat(), Text(items), BreakGlyphs) + StartOffset(); } // Flow control fragments such as forced line break, tabulation, soft-wrap // opportunities, etc. do not have ShapeResult. DCHECK(IsFlowControl()); // Zero-inline-size objects such as newline always return the start offset. LogicalSize size = Size().ConvertToLogical(style.GetWritingMode()); if (!size.inline_size) return StartOffset(); // Sized objects such as tabulation returns the next offset if the given point // is on the right half. LayoutUnit inline_offset = IsLtr(ResolvedDirection()) ? point_in_line_direction : size.inline_size - point_in_line_direction; DCHECK_EQ(1u, TextLength()); return inline_offset <= size.inline_size / 2 ? StartOffset() : EndOffset(); } std::ostream& operator<<(std::ostream& ostream, const NGFragmentItem& item) { ostream << "{"; switch (item.Type()) { case NGFragmentItem::kText: ostream << "Text " << item.StartOffset() << "-" << item.EndOffset() << " " << (IsLtr(item.ResolvedDirection()) ? "LTR" : "RTL"); break; case NGFragmentItem::kGeneratedText: ostream << "GeneratedText \"" << item.GeneratedText() << "\""; break; case NGFragmentItem::kLine: ostream << "Line #descendants=" << item.DescendantsCount() << " " << (IsLtr(item.BaseDirection()) ? "LTR" : "RTL"); break; case NGFragmentItem::kBox: ostream << "Box #descendants=" << item.DescendantsCount(); if (item.IsAtomicInline()) { ostream << " AtomicInline" << (IsLtr(item.ResolvedDirection()) ? "LTR" : "RTL"); } break; } ostream << " "; switch (item.StyleVariant()) { case NGStyleVariant::kStandard: ostream << "Standard"; break; case NGStyleVariant::kFirstLine: ostream << "FirstLine"; break; case NGStyleVariant::kEllipsis: ostream << "Ellipsis"; break; } return ostream << "}"; } std::ostream& operator<<(std::ostream& ostream, const NGFragmentItem* item) { if (!item) return ostream << "<null>"; return ostream << *item; } } // namespace blink
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
06dd0750fbba1beb40af1a1fdfdacca4449ac61b
34f2081361c2cdb28649db5c311b23ae45729867
/Codeforces/456b.cpp
a39ccfd2b5e6d7e59924b095b93e763e27a4ac61
[]
no_license
shashank21j/CompetitiveProgramming
bd7d1516bda0047162293f62e78a8f3134021454
5e905ad7f59f36541baaa669391eba667f291a45
refs/heads/master
2022-02-14T08:12:05.656586
2022-01-30T02:56:15
2022-01-30T02:56:15
14,283,517
4
1
null
null
null
null
UTF-8
C++
false
false
324
cpp
#include<bits/stdc++.h> using namespace std; int main() { string s; cin >> s; if (s.length() == 1) { int n = s[0] - 48; if (n%4 == 0) cout<<"4\n"; else cout<<"0\n"; } else { int a = s[s.length()-1] - 48; int b = s[s.length()-2] - 48; if ((b*10 + a)%4 == 0) cout<<"4\n"; else cout<<"0\n"; } return 0; }
[ "shashank@hackerrank.com" ]
shashank@hackerrank.com
804fce7a8816f4385f5db9ab1177c0ec82905228
b2c271bb090655cfd2859fd1992d4992ccc4b0f7
/halley/src/plugins/asio/src/asio_tcp_network_service.cpp
eaa4e364f2b5c0ce2b3cb8171a59d034d1015236
[ "Apache-2.0" ]
permissive
AWhitehouseDeveloper/HalleyEngine
acaf3fe2263935c7db05da648bb848923e6ed711
bf22d1ce1fc5df84e3426b3c423b87874bb49e65
refs/heads/main
2023-07-15T02:07:13.063836
2021-08-25T04:39:34
2021-08-25T04:39:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,233
cpp
#include "asio_tcp_network_service.h" #include "halley/support/logger.h" #include "halley/text/string_converter.h" using namespace Halley; AsioTCPNetworkService::AsioTCPNetworkService(int port, IPVersion version) : work(service) , localEndpoint(version == IPVersion::IPv4 ? asio::ip::tcp::v4() : asio::ip::tcp::v6(), static_cast<unsigned short>(port)) , acceptor(service, localEndpoint) { Expects(port == 0 || port > 1024); Expects(port < 65536); } void AsioTCPNetworkService::update() { bool needsPoll; do { needsPoll = false; for (auto& conn: activeConnections) { needsPoll |= conn->needsPolling(); conn->update(); } service.poll(); } while (needsPoll); activeConnections.erase(std::remove_if(activeConnections.begin(), activeConnections.end(), [] (const std::shared_ptr<IConnection>& conn) { return conn->getStatus() == ConnectionStatus::Closed; }), activeConnections.end()); } void AsioTCPNetworkService::setAcceptingConnections(bool accepting) { if (acceptingConnection != accepting) { acceptingConnection = accepting; if (accepting) { acceptingSocket = TCPSocket(service); acceptor.async_accept(acceptingSocket.value(), [this] (const boost::system::error_code& ec) { if (ec) { Logger::logError("Error accepting connection: " + ec.message()); } else { if (acceptingConnection) { onConnectionAccepted(); } } }); } } } std::shared_ptr<IConnection> AsioTCPNetworkService::tryAcceptConnection() { if (!pendingConnections.empty()) { auto res = pendingConnections.front(); pendingConnections.erase(pendingConnections.begin()); return res; } else { return {}; } } std::shared_ptr<IConnection> AsioTCPNetworkService::connect(String address, int port) { auto conn = std::make_shared<AsioTCPConnection>(service, address, port); activeConnections.push_back(conn); return conn; } void AsioTCPNetworkService::onConnectionAccepted() { // Move socket into a new connection pendingConnections.push_back(std::make_shared<AsioTCPConnection>(service, std::move(acceptingSocket.value()))); activeConnections.push_back(pendingConnections.back()); acceptingSocket = {}; // Accept more acceptingConnection = false; setAcceptingConnections(true); }
[ "AWhitehouse@student.neumont.edu" ]
AWhitehouse@student.neumont.edu
229a8d352725ef54519cbf20fc90db72b02a2fc4
c7468aedc176931b46f5b97e1d2ec4c372bf50dd
/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_volkhan.cpp
f410fc63e5de97572014d6e686f1b017d5ef5ada
[]
no_license
planee/new
68069f16dcb49714a16c2077d22e0f563c600e59
d6afe0cd87c5e8423855b909682271ad075d6479
refs/heads/master
2021-05-10T13:54:52.148537
2016-07-07T12:51:07
2016-07-07T12:51:07
null
0
0
null
null
null
null
ISO-8859-10
C++
false
false
13,028
cpp
/* * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * * Copyright (C) 2010-2015 QuantumCore <http://vk.com/quantumcore> * * Copyright (C) 2010-2012 MaNGOS project <http://getmangos.com> * */ #include "ScriptMgr.h" #include "QuantumCreature.h" #include "Player.h" #include "SpellInfo.h" #include "halls_of_lightning.h" enum Texts { SAY_AGGRO = -1602032, SAY_SLAY_1 = -1602033, SAY_SLAY_2 = -1602034, SAY_SLAY_3 = -1602035, SAY_DEATH = -1602036, SAY_STOMP_1 = -1602037, SAY_STOMP_2 = -1602038, SAY_FORGE_1 = -1602039, SAY_FORGE_2 = -1602040, EMOTE_TO_ANVIL = -1602041, EMOTE_SHATTER = -1602042, }; enum Spells { SPELL_HEAT_5N = 52387, SPELL_HEAT_5H = 59528, SPELL_SHATTERING_STOMP_5N = 52237, SPELL_SHATTERING_STOMP_5H = 59529, SPELL_TEMPER = 52238, SPELL_TEMPER_DUMMY = 52654, //SPELL_TEMPER_VISUAL = 52661, //summons GO SPELL_SUMMON_MOLTEN_GOLEM = 52405, SPELL_BLAST_WAVE = 23113, SPELL_IMMOLATION_STRIKE_5N = 52433, SPELL_IMMOLATION_STRIKE_5H = 59530, SPELL_SHATTER_5N = 52429, SPELL_SHATTER_5H = 59527, }; enum Misc { POINT_ID_ANVIL = 0, MAX_GOLEM = 2, DATA_SHATTER_RESISTANT = 2042, }; class boss_volkhan : public CreatureScript { public: boss_volkhan() : CreatureScript("boss_volkhan") { } struct boss_volkhanAI : public QuantumBasicAI { boss_volkhanAI(Creature* creature) : QuantumBasicAI(creature) { instance = creature->GetInstanceScript(); } InstanceScript* instance; std::list<uint64> m_lGolemGUIDList; bool HasTemper; bool IsStriking; bool CanShatterGolem; bool Move; uint8 GolemsShattered; uint32 PauseTimer; uint32 ShatteringStompTimer; uint32 ShatterTimer; uint32 CheckTimer; uint32 CheckZ; uint32 HealthAmountModifier; void Reset() { IsStriking = false; HasTemper = false; CanShatterGolem = false; Move = false; PauseTimer = 1500; ShatteringStompTimer = 30000; ShatterTimer = 3000; CheckTimer = 1100; CheckZ = 1000; GolemsShattered = 0; HealthAmountModifier = 1; DespawnGolem(); DoCast(me, SPELL_UNIT_DETECTION_WOTLK); me->SetReactState(REACT_AGGRESSIVE); if (!me->HasUnitMovementFlag(MOVEMENTFLAG_WALKING)) me->SetWalk(true); instance->SetData(TYPE_VOLKHAN, NOT_STARTED); } void EnterToBattle(Unit* /*who*/) { DoSendQuantumText(SAY_AGGRO, me); me->SetPowerType(POWER_RAGE); me->SetPower(POWER_RAGE, POWER_QUANTITY_MAX); instance->SetData(TYPE_VOLKHAN, IN_PROGRESS); } void AttackStart(Unit* who) { if (me->Attack(who, true)) { me->AddThreat(who, 0.0f); me->SetInCombatWith(who); who->SetInCombatWith(me); if (!HasTemper) me->GetMotionMaster()->MoveChase(who); } } void JustDied(Unit* /*killer*/) { DoSendQuantumText(SAY_DEATH, me); DespawnGolem(); instance->SetData(TYPE_VOLKHAN, DONE); } void KilledUnit(Unit* /*victim*/) { DoSendQuantumText(RAND(SAY_SLAY_1, SAY_SLAY_2, SAY_SLAY_3), me); } void DespawnGolem() { if (m_lGolemGUIDList.empty()) return; for (std::list<uint64>::const_iterator itr = m_lGolemGUIDList.begin(); itr != m_lGolemGUIDList.end(); ++itr) { if (Creature* temp = Unit::GetCreature(*me, *itr)) { if (temp->IsAlive()) temp->DespawnAfterAction(); } } m_lGolemGUIDList.clear(); } void ShatterGolem() { if (m_lGolemGUIDList.empty()) return; for (std::list<uint64>::const_iterator itr = m_lGolemGUIDList.begin(); itr != m_lGolemGUIDList.end(); ++itr) { if (Creature* golem = Unit::GetCreature(*me, *itr)) { // only shatter brittle golems if (golem->IsAlive() && golem->GetEntry() == NPC_BRITTLE_GOLEM) { golem->CastSpell(golem, DUNGEON_MODE(SPELL_SHATTER_5N, SPELL_SHATTER_5H), false); GolemsShattered++; } } } } void JustSummoned(Creature* summoned) { if (summoned->GetEntry() == NPC_MOLTEN_GOLEM) { m_lGolemGUIDList.push_back(summoned->GetGUID()); if (Unit* target = SelectTarget(TARGET_RANDOM, 0)) summoned->AI()->AttackStart(target); //useless at this position //summoned->CastSpell(summoned, DUNGEON_MODE(SPELL_HEAT_N, SPELL_HEAT_H), false, NULL, NULL, me->GetGUID()); } } uint32 GetData(uint32 data) const { if (data == DATA_SHATTER_RESISTANT) return GolemsShattered; return 0; } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; if (me->HasUnitState(UNIT_STATE_CASTING)) return; if (CheckZ <= diff) { if (me->GetPositionZ() < 50.0f) { EnterEvadeMode(); return; } CheckZ = 1000; } else CheckZ -= diff; if (IsStriking && !Move) { if (PauseTimer <= diff) { if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() != CHASE_MOTION_TYPE) { if (me->GetVictim()) me->GetMotionMaster()->MoveChase(me->GetVictim()); } HasTemper = false; IsStriking = false; PauseTimer = 1500; } else PauseTimer -= diff; return; } // ShatteringStomp all the Time, if (!HasTemper && !Move) { if (ShatteringStompTimer <= diff) { DoSendQuantumText(RAND(SAY_STOMP_1, SAY_STOMP_2), me); DoCast(me, DUNGEON_MODE(SPELL_SHATTERING_STOMP_5N, SPELL_SHATTERING_STOMP_5H)); if (Creature* temp = me->FindCreatureWithDistance(NPC_BRITTLE_GOLEM, 250.f)) { DoSendQuantumText(EMOTE_SHATTER, me); CanShatterGolem = true; } ShatteringStompTimer = 30000; } else ShatteringStompTimer -= diff; } // Shatter Golems 3 seconds after Shattering Stomp if (CanShatterGolem) { if (ShatterTimer <= diff) { ShatterGolem(); ShatterTimer = 3000; CanShatterGolem = false; } else ShatterTimer -= diff; } Creature* pAnvil = instance->instance->GetCreature(instance->GetData64(DATA_VOLKHAN_ANVIL)); float fX, fY, fZ; me->GetContactPoint(pAnvil, fX, fY, fZ, INTERACTION_DISTANCE); // Health check if (!CanShatterGolem && me->HealthBelowPct(100 - 20 * HealthAmountModifier) && !Move) { ++HealthAmountModifier; if (me->IsNonMeleeSpellCasted(false)) me->InterruptNonMeleeSpells(false); DoSendQuantumText(RAND(SAY_FORGE_1, SAY_FORGE_2), me); if (me->GetDistance(pAnvil) > 5) { me->GetMotionMaster()->Clear(); me->SetReactState(REACT_PASSIVE); me->GetMotionMaster()->MovePoint(5, fX, fY, fZ); } DoSendQuantumText(EMOTE_TO_ANVIL, me); Move = true; } if (me->IsWithinMeleeRange(pAnvil,5) && Move) { me->GetMotionMaster()->Clear(); me->SetReactState(REACT_AGGRESSIVE); HasTemper = true; Move = false; for (uint8 i = 0; i < MAX_GOLEM; ++i) DoCast(SPELL_SUMMON_MOLTEN_GOLEM); DoCast(SPELL_TEMPER); IsStriking = true; } if (me->GetMotionMaster()->GetCurrentMovementGeneratorType()!=POINT_MOTION_TYPE && Move) //if (CheckTimer<=diff) { me->GetMotionMaster()->MovePoint(5,fX,fY,fZ); CheckTimer=1100; } //else //CheckTimer-=diff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const { return new boss_volkhanAI(creature); } }; class npc_molten_golem : public CreatureScript { public: npc_molten_golem() : CreatureScript("npc_molten_golem") { } struct npc_molten_golemAI : public QuantumBasicAI { npc_molten_golemAI(Creature* creature) : QuantumBasicAI(creature) {} bool IsFrozen; uint32 BlastTimer; uint32 DeathDelayTimer; uint32 ImmolationTimer; void Reset() { IsFrozen = false; BlastTimer = 20000; DeathDelayTimer = 0; ImmolationTimer = 5000; } void AttackStart(Unit* who) { if (me->Attack(who, true)) { me->AddThreat(who, 0.0f); me->SetInCombatWith(who); who->SetInCombatWith(me); if (!IsFrozen) me->GetMotionMaster()->MoveChase(who); } } void DamageTaken(Unit* /*pDoneBy*/, uint32 &damage) { if (damage > me->GetHealth()) { me->UpdateEntry(NPC_BRITTLE_GOLEM); me->SetHealth(1); damage = 0; me->RemoveAllAuras(); me->AttackStop(); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED); if (me->IsNonMeleeSpellCasted(false)) me->InterruptNonMeleeSpells(false); if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() == CHASE_MOTION_TYPE) me->GetMotionMaster()->MovementExpired(); IsFrozen = true; } } void SpellHit(Unit* /*ņaster*/, const SpellInfo* spell) { if (spell->Id == SPELL_SHATTER_5N || spell->Id == SPELL_SHATTER_5H) { if (me->GetEntry() == NPC_BRITTLE_GOLEM) me->DespawnAfterAction(); } } void UpdateAI(const uint32 diff) { if (!UpdateVictim() || IsFrozen) return; if (BlastTimer <= diff) { DoCast(me, SPELL_BLAST_WAVE); BlastTimer = 20000; } else BlastTimer -= diff; if (ImmolationTimer <= diff) { DoCastVictim(DUNGEON_MODE(SPELL_IMMOLATION_STRIKE_5N, SPELL_IMMOLATION_STRIKE_5H)); ImmolationTimer = 5000; } else ImmolationTimer -= diff; DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* creature) const { return new npc_molten_golemAI(creature); } }; class achievement_shatter_resistant : public AchievementCriteriaScript { public: achievement_shatter_resistant() : AchievementCriteriaScript("achievement_shatter_resistant") { } bool OnCheck(Player* /*source*/, Unit* target) { return target && target->GetAI()->GetData(DATA_SHATTER_RESISTANT) < 5; } }; void AddSC_boss_volkhan() { new boss_volkhan(); new npc_molten_golem(); new achievement_shatter_resistant(); }
[ "87046964@qq.com" ]
87046964@qq.com
5f496808a2248aa4d82847303eeb7acfcc29bc84
8947812c9c0be1f0bb6c30d1bb225d4d6aafb488
/02_Library/Include/XMCocos2D/support/CCProfiling.h
cc3770ab84bd34274d7b09cf6f69624d5275e4dc
[ "MIT" ]
permissive
alissastanderwick/OpenKODE-Framework
cbb298974e7464d736a21b760c22721281b9c7ec
d4382d781da7f488a0e7667362a89e8e389468dd
refs/heads/master
2021-10-25T01:33:37.821493
2016-07-12T01:29:35
2016-07-12T01:29:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,919
h
/* ----------------------------------------------------------------------------------- * * File CCProfiling.h * Ported By Young-Hwan Mun * Contact xmsoft77@gmail.com * * ----------------------------------------------------------------------------------- * * Copyright (c) 2010-2013 XMSoft * Copyright (c) 2010-2013 cocos2d-x.org * Copyright (c) 2010 Stuart Carnie * * http://www.cocos2d-x.org * * ----------------------------------------------------------------------------------- * * 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. * * ----------------------------------------------------------------------------------- */ #ifndef __CCProfiling_h__ #define __CCProfiling_h__ #include "../cocoa/CCDictionary.h" #include "../support/CCTime.h" NS_CC_BEGIN /** * @addtogroup global * @{ */ class CCProfilingTimer; /** * CCProfiler * cocos2d builtin profiler. * * To use it, enable set the CC_ENABLE_PROFILERS=1 in the ccConfig.h file * @js NA * @lua NA */ class CCProfiler : public CCObject { public : virtual ~CCProfiler ( KDvoid ); static CCProfiler* sharedProfiler ( KDvoid ); public : virtual KDbool init ( KDvoid ); /** display the timers */ KDvoid displayTimers ( KDvoid ); /** Creates and adds a new timer */ CCProfilingTimer* createAndAddTimerWithName ( const KDchar* szTimerName ); /** releases a timer */ KDvoid releaseTimer ( const KDchar* szTimerName ); /** releases all timers */ KDvoid releaseAllTimers ( KDvoid ); public : CCDictionary* m_pActiveTimers; }; /** * @js NA * @lua NA */ class CCProfilingTimer : public CCObject { public : CCProfilingTimer ( KDvoid ); virtual ~CCProfilingTimer ( KDvoid ); public : virtual KDbool initWithName ( const KDchar* szTimerName ); const KDchar* description ( KDvoid ); struct KDTimeval* getStartTime ( KDvoid ) { return &m_tStartTime; }; /** resets the timer properties */ KDvoid reset ( KDvoid ); public : std::string m_sNameStr; KDint m_nNumberOfCalls; KDint m_nAverageTime1; KDint m_nAverageTime2; KDint64 m_nTotalTime; KDint m_nMinTime; KDint m_nMaxTime; struct KDTimeval m_tStartTime; }; extern KDvoid CCProfilingBeginTimingBlock ( const KDchar* szTimerName ); extern KDvoid CCProfilingEndTimingBlock ( const KDchar* szTimerName ); extern KDvoid CCProfilingResetTimingBlock ( const KDchar* szTimerName ); /** * cocos2d profiling categories * used to enable / disable profilers with granularity */ extern KDbool kCCProfilerCategorySprite; extern KDbool kCCProfilerCategoryBatchSprite; extern KDbool kCCProfilerCategoryParticles; // end of global group /// @} NS_CC_END #endif // __CCProfiling_h__
[ "mcodegeeks@gmail.com" ]
mcodegeeks@gmail.com
b4a65172c643117499b6e5b1ce757572c2b69d54
3aa0b032cb20638fd9df28b7c15ddb5f5e876f25
/src/cc/chunk/ChunkServer.h
9ca9eeefd38898e3b92167b855c7396bcff2e5d0
[ "Apache-2.0" ]
permissive
nzinfo/my-kfs-022
41eeceee3adc640bcaa16bae4870d6217e9f325d
739a92f9bfce3bb94b41853608a693eb224fa16c
refs/heads/master
2021-01-10T19:20:06.276474
2010-07-15T09:38:19
2010-07-15T09:38:19
35,748,843
0
0
null
null
null
null
UTF-8
C++
false
false
2,692
h
//---------------------------------------------------------- -*- Mode: C++ -*- // $Id: ChunkServer.h 92 2008-07-21 21:20:48Z sriramsrao $ // // Created 2006/03/16 // Author: Sriram Rao // // Copyright 2008 Quantcast Corp. // Copyright 2006-2008 Kosmix Corp. // // This file is part of Kosmos File System (KFS). // // Licensed under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // // //---------------------------------------------------------------------------- #ifndef _CHUNKSERVER_H #define _CHUNKSERVER_H #include "libkfsIO/Acceptor.h" #include "libkfsIO/DiskManager.h" #include "libkfsIO/EventManager.h" #include "libkfsIO/NetManager.h" #include "libkfsIO/Globals.h" #include "ChunkManager.h" #include "ClientManager.h" #include "ClientSM.h" #include "MetaServerSM.h" #include "RemoteSyncSM.h" namespace KFS { class ChunkServer { public: ChunkServer() : mOpCount(0), mKickNetThread(false) { } ; void Init(); void MainLoop(int clientAcceptPort); bool IsLocalServer(const ServerLocation &location) const { return mLocation == location; } RemoteSyncSMPtr FindServer(const ServerLocation &location, bool connect = true); void RemoveServer(RemoteSyncSM *target); std::string GetMyLocation() const { return mLocation.ToString(); } void ToggleNetThreadKicking(bool v) { mKickNetThread = v; } bool NeedToKickNetThread() { return mKickNetThread; } void OpInserted() { mOpCount++; } void OpFinished() { mOpCount--; if (mOpCount < 0) mOpCount = 0; } int GetNumOps() const { return mOpCount; } private: /// 接收client请求的端口 int mClientAcceptPort; // 系统中操作(op)计数器 int mOpCount; /// Unknown!! bool mKickNetThread; // 当前主机的ServerLocation ServerLocation mLocation; /// 用于向远端服务器发送消息和处理远端服务器返回的信息,处理完成后调用 /// KFS::SubmitOpResponse()函数. /// @note 每一个server会对应一个RemoteSyncSM std::list<RemoteSyncSMPtr> mRemoteSyncers; }; extern void verifyExecutingOnNetProcessor(); extern void verifyExecutingOnEventProcessor(); extern void StopNetProcessor(int status); extern ChunkServer gChunkServer; } #endif // _CHUNKSERVER_H
[ "fifywang@c3a0cf16-f052-ac97-a8a5-60cda90d0a3d" ]
fifywang@c3a0cf16-f052-ac97-a8a5-60cda90d0a3d
946d52c4d9dc287a4b30bf67c7f7fe4ff25ca561
f6b678499969cf807fad25ebcd098c0cce272d66
/src/ui/painters/painteritem.h
997e1d44ce2a721e0b58dfb9f00d9d2d8a80ce8b
[]
no_license
Louis-Simon22/random-map-generation
c1fc6bb12a8f9d14c858c42a2b53e6d83518cd48
523cf5fc171f485dc42328656b2463eb2b021fd6
refs/heads/master
2022-11-25T20:16:53.189403
2020-08-04T20:38:33
2020-08-04T20:38:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
357
h
#ifndef GRAPHENTITYPAINTER_H #define GRAPHENTITYPAINTER_H #include <QQuickItem> namespace how { namespace ui { class PainterItem : public QQuickItem { Q_OBJECT public: PainterItem(QQuickItem *parent); virtual ~PainterItem() override = 0; signals: void updateOnGuiThread(); }; } // namespace ui } // namespace how #endif // GRAPHENTITYPAINTER_H
[ "louissimonmcnicoll@gmail.com" ]
louissimonmcnicoll@gmail.com
0223d98117efdaff8132e64ab0cd5c794ab37ce5
7b79b6f0a96554ac41aba7b739b9bd93b3f57c45
/A1091.cpp
774e7a74a7db71f9fcf442d2c2e7263d9786082b
[]
no_license
lrscy/PAT
f80ff57995821b493e8b98c72de56cdf13ab8994
831bb1f462aad5a6d4ab622bc04c4393832df868
refs/heads/master
2021-01-10T07:38:08.739617
2016-02-24T15:23:21
2016-02-24T15:23:21
52,203,012
0
0
null
null
null
null
UTF-8
C++
false
false
1,342
cpp
#include <bits/stdc++.h> using namespace std; const int MAXN = 1e6 + 10; struct Node { int x, y, z; Node() {} Node( int _x, int _y, int _z ) : x( _x ), y( _y ), z( _z ) {} }que[MAXN]; int dx[10] = { 0, 0, 0, 0, -1, 1 }; int dy[10] = { -1, 0, 1, 0, 0, 0 }; int dz[10] = { 0, 1, 0, -1, 0, 0 }; int a[80][1300][150]; int n, m, p, t, ans; bool check( int x, int y, int z ) { if( 0 <= x && x < p && 0 <= y && y < n && 0 <= z && z < m ) return true; return false; } int bfs( int x, int y, int z ) { int mf, me, ret = 0; mf = me = 0; que[me++] = Node( x, y, z ); a[x][y][z] = 0; while( mf != me ) { Node u = que[mf++]; if( mf >= MAXN ) mf -= MAXN; ++ret; for( int i = 0; i < 6; ++i ) { int tx = u.x + dx[i]; int ty = u.y + dy[i]; int tz = u.z + dz[i]; if( check( tx, ty, tz ) && a[tx][ty][tz] == 1 ) { a[tx][ty][tz] = 0; que[me++] = Node( tx, ty, tz ); if( me >= MAXN ) me -= MAXN; } } } return ret >= t ? ret : 0; } int main() { ans = 0; scanf( "%d%d%d%d", &n, &m, &p, &t ); for( int i = 0; i < p; ++i ) { for( int j = 0; j < n; ++j ) for( int k = 0; k < m; ++k ) scanf( "%d", &a[i][j][k] ); } for( int i = 0; i < p; ++i ) { for( int j = 0; j < n; ++j ) for( int k = 0; k < m; ++k ) if( a[i][j][k] == 1 ) ans += bfs( i, j, k ); } printf( "%d\n", ans ); return 0; }
[ "ruosenlee@gmail.com" ]
ruosenlee@gmail.com
f1a52cb7e13da866406250388b62d5256eb970cb
cfad81d6574be873c35038b272d60ee66ffa292a
/pathfinding/board/board.h
45867562625b15e79bece948c7e6228cf44be34d
[]
no_license
dundeegames/pathfinding-coursework-demo
f3d6035f29bf025ab1c5001c6e61ef0c6742a58c
1aefb1f64d995fdb5ae914ab67cb4c91052b2176
refs/heads/master
2020-06-11T23:21:15.763132
2014-12-12T14:59:46
2014-12-12T14:59:46
75,613,010
0
0
null
null
null
null
UTF-8
C++
false
false
1,190
h
#ifndef BOARD_H #define BOARD_H #include "../ui/gui.h" #include "node.h" #include <iostream> #include <fstream> using namespace std; #define BOARD_X 20 #define BOARD_Y 20 #define B_EMPTY 1000 #define B_WALL 999 #define B_START 0 #define B_END 1001 enum MapType {MAP_A, MAP_L}; class Board { public: Board(); ~Board(); void init(Gui* ui_, int xpos_, int ypos_); void loadMap(char* file_); // load external map void loadMap(MapType type_); // load internal map void setI(int x, int y, int i_); void setFGH(int x, int y, int g_, int h_); //void setParent(int x, int y, int px, int py); int getI(int x, int y); int getF(int x, int y); //int getH(int x, int y); void updateData(int nodes_, int mcur_, int mmax_); void drawMap(); void drawIndex(int x, int y, int i_); void clearBoard(); Node getNode(int x, int y); private: int sizeNcur; // Current and Max size of wset in Numer of nodes int sizeNmax; int sizeBcur; // Current and Max size of wset in Bytes int sizeBmax; void drawData(); // displays values of cur and max wset // Lee -------------------- Node nodeMap[BOARD_X][BOARD_Y]; int xPosition; int yPosition; Gui* ui; }; #endif BOARD_H
[ "jiri.klic@dundeegames.com" ]
jiri.klic@dundeegames.com
91805f3405e63cf5399c310e03863893392fb94c
5b9bfdec4cec3a8e774b0aa0579f74df86eda824
/arduino/Board/CarController/CarController.ino
a55db0e44ea7366a0e02681dfe5555ca16eeb1ca
[]
no_license
joancafom/carrot
88b4edf36f1fa4640d11361444a86d60d7aaf393
c10b5f018972e892af3937bde7c67c271f5f6f8e
refs/heads/master
2023-04-10T09:41:03.012896
2019-09-02T11:17:07
2019-09-02T11:17:07
157,711,369
0
1
null
2023-03-24T22:48:03
2018-11-15T12:56:28
Java
UTF-8
C++
false
false
4,336
ino
/* * Program to be executed on the Arduino Board. * * Constantly listens to the Serial Port, where * instructions coming from the computer are * sent. When an action is received, * the program first validates it and proceeds * to activate the corresponding pins attatched * to the RC Car remote controller. * * The provided specification sheet provides * more details about the hardware architecture. * * RC Car remote controller has 4 physical buttons: * S1, S2, S3, S4 * * * /------ SUPPORTED ACTIONS ------/ * | | * | 'Izquierda' ==> 0, | * | 'Centro' ==> 1, | * | 'Derecha' ==> 2, | * | 'Centro-Gas' ==> 3, | * | 'Freno' ==> 4, | * | | * /-------------------------------/ * * /----- ACTIONs to BUTTONs -----/ * | | * | 'Izquierda' ==> S2, | * | 'Centro' ==> null, | * | 'Derecha' ==> S3, | * | 'Centro-Gas' ==> S1, | * | 'Freno' ==> S4, | * | | * /------------------------------/ * * /------- BUTTONs to PINs ------/ * | | * | S1 ==> 13, | * | S2 ==> 11, | * | S3 ==> 9, | * | S4 ==> 7, | * | | * /------------------------------/ * */ // ----- CONSTANTS ----- // BUTTONs to PINs const unsigned int S1 = 13; const unsigned int S2 = 11; const unsigned int S3 = 9; const unsigned int S4 = 7; // ms to wait for a new action to come through // SerialPort const long waitingInverval = 500; // ----- COMMON VARS ----- // Last action performed static char lastAction; // Last moment an action took place static unsigned long previousMillis = 0; void setup() { // Initialize Serial Communications on 9600 Serial.begin(9600); // All PINs are outputs pinMode(S1, OUTPUT); pinMode(S2, OUTPUT); pinMode(S3, OUTPUT); pinMode(S4, OUTPUT); } void loop() { // Current time unsigned long currentMillis = millis(); // If the PC has sent an action, we need to perform // it if(Serial.available()>0){ // Read the data on the SerialPort // and update the last time // we received an action char action = Serial.read(); previousMillis = currentMillis; // Assert instruction correctness. // We only truly perform an action if it // wasn't executed right before (as in that // case, its corresponding output PINs are // still enabled) if(action >= '0' && action < '5' && lastAction != action) { lastAction = action; // We need to disable all outputs to ensure // we only light the correct ones up. disableOutputs(action); if(action == '0'){ // Izquierda digitalWrite(S2, HIGH); // Ensure the physical mechanisms have // time to execute the action delay(125); }else if(action == '1'){ // Centro // No-op ; }else if(action == '2'){ // Derecha digitalWrite(S3, HIGH); delay(125); }else if(action == '3'){ // Centro-Gas digitalWrite(S1, HIGH); delay(62); } else if(action == '4'){ // Freno digitalWrite(S4, HIGH); delay(31); } } // If no action is received, we keep the PINs' curent status // for a time no longer than the permitted. After that time // expires, we disable all PINs. }else if (currentMillis - previousMillis >= waitingInverval) { previousMillis = currentMillis; disableOutputs('\0'); // Null Character lastAction = '\0'; } } // Set all output PINs to LOW void disableOutputs(char action){ if(action != '3'){ // Izquierda digitalWrite(S2, LOW); // Derecha digitalWrite(S3, LOW); } // Centro-Gas digitalWrite(S1, LOW); // Freno digitalWrite(S4, LOW); }
[ "joscarfom@alum.us.es" ]
joscarfom@alum.us.es
93b39cb9daeeef9cdd3b8f3d9c9fe04f6988c56a
cb4fd9762920fe2ad80c516cc203dcd634419b7b
/include/PHO_PathTracer.h
4d0130d5c39396eae0991252d60183a487fd590f
[]
no_license
Burnung/TestOpenGL
fb79e451c605dee1078c344d6f8a2e9e494d294d
0d844761eacadaea2d51f4391f141e94e2f2fdda
refs/heads/master
2020-03-28T06:37:10.523171
2018-09-07T16:36:37
2018-09-07T16:36:37
147,847,756
0
0
null
null
null
null
GB18030
C++
false
false
970
h
#ifndef PHO_PATHTRACER_H #define PHO_PATHTRACER_H #include"gl_util.h" #include<glm\vec3.hpp> #include"GL_BaseType.h" #include"PHO_Random.h" //#define PATHTRACER_USE_GPU //是否使用GPU加速 class PHO_ViewPort; class PHO_PahtTracer{ GL_DECLARE_SINGLETON(PHO_PahtTracer); public: ~PHO_PahtTracer(); void Init(PHO_ViewPort*); //void SetViewPort() void GoTrace(int samples); void SaveRet(); void Update(); int GetMaxDepth(); void Save2BMP(const char* filename ); private: PHO_ViewPort *m_ViewPort; BYTE *m_RetBMP; int m_WindowWidth; int m_WindowHeight; glm::vec3 m_CamPos; glm::vec3 m_CamTarVec; glm::vec3 m_CamYVec; glm::vec3 m_CamXVec; float m_Width_recp; float m_Height_recp; float m_FovS; float m_Ratio; float m_X_Spacing; float m_X_Spacing_Half; float m_Y_Spacing; float m_Y_Spacing_Half; private: void ClearRetBuffer(); void Clear(); GL_Ray GetRay(int x,int y); void WriteColor(glm::vec3 &col, int x, int y); }; #endif
[ "zhangboning234@126.com" ]
zhangboning234@126.com
1a2b6d987ce3ae4b8981dbdc7337ed25090deaa2
97fde28997b618180cfa5dd979b142fd54dd2105
/core/dep/acelite/ace/IO_SAP.h
aaff9f6901ea058e143d5c71d01050a6e2e298d9
[]
no_license
Refuge89/sunwell-2
5897f4e78c693e791e368761904e79d2b7af20da
f01a89300394065f33eaec799c8779c2cac5c320
refs/heads/master
2020-12-31T05:55:43.496145
2016-02-16T20:46:50
2016-02-16T20:46:50
80,622,543
1
0
null
2017-02-01T13:30:06
2017-02-01T13:30:06
null
UTF-8
C++
false
false
2,064
h
// -*- C++ -*- //============================================================================= /** * @file IO_SAP.h * * @author Doug Schmidt */ //============================================================================= #ifndef ACE_IO_SAP_H #define ACE_IO_SAP_H #include /**/ "ace/pre.h" #include "ace/Flag_Manip.h" #include "ace/os_include/sys/os_types.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) # pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ ACE_BEGIN_VERSIONED_NAMESPACE_DECL /** * @class ACE_IO_SAP * * @brief Defines the methods for the base class of the ACE_IO_SAP * abstraction, which includes ACE_FILE and ACE_DEV. */ class ACE_Export ACE_IO_SAP { public: enum { /// Be consistent with Winsock INVALID_HANDLE = -1 }; /// Default dtor. ~ACE_IO_SAP (void); /// Interface for ioctl. int control (int cmd, void *) const; // = Common I/O handle options related to files. /** * Enable asynchronous I/O (ACE_SIGIO), urgent data (ACE_SIGURG), * non-blocking I/O (ACE_NONBLOCK), or close-on-exec (ACE_CLOEXEC), * which is passed as the @a value. */ int enable (int value) const; /** * Disable asynchronous I/O (ACE_SIGIO), urgent data (ACE_SIGURG), * non-blocking I/O (ACE_NONBLOCK), or close-on-exec (ACE_CLOEXEC), * which is passed as the @a value. */ int disable (int value) const; /// Get the underlying handle. ACE_HANDLE get_handle (void) const; /// Set the underlying handle. void set_handle (ACE_HANDLE handle); /// Dump the state of an object. void dump (void) const; /// Declare the dynamic allocation hooks. ACE_ALLOC_HOOK_DECLARE; protected: /// Ensure that ACE_IO_SAP is an abstract base class. ACE_IO_SAP (void); private: /// Underlying I/O handle. ACE_HANDLE handle_; }; ACE_END_VERSIONED_NAMESPACE_DECL #if defined (__ACE_INLINE__) #include "ace/IO_SAP.inl" #endif /* __ACE_INLINE__ */ #include /**/ "ace/post.h" #endif /* ACE_IO_SAP_H */
[ "root@wow.playstar.se" ]
root@wow.playstar.se
a6a66c27a64807c9ccffed53c06e58921b8ecb84
d33268b98151cd2899d338a2b7da362fe9ac32e8
/ParProg/ParProg/main.cpp
8cf5136f2c06de17ea5e33459c3152a3d1af1730
[]
no_license
Edvard-Hagerup-Grieg/UNN-ParallelProg
0f34fb56f4c2eb7fd6a56924f9bfa2ff87a78405
4737874442e7cf60cad4f98fa53ade2ce05552fb
refs/heads/master
2020-05-19T11:52:51.461773
2019-05-05T10:12:15
2019-05-05T10:12:15
185,001,708
0
0
null
null
null
null
UTF-8
C++
false
false
3,878
cpp
#include <iostream> #include "omp.h" #include "tbb/task_scheduler_init.h" #include "tbb/parallel_for.h" #include "tbb/blocked_range.h" using namespace std; using namespace tbb; class CannonAlgorithm { const double *AM, *BM; double *const CM; int const N; int const B; public: CannonAlgorithm(double *AM, double *BM, double *CM, int N, int B) : AM(AM), BM(BM), CM(CM), N(N), B(B) {} void operator()(const blocked_range<int>& r) const { int begin = r.begin(), end = r.end(); for (int block = begin; block != end; block++) { int ib = block / B; int jb = block - ib * B; int jj = (ib + jb) % B; for (int k = 0; k < B; k++) { for (int mi = ib * (N / B); mi < (ib + 1)*(N / B); mi++) for (int mj = jb * (N / B); mj < (jb + 1)*(N / B); mj++) { double SUM = 0.0; for (int mk = jj * (N / B); mk < (jj + 1)*(N / B); mk++) SUM += AM[mi*N + mk] * BM[mk*N + mj]; CM[mi*N + mj] += SUM; } jj = (jj + 1) % B; } } } }; double CannonAlgorithm_Seq(double * AM, double * BM, double * CM, int N, int B) { double start = 0, finish = 0; start = omp_get_wtime(); for (int block = 0; block < B*B; block++) { int ib = block / B; int jb = block - ib * B; int jj = (ib + jb) % B; for (int k = 0; k < B; k++) { for (int mi = ib * (N / B); mi < (ib + 1)*(N / B); mi++) for (int mj = jb * (N / B); mj < (jb + 1)*(N / B); mj++) { double SUM = 0.0; for (int mk = jj * (N / B); mk < (jj + 1)*(N / B); mk++) SUM += AM[mi*N + mk] * BM[mk*N + mj]; CM[mi*N + mj] += SUM; } jj = (jj + 1) % B; } } finish = omp_get_wtime(); return (finish - start); } double CannonAlgorithm_OMP(double * AM, double * BM, double * CM, int N, int B) { double start = 0, finish = 0; start = omp_get_wtime(); #pragma omp parallel for for (int block = 0; block < B*B; block++) { int ib = block / B; int jb = block - ib * B; int jj = (ib + jb) % B; for (int k = 0; k < B; k++) { for (int mi = ib * (N / B); mi < (ib + 1)*(N / B); mi++) for (int mj = jb * (N / B); mj < (jb + 1)*(N / B); mj++) { double SUM = 0.0; for (int mk = jj * (N / B); mk < (jj + 1)*(N / B); mk++) SUM += AM[mi*N + mk] * BM[mk*N + mj]; CM[mi*N + mj] += SUM; } jj = (jj + 1) % B; } } finish = omp_get_wtime(); return (finish - start); } double CannonAlgorithm_TBB(double * AM, double * BM, double * CM, int N, int B, int grainSize) { task_scheduler_init init; double start = 0, finish = 0; start = omp_get_wtime(); parallel_for(blocked_range<int>(0, B*B, grainSize), CannonAlgorithm(AM, BM, CM, N, B)); finish = omp_get_wtime(); return (finish - start); } void main() { int B = 40; // grid size B*B int b = 50; // block size b*b int N = B * b; // matrix size: N*N double *AM = new double[N*N]; double *BM = new double[N*N]; double *CM = new double[N*N]; for (int i = 0; i < N*N; i++) { AM[i] = rand() % 5 + 1; BM[i] = rand() % 5 + 1; CM[i] = 0.0; } double TIME = 0.0; cout << "SIZE: " << N << endl; TIME = CannonAlgorithm_Seq(AM, BM, CM, N, B); cout << "TIME Seq: " << TIME << endl; TIME = CannonAlgorithm_OMP(AM, BM, CM, N, B); cout << "TIME OMP: " << TIME << endl; TIME = CannonAlgorithm_TBB(AM, BM, CM, N, B, 1); cout << "TIME TBB: " << TIME << endl; bool visual = false; if (visual) { cout << "A:" << endl; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout << AM[i*N + j] << "\t"; } cout << endl; } cout << endl; cout << "B:" << endl; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout << BM[i*N + j] << "\t"; } cout << endl; } cout << endl; cout << "C:" << endl; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout << CM[i*N + j] << "\t"; } cout << endl; } } cin.get(); }
[ "mari.louis.von.franz@gmail.com" ]
mari.louis.von.franz@gmail.com
3b643e6bd3f1801434367c7ede84bfe698f6c467
77a08ec51aa16191986a739267fd9d4379bbb208
/hdu/5585.cpp
c3eecf604497a986546ea8d591c17662974b0b2c
[]
no_license
cenariusxz/ACM-Coding
8f698203db802f79578921b311b38346950ef0ca
dc09ac9adfb4b80d463bdc93f52b479a957154e6
refs/heads/master
2023-06-24T13:12:13.279255
2021-07-26T01:24:36
2021-07-26T01:24:36
185,567,471
0
0
null
null
null
null
UTF-8
C++
false
false
388
cpp
#include<stdio.h> #include<string.h> #include<algorithm> #include<math.h> using namespace std; char s[35]; int main(){ while(scanf("%s",s)!=EOF){ int len=strlen(s); if(!((s[len-1]-'0')%2)||s[len-1]=='5'){ printf("YES\n"); continue; } int sum=0; for(int i=0;i<len;++i)sum+=s[i]-'0'; if(!(sum%3)){ printf("YES\n"); continue; } printf("NO\n"); } return 0; }
[ "810988849@qq.com" ]
810988849@qq.com
543336c00b6d49b7afd2f2be5e22f10197111e0f
5e68dd1c7e455c9ed3b101741c1d95f2ab7a2e9c
/src/plugins/Sobel_V/controller.h
379826e323854f7924ef68f4b0bbd7de4426c388
[]
no_license
Dariasteam/CV
d927235a76cf2a567507504a224b836b65e6a602
00afc1eeb38920fe99daaf17fc87b9cdcc1f6f17
refs/heads/master
2021-09-04T02:36:22.883772
2018-01-14T18:49:40
2018-01-14T18:49:40
105,511,783
0
0
null
null
null
null
UTF-8
C++
false
false
1,095
h
#ifndef CONTROLLER_H #define CONTROLLER_H #include <QObject> #include "menu.h" #include "model.h" #include "../../controller/plugin_interface.h" #include "../../model/lut.h" #include "../../view/canvas_image_label.h" class plugin_controller : public QObject { Q_OBJECT protected: QWidget* view; PluginModel* mdl; public: plugin_controller (QWidget* vw, PluginModel* msdl) : view (vw), mdl (msdl) { connect ((view_interface*)view,SIGNAL(update_inform()),this,SIGNAL(update_inform())); } virtual bool operator () (picture* image, LUT* lut, canvas_image_label* canvas) = 0; signals: virtual void update_inform () = 0; virtual void set_canvas_image_label (QLabel*) = 0; }; class controller : public plugin_controller { Q_OBJECT public: bool operator () (); virtual bool operator () (picture* image, LUT* lut, canvas_image_label* canvas); controller (QWidget* mn, PluginModel* mdl); public slots: void on_change_contrast (rgb_float_values rgb); signals: void update_inform (); void set_canvas_image_label (QLabel*); }; #endif // CONTROLLER_H
[ "dariasteam94@gmail.com" ]
dariasteam94@gmail.com
003860b9b15aa61986a7b43bd75f4b677371e7f0
711e5c8b643dd2a93fbcbada982d7ad489fb0169
/XPSP1/NT/shell/shlwapi/security.cpp
491b3f65d4c3c134d236f034615352e230ae8027
[]
no_license
aurantst/windows-XP-SP1
629a7763c082fd04d3b881e0d32a1cfbd523b5ce
d521b6360fcff4294ae6c5651c539f1b9a6cbb49
refs/heads/master
2023-03-21T01:08:39.870106
2020-09-28T08:10:11
2020-09-28T08:10:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
23,584
cpp
#include "priv.h" #include <shlobj.h> #include <shellp.h> #include <shdguid.h> #include "ids.h" #include <objbase.h> #include <wininet.h> // INTERNET_MAX_URL_LENGTH #include <shellp.h> #include <commctrl.h> #include <mluisupp.h> #include <inetcpl.h> #include <crypto\md5.h> #ifdef UNIX #include <urlmon.h> #endif // This will automatically be freed when the process shuts down. // Creating the ClassFactory for CLSID_InternetSecurityManager // is really slow, so we cache it because dragging and dropping // files does a lot of zone checking. IClassFactory * g_pcf = NULL; HRESULT _GetCachedZonesManager(REFIID riid, void **ppv) { HRESULT hr; if (!g_pcf) { CoGetClassObject(CLSID_InternetSecurityManager, CLSCTX_INPROC_SERVER, NULL, IID_IClassFactory, (void **)&g_pcf); SHPinDllOfCLSID(&CLSID_InternetSecurityManager); } if (g_pcf) { hr = g_pcf->CreateInstance(NULL, riid, ppv); } else { *ppv = NULL; hr = E_FAIL; } return hr; } /**********************************************************************\ FUNCTION: ZoneCheckUrlExCacheW DESCRIPTION: Call IInternetSecurityManager::ProcessUrlAction using the cached one if available. pwszUrl - URL to check pdwPolicy - Receives resulting policy (optional) dwPolicySize - size of policy buffer (usually sizeof(DWORD)) pdwContext - context (optional) dwContextSize - size of context buffer (usually sizeof(DWORD)) dwActionType - ProcessUrlAction action type code dwFlags - Flags for ProcessUrlAction pisms - IInternetSecurityMgrSite to use during ProcessUrlAction (optional) ppismCache - (in/out) IInternetSecurityManager to use If ppismCache is NULL, then no cacheing is performed; we use a brand new IInternetSecurityManager. If ppismCache is non-null, then it used to cache an IInternetSecurityManager. If there is one there already, we use it. If there isn't one there already, we create one and save it there. Return S_OK if access is allowed. This function will return S_FALSE if access was not allowed. \**********************************************************************/ LWSTDAPI ZoneCheckUrlExCacheW(LPCWSTR pwzUrl, DWORD * pdwPolicy, DWORD dwPolicySize, DWORD * pdwContext, DWORD dwContextSize, DWORD dwActionType, DWORD dwFlags, IInternetSecurityMgrSite * pisms, IInternetSecurityManager ** ppismCache) { HRESULT hr = E_INVALIDARG; if (pwzUrl) { IInternetSecurityManager *psim; if (ppismCache && *ppismCache) { hr = (*ppismCache)->QueryInterface(IID_PPV_ARG(IInternetSecurityManager, &psim)); } else { hr = _GetCachedZonesManager(IID_PPV_ARG(IInternetSecurityManager, &psim)); if (SUCCEEDED(hr) && ppismCache) psim->QueryInterface(IID_PPV_ARG(IInternetSecurityManager, ppismCache)); } if (SUCCEEDED(hr)) { DWORD dwPolicy = 0; DWORD dwContext = 0; if (pisms) psim->SetSecuritySite(pisms); hr = psim->ProcessUrlAction(pwzUrl, dwActionType, (BYTE *)(pdwPolicy ? pdwPolicy : &dwPolicy), (pdwPolicy ? dwPolicySize : sizeof(dwPolicy)), (BYTE *)(pdwContext ? pdwContext : &dwContext), (pdwContext ? dwContextSize : sizeof(dwContext)), dwFlags, 0); TraceMsg(TF_GENERAL, "ZoneCheckUrlExW(\"%ls\") IsFile=%s; NoUI=%s; dwActionType=0x%lx; dwFlags=0x%lx; hr=%lx>", pwzUrl, (dwFlags & PUAF_ISFILE) ? TEXT("Yes") : TEXT("No"), (dwFlags & PUAF_NOUI) ? TEXT("Yes") : TEXT("No"), dwActionType, dwFlags, hr); if (pisms) psim->SetSecuritySite(NULL); psim->Release(); } } return hr; } /**********************************************************************\ FUNCTION: ZoneCheckUrlExCacheA DESCRIPTION: ANSI version of ZoneCheckUrlExCacheW. Return S_OK if access is allowed. This function will return S_FALSE if access was not allowed. \**********************************************************************/ LWSTDAPI ZoneCheckUrlExCacheA(LPCSTR pszUrl, DWORD * pdwPolicy, DWORD dwPolicySize, DWORD * pdwContext, DWORD dwContextSize, DWORD dwActionType, DWORD dwFlags, IInternetSecurityMgrSite * pisms, IInternetSecurityManager ** ppismCache) { WCHAR wzUrl[INTERNET_MAX_URL_LENGTH]; ASSERT(ARRAYSIZE(wzUrl) > lstrlenA(pszUrl)); // We only work for Urls of INTERNET_MAX_URL_LENGTH or shorter. SHAnsiToUnicode(pszUrl, wzUrl, ARRAYSIZE(wzUrl)); return ZoneCheckUrlExCacheW(wzUrl, pdwPolicy, dwPolicySize, pdwContext, dwContextSize, dwActionType, dwFlags, pisms, ppismCache); } /**********************************************************************\ FUNCTION: ZoneCheckUrlExW DESCRIPTION: Just like ZoneCheckUrlExCacheW, except never caches. Return S_OK if access is allowed. This function will return S_FALSE if access was not allowed. \**********************************************************************/ LWSTDAPI ZoneCheckUrlExW(LPCWSTR pwzUrl, DWORD * pdwPolicy, DWORD dwPolicySize, DWORD * pdwContext, DWORD dwContextSize, DWORD dwActionType, DWORD dwFlags, IInternetSecurityMgrSite * pisms) { return ZoneCheckUrlExCacheW(pwzUrl, pdwPolicy, dwPolicySize, pdwContext, dwContextSize, dwActionType, dwFlags, pisms, NULL); } /**********************************************************************\ FUNCTION: ZoneCheckUrlExA DESCRIPTION: ANSI version of ZoneCheckUrlExW. Return S_OK if access is allowed. This function will return S_FALSE if access was not allowed. \**********************************************************************/ LWSTDAPI ZoneCheckUrlExA(LPCSTR pszUrl, DWORD * pdwPolicy, DWORD dwPolicySize, DWORD * pdwContext, DWORD dwContextSize, DWORD dwActionType, DWORD dwFlags, IInternetSecurityMgrSite * pisms) { WCHAR wzUrl[INTERNET_MAX_URL_LENGTH]; ASSERT(ARRAYSIZE(wzUrl) > lstrlenA(pszUrl)); // We only work for Urls of INTERNET_MAX_URL_LENGTH or shorter. SHAnsiToUnicode(pszUrl, wzUrl, ARRAYSIZE(wzUrl)); return ZoneCheckUrlExW(wzUrl, pdwPolicy, dwPolicySize, pdwContext, dwContextSize, dwActionType, dwFlags, pisms); } /**********************************************************************\ FUNCTION: ZoneCheckUrlW DESCRIPTION: Just like ZoneCheckUrlExW, except that no context or policy information are used. Return S_OK if access is allowed. This function will return S_FALSE if access was not allowed. \**********************************************************************/ LWSTDAPI ZoneCheckUrlW(LPCWSTR pwzUrl, DWORD dwActionType, DWORD dwFlags, IInternetSecurityMgrSite * pisms) { return ZoneCheckUrlExW(pwzUrl, NULL, 0, NULL, 0, dwActionType, dwFlags, pisms); } /**********************************************************************\ FUNCTION: ZoneCheckUrlA DESCRIPTION: ANSI version of ZoneCheckUrlW, Return S_OK if access is allowed. This function will return S_FALSE if access was not allowed. \**********************************************************************/ LWSTDAPI ZoneCheckUrlA(LPCSTR pszUrl, DWORD dwActionType, DWORD dwFlags, IInternetSecurityMgrSite * pisms) { WCHAR wzUrl[INTERNET_MAX_URL_LENGTH]; ASSERT(ARRAYSIZE(wzUrl) > lstrlenA(pszUrl)); // We only work for Urls of INTERNET_MAX_URL_LENGTH or shorter. SHAnsiToUnicode(pszUrl, wzUrl, ARRAYSIZE(wzUrl)); return ZoneCheckUrlW(wzUrl, dwActionType, dwFlags, pisms); } /**********************************************************************\ FUNCTION: ZoneCheckPathW DESCRIPTION: Just like ZoneCheckUrlW, except for filenames instead of URLs. Return S_OK if access is allowed. This function will return S_FALSE if access was not allowed. \**********************************************************************/ LWSTDAPI ZoneCheckPathW(LPCWSTR pwzPath, DWORD dwActionType, DWORD dwFlags, IInternetSecurityMgrSite * pisms) { ASSERT(!PathIsRelativeW(pwzPath)); return ZoneCheckUrlW(pwzPath, dwActionType, (dwFlags | PUAF_ISFILE), pisms); } /**********************************************************************\ FUNCTION: ZoneCheckPathA DESCRIPTION: ANSI version of ZoneCheckPathW, Return S_OK if access is allowed. This function will return S_FALSE if access was not allowed. \**********************************************************************/ LWSTDAPI ZoneCheckPathA(LPCSTR pszPath, DWORD dwActionType, DWORD dwFlags, IInternetSecurityMgrSite * pisms) { WCHAR wzPath[INTERNET_MAX_URL_LENGTH]; ASSERT(ARRAYSIZE(wzPath) > lstrlenA(pszPath)); // We only work for Urls of INTERNET_MAX_URL_LENGTH or shorter. SHAnsiToUnicode(pszPath, wzPath, ARRAYSIZE(wzPath)); return ZoneCheckPathW(wzPath, dwActionType, dwFlags, pisms); } /**********************************************************************\ FUNCTION: ZoneCheckHostEx DESCRIPTION: Return S_OK if access is allowed. This function will return S_FALSE if access was not allowed. \**********************************************************************/ LWSTDAPI ZoneCheckHostEx(IInternetHostSecurityManager * pihsm, DWORD * pdwPolicy, DWORD dwPolicySize, DWORD * pdwContext, DWORD dwContextSize, DWORD dwActionType, DWORD dwFlags) { HRESULT hr; DWORD dwPolicy = 0; DWORD dwContext = 0; ASSERT(IsFlagClear(dwFlags, PUAF_ISFILE)); // This flag is not appropriate here. if (!EVAL(pihsm)) return E_INVALIDARG; hr = pihsm->ProcessUrlAction(dwActionType, (BYTE *)(pdwPolicy ? pdwPolicy : &dwPolicy), (pdwPolicy ? dwPolicySize : sizeof(dwPolicy)), (BYTE *)(pdwContext ? pdwContext : &dwContext), (pdwContext ? dwContextSize : sizeof(dwContext)), dwFlags, 0); TraceMsg(TF_GENERAL, "ZoneCheckHostEx() NoUI=%s; hr=%lx", (dwFlags & PUAF_NOUI) ? TEXT("Yes") : TEXT("No"), hr); return hr; } /**********************************************************************\ FUNCTION: ZoneCheckHost DESCRIPTION: Return S_OK if access is allowed. This function will return S_FALSE if access was not allowed. \**********************************************************************/ LWSTDAPI ZoneCheckHost(IInternetHostSecurityManager * pihsm, DWORD dwActionType, DWORD dwFlags) { return ZoneCheckHostEx(pihsm, NULL, 0, NULL, 0, dwActionType, dwFlags); } /**********************************************************************\ FUNCTION: ZoneComputePaneSize DESCRIPTION: Computes the necessary size for the zones pane in a status bar. NOTES The longest zone is the following: Width of longest zone name + Width of " (Mixed)" + Width of small icon (SM_CXSMICON) + Width of gripper (SM_CXVSCROLL) + Four edges (4 * SM_CXEDGE) Why four edges? Because the rectangle is framed in a DrawEdge(), which adds two edges on the left and two on the right, for a total of four. We cache the results of the font measurements for performance. \**********************************************************************/ #define ZONES_PANE_WIDTH 220 // Size to use if we are desperate int _ZoneComputePaneStringSize(HWND hwndStatus, HFONT hf) { HDC hdc = GetDC(hwndStatus); HFONT hfPrev = SelectFont(hdc, hf); SIZE siz, sizMixed; HRESULT hrInit, hr; int cxZone; ZONEATTRIBUTES za; // Start with the length of the phrase " (Mixed)" MLLoadStringW(IDS_MIXED, za.szDisplayName, ARRAYSIZE(za.szDisplayName)); GetTextExtentPoint32WrapW(hdc, za.szDisplayName, lstrlenW(za.szDisplayName), &sizMixed); cxZone = 0; hrInit = SHCoInitialize(); IInternetZoneManager *pizm; hr = CoCreateInstance(CLSID_InternetZoneManager, NULL, CLSCTX_INPROC_SERVER, IID_IInternetZoneManager, (void **)&pizm); if (SUCCEEDED(hr)) { DWORD dwZoneEnum, dwZoneCount; hr = pizm->CreateZoneEnumerator(&dwZoneEnum, &dwZoneCount, 0); if (SUCCEEDED(hr)) { for (int nIndex=0; (DWORD)nIndex < dwZoneCount; nIndex++) { DWORD dwZone; za.cbSize = sizeof(ZONEATTRIBUTES); pizm->GetZoneAt(dwZoneEnum, nIndex, &dwZone); pizm->GetZoneAttributes(dwZone, &za); GetTextExtentPoint32WrapW(hdc, za.szDisplayName, lstrlenW(za.szDisplayName), &siz); if (cxZone < siz.cx) cxZone = siz.cx; } pizm->DestroyZoneEnumerator(dwZoneEnum); } pizm->Release(); } SHCoUninitialize(hrInit); SelectFont(hdc, hfPrev); ReleaseDC(hwndStatus, hdc); // If we couldn't get any zones, then use the panic value. if (cxZone == 0) return ZONES_PANE_WIDTH; else return cxZone + sizMixed.cx; } LOGFONT s_lfStatusBar; // status bar font (cached metrics) int s_cxMaxZoneText; // size of longest zone text (cached) LWSTDAPI_(int) ZoneComputePaneSize(HWND hwndStatus) { LOGFONT lf; HFONT hf = GetWindowFont(hwndStatus); GetObject(hf, sizeof(lf), &lf); // Warning: lf.lfFaceName is an ASCIIZ string, and there might be // uninitialized garbage there, so zero-fill it for consistency. UINT cchFaceName = lstrlen(lf.lfFaceName); ZeroMemory(&lf.lfFaceName[cchFaceName], sizeof(TCHAR) * (LF_FACESIZE - cchFaceName)); if (memcmp(&lf, &s_lfStatusBar, sizeof(LOGFONT)) != 0) { ENTERCRITICAL; s_cxMaxZoneText = _ZoneComputePaneStringSize(hwndStatus, hf); s_lfStatusBar = lf; // Update the cache LEAVECRITICAL; } return s_cxMaxZoneText + GetSystemMetrics(SM_CXSMICON) + GetSystemMetrics(SM_CXVSCROLL) + GetSystemMetrics(SM_CXEDGE) * 4; } /**********************************************************************\ FUNCTION: ZoneConfigure DESCRIPTION: Displays the Zones configuration control panel. pwszUrl is used to specify which zone is chosen as default. Inetcpl will choose the zone that the URL belongs to. \**********************************************************************/ #define MAX_CPL_PAGES 16 BOOL CALLBACK _ZoneAddPropSheetPage(HPROPSHEETPAGE hpage, LPARAM lParam) { PROPSHEETHEADER * ppsh = (PROPSHEETHEADER *)lParam; if (ppsh->nPages < MAX_CPL_PAGES) { ppsh->phpage[ppsh->nPages++] = hpage; return TRUE; } return FALSE; } LWSTDAPI_(void) ZoneConfigureW(HWND hwnd, LPCWSTR pwszUrl) { HMODULE hModInetCpl; if (hModInetCpl = LoadLibrary(TEXT("inetcpl.cpl"))) { PFNADDINTERNETPROPERTYSHEETSEX pfnAddSheet = (PFNADDINTERNETPROPERTYSHEETSEX)GetProcAddress(hModInetCpl, STR_ADDINTERNETPROPSHEETSEX); if (pfnAddSheet) { IEPROPPAGEINFO iepi = {SIZEOF(iepi)}; // Load the current url into the properties page CHAR szBufA[INTERNET_MAX_URL_LENGTH]; SHUnicodeToAnsi(pwszUrl, szBufA, ARRAYSIZE(szBufA)); iepi.pszCurrentURL = szBufA; PROPSHEETHEADER psh; HPROPSHEETPAGE rPages[MAX_CPL_PAGES]; psh.dwSize = SIZEOF(psh); psh.dwFlags = PSH_PROPTITLE; psh.hInstance = MLGetHinst(); psh.hwndParent = hwnd; psh.pszCaption = MAKEINTRESOURCE(IDS_INTERNETSECURITY); psh.nPages = 0; psh.nStartPage = 0; psh.phpage = rPages; // we just want the security page. iepi.dwFlags = INET_PAGE_SECURITY; pfnAddSheet(_ZoneAddPropSheetPage, (LPARAM)&psh, 0, 0, &iepi); // // Display the property sheet only if the "security" page was // successfully added (it will fail if an IEAK setting says so) // if (psh.nPages > 0) { PropertySheet(&psh); } else { SHRestrictedMessageBox(hwnd); } } FreeLibrary(hModInetCpl); } } /**********************************************************************\ DESCRIPTION: Registers or validates an htt/htm template with the shell. The WebView customization wizard and the code that installs the default WebView templates calls this API to register the templates. The shell object model uses this API to grant privileges to execute unsafe method calls (e.g. SHELL.APPLICATION) to templates registered with this API. If they aren't registered, they can't call the unsafe methods. \**********************************************************************/ #define REGSTR_TEMPLATE_REGISTRY (REGSTR_PATH_EXPLORER TEXT("\\TemplateRegistry")) #define REGSTR_VALUE_KEY (TEXT("Value")) BOOL GetTemplateValueFromReg(LPTSTR pszValue, DWORD *pdwValue) { DWORD cbValue = sizeof(DWORD); BOOL bSuccess; if (!(bSuccess = (ERROR_SUCCESS == SHGetValue(HKEY_LOCAL_MACHINE, REGSTR_TEMPLATE_REGISTRY, pszValue, NULL, pdwValue, &cbValue)))) { cbValue = sizeof(DWORD); bSuccess = (ERROR_SUCCESS == SHGetValue(HKEY_CURRENT_USER, REGSTR_TEMPLATE_REGISTRY, pszValue, NULL, pdwValue, &cbValue)); } return bSuccess; } BOOL SetTemplateValueInReg(LPTSTR pszValue, DWORD *pdwValue) { return ((ERROR_SUCCESS == SHSetValue(HKEY_LOCAL_MACHINE, REGSTR_TEMPLATE_REGISTRY, pszValue, REG_DWORD, pdwValue, sizeof(DWORD))) || (ERROR_SUCCESS == SHSetValue(HKEY_CURRENT_USER, REGSTR_TEMPLATE_REGISTRY, pszValue, REG_DWORD, pdwValue, sizeof(DWORD)))); } HRESULT GetTemplateInfoFromHandle(HANDLE h, UCHAR * pKey, DWORD *pdwSize) { HRESULT hres = E_FAIL; DWORD dwSize = GetFileSize(h, NULL); LPBYTE pFileBuff = (LPBYTE)LocalAlloc(0, dwSize); if (pFileBuff) { DWORD dwBytesRead; if (ReadFile(h, pFileBuff, dwSize, &dwBytesRead, NULL)) { MD5_CTX md5; MD5Init(&md5); MD5Update(&md5, pFileBuff, dwBytesRead); MD5Final(&md5); memcpy(pKey, md5.digest, MD5DIGESTLEN); *pdwSize = dwSize; hres = S_OK; } LocalFree(pFileBuff); } else { hres = E_OUTOFMEMORY; } return hres; } // in: // pszPath URL or file system path // return: // S_OK if pszPath is in the local zone // E_ACCESSDENIED we are not in a local zone // // WARNING: Only use this from SHRegisterValidateTemplate // because this isn't good enough for general use. // It's not good enought to CoCreate IInternetSecurityManager // because it needs to be provided from the host // via QueryService. Outlook Express is one example // that needs to over ride the default implementation. // Using this from SHRegisterValidateTemplate is OK // because it still doesn't the registry check. STDAPI SuperPrivate_ZoneCheckPath(LPCWSTR pszPath, DWORD dwZone) { HRESULT hr = E_ACCESSDENIED; IInternetSecurityManager *pSecMgr; if (SUCCEEDED(_GetCachedZonesManager(IID_PPV_ARG(IInternetSecurityManager, &pSecMgr)))) { DWORD dwZoneID = URLZONE_UNTRUSTED; if (SUCCEEDED(pSecMgr->MapUrlToZone(pszPath, &dwZoneID, 0))) { if (dwZoneID == dwZone) { hr = S_OK; // we are good } } pSecMgr->Release(); } return hr; } // this API takes a Win32 file path // in: // dwFlags SHRVT_ falgs in shlwapi.h // out: // S_OK happy LWSTDAPI SHRegisterValidateTemplate(LPCWSTR pszPath, DWORD dwFlags) { if ((dwFlags & SHRVT_VALID) != dwFlags) return E_INVALIDARG; HRESULT hr = S_OK; if (dwFlags & SHRVT_VALIDATE) { hr = SuperPrivate_ZoneCheckPath(pszPath, URLZONE_LOCAL_MACHINE); if (FAILED(hr) && (dwFlags & SHRVT_ALLOW_INTRANET)) { hr = SuperPrivate_ZoneCheckPath(pszPath, URLZONE_INTRANET); } } if (S_OK == hr) { DWORD dwSize; UCHAR pKey[MD5DIGESTLEN]; HANDLE hfile = CreateFileWrapW(pszPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL); if (INVALID_HANDLE_VALUE != hfile) { hr = GetTemplateInfoFromHandle(hfile, pKey, &dwSize); CloseHandle(hfile); } else hr = E_INVALIDARG; if (SUCCEEDED(hr)) { BOOL bSuccess; TCHAR szTemplate[MAX_PATH]; DWORD *pdw = (DWORD *)pKey; ASSERT(MD5DIGESTLEN == (4 * sizeof(DWORD))); wsprintf(szTemplate, TEXT("%u%u%u%u"), pdw[0], pdw[1], pdw[2], pdw[3]); if (dwFlags & SHRVT_VALIDATE) { DWORD dwSizeReg; bSuccess = (GetTemplateValueFromReg(szTemplate, &dwSizeReg) && (dwSizeReg == dwSize)); if (!bSuccess && (dwFlags & SHRVT_PROMPTUSER)) { MSGBOXPARAMS mbp = {sizeof(MSGBOXPARAMS), NULL, g_hinst, MAKEINTRESOURCE(IDS_TEMPLATENOTSECURE), MAKEINTRESOURCE(IDS_SECURITY), MB_YESNO | MB_DEFBUTTON2 | MB_TASKMODAL | MB_USERICON, MAKEINTRESOURCE(IDI_SECURITY), 0, NULL, 0}; // REARCHITECT: posting a msg box with NULL hwnd, this should // could use a site pointer to get an hwnd to go modal against // if one was provided to the API // Are we calling A or W MessageBoxIndirect and does this break on NT/9x? // Doesn't seem to, -justmann bSuccess = (MessageBoxIndirect(&mbp) == IDYES); if (bSuccess && (dwFlags & SHRVT_REGISTERIFPROMPTOK)) SetTemplateValueInReg(szTemplate, &dwSize); } } else if (dwFlags & SHRVT_REGISTER) { bSuccess = SetTemplateValueInReg(szTemplate, &dwSize); } hr = bSuccess ? S_OK : E_ACCESSDENIED; } } return hr; }
[ "112426112@qq.com" ]
112426112@qq.com
be389acdb11c22b31d60dac9821a46bc1b8075b6
ca20c31c2d5e36497a3bf4d67b7c3d4260518f44
/src/qt/askpassphrasedialog.cpp
75c6a7fcffefc7822f3533f758909647111233b5
[ "MIT" ]
permissive
SamaelDNM/Checoin
17cdab27490f0b88668655f7a2aa33d15c42ac1f
1eae885384476f410c4291a243edef82a60932b9
refs/heads/master
2020-04-07T15:58:01.636636
2018-11-21T08:27:39
2018-11-21T08:27:39
158,509,366
1
0
null
null
null
null
UTF-8
C++
false
false
9,717
cpp
#include "askpassphrasedialog.h" #include "ui_askpassphrasedialog.h" #include "guiconstants.h" #include "walletmodel.h" #include <QMessageBox> #include <QPushButton> #include <QKeyEvent> AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::AskPassphraseDialog), mode(mode), model(0), fCapsLock(false) { ui->setupUi(this); ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE); // Setup Caps Lock detection. ui->passEdit1->installEventFilter(this); ui->passEdit2->installEventFilter(this); ui->passEdit3->installEventFilter(this); switch(mode) { case Encrypt: // Ask passphrase x2 ui->passLabel1->hide(); ui->passEdit1->hide(); ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.")); setWindowTitle(tr("Encrypt wallet")); break; case Unlock: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Unlock wallet")); break; case Decrypt: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Decrypt wallet")); break; case ChangePass: // Ask old passphrase + new passphrase x2 setWindowTitle(tr("Change passphrase")); ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet.")); break; } textChanged(); connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); } AskPassphraseDialog::~AskPassphraseDialog() { // Attempt to overwrite text so that they do not linger around in memory ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size())); ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size())); ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size())); delete ui; } void AskPassphraseDialog::setModel(WalletModel *model) { this->model = model; } void AskPassphraseDialog::accept() { SecureString oldpass, newpass1, newpass2; if(!model) return; oldpass.reserve(MAX_PASSPHRASE_SIZE); newpass1.reserve(MAX_PASSPHRASE_SIZE); newpass2.reserve(MAX_PASSPHRASE_SIZE); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make this input mlock()'d to begin with. oldpass.assign(ui->passEdit1->text().toStdString().c_str()); newpass1.assign(ui->passEdit2->text().toStdString().c_str()); newpass2.assign(ui->passEdit3->text().toStdString().c_str()); switch(mode) { case Encrypt: { if(newpass1.empty() || newpass2.empty()) { // Cannot encrypt with empty passphrase break; } QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"), tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BITCOINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval == QMessageBox::Yes) { if(newpass1 == newpass2) { if(model->setWalletEncrypted(true, newpass1)) { QMessageBox::warning(this, tr("Wallet encrypted"), "<qt>" + tr("checoin will close now to finish the encryption process. " "Remember that encrypting your wallet cannot fully protect " "your checoins from being stolen by malware infecting your computer.") + "<br><br><b>" + tr("IMPORTANT: Any previous backups you have made of your wallet file " "should be replaced with the newly generated, encrypted wallet file. " "For security reasons, previous backups of the unencrypted wallet file " "will become useless as soon as you start using the new, encrypted wallet.") + "</b></qt>"); QApplication::quit(); } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted.")); } QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } } else { QDialog::reject(); // Cancelled } } break; case Unlock: if(!model->setWalletLocked(false, oldpass)) { QMessageBox::critical(this, tr("Wallet unlock failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case Decrypt: if(!model->setWalletEncrypted(false, oldpass)) { QMessageBox::critical(this, tr("Wallet decryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case ChangePass: if(newpass1 == newpass2) { if(model->changePassphrase(oldpass, newpass1)) { QMessageBox::information(this, tr("Wallet encrypted"), tr("Wallet passphrase was successfully changed.")); QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } break; } } void AskPassphraseDialog::textChanged() { // Validate input, set Ok button to enabled when acceptable bool acceptable = false; switch(mode) { case Encrypt: // New passphrase x2 acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; case Unlock: // Old passphrase x1 case Decrypt: acceptable = !ui->passEdit1->text().isEmpty(); break; case ChangePass: // Old passphrase x1, new passphrase x2 acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; } ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable); } bool AskPassphraseDialog::event(QEvent *event) { // Detect Caps Lock key press. if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); if (ke->key() == Qt::Key_CapsLock) { fCapsLock = !fCapsLock; } if (fCapsLock) { ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else { ui->capsLabel->clear(); } } return QWidget::event(event); } bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event) { /* Detect Caps Lock. * There is no good OS-independent way to check a key state in Qt, but we * can detect Caps Lock by checking for the following condition: * Shift key is down and the result is a lower case character, or * Shift key is not down and the result is an upper case character. */ if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); QString str = ke->text(); if (str.length() != 0) { const QChar *psz = str.unicode(); bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0; if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) { fCapsLock = true; ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else if (psz->isLetter()) { fCapsLock = false; ui->capsLabel->clear(); } } } return QDialog::eventFilter(object, event); }
[ "samaelnottaro@gmail.com" ]
samaelnottaro@gmail.com
a405e839dbb2a4d2476bca7c124e42c1a32cf14d
341d4c24f6f2e24d5178124d250953485ff65470
/include/IGVCSimulator.h
59325d62cce304a95915ff53fc41ffb7666bb3f7
[]
no_license
John-Brooks/IGVC-Gem-Simulator
7e98baee7a27b80e164fc6723288adb2a3213392
6143ef7617d82350ac2b541626e4a9f10bd4dc13
refs/heads/master
2020-07-18T08:11:10.567127
2020-04-18T19:24:20
2020-04-18T19:24:20
206,211,482
0
0
null
null
null
null
UTF-8
C++
false
false
930
h
#pragma once #include <stdio.h> #include "Graphics.h" #include "Environment.h" #include "ActionSpace.h" #include "StateSpace.h" #include <chrono> #include <thread> #include "Scenario.h" extern "C" void HelloWorld() { printf("Hello World!\n"); } void run() { Environment env; ActionSpace action; StateSpace state; action.VehicleSpeed = 1; action.SteeringAngle = 0.0; env.LoadScenario("/media/john/5A506552506535C3/Users/John/Desktop/drawing.svg"); env.SetSimulationTimeStep(0.016); int direction = 1; while(true) { action.SteeringAngle += 0.01 * direction; if (action.SteeringAngle > M_PI / 4.0 || action.SteeringAngle < M_PI / -4.0) direction = direction * -1; state = env.Step(action); if(!env.Render()) { env.Close(); return; } if (state.test_ended) env.Reset(); std::this_thread::sleep_for(std::chrono::milliseconds(16)); } env.Close(); } StateSpace Step(ActionSpace action) { }
[ "johnbrooks@oakland.edu" ]
johnbrooks@oakland.edu
91236283fca8d80ed4d464ae7053812caddc2d47
b8bd16268d0d49005d2a5a50aaafb4501ff5c279
/src/mainwindow.cpp
dd5d332f12efc6abef8b3ee1668d394ae68acdf8
[ "MIT" ]
permissive
jonpas/SymRec
b0c07314d78350c1eeffe8de7b013ed4e2481153
2432cdfe253582134593baade274cf47c5f6539e
refs/heads/master
2022-01-15T07:50:07.581076
2019-06-03T17:36:30
2019-06-03T17:36:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,143
cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QInputDialog> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->graphicsView->installEventFilter(this); scene = ui->graphicsView->scene(); updateUi(); } MainWindow::~MainWindow() { delete network; delete ui; } void MainWindow::updateUi() { // Buttons ui->pushButtonInputPredict->setText(network == nullptr ? "Input" : "Predict"); ui->pushButtonTrain->setEnabled(network == nullptr); // Status QString savedSymbolsStr = QString::number(symbols.size()); QString networkStr = "Untrained"; if (network != nullptr) { networkStr = network->trained() ? "Trained" : "Failed Training"; } ui->statusNetwork->setPlainText( "Saved Symbols: " + savedSymbolsStr + "\n" "Network: " + networkStr + "\n" ); } // UI input getters uint MainWindow::getSymbolPoints() const { return ui->spinBoxSymbolPoints->text().toUInt(); } uint MainWindow::getHiddenNeurons() const { return ui->spinBoxHiddenNeurons->text().toUInt(); } double MainWindow::getLearningRate() const { return ui->doubleSpinBoxLearningRate->text().toDouble(); } double MainWindow::getMomentumConst() const { return ui->doubleSpinBoxMomentumConst->text().toDouble(); } uint MainWindow::getMaxEpochs() const { return ui->spinBoxMaxEpochs->text().toUInt(); } double MainWindow::getMinError() const { return ui->doubleSpinBoxMinError->text().toDouble(); } void MainWindow::createNetwork() { encodeCharacters(); // Required for output layer neuron count network = new NeuralNetwork(getLearningRate(), getMomentumConst(), getMaxEpochs(), getMinError()); // Input: x, y flattened (2x amount of coordinates) network->addLayer(Layer(getSymbolPoints() * 2, getHiddenNeurons(), "sigmoid", {-0.5, 0.5}, {0.0, 0.0})); // Hidden: set by user network->addLayer(Layer(getHiddenNeurons(), static_cast<uint>(charCodeMap.size()), "sigmoid", {-0.5, 0.5}, {0.0, 0.0})); // Output: amount of different characters } bool MainWindow::drawingToPoints(QList<QPointF> &points) const { int symbolPoints = static_cast<int>(getSymbolPoints()); scene->stopDrawing(); points = scene->simplify(symbolPoints); if (points.size() == symbolPoints) { scene->drawPoints(points); scene->normalize(points); return true; } return false; } DataRow MainWindow::pointsToData(QList<QPointF> points) const { DataRow pointsData; for (auto &point : points) { pointsData.append({point.x(), point.y()}); } return pointsData; } Data MainWindow::symbolsToData() const { Data symbolsData; for (auto &symbol : symbols) { symbolsData.append(pointsToData(symbol)); } return symbolsData; } void MainWindow::encodeCharacters() { int charAmount = characters.toSet().size(); for (int i = 0; i < characters.size(); ++i) { ResultRow charRow; if (!charCodeMap.contains(characters[i])) { for (int j = 0; j < charAmount; ++j) { charRow.append((i == j) ? 1 : 0); } charCodeMap[characters[i]] = charRow; } } } Result MainWindow::charactersToResult() const { Result charData; for (auto &character : characters) { charData.append(charCodeMap[character]); } return charData; } // Slots void MainWindow::on_pushButtonInputPredict_clicked() { QList<QPointF> points; bool ok = drawingToPoints(points); if (!ok) { ui->statusBar->showMessage("Error! Symbol conversion failed! Symbol possibly does not have enough points."); return; } if (network == nullptr) { // Input QString text = QInputDialog::getText(this, "Character Name", "Which character did you draw?", QLineEdit::Normal, nullptr, &ok); if (ok && !text.isEmpty()) { char character = text.at(0).toLatin1(); symbols.append(points); characters.append(character); ui->statusBar->showMessage("Added symbol '" + QString(character) + "'"); } } else { // Predict Result predictions = network->predict({pointsToData(points)}); ResultRow charCode = predictions[0]; char character = charCodeMap.key(charCode); ui->statusBar->showMessage("Recognized: " + QString(character)); } updateUi(); } void MainWindow::on_pushButtonTrain_clicked() { if (symbols.size() > 0) { createNetwork(); network->train(symbolsToData(), charactersToResult()); ui->statusBar->showMessage("Neural network successfully trained with " + QString::number(symbols.size()) + " symbols"); } else { ui->statusBar->showMessage("Error! Neural network training failed! No symbols given."); } updateUi(); } void MainWindow::on_pushButtonReset_clicked() { symbols.clear(); characters.clear(); delete network; network = nullptr; scene->reset(); ui->statusBar->showMessage("Neural network reset!"); updateUi(); }
[ "jonpas33@gmail.com" ]
jonpas33@gmail.com
f9619eee0778a251e4de098be1f3f25780578211
aa6468f47e790c91e45e0b98ccde711c37efe4e1
/84.柱状图中最大的矩形.cpp
73aa0ab92ad3c578e2971884bcfde208a25f6678
[]
no_license
qixuanxuan/leetcode
208562ac528a78243d5b2cb882cfb4912c817206
95578b9282b022df951176422f31781ac3b8e390
refs/heads/master
2022-12-19T04:02:38.812831
2020-09-29T15:25:27
2020-09-29T15:25:27
265,843,684
0
0
null
null
null
null
UTF-8
C++
false
false
764
cpp
class Solution { public: int largestRectangleArea(vector<int>& heights) { vector<int> Left(heights.size()); vector<int> Right(heights.size()); stack<int> Temp; int result = 0; for(int i=0;i<heights.size();++i){ while(!Temp.empty() && heights[i]<=heights[Temp.top()]){ Temp.pop(); } Left[i] = Temp.empty() ? -1:Temp.top(); Temp.push(i); } Temp = stack<int>(); for(int i=heights.size()-1;i>=0;--i){ while(!Temp.empty() && heights[i]<=heights[Temp.top()]){ Temp.pop(); } Right[i] = Temp.empty() ? heights.size():Temp.top(); Temp.push(i); } for(int i=0;i<heights.size();i++){ if(heights[i]*(Right[i]-Left[i]-1)>result){ result = heights[i]*(Right[i]-Left[i]-1); } } return result; } };
[ "hfut_qxx@163.com" ]
hfut_qxx@163.com
00f95da21b97f52878cae47edd87bbf791cf3bf7
83cb2749b582294916c9c700c81749e2ea125e39
/ffs/source/wearleveling/rtos/mqx/simple_mutex.cpp
a224b59874b82808ae1347dad116726a0f519ca1
[]
no_license
jiaoah97/MQX411
446d41cdb70327dad9598fb6e847b7efff5579b4
78cf20856d7f49b09370ef066c1f9c83aaada0ec
refs/heads/master
2021-05-29T10:06:15.845663
2015-05-06T14:00:32
2015-05-06T14:00:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,694
cpp
/*HEADER********************************************************************** * * Copyright 2012 Freescale Semiconductor, Inc. * * This software is owned or controlled by Freescale Semiconductor. * Use of this software is governed by the Freescale MQX RTOS License * distributed with this Material. * See the MQX_RTOS_LICENSE file distributed for more details. * * Brief License Summary: * This software is provided in source form for you to use free of charge, * but it is not open source software. You are allowed to use this software * but you cannot redistribute it or derivative works of it in source form. * The software may be used only in connection with a product containing * a Freescale microprocessor, microcontroller, or digital signal processor. * See license agreement file for full license terms including other restrictions. ***************************************************************************** * * Comments: * * Defines a mutex helper class * *END************************************************************************/ #include "wl_common.h" #include "simple_mutex.h" MUTEX_ATTR_STRUCT SimpleMutex::m_mutexattr = { 0}; /*FUNCTION*---------------------------------------------------------------- * * Function Name : SimpleMutex::CreateMutexAttr * Returned Value : TRUE or FALSE * Comments : * Initialise the Mutex Attributes * *END*--------------------------------------------------------------------*/ bool SimpleMutex::CreateMutexAttr() { /* Body */ static bool bIsInit = FALSE; /* Init already */ if (bIsInit) return TRUE; if (_mutatr_init(&SimpleMutex::m_mutexattr) != MQX_OK) { WL_LOG(WL_MODULE_GENERAL,WL_LOG_ERROR, "Initializing mutex attributes failed.\n"); return FALSE; }/* Endif*/ bIsInit = TRUE; return TRUE; }/* Endbody */ /*FUNCTION*---------------------------------------------------------------- * * Function Name : SimpleMutex::InitMutex * Returned Value : TRUE or FALSE * Comments : * Initialise the Mutex * *END*--------------------------------------------------------------------*/ bool SimpleMutex::InitMutex ( /* [IN] pointer to Mutex */ WL_MUTEX * pIncMutex ) {/* Body */ SimpleMutex::CreateMutexAttr(); if (_mutex_init(pIncMutex, &SimpleMutex::m_mutexattr) != MQX_OK) { WL_LOG(WL_MODULE_GENERAL, WL_LOG_ERROR,"Initializing mutex failed.\n"); return FALSE; }/* Endif*/ return TRUE; }/* Endbody */ /*FUNCTION*---------------------------------------------------------------- * * Function Name : SimpleMutex::DestroyMutex * Returned Value : TRUE or FALSE * Comments : * Destroy the Mutex * *END*--------------------------------------------------------------------*/ bool SimpleMutex::DestroyMutex ( /* [IN] pointer to Mutex */ WL_MUTEX * pIncMutex ) {/* Body */ if (_mutex_destroy(pIncMutex) != MQX_OK) { WL_LOG(WL_MODULE_GENERAL, WL_LOG_ERROR,"Destroying mutex failed.\n"); return FALSE; }/* Endif*/ return TRUE; }/* Endbody */ /*FUNCTION*---------------------------------------------------------------- * * Function Name : SimpleMutex::InitMutex * Returned Value : TRUE or FALSE * Comments : * Constructor. Gets mutex. Takes a mutex pointer * *END*--------------------------------------------------------------------*/ SimpleMutex::SimpleMutex ( /* [IN] pointer to Mutex */ WL_MUTEX * pIncMutex ) : m_mutex(pIncMutex) {/* Body */ if (_mutex_lock(m_mutex) != MQX_OK) { WL_LOG(WL_MODULE_GENERAL, WL_LOG_ERROR, "Mutex lock failed.\n"); assert(0); }/* Endif*/ }/* Endbody */ /*FUNCTION*---------------------------------------------------------------- * * Function Name : SimpleMutex::InitMutex * Returned Value : TRUE or FALSE * Comments : * Constructor. Gets mutex. Takes a mutex reference * *END*--------------------------------------------------------------------*/ SimpleMutex::SimpleMutex ( /* [IN] pointer to Mutex */ WL_MUTEX & incMutex ) : m_mutex(&incMutex) {/* Body */ if (_mutex_lock(m_mutex) != MQX_OK) { WL_LOG(WL_MODULE_GENERAL, WL_LOG_ERROR, "Mutex lock failed.\n"); assert(0); }/* Endif*/ }/* Endbody */ /*FUNCTION*---------------------------------------------------------------- * * Function Name : SimpleMutex::InitMutex * Returned Value : TRUE or FALSE * Comments : * Destructor. Puts mutex * *END*--------------------------------------------------------------------*/ SimpleMutex::~SimpleMutex() { /* Body */ _mutex_unlock(m_mutex); }/* Endbody */ /* EOF */
[ "kunyi_chen@(NB)" ]
kunyi_chen@(NB)
8794faa304437a565c4c090f3f4230f5755de806
5ff9f5737d26c7dd2f3e383c1bc95d854fd64475
/DinamickoStablo/DinamickoStablo/Red.h
524d420c144b140e54584705614e1a540a323012
[]
no_license
NinaLazarevic/C-plus-plus-projects
ca5007c2e45b9b7385f983040a3138e3cd1d35b2
15889e202296b151a4fdd2722e2e61b00710fd47
refs/heads/master
2020-09-08T06:37:53.518499
2019-11-11T20:18:13
2019-11-11T20:18:13
221,047,467
0
0
null
null
null
null
UTF-8
C++
false
false
293
h
#pragma once #include "Node.h" #include <iostream> using namespace std; class QueueAsArray { protected: int n; Node **a; int head; int tail; int brel; public: QueueAsArray(int t); ~QueueAsArray(void); void enqueue(Node* el); Node* dequeue(); bool isEmpty() { return brel == 0; } };
[ "ninalazarevic@users.noreply.github.com" ]
ninalazarevic@users.noreply.github.com
c477cd3e67b7824264939cace6480ddb125e7cb4
c91ba4e746dc5b8f2dface963b4096dd721070fd
/rds/src/model/DescribeResourceUsageRequest.cc
0a7c93635e311ce1daf2a8f952394f91a1c86915
[ "Apache-2.0" ]
permissive
IthacaDream/aliyun-openapi-cpp-sdk
fa9120604ca3af4fc48a5f9bf70ff10542103c3a
31a064d1568f59e0731485a1b0452cfd5d767e42
refs/heads/master
2021-09-05T09:44:19.244166
2018-01-26T07:00:14
2018-01-26T07:00:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,770
cc
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/rds/model/DescribeResourceUsageRequest.h> using namespace AlibabaCloud::Rds; using namespace AlibabaCloud::Rds::Model; DescribeResourceUsageRequest::DescribeResourceUsageRequest() : RdsRequest("DescribeResourceUsage") {} DescribeResourceUsageRequest::~DescribeResourceUsageRequest() {} long DescribeResourceUsageRequest::getResourceOwnerId()const { return resourceOwnerId_; } void DescribeResourceUsageRequest::setResourceOwnerId(long resourceOwnerId) { resourceOwnerId_ = resourceOwnerId; setParameter("ResourceOwnerId", std::to_string(resourceOwnerId)); } std::string DescribeResourceUsageRequest::getResourceOwnerAccount()const { return resourceOwnerAccount_; } void DescribeResourceUsageRequest::setResourceOwnerAccount(const std::string& resourceOwnerAccount) { resourceOwnerAccount_ = resourceOwnerAccount; setParameter("ResourceOwnerAccount", resourceOwnerAccount); } std::string DescribeResourceUsageRequest::getClientToken()const { return clientToken_; } void DescribeResourceUsageRequest::setClientToken(const std::string& clientToken) { clientToken_ = clientToken; setParameter("ClientToken", clientToken); } std::string DescribeResourceUsageRequest::getOwnerAccount()const { return ownerAccount_; } void DescribeResourceUsageRequest::setOwnerAccount(const std::string& ownerAccount) { ownerAccount_ = ownerAccount; setParameter("OwnerAccount", ownerAccount); } std::string DescribeResourceUsageRequest::getDBInstanceId()const { return dBInstanceId_; } void DescribeResourceUsageRequest::setDBInstanceId(const std::string& dBInstanceId) { dBInstanceId_ = dBInstanceId; setParameter("DBInstanceId", dBInstanceId); } long DescribeResourceUsageRequest::getOwnerId()const { return ownerId_; } void DescribeResourceUsageRequest::setOwnerId(long ownerId) { ownerId_ = ownerId; setParameter("OwnerId", std::to_string(ownerId)); } std::string DescribeResourceUsageRequest::getAccessKeyId()const { return accessKeyId_; } void DescribeResourceUsageRequest::setAccessKeyId(const std::string& accessKeyId) { accessKeyId_ = accessKeyId; setParameter("AccessKeyId", accessKeyId); }
[ "wb-flc318515@alibaba-inc.com" ]
wb-flc318515@alibaba-inc.com
b6eb7c6b9828bb5820acc570e454f064b56d6485
bf8e96b9e15bf862e05a5f9cd0f36b5e790bfe78
/CPE553-2020s/553assignment05/Feng_Liu_hwpointers.cpp
4462d91533042955d36bd33681b1e03abd7133cd
[]
no_license
fengliu1227/Cpp-code
6503f7357ee5a13bdeedf37f1cdd5f833fe5e668
c7498fcd93f92ffff686e411164a4447ad62fb89
refs/heads/master
2023-03-09T06:09:00.450318
2021-02-22T07:59:49
2021-02-22T07:59:49
259,941,648
0
0
null
null
null
null
UTF-8
C++
false
false
994
cpp
#include <iostream> using namespace std; // fill the array x with zeros (using pointer) void fill(int x[], int size) { // x[i] = 0; // NO, use pointer!!! *p++ = 0 int* p = x; for(int i = 0; i < size; ++p, ++i){ p = &x[i]; } } // add 1 to every element of x void increment(int x[], int size) { int* p = x; for(int i = 0; i < size; ++p, ++i){ *p += 1; } } // double every element of x void doubleMe(int x[], int size) { int* p = x; for(int i = 0; i < size; ++p, ++i){ *p *= 2; } } // print out every element of x separated by spaces then newline void print(const int x[], int size) { const int *p = x; for(int i = 0; i < size; ++p, ++i){ cout << *p << " "; } cout << endl; } int main() { int x[10] = {1}; const int size = sizeof(x)/sizeof(int); print(x, size); fill(x, size); print(x, size); increment(x, size); print(x, size); doubleMe(x, size); print(x, size); }
[ "fengliu1227@outlook.com" ]
fengliu1227@outlook.com
7e0c2089be1c5e199464d86f2b790e984965376c
e77f8c0500790bbf5059b1e2dcfce1957a34dc2f
/CodeView/GridCtrl_src/GridCtrl.cpp
37bc13ea4005adc14e3d1709537fb8389a3eb0f2
[]
no_license
pmosoft/CodeView
f5b7b69729501a6c3b8627a43b6d61084d0757a3
3944e29ae6c5960fb1eb9e06ec22ea2953b822ad
refs/heads/master
2021-01-17T18:10:53.559409
2017-01-23T14:52:00
2017-01-23T14:52:00
71,216,217
0
0
null
null
null
null
UTF-8
C++
false
false
225,305
cpp
// GridCtrl.cpp : implementation file // // MFC Grid Control v2.26 // // Written by Chris Maunder <chris@codeproject.com> // Copyright (c) 1998-2005. All Rights Reserved. / // The code contained in this file was based on the original // WorldCom Grid control written by Joe Willcoxson, // mailto:chinajoe@aol.com // http://users.aol.com/chinajoe // (These addresses may be out of date) The code has gone through // so many modifications that I'm not sure if there is even a single // original line of code. In any case Joe's code was a great // framework on which to build. // // This code may be used in compiled form in any way you desire. This // file may be redistributed unmodified by any means PROVIDING it is // not sold for profit without the authors written consent, and // providing that this notice and the authors name and all copyright // notices remains intact. // // An email letting me know how you are using it would be nice as well. // // This file is provided "as is" with no expressed or implied warranty. // The author accepts no liability for any damage/loss of business that // this product may cause. // // Expect bugs! // // Please use and enjoy, and let me know of any bugs/mods/improvements // that you have found/implemented and I will fix/incorporate them into // this file. // // History: // -------- // This control is constantly evolving, sometimes due to new features that I // feel are necessary, and sometimes due to existing bugs. Where possible I // have credited the changes to those who contributed code corrections or // enhancements (names in brackets) or code suggestions (suggested by...) // // 1.0 - 1.13 20 Feb 1998 - 6 May 1999 // First release version. Progressed from being a basic // grid based on the original WorldCom Grid control // written by Joe Willcoxson (mailto:chinajoe@aol.com, // http://users.aol.com/chinajoe) to something a little // more feature rich. Rewritten so many times I doubt // there is a single line of Joe's code left. Many, many, // MANY people sent in bug reports and fixes. Thank you // all. // // 2.0 1 Feb 2000 // Rewritten to make the grid more object oriented, in // that the CGridCell class now takes care of cell-specific // tasks. This makes the code more robust, but more // importantly it allows the simple insertion of other // types of cells. // // 2.10 11 Mar 2000 - Ken Bertelson and Chris Maunder // - Additions for virtual CGridCell support of embedded tree // & cell buttons implementation // - Optional WYSIWYG printing // - Awareness of hidden (0 width/height) rows and columns for // key movements, cut, copy, paste, and autosizing // - CGridCell can make title tips display any text rather than // cell text only // - Minor vis bug fixes // - CGridCtrl now works with CGridCellBase instead of CGridCell // This is a taste of things to come. // // 2.20 30 Jul 2000 - Chris Maunder // - Font storage optimised (suggested by Martin Richter) // - AutoSizeColumn works on either column header, data or both // - EnsureVisible. The saga continues... (Ken) // - Rewrote exception handling // - Added TrackFocusCell and FrameFocusCell properties, as well as // ExpandLastColumn (suggested by Bruce E. Stemplewski). // - InsertColumn now allows you to insert columns at the end of the // column range (David Weibel) // - Shift-cell-selection more intuitive // - API change: Set/GetGridColor now Set/GetGridLineColor // - API change: Set/GetBkColor now Set/GetGridBkColor // - API change: Set/GetTextColor, Set/GetTextBkColor depricated // - API change: Set/GetFixedTextColor, Set/GetFixedBkColor depricated // - Stupid DDX_GridControl workaround removed. // - Added "virtual mode" via Set/GetVirtualMode // - Added SetCallbackFunc to allow callback functions in virtual mode // - Added Set/GetAutoSizeStyle // - AutoSize() bug fixed // - added GVIS_FIXEDROW, GVIS_FIXEDCOL states // - added Get/SetFixed[Row|Column]Selection // - cell "Get" methods now const'd. Sorry folks... // - GetMouseScrollLines now uses win98/W2K friendly code // - WS_EX_CLIENTEDGE style now implicit // // [ Only the latest version and major version changes will be shown ] //// // 2.25 13 Mar 2004 - Chris Maunder // - Minor changes so it will compile in VS.NET (inc. Whidbey) // - Fixed minor bug in EnsureVisible - Junlin Xu // - Changed AfxGetInstanceHandle for AfxGetResourceHandle in RegisterWindowClass // - Various changes thanks to Yogurt // // 2.26 13 Dec 2005 - Pierre Couderc // - Added sort in Virtual mode // - Change row/column order programatically or via drag and drop // - Added save/restore layer (for undoing row/column order changes) // // TODO: 1) Implement sparse grids (super easy now) // 2) Fix it so that as you drag select, the speed of selection increases // with time. // 3) Scrolling is still a little dodgy (too much grey area). I know there // is a simple fix but it's been a low priority // // ISSUES: 1) WindowFromPoint seems to do weird things in W2K. Causing problems for // the rigt-click-on-titletip code. // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "MemDC.h" #include "GridCtrl.h" #include <algorithm> // OLE stuff for clipboard operations #include <afxadv.h> // For CSharedFile #include <afxconv.h> // For LPTSTR -> LPSTR macros #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif // Spit out some messages as a sanity check for programmers #ifdef GRIDCONTROL_NO_TITLETIPS #pragma message(" -- CGridCtrl: No titletips for cells with large data") #endif #ifdef GRIDCONTROL_NO_DRAGDROP #pragma message(" -- CGridCtrl: No OLE drag and drop") #endif #ifdef GRIDCONTROL_NO_CLIPBOARD #pragma message(" -- CGridCtrl: No clipboard support") #endif #ifdef GRIDCONTROL_NO_PRINTING #pragma message(" -- CGridCtrl: No printing support") #endif IMPLEMENT_DYNCREATE(CGridCtrl, CWnd) // Get the number of lines to scroll with each mouse wheel notch // Why doesn't windows give us this function??? UINT GetMouseScrollLines() { int nScrollLines = 3; // reasonable default #ifndef _WIN32_WCE // Do things the hard way in win95 OSVERSIONINFO VersionInfo; VersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); if (!GetVersionEx(&VersionInfo) || (VersionInfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS && VersionInfo.dwMinorVersion == 0)) { HKEY hKey; if (RegOpenKeyEx(HKEY_CURRENT_USER, _T("Control Panel\\Desktop"), 0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS) { TCHAR szData[128]; DWORD dwKeyDataType; DWORD dwDataBufSize = sizeof(szData); if (RegQueryValueEx(hKey, _T("WheelScrollLines"), NULL, &dwKeyDataType, (LPBYTE) &szData, &dwDataBufSize) == ERROR_SUCCESS) { nScrollLines = _tcstoul(szData, NULL, 10); } RegCloseKey(hKey); } } // win98 or greater else SystemParametersInfo (SPI_GETWHEELSCROLLLINES, 0, &nScrollLines, 0); #endif return nScrollLines; } ///////////////////////////////////////////////////////////////////////////// // CGridCtrl CGridCtrl::CGridCtrl(int nRows, int nCols, int nFixedRows, int nFixedCols) { RegisterWindowClass(); #if !defined(GRIDCONTROL_NO_DRAGDROP) || !defined(GRIDCONTROL_NO_CLIPBOARD) _AFX_THREAD_STATE* pState = AfxGetThreadState(); if (!pState->m_bNeedTerm && !AfxOleInit()) AfxMessageBox(_T("OLE initialization failed. Make sure that the OLE libraries are the correct version")); #endif // Store the system colours in case they change. The gridctrl uses // these colours, and in OnSysColorChange we can check to see if // the gridctrl colours have been changed from the system colours. // If they have, then leave them, otherwise change them to reflect // the new system colours. m_crWindowText = ::GetSysColor(COLOR_WINDOWTEXT); m_crWindowColour = ::GetSysColor(COLOR_WINDOW); m_cr3DFace = ::GetSysColor(COLOR_3DFACE); m_crShadow = ::GetSysColor(COLOR_3DSHADOW); m_crGridLineColour = RGB(192,192,192); m_nRows = 0; m_nCols = 0; m_nFixedRows = 0; m_nFixedCols = 0; m_InDestructor = false; m_bVirtualMode = FALSE; m_pfnCallback = NULL; m_nVScrollMax = 0; // Scroll position m_nHScrollMax = 0; m_nRowsPerWheelNotch = GetMouseScrollLines(); // Get the number of lines // per mouse wheel notch to scroll m_nBarState = GVL_NONE; m_MouseMode = MOUSE_NOTHING; m_nGridLines = GVL_BOTH; m_bEditable = TRUE; m_bListMode = FALSE; m_bSingleRowSelection = FALSE; m_bSingleColSelection = FALSE; m_bLMouseButtonDown = FALSE; m_bRMouseButtonDown = FALSE; m_bAllowDraw = TRUE; // allow draw updates m_bEnableSelection = TRUE; m_bFixedColumnSelection = TRUE; m_bFixedRowSelection = TRUE; m_bAllowRowResize = TRUE; m_bAllowColumnResize = TRUE; m_bSortOnClick = FALSE; // Sort on header row click m_bHandleTabKey = TRUE; #ifdef _WIN32_WCE m_bDoubleBuffer = FALSE; // Use double buffering to avoid flicker? #else m_bDoubleBuffer = TRUE; // Use double buffering to avoid flicker? #endif m_bTitleTips = TRUE; // show cell title tips m_bWysiwygPrinting = FALSE; // use size-to-width printing m_bHiddenColUnhide = TRUE; // 0-width columns can be expanded via mouse m_bHiddenRowUnhide = TRUE; // 0-Height rows can be expanded via mouse m_bAllowColHide = TRUE; // Columns can be contracted to 0-width via mouse m_bAllowRowHide = TRUE; // Rows can be contracted to 0-height via mouse m_bAscending = TRUE; // sorting stuff m_nSortColumn = -1; m_pfnCompare = NULL; m_pfnVirtualCompare = NULL; m_nAutoSizeColumnStyle = GVS_BOTH; // Autosize grid using header and data info m_nTimerID = 0; // For drag-selection m_nTimerInterval = 25; // (in milliseconds) m_nResizeCaptureRange = 3; // When resizing columns/row, the cursor has to be // within +/-3 pixels of the dividing line for // resizing to be possible m_pImageList = NULL; // Images in the grid m_bAllowDragAndDrop = FALSE; // for drag and drop - EFW - off by default m_bTrackFocusCell = TRUE; // Track Focus cell? m_bFrameFocus = TRUE; // Frame the selected cell? m_AllowReorderColumn = false; m_QuitFocusOnTab = false; m_AllowSelectRowInFixedCol = false; m_bDragRowMode = TRUE; // allow to drop a line over another one to change row order m_pRtcDefault = RUNTIME_CLASS(CGridCell); SetupDefaultCells(); SetGridBkColor(m_crShadow); // Set up the initial grid size SetRowCount(nRows); SetColumnCount(nCols); SetFixedRowCount(nFixedRows); SetFixedColumnCount(nFixedCols); SetTitleTipTextClr(CLR_DEFAULT); //FNA SetTitleTipBackClr(CLR_DEFAULT); // set initial selection range (ie. none) m_SelectedCellMap.RemoveAll(); m_PrevSelectedCellMap.RemoveAll(); #if !defined(_WIN32_WCE_NO_PRINTING) && !defined(GRIDCONTROL_NO_PRINTING) // EFW - Added to support shaded/unshaded printout and // user-definable margins. m_bShadedPrintOut = TRUE; SetPrintMarginInfo(2, 2, 4, 4, 1, 1, 1); #endif } CGridCtrl::~CGridCtrl() { m_InDestructor = true; DeleteAllItems(); #ifndef GRIDCONTROL_NO_TITLETIPS if (m_bTitleTips && ::IsWindow(m_TitleTip.GetSafeHwnd())) m_TitleTip.DestroyWindow(); #endif DestroyWindow(); #if !defined(GRIDCONTROL_NO_DRAGDROP) || !defined(GRIDCONTROL_NO_CLIPBOARD) // BUG FIX - EFW COleDataSource *pSource = COleDataSource::GetClipboardOwner(); if(pSource) COleDataSource::FlushClipboard(); #endif } // Register the window class if it has not already been registered. BOOL CGridCtrl::RegisterWindowClass() { WNDCLASS wndcls; //HINSTANCE hInst = AfxGetInstanceHandle(); HINSTANCE hInst = AfxGetResourceHandle(); if (!(::GetClassInfo(hInst, GRIDCTRL_CLASSNAME, &wndcls))) { // otherwise we need to register a new class wndcls.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW; wndcls.lpfnWndProc = ::DefWindowProc; wndcls.cbClsExtra = wndcls.cbWndExtra = 0; wndcls.hInstance = hInst; wndcls.hIcon = NULL; #ifndef _WIN32_WCE_NO_CURSOR wndcls.hCursor = AfxGetApp()->LoadStandardCursor(IDC_ARROW); #else wndcls.hCursor = 0; #endif wndcls.hbrBackground = (HBRUSH) (COLOR_3DFACE + 1); wndcls.lpszMenuName = NULL; wndcls.lpszClassName = GRIDCTRL_CLASSNAME; if (!AfxRegisterClass(&wndcls)) { AfxThrowResourceException(); return FALSE; } } return TRUE; } BOOL CGridCtrl::Initialise() { // Stop re-entry problems static BOOL bInProcedure = FALSE; if (bInProcedure) return FALSE; bInProcedure = TRUE; #ifndef GRIDCONTROL_NO_TITLETIPS m_TitleTip.SetParentWnd(this); #endif // This would be a good place to register the droptarget but // unfortunately this causes problems if you are using the // grid in a view. // Moved from OnSize. //#ifndef GRIDCONTROL_NO_DRAGDROP // m_DropTarget.Register(this); //#endif if (::IsWindow(m_hWnd)) ModifyStyleEx(0, WS_EX_CLIENTEDGE); // Kludge: Make sure the client edge shows // This is so horrible it makes my eyes water. CRect rect; GetWindowRect(rect); CWnd* pParent = GetParent(); if (pParent != NULL) pParent->ScreenToClient(rect); rect.InflateRect(1,1); MoveWindow(rect); rect.DeflateRect(1,1); MoveWindow(rect); bInProcedure = FALSE; return TRUE; } // creates the control - use like any other window create control BOOL CGridCtrl::Create(const RECT& rect, CWnd* pParentWnd, UINT nID, DWORD dwStyle) { ASSERT(pParentWnd->GetSafeHwnd()); if (!CWnd::Create(GRIDCTRL_CLASSNAME, NULL, dwStyle, rect, pParentWnd, nID)) return FALSE; //Initialise(); - called in PreSubclassWnd // The number of rows and columns will only be non-zero if the constructor // was called with non-zero initialising parameters. If this window was created // using a dialog template then the number of rows and columns will be 0 (which // means that the code below will not be needed - which is lucky 'cause it ain't // gonna get called in a dialog-template-type-situation. TRY { m_arRowHeights.SetSize(m_nRows); // initialize row heights m_arColWidths.SetSize(m_nCols); // initialize column widths } CATCH (CMemoryException, e) { e->ReportError(); return FALSE; } END_CATCH int i; for (i = 0; i < m_nRows; i++) m_arRowHeights[i] = m_cellDefault.GetHeight(); for (i = 0; i < m_nCols; i++) m_arColWidths[i] = m_cellDefault.GetWidth(); return TRUE; } void CGridCtrl::SetupDefaultCells() { m_cellDefault.SetGrid(this); // Normal editable cell m_cellFixedColDef.SetGrid(this); // Cell for fixed columns m_cellFixedRowDef.SetGrid(this); // Cell for fixed rows m_cellFixedRowColDef.SetGrid(this); // Cell for area overlapped by fixed columns/rows m_cellDefault.SetTextClr(m_crWindowText); m_cellDefault.SetBackClr(m_crWindowColour); m_cellFixedColDef.SetTextClr(m_crWindowText); m_cellFixedColDef.SetBackClr(m_cr3DFace); m_cellFixedRowDef.SetTextClr(m_crWindowText); m_cellFixedRowDef.SetBackClr(m_cr3DFace); m_cellFixedRowColDef.SetTextClr(m_crWindowText); m_cellFixedRowColDef.SetBackClr(m_cr3DFace); } void CGridCtrl::PreSubclassWindow() { CWnd::PreSubclassWindow(); //HFONT hFont = ::CreateFontIndirect(m_cellDefault.GetFont()); //OnSetFont((LPARAM)hFont, 0); //DeleteObject(hFont); Initialise(); } // Sends a message to the parent in the form of a WM_NOTIFY message with // a NM_GRIDVIEW structure attached LRESULT CGridCtrl::SendMessageToParent(int nRow, int nCol, int nMessage) const { if (!IsWindow(m_hWnd)) return 0; NM_GRIDVIEW nmgv; nmgv.iRow = nRow; nmgv.iColumn = nCol; nmgv.hdr.hwndFrom = m_hWnd; nmgv.hdr.idFrom = GetDlgCtrlID(); nmgv.hdr.code = nMessage; CWnd *pOwner = GetOwner(); if (pOwner && IsWindow(pOwner->m_hWnd)) return pOwner->SendMessage(WM_NOTIFY, nmgv.hdr.idFrom, (LPARAM)&nmgv); else return 0; } // Send a request to the parent to return information on a given cell LRESULT CGridCtrl::SendDisplayRequestToParent(GV_DISPINFO* pDisplayInfo) const { if (!IsWindow(m_hWnd)) return 0; // Fix up the message headers pDisplayInfo->hdr.hwndFrom = m_hWnd; pDisplayInfo->hdr.idFrom = GetDlgCtrlID(); pDisplayInfo->hdr.code = GVN_GETDISPINFO; // Send the message CWnd *pOwner = GetOwner(); if (pOwner && IsWindow(pOwner->m_hWnd)) return pOwner->SendMessage(WM_NOTIFY, pDisplayInfo->hdr.idFrom, (LPARAM)pDisplayInfo); else return 0; } // Send a hint to the parent about caching information LRESULT CGridCtrl::SendCacheHintToParent(const CCellRange& range) const { if (!IsWindow(m_hWnd)) return 0; GV_CACHEHINT CacheHint; // Fix up the message headers CacheHint.hdr.hwndFrom = m_hWnd; CacheHint.hdr.idFrom = GetDlgCtrlID(); CacheHint.hdr.code = GVN_ODCACHEHINT; CacheHint.range = range; // Send the message CWnd *pOwner = GetOwner(); if (pOwner && IsWindow(pOwner->m_hWnd)) return pOwner->SendMessage(WM_NOTIFY, CacheHint.hdr.idFrom, (LPARAM)&CacheHint); else return 0; } #define LAYER_SIGNATURE (0x5FD4E64) int CGridCtrl::GetLayer(int** pLayer) // used to save and restore order of columns { // gives back the size of the area (do not forget to delete pLayer) int Length = 2+GetColumnCount()*2; int *Layer = new int[Length]; // the caller is supposed to delete it Layer[0]= LAYER_SIGNATURE; Layer[1]= GetColumnCount(); memcpy(&Layer[2], &m_arColOrder[0], GetColumnCount()*sizeof(int)); memcpy(&Layer[2+GetColumnCount()], &m_arColWidths[0], GetColumnCount()*sizeof(int)); *pLayer = Layer; return Length; } void CGridCtrl::SetLayer(int* pLayer) { // coming from a previous GetLayer (ignored if not same number of column, or the same revision number) if(pLayer[0] != LAYER_SIGNATURE) return; if(pLayer[1] != GetColumnCount()) return; /* TRACE(" %d == %d \n",m_arColOrder[0],pLayer[2]); TRACE(" %d == %d \n",m_arColOrder[1],pLayer[3]); TRACE(" %d == %d \n",m_arColOrder[2],pLayer[4]); TRACE(" %d == %d \n",m_arColWidths[0],pLayer[2+3]); TRACE(" %d == %d \n",m_arColWidths[1],pLayer[3+3]); TRACE(" %d == %d \n",m_arColWidths[2],pLayer[4+3]); TRACE(" %d == %d \n",GetColumnCount(),3); ASSERT(m_arColOrder[0]==pLayer[2]); ASSERT(m_arColOrder[1]==pLayer[3]); ASSERT(m_arColOrder[2]==pLayer[4]); ASSERT(m_arColWidths[0]==pLayer[2+3]); ASSERT(m_arColWidths[1]==pLayer[3+3]); ASSERT(m_arColWidths[2]==pLayer[4+3]); ASSERT(GetColumnCount()==3); */ memcpy(&m_arColOrder[0],&pLayer[2], GetColumnCount()*sizeof(int)); memcpy(&m_arColWidths[0],&pLayer[2+GetColumnCount()], GetColumnCount()*sizeof(int)); } BEGIN_MESSAGE_MAP(CGridCtrl, CWnd) //EFW - Added ON_WM_RBUTTONUP //{{AFX_MSG_MAP(CGridCtrl) ON_WM_PAINT() ON_WM_HSCROLL() ON_WM_VSCROLL() ON_WM_SIZE() ON_WM_LBUTTONUP() ON_WM_LBUTTONDOWN() ON_WM_MOUSEMOVE() ON_WM_TIMER() ON_WM_GETDLGCODE() ON_WM_KEYDOWN() ON_WM_CHAR() ON_WM_LBUTTONDBLCLK() ON_WM_ERASEBKGND() ON_UPDATE_COMMAND_UI(ID_EDIT_SELECT_ALL, OnUpdateEditSelectAll) ON_COMMAND(ID_EDIT_SELECT_ALL, OnEditSelectAll) ON_WM_SYSKEYDOWN() //}}AFX_MSG_MAP #ifndef _WIN32_WCE_NO_CURSOR ON_WM_SETCURSOR() #endif #ifndef _WIN32_WCE ON_WM_RBUTTONUP() ON_WM_SYSCOLORCHANGE() ON_WM_CAPTURECHANGED() #endif #ifndef GRIDCONTROL_NO_CLIPBOARD ON_COMMAND(ID_EDIT_COPY, OnEditCopy) ON_UPDATE_COMMAND_UI(ID_EDIT_COPY, OnUpdateEditCopy) ON_COMMAND(ID_EDIT_CUT, OnEditCut) ON_UPDATE_COMMAND_UI(ID_EDIT_CUT, OnUpdateEditCut) ON_COMMAND(ID_EDIT_PASTE, OnEditPaste) ON_UPDATE_COMMAND_UI(ID_EDIT_PASTE, OnUpdateEditPaste) #endif #if (_WIN32_WCE >= 210) ON_WM_SETTINGCHANGE() #endif #if !defined(_WIN32_WCE) && (_MFC_VER >= 0x0421) ON_WM_MOUSEWHEEL() #endif ON_MESSAGE(WM_SETFONT, OnSetFont) ON_MESSAGE(WM_GETFONT, OnGetFont) ON_MESSAGE(WM_IME_CHAR, OnImeChar) ON_NOTIFY(GVN_ENDLABELEDIT, IDC_INPLACE_CONTROL, OnEndInPlaceEdit) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CGridCtrl message handlers void CGridCtrl::OnPaint() { CPaintDC dc(this); // device context for painting if (m_bDoubleBuffer) // Use a memory DC to remove flicker { CGridCtrlMemDC MemDC(&dc); OnDraw(&MemDC); } else // Draw raw - this helps in debugging vis problems. OnDraw(&dc); } BOOL CGridCtrl::OnEraseBkgnd(CDC* /*pDC*/) { return TRUE; // Don't erase the background. } // Custom background erasure. This gets called from within the OnDraw function, // since we will (most likely) be using a memory DC to stop flicker. If we just // erase the background normally through OnEraseBkgnd, and didn't fill the memDC's // selected bitmap with colour, then all sorts of vis problems would occur void CGridCtrl::EraseBkgnd(CDC* pDC) { CRect VisRect, ClipRect, rect; CBrush FixedRowColBack(GetDefaultCell(TRUE, TRUE)->GetBackClr()), FixedRowBack(GetDefaultCell(TRUE, FALSE)->GetBackClr()), FixedColBack(GetDefaultCell(FALSE, TRUE)->GetBackClr()), TextBack(GetDefaultCell(FALSE, FALSE)->GetBackClr()); CBrush Back(GetGridBkColor()); //CBrush Back(GetTextBkColor()); if (pDC->GetClipBox(ClipRect) == ERROR) return; GetVisibleNonFixedCellRange(VisRect); int nFixedColumnWidth = GetFixedColumnWidth(); int nFixedRowHeight = GetFixedRowHeight(); // Draw Fixed row/column background if (ClipRect.left < nFixedColumnWidth && ClipRect.top < nFixedRowHeight) pDC->FillRect(CRect(ClipRect.left, ClipRect.top, nFixedColumnWidth, nFixedRowHeight), &FixedRowColBack); // Draw Fixed columns background if (ClipRect.left < nFixedColumnWidth && ClipRect.top < VisRect.bottom) pDC->FillRect(CRect(ClipRect.left, ClipRect.top, nFixedColumnWidth, VisRect.bottom), &FixedColBack); // Draw Fixed rows background if (ClipRect.top < nFixedRowHeight && ClipRect.right > nFixedColumnWidth && ClipRect.left < VisRect.right) pDC->FillRect(CRect(nFixedColumnWidth-1, ClipRect.top, VisRect.right, nFixedRowHeight), &FixedRowBack); // Draw non-fixed cell background if (rect.IntersectRect(VisRect, ClipRect)) { CRect CellRect(__max(nFixedColumnWidth, rect.left), __max(nFixedRowHeight, rect.top), rect.right, rect.bottom); pDC->FillRect(CellRect, &TextBack); } // Draw right hand side of window outside grid if (VisRect.right < ClipRect.right) pDC->FillRect(CRect(VisRect.right, ClipRect.top, ClipRect.right, ClipRect.bottom), &Back); // Draw bottom of window below grid if (VisRect.bottom < ClipRect.bottom && ClipRect.left < VisRect.right) pDC->FillRect(CRect(ClipRect.left, VisRect.bottom, VisRect.right, ClipRect.bottom), &Back); } void CGridCtrl::OnSize(UINT nType, int cx, int cy) { static BOOL bAlreadyInsideThisProcedure = FALSE; if (bAlreadyInsideThisProcedure) return; if (!::IsWindow(m_hWnd)) return; // This is not the ideal place to register the droptarget #ifndef GRIDCONTROL_NO_DRAGDROP m_DropTarget.Register(this); #endif // Start re-entry blocking bAlreadyInsideThisProcedure = TRUE; EndEditing(); // destroy any InPlaceEdit's CWnd::OnSize(nType, cx, cy); ResetScrollBars(); // End re-entry blocking bAlreadyInsideThisProcedure = FALSE; } UINT CGridCtrl::OnGetDlgCode() { UINT nCode = DLGC_WANTARROWS | DLGC_WANTCHARS; // DLGC_WANTALLKEYS; // if (m_bHandleTabKey && !IsCTRLpressed()) nCode |= DLGC_WANTTAB; return nCode; } #ifndef _WIN32_WCE // If system colours change, then redo colours void CGridCtrl::OnSysColorChange() { CWnd::OnSysColorChange(); if (GetDefaultCell(FALSE, FALSE)->GetTextClr() == m_crWindowText) // Still using system colours GetDefaultCell(FALSE, FALSE)->SetTextClr(::GetSysColor(COLOR_WINDOWTEXT)); // set to new system colour if (GetDefaultCell(FALSE, FALSE)->GetBackClr() == m_crWindowColour) GetDefaultCell(FALSE, FALSE)->SetBackClr(::GetSysColor(COLOR_WINDOW)); if (GetDefaultCell(TRUE, FALSE)->GetTextClr() == m_crWindowText) // Still using system colours GetDefaultCell(TRUE, FALSE)->SetTextClr(::GetSysColor(COLOR_WINDOWTEXT)); // set to new system colour if (GetDefaultCell(TRUE, FALSE)->GetBackClr() == m_crWindowColour) GetDefaultCell(TRUE, FALSE)->SetBackClr(::GetSysColor(COLOR_WINDOW)); if (GetDefaultCell(FALSE, TRUE)->GetTextClr() == m_crWindowText) // Still using system colours GetDefaultCell(FALSE, TRUE)->SetTextClr(::GetSysColor(COLOR_WINDOWTEXT)); // set to new system colour if (GetDefaultCell(FALSE, TRUE)->GetBackClr() == m_crWindowColour) GetDefaultCell(FALSE, TRUE)->SetBackClr(::GetSysColor(COLOR_WINDOW)); if (GetDefaultCell(TRUE, TRUE)->GetTextClr() == m_crWindowText) // Still using system colours GetDefaultCell(TRUE, TRUE)->SetTextClr(::GetSysColor(COLOR_WINDOWTEXT)); // set to new system colour if (GetDefaultCell(TRUE, TRUE)->GetBackClr() == m_crWindowColour) GetDefaultCell(TRUE, TRUE)->SetBackClr(::GetSysColor(COLOR_WINDOW)); if (GetGridBkColor() == m_crShadow) SetGridBkColor(::GetSysColor(COLOR_3DSHADOW)); m_crWindowText = ::GetSysColor(COLOR_WINDOWTEXT); m_crWindowColour = ::GetSysColor(COLOR_WINDOW); m_cr3DFace = ::GetSysColor(COLOR_3DFACE); m_crShadow = ::GetSysColor(COLOR_3DSHADOW); } #endif #ifndef _WIN32_WCE_NO_CURSOR // If we are drag-selecting cells, or drag and dropping, stop now void CGridCtrl::OnCaptureChanged(CWnd *pWnd) { if (pWnd->GetSafeHwnd() == GetSafeHwnd()) return; // kill timer if active if (m_nTimerID != 0) { KillTimer(m_nTimerID); m_nTimerID = 0; } #ifndef GRIDCONTROL_NO_DRAGDROP // Kill drag and drop if active if (m_MouseMode == MOUSE_DRAGGING) m_MouseMode = MOUSE_NOTHING; #endif } #endif #if (_MFC_VER >= 0x0421) || (_WIN32_WCE >= 210) // If system settings change, then redo colours void CGridCtrl::OnSettingChange(UINT uFlags, LPCTSTR lpszSection) { CWnd::OnSettingChange(uFlags, lpszSection); if (GetDefaultCell(FALSE, FALSE)->GetTextClr() == m_crWindowText) // Still using system colours GetDefaultCell(FALSE, FALSE)->SetTextClr(::GetSysColor(COLOR_WINDOWTEXT)); // set to new system colour if (GetDefaultCell(FALSE, FALSE)->GetBackClr() == m_crWindowColour) GetDefaultCell(FALSE, FALSE)->SetBackClr(::GetSysColor(COLOR_WINDOW)); if (GetDefaultCell(TRUE, FALSE)->GetTextClr() == m_crWindowText) // Still using system colours GetDefaultCell(TRUE, FALSE)->SetTextClr(::GetSysColor(COLOR_WINDOWTEXT)); // set to new system colour if (GetDefaultCell(TRUE, FALSE)->GetBackClr() == m_crWindowColour) GetDefaultCell(TRUE, FALSE)->SetBackClr(::GetSysColor(COLOR_WINDOW)); if (GetDefaultCell(FALSE, TRUE)->GetTextClr() == m_crWindowText) // Still using system colours GetDefaultCell(FALSE, TRUE)->SetTextClr(::GetSysColor(COLOR_WINDOWTEXT)); // set to new system colour if (GetDefaultCell(FALSE, TRUE)->GetBackClr() == m_crWindowColour) GetDefaultCell(FALSE, TRUE)->SetBackClr(::GetSysColor(COLOR_WINDOW)); if (GetDefaultCell(TRUE, TRUE)->GetTextClr() == m_crWindowText) // Still using system colours GetDefaultCell(TRUE, TRUE)->SetTextClr(::GetSysColor(COLOR_WINDOWTEXT)); // set to new system colour if (GetDefaultCell(TRUE, TRUE)->GetBackClr() == m_crWindowColour) GetDefaultCell(TRUE, TRUE)->SetBackClr(::GetSysColor(COLOR_WINDOW)); if (GetGridBkColor() == m_crShadow) SetGridBkColor(::GetSysColor(COLOR_3DSHADOW)); m_crWindowText = ::GetSysColor(COLOR_WINDOWTEXT); m_crWindowColour = ::GetSysColor(COLOR_WINDOW); m_cr3DFace = ::GetSysColor(COLOR_3DFACE); m_crShadow = ::GetSysColor(COLOR_3DSHADOW); m_nRowsPerWheelNotch = GetMouseScrollLines(); // Get the number of lines } #endif // For drag-selection. Scrolls hidden cells into view // TODO: decrease timer interval over time to speed up selection over time void CGridCtrl::OnTimer(UINT nIDEvent) { ASSERT(nIDEvent == WM_LBUTTONDOWN); if (nIDEvent != WM_LBUTTONDOWN) return; CPoint pt, origPt; #ifdef _WIN32_WCE if (m_MouseMode == MOUSE_NOTHING) return; origPt = GetMessagePos(); #else if (!GetCursorPos(&origPt)) return; #endif ScreenToClient(&origPt); CRect rect; GetClientRect(rect); int nFixedRowHeight = GetFixedRowHeight(); int nFixedColWidth = GetFixedColumnWidth(); pt = origPt; if (pt.y > rect.bottom) { //SendMessage(WM_VSCROLL, SB_LINEDOWN, 0); SendMessage(WM_KEYDOWN, VK_DOWN, 0); if (pt.x < rect.left) pt.x = rect.left; if (pt.x > rect.right) pt.x = rect.right; pt.y = rect.bottom; OnSelecting(GetCellFromPt(pt)); } else if (pt.y < nFixedRowHeight) { //SendMessage(WM_VSCROLL, SB_LINEUP, 0); SendMessage(WM_KEYDOWN, VK_UP, 0); if (pt.x < rect.left) pt.x = rect.left; if (pt.x > rect.right) pt.x = rect.right; pt.y = nFixedRowHeight + 1; OnSelecting(GetCellFromPt(pt)); } pt = origPt; if (pt.x > rect.right) { // SendMessage(WM_HSCROLL, SB_LINERIGHT, 0); SendMessage(WM_KEYDOWN, VK_RIGHT, 0); if (pt.y < rect.top) pt.y = rect.top; if (pt.y > rect.bottom) pt.y = rect.bottom; pt.x = rect.right; OnSelecting(GetCellFromPt(pt)); } else if (pt.x < nFixedColWidth) { //SendMessage(WM_HSCROLL, SB_LINELEFT, 0); SendMessage(WM_KEYDOWN, VK_LEFT, 0); if (pt.y < rect.top) pt.y = rect.top; if (pt.y > rect.bottom) pt.y = rect.bottom; pt.x = nFixedColWidth + 1; OnSelecting(GetCellFromPt(pt)); } } // move about with keyboard void CGridCtrl::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { if (!IsValid(m_idCurrentCell)) { CWnd::OnKeyDown(nChar, nRepCnt, nFlags); return; } CCellID next = m_idCurrentCell; BOOL bChangeLine = FALSE; BOOL bHorzScrollAction = FALSE; BOOL bVertScrollAction = FALSE; if (IsCTRLpressed()) { switch (nChar) { case 'A': OnEditSelectAll(); break; case 'k': // This is ctrl+ on french keyboard, may need to be better processed for other locales AutoSizeColumns(); Invalidate(); break; #ifndef GRIDCONTROL_NO_CLIPBOARD case 'X': OnEditCut(); break; case VK_INSERT: case 'C': OnEditCopy(); break; case 'V': OnEditPaste(); break; #endif } } #ifndef GRIDCONTROL_NO_CLIPBOARD if (IsSHIFTpressed() &&(nChar == VK_INSERT)) OnEditPaste(); #endif BOOL bFoundVisible; int iOrig; if (nChar == VK_DELETE) { CutSelectedText(); } else if (nChar == VK_DOWN) { // don't let user go to a hidden row bFoundVisible = FALSE; iOrig = next.row; next.row++; while( next.row < GetRowCount()) { if( GetRowHeight( next.row) > 0) { bFoundVisible = TRUE; break; } next.row++; } if( !bFoundVisible) next.row = iOrig; } else if (nChar == VK_UP) { // don't let user go to a hidden row bFoundVisible = FALSE; iOrig = next.row; next.row--; while( next.row >= m_nFixedRows) { if( GetRowHeight( next.row) > 0) { bFoundVisible = TRUE; break; } next.row--; } if( !bFoundVisible) next.row = iOrig; } else if (nChar == VK_RIGHT || (nChar == VK_TAB && !IsSHIFTpressed()) ) { if( (nChar == VK_TAB) && m_QuitFocusOnTab ) { CDialog* p= (CDialog*) GetParent(); if(p) p->NextDlgCtrl(); return; } // don't let user go to a hidden column bFoundVisible = FALSE; iOrig = next.col; next.col++; if (nChar == VK_TAB) { // If we're at the end of a row, go down a row till we find a non-hidden row if (next.col == (GetColumnCount()) && next.row < (GetRowCount() - 1)) { next.row++; while( next.row < GetRowCount()) { if( GetRowHeight(next.row) > 0) { bFoundVisible = TRUE; break; } next.row++; } next.col = m_nFixedCols; // Place focus on first non-fixed column bChangeLine = TRUE; } else CWnd::OnKeyDown(nChar, nRepCnt, nFlags); } // We're on a non-hidden row, so look across for the next non-hidden column while( next.col < GetColumnCount()) { if( GetColumnWidth( next.col) > 0) { bFoundVisible = TRUE; break; } next.col++; } // If nothing worked then don't bother if( !bFoundVisible) next.col = iOrig; } else if (nChar == VK_LEFT || (nChar == VK_TAB && IsSHIFTpressed()) ) { // don't let user go to a hidden column bFoundVisible = FALSE; iOrig = next.col; next.col--; if (nChar == VK_TAB) { if (next.col == (GetFixedColumnCount()-1) && next.row > GetFixedRowCount()) { next.row--; while( next.row > GetFixedRowCount()) { if( GetRowHeight(next.row) > 0) { bFoundVisible = TRUE; break; } next.row--; } next.col = GetColumnCount() - 1; bChangeLine = TRUE; } else CWnd::OnKeyDown(nChar, nRepCnt, nFlags); } while( next.col >= m_nFixedCols) { if( GetColumnWidth( next.col) > 0) { bFoundVisible = TRUE; break; } next.col--; } if( !bFoundVisible) next.col = iOrig; } else if (nChar == VK_NEXT) { CCellID idOldTopLeft = GetTopleftNonFixedCell(); SendMessage(WM_VSCROLL, SB_PAGEDOWN, 0); bVertScrollAction = TRUE; CCellID idNewTopLeft = GetTopleftNonFixedCell(); int increment = idNewTopLeft.row - idOldTopLeft.row; if (increment) { next.row += increment; if (next.row >(GetRowCount() - 1)) next.row = GetRowCount() - 1; } else next.row = GetRowCount() - 1; } else if (nChar == VK_PRIOR) { CCellID idOldTopLeft = GetTopleftNonFixedCell(); SendMessage(WM_VSCROLL, SB_PAGEUP, 0); bVertScrollAction = TRUE; CCellID idNewTopLeft = GetTopleftNonFixedCell(); int increment = idNewTopLeft.row - idOldTopLeft.row; if (increment) { next.row += increment; if (next.row < m_nFixedRows) next.row = m_nFixedRows; } else next.row = m_nFixedRows; } else if (nChar == VK_HOME) { // Home and Ctrl-Home work more like Excel // and don't let user go to a hidden cell if (IsCTRLpressed()) { SendMessage(WM_VSCROLL, SB_TOP, 0); SendMessage(WM_HSCROLL, SB_LEFT, 0); bVertScrollAction = TRUE; bHorzScrollAction = TRUE; next.row = m_nFixedRows; next.col = m_nFixedCols; } else { SendMessage(WM_HSCROLL, SB_LEFT, 0); bHorzScrollAction = TRUE; next.col = m_nFixedCols; } // adjust column to avoid hidden columns and rows while( next.col < GetColumnCount() - 1) { if( GetColumnWidth( next.col) > 0) break; next.col++; } while( next.row < GetRowCount() - 1) { if( GetRowHeight( next.row) > 0) break; next.row++; } } else if (nChar == VK_END) { // End and Ctrl-End work more like Excel // and don't let user go to a hidden cell if (IsCTRLpressed()) { SendMessage(WM_VSCROLL, SB_BOTTOM, 0); SendMessage(WM_HSCROLL, SB_RIGHT, 0); bHorzScrollAction = TRUE; bVertScrollAction = TRUE; next.row = GetRowCount() - 1; next.col = GetColumnCount() - 1; } else { SendMessage(WM_HSCROLL, SB_RIGHT, 0); bHorzScrollAction = TRUE; next.col = GetColumnCount() - 1; } // adjust column to avoid hidden columns and rows while( next.col > m_nFixedCols + 1) { if( GetColumnWidth( next.col) > 0) break; next.col--; } while( next.row > m_nFixedRows + 1) { if( GetRowHeight( next.row) > 0) break; next.row--; } } else if (nChar == VK_F2) { OnEditCell(m_idCurrentCell.row, m_idCurrentCell.col, CPoint( -1, -1), VK_LBUTTON); } else { CWnd::OnKeyDown(nChar, nRepCnt, nFlags); return; } if (next != m_idCurrentCell) { // While moving with the Cursorkeys the current ROW/CELL will get selected // OR Selection will get expanded when SHIFT is pressed // Cut n paste from OnLButtonDown - Franco Bez // Added check for NULL mouse mode - Chris Maunder. if (m_MouseMode == MOUSE_NOTHING) { m_PrevSelectedCellMap.RemoveAll(); m_MouseMode = m_bListMode? MOUSE_SELECT_ROW : MOUSE_SELECT_CELLS; if (!IsSHIFTpressed() || nChar == VK_TAB) m_SelectionStartCell = next; // Notify parent that selection is changing - Arthur Westerman/Scot Brennecke SendMessageToParent(next.row, next.col, GVN_SELCHANGING); OnSelecting(next); SendMessageToParent(next.row, next.col, GVN_SELCHANGED); m_MouseMode = MOUSE_NOTHING; } SetFocusCell(next); if (!IsCellVisible(next)) { switch (nChar) { case VK_RIGHT: SendMessage(WM_HSCROLL, SB_LINERIGHT, 0); bHorzScrollAction = TRUE; break; case VK_LEFT: SendMessage(WM_HSCROLL, SB_LINELEFT, 0); bHorzScrollAction = TRUE; break; case VK_DOWN: SendMessage(WM_VSCROLL, SB_LINEDOWN, 0); bVertScrollAction = TRUE; break; case VK_UP: SendMessage(WM_VSCROLL, SB_LINEUP, 0); bVertScrollAction = TRUE; break; case VK_TAB: if (IsSHIFTpressed()) { if (bChangeLine) { SendMessage(WM_VSCROLL, SB_LINEUP, 0); bVertScrollAction = TRUE; SetScrollPos32(SB_HORZ, m_nHScrollMax); break; } else { SendMessage(WM_HSCROLL, SB_LINELEFT, 0); bHorzScrollAction = TRUE; } } else { if (bChangeLine) { SendMessage(WM_VSCROLL, SB_LINEDOWN, 0); bVertScrollAction = TRUE; SetScrollPos32(SB_HORZ, 0); break; } else { SendMessage(WM_HSCROLL, SB_LINERIGHT, 0); bHorzScrollAction = TRUE; } } break; } EnsureVisible(next); // Make sure cell is visible Invalidate(); } EnsureVisible(next); // Make sure cell is visible if (bHorzScrollAction) SendMessage(WM_HSCROLL, SB_ENDSCROLL, 0); if (bVertScrollAction) SendMessage(WM_VSCROLL, SB_ENDSCROLL, 0); } } void CGridCtrl::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags) { CWnd::OnKeyUp(nChar, nRepCnt, nFlags); } void CGridCtrl::OnSysKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { #ifdef GRIDCONTROL_USE_TITLETIPS m_TitleTip.Hide(); // hide any titletips #endif CWnd::OnSysKeyDown(nChar, nRepCnt, nFlags); } // Instant editing of cells when keys are pressed void CGridCtrl::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) { // EFW - BUG FIX if (!IsCTRLpressed() && m_MouseMode == MOUSE_NOTHING && nChar != VK_ESCAPE) { if (!m_bHandleTabKey || (m_bHandleTabKey && nChar != VK_TAB)) OnEditCell(m_idCurrentCell.row, m_idCurrentCell.col, CPoint( -1, -1), nChar); } CWnd::OnChar(nChar, nRepCnt, nFlags); } // Added by KiteFly LRESULT CGridCtrl::OnImeChar(WPARAM wCharCode, LPARAM) { // EFW - BUG FIX if (!IsCTRLpressed() && m_MouseMode == MOUSE_NOTHING && wCharCode != VK_ESCAPE) OnEditCell(m_idCurrentCell.row, m_idCurrentCell.col, CPoint( -1, -1), (UINT)wCharCode); return 0; } // Callback from any CInPlaceEdits that ended. This just calls OnEndEditCell, // refreshes the edited cell and moves onto next cell if the return character // from the edit says we should. void CGridCtrl::OnEndInPlaceEdit(NMHDR* pNMHDR, LRESULT* pResult) { GV_DISPINFO *pgvDispInfo = (GV_DISPINFO *)pNMHDR; GV_ITEM *pgvItem = &pgvDispInfo->item; // In case OnEndInPlaceEdit called as window is being destroyed if (!IsWindow(GetSafeHwnd())) return; OnEndEditCell(pgvItem->row, pgvItem->col, pgvItem->strText); //InvalidateCellRect(CCellID(pgvItem->row, pgvItem->col)); switch (pgvItem->lParam) { case VK_TAB: case VK_DOWN: case VK_UP: case VK_RIGHT: case VK_LEFT: case VK_NEXT: case VK_PRIOR: case VK_HOME: case VK_END: OnKeyDown((UINT)pgvItem->lParam, 0, 0); OnEditCell(m_idCurrentCell.row, m_idCurrentCell.col, CPoint( -1, -1), (UINT)pgvItem->lParam); } *pResult = 0; } // Handle horz scrollbar notifications void CGridCtrl::OnHScroll(UINT nSBCode, UINT /*nPos*/, CScrollBar* /*pScrollBar*/) { EndEditing(); #ifndef GRIDCONTROL_NO_TITLETIPS m_TitleTip.Hide(); // hide any titletips #endif int scrollPos = GetScrollPos32(SB_HORZ); CCellID idTopLeft = GetTopleftNonFixedCell(); CRect rect; GetClientRect(rect); switch (nSBCode) { case SB_LINERIGHT: if (scrollPos < m_nHScrollMax) { // may have contiguous hidden columns. Blow by them while (idTopLeft.col < (GetColumnCount()-1) && GetColumnWidth( idTopLeft.col) < 1 ) { idTopLeft.col++; } int xScroll = GetColumnWidth(idTopLeft.col); SetScrollPos32(SB_HORZ, scrollPos + xScroll); if (GetScrollPos32(SB_HORZ) == scrollPos) break; // didn't work rect.left = GetFixedColumnWidth(); //rect.left = GetFixedColumnWidth() + xScroll; //ScrollWindow(-xScroll, 0, rect); //rect.left = rect.right - xScroll; InvalidateRect(rect); } break; case SB_LINELEFT: if (scrollPos > 0 && idTopLeft.col > GetFixedColumnCount()) { int iColToUse = idTopLeft.col-1; // may have contiguous hidden columns. Blow by them while( iColToUse > GetFixedColumnCount() && GetColumnWidth( iColToUse) < 1 ) { iColToUse--; } int xScroll = GetColumnWidth(iColToUse); SetScrollPos32(SB_HORZ, __max(0, scrollPos - xScroll)); rect.left = GetFixedColumnWidth(); //ScrollWindow(xScroll, 0, rect); //rect.right = rect.left + xScroll; InvalidateRect(rect); } break; case SB_PAGERIGHT: if (scrollPos < m_nHScrollMax) { rect.left = GetFixedColumnWidth(); int offset = rect.Width(); int pos = min(m_nHScrollMax, scrollPos + offset); SetScrollPos32(SB_HORZ, pos); rect.left = GetFixedColumnWidth(); InvalidateRect(rect); } break; case SB_PAGELEFT: if (scrollPos > 0) { rect.left = GetFixedColumnWidth(); int offset = -rect.Width(); int pos = __max(0, scrollPos + offset); SetScrollPos32(SB_HORZ, pos); rect.left = GetFixedColumnWidth(); InvalidateRect(rect); } break; case SB_THUMBPOSITION: case SB_THUMBTRACK: { SetScrollPos32(SB_HORZ, GetScrollPos32(SB_HORZ, TRUE)); m_idTopLeftCell.row = -1; CCellID idNewTopLeft = GetTopleftNonFixedCell(); if (idNewTopLeft != idTopLeft) { rect.left = GetFixedColumnWidth(); InvalidateRect(rect); } } break; case SB_LEFT: if (scrollPos > 0) { SetScrollPos32(SB_HORZ, 0); Invalidate(); } break; case SB_RIGHT: if (scrollPos < m_nHScrollMax) { SetScrollPos32(SB_HORZ, m_nHScrollMax); Invalidate(); } break; default: break; } } // Handle vert scrollbar notifications void CGridCtrl::OnVScroll(UINT nSBCode, UINT /*nPos*/, CScrollBar* /*pScrollBar*/) { EndEditing(); #ifndef GRIDCONTROL_NO_TITLETIPS m_TitleTip.Hide(); // hide any titletips #endif // Get the scroll position ourselves to ensure we get a 32 bit value int scrollPos = GetScrollPos32(SB_VERT); CCellID idTopLeft = GetTopleftNonFixedCell(); CRect rect; GetClientRect(rect); switch (nSBCode) { case SB_LINEDOWN: if (scrollPos < m_nVScrollMax) { // may have contiguous hidden rows. Blow by them while( idTopLeft.row < (GetRowCount()-1) && GetRowHeight( idTopLeft.row) < 1 ) { idTopLeft.row++; } int yScroll = GetRowHeight(idTopLeft.row); SetScrollPos32(SB_VERT, scrollPos + yScroll); if (GetScrollPos32(SB_VERT) == scrollPos) break; // didn't work rect.top = GetFixedRowHeight(); //rect.top = GetFixedRowHeight() + yScroll; //ScrollWindow(0, -yScroll, rect); //rect.top = rect.bottom - yScroll; InvalidateRect(rect); } break; case SB_LINEUP: if (scrollPos > 0 && idTopLeft.row > GetFixedRowCount()) { int iRowToUse = idTopLeft.row-1; // may have contiguous hidden rows. Blow by them while( iRowToUse > GetFixedRowCount() && GetRowHeight( iRowToUse) < 1 ) { iRowToUse--; } int yScroll = GetRowHeight( iRowToUse); SetScrollPos32(SB_VERT, __max(0, scrollPos - yScroll)); rect.top = GetFixedRowHeight(); //ScrollWindow(0, yScroll, rect); //rect.bottom = rect.top + yScroll; InvalidateRect(rect); } break; case SB_PAGEDOWN: if (scrollPos < m_nVScrollMax) { rect.top = GetFixedRowHeight(); scrollPos = min(m_nVScrollMax, scrollPos + rect.Height()); SetScrollPos32(SB_VERT, scrollPos); rect.top = GetFixedRowHeight(); InvalidateRect(rect); } break; case SB_PAGEUP: if (scrollPos > 0) { rect.top = GetFixedRowHeight(); int offset = -rect.Height(); int pos = __max(0, scrollPos + offset); SetScrollPos32(SB_VERT, pos); rect.top = GetFixedRowHeight(); InvalidateRect(rect); } break; case SB_THUMBPOSITION: case SB_THUMBTRACK: { SetScrollPos32(SB_VERT, GetScrollPos32(SB_VERT, TRUE)); m_idTopLeftCell.row = -1; CCellID idNewTopLeft = GetTopleftNonFixedCell(); if (idNewTopLeft != idTopLeft) { rect.top = GetFixedRowHeight(); InvalidateRect(rect); } } break; case SB_TOP: if (scrollPos > 0) { SetScrollPos32(SB_VERT, 0); Invalidate(); } break; case SB_BOTTOM: if (scrollPos < m_nVScrollMax) { SetScrollPos32(SB_VERT, m_nVScrollMax); Invalidate(); } default: break; } } ///////////////////////////////////////////////////////////////////////////// // CGridCtrl implementation functions void CGridCtrl::OnDraw(CDC* pDC) { if (!m_bAllowDraw) return; CRect clipRect; if (pDC->GetClipBox(&clipRect) == ERROR) return; EraseBkgnd(pDC); // OnEraseBkgnd does nothing, so erase bkgnd here. // This necessary since we may be using a Memory DC. #ifdef _DEBUG LARGE_INTEGER iStartCount; QueryPerformanceCounter(&iStartCount); #endif CRect rect; int row, col; CGridCellBase* pCell; int nFixedRowHeight = GetFixedRowHeight(); int nFixedColWidth = GetFixedColumnWidth(); CCellID idTopLeft = GetTopleftNonFixedCell(); int minVisibleRow = idTopLeft.row, minVisibleCol = idTopLeft.col; CRect VisRect; CCellRange VisCellRange = GetVisibleNonFixedCellRange(VisRect); int maxVisibleRow = VisCellRange.GetMaxRow(), maxVisibleCol = VisCellRange.GetMaxCol(); if (GetVirtualMode()) SendCacheHintToParent(VisCellRange); // draw top-left cells 0..m_nFixedRows-1, 0..m_nFixedCols-1 rect.bottom = -1; for (row = 0; row < m_nFixedRows; row++) { if (GetRowHeight(row) <= 0) continue; rect.top = rect.bottom+1; rect.bottom = rect.top + GetRowHeight(row)-1; rect.right = -1; for (col = 0; col < m_nFixedCols; col++) { if (GetColumnWidth(col) <= 0) continue; rect.left = rect.right+1; rect.right = rect.left + GetColumnWidth(col)-1; pCell = GetCell(row, col); if (pCell) { pCell->SetCoords(row,col); pCell->Draw(pDC, row, col, rect, FALSE); } } } // draw fixed column cells: m_nFixedRows..n, 0..m_nFixedCols-1 rect.bottom = nFixedRowHeight-1; for (row = minVisibleRow; row <= maxVisibleRow; row++) { if (GetRowHeight(row) <= 0) continue; rect.top = rect.bottom+1; rect.bottom = rect.top + GetRowHeight(row)-1; // rect.bottom = bottom pixel of previous row if (rect.top > clipRect.bottom) break; // Gone past cliprect if (rect.bottom < clipRect.top) continue; // Reached cliprect yet? rect.right = -1; for (col = 0; col < m_nFixedCols; col++) { if (GetColumnWidth(col) <= 0) continue; rect.left = rect.right+1; rect.right = rect.left + GetColumnWidth(col)-1; if (rect.left > clipRect.right) break; // gone past cliprect if (rect.right < clipRect.left) continue; // Reached cliprect yet? pCell = GetCell(row, col); if (pCell) { pCell->SetCoords(row,col); pCell->Draw(pDC, row, col, rect, FALSE); } } } // draw fixed row cells 0..m_nFixedRows, m_nFixedCols..n rect.bottom = -1; for (row = 0; row < m_nFixedRows; row++) { if (GetRowHeight(row) <= 0) continue; rect.top = rect.bottom+1; rect.bottom = rect.top + GetRowHeight(row)-1; // rect.bottom = bottom pixel of previous row if (rect.top > clipRect.bottom) break; // Gone past cliprect if (rect.bottom < clipRect.top) continue; // Reached cliprect yet? rect.right = nFixedColWidth-1; for (col = minVisibleCol; col <= maxVisibleCol; col++) { if (GetColumnWidth(col) <= 0) continue; rect.left = rect.right+1; rect.right = rect.left + GetColumnWidth(col)-1; if (rect.left > clipRect.right) break; // gone past cliprect if (rect.right < clipRect.left) continue; // Reached cliprect yet? pCell = GetCell(row, col); if (pCell) { pCell->SetCoords(row,col); pCell->Draw(pDC, row, col, rect, FALSE); } } } // draw rest of non-fixed cells rect.bottom = nFixedRowHeight-1; for (row = minVisibleRow; row <= maxVisibleRow; row++) { if (GetRowHeight(row) <= 0) continue; rect.top = rect.bottom+1; rect.bottom = rect.top + GetRowHeight(row)-1; // rect.bottom = bottom pixel of previous row if (rect.top > clipRect.bottom) break; // Gone past cliprect if (rect.bottom < clipRect.top) continue; // Reached cliprect yet? rect.right = nFixedColWidth-1; for (col = minVisibleCol; col <= maxVisibleCol; col++) { if (GetColumnWidth(col) <= 0) continue; rect.left = rect.right+1; rect.right = rect.left + GetColumnWidth(col)-1; if (rect.left > clipRect.right) break; // gone past cliprect if (rect.right < clipRect.left) continue; // Reached cliprect yet? pCell = GetCell(row, col); // TRACE(_T("Cell %d,%d type: %s\n"), row, col, pCell->GetRuntimeClass()->m_lpszClassName); if (pCell) { pCell->SetCoords(row,col); pCell->Draw(pDC, row, col, rect, FALSE); } } } CPen pen; pen.CreatePen(PS_SOLID, 0, m_crGridLineColour); pDC->SelectObject(&pen); // draw vertical lines (drawn at ends of cells) if (m_nGridLines == GVL_BOTH || m_nGridLines == GVL_VERT) { int x = nFixedColWidth; for (col = minVisibleCol; col <= maxVisibleCol; col++) { if (GetColumnWidth(col) <= 0) continue; x += GetColumnWidth(col); pDC->MoveTo(x-1, nFixedRowHeight); pDC->LineTo(x-1, VisRect.bottom); } } // draw horizontal lines (drawn at bottom of each cell) if (m_nGridLines == GVL_BOTH || m_nGridLines == GVL_HORZ) { int y = nFixedRowHeight; for (row = minVisibleRow; row <= maxVisibleRow; row++) { if (GetRowHeight(row) <= 0) continue; y += GetRowHeight(row); pDC->MoveTo(nFixedColWidth, y-1); pDC->LineTo(VisRect.right, y-1); } } pDC->SelectStockObject(NULL_PEN); // Let parent know it can discard it's data if it needs to. if (GetVirtualMode()) SendCacheHintToParent(CCellRange(-1,-1,-1,-1)); #ifdef _DEBUG LARGE_INTEGER iEndCount; QueryPerformanceCounter(&iEndCount); TRACE1("Draw counter ticks: %d\n", iEndCount.LowPart-iStartCount.LowPart); #endif } //////////////////////////////////////////////////////////////////////////////////////// // CGridCtrl Cell selection stuff // Is a given cell designation valid (ie within the bounds of our number // of columns/rows)? BOOL CGridCtrl::IsValid(int nRow, int nCol) const { return (nRow >= 0 && nRow < m_nRows && nCol >= 0 && nCol < m_nCols); } BOOL CGridCtrl::IsValid(const CCellID& cell) const { return IsValid(cell.row, cell.col); } // Is a given cell range valid (ie within the bounds of our number // of columns/rows)? BOOL CGridCtrl::IsValid(const CCellRange& range) const { return (range.GetMinRow() >= 0 && range.GetMinCol() >= 0 && range.GetMaxRow() >= 0 && range.GetMaxCol() >= 0 && range.GetMaxRow() < m_nRows && range.GetMaxCol() < m_nCols && range.GetMinRow() <= range.GetMaxRow() && range.GetMinCol() <= range.GetMaxCol()); } // Enables/Disables redraw for certain operations like columns auto-sizing etc, // but not for user caused things such as selection changes. void CGridCtrl::SetRedraw(BOOL bAllowDraw, BOOL bResetScrollBars /* = FALSE */) { // TRACE(_T("%s: Setting redraw to %s\n"), // GetRuntimeClass()->m_lpszClassName, bAllowDraw? _T("TRUE") : _T("FALSE")); if (bAllowDraw && !m_bAllowDraw) { m_bAllowDraw = TRUE; Refresh(); } m_bAllowDraw = bAllowDraw; if (bResetScrollBars) ResetScrollBars(); } // Forces a redraw of a cell immediately (using a direct DC construction, // or the supplied dc) BOOL CGridCtrl::RedrawCell(const CCellID& cell, CDC* pDC /* = NULL */) { return RedrawCell(cell.row, cell.col, pDC); } BOOL CGridCtrl::RedrawCell(int nRow, int nCol, CDC* pDC /* = NULL */) { BOOL bResult = TRUE; BOOL bMustReleaseDC = FALSE; if (!m_bAllowDraw || !IsCellVisible(nRow, nCol)) return FALSE; CRect rect; if (!GetCellRect(nRow, nCol, rect)) return FALSE; if (!pDC) { pDC = GetDC(); if (pDC) bMustReleaseDC = TRUE; } if (pDC) { // Redraw cells directly if (nRow < m_nFixedRows || nCol < m_nFixedCols) { CGridCellBase* pCell = GetCell(nRow, nCol); if (pCell) bResult = pCell->Draw(pDC, nRow, nCol, rect, TRUE); } else { CGridCellBase* pCell = GetCell(nRow, nCol); if (pCell) bResult = pCell->Draw(pDC, nRow, nCol, rect, TRUE); // Since we have erased the background, we will need to redraw the gridlines CPen pen; pen.CreatePen(PS_SOLID, 0, m_crGridLineColour); CPen* pOldPen = (CPen*) pDC->SelectObject(&pen); if (m_nGridLines == GVL_BOTH || m_nGridLines == GVL_HORZ) { pDC->MoveTo(rect.left, rect.bottom); pDC->LineTo(rect.right + 1, rect.bottom); } if (m_nGridLines == GVL_BOTH || m_nGridLines == GVL_VERT) { pDC->MoveTo(rect.right, rect.top); pDC->LineTo(rect.right, rect.bottom + 1); } pDC->SelectObject(pOldPen); } } else InvalidateRect(rect, TRUE); // Could not get a DC - invalidate it anyway // and hope that OnPaint manages to get one if (bMustReleaseDC) ReleaseDC(pDC); return bResult; } // redraw a complete row BOOL CGridCtrl::RedrawRow(int row) { BOOL bResult = TRUE; CDC* pDC = GetDC(); for (int col = 0; col < GetColumnCount(); col++) bResult = RedrawCell(row, col, pDC) && bResult; if (pDC) ReleaseDC(pDC); return bResult; } // redraw a complete column BOOL CGridCtrl::RedrawColumn(int col) { BOOL bResult = TRUE; CDC* pDC = GetDC(); for (int row = 0; row < GetRowCount(); row++) bResult = RedrawCell(row, col, pDC) && bResult; if (pDC) ReleaseDC(pDC); return bResult; } // Sets the currently selected cell, returning the previous current cell CCellID CGridCtrl::SetFocusCell(int nRow, int nCol) { return SetFocusCell(CCellID(nRow, nCol)); } CCellID CGridCtrl::SetFocusCell(CCellID cell) { if (cell == m_idCurrentCell) return m_idCurrentCell; CCellID idPrev = m_idCurrentCell; // EFW - Bug Fix - Force focus to be in a non-fixed cell if (cell.row != -1 && cell.row < GetFixedRowCount()) cell.row = GetFixedRowCount(); if (cell.col != -1 && cell.col < GetFixedColumnCount()) cell.col = GetFixedColumnCount(); m_idCurrentCell = cell; if (IsValid(idPrev)) { SetItemState(idPrev.row, idPrev.col, GetItemState(idPrev.row, idPrev.col) & ~GVIS_FOCUSED); RedrawCell(idPrev); // comment to reduce flicker if (GetTrackFocusCell() && idPrev.col != m_idCurrentCell.col) for (int row = 0; row < m_nFixedRows; row++) RedrawCell(row, idPrev.col); if (GetTrackFocusCell() && idPrev.row != m_idCurrentCell.row) for (int col = 0; col < m_nFixedCols; col++) RedrawCell(idPrev.row, col); } if (IsValid(m_idCurrentCell)) { SetItemState(m_idCurrentCell.row, m_idCurrentCell.col, GetItemState(m_idCurrentCell.row, m_idCurrentCell.col) | GVIS_FOCUSED); RedrawCell(m_idCurrentCell); // comment to reduce flicker if (GetTrackFocusCell() && idPrev.col != m_idCurrentCell.col) for (int row = 0; row < m_nFixedRows; row++) RedrawCell(row, m_idCurrentCell.col); if (GetTrackFocusCell() && idPrev.row != m_idCurrentCell.row) for (int col = 0; col < m_nFixedCols; col++) RedrawCell(m_idCurrentCell.row, col); // EFW - New addition. If in list mode, make sure the selected // row highlight follows the cursor. // Removed by C Maunder 27 May //if (m_bListMode) //{ // m_PrevSelectedCellMap.RemoveAll(); // m_MouseMode = MOUSE_SELECT_ROW; // OnSelecting(m_idCurrentCell); // Leave this off so that you can still drag the highlight around // without selecting rows. // m_MouseMode = MOUSE_NOTHING; //} } return idPrev; } // Sets the range of currently selected cells void CGridCtrl::SetSelectedRange(const CCellRange& Range, BOOL bForceRepaint /* = FALSE */, BOOL bSelectCells/*=TRUE*/) { SetSelectedRange(Range.GetMinRow(), Range.GetMinCol(), Range.GetMaxRow(), Range.GetMaxCol(), bForceRepaint, bSelectCells); } void CGridCtrl::SetSelectedRange(int nMinRow, int nMinCol, int nMaxRow, int nMaxCol, BOOL bForceRepaint /* = FALSE */, BOOL bSelectCells/*=TRUE*/) { if (!m_bEnableSelection) return; CWaitCursor wait; // Thomas Haase CDC* pDC = NULL; if (bForceRepaint) pDC = GetDC(); // Only redraw visible cells CCellRange VisCellRange, FixedVisCellRange; if (IsWindow(GetSafeHwnd())) { VisCellRange = GetVisibleNonFixedCellRange(); FixedVisCellRange = GetVisibleFixedCellRange(); } // EFW - Bug fix - Don't allow selection of fixed rows int Left= (m_AllowSelectRowInFixedCol ? 0 : GetFixedColumnCount()); if(nMinRow >= 0 && nMinRow < GetFixedRowCount()) nMinRow = GetFixedRowCount(); if(nMaxRow >= 0 && nMaxRow < GetFixedRowCount()) nMaxRow = GetFixedRowCount(); if(nMinCol >= 0 && nMinCol < Left) nMinCol = GetFixedColumnCount(); if(nMaxCol >= 0 && nMaxCol < Left) nMaxCol = GetFixedColumnCount(); // If we are selecting cells, then first clear out the list of currently selected cells, then if (bSelectCells) { POSITION pos; // Unselect all previously selected cells for (pos = m_SelectedCellMap.GetStartPosition(); pos != NULL; ) { DWORD key; CCellID cell; m_SelectedCellMap.GetNextAssoc(pos, key, (CCellID&)cell); // Reset the selection flag on the cell if (IsValid(cell)) { // This will remove the cell from the m_SelectedCellMap map SetItemState(cell.row, cell.col, GetItemState(cell.row, cell.col) & ~GVIS_SELECTED); // If this is to be reselected, continue on past the redraw if (nMinRow <= cell.row && cell.row <= nMaxRow && nMinCol <= cell.col && cell.col <= nMaxCol) continue; if ( (VisCellRange.IsValid() && VisCellRange.InRange( cell )) || FixedVisCellRange.InRange( cell ) ) { if (bForceRepaint && pDC) // Redraw NOW RedrawCell(cell.row, cell.col, pDC); else InvalidateCellRect(cell); // Redraw at leisure } } else { m_SelectedCellMap.RemoveKey( key); // if it's not valid, get rid of it! } } // if we are selecting cells, and there are previous selected cells to be retained // (eg Ctrl is being held down) then copy them to the newly created list, and mark // all these cells as selected // Note that if we are list mode, single row selection, then we won't be adding // the previous cells. Only the current row of cells will be added (see below) if (!GetSingleRowSelection() && nMinRow >= 0 && nMinCol >= 0 && nMaxRow >= 0 && nMaxCol >= 0) { for (pos = m_PrevSelectedCellMap.GetStartPosition(); pos != NULL; /* nothing */) { DWORD key; CCellID cell; m_PrevSelectedCellMap.GetNextAssoc(pos, key, (CCellID&)cell); if (!IsValid(cell)) continue; int nState = GetItemState(cell.row, cell.col); // Set state as Selected. This will add the cell to m_SelectedCellMap SetItemState(cell.row, cell.col, nState | GVIS_SELECTED); if (( VisCellRange.IsValid() && VisCellRange.InRange( cell )) || FixedVisCellRange.InRange( cell ) ) { // Redraw (immediately or at leisure) if (bForceRepaint && pDC) RedrawCell(cell.row, cell.col, pDC); else InvalidateCellRect(cell); } } } } // Now select/deselect all cells in the cell range specified. If selecting, and the cell // has already been marked as selected (above) then ignore it. If we are deselecting and // the cell isn't selected, then ignore if (nMinRow >= 0 && nMinCol >= 0 && nMaxRow >= 0 && nMaxCol >= 0 && nMaxRow < m_nRows && nMaxCol < m_nCols && nMinRow <= nMaxRow && nMinCol <= nMaxCol) { for (int row = nMinRow; row <= nMaxRow; row++) for (int col = nMinCol; col <= nMaxCol; col++) { BOOL bCellSelected = IsCellSelected(row, col); if (bSelectCells == bCellSelected) continue; // Already selected or deselected - ignore // Set the selected state. This will add/remove the cell to m_SelectedCellMap if (bSelectCells) SetItemState(row, col, GetItemState(row, col) | GVIS_SELECTED); else SetItemState(row, col, GetItemState(row, col) & ~GVIS_SELECTED); if ( (VisCellRange.IsValid() && VisCellRange.InRange(row, col)) || FixedVisCellRange.InRange(row, col) ) { // Redraw (immediately or at leisure) if (bForceRepaint && pDC) RedrawCell(row, col, pDC); else InvalidateCellRect(row, col); } } } // TRACE(_T("%d cells selected.\n"), m_SelectedCellMap.GetCount()); if (pDC != NULL) ReleaseDC(pDC); } // selects all cells void CGridCtrl::SelectAllCells() { if (!m_bEnableSelection) return; SetSelectedRange(m_nFixedRows, m_nFixedCols, GetRowCount()-1, GetColumnCount()-1); } // selects columns void CGridCtrl::SelectColumns(CCellID currentCell, BOOL bForceRedraw /*=FALSE*/, BOOL bSelectCells /*=TRUE*/) { if (!m_bEnableSelection) return; //if (currentCell.col == m_idCurrentCell.col) return; if (currentCell.col < m_nFixedCols) return; if (!IsValid(currentCell)) return; if (GetSingleColSelection()) SetSelectedRange(GetFixedRowCount(), currentCell.col, GetRowCount()-1, currentCell.col, bForceRedraw, bSelectCells); else SetSelectedRange(GetFixedRowCount(), min(m_SelectionStartCell.col, currentCell.col), GetRowCount()-1, max(m_SelectionStartCell.col, currentCell.col), bForceRedraw, bSelectCells); } // selects rows void CGridCtrl::SelectRows(CCellID currentCell, BOOL bForceRedraw /*=FALSE*/, BOOL bSelectCells /*=TRUE*/) { if (!m_bEnableSelection) return; //if (currentCell.row; == m_idCurrentCell.row) return; if (currentCell.row < m_nFixedRows) return; if (!IsValid(currentCell)) return; int Left = ( m_AllowSelectRowInFixedCol ? 0 : GetFixedColumnCount()); if (GetSingleRowSelection()) SetSelectedRange(currentCell.row, Left , currentCell.row, GetColumnCount()-1, bForceRedraw, bSelectCells); else SetSelectedRange(min(m_SelectionStartCell.row, currentCell.row), Left, __max(m_SelectionStartCell.row, currentCell.row), GetColumnCount()-1, bForceRedraw, bSelectCells); } // selects cells void CGridCtrl::SelectCells(CCellID currentCell, BOOL bForceRedraw /*=FALSE*/, BOOL bSelectCells /*=TRUE*/) { if (!m_bEnableSelection) return; int row = currentCell.row; int col = currentCell.col; if (row < m_nFixedRows || col < m_nFixedCols) return; if (!IsValid(currentCell)) return; // Prevent unnecessary redraws //if (currentCell == m_LeftClickDownCell) return; //else if (currentCell == m_idCurrentCell) return; SetSelectedRange(min(m_SelectionStartCell.row, row), min(m_SelectionStartCell.col, col), __max(m_SelectionStartCell.row, row), __max(m_SelectionStartCell.col, col), bForceRedraw, bSelectCells); } // Called when mouse/keyboard selection is a-happening. void CGridCtrl::OnSelecting(const CCellID& currentCell) { if (!m_bEnableSelection) return; switch (m_MouseMode) { case MOUSE_SELECT_ALL: SelectAllCells(); break; case MOUSE_SELECT_COL: SelectColumns(currentCell, FALSE); break; case MOUSE_SELECT_ROW: SelectRows(currentCell, FALSE); break; case MOUSE_SELECT_CELLS: SelectCells(currentCell, FALSE); break; } // EFW - Bug fix [REMOVED CJM: this will cause infinite loop in list mode] // SetFocusCell(max(currentCell.row, m_nFixedRows), max(currentCell.col, m_nFixedCols)); } void CGridCtrl::ValidateAndModifyCellContents(int nRow, int nCol, LPCTSTR strText) { if (!IsCellEditable(nRow, nCol)) return; if (SendMessageToParent(nRow, nCol, GVN_BEGINLABELEDIT) >= 0) { CString strCurrentText = GetItemText(nRow, nCol); if (strCurrentText != strText) { SetItemText(nRow, nCol, strText); if (ValidateEdit(nRow, nCol, strText) && SendMessageToParent(nRow, nCol, GVN_ENDLABELEDIT) >= 0) { SetModified(TRUE, nRow, nCol); RedrawCell(nRow, nCol); } else { SetItemText(nRow, nCol, strCurrentText); } } } } void CGridCtrl::ClearCells(CCellRange Selection) { for (int row = Selection.GetMinRow(); row <= Selection.GetMaxRow(); row++) { for (int col = Selection.GetMinCol(); col <= Selection.GetMaxCol(); col++) { // don't clear hidden cells if ( m_arRowHeights[row] > 0 && m_arColWidths[col] > 0 ) { ValidateAndModifyCellContents(row, col, _T("")); } } } Refresh(); } #ifndef GRIDCONTROL_NO_CLIPBOARD //////////////////////////////////////////////////////////////////////////////////////// // Clipboard functions // Deletes the contents from the selected cells void CGridCtrl::CutSelectedText() { if (!IsEditable()) return; for (POSITION pos = m_SelectedCellMap.GetStartPosition(); pos != NULL; ) { DWORD key; CCellID cell; m_SelectedCellMap.GetNextAssoc(pos, key, (CCellID&)cell); ValidateAndModifyCellContents(cell.row, cell.col, _T("")); } } // Copies text from the selected cells to the clipboard COleDataSource* CGridCtrl::CopyTextFromGrid() { USES_CONVERSION; CCellRange Selection = GetSelectedCellRange(); if (!IsValid(Selection)) return NULL; if (GetVirtualMode()) SendCacheHintToParent(Selection); // Write to shared file (REMEBER: CF_TEXT is ANSI, not UNICODE, so we need to convert) CSharedFile sf(GMEM_MOVEABLE | GMEM_DDESHARE | GMEM_ZEROINIT); // Get a tab delimited string to copy to cache CString str; CGridCellBase *pCell; for (int row = Selection.GetMinRow(); row <= Selection.GetMaxRow(); row++) { // don't copy hidden cells if( m_arRowHeights[row] <= 0 ) continue; str.Empty(); for (int col = Selection.GetMinCol(); col <= Selection.GetMaxCol(); col++) { // don't copy hidden cells if( m_arColWidths[col] <= 0 ) continue; pCell = GetCell(row, col); if (pCell &&(pCell->GetState() & GVIS_SELECTED)) { // if (!pCell->GetText()) // str += _T(" "); // else str += pCell->GetText(); } if (col != Selection.GetMaxCol()) str += _T("\t"); } if (row != Selection.GetMaxRow()) str += _T("\r\n"); sf.Write(T2A(str.GetBuffer(1)), str.GetLength()); str.ReleaseBuffer(); } char c = '\0'; sf.Write(&c, 1); if (GetVirtualMode()) SendCacheHintToParent(CCellRange(-1,-1,-1,-1)); DWORD dwLen = (DWORD) sf.GetLength(); HGLOBAL hMem = sf.Detach(); if (!hMem) return NULL; hMem = ::GlobalReAlloc(hMem, dwLen, GMEM_MOVEABLE | GMEM_DDESHARE | GMEM_ZEROINIT); if (!hMem) return NULL; // Cache data COleDataSource* pSource = new COleDataSource(); pSource->CacheGlobalData(CF_TEXT, hMem); return pSource; } // Pastes text from the clipboard to the selected cells BOOL CGridCtrl::PasteTextToGrid(CCellID cell, COleDataObject* pDataObject, BOOL bSelectPastedCells /*=TRUE*/) { if (!IsValid(cell) || !IsCellEditable(cell) || !pDataObject->IsDataAvailable(CF_TEXT)) return FALSE; // Get the text from the COleDataObject HGLOBAL hmem = pDataObject->GetGlobalData(CF_TEXT); CMemFile sf((BYTE*) ::GlobalLock(hmem), (UINT)::GlobalSize(hmem)); // CF_TEXT is ANSI text, so we need to allocate a char* buffer // to hold this. LPSTR szBuffer = new char[::GlobalSize(hmem)]; // FIX: Use LPSTR char here if (!szBuffer) return FALSE; sf.Read(szBuffer, (UINT)::GlobalSize(hmem)); ::GlobalUnlock(hmem); // Now store in generic TCHAR form so we no longer have to deal with // ANSI/UNICODE problems CString strText(szBuffer); delete szBuffer; // Parse text data and set in cells... strText.LockBuffer(); CString strLine = strText; int nLine = 0; // Find the end of the first line CCellRange PasteRange(cell.row, cell.col,-1,-1); int nIndex; do { int nColumn = 0; nIndex = strLine.Find(_T("\n")); // Store the remaining chars after the newline CString strNext = (nIndex < 0)? _T("") : strLine.Mid(nIndex + 1); // Remove all chars after the newline if (nIndex >= 0) strLine = strLine.Left(nIndex); int nLineIndex = strLine.FindOneOf(_T("\t,")); CString strCellText = (nLineIndex >= 0)? strLine.Left(nLineIndex) : strLine; // skip hidden rows int iRowVis = cell.row + nLine; while( iRowVis < GetRowCount()) { if( GetRowHeight( iRowVis) > 0) break; nLine++; iRowVis++; } while (!strLine.IsEmpty()) { // skip hidden columns int iColVis = cell.col + nColumn; while( iColVis < GetColumnCount()) { if( GetColumnWidth( iColVis) > 0) break; nColumn++; iColVis++; } CCellID TargetCell(iRowVis, iColVis); if (IsValid(TargetCell)) { strCellText.TrimLeft(); strCellText.TrimRight(); ValidateAndModifyCellContents(TargetCell.row, TargetCell.col, strCellText); // Make sure cell is not selected to avoid data loss SetItemState(TargetCell.row, TargetCell.col, GetItemState(TargetCell.row, TargetCell.col) & ~GVIS_SELECTED); if (iRowVis > PasteRange.GetMaxRow()) PasteRange.SetMaxRow(iRowVis); if (iColVis > PasteRange.GetMaxCol()) PasteRange.SetMaxCol(iColVis); } strLine = (nLineIndex >= 0)? strLine.Mid(nLineIndex + 1) : _T(""); nLineIndex = strLine.FindOneOf(_T("\t,")); strCellText = (nLineIndex >= 0)? strLine.Left(nLineIndex) : strLine; nColumn++; } strLine = strNext; nLine++; } while (nIndex >= 0); strText.UnlockBuffer(); if (bSelectPastedCells) SetSelectedRange(PasteRange, TRUE); else { ResetSelectedRange(); Refresh(); } return TRUE; } #endif #ifndef GRIDCONTROL_NO_DRAGDROP // Start drag n drop void CGridCtrl::OnBeginDrag() { COleDataSource* pSource = NULL; if (!m_bAllowDragAndDrop && m_CurCol==-1) return; if (m_CurCol>=0) pSource = new COleDataSource(); if (!pSource && m_bAllowDragAndDrop) pSource = CopyTextFromGrid(); if (pSource) { SendMessageToParent(GetSelectedCellRange().GetTopLeft().row, GetSelectedCellRange().GetTopLeft().col, GVN_BEGINDRAG); m_MouseMode = MOUSE_DRAGGING; m_bLMouseButtonDown = FALSE; DROPEFFECT dropEffect = pSource->DoDragDrop(DROPEFFECT_COPY | DROPEFFECT_MOVE); if (dropEffect & DROPEFFECT_MOVE) CutSelectedText(); if (pSource) delete pSource; // Did not pass source to clipboard, so must delete } } // Handle drag over grid DROPEFFECT CGridCtrl::OnDragOver(COleDataObject* pDataObject, DWORD dwKeyState, CPoint point) { // Find which cell we are over and drop-highlight it CCellID cell = GetCellFromPt(point, FALSE); bool Valid; // Any text data available for us? if(m_CurCol==-1) { if(m_bDragRowMode) { Valid = cell.col>=GetFixedColumnCount() && cell.row>=GetFixedRowCount(); } else { if (!m_bAllowDragAndDrop || !IsEditable() || !pDataObject->IsDataAvailable(CF_TEXT)) return DROPEFFECT_NONE; Valid = IsValid(cell)!=0; } } else { Valid = cell.col>=GetFixedColumnCount() && cell.row<GetFixedRowCount() ; } // If not valid, set the previously drop-highlighted cell as no longer drop-highlighted if (!Valid) { OnDragLeave(); m_LastDragOverCell = CCellID(-1,-1); return DROPEFFECT_NONE; } if(m_CurCol==-1) { if (!m_bDragRowMode && !IsCellEditable(cell)) return DROPEFFECT_NONE; } // Have we moved over a different cell than last time? if (cell != m_LastDragOverCell) { // Set the previously drop-highlighted cell as no longer drop-highlighted if (IsValid(m_LastDragOverCell)) { UINT nState = GetItemState(m_LastDragOverCell.row, m_LastDragOverCell.col); SetItemState(m_LastDragOverCell.row, m_LastDragOverCell.col, nState & ~GVIS_DROPHILITED); RedrawCell(m_LastDragOverCell); } m_LastDragOverCell = cell; // Set the new cell as drop-highlighted if (IsValid(m_LastDragOverCell)) { UINT nState = GetItemState(m_LastDragOverCell.row, m_LastDragOverCell.col); SetItemState(m_LastDragOverCell.row, m_LastDragOverCell.col, nState | GVIS_DROPHILITED); RedrawCell(m_LastDragOverCell); } } // Return an appropraite value of DROPEFFECT so mouse cursor is set properly if (dwKeyState & MK_CONTROL) return DROPEFFECT_COPY; else return DROPEFFECT_MOVE; } // Something has just been dragged onto the grid DROPEFFECT CGridCtrl::OnDragEnter(COleDataObject* pDataObject, DWORD dwKeyState, CPoint point) { // Any text data available for us? m_LastDragOverCell = GetCellFromPt(point, m_CurCol>=0); bool Valid; if(m_CurCol==-1) { if (!m_bAllowDragAndDrop || !pDataObject->IsDataAvailable(CF_TEXT)) return DROPEFFECT_NONE; // Find which cell we are over and drop-highlight it if (!IsValid(m_LastDragOverCell)) return DROPEFFECT_NONE; if (!IsCellEditable(m_LastDragOverCell)) return DROPEFFECT_NONE; Valid = IsValid(m_LastDragOverCell)!=0; } else { Valid = m_LastDragOverCell.row>=0 && m_LastDragOverCell.row<GetFixedRowCount() && m_LastDragOverCell.col>=GetFixedColumnCount(); } if (Valid) { UINT nState = GetItemState(m_LastDragOverCell.row, m_LastDragOverCell.col); SetItemState(m_LastDragOverCell.row, m_LastDragOverCell.col, nState | GVIS_DROPHILITED); RedrawCell(m_LastDragOverCell); } // Return an appropraite value of DROPEFFECT so mouse cursor is set properly if (dwKeyState & MK_CONTROL) return DROPEFFECT_COPY; else return DROPEFFECT_MOVE; } // Something has just been dragged away from the grid void CGridCtrl::OnDragLeave() { // Set the previously drop-highlighted cell as no longer drop-highlighted if (IsValid(m_LastDragOverCell)) { UINT nState = GetItemState(m_LastDragOverCell.row, m_LastDragOverCell.col); SetItemState(m_LastDragOverCell.row, m_LastDragOverCell.col, nState & ~GVIS_DROPHILITED); RedrawCell(m_LastDragOverCell); } } // Something has just been dropped onto the grid BOOL CGridCtrl::OnDrop(COleDataObject* pDataObject, DROPEFFECT /*dropEffect*/, CPoint /* point */) { m_MouseMode = MOUSE_NOTHING; if(m_CurCol ==-1) { if (!m_bAllowDragAndDrop || (!IsCellEditable(m_LastDragOverCell) && !m_bDragRowMode)) return FALSE; } OnDragLeave(); if (m_CurCol>=0) { if(m_LastDragOverCell.col == m_CurCol || m_LastDragOverCell.row >= GetFixedRowCount()) return FALSE; else { int New = m_arColOrder[m_CurCol]; m_arColOrder.erase(m_arColOrder.begin()+m_CurCol); m_arColOrder.insert(m_arColOrder.begin()+m_LastDragOverCell.col, New); m_CurCol=-1; Invalidate(); return TRUE; } } else { if(m_bDragRowMode) { Reorder(m_CurRow,m_LastDragOverCell.row); Invalidate(); return TRUE; } else return PasteTextToGrid(m_LastDragOverCell, pDataObject, FALSE); } } #endif #ifndef GRIDCONTROL_NO_CLIPBOARD void CGridCtrl::OnEditCut() { if (!IsEditable()) return; COleDataSource* pSource = CopyTextFromGrid(); if (!pSource) return; pSource->SetClipboard(); CutSelectedText(); } void CGridCtrl::OnEditCopy() { COleDataSource* pSource = CopyTextFromGrid(); if (!pSource) return; pSource->SetClipboard(); } void CGridCtrl::OnEditPaste() { if (!IsEditable()) return; CCellRange cellRange = GetSelectedCellRange(); // Get the top-left selected cell, or the Focus cell, or the topleft (non-fixed) cell CCellID cell; if (cellRange.IsValid()) { cell.row = cellRange.GetMinRow(); cell.col = cellRange.GetMinCol(); } else { cell = GetFocusCell(); if (!IsValid(cell)) cell = GetTopleftNonFixedCell(); if (!IsValid(cell)) return; } // If a cell is being edited, then call it's edit window paste function. if ( IsItemEditing(cell.row, cell.col) ) { CGridCellBase* pCell = GetCell(cell.row, cell.col); ASSERT(pCell); if (!pCell) return; CWnd* pEditWnd = pCell->GetEditWnd(); if ( pEditWnd && pEditWnd->IsKindOf(RUNTIME_CLASS(CEdit)) ) { ((CEdit*)pEditWnd)->Paste(); return; } } // Attach a COleDataObject to the clipboard and paste the data to the grid COleDataObject obj; if (obj.AttachClipboard()) PasteTextToGrid(cell, &obj); } #endif void CGridCtrl::OnEditSelectAll() { SendMessageToParent(m_LeftClickDownCell.row, m_LeftClickDownCell.col, GVN_SELCHANGING); SelectAllCells(); SendMessageToParent(m_idCurrentCell.row, m_idCurrentCell.col, GVN_SELCHANGED); } #ifndef GRIDCONTROL_NO_CLIPBOARD void CGridCtrl::OnUpdateEditCopy(CCmdUI* pCmdUI) { pCmdUI->Enable(GetSelectedCount() > 0); // - Thomas Haase //CCellRange Selection = GetSelectedCellRange(); //pCmdUI->Enable(Selection.Count() && IsValid(Selection)); } void CGridCtrl::OnUpdateEditCut(CCmdUI* pCmdUI) { pCmdUI->Enable(IsEditable() && GetSelectedCount() > 0); // - Thomas Haase //CCellRange Selection = GetSelectedCellRange(); //pCmdUI->Enable(IsEditable() && Selection.Count() && IsValid(Selection)); } void CGridCtrl::OnUpdateEditPaste(CCmdUI* pCmdUI) { CCellID cell = GetFocusCell(); BOOL bCanPaste = IsValid(cell) && IsCellEditable(cell) && ::IsClipboardFormatAvailable(CF_TEXT); pCmdUI->Enable(bCanPaste); } #endif void CGridCtrl::OnUpdateEditSelectAll(CCmdUI* pCmdUI) { pCmdUI->Enable(m_bEnableSelection); } //////////////////////////////////////////////////////////////////////////////////////// // hittest-like functions // TRUE if the mouse is over a row resize area BOOL CGridCtrl::MouseOverRowResizeArea(CPoint& point) { if (point.x >= GetFixedColumnWidth()) return FALSE; CCellID idCurrentCell = GetCellFromPt(point); CPoint start; if (!GetCellOrigin(idCurrentCell, &start)) return FALSE; int endy = start.y + GetRowHeight(idCurrentCell.row); if ((point.y - start.y < m_nResizeCaptureRange && idCurrentCell.row != 0) || endy - point.y < m_nResizeCaptureRange) { return TRUE; } else return FALSE; } // TRUE if the mouse is over a column resize area. point is in Client coords BOOL CGridCtrl::MouseOverColumnResizeArea(CPoint& point) { if (point.y >= GetFixedRowHeight()) return FALSE; CCellID idCurrentCell = GetCellFromPt(point); CPoint start; if (!GetCellOrigin(idCurrentCell, &start)) return FALSE; int endx = start.x + GetColumnWidth(idCurrentCell.col); if ((point.x - start.x < m_nResizeCaptureRange && idCurrentCell.col != 0) || endx - point.x < m_nResizeCaptureRange) { return TRUE; } else return FALSE; } // Get cell from point. // point - client coordinates // bAllowFixedCellCheck - if TRUE then fixed cells are checked CCellID CGridCtrl::GetCellFromPt(CPoint point, BOOL bAllowFixedCellCheck /*=TRUE*/) { CCellID cellID; // return value CCellID idTopLeft = GetTopleftNonFixedCell(); if (!bAllowFixedCellCheck && !IsValid(idTopLeft)) return cellID; // calculate column index int fixedColWidth = GetFixedColumnWidth(); if (point.x < 0 || (!bAllowFixedCellCheck && point.x < fixedColWidth)) // not in window cellID.col = -1; else if (point.x < fixedColWidth) // in fixed col { int xpos = 0; int col = 0; while (col < m_nFixedCols) { xpos += GetColumnWidth(col); if (xpos > point.x) break; col++; } cellID.col = col; } else // in non-fixed col { int xpos = fixedColWidth; int col = idTopLeft.col; //m_nFixedCols; while ( col < GetColumnCount()) { xpos += GetColumnWidth(col); if (xpos > point.x) break; col++; } if (col >= GetColumnCount()) cellID.col = -1; else cellID.col = col; } // calculate row index int fixedRowHeight = GetFixedRowHeight(); if (point.y < 0 || (!bAllowFixedCellCheck && point.y < fixedRowHeight)) // not in window cellID.row = -1; else if (point.y < fixedRowHeight) // in fixed col { int ypos = 0; int row = 0; while (row < m_nFixedRows) { ypos += GetRowHeight(row); if (ypos > point.y) break; row++; } cellID.row = row; } else { int ypos = fixedRowHeight; int row = idTopLeft.row; //m_nFixedRows; while ( row < GetRowCount() ) { ypos += GetRowHeight(row); if (ypos > point.y) break; row++; } if (row >= GetRowCount()) cellID.row = -1; else cellID.row = row; } return cellID; } //////////////////////////////////////////////////////////////////////////////// // CGridCtrl cellrange functions // Gets the first non-fixed cell ID CCellID CGridCtrl::GetTopleftNonFixedCell(BOOL bForceRecalculation /*=FALSE*/) { // Used cached value if possible if (m_idTopLeftCell.IsValid() && !bForceRecalculation) return m_idTopLeftCell; int nVertScroll = GetScrollPos(SB_VERT), nHorzScroll = GetScrollPos(SB_HORZ); m_idTopLeftCell.col = m_nFixedCols; int nRight = 0; while (nRight < nHorzScroll && m_idTopLeftCell.col < (GetColumnCount()-1)) nRight += GetColumnWidth(m_idTopLeftCell.col++); m_idTopLeftCell.row = m_nFixedRows; int nTop = 0; while (nTop < nVertScroll && m_idTopLeftCell.row < (GetRowCount()-1)) nTop += GetRowHeight(m_idTopLeftCell.row++); //TRACE2("TopLeft cell is row %d, col %d\n",m_idTopLeftCell.row, m_idTopLeftCell.col); return m_idTopLeftCell; } // This gets even partially visible cells CCellRange CGridCtrl::GetVisibleNonFixedCellRange(LPRECT pRect /*=NULL*/, BOOL bForceRecalculation /*=FALSE*/) { int i; CRect rect; GetClientRect(rect); CCellID idTopLeft = GetTopleftNonFixedCell(bForceRecalculation); // calc bottom int bottom = GetFixedRowHeight(); for (i = idTopLeft.row; i < GetRowCount(); i++) { bottom += GetRowHeight(i); if (bottom >= rect.bottom) { bottom = rect.bottom; break; } } int maxVisibleRow = min(i, GetRowCount() - 1); // calc right int right = GetFixedColumnWidth(); for (i = idTopLeft.col; i < GetColumnCount(); i++) { right += GetColumnWidth(i); if (right >= rect.right) { right = rect.right; break; } } int maxVisibleCol = min(i, GetColumnCount() - 1); if (pRect) { pRect->left = pRect->top = 0; pRect->right = right; pRect->bottom = bottom; } return CCellRange(idTopLeft.row, idTopLeft.col, maxVisibleRow, maxVisibleCol); } CCellRange CGridCtrl::GetVisibleFixedCellRange(LPRECT pRect /*=NULL*/, BOOL bForceRecalculation /*=FALSE*/) { int i; CRect rect; GetClientRect(rect); CCellID idTopLeft = GetTopleftNonFixedCell(bForceRecalculation); // calc bottom int bottom = GetFixedRowHeight(); for (i = idTopLeft.row; i < GetRowCount(); i++) { bottom += GetRowHeight(i); if (bottom >= rect.bottom) { bottom = rect.bottom; break; } } int maxVisibleRow = min(i, GetRowCount() - 1); // calc right int right = 0; for (i = 0; i < GetFixedColumnCount(); i++) { right += GetColumnWidth(i); if (right >= rect.right) { right = rect.right; break; } } int maxVisibleCol = min(i, GetColumnCount() - 1); if (pRect) { pRect->left = pRect->top = 0; pRect->right = right; pRect->bottom = bottom; } return CCellRange(idTopLeft.row, 0, maxVisibleRow, maxVisibleCol); } // used by ResetScrollBars() - This gets only fully visible cells CCellRange CGridCtrl::GetUnobstructedNonFixedCellRange(BOOL bForceRecalculation /*=FALSE*/) { CRect rect; GetClientRect(rect); CCellID idTopLeft = GetTopleftNonFixedCell(bForceRecalculation); // calc bottom int i; int bottom = GetFixedRowHeight(); for (i = idTopLeft.row; i < GetRowCount(); i++) { bottom += GetRowHeight(i); if (bottom >= rect.bottom) break; } int maxVisibleRow = min(i, GetRowCount() - 1); if (maxVisibleRow > 0 && bottom > rect.bottom) maxVisibleRow--; // calc right int right = GetFixedColumnWidth(); for (i = idTopLeft.col; i < GetColumnCount(); i++) { right += GetColumnWidth(i); if (right >= rect.right) break; } int maxVisibleCol = min(i, GetColumnCount() - 1); if (maxVisibleCol > 0 && right > rect.right) maxVisibleCol--; return CCellRange(idTopLeft.row, idTopLeft.col, maxVisibleRow, maxVisibleCol); } // Returns the minimum bounding range of the current selection // If no selection, then the returned CCellRange will be invalid CCellRange CGridCtrl::GetSelectedCellRange() const { CCellRange Selection(GetRowCount(), GetColumnCount(), -1,-1); for (POSITION pos = m_SelectedCellMap.GetStartPosition(); pos != NULL; ) { DWORD key; CCellID cell; m_SelectedCellMap.GetNextAssoc(pos, key, (CCellID&)cell); Selection.SetMinRow( min(Selection.GetMinRow(), cell.row) ); Selection.SetMinCol( min(Selection.GetMinCol(), cell.col) ); Selection.SetMaxRow( __max(Selection.GetMaxRow(), cell.row) ); Selection.SetMaxCol( __max(Selection.GetMaxCol(), cell.col) ); } return Selection; } // Returns ALL the cells in the grid CCellRange CGridCtrl::GetCellRange() const { return CCellRange(0, 0, GetRowCount() - 1, GetColumnCount() - 1); } // Resets the selected cell range to the empty set. void CGridCtrl::ResetSelectedRange() { m_PrevSelectedCellMap.RemoveAll(); SetSelectedRange(-1,-1,-1,-1); SetFocusCell(-1,-1); } // Get/Set scroll position using 32 bit functions int CGridCtrl::GetScrollPos32(int nBar, BOOL bGetTrackPos /* = FALSE */) { SCROLLINFO si; si.cbSize = sizeof(SCROLLINFO); if (bGetTrackPos) { if (GetScrollInfo(nBar, &si, SIF_TRACKPOS)) return si.nTrackPos; } else { if (GetScrollInfo(nBar, &si, SIF_POS)) return si.nPos; } return 0; } BOOL CGridCtrl::SetScrollPos32(int nBar, int nPos, BOOL bRedraw /* = TRUE */) { m_idTopLeftCell.row = -1; SCROLLINFO si; si.cbSize = sizeof(SCROLLINFO); si.fMask = SIF_POS; si.nPos = nPos; return SetScrollInfo(nBar, &si, bRedraw); } void CGridCtrl::EnableScrollBars(int nBar, BOOL bEnable /*=TRUE*/) { if (bEnable) { if (!IsVisibleHScroll() && (nBar == SB_HORZ || nBar == SB_BOTH)) { m_nBarState |= GVL_HORZ; CWnd::EnableScrollBarCtrl(SB_HORZ, bEnable); } if (!IsVisibleVScroll() && (nBar == SB_VERT || nBar == SB_BOTH)) { m_nBarState |= GVL_VERT; CWnd::EnableScrollBarCtrl(SB_VERT, bEnable); } } else { if ( IsVisibleHScroll() && (nBar == SB_HORZ || nBar == SB_BOTH)) { m_nBarState &= ~GVL_HORZ; CWnd::EnableScrollBarCtrl(SB_HORZ, bEnable); } if ( IsVisibleVScroll() && (nBar == SB_VERT || nBar == SB_BOTH)) { m_nBarState &= ~GVL_VERT; CWnd::EnableScrollBarCtrl(SB_VERT, bEnable); } } } // If resizing or cell counts/sizes change, call this - it'll fix up the scroll bars void CGridCtrl::ResetScrollBars() { // Force a refresh. m_idTopLeftCell.row = -1; if (!m_bAllowDraw || !::IsWindow(GetSafeHwnd())) return; CRect rect; // This would have caused OnSize event - Brian //EnableScrollBars(SB_BOTH, FALSE); GetClientRect(rect); if (rect.left == rect.right || rect.top == rect.bottom) return; if (IsVisibleVScroll()) rect.right += GetSystemMetrics(SM_CXVSCROLL) + GetSystemMetrics(SM_CXBORDER); if (IsVisibleHScroll()) rect.bottom += GetSystemMetrics(SM_CYHSCROLL) + GetSystemMetrics(SM_CYBORDER); rect.left += GetFixedColumnWidth(); rect.top += GetFixedRowHeight(); if (rect.left >= rect.right || rect.top >= rect.bottom) { EnableScrollBarCtrl(SB_BOTH, FALSE); return; } CRect VisibleRect(GetFixedColumnWidth(), GetFixedRowHeight(), rect.right, rect.bottom); CRect VirtualRect(GetFixedColumnWidth(), GetFixedRowHeight(), GetVirtualWidth(), GetVirtualHeight()); // Removed to fix single row scrollbar problem (Pontus Goffe) // CCellRange visibleCells = GetUnobstructedNonFixedCellRange(); // if (!IsValid(visibleCells)) return; //TRACE(_T("Visible: %d x %d, Virtual %d x %d. H %d, V %d\n"), // VisibleRect.Width(), VisibleRect.Height(), // VirtualRect.Width(), VirtualRect.Height(), // IsVisibleHScroll(), IsVisibleVScroll()); // If vertical scroll bar, horizontal space is reduced if (VisibleRect.Height() < VirtualRect.Height()) VisibleRect.right -= ::GetSystemMetrics(SM_CXVSCROLL); // If horz scroll bar, vert space is reduced if (VisibleRect.Width() < VirtualRect.Width()) VisibleRect.bottom -= ::GetSystemMetrics(SM_CYHSCROLL); // Recheck vertical scroll bar //if (VisibleRect.Height() < VirtualRect.Height()) // VisibleRect.right -= ::GetSystemMetrics(SM_CXVSCROLL); if (VisibleRect.Height() < VirtualRect.Height()) { EnableScrollBars(SB_VERT, TRUE); m_nVScrollMax = VirtualRect.Height() - 1; } else { EnableScrollBars(SB_VERT, FALSE); m_nVScrollMax = 0; } if (VisibleRect.Width() < VirtualRect.Width()) { EnableScrollBars(SB_HORZ, TRUE); m_nHScrollMax = VirtualRect.Width() - 1; } else { EnableScrollBars(SB_HORZ, FALSE); m_nHScrollMax = 0; } ASSERT(m_nVScrollMax < INT_MAX && m_nHScrollMax < INT_MAX); // This should be fine /* Old code - CJM SCROLLINFO si; si.cbSize = sizeof(SCROLLINFO); si.fMask = SIF_PAGE; si.nPage = (m_nHScrollMax>0)? VisibleRect.Width() : 0; SetScrollInfo(SB_HORZ, &si, FALSE); si.nPage = (m_nVScrollMax>0)? VisibleRect.Height() : 0; SetScrollInfo(SB_VERT, &si, FALSE); SetScrollRange(SB_VERT, 0, m_nVScrollMax, TRUE); SetScrollRange(SB_HORZ, 0, m_nHScrollMax, TRUE); */ // New code - Paul Runstedler SCROLLINFO si; si.cbSize = sizeof(SCROLLINFO); si.fMask = SIF_PAGE | SIF_RANGE; si.nPage = (m_nHScrollMax>0)? VisibleRect.Width() : 0; si.nMin = 0; si.nMax = m_nHScrollMax; SetScrollInfo(SB_HORZ, &si, TRUE); si.fMask |= SIF_DISABLENOSCROLL; si.nPage = (m_nVScrollMax>0)? VisibleRect.Height() : 0; si.nMin = 0; si.nMax = m_nVScrollMax; SetScrollInfo(SB_VERT, &si, TRUE); } //////////////////////////////////////////////////////////////////////////////////// // Row/Column position functions // returns the top left point of the cell. Returns FALSE if cell not visible. BOOL CGridCtrl::GetCellOrigin(int nRow, int nCol, LPPOINT p) { int i; if (!IsValid(nRow, nCol)) return FALSE; CCellID idTopLeft; if (nCol >= m_nFixedCols || nRow >= m_nFixedRows) idTopLeft = GetTopleftNonFixedCell(); if ((nRow >= m_nFixedRows && nRow < idTopLeft.row) || (nCol>= m_nFixedCols && nCol < idTopLeft.col)) return FALSE; p->x = 0; if (nCol < m_nFixedCols) // is a fixed column for (i = 0; i < nCol; i++) p->x += GetColumnWidth(i); else { // is a scrollable data column for (i = 0; i < m_nFixedCols; i++) p->x += GetColumnWidth(i); for (i = idTopLeft.col; i < nCol; i++) p->x += GetColumnWidth(i); } p->y = 0; if (nRow < m_nFixedRows) // is a fixed row for (i = 0; i < nRow; i++) p->y += GetRowHeight(i); else { // is a scrollable data row for (i = 0; i < m_nFixedRows; i++) p->y += GetRowHeight(i); for (i = idTopLeft.row; i < nRow; i++) p->y += GetRowHeight(i); } return TRUE; } BOOL CGridCtrl::GetCellOrigin(const CCellID& cell, LPPOINT p) { return GetCellOrigin(cell.row, cell.col, p); } // Returns the bounding box of the cell BOOL CGridCtrl::GetCellRect(const CCellID& cell, LPRECT pRect) { return GetCellRect(cell.row, cell.col, pRect); } BOOL CGridCtrl::GetCellRect(int nRow, int nCol, LPRECT pRect) { CPoint CellOrigin; if (!GetCellOrigin(nRow, nCol, &CellOrigin)) return FALSE; pRect->left = CellOrigin.x; pRect->top = CellOrigin.y; pRect->right = CellOrigin.x + GetColumnWidth(nCol)-1; pRect->bottom = CellOrigin.y + GetRowHeight(nRow)-1; //TRACE("Row %d, col %d: L %d, T %d, W %d, H %d: %d,%d - %d,%d\n", // nRow,nCol, CellOrigin.x, CellOrigin.y, GetColumnWidth(nCol), GetRowHeight(nRow), // pRect->left, pRect->top, pRect->right, pRect->bottom); return TRUE; } BOOL CGridCtrl::GetTextRect(const CCellID& cell, LPRECT pRect) { return GetTextRect(cell.row, cell.col, pRect); } BOOL CGridCtrl::GetTextRect(int nRow, int nCol, LPRECT pRect) { CGridCellBase* pCell = GetCell( nRow, nCol); if( pCell == NULL) return FALSE; if( !GetCellRect( nRow, nCol, pRect) ) return FALSE; return pCell->GetTextRect( pRect); } // Returns the bounding box of a range of cells BOOL CGridCtrl::GetCellRangeRect(const CCellRange& cellRange, LPRECT lpRect) { CPoint MinOrigin,MaxOrigin; if (!GetCellOrigin(cellRange.GetMinRow(), cellRange.GetMinCol(), &MinOrigin)) return FALSE; if (!GetCellOrigin(cellRange.GetMaxRow(), cellRange.GetMaxCol(), &MaxOrigin)) return FALSE; lpRect->left = MinOrigin.x; lpRect->top = MinOrigin.y; lpRect->right = MaxOrigin.x + GetColumnWidth(cellRange.GetMaxCol()) - 1; lpRect->bottom = MaxOrigin.y + GetRowHeight(cellRange.GetMaxRow()) - 1; return TRUE; } //////////////////////////////////////////////////////////////////////////////////// // Grid attribute functions LRESULT CGridCtrl::OnSetFont(WPARAM hFont, LPARAM /*lParam */) { LRESULT result = Default(); // Get the logical font LOGFONT lf; if (!GetObject((HFONT) hFont, sizeof(LOGFONT), &lf)) return result; m_cellDefault.SetFont(&lf); m_cellFixedColDef.SetFont(&lf); m_cellFixedRowDef.SetFont(&lf); m_cellFixedRowColDef.SetFont(&lf); Refresh(); return result; } LRESULT CGridCtrl::OnGetFont(WPARAM /*wParam*/, LPARAM /*lParam*/) { //LOGFONT lf; //m_cellDefault.GetFontObject()->GetLogFont(&lf); return (LRESULT) m_cellDefault.GetFontObject()->GetSafeHandle(); } #ifndef _WIN32_WCE_NO_CURSOR BOOL CGridCtrl::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) { if (nHitTest == HTCLIENT) { switch (m_MouseMode) { case MOUSE_OVER_COL_DIVIDE: SetCursor(AfxGetApp()->LoadStandardCursor(IDC_SIZEWE)); break; case MOUSE_OVER_ROW_DIVIDE: SetCursor(AfxGetApp()->LoadStandardCursor(IDC_SIZENS)); break; #ifndef GRIDCONTROL_NO_DRAGDROP case MOUSE_DRAGGING: break; #endif default: if (!GetVirtualMode()) { CPoint pt(GetMessagePos()); ScreenToClient(&pt); CCellID cell = GetCellFromPt(pt); if (IsValid(cell)) { CGridCellBase* pCell = GetCell(cell.row, cell.col); if (pCell) return pCell->OnSetCursor(); } } SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW)); } return TRUE; } return CWnd::OnSetCursor(pWnd, nHitTest, message); } #endif //////////////////////////////////////////////////////////////////////////////////// // Row/Column count functions BOOL CGridCtrl::SetFixedRowCount(int nFixedRows) { if (m_nFixedRows == nFixedRows) return TRUE; ASSERT(nFixedRows >= 0); ResetSelectedRange(); // Force recalculation m_idTopLeftCell.col = -1; if (nFixedRows > GetRowCount()) if (!SetRowCount(nFixedRows)) return FALSE; if (m_idCurrentCell.row < nFixedRows) SetFocusCell(-1, - 1); if (!GetVirtualMode()) { if (nFixedRows > m_nFixedRows) { for (int i = m_nFixedRows; i < nFixedRows; i++) for (int j = 0; j < GetColumnCount(); j++) { SetItemState(i, j, GetItemState(i, j) | GVIS_FIXED | GVIS_FIXEDROW); SetItemBkColour(i, j, CLR_DEFAULT ); SetItemFgColour(i, j, CLR_DEFAULT ); } } else { for (int i = nFixedRows; i < m_nFixedRows; i++) { int j; for (j = 0; j < GetFixedColumnCount(); j++) SetItemState(i, j, GetItemState(i, j) & ~GVIS_FIXEDROW ); for (j = GetFixedColumnCount(); j < GetColumnCount(); j++) { SetItemState(i, j, GetItemState(i, j) & ~(GVIS_FIXED | GVIS_FIXEDROW) ); SetItemBkColour(i, j, CLR_DEFAULT ); SetItemFgColour(i, j, CLR_DEFAULT ); } } } } m_nFixedRows = nFixedRows; Refresh(); return TRUE; } BOOL CGridCtrl::SetFixedColumnCount(int nFixedCols) { if (m_nFixedCols == nFixedCols) return TRUE; ASSERT(nFixedCols >= 0); if (nFixedCols > GetColumnCount()) if (!SetColumnCount(nFixedCols)) return FALSE; if (m_idCurrentCell.col < nFixedCols) SetFocusCell(-1, - 1); ResetSelectedRange(); // Force recalculation m_idTopLeftCell.col = -1; if (!GetVirtualMode()) { if (nFixedCols > m_nFixedCols) { for (int i = 0; i < GetRowCount(); i++) for (int j = m_nFixedCols; j < nFixedCols; j++) { SetItemState(i, j, GetItemState(i, j) | GVIS_FIXED | GVIS_FIXEDCOL); SetItemBkColour(i, j, CLR_DEFAULT ); SetItemFgColour(i, j, CLR_DEFAULT ); } } else { { // Scope limit i,j for (int i = 0; i < GetFixedRowCount(); i++) for (int j = nFixedCols; j < m_nFixedCols; j++) SetItemState(i, j, GetItemState(i, j) & ~GVIS_FIXEDCOL ); } {// Scope limit i,j for (int i = GetFixedRowCount(); i < GetRowCount(); i++) for (int j = nFixedCols; j < m_nFixedCols; j++) { SetItemState(i, j, GetItemState(i, j) & ~(GVIS_FIXED | GVIS_FIXEDCOL) ); SetItemBkColour(i, j, CLR_DEFAULT ); SetItemFgColour(i, j, CLR_DEFAULT ); } } } } m_nFixedCols = nFixedCols; Refresh(); return TRUE; } BOOL CGridCtrl::SetRowCount(int nRows) { BOOL bResult = TRUE; ASSERT(nRows >= 0); if (nRows == GetRowCount()) return bResult; // Force recalculation m_idTopLeftCell.col = -1; if (nRows < m_nFixedRows) m_nFixedRows = nRows; if (m_idCurrentCell.row >= nRows) SetFocusCell(-1, - 1); int addedRows = nRows - GetRowCount(); // If we are about to lose rows, then we need to delete the GridCell objects // in each column within each row if (addedRows < 0) { if (!GetVirtualMode()) { for (int row = nRows; row < m_nRows; row++) { // Delete cells for (int col = 0; col < m_nCols; col++) DestroyCell(row, col); // Delete rows GRID_ROW* pRow = m_RowData[row]; if (pRow) delete pRow; } } m_nRows = nRows; } TRY { m_arRowHeights.SetSize(nRows); if (GetVirtualMode()) { m_nRows = nRows; if (addedRows > 0) { int startRow = nRows - addedRows; for (int row = startRow; row < nRows; row++) m_arRowHeights[row] = m_cellDefault.GetHeight(); } ResetVirtualOrder(); } else { // Change the number of rows. m_RowData.SetSize(nRows); // If we have just added rows, we need to construct new elements for each cell // and set the default row height if (addedRows > 0) { // initialize row heights and data int startRow = nRows - addedRows; for (int row = startRow; row < nRows; row++) { m_arRowHeights[row] = m_cellDefault.GetHeight(); m_RowData[row] = new GRID_ROW; m_RowData[row]->SetSize(m_nCols); for (int col = 0; col < m_nCols; col++) { GRID_ROW* pRow = m_RowData[row]; if (pRow && !GetVirtualMode()) pRow->SetAt(col, CreateCell(row, col)); } m_nRows++; } } } } CATCH (CMemoryException, e) { e->ReportError(); bResult = FALSE; } END_CATCH SetModified(); ResetScrollBars(); Refresh(); return bResult; } BOOL CGridCtrl::SetColumnCount(int nCols) { BOOL bResult = TRUE; ASSERT(nCols >= 0); if (nCols == GetColumnCount()) return bResult; // Force recalculation m_idTopLeftCell.col = -1; if (nCols < m_nFixedCols) m_nFixedCols = nCols; if (m_idCurrentCell.col >= nCols) SetFocusCell(-1, - 1); int addedCols = nCols - GetColumnCount(); // If we are about to lose columns, then we need to delete the GridCell objects // within each column if (addedCols < 0 && !GetVirtualMode()) { for (int row = 0; row < m_nRows; row++) for (int col = nCols; col < GetColumnCount(); col++) DestroyCell(row, col); } TRY { // Change the number of columns. m_arColWidths.SetSize(nCols); // Change the number of columns in each row. if (!GetVirtualMode()) for (int i = 0; i < m_nRows; i++) if (m_RowData[i]) m_RowData[i]->SetSize(nCols); // If we have just added columns, we need to construct new elements for each cell // and set the default column width if (addedCols > 0) { int row, col; // initialized column widths int startCol = nCols - addedCols; for (col = startCol; col < nCols; col++) m_arColWidths[col] = m_cellFixedColDef.GetWidth(); // initialise column data if (!GetVirtualMode()) { for (row = 0; row < m_nRows; row++) for (col = startCol; col < nCols; col++) { GRID_ROW* pRow = m_RowData[row]; if (pRow) pRow->SetAt(col, CreateCell(row, col)); } } } // else // check for selected cell ranges // ResetSelectedRange(); } CATCH (CMemoryException, e) { e->ReportError(); bResult = FALSE; } END_CATCH m_arColOrder.resize(nCols); // Reset Column Order for (int i = 0; i < nCols; i++) { m_arColOrder[i] = i; } m_nCols = nCols; SetModified(); ResetScrollBars(); Refresh(); return bResult; } // Insert a column at a given position, or add to end of columns (if nColumn = -1) int CGridCtrl::InsertColumn(LPCTSTR strHeading, UINT nFormat /* = DT_CENTER|DT_VCENTER|DT_SINGLELINE */, int nColumn /* = -1 */) { ASSERT(!m_AllowReorderColumn); // function not implemented in case of m_AllowReorderColumn option if (nColumn >= 0 && nColumn < m_nFixedCols) { // TODO: Fix it so column insertion works for in the fixed column area ASSERT(FALSE); return -1; } // If the insertion is for a specific column, check it's within range. if (nColumn >= 0 && nColumn > GetColumnCount()) return -1; // Force recalculation m_idTopLeftCell.col = -1; ResetSelectedRange(); // Gotta be able to at least _see_ some of the column. if (m_nRows < 1) SetRowCount(1); // Allow the user to insert after the last of the columns, but process it as a // "-1" column, meaning it gets flaged as being the last column, and not a regular // "insert" routine. if (nColumn == GetColumnCount()) nColumn = -1; TRY { if (nColumn < 0) { nColumn = m_nCols; m_arColWidths.Add(0); if (!GetVirtualMode()) { for (int row = 0; row < m_nRows; row++) { GRID_ROW* pRow = m_RowData[row]; if (!pRow) return -1; pRow->Add(CreateCell(row, nColumn)); } } } else { m_arColWidths.InsertAt(nColumn, (UINT)0); if (!GetVirtualMode()) { for (int row = 0; row < m_nRows; row++) { GRID_ROW* pRow = m_RowData[row]; if (!pRow) return -1; pRow->InsertAt(nColumn, CreateCell(row, nColumn)); } } } } CATCH (CMemoryException, e) { e->ReportError(); return -1; } END_CATCH m_nCols++; // Initialise column data SetItemText(0, nColumn, strHeading); for (int row = 0; row < m_nRows; row++) SetItemFormat(row, nColumn, nFormat); // initialized column width m_arColWidths[nColumn] = GetTextExtent(0, nColumn, strHeading).cx; if (m_idCurrentCell.col != -1 && nColumn < m_idCurrentCell.col) m_idCurrentCell.col++; ResetScrollBars(); SetModified(); return nColumn; } // Insert a row at a given position, or add to end of rows (if nRow = -1) int CGridCtrl::InsertRow(LPCTSTR strHeading, int nRow /* = -1 */) { if (nRow >= 0 && nRow < m_nFixedRows) { // TODO: Fix it so column insertion works for in the fixed row area ASSERT(FALSE); return -1; } // If the insertion is for a specific row, check it's within range. if (nRow >= 0 && nRow >= GetRowCount()) return -1; // Force recalculation m_idTopLeftCell.col = -1; ResetSelectedRange(); // Gotta be able to at least _see_ some of the row. if (m_nCols < 1) SetColumnCount(1); TRY { // Adding a row to the bottom if (nRow < 0) { nRow = m_nRows; m_arRowHeights.Add(0); if (!GetVirtualMode()) m_RowData.Add(new GRID_ROW); else m_arRowOrder.push_back(m_nRows); } else { m_arRowHeights.InsertAt(nRow, (UINT)0); if (!GetVirtualMode()) m_RowData.InsertAt(nRow, new GRID_ROW); else { ResetVirtualOrder(); } } if (!GetVirtualMode()) m_RowData[nRow]->SetSize(m_nCols); } CATCH (CMemoryException, e) { e->ReportError(); return -1; } END_CATCH m_nRows++; // Initialise cell data if (!GetVirtualMode()) { for (int col = 0; col < m_nCols; col++) { GRID_ROW* pRow = m_RowData[nRow]; if (!pRow) return -1; pRow->SetAt(col, CreateCell(nRow, col)); } } // Set row title SetItemText(nRow, 0, strHeading); // initialized row height if (strHeading && strHeading[0]) m_arRowHeights[nRow] = GetTextExtent(nRow, 0, strHeading).cy; else m_arRowHeights[nRow] = m_cellFixedRowDef.GetHeight(); if (m_idCurrentCell.row != -1 && nRow < m_idCurrentCell.row) m_idCurrentCell.row++; ResetScrollBars(); SetModified(); return nRow; } /////////////////////////////////////////////////////////////////////////////// // Cell creation stuff BOOL CGridCtrl::SetCellType(int nRow, int nCol, CRuntimeClass* pRuntimeClass) { if (GetVirtualMode()) return FALSE; ASSERT(IsValid(nRow, nCol)); if (!IsValid(nRow, nCol)) return FALSE; if (!pRuntimeClass->IsDerivedFrom(RUNTIME_CLASS(CGridCellBase))) { ASSERT( FALSE); return FALSE; } CGridCellBase* pNewCell = (CGridCellBase*) pRuntimeClass->CreateObject(); CGridCellBase* pCurrCell = GetCell(nRow, nCol); if (pCurrCell) *pNewCell = *pCurrCell; SetCell(nRow, nCol, pNewCell); delete pCurrCell; return TRUE; } BOOL CGridCtrl::SetDefaultCellType( CRuntimeClass* pRuntimeClass) { ASSERT( pRuntimeClass != NULL ); if (!pRuntimeClass->IsDerivedFrom(RUNTIME_CLASS(CGridCellBase))) { ASSERT( FALSE); return FALSE; } m_pRtcDefault = pRuntimeClass; return TRUE; } // Creates a new grid cell and performs any necessary initialisation /*virtual*/ CGridCellBase* CGridCtrl::CreateCell(int nRow, int nCol) { ASSERT(!GetVirtualMode()); if (!m_pRtcDefault || !m_pRtcDefault->IsDerivedFrom(RUNTIME_CLASS(CGridCellBase))) { ASSERT( FALSE); return NULL; } CGridCellBase* pCell = (CGridCellBase*) m_pRtcDefault->CreateObject(); if (!pCell) return NULL; pCell->SetGrid(this); pCell->SetCoords(nRow, nCol); if (nCol < m_nFixedCols) pCell->SetState(pCell->GetState() | GVIS_FIXED | GVIS_FIXEDCOL); if (nRow < m_nFixedRows) pCell->SetState(pCell->GetState() | GVIS_FIXED | GVIS_FIXEDROW); pCell->SetFormat(pCell->GetDefaultCell()->GetFormat()); return pCell; } // Performs any cell cleanup necessary to maintain grid integrity /*virtual*/ void CGridCtrl::DestroyCell(int nRow, int nCol) { // Should NEVER get here in virtual mode. ASSERT(!GetVirtualMode()); // Set the cells state to 0. If the cell is selected, this // will remove the cell from the selected list. SetItemState(nRow, nCol, 0); delete GetCell(nRow, nCol); } BOOL CGridCtrl::DeleteColumn(int nColumn) { if (nColumn < 0 || nColumn >= GetColumnCount()) return FALSE; ResetSelectedRange(); if (!GetVirtualMode()) { for (int row = 0; row < GetRowCount(); row++) { GRID_ROW* pRow = m_RowData[row]; if (!pRow) return FALSE; DestroyCell(row, nColumn); pRow->RemoveAt(nColumn); } } m_arColWidths.RemoveAt(nColumn); m_nCols--; if (nColumn < m_nFixedCols) m_nFixedCols--; if (nColumn == m_idCurrentCell.col) m_idCurrentCell.row = m_idCurrentCell.col = -1; else if (nColumn < m_idCurrentCell.col) m_idCurrentCell.col--; ResetScrollBars(); SetModified(); return TRUE; } void CGridCtrl::AddSubVirtualRow(int Num, int Nb) { ASSERT(Nb == -1 || Nb ==1); // only these vlaues are implemented now if(!GetVirtualMode()) return; for(int ind = 0; ind<m_nRows ; ind++) if(m_arRowOrder[ind]>Num) m_arRowOrder[ind]+=Nb; if(Nb>0) m_arRowOrder.insert(m_arRowOrder.begin()+Num,Num); else m_arRowOrder.erase(m_arRowOrder.begin()+Num); } BOOL CGridCtrl::DeleteRow(int nRow) { if (nRow < 0 || nRow >= GetRowCount()) return FALSE; ResetSelectedRange(); if (!GetVirtualMode()) { GRID_ROW* pRow = m_RowData[nRow]; if (!pRow) return FALSE; for (int col = 0; col < GetColumnCount(); col++) DestroyCell(nRow, col); delete pRow; m_RowData.RemoveAt(nRow); } else AddSubVirtualRow(nRow,-1); m_arRowHeights.RemoveAt(nRow); m_nRows--; if (nRow < m_nFixedRows) m_nFixedRows--; if (nRow == m_idCurrentCell.row) m_idCurrentCell.row = m_idCurrentCell.col = -1; else if (nRow < m_idCurrentCell.row) m_idCurrentCell.row--; ResetScrollBars(); SetModified(); return TRUE; } // Handy function that removes all non-fixed rows BOOL CGridCtrl::DeleteNonFixedRows() { ResetSelectedRange(); int nFixed = GetFixedRowCount(); int nCount = GetRowCount(); if (GetVirtualMode()) { if(nCount != nFixed) { SetRowCount(nFixed); m_arRowOrder.resize(nFixed); m_arRowHeights.SetSize(nFixed); m_idCurrentCell.row = m_idCurrentCell.col = -1; ResetScrollBars(); SetModified(); } } else { // Delete all data rows for (int nRow = nCount; nRow >= nFixed; nRow--) DeleteRow(nRow); } return TRUE; } // Removes all rows, columns and data from the grid. BOOL CGridCtrl::DeleteAllItems() { ResetSelectedRange(); m_arColWidths.RemoveAll(); m_arRowHeights.RemoveAll(); // Delete all cells in the grid if (!GetVirtualMode()) { for (int row = 0; row < m_nRows; row++) { for (int col = 0; col < m_nCols; col++) DestroyCell(row, col); GRID_ROW* pRow = m_RowData[row]; delete pRow; } // Remove all rows m_RowData.RemoveAll(); } else m_arRowOrder.clear(); m_idCurrentCell.row = m_idCurrentCell.col = -1; m_nRows = m_nFixedRows = m_nCols = m_nFixedCols = 0; ResetScrollBars(); SetModified(); return TRUE; } void CGridCtrl::AutoFill() { if (!::IsWindow(m_hWnd)) return; CRect rect; GetClientRect(rect); SetColumnCount(rect.Width() / m_cellDefault.GetWidth() + 1); SetRowCount(rect.Height() / m_cellDefault.GetHeight() + 1); SetFixedRowCount(1); SetFixedColumnCount(1); ExpandToFit(); } ///////////////////////////////////////////////////////////////////////////// // CGridCtrl data functions // Set CListCtrl::GetNextItem for details CCellID CGridCtrl::GetNextItem(CCellID& cell, int nFlags) const { if ((nFlags & GVNI_ALL) == GVNI_ALL) { // GVNI_ALL Search whole Grid beginning from cell // First row (cell.row) -- ONLY Columns to the right of cell // following rows -- ALL Columns int row = cell.row , col = cell.col + 1; if (row <= 0) row = GetFixedRowCount(); for (; row < GetRowCount(); row++) { if (col <= 0) col = GetFixedColumnCount(); for (; col < GetColumnCount(); col++) { int nState = GetItemState(row, col); if ((nFlags & GVNI_DROPHILITED && nState & GVIS_DROPHILITED) || (nFlags & GVNI_FOCUSED && nState & GVIS_FOCUSED) || (nFlags & GVNI_SELECTED && nState & GVIS_SELECTED) || (nFlags & GVNI_READONLY && nState & GVIS_READONLY) || (nFlags & GVNI_FIXED && nState & GVIS_FIXED) || (nFlags & GVNI_MODIFIED && nState & GVIS_MODIFIED)) return CCellID(row, col); } // go to First Column col = GetFixedColumnCount(); } } else if ((nFlags & GVNI_BELOW) == GVNI_BELOW && (nFlags & GVNI_TORIGHT) == GVNI_TORIGHT) { // GVNI_AREA Search Grid beginning from cell to Lower-Right of Grid // Only rows starting with cell.row and below // All rows -- ONLY Columns to the right of cell int row = cell.row; if (row <= 0) row = GetFixedRowCount(); for (; row < GetRowCount(); row++) { int col = cell.col + 1; if (col <= 0) col = GetFixedColumnCount(); for (; col < GetColumnCount(); col++) { int nState = GetItemState(row, col); if ((nFlags & GVNI_DROPHILITED && nState & GVIS_DROPHILITED) || (nFlags & GVNI_FOCUSED && nState & GVIS_FOCUSED) || (nFlags & GVNI_SELECTED && nState & GVIS_SELECTED) || (nFlags & GVNI_READONLY && nState & GVIS_READONLY) || (nFlags & GVNI_FIXED && nState & GVIS_FIXED) || (nFlags & GVNI_MODIFIED && nState & GVIS_MODIFIED)) return CCellID(row, col); } } } else if ((nFlags & GVNI_ABOVE) == GVNI_ABOVE) { for (int row = cell.row - 1; row >= GetFixedRowCount(); row--) { int nState = GetItemState(row, cell.col); if ((nFlags & GVNI_DROPHILITED && nState & GVIS_DROPHILITED) || (nFlags & GVNI_FOCUSED && nState & GVIS_FOCUSED) || (nFlags & GVNI_SELECTED && nState & GVIS_SELECTED) || (nFlags & GVNI_READONLY && nState & GVIS_READONLY) || (nFlags & GVNI_FIXED && nState & GVIS_FIXED) || (nFlags & GVNI_MODIFIED && nState & GVIS_MODIFIED)) return CCellID(row, cell.col); } } else if ((nFlags & GVNI_BELOW) == GVNI_BELOW) { for (int row = cell.row + 1; row < GetRowCount(); row++) { int nState = GetItemState(row, cell.col); if ((nFlags & GVNI_DROPHILITED && nState & GVIS_DROPHILITED) || (nFlags & GVNI_FOCUSED && nState & GVIS_FOCUSED) || (nFlags & GVNI_SELECTED && nState & GVIS_SELECTED) || (nFlags & GVNI_READONLY && nState & GVIS_READONLY) || (nFlags & GVNI_FIXED && nState & GVIS_FIXED) || (nFlags & GVNI_MODIFIED && nState & GVIS_MODIFIED)) return CCellID(row, cell.col); } } else if ((nFlags & GVNI_TOLEFT) == GVNI_TOLEFT) { for (int col = cell.col - 1; col >= GetFixedColumnCount(); col--) { int nState = GetItemState(cell.row, col); if ((nFlags & GVNI_DROPHILITED && nState & GVIS_DROPHILITED) || (nFlags & GVNI_FOCUSED && nState & GVIS_FOCUSED) || (nFlags & GVNI_SELECTED && nState & GVIS_SELECTED) || (nFlags & GVNI_READONLY && nState & GVIS_READONLY) || (nFlags & GVNI_FIXED && nState & GVIS_FIXED) || (nFlags & GVNI_MODIFIED && nState & GVIS_MODIFIED)) return CCellID(cell.row, col); } } else if ((nFlags & GVNI_TORIGHT) == GVNI_TORIGHT) { for (int col = cell.col + 1; col < GetColumnCount(); col++) { int nState = GetItemState(cell.row, col); if ((nFlags & GVNI_DROPHILITED && nState & GVIS_DROPHILITED) || (nFlags & GVNI_FOCUSED && nState & GVIS_FOCUSED) || (nFlags & GVNI_SELECTED && nState & GVIS_SELECTED) || (nFlags & GVNI_READONLY && nState & GVIS_READONLY) || (nFlags & GVNI_FIXED && nState & GVIS_FIXED) || (nFlags & GVNI_MODIFIED && nState & GVIS_MODIFIED)) return CCellID(cell.row, col); } } return CCellID(-1, -1); } // Sorts on a given column using the cell text BOOL CGridCtrl::SortTextItems(int nCol, BOOL bAscending, LPARAM data /* = 0 */) { return CGridCtrl::SortItems(pfnCellTextCompare, nCol, bAscending, data); } void CGridCtrl::SetCompareFunction(PFNLVCOMPARE pfnCompare) { m_pfnCompare = pfnCompare; } // Sorts on a given column using the cell text and using the specified comparison // function BOOL CGridCtrl::SortItems(int nCol, BOOL bAscending, LPARAM data /* = 0 */) { SetSortColumn(nCol); SetSortAscending(bAscending); ResetSelectedRange(); SetFocusCell(-1, - 1); if (m_pfnCompare == NULL) return CGridCtrl::SortItems(pfnCellTextCompare, nCol, bAscending, data); else return CGridCtrl::SortItems(m_pfnCompare, nCol, bAscending, data); } // Sorts on a given column using the supplied compare function (see CListCtrl::SortItems) BOOL CGridCtrl::SortItems(PFNLVCOMPARE pfnCompare, int nCol, BOOL bAscending, LPARAM data /* = 0 */) { SetSortColumn(nCol); SetSortAscending(bAscending); ResetSelectedRange(); SetFocusCell(-1, -1); return SortItems(pfnCompare, nCol, bAscending, data, GetFixedRowCount(), -1); } int CALLBACK CGridCtrl::pfnCellTextCompare(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort) { UNUSED_ALWAYS(lParamSort); CGridCellBase* pCell1 = (CGridCellBase*) lParam1; CGridCellBase* pCell2 = (CGridCellBase*) lParam2; if (!pCell1 || !pCell2) return 0; return _tcscmp(pCell1->GetText(), pCell2->GetText()); } int CALLBACK CGridCtrl::pfnCellNumericCompare(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort) { UNUSED_ALWAYS(lParamSort); CGridCellBase* pCell1 = (CGridCellBase*) lParam1; CGridCellBase* pCell2 = (CGridCellBase*) lParam2; if (!pCell1 || !pCell2) return 0; int nValue1 = _ttol(pCell1->GetText()); int nValue2 = _ttol(pCell2->GetText()); if (nValue1 < nValue2) return -1; else if (nValue1 == nValue2) return 0; else return 1; } CGridCtrl * CGridCtrl::m_This; // private recursive sort implementation bool CGridCtrl::NotVirtualCompare(int c1, int c2) { return ! CGridCtrl::m_This->m_pfnVirtualCompare(c1, c2); } BOOL CGridCtrl::SortItems(PFNLVCOMPARE pfnCompare, int nCol, BOOL bAscending, LPARAM data, int low, int high) { if (nCol >= GetColumnCount()) return FALSE; if (high == -1) high = GetRowCount() - 1; int lo = low; int hi = high; if (hi <= lo) return FALSE; if (GetVirtualMode()) { ASSERT(m_pfnVirtualCompare); m_CurCol = m_arColOrder[nCol]; m_This = this; std::stable_sort(m_arRowOrder.begin() + m_nFixedRows, m_arRowOrder.end(), bAscending ? m_pfnVirtualCompare : NotVirtualCompare); return TRUE; } //LPARAM midItem = GetItemData((lo + hi)/2, nCol); LPARAM pMidCell = (LPARAM) GetCell((lo + hi)/2, nCol); // loop through the list until indices cross while (lo <= hi) { // Find the first element that is greater than or equal to the partition // element starting from the left Index. if (bAscending) while (lo < high && pfnCompare( (LPARAM)GetCell(lo, nCol), (LPARAM) pMidCell, data) < 0) ++lo; else while (lo < high && pfnCompare((LPARAM)GetCell(lo, nCol), pMidCell, data) > 0) ++lo; // Find an element that is smaller than or equal to the partition // element starting from the right Index. if (bAscending) while (hi > low && pfnCompare((LPARAM)GetCell(hi, nCol), pMidCell, data) > 0) --hi; else while (hi > low && pfnCompare((LPARAM)GetCell(hi, nCol), pMidCell, data) < 0) --hi; // If the indexes have not crossed, swap if the items are not equal if (lo <= hi) { // swap only if the items are not equal if (pfnCompare((LPARAM)GetCell(lo, nCol), (LPARAM)GetCell(hi, nCol), data) != 0) { for (int col = 0; col < GetColumnCount(); col++) { CGridCellBase *pCell = GetCell(lo, col); SetCell(lo, col, GetCell(hi, col)); SetCell(hi, col, pCell); } UINT nRowHeight = m_arRowHeights[lo]; m_arRowHeights[lo] = m_arRowHeights[hi]; m_arRowHeights[hi] = nRowHeight; } ++lo; --hi; } } // If the right index has not reached the left side of array // must now sort the left partition. if (low < hi) SortItems(pfnCompare, nCol, bAscending, data, low, hi); // If the left index has not reached the right side of array // must now sort the right partition. if (lo < high) SortItems(pfnCompare, nCol, bAscending, data, lo, high); return TRUE; } ///////////////////////////////////////////////////////////////////////////// // CGridCtrl data functions BOOL CGridCtrl::SetItem(const GV_ITEM* pItem) { if (!pItem || GetVirtualMode()) return FALSE; CGridCellBase* pCell = GetCell(pItem->row, pItem->col); if (!pCell) return FALSE; SetModified(TRUE, pItem->row, pItem->col); if (pItem->mask & GVIF_TEXT) pCell->SetText(pItem->strText); if (pItem->mask & GVIF_PARAM) pCell->SetData(pItem->lParam); if (pItem->mask & GVIF_IMAGE) pCell->SetImage(pItem->iImage); if (pItem->mask & GVIF_STATE) SetItemState(pItem->row, pItem->col, pItem->nState); if (pItem->mask & GVIF_FORMAT) pCell->SetFormat(pItem->nFormat); if (pItem->mask & GVIF_BKCLR) pCell->SetBackClr(pItem->crBkClr); if (pItem->mask & GVIF_FGCLR) pCell->SetTextClr(pItem->crFgClr); if (pItem->mask & GVIF_FONT) pCell->SetFont(&(pItem->lfFont)); if( pItem->mask & GVIF_MARGIN) pCell->SetMargin( pItem->nMargin); return TRUE; } BOOL CGridCtrl::GetItem(GV_ITEM* pItem) { if (!pItem) return FALSE; CGridCellBase* pCell = GetCell(pItem->row, pItem->col); if (!pCell) return FALSE; if (pItem->mask & GVIF_TEXT) pItem->strText = GetItemText(pItem->row, pItem->col); if (pItem->mask & GVIF_PARAM) pItem->lParam = pCell->GetData();; if (pItem->mask & GVIF_IMAGE) pItem->iImage = pCell->GetImage(); if (pItem->mask & GVIF_STATE) pItem->nState = pCell->GetState(); if (pItem->mask & GVIF_FORMAT) pItem->nFormat = pCell->GetFormat(); if (pItem->mask & GVIF_BKCLR) pItem->crBkClr = pCell->GetBackClr(); if (pItem->mask & GVIF_FGCLR) pItem->crFgClr = pCell->GetTextClr(); if (pItem->mask & GVIF_FONT) memcpy(&(pItem->lfFont), pCell->GetFont(), sizeof(LOGFONT)); if( pItem->mask & GVIF_MARGIN) pItem->nMargin = pCell->GetMargin(); return TRUE; } BOOL CGridCtrl::SetItemText(int nRow, int nCol, LPCTSTR str) { if (GetVirtualMode()) return FALSE; CGridCellBase* pCell = GetCell(nRow, nCol); if (!pCell) return FALSE; pCell->SetText(str); SetModified(TRUE, nRow, nCol); return TRUE; } #if !defined(_WIN32_WCE) || (_WIN32_WCE >= 210) // EFW - 06/13/99 - Added to support printf-style formatting codes BOOL CGridCtrl::SetItemTextFmt(int nRow, int nCol, LPCTSTR szFmt, ...) { if (GetVirtualMode()) return FALSE; CString strText; va_list argptr; CGridCellBase* pCell = GetCell(nRow, nCol); if (!pCell) return FALSE; // Format the message text va_start(argptr, szFmt); strText.FormatV(szFmt, argptr); va_end(argptr); pCell->SetText(strText); SetModified(TRUE, nRow, nCol); return TRUE; } // EFW - 06/13/99 - Added to support string resource ID. Supports // a variable argument list too. BOOL CGridCtrl::SetItemTextFmtID(int nRow, int nCol, UINT nID, ...) { if (GetVirtualMode()) return FALSE; CString strFmt, strText; va_list argptr; CGridCellBase* pCell = GetCell(nRow, nCol); if (!pCell) return FALSE; // Format the message text va_start(argptr, nID); VERIFY(strFmt.LoadString(nID)); strText.FormatV(strFmt, argptr); va_end(argptr); pCell->SetText(strText); SetModified(TRUE, nRow, nCol); return TRUE; } #endif BOOL CGridCtrl::SetItemData(int nRow, int nCol, LPARAM lParam) { if (GetVirtualMode()) return FALSE; CGridCellBase* pCell = GetCell(nRow, nCol); if (!pCell) return FALSE; pCell->SetData(lParam); SetModified(TRUE, nRow, nCol); return TRUE; } LPARAM CGridCtrl::GetItemData(int nRow, int nCol) const { CGridCellBase* pCell = GetCell(nRow, nCol); if (!pCell) return (LPARAM) 0; return pCell->GetData(); } BOOL CGridCtrl::SetItemImage(int nRow, int nCol, int iImage) { if (GetVirtualMode()) return FALSE; CGridCellBase* pCell = GetCell(nRow, nCol); if (!pCell) return FALSE; pCell->SetImage(iImage); SetModified(TRUE, nRow, nCol); return TRUE; } int CGridCtrl::GetItemImage(int nRow, int nCol) const { CGridCellBase* pCell = GetCell(nRow, nCol); ASSERT(pCell); if (!pCell) return -1; return pCell->GetImage(); } BOOL CGridCtrl::SetItemState(int nRow, int nCol, UINT state) { BOOL bSelected = IsCellSelected(nRow, nCol); // If the cell is being unselected, remove it from the selected list if (bSelected && !(state & GVIS_SELECTED)) { CCellID cell; DWORD key = MAKELONG(nRow, nCol); if (m_SelectedCellMap.Lookup(key, (CCellID&)cell)) m_SelectedCellMap.RemoveKey(key); } // If cell is being selected, add it to the list of selected cells else if (!bSelected && (state & GVIS_SELECTED)) { CCellID cell(nRow, nCol); m_SelectedCellMap.SetAt(MAKELONG(nRow, nCol), cell); } if (GetVirtualMode()) return FALSE; CGridCellBase* pCell = GetCell(nRow, nCol); ASSERT(pCell); if (!pCell) return FALSE; // Set the cell's state pCell->SetState(state); return TRUE; } UINT CGridCtrl::GetItemState(int nRow, int nCol) const { CGridCellBase* pCell = GetCell(nRow, nCol); ASSERT(pCell); if (!pCell) return 0; return pCell->GetState(); } BOOL CGridCtrl::SetItemFormat(int nRow, int nCol, UINT nFormat) { if (GetVirtualMode()) return FALSE; CGridCellBase* pCell = GetCell(nRow, nCol); ASSERT(pCell); if (!pCell) return FALSE; pCell->SetFormat(nFormat); return TRUE; } UINT CGridCtrl::GetItemFormat(int nRow, int nCol) const { CGridCellBase* pCell = GetCell(nRow, nCol); ASSERT(pCell); if (!pCell) return 0; return pCell->GetFormat(); } BOOL CGridCtrl::SetItemBkColour(int nRow, int nCol, COLORREF cr /* = CLR_DEFAULT */) { if (GetVirtualMode()) return FALSE; CGridCellBase* pCell = GetCell(nRow, nCol); ASSERT(pCell); if (!pCell) return FALSE; pCell->SetBackClr(cr); return TRUE; } COLORREF CGridCtrl::GetItemBkColour(int nRow, int nCol) const { CGridCellBase* pCell = GetCell(nRow, nCol); ASSERT(pCell); if (!pCell) return 0; return pCell->GetBackClr(); } BOOL CGridCtrl::SetItemFgColour(int nRow, int nCol, COLORREF cr /* = CLR_DEFAULT */) { if (GetVirtualMode()) return FALSE; CGridCellBase* pCell = GetCell(nRow, nCol); ASSERT(pCell); if (!pCell) return FALSE; pCell->SetTextClr(cr); return TRUE; } COLORREF CGridCtrl::GetItemFgColour(int nRow, int nCol) const { CGridCellBase* pCell = GetCell(nRow, nCol); ASSERT(pCell); if (!pCell) return 0; return pCell->GetTextClr(); } BOOL CGridCtrl::SetItemFont(int nRow, int nCol, const LOGFONT* plf) { if (GetVirtualMode()) return FALSE; CGridCellBase* pCell = GetCell(nRow, nCol); ASSERT(pCell); if (!pCell) return FALSE; pCell->SetFont(plf); return TRUE; } const LOGFONT* CGridCtrl::GetItemFont(int nRow, int nCol) { CGridCellBase* pCell = GetCell(nRow, nCol); ASSERT(pCell); if (!pCell) return GetDefaultCell(nRow < GetFixedRowCount(), nCol < GetFixedColumnCount())->GetFont(); return pCell->GetFont(); } BOOL CGridCtrl::IsItemEditing(int nRow, int nCol) { CGridCellBase* pCell = GetCell(nRow, nCol); ASSERT(pCell); if (!pCell) return FALSE; return pCell->IsEditing(); } //////////////////////////////////////////////////////////////////////////////////// // Row/Column size functions long CGridCtrl::GetVirtualWidth() const { long lVirtualWidth = 0; int iColCount = GetColumnCount(); for (int i = 0; i < iColCount; i++) lVirtualWidth += m_arColWidths[i]; return lVirtualWidth; } long CGridCtrl::GetVirtualHeight() const { long lVirtualHeight = 0; int iRowCount = GetRowCount(); for (int i = 0; i < iRowCount; i++) lVirtualHeight += m_arRowHeights[i]; return lVirtualHeight; } int CGridCtrl::GetRowHeight(int nRow) const { ASSERT(nRow >= 0 && nRow < m_nRows); if (nRow < 0 || nRow >= m_nRows) return -1; return m_arRowHeights[nRow]; } int CGridCtrl::GetColumnWidth(int nCol) const { ASSERT(nCol >= 0 && nCol < m_nCols); if (nCol < 0 || nCol >= m_nCols) return -1; return m_arColWidths[m_arColOrder[nCol]]; } BOOL CGridCtrl::SetRowHeight(int nRow, int height) { ASSERT(nRow >= 0 && nRow < m_nRows && height >= 0); if (nRow < 0 || nRow >= m_nRows || height < 0) return FALSE; m_arRowHeights[nRow] = height; ResetScrollBars(); return TRUE; } BOOL CGridCtrl::SetColumnWidth(int nCol, int width) { ASSERT(nCol >= 0 && nCol < m_nCols && width >= 0); if (nCol < 0 || nCol >= m_nCols || width < 0) return FALSE; m_arColWidths[m_arColOrder[nCol]] = width; ResetScrollBars(); return TRUE; } int CGridCtrl::GetFixedRowHeight() const { int nHeight = 0; for (int i = 0; i < m_nFixedRows; i++) nHeight += GetRowHeight(i); return nHeight; } int CGridCtrl::GetFixedColumnWidth() const { int nWidth = 0; for (int i = 0; i < m_nFixedCols; i++) nWidth += GetColumnWidth(i); return nWidth; } BOOL CGridCtrl::AutoSizeColumn(int nCol, UINT nAutoSizeStyle /*=GVS_DEFAULT*/, BOOL bResetScroll /*=TRUE*/) { ASSERT(nCol >= 0 && nCol < m_nCols); if (nCol < 0 || nCol >= m_nCols) return FALSE; // Skip hidden columns when autosizing if( GetColumnWidth( nCol) <=0 ) return FALSE; CSize size; CDC* pDC = GetDC(); if (!pDC) return FALSE; int nWidth = 0; ASSERT(GVS_DEFAULT <= nAutoSizeStyle && nAutoSizeStyle <= GVS_BOTH); if (nAutoSizeStyle == GVS_DEFAULT) nAutoSizeStyle = GetAutoSizeStyle(); int nStartRow = (nAutoSizeStyle & GVS_HEADER)? 0 : GetFixedRowCount(); int nEndRow = (nAutoSizeStyle & GVS_DATA)? GetRowCount()-1 : GetFixedRowCount()-1; if (GetVirtualMode()) SendCacheHintToParent(CCellRange(nStartRow, nCol, nEndRow, nCol)); for (int nRow = nStartRow; nRow <= nEndRow; nRow++) { CGridCellBase* pCell = GetCell(nRow, nCol); if (pCell) size = pCell->GetCellExtent(pDC); if (size.cx > nWidth) nWidth = size.cx; } if (GetVirtualMode()) SendCacheHintToParent(CCellRange(-1,-1,-1,-1)); m_arColWidths[nCol] = nWidth; ReleaseDC(pDC); if (bResetScroll) ResetScrollBars(); return TRUE; } BOOL CGridCtrl::AutoSizeRow(int nRow, BOOL bResetScroll /*=TRUE*/) { ASSERT(nRow >= 0 && nRow < m_nRows); if (nRow < 0 || nRow >= m_nRows) return FALSE; // Skip hidden rows when autosizing if( GetRowHeight( nRow) <=0 ) return FALSE; CSize size; CDC* pDC = GetDC(); if (!pDC) return FALSE; int nHeight = 0; int nNumColumns = GetColumnCount(); if (GetVirtualMode()) SendCacheHintToParent(CCellRange(nRow, 0, nRow, nNumColumns)); for (int nCol = 0; nCol < nNumColumns; nCol++) { CGridCellBase* pCell = GetCell(nRow, nCol); if (pCell) size = pCell->GetCellExtent(pDC); if (size.cy > nHeight) nHeight = size.cy; } m_arRowHeights[nRow] = nHeight; if (GetVirtualMode()) SendCacheHintToParent(CCellRange(-1,-1,-1,-1)); ReleaseDC(pDC); if (bResetScroll) ResetScrollBars(); return TRUE; } void CGridCtrl::AutoSizeColumns(UINT nAutoSizeStyle /*=GVS_DEFAULT*/) { int nNumColumns = GetColumnCount(); for (int nCol = 0; nCol < nNumColumns; nCol++) { // Skip hidden columns when autosizing if( GetColumnWidth( nCol) > 0 ) AutoSizeColumn(nCol, nAutoSizeStyle, FALSE); } ResetScrollBars(); } void CGridCtrl::AutoSizeRows() { int nNumRows = GetRowCount(); for (int nRow = 0; nRow < nNumRows; nRow++) { // Skip hidden rows when autosizing if( GetRowHeight( nRow) > 0 ) AutoSizeRow(nRow, FALSE); } ResetScrollBars(); } // sizes all rows and columns // faster than calling both AutoSizeColumns() and AutoSizeRows() void CGridCtrl::AutoSize(UINT nAutoSizeStyle /*=GVS_DEFAULT*/) { CDC* pDC = GetDC(); if (!pDC) return; int nNumColumns = GetColumnCount(); int nCol, nRow; ASSERT(GVS_DEFAULT <= nAutoSizeStyle && nAutoSizeStyle <= GVS_BOTH); if (nAutoSizeStyle == GVS_DEFAULT) nAutoSizeStyle = GetAutoSizeStyle(); int nStartRow = (nAutoSizeStyle & GVS_HEADER)? 0 : GetFixedRowCount(); int nEndRow = (nAutoSizeStyle & GVS_DATA)? GetRowCount()-1 : GetFixedRowCount()-1; if (GetVirtualMode()) SendCacheHintToParent(CCellRange(nStartRow, 0, nEndRow, nNumColumns)); // Row initialisation - only work on rows whose height is > 0 for (nRow = nStartRow; nRow <= nEndRow; nRow++) { if( GetRowHeight( nRow) > 0 ) m_arRowHeights[nRow] = 1; } CSize size; for (nCol = 0; nCol < nNumColumns; nCol++) { // Don't size hidden columns or rows if( GetColumnWidth( nCol) > 0 ) { // Skip columns that are hidden, but now initialize m_arColWidths[nCol] = 0; for (nRow = nStartRow; nRow <= nEndRow; nRow++) { if( GetRowHeight( nRow) > 0 ) { CGridCellBase* pCell = GetCell(nRow, nCol); if (pCell) size = pCell->GetCellExtent(pDC); if (size.cx >(int) m_arColWidths[nCol]) m_arColWidths[nCol] = size.cx; if (size.cy >(int) m_arRowHeights[nRow]) m_arRowHeights[nRow] = size.cy; } } } } if (GetVirtualMode()) SendCacheHintToParent(CCellRange(-1,-1,-1,-1)); ReleaseDC(pDC); ResetScrollBars(); Refresh(); } // Expands the columns to fit the screen space. If bExpandFixed is FALSE then fixed // columns will not be affected void CGridCtrl::ExpandColumnsToFit(BOOL bExpandFixed /*=TRUE*/) { if (bExpandFixed) { if (GetColumnCount() <= 0) return; } else { if (GetColumnCount() <= GetFixedColumnCount()) return; } EnableScrollBars(SB_HORZ, FALSE); int col; CRect rect; GetClientRect(rect); int nFirstColumn = (bExpandFixed)? 0 : GetFixedColumnCount(); int nNumColumnsAffected = 0; for (col = nFirstColumn; col < GetColumnCount(); col++) { if (m_arColWidths[col] > 0) nNumColumnsAffected++; } if (nNumColumnsAffected <= 0) return; long virtualWidth = GetVirtualWidth(); int nDifference = rect.Width() -(int) virtualWidth; int nColumnAdjustment = nDifference / nNumColumnsAffected; for (col = nFirstColumn; col < GetColumnCount(); col++) { if (m_arColWidths[col] > 0) m_arColWidths[col] += nColumnAdjustment; } if (nDifference > 0) { int leftOver = nDifference % nNumColumnsAffected; for (int nCount = 0, col = nFirstColumn; (col < GetColumnCount()) && (nCount < leftOver); col++, nCount++) { if (m_arColWidths[col] > 0) m_arColWidths[col] += 1; } } else { int leftOver = (-nDifference) % nNumColumnsAffected; for (int nCount = 0, col = nFirstColumn; (col < GetColumnCount()) && (nCount < leftOver); col++, nCount++) { if (m_arColWidths[col] > 0) m_arColWidths[col] -= 1; } } Refresh(); ResetScrollBars(); } void CGridCtrl::ExpandLastColumn() { if (GetColumnCount() <= 0) return; // Search for last non-hidden column int nLastColumn = GetColumnCount()-1; while (m_arColWidths[nLastColumn] <= 0) nLastColumn--; if (nLastColumn <= 0) return; EnableScrollBars(SB_HORZ, FALSE); CRect rect; GetClientRect(rect); long virtualWidth = GetVirtualWidth(); int nDifference = rect.Width() -(int) virtualWidth; if (nDifference > 0) { //if (GetVirtualHeight() > rect.Height()) // nDifference -= GetSystemMetrics(SM_CXVSCROLL); m_arColWidths[ nLastColumn ] += nDifference; Refresh(); } ResetScrollBars(); } // Expands the rows to fit the screen space. If bExpandFixed is FALSE then fixed // rows will not be affected void CGridCtrl::ExpandRowsToFit(BOOL bExpandFixed /*=TRUE*/) { if (bExpandFixed) { if (GetRowCount() <= 0) return; } else { if (GetRowCount() <= GetFixedRowCount()) return; } EnableScrollBars(SB_VERT, FALSE); int row; CRect rect; GetClientRect(rect); int nFirstRow = (bExpandFixed)? 0 : GetFixedRowCount(); int nNumRowsAffected = 0; for (row = nFirstRow; row < GetRowCount(); row++) { if (m_arRowHeights[row] > 0) nNumRowsAffected++; } if (nNumRowsAffected <= 0) return; long virtualHeight = GetVirtualHeight(); int nDifference = rect.Height() -(int) virtualHeight; int nRowAdjustment = nDifference / nNumRowsAffected; for (row = nFirstRow; row < GetRowCount(); row++) { if (m_arRowHeights[row] > 0) m_arRowHeights[row] += nRowAdjustment; } if (nDifference > 0) { int leftOver = nDifference % nNumRowsAffected; for (int nCount = 0, row = nFirstRow; (row < GetRowCount()) && (nCount < leftOver); row++, nCount++) { if (m_arRowHeights[row] > 0) m_arRowHeights[row] += 1; } } else { int leftOver = (-nDifference) % nNumRowsAffected; for (int nCount = 0, row = nFirstRow; (row < GetRowCount()) && (nCount < leftOver); row++, nCount++) { if (m_arRowHeights[row] > 0) m_arRowHeights[row] -= 1; } } Refresh(); ResetScrollBars(); } // Expands the cells to fit the screen space. If bExpandFixed is FALSE then fixed // cells will not be affected void CGridCtrl::ExpandToFit(BOOL bExpandFixed /*=TRUE*/) { ExpandColumnsToFit(bExpandFixed); // This will remove any existing horz scrollbar ExpandRowsToFit(bExpandFixed); // This will remove any existing vert scrollbar ExpandColumnsToFit(bExpandFixed); // Just in case the first adjustment was with a vert // scrollbar in place Refresh(); } ///////////////////////////////////////////////////////////////////////////////////// // Attributes void CGridCtrl::SetVirtualMode(BOOL bVirtual) { DeleteAllItems(); m_bVirtualMode = bVirtual; // Force some defaults here. if (m_bVirtualMode) { SetEditable(FALSE); SetAutoSizeStyle(GVS_HEADER); SetFixedColumnSelection(FALSE); SetFixedRowSelection(FALSE); ResetVirtualOrder(); } } void CGridCtrl::SetGridLines(int nWhichLines /*=GVL_BOTH*/) { m_nGridLines = nWhichLines; Refresh(); } void CGridCtrl::SetListMode(BOOL bEnableListMode /*=TRUE*/) { ResetSelectedRange(); SetSortColumn(-1); m_bListMode = bEnableListMode; SetFixedRowSelection(FALSE); Refresh(); } void CGridCtrl::SetSortColumn(int nCol) { if (m_nSortColumn >= 0) InvalidateCellRect(0, m_nSortColumn); m_nSortColumn = nCol; if (nCol >= 0) InvalidateCellRect(0, nCol); } BOOL CGridCtrl::IsCellFixed(int nRow, int nCol) { return (nRow < GetFixedRowCount() || nCol < GetFixedColumnCount()); } void CGridCtrl::SetModified(BOOL bModified /*=TRUE*/, int nRow /*=-1*/, int nCol /*=-1*/) { // Cannot guarantee sorting anymore... if (nCol < 0 || nCol == GetSortColumn()) SetSortColumn(-1); if (nRow >= 0 && nCol >= 0) { if (bModified) { SetItemState(nRow, nCol, GetItemState(nRow, nCol) | GVIS_MODIFIED); m_bModified = TRUE; } else SetItemState(nRow, nCol, GetItemState(nRow, nCol) & ~GVIS_MODIFIED); } else m_bModified = bModified; if (!m_bModified) { for (int row = 0; row < GetRowCount(); row++) for (int col = 0; col < GetColumnCount(); col++) SetItemState(row, col, GetItemState(row, col) & ~GVIS_MODIFIED); } } BOOL CGridCtrl::GetModified(int nRow /*=-1*/, int nCol /*=-1*/) { if (nRow >= 0 && nCol >= 0) return ( (GetItemState(nRow, nCol) & GVIS_MODIFIED) == GVIS_MODIFIED ); else return m_bModified; } ///////////////////////////////////////////////////////////////////////////////////// // GridCtrl cell visibility tests and invalidation/redraw functions void CGridCtrl::Refresh() { if (GetSafeHwnd() && m_bAllowDraw) Invalidate(); } // EnsureVisible supplied by Roelf Werkman void CGridCtrl::EnsureVisible(int nRow, int nCol) { if (!m_bAllowDraw) return; CRect rectWindow; /* // set the scroll to the approximate position of row (Nigel Page-Jones) int nPos = (int)((float)nRow / GetRowCount() * 1000); float fPos = (float)nPos / 1000; SCROLLINFO scrollInfo; GetScrollInfo(SB_VERT, &scrollInfo); scrollInfo.nPos = (int)(scrollInfo.nMax * fPos); SetScrollInfo(SB_VERT, &scrollInfo, FALSE); GetClientRect(rectWindow); // redraw cells if necessary (Nigel Page-Jones) CCellID idTopLeft = GetTopleftNonFixedCell(FALSE); CCellID idNewTopLeft = GetTopleftNonFixedCell(TRUE); if (idNewTopLeft != idTopLeft) { rectWindow.top = GetFixedRowHeight(); InvalidateRect(rectWindow); } */ // We are going to send some scroll messages, which will steal the focus // from it's rightful owner. Squirrel it away ourselves so we can give // it back. (Damir) CWnd* pFocusWnd = GetFocus(); CCellRange VisibleCells = GetVisibleNonFixedCellRange(); int right = nCol - VisibleCells.GetMaxCol(); int left = VisibleCells.GetMinCol() - nCol; int down = nRow - VisibleCells.GetMaxRow(); int up = VisibleCells.GetMinRow() - nRow; int iColumnStart; int iRowStart; iColumnStart = VisibleCells.GetMaxCol() + 1; while( right > 0 ) { if( GetColumnWidth( iColumnStart ) > 0 ) SendMessage( WM_HSCROLL, SB_LINERIGHT, 0 ); right--; iColumnStart++; } iColumnStart = VisibleCells.GetMinCol() - 1; while( left > 0 ) { if( GetColumnWidth( iColumnStart ) > 0 ) SendMessage( WM_HSCROLL, SB_LINELEFT, 0 ); left--; iColumnStart--; } iRowStart = VisibleCells.GetMaxRow() + 1; while( down > 0 ) { if( GetRowHeight( iRowStart ) > 0 ) SendMessage( WM_VSCROLL, SB_LINEDOWN, 0 ); down--; iRowStart++; } iRowStart = VisibleCells.GetMinRow() - 1; while( up > 0 ) { if( GetRowHeight( iRowStart ) > 0 ) SendMessage( WM_VSCROLL, SB_LINEUP, 0 ); up--; iRowStart--; } // Move one more if we only see a snall bit of the cell CRect rectCell; if (!GetCellRect(nRow, nCol, rectCell)) { if (pFocusWnd && ::IsWindow(pFocusWnd->GetSafeHwnd())) pFocusWnd->SetFocus(); return; } GetClientRect(rectWindow); // The previous fix was fixed properly by Martin Richter while (rectCell.right > rectWindow.right && rectCell.left > GetFixedColumnWidth() && IsVisibleHScroll() // Junlin Xu: added to prevent infinite loop ) { SendMessage(WM_HSCROLL, SB_LINERIGHT, 0); if (!GetCellRect(nRow, nCol, rectCell)) { pFocusWnd->SetFocus(); return; } } while (rectCell.bottom > rectWindow.bottom && rectCell.top > GetFixedRowHeight() && IsVisibleVScroll() // Junlin Xu: added to prevent infinite loop ) { SendMessage(WM_VSCROLL, SB_LINEDOWN, 0); if (!GetCellRect(nRow, nCol, rectCell)) { pFocusWnd->SetFocus(); return; } } // restore focus to whoever owned it pFocusWnd->SetFocus(); } BOOL CGridCtrl::IsCellEditable(CCellID &cell) const { return IsCellEditable(cell.row, cell.col); } BOOL CGridCtrl::IsCellEditable(int nRow, int nCol) const { return IsEditable() && ((GetItemState(nRow, nCol) & GVIS_READONLY) != GVIS_READONLY); } BOOL CGridCtrl::IsCellSelected(CCellID &cell) const { return IsCellSelected(cell.row, cell.col); } BOOL CGridCtrl::IsCellSelected(int nRow, int nCol) const { if (GetVirtualMode()) { if (!IsSelectable()) return FALSE; CCellID cell; DWORD key = MAKELONG(nRow, nCol); return (m_SelectedCellMap.Lookup(key, (CCellID&)cell)); } else return IsSelectable() && ((GetItemState(nRow, nCol) & GVIS_SELECTED) == GVIS_SELECTED); } BOOL CGridCtrl::IsCellVisible(CCellID cell) { return IsCellVisible(cell.row, cell.col); } BOOL CGridCtrl::IsCellVisible(int nRow, int nCol) { if (!IsWindow(m_hWnd)) return FALSE; int x, y; CCellID TopLeft; if (nCol >= GetFixedColumnCount() || nRow >= GetFixedRowCount()) { TopLeft = GetTopleftNonFixedCell(); if (nCol >= GetFixedColumnCount() && nCol < TopLeft.col) return FALSE; if (nRow >= GetFixedRowCount() && nRow < TopLeft.row) return FALSE; } CRect rect; GetClientRect(rect); if (nCol < GetFixedColumnCount()) { x = 0; for (int i = 0; i <= nCol; i++) { if (x >= rect.right) return FALSE; x += GetColumnWidth(i); } } else { x = GetFixedColumnWidth(); for (int i = TopLeft.col; i <= nCol; i++) { if (x >= rect.right) return FALSE; x += GetColumnWidth(i); } } if (nRow < GetFixedRowCount()) { y = 0; for (int i = 0; i <= nRow; i++) { if (y >= rect.bottom) return FALSE; y += GetRowHeight(i); } } else { if (nRow < TopLeft.row) return FALSE; y = GetFixedRowHeight(); for (int i = TopLeft.row; i <= nRow; i++) { if (y >= rect.bottom) return FALSE; y += GetRowHeight(i); } } return TRUE; } BOOL CGridCtrl::InvalidateCellRect(const CCellID& cell) { return InvalidateCellRect(cell.row, cell.col); } BOOL CGridCtrl::InvalidateCellRect(const int row, const int col) { if (!::IsWindow(GetSafeHwnd()) || !m_bAllowDraw) return FALSE; if (!IsValid(row, col)) return FALSE; if (!IsCellVisible(row, col)) return FALSE; CRect rect; if (!GetCellRect(row, col, rect)) return FALSE; rect.right++; rect.bottom++; InvalidateRect(rect, TRUE); return TRUE; } BOOL CGridCtrl::InvalidateCellRect(const CCellRange& cellRange) { ASSERT(IsValid(cellRange)); if (!::IsWindow(GetSafeHwnd()) || !m_bAllowDraw) return FALSE; CCellRange visibleCellRange = GetVisibleNonFixedCellRange().Intersect(cellRange); CRect rect; if (!GetCellRangeRect(visibleCellRange, rect)) return FALSE; rect.right++; rect.bottom++; InvalidateRect(rect, TRUE); return TRUE; } ///////////////////////////////////////////////////////////////////////////// // CGridCtrl Mouse stuff // Handles mouse wheel notifications // Note - if this doesn't work for win95 then use OnRegisteredMouseWheel instead #if !defined(_WIN32_WCE) && (_MFC_VER >= 0x0421) BOOL CGridCtrl::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt) { // A m_nRowsPerWheelNotch value less than 0 indicates that the mouse // wheel scrolls whole pages, not just lines. if (m_nRowsPerWheelNotch == -1) { int nPagesScrolled = zDelta / 120; if (nPagesScrolled > 0) { for (int i = 0; i < nPagesScrolled; i++) { PostMessage(WM_VSCROLL, SB_PAGEUP, 0); } } else { for (int i = 0; i > nPagesScrolled; i--) { PostMessage(WM_VSCROLL, SB_PAGEDOWN, 0); } } } else { int nRowsScrolled = m_nRowsPerWheelNotch * zDelta / 120; if (nRowsScrolled > 0) { for (int i = 0; i < nRowsScrolled; i++) { PostMessage(WM_VSCROLL, SB_LINEUP, 0); } } else { for (int i = 0; i > nRowsScrolled; i--) { PostMessage(WM_VSCROLL, SB_LINEDOWN, 0); } } } return CWnd::OnMouseWheel(nFlags, zDelta, pt); } #endif // !defined(_WIN32_WCE) && (_MFC_VER >= 0x0421) void CGridCtrl::OnMouseMove(UINT /*nFlags*/, CPoint point) { CRect rect; GetClientRect(rect); #ifndef GRIDCONTROL_NO_DRAGDROP // If outside client area, return (unless we are drag n dropping) if (m_MouseMode != MOUSE_DRAGGING && !rect.PtInRect(point)) return; #endif // Sometimes a MOUSEMOVE message can come after the left buttons // has been let go, but before the BUTTONUP message hs been processed. // We'll keep track of mouse buttons manually to avoid this. // All bMouseButtonDown's have been replaced with the member m_bLMouseButtonDown // BOOL bMouseButtonDown = ((nFlags & MK_LBUTTON) == MK_LBUTTON); // If the left mouse button is up, then test to see if row/column sizing is imminent if (!m_bLMouseButtonDown || (m_bLMouseButtonDown && m_MouseMode == MOUSE_NOTHING)) { if (m_bAllowColumnResize && MouseOverColumnResizeArea(point)) { if (m_MouseMode != MOUSE_OVER_COL_DIVIDE) { #ifndef _WIN32_WCE_NO_CURSOR SetCursor(AfxGetApp()->LoadStandardCursor(IDC_SIZEWE)); #endif m_MouseMode = MOUSE_OVER_COL_DIVIDE; } } else if (m_bAllowRowResize && MouseOverRowResizeArea(point)) { if (m_MouseMode != MOUSE_OVER_ROW_DIVIDE) { #ifndef _WIN32_WCE_NO_CURSOR SetCursor(AfxGetApp()->LoadStandardCursor(IDC_SIZENS)); #endif m_MouseMode = MOUSE_OVER_ROW_DIVIDE; } } else if (m_MouseMode != MOUSE_NOTHING) { #ifndef _WIN32_WCE_NO_CURSOR SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW)); #endif m_MouseMode = MOUSE_NOTHING; } if (m_MouseMode == MOUSE_NOTHING) { CGridCellBase* pCell = NULL; CCellID idCurrentCell; if (!GetVirtualMode() || m_bTitleTips) { // Let the cell know that a big fat cursor is currently hovering // over it. idCurrentCell = GetCellFromPt(point); pCell = GetCell(idCurrentCell.row, idCurrentCell.col); if (pCell) pCell->OnMouseOver(); } #ifndef GRIDCONTROL_NO_TITLETIPS // Titletips anyone? anyone? if (m_bTitleTips) { CRect TextRect, CellRect; if (pCell) { LPCTSTR szTipText = pCell->GetTipText(); if (!m_bRMouseButtonDown && szTipText && szTipText[0] && !pCell->IsEditing() && GetCellRect( idCurrentCell.row, idCurrentCell.col, &TextRect) && pCell->GetTipTextRect( &TextRect) && GetCellRect(idCurrentCell.row, idCurrentCell.col, CellRect) ) { // TRACE0("Showing TitleTip\n"); m_TitleTip.Show(TextRect, pCell->GetTipText(), 0, CellRect, pCell->GetFont(), GetTitleTipTextClr(), GetTitleTipBackClr()); } } } #endif } m_LastMousePoint = point; return; } if (!IsValid(m_LeftClickDownCell)) { m_LastMousePoint = point; return; } // If the left mouse button is down, then process appropriately if (m_bLMouseButtonDown) { switch (m_MouseMode) { case MOUSE_SELECT_ALL: break; case MOUSE_SELECT_COL: case MOUSE_SELECT_ROW: case MOUSE_SELECT_CELLS: { CCellID idCurrentCell = GetCellFromPt(point); if (!IsValid(idCurrentCell)) return; if (idCurrentCell != GetFocusCell()) { OnSelecting(idCurrentCell); // EFW - BUG FIX - Keep the appropriate cell row and/or // column focused. A fix in SetFocusCell() will place // the cursor in a non-fixed cell as needed. if((idCurrentCell.row >= m_nFixedRows && idCurrentCell.col >= m_nFixedCols) || m_MouseMode==MOUSE_SELECT_COL || m_MouseMode==MOUSE_SELECT_ROW) { SetFocusCell(idCurrentCell); } } break; } case MOUSE_SIZING_COL: { CDC* pDC = GetDC(); if (!pDC) break; CRect oldInvertedRect(m_LastMousePoint.x, rect.top, m_LastMousePoint.x + 2, rect.bottom); pDC->InvertRect(&oldInvertedRect); CRect newInvertedRect(point.x, rect.top, point.x + 2, rect.bottom); pDC->InvertRect(&newInvertedRect); ReleaseDC(pDC); } break; case MOUSE_SIZING_ROW: { CDC* pDC = GetDC(); if (!pDC) break; CRect oldInvertedRect(rect.left, m_LastMousePoint.y, rect.right, m_LastMousePoint.y + 2); pDC->InvertRect(&oldInvertedRect); CRect newInvertedRect(rect.left, point.y, rect.right, point.y + 2); pDC->InvertRect(&newInvertedRect); ReleaseDC(pDC); } break; #ifndef GRIDCONTROL_NO_DRAGDROP case MOUSE_PREPARE_EDIT: case MOUSE_PREPARE_DRAG: m_MouseMode = MOUSE_PREPARE_DRAG; OnBeginDrag(); break; #endif } } m_LastMousePoint = point; } // Returns the point inside the cell that was clicked (coords relative to cell top left) CPoint CGridCtrl::GetPointClicked(int nRow, int nCol, const CPoint& point) { CPoint PointCellOrigin; if( !GetCellOrigin( nRow, nCol, &PointCellOrigin) ) return CPoint( 0, 0); CPoint PointClickedCellRelative( point); PointClickedCellRelative -= PointCellOrigin; return PointClickedCellRelative; } void CGridCtrl::OnLButtonDblClk(UINT nFlags, CPoint point) { TRACE0("CGridCtrl::OnLButtonDblClk\n"); CCellID cell = GetCellFromPt(point); if( !IsValid( cell) ) { //ASSERT(FALSE); return; } #ifdef _WIN32_WCE if (MouseOverColumnResizeArea(point)) #else if (m_MouseMode == MOUSE_OVER_COL_DIVIDE) #endif { CPoint start; if (!GetCellOrigin(0, cell.col, &start)) return; if (point.x - start.x < m_nResizeCaptureRange) // Clicked right of border cell.col--; // ignore columns that are hidden and look left towards first visible column BOOL bFoundVisible = FALSE; while( cell.col >= 0) { if( GetColumnWidth( cell.col) > 0) { bFoundVisible = TRUE; break; } cell.col--; } if( !bFoundVisible) return; AutoSizeColumn(cell.col, GetAutoSizeStyle()); Invalidate(); } #ifdef _WIN32_WCE else if (MouseOverRowResizeArea(point)) #else else if (m_MouseMode == MOUSE_OVER_ROW_DIVIDE) #endif { CPoint start; if (!GetCellOrigin(0, cell.col, &start)) return; if (point.y - start.y < m_nResizeCaptureRange) // Clicked below border cell.row--; // ignore rows that are hidden and look up towards first visible row BOOL bFoundVisible = FALSE; while( cell.row >= 0) { if( GetRowHeight( cell.row) > 0) { bFoundVisible = TRUE; break; } cell.row--; } if( !bFoundVisible) return; AutoSizeRow(cell.row); Invalidate(); } else if (m_MouseMode == MOUSE_NOTHING) { CPoint pointClickedRel; pointClickedRel = GetPointClicked( cell.row, cell.col, point); CGridCellBase* pCell = NULL; if (IsValid(cell)) pCell = GetCell(cell.row, cell.col); // Clicked in the text area? Only then will cell selection work BOOL bInTextArea = FALSE; if (pCell) { CRect rectCell; if (GetCellRect(cell.row, cell.col, rectCell) && pCell->GetTextRect(rectCell)) bInTextArea = rectCell.PtInRect(point); } if (cell.row >= m_nFixedRows && IsValid(m_LeftClickDownCell) && cell.col >= m_nFixedCols && bInTextArea) { OnEditCell(cell.row, cell.col, pointClickedRel, VK_LBUTTON); } else if (m_bListMode) { if (!IsValid(cell)) return; if (cell.row >= m_nFixedRows && cell.col >= m_nFixedCols && bInTextArea) OnEditCell(cell.row, cell.col, pointClickedRel, VK_LBUTTON); } if (IsValid(cell)) { CGridCellBase* pCell = GetCell(cell.row, cell.col); if (pCell) pCell->OnDblClick(pointClickedRel); SendMessageToParent(cell.row, cell.col, NM_DBLCLK); } } CWnd::OnLButtonDblClk(nFlags, point); } void CGridCtrl::OnLButtonDown(UINT nFlags, CPoint point) { #ifdef GRIDCONTROL_USE_TITLETIPS // EFW - Bug Fix m_TitleTip.Hide(); // hide any titletips #endif // TRACE0("CGridCtrl::OnLButtonDown\n"); // CWnd::OnLButtonDown(nFlags, point); SetFocus(); m_CurCol = -1; m_bLMouseButtonDown = TRUE; m_LeftClickDownPoint = point; m_LeftClickDownCell = GetCellFromPt(point); if (!IsValid(m_LeftClickDownCell)) return; m_CurRow = m_LeftClickDownCell.row; // If the SHIFT key is not down, then the start of the selection area should be the // cell just clicked. Otherwise, keep the previous selection-start-cell so the user // can add to their previous cell selections in an intuitive way. If no selection- // start-cell has been specified, then set it's value here and now. if ((nFlags & MK_SHIFT) != MK_SHIFT) m_SelectionStartCell = m_LeftClickDownCell; else { if (!IsValid(m_SelectionStartCell)) m_SelectionStartCell = m_idCurrentCell; } EndEditing(); // tell the cell about it CGridCellBase* pCell = GetCell(m_LeftClickDownCell.row, m_LeftClickDownCell.col); if (pCell) pCell->OnClickDown(GetPointClicked( m_LeftClickDownCell.row, m_LeftClickDownCell.col, point)); // Clicked in the text area? Only then will cell selection work BOOL bInTextArea = FALSE; if (pCell) { CRect rectCell; if (GetCellRect(m_LeftClickDownCell.row, m_LeftClickDownCell.col, rectCell) && pCell->GetTextRect(rectCell)) { bInTextArea = rectCell.PtInRect(point); } } // If the user clicks on the current cell, then prepare to edit it. // (If the user moves the mouse, then dragging occurs) if (m_LeftClickDownCell == m_idCurrentCell && !(nFlags & MK_CONTROL) && bInTextArea && IsCellEditable(m_LeftClickDownCell)) { m_MouseMode = MOUSE_PREPARE_EDIT; return; } // If the user clicks on a selected cell, then prepare to drag it. // (If the user moves the mouse, then dragging occurs) else if (IsCellSelected(m_LeftClickDownCell)) { SetFocusCell(m_LeftClickDownCell.row, m_LeftClickDownCell.col); // If control is pressed then unselect the cell or row (depending on the list mode) if (nFlags & MK_CONTROL) { SetFocusCell(m_LeftClickDownCell); if (GetListMode()) SelectRows(m_LeftClickDownCell, TRUE, FALSE); else SelectCells(m_LeftClickDownCell, TRUE, FALSE); return; } #ifndef GRIDCONTROL_NO_DRAGDROP else if (m_bAllowDragAndDrop) m_MouseMode = MOUSE_PREPARE_DRAG; #endif } else if (m_MouseMode != MOUSE_OVER_COL_DIVIDE && m_MouseMode != MOUSE_OVER_ROW_DIVIDE) { if (m_LeftClickDownCell.row >= GetFixedRowCount() && m_LeftClickDownCell.col >= GetFixedColumnCount()) { SetFocusCell(m_LeftClickDownCell.row, m_LeftClickDownCell.col); } else SetFocusCell(-1, -1); //Don't set focus on any cell if the user clicked on a fixed cell - David Pritchard //if (GetRowCount() > GetFixedRowCount() && // GetColumnCount() > GetFixedColumnCount()) // SetFocusCell(max(m_LeftClickDownCell.row, m_nFixedRows), // max(m_LeftClickDownCell.col, m_nFixedCols)); } SetCapture(); if (m_MouseMode == MOUSE_NOTHING) { if (m_bAllowColumnResize && MouseOverColumnResizeArea(point)) { if (m_MouseMode != MOUSE_OVER_COL_DIVIDE) { #ifndef _WIN32_WCE_NO_CURSOR SetCursor(AfxGetApp()->LoadStandardCursor(IDC_SIZEWE)); #endif m_MouseMode = MOUSE_OVER_COL_DIVIDE; } } else if (m_bAllowRowResize && MouseOverRowResizeArea(point)) { if (m_MouseMode != MOUSE_OVER_ROW_DIVIDE) { #ifndef _WIN32_WCE_NO_CURSOR SetCursor(AfxGetApp()->LoadStandardCursor(IDC_SIZENS)); #endif m_MouseMode = MOUSE_OVER_ROW_DIVIDE; } } // else if (m_MouseMode != MOUSE_NOTHING) //{ // SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW)); // m_MouseMode = MOUSE_NOTHING; //} } if (m_MouseMode == MOUSE_OVER_COL_DIVIDE) // sizing column { m_MouseMode = MOUSE_SIZING_COL; // Kludge for if we are over the last column... if (GetColumnWidth(GetColumnCount()-1) < m_nResizeCaptureRange) { CRect VisRect; GetVisibleNonFixedCellRange(VisRect); if (abs(point.x - VisRect.right) < m_nResizeCaptureRange) m_LeftClickDownCell.col = GetColumnCount()-1; } CPoint start; if (!GetCellOrigin(0, m_LeftClickDownCell.col, &start)) return; if( !m_bHiddenColUnhide) { // ignore columns that are hidden and look left towards first visible column BOOL bLookForVisible = TRUE; BOOL bIsCellRightBorder = point.x - start.x >= m_nResizeCaptureRange; if( bIsCellRightBorder && m_LeftClickDownCell.col + 1 >= GetColumnCount() ) { // clicked on last column's right border // if last column is visible, don't do anything if( m_LeftClickDownCell.col >= 0) bLookForVisible = FALSE; } if( bLookForVisible) { // clicked on column divider other than last right border BOOL bFoundVisible = FALSE; int iOffset = 1; if( bIsCellRightBorder) iOffset = 0; while( m_LeftClickDownCell.col - iOffset >= 0) { if( GetColumnWidth( m_LeftClickDownCell.col - iOffset) > 0) { bFoundVisible = TRUE; break; } m_LeftClickDownCell.col--; } if( !bFoundVisible) return; } } CRect rect; GetClientRect(rect); CRect invertedRect(point.x, rect.top, point.x + 2, rect.bottom); CDC* pDC = GetDC(); if (pDC) { pDC->InvertRect(&invertedRect); ReleaseDC(pDC); } // If we clicked to the right of the colimn divide, then reset the click-down cell // as the cell to the left of the column divide - UNLESS we clicked on the last column // and the last column is teensy (kludge fix) if (point.x - start.x < m_nResizeCaptureRange) { if (m_LeftClickDownCell.col < GetColumnCount()-1 || GetColumnWidth(GetColumnCount()-1) >= m_nResizeCaptureRange) { if (!GetCellOrigin(0, --m_LeftClickDownCell.col, &start)) return; } } // Allow a cell resize width no greater than that which can be viewed within // the grid itself int nMaxCellWidth = rect.Width()-GetFixedColumnWidth(); rect.left = start.x + 1; rect.right = rect.left + nMaxCellWidth; ClientToScreen(rect); #ifndef _WIN32_WCE_NO_CURSOR ClipCursor(rect); #endif } else if (m_MouseMode == MOUSE_OVER_ROW_DIVIDE) // sizing row { m_MouseMode = MOUSE_SIZING_ROW; // Kludge for if we are over the last column... if (GetRowHeight(GetRowCount()-1) < m_nResizeCaptureRange) { CRect VisRect; GetVisibleNonFixedCellRange(VisRect); if (abs(point.y - VisRect.bottom) < m_nResizeCaptureRange) m_LeftClickDownCell.row = GetRowCount()-1; } CPoint start; if (!GetCellOrigin(m_LeftClickDownCell, &start)) return; if( !m_bHiddenRowUnhide) { // ignore rows that are hidden and look up towards first visible row BOOL bLookForVisible = TRUE; BOOL bIsCellBottomBorder = point.y - start.y >= m_nResizeCaptureRange; if( bIsCellBottomBorder && m_LeftClickDownCell.row + 1 >= GetRowCount() ) { // clicked on last row's bottom border // if last row is visible, don't do anything if( m_LeftClickDownCell.row >= 0) bLookForVisible = FALSE; } if( bLookForVisible) { // clicked on row divider other than last bottom border BOOL bFoundVisible = FALSE; int iOffset = 1; if( bIsCellBottomBorder) iOffset = 0; while( m_LeftClickDownCell.row - iOffset >= 0) { if( GetRowHeight( m_LeftClickDownCell.row - iOffset) > 0) { bFoundVisible = TRUE; break; } m_LeftClickDownCell.row--; } if( !bFoundVisible) return; } } CRect rect; GetClientRect(rect); CRect invertedRect(rect.left, point.y, rect.right, point.y + 2); CDC* pDC = GetDC(); if (pDC) { pDC->InvertRect(&invertedRect); ReleaseDC(pDC); } // If we clicked below the row divide, then reset the click-down cell // as the cell above the row divide - UNLESS we clicked on the last row // and the last row is teensy (kludge fix) if (point.y - start.y < m_nResizeCaptureRange) // clicked below border { if (m_LeftClickDownCell.row < GetRowCount()-1 || GetRowHeight(GetRowCount()-1) >= m_nResizeCaptureRange) { if (!GetCellOrigin(--m_LeftClickDownCell.row, 0, &start)) return; } } int nMaxCellHeight = rect.Height()-GetFixedRowHeight(); rect.top = start.y + 1; rect.bottom = rect.top + nMaxCellHeight; ClientToScreen(rect); #ifndef _WIN32_WCE_NO_CURSOR ClipCursor(rect); #endif } else #ifndef GRIDCONTROL_NO_DRAGDROP if (m_MouseMode != MOUSE_PREPARE_DRAG) // not sizing or editing -- selecting #endif { SendMessageToParent(m_LeftClickDownCell.row, m_LeftClickDownCell.col, GVN_SELCHANGING); // If Ctrl pressed, save the current cell selection. This will get added // to the new cell selection at the end of the cell selection process m_PrevSelectedCellMap.RemoveAll(); if (nFlags & MK_CONTROL) { for (POSITION pos = m_SelectedCellMap.GetStartPosition(); pos != NULL; ) { DWORD key; CCellID cell; m_SelectedCellMap.GetNextAssoc(pos, key, (CCellID&)cell); m_PrevSelectedCellMap.SetAt(key, cell); } } if (m_LeftClickDownCell.row < GetFixedRowCount()) { OnFixedRowClick(m_LeftClickDownCell); if(m_AllowReorderColumn && m_LeftClickDownCell.col >= GetFixedColumnCount()) { ResetSelectedRange(); // TODO : This is not the better solution, as we do not see why clicking in column header should reset selection //but the state of selection is instable after drag (at least until someone debugs it), so better clear it allways. m_MouseMode = MOUSE_PREPARE_DRAG; m_CurCol = m_LeftClickDownCell.col; } } else if (m_LeftClickDownCell.col < GetFixedColumnCount()) OnFixedColumnClick(m_LeftClickDownCell); else { m_MouseMode = m_bListMode? MOUSE_SELECT_ROW : MOUSE_SELECT_CELLS; OnSelecting(m_LeftClickDownCell); m_nTimerID = SetTimer(WM_LBUTTONDOWN, m_nTimerInterval, 0); } } m_LastMousePoint = point; } void CGridCtrl::OnLButtonUp(UINT nFlags, CPoint point) { // TRACE0("CGridCtrl::OnLButtonUp\n"); CWnd::OnLButtonUp(nFlags, point); m_bLMouseButtonDown = FALSE; #ifndef _WIN32_WCE_NO_CURSOR ClipCursor(NULL); #endif if (GetCapture()->GetSafeHwnd() == GetSafeHwnd()) { ReleaseCapture(); KillTimer(m_nTimerID); m_nTimerID = 0; } CPoint pointClickedRel; pointClickedRel = GetPointClicked( m_idCurrentCell.row, m_idCurrentCell.col, point); // m_MouseMode == MOUSE_PREPARE_EDIT only if user clicked down on current cell // and then didn't move mouse before clicking up (releasing button) if (m_MouseMode == MOUSE_PREPARE_EDIT) { OnEditCell(m_idCurrentCell.row, m_idCurrentCell.col, pointClickedRel, VK_LBUTTON); } #ifndef GRIDCONTROL_NO_DRAGDROP // m_MouseMode == MOUSE_PREPARE_DRAG only if user clicked down on a selected cell // and then didn't move mouse before clicking up (releasing button) else if (m_MouseMode == MOUSE_PREPARE_DRAG) { CGridCellBase* pCell = GetCell(m_idCurrentCell.row, m_idCurrentCell.col); if (pCell) pCell->OnClick( GetPointClicked( m_idCurrentCell.row, m_idCurrentCell.col, point) ); SendMessageToParent(m_LeftClickDownCell.row, m_LeftClickDownCell.col, NM_CLICK); SendMessageToParent(m_LeftClickDownCell.row, m_LeftClickDownCell.col, GVN_SELCHANGING); ResetSelectedRange(); SendMessageToParent(m_idCurrentCell.row, m_idCurrentCell.col, GVN_SELCHANGED); } #endif else if (m_MouseMode == MOUSE_SIZING_COL) { CRect rect; GetClientRect(rect); CRect invertedRect(m_LastMousePoint.x, rect.top, m_LastMousePoint.x + 2, rect.bottom); CDC* pDC = GetDC(); if (pDC) { pDC->InvertRect(&invertedRect); ReleaseDC(pDC); } if (m_LeftClickDownPoint != point && (point.x != 0 || point.y != 0)) // 0 pt fix by email1@bierling.net { CPoint start; if (!GetCellOrigin(m_LeftClickDownCell, &start)) return; int nColumnWidth = __max(point.x - start.x, m_bAllowColHide? 0 : 1); SetColumnWidth(m_LeftClickDownCell.col, nColumnWidth); ResetScrollBars(); Invalidate(); } } else if (m_MouseMode == MOUSE_SIZING_ROW) { CRect rect; GetClientRect(rect); CRect invertedRect(rect.left, m_LastMousePoint.y, rect.right, m_LastMousePoint.y + 2); CDC* pDC = GetDC(); if (pDC) { pDC->InvertRect(&invertedRect); ReleaseDC(pDC); } if (m_LeftClickDownPoint != point && (point.x != 0 || point.y != 0)) // 0 pt fix by email1@bierling.net { CPoint start; if (!GetCellOrigin(m_LeftClickDownCell, &start)) return; int nRowHeight = __max(point.y - start.y, m_bAllowRowHide? 0 : 1); SetRowHeight(m_LeftClickDownCell.row, nRowHeight); ResetScrollBars(); Invalidate(); } } else { SendMessageToParent(m_idCurrentCell.row, m_idCurrentCell.col, GVN_SELCHANGED); CGridCellBase* pCell = GetCell(m_idCurrentCell.row, m_idCurrentCell.col); if (pCell) pCell->OnClick( GetPointClicked( m_idCurrentCell.row, m_idCurrentCell.col, point) ); SendMessageToParent(m_LeftClickDownCell.row, m_LeftClickDownCell.col, NM_CLICK); } m_MouseMode = MOUSE_NOTHING; #ifndef _WIN32_WCE_NO_CURSOR SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW)); #endif if (!IsValid(m_LeftClickDownCell)) return; CWnd *pOwner = GetOwner(); if (pOwner && IsWindow(pOwner->m_hWnd)) pOwner->PostMessage(WM_COMMAND, MAKELONG(GetDlgCtrlID(), BN_CLICKED), (LPARAM) GetSafeHwnd()); } #ifndef _WIN32_WCE void CGridCtrl::OnRButtonDown(UINT nFlags, CPoint point) { CWnd::OnRButtonDown(nFlags, point); m_bRMouseButtonDown = TRUE; #ifdef GRIDCONTROL_USE_TITLETIPS TRACE0("Hiding TitleTip\n"); m_TitleTip.Hide(); // hide any titletips #endif } // EFW - Added to forward right click to parent so that a context // menu can be shown without deriving a new grid class. void CGridCtrl::OnRButtonUp(UINT nFlags, CPoint point) { CWnd::OnRButtonUp(nFlags, point); m_bRMouseButtonDown = FALSE; CCellID FocusCell; FocusCell = GetCellFromPt(point); EndEditing(); // Auto-destroy any InPlaceEdit's // If not a valid cell, pass -1 for row and column if(!IsValid(FocusCell)) SendMessageToParent(-1, -1, NM_RCLICK); else { SetFocusCell(-1,-1); SetFocusCell(__max(FocusCell.row, m_nFixedRows), __max(FocusCell.col, m_nFixedCols)); // tell the cell about it CGridCellBase* pCell = GetCell(FocusCell.row, FocusCell.col); if (pCell) pCell->OnRClick( GetPointClicked( FocusCell.row, FocusCell.col, point) ); SendMessageToParent(FocusCell.row, FocusCell.col, NM_RCLICK); } } #endif #if !defined(_WIN32_WCE_NO_PRINTING) && !defined(GRIDCONTROL_NO_PRINTING) ///////////////////////////////////////////////////////////////////////////// // CGridCtrl printing // EFW - New print margin support functions void CGridCtrl::SetPrintMarginInfo(int nHeaderHeight, int nFooterHeight, int nLeftMargin, int nRightMargin, int nTopMargin, int nBottomMargin, int nGap) { // If any parameter is -1, keep the existing setting if(nHeaderHeight > -1) m_nHeaderHeight = nHeaderHeight; if(nFooterHeight > -1) m_nFooterHeight = nFooterHeight; if(nLeftMargin > -1) m_nLeftMargin = nLeftMargin; if(nRightMargin > -1) m_nRightMargin = nRightMargin; if(nTopMargin > -1) m_nTopMargin = nTopMargin; if(nBottomMargin > -1) m_nBottomMargin = nBottomMargin; if(nGap > -1) m_nGap = nGap; } void CGridCtrl::GetPrintMarginInfo(int &nHeaderHeight, int &nFooterHeight, int &nLeftMargin, int &nRightMargin, int &nTopMargin, int &nBottomMargin, int &nGap) { nHeaderHeight = m_nHeaderHeight; nFooterHeight = m_nFooterHeight; nLeftMargin = m_nLeftMargin; nRightMargin = m_nRightMargin; nTopMargin = m_nTopMargin; nBottomMargin = m_nBottomMargin; nGap = m_nGap; } void CGridCtrl::Print(CPrintDialog* pPrntDialog /*=NULL*/) { CDC dc; if (pPrntDialog == NULL) { CPrintDialog printDlg(FALSE); if (printDlg.DoModal() != IDOK) // Get printer settings from user return; dc.Attach(printDlg.GetPrinterDC()); // attach a printer DC } else dc.Attach(pPrntDialog->GetPrinterDC()); // attach a printer DC dc.m_bPrinting = TRUE; CString strTitle; strTitle.LoadString(AFX_IDS_APP_TITLE); if( strTitle.IsEmpty() ) { CWnd *pParentWnd = GetParent(); while (pParentWnd) { pParentWnd->GetWindowText(strTitle); if (strTitle.GetLength()) // can happen if it is a CView, CChildFrm has the title break; pParentWnd = pParentWnd->GetParent(); } } DOCINFO di; // Initialise print doc details memset(&di, 0, sizeof (DOCINFO)); di.cbSize = sizeof (DOCINFO); di.lpszDocName = strTitle; BOOL bPrintingOK = dc.StartDoc(&di); // Begin a new print job CPrintInfo Info; Info.m_rectDraw.SetRect(0,0, dc.GetDeviceCaps(HORZRES), dc.GetDeviceCaps(VERTRES)); OnBeginPrinting(&dc, &Info); // Initialise printing for (UINT page = Info.GetMinPage(); page <= Info.GetMaxPage() && bPrintingOK; page++) { dc.StartPage(); // begin new page Info.m_nCurPage = page; OnPrint(&dc, &Info); // Print page bPrintingOK = (dc.EndPage() > 0); // end page } OnEndPrinting(&dc, &Info); // Clean up after printing if (bPrintingOK) dc.EndDoc(); // end a print job else dc.AbortDoc(); // abort job. dc.Detach(); // detach the printer DC } ///////////////////////////////////////////////////////////////////////////// // CGridCtrl printing overridables - for Doc/View print/print preview framework // EFW - Various changes in the next few functions to support the // new print margins and a few other adjustments. void CGridCtrl::OnBeginPrinting(CDC *pDC, CPrintInfo *pInfo) { // OnBeginPrinting() is called after the user has committed to // printing by OK'ing the Print dialog, and after the framework // has created a CDC object for the printer or the preview view. // This is the right opportunity to set up the page range. // Given the CDC object, we can determine how many rows will // fit on a page, so we can in turn determine how many printed // pages represent the entire document. ASSERT(pDC && pInfo); if (!pDC || !pInfo) return; // Get a DC for the current window (will be a screen DC for print previewing) CDC *pCurrentDC = GetDC(); // will have dimensions of the client area if (!pCurrentDC) return; CSize PaperPixelsPerInch(pDC->GetDeviceCaps(LOGPIXELSX), pDC->GetDeviceCaps(LOGPIXELSY)); CSize ScreenPixelsPerInch(pCurrentDC->GetDeviceCaps(LOGPIXELSX), pCurrentDC->GetDeviceCaps(LOGPIXELSY)); // Create the printer font int nFontSize = -10; CString strFontName = _T("Arial"); m_PrinterFont.CreateFont(nFontSize, 0,0,0, FW_NORMAL, 0,0,0, DEFAULT_CHARSET, OUT_CHARACTER_PRECIS, CLIP_CHARACTER_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, strFontName); CFont *pOldFont = pDC->SelectObject(&m_PrinterFont); // Get the average character width (in GridCtrl units) and hence the margins m_CharSize = pDC->GetTextExtent(_T("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSATUVWXYZ"),52); m_CharSize.cx /= 52; int nMargins = (m_nLeftMargin+m_nRightMargin)*m_CharSize.cx; // Get the page sizes (physical and logical) m_PaperSize = CSize(pDC->GetDeviceCaps(HORZRES), pDC->GetDeviceCaps(VERTRES)); if( m_bWysiwygPrinting) { m_LogicalPageSize.cx = ScreenPixelsPerInch.cx * m_PaperSize.cx / PaperPixelsPerInch.cx * 3 / 4; m_LogicalPageSize.cy = ScreenPixelsPerInch.cy * m_PaperSize.cy / PaperPixelsPerInch.cy * 3 / 4; } else { m_PaperSize = CSize(pDC->GetDeviceCaps(HORZRES), pDC->GetDeviceCaps(VERTRES)); m_LogicalPageSize.cx = GetVirtualWidth()+nMargins; #ifdef _WIN32_WCE m_LogicalPageSize.cy = (m_LogicalPageSize.cx * m_PaperSize.cy) / m_PaperSize.cx; #else m_LogicalPageSize.cy = MulDiv(m_LogicalPageSize.cx, m_PaperSize.cy, m_PaperSize.cx); #endif } m_nPageHeight = m_LogicalPageSize.cy - GetFixedRowHeight() - (m_nHeaderHeight+m_nFooterHeight + 2*m_nGap)*m_CharSize.cy; // Get the number of pages. Assumes no row is bigger than the page size. int nTotalRowHeight = 0; m_nNumPages = 1; for (int row = GetFixedRowCount(); row < GetRowCount(); row++) { nTotalRowHeight += GetRowHeight(row); if (nTotalRowHeight > m_nPageHeight) { m_nNumPages++; nTotalRowHeight = GetRowHeight(row); } } // now, figure out how many additional pages must print out if rows ARE bigger // than page size int iColumnOffset = 0; int i1; for( i1=0; i1 < GetFixedColumnCount(); i1++) { iColumnOffset += GetColumnWidth( i1); } m_nPageWidth = m_LogicalPageSize.cx - iColumnOffset - nMargins; m_nPageMultiplier = 1; if( m_bWysiwygPrinting) { int iTotalRowWidth = 0; for( i1 = GetFixedColumnCount(); i1 < GetColumnCount(); i1++) { iTotalRowWidth += GetColumnWidth( i1); if( iTotalRowWidth > m_nPageWidth) { m_nPageMultiplier++; iTotalRowWidth = GetColumnWidth( i1); } } m_nNumPages *= m_nPageMultiplier; } // Set up the print info pInfo->SetMaxPage(m_nNumPages); pInfo->m_nCurPage = 1; // start printing at page# 1 ReleaseDC(pCurrentDC); pDC->SelectObject(pOldFont); } void CGridCtrl::OnPrint(CDC *pDC, CPrintInfo *pInfo) { if (!pDC || !pInfo) return; //CRect rcPage(pInfo->m_rectDraw); CFont *pOldFont = pDC->SelectObject(&m_PrinterFont); // Set the page map mode to use GridCtrl units, and setup margin pDC->SetMapMode(MM_ANISOTROPIC); pDC->SetWindowExt(m_LogicalPageSize); pDC->SetViewportExt(m_PaperSize); pDC->SetWindowOrg(-m_nLeftMargin * m_CharSize.cx, 0); // Header pInfo->m_rectDraw.top = 0; pInfo->m_rectDraw.left = 0; pInfo->m_rectDraw.right = m_LogicalPageSize.cx - (m_nLeftMargin + m_nRightMargin) * m_CharSize.cx; pInfo->m_rectDraw.bottom = m_nHeaderHeight * m_CharSize.cy; PrintHeader(pDC, pInfo); pDC->OffsetWindowOrg(0, -m_nHeaderHeight * m_CharSize.cy); // Gap between header and column headings pDC->OffsetWindowOrg(0, -m_nGap * m_CharSize.cy); pDC->OffsetWindowOrg(0, -GetFixedRowHeight()); // We need to find out which row to start printing for this page. int nTotalRowHeight = 0; UINT nNumPages = 1; m_nCurrPrintRow = GetFixedRowCount(); // Not only the row, but we need to figure out column, too // Can print 4 pages, where page 1 and 2 represent the same rows but // with different WIDE columns. // // ....... // .1 .2 . If representing page 3 --> iPageIfIgnoredWideCols = 2 // ....... iWideColPageOffset = 0 // .3 .4 . If representing page 2 --> iPageIfIgnoredWideCols = 1 // ....... iWideColPageOffset = 1 int iPageIfIgnoredWideCols = pInfo->m_nCurPage / m_nPageMultiplier; int iWideColPageOffset = pInfo->m_nCurPage - ( iPageIfIgnoredWideCols * m_nPageMultiplier); if( iWideColPageOffset > 0) iPageIfIgnoredWideCols++; if( iWideColPageOffset == 0) iWideColPageOffset = m_nPageMultiplier; iWideColPageOffset--; // calculate current print row based on iPageIfIgnoredWideCols while( m_nCurrPrintRow < GetRowCount() && (int)nNumPages < iPageIfIgnoredWideCols) { nTotalRowHeight += GetRowHeight(m_nCurrPrintRow); if (nTotalRowHeight > m_nPageHeight) { nNumPages++; if ((int)nNumPages == iPageIfIgnoredWideCols) break; nTotalRowHeight = GetRowHeight(m_nCurrPrintRow); } m_nCurrPrintRow++; } m_nPrintColumn = GetFixedColumnCount(); int iTotalRowWidth = 0; int i1, i2; // now, calculate which print column to start displaying for( i1 = 0; i1 < iWideColPageOffset; i1++) { for( i2 = m_nPrintColumn; i2 < GetColumnCount(); i2++) { iTotalRowWidth += GetColumnWidth( i2); if( iTotalRowWidth > m_nPageWidth) { m_nPrintColumn = i2; iTotalRowWidth = 0; break; } } } PrintRowButtons( pDC, pInfo); // print row buttons on each page int iColumnOffset = 0; for( i1=0; i1 < GetFixedColumnCount(); i1++) { iColumnOffset += GetColumnWidth( i1); } // Print the column headings pInfo->m_rectDraw.bottom = GetFixedRowHeight(); if( m_nPrintColumn == GetFixedColumnCount()) { // have the column headings fcn draw the upper left fixed cells // for the very first columns, only pDC->OffsetWindowOrg( 0, +GetFixedRowHeight()); m_nPageWidth += iColumnOffset; m_nPrintColumn = 0; PrintColumnHeadings(pDC, pInfo); m_nPageWidth -= iColumnOffset; m_nPrintColumn = GetFixedColumnCount(); pDC->OffsetWindowOrg( -iColumnOffset, -GetFixedRowHeight()); } else { // changed all of this here to match above almost exactly same pDC->OffsetWindowOrg( 0, +GetFixedRowHeight()); m_nPageWidth += iColumnOffset; // print from column 0 ... last column that fits on the current page PrintColumnHeadings(pDC, pInfo); m_nPageWidth -= iColumnOffset; pDC->OffsetWindowOrg( -iColumnOffset, -GetFixedRowHeight()); } if (m_nCurrPrintRow >= GetRowCount()) return; // Draw as many rows as will fit on the printed page. // Clip the printed page so that there is no partially shown // row at the bottom of the page (the same row which will be fully // shown at the top of the next page). BOOL bFirstPrintedRow = TRUE; CRect rect; rect.bottom = -1; while (m_nCurrPrintRow < GetRowCount()) { rect.top = rect.bottom+1; rect.bottom = rect.top + GetRowHeight(m_nCurrPrintRow) - 1; if (rect.bottom > m_nPageHeight) break; // Gone past end of page rect.right = -1; // modified to allow printing of wide grids on multiple pages for (int col = m_nPrintColumn; col < GetColumnCount(); col++) { rect.left = rect.right+1; rect.right = rect.left + GetColumnWidth( col) - 1; if( rect.right > m_nPageWidth) break; CGridCellBase* pCell = GetCell(m_nCurrPrintRow, col); if (pCell) pCell->PrintCell(pDC, m_nCurrPrintRow, col, rect); if (m_nGridLines == GVL_BOTH || m_nGridLines == GVL_HORZ) { int Overlap = (col == 0)? 0:1; pDC->MoveTo(rect.left-Overlap, rect.bottom); pDC->LineTo(rect.right, rect.bottom); if (m_nCurrPrintRow == 0) { pDC->MoveTo(rect.left-Overlap, rect.top); pDC->LineTo(rect.right, rect.top); } } if (m_nGridLines == GVL_BOTH || m_nGridLines == GVL_VERT) { int Overlap = (bFirstPrintedRow)? 0:1; pDC->MoveTo(rect.right, rect.top-Overlap); pDC->LineTo(rect.right, rect.bottom); if (col == 0) { pDC->MoveTo(rect.left, rect.top-Overlap); pDC->LineTo(rect.left, rect.bottom); } } } m_nCurrPrintRow++; bFirstPrintedRow = FALSE; } // Footer pInfo->m_rectDraw.bottom = m_nFooterHeight * m_CharSize.cy; pDC->SetWindowOrg( -m_nLeftMargin * m_CharSize.cx, -m_LogicalPageSize.cy + m_nFooterHeight * m_CharSize.cy); PrintFooter(pDC, pInfo); // SetWindowOrg back for next page pDC->SetWindowOrg(0,0); pDC->SelectObject(pOldFont); } // added by M.Fletcher 12/17/00 void CGridCtrl::PrintFixedRowCells(int nStartColumn, int nStopColumn, int& row, CRect& rect, CDC *pDC, BOOL& bFirst) { // print all cells from nStartColumn to nStopColumn on row for (int col =nStartColumn; col < nStopColumn; col++) { rect.left = rect.right+1; rect.right = rect.left + GetColumnWidth( col) - 1; if( rect.right > m_nPageWidth) break; CGridCellBase* pCell = GetCell(row, col); if (pCell) pCell->PrintCell(pDC, row, col, rect); if (m_nGridLines == GVL_BOTH || m_nGridLines == GVL_HORZ) { int Overlap = (col == 0)? 0:1; pDC->MoveTo(rect.left-Overlap, rect.bottom); pDC->LineTo(rect.right, rect.bottom); if (row == 0) { pDC->MoveTo(rect.left-Overlap, rect.top); pDC->LineTo(rect.right, rect.top); } } if (m_nGridLines == GVL_BOTH || m_nGridLines == GVL_VERT) { int Overlap = (row == 0)? 0:1; pDC->MoveTo(rect.right, rect.top-Overlap); pDC->LineTo(rect.right, rect.bottom); if( bFirst) { pDC->MoveTo(rect.left-1, rect.top-Overlap); pDC->LineTo(rect.left-1, rect.bottom); bFirst = FALSE; } } } // end of column cells loop } // end of CGridCtrl::PrintFixedRowCells void CGridCtrl::PrintColumnHeadings(CDC *pDC, CPrintInfo* /*pInfo*/) { CFont *pOldFont = pDC->SelectObject(&m_PrinterFont); CRect rect; rect.bottom = -1; BOOL bFirst = TRUE; BOOL bOriginal; // modified to allow column hdr printing of multi-page wide grids for (int row = 0; row < GetFixedRowCount(); row++) { rect.top = rect.bottom+1; rect.bottom = rect.top + GetRowHeight(row) - 1; rect.right = -1; // if printColumn > fixedcolumncount we are on page 2 or more // lets printout those fixed cell headings again the 1 or more that would be missed // added by M.Fletcher 12/17/00 if(m_nPrintColumn>= GetFixedColumnCount()) { bOriginal=bFirst; // lets print the missing fixed cells on left first out to last fixed column PrintFixedRowCells(0,GetFixedColumnCount(), row, rect, pDC, bFirst); bFirst=bOriginal; } // now back to normal business print cells in heading after all fixed columns PrintFixedRowCells(m_nPrintColumn, GetColumnCount(), row, rect, pDC, bFirst); } // end of Row Loop pDC->SelectObject(pOldFont); } // end of CGridCtrl::PrintColumnHeadings /***************************************************************************** Prints line of row buttons on each page of the printout. Assumes that the window origin is setup before calling *****************************************************************************/ void CGridCtrl::PrintRowButtons(CDC *pDC, CPrintInfo* /*pInfo*/) { CFont *pOldFont = pDC->SelectObject(&m_PrinterFont); CRect rect; rect.right = -1; BOOL bFirst = TRUE; for( int iCol = 0; iCol < GetFixedColumnCount(); iCol++) { rect.left = rect.right+1; rect.right = rect.left + GetColumnWidth( iCol) - 1; rect.bottom = -1; for( int iRow = m_nCurrPrintRow; iRow < GetRowCount(); iRow++) { rect.top = rect.bottom+1; rect.bottom = rect.top + GetRowHeight( iRow) - 1; if( rect.bottom > m_nPageHeight) break; CGridCellBase* pCell = GetCell(iRow, iCol); if (pCell) pCell->PrintCell(pDC, iRow, iCol, rect); if (m_nGridLines == GVL_BOTH || m_nGridLines == GVL_HORZ) { int Overlap = (iCol == 0)? 0:1; pDC->MoveTo(rect.left-Overlap, rect.bottom); pDC->LineTo(rect.right, rect.bottom); if( bFirst) { pDC->MoveTo(rect.left-Overlap, rect.top-1); pDC->LineTo(rect.right, rect.top-1); bFirst = FALSE; } } if (m_nGridLines == GVL_BOTH || m_nGridLines == GVL_VERT) { int Overlap = (iRow == 0)? 0:1; pDC->MoveTo(rect.right, rect.top-Overlap); pDC->LineTo(rect.right, rect.bottom); if (iCol == 0) { pDC->MoveTo(rect.left, rect.top-Overlap); pDC->LineTo(rect.left, rect.bottom); } } } } pDC->SelectObject(pOldFont); } void CGridCtrl::PrintHeader(CDC *pDC, CPrintInfo *pInfo) { // print App title on top right margin CString strRight; strRight.LoadString(AFX_IDS_APP_TITLE); // print parent window title in the centre (Gert Rijs) CString strCenter; CWnd *pParentWnd = GetParent(); while (pParentWnd) { pParentWnd->GetWindowText(strCenter); if (strCenter.GetLength()) // can happen if it is a CView, CChildFrm has the title break; pParentWnd = pParentWnd->GetParent(); } CFont BoldFont; LOGFONT lf; //create bold font for header and footer VERIFY(m_PrinterFont.GetLogFont(&lf)); lf.lfWeight = FW_BOLD; VERIFY(BoldFont.CreateFontIndirect(&lf)); CFont *pNormalFont = pDC->SelectObject(&BoldFont); int nPrevBkMode = pDC->SetBkMode(TRANSPARENT); CRect rc(pInfo->m_rectDraw); if( !strCenter.IsEmpty() ) pDC->DrawText( strCenter, &rc, DT_CENTER | DT_SINGLELINE | DT_NOPREFIX | DT_VCENTER); if( !strRight.IsEmpty() ) pDC->DrawText( strRight, &rc, DT_RIGHT | DT_SINGLELINE | DT_NOPREFIX | DT_VCENTER); pDC->SetBkMode(nPrevBkMode); pDC->SelectObject(pNormalFont); BoldFont.DeleteObject(); // draw ruled-line across top pDC->SelectStockObject(BLACK_PEN); pDC->MoveTo(rc.left, rc.bottom); pDC->LineTo(rc.right, rc.bottom); } //print footer with a line and date, and page number void CGridCtrl::PrintFooter(CDC *pDC, CPrintInfo *pInfo) { // page numbering on left CString strLeft; strLeft.Format(_T("Page %d of %d"), pInfo->m_nCurPage, pInfo->GetMaxPage() ); // date and time on the right CString strRight; COleDateTime t = COleDateTime::GetCurrentTime(); strRight = t.Format(_T("%c")); CRect rc(pInfo->m_rectDraw); // draw ruled line on bottom pDC->SelectStockObject(BLACK_PEN); pDC->MoveTo(rc.left, rc.top); pDC->LineTo(rc.right, rc.top); CFont BoldFont; LOGFONT lf; //create bold font for header and footer m_PrinterFont.GetLogFont(&lf); lf.lfWeight = FW_BOLD; BoldFont.CreateFontIndirect(&lf); CFont *pNormalFont = pDC->SelectObject(&BoldFont); int nPrevBkMode = pDC->SetBkMode(TRANSPARENT); // EFW - Bug fix - Force text color to black. It doesn't always // get set to a printable color when it gets here. pDC->SetTextColor(RGB(0, 0, 0)); if( !strLeft.IsEmpty() ) pDC->DrawText( strLeft, &rc, DT_LEFT | DT_SINGLELINE | DT_NOPREFIX | DT_VCENTER); if( !strRight.IsEmpty() ) pDC->DrawText( strRight, &rc, DT_RIGHT | DT_SINGLELINE | DT_NOPREFIX | DT_VCENTER); pDC->SetBkMode(nPrevBkMode); pDC->SelectObject(pNormalFont); BoldFont.DeleteObject(); } void CGridCtrl::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { m_PrinterFont.DeleteObject(); } #endif // !defined(_WIN32_WCE_NO_PRINTING) && !defined(GRIDCONTROL_NO_PRINTING) #ifndef _WIN32_WCE ///////////////////////////////////////////////////////////////////////////// // CGridCtrl persistance BOOL CGridCtrl::Save(LPCTSTR filename, TCHAR chSeparator/*=_T(',')*/) { CStdioFile File; CFileException ex; CString strSeparator(chSeparator); if (!File.Open(filename, CFile::modeWrite | CFile::modeCreate| CFile::typeText, &ex)) { ex.ReportError(); return FALSE; } TRY { int nNumColumns = GetColumnCount(); for (int i = 0; i < GetRowCount(); i++) { for (int j = 0; j < nNumColumns; j++) { File.WriteString(GetItemText(i,j)); File.WriteString((j==(nNumColumns-1))? _T("\n"): strSeparator); } } File.Close(); } CATCH (CFileException, e) { AfxMessageBox(_T("Unable to save grid list")); return FALSE; } END_CATCH return TRUE; } BOOL CGridCtrl::Load(LPCTSTR filename, TCHAR chSeparator/*=_T(',')*/) { if (GetVirtualMode()) return FALSE; TCHAR *token, *end; TCHAR buffer[1024]; CStdioFile File; CFileException ex; if (!File.Open(filename, CFile::modeRead | CFile::typeText)) { ex.ReportError(); return FALSE; } DeleteAllItems(); TRY { // Read Header off file File.ReadString(buffer, 1024); // Get first token for (token=buffer, end=buffer; *end && (*end != chSeparator) && (*end != _T('\n')); end++) ; if ((*end == _T('\0')) && (token == end)) token = NULL; *end = _T('\0'); while (token) { InsertColumn(token); // Get next token for (token=++end; *end && (*end != chSeparator) && (*end != _T('\n')); end++) ; if ((*end == _T('\0')) && (token == end)) token = NULL; *end = _T('\0'); } // Read in rest of data int nItem = 1; while (File.ReadString(buffer, 1024)) { // Get first token for (token=buffer, end=buffer; *end && (*end != chSeparator) && (*end != _T('\n')); end++) ; if ((*end == _T('\0')) && (token == end)) token = NULL; *end = _T('\0'); int nSubItem = 0; while (token) { if (!nSubItem) InsertRow(token); else SetItemText(nItem, nSubItem, token); // Get next token for (token=++end; *end && (*end != chSeparator) && (*end != _T('\n')); end++) ; if ((*end == _T('\0')) && (token == end)) token = NULL; *end = _T('\0'); nSubItem++; } nItem++; } AutoSizeColumns(GetAutoSizeStyle()); File.Close(); } CATCH (CFileException, e) { AfxMessageBox(_T("Unable to load grid data")); return FALSE; } END_CATCH return TRUE; } #endif ///////////////////////////////////////////////////////////////////////////// // CGridCtrl overrideables #ifndef GRIDCONTROL_NO_DRAGDROP // This is no longer needed since I've changed to OLE drag and drop - but it's // still cool code. :) CImageList* CGridCtrl::CreateDragImage(CPoint *pHotSpot) { CDC* pDC = GetDC(); if (!pDC) return NULL; CRect rect; CCellID cell = GetFocusCell(); if (!GetCellRect(cell.row, cell.col, rect)) return NULL; // Translate coordinate system rect.BottomRight() = CPoint(rect.Width(), rect.Height()); rect.TopLeft() = CPoint(0, 0); *pHotSpot = rect.BottomRight(); // Create a new imagelist (the caller of this function has responsibility // for deleting this list) CImageList* pList = new CImageList; if (!pList || !pList->Create(rect.Width(), rect.Height(), ILC_MASK, 1, 1)) { if (pList) delete pList; return NULL; } // Create mem DC and bitmap CDC MemDC; CBitmap bm; MemDC.CreateCompatibleDC(pDC); bm.CreateCompatibleBitmap(pDC, rect.Width(), rect.Height()); CBitmap* pOldBitmap = MemDC.SelectObject(&bm); MemDC.SetWindowOrg(0, 0); // Draw cell onto bitmap in memDC CGridCellBase* pCell = GetCell(cell.row, cell.col); if (pCell) pCell->Draw(&MemDC, cell.row, cell.col, rect, FALSE); // Clean up MemDC.SelectObject(pOldBitmap); ReleaseDC(pDC); // Add the bitmap we just drew to the image list. pList->Add(&bm, GetDefaultCell(FALSE, FALSE)->GetBackClr()); bm.DeleteObject(); return pList; } #endif void CGridCtrl::OnFixedRowClick(CCellID& cell) { if (!IsValid(cell)) return; if (GetHeaderSort()) { CWaitCursor waiter; if (cell.col == GetSortColumn()) SortItems(cell.col, !GetSortAscending()); else SortItems(cell.col, TRUE); Invalidate(); } // Did the user click on a fixed column cell (so the cell was within the overlap of // fixed row and column cells) - (fix by David Pritchard) if (GetFixedColumnSelection()) { if (cell.col < GetFixedColumnCount()) { m_MouseMode = MOUSE_SELECT_ALL; OnSelecting(cell); } else { m_MouseMode = MOUSE_SELECT_COL; OnSelecting(cell); } } } void CGridCtrl::OnFixedColumnClick(CCellID& cell) { if (!IsValid(cell)) return; // if (m_bListMode && (GetItemState(cell.row, m_nFixedCols) & GVNI_SELECTED)) // { // OnEditCell(cell.row, cell.col, VK_LBUTTON); // return; // } // Did the user click on a fixed row cell (so the cell was within the overlap of // fixed row and column cells) - (fix by David Pritchard) if (GetFixedRowSelection()) { if (cell.row < GetFixedRowCount()) { m_MouseMode = MOUSE_SELECT_ALL; OnSelecting(cell); } else { m_MouseMode = MOUSE_SELECT_ROW; OnSelecting(cell); } } } // Gets the extent of the text pointed to by str (no CDC needed) // By default this uses the selected font (which is a bigger font) CSize CGridCtrl::GetTextExtent(int nRow, int nCol, LPCTSTR str) { CGridCellBase* pCell = GetCell(nRow, nCol); if (!pCell) return CSize(0, 0); else return pCell->GetTextExtent(str); } // virtual void CGridCtrl::OnEditCell(int nRow, int nCol, CPoint point, UINT nChar) { #ifndef GRIDCONTROL_NO_TITLETIPS m_TitleTip.Hide(); // hide any titletips #endif // Can we do it? CCellID cell(nRow, nCol); if (!IsValid(cell) || !IsCellEditable(nRow, nCol)) return; // Can we see what we are doing? EnsureVisible(nRow, nCol); if (!IsCellVisible(nRow, nCol)) return; // Where, exactly, are we gonna do it?? CRect rect; if (!GetCellRect(cell, rect)) return; // Check we can edit... if (SendMessageToParent(nRow, nCol, GVN_BEGINLABELEDIT) >= 0) { // Let's do it... CGridCellBase* pCell = GetCell(nRow, nCol); if (pCell) pCell->Edit(nRow, nCol, rect, point, IDC_INPLACE_CONTROL, nChar); } } // virtual void CGridCtrl::EndEditing() { CCellID cell = GetFocusCell(); if (!IsValid(cell)) return; CGridCellBase *pCell = GetCell(cell.row, cell.col); if (pCell) pCell->EndEdit(); } // virtual void CGridCtrl::OnEndEditCell(int nRow, int nCol, CString str) { CString strCurrentText = GetItemText(nRow, nCol); if (strCurrentText != str) { SetItemText(nRow, nCol, str); if (ValidateEdit(nRow, nCol, str) && SendMessageToParent(nRow, nCol, GVN_ENDLABELEDIT) >= 0) { SetModified(TRUE, nRow, nCol); RedrawCell(nRow, nCol); } else { SetItemText(nRow, nCol, strCurrentText); } } CGridCellBase* pCell = GetCell(nRow, nCol); if (pCell) pCell->OnEndEdit(); } // If this returns FALSE then the editing isn't allowed // virtual BOOL CGridCtrl::ValidateEdit(int nRow, int nCol, LPCTSTR str) { CGridCellBase* pCell = GetCell(nRow, nCol); ASSERT(pCell); if (!pCell) return TRUE; return pCell->ValidateEdit(str); } // virtual CString CGridCtrl::GetItemText(int nRow, int nCol) const { if (nRow < 0 || nRow >= m_nRows || nCol < 0 || nCol >= m_nCols) return _T(""); CGridCellBase* pCell = GetCell(nRow, nCol); ASSERT(pCell); if (!pCell) return _T(""); return pCell->GetText(); } void CGridCtrl::ResetVirtualOrder() { m_arRowOrder.resize(m_nRows); for (int i = 0; i < m_nRows; i++) { m_arRowOrder[i] = i; } } void CGridCtrl::Reorder(int From, int To) { // Set line From just after Line To ASSERT(From>= GetFixedRowCount() && To>=GetFixedRowCount()-1 && From<m_nRows && To<m_nRows); int Value = m_arRowOrder[From]; m_arRowOrder.erase(m_arRowOrder.begin()+From); int Offset = (From>=To ? 1:0); m_arRowOrder.insert(m_arRowOrder.begin()+To+Offset, Value); }
[ "pmosoft@gmail.com" ]
pmosoft@gmail.com
56e78b388ce06cd0acde0a1caa580025ec93c101
eb3d5a6ac04c715b2ac3e7f6190da3217c40b331
/softwareDesingProject/savemanager.h
49e1c02f943b48ecfb8798d88673b5c9bd1ab58e
[]
no_license
kosonen/SW_design_project
7e75265e8ef0a69a64f49d36923e48cc8a76283a
11839c7509d27bf1a78d1eb7d471c6e1e27ba176
refs/heads/master
2023-08-23T08:45:35.595480
2021-04-18T19:31:07
2021-04-18T19:31:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,250
h
#ifndef SAVEMANAGER_H #define SAVEMANAGER_H #include "isaveobject.h" #include <QObject> #include <unordered_map> /** * @brief The SaveManager class is responsible for saving and loadig savable * objects. Objects are saved and loaded froom a text file. */ class SaveManager : public QObject { Q_OBJECT public: explicit SaveManager(QObject *parent = nullptr); /** * @brief add method is used to add new object to save manager so they can * be loaded and saved to/from the same file * @param key defines the name for the obj * @param obj contains the object to be saved */ void add(QString key, ISaveObject* obj); /** * @brief load is used to load previously added objects from a fle * @param filePath contains path to the file to be loaded * @return true if loading file was successful, otherwise false */ bool load(QString filePath); /** * @brief save is used to save previosly added objects to a file * @param filePath contains path to the file to save to. * @return true if saving file was successful. otherwise false */ bool save(QString filePath); private: std::unordered_map<QString, ISaveObject*> m_data; }; #endif // SAVEMANAGER_H
[ "markus.jamback@tuni.fi" ]
markus.jamback@tuni.fi
96c84e32fc5dfb93077f04bbcca5b5532dd2a533
04b1803adb6653ecb7cb827c4f4aa616afacf629
/content/browser/media/cdm_file_impl.cc
242e248dbf525c999584e14e736dbc4a44bf5f8a
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
13,735
cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/media/cdm_file_impl.h" #include <set> #include <utility> #include "base/bind.h" #include "base/callback.h" #include "base/logging.h" #include "base/strings/string_util.h" #include "base/task/post_task.h" #include "storage/browser/fileapi/file_system_context.h" #include "storage/browser/fileapi/file_system_operation_context.h" #include "storage/browser/fileapi/file_system_url.h" #include "storage/browser/quota/quota_manager.h" #include "storage/common/fileapi/file_system_types.h" namespace content { namespace { // The CDM interface has a restriction that file names can not begin with _, // so use it to prefix temporary files. const char kTemporaryFilePrefix[] = "_"; std::string GetTempFileName(const std::string& file_name) { DCHECK(!base::StartsWith(file_name, kTemporaryFilePrefix, base::CompareCase::SENSITIVE)); return kTemporaryFilePrefix + file_name; } // The file system is different for each CDM and each origin. So track files // in use based on (file system ID, origin, file name). struct FileLockKey { FileLockKey(const std::string& file_system_id, const url::Origin& origin, const std::string& file_name) : file_system_id(file_system_id), origin(origin), file_name(file_name) {} ~FileLockKey() = default; // Allow use as a key in std::set. bool operator<(const FileLockKey& other) const { return std::tie(file_system_id, origin, file_name) < std::tie(other.file_system_id, other.origin, other.file_name); } std::string file_system_id; url::Origin origin; std::string file_name; }; // File map shared by all CdmFileImpl objects to prevent read/write race. // A lock must be acquired before opening a file to ensure that the file is not // currently in use. The lock must be held until the file is closed. class FileLockMap { public: FileLockMap() = default; ~FileLockMap() = default; // Acquire a lock on the file represented by |key|. Returns true if |key| // is not currently in use, false otherwise. bool AcquireFileLock(const FileLockKey& key) { DVLOG(3) << __func__ << " file: " << key.file_name; DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); // Add a new entry. If |key| already has an entry, insert() tells so // with the second piece of the returned value and does not modify // the original. return file_lock_map_.insert(key).second; } // Tests whether a lock is held on |key| or not. Returns true if |key| // is currently locked, false otherwise. bool IsFileLockHeld(const FileLockKey& key) { DVLOG(3) << __func__ << " file: " << key.file_name; DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); // Lock is held if there is an entry for |key|. return file_lock_map_.count(key) > 0; } // Release the lock held on the file represented by |key|. If // |on_close_callback| has been set, run it before releasing the lock. void ReleaseFileLock(const FileLockKey& key) { DVLOG(3) << __func__ << " file: " << key.file_name; DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); auto entry = file_lock_map_.find(key); if (entry == file_lock_map_.end()) { NOTREACHED() << "Unable to release lock on file " << key.file_name; return; } file_lock_map_.erase(entry); } private: // Note that this map is never deleted. As entries are removed when a file // is closed, it should never get too large. std::set<FileLockKey> file_lock_map_; THREAD_CHECKER(thread_checker_); DISALLOW_COPY_AND_ASSIGN(FileLockMap); }; // The FileLockMap is a global lock map shared by all CdmFileImpl instances. FileLockMap* GetFileLockMap() { static auto* file_lock_map = new FileLockMap(); return file_lock_map; } } // namespace CdmFileImpl::CdmFileImpl( const std::string& file_name, const url::Origin& origin, const std::string& file_system_id, const std::string& file_system_root_uri, scoped_refptr<storage::FileSystemContext> file_system_context) : file_name_(file_name), temp_file_name_(GetTempFileName(file_name_)), origin_(origin), file_system_id_(file_system_id), file_system_root_uri_(file_system_root_uri), file_system_context_(file_system_context), weak_factory_(this) { DVLOG(3) << __func__ << " " << file_name_; } CdmFileImpl::~CdmFileImpl() { DVLOG(3) << __func__ << " " << file_name_; DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); // If a file open was started but hasn't completed by now, run the callback // and report an error. if (pending_open_callback_) { std::move(pending_open_callback_) .Run(base::File(base::File::FILE_ERROR_ABORT)); } if (lock_state_ == LockState::kFileAndTempFileLocked) { // Temporary file is open, so close and release it. if (temporary_file_on_close_callback_) std::move(temporary_file_on_close_callback_).Run(); ReleaseFileLock(temp_file_name_); } if (lock_state_ != LockState::kNone) { // Original file is open, so close and release it. if (on_close_callback_) std::move(on_close_callback_).Run(); ReleaseFileLock(file_name_); } } void CdmFileImpl::Initialize(OpenFileCallback callback) { DVLOG(3) << __func__ << " file: " << file_name_; DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK_EQ(LockState::kNone, lock_state_); DCHECK(!pending_open_callback_); // Grab the lock on |file_name_|. The lock will be held until this object is // destructed. if (!AcquireFileLock(file_name_)) { DVLOG(3) << "File " << file_name_ << " is already in use."; std::move(callback).Run(base::File(base::File::FILE_ERROR_IN_USE)); return; } // We have the lock on |file_name_|. Now open the file for reading. Since // we don't know if this file exists or not, provide FLAG_OPEN_ALWAYS to // create the file if it doesn't exist. lock_state_ = LockState::kFileLocked; pending_open_callback_ = std::move(callback); OpenFile(file_name_, base::File::FLAG_OPEN_ALWAYS | base::File::FLAG_READ, base::BindOnce(&CdmFileImpl::OnFileOpenedForReading, weak_factory_.GetWeakPtr())); } void CdmFileImpl::OpenFile(const std::string& file_name, uint32_t file_flags, CreateOrOpenCallback callback) { DVLOG(3) << __func__ << " file: " << file_name << ", flags: " << file_flags; DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK_NE(LockState::kNone, lock_state_); DCHECK(IsFileLockHeld(file_name)); DCHECK(pending_open_callback_); storage::FileSystemURL file_url = CreateFileSystemURL(file_name); storage::AsyncFileUtil* file_util = file_system_context_->GetAsyncFileUtil( storage::kFileSystemTypePluginPrivate); auto operation_context = std::make_unique<storage::FileSystemOperationContext>( file_system_context_.get()); operation_context->set_allowed_bytes_growth(storage::QuotaManager::kNoLimit); DVLOG(3) << "Opening " << file_url.DebugString(); file_util->CreateOrOpen(std::move(operation_context), file_url, file_flags, std::move(callback)); } void CdmFileImpl::OnFileOpenedForReading(base::File file, base::OnceClosure on_close_callback) { DVLOG(3) << __func__ << " file: " << file_name_; DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK_EQ(LockState::kFileLocked, lock_state_); DCHECK(pending_open_callback_); if (!file.IsValid()) { // File is invalid. Note that the lock on |file_name_| is kept until this // object is destructed. DLOG(WARNING) << "Unable to open file " << file_name_ << ", error: " << base::File::ErrorToString(file.error_details()); std::move(pending_open_callback_).Run(std::move(file)); return; } // When the file is closed, |on_close_callback| will be run. on_close_callback_ = std::move(on_close_callback); std::move(pending_open_callback_).Run(std::move(file)); } void CdmFileImpl::OpenFileForWriting(OpenFileForWritingCallback callback) { DVLOG(3) << __func__ << " " << file_name_; // Fail if this is called out of order. We must have opened the original // file, and there should be no call in progress. if (lock_state_ != LockState::kFileLocked || pending_open_callback_) { std::move(callback).Run( base::File(base::File::FILE_ERROR_INVALID_OPERATION)); return; } // Grab a lock on the temporary file. The lock will be held until this // new file is renamed in CommitWrite() (or this object is // destructed). if (!AcquireFileLock(temp_file_name_)) { DVLOG(3) << "File " << temp_file_name_ << " is already in use."; std::move(callback).Run(base::File(base::File::FILE_ERROR_IN_USE)); return; } // We now have locks on both |file_name_| and |temp_file_name_|. Open the // temporary file for writing. Specifying FLAG_CREATE_ALWAYS which will // overwrite any existing file. lock_state_ = LockState::kFileAndTempFileLocked; pending_open_callback_ = std::move(callback); OpenFile(temp_file_name_, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE, base::BindOnce(&CdmFileImpl::OnTempFileOpenedForWriting, weak_factory_.GetWeakPtr())); } void CdmFileImpl::OnTempFileOpenedForWriting( base::File file, base::OnceClosure on_close_callback) { DVLOG(3) << __func__ << " file: " << file_name_; DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK_EQ(LockState::kFileAndTempFileLocked, lock_state_); DCHECK(pending_open_callback_); if (!file.IsValid()) { DLOG(WARNING) << "Unable to open file " << temp_file_name_ << ", error: " << base::File::ErrorToString(file.error_details()); lock_state_ = LockState::kFileLocked; ReleaseFileLock(temp_file_name_); std::move(pending_open_callback_).Run(std::move(file)); return; } temporary_file_on_close_callback_ = std::move(on_close_callback); std::move(pending_open_callback_).Run(std::move(file)); } void CdmFileImpl::CommitWrite(CommitWriteCallback callback) { DVLOG(3) << __func__ << " " << temp_file_name_ << " to " << file_name_; DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK_EQ(LockState::kFileAndTempFileLocked, lock_state_); DCHECK(IsFileLockHeld(file_name_)); DCHECK(IsFileLockHeld(temp_file_name_)); // TODO(jrummell): Verify that the written file does not exceed the file // size limit of 32MB. If it does simply delete the written file and fail. // Fail if this is called out of order. We must have opened both the original // and the temporary file, and there should be no call in progress. if (lock_state_ != LockState::kFileAndTempFileLocked || pending_open_callback_) { std::move(callback).Run( base::File(base::File::FILE_ERROR_INVALID_OPERATION)); return; } if (on_close_callback_) std::move(on_close_callback_).Run(); if (temporary_file_on_close_callback_) std::move(temporary_file_on_close_callback_).Run(); // OpenFile() will be called after the file is renamed, so save |callback|. pending_open_callback_ = std::move(callback); storage::FileSystemURL src_file_url = CreateFileSystemURL(temp_file_name_); storage::FileSystemURL dest_file_url = CreateFileSystemURL(file_name_); storage::AsyncFileUtil* file_util = file_system_context_->GetAsyncFileUtil( storage::kFileSystemTypePluginPrivate); auto operation_context = std::make_unique<storage::FileSystemOperationContext>( file_system_context_.get()); DVLOG(3) << "Renaming " << src_file_url.DebugString() << " to " << dest_file_url.DebugString(); file_util->MoveFileLocal( std::move(operation_context), src_file_url, dest_file_url, storage::FileSystemOperation::OPTION_NONE, base::BindOnce(&CdmFileImpl::OnFileRenamed, weak_factory_.GetWeakPtr())); } void CdmFileImpl::OnFileRenamed(base::File::Error move_result) { DVLOG(3) << __func__; DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK_EQ(LockState::kFileAndTempFileLocked, lock_state_); DCHECK(pending_open_callback_); // Temporary file has been renamed, so we can release the lock on it. ReleaseFileLock(temp_file_name_); lock_state_ = LockState::kFileLocked; // Was the rename successful? if (move_result != base::File::FILE_OK) { std::move(pending_open_callback_).Run(base::File(move_result)); return; } // Reopen the original file for reading. Specifying FLAG_OPEN as the file // has to exist or something's wrong. OpenFile(file_name_, base::File::FLAG_OPEN | base::File::FLAG_READ, base::BindOnce(&CdmFileImpl::OnFileOpenedForReading, weak_factory_.GetWeakPtr())); } storage::FileSystemURL CdmFileImpl::CreateFileSystemURL( const std::string& file_name) { return file_system_context_->CrackURL( GURL(file_system_root_uri_ + file_name)); } bool CdmFileImpl::AcquireFileLock(const std::string& file_name) { FileLockKey file_lock_key(file_system_id_, origin_, file_name); return GetFileLockMap()->AcquireFileLock(file_lock_key); } bool CdmFileImpl::IsFileLockHeld(const std::string& file_name) { FileLockKey file_lock_key(file_system_id_, origin_, file_name); return GetFileLockMap()->IsFileLockHeld(file_lock_key); } void CdmFileImpl::ReleaseFileLock(const std::string& file_name) { FileLockKey file_lock_key(file_system_id_, origin_, file_name); GetFileLockMap()->ReleaseFileLock(file_lock_key); } } // namespace content
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
d6546c32fd50e45f1d15c33d91512fd832c0b377
6a06b78872090333760204f93b1b2d99aa67624a
/Contest/INDIV CC Sept. 2016/A.cpp
a1ea9486cc7c79d5ea7d65a688be04d9578fd350
[]
no_license
SixSiebenUno/ACM-ICPC
ccbc6127290f62a87f654c842c78cd0806a4929c
b3932fcec0a912aa1e610a2a4541f1f0a21a0da1
refs/heads/master
2020-07-19T13:02:58.674238
2016-09-19T13:56:50
2016-09-19T13:56:50
67,402,220
0
0
null
null
null
null
UTF-8
C++
false
false
436
cpp
#include <iostream> #include <cstdio> #include <cstdlib> #include <cmath> #include <cstring> #include <algorithm> using namespace std; const int MaxL = 100007; int T; char str[MaxL]; int main() { int i,l,a,b; scanf("%d",&T); while(T--) { scanf("%s",str+1); l = strlen(str+1); a = b = 0; for(i=1;i<=l;i++) if(str[i]=='1') a++; else b++; if(a==1 || b==1) printf("Yes\n"); else printf("No\n"); } return 0; }
[ "SixSiebenUno@gmail.com" ]
SixSiebenUno@gmail.com
9d46600fb49693951056d84750a1667a9ba7412d
265a865a1d4420a76abdf739034c8e96b1038de1
/LuckyLeprechauns/Game/MushroomView.h
c59181c7d5ac7740c7e40e2c48eb2b3030909751
[]
no_license
steinbergerbernd/Lucky-Leprechauns
c6ab6ec3f2636b39f6a53323de9f3d19d318e356
935c4e72dfef7815766ec3af64a5cb1b0f3fd3cc
refs/heads/master
2021-01-25T12:01:20.819357
2013-09-24T18:02:33
2013-09-24T18:02:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
449
h
#pragma once #include "LLControlledGraphicsComponent.h" #include "MushroomController.h" #include "StoneView.h" class MushroomView : public LLControlledGraphicsComponent<MushroomController> { public: MushroomView(LLGraphicsManager* manager, const MushroomController* controller); void init(); void draw(const GameTime& gameTime); private: FBXModel model; StoneView* stone; std::vector<Texture> playerTextures; Texture neutralTexture; };
[ "bernd.steinberger@hotmail.com" ]
bernd.steinberger@hotmail.com
290e4b7a7bd3faaa9c60f3ece7719c609bf20e76
df59b0571730619d5d3f72bdf3d9427393fcf8cc
/ld21/glesgae/Events/X11/X11EventSystem.h
9616abfa4eaebc113764a9ce8340c48af46d7668
[]
no_license
stuckie/ludumdare
69642be40da72e64bd0c1a17d4c4d6937fd278a9
b61d30e97a63b56376defaf06a8eaebe3322811c
refs/heads/master
2021-01-21T10:13:02.901439
2019-01-02T14:48:56
2019-01-02T14:48:56
4,536,120
1
0
null
null
null
null
UTF-8
C++
false
false
523
h
#ifndef _X11_EVENT_SYSTEM_H_ #define _X11_EVENT_SYSTEM_H_ namespace GLESGAE { class RenderWindow; class X11RenderWindow; class EventSystem : public CommonEventSystem { public: EventSystem(); ~EventSystem(); /// Update the Event System void update(); /// Bind to the Window void bindToWindow(RenderWindow* const window); private: // No Copying EventSystem(const EventSystem&); EventSystem& operator=(const EventSystem&); bool mActive; X11RenderWindow* mWindow; }; } #endif
[ "stuckie@stuckiegamez.co.uk" ]
stuckie@stuckiegamez.co.uk
de7b91faa9c971efceff6274085b587bd510e3cf
051840dd4538845119dae6f1b3abf9a7f03496a7
/devel/include/action_primitive_variation/AddTwoIntsRequest.h
fd526fd4369b0cd6cb328322c67106d2b106334c
[]
no_license
mateoguaman/action_primitive_variation
fded53a649235f7e510f725da39f962b0d01d9df
bde8ae0c6efbb4e3ea926ec1c5e6cbfa76277863
refs/heads/master
2020-03-22T18:04:40.137119
2018-07-21T23:30:06
2018-07-21T23:30:06
140,435,583
0
0
null
2018-07-10T13:22:44
2018-07-10T13:22:44
null
UTF-8
C++
false
false
5,655
h
// Generated by gencpp from file action_primitive_variation/AddTwoIntsRequest.msg // DO NOT EDIT! #ifndef ACTION_PRIMITIVE_VARIATION_MESSAGE_ADDTWOINTSREQUEST_H #define ACTION_PRIMITIVE_VARIATION_MESSAGE_ADDTWOINTSREQUEST_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace action_primitive_variation { template <class ContainerAllocator> struct AddTwoIntsRequest_ { typedef AddTwoIntsRequest_<ContainerAllocator> Type; AddTwoIntsRequest_() : a(0) , b(0) { } AddTwoIntsRequest_(const ContainerAllocator& _alloc) : a(0) , b(0) { (void)_alloc; } typedef int64_t _a_type; _a_type a; typedef int64_t _b_type; _b_type b; typedef boost::shared_ptr< ::action_primitive_variation::AddTwoIntsRequest_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::action_primitive_variation::AddTwoIntsRequest_<ContainerAllocator> const> ConstPtr; }; // struct AddTwoIntsRequest_ typedef ::action_primitive_variation::AddTwoIntsRequest_<std::allocator<void> > AddTwoIntsRequest; typedef boost::shared_ptr< ::action_primitive_variation::AddTwoIntsRequest > AddTwoIntsRequestPtr; typedef boost::shared_ptr< ::action_primitive_variation::AddTwoIntsRequest const> AddTwoIntsRequestConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::action_primitive_variation::AddTwoIntsRequest_<ContainerAllocator> & v) { ros::message_operations::Printer< ::action_primitive_variation::AddTwoIntsRequest_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace action_primitive_variation namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False} // {'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'action_primitive_variation': ['/home/evana/apv_ws/src/action_primitive_variation/msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::action_primitive_variation::AddTwoIntsRequest_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsFixedSize< ::action_primitive_variation::AddTwoIntsRequest_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::action_primitive_variation::AddTwoIntsRequest_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::action_primitive_variation::AddTwoIntsRequest_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::action_primitive_variation::AddTwoIntsRequest_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::action_primitive_variation::AddTwoIntsRequest_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::action_primitive_variation::AddTwoIntsRequest_<ContainerAllocator> > { static const char* value() { return "36d09b846be0b371c5f190354dd3153e"; } static const char* value(const ::action_primitive_variation::AddTwoIntsRequest_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x36d09b846be0b371ULL; static const uint64_t static_value2 = 0xc5f190354dd3153eULL; }; template<class ContainerAllocator> struct DataType< ::action_primitive_variation::AddTwoIntsRequest_<ContainerAllocator> > { static const char* value() { return "action_primitive_variation/AddTwoIntsRequest"; } static const char* value(const ::action_primitive_variation::AddTwoIntsRequest_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::action_primitive_variation::AddTwoIntsRequest_<ContainerAllocator> > { static const char* value() { return "int64 a\n\ int64 b\n\ "; } static const char* value(const ::action_primitive_variation::AddTwoIntsRequest_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::action_primitive_variation::AddTwoIntsRequest_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.a); stream.next(m.b); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct AddTwoIntsRequest_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::action_primitive_variation::AddTwoIntsRequest_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::action_primitive_variation::AddTwoIntsRequest_<ContainerAllocator>& v) { s << indent << "a: "; Printer<int64_t>::stream(s, indent + " ", v.a); s << indent << "b: "; Printer<int64_t>::stream(s, indent + " ", v.b); } }; } // namespace message_operations } // namespace ros #endif // ACTION_PRIMITIVE_VARIATION_MESSAGE_ADDTWOINTSREQUEST_H
[ "Evana13G@gmail.com" ]
Evana13G@gmail.com
951fbc373003c4775dc6f812469facd7e78025f9
a130745e3a6aba0f636b7a138506b7a5eca3578e
/Texture_Class.h
f103f83a47fd4f12d38dc542ff8c74a1c3eb54a0
[]
no_license
deesaa/come-engine-2013
70d12abd4fbb22fc911e41c5e1e7d8094ac2a685
176dc8066cf1b7954f21ca086be22c4a9b6d001d
refs/heads/master
2020-08-09T08:03:08.426270
2019-10-09T23:55:14
2019-10-09T23:55:14
214,043,480
0
0
null
null
null
null
UTF-8
C++
false
false
2,132
h
class texture_class { private: IDirect3DDevice9* device; IDirect3DTexture9* texture; bool initialized; public: void initBaseForTexture(IDirect3DDevice9* bDevice) { initialized = FALSE; device = bDevice; } void loadTexture4Verts(DWORD vertsID[], vertex* vertices, sphere_struct* vertsSpheres[]) { initialized = TRUE; D3DXVECTOR3 textureVerts[4]; DWORD textureVertsID[4]; for(DWORD counter(0); counter != 4;) { textureVerts[counter].x = (vertices[vertsID[0]].pos.x + vertices[vertsID[1]].pos.x + vertices[vertsID[2]].pos.x + vertices[vertsID[3]].pos.x) / 4; textureVerts[counter].y = (vertices[vertsID[0]].pos.y + vertices[vertsID[1]].pos.y + vertices[vertsID[2]].pos.y + vertices[vertsID[3]].pos.y) / 4; for (DWORD counter_2(0); counter_2 != 4;) { if(vertices[vertsID[counter_2]].pos.x < textureVerts[counter].x && vertices[vertsID[counter_2]].pos.y > textureVerts[counter].y) { textureVertsID[0] = vertsID[counter_2]; } else if(vertices[vertsID[counter_2]].pos.x > textureVerts[counter].x && vertices[vertsID[counter_2]].pos.y > textureVerts[counter].y) { textureVertsID[1] = vertsID[counter_2]; } else if(vertices[vertsID[counter_2]].pos.x > textureVerts[counter].x && vertices[vertsID[counter_2]].pos.y < textureVerts[counter].y) { textureVertsID[2] = vertsID[counter_2]; } else if(vertices[vertsID[counter_2]].pos.x < textureVerts[counter].x && vertices[vertsID[counter_2]].pos.y < textureVerts[counter].y) { textureVertsID[3] = vertsID[counter_2]; } counter_2 += 1; } counter += 1; } vertices[textureVertsID[0]].u = 0; vertices[textureVertsID[0]].v = 0; vertices[textureVertsID[1]].u = 1; vertices[textureVertsID[1]].v = 0; vertices[textureVertsID[2]].u = 1; vertices[textureVertsID[2]].v = 1; vertices[textureVertsID[3]].u = 0; vertices[textureVertsID[3]].v = 1; D3DXCreateTextureFromFile(device, L"Nyan.bmp", &texture); } void resetTexture() { if(initialized) device->SetTexture(0, texture); else device->SetTexture(0, 0); } };
[ "deemsaer@gmail.com" ]
deemsaer@gmail.com
a9ad8b5e4db046d56c699f8bfdab11d2f22662a6
c99cdc49376de34f73543ddf21a5730ca45888fe
/8111.cpp
30d76671109827b3b33beba86646cfdec0844718
[]
no_license
ParkSale/Boj
6dda75b47bc5b0938f1756a56e2432f3a05f0ca6
5d98f8024a2bf84e3aa86c50de8cdd55466e51e1
refs/heads/master
2020-09-18T18:24:46.408515
2020-07-29T06:01:56
2020-07-29T06:01:56
224,163,776
0
0
null
null
null
null
UTF-8
C++
false
false
810
cpp
#include <bits/stdc++.h> using namespace std; bool visit[20005]; struct info { int n; string s; }; queue<info> q; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int N; cin >> N; while (N--) { int a; cin >> a; for (int i = 0; i <= 20000; ++i) visit[i] = 0; while (!q.empty()) q.pop(); q.push({ 1,"1" }); visit[1] = 1; bool flag = 0; while (!q.empty()) { info p = q.front(); q.pop(); if (p.n % a == 0) { flag = 1; cout << p.s << "\n"; break; } string tmp = p.s; int n = (p.n * 10) % a; tmp.push_back('0'); if (!visit[n]) { visit[n] = 1; q.push({ n,tmp }); } n = ((p.n * 10) + 1) % a; tmp = p.s; tmp.push_back('1'); if (!visit[n]) { visit[n] = 1; q.push({ n,tmp }); } } if (!flag) cout << "BANK\n"; } }
[ "psi0613@naver.com" ]
psi0613@naver.com
4b3496d9ec734dc3fae8c4287ce4b44ad93b65e8
431d823cff60949e83b6babf79c87bc7f1be00ad
/Controller/RowHistoryLogController.h
a88114fc544604000e8a33a79f15c0947d8983c6
[]
no_license
hieutrtr/CMDBv2
645fc41bdeb3d71685bfd409cf9029a70c266a92
a1c54d33eda350a35939d207e07b29ce18238f83
refs/heads/master
2016-09-15T23:04:28.212321
2014-06-20T09:54:48
2014-06-20T09:54:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
195
h
#pragma once #include "CIHistoryLogController.h" class CRowHistoryLogController : public CCIHistoryLogController { public: CRowHistoryLogController(void); ~CRowHistoryLogController(void); };
[ "hieutrantrung.it@gmail.com" ]
hieutrantrung.it@gmail.com
51f328ecbe67f82999e900ebca604edefc5302cf
1867d31e1840341a8f73e20368484f37329c5f52
/src/qt/askpassphrasedialog.h
abd45feb07368bd4e290a0a4789d5996eaf8fdb6
[ "MIT" ]
permissive
avshyk/cashhand
614f8b8394ffcc9de29452d02c78c102b2ff9d26
890c739c4b81325d9645de96a6cbaf5469579b74
refs/heads/master
2023-04-03T14:31:47.229221
2021-04-08T13:07:44
2021-04-08T13:07:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,883
h
// Copyright (c) 2011-2013 The Bitcoin developers // Copyright (c) 2017-2019 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_QT_ASKPASSPHRASEDIALOG_H #define BITCOIN_QT_ASKPASSPHRASEDIALOG_H #include <QDialog> #include "qt/pivx/prunnable.h" #include "allocators.h" #include <QCheckBox> class WalletModel; class CASHHANDGUI; namespace Ui { class AskPassphraseDialog; class QCheckBox; } /** Multifunctional dialog to ask for passphrases. Used for encryption, unlocking, and changing the passphrase. */ class AskPassphraseDialog : public QDialog, public Runnable { Q_OBJECT public: enum class Mode { Encrypt, /**< Ask passphrase twice and encrypt */ UnlockAnonymize, /**< Ask passphrase and unlock only for anonymization */ Unlock, /**< Ask passphrase and unlock */ ChangePass, /**< Ask old passphrase + new passphrase twice */ Decrypt /**< Ask passphrase and decrypt wallet */ }; // Context from where / for what the passphrase dialog was called to set the status of the checkbox // Partly redundant to Mode above, but offers more flexibility for future enhancements enum class Context { Unlock_Menu, /** Unlock wallet from menu */ Unlock_Full, /** Wallet needs to be fully unlocked */ Encrypt, /** Encrypt unencrypted wallet */ ToggleLock, /** Toggle wallet lock state */ ChangePass, /** Change passphrase */ Send_CHND, /** Send CHND */ BIP_38, /** BIP38 menu */ Multi_Sig, /** Multi-Signature dialog */ Sign_Message, /** Sign/verify message dialog */ UI_Vote, /** Governance Tab UI Voting */ }; explicit AskPassphraseDialog(Mode mode, QWidget* parent, WalletModel* model, Context context); ~AskPassphraseDialog(); void showEvent(QShowEvent *event) override; void accept() override; SecureString getPassword() { return oldpass; } private: Ui::AskPassphraseDialog* ui; Mode mode; WalletModel* model; Context context; bool fCapsLock; SecureString newpassCache = ""; SecureString oldpass, newpass1, newpass2; void run(int type) override; void onError(QString error, int type) override; QCheckBox *btnWatch; void initWatch(QWidget *parent); private Q_SLOTS: void onWatchClicked(); void textChanged(); void warningMessage(); void errorEncryptingWallet(); bool openStandardDialog(QString title = "", QString body = "", QString okBtn = "OK", QString cancelBtn = ""); protected: bool event(QEvent* event) override ; bool eventFilter(QObject* object, QEvent* event) override; }; #endif // BITCOIN_QT_ASKPASSPHRASEDIALOG_H
[ "cashhandcrypto@gmail.com" ]
cashhandcrypto@gmail.com
9ed550dd27d63437f23e433770ee1c931d942612
e5937bed3ac457e4572b3fe64e735bec9e7d947c
/elfModel.cpp
f6c91bb33e7dcbf973545e1c0e7fdc7b97304be3
[ "BSD-2-Clause" ]
permissive
nikkej/elfix
be4b725172bb19b8ae8d4270f895618baa533f76
f1990577a69a702ba21d7e2d6adcfe7d081d9293
refs/heads/master
2021-01-11T01:31:29.823868
2018-02-05T13:26:19
2018-02-05T13:26:19
70,695,919
4
0
null
null
null
null
UTF-8
C++
false
false
54,489
cpp
//******************************************************************************** // // elfModel.cpp // // Copyright (c) 2016, Juha T Nikkanen <nikkej@gmail.com> // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // The views and conclusions contained in the software and documentation are those // of the authors and should not be interpreted as representing official policies, // either expressed or implied, of the FreeBSD Project. // //******************************************************************************** #include <sstream> #include <iostream> #include <iomanip> #include <limits.h> #include <string> #include <cstring> //#include <inttypes.h> #include <capstone/capstone.h> #include <map> #include "asmDump.hpp" #include "hexDump.hpp" #include "elfModel.hpp" #include "elfDefs.hpp" ElfFileModel::ElfFileModel( const char* objFile, const long length ) throw() : _objFile( objFile ), _length( length ), _objFileModelImpl( NULL ) { Elf32_Ehdr* hdr = (Elf32_Ehdr*)_objFile; if( hdr->e_ident[ EI_MAG0 ] == ELFMAG0 \ && hdr->e_ident[ EI_MAG1 ] == ELFMAG1 \ && hdr->e_ident[ EI_MAG2 ] == ELFMAG2 \ && hdr->e_ident[ EI_MAG3 ] == ELFMAG3 ) { if( hdr->e_ident[ EI_CLASS ] == ELFCLASS32 ) { _objFileModelImpl = new ElfModelImpl32( _objFile, _length ); } else if( hdr->e_ident[ EI_CLASS ] == ELFCLASS64 ) { _objFileModelImpl = new ElfModelImpl64( (Elf64_Ehdr*)_objFile, _length ); } else { throw elfClassException(); } } else { throw elfMagicException(); } } ElfFileModel::~ElfFileModel() { if( _objFileModelImpl ) { delete _objFileModelImpl; _objFileModelImpl = NULL; } } const std::string ElfFileModelBase::parseSectionFlags( Elf64_Xword flags ) { std::ostringstream strBuf; uint64_t mask = 1; while( mask < ( (uint64_t)1 << 31 ) ) { if( Elf::SHdr::sh_flags.find( mask ) != Elf::SHdr::sh_flags.end() ) { if( flags & mask ) strBuf << Elf::SHdr::sh_flags.at( mask ); else strBuf << ' '; } mask <<= 1; } return strBuf.str(); } void ElfFileModelBase::parseSectionDescription( const std::string& sectionDescr, long& index ) { char* endPtr; // Assume numerical value first errno = 0; index = strtol( sectionDescr.c_str(), &endPtr, 10 ); if( ( errno == ERANGE && ( index == LONG_MAX || index == LONG_MIN ) ) || ( errno != 0 && index == 0 ) ) { std::cerr << __func__ << ", "; perror( "strtol" ); return; } // Section name as a string if( endPtr == sectionDescr.c_str() ) { index = -1; } } size_t ElfFileModelBase::numberFieldWidth( const unsigned int& number ) { char nrAsc[ 10 ] = { 0 }; char* p = nrAsc; size_t nrWidth = 0; snprintf( nrAsc, 8, "%u", number ); while( *p++ ) nrWidth++; return( nrWidth ); } ElfModelImpl32::ElfModelImpl32( const char* objFile, const long fileLength ) : _ehdr( (Elf32_Ehdr*)objFile ), _fileLength( fileLength ) { } bool ElfModelImpl32::Elf32HaveSectionTable() { if( _ehdr->e_shoff != 0 ) return( true ); else { std::cerr << "No section header table" << std::endl; return( false ); } } char* ElfModelImpl32::Elf32GetName( const Elf32_Word sh_name, const Elf32_Shdr* strtable ) { if( sh_name < strtable->sh_size ) return( (char*)( (char*)_ehdr + strtable->sh_offset + sh_name ) ); else return( (char*)"" ); } Elf32_Shdr* ElfModelImpl32::Elf32GetSection( const Elf32_Half index, ElfItemFilter* eif ) { if( index < _ehdr->e_shnum ) { Elf32_Shdr* section = (Elf32_Shdr*)( (char*)_ehdr + _ehdr->e_shoff + index * _ehdr->e_shentsize ); if( eif ) { if( (*eif)[ byType ].test( section->sh_type ) && (*eif)[ byLink ].test( section->sh_link ) ) { return( section ); } } else { return( section ); } } return( NULL ); } Elf32_Sym* ElfModelImpl32::Elf32GetSymbol( const Elf32_Shdr* symtab, const Elf32_Half index, ElfItemFilter* eif ) { if( symtab != NULL && index < (symtab->sh_size / symtab->sh_entsize) ) { Elf32_Sym* symbol = (Elf32_Sym*)((char*)_ehdr + symtab->sh_offset + index * symtab->sh_entsize ); if( eif ) { if( (*eif)[ byType ].test( ELF32_ST_TYPE( symbol->st_info ) ) && (*eif)[ byRelatedIndex ].test( symbol->st_shndx ) ) { return( symbol ); } } else { return( symbol ); } } return( NULL ); } Elf32_Rel* ElfModelImpl32::Elf32GetRelEntry( const Elf32_Shdr* reltab, const Elf32_Half index, ElfItemFilter* eif ) { if( reltab != NULL && index < (reltab->sh_size / reltab->sh_entsize) ) { Elf32_Rel* reloc = (Elf32_Rel*)((char*)_ehdr + reltab->sh_offset + index * reltab->sh_entsize ); if( eif ) { if( (*eif)[ byType ].test( ELF32_R_TYPE( reloc->r_info ) ) && (*eif)[ byRelatedIndex ].test( ELF32_R_SYM( reloc->r_info ) ) ) return( reloc ); } else { return( reloc ); } } return( NULL ); } Elf32_Rela* ElfModelImpl32::Elf32GetRelaEntry( const Elf32_Shdr* relatab, const Elf32_Half index, ElfItemFilter* eif ) { if( relatab != NULL && index < (relatab->sh_size / relatab->sh_entsize) ) { Elf32_Rela* reloc_a = (Elf32_Rela*)((char*)_ehdr + relatab->sh_offset + index * relatab->sh_entsize ); if( eif ) { if( (*eif)[ byType ].test( ELF32_R_TYPE( reloc_a->r_info ) ) && (*eif)[ byRelatedIndex ].test( ELF32_R_SYM( reloc_a->r_info ) ) ) return( reloc_a ); } else { return( reloc_a ); } } return( NULL ); } void ElfModelImpl32::Elf32GetSectionByIndex( const Elf32_Half index, Elf32_Shdr*& shdr ) { if( index < _ehdr->e_shnum ) shdr = (Elf32_Shdr*)( (char*)_ehdr + _ehdr->e_shoff + index * _ehdr->e_shentsize ); else shdr = NULL; } Elf32_Half ElfModelImpl32::Elf32GetSectionByType( const Elf32_Half startIndex, const Elf32_Word type, Elf32_Shdr*& shdr ) { shdr = NULL; if( startIndex < _ehdr->e_shnum ) { for( Elf32_Half index = startIndex; index < _ehdr->e_shnum; index++ ) { if( type == ( (Elf32_Shdr*)( (char*)_ehdr + _ehdr->e_shoff + index * _ehdr->e_shentsize ) )->sh_type ) { shdr = (Elf32_Shdr*)( (char*)_ehdr + _ehdr->e_shoff + index * _ehdr->e_shentsize ); return( index ); } } } return( 0 ); } Elf32_Half ElfModelImpl32::Elf32GetSectionByName( const Elf32_Half startIndex, const char *section, Elf32_Shdr*& shdr ) { Elf32_Shdr* shstrtable; Elf32_Shdr* tmp_section; Elf32GetSectionByIndex ( _ehdr->e_shstrndx, shstrtable ); shdr = NULL; if( startIndex < _ehdr->e_shnum ) { for( Elf32_Half index = 0; index < _ehdr->e_shnum; index++ ) { Elf32GetSectionByIndex( index, tmp_section ); if ( !strcmp( Elf32GetName( tmp_section->sh_name, shstrtable ), section ) ) { shdr = (Elf32_Shdr*)( (char*)_ehdr + _ehdr->e_shoff + index * _ehdr->e_shentsize ); return( index ); } } } return( 0 ); } void ElfModelImpl32::Elf32GetSectionOffsetAndSize( const std::string& sectionDescr, long& offset, long& size ) { long sectionIndex; parseSectionDescription( sectionDescr, sectionIndex ); Elf32_Shdr* section; if( sectionIndex != -1 ) { Elf32GetSectionByIndex( (Elf32_Half)sectionIndex, section ); } else { Elf32GetSectionByName( 1, sectionDescr.c_str(), section ); } if( section ) { offset = section->sh_offset; size = section->sh_size; } else { offset = 0; size = 0; std::cerr << "Invalid section definition: " << sectionDescr << std::endl; return; } } void ElfModelImpl32::Elf32GetSectionOffsetAndSize( const Elf32_Half& sectionIndex, long& offset, long& size ) { Elf32_Shdr* section; Elf32GetSectionByIndex( sectionIndex, section ); if( section ) { offset = section->sh_offset; size = section->sh_size; } else { offset = 0; size = 0; std::cerr << "Invalid section definition: " << sectionIndex << std::endl; return; } } void ElfModelImpl32::Elf32GetTotalSize( long& totalSize ) { totalSize = _ehdr->e_ehsize; totalSize += _ehdr->e_shnum * _ehdr->e_shentsize; for( Elf32_Half index = 0; index < _ehdr->e_shnum; index++ ) { if( SHT_NOBITS != ( (Elf32_Shdr*)( (char*)_ehdr + _ehdr->e_shoff + index * _ehdr->e_shentsize ) )->sh_type ) totalSize += ( (Elf32_Shdr*)( (char*)_ehdr + _ehdr->e_shoff + index * _ehdr->e_shentsize ) )->sh_size; } } void ElfModelImpl32::CheckFile() { if( Elf32HaveSectionTable() ) { long sectionsSize = 0; Elf32GetTotalSize( sectionsSize ); if( sectionsSize == _fileLength ) { std::cout << "Size of sections and file header matches file size" << std::endl; } else { std::cout << "There are " << _fileLength - sectionsSize << " bytes of bogus data in file" << std::endl; } } } void ElfModelImpl32::DisassembleSection( const std::string& sectionDescr, const bool showAddr = true ) { std::map<Elf32_Addr, Elf32_Sym*> elf32FuncSyms; std::map<Elf32_Addr, Elf32_Sym*> elf32NoTypeSyms; std::map<Elf32_Addr, Elf32_Rel*> elf32Relocs; Elf32_Shdr* strtab; if( Elf32HaveSectionTable() ) { long offset, size, sectionIndex; parseSectionDescription( sectionDescr, sectionIndex ); Elf32GetSectionOffsetAndSize( sectionDescr, offset, size ); if( sectionIndex == -1 ) { Elf32_Shdr* dummySection; sectionIndex = Elf32GetSectionByName( 1, sectionDescr.c_str(), dummySection ); } // Get all func & notype symbols for this section Elf32_Sym* symbol; Elf32_Shdr* symtab; ElfItemFilter ef; Elf32GetSectionByName( 1, ".strtab", strtab ); Elf32GetSectionByType( 1, SHT_SYMTAB, symtab ); ef[ byType ].resize( STT_FUNC +1 ).set( STT_NOTYPE ).set( STT_FUNC ); ef[ byRelatedIndex ].resize( symtab->sh_size / symtab->sh_entsize ).set( sectionIndex ); for( Elf32_Word index = 0; index < symtab->sh_size / symtab->sh_entsize; index++ ) { if( ( symbol = Elf32GetSymbol( symtab, index, &ef ) ) != NULL ) { if( ELF32_ST_TYPE( symbol->st_info ) == STT_NOTYPE ) elf32NoTypeSyms.insert( std::make_pair( symbol->st_value, symbol ) ); if( ELF32_ST_TYPE( symbol->st_info ) == STT_FUNC ) elf32FuncSyms.insert( std::make_pair( symbol->st_value, symbol ) ); } } // Get all relocations for this section Elf32_Rel* reloc; Elf32_Shdr* reltab; for( Elf32_Half index = 1; index < _ehdr->e_shnum; index++ ) { Elf32GetSectionByType( index, SHT_REL, reltab ); if( reltab && reltab->sh_info == sectionIndex ) { for( Elf32_Word index = 0; index < reltab->sh_size / reltab->sh_entsize; index++ ) { if( ( reloc = Elf32GetRelEntry( reltab, index ) ) != NULL ) elf32Relocs.insert( std::make_pair( reloc->r_offset, reloc ) ); } } } if( offset && size ) { csh handle; cs_arch arch; cs_mode mode; cs_insn *insn; size_t count; if( _ehdr->e_machine == EM_ARM ) { arch = CS_ARCH_ARM; mode = CS_MODE_ARM; } else { std::cerr << "With 32bit Elf relocatables, only ARM supported for now" << std::endl; return; } try { if ( cs_open( arch, mode, &handle ) != CS_ERR_OK ) { std::cerr << "Cannot open capstone handle" << std::endl; return; } if ( cs_option( handle, CS_OPT_DETAIL, CS_OPT_ON) != CS_ERR_OK ) { std::cerr << "Cannot set more detailed instruction decomposition, giving up" << std::endl; return; } for( const auto& functionSym: elf32FuncSyms ) { const uint64_t codeBlockAddress = (functionSym.second)->st_value; uint64_t subBlockAddress = 0; const size_t codeBlockSize = (size_t)(functionSym.second)->st_size; size_t subBlockSize; Elf_ARM_adt subBlockType; typedef std::vector<struct Block> blockv; blockv blocks; std::map<Elf32_Addr, Elf32_Sym*>::iterator itBlockBegin, itBlockNext; // Now assume mapping symbol '$d' is always after function begin if exist at all, so it // should be safe to get upper bound iterator to figure out presence of '$d' in function itBlockBegin = elf32NoTypeSyms.upper_bound( codeBlockAddress ); if( itBlockBegin != elf32NoTypeSyms.end() && itBlockBegin->first < ( codeBlockAddress + codeBlockSize ) ) { // Okay, we have found '$d' inside a function, divide it to sub blocks subBlockSize = itBlockBegin->first - codeBlockAddress; // First block blocks.push_back( Block( ARMCode, codeBlockAddress, subBlockSize ) ); do { if( strncmp( "$d", Elf32GetName( (itBlockBegin->second)->st_name, strtab ), 2 ) == 0 ) { subBlockType = ARMData; } if( strncmp( "$a", Elf32GetName( (itBlockBegin->second)->st_name, strtab ), 2 ) == 0 ) { subBlockType = ARMCode; } subBlockAddress = itBlockBegin->first; itBlockNext = itBlockBegin; if( ++itBlockNext != elf32NoTypeSyms.end() && itBlockNext->first < ( codeBlockAddress + codeBlockSize ) ) subBlockSize = itBlockNext->first - itBlockBegin->first; else subBlockSize = ( codeBlockAddress + codeBlockSize ) - itBlockBegin->first; blocks.push_back( Block( subBlockType, subBlockAddress, subBlockSize ) ); } while( ++itBlockBegin != elf32NoTypeSyms.end() && itBlockBegin->first < ( codeBlockAddress + codeBlockSize ) ); } else { // Only one block, i.e. function itself blocks.push_back( Block( ARMCode, codeBlockAddress, codeBlockSize ) ); } blockv::const_iterator blockIt = blocks.begin(); for( ; blockIt != blocks.end(); ++blockIt ) { if( blockIt->type == ARMCode ) { count = cs_disasm( handle, (const uint8_t*)( (char*)_ehdr + offset + blockIt->address ), blockIt->size, blockIt->address, 0, &insn ); if ( count > 0 ) { for( size_t j = 0; j < count; j++ ) { if( elf32FuncSyms.find( insn[j].address ) != elf32FuncSyms.end() ) std::cout << Elf32GetName( elf32FuncSyms.at( insn[j].address )->st_name, strtab ) << ":" << std::endl; showAddr ? std::cout << std::setw( 8 ) << std::setfill( ' ' ) << std::hex << std::right << insn[j].address << ": " : std::cout << std::setw( 10 ) << std::setfill( ' ' ) << ""; std::cout << std::setw( 16 ) << std::setfill( ' ' ) << std::left << insn[j].mnemonic; if( elf32Relocs.find( insn[j].address ) != elf32Relocs.end() ) { Elf32_Sym* symbol = Elf32GetSymbol( symtab, ELF32_R_SYM( elf32Relocs.at( insn[j].address )->r_info ) ); std::string symName = Elf32GetName( symbol->st_name, strtab ); if( symName.empty() ) symName = "<no name>"; std::cout << std::setw( 8 ) << std::setfill( ' ' ) << std::left << symName << std::endl; } else { std::cout << std::setw( 8 ) << std::setfill( ' ' ) << std::left << insn[j].op_str << std::endl; } } cs_err errorCode = cs_errno( handle ); if( errorCode != CS_ERR_OK ) std::cerr << "Disasm engine reports: " << cs_strerror( errorCode ) << std::endl; cs_free( insn, count ); } else { printf( "ERROR: Failed to disassemble given code!\n" ); } } else if( blockIt->type == ARMData ) { uint64_t dataBlockAddr = blockIt->address; uint64_t dataBlockSize = blockIt->size; while( dataBlockSize ) { if( dataBlockSize % 4 != 0 ) { std::cerr << "Weird aligment error?" << std::endl; break; } showAddr ? std::cout << std::setw( 8 ) << std::setfill( ' ' ) << std::hex << std::right << dataBlockAddr << ": " : std::cout << std::setw( 10 ) << std::setfill( ' ' ) << ""; std::cout << std::setw( 16 ) << std::setfill( ' ' ) << std::left << ".word"; if( elf32Relocs.find( dataBlockAddr ) != elf32Relocs.end() ) { Elf32_Sym* symbol = Elf32GetSymbol( symtab, ELF32_R_SYM( elf32Relocs.at( dataBlockAddr )->r_info ) ); std::string symName = Elf32GetName( symbol->st_name, strtab ); if( symName.empty() ) symName = "<no name>"; std::cout << std::setw( 8 ) << std::setfill( ' ' ) << std::left << symName; std::cout << ' ' << "@ 0x" << std::hex << *(uint32_t*)((char*)_ehdr + offset + dataBlockAddr); std::cout << ", " << Elf::ARM::Reloc::type.at( ELF32_R_TYPE( elf32Relocs.at( dataBlockAddr )->r_info ) ) << std::endl; } else { std::cout << "0x" << std::setw( 8 ) << std::setfill( '0' ) << std::left << std::hex << *(uint32_t*)((char*)_ehdr + offset + dataBlockAddr) << std::endl; } dataBlockAddr += 4; dataBlockSize -= 4; } } } } cs_close( &handle ); } catch( std::exception &e ) { std::cerr << e.what() << std::endl; return; } } #if 0 // Iterate and print keys and values of unordered_map std::cout << "Reloc map32: " << elf32Relocs.size() << " entries" << std::endl; std::cout << "Func Sym map32: " << elf32FuncSyms.size() << " entries" << std::endl; for( const auto& n : elf32FuncSyms ) { std::cout << "Key:[" << n.first << "], shndx: " << (n.second)->st_shndx << ", value: "; std::cout << std::hex << (n.second)->st_value << ", size: "; std::cout << std::hex << (n.second)->st_size << ", Name:[" << Elf32GetName( (n.second)->st_name, strtab ) << "]" << std::endl; } #endif } } void ElfModelImpl32::DisassembleFile( const bool showAddr = true ) { //unordered_map<Elf32_Addr, Elf32_Sym*> elf32Syms; std::unique_ptr<std::map<Elf32_Addr, Elf32_Sym*>> elf32Syms( new std::map<Elf32_Addr, Elf32_Sym*>() ); std::map<Elf32_Addr, Elf32_Rel*> elf32Relocs; std::map<Elf32_Section, Elf32_Shdr*> elf32Progbits; Elf32_Shdr* strtab; Elf32_Shdr* shstrtab; Elf32GetSectionByIndex ( _ehdr->e_shstrndx, shstrtab ); if( Elf32HaveSectionTable() ) { long offset, size; Elf32_Half machine; // Get all program bit sections Elf32_Shdr* tmpSection; for( Elf32_Half index = 0; index < _ehdr->e_shnum; index++ ) { Elf32GetSectionByIndex( index, tmpSection ); if( tmpSection && tmpSection->sh_type == SHT_PROGBITS ) { elf32Progbits.insert( std::make_pair( index, tmpSection ) ); } } // Get all relocations Elf32_Rel* reloc; Elf32_Shdr* reltab; ElfItemFilter ef; Elf32GetSectionByType( 1, SHT_REL, reltab ); if( reltab ) { for( Elf32_Word index = 0; index < reltab->sh_size / reltab->sh_entsize; index++ ) { if( ( reloc = Elf32GetRelEntry( reltab, index, &ef ) ) != NULL ) elf32Relocs.insert( std::make_pair( reloc->r_offset, reloc ) ); } } #if 1 csh handle; cs_arch arch; cs_mode mode; cs_insn *insn; size_t count; machine = _ehdr->e_machine; if( machine == EM_ARM ) { arch = CS_ARCH_ARM; mode = CS_MODE_ARM; } else if( machine == EM_X86_64 ) { arch = CS_ARCH_X86; mode = CS_MODE_64; } else return; Elf32_Sym* symbol; Elf32_Shdr* symtab; Elf32GetSectionByName( 1, ".strtab", strtab ); Elf32GetSectionByType( 1, SHT_SYMTAB, symtab ); try { if ( cs_open( arch, mode, &handle ) != CS_ERR_OK ) return; for( const auto& section: elf32Progbits ) { // Get all function symbols for this section elf32Syms->clear(); ef[ byType ].resize( 3 ).set( STT_FUNC ); ef[ byRelatedIndex ].resize( section.first + 1 ).set( section.first ); for( Elf32_Word index = 0; index < symtab->sh_size / symtab->sh_entsize; index++ ) { if( ( symbol = Elf32GetSymbol( symtab, index, &ef ) ) != NULL ) elf32Syms->insert( std::make_pair( symbol->st_value, symbol ) ); } Elf32GetSectionOffsetAndSize( section.first, offset, size ); if( offset && size ) { std::cout << "Disassembly of section " << Elf32GetName( (section.second)->sh_name, shstrtab ) << std::endl; count = cs_disasm( handle, (const uint8_t*)( (char*)_ehdr + offset ), (size_t)size, 0, 0, &insn ); if ( count > 0 ) { for( size_t j = 0; j < count; j++ ) { showAddr ? std::cout << "0x" << std::hex << insn[j].address << ":" : std::cout << ""; if( elf32Syms->find( insn[j].address ) != elf32Syms->end() ) std::cout << Elf32GetName( (*elf32Syms)[ insn[j].address ]->st_name, strtab ) << ":" << std::endl; std::cout << "\t\t" << insn[j].mnemonic; if( elf32Relocs.find( insn[j].address ) != elf32Relocs.end() ) { Elf32_Sym* symbol = Elf32GetSymbol( symtab, ELF32_R_SYM( elf32Relocs[ insn[j].address ]->r_info ) ); std::cout << "\t" << Elf32GetName( symbol->st_name, strtab ) << std::endl; } else std::cout << "\t" << insn[j].op_str << std::endl; } cs_free( insn, count ); } else printf( "ERROR: Failed to disassemble given code!\n" ); } } cs_close( &handle ); } catch( std::exception &e ) { std::cerr << e.what() << std::endl; return; } #endif // Iterate and print keys and values of unordered_map std::cout << "Reloc map32: " << elf32Relocs.size() << " entries" << std::endl; std::cout << "Sym map32: " << elf32Syms->size() << " entries" << std::endl; Elf32_Shdr* section; size_t nrWidth = numberFieldWidth( _ehdr->e_shnum ); size_t longestName = 0; for( Elf32_Half index = 0; index < _ehdr->e_shnum; index++ ) { Elf32GetSectionByIndex( index, section ); size_t tmpLen = strlen( Elf32GetName( section->sh_name, shstrtab ) ); if( longestName < tmpLen ) longestName = tmpLen; } for( const auto& sec : elf32Progbits ) { //std::cout << "Key:[" << sec.first << "] Name:[" << Elf32GetName( (sec.second)->st_name, strtab ) << "]\n"; try { Elf32GetSectionByIndex( sec.first, section ); std::cout << " [" << std::setw( nrWidth ) << std::setfill( ' ' ) << std::dec << std::right << sec.first << ']'; std::cout << ' ' << std::setw( longestName + 2 ) << std::setfill( ' ' ) << std::left << Elf32GetName( section->sh_name, shstrtab ); std::cout << ' ' << std::setw( 15 ) << std::setfill( ' ' ) << std::left << Elf::SHdr::sh_type.at( section->sh_type ); std::cout << " 0x" << std::setw( sizeof( section->sh_offset ) * 2 ) << std::setfill( '0' ) << std::hex << std::right << section->sh_offset; std::cout << " 0x" << std::setw( sizeof( section->sh_size ) * 2 ) << std::setfill( '0' ) << std::hex << std::right << section->sh_size; std::cout << ' ' << std::setw( 2 ) << std::setfill( ' ' ) << std::dec << std::right << section->sh_entsize; std::cout << ' ' << std::right << parseSectionFlags( section->sh_flags ); std::cout << ' ' << std::setw( nrWidth ) << std::setfill( ' ' ) << std::dec << std::right << section->sh_link; std::cout << ' ' << std::setw( nrWidth ) << std::setfill( ' ' ) << std::dec << std::right << section->sh_info; std::cout << ' ' << std::setw( 2 ) << std::setfill( ' ' ) << std::dec << std::right << section->sh_addralign; std::cout << std::endl; } catch( std::exception& e ) { std::cerr << e.what() << ", error in matching section header numerical values to text" << std::endl; std::cerr << "Probable cause, definitions for section header num to text are outdated" << std::endl; } } } } void ElfModelImpl32::DumpSection( const std::string& sectionDescr, const Dump_mode mode ) { if( Elf32HaveSectionTable() ) { long offset, size; Elf32GetSectionOffsetAndSize( sectionDescr, offset, size ); switch( mode ) { case DumpAsm: { asmDump ad( ( (char*)_ehdr + offset ), size ); std::cout << ad; break; } case DumpHex: { hexDump hd( ( (char*)_ehdr + offset ), size ); std::cout << hd; break; } case DumpRaw: { std::cout.write( ( (char*)_ehdr + offset ), size ); std::cout.flush(); break; } } } } void ElfModelImpl32::IterateRelocations( const std::string& s ) { // vector<Elf32_Rel*> elf32Relocs; // vector<Elf32_Rela*> elf32Relocs_a; boost::dynamic_bitset<> rel_bset( R_ARM_NUM ); boost::dynamic_bitset<> rela_bset( R_ARM_NUM ); Elf32_Rel* reloc; Elf32_Rela* reloc_a; Elf32_Shdr* strtab; Elf32_Shdr* shstrtab; Elf32GetSectionByIndex ( _ehdr->e_shstrndx, shstrtab ); if( Elf32HaveSectionTable() ) { // Get all rel & rela entries Elf32_Shdr* reltab; for( Elf32_Half index = 0; index < _ehdr->e_shnum; index++ ) { Elf32GetSectionByIndex( index, reltab ); if( reltab && reltab->sh_type == SHT_REL ) { for( Elf32_Word index = 0; index < reltab->sh_size / reltab->sh_entsize; index++ ) { if( ( reloc = Elf32GetRelEntry( reltab, index ) ) != NULL ) { // elf32Relocs.push_back( reloc ); rel_bset.set( ELF32_R_TYPE( reloc->r_info ) ); } } } if( reltab && reltab->sh_type == SHT_RELA ) { for( Elf32_Word index = 0; index < reltab->sh_size / reltab->sh_entsize; index++ ) { if( ( reloc_a = Elf32GetRelaEntry( reltab, index ) ) != NULL ) { // elf32Relocs_a.push_back( reloc_a ); rela_bset.set( ELF32_R_TYPE( reloc_a->r_info ) ); } } } } } if( rel_bset.count() ) { std::cout << "There are " << rel_bset.count() << " rel types:" << std::endl; for( size_t i = 0; i < rel_bset.size(); i++ ) { if( rel_bset.test( i ) ) std::cout << " " << Elf::ARM::Reloc::type.at( i ) << std::endl; } } if( rela_bset.count() ) { std::cout << "There are " << rela_bset.count() << " rela types" << std::endl; } // for( const auto& rel: elf32Relocs ) { } } void ElfModelImpl32::IterateSections() { Elf32_Shdr* section; Elf32_Shdr* shstrtab; Elf32GetSectionByIndex( _ehdr->e_shstrndx, shstrtab ); std::cout << "There are " << _ehdr->e_shnum << " section headers, starting at offset 0x" << std::hex << _ehdr->e_shoff << ':' << std::endl; std::cout << "Section headers:" << std::endl; // Resolve longest section name string size_t longestName = 0; for( Elf32_Half index = 0; index < _ehdr->e_shnum; index++ ) { Elf32GetSectionByIndex( index, section ); size_t tmpLen = strlen( Elf32GetName( section->sh_name, shstrtab ) ); if( longestName < tmpLen ) longestName = tmpLen; } // Resolve width for Nr field size_t nrWidth = numberFieldWidth( _ehdr->e_shnum ); try { for( Elf32_Half index = 0; index < _ehdr->e_shnum; index++ ) { Elf32GetSectionByIndex( index, section ); std::cout << " [" << std::setw( nrWidth ) << std::setfill( ' ' ) << std::dec << std::right << index << ']'; std::cout << ' ' << std::setw( longestName + 2 ) << std::setfill( ' ' ) << std::left << Elf32GetName( section->sh_name, shstrtab ); std::cout << ' ' << std::setw( 15 ) << std::setfill( ' ' ) << std::left << Elf::SHdr::sh_type.at( section->sh_type ); std::cout << " 0x" << std::setw( sizeof( section->sh_offset ) * 2 ) << std::setfill( '0' ) << std::hex << std::right << section->sh_offset; std::cout << " 0x" << std::setw( sizeof( section->sh_size ) * 2 ) << std::setfill( '0' ) << std::hex << std::right << section->sh_size; std::cout << ' ' << std::setw( 2 ) << std::setfill( ' ' ) << std::dec << std::right << section->sh_entsize; std::cout << ' ' << std::right << parseSectionFlags( section->sh_flags ); std::cout << ' ' << std::setw( nrWidth ) << std::setfill( ' ' ) << std::dec << std::right << section->sh_link; std::cout << ' ' << std::setw( nrWidth ) << std::setfill( ' ' ) << std::dec << std::right << section->sh_info; std::cout << ' ' << std::setw( 2 ) << std::setfill( ' ' ) << std::dec << std::right << section->sh_addralign; std::cout << std::endl; } } catch( std::exception& e ) { std::cerr << e.what() << ", error in matching section header numerical values to text" << std::endl; std::cerr << "Probable cause, definitions for section header num to text are outdated" << std::endl; } } // Iterate 32bit elf file symbol table // void ElfModelImpl32::IterateSymbols() { Elf32_Shdr* symtab; Elf32_Shdr* shstrtab; Elf32GetSectionByIndex( _ehdr->e_shstrndx, shstrtab ); Elf32GetSectionByType( 1, SHT_SYMTAB, symtab ); if( symtab != NULL ) { size_t nrWidth = numberFieldWidth( symtab->sh_size / symtab->sh_entsize ); std::cout << "Symbol table " << Elf32GetName( symtab->sh_name, shstrtab ) << " contains " << symtab->sh_size / symtab->sh_entsize << " entries:" << std::endl; Elf32_Shdr* strtab; Elf32GetSectionByName( 1, ".strtab", strtab ); if( strtab ) { std::cout << " " << std::setw( nrWidth > strlen( "Num:") ? nrWidth : strlen( "Num:" ) ) << std::setfill( ' ' ) << std::right << "Num:"; std::cout << ' ' << std::setw( sizeof( Elf32_Addr ) * 2 ) << std::setfill( ' ' ) << std::right << "Value"; std::cout << ' ' << std::setw( 4 ) << std::setfill( ' ' ) << std::right << "Size"; std::cout << ' ' << std::setw( 10 ) << std::setfill( ' ' ) << std::left << "Type"; std::cout << ' ' << std::setw( 11 ) << std::setfill( ' ' ) << std::left << "Binding"; std::cout << ' ' << std::setw( 10 ) << std::setfill( ' ' ) << std::left << "Visib"; std::cout << ' ' << std::setw( 6 ) << std::setfill( ' ' ) << std::right << "Ndx"; std::cout << ' ' << std::left << "Name"; std::cout << std::endl; Elf32_Sym* symbol = (Elf32_Sym*)((char*)_ehdr + symtab->sh_offset ); try { for( Elf32_Word index = 0; index < symtab->sh_size / symtab->sh_entsize; index++, symbol++ ) { std::cout << ' ' << std::setw( nrWidth > strlen( "Num:") ? nrWidth : strlen( "Num:" ) ) << std::setfill( ' ' ) << std::dec << std::right << index << ':'; std::cout << ' ' << std::setw( sizeof( Elf32_Addr ) * 2 ) << std::setfill( '0' ) << std::hex << std::right << symbol->st_value; std::cout << ' ' << std::setw( 4 ) << std::setfill( ' ' ) << std::hex << std::right << symbol->st_size; std::cout << ' ' << std::setw( 10 ) << std::setfill( ' ' ) << std::left << Elf::Sym::sym_type.at( ELF32_ST_TYPE( symbol->st_info ) ); std::cout << ' ' << std::setw( 11 ) << std::setfill( ' ' ) << std::left << Elf::Sym::sym_bind.at( ELF32_ST_BIND( symbol->st_info ) ); std::cout << ' ' << std::setw( 10 ) << std::setfill( ' ' ) << std::left << Elf::Sym::sym_visib.at( ELF32_ST_VISIBILITY( symbol->st_other ) ); std::cout << ' ' << std::setw( 6 ) << std::setfill( ' ' ); ( symbol->st_shndx != 0 && symbol->st_shndx < SHN_LOPROC ) ? std::cout << std::dec << std::right << symbol->st_shndx : std::cout << std::right << Elf::Sym::sym_special_ndx.at( symbol->st_shndx ); std::cout << ' ' << Elf32GetName( symbol->st_name, strtab ); std::cout << std::endl; } } catch( std::exception& e ) { std::cerr << e.what() << ", error in matching symbol header numerical values to text" << std::endl; std::cerr << "Probable cause, definitions for symbol header num to text are outdated" << std::endl; } } } } // 64 bit elf helper functions // bool ElfModelImpl64::Elf64HaveSectionTable() { if( _ehdr->e_shoff != 0 ) return( true ); else { std::cerr << "No section header table" << std::endl; return( false ); } } char* ElfModelImpl64::Elf64GetName( const Elf64_Word sh_name, const Elf64_Shdr* strtable ) { if( sh_name < strtable->sh_size ) return( (char*)( (char*)_ehdr + strtable->sh_offset + sh_name ) ); else return( NULL ); } Elf64_Sym* ElfModelImpl64::Elf64GetSymbol(const Elf64_Shdr* symtab, const Elf64_Half index ) { if( symtab != NULL && index < (symtab->sh_size / symtab->sh_entsize) ) { Elf64_Sym* symbol = (Elf64_Sym*)((char*)_ehdr + symtab->sh_offset + index * symtab->sh_entsize ); return( symbol ); } return( NULL ); } Elf64_Rel* ElfModelImpl64::Elf64GetRelEntry( const Elf64_Shdr* reltab, const Elf64_Half index, const Elf64_Section section ) { if( reltab != NULL && index < (reltab->sh_size / reltab->sh_entsize) ) { Elf64_Rel* reloc = (Elf64_Rel*)((char*)_ehdr + reltab->sh_offset + index * reltab->sh_entsize ); return( reloc ); } return( NULL ); } void ElfModelImpl64::Elf64GetSectionByIndex( const Elf64_Half index, Elf64_Shdr*& shdr ) { if( index < _ehdr->e_shnum ) shdr = (Elf64_Shdr*)( (char*)_ehdr + _ehdr->e_shoff + index * _ehdr->e_shentsize ); else shdr = NULL; } Elf64_Half ElfModelImpl64::Elf64GetSectionByType( const Elf64_Half startIndex, const Elf64_Word type, Elf64_Shdr*& shdr ) { shdr = NULL; if( startIndex < _ehdr->e_shnum ) { for( Elf64_Half index = 0; index < _ehdr->e_shnum; index++ ) { if( type == ( (Elf64_Shdr*)( (char*)_ehdr + _ehdr->e_shoff + index * _ehdr->e_shentsize ) )->sh_type ) { shdr = (Elf64_Shdr*)( (char*)_ehdr + _ehdr->e_shoff + index * _ehdr->e_shentsize ); return( index ); } } } return( 0 ); } Elf64_Half ElfModelImpl64::Elf64GetSectionByName( const Elf64_Half startIndex, const char *section, Elf64_Shdr*& shdr ) { Elf64_Shdr* shstrtable; Elf64_Shdr* tmp_section; Elf64GetSectionByIndex ( _ehdr->e_shstrndx, shstrtable ); shdr = NULL; if( startIndex < _ehdr->e_shnum ) { for( Elf64_Half index = 0; index < _ehdr->e_shnum; index++ ) { Elf64GetSectionByIndex( index, tmp_section ); if ( !strcmp( Elf64GetName( tmp_section->sh_name, shstrtable ), section ) ) { shdr = (Elf64_Shdr*)( (char*)_ehdr + _ehdr->e_shoff + index * _ehdr->e_shentsize ); return( index ); } } } return( 0 ); } void ElfModelImpl64::Elf64GetSectionOffsetAndSize( const std::string& sectionDescr, long& offset, long& size ) { long sectionIndex; parseSectionDescription( sectionDescr, sectionIndex ); Elf64_Shdr* section; if( sectionIndex != -1 ) { Elf64GetSectionByIndex( (Elf64_Half)sectionIndex, section ); } else { Elf64GetSectionByName( 1, sectionDescr.c_str(), section ); } if( section ) { offset = section->sh_offset; size = section->sh_size; } else { offset = 0; size = 0; std::cerr << "Invalid section definition: " << sectionDescr << std::endl; return; } } void ElfModelImpl64::Elf64GetSectionOffsetAndSize( const Elf64_Half& sectionIndex, long& offset, long& size ) { Elf64_Shdr* section; Elf64GetSectionByIndex( sectionIndex, section ); if( section ) { offset = section->sh_offset; size = section->sh_size; } else { offset = 0; size = 0; std::cerr << "Invalid section definition: " << sectionIndex << std::endl; return; } } void ElfModelImpl64::Elf64GetTotalSize( long& totalSize ) { totalSize = _ehdr->e_ehsize; totalSize += _ehdr->e_shnum * _ehdr->e_shentsize; for( Elf64_Half index = 0; index < _ehdr->e_shnum; index++ ) { if( SHT_NOBITS != ( (Elf64_Shdr*)( (char*)_ehdr + _ehdr->e_shoff + index * _ehdr->e_shentsize ) )->sh_type ) totalSize += ( (Elf64_Shdr*)( (char*)_ehdr + _ehdr->e_shoff + index * _ehdr->e_shentsize ) )->sh_size; } } void ElfModelImpl64::CheckFile() { if( Elf64HaveSectionTable() ) { long sectionsSize = 0; Elf64GetTotalSize( sectionsSize ); if( sectionsSize == _fileLength ) { std::cout << "Size of sections and file header matches file size" << std::endl; } else { std::cout << "There are " << _fileLength - sectionsSize << " bytes of bogus data in file" << std::endl; } } } void ElfModelImpl64::DisassembleSection( const std::string& sectionDescr, const bool showAddr = true ) { std::unordered_map<Elf64_Addr, Elf64_Sym*> elf64Syms; Elf64_Shdr* strtab; if( Elf64HaveSectionTable() ) { long offset, size, sectionIndex; Elf64_Half machine; parseSectionDescription( sectionDescr, sectionIndex ); Elf64GetSectionOffsetAndSize( sectionDescr, offset, size ); machine = _ehdr->e_machine; Elf64_Sym* symbol; Elf64_Shdr* symtab; if( sectionIndex == -1 ) { Elf64_Shdr* dummySection; sectionIndex = Elf64GetSectionByName( 1, sectionDescr.c_str(), dummySection ); } Elf64GetSectionByName( 1, ".strtab", strtab ); Elf64GetSectionByType( 1, SHT_SYMTAB, symtab ); for( Elf64_Word index = 0; index < symtab->sh_size / symtab->sh_entsize; index++ ) { if( ( symbol = Elf64GetSymbol( symtab, index ) ) != NULL ) elf64Syms.insert( std::make_pair( symbol->st_value, symbol ) ); } if( offset && size ) { csh handle; cs_arch arch; cs_mode mode; cs_insn *insn; size_t count; if( machine == EM_ARM ) { arch = CS_ARCH_ARM; mode = CS_MODE_ARM; } else if( machine == EM_X86_64 ) { arch = CS_ARCH_X86; mode = CS_MODE_64; } else // Unsupported machine return; try { if ( cs_open( arch, mode, &handle ) != CS_ERR_OK ) return; count = cs_disasm( handle, (const uint8_t*)( (char*)_ehdr + offset ), (size_t)size, 0, 0, &insn ); if ( count > 0 ) { for( size_t j = 0; j < count; j++ ) { showAddr ? std::cout << "0x" << std::hex << insn[j].address << ":" : std::cout << ""; if( elf64Syms.find( insn[j].address ) != elf64Syms.end() ) std::cout << Elf64GetName( elf64Syms[ insn[j].address ]->st_name, strtab ) << ":" << std::endl; std::cout << "\t\t" << insn[j].mnemonic; std::cout << "\t" << insn[j].op_str << std::endl; } cs_free( insn, count ); } else printf( "ERROR: Failed to disassemble given code!\n" ); cs_close( &handle ); } catch( std::exception &e ) { std::cerr << e.what() << std::endl; return; } } // Iterate and print keys and values of unordered_map // std::cout << "Sym map64: " << elf64Syms.size() << " entries" << std::endl; // for( const auto& n : elf64Syms ) { // std::cout << "Key:[" << n.first << "] Value:[" << (n.second)->st_name << "]\n"; // } } } void ElfModelImpl64::DisassembleFile( const bool showAddr = true ) { #if 0 unordered_map<Elf64_Addr, Elf64_Sym*> elf64Syms; Elf64_Shdr* strtab; if( Elf64HaveSectionTable() ) { long offset, size, sectionIndex; Elf64_Half machine; parseSectionDescription( sectionDescr, sectionIndex ); Elf64GetSectionOffsetAndSize( sectionDescr, offset, size ); machine = _ehdr->e_machine; Elf64_Sym* symbol; Elf64_Shdr* symtab; if( sectionIndex == -1 ) { Elf64_Shdr* dummySection; sectionIndex = Elf64GetSectionByName( 1, sectionDescr.c_str(), dummySection ); } Elf64GetSectionByName( 1, ".strtab", strtab ); Elf64GetSectionByType( 1, SHT_SYMTAB, symtab ); for( Elf64_Word index = 0; index < symtab->sh_size / symtab->sh_entsize; index++ ) { if( ( symbol = Elf64GetSymbol( symtab, index ) ) != NULL ) elf64Syms.insert( make_pair( symbol->st_value, symbol ) ); } if( offset && size ) { csh handle; cs_arch arch; cs_mode mode; cs_insn *insn; size_t count; if( machine == EM_ARM ) { arch = CS_ARCH_ARM; mode = CS_MODE_ARM; } else if( machine == EM_X86_64 ) { arch = CS_ARCH_X86; mode = CS_MODE_64; } else // Unsupported machine return; try { if ( cs_open( arch, mode, &handle ) != CS_ERR_OK ) return; count = cs_disasm( handle, (const uint8_t*)( (char*)_ehdr + offset ), (size_t)size, 0, 0, &insn ); if ( count > 0 ) { for( size_t j = 0; j < count; j++ ) { showAddr ? std::cout << "0x" << std::hex << insn[j].address << ":" : std::cout << ""; if( elf64Syms.find( insn[j].address ) != elf64Syms.end() ) std::cout << Elf64GetName( elf64Syms[ insn[j].address ]->st_name, strtab ) << ":" << std::endl; std::cout << "\t\t" << insn[j].mnemonic; std::cout << "\t" << insn[j].op_str << std::endl; } cs_free( insn, count ); } else printf( "ERROR: Failed to disassemble given code!\n" ); cs_close( &handle ); } catch( exception &e ) { std::cerr << e.what() << std::endl; return; } } // Iterate and print keys and values of unordered_map std::cout << "Sym map64: " << elf64Syms.size() << " entries" << std::endl; // for( const auto& n : elf64Syms ) { // std::cout << "Key:[" << n.first << "] Value:[" << (n.second)->st_name << "]\n"; // } } #endif } void ElfModelImpl64::DumpSection( const std::string& sectionDescr, const Dump_mode mode ) { if( Elf64HaveSectionTable() ) { long offset, size; Elf64GetSectionOffsetAndSize( sectionDescr, offset, size ); switch( mode ) { case DumpAsm: { asmDump ad( ( (char*)_ehdr + offset ), size ); std::cout << ad; break; } case DumpHex: { hexDump hd( ( (char*)_ehdr + offset ), size ); std::cout << hd; break; } case DumpRaw: { std::cout.write( ( (char*)_ehdr + offset ), size ); std::cout.flush(); break; } } } } void ElfModelImpl64::IterateRelocations( const std::string& s ) { } // Iterate 64bit elf file sections // void ElfModelImpl64::IterateSections() { Elf64_Shdr* section; Elf64_Shdr* shstrtab; Elf64GetSectionByIndex( _ehdr->e_shstrndx, shstrtab ); std::cout << "There are " << _ehdr->e_shnum << " section headers, starting at offset 0x" << std::hex << _ehdr->e_shoff << ':' << std::endl; // Resolve longest section name string size_t longestName = 0; for( Elf64_Half index = 0; index < _ehdr->e_shnum; index++ ) { Elf64GetSectionByIndex( index, section ); size_t tmpLen = strlen( Elf64GetName( section->sh_name, shstrtab ) ); if( longestName < tmpLen ) longestName = tmpLen; } // Resolve width for Nr field size_t nrWidth = numberFieldWidth( _ehdr->e_shnum ); try { for( Elf64_Half index = 0; index < _ehdr->e_shnum; index++ ) { Elf64GetSectionByIndex( index, section ); std::cout << " [" << std::setw( nrWidth ) << std::setfill( ' ' ) << std::dec << std::right << index << ']'; std::cout << ' ' << std::setw( longestName + 2 ) << std::setfill( ' ' ) << std::left << Elf64GetName( section->sh_name, shstrtab ); std::cout << ' ' << std::setw( 15 ) << std::setfill( ' ' ) << std::left << Elf::SHdr::sh_type.at( section->sh_type ); std::cout << " 0x" << std::setw( sizeof( section->sh_offset ) * 2 ) << std::setfill( '0' ) << std::hex << std::right << section->sh_offset; std::cout << " 0x" << std::setw( sizeof( section->sh_size ) * 2 ) << std::setfill( '0' ) << std::hex << std::right << section->sh_size; std::cout << ' ' << std::setw( 2 ) << std::setfill( ' ' ) << std::dec << std::right << section->sh_entsize; std::cout << ' ' << std::right << parseSectionFlags( section->sh_flags ); std::cout << ' ' << std::setw( nrWidth ) << std::setfill( ' ' ) << std::dec << std::right << section->sh_link; std::cout << ' ' << std::setw( nrWidth ) << std::setfill( ' ' ) << std::dec << std::right << section->sh_info; std::cout << ' ' << std::setw( 2 ) << std::setfill( ' ' ) << std::dec << std::right << section->sh_addralign; std::cout << std::endl; } } catch( std::exception& e ) { std::cerr << e.what() << ", error in matching section header numerical values to text" << std::endl; std::cerr << "Probable cause, definitions for section header num to text are outdated" << std::endl; } } // Iterate 64bit elf file symbol table // void ElfModelImpl64::IterateSymbols() { // Iterate symbol table Elf64_Shdr* symtab; Elf64_Shdr* shstrtab; Elf64GetSectionByIndex( _ehdr->e_shstrndx, shstrtab ); Elf64GetSectionByType( 1, SHT_SYMTAB, symtab ); if( symtab != NULL ) { size_t nrWidth = numberFieldWidth( symtab->sh_size / symtab->sh_entsize ); std::cout << "Symbol table " << Elf64GetName( symtab->sh_name, shstrtab ) << " contains " << symtab->sh_size / symtab->sh_entsize << " entries:" << std::endl; Elf64_Shdr* strtab; Elf64GetSectionByName( 1, ".strtab", strtab ); if( strtab != NULL ) { std::cout << " " << std::setw( nrWidth > strlen( "Num:") ? nrWidth : strlen( "Num:" ) ) << std::setfill( ' ' ) << std::right << "Num:"; std::cout << ' ' << std::setw( sizeof( Elf64_Addr ) * 2 ) << std::setfill( ' ' ) << std::right << "Value"; std::cout << ' ' << std::setw( 5 ) << std::setfill( ' ' ) << std::right << "Size"; std::cout << ' ' << std::setw( 10 ) << std::setfill( ' ' ) << std::left << "Type"; std::cout << ' ' << std::setw( 11 ) << std::setfill( ' ' ) << std::left << "Binding"; std::cout << ' ' << std::setw( 10 ) << std::setfill( ' ' ) << std::left << "Visib"; std::cout << ' ' << std::setw( 6 ) << std::setfill( ' ' ) << std::right << "Ndx"; std::cout << ' ' << std::left << "Name"; std::cout << std::endl; Elf64_Sym* symbol = (Elf64_Sym*)((char*)_ehdr + symtab->sh_offset ); try { for( Elf64_Word index = 0; index < symtab->sh_size / symtab->sh_entsize; index++, symbol++ ) { std::cout << ' ' << std::setw( nrWidth > strlen( "Num:") ? nrWidth : strlen( "Num:" ) ) << std::setfill( ' ' ) << std::dec << std::right << index << ':'; std::cout << ' ' << std::setw( sizeof( Elf64_Addr ) * 2 ) << std::setfill( '0' ) << std::hex << std::right << symbol->st_value; std::cout << ' ' << std::setw( 5 ) << std::setfill( ' ' ) << std::hex << std::right << symbol->st_size; std::cout << ' ' << std::setw( 10 ) << std::setfill( ' ' ) << std::left << Elf::Sym::sym_type.at( ELF64_ST_TYPE( symbol->st_info ) ); std::cout << ' ' << std::setw( 11 ) << std::setfill( ' ' ) << std::left << Elf::Sym::sym_bind.at( ELF64_ST_BIND( symbol->st_info ) ); std::cout << ' ' << std::setw( 10 ) << std::setfill( ' ' ) << std::left << Elf::Sym::sym_visib.at( ELF64_ST_VISIBILITY( symbol->st_other ) ); std::cout << ' ' << std::setw( 6 ) << std::setfill( ' ' ); ( symbol->st_shndx != 0 && symbol->st_shndx < SHN_LOPROC ) ? std::cout << std::dec << std::right << symbol->st_shndx : std::cout << std::right << Elf::Sym::sym_special_ndx.at( symbol->st_shndx ); std::cout << ' ' << Elf64GetName( symbol->st_name, strtab ); std::cout << std::endl; } } catch( std::exception& e ) { std::cerr << e.what() << ", error in matching symbol header numerical values to text" << std::endl; std::cerr << "Probable cause, definitions for symbol header num to text are outdated" << std::endl; } } } }
[ "nikkej@gmail.com" ]
nikkej@gmail.com
45d0bc6e34eb722e70f2c82e28444cbfa5154c7f
579f6399b3f8238eee552b8a70b5940db894a3eb
/pashin.fedor/A1/triangle.cpp
ebed4eeea60da14559f85e35c8671eeff1dce9ba
[]
no_license
a-kashirin-official/spbspu-labs-2018
9ac7b7abaa626d07497104f20f7ed7feb6359ecf
aac2bb38fe61c12114975f034b498a116e7075c3
refs/heads/master
2020-03-19T04:18:15.774227
2018-12-02T22:21:38
2018-12-02T22:21:38
135,814,536
0
0
null
null
null
null
UTF-8
C++
false
false
2,292
cpp
#include "triangle.hpp" #include <sstream> #include <math.h> using namespace std; Triangle::Triangle(point_t vertices[3]) { for (int i = 0; i < 3; i++) { vertices_[i] = vertices[i]; } } string Triangle::getInfo() const { stringstream info; const point_t center = getCenter(); info << "Type: Triangle" << endl << "Center coordinates: (" << center.x << "; " << center.y << ")" << endl; for (int i = 0; i < 3; i++) { info << "Vertex number " << i + 1 << " coordinates: (" << vertices_[i].x << "; " << vertices_[i].y << ")" << endl; } rectangle_t frame_rect = getFrameRect(); info << "Area: " << getArea() << endl << "Frame Rectangle:" << endl << "\t" << "Center coordinates: (" << frame_rect.pos.x << "; " << frame_rect.pos.y << ")" << endl << "\t" << "Width: " << frame_rect.width << endl << "\t" << "Height: " << frame_rect.height << endl; return info.str(); } double Triangle::getArea() const { return abs((vertices_[0].x * (vertices_[1].y - vertices_[2].y) + vertices_[1].x * (vertices_[2].y - vertices_[0].y) + vertices_[2].x * (vertices_[0].y - vertices_[1].y)) / 2); } rectangle_t Triangle::getFrameRect() const { double min_x = vertices_[0].x; double max_x = vertices_[0].x; double min_y = vertices_[0].y; double max_y = vertices_[0].y; for (const point_t& vertex: vertices_) { if (vertex.x < min_x) { min_x = vertex.x; } else if (vertex.x > max_x) { max_x = vertex.x; } if (vertex.y < min_y) { min_y = vertex.y; } else if (vertex.y > max_y) { max_y = vertex.y; } } return {{(min_x + max_x) / 2, (min_y + max_y) / 2}, (max_x - min_x), (max_y - min_y)}; } void Triangle::move(const point_t& new_center) { point_t center = getCenter(); double dx = new_center.x - center.x; double dy = new_center.y - center.y; for (point_t& vertex: vertices_) { vertex.x += dx; vertex.y += dy; } } void Triangle::move(double dx, double dy) { for (point_t& vertex: vertices_) { vertex.x += dx; vertex.y += dy; } } point_t Triangle::getCenter() const { return {(vertices_[0].x + vertices_[1].x + vertices_[2].x) / 3, (vertices_[0].y + vertices_[1].y + vertices_[2].y) / 3}; }
[ "a.kashirin.official@gmail.com" ]
a.kashirin.official@gmail.com
e904720265c4563b779ad085ae7ff40ab533f4cf
86648ccbd1cce95a95894f694fa01ea9c81509cc
/Object Oriented Programming Lab/9_SingleInheritance.cpp
7350598d44e62395591e245f66948a1ee84739ef
[]
no_license
crpytoscooby/College-Assignment
df4f380d61eaa855dc1b415bf96261ee053aacfa
e6adb36a58218e225b26726646659374d1d103b4
refs/heads/main
2023-08-07T12:46:43.543599
2021-10-08T11:45:22
2021-10-08T11:45:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
420
cpp
#include<iostream> using namespace std; class Vehicle // Vehicle is a Base Class or a Parent Class { public: Vehicle() { cout<<"Vehicle Class is Called\n"; } }; class Car:public Vehicle // Car is a Derived Class or a Child Class { public: Car() { cout<<"Car Class is Called\n"; } }; int main() { Car obj; // Creating the object of base class return 0; }
[ "denzil.s.samuel@gmail.com" ]
denzil.s.samuel@gmail.com
54da6d82a407d509ee0fdb390804771f1efeb931
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5751500831719424_0/C++/nsv/A.cpp
ff686a5d236181109ddb0e61215e56640f2cd0ba
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
3,428
cpp
#if 1 #include <functional> #include <algorithm> #include <iostream> #include <iterator> #include <iomanip> #include <sstream> #include <numeric> #include <string> #include <vector> #include <bitset> #include <queue> #include <stack> #include <map> #include <set> #include <cstdlib> #include <cassert> #include <cstring> #include <cstdio> #include <cmath> #include <ctime> #include <list> using namespace std; typedef long long LL; typedef long double LD; typedef pair<int, int> pii; const LD eps = 1e-9; const LD pi = acos(-1.0); const LL inf = 1e+9; #define mp make_pair #define pb push_back #define X first #define Y second #define dbg(x) { cerr << #x << " = " << x << endl; } // extended template #pragma comment(linker, "/STACK:36777216") typedef vector<int> vi; typedef vector<vi> vvi; #define forn(i, n) for (int i = 0; i < n; ++i) #define all(a) (a).begin(), (a).end() #define rall(a) (a).rbegin(), (a).rend() template<typename T> istream & operator >> (istream &, vector<T> &); template<typename T> ostream & operator << (ostream &, const vector<T> &); #define START clock_t _clock = clock(); #define END cerr << endl << "time: " << (clock() - _clock) / LD(CLOCKS_PER_SEC) << endl; #define NAME "problem" pair<string, vi> zip(string s) { s += '#'; vi v; string r; int pos = 0; forn(i, s.length()) { if (i > 0 && s[i - 1] != s[i]) { r += s[i - 1]; v.push_back(i - pos); pos = i; } } return mp(r, v); } void test() { string s = "abbcca"; dbg(zip(s).X); dbg(zip(s).Y); exit(0); } void solve(int test) { int n; cin >> n; vector<string> a(n); cin >> a; vector<string> ss(n); vvi lens(n); forn(i, n) { auto tmp = zip(a[i]); ss[i] = tmp.X; lens[i] = tmp.Y; } cout << "Case #" << test << ": "; forn(i, n - 1) if (ss[i] != ss[i + 1]) { cout << "Fegla Won" << endl; return; } int res = 0; forn(i, lens[0].size()) { vi t; forn(j, n) t.push_back(lens[j][i]); int mn = *min_element(all(t)); int mx = *max_element(all(t)); int mn_cur = -1; for (int z = mn; z <= mx; ++z) { int cur = 0; forn(j, t.size()) cur += abs(t[j] - z); if (mn_cur == -1 || cur < mn_cur) mn_cur = cur; } mn_cur = max(0, mn_cur); res += mn_cur; } cout << res << endl; } int main() { //test(); START // freopen(NAME ".in", "r", stdin); freopen(NAME ".out", "w", stdout); freopen("A-small-attempt0.in", "r", stdin); freopen("output.txt", "w", stdout); ios_base::sync_with_stdio(false); int t; cin >> t; forn(i, t) solve(i + 1); END return 0; } /******************************************* *******************************************/ template<typename T> istream & operator >> (istream &is, vector<T> &v) { forn(i, v.size()) is >> v[i]; return is; } template<typename T> ostream & operator << (ostream &os, const vector<T> &v) { forn(i, v.size()) os << v[i] << " "; return os; } #endif
[ "eewestman@gmail.com" ]
eewestman@gmail.com
6f28463ca8700575027cf1e365fd6e2d90e24efd
4111b4943472b96bf4aaa04c5d61f35ec0b9011b
/gecode/set/rel/common.hpp
746e090e9d85d664a10e929f66566a9c2d71fe10
[ "MIT" ]
permissive
jahewson/gecode
3862ed7ac48124bbb5d16ddd39aa2803aacaf145
91f3bbeafe96ec7172aeb5417f624109143415bb
refs/heads/master
2020-05-17T01:51:26.270717
2013-02-11T19:40:23
2013-02-11T19:40:23
6,619,246
0
1
null
null
null
null
UTF-8
C++
false
false
4,337
hpp
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <tack@gecode.org> * Christian Schulte <schulte@gecode.org> * * Contributing authors: * Gabor Szokoli <szokoli@gecode.org> * * Copyright: * Guido Tack, 2004 * Christian Schulte, 2004 * Gabor Szokoli, 2004 * * Last modified: * $Date: 2010-06-02 10:00:04 +0100 (Wed, 02 Jun 2010) $ by $Author: schulte $ * $Revision: 11004 $ * * This file is part of Gecode, the generic constraint * development environment: * http://www.gecode.org * * 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. * */ #define GECODE_SET_ME_CHECK_VAL(p,f) { \ ModEvent __me__ ## __LINE__ = (p); \ if (me_failed(__me__ ## __LINE__)) return ES_FAILED; \ if (ME_GEN_ASSIGNED==(__me__ ## __LINE__))f=true; } #define GECODE_SET_ME_CHECK_VAL_B(modified, tell, f) \ { \ ModEvent me = (tell); \ modified |= me_modified(me); \ if (ME_GEN_ASSIGNED==(me))f=true; \ GECODE_ME_CHECK(me); \ } namespace Gecode { namespace Set { namespace Rel { forceinline bool subsumesME(ModEvent me0, ModEvent me1, ModEvent me2, ModEvent me) { ModEvent cme = SetVarImp::me_combine(me0,SetVarImp::me_combine(me1, me2)); return SetVarImp::me_combine(cme, me)==cme; } forceinline bool subsumesME(ModEvent me0, ModEvent me1, ModEvent me) { ModEvent cme = SetVarImp::me_combine(me0, me1); return SetVarImp::me_combine(cme, me)==cme; } forceinline bool subsumesME(ModEvent me0, ModEvent me) { return SetVarImp::me_combine(me0, me)==me0; } forceinline bool testSetEventLB(ModEvent me0, ModEvent me1, ModEvent me2) { return subsumesME(me0, me1, me2, ME_SET_GLB); } forceinline bool testSetEventUB(ModEvent me0, ModEvent me1, ModEvent me2) { return subsumesME(me0, me1, me2, ME_SET_LUB); } forceinline bool testSetEventAnyB(ModEvent me0, ModEvent me1, ModEvent me2) { return ( me0!=ME_SET_CARD || me1!=ME_SET_CARD || me2!=ME_SET_CARD ); } forceinline bool testSetEventCard(ModEvent me0, ModEvent me1, ModEvent me2) { return subsumesME(me0, me1, me2, ME_SET_CARD); } forceinline bool testSetEventLB(ModEvent me0, ModEvent me1) { return subsumesME(me0, me1, ME_SET_GLB); } forceinline bool testSetEventUB(ModEvent me0, ModEvent me1) { return subsumesME(me0, me1, ME_SET_LUB); } forceinline bool testSetEventAnyB(ModEvent me0, ModEvent me1) { return ( me0!=ME_SET_CARD || me1!=ME_SET_CARD ); } forceinline bool testSetEventCard(ModEvent me0, ModEvent me1) { return subsumesME(me0, me1, ME_SET_CARD); } forceinline bool testSetEventLB(ModEvent me0) { return subsumesME(me0, ME_SET_GLB); } forceinline bool testSetEventUB(ModEvent me0) { return subsumesME(me0, ME_SET_LUB); } forceinline bool testSetEventAnyB(ModEvent me0) { return ( me0!=ME_SET_CARD ); } forceinline bool testSetEventCard(ModEvent me0) { return subsumesME(me0, ME_SET_CARD); } }}} // STATISTICS: set-prop
[ "john@jahewson.com" ]
john@jahewson.com
a9dcf6997190eb430baae50be29b571a0b7ead20
aaff0a475ba8195d622b6989c089ba057f180d54
/backup/2/leetcode/c++/balance-a-binary-search-tree.cpp
81f7d52eea43d9be3e56f15537253aa25f91a54c
[ "Apache-2.0" ]
permissive
DandelionLU/code-camp
328b2660391f1b529f1187a87c41e15a3eefb3ee
0fd18432d0d2c4123b30a660bae156283a74b930
refs/heads/master
2023-08-24T00:01:48.900746
2021-10-30T06:37:42
2021-10-30T06:37:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,728
cpp
// Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site . // For this specific algothmic problem, visit my Youtube Video : . // It's fascinating to solve algothmic problems, follow Yanzhan to learn more! // Blog URL for this problem: https://yanzhan.site/leetcode/balance-a-binary-search-tree.html . /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *balanceBST(TreeNode *root) { vector<int> nums = flatten(root); sort(nums.begin(), nums.end()); return construct(nums, 0, nums.size() - 1); } TreeNode *construct(vector<int> &nums, int start, int end) { if (start > end) { return nullptr; } int half = (start + end) / 2; auto head = new TreeNode(nums[half]); auto left = construct(nums, start, half - 1); auto right = construct(nums, half + 1, end); head->left = left; head->right = right; return head; } vector<int> flatten(TreeNode *root) { if (root == nullptr) { return vector<int>(); } auto res = flatten(root->left); auto rights = flatten(root->right); res.push_back(root->val); res.insert(res.end(), rights.begin(), rights.end()); return res; } };
[ "yangyanzhan@gmail.com" ]
yangyanzhan@gmail.com
e43b58d4475c8f47f798586939e18b0df36869e8
21d95c8e302242eb03e334d97ff51b9fee8fff90
/server/src/_jMetalCpp/main/CMAES_main.cpp
4900848c0d2e8d870f872e41b35ddd90d1f35057
[]
no_license
nszknao/master
8e909336476efba112e27bd5c4478373a191db12
ef7fd255209e7ef3d63a483ae03a55b54727a194
refs/heads/master
2023-04-30T16:23:17.485757
2023-04-26T07:26:17
2023-04-26T07:26:17
45,908,367
1
0
null
null
null
null
UTF-8
C++
false
false
2,384
cpp
// CMAES_main.cpp // // Author: // Esteban López-Camacho <esteban@lcc.uma.es> // // Copyright (c) 2011 Antonio J. Nebro, Juan J. Durillo // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #include <Problem.h> #include <Algorithm.h> #include <Solution.h> #include <ProblemFactory.h> #include <iostream> #include <CMAES.h> #include <time.h> int main(int argc, char ** argv) { clock_t t_ini, t_fin; Problem * problem ; // The problem to solve Algorithm * algorithm ; // The algorithm to use if (argc>=2) { problem = ProblemFactory::getProblem(argc, argv); cout << "Selected problem: " << problem->getName() << endl; } else { cout << "No problem selected." << endl; cout << "Default problem will be used: Sphere" << endl; problem = ProblemFactory::getProblem(const_cast<char *>("Sphere")); } algorithm = new CMAES(problem); // Algorithm parameters int populationSizeValue = 20; int maxEvaluationsValue = 1000000; algorithm->setInputParameter("populationSize",&populationSizeValue); algorithm->setInputParameter("maxEvaluations",&maxEvaluationsValue); // Add the indicator object to the algorithm //algorithm->setInputParameter("indicators", indicators) ; // Execute the Algorithm t_ini = clock(); SolutionSet * population = algorithm->execute(); t_fin = clock(); double secs = (double) (t_fin - t_ini); secs = secs / CLOCKS_PER_SEC; // Result messages cout << "Total execution time: " << secs << "s" << endl; cout << "Variables values have been written to file VAR" << endl; population->printVariablesToFile("VAR"); cout << "Objectives values have been written to file FUN" << endl; population->printObjectivesToFile("FUN"); delete population; delete algorithm; } // main
[ "iloilo_has@yahoo.co.jp" ]
iloilo_has@yahoo.co.jp
8cced78d563f739a1097ca3a175a34901b2707cf
1fdbb7e551cf8b52b43359cf406bedd969b5f59f
/include/common/gettimeofday.h
0ad6aa085e1f6fc7830bd5f656d710d3adbdca10
[]
no_license
trigrass2/eview-server
1292958416ebe772ff4ce0b1f1639c65ca13ce92
a5e452016a730af79a1d402a3d918403eb6073aa
refs/heads/master
2023-06-17T09:38:25.004889
2021-07-15T09:45:56
2021-07-15T09:45:56
null
0
0
null
null
null
null
GB18030
C++
false
false
935
h
#ifndef _GETTIMEOFDAY_TCNT_H_ #define _GETTIMEOFDAY_TCNT_H_ #include <ace/OS_NS_sys_time.h> #include <ace/High_Res_Timer.h> namespace CVLibHead { //#ifdef _WIN32 static ACE_Time_Value gettimeofday_tickcnt() { return ACE_High_Res_Timer::gettimeofday_hr(); // 避免修改系统时间造成不良影响 } /* static ACE_UINT32 nLastTickCount = 0; static ACE_UINT32 nTickCountSwitch = 0; ACE_UINT64 nTickCount64; ACE_UINT32 nTickCount = GetTickCount(); if (nLastTickCount > nTickCount) { nTickCountSwitch ++; } nLastTickCount = nTickCount; nTickCount64 = nTickCountSwitch; nTickCount64 = nTickCount64 << 32; nTickCount64 += nTickCount; return ACE_Time_Value( (ACE_UINT32)(nTickCount64/1000), (ACE_UINT32)(nTickCount64%1000 * 1000)); //return tv; } #else inline ACE_Time_Value gettimeofday_tickcnt() { return ACE_OS::gettimeofday(); } */ //#endif//_WIN32 } // namespace CVLibHead #endif//_GETTIMEOFDAY_TCNT_H_
[ "746257224@qq.com" ]
746257224@qq.com
06208f7c47c82dc84a909f0d17457bab4b3090a0
f9aac22297568f3be224b2623c982acc6f78ecdb
/bjfu_oj/249_Ackermann.cpp
54de95272f74bc9c28b8c4cffa080064fa8d8889
[]
no_license
CuriousLei/cppcode
b0ab0d4200735b8db3f6bcb5572b2c107219314f
b26160772a82a8b5a60752b4191eef29f8e17818
refs/heads/master
2020-04-16T12:58:31.545127
2019-08-12T07:34:03
2019-08-12T07:34:03
165,604,528
0
0
null
null
null
null
IBM852
C++
false
false
380
cpp
//Ackermann║»╩řÁ─ÁŢ╣ÚăˇÍÁ #include"iostream" using namespace std; int ackermann(int m,int n){ if(m==0){ cout<<n+1<<endl; return n+1; }else if(n==0){ return ackermann(m-1,1); }else{ return ackermann(m-1,ackermann(m,n-1)); } } int main (){ int m,n; while(1){ cin>>m>>n; if(m==0&&n==0){ break; } cout<<ackermann(m,n)<<endl; } return 0; }
[ "bjfuleida@126.com" ]
bjfuleida@126.com
c1ab080527cbfd9fcf7d1f835b6247f84dad7816
f3c2cc5754c47aac12db087995ee7bdccc09588f
/logger.cpp
0bf0ae3bbbd37e9d656a87dd63da808e5f087b02
[]
no_license
friverosy/Fiordo-Austral
64f76f37bb21f7620a8456770f3e8aeeb1e498e8
1a5c6b28e4a48a06e2b812a932e2e95553a6028a
refs/heads/master
2021-08-28T16:25:45.835571
2016-08-17T18:07:27
2016-08-17T18:07:27
114,008,886
0
0
null
null
null
null
UTF-8
C++
false
false
1,145
cpp
#include "logger.h" #include "ui_logger.h" #include "connection.h" #include <QFile> #include <QTextStream> #include <QMessageBox> #include <QDateTime> Logger::Logger(QWidget *parent) : QDialog(parent), ui(new Ui::Logger) { ui->setupUi(this); QFile file("./comboscan.log"); if(file.open(QFile::ReadOnly|QFile::Truncate)){ QTextStream in(&file); QString text = in.readAll(); file.close(); ui->plainTextEdit->setPlainText(text); } else { QMessageBox::critical(this, tr("ERROR"), tr("Error al leer log, este no existe")); } } void Logger::insert2Logger(const QString rut_user, const QString level, const QString event) { QFile fileName("comboscan.log"); if(fileName.open(QIODevice::WriteOnly | QIODevice::Append)) { QTextStream textStream(&fileName); QDateTime currentDateTime = QDateTime::currentDateTime(); textStream << currentDateTime.toString("yyyy-MM-dd h:m:s") << level << rut_user+": " << event << "\n"; fileName.close(); } else qDebug()<<"log file not found"; } Logger::~Logger() { delete ui; }
[ "pala_jdrums69tsd@hotmail.com" ]
pala_jdrums69tsd@hotmail.com
aa9926c398312a9ca28e11964fda2bd4a99e8928
e62ee12fded9e3022010edc3bad99d5913a9cad6
/Classes/vgc/GameControllerDpad.h
108ff124b60a5b3abfb65f031fccf25e60da3567
[]
no_license
thibetabc/gloudhelper
309698c5018363cb479f1e47f8b4354c582e22fb
16776e0651e3323eac30579d1a22f71ce49c7f4f
refs/heads/HuangFeng
2021-01-15T15:42:55.937723
2016-08-18T08:41:24
2016-08-18T08:41:24
52,324,439
0
0
null
2016-04-17T15:21:32
2016-02-23T02:48:48
C++
UTF-8
C++
false
false
2,001
h
#ifndef __GAMECONTROLLERDPAD_H__ #define __GAMECONTROLLERDPAD_H__ #include "GameControllerDef.h" NS_CC_BEGIN namespace ui { class GameControllerDpad : public ImageView { public: virtual ~GameControllerDpad(); CREATE_FUNC(GameControllerDpad); void setObject(GameControllerDef::OBJECT objup, GameControllerDef::OBJECT objdown, GameControllerDef::OBJECT objleft, GameControllerDef::OBJECT objright); void loadTextures(const std::string & bg, const std::string & normal, const std::string & press, \ const std::string & upnormal, const std::string & uppress, const std::string & downnormal, const std::string & downpress, \ const std::string & leftnormal, const std::string & leftpress, const std::string & rightnormal, const std::string & rightpress); void addDpadEventListener(std::function<void(GameControllerDef::OBJECT, GameControllerDef::EVENT, float)> handler); protected: GameControllerDpad(); virtual bool init(); virtual void onEnter(); virtual void onExit(); private: float _blind = 0.2f; GameControllerDef::TYPE _type = GameControllerDef::TYPE::DPAD; GameControllerDef::OBJECT _objup = GameControllerDef::OBJECT::DPAD_UP; GameControllerDef::OBJECT _objdown = GameControllerDef::OBJECT::DPAD_DOWN; GameControllerDef::OBJECT _objleft = GameControllerDef::OBJECT::DPAD_LEFT; GameControllerDef::OBJECT _objright = GameControllerDef::OBJECT::DPAD_RIGHT; std::function<void(GameControllerDef::OBJECT, GameControllerDef::EVENT, float)> _handler = nullptr; Button * _effect = nullptr; Button * _up = nullptr; bool _upbright = false; Button * _down = nullptr; bool _downbright = false; Button * _left = nullptr; bool _leftbright = false; Button * _right = nullptr; bool _rightbright = false; }; }; NS_CC_END #endif
[ "panyumiao@panyumiaodeMacBook-Pro.local" ]
panyumiao@panyumiaodeMacBook-Pro.local
99f595e9ae837f0b7e2c4dd0d534b4e13f9c9fe4
746bf62ae3599f0d2dcd620ae37cd11370733cc3
/network/SimpleSniffer/SimpleSniffer/StdAfx.cpp
e6e78f96ad07a87d130382dc579808cea4d5f3f6
[]
no_license
wanglinjie/coding
ec0e614343b39dc02191455165eb1a5c9e6747ce
350f28cad5ec384df476f6403cb7a7db419de329
refs/heads/master
2021-04-22T14:00:48.825959
2017-05-02T12:49:05
2017-05-02T12:49:05
48,011,510
0
0
null
null
null
null
UTF-8
C++
false
false
215
cpp
// stdafx.cpp : source file that includes just the standard includes // SimpleSniffer.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ "hitwhwlj@163.com" ]
hitwhwlj@163.com
d50d90a680cc9baf201b59697ad0caf7a59b3934
9945fe4e4556c630e991d6783082ad233b811972
/src/qt/sagbitgui.cpp
e03f9e7a3851e5a8a0955d4086139f53db94a457
[ "MIT" ]
permissive
mirzaei-ce/linux-sagbit
17e77a538683fc2a8f9112bedb7e825dda9722d1
3671bc665897d3ff7856d634344654ea2865cee0
refs/heads/master
2021-08-23T09:06:40.952584
2017-12-04T12:24:59
2017-12-04T12:24:59
113,039,244
0
0
null
null
null
null
UTF-8
C++
false
false
40,629
cpp
// Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "sagbitgui.h" #include "sagbitunits.h" #include "clientmodel.h" #include "guiconstants.h" #include "guiutil.h" #include "networkstyle.h" #include "notificator.h" #include "openuridialog.h" #include "optionsdialog.h" #include "optionsmodel.h" #include "platformstyle.h" #include "rpcconsole.h" #include "utilitydialog.h" #ifdef ENABLE_WALLET #include "walletframe.h" #include "walletmodel.h" #endif // ENABLE_WALLET #ifdef Q_OS_MAC #include "macdockiconhandler.h" #endif #include "init.h" #include "ui_interface.h" #include "util.h" #include <iostream> #include <QAction> #include <QApplication> #include <QDateTime> #include <QDesktopWidget> #include <QDragEnterEvent> #include <QListWidget> #include <QMenuBar> #include <QMessageBox> #include <QMimeData> #include <QProgressBar> #include <QProgressDialog> #include <QSettings> #include <QShortcut> #include <QStackedWidget> #include <QStatusBar> #include <QStyle> #include <QTimer> #include <QToolBar> #include <QVBoxLayout> #if QT_VERSION < 0x050000 #include <QTextDocument> #include <QUrl> #else #include <QUrlQuery> #endif const std::string SagbitGUI::DEFAULT_UIPLATFORM = #if defined(Q_OS_MAC) "macosx" #elif defined(Q_OS_WIN) "windows" #else "other" #endif ; const QString SagbitGUI::DEFAULT_WALLET = "~Default"; SagbitGUI::SagbitGUI(const PlatformStyle *platformStyle, const NetworkStyle *networkStyle, QWidget *parent) : QMainWindow(parent), clientModel(0), walletFrame(0), unitDisplayControl(0), labelEncryptionIcon(0), labelConnectionsIcon(0), labelBlocksIcon(0), progressBarLabel(0), progressBar(0), progressDialog(0), appMenuBar(0), overviewAction(0), historyAction(0), quitAction(0), sendCoinsAction(0), sendCoinsMenuAction(0), usedSendingAddressesAction(0), usedReceivingAddressesAction(0), signMessageAction(0), verifyMessageAction(0), aboutAction(0), receiveCoinsAction(0), receiveCoinsMenuAction(0), optionsAction(0), toggleHideAction(0), encryptWalletAction(0), backupWalletAction(0), changePassphraseAction(0), aboutQtAction(0), openRPCConsoleAction(0), openAction(0), showHelpMessageAction(0), trayIcon(0), trayIconMenu(0), notificator(0), rpcConsole(0), helpMessageDialog(0), prevBlocks(0), spinnerFrame(0), platformStyle(platformStyle) { GUIUtil::restoreWindowGeometry("nWindow", QSize(850, 550), this); QString windowTitle = tr("Sagbit Core") + " - "; #ifdef ENABLE_WALLET /* if compiled with wallet support, -disablewallet can still disable the wallet */ enableWallet = !GetBoolArg("-disablewallet", false); #else enableWallet = false; #endif // ENABLE_WALLET if(enableWallet) { windowTitle += tr("Wallet"); } else { windowTitle += tr("Node"); } windowTitle += " " + networkStyle->getTitleAddText(); #ifndef Q_OS_MAC QApplication::setWindowIcon(networkStyle->getTrayAndWindowIcon()); setWindowIcon(networkStyle->getTrayAndWindowIcon()); #else MacDockIconHandler::instance()->setIcon(networkStyle->getAppIcon()); #endif setWindowTitle(windowTitle); #if defined(Q_OS_MAC) && QT_VERSION < 0x050000 // This property is not implemented in Qt 5. Setting it has no effect. // A replacement API (QtMacUnifiedToolBar) is available in QtMacExtras. setUnifiedTitleAndToolBarOnMac(true); #endif rpcConsole = new RPCConsole(platformStyle, 0); helpMessageDialog = new HelpMessageDialog(this, false); #ifdef ENABLE_WALLET if(enableWallet) { /** Create wallet frame and make it the central widget */ walletFrame = new WalletFrame(platformStyle, this); setCentralWidget(walletFrame); } else #endif // ENABLE_WALLET { /* When compiled without wallet or -disablewallet is provided, * the central widget is the rpc console. */ setCentralWidget(rpcConsole); } // Accept D&D of URIs setAcceptDrops(true); // Create actions for the toolbar, menu bar and tray/dock icon // Needs walletFrame to be initialized createActions(); // Create application menu bar createMenuBar(); // Create the toolbars createToolBars(); // Create system tray icon and notification createTrayIcon(networkStyle); // Create status bar statusBar(); // Disable size grip because it looks ugly and nobody needs it statusBar()->setSizeGripEnabled(false); // Status bar notification icons QFrame *frameBlocks = new QFrame(); frameBlocks->setContentsMargins(0,0,0,0); frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks); frameBlocksLayout->setContentsMargins(3,0,3,0); frameBlocksLayout->setSpacing(3); unitDisplayControl = new UnitDisplayStatusBarControl(platformStyle); labelEncryptionIcon = new QLabel(); labelConnectionsIcon = new QLabel(); labelBlocksIcon = new QLabel(); if(enableWallet) { frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(unitDisplayControl); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelEncryptionIcon); } frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelConnectionsIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelBlocksIcon); frameBlocksLayout->addStretch(); // Progress bar and label for blocks download progressBarLabel = new QLabel(); progressBarLabel->setVisible(false); progressBar = new GUIUtil::ProgressBar(); progressBar->setAlignment(Qt::AlignCenter); progressBar->setVisible(false); // Override style sheet for progress bar for styles that have a segmented progress bar, // as they make the text unreadable (workaround for issue #1071) // See https://qt-project.org/doc/qt-4.8/gallery.html QString curStyle = QApplication::style()->metaObject()->className(); if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle") { progressBar->setStyleSheet("QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }"); } statusBar()->addWidget(progressBarLabel); statusBar()->addWidget(progressBar); statusBar()->addPermanentWidget(frameBlocks); // Install event filter to be able to catch status tip events (QEvent::StatusTip) this->installEventFilter(this); // Initially wallet actions should be disabled setWalletActionsEnabled(false); // Subscribe to notifications from core subscribeToCoreSignals(); } SagbitGUI::~SagbitGUI() { // Unsubscribe from notifications from core unsubscribeFromCoreSignals(); GUIUtil::saveWindowGeometry("nWindow", this); if(trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu) trayIcon->hide(); #ifdef Q_OS_MAC delete appMenuBar; MacDockIconHandler::cleanup(); #endif delete rpcConsole; } void SagbitGUI::createActions() { QActionGroup *tabGroup = new QActionGroup(this); overviewAction = new QAction(platformStyle->SingleColorIcon(":/icons/overview"), tr("&Overview"), this); overviewAction->setStatusTip(tr("Show general overview of wallet")); overviewAction->setToolTip(overviewAction->statusTip()); overviewAction->setCheckable(true); overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1)); tabGroup->addAction(overviewAction); sendCoinsAction = new QAction(platformStyle->SingleColorIcon(":/icons/send"), tr("&Send"), this); sendCoinsAction->setStatusTip(tr("Send coins to a Sagbit address")); sendCoinsAction->setToolTip(sendCoinsAction->statusTip()); sendCoinsAction->setCheckable(true); sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2)); tabGroup->addAction(sendCoinsAction); sendCoinsMenuAction = new QAction(platformStyle->TextColorIcon(":/icons/send"), sendCoinsAction->text(), this); sendCoinsMenuAction->setStatusTip(sendCoinsAction->statusTip()); sendCoinsMenuAction->setToolTip(sendCoinsMenuAction->statusTip()); receiveCoinsAction = new QAction(platformStyle->SingleColorIcon(":/icons/receiving_addresses"), tr("&Receive"), this); receiveCoinsAction->setStatusTip(tr("Request payments (generates QR codes and sagbit: URIs)")); receiveCoinsAction->setToolTip(receiveCoinsAction->statusTip()); receiveCoinsAction->setCheckable(true); receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3)); tabGroup->addAction(receiveCoinsAction); receiveCoinsMenuAction = new QAction(platformStyle->TextColorIcon(":/icons/receiving_addresses"), receiveCoinsAction->text(), this); receiveCoinsMenuAction->setStatusTip(receiveCoinsAction->statusTip()); receiveCoinsMenuAction->setToolTip(receiveCoinsMenuAction->statusTip()); historyAction = new QAction(platformStyle->SingleColorIcon(":/icons/history"), tr("&Transactions"), this); historyAction->setStatusTip(tr("Browse transaction history")); historyAction->setToolTip(historyAction->statusTip()); historyAction->setCheckable(true); historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4)); tabGroup->addAction(historyAction); #ifdef ENABLE_WALLET // These showNormalIfMinimized are needed because Send Coins and Receive Coins // can be triggered from the tray menu, and need to show the GUI to be useful. connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage())); connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage())); connect(sendCoinsMenuAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(sendCoinsMenuAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage())); connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage())); connect(receiveCoinsMenuAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(receiveCoinsMenuAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage())); connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage())); #endif // ENABLE_WALLET quitAction = new QAction(platformStyle->TextColorIcon(":/icons/quit"), tr("E&xit"), this); quitAction->setStatusTip(tr("Quit application")); quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q)); quitAction->setMenuRole(QAction::QuitRole); aboutAction = new QAction(platformStyle->TextColorIcon(":/icons/about"), tr("&About Sagbit Core"), this); aboutAction->setStatusTip(tr("Show information about Sagbit Core")); aboutAction->setMenuRole(QAction::AboutRole); aboutQtAction = new QAction(platformStyle->TextColorIcon(":/icons/about_qt"), tr("About &Qt"), this); aboutQtAction->setStatusTip(tr("Show information about Qt")); aboutQtAction->setMenuRole(QAction::AboutQtRole); optionsAction = new QAction(platformStyle->TextColorIcon(":/icons/options"), tr("&Options..."), this); optionsAction->setStatusTip(tr("Modify configuration options for Sagbit Core")); optionsAction->setMenuRole(QAction::PreferencesRole); toggleHideAction = new QAction(platformStyle->TextColorIcon(":/icons/about"), tr("&Show / Hide"), this); toggleHideAction->setStatusTip(tr("Show or hide the main Window")); encryptWalletAction = new QAction(platformStyle->TextColorIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this); encryptWalletAction->setStatusTip(tr("Encrypt the private keys that belong to your wallet")); encryptWalletAction->setCheckable(true); backupWalletAction = new QAction(platformStyle->TextColorIcon(":/icons/filesave"), tr("&Backup Wallet..."), this); backupWalletAction->setStatusTip(tr("Backup wallet to another location")); changePassphraseAction = new QAction(platformStyle->TextColorIcon(":/icons/key"), tr("&Change Passphrase..."), this); changePassphraseAction->setStatusTip(tr("Change the passphrase used for wallet encryption")); signMessageAction = new QAction(platformStyle->TextColorIcon(":/icons/edit"), tr("Sign &message..."), this); signMessageAction->setStatusTip(tr("Sign messages with your Sagbit addresses to prove you own them")); verifyMessageAction = new QAction(platformStyle->TextColorIcon(":/icons/verify"), tr("&Verify message..."), this); verifyMessageAction->setStatusTip(tr("Verify messages to ensure they were signed with specified Sagbit addresses")); openRPCConsoleAction = new QAction(platformStyle->TextColorIcon(":/icons/debugwindow"), tr("&Debug window"), this); openRPCConsoleAction->setStatusTip(tr("Open debugging and diagnostic console")); usedSendingAddressesAction = new QAction(platformStyle->TextColorIcon(":/icons/address-book"), tr("&Sending addresses..."), this); usedSendingAddressesAction->setStatusTip(tr("Show the list of used sending addresses and labels")); usedReceivingAddressesAction = new QAction(platformStyle->TextColorIcon(":/icons/address-book"), tr("&Receiving addresses..."), this); usedReceivingAddressesAction->setStatusTip(tr("Show the list of used receiving addresses and labels")); openAction = new QAction(platformStyle->TextColorIcon(":/icons/open"), tr("Open &URI..."), this); openAction->setStatusTip(tr("Open a sagbit: URI or payment request")); showHelpMessageAction = new QAction(platformStyle->TextColorIcon(":/icons/info"), tr("&Command-line options"), this); showHelpMessageAction->setMenuRole(QAction::NoRole); showHelpMessageAction->setStatusTip(tr("Show the Sagbit Core help message to get a list with possible Sagbit command-line options")); connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked())); connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt())); connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked())); connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden())); connect(showHelpMessageAction, SIGNAL(triggered()), this, SLOT(showHelpMessageClicked())); connect(openRPCConsoleAction, SIGNAL(triggered()), this, SLOT(showDebugWindow())); // prevents an open debug window from becoming stuck/unusable on client shutdown connect(quitAction, SIGNAL(triggered()), rpcConsole, SLOT(hide())); #ifdef ENABLE_WALLET if(walletFrame) { connect(encryptWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(encryptWallet(bool))); connect(backupWalletAction, SIGNAL(triggered()), walletFrame, SLOT(backupWallet())); connect(changePassphraseAction, SIGNAL(triggered()), walletFrame, SLOT(changePassphrase())); connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab())); connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab())); connect(usedSendingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedSendingAddresses())); connect(usedReceivingAddressesAction, SIGNAL(triggered()), walletFrame, SLOT(usedReceivingAddresses())); connect(openAction, SIGNAL(triggered()), this, SLOT(openClicked())); } #endif // ENABLE_WALLET new QShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_C), this, SLOT(showDebugWindowActivateConsole())); new QShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_D), this, SLOT(showDebugWindow())); } void SagbitGUI::createMenuBar() { #ifdef Q_OS_MAC // Create a decoupled menu bar on Mac which stays even if the window is closed appMenuBar = new QMenuBar(); #else // Get the main window's menu bar on other platforms appMenuBar = menuBar(); #endif // Configure the menus QMenu *file = appMenuBar->addMenu(tr("&File")); if(walletFrame) { file->addAction(openAction); file->addAction(backupWalletAction); file->addAction(signMessageAction); file->addAction(verifyMessageAction); file->addSeparator(); file->addAction(usedSendingAddressesAction); file->addAction(usedReceivingAddressesAction); file->addSeparator(); } file->addAction(quitAction); QMenu *settings = appMenuBar->addMenu(tr("&Settings")); if(walletFrame) { settings->addAction(encryptWalletAction); settings->addAction(changePassphraseAction); settings->addSeparator(); } settings->addAction(optionsAction); QMenu *help = appMenuBar->addMenu(tr("&Help")); if(walletFrame) { help->addAction(openRPCConsoleAction); } help->addAction(showHelpMessageAction); help->addSeparator(); help->addAction(aboutAction); help->addAction(aboutQtAction); } void SagbitGUI::createToolBars() { if(walletFrame) { QToolBar *toolbar = addToolBar(tr("Tabs toolbar")); toolbar->setMovable(false); toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); toolbar->addAction(overviewAction); toolbar->addAction(sendCoinsAction); toolbar->addAction(receiveCoinsAction); toolbar->addAction(historyAction); overviewAction->setChecked(true); } } void SagbitGUI::setClientModel(ClientModel *clientModel) { this->clientModel = clientModel; if(clientModel) { // Create system tray menu (or setup the dock menu) that late to prevent users from calling actions, // while the client has not yet fully loaded createTrayIconMenu(); // Keep up to date with client setNumConnections(clientModel->getNumConnections()); connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); setNumBlocks(clientModel->getNumBlocks(), clientModel->getLastBlockDate(), clientModel->getVerificationProgress(NULL)); connect(clientModel, SIGNAL(numBlocksChanged(int,QDateTime,double)), this, SLOT(setNumBlocks(int,QDateTime,double))); // Receive and report messages from client model connect(clientModel, SIGNAL(message(QString,QString,unsigned int)), this, SLOT(message(QString,QString,unsigned int))); // Show progress dialog connect(clientModel, SIGNAL(showProgress(QString,int)), this, SLOT(showProgress(QString,int))); rpcConsole->setClientModel(clientModel); #ifdef ENABLE_WALLET if(walletFrame) { walletFrame->setClientModel(clientModel); } #endif // ENABLE_WALLET unitDisplayControl->setOptionsModel(clientModel->getOptionsModel()); } else { // Disable possibility to show main window via action toggleHideAction->setEnabled(false); if(trayIconMenu) { // Disable context menu on tray icon trayIconMenu->clear(); } } } #ifdef ENABLE_WALLET bool SagbitGUI::addWallet(const QString& name, WalletModel *walletModel) { if(!walletFrame) return false; setWalletActionsEnabled(true); return walletFrame->addWallet(name, walletModel); } bool SagbitGUI::setCurrentWallet(const QString& name) { if(!walletFrame) return false; return walletFrame->setCurrentWallet(name); } void SagbitGUI::removeAllWallets() { if(!walletFrame) return; setWalletActionsEnabled(false); walletFrame->removeAllWallets(); } #endif // ENABLE_WALLET void SagbitGUI::setWalletActionsEnabled(bool enabled) { overviewAction->setEnabled(enabled); sendCoinsAction->setEnabled(enabled); sendCoinsMenuAction->setEnabled(enabled); receiveCoinsAction->setEnabled(enabled); receiveCoinsMenuAction->setEnabled(enabled); historyAction->setEnabled(enabled); encryptWalletAction->setEnabled(enabled); backupWalletAction->setEnabled(enabled); changePassphraseAction->setEnabled(enabled); signMessageAction->setEnabled(enabled); verifyMessageAction->setEnabled(enabled); usedSendingAddressesAction->setEnabled(enabled); usedReceivingAddressesAction->setEnabled(enabled); openAction->setEnabled(enabled); } void SagbitGUI::createTrayIcon(const NetworkStyle *networkStyle) { #ifndef Q_OS_MAC trayIcon = new QSystemTrayIcon(this); QString toolTip = tr("Sagbit Core client") + " " + networkStyle->getTitleAddText(); trayIcon->setToolTip(toolTip); trayIcon->setIcon(networkStyle->getTrayAndWindowIcon()); trayIcon->show(); #endif notificator = new Notificator(QApplication::applicationName(), trayIcon, this); } void SagbitGUI::createTrayIconMenu() { #ifndef Q_OS_MAC // return if trayIcon is unset (only on non-Mac OSes) if (!trayIcon) return; trayIconMenu = new QMenu(this); trayIcon->setContextMenu(trayIconMenu); connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason))); #else // Note: On Mac, the dock icon is used to provide the tray's functionality. MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance(); dockIconHandler->setMainWindow((QMainWindow *)this); trayIconMenu = dockIconHandler->dockMenu(); #endif // Configuration of the tray icon (or dock icon) icon menu trayIconMenu->addAction(toggleHideAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(sendCoinsMenuAction); trayIconMenu->addAction(receiveCoinsMenuAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(signMessageAction); trayIconMenu->addAction(verifyMessageAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(optionsAction); trayIconMenu->addAction(openRPCConsoleAction); #ifndef Q_OS_MAC // This is built-in on Mac trayIconMenu->addSeparator(); trayIconMenu->addAction(quitAction); #endif } #ifndef Q_OS_MAC void SagbitGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason) { if(reason == QSystemTrayIcon::Trigger) { // Click on system tray icon triggers show/hide of the main window toggleHidden(); } } #endif void SagbitGUI::optionsClicked() { if(!clientModel || !clientModel->getOptionsModel()) return; OptionsDialog dlg(this, enableWallet); dlg.setModel(clientModel->getOptionsModel()); dlg.exec(); } void SagbitGUI::aboutClicked() { if(!clientModel) return; HelpMessageDialog dlg(this, true); dlg.exec(); } void SagbitGUI::showDebugWindow() { rpcConsole->showNormal(); rpcConsole->show(); rpcConsole->raise(); rpcConsole->activateWindow(); } void SagbitGUI::showDebugWindowActivateConsole() { rpcConsole->setTabFocus(RPCConsole::TAB_CONSOLE); showDebugWindow(); } void SagbitGUI::showHelpMessageClicked() { helpMessageDialog->show(); } #ifdef ENABLE_WALLET void SagbitGUI::openClicked() { OpenURIDialog dlg(this); if(dlg.exec()) { Q_EMIT receivedURI(dlg.getURI()); } } void SagbitGUI::gotoOverviewPage() { overviewAction->setChecked(true); if (walletFrame) walletFrame->gotoOverviewPage(); } void SagbitGUI::gotoHistoryPage() { historyAction->setChecked(true); if (walletFrame) walletFrame->gotoHistoryPage(); } void SagbitGUI::gotoReceiveCoinsPage() { receiveCoinsAction->setChecked(true); if (walletFrame) walletFrame->gotoReceiveCoinsPage(); } void SagbitGUI::gotoSendCoinsPage(QString addr) { sendCoinsAction->setChecked(true); if (walletFrame) walletFrame->gotoSendCoinsPage(addr); } void SagbitGUI::gotoSignMessageTab(QString addr) { if (walletFrame) walletFrame->gotoSignMessageTab(addr); } void SagbitGUI::gotoVerifyMessageTab(QString addr) { if (walletFrame) walletFrame->gotoVerifyMessageTab(addr); } #endif // ENABLE_WALLET void SagbitGUI::setNumConnections(int count) { QString icon; switch(count) { case 0: icon = ":/icons/connect_0"; break; case 1: case 2: case 3: icon = ":/icons/connect_1"; break; case 4: case 5: case 6: icon = ":/icons/connect_2"; break; case 7: case 8: case 9: icon = ":/icons/connect_3"; break; default: icon = ":/icons/connect_4"; break; } labelConnectionsIcon->setPixmap(platformStyle->SingleColorIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE)); labelConnectionsIcon->setToolTip(tr("%n active connection(s) to Sagbit network", "", count)); } void SagbitGUI::setNumBlocks(int count, const QDateTime& blockDate, double nVerificationProgress) { if(!clientModel) return; // Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbelled text) statusBar()->clearMessage(); // Acquire current block source enum BlockSource blockSource = clientModel->getBlockSource(); switch (blockSource) { case BLOCK_SOURCE_NETWORK: progressBarLabel->setText(tr("Synchronizing with network...")); break; case BLOCK_SOURCE_DISK: progressBarLabel->setText(tr("Importing blocks from disk...")); break; case BLOCK_SOURCE_REINDEX: progressBarLabel->setText(tr("Reindexing blocks on disk...")); break; case BLOCK_SOURCE_NONE: // Case: not Importing, not Reindexing and no network connection progressBarLabel->setText(tr("No block source available...")); break; } QString tooltip; QDateTime currentDate = QDateTime::currentDateTime(); qint64 secs = blockDate.secsTo(currentDate); tooltip = tr("Processed %n block(s) of transaction history.", "", count); // Set icon state: spinning if catching up, tick otherwise if(secs < 90*60) { tooltip = tr("Up to date") + QString(".<br>") + tooltip; labelBlocksIcon->setPixmap(platformStyle->SingleColorIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); #ifdef ENABLE_WALLET if(walletFrame) walletFrame->showOutOfSyncWarning(false); #endif // ENABLE_WALLET progressBarLabel->setVisible(false); progressBar->setVisible(false); } else { // Represent time from last generated block in human readable text QString timeBehindText; const int HOUR_IN_SECONDS = 60*60; const int DAY_IN_SECONDS = 24*60*60; const int WEEK_IN_SECONDS = 7*24*60*60; const int YEAR_IN_SECONDS = 31556952; // Average length of year in Gregorian calendar if(secs < 2*DAY_IN_SECONDS) { timeBehindText = tr("%n hour(s)","",secs/HOUR_IN_SECONDS); } else if(secs < 2*WEEK_IN_SECONDS) { timeBehindText = tr("%n day(s)","",secs/DAY_IN_SECONDS); } else if(secs < YEAR_IN_SECONDS) { timeBehindText = tr("%n week(s)","",secs/WEEK_IN_SECONDS); } else { qint64 years = secs / YEAR_IN_SECONDS; qint64 remainder = secs % YEAR_IN_SECONDS; timeBehindText = tr("%1 and %2").arg(tr("%n year(s)", "", years)).arg(tr("%n week(s)","", remainder/WEEK_IN_SECONDS)); } progressBarLabel->setVisible(true); progressBar->setFormat(tr("%1 behind").arg(timeBehindText)); progressBar->setMaximum(1000000000); progressBar->setValue(nVerificationProgress * 1000000000.0 + 0.5); progressBar->setVisible(true); tooltip = tr("Catching up...") + QString("<br>") + tooltip; if(count != prevBlocks) { labelBlocksIcon->setPixmap(platformStyle->SingleColorIcon(QString( ":/movies/spinner-%1").arg(spinnerFrame, 3, 10, QChar('0'))) .pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); spinnerFrame = (spinnerFrame + 1) % SPINNER_FRAMES; } prevBlocks = count; #ifdef ENABLE_WALLET if(walletFrame) walletFrame->showOutOfSyncWarning(true); #endif // ENABLE_WALLET tooltip += QString("<br>"); tooltip += tr("Last received block was generated %1 ago.").arg(timeBehindText); tooltip += QString("<br>"); tooltip += tr("Transactions after this will not yet be visible."); } // Don't word-wrap this (fixed-width) tooltip tooltip = QString("<nobr>") + tooltip + QString("</nobr>"); labelBlocksIcon->setToolTip(tooltip); progressBarLabel->setToolTip(tooltip); progressBar->setToolTip(tooltip); } void SagbitGUI::message(const QString &title, const QString &message, unsigned int style, bool *ret) { QString strTitle = tr("Sagbit"); // default title // Default to information icon int nMBoxIcon = QMessageBox::Information; int nNotifyIcon = Notificator::Information; QString msgType; // Prefer supplied title over style based title if (!title.isEmpty()) { msgType = title; } else { switch (style) { case CClientUIInterface::MSG_ERROR: msgType = tr("Error"); break; case CClientUIInterface::MSG_WARNING: msgType = tr("Warning"); break; case CClientUIInterface::MSG_INFORMATION: msgType = tr("Information"); break; default: break; } } // Append title to "Sagbit - " if (!msgType.isEmpty()) strTitle += " - " + msgType; // Check for error/warning icon if (style & CClientUIInterface::ICON_ERROR) { nMBoxIcon = QMessageBox::Critical; nNotifyIcon = Notificator::Critical; } else if (style & CClientUIInterface::ICON_WARNING) { nMBoxIcon = QMessageBox::Warning; nNotifyIcon = Notificator::Warning; } // Display message if (style & CClientUIInterface::MODAL) { // Check for buttons, use OK as default, if none was supplied QMessageBox::StandardButton buttons; if (!(buttons = (QMessageBox::StandardButton)(style & CClientUIInterface::BTN_MASK))) buttons = QMessageBox::Ok; showNormalIfMinimized(); QMessageBox mBox((QMessageBox::Icon)nMBoxIcon, strTitle, message, buttons, this); int r = mBox.exec(); if (ret != NULL) *ret = r == QMessageBox::Ok; } else notificator->notify((Notificator::Class)nNotifyIcon, strTitle, message); } void SagbitGUI::changeEvent(QEvent *e) { QMainWindow::changeEvent(e); #ifndef Q_OS_MAC // Ignored on Mac if(e->type() == QEvent::WindowStateChange) { if(clientModel && clientModel->getOptionsModel() && clientModel->getOptionsModel()->getMinimizeToTray()) { QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e); if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized()) { QTimer::singleShot(0, this, SLOT(hide())); e->ignore(); } } } #endif } void SagbitGUI::closeEvent(QCloseEvent *event) { #ifndef Q_OS_MAC // Ignored on Mac if(clientModel && clientModel->getOptionsModel()) { if(!clientModel->getOptionsModel()->getMinimizeToTray() && !clientModel->getOptionsModel()->getMinimizeOnClose()) { // close rpcConsole in case it was open to make some space for the shutdown window rpcConsole->close(); QApplication::quit(); } } #endif QMainWindow::closeEvent(event); } #ifdef ENABLE_WALLET void SagbitGUI::incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address, const QString& label) { // On new transaction, make an info balloon QString msg = tr("Date: %1\n").arg(date) + tr("Amount: %1\n").arg(SagbitUnits::formatWithUnit(unit, amount, true)) + tr("Type: %1\n").arg(type); if (!label.isEmpty()) msg += tr("Label: %1\n").arg(label); else if (!address.isEmpty()) msg += tr("Address: %1\n").arg(address); message((amount)<0 ? tr("Sent transaction") : tr("Incoming transaction"), msg, CClientUIInterface::MSG_INFORMATION); } #endif // ENABLE_WALLET void SagbitGUI::dragEnterEvent(QDragEnterEvent *event) { // Accept only URIs if(event->mimeData()->hasUrls()) event->acceptProposedAction(); } void SagbitGUI::dropEvent(QDropEvent *event) { if(event->mimeData()->hasUrls()) { Q_FOREACH(const QUrl &uri, event->mimeData()->urls()) { Q_EMIT receivedURI(uri.toString()); } } event->acceptProposedAction(); } bool SagbitGUI::eventFilter(QObject *object, QEvent *event) { // Catch status tip events if (event->type() == QEvent::StatusTip) { // Prevent adding text from setStatusTip(), if we currently use the status bar for displaying other stuff if (progressBarLabel->isVisible() || progressBar->isVisible()) return true; } return QMainWindow::eventFilter(object, event); } #ifdef ENABLE_WALLET bool SagbitGUI::handlePaymentRequest(const SendCoinsRecipient& recipient) { // URI has to be valid if (walletFrame && walletFrame->handlePaymentRequest(recipient)) { showNormalIfMinimized(); gotoSendCoinsPage(); return true; } return false; } void SagbitGUI::setEncryptionStatus(int status) { switch(status) { case WalletModel::Unencrypted: labelEncryptionIcon->hide(); encryptWalletAction->setChecked(false); changePassphraseAction->setEnabled(false); encryptWalletAction->setEnabled(true); break; case WalletModel::Unlocked: labelEncryptionIcon->show(); labelEncryptionIcon->setPixmap(platformStyle->SingleColorIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE)); labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>")); encryptWalletAction->setChecked(true); changePassphraseAction->setEnabled(true); encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported break; case WalletModel::Locked: labelEncryptionIcon->show(); labelEncryptionIcon->setPixmap(platformStyle->SingleColorIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE)); labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>")); encryptWalletAction->setChecked(true); changePassphraseAction->setEnabled(true); encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported break; } } #endif // ENABLE_WALLET void SagbitGUI::showNormalIfMinimized(bool fToggleHidden) { if(!clientModel) return; // activateWindow() (sometimes) helps with keyboard focus on Windows if (isHidden()) { show(); activateWindow(); } else if (isMinimized()) { showNormal(); activateWindow(); } else if (GUIUtil::isObscured(this)) { raise(); activateWindow(); } else if(fToggleHidden) hide(); } void SagbitGUI::toggleHidden() { showNormalIfMinimized(true); } void SagbitGUI::detectShutdown() { if (ShutdownRequested()) { if(rpcConsole) rpcConsole->hide(); qApp->quit(); } } void SagbitGUI::showProgress(const QString &title, int nProgress) { if (nProgress == 0) { progressDialog = new QProgressDialog(title, "", 0, 100); progressDialog->setWindowModality(Qt::ApplicationModal); progressDialog->setMinimumDuration(0); progressDialog->setCancelButton(0); progressDialog->setAutoClose(false); progressDialog->setValue(0); } else if (nProgress == 100) { if (progressDialog) { progressDialog->close(); progressDialog->deleteLater(); } } else if (progressDialog) progressDialog->setValue(nProgress); } static bool ThreadSafeMessageBox(SagbitGUI *gui, const std::string& message, const std::string& caption, unsigned int style) { bool modal = (style & CClientUIInterface::MODAL); // The SECURE flag has no effect in the Qt GUI. // bool secure = (style & CClientUIInterface::SECURE); style &= ~CClientUIInterface::SECURE; bool ret = false; // In case of modal message, use blocking connection to wait for user to click a button QMetaObject::invokeMethod(gui, "message", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(unsigned int, style), Q_ARG(bool*, &ret)); return ret; } void SagbitGUI::subscribeToCoreSignals() { // Connect signals to client uiInterface.ThreadSafeMessageBox.connect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3)); } void SagbitGUI::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.ThreadSafeMessageBox.disconnect(boost::bind(ThreadSafeMessageBox, this, _1, _2, _3)); } UnitDisplayStatusBarControl::UnitDisplayStatusBarControl(const PlatformStyle *platformStyle) : optionsModel(0), menu(0) { createContextMenu(); setToolTip(tr("Unit to show amounts in. Click to select another unit.")); QList<SagbitUnits::Unit> units = SagbitUnits::availableUnits(); int max_width = 0; const QFontMetrics fm(font()); Q_FOREACH (const SagbitUnits::Unit unit, units) { max_width = qMax(max_width, fm.width(SagbitUnits::name(unit))); } setMinimumSize(max_width, 0); setAlignment(Qt::AlignRight | Qt::AlignVCenter); setStyleSheet(QString("QLabel { color : %1 }").arg(platformStyle->SingleColor().name())); } /** So that it responds to button clicks */ void UnitDisplayStatusBarControl::mousePressEvent(QMouseEvent *event) { onDisplayUnitsClicked(event->pos()); } /** Creates context menu, its actions, and wires up all the relevant signals for mouse events. */ void UnitDisplayStatusBarControl::createContextMenu() { menu = new QMenu(); Q_FOREACH(SagbitUnits::Unit u, SagbitUnits::availableUnits()) { QAction *menuAction = new QAction(QString(SagbitUnits::name(u)), this); menuAction->setData(QVariant(u)); menu->addAction(menuAction); } connect(menu,SIGNAL(triggered(QAction*)),this,SLOT(onMenuSelection(QAction*))); } /** Lets the control know about the Options Model (and its signals) */ void UnitDisplayStatusBarControl::setOptionsModel(OptionsModel *optionsModel) { if (optionsModel) { this->optionsModel = optionsModel; // be aware of a display unit change reported by the OptionsModel object. connect(optionsModel,SIGNAL(displayUnitChanged(int)),this,SLOT(updateDisplayUnit(int))); // initialize the display units label with the current value in the model. updateDisplayUnit(optionsModel->getDisplayUnit()); } } /** When Display Units are changed on OptionsModel it will refresh the display text of the control on the status bar */ void UnitDisplayStatusBarControl::updateDisplayUnit(int newUnits) { setText(SagbitUnits::name(newUnits)); } /** Shows context menu with Display Unit options by the mouse coordinates */ void UnitDisplayStatusBarControl::onDisplayUnitsClicked(const QPoint& point) { QPoint globalPos = mapToGlobal(point); menu->exec(globalPos); } /** Tells underlying optionsModel to update its current display unit. */ void UnitDisplayStatusBarControl::onMenuSelection(QAction* action) { if (action) { optionsModel->setDisplayUnit(action->data()); } }
[ "mirzaei@ce.sharif.edu" ]
mirzaei@ce.sharif.edu
ee3cf5c040bc2e9e554b6fe93e24f70c96b8a19b
13f78c34e80a52442d72e0aa609666163233e7e0
/AtCoder/ARC 119/C.cpp
3146b708e359e0adc95f941e534c32fa29c209c0
[]
no_license
Giantpizzahead/comp-programming
0d16babe49064aee525d78a70641ca154927af20
232a19fdd06ecef7be845c92db38772240a33e41
refs/heads/master
2023-08-17T20:23:28.693280
2023-08-11T22:18:26
2023-08-11T22:18:26
252,904,746
2
0
null
null
null
null
UTF-8
C++
false
false
606
cpp
#include <bits/stdc++.h> using namespace std; #define rep(i, a, b) for (int i = (a); i < (b); i++) #define sz(x) ((int) x.size()) #define all(x) x.begin(), x.end() #define debug if (true) cerr using ll = long long; const int MAXN = 3e5+5; int N; ll A[MAXN]; map<ll, int> cnt; void solve() { cin >> N; rep(i, 0, N) cin >> A[i]; ll ans = 0, sum = 0; cnt[0]++; rep(i, 0, N) { if (i % 2 == 0) sum += A[i]; else sum -= A[i]; ans += cnt[sum]++; } cout << ans << '\n'; } int main() { ios::sync_with_stdio(0); cin.tie(0); solve(); return 0; }
[ "43867185+Giantpizzahead@users.noreply.github.com" ]
43867185+Giantpizzahead@users.noreply.github.com
693a3e8bc3f19c223b781fc106821b6643910fe6
3b9a242f2d7df732f5f7dc29027f73bd8773e71d
/sandboxes/cb/sharel00/share00.cpp
55fdf85ddbe24a5dfd149e23d227cf61abb94fbf
[]
no_license
skubliy/scratches
8d0c15b30d7f60cf7f82382148d6a18f658609b4
813be4487bb82e76c4e26b85f357e6d1b0910a34
refs/heads/master
2021-01-16T23:21:33.071813
2016-07-13T19:31:58
2016-07-13T19:31:58
59,788,158
0
0
null
null
null
null
UTF-8
C++
false
false
844
cpp
// The functions contained in this file are pretty dummy // and are included only as a placeholder. Nevertheless, // they *will* get included in the shared library if you // don't remove them :) // // Obviously, you 'll have to write yourself the super-duper // functions to include in the resulting library... // Also, it's not necessary to write every function in this file. // Feel free to add more files in this project. They will be // included in the resulting library. #include <iostream> using namespace std; extern "C" { // A function adding two integers and returning the result int SampleAddInt(int i1, int i2) { cout << __func__ << "\t" << i1 << " + "<< i2 << " = "; return i1 + i2; } // A function doing nothing ;) void SampleFunction1() { cout << __func__ << endl; } }
[ "skubliy@gmail.com" ]
skubliy@gmail.com
73016ce2baacbaf2172db42ec4f7166eee64b05c
7a046978779f0496d41e5bae4c4218abd0d06f57
/HIDMapper/MapperJoystickToKeyboard.cpp
d197767a68f5e34cd33368731d845c60f974529e
[ "MIT" ]
permissive
stewienj/DxHIDLoggerMapper
943e54361532c09f96421731f2731ccfb13350a1
a66606706e6f441385b73a199d4b1323bf765e55
refs/heads/master
2023-05-24T17:21:22.167078
2023-05-13T07:30:18
2023-05-13T08:55:27
124,023,064
3
0
null
null
null
null
UTF-8
C++
false
false
4,281
cpp
#include "MapperJoystickToKeyboard.h" #include "MapperJoystickToKeyboardConfig.h" #include "HIDMapperInterface.h" #include <tchar.h> #include <strsafe.h> #include <Windows.h> MapperJoystickToKeyboard::MapperJoystickToKeyboard(GUID deviceGuid, HIDMapperDLL::HIDMapperInterface^ loggerInterface) : MapperJoystick(deviceGuid, loggerInterface) { memset(_keyActivatedCount, 0, sizeof(_keyActivatedCount)); _config = gcnew HIDMapperDLL::MapperJoystickToKeyboardConfig(); _config->ConfigureForFortnite(); } void MapperJoystickToKeyboard::Log(const DIJOYSTATE2& joyState) { if (_loggerInterface->SuppressMapping) { MapperJoystick::Log(joyState); return; } int previousKeyActivatedCount[KEY_COUNT]; memcpy(previousKeyActivatedCount, _keyActivatedCount, sizeof(_keyActivatedCount)); // Check the buttons first int buttonCount = sizeof(joyState.rgbButtons); for (int buttonNo = 0; buttonNo < buttonCount; ++buttonNo) { auto keySequence = _config->ButtonToKeySequence[buttonNo]; if (keySequence != nullptr && keySequence->Length > 0) { // Just use the first key at the moment, key combos can come later auto key = keySequence[0]; if (joyState.rgbButtons[buttonNo] > 0 && _lastState.rgbButtons[buttonNo] == 0) { // On _keyActivatedCount[key]++; } if (joyState.rgbButtons[buttonNo] == 0 && _lastState.rgbButtons[buttonNo] >0) { // Off _keyActivatedCount[key]--; } } } // Check each linear axis position for each(auto combo in _config->X) { CheckAxis(joyState.lX, _lastState.lX, combo.Threshold, combo.Key); } for each(auto combo in _config->Y) { CheckAxis(joyState.lY, _lastState.lY, combo.Threshold, combo.Key); } for each(auto combo in _config->Z) { CheckAxis(joyState.lZ, _lastState.lZ, combo.Threshold, combo.Key); } // Check each rotation axis position for each(auto combo in _config->RX) { CheckAxis(joyState.lRx, _lastState.lRx, combo.Threshold, combo.Key); } for each(auto combo in _config->RY) { CheckAxis(joyState.lRy, _lastState.lRy, combo.Threshold, combo.Key); } for each(auto combo in _config->RZ) { CheckAxis(joyState.lRz, _lastState.lRz, combo.Threshold, combo.Key); } for (int i = 0; i < KEY_COUNT; ++i) { if (previousKeyActivatedCount[i] == 0 && _keyActivatedCount[i] > 0) { MapperJoystickToKeyboard::KeyDown(i); } if (previousKeyActivatedCount[i] > 0 && _keyActivatedCount[i] == 0) { MapperJoystickToKeyboard::KeyUp(i); } } MapperJoystick::Log(joyState); } void MapperJoystickToKeyboard::CheckAxis(int current, int previous, int threshold, int key) { if (threshold < 0) { if (current < threshold && previous >= threshold) { _keyActivatedCount[key]++; } if (current >= threshold && previous < threshold) { _keyActivatedCount[key]--; } } else if (threshold >= 0) { if (current > threshold && previous <= threshold) { _keyActivatedCount[key]++; } if (current <= threshold && previous > threshold) { _keyActivatedCount[key]--; } } } // For key codes // https://www.codeproject.com/Articles/7305/Keyboard-Events-Simulation-using-keybd-event-funct // https://msdn.microsoft.com/en-us/library/windows/desktop/ms646271(v=vs.85).aspx // https://stackoverflow.com/questions/22419038/how-to-use-sendinput-function-c // https://stackoverflow.com/questions/3644881/simulating-keyboard-with-sendinput-api-in-directinput-applications/3647975#3647975 void MapperJoystickToKeyboard::KeyDown(int scanCode) { // Send keyboard state using the scan code INPUT inputData = { 0 }; inputData.type = INPUT_KEYBOARD; inputData.ki.wScan = scanCode; inputData.ki.dwFlags = KEYEVENTF_SCANCODE; SendInput(1, &inputData, sizeof(INPUT)); } void MapperJoystickToKeyboard::KeyUp(int scanCode) { // Send keyboard state using the scan code INPUT inputData = { 0 }; inputData.type = INPUT_KEYBOARD; inputData.ki.wScan = scanCode; inputData.ki.dwFlags = KEYEVENTF_KEYUP | KEYEVENTF_SCANCODE; SendInput(1, &inputData, sizeof(INPUT)); } HIDMapperDLL::MapperJoystickToKeyboardConfig^ MapperJoystickToKeyboard::GetMapperConfig() { return _config; }
[ "stewienj@users.noreply.github.com" ]
stewienj@users.noreply.github.com
f3be72c9d6c135dabb92f595b27427fb8a887c04
5a2563f4cd1fd50c3945478def86254ce0a93e1d
/components/rf_bridge_cc1101/remote_transmitter_esp8266.cpp
6b7cb79286a449d0f7b612755c58a11474127e52
[]
no_license
x64life/esphome-custom-components
dd8344a53947f719dcac56e30ed98c59d9c5ae9c
127dd1a363be1dba465b985c83eb9f45bd966dfc
refs/heads/main
2023-08-01T09:36:28.119558
2021-09-21T09:28:41
2021-09-21T09:28:41
408,473,870
0
0
null
2021-09-21T09:28:42
2021-09-20T14:23:12
null
UTF-8
C++
false
false
2,679
cpp
#include "remote_transmitter.h" #include "esphome/core/log.h" #include "esphome/core/application.h" #ifdef ARDUINO_ARCH_ESP8266 namespace esphome { namespace rf_bridge_cc1101 { static const char *const TAG = "rf_bridge_cc1101.transmitter.esp8266"; void RemoteTransmitter::setup() { this->pin_->setup(); this->pin_->digital_write(false); } void RemoteTransmitter::enable() { this->pin_->setup(); this->pin_->digital_write(false); } void RemoteTransmitter::calculate_on_off_time_(uint32_t carrier_frequency, uint32_t *on_time_period, uint32_t *off_time_period) { if (carrier_frequency == 0) { *on_time_period = 0; *off_time_period = 0; return; } uint32_t period = (1000000UL + carrier_frequency / 2) / carrier_frequency; // round(1000000/freq) period = std::max(uint32_t(1), period); *on_time_period = (period * this->carrier_duty_percent_) / 100; *off_time_period = period - *on_time_period; } void RemoteTransmitter::mark_(uint32_t on_time, uint32_t off_time, uint32_t usec) { if (this->carrier_duty_percent_ == 100 || (on_time == 0 && off_time == 0)) { this->pin_->digital_write(true); delay_microseconds_accurate(usec); this->pin_->digital_write(false); return; } const uint32_t start_time = micros(); uint32_t current_time = start_time; while (current_time - start_time < usec) { const uint32_t elapsed = current_time - start_time; this->pin_->digital_write(true); delay_microseconds_accurate(std::min(on_time, usec - elapsed)); this->pin_->digital_write(false); if (elapsed + on_time >= usec) return; delay_microseconds_accurate(std::min(usec - elapsed - on_time, off_time)); current_time = micros(); } } void RemoteTransmitter::space_(uint32_t usec) { this->pin_->digital_write(false); delay_microseconds_accurate(usec); } void RemoteTransmitter::send_internal(uint32_t send_times, uint32_t send_wait) { ESP_LOGD(TAG, "Sending remote code..."); uint32_t on_time, off_time; this->calculate_on_off_time_(this->temp_.get_carrier_frequency(), &on_time, &off_time); for (uint32_t i = 0; i < send_times; i++) { { InterruptLock lock; for (int32_t item : this->temp_.get_data()) { if (item > 0) { const auto length = uint32_t(item); this->mark_(on_time, off_time, length); } else { const auto length = uint32_t(-item); this->space_(length); } App.feed_wdt(); } } if (i + 1 < send_times) { delay_microseconds_accurate(send_wait); } } } } // namespace rf_bridge_cc1101 } // namespace esphome #endif
[ "ryanh7@163.com|" ]
ryanh7@163.com|
56b4ae933be53f8e6a6549f08a67e032520461cc
6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849
/sstd_boost/sstd/libs/gil/io/test/tiff_tiled_palette_write_test_1-8.cpp
58eb148b849b6533ee1ab450903b25bfef3fee9c
[ "BSL-1.0" ]
permissive
KqSMea8/sstd_library
9e4e622e1b01bed5de7322c2682539400d13dd58
0fcb815f50d538517e70a788914da7fbbe786ce1
refs/heads/master
2020-05-03T21:07:01.650034
2019-04-01T00:10:47
2019-04-01T00:10:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
669
cpp
// // Copyright 2013 Christian Henning // // Distributed under the Boost Software License, Version 1.0 // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // //#define BOOST_TEST_MODULE tiff_tiled_palette_write_test_1_8_module #include <sstd/boost/test/unit_test.hpp> #include "tiff_tiled_write_macros.hpp" BOOST_AUTO_TEST_SUITE( gil_io_tiff_tests ) #ifdef BOOST_GIL_IO_USE_TIFF_GRAPHICSMAGICK_TEST_SUITE_IMAGES // CHH - not supported palette //BOOST_PP_REPEAT_FROM_TO(1, 9, GENERATE_WRITE_TILE_BIT_ALIGNED_PALETTE, palette ) #endif // BOOST_GIL_IO_USE_TIFF_GRAPHICSMAGICK_TEST_SUITE_IMAGES BOOST_AUTO_TEST_SUITE_END()
[ "zhaixueqiang@hotmail.com" ]
zhaixueqiang@hotmail.com
6c544d6228156e4406fd394c0f126706dbbfb1c5
de5cec21781c5f89f13845d15a32782162290a76
/Two Substrings.cpp
8ccaddd49d161689eca8bd75df0f3451ed89f737
[]
no_license
thongngo3301/Codeforces
819e232577c4b2b1b5b9fb7d2ebfc518e0c2daa9
f4647cf44e9c8715ec86d23b99ead7fafdc66e4d
refs/heads/master
2021-05-06T15:44:27.361559
2017-12-09T05:59:37
2017-12-09T05:59:37
113,646,165
0
0
null
null
null
null
UTF-8
C++
false
false
1,309
cpp
#include <bits/stdc++.h> using namespace std; int main() { string input; cin>>input; size_t found = input.find("AB"); size_t foundReverse = input.find("BA"); while(found!=string::npos){ foundReverse = input.find("BA"); if(foundReverse != string::npos){ if(foundReverse == found-1 || foundReverse == found+1){ foundReverse = input.find("BA",foundReverse+1); if(foundReverse != string:: npos){ if(foundReverse == found+1){ foundReverse = input.find("BA",foundReverse+1); if(foundReverse != string::npos){ cout<<"YES"; return 0; }else{ found = input.find("AB",found+1); } }else{ cout<<"YES"; return 0; } }else{ found = input.find("AB",found+1); } continue; }else{ cout<<"YES"; return 0; } }else{ // found = input.find("AB",found+1); break; } } cout<<"NO"; return 0; }
[ "thongngo3301@gmail.com" ]
thongngo3301@gmail.com
f950cbfaf0c0e45ba5f99e60bc1587686f64a188
8dc84558f0058d90dfc4955e905dab1b22d12c08
/third_party/blink/renderer/core/paint/rounded_inner_rect_clipper.h
25fd36bbe06d6b3949eb1d5dc37a027b15468716
[ "LGPL-2.0-only", "BSD-2-Clause", "LGPL-2.1-only", "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
meniossin/src
42a95cc6c4a9c71d43d62bc4311224ca1fd61e03
44f73f7e76119e5ab415d4593ac66485e65d700a
refs/heads/master
2022-12-16T20:17:03.747113
2020-09-03T10:43:12
2020-09-03T10:43:12
263,710,168
1
0
BSD-3-Clause
2020-05-13T18:20:09
2020-05-13T18:20:08
null
UTF-8
C++
false
false
1,271
h
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_ROUNDED_INNER_RECT_CLIPPER_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_ROUNDED_INNER_RECT_CLIPPER_H_ #include "third_party/blink/renderer/platform/graphics/paint/display_item.h" #include "third_party/blink/renderer/platform/wtf/allocator.h" namespace blink { class FloatRoundedRect; class LayoutRect; class DisplayItemClient; struct PaintInfo; enum RoundedInnerRectClipperBehavior { kApplyToDisplayList, kApplyToContext }; class RoundedInnerRectClipper { DISALLOW_NEW_EXCEPT_PLACEMENT_NEW(); public: RoundedInnerRectClipper(const DisplayItemClient&, const PaintInfo&, const LayoutRect&, const FloatRoundedRect& clip_rect, RoundedInnerRectClipperBehavior); ~RoundedInnerRectClipper(); private: const DisplayItemClient& display_item_; const PaintInfo& paint_info_; bool use_paint_controller_; DisplayItem::Type clip_type_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_ROUNDED_INNER_RECT_CLIPPER_H_
[ "arnaud@geometry.ee" ]
arnaud@geometry.ee
7dd48f51be120deccc71cf79b26a159c9406a48a
02a249c0c48ad11f8b5476626e42a7a2af889637
/solutions/POJ/2251/17354936_AC_16ms_844kB.cpp
310b6a94c95c25652eb10d991f66bad485dcc2b2
[]
no_license
Kanaricc/MyICPC
3a3351fc02d7f36e7438eb1c92a87c9263028c8f
73e80b2263ae8e2fe87009743defb59ff36e38ca
refs/heads/master
2023-07-06T14:38:39.495821
2023-07-06T09:18:58
2023-07-06T09:18:58
186,849,167
0
0
null
null
null
null
UTF-8
C++
false
false
1,681
cpp
#include <iostream> #include <queue> #include <cstring> using namespace std; const int MAXN=40; int L,R,C; struct v4q{ int x,y,z; int waste; v4q(){} v4q(int x,int y,int z,int waste):x(x),y(y),z(z),waste(waste){} }; char game[MAXN][MAXN][MAXN]; bool vis[MAXN][MAXN][MAXN]; int bfs(int x,int y,int z){ queue<v4q> q; q.push(v4q(x,y,z,0)); memset(vis,0,sizeof(vis)); while(!q.empty()){ v4q cur=q.front(); q.pop(); int x=cur.x,y=cur.y,z=cur.z; if(vis[z][x][y])continue; vis[z][x][y]=1; if(game[z][x][y]=='E'){ return cur.waste; } for(int of=-1;of<=1;of+=2){ if(x+of>=1 && x+of<=R && game[z][x+of][y]!='#'){ q.push(v4q(x+of,y,z,cur.waste+1)); } if(y+of>=1 && y+of<=C && game[z][x][y+of]!='#'){ q.push(v4q(x,y+of,z,cur.waste+1)); } if(z+of>=1 && z+of<=L && game[z+of][x][y]!='#'){ q.push(v4q(x,y,z+of,cur.waste+1)); } } } return -1; } int main(){ ios::sync_with_stdio(false); while(cin>>L>>R>>C){ if(L==0)break; int sx,sy,sz; for(int z=1;z<=L;z++){ for(int x=1;x<=R;x++){ for(int y=1;y<=C;y++){ cin>>game[z][x][y]; if(game[z][x][y]=='S'){ sx=x;sy=y,sz=z; } } } } int ans=bfs(sx,sy,sz); if(ans!=-1){ cout<<"Escaped in "<<ans<<" minute(s)."<<endl; }else{ cout<<"Trapped!"<<endl; } } return 0; }
[ "iovo7c@gmail.com" ]
iovo7c@gmail.com
4e0ab4f7b0595120523a326caf5fd3cd8b0ae829
1880ae99db197e976c87ba26eb23a20248e8ee51
/cvm/include/tencentcloud/cvm/v20170312/model/DescribeAccountQuotaResponse.h
2d8833c8fc0c08860a3b17cabd105a8c378f6276
[ "Apache-2.0" ]
permissive
caogenwang/tencentcloud-sdk-cpp
84869793b5eb9811bb1eb46ed03d4dfa7ce6d94d
6e18ee6622697a1c60a20a509415b0ddb8bdeb75
refs/heads/master
2023-08-23T12:37:30.305972
2021-11-08T01:18:30
2021-11-08T01:18:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,973
h
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TENCENTCLOUD_CVM_V20170312_MODEL_DESCRIBEACCOUNTQUOTARESPONSE_H_ #define TENCENTCLOUD_CVM_V20170312_MODEL_DESCRIBEACCOUNTQUOTARESPONSE_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/AbstractModel.h> #include <tencentcloud/cvm/v20170312/model/AccountQuotaOverview.h> namespace TencentCloud { namespace Cvm { namespace V20170312 { namespace Model { /** * DescribeAccountQuota返回参数结构体 */ class DescribeAccountQuotaResponse : public AbstractModel { public: DescribeAccountQuotaResponse(); ~DescribeAccountQuotaResponse() = default; CoreInternalOutcome Deserialize(const std::string &payload); std::string ToJsonString() const; /** * 获取用户appid * @return AppId 用户appid */ std::string GetAppId() const; /** * 判断参数 AppId 是否已赋值 * @return AppId 是否已赋值 */ bool AppIdHasBeenSet() const; /** * 获取配额数据 * @return AccountQuotaOverview 配额数据 */ AccountQuotaOverview GetAccountQuotaOverview() const; /** * 判断参数 AccountQuotaOverview 是否已赋值 * @return AccountQuotaOverview 是否已赋值 */ bool AccountQuotaOverviewHasBeenSet() const; private: /** * 用户appid */ std::string m_appId; bool m_appIdHasBeenSet; /** * 配额数据 */ AccountQuotaOverview m_accountQuotaOverview; bool m_accountQuotaOverviewHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_CVM_V20170312_MODEL_DESCRIBEACCOUNTQUOTARESPONSE_H_
[ "tencentcloudapi@tenent.com" ]
tencentcloudapi@tenent.com
0d75bd829bb343f940344241edd1988a0462f668
06eb60c98f4d106fc3bb3d0b7e990828b87d714d
/Source/WebCore/html/PasswordInputType.h
9ff12f31df1d04f25dfd0cf93ea05fd60ca2a059
[]
no_license
snyh/dui
9486a81d97ec1173b161b6aef8fcea21066aebff
c4464629f1efdecae792ed3abc2a7fc9ce9b88db
refs/heads/master
2021-01-25T08:28:55.224303
2013-10-23T00:42:02
2013-10-23T00:42:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,514
h
/* * Copyright (C) 2010 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef PasswordInputType_h #define PasswordInputType_h #include "html/BaseTextInputType.h" namespace WebCore { class PasswordInputType : public BaseTextInputType { public: static PassOwnPtr<InputType> create(HTMLInputElement*); private: PasswordInputType(HTMLInputElement* element) : BaseTextInputType(element) { } virtual const AtomicString& formControlType() const OVERRIDE; virtual bool shouldSaveAndRestoreFormControlState() const OVERRIDE; virtual FormControlState saveFormControlState() const OVERRIDE; virtual void restoreFormControlState(const FormControlState&) OVERRIDE; virtual bool shouldUseInputMethod() const OVERRIDE; virtual bool shouldResetOnDocumentActivation() OVERRIDE; virtual bool shouldRespectListAttribute() OVERRIDE; virtual bool shouldRespectSpeechAttribute() OVERRIDE; virtual bool isPasswordField() const OVERRIDE; }; } // namespace WebCore #endif // PasswordInputType_h
[ "snyh@snyh.org" ]
snyh@snyh.org
4f59baaf75911ebd4e067a9f03894b271d27fb4e
1c30108db5cc94ef91edf858a922c6867c38479e
/src/gz_piter/sketch/PiTeR/Pid.h
8790a86f2b9689a170a124f0af68285602bd1cb0
[]
no_license
penguinman543/Pi
0d483b000503aae044ee92f6749fd83c920fefaa
97e5eed8f2c81ee62b5a14a0ab467c1bb3d7ceb6
refs/heads/master
2020-06-13T08:12:45.126042
2017-02-04T07:53:17
2017-02-04T07:53:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,474
h
#ifndef _pid_h_ #define _pid_h_ /* * Pid.h * * Pi Terrestrial Robot - Proportional Integral Derivative algorithm * * Copyright 2014 guzunty * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * The class definition in this file encapsulates the PID algorithm for * the PiTeR robot firmware. There are two instantiations of this class, * one takes as input the desired balance angle and outputs the motor * drive. The second takes the desired wheel speed and outputs the desired * balance angle. Hence, the two instantiations form a control cascade. * */ #include<Arduino.h> #define GUARD_GAIN 20.0 class Pid { private: float K ; float Kp; float Ki; float Kd; float error; float last_position; float integrated_error; float pTerm, iTerm, dTerm; boolean nonlinear = false; public: Pid(float K, float Kp, float Ki, float Kd, boolean nl): K(K), Kp(Kp), Ki(Ki), Kd(Kd), nonlinear(nl) { error = 0.0; last_position = 0.0; integrated_error = 0.0; pTerm = 0.0; iTerm = 0.0; dTerm = 0.0; }; float updatePid(float targetPosition, float currentPosition, unsigned long dt) { float rdt = (float)dt / 1000000.0; error = targetPosition - currentPosition; pTerm = Kp * error; integrated_error += error * rdt * 100.0; iTerm = Ki * constrain(integrated_error, -GUARD_GAIN, GUARD_GAIN); integrated_error *= 0.9; // Decay integrated error integrated_error = constrain(integrated_error, -100.0, 100.0); dTerm = (- Kd * (currentPosition - last_position) / (rdt * 100.0)); last_position = currentPosition; float result = K*(pTerm + iTerm + dTerm); if (nonlinear) { float rads = abs(((float)error/512.0)); if (rads > 0.5) { rads = 0.5; } result *= 0.5 + (1.0 - cos(rads * PI)); } return -constrain(result, -255, 255); }; float getK() { return K; } float getKp() { return Kp; } float getKi() { return Ki; } float getKd() { return Kd; } float getPTerm() { return pTerm; } float getITerm() { return iTerm; } float getDTerm() { return dTerm; } float getError() { return error; } float getIntegratedError() { return integrated_error; } void setK(float K) { this->K = K; } void setKp(float Kp) { this->Kp = Kp; } void setKi(float Ki) { this->Ki = Ki; } void setKd(float Kd) { this->Kd = Kd; } void resetIntegratedError() { integrated_error = 0.0; } void resetDerivativeError(float newLastInput) { last_position = newLastInput; } }; #endif
[ "guzunty@gmail.com" ]
guzunty@gmail.com
dd488cc74d1a4a35d2c4fec7c2a1a82334838611
b1af8bb863a6730e6e4e93129efbad89d33cf509
/SDK/SCUM_Cal_9mm_functions.cpp
8cb75a73550f136b55e9d3fb26c8e4f6f2a62425
[]
no_license
frankie-11/SCUM_SDK7.13.2020
b3bbd8fb9b6c03120b865a6254eca6a2389ea654
7b48bcf9e8088aa8917c07dd6756eac90e3f693a
refs/heads/master
2022-11-16T05:48:55.729087
2020-07-13T23:48:50
2020-07-13T23:48:50
279,433,512
0
1
null
null
null
null
UTF-8
C++
false
false
2,702
cpp
// SCUM (4.24) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function ConZ.AmmunitionItem.SetAmmoCount // () // Parameters: // int* count (Parm, ZeroConstructor, IsPlainOldData) // bool* replicateToOwner (Parm, ZeroConstructor, IsPlainOldData) void ACal_9mm_C::SetAmmoCount(int* count, bool* replicateToOwner) { static auto fn = UObject::FindObject<UFunction>("Function ConZ.AmmunitionItem.SetAmmoCount"); ACal_9mm_C_SetAmmoCount_Params params; params.count = count; params.replicateToOwner = replicateToOwner; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ConZ.AmmunitionItem.OnRep_AmmoCountOwnerHelper // () void ACal_9mm_C::OnRep_AmmoCountOwnerHelper() { static auto fn = UObject::FindObject<UFunction>("Function ConZ.AmmunitionItem.OnRep_AmmoCountOwnerHelper"); ACal_9mm_C_OnRep_AmmoCountOwnerHelper_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ConZ.AmmunitionItem.OnRep_AmmoCount // () void ACal_9mm_C::OnRep_AmmoCount() { static auto fn = UObject::FindObject<UFunction>("Function ConZ.AmmunitionItem.OnRep_AmmoCount"); ACal_9mm_C_OnRep_AmmoCount_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ConZ.AmmunitionItem.GetAmmoCount // () // Parameters: // int ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) int ACal_9mm_C::GetAmmoCount() { static auto fn = UObject::FindObject<UFunction>("Function ConZ.AmmunitionItem.GetAmmoCount"); ACal_9mm_C_GetAmmoCount_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function ConZ.AmmunitionItem.Client_SetAmmoCount // () // Parameters: // int* count (Parm, ZeroConstructor, IsPlainOldData) void ACal_9mm_C::Client_SetAmmoCount(int* count) { static auto fn = UObject::FindObject<UFunction>("Function ConZ.AmmunitionItem.Client_SetAmmoCount"); ACal_9mm_C_Client_SetAmmoCount_Params params; params.count = count; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "60810131+frankie-11@users.noreply.github.com" ]
60810131+frankie-11@users.noreply.github.com
c0f033648e44b465084fee9839d767da8fe3a20f
3de461274828f91e7997298c496ffd5d49a15e51
/Beam/Include/Beam/Queues/Queues.hpp
349e2b9e73b23c3f9bc4f55b97073d48e865715e
[]
no_license
lineCode/beam
aaceffb36510d0e4551c81d67e9b5326bd3c0c94
8cd3d175118a9c9f17feb5ab272472de6ddc0327
refs/heads/master
2022-04-18T22:21:21.483345
2020-04-16T21:57:53
2020-04-16T21:57:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,717
hpp
#ifndef BEAM_QUEUES_HPP #define BEAM_QUEUES_HPP namespace Beam { template<typename T> class AbstractQueue; template<typename PublisherType> class AggregatePublisher; template<typename T> class AggregateQueue; template<typename T> class AliasQueue; class BaseCallbackWriterQueue; class BasePublisher; class BaseQueue; class CallbackQueue; template<typename T> class CallbackWriterQueue; template<typename TargetType, typename SourceQueueType, typename ConverterType> class ConverterReaderQueue; template<typename SourceType, typename TargetQueueType, typename ConverterType> class ConverterWriterQueue; template<typename PublisherType> class FilteredPublisher; template<typename SourceType, typename DestinationQueueType> class FilterWriterQueue; template<typename T> class MultiQueueReader; template<typename T> class MultiQueueWriter; class PipeBrokenException; template<typename T> class Publisher; template<typename T> class Queue; template<typename PublisherType> class QueuePublisher; template<typename T> class QueueReader; template<typename T> class QueueWriter; template<typename T, typename SequenceType> class SequencePublisher; template<typename T, typename SnapshotType> class SnapshotPublisher; template<typename T> class StatePublisher; template<typename T> class StateQueue; template<typename KeyType, typename ValueType> struct TableEntry; template<typename KeyType, typename ValueType> class TablePublisher; template<typename KeyType, typename ValueType> class TaggedQueue; class TaskQueue; template<typename ValueType, typename SnapshotType> class ValueSnapshotPublisher; template<typename T> class WeakQueue; } #endif
[ "kamal@eidolonsystems.com" ]
kamal@eidolonsystems.com
be7073a8bf68935d130eb85202b1287c1707bbea
5437328fa32923b6c13615c82a45d3657647d1fd
/cpid/estrainer.cpp
606a48f748e0445a2d3d807564b9fb8d19bae908
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ShawnshanksGui/TorchCraftAI
d6a2bf93ace07832a33d65dcd0eb3d19c3b6a82c
65f345b70662e8236fcb40201040c3c99f401df6
refs/heads/master
2020-06-05T16:39:09.146369
2019-04-17T18:25:47
2019-04-17T18:25:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,822
cpp
/* * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "estrainer.h" #include "batcher.h" #include "common/rand.h" #include "evaluator.h" #include "policygradienttrainer.h" #include "sampler.h" #include "distributed.h" #include <ATen/CPUGenerator.h> #ifdef HAVE_CUDA #include <ATen/CUDAGenerator.h> #endif #include <math.h> namespace cpid { namespace { struct Fan { explicit Fan(torch::Tensor& tensor) { const auto dimensions = tensor.ndimension(); AT_CHECK( dimensions >= 2, "Fan in and fan out can not be computed for tensor with fewer than 2 " "dimensions"); if (dimensions == 2) { in = tensor.size(1); out = tensor.size(0); } else { in = tensor.size(1) * tensor[0][0].numel(); out = tensor.size(0) * tensor[0][0].numel(); } } int64_t in; int64_t out; }; } // namespace float kaiming_normal_(torch::Tensor tensor, double gain) { // Use Fan_in as default torch::NoGradGuard guard; Fan fan(tensor); return gain / std::sqrt(fan.in); } ESTrainer::ESTrainer( ag::Container model, ag::Optimizer optim, std::unique_ptr<BaseSampler> sampler, float std, size_t batchSize, size_t historyLength, bool antithetic, RewardTransform transform, bool onPolicy) : Trainer(model, optim, std::move(sampler), nullptr), std_(std), batchSize_(batchSize), historyLength_(historyLength), antithetic_(antithetic), transform_(transform), onPolicy_(onPolicy), gatherSize_(batchSize_ * distributed::globalContext()->size), allRewards_(gatherSize_), allGenerations_(gatherSize_), allSeeds_(gatherSize_), rewards_(batchSize_), generations_(batchSize_), seeds_(batchSize_) { auto clone = ag::clone(model_); modelsHistory_.emplace_back(0, clone); } void ESTrainer::stepEpisode( GameUID const& gameUID, EpisodeKey const& key, ReplayBuffer::Episode& /*gen_episode*/) { { std::unique_lock<std::shared_timed_mutex> lock(insertionMutex_); // We put the most recent epsidoes to the back of the queue. // When learning, we retrieve starting from the back, too. This way // we are trying to use the freshest ones first. newGames_.emplace_back(std::make_pair(gameUID, key)); } { // free the model: update() would regenerate it when needed auto perturbedModelKey = std::make_pair(gameUID, key); std::unique_lock<std::shared_timed_mutex> lock(modelStorageMutex_); modelCache_.erase(gameToGenerationSeed_[perturbedModelKey]); } } bool ESTrainer::update() { // ES should never need gradients really torch::NoGradGuard guard; namespace dist = distributed; std::lock_guard<std::mutex> updateLock(updateMutex_); // TODO: split in smaller methods { std::shared_lock<std::shared_timed_mutex> lock(insertionMutex_); if (newGames_.size() < batchSize_) { if (onPolicy_ && gamesStarted_ < batchSize_) { batchBarrier_.notify_all(); } return false; } if (onPolicy_ && (gamesStarted_ > batchSize_)) { LOG(FATAL) << "onPolicy, but we have too many games playing/played" << " gamesStarted_ = " << gamesStarted_; } } if (metricsContext_) { metricsContext_->pushEvent("trainer:batch"); } MetricsContext::Timer modelUpdateTimer( metricsContext_, "trainer:model_update"); auto currentParams = model_->named_parameters(); // TODO: inefficient optim_->zero_grad(); for (size_t b = 0; b < batchSize_; ++b) { std::vector<RewardBufferFrame const*> episode; GameUID gameUID; EpisodeKey key; { std::unique_lock<std::shared_timed_mutex> lock(insertionMutex_); gameUID = newGames_.back().first; key = newGames_.back().second; episode = cast<RewardBufferFrame>(replayer_.get(gameUID, key)); newGames_.pop_back(); } float episodeReward = 0.0; for (size_t i = 0; i < episode.size(); ++i) { episodeReward += episode[i]->reward; } auto perturbedModelKey = std::make_pair(gameUID, key); int generation; int64_t seed; { std::shared_lock<std::shared_timed_mutex> lock(modelStorageMutex_); auto modelKey = gameToGenerationSeed_[perturbedModelKey]; generation = modelKey.first; seed = modelKey.second; } rewards_[b] = episodeReward; seeds_[b] = seed; generations_[b] = generation; // clean up replayer_.erase(gameUID, key); std::unique_lock<std::shared_timed_mutex> lock(modelStorageMutex_); gameToGenerationSeed_.erase(perturbedModelKey); } { MetricsContext::Timer timeAllreduce( metricsContext_, "trainer:network_time"); dist::allgather(allRewards_.data(), rewards_.data(), (int)batchSize_); dist::allgather( allGenerations_.data(), generations_.data(), (int)batchSize_); dist::allgather(allSeeds_.data(), seeds_.data(), (int)batchSize_); } float meanBatchReward = std::accumulate(allRewards_.begin(), allRewards_.end(), 0.0f) / gatherSize_; auto rewardsAsT = torch::from_blob(allRewards_.data(), {(int64_t)gatherSize_}); auto rewardsTransformed = rewardTransform(rewardsAsT, transform_); float meanGenerationsDelay = 0.0; int oldestGeneration = modelsHistory_.front().first; int latestGeneration = modelsHistory_.back().first; size_t outdatedEpisodes = 0; for (auto g : allGenerations_) { outdatedEpisodes += oldestGeneration > g ? 1 : 0; } if (outdatedEpisodes >= gatherSize_ / 2) { VLOG(0) << "Too many outdated episodes, " << outdatedEpisodes << "/" << gatherSize_ << ", consider increasing history length"; } for (size_t b = 0; b < gatherSize_; ++b) { int generation = allGenerations_[b]; int64_t seed = allSeeds_[b]; float reward = rewardsTransformed[b].item<float>(); ag::Container originalModel; { if (oldestGeneration > generation) { // we have an episode generated by perturbing a model that is too // old to be stored in the history. We skip such an episode. continue; } originalModel = modelsHistory_[generation - oldestGeneration].second; } // TODO: lookup in the cache for the local models ag::Container perturbedModel = generateModel(generation, seed); auto perturbedParams = perturbedModel->named_parameters(); double importanceWeight = 1.0; if (generation != latestGeneration) { if (onPolicy_) { LOG(FATAL) << "While onPolicy, got episode of generation " << generation << "while the current one is " << latestGeneration; } meanGenerationsDelay += latestGeneration - generation; // the perturbedModel was sampled from // N(originalParams, std_), but we want to pretend it was sampled from // N(model_, std_) importance weight would be iw = P(perturbed | model_, // std_) / P(perturbed | originalModel, std_) => log(iw) = 0.5 * // (-(perturbed - model_)^2 + (perturbed - originalModel_)^2) / std_^2 auto originalParams = originalModel->named_parameters(); double logImportanceWeight = 0.0; for (auto& it : currentParams) { auto& name = it.key(); auto& perturbedTensor = perturbedParams[name]; auto& originalTensor = originalParams[name]; auto& currentTensor = currentParams[name]; logImportanceWeight += -(perturbedTensor - currentTensor).pow_(2.0).sum().item<float>() + (perturbedTensor - originalTensor).pow_(2.0).sum().item<float>(); } logImportanceWeight *= 0.5 / std_ / std_; importanceWeight = exp(logImportanceWeight); importanceWeight = importanceWeight > 1.0 ? 1.0 : importanceWeight; } for (auto& it : currentParams) { auto& name = it.key(); auto& modelVar = it.value(); auto& modelValue = it.value(); auto& pertrubedValue = perturbedParams[name]; auto gradEstimate = pertrubedValue - modelValue; // Need to flip the sign as we maximize; we also adjust the normalizer to // account for outdated episodes which we have thrown away. In case if all // episodes are outdated, this line is never executed. gradEstimate.mul_( -1.0 * reward / std_ * importanceWeight / (gatherSize_ - outdatedEpisodes)); if (modelVar.grad().defined()) { modelVar.grad().add_(gradEstimate); } else { modelVar.grad() = torch::Tensor(gradEstimate).set_requires_grad(true); } } // end NoGradGuard } { std::unique_lock<std::shared_timed_mutex> lock(currentModelMutex_); optim_->step(); auto clone = ag::clone(model_); assert(clone->options() == model_->options()); int newGeneration = latestGeneration + 1; modelsHistory_.emplace_back(newGeneration, clone); if (modelsHistory_.size() > historyLength_) { modelsHistory_.pop_front(); } } if (metricsContext_) { metricsContext_->pushEvent("trainer:batch_policy_loss", 0.0); metricsContext_->pushEvent("trainer:batch_value_loss", 0.0); metricsContext_->pushEvent("trainer:batch_loss", 0.0); metricsContext_->pushEvent("trainer:mean_batch_reward", meanBatchReward); metricsContext_->snapshotCounter("steps", "trainer:steps_per_batch", 0); metricsContext_->pushEvent( "trainer:mean_generations_delay", meanGenerationsDelay / gatherSize_); metricsContext_->incCounter("trainer:model_updates"); metricsContext_->incCounter("trainer:outdated_episodes", outdatedEpisodes); } if (onPolicy_) { std::lock_guard<std::shared_timed_mutex> mapLock(activeMapMutex_); if (!actives_.empty()) { LOG(FATAL) << "onPolicy, but somehow we have games at the end of the update!"; } std::shared_lock<std::shared_timed_mutex> insertLock(insertionMutex_); // It is possible that after a reset() some new games would be pushed, // hence in the first learning after a reset there could be more than // batchSize_ games in the buffer. newGames_.clear(); replayer_.clear(); gamesStarted_ = 0; if (!waitUpdate_) { batchBarrier_.notify_all(); } } return true; } void ESTrainer::forceStopEpisode(EpisodeHandle const& handle) { { std::unique_lock<std::mutex> updateLock(updateMutex_); if (onPolicy_ && isActive(handle)) { LOG_IF(FATAL, gamesStarted_ == 0) << "Stopping episode but gamesStarted_=0 already"; gamesStarted_--; } } Trainer::forceStopEpisode(handle); } Trainer::EpisodeHandle ESTrainer::startEpisode() { using namespace std::chrono_literals; auto handle = [&]() { std::unique_lock<std::mutex> updateLock(updateMutex_); if (onPolicy_) { while (true) { // we need to produce a game, so we proceed if (gamesStarted_ < batchSize_) { break; } auto wakeReason = batchBarrier_.wait_for(updateLock, 100ms); if (wakeReason == std::cv_status::timeout) { return EpisodeHandle(); } } gamesStarted_++; } return Trainer::startEpisode(); }(); if (!handle) { return handle; } auto modelKey = std::make_pair(handle.gameID(), handle.episodeKey()); int64_t seed; // To implement the variance reduction via antithetic variates, // we always generate seeds in pairs with swapped signs: seed and -seed. // Hence, we first check if there's a seed value stashed before, otherwise // generate a new one and stash its pair in the seedQueue. { std::lock_guard<std::mutex> lock(seedQueueMutex_); if (seedQueue_.empty()) { populateSeedQueue(); } seed = seedQueue_.back(); seedQueue_.pop_back(); } int generation; { std::shared_lock<std::shared_timed_mutex> lock(currentModelMutex_); generation = modelsHistory_.back().first; } auto model = generateModel(generation, seed); { std::unique_lock<std::shared_timed_mutex> lock(modelStorageMutex_); auto generationSeed = std::make_pair(generation, seed); gameToGenerationSeed_[modelKey] = generationSeed; modelCache_[generationSeed] = model; } return handle; } ag::Container ESTrainer::getGameModel( GameUID const& gameUID, EpisodeKey const& key) { if (!this->train_) { return model_; } auto modelKey = std::make_pair(gameUID, key); { // model was already generated std::shared_lock<std::shared_timed_mutex> lock(modelStorageMutex_); auto lookup = gameToGenerationSeed_.find(modelKey); if (lookup != gameToGenerationSeed_.end()) { auto generationSeedPair = lookup->second; return modelCache_[generationSeedPair]; } else { return model_; } } } /// Re-creates model based on its seed and the generation it was produced from. /// The absolute value of the seed is used for seeding, and its sign indicates /// if we add or subtract the noise, which is used to implement antithetic /// variates. ag::Container ESTrainer::generateModel(int generation, int64_t seed) { torch::NoGradGuard guard; ag::Container originalModel; { std::shared_lock<std::shared_timed_mutex> lock(currentModelMutex_); auto oldestGeneration = modelsHistory_.front().first; if (oldestGeneration > generation) { // shouldn't happen that we call generateModel with a too old generation, // the only unlikely case is that the whole historyLength_ was maxed // during a single startEpisode call throw std::runtime_error( "Cannot generate a model from a too old generation, increase history " "length!"); } originalModel = modelsHistory_[generation - oldestGeneration].second; } auto perturbed = ag::clone(originalModel); std::shared_ptr<at::Generator> generator; if (perturbed->options().device().is_cuda()) { #ifdef HAVE_CUDA generator = std::make_shared<at::CUDAGenerator>(&at::globalContext()); assert(perturbed->options() == originalModel->options()); #endif } else { generator = std::make_shared<at::CPUGenerator>(&at::globalContext()); assert(perturbed->options() == originalModel->options()); } // The actually applied perturbation would be sign(seed) * noise(abs(seed)) generator->manualSeed(seed < 0 ? -seed : seed); auto clonedParams = perturbed->parameters(); for (auto& tensor : clonedParams) { float realStd = std_; if (tensor.ndimension() != 1) { realStd *= kaiming_normal_(tensor, std::sqrt(2.0)); } auto delta = at::zeros_like(tensor).normal_(0, realStd, generator.get()); tensor.add_(delta, seed < 0 ? -1.0 : 1.0); } return perturbed; // END NoGradGuard } ag::Variant ESTrainer::forward(ag::Variant inp, EpisodeHandle const& handle) { MetricsContext::Timer forwardTimer( metricsContext_, "trainer:forward", kFwdMetricsSubsampling); ag::Container model = getGameModel(handle.gameID(), handle.episodeKey()); torch::NoGradGuard g; return forwardUnbatched(inp, model); } std::shared_ptr<Evaluator> ESTrainer::makeEvaluator( size_t n, std::unique_ptr<BaseSampler> sampler) { return evaluatorFactory( model_, std::move(sampler), n, [this](ag::Variant inp, EpisodeHandle const& handle) { torch::NoGradGuard g; return this->forwardUnbatched(inp); }); } torch::Tensor ESTrainer::rewardTransform( torch::Tensor const& rewards, ESTrainer::RewardTransform transform) { auto transformed = rewards.clone(); int64_t size = rewards.size(0); switch (transform) { case kNone: break; case kRankTransform: { auto indices = std::get<1>(at::sort(transformed, 0)); auto tmp = torch::range(0, size - 1, 1, at::CPU(at::kFloat)) .div_(size - 1.0) .add_(-0.5f); transformed.index_copy_(0, indices, tmp); } break; case kStdNormalize: if (size > 0) { transformed.div_(transformed.std() + 1e-8); } break; default: throw std::runtime_error("Unknown reward transform!"); break; } return transformed; } void ESTrainer::populateSeedQueue() { auto seed = (int64_t)common::Rand::rand(); seedQueue_.push_back(seed); if (antithetic_) { seedQueue_.push_back(-seed); } } void ESTrainer::reset() { if (onPolicy_) { std::unique_lock<std::mutex> updateLock(updateMutex_); Trainer::reset(); gamesStarted_ = 0; newGames_.clear(); batchBarrier_.notify_all(); return; } Trainer::reset(); } std::shared_ptr<ReplayBufferFrame> ESTrainer::makeFrame( ag::Variant /*trainerOutput*/, ag::Variant /*state*/, float reward) { return std::make_shared<RewardBufferFrame>(reward); } } // namespace cpid
[ "danthe3rd@users.noreply.github.com" ]
danthe3rd@users.noreply.github.com
ba8c25a2ea596ec2317f239e1b0d6c66f4039cd4
297d263d30ee4ce8ee66b5a581c687a129af7de6
/src/utils/Defer.cpp
be240719ba4875e2867bf546cc77acf414225624
[]
no_license
LUMAIS/artemis
bd0fdce7d2b56e3e9f6ba29e28ce1b4fb65b264e
7c4c4e3f83233525903a5981f75996169146a1f2
refs/heads/master
2023-08-03T12:59:11.189128
2023-06-28T08:46:23
2023-06-28T09:26:59
279,585,178
1
1
null
null
null
null
UTF-8
C++
false
false
136
cpp
#include "Defer.hpp" Defer::Defer(const std::function<void()> & toDefer) : d_toDefer(toDefer) {} Defer::~Defer() { d_toDefer(); }
[ "alexandre.tuleu.2005@polytechnique.org" ]
alexandre.tuleu.2005@polytechnique.org
d8c673d3393c67c6cf4833df19b46e3b5568af4a
536a80a503da4371ece77ac8602e00a399d33d44
/folly/experimental/io/test/IoUringBackendTest.cpp
f6ae03f6f2e1b2b068102cc6808f63ba1bd70cf3
[ "MIT", "Apache-2.0" ]
permissive
asklar/folly
122a32fc610c36ce9ca4e89d658c26c4608b8920
a24e4441f972cc9ab8a8cb350d701e9d87826a48
refs/heads/master
2023-04-29T09:29:38.499814
2020-09-18T22:04:00
2020-09-18T22:04:00
295,598,687
0
0
Apache-2.0
2020-09-15T02:59:31
2020-09-15T02:59:31
null
UTF-8
C++
false
false
26,474
cpp
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 <sys/eventfd.h> #include <numeric> #include <folly/FileUtil.h> #include <folly/String.h> #include <folly/experimental/io/IoUringBackend.h> #include <folly/experimental/io/test/IoTestTempFileUtil.h> #include <folly/init/Init.h> #include <folly/io/async/AsyncUDPServerSocket.h> #include <folly/io/async/AsyncUDPSocket.h> #include <folly/io/async/EventHandler.h> #include <folly/io/async/test/EventBaseTestLib.h> #include <folly/portability/GTest.h> // IoUringBackend specific tests namespace { class AlignedBuf { public: static constexpr size_t kAlign = 4096; AlignedBuf() = delete; AlignedBuf(size_t count, char ch) : size_(count) { ::posix_memalign(&data_, kAlign, size_); CHECK(!!data_); ::memset(data_, ch, count); } AlignedBuf(const AlignedBuf& buf) : size_(buf.size_) { if (size_) { ::posix_memalign(&data_, kAlign, size_); CHECK(!!data_); ::memcpy(data_, buf.data_, size_); } } ~AlignedBuf() { if (data_) { ::free(data_); } } AlignedBuf& operator=(const AlignedBuf& buf) { if (data_) { ::free(data_); } size_ = buf.size_; if (size_) { ::posix_memalign(&data_, kAlign, size_); CHECK(!!data_); ::memcpy(data_, buf.data_, size_); } return *this; } bool operator==(const AlignedBuf& buf) const { if (size_ != buf.size_) { return false; } if (size_ == 0) { return true; } return (0 == ::memcmp(data_, buf.data_, size_)); } bool operator!=(const AlignedBuf& buf) const { return !(*this == buf); } void* data() const { return data_; } size_t size() const { return size_; } private: void* data_{nullptr}; size_t size_{0}; }; class EventFD : public folly::EventHandler, public folly::EventReadCallback { public: EventFD( bool valid, uint64_t num, uint64_t& total, bool persist, folly::EventBase* eventBase) : EventFD(total, valid ? createFd(num) : -1, persist, eventBase) {} ~EventFD() override { unregisterHandler(); if (fd_ >= 0) { ::close(fd_); fd_ = -1; } } void useAsyncReadCallback(bool val) { if (val) { setEventCallback(this); } else { resetEventCallback(); } } // from folly::EventHandler void handlerReady(uint16_t /*events*/) noexcept override { // we do not read to leave the fd signalled ++num_; if (total_ > 0) { --total_; } if (total_ > 0) { if (!persist_) { registerHandler(folly::EventHandler::READ); } } else { if (persist_) { unregisterHandler(); } } } uint64_t getAsyncNum() const { return asyncNum_; } uint64_t getNum() const { return num_; } // from folly::EventReadCallback folly::EventReadCallback::IoVec* allocateData() override { auto* ret = ioVecPtr_.release(); return (ret ? ret : new IoVec(this)); } private: struct IoVec : public folly::EventReadCallback::IoVec { IoVec() = delete; ~IoVec() override = default; explicit IoVec(EventFD* eventFd) { arg_ = eventFd; freeFunc_ = IoVec::free; cbFunc_ = IoVec::cb; data_.iov_base = &eventData_; data_.iov_len = sizeof(eventData_); } static void free(EventReadCallback::IoVec* ioVec) { delete ioVec; } static void cb(EventReadCallback::IoVec* ioVec, int res) { reinterpret_cast<EventFD*>(ioVec->arg_) ->cb(reinterpret_cast<IoVec*>(ioVec), res); } uint64_t eventData_{0}; }; static int createFd(uint64_t num) { // we want it a semaphore // and blocking for the async reads int fd = ::eventfd(0, EFD_CLOEXEC | EFD_SEMAPHORE); CHECK_GT(fd, 0); CHECK_EQ(folly::writeNoInt(fd, &num, sizeof(num)), sizeof(num)); return fd; } EventFD(uint64_t& total, int fd, bool persist, folly::EventBase* eventBase) : EventHandler(eventBase, folly::NetworkSocket::fromFd(fd)), total_(total), fd_(fd), persist_(persist), evb_(eventBase) { if (persist_) { registerHandler(folly::EventHandler::READ | folly::EventHandler::PERSIST); } else { registerHandler(folly::EventHandler::READ); } } void cb(IoVec* ioVec, int res) { CHECK_EQ(res, sizeof(IoVec::eventData_)); CHECK_EQ(ioVec->eventData_, 1); // reset it ioVec->eventData_ = 0; // save it for future use ioVecPtr_.reset(ioVec); ++asyncNum_; if (total_ > 0) { --total_; } if (total_ > 0) { if (!persist_) { registerHandler(folly::EventHandler::READ); } } else { if (persist_) { unregisterHandler(); } } } uint64_t asyncNum_{0}; uint64_t num_{0}; uint64_t& total_; int fd_{-1}; bool persist_; folly::EventBase* evb_; std::unique_ptr<IoVec> ioVecPtr_; }; std::unique_ptr<folly::EventBase> getEventBase( folly::PollIoBackend::Options opts) { try { auto factory = [opts] { return std::make_unique<folly::IoUringBackend>(opts); }; return std::make_unique<folly::EventBase>( folly::EventBase::Options().setBackendFactory(std::move(factory))); } catch (const folly::IoUringBackend::NotAvailable&) { return nullptr; } } void testEventFD(bool overflow, bool persist, bool asyncRead) { static constexpr size_t kBackendCapacity = 64; static constexpr size_t kBackendMaxSubmit = 32; // for overflow == true we use a greater than kBackendCapacity number of // EventFD instances and lower when overflow == false size_t kNumEventFds = overflow ? 2048 : 32; static constexpr size_t kEventFdCount = 16; auto total = kNumEventFds * kEventFdCount + kEventFdCount / 2; folly::PollIoBackend::Options options; options.setCapacity(kBackendCapacity).setMaxSubmit(kBackendMaxSubmit); auto evbPtr = getEventBase(options); SKIP_IF(!evbPtr) << "Backend not available"; std::vector<std::unique_ptr<EventFD>> eventsVec; eventsVec.reserve(kNumEventFds); for (size_t i = 0; i < kNumEventFds; i++) { auto ev = std::make_unique<EventFD>( true, 2 * kEventFdCount, total, persist, evbPtr.get()); ev->useAsyncReadCallback(asyncRead); eventsVec.emplace_back(std::move(ev)); } evbPtr->loop(); for (size_t i = 0; i < kNumEventFds; i++) { CHECK_GE( (asyncRead ? eventsVec[i]->getAsyncNum() : eventsVec[i]->getNum()), kEventFdCount); } } void testInvalidFd(size_t numTotal, size_t numValid, size_t numInvalid) { static constexpr size_t kBackendCapacity = 128; static constexpr size_t kBackendMaxSubmit = 64; auto total = numTotal; folly::PollIoBackend::Options options; options.setCapacity(kBackendCapacity).setMaxSubmit(kBackendMaxSubmit); auto evbPtr = getEventBase(options); SKIP_IF(!evbPtr) << "Backend not available"; std::vector<std::unique_ptr<EventFD>> eventsVec; eventsVec.reserve(numTotal); for (size_t i = 0; i < numTotal; i++) { bool valid = (i % (numValid + numInvalid)) < numValid; eventsVec.emplace_back(std::make_unique<EventFD>( valid, 1, total, false /*persist*/, evbPtr.get())); } evbPtr->loop(); for (size_t i = 0; i < numTotal; i++) { CHECK_GE(eventsVec[i]->getNum(), 1); } } class EventRecvmsgCallback : public folly::EventRecvmsgCallback { private: struct MsgHdr : public folly::EventRecvmsgCallback::MsgHdr { static auto constexpr kBuffSize = 1024; MsgHdr() = delete; ~MsgHdr() override = default; explicit MsgHdr(EventRecvmsgCallback* cb) { arg_ = cb; freeFunc_ = MsgHdr::free; cbFunc_ = MsgHdr::cb; ioBuf_ = folly::IOBuf::create(kBuffSize); } void reset() { ::memset(&data_, 0, sizeof(data_)); iov_.iov_base = ioBuf_->writableData(); iov_.iov_len = kBuffSize; data_.msg_iov = &iov_; data_.msg_iovlen = 1; ::memset(&addrStorage_, 0, sizeof(addrStorage_)); data_.msg_name = reinterpret_cast<sockaddr*>(&addrStorage_); data_.msg_namelen = sizeof(addrStorage_); } static void free(folly::EventRecvmsgCallback::MsgHdr* msgHdr) { delete msgHdr; } static void cb(folly::EventRecvmsgCallback::MsgHdr* msgHdr, int res) { reinterpret_cast<EventRecvmsgCallback*>(msgHdr->arg_) ->cb(reinterpret_cast<MsgHdr*>(msgHdr), res); } // data std::unique_ptr<folly::IOBuf> ioBuf_; struct iovec iov_; // addr struct sockaddr_storage addrStorage_; }; void cb(MsgHdr* msgHdr, int res) { // check the number of bytes CHECK_EQ(res, static_cast<int>(numBytes_)); // check the contents std::string data; data.assign( reinterpret_cast<const char*>(msgHdr->ioBuf_->data()), static_cast<size_t>(res)); CHECK_EQ(data, data_); // check the address folly::SocketAddress addr; addr.setFromSockaddr( reinterpret_cast<sockaddr*>(msgHdr->data_.msg_name), msgHdr->data_.msg_namelen); CHECK_EQ(addr, addr_); // reuse the msgHdr msgHdr_.reset(msgHdr); ++asyncNum_; if (total_ > 0) { --total_; if (total_ == 0) { evb_->terminateLoopSoon(); } } } public: EventRecvmsgCallback( const std::string& data, const folly::SocketAddress& addr, size_t numBytes, uint64_t& total, folly::EventBase* eventBase) : data_(data), addr_(addr), numBytes_(numBytes), total_(total), evb_(eventBase) {} ~EventRecvmsgCallback() override = default; // from EventRecvmsgCallback EventRecvmsgCallback::MsgHdr* allocateData() override { auto* ret = msgHdr_.release(); if (!ret) { ret = new MsgHdr(this); } ret->reset(); return ret; } uint64_t getAsyncNum() const { return asyncNum_; } private: const std::string& data_; folly::SocketAddress addr_; size_t numBytes_{0}; uint64_t& total_; folly::EventBase* evb_; uint64_t asyncNum_{0}; std::unique_ptr<MsgHdr> msgHdr_; }; void testAsyncUDPRecvmsg(bool useRegisteredFds) { static constexpr size_t kBackendCapacity = 64; static constexpr size_t kBackendMaxSubmit = 32; static constexpr size_t kBackendMaxGet = 32; static constexpr size_t kNumSockets = 32; static constexpr size_t kNumBytes = 16; static constexpr size_t kNumPackets = 32; auto total = kNumPackets * kNumSockets; folly::PollIoBackend::Options options; options.setCapacity(kBackendCapacity) .setMaxSubmit(kBackendMaxSubmit) .setMaxGet(kBackendMaxGet) .setUseRegisteredFds(useRegisteredFds); auto evbPtr = getEventBase(options); SKIP_IF(!evbPtr) << "Backend not available"; // create the server sockets std::vector<std::unique_ptr<folly::AsyncUDPServerSocket>> serverSocketVec; serverSocketVec.reserve(kNumSockets); std::vector<std::unique_ptr<folly::AsyncUDPSocket>> clientSocketVec; serverSocketVec.reserve(kNumSockets); std::vector<std::unique_ptr<EventRecvmsgCallback>> cbVec; cbVec.reserve(kNumSockets); std::string data(kNumBytes, 'A'); for (size_t i = 0; i < kNumSockets; i++) { auto clientSock = std::make_unique<folly::AsyncUDPSocket>(evbPtr.get()); clientSock->bind(folly::SocketAddress("::1", 0)); auto cb = std::make_unique<EventRecvmsgCallback>( data, clientSock->address(), kNumBytes, total, evbPtr.get()); auto serverSock = std::make_unique<folly::AsyncUDPServerSocket>( evbPtr.get(), 1500, folly::AsyncUDPServerSocket::DispatchMechanism::RoundRobin); // set the event callback serverSock->setEventCallback(cb.get()); // bind serverSock->bind(folly::SocketAddress("::1", 0)); // retrieve the real address folly::SocketAddress addr = serverSock->address(); serverSock->listen(); serverSocketVec.emplace_back(std::move(serverSock)); // connect the client clientSock->connect(addr); for (size_t j = 0; j < kNumPackets; j++) { auto buf = folly::IOBuf::copyBuffer(data.c_str(), data.size()); CHECK_EQ(clientSock->write(addr, std::move(buf)), data.size()); } clientSocketVec.emplace_back(std::move(clientSock)); cbVec.emplace_back(std::move(cb)); } evbPtr->loopForever(); for (size_t i = 0; i < kNumSockets; i++) { CHECK_GE(cbVec[i]->getAsyncNum(), kNumPackets); } } } // namespace TEST(IoUringBackend, AsyncUDPRecvmsgNoRegisterFd) { testAsyncUDPRecvmsg(false); } TEST(IoUringBackend, AsyncUDPRecvmsgRegisterFd) { testAsyncUDPRecvmsg(true); } TEST(IoUringBackend, EventFD_NoOverflowNoPersist) { testEventFD(false, false, false); } TEST(IoUringBackend, EventFD_OverflowNoPersist) { testEventFD(true, false, false); } TEST(IoUringBackend, EventFD_NoOverflowPersist) { testEventFD(false, true, false); } TEST(IoUringBackend, EventFD_OverflowPersist) { testEventFD(true, true, false); } TEST(IoUringBackend, EventFD_Persist_AsyncRead) { testEventFD(false, true, true); } // 9 valid fds followed by an invalid one TEST(IoUringBackend, Invalid_fd_9_1) { testInvalidFd(32, 10, 1); } // only invalid fds TEST(IoUringBackend, Invalid_fd_0_10) { testInvalidFd(32, 0, 10); } // equal distribution TEST(IoUringBackend, Invalid_fd_5_5) { testInvalidFd(32, 10, 10); } TEST(IoUringBackend, RegisteredFds) { static constexpr size_t kBackendCapacity = 64; static constexpr size_t kBackendMaxSubmit = 32; static constexpr size_t kBackendMaxGet = 32; std::unique_ptr<folly::IoUringBackend> backendReg; std::unique_ptr<folly::IoUringBackend> backendNoReg; try { folly::PollIoBackend::Options options; options.setCapacity(kBackendCapacity) .setMaxSubmit(kBackendMaxSubmit) .setMaxGet(kBackendMaxGet) .setUseRegisteredFds(true); backendReg = std::make_unique<folly::IoUringBackend>(options); options.setUseRegisteredFds(false); backendNoReg = std::make_unique<folly::IoUringBackend>(options); } catch (const folly::IoUringBackend::NotAvailable&) { } SKIP_IF(!backendReg) << "Backend not available"; SKIP_IF(!backendNoReg) << "Backend not available"; int eventFd = ::eventfd(0, EFD_CLOEXEC | EFD_SEMAPHORE | EFD_NONBLOCK); CHECK_GT(eventFd, 0); SCOPE_EXIT { ::close(eventFd); }; // verify for useRegisteredFds = false we get a nullptr FdRegistrationRecord auto* record = backendNoReg->registerFd(eventFd); CHECK(!record); std::vector<folly::IoUringBackend::FdRegistrationRecord*> records; // we use kBackendCapacity -1 since we can have the timerFd // already using one fd records.reserve(kBackendCapacity - 1); for (size_t i = 0; i < kBackendCapacity - 1; i++) { record = backendReg->registerFd(eventFd); CHECK(record); records.emplace_back(record); } // try to allocate one more and check if we get a nullptr record = backendReg->registerFd(eventFd); CHECK(!record); // deallocate and allocate again for (size_t i = 0; i < records.size(); i++) { CHECK(backendReg->unregisterFd(records[i])); record = backendReg->registerFd(eventFd); CHECK(record); records[i] = record; } } TEST(IoUringBackend, FileReadWrite) { static constexpr size_t kBackendCapacity = 2048; static constexpr size_t kBackendMaxSubmit = 32; static constexpr size_t kBackendMaxGet = 32; folly::PollIoBackend::Options options; options.setCapacity(kBackendCapacity) .setMaxSubmit(kBackendMaxSubmit) .setMaxGet(kBackendMaxGet) .setUseRegisteredFds(false); auto evbPtr = getEventBase(options); SKIP_IF(!evbPtr) << "Backend not available"; static constexpr size_t kNumBlocks = 512; static constexpr size_t kBlockSize = 4096; static constexpr size_t kFileSize = kNumBlocks * kBlockSize; auto tempFile = folly::test::TempFileUtil::getTempFile(kFileSize); int fd = ::open(tempFile.path().c_str(), O_DIRECT | O_RDWR); SKIP_IF(fd == -1) << "Tempfile can't be opened with O_DIRECT: " << folly::errnoStr(errno); SCOPE_EXIT { ::close(fd); }; auto* backendPtr = dynamic_cast<folly::IoUringBackend*>(evbPtr->getBackend()); CHECK(!!backendPtr); size_t num = 0; AlignedBuf writeData(kBlockSize, 'A'), readData(kBlockSize, 'Z'); std::vector<AlignedBuf> writeDataVec(kNumBlocks, writeData), readDataVec(kNumBlocks, readData); CHECK(readData != writeData); for (size_t i = 0; i < kNumBlocks; i++) { folly::IoUringBackend::FileOpCallback writeCb = [&, i](int res) { CHECK_EQ(res, writeDataVec[i].size()); folly::IoUringBackend::FileOpCallback readCb = [&, i](int res) { CHECK_EQ(res, readDataVec[i].size()); CHECK(readDataVec[i] == writeDataVec[i]); ++num; }; backendPtr->queueRead( fd, readDataVec[i].data(), readDataVec[i].size(), i * kBlockSize, std::move(readCb)); }; backendPtr->queueWrite( fd, writeDataVec[i].data(), writeDataVec[i].size(), i * kBlockSize, std::move(writeCb)); } evbPtr->loop(); EXPECT_EQ(num, kNumBlocks); } TEST(IoUringBackend, FileReadvWritev) { static constexpr size_t kBackendCapacity = 2048; static constexpr size_t kBackendMaxSubmit = 32; static constexpr size_t kBackendMaxGet = 32; folly::PollIoBackend::Options options; options.setCapacity(kBackendCapacity) .setMaxSubmit(kBackendMaxSubmit) .setMaxGet(kBackendMaxGet) .setUseRegisteredFds(false); auto evbPtr = getEventBase(options); SKIP_IF(!evbPtr) << "Backend not available"; static constexpr size_t kNumBlocks = 512; static constexpr size_t kNumIov = 4; static constexpr size_t kIovSize = 4096; static constexpr size_t kBlockSize = kNumIov * kIovSize; static constexpr size_t kFileSize = kNumBlocks * kBlockSize; auto tempFile = folly::test::TempFileUtil::getTempFile(kFileSize); int fd = ::open(tempFile.path().c_str(), O_DIRECT | O_RDWR); SKIP_IF(fd == -1) << "Tempfile can't be opened with O_DIRECT: " << folly::errnoStr(errno); SCOPE_EXIT { ::close(fd); }; auto* backendPtr = dynamic_cast<folly::IoUringBackend*>(evbPtr->getBackend()); CHECK(!!backendPtr); size_t num = 0; AlignedBuf writeData(kIovSize, 'A'), readData(kIovSize, 'Z'); std::vector<AlignedBuf> writeDataVec(kNumIov, writeData), readDataVec(kNumIov, readData); std::vector<std::vector<AlignedBuf>> writeDataVecVec( kNumBlocks, writeDataVec), readDataVecVec(kNumBlocks, readDataVec); CHECK(readDataVec != writeDataVec); std::vector<std::vector<struct iovec>> readDataIov, writeDataIov; std::vector<size_t> lenVec; readDataIov.reserve(kNumBlocks); writeDataIov.reserve(kNumBlocks); lenVec.reserve(kNumBlocks); for (size_t i = 0; i < kNumBlocks; i++) { size_t len = 0; std::vector<struct iovec> readIov, writeIov; readIov.reserve(kNumIov); writeIov.reserve(kNumIov); for (size_t j = 0; j < kNumIov; j++) { struct iovec riov { readDataVecVec[i][j].data(), readDataVecVec[i][j].size() }; readIov.push_back(riov); struct iovec wiov { writeDataVecVec[i][j].data(), writeDataVecVec[i][j].size() }; writeIov.push_back(wiov); len += riov.iov_len; } readDataIov.emplace_back(std::move(readIov)); writeDataIov.emplace_back(std::move(writeIov)); lenVec.emplace_back(len); } for (size_t i = 0; i < kNumBlocks; i++) { folly::IoUringBackend::FileOpCallback writeCb = [&, i](int res) { CHECK_EQ(res, lenVec[i]); folly::IoUringBackend::FileOpCallback readCb = [&, i](int res) { CHECK_EQ(res, lenVec[i]); CHECK(readDataVecVec[i] == writeDataVecVec[i]); if (++num == kNumBlocks) { evbPtr->terminateLoopSoon(); } }; backendPtr->queueReadv( fd, readDataIov[i], i * kBlockSize, std::move(readCb)); }; backendPtr->queueWritev( fd, writeDataIov[i], i * kBlockSize, std::move(writeCb)); } evbPtr->loopForever(); EXPECT_EQ(num, kNumBlocks); } TEST(IoUringBackend, FileReadMany) { static constexpr size_t kBackendCapacity = 1024; static constexpr size_t kBackendMaxSubmit = 128; static constexpr size_t kBackendMaxGet = 128; folly::PollIoBackend::Options options; options.setCapacity(kBackendCapacity) .setMaxSubmit(kBackendMaxSubmit) .setMaxGet(kBackendMaxGet) .setUseRegisteredFds(false); auto evbPtr = getEventBase(options); SKIP_IF(!evbPtr) << "Backend not available"; static constexpr size_t kNumBlocks = 8 * 1024; static constexpr size_t kBlockSize = 4096; static constexpr size_t kBigBlockSize = 2 * 1024 * 1024; static constexpr size_t kFileSize = kNumBlocks * kBlockSize; auto tempFile = folly::test::TempFileUtil::getTempFile(kFileSize); int fd = ::open(tempFile.path().c_str(), O_DIRECT | O_RDWR); SKIP_IF(fd == -1) << "Tempfile can't be opened with O_DIRECT: " << folly::errnoStr(errno); SCOPE_EXIT { ::close(fd); }; auto* backendPtr = dynamic_cast<folly::IoUringBackend*>(evbPtr->getBackend()); CHECK(!!backendPtr); size_t num = 0; AlignedBuf readData(kBlockSize, 'Z'); std::vector<AlignedBuf> readDataVec(kNumBlocks, readData); AlignedBuf bigReadData(kBigBlockSize, 'Z'); for (size_t i = 0; i < kNumBlocks; i++) { folly::IoUringBackend::FileOpCallback readCb = [&, i](int res) { CHECK_EQ(res, readDataVec[i].size()); ++num; }; backendPtr->queueRead( fd, readDataVec[i].data(), readDataVec[i].size(), i * kBlockSize, std::move(readCb)); } folly::IoUringBackend::FileOpCallback bigReadCb = [&](int res) { CHECK_EQ(res, bigReadData.size()); }; backendPtr->queueRead( fd, bigReadData.data(), bigReadData.size(), 0, std::move(bigReadCb)); evbPtr->loop(); EXPECT_EQ(num, kNumBlocks); } TEST(IoUringBackend, FileWriteMany) { static constexpr size_t kBackendCapacity = 1024; static constexpr size_t kBackendMaxSubmit = 128; static constexpr size_t kBackendMaxGet = 128; folly::PollIoBackend::Options options; options.setCapacity(kBackendCapacity) .setMaxSubmit(kBackendMaxSubmit) .setMaxGet(kBackendMaxGet) .setUseRegisteredFds(false); auto evbPtr = getEventBase(options); SKIP_IF(!evbPtr) << "Backend not available"; static constexpr size_t kNumBlocks = 8 * 1024; static constexpr size_t kBlockSize = 4096; static constexpr size_t kBigBlockSize = 2 * 1024 * 1024; static constexpr size_t kFileSize = kNumBlocks * kBlockSize; auto tempFile = folly::test::TempFileUtil::getTempFile(kFileSize); int fd = ::open(tempFile.path().c_str(), O_DIRECT | O_RDWR); SKIP_IF(fd == -1) << "Tempfile can't be opened with O_DIRECT: " << folly::errnoStr(errno); SCOPE_EXIT { ::close(fd); }; auto* backendPtr = dynamic_cast<folly::IoUringBackend*>(evbPtr->getBackend()); CHECK(!!backendPtr); size_t num = 0; AlignedBuf writeData(kBlockSize, 'A'); std::vector<AlignedBuf> writeDataVec(kNumBlocks, writeData); AlignedBuf bigWriteData(kBigBlockSize, 'A'); bool bFdatasync = false; for (size_t i = 0; i < kNumBlocks; i++) { folly::IoUringBackend::FileOpCallback writeCb = [&, i](int res) { CHECK_EQ(res, writeDataVec[i].size()); ++num; if (num == kNumBlocks) { folly::IoUringBackend::FileOpCallback fdatasyncCb = [&](int res) { CHECK_EQ(res, 0); bFdatasync = true; }; backendPtr->queueFdatasync(fd, std::move(fdatasyncCb)); } }; backendPtr->queueWrite( fd, writeDataVec[i].data(), writeDataVec[i].size(), i * kBlockSize, std::move(writeCb)); } evbPtr->loop(); EXPECT_EQ(num, kNumBlocks); EXPECT_EQ(bFdatasync, true); bool bFsync = false; folly::IoUringBackend::FileOpCallback bigWriteCb = [&](int res) { CHECK_EQ(res, bigWriteData.size()); folly::IoUringBackend::FileOpCallback fsyncCb = [&](int res) { CHECK_EQ(res, 0); bFsync = true; }; backendPtr->queueFsync(fd, std::move(fsyncCb)); }; backendPtr->queueWrite( fd, bigWriteData.data(), bigWriteData.size(), 0, std::move(bigWriteCb)); evbPtr->loop(); EXPECT_EQ(bFsync, true); } namespace folly { namespace test { static constexpr size_t kCapacity = 16 * 1024; static constexpr size_t kMaxSubmit = 128; static constexpr size_t kMaxGet = static_cast<size_t>(-1); struct IoUringBackendProvider { static std::unique_ptr<folly::EventBaseBackendBase> getBackend() { try { folly::PollIoBackend::Options options; options.setCapacity(kCapacity) .setMaxSubmit(kMaxSubmit) .setMaxGet(kMaxGet) .setUseRegisteredFds(false); return std::make_unique<folly::IoUringBackend>(options); } catch (const IoUringBackend::NotAvailable&) { return nullptr; } } }; struct IoUringRegFdBackendProvider { static std::unique_ptr<folly::EventBaseBackendBase> getBackend() { try { folly::PollIoBackend::Options options; options.setCapacity(kCapacity) .setMaxSubmit(kMaxSubmit) .setMaxGet(kMaxGet) .setUseRegisteredFds(true); return std::make_unique<folly::IoUringBackend>(options); } catch (const IoUringBackend::NotAvailable&) { return nullptr; } } }; // Instantiate the non registered fd tests INSTANTIATE_TYPED_TEST_CASE_P(IoUring, EventBaseTest, IoUringBackendProvider); INSTANTIATE_TYPED_TEST_CASE_P(IoUring, EventBaseTest1, IoUringBackendProvider); // Instantiate the registered fd tests INSTANTIATE_TYPED_TEST_CASE_P( IoUringRegFd, EventBaseTest, IoUringRegFdBackendProvider); INSTANTIATE_TYPED_TEST_CASE_P( IoUringRegFd, EventBaseTest1, IoUringRegFdBackendProvider); } // namespace test } // namespace folly
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com