id
int64
0
877k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
66
repo_stars
int64
94
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
11 values
repo_extraction_date
stringclasses
197 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
1,533,973
ui_MainPageLayout.cpp
bemardev_HekateBrew/Source/ui/ui_MainPageLayout.cpp
/* * Copyright (C) 2019 bemar * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <ui/ui_MainPageLayout.hpp> #include <ui/ui_MainApplication.hpp> #include <PayloadReboot.hpp> namespace ui { MainPageLayout::MainPageLayout() : pu::ui::Layout() { this->SetBackgroundColor(gsets.CustomScheme.Background); //ActionIcons this->iconLaunch = elm::TextIcon::New(1220, 670, "Launch", Icons::Icon_A, gsets.CustomScheme.Text, elm::TextIconAlign::Right); this->Add(this->iconLaunch); this->iconClose = elm::TextIcon::New(this->iconLaunch->GetX() - 40, 670, "Exit", Icons::Icon_B, gsets.CustomScheme.Text, elm::TextIconAlign::Right); this->Add(this->iconClose); this->iconOptions = elm::TextIcon::New(1220, 20, "Options", Icons::Icon_Plus, gsets.CustomScheme.Text, elm::TextIconAlign::Right); this->Add(this->iconOptions); this->iconReboot = elm::TextIcon::New(this->iconOptions->GetX() - 40, 20, "Reboot to RCM", Icons::Icon_ZR, gsets.CustomScheme.Text, elm::TextIconAlign::Right); this->Add(this->iconReboot); this->iconHReboot = elm::TextIcon::New(this->iconReboot->GetX() - 40, 20, "Reboot to Hekate", Icons::Icon_ZL, gsets.CustomScheme.Text, elm::TextIconAlign::Right); this->Add(this->iconHReboot); this->pageName = pu::ui::elm::TextBlock::New(60, 20, "HekateBrew", 25); this->pageName->SetColor(gsets.CustomScheme.Text); this->Add(this->pageName); this->errMessage = pu::ui::elm::TextBlock::New(0,0, "No payloads found and no Hekate config found.\nGo to Options to select payloads directory."); this->errMessage->SetColor(gsets.CustomScheme.Text); this->errMessage->SetHorizontalAlign(pu::ui::elm::HorizontalAlign::Center); this->errMessage->SetVerticalAlign(pu::ui::elm::VerticalAlign::Center); this->errMessage->SetVisible(false); this->Add(this->errMessage); this->autobootInfos = pu::ui::elm::TextBlock::New(0, 612, "", 25); this->autobootInfos->SetColor(gsets.CustomScheme.BaseFocus); this->autobootInfos->SetVisible(false); this->Add(this->autobootInfos); this->buttonGrid = elm::SimpleGrid::New(58, 232, true); this->buttonGrid->SetColorScheme(gsets.CustomScheme.Text, gsets.CustomScheme.GridBord, gsets.CustomScheme.GridAlt, gsets.CustomScheme.GridInner, gsets.CustomScheme.Base); this->Add(this->buttonGrid); this->SetOnInput(std::bind(&MainPageLayout::OnInput, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); } void MainPageLayout::Load() { int buttonIndex = 1; if (gsets.hbConfig.hasHekate) { elm::SimpleGridItem::Ref launchItem = elm::SimpleGridItem::New(gsets.CustomScheme.hekateMenuImage, "Hekate Config"); launchItem->AddOnClick([this, buttonIndex] { this->buttonGrid_OnClick(buttonIndex); }); this->buttonGrid->AddItem(launchItem); } buttonIndex += 1; if (gsets.payloadItems.size() > 0) { elm::SimpleGridItem::Ref configItem = elm::SimpleGridItem::New(gsets.CustomScheme.defaultImage, "Payloads"); configItem->AddOnClick([this, buttonIndex] { this->buttonGrid_OnClick(buttonIndex); }); this->buttonGrid->AddItem(configItem); } if (this->buttonGrid->GetItems().size() > 0) { this->buttonGrid->SetSelectedIndex(0); this->errMessage->SetVisible(false); if(gsets.hbConfig.autoboot == "1" && gsets.hbConfig.autoboot_payload != "" && stoi(gsets.hbConfig.autoboot_payload) < gsets.payloadItems.size()) { this->autobootInfos->SetText("Autoboot payload: " + gsets.payloadItems[stoi(gsets.hbConfig.autoboot_payload)].payloadPath); this->autobootInfos->SetX(1220 - this->autobootInfos->GetTextWidth()); this->autobootInfos->SetVisible(true); } else if(gsets.hbConfig.autoboot == "2" && gsets.hbConfig.autoboot_config != "" && stoi(gsets.hbConfig.autoboot_config) < gsets.hekateItems.size()) { this->autobootInfos->SetText("Autoboot config: " + gsets.hekateItems[stoi(gsets.hbConfig.autoboot_config)].entryName); this->autobootInfos->SetX(1220 - this->autobootInfos->GetTextWidth()); this->autobootInfos->SetVisible(true); } else { this->autobootInfos->SetVisible(false); } }else this->errMessage->SetVisible(true); } void MainPageLayout::Unload() { this->buttonGrid->ClearItems(); } void MainPageLayout::buttonGrid_OnClick(int btnIndex) { if (btnIndex == 1) { this->Unload(); mainapp->LoadLayout(mainapp->GetHkConfigLayout()); mainapp->GetHkConfigLayout()->Load(); } else if (btnIndex == 2) { this->Unload(); mainapp->LoadLayout(mainapp->GetPayloadLayout()); mainapp->GetPayloadLayout()->Load(); } } void MainPageLayout::OnInput(u64 Down, u64 Up, u64 Held) { if ((Down & KEY_B)) { mainapp->mainClose(); } else if ((Down & KEY_ZR)) { PayloadReboot::RebootRCM(); } else if ((Down & KEY_ZL)) { PayloadReboot::RebootHekate(gsets.hbConfig.path); } else if ((Down & KEY_PLUS)) { this->Unload(); mainapp->LoadLayout(mainapp->GetOptionsLayout()); mainapp->GetOptionsLayout()->Load(); } } }
6,639
C++
.cpp
140
37.378571
179
0.61687
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,974
cfw_Helper.cpp
bemardev_HekateBrew/Source/cfw/cfw_Helper.cpp
/* * Copyright (C) 2019 bemar * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <cfw/cfw_Helper.hpp> namespace cfw { bool IsAtmosphere() { u64 tmpc = 0; return R_SUCCEEDED(splGetConfig((SplConfigItem) 65000, &tmpc)); } bool IsReiNX() { Handle tmph = 0; Result rc = smRegisterService(&tmph, "rnx", false, 1); if (R_FAILED(rc)) return true; smUnregisterService("rnx"); return false; } bool IsSXOS() { Handle tmph = 0; Result rc = smRegisterService(&tmph, "tx", false, 1); if (R_FAILED(rc)) return true; smUnregisterService("tx"); return false; } }
1,408
C++
.cpp
42
27.857143
79
0.654893
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,980
Ini.cpp
bemardev_HekateBrew/SimpleIniParser/source/SimpleIniParser/Ini.cpp
/* * SimpleIniParser * Copyright (c) 2019 Nichole Mattera * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <algorithm> #include <fstream> #include <iostream> #include <sstream> #include <switch.h> #include "Ini.hpp" #include "IniOption.hpp" #include "IniStringHelper.hpp" using namespace std; namespace simpleIniParser { Ini::~Ini() { magic = ""; for (IniSection * section : sections) { if (section != nullptr) { delete section; section = nullptr; } } sections.clear(); } string Ini::build() { string result; if (magic != "") { result += magic + "\n"; } for (auto const& option : options) { result += option->build(); } for (auto const& section : sections) { result += section->build(); } return result; } IniOption * Ini::findFirstOption(string term, bool caseSensitive, IniOptionType type, IniOptionSearchField field) { if (!caseSensitive) { IniStringHelper::toupper(term); } auto it = find_if(options.begin(), options.end(), [&term, &caseSensitive, &type, &field](const IniOption * obj) { if (type != IniOptionType::Any && type != obj->type) { return false; } string fieldValue = ""; if (field == IniOptionSearchField::Key) { fieldValue = (!caseSensitive) ? IniStringHelper::toupper_copy(obj->key) : obj->key; } else { fieldValue = (!caseSensitive) ? IniStringHelper::toupper_copy(obj->value) : obj->value; } return fieldValue == term; }); if (it == options.end()) return nullptr; return (*it); } IniSection * Ini::findSection(string term, bool caseSensitive, IniSectionType type) { if (!caseSensitive) { IniStringHelper::toupper(term); } auto it = find_if(sections.begin(), sections.end(), [&term, &caseSensitive, &type](const IniSection * obj) { if (type != IniSectionType::Any && type != obj->type) { return false; } string fieldValue = (!caseSensitive) ? IniStringHelper::toupper_copy(obj->value) : obj->value; return fieldValue == term; }); if (it == sections.end()) return nullptr; return (*it); } bool Ini::writeToFile(string path) { ofstream file(path); if (!file.is_open()) return false; file << build(); file.flush(); file.close(); fsdevCommitDevice("sdmc"); return true; } Ini * Ini::parseFile(string path) { ifstream file(path); if (!file.is_open()) return nullptr; stringstream buffer; buffer << file.rdbuf(); file.close(); return _parseContent(&buffer, ""); } Ini * Ini::parseFileWithMagic(string path, string magic) { ifstream file(path); if (!file.is_open()) return nullptr; stringstream buffer; buffer << file.rdbuf(); file.close(); string line; getline(buffer, line); IniStringHelper::trim(line); if (line != magic) { return nullptr; } return _parseContent(&buffer, magic); } Ini * Ini::_parseContent(stringstream * content, string magic) { Ini * ini = new Ini(); ini->magic = magic; string line; while (getline(* content, line)) { IniStringHelper::trim(line); if (line.size() == 0) continue; bool shouldParseCommentsAsSection = ini->sections.size() != 0 && ini->sections.back()->type != IniSectionType::Section; IniSection * section = IniSection::parse(line, shouldParseCommentsAsSection); if (section != nullptr) { ini->sections.push_back(section); } else { IniOption * option = IniOption::parse(line); if (option != nullptr && ini->sections.size() == 0) { ini->options.push_back(option); } else if (option != nullptr && ini->sections.size() != 0 && ini->sections.back()->type == IniSectionType::Section) { ini->sections.back()->options.push_back(option); } } } return ini; } }
5,252
C++
.cpp
142
27.760563
133
0.574901
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,981
IniSection.cpp
bemardev_HekateBrew/SimpleIniParser/source/SimpleIniParser/IniSection.cpp
/* * SimpleIniParser * Copyright (c) 2019 Nichole Mattera * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <algorithm> #include <iostream> #include "IniSection.hpp" #include "IniStringHelper.hpp" using namespace std; namespace simpleIniParser { IniSection::IniSection(IniSectionType t, string v) { type = t; value = v; } IniSection::~IniSection() { for (IniOption * option : options) { if (option != nullptr) { delete option; option = nullptr; } } options.clear(); } IniOption * IniSection::findFirstOption(string term, bool caseSensitive, IniOptionType type, IniOptionSearchField field) { if (!caseSensitive) { IniStringHelper::toupper(term); } auto it = find_if(options.begin(), options.end(), [&term, &caseSensitive, &type, &field](const IniOption * obj) { if (type != IniOptionType::Any && type != obj->type) { return false; } string fieldValue = ""; if (field == IniOptionSearchField::Key) { fieldValue = (!caseSensitive) ? IniStringHelper::toupper_copy(obj->key) : obj->key; } else { fieldValue = (!caseSensitive) ? IniStringHelper::toupper_copy(obj->value) : obj->value; } return fieldValue == term; }); if (it == options.end()) return nullptr; return (*it); } string IniSection::build() { switch (type) { case IniSectionType::HekateCaption: return "\n{" + value + "}\n"; case IniSectionType::SemicolonComment: return "\n; " + value + "\n"; case IniSectionType::HashtagComment: return "\n# " + value + "\n"; default: string result = "\n[" + value + "]\n"; for (auto const& option : options) { result += option->build(); } return result; } } IniSection * IniSection::parse(string line, bool parseComments) { if (line.at(0) == '{' && line.at(line.size() - 1) == '}') { return new IniSection(IniSectionType::HekateCaption, IniStringHelper::trim_copy(line.substr(1, line.size() - 2))); } else if (parseComments && line.at(0) == ';') { return new IniSection(IniSectionType::SemicolonComment, IniStringHelper::trim_copy(line.substr(1, line.size() - 1))); } else if (parseComments && line.at(0) == '#') { return new IniSection(IniSectionType::HashtagComment, IniStringHelper::trim_copy(line.substr(1, line.size() - 1))); } else if (line.at(0) == '[' && line.at(line.size() - 1) == ']') { return new IniSection(IniSectionType::Section, IniStringHelper::trim_copy(line.substr(1, line.size() - 2))); } else { return nullptr; } } }
3,690
C++
.cpp
85
34.423529
129
0.598829
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,986
ui_Utils.hpp
bemardev_HekateBrew/Include/ui_Utils.hpp
/* * Copyright (C) 2019 bemar * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #pragma once #include <Utils.hpp> #include <Types.hpp> #include <SimpleIniParser.hpp> #include <vector> #include <string> const std::string hekateBrewDir = "sdmc:/switch/HekateBrew/"; const std::string hekateBrewFile = "sdmc:/switch/HekateBrew/settings.ini"; const std::string hekateFile = "sdmc:/bootloader/hekate_ipl.ini"; const std::string hekateIniDir = "sdmc:/bootloader/ini/"; const std::string hekatePayloadDir = "sdmc:/bootloader/payloads/"; const std::string argonDir = "sdmc:/argon/"; const std::string argonPayloadDir = "sdmc:/argon/payloads/"; const std::string argonLogoDir = "sdmc:/argon/logos/"; const std::string rootPayloadDir = "sdmc:/payloads/"; static inline void CreateDefaultHekateBrewConfig() { simpleIniParser::Ini * hbIni = new simpleIniParser::Ini(); simpleIniParser::IniSection * configSection = new simpleIniParser::IniSection(simpleIniParser::IniSectionType::Section, "config"); configSection->options.push_back(new simpleIniParser::IniOption(simpleIniParser::IniOptionType::Option, "showhekate", "0")); configSection->options.push_back(new simpleIniParser::IniOption(simpleIniParser::IniOptionType::Option, "showargon", "0")); configSection->options.push_back(new simpleIniParser::IniOption(simpleIniParser::IniOptionType::Option, "showrootdir", "0")); configSection->options.push_back(new simpleIniParser::IniOption(simpleIniParser::IniOptionType::Option, "showcustompath", "0")); configSection->options.push_back(new simpleIniParser::IniOption(simpleIniParser::IniOptionType::Option, "custompath", "")); configSection->options.push_back(new simpleIniParser::IniOption(simpleIniParser::IniOptionType::Option, "autoboot", "0")); configSection->options.push_back(new simpleIniParser::IniOption(simpleIniParser::IniOptionType::Option, "autoboot_config", "")); configSection->options.push_back(new simpleIniParser::IniOption(simpleIniParser::IniOptionType::Option, "autoboot_payload", "")); hbIni->sections.push_back(configSection); hbIni->writeToFile(hekateBrewFile); delete hbIni; } static inline bool SaveHekateBrewConfig(HekateBrewConfig config) { if(isFile(hekateBrewFile)) { simpleIniParser::Ini *hbIni = simpleIniParser::Ini::parseFile(hekateBrewFile); hbIni->findSection("config")->findFirstOption("showhekate")->value = config.showHekate; hbIni->findSection("config")->findFirstOption("showargon")->value = config.showArgon; hbIni->findSection("config")->findFirstOption("showrootdir")->value = config.showRootDir; hbIni->findSection("config")->findFirstOption("showcustompath")->value = config.showCustomPath; hbIni->findSection("config")->findFirstOption("custompath")->value = config.customPath; //handle update case for version prior to 1.0 simpleIniParser::IniOption * option = hbIni->findSection("config")->findFirstOption("autoboot", false); if(option != nullptr) hbIni->findSection("config")->findFirstOption("autoboot")->value = config.autoboot; else hbIni->findSection("config")->options.push_back(new simpleIniParser::IniOption(simpleIniParser::IniOptionType::Option, "autoboot", config.autoboot)); option = hbIni->findSection("config")->findFirstOption("autoboot_config", false); if(option != nullptr) hbIni->findSection("config")->findFirstOption("autoboot_config")->value = config.autoboot_config; else hbIni->findSection("config")->options.push_back(new simpleIniParser::IniOption(simpleIniParser::IniOptionType::Option, "autoboot_config", config.autoboot_config)); option = hbIni->findSection("config")->findFirstOption("autoboot_payload", false); if(option != nullptr) hbIni->findSection("config")->findFirstOption("autoboot_payload")->value = config.autoboot_payload; else hbIni->findSection("config")->options.push_back(new simpleIniParser::IniOption(simpleIniParser::IniOptionType::Option, "autoboot_payload", config.autoboot_payload)); hbIni->writeToFile(hekateBrewFile); delete hbIni; return true; } return false; } static inline bool SaveHekateConfig(HekateConfig config) { if (isFile(hekateFile)) { simpleIniParser::Ini *hkIni = simpleIniParser::Ini::parseFile(hekateFile); hkIni->findSection("config")->findFirstOption("autoboot")->value = config.autoboot; hkIni->findSection("config")->findFirstOption("autoboot_list")->value = config.autoboot_list; hkIni->findSection("config")->findFirstOption("bootwait")->value = config.bootwait; hkIni->findSection("config")->findFirstOption("verification")->value = config.verification; hkIni->findSection("config")->findFirstOption("backlight")->value = config.backlight; hkIni->findSection("config")->findFirstOption("autohosoff")->value = config.autohosoff; hkIni->findSection("config")->findFirstOption("autonogc")->value = config.autonogc; hkIni->writeToFile(hekateFile); delete hkIni; return true; } else return false; } static inline void LoadHekateBrewConfig(HekateBrewConfig &config) { bool hasHkbDir = isDir(hekateBrewDir); if (!hasHkbDir) hasHkbDir = create_directory(hekateBrewDir); if(!isFile(hekateBrewFile)) CreateDefaultHekateBrewConfig(); simpleIniParser::Ini *hbIni = simpleIniParser::Ini::parseFile(hekateBrewFile); simpleIniParser::IniOption * option = hbIni->findSection("config")->findFirstOption("showhekate", false); if (option != nullptr) config.showHekate = option->value.c_str(); else config.showHekate = "0"; option = hbIni->findSection("config")->findFirstOption("showargon", false); if (option != nullptr) config.showArgon = option->value.c_str(); else config.showArgon = "0"; option = hbIni->findSection("config")->findFirstOption("showrootdir", false); if (option != nullptr) config.showRootDir = option->value.c_str(); else config.showRootDir = "0"; option = hbIni->findSection("config")->findFirstOption("showcustompath", false); if (option != nullptr) config.showCustomPath = option->value.c_str(); else config.showCustomPath = "0"; option = hbIni->findSection("config")->findFirstOption("custompath", false); if (option != nullptr) config.customPath = option->value.c_str(); else config.customPath = std::string(); option = hbIni->findSection("config")->findFirstOption("autoboot", false); if (option != nullptr) config.autoboot = option->value.c_str(); else config.autoboot = "0"; option = hbIni->findSection("config")->findFirstOption("autoboot_config", false); if (option != nullptr) config.autoboot_config = option->value.c_str(); else config.autoboot_config = std::string(); option = hbIni->findSection("config")->findFirstOption("autoboot_payload", false); if (option != nullptr) config.autoboot_payload = option->value.c_str(); else config.autoboot_payload = std::string(); config.hasHekate = isFile(hekateFile); config.hasArgon = isDir(argonDir); config.path = hekateBrewDir; delete hbIni; } static inline void LoadHekateConfig(HekateConfig &config) { if (isFile(hekateFile)) { simpleIniParser::Ini *hkIni = simpleIniParser::Ini::parseFile(hekateFile); simpleIniParser::IniOption * option = hkIni->findSection("config")->findFirstOption("autoboot", false); if (option != nullptr) config.autoboot = option->value.c_str(); else config.autoboot = "0"; option = hkIni->findSection("config")->findFirstOption("autoboot", false); if (option != nullptr) config.autoboot_list = option->value.c_str(); else config.autoboot_list = "0"; option = hkIni->findSection("config")->findFirstOption("bootwait", false); if (option != nullptr) config.bootwait = option->value.c_str(); else config.bootwait = "1"; option = hkIni->findSection("config")->findFirstOption("verification", false); if (option != nullptr) config.verification = option->value.c_str(); else config.verification = "1"; option = hkIni->findSection("config")->findFirstOption("backlight", false); if (option != nullptr) config.backlight = option->value.c_str(); else config.backlight = "100"; option = hkIni->findSection("config")->findFirstOption("autohosoff", false); if (option != nullptr) config.autohosoff = option->value.c_str(); else config.autohosoff = "0"; option = hkIni->findSection("config")->findFirstOption("autonogc", false); if (option != nullptr) config.autonogc = option->value.c_str(); else config.autonogc = "1"; delete hkIni; } } static inline void LoadHekateInfos(std::vector<LauncherItem> &configItems) { if (isFile(hekateFile)) { simpleIniParser::Ini *hkIni = simpleIniParser::Ini::parseFile(hekateFile); int configIndex = 1; for (auto const& section : hkIni->sections) { if (section->type != simpleIniParser::IniSectionType::Section) continue; if (section->value != "config") { std::string image = ""; auto iconPath = section->findFirstOption("icon", false); if (iconPath != nullptr) image = "sdmc:/" + iconPath->value; configItems.push_back({section->value, image, std::to_string(configIndex), "0"}); configIndex += 1; } } delete hkIni; } if (isDir(hekateIniDir)) { int configIndex = 1; std::vector<std::string> files = read_directory(hekateIniDir); for (std::vector<std::string>::iterator it = files.begin(); it != files.end(); ++it) { simpleIniParser::Ini *hkIni = simpleIniParser::Ini::parseFile(*it); for (auto const& section : hkIni->sections) { if (section->type != simpleIniParser::IniSectionType::Section) continue; if (section->value != "config") { std::string image = ""; auto iconPath = section->findFirstOption("icon", false); if (iconPath != nullptr) image = "sdmc:/" + iconPath->value; configItems.push_back({section->value, image, std::to_string(configIndex), "1"}); configIndex += 1; } } delete hkIni; } } } static inline void LoadPayloadsInfos(std::vector<PayloadItem> &payloadItems, std::string payloadPath, std::string logoPath) { if(isDir(payloadPath) && isDir(logoPath)) { std::vector<std::string> files = read_directory(payloadPath); for(auto& file : files) { if(endsWith(file, ".bin")) { std::string image = ""; std::string currentFile = (file).substr((file).find_last_of("\\/") + 1, (file).length()-(file).find_last_of("\\/") - 5); if (isFile(logoPath + R"(/)" + currentFile + ".bmp")) image = logoPath + R"(/)" + currentFile + ".bmp"; else if (isFile(logoPath + R"(/)" + currentFile + ".png")) image = logoPath + R"(/)" + currentFile + ".png"; payloadItems.push_back({currentFile, file, image}); } } } } static inline void LoadAllPayloads(std::vector<PayloadItem> &payloadItems, HekateBrewConfig config) { if(config.hasHekate && config.showHekate == "1") LoadPayloadsInfos(payloadItems, hekatePayloadDir, hekatePayloadDir); if(config.hasArgon && config.showArgon == "1") LoadPayloadsInfos(payloadItems, argonPayloadDir, argonLogoDir); if(config.showRootDir == "1") LoadPayloadsInfos(payloadItems, rootPayloadDir, rootPayloadDir); if(config.showCustomPath == "1" && config.customPath != std::string()) LoadPayloadsInfos(payloadItems, config.customPath, config.customPath); }
13,148
C++
.h
264
42.026515
177
0.662963
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,987
Utils.hpp
bemardev_HekateBrew/Include/Utils.hpp
/* * Copyright (C) 2019 bemar * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #pragma once #include <algorithm> #include <cctype> #include <locale> #include <string> #include <vector> #include <filesystem> #include <fstream> #include <cstdio> #include <dirent.h> #include <sys/types.h> namespace fs = std::filesystem; // trim from start (in place) static inline void ltrim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) { return !std::isspace(ch); })); } // trim from end (in place) static inline void rtrim(std::string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { return !std::isspace(ch); }).base(), s.end()); } // trim from both ends (in place) static inline void trim(std::string &s) { ltrim(s); rtrim(s); } // trim from start (copying) static inline std::string ltrim_copy(std::string s) { ltrim(s); return s; } // trim from end (copying) static inline std::string rtrim_copy(std::string s) { rtrim(s); return s; } // trim from both ends (copying) static inline std::string trim_copy(std::string s) { trim(s); return s; } // ends with suffix static inline bool endsWith(const std::string& str, const std::string& suffix) { return str.size() >= suffix.size() && 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix); } // begins with suffix static inline bool startsWith(const std::string& str, const std::string& prefix) { return str.size() >= prefix.size() && 0 == str.compare(0, prefix.size(), prefix); } // replace occurence in string inline void find_and_replace(std::string& file_contents, const std::string& before, const std::string& after) { // This searches the file for the first occurence of the morn string. auto pos = file_contents.find(before); while (pos != std::string::npos) { file_contents.replace(pos, before.length() + 1, after); // Continue searching from here. pos = file_contents.find(before, pos); } } // remove double slash inline void removeDblSlash(std::string& file_contents) { file_contents.erase(std::unique(file_contents.begin(), file_contents.end(), [](char a, char b){return a == '/' && b == '/';}), file_contents.end()); } // shift string inline void stringShift(std::string& str) { if (str.length() > 0) { std::string tmp = str; str.erase(0, 1); str += tmp[0]; } } // fs is directory inline bool isDir(const std::string& pathString = std::string()) { const fs::path path(pathString); std::error_code ec; if (fs::is_directory(path, ec)) { return true; } if (ec) // handle error { } return false; } // fs is file inline bool isFile(const std::string& pathString = std::string()) { const fs::path path(pathString); std::error_code ec; if (fs::is_regular_file(path, ec)) { return true; } if (ec) // handle error { } return false; } // fs remove file inline bool removeFile(const std::string& pathString) { std::error_code ec; const fs::path path(pathString); if (std::remove(pathString.c_str()) == 0) return true; return false; } // fs rename file inline bool renameFile(const std::string& pathOrigString, const std::string& pathDestString) { if (pathOrigString != "" && pathDestString != "") { if (std::rename(pathOrigString.c_str(), pathDestString.c_str()) == 0) return true; } return false; } // stream copy file inline bool copyFile(const std::string& pathOrigString, const std::string& pathDestString) { std::ifstream src(pathOrigString, std::ios::binary); std::ofstream dst(pathDestString, std::ios::binary); dst << src.rdbuf(); if (src.tellg() != dst.tellp()) { removeFile(pathDestString); } else { return true; } return false; } // fs create dir inline bool create_directory(const std::string& pathString) { if (!pathString.empty()) { const fs::path path(pathString); return fs::create_directory(path); } else return false; } // fs read dir ascii order inline std::vector<std::string> read_directory(const std::string& pathString = std::string()) { std::vector <std::string> result; for (const auto & entry : fs::directory_iterator(pathString)) { result.push_back(entry.path()); } std::sort(result.begin(), result.end()); return result; } inline std::vector<std::string> listSubDirectories(const std::string& pathString) { std::vector<std::string> result; DIR * dir; struct dirent* entry; dir = opendir(pathString.c_str()); if(dir != NULL) { while((entry = readdir(dir))) { if(entry->d_type == DT_DIR) result.push_back(entry->d_name); } } closedir(dir); std::sort(result.begin(), result.end()); return result; }
5,819
C++
.h
197
24.786802
153
0.636754
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,988
Types.hpp
bemardev_HekateBrew/Include/Types.hpp
/* * Copyright (C) 2019 bemar * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #pragma once #include <string> #include <switch.h> #include <pu/Plutonium> #include <IconTypes.hpp> struct FileInfo { std::string name; std::string pathName; std::string previousPath; }; struct ini_info { std::string name; std::string value; std::string link; std::string type; }; struct HekateConfig { std::string autoboot; std::string autoboot_list; std::string bootwait; std::string verification; std::string autohosoff; std::string autonogc; std::string backlight; }; struct HekateBrewConfig { std::string path; std::string theme; std::string showHekate; std::string showArgon; std::string showRootDir; std::string showCustomPath; std::string customPath; std::string autoboot; std::string autoboot_config; std::string autoboot_payload; bool hasHekate; bool hasArgon; }; struct ColorScheme { pu::ui::Color Background; // background layout color pu::ui::Color Base; // background imagebutton color pu::ui::Color BaseFocus; // focus color pu::ui::Color Text; // menu text color pu::ui::Color GridText; // grid text pu::ui::Color GridBord; // grid border color pu::ui::Color GridAlt; // grid alternate border color pu::ui::Color GridInner; // grid inner border color pu::ui::Color LineSep; std::string hekateMenuImage; std::string payloadMenuImage; std::string defaultImage; std::string warnImage; std::string loaderImage; }; struct LauncherItem { std::string entryName; std::string entryImage; std::string entryIndex; std::string entryInList; }; struct PayloadItem { std::string payloadName; std::string payloadPath; std::string payloadImage; }; enum class LaunchMode { Unknown, Applet, Application }; LaunchMode GetLaunchMode();
2,685
C++
.h
97
23.412371
79
0.694272
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,989
PayloadReboot.hpp
bemardev_HekateBrew/Include/PayloadReboot.hpp
/* * Copyright (C) 2019 bemar * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #pragma once #include <string> #define PATCHED_RELOC_SZ 0x94 #define IRAM_PAYLOAD_MAX_SIZE 0x2F000 #define IRAM_PAYLOAD_BASE 0x40010000 #define BOOT_CFG_AUTOBOOT_EN (1 << 0) #define BOOT_CFG_FROM_LAUNCH (1 << 1) #define BOOT_CFG_SEPT_RUN (1 << 7) typedef struct __attribute__ ((__packed__)) _boot_cfg_t { unsigned char boot_cfg; unsigned char autoboot; unsigned char autoboot_list; unsigned char extra_cfg; union { struct { char id[8]; }; unsigned char xt_str[0x80]; }; } boot_cfg_t; namespace PayloadReboot { bool Init(std::string payloadPath); void Reboot(); void RebootRCM(); void RebootHekate(std::string hbPath); void Shutdown(); bool AlterPayload(std::string autoboot, std::string autobootl, std::string hbPath, bool launch = false, bool nocfg = false); }
1,672
C++
.h
50
29.04
129
0.691259
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,990
IconTypes.hpp
bemardev_HekateBrew/Include/IconTypes.hpp
/* * Copyright (C) 2019 bemar * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #pragma once #include <switch.h> enum Icons : uint16_t { Icon_RoundArrowLeft = 0xE08E, Icon_RoundArrowRigh = 0xE08F, Icon_Close = 0xE098, Icon_A = 0xE0E0, Icon_B = 0xE0E1, Icon_X = 0xE0E2, Icon_Y = 0xE0E3, Icon_L = 0xE0E4, Icon_R = 0xE0E5, Icon_ZL = 0xE0E6, Icon_ZR = 0xE0E7, Icon_SL = 0xE0E8, Icon_SR = 0xE0E9, Icon_PadBtn = 0xE0EA, Icon_ArrowUp = 0xE0EB, Icon_ArrowDown = 0xE0EC, Icon_ArrowLeft = 0xE0ED, Icon_ArrowRight = 0xE0EE, Icon_Plus = 0xE0EF, Icon_Minus = 0xE0F0, Icon_PlusN = 0xE0F1, Icon_MinusN = 0xE0F2, Icon_Power = 0xE0F3, Icon_Home = 0xE0F4, Icon_Circle = 0xE0F5, Icon_Joystick = 0xE100, Icon_JoystickL = 0xE101, Icon_JoystickR = 0xE102, Icon_JoystickDown = 0xE103, Icon_JoystickLDown = 0xE104, Icon_JoystickRDown = 0xE105, Icon_DPad = 0xE110, Icon_DPadUp = 0xE111, Icon_DPadDown = 0xE112, Icon_DPadLeft = 0xE113, Icon_DPadRigh = 0xE114, Icon_DPadUpDown = 0xE115, Icon_DPadLeftRight = 0xE116, Icon_Switch = 0xE121, Icon_JoyconBoth = 0xE122, Icon_JoyconLeft = 0xE123, Icon_JoyconRight = 0x124, Icon_JoyconLeft1 = 0xE125, Icon_JoyconRight1 = 0xE126, Icon_JoyconHLeft = 0xE127, Icon_JoyconHRight = 0xE128, Icon_JoyconHLeft1 = 0xE129, Icon_JoyconBothAttached = 0xE12A, //... Icon_Checked = 0xE14B, Icon_ExclamBlack = 0xE14D, Icon_ExclamWhite = 0xE150, Icon_ExclamSquareWhite = 0xE151, Icon_InterrogWhite = 0xE152, Icon_InfoWhite = 0xE153 };
2,403
C++
.h
77
26.142857
79
0.671109
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,991
elm_TextIcon.hpp
bemardev_HekateBrew/Include/elm/elm_TextIcon.hpp
/* * Copyright (C) 2019 bemar * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #pragma once #include <pu/Plutonium> #include <IconTypes.hpp> namespace elm { enum class TextIconAlign { Left, // X is coord of begin Right // X is coord of end }; class TextIcon : public pu::ui::elm::Element { public: TextIcon(s32 X, s32 Y, pu::String Text, Icons IconType, pu::ui::Color Color, TextIconAlign Align = TextIconAlign::Left, s32 FontSize = 25); PU_SMART_CTOR(TextIcon) ~TextIcon(); s32 GetX(); void SetX(s32 X); s32 GetY(); void SetY(s32 Y); s32 GetWidth(); s32 GetHeight(); s32 GetTextWidth(); s32 GetTextHeight(); pu::String GetText(); void SetText(pu::String Text, Icons IconType); void SetFont(pu::ui::render::NativeFont Font); pu::ui::Color GetColor(); void SetColor(pu::ui::Color Color); void OnRender(pu::ui::render::Renderer::Ref &Drawer, s32 X, s32 Y); void OnInput(u64 Down, u64 Up, u64 Held, bool Touch); private: pu::String text; Icons iconType; TextIconAlign align; s32 padding; s32 x; s32 y; pu::ui::render::NativeFont fnt; pu::ui::render::NativeFont icofnt; s32 fsize; pu::ui::Color clr; pu::ui::render::NativeTexture ntex; pu::ui::render::NativeTexture itex; void ReloadTextures(); }; }
2,167
C++
.h
64
27.96875
147
0.647003
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,992
elm_NinContentMenu.hpp
bemardev_HekateBrew/Include/elm/elm_NinContentMenu.hpp
/* * Copyright (C) 2019 bemar * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #pragma once #include <pu/Plutonium> #include <vector> #include <chrono> #include <functional> #include <map> namespace elm { class NinContentMenuItem { public: NinContentMenuItem(pu::String Name, pu::String Value); PU_SMART_CTOR(NinContentMenuItem) pu::String GetName(); void SetName(pu::String Name); pu::String GetValue(); void SetValue(pu::String value); pu::ui::Color GetColor(); void SetColor(pu::ui::Color Color); pu::ui::Color GetValueColor(); void SetValueColor(pu::ui::Color Color); bool GetCoolDown(); void SetCoolDown(bool CoolDown); void AddOnClick(std::function<void()> Callback, u64 Key = KEY_A); s32 GetCallbackCount(); std::function<void()> GetCallback(s32 Index); u64 GetCallbackKey(s32 Index); std::string GetIcon(); void SetIcon(std::string Icon); bool HasIcon(); bool IsDisabled(); void SetIsDisabled(bool Disabled); private: pu::String name; pu::String value; pu::ui::Color clr; pu::ui::Color vclr; bool icdown; bool hasicon; bool disabled; std::string icon; std::vector<std::function<void()>> cbs; std::vector<u64> cbipts; }; class NinContentMenu : public pu::ui::elm::Element { public: NinContentMenu(s32 X, s32 Y, s32 Width, pu::ui::Color OptionColor, s32 ItemSize, s32 ItemsToShow); PU_SMART_CTOR(NinContentMenu) s32 GetX(); void SetX(s32 X); s32 GetY(); void SetY(s32 Y); s32 GetWidth(); void SetWidth(s32 Width); s32 GetHeight(); s32 GetItemSize(); void SetItemSize(s32 ItemSize); s32 GetNumberOfItemsToShow(); void SetNumberOfItemsToShow(s32 ItemsToShow); pu::ui::Color GetColor(); void SetColor(pu::ui::Color Color); void SetColorScheme(pu::ui::Color TextColor, pu::ui::Color BorderColor, pu::ui::Color AltBorderColor, pu::ui::Color InnerBorderColor, pu::ui::Color BaseColor, pu::ui::Color LineColor); pu::ui::Color GetOnFocusColor(); void SetOnFocusColor(pu::ui::Color Color); void SetIsFocused(bool isFocus); pu::ui::Color GetScrollbarColor(); void SetScrollbarColor(pu::ui::Color Color); void SetOnSelectionChanged(std::function<void()> Callback); void AddItem(NinContentMenuItem::Ref &Item); void ClearItems(); void SetCooldownEnabled(bool Cooldown); NinContentMenuItem::Ref &GetSelectedItem(); std::vector<NinContentMenuItem::Ref> &GetItems(); s32 GetSelectedIndex(); void SetSelectedIndex(s32 Index); void OnRender(pu::ui::render::Renderer::Ref &Drawer, s32 X, s32 Y); void OnInput(u64 Down, u64 Up, u64 Held, bool Touch); private: void ReloadItemRenders(); std::map<std::string, pu::ui::render::NativeTexture> _contents; bool dtouch; s32 x; s32 y; s32 w; s32 isize; s32 ishow; s32 previsel; s32 fisel; s32 isel; pu::ui::Color scb; pu::ui::Color clr; pu::ui::Color fcs; bool icdown; int basestatus; std::chrono::time_point<std::chrono::steady_clock> basetime; std::function<void()> onselch; std::vector<NinContentMenuItem::Ref> itms; pu::ui::render::NativeFont font; std::vector<pu::ui::render::NativeTexture> loadednames; std::vector<pu::ui::render::NativeTexture> loadedvalues; std::vector<pu::ui::render::NativeTexture> loadedicons; std::chrono::time_point<std::chrono::steady_clock> blinktime; bool _blink; pu::ui::Color _txtclr; pu::ui::Color _borderclr; pu::ui::Color _altclr; pu::ui::Color _baseclr; pu::ui::Color _innerclr; bool _isfocus; }; }
5,129
C++
.h
129
29.426357
196
0.588684
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,993
elm_NinMenu.hpp
bemardev_HekateBrew/Include/elm/elm_NinMenu.hpp
/* * Copyright (C) 2019 bemar * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #pragma once #include <pu/Plutonium> #include <vector> #include <chrono> #include <functional> #include <map> namespace elm { class NinMenuItem { public: NinMenuItem(pu::String Name); PU_SMART_CTOR(NinMenuItem) pu::String GetName(); void SetName(pu::String Name); pu::ui::Color GetColor(); void SetColor(pu::ui::Color Color); void AddOnClick(std::function<void()> Callback, u64 Key = KEY_A); s32 GetCallbackCount(); std::function<void()> GetCallback(s32 Index); u64 GetCallbackKey(s32 Index); std::string GetIcon(); void SetIcon(std::string Icon); bool HasIcon(); private: pu::String name; pu::ui::Color clr; bool hasicon; std::string icon; std::vector<std::function<void()>> cbs; std::vector<u64> cbipts; }; class NinMenu : public pu::ui::elm::Element { public: NinMenu(s32 X, s32 Y, s32 Width, pu::ui::Color OptionColor, s32 ItemSize, s32 ItemsToShow); PU_SMART_CTOR(NinMenu) s32 GetX(); void SetX(s32 X); s32 GetY(); void SetY(s32 Y); s32 GetWidth(); void SetWidth(s32 Width); s32 GetHeight(); s32 GetItemSize(); void SetItemSize(s32 ItemSize); s32 GetNumberOfItemsToShow(); void SetNumberOfItemsToShow(s32 ItemsToShow); pu::ui::Color GetColor(); void SetColor(pu::ui::Color Color); void SetColorScheme(pu::ui::Color TextColor, pu::ui::Color BorderColor, pu::ui::Color AltBorderColor, pu::ui::Color InnerBorderColor, pu::ui::Color BaseColor, pu::ui::Color LineColor); void SetIsFocused(bool isFocus); pu::ui::Color GetScrollbarColor(); void SetScrollbarColor(pu::ui::Color Color); void SetOnSelectionChanged(std::function<void()> Callback); void AddItem(NinMenuItem::Ref &Item); void ClearItems(); void SetCooldownEnabled(bool Cooldown); NinMenuItem::Ref &GetSelectedItem(); std::vector<NinMenuItem::Ref> &GetItems(); s32 GetSelectedIndex(); void SetSelectedIndex(s32 Index); void OnRender(pu::ui::render::Renderer::Ref &Drawer, s32 X, s32 Y); void OnInput(u64 Down, u64 Up, u64 Held, bool Touch); private: void ReloadItemRenders(); pu::ui::render::NativeTexture GetTextContent(std::string text, bool selected = false); std::map<std::string, pu::ui::render::NativeTexture> _contents; bool dtouch; s32 x; s32 y; s32 w; s32 isize; s32 ishow; s32 previsel; s32 fisel; s32 isel; pu::ui::Color scb; pu::ui::Color clr; bool icdown; int basestatus; std::chrono::time_point<std::chrono::steady_clock> basetime; std::function<void()> onselch; std::vector<NinMenuItem::Ref> itms; pu::ui::render::NativeFont font; std::vector<pu::ui::render::NativeTexture> loadednames; std::vector<pu::ui::render::NativeTexture> loadedicons; std::chrono::time_point<std::chrono::steady_clock> blinktime; bool _blink; pu::ui::Color _txtclr; pu::ui::Color _borderclr; pu::ui::Color _altclr; pu::ui::Color _baseclr; pu::ui::Color _innerclr; pu::ui::Color _lineclr; bool _isfocus; }; }
4,531
C++
.h
115
29.391304
196
0.589545
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,994
elm_RotatableImage.hpp
bemardev_HekateBrew/Include/elm/elm_RotatableImage.hpp
/* * Copyright (C) 2019 bemar * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #pragma once #include <pu/Plutonium> #include <chrono> namespace elm { class RotatableImage : public pu::ui::elm::Image { public: RotatableImage(s32 X, s32 Y, pu::String Image, s32 angledelta, s32 delay); PU_SMART_CTOR(RotatableImage) void OnRender(pu::ui::render::Renderer::Ref &Drawer, s32 X, s32 Y); private: s32 _angle; s32 _delta; s32 _delay; std::chrono::time_point<std::chrono::steady_clock> delaytime; }; }
1,245
C++
.h
35
31.914286
82
0.710505
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,995
elm_TextScroll.hpp
bemardev_HekateBrew/Include/elm/elm_TextScroll.hpp
/* * Copyright (C) 2019 bemar * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #pragma once #include <pu/Plutonium> namespace elm { class TextScroll : public pu::ui::elm::Element { public: TextScroll(s32 X, s32 Y, s32 Width, pu::String Text, s32 FontSize = 30); PU_SMART_CTOR(TextScroll) ~TextScroll(); s32 GetX(); void SetX(s32 X); s32 GetY(); void SetY(s32 Y); s32 GetWidth(); s32 GetHeight(); s32 GetTextWidth(); s32 GetTextHeight(); pu::String GetText(); void SetText(pu::String Text); void SetFont(pu::ui::render::NativeFont Font); pu::ui::Color GetColor(); void SetColor(pu::ui::Color Color); void OnRender(pu::ui::render::Renderer::Ref &Drawer, s32 X, s32 Y); void OnInput(u64 Down, u64 Up, u64 Held, bool Touch); private: int newLength; pu::String text; std::string currentText; s32 x; s32 y; s32 outputW; pu::ui::render::NativeFont fnt; s32 fsize; pu::ui::Color clr; pu::ui::render::NativeTexture ntex; std::chrono::high_resolution_clock::time_point start_time; std::chrono::high_resolution_clock::time_point current_time; std::chrono::duration<double, std::milli> Elapsed; }; }
2,031
C++
.h
58
29.103448
80
0.651623
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,996
elm_SeparatorLine.hpp
bemardev_HekateBrew/Include/elm/elm_SeparatorLine.hpp
/* * Copyright (C) 2019 bemar * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #pragma once #include <functional> #include <pu/Plutonium> namespace elm { class SeparatorLine : public pu::ui::elm::Element { public: SeparatorLine(s32 X1, s32 Y1, s32 X2, s32 Y2, pu::ui::Color LineColor); PU_SMART_CTOR(SeparatorLine) s32 GetX(); s32 GetY(); s32 GetWidth(); s32 GetHeight(); void OnRender(pu::ui::render::Renderer::Ref &Drawer, s32 X, s32 Y); void OnInput(u64 Down, u64 Up, u64 Held, bool Touch); private: s32 x1; s32 x2; s32 y1; s32 y2; pu::ui::Color clr; }; }
1,358
C++
.h
41
28.682927
79
0.680091
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,997
elm_SimpleGrid.hpp
bemardev_HekateBrew/Include/elm/elm_SimpleGrid.hpp
/* * Copyright (C) 2019 bemar * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #pragma once #include <pu/Plutonium> #include <vector> #include <chrono> #include <functional> #include <map> namespace elm { class SimpleGridItem { public: SimpleGridItem(pu::String Image, pu::String Name); PU_SMART_CTOR(SimpleGridItem) pu::String GetName(); pu::String GetImage(); void SetNewLength(s32 length); s32 GetNewLength(); void SetName(pu::String Name); pu::ui::Color GetColor(); void SetColor(pu::ui::Color Color); bool GetCoolDown(); void SetCoolDown(bool CoolDown); void AddOnClick(std::function<void() > Callback, u64 Key = KEY_A); s32 GetCallbackCount(); std::function<void() > GetCallback(s32 Index); u64 GetCallbackKey(s32 Index); std::string GetIcon(); void SetIcon(std::string Icon); bool HasIcon(); private: pu::String name; pu::String img; pu::ui::Color clr; bool icdown; bool hasicon; std::string icon; std::vector<std::function<void() >> cbs; std::vector<u64> cbipts; s32 newLength; pu::ui::render::NativeTexture ntex; }; class SimpleGrid : public pu::ui::elm::Element { public: SimpleGrid(s32 X, s32 Y, bool rounded = false); PU_SMART_CTOR(SimpleGrid) s32 GetX(); void SetX(s32 X); s32 GetY(); void SetY(s32 Y); s32 GetWidth(); void SetWidth(s32 Width); s32 GetHeight(); s32 GetItemSize(); void SetItemSize(s32 ItemSize); s32 GetNumberOfItemsToShow(); void SetNumberOfItemsToShow(s32 ItemsToShow); void SetHorizontalPadding(s32 HorizontalPadding); void SetVerticalPadding(s32 VerticalPadding); void SetColorScheme(pu::ui::Color TextColor, pu::ui::Color BorderColor, pu::ui::Color AltBorderColor, pu::ui::Color InnerBorderColor, pu::ui::Color BaseColor); pu::ui::Color GetColor(); void SetColor(pu::ui::Color Color); pu::ui::Color GetOnFocusColor(); void SetOnFocusColor(pu::ui::Color Color); pu::ui::Color GetScrollbarColor(); void SetScrollbarColor(pu::ui::Color Color); void SetOnSelectionChanged(std::function<void() > Callback); void SetDisplayNameOnSelected(bool txtonsel); void SetTextUnderIcon(bool txtunder); void SetFontSize(s32 fontsize); void AddItem(SimpleGridItem::Ref &Item); void ClearItems(); void SetCooldownEnabled(bool Cooldown); SimpleGridItem::Ref &GetSelectedItem(); std::vector<SimpleGridItem::Ref> &GetItems(); s32 GetSelectedIndex(); void SetSelectedIndex(s32 Index); void OnRender(pu::ui::render::Renderer::Ref &Drawer, s32 X, s32 Y); void OnInput(u64 Down, u64 Up, u64 Held, bool Touch); pu::ui::render::NativeTexture GetImageContent(std::string imagePath); pu::ui::render::NativeTexture GetBorder(pu::ui::Color color); pu::ui::render::NativeTexture GetTextContent(std::string text); private: bool dtouch; s32 x; s32 y; s32 w; s32 isize; s32 ishow; s32 rshow; s32 previsel; s32 fisel; s32 isel; s32 hspace; s32 vspace; s32 _fontsize; pu::ui::Color scb; pu::ui::Color clr; pu::ui::Color fcs; bool icdown; int basestatus; std::chrono::time_point<std::chrono::steady_clock> basetime; std::chrono::time_point<std::chrono::steady_clock> blinktime; std::function<void() > onselch; std::vector<SimpleGridItem::Ref> itms; pu::ui::render::NativeFont font; std::map<std::string, pu::ui::render::NativeTexture> _contents; pu::ui::render::NativeTexture _currentDisplayText; bool _blink; bool _rounded; bool _txtonsel; bool _txtunder; pu::ui::Color _txtclr; pu::ui::Color _borderclr; pu::ui::Color _altclr; pu::ui::Color _baseclr; pu::ui::Color _innerclr; }; }
4,895
C++
.h
136
28.683824
167
0.636536
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,998
set_Settings.hpp
bemardev_HekateBrew/Include/set/set_Settings.hpp
/* * Copyright (C) 2019 bemar * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #pragma once #include <switch.h> #include <Types.hpp> #include <ui_Utils.hpp> #include <vector> namespace set { struct Settings { ColorScheme CustomScheme; HekateConfig hConfig; HekateBrewConfig hbConfig; bool needSave; int blinkDelay; std::vector<LauncherItem> hekateItems; std::vector<PayloadItem> payloadItems; }; Settings ProcessSettings(); void ReloadList(Settings &gset); void SaveSettings(Settings &gset); }
1,312
C++
.h
38
29.315789
79
0.708333
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,533,999
ui_FileDialog.hpp
bemardev_HekateBrew/Include/ui/ui_FileDialog.hpp
/* * Copyright (C) 2019 bemar * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #pragma once #include <pu/Plutonium> #include <elm/elm_TextIcon.hpp> #include <vector> #include <chrono> #include <functional> #include <filesystem> namespace ui { struct File { std::string name; std::string pathName; }; class FileDialog { public: FileDialog(std::string BeginPath); PU_SMART_CTOR(FileDialog) ~FileDialog(); s32 GetX(); void SetX(s32 X); s32 GetY(); void SetY(s32 Y); s32 GetWidth(); void SetWidth(s32 Width); s32 GetHeight(); s32 GetItemSize(); void SetItemSize(s32 ItemSize); s32 GetNumberOfItemsToShow(); void SetNumberOfItemsToShow(s32 ItemsToShow); void SetColorScheme(pu::ui::Color TextColor, pu::ui::Color BorderColor, pu::ui::Color AltBorderColor, pu::ui::Color InnerBorderColor, pu::ui::Color BaseColor, pu::ui::Color LineColor, pu::ui::Color BaseFocus); void SetOnSelectionChanged(std::function<void()> Callback); void AddItem(File Item); void ClearItems(); void SetCooldownEnabled(bool Cooldown); std::vector<File> GetItems(); s32 GetSelectedIndex(); void SetSelectedIndex(s32 Index); void OnRender(pu::ui::render::Renderer::Ref &Drawer, s32 X, s32 Y); std::string Show(pu::ui::render::Renderer::Ref &Drawer, void *App); void OnInput(u64 Down, u64 Up, u64 Held, bool Touch); bool UserCancelled(); private: void ReloadItemRenders(); void SetCurrentPath(std::string pathName); std::string currentPath; elm::TextIcon::Ref iconLaunch; elm::TextIcon::Ref iconSelect; elm::TextIcon::Ref iconCancel; bool dtouch; s32 isize; s32 ishow; s32 fisel; s32 isel; s32 x; s32 y; s32 w; s32 h; bool cancel; std::chrono::time_point<std::chrono::steady_clock> blinktime; bool _blink; std::function<void()> onselch; std::vector<File> itms; pu::ui::render::NativeFont font; pu::ui::render::NativeFont icofont; pu::ui::render::NativeTexture istex; pu::ui::Color _txtclr; pu::ui::Color _borderclr; pu::ui::Color _altclr; pu::ui::Color _baseclr; pu::ui::Color _innerclr; pu::ui::Color _lineclr; pu::ui::Color _bfocus; s32 previsel; s32 pselfact; s32 selfact; bool icdown; int basestatus; std::chrono::time_point<std::chrono::steady_clock> basetime; std::vector<pu::ui::render::NativeTexture> loadednames; std::vector<pu::ui::render::NativeTexture> loadedicons; }; }
3,818
C++
.h
101
27.772277
221
0.593443
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,000
ui_MainPageLayout.hpp
bemardev_HekateBrew/Include/ui/ui_MainPageLayout.hpp
/* * Copyright (C) 2019 bemar * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #pragma once #include <pu/Plutonium> #include <elm/elm_TextIcon.hpp> #include <elm/elm_SimpleGrid.hpp> namespace ui { class MainPageLayout : public pu::ui::Layout { public: MainPageLayout(); PU_SMART_CTOR(MainPageLayout) void OnInput(u64 Down, u64 Up, u64 Held); void Load(); void Unload(); private: void buttonGrid_OnClick(int btnIndex); elm::TextIcon::Ref iconClose; elm::TextIcon::Ref iconLaunch; elm::TextIcon::Ref iconOptions; elm::TextIcon::Ref iconReboot; elm::TextIcon::Ref iconHReboot; pu::ui::elm::TextBlock::Ref autobootInfos; pu::ui::elm::TextBlock::Ref pageName; pu::ui::elm::TextBlock::Ref errMessage; elm::SimpleGrid::Ref buttonGrid; }; }
1,593
C++
.h
44
30.613636
79
0.67744
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,001
ui_SliderDialog.hpp
bemardev_HekateBrew/Include/ui/ui_SliderDialog.hpp
/* * Copyright (C) 2019 bemar * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #pragma once #include <pu/Plutonium> #include <elm/elm_TextIcon.hpp> #include <vector> #include <chrono> #include <functional> #include <filesystem> namespace ui { class SliderDialog { public: SliderDialog(std::string Title, int MinValue, int MaxValue, int Step, int CurrentValue); PU_SMART_CTOR(SliderDialog) ~SliderDialog(); s32 GetX(); void SetX(s32 X); s32 GetY(); void SetY(s32 Y); void SetColorScheme(pu::ui::Color TextColor, pu::ui::Color BorderColor, pu::ui::Color AltBorderColor, pu::ui::Color InnerBorderColor, pu::ui::Color BaseColor, pu::ui::Color LineColor, pu::ui::Color BaseFocus); void SetOnSelectionChanged(std::function<void()> Callback); int Show(pu::ui::render::Renderer::Ref &Drawer, void *App); bool UserCancelled(); private: std::string title; elm::TextIcon::Ref iconLaunch; elm::TextIcon::Ref iconMove; elm::TextIcon::Ref iconCancel; bool dtouch; s32 fisel; s32 isel; s32 x; s32 y; s32 w; s32 h; s32 minValue; s32 maxValue; s32 currentValue; s32 step; s32 currentXpos; bool cancel; std::chrono::time_point<std::chrono::steady_clock> blinktime; bool _blink; std::function<void()> onselch; pu::ui::render::NativeFont font; pu::ui::render::NativeFont icofont; pu::ui::render::NativeTexture vtex; pu::ui::Color _txtclr; pu::ui::Color _borderclr; pu::ui::Color _altclr; pu::ui::Color _baseclr; pu::ui::Color _innerclr; pu::ui::Color _lineclr; pu::ui::Color _bfocus; s32 previsel; s32 pselfact; s32 selfact; bool icdown; }; }
2,818
C++
.h
77
27.324675
221
0.599556
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,002
ui_OptionsLayout.hpp
bemardev_HekateBrew/Include/ui/ui_OptionsLayout.hpp
/* * Copyright (C) 2019 bemar * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #pragma once #include <pu/Plutonium> #include <elm/elm_NinMenu.hpp> #include <elm/elm_NinContentMenu.hpp> #include <elm/elm_TextIcon.hpp> #include <elm/elm_SeparatorLine.hpp> namespace ui { class OptionsLayout : public pu::ui::Layout { public: OptionsLayout(); PU_SMART_CTOR(OptionsLayout) void Load(); void Unload(); private: elm::TextIcon::Ref iconClose; elm::TextIcon::Ref iconHint; elm::TextIcon::Ref iconLaunch; elm::TextIcon::Ref iconSave; elm::SeparatorLine::Ref optionSeparator; elm::NinMenu::Ref optionsMenu; elm::NinContentMenu::Ref contentsMenu; pu::ui::elm::TextBlock::Ref pageName; void LoadPayloadOptionsItems(bool isFocused); void LoadHekateOptionsItems(bool isFocused); void LoadHekateBrewOptionsItems(bool isFocused); void OnInput(u64 Down, u64 Up, u64 Held); }; }
1,686
C++
.h
47
31.319149
78
0.711491
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,003
ui_LoadingOverlay.hpp
bemardev_HekateBrew/Include/ui/ui_LoadingOverlay.hpp
/* * Copyright (C) 2019 bemar * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #pragma once #include <pu/Plutonium> #include <elm/elm_RotatableImage.hpp> namespace ui { class LoadingOverlay final : public pu::ui::Overlay { public: LoadingOverlay(pu::String imagePath, pu::ui::Color BaseColor); PU_SMART_CTOR(LoadingOverlay) void OnPreRender(pu::ui::render::Renderer::Ref &Drawer); void OnPostRender(pu::ui::render::Renderer::Ref &Drawer); private: elm::RotatableImage::Ref Loader; }; }
1,221
C++
.h
33
33.666667
78
0.728728
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,004
ui_HkConfigLayout.hpp
bemardev_HekateBrew/Include/ui/ui_HkConfigLayout.hpp
/* * Copyright (C) 2019 bemar * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #pragma once #include <pu/Plutonium> #include <elm/elm_TextIcon.hpp> #include <elm/elm_SimpleGrid.hpp> namespace ui { class HkConfigLayout : public pu::ui::Layout { public: HkConfigLayout(); PU_SMART_CTOR(HkConfigLayout) void Load(); void Unload(); private: elm::TextIcon::Ref iconClose; elm::TextIcon::Ref iconAutoboot; elm::TextIcon::Ref iconLaunch; pu::ui::elm::TextBlock::Ref pageName; elm::SimpleGrid::Ref buttonGrid; void buttonGrid_OnClick(std::string autoboot, std::string autobootl); void OnInput(u64 Down, u64 Up, u64 Held); }; }
1,402
C++
.h
40
30.925
78
0.707568
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,005
ui_PayloadLayout.hpp
bemardev_HekateBrew/Include/ui/ui_PayloadLayout.hpp
/* * Copyright (C) 2019 bemar * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #pragma once #include <pu/Plutonium> #include <elm/elm_TextIcon.hpp> #include <elm/elm_SimpleGrid.hpp> namespace ui { class PayloadLayout : public pu::ui::Layout { public: PayloadLayout(); PU_SMART_CTOR(PayloadLayout) void Load(); void Unload(); private: elm::TextIcon::Ref iconClose; elm::TextIcon::Ref iconAutoboot; elm::TextIcon::Ref iconLaunch; pu::ui::elm::TextBlock::Ref pageName; elm::SimpleGrid::Ref buttonGrid; void buttonGrid_OnClick(std::string payloadPath); void OnInput(u64 Down, u64 Up, u64 Held); }; }
1,420
C++
.h
40
30.35
79
0.685776
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,006
ui_ListDialog.hpp
bemardev_HekateBrew/Include/ui/ui_ListDialog.hpp
/* * Copyright (C) 2019 bemar * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #pragma once #include <pu/Plutonium> #include <elm/elm_TextIcon.hpp> #include <vector> #include <chrono> #include <functional> #include <filesystem> namespace ui { class ListDialogItem { public: ListDialogItem(pu::String Name); PU_SMART_CTOR(ListDialogItem) ~ListDialogItem(); pu::String GetName(); void SetName(pu::String Name); pu::ui::Color GetColor(); void SetColor(pu::ui::Color Color); std::string GetIcon(); void SetIcon(std::string Icon); bool HasIcon(); bool IsSelected(); void SetSelected(bool Selected); private: pu::String name; pu::ui::Color clr; bool hasicon; std::string icon; bool _selected; }; class ListDialog { public: ListDialog(std::string Title); PU_SMART_CTOR(ListDialog) ~ListDialog(); s32 GetX(); void SetX(s32 X); s32 GetY(); void SetY(s32 Y); s32 GetWidth(); void SetWidth(s32 Width); s32 GetHeight(); s32 GetItemSize(); void SetItemSize(s32 ItemSize); s32 GetNumberOfItemsToShow(); void SetNumberOfItemsToShow(s32 ItemsToShow); void SetColorScheme(pu::ui::Color TextColor, pu::ui::Color BorderColor, pu::ui::Color AltBorderColor, pu::ui::Color InnerBorderColor, pu::ui::Color BaseColor, pu::ui::Color LineColor, pu::ui::Color BaseFocus); void SetOnSelectionChanged(std::function<void()> Callback); void AddItem(ListDialogItem::Ref Item); void ClearItems(); void SetCooldownEnabled(bool Cooldown); std::vector<ListDialogItem::Ref> GetItems(); s32 GetSelectedIndex(); void SetSelectedIndex(s32 Index); void OnRender(pu::ui::render::Renderer::Ref &Drawer, s32 X, s32 Y); int Show(pu::ui::render::Renderer::Ref &Drawer, void *App); void OnInput(u64 Down, u64 Up, u64 Held, bool Touch); bool UserCancelled(); private: void ReloadItemRenders(); std::string title; elm::TextIcon::Ref iconLaunch; elm::TextIcon::Ref iconCancel; bool dtouch; s32 isize; s32 ishow; s32 fisel; s32 isel; s32 x; s32 y; s32 w; s32 h; bool cancel; std::chrono::time_point<std::chrono::steady_clock> blinktime; bool _blink; std::function<void()> onselch; std::vector<ListDialogItem::Ref> itms; pu::ui::render::NativeFont font; pu::ui::render::NativeFont icofont; pu::ui::render::NativeTexture istex; pu::ui::Color _txtclr; pu::ui::Color _borderclr; pu::ui::Color _altclr; pu::ui::Color _baseclr; pu::ui::Color _innerclr; pu::ui::Color _lineclr; pu::ui::Color _bfocus; s32 previsel; s32 pselfact; s32 selfact; bool icdown; int basestatus; std::chrono::time_point<std::chrono::steady_clock> basetime; std::vector<pu::ui::render::NativeTexture> loadednames; std::vector<pu::ui::render::NativeTexture> loadedicons; }; }
4,354
C++
.h
116
27.008621
221
0.582054
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,007
ui_TimeDialog.hpp
bemardev_HekateBrew/Include/ui/ui_TimeDialog.hpp
/* * Copyright (C) 2019 bemar * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #pragma once #include <pu/Plutonium> #include <vector> #include <chrono> #include <functional> #include <filesystem> namespace ui { class TimeDialog { public: TimeDialog(std::string DialogText, s32 Delay=3000); PU_SMART_CTOR(TimeDialog) ~TimeDialog(); s32 GetX(); void SetX(s32 X); s32 GetY(); void SetY(s32 Y); s32 GetWidth(); void SetWidth(s32 Width); s32 GetHeight(); void SetColorScheme(pu::ui::Color TextColor, pu::ui::Color BaseColor, pu::ui::Color BaseFocus); s32 Show(pu::ui::render::Renderer::Ref &Drawer, void *App); bool UserCancelled(); private: std::string dialogText; std::string txtcounter; s32 initialDelay; bool dtouch; s32 x; s32 y; s32 w; s32 h; bool cancel; std::chrono::time_point<std::chrono::steady_clock> delaytime; pu::ui::render::NativeFont font; pu::ui::render::NativeTexture texdialog; pu::ui::Color _txtclr; pu::ui::Color _bfocus; pu::ui::Color _baseclr; }; }
2,023
C++
.h
59
26.559322
107
0.617632
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,008
ui_MainApplication.hpp
bemardev_HekateBrew/Include/ui/ui_MainApplication.hpp
/* * Copyright (C) 2019 bemar * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #pragma once #include <ui/ui_MainPageLayout.hpp> #include <ui/ui_HkConfigLayout.hpp> #include <ui/ui_PayloadLayout.hpp> #include <ui/ui_LoadingOverlay.hpp> #include <ui/ui_OptionsLayout.hpp> #include <ui/ui_ListDialog.hpp> #include <set/set_Settings.hpp> #include <elm/elm_SeparatorLine.hpp> #include <Types.hpp> #include <pu/Plutonium> extern set::Settings gsets; namespace ui { class MainApplication : public pu::ui::Application { public: MainApplication(); PU_SMART_CTOR(MainApplication) MainPageLayout::Ref &GetMainPageLayout(); HkConfigLayout::Ref &GetHkConfigLayout(); PayloadLayout::Ref &GetPayloadLayout(); OptionsLayout::Ref &GetOptionsLayout(); void showNotification(std::string text, int delay=1500); int CreateShowDialog(pu::String Title, pu::String Content, std::vector<pu::String> Options, bool UseLastOptionAsCancel, std::string Icon = ""); std::string CreateFileDialog(std::string title, std::string BeginPath); int CreateListDialog(std::string title, std::vector<ListDialogItem::Ref> &listItems); int CreateSliderDialog(std::string title, int minValue, int maxValue, int step, int currentValue); int CreateTimeDialog(std::string dialogText, int delay); void endWithErrorMessage(std::string errMessage); void ShowLoading(bool close = false); void mainClose(); private: elm::SeparatorLine::Ref topSeparator; elm::SeparatorLine::Ref bottomSeparator; pu::ui::extras::Toast::Ref toast; ui::LoadingOverlay::Ref loader; MainPageLayout::Ref mainPage; HkConfigLayout::Ref configPage; PayloadLayout::Ref payloadPage; OptionsLayout::Ref optionsPage; void OnInput(u64 Down, u64 Up, u64 Held); }; static const ColorScheme DefaultDark = { { 45, 45, 45, 1}, // background layout color { 70, 70, 70, 255}, // background imagebutton color { 115, 223, 235, 255}, // focus color { 255, 255, 255, 255}, // menu text color { 255, 255, 255, 255}, // grid text { 18, 187, 254, 255}, // grid border color { 115, 223, 235, 255}, // grid alternate border color { 58, 61, 66, 255}, // grid inner border color { 104, 110, 108, 255}, // line & disabled text color "romfs:/icon_hekate.png", "romfs:/PayloadIcon.png", "romfs:/config.bmp", "romfs:/Warn.png", "romfs:/loader.png" }; static const ColorScheme DefaultLight = { { 235, 235, 235, 1}, // background layout color { 240, 240, 240, 255}, // background imagebutton color { 45, 79, 238, 255}, // focus color { 15, 15, 15, 255}, // menu text color { 15, 15, 15, 255}, // grid text { 85, 253, 217, 255}, // grid border color { 12, 191, 195, 255}, // grid alternate border color { 253, 253, 253, 255}, // grid inner border color { 182, 185, 192, 255}, // line & disabled text color "romfs:/icon_hekate.l.png", "romfs:/PayloadIcon.l.png", "romfs:/config.l.bmp", "romfs:/Warn.l.png", "romfs:/loader.png" }; extern MainApplication::Ref mainapp; }
4,102
C++
.h
94
36.425532
152
0.645614
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,009
cfw_Helper.hpp
bemardev_HekateBrew/Include/cfw/cfw_Helper.hpp
/* * Copyright (C) 2019 bemar * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #pragma once #include <string> #include <switch.h> #include <unistd.h> namespace cfw { bool IsAtmosphere(); bool IsReiNX(); bool IsSXOS(); }
933
C++
.h
27
31.518519
79
0.725967
bemardev/HekateBrew
31
2
1
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,010
palammps2D.cpp
huilinye_OpenFSI/example/2D/palammps2D.cpp
/* This file is part of the Palabos_Lammps coupling program. * * Copyright (C) 2011-2015 FlowKit Sarl * Route d'Oron 2 * 1010 Lausanne, Switzerland * E-mail contact: contact@flowkit.com * * The most recent release of Palabos can be downloaded at * <http://www.palabos.org/> * * The library Palabos is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * The library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * Copyright 2018 Huilin Ye University of Connecticut * Author: Huilin Ye (huilin.ye@uconn.edu) */ #include "palabos2D.h" #include "palabos2D.hh" #include "ibm2D.h" #include <vector> #include <cmath> #include <iostream> #include <fstream> #include "mpi.h" #include "lammps.h" #include "input.h" #include "library.h" #include "lammpsWrapper.h" #include "latticeDecomposition2D.h" //#include "nearestTwoNeighborLattices3D.h" using namespace plb; using namespace std; typedef double T; //#define DESCRIPTOR descriptors::ForcedN2D3Q19Descriptor #define DESCRIPTOR descriptors::ForcedD2Q9Descriptor //#define DYNAMICS BGKdynamics<T, DESCRIPTOR>(parameters.getOmega()) #define DYNAMICS GuoExternalForceBGKdynamics<T, DESCRIPTOR>(parameters.getOmega()) #define NMAX 150 // initial parameters plint Resolution = 0; T ReynoldsNumber = 0; T Viscosity = 0.; T x_length = 0; T y_length = 0; //T z_length = 0; plint Shear_flag = 0; T Shear_Top_Velocity = 0; T Shear_Bot_Velocity = 0; plint Poiseuille_flag = 0; T Poiseuille_bodyforce = 0; plint Uniform_flag = 0; T U_uniform = 0; plint Total_timestep = 0; plint Output_fluid_file = 0; plint Output_check_file = 0; plint CouplingType = 1; //1: velocity coupling(default); 2: force coupling plint StaticAtomType = 0; //fix atom with specific type const T pi = (T)4.*std::atan((T)1.); /// Velocity on the parabolic Poiseuille profile T poiseuilleVelocity(plint iY, IncomprFlowParam<T> const& parameters) { T y = (T)iY / parameters.getResolution(); T Ly = parameters.getNy()-1; return 0.06*6*y*(Ly-y)/(Ly*Ly); } /// Linearly decreasing pressure profile T poiseuillePressure(plint iX, IncomprFlowParam<T> const& parameters) { T Lx = parameters.getNx()-1; T Ly = parameters.getNy()-1; return 0.06*12.*parameters.getLatticeNu()/ (Ly*Ly) * (Lx-(T)iX); } /// Convert pressure to density according to ideal gas law T poiseuilleDensity(plint iX, IncomprFlowParam<T> const& parameters) { return poiseuillePressure(iX,parameters)*DESCRIPTOR<T>::invCs2 + (T)1; } /// A functional, used to initialize the velocity for the boundary conditions template<typename T> class PoiseuilleVelocity { public: PoiseuilleVelocity(IncomprFlowParam<T> parameters_) : parameters(parameters_) { } void operator()(plint iX, plint iY, Array<T,2>& u) const { u[0] = poiseuilleVelocity(iY, parameters); u[1] = T(); } private: IncomprFlowParam<T> parameters; }; /// A functional, used to initialize a pressure boundary to constant density template<typename T> class ConstantDensity { public: ConstantDensity(T density_) : density(density_) { } T operator()(plint iX, plint iY) const { return density; } private: T density; }; /// A functional, used to create an initial condition for the density and velocity template<typename T> class PoiseuilleVelocityAndDensity { public: PoiseuilleVelocityAndDensity(IncomprFlowParam<T> parameters_) : parameters(parameters_) { } void operator()(plint iX, plint iY, T& rho, Array<T,2>& u) const { rho = poiseuilleDensity(iX,parameters); u[0] = poiseuilleVelocity(iY, parameters); u[1] = T(); } private: IncomprFlowParam<T> parameters; }; template <typename T> class ShearTopVelocity { public: ShearTopVelocity( IncomprFlowParam<T> const& parameters_, plint maxN_) : parameters(parameters_), maxN(maxN_) { } void operator()(plint iX, plint iY, Array<T,2>& u) const { u[0] = Shear_Top_Velocity; u[1] = T(); //u[2] = T(); } private: IncomprFlowParam<T> parameters; plint maxN; }; template <typename T> class ShearBottomVelocity { public: ShearBottomVelocity(IncomprFlowParam<T> const& parameters_, plint maxN_) : parameters(parameters_), maxN(maxN_) { } void operator()(plint iX, plint iY, Array<T,2>& u) const { u[0] = Shear_Bot_Velocity; u[1] = T(); //u[2] = T(); } private: IncomprFlowParam<T> parameters; plint maxN; }; void bishearSetup(MultiBlockLattice2D<T,DESCRIPTOR>& lattice, IncomprFlowParam<T> const& parameters, OnLatticeBoundaryCondition2D<T,DESCRIPTOR>& boundaryCondition ) //velocity along y direction { const plint nx = parameters.getNx(); const plint ny = parameters.getNy(); //const plint nz = parameters.getNz(); Box2D top = Box2D(0, nx-1, ny-1, ny-1); //y-direction Box2D bottom = Box2D(0, nx-1, 0, 0); //Box3D left = Box3D(1, nx-2, 0, 0, 1, nz-2); //Box3D right = Box3D(1, nx-2, ny-1, ny-1, 1, nz-2); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, top ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, bottom ); //boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, left, boundary::outflow ); //boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, right, boundary::outflow ); setBoundaryVelocity(lattice, top, ShearTopVelocity<T>(parameters,NMAX)); setBoundaryVelocity(lattice, bottom, ShearBottomVelocity<T>(parameters,NMAX)); initializeAtEquilibrium(lattice, lattice.getBoundingBox(),(T)1.0, Array<T,2>(0.0,0.0)); lattice.initialize(); } void poiseSetup( MultiBlockLattice2D<T,DESCRIPTOR>& lattice, IncomprFlowParam<T> const& parameters, OnLatticeBoundaryCondition2D<T,DESCRIPTOR>& boundaryCondition ) { const plint nx = parameters.getNx(); const plint ny = parameters.getNy(); Box2D outlet(nx-1,nx-1, 1, ny-2); // Create Velocity boundary conditions everywhere boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, Box2D(0, 0, 1, ny-2) ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, Box2D(0, nx-1, 0, 0) ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, Box2D(0, nx-1, ny-1, ny-1) ); // .. except on right boundary, where we prefer an outflow condition // (zero velocity-gradient). boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, Box2D(nx-1, nx-1, 1, ny-2), boundary::outflow ); setBoundaryVelocity ( lattice, lattice.getBoundingBox(), PoiseuilleVelocity<T>(parameters) ); setBoundaryDensity ( lattice, outlet, ConstantDensity<T>(1.) ); initializeAtEquilibrium ( lattice, lattice.getBoundingBox(), PoiseuilleVelocityAndDensity<T>(parameters) ); lattice.initialize(); } void poise_force_Setup( MultiBlockLattice2D<T,DESCRIPTOR>& lattice, IncomprFlowParam<T> const& parameters, OnLatticeBoundaryCondition2D<T,DESCRIPTOR>& boundaryCondition ) { const plint nx = parameters.getNx(); const plint ny = parameters.getNy(); Box2D top = Box2D(0, nx-1, ny-1, ny-1); //y-direction Box2D bottom = Box2D(0, nx-1, 0, 0); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, top ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, bottom ); setBoundaryVelocity(lattice, top, Array<T,2>((T)0.0,(T)0.0)); setBoundaryVelocity(lattice, bottom, Array<T,2>((T)0.0,(T)0.0)); initializeAtEquilibrium(lattice, lattice.getBoundingBox(),(T)1.0, Array<T,2>(0.0,0.0)); lattice.initialize(); } void uniformSetup( MultiBlockLattice2D<T,DESCRIPTOR>& lattice, IncomprFlowParam<T> const& parameters, OnLatticeBoundaryCondition2D<T,DESCRIPTOR>& boundaryCondition ) { const plint nx = parameters.getNx(); const plint ny = parameters.getNy(); Box2D outlet(nx-1,nx-1, 0, ny-1); Box2D inlet(0,0, 0, ny-1); Box2D top = Box2D(1, nx-2, ny-1, ny-1); //y-direction Box2D bottom = Box2D(1, nx-2, 0, 0); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, top, boundary::freeslip ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, bottom, boundary::freeslip ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, inlet ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, outlet, boundary::normalOutflow ); setBoundaryVelocity(lattice, inlet,Array<T,2>(U_uniform,0.0)); initializeAtEquilibrium ( lattice, lattice.getBoundingBox(), (T)1.0, Array<T,2>(U_uniform,0.0) ); lattice.initialize(); } void writeVTK(MultiBlockLattice2D<T,DESCRIPTOR>& lattice, IncomprFlowParam<T> const& parameters, plint iter) { T dx = parameters.getDeltaX(); T dt = parameters.getDeltaT(); VtkImageOutput2D<T> vtkOut(createFileName("vtk", iter, 6), dx); vtkOut.writeData<float>(*computeVelocityNorm(lattice), "velocityNorm", dx/dt); vtkOut.writeData<float>(*computeDensity(lattice), "density", (T)1.0); vtkOut.writeData<2,float>(*computeVelocity(lattice), "velocity", dx/dt); //vtkOut.writeData<2,float>(*computeVorticity(*computeVelocity(lattice)), "vorticity", 1./dt); } void readParameters(XMLreader const& document) { document["geometry"]["Resolution"].read(Resolution); document["geometry"]["Viscosity"].read(Viscosity); document["geometry"]["x_length"].read(x_length); document["geometry"]["y_length"].read(y_length); //document["geometry"]["z_length"].read(z_length); document["fluid"]["Shear_flag"].read(Shear_flag); document["fluid"]["Shear_Top_Velocity"].read(Shear_Top_Velocity); document["fluid"]["Shear_Bot_Velocity"].read(Shear_Bot_Velocity); document["fluid"]["Poiseuille_flag"].read(Poiseuille_flag); document["fluid"]["Poiseuille_bodyforce"].read(Poiseuille_bodyforce); document["fluid"]["Uniform_flag"].read(Uniform_flag); document["fluid"]["U_uniform"].read(U_uniform); document["simulation"]["Total_timestep"].read(Total_timestep); document["simulation"]["Output_fluid_file"].read(Output_fluid_file); document["simulation"]["Output_check_file"].read(Output_check_file); document["simulation"]["CouplingType"].read(CouplingType); document["simulation"]["StaticAtomType"].read(StaticAtomType); } int main(int argc, char* argv[]) { plbInit(&argc, &argv); global::directories().setOutputDir("./tmp/"); //read parameters from external file string paramXmlFileName; paramXmlFileName = "param.xml"; XMLreader document(paramXmlFileName); readParameters(paramXmlFileName); ReynoldsNumber = 1.0/Viscosity; IncomprFlowParam<T> parameters( 1.0, ReynoldsNumber, Resolution, x_length, // lx y_length // ly ); //writeLogFile(parameters, "Flow conditions"); LammpsWrapper wrapper(argv,global::mpi().getGlobalCommunicator()); char * inlmp = argv[1]; wrapper.execFile(inlmp); //MultiTensorField3D<T,3> vel(parameters.getNx(),parameters.getNy(),parameters.getNz()); pcout<<"Nx,Ny "<<parameters.getNx()<<" "<<parameters.getNy()<<endl; LatticeDecomposition2D lDec(parameters.getNx(),parameters.getNy(), 1.0, wrapper.lmp); SparseBlockStructure2D blockStructure = lDec.getBlockDistribution(); ExplicitThreadAttribution* threadAttribution = lDec.getThreadAttribution(); plint envelopeWidth = 2; MultiBlockLattice2D<T, DESCRIPTOR> lattice (MultiBlockManagement2D (blockStructure, threadAttribution, envelopeWidth ), defaultMultiBlockPolicy2D().getBlockCommunicator(), defaultMultiBlockPolicy2D().getCombinedStatistics(), defaultMultiBlockPolicy2D().getMultiCellAccess<T,DESCRIPTOR>(), new DYNAMICS ); //Cell<T,DESCRIPTOR> &cell = lattice.get(550,5500,550); pcout<<"dx "<<parameters.getDeltaX()<<" dt "<<parameters.getDeltaT()<<" tau "<<parameters.getTau()<<endl; //pcout<<"51 works"<<endl; // set periodic boundary conditions. if (Shear_flag == 1){ lattice.periodicity().toggle(0,true); //lattice.periodicity().toggle(1,true); } if(Poiseuille_flag == 1){ lattice.periodicity().toggle(0,true); } OnLatticeBoundaryCondition2D<T,DESCRIPTOR>* boundaryCondition = createLocalBoundaryCondition2D<T,DESCRIPTOR>(); if (Shear_flag == 1) bishearSetup(lattice, parameters, *boundaryCondition); //bi-shear flow boundary condition //if (Poiseuille_flag == 1) //poiseSetup(lattice, parameters, *boundaryCondition); //velocity distribution if (Poiseuille_flag == 1) poise_force_Setup(lattice, parameters, *boundaryCondition); if (Uniform_flag == 1) uniformSetup(lattice, parameters, *boundaryCondition); // Loop over main time iteration. util::ValueTracer<T> converge(parameters.getLatticeU(),parameters.getResolution(),1.0e-3); //coupling between lammps and palabos /* for (plint iT=0;iT<4e3;iT++){ //warm up lattice.collideAndStream(); } */ T timeduration = T(); global::timer("mainloop").start(); //writeVTK(lattice, parameters, 0); for (plint iT=0; iT<Total_timestep+1; ++iT) { if (iT%Output_fluid_file ==0 && iT >0){ pcout<<"Saving VTK file..."<<endl; writeVTK(lattice, parameters, iT); } if (iT%Output_check_file ==0 && iT >0){ pcout<<"Timestep "<<iT<<" Saving checkPoint file..."<<endl; saveBinaryBlock(lattice,"checkpoint.dat"); } // lammps to calculate force //wrapper.execCommand("run 1 pre no post no"); wrapper.execCommand("run 1"); // Clear and spread fluid force if (Shear_flag == 1){ Array<T,2> force(0,0.); setExternalVector(lattice,lattice.getBoundingBox(),DESCRIPTOR<T>::ExternalField::forceBeginsAt,force); } if (Poiseuille_flag == 1){ Array<T,2> force(Poiseuille_bodyforce,0); setExternalVector(lattice,lattice.getBoundingBox(),DESCRIPTOR<T>::ExternalField::forceBeginsAt,force); } if (CouplingType == 1){ //-----classical ibm coupling-------------// spreadForce2D_fix(lattice,wrapper,StaticAtomType); ////// Lattice Boltzmann iteration step. //interpolateVelocity3D_fix(lattice,wrapper); lattice.collideAndStream(); //Interpolate and update solid position interpolateVelocity2D_fix(lattice,wrapper,StaticAtomType); }else{ forceCoupling2D(lattice,wrapper); lattice.collideAndStream(); } } timeduration = global::timer("mainloop").stop(); pcout<<"total execution time "<<timeduration<<endl; delete boundaryCondition; }
15,770
C++
.cpp
373
36.742627
121
0.694779
huilinye/OpenFSI
31
20
6
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,011
palammps3D.cpp
huilinye_OpenFSI/example/3D/Flapping of plate/palammps3D.cpp
/* This file is part of the Palabos_Lammps coupling program. * * Copyright (C) 2011-2015 FlowKit Sarl * Route d'Oron 2 * 1010 Lausanne, Switzerland * E-mail contact: contact@flowkit.com * * The most recent release of Palabos can be downloaded at * <http://www.palabos.org/> * * The library Palabos is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * The library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * Copyright 2018 Huilin Ye University of Connecticut * Author: Huilin Ye (huilin.ye@uconn.edu) */ #include "palabos3D.h" #include "palabos3D.hh" #include "ibm3D.h" #include <vector> #include <cmath> #include <iostream> #include <fstream> #include "mpi.h" #include "lammps.h" #include "input.h" #include "library.h" #include "lammpsWrapper.h" #include "latticeDecomposition.h" //#include "nearestTwoNeighborLattices3D.h" using namespace plb; using namespace std; typedef double T; //#define DESCRIPTOR descriptors::ForcedN2D3Q19Descriptor #define DESCRIPTOR descriptors::ForcedD3Q19Descriptor //#define DYNAMICS BGKdynamics<T, DESCRIPTOR>(parameters.getOmega()) #define DYNAMICS GuoExternalForceBGKdynamics<T, DESCRIPTOR>(parameters.getOmega()) #define NMAX 150 // initial parameters plint Resolution = 0; T ReynoldsNumber = 0; T Viscosity = 0.; T x_length = 0; T y_length = 0; T z_length = 0; plint Shear_flag = 0; T Shear_Top_Velocity = 0; T Shear_Bot_Velocity = 0; plint Poiseuille_flag = 0; T Poiseuille_bodyforce = 0; plint Uniform_flag = 0; T U_uniform = 0; plint Total_timestep = 0; plint Output_fluid_file = 0; plint Output_check_file = 0; plint CouplingType = 1; //1: velocity coupling(default); 2: force coupling const T pi = (T)4.*std::atan((T)1.); template <typename T> class ShearTopVelocity { public: ShearTopVelocity( IncomprFlowParam<T> const& parameters_, plint maxN_) : parameters(parameters_), maxN(maxN_) { } void operator()(plint iX, plint iY, plint iZ, Array<T,3>& u) const { u[0] = T(); u[1] = Shear_Top_Velocity; u[2] = T(); } private: IncomprFlowParam<T> parameters; plint maxN; }; template <typename T> class ShearBottomVelocity { public: ShearBottomVelocity(IncomprFlowParam<T> const& parameters_, plint maxN_) : parameters(parameters_), maxN(maxN_) { } void operator()(plint iX, plint iY, plint iZ, Array<T,3>& u) const { u[0] = T(); u[1] = Shear_Bot_Velocity; u[2] = T(); } private: IncomprFlowParam<T> parameters; plint maxN; }; void bishearSetup(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, IncomprFlowParam<T> const& parameters, OnLatticeBoundaryCondition3D<T,DESCRIPTOR>& boundaryCondition ) //velocity along y direction { const plint nx = parameters.getNx(); const plint ny = parameters.getNy(); const plint nz = parameters.getNz(); Box3D top = Box3D(0, nx-1, 0, ny-1, nz-1, nz-1); //z-direction Box3D bottom = Box3D(0, nx-1, 0, ny-1, 0, 0); //Box3D left = Box3D(1, nx-2, 0, 0, 1, nz-2); //Box3D right = Box3D(1, nx-2, ny-1, ny-1, 1, nz-2); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, top ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, bottom ); //boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, left, boundary::outflow ); //boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, right, boundary::outflow ); setBoundaryVelocity(lattice, top, ShearTopVelocity<T>(parameters,NMAX)); setBoundaryVelocity(lattice, bottom, ShearBottomVelocity<T>(parameters,NMAX)); initializeAtEquilibrium(lattice, lattice.getBoundingBox(),(T)1.0, Array<T,3>(0.0,0.0,0.0)); lattice.initialize(); } void squarePoiseuilleSetup( MultiBlockLattice3D<T,DESCRIPTOR>& lattice, IncomprFlowParam<T> const& parameters, OnLatticeBoundaryCondition3D<T,DESCRIPTOR>& boundaryCondition ) { const plint nx = parameters.getNx(); const plint ny = parameters.getNy(); const plint nz = parameters.getNz(); Box3D top = Box3D(0, nx-1, 0, ny-1, nz-1, nz-1); //z direction Box3D bottom = Box3D(0, nx-1, 0, ny-1, 0, 0); //Box3D inlet = Box3D(0, nx-1, 0, 0, 0, nz-1); //y direction //Box3D outlet = Box3D(0, nx-1, ny-1, ny-1, 0, nz-1); Box3D back = Box3D(0, 0, 0, ny-1, 0, nz-1); Box3D front = Box3D(nx-1, nx-1, 0, ny-1, 0, nz-1); // channel flow //boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, inlet); //boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, outlet); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, top ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, bottom ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, front ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, back ); //setBoundaryVelocity(lattice, inlet, SquarePoiseuilleVelocity<T>(parameters, NMAX)); //setBoundaryVelocity(lattice, outlet, SquarePoiseuilleVelocity<T>(parameters, NMAX)); setBoundaryVelocity(lattice, top, Array<T,3>((T)0.0,(T)0.0,(T)0.0)); setBoundaryVelocity(lattice, bottom, Array<T,3>((T)0.0,(T)0.0,(T)0.0)); setBoundaryVelocity(lattice, front, Array<T,3>((T)0.0,(T)0.0,(T)0.0)); setBoundaryVelocity(lattice, back, Array<T,3>((T)0.0,(T)0.0,(T)0.0)); //initializeAtEquilibrium(lattice, lattice.getBoundingBox(), SquarePoiseuilleDensityAndVelocity<T>(parameters, NMAX)); initializeAtEquilibrium(lattice, lattice.getBoundingBox(),(T)1.0, Array<T,3>(0.0,0.0,0.0)); lattice.initialize(); } void uniformSetup(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, IncomprFlowParam<T> const& parameters, OnLatticeBoundaryCondition3D<T,DESCRIPTOR>& boundaryCondition ) //velocity along y direction { const plint nx = parameters.getNx(); const plint ny = parameters.getNy(); const plint nz = parameters.getNz(); Box3D left = Box3D(0, nx-1, 0, 0, 0, nz-1); Box3D right = Box3D(0, nx-1, ny-1, ny-1, 0, nz-1); Box3D front = Box3D(0, 0, 1, ny-2, 0, nz-1); Box3D back = Box3D(nx-1, nx-1, 1, ny-2, 0, nz-1); Box3D top = Box3D(1, nx-2, 1, ny-2, nz-1, nz-1); //z-direction Box3D bottom = Box3D(1, nx-2, 1, ny-2, 0, 0); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, left,boundary::dirichlet); setBoundaryVelocity(lattice, left, Array<T,3>(0.0,U_uniform,0.0)); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, top, boundary::freeslip ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, bottom, boundary::freeslip); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, front, boundary::freeslip ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, back, boundary::freeslip); setBoundaryVelocity(lattice, top, Array<T,3>((T)0.0,(T)U_uniform,(T)0.0)); setBoundaryVelocity(lattice, bottom, Array<T,3>((T)0.0,(T)U_uniform,(T)0.0)); setBoundaryVelocity(lattice, front, Array<T,3>((T)0.0,(T)U_uniform,(T)0.0)); setBoundaryVelocity(lattice, back, Array<T,3>((T)0.0,(T)U_uniform,(T)0.0)); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, right, boundary::outflow); setBoundaryDensity(lattice,right, (T)1.0); //set right outflow boundary /* Box3D globalDomain(lattice->getBoundingBox()); std::vector<MultiBlock3D*> bcargs; bcargs.push_back(lattice); bcargs.push_back(rhoBar); bcargs.push_back(j); T outsideDensity = 1.0; int bcType = 1; integrateProcessingFunctional(new VirtualOutlet<T,DESCRIPTOR>(outsideDensity, globalDomain, bcType), param.outlet, bcargs, 2); setBoundaryVelocity(*lattice, param.outlet, uBoundary); */ initializeAtEquilibrium(lattice, lattice.getBoundingBox(),(T)1.0, Array<T,3>(0.0,U_uniform,0.0)); lattice.initialize(); } void writeVTK(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, IncomprFlowParam<T> const& parameters, plint iter) { T dx = parameters.getDeltaX(); T dt = parameters.getDeltaT(); VtkImageOutput3D<T> vtkOut(createFileName("vtk", iter, 6), dx); vtkOut.writeData<float>(*computeVelocityNorm(lattice), "velocityNorm", dx/dt); vtkOut.writeData<float>(*computeDensity(lattice), "density", (T)1.0); vtkOut.writeData<3,float>(*computeVelocity(lattice), "velocity", dx/dt); vtkOut.writeData<3,float>(*computeVorticity(*computeVelocity(lattice)), "vorticity", 1./dt); } void readParameters(XMLreader const& document) { document["geometry"]["Resolution"].read(Resolution); document["geometry"]["Viscosity"].read(Viscosity); document["geometry"]["x_length"].read(x_length); document["geometry"]["y_length"].read(y_length); document["geometry"]["z_length"].read(z_length); document["fluid"]["Shear_flag"].read(Shear_flag); document["fluid"]["Shear_Top_Velocity"].read(Shear_Top_Velocity); document["fluid"]["Shear_Bot_Velocity"].read(Shear_Bot_Velocity); document["fluid"]["Poiseuille_flag"].read(Poiseuille_flag); document["fluid"]["Poiseuille_bodyforce"].read(Poiseuille_bodyforce); document["fluid"]["Uniform_flag"].read(Uniform_flag); document["fluid"]["U_uniform"].read(U_uniform); document["simulation"]["Total_timestep"].read(Total_timestep); document["simulation"]["Output_fluid_file"].read(Output_fluid_file); document["simulation"]["Output_check_file"].read(Output_check_file); document["simulation"]["CouplingType"].read(CouplingType); } int main(int argc, char* argv[]) { plbInit(&argc, &argv); global::directories().setOutputDir("./tmp/"); //read parameters from external file string paramXmlFileName; paramXmlFileName = "param.xml"; XMLreader document(paramXmlFileName); readParameters(paramXmlFileName); ReynoldsNumber = 1.0/Viscosity; IncomprFlowParam<T> parameters( 1., 1., ReynoldsNumber, Resolution, Resolution, x_length, // lx y_length, // ly z_length // lz ); writeLogFile(parameters, "Flow conditions"); LammpsWrapper wrapper(argv,global::mpi().getGlobalCommunicator()); char * inlmp = argv[1]; wrapper.execFile(inlmp); //MultiTensorField3D<T,3> vel(parameters.getNx(),parameters.getNy(),parameters.getNz()); pcout<<"Nx,Ny,Nz "<<parameters.getNx()<<" "<<parameters.getNy()<<" "<<parameters.getNz()<<endl; LatticeDecomposition lDec(parameters.getNx(),parameters.getNy(),parameters.getNz(), wrapper.lmp); SparseBlockStructure3D blockStructure = lDec.getBlockDistribution(); ExplicitThreadAttribution* threadAttribution = lDec.getThreadAttribution(); plint envelopeWidth = 2; MultiBlockLattice3D<T, DESCRIPTOR> lattice (MultiBlockManagement3D (blockStructure, threadAttribution, envelopeWidth ), defaultMultiBlockPolicy3D().getBlockCommunicator(), defaultMultiBlockPolicy3D().getCombinedStatistics(), defaultMultiBlockPolicy3D().getMultiCellAccess<T,DESCRIPTOR>(), new DYNAMICS ); //Cell<T,DESCRIPTOR> &cell = lattice.get(550,5500,550); pcout<<"dx "<<parameters.getDeltaX()<<" dt "<<parameters.getDeltaT()<<" tau "<<parameters.getTau()<<endl; //pcout<<"51 works"<<endl; // set periodic boundary conditions. if (Shear_flag == 1){ lattice.periodicity().toggle(0,true); lattice.periodicity().toggle(1,true); } if(Poiseuille_flag == 1){ lattice.periodicity().toggle(1,true); } /* if (Uniform_flag == 1){ lattice.periodicity().toggle(0,true); lattice.periodicity().toggle(2,true); } */ OnLatticeBoundaryCondition3D<T,DESCRIPTOR>* boundaryCondition = createLocalBoundaryCondition3D<T,DESCRIPTOR>(); if (Poiseuille_flag == 1) squarePoiseuilleSetup(lattice, parameters, *boundaryCondition); //poiseuille flow boundary condition if (Shear_flag == 1) bishearSetup(lattice, parameters, *boundaryCondition); //bi-shear flow boundary condition if (Uniform_flag == 1){ uniformSetup(lattice, parameters, *boundaryCondition); } // Loop over main time iteration. util::ValueTracer<T> converge(parameters.getLatticeU(),parameters.getResolution(),1.0e-3); //coupling between lammps and palabos /* for (plint iT=0;iT<4e3;iT++){ //warm up lattice.collideAndStream(); } */ T timeduration = T(); global::timer("mainloop").start(); writeVTK(lattice, parameters, 0); for (plint iT=0; iT<Total_timestep+1; ++iT) { if (iT%Output_fluid_file ==0 && iT >0){ pcout<<"Saving VTK file..."<<endl; writeVTK(lattice, parameters, iT); } if (iT%Output_check_file ==0 && iT >0){ pcout<<"Timestep "<<iT<<" Saving checkPoint file..."<<endl; saveBinaryBlock(lattice,"checkpoint.dat"); } // lammps to calculate force wrapper.execCommand("run 1 pre no post no"); // Clear and spread fluid force if (Shear_flag == 1){ Array<T,3> force(0,0.,0); setExternalVector(lattice,lattice.getBoundingBox(),DESCRIPTOR<T>::ExternalField::forceBeginsAt,force); } if (Poiseuille_flag == 1){ Array<T,3> force(0,Poiseuille_bodyforce,0); setExternalVector(lattice,lattice.getBoundingBox(),DESCRIPTOR<T>::ExternalField::forceBeginsAt,force); } if (CouplingType == 1){ //-----classical ibm coupling-------------// spreadForce3D_fix(lattice,wrapper); ////// Lattice Boltzmann iteration step. //interpolateVelocity3D_fix(lattice,wrapper); lattice.collideAndStream(); //Interpolate and update solid position interpolateVelocity3D_fix(lattice,wrapper); } else { //-----force FSI ibm coupling-------------// forceCoupling3D(lattice,wrapper); lattice.collideAndStream(); } } timeduration = global::timer("mainloop").stop(); pcout<<"total execution time "<<timeduration<<endl; delete boundaryCondition; }
15,115
C++
.cpp
325
40.590769
122
0.686401
huilinye/OpenFSI
31
20
6
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,015
improper_octa.cpp
huilinye_OpenFSI/src/structure_potential/improper_octa.cpp
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ /* Use four node improper type to compute eight node cube volume and corresponding force. -----------Huilin Ye(09/11/2018) huilin.ye@uconn.edu */ #include <mpi.h> #include <math.h> #include <stdlib.h> #include "improper_octa.h" #include "atom.h" #include "comm.h" #include "neighbor.h" #include "domain.h" #include "force.h" #include "update.h" #include "math_const.h" #include "memory.h" #include "error.h" using namespace LAMMPS_NS; using namespace MathConst; #define TOLERANCE 0.05 #define SMALL 0.001 /* ---------------------------------------------------------------------- */ ImproperOcta::ImproperOcta(LAMMPS *lmp) : Improper(lmp) { writedata = 1; } /* ---------------------------------------------------------------------- */ ImproperOcta::~ImproperOcta() { if (allocated && !copymode) { memory->destroy(setflag); memory->destroy(mu); memory->destroy(lamda); memory->destroy(v0); memory->destroy(ele5); memory->destroy(ele6); memory->destroy(ele7); memory->destroy(ele8); } } /* ---------------------------------------------------------------------- */ void ImproperOcta::compute(int eflag, int vflag) { int i1,i2,i3,i4,n,type; int j1,j2,j3,j4,m,po; int i,j,k; int new_cell[4]={0}; double xa[8], ya[8], za[8]; tagint *tag = atom->tag; double **x = atom->x; double **f = atom->f; int **improperlist = neighbor->improperlist; int nimproperlist = neighbor->nimproperlist; int **bondlist = neighbor->bondlist; int nbondlist = neighbor->nbondlist; int nlocal = atom->nlocal; int newton_bond = force->newton_bond; // bond information for searching int *num_bond = atom->num_bond; tagint **bond_atom = atom->bond_atom; int co_node,se_node,s1_node,s2_node,s3_node; int i1_list,co_list; for (n = 0; n < nimproperlist; n++) { i1 = improperlist[n][0]; i2 = improperlist[n][1]; i3 = improperlist[n][2]; i4 = improperlist[n][3]; type = improperlist[n][4]; // obtain four new nodes j1 = atom->map(ele5[type]); j2 = atom->map(ele6[type]); j3 = atom->map(ele7[type]); j4 = atom->map(ele8[type]); //printf("local nodes! %d %d %d %d\n",tag[i1],tag[i2],tag[i3],tag[i4]); //printf("new nodes! %d %d %d %d\n",tag[j1],tag[j2],tag[j3],tag[j4]); //printf("element information! %f %d %d %d %d\n",v0[type],ele5[type],ele6[type],ele7[type],ele8[type]); //if (m!=4) error->all(FLERR,"Cannot find nodes!"); //printf("coordinates! %f %f %f %f\n",x[j1][0],x[j2][0],x[j3][0],x[j4][0]); xa[0] = x[i1][0]; xa[1] = x[i2][0]; xa[2] = x[i3][0]; xa[3] = x[i4][0]; xa[4] = x[j1][0]; xa[5] = x[j2][0]; xa[6] = x[j3][0]; xa[7] = x[j4][0]; ya[0] = x[i1][1]; ya[1] = x[i2][1]; ya[2] = x[i3][1]; ya[3] = x[i4][1]; ya[4] = x[j1][1]; ya[5] = x[j2][1]; ya[6] = x[j3][1]; ya[7] = x[j4][1]; za[0] = x[i1][2]; za[1] = x[i2][2]; za[2] = x[i3][2]; za[3] = x[i4][2]; za[4] = x[j1][2]; za[5] = x[j2][2]; za[6] = x[j3][2]; za[7] = x[j4][2]; double ddve[24][24] = {0.0}; int ci[8],cci[8]; double epx[8][8] = {0.0}, epy[8][8] = {0.0}, epz[8][8] = {0.0}; double eepx[8][8] = {0.0}, eepy[8][8] = {0.0}, eepz[8][8] = {0.0}; /* stringstream output_filename; output_filename << "check.dat"; ofstream output_file; /// Open file output_file.open(output_filename.str().c_str(),ofstream::app); int ppc; */ for (j = 0; j < 24; j++){ for (k = 0; k < 24; k++){ ddve[j][k] = 0.0; } } for (i = 0; i < 4; i++){ for (j = 0; j < 8; j++){ ci[j] = nc[j][i]-1; //minus 1 is a must, because index in c++ is from 0 rather than 1; } for (j = 0; j < 8; j++){ for (k = 0; k < 8; k++){ ddve[8+j][16+k] += kab[ci[j]][ci[k]]*xa[i]; ddve[16+j][8+k] += -kab[ci[j]][ci[k]]*xa[i]; ddve[16+j][k] += kab[ci[j]][ci[k]]*ya[i]; ddve[j][16+k] += -kab[ci[j]][ci[k]]*ya[i]; ddve[j][8+k] += kab[ci[j]][ci[k]]*za[i]; ddve[8+j][k] += -kab[ci[j]][ci[k]]*za[i]; } } for (j = 0; j < 8; j++){ cci[j] = nc[j][i+4]-1; } /* for (j = 0; j < 8; j++){ for (k = 0; k < 8; k++){ eepx[j][k] += kab[cci[j]][cci[k]]*xa[i+4]; eepy[j][k] += kab[cci[j]][cci[k]]*ya[i+4]; eepz[j][k] += kab[cci[j]][cci[k]]*za[i+4]; } } */ for (j = 0; j < 8; j++){ for (k = 0; k < 8; k++){ ddve[8+j][16+k] += -kab[cci[j]][cci[k]]*xa[i+4]; ddve[16+j][8+k] += kab[cci[j]][cci[k]]*xa[i+4]; ddve[16+j][k] += -kab[cci[j]][cci[k]]*ya[i+4]; ddve[j][16+k] += kab[cci[j]][cci[k]]*ya[i+4]; ddve[j][8+k] += -kab[cci[j]][cci[k]]*za[i+4]; ddve[8+j][k] += kab[cci[j]][cci[k]]*za[i+4]; } } } //printf("Finish second derivation!\n"); double xyz[24]; double dve[24], fpe[24]; double ve, Jordan,pp; for (i = 0; i < 8; i++ ){ xyz[i] = xa[i]; xyz[i+8] = ya[i]; xyz[i+16] = za[i]; } /* //=============== for (j = 0; j < 24; j++){ output_file <<xyz[j]<<"\n"; } //==================== */ for (j = 0; j < 24; j++){ dve[j] = 0.0; } for (j = 0; j < 24; j++){ for (k = 0; k < 24; k++){ dve[j] += ddve[j][k]*xyz[k]; } } ve = 0.0; for (j = 0; j < 24; j++){ ve += dve[j]*xyz[j]; } ve = ve/72.0; //printf("Ve! %f\n", ve); for (j = 0; j < 24; j++){ dve[j] = dve[j]/24.0; } for (j = 0; j < 24; j++){ for (k = 0; k < 24; k++){ ddve[j][k] = ddve[j][k]/12.0; } } //printf("Finish derivation! volume: %f\n", ve); Jordan = ve/v0[type]; //printf("Jordan! %f\n", Jordan); if (Jordan < 1e-7) error->one(FLERR,"Negative volume!"); pp = v0[type]/Jordan*(-mu[type]+lamda[type]*log(Jordan)); //printf("pp! %f\n", pp); for (i = 0; i < 24; i++){ fpe[i] = -pp*dve[i]/v0[type]; } /* //=============== for (j = 0; j < 24; j++){ output_file <<fpe[j]<<"\n"; } output_file.close (); //==================== */ f[i1][0] += fpe[0]; f[i2][0] += fpe[1]; f[i3][0] += fpe[2]; f[i4][0] += fpe[3]; f[j1][0] += fpe[4]; f[j2][0] += fpe[5]; f[j3][0] += fpe[6]; f[j4][0] += fpe[7]; f[i1][1] += fpe[8]; f[i2][1] += fpe[9]; f[i3][1] += fpe[10]; f[i4][1] += fpe[11]; f[j1][1] += fpe[12]; f[j2][1] += fpe[13]; f[j3][1] += fpe[14]; f[j4][1] += fpe[15]; f[i1][2] += fpe[16]; f[i2][2] += fpe[17]; f[i3][2] += fpe[18]; f[i4][2] += fpe[19]; f[j1][2] += fpe[20]; f[j2][2] += fpe[21]; f[j3][2] += fpe[22]; f[j4][2] += fpe[23]; /* f[EleNode[j]][0] += fpe[j]; f[EleNode[j]][1] += fpe[j+8]; f[EleNode[j]][2] += fpe[j+16]; */ //printf("finish force!\n"); } } /* ---------------------------------------------------------------------- */ void ImproperOcta::allocate() { allocated = 1; int n = atom->nimpropertypes; memory->create(mu,n+1,"improper:mu"); memory->create(lamda,n+1,"improper:lamda"); memory->create(v0,n+1,"improper:v0"); memory->create(ele5,n+1,"improper:ele5"); memory->create(ele6,n+1,"improper:ele6"); memory->create(ele7,n+1,"improper:ele7"); memory->create(ele8,n+1,"improper:ele8"); memory->create(setflag,n+1,"improper:setflag"); for (int i = 1; i <= n; i++) setflag[i] = 0; } /* ---------------------------------------------------------------------- set coeffs for one type ------------------------------------------------------------------------- */ void ImproperOcta::coeff(int narg, char **arg) { if (narg != 8) error->all(FLERR,"Incorrect args for improper coefficients"); if (!allocated) allocate(); int ilo,ihi; force->bounds(arg[0],atom->nimpropertypes,ilo,ihi); double mu_one = force->numeric(FLERR,arg[1]); double lamda_one = force->numeric(FLERR,arg[2]); double v0_one = force->numeric(FLERR,arg[3]); int ele5_one = force->inumeric(FLERR,arg[4]); int ele6_one = force->inumeric(FLERR,arg[5]); int ele7_one = force->inumeric(FLERR,arg[6]); int ele8_one = force->inumeric(FLERR,arg[7]); int count = 0; for (int i = ilo; i <= ihi; i++) { mu[i] = mu_one; lamda[i] = lamda_one; v0[i] = v0_one; ele5[i] = ele5_one; ele6[i] = ele6_one; ele7[i] = ele7_one; ele8[i] = ele8_one; setflag[i] = 1; count++; } //prepare for the force calculation kab[0][0] = 0; kab[0][1] = 0; kab[0][2] = 0; kab[0][3] = 0; kab[0][4] = 0; kab[0][5] = 0; kab[0][6] = 0; kab[0][7] = 0; kab[1][0] = 0; kab[1][1] = 0; kab[1][2] = -1; kab[1][3] = -1.0; kab[1][4] = 1.0; kab[1][5] = 1.0; kab[1][6] = 0; kab[1][7] = 0; kab[2][0] = 0; kab[2][1] = 1; kab[2][2] = 0; kab[2][3] = -1.0; kab[2][4] = 0; kab[2][5] = 0; kab[2][6] = 0; kab[2][7] = 0; kab[3][0] = 0; kab[3][1] = 1; kab[3][2] = 1; kab[3][3] = 0; kab[3][4] = -1; kab[3][5] = 0; kab[3][6] = 0; kab[3][7] = -1; kab[4][0] = 0; kab[4][1] = -1; kab[4][2] = 0; kab[4][3] = 1; kab[4][4] = 0; kab[4][5] = -1; kab[4][6] = 0; kab[4][7] = 1; kab[5][0] = 0; kab[5][1] = -1; kab[5][2] = 0; kab[5][3] = 0; kab[5][4] = 1; kab[5][5] = 0; kab[5][6] = 0; kab[5][7] = 0; kab[6][0] = 0; kab[6][1] = 0; kab[6][2] = 0; kab[6][3] = 0; kab[6][4] = 0; kab[6][5] = 0; kab[6][6] = 0; kab[6][7] = 0; kab[7][0] = 0; kab[7][1] = 0; kab[7][2] = 0; kab[7][3] = 1; kab[7][4] = -1; kab[7][5] = 0; kab[7][6] = 0; kab[7][7] = 0; nc[0][0] = 1; nc[0][1] = 4; nc[0][2] = 3; nc[0][3] = 2; nc[0][4] = 5; nc[0][5] = 8; nc[0][6] = 7; nc[0][7] = 6; nc[1][0] = 2; nc[1][1] = 1; nc[1][2] = 4; nc[1][3] = 3; nc[1][4] = 6; nc[1][5] = 5; nc[1][6] = 8; nc[1][7] = 7; nc[2][0] = 3; nc[2][1] = 2; nc[2][2] = 1; nc[2][3] = 4; nc[2][4] = 7; nc[2][5] = 6; nc[2][6] = 5; nc[2][7] = 8; nc[3][0] = 4; nc[3][1] = 3; nc[3][2] = 2; nc[3][3] = 1; nc[3][4] = 8; nc[3][5] = 7; nc[3][6] = 6; nc[3][7] = 5; nc[4][0] = 5; nc[4][1] = 8; nc[4][2] = 7; nc[4][3] = 6; nc[4][4] = 1; nc[4][5] = 4; nc[4][6] = 3; nc[4][7] = 2; nc[5][0] = 6; nc[5][1] = 5; nc[5][2] = 8; nc[5][3] = 7; nc[5][4] = 2; nc[5][5] = 1; nc[5][6] = 4; nc[5][7] = 3; nc[6][0] = 7; nc[6][1] = 6; nc[6][2] = 5; nc[6][3] = 8; nc[6][4] = 3; nc[6][5] = 2; nc[6][6] = 1; nc[6][7] = 4; nc[7][0] = 8; nc[7][1] = 7; nc[7][2] = 6; nc[7][3] = 5; nc[7][4] = 4; nc[7][5] = 3; nc[7][6] = 2; nc[7][7] = 1; if (count == 0) error->all(FLERR,"Incorrect args for improper coefficients"); //printf("Finish initial step!\n"); } /* ---------------------------------------------------------------------- proc 0 writes out coeffs to restart file ------------------------------------------------------------------------- */ void ImproperOcta::write_restart(FILE *fp) { fwrite(&mu[1],sizeof(double),atom->nimpropertypes,fp); fwrite(&lamda[1],sizeof(double),atom->nimpropertypes,fp); } /* ---------------------------------------------------------------------- proc 0 reads coeffs from restart file, bcasts them ------------------------------------------------------------------------- */ void ImproperOcta::read_restart(FILE *fp) { allocate(); if (comm->me == 0) { fread(&mu[1],sizeof(double),atom->nimpropertypes,fp); fread(&lamda[1],sizeof(double),atom->nimpropertypes,fp); } MPI_Bcast(&mu[1],atom->nimpropertypes,MPI_DOUBLE,0,world); MPI_Bcast(&lamda[1],atom->nimpropertypes,MPI_DOUBLE,0,world); for (int i = 1; i <= atom->nimpropertypes; i++) setflag[i] = 1; } /* ---------------------------------------------------------------------- proc 0 writes to data file ------------------------------------------------------------------------- */ void ImproperOcta::write_data(FILE *fp) { for (int i = 1; i <= atom->nimpropertypes; i++) fprintf(fp,"%d %g %g\n",i,mu[i],lamda[i]); }
12,008
C++
.cpp
300
36.65
128
0.48903
huilinye/OpenFSI
31
20
6
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,018
improper_neohookean.cpp
huilinye_OpenFSI/src/structure_potential/improper_neohookean.cpp
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. Modified by Teng Zhang at 2/7/2017 to simulate area change u_a = -2k1*lnJ + k2*(lnJ)^2 k1: mu ; k2: lammda ; chi: initial area of element J = A/A0 ------------------------------------------------------------------------- */ #include <mpi.h> #include <math.h> #include <stdlib.h> #include "improper_neohookean.h" #include "atom.h" #include "comm.h" #include "neighbor.h" #include "domain.h" #include "force.h" #include "update.h" #include "math_const.h" #include "memory.h" #include "error.h" using namespace LAMMPS_NS; using namespace MathConst; #define TOLERANCE 0.05 #define SMALL 0.001 /* ---------------------------------------------------------------------- */ ImproperNeohookean::ImproperNeohookean(LAMMPS *lmp) : Improper(lmp) { writedata = 1; } /* ---------------------------------------------------------------------- */ ImproperNeohookean::~ImproperNeohookean() { if (allocated && !copymode) { memory->destroy(setflag); memory->destroy(k1); memory->destroy(k2); memory->destroy(chi); } } /* ---------------------------------------------------------------------- */ void ImproperNeohookean::compute(int eflag, int vflag) { int i1,i2,i3,i4,n,type; double vb1x,vb1y,vb1z,vb2x,vb2y,vb2z,vb3x,vb3y,vb3z; double eimproper,f1[3],f2[3],f3[3],f4[3]; double domega,a, area, tk; eimproper = 0.0; if (eflag || vflag) ev_setup(eflag,vflag); else evflag = 0; double **x = atom->x; double **f = atom->f; int **improperlist = neighbor->improperlist; int nimproperlist = neighbor->nimproperlist; int nlocal = atom->nlocal; int newton_bond = force->newton_bond; for (n = 0; n < nimproperlist; n++) { i1 = improperlist[n][0]; i2 = improperlist[n][1]; i3 = improperlist[n][2]; i4 = improperlist[n][3]; type = improperlist[n][4]; // geometry of 4-body /* 1,2,3,4 is the real number for calculating area i,j,k,l is the number in the improper angle (k)4------- 3(j) ! ! ! ! 1(i)!------ !2(l) vb1 ---> x1-x3 vb3 ---> x2-x4 */ vb1x = x[i1][0] - x[i2][0]; vb1y = x[i1][1] - x[i2][1]; vb1z = x[i1][2] - x[i2][2]; vb2x = x[i3][0] - x[i2][0]; vb2y = x[i3][1] - x[i2][1]; vb2z = x[i3][2] - x[i2][2]; vb3x = x[i4][0] - x[i3][0]; vb3y = x[i4][1] - x[i3][1]; vb3z = x[i4][2] - x[i3][2]; area = 1.0/2.0* (vb3y*vb1x - vb1y*vb3x); // printf("i1 %d i2 %d i3 %d i4 %d\n", i1,i2,i3,i4); // printf("area %12.9f\n", area); // force & energy domega = area/chi[type]; // du/dA=du/dJ*(1/A0) tk = 1.0/domega*(k2[type]*log(domega) - k1[type]); if (eflag) eimproper = (k2[type]*log(domega) - 2.0*k1[type])*log(domega)*chi[type]; a = -tk * 2.0; f1[0] = 1.0/2.0*a*vb3y; f1[1] = -1.0/2.0*a*vb3x; f1[2] = 0.0; f2[0] = -1.0/2.0*a*vb3y; f2[1] = +1.0/2.0*a*vb3x; f2[2] = 0.0; f4[0] = -1.0/2.0*a*vb1y; f4[1] = 1.0/2.0*a*vb1x; f4[2] = 0.0; f3[0] = 1.0/2.0*a*vb1y; f3[1] = -1./2.0*a*vb1x; f3[2] = 0.0; // apply force to each of 4 atoms if (newton_bond || i1 < nlocal) { f[i1][0] += f1[0]; f[i1][1] += f1[1]; f[i1][2] += f1[2]; } if (newton_bond || i2 < nlocal) { f[i2][0] += f2[0]; f[i2][1] += f2[1]; f[i2][2] += f2[2]; } if (newton_bond || i3 < nlocal) { f[i3][0] += f3[0]; f[i3][1] += f3[1]; f[i3][2] += f3[2]; } if (newton_bond || i4 < nlocal) { f[i4][0] += f4[0]; f[i4][1] += f4[1]; f[i4][2] += f4[2]; } if (evflag) ev_tally(i1,i2,i3,i4,nlocal,newton_bond,eimproper,f1,f3,f4, vb1x,vb1y,vb1z,vb2x,vb2y,vb2z,vb3x,vb3y,vb3z); } } /* ---------------------------------------------------------------------- */ void ImproperNeohookean::allocate() { allocated = 1; int n = atom->nimpropertypes; memory->create(k1,n+1,"improper:k1"); memory->create(k2,n+1,"improper:k2"); memory->create(chi,n+1,"improper:chi"); memory->create(setflag,n+1,"improper:setflag"); for (int i = 1; i <= n; i++) setflag[i] = 0; } /* ---------------------------------------------------------------------- set coeffs for one type ------------------------------------------------------------------------- */ void ImproperNeohookean::coeff(int narg, char **arg) { if (narg != 4) error->all(FLERR,"Incorrect args for improper coefficients"); if (!allocated) allocate(); int ilo,ihi; force->bounds(arg[0],atom->nimpropertypes,ilo,ihi); double k1_one = force->numeric(FLERR,arg[1]); double k2_one = force->numeric(FLERR,arg[2]); double chi_one = force->numeric(FLERR,arg[3]); // convert chi from degrees to radians int count = 0; for (int i = ilo; i <= ihi; i++) { k1[i] = k1_one; k2[i] = k2_one; chi[i] = chi_one; setflag[i] = 1; count++; } if (count == 0) error->all(FLERR,"Incorrect args for improper coefficients"); } /* ---------------------------------------------------------------------- proc 0 writes out coeffs to restart file ------------------------------------------------------------------------- */ void ImproperNeohookean::write_restart(FILE *fp) { fwrite(&k1[1],sizeof(double),atom->nimpropertypes,fp); fwrite(&k2[1],sizeof(double),atom->nimpropertypes,fp); fwrite(&chi[1],sizeof(double),atom->nimpropertypes,fp); } /* ---------------------------------------------------------------------- proc 0 reads coeffs from restart file, bcasts them ------------------------------------------------------------------------- */ void ImproperNeohookean::read_restart(FILE *fp) { allocate(); if (comm->me == 0) { fread(&k1[1],sizeof(double),atom->nimpropertypes,fp); fread(&k2[1],sizeof(double),atom->nimpropertypes,fp); fread(&chi[1],sizeof(double),atom->nimpropertypes,fp); } MPI_Bcast(&k1[1],atom->nimpropertypes,MPI_DOUBLE,0,world); MPI_Bcast(&k2[1],atom->nimpropertypes,MPI_DOUBLE,0,world); MPI_Bcast(&chi[1],atom->nimpropertypes,MPI_DOUBLE,0,world); for (int i = 1; i <= atom->nimpropertypes; i++) setflag[i] = 1; } /* ---------------------------------------------------------------------- proc 0 writes to data file ------------------------------------------------------------------------- */ void ImproperNeohookean::write_data(FILE *fp) { for (int i = 1; i <= atom->nimpropertypes; i++) fprintf(fp,"%d %g %g\n",i,k1[i],k2[i],chi[i]); }
6,942
C++
.cpp
201
30.895522
87
0.524273
huilinye/OpenFSI
31
20
6
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,019
fix_lb_rigid_pc_sphere.cpp
huilinye_OpenFSI/src/fix_LB/fix_lb_rigid_pc_sphere.cpp
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Contributing authors: Frances Mackay, Santtu Ollila, Colin Denniston (UWO) Based on fix_rigid (version from 2008). ------------------------------------------------------------------------- */ #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "fix_lb_rigid_pc_sphere.h" #include "atom.h" #include "atom_vec.h" #include "domain.h" #include "update.h" #include "respa.h" #include "modify.h" #include "group.h" #include "comm.h" #include "force.h" #include "output.h" #include "memory.h" #include "error.h" #include "fix_lb_fluid.h" using namespace LAMMPS_NS; using namespace FixConst; /* -------------------------------------------------------------------------- */ FixLbRigidPCSphere::FixLbRigidPCSphere(LAMMPS *lmp, int narg, char **arg) : Fix(lmp, narg, arg) { int i, ibody; scalar_flag = 1; extscalar = 0; time_integrate = 1; rigid_flag = 1; create_attribute = 1; virial_flag = 1; // perform initial allocation of atom-based arrays // register with Atom class body = NULL; up = NULL; grow_arrays(atom->nmax); atom->add_callback(0); // by default assume all of the particles interact with the fluid. inner_nodes = 0; // parse command-line args // set nbody and body[i] for each atom if (narg < 4) error->all(FLERR,"Illegal fix lb/rigid/pc/sphere command"); // single rigid body // nbody = 1 // all atoms in fix group are part of body int iarg; if (strcmp(arg[3],"single") == 0) { iarg = 4; nbody = 1; int *mask = atom->mask; int nlocal = atom->nlocal; for (i = 0; i < nlocal; i++) { body[i] = -1; if (mask[i] & groupbit) body[i] = 0; } // each molecule in fix group is a rigid body // maxmol = largest molecule # // ncount = # of atoms in each molecule (have to sum across procs) // nbody = # of non-zero ncount values // use nall as incremented ptr to set body[] values for each atom } else if (strcmp(arg[3],"molecule") == 0) { iarg = 4; if (atom->molecular == 0) error->all(FLERR,"Must use a molecular atom style with " "fix lb/rigid/pc/sphere molecule"); int *mask = atom->mask; tagint *molecule = atom->molecule; int nlocal = atom->nlocal; tagint maxmol_tag = -1; for (i = 0; i < nlocal; i++) if (mask[i] & groupbit) maxmol_tag = MAX(maxmol_tag,molecule[i]); tagint itmp; MPI_Allreduce(&maxmol_tag,&itmp,1,MPI_LMP_TAGINT,MPI_MAX,world); if (itmp+1 > MAXSMALLINT) error->all(FLERR,"Too many molecules for fix lb/rigid/pc/sphere"); int maxmol = (int) itmp; int *ncount; memory->create(ncount,maxmol+1,"rigid:ncount"); for (i = 0; i <= maxmol; i++) ncount[i] = 0; for (i = 0; i < nlocal; i++) if (mask[i] & groupbit) ncount[molecule[i]]++; int *nall; memory->create(nall,maxmol+1,"rigid:ncount"); MPI_Allreduce(ncount,nall,maxmol+1,MPI_LMP_TAGINT,MPI_SUM,world); nbody = 0; for (i = 0; i <= maxmol; i++) if (nall[i]) nall[i] = nbody++; else nall[i] = -1; for (i = 0; i < nlocal; i++) { body[i] = -1; if (mask[i] & groupbit) body[i] = nall[molecule[i]]; } memory->destroy(ncount); memory->destroy(nall); // each listed group is a rigid body // check if all listed groups exist // an atom must belong to fix group and listed group to be in rigid body // error if atom belongs to more than 1 rigid body } else if (strcmp(arg[3],"group") == 0) { if (narg < 5) error->all(FLERR,"Illegal fix lb/rigid/pc/sphere command"); nbody = atoi(arg[4]); if (nbody <= 0) error->all(FLERR,"Illegal fix lb/rigid/pc/sphere command"); if (narg < 5+nbody) error->all(FLERR,"Illegal fix lb/rigid/pc/sphere command"); iarg = 5 + nbody; int *igroups = new int[nbody]; for (ibody = 0; ibody < nbody; ibody++) { igroups[ibody] = group->find(arg[5+ibody]); if (igroups[ibody] == -1) error->all(FLERR,"Could not find fix lb/rigid/pc/sphere group ID"); } int *mask = atom->mask; int nlocal = atom->nlocal; int flag = 0; for (i = 0; i < nlocal; i++) { body[i] = -1; if (mask[i] & groupbit) for (ibody = 0; ibody < nbody; ibody++) if (mask[i] & group->bitmask[igroups[ibody]]) { if (body[i] >= 0) flag = 1; body[i] = ibody; } } int flagall; MPI_Allreduce(&flag,&flagall,1,MPI_INT,MPI_SUM,world); if (flagall) error->all(FLERR,"One or more atoms belong to multiple rigid bodies"); delete [] igroups; }else error->all(FLERR,"Illegal fix lb/rigid/pc/sphere command"); // error check on nbody if (nbody == 0) error->all(FLERR,"No rigid bodies defined"); // create all nbody-length arrays memory->create(nrigid,nbody,"lb/rigid/pc/sphere:nrigid"); memory->create(nrigid_shell,nbody,"lb/rigid/pc/sphere:nrigid_shell"); memory->create(masstotal,nbody,"lb/rigid/pc/sphere:masstotal"); memory->create(masstotal_shell,nbody,"lb/rigid/pc/sphere:masstotal_shell"); memory->create(sphereradius,nbody,"lb/rigid/pc/sphere:sphereradius"); memory->create(xcm,nbody,3,"lb/rigid/pc/sphere:xcm"); memory->create(xcm_old,nbody,3,"lb/rigid/pc/sphere:xcm_old"); memory->create(vcm,nbody,3,"lb/rigid/pc/sphere:vcm"); memory->create(ucm,nbody,3,"lb/rigid/pc/sphere:ucm"); memory->create(ucm_old,nbody,3,"lb/rigid/pc/sphere:ucm_old"); memory->create(fcm,nbody,3,"lb/rigid/pc/sphere:fcm"); memory->create(fcm_old,nbody,3,"lb/rigid/pc/sphere:fcm_old"); memory->create(fcm_fluid,nbody,3,"lb/rigid/pc/sphere:fcm_fluid"); memory->create(omega,nbody,3,"lb/rigid/pc/sphere:omega"); memory->create(torque,nbody,3,"lb/rigid/pc/sphere:torque"); memory->create(torque_old,nbody,3,"lb/rigid/pc/sphere:torque_old"); memory->create(torque_fluid,nbody,3,"lb/rigid/pc/sphere:torque_fluid"); memory->create(torque_fluid_old,nbody,3,"lb/rigid/pc/sphere:torque_fluid_old"); memory->create(rotate,nbody,3,"lb/rigid/pc/sphere:rotate"); memory->create(imagebody,nbody,"lb/rigid/pc/sphere:imagebody"); memory->create(fflag,nbody,3,"lb/rigid/pc/sphere:fflag"); memory->create(tflag,nbody,3,"lb/rigid/pc/sphere:tflag"); memory->create(sum,nbody,6,"lb/rigid/pc/sphere:sum"); memory->create(all,nbody,6,"lb/rigid/pc/sphere:all"); memory->create(remapflag,nbody,4,"lb/rigid/pc/sphere:remapflag"); Gamma_MD = new double[nbody]; // initialize force/torque flags to default = 1.0 array_flag = 1; size_array_rows = nbody; size_array_cols = 15; global_freq = 1; extarray = 0; for (i = 0; i < nbody; i++) { fflag[i][0] = fflag[i][1] = fflag[i][2] = 1.0; tflag[i][0] = tflag[i][1] = tflag[i][2] = 1.0; } // parse optional args that set fflag and tflag while (iarg < narg) { if (strcmp(arg[iarg],"force") == 0) { if (iarg+5 > narg) error->all(FLERR,"Illegal fix lb/rigid/pc/sphere command"); int mlo,mhi; force->bounds(arg[iarg+1],nbody,mlo,mhi); double xflag,yflag,zflag; if (strcmp(arg[iarg+2],"off") == 0) xflag = 0.0; else if (strcmp(arg[iarg+2],"on") == 0) xflag = 1.0; else error->all(FLERR,"Illegal fix lb/rigid/pc/sphere command"); if (strcmp(arg[iarg+2],"off") == 0) yflag = 0.0; else if (strcmp(arg[iarg+3],"on") == 0) yflag = 1.0; else error->all(FLERR,"Illegal fix lb/rigid/pc/sphere command"); if (strcmp(arg[iarg+4],"off") == 0) zflag = 0.0; else if (strcmp(arg[iarg+4],"on") == 0) zflag = 1.0; else error->all(FLERR,"Illegal fix lb/rigid/pc/sphere command"); int count = 0; for (int m = mlo; m <= mhi; m++) { fflag[m-1][0] = xflag; fflag[m-1][1] = yflag; fflag[m-1][2] = zflag; count++; } if (count == 0) error->all(FLERR,"Illegal fix lb/rigid/pc/sphere command"); iarg += 5; } else if (strcmp(arg[iarg],"torque") == 0) { if (iarg+5 > narg) error->all(FLERR,"Illegal fix lb/rigid/pc/sphere command"); int mlo,mhi; force->bounds(arg[iarg+1],nbody,mlo,mhi); double xflag,yflag,zflag; if (strcmp(arg[iarg+2],"off") == 0) xflag = 0.0; else if (strcmp(arg[iarg+2],"on") == 0) xflag = 1.0; else error->all(FLERR,"Illegal fix lb/rigid/pc/sphere command"); if (strcmp(arg[iarg+3],"off") == 0) yflag = 0.0; else if (strcmp(arg[iarg+3],"on") == 0) yflag = 1.0; else error->all(FLERR,"Illegal fix lb/rigid/pc/sphere command"); if (strcmp(arg[iarg+4],"off") == 0) zflag = 0.0; else if (strcmp(arg[iarg+4],"on") == 0) zflag = 1.0; else error->all(FLERR,"Illegal fix lb/rigid/pc/sphere command"); int count = 0; for (int m = mlo; m <= mhi; m++) { tflag[m-1][0] = xflag; tflag[m-1][1] = yflag; tflag[m-1][2] = zflag; count++; } if (count == 0) error->all(FLERR,"Illegal fix lb/rigid/pc/sphere command"); iarg += 5; // specify if certain particles are inside the rigid spherical body, // and therefore should not } else if(strcmp(arg[iarg],"innerNodes")==0){ inner_nodes = 1; igroupinner = group->find(arg[iarg+1]); if(igroupinner == -1) error->all(FLERR,"Could not find fix lb/rigid/pc/sphere innerNodes group ID"); iarg += 2; } else error->all(FLERR,"Illegal fix lb/rigid/pc/sphere command"); } // initialize vector output quantities in case accessed before run for (i = 0; i < nbody; i++) { xcm[i][0] = xcm[i][1] = xcm[i][2] = 0.0; xcm_old[i][0] = xcm_old[i][1] = xcm_old[i][2] = 0.0; vcm[i][0] = vcm[i][1] = vcm[i][2] = 0.0; ucm[i][0] = ucm[i][1] = ucm[i][2] = 0.0; ucm_old[i][0] = ucm_old[i][1] = ucm_old[i][2] = 0.0; fcm[i][0] = fcm[i][1] = fcm[i][2] = 0.0; fcm_old[i][0] = fcm_old[i][1] = fcm_old[i][2] = 0.0; fcm_fluid[i][0] = fcm_fluid[i][1] = fcm_fluid[i][2] = 0.0; torque[i][0] = torque[i][1] = torque[i][2] = 0.0; torque_old[i][0] = torque_old[i][1] = torque_old[i][2] = 0.0; torque_fluid[i][0] = torque_fluid[i][1] = torque_fluid[i][2] = 0.0; torque_fluid_old[i][0] = torque_fluid_old[i][1] = torque_fluid_old[i][2] = 0.0; } // nrigid[n] = # of atoms in Nth rigid body // error if one or zero atoms int *ncount = new int[nbody]; for (ibody = 0; ibody < nbody; ibody++) ncount[ibody] = 0; int nlocal = atom->nlocal; for (i = 0; i < nlocal; i++) if (body[i] >= 0) ncount[body[i]]++; MPI_Allreduce(ncount,nrigid,nbody,MPI_INT,MPI_SUM,world); //count the number of atoms in the shell. if(inner_nodes == 1){ int *mask = atom->mask; for(ibody=0; ibody<nbody; ibody++) ncount[ibody] = 0; for(i=0; i<nlocal; i++){ if(!(mask[i] & group->bitmask[igroupinner])){ if(body[i] >= 0) ncount[body[i]]++; } } MPI_Allreduce(ncount,nrigid_shell,nbody,MPI_INT,MPI_SUM,world); }else { for(ibody=0; ibody < nbody; ibody++) nrigid_shell[ibody]=nrigid[ibody]; } delete [] ncount; for (ibody = 0; ibody < nbody; ibody++) if (nrigid[ibody] <= 1) error->all(FLERR,"One or zero atoms in rigid body"); // set image flags for each rigid body to default values // will be reset during init() based on xcm and then by pre_neighbor() // set here, so image value will persist from run to run for (ibody = 0; ibody < nbody; ibody++) imagebody[ibody] = ((imageint) IMGMAX << IMG2BITS) | ((imageint) IMGMAX << IMGBITS) | IMGMAX; // print statistics int nsum = 0; for (ibody = 0; ibody < nbody; ibody++) nsum += nrigid[ibody]; if (comm->me == 0) { if (screen) fprintf(screen,"%d rigid bodies with %d atoms\n",nbody,nsum); if (logfile) fprintf(logfile,"%d rigid bodies with %d atoms\n",nbody,nsum); } int groupbit_lb_fluid = 0; for(int ifix=0; ifix<modify->nfix; ifix++) if(strcmp(modify->fix[ifix]->style,"lb/fluid")==0){ fix_lb_fluid = (FixLbFluid *)modify->fix[ifix]; groupbit_lb_fluid = group->bitmask[modify->fix[ifix]->igroup]; } if(groupbit_lb_fluid == 0) error->all(FLERR,"the lb/fluid fix must also be used if using the lb/rigid/pc/sphere fix"); int *mask = atom->mask; if(inner_nodes == 1){ for(int j=0; j<nlocal; j++){ if((mask[j] & groupbit) && !(mask[j] & group->bitmask[igroupinner]) && !(mask[j] & groupbit_lb_fluid)) error->one(FLERR,"use the innerNodes keyword in the lb/rigid/pc/sphere fix for atoms which do not interact with the lb/fluid"); // If inner nodes are present, which should not interact with the fluid, make // sure these are not used by the lb/fluid fix to apply a force to the fluid. if((mask[j] & groupbit) && (mask[j] & groupbit_lb_fluid) && (mask[j] & group->bitmask[igroupinner])) error->one(FLERR,"the inner nodes specified in lb/rigid/pc/sphere should not be included in the lb/fluid fix"); } }else{ for(int j=0; j<nlocal; j++){ if((mask[j] & groupbit) && !(mask[j] & groupbit_lb_fluid)) error->one(FLERR,"use the innerNodes keyword in the lb/rigid/pc/sphere fix for atoms which do not interact with the lb/fluid"); } } } /* ---------------------------------------------------------------------- */ FixLbRigidPCSphere::~FixLbRigidPCSphere() { // unregister callbacks to this fix from Atom class atom->delete_callback(id,0); // delete locally stored arrays memory->destroy(body); memory->destroy(up); // delete nbody-length arrays memory->destroy(nrigid); memory->destroy(nrigid_shell); memory->destroy(masstotal); memory->destroy(masstotal_shell); memory->destroy(sphereradius); memory->destroy(xcm); memory->destroy(xcm_old); memory->destroy(vcm); memory->destroy(ucm); memory->destroy(ucm_old); memory->destroy(fcm); memory->destroy(fcm_old); memory->destroy(fcm_fluid); memory->destroy(omega); memory->destroy(torque); memory->destroy(torque_old); memory->destroy(torque_fluid); memory->destroy(torque_fluid_old); memory->destroy(rotate); memory->destroy(imagebody); memory->destroy(fflag); memory->destroy(tflag); memory->destroy(sum); memory->destroy(all); memory->destroy(remapflag); delete [] Gamma_MD; } /* ---------------------------------------------------------------------- */ int FixLbRigidPCSphere::setmask() { int mask = 0; mask |= INITIAL_INTEGRATE; mask |= FINAL_INTEGRATE; mask |= PRE_NEIGHBOR; return mask; } /* ---------------------------------------------------------------------- */ void FixLbRigidPCSphere::init() { int i,ibody; // warn if more than one rigid fix int count = 0; for (int i = 0; i < modify->nfix; i++) if (strcmp(modify->fix[i]->style,"lb/rigid/pc/sphere") == 0) count++; if (count > 1 && comm->me == 0) error->warning(FLERR,"More than one fix lb/rigid/pc/sphere"); // timestep info dtv = update->dt; dtf = 0.5 * update->dt * force->ftm2v; int *type = atom->type; int nlocal = atom->nlocal; double **x = atom->x; imageint *image = atom->image; double *rmass = atom->rmass; double *mass = atom->mass; int *periodicity = domain->periodicity; double xprd = domain->xprd; double yprd = domain->yprd; double zprd = domain->zprd; double **mu = atom->mu; double *radius = atom->radius; int *ellipsoid = atom->ellipsoid; int extended = 0; int *mask = atom->mask; // Warn if any extended particles are included. if (atom->radius_flag || atom->ellipsoid_flag || atom->mu_flag) { int flag = 0; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; if (radius && radius[i] > 0.0) flag = 1; if (ellipsoid && ellipsoid[i] >= 0) flag = 1; if (mu && mu[i][3] > 0.0) flag = 1; } MPI_Allreduce(&flag,&extended,1,MPI_INT,MPI_MAX,world); } if(extended) error->warning(FLERR,"Fix lb/rigid/pc/sphere assumes point particles"); // compute masstotal & center-of-mass of each rigid body for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; int xbox,ybox,zbox; double massone,xunwrap,yunwrap,zunwrap; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; xbox = (image[i] & IMGMASK) - IMGMAX; ybox = (image[i] >> IMGBITS & IMGMASK) - IMGMAX; zbox = (image[i] >> IMG2BITS) - IMGMAX; if (rmass) massone = rmass[i]; else massone = mass[type[i]]; if ((xbox && !periodicity[0]) || (ybox && !periodicity[1]) || (zbox && !periodicity[2])) error->one(FLERR,"Fix lb/rigid/pc/sphere atom has non-zero image flag " "in a non-periodic dimension"); xunwrap = x[i][0] + xbox*xprd; yunwrap = x[i][1] + ybox*yprd; zunwrap = x[i][2] + zbox*zprd; sum[ibody][0] += xunwrap * massone; sum[ibody][1] += yunwrap * massone; sum[ibody][2] += zunwrap * massone; sum[ibody][3] += massone; if(inner_nodes == 1){ if(!(mask[i] & group->bitmask[igroupinner])){ sum[ibody][4] += massone; } }else{ sum[ibody][4] += massone; } } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); for (ibody = 0; ibody < nbody; ibody++) { masstotal[ibody] = all[ibody][3]; masstotal_shell[ibody] = all[ibody][4]; xcm[ibody][0] = all[ibody][0]/masstotal[ibody]; xcm[ibody][1] = all[ibody][1]/masstotal[ibody]; xcm[ibody][2] = all[ibody][2]/masstotal[ibody]; } // Calculate the radius of the rigid body, and assign the value for gamma: double dx,dy,dz; double *Gamma = fix_lb_fluid->Gamma; double dm_lb = fix_lb_fluid->dm_lb; double dt_lb = fix_lb_fluid->dt_lb; for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; for (i=0; i<nlocal; i++){ if(body[i] < 0) continue; if(inner_nodes == 1){ if(!(mask[i] & group->bitmask[igroupinner])){ ibody = body[i]; xbox = (image[i] & IMGMASK) - IMGMAX; ybox = (image[i] >> IMGBITS & IMGMASK) - IMGMAX; zbox = (image[i] >> IMG2BITS) - IMGMAX; xunwrap = x[i][0] + xbox*xprd; yunwrap = x[i][1] + ybox*yprd; zunwrap = x[i][2] + zbox*zprd; dx = xunwrap - xcm[ibody][0]; dy = yunwrap - xcm[ibody][1]; dz = zunwrap - xcm[ibody][2]; sum[ibody][0] += dx*dx + dy*dy + dz*dz; sum[ibody][1] += Gamma[type[i]]; } }else{ ibody = body[i]; xbox = (image[i] & IMGMASK) - IMGMAX; ybox = (image[i] >> IMGBITS & IMGMASK) - IMGMAX; zbox = (image[i] >> IMG2BITS) - IMGMAX; xunwrap = x[i][0] + xbox*xprd; yunwrap = x[i][1] + ybox*yprd; zunwrap = x[i][2] + zbox*zprd; dx = xunwrap - xcm[ibody][0]; dy = yunwrap - xcm[ibody][1]; dz = zunwrap - xcm[ibody][2]; sum[ibody][0] += dx*dx + dy*dy + dz*dz; sum[ibody][1] += Gamma[type[i]]; } } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); for(ibody=0; ibody < nbody; ibody++){ sphereradius[ibody] = sqrt(all[ibody][0]/nrigid_shell[ibody]); Gamma_MD[ibody] = all[ibody][1]*dm_lb/dt_lb/nrigid_shell[ibody]; } // Check that all atoms in the rigid body have the same value of gamma. double eps = 1.0e-7; for (i=0; i<nlocal; i++){ if(body[i] < 0) continue; if(inner_nodes == 1){ if(!(mask[i] & group->bitmask[igroupinner])){ ibody = body[i]; if(Gamma_MD[ibody]*dt_lb/dm_lb - Gamma[type[i]] > eps) error->one(FLERR,"All atoms in a rigid body must have the same gamma value"); } }else{ ibody = body[i]; if(Gamma_MD[ibody]*dt_lb/dm_lb - Gamma[type[i]] > eps) error->one(FLERR,"All atoms in a rigid body must have the same gamma value"); } } // remap the xcm of each body back into simulation box if needed // only really necessary the 1st time a run is performed pre_neighbor(); // temperature scale factor double ndof = 0.0; for (ibody = 0; ibody < nbody; ibody++) { ndof += fflag[ibody][0] + fflag[ibody][1] + fflag[ibody][2]; ndof += tflag[ibody][0] + tflag[ibody][1] + tflag[ibody][2]; } if (ndof > 0.0) tfactor = force->mvv2e / (ndof * force->boltz); else tfactor = 0.0; } /* ---------------------------------------------------------------------- */ void FixLbRigidPCSphere::setup(int vflag) { int i,n,ibody; double massone; // vcm = velocity of center-of-mass of each rigid body // fcm = force on center-of-mass of each rigid body double **x = atom->x; double **v = atom->v; double **f = atom->f; double *rmass = atom->rmass; double *mass = atom->mass; int *type = atom->type; int nlocal = atom->nlocal; imageint *image = atom->image; double unwrap[3]; double dx,dy,dz; for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (rmass) massone = rmass[i]; else massone = mass[type[i]]; sum[ibody][0] += v[i][0] * massone; sum[ibody][1] += v[i][1] * massone; sum[ibody][2] += v[i][2] * massone; sum[ibody][3] += f[i][0]; sum[ibody][4] += f[i][1]; sum[ibody][5] += f[i][2]; } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); for (ibody = 0; ibody < nbody; ibody++) { vcm[ibody][0] = all[ibody][0]/masstotal[ibody]; vcm[ibody][1] = all[ibody][1]/masstotal[ibody]; vcm[ibody][2] = all[ibody][2]/masstotal[ibody]; fcm[ibody][0] = all[ibody][3]; fcm[ibody][1] = all[ibody][4]; fcm[ibody][2] = all[ibody][5]; } // omega = angular velocity of each rigid body // Calculated as the average of the angular velocities of the // individual atoms comprising the rigid body. // torque = torque on each rigid body for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; domain->unmap(x[i],image[i],unwrap); dx = unwrap[0] - xcm[ibody][0]; dy = unwrap[1] - xcm[ibody][1]; dz = unwrap[2] - xcm[ibody][2]; if (rmass) massone = rmass[i]; else massone = mass[type[i]]; sum[ibody][0] += (dy * (v[i][2]-vcm[ibody][2]) - dz * (v[i][1]-vcm[ibody][1]))/(dx*dx+dy*dy+dz*dz); sum[ibody][1] += (dz * (v[i][0]-vcm[ibody][0]) - dx * (v[i][2]-vcm[ibody][2]))/(dx*dx+dy*dy+dz*dz); sum[ibody][2] += (dx * (v[i][1]-vcm[ibody][1]) - dy * (v[i][0]-vcm[ibody][0]))/(dx*dx+dy*dy+dz*dz); sum[ibody][3] += dy * f[i][2] - dz * f[i][1]; sum[ibody][4] += dz * f[i][0] - dx * f[i][2]; sum[ibody][5] += dx * f[i][1] - dy * f[i][0]; } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); for (ibody = 0; ibody < nbody; ibody++) { omega[ibody][0] = all[ibody][0]/nrigid[ibody]; omega[ibody][1] = all[ibody][1]/nrigid[ibody]; omega[ibody][2] = all[ibody][2]/nrigid[ibody]; torque[ibody][0] = all[ibody][3]; torque[ibody][1] = all[ibody][4]; torque[ibody][2] = all[ibody][5]; } // virial setup before call to set_v if (vflag) v_setup(vflag); else evflag = 0; // Set the velocities set_v(); if (vflag_global) for (n = 0; n < 6; n++) virial[n] *= 2.0; if (vflag_atom) { for (i = 0; i < nlocal; i++) for (n = 0; n < 6; n++) vatom[i][n] *= 2.0; } } /* ---------------------------------------------------------------------- */ void FixLbRigidPCSphere::initial_integrate(int vflag) { double dtfm; int i,ibody; double massone; double **x = atom->x; double **v = atom->v; double *rmass = atom->rmass; double *mass = atom->mass; int *type = atom->type; int nlocal = atom->nlocal; imageint *image = atom->image; double unwrap[3]; double dx,dy,dz; int *mask = atom->mask; // compute the fluid velocity at the initial particle positions compute_up(); for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; // Store the fluid velocity at the center of mass for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (rmass) massone = rmass[i]; else massone = mass[type[i]]; if(inner_nodes == 1){ if(!(mask[i] & group->bitmask[igroupinner])){ sum[ibody][0] += up[i][0]*massone; sum[ibody][1] += up[i][1]*massone; sum[ibody][2] += up[i][2]*massone; } }else{ sum[ibody][0] += up[i][0]*massone; sum[ibody][1] += up[i][1]*massone; sum[ibody][2] += up[i][2]*massone; } } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); for (ibody = 0; ibody < nbody; ibody++) { ucm[ibody][0] = all[ibody][0]/masstotal_shell[ibody]; ucm[ibody][1] = all[ibody][1]/masstotal_shell[ibody]; ucm[ibody][2] = all[ibody][2]/masstotal_shell[ibody]; } //Store the total torque due to the fluid. for (ibody = 0; ibody < nbody; ibody++) for(i = 0; i < 6; i++) sum[ibody][i] = 0.0; for(i = 0; i<nlocal; i++){ if(body[i] < 0) continue; ibody = body[i]; domain->unmap(x[i],image[i],unwrap); dx = unwrap[0] - xcm[ibody][0]; dy = unwrap[1] - xcm[ibody][1]; dz = unwrap[2] - xcm[ibody][2]; if (rmass) massone = rmass[i]; else massone = mass[type[i]]; if(inner_nodes == 1){ if(!(mask[i] & group->bitmask[igroupinner])){ sum[ibody][0] += Gamma_MD[ibody]*(dy * ((up[i][2]-vcm[ibody][2])) - dz * ((up[i][1]-vcm[ibody][1]))); sum[ibody][1] += Gamma_MD[ibody]*(dz * ((up[i][0]-vcm[ibody][0])) - dx * ((up[i][2]-vcm[ibody][2]))); sum[ibody][2] += Gamma_MD[ibody]*(dx * ((up[i][1]-vcm[ibody][1])) - dy * ((up[i][0]-vcm[ibody][0]))); sum[ibody][3] += -Gamma_MD[ibody]*(v[i][0]-up[i][0]); sum[ibody][4] += -Gamma_MD[ibody]*(v[i][1]-up[i][1]); sum[ibody][5] += -Gamma_MD[ibody]*(v[i][2]-up[i][2]); } }else{ sum[ibody][0] += Gamma_MD[ibody]*(dy * ((up[i][2]-vcm[ibody][2])) - dz * ((up[i][1]-vcm[ibody][1]))); sum[ibody][1] += Gamma_MD[ibody]*(dz * ((up[i][0]-vcm[ibody][0])) - dx * ((up[i][2]-vcm[ibody][2]))); sum[ibody][2] += Gamma_MD[ibody]*(dx * ((up[i][1]-vcm[ibody][1])) - dy * ((up[i][0]-vcm[ibody][0]))); sum[ibody][3] += -Gamma_MD[ibody]*(v[i][0]-up[i][0]); sum[ibody][4] += -Gamma_MD[ibody]*(v[i][1]-up[i][1]); sum[ibody][5] += -Gamma_MD[ibody]*(v[i][2]-up[i][2]); } } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); for (ibody = 0; ibody < nbody; ibody++) { torque_fluid[ibody][0] = all[ibody][0]; torque_fluid[ibody][1] = all[ibody][1]; torque_fluid[ibody][2] = all[ibody][2]; fcm_fluid[ibody][0] = all[ibody][3]; fcm_fluid[ibody][1] = all[ibody][4]; fcm_fluid[ibody][2] = all[ibody][5]; } for (int ibody = 0; ibody < nbody; ibody++) { fcm_old[ibody][0] = fcm[ibody][0]; fcm_old[ibody][1] = fcm[ibody][1]; fcm_old[ibody][2] = fcm[ibody][2]; torque_old[ibody][0] = torque[ibody][0]; torque_old[ibody][1] = torque[ibody][1]; torque_old[ibody][2] = torque[ibody][2]; torque_fluid_old[ibody][0] = torque_fluid[ibody][0]; torque_fluid_old[ibody][1] = torque_fluid[ibody][1]; torque_fluid_old[ibody][2] = torque_fluid[ibody][2]; ucm_old[ibody][0] = ucm[ibody][0]; ucm_old[ibody][1] = ucm[ibody][1]; ucm_old[ibody][2] = ucm[ibody][2]; xcm_old[ibody][0] = xcm[ibody][0]; xcm_old[ibody][1] = xcm[ibody][1]; xcm_old[ibody][2] = xcm[ibody][2]; // update xcm by full step dtfm = dtf / masstotal[ibody]; xcm[ibody][0] += dtv * vcm[ibody][0]+(fcm[ibody][0]+fcm_fluid[ibody][0]/force->ftm2v)*fflag[ibody][0]*dtfm*dtv; xcm[ibody][1] += dtv * vcm[ibody][1]+(fcm[ibody][1]+fcm_fluid[ibody][1]/force->ftm2v)*fflag[ibody][1]*dtfm*dtv; xcm[ibody][2] += dtv * vcm[ibody][2]+(fcm[ibody][2]+fcm_fluid[ibody][2]/force->ftm2v)*fflag[ibody][2]*dtfm*dtv; rotate[ibody][0] = omega[ibody][0]*dtv + tflag[ibody][0]*(torque[ibody][0]*force->ftm2v+torque_fluid[ibody][0])* dtv*dtv*5.0/(4.0*masstotal[ibody]*sphereradius[ibody]*sphereradius[ibody]); rotate[ibody][1] = omega[ibody][1]*dtv + tflag[ibody][1]*(torque[ibody][1]*force->ftm2v+torque_fluid[ibody][1])* dtv*dtv*5.0/(4.0*masstotal[ibody]*sphereradius[ibody]*sphereradius[ibody]); rotate[ibody][2] = omega[ibody][2]*dtv + tflag[ibody][2]*(torque[ibody][2]*force->ftm2v+torque_fluid[ibody][2])* dtv*dtv*5.0/(4.0*masstotal[ibody]*sphereradius[ibody]*sphereradius[ibody]); // Approximate vcm expminusdttimesgamma = exp(-Gamma_MD[ibody]*dtv*nrigid_shell[ibody]/masstotal[ibody]); force_factor = force->ftm2v/Gamma_MD[ibody]/nrigid_shell[ibody]; if(fflag[ibody][0]==1){ vcm[ibody][0] = expminusdttimesgamma*(vcm[ibody][0] - ucm[ibody][0] - fcm[ibody][0]*force_factor) + ucm[ibody][0] + fcm[ibody][0]*force_factor; } if(fflag[ibody][1]==1){ vcm[ibody][1] = expminusdttimesgamma*(vcm[ibody][1] - ucm[ibody][1] - fcm[ibody][1]*force_factor) + ucm[ibody][1] + fcm[ibody][1]*force_factor; } if(fflag[ibody][2]==1){ vcm[ibody][2] = expminusdttimesgamma*(vcm[ibody][2] - ucm[ibody][2] - fcm[ibody][2]*force_factor) + ucm[ibody][2] + fcm[ibody][2]*force_factor; } // Approximate angmom torque_factor = 5.0*Gamma_MD[ibody]*nrigid_shell[ibody]/(3.0*masstotal[ibody]); expminusdttimesgamma = exp(-dtv*torque_factor); if(tflag[ibody][0]==1){ omega[ibody][0] = expminusdttimesgamma*(omega[ibody][0] - (3.0/(2.0*nrigid_shell[ibody]*sphereradius[ibody]*sphereradius[ibody]*Gamma_MD[ibody]))* (force->ftm2v*torque[ibody][0] + torque_fluid[ibody][0])) + (3.0/(2.0*nrigid_shell[ibody]*sphereradius[ibody]*sphereradius[ibody]*Gamma_MD[ibody]))* (force->ftm2v*torque[ibody][0] + torque_fluid[ibody][0]); } if(tflag[ibody][1]==1){ omega[ibody][1] = expminusdttimesgamma*(omega[ibody][1] - (3.0/(2.0*nrigid_shell[ibody]*sphereradius[ibody]*sphereradius[ibody]*Gamma_MD[ibody]))* (force->ftm2v*torque[ibody][1] + torque_fluid[ibody][1])) + (3.0/(2.0*nrigid_shell[ibody]*sphereradius[ibody]*sphereradius[ibody]*Gamma_MD[ibody]))* (force->ftm2v*torque[ibody][1] + torque_fluid[ibody][1]); } if(tflag[ibody][2]==1){ omega[ibody][2] = expminusdttimesgamma*(omega[ibody][2] - (3.0/(2.0*nrigid_shell[ibody]*sphereradius[ibody]*sphereradius[ibody]*Gamma_MD[ibody]))* (force->ftm2v*torque[ibody][2] + torque_fluid[ibody][2])) + (3.0/(2.0*nrigid_shell[ibody]*sphereradius[ibody]*sphereradius[ibody]*Gamma_MD[ibody]))* (force->ftm2v*torque[ibody][2] + torque_fluid[ibody][2]); } } // virial setup before call to set_xv if (vflag) v_setup(vflag); else evflag = 0; set_xv(); } /* ---------------------------------------------------------------------- */ void FixLbRigidPCSphere::final_integrate() { int i,ibody; // sum over atoms to get force and torque on rigid body double massone; imageint *image = atom->image; double **x = atom->x; double **f = atom->f; double *rmass = atom->rmass; double *mass = atom->mass; int *type = atom->type; int nlocal = atom->nlocal; double unwrap[3]; double dx,dy,dz; int *mask = atom->mask; for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; sum[ibody][0] += f[i][0]; sum[ibody][1] += f[i][1]; sum[ibody][2] += f[i][2]; domain->unmap(x[i],image[i],unwrap); dx = unwrap[0] - xcm[ibody][0]; dy = unwrap[1] - xcm[ibody][1]; dz = unwrap[2] - xcm[ibody][2]; sum[ibody][3] += dy*f[i][2] - dz*f[i][1]; sum[ibody][4] += dz*f[i][0] - dx*f[i][2]; sum[ibody][5] += dx*f[i][1] - dy*f[i][0]; } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); //Compute the correction to the velocity and angular momentum due to the non-fluid forces: for (ibody = 0; ibody < nbody; ibody++) { fcm[ibody][0] = all[ibody][0]; fcm[ibody][1] = all[ibody][1]; fcm[ibody][2] = all[ibody][2]; torque[ibody][0] = all[ibody][3]; torque[ibody][1] = all[ibody][4]; torque[ibody][2] = all[ibody][5]; expminusdttimesgamma = exp(-dtv*Gamma_MD[ibody]*nrigid_shell[ibody]/masstotal[ibody]); DMDcoeff= (dtv - (masstotal[ibody]/nrigid_shell[ibody])*(1.0-expminusdttimesgamma)/Gamma_MD[ibody]); vcm[ibody][0] += fflag[ibody][0]*DMDcoeff*force->ftm2v*(fcm[ibody][0]-fcm_old[ibody][0])/Gamma_MD[ibody]/dtv/nrigid_shell[ibody]; vcm[ibody][1] += fflag[ibody][1]*DMDcoeff*force->ftm2v*(fcm[ibody][1]-fcm_old[ibody][1])/Gamma_MD[ibody]/dtv/nrigid_shell[ibody]; vcm[ibody][2] += fflag[ibody][2]*DMDcoeff*force->ftm2v*(fcm[ibody][2]-fcm_old[ibody][2])/Gamma_MD[ibody]/dtv/nrigid_shell[ibody]; torque_factor = 5.0*Gamma_MD[ibody]*nrigid_shell[ibody]/(3.0*masstotal[ibody]); expminusdttimesgamma = exp(-dtv*torque_factor); DMDcoeff = (dtv - (1.0-expminusdttimesgamma)/torque_factor); omega[ibody][0] += tflag[ibody][0]*(3.0/(2.0*nrigid_shell[ibody]*sphereradius[ibody]*sphereradius[ibody]*Gamma_MD[ibody]))*DMDcoeff* force->ftm2v*(torque[ibody][0] - torque_old[ibody][0])/dtv; omega[ibody][1] += tflag[ibody][1]*(3.0/(2.0*nrigid_shell[ibody]*sphereradius[ibody]*sphereradius[ibody]*Gamma_MD[ibody]))*DMDcoeff* force->ftm2v*(torque[ibody][1] - torque_old[ibody][1])/dtv; omega[ibody][2] += tflag[ibody][2]*(3.0/(2.0*nrigid_shell[ibody]*sphereradius[ibody]*sphereradius[ibody]*Gamma_MD[ibody]))*DMDcoeff* force->ftm2v*(torque[ibody][2] - torque_old[ibody][2])/dtv; } //Next, calculate the correction to the velocity and angular momentum due to the fluid forces: //Calculate the fluid velocity at the new particle locations. compute_up(); // store fluid quantities for the total body for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; // Store the fluid velocity at the center of mass, and the total force // due to the fluid. for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (rmass) massone = rmass[i]; else massone = mass[type[i]]; domain->unmap(x[i],image[i],unwrap); dx = unwrap[0] - xcm[ibody][0]; dy = unwrap[1] - xcm[ibody][1]; dz = unwrap[2] - xcm[ibody][2]; if(inner_nodes == 1){ if(!(mask[i] & group->bitmask[igroupinner])){ sum[ibody][0] += up[i][0]*massone; sum[ibody][1] += up[i][1]*massone; sum[ibody][2] += up[i][2]*massone; sum[ibody][3] += Gamma_MD[ibody]*(dy * ((up[i][2]-vcm[ibody][2])) - dz * ((up[i][1]-vcm[ibody][1]))); sum[ibody][4] += Gamma_MD[ibody]*(dz * ((up[i][0]-vcm[ibody][0])) - dx * ((up[i][2]-vcm[ibody][2]))); sum[ibody][5] += Gamma_MD[ibody]*(dx * ((up[i][1]-vcm[ibody][1])) - dy * ((up[i][0]-vcm[ibody][0]))); } }else{ sum[ibody][0] += up[i][0]*massone; sum[ibody][1] += up[i][1]*massone; sum[ibody][2] += up[i][2]*massone; sum[ibody][3] += Gamma_MD[ibody]*(dy * ((up[i][2]-vcm[ibody][2])) - dz * ((up[i][1]-vcm[ibody][1]))); sum[ibody][4] += Gamma_MD[ibody]*(dz * ((up[i][0]-vcm[ibody][0])) - dx * ((up[i][2]-vcm[ibody][2]))); sum[ibody][5] += Gamma_MD[ibody]*(dx * ((up[i][1]-vcm[ibody][1])) - dy * ((up[i][0]-vcm[ibody][0]))); } } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); for (ibody = 0; ibody < nbody; ibody++) { ucm[ibody][0] = all[ibody][0]/masstotal_shell[ibody]; ucm[ibody][1] = all[ibody][1]/masstotal_shell[ibody]; ucm[ibody][2] = all[ibody][2]/masstotal_shell[ibody]; torque_fluid[ibody][0] = all[ibody][3]; torque_fluid[ibody][1] = all[ibody][4]; torque_fluid[ibody][2] = all[ibody][5]; } for (ibody = 0; ibody < nbody; ibody++) { expminusdttimesgamma = exp(-dtv*Gamma_MD[ibody]*nrigid_shell[ibody]/masstotal[ibody]); DMDcoeff= (dtv - (masstotal[ibody]/nrigid_shell[ibody])*(1.0-expminusdttimesgamma)/Gamma_MD[ibody]); vcm[ibody][0] += DMDcoeff*fflag[ibody][0]*(ucm[ibody][0]-ucm_old[ibody][0])/dtv; vcm[ibody][1] += DMDcoeff*fflag[ibody][1]*(ucm[ibody][1]-ucm_old[ibody][1])/dtv; vcm[ibody][2] += DMDcoeff*fflag[ibody][2]*(ucm[ibody][2]-ucm_old[ibody][2])/dtv; torque_factor = 5.0*Gamma_MD[ibody]*nrigid_shell[ibody]/(3.0*masstotal[ibody]); expminusdttimesgamma = exp(-dtv*torque_factor); DMDcoeff = (dtv - (1.0-expminusdttimesgamma)/torque_factor); omega[ibody][0] += tflag[ibody][0]*(3.0/(2.0*nrigid_shell[ibody]*sphereradius[ibody]*sphereradius[ibody]*Gamma_MD[ibody]))* DMDcoeff*(torque_fluid[ibody][0] - torque_fluid_old[ibody][0])/dtv; omega[ibody][1] += tflag[ibody][1]*(3.0/(2.0*nrigid_shell[ibody]*sphereradius[ibody]*sphereradius[ibody]*Gamma_MD[ibody]))* DMDcoeff*(torque_fluid[ibody][1] - torque_fluid_old[ibody][1])/dtv; omega[ibody][2] += tflag[ibody][2]*(3.0/(2.0*nrigid_shell[ibody]*sphereradius[ibody]*sphereradius[ibody]*Gamma_MD[ibody]))* DMDcoeff*(torque_fluid[ibody][2] - torque_fluid_old[ibody][2])/dtv; } set_v(); } /* ---------------------------------------------------------------------- set space-frame velocity of each atom in a rigid body set omega and angmom of extended particles v = Vcm + (W cross (x - Xcm)) ------------------------------------------------------------------------- */ void FixLbRigidPCSphere::set_v() { int ibody; int xbox,ybox,zbox; double dx,dy,dz; double x0,x1,x2,v0,v1,v2,fc0,fc1,fc2,massone; double vr[6]; double **x = atom->x; double **v = atom->v; double **f = atom->f; double *rmass = atom->rmass; double *mass = atom->mass; int *type = atom->type; imageint *image = atom->image; int nlocal = atom->nlocal; double xprd = domain->xprd; double yprd = domain->yprd; double zprd = domain->zprd; double xunwrap,yunwrap,zunwrap; // set v of each atom for (int i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; xbox = (image[i] & IMGMASK) - IMGMAX; ybox = (image[i] >> IMGBITS & IMGMASK) - IMGMAX; zbox = (image[i] >> IMG2BITS) - IMGMAX; xunwrap = x[i][0] + xbox*xprd; yunwrap = x[i][1] + ybox*yprd; zunwrap = x[i][2] + zbox*zprd; dx = xunwrap - xcm[ibody][0]; dy = yunwrap - xcm[ibody][1]; dz = zunwrap - xcm[ibody][2]; // save old velocities for virial. if(evflag){ v0 = v[i][0]; v1 = v[i][1]; v2 = v[i][2]; } v[i][0] = (omega[ibody][1]*dz - omega[ibody][2]*dy) + vcm[ibody][0]; v[i][1] = (omega[ibody][2]*dx - omega[ibody][0]*dz) + vcm[ibody][1]; v[i][2] = (omega[ibody][0]*dy - omega[ibody][1]*dx) + vcm[ibody][2]; // virial = unwrapped coords dotted into body constraint force // body constraint force = implied force due to v change minus f external // assume f does not include forces internal to body // 1/2 factor b/c initial_integrate contributes other half // assume per-atom contribution is due to constraint force on that atom if (evflag) { if (rmass) massone = rmass[i]; else massone = mass[type[i]]; fc0 = massone*(v[i][0] - v0)/dtf - f[i][0] + Gamma_MD[ibody]*(v0-up[i][0]); fc1 = massone*(v[i][1] - v1)/dtf - f[i][1] + Gamma_MD[ibody]*(v1-up[i][1]); fc2 = massone*(v[i][2] - v2)/dtf - f[i][2] + Gamma_MD[ibody]*(v2-up[i][2]); xbox = (image[i] & IMGMASK) - IMGMAX; ybox = (image[i] >> IMGBITS & IMGMASK) - IMGMAX; zbox = (image[i] >> IMG2BITS) - IMGMAX; x0 = x[i][0] + xbox*xprd; x1 = x[i][1] + ybox*yprd; x2 = x[i][2] + zbox*zprd; vr[0] = 0.5*x0*fc0; vr[1] = 0.5*x1*fc1; vr[2] = 0.5*x2*fc2; vr[3] = 0.5*x0*fc1; vr[4] = 0.5*x0*fc2; vr[5] = 0.5*x1*fc2; v_tally(1,&i,1.0,vr); } } } /* ---------------------------------------------------------------------- set space-frame coords and velocity of each atom in each rigid body set orientation and rotation of extended particles x = Q displace + Xcm, mapped back to periodic box v = Vcm + (W cross (x - Xcm)) ------------------------------------------------------------------------- */ void FixLbRigidPCSphere::set_xv() { int ibody; int xbox,ybox,zbox; double x0,x1,x2,v0,v1,v2,fc0,fc1,fc2,massone; double vr[6]; double **x = atom->x; double **v = atom->v; double **f = atom->f; double *rmass = atom->rmass; double *mass = atom->mass; int *type = atom->type; imageint *image = atom->image; int nlocal = atom->nlocal; double xprd = domain->xprd; double yprd = domain->yprd; double zprd = domain->zprd; double xunwrap,yunwrap,zunwrap; double dx,dy,dz; // set x and v of each atom for (int i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; xbox = (image[i] & IMGMASK) - IMGMAX; ybox = (image[i] >> IMGBITS & IMGMASK) - IMGMAX; zbox = (image[i] >> IMG2BITS) - IMGMAX; xunwrap = x[i][0] + xbox*xprd; yunwrap = x[i][1] + ybox*yprd; zunwrap = x[i][2] + zbox*zprd; dx = xunwrap - xcm_old[ibody][0]; dy = yunwrap - xcm_old[ibody][1]; dz = zunwrap - xcm_old[ibody][2]; // save old positions and velocities for virial if(evflag){ x0 = xunwrap; x1 = yunwrap; x2 = zunwrap; v0 = v[i][0]; v1 = v[i][1]; v2 = v[i][2]; } // x = displacement from center-of-mass, based on body orientation // v = vcm + omega around center-of-mass x[i][0] = dx; x[i][1] = dy; x[i][2] = dz; //Perform the rotations: dx = x[i][0]; dy = x[i][1]; dz = x[i][2]; x[i][0] = cos(rotate[ibody][2])*dx - sin(rotate[ibody][2])*dy; x[i][1] = sin(rotate[ibody][2])*dx + cos(rotate[ibody][2])*dy; dx = x[i][0]; dy = x[i][1]; dz = x[i][2]; x[i][0] = cos(rotate[ibody][1])*dx + sin(rotate[ibody][1])*dz; x[i][2] = -sin(rotate[ibody][1])*dx + cos(rotate[ibody][1])*dz; dx = x[i][0]; dy = x[i][1]; dz = x[i][2]; x[i][1] = cos(rotate[ibody][0])*dy - sin(rotate[ibody][0])*dz; x[i][2] = sin(rotate[ibody][0])*dy + cos(rotate[ibody][0])*dz; v[i][0] = (omega[ibody][1]*x[i][2] - omega[ibody][2]*x[i][1]) + vcm[ibody][0]; v[i][1] = (omega[ibody][2]*x[i][0] - omega[ibody][0]*x[i][2]) + vcm[ibody][1]; v[i][2] = (omega[ibody][0]*x[i][1] - omega[ibody][1]*x[i][0]) + vcm[ibody][2]; // add center of mass to displacement // map back into periodic box via xbox,ybox,zbox // for triclinic, add in box tilt factors as well x[i][0] += xcm[ibody][0] - xbox*xprd; x[i][1] += xcm[ibody][1] - ybox*yprd; x[i][2] += xcm[ibody][2] - zbox*zprd; // virial = unwrapped coords dotted into body constraint force // body constraint force = implied force due to v change minus f external // assume f does not include forces internal to body // 1/2 factor b/c final_integrate contributes other half // assume per-atom contribution is due to constraint force on that atom if (evflag) { if (rmass) massone = rmass[i]; else massone = mass[type[i]]; fc0 = massone*(v[i][0] - v0)/dtf - f[i][0] + Gamma_MD[ibody]*(v0-up[i][0]); fc1 = massone*(v[i][1] - v1)/dtf - f[i][1] + Gamma_MD[ibody]*(v1-up[i][1]); fc2 = massone*(v[i][2] - v2)/dtf - f[i][2] + Gamma_MD[ibody]*(v2-up[i][2]); vr[0] = 0.5*x0*fc0; vr[1] = 0.5*x1*fc1; vr[2] = 0.5*x2*fc2; vr[3] = 0.5*x0*fc1; vr[4] = 0.5*x0*fc2; vr[5] = 0.5*x1*fc2; v_tally(1,&i,1.0,vr); } } } /* ---------------------------------------------------------------------- remap xcm of each rigid body back into periodic simulation box done during pre_neighbor so will be after call to pbc() and after fix_deform::pre_exchange() may have flipped box use domain->remap() in case xcm is far away from box due to 1st definition of rigid body or due to box flip if don't do this, then atoms of a body which drifts far away from a triclinic box will be remapped back into box with huge displacements when the box tilt changes via set_x() ------------------------------------------------------------------------- */ void FixLbRigidPCSphere::pre_neighbor() { imageint original,oldimage,newimage; for (int ibody = 0; ibody < nbody; ibody++) { original = imagebody[ibody]; domain->remap(xcm[ibody],imagebody[ibody]); if (original == imagebody[ibody]) remapflag[ibody][3] = 0; else { oldimage = original & IMGMASK; newimage = imagebody[ibody] & IMGMASK; remapflag[ibody][0] = newimage - oldimage; oldimage = (original >> IMGBITS) & IMGMASK; newimage = (imagebody[ibody] >> IMGBITS) & IMGMASK; remapflag[ibody][1] = newimage - oldimage; oldimage = original >> IMG2BITS; newimage = imagebody[ibody] >> IMG2BITS; remapflag[ibody][2] = newimage - oldimage; remapflag[ibody][3] = 1; } } // adjust image flags of any atom in a rigid body whose xcm was remapped imageint *atomimage = atom->image; int nlocal = atom->nlocal; int ibody; imageint idim,otherdims; for (int i = 0; i < nlocal; i++) { if (body[i] == -1) continue; if (remapflag[body[i]][3] == 0) continue; ibody = body[i]; if (remapflag[ibody][0]) { idim = atomimage[i] & IMGMASK; otherdims = atomimage[i] ^ idim; idim -= remapflag[ibody][0]; idim &= IMGMASK; atomimage[i] = otherdims | idim; } if (remapflag[ibody][1]) { idim = (atomimage[i] >> IMGBITS) & IMGMASK; otherdims = atomimage[i] ^ (idim << IMGBITS); idim -= remapflag[ibody][1]; idim &= IMGMASK; atomimage[i] = otherdims | (idim << IMGBITS); } if (remapflag[ibody][2]) { idim = atomimage[i] >> IMG2BITS; otherdims = atomimage[i] ^ (idim << IMG2BITS); idim -= remapflag[ibody][2]; idim &= IMGMASK; atomimage[i] = otherdims | (idim << IMG2BITS); } } } /* ---------------------------------------------------------------------- count # of degrees-of-freedom removed by fix_rigid for atoms in igroup ------------------------------------------------------------------------- */ int FixLbRigidPCSphere::dof(int igroup) { int groupbit = group->bitmask[igroup]; // ncount = # of atoms in each rigid body that are also in group int *mask = atom->mask; int nlocal = atom->nlocal; int *ncount = new int[nbody]; for (int ibody = 0; ibody < nbody; ibody++) ncount[ibody] = 0; for (int i = 0; i < nlocal; i++) if (body[i] >= 0 && mask[i] & groupbit) ncount[body[i]]++; int *nall = new int[nbody]; MPI_Allreduce(ncount,nall,nbody,MPI_INT,MPI_SUM,world); // remove 3N - 6 dof for each rigid body if more than 2 atoms in igroup // remove 3N - 5 dof for each diatomic rigid body in igroup int n = 0; for (int ibody = 0; ibody < nbody; ibody++) { if (nall[ibody] > 2) n += 3*nall[ibody] - 6; else if (nall[ibody] == 2) n++; } delete [] ncount; delete [] nall; return n; } /* ---------------------------------------------------------------------- memory usage of local atom-based arrays ------------------------------------------------------------------------- */ double FixLbRigidPCSphere::memory_usage() { int nmax = atom->nmax; double bytes = nmax * sizeof(int); bytes += nmax*3 * sizeof(double); bytes += maxvatom*6 * sizeof(double); return bytes; } /* ---------------------------------------------------------------------- allocate local atom-based arrays ------------------------------------------------------------------------- */ void FixLbRigidPCSphere::grow_arrays(int nmax) { memory->grow(body,nmax,"rigid:body"); memory->grow(up,nmax,3,"rigid:up"); } /* ---------------------------------------------------------------------- copy values within local atom-based arrays ------------------------------------------------------------------------- */ void FixLbRigidPCSphere::copy_arrays(int i, int j, int delflag) { body[j] = body[i]; up[j][0] = up[i][0]; up[j][1] = up[i][1]; up[j][2] = up[i][2]; } /* ---------------------------------------------------------------------- initialize one atom's array values, called when atom is created ------------------------------------------------------------------------- */ void FixLbRigidPCSphere::set_arrays(int i) { body[i] = -1; up[i][0] = 0.0; up[i][1] = 0.0; up[i][2] = 0.0; } /* ---------------------------------------------------------------------- pack values in local atom-based arrays for exchange with another proc ------------------------------------------------------------------------- */ int FixLbRigidPCSphere::pack_exchange(int i, double *buf) { buf[0] = body[i]; buf[1] = up[i][0]; buf[2] = up[i][1]; buf[3] = up[i][2]; return 4; } /* ---------------------------------------------------------------------- unpack values in local atom-based arrays from exchange with another proc ------------------------------------------------------------------------- */ int FixLbRigidPCSphere::unpack_exchange(int nlocal, double *buf) { body[nlocal] = static_cast<int> (buf[0]); up[nlocal][0] = buf[1]; up[nlocal][1] = buf[2]; up[nlocal][2] = buf[3]; return 4; } /* ---------------------------------------------------------------------- */ void FixLbRigidPCSphere::reset_dt() { dtv = update->dt; dtf = 0.5 * update->dt * force->ftm2v; } /* ---------------------------------------------------------------------- return temperature of collection of rigid bodies non-active DOF are removed by fflag/tflag and in tfactor ------------------------------------------------------------------------- */ double FixLbRigidPCSphere::compute_scalar() { double inertia; double t = 0.0; for (int i = 0; i < nbody; i++) { t += masstotal[i] * (fflag[i][0]*vcm[i][0]*vcm[i][0] + fflag[i][1]*vcm[i][1]*vcm[i][1] + \ fflag[i][2]*vcm[i][2]*vcm[i][2]); // wbody = angular velocity in body frame inertia = 2.0*masstotal[i]*sphereradius[i]*sphereradius[i]/5.0; t += tflag[i][0]*inertia*omega[i][0]*omega[i][0] + tflag[i][1]*inertia*omega[i][1]*omega[i][1] + tflag[i][2]*inertia*omega[i][2]*omega[i][2]; } t *= tfactor; return t; } /* ---------------------------------------------------------------------- return attributes of a rigid body 15 values per body xcm = 0,1,2; vcm = 3,4,5; fcm = 6,7,8; torque = 9,10,11; image = 12,13,14 ------------------------------------------------------------------------- */ double FixLbRigidPCSphere::compute_array(int i, int j) { if (j < 3) return xcm[i][j]; if (j < 6) return vcm[i][j-3]; if (j < 9) return (fcm[i][j-6]+fcm_fluid[i][j-6]); if (j < 12) return (torque[i][j-9]+torque_fluid[i][j-9]); if (j == 12) return (imagebody[i] & IMGMASK) - IMGMAX; if (j == 13) return (imagebody[i] >> IMGBITS & IMGMASK) - IMGMAX; return (imagebody[i] >> IMG2BITS) - IMGMAX; } /* ---------------------------------------------------------------------- */ void FixLbRigidPCSphere::compute_up(void) { int *mask = atom->mask; int nlocal = atom->nlocal; double **x = atom->x; int i,k; int ix,iy,iz; int ixp,iyp,izp; double dx1,dy1,dz1; int isten,ii,jj,kk; double r,rsq,weightx,weighty,weightz; double ****u_lb = fix_lb_fluid->u_lb; int subNbx = fix_lb_fluid->subNbx; int subNby = fix_lb_fluid->subNby; int subNbz = fix_lb_fluid->subNbz; double dx_lb = fix_lb_fluid->dx_lb; double dt_lb = fix_lb_fluid->dt_lb; int trilinear_stencil = fix_lb_fluid->trilinear_stencil; double FfP[64]; for(i=0; i<nlocal; i++){ if(mask[i] & groupbit){ //Calculate nearest leftmost grid point. //Since array indices from 1 to subNb-2 correspond to the // local subprocessor domain (not indices from 0), use the // ceiling value. ix = (int)ceil((x[i][0]-domain->sublo[0])/dx_lb); iy = (int)ceil((x[i][1]-domain->sublo[1])/dx_lb); iz = (int)ceil((x[i][2]-domain->sublo[2])/dx_lb); //Calculate distances to the nearest points. dx1 = x[i][0] - (domain->sublo[0] + (ix-1)*dx_lb); dy1 = x[i][1] - (domain->sublo[1] + (iy-1)*dx_lb); dz1 = x[i][2] - (domain->sublo[2] + (iz-1)*dx_lb); // Need to convert these to lattice units: dx1 = dx1/dx_lb; dy1 = dy1/dx_lb; dz1 = dz1/dx_lb; up[i][0]=0.0; up[i][1]=0.0; up[i][2]=0.0; if(trilinear_stencil==0){ isten=0; for(ii=-1; ii<3; ii++){ rsq=(-dx1+ii)*(-dx1+ii); if(rsq>=4) weightx=0.0; else{ r=sqrt(rsq); if(rsq>1){ weightx=(5.0-2.0*r-sqrt(-7.0+12.0*r-4.0*rsq))/8.; } else{ weightx=(3.0-2.0*r+sqrt(1.0+4.0*r-4.0*rsq))/8.; } } for(jj=-1; jj<3; jj++){ rsq=(-dy1+jj)*(-dy1+jj); if(rsq>=4) weighty=0.0; else{ r=sqrt(rsq); if(rsq>1){ weighty=(5.0-2.0*r-sqrt(-7.0+12.0*r-4.0*rsq))/8.; } else{ weighty=(3.0-2.0*r+sqrt(1.0+4.0*r-4.0*rsq))/8.; } } for(kk=-1; kk<3; kk++){ rsq=(-dz1+kk)*(-dz1+kk); if(rsq>=4) weightz=0.0; else{ r=sqrt(rsq); if(rsq>1){ weightz=(5.0-2.0*r-sqrt(-7.0+12.0*r-4.0*rsq))/8.; } else{ weightz=(3.0-2.0*r+sqrt(1.0+4.0*r-4.0*rsq))/8.; } } ixp = ix+ii; iyp = iy+jj; izp = iz+kk; if(ixp==-1) ixp=subNbx+2; if(iyp==-1) iyp=subNby+2; if(izp==-1) izp=subNbz+2; FfP[isten] = weightx*weighty*weightz; // interpolated velocity based on delta function. for(k=0; k<3; k++){ up[i][k] += u_lb[ixp][iyp][izp][k]*FfP[isten]; } } } } }else{ FfP[0] = (1.-dx1)*(1.-dy1)*(1.-dz1); FfP[1] = (1.-dx1)*(1.-dy1)*dz1; FfP[2] = (1.-dx1)*dy1*(1.-dz1); FfP[3] = (1.-dx1)*dy1*dz1; FfP[4] = dx1*(1.-dy1)*(1.-dz1); FfP[5] = dx1*(1.-dy1)*dz1; FfP[6] = dx1*dy1*(1.-dz1); FfP[7] = dx1*dy1*dz1; ixp = (ix+1); iyp = (iy+1); izp = (iz+1); for (k=0; k<3; k++) { // tri-linearly interpolated velocity at node up[i][k] = u_lb[ix][iy][iz][k]*FfP[0] + u_lb[ix][iy][izp][k]*FfP[1] + u_lb[ix][iyp][iz][k]*FfP[2] + u_lb[ix][iyp][izp][k]*FfP[3] + u_lb[ixp][iy][iz][k]*FfP[4] + u_lb[ixp][iy][izp][k]*FfP[5] + u_lb[ixp][iyp][iz][k]*FfP[6] + u_lb[ixp][iyp][izp][k]*FfP[7]; } } for(k=0; k<3; k++) up[i][k] = up[i][k]*dx_lb/dt_lb; } } }
54,740
C++
.cpp
1,360
35.722059
152
0.576787
huilinye/OpenFSI
31
20
6
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
1,534,022
palammps2D.cpp
huilinye_OpenFSI/src/main/palammps2D.cpp
/* This file is part of the Palabos_Lammps coupling program. * * Copyright (C) 2011-2015 FlowKit Sarl * Route d'Oron 2 * 1010 Lausanne, Switzerland * E-mail contact: contact@flowkit.com * * The most recent release of Palabos can be downloaded at * <http://www.palabos.org/> * * The library Palabos is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * The library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * Copyright 2018 Huilin Ye University of Connecticut * Author: Huilin Ye (huilin.ye@uconn.edu) */ #include "palabos2D.h" #include "palabos2D.hh" #include "ibm2D.h" #include <vector> #include <cmath> #include <iostream> #include <fstream> #include "mpi.h" #include "lammps.h" #include "input.h" #include "library.h" #include "lammpsWrapper.h" #include "latticeDecomposition2D.h" //#include "nearestTwoNeighborLattices3D.h" using namespace plb; using namespace std; typedef double T; //#define DESCRIPTOR descriptors::ForcedN2D3Q19Descriptor #define DESCRIPTOR descriptors::ForcedD2Q9Descriptor //#define DYNAMICS BGKdynamics<T, DESCRIPTOR>(parameters.getOmega()) #define DYNAMICS GuoExternalForceBGKdynamics<T, DESCRIPTOR>(parameters.getOmega()) #define NMAX 150 // initial parameters plint Resolution = 0; T ReynoldsNumber = 0; T Viscosity = 0.; T x_length = 0; T y_length = 0; //T z_length = 0; plint Shear_flag = 0; T Shear_Top_Velocity = 0; T Shear_Bot_Velocity = 0; plint Poiseuille_flag = 0; T Poiseuille_bodyforce = 0; plint Uniform_flag = 0; T U_uniform = 0; plint Total_timestep = 0; plint Output_fluid_file = 0; plint Output_check_file = 0; plint CouplingType = 1; //1: velocity coupling(default); 2: force coupling plint StaticAtomType = 0; //fix atom with specific type const T pi = (T)4.*std::atan((T)1.); /// Velocity on the parabolic Poiseuille profile T poiseuilleVelocity(plint iY, IncomprFlowParam<T> const& parameters) { T y = (T)iY / parameters.getResolution(); T Ly = parameters.getNy()-1; return 0.06*6*y*(Ly-y)/(Ly*Ly); } /// Linearly decreasing pressure profile T poiseuillePressure(plint iX, IncomprFlowParam<T> const& parameters) { T Lx = parameters.getNx()-1; T Ly = parameters.getNy()-1; return 0.06*12.*parameters.getLatticeNu()/ (Ly*Ly) * (Lx-(T)iX); } /// Convert pressure to density according to ideal gas law T poiseuilleDensity(plint iX, IncomprFlowParam<T> const& parameters) { return poiseuillePressure(iX,parameters)*DESCRIPTOR<T>::invCs2 + (T)1; } /// A functional, used to initialize the velocity for the boundary conditions template<typename T> class PoiseuilleVelocity { public: PoiseuilleVelocity(IncomprFlowParam<T> parameters_) : parameters(parameters_) { } void operator()(plint iX, plint iY, Array<T,2>& u) const { u[0] = poiseuilleVelocity(iY, parameters); u[1] = T(); } private: IncomprFlowParam<T> parameters; }; /// A functional, used to initialize a pressure boundary to constant density template<typename T> class ConstantDensity { public: ConstantDensity(T density_) : density(density_) { } T operator()(plint iX, plint iY) const { return density; } private: T density; }; /// A functional, used to create an initial condition for the density and velocity template<typename T> class PoiseuilleVelocityAndDensity { public: PoiseuilleVelocityAndDensity(IncomprFlowParam<T> parameters_) : parameters(parameters_) { } void operator()(plint iX, plint iY, T& rho, Array<T,2>& u) const { rho = poiseuilleDensity(iX,parameters); u[0] = poiseuilleVelocity(iY, parameters); u[1] = T(); } private: IncomprFlowParam<T> parameters; }; template <typename T> class ShearTopVelocity { public: ShearTopVelocity( IncomprFlowParam<T> const& parameters_, plint maxN_) : parameters(parameters_), maxN(maxN_) { } void operator()(plint iX, plint iY, Array<T,2>& u) const { u[0] = Shear_Top_Velocity; u[1] = T(); //u[2] = T(); } private: IncomprFlowParam<T> parameters; plint maxN; }; template <typename T> class ShearBottomVelocity { public: ShearBottomVelocity(IncomprFlowParam<T> const& parameters_, plint maxN_) : parameters(parameters_), maxN(maxN_) { } void operator()(plint iX, plint iY, Array<T,2>& u) const { u[0] = Shear_Bot_Velocity; u[1] = T(); //u[2] = T(); } private: IncomprFlowParam<T> parameters; plint maxN; }; void bishearSetup(MultiBlockLattice2D<T,DESCRIPTOR>& lattice, IncomprFlowParam<T> const& parameters, OnLatticeBoundaryCondition2D<T,DESCRIPTOR>& boundaryCondition ) //velocity along y direction { const plint nx = parameters.getNx(); const plint ny = parameters.getNy(); //const plint nz = parameters.getNz(); Box2D top = Box2D(0, nx-1, ny-1, ny-1); //y-direction Box2D bottom = Box2D(0, nx-1, 0, 0); //Box3D left = Box3D(1, nx-2, 0, 0, 1, nz-2); //Box3D right = Box3D(1, nx-2, ny-1, ny-1, 1, nz-2); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, top ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, bottom ); //boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, left, boundary::outflow ); //boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, right, boundary::outflow ); setBoundaryVelocity(lattice, top, ShearTopVelocity<T>(parameters,NMAX)); setBoundaryVelocity(lattice, bottom, ShearBottomVelocity<T>(parameters,NMAX)); initializeAtEquilibrium(lattice, lattice.getBoundingBox(),(T)1.0, Array<T,2>(0.0,0.0)); lattice.initialize(); } void poiseSetup( MultiBlockLattice2D<T,DESCRIPTOR>& lattice, IncomprFlowParam<T> const& parameters, OnLatticeBoundaryCondition2D<T,DESCRIPTOR>& boundaryCondition ) { const plint nx = parameters.getNx(); const plint ny = parameters.getNy(); Box2D outlet(nx-1,nx-1, 1, ny-2); // Create Velocity boundary conditions everywhere boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, Box2D(0, 0, 1, ny-2) ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, Box2D(0, nx-1, 0, 0) ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, Box2D(0, nx-1, ny-1, ny-1) ); // .. except on right boundary, where we prefer an outflow condition // (zero velocity-gradient). boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, Box2D(nx-1, nx-1, 1, ny-2), boundary::outflow ); setBoundaryVelocity ( lattice, lattice.getBoundingBox(), PoiseuilleVelocity<T>(parameters) ); setBoundaryDensity ( lattice, outlet, ConstantDensity<T>(1.) ); initializeAtEquilibrium ( lattice, lattice.getBoundingBox(), PoiseuilleVelocityAndDensity<T>(parameters) ); lattice.initialize(); } void poise_force_Setup( MultiBlockLattice2D<T,DESCRIPTOR>& lattice, IncomprFlowParam<T> const& parameters, OnLatticeBoundaryCondition2D<T,DESCRIPTOR>& boundaryCondition ) { const plint nx = parameters.getNx(); const plint ny = parameters.getNy(); Box2D top = Box2D(0, nx-1, ny-1, ny-1); //y-direction Box2D bottom = Box2D(0, nx-1, 0, 0); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, top ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, bottom ); setBoundaryVelocity(lattice, top, Array<T,2>((T)0.0,(T)0.0)); setBoundaryVelocity(lattice, bottom, Array<T,2>((T)0.0,(T)0.0)); initializeAtEquilibrium(lattice, lattice.getBoundingBox(),(T)1.0, Array<T,2>(0.0,0.0)); lattice.initialize(); } void uniformSetup( MultiBlockLattice2D<T,DESCRIPTOR>& lattice, IncomprFlowParam<T> const& parameters, OnLatticeBoundaryCondition2D<T,DESCRIPTOR>& boundaryCondition ) { const plint nx = parameters.getNx(); const plint ny = parameters.getNy(); Box2D outlet(nx-1,nx-1, 0, ny-1); Box2D inlet(0,0, 0, ny-1); Box2D top = Box2D(1, nx-2, ny-1, ny-1); //y-direction Box2D bottom = Box2D(1, nx-2, 0, 0); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, top, boundary::freeslip ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, bottom, boundary::freeslip ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, inlet ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, outlet, boundary::normalOutflow ); setBoundaryVelocity(lattice, inlet,Array<T,2>(U_uniform,0.0)); initializeAtEquilibrium ( lattice, lattice.getBoundingBox(), (T)1.0, Array<T,2>(U_uniform,0.0) ); lattice.initialize(); } void writeVTK(MultiBlockLattice2D<T,DESCRIPTOR>& lattice, IncomprFlowParam<T> const& parameters, plint iter) { T dx = parameters.getDeltaX(); T dt = parameters.getDeltaT(); VtkImageOutput2D<T> vtkOut(createFileName("vtk", iter, 6), dx); vtkOut.writeData<float>(*computeVelocityNorm(lattice), "velocityNorm", dx/dt); vtkOut.writeData<float>(*computeDensity(lattice), "density", (T)1.0); vtkOut.writeData<2,float>(*computeVelocity(lattice), "velocity", dx/dt); //vtkOut.writeData<2,float>(*computeVorticity(*computeVelocity(lattice)), "vorticity", 1./dt); } void readParameters(XMLreader const& document) { document["geometry"]["Resolution"].read(Resolution); document["geometry"]["Viscosity"].read(Viscosity); document["geometry"]["x_length"].read(x_length); document["geometry"]["y_length"].read(y_length); //document["geometry"]["z_length"].read(z_length); document["fluid"]["Shear_flag"].read(Shear_flag); document["fluid"]["Shear_Top_Velocity"].read(Shear_Top_Velocity); document["fluid"]["Shear_Bot_Velocity"].read(Shear_Bot_Velocity); document["fluid"]["Poiseuille_flag"].read(Poiseuille_flag); document["fluid"]["Poiseuille_bodyforce"].read(Poiseuille_bodyforce); document["fluid"]["Uniform_flag"].read(Uniform_flag); document["fluid"]["U_uniform"].read(U_uniform); document["simulation"]["Total_timestep"].read(Total_timestep); document["simulation"]["Output_fluid_file"].read(Output_fluid_file); document["simulation"]["Output_check_file"].read(Output_check_file); document["simulation"]["CouplingType"].read(CouplingType); document["simulation"]["StaticAtomType"].read(StaticAtomType); } int main(int argc, char* argv[]) { plbInit(&argc, &argv); global::directories().setOutputDir("./tmp/"); //read parameters from external file string paramXmlFileName; paramXmlFileName = "param.xml"; XMLreader document(paramXmlFileName); readParameters(paramXmlFileName); ReynoldsNumber = 1.0/Viscosity; IncomprFlowParam<T> parameters( 1.0, ReynoldsNumber, Resolution, x_length, // lx y_length // ly ); //writeLogFile(parameters, "Flow conditions"); LammpsWrapper wrapper(argv,global::mpi().getGlobalCommunicator()); char * inlmp = argv[1]; wrapper.execFile(inlmp); //MultiTensorField3D<T,3> vel(parameters.getNx(),parameters.getNy(),parameters.getNz()); pcout<<"Nx,Ny "<<parameters.getNx()<<" "<<parameters.getNy()<<endl; LatticeDecomposition2D lDec(parameters.getNx(),parameters.getNy(), 1.0, wrapper.lmp); SparseBlockStructure2D blockStructure = lDec.getBlockDistribution(); ExplicitThreadAttribution* threadAttribution = lDec.getThreadAttribution(); plint envelopeWidth = 2; MultiBlockLattice2D<T, DESCRIPTOR> lattice (MultiBlockManagement2D (blockStructure, threadAttribution, envelopeWidth ), defaultMultiBlockPolicy2D().getBlockCommunicator(), defaultMultiBlockPolicy2D().getCombinedStatistics(), defaultMultiBlockPolicy2D().getMultiCellAccess<T,DESCRIPTOR>(), new DYNAMICS ); //Cell<T,DESCRIPTOR> &cell = lattice.get(550,5500,550); pcout<<"dx "<<parameters.getDeltaX()<<" dt "<<parameters.getDeltaT()<<" tau "<<parameters.getTau()<<endl; //pcout<<"51 works"<<endl; // set periodic boundary conditions. if (Shear_flag == 1){ lattice.periodicity().toggle(0,true); //lattice.periodicity().toggle(1,true); } //if(Poiseuille_flag == 1){ //lattice.periodicity().toggle(0,true); //} OnLatticeBoundaryCondition2D<T,DESCRIPTOR>* boundaryCondition = createLocalBoundaryCondition2D<T,DESCRIPTOR>(); if (Shear_flag == 1) bishearSetup(lattice, parameters, *boundaryCondition); //bi-shear flow boundary condition if (Poiseuille_flag == 1) poiseSetup(lattice, parameters, *boundaryCondition); //velocity distribution //if (Poiseuille_flag == 1) //poise_force_Setup(lattice, parameters, *boundaryCondition); if (Uniform_flag == 1) uniformSetup(lattice, parameters, *boundaryCondition); // Loop over main time iteration. util::ValueTracer<T> converge(parameters.getLatticeU(),parameters.getResolution(),1.0e-3); //coupling between lammps and palabos /* for (plint iT=0;iT<4e3;iT++){ //warm up lattice.collideAndStream(); } */ T timeduration = T(); global::timer("mainloop").start(); //writeVTK(lattice, parameters, 0); for (plint iT=0; iT<Total_timestep+1; ++iT) { if (iT%Output_fluid_file ==0 && iT >0){ pcout<<"Saving VTK file..."<<endl; writeVTK(lattice, parameters, iT); } if (iT%Output_check_file ==0 && iT >0){ pcout<<"Timestep "<<iT<<" Saving checkPoint file..."<<endl; saveBinaryBlock(lattice,"checkpoint.dat"); } // lammps to calculate force //wrapper.execCommand("run 1 pre no post no"); wrapper.execCommand("run 1"); // Clear and spread fluid force if (Shear_flag == 1){ Array<T,2> force(0,0.); setExternalVector(lattice,lattice.getBoundingBox(),DESCRIPTOR<T>::ExternalField::forceBeginsAt,force); } //if (Poiseuille_flag == 1){ //Array<T,2> force(Poiseuille_bodyforce,0); //setExternalVector(lattice,lattice.getBoundingBox(),DESCRIPTOR<T>::ExternalField::forceBeginsAt,force); //} if (CouplingType == 1){ //-----classical ibm coupling-------------// spreadForce2D_fix(lattice,wrapper,StaticAtomType); ////// Lattice Boltzmann iteration step. //interpolateVelocity3D_fix(lattice,wrapper); lattice.collideAndStream(); //Interpolate and update solid position interpolateVelocity2D_fix(lattice,wrapper,StaticAtomType); }else{ forceCoupling2D(lattice,wrapper); lattice.collideAndStream(); } } timeduration = global::timer("mainloop").stop(); pcout<<"total execution time "<<timeduration<<endl; delete boundaryCondition; }
15,784
C++
.cpp
373
36.780161
121
0.694139
huilinye/OpenFSI
31
20
6
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,023
palammps.cpp
huilinye_OpenFSI/src/main/palammps.cpp
/* This file is part of the Palabos_Lammps coupling program. * * Copyright (C) 2011-2015 FlowKit Sarl * Route d'Oron 2 * 1010 Lausanne, Switzerland * E-mail contact: contact@flowkit.com * * The most recent release of Palabos can be downloaded at * <http://www.palabos.org/> * * The library Palabos is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * The library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * Copyright 2018 Huilin Ye University of Connecticut * Author: Huilin Ye (huilin.ye@uconn.edu) */ #include "palabos3D.h" #include "palabos3D.hh" #include "ibm3D.h" #include <vector> #include <cmath> #include <iostream> #include <fstream> #include "mpi.h" #include "lammps.h" #include "input.h" #include "library.h" #include "lammpsWrapper.h" #include "latticeDecomposition.h" //#include "nearestTwoNeighborLattices3D.h" using namespace plb; using namespace std; typedef double T; //#define DESCRIPTOR descriptors::ForcedN2D3Q19Descriptor #define DESCRIPTOR descriptors::ForcedD3Q19Descriptor //#define DYNAMICS BGKdynamics<T, DESCRIPTOR>(parameters.getOmega()) #define DYNAMICS GuoExternalForceBGKdynamics<T, DESCRIPTOR>(parameters.getOmega()) #define NMAX 150 // initial parameters plint Resolution = 0; T ReynoldsNumber = 0; T Viscosity = 0.; T x_length = 0; T y_length = 0; T z_length = 0; plint Shear_flag = 0; T Shear_Top_Velocity = 0; T Shear_Bot_Velocity = 0; plint Poiseuille_flag = 0; T Poiseuille_bodyforce = 0; plint Uniform_flag = 0; T U_uniform = 0; plint Total_timestep = 0; plint Output_fluid_file = 0; plint Output_check_file = 0; plint CouplingType = 1; //1: velocity coupling(default); 2: force coupling const T pi = (T)4.*std::atan((T)1.); template <typename T> class ShearTopVelocity { public: ShearTopVelocity( IncomprFlowParam<T> const& parameters_, plint maxN_) : parameters(parameters_), maxN(maxN_) { } void operator()(plint iX, plint iY, plint iZ, Array<T,3>& u) const { u[0] = T(); u[1] = Shear_Top_Velocity; u[2] = T(); } private: IncomprFlowParam<T> parameters; plint maxN; }; template <typename T> class ShearBottomVelocity { public: ShearBottomVelocity(IncomprFlowParam<T> const& parameters_, plint maxN_) : parameters(parameters_), maxN(maxN_) { } void operator()(plint iX, plint iY, plint iZ, Array<T,3>& u) const { u[0] = T(); u[1] = Shear_Bot_Velocity; u[2] = T(); } private: IncomprFlowParam<T> parameters; plint maxN; }; void bishearSetup(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, IncomprFlowParam<T> const& parameters, OnLatticeBoundaryCondition3D<T,DESCRIPTOR>& boundaryCondition ) //velocity along y direction { const plint nx = parameters.getNx(); const plint ny = parameters.getNy(); const plint nz = parameters.getNz(); Box3D top = Box3D(0, nx-1, 0, ny-1, nz-1, nz-1); //z-direction Box3D bottom = Box3D(0, nx-1, 0, ny-1, 0, 0); //Box3D left = Box3D(1, nx-2, 0, 0, 1, nz-2); //Box3D right = Box3D(1, nx-2, ny-1, ny-1, 1, nz-2); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, top ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, bottom ); //boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, left, boundary::outflow ); //boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, right, boundary::outflow ); setBoundaryVelocity(lattice, top, ShearTopVelocity<T>(parameters,NMAX)); setBoundaryVelocity(lattice, bottom, ShearBottomVelocity<T>(parameters,NMAX)); initializeAtEquilibrium(lattice, lattice.getBoundingBox(),(T)1.0, Array<T,3>(0.0,0.0,0.0)); lattice.initialize(); } void squarePoiseuilleSetup( MultiBlockLattice3D<T,DESCRIPTOR>& lattice, IncomprFlowParam<T> const& parameters, OnLatticeBoundaryCondition3D<T,DESCRIPTOR>& boundaryCondition ) { const plint nx = parameters.getNx(); const plint ny = parameters.getNy(); const plint nz = parameters.getNz(); Box3D top = Box3D(0, nx-1, 0, ny-1, nz-1, nz-1); //z direction Box3D bottom = Box3D(0, nx-1, 0, ny-1, 0, 0); //Box3D inlet = Box3D(0, nx-1, 0, 0, 0, nz-1); //y direction //Box3D outlet = Box3D(0, nx-1, ny-1, ny-1, 0, nz-1); Box3D back = Box3D(0, 0, 0, ny-1, 0, nz-1); Box3D front = Box3D(nx-1, nx-1, 0, ny-1, 0, nz-1); // channel flow //boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, inlet); //boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, outlet); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, top ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, bottom ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, front ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, back ); //setBoundaryVelocity(lattice, inlet, SquarePoiseuilleVelocity<T>(parameters, NMAX)); //setBoundaryVelocity(lattice, outlet, SquarePoiseuilleVelocity<T>(parameters, NMAX)); setBoundaryVelocity(lattice, top, Array<T,3>((T)0.0,(T)0.0,(T)0.0)); setBoundaryVelocity(lattice, bottom, Array<T,3>((T)0.0,(T)0.0,(T)0.0)); setBoundaryVelocity(lattice, front, Array<T,3>((T)0.0,(T)0.0,(T)0.0)); setBoundaryVelocity(lattice, back, Array<T,3>((T)0.0,(T)0.0,(T)0.0)); //initializeAtEquilibrium(lattice, lattice.getBoundingBox(), SquarePoiseuilleDensityAndVelocity<T>(parameters, NMAX)); initializeAtEquilibrium(lattice, lattice.getBoundingBox(),(T)1.0, Array<T,3>(0.0,0.0,0.0)); lattice.initialize(); } void uniformSetup(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, IncomprFlowParam<T> const& parameters, OnLatticeBoundaryCondition3D<T,DESCRIPTOR>& boundaryCondition ) //velocity along y direction { const plint nx = parameters.getNx(); const plint ny = parameters.getNy(); const plint nz = parameters.getNz(); Box3D top = Box3D(0, nx-1, 0, ny-1, nz-1, nz-1); //z-direction Box3D bottom = Box3D(0, nx-1, 0, ny-1, 0, 0); Box3D left = Box3D(1, nx-2, 0, 0, 1, nz-2); Box3D right = Box3D(1, nx-2, ny-1, ny-1, 1, nz-2); Box3D front = Box3D(0, 0, 1, ny-1, 1, nz-1); Box3D back = Box3D(nx-1, nx-1, 1, ny-1, 1, nz-1); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, top ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, bottom); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, left); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, right, boundary::outflow ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, front ); boundaryCondition.setVelocityConditionOnBlockBoundaries ( lattice, back); setBoundaryVelocity(lattice, left, Array<T,3>(0.0,U_uniform,0.0)); //setBoundaryVelocity(lattice, bottom, ShearBottomVelocity<T>(parameters,NMAX)); setBoundaryVelocity(lattice, top, Array<T,3>((T)0.0,(T)U_uniform,(T)0.0)); setBoundaryVelocity(lattice, bottom, Array<T,3>((T)0.0,(T)U_uniform,(T)0.0)); setBoundaryVelocity(lattice, front, Array<T,3>((T)0.0,(T)U_uniform,(T)0.0)); setBoundaryVelocity(lattice, back, Array<T,3>((T)0.0,(T)U_uniform,(T)0.0)); setBoundaryDensity (lattice, right,(T)1.0 ); initializeAtEquilibrium(lattice, lattice.getBoundingBox(),(T)1.0, Array<T,3>(0.0,0.0,0.0)); lattice.initialize(); } void writeVTK(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, IncomprFlowParam<T> const& parameters, plint iter) { T dx = parameters.getDeltaX(); T dt = parameters.getDeltaT(); VtkImageOutput3D<T> vtkOut(createFileName("vtk", iter, 6), dx); vtkOut.writeData<float>(*computeVelocityNorm(lattice), "velocityNorm", dx/dt); vtkOut.writeData<float>(*computeDensity(lattice), "density", (T)1.0); vtkOut.writeData<3,float>(*computeVelocity(lattice), "velocity", dx/dt); vtkOut.writeData<3,float>(*computeVorticity(*computeVelocity(lattice)), "vorticity", 1./dt); } void readParameters(XMLreader const& document) { document["geometry"]["Resolution"].read(Resolution); document["geometry"]["Viscosity"].read(Viscosity); document["geometry"]["x_length"].read(x_length); document["geometry"]["y_length"].read(y_length); document["geometry"]["z_length"].read(z_length); document["fluid"]["Shear_flag"].read(Shear_flag); document["fluid"]["Shear_Top_Velocity"].read(Shear_Top_Velocity); document["fluid"]["Shear_Bot_Velocity"].read(Shear_Bot_Velocity); document["fluid"]["Poiseuille_flag"].read(Poiseuille_flag); document["fluid"]["Poiseuille_bodyforce"].read(Poiseuille_bodyforce); document["fluid"]["Uniform_flag"].read(Uniform_flag); document["fluid"]["U_uniform"].read(U_uniform); document["simulation"]["Total_timestep"].read(Total_timestep); document["simulation"]["Output_fluid_file"].read(Output_fluid_file); document["simulation"]["Output_check_file"].read(Output_check_file); document["simulation"]["CouplingType"].read(CouplingType); } int main(int argc, char* argv[]) { plbInit(&argc, &argv); global::directories().setOutputDir("./tmp/"); //read parameters from external file string paramXmlFileName; paramXmlFileName = "param.xml"; XMLreader document(paramXmlFileName); readParameters(paramXmlFileName); ReynoldsNumber = 1.0/Viscosity; IncomprFlowParam<T> parameters( 1., 1., ReynoldsNumber, Resolution, Resolution, x_length, // lx y_length, // ly z_length // lz ); writeLogFile(parameters, "Flow conditions"); LammpsWrapper wrapper(argv,global::mpi().getGlobalCommunicator()); char * inlmp = argv[1]; wrapper.execFile(inlmp); //MultiTensorField3D<T,3> vel(parameters.getNx(),parameters.getNy(),parameters.getNz()); pcout<<"Nx,Ny,Nz "<<parameters.getNx()<<" "<<parameters.getNy()<<" "<<parameters.getNz()<<endl; LatticeDecomposition lDec(parameters.getNx(),parameters.getNy(),parameters.getNz(), wrapper.lmp); SparseBlockStructure3D blockStructure = lDec.getBlockDistribution(); ExplicitThreadAttribution* threadAttribution = lDec.getThreadAttribution(); plint envelopeWidth = 2; MultiBlockLattice3D<T, DESCRIPTOR> lattice (MultiBlockManagement3D (blockStructure, threadAttribution, envelopeWidth ), defaultMultiBlockPolicy3D().getBlockCommunicator(), defaultMultiBlockPolicy3D().getCombinedStatistics(), defaultMultiBlockPolicy3D().getMultiCellAccess<T,DESCRIPTOR>(), new DYNAMICS ); //Cell<T,DESCRIPTOR> &cell = lattice.get(550,5500,550); pcout<<"dx "<<parameters.getDeltaX()<<" dt "<<parameters.getDeltaT()<<" tau "<<parameters.getTau()<<endl; //pcout<<"51 works"<<endl; // set periodic boundary conditions. if (Shear_flag == 1){ lattice.periodicity().toggle(0,true); lattice.periodicity().toggle(1,true); } if(Poiseuille_flag == 1){ lattice.periodicity().toggle(1,true); } OnLatticeBoundaryCondition3D<T,DESCRIPTOR>* boundaryCondition = createLocalBoundaryCondition3D<T,DESCRIPTOR>(); if (Poiseuille_flag == 1) squarePoiseuilleSetup(lattice, parameters, *boundaryCondition); //poiseuille flow boundary condition if (Shear_flag == 1) bishearSetup(lattice, parameters, *boundaryCondition); //bi-shear flow boundary condition if (Uniform_flag == 1) uniformSetup(lattice, parameters, *boundaryCondition); // Loop over main time iteration. util::ValueTracer<T> converge(parameters.getLatticeU(),parameters.getResolution(),1.0e-3); //coupling between lammps and palabos /* for (plint iT=0;iT<4e3;iT++){ //warm up lattice.collideAndStream(); } */ T timeduration = T(); global::timer("mainloop").start(); writeVTK(lattice, parameters, 0); for (plint iT=0; iT<Total_timestep+1; ++iT) { if (iT%Output_fluid_file ==0 && iT >0){ pcout<<"Saving VTK file..."<<endl; writeVTK(lattice, parameters, iT); } if (iT%Output_check_file ==0 && iT >0){ pcout<<"Timestep "<<iT<<" Saving checkPoint file..."<<endl; saveBinaryBlock(lattice,"checkpoint.dat"); } // lammps to calculate force wrapper.execCommand("run 1 pre no post no"); // Clear and spread fluid force if (Shear_flag == 1){ Array<T,3> force(0,0.,0); setExternalVector(lattice,lattice.getBoundingBox(),DESCRIPTOR<T>::ExternalField::forceBeginsAt,force); } if (Poiseuille_flag == 1){ Array<T,3> force(0,Poiseuille_bodyforce,0); setExternalVector(lattice,lattice.getBoundingBox(),DESCRIPTOR<T>::ExternalField::forceBeginsAt,force); } if (CouplingType == 1){ //-----classical ibm coupling-------------// spreadForce3D_fix(lattice,wrapper); ////// Lattice Boltzmann iteration step. //interpolateVelocity3D_fix(lattice,wrapper); lattice.collideAndStream(); //Interpolate and update solid position interpolateVelocity3D_fix(lattice,wrapper); } else { //-----force FSI ibm coupling-------------// forceCoupling3D(lattice,wrapper); lattice.collideAndStream(); } } timeduration = global::timer("mainloop").stop(); pcout<<"total execution time "<<timeduration<<endl; delete boundaryCondition; }
14,456
C++
.cpp
310
40.83871
122
0.686989
huilinye/OpenFSI
31
20
6
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,026
lammpsWrapper.h
huilinye_OpenFSI/src/lammps_palabos_coupling/lammpsWrapper.h
#ifndef LAMMPS_WRAPPER_H #define LAMMPS_WRAPPER_H //#include "palabos3D.h" //#include "palabos3D.hh" // necessary LAMMPS includes #include "mpi.h" #include "lammps.h" #include "input.h" #include "library.h" class LammpsWrapper { public: LammpsWrapper(char **argv, MPI_Comm communicator); //LammpsWrapper(int narg, char **argv, MPI_Comm communicator); void execFile(char* const fname); void execCommand(std::stringstream const &cmd); void execCommand(char* const cmd); //void run(plb::plint nSteps); //void runUpto(plb::plint nSteps); void run(long int nSteps); void runUpto(long int nSteps); int getNumParticles(); void setVariable(char const *name, double value); void setVariable(char const *name, std::string &value); //private: LAMMPS_NS::LAMMPS *lmp; //LAMMPS_NS::LAMMPS **lmp; //int n; }; #include "lammpsWrapper.hh" #endif /* LAMMPS_WRAPPER_H */
890
C++
.h
30
27.433333
64
0.734503
huilinye/OpenFSI
31
20
6
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,028
latticeDecomposition.h
huilinye_OpenFSI/src/lammps_palabos_coupling/latticeDecomposition.h
/* * This file is part of the OpenFSI software. * * OpenFSI 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, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * This file is written based on the DEMCoupling in LIGGGHTS by the * author Philippe Seil (philippe.seil@jku.at) 2014 Johannes Kepler University Linz * * Copyright 2020 University of Connecticut * * Author: Huilin Ye (huilin.ye@uconn.edu) */ #ifndef LATTICE_DECOMPOSITION_H #define LATTICE_DECOMPOSITION_H #include "mpi.h" #include "lammps.h" namespace plb{ class LatticeDecomposition { public: LatticeDecomposition(plb::plint nx_, plb::plint ny_, plb::plint nz_, LAMMPS_NS::LAMMPS *lmp_); ~LatticeDecomposition(); plb::SparseBlockStructure3D getBlockDistribution(); plb::ExplicitThreadAttribution* getThreadAttribution(); private: plb::plint nx,ny,nz; LAMMPS_NS::LAMMPS &lmp; plb::plint npx,npy,npz; std::vector<plb::plint> xVal, yVal, zVal; plb::SparseBlockStructure3D *blockStructure; plb::ExplicitThreadAttribution *threadAttribution; }; }; #include "latticeDecomposition.hh" #endif /* LATTICE_DECOMPOSITION_H */
1,587
C++
.h
44
33.886364
96
0.769733
huilinye/OpenFSI
31
20
6
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,029
latticeDecomposition2D.h
huilinye_OpenFSI/src/lammps_palabos_coupling/latticeDecomposition2D.h
/* * This file is part of the OpenFSI package. * * OpenFSI is free package: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2019 Huilin Ye University of Connecticut * * Author: Huilin Ye (huilin.ye@uconn.edu) * Note: This file is written based on lattice decomposition from LIGGGHTS parallelization */ #ifndef LATTICE_DECOMPOSITION2D_H #define LATTICE_DECOMPOSITION2D_H #include "mpi.h" #include "lammps.h" namespace plb{ class LatticeDecomposition2D { public: LatticeDecomposition2D(plb::plint nx_, plb::plint ny_,plb::plint nz_, LAMMPS_NS::LAMMPS *lmp_); ~LatticeDecomposition2D(); plb::SparseBlockStructure2D getBlockDistribution(); plb::ExplicitThreadAttribution* getThreadAttribution(); private: plb::plint nx,ny,nz; LAMMPS_NS::LAMMPS &lmp; plb::plint npx,npy,npz; std::vector<plb::plint> xVal, yVal,zVal; plb::SparseBlockStructure2D *blockStructure; plb::ExplicitThreadAttribution *threadAttribution; }; }; #include "latticeDecomposition2D.hh" #endif /* LATTICE_DECOMPOSITION2D_H */
1,542
C++
.h
42
34.547619
97
0.775168
huilinye/OpenFSI
31
20
6
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,031
improper_octa.h
huilinye_OpenFSI/src/structure_potential/improper_octa.h
/* -*- c++ -*- ---------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ #ifdef IMPROPER_CLASS ImproperStyle(octa,ImproperOcta) #else #ifndef LMP_IMPROPER_OCTA_H #define LMP_IMPROPER_OCTA_H #include <stdio.h> #include "improper.h" namespace LAMMPS_NS { class ImproperOcta : public Improper { public: ImproperOcta(class LAMMPS *); virtual ~ImproperOcta(); virtual void compute(int, int); virtual void coeff(int, char **); void write_restart(FILE *); void read_restart(FILE *); void write_data(FILE *); protected: double *mu,*lamda,*v0; int *ele5,*ele6,*ele7,*ele8; virtual void allocate(); private: double kab[8][8]; int nc[8][8]; }; } #endif #endif /* ERROR/WARNING messages: W: Improper problem: %d %ld %d %d %d %d Conformation of the 4 listed improper atoms is extreme; you may want to check your simulation geometry. E: Incorrect args for improper coefficients Self-explanatory. Check the input script or data file. */
1,521
C++
.h
45
31.244444
76
0.686598
huilinye/OpenFSI
31
20
6
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,034
improper_neohookean.h
huilinye_OpenFSI/src/structure_potential/improper_neohookean.h
/* -*- c++ -*- ---------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ #ifdef IMPROPER_CLASS ImproperStyle(neohookean,ImproperNeohookean) #else #ifndef LMP_IMPROPER_NEOHOOKEAN_H #define LMP_IMPROPER_NEOHOOKEAN_H #include <stdio.h> #include "improper.h" namespace LAMMPS_NS { class ImproperNeohookean : public Improper { public: ImproperNeohookean(class LAMMPS *); virtual ~ImproperNeohookean(); virtual void compute(int, int); virtual void coeff(int, char **); void write_restart(FILE *); void read_restart(FILE *); void write_data(FILE *); protected: double *k1,*k2,*chi; virtual void allocate(); }; } #endif #endif /* ERROR/WARNING messages: W: Improper problem: %d %ld %d %d %d %d Conformation of the 4 listed improper atoms is extreme; you may want to check your simulation geometry. E: Incorrect args for improper coefficients Self-explanatory. Check the input script or data file. */
1,484
C++
.h
41
33.658537
76
0.698736
huilinye/OpenFSI
31
20
6
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,040
ibm2D.h
huilinye_OpenFSI/src/IB_interface/ibm2D.h
#ifndef IBM_LBM_2D_H #define IBM_LBM_2D_H #include "lammpsWrapper.h" namespace plb { template<typename T, template<typename U> class Descriptor> void interpolateVelocity2D_fix(MultiBlockLattice2D<T,Descriptor> &lattice, LammpsWrapper &wrapper, plint StaticAtomType); template<typename T, template<typename U> class Descriptor> void spreadForce2D_fix(MultiBlockLattice2D<T,Descriptor> &lattice, LammpsWrapper &wrapper, plint StaticAtomType); template<typename T, template<typename U> class Descriptor> void forceCoupling2D(MultiBlockLattice2D<T,Descriptor> &lattice, LammpsWrapper &wrapper); }; /* namespace plb */ #include "ibm2D.hh" #endif
778
C++
.h
16
39.0625
76
0.719054
huilinye/OpenFSI
31
20
6
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,041
ibm3D.hh
huilinye_OpenFSI/src/IB_interface/ibm3D.hh
/* * This file is part of the OpenFSI package. * * OpenFSI is free package: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2019 Huilin Ye University of Connecticut * * Author: Huilin Ye (huilin.ye@uconn.edu) * Note: This file is written based on Jifu Tan(https://github.com/TJFord/palabos-lammps). */ #ifndef IBM_LBM_3D_HH #define IBM_LBM_3D_HH #include "atom.h" #include "modify.h" #include "fix.h" #include "fix_fcm.h" #include "update.h" #include <algorithm> namespace plb { template<typename T> void weight(T r, std::vector<T> & w){ T q = sqrt(1 + 4*r*(1-r)); w[0] = (3 - 2*r - q)/8.0; w[1] = (3 - 2*r + q)/8.0; w[2] = (1 + 2*r + q)/8.0; w[3] = (1 + 2*r - q)/8.0; } template<typename T> T phi2(T r){ r = fabs(r); r = 1.0 - r; if (r>0.0) return r; else return 0.0; } //****************************** // interpolation velocity //****************************** template<typename T, template<typename U> class Descriptor> class Interpolation3D: public BoxProcessingFunctional3D_L<T,Descriptor>{ public: Interpolation3D(LammpsWrapper &wrapper_):wrapper(wrapper_){ dt = wrapper.lmp->update->dt; } virtual void process(Box3D domain, BlockLattice3D<T,Descriptor> &lattice){ Dot3D offset = lattice.getLocation(); TensorField3D<T,Descriptor<T>::d> velocity(lattice.getNx(),lattice.getNy(),lattice.getNz()); plint xl,yl,zl,ix,iy,iz,ii,jj,kk; T rx,ry,rz,wgt,rho; Array<T,3> us(0.,0.,0.); Array<T,3> uf; T **x = wrapper.lmp->atom->x; T **v = wrapper.lmp->atom->v; int *mask = wrapper.lmp->atom->mask; plint nlocal = wrapper.lmp->atom->nlocal; std::vector<T> wx(4,0.0),wy(4,0.0),wz(4,0.0); plint env = 2; for(ix=domain.x0-env;ix<=domain.x1+env;ix++) for(iy=domain.y0-env;iy<=domain.y1+env;iy++) for(iz=domain.z0-env;iz<=domain.z1+env;iz++){ lattice.get(ix,iy,iz).computeVelocity(velocity.get(ix,iy,iz)); } for (plint iS=0; iS<nlocal; iS++){ if (mask[iS] ){ xl = floor(x[iS][0]); yl = floor(x[iS][1]); zl = floor(x[iS][2]); rx = x[iS][0] - xl; ry = x[iS][1] - yl; rz = x[iS][2] - zl; weight<T>(rx,wx); weight<T>(ry,wy); weight<T>(rz,wz); us[0] = us[1] = us[2]=0.0; rho = 0.0; for (ii=0;ii<4;ii++ ) for (jj=0;jj<4;jj++ ) for (kk=0;kk<4;kk++ ){ ix = xl-1 + ii - offset.x ; iy = yl-1 + jj - offset.y ; iz = zl-1 + kk - offset.z ; if (ix > domain.x1+2 || ix < domain.x0-2) continue; if (iy > domain.y1+2 || iy < domain.y0-2) continue; if (iz > domain.z1+2 || iz < domain.z0-2) continue; uf = velocity.get(ix,iy,iz); Cell<T,Descriptor>& cell = lattice.get(ix,iy,iz); T *bodyforce=cell.getExternal(Descriptor<T>::ExternalField::forceBeginsAt); wgt = wx[ii]*wy[jj]*wz[kk]; us[0] += wgt*(uf[0] + 0.5*bodyforce[0]/lattice.get(ix,iy,iz).computeDensity()); //update velocity us[1] += wgt*(uf[1] + 0.5*bodyforce[1]/lattice.get(ix,iy,iz).computeDensity()); us[2] += wgt*(uf[2] + 0.5*bodyforce[2]/lattice.get(ix,iy,iz).computeDensity()); rho += wgt*lattice.get(ix,iy,iz).computeDensity(); } v[iS][0]=us[0]; v[iS][1]=us[1]; v[iS][2]=us[2]; //Euler method to update position x[iS][0] += v[iS][0]*dt; x[iS][1] += v[iS][1]*dt; x[iS][2] += v[iS][2]*dt; } } } virtual Interpolation3D<T,Descriptor> * clone() const{ return new Interpolation3D(*this); } void getTypeOfModification(std::vector<modif::ModifT> & modified) const { modified[0]=modif::nothing; } virtual BlockDomain::DomainT appliesTo() const{ return BlockDomain::bulk; } private: LammpsWrapper &wrapper; T dt; }; template<typename T, template<typename U> class Descriptor> void interpolateVelocity3D(MultiBlockLattice3D<T,Descriptor> &lattice, LammpsWrapper &wrapper) { applyProcessingFunctional(new Interpolation3D<T,Descriptor>(wrapper), lattice.getBoundingBox(),lattice); } //***************************** // interpolation velocity ends //***************************** //****************************** // interpolation velocity //****************************** template<typename T, template<typename U> class Descriptor> class Interpolation3D_fix: public BoxProcessingFunctional3D_L<T,Descriptor>{ public: Interpolation3D_fix(LammpsWrapper &wrapper_):wrapper(wrapper_){ dt = wrapper.lmp->update->dt; } virtual void process(Box3D domain, BlockLattice3D<T,Descriptor> &lattice){ Dot3D offset = lattice.getLocation(); TensorField3D<T,Descriptor<T>::d> velocity(lattice.getNx(),lattice.getNy(),lattice.getNz()); //plint xl,yl,zl,ix,iy,iz,ii,jj,kk; //T rx,ry,rz,wgt,rho; Array<T,3> us(0.,0.,0.); Array<T,3> uf; T **x = wrapper.lmp->atom->x; T **v = wrapper.lmp->atom->v; int *mask = wrapper.lmp->atom->mask; plint nlocal = wrapper.lmp->atom->nlocal; //std::vector<T> wx(4,0.0),wy(4,0.0),wz(4,0.0); plint ix,iy,iz; plint ixp,iyp,izp; T dx1,dy1,dz1; plint isten,ii,jj,kk; T r,rsq,weightx,weighty,weightz; T Ffp[64]; //int k; //double unode[3]; plint env = 2; for(ix=domain.x0-env;ix<=domain.x1+env;ix++) for(iy=domain.y0-env;iy<=domain.y1+env;iy++) for(iz=domain.z0-env;iz<=domain.z1+env;iz++){ lattice.get(ix,iy,iz).computeVelocity(velocity.get(ix,iy,iz)); } for (plint iS=0; iS<nlocal; iS++){ if(mask[iS] ){ us[0] = us[1] = us[2]=0.0; ix = (int)ceil(x[iS][0]-offset.x); iy = (int)ceil(x[iS][1]-offset.y); iz = (int)ceil(x[iS][2]-offset.z); dx1 = x[iS][0] - offset.x -ix + 1.0; dy1 = x[iS][1] - offset.y -iy + 1.0; dz1 = x[iS][2] - offset.z -iz + 1.0; isten = 0; for (ii=-1;ii<3;ii++ ){ rsq = (-dx1+ii)*(-dx1+ii); if(rsq>=4) weightx=0.0; else{ r=sqrt(rsq); if(rsq>1){ weightx=(5.0-2.0*r-sqrt(-7.0+12.0*r-4.0*rsq))/8.; } else{ weightx=(3.0-2.0*r+sqrt(1.0+4.0*r-4.0*rsq))/8.; } } for(jj=-1; jj<3; jj++){ rsq=(-dy1+jj)*(-dy1+jj); if(rsq>=4) weighty=0.0; else{ r=sqrt(rsq); if(rsq>1){ weighty=(5.0-2.0*r-sqrt(-7.0+12.0*r-4.0*rsq))/8.; } else{ weighty=(3.0-2.0*r+sqrt(1.0+4.0*r-4.0*rsq))/8.; } } for(kk=-1; kk<3; kk++){ rsq=(-dz1+kk)*(-dz1+kk); if(rsq>=4) weightz=0.0; else{ r=sqrt(rsq); if(rsq>1){ weightz=(5.0-2.0*r-sqrt(-7.0+12.0*r-4.0*rsq))/8.; } else{ weightz=(3.0-2.0*r+sqrt(1.0+4.0*r-4.0*rsq))/8.; } } ixp = ix+ii; iyp = iy+jj; izp = iz+kk; if(ixp<domain.x0-env || ixp>domain.x1+env) continue;//ixp = domain.x1+2; if(iyp<domain.y0-env || iyp>domain.y1+env) continue;//iyp = domain.y1+2; if(izp<domain.z0-env || izp>domain.z1+env) continue;//izp = domain.z1+2; Ffp[isten] = weightx*weighty*weightz; //std::cout<<" Ffp "<<isten <<" value "<<Ffp[isten]<<std::endl; int shift = 0; uf = velocity.get(ixp+shift,iyp+shift,izp+shift); Cell<T,Descriptor>& cell = lattice.get(ixp+shift,iyp+shift,izp+shift); T *bodyforce=cell.getExternal(Descriptor<T>::ExternalField::forceBeginsAt); us[0] += Ffp[isten]*(uf[0] + 0.5*bodyforce[0]/lattice.get(ixp,iyp,izp).computeDensity()); //update velocity us[1] += Ffp[isten]*(uf[1] + 0.5*bodyforce[1]/lattice.get(ixp,iyp,izp).computeDensity()); us[2] += Ffp[isten]*(uf[2] + 0.5*bodyforce[2]/lattice.get(ixp,iyp,izp).computeDensity()); isten++; //rho += wgt*lattice.get(ix,iy,iz).computeDensity(); } } } v[iS][0]=us[0]; v[iS][1]=us[1]; v[iS][2]=us[2]; //std::cout<<" usx "<<us[0] <<" usy "<<us[1]<<" usz "<<us[2]<<std::endl; //Euler method to update position x[iS][0] += v[iS][0]*dt; x[iS][1] += v[iS][1]*dt; x[iS][2] += v[iS][2]*dt; } } } virtual Interpolation3D_fix<T,Descriptor> * clone() const{ return new Interpolation3D_fix(*this); } void getTypeOfModification(std::vector<modif::ModifT> & modified) const { modified[0]=modif::nothing; } virtual BlockDomain::DomainT appliesTo() const{ return BlockDomain::bulk; } private: LammpsWrapper &wrapper; T dt; }; template<typename T, template<typename U> class Descriptor> void interpolateVelocity3D_fix(MultiBlockLattice3D<T,Descriptor> &lattice, LammpsWrapper &wrapper) { applyProcessingFunctional(new Interpolation3D_fix<T,Descriptor>(wrapper), lattice.getBoundingBox(),lattice); } //***************************** // interpolation velocity ends //***************************** //****************************** // interpolation velocity //****************************** template<typename T, template<typename U> class Descriptor> class Interpolation3D_fix2: public BoxProcessingFunctional3D_L<T,Descriptor>{ public: Interpolation3D_fix2(LammpsWrapper &wrapper_):wrapper(wrapper_){ dt = wrapper.lmp->update->dt; } virtual void process(Box3D domain, BlockLattice3D<T,Descriptor> &lattice){ Dot3D offset = lattice.getLocation(); TensorField3D<T,Descriptor<T>::d> velocity(lattice.getNx(),lattice.getNy(),lattice.getNz()); //plint xl,yl,zl,ix,iy,iz,ii,jj,kk; //T rx,ry,rz,wgt,rho; //Array<T,3> uf; Array<T,3> ufp[8]; Array<T,3> us(0.,0.,0.); //T ufp[8][3]; T **x = wrapper.lmp->atom->x; T **v = wrapper.lmp->atom->v; int *mask = wrapper.lmp->atom->mask; plint nlocal = wrapper.lmp->atom->nlocal; //std::vector<T> wx(4,0.0),wy(4,0.0),wz(4,0.0); plint ix,iy,iz; plint ixp,iyp,izp; T dx1,dy1,dz1; plint isten,ii,jj,k; T r,rsq,weightx,weighty,weightz; T FfP[8]; //int k; //double unode[3]; plint env = 2; for(ix=domain.x0-env;ix<=domain.x1+env;ix++) for(iy=domain.y0-env;iy<=domain.y1+env;iy++) for(iz=domain.z0-env;iz<=domain.z1+env;iz++){ lattice.get(ix,iy,iz).computeVelocity(velocity.get(ix,iy,iz)); } for (plint iS=0; iS<nlocal; iS++){ if(mask[iS] ){ ix = (int)ceil(x[iS][0]-offset.x); iy = (int)ceil(x[iS][1]-offset.y); iz = (int)ceil(x[iS][2]-offset.z); dx1 = x[iS][0] - offset.x -ix + 1.0; dy1 = x[iS][1] - offset.y -iy + 1.0; dz1 = x[iS][2] - offset.z -iz + 1.0; //-------------------------------------------------------------------------- // Calculate the interpolation weights //-------------------------------------------------------------------------- FfP[0] = (1.-dx1)*(1.-dy1)*(1.-dz1); FfP[1] = (1.-dx1)*(1.-dy1)*dz1; FfP[2] = (1.-dx1)*dy1*(1.-dz1); FfP[3] = (1.-dx1)*dy1*dz1; FfP[4] = dx1*(1.-dy1)*(1.-dz1); FfP[5] = dx1*(1.-dy1)*dz1; FfP[6] = dx1*dy1*(1.-dz1); FfP[7] = dx1*dy1*dz1; ixp = ix+1; iyp = iy+1; izp = iz+1; if(ixp<domain.x0-2 || ixp>domain.x1+2 ) continue;//ixp = domain.x1+2; if(iyp<domain.y0-2 || iyp>domain.y1+2) continue;//iyp = domain.y1+2; if(izp<domain.z0-2 || izp>domain.z1+2) continue;//izp = domain.z1+2; //extract velocity ufp[0] = velocity.get(ix,iy,iz); ufp[1] = velocity.get(ix,iy,izp); ufp[2] = velocity.get(ix,iyp,iz); ufp[3] = velocity.get(ix,iyp,izp); ufp[4] = velocity.get(ixp,iy,iz); ufp[5] = velocity.get(ixp,iy,izp); ufp[6] = velocity.get(ixp,iyp,iz); ufp[7] = velocity.get(ixp,iyp,izp); // extract bodyforce //T * //Cell<T,Descriptor>& cell = lattice.get(ixp+shift,iyp+shift,izp+shift); // T *bodyforce=cell.getExternal(Descriptor<T>::ExternalField::forceBeginsAt); T *bodyforce0,*bodyforce1,*bodyforce2,*bodyforce3,*bodyforce4,*bodyforce5,*bodyforce6,*bodyforce7; Cell<T,Descriptor>& cell0 = lattice.get(ix,iy,iz); bodyforce0=cell0.getExternal(Descriptor<T>::ExternalField::forceBeginsAt); Cell<T,Descriptor>& cell1 = lattice.get(ix,iy,izp); bodyforce1=cell1.getExternal(Descriptor<T>::ExternalField::forceBeginsAt); Cell<T,Descriptor>& cell2 = lattice.get(ix,iyp,iz); bodyforce2=cell2.getExternal(Descriptor<T>::ExternalField::forceBeginsAt); Cell<T,Descriptor>& cell3 = lattice.get(ix,iyp,izp); bodyforce3=cell3.getExternal(Descriptor<T>::ExternalField::forceBeginsAt); Cell<T,Descriptor>& cell4 = lattice.get(ixp,iy,iz); bodyforce4=cell4.getExternal(Descriptor<T>::ExternalField::forceBeginsAt); Cell<T,Descriptor>& cell5 = lattice.get(ixp,iy,izp); bodyforce5=cell5.getExternal(Descriptor<T>::ExternalField::forceBeginsAt); Cell<T,Descriptor>& cell6 = lattice.get(ixp,iyp,iz); bodyforce6=cell6.getExternal(Descriptor<T>::ExternalField::forceBeginsAt); Cell<T,Descriptor>& cell7 = lattice.get(ixp,iyp,izp); bodyforce7=cell7.getExternal(Descriptor<T>::ExternalField::forceBeginsAt); //wgt = wx[ii]*wy[jj]*wz[kk]; //std::cout<<" bodyforcex "<<bodyforce[0] <<" bodyforcey "<<bodyforce[1]<<" bodyforcez "<<bodyforce[2]<<std::endl; //std::cout<<" ufx "<<uf[0] <<" ufy "<<uf[1]<<" ufz "<<uf[2]<<std::endl; for (k=0; k<3; k++){ //us[0] += Ffp[isten]*(uf[0] + 0.5*bodyforce[0]/lattice.get(ixp,iyp,izp).computeDensity()); //update velocity us[k] = (ufp[0][k] + 0.5*bodyforce0[k]/lattice.get(ix,iy,iz).computeDensity())*FfP[0] + (ufp[1][k] + 0.5*bodyforce1[k]/lattice.get(ix,iy,izp).computeDensity())*FfP[1] + (ufp[2][k] + 0.5*bodyforce2[k]/lattice.get(ix,iyp,iz).computeDensity())*FfP[2] + (ufp[3][k] + 0.5*bodyforce3[k]/lattice.get(ix,iyp,izp).computeDensity())*FfP[3] + (ufp[4][k] + 0.5*bodyforce4[k]/lattice.get(ixp,iy,iz).computeDensity())*FfP[4] + (ufp[5][k] + 0.5*bodyforce5[k]/lattice.get(ixp,iy,izp).computeDensity())*FfP[5] + (ufp[6][k] + 0.5*bodyforce6[k]/lattice.get(ixp,iyp,iz).computeDensity())*FfP[6] + (ufp[7][k] + 0.5*bodyforce7[k]/lattice.get(ixp,iyp,izp).computeDensity())*FfP[7]; } v[iS][0]=us[0]; v[iS][1]=us[1]; v[iS][2]=us[2]; //std::cout<<" usx "<<us[0] <<" usy "<<us[1]<<" usz "<<us[2]<<std::endl; //Euler method to update position x[iS][0] += v[iS][0]*dt; x[iS][1] += v[iS][1]*dt; x[iS][2] += v[iS][2]*dt; } } } virtual Interpolation3D_fix2<T,Descriptor> * clone() const{ return new Interpolation3D_fix2(*this); } void getTypeOfModification(std::vector<modif::ModifT> & modified) const { modified[0]=modif::nothing; } virtual BlockDomain::DomainT appliesTo() const{ return BlockDomain::bulk; } private: LammpsWrapper &wrapper; T dt; }; template<typename T, template<typename U> class Descriptor> void interpolateVelocity3D_fix2(MultiBlockLattice3D<T,Descriptor> &lattice, LammpsWrapper &wrapper) { //plint envelopeWidth = 3; //applyProcessingFunctional(new Interpolation3D_fix<T,Descriptor>(wrapper), lattice.getBoundingBox(),lattice, envelopeWidth); applyProcessingFunctional(new Interpolation3D_fix2<T,Descriptor>(wrapper), lattice.getBoundingBox(),lattice); } //***************************** // interpolation velocity ends //***************************** //********************************* //spreding fsi force to fluid nodes //********************************* template<typename T, template<typename U> class Descriptor> class Spreading3D: public BoxProcessingFunctional3D_L<T,Descriptor>{ public: Spreading3D(LammpsWrapper &wrapper_):wrapper(wrapper_){ } virtual void process(Box3D domain, BlockLattice3D<T,Descriptor> &lattice){ Dot3D offset = lattice.getLocation(); plint xl,yl,zl,ix,iy,iz,ii,jj,kk; T rx,ry,rz,wgt; //Array<T,3> ff(0.,0.,0.); T **x = wrapper.lmp->atom->x; T **f = wrapper.lmp->atom->f; int *mask = wrapper.lmp->atom->mask; plint nlocal = wrapper.lmp->atom->nlocal; std::vector<T> wx(4,0.0),wy(4,0.0),wz(4,0.0); for (plint iS=0; iS<nlocal; iS++){ if(mask[iS] ){ xl = floor(x[iS][0]); yl = floor(x[iS][1]); zl = floor(x[iS][2]); rx = x[iS][0] - xl; ry = x[iS][1] - yl; rz = x[iS][2] - zl; weight<T>(rx,wx); weight<T>(ry,wy); weight<T>(rz,wz); for (ii=0;ii<4;ii++ ) for (jj=0;jj<4;jj++ ) for (kk=0;kk<4;kk++ ){ ix = xl-1 + ii - offset.x ; iy = yl-1 + jj - offset.y ; iz = zl-1 + kk - offset.z ; if (ix > domain.x1+2 || ix < domain.x0-2) continue; if (iy > domain.y1+2 || iy < domain.y0-2) continue; if (iz > domain.z1+2 || iz < domain.z0-2) continue; //if ( ix == domain.x0-3) ix = ix+1; //ensure the interpolation nodes locate within subprocessor //if ( iy == domain.y0-3) iy = iy+1; //if ( iz == domain.z0-3) iz = iz+1; Cell<T,Descriptor>& cell = lattice.get(ix,iy,iz); T *ff=cell.getExternal(Descriptor<T>::ExternalField::forceBeginsAt); wgt = wx[ii]*wy[jj]*wz[kk]; ff[0] += wgt*f[iS][0]; ff[1] += wgt*f[iS][1]; ff[2] += wgt*f[iS][2]; cell.setExternalField(Descriptor<T>::ExternalField::forceBeginsAt,Descriptor<T>::ExternalField::sizeOfForce,ff ); } }//mask[iS] } } virtual Spreading3D<T,Descriptor> * clone() const{ return new Spreading3D(*this); } void getTypeOfModification(std::vector<modif::ModifT> & modified) const { modified[0]=modif::staticVariables; } virtual BlockDomain::DomainT appliesTo() const{ return BlockDomain::bulk; } private: LammpsWrapper &wrapper; }; template<typename T, template<typename U> class Descriptor> void spreadForce3D(MultiBlockLattice3D<T,Descriptor> &lattice, LammpsWrapper &wrapper ){ //plint envelopeWidth = 2; applyProcessingFunctional(new Spreading3D<T,Descriptor>(wrapper), lattice.getBoundingBox(),lattice); } //********************************* //spreding force ends //********************************* //********************************* //spreding fsi force to fluid nodes using fix_lb style IB //********************************* template<typename T, template<typename U> class Descriptor> class Spreading3D_fix: public BoxProcessingFunctional3D_L<T,Descriptor>{ public: Spreading3D_fix(LammpsWrapper &wrapper_):wrapper(wrapper_){ } virtual void process(Box3D domain, BlockLattice3D<T,Descriptor> &lattice){ Dot3D offset = lattice.getLocation(); //plint xl,yl,zl,ix,iy,iz,ii,jj,kk; //T rx,ry,rz,wgt; //Array<T,3> ff(0.,0.,0.); T **x = wrapper.lmp->atom->x; T **f = wrapper.lmp->atom->f; int *mask = wrapper.lmp->atom->mask; plint nlocal = wrapper.lmp->atom->nlocal; //std::vector<T> wx(4,0.0),wy(4,0.0),wz(4,0.0); int ix,iy,iz; int ixp,iyp,izp; double dx1,dy1,dz1; int isten,ii,jj,kk; double r,rsq,weightx,weighty,weightz; double Ffp[64]; //int k; //double unode[3]; plint env =2; for (plint iS=0; iS<nlocal; iS++){ if(mask[iS] ){ ix = (int)ceil(x[iS][0]-offset.x); iy = (int)ceil(x[iS][1]-offset.y); iz = (int)ceil(x[iS][2]-offset.z); dx1 = x[iS][0] - offset.x -ix + 1.0; dy1 = x[iS][1] - offset.y -iy + 1.0; dz1 = x[iS][2] - offset.z -iz + 1.0; //unode[0] = 0.0; unode[1] = 0.0; unode[2] = 0.0; isten = 0; for (ii=-1;ii<3;ii++ ){ rsq = (-dx1+ii)*(-dx1+ii); if(rsq>=4) weightx=0.0; else{ r=sqrt(rsq); if(rsq>1){ weightx=(5.0-2.0*r-sqrt(-7.0+12.0*r-4.0*rsq))/8.; } else{ weightx=(3.0-2.0*r+sqrt(1.0+4.0*r-4.0*rsq))/8.; } } for(jj=-1; jj<3; jj++){ rsq=(-dy1+jj)*(-dy1+jj); if(rsq>=4) weighty=0.0; else{ r=sqrt(rsq); if(rsq>1){ weighty=(5.0-2.0*r-sqrt(-7.0+12.0*r-4.0*rsq))/8.; } else{ weighty=(3.0-2.0*r+sqrt(1.0+4.0*r-4.0*rsq))/8.; } } for(kk=-1; kk<3; kk++){ rsq=(-dz1+kk)*(-dz1+kk); if(rsq>=4) weightz=0.0; else{ r=sqrt(rsq); if(rsq>1){ weightz=(5.0-2.0*r-sqrt(-7.0+12.0*r-4.0*rsq))/8.; } else{ weightz=(3.0-2.0*r+sqrt(1.0+4.0*r-4.0*rsq))/8.; } } ixp = ix+ii; iyp = iy+jj; izp = iz+kk; if(ixp<domain.x0-env || ixp>domain.x1+env ) continue;//ixp = domain.x1+2; if(iyp<domain.y0-env || iyp>domain.y1+env) continue;//iyp = domain.y1+2; if(izp<domain.z0-env || izp>domain.z1+env) continue;//izp = domain.z1+2; Ffp[isten] = weightx*weighty*weightz; int shift = 0; Cell<T,Descriptor>& cell = lattice.get(ixp+shift,iyp+shift,izp+shift); T *ff=cell.getExternal(Descriptor<T>::ExternalField::forceBeginsAt); //wgt = wx[ii]*wy[jj]*wz[kk]; ff[0] += Ffp[isten]*f[iS][0]; ff[1] += Ffp[isten]*f[iS][1]; ff[2] += Ffp[isten]*f[iS][2]; cell.setExternalField(Descriptor<T>::ExternalField::forceBeginsAt,Descriptor<T>::ExternalField::sizeOfForce,ff ); isten++; } } } } } } virtual Spreading3D_fix<T,Descriptor> * clone() const{ return new Spreading3D_fix(*this); } void getTypeOfModification(std::vector<modif::ModifT> & modified) const { modified[0]=modif::staticVariables; } virtual BlockDomain::DomainT appliesTo() const{ return BlockDomain::bulk; } private: LammpsWrapper &wrapper; }; template<typename T, template<typename U> class Descriptor> void spreadForce3D_fix(MultiBlockLattice3D<T,Descriptor> &lattice, LammpsWrapper &wrapper ){ //plint envelopeWidth = 2; applyProcessingFunctional(new Spreading3D_fix<T,Descriptor>(wrapper), lattice.getBoundingBox(),lattice); } //********************************* //spreding force ends //********************************* //********************************* //spreding fsi force to fluid nodes using fix_lb style IB //********************************* template<typename T, template<typename U> class Descriptor> class Spreading3D_fix2: public BoxProcessingFunctional3D_L<T,Descriptor>{ public: Spreading3D_fix2(LammpsWrapper &wrapper_):wrapper(wrapper_){ } virtual void process(Box3D domain, BlockLattice3D<T,Descriptor> &lattice){ Dot3D offset = lattice.getLocation(); //plint xl,yl,zl,ix,iy,iz,ii,jj,kk; //T rx,ry,rz,wgt; //Array<T,3> ff(0.,0.,0.); T **x = wrapper.lmp->atom->x; T **f = wrapper.lmp->atom->f; int *mask = wrapper.lmp->atom->mask; plint nlocal = wrapper.lmp->atom->nlocal; //std::vector<T> wx(4,0.0),wy(4,0.0),wz(4,0.0); int ix,iy,iz; int ixp,iyp,izp; double dx1,dy1,dz1; int isten,ii,jj,kk; double r,rsq,weightx,weighty,weightz; double FfP[8]; int k; double unode[3]; for (plint iS=0; iS<nlocal; iS++){ if(mask[iS] ){ ix = (int)ceil(x[iS][0]-offset.x); iy = (int)ceil(x[iS][1]-offset.y); iz = (int)ceil(x[iS][2]-offset.z); dx1 = x[iS][0] - offset.x -ix + 1.0; dy1 = x[iS][1] - offset.y -iy + 1.0; dz1 = x[iS][2] - offset.z -iz + 1.0; //-------------------------------------------------------------------------- // Calculate the interpolation weights //-------------------------------------------------------------------------- FfP[0] = (1.-dx1)*(1.-dy1)*(1.-dz1); FfP[1] = (1.-dx1)*(1.-dy1)*dz1; FfP[2] = (1.-dx1)*dy1*(1.-dz1); FfP[3] = (1.-dx1)*dy1*dz1; FfP[4] = dx1*(1.-dy1)*(1.-dz1); FfP[5] = dx1*(1.-dy1)*dz1; FfP[6] = dx1*dy1*(1.-dz1); FfP[7] = dx1*dy1*dz1; ixp = ix+1; iyp = iy+1; izp = iz+1; if(ixp<domain.x0-2 || ixp>domain.x1+2 ) continue;//ixp = domain.x1+2; if(iyp<domain.y0-2 || iyp>domain.y1+2) continue;//iyp = domain.y1+2; if(izp<domain.z0-2 || izp>domain.z1+2) continue;//izp = domain.z1+2; // extract bodyforce //T * //Cell<T,Descriptor>& cell = lattice.get(ixp+shift,iyp+shift,izp+shift); // T *bodyforce=cell.getExternal(Descriptor<T>::ExternalField::forceBeginsAt); T *bodyforce0,*bodyforce1,*bodyforce2,*bodyforce3,*bodyforce4,*bodyforce5,*bodyforce6,*bodyforce7; Cell<T,Descriptor>& cell0 = lattice.get(ix,iy,iz); bodyforce0=cell0.getExternal(Descriptor<T>::ExternalField::forceBeginsAt); Cell<T,Descriptor>& cell1 = lattice.get(ix,iy,izp); bodyforce1=cell1.getExternal(Descriptor<T>::ExternalField::forceBeginsAt); Cell<T,Descriptor>& cell2 = lattice.get(ix,iyp,iz); bodyforce2=cell2.getExternal(Descriptor<T>::ExternalField::forceBeginsAt); Cell<T,Descriptor>& cell3 = lattice.get(ix,iyp,izp); bodyforce3=cell3.getExternal(Descriptor<T>::ExternalField::forceBeginsAt); Cell<T,Descriptor>& cell4 = lattice.get(ixp,iy,iz); bodyforce4=cell4.getExternal(Descriptor<T>::ExternalField::forceBeginsAt); Cell<T,Descriptor>& cell5 = lattice.get(ixp,iy,izp); bodyforce5=cell5.getExternal(Descriptor<T>::ExternalField::forceBeginsAt); Cell<T,Descriptor>& cell6 = lattice.get(ixp,iyp,iz); bodyforce6=cell6.getExternal(Descriptor<T>::ExternalField::forceBeginsAt); Cell<T,Descriptor>& cell7 = lattice.get(ixp,iyp,izp); bodyforce7=cell7.getExternal(Descriptor<T>::ExternalField::forceBeginsAt); for(k=0;k<3;k++){ bodyforce0[k] += FfP[0]*f[iS][k]; bodyforce1[k] += FfP[1]*f[iS][k]; bodyforce2[k] += FfP[2]*f[iS][k]; bodyforce3[k] += FfP[3]*f[iS][k]; bodyforce4[k] += FfP[4]*f[iS][k]; bodyforce5[k] += FfP[5]*f[iS][k]; bodyforce6[k] += FfP[6]*f[iS][k]; bodyforce7[k] += FfP[7]*f[iS][k]; } cell0.setExternalField(Descriptor<T>::ExternalField::forceBeginsAt,Descriptor<T>::ExternalField::sizeOfForce,bodyforce0 ); cell1.setExternalField(Descriptor<T>::ExternalField::forceBeginsAt,Descriptor<T>::ExternalField::sizeOfForce,bodyforce1 ); cell2.setExternalField(Descriptor<T>::ExternalField::forceBeginsAt,Descriptor<T>::ExternalField::sizeOfForce,bodyforce2 ); cell3.setExternalField(Descriptor<T>::ExternalField::forceBeginsAt,Descriptor<T>::ExternalField::sizeOfForce,bodyforce3 ); cell4.setExternalField(Descriptor<T>::ExternalField::forceBeginsAt,Descriptor<T>::ExternalField::sizeOfForce,bodyforce4 ); cell5.setExternalField(Descriptor<T>::ExternalField::forceBeginsAt,Descriptor<T>::ExternalField::sizeOfForce,bodyforce5 ); cell6.setExternalField(Descriptor<T>::ExternalField::forceBeginsAt,Descriptor<T>::ExternalField::sizeOfForce,bodyforce6 ); cell7.setExternalField(Descriptor<T>::ExternalField::forceBeginsAt,Descriptor<T>::ExternalField::sizeOfForce,bodyforce7 ); } } } virtual Spreading3D_fix2<T,Descriptor> * clone() const{ return new Spreading3D_fix2(*this); } void getTypeOfModification(std::vector<modif::ModifT> & modified) const { modified[0]=modif::staticVariables; } virtual BlockDomain::DomainT appliesTo() const{ return BlockDomain::bulk; } private: LammpsWrapper &wrapper; }; template<typename T, template<typename U> class Descriptor> void spreadForce3D_fix2(MultiBlockLattice3D<T,Descriptor> &lattice, LammpsWrapper &wrapper ){ //plint envelopeWidth = 2; applyProcessingFunctional(new Spreading3D_fix2<T,Descriptor>(wrapper), lattice.getBoundingBox(),lattice); } //********************************* //spreding force ends //********************************* //******************************** //force coupling //******************************** template<typename T, template<typename U> class Descriptor> class ForceFSI3D: public BoxProcessingFunctional3D_L<T,Descriptor>{ public: ForceFSI3D(LammpsWrapper &wrapper_):wrapper(wrapper_){ plint i,ifix(0),nfix; nfix = wrapper.lmp->modify->nfix; for (i=0;i<nfix;i++) if (strcmp(wrapper.lmp->modify->fix[i]->style,"fcm")==0) ifix=i; f_fcm = static_cast<LAMMPS_NS::FixFCM *>(wrapper.lmp->modify->fix[ifix]); f_fcm->grow_arrays(wrapper.lmp->atom->nmax); f_fcm->init(); groupbit = f_fcm->groupbit;//new code } virtual void process(Box3D domain, BlockLattice3D<T,Descriptor> &lattice){ Dot3D offset = lattice.getLocation(); TensorField3D<T,Descriptor<T>::d> velocity(lattice.getNx(),lattice.getNy(),lattice.getNz()); plint xl,yl,zl,ix,iy,iz,ii,jj,kk; T rx,ry,rz,wgt; T rho; Array<T,3> us(0.,0.,0.); Array<T,3> fsi(0.,0.,0.); Array<T,3> uf(0.,0.,0.); T **x = wrapper.lmp->atom->x; T **v = wrapper.lmp->atom->v; //T **f = wrapper.lmp->atom->f; T **fe = f_fcm->fexternal; T dampcoe = f_fcm->dampcoe; int ntimestep = wrapper.lmp->update->ntimestep; int *mask = wrapper.lmp->atom->mask; double invdampcoe = 1.0; invdampcoe = 1.0-exp(-ntimestep/dampcoe); //if (ntimestep < dampcoe) invdampcoe = 1.0-exp(-ntimestep/dampcoe); plint nlocal = wrapper.lmp->atom->nlocal; std::vector<T> wx(4,0.0),wy(4,0.0),wz(4,0.0); for(ix=domain.x0-2;ix<=domain.x1+2;ix++) for(iy=domain.y0-2;iy<=domain.y1+2;iy++) for(iz=domain.z0-2;iz<=domain.z1+2;iz++){ lattice.get(ix,iy,iz).computeVelocity(velocity.get(ix,iy,iz)); //density(ix,iy,iz)=lattice.get(ix,iy,iz).computeDensity(); } for (plint iS=0; iS<nlocal; iS++){ if (mask[iS] & groupbit ){ xl = floor(x[iS][0]); yl = floor(x[iS][1]); zl = floor(x[iS][2]); rx = x[iS][0] - xl; ry = x[iS][1] - yl; rz = x[iS][2] - zl; weight<T>(rx,wx); weight<T>(ry,wy); weight<T>(rz,wz); us[0] = us[1] = us[2]=0.0; rho=0.0; for (ii=0;ii<4;ii++ ) for (jj=0;jj<4;jj++ ) for (kk=0;kk<4;kk++ ){ ix = xl-1 + ii - offset.x ; iy = yl-1 + jj - offset.y ; iz = zl-1 + kk - offset.z ; if ( ix < domain.x0-2) continue; if ( iy < domain.y0-2) continue; if ( iz < domain.z0-2) continue; uf = velocity.get(ix,iy,iz); wgt = wx[ii]*wy[jj]*wz[kk]; us[0] += wgt*uf[0]; us[1] += wgt*uf[1]; us[2] += wgt*uf[2]; rho += wgt*lattice.get(ix,iy,iz).computeDensity(); } // assume rho = 1. //fsi[0]=us[0]-v[iS][0]; //Eqn.(5) in K. Aidun. Int J. Numer. Meth. Fluids 2010:62:765-783 //fsi[1]=us[1]-v[iS][1]; //fsi[2]=us[2]-v[iS][2]; // using rho value fsi[0]=rho*(us[0]-v[iS][0])*invdampcoe; //Eqn.(5) in K. Aidun. Int J. Numer. Meth. Fluids 2010:62:765-783 fsi[1]=rho*(us[1]-v[iS][1])*invdampcoe; fsi[2]=rho*(us[2]-v[iS][2])*invdampcoe; fe[iS][0] = fsi[0]; // no accumulation for external force fe[iS][1] = fsi[1]; fe[iS][2] = fsi[2]; for (ii=0;ii<4;ii++ ) for (jj=0;jj<4;jj++ ) for (kk=0;kk<4;kk++ ){ ix = xl-1 + ii - offset.x ; iy = yl-1 + jj - offset.y ; iz = zl-1 + kk - offset.z ; if (ix > domain.x1 || ix < domain.x0-2) continue; if (iy > domain.y1 || iy < domain.y0-2) continue; if (iz > domain.z1 || iz < domain.z0-2) continue; Cell<T,Descriptor>& cell = lattice.get(ix,iy,iz); T *ff=cell.getExternal(Descriptor<T>::ExternalField::forceBeginsAt); wgt = wx[ii]*wy[jj]*wz[kk]; ff[0] -= wgt*fsi[0]; ff[1] -= wgt*fsi[1]; ff[2] -= wgt*fsi[2]; cell.setExternalField(Descriptor<T>::ExternalField::forceBeginsAt,Descriptor<T>::ExternalField::sizeOfForce,ff ); } }//mask[is] } } virtual ForceFSI3D<T,Descriptor> * clone() const{ return new ForceFSI3D(*this); } void getTypeOfModification(std::vector<modif::ModifT> & modified) const { modified[0]=modif::staticVariables; } virtual BlockDomain::DomainT appliesTo() const{ return BlockDomain::bulk; } private: LammpsWrapper &wrapper; class LAMMPS_NS::FixFCM *f_fcm; plint groupbit; }; template<typename T, template<typename U> class Descriptor> void forceCoupling3D(MultiBlockLattice3D<T,Descriptor> &lattice, LammpsWrapper &wrapper) { //plint envelopeWidth = 2; //applyProcessingFunctional(new Interpolation3D<T>(wrapper), velocity.getBoundingBox(),velocity, envelopeWidth); applyProcessingFunctional(new ForceFSI3D<T,Descriptor>(wrapper), lattice.getBoundingBox(),lattice); } //********************************* // force coupling ends //********************************* }; /* namespace plb */ #endif
36,026
C++
.h
838
33.775656
131
0.555569
huilinye/OpenFSI
31
20
6
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,042
ibm2D.hh
huilinye_OpenFSI/src/IB_interface/ibm2D.hh
/* * This file is part of the OpenFSI package. * * OpenFSI is free package: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2019 Huilin Ye University of Connecticut * * Author: Huilin Ye (huilin.ye@uconn.edu) * Note: This file is written based on Jifu Tan(https://github.com/TJFord/palabos-lammps). */ #ifndef IBM_LBM_2D_HH #define IBM_LBM_2D_HH #include "atom.h" #include "modify.h" #include "group.h" #include "molecule.h" #include "fix.h" #include "fix_fcm.h" #include "update.h" #include <algorithm> #include <map> #include "pointers.h" namespace plb { template<typename T> void weight(T r, std::vector<T> & w){ T q = sqrt(1 + 4*r*(1-r)); w[0] = (3 - 2*r - q)/8.0; w[1] = (3 - 2*r + q)/8.0; w[2] = (1 + 2*r + q)/8.0; w[3] = (1 + 2*r - q)/8.0; } //****************************** // interpolation velocity //****************************** template<typename T, template<typename U> class Descriptor> class Interpolation2D_fix: public BoxProcessingFunctional2D_L<T,Descriptor>{ public: Interpolation2D_fix(LammpsWrapper &wrapper_, plint StaticAtomType_):wrapper(wrapper_), StaticAtomType(StaticAtomType_){ dt = wrapper.lmp->update->dt; } virtual void process(Box2D domain, BlockLattice2D<T,Descriptor> &lattice){ Dot2D offset = lattice.getLocation(); TensorField2D<T,Descriptor<T>::d> velocity(lattice.getNx(),lattice.getNy()); //plint xl,yl,zl,ix,iy,iz,ii,jj,kk; //T rx,ry,rz,wgt,rho; Array<T,2> us(0.,0.); Array<T,2> uf; T **x = wrapper.lmp->atom->x; T **v = wrapper.lmp->atom->v; int *mask = wrapper.lmp->atom->mask; int *type = wrapper.lmp->atom->type; plint nlocal = wrapper.lmp->atom->nlocal; //std::vector<T> wx(4,0.0),wy(4,0.0),wz(4,0.0); plint ix,iy; plint ixp,iyp; T dx1,dy1; plint isten,ii,jj; T r,rsq,weightx,weighty; T Ffp[16]; plint env = 2; for(ix=domain.x0-env;ix<=domain.x1+env;ix++) for(iy=domain.y0-env;iy<=domain.y1+env;iy++){ //for(iz=domain.z0-env;iz<=domain.z1+env;iz++) lattice.get(ix,iy).computeVelocity(velocity.get(ix,iy)); } for (plint iS=0; iS<nlocal; iS++){ //if(mask[iS] && type[iS] < MAX_TYPE){ if(mask[iS] && type[iS] != StaticAtomType){ us[0] = us[1] = 0.0; ix = (int)ceil(x[iS][0]-offset.x); iy = (int)ceil(x[iS][1]-offset.y); //iz = (int)ceil(x[iS][2]-offset.z); dx1 = x[iS][0] - offset.x -ix + 1.0; dy1 = x[iS][1] - offset.y -iy + 1.0; isten = 0; for (ii=-1;ii<3;ii++ ){ rsq = (-dx1+ii)*(-dx1+ii); if(rsq>=4) weightx=0.0; else{ r=sqrt(rsq); if(rsq>1){ weightx=(5.0-2.0*r-sqrt(-7.0+12.0*r-4.0*rsq))/8.; } else{ weightx=(3.0-2.0*r+sqrt(1.0+4.0*r-4.0*rsq))/8.; } } for(jj=-1; jj<3; jj++){ rsq=(-dy1+jj)*(-dy1+jj); if(rsq>=4) weighty=0.0; else{ r=sqrt(rsq); if(rsq>1){ weighty=(5.0-2.0*r-sqrt(-7.0+12.0*r-4.0*rsq))/8.; } else{ weighty=(3.0-2.0*r+sqrt(1.0+4.0*r-4.0*rsq))/8.; } } ixp = ix+ii; iyp = iy+jj; if(ixp<domain.x0-env || ixp>domain.x1+env) continue;//ixp = domain.x1+2; if(iyp<domain.y0-env || iyp>domain.y1+env) continue; Ffp[isten] = weightx*weighty; int shift = 0; uf = velocity.get(ixp+shift,iyp+shift); Cell<T,Descriptor>& cell = lattice.get(ixp+shift,iyp+shift); T *bodyforce=cell.getExternal(Descriptor<T>::ExternalField::forceBeginsAt); us[0] += Ffp[isten]*(uf[0] + 0.5*bodyforce[0]/lattice.get(ixp,iyp).computeDensity()); //update velocity us[1] += Ffp[isten]*(uf[1] + 0.5*bodyforce[1]/lattice.get(ixp,iyp).computeDensity()); isten++; } } v[iS][0]=us[0]; v[iS][1]=us[1]; //v[iS][2]=us[2]; //Euler method to update position x[iS][0] += v[iS][0]*dt; x[iS][1] += v[iS][1]*dt; } } } virtual Interpolation2D_fix<T,Descriptor> * clone() const{ return new Interpolation2D_fix(*this); } void getTypeOfModification(std::vector<modif::ModifT> & modified) const { modified[0]=modif::nothing; } virtual BlockDomain::DomainT appliesTo() const{ return BlockDomain::bulk; } private: LammpsWrapper &wrapper; plint StaticAtomType; T dt; }; template<typename T, template<typename U> class Descriptor> void interpolateVelocity2D_fix(MultiBlockLattice2D<T,Descriptor> &lattice, LammpsWrapper &wrapper, plint StaticAtomType) { //plint envelopeWidth = 3; //applyProcessingFunctional(new Interpolation3D_fix<T,Descriptor>(wrapper), lattice.getBoundingBox(),lattice, envelopeWidth); applyProcessingFunctional(new Interpolation2D_fix<T,Descriptor>(wrapper,StaticAtomType), lattice.getBoundingBox(),lattice); } //***************************** // interpolation velocity ends //***************************** //********************************* //spreding fsi force to fluid nodes using fix_lb style IB //********************************* template<typename T, template<typename U> class Descriptor> class Spreading2D_fix: public BoxProcessingFunctional2D_L<T,Descriptor>{ public: Spreading2D_fix(LammpsWrapper &wrapper_, plint StaticAtomType_):wrapper(wrapper_), StaticAtomType(StaticAtomType_){ } virtual void process(Box2D domain, BlockLattice2D<T,Descriptor> &lattice){ Dot2D offset = lattice.getLocation(); T **x = wrapper.lmp->atom->x; T **f = wrapper.lmp->atom->f; int *mask = wrapper.lmp->atom->mask; int *type = wrapper.lmp->atom->type; plint nlocal = wrapper.lmp->atom->nlocal; //std::vector<T> wx(4,0.0),wy(4,0.0),wz(4,0.0); int ix,iy; int ixp,iyp; double dx1,dy1; int isten,ii,jj; double r,rsq,weightx,weighty; double Ffp[16]; //int k; //double unode[3]; plint env =2; for (plint iS=0; iS<nlocal; iS++){ //if(mask[iS] && type[iS]<MAX_TYPE){ if(mask[iS] && type[iS] != StaticAtomType){ ix = (int)ceil(x[iS][0]-offset.x); iy = (int)ceil(x[iS][1]-offset.y); dx1 = x[iS][0] - offset.x -ix + 1.0; dy1 = x[iS][1] - offset.y -iy + 1.0; //dz1 = x[iS][2] - offset.z -iz + 1.0; isten = 0; for (ii=-1;ii<3;ii++ ){ rsq = (-dx1+ii)*(-dx1+ii); if(rsq>=4) weightx=0.0; else{ r=sqrt(rsq); if(rsq>1){ weightx=(5.0-2.0*r-sqrt(-7.0+12.0*r-4.0*rsq))/8.; } else{ weightx=(3.0-2.0*r+sqrt(1.0+4.0*r-4.0*rsq))/8.; } } for(jj=-1; jj<3; jj++){ rsq=(-dy1+jj)*(-dy1+jj); if(rsq>=4) weighty=0.0; else{ r=sqrt(rsq); if(rsq>1){ weighty=(5.0-2.0*r-sqrt(-7.0+12.0*r-4.0*rsq))/8.; } else{ weighty=(3.0-2.0*r+sqrt(1.0+4.0*r-4.0*rsq))/8.; } } ixp = ix+ii; iyp = iy+jj; if(ixp<domain.x0-env || ixp>domain.x1+env ) continue;//ixp = domain.x1+2; if(iyp<domain.y0-env || iyp>domain.y1+env) continue;//iyp = domain.y1+2; Ffp[isten] = weightx*weighty; int shift = 0; Cell<T,Descriptor>& cell = lattice.get(ixp+shift,iyp+shift); T *ff=cell.getExternal(Descriptor<T>::ExternalField::forceBeginsAt); ff[0] += Ffp[isten]*f[iS][0]; ff[1] += Ffp[isten]*f[iS][1]; cell.setExternalField(Descriptor<T>::ExternalField::forceBeginsAt,Descriptor<T>::ExternalField::sizeOfForce,ff ); isten++; } } } } } virtual Spreading2D_fix<T,Descriptor> * clone() const{ return new Spreading2D_fix(*this); } void getTypeOfModification(std::vector<modif::ModifT> & modified) const { modified[0]=modif::staticVariables; } virtual BlockDomain::DomainT appliesTo() const{ return BlockDomain::bulk; } private: LammpsWrapper &wrapper; plint StaticAtomType; }; template<typename T, template<typename U> class Descriptor> void spreadForce2D_fix(MultiBlockLattice2D<T,Descriptor> &lattice, LammpsWrapper &wrapper, plint StaticAtomType ){ //plint envelopeWidth = 2; applyProcessingFunctional(new Spreading2D_fix<T,Descriptor>(wrapper,StaticAtomType), lattice.getBoundingBox(),lattice); } //********************************* //spreding force ends //********************************* //******************************** //force coupling //******************************** template<typename T, template<typename U> class Descriptor> class ForceFSI2D: public BoxProcessingFunctional2D_L<T,Descriptor>{ public: ForceFSI2D(LammpsWrapper &wrapper_):wrapper(wrapper_){ plint i,ifix(0),nfix; nfix = wrapper.lmp->modify->nfix; for (i=0;i<nfix;i++) if (strcmp(wrapper.lmp->modify->fix[i]->style,"fcm")==0) ifix=i; f_fcm = static_cast<LAMMPS_NS::FixFCM *>(wrapper.lmp->modify->fix[ifix]); f_fcm->grow_arrays(wrapper.lmp->atom->nmax); f_fcm->init(); groupbit = f_fcm->groupbit;//new code dt = wrapper.lmp->update->dt; } virtual void process(Box2D domain, BlockLattice2D<T,Descriptor> &lattice){ Dot2D offset = lattice.getLocation(); TensorField2D<T,Descriptor<T>::d> velocity(lattice.getNx(),lattice.getNy()); plint xl,yl,ix,iy,ii,jj; T rx,ry,wgt; T rho,dtfm; Array<T,2> us(0.,0.); Array<T,2> fsi(0.,0.); Array<T,2> uf(0.,0.); T **x = wrapper.lmp->atom->x; T **v = wrapper.lmp->atom->v; T **f = wrapper.lmp->atom->f; T **fe = f_fcm->fexternal; int *mask = wrapper.lmp->atom->mask; double *mass = wrapper.lmp->atom->mass; int *type = wrapper.lmp->atom->type; molecule = wrapper.lmp->atom->molecule; plint nlocal = wrapper.lmp->atom->nlocal; std::vector<T> wx(4,0.0),wy(4,0.0); for(ix=domain.x0-2;ix<=domain.x1+2;ix++) for(iy=domain.y0-2;iy<=domain.y1+2;iy++){ lattice.get(ix,iy).computeVelocity(velocity.get(ix,iy)); } for (plint iS=0; iS<nlocal; iS++){ if (mask[iS] & groupbit ){ xl = floor(x[iS][0]); yl = floor(x[iS][1]); rx = x[iS][0] - xl; ry = x[iS][1] - yl; weight<T>(rx,wx); weight<T>(ry,wy); us[0] = us[1] = 0.0; rho=0.0; for (ii=0;ii<4;ii++ ) for (jj=0;jj<4;jj++ ){ ix = xl-1 + ii - offset.x ; iy = yl-1 + jj - offset.y ; if ( ix < domain.x0-2) continue; if ( iy < domain.y0-2) continue; uf = velocity.get(ix,iy); wgt = wx[ii]*wy[jj]; us[0] += wgt*uf[0]; us[1] += wgt*uf[1]; rho += wgt*lattice.get(ix,iy).computeDensity(); } fsi[0]=rho*(us[0]-v[iS][0]); fsi[1]=rho*(us[1]-v[iS][1]); fe[iS][0] = fsi[0]; // no accumulation for external force fe[iS][1] = fsi[1]; //update position and velocity of atom if (molecule[iS] != 1) { dtfm = dt / mass[type[iS]]; v[iS][0] += dtfm * (f[iS][0] + fe[iS][0]); v[iS][1] += dtfm * (f[iS][1] + fe[iS][1]); //v[iS][2] += dtfm * f[iS][2]; x[iS][0] += dt * v[iS][0]; x[iS][1] += dt * v[iS][1]; } for (ii=0;ii<4;ii++ ) for (jj=0;jj<4;jj++ ){ ix = xl-1 + ii - offset.x ; iy = yl-1 + jj - offset.y ; if (ix > domain.x1 || ix < domain.x0-2) continue; if (iy > domain.y1 || iy < domain.y0-2) continue; Cell<T,Descriptor>& cell = lattice.get(ix,iy); T *ff=cell.getExternal(Descriptor<T>::ExternalField::forceBeginsAt); wgt = wx[ii]*wy[jj]; ff[0] -= wgt*fsi[0]; ff[1] -= wgt*fsi[1]; cell.setExternalField(Descriptor<T>::ExternalField::forceBeginsAt,Descriptor<T>::ExternalField::sizeOfForce,ff ); } }//mask[is] } } virtual ForceFSI2D<T,Descriptor> * clone() const{ return new ForceFSI2D(*this); } void getTypeOfModification(std::vector<modif::ModifT> & modified) const { modified[0]=modif::staticVariables; } virtual BlockDomain::DomainT appliesTo() const{ return BlockDomain::bulk; } private: LammpsWrapper &wrapper; class LAMMPS_NS::FixFCM *f_fcm; plint groupbit; LAMMPS_NS::tagint *molecule; T dt; }; template<typename T, template<typename U> class Descriptor> void forceCoupling2D(MultiBlockLattice2D<T,Descriptor> &lattice, LammpsWrapper &wrapper) { applyProcessingFunctional(new ForceFSI2D<T,Descriptor>(wrapper), lattice.getBoundingBox(),lattice); } //********************************* // force coupling ends //********************************* }; /* namespace plb */ #endif
14,493
C++
.h
370
29.713514
131
0.556153
huilinye/OpenFSI
31
20
6
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,047
SHE.cpp
qianlou_SHE/src/SHE.cpp
#include "encryption.hpp" #include "alu.hpp" #include "matrix.hpp" #include <iostream> #include <sys/time.h> int ShiftDotProduct(int* inputs, int * We,const int cols){ int result=0; for(int i=0; i<cols; i++){ if(We[i]<0){ for( int j=0; j<-We[i]; j++){ inputs[i]=inputs[i]>>1; } } else if(We[i]>0){ for( int j=0; j<We[i]; j++){ inputs[i]=inputs[i]<<1; }} result=result+inputs[i]; } return result; } //Plaintext Max operations and verification int max(int A, int B){ if(A>B) return A; else return B; } // elementary full comparator gate that is used to compare the i-th bit: // input: ai and bi the i-th bit of a and b // lsb_carry: the result of the comparison on the lowest bits // algo: if (a==b) return lsb_carry else return b void compare_bit(LweSample* result, const LweSample* a, const LweSample* b, const LweSample* lsb_carry, LweSample* tmp, const TFheGateBootstrappingCloudKeySet* bk) { bootsXNOR(tmp, a, b, bk); bootsMUX(result, tmp, lsb_carry, a, bk); } // this function compares two multibit words, and puts the max in result void maximum(LweSample* result, const LweSample* a, const LweSample* b, const int nb_bits, const TFheGateBootstrappingCloudKeySet* bk) { LweSample* tmps = new_gate_bootstrapping_ciphertext_array(2, bk->params); //initialize the carry to 0 bootsCONSTANT(&tmps[0], 0, bk); //run the elementary comparator gate n times for (int i=0; i<nb_bits-1; i++) { compare_bit(&tmps[0], &a[i], &b[i], &tmps[0], &tmps[1], bk); } //we need to handel the comparison between positive number and negative number LweSample* msb_nota = new_gate_bootstrapping_ciphertext_array(1, bk->params); LweSample* msb_notb = new_gate_bootstrapping_ciphertext_array(1, bk->params); LweSample* msb_nota_and_b = new_gate_bootstrapping_ciphertext_array(1, bk->params); LweSample* msb_notb_and_a = new_gate_bootstrapping_ciphertext_array(1, bk->params); LweSample* msb_notb_and_a_or_msb_notb_and_a = new_gate_bootstrapping_ciphertext_array(1, bk->params); LweSample* not_tmps = new_gate_bootstrapping_ciphertext_array(1, bk->params); bootsNOT(msb_nota, &a[nb_bits-1], bk); bootsNOT(msb_notb, &b[nb_bits-1], bk); bootsAND(msb_nota_and_b, msb_nota, &b[nb_bits-1], bk); bootsAND(msb_notb_and_a, msb_notb, &a[nb_bits-1], bk); bootsOR(msb_notb_and_a_or_msb_notb_and_a, msb_notb_and_a, msb_nota_and_b, bk); bootsNOT(not_tmps, &tmps[0], bk); bootsMUX(&tmps[0], msb_notb_and_a_or_msb_notb_and_a, not_tmps, &tmps[0], bk); //tmps[0] is the result of the comparaison: 0 if a is larger, 1 if b is larger //select the max and copy it to the result for (int i=0; i<nb_bits; i++) { bootsMUX(&result[i], &tmps[0], &a[i], &b[i], bk); } delete_gate_bootstrapping_ciphertext_array(2, tmps); } void ReLU(LweSample* result, const LweSample* a,const int bits,const TFheGateBootstrappingCloudKeySet* ck){ LweSample* b=new_gate_bootstrapping_ciphertext_array(bits, ck->params); zero(b, ck, bits); maximum(result, a, b, bits, ck); } int verify(int A, int B){ if (A==B){printf("Verify Sucess!");} else{printf("There is difference between plaintext result and decrypted result!");} } int main(){ const double clocks2seconds = 1. / CLOCKS_PER_SEC; // setup parameters typedef int8_t num_type ; size_t bits = sizeof(num_type) * 4; const int minimum_lambda = 80; TFheGateBootstrappingParameterSet* params = new_default_gate_bootstrapping_parameters(minimum_lambda); const TFheGateBootstrappingSecretKeySet* sk = new_random_gate_bootstrapping_secret_keyset(params); const TFheGateBootstrappingCloudKeySet* ck = &sk->cloud; printf("######## 1. shiftDot(A[0:input_size-1], Be[0:input_size-1]) Verification#######\n"); //Unencrypted DotProduct between inputs A[input_size] and B[input_size] int input_size=8; int result=0; int *A=new int[input_size]; int *Be=new int[input_size]; printf("A=["); for(int i=0; i< input_size; i++){ A[i]=i; printf(" %d", A[i]); } printf("]\nBe=["); for(int i=0; i< input_size; i++){ Be[i]=1; printf(" %d", Be[i]); } printf("]\n"); result=ShiftDotProduct(A,Be,input_size); //Encrypted DotProduct between Enc_A[input_size][bits] and B[input_size] LweSample **Enc_A=new LweSample*[input_size]; LweSample *Enc_result = new_gate_bootstrapping_ciphertext_array(bits, ck->params); for(int i1 = 0; i1 < input_size; i1++) { Enc_A[i1] = new_gate_bootstrapping_ciphertext_array(bits, ck->params); } Enc_result = new_gate_bootstrapping_ciphertext_array(bits, ck->params); for(num_type i=0; i<input_size;i++){ encrypt<num_type>(Enc_A[i], i, sk); } //num_type plain_hidden_result=decrypt<num_type>(enc_inputs[3], sk); shiftDot(Enc_result, Enc_A, Be, input_size, ck, bits); num_type plain_result=decrypt<num_type>(Enc_result, sk); printf("Decrypted Result:%d\n",plain_result); //cout<<"Decrypted Result"<<plain_hidden_result; printf("Plaintext Result: %d\n",result); int A1=0, B1=-4; printf("######## 2. Max(A=%d, B=%d) Verification ####### \n", A1, B1); LweSample * Max_Enc_A=new_gate_bootstrapping_ciphertext_array(bits, ck->params); encrypt<num_type>(Max_Enc_A, A1, sk); LweSample * Max_Enc_B=new_gate_bootstrapping_ciphertext_array(bits, ck->params); encrypt<num_type>(Max_Enc_B, B1, sk); LweSample * Max_Enc_Result=new_gate_bootstrapping_ciphertext_array(bits, ck->params); maximum(Max_Enc_Result, Max_Enc_A, Max_Enc_B, bits, ck); num_type Max_plain_result=decrypt<num_type>(Max_Enc_Result, sk); printf("Decrypted Result: %d\n",Max_plain_result); printf("Plaintex Result: %d\n",max(A1,B1)); int A2=-5; printf("######## 3. ReLU(A=%d) Verification######## \n", A2); LweSample * ReLU_Enc_A=new_gate_bootstrapping_ciphertext_array(bits, ck->params); encrypt<num_type>(ReLU_Enc_A, A2, sk); LweSample * ReLU_Enc_Result=new_gate_bootstrapping_ciphertext_array(bits, ck->params); ReLU(ReLU_Enc_Result, ReLU_Enc_A,bits,ck); num_type ReLU_plain_result=decrypt<num_type>(ReLU_Enc_Result, sk); printf("Decrypted Result: %d\n",ReLU_plain_result); printf("Plaintex Result: %d\n",max(A2,0)); //verify(ReLU_plain_result, max(A,0)); }
6,484
C++
.cpp
138
41.869565
165
0.664278
qianlou/SHE
30
5
3
GPL-3.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,057
menusettingdir.cpp
MiyooCFW_gmenu2x/src/menusettingdir.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "menusettingdir.h" #include "browsedialog.h" #include "debug.h" extern const char *CARD_ROOT; using std::string; using fastdelegate::MakeDelegate; MenuSettingDir::MenuSettingDir(GMenu2X *gmenu2x, const string &title, const string &description, string *value, const std::string &startPath, const std::string &dialogTitle, const std::string &dialogIcon): MenuSettingStringBase(gmenu2x, title, description, value), startPath(startPath), dialogTitle(dialogTitle), dialogIcon(dialogIcon) { if (dialogTitle.empty()) this->dialogTitle = this->title; if (dialogIcon.empty()) this->dialogIcon = "icons/explorer.png"; if (startPath.empty()) this->startPath = CARD_ROOT; btn = new IconButton(gmenu2x, "select", gmenu2x->tr["Reset"]); btn->setAction(MakeDelegate(this, &MenuSettingDir::clear)); buttonBox.add(btn); btn = new IconButton(gmenu2x, "a", gmenu2x->tr["Select"]); btn->setAction(MakeDelegate(this, &MenuSettingDir::edit)); buttonBox.add(btn); } void MenuSettingDir::edit() { string _value = value(); if (_value.empty()) _value = startPath + "/"; BrowseDialog bd(gmenu2x, dialogTitle, description, dialogIcon); bd.setPath(_value); bd.showDirectories = true; bd.showFiles = false; bd.allowSelectDirectory = true; if (bd.exec()) setValue(bd.getPath()); }
2,691
C++
.cpp
49
52.979592
205
0.586338
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,058
menusettingfile.cpp
MiyooCFW_gmenu2x/src/menusettingfile.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "menusettingfile.h" #include "browsedialog.h" #include "debug.h" using std::string; using fastdelegate::MakeDelegate; MenuSettingFile::MenuSettingFile(GMenu2X *gmenu2x, const string &title, const string &description, string *value, const string &filter, const string &startPath, const string &dialogTitle, const string &dialogIcon): MenuSettingStringBase(gmenu2x, title, description, value), filter(filter), startPath(startPath), dialogTitle(dialogTitle), dialogIcon(dialogIcon) { btn = new IconButton(gmenu2x, "select", gmenu2x->tr["Reset"]); btn->setAction(MakeDelegate(this, &MenuSettingFile::clear)); buttonBox.add(btn); btn = new IconButton(gmenu2x, "a", gmenu2x->tr["Select"]); btn->setAction(MakeDelegate(this, &MenuSettingFile::edit)); buttonBox.add(btn); } void MenuSettingFile::edit() { string _value = value(); if (_value.empty()) _value = startPath + "/"; _value = dir_name(_value); BrowseDialog bd(gmenu2x, dialogTitle, description, dialogIcon); bd.setPath(_value); bd.showDirectories = true; bd.showFiles = true; bd.setFilter(filter); if (bd.exec()) setValue(bd.getFilePath(bd.selected)); }
2,543
C++
.cpp
46
53.347826
214
0.579285
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,059
linkapp.cpp
MiyooCFW_gmenu2x/src/linkapp.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include <sys/stat.h> #include <unistd.h> #include <fstream> #include "linkapp.h" #include "menu.h" #include "selector.h" #include "messagebox.h" #include "debug.h" using namespace std; extern char** environ; LinkApp::LinkApp(GMenu2X *gmenu2x, const char* file): Link(gmenu2x, MakeDelegate(this, &LinkApp::run)), file(file) { setCPU(gmenu2x->confInt["cpuLink"]); setKbdLayout(gmenu2x->confInt["keyboardLayoutMenu"]); setTefix(gmenu2x->confInt["tefixMenu"]); #if defined(HW_GAMMA) //G setGamma(0); // wrapper = false; // dontleave = false; // setVolume(-1); // useRamTimings = false; // useGinge = false; #endif if (((float)(gmenu2x->w)/gmenu2x->h) != (4.0f/3.0f)) _scalemode = 3; // 4:3 by default scalemode = _scalemode; string line; ifstream infile(file, ios_base::in); while (getline(infile, line, '\n')) { line = trim(line); if (line == "") continue; if (line[0] == '#') continue; string::size_type position = line.find("="); string name = trim(line.substr(0, position)); string value, valuess; string::size_type position_newl_all = line.find("\\n"); string::size_type pos = 0; uint32_t count = 0; while ((pos = line.find("\\n", pos)) != std::string::npos) { ++count; pos += 2; } if (position_newl_all != std::string::npos) { string::size_type position_newl[365]; for (uint32_t i = 0; i <= count; i++) { // check if this is first chunk if (i == 0) position_newl[i] = line.find("\\n"); else position_newl[i] = line.find("\\n", position_newl[i-1] + 2); // genearate translation string from all chunks if (i == 0 && position_newl[i] != std::string::npos) valuess += trim(line.substr(position + 1, position_newl[i] - position - 1)) + "\n"; else if (position_newl[i] != std::string::npos) valuess += trim(line.substr(position_newl[i-1] + 2, position_newl[i] - position_newl[i-1] - 2)) + "\n"; else valuess += trim(line.substr(position_newl[i-1] + 2)); } value = valuess; } else { value = trim(line.substr(position + 1)); } if (name == "exec") setExec(value); else if (name == "title") setTitle(value); else if (name == "description") setDescription(value); else if (name == "icon") setIcon(value); else if (name == "opk[icon]") icon_opk = value; else if (name == "params") setParams(value); else if (name == "home") setHomeDir(value); else if (name == "manual") setManual(value); else if (name == "clock") setCPU(atoi(value.c_str())); else if (name == "layout") setKbdLayout(atoi(value.c_str())); else if (name == "tefix") setTefix(atoi(value.c_str())); #if defined(HW_GAMMA) // else if (name == "wrapper" && value == "true") // wrapper = true; // else if (name == "dontleave" && value == "true") // dontleave = true; // else if (name == "volume") // setVolume(atoi(value.c_str())); // else if (name == "useramtimings" && value == "true") // useRamTimings = true; // else if (name == "useginge" && value == "true") // useGinge = true; else if (name == "gamma") setGamma(atoi(value.c_str())); #endif else if (name == "selectordir") setSelectorDir(value); else if (name == "selectorbrowser" && value == "false") setSelectorBrowser(false); else if (name == "scalemode") setScaleMode(atoi(value.c_str())); else if (name == "selectorfilter") setSelectorFilter(value); else if (name == "selectorscreens") setSelectorScreens(value); else if (name == "selectoraliases") setAliasFile(value); else if (name == "selectorelement") setSelectorElement(atoi(value.c_str())); else if ((name == "consoleapp") || (name == "terminal")) setTerminal(value == "true"); else if (name == "backdrop") setBackdrop(value); // else WARNING("Unrecognized option: '%s'", name.c_str()); } infile.close(); is_opk = (file_ext(exec, true) == ".opk"); if (iconPath.empty()) iconPath = searchIcon(); if (manualPath.empty()) manualPath = searchManual(); if (backdropPath.empty()) backdropPath = searchBackdrop(); } const string LinkApp::searchManual() { if (!manualPath.empty()) return manualPath; string filename = exec; string::size_type pos = exec.rfind("."); if (pos != string::npos) filename = exec.substr(0, pos); string imagename = filename + ".man.png"; filename += ".man.txt"; string dname = dir_name(exec) + "/"; string dirtitle = dname + base_name(dir_name(exec)) + ".man.txt"; string linktitle = base_name(file, true); linktitle = dname + linktitle + ".man.txt"; if (file_exists(linktitle)) return linktitle; if (file_exists(filename)) return filename; if (file_exists(imagename)) return imagename; if (file_exists(dirtitle)) return dirtitle; return ""; } const string LinkApp::searchBackdrop() { if (!backdropPath.empty() || !gmenu2x->confInt["skinBackdrops"]) return backdropPath; string execicon = exec; string::size_type pos = exec.rfind("."); if (pos != string::npos) execicon = exec.substr(0, pos); string exectitle = base_name(execicon); string dirtitle = base_name(dir_name(exec)); string linktitle = base_name(file); string sublinktitle = base_name(file); pos = linktitle.find("."); if (pos != string::npos) sublinktitle = linktitle.substr(0, pos); pos = linktitle.rfind("."); if (pos != string::npos) linktitle = linktitle.substr(0, pos); if (gmenu2x->skinConfInt["searchBackdrops"] != SBAK_EXEC) { backdropPath = gmenu2x->sc.getSkinFilePath("backdrops/" + sublinktitle + ".png"); if (!backdropPath.empty()) return backdropPath; backdropPath = gmenu2x->sc.getSkinFilePath("backdrops/" + sublinktitle + ".jpg"); if (!backdropPath.empty()) return backdropPath; backdropPath = gmenu2x->sc.getSkinFilePath("backdrops/" + linktitle + ".png"); if (!backdropPath.empty()) return backdropPath; backdropPath = gmenu2x->sc.getSkinFilePath("backdrops/" + linktitle + ".jpg"); if (!backdropPath.empty()) return backdropPath; } if (gmenu2x->skinConfInt["searchBackdrops"] != SBAK_LINK) { backdropPath = gmenu2x->sc.getSkinFilePath("backdrops/" + exectitle + ".png"); if (!backdropPath.empty()) return backdropPath; backdropPath = gmenu2x->sc.getSkinFilePath("backdrops/" + exectitle + ".jpg"); if (!backdropPath.empty()) return backdropPath; backdropPath = gmenu2x->sc.getSkinFilePath("backdrops/" + dirtitle + ".png"); if (!backdropPath.empty()) return backdropPath; backdropPath = gmenu2x->sc.getSkinFilePath("backdrops/" + dirtitle + ".jpg"); if (!backdropPath.empty()) return backdropPath; } backdropPath = dir_name(exec) + "/backdrop.png"; if (file_exists(backdropPath)) return backdropPath; backdropPath = gmenu2x->sc.getSkinFilePath("backdrops/generic.png"); if (file_exists(backdropPath)) return backdropPath; return ""; } const string LinkApp::searchIcon() { string iconpath = gmenu2x->sc.getSkinFilePath(icon, false); if (!iconpath.empty()) return iconpath; string execicon = exec; string::size_type pos = exec.rfind("."); if (pos != string::npos) execicon = exec.substr(0, pos); string exectitle = base_name(execicon); string dirtitle = base_name(dir_name(exec)); string linktitle = base_name(file); vector<string> linkparts; split(linkparts, linktitle, "."); if (linkparts.size() > 2) { iconpath = gmenu2x->sc.getSkinFilePath("icons/" + linkparts[0] + "." + linkparts[1] + ".png", false); if (!iconpath.empty()) return iconpath; iconpath = gmenu2x->sc.getSkinFilePath("icons/" + linkparts[1] + "." + linkparts[0] + ".png", false); if (!iconpath.empty()) return iconpath; } if (linkparts.size() > 1) { iconpath = gmenu2x->sc.getSkinFilePath("icons/" + linkparts[1] + ".png", false); if (!iconpath.empty()) return iconpath; iconpath = gmenu2x->sc.getSkinFilePath("icons/" + linkparts[0] + ".png", false); if (!iconpath.empty()) return iconpath; } iconpath = gmenu2x->sc.getSkinFilePath("icons/" + linktitle + ".png", false); if (!iconpath.empty()) return iconpath; iconpath = gmenu2x->sc.getSkinFilePath("icons/" + exectitle + ".png", false); if (!iconpath.empty()) return iconpath; iconpath = gmenu2x->sc.getSkinFilePath("icons/" + dirtitle + ".png", false); if (!iconpath.empty()) return iconpath; iconpath = dir_name(exec) + "/" + exectitle + ".png"; if (file_exists(iconpath)) return iconpath; iconpath = execicon + ".png"; if (file_exists(iconpath)) return iconpath; #if defined(OPK_SUPPORT) if (isOPK()) { return exec + "#" + icon_opk; } else #endif return gmenu2x->sc.getSkinFilePath("icons/generic.png"); } void LinkApp::setCPU(int mhz) { clock = mhz; if (clock != 0) clock = constrain(clock, gmenu2x->confInt["cpuMin"], gmenu2x->confInt["cpuMax"]); edited = true; } void LinkApp::setKbdLayout(int val) { layout = val; if (layout != 0) layout = constrain(layout, 1, gmenu2x->confInt["keyboardLayoutMax"]); edited = true; } void LinkApp::setTefix(int val) { tefix = val; if (tefix != -1) tefix = constrain(tefix, 0, gmenu2x->confInt["tefixMax"]); edited = true; } #if defined(HW_GAMMA) void LinkApp::setGamma(int gamma) { gamma = constrain(gamma, 0, 100); edited = true; } #endif bool LinkApp::targetExists() { #if defined(TARGET_LINUX) return true; //For displaying elements during testing on pc #endif string target = exec; if (!exec.empty() && exec[0] != '/' && !homedir.empty()) target = homedir + "/" + exec; return file_exists(target); } bool LinkApp::save() { if (!edited) return false; int pos = icon.find('#'); // search for "opkfile.opk#icon.png" if (pos != string::npos) { icon_opk = icon.substr(pos + 1); } ofstream f(file.c_str()); if (f.is_open()) { if (title != "") f << "title=" << title << endl; if (description != "") f << "description=" << description << endl; if (icon != "") f << "icon=" << icon << endl; if (icon_opk != "") f << "opk[icon]=" << icon_opk << endl; if (exec != "") f << "exec=" << exec << endl; if (params != "") f << "params=" << params << endl; if (homedir != "") f << "home=" << homedir << endl; if (manual != "") f << "manual=" << manual << endl; if (clock != 0 && clock != gmenu2x->confInt["cpuLink"]) f << "clock=" << clock << endl; if (layout != 0 && layout != gmenu2x->confInt["keyboardLayoutMenu"]) f << "layout=" << layout << endl; if (tefix != -1 && tefix != gmenu2x->confInt["tefixMenu"]) f << "tefix=" << tefix << endl; // if (useRamTimings) f << "useramtimings=true" << endl; // if (useGinge) f << "useginge=true" << endl; // if (volume > 0) f << "volume=" << volume << endl; #if defined(HW_GAMMA) if (gamma != 0) f << "gamma=" << gamma << endl; #endif if (selectordir != "") f << "selectordir=" << selectordir << endl; if (!selectorbrowser) f << "selectorbrowser=false" << endl; // selectorbrowser = true by default if (scalemode != _scalemode) f << "scalemode=" << scalemode << endl; // scalemode = 0 by default if (selectorfilter != "") f << "selectorfilter=" << selectorfilter << endl; if (selectorscreens != "") f << "selectorscreens=" << selectorscreens << endl; if (selectorelement > 0) f << "selectorelement=" << selectorelement << endl; if (aliasfile != "") f << "selectoraliases=" << aliasfile << endl; if (backdrop != "") f << "backdrop=" << backdrop << endl; if (terminal) f << "terminal=true" << endl; f.close(); return true; } ERROR("Error while opening the file '%s' for write.", file.c_str()); return false; } void LinkApp::run() { uint32_t start = SDL_GetTicks(); while (gmenu2x->input[CONFIRM]) { gmenu2x->input.update(); if (SDL_GetTicks() - start > 1400) { // hold press -> inverted if (selectordir != "") return launch(); return selector(); } } // quick press -> normal if (selectordir != "") return selector(); return launch(); } void LinkApp::selector(int startSelection, const string &selectorDir) { //Run selector interface Selector bd(gmenu2x, this->getTitle(), this->getDescription(), this->getIconPath(), this); bd.showDirectories = this->getSelectorBrowser(); if (selectorDir != "") bd.directoryEnter(selectorDir); else bd.directoryEnter(this->getSelectorDir()); bd.setFilter(this->getSelectorFilter()); if (startSelection > 0) bd.selected = startSelection; else bd.selected = this->getSelectorElement(); if (bd.exec()) { gmenu2x->writeTmp(bd.selected, bd.getPath()); string s = ""; s += this->getSelectorDir().back(); if (s != "/") { setSelectorDir(bd.getPath()); setSelectorElement(bd.selected); save(); } params = trim(params + " " + bd.getParams(bd.selected)); launch(bd.getFile(bd.selected), bd.getPath()); } } void LinkApp::launch(const string &selectedFile, string dir) { MessageBox mb(gmenu2x, gmenu2x->tr["Launching"] + " " + this->getTitle().c_str(), this->getIconPath()); mb.setAutoHide(1); mb.exec(); string command = cmdclean(exec); if (selectedFile.empty()) { gmenu2x->writeTmp(); } else { if (dir.empty()) { dir = getSelectorDir(); } if (params.empty()) { params = cmdclean(dir + "/" + selectedFile); } else { string origParams = params; params = strreplace(params, "[selFullPath]", cmdclean(dir + "/" + selectedFile)); params = strreplace(params, "\%f", cmdclean(dir + "/" + selectedFile)); params = strreplace(params, "[selPath]", cmdclean(dir)); params = strreplace(params, "[selFile]", cmdclean(base_name(selectedFile, true))); params = strreplace(params, "[selFileFull]", cmdclean(selectedFile)); params = strreplace(params, "[selExt]", cmdclean(file_ext(selectedFile, false))); if (params == origParams) params += " " + cmdclean(dir + "/" + selectedFile); } } INFO("Executing '%s' (%s %s)", title.c_str(), exec.c_str(), params.c_str()); #if defined(OPK_SUPPORT) if (isOPK()) { string opk_mount = "umount -fl /mnt &> /dev/null; mount -o loop " + command + " /mnt"; system(opk_mount.c_str()); chdir("/mnt"); // Set correct working directory command = "/mnt/" + params; params = ""; } else #endif { chdir(dir_name(exec).c_str()); // Set correct working directory } // Check to see if permissions are desirable struct stat fstat; if (!stat(command.c_str(), &fstat)) { struct stat newstat = fstat; if (S_IRUSR != (fstat.st_mode & S_IRUSR)) newstat.st_mode |= S_IRUSR; if (S_IXUSR != (fstat.st_mode & S_IXUSR)) newstat.st_mode |= S_IXUSR; if (fstat.st_mode != newstat.st_mode) chmod(command.c_str(), newstat.st_mode); } // else, well.. we are no worse off :) if (params != "") command += " " + params; if (gmenu2x->confInt["saveSelection"] && (gmenu2x->confInt["section"] != gmenu2x->menu->selSectionIndex() || gmenu2x->confInt["link"] != gmenu2x->menu->selLinkIndex())) { gmenu2x->writeConfig(); } if (gmenu2x->confInt["saveAutoStart"]) { gmenu2x->confInt["lastCPU"] = clock; gmenu2x->confInt["lastKeyboardLayout"] = layout; gmenu2x->confInt["lastTefix"] = tefix; gmenu2x->confStr["lastCommand"] = command.c_str(); gmenu2x->confStr["lastDirectory"] = dir_name(exec).c_str(); gmenu2x->writeConfig(); } if (getCPU() != gmenu2x->confInt["cpuMenu"]) gmenu2x->setCPU(getCPU()); if (getKbdLayout() != gmenu2x->confInt["keyboardLayoutMenu"]) gmenu2x->setKbdLayout(getKbdLayout()); if (getTefix() != gmenu2x->confInt["tefixMenu"]) gmenu2x->setTefix(getTefix()); #if defined(TARGET_GP2X) //if (useRamTimings) gmenu2x->applyRamTimings(); // if (useGinge) { // string ginge_prep = exe_path() + "/ginge/ginge_prep"; // if (file_exists(ginge_prep)) command = cmdclean(ginge_prep) + " " + command; // } if (fwType == "open2x") gmenu2x->writeConfigOpen2x(); #endif #if defined(HW_GAMMA) if (gamma() != 0 && gamma() != gmenu2x->confInt["gamma"]) gmenu2x->setGamma(gamma()); #endif gmenu2x->setScaleMode(scalemode); command = gmenu2x->hwPreLinkLaunch() + command; if (gmenu2x->confInt["outputLogs"]) { params = "echo " + cmdclean(command) + " > " + cmdclean(exe_path()) + "/log.txt"; system(params.c_str()); command += " 2>&1 | tee -a " + cmdclean(exe_path()) + "/log.txt"; } // params = this->getHomeDir(); params = gmenu2x->confStr["homePath"]; if (!params.empty() && dir_exists(params)) { command = "HOME=" + params + " " + command; } gmenu2x->quit(); if (getTerminal()) gmenu2x->enableTerminal(); // execle("/bin/sh", "/bin/sh", "-c", command.c_str(), NULL, environ); if (gmenu2x->confInt["saveAutoStart"]) { string prevCmd = command.c_str(); string tmppath = exe_path() + "/gmenu2x.conf"; string writeDateCmd = "; sed -i \"/datetime=/c\\datetime=\\\"$(date +\\%\\F\\ %H:%M)\\\"\" "; #if defined(TARGET_LINUX) string exitCmd = "; exit" ; #else string exitCmd = "; sync; mount -o remount,ro $HOME; poweroff"; #endif string launchCmd = prevCmd + writeDateCmd + tmppath + exitCmd; execlp("/bin/sh", "/bin/sh", "-c", launchCmd.c_str(), NULL); } else { execlp("/bin/sh", "/bin/sh", "-c", command.c_str(), NULL); } //if execution continues then something went wrong and as we already called SDL_Quit we cannot continue //try relaunching gmenu2x chdir(exe_path().c_str()); execlp("./gmenu2x", "./gmenu2x", NULL); } void LinkApp::setExec(const string &exec) { this->exec = exec; edited = true; } void LinkApp::setParams(const string &params) { this->params = params; edited = true; } void LinkApp::setHomeDir(const string &homedir) { this->homedir = homedir; edited = true; } void LinkApp::setManual(const string &manual) { this->manual = manualPath = manual; edited = true; } void LinkApp::setSelectorDir(const string &selectordir) { edited = this->selectordir != selectordir; this->selectordir = selectordir; // if (this->selectordir != "") this->selectordir = real_path(this->selectordir); } void LinkApp::setSelectorBrowser(bool value) { selectorbrowser = value; edited = true; } void LinkApp::setTerminal(bool value) { terminal = value; edited = true; } void LinkApp::setScaleMode(int value) { scalemode = value; edited = true; } void LinkApp::setSelectorFilter(const string &selectorfilter) { this->selectorfilter = selectorfilter; edited = true; } void LinkApp::setSelectorScreens(const string &selectorscreens) { this->selectorscreens = selectorscreens; edited = true; } void LinkApp::setSelectorElement(int i) { edited = selectorelement != i; selectorelement = i; } void LinkApp::setAliasFile(const string &aliasfile) { this->aliasfile = aliasfile; edited = true; } void LinkApp::renameFile(const string &name) { file = name; } // void LinkApp::setUseRamTimings(bool value) { // useRamTimings = value; // edited = true; // } // void LinkApp::setUseGinge(bool value) { // useGinge = value; // edited = true; // }
20,014
C++
.cpp
485
38.756701
171
0.648031
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,060
opkscannerdialog.cpp
MiyooCFW_gmenu2x/src/opkscannerdialog.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #if defined(OPK_SUPPORT) #include "opkscannerdialog.h" #include "utilities.h" #include "menu.h" #include "powermanager.h" #include "debug.h" #include "linkapp.h" #include <dirent.h> #include <libopk.h> #include "filelister.h" #include <algorithm> using namespace std; extern const char *CARD_ROOT; bool any_platform = false; OPKScannerDialog::OPKScannerDialog(GMenu2X *gmenu2x, const string &title, const string &description, const string &icon, const string &backdrop): TextDialog(gmenu2x, title, description, icon, backdrop) {} void OPKScannerDialog::opkInstall(const string &path) { string pkgname = base_name(path, true); struct OPK *opk = opk_open(path.c_str()); if (!opk) { text.push_back(path + ": " + gmenu2x->tr["Unable to open OPK"]); lineWidth = drawText(&text, firstCol, -1, rowsPerPage); ERROR("%s: Unable to open OPK", path.c_str()); return; } while (true) { const char *name; int ret = opk_open_metadata(opk, &name); if (ret < 0) { text.push_back(path + ": " + gmenu2x->tr["Error loading meta-data"]); lineWidth = drawText(&text, firstCol, -1, rowsPerPage); ERROR("Error loading meta-data"); goto close; } else if (ret == 0) { goto close; } /* Strip .desktop */ string linkname(name), platform; string::size_type pos = linkname.rfind('.'); linkname = linkname.substr(0, pos); pos = linkname.rfind('.'); platform = linkname.substr(pos + 1); string linkpath = linkname.substr(0, pos); linkpath = pkgname + "." + linkname + ".lnk"; if (!(any_platform || platform == PLATFORM || platform == "all")) { text.push_back(" - " + linkname + ": " + gmenu2x->tr["Unsupported platform"]); lineWidth = drawText(&text, firstCol, -1, rowsPerPage); ERROR("%s: Unsupported platform '%s'", pkgname.c_str(), platform.c_str()); continue; } else { text.push_back(" + " + linkname + ": " + gmenu2x->tr["OK"]); lineWidth = drawText(&text, firstCol, -1, rowsPerPage); } const char *key, *val; size_t lkey, lval; string title = "", params = "", description = "", manual = "", selectordir = "", selectorfilter = "", aliasfile = "", scaling = "", icon = "", section = "applications"; bool terminal = false; while (ret = opk_read_pair(opk, &key, &lkey, &val, &lval)) { if (ret < 0) { text.push_back(path + ": " + gmenu2x->tr["Error loading meta-data"]); lineWidth = drawText(&text, firstCol, -1, rowsPerPage); ERROR("Error loading meta-data"); goto close; } else if (ret == 0) { goto close; } char buf[lval + 1]; sprintf(buf, "%.*s", lval, val); if (!strncmp(key, "Name", lkey)) { title = buf; } else if (!strncmp(key, "Exec", lkey)) { params = buf; } else if (!strncmp(key, "Comment", lkey)) { description = buf; } else if (!strncmp(key, "Terminal", lkey)) { terminal = !strcmp(buf, "true"); } else if (!strncmp(key, "X-OD-Manual", lkey)) { manual = buf; } else if (!strncmp(key, "X-OD-Selector", lkey)) { selectordir = buf; } else if (!strncmp(key, "X-OD-Scaling", lkey)) { scaling = buf; } else if (!strncmp(key, "X-OD-Filter", lkey)) { selectorfilter = buf; } else if (!strncmp(key, "X-OD-Alias", lkey)) { aliasfile = buf; } else if (!strncmp(key, "Categories", lkey)) { section = buf; pos = section.find(';'); if (pos != section.npos) { section = section.substr(0, pos); } } else if (!strncmp(key, "Icon", lkey)) { icon = path + "#" + (string)buf + ".png"; } } gmenu2x->menu->addSection(section); linkpath = "sections/" + section + "/" + linkpath; LinkApp *link = new LinkApp(gmenu2x, linkpath.c_str()); if (!path.empty()) link->setExec(path); if (!params.empty()) link->setParams(params); if (!title.empty()) link->setTitle(title); if (!description.empty()) link->setDescription(description); if (!manual.empty()) link->setManual(manual); if (((char)params.find("\%f") >= 0) && link->getSelectorDir().empty()) link->setSelectorDir(gmenu2x->confStr["homePath"]); if (!selectordir.empty() && link->getSelectorDir().empty()) link->setSelectorDir(selectordir); if (!selectorfilter.empty()) link->setSelectorFilter(selectorfilter); if (!aliasfile.empty()) link->setAliasFile(aliasfile); if (!icon.empty()) link->setIcon(icon); if (!scaling.empty()) link->setScaleMode(atoi(scaling.c_str())); link->setTerminal(terminal); link->save(); } close: opk_close(opk); } void OPKScannerDialog::opkScan(string opkdir) { FileLister fl; fl.showDirectories = false; fl.showFiles = true; fl.setFilter(".opk"); fl.setPath(opkdir); fl.browse(); for (uint32_t i = 0; i < fl.size(); i++) { text.push_back(gmenu2x->tr["Installing"] + " " + fl.getFilePath(i)); lineWidth = drawText(&text, firstCol, -1, rowsPerPage); opkInstall(fl.getFilePath(i)); } } void OPKScannerDialog::exec(bool _any_platform) { any_platform = _any_platform; rowsPerPage = gmenu2x->listRect.h/gmenu2x->font->getHeight(); gmenu2x->powerManager->clearTimer(); if (gmenu2x->sc[this->icon] == NULL) { this->icon = "skin:icons/terminal.png"; } buttons.push_back({"skin:imgs/manual.png", gmenu2x->tr["Running.. Please wait.."]}); drawDialog(gmenu2x->s); gmenu2x->s->flip(); if (!opkpath.empty()) { text.push_back(gmenu2x->tr["Installing"] + " " + base_name(opkpath)); lineWidth = drawText(&text, firstCol, -1, rowsPerPage); opkInstall(opkpath); } else { vector<string> paths; paths.clear(); FileLister fl; fl.showDirectories = true; fl.showFiles = false; fl.allowDirUp = false; fl.setPath(CARD_ROOT); fl.browse(); for (uint32_t j = 0; j < fl.size(); j++) { if (find(paths.begin(), paths.end(), fl.getFilePath(j)) == paths.end()) { paths.push_back(fl.getFilePath(j)); } } if (gmenu2x->confStr["homePath"] != CARD_ROOT) { fl.setPath(gmenu2x->confStr["homePath"]); fl.browse(); for (uint32_t j = 0; j < fl.size(); j++) { if (find(paths.begin(), paths.end(), fl.getFilePath(j)) == paths.end()) { paths.push_back(fl.getFilePath(j)); } } } fl.setPath("/media"); fl.browse(); for (uint32_t i = 0; i < fl.size(); i++) { FileLister flsub; flsub.showDirectories = true; flsub.showFiles = false; flsub.allowDirUp = false; flsub.setPath(fl.getFilePath(i)); flsub.browse(); for (uint32_t j = 0; j < flsub.size(); j++) { if (find(paths.begin(), paths.end(), flsub.getFilePath(j)) == paths.end()) { paths.push_back(flsub.getFilePath(j)); } } } for (uint32_t i = 0; i < paths.size(); i++) { text.push_back(gmenu2x->tr["Scanning"] + " " + paths[i]); lineWidth = drawText(&text, firstCol, -1, rowsPerPage); opkScan(paths[i]); } } system("sync &"); text.push_back("----"); text.push_back(gmenu2x->tr["Done"]); if (text.size() >= rowsPerPage) { firstRow = text.size() - rowsPerPage; } buttons.clear(); TextDialog::exec(); } #endif // defined(OPK_SUPPORT)
8,395
C++
.cpp
236
32.283898
145
0.604585
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,061
browsedialog.cpp
MiyooCFW_gmenu2x/src/browsedialog.cpp
#include "browsedialog.h" #include "messagebox.h" #include "debug.h" #include "utilities.h" #include "powermanager.h" #include "inputmanager.h" using namespace std; extern const char *CARD_ROOT; SDL_TimerID alphanum_timer = NULL; uint32_t hideAlphaNum(uint32_t interval, void *param) { SDL_RemoveTimer(alphanum_timer); alphanum_timer = NULL; InputManager::wakeUp(0, (void*)false); return 0; } BrowseDialog::BrowseDialog(GMenu2X *gmenu2x, const string &title, const string &description, const string &icon): Dialog(gmenu2x, title, description, icon) { setPath(gmenu2x->confStr["homePath"]); srand(SDL_GetTicks()); } bool BrowseDialog::exec() { this->bg = new Surface(gmenu2x->bg); // needed to redraw on child screen return Surface *iconGoUp = gmenu2x->sc["skin:imgs/go-up.png"]; Surface *iconFolder = gmenu2x->sc["skin:imgs/folder.png"]; Surface *iconFile = gmenu2x->sc["skin:imgs/file.png"]; Surface *iconSd = gmenu2x->sc["skin:imgs/sd.png"]; Surface *iconCur; uint32_t i, iY, firstElement = 0, padding = 6; int32_t animation = 0; uint32_t rowHeight = gmenu2x->font->getHeight() + 1; uint32_t numRows = (gmenu2x->listRect.h - 2) / rowHeight - 1; if (path.empty() || !dir_exists(path)) setPath(gmenu2x->confStr["homePath"]); directoryEnter(path); string preview = getPreview(selected); // this->description = getFilter(); while (true) { if (selected < 0) selected = this->size() - 1; if (selected >= this->size()) selected = 0; bool inputAction = false; buttons.clear(); if (alphanum_timer != NULL) { int c = toupper(getFileName(selected).at(0)); if (!isalpha(c)) c = '#'; string sel(1, c); buttons.push_back({"skin:imgs/manual.png", strreplace("#ABCDEFGHIJKLMNOPQRSTUVWXYZ", sel, " < " + sel + " > ")}); } else { buttons.push_back({"select", gmenu2x->tr["Menu"]}); buttons.push_back({"b", gmenu2x->tr["Cancel"]}); if (!showFiles && allowSelectDirectory) buttons.push_back({"start", gmenu2x->tr["Select"]}); else if ((allowEnterDirectory && isDirectory(selected)) || !isDirectory(selected)) buttons.push_back({"a", gmenu2x->tr["Select"]}); if (showDirectories && allowDirUp && path != "/") buttons.push_back({"x", gmenu2x->tr["Folder up"]}); if (gmenu2x->confStr["previewMode"] == "Backdrop") { if (!(preview.empty() || preview == "#")) gmenu2x->setBackground(this->bg, preview); else gmenu2x->bg->blit(this->bg,0,0); } } this->description = path; drawDialog(gmenu2x->s); if (!size()) { MessageBox mb(gmenu2x, gmenu2x->tr["This directory is empty"]); mb.setAutoHide(1); mb.setBgAlpha(0); mb.exec(); } else { // Selection if (selected >= firstElement + numRows) firstElement = selected - numRows; if (selected < firstElement) firstElement = selected; // Files & Directories iY = gmenu2x->listRect.y + 1; for (i = firstElement; i < size() && i <= firstElement + numRows; i++, iY += rowHeight) { if (i == selected) gmenu2x->s->box(gmenu2x->listRect.x, iY, gmenu2x->listRect.w, rowHeight, gmenu2x->skinConfColors[COLOR_SELECTION_BG]); iconCur = iconFile; if (isDirectory(i)) { if (getFile(i) == "..") iconCur = iconGoUp; else if ((path == "/" && getFileName(i) == "media") || path == "/media") iconCur = iconSd; else iconCur = iconFolder; } iconCur->blit(gmenu2x->s, gmenu2x->listRect.x + 10, iY + rowHeight/2, HAlignCenter | VAlignMiddle); gmenu2x->s->write(gmenu2x->font, getFileName(i), gmenu2x->listRect.x + 21, iY + rowHeight/2, VAlignMiddle); } gmenu2x->allyTTS(getFileName(selected).c_str(), FAST_GAP_TTS, FAST_SPEED_TTS, 0); if (gmenu2x->confStr["previewMode"] != "Backdrop") { Surface anim = new Surface(gmenu2x->s); if (preview.empty() || preview == "#") { // hide preview while (animation > 0) { animation -= gmenu2x->skinConfInt["previewWidth"] / 8; if (animation < 0) animation = 0; anim.blit(gmenu2x->s,0,0); gmenu2x->s->box(gmenu2x->w - animation, gmenu2x->listRect.y, gmenu2x->skinConfInt["previewWidth"] + 2 * padding, gmenu2x->listRect.h, gmenu2x->skinConfColors[COLOR_PREVIEW_BG]); gmenu2x->s->flip(); SDL_Delay(10); }; } else { // show preview if (!gmenu2x->sc.exists(preview + "scaled")) { Surface *previm = new Surface(preview); gmenu2x->sc.add(previm, preview + "scaled"); if (gmenu2x->confStr["bgscale"] == "Stretch") gmenu2x->sc[preview + "scaled"]->softStretch(gmenu2x->skinConfInt["previewWidth"], gmenu2x->listRect.h - 2 * padding, SScaleStretch); else if (gmenu2x->confStr["bgscale"] == "Crop") gmenu2x->sc[preview + "scaled"]->softStretch(gmenu2x->skinConfInt["previewWidth"], gmenu2x->listRect.h - 2 * padding, SScaleMax); else if (gmenu2x->confStr["bgscale"] == "Aspect") gmenu2x->sc[preview + "scaled"]->softStretch(gmenu2x->skinConfInt["previewWidth"], gmenu2x->listRect.h - 2 * padding, SScaleFit); } do { animation += gmenu2x->skinConfInt["previewWidth"] / 8; if (animation > gmenu2x->skinConfInt["previewWidth"] + 2 * padding) animation = gmenu2x->skinConfInt["previewWidth"] + 2 * padding; anim.blit(gmenu2x->s,0,0); gmenu2x->s->box(gmenu2x->w - animation, gmenu2x->listRect.y, gmenu2x->skinConfInt["previewWidth"] + 2 * padding, gmenu2x->listRect.h, gmenu2x->skinConfColors[COLOR_PREVIEW_BG]); gmenu2x->sc[preview + "scaled"]->blit(gmenu2x->s, {gmenu2x->w - animation + padding, gmenu2x->listRect.y + padding, gmenu2x->skinConfInt["previewWidth"], gmenu2x->listRect.h - 2 * padding}, HAlignCenter | VAlignMiddle, gmenu2x->h); gmenu2x->s->flip(); SDL_Delay(10); } while (animation < gmenu2x->skinConfInt["previewWidth"] + 2 * padding); } } gmenu2x->drawScrollBar(numRows, size(), firstElement, gmenu2x->listRect); gmenu2x->s->flip(); } do { inputAction = gmenu2x->input.update(); } while (!inputAction); if (gmenu2x->inputCommonActions(inputAction)) continue; SDL_RemoveTimer(alphanum_timer); alphanum_timer = NULL; if (gmenu2x->input[UP] || gmenu2x->input.hatEvent(DUP) == DUP) { selected--; preview = getPreview(selected); } else if (gmenu2x->input[DOWN] || gmenu2x->input.hatEvent(DDOWN) == DDOWN) { selected++; preview = getPreview(selected); } else if (gmenu2x->input[LEFT] || gmenu2x->input.hatEvent(DLEFT) == DLEFT) { selected -= numRows; if (selected < 0) selected = 0; preview = getPreview(selected); } else if (gmenu2x->input[RIGHT] || gmenu2x->input.hatEvent(DRIGHT) == DRIGHT) { selected += numRows; if (selected >= this->size()) selected = this->size() - 1; preview = getPreview(selected); } else if (gmenu2x->input[PAGEDOWN]) { alphanum_timer = SDL_AddTimer(1500, hideAlphaNum, (void*)false); int cur = toupper(getFileName(selected).at(0)); while ((selected < this->size() - 1) && ++selected && cur == toupper(getFileName(selected).at(0))) { } preview = getPreview(selected); } else if (gmenu2x->input[PAGEUP]) { alphanum_timer = SDL_AddTimer(1500, hideAlphaNum, (void*)false); int cur = toupper(getFileName(selected).at(0)); while (selected > 0 && selected-- && cur == toupper(getFileName(selected).at(0))) { } preview = getPreview(selected); } else if (showDirectories && allowDirUp && (gmenu2x->input[MODIFIER] && !gmenu2x->input[MANUAL] || (gmenu2x->input[CONFIRM] && getFile(selected) == ".."))) { /*Directory Up */ selected = 0; preview = ""; if (browse_history.size() > 0) { selected = browse_history.back(); browse_history.pop_back(); } directoryEnter(path + "/.."); } else if (gmenu2x->input[CONFIRM]) { if (allowEnterDirectory && isDirectory(selected)) { browse_history.push_back(selected); directoryEnter(getFilePath(selected)); selected = 0; } else { return true; } } else if (gmenu2x->input[SETTINGS] && allowSelectDirectory) { return true; } else if (gmenu2x->input[CANCEL] || gmenu2x->input[SETTINGS]) { if (!((gmenu2x->confStr["previewMode"] != "Backdrop") && !(preview.empty() || preview == "#"))) return false; // close only if preview is empty. preview = ""; } else if (gmenu2x->input[MANUAL] && !gmenu2x->input[MODIFIER]) { alphanum_timer = SDL_AddTimer(1500, hideAlphaNum, (void*)false); selected = (rand() % fileCount()) + dirCount(); preview = getPreview(selected); } else if (gmenu2x->input[MENU]) { contextMenu(); preview = getPreview(selected); } } } void BrowseDialog::directoryEnter(const string &path) { gmenu2x->input.dropEvents(); // prevent passing input away gmenu2x->powerManager->clearTimer(); this->description = path; buttons.clear(); buttons.push_back({"skin:imgs/manual.png", gmenu2x->tr["Loading.. Please wait.."]}); drawDialog(gmenu2x->s); SDL_TimerID flipScreenTimer = SDL_AddTimer(500, GMenu2X::timerFlip, (void*)false); setPath(path); browse(); onChangeDir(); SDL_RemoveTimer(flipScreenTimer); flipScreenTimer = NULL; gmenu2x->powerManager->resetSuspendTimer(); } const std::string BrowseDialog::getFileName(uint32_t i) { return getFile(i); } const std::string BrowseDialog::getParams(uint32_t i) { return ""; } const std::string BrowseDialog::getPreview(uint32_t i) { string ext = getExt(i); if (ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".gif" || ext == ".bmp") return getFilePath(i); return ""; } void BrowseDialog::contextMenu() { vector<MenuOption> options; string ext = getExt(selected); customOptions(options); if (ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".gif" || ext == ".bmp") options.push_back((MenuOption){gmenu2x->tr["Set as wallpaper"], MakeDelegate(this, &BrowseDialog::setWallpaper)}); if (path == "/roms" && getFile(selected) != ".." && isDirectory(selected)) options.push_back((MenuOption){gmenu2x->tr["Umount"], MakeDelegate(this, &BrowseDialog::umountDir)}); if (path != CARD_ROOT) options.push_back((MenuOption){gmenu2x->tr["Go to"] + " " + CARD_ROOT, MakeDelegate(this, &BrowseDialog::exploreHome)}); if (path != "/mnt/roms") options.push_back((MenuOption){gmenu2x->tr["Go to"] + " /mnt/roms", MakeDelegate(this, &BrowseDialog::exploreMedia)}); if (isFile(selected)) options.push_back((MenuOption){gmenu2x->tr["Delete"], MakeDelegate(this, &BrowseDialog::deleteFile)}); MessageBox mb(gmenu2x, options); } void BrowseDialog::deleteFile() { MessageBox mb(gmenu2x, gmenu2x->tr["Delete"] + " '" + getFile(selected) + "'\n" + gmenu2x->tr["THIS CAN'T BE UNDONE"] + "\n" + gmenu2x->tr["Are you sure?"], "explorer.png"); mb.setButton(MANUAL, gmenu2x->tr["Yes"]); mb.setButton(CANCEL, gmenu2x->tr["No"]); if (mb.exec() != MANUAL) return; if (!unlink(getFilePath(selected).c_str())) { directoryEnter(path); // refresh sync(); } } void BrowseDialog::umountDir() { string umount = "sync; umount -fl " + getFilePath(selected) + " && rm -r " + getFilePath(selected); system(umount.c_str()); directoryEnter(path); // refresh } void BrowseDialog::exploreHome() { selected = 0; directoryEnter(CARD_ROOT); } void BrowseDialog::exploreMedia() { selected = 0; directoryEnter("/mnt/roms"); } void BrowseDialog::setWallpaper() { string src = getFilePath(selected); string dst = "skins/Default/wallpapers/Wallpaper" + file_ext(src, true); if (file_copy(src, dst)) { gmenu2x->confStr["wallpaper"] = dst; gmenu2x->writeConfig(); gmenu2x->setBackground(gmenu2x->bg, dst); this->exec(); } }
11,488
C++
.cpp
261
40.440613
237
0.672068
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,062
inputmanager.cpp
MiyooCFW_gmenu2x/src/inputmanager.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "debug.h" #include "inputmanager.h" #include "utilities.h" #include "gmenu2x.h" #include <fstream> using namespace std; extern uint8_t numJoy; // number of connected joysticks enum InputManagerMappingTypes { MAPPING_TYPE_BUTTON, MAPPING_TYPE_AXIS, MAPPING_TYPE_KEYPRESS }; static SDL_TimerID timer = NULL; uint8_t *keystate = SDL_GetKeyState(NULL); InputManager::InputManager() {} InputManager::~InputManager() { SDL_RemoveTimer(timer); timer = NULL; for (uint32_t x = 0; x < joysticks.size(); x++) if (SDL_JoystickOpened(x)) SDL_JoystickClose(joysticks[x]); } void InputManager::initJoysticks(bool reinit) { if (reinit) { SDL_QuitSubSystem(SDL_INIT_JOYSTICK); SDL_InitSubSystem(SDL_INIT_JOYSTICK); } joysticks.clear(); int nj = SDL_NumJoysticks(); INFO("%d joysticks found", nj); for (int x = 0; x < nj; x++) { SDL_Joystick *joy = SDL_JoystickOpen(x); if (joy) { INFO("Initialized joystick: '%s'", SDL_JoystickName(x)); joysticks.push_back(joy); } else WARNING("Failed to initialize joystick: %i", x); } } void InputManager::init(const string &conffile) { setActionsCount(NUM_ACTIONS); initJoysticks(false); SDL_EnableKeyRepeat(0, 0); if (!file_exists(conffile)) { ERROR("File not found: %s", conffile.c_str()); return; } ifstream inf(conffile.c_str(), ios_base::in); if (!inf.is_open()) { ERROR("Could not open %s", conffile.c_str()); return; } int action, linenum = 0; string line, name, value; string::size_type pos; vector<string> values; for (uint32_t x = UDC_CONNECT; x < NUM_ACTIONS; x++) { InputMap map; map.type = MAPPING_TYPE_KEYPRESS; map.value = x - UDC_CONNECT + SDLK_WORLD_0; actions[x].maplist.push_back(map); } while (getline(inf, line, '\n')) { linenum++; pos = line.find("="); name = trim(line.substr(0, pos)); value = trim(line.substr(pos + 1)); if (name == "up") action = UP; else if (name == "down") action = DOWN; else if (name == "left") action = LEFT; else if (name == "right") action = RIGHT; else if (name == "modifier") action = MODIFIER; else if (name == "confirm") action = CONFIRM; else if (name == "cancel") action = CANCEL; else if (name == "manual") action = MANUAL; else if (name == "dec") action = DEC; else if (name == "inc") action = INC; else if (name == "section_prev") action = SECTION_PREV; else if (name == "section_next") action = SECTION_NEXT; else if (name == "pageup") action = PAGEUP; else if (name == "pagedown") action = PAGEDOWN; else if (name == "settings") action = SETTINGS; else if (name == "volup") action = VOLUP; else if (name == "voldown") action = VOLDOWN; else if (name == "backlight") action = BACKLIGHT; else if (name == "power") action = POWER; else if (name == "menu") action = MENU; else if (name == "speaker") {} else { ERROR("%s:%d Unknown action '%s'.", conffile.c_str(), linenum, name.c_str()); continue; } split(values, value, ","); if (values.size() >= 2) { if (values[0] == "joystickbutton" && values.size() == 3) { InputMap map; map.type = MAPPING_TYPE_BUTTON; map.num = atoi(values[1].c_str()); map.value = atoi(values[2].c_str()); map.treshold = 0; actions[action].maplist.push_back(map); // INFO("ADDING: joystickbutton %d %d ", map.num, map.value); } else if (values[0] == "joystickaxis" && values.size() == 4) { InputMap map; map.type = MAPPING_TYPE_AXIS; map.num = atoi(values[1].c_str()); map.value = atoi(values[2].c_str()); map.treshold = atoi(values[3].c_str()); actions[action].maplist.push_back(map); } else if (values[0] == "keyboard") { InputMap map; map.type = MAPPING_TYPE_KEYPRESS; map.value = atoi(values[1].c_str()); actions[action].maplist.push_back(map); } else { ERROR("%s:%d Invalid syntax or unsupported mapping type '%s'.", conffile.c_str(), linenum, value.c_str()); continue; } } else { ERROR("%s:%d Every definition must have at least 2 values (%s).", conffile.c_str(), linenum, value.c_str()); continue; } } inf.close(); } void InputManager::setActionsCount(int count) { actions.clear(); for (int x = 0; x < count; x++) { InputManagerAction action; action.active = false; action.interval = 150; actions.push_back(action); } } bool InputManager::update(bool wait) { bool anyactions = false; uint32_t x; SDL_Event event; SDL_JoystickUpdate(); if (wait) SDL_WaitEvent(&event); else if (!SDL_PollEvent(&event)) return false; if (timer && (event.type == SDL_JOYAXISMOTION || event.type == SDL_JOYHATMOTION)) { dropEvents(false); return false; } dropEvents(); x = event.key.keysym.sym; if (!x) x = event.key.keysym.scancode; switch (event.type) { case SDL_KEYDOWN: keystate[x] = true; break; case SDL_KEYUP: anyactions = true; keystate[x] = false; break; case SDL_JOYHATMOTION: { Uint8 hatState; for (int j = 0; j < joysticks.size(); j++) { hatState = SDL_JoystickGetHat(joysticks[j], 0); } switch (hatState) { case SDL_HAT_CENTERED: dropEvents(); return false; case SDL_HAT_UP: up = true; break; case SDL_HAT_DOWN: down = true; break; case SDL_HAT_LEFT: left = true; break; case SDL_HAT_RIGHT: right = true; break; } anyactions = true; break; } case SDL_USEREVENT: if (event.user.code == WAKE_UP) anyactions = true; break; } int active = -1; for (x = 0; x < actions.size(); x++) { actions[x].active = isActive(x); if (actions[x].active) { memcpy(input_combo, input_combo + 1, sizeof(input_combo) - 1); input_combo[sizeof(input_combo) - 1] = x; // eegg anyactions = true; active = x; } } if (active >= 0) { SDL_RemoveTimer(timer); timer = SDL_AddTimer(actions[active].interval, wakeUp, (void*)false); } x = 0; while (SDL_PollEvent(&event) && x++ < 30) { if (event.type == SDL_KEYUP || event.type == SDL_KEYDOWN) { keystate[event.key.keysym.sym] = false; } } return anyactions; } bool InputManager::combo() { // eegg return !memcmp(input_combo, konami, sizeof(input_combo)); } int InputManager::hatEvent(int hat_action) { // use joystick hat position or 3rd analog (e.g. D-pad) switch (hat_action) { case DUP: if (up) return DUP; break; case DDOWN: if (down) return DDOWN; break; case DLEFT: if (left) return DLEFT; break; case DRIGHT: if (right) return DRIGHT; break; default: return -1; break; } return -1; } void InputManager::dropEvents(bool drop_timer) { down = up = left = right = false; if (drop_timer) { SDL_RemoveTimer(timer); timer = NULL; } for (uint32_t x = 0; x < actions.size(); x++) { actions[x].active = false; } } uint32_t pushEventEnd(uint32_t interval, void *action) { SDL_Event event; event.type = SDL_KEYUP; event.key.state = SDL_RELEASED; event.key.keysym.sym = (SDLKey)((size_t)action - UDC_CONNECT + SDLK_WORLD_0); SDL_PushEvent(&event); return 0; } void InputManager::pushEvent(int action) { WARNING("EVENT START"); SDL_Event event; event.type = SDL_KEYDOWN; event.key.state = SDL_PRESSED; event.key.keysym.sym = (SDLKey)(action - UDC_CONNECT + SDLK_WORLD_0); SDL_PushEvent(&event); SDL_AddTimer(50, pushEventEnd, (void*)action); } int InputManager::count() { return actions.size(); } void InputManager::setInterval(int ms, int action) { if (action < 0) for (uint32_t x = 0; x < actions.size(); x++) actions[x].interval = ms; else if ((uint32_t)action < actions.size()) actions[action].interval = ms; } uint32_t InputManager::wakeUp(uint32_t interval, void *repeat) { SDL_RemoveTimer(timer); timer = NULL; SDL_Event event; event.type = SDL_USEREVENT; event.user.code = WAKE_UP; SDL_PushEvent(&event); // if ((bool*) repeat) return interval; return 0; } bool &InputManager::operator[](int action) { // if (action<0 || (uint32_t)action>=actions.size()) return false; return actions[action].active; } bool InputManager::isActive(int action) { MappingList mapList = actions[action].maplist; for (MappingList::const_iterator it = mapList.begin(); it != mapList.end(); ++it) { InputMap map = *it; switch (map.type) { case MAPPING_TYPE_BUTTON: for (int j = 0; j < joysticks.size(); j++) { if (SDL_JoystickGetButton(joysticks[j], map.value)) return true; } break; case MAPPING_TYPE_AXIS: if (map.num < joysticks.size()) { int axyspos = SDL_JoystickGetAxis(joysticks[map.num], map.value); if (map.treshold < 0 && axyspos < map.treshold) return true; if (map.treshold > 0 && axyspos > map.treshold) return true; } break; case MAPPING_TYPE_KEYPRESS: if (keystate[map.value]) return true; break; } } return false; }
10,288
C++
.cpp
321
29.034268
115
0.621385
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,063
filelister.cpp
MiyooCFW_gmenu2x/src/filelister.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ //for browsing the filesystem #include <sys/stat.h> #include <dirent.h> #include <algorithm> #include "filelister.h" #include "utilities.h" #include "gmenu2x.h" #include "debug.h" using namespace std; FileLister::FileLister(const string &startPath, bool showDirectories, bool showFiles): showDirectories(showDirectories), showFiles(showFiles) { setPath(startPath); } void FileLister::browse() { directories.clear(); files.clear(); if (showDirectories || showFiles) { if (showDirectories && path != "/" && allowDirUp) directories.push_back(".."); vector<string> vfilter; split(vfilter, getFilter(), ","); struct stat st; struct dirent **dptr; int i = 0, n = scandir(path.c_str(), &dptr, NULL, alphasort); if (n < 0) { ERROR("scandir(%s)", path.c_str()); return; } while (++i < n) { string file = dptr[i]->d_name; if (file[0] == '.' || (find(excludes.begin(), excludes.end(), file) != excludes.end())) continue; if (!((dptr[i]->d_type & DT_REG) || (dptr[i]->d_type & DT_DIR))) { string filepath = path + "/" + file; if (stat(filepath.c_str(), &st) == -1) { ERROR("Stat failed on '%s': '%s'", filepath.c_str(), strerror(errno)); continue; } if (S_ISDIR(st.st_mode)) { dptr[i]->d_type |= DT_DIR; } else { dptr[i]->d_type |= DT_REG; } } if (dptr[i]->d_type & DT_DIR) { if (showDirectories) directories.push_back(file); // warning: do not merge the _if_ } else if (showFiles) { for (vector<string>::iterator it = vfilter.begin(); it != vfilter.end(); ++it) { if (vfilter.size() > 1 && it->length() == 0 && (int32_t)file.rfind(".") >= 0) { continue; } if (it->length() <= file.length()) { if (!strcasecmp(file.substr(file.size() - it->length()).c_str(), it->c_str())) { files.push_back(file); break; } } } } free(dptr[i]); } free(dptr); } } void FileLister::setPath(const string &path) { this->path = real_path(path); } void FileLister::setFilter(const string &filter) { this->filter = filter; } uint32_t FileLister::size() { return files.size() + directories.size(); } uint32_t FileLister::dirCount() { return directories.size(); } uint32_t FileLister::fileCount() { return files.size(); } string FileLister::operator[](uint32_t x) { return getFile(x); } string FileLister::getFile(uint32_t x) { if (x >= size()) return ""; if (x < directories.size()) return directories[x]; return files[x - directories.size()]; } const string FileLister::getFilePath(uint32_t i) { return getPath() + "/" + getFile(i); } const string FileLister::getExt(uint32_t i) { return file_ext(getFile(i), true); } bool FileLister::isFile(uint32_t x) { return x >= directories.size() && x < size(); } bool FileLister::isDirectory(uint32_t x) { return x < directories.size(); } void FileLister::insertFile(const string &file) { files.insert(files.begin(), file); } void FileLister::addExclude(const string &exclude) { if (exclude == "..") allowDirUp = false; excludes.push_back(exclude); }
4,460
C++
.cpp
124
33.209677
90
0.577181
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,064
surface.cpp
MiyooCFW_gmenu2x/src/surface.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "surface.h" #include "fonthelper.h" #include "utilities.h" #include "debug.h" #include <cassert> RGBAColor strtorgba(const string &strColor) { const int s = (strColor.at(0) == '#') ? 1 : 0; RGBAColor c = {0,0,0,255}; c.r = constrain(strtol(strColor.substr(0 + s, 2).c_str(), NULL, 16), 0, 255); c.g = constrain(strtol(strColor.substr(2 + s, 2).c_str(), NULL, 16), 0, 255); c.b = constrain(strtol(strColor.substr(4 + s, 2).c_str(), NULL, 16), 0, 255); c.a = constrain(strtol(strColor.substr(6 + s, 2).c_str(), NULL, 16), 0, 255); return c; } string rgbatostr(RGBAColor color) { char hexcolor[10]; snprintf(hexcolor, sizeof(hexcolor), "#%02x%02x%02x%02x", color.r, color.g, color.b, color.a); return (string)hexcolor; } SDL_Color rgbatosdl(RGBAColor color) { return (SDL_Color){color.r, color.g, color.b, color.a}; } Surface::Surface() { raw = NULL; dblbuffer = NULL; } Surface::Surface(void *s, size_t &size) { SDL_RWops *rw = SDL_RWFromMem(s, size); SDL_Surface *_raw = IMG_Load_RW(rw, 1); raw = SDL_DisplayFormatAlpha(_raw); SDL_FreeSurface(_raw); } Surface::Surface(const string &img, bool alpha, const string &skin) { raw = NULL; dblbuffer = NULL; load(img, alpha, skin); halfW = raw->w/2; halfH = raw->h/2; } Surface::Surface(const string &img, const string &skin, bool alpha) { raw = NULL; dblbuffer = NULL; load(img, alpha, skin); halfW = raw->w/2; halfH = raw->h/2; } Surface::Surface(SDL_Surface *s, SDL_PixelFormat *fmt, uint32_t flags) { dblbuffer = NULL; this->operator =(s); // if (fmt != NULL || flags != 0) { if (fmt == NULL) fmt = s->format; if (flags == 0) flags = s->flags; raw = SDL_ConvertSurface(s, fmt, flags); // } } Surface::Surface(Surface *s) { dblbuffer = NULL; this->operator =(s->raw); } Surface::Surface(int w, int h, uint32_t flags) { dblbuffer = NULL; uint32_t rmask, gmask, bmask, amask; #if SDL_BYTEORDER == SDL_BIG_ENDIAN rmask = 0xff000000; gmask = 0x00ff0000; bmask = 0x0000ff00; amask = 0x000000ff; #else rmask = 0x000000ff; gmask = 0x0000ff00; bmask = 0x00ff0000; amask = 0xff000000; #endif SDL_Surface* _raw = SDL_CreateRGBSurface(flags, w, h, 16, rmask, gmask, bmask, amask); raw = SDL_DisplayFormat(_raw); SDL_FreeSurface(_raw); //SDL_SetAlpha(raw, SDL_SRCALPHA|SDL_RLEACCEL, SDL_ALPHA_OPAQUE); halfW = w/2; halfH = h/2; } Surface::~Surface() { free(); } void Surface::enableVirtualDoubleBuffer(SDL_Surface *surface) { dblbuffer = surface; SDL_Surface* _raw = SDL_CreateRGBSurface(SDL_SWSURFACE, dblbuffer->w, dblbuffer->h, 16, 0, 0, 0, 0); raw = SDL_DisplayFormat(_raw); SDL_FreeSurface(_raw); } void Surface::enableAlpha() { SDL_Surface *alpha_surface = SDL_DisplayFormatAlpha(raw); SDL_FreeSurface(raw); raw = alpha_surface; } void Surface::free() { SDL_FreeSurface(raw); SDL_FreeSurface(dblbuffer); raw = NULL; dblbuffer = NULL; } SDL_PixelFormat *Surface::format() { if (raw == NULL) return NULL; else return raw->format; } void Surface::load(const string &img, bool alpha, string skin) { free(); if (!skin.empty() && !img.empty() && img[0]!='/') { skin = "skins/" + skin + "/" + img; if (!file_exists(skin)) skin = "skins/Default/" + img; } else { skin = img; } raw = IMG_Load(skin.c_str()); if (raw == NULL) { ERROR("Couldn't load surface '%s'", img.c_str()); uint32_t rmask, gmask, bmask, amask; #if SDL_BYTEORDER == SDL_BIG_ENDIAN rmask = 0xff000000; gmask = 0x00ff0000; bmask = 0x0000ff00; amask = 0x000000ff; #else rmask = 0x000000ff; gmask = 0x0000ff00; bmask = 0x00ff0000; amask = 0xff000000; #endif SDL_Surface* _raw = SDL_CreateRGBSurface(SDL_SWSURFACE | SDL_SRCALPHA, 16, 16, 16, rmask, gmask, bmask, amask); raw = SDL_DisplayFormat(_raw); SDL_FreeSurface(_raw); } if (alpha) enableAlpha(); } void Surface::lock() { if (SDL_MUSTLOCK(raw) && !locked) { if (SDL_LockSurface(raw) < 0) { ERROR("Can't lock surface: '%s'", SDL_GetError()); SDL_Quit(); } locked = true; } } void Surface::unlock() { if (SDL_MUSTLOCK(raw) && locked) { SDL_UnlockSurface(raw); locked = false; } } void Surface::flip() { if (dblbuffer != NULL) { SDL_BlitSurface(raw, NULL, dblbuffer, NULL); SDL_Flip(dblbuffer); } else { SDL_Flip(raw); } } void Surface::putPixel(int x, int y, RGBAColor color) { putPixel(x,y, SDL_MapRGBA(raw->format, color.r, color.g, color.b, color.a)); } void Surface::putPixel(int x, int y, uint32_t color) { //determine position char* pPosition = (char*) raw->pixels; //offset by y pPosition += (raw->pitch * y); //offset by x pPosition += (raw->format->BytesPerPixel * x); //copy pixel data memcpy(pPosition, &color, raw->format->BytesPerPixel); } RGBAColor Surface::pixelColor(int x, int y) { RGBAColor color; uint32_t col = pixel(x,y); SDL_GetRGBA(col, raw->format, &color.r, &color.g, &color.b, &color.a); return color; } uint32_t Surface::pixel(int x, int y) { //determine position char* pPosition = (char*) raw->pixels; //offset by y pPosition += (raw->pitch * y); //offset by x pPosition += (raw->format->BytesPerPixel * x); //copy pixel data uint32_t col = 0; memcpy(&col, pPosition, raw->format->BytesPerPixel); return col; } void Surface::blendAdd(Surface *target, int x, int y) { RGBAColor targetcol, blendcol; for (int iy = 0; iy < raw->h; iy++) if (iy + y >= 0 && iy + y < target->raw->h) for (int ix = 0; ix < raw->w; ix++) { if (ix + x >= 0 && ix + x < target->raw->w) { blendcol = pixelColor(ix,iy); targetcol = target->pixelColor(ix + x, iy + y); targetcol.r = min(targetcol.r + blendcol.r, 255); targetcol.g = min(targetcol.g + blendcol.g, 255); targetcol.b = min(targetcol.b + blendcol.b, 255); target->putPixel(ix + x, iy + y, targetcol); } } /* uint32_t bcol, tcol; char *pPos, *tpPos; for (int iy=0; iy<raw->h; iy++) if (iy+y >= 0 && iy+y < target->raw->h) { pPos = (char*)raw->pixels + raw->pitch*iy; tpPos = (char*)target->raw->pixels + target->raw->pitch*(iy+y); for (int ix=0; ix<raw->w; ix++) { memcpy(&bcol, pPos, raw->format->BytesPerPixel); memcpy(&tcol, tpPos, target->raw->format->BytesPerPixel); //memcpy(tpPos, &bcol, target->raw->format->BytesPerPixel); pPos += raw->format->BytesPerPixel; tpPos += target->raw->format->BytesPerPixel; target->putPixel(ix+x,iy+y,bcol); } } */ } void Surface::write(FontHelper *font, const string &text, int x, int y, const uint8_t align) { font->write(this, text, x, y, align); } void Surface::write(FontHelper *font, const string &text, int x, int y, const uint8_t align, RGBAColor fgColor, RGBAColor bgColor) { font->write(this, text, x, y, align, fgColor, bgColor); } void Surface::write(FontHelper *font, const string &text, SDL_Rect &wrapRect, const uint8_t align) { font->write(this, text, wrapRect, align); } void Surface::operator = (SDL_Surface *s) { raw = SDL_DisplayFormat(s); halfW = raw->w/2; halfH = raw->h/2; } void Surface::operator = (Surface *s) { this->operator =(s->raw); } void Surface::box(SDL_Rect re, RGBAColor c) { if (c.a == 255) { SDL_FillRect(raw, &re, c.pixelValue(raw->format)); } else if (c.a != 0) { fillRectAlpha(re, c); } } void Surface::applyClipRect(SDL_Rect& rect) { SDL_Rect clip; SDL_GetClipRect(raw, &clip); // Clip along X-axis. if (rect.x < clip.x) { rect.w = max(rect.x + rect.w - clip.x, 0); rect.x = clip.x; } if (rect.x + rect.w > clip.x + clip.w) { rect.w = max(clip.x + clip.w - rect.x, 0); } // Clip along Y-axis. if (rect.y < clip.y) { rect.h = max(rect.y + rect.h - clip.y, 0); rect.y = clip.y; } if (rect.y + rect.h > clip.y + clip.h) { rect.h = max(clip.y + clip.h - rect.y, 0); } } static inline uint32_t mult8x4(uint32_t c, uint8_t a) { return ((((c >> 8) & 0x00FF00FF) * a) & 0xFF00FF00) | ((((c & 0x00FF00FF) * a) & 0xFF00FF00) >> 8); } void Surface::fillRectAlpha(SDL_Rect rect, RGBAColor c) { applyClipRect(rect); if (rect.w == 0 || rect.h == 0) { // Entire rectangle is outside clipping area. return; } if (SDL_MUSTLOCK(raw)) { if (SDL_LockSurface(raw) < 0) { return; } } SDL_PixelFormat *format = raw->format; uint32_t color = c.pixelValue(format); uint8_t alpha = c.a; uint8_t* edge = static_cast<uint8_t*>(raw->pixels) + rect.y * raw->pitch + rect.x * format->BytesPerPixel; // Blending: surf' = surf * (1 - alpha) + fill * alpha if (format->BytesPerPixel == 2) { uint32_t Rmask = format->Rmask; uint32_t Gmask = format->Gmask; uint32_t Bmask = format->Bmask; // Pre-multiply the fill color. We're hardcoding alpha to 1: 15/16bpp // modes are unlikely to have an alpha channel and even if they do, // the written alpha isn't used by gmenu2x. uint16_t f = (((color & Rmask) * alpha >> 8) & Rmask) | (((color & Gmask) * alpha >> 8) & Gmask) | (((color & Bmask) * alpha >> 8) & Bmask) | format->Amask; alpha = 255 - alpha; for (auto y = 0; y < rect.h; y++) { for (auto x = 0; x < rect.w; x++) { uint16_t& pixel = reinterpret_cast<uint16_t*>(edge)[x]; uint32_t R = ((pixel & Rmask) * alpha >> 8) & Rmask; uint32_t G = ((pixel & Gmask) * alpha >> 8) & Gmask; uint32_t B = ((pixel & Bmask) * alpha >> 8) & Bmask; pixel = uint16_t(R | G | B) + f; } edge += raw->pitch; } } else if (format->BytesPerPixel == 4) { // Assume the pixel format uses 8 bits per component; we don't care // which component is where since they all blend the same. uint32_t f = mult8x4(color, alpha); // pre-multiply the fill color alpha = 255 - alpha; for (auto y = 0; y < rect.h; y++) { for (auto x = 0; x < rect.w; x++) { uint32_t& pixel = reinterpret_cast<uint32_t*>(edge)[x]; pixel = mult8x4(pixel, alpha) + f; } edge += raw->pitch; } } else { assert(false); } if (SDL_MUSTLOCK(raw)) { SDL_UnlockSurface(raw); } } void Surface::rectangle(SDL_Rect re, RGBAColor c) { if (re.h >= 1) { // Top. box(SDL_Rect { re.x, re.y, re.w, 1 }, c); } if (re.h >= 2) { Sint16 ey = re.y + re.h - 1; // Bottom. box(SDL_Rect { re.x, ey, re.w, 1 }, c); Sint16 ex = re.x + re.w - 1; Sint16 sy = re.y + 1; Uint16 sh = re.h - 2; // Left. if (re.w >= 1) { box(SDL_Rect { re.x, sy, 1, sh }, c); } // Right. if (re.w >= 2) { box(SDL_Rect { ex, sy, 1, sh }, c); } } } void Surface::clearClipRect() { SDL_SetClipRect(raw, NULL); } void Surface::setClipRect(SDL_Rect rect) { SDL_SetClipRect(raw, &rect); } bool Surface::blit(Surface *destination, int x, int y, const uint8_t align, uint8_t alpha) { if (align & HAlignCenter) { x -= raw->w / 2; } else if (align & HAlignRight) { x -= raw->w; } if (align & VAlignMiddle) { y -= raw->h / 2; } else if (align & VAlignBottom) { y -= raw->h; } return blit(destination, {x, y, raw->w, raw->h}, HAlignLeft | VAlignTop, alpha); } bool Surface::blit(Surface *destination, SDL_Rect destrect, const uint8_t align, uint8_t alpha) { if (destination->raw == NULL || alpha == 0) return false; SDL_Rect srcrect = {0, 0, destrect.w, destrect.h}; if (align & HAlignCenter) { srcrect.x = (raw->w - srcrect.w) / 2; } else if (align & HAlignRight) { srcrect.x = raw->w - srcrect.w; } if (align & VAlignMiddle) { srcrect.y = (raw->h - srcrect.h) / 2; } else if (align & VAlignBottom) { srcrect.y = raw->h - srcrect.h; } if (alpha > 0 && alpha != raw->format->alpha) SDL_SetAlpha(raw, SDL_SRCALPHA | SDL_RLEACCEL, alpha); return SDL_BlitSurface(raw, &srcrect, destination->raw, &destrect); } void Surface::softStretch(uint16_t w, uint16_t h, uint8_t scale_mode) { float src_r = (float)raw->w / raw->h; float dst_r = (float)w / h; if (scale_mode & SScaleMax) { if (dst_r >= src_r) h = w / src_r; if (dst_r <= src_r) w = h * src_r; } else if (scale_mode & SScaleFit) { if (dst_r >= src_r) w = h * src_r; if (dst_r <= src_r) h = w / src_r; } SDL_Surface* _src = SDL_ConvertSurface(raw, raw->format, raw->flags); SDL_Surface* src = SDL_DisplayFormatAlpha(_src); SDL_FreeSurface(raw); SDL_Surface* _raw = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, 16, 0, 0, 0, 0); raw = SDL_DisplayFormatAlpha(_raw); SDL_SoftStretch(src, NULL, raw, NULL); SDL_FreeSurface(src); SDL_FreeSurface(_src); SDL_FreeSurface(_raw); } // Changes a surface's alpha value, by altering per-pixel alpha if necessary. void Surface::setAlpha(uint8_t alpha) { SDL_PixelFormat* fmt = raw->format; if (fmt->Amask == 0) { // If surface has no alpha channel, just set the surface alpha. SDL_SetAlpha(raw, SDL_SRCALPHA, alpha); } else { // Else change the alpha of each pixel. unsigned bpp = fmt->BytesPerPixel; float scale = alpha / 255.0f; // Scaling factor to clamp alpha to [0, alpha]. SDL_LockSurface(raw); for (int y = 0; y < raw->h; ++y) { for (int x = 0; x < raw->w; ++x) { // Get a pointer to the current pixel. Uint32* pixel_ptr = (Uint32 *)( (Uint8 *)raw->pixels + y * raw->pitch + x * bpp ); Uint8 r, g, b, a; SDL_GetRGBA(*pixel_ptr, fmt, &r, &g, &b, &a); // Get the old pixel components. *pixel_ptr = SDL_MapRGBA(fmt, r, g, b, scale * a); // Set the pixel with the new alpha. } } SDL_UnlockSurface(raw); } }
14,642
C++
.cpp
451
29.875831
132
0.621386
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,065
inputdialog.cpp
MiyooCFW_gmenu2x/src/inputdialog.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "inputdialog.h" #include "messagebox.h" #include "debug.h" using namespace std; using namespace fastdelegate; InputDialog::InputDialog(GMenu2X *gmenu2x, const string &text, const string &startvalue, const string &title, const string &icon): gmenu2x(gmenu2x) { gmenu2x->input.dropEvents(); // prevent passing input away if (title == "") { this->title = text; this->text = ""; } else { this->title = title; this->text = text; } this->icon = ""; if (icon != "" && gmenu2x->sc[icon] != NULL) this->icon = icon; input = startvalue; selCol = 0; selRow = 0; keyboard.resize(MAX_KB + 1); kb11 = gmenu2x->tr["_keyboard_en_t1_l1_"]; kb12 = gmenu2x->tr["_keyboard_en_t1_l2_"]; kb13 = gmenu2x->tr["_keyboard_en_t1_l3_"]; kb21 = gmenu2x->tr["_keyboard_en_t2_l1_"]; kb22 = gmenu2x->tr["_keyboard_en_t2_l2_"]; kb23 = gmenu2x->tr["_keyboard_en_t2_l3_"]; if (kb11 == "_keyboard_en_t1_l1_") kb11 = "qwertyuiop[]=789"; if (kb12 == "_keyboard_en_t1_l2_") kb12 = "asdfghjkl;'\\`456"; if (kb13 == "_keyboard_en_t1_l3_") kb13 = "zxcvbnm,./-=0123"; if (kb21 == "_keyboard_en_t2_l1_") kb21 = "QWERTYUIOP{}&*()"; if (kb22 == "_keyboard_en_t2_l2_") kb22 = "ASDFGHJKL:\"|~$%^"; if (kb23 == "_keyboard_en_t2_l3_") kb23 = "ZXCVBNM<>?_+\n!@#"; kb31 = kb11; kb32 = kb12; kb33 = kb13; kbc11 = gmenu2x->tr["_keyboard_t1_l1_"]; kbc12 = gmenu2x->tr["_keyboard_t1_l2_"]; kbc13 = gmenu2x->tr["_keyboard_t1_l3_"]; kbc21 = gmenu2x->tr["_keyboard_t2_l1_"]; kbc22 = gmenu2x->tr["_keyboard_t2_l2_"]; kbc23 = gmenu2x->tr["_keyboard_t2_l3_"]; kbc31 = gmenu2x->tr["_keyboard_t3_l1_"]; kbc32 = gmenu2x->tr["_keyboard_t3_l2_"]; kbc33 = gmenu2x->tr["_keyboard_t3_l3_"]; if (kbc11 == "_keyboard_t1_l1_") kbc11 = kb11; if (kbc12 == "_keyboard_t1_l2_") kbc12 = kb12; if (kbc13 == "_keyboard_t1_l3_") kbc13 = kb13; if (kbc21 == "_keyboard_t2_l1_") kbc21 = kb21; if (kbc22 == "_keyboard_t2_l2_") kbc22 = kb22; if (kbc23 == "_keyboard_t2_l3_") kbc23 = kb23; if (kbc31 == "_keyboard_t3_l1_") kbc31 = kb31; if (kbc32 == "_keyboard_t3_l2_") kbc32 = kb32; if (kbc33 == "_keyboard_t3_l3_") kbc33 = kb33; keyboard[0].push_back(kb11); keyboard[0].push_back(kb12); keyboard[0].push_back(kb13); keyboard[1].push_back(kb21); keyboard[1].push_back(kb22); keyboard[1].push_back(kb23); keyboard[2].push_back(kb31); keyboard[2].push_back(kb32); keyboard[2].push_back(kb33); keyboard[3].push_back(kbc11); keyboard[3].push_back(kbc12); keyboard[3].push_back(kbc13); keyboard[4].push_back(kbc21); keyboard[4].push_back(kbc22); keyboard[4].push_back(kbc23); keyboard[MAX_KB].push_back(kbc31); keyboard[MAX_KB].push_back(kbc32); keyboard[MAX_KB].push_back(kbc33); setKeyboard(0); } void InputDialog::setKeyboard(int kb) { kb = constrain(kb,0,keyboard.size()-1); curKeyboard = kb; this->kb = &(keyboard[kb]); kbLength = this->kb->at(0).length(); for (int x = 0, l = kbLength; x < l; x++) { if (gmenu2x->font->utf8Code(this->kb->at(0)[x])) { kbLength--; x++; } } kbLeft = (gmenu2x->w - kbLength * KEY_WIDTH) / 2; kbWidth = kbLength * KEY_WIDTH + 3; kbHeight = (this->kb->size()) * KEY_HEIGHT + 3; kbRect.x = kbLeft - 3; kbRect.y = gmenu2x->bottomBarRect.y - kbHeight; kbRect.w = kbWidth; kbRect.h = kbHeight; } bool InputDialog::exec() { string readWarning = gmenu2x->tr["Entering Text Dialog editor, press B to exit"]; gmenu2x->allyTTS(readWarning.c_str(), MEDIUM_GAP_TTS, MEDIUM_SPEED_TTS, 1); Surface *bg = new Surface(gmenu2x->s); SDL_Rect box = {gmenu2x->listRect.x + 2, 0, gmenu2x->listRect.w - 4, gmenu2x->font->getHeight() + 4}; box.y = kbRect.y - box.h; uint32_t caretTick = 0, curTick; bool caretOn = true; bg->box(gmenu2x->bottomBarRect, (RGBAColor){0,0,0,255}); gmenu2x->s->box(gmenu2x->bottomBarRect, gmenu2x->skinConfColors[COLOR_BOTTOM_BAR_BG]); string readValue = ""; string readTyped = gmenu2x->tr["Typed"] + " "; string altBtn = "x"; string altChar = gmenu2x->tr["Alt"]; string spaceChar = gmenu2x->tr["Space"]; string backspaceChar = gmenu2x->tr["Backspace"]; string shiftChar = gmenu2x->tr["Shift"]; string saveChar = gmenu2x->tr["Save"]; string exitChar = gmenu2x->tr["Exit"]; if (gmenu2x->tr.lang() == "") { altChar = ""; altBtn = ""; } int prevBarWidth = 0; while (bottomBarWidth >= gmenu2x->w) { bottomBarWidth = gmenu2x->drawButton(bg, "r", spaceChar) + gmenu2x->drawButton(bg, "l", backspaceChar) + gmenu2x->drawButton(bg, "y", shiftChar) + gmenu2x->drawButton(bg, altBtn, altChar) + gmenu2x->drawButton(bg, "start", saveChar) + gmenu2x->drawButton(bg, "b", exitChar) - 30; if (bottomBarWidth >= prevBarWidth && prevBarWidth != 0) { spaceChar = gmenu2x->tr["Space"]; backspaceChar = gmenu2x->tr["Backspace"]; break; } else if (bottomBarWidth < prevBarWidth && bottomBarWidth >= gmenu2x->w || bottomBarWidth < gmenu2x->w) { break; } else { spaceChar = "⎵" ; backspaceChar = "←"; } prevBarWidth = bottomBarWidth; } bg->box(gmenu2x->bottomBarRect, (RGBAColor){0,0,0,255}); gmenu2x->drawButton(bg, "r", spaceChar, gmenu2x->drawButton(bg, "l", backspaceChar, gmenu2x->drawButton(bg, "y", shiftChar, gmenu2x->drawButton(bg, altBtn, altChar, gmenu2x->drawButton(bg, "start", saveChar, gmenu2x->drawButton(bg, "b", exitChar )))))); while (true) { SDL_RemoveTimer(wakeUpTimer); wakeUpTimer = SDL_AddTimer(500, gmenu2x->input.wakeUp, (void*)false); bg->blit(gmenu2x->s,0,0); gmenu2x->s->box(gmenu2x->listRect.x, box.y - 2, gmenu2x->listRect.w, box.h + 2, (RGBAColor){0,0,0,220}); gmenu2x->s->box(box, (RGBAColor){0x33,0x33,0x33,220}); gmenu2x->s->setClipRect(box); gmenu2x->s->write(gmenu2x->font, input, box.x + box.w / 2, box.y + box.h / 2, HAlignCenter | VAlignMiddle, (RGBAColor){0xff,0xff,0xff,0xff}, (RGBAColor){0,0,0,200}); curTick = SDL_GetTicks(); if (curTick - caretTick >= 600) { caretOn = !caretOn; caretTick = curTick; } if (caretOn) gmenu2x->s->box(box.x + (box.w + gmenu2x->font->getTextWidth(input)) / 2, box.y + 3, 8, box.h - 6, (RGBAColor){0xff,0xff,0xff,220}); gmenu2x->s->clearClipRect(); // if (gmenu2x->f200) ts.poll(); // action = drawVirtualKeyboard(); gmenu2x->s->flip(); bool inputAction = gmenu2x->input.update(); if (!allyRead) { readValue = currKey(); gmenu2x->allyTTS(readValue.c_str()); allyRead = true; } if (gmenu2x->inputCommonActions(inputAction)) { continue; } if (gmenu2x->input[CANCEL] || gmenu2x->input[MENU]) return false; else if (gmenu2x->input[SETTINGS]) { string inputss; string::size_type position_newl_all = input.find("\n"); string::size_type pos = 0; uint32_t count = 0; while ((pos = input.find("\n", pos)) != std::string::npos) { ++count; pos += 2; } if (position_newl_all != std::string::npos) { string::size_type position_newl[365]; for (uint32_t i = 0; i <= count; i++) { // check if this is first chunk if (i == 0) position_newl[i] = input.find("\n"); else position_newl[i] = input.find("\n", position_newl[i-1] + 2); // genearate translation string from all chunks if (i == 0 && position_newl[i] != std::string::npos) inputss += trim(input.substr(0, position_newl[i])) + "\\n"; else if (position_newl[i] != std::string::npos) inputss += trim(input.substr(position_newl[i-1] + 1, position_newl[i] - position_newl[i-1] - 1)) + "\\n"; else inputss += trim(input.substr(position_newl[i-1])); } input = inputss; // } else { // input = trim(line.substr(position + 1)); } return true; } else if (gmenu2x->input[UP] || gmenu2x->input.hatEvent(DUP) == DUP) selRow--; else if (gmenu2x->input[DOWN] || gmenu2x->input.hatEvent(DDOWN) == DDOWN) selRow++; else if (gmenu2x->input[LEFT] || gmenu2x->input.hatEvent(DLEFT) == DLEFT) selCol--; else if (gmenu2x->input[RIGHT] || gmenu2x->input.hatEvent(DRIGHT) == DRIGHT) selCol++; else if (gmenu2x->input[CONFIRM]) confirm(); else if (gmenu2x->input[MANUAL] && !gmenu2x->input[MODIFIER]) changeKeys(); else if (gmenu2x->input[MODIFIER] && !gmenu2x->input[MANUAL]) changeKeysCustom(); else if (gmenu2x->input[SECTION_PREV]) backspace(); else if (gmenu2x->input[SECTION_NEXT]) space(); if ( gmenu2x->input[LEFT] || gmenu2x->input[RIGHT] || gmenu2x->input[UP] || gmenu2x->input[DOWN] || gmenu2x->input[MANUAL] || gmenu2x->input.hatEvent(DLEFT) == DLEFT || gmenu2x->input.hatEvent(DRIGHT) == DRIGHT || gmenu2x->input.hatEvent(DUP) == DUP || gmenu2x->input.hatEvent(DDOWN) == DDOWN ) { allyRead = false; } else if (gmenu2x->input[SECTION_NEXT]) { readValue = readTyped + gmenu2x->tr["Space"]; gmenu2x->allyTTS(readValue.c_str(), MEDIUM_GAP_TTS, MEDIUM_SPEED_TTS, 0); } else if (gmenu2x->input[SECTION_PREV]) { readValue = readTyped + gmenu2x->tr["Backspace"]; gmenu2x->allyTTS(readValue.c_str(), MEDIUM_GAP_TTS, MEDIUM_SPEED_TTS, 0); } else if (gmenu2x->input[CONFIRM]) { readValue = readTyped + currKey(); gmenu2x->allyTTS(readValue.c_str()); } } } void InputDialog::backspace() { // check for utf8 characters input = input.substr(0, input.length() - (gmenu2x->font->utf8Code(input[input.length() - 2]) ? 2 : 1)); } void InputDialog::space() { input += " "; } string InputDialog::currKey() { bool utf8; int xc=0; for (uint32_t x = 0; x < kb->at(selRow).length(); x++) { utf8 = gmenu2x->font->utf8Code(kb->at(selRow)[x]); if (xc == selCol) return kb->at(selRow).substr(x, utf8 ? 2 : 1); if (utf8) x++; xc++; } return ""; } void InputDialog::confirm() { input += currKey(); } void InputDialog::changeKeys() { int maxKb = MAX_KB; if (kb31 == kb11 && kb32 == kb12 && kb33 == kb13) maxKb = 4; if (!customKb) { if (curKeyboard >= maxKb / 2 - 1 && maxKb == 4 || curKeyboard >= maxKb / 2 && maxKb == MAX_KB) setKeyboard(maxKb / 2 - 2); else setKeyboard(curKeyboard + 1); } else { if (kbc31 != kb11 || kbc32 != kb12 || kbc33 != kb13) maxKb = MAX_KB; if (curKeyboard == maxKb) setKeyboard(MAX_KB - 2); else setKeyboard(curKeyboard + 1); } } void InputDialog::changeKeysCustom() { if (customKb) customKb = false; else customKb = true; if (curKeyboard == 0) setKeyboard(0 + 3); else if (curKeyboard == 1) setKeyboard(1 + 3); else if (curKeyboard == 2) setKeyboard(2 + 3); else if (curKeyboard == 3) setKeyboard(3 - 3); else if (curKeyboard == 4) setKeyboard(4 - 3); else if (curKeyboard == MAX_KB && kbc31 != kb11 || kbc32 != kb12 || kbc33 != kb13) setKeyboard(0); else if (curKeyboard == MAX_KB) setKeyboard(MAX_KB - 3); } int InputDialog::drawVirtualKeyboard() { // int action = ID_NO_ACTION; gmenu2x->s->box(gmenu2x->listRect.x, kbRect.y, gmenu2x->listRect.w, kbRect.h, (RGBAColor){0,0,0,220}); if (selCol < 0) selCol = selRow == (int)kb->size() ? 1 : kbLength - 1; if (selCol >= (int)kbLength) selCol = 0; if (selRow < 0) selRow = kb->size() - 1; if (selRow >= (int)kb->size()) selRow = 0; // selection // if (selRow < (int)kb->size()) gmenu2x->s->box(kbLeft + selCol * KEY_WIDTH, kbRect.y + 2 + selRow * KEY_HEIGHT, KEY_WIDTH - 1, KEY_HEIGHT - 2, (RGBAColor){0xff,0xff,0xff,220}); // keys for (uint32_t l = 0; l < kb->size(); l++) { string line = kb->at(l); for (uint32_t x = 0, xc = 0; x < line.length(); x++) { string charX; // utf8 characters if (gmenu2x->font->utf8Code(line[x])) { charX = line.substr(x,2); x++; } else { charX = line[x]; } SDL_Rect re = {kbLeft + xc * KEY_WIDTH, kbRect.y + 2 + l * KEY_HEIGHT, KEY_WIDTH - 1, KEY_HEIGHT - 2}; // if ts on rect, change selection // if (gmenu2x->f200 && ts.pressed() && ts.inRect(re)) { // selCol = xc; // selRow = l; // } gmenu2x->s->rectangle(re, (RGBAColor){0xff,0xff,0xff,220}); if (charX != "\n") gmenu2x->s->write(gmenu2x->font, charX, kbLeft + xc * KEY_WIDTH + KEY_WIDTH / 2, kbRect.y + 2 + l * KEY_HEIGHT + KEY_HEIGHT / 2 - 2, HAlignCenter | VAlignMiddle, (RGBAColor){0xff,0xff,0xff,0xff}, (RGBAColor){0,0,0,200}); else gmenu2x->s->write(gmenu2x->font, "⏎", kbLeft + xc * KEY_WIDTH + KEY_WIDTH / 2, kbRect.y + 2 + l * KEY_HEIGHT + KEY_HEIGHT / 2 - 2, HAlignCenter | VAlignMiddle, (RGBAColor){0xff,0xff,0xff,0xff}, (RGBAColor){0,0,0,200}); xc++; } } // if ts released // if (gmenu2x->f200 && ts.released() && ts.inRect(kbRect)) { // action = ID_ACTION_SELECT; // } return 0; //action; } InputDialog::~InputDialog() { SDL_RemoveTimer(wakeUpTimer); wakeUpTimer = NULL; gmenu2x->input.dropEvents(); // prevent passing input away }
13,950
C++
.cpp
336
38.625
224
0.623929
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,066
menu.cpp
MiyooCFW_gmenu2x/src/menu.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include <unistd.h> #include <sstream> #include <sys/stat.h> #include <sys/types.h> #include <dirent.h> #include <algorithm> #include <math.h> #include <fstream> #include "linkapp.h" #include "menu.h" #include "debug.h" #include "messagebox.h" #include "powermanager.h" #include "utilities.h" using namespace std; Menu::Menu(GMenu2X *gmenu2x): gmenu2x(gmenu2x) { iFirstDispSection = 0; readSections(); setSectionIndex(0); } Menu::~Menu() { freeLinks(); } void Menu::readSections() { DIR *dirp; struct dirent *dptr; mkdir("sections", 0777); if ((dirp = opendir("sections")) == NULL) { return; } sections.clear(); links.clear(); while ((dptr = readdir(dirp))) { if (dptr->d_name[0] == '.') { continue; } string filepath = (string)"sections/" + dptr->d_name; if (dir_exists(filepath)) { sections.push_back((string)dptr->d_name); linklist ll; links.push_back(ll); } } addSection("settings"); addSection("applications"); closedir(dirp); sort(sections.begin(),sections.end(), case_less()); } void Menu::readLinks() { vector<string> linkfiles; iLink = 0; iFirstDispRow = 0; DIR *dirp; struct dirent *dptr; for (uint32_t i = 0; i < links.size(); i++) { links[i].clear(); linkfiles.clear(); if ((dirp = opendir(sectionPath(i).c_str())) == NULL) { continue; } while ((dptr = readdir(dirp))) { if (dptr->d_name[0] == '.') { continue; } string filepath = sectionPath(i) + dptr->d_name; if (filepath.substr(filepath.size() - 5, 5) == "-opkg") { continue; } linkfiles.push_back(filepath); } sort(linkfiles.begin(), linkfiles.end(), case_less()); for (uint32_t x = 0; x < linkfiles.size(); x++) { LinkApp *link = new LinkApp(gmenu2x, linkfiles[x].c_str()); if (link->targetExists()) { links[i].push_back(link); } else { delete link; } } closedir(dirp); } } uint32_t Menu::firstDispRow() { return iFirstDispRow; } // SECTION MANAGEMENT void Menu::freeLinks() { for (vector<linklist>::iterator section = links.begin(); section < links.end(); section++) { for (linklist::iterator link = section->begin(); link < section->end(); link++) { delete *link; } } } linklist *Menu::sectionLinks(int i) { if (i < 0 || i > (int)links.size()) { i = selSectionIndex(); } if (i < 0 || i > (int)links.size()) { return NULL; } return &links[i]; } void Menu::decSectionIndex() { setSectionIndex(iSection - 1); } void Menu::incSectionIndex() { setSectionIndex(iSection + 1); } uint32_t Menu::firstDispSection() { return iFirstDispSection; } int Menu::selSectionIndex() { return iSection; } const string &Menu::selSection() { return sections[iSection]; } const string Menu::selSectionName() { string sectionname = sections[iSection]; string::size_type pos = sectionname.find("."); if (sectionname == "applications") { return "apps"; } if (sectionname == "emulators") { return "emus"; } if (pos != string::npos && pos > 0 && pos < sectionname.length()) { return sectionname.substr(pos + 1); } return sectionname; } int Menu::sectionNumItems() { if (gmenu2x->skinConfInt["sectionBar"] == SB_LEFT || gmenu2x->skinConfInt["sectionBar"] == SB_RIGHT) { return (gmenu2x->h - 40) / gmenu2x->skinConfInt["sectionBarSize"]; } if (gmenu2x->skinConfInt["sectionBar"] == SB_TOP || gmenu2x->skinConfInt["sectionBar"] == SB_BOTTOM) { return (gmenu2x->w - 40) / gmenu2x->skinConfInt["sectionBarSize"]; } return (gmenu2x->w / gmenu2x->skinConfInt["sectionBarSize"]) - 1; } void Menu::setSectionIndex(int i) { if (i < 0) { i = sections.size() - 1; } else if (i >= (int)sections.size()) { i = 0; } iSection = i; int numRows = sectionNumItems() - 1; if (i >= (int)iFirstDispSection + numRows) { iFirstDispSection = i - numRows; } else if (i < (int)iFirstDispSection) { iFirstDispSection = i; } iLink = 0; iFirstDispRow = 0; } string Menu::sectionPath(int section) { if (section < 0 || section > (int)sections.size()) { section = iSection; } return "sections/" + sections[section] + "/"; } // LINKS MANAGEMENT bool Menu::addActionLink(uint32_t section, const string &title, fastdelegate::FastDelegate0<> action, const string &description, const string &icon) { if (section >= sections.size()) { return false; } Link *linkact = new Link(gmenu2x, action); linkact->setTitle(title); linkact->setDescription(description); linkact->setIcon("skin:icons/" + icon); linkact->setBackdrop("skin:backdrops/" + icon); sectionLinks(section)->push_back(linkact); return true; } bool Menu::addLink(string exec) { string section = selSection(); string title = base_name(exec, true); string linkpath = unique_filename("sections/" + section + "/" + title, ".lnk"); // Reduce title length to fit the link width if ((int)gmenu2x->font->getTextWidth(title) > linkWidth) { while ((int)gmenu2x->font->getTextWidth(title + "..") > linkWidth) { title = title.substr(0, title.length() - 1); } title += ".."; } INFO("Adding link: '%s'", linkpath.c_str()); LinkApp *link = new LinkApp(gmenu2x, linkpath.c_str()); if (!exec.empty()) link->setExec(exec); if (!title.empty()) link->setTitle(title); link->save(); int isection = find(sections.begin(), sections.end(), section) - sections.begin(); if (isection >= 0 && isection < (int)sections.size()) { links[isection].push_back(link); setLinkIndex(links[isection].size() - 1); } return true; } bool Menu::addSection(const string &sectionName) { string sectiondir = "sections/" + sectionName; if (mkdir(sectiondir.c_str(), 0777) == 0) { sections.push_back(sectionName); linklist ll; links.push_back(ll); return true; } string tmpfile = sectiondir + "/.section"; FILE *fp = fopen(tmpfile.c_str(), "wb+"); if (fp) fclose(fp); return false; } void Menu::deleteSelectedLink() { string iconpath = selLink()->getIconPath(); INFO("Deleting link '%s'", selLink()->getTitle().c_str()); if (selLinkApp() != NULL) unlink(selLinkApp()->getFile().c_str()); sectionLinks()->erase(sectionLinks()->begin() + selLinkIndex()); setLinkIndex(selLinkIndex()); for (uint32_t i = 0; i < sections.size(); i++) { for (uint32_t j = 0; j < sectionLinks(i)->size(); j++) { if (iconpath == sectionLinks(i)->at(j)->getIconPath()) { return; // icon in use by another link; return here. } } } gmenu2x->sc.del(iconpath); } void Menu::deleteSelectedSection() { INFO("Deleting section '%s'", selSection().c_str()); string iconpath = "sections/" + selSection() + ".png"; links.erase(links.begin() + selSectionIndex()); sections.erase(sections.begin() + selSectionIndex()); setSectionIndex(0); //reload sections for (uint32_t i = 0; i < sections.size(); i++) { if (iconpath == getSectionIcon(i)) { return; // icon in use by another section; return here. } } gmenu2x->sc.del(iconpath); } bool Menu::linkChangeSection(uint32_t linkIndex, uint32_t oldSectionIndex, uint32_t newSectionIndex) { if (oldSectionIndex < sections.size() && newSectionIndex < sections.size() && linkIndex < sectionLinks(oldSectionIndex)->size()) { sectionLinks(newSectionIndex)->push_back(sectionLinks(oldSectionIndex)->at(linkIndex)); sectionLinks(oldSectionIndex)->erase(sectionLinks(oldSectionIndex)->begin() + linkIndex); // Select the same link in the new position setSectionIndex(newSectionIndex); setLinkIndex(sectionLinks(newSectionIndex)->size() - 1); return true; } return false; } void Menu::pageUp() { // PAGEUP with left if ((int)(iLink - linkRows - 1) < 0) { setLinkIndex(0); } else { setLinkIndex(iLink - linkRows + 1); } } void Menu::pageDown() { // PAGEDOWN with right if (iLink + linkRows > sectionLinks()->size()) { setLinkIndex(sectionLinks()->size() - 1); } else { setLinkIndex(iLink + linkRows - 1); } } void Menu::linkLeft() { setLinkIndex(iLink - 1); } void Menu::linkRight() { setLinkIndex(iLink + 1); } void Menu::linkUp() { int l = iLink - linkCols; if (l < 0) { uint32_t rows = (uint32_t)ceil(sectionLinks()->size() / (double)linkCols); l += (rows * linkCols); if (l >= (int)sectionLinks()->size()) { l -= linkCols; } } setLinkIndex(l); } void Menu::linkDown() { uint32_t l = iLink + linkCols; if (l >= sectionLinks()->size()) { uint32_t rows = (uint32_t)ceil(sectionLinks()->size() / (double)linkCols); uint32_t curCol = (uint32_t)ceil((iLink+1) / (double)linkCols); if (rows > curCol) { l = sectionLinks()->size() - 1; } else { l %= linkCols; } } setLinkIndex(l); } int Menu::selLinkIndex() { return iLink; } Link *Menu::selLink() { if (sectionLinks()->size() == 0) { return NULL; } return sectionLinks()->at(iLink); } LinkApp *Menu::selLinkApp() { return dynamic_cast<LinkApp*>(selLink()); } void Menu::setLinkIndex(int i) { if (i < 0) { i = sectionLinks()->size() - 1; } else if (i >= (int)sectionLinks()->size()) { i = 0; } int perPage = linkCols * linkRows; if (linkRows == 1) { if (i < iFirstDispRow) { iFirstDispRow = i; } else if (i >= iFirstDispRow + perPage) { iFirstDispRow = i - perPage + 1; } } else { int page = i / linkCols; if (i < iFirstDispRow) { iFirstDispRow = page * linkCols; } else if (i >= iFirstDispRow + perPage) { iFirstDispRow = page * linkCols - linkCols * (linkRows - 1); } } if (iFirstDispRow < 0) { iFirstDispRow = 0; } iLink = i; } void Menu::renameSection(int index, const string &name) { // section directory doesn't exists string oldsection = "sections/" + selSection(); string newsection = "sections/" + name; if (oldsection != newsection && rename(oldsection.c_str(), newsection.c_str()) == 0) { sections[index] = name; } } int Menu::getSectionIndex(const string &name) { return distance(sections.begin(), find(sections.begin(), sections.end(), name)); } const string Menu::getSectionIcon(int i) { if (i < 0) i = iSection; string sectionIcon = gmenu2x->sc.getSkinFilePath("sections/" + sections[i] + ".png", false); if (!sectionIcon.empty()) { return sectionIcon; } string::size_type pos = sections[i].rfind("."); if (pos != string::npos) { string subsectionIcon = gmenu2x->sc.getSkinFilePath("sections/" + sections[i].substr(pos) + ".png", false); if (!subsectionIcon.empty()) { return subsectionIcon; } } pos = sections[i].find("."); if (pos != string::npos) { string mainsectionIcon = gmenu2x->sc.getSkinFilePath("sections/" + sections[i].substr(0, pos) + ".png", false); if (!mainsectionIcon.empty()) { return mainsectionIcon; } } return gmenu2x->sc.getSkinFilePath("icons/section.png"); } void Menu::initLayout() { // LINKS rect gmenu2x->linksRect = (SDL_Rect){0, 0, gmenu2x->w, gmenu2x->h}; gmenu2x->sectionBarRect = (SDL_Rect){0, 0, gmenu2x->w, gmenu2x->h}; if (gmenu2x->skinConfInt["sectionBar"]) { if (gmenu2x->skinConfInt["sectionBar"] == SB_LEFT || gmenu2x->skinConfInt["sectionBar"] == SB_RIGHT) { gmenu2x->sectionBarRect.x = (gmenu2x->skinConfInt["sectionBar"] == SB_RIGHT) * (gmenu2x->w - gmenu2x->skinConfInt["sectionBarSize"]); gmenu2x->sectionBarRect.w = gmenu2x->skinConfInt["sectionBarSize"]; gmenu2x->linksRect.w = gmenu2x->w - gmenu2x->skinConfInt["sectionBarSize"]; if (gmenu2x->skinConfInt["sectionBar"] == SB_LEFT) { gmenu2x->linksRect.x = gmenu2x->skinConfInt["sectionBarSize"]; } } else { gmenu2x->sectionBarRect.y = (gmenu2x->skinConfInt["sectionBar"] == SB_BOTTOM) * (gmenu2x->h - gmenu2x->skinConfInt["sectionBarSize"]); gmenu2x->sectionBarRect.h = gmenu2x->skinConfInt["sectionBarSize"]; gmenu2x->linksRect.h = gmenu2x->h - gmenu2x->skinConfInt["sectionBarSize"]; if (gmenu2x->skinConfInt["sectionBar"] == SB_TOP || gmenu2x->skinConfInt["sectionBar"] == SB_CLASSIC) { gmenu2x->linksRect.y = gmenu2x->skinConfInt["sectionBarSize"]; } if (gmenu2x->skinConfInt["sectionBar"] == SB_CLASSIC) { gmenu2x->linksRect.h -= gmenu2x->skinConfInt["bottomBarHeight"]; } } } gmenu2x->listRect = (SDL_Rect){0, gmenu2x->skinConfInt["sectionBarSize"], gmenu2x->w, gmenu2x->h - gmenu2x->skinConfInt["bottomBarHeight"] - gmenu2x->skinConfInt["sectionBarSize"]}; gmenu2x->bottomBarRect = (SDL_Rect){0, gmenu2x->h - gmenu2x->skinConfInt["bottomBarHeight"], gmenu2x->w, gmenu2x->skinConfInt["bottomBarHeight"]}; // WIP linkCols = gmenu2x->skinConfInt["linkCols"]; linkRows = gmenu2x->skinConfInt["linkRows"]; linkWidth = (gmenu2x->linksRect.w - (linkCols + 1) * linkSpacing) / linkCols; linkHeight = (gmenu2x->linksRect.h - (linkCols > 1) * (linkRows + 1) * linkSpacing) / linkRows; } void Menu::drawList() { int i = firstDispRow(); int ix = gmenu2x->linksRect.x; for (int y = 0; y < linkRows && i < sectionLinks()->size(); y++, i++) { int iy = gmenu2x->linksRect.y + y * linkHeight; if (i == (uint32_t)selLinkIndex()) { gmenu2x->s->box(ix, iy, gmenu2x->linksRect.w, linkHeight, gmenu2x->skinConfColors[COLOR_SELECTION_BG]); } Surface *icon = gmenu2x->sc[sectionLinks()->at(i)->getIconPath()]; if (icon == NULL) { icon = gmenu2x->sc["skin:icons/generic.png"]; } if (icon->width() > 32 || icon->height() > linkHeight - 4) { icon->softStretch(32, linkHeight - 4, SScaleFit); } if (gmenu2x->skinConfInt["showLinkIcon"]) icon->blit(gmenu2x->s, {ix + 2, iy + 2, 32, linkHeight - 4}, HAlignCenter | VAlignMiddle); #if !defined(CHECK_TRANSLATION) gmenu2x->s->write(gmenu2x->titlefont, gmenu2x->tr[sectionLinks()->at(i)->getTitle()], ix + linkSpacing + 36, iy + gmenu2x->titlefont->getHeight()/2, VAlignMiddle); gmenu2x->s->write(gmenu2x->font, gmenu2x->tr[sectionLinks()->at(i)->getDescription()], ix + linkSpacing + 36, iy + linkHeight - linkSpacing/2, VAlignBottom); #else gmenu2x->s->write(gmenu2x->titlefont, sectionLinks()->at(i)->getTitle(), ix + linkSpacing + 36, iy + gmenu2x->titlefont->getHeight()/2, VAlignMiddle); gmenu2x->s->write(gmenu2x->font, sectionLinks()->at(i)->getDescription(), ix + linkSpacing + 36, iy + linkHeight - linkSpacing/2, VAlignBottom); #endif } if (sectionLinks()->size() > linkRows) { gmenu2x->drawScrollBar(1, sectionLinks()->size(), selLinkIndex(), gmenu2x->linksRect, HAlignRight); } } void Menu::drawGrid() { int i = firstDispRow(); for (int y = 0; y < linkRows; y++) { for (int x = 0; x < linkCols && i < sectionLinks()->size(); x++, i++) { int ix = gmenu2x->linksRect.x + x * linkWidth + (x + 1) * linkSpacing; int iy = gmenu2x->linksRect.y + y * linkHeight + (y + 1) * linkSpacing; Surface *icon = gmenu2x->sc[sectionLinks()->at(i)->getIconPath()]; if (icon == NULL) { icon = gmenu2x->sc["skin:icons/generic.png"]; } if (icon->width() > linkWidth || icon->height() > linkHeight) { icon->softStretch(linkWidth, linkHeight, SScaleFit); } if (i == (uint32_t)selLinkIndex()) { if (iconBGon != NULL && icon->width() <= iconBGon->width() && icon->height() <= iconBGon->height()) { iconBGon->blit(gmenu2x->s, ix + (linkWidth + iconPadding) / 2, iy + (linkHeight + iconPadding) / 2, HAlignCenter | VAlignMiddle, 50); } else { gmenu2x->s->box(ix + (linkWidth - min(linkWidth, icon->width())) / 2 - 4, iy + (linkHeight - min(linkHeight, icon->height())) / 2 - 4, min(linkWidth, icon->width()) + 8, min(linkHeight, icon->height()) + 8, gmenu2x->skinConfColors[COLOR_SELECTION_BG]); } } else if (iconBGoff != NULL && icon->width() <= iconBGoff->width() && icon->height() <= iconBGoff->height()) { iconBGoff->blit(gmenu2x->s, {ix + iconPadding/2, iy + iconPadding/2, linkWidth - iconPadding, linkHeight - iconPadding}, HAlignCenter | VAlignMiddle); } if (gmenu2x->skinConfInt["showLinkIcon"]) icon->blit(gmenu2x->s, {ix + iconPadding/2, iy + iconPadding/2, linkWidth - iconPadding, linkHeight - iconPadding}, HAlignCenter | VAlignMiddle); if (gmenu2x->skinConfInt["linkLabel"] || i == (uint32_t)selLinkIndex() && gmenu2x->confInt["skinBackdrops"] && (gmenu2x->currBackdrop == gmenu2x->sc.getSkinFilePath("backdrops/generic.png", false) /*|| gmenu2x->currBackdrop == gmenu2x->confStr["wallpaper"]*/)) { SDL_Rect labelRect; labelRect.x = ix + 2 + linkWidth/2; labelRect.y = iy + (linkHeight + min(linkHeight, icon->height()))/2; labelRect.w = linkWidth - iconPadding; labelRect.h = linkHeight - iconPadding; #if !defined(CHECK_TRANSLATION) gmenu2x->s->write(gmenu2x->font, gmenu2x->tr[sectionLinks()->at(i)->getTitle()], labelRect, HAlignCenter | VAlignMiddle); #else gmenu2x->s->write(gmenu2x->font, sectionLinks()->at(i)->getTitle(), labelRect, HAlignCenter | VAlignMiddle); #endif } } } if (linkRows == 1 && sectionLinks()->size() > linkCols) { gmenu2x->drawScrollBar(1, sectionLinks()->size(), selLinkIndex(), gmenu2x->linksRect, VAlignBottom); } else if (sectionLinks()->size() > linkCols * linkRows) { gmenu2x->drawScrollBar(1, sectionLinks()->size()/linkCols + 1, selLinkIndex()/linkCols, gmenu2x->linksRect, HAlignRight); } } void Menu::drawSectionBar() { gmenu2x->s->box(gmenu2x->sectionBarRect, gmenu2x->skinConfColors[COLOR_TOP_BAR_BG]); int ix = 0, iy = 0, sy = 0; int x = gmenu2x->sectionBarRect.x; int y = gmenu2x->sectionBarRect.y; int sx = (selSectionIndex() - firstDispSection()) * gmenu2x->skinConfInt["sectionBarSize"]; if (gmenu2x->skinConfInt["sectionBar"] == SB_CLASSIC) { ix = (gmenu2x->w - gmenu2x->skinConfInt["sectionBarSize"] * min(sectionNumItems(), getSections().size())) / 2; } for (int i = firstDispSection(); i < getSections().size() && i < firstDispSection() + sectionNumItems(); i++) { if (gmenu2x->skinConfInt["sectionBar"] == SB_LEFT || gmenu2x->skinConfInt["sectionBar"] == SB_RIGHT) { y = (i - firstDispSection()) * gmenu2x->skinConfInt["sectionBarSize"]; } else { x = (i - firstDispSection()) * gmenu2x->skinConfInt["sectionBarSize"] + ix; } if (selSectionIndex() == (int)i) { sx = x; sy = y; gmenu2x->s->box(sx, sy, gmenu2x->skinConfInt["sectionBarSize"], gmenu2x->skinConfInt["sectionBarSize"], gmenu2x->skinConfColors[COLOR_SELECTION_BG]); } gmenu2x->sc[getSectionIcon(i)]->blit(gmenu2x->s, {x, y, gmenu2x->skinConfInt["sectionBarSize"], gmenu2x->skinConfInt["sectionBarSize"]}, HAlignCenter | VAlignMiddle); } if (gmenu2x->skinConfInt["sectionLabel"] && SDL_GetTicks() - section_changed < 1400) { if (gmenu2x->skinConfInt["sectionBar"] == SB_LEFT) { gmenu2x->s->write(gmenu2x->font, gmenu2x->tr[selSectionName()], sx, sy + gmenu2x->skinConfInt["sectionBarSize"], HAlignLeft | VAlignBottom); } else if (gmenu2x->skinConfInt["sectionBar"] == SB_RIGHT) { gmenu2x->s->write(gmenu2x->font, gmenu2x->tr[selSectionName()], sx + gmenu2x->skinConfInt["sectionBarSize"], sy + gmenu2x->skinConfInt["sectionBarSize"], HAlignRight | VAlignBottom); } else { gmenu2x->s->write(gmenu2x->font, gmenu2x->tr[selSectionName()], sx + gmenu2x->skinConfInt["sectionBarSize"] / 2 , sy + gmenu2x->skinConfInt["sectionBarSize"], HAlignCenter | VAlignBottom); } } else { SDL_RemoveTimer(sectionChangedTimer); sectionChangedTimer = NULL; } if (gmenu2x->skinConfInt["sectionBar"] == SB_CLASSIC) { if (iconL != NULL) iconL->blit(gmenu2x->s, 0, 0, HAlignLeft | VAlignTop); if (iconR != NULL) iconR->blit(gmenu2x->s, gmenu2x->w, 0, HAlignRight | VAlignTop); } } void Menu::drawStatusBar() { int iconTrayShift = 0; const int iconWidth = 16, pctWidth = gmenu2x->font->getTextWidth("100"); char buf[32]; int x = 0; gmenu2x->s->box(gmenu2x->bottomBarRect, gmenu2x->skinConfColors[COLOR_BOTTOM_BAR_BG]); if (!iconDescription.empty() && SDL_GetTicks() - icon_changed < 300) { x = iconPadding; iconManual->blit(gmenu2x->s, x, gmenu2x->bottomBarRect.y + gmenu2x->bottomBarRect.h / 2, VAlignMiddle); x += iconWidth + iconPadding; #if !defined(CHECK_TRANSLATION) gmenu2x->s->write(gmenu2x->font, gmenu2x->tr[iconDescription].c_str(), x, gmenu2x->bottomBarRect.y + gmenu2x->bottomBarRect.h / 2, VAlignMiddle, gmenu2x->skinConfColors[COLOR_FONT_ALT], gmenu2x->skinConfColors[COLOR_FONT_ALT_OUTLINE]); #else gmenu2x->s->write(gmenu2x->font, gmenu2x->iconDescription.c_str(), x, gmenu2x->bottomBarRect.y + gmenu2x->bottomBarRect.h / 2, VAlignMiddle, gmenu2x->skinConfColors[COLOR_FONT_ALT], gmenu2x->skinConfColors[COLOR_FONT_ALT_OUTLINE]); #endif } else { SDL_RemoveTimer(iconChangedTimer); iconChangedTimer = NULL; // Volume indicator // TODO: use drawButton(gmenu2x->s, iconVolume[volumeMode], confInt["globalVolume"], x); #if defined(HW_LIDVOL) { stringstream ss; ss << gmenu2x->getVolume() /*<< "%"*/; ss.get(&buf[0], sizeof(buf)); } #else { stringstream ss; ss << gmenu2x->confInt["globalVolume"] /*<< "%"*/; ss.get(&buf[0], sizeof(buf)); } #endif x = iconPadding; // 1 * (iconWidth + 2 * iconPadding) + iconPadding + 1 * pctWidth; iconVolume[volumeMode]->blit(gmenu2x->s, x, gmenu2x->bottomBarRect.y + gmenu2x->bottomBarRect.h / 2, VAlignMiddle); x += iconWidth + iconPadding; gmenu2x->s->write(gmenu2x->font, buf, x, gmenu2x->bottomBarRect.y + gmenu2x->bottomBarRect.h / 2, VAlignMiddle, gmenu2x->skinConfColors[COLOR_FONT_ALT], gmenu2x->skinConfColors[COLOR_FONT_ALT_OUTLINE]); // Brightness indicator #if defined(HW_LIDVOL) { stringstream ss; ss << gmenu2x->getBacklight() /*<< "%"*/; ss.get(&buf[0], sizeof(buf)); } #else { stringstream ss; ss << gmenu2x->confInt["backlight"] /*<< "%"*/; ss.get(&buf[0], sizeof(buf)); } #endif x += iconPadding + pctWidth; iconBrightness[brightnessIcon]->blit(gmenu2x->s, x, gmenu2x->bottomBarRect.y + gmenu2x->bottomBarRect.h / 2, VAlignMiddle); x += iconWidth + iconPadding; gmenu2x->s->write(gmenu2x->font, buf, x, gmenu2x->bottomBarRect.y + gmenu2x->bottomBarRect.h / 2, VAlignMiddle, gmenu2x->skinConfColors[COLOR_FONT_ALT], gmenu2x->skinConfColors[COLOR_FONT_ALT_OUTLINE]); // // Menu indicator // iconMenu->blit(gmenu2x->s, iconPadding, gmenu2x->bottomBarRect.y + gmenu2x->bottomBarRect.h / 2, VAlignMiddle); // sc["skin:imgs/debug.png"]->blit(gmenu2x->s, gmenu2x->bottomBarRect.w - iconTrayShift * (iconWidth + iconPadding) - iconPadding, gmenu2x->bottomBarRect.y + gmenu2x->bottomBarRect.h / 2, HAlignRight | VAlignMiddle); // Battery indicator iconBattery[batteryIcon]->blit(gmenu2x->s, gmenu2x->bottomBarRect.w - iconTrayShift * (iconWidth + iconPadding) - iconPadding, gmenu2x->bottomBarRect.y + gmenu2x->bottomBarRect.h / 2, HAlignRight | VAlignMiddle); iconTrayShift++; // SD Card indicator if (mmcStatus == MMC_INSERT) { iconSD->blit(gmenu2x->s, gmenu2x->bottomBarRect.w - iconTrayShift * (iconWidth + iconPadding) - iconPadding, gmenu2x->bottomBarRect.y + gmenu2x->bottomBarRect.h / 2, HAlignRight | VAlignMiddle); iconTrayShift++; } // Network indicator if (gmenu2x->iconInet != NULL) { gmenu2x->iconInet->blit(gmenu2x->s, gmenu2x->bottomBarRect.w - iconTrayShift * (iconWidth + iconPadding) - iconPadding, gmenu2x->bottomBarRect.y + gmenu2x->bottomBarRect.h / 2, HAlignRight | VAlignMiddle); iconTrayShift++; } if (selLink() != NULL) { if (selLinkApp() != NULL) { if (!selLinkApp()->getManualPath().empty()) { // Manual indicator iconManual->blit(gmenu2x->s, gmenu2x->bottomBarRect.w - iconTrayShift * (iconWidth + iconPadding) - iconPadding, gmenu2x->bottomBarRect.y + gmenu2x->bottomBarRect.h / 2, HAlignRight | VAlignMiddle); } if (CPU_MAX != CPU_MIN) { // CPU indicator { stringstream ss; ss << selLinkApp()->getCPU() << "MHz"; ss.get(&buf[0], sizeof(buf)); } x += iconPadding + pctWidth; iconCPU->blit(gmenu2x->s, x, gmenu2x->bottomBarRect.y + gmenu2x->bottomBarRect.h / 2, VAlignMiddle); x += iconWidth + iconPadding; gmenu2x->s->write(gmenu2x->font, buf, x, gmenu2x->bottomBarRect.y + gmenu2x->bottomBarRect.h / 2, VAlignMiddle, gmenu2x->skinConfColors[COLOR_FONT_ALT], gmenu2x->skinConfColors[COLOR_FONT_ALT_OUTLINE]); } } } } } void Menu::drawIconTray() { int iconTrayShift = 0; // TRAY DEBUG // s->box(sectionBarRect.x + gmenu2x->sectionBarRect.w - 38 + 0 * 20, gmenu2x->sectionBarRect.y + gmenu2x->sectionBarRect.h - 18,16,16, strtorgba("ffff00ff")); // s->box(sectionBarRect.x + gmenu2x->sectionBarRect.w - 38 + 1 * 20, gmenu2x->sectionBarRect.y + gmenu2x->sectionBarRect.h - 18,16,16, strtorgba("00ff00ff")); // s->box(sectionBarRect.x + gmenu2x->sectionBarRect.w - 38, gmenu2x->sectionBarRect.y + gmenu2x->sectionBarRect.h - 38,16,16, strtorgba("0000ffff")); // s->box(sectionBarRect.x + gmenu2x->sectionBarRect.w - 18, gmenu2x->sectionBarRect.y + gmenu2x->sectionBarRect.h - 38,16,16, strtorgba("ff00ffff")); // TRAY 0,0 iconVolume[volumeMode]->blit(gmenu2x->s, gmenu2x->sectionBarRect.x + gmenu2x->sectionBarRect.w - 38, gmenu2x->sectionBarRect.y + gmenu2x->sectionBarRect.h - 38); // TRAY 1,0 iconBattery[batteryIcon]->blit(gmenu2x->s, gmenu2x->sectionBarRect.x + gmenu2x->sectionBarRect.w - 18, gmenu2x->sectionBarRect.y + gmenu2x->sectionBarRect.h - 38); // TRAY iconTrayShift,1 if (mmcStatus == MMC_INSERT) { iconSD->blit(gmenu2x->s, gmenu2x->sectionBarRect.x + gmenu2x->sectionBarRect.w - 38 + iconTrayShift * 20, gmenu2x->sectionBarRect.y + gmenu2x->sectionBarRect.h - 18); iconTrayShift++; } if (selLink() != NULL) { if (selLinkApp() != NULL) { if (!selLinkApp()->getManualPath().empty() && iconTrayShift < 2) { // Manual indicator iconManual->blit(gmenu2x->s, gmenu2x->sectionBarRect.x + gmenu2x->sectionBarRect.w - 38 + iconTrayShift * 20, gmenu2x->sectionBarRect.y + gmenu2x->sectionBarRect.h - 18); iconTrayShift++; } if (CPU_MAX != CPU_MIN) { if (selLinkApp()->getCPU() != gmenu2x->confInt["cpuMenu"] && iconTrayShift < 2) { // CPU indicator iconCPU->blit(gmenu2x->s, gmenu2x->sectionBarRect.x + gmenu2x->sectionBarRect.w - 38 + iconTrayShift * 20, gmenu2x->sectionBarRect.y + gmenu2x->sectionBarRect.h - 18); iconTrayShift++; } } } } if (iconTrayShift < 2) { brightnessIcon = gmenu2x->confInt["backlight"] / 20; if (brightnessIcon > 4 || iconBrightness[brightnessIcon] == NULL) { brightnessIcon = 5; } iconBrightness[brightnessIcon]->blit(gmenu2x->s, gmenu2x->sectionBarRect.x + gmenu2x->sectionBarRect.w - 38 + iconTrayShift * 20, gmenu2x->sectionBarRect.y + gmenu2x->sectionBarRect.h - 18); iconTrayShift++; } if (iconTrayShift < 2) { // Menu indicator iconMenu->blit(gmenu2x->s, gmenu2x->sectionBarRect.x + gmenu2x->sectionBarRect.w - 38 + iconTrayShift * 20, gmenu2x->sectionBarRect.y + gmenu2x->sectionBarRect.h - 18); iconTrayShift++; } } void Menu::exec() { icon_changed = SDL_GetTicks(); section_changed = icon_changed; sectionChangedTimer = SDL_AddTimer(2000, gmenu2x->input.wakeUp, (void*)false); iconChangedTimer = SDL_AddTimer(1000, gmenu2x->input.wakeUp, (void*)false); iconBrightness[0] = gmenu2x->sc["skin:imgs/brightness/0.png"], iconBrightness[1] = gmenu2x->sc["skin:imgs/brightness/1.png"], iconBrightness[2] = gmenu2x->sc["skin:imgs/brightness/2.png"], iconBrightness[3] = gmenu2x->sc["skin:imgs/brightness/3.png"], iconBrightness[4] = gmenu2x->sc["skin:imgs/brightness/4.png"], iconBrightness[5] = gmenu2x->sc["skin:imgs/brightness.png"], iconBattery[0] = gmenu2x->sc["skin:imgs/battery/0.png"], iconBattery[1] = gmenu2x->sc["skin:imgs/battery/1.png"], iconBattery[2] = gmenu2x->sc["skin:imgs/battery/2.png"], iconBattery[3] = gmenu2x->sc["skin:imgs/battery/3.png"], iconBattery[4] = gmenu2x->sc["skin:imgs/battery/4.png"], iconBattery[5] = gmenu2x->sc["skin:imgs/battery/5.png"], iconBattery[6] = gmenu2x->sc["skin:imgs/battery/ac.png"], iconVolume[0] = gmenu2x->sc["skin:imgs/mute.png"], iconVolume[1] = gmenu2x->sc["skin:imgs/phones.png"], iconVolume[2] = gmenu2x->sc["skin:imgs/volume.png"], iconSD = gmenu2x->sc["skin:imgs/sd.png"]; iconManual = gmenu2x->sc["skin:imgs/manual.png"]; iconCPU = gmenu2x->sc["skin:imgs/cpu.png"]; iconMenu = gmenu2x->sc["skin:imgs/menu.png"]; iconL = gmenu2x->sc["skins/" + gmenu2x->confStr["skin"] + "/imgs/section-l.png"]; iconR = gmenu2x->sc["skins/" + gmenu2x->confStr["skin"] + "/imgs/section-r.png"]; iconBGoff = gmenu2x->sc["skins/" + gmenu2x->confStr["skin"] + "/imgs/iconbg_off.png"]; iconBGon = gmenu2x->sc["skins/" + gmenu2x->confStr["skin"] + "/imgs/iconbg_on.png"]; while (true) { // BACKGROUND gmenu2x->currBackdrop = gmenu2x->confStr["wallpaper"]; if (gmenu2x->confInt["skinBackdrops"] & BD_MENU) { if (selLink() != NULL && !selLink()->getBackdropPath().empty()) { gmenu2x->currBackdrop = selLink()->getBackdropPath(); } else if (selLinkApp() != NULL && !selLinkApp()->getBackdropPath().empty()) { gmenu2x->currBackdrop = selLinkApp()->getBackdropPath(); } } gmenu2x->setBackground(gmenu2x->s, gmenu2x->currBackdrop); if (gmenu2x->skinConfInt["sectionBackdrops"]) { // string sectionBackdrop = gmenu2x->sc.getSkinFilePath("backdrops/" + selSection() + ".png", false); // string sectionBackdropGeneric = gmenu2x->sc.getSkinFilePath("backdrops/generic-section.png", false); sectionBackdrop = gmenu2x->sc["skins/" + gmenu2x->confStr["skin"] + "/backdrops/" + selSection() + ".png"]; sectionBackdropGeneric = gmenu2x->sc["skins/"+ gmenu2x->confStr["skin"] + "/backdrops/generic-section.png"]; if (sectionBackdrop != NULL) { sectionBackdrop->blit(gmenu2x->s, 0, 0, 0, 50); // gmenu2x->currBackdrop = sectionBackdrop; } else if (sectionBackdropGeneric != NULL) { sectionBackdropGeneric->blit(gmenu2x->s, 0, 0, 0, 50); // gmenu2x->currBackdrop = sectionBackdropGeneric; } } // gmenu2x->setBackground(gmenu2x->s, gmenu2x->currBackdrop); // SECTIONS if (gmenu2x->skinConfInt["sectionBar"]) { drawSectionBar(); brightnessIcon = gmenu2x->confInt["backlight"] / 20; if (brightnessIcon > 4 || iconBrightness[brightnessIcon] == NULL) { brightnessIcon = 5; } if (gmenu2x->skinConfInt["sectionBar"] == SB_CLASSIC) { drawStatusBar(); } else { drawIconTray(); } } // LINKS gmenu2x->s->setClipRect(gmenu2x->linksRect); gmenu2x->s->box(gmenu2x->linksRect, gmenu2x->skinConfColors[COLOR_LIST_BG]); if (linkCols == 1 && linkRows > 1) { drawList(); // LIST } else { drawGrid(); // CLASSIC } gmenu2x->s->clearClipRect(); if (!sectionLinks()->size()) { MessageBox mb(gmenu2x, gmenu2x->tr["This section is empty"]); mb.setAutoHide(1); mb.setBgAlpha(0); mb.exec(); } if (!gmenu2x->powerManager->suspendActive && !gmenu2x->input.combo()) { gmenu2x->s->flip(); } bool inputAction = gmenu2x->input.update(); if (gmenu2x->input.combo()) { gmenu2x->skinConfInt["sectionBar"] = ((gmenu2x->skinConfInt["sectionBar"]) % 5) + 1; initLayout(); MessageBox mb(gmenu2x, gmenu2x->tr["CHEATER! ;)"]); mb.setBgAlpha(0); mb.setAutoHide(200); mb.exec(); gmenu2x->input.dropEvents(); SDL_AddTimer(350, gmenu2x->input.wakeUp, (void*)false); } else if (!gmenu2x->powerManager->suspendActive) { gmenu2x->s->flip(); } if (gmenu2x->inputCommonActions(inputAction)) { continue; } if (gmenu2x->input[CANCEL] || gmenu2x->input[CONFIRM] || gmenu2x->input[SETTINGS] || gmenu2x->input[MENU]) { SDL_RemoveTimer(sectionChangedTimer); sectionChangedTimer = NULL; SDL_RemoveTimer(iconChangedTimer); iconChangedTimer = NULL; icon_changed = section_changed = 0; } if (gmenu2x->input[CONFIRM] && selLink() != NULL) { if (gmenu2x->confInt["skinBackdrops"] & BD_DIALOG) { gmenu2x->setBackground(gmenu2x->bg, gmenu2x->currBackdrop); } else { gmenu2x->setBackground(gmenu2x->bg, gmenu2x->confStr["wallpaper"]); } selLink()->run(); } else if (gmenu2x->input[CANCEL]) { continue; } else if (gmenu2x->input[MODIFIER] && !gmenu2x->input[MANUAL]) { if (selLinkApp() != NULL || selLink() != NULL) gmenu2x->allyTTS(iconDescription.c_str(), MEDIUM_GAP_TTS, MEDIUM_SPEED_TTS, 0); continue; } else if (gmenu2x->input[SETTINGS] && !(gmenu2x->actionPerformed)) { gmenu2x->settings(); } else if (gmenu2x->input[MENU]) { gmenu2x->contextMenu(); } // LINK NAVIGATION else if ((gmenu2x->input[LEFT] || gmenu2x->input.hatEvent(DLEFT) == DLEFT) && linkCols == 1 && linkRows > 1) pageUp(); else if ((gmenu2x->input[RIGHT] || gmenu2x->input.hatEvent(DRIGHT) == DRIGHT) && linkCols == 1 && linkRows > 1) pageDown(); else if (gmenu2x->input[LEFT] || gmenu2x->input.hatEvent(DLEFT) == DLEFT) linkLeft(); else if (gmenu2x->input[RIGHT] || gmenu2x->input.hatEvent(DRIGHT) == DRIGHT) linkRight(); else if (gmenu2x->input[UP] || gmenu2x->input.hatEvent(DUP) == DUP) linkUp(); else if (gmenu2x->input[DOWN] || gmenu2x->input.hatEvent(DDOWN) == DDOWN) linkDown(); // SECTION else if (gmenu2x->input[SECTION_PREV]) decSectionIndex(); else if (gmenu2x->input[SECTION_NEXT]) incSectionIndex(); // SELLINKAPP SELECTED else if (gmenu2x->input[MANUAL] && !gmenu2x->input[MODIFIER] && selLinkApp() != NULL && !selLinkApp()->getManualPath().empty()) gmenu2x->showManual(); // On Screen Help // else if (gmenu2x->input[MANUAL]) { // s->box(10,50,300,162, gmenu2x->skinConfColors[COLOR_MESSAGE_BOX_BG]); // s->rectangle(12,52,296,158, gmenu2x->skinConfColors[COLOR_MESSAGE_BOX_BORDER]); // int line = 60; s->write(gmenu2x->font, gmenu2x->tr["CONTROLS"], 20, line); // line += font->getHeight() + 5; s->write(gmenu2x->font, gmenu2x->tr["A: Select"], 20, line); // line += font->getHeight() + 5; s->write(gmenu2x->font, gmenu2x->tr["B: Cancel"], 20, line); // line += font->getHeight() + 5; s->write(gmenu2x->font, gmenu2x->tr["Y: Show manual"], 20, line); // line += font->getHeight() + 5; s->write(gmenu2x->font, gmenu2x->tr["L, R: Change section"], 20, line); // line += font->getHeight() + 5; s->write(gmenu2x->font, gmenu2x->tr["Start: Settings"], 20, line); // line += font->getHeight() + 5; s->write(gmenu2x->font, gmenu2x->tr["Select: Menu"], 20, line); // line += font->getHeight() + 5; s->write(gmenu2x->font, gmenu2x->tr["Select+Start: Save screenshot"], 20, line); // line += font->getHeight() + 5; s->write(gmenu2x->font, gmenu2x->tr["Select+L: Adjust volume level"], 20, line); // line += font->getHeight() + 5; s->write(gmenu2x->font, gmenu2x->tr["Select+R: Adjust backlight level"], 20, line); // s->flip(); // bool close = false; // while (!close) { // gmenu2x->input.update(); // if (gmenu2x->input[MODIFIER] || gmenu2x->input[CONFIRM] || gmenu2x->input[CANCEL]) close = true; // } // } iconTitle = ""; iconDescription = ""; if (selLinkApp() != NULL) { iconTitle = selLinkApp()->getTitle(); iconDescription = selLinkApp()->getDescription(); } else if (selLink() != NULL) { iconTitle = selLink()->getTitle(); iconDescription = selLink()->getDescription(); } if ( gmenu2x->input[LEFT] || gmenu2x->input[RIGHT] || gmenu2x->input[UP] || gmenu2x->input[DOWN] || gmenu2x->input[MANUAL] || gmenu2x->input.hatEvent(DLEFT) == DLEFT || gmenu2x->input.hatEvent(DRIGHT) == DRIGHT || gmenu2x->input.hatEvent(DUP) == DUP || gmenu2x->input.hatEvent(DDOWN) == DDOWN || gmenu2x->input[MANUAL] || gmenu2x->input[MODIFIER] ) allyRead = false; readSection = gmenu2x->tr["Section"] + " " + gmenu2x->tr[selSectionName()] + " " + gmenu2x->tr["at"] + " " + iconTitle; if (!allyRead) { gmenu2x->allyTTS(readSection.c_str(), MEDIUM_GAP_TTS, MEDIUM_SPEED_TTS, 0); allyRead = true; } if ( !iconDescription.empty() && (gmenu2x->input[LEFT] || gmenu2x->input[RIGHT] || gmenu2x->input[UP] || gmenu2x->input[DOWN] || gmenu2x->input[SECTION_PREV] || gmenu2x->input[SECTION_NEXT] || gmenu2x->input.hatEvent(DLEFT) == DLEFT || gmenu2x->input.hatEvent(DRIGHT) == DRIGHT || gmenu2x->input.hatEvent(DUP) == DUP || gmenu2x->input.hatEvent(DDOWN) == DDOWN) ) { icon_changed = SDL_GetTicks(); SDL_RemoveTimer(iconChangedTimer); iconChangedTimer = NULL; iconChangedTimer = SDL_AddTimer(1000, gmenu2x->input.wakeUp, (void*)false); } if ( !iconTitle.empty() && (gmenu2x->input[LEFT] || gmenu2x->input[RIGHT] || gmenu2x->input[LEFT] || gmenu2x->input[RIGHT] || gmenu2x->input[UP] || gmenu2x->input[DOWN]) ) { gmenu2x->allyTTS(iconTitle.c_str(), MEDIUM_GAP_TTS, MEDIUM_SPEED_TTS, 0); } if (gmenu2x->skinConfInt["sectionLabel"] && (gmenu2x->input[SECTION_PREV] || gmenu2x->input[SECTION_NEXT])) { section_changed = SDL_GetTicks(); SDL_RemoveTimer(sectionChangedTimer); sectionChangedTimer = NULL; sectionChangedTimer = SDL_AddTimer(2000, gmenu2x->input.wakeUp, (void*)false); gmenu2x->allyTTS(readSection.c_str(), MEDIUM_GAP_TTS, MEDIUM_SPEED_TTS, 0); } } }
37,897
C++
.cpp
846
41.882979
265
0.673165
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,067
menusettingdatetime.cpp
MiyooCFW_gmenu2x/src/menusettingdatetime.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "menusettingdatetime.h" #include "gmenu2x.h" #include <sstream> #include <iomanip> using std::stringstream; using fastdelegate::MakeDelegate; MenuSettingDateTime::MenuSettingDateTime(GMenu2X *gmenu2x, const string &title, const string &description, string *value): MenuSetting(gmenu2x, title, description) { _value = value; originalValue = *value; selPart = 0; sscanf(_value->c_str(), "%d-%d-%d %d:%d", &iyear, &imonth, &iday, &ihour, &iminute); this->setYear(iyear); this->setMonth(imonth); this->setDay(iday); this->setHour(ihour); this->setMinute(iminute); btn = new IconButton(gmenu2x, "a", gmenu2x->tr["Edit"]); buttonBox.add(btn); } void MenuSettingDateTime::draw(int y) { this->y = y; MenuSetting::draw(y); gmenu2x->s->write(gmenu2x->font, year + "-" + month + "-" + day + " " + hour + ":" + minute, 155, y+gmenu2x->font->getHalfHeight(), VAlignMiddle); } void MenuSettingDateTime::drawSelected(int y) { if (editing) { int x = 155, w = 40; switch (selPart) { case 1: x += gmenu2x->font->getTextWidth(year + "-"); w = gmenu2x->font->getTextWidth(month); break; case 2: x += gmenu2x->font->getTextWidth(year + "-" + month + "-"); w = gmenu2x->font->getTextWidth(day); break; case 3: x += gmenu2x->font->getTextWidth(year + "-" + month + "-" + day + " "); w = gmenu2x->font->getTextWidth(hour); break; case 4: x += gmenu2x->font->getTextWidth(year + "-" + month + "-" + day + " " + hour + ":"); w = gmenu2x->font->getTextWidth(minute); break; default: w = gmenu2x->font->getTextWidth(year); break; } gmenu2x->s->box(x - 2, y, w + 3, gmenu2x->font->getHeight() + 1, gmenu2x->skinConfColors[COLOR_SELECTION_BG]); gmenu2x->s->rectangle(x - 2, y, w + 3, gmenu2x->font->getHeight() + 1, 0, 0, 0, 255); } MenuSetting::drawSelected(y); } uint32_t MenuSettingDateTime::manageInput() { if (editing) { if (gmenu2x->input[SETTINGS]) return 0; if (gmenu2x->input[INC] || gmenu2x->input[UP] || gmenu2x->input.hatEvent(DUP) == DUP) inc(); else if (gmenu2x->input[DEC] || gmenu2x->input[DOWN] || gmenu2x->input.hatEvent(DDOWN) == DDOWN) dec(); else if (gmenu2x->input[MODIFIER] && !gmenu2x->input[MANUAL]) current(); else if (gmenu2x->input[LEFT] || gmenu2x->input.hatEvent(DLEFT) == DLEFT) leftComponent(); else if (gmenu2x->input[RIGHT] || gmenu2x->input.hatEvent(DRIGHT) == DRIGHT) rightComponent(); else if (gmenu2x->input[CONFIRM] || gmenu2x->input[CANCEL]) { editing = false; buttonBox.remove(2); btn = new IconButton(gmenu2x, "a", gmenu2x->tr["Edit"]); buttonBox.add(btn); } return -1; } else if (gmenu2x->input[MODIFIER] && !gmenu2x->input[MANUAL]) { current(); } else if (gmenu2x->input[CONFIRM]) { editing = true; buttonBox.remove(1); btn = new IconButton(gmenu2x, "dpad", gmenu2x->tr["Edit"]); buttonBox.add(btn); btn = new IconButton(gmenu2x, "a", gmenu2x->tr["OK"]); buttonBox.add(btn); } return 0; // SD_NO_ACTION } void MenuSettingDateTime::dec() { setSelPart(getSelPart() - 1); } void MenuSettingDateTime::inc() { setSelPart(getSelPart() + 1); } void MenuSettingDateTime::current() { setSelPart(getSelPart()); } void MenuSettingDateTime::leftComponent() { selPart = constrain(selPart - 1, 0, 4); } void MenuSettingDateTime::rightComponent() { selPart = constrain(selPart + 1, 0, 4); } void MenuSettingDateTime::setYear(int16_t i) { iyear = constrain(i, 2022, 2100); stringstream ss; ss << iyear; ss >> year; } void MenuSettingDateTime::setMonth(int16_t i) { imonth = i; if (i < 1) imonth = 12; else if (i > 12) imonth = 1; stringstream ss; ss << std::setw(2) << std::setfill('0') << imonth; ss >> month; } void MenuSettingDateTime::setDay(int16_t i) { iday = i; if (i < 1) iday = 31; else if (i > 31) iday = 1; stringstream ss; ss << std::setw(2) << std::setfill('0') << iday; ss >> day; } void MenuSettingDateTime::setHour(int16_t i) { ihour = i; if (i < 0) ihour = 23; else if (i > 23) ihour = 0; stringstream ss; ss << std::setw(2) << std::setfill('0') << ihour; ss >> hour; } void MenuSettingDateTime::setMinute(int16_t i) { iminute = i; if (i < 0) iminute = 59; else if (i > 59) iminute = 0; stringstream ss; ss << std::setw(2) << std::setfill('0') << iminute; ss >> minute; } void MenuSettingDateTime::setSelPart(uint16_t i) { switch (selPart) { case 1: setMonth(i); break; case 2: setDay(i); break; case 3: setHour(i); break; case 4: setMinute(i); break; default: setYear(i); break; } *_value = year + "-" + month + "-" + day + " " + hour + ":" + minute; gmenu2x->allyTTS(value().c_str(), MEDIUM_GAP_TTS, MEDIUM_SPEED_TTS, 0); } string MenuSettingDateTime::value() { return *_value; } uint16_t MenuSettingDateTime::getSelPart() { switch (selPart) { case 1: return imonth; case 2: return iday; case 3: return ihour; case 4: return iminute; default: return iyear; } } bool MenuSettingDateTime::edited() { return originalValue != *_value; }
6,401
C++
.cpp
179
33.329609
147
0.611757
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,068
dialog.cpp
MiyooCFW_gmenu2x/src/dialog.cpp
#include "dialog.h" #include "gmenu2x.h" #include "debug.h" Dialog::Dialog(GMenu2X *gmenu2x, const std::string &title, const std::string &description, const std::string &icon): gmenu2x(gmenu2x), title(title), description(description), icon(icon) { bg = new Surface(gmenu2x->bg); buttons.clear(); gmenu2x->input.dropEvents(); // prevent passing input away } Dialog::~Dialog() { gmenu2x->input.dropEvents(); // prevent passing input away delete bg; } void Dialog::drawTopBar(Surface *s, const std::string &title, const std::string &description, const std::string &icon) { // Surface *bar = sc["skins/" + gmenu2x->confStr["skin"] + "/imgs/topbar.png"]; // if (bar != NULL) bar->blit(s, 0, 0); // else s->setClipRect({0, 0, gmenu2x->w, gmenu2x->skinConfInt["sectionBarSize"]}); s->box(0, 0, gmenu2x->w, gmenu2x->skinConfInt["sectionBarSize"], gmenu2x->skinConfColors[COLOR_TOP_BAR_BG]); int iconOffset = 2; if (!icon.empty() && gmenu2x->skinConfInt["showDialogIcon"]) { // drawTitleIcon iconOffset = gmenu2x->skinConfInt["sectionBarSize"]; Surface *i = gmenu2x->sc.add(icon, icon + "dialog"); if (i == NULL) i = gmenu2x->sc["skin:" + icon]; if (i == NULL) i = gmenu2x->sc["skin:icons/generic.png"]; gmenu2x->s->setClipRect({4, 4, iconOffset - 8, iconOffset - 8}); i->blit(s, {4, 4, iconOffset - 8, iconOffset - 8}, HAlignCenter | VAlignMiddle); gmenu2x->s->clearClipRect(); } if (!title.empty()) // writeTitle s->write(gmenu2x->titlefont, title, iconOffset, 2, VAlignTop, gmenu2x->skinConfColors[COLOR_FONT_ALT], gmenu2x->skinConfColors[COLOR_FONT_ALT_OUTLINE]); if (!description.empty()) // writeSubTitle s->write(gmenu2x->font, description, iconOffset, gmenu2x->skinConfInt["sectionBarSize"] - 2, VAlignBottom, gmenu2x->skinConfColors[COLOR_FONT_ALT], gmenu2x->skinConfColors[COLOR_FONT_ALT_OUTLINE]); s->clearClipRect(); } void Dialog::drawBottomBar(Surface *s, buttons_t buttons) { // Surface *bar = sc["skins/" + gmenu2x->confStr["skin"] + "/imgs/bottombar.png"]; // if (bar != NULL) bar->blit(s, 0, gmenu2x->h - bar->raw->h); // else s->box(gmenu2x->bottomBarRect, gmenu2x->skinConfColors[COLOR_BOTTOM_BAR_BG]); int x = gmenu2x->bottomBarRect.x + 5, y = gmenu2x->bottomBarRect.y + gmenu2x->bottomBarRect.h / 2; for (const auto &itr: buttons) { Surface *btn; string path = itr[0]; if (path.substr(0, 5) != "skin:") { path = "skin:imgs/buttons/" + path + ".png"; } btn = gmenu2x->sc[path]; string txt = itr[1]; if (btn != NULL) { btn->blit(s, x, y, HAlignLeft | VAlignMiddle); x += btn->width() + 4; } if (!txt.empty()) { s->write(gmenu2x->font, txt, x, y, VAlignMiddle, gmenu2x->skinConfColors[COLOR_FONT_ALT], gmenu2x->skinConfColors[COLOR_FONT_ALT_OUTLINE]); x += gmenu2x->font->getTextWidth(txt); } x += 6; } } void Dialog::drawDialog(Surface *s, bool top, bool bottom) { if (s == NULL) s = gmenu2x->s; this->bg->blit(s, 0, 0); if (top) { // Replace '\n' with " " string::size_type pos = 0; while ((pos = title.find('\n', pos)) != std::string::npos) { title.replace(pos, 1, " "); pos += 1; } drawTopBar(s, title, description, icon); } if (bottom) drawBottomBar(s, buttons); s->box(gmenu2x->linksRect, gmenu2x->skinConfColors[COLOR_LIST_BG]); }
3,267
C++
.cpp
75
40.973333
199
0.676332
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,069
link.cpp
MiyooCFW_gmenu2x/src/link.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "link.h" #include "gmenu2x.h" Link::Link(GMenu2X *gmenu2x, LinkAction action): Button(gmenu2x->ts, true), gmenu2x(gmenu2x), action(action) {} void Link::run() { this->action(); } void Link::setTitle(const string &title) { this->title = title; edited = true; } void Link::setDescription(const string &description) { this->description = description; edited = true; } const string &Link::getIcon() { int pos = iconPath.find('#'); // search for "opkfile.opk#icon.png" if (pos != string::npos) icon = ""; return icon; } void Link::setIcon(const string &icon) { int pos = icon.find('#'); // search for "opkfile.opk#icon.png" this->icon = icon; if (icon.compare(0, 5, "skin:") == 0 && !gmenu2x->sc.getSkinFilePath(icon.substr(5, string::npos)).empty()) { this->iconPath = gmenu2x->sc.getSkinFilePath(icon.substr(5, string::npos)); } else if (file_exists(icon)) { this->iconPath = icon; } else if (!(icon.empty() && pos != string::npos)) { // keep the opk icon this->iconPath = ""; } edited = true; } void Link::setBackdrop(const string &backdrop) { this->backdrop = backdrop; backdropPathGeneric = gmenu2x->sc.getSkinFilePath("backdrops/generic.png"); if (backdrop.compare(0, 5, "skin:") == 0 && !gmenu2x->sc.getSkinFilePath(backdrop.substr(5, string::npos)).empty()) this->backdropPath = gmenu2x->sc.getSkinFilePath(backdrop.substr(5, string::npos)); else if (file_exists(backdrop)) this->backdropPath = backdrop; else if (file_exists(backdropPathGeneric)) this->backdropPath = backdropPathGeneric; else this->backdropPath = ""; edited = true; } const string Link::searchIcon() { if (!gmenu2x->sc.getSkinFilePath(iconPath).empty()) return gmenu2x->sc.getSkinFilePath(iconPath); return gmenu2x->sc.getSkinFilePath("icons/generic.png"); } const string &Link::getIconPath() { if (iconPath.empty()) iconPath = searchIcon(); return iconPath; } void Link::setIconPath(const string &icon) { if (file_exists(icon)) iconPath = icon; else iconPath = gmenu2x->sc.getSkinFilePath("icons/generic.png"); }
3,462
C++
.cpp
79
41.797468
116
0.598872
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,070
selector.cpp
MiyooCFW_gmenu2x/src/selector.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include <fstream> #include "messagebox.h" #include "linkapp.h" #include "selector.h" #include "debug.h" #if defined(OPK_SUPPORT) #include <libopk.h> #endif Selector::Selector(GMenu2X *gmenu2x, const string &title, const string &description, const string &icon, LinkApp *link): BrowseDialog(gmenu2x, title, description, icon), link(link) { loadAliases(); setFilter(link->getSelectorFilter()); setPath(gmenu2x->confStr["homePath"]); } const std::string Selector::getPreview(uint32_t i) { string fname = getFile(i); string fpath = getFilePath(i); if (previews[fpath].empty()) { string screendir = link->getSelectorScreens(); string noext, realdir; previews[fpath] = "#"; // dummy path int d1 = fname.rfind("."); if (d1 != string::npos && d1 > 0) noext = fname.substr(0, d1); if (noext.empty() || noext == ".") return previews[fpath]; if (screendir.empty()) screendir = "./.images"; if (screendir[0] == '.') realdir = real_path(path + "/" + screendir) + "/"; // allow "." as "current directory", therefore, relative paths else realdir = real_path(screendir) + "/"; INFO("Searching preview '%s%s.(png|jpg)'", realdir.c_str(), noext.c_str()); if (dir_exists(realdir)) { if (file_exists(realdir + noext + ".png")) previews[fpath] = realdir + noext + ".png"; else if (file_exists(realdir + noext + ".jpg")) previews[fpath] = realdir + noext + ".jpg"; } if (previews[fpath] == "#") { // fallback - always search for ./filename.png if (file_exists(path + "/" + noext + ".png")) previews[fpath] = path + "/" + noext + ".png"; else if (file_exists(path + "/" + noext + ".jpg")) previews[fpath] = path + "/" + noext + ".jpg"; } } return previews[fpath]; } void Selector::parseAliases(istream &infile) { aliases.clear(); params.clear(); string line; while (getline(infile, line, '\n')) { string name, value; int d1 = line.find("="); int d2 = line.find(";"); if (d2 > d1) d2 -= d1 + 1; name = lowercase(trim(line.substr(0, d1))); aliases[name] = trim(line.substr(d1 + 1, d2)); if (d2 > 0) params[name] = trim(line.substr(d1 + d2 + 2)); } } void Selector::loadAliases() { string linkExec = link->getExec(); string linkAlias = link->getAliasFile(); if (file_exists(linkAlias)) { ifstream infile; infile.open(linkAlias.c_str(), ios_base::in); parseAliases(infile); infile.close(); #if defined(OPK_SUPPORT) } else if (file_ext(linkExec, true) == ".opk") { void *buf; size_t len; struct OPK *opk = opk_open(linkExec.c_str()); if (!opk) { ERROR("Unable to open OPK"); return; } if (opk_extract_file(opk, linkAlias.c_str(), &buf, &len) < 0) { ERROR("Unable to extract file: %s\n", linkAlias.c_str()); return; } opk_close(opk); istringstream infile((char *)buf); parseAliases(infile); #endif // OPK_SUPPORT } } const std::string Selector::getFileName(uint32_t i) { string fname = getFile(i); string noext = lowercase(fname); int d1 = fname.rfind("."); if (d1 != string::npos && d1 > 0) noext = lowercase(fname.substr(0, d1)); unordered_map<string, string>::iterator it = aliases.find(noext); if (it == aliases.end() || it->second.empty()) return fname; return it->second; } const std::string Selector::getParams(uint32_t i) { string fname = getFile(i); string noext = fname; int d1 = fname.rfind("."); if (d1 != string::npos && d1 > 0) noext = lowercase(fname.substr(0, d1)); unordered_map<string, string>::iterator it = params.find(noext); if (it == params.end()) return ""; return it->second; } void Selector::customOptions(vector<MenuOption> &options) { if (isFile(selected)) { options.push_back((MenuOption){gmenu2x->tr["Add to Favorites"], MakeDelegate(this, &Selector::addFavorite)}); } } void Selector::addFavorite() { string favicon = getPreview(selected); if (favicon.empty() || favicon == "#") favicon = this->icon; gmenu2x->menu->addSection("favorites"); string title = base_name(getFileName(selected), true); string linkpath = "sections/favorites/" + title + "." + base_name(link->getExec(), true) + ".lnk"; LinkApp *fav = new LinkApp(gmenu2x, linkpath.c_str()); fav->setExec(link->getExec()); fav->setTitle(title); fav->setDescription(link->getDescription()); fav->setIcon(favicon); string selFullPath = cmdclean(getFilePath(selected)); string params = link->getParams(); if (params.find("\%f") != std::string::npos) params = strreplace(params, "\%f", selFullPath); else params = link->getParams() + " " + selFullPath; fav->setParams(params); fav->save(); gmenu2x->initMenu(); MessageBox mb(gmenu2x, gmenu2x->tr["Link created"], favicon); mb.setAutoHide(1000); mb.exec(); }
6,081
C++
.cpp
152
37.493421
140
0.6131
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,071
menusettingmultiint.cpp
MiyooCFW_gmenu2x/src/menusettingmultiint.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "menusettingmultiint.h" #include "gmenu2x.h" #include "utilities.h" #include <sstream> using std::string; using std::stringstream; using fastdelegate::MakeDelegate; // MenuSettingMultiInt::MenuSettingMultiInt(GMenu2X *gmenu2x, const string &title, const string &description, int *value, int def, int min, int max) MenuSettingMultiInt::MenuSettingMultiInt(GMenu2X *gmenu2x, const string &title, const string &description, int *value, int *choice_pointer, int choice_size, int def, int min, int max) : MenuSetting(gmenu2x, title, description) { _value = value; originalValue = *value; choices = choice_pointer; selection_max = choice_size - 1; selection = reverseLookup(*value); this->def = choices[reverseLookup(def)]; this->min = min; this->max = max; setValue(evalIntConf(choices[selection], def, min, max), 0); //Delegates ButtonAction actionInc = MakeDelegate(this, &MenuSettingMultiInt::inc); ButtonAction actionDec = MakeDelegate(this, &MenuSettingMultiInt::dec); btn = new IconButton(gmenu2x, "skin:imgs/buttons/select.png", gmenu2x->tr["Default"]); btn->setAction(MakeDelegate(this, &MenuSettingMultiInt::setDefault)); buttonBox.add(btn); btn = new IconButton(gmenu2x, "skin:imgs/buttons/left.png"); btn->setAction(actionDec); buttonBox.add(btn); btn = new IconButton(gmenu2x, "skin:imgs/buttons/right.png", gmenu2x->tr["Change"]); btn->setAction(actionInc); buttonBox.add(btn); } void MenuSettingMultiInt::draw(int y) { MenuSetting::draw(y); gmenu2x->s->write( gmenu2x->font, strvalue, 180, y+gmenu2x->font->getHalfHeight(), VAlignMiddle ); } uint32_t MenuSettingMultiInt::manageInput() { if ( gmenu2x->input[LEFT] || gmenu2x->input.hatEvent(DLEFT) == DLEFT ) dec(); if ( gmenu2x->input[RIGHT] || gmenu2x->input.hatEvent(DRIGHT) == DRIGHT ) inc(); if ( gmenu2x->input[DEC] ) dec2x(); if ( gmenu2x->input[INC] ) inc2x(); if ( gmenu2x->input[MENU] ) setDefault(); if ( gmenu2x->input[MODIFIER] && !gmenu2x->input[MANUAL]) current(); return 0; // SD_NO_ACTION } int MenuSettingMultiInt::reverseLookup(int value) { int output; for (int i = 0; i <= selection_max + 1; i++) { if (choices[i] <= value) { output = i; } else { break; } } return output; } void MenuSettingMultiInt::inc() { if (selection < selection_max && choices[selection + 1] <= max) { selection = selection + 1; setValue(choices[selection], 1); } } void MenuSettingMultiInt::inc2x() { if (selection < selection_max && ((choices[selection + 1] < max) || (choices[selection + 2] == max))) { selection = selection + 2; setValue(choices[selection], 1); } else if (selection < selection_max && choices[selection + 1] == max) { selection = selection + 1; setValue(choices[selection], 1); } } void MenuSettingMultiInt::dec() { if (selection > 0 && choices[selection - 1] >= min) { selection = selection - 1; setValue(choices[selection], 1); } } void MenuSettingMultiInt::dec2x() { if (selection > 0 && ((choices[selection - 1] > min) || (choices[selection - 2] == min))) { selection = selection - 2; setValue(choices[selection], 1); } else if (selection > 0 && choices[selection - 1] == min) { selection = selection - 1; setValue(choices[selection], 1); } } void MenuSettingMultiInt::current() { setValue(*_value, 1); } void MenuSettingMultiInt::setValue(int value, bool readValue) { *_value = value; stringstream ss; ss << *_value; strvalue = ""; ss >> strvalue; if (readValue) gmenu2x->allyTTS(strvalue.c_str(), MEDIUM_GAP_TTS, MEDIUM_SPEED_TTS, 0); } void MenuSettingMultiInt::setDefault() { selection = reverseLookup(def); setValue(choices[selection], 1); } int MenuSettingMultiInt::value() { return *_value; } // void MenuSettingMultiInt::adjustInput() { // gmenu2x->input.setInterval(100, LEFT); // gmenu2x->input.setInterval(100, RIGHT); // gmenu2x->input.setInterval(100, DEC); // gmenu2x->input.setInterval(100, INC); // } bool MenuSettingMultiInt::edited() { return originalValue != value(); }
5,402
C++
.cpp
132
38.893939
183
0.640991
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,072
iconbutton.cpp
MiyooCFW_gmenu2x/src/iconbutton.cpp
#include "iconbutton.h" #include "gmenu2x.h" #include "surface.h" #include "debug.h" using namespace std; using namespace fastdelegate; IconButton::IconButton(GMenu2X *gmenu2x, const string &icon, const string &label): Button(gmenu2x->ts), gmenu2x(gmenu2x), icon(icon), label(label) { labelPosition = IconButton::DISP_RIGHT; labelMargin = 2; updateSurfaces(); } void IconButton::updateSurfaces() { iconSurface = gmenu2x->sc[icon]; recalcSize(); } void IconButton::setPosition(int x, int y) { if (rect.x != x || rect.y != y) { Button::setPosition(x,y); recalcSize(); } } uint16_t IconButton::paint() { return gmenu2x->drawButton(gmenu2x->s, this->icon, this->label, rect.x, rect.y); } bool IconButton::paintHover() { return true; } void IconButton::recalcSize() { uint32_t h = 0, w = 0; uint32_t margin = labelMargin; if (iconSurface == NULL || label == "") margin = 0; if (iconSurface != NULL) { w += iconSurface->raw->w; h += iconSurface->raw->h; iconRect.w = w; iconRect.h = h; iconRect.x = rect.x; iconRect.y = rect.y; } else { iconRect.x = 0; iconRect.y = 0; iconRect.w = 0; iconRect.h = 0; } if (label != "") { labelRect.w = gmenu2x->font->getTextWidth(label); labelRect.h = gmenu2x->font->getHeight(); if (labelPosition == IconButton::DISP_LEFT || labelPosition == IconButton::DISP_RIGHT) { w += margin + labelRect.w; labelHAlign = HAlignLeft; labelVAlign = VAlignMiddle; } else { h += margin + labelRect.h; labelHAlign = HAlignCenter; labelVAlign = VAlignTop; } switch (labelPosition) { case IconButton::DISP_BOTTOM: labelRect.x = iconRect.x + iconRect.w/2; labelRect.y = iconRect.y + iconRect.h + margin; break; case IconButton::DISP_TOP: labelRect.x = iconRect.x + iconRect.w/2; labelRect.y = rect.y; iconRect.y += labelRect.h + margin; break; case IconButton::DISP_LEFT: labelRect.x = rect.x; labelRect.y = rect.y+h/2; iconRect.x += labelRect.w + margin; break; default: labelRect.x = iconRect.x + iconRect.w + margin; labelRect.y = rect.y+h/2; break; } } setSize(w, h); } const string &IconButton::getLabel() { return label; } void IconButton::setLabel(const string &label) { this->label = label; } void IconButton::setLabelPosition(int pos, int margin) { labelPosition = pos; labelMargin = margin; recalcSize(); } const string &IconButton::getIcon() { return icon; } void IconButton::setIcon(const string &icon) { this->icon = icon; updateSurfaces(); } void IconButton::setAction(ButtonAction action) { this->action = action; }
2,606
C++
.cpp
102
22.921569
90
0.691194
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,073
surfacecollection.cpp
MiyooCFW_gmenu2x/src/surfacecollection.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "surfacecollection.h" #include "surface.h" #include "utilities.h" #include "debug.h" #if defined(OPK_SUPPORT) #include <libopk.h> #endif using std::endl; using std::string; SurfaceCollection::SurfaceCollection() { setSkin("Default"); } void SurfaceCollection::debug() { SurfaceHash::iterator end = surfaces.end(); for (SurfaceHash::iterator curr = surfaces.begin(); curr != end; curr++) { DEBUG("key: %i", curr->first.c_str()); } } void SurfaceCollection::setSkin(const string &skin) { this->skin = skin; } string SurfaceCollection::getSkinFilePath(const string &file, bool fallback) { string ret = "skins/" + skin + "/" + file; if (file_exists(ret)) return ret; if (fallback) { ret = "skins/Default/" + file; if (file_exists(ret)) return ret; } return ""; } Surface *SurfaceCollection::add(string path, string key) { if (path.empty()) return NULL; if (key.empty()) key = path; if (exists(key)) return surfaces[key]; //del(key); Surface *s = NULL; #if defined(OPK_SUPPORT) int pos = path.find('#'); // search for "opkfile.opk#icon.png" if (pos != path.npos) { string iconpath = "icons/" + path.substr(pos + 1); iconpath = getSkinFilePath(iconpath, false); if (!iconpath.empty()) { DEBUG("Adding OPK skin surface: '%s'", iconpath.c_str()); s = new Surface(iconpath, true); } else { DEBUG("Adding OPK surface: %s", path.c_str()); void *buf; size_t len; struct OPK *opk = opk_open(path.substr(0, pos).c_str()); if (!opk) { ERROR("Unable to open OPK"); // return NULL; } else if (opk_extract_file(opk, path.substr(pos + 1).c_str(), &buf, &len) < 0) { ERROR("Unable to extract file: %s", path.substr(pos + 1).c_str()); // return NULL; } else { opk_close(opk); s = new Surface(buf, len); } } } else #endif // OPK_SUPPORT { if (path.substr(0, 5) == "skin:") { path = getSkinFilePath(path.substr(5)); } if (!path.empty() && file_exists(path)) { DEBUG("Adding surface: '%s'", path.c_str()); s = new Surface(path, true); } } // if (s != NULL) surfaces[key] = s; return s; } Surface *SurfaceCollection::add(Surface *s, const string &key) { if (exists(key)) return surfaces[key]; //del(key); surfaces[key] = s; return s; } Surface *SurfaceCollection::operator[](const string &key) { if (exists(key)) return surfaces[key]; return add(key); } bool SurfaceCollection::del(const string &path) { SurfaceHash::iterator i = surfaces.find(path); if (i != surfaces.end()) { delete i->second; surfaces.erase(i); return true; } return false; } void SurfaceCollection::clear() { while (surfaces.size() > 0) { delete surfaces.begin()->second; surfaces.erase(surfaces.begin()); } } bool SurfaceCollection::exists(const string &path) { return surfaces.find(path) != surfaces.end(); } void SurfaceCollection::move(const string &from, const string &to) { del(to); surfaces[to] = surfaces[from]; surfaces.erase(from); }
4,362
C++
.cpp
126
32.214286
84
0.592689
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,074
settingsdialog.cpp
MiyooCFW_gmenu2x/src/settingsdialog.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "settingsdialog.h" #include "messagebox.h" #include "menu.h" #include "gmenu2x.h" using namespace std; SettingsDialog::SettingsDialog(GMenu2X *gmenu2x, Touchscreen &ts, const string &title, const string &icon): Dialog(gmenu2x, title, "", icon), ts(ts) {} SettingsDialog::~SettingsDialog() { for (uint32_t i = 0; i < voices.size(); i++) delete voices[i]; } bool SettingsDialog::exec() { bool ts_pressed = false, inputAction = false; uint32_t i, iY, firstElement = 0, action = SD_NO_ACTION, rowHeight, numRows; string readSetting = title + " " + voices[selected]->getTitle() + " " + voices[selected]->getDescription(); gmenu2x->allyTTS(readSetting.c_str(), MEDIUM_GAP_TTS, MEDIUM_SPEED_TTS, 0); while (loop) { bool ally = false; gmenu2x->menu->initLayout(); gmenu2x->font->setSize(gmenu2x->skinConfInt["fontSize"])->setColor(gmenu2x->skinConfColors[COLOR_FONT])->setOutlineColor(gmenu2x->skinConfColors[COLOR_FONT_OUTLINE]); gmenu2x->titlefont->setSize(gmenu2x->skinConfInt["fontSizeTitle"])->setColor(gmenu2x->skinConfColors[COLOR_FONT_ALT])->setOutlineColor(gmenu2x->skinConfColors[COLOR_FONT_ALT_OUTLINE]); rowHeight = gmenu2x->font->getHeight() + 1; numRows = (gmenu2x->listRect.h - 2)/rowHeight - 1; gmenu2x->setInputSpeed(); voices[selected]->adjustInput(); this->description = voices[selected]->getDescription(); drawDialog(gmenu2x->s); //Selection if (selected >= firstElement + numRows) firstElement = selected - numRows; if (selected < firstElement) firstElement = selected; iY = gmenu2x->listRect.y + 1; for (i = firstElement; i < voices.size() && i <= firstElement + numRows; i++, iY += rowHeight) { if (i == selected) { gmenu2x->s->box(gmenu2x->listRect.x, iY, gmenu2x->listRect.w, rowHeight, gmenu2x->skinConfColors[COLOR_SELECTION_BG]); voices[selected]->drawSelected(iY); } voices[i]->draw(iY); } gmenu2x->drawScrollBar(numRows, voices.size(), firstElement, gmenu2x->listRect); gmenu2x->s->flip(); do { inputAction = gmenu2x->input.update(); if (gmenu2x->inputCommonActions(inputAction)) continue; action = SD_NO_ACTION; if (!(action = voices[selected]->manageInput())) { if (gmenu2x->input[UP] || gmenu2x->input.hatEvent(DUP) == DUP) action = SD_ACTION_UP; else if (gmenu2x->input[DOWN] || gmenu2x->input.hatEvent(DDOWN) == DDOWN) action = SD_ACTION_DOWN; else if (gmenu2x->input[PAGEUP]) action = SD_ACTION_PAGEUP; else if (gmenu2x->input[PAGEDOWN]) action = SD_ACTION_PAGEDOWN; else if (gmenu2x->input[SETTINGS]) action = SD_ACTION_SAVE; else if (gmenu2x->input[CANCEL] && (allowCancel)) action = SD_ACTION_CLOSE; else if (gmenu2x->input[CANCEL] && (allowCancel_nomb)) action = SD_ACTION_CLOSE_NOMB; else if (gmenu2x->input[CANCEL] && (allowCancel_link)) action = SD_ACTION_CLOSE_LINK; else if (gmenu2x->input[CANCEL] && (allowCancel_link_nomb)) action = SD_ACTION_CLOSE_LINK_NOMB; } switch (action) { case SD_ACTION_SAVE: save = true; loop = false; break; case SD_ACTION_CLOSE: loop = false; if (allowCancel && edited()) { MessageBox mb(gmenu2x, gmenu2x->tr["Save changes?"], this->icon); mb.setButton(CONFIRM, gmenu2x->tr["Yes"]); mb.setButton(CANCEL, gmenu2x->tr["No"]); int res = mb.exec(); switch (res) { case CONFIRM: { save = true; break; } case CANCEL: { gmenu2x->reinit(); break; } } } break; case SD_ACTION_CLOSE_NOMB: loop = false; if (allowCancel_nomb) { if (gmenu2x->input[CONFIRM]) { gmenu2x->writeConfig(); gmenu2x->writeSkinConfig(); break; } else if (gmenu2x->input[CANCEL]) { gmenu2x->reinit(); break; } } case SD_ACTION_CLOSE_LINK: loop = false; if (allowCancel_link && edited()) { MessageBox mb(gmenu2x, gmenu2x->tr["Save changes?"], this->icon); mb.setButton(CONFIRM, gmenu2x->tr["Yes"]); mb.setButton(CANCEL, gmenu2x->tr["No"]); save = (mb.exec() == CONFIRM); } break; case SD_ACTION_CLOSE_LINK_NOMB: loop = false; if (allowCancel_link_nomb && edited()) { save = CONFIRM; } break; case SD_ACTION_UP: ally = true; selected--; break; case SD_ACTION_DOWN: ally = true; selected++; break; case SD_ACTION_PAGEUP: ally = true; selected -= numRows; if (selected < 0) selected = 0; break; case SD_ACTION_PAGEDOWN: ally = true; selected += numRows; if (selected >= voices.size()) selected = voices.size() - 1; break; } } while (!inputAction); if (selected < 0) selected = voices.size() - 1; if (selected >= voices.size()) selected = 0; if (ally) { readSetting = voices[selected]->getTitle() + " " + voices[selected]->getDescription(); // read whole text for more clarity gmenu2x->allyTTS(readSetting.c_str(), MEDIUM_GAP_TTS, MEDIUM_SPEED_TTS, 0); } } gmenu2x->setInputSpeed(); return true; } void SettingsDialog::addSetting(MenuSetting* set) { voices.push_back(set); } bool SettingsDialog::edited() { for (uint32_t i = 0; i < voices.size(); i++) if (voices[i]->edited()) return true; return false; }
6,695
C++
.cpp
164
36.359756
186
0.607
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,075
messagebox.cpp
MiyooCFW_gmenu2x/src/messagebox.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "messagebox.h" #include "powermanager.h" #include "debug.h" using namespace std; MessageBox::MessageBox(GMenu2X *gmenu2x, vector<MenuOption> options): gmenu2x(gmenu2x) { bool inputAction = false; int32_t selected = 0; uint32_t i, fadeAlpha = 0, h = gmenu2x->font->getHeight(), h2 = gmenu2x->font->getHalfHeight(); SDL_Rect box; Surface bg(gmenu2x->s); gmenu2x->input.dropEvents(); // prevent passing input away gmenu2x->powerManager->clearTimer(); box.h = h * options.size() + 8; box.w = 0; for (i = 0; i < options.size(); i++) { box.w = max(gmenu2x->font->getTextWidth(options[i].text), box.w); }; box.w += 23; box.x = (gmenu2x->w - box.w) / 2; box.y = (gmenu2x->h - box.h) / 2; uint32_t tickStart = SDL_GetTicks(); while (true) { if (selected < 0) selected = options.size() - 1; if (selected >= options.size()) selected = 0; bg.blit(gmenu2x->s, 0, 0); gmenu2x->s->box(0, 0, gmenu2x->w, gmenu2x->h, 0,0,0, fadeAlpha); gmenu2x->s->box(box.x, box.y, box.w, box.h, gmenu2x->skinConfColors[COLOR_MESSAGE_BOX_BG]); gmenu2x->s->rectangle(box.x + 2, box.y + 2, box.w - 4, box.h - 4, gmenu2x->skinConfColors[COLOR_MESSAGE_BOX_BORDER]); // draw selection rect gmenu2x->s->box(box.x + 4, box.y + 4 + h * selected, box.w - 8, h, gmenu2x->skinConfColors[COLOR_MESSAGE_BOX_SELECTION]); for (i = 0; i < options.size(); i++) gmenu2x->s->write(gmenu2x->font, options[i].text, box.x + 12, box.y + h2 + 3 + h * i, VAlignMiddle, gmenu2x->skinConfColors[COLOR_FONT_ALT], gmenu2x->skinConfColors[COLOR_FONT_ALT_OUTLINE]); gmenu2x->s->flip(); if (fadeAlpha < 200) { fadeAlpha = intTransition(0, 200, tickStart, 200); continue; } do { string readOption = options[selected].text; gmenu2x->allyTTS(readOption.c_str(), MEDIUM_GAP_TTS, MEDIUM_SPEED_TTS, 0); inputAction = gmenu2x->input.update(); if (gmenu2x->inputCommonActions(inputAction)) continue; if (gmenu2x->input[MENU] || gmenu2x->input[CANCEL]) return; else if (gmenu2x->input[UP] || gmenu2x->input.hatEvent(DUP) == DUP) selected--; else if (gmenu2x->input[DOWN] || gmenu2x->input.hatEvent(DDOWN) == DDOWN) selected++; else if (gmenu2x->input[LEFT] || gmenu2x->input.hatEvent(DLEFT) == DLEFT || gmenu2x->input[PAGEUP]) selected = 0; else if (gmenu2x->input[RIGHT] || gmenu2x->input.hatEvent(DRIGHT) == DRIGHT || gmenu2x->input[PAGEDOWN]) selected = (int)options.size() - 1; else if (gmenu2x->input[SETTINGS] || gmenu2x->input[CONFIRM]) { options[selected].action(); return; } } while (!inputAction); } } MessageBox::MessageBox(GMenu2X *gmenu2x, const string &text, const string &icon): gmenu2x(gmenu2x), text(text), icon(icon) { buttonText.resize(19); button.resize(19); buttonPosition.resize(19); bool anyaction = false; for (uint32_t x = 0; x < buttonText.size(); x++) { buttonText[x] = ""; button[x] = ""; buttonPosition[x].h = gmenu2x->font->getHeight(); anyaction = true; } if (!anyaction) // Default enabled button buttonText[CONFIRM] = "OK"; // Default labels button[UP] = "up"; button[DOWN] = "down"; button[LEFT] = "left"; button[RIGHT] = "right"; button[MODIFIER] = "x"; button[CONFIRM] = "a"; button[CANCEL] = "b"; button[MANUAL] = "y"; button[DEC] = "x"; button[INC] = "y"; button[SECTION_PREV] = "l"; button[SECTION_NEXT] = "r"; button[PAGEUP] = "l"; button[PAGEDOWN] = "r"; button[SETTINGS] = "start"; button[MENU] = "select"; button[VOLUP] = "vol+"; button[VOLDOWN] = "vol-"; } MessageBox::~MessageBox() { gmenu2x->input.dropEvents(); // prevent passing input away gmenu2x->powerManager->resetSuspendTimer(); clearTimer(); } void MessageBox::setButton(int action, const string &btn) { buttonText[action] = btn; } void MessageBox::setAutoHide(uint32_t autohide) { if (autohide == 0) { loophide = true; autohide = 1; } this->autohide = autohide; } void MessageBox::setBgAlpha(uint32_t bgalpha) { this->bgalpha = bgalpha; } int MessageBox::exec() { int fadeAlpha = 0, ix = 0; SDL_Rect box; Surface bg(gmenu2x->s); gmenu2x->input.dropEvents(); // prevent passing input away gmenu2x->powerManager->clearTimer(); Surface *icn = gmenu2x->sc.add(icon, icon + "mb"); box.h = gmenu2x->font->getTextHeight(text) * gmenu2x->font->getHeight() + gmenu2x->font->getHeight(); if (icn != NULL && box.h < 40) box.h = 48; box.w = gmenu2x->font->getTextWidth(text) + 24; for (uint32_t i = 0; i < buttonText.size(); i++) { if (!buttonText[i].empty()) ix += gmenu2x->font->getTextWidth(buttonText[i]) + 24; } ix += 6; if (ix > box.w) box.w = ix; ix = (icn != NULL ? 42 : 0); box.w += ix; box.x = (gmenu2x->w - box.w) / 2 - 2; box.y = (gmenu2x->h - box.h) / 2 - 2; uint32_t tickStart = SDL_GetTicks(); do { bg.blit(gmenu2x->s, 0, 0); // Darken background gmenu2x->s->box(0, 0, gmenu2x->w, gmenu2x->h, 0,0,0, fadeAlpha); fadeAlpha = intTransition(0, bgalpha, tickStart, 200); // outer box gmenu2x->s->box(box, gmenu2x->skinConfColors[COLOR_MESSAGE_BOX_BG]); // draw inner rectangle gmenu2x->s->rectangle(box.x + 2, box.y + 2, box.w - 4, box.h - 4, gmenu2x->skinConfColors[COLOR_MESSAGE_BOX_BORDER]); // icon+text if (icn != NULL) { gmenu2x->s->setClipRect({box.x + 8, box.y + 8, 32, 32}); if (icn->width() > 32 || icn->height() > 32) icn->softStretch(32, 32, SScaleFit); icn->blit(gmenu2x->s, box.x + 24, box.y + 24, HAlignCenter | VAlignMiddle); gmenu2x->s->clearClipRect(); } // gmenu2x->s->box(ix + box.x, box.y, (box.w - ix), box.h, strtorgba("ffff00ff")); gmenu2x->s->write(gmenu2x->font, text, ix + box.x + (box.w - ix) / 2, box.y + box.h / 2, HAlignCenter | VAlignMiddle, gmenu2x->skinConfColors[COLOR_FONT_ALT], gmenu2x->skinConfColors[COLOR_FONT_ALT_OUTLINE]); if (!this->autohide) { // draw buttons rectangle gmenu2x->s->box(box.x, box.y+box.h, box.w, gmenu2x->font->getHeight(), gmenu2x->skinConfColors[COLOR_MESSAGE_BOX_BG]); int btnX = (gmenu2x->w + box.w) / 2 - 6; for (uint32_t i = 0; i < buttonText.size(); i++) { if (!buttonText[i].empty()) { buttonPosition[i].y = box.y+box.h+gmenu2x->font->getHalfHeight(); buttonPosition[i].w = btnX; btnX = gmenu2x->drawButtonRight(gmenu2x->s, button[i], buttonText[i], btnX, buttonPosition[i].y); buttonPosition[i].x = btnX; buttonPosition[i].w = buttonPosition[i].x-btnX-6; } } } gmenu2x->s->flip(); } while (fadeAlpha < bgalpha); if (this->autohide) { // gmenu2x->powerManager->resetSuspendTimer(); // prevent immediate suspend if (loophide) { while (!(gmenu2x->input[CONFIRM] || gmenu2x->input[CANCEL] || gmenu2x->input[SETTINGS] || gmenu2x->input[MENU])) gmenu2x->input.update(); } SDL_Delay(this->autohide); return -1; } while (true) { // touchscreen // if (gmenu2x->f200 && gmenu2x->ts.poll()) { // for (uint32_t i = 0; i < buttonText.size(); i++) { // if (buttonText[i] != "" && gmenu2x->ts.inRect(buttonPosition[i])) { // result = i; // break; // } // } // } string strButtons, strButtonsText; for (uint32_t i = 0; i < buttonText.size(); i++) { if (buttonText[i] != "") { if (button[i] == "a") button[i] = "[[eI]]"; //espeak doesn't recognize if it's a letter or article so let us use Phoneme Input for "A" letter strButtons += " " + button[i] + " is " + buttonText[i]; } } string strMessage = text; string readMessage = strMessage + " " + strButtons; gmenu2x->allyTTS(readMessage.c_str(), SLOW_GAP_TTS, SLOW_SPEED_TTS, 0); bool inputAction = gmenu2x->input.update(); if (inputAction) { // if (gmenu2x->inputCommonActions(inputAction)) continue; // causes power button bounce for (uint32_t i = 0; i < buttonText.size(); i++) { if (buttonText[i] != "" && gmenu2x->input[i]) { return i; break; } } } } return -1; } void MessageBox::exec(uint32_t timeOut) { clearTimer(); popupTimer = SDL_AddTimer(timeOut, execTimer, this); } void MessageBox::clearTimer() { SDL_RemoveTimer(popupTimer); popupTimer = NULL; } uint32_t MessageBox::execTimer(uint32_t interval, void *param) { MessageBox *mb = reinterpret_cast<MessageBox *>(param); mb->clearTimer(); mb->exec(); return 0; }
9,612
C++
.cpp
238
37.508403
210
0.622706
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,076
wallpaperdialog.cpp
MiyooCFW_gmenu2x/src/wallpaperdialog.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "wallpaperdialog.h" #include "messagebox.h" #include "filelister.h" #include "debug.h" using namespace std; WallpaperDialog::WallpaperDialog(GMenu2X *gmenu2x, const string &title, const string &description, const string &icon): Dialog(gmenu2x, title, description, icon) {} WallpaperDialog::~WallpaperDialog() { for (uint32_t i = 0; i < wallpapers.size(); i++) { if (!gmenu2x->sc.del("skins/" + gmenu2x->confStr["skin"] + "/wallpapers/" + wallpapers[i])) { gmenu2x->sc.del("skins/Default/wallpapers/" + wallpapers[i]); } } } bool WallpaperDialog::exec() { bool inputAction = false; uint32_t i, iY, firstElement = 0; uint32_t rowHeight = gmenu2x->font->getHeight() + 1; uint32_t numRows = (gmenu2x->listRect.h - 2) / rowHeight - 1; int32_t selected = 0; string skin = gmenu2x->confStr["skin"]; FileLister fl; fl.setFilter(".png,.jpg,.jpeg,.bmp"); fl.setPath("skins/" + skin + "/wallpapers"); fl.browse(); wallpapers = fl.getFiles(); if (skin != "Default") { fl.setPath("skins/Default/wallpapers"); fl.browse(); for (uint32_t i = 0; i < fl.getFiles().size(); i++) wallpapers.push_back(fl.getFiles()[i]); } wallpaper = base_name(gmenu2x->confStr["tmp_wallpaper"]); for (uint32_t i = 0; i < wallpapers.size(); i++) { if (wallpaper == wallpapers[i]) { selected = i; break; } } buttons.push_back({"select", gmenu2x->tr["Menu"]}); buttons.push_back({"b", gmenu2x->tr["Cancel"]}); buttons.push_back({"a", gmenu2x->tr["Select"]}); while (true) { if (selected < 0) selected = wallpapers.size() - 1; if (selected >= wallpapers.size()) selected = 0; skin = "Default"; if (selected < wallpapers.size() - fl.getFiles().size()) { skin = gmenu2x->confStr["skin"]; } gmenu2x->setBackground(this->bg, "skins/" + skin + "/wallpapers/" + wallpapers[selected]); gmenu2x->allyTTS(wallpapers[selected].c_str(), FAST_GAP_TTS, FAST_SPEED_TTS, 0); drawDialog(gmenu2x->s); if (wallpaper.size() < 1) { MessageBox mb(gmenu2x, gmenu2x->tr["No wallpapers available"]); mb.setAutoHide(1); mb.setBgAlpha(0); mb.exec(); } else { // Selection if (selected >= firstElement + numRows) firstElement = selected - numRows; if (selected < firstElement) firstElement = selected; // Files & Directories iY = gmenu2x->listRect.y + 1; for (i = firstElement; i < wallpapers.size() && i <= firstElement + numRows; i++, iY += rowHeight) { if (i == selected) gmenu2x->s->box(gmenu2x->listRect.x, iY, gmenu2x->listRect.w, rowHeight, gmenu2x->skinConfColors[COLOR_SELECTION_BG]); gmenu2x->s->write(gmenu2x->font, wallpapers[i], gmenu2x->listRect.x + 5, iY + rowHeight/2, VAlignMiddle); } gmenu2x->drawScrollBar(numRows, wallpapers.size(), firstElement, gmenu2x->listRect); gmenu2x->s->flip(); } do { inputAction = gmenu2x->input.update(); if (gmenu2x->inputCommonActions(inputAction)) continue; if (gmenu2x->input[UP] || gmenu2x->input.hatEvent(DUP) == DUP) { selected--; } else if (gmenu2x->input[DOWN] || gmenu2x->input.hatEvent(DDOWN) == DDOWN) { selected++; } else if (gmenu2x->input[PAGEUP] || gmenu2x->input[LEFT] || gmenu2x->input.hatEvent(DLEFT) == DLEFT) { selected -= numRows; if (selected < 0) selected = 0; } else if (gmenu2x->input[PAGEDOWN] || gmenu2x->input[RIGHT] || gmenu2x->input.hatEvent(DRIGHT) == DRIGHT) { selected += numRows; if (selected >= wallpapers.size()) selected = wallpapers.size() - 1; } else if (gmenu2x->input[MENU] || gmenu2x->input[CANCEL]) { return false; } else if ((gmenu2x->input[SETTINGS] || gmenu2x->input[CONFIRM]) && wallpapers.size() > 0) { if (selected < wallpapers.size() - fl.getFiles().size()) { wallpaper = "skins/" + gmenu2x->confStr["skin"] + "/wallpapers/" + wallpapers[selected]; } else { wallpaper = "skins/Default/wallpapers/" + wallpapers[selected]; } return true; } } while (!inputAction); } }
5,340
C++
.cpp
115
43.304348
141
0.603766
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,077
menusettingbool.cpp
MiyooCFW_gmenu2x/src/menusettingbool.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "menusettingbool.h" #include "gmenu2x.h" using fastdelegate::MakeDelegate; MenuSettingBool::MenuSettingBool(GMenu2X *gmenu2x, const string &title, const string &description, int *value): MenuSetting(gmenu2x, title, description), _ivalue(value) { _value = NULL; originalValue = *value != 0; setValue(this->value(), 0); initButton(); } MenuSettingBool::MenuSettingBool(GMenu2X *gmenu2x, const string &title, const string &description, bool *value): MenuSetting(gmenu2x, title, description), _value(value) { _ivalue = NULL; originalValue = *value; setValue(this->value(), 0); initButton(); } void MenuSettingBool::initButton() { ButtonAction actionToggle = MakeDelegate(this, &MenuSettingBool::toggle); btn = new IconButton(gmenu2x, "dpad", gmenu2x->tr["Change"]); btn->setAction(actionToggle); buttonBox.add(btn); } void MenuSettingBool::draw(int y) { MenuSetting::draw(y); RGBAColor color = (RGBAColor){255, 0, 0, 255}; if (value()) color = (RGBAColor) {0, 255, 0, 255}; int w = gmenu2x->font->getHeight()/2.5; gmenu2x->s->box(180, y + 1, w, gmenu2x->font->getHeight() - 2, color); gmenu2x->s->rectangle(180, y + 1, w, gmenu2x->font->getHeight() - 2, 0, 0, 0, 255); gmenu2x->s->write(gmenu2x->font, strvalue, 180 + w + 2, y + gmenu2x->font->getHalfHeight(), VAlignMiddle); } uint32_t MenuSettingBool::manageInput() { if (gmenu2x->input[LEFT] || gmenu2x->input[RIGHT] || gmenu2x->input[CONFIRM] || gmenu2x->input.hatEvent(DLEFT) == DLEFT || gmenu2x->input.hatEvent(DRIGHT) == DRIGHT) toggle(); else if (gmenu2x->input[MODIFIER] && !gmenu2x->input[MANUAL]) current(); return 0; // SD_NO_ACTION } void MenuSettingBool::toggle() { setValue(!value(), 1); } void MenuSettingBool::current() { setValue(value(), 1); } void MenuSettingBool::setValue(int value) { setValue(value != 0); } void MenuSettingBool::setValue(bool value, bool readValue) { if (_value == NULL) *_ivalue = value; else *_value = value; strvalue = value ? "ON" : "OFF"; if (readValue) gmenu2x->allyTTS(strvalue.c_str(), SLOW_GAP_TTS, SLOW_SPEED_TTS, 0); } bool MenuSettingBool::value() { if (_value == NULL) return *_ivalue != 0; return *_value; } bool MenuSettingBool::edited() { return originalValue != value(); }
3,646
C++
.cpp
83
42.036145
112
0.602987
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,078
terminaldialog.cpp
MiyooCFW_gmenu2x/src/terminaldialog.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "terminaldialog.h" #include "messagebox.h" #include "utilities.h" #include "powermanager.h" #include "debug.h" using namespace std; TerminalDialog::TerminalDialog(GMenu2X *gmenu2x, const string &title, const string &description, const string &icon, const string &backdrop): TextDialog(gmenu2x, title, description, icon, backdrop) {} void TerminalDialog::exec(string cmd) { rowsPerPage = gmenu2x->listRect.h/gmenu2x->font->getHeight(); if (gmenu2x->sc[this->icon] == NULL) this->icon = "skin:icons/terminal.png"; buttons.push_back({"skin:imgs/manual.png", gmenu2x->tr["Running.. Please wait.."]}); drawDialog(gmenu2x->s); gmenu2x->s->flip(); if (file_exists("/usr/bin/script")) cmd = "/usr/bin/script -q -c " + cmdclean(cmd) + " /dev/null 2>&1"; else cmd = "/bin/sh -c " + cmdclean(cmd) + " 2>&1"; FILE* pipe = popen(cmd.c_str(), "r"); if (!pipe) return; char buffer[128]; gmenu2x->powerManager->clearTimer(); gmenu2x->allyTTS(gmenu2x->tr["Processing output."].c_str(), MEDIUM_GAP_TTS, MEDIUM_SPEED_TTS, 1); while (!feof(pipe) && fgets(buffer, 128, pipe) != NULL) { rawText += buffer; split(text, rawText, "\r\n"); lineWidth = drawText(&text, firstCol, -1, rowsPerPage); } pclose(pipe); pipe = NULL; system("sync &"); MessageBox mb(gmenu2x, gmenu2x->tr["Done processing."]); mb.setAutoHide(0); string readText = gmenu2x->tr["Done processing."] + /*PAUSE*/ "[[_::_::]]" + gmenu2x->tr["Terminal output as follows"] + /*PAUSE*/ "[[_::_::_::]]" + rawText; gmenu2x->allyTTS(readText.c_str()); mb.exec(); if (text.size() >= rowsPerPage) firstRow = text.size() - rowsPerPage; buttons.clear(); TextDialog::exec(); }
3,077
C++
.cpp
60
49.033333
158
0.567234
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,079
touchscreen.cpp
MiyooCFW_gmenu2x/src/touchscreen.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ // #include <unistd.h> // #include <iostream> #include "touchscreen.h" using namespace std; Touchscreen::Touchscreen() { wm97xx = 0; calibrated = false; wasPressed = false; _handled = false; x = 0; y = 0; startX = 0; startY = 0; event.x = 0; event.y = 0; event.pressure = 0; } Touchscreen::~Touchscreen() { if (wm97xx) deinit(); } bool Touchscreen::init() { #ifdef TARGET_GP2X wm97xx = open("/dev/touchscreen/wm97xx", O_RDONLY|O_NOCTTY); #endif return initialized(); } bool Touchscreen::initialized() { #ifdef TARGET_GP2X return wm97xx>0; #else return true; #endif } void Touchscreen::deinit() { #ifdef TARGET_GP2X close(wm97xx); wm97xx = 0; #endif } void Touchscreen::calibrate() { if (event.pressure==0) { calibX = ((event.x-200)*320/3750)/4; calibY = (((event.y-200)*240/3750))/4; calibrated = true; } } bool Touchscreen::poll() { wasPressed = pressed(); #ifdef TARGET_GP2X read(wm97xx, &event, sizeof(TS_EVENT)); if (!calibrated) calibrate(); if (event.pressure>0) { x = ((event.x-200)*320/3750)-calibX; y = (240 - ((event.y-200)*240/3750))-calibY; } #else SDL_PumpEvents(); int mx, my; if (SDL_GetMouseState(&mx,&my) && SDL_BUTTON(1)) { x = mx; y = my; event.pressure = 1; } else { event.pressure = 0; } #endif _handled = false; if (!wasPressed && pressed()) { startX = x; startY = y; } return pressed(); } bool Touchscreen::handled() { return _handled; } void Touchscreen::setHandled() { wasPressed = false; _handled = true; } bool Touchscreen::pressed() { return !_handled && event.pressure>0; } bool Touchscreen::released() { return !pressed() && wasPressed; } bool Touchscreen::inRect(SDL_Rect r) { return !_handled && (y>=r.y) && (y<=r.y+r.h) && (x>=r.x) && (x<=r.x+r.w); } bool Touchscreen::inRect(int x, int y, int w, int h) { SDL_Rect rect = {x,y,w,h}; return inRect(rect); } bool Touchscreen::startedInRect(SDL_Rect r) { return !_handled && (startY>=r.y) && (startY<=r.y+r.h) && (startX>=r.x) && (startX<=r.x+r.w); } bool Touchscreen::startedInRect(int x, int y, int w, int h) { SDL_Rect rect = {x,y,w,h}; return startedInRect(rect); }
3,542
C++
.cpp
119
27.87395
94
0.572604
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
1,534,080
textdialog.cpp
MiyooCFW_gmenu2x/src/textdialog.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "textdialog.h" #include "messagebox.h" // #include "debug.h" using namespace std; #include <fstream> #include <sstream> TextDialog::TextDialog(GMenu2X *gmenu2x, const string &title, const string &description, const string &icon, const string &backdrop): Dialog(gmenu2x, title, description, icon), backdrop(backdrop) {} void TextDialog::preProcess() { uint32_t i = 0; string row; split(text, rawText, "\n"); while (i < text.size()) { //clean this row row = trim(text.at(i)); //check if this row is not too long if (gmenu2x->font->getTextWidth(row) > gmenu2x->w - 15) { vector<string> words; split(words, row, " "); uint32_t numWords = words.size(); //find the maximum number of rows that can be printed on screen while (gmenu2x->font->getTextWidth(row) > gmenu2x->w - 15 && numWords > 0) { numWords--; row = ""; for (uint32_t x = 0; x < numWords; x++) row += words[x] + " "; row = trim(row); } //if numWords==0 then the string must be printed as-is, it cannot be split if (numWords > 0) { //replace with the shorter version text.at(i) = row; //build the remaining text in another row row = ""; for (uint32_t x = numWords; x < words.size(); x++) row += words[x] + " "; row = trim(row); if (!row.empty()) text.insert(text.begin() + i + 1, row); } } i++; } } int TextDialog::drawText(vector<string> *text, int32_t firstCol, int32_t firstRow, uint32_t rowsPerPage) { drawDialog(gmenu2x->s); gmenu2x->s->setClipRect(gmenu2x->listRect); int mx = 0; if (firstRow < 0 && text->size() >= rowsPerPage) firstRow = text->size() - rowsPerPage; if (firstRow < 0) firstRow = 0; int fh = gmenu2x->font->getHeight(); for (uint32_t i = firstRow; i < firstRow + rowsPerPage && i < text->size(); i++) { int y = gmenu2x->listRect.y + (i - firstRow) * fh; mx = max(mx, gmenu2x->font->getTextWidth(text->at(i))); if (text->at(i) == "----") { // draw a line gmenu2x->s->box(5, y - 1 + fh / 2, gmenu2x->w - 10, 1, 255, 255, 255, 130); gmenu2x->s->box(5, y + fh / 2, gmenu2x->w - 10, 1, 0, 0, 0, 130); } else { gmenu2x->font->write(gmenu2x->s, text->at(i), 5 + firstCol, y); } } gmenu2x->s->clearClipRect(); gmenu2x->drawScrollBar(rowsPerPage, text->size(), firstRow, gmenu2x->listRect); gmenu2x->s->flip(); return mx; } void TextDialog::exec() { if (gmenu2x->sc[backdrop] != NULL) gmenu2x->sc[backdrop]->blit(this->bg,0,0); preProcess(); bool inputAction = false; rowsPerPage = gmenu2x->listRect.h / gmenu2x->font->getHeight(); if (gmenu2x->sc[this->icon] == NULL) this->icon = "skin:icons/ebook.png"; buttons.push_back({"dpad", gmenu2x->tr["Scroll"]}); buttons.push_back({"b", gmenu2x->tr["Exit"]}); drawDialog(gmenu2x->s); while (true) { if (gmenu2x->confStr["previewMode"] == "Backdrop") { if (!backdrop.empty()) gmenu2x->setBackground(this->bg, backdrop); else gmenu2x->bg->blit(this->bg,0,0); } lineWidth = drawText(&text, firstCol, firstRow, rowsPerPage); do { inputAction = gmenu2x->input.update(); if (gmenu2x->inputCommonActions(inputAction)) continue; if ((gmenu2x->input[UP] || gmenu2x->input.hatEvent(DUP) == DUP) && firstRow > 0) firstRow--; else if ((gmenu2x->input[DOWN] || gmenu2x->input.hatEvent(DDOWN) == DDOWN) && firstRow + rowsPerPage < text.size()) firstRow++; else if ((gmenu2x->input[RIGHT] || gmenu2x->input.hatEvent(DRIGHT) == DRIGHT) && firstCol > -1 * (lineWidth - gmenu2x->listRect.w) - 10) firstCol -= 30; else if ((gmenu2x->input[LEFT] || gmenu2x->input.hatEvent(DLEFT) == DLEFT) && firstCol < 0) firstCol += 30; // TODO: Fix HAT events not being registered twice on the same loop run else if (gmenu2x->input[PAGEUP] || ((gmenu2x->input[LEFT] || gmenu2x->input.hatEvent(DLEFT) == DLEFT) && firstCol == 0)) { if (firstRow >= rowsPerPage - 1) firstRow -= rowsPerPage - 1; else firstRow = 0; } else if (gmenu2x->input[PAGEDOWN] || ((gmenu2x->input[RIGHT] || gmenu2x->input.hatEvent(DRIGHT) == DRIGHT) && firstCol == 0)) { if (firstRow + rowsPerPage * 2 - 1 < text.size()) firstRow += rowsPerPage - 1; else firstRow = max(0, text.size() - rowsPerPage); } else if (gmenu2x->input[SETTINGS] || gmenu2x->input[CANCEL]) return; } while (!inputAction); } } void TextDialog::appendText(const string &text) { this->rawText += text; } void TextDialog::appendFile(const string &file) { ifstream t(file); stringstream buf; buf << t.rdbuf(); this->rawText += buf.str(); }
5,956
C++
.cpp
136
40.595588
155
0.596785
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,081
menusettingrgba.cpp
MiyooCFW_gmenu2x/src/menusettingrgba.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "menusettingrgba.h" #include "gmenu2x.h" #include <sstream> using std::string; using std::stringstream; using fastdelegate::MakeDelegate; MenuSettingRGBA::MenuSettingRGBA(GMenu2X *gmenu2x, const string &title, const string &description, RGBAColor *value): MenuSetting(gmenu2x, title, description) { selPart = 0; _value = value; originalValue = *value; this->setR(this->value().r); this->setG(this->value().g); this->setB(this->value().b); this->setA(this->value().a); btn = new IconButton(gmenu2x, "a", gmenu2x->tr["Edit"]); buttonBox.add(btn); } void MenuSettingRGBA::draw(int y) { this->y = y; MenuSetting::draw(y); gmenu2x->s->box(153, y + (gmenu2x->font->getHeight()/2) - 6, 12, 12, value()); gmenu2x->s->rectangle(153, y + (gmenu2x->font->getHeight()/2) - 6, 12, 12, 0, 0, 0, 255); gmenu2x->s->write(gmenu2x->font, /*"R: "+*/ strR, 169, y + gmenu2x->font->getHalfHeight(), VAlignMiddle); gmenu2x->s->write(gmenu2x->font, /*"G: "+*/ strG, 205, y + gmenu2x->font->getHalfHeight(), VAlignMiddle); gmenu2x->s->write(gmenu2x->font, /*"B: "+*/ strB, 241, y + gmenu2x->font->getHalfHeight(), VAlignMiddle); gmenu2x->s->write(gmenu2x->font, /*"A: "+*/ strA, 277, y + gmenu2x->font->getHalfHeight(), VAlignMiddle); } void MenuSettingRGBA::drawSelected(int y) { if (editing) { int x = 166 + selPart * 36; RGBAColor color; switch (selPart) { case 0: color = (RGBAColor){255, 0, 0, 255}; break; case 1: color = (RGBAColor){ 0, 255, 0, 255}; break; case 2: color = (RGBAColor){ 0, 0, 255, 255}; break; default: color = gmenu2x->skinConfColors[COLOR_SELECTION_BG]; break; } gmenu2x->s->box(x, y, 36, gmenu2x->font->getHeight() + 1, color); gmenu2x->s->rectangle(x, y, 36, gmenu2x->font->getHeight() + 1, 0, 0, 0,255); } MenuSetting::drawSelected(y); } uint32_t MenuSettingRGBA::manageInput() { if (editing) { if (gmenu2x->input[SETTINGS]) return 0; if (gmenu2x->input[INC] || gmenu2x->input[UP] || gmenu2x->input.hatEvent(DUP) == DUP) inc(); else if (gmenu2x->input[DEC] || gmenu2x->input[DOWN] || gmenu2x->input.hatEvent(DDOWN) == DDOWN) dec(); else if (gmenu2x->input[MODIFIER] && !gmenu2x->input[MANUAL]) current(); else if (gmenu2x->input[LEFT] || gmenu2x->input.hatEvent(DLEFT) == DLEFT) leftComponent(); else if (gmenu2x->input[RIGHT] || gmenu2x->input.hatEvent(DRIGHT) == DRIGHT) rightComponent(); else if (gmenu2x->input[CONFIRM] || gmenu2x->input[CANCEL]) { editing = false; buttonBox.remove(2); btn = new IconButton(gmenu2x, "a", gmenu2x->tr["Edit"]); buttonBox.add(btn); } return -1; } else if (gmenu2x->input[MODIFIER] && !gmenu2x->input[MANUAL]) { current(); } else if (gmenu2x->input[CONFIRM]) { editing = true; buttonBox.remove(1); btn = new IconButton(gmenu2x, "dpad", gmenu2x->tr["Edit"]); buttonBox.add(btn); btn = new IconButton(gmenu2x, "a", gmenu2x->tr["OK"]); buttonBox.add(btn); } return 0; } // void MenuSettingRGBA::handleTS() { // if (gmenu2x->ts.pressed()) { // for (int i=0; i<4; i++) { // if (i!=selPart && gmenu2x->ts.inRect(166+i*36,y,36,14)) { // selPart = i; // i = 4; // } // } // } // MenuSetting::handleTS(); // } void MenuSettingRGBA::dec() { setSelPart(constrain(getSelPart()-1,0,255)); } void MenuSettingRGBA::inc() { setSelPart(constrain(getSelPart()+1,0,255)); } void MenuSettingRGBA::current() { setSelPart(getSelPart()); } void MenuSettingRGBA::leftComponent() { selPart = constrain(selPart-1,0,3); } void MenuSettingRGBA::rightComponent() { selPart = constrain(selPart+1,0,3); } void MenuSettingRGBA::setR(uint16_t r) { _value->r = r; stringstream ss; ss << r; ss >> strR; } void MenuSettingRGBA::setG(uint16_t g) { _value->g = g; stringstream ss; ss << g; ss >> strG; } void MenuSettingRGBA::setB(uint16_t b) { _value->b = b; stringstream ss; ss << b; ss >> strB; } void MenuSettingRGBA::setA(uint16_t a) { _value->a = a; stringstream ss; ss << a; ss >> strA; } void MenuSettingRGBA::setSelPart(uint16_t value) { switch (selPart) { case 1: setG(value); break; case 2: setB(value); break; case 3: setA(value); break; default: setR(value); break; } string readRGBA = gmenu2x->tr["RGBA values are"] + " " + strR + " " + strG + " " + strB + " " + strA; gmenu2x->allyTTS(readRGBA.c_str(), MEDIUM_GAP_TTS, MEDIUM_SPEED_TTS, 0); } RGBAColor MenuSettingRGBA::value() { return *_value; } uint16_t MenuSettingRGBA::getSelPart() { switch (selPart) { case 1: return value().g; case 2: return value().b; case 3: return value().a; default: return value().r; } } void MenuSettingRGBA::adjustInput() { gmenu2x->input.setInterval(30, INC ); gmenu2x->input.setInterval(30, DEC ); } bool MenuSettingRGBA::edited() { return originalValue.r != value().r || originalValue.g != value().g || originalValue.b != value().b || originalValue.a != value().a; }
6,276
C++
.cpp
163
36.386503
133
0.61479
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,082
menusettingstringbase.cpp
MiyooCFW_gmenu2x/src/menusettingstringbase.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "menusettingstringbase.h" #include "gmenu2x.h" #include "debug.h" using std::string; MenuSettingStringBase::MenuSettingStringBase(GMenu2X *gmenu2x, const string &title, const string &description, string *value): MenuSetting(gmenu2x, title, description) , originalValue(*value) , _value(value) {} MenuSettingStringBase::~MenuSettingStringBase() {} void MenuSettingStringBase::draw(int y) { MenuSetting::draw(y); gmenu2x->s->write(gmenu2x->font, value(), 180, y + gmenu2x->font->getHalfHeight(), VAlignMiddle); } uint32_t MenuSettingStringBase::manageInput() { if (gmenu2x->input[MENU]) clear(); if (gmenu2x->input[CONFIRM]) edit(); if (gmenu2x->input[MODIFIER] && !gmenu2x->input[MANUAL]) current(); return 0; // SD_NO_ACTION } void MenuSettingStringBase::clear() { setValue(""); } void MenuSettingStringBase::current() { gmenu2x->allyTTS(value().c_str(), MEDIUM_GAP_TTS, MEDIUM_SPEED_TTS, 0); } bool MenuSettingStringBase::edited() { return originalValue != value(); }
2,399
C++
.cpp
45
51.533333
126
0.565217
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
1,534,083
utilities.cpp
MiyooCFW_gmenu2x/src/utilities.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ //for browsing the filesystem #include <sys/stat.h> #include <dirent.h> #include <math.h> #include <ctime> #include <sys/time.h> /* for settimeofday() */ #include <SDL.h> #include <algorithm> #include <fstream> #include "utilities.h" #include "debug.h" using namespace std; bool case_less::operator()(const string &left, const string &right) const { return strcasecmp(left.c_str(), right.c_str()) < 0; } // General tool to strip spaces from both ends: string trim(const string &s) { if (s.length() == 0) return s; int b = s.find_first_not_of(" \t\n\r"); int e = s.find_last_not_of(" \t\r\n"); if (b == -1) // No non-spaces return ""; return string(s, b, e - b + 1); } void string_copy(const string &s, char **cs) { *cs = (char*)malloc(s.length()); strcpy(*cs, s.c_str()); } char *string_copy(const string &s) { char *cs = NULL; string_copy(s, &cs); return cs; } bool dir_exists(const string &path) { struct stat s; return (stat(path.c_str(), &s) == 0 && s.st_mode & S_IFDIR); // exists and is dir } bool file_exists(const string &path) { struct stat s; return (stat(path.c_str(), &s) == 0 && s.st_mode & S_IFREG); // exists and is file } bool rmtree(string path) { DIR *dirp; struct stat st; struct dirent *dptr; string filepath; DEBUG("RMTREE: '%s'", path.c_str()); if ((dirp = opendir(path.c_str())) == NULL) return false; if (path[path.length() - 1] != '/') path += "/"; while ((dptr = readdir(dirp))) { filepath = dptr->d_name; if (filepath == "." || filepath == "..") continue; filepath = path + filepath; int statRet = stat(filepath.c_str(), &st); if (statRet == -1) continue; if (S_ISDIR(st.st_mode)) { if (!rmtree(filepath)) return false; } else { if (unlink(filepath.c_str()) != 0) return false; } } closedir(dirp); return rmdir(path.c_str()) == 0; } int max(int a, int b) { return a > b ? a : b; } float max(float a, float b) { return a > b ? a : b; } int min(int a, int b) { return a < b ? a : b; } float min(float a, float b) { return a < b ? a : b; } int constrain(int x, int imin, int imax) { return min(imax, max(imin, x)); } float constrain(float x, float imin, float imax) { return min(imax, max(imin, x)); } //Configuration parsing utilities int evalIntConf(int val, int def, int imin, int imax) { return evalIntConf(&val, def, imin, imax); } int evalIntConf(int *val, int def, int imin, int imax) { if (*val == 0 && (*val < imin || *val > imax)) *val = def; else *val = constrain(*val, imin, imax); return *val; } const string &evalStrConf(const string &val, const string &def) { return val.empty() ? def : val; } const string &evalStrConf(string *val, const string &def) { *val = evalStrConf(*val, def); return *val; } bool split(vector<string> &vec, const string &str, const string &delim, bool destructive) { vec.clear(); if (delim.empty()) { vec.push_back(str); return false; } std::string::size_type i = 0; std::string::size_type j = 0; while (true) { j = str.find(delim,i); if (j == std::string::npos) { vec.push_back(str.substr(i)); break; } if (!destructive) { j += delim.size(); } vec.push_back(str.substr(i,j-i)); if (destructive) { i = j + delim.size(); } if (i == str.size()) { vec.push_back(std::string()); break; } } return true; } string strreplace(string orig, const string &search, const string &replace) { string::size_type pos = orig.find(search, 0); while (pos != string::npos) { orig.replace(pos, search.length(), replace); pos = orig.find(search, pos + replace.length()); } return orig; } string cmdclean(string cmdline) { string spchars = "\\`$();|{}&'\"*?<>[]!^~-#\n\r "; for (uint32_t i = 0; i < spchars.length(); i++) { string curchar = spchars.substr(i, 1); cmdline = strreplace(cmdline, curchar, "\\" + curchar); } return cmdline; } int intTransition(int from, int to, int32_t tickStart, int32_t duration, int32_t tickNow) { if (tickNow < 0) tickNow = SDL_GetTicks(); float elapsed = (float)(tickNow - tickStart) / duration; // elapsed increments return min((int)round(elapsed * (to - from)), (int)max(from, to)); } string exec(const char* cmd) { FILE* pipe = popen(cmd, "r"); if (!pipe) return ""; char buffer[128]; string result = ""; while (!feof(pipe)) { if (fgets(buffer, 128, pipe) != NULL) result += buffer; } pclose(pipe); return result; } string real_path(const string &path) { char real_path[PATH_MAX]; char *ptr; ptr = realpath(path.c_str(), real_path); if (ptr == NULL && errno == ENOENT) { string outpath; vector<string> vpath; split(vpath, path, "/"); if (vpath.size() > 2) { int i = 1; vector<string>::iterator it = vpath.begin() + 1; while (it < vpath.end()) { if (*it == "." || it->empty()) { vpath.erase(vpath.begin() + i); } else if (*it == "..") { vpath.erase(vpath.begin() + i); vpath.erase(vpath.begin() + i - 1); it = vpath.begin() + 1; i = 1; } else { it++; i++; } } outpath = vpath.at(0) + "/"; for (vector<string>::iterator it = vpath.begin() + 1; it < vpath.end() - 1; ++it) { outpath += *it + "/"; } outpath += vpath.back(); } return outpath; } return (string)real_path; } string dir_name(const string &path) { string::size_type p = path.rfind("/"); if (p == path.size() - 1) p = path.rfind("/", p - 1); return real_path("/" + path.substr(0, p)); } string base_name(string path, bool strip_extension) { string::size_type p = path.rfind("/"); if (p == path.size() - 1) p = path.rfind("/", p - 1); path = path.substr(p + 1); if (strip_extension) { p = path.rfind('.'); path = path.substr(0, p); } return path; } string file_ext(const string &path, bool tolower) { string ext = ""; string::size_type pos = path.rfind("."); if (pos != string::npos && pos > 0) { ext = path.substr(pos); if (tolower) return lowercase(ext); } return ext; } string lowercase(string s) { transform(s.begin(), s.end(), s.begin(), ::tolower); return s; } bool file_copy(const string &src, const string &dst) { FILE *fs, *fd; fs = fopen(src.c_str(), "r"); if (fs == NULL) { ERROR("Cannot open source file %s\n", src.c_str()); return false; } fd = fopen(dst.c_str(), "w"); if (fd == NULL) { ERROR("Cannot open destiny file %s\n", src.c_str()); fclose(fs); return false; } // Read contents from file int c = fgetc(fs); while (c != EOF) { fputc(c, fd); c = fgetc(fs); } fclose(fs); fclose(fd); return true; } string file_read(const string& path) { if (!file_exists(path)) return 0; ifstream file(path); string content; if (file.is_open()) { getline(file, content); file.close(); } return content; } string unique_filename(string path, string ext) { uint32_t x = 0; string fname = path + ext; while (file_exists(fname)) { stringstream ss; ss << x; ss >> fname; fname = path + fname + ext; x++; } return fname; } string exe_path() { char real_path[PATH_MAX]; memset(real_path, 0, PATH_MAX); readlink("/proc/self/exe", real_path, PATH_MAX); return dir_name(real_path); } string disk_free(const char *path) { string df = "N/A"; struct statvfs b; if (statvfs(path, &b) == 0) { // Make sure that the multiplication happens in 64 bits. uint32_t freeMiB = ((uint64_t)b.f_bfree * b.f_bsize) / (1024 * 1024); uint32_t totalMiB = ((uint64_t)b.f_blocks * b.f_frsize) / (1024 * 1024); stringstream ss; if (totalMiB >= 10000) { ss << (freeMiB / 1024) << "." << ((freeMiB % 1024) * 10) / 1024 << "/" << (totalMiB / 1024) << "." << ((totalMiB % 1024) * 10) / 1024 << "GiB"; } else { ss << freeMiB << "/" << totalMiB << "MiB"; } ss >> df; } else { WARNING("statvfs failed with error '%s'", strerror(errno)); } return df; } const string get_date_time() { #if !defined(TARGET_LINUX) system("hwclock --hctosys &"); #endif char buf[80]; time_t now = time(0); struct tm tstruct = *localtime(&now); strftime(buf, sizeof(buf), "%F %R", &tstruct); return buf; } void sync_date_time(time_t t) { #if !defined(TARGET_LINUX) struct timeval tv = { t, 0 }; settimeofday(&tv, NULL); system("hwclock --systohc &"); #endif } /* void init_date_time() { time_t now = time(0); const uint32_t t = 0; if (now < t) { sync_date_time(t); } } void build_date_time() { const uint32_t t = 0; sync_date_time(t); } */ void set_date_time(const char* timestamp) { int imonth, iday, iyear, ihour, iminute; sscanf(timestamp, "%d-%d-%d %d:%d", &iyear, &imonth, &iday, &ihour, &iminute); struct tm datetime = { 0 }; datetime.tm_year = iyear - 1900; datetime.tm_mon = imonth - 1; datetime.tm_mday = iday; datetime.tm_hour = ihour; datetime.tm_min = iminute; datetime.tm_sec = 0; if (datetime.tm_year < 0) datetime.tm_year = 0; time_t t = mktime(&datetime); sync_date_time(t); } // char *ms2hms(uint32_t t, bool mm = true, bool ss = true) { // static char buf[10]; // t = t / 1000; // int s = (t % 60); // int m = (t % 3600) / 60; // int h = (t % 86400) / 3600; // // int d = (t % (86400 * 30)) / 86400; // if (!ss) sprintf(buf, "%02d:%02d", h, m); // else if (!mm) sprintf(buf, "%02d", h); // else sprintf(buf, "%02d:%02d:%02d", h, m, s); // return buf; // };
10,678
C++
.cpp
372
26.38172
91
0.595268
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,084
menusettingint.cpp
MiyooCFW_gmenu2x/src/menusettingint.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "menusettingint.h" #include "gmenu2x.h" #include "utilities.h" #include <sstream> using std::string; using std::stringstream; using fastdelegate::MakeDelegate; MenuSettingInt::MenuSettingInt(GMenu2X *gmenu2x, const string &title, const string &description, int *value, int def, int min, int max, int delta): MenuSetting(gmenu2x, title, description), _value(value), def(def), min(min), max(max), delta(delta), off(false) { originalValue = *value; setValue(evalIntConf(value, def, min, max), 0); //Delegates // ButtonAction actionInc = MakeDelegate(this, &MenuSettingInt::inc); // ButtonAction actionDec = MakeDelegate(this, &MenuSettingInt::dec); btn = new IconButton(gmenu2x, "select", gmenu2x->tr["Reset"]); // btn->setAction(MakeDelegate(this, &MenuSettingInt::setDefault)); buttonBox.add(btn); btn = new IconButton(gmenu2x, "dpad", gmenu2x->tr["Change"]); // btn->setAction(actionInc); buttonBox.add(btn); } void MenuSettingInt::draw(int y) { MenuSetting::draw(y); int w = 0; if (off && *_value <= offValue) { strvalue = "OFF"; w = gmenu2x->font->getHeight() / 2.5; RGBAColor color = (RGBAColor){255, 0, 0, 255}; gmenu2x->s->box(180, y + 1, w, gmenu2x->font->getHeight() - 2, color); gmenu2x->s->rectangle(180, y + 1, w, gmenu2x->font->getHeight() - 2, 0, 0, 0, 255); w += 2; } gmenu2x->s->write(gmenu2x->font, strvalue, 180 + w, y+gmenu2x->font->getHeight() / 2, VAlignMiddle); } uint32_t MenuSettingInt::manageInput() { if (gmenu2x->input[LEFT] || gmenu2x->input.hatEvent(DLEFT) == DLEFT) dec(); else if (gmenu2x->input[RIGHT] || gmenu2x->input.hatEvent(DRIGHT) == DRIGHT) inc(); else if (gmenu2x->input[DEC]) setValue(value() - 10 * delta, 1); else if (gmenu2x->input[INC]) setValue(value() + 10 * delta, 1); else if (gmenu2x->input[MENU]) setDefault(); else if (gmenu2x->input[MODIFIER] && !gmenu2x->input[MANUAL]) current(); return 0; // SD_NO_ACTION } void MenuSettingInt::inc() { setValue(value() + delta, 1); } void MenuSettingInt::dec() { setValue(value() - delta, 1); } void MenuSettingInt::current() { setValue(*_value, 1); } void MenuSettingInt::setValue(int value, bool readValue) { if (off && *_value < value && value <= offValue) *_value = offValue + 1; else if (off && *_value > value && value <= offValue) *_value = min; else { *_value = constrain(value,min,max); if (off && *_value <= offValue) *_value = min; } stringstream ss; ss << *_value; strvalue = ""; ss >> strvalue; if (readValue) gmenu2x->allyTTS(strvalue.c_str(), SLOW_GAP_TTS, SLOW_SPEED_TTS, 0); } void MenuSettingInt::setDefault() { setValue(def, 1); } int MenuSettingInt::value() { return *_value; } bool MenuSettingInt::edited() { return originalValue != value(); } MenuSettingInt *MenuSettingInt::setOff(int value) { off = true; offValue = constrain(value,min,max); return this; }
4,270
C++
.cpp
101
40.267327
147
0.605929
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,085
gmenu2x.cpp
MiyooCFW_gmenu2x/src/gmenu2x.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include <iostream> #include <sstream> #include <fstream> #include <algorithm> #include <stdlib.h> #include <signal.h> #include <sys/ioctl.h> #include <linux/vt.h> #include <linux/kd.h> #include <linux/fb.h> #include "linkapp.h" #include "fonthelper.h" #include "surface.h" #include "browsedialog.h" #include "powermanager.h" #include "gmenu2x.h" #include "filelister.h" #include "iconbutton.h" #include "messagebox.h" #include "inputdialog.h" #include "settingsdialog.h" #include "wallpaperdialog.h" #include "textdialog.h" #include "terminaldialog.h" #include "menusettingint.h" #include "menusettingbool.h" #include "menusettingrgba.h" #include "menusettingmultiint.h" #include "menusettingstring.h" #include "menusettingmultistring.h" #include "menusettingfile.h" #include "menusettingimage.h" #include "menusettingdir.h" #include "imageviewerdialog.h" #include "menusettingdatetime.h" #include "debug.h" #if defined(OPK_SUPPORT) #include "opkscannerdialog.h" #include <libopk.h> #endif using std::ifstream; using std::ofstream; using std::stringstream; using namespace fastdelegate; #define sync() sync(); system("sync &"); enum vol_mode_t { VOLUME_MODE_MUTE, VOLUME_MODE_PHONES, VOLUME_MODE_NORMAL }; string fwType = ""; uint16_t mmcPrev, mmcStatus; uint16_t udcPrev = UDC_REMOVE, udcStatus; uint16_t tvOutPrev = TV_REMOVE, tvOutStatus; uint16_t volumeModePrev, volumeMode; uint16_t batteryIcon = 3; uint8_t numJoyPrev, numJoy; // number of connected joysticks int CPU_MENU = 0; int CPU_LINK = 0; int CPU_MAX = 0; int CPU_EDGE = 0; int CPU_MIN = 0; int CPU_STEP = 0; int LAYOUT_VERSION = 0; int LAYOUT_VERSION_MAX = 0; int TEFIX = -1; int TEFIX_MAX = -1; const char *CARD_ROOT = getenv("HOME"); int SLOW_GAP_TTS = 5; int SLOW_SPEED_TTS = 140; int MEDIUM_GAP_TTS = 3; int MEDIUM_SPEED_TTS = 150; int FAST_GAP_TTS = 0; //default for espeak int FAST_SPEED_TTS = 175; //default for espeak string VOICE_TTS = "en"; //default for espeak #if defined(TARGET_RETROFW) #include "platform/retrofw.h" #elif defined(TARGET_RG350) #include "platform/rg350.h" #elif defined(TARGET_MIYOO) #include "platform/miyoo.h" #elif defined(TARGET_GP2X) || defined(TARGET_WIZ) || defined(TARGET_CAANOO) #include "platform/gp2x.h" #else //if defined(TARGET_LINUX) #include "platform/linux.h" #endif #ifndef DEFAULT_CPU #define DEFAULT_CPU 0 #endif #ifndef DEFAULT_LAYOUT #define DEFAULT_LAYOUT 0 #endif #ifndef DEFAULT_TEFIX #define DEFAULT_TEFIX -1 #endif #ifndef TTS_ENGINE #define TTS_ENGINE ":" #endif #include "menu.h" // Note: Keep this in sync with the enum! static const char *colorNames[NUM_COLORS] = { "topBarBg", "listBg", "bottomBarBg", "selectionBg", "previewBg", "messageBoxBg", "messageBoxBorder", "messageBoxSelection", "font", "fontOutline", "fontAlt", "fontAltOutline" }; static enum color stringToColor(const string &name) { for (uint32_t i = 0; i < NUM_COLORS; i++) { if (strcmp(colorNames[i], name.c_str()) == 0) { return (enum color)i; } } return (enum color)-1; } static const char *colorToString(enum color c) { return colorNames[c]; } GMenu2X *GMenu2X::instance = NULL; static void quit_all(int err) { delete GMenu2X::instance; exit(err); } int main(int argc, char * argv[]) { INFO("Starting GMenu2X..."); signal(SIGINT, &quit_all); signal(SIGSEGV, &quit_all); signal(SIGTERM, &quit_all); bool autoStart = false; for (int i = 0; i < argc; i++) { if (strcmp(argv[i],"--autostart")==0) { INFO("Launching Autostart"); autoStart = true; } } int fd = open("/dev/tty0", O_RDONLY); if (fd > 0) { ioctl(fd, VT_UNLOCKSWITCH, 1); ioctl(fd, KDSETMODE, KD_TEXT); ioctl(fd, KDSKBMODE, K_XLATE); close(fd); } usleep(1000); GMenu2X::instance = new GMenu2X_platform(); GMenu2X::instance->main(autoStart); return 0; } GMenu2X::~GMenu2X() { get_date_time(); // update sw clock confStr["datetime"] = get_date_time(); writeConfig(); quit(); delete menu; delete s; delete font; delete titlefont; } void GMenu2X::allyTTS(const char* text) { if (!confInt["enableTTS"]) return; char tmp_chr[256]; const char* voice; voice = VOICE_TTS.c_str(); system("killall " TTS_ENGINE " >/dev/null 2>&1"); snprintf(tmp_chr, sizeof(tmp_chr), TTS_ENGINE " \'%s\' -v%s &", text, voice); system(tmp_chr); } void GMenu2X::allyTTS(const char* file, int gap, int speed) { if (!confInt["enableTTS"]) return; char tmp_chr[256]; const char* voice; voice = VOICE_TTS.c_str(); system("killall " TTS_ENGINE " >/dev/null 2>&1"); snprintf(tmp_chr, sizeof(tmp_chr), TTS_ENGINE " -f%s -g%i -s%i -v%s &", file, gap, speed, voice); system(tmp_chr); } void GMenu2X::allyTTS(const char* text, int gap, int speed, bool wait) { if (!confInt["enableTTS"]) return; char tmp_chr[256]; const char* voice; //static char rm_tmp_chr[256]; //if (strcmp(text, rm_tmp_chr) == 0) return; //snprintf(rm_tmp_chr, sizeof(rm_tmp_chr), "%s", text); voice = VOICE_TTS.c_str(); //freopen("/dev/null", "w", stdout); // nulify stdout if (confInt["enableTTS"]) system("killall " TTS_ENGINE " >/dev/null 2>&1"); snprintf(tmp_chr, sizeof(tmp_chr), TTS_ENGINE " \"%s\" -g%i -s%i -v%s &", text, gap, speed, voice); system(tmp_chr); if (wait) while (system("pgrep " TTS_ENGINE " >/dev/null 2>&1") == 0) { usleep(100000); input.update(false); if (input[SETTINGS]) system("killall " TTS_ENGINE " >/dev/null 2>&1"); } //fflush(stdout); //freopen("/dev/tty", "w", stdout); // activate stdout } void GMenu2X::quit() { s->flip(); s->flip(); s->flip(); // flush buffers powerManager->clearTimer(); get_date_time(); // update sw clock confStr["datetime"] = get_date_time(); //#if defined(HW_LIDVOL) // setBacklight(getBacklight()); // setVolume(getVolume()); //#endif writeConfig(); if (confInt["enableTTS"]) system("killall " TTS_ENGINE); s->free(); font->free(); titlefont->free(); fflush(NULL); SDL_Quit(); hwDeinit(); } void GMenu2X::quit_nosave() { s->flip(); s->flip(); s->flip(); // flush buffers powerManager->clearTimer(); s->free(); font->free(); titlefont->free(); fflush(NULL); SDL_Quit(); hwDeinit(); } void GMenu2X::main(bool autoStart) { hwInit(); chdir(exe_path().c_str()); readConfig(); setScaleMode(0); #if defined(HW_LIDVOL) if (setBacklight(getBacklight()) == 0) setBacklight(50); setVolume(getVolume()); #else if (setBacklight(confInt["backlight"]) == 0) setBacklight(50); setVolume(confInt["globalVolume"]); #endif setKbdLayout(confInt["keyboardLayoutMenu"]); setTefix(confInt["tefixMenu"]); setenv("SDL_FBCON_DONT_CLEAR", "1", 0); setenv("SDL_NOMOUSE", "1", 1); string prevDateTime = confStr["datetime"]; string freshDateTime = get_date_time(); if (prevDateTime > freshDateTime) { set_date_time(prevDateTime.c_str()); } if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_JOYSTICK) < 0) { ERROR("Could not initialize SDL: %s", SDL_GetError()); quit(); return; } SDL_ShowCursor(SDL_DISABLE); input.init(exe_path() + "/input.conf"); setInputSpeed(); SDL_Surface *screen = SDL_SetVideoMode(this->w, this->h, this->bpp, SDL_HWSURFACE | #ifdef SDL_TRIPLEBUF SDL_TRIPLEBUF #else SDL_DOUBLEBUF #endif ); s = new Surface(); s->enableVirtualDoubleBuffer(screen); setSkin(confStr["skin"], true); powerManager = new PowerManager(this, confInt["backlightTimeout"], confInt["powerTimeout"]); // overclock CPU only after first surface has been draw (hopefully won't interfere fb0 init execution) setCPU(confInt["cpuMenu"]); srand(time(0)); // Seed the rand with current time to get different number sequences int randomInt = rand() % 10; // Generate a random val={0..x} to print "Hint" msg occasionally // Hint messages //while (true) { if (confInt["showHints"] == 1) { if (confInt["enableTTS"] == 1 && (confStr["lastCommand"] == "" || confStr["lastDirectory"] == "")) { switch (randomInt) { case 0: case 1: case 2: { string readHint = tr["Hint: To read a selected value or Link's description press X"]; allyTTS(readHint.c_str(), FAST_GAP_TTS, FAST_SPEED_TTS, 1); break; } case 3: case 4: case 5: { string readHint = tr["Hint: You can skip reading a message, by pressing START"]; allyTTS(readHint.c_str(), FAST_GAP_TTS, FAST_SPEED_TTS, 1); break; } default: { allyTTS(tr["Loading"].c_str(), FAST_GAP_TTS, FAST_SPEED_TTS, 1); break; } } } else if (confStr["lastCommand"] == "" || confStr["lastDirectory"] == "") { switch (randomInt) { case 0: { MessageBox mb(this, tr["Loading."]+"\n"+tr["Hint: Press 'Y' now quickly\nto reset gmenu2x.cfg"]); mb.setAutoHide(1000); mb.setBgAlpha(0); mb.exec(); break; } case 1: { MessageBox mb(this, tr["Loading."]+"\n"+tr["Hint: Hold 'X' to change Date & Time"]); mb.setAutoHide(1000); mb.setBgAlpha(0); mb.exec(); break; } case 2: { MessageBox mb(this, tr["Loading."]+"\n"+tr["Hint: Hold 'SELECT' to disable TV-output"]); mb.setAutoHide(1000); mb.setBgAlpha(0); mb.exec(); break; } case 3: { MessageBox mb(this, tr["Loading."]+"\n"+tr["Hint: Hold 'START' to enter Suspend Mode"]); mb.setAutoHide(1000); mb.setBgAlpha(0); mb.exec(); break; } case 4: { MessageBox mb(this, tr["Loading."]+"\n"+tr["Hint: You can AutoStart any game/app!?\nSee settings"]); mb.setAutoHide(1000); mb.setBgAlpha(0); mb.exec(); break; } case 5: { MessageBox mb(this, tr["Loading."]+"\n"+tr["Hint: Hold 'Y' to restart GMenu2X"]); mb.setAutoHide(1000); mb.setBgAlpha(0); mb.exec(); break; } default: { MessageBox mb(this, tr["Loading"]); mb.setAutoHide(1); mb.setBgAlpha(0); mb.exec(); break; } } } else if (!confInt["dialogAutoStart"]) { switch (randomInt) { case 0: case 1: case 2: { MessageBox mb(this, tr["Loading."]+"\n"+tr["Hint: Press 'Y' now quickly\nto disable AutoStart"]); mb.setAutoHide(1000); mb.setBgAlpha(0); mb.exec(); break; } default: { MessageBox mb(this, tr["Loading"]); mb.setAutoHide(1); mb.setBgAlpha(0); mb.exec(); break; } } } else { MessageBox mb(this, tr["Loading"]); mb.setAutoHide(1); mb.setBgAlpha(0); mb.exec(); } } else { MessageBox mb(this, tr["Loading"]); mb.setAutoHide(1); mb.setBgAlpha(0); mb.exec(); } //SDL_Delay(1000);reinit();} input.update(false); if (confStr["lastCommand"] == "" || confStr["lastDirectory"] == "" || confInt["dialogAutoStart"]) { if (input[MANUAL]) { // Reset GMenu2X settings string tmppath = exe_path() + "/gmenu2x.conf"; unlink(tmppath.c_str()); reinit(); } } else { if (input[MANUAL]) { // Reset settings for viewAutoStart() confInt["saveAutoStart"] = 0; confInt["dialogAutoStart"] = 0; confStr["lastDirectory"] = ""; confStr["lastCommand"] = ""; reinit_save(); } } string readMenu = tr["Welcome to GMenu"]; allyTTS(readMenu.c_str(), MEDIUM_GAP_TTS, MEDIUM_SPEED_TTS, 0); menu = new Menu(this); initMenu(); tvOutStatus = getTVOutStatus(); mmcPrev = mmcStatus = getMMCStatus(); udcStatus = getUDCStatus(); numJoyPrev = numJoy = getDevStatus(); volumeModePrev = volumeMode = getVolumeMode(confInt["globalVolume"]); if (confInt["dialogAutoStart"] && confStr["lastCommand"] != "" && confStr["lastDirectory"] != "") { viewAutoStart(); } if (confStr["lastCommand"] != "" && confStr["lastDirectory"] != "") { INFO("Starting autostart()"); INFO("conf %s %s",confStr["lastDirectory"].c_str(),confStr["lastCommand"].c_str()); INFO("autostart %s %s",confStr["lastDirectory"],confStr["lastCommand"]); setCPU(confInt["lastCPU"]); setKbdLayout(confInt["lastKeyboardLayout"]); setTefix(confInt["lastTefix"]); chdir(confStr["lastDirectory"].c_str()); quit(); string prevCmd = confStr["lastCommand"].c_str(); string writeDateCmd = "; sed -i \"/datetime=/c\\datetime=\\\"$(date +\\%\\F\\ %H:%M)\\\"\" "; string tmppath = exe_path() + "/gmenu2x.conf"; #if defined(TARGET_LINUX) string exitCmd = "; exit" ; #else string exitCmd = "; sync; mount -o remount,ro $HOME; poweroff"; #endif string launchCmd = prevCmd + writeDateCmd + tmppath + exitCmd; execlp("/bin/sh", "/bin/sh", "-c", launchCmd.c_str(), NULL); } currBackdrop = confStr["wallpaper"]; confStr["wallpaper"] = setBackground(s, currBackdrop); bg = new Surface(s); if (readTmp() && confInt["outputLogs"]) { viewLog(); } input.dropEvents(); SDL_TimerID hwCheckTimer = SDL_AddTimer(1000, hwCheck, NULL); powerManager->resetSuspendTimer(); // recover last session if (lastSelectorElement >= 0 && menu->selLinkApp() != NULL && (!menu->selLinkApp()->getSelectorDir().empty() || !lastSelectorDir.empty())) { if (confInt["skinBackdrops"] & BD_DIALOG) setBackground(bg, currBackdrop); else setBackground(bg, confStr["wallpaper"]); menu->selLinkApp()->selector(lastSelectorElement, lastSelectorDir); } menu->exec(); } bool GMenu2X::inputCommonActions(bool &inputAction) { if (powerManager->suspendActive) { // SUSPEND ACTIVE while (!(input[POWER] || input[SETTINGS] || input[UDC_CONNECT] || input[UDC_REMOVE] || input[MMC_INSERT] || input[MMC_REMOVE])) { input.update(); } powerManager->doSuspend(0); input[WAKE_UP] = true; if (!(input[UDC_REMOVE] || input[UDC_CONNECT] || input[MMC_INSERT] || input[MMC_REMOVE])) { return true; } } if (inputAction) powerManager->resetSuspendTimer(); uint32_t button_hold = SDL_GetTicks(); int wasActive = 0; while (input[MODIFIER]) { // MODIFIER HOLD wasActive = MODIFIER; input.update(); if (SDL_GetTicks() - button_hold > 1000) { #if defined(HW_LIDVOL) confInt["backlight"] = getBacklight(); confInt["globalVolume"] = getVolume(); #endif wasActive = 0; settings_date(); } else if (input[MANUAL] && skinFont == "skins/Default/font.ttf") { wasActive = 0; initFont(false); sc.setSkin(confStr["skin"]); } else if (input[MANUAL]) { wasActive = 0; initFont(true); sc.setSkin(confStr["skin"]); } else { continue; } break; } while (input[MANUAL]) { // MANUAL HOLD wasActive = MANUAL; input.update(); if (SDL_GetTicks() - button_hold > 1000) { wasActive = 0; reinit(); } } while (input[SETTINGS]) { // SETTINGS HOLD wasActive = SETTINGS; input.update(); if (confInt["enableTTS"]) system("killall " TTS_ENGINE); if (SDL_GetTicks() - button_hold > 1000 && !actionPerformed) { wasActive = 0; actionPerformed = true; powerManager->doSuspend(1); } } while (input[MENU]) { // MENU HOLD wasActive = MENU; input.update(); if (SDL_GetTicks() - button_hold > 1000) { wasActive = 0; setTVoff(); } else if (input[SETTINGS]) { wasActive = SCREENSHOT; } else if (input[BACKLIGHT_HOTKEY]) { wasActive = BACKLIGHT; } else if (input[VOLUME_HOTKEY]) { wasActive = VOLUP; } else if (input[POWER]) { wasActive = UDC_CONNECT; } else { continue; } break; } input[wasActive] = true; if (input[POWER]) { poweroffDialog(); } else if (input[SCREENSHOT]) { if (!saveScreenshot(confStr["homePath"])) { ERROR("Can't save screenshot"); return true; } MessageBox mb(this, tr["Screenshot saved"]); mb.setAutoHide(1000); mb.exec(); } else if (input[VOLUP] || input[VOLDOWN]) { setVolume(getVolume(), true); } else if (input[BACKLIGHT]) { setBacklight(getBacklight(), true); } else if (input[UDC_CONNECT]) { powerManager->setPowerTimeout(0); batteryIcon = 6; udcDialog(UDC_CONNECT); } else if (input[UDC_REMOVE]) { udcDialog(UDC_REMOVE); iconInet = NULL; batteryIcon = getBatteryStatus(getBatteryLevel(), confInt["minBattery"], confInt["maxBattery"]); powerManager->setPowerTimeout(confInt["powerTimeout"]); } else if (input[TV_CONNECT]) { tvOutDialog(); } else if (input[TV_REMOVE]) { tvOutDialog(TV_OFF); } else if (input[JOYSTICK_CONNECT]) { input.initJoysticks(true); // } else if (input[PHONES_CONNECT]) { // // tvOutDialog(TV_OFF); // WARNING("volume mode changed"); // return true; } else if (input[MMC_INSERT] || input[MMC_REMOVE]) { confInt["section"] = menu->selSectionIndex(); confInt["link"] = menu->selLinkIndex(); initMenu(); } else { return false; } return true; } void GMenu2X::cls(Surface *s, bool flip) { if (s == NULL) { s = this->s; } s->box((SDL_Rect){0, 0, s->width(), s->height()}, (RGBAColor){0, 0, 0, 255}); if (flip) { s->flip(); } } string GMenu2X::setBackground(Surface *bg, string wallpaper) { if (!sc.exists(wallpaper)) { // search and scale background if (wallpaper.empty() || sc[wallpaper] == NULL) { DEBUG("Searching wallpaper"); FileLister fl("skins/Default/wallpapers", false, true); fl.setFilter(".png,.jpg,.jpeg,.bmp"); fl.browse(); wallpaper = "skins/Default/wallpapers/" + fl.getFiles()[0]; } if (sc[wallpaper] == NULL) return ""; if (confStr["bgscale"] == "Stretch") sc[wallpaper]->softStretch(this->w, this->h, SScaleStretch); else if (confStr["bgscale"] == "Crop") sc[wallpaper]->softStretch(this->w, this->h, SScaleMax); else if (confStr["bgscale"] == "Aspect") sc[wallpaper]->softStretch(this->w, this->h, SScaleFit); } cls(bg, false); sc[wallpaper]->blit(bg, (this->w - sc[wallpaper]->width()) / 2, (this->h - sc[wallpaper]->height()) / 2); return wallpaper; } void GMenu2X::initFont(bool deffont) { if (deffont) skinFont = "skins/Default/font.ttf"; else skinFont = confStr["skinFont"] == "Default" ? "skins/Default/font.ttf" : sc.getSkinFilePath("font.ttf"); delete font; font = new FontHelper(skinFont, skinConfInt["fontSize"], skinConfColors[COLOR_FONT], skinConfColors[COLOR_FONT_OUTLINE]); if (!font->font) { delete font; font = new FontHelper("skins/Default/font.ttf", skinConfInt["fontSize"], skinConfColors[COLOR_FONT], skinConfColors[COLOR_FONT_OUTLINE]); } delete titlefont; titlefont = new FontHelper(skinFont, skinConfInt["fontSizeTitle"], skinConfColors[COLOR_FONT], skinConfColors[COLOR_FONT_OUTLINE]); if (!titlefont->font) { delete titlefont; titlefont = new FontHelper("skins/Default/font.ttf", skinConfInt["fontSizeTitle"], skinConfColors[COLOR_FONT], skinConfColors[COLOR_FONT_OUTLINE]); } } void GMenu2X::initMenu() { // Menu structure handler menu->initLayout(); menu->readSections(); menu->readLinks(); for (uint32_t i = 0; i < menu->getSections().size(); i++) { // Add virtual links in the applications section if (menu->getSections()[i] == "applications") { menu->addActionLink(i, tr["Explorer"], MakeDelegate(this, &GMenu2X::explorer), tr["Browse files and launch apps"], "explorer.png"); #if defined(HW_EXT_SD) menu->addActionLink(i, tr["Umount"], MakeDelegate(this, &GMenu2X::umountSdDialog), tr["Umount external media device"], "eject.png"); #endif } // Add virtual links in the setting section else if (menu->getSections()[i] == "settings") { menu->addActionLink(i, tr["Settings"], MakeDelegate(this, &GMenu2X::settings), tr["Configure system"], "configure.png"); menu->addActionLink(i, tr["Skin"], MakeDelegate(this, &GMenu2X::skinMenu), tr["Appearance & skin settings"], "skin.png"); #if defined(TARGET_GP2X) if (fwType == "open2x") { menu->addActionLink(i, "Open2x", MakeDelegate(this, &GMenu2X::settingsOpen2x), tr["Configure Open2x system settings"], "o2xconfigure.png"); } menu->addActionLink(i, "USB SD", MakeDelegate(this, &GMenu2X::activateSdUsb), tr["Activate USB on SD"], "usb.png"); if (fwType == "gph" && !f200) { menu->addActionLink(i, "USB Nand", MakeDelegate(this, &GMenu2X::activateNandUsb), tr["Activate USB on NAND"], "usb.png"); } #endif if (file_exists(exe_path() + "/log.txt")) { menu->addActionLink(i, tr["Log Viewer"], MakeDelegate(this, &GMenu2X::viewLog), tr["Displays last launched program's output"], "ebook.png"); } menu->addActionLink(i, tr["About"], MakeDelegate(this, &GMenu2X::about), tr["Info about GMenu2X"], "about.png"); menu->addActionLink(i, tr["Power"], MakeDelegate(this, &GMenu2X::poweroffDialog), tr["Power menu"], "exit.png"); menu->addActionLink(i, tr["CPU Settings"], MakeDelegate(this, &GMenu2X::cpuSettings), tr["Config CPU clock"], "cpu.png"); } } menu->setSectionIndex(confInt["section"]); menu->setLinkIndex(confInt["link"]); } void GMenu2X::settings_date() { powerManager->clearTimer(); // int prevgamma = confInt["gamma"]; vector<string> opFactory; opFactory.push_back(">>"); string tmp = ">>"; SettingsDialog sd(this, ts, tr["SW Clock"], "skin:icons/clock.png"); sd.allowCancel = true; string prevDateTime = confStr["datetime"] = get_date_time(); sd.addSetting(new MenuSettingDateTime(this, tr["Date & Time"], tr["Set system's software clock"], &confStr["datetime"])); if (sd.exec() && sd.edited() && sd.save) { writeConfig(); } string freshDateTime = confStr["datetime"]; if (prevDateTime != confStr["datetime"]) { set_date_time(freshDateTime.c_str()); powerManager->doSuspend(0); } } void GMenu2X::settings() { powerManager->clearTimer(); #if defined(HW_LIDVOL) confInt["backlight"] = getBacklight(); confInt["globalVolume"] = getVolume(); #endif // int prevgamma = confInt["gamma"]; FileLister fl_tr("translations"); fl_tr.browse(); fl_tr.insertFile("English"); string lang = tr.lang(); if (lang == "") lang = "English"; vector<string> opFactory; opFactory.push_back(">>"); string tmp = ">>"; SettingsDialog sd(this, ts, tr["Settings"], "skin:icons/configure.png"); sd.allowCancel = true; sd.addSetting(new MenuSettingMultiString(this, tr["Language"], tr["Set the language used by GMenu2X"], &lang, &fl_tr.getFiles())); string prevDateTime = confStr["datetime"] = get_date_time(); sd.addSetting(new MenuSettingDateTime(this, tr["Date & Time"], tr["Set system's date & time"], &confStr["datetime"])); sd.addSetting(new MenuSettingDir(this, tr["Home path"], tr["Set as home for launched links"], &confStr["homePath"])); #if defined(HW_UDC) vector<string> usbMode; usbMode.push_back("Ask"); usbMode.push_back("Storage"); usbMode.push_back("Charger"); sd.addSetting(new MenuSettingMultiString(this, tr["USB mode"], tr["Define default USB mode"], &confStr["usbMode"], &usbMode)); #endif #if defined(HW_TVOUT) vector<string> tvMode; tvMode.push_back("Ask"); tvMode.push_back("NTSC"); tvMode.push_back("PAL"); tvMode.push_back("OFF"); sd.addSetting(new MenuSettingMultiString(this, tr["TV mode"], tr["Define default TV mode"], &confStr["tvMode"], &tvMode)); #endif sd.addSetting((MenuSettingInt *)(new MenuSettingInt(this, tr["Suspend timeout"], tr["Seconds until suspend the device when inactive"], &confInt["backlightTimeout"], 30, 0, 300))->setOff(9)); sd.addSetting((MenuSettingInt *)(new MenuSettingInt(this, tr["Power timeout"], tr["Minutes to poweroff system if inactive"], &confInt["powerTimeout"], 10, 0, 60))->setOff(0)); sd.addSetting(new MenuSettingInt(this, tr["Backlight"], tr["Set LCD backlight"], &confInt["backlight"], 50, 10, 100, 10)); sd.addSetting(new MenuSettingInt(this, tr["Audio volume"], tr["Set the default audio volume"], &confInt["globalVolume"], 50, 0, 90, 10)); sd.addSetting(new MenuSettingInt(this, tr["Keyboard layout"], tr["Set the default A/B/X/Y layout"], &confInt["keyboardLayoutMenu"], DEFAULT_LAYOUT, 1, confInt["keyboardLayoutMax"])); sd.addSetting(new MenuSettingInt(this, tr["TEfix method"], tr["Set the default tearing FIX method"], &confInt["tefixMenu"], DEFAULT_TEFIX, 0, confInt["tefixMax"])); sd.addSetting(new MenuSettingBool(this, tr["Remember selection"], tr["Remember the last selected section, link and file"], &confInt["saveSelection"])); sd.addSetting(new MenuSettingBool(this, tr["Autostart"], tr["Run last app on restart"], &confInt["saveAutoStart"])); sd.addSetting(new MenuSettingBool(this, tr["Hints"], tr["Show \"Hint\" messages"], &confInt["showHints"])); sd.addSetting(new MenuSettingBool(this, tr["Output logs"], tr["Logs the link's output to read with Log Viewer"], &confInt["outputLogs"])); sd.addSetting(new MenuSettingBool(this, tr["Text To Speech"], tr["Use TTS engine to read menu out loud"], &confInt["enableTTS"])); sd.addSetting(new MenuSettingMultiString(this, tr["Reset settings"], tr["Choose settings to reset back to defaults"], &tmp, &opFactory, 0, MakeDelegate(this, &GMenu2X::resetSettings))); if (sd.exec() && sd.edited() && sd.save) { writeConfig(); if (lang == "English") lang = ""; if (confStr["lang"] != lang) { confStr["lang"] = lang; tr.setLang(lang); } } setBacklight(confInt["backlight"], false); setVolume(confInt["globalVolume"], false); #if defined(TARGET_GP2X) if (prevgamma != confInt["gamma"]) { setGamma(confInt["gamma"]); } #endif string freshDateTime = confStr["datetime"]; if (prevDateTime != confStr["datetime"]) { set_date_time(freshDateTime.c_str()); powerManager->doSuspend(0); } powerManager->setSuspendTimeout(confInt["backlightTimeout"]); powerManager->setPowerTimeout(confInt["powerTimeout"]); if (sd.exec() && sd.edited() && sd.save) { if (confInt["saveAutoStart"]) confInt["dialogAutoStart"] = 1; reinit_save(); } } void GMenu2X::resetSettings() { bool reset_gmenu = false, reset_skin = false, reset_icon = false, /* reset_homedir = false, */ reset_manual = false, reset_parameter = false, reset_backdrop = false, reset_filter = false, reset_directory = false, reset_boxart = false, reset_cpu = false; SettingsDialog sd(this, ts, tr["Reset settings"], "skin:icons/configure.png"); sd.allowCancel_link_nomb = true; sd.addSetting(new MenuSettingBool(this, tr["GMenu2X"], tr["Reset GMenu2X settings"], &reset_gmenu)); sd.addSetting(new MenuSettingBool(this, tr["Default skin"], tr["Reset Default skin settings back to default"], &reset_skin)); sd.addSetting(new MenuSettingBool(this, tr["Icons"], tr["Reset link's icon back to default"], &reset_icon)); sd.addSetting(new MenuSettingBool(this, tr["Manuals"], tr["Unset link's manual"], &reset_manual)); // sd.addSetting(new MenuSettingBool(this, tr["Home directory"], tr["Unset link's home directory"], &reset_homedir)); sd.addSetting(new MenuSettingBool(this, tr["Parameters"], tr["Unset link's additional parameters"], &reset_parameter)); sd.addSetting(new MenuSettingBool(this, tr["Backdrops"], tr["Unset link's backdrops"], &reset_backdrop)); sd.addSetting(new MenuSettingBool(this, tr["Filters"], tr["Unset link's selector file filters"], &reset_filter)); sd.addSetting(new MenuSettingBool(this, tr["Directories"], tr["Unset link's selector directory"], &reset_directory)); sd.addSetting(new MenuSettingBool(this, tr["Box art"], tr["Unset link's selector box art path"], &reset_boxart)); if (CPU_MAX != CPU_MIN) { sd.addSetting(new MenuSettingBool(this, tr["CPU speed"], tr["Reset link's custom CPU speed back to default"], &reset_cpu)); } if (sd.exec() && sd.edited() && sd.save) { MessageBox mb(this, tr["Changes will be applied\nto ALL apps and GMenu2X."] + "\n" + tr["Are you sure?"], "skin:icons/exit.png"); mb.setButton(CANCEL, tr["Cancel"]); mb.setButton(MANUAL, tr["Yes"]); if (mb.exec() != MANUAL) return; for (uint32_t s = 0; s < menu->getSections().size(); s++) { for (uint32_t l = 0; l < menu->sectionLinks(s)->size(); l++) { menu->setSectionIndex(s); menu->setLinkIndex(l); bool islink = menu->selLinkApp() != NULL; // WARNING("APP: %d %d %d %s", s, l, islink, menu->sectionLinks(s)->at(l)->getTitle().c_str()); if (!islink) continue; if (reset_cpu) menu->selLinkApp()->setCPU(); if (reset_icon) menu->selLinkApp()->setIcon(""); // if (reset_homedir) menu->selLinkApp()->setHomeDir(""); if (reset_manual) menu->selLinkApp()->setManual(""); if (reset_parameter) menu->selLinkApp()->setParams(""); if (reset_filter) menu->selLinkApp()->setSelectorFilter(""); if (reset_directory) menu->selLinkApp()->setSelectorDir(""); if (reset_boxart) menu->selLinkApp()->setSelectorScreens(""); if (reset_backdrop) menu->selLinkApp()->setBackdrop(""); if (reset_cpu || reset_icon || reset_manual || reset_parameter || reset_backdrop || reset_filter || reset_directory || reset_boxart ) menu->selLinkApp()->save(); } } if (reset_skin) { string tmppath = exe_path() + "/skins/Default/skin.conf"; unlink(tmppath.c_str()); } if (reset_gmenu) { string tmppath = exe_path() + "/gmenu2x.conf"; unlink(tmppath.c_str()); } reinit(); } } void GMenu2X::cpuSettings() { SettingsDialog sd(this, ts, tr["CPU setup"], "skin:icons/cpu.png"); sd.allowCancel = true; #if defined(MULTI_INT) sd.addSetting(new MenuSettingMultiInt(this, tr["Default CPU clock"], tr["Set the default working CPU frequency"], &confInt["cpuMenu"], oc_choices, oc_choices_size, CPU_MENU, CPU_MIN, CPU_MENU)); sd.addSetting(new MenuSettingMultiInt(this, tr["Maximum CPU clock"], tr["Maximum overclock for launching links"], &confInt["cpuMax"], oc_choices, oc_choices_size, CPU_MAX, CPU_EDGE, CPU_MAX)); sd.addSetting(new MenuSettingMultiInt(this, tr["Minimum CPU clock"], tr["Minimum underclock used in Suspend mode"], &confInt["cpuMin"], oc_choices, oc_choices_size, CPU_MIN, CPU_MIN, CPU_MAX)); sd.addSetting(new MenuSettingMultiInt(this, tr["Link CPU clock"], tr["Set LinkApp default CPU frequency"], &confInt["cpuLink"], oc_choices, oc_choices_size, CPU_MENU, CPU_MIN, CPU_MAX)); #else sd.addSetting(new MenuSettingInt(this, tr["Default CPU clock"], tr["Set the default working CPU frequency"], &confInt["cpuMenu"], 672, 480, 864, 48)); sd.addSetting(new MenuSettingInt(this, tr["Maximum CPU clock"], tr["Maximum overclock for launching links"], &confInt["cpuMax"], 864, 720, 1248, 48)); sd.addSetting(new MenuSettingInt(this, tr["Minimum CPU clock"], tr["Minimum underclock used in Suspend mode"], &confInt["cpuMin"], 192, 48, 720, 48)); sd.addSetting(new MenuSettingInt(this, tr["Link CPU clock"], tr["Set LinkApp default CPU frequency"], &confInt["cpuLink"], 720, 480, 1248, 48)); sd.addSetting(new MenuSettingInt(this, tr["Step for clock values"], tr["Set default step for CPU frequency"], &confInt["cpuStep"], 48, 48, 240, 48)); #endif if (sd.exec() && sd.edited() && sd.save) { setCPU(confInt["cpuMenu"]); writeConfig(); } } bool GMenu2X::readTmp() { lastSelectorElement = -1; ifstream tmp("/tmp/gmenu2x.tmp", ios_base::in); if (!tmp.is_open()) return false; string line; while (getline(tmp, line, '\n')) { string::size_type pos = line.find("="); string name = trim(line.substr(0, pos)); string value = trim(line.substr(pos + 1)); if (name == "section") menu->setSectionIndex(atoi(value.c_str())); else if (name == "link") menu->setLinkIndex(atoi(value.c_str())); else if (name == "selectorelem") lastSelectorElement = atoi(value.c_str()); else if (name == "selectordir") lastSelectorDir = value; // else if (name == "TVOut") TVOut = atoi(value.c_str()); else if (name == "tvOutPrev") tvOutPrev = atoi(value.c_str()); else if (name == "udcPrev") udcPrev = atoi(value.c_str()); else if (name == "currBackdrop") currBackdrop = value; else if (name == "explorerLastDir") confStr["explorerLastDir"] = value; } // if (TVOut > 2) TVOut = 0; tmp.close(); unlink("/tmp/gmenu2x.tmp"); return true; } void GMenu2X::writeTmp(int selelem, const string &selectordir) { ofstream tmp("/tmp/gmenu2x.tmp"); if (tmp.is_open()) { tmp << "section=" << menu->selSectionIndex() << endl; tmp << "link=" << menu->selLinkIndex() << endl; if (selelem >- 1) tmp << "selectorelem=" << selelem << endl; if (selectordir != "") tmp << "selectordir=" << selectordir << endl; tmp << "udcPrev=" << udcPrev << endl; tmp << "tvOutPrev=" << tvOutPrev << endl; // tmp << "TVOut=" << TVOut << endl; tmp << "currBackdrop=" << currBackdrop << endl; if (!confStr["explorerLastDir"].empty()) tmp << "explorerLastDir=" << confStr["explorerLastDir"] << endl; tmp.close(); } } void GMenu2X::readConfig() { #if defined (__BUILDTIME__) #define xstr(s) str(s) #define str(s) #s #endif string conf = exe_path() + "/gmenu2x.conf"; // Defaults *** Sync with default values in writeConfig confInt["saveSelection"] = 1; confInt["dialogAutoStart"] = 1; confInt["enableTTS"] = 0; confInt["showHints"] = 1; confStr["datetime"] = xstr(__BUILDTIME__); confInt["skinBackdrops"] = 1; confStr["homePath"] = CARD_ROOT; confInt["keyboardLayoutMenu"] = LAYOUT_VERSION; confInt["keyboardLayoutMax"] = LAYOUT_VERSION_MAX; confInt["tefixMenu"] = TEFIX; confInt["tefixMax"] = TEFIX_MAX; confStr["bgscale"] = "Crop"; confStr["skinFont"] = "Custom"; confInt["backlightTimeout"] = 30; confInt["powerTimeout"] = 0; #if !defined(HW_LIDVOL) confInt["backlight"] = 50; confInt["globalVolume"] = 50; #endif confInt["cpuMenu"] = CPU_MENU; confInt["cpuMax"] = CPU_MAX; confInt["cpuMin"] = CPU_MIN; confInt["cpuLink"] = CPU_LINK; confInt["cpuStep"] = CPU_STEP; // input.update(false); // if (!input[SETTINGS] && file_exists(conf)) { ifstream cfg(conf.c_str(), ios_base::in); if (cfg.is_open()) { string line; while (getline(cfg, line, '\n')) { string::size_type pos = line.find("="); string name = trim(line.substr(0, pos)); string value = trim(line.substr(pos + 1)); if (value.length() > 1 && value.at(0) == '"' && value.at(value.length() - 1) == '"') confStr[name] = value.substr(1, value.length() - 2); confInt[name] = atoi(value.c_str()); } cfg.close(); } if (!confStr["lang"].empty()) { tr.setLang(confStr["lang"]); string voiceTTS = tr["_TTS_voice_"]; INFO("voice is set to %s",voiceTTS.c_str()); if (voiceTTS != "_TTS_voice_" && !voiceTTS.empty()) VOICE_TTS = voiceTTS; } if (!confStr["wallpaper"].empty() && !file_exists(confStr["wallpaper"])) confStr["wallpaper"] = ""; if (confStr["skin"].empty() || !dir_exists("skins/" + confStr["skin"])) confStr["skin"] = "Default"; evalIntConf(&confInt["backlightTimeout"], 30, 0, 300); evalIntConf(&confInt["powerTimeout"], 10, 0, 60); evalIntConf(&confInt["outputLogs"], 0, 0, 1 ); // evalIntConf(&confInt["cpuMax"], 2000, 200, 2000 ); // evalIntConf(&confInt["cpuMin"], 342, 200, 1200 ); // evalIntConf(&confInt["cpuMenu"], 528, 200, 1200 ); evalIntConf(&confInt["globalVolume"], 60, 0, 100 ); evalIntConf(&confInt["backlight"], 70, 1, 100); evalIntConf(&confInt["minBattery"], 3550, 1, 10000); evalIntConf(&confInt["maxBattery"], 3720, 1, 10000); if (!confInt["saveSelection"]) { confInt["section"] = 0; confInt["link"] = 0; } } void GMenu2X::writeConfig() { if (confInt["saveSelection"] && menu != NULL) { confInt["section"] = menu->selSectionIndex(); confInt["link"] = menu->selLinkIndex(); } string conf = exe_path() + "/gmenu2x.conf"; ofstream cfg(conf.c_str()); if (cfg.is_open()) { for (ConfStrHash::iterator curr = confStr.begin(); curr != confStr.end(); curr++) { if ( // deprecated curr->first == "sectionBarPosition" || curr->first == "tvoutEncoding" || curr->first == "explorerLastDir" || curr->first == "defaultDir" || // defaults (curr->first == "cpuMenu" && curr->second.empty()) || (curr->first == "cpuMax" && curr->second.empty()) || (curr->first == "cpuMin" && curr->second.empty()) || (curr->first == "cpuLink" && curr->second.empty()) || (curr->first == "cpuStep" && curr->second.empty()) || (curr->first == "datetime" && curr->second.empty()) || (curr->first == "homePath" && curr->second == CARD_ROOT) || (curr->first == "skin" && curr->second == "Default") || (curr->first == "previewMode" && curr->second == "Miniature") || (curr->first == "skinFont" && curr->second == "Custom") || (curr->first == "usbMode" && curr->second == "Ask") || (curr->first == "tvMode" && curr->second == "Ask") || (curr->first == "lang" && curr->second.empty()) || (curr->first == "lang" && curr->second.empty()) || (curr->first == "bgscale" && curr->second.empty()) || (curr->first == "bgscale" && curr->second == "Crop") || curr->first.empty() || curr->second.empty() ) continue; cfg << curr->first << "=\"" << curr->second << "\"" << endl; } for (ConfIntHash::iterator curr = confInt.begin(); curr != confInt.end(); curr++) { if ( // deprecated curr->first == "batteryLog" || curr->first == "maxClock" || curr->first == "minClock" || curr->first == "menuClock" || curr->first == "TVOut" || // moved to skin conf curr->first == "linkCols" || curr->first == "linkRows" || curr->first == "sectionBar" || curr->first == "searchBackdrops" || curr->first == "sectionBackdrops" || curr->first == "sectionLabel" || curr->first == "linkLabel" || curr->first == "showLinkIcon" || // defaults (curr->first == "skinBackdrops" && curr->second == 1) || (curr->first == "backlightTimeout" && curr->second == 30) || (curr->first == "powerTimeout" && curr->second == 10) || (curr->first == "outputLogs" && curr->second == 0) || // (curr->first == "cpuMin" && curr->second == 342) || // (curr->first == "cpuMax" && curr->second == 740) || // (curr->first == "cpuMenu" && curr->second == 528) || (curr->first == "minBattery" && curr->second == 3550) || (curr->first == "maxBattery" && curr->second == 3720) || (curr->first == "saveSelection" && curr->second == 1) || (curr->first == "section" && curr->second == 0) || (curr->first == "link" && curr->second == 0) || curr->first.empty() ) continue; cfg << curr->first << "=" << curr->second << endl; } cfg.close(); } sync(); } void GMenu2X::writeSkinConfig() { string skinconf = exe_path() + "/skins/" + confStr["skin"] + "/skin.conf"; ofstream inf(skinconf.c_str()); if (!inf.is_open()) return; for (ConfStrHash::iterator curr = skinConfStr.begin(); curr != skinConfStr.end(); curr++) { if (curr->first.empty() || curr->second.empty()) { continue; } inf << curr->first << "=\"" << curr->second << "\"" << endl; } for (ConfIntHash::iterator curr = skinConfInt.begin(); curr != skinConfInt.end(); curr++) { if ( curr->first == "titleFontSize" || curr->first == "sectionBarHeight" || curr->first == "linkHeight" || curr->first == "selectorPreviewX" || curr->first == "selectorPreviewY" || curr->first == "selectorPreviewWidth" || curr->first == "selectorPreviewHeight" || curr->first == "selectorX" || curr->first == "linkItemHeight" || curr->first == "topBarHeight" || (curr->first == "previewWidth" && curr->second == 128) || (curr->first == "linkCols" && curr->second == 4) || (curr->first == "linkRows" && curr->second == 4) || (curr->first == "sectionBar" && curr->second == SB_CLASSIC) || (curr->first == "sectionLabel" && curr->second == 1) || (curr->first == "searchBackdrops" && curr->second == SBAK_OFF) || (curr->first == "sectionBackdrops" && curr->second == 0) || (curr->first == "linkLabel" && curr->second == 1) || (curr->first == "showLinkIcon" && curr->second == 1) || (curr->first == "showDialogIcon" && curr->second == 1) || curr->first.empty() ) { continue; } inf << curr->first << "=" << curr->second << endl; } for (int i = 0; i < NUM_COLORS; ++i) { inf << colorToString((enum color)i) << "=" << rgbatostr(skinConfColors[i]) << endl; } inf.close(); sync(); } void GMenu2X::setSkin(string skin, bool clearSC) { input.update(false); if (input[SETTINGS]) skin = "Default"; confStr["skin"] = skin; // Clear previous skin settings skinConfStr.clear(); skinConfInt.clear(); // Defaults *** Sync with default values in writeConfig skinConfInt["sectionBar"] = SB_CLASSIC; skinConfInt["sectionLabel"] = 1; skinConfInt["searchBackdrops"] = SBAK_OFF; skinConfInt["sectionBackdrops"] = 0; skinConfInt["linkLabel"] = 1; skinConfInt["showLinkIcon"] = 1; skinConfInt["showDialogIcon"] = 1; // clear collection and change the skin path if (clearSC) { sc.clear(); } sc.setSkin(skin); // reset colors to the default values skinConfColors[COLOR_TOP_BAR_BG] = (RGBAColor){255,255,255,130}; skinConfColors[COLOR_LIST_BG] = (RGBAColor){255,255,255,0}; skinConfColors[COLOR_BOTTOM_BAR_BG] = (RGBAColor){255,255,255,130}; skinConfColors[COLOR_SELECTION_BG] = (RGBAColor){255,255,255,130}; skinConfColors[COLOR_PREVIEW_BG] = (RGBAColor){253,1,252,0};; skinConfColors[COLOR_MESSAGE_BOX_BG] = (RGBAColor){255,255,255,255}; skinConfColors[COLOR_MESSAGE_BOX_BORDER] = (RGBAColor){80,80,80,255}; skinConfColors[COLOR_MESSAGE_BOX_SELECTION] = (RGBAColor){160,160,160,255}; skinConfColors[COLOR_FONT] = (RGBAColor){255,255,255,255}; skinConfColors[COLOR_FONT_OUTLINE] = (RGBAColor){0,0,0,200}; skinConfColors[COLOR_FONT_ALT] = (RGBAColor){253,1,252,0}; skinConfColors[COLOR_FONT_ALT_OUTLINE] = (RGBAColor){253,1,252,0}; // load skin settings skin = "skins/" + skin + "/skin.conf"; ifstream skinconf(skin.c_str(), ios_base::in); if (skinconf.is_open()) { string line; while (getline(skinconf, line, '\n')) { line = trim(line); // DEBUG("skinconf: '%s'", line.c_str()); string::size_type pos = line.find("="); string name = trim(line.substr(0, pos)); string value = trim(line.substr(pos + 1)); if (value.length() > 0) { if (value.length() > 1 && value.at(0) == '"' && value.at(value.length() - 1) == '"') { skinConfStr[name] = value.substr(1, value.length() - 2); } else if (value.at(0) == '#') { // skinConfColor[name] = strtorgba(value.substr(1,value.length()) ); skinConfColors[stringToColor(name)] = strtorgba(value); } else if (name.length() > 6 && name.substr(name.length() - 6, 5) == "Color") { value += name.substr(name.length() - 1); name = name.substr(0, name.length() - 6); if (name == "selection" || name == "topBar" || name == "bottomBar" || name == "messageBox") name += "Bg"; if (value.substr(value.length() - 1) == "R") skinConfColors[stringToColor(name)].r = atoi(value.c_str()); if (value.substr(value.length() - 1) == "G") skinConfColors[stringToColor(name)].g = atoi(value.c_str()); if (value.substr(value.length() - 1) == "B") skinConfColors[stringToColor(name)].b = atoi(value.c_str()); if (value.substr(value.length() - 1) == "A") skinConfColors[stringToColor(name)].a = atoi(value.c_str()); } else { skinConfInt[name] = atoi(value.c_str()); } } } skinconf.close(); } // (poor) HACK: ensure some colors have a default value if (skinConfColors[COLOR_FONT_ALT].r == 253 && skinConfColors[COLOR_FONT_ALT].g == 1 && skinConfColors[COLOR_FONT_ALT].b == 252 && skinConfColors[COLOR_FONT_ALT].a == 0) { skinConfColors[COLOR_FONT_ALT] = skinConfColors[COLOR_FONT]; } if (skinConfColors[COLOR_FONT_ALT_OUTLINE].r == 253 && skinConfColors[COLOR_FONT_ALT_OUTLINE].g == 1 && skinConfColors[COLOR_FONT_ALT_OUTLINE].b == 252 && skinConfColors[COLOR_FONT_ALT_OUTLINE].a == 0) { skinConfColors[COLOR_FONT_ALT_OUTLINE] = skinConfColors[COLOR_FONT_OUTLINE]; } if (skinConfColors[COLOR_PREVIEW_BG].r == 253 && skinConfColors[COLOR_PREVIEW_BG].g == 1 && skinConfColors[COLOR_PREVIEW_BG].b == 252 && skinConfColors[COLOR_PREVIEW_BG].a == 0) { skinConfColors[COLOR_PREVIEW_BG] = skinConfColors[COLOR_TOP_BAR_BG]; skinConfColors[COLOR_PREVIEW_BG].a == 170; } // prevents breaking current skin until they are updated if (!skinConfInt["fontSizeTitle"] && skinConfInt["titleFontSize"] > 0) skinConfInt["fontSizeTitle"] = skinConfInt["titleFontSize"]; evalIntConf(&skinConfInt["sectionBarSize"], 40, 1, this->w); evalIntConf(&skinConfInt["bottomBarHeight"], 16, 1, this->h); evalIntConf(&skinConfInt["previewWidth"], 128, 1, this->w); evalIntConf(&skinConfInt["fontSize"], 14, 6, 60); evalIntConf(&skinConfInt["fontSizeTitle"], 20, 1, 60); evalIntConf(&skinConfInt["sectionBar"], SB_CLASSIC, 0, 5); evalIntConf(&skinConfInt["linkCols"], 4, 1, 8); evalIntConf(&skinConfInt["linkRows"], 4, 1, 8); initFont(false); } void GMenu2X::skinMenu() { bool save = false; int selected = 0; string initSkin = confStr["skin"]; string prevSkin = "/"; FileLister fl_sk("skins", true, false); fl_sk.addExclude(".."); fl_sk.browse(); vector<string> wpLabel; wpLabel.push_back(">>"); string tmp = ">>"; vector<string> sbStr; sbStr.push_back("OFF"); sbStr.push_back("Left"); sbStr.push_back("Bottom"); sbStr.push_back("Right"); sbStr.push_back("Top"); sbStr.push_back("Classic"); int sbPrev = skinConfInt["sectionBar"]; string sectionBar = sbStr[skinConfInt["sectionBar"]]; int linkColsPrev = skinConfInt["linkCols"]; int linkRowsPrev = skinConfInt["linkRows"]; vector<string> bgScale; bgScale.push_back("Original"); bgScale.push_back("Crop"); bgScale.push_back("Aspect"); bgScale.push_back("Stretch"); string bgScalePrev = confStr["bgscale"]; vector<string> bdStr; bdStr.push_back("OFF"); bdStr.push_back("Menu only"); bdStr.push_back("Dialog only"); bdStr.push_back("Menu & Dialog"); int bdPrev = confInt["skinBackdrops"]; string skinBackdrops = bdStr[confInt["skinBackdrops"]]; vector<string> sbdStr; sbdStr.push_back("OFF"); sbdStr.push_back("Link name only"); sbdStr.push_back("Exec name/path only"); int sbdPrev = skinConfInt["searchBackdrops"]; string searchBackdrops = sbdStr[skinConfInt["searchBackdrops"]]; vector<string> skinFont; skinFont.push_back("Custom"); skinFont.push_back("Default"); string skinFontPrev = confStr["skinFont"]; vector<string> previewMode; previewMode.push_back("Miniature"); previewMode.push_back("Backdrop"); vector<string> wallpapers; string wpPath = confStr["wallpaper"]; confStr["tmp_wallpaper"] = ""; do { if (prevSkin != confStr["skin"] || skinFontPrev != confStr["skinFont"]) { prevSkin = confStr["skin"]; skinFontPrev = confStr["skinFont"]; setSkin(confStr["skin"], false); sectionBar = sbStr[skinConfInt["sectionBar"]]; searchBackdrops = sbdStr[skinConfInt["searchBackdrops"]]; confStr["tmp_wallpaper"] = (confStr["tmp_wallpaper"].empty() || skinConfStr["wallpaper"].empty()) ? base_name(confStr["wallpaper"]) : skinConfStr["wallpaper"]; wallpapers.clear(); FileLister fl_wp("skins/" + confStr["skin"] + "/wallpapers"); fl_wp.setFilter(".png,.jpg,.jpeg,.bmp"); fl_wp.browse(); wallpapers = fl_wp.getFiles(); if (confStr["skin"] != "Default") { fl_wp.setPath("skins/Default/wallpapers"); fl_wp.browse(); wallpapers.insert(wallpapers.end(), fl_wp.getFiles().begin(), fl_wp.getFiles().end()); } sc.del("skin:icons/skin.png"); sc.del("skin:imgs/buttons/left.png"); sc.del("skin:imgs/buttons/right.png"); sc.del("skin:imgs/buttons/a.png"); } wpPath = "skins/" + confStr["skin"] + "/wallpapers/" + confStr["tmp_wallpaper"]; if (!file_exists(wpPath)) wpPath = "skins/Default/wallpapers/" + confStr["tmp_wallpaper"]; if (!file_exists(wpPath)) wpPath = "skins/" + confStr["skin"] + "/wallpapers/" + wallpapers.at(0); if (!file_exists(wpPath)) wpPath = "skins/Default/wallpapers/" + wallpapers.at(0); setBackground(bg, wpPath); SettingsDialog sd(this, ts, tr["Skin"], "skin:icons/skin.png"); sd.selected = selected; sd.allowCancel_nomb = true; sd.addSetting(new MenuSettingMultiString(this, tr["Skin"], tr["Set the skin used by GMenu2X"], &confStr["skin"], &fl_sk.getDirectories(), MakeDelegate(this, &GMenu2X::onChangeSkin))); sd.addSetting(new MenuSettingMultiString(this, tr["Wallpaper"], tr["Select an image to use as a wallpaper"], &confStr["tmp_wallpaper"], &wallpapers, MakeDelegate(this, &GMenu2X::onChangeSkin), MakeDelegate(this, &GMenu2X::changeWallpaper))); sd.addSetting(new MenuSettingMultiString(this, tr["Background"], tr["How to scale wallpaper, backdrops and game art"], &confStr["bgscale"], &bgScale)); sd.addSetting(new MenuSettingMultiString(this, tr["Preview mode"], tr["How to show image preview and game art"], &confStr["previewMode"], &previewMode)); sd.addSetting(new MenuSettingMultiString(this, tr["Skin colors"], tr["Customize skin colors"], &tmp, &wpLabel, MakeDelegate(this, &GMenu2X::onChangeSkin), MakeDelegate(this, &GMenu2X::skinColors))); sd.addSetting(new MenuSettingMultiString(this, tr["Skin backdrops"], tr["Automatic load backdrops from skin pack"], &skinBackdrops, &bdStr)); sd.addSetting(new MenuSettingMultiString(this, tr["Search backdrops"], tr["Narrow backdrops searching"], &searchBackdrops, &sbdStr)); sd.addSetting(new MenuSettingMultiString(this, tr["Font face"], tr["Override the skin font face"], &confStr["skinFont"], &skinFont, MakeDelegate(this, &GMenu2X::onChangeSkin))); sd.addSetting(new MenuSettingInt(this, tr["Font size"], tr["Size of text font"], &skinConfInt["fontSize"], 12, 6, 60)); sd.addSetting(new MenuSettingInt(this, tr["Title font size"], tr["Size of title's text font"], &skinConfInt["fontSizeTitle"], 20, 1, 60)); sd.addSetting(new MenuSettingMultiString(this, tr["Section bar layout"], tr["Set the layout and position of the Section Bar"], &sectionBar, &sbStr)); sd.addSetting(new MenuSettingInt(this, tr["Section bar size"], tr["Size of section and top bar"], &skinConfInt["sectionBarSize"], 40, 1, this->w)); sd.addSetting(new MenuSettingBool(this, tr["Section backdrops"], tr["Load section backdrop from skin pack"], &skinConfInt["sectionBackdrops"])); sd.addSetting(new MenuSettingInt(this, tr["Bottom bar height"], tr["Height of bottom bar"], &skinConfInt["bottomBarHeight"], 16, 1, this->h)); sd.addSetting(new MenuSettingInt(this, tr["Menu columns"], tr["Number of columns of links in main menu"], &skinConfInt["linkCols"], 4, 1, 8)); sd.addSetting(new MenuSettingInt(this, tr["Menu rows"], tr["Number of rows of links in main menu"], &skinConfInt["linkRows"], 4, 1, 8)); sd.addSetting(new MenuSettingBool(this, tr["Show link icon"], tr["Show link icon in main menu"], &skinConfInt["showLinkIcon"])); sd.addSetting(new MenuSettingBool(this, tr["Link label"], tr["Show link labels in main menu"], &skinConfInt["linkLabel"])); sd.addSetting(new MenuSettingBool(this, tr["Section label"], tr["Show the active section label in main menu"], &skinConfInt["sectionLabel"])); sd.exec(); selected = sd.selected; save = sd.save; } while (!save); if (skinBackdrops == "OFF") confInt["skinBackdrops"] = BD_OFF; else if (skinBackdrops == "Menu & Dialog") confInt["skinBackdrops"] = BD_MENU | BD_DIALOG; else if (skinBackdrops == "Menu only") confInt["skinBackdrops"] = BD_MENU; else if (skinBackdrops == "Dialog only") confInt["skinBackdrops"] = BD_DIALOG; if (sectionBar == "OFF") skinConfInt["sectionBar"] = SB_OFF; else if (sectionBar == "Right") skinConfInt["sectionBar"] = SB_RIGHT; else if (sectionBar == "Top") skinConfInt["sectionBar"] = SB_TOP; else if (sectionBar == "Bottom") skinConfInt["sectionBar"] = SB_BOTTOM; else if (sectionBar == "Left") skinConfInt["sectionBar"] = SB_LEFT; else skinConfInt["sectionBar"] = SB_CLASSIC; if (searchBackdrops == "OFF") skinConfInt["searchBackdrops"] = SBAK_OFF; else if (searchBackdrops == "Link name only") skinConfInt["searchBackdrops"] = SBAK_LINK; else if (searchBackdrops == "Exec name/path only") skinConfInt["searchBackdrops"] = SBAK_EXEC; confStr["tmp_wallpaper"] = ""; confStr["wallpaper"] = wpPath; writeSkinConfig(); writeConfig(); if ( bdPrev != confInt["skinBackdrops"] || sbdPrev != skinConfInt["searchBackdrops"] || initSkin != confStr["skin"] || bgScalePrev != confStr["bgscale"] || linkColsPrev != skinConfInt["linkCols"] || linkRowsPrev != skinConfInt["linkRows"] || sbPrev != skinConfInt["sectionBar"] ) reinit(); } void GMenu2X::skinColors() { bool save = false; do { setSkin(confStr["skin"], false); SettingsDialog sd(this, ts, tr["Skin Colors"], "skin:icons/skin.png"); sd.allowCancel_nomb = true; sd.addSetting(new MenuSettingRGBA(this, tr["Top/Section Bar"], tr["Color of the top and section bar"], &skinConfColors[COLOR_TOP_BAR_BG])); sd.addSetting(new MenuSettingRGBA(this, tr["List Body"], tr["Color of the list body"], &skinConfColors[COLOR_LIST_BG])); sd.addSetting(new MenuSettingRGBA(this, tr["Bottom Bar"], tr["Color of the bottom bar"], &skinConfColors[COLOR_BOTTOM_BAR_BG])); sd.addSetting(new MenuSettingRGBA(this, tr["Selection"], tr["Color of the selection and other interface details"], &skinConfColors[COLOR_SELECTION_BG])); sd.addSetting(new MenuSettingRGBA(this, tr["Box Art"], tr["Color of the box art background"], &skinConfColors[COLOR_PREVIEW_BG])); sd.addSetting(new MenuSettingRGBA(this, tr["Message Box"], tr["Background color of the message box"], &skinConfColors[COLOR_MESSAGE_BOX_BG])); sd.addSetting(new MenuSettingRGBA(this, tr["Msg Box Border"], tr["Border color of the message box"], &skinConfColors[COLOR_MESSAGE_BOX_BORDER])); sd.addSetting(new MenuSettingRGBA(this, tr["Msg Box Selection"], tr["Color of the selection of the message box"], &skinConfColors[COLOR_MESSAGE_BOX_SELECTION])); sd.addSetting(new MenuSettingRGBA(this, tr["Font"], tr["Color of the font"], &skinConfColors[COLOR_FONT])); sd.addSetting(new MenuSettingRGBA(this, tr["Font Outline"], tr["Color of the font's outline"], &skinConfColors[COLOR_FONT_OUTLINE])); sd.addSetting(new MenuSettingRGBA(this, tr["Alt Font"], tr["Color of the alternative font"], &skinConfColors[COLOR_FONT_ALT])); sd.addSetting(new MenuSettingRGBA(this, tr["Alt Font Outline"], tr["Color of the alternative font outline"], &skinConfColors[COLOR_FONT_ALT_OUTLINE])); sd.exec(); save = sd.save; } while (!save); writeSkinConfig(); } void GMenu2X::about() { #if defined (__COMMIT_HASH__) || defined (__BUILDROOT_HASH__) || defined (__CFW_HASH__) #define xstr(s) str(s) #define str(s) #s #endif vector<string> text; // string temp = "", buf; // temp = tr["Build date: "] + __DATE__ + "\n"; // float battlevel = getBatteryStatus(); // { stringstream ss; ss.precision(2); ss << battlevel/1000; ss >> buf; } // temp += tr["Battery: "] + ((battlevel < 0 || battlevel > 10000) ? tr["Charging"] : buf + " V") + "\n"; // temp += tr["Uptime: "] + ms2hms(SDL_GetTicks()) + "\n"; // temp += "----\n"; #if defined (__COMMIT_HASH__) && defined (__BUILDROOT_HASH__) && defined (__CFW_HASH__) TextDialog td(this, "MiyooCFW build", tr[""] + "CFW-ver:" + xstr(__CFW_HASH__) + " BR2:" + xstr(__BUILDROOT_HASH__) + " GM2X:" xstr(__COMMIT_HASH__), "skin:icons/about.png"); #elif defined (__COMMIT_HASH__) && defined (__BUILDROOT_HASH__) TextDialog td(this, "GMenu2X BR2 package", tr["Build"] + ": " + __DATE__ + " BR2:" + xstr(__BUILDROOT_HASH__) + " GM2X:" xstr(__COMMIT_HASH__), "skin:icons/about.png"); #elif defined (__COMMIT_HASH__) TextDialog td(this, "GMenu2X upstream", tr["Build"] + ": " + __DATE__ + " " + __TIME__ + " with commit:" xstr(__COMMIT_HASH__), "skin:icons/about.png"); #else TextDialog td(this, "GMenu2X", tr["Build"] + ": " + __DATE__ + " " + __TIME__, "skin:icons/about.png"); #endif // td.appendText(temp); td.appendFile(tr["_about_"] + ".txt"); allyTTS((tr["_about_"] + ".txt").c_str(), FAST_GAP_TTS, FAST_SPEED_TTS); td.exec(); } void GMenu2X::viewLog() { string logfile = exe_path() + "/log.txt"; if (!file_exists(logfile)) return; TextDialog td(this, tr["Log Viewer"], tr["Last launched program's output"], "skin:icons/ebook.png"); td.appendFile(exe_path() + "/log.txt"); allyTTS((exe_path() + "/log.txt").c_str(), FAST_GAP_TTS, FAST_SPEED_TTS); td.exec(); MessageBox mb(this, tr["Delete the log file?"], "skin:icons/ebook.png"); mb.setButton(MANUAL, tr["Delete and disable"]); mb.setButton(CONFIRM, tr["Delete"]); mb.setButton(CANCEL, tr["No"]); int res = mb.exec(); switch (res) { case MANUAL: confInt["outputLogs"] = false; writeConfig(); case CONFIRM: ledOn(); unlink(logfile.c_str()); sync(); initMenu(); ledOff(); break; } } void GMenu2X::viewAutoStart() { MessageBox mb(this, tr["Continue with the AutoStart selected app?"]); mb.setButton(CONFIRM, tr["Yes"]); mb.setButton(CANCEL, tr["No"]); mb.setButton(MODIFIER, tr["Remove this dialog!"]); mb.setButton(MANUAL, tr["Poweroff"]); int res = mb.exec(); switch (res) { case CANCEL: confInt["saveAutoStart"] = 0; confInt["dialogAutoStart"] = 0; confStr["lastDirectory"] = ""; confStr["lastCommand"] = ""; reinit_save(); case MODIFIER: confInt["dialogAutoStart"] = 0; reinit_save(); case MANUAL: quit(); #if !defined(TARGET_LINUX) system("sync; mount -o remount,ro $HOME; poweroff"); #endif break; } } void GMenu2X::changeWallpaper() { WallpaperDialog wp(this, tr["Wallpaper"], tr["Select an image to use as a wallpaper"], "skin:icons/wallpaper.png"); if (wp.exec() && confStr["wallpaper"] != wp.wallpaper) { confStr["wallpaper"] = wp.wallpaper; confStr["tmp_wallpaper"] = base_name(confStr["wallpaper"]); } } void GMenu2X::showManual() { string linkTitle = menu->selLinkApp()->getTitle(); string linkDescription = menu->selLinkApp()->getDescription(); string linkIcon = menu->selLinkApp()->getIcon(); string linkManual = menu->selLinkApp()->getManualPath(); string linkBackdrop = confInt["skinBackdrops"] | BD_DIALOG ? menu->selLinkApp()->getBackdropPath() : ""; string linkExec = menu->selLinkApp()->getExec(); if (linkManual == "") return; TextDialog td(this, linkTitle, linkDescription, linkIcon); //, linkBackdrop); if (file_exists(linkManual)) { string ext = linkManual.substr(linkManual.size() - 4, 4); if (ext == ".png" || ext == ".bmp" || ext == ".jpg" || ext == "jpeg") { ImageViewerDialog im(this, linkTitle, linkDescription, linkIcon, linkManual); im.exec(); return; } td.appendFile(linkManual); #if defined(OPK_SUPPORT) } else if (file_ext(linkExec, true) == ".opk") { void *buf; size_t len; struct OPK *opk = opk_open(linkExec.c_str()); if (!opk) { ERROR("Unable to open OPK"); return; } if (opk_extract_file(opk, linkManual.c_str(), &buf, &len) < 0) { ERROR("Unable to extract file: %s\n", linkManual.c_str()); return; } opk_close(opk); char* str = strdup((const char*)buf); str[len] = 0; td.appendText(str); #endif // OPK_SUPPORT } else { return; } allyTTS(linkManual.c_str(), FAST_GAP_TTS, FAST_SPEED_TTS); td.exec(); } void GMenu2X::explorer() { BrowseDialog bd(this, tr["Explorer"], tr["Select a file or application"]); bd.showDirectories = true; bd.showFiles = true; if (confInt["saveSelection"]) bd.setPath(confStr["explorerLastDir"]); string command = cmdclean(bd.getFilePath(bd.selected)); if (confInt["saveAutoStart"]) { confInt["lastCPU"] = confInt["cpuMenu"]; confInt["lastKeyboardLayout"] = confInt["keyboardLayoutMenu"]; confStr["lastCommand"] = command.c_str(); confStr["lastDirectory"] = bd.getFilePath().c_str(); writeConfig(); } while (bd.exec()) { string ext = bd.getExt(bd.selected); if (ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".gif" || ext == ".bmp") { ImageViewerDialog im(this, tr["Image viewer"], bd.getFile(bd.selected), "icons/explorer.png", bd.getFilePath(bd.selected)); im.exec(); } else if (ext == ".txt" || ext == ".conf" || ext == ".me" || ext == ".md" || ext == ".xml" || ext == ".log" || ext == ".ini") { TextDialog td(this, tr["Text viewer"], bd.getFile(bd.selected), "skin:icons/ebook.png"); td.appendFile(bd.getFilePath(bd.selected)); allyTTS(bd.getFilePath(bd.selected).c_str(), FAST_GAP_TTS, FAST_SPEED_TTS); td.exec(); #if defined(IPK_SUPPORT) } else if (ext == ".ipk" && file_exists("/usr/bin/opkg")) { ipkInstall(bd.getFilePath(bd.selected)); #endif #if defined(OPK_SUPPORT) } else if (ext == ".opk") { opkInstall(bd.getFilePath(bd.selected)); #endif } else if (ext == ".sh") { TerminalDialog td(this, tr["Terminal"], "sh " + cmdclean(bd.getFileName(bd.selected)), "skin:icons/terminal.png"); td.exec(bd.getFilePath(bd.selected)); } else if (ext == ".zip" && file_exists("/usr/bin/unzip") && (bd.getFile(bd.selected).rfind("gmenu2x-skin-", 0) == 0) || (bd.getFile(bd.selected).rfind("gmenunx-skin-", 0) == 0)) { string path = bd.getFilePath(bd.selected); string skinname = base_name(path, true).substr(13); // strip gmenu2x-skin- and .zip if (skinname.size() > 1) { TerminalDialog td(this, tr["Skin installer"], tr["Installing skin"] + " " + skinname, "skin:icons/skin.png"); string cmd = "rm -rf \"skins/" + skinname + "/\"; mkdir -p \"skins/" + skinname + "/\"; unzip \"" + path + "\" -d \"skins/" + skinname + "/\"; if [ `ls \"skins/" + skinname + "\" | wc -l` == 1 ]; then subdir=`ls \"skins/" + skinname + "\"`; mv \"skins/" + skinname + "\"/$subdir/* \"skins/" + skinname + "/\"; rmdir \"skins/" + skinname + "\"/$subdir; fi; sync"; td.exec(cmd); setSkin(skinname, false); } } else if (ext == ".zip" && file_exists("/usr/bin/unzip")) { TerminalDialog td(this, tr["Zip content"], bd.getFileName(bd.selected), "skin:icons/terminal.png"); td.exec("unzip -l " + cmdclean(bd.getFilePath(bd.selected))); } else { if (confInt["saveSelection"] && (confInt["section"] != menu->selSectionIndex() || confInt["link"] != menu->selLinkIndex())) { writeConfig(); } string command = cmdclean(bd.getFilePath(bd.selected)); string params = ""; if (confInt["saveAutoStart"]) { confInt["lastCPU"] = confInt["cpuMenu"]; confInt["lastKeyboardLayout"] = confInt["keyboardLayoutMenu"]; confStr["lastCommand"] = command.c_str(); confStr["lastDirectory"] = bd.getFilePath().c_str(); writeConfig(); } if (confInt["outputLogs"]) { if (file_exists("/usr/bin/gdb")) { params = "-batch -ex \"run\" -ex \"bt\" --args " + command; command = "gdb"; } params += " 2>&1 | tee " + cmdclean(exe_path()) + "/log.txt"; } LinkApp *link = new LinkApp(this, "explorer.lnk~"); link->setExec(command); link->setParams(params); link->setIcon("skin:icons/terminal.png"); link->setTitle(bd.getFile(bd.selected)); link->launch(); return; } } confStr["explorerLastDir"] = bd.getPath(); } bool GMenu2X::saveScreenshot(string path) { #if !defined(TARGET_MIYOO) //for performance sake if (file_exists("/usr/bin/fbgrab")) { path = unique_filename(path + "/screenshot", ".png"); path = "/usr/bin/fbgrab " + path; return system(path.c_str()) == 0; } #endif path = unique_filename(path + "/screenshot", ".bmp"); return SDL_SaveBMP(s->raw, path.c_str()) == 0; } void GMenu2X::reinit(bool showDialog) { if (showDialog) { MessageBox mb(this, tr["GMenu2X will restart to apply"]+"\n"+tr["the settings. Continue?"], "skin:icons/exit.png"); mb.setButton(CONFIRM, tr["Restart"]); mb.setButton(CANCEL, tr["Cancel"]); if (mb.exec() == CANCEL) return; } quit_nosave(); WARNING("Re-launching gmenu2x"); chdir(exe_path().c_str()); execlp("./gmenu2x", "./gmenu2x", NULL); } void GMenu2X::reinit_save() { quit(); WARNING("Re-launching gmenu2x"); chdir(exe_path().c_str()); execlp("./gmenu2x", "./gmenu2x", NULL); } void GMenu2X::poweroffDialog() { #if !defined(NO_REBOOT) MessageBox mb(this, tr["Poweroff or reboot the device?"], "skin:icons/exit.png"); mb.setButton(SECTION_NEXT, tr["Reboot"]); #else MessageBox mb(this, tr["Poweroff the device?"], "skin:icons/exit.png"); #endif mb.setButton(CONFIRM, tr["Poweroff"]); mb.setButton(CANCEL, tr["Cancel"]); int res = mb.exec(); writeConfig(); switch (res) { case CONFIRM: { MessageBox mb(this, tr["Poweroff"]); mb.setAutoHide(1); mb.exec(); // setVolume(0); quit(); #if !defined(TARGET_LINUX) system("sync; mount -o remount,ro $HOME; poweroff"); #endif break; } case SECTION_NEXT: { MessageBox mb(this, tr["Rebooting"]); mb.setAutoHide(1); mb.exec(); // setVolume(0); quit(); #if !defined(TARGET_LINUX) system("sync; mount -o remount,ro $HOME; reboot"); #endif break; } } } void GMenu2X::umountSdDialog() { BrowseDialog bd(this, tr["Umount"], tr["Umount external media device"], "skin:icons/eject.png"); bd.showDirectories = true; bd.showFiles = false; bd.allowDirUp = false; bd.allowEnterDirectory = false; bd.setPath("/media"); bd.exec(); } void GMenu2X::contextMenu() { vector<MenuOption> options; if (menu->selLinkApp() != NULL) { options.push_back((MenuOption){tr["Edit"] + " " + menu->selLink()->getTitle(), MakeDelegate(this, &GMenu2X::editLink)}); options.push_back((MenuOption){tr["Delete"] + " " + menu->selLink()->getTitle(), MakeDelegate(this, &GMenu2X::deleteLink)}); } options.push_back((MenuOption){tr["Add link"], MakeDelegate(this, &GMenu2X::addLink)}); options.push_back((MenuOption){tr["Add section"], MakeDelegate(this, &GMenu2X::addSection)}); options.push_back((MenuOption){tr["Rename section"], MakeDelegate(this, &GMenu2X::renameSection)}); options.push_back((MenuOption){tr["Delete section"], MakeDelegate(this, &GMenu2X::deleteSection)}); #if defined(OPK_SUPPORT) options.push_back((MenuOption){tr["Update OPK links"], MakeDelegate(this, &GMenu2X::opkScanner)}); #endif MessageBox mb(this, options); } void GMenu2X::addLink() { BrowseDialog bd(this, tr["Add link"], tr["Select an application"]); bd.showDirectories = true; bd.showFiles = true; string filter = ".dge,.gpu,.gpe,.sh,.bin,.elf,"; #if defined(IPK_SUPPORT) filter = ".ipk," + filter; #endif #if defined(OPK_SUPPORT) filter = ".opk," + filter; #endif bd.setFilter(filter); while (bd.exec()) { string ext = bd.getExt(bd.selected); #if defined(IPK_SUPPORT) if (ext == ".ipk" && file_exists("/usr/bin/opkg")) { ipkInstall(bd.getFilePath(bd.selected)); } else #endif #if defined(OPK_SUPPORT) if (ext == ".opk") { opkInstall(bd.getFilePath(bd.selected)); } else #endif if (menu->addLink(bd.getFilePath(bd.selected))) { editLink(); return; } } sync(); } void GMenu2X::changeSelectorDir() { BrowseDialog bd(this, tr["Selector Path"], tr["Directory to start the selector"]); bd.showDirectories = true; bd.showFiles = false; bd.allowSelectDirectory = true; if (bd.exec() && bd.getPath() != "/") { confStr["tmp_selector"] = bd.getPath() + "/"; } } void GMenu2X::editLink() { if (menu->selLinkApp() == NULL) return; vector<string> pathV; split(pathV, menu->selLinkApp()->getFile(), "/"); string oldSection = ""; if (pathV.size() > 1) oldSection = pathV[pathV.size()-2]; string newSection = oldSection; string linkExec = menu->selLinkApp()->getExec(); string linkTitle = menu->selLinkApp()->getTitle(); string linkDescription = menu->selLinkApp()->getDescription(); string linkIcon = menu->selLinkApp()->getIcon(); string linkManual = menu->selLinkApp()->getManual(); string linkParams = menu->selLinkApp()->getParams(); string linkSelFilter = menu->selLinkApp()->getSelectorFilter(); string linkSelDir = menu->selLinkApp()->getSelectorDir(); bool useSelector = !linkSelDir.empty(); bool linkSelBrowser = menu->selLinkApp()->getSelectorBrowser(); string linkSelScreens = menu->selLinkApp()->getSelectorScreens(); string linkSelAliases = menu->selLinkApp()->getAliasFile(); int linkClock = menu->selLinkApp()->getCPU(); int linkKbdLayout = menu->selLinkApp()->getKbdLayout(); int linkTefix = menu->selLinkApp()->getTefix(); string linkBackdrop = menu->selLinkApp()->getBackdrop(); string dialogTitle = tr["Edit"] + " " + linkTitle; string dialogIcon = menu->selLinkApp()->getIconPath(); string linkDir = dir_name(linkExec); // string linkHomeDir = menu->selLinkApp()->getHomeDir(); vector<string> scaleMode; // scaleMode.push_back("Crop"); scaleMode.push_back("Stretch"); scaleMode.push_back("Aspect"); scaleMode.push_back("Original"); if (((float)(this->w)/this->h) != (4.0f/3.0f)) scaleMode.push_back("4:3"); string linkScaleMode = scaleMode[menu->selLinkApp()->getScaleMode()]; vector<string> selStr; selStr.push_back("OFF"); selStr.push_back("AUTO"); if (!linkSelDir.empty()) selStr.push_back(real_path(linkSelDir) + "/"); string s = ""; s += linkSelDir.back(); if (linkSelDir.empty()) confStr["tmp_selector"] = selStr[0]; else if (s != "/") confStr["tmp_selector"] = selStr[1]; else confStr["tmp_selector"] = selStr[2]; SettingsDialog sd(this, ts, dialogTitle, dialogIcon); // sd.addSetting(new MenuSettingFile( this, tr["Executable"], tr["Application this link points to"], &linkExec, ".dge,.gpu,.gpe,.sh,.bin,.opk,.elf,", linkExec, dialogTitle, dialogIcon)); sd.allowCancel_link = true; sd.addSetting(new MenuSettingString( this, tr["Title"], tr["Link title"], &linkTitle, dialogTitle, dialogIcon)); sd.addSetting(new MenuSettingString( this, tr["Description"], tr["Link description"], &linkDescription, dialogTitle, dialogIcon)); sd.addSetting(new MenuSettingMultiString( this, tr["Section"], tr["The section this link belongs to"], &newSection, &menu->getSections())); sd.addSetting(new MenuSettingString( this, tr["Parameters"], tr["Command line arguments to pass to the application"], &linkParams, dialogTitle, dialogIcon)); sd.addSetting(new MenuSettingImage( this, tr["Icon"], tr["Select a custom icon for the link"], &linkIcon, ".png,.bmp,.jpg,.jpeg,.gif", linkExec, dialogTitle, dialogIcon)); if (CPU_MAX != CPU_MIN) { #if defined(MULTI_INT) sd.addSetting(new MenuSettingMultiInt( this, tr["CPU Clock"], tr["CPU clock frequency when launching this link"], &linkClock, oc_choices, oc_choices_size, confInt["cpuLink"], confInt["cpuMin"], confInt["cpuMax"])); #else sd.addSetting(new MenuSettingInt( this, tr["CPU Clock"], tr["CPU clock frequency when launching this link"], &linkClock, confInt["cpuLink"], confInt["cpuMin"], confInt["cpuMax"], confInt["cpuStep"])); #endif } // sd.addSetting(new MenuSettingDir( this, tr["Home Path"], tr["Set directory as $HOME for this link"], &linkHomeDir, CARD_ROOT, dialogTitle, dialogIcon)); #if defined(HW_SCALER) sd.addSetting(new MenuSettingMultiString(this, tr["Scale Mode"], tr["Hardware scaling mode"], &linkScaleMode, &scaleMode)); #endif sd.addSetting(new MenuSettingInt( this, tr["Keyboard Layout"], tr["Set the appropriate A/B/X/Y layout"], &linkKbdLayout, confInt["keyboardLayoutMenu"], 1, confInt["keyboardLayoutMax"], 1)); sd.addSetting(new MenuSettingInt( this, tr["TEfix method"], tr["Set different tearing FIX method"], &linkTefix, confInt["tefixMenu"], 0, confInt["tefixMax"], 1)); sd.addSetting(new MenuSettingMultiString( this, tr["File Selector"], tr["Use file browser selector"], &confStr["tmp_selector"], &selStr, NULL, MakeDelegate(this, &GMenu2X::changeSelectorDir))); sd.addSetting(new MenuSettingBool( this, tr["Show Folders"], tr["Allow the selector to change directory"], &linkSelBrowser)); sd.addSetting(new MenuSettingString( this, tr["File Filter"], tr["Filter by file extension (separate with commas)"], &linkSelFilter, dialogTitle, dialogIcon)); sd.addSetting(new MenuSettingDir( this, tr["Box Art"], tr["Directory of the box art for the selector"], &linkSelScreens, linkDir, dialogTitle, dialogIcon)); sd.addSetting(new MenuSettingFile( this, tr["Aliases"], tr["File containing a list of aliases for the selector"], &linkSelAliases, ".txt,.dat", linkExec, dialogTitle, dialogIcon)); sd.addSetting(new MenuSettingImage( this, tr["Backdrop"], tr["Select an image backdrop"], &linkBackdrop, ".png,.bmp,.jpg,.jpeg", linkExec, dialogTitle, dialogIcon)); sd.addSetting(new MenuSettingFile( this, tr["Manual"], tr["Select a Manual or Readme file"], &linkManual, ".png,.bmp,.jpg,.jpeg,.txt,.me", linkExec, dialogTitle, dialogIcon)); #if defined(TARGET_WIZ) || defined(TARGET_CAANOO) bool linkUseGinge = menu->selLinkApp()->getUseGinge(); string ginge_prep = exe_path() + "/ginge/ginge_prep"; if (file_exists(ginge_prep)) sd.addSetting(new MenuSettingBool( this, tr["Use Ginge"], tr["Compatibility layer for running GP2X applications"], &linkUseGinge )); #endif #if defined(HW_GAMMA) int linkGamma = menu->selLinkApp()->getGamma(); sd.addSetting(new MenuSettingInt( this, tr["Gamma"], tr["Gamma value to set when launching this link"], &linkGamma, 0, 100 )); #endif if (sd.exec() && sd.edited() && sd.save) { ledOn(); menu->selLinkApp()->setExec(linkExec); menu->selLinkApp()->setTitle(linkTitle); menu->selLinkApp()->setDescription(linkDescription); menu->selLinkApp()->setIcon(linkIcon); menu->selLinkApp()->setManual(linkManual); menu->selLinkApp()->setParams(linkParams); menu->selLinkApp()->setSelectorFilter(linkSelFilter); menu->selLinkApp()->setSelectorElement(0); if (linkSelDir.empty()) linkSelDir = confStr["homePath"]; if (confStr["tmp_selector"] == "OFF") linkSelDir = ""; else if (confStr["tmp_selector"] == "AUTO") linkSelDir = real_path(linkSelDir); else linkSelDir = confStr["tmp_selector"]; int scalemode = 0; if (linkScaleMode == "Aspect") scalemode = 1; else if (linkScaleMode == "Original") scalemode = 2; else if (linkScaleMode == "4:3") scalemode = 3; menu->selLinkApp()->setScaleMode(scalemode); menu->selLinkApp()->setSelectorDir(linkSelDir); menu->selLinkApp()->setSelectorBrowser(linkSelBrowser); menu->selLinkApp()->setSelectorScreens(linkSelScreens); menu->selLinkApp()->setAliasFile(linkSelAliases); menu->selLinkApp()->setBackdrop(linkBackdrop); menu->selLinkApp()->setCPU(linkClock); menu->selLinkApp()->setKbdLayout(linkKbdLayout); menu->selLinkApp()->setTefix(linkTefix); #if defined(HW_GAMMA) menu->selLinkApp()->setGamma(linkGamma); #endif #if defined(TARGET_WIZ) || defined(TARGET_CAANOO) menu->selLinkApp()->setUseGinge(linkUseGinge); #endif // if section changed move file and update link->file if (oldSection != newSection) { vector<string>::const_iterator newSectionIndex = find(menu->getSections().begin(), menu->getSections().end(), newSection); if (newSectionIndex == menu->getSections().end()) return; string newFileName = "sections/" + newSection + "/" + linkTitle; uint32_t x = 2; while (file_exists(newFileName)) { string id = ""; stringstream ss; ss << x; ss >> id; newFileName = "sections/" + newSection + "/" + linkTitle + id; x++; } rename(menu->selLinkApp()->getFile().c_str(), newFileName.c_str()); menu->selLinkApp()->renameFile(newFileName); INFO("New section: (%i) %s", newSectionIndex - menu->getSections().begin(), newSection.c_str()); menu->linkChangeSection(menu->selLinkIndex(), menu->selSectionIndex(), newSectionIndex - menu->getSections().begin()); } menu->selLinkApp()->save(); sync(); ledOff(); } confInt["section"] = menu->selSectionIndex(); confInt["link"] = menu->selLinkIndex(); confStr["tmp_selector"] = ""; } void GMenu2X::deleteLink() { int package_type = 0; MessageBox mb(this, tr["Delete"] + " " + menu->selLink()->getTitle() + "\n" + tr["THIS CAN'T BE UNDONE"] + "\n" + tr["Are you sure?"], menu->selLink()->getIconPath()); string package = menu->selLinkApp()->getExec(); #if defined(OPK_SUPPORT) if (file_ext(package, true) == ".opk") { package_type = 1; mb.setButton(MODIFIER, tr["Uninstall OPK"]); goto dialog; // shameless use of goto } #endif #if defined(IPK_SUPPORT) package = ipkName(menu->selLinkApp()->getFile()); if (!package.empty()) { package_type = 2; mb.setButton(MODIFIER, tr["Uninstall IPK"]); goto dialog; // shameless use of goto } #endif dialog: mb.setButton(MANUAL, tr["Delete link"]); mb.setButton(CANCEL, tr["No"]); switch (mb.exec()) { case MODIFIER: if (package_type == 1) { unlink(package.c_str()); menu->deleteSelectedLink(); } else if (package_type == 2) { TerminalDialog td(this, tr["Uninstall package"], "opkg remove " + package, "skin:icons/configure.png"); td.exec("opkg remove " + package); } initMenu(); break; case MANUAL: menu->deleteSelectedLink(); break; default: return; } } void GMenu2X::addSection() { InputDialog id(this, /*ts,*/ tr["Insert a name for the new section"], "", tr["Add section"], "skin:icons/section.png"); if (id.exec()) { // only if a section with the same name does not exist if (find(menu->getSections().begin(), menu->getSections().end(), id.getInput()) == menu->getSections().end()) { // section directory doesn't exists ledOn(); if (menu->addSection(id.getInput())) { menu->setSectionIndex(menu->getSections().size() - 1); //switch to the new section sync(); } ledOff(); } } } void GMenu2X::renameSection() { InputDialog id(this, /*ts,*/ tr["Insert a new name for this section"], menu->selSection(), tr["Rename section"], menu->getSectionIcon()); if (id.exec()) { menu->renameSection(menu->selSectionIndex(), id.getInput()); sync(); } } void GMenu2X::deleteSection() { MessageBox mb(this, tr["Delete section"] + " '" + menu->selSectionName() + "'\n" + tr["THIS CAN'T BE UNDONE"] + "\n" + tr["Are you sure?"], menu->getSectionIcon()); mb.setButton(MANUAL, tr["Yes"]); mb.setButton(CANCEL, tr["No"]); if (mb.exec() != MANUAL) return; ledOn(); if (rmtree(exe_path() + "/sections/" + menu->selSection())) { menu->deleteSelectedSection(); sync(); } ledOff(); } #if defined(OPK_SUPPORT) void GMenu2X::opkScanner() { OPKScannerDialog od(this, tr["Update OPK links"], "Scanning OPK packages", "skin:icons/configure.png"); od.exec(); initMenu(); } void GMenu2X::opkInstall(string path) { input.update(false); bool debug = input[MANUAL]; OPKScannerDialog od(this, tr["Package installer"], tr["Installing"] + " " + base_name(path), "skin:icons/configure.png"); od.opkpath = path; od.exec(debug); initMenu(); } #endif #if defined(IPK_SUPPORT) string GMenu2X::ipkName(string cmd) { if (!file_exists("/usr/bin/opkg")) return ""; char package[128] = {0,0,0,0,0,0,0,0}; cmd = "opkg search \"*" + base_name(cmd) + "\" | cut -f1 -d' '"; FILE *fp = popen(cmd.c_str(), "r"); if (fp == NULL) return ""; fgets(package, sizeof(package) - 1, fp); pclose(fp); if (package == NULL) return ""; return trim((string)package); } void GMenu2X::ipkInstall(string path) { string cmd = "opkg install --force-reinstall --force-overwrite "; input.update(false); if (input[MANUAL]) cmd += "--force-downgrade "; TerminalDialog td(this, tr["Package installer"], "opkg install " + base_name(path), "skin:icons/configure.png"); td.exec(cmd + cmdclean(path)); //system("if [ -d sections/systems ]; then mkdir -p sections/emulators.systems; cp -r sections/systems/* sections/emulators.systems/; rm -rf sections/systems; fi; sync;"); initMenu(); } #endif void GMenu2X::setInputSpeed() { input.setInterval(150); input.setInterval(300, SECTION_PREV); input.setInterval(300, SECTION_NEXT); input.setInterval(300, CONFIRM); input.setInterval(300, CANCEL); input.setInterval(300, MANUAL); input.setInterval(300, MODIFIER); input.setInterval(300, PAGEUP); input.setInterval(300, PAGEDOWN); // input.setInterval(1000, SETTINGS); // input.setInterval(100, MENU); // input.setInterval(1000, POWER); // input.setInterval(30, VOLDOWN); // input.setInterval(30, VOLUP); // input.setInterval(100, INC); // input.setInterval(100, DEC); // input.setInterval(200, BACKLIGHT); } int GMenu2X::setVolume(int val, bool popup) { int volumeStep = 10; val = constrain(val, 0, 90); if (popup) { Surface bg(s); Surface *iconVolume[3] = { sc["skin:imgs/mute.png"], sc["skin:imgs/phones.png"], sc["skin:imgs/volume.png"], }; powerManager->clearTimer(); while (true) { drawSlider(val, 0, 90, *iconVolume[getVolumeMode(val)], bg); input.update(); if (input[SETTINGS] || input[CONFIRM] || input[CANCEL]) { break; } else if (input[LEFT] || input.hatEvent(DLEFT) == DLEFT || input[DEC] || input[VOLDOWN] || input[SECTION_PREV]) { val = max(0, val - volumeStep); } else if (input[RIGHT] || input.hatEvent(DRIGHT) == DRIGHT || input[INC] || input[VOLUP] || input[SECTION_NEXT]) { val = min(90, val + volumeStep); } val = constrain(val, 0, 90); } bg.blit(s, 0, 0); s->flip(); powerManager->resetSuspendTimer(); #if !defined(HW_LIDVOL) confInt["globalVolume"] = val; writeConfig(); #endif } return val; } int GMenu2X::setBacklight(int val, bool popup) { if (popup) { int backlightStep = 10; val = constrain(val, 10, 100); Surface bg(s); Surface *iconBrightness[6] = { sc["skin:imgs/brightness/0.png"], sc["skin:imgs/brightness/1.png"], sc["skin:imgs/brightness/2.png"], sc["skin:imgs/brightness/3.png"], sc["skin:imgs/brightness/4.png"], sc["skin:imgs/brightness.png"], }; powerManager->clearTimer(); while (true) { int brightnessIcon = val / 20; if (brightnessIcon > 4 || iconBrightness[brightnessIcon] == NULL) brightnessIcon = 5; drawSlider(val, 0, 100, *iconBrightness[brightnessIcon], bg); input.update(); if (input[SETTINGS] || input[CONFIRM] || input[CANCEL]) { break; } else if (input[LEFT] || input.hatEvent(DLEFT) == DLEFT || input[DEC] || input[SECTION_PREV]) { val = setBacklight(max(10, val - backlightStep), false); } else if (input[RIGHT] || input.hatEvent(DRIGHT) == DRIGHT || input[INC] || input[SECTION_NEXT]) { val = setBacklight(min(100, val + backlightStep), false); } else if (input[BACKLIGHT]) { SDL_Delay(50); val = getBacklight(); } val = constrain(val, 5, 100); } bg.blit(s, 0, 0); s->flip(); powerManager->resetSuspendTimer(); #if !defined(HW_LIDVOL) confInt["backlight"] = val; writeConfig(); #endif } return val; } int GMenu2X::drawButton(Button *btn, int x, int y) { if (y < 0) y = this->h + y; btn->setPosition(x, y); btn->paint(); } int GMenu2X::drawButton(Surface *s, const string &btn, const string &text, int x, int y) { if (y < 0) y = this->h + y; Surface *icon = sc["skin:imgs/buttons/" + btn + ".png"]; if (icon != NULL) { icon->blit(s, x, y, HAlignLeft | VAlignMiddle); x += 19; if (!text.empty()) { s->write(font, text, x, y, VAlignMiddle, skinConfColors[COLOR_FONT_ALT], skinConfColors[COLOR_FONT_ALT_OUTLINE]); x += font->getTextWidth(text); } } return x + 6; } int GMenu2X::drawButtonRight(Surface *s, const string &btn, const string &text, int x, int y) { if (y < 0) y = this->h + y; Surface *icon = sc["skin:imgs/buttons/" + btn + ".png"]; if (icon != NULL) { if (!text.empty()) { x -= font->getTextWidth(text); s->write(font, text, x, y, HAlignLeft | VAlignMiddle, skinConfColors[COLOR_FONT_ALT], skinConfColors[COLOR_FONT_ALT_OUTLINE]); } x -= 19; icon->blit(s, x, y, HAlignLeft | VAlignMiddle); } return x - 6; } void GMenu2X::drawScrollBar(uint32_t pagesize, uint32_t totalsize, uint32_t pagepos, SDL_Rect scrollRect, const uint8_t align) { if (totalsize <= pagesize) return; SDL_Rect bar = {2, 2, 2, 2}; if ((align & VAlignBottom) || (align & VAlignTop)) { bar.w = (scrollRect.w - 3) * pagesize / totalsize; bar.x = (scrollRect.w - 3) * pagepos / totalsize; bar.x = scrollRect.x + bar.x + 3; if (align & VAlignTop) { bar.y = scrollRect.y + 2; // top } else { bar.y = scrollRect.y + scrollRect.h - 4; // bottom } if (bar.w < 8) { bar.w = 8; } if (bar.x + bar.w > scrollRect.x + scrollRect.w - 3) { bar.x = scrollRect.x + scrollRect.w - bar.w - 3; } } else { // HAlignLeft || HAlignRight bar.h = (scrollRect.h - 3) * pagesize / totalsize; bar.y = (scrollRect.h - 3) * pagepos / totalsize; bar.y = scrollRect.y + bar.y + 3; if (align & HAlignRight) { bar.x = scrollRect.x + scrollRect.w - 4; // right } if (bar.h < 8) { bar.h = 8; } if (bar.y + bar.h > scrollRect.y + scrollRect.h - 3) { bar.y = scrollRect.y + scrollRect.h - bar.h - 3; } } s->box(bar, skinConfColors[COLOR_SELECTION_BG]); s->rectangle(bar.x - 1, bar.y - 1, bar.w + 2, bar.h + 2, skinConfColors[COLOR_LIST_BG]); } void GMenu2X::drawSlider(int val, int min, int max, Surface &icon, Surface &bg) { SDL_Rect progress = {52, 32, this->w - 84, 8}; SDL_Rect box = {20, 20, this->w - 40, 32}; val = constrain(val, min, max); bg.blit(s,0,0); s->box(box, skinConfColors[COLOR_MESSAGE_BOX_BG]); s->rectangle(box.x + 2, box.y + 2, box.w - 4, box.h - 4, skinConfColors[COLOR_MESSAGE_BOX_BORDER]); icon.blit(s, 28, 28); s->box(progress, skinConfColors[COLOR_MESSAGE_BOX_BG]); s->box(progress.x + 1, progress.y + 1, val * (progress.w - 3) / max + 1, progress.h - 2, skinConfColors[COLOR_MESSAGE_BOX_SELECTION]); s->flip(); } uint32_t GMenu2X::timerFlip(uint32_t interval, void *param) { instance->s->flip(); return 0; };
85,687
C++
.cpp
2,064
38.682655
366
0.671567
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,086
buttonbox.cpp
MiyooCFW_gmenu2x/src/buttonbox.cpp
#include "button.h" #include "gmenu2x.h" #include "buttonbox.h" ButtonBox::ButtonBox(GMenu2X *gmenu2x): gmenu2x(gmenu2x) {} ButtonBox::~ButtonBox() { for (ButtonList::const_iterator it = buttons.begin(); it != buttons.end(); ++it) delete *it; } void ButtonBox::add(Button *button) { buttons.push_back(button); } void ButtonBox::remove(uint32_t n) { for (uint32_t i = 0; i < n; i++) buttons.pop_back(); } void ButtonBox::paint(uint32_t posX) { for (ButtonList::const_iterator it = buttons.begin(); it != buttons.end(); ++it) posX = gmenu2x->drawButton(*it, posX); } void ButtonBox::handleTS() { for (ButtonList::iterator it = buttons.begin(); it != buttons.end(); ++it) (*it)->handleTS(); }
707
C++
.cpp
23
29
81
0.688791
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
1,534,087
menusettingmultistring.cpp
MiyooCFW_gmenu2x/src/menusettingmultistring.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "menusettingmultistring.h" #include "gmenu2x.h" #include "iconbutton.h" #include <algorithm> using std::find; MenuSettingMultiString::MenuSettingMultiString(GMenu2X *gmenu2x, const string &title, const string &description, string *value, const vector<string> *choices, msms_onchange_t onChange, msms_onselect_t onSelect): MenuSettingStringBase(gmenu2x, title, description, value), choices(choices), onChange(onChange), onSelect(onSelect) { setSel(find(choices->begin(), choices->end(), *value) - choices->begin(), 0); if (choices->size() > 1) { btn = new IconButton(gmenu2x, "dpad", gmenu2x->tr["Change"]); // btn->setAction(MakeDelegate(this, &MenuSettingMultiString::incSel)); buttonBox.add(btn); } if (this->onSelect) { btn = new IconButton(gmenu2x, "a", gmenu2x->tr["Open"]); // btn->setAction(MakeDelegate(this, &MenuSettingMultiString::incSel)); buttonBox.add(btn); } } uint32_t MenuSettingMultiString::manageInput() { if (gmenu2x->input[LEFT] || gmenu2x->input.hatEvent(DLEFT) == DLEFT) { decSel(); return this->onChange && this->onChange(); } else if (gmenu2x->input[RIGHT] || gmenu2x->input.hatEvent(DRIGHT) == DRIGHT) { incSel(); return this->onChange && this->onChange(); } else if (gmenu2x->input[CONFIRM] && this->onSelect) { this->onSelect(); return this->onChange && this->onChange(); } else if (gmenu2x->input[MODIFIER] && !gmenu2x->input[MANUAL]) { currentSel(); } else if (gmenu2x->input[MENU]) { setSel(0, 1); return this->onChange && this->onChange(); } return 0; // SD_NO_ACTION } void MenuSettingMultiString::incSel() { setSel(selected + 1, 1); } void MenuSettingMultiString::decSel() { setSel(selected - 1, 1); } void MenuSettingMultiString::currentSel() { setSel(selected, 1); } void MenuSettingMultiString::setSel(int sel, bool readValue) { if (sel < 0) { sel = choices->size()-1; } else if (sel >= (int)choices->size()) { sel = 0; } selected = sel; setValue((*choices)[sel]); if (readValue) gmenu2x->allyTTS(value().c_str(), MEDIUM_GAP_TTS, MEDIUM_SPEED_TTS, 0); } void MenuSettingMultiString::draw(int y) { MenuSetting::draw(y); int w = 0; if (value() == "ON" || value() == "AUTO" || value() == "OFF") { w = gmenu2x->font->getHeight()/2.5; RGBAColor color = (RGBAColor){255, 0, 0, 255}; if (value() == "ON" || value() == "AUTO") color = (RGBAColor) {0, 255, 0, 255}; gmenu2x->s->box(180, y + 1, w, gmenu2x->font->getHeight() - 2, color); gmenu2x->s->rectangle(180, y + 1, w, gmenu2x->font->getHeight() - 2, 0, 0, 0, 255); w += 2; } gmenu2x->s->write(gmenu2x->font, value(), 180 + w, y + gmenu2x->font->getHalfHeight(), VAlignMiddle); }
4,064
C++
.cpp
92
42.021739
211
0.596212
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,088
translator.cpp
MiyooCFW_gmenu2x/src/translator.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include <fstream> #include <sstream> #include <stdarg.h> #if defined(CHECK_TRANSLATION) #include <set> #include <algorithm> #endif #include "translator.h" #include "debug.h" using namespace std; Translator::Translator(const string &lang) { _lang = ""; if (!lang.empty()) setLang(lang); } Translator::~Translator() {} // bool Translator::exists(const string &term) { // return translations.find(term) != translations.end(); // } void Translator::setLang(const string &lang) { translations.clear(); string line; ifstream infile (string("translations/"+lang).c_str(), ios_base::in); if (infile.is_open()) { while (getline(infile, line, '\n')) { line = trim(line); if (line=="") continue; if (line[0]=='#') continue; if (line.back() == '=') continue; string::size_type position = line.find("="); string::size_type position_newl_all = line.find("\\n"); string trans; string::size_type pos = 0; uint32_t count = 0; while ((pos = line.find("\\n", pos)) != std::string::npos) { ++count; pos += 2; } if (position_newl_all != std::string::npos) { string::size_type position_newl[365]; for (uint32_t i = 0; i <= count; i++) { // check if this is first chunk if (i == 0) position_newl[i] = line.find("\\n"); else position_newl[i] = line.find("\\n", position_newl[i-1] + 2); // genearate translation string from all chunks if (i == 0 && position_newl[i] != std::string::npos) trans += trim(line.substr(position + 1, position_newl[i] - position - 1)) + "\n"; else if (position_newl[i] != std::string::npos) trans += trim(line.substr(position_newl[i-1] + 2, position_newl[i] - position_newl[i-1] - 2)) + "\n"; else trans += trim(line.substr(position_newl[i-1] + 2)); } translations[trim(line.substr(0, position))] = trans; } else { translations[trim(line.substr(0, position))] = trim(line.substr(position + 1)); } } infile.close(); _lang = lang; } } string Translator::translate(const string &term,const char *replacestr,...) { string result = term; string termFind = term; string::size_type pos = 0; while ((pos = termFind.find('\n', pos)) != std::string::npos) { termFind.replace(pos, 1, " "); pos += 1; } if (!_lang.empty()) { unordered_map<string, string>::iterator i = translations.find(termFind); if (i != translations.end()) { result = i->second; #if defined(CHECK_TRANSLATION) } else { WARNING("Untranslated string: '%s'", term.c_str()); ofstream langLog("untranslated.txt", ios::app); if (langLog.is_open()) { // Write strings to the file, each on a new line langLog << term + "=\n"; INFO("String written to the file successfully."); langLog.close(); //sort and remove double entries in generated list ifstream input("untranslated.txt"); if (input.is_open()) { vector<std::string> lines; string line; while (std::getline(input, line)) { lines.push_back(line); } input.close(); sort(lines.begin(), lines.end()); set<std::string> uniqueLines(lines.begin(), lines.end()); ofstream output("untranslated.txt"); for (const auto& uniqueLine : uniqueLines) { output << uniqueLine << '\n'; } output.close(); } } else { WARNING("Unable to open the file."); } #endif } } va_list arglist; va_start(arglist, replacestr); const char *param = replacestr; int argnum = 1; while (param!=NULL) { string id = ""; stringstream ss; ss << argnum; ss >> id; result = strreplace(result, "$" + id, param); param = va_arg(arglist, const char*); argnum++; } va_end(arglist); return result; } string Translator::operator[](const string &term) { return translate(term); } string Translator::lang() { return _lang; }
5,199
C++
.cpp
141
33.531915
154
0.582936
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,089
powermanager.cpp
MiyooCFW_gmenu2x/src/powermanager.cpp
#include "powermanager.h" PowerManager *PowerManager::instance = NULL; PowerManager::PowerManager(GMenu2X *gmenu2x, uint32_t suspendTimeout, uint32_t powerTimeout): gmenu2x(gmenu2x), suspendTimeout(suspendTimeout), powerTimeout(powerTimeout) { instance = this; resetSuspendTimer(); } PowerManager::~PowerManager() { clearTimer(); instance = NULL; } void PowerManager::setSuspendTimeout(uint32_t suspendTimeout) { this->suspendTimeout = suspendTimeout; resetSuspendTimer(); }; void PowerManager::setPowerTimeout(uint32_t powerTimeout) { this->powerTimeout = powerTimeout; resetSuspendTimer(); }; void PowerManager::clearTimer() { SDL_RemoveTimer(powerTimer); powerTimer = NULL; }; void PowerManager::resetSuspendTimer() { clearTimer(); if (this->suspendTimeout > 0) powerTimer = SDL_AddTimer(this->suspendTimeout * 1e3, doSuspend, NULL); }; void PowerManager::resetPowerTimer() { clearTimer(); if (this->powerTimeout > 0) powerTimer = SDL_AddTimer(this->powerTimeout * 60e3, doPowerOff, NULL); }; uint32_t PowerManager::doSuspend(uint32_t interval, void *param) { if (interval > 0) { #if defined(HW_LIDVOL) PowerManager::instance->gmenu2x->confInt["backlight"] = PowerManager::instance->gmenu2x->getBacklight(); PowerManager::instance->gmenu2x->confInt["globalVolume"] = PowerManager::instance->gmenu2x->getVolume(); // INFO("%i", PowerManager::instance->gmenu2x->confInt["backlight"]); // INFO("%i", PowerManager::instance->gmenu2x->confInt["globalVolume"]); #endif PowerManager::instance->gmenu2x->setBacklight(0); // PowerManager::instance->gmenu2x->setVolume(0); PowerManager::instance->resetPowerTimer(); PowerManager::instance->gmenu2x->cls(); if (!PowerManager::instance->gmenu2x->isUsbConnected()) PowerManager::instance->gmenu2x->setCPU(PowerManager::instance->gmenu2x->confInt["cpuMin"]); PowerManager::instance->suspendActive = true; return interval; } // INFO("%i", PowerManager::instance->gmenu2x->confInt["backlight"]); // INFO("%i", PowerManager::instance->gmenu2x->confInt["globalVolume"]); PowerManager::instance->gmenu2x->setBacklight(max(10, PowerManager::instance->gmenu2x->confInt["backlight"])); PowerManager::instance->gmenu2x->setVolume(PowerManager::instance->gmenu2x->confInt["globalVolume"]); PowerManager::instance->gmenu2x->setCPU(PowerManager::instance->gmenu2x->confInt["cpuMenu"]); PowerManager::instance->suspendActive = false; PowerManager::instance->resetSuspendTimer(); PowerManager::instance->gmenu2x->actionPerformed = false; return interval; }; uint32_t PowerManager::doPowerOff(uint32_t interval, void *param) { #if !defined(TARGET_LINUX) system("sync; poweroff"); #endif return interval; };
2,693
C++
.cpp
65
39.523077
111
0.770642
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,090
imageviewerdialog.cpp
MiyooCFW_gmenu2x/src/imageviewerdialog.cpp
#include "imageviewerdialog.h" #include "debug.h" ImageViewerDialog::ImageViewerDialog(GMenu2X *gmenu2x, const string &title, const string &description, const string &icon, const string &path): Dialog(gmenu2x, title, description, icon), path(path) {} void ImageViewerDialog::exec() { Surface image(path); bool inputAction = false; int offsetX = 0, offsetY = 0; buttons.push_back({"dpad", gmenu2x->tr["Pan"]}); buttons.push_back({"b", gmenu2x->tr["Exit"]}); drawDialog(this->bg); while (true) { this->bg->blit(gmenu2x->s, 0, 0); gmenu2x->s->setClipRect(gmenu2x->listRect); image.blit(gmenu2x->s, gmenu2x->listRect.x + offsetX, gmenu2x->listRect.y + offsetY); gmenu2x->s->flip(); gmenu2x->s->clearClipRect(); do { inputAction = gmenu2x->input.update(); if (gmenu2x->inputCommonActions(inputAction)) continue; if (gmenu2x->input[CANCEL] || gmenu2x->input[SETTINGS]) return; else if ((gmenu2x->input[LEFT] || gmenu2x->input.hatEvent(DLEFT) == DLEFT) && offsetX < 0) { offsetX += gmenu2x->listRect.w / 3; if (offsetX > 0) offsetX = 0; } else if ((gmenu2x->input[RIGHT] || gmenu2x->input.hatEvent(DRIGHT) == DRIGHT) && image.raw->w + offsetX > gmenu2x->listRect.w) { offsetX -= gmenu2x->listRect.w / 3; if (image.raw->w + offsetX < gmenu2x->listRect.w) offsetX = gmenu2x->listRect.w - image.raw->w; } else if ((gmenu2x->input[UP] || gmenu2x->input.hatEvent(DUP) == DUP) && offsetY < 0) { offsetY += gmenu2x->listRect.h / 3; if (offsetY > 0) offsetY = 0; } else if ((gmenu2x->input[DOWN] || gmenu2x->input.hatEvent(DDOWN) == DDOWN) && image.raw->h + offsetY > gmenu2x->listRect.h) { offsetY -= gmenu2x->listRect.h / 3; if (image.raw->h + offsetY < gmenu2x->listRect.h) offsetY = gmenu2x->listRect.h - image.raw->h; } } while (!inputAction); } }
1,835
C++
.cpp
40
42.525
143
0.670022
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,091
fonthelper.cpp
MiyooCFW_gmenu2x/src/fonthelper.cpp
#include "fonthelper.h" #include "utilities.h" #include "debug.h" #include <sstream> const uint8_t outline = 1; FontHelper::FontHelper(const string &fontName, int fontSize, RGBAColor textColor, RGBAColor outlineColor): fontName(fontName), fontSize(fontSize), textColor(textColor), outlineColor(outlineColor) { loadFont(fontName, fontSize); } FontHelper::~FontHelper() { free(); } void FontHelper::free() { TTF_CloseFont(font); TTF_CloseFont(fontOutline); } void FontHelper::loadFont(const string &fontName, int fontSize) { if (!TTF_WasInit()) { DEBUG("Initializing font"); if (TTF_Init() == -1) { ERROR("TTF_Init: %s", TTF_GetError()); exit(2); } } this->font = TTF_OpenFont(fontName.c_str(), fontSize); this->fontOutline = TTF_OpenFont(fontName.c_str(), fontSize); if (!this->font || !this->fontOutline) { ERROR("TTF_OpenFont %s: %s", fontName.c_str(), TTF_GetError()); return; } fontFamilyName = TTF_FontFaceFamilyName(font); if (fontFamilyName == "") { WARNING("Unable to read TTF font family name.\n"); } DEBUG("Font Name: %s", fontFamilyName.c_str()); TTF_SetFontHinting(this->font, TTF_HINTING_LIGHT); TTF_SetFontHinting(this->fontOutline, TTF_HINTING_LIGHT); TTF_SetFontOutline(this->fontOutline, outline); height = 0; // Get maximum line height with a sample text TTF_SizeUTF8(this->font, "AZ0987654321", NULL, &height); halfHeight = height / 2; } bool FontHelper::utf8Code(uint8_t c) { return (c >= 194 && c <= 198) || c == 208 || c == 209; } FontHelper *FontHelper::setSize(const int size) { if (this->fontSize == size) return this; TTF_CloseFont(font); TTF_CloseFont(fontOutline); fontSize = size; loadFont(this->fontName, this->fontSize); return this; } FontHelper *FontHelper::setColor(RGBAColor color) { textColor = color; return this; } FontHelper *FontHelper::setOutlineColor(RGBAColor color) { outlineColor = color; return this; } uint32_t FontHelper::getLineWidth(const string &text) { int width = 0; TTF_SizeUTF8(fontOutline, text.c_str(), &width, NULL); return width; } uint32_t FontHelper::getTextWidth(const string &text) { if (text.find("\n",0) != string::npos) { vector<string> textArr; split(textArr,text,"\n"); return getTextWidth(&textArr); } return getLineWidth(text); } uint32_t FontHelper::getTextWidth(vector<string> *text) { int w = 0; for (uint32_t i = 0; i < text->size(); i++) { w = max(getLineWidth(text->at(i)), w); }; return w; } int FontHelper::getTextHeight(const string &text) { vector<string> textArr; split(textArr, text, "\n"); return textArr.size(); } void FontHelper::write(Surface *surface, vector<string> *text, int x, int y, const uint8_t align) { write(surface, text, x, y, align, textColor, outlineColor); } void FontHelper::write(Surface *surface, vector<string> *text, int x, int y, const uint8_t align, RGBAColor fgColor, RGBAColor bgColor) { if (align & VAlignMiddle) { y -= getHalfHeight() * text->size(); } else if (align & VAlignBottom) { y -= getHeight() * text->size(); } for (uint32_t i = 0; i < text->size(); i++) { int ix = x; if (align & HAlignCenter) { ix -= getTextWidth(text->at(i)) / 2; } else if (align & HAlignRight) { ix -= getTextWidth(text->at(i)); } write(surface, text->at(i), ix, y + i * getHeight(), fgColor, bgColor); } } void FontHelper::write(Surface* surface, const string &text, int x, int y, const uint8_t align, RGBAColor fgColor, RGBAColor bgColor) { if (text.find("\n", 0) != string::npos) { vector<string> textArr; split(textArr,text, "\n"); write(surface, &textArr, x, y, align, fgColor, bgColor); return; } if (align & HAlignCenter) { x -= getTextWidth(text) / 2; } else if (align & HAlignRight) { x -= getTextWidth(text); } if (align & VAlignMiddle) { y -= getHalfHeight(); } else if (align & VAlignBottom) { y -= getHeight(); } write(surface, text, x, y, fgColor, bgColor); } void FontHelper::write(Surface *surface, const string &text, int x, int y, const uint8_t align) { write(surface, text, x, y, align, textColor, outlineColor); } void FontHelper::write(Surface *surface, const string &text, SDL_Rect &wrapRect, const uint8_t align) { string textwrap = ""; uint32_t maxWidth = wrapRect.w; //uint32_t maxString = 0; bool firstline = true; if (getTextWidth(text) > maxWidth) { string line = ""; string prvsub = ""; std::istringstream iss(text); do { string subs; iss >> subs; if (getTextWidth(subs) > maxWidth) maxWidth = getTextWidth(subs); //if (getTextWidth(subs) > maxString) maxString = getTextWidth(subs); } while (iss); //if (maxWidth == wrapRect.w) firstline = false; std::istringstream iss2(text); do { string subs; iss2 >> subs; line += subs + " "; if (getTextWidth(line) > maxWidth || getTextWidth(prvsub) == maxWidth /*|| (maxWidth == wrapRect.w && getTextWidth(textwrap) > maxWidth && getTextWidth(prvsub + " " + line) > maxWidth && getTextWidth(prvsub) < maxString)*/) { textwrap += "\n"; if (!firstline) { line = ""; firstline = true; } } else { textwrap += " "; } if (line != "") firstline = false; textwrap += subs; prvsub = subs; } while (iss2); textwrap = trim(textwrap); } else { textwrap = trim(text); } write(surface, textwrap, wrapRect.x, wrapRect.y, align, textColor, outlineColor); } void FontHelper::write(Surface *surface, const string &text, int x, int y, RGBAColor fgColor, RGBAColor bgColor) { if (text.empty()) return; if (bgColor.a > 0) { Surface bg; if (fontFamilyName.find("Unifont") == string::npos) { bg.raw = TTF_RenderUTF8_Blended(fontOutline, text.c_str(), rgbatosdl(bgColor)); } else { bg.raw = TTF_RenderUTF8_Solid(fontOutline, text.c_str(), rgbatosdl(bgColor)); } bg.setAlpha(bgColor.a); bg.blit(surface, x - outline, y - outline); } if (fgColor.a > 0) { Surface fg; if (fontFamilyName.find("Unifont") == string::npos) { fg.raw = TTF_RenderUTF8_Blended(font, text.c_str(), rgbatosdl(fgColor)); } else { fg.raw = TTF_RenderUTF8_Solid(font, text.c_str(), rgbatosdl(fgColor)); } fg.setAlpha(fgColor.a); fg.blit(surface, x, y); } }
6,160
C++
.cpp
193
29.38342
137
0.684113
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,092
menusettingstring.cpp
MiyooCFW_gmenu2x/src/menusettingstring.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "menusettingstring.h" #include "iconbutton.h" #include "inputdialog.h" using std::string; using fastdelegate::MakeDelegate; MenuSettingString::MenuSettingString(GMenu2X *gmenu2x, const string &title, const string &description, string *value, const string &dialogTitle, const string &dialogIcon): MenuSettingStringBase(gmenu2x, title, description, value), dialogTitle(dialogTitle), dialogIcon(dialogIcon) { btn = new IconButton(gmenu2x, "select", gmenu2x->tr["Reset"]); // btn->setAction(MakeDelegate(this, &MenuSettingString::clear)); buttonBox.add(btn); btn = new IconButton(gmenu2x, "a", gmenu2x->tr["Edit"]); // btn->setAction(MakeDelegate(this, &MenuSettingString::edit)); buttonBox.add(btn); } void MenuSettingString::edit() { InputDialog id(gmenu2x, /*gmenu2x->ts,*/ description, value(), dialogTitle, dialogIcon); if (id.exec()) setValue(id.getInput()); gmenu2x->allyTTS(value().c_str(), MEDIUM_GAP_TTS, MEDIUM_SPEED_TTS, 0); }
2,361
C++
.cpp
38
60.315789
171
0.566624
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
1,534,093
menusetting.cpp
MiyooCFW_gmenu2x/src/menusetting.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "menusetting.h" #include "gmenu2x.h" MenuSetting::MenuSetting(GMenu2X *gmenu2x, const string &title, const string &description): gmenu2x(gmenu2x), buttonBox(gmenu2x), title(title), description(description) { btn = new IconButton(gmenu2x, "start", gmenu2x->tr["Save"]); buttonBox.add(btn); btn = new IconButton(gmenu2x, "b", gmenu2x->tr["Exit"]); buttonBox.add(btn); } MenuSetting::~MenuSetting() {} void MenuSetting::draw(int y) { gmenu2x->s->write(gmenu2x->font, title, 5, y + gmenu2x->font->getHalfHeight(), VAlignMiddle); } void MenuSetting::handleTS() { buttonBox.handleTS(); } void MenuSetting::adjustInput() {} void MenuSetting::drawSelected(int /*y*/) { buttonBox.paint(5); }
2,109
C++
.cpp
39
52.282051
94
0.534884
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,094
button.cpp
MiyooCFW_gmenu2x/src/button.cpp
#include "button.h" #include "gmenu2x.h" using namespace std; using namespace fastdelegate; Button::Button(Touchscreen &ts, bool doubleClick): ts(ts), action(MakeDelegate(this, &Button::voidAction)), rect((SDL_Rect) { 0, 0, 0, 0 }), doubleClick(doubleClick), lastTick(0) {} uint16_t Button::paint() { return 0; // if (ts.inRect(rect)) // if (!paintHover()) return 0; } bool Button::paintHover() { return false; } bool Button::isPressed() { return ts.pressed() && ts.inRect(rect); } bool Button::isReleased() { return ts.released() && ts.inRect(rect); } bool Button::handleTS() { if (isReleased()) { if (doubleClick) { int tickNow = SDL_GetTicks(); if (tickNow - lastTick < 400) exec(); lastTick = tickNow; } else { exec(); } return true; } return false; } void Button::exec() { ts.setHandled(); action(); } SDL_Rect Button::getRect() { return rect; } void Button::setSize(int w, int h) { rect.w = w; rect.h = h; } void Button::setPosition(int x, int y) { rect.x = x; rect.y = y; } void Button::setAction(ButtonAction action) { this->action = action; }
1,106
C++
.cpp
52
19.230769
130
0.679463
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
1,534,095
menusettingimage.cpp
MiyooCFW_gmenu2x/src/menusettingimage.cpp
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "menusettingimage.h" #include "gmenu2x.h" #include "utilities.h" using std::string; MenuSettingImage::MenuSettingImage(GMenu2X *gmenu2x, const string &title, const string &description, string *value, const string &filter, const string &startPath, const string &dialogTitle, const string &dialogIcon): MenuSettingFile(gmenu2x, title, description, value, filter, startPath, dialogTitle, dialogIcon) {} void MenuSettingImage::setValue(const string &value) { string skinpath(exe_path() + "/skins/" + gmenu2x->confStr["skin"]); bool inSkinDir = value.substr(0, skinpath.length()) == skinpath; if (!inSkinDir && gmenu2x->confStr["skin"] != "Default") { skinpath = exe_path() + "/skins/Default"; inSkinDir = value.substr(0, skinpath.length()) == skinpath; } *_value = value; if (inSkinDir) { string tempIcon = value.substr(skinpath.length(), value.length()); string::size_type pos = tempIcon.find("/"); if (pos != string::npos) { *_value = "skin:" + tempIcon.substr(pos + 1, value.length()); } } }
2,431
C++
.cpp
41
57.195122
216
0.553459
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,096
iconbutton.h
MiyooCFW_gmenu2x/src/iconbutton.h
#ifndef ICONBUTTON_H #define ICONBUTTON_H #include <string> #include "button.h" using std::string; class GMenu2X; class Surface; class IconButton : public Button { protected: GMenu2X *gmenu2x; int labelPosition, labelMargin; string icon, label; uint16_t labelHAlign, labelVAlign; void recalcSize(); SDL_Rect iconRect, labelRect; Surface *iconSurface; void updateSurfaces(); public: enum icon_button_position { DISP_RIGHT, DISP_LEFT, DISP_TOP, DISP_BOTTOM }; IconButton(GMenu2X *gmenu2x, const string &icon, const string &label=""); virtual ~IconButton() {}; virtual uint16_t paint(); virtual bool paintHover(); virtual void setPosition(int x, int y); const string &getLabel(); void setLabel(const string &label); void setLabelPosition(int pos, int margin); const string &getIcon(); void setIcon(const string &icon); void setAction(ButtonAction action); }; #endif
904
C++
.h
37
22.324324
74
0.77193
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,097
surfacecollection.h
MiyooCFW_gmenu2x/src/surfacecollection.h
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef SURFACECOLLECTION_H #define SURFACECOLLECTION_H #include <string> #include <tr1/unordered_map> class Surface; typedef std::tr1::unordered_map<std::string, Surface *> SurfaceHash; /** Hash Map of surfaces that loads surfaces not already loaded and reuses already loaded ones. @author Massimiliano Torromeo <massimiliano.torromeo@gmail.com> */ class SurfaceCollection { private: SurfaceHash surfaces; std::string skin; public: SurfaceCollection(); void setSkin(const std::string &skin); std::string getSkinFilePath(const std::string &file, bool falback = true); void debug(); Surface *add(Surface *s, const std::string &path); Surface *add(std::string path, std::string key=""); bool del(const std::string &key); void clear(); void move(const std::string &from, const std::string &to); bool exists(const std::string &path); Surface *operator[](const std::string &); }; #endif
2,307
C++
.h
47
47.255319
91
0.561917
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,098
menusettingmultiint.h
MiyooCFW_gmenu2x/src/menusettingmultiint.h
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef MENUSETTINGMULTIINT_H #define MENUSETTINGMULTIINT_H #include "menusetting.h" class MenuSettingMultiInt : public MenuSetting { private: int originalValue; int *_value; std::string strvalue; int def, min, max; int selection_max; int selection; void inc(); void dec(); void inc2x(); void dec2x(); void current(); int *choices; int reverseLookup(int value); public: MenuSettingMultiInt(GMenu2X *gmenu2x, const std::string &title, const std::string &description, int *value, int *choice_pointer, int choice_size, int def, int min, int max); // MenuSettingMultiInt(GMenu2X *gmenu2x, const std::string &title, const std::string &description, int *value, int def, int min, int max); virtual ~MenuSettingMultiInt() {}; virtual uint32_t manageInput(); // virtual void adjustInput(); virtual void draw(int); virtual bool edited(); virtual void setValue(int value, bool readValue); virtual void setDefault(); int value(); }; #endif
2,366
C++
.h
50
45.28
175
0.56418
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,099
menusettingdir.h
MiyooCFW_gmenu2x/src/menusettingdir.h
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef MENUSETTINGDIR_H #define MENUSETTINGDIR_H #include "menusettingstringbase.h" class MenuSettingDir : public MenuSettingStringBase { protected: virtual void edit(); std::string startPath, dialogTitle, dialogIcon; public: MenuSettingDir(GMenu2X *gmenu2x, const std::string &title, const std::string &description, std::string *value, const std::string &startPath = "", const std::string &dialogTitle = "", const std::string &dialogIcon = ""); virtual ~MenuSettingDir() {} }; #endif
1,899
C++
.h
31
59.387097
220
0.521739
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,100
dialog.h
MiyooCFW_gmenu2x/src/dialog.h
#ifndef __DIALOG_H__ #define __DIALOG_H__ #include <string> #include <vector> class GMenu2X; class Surface; typedef std::vector<std::vector<std::string>> buttons_t; class Dialog { public: Dialog(GMenu2X *gmenu2x, const std::string &title = "", const std::string &description = "", const std::string &icon = ""); protected: std::string title, description, icon; ~Dialog(); Surface *bg; GMenu2X *gmenu2x; buttons_t buttons; void drawTopBar(Surface *s, const std::string &title = "", const std::string &description = "", const std::string &icon = ""); void drawBottomBar(Surface *s, buttons_t buttons = {}); void drawDialog(Surface *s, bool top = true, bool bottom = true); }; #endif
699
C++
.h
22
29.954545
127
0.711078
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,101
menusettingrgba.h
MiyooCFW_gmenu2x/src/menusettingrgba.h
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef MENUSETTINGRGBA_H #define MENUSETTINGRGBA_H #include "menusetting.h" #include "surface.h" // class GMenu2X; class MenuSettingRGBA : public MenuSetting { private: uint16_t selPart; int y; std::string strR, strG, strB, strA; RGBAColor originalValue; RGBAColor *_value; bool editing = false; void dec(); void inc(); void current(); void leftComponent(); void rightComponent(); public: MenuSettingRGBA(GMenu2X *gmenu2x, const std::string &title, const std::string &description, RGBAColor *value); virtual ~MenuSettingRGBA() {}; virtual void draw(int y); // virtual void handleTS(); virtual uint32_t manageInput(); virtual void adjustInput(); virtual void drawSelected(int y); virtual bool edited(); void setSelPart(uint16_t value); void setR(uint16_t r); void setG(uint16_t g); void setB(uint16_t b); void setA(uint16_t a); uint16_t getSelPart(); RGBAColor value(); }; #endif
2,318
C++
.h
55
40.2
111
0.559202
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,102
browsedialog.h
MiyooCFW_gmenu2x/src/browsedialog.h
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef BROWSEDIALOG_H_ #define BROWSEDIALOG_H_ #include <string> #include "gmenu2x.h" #include "dialog.h" #include "filelister.h" #include "menu.h" class FileLister; using std::string; class BrowseDialog : protected Dialog, public FileLister { protected: virtual void onChangeDir() {}; private: bool ts_pressed; virtual const std::string getPreview(uint32_t i = 0); vector<int> browse_history; void contextMenu(); void deleteFile(); void umountDir(); void exploreHome(); void exploreMedia(); void setWallpaper(); public: BrowseDialog(GMenu2X *gmenu2x, const string &title, const string &description, const string &icon = "icons/explorer.png"); virtual ~BrowseDialog() {}; bool allowSelectDirectory = false, allowEnterDirectory = true; int32_t selected = 0; bool exec(); void directoryEnter(const string &path); virtual const std::string getFileName(uint32_t i = 0); virtual const std::string getParams(uint32_t i = 0); virtual void customOptions(vector<MenuOption> &options) { return; }; }; #endif /*BROWSEDIALOG_H_*/
2,452
C++
.h
53
44.377358
123
0.573462
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,103
button.h
MiyooCFW_gmenu2x/src/button.h
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef BUTTON_H_ #define BUTTON_H_ #include <string> #include <SDL.h> #include "FastDelegate.h" using std::string; using fastdelegate::FastDelegate0; typedef FastDelegate0<> ButtonAction; class Touchscreen; class Button { private: Touchscreen &ts; protected: ButtonAction action; SDL_Rect rect; bool doubleClick; int lastTick; public: Button(Touchscreen &ts, bool doubleClick = false); virtual ~Button() {}; SDL_Rect getRect(); void setSize(int w, int h); virtual void setPosition(int x, int y); virtual uint16_t paint(); virtual bool paintHover(); bool isPressed(); bool isReleased(); bool handleTS(); void exec(); void voidAction() {}; void setAction(ButtonAction action); }; #endif /*BUTTON_H_*/
2,134
C++
.h
52
39.115385
77
0.542995
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,104
buttonbox.h
MiyooCFW_gmenu2x/src/buttonbox.h
#ifndef __BUTTONBOX_H__ #define __BUTTONBOX_H__ #include <vector> #include <cstdint> class GMenu2X; class Button; class ButtonBox { public: ButtonBox(GMenu2X *gmenu2x); ~ButtonBox(); void add(Button *button); void remove(uint32_t n); void paint(uint32_t posX); void handleTS(); private: typedef std::vector<Button*> ButtonList; ButtonList buttons; GMenu2X *gmenu2x; }; #endif
392
C++
.h
21
16.904762
41
0.763736
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,105
messagebox.h
MiyooCFW_gmenu2x/src/messagebox.h
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef MESSAGEBOX_H_ #define MESSAGEBOX_H_ #include <string> #include "gmenu2x.h" using std::string; using std::vector; enum { MB_BTN_B, MB_BTN_X, MB_BTN_START, MB_BTN_SELECT }; class MessageBox { private: string text, icon; uint32_t autohide = 0, bgalpha = 200; GMenu2X *gmenu2x; vector<string> button; vector<string> buttonText; vector<SDL_Rect> buttonPosition; public: MessageBox(GMenu2X *gmenu2x, vector<MenuOption> options); MessageBox(GMenu2X *gmenu2x, const string &text, const string &icon = ""); ~MessageBox(); void setButton(int action, const string &btn); void setAutoHide(uint32_t delay); void setBgAlpha(uint32_t bgalpha); int exec(); bool loophide = false; void exec(uint32_t timeOut); void clearTimer(); static uint32_t execTimer(uint32_t interval, void *param); SDL_TimerID popupTimer; }; #endif /*MESSAGEBOX_H_*/
2,265
C++
.h
54
40.055556
77
0.554698
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,106
inputmanager.h
MiyooCFW_gmenu2x/src/inputmanager.h
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef INPUTMANAGER_H #define INPUTMANAGER_H enum actions { WAKE_UP, UP, DOWN, LEFT, RIGHT, CONFIRM, CANCEL, MANUAL, MODIFIER, SECTION_PREV, SECTION_NEXT, INC, DEC, PAGEUP, PAGEDOWN, SETTINGS, MENU, VOLUP, VOLDOWN, BACKLIGHT, POWER, UDC_CONNECT, // = NUM_ACTIONS, UDC_REMOVE, MMC_INSERT, MMC_REMOVE, TV_CONNECT, TV_REMOVE, PHONES_CONNECT, PHONES_REMOVE, JOYSTICK_CONNECT, JOYSTICK_REMOVE, SCREENSHOT, NUM_ACTIONS }; enum hat_actions { DUP, DDOWN, DLEFT, DRIGHT }; #define VOLUME_HOTKEY SECTION_PREV #define BACKLIGHT_HOTKEY SECTION_NEXT #include <SDL.h> #include <vector> #include <string> using std::vector; using std::string; typedef struct { int type; uint32_t num; int value; int treshold; } InputMap; typedef vector<InputMap> MappingList; typedef struct { bool active; int interval; MappingList maplist; } InputManagerAction; class InputManager { private: InputMap getInputMapping(int action); vector <SDL_Joystick*> joysticks; vector <InputManagerAction> actions; bool up = false, down = false, left = false, right = false; const char konami[10] = {UP, UP, DOWN, DOWN, LEFT, RIGHT, LEFT, RIGHT, CANCEL, CONFIRM}; // eegg char input_combo[10] = {POWER}; // eegg public: static uint32_t wakeUp(uint32_t interval, void *repeat); InputManager(); ~InputManager(); void init(const string &conffile); void initJoysticks(bool reinit = false); bool update(bool wait = true); bool combo(); int hatEvent(int hat_action); void dropEvents(bool drop_timer = true); static void pushEvent(int action); int count(); void setActionsCount(int count); void setInterval(int ms, int action = -1); bool &operator[](int action); bool isActive(int action); }; #endif
3,119
C++
.h
92
32
97
0.608898
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,107
touchscreen.h
MiyooCFW_gmenu2x/src/touchscreen.h
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef TOUCHSCREEN_H #define TOUCHSCREEN_H #include <SDL.h> #include <fcntl.h> #include <cstdint> typedef struct { uint16_t pressure; uint16_t x; uint16_t y; uint16_t pad; struct timeval stamp; } TS_EVENT; class Touchscreen { private: int wm97xx; bool calibrated, _handled; TS_EVENT event; int calibX, calibY; int x, y, startX, startY; bool wasPressed; void calibrate(/*TS_EVENT event*/); public: Touchscreen(); ~Touchscreen(); bool init(); bool initialized(); void deinit(); bool poll(); bool pressed(); bool released(); bool handled(); void setHandled(); bool inRect(SDL_Rect r); bool inRect(int x, int y, int w, int h); bool startedInRect(SDL_Rect r); bool startedInRect(int x, int y, int w, int h); int getX() { return x; } int getY() { return y; } }; #endif
2,209
C++
.h
59
35.440678
77
0.534862
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,108
link.h
MiyooCFW_gmenu2x/src/link.h
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef LINK_H #define LINK_H #include <string> // #include <iostream> #include "button.h" #include "surface.h" // linkaction #include "FastDelegate.h" using namespace fastdelegate; typedef FastDelegate0<> LinkAction; using std::string; class GMenu2X; /** Base class that represents a link on screen. @author Massimiliano Torromeo <massimiliano.torromeo@gmail.com> */ class Link : public Button { private: uint32_t padding = 4; LinkAction action; protected: GMenu2X *gmenu2x; bool edited = false, is_opk = false; string exec = "", title = "", description = "", icon = "", iconPath = "", backdrop = "", backdropPath = "", backdropPathGeneric = ""; public: // linkaction Link(GMenu2X *gmenu2x, LinkAction action); virtual ~Link() {}; const string &getTitle() { return title; } void setTitle(const string &title); const string &getDescription() { return description; } void setDescription(const string &description); const string &getIcon(); void setIcon(const string &icon); virtual const string searchIcon(); const string &getIconPath(); void setIconPath(const string &icon); void setBackdrop(const string &backdrop); const string &getBackdrop() { return backdrop; } const string &getBackdropPath() { return backdropPath; } bool isOPK() { return is_opk; } virtual void run(); }; #endif
2,751
C++
.h
71
36.619718
77
0.579737
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,109
menusettingdatetime.h
MiyooCFW_gmenu2x/src/menusettingdatetime.h
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef MENUSETTINGDATETIME_H #define MENUSETTINGDATETIME_H #include "menusetting.h" #include "surface.h" class GMenu2X; class MenuSettingDateTime : public MenuSetting { private: uint16_t selPart; int y; std::string month, day, year, hour, minute, *_value, originalValue; int imonth, iday, iyear, ihour, iminute; bool editing = false; void dec(); void inc(); void current(); void leftComponent(); void rightComponent(); public: MenuSettingDateTime(GMenu2X *gmenu2x, const std::string &title, const std::string &description, std::string *value); virtual ~MenuSettingDateTime() {}; virtual void draw(int y); virtual uint32_t manageInput(); virtual void drawSelected(int y); virtual bool edited(); void setSelPart(uint16_t i); void setYear(int16_t i); void setMonth(int16_t i); void setDay(int16_t i); void setHour(int16_t i); void setMinute(int16_t i); uint16_t getSelPart(); string value(); }; #endif
2,337
C++
.h
53
42.132075
117
0.562198
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,110
linkapp.h
MiyooCFW_gmenu2x/src/linkapp.h
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef LINKAPP_H #define LINKAPP_H #include <string> #include "link.h" using std::string; /** Parses links files. @author Massimiliano Torromeo <massimiliano.torromeo@gmail.com> */ class LinkApp : public Link { private: // InputManager &input; int clock = 0, layout = 0, tefix = -1, selectorelement = 0, scalemode, _scalemode = 0; //, ivolume = 0; bool selectorbrowser = true, terminal = false; string params = "", homedir = "", manual = "", manualPath = "", selectordir = "", selectorfilter = "", selectorscreens = "", aliasfile = "", file = "", icon_opk = ""; public: LinkApp(GMenu2X *gmenu2x, const char* file); const string &getExec() { return exec; } void setExec(const string &exec); const string &getParams() { return params; } void setParams(const string &params); const string &getHomeDir() { return homedir; } void setHomeDir(const string &homedir); const string &getManual() { return manual; } const string &getManualPath() { return manualPath; } void setManual(const string &manual); const string &getSelectorDir() { return selectordir; } void setSelectorDir(const string &selectordir); bool getSelectorBrowser() { return selectorbrowser; } void setSelectorBrowser(bool value); bool getTerminal() { return terminal; } void setTerminal(bool value); int getScaleMode() { return scalemode; } void setScaleMode(int value); const string &getSelectorScreens() { return selectorscreens; } void setSelectorScreens(const string &selectorscreens); const string &getSelectorFilter() { return selectorfilter; } void setSelectorFilter(const string &selectorfilter); int getSelectorElement() { return selectorelement; } void setSelectorElement(int i); const string &getAliasFile() { return aliasfile; } void setAliasFile(const string &aliasfile); int getCPU() { return clock; } void setCPU(int mhz = 0); int getKbdLayout() { return layout; } void setKbdLayout(int val = 0); int getTefix() { return tefix; } void setTefix(int val = -1); bool save(); void run(); void selector(int startSelection = 0, const string &selectorDir = ""); void launch(const string &selectedFile = "", string selectedDir = ""); bool targetExists(); void renameFile(const string &name); const string &getFile() { return file; } #if defined(TARGET_GP2X) // int volume(); // const string &volumeStr(); // void setVolume(int vol); // bool getUseRamTimings() { return useRamTimings; } // void setUseRamTimings(bool value); // bool getUseGinge() { return useGinge; } // void setUseGinge(bool value); // const string &clockStr(int maxClock); // string sgamma; #endif #if defined(HW_GAMMA) int gamma; int getGamma() { return gamma; } void setGamma(int gamma); // const string &gammaStr(); // bool &needsWrapperRef() { return wrapper; } // bool &runsInBackgroundRef() { return dontleave; } #endif const string searchIcon(); const string searchBackdrop(); const string searchManual(); }; #endif
4,382
C++
.h
113
36.575221
77
0.631369
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,111
menusettingstring.h
MiyooCFW_gmenu2x/src/menusettingstring.h
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef MENUSETTINGSTRING_H #define MENUSETTINGSTRING_H #include "menusettingstringbase.h" class MenuSettingString : public MenuSettingStringBase { protected: virtual void edit(); std::string dialogTitle, dialogIcon; public: MenuSettingString(GMenu2X *gmenu2x, const std::string &title, const std::string &description, std::string *value, const std::string &dialogTitle = "", const std::string &dialogIcon = ""); virtual ~MenuSettingString() {} }; #endif
1,889
C++
.h
34
53.147059
77
0.516216
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,534,112
wallpaperdialog.h
MiyooCFW_gmenu2x/src/wallpaperdialog.h
/*************************************************************************** * Copyright (C) 2006 by Massimiliano Torromeo * * massimiliano.torromeo@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 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., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef WALLPAPERDIALOG_H_ #define WALLPAPERDIALOG_H_ #include <string> #include "gmenu2x.h" #include "dialog.h" using std::string; using std::vector; class WallpaperDialog : protected Dialog { public: WallpaperDialog(GMenu2X *gmenu2x, const string &title, const string &description, const string &icon); ~WallpaperDialog(); string wallpaper; vector<string> wallpapers; bool exec(); }; #endif /*WALLPAPERDIALOG_H_*/
1,832
C++
.h
35
50.485714
103
0.513966
MiyooCFW/gmenu2x
30
27
9
GPL-2.0
9/20/2024, 10:44:02 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false