diff --git a/Source/Collection/CollectionInfo.cpp b/Source/Collection/CollectionInfo.cpp index 3a47d7b..d6191c8 100644 --- a/Source/Collection/CollectionInfo.cpp +++ b/Source/Collection/CollectionInfo.cpp @@ -1,20 +1,20 @@ -/* This file is subject to the terms and conditions defined in - * file 'LICENSE.txt', which is part of this source code package. +/* This file is subject to the terms and conditions defined in + * file 'LICENSE.txt', which is part of this source code package. */ #include "CollectionInfo.h" #include "../Database/Configuration.h" #include -CollectionInfo::CollectionInfo(std::string name, - std::string listPath, - std::string extensions, - std::string metadataType, +CollectionInfo::CollectionInfo(std::string name, + std::string listPath, + std::string extensions, + std::string metadataType, std::string metadataPath) -: Name(name) -, ListPath(listPath) -, Extensions(extensions) -, MetadataType(metadataType) -, MetadataPath(metadataPath) + : Name(name) + , ListPath(listPath) + , Extensions(extensions) + , MetadataType(metadataType) + , MetadataPath(metadataPath) { } @@ -24,43 +24,43 @@ CollectionInfo::~CollectionInfo() std::string CollectionInfo::GetName() const { - return Name; + return Name; } std::string CollectionInfo::GetSettingsPath() const { - return Configuration::GetAbsolutePath() + "/Collections/" + GetName(); + return Configuration::GetAbsolutePath() + "/Collections/" + GetName(); } std::string CollectionInfo::GetListPath() const { - return ListPath; + return ListPath; } std::string CollectionInfo::GetMetadataType() const { - return MetadataType; + return MetadataType; } std::string CollectionInfo::GetMetadataPath() const { - return MetadataPath; + return MetadataPath; } std::string CollectionInfo::GetExtensions() const { - return Extensions; + return Extensions; } void CollectionInfo::GetExtensions(std::vector &extensions) { - std::istringstream ss(Extensions); - std::string token; + std::istringstream ss(Extensions); + std::string token; - while(std::getline(ss, token, ',')) - { - extensions.push_back(token); - } + while(std::getline(ss, token, ',')) + { + extensions.push_back(token); + } } diff --git a/Source/Collection/CollectionInfo.h b/Source/Collection/CollectionInfo.h index 6bfaa1f..9f5750e 100644 --- a/Source/Collection/CollectionInfo.h +++ b/Source/Collection/CollectionInfo.h @@ -1,5 +1,5 @@ -/* This file is subject to the terms and conditions defined in - * file 'LICENSE.txt', which is part of this source code package. +/* This file is subject to the terms and conditions defined in + * file 'LICENSE.txt', which is part of this source code package. */ #pragma once @@ -9,20 +9,20 @@ class CollectionInfo { public: - CollectionInfo(std::string name, std::string listPath, std::string extensions, std::string metadataType, std::string metadataPath); - virtual ~CollectionInfo(); - std::string GetName() const; - std::string GetSettingsPath() const; - std::string GetListPath() const; - std::string GetMetadataType() const; - std::string GetMetadataPath() const; - std::string GetExtensions() const; - void GetExtensions(std::vector &extensions); + CollectionInfo(std::string name, std::string listPath, std::string extensions, std::string metadataType, std::string metadataPath); + virtual ~CollectionInfo(); + std::string GetName() const; + std::string GetSettingsPath() const; + std::string GetListPath() const; + std::string GetMetadataType() const; + std::string GetMetadataPath() const; + std::string GetExtensions() const; + void GetExtensions(std::vector &extensions); private: - std::string Name; - std::string ListPath; - std::string Extensions; - std::string MetadataType; - std::string MetadataPath; + std::string Name; + std::string ListPath; + std::string Extensions; + std::string MetadataType; + std::string MetadataPath; }; diff --git a/Source/Collection/CollectionInfoBuilder.cpp b/Source/Collection/CollectionInfoBuilder.cpp index a8c389e..2176667 100644 --- a/Source/Collection/CollectionInfoBuilder.cpp +++ b/Source/Collection/CollectionInfoBuilder.cpp @@ -6,121 +6,121 @@ #include CollectionInfoBuilder::CollectionInfoBuilder(Configuration *c) -: Conf(c) + : Conf(c) { } CollectionInfoBuilder::~CollectionInfoBuilder() { - std::map::iterator it = InfoMap.begin(); + std::map::iterator it = InfoMap.begin(); - for(it == InfoMap.begin(); it != InfoMap.end(); ++it) - { - delete it->second; - } + for(it == InfoMap.begin(); it != InfoMap.end(); ++it) + { + delete it->second; + } - InfoMap.clear(); + InfoMap.clear(); } bool CollectionInfoBuilder::LoadAllCollections() { - std::vector collections; + std::vector collections; - Conf->GetChildKeyCrumbs("collections", collections); + Conf->GetChildKeyCrumbs("collections", collections); - if(collections.size() == 0) - { - Logger::Write(Logger::ZONE_ERROR, "Collections", "No collections were found. Please configure Settings.conf"); - return false; - } + if(collections.size() == 0) + { + Logger::Write(Logger::ZONE_ERROR, "Collections", "No collections were found. Please configure Settings.conf"); + return false; + } - bool retVal = true; - std::vector::iterator it; + bool retVal = true; + std::vector::iterator it; - for(it = collections.begin(); it != collections.end(); ++it) - { - // todo: There is nothing that should really stop us from creating a collection - // in the main folder. I just need to find some time to look at the impacts if - // I remove this conditional check. - if(*it != "Main") - { - if(ImportCollection(*it)) - { - Logger::Write(Logger::ZONE_INFO, "Collections", "Adding collection " + *it); - } - else - { - // Continue processing the rest of the collections if an error occurs during import. - // ImportCollection() will print out an error to the log file. - retVal = false; - } - } - } + for(it = collections.begin(); it != collections.end(); ++it) + { + // todo: There is nothing that should really stop us from creating a collection + // in the main folder. I just need to find some time to look at the impacts if + // I remove this conditional check. + if(*it != "Main") + { + if(ImportCollection(*it)) + { + Logger::Write(Logger::ZONE_INFO, "Collections", "Adding collection " + *it); + } + else + { + // Continue processing the rest of the collections if an error occurs during import. + // ImportCollection() will print out an error to the log file. + retVal = false; + } + } + } - return retVal; + return retVal; } void CollectionInfoBuilder::GetCollections(std::vector &collections) { - std::map::iterator InfoMapIt; + std::map::iterator InfoMapIt; - for(InfoMapIt = InfoMap.begin(); InfoMapIt != InfoMap.end(); ++InfoMapIt) - { - collections.push_back(InfoMapIt->second); - } + for(InfoMapIt = InfoMap.begin(); InfoMapIt != InfoMap.end(); ++InfoMapIt) + { + collections.push_back(InfoMapIt->second); + } } bool CollectionInfoBuilder::ImportCollection(std::string name) { - // create a new instance if one does not exist - if(InfoMap.find(name) != InfoMap.end()) - { - return true; - } - std::string listItemsPathKey = "collections." + name + ".list.path"; - std::string listFilterKey = "collections." + name + ".list.filter"; - std::string extensionsKey = "collections." + name + ".list.extensions"; - std::string launcherKey = "collections." + name + ".launcher"; + // create a new instance if one does not exist + if(InfoMap.find(name) != InfoMap.end()) + { + return true; + } + std::string listItemsPathKey = "collections." + name + ".list.path"; + std::string listFilterKey = "collections." + name + ".list.filter"; + std::string extensionsKey = "collections." + name + ".list.extensions"; + std::string launcherKey = "collections." + name + ".launcher"; - //todo: metadata is not fully not implemented - std::string metadataTypeKey = "collections." + name + ".metadata.type"; - std::string metadataPathKey = "collections." + name + ".metadata.path"; + //todo: metadata is not fully not implemented + std::string metadataTypeKey = "collections." + name + ".metadata.type"; + std::string metadataPathKey = "collections." + name + ".metadata.path"; - std::string listItemsPath; - std::string launcherName; - std::string extensions; - std::string metadataType; - std::string metadataPath; + std::string listItemsPath; + std::string launcherName; + std::string extensions; + std::string metadataType; + std::string metadataPath; - if(!Conf->GetPropertyAbsolutePath(listItemsPathKey, listItemsPath)) - { - Logger::Write(Logger::ZONE_INFO, "Collections", "Property \"" + listItemsPathKey + "\" does not exist. Assuming \"" + name + "\" is a menu"); - return false; - } + if(!Conf->GetPropertyAbsolutePath(listItemsPathKey, listItemsPath)) + { + Logger::Write(Logger::ZONE_INFO, "Collections", "Property \"" + listItemsPathKey + "\" does not exist. Assuming \"" + name + "\" is a menu"); + return false; + } - if(!Conf->GetProperty(extensionsKey, extensions)) - { - Logger::Write(Logger::ZONE_INFO, "Collections", "Property \"" + extensionsKey + "\" does not exist. Assuming \"" + name + "\" is a menu"); - return false; - } + if(!Conf->GetProperty(extensionsKey, extensions)) + { + Logger::Write(Logger::ZONE_INFO, "Collections", "Property \"" + extensionsKey + "\" does not exist. Assuming \"" + name + "\" is a menu"); + return false; + } - (void)Conf->GetProperty(metadataTypeKey, metadataType); - (void)Conf->GetProperty(metadataPathKey, metadataPath); + (void)Conf->GetProperty(metadataTypeKey, metadataType); + (void)Conf->GetProperty(metadataPathKey, metadataPath); - if(!Conf->GetProperty(launcherKey, launcherName)) - { - std::stringstream ss; - ss << "Warning: launcher property \"" - << launcherKey - << "\" points to a launcher that is not configured (launchers." - << launcherName - << "). Your collection will be viewable, however you will not be able to " - << "launch any of the items in your collection."; + if(!Conf->GetProperty(launcherKey, launcherName)) + { + std::stringstream ss; + ss << "Warning: launcher property \"" + << launcherKey + << "\" points to a launcher that is not configured (launchers." + << launcherName + << "). Your collection will be viewable, however you will not be able to " + << "launch any of the items in your collection."; - Logger::Write(Logger::ZONE_WARNING, "Collections", ss.str()); - } + Logger::Write(Logger::ZONE_WARNING, "Collections", ss.str()); + } - InfoMap[name] = new CollectionInfo(name, listItemsPath, extensions, metadataType, metadataPath); + InfoMap[name] = new CollectionInfo(name, listItemsPath, extensions, metadataType, metadataPath); - return (InfoMap[name] != NULL); + return (InfoMap[name] != NULL); } diff --git a/Source/Collection/CollectionInfoBuilder.h b/Source/Collection/CollectionInfoBuilder.h index eb438bb..efba4e3 100644 --- a/Source/Collection/CollectionInfoBuilder.h +++ b/Source/Collection/CollectionInfoBuilder.h @@ -1,5 +1,5 @@ -/* This file is subject to the terms and conditions defined in - * file 'LICENSE.txt', which is part of this source code package. +/* This file is subject to the terms and conditions defined in + * file 'LICENSE.txt', which is part of this source code package. */ #pragma once @@ -13,13 +13,13 @@ class CollectionInfo; class CollectionInfoBuilder { public: - CollectionInfoBuilder(Configuration *c); - virtual ~CollectionInfoBuilder(); - bool LoadAllCollections(); - void GetCollections(std::vector &keys); + CollectionInfoBuilder(Configuration *c); + virtual ~CollectionInfoBuilder(); + bool LoadAllCollections(); + void GetCollections(std::vector &keys); private: - bool ImportCollection(std::string name); - std::map InfoMap; - Configuration *Conf; + bool ImportCollection(std::string name); + std::map InfoMap; + Configuration *Conf; }; diff --git a/Source/Collection/Item.cpp b/Source/Collection/Item.cpp index 61b9000..78bcd48 100644 --- a/Source/Collection/Item.cpp +++ b/Source/Collection/Item.cpp @@ -1,5 +1,5 @@ -/* This file is subject to the terms and conditions defined in - * file 'LICENSE.txt', which is part of this source code package. +/* This file is subject to the terms and conditions defined in + * file 'LICENSE.txt', which is part of this source code package. */ #include "Item.h" #include "../Utility/Utils.h" @@ -7,9 +7,9 @@ #include Item::Item() -: NumberPlayers(0) -, NumberButtons(0) -, Leaf(true) + : NumberPlayers(0) + , NumberButtons(0) + , Leaf(true) { } @@ -19,142 +19,148 @@ Item::~Item() const std::string Item::GetFileName() const { - return Utils::GetFileName(FilePath); + return Utils::GetFileName(FilePath); } const std::string& Item::GetFilePath() const { - return FilePath; + return FilePath; } void Item::SetFilePath(const std::string& filepath) { - FilePath = filepath; + FilePath = filepath; } const std::string& Item::GetLauncher() const { - return Launcher; + return Launcher; } void Item::SetLauncher(const std::string& launcher) { - Launcher = launcher; + Launcher = launcher; } const std::string& Item::GetManufacturer() const { - return Manufacturer; + return Manufacturer; } void Item::SetManufacturer(const std::string& manufacturer) { - Manufacturer = manufacturer; + Manufacturer = manufacturer; } const std::string& Item::GetName() const { - return Name; + return Name; } void Item::SetName(const std::string& name) { - Name = name; + Name = name; } int Item::GetNumberButtons() const { - return NumberButtons; + return NumberButtons; } std::string Item::GetNumberButtonsString() { - std::stringstream ss; - ss << NumberButtons; - return ss.str(); + std::stringstream ss; + ss << NumberButtons; + return ss.str(); } void Item::SetNumberButtons(int numberbuttons) { - NumberButtons = numberbuttons; + NumberButtons = numberbuttons; } int Item::GetNumberPlayers() const { - return NumberPlayers; + return NumberPlayers; } std::string Item::GetNumberPlayersString() { - std::stringstream ss; - ss << NumberButtons; - return ss.str(); + std::stringstream ss; + ss << NumberButtons; + return ss.str(); } void Item::SetNumberPlayers(int numberplayers) { - NumberPlayers = numberplayers; + NumberPlayers = numberplayers; } const std::string& Item::GetTitle() const { - return Title; + return Title; } const std::string& Item::GetLCTitle() const { - return LCTitle; + return LCTitle; } void Item::SetTitle(const std::string& title) { - Title = title; - LCTitle = Title; - std::transform(LCTitle.begin(), LCTitle.end(), LCTitle.begin(), ::tolower); + Title = title; + LCTitle = Title; + std::transform(LCTitle.begin(), LCTitle.end(), LCTitle.begin(), ::tolower); } const std::string& Item::GetYear() const { - return Year; + return Year; } void Item::SetYear(const std::string& year) { - Year = year; + Year = year; } bool Item::IsLeaf() const { - return Leaf; + return Leaf; } void Item::SetIsLeaf(bool leaf) { - Leaf = leaf; + Leaf = leaf; } const std::string& Item::GetFullTitle() const { - return FullTitle; + return FullTitle; } void Item::SetFullTitle(const std::string& fulltitle) { - FullTitle = fulltitle; + FullTitle = fulltitle; } const std::string& Item::GetCloneOf() const { - return CloneOf; + return CloneOf; } void Item::SetCloneOf(const std::string& cloneOf) { - CloneOf = cloneOf; + CloneOf = cloneOf; } -bool Item::operator<(const Item &rhs) { return LCTitle < rhs.LCTitle; } -bool Item::operator>(const Item &rhs) { return LCTitle > rhs.LCTitle; } +bool Item::operator<(const Item &rhs) +{ + return LCTitle < rhs.LCTitle; +} +bool Item::operator>(const Item &rhs) +{ + return LCTitle > rhs.LCTitle; +} diff --git a/Source/Collection/Item.h b/Source/Collection/Item.h index 856041f..2109c8e 100644 --- a/Source/Collection/Item.h +++ b/Source/Collection/Item.h @@ -1,5 +1,5 @@ -/* This file is subject to the terms and conditions defined in - * file 'LICENSE.txt', which is part of this source code package. +/* This file is subject to the terms and conditions defined in + * file 'LICENSE.txt', which is part of this source code package. */ #pragma once @@ -8,49 +8,49 @@ class Item { public: - Item(); - virtual ~Item(); - const std::string GetFileName() const; - const std::string& GetFilePath() const; - void SetFilePath(const std::string& filepath); - const std::string& GetLauncher() const; - void SetLauncher(const std::string& launcher); - const std::string& GetManufacturer() const; - void SetManufacturer(const std::string& manufacturer); - const std::string& GetName() const; - void SetName(const std::string& name); - int GetNumberButtons() const; - std::string GetNumberButtonsString(); - void SetNumberButtons(int numberbuttons); - void SetNumberPlayers(int numberplayers); - int GetNumberPlayers() const; - std::string GetNumberPlayersString(); - const std::string& GetTitle() const; - const std::string& GetLCTitle() const; - void SetTitle(const std::string& title); - const std::string& GetYear() const; - void SetYear(const std::string& year); - bool IsLeaf() const; - void SetIsLeaf(bool leaf); - const std::string& GetFullTitle() const; - void SetFullTitle(const std::string& fulltitle); - const std::string& GetCloneOf() const; - void SetCloneOf(const std::string& cloneOf); - bool operator<(const Item& rhs); - bool operator>(const Item& rhs); + Item(); + virtual ~Item(); + const std::string GetFileName() const; + const std::string& GetFilePath() const; + void SetFilePath(const std::string& filepath); + const std::string& GetLauncher() const; + void SetLauncher(const std::string& launcher); + const std::string& GetManufacturer() const; + void SetManufacturer(const std::string& manufacturer); + const std::string& GetName() const; + void SetName(const std::string& name); + int GetNumberButtons() const; + std::string GetNumberButtonsString(); + void SetNumberButtons(int numberbuttons); + void SetNumberPlayers(int numberplayers); + int GetNumberPlayers() const; + std::string GetNumberPlayersString(); + const std::string& GetTitle() const; + const std::string& GetLCTitle() const; + void SetTitle(const std::string& title); + const std::string& GetYear() const; + void SetYear(const std::string& year); + bool IsLeaf() const; + void SetIsLeaf(bool leaf); + const std::string& GetFullTitle() const; + void SetFullTitle(const std::string& fulltitle); + const std::string& GetCloneOf() const; + void SetCloneOf(const std::string& cloneOf); + bool operator<(const Item& rhs); + bool operator>(const Item& rhs); private: - std::string Launcher; - std::string FilePath; - std::string Name; - std::string Title; - std::string LCTitle; - std::string FullTitle; - std::string Year; - std::string Manufacturer; - std::string CloneOf; - int NumberPlayers; - int NumberButtons; - bool Leaf; + std::string Launcher; + std::string FilePath; + std::string Name; + std::string Title; + std::string LCTitle; + std::string FullTitle; + std::string Year; + std::string Manufacturer; + std::string CloneOf; + int NumberPlayers; + int NumberButtons; + bool Leaf; }; diff --git a/Source/Collection/MenuParser.cpp b/Source/Collection/MenuParser.cpp index 5554b2d..dc601f7 100644 --- a/Source/Collection/MenuParser.cpp +++ b/Source/Collection/MenuParser.cpp @@ -1,5 +1,5 @@ -/* This file is subject to the terms and conditions defined in - * file 'LICENSE.txt', which is part of this source code package. +/* This file is subject to the terms and conditions defined in + * file 'LICENSE.txt', which is part of this source code package. */ #include "MenuParser.h" #include "Item.h" @@ -14,7 +14,7 @@ bool VectorSort(const Item *d1, const Item *d2) { - return d1->GetLCTitle() < d2->GetLCTitle(); + return d1->GetLCTitle() < d2->GetLCTitle(); } MenuParser::MenuParser() @@ -28,81 +28,81 @@ MenuParser::~MenuParser() //todo: clean up this method, too much nesting bool MenuParser::GetMenuItems(CollectionDatabase *cdb, std::string collectionName, std::vector &items) { - bool retVal = false; - //todo: magic string - std::string menuFilename = Configuration::GetAbsolutePath() + "/Collections/" + collectionName + "/Menu.xml"; - rapidxml::xml_document<> doc; - rapidxml::xml_node<> * rootNode; + bool retVal = false; + //todo: magic string + std::string menuFilename = Configuration::GetAbsolutePath() + "/Collections/" + collectionName + "/Menu.xml"; + rapidxml::xml_document<> doc; + rapidxml::xml_node<> * rootNode; - Logger::Write(Logger::ZONE_INFO, "Menu", "Checking if menu exists at \"" + menuFilename + "\""); + Logger::Write(Logger::ZONE_INFO, "Menu", "Checking if menu exists at \"" + menuFilename + "\""); - try - { - std::ifstream file(menuFilename.c_str()); + try + { + std::ifstream file(menuFilename.c_str()); - // gracefully exit if there is no menu file for the pa - if(file.good()) - { - Logger::Write(Logger::ZONE_INFO, "Menu", "Found menu"); - std::vector buffer((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + // gracefully exit if there is no menu file for the pa + if(file.good()) + { + Logger::Write(Logger::ZONE_INFO, "Menu", "Found menu"); + std::vector buffer((std::istreambuf_iterator(file)), std::istreambuf_iterator()); - buffer.push_back('\0'); + buffer.push_back('\0'); - doc.parse<0>(&buffer[0]); + doc.parse<0>(&buffer[0]); - rootNode = doc.first_node("menu"); + rootNode = doc.first_node("menu"); - for (rapidxml::xml_node<> * itemNode = rootNode->first_node("item"); itemNode; itemNode = itemNode->next_sibling()) - { - rapidxml::xml_attribute<> *collectionAttribute = itemNode->first_attribute("collection"); - rapidxml::xml_attribute<> *importAttribute = itemNode->first_attribute("import"); - - if(!collectionAttribute) + for (rapidxml::xml_node<> * itemNode = rootNode->first_node("item"); itemNode; itemNode = itemNode->next_sibling()) { - retVal = false; - Logger::Write(Logger::ZONE_ERROR, "Menu", "Menu item tag is missing collection attribute"); - break; + rapidxml::xml_attribute<> *collectionAttribute = itemNode->first_attribute("collection"); + rapidxml::xml_attribute<> *importAttribute = itemNode->first_attribute("import"); + + if(!collectionAttribute) + { + retVal = false; + Logger::Write(Logger::ZONE_ERROR, "Menu", "Menu item tag is missing collection attribute"); + break; + } + else + { + //todo: too much nesting! Ack! + std::string import; + if(importAttribute) + { + import = importAttribute->value(); + } + if(import != "true") + { + //todo, check for empty string + std::string title = collectionAttribute->value(); + Item *item = new Item(); + item->SetTitle(title); + item->SetFullTitle(title); + item->SetName(collectionAttribute->value()); + item->SetIsLeaf(false); + items.push_back(item); + } + else + { + std::string collectionName = collectionAttribute->value(); + Logger::Write(Logger::ZONE_INFO, "Menu", "Loading collection into menu: " + collectionName); + cdb->GetCollection(collectionAttribute->value(), items); + } + } } - else - { - //todo: too much nesting! Ack! - std::string import; - if(importAttribute) - { - import = importAttribute->value(); - } - if(import != "true") - { - //todo, check for empty string - std::string title = collectionAttribute->value(); - Item *item = new Item(); - item->SetTitle(title); - item->SetFullTitle(title); - item->SetName(collectionAttribute->value()); - item->SetIsLeaf(false); - items.push_back(item); - } - else - { - std::string collectionName = collectionAttribute->value(); - Logger::Write(Logger::ZONE_INFO, "Menu", "Loading collection into menu: " + collectionName); - cdb->GetCollection(collectionAttribute->value(), items); - } - } - } - std::sort( items.begin(), items.end(), VectorSort); + std::sort( items.begin(), items.end(), VectorSort); - retVal = true; - } - } - catch(std::ifstream::failure &e) - { - std::stringstream ss; - ss << "Unable to open menu file \"" << menuFilename << "\": " << e.what(); - Logger::Write(Logger::ZONE_ERROR, "Menu", ss.str()); - } + retVal = true; + } + } + catch(std::ifstream::failure &e) + { + std::stringstream ss; + ss << "Unable to open menu file \"" << menuFilename << "\": " << e.what(); + Logger::Write(Logger::ZONE_ERROR, "Menu", ss.str()); + } - return retVal; + return retVal; } diff --git a/Source/Collection/MenuParser.h b/Source/Collection/MenuParser.h index 4c15e31..a712149 100644 --- a/Source/Collection/MenuParser.h +++ b/Source/Collection/MenuParser.h @@ -1,5 +1,5 @@ -/* This file is subject to the terms and conditions defined in - * file 'LICENSE.txt', which is part of this source code package. +/* This file is subject to the terms and conditions defined in + * file 'LICENSE.txt', which is part of this source code package. */ #pragma once #include "Item.h" @@ -10,8 +10,8 @@ class CollectionDatabase; class MenuParser { public: - MenuParser(); - virtual ~MenuParser(); - bool GetMenuItems(CollectionDatabase *cdb, std::string collectionName, std::vector &items); + MenuParser(); + virtual ~MenuParser(); + bool GetMenuItems(CollectionDatabase *cdb, std::string collectionName, std::vector &items); }; diff --git a/Source/Control/UserInput.cpp b/Source/Control/UserInput.cpp index a14e2cc..1d19689 100644 --- a/Source/Control/UserInput.cpp +++ b/Source/Control/UserInput.cpp @@ -1,12 +1,12 @@ -/* This file is subject to the terms and conditions defined in - * file 'LICENSE.txt', which is part of this source code package. +/* This file is subject to the terms and conditions defined in + * file 'LICENSE.txt', which is part of this source code package. */ #include "UserInput.h" #include "../Database/Configuration.h" #include "../Utility/Log.h" UserInput::UserInput(Configuration *c) -: Config(c) + : Config(c) { } @@ -16,63 +16,63 @@ UserInput::~UserInput() bool UserInput::Initialize() { - bool retVal = true; + bool retVal = true; - retVal = MapKey("nextItem", KeyCodeNextItem) && retVal; - retVal = MapKey("previousItem", KeyCodePreviousItem) && retVal; - retVal = MapKey("pageDown", KeyCodePageDown) && retVal; - retVal = MapKey("pageUp", KeyCodePageUp) && retVal; - retVal = MapKey("select", KeyCodeSelect) && retVal; - retVal = MapKey("back", KeyCodeBack) && retVal; - retVal = MapKey("quit", KeyCodeQuit) && retVal; - // these features will need to be implemented at a later time + retVal = MapKey("nextItem", KeyCodeNextItem) && retVal; + retVal = MapKey("previousItem", KeyCodePreviousItem) && retVal; + retVal = MapKey("pageDown", KeyCodePageDown) && retVal; + retVal = MapKey("pageUp", KeyCodePageUp) && retVal; + retVal = MapKey("select", KeyCodeSelect) && retVal; + retVal = MapKey("back", KeyCodeBack) && retVal; + retVal = MapKey("quit", KeyCodeQuit) && retVal; + // these features will need to be implemented at a later time // retVal = MapKey("admin", KeyCodeAdminMode) && retVal; // retVal = MapKey("remove", KeyCodeHideItem) && retVal; - return retVal; + return retVal; } SDL_Scancode UserInput::GetScancode(KeyCode_E key) { - SDL_Scancode scancode = SDL_SCANCODE_UNKNOWN; - std::map::iterator it = KeyMap.find(key); + SDL_Scancode scancode = SDL_SCANCODE_UNKNOWN; + std::map::iterator it = KeyMap.find(key); - if(it != KeyMap.end()) - { - scancode = it->second; - } + if(it != KeyMap.end()) + { + scancode = it->second; + } - return scancode; + return scancode; } bool UserInput::MapKey(std::string keyDescription, KeyCode_E key) { - bool retVal = false; - SDL_Scancode scanCode; - std::string description; + bool retVal = false; + SDL_Scancode scanCode; + std::string description; - std::string configKey = "controls." + keyDescription; + std::string configKey = "controls." + keyDescription; - if(!Config->GetProperty(configKey, description)) - { - Logger::Write(Logger::ZONE_ERROR, "Configuration", "Missing property " + configKey); - } - else - { - scanCode = SDL_GetScancodeFromName(description.c_str()); + if(!Config->GetProperty(configKey, description)) + { + Logger::Write(Logger::ZONE_ERROR, "Configuration", "Missing property " + configKey); + } + else + { + scanCode = SDL_GetScancodeFromName(description.c_str()); - if(scanCode == SDL_SCANCODE_UNKNOWN) - { - Logger::Write(Logger::ZONE_ERROR, "Configuration", "Unsupported property value for " + configKey + "(" + description + "). See Documentation/Keycodes.txt for valid inputs"); - } - else - { - KeyMap[key] = scanCode; - retVal = true; - } - } + if(scanCode == SDL_SCANCODE_UNKNOWN) + { + Logger::Write(Logger::ZONE_ERROR, "Configuration", "Unsupported property value for " + configKey + "(" + description + "). See Documentation/Keycodes.txt for valid inputs"); + } + else + { + KeyMap[key] = scanCode; + retVal = true; + } + } - return retVal; + return retVal; } diff --git a/Source/Control/UserInput.h b/Source/Control/UserInput.h index c58b2ad..0ac93b9 100644 --- a/Source/Control/UserInput.h +++ b/Source/Control/UserInput.h @@ -1,5 +1,5 @@ -/* This file is subject to the terms and conditions defined in - * file 'LICENSE.txt', which is part of this source code package. +/* This file is subject to the terms and conditions defined in + * file 'LICENSE.txt', which is part of this source code package. */ #pragma once #include @@ -11,28 +11,28 @@ class Configuration; class UserInput { public: - enum KeyCode_E - { - KeyCodeNextItem, - KeyCodePreviousItem, - KeyCodeSelect, - KeyCodeBack, - KeyCodePageDown, - KeyCodePageUp, - KeyCodeAdminMode, - KeyCodeHideItem, - KeyCodeQuit - }; + enum KeyCode_E + { + KeyCodeNextItem, + KeyCodePreviousItem, + KeyCodeSelect, + KeyCodeBack, + KeyCodePageDown, + KeyCodePageUp, + KeyCodeAdminMode, + KeyCodeHideItem, + KeyCodeQuit + }; - UserInput(Configuration *c); - virtual ~UserInput(); - bool Initialize(); - SDL_Scancode GetScancode(KeyCode_E key); + UserInput(Configuration *c); + virtual ~UserInput(); + bool Initialize(); + SDL_Scancode GetScancode(KeyCode_E key); private: - bool MapKey(std::string keyDescription, KeyCode_E key); - std::map KeyMap; + bool MapKey(std::string keyDescription, KeyCode_E key); + std::map KeyMap; - Configuration *Config; + Configuration *Config; }; diff --git a/Source/Database/CollectionDatabase.cpp b/Source/Database/CollectionDatabase.cpp index ad256c8..d9f0ea0 100644 --- a/Source/Database/CollectionDatabase.cpp +++ b/Source/Database/CollectionDatabase.cpp @@ -24,8 +24,8 @@ #include CollectionDatabase::CollectionDatabase(DB *db, Configuration *c) -: Config(c) -, DBInstance(db) + : Config(c) + , DBInstance(db) { } @@ -36,591 +36,591 @@ CollectionDatabase::~CollectionDatabase() bool CollectionDatabase::ResetDatabase() { - bool retVal = true; - int rc; - char *error = NULL; - sqlite3 *handle = DBInstance->GetHandle(); + bool retVal = true; + int rc; + char *error = NULL; + sqlite3 *handle = DBInstance->GetHandle(); - Logger::Write(Logger::ZONE_INFO, "Database", "Erasing"); + Logger::Write(Logger::ZONE_INFO, "Database", "Erasing"); - std::string sql; - sql.append("DROP TABLE IF EXISTS CollectionItems;"); - sql.append("DROP TABLE IF EXISTS Meta;"); - sql.append("DROP TABLE IF EXISTS Collections;"); + std::string sql; + sql.append("DROP TABLE IF EXISTS CollectionItems;"); + sql.append("DROP TABLE IF EXISTS Meta;"); + sql.append("DROP TABLE IF EXISTS Collections;"); - rc = sqlite3_exec(handle, sql.c_str(), NULL, 0, &error); + rc = sqlite3_exec(handle, sql.c_str(), NULL, 0, &error); - if(rc != SQLITE_OK) - { - std::stringstream ss; - ss << "Unable to create Configurations table. Error: " << error; - Logger::Write(Logger::ZONE_ERROR, "Database", ss.str()); - retVal = false; - } + if(rc != SQLITE_OK) + { + std::stringstream ss; + ss << "Unable to create Configurations table. Error: " << error; + Logger::Write(Logger::ZONE_ERROR, "Database", ss.str()); + retVal = false; + } - return retVal; + return retVal; } bool CollectionDatabase::Initialize() { - int rc; - char *error = NULL; - sqlite3 *handle = DBInstance->GetHandle(); + int rc; + char *error = NULL; + sqlite3 *handle = DBInstance->GetHandle(); - std::string sql; - sql.append("CREATE TABLE IF NOT EXISTS CollectionItems("); - sql.append("collectionName TEXT KEY,"); - sql.append("filePath TEXT NOT NULL DEFAULT '',"); - sql.append("name TEXT NOT NULL DEFAULT '',"); - sql.append("hidden INT NOT NULL DEFAULT 0);"); + std::string sql; + sql.append("CREATE TABLE IF NOT EXISTS CollectionItems("); + sql.append("collectionName TEXT KEY,"); + sql.append("filePath TEXT NOT NULL DEFAULT '',"); + sql.append("name TEXT NOT NULL DEFAULT '',"); + sql.append("hidden INT NOT NULL DEFAULT 0);"); - sql.append("CREATE TABLE IF NOT EXISTS Meta("); - sql.append("collectionName TEXT KEY,"); - sql.append("name TEXT NOT NULL DEFAULT '',"); - sql.append("title TEXT NOT NULL DEFAULT '',"); - sql.append("year TEXT NOT NULL DEFAULT '',"); - sql.append("manufacturer TEXT NOT NULL DEFAULT '',"); - sql.append("cloneOf TEXT NOT NULL DEFAULT '',"); - sql.append("players INTEGER,"); - sql.append("buttons INTEGER);"); - sql.append("CREATE UNIQUE INDEX IF NOT EXISTS MetaUniqueId ON Meta(collectionName, name);"); + sql.append("CREATE TABLE IF NOT EXISTS Meta("); + sql.append("collectionName TEXT KEY,"); + sql.append("name TEXT NOT NULL DEFAULT '',"); + sql.append("title TEXT NOT NULL DEFAULT '',"); + sql.append("year TEXT NOT NULL DEFAULT '',"); + sql.append("manufacturer TEXT NOT NULL DEFAULT '',"); + sql.append("cloneOf TEXT NOT NULL DEFAULT '',"); + sql.append("players INTEGER,"); + sql.append("buttons INTEGER);"); + sql.append("CREATE UNIQUE INDEX IF NOT EXISTS MetaUniqueId ON Meta(collectionName, name);"); - sql.append("CREATE TABLE IF NOT EXISTS Collections("); - sql.append("collectionName TEXT KEY,"); - sql.append("crc32 UNSIGNED INTEGER NOT NULL DEFAULT 0);"); - sql.append("CREATE UNIQUE INDEX IF NOT EXISTS CollectionsUniqueId ON Collections(collectionName);"); + sql.append("CREATE TABLE IF NOT EXISTS Collections("); + sql.append("collectionName TEXT KEY,"); + sql.append("crc32 UNSIGNED INTEGER NOT NULL DEFAULT 0);"); + sql.append("CREATE UNIQUE INDEX IF NOT EXISTS CollectionsUniqueId ON Collections(collectionName);"); - rc = sqlite3_exec(handle, sql.c_str(), NULL, 0, &error); + rc = sqlite3_exec(handle, sql.c_str(), NULL, 0, &error); - if(rc != SQLITE_OK) - { - std::stringstream ss; - ss << "Unable to create Configurations table. Error: " << error; - Logger::Write(Logger::ZONE_ERROR, "Database", ss.str()); + if(rc != SQLITE_OK) + { + std::stringstream ss; + ss << "Unable to create Configurations table. Error: " << error; + Logger::Write(Logger::ZONE_ERROR, "Database", ss.str()); - return false; - } + return false; + } - return true; + return true; } bool CollectionDatabase::Import() { - bool retVal = true; + bool retVal = true; - // should keep allocation here - CollectionInfoBuilder cib(Config); + // should keep allocation here + CollectionInfoBuilder cib(Config); - (void)cib.LoadAllCollections(); + (void)cib.LoadAllCollections(); - std::vector collections; - cib.GetCollections(collections); + std::vector collections; + cib.GetCollections(collections); - std::vector::iterator it; - for(it = collections.begin(); it != collections.end() && retVal; ++it) - { - CollectionInfo *info = *it; - std::string title = info->GetName(); - unsigned long crc32 = CalculateCollectionCrc32(info); + std::vector::iterator it; + for(it = collections.begin(); it != collections.end() && retVal; ++it) + { + CollectionInfo *info = *it; + std::string title = info->GetName(); + unsigned long crc32 = CalculateCollectionCrc32(info); - std::stringstream crcStr; - crcStr << crc32; + std::stringstream crcStr; + crcStr << crc32; - if(title != "Main") - { - if(CollectionChanged(info, crc32)) - { - std::string msg = "Detected collection \"" + title + "\" has changed (new CRC: " + crcStr.str() + "). Rebuilding database for this collection."; - Logger::Write(Logger::ZONE_INFO, "Database", msg); + if(title != "Main") + { + if(CollectionChanged(info, crc32)) + { + std::string msg = "Detected collection \"" + title + "\" has changed (new CRC: " + crcStr.str() + "). Rebuilding database for this collection."; + Logger::Write(Logger::ZONE_INFO, "Database", msg); - (void)ImportDirectory(info, crc32); - retVal = true; - } - else - { - std::stringstream ss; - std::string msg = "Collection \"" + title + "\" has not changed (CRC: " + crcStr.str() + "). Using existing database settings."; - Logger::Write(Logger::ZONE_INFO, "Database", msg); + (void)ImportDirectory(info, crc32); + retVal = true; + } + else + { + std::stringstream ss; + std::string msg = "Collection \"" + title + "\" has not changed (CRC: " + crcStr.str() + "). Using existing database settings."; + Logger::Write(Logger::ZONE_INFO, "Database", msg); - } - } - //std::cout << "Importing collection metadata for " << info->GetFullTitle() << " (collections." << info->GetName() << ")" << std::endl; - //ImportMetadata(info); - } - Logger::Write(Logger::ZONE_INFO, "Database", "COMPLETE"); - Sleep(1000); - return retVal; + } + } + //std::cout << "Importing collection metadata for " << info->GetFullTitle() << " (collections." << info->GetName() << ")" << std::endl; + //ImportMetadata(info); + } + Logger::Write(Logger::ZONE_INFO, "Database", "COMPLETE"); + Sleep(1000); + return retVal; } unsigned long CollectionDatabase::CalculateCollectionCrc32(CollectionInfo *info) { - unsigned long crc = crc32(0L, Z_NULL, 0); + unsigned long crc = crc32(0L, Z_NULL, 0); - // start off by reading all of the contents in the collection configuration folders - std::string settingsFile = info->GetSettingsPath() + "/Settings.conf"; - crc = CrcFile(settingsFile, crc); + // start off by reading all of the contents in the collection configuration folders + std::string settingsFile = info->GetSettingsPath() + "/Settings.conf"; + crc = CrcFile(settingsFile, crc); - std::string includeFile = info->GetSettingsPath() + "/Include.txt"; - crc = CrcFile(includeFile, crc); + std::string includeFile = info->GetSettingsPath() + "/Include.txt"; + crc = CrcFile(includeFile, crc); - std::string excludeFile = info->GetSettingsPath() + "/Exclude.txt"; - crc = CrcFile(excludeFile, crc); + std::string excludeFile = info->GetSettingsPath() + "/Exclude.txt"; + crc = CrcFile(excludeFile, crc); - std::string mamelistFile = info->GetSettingsPath() + "/Mamelist.xml"; - crc = CrcFile(mamelistFile, crc); + std::string mamelistFile = info->GetSettingsPath() + "/Mamelist.xml"; + crc = CrcFile(mamelistFile, crc); - DIR *dp; - struct dirent *dirp; - std::string path = info->GetListPath(); - dp = opendir(path.c_str()); + DIR *dp; + struct dirent *dirp; + std::string path = info->GetListPath(); + dp = opendir(path.c_str()); - if(dp == NULL) - { - Logger::Write(Logger::ZONE_ERROR, "Database", "Could not read directory for caching \"" + info->GetListPath() + "\""); - return crc; - } + if(dp == NULL) + { + Logger::Write(Logger::ZONE_ERROR, "Database", "Could not read directory for caching \"" + info->GetListPath() + "\""); + return crc; + } - std::vector extensions; - info->GetExtensions(extensions); - std::vector::iterator extensionsIt; + std::vector extensions; + info->GetExtensions(extensions); + std::vector::iterator extensionsIt; - // md5sum each filename for the matching extension - while((dirp = readdir(dp)) != NULL) - { - std::string file = dirp->d_name; - for(extensionsIt = extensions.begin(); extensionsIt != extensions.end(); ++extensionsIt) - { - std::string comparator = "." + *extensionsIt; - int start = file.length() - comparator.length() + 1; + // md5sum each filename for the matching extension + while((dirp = readdir(dp)) != NULL) + { + std::string file = dirp->d_name; + for(extensionsIt = extensions.begin(); extensionsIt != extensions.end(); ++extensionsIt) + { + std::string comparator = "." + *extensionsIt; + int start = file.length() - comparator.length() + 1; - if(start >= 0 && file.compare(start, comparator.length(), *extensionsIt) == 0) - { - std::string filename = dirp->d_name; - filename.append("\n"); - crc = crc32(crc, (const unsigned char *)filename.c_str(), (unsigned int)filename.length()); - } - } - } + if(start >= 0 && file.compare(start, comparator.length(), *extensionsIt) == 0) + { + std::string filename = dirp->d_name; + filename.append("\n"); + crc = crc32(crc, (const unsigned char *)filename.c_str(), (unsigned int)filename.length()); + } + } + } - return crc; + return crc; } unsigned long CollectionDatabase::CrcFile(std::string file, unsigned long crc) { - // CRC both the filename and its contents - crc = crc32(crc, (const unsigned char *)file.c_str(), (unsigned int)file.length()); - std::ifstream ifFile(file.c_str()); - if(ifFile.good()) - { - std::stringstream ss; - ss << ifFile.rdbuf(); + // CRC both the filename and its contents + crc = crc32(crc, (const unsigned char *)file.c_str(), (unsigned int)file.length()); + std::ifstream ifFile(file.c_str()); + if(ifFile.good()) + { + std::stringstream ss; + ss << ifFile.rdbuf(); - crc = crc32(crc, (const unsigned char *)ss.str().c_str(), (unsigned int)ss.str().length()); - Logger::Write(Logger::ZONE_INFO, "Database", "Crcing \"" + file + "\""); - ifFile.close(); - } + crc = crc32(crc, (const unsigned char *)ss.str().c_str(), (unsigned int)ss.str().length()); + Logger::Write(Logger::ZONE_INFO, "Database", "Crcing \"" + file + "\""); + ifFile.close(); + } - return crc; + return crc; } bool CollectionDatabase::CollectionChanged(CollectionInfo *info, unsigned long crc32) { - bool retVal = true; + bool retVal = true; - sqlite3 *handle = DBInstance->GetHandle(); - int rc; - sqlite3_stmt *stmt; + sqlite3 *handle = DBInstance->GetHandle(); + int rc; + sqlite3_stmt *stmt; - sqlite3_prepare_v2(handle, - "SELECT crc32 " - "FROM Collections WHERE collectionName=? and crc32=?;", - -1, &stmt, 0); + sqlite3_prepare_v2(handle, + "SELECT crc32 " + "FROM Collections WHERE collectionName=? and crc32=?;", + -1, &stmt, 0); - sqlite3_bind_text(stmt, 1, info->GetName().c_str(), -1, SQLITE_TRANSIENT); - sqlite3_bind_int(stmt, 2, crc32); + sqlite3_bind_text(stmt, 1, info->GetName().c_str(), -1, SQLITE_TRANSIENT); + sqlite3_bind_int(stmt, 2, crc32); - rc = sqlite3_step(stmt); + rc = sqlite3_step(stmt); - if(rc == SQLITE_ROW) - { - retVal = false; - } + if(rc == SQLITE_ROW) + { + retVal = false; + } - return retVal; + return retVal; } bool CollectionDatabase::SetHidden(std::string collectionName, Item *item, bool hidden) { - bool retVal = true; - char *error = NULL; - sqlite3 *handle = DBInstance->GetHandle(); - std::string mode = (hidden) ? "hidden":"visible"; - int isHidden = (hidden)?1:0; + bool retVal = true; + char *error = NULL; + sqlite3 *handle = DBInstance->GetHandle(); + std::string mode = (hidden) ? "hidden":"visible"; + int isHidden = (hidden)?1:0; - Logger::Write(Logger::ZONE_DEBUG, "Database", "Marking \"" + item->GetFullTitle() + "\" " + mode); + Logger::Write(Logger::ZONE_DEBUG, "Database", "Marking \"" + item->GetFullTitle() + "\" " + mode); - sqlite3_stmt *stmt; - sqlite3_prepare_v2(handle, - "UPDATE CollectionItems SET hidden=? WHERE collectionName=? AND name=?;", - -1, &stmt, 0); + sqlite3_stmt *stmt; + sqlite3_prepare_v2(handle, + "UPDATE CollectionItems SET hidden=? WHERE collectionName=? AND name=?;", + -1, &stmt, 0); - sqlite3_bind_int(stmt, 1, isHidden); - sqlite3_bind_text(stmt, 2, collectionName.c_str(), -1, SQLITE_TRANSIENT); - sqlite3_bind_text(stmt, 3, item->GetFullTitle().c_str(), -1, SQLITE_TRANSIENT); + sqlite3_bind_int(stmt, 1, isHidden); + sqlite3_bind_text(stmt, 2, collectionName.c_str(), -1, SQLITE_TRANSIENT); + sqlite3_bind_text(stmt, 3, item->GetFullTitle().c_str(), -1, SQLITE_TRANSIENT); - sqlite3_step(stmt); - sqlite3_finalize(stmt); + sqlite3_step(stmt); + sqlite3_finalize(stmt); - sqlite3_exec(handle, "COMMIT TRANSACTION;", NULL, NULL, &error); + sqlite3_exec(handle, "COMMIT TRANSACTION;", NULL, NULL, &error); - return retVal; + return retVal; } //todo: This file needs MASSIVE REFACTORING! bool CollectionDatabase::ImportDirectory(CollectionInfo *info, unsigned long crc32) { - DIR *dp; - struct dirent *dirp; - std::string path = info->GetListPath(); - std::map includeFilter; - std::map excludeFilter; - std::map includeList; - std::map metaList; - bool retVal = true; - char *error = NULL; - sqlite3 *handle = DBInstance->GetHandle(); - std::string includeFile = Configuration::GetAbsolutePath() + "/Collections/" + info->GetName() + "/Include.txt"; - std::string excludeFile = Configuration::GetAbsolutePath() + "/Collections/" + info->GetName() + "/Exclude.txt"; - std::string includeHyperListFile = Configuration::GetAbsolutePath() + "/Collections/" + info->GetName() + "/Include.xml"; + DIR *dp; + struct dirent *dirp; + std::string path = info->GetListPath(); + std::map includeFilter; + std::map excludeFilter; + std::map includeList; + std::map metaList; + bool retVal = true; + char *error = NULL; + sqlite3 *handle = DBInstance->GetHandle(); + std::string includeFile = Configuration::GetAbsolutePath() + "/Collections/" + info->GetName() + "/Include.txt"; + std::string excludeFile = Configuration::GetAbsolutePath() + "/Collections/" + info->GetName() + "/Exclude.txt"; + std::string includeHyperListFile = Configuration::GetAbsolutePath() + "/Collections/" + info->GetName() + "/Include.xml"; - if(!ImportBasicList(info, includeFile, includeFilter)) - { - ImportHyperList(info, includeHyperListFile, includeFilter); + if(!ImportBasicList(info, includeFile, includeFilter)) + { + ImportHyperList(info, includeHyperListFile, includeFilter); - } - //todo: this shouldn't be read twice, perform a copy - ImportHyperList(info, includeHyperListFile, metaList); + } + //todo: this shouldn't be read twice, perform a copy + ImportHyperList(info, includeHyperListFile, metaList); - (void)ImportBasicList(info, excludeFile, excludeFilter); + (void)ImportBasicList(info, excludeFile, excludeFilter); - dp = opendir(path.c_str()); - std::vector extensions; - info->GetExtensions(extensions); - std::vector::iterator extensionsIt; + dp = opendir(path.c_str()); + std::vector extensions; + info->GetExtensions(extensions); + std::vector::iterator extensionsIt; - if(dp == NULL) - { - Logger::Write(Logger::ZONE_ERROR, "Database", "Could not read directory \"" + info->GetListPath() + "\""); - //todo: store into a database - } - else - { - while((dirp = readdir(dp)) != NULL) - { - std::string file = dirp->d_name; + if(dp == NULL) + { + Logger::Write(Logger::ZONE_ERROR, "Database", "Could not read directory \"" + info->GetListPath() + "\""); + //todo: store into a database + } + else + { + while((dirp = readdir(dp)) != NULL) + { + std::string file = dirp->d_name; - Utils::NormalizeBackSlashes(file); - size_t position = file.find_last_of("."); - std::string basename = (std::string::npos == position)? file : file.substr(0, position); + Utils::NormalizeBackSlashes(file); + size_t position = file.find_last_of("."); + std::string basename = (std::string::npos == position)? file : file.substr(0, position); - if((includeFilter.size() == 0 || includeFilter.find(basename) != includeFilter.end()) && - (excludeFilter.size() == 0 || excludeFilter.find(basename) == excludeFilter.end())) - { - for(extensionsIt = extensions.begin(); extensionsIt != extensions.end(); ++extensionsIt) + if((includeFilter.size() == 0 || includeFilter.find(basename) != includeFilter.end()) && + (excludeFilter.size() == 0 || excludeFilter.find(basename) == excludeFilter.end())) { - std::string comparator = "." + *extensionsIt; - int start = file.length() - comparator.length() + 1; + for(extensionsIt = extensions.begin(); extensionsIt != extensions.end(); ++extensionsIt) + { + std::string comparator = "." + *extensionsIt; + int start = file.length() - comparator.length() + 1; - if(start >= 0) - { - if(file.compare(start, comparator.length(), *extensionsIt) == 0) - { - if(includeList.find(basename) == includeList.end()) - { - Item *i = new Item(); - i->SetFullTitle(file); - includeList[basename] = i; - } - if(metaList.find(basename) == metaList.end()) - { - Item *i = new Item(); - i->SetFullTitle(file); - metaList[basename] = i; - } - } - } + if(start >= 0) + { + if(file.compare(start, comparator.length(), *extensionsIt) == 0) + { + if(includeList.find(basename) == includeList.end()) + { + Item *i = new Item(); + i->SetFullTitle(file); + includeList[basename] = i; + } + if(metaList.find(basename) == metaList.end()) + { + Item *i = new Item(); + i->SetFullTitle(file); + metaList[basename] = i; + } + } + } + } } - } - } - } + } + } - while(includeFilter.size() > 0) - { - std::map::iterator it = includeFilter.begin(); - delete it->second; - includeFilter.erase(it); - } - while(excludeFilter.size() > 0) - { - std::map::iterator it = excludeFilter.begin(); - delete it->second; - excludeFilter.erase(it); - } + while(includeFilter.size() > 0) + { + std::map::iterator it = includeFilter.begin(); + delete it->second; + includeFilter.erase(it); + } + while(excludeFilter.size() > 0) + { + std::map::iterator it = excludeFilter.begin(); + delete it->second; + excludeFilter.erase(it); + } - Logger::Write(Logger::ZONE_INFO, "Database", "Scanning to import \"" + path + "\""); - sqlite3_exec(handle, "BEGIN IMMEDIATE TRANSACTION;", NULL, NULL, &error); + Logger::Write(Logger::ZONE_INFO, "Database", "Scanning to import \"" + path + "\""); + sqlite3_exec(handle, "BEGIN IMMEDIATE TRANSACTION;", NULL, NULL, &error); - sqlite3_stmt *stmt; - sqlite3_prepare_v2(handle, - "DELETE FROM Collections WHERE collectionName=?;", - -1, &stmt, 0); - sqlite3_bind_text(stmt, 1, info->GetName().c_str(), -1, SQLITE_TRANSIENT); - sqlite3_step(stmt); - sqlite3_finalize(stmt); + sqlite3_stmt *stmt; + sqlite3_prepare_v2(handle, + "DELETE FROM Collections WHERE collectionName=?;", + -1, &stmt, 0); + sqlite3_bind_text(stmt, 1, info->GetName().c_str(), -1, SQLITE_TRANSIENT); + sqlite3_step(stmt); + sqlite3_finalize(stmt); - sqlite3_prepare_v2(handle, - "DELETE FROM CollectionItems WHERE collectionName=?;", - -1, &stmt, 0); - sqlite3_bind_text(stmt, 1, info->GetName().c_str(), -1, SQLITE_TRANSIENT); - sqlite3_step(stmt); - sqlite3_finalize(stmt); + sqlite3_prepare_v2(handle, + "DELETE FROM CollectionItems WHERE collectionName=?;", + -1, &stmt, 0); + sqlite3_bind_text(stmt, 1, info->GetName().c_str(), -1, SQLITE_TRANSIENT); + sqlite3_step(stmt); + sqlite3_finalize(stmt); - sqlite3_prepare_v2(handle, - "DELETE FROM Meta WHERE collectionName=?;", - -1, &stmt, 0); - sqlite3_bind_text(stmt, 1, info->GetName().c_str(), -1, SQLITE_TRANSIENT); - sqlite3_step(stmt); - sqlite3_finalize(stmt); + sqlite3_prepare_v2(handle, + "DELETE FROM Meta WHERE collectionName=?;", + -1, &stmt, 0); + sqlite3_bind_text(stmt, 1, info->GetName().c_str(), -1, SQLITE_TRANSIENT); + sqlite3_step(stmt); + sqlite3_finalize(stmt); - if(sqlite3_exec(handle, "COMMIT TRANSACTION;", NULL, NULL, &error) != SQLITE_OK) - { - std::stringstream ss; - ss << "Updating cache collection failure " << error; - Logger::Write(Logger::ZONE_ERROR, "Database", ss.str()); - retVal = false; - } + if(sqlite3_exec(handle, "COMMIT TRANSACTION;", NULL, NULL, &error) != SQLITE_OK) + { + std::stringstream ss; + ss << "Updating cache collection failure " << error; + Logger::Write(Logger::ZONE_ERROR, "Database", ss.str()); + retVal = false; + } - std::map::iterator it; + std::map::iterator it; - if(sqlite3_exec(handle, "BEGIN IMMEDIATE TRANSACTION;", NULL, NULL, &error) != SQLITE_OK) - { - std::stringstream ss; - ss << "Delete cache collection failure " << error; - Logger::Write(Logger::ZONE_ERROR, "Database", ss.str()); - retVal = false; - } + if(sqlite3_exec(handle, "BEGIN IMMEDIATE TRANSACTION;", NULL, NULL, &error) != SQLITE_OK) + { + std::stringstream ss; + ss << "Delete cache collection failure " << error; + Logger::Write(Logger::ZONE_ERROR, "Database", ss.str()); + retVal = false; + } - for(it = includeList.begin(); it != includeList.end(); it++) - { - std::string basename = it->first; - Item *file = it->second; + for(it = includeList.begin(); it != includeList.end(); it++) + { + std::string basename = it->first; + Item *file = it->second; - std::string name = file->GetFullTitle(); - Utils::NormalizeBackSlashes(name); - file->SetFullTitle(name); + std::string name = file->GetFullTitle(); + Utils::NormalizeBackSlashes(name); + file->SetFullTitle(name); - sqlite3_prepare_v2(handle, - "INSERT OR REPLACE INTO CollectionItems (collectionName, filePath, name) VALUES (?,?,?);", - -1, &stmt, 0); + sqlite3_prepare_v2(handle, + "INSERT OR REPLACE INTO CollectionItems (collectionName, filePath, name) VALUES (?,?,?);", + -1, &stmt, 0); - sqlite3_bind_text(stmt, 1, info->GetName().c_str(), -1, SQLITE_TRANSIENT); - sqlite3_bind_text(stmt, 2, file->GetFullTitle().c_str(), -1, SQLITE_TRANSIENT); - sqlite3_bind_text(stmt, 3, basename.c_str(), -1, SQLITE_TRANSIENT); + sqlite3_bind_text(stmt, 1, info->GetName().c_str(), -1, SQLITE_TRANSIENT); + sqlite3_bind_text(stmt, 2, file->GetFullTitle().c_str(), -1, SQLITE_TRANSIENT); + sqlite3_bind_text(stmt, 3, basename.c_str(), -1, SQLITE_TRANSIENT); - //todo: better error handling for all of these messages - sqlite3_step(stmt); - sqlite3_finalize(stmt); - } - for(it = metaList.begin(); it != metaList.end(); it++) - { - std::string basename = it->first; - Item *file = it->second; + //todo: better error handling for all of these messages + sqlite3_step(stmt); + sqlite3_finalize(stmt); + } + for(it = metaList.begin(); it != metaList.end(); it++) + { + std::string basename = it->first; + Item *file = it->second; - sqlite3_prepare_v2(handle, - "INSERT OR REPLACE INTO Meta (collectionName, name, title, year, manufacturer, cloneOf, players, buttons) VALUES (?,?,?,?,?,?,?,?);", - -1, &stmt, 0); + sqlite3_prepare_v2(handle, + "INSERT OR REPLACE INTO Meta (collectionName, name, title, year, manufacturer, cloneOf, players, buttons) VALUES (?,?,?,?,?,?,?,?);", + -1, &stmt, 0); - sqlite3_bind_text(stmt, 1, info->GetName().c_str(), -1, SQLITE_TRANSIENT); - sqlite3_bind_text(stmt, 2, basename.c_str(), -1, SQLITE_TRANSIENT); - sqlite3_bind_text(stmt, 3, basename.c_str(), -1, SQLITE_TRANSIENT); - sqlite3_bind_text(stmt, 4, file->GetYear().c_str(), -1, SQLITE_TRANSIENT); - sqlite3_bind_text(stmt, 5, file->GetManufacturer().c_str(), -1, SQLITE_TRANSIENT); - sqlite3_bind_text(stmt, 6, file->GetCloneOf().c_str(), -1, SQLITE_TRANSIENT); - sqlite3_bind_text(stmt, 7, file->GetNumberPlayersString().c_str(), -1, SQLITE_TRANSIENT); - sqlite3_bind_text(stmt, 8, file->GetNumberButtonsString().c_str(), -1, SQLITE_TRANSIENT); + sqlite3_bind_text(stmt, 1, info->GetName().c_str(), -1, SQLITE_TRANSIENT); + sqlite3_bind_text(stmt, 2, basename.c_str(), -1, SQLITE_TRANSIENT); + sqlite3_bind_text(stmt, 3, basename.c_str(), -1, SQLITE_TRANSIENT); + sqlite3_bind_text(stmt, 4, file->GetYear().c_str(), -1, SQLITE_TRANSIENT); + sqlite3_bind_text(stmt, 5, file->GetManufacturer().c_str(), -1, SQLITE_TRANSIENT); + sqlite3_bind_text(stmt, 6, file->GetCloneOf().c_str(), -1, SQLITE_TRANSIENT); + sqlite3_bind_text(stmt, 7, file->GetNumberPlayersString().c_str(), -1, SQLITE_TRANSIENT); + sqlite3_bind_text(stmt, 8, file->GetNumberButtonsString().c_str(), -1, SQLITE_TRANSIENT); - sqlite3_step(stmt); - sqlite3_finalize(stmt); - } + sqlite3_step(stmt); + sqlite3_finalize(stmt); + } - sqlite3_prepare_v2(handle, - "INSERT OR REPLACE INTO Collections (collectionName, crc32) VALUES (?,?);", - -1, &stmt, 0); + sqlite3_prepare_v2(handle, + "INSERT OR REPLACE INTO Collections (collectionName, crc32) VALUES (?,?);", + -1, &stmt, 0); - sqlite3_bind_text(stmt, 1, info->GetName().c_str(), -1, SQLITE_TRANSIENT); - sqlite3_bind_int(stmt, 2, crc32); + sqlite3_bind_text(stmt, 1, info->GetName().c_str(), -1, SQLITE_TRANSIENT); + sqlite3_bind_int(stmt, 2, crc32); - sqlite3_step(stmt); - sqlite3_finalize(stmt); + sqlite3_step(stmt); + sqlite3_finalize(stmt); - if(sqlite3_exec(handle, "COMMIT TRANSACTION;", NULL, NULL, &error) != SQLITE_OK) - { - std::stringstream ss; - ss << "Updating cache collection failure " << error; - Logger::Write(Logger::ZONE_ERROR, "Database", ss.str()); - retVal = false; - } + if(sqlite3_exec(handle, "COMMIT TRANSACTION;", NULL, NULL, &error) != SQLITE_OK) + { + std::stringstream ss; + ss << "Updating cache collection failure " << error; + Logger::Write(Logger::ZONE_ERROR, "Database", ss.str()); + retVal = false; + } - Logger::Write(Logger::ZONE_INFO, "Database", "Imported files from \"" + path + "\" into database"); + Logger::Write(Logger::ZONE_INFO, "Database", "Imported files from \"" + path + "\" into database"); - //todo: create a helper method to get this file directly (copy paste hazard) - std::string mamelistFile = info->GetSettingsPath() + "/Mamelist.xml"; - std::ifstream infile(mamelistFile.c_str()); + //todo: create a helper method to get this file directly (copy paste hazard) + std::string mamelistFile = info->GetSettingsPath() + "/Mamelist.xml"; + std::ifstream infile(mamelistFile.c_str()); - if(infile.good()) - { - Logger::Write(Logger::ZONE_INFO, "Database", "Updating Mamelist metadata for \"" + info->GetName() + "\" (\"" + mamelistFile + "\") into database. This will take a while..."); - MamelistMetadata mld(DBInstance); - mld.Import(mamelistFile, info->GetName()); - } - infile.close(); + if(infile.good()) + { + Logger::Write(Logger::ZONE_INFO, "Database", "Updating Mamelist metadata for \"" + info->GetName() + "\" (\"" + mamelistFile + "\") into database. This will take a while..."); + MamelistMetadata mld(DBInstance); + mld.Import(mamelistFile, info->GetName()); + } + infile.close(); - while(includeList.size() > 0) - { - std::map::iterator it = includeList.begin(); - delete it->second; - includeList.erase(it); - } - while(metaList.size() > 0) - { - std::map::iterator it = metaList.begin(); - delete it->second; - metaList.erase(it); - } - return retVal; + while(includeList.size() > 0) + { + std::map::iterator it = includeList.begin(); + delete it->second; + includeList.erase(it); + } + while(metaList.size() > 0) + { + std::map::iterator it = metaList.begin(); + delete it->second; + metaList.erase(it); + } + return retVal; } bool CollectionDatabase::ImportBasicList(CollectionInfo *info, std::string file, std::map &list) { - bool retVal = false; + bool retVal = false; - Logger::Write(Logger::ZONE_DEBUG, "Database", "Checking to see if \"" + file + "\" exists"); + Logger::Write(Logger::ZONE_DEBUG, "Database", "Checking to see if \"" + file + "\" exists"); - std::ifstream includeStream(file.c_str()); + std::ifstream includeStream(file.c_str()); - if (includeStream.good()) - { - Logger::Write(Logger::ZONE_DEBUG, "Database", "Importing \"" + file + "\""); - std::string line; + if (includeStream.good()) + { + Logger::Write(Logger::ZONE_DEBUG, "Database", "Importing \"" + file + "\""); + std::string line; - while(std::getline(includeStream, line)) - { - if(list.find(line) == list.end()) - { - Item *i = new Item(); - line.erase( std::remove(line.begin(), line.end(), '\r'), line.end() ); + while(std::getline(includeStream, line)) + { + if(list.find(line) == list.end()) + { + Item *i = new Item(); + line.erase( std::remove(line.begin(), line.end(), '\r'), line.end() ); - i->SetFullTitle(line); - list[line] = i; - Logger::Write(Logger::ZONE_DEBUG, "Database", "Including \"" + line + "\" (if file exists)"); - } - } + i->SetFullTitle(line); + list[line] = i; + Logger::Write(Logger::ZONE_DEBUG, "Database", "Including \"" + line + "\" (if file exists)"); + } + } - retVal = true; - } + retVal = true; + } - return retVal; + return retVal; } bool CollectionDatabase::ImportHyperList(CollectionInfo *info, std::string hyperlistFile, std::map &list) { - bool retVal = false; - rapidxml::xml_document<> doc; - std::ifstream file(hyperlistFile.c_str()); - std::vector buffer((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + bool retVal = false; + rapidxml::xml_document<> doc; + std::ifstream file(hyperlistFile.c_str()); + std::vector buffer((std::istreambuf_iterator(file)), std::istreambuf_iterator()); - Logger::Write(Logger::ZONE_DEBUG, "Database", "Checking to see if \"" + hyperlistFile + "\" exists"); + Logger::Write(Logger::ZONE_DEBUG, "Database", "Checking to see if \"" + hyperlistFile + "\" exists"); - if(!file.good()) - { - Logger::Write(Logger::ZONE_INFO, "Database", "Could not find HyperList file: " + hyperlistFile); - return retVal; - } + if(!file.good()) + { + Logger::Write(Logger::ZONE_INFO, "Database", "Could not find HyperList file: " + hyperlistFile); + return retVal; + } - try - { - Logger::Write(Logger::ZONE_INFO, "Database", "Importing: " + hyperlistFile); - buffer.push_back('\0'); + try + { + Logger::Write(Logger::ZONE_INFO, "Database", "Importing: " + hyperlistFile); + buffer.push_back('\0'); - doc.parse<0>(&buffer[0]); + doc.parse<0>(&buffer[0]); - rapidxml::xml_node<> *root = doc.first_node("menu"); + rapidxml::xml_node<> *root = doc.first_node("menu"); - if(!root) - { - Logger::Write(Logger::ZONE_ERROR, "CollectionDatabase", "Does not appear to be a HyperList file (missing tag)"); - return NULL; - } - else - { - for(rapidxml::xml_node<> *game = root->first_node("game"); game; game = game->next_sibling("game")) - { - rapidxml::xml_attribute<> *nameXml = game->first_attribute("name"); - rapidxml::xml_node<> *descriptionXml = game->first_node("description"); - rapidxml::xml_node<> *cloneofXml = game->first_node("cloneof"); - rapidxml::xml_node<> *crcXml = game->first_node("crc"); - rapidxml::xml_node<> *manufacturerXml = game->first_node("manufacturer"); - rapidxml::xml_node<> *yearXml = game->first_node("year"); - rapidxml::xml_node<> *genreXml = game->first_node("genre"); - rapidxml::xml_node<> *ratingXml = game->first_node("rating"); - rapidxml::xml_node<> *enabledXml = game->first_node("enabled"); - std::string name = (nameXml) ? nameXml->value() : ""; - std::string description = (descriptionXml) ? descriptionXml->value() : ""; - std::string crc = (crcXml) ? crcXml->value() : ""; - std::string cloneOf = (cloneofXml) ? cloneofXml->value() : ""; - std::string manufacturer = (manufacturerXml) ? manufacturerXml->value() : ""; - std::string year = (yearXml) ? yearXml->value() : ""; - std::string genre = (genreXml) ? genreXml->value() : ""; - std::string rating = (ratingXml) ? ratingXml->value() : ""; - std::string enabled = (enabledXml) ? enabledXml->value() : ""; - - if(name.length() > 0 && list.find(name) == list.end()) + if(!root) + { + Logger::Write(Logger::ZONE_ERROR, "CollectionDatabase", "Does not appear to be a HyperList file (missing tag)"); + return NULL; + } + else + { + for(rapidxml::xml_node<> *game = root->first_node("game"); game; game = game->next_sibling("game")) { - Item *i = new Item(); - i->SetFullTitle(name); - i->SetYear(year); - i->SetManufacturer(manufacturer); - i->SetCloneOf(cloneOf); - list[name] = i; - Logger::Write(Logger::ZONE_DEBUG, "Database", "Including \"" + name + "\" (if file exists)"); + rapidxml::xml_attribute<> *nameXml = game->first_attribute("name"); + rapidxml::xml_node<> *descriptionXml = game->first_node("description"); + rapidxml::xml_node<> *cloneofXml = game->first_node("cloneof"); + rapidxml::xml_node<> *crcXml = game->first_node("crc"); + rapidxml::xml_node<> *manufacturerXml = game->first_node("manufacturer"); + rapidxml::xml_node<> *yearXml = game->first_node("year"); + rapidxml::xml_node<> *genreXml = game->first_node("genre"); + rapidxml::xml_node<> *ratingXml = game->first_node("rating"); + rapidxml::xml_node<> *enabledXml = game->first_node("enabled"); + std::string name = (nameXml) ? nameXml->value() : ""; + std::string description = (descriptionXml) ? descriptionXml->value() : ""; + std::string crc = (crcXml) ? crcXml->value() : ""; + std::string cloneOf = (cloneofXml) ? cloneofXml->value() : ""; + std::string manufacturer = (manufacturerXml) ? manufacturerXml->value() : ""; + std::string year = (yearXml) ? yearXml->value() : ""; + std::string genre = (genreXml) ? genreXml->value() : ""; + std::string rating = (ratingXml) ? ratingXml->value() : ""; + std::string enabled = (enabledXml) ? enabledXml->value() : ""; + + if(name.length() > 0 && list.find(name) == list.end()) + { + Item *i = new Item(); + i->SetFullTitle(name); + i->SetYear(year); + i->SetManufacturer(manufacturer); + i->SetCloneOf(cloneOf); + list[name] = i; + Logger::Write(Logger::ZONE_DEBUG, "Database", "Including \"" + name + "\" (if file exists)"); + } + } + } + } + catch(rapidxml::parse_error &e) + { + std::string what = e.what(); + long line = static_cast(std::count(&buffer.front(), e.where(), char('\n')) + 1); + std::stringstream ss; + ss << "Could not parse layout file. [Line: " << line << "] Reason: " << e.what(); - } - } - } - catch(rapidxml::parse_error &e) - { - std::string what = e.what(); - long line = static_cast(std::count(&buffer.front(), e.where(), char('\n')) + 1); - std::stringstream ss; - ss << "Could not parse layout file. [Line: " << line << "] Reason: " << e.what(); - - Logger::Write(Logger::ZONE_ERROR, "Layout", ss.str()); - } - catch(std::exception &e) - { - std::string what = e.what(); - Logger::Write(Logger::ZONE_ERROR, "Layout", "Could not parse layout file. Reason: " + what); - } + Logger::Write(Logger::ZONE_ERROR, "Layout", ss.str()); + } + catch(std::exception &e) + { + std::string what = e.what(); + Logger::Write(Logger::ZONE_ERROR, "Layout", "Could not parse layout file. Reason: " + what); + } - return retVal; + return retVal; } /* @@ -650,98 +650,98 @@ bool CollectionDatabase::ImportMetadata(CollectionInfo *info) bool CollectionDatabase::GetCollection(std::string collectionName, std::vector &list) { - bool retVal = true; + bool retVal = true; - sqlite3 *handle = DBInstance->GetHandle(); - int rc; - sqlite3_stmt *stmt; + sqlite3 *handle = DBInstance->GetHandle(); + int rc; + sqlite3_stmt *stmt; - bool showParenthesis = true; - bool showSquareBrackets = true; + bool showParenthesis = true; + bool showSquareBrackets = true; - (void)Config->GetProperty("showParenthesis", showParenthesis); - (void)Config->GetProperty("showSquareBrackets", showSquareBrackets); + (void)Config->GetProperty("showParenthesis", showParenthesis); + (void)Config->GetProperty("showSquareBrackets", showSquareBrackets); - //todo: program crashes if this query fails - sqlite3_prepare_v2(handle, - "SELECT DISTINCT CollectionItems.filePath, CollectionItems.name, Meta.title, Meta.year, Meta.manufacturer, Meta.players, Meta.buttons, Meta.cloneOf " - "FROM CollectionItems, Meta WHERE CollectionItems.collectionName=? AND Meta.collectionName=? AND CollectionItems.name=Meta.name AND CollectionItems.hidden=0 ORDER BY title ASC;", - -1, &stmt, 0); + //todo: program crashes if this query fails + sqlite3_prepare_v2(handle, + "SELECT DISTINCT CollectionItems.filePath, CollectionItems.name, Meta.title, Meta.year, Meta.manufacturer, Meta.players, Meta.buttons, Meta.cloneOf " + "FROM CollectionItems, Meta WHERE CollectionItems.collectionName=? AND Meta.collectionName=? AND CollectionItems.name=Meta.name AND CollectionItems.hidden=0 ORDER BY title ASC;", + -1, &stmt, 0); - sqlite3_bind_text(stmt, 1, collectionName.c_str(), -1, SQLITE_TRANSIENT); - sqlite3_bind_text(stmt, 2, collectionName.c_str(), -1, SQLITE_TRANSIENT); + sqlite3_bind_text(stmt, 1, collectionName.c_str(), -1, SQLITE_TRANSIENT); + sqlite3_bind_text(stmt, 2, collectionName.c_str(), -1, SQLITE_TRANSIENT); - rc = sqlite3_step(stmt); + rc = sqlite3_step(stmt); - while(rc == SQLITE_ROW) - { - std::string filePath = (char *)sqlite3_column_text(stmt, 0); - std::string name = (char *)sqlite3_column_text(stmt, 1); - std::string fullTitle = (char *)sqlite3_column_text(stmt, 2); - std::string year = (char *)sqlite3_column_text(stmt, 3); - std::string manufacturer = (char *)sqlite3_column_text(stmt, 4); - int numberPlayers = (int)sqlite3_column_int(stmt, 5); - int numberButtons = (int)sqlite3_column_int(stmt, 6); - std::string cloneOf = (char *)sqlite3_column_text(stmt, 7); - std::string launcher; - std::string title = fullTitle; + while(rc == SQLITE_ROW) + { + std::string filePath = (char *)sqlite3_column_text(stmt, 0); + std::string name = (char *)sqlite3_column_text(stmt, 1); + std::string fullTitle = (char *)sqlite3_column_text(stmt, 2); + std::string year = (char *)sqlite3_column_text(stmt, 3); + std::string manufacturer = (char *)sqlite3_column_text(stmt, 4); + int numberPlayers = (int)sqlite3_column_int(stmt, 5); + int numberButtons = (int)sqlite3_column_int(stmt, 6); + std::string cloneOf = (char *)sqlite3_column_text(stmt, 7); + std::string launcher; + std::string title = fullTitle; - if(!showParenthesis) - { - std::string::size_type firstPos = title.find_first_of("("); - std::string::size_type secondPos = title.find_first_of(")", firstPos); + if(!showParenthesis) + { + std::string::size_type firstPos = title.find_first_of("("); + std::string::size_type secondPos = title.find_first_of(")", firstPos); - while(firstPos != std::string::npos && secondPos != std::string::npos) - { - firstPos = title.find_first_of("("); - secondPos = title.find_first_of(")", firstPos); - - if (firstPos != std::string::npos) + while(firstPos != std::string::npos && secondPos != std::string::npos) { - title.erase(firstPos, (secondPos - firstPos) + 1); + firstPos = title.find_first_of("("); + secondPos = title.find_first_of(")", firstPos); + + if (firstPos != std::string::npos) + { + title.erase(firstPos, (secondPos - firstPos) + 1); + } } - } - } - if(!showSquareBrackets) - { - std::string::size_type firstPos = title.find_first_of("["); - std::string::size_type secondPos = title.find_first_of("]", firstPos); + } + if(!showSquareBrackets) + { + std::string::size_type firstPos = title.find_first_of("["); + std::string::size_type secondPos = title.find_first_of("]", firstPos); - while(firstPos != std::string::npos && secondPos != std::string::npos) - { - firstPos = title.find_first_of("["); - secondPos = title.find_first_of("]", firstPos); - - if (firstPos != std::string::npos && secondPos != std::string::npos) + while(firstPos != std::string::npos && secondPos != std::string::npos) { - title.erase(firstPos, (secondPos - firstPos) + 1); + firstPos = title.find_first_of("["); + secondPos = title.find_first_of("]", firstPos); + + if (firstPos != std::string::npos && secondPos != std::string::npos) + { + title.erase(firstPos, (secondPos - firstPos) + 1); + } } - } - } + } - Item *item = new Item(); - item->SetFilePath(filePath); - item->SetName(name); - item->SetTitle(title); - item->SetFullTitle(fullTitle); - item->SetYear(year); - item->SetManufacturer(manufacturer); - item->SetNumberPlayers(numberPlayers); - item->SetNumberButtons(numberButtons); - item->SetCloneOf(cloneOf); + Item *item = new Item(); + item->SetFilePath(filePath); + item->SetName(name); + item->SetTitle(title); + item->SetFullTitle(fullTitle); + item->SetYear(year); + item->SetManufacturer(manufacturer); + item->SetNumberPlayers(numberPlayers); + item->SetNumberButtons(numberButtons); + item->SetCloneOf(cloneOf); - //std::cout << "loading " << title << std::endl; - if(Config->GetProperty("collections." + collectionName + ".launcher", launcher)) - { - item->SetLauncher(launcher); - } + //std::cout << "loading " << title << std::endl; + if(Config->GetProperty("collections." + collectionName + ".launcher", launcher)) + { + item->SetLauncher(launcher); + } - list.push_back(item); + list.push_back(item); - rc = sqlite3_step(stmt); - } + rc = sqlite3_step(stmt); + } - //todo: query the metadata table to populate each item + //todo: query the metadata table to populate each item - return retVal; + return retVal; } diff --git a/Source/Database/CollectionDatabase.h b/Source/Database/CollectionDatabase.h index a18f3e7..1287b79 100644 --- a/Source/Database/CollectionDatabase.h +++ b/Source/Database/CollectionDatabase.h @@ -15,30 +15,30 @@ class Item; class CollectionDatabase { public: - CollectionDatabase(DB *db, Configuration *c); - virtual ~CollectionDatabase(); - bool Initialize(); - bool Import(); - bool ResetDatabase(); + CollectionDatabase(DB *db, Configuration *c); + virtual ~CollectionDatabase(); + bool Initialize(); + bool Import(); + bool ResetDatabase(); - bool GetCollection(std::string collectionName, std::vector &list); - bool SetHidden(std::string collectionName, Item *item, bool hidden); + bool GetCollection(std::string collectionName, std::vector &list); + bool SetHidden(std::string collectionName, Item *item, bool hidden); private: - unsigned long CalculateCollectionCrc32(CollectionInfo *info); - bool CollectionChanged(CollectionInfo *info, unsigned long crc32); - unsigned long CrcFile(std::string file, unsigned long crc); + unsigned long CalculateCollectionCrc32(CollectionInfo *info); + bool CollectionChanged(CollectionInfo *info, unsigned long crc32); + unsigned long CrcFile(std::string file, unsigned long crc); // bool ImportMetadata(CollectionInfo *info); - bool ImportDirectory(CollectionInfo *info, unsigned long crc32); - bool ImportBasicList(CollectionInfo *info, - std::string file, - std::map &list); - bool ImportHyperList(CollectionInfo *info, - std::string file, - std::map &list); - std::map *ImportHyperList(CollectionInfo *info); - Configuration *Config; - DB *DBInstance; + bool ImportDirectory(CollectionInfo *info, unsigned long crc32); + bool ImportBasicList(CollectionInfo *info, + std::string file, + std::map &list); + bool ImportHyperList(CollectionInfo *info, + std::string file, + std::map &list); + std::map *ImportHyperList(CollectionInfo *info); + Configuration *Config; + DB *DBInstance; }; diff --git a/Source/Database/Configuration.cpp b/Source/Database/Configuration.cpp index 08d0191..26f84b0 100644 --- a/Source/Database/Configuration.cpp +++ b/Source/Database/Configuration.cpp @@ -19,7 +19,7 @@ std::string Configuration::AbsolutePath; Configuration::Configuration() -: Verbose(false) + : Verbose(false) { } @@ -27,307 +27,307 @@ Configuration::~Configuration() { } -void Configuration::Initialize() +void Configuration::Initialize() { - const char *environment = std::getenv("RETROFE_PATH"); - std::string environmentStr; - if (environment != NULL) - { - environmentStr = environment; - Configuration::SetAbsolutePath(environment); - } - else - { + const char *environment = std::getenv("RETROFE_PATH"); + std::string environmentStr; + if (environment != NULL) + { + environmentStr = environment; + Configuration::SetAbsolutePath(environment); + } + else + { #ifdef WIN32 - HMODULE hModule = GetModuleHandle(NULL); - CHAR exe[MAX_PATH]; - GetModuleFileName(hModule, exe, MAX_PATH); - std::string sPath(exe); - sPath = Utils::GetDirectory(sPath); - sPath = Utils::GetParentDirectory(sPath); + HMODULE hModule = GetModuleHandle(NULL); + CHAR exe[MAX_PATH]; + GetModuleFileName(hModule, exe, MAX_PATH); + std::string sPath(exe); + sPath = Utils::GetDirectory(sPath); + sPath = Utils::GetParentDirectory(sPath); #else - char exepath[1024]; - sprintf(exepath, "/proc/%d/exe", getpid()); - readlink(exepath, exepath, sizeof(exepath)); - std::string sPath(exepath); - sPath = Utils::GetDirectory(sPath); + char exepath[1024]; + sprintf(exepath, "/proc/%d/exe", getpid()); + readlink(exepath, exepath, sizeof(exepath)); + std::string sPath(exepath); + sPath = Utils::GetDirectory(sPath); #endif - Configuration::SetAbsolutePath(sPath); - } + Configuration::SetAbsolutePath(sPath); + } } bool Configuration::Import(std::string keyPrefix, std::string file) { - bool retVal = true; - int lineCount = 0; - std::string line; + bool retVal = true; + int lineCount = 0; + std::string line; - Logger::Write(Logger::ZONE_INFO, "Configuration", "Importing " + file); + Logger::Write(Logger::ZONE_INFO, "Configuration", "Importing " + file); - std::ifstream ifs(file.c_str()); + std::ifstream ifs(file.c_str()); - if (!ifs.is_open()) - { - Logger::Write(Logger::ZONE_ERROR, "Configuration", "Could not open " + file); + if (!ifs.is_open()) + { + Logger::Write(Logger::ZONE_ERROR, "Configuration", "Could not open " + file); - return false; - } + return false; + } - while (std::getline (ifs, line)) - { - lineCount++; - retVal = retVal && ParseLine(keyPrefix, line, lineCount); - } + while (std::getline (ifs, line)) + { + lineCount++; + retVal = retVal && ParseLine(keyPrefix, line, lineCount); + } - ifs.close(); + ifs.close(); - return retVal; + return retVal; } bool Configuration::ParseLine(std::string keyPrefix, std::string line, int lineCount) { - bool retVal = false; - std::string key; - std::string value; - size_t position; - std::string delimiter = "="; + bool retVal = false; + std::string key; + std::string value; + size_t position; + std::string delimiter = "="; - // strip out any comments - if((position = line.find("#")) != std::string::npos) - { - line = line.substr(0, position); - } - // unix only wants \n. Windows uses \r\n. Strip off the \r for unix. - line.erase( std::remove(line.begin(), line.end(), '\r'), line.end() ); - if(line.empty() || (line.find_first_not_of(" \t\r") == std::string::npos)) - { - retVal = true; - } - // all configuration fields must have an assignment operator - else if((position = line.find(delimiter)) != std::string::npos) - { - if(keyPrefix.size() != 0) - { - keyPrefix += "."; - } + // strip out any comments + if((position = line.find("#")) != std::string::npos) + { + line = line.substr(0, position); + } + // unix only wants \n. Windows uses \r\n. Strip off the \r for unix. + line.erase( std::remove(line.begin(), line.end(), '\r'), line.end() ); + if(line.empty() || (line.find_first_not_of(" \t\r") == std::string::npos)) + { + retVal = true; + } + // all configuration fields must have an assignment operator + else if((position = line.find(delimiter)) != std::string::npos) + { + if(keyPrefix.size() != 0) + { + keyPrefix += "."; + } - key = keyPrefix + line.substr(0, position); + key = keyPrefix + line.substr(0, position); - key = TrimEnds(key); + key = TrimEnds(key); - value = line.substr(position + delimiter.length(), line.length()); - value = TrimEnds(value); + value = line.substr(position + delimiter.length(), line.length()); + value = TrimEnds(value); - Properties.insert(PropertiesPair(key, value)); + Properties.insert(PropertiesPair(key, value)); - std::stringstream ss; - ss << "Dump: " << "\"" << key << "\" = \"" << value << "\""; + std::stringstream ss; + ss << "Dump: " << "\"" << key << "\" = \"" << value << "\""; - Logger::Write(Logger::ZONE_INFO, "Configuration", ss.str()); - retVal = true; - } - else - { - std::stringstream ss; - ss << "Missing an assignment operator (=) on line " << lineCount; - Logger::Write(Logger::ZONE_ERROR, "Configuration", ss.str()); - } + Logger::Write(Logger::ZONE_INFO, "Configuration", ss.str()); + retVal = true; + } + else + { + std::stringstream ss; + ss << "Missing an assignment operator (=) on line " << lineCount; + Logger::Write(Logger::ZONE_ERROR, "Configuration", ss.str()); + } - return retVal; + return retVal; } std::string Configuration::TrimEnds(std::string str) { - // strip off any initial tabs or spaces - size_t trimStart = str.find_first_not_of(" \t"); + // strip off any initial tabs or spaces + size_t trimStart = str.find_first_not_of(" \t"); - if(trimStart != std::string::npos) - { - size_t trimEnd = str.find_last_not_of(" \t"); + if(trimStart != std::string::npos) + { + size_t trimEnd = str.find_last_not_of(" \t"); - str = str.substr(trimStart, trimEnd - trimStart + 1); - } + str = str.substr(trimStart, trimEnd - trimStart + 1); + } - return str; + return str; } bool Configuration::GetProperty(std::string key, std::string &value) { - bool retVal = false; - if(Properties.find(key) != Properties.end()) - { - value = Properties[key]; + bool retVal = false; + if(Properties.find(key) != Properties.end()) + { + value = Properties[key]; - retVal = true; - } - else if(Verbose) - { - Logger::Write(Logger::ZONE_DEBUG, "Configuration", "Missing property " + key); - } + retVal = true; + } + else if(Verbose) + { + Logger::Write(Logger::ZONE_DEBUG, "Configuration", "Missing property " + key); + } - return retVal; + return retVal; } bool Configuration::GetProperty(std::string key, int &value) { - std::string strValue; + std::string strValue; - bool retVal = GetProperty(key, strValue); + bool retVal = GetProperty(key, strValue); - if(retVal) - { - std::stringstream ss; - ss << strValue; - ss >> value; - } + if(retVal) + { + std::stringstream ss; + ss << strValue; + ss >> value; + } - return retVal; + return retVal; } bool Configuration::GetProperty(std::string key, bool &value) { - std::string strValue; + std::string strValue; - bool retVal = GetProperty(key, strValue); + bool retVal = GetProperty(key, strValue); - if(retVal) - { - std::stringstream ss; - ss << strValue; + if(retVal) + { + std::stringstream ss; + ss << strValue; - for(unsigned int i=0; i < strValue.length(); ++i) - { - std::locale loc; - strValue[i] = std::tolower(strValue[i], loc); - } + for(unsigned int i=0; i < strValue.length(); ++i) + { + std::locale loc; + strValue[i] = std::tolower(strValue[i], loc); + } - if(!strValue.compare("yes") || !strValue.compare("true")) - { - value = true; - } - else - { - value = false; - } - } + if(!strValue.compare("yes") || !strValue.compare("true")) + { + value = true; + } + else + { + value = false; + } + } - return retVal; + return retVal; } void Configuration::SetProperty(std::string key, std::string value) { - Properties[key] = value; + Properties[key] = value; } bool Configuration::PropertyExists(std::string key) { - return (Properties.find(key) != Properties.end()); + return (Properties.find(key) != Properties.end()); } bool Configuration::PropertyPrefixExists(std::string key) { - PropertiesType::iterator it; + PropertiesType::iterator it; - for(it = Properties.begin(); it != Properties.end(); ++it) - { - std::string search = key + "."; - if(it->first.compare(0, search.length(), search) == 0) - { - return true; - } - } + for(it = Properties.begin(); it != Properties.end(); ++it) + { + std::string search = key + "."; + if(it->first.compare(0, search.length(), search) == 0) + { + return true; + } + } - return false; + return false; } void Configuration::GetChildKeyCrumbs(std::string parent, std::vector &children) { - PropertiesType::iterator it; + PropertiesType::iterator it; - for(it = Properties.begin(); it != Properties.end(); ++it) - { - std::string search = parent + "."; - if(it->first.compare(0, search.length(), search) == 0) - { - std::string crumb = Utils::Replace(it->first, search, ""); + for(it = Properties.begin(); it != Properties.end(); ++it) + { + std::string search = parent + "."; + if(it->first.compare(0, search.length(), search) == 0) + { + std::string crumb = Utils::Replace(it->first, search, ""); - std::size_t end = crumb.find_first_of("."); + std::size_t end = crumb.find_first_of("."); - if(end != std::string::npos) - { - crumb = crumb.substr(0, end); - } + if(end != std::string::npos) + { + crumb = crumb.substr(0, end); + } - if(std::find(children.begin(), children.end(), crumb) == children.end()) - { - children.push_back(crumb); - } - } - } + if(std::find(children.begin(), children.end(), crumb) == children.end()) + { + children.push_back(crumb); + } + } + } } std::string Configuration::ConvertToAbsolutePath(std::string prefix, std::string path) { - char first = ' '; - char second = ' '; + char first = ' '; + char second = ' '; - if(path.length() >= 0) - { - first = path.c_str()[0]; - } - if(path.length() >= 1) - { - second = path.c_str()[1]; - } + if(path.length() >= 0) + { + first = path.c_str()[0]; + } + if(path.length() >= 1) + { + second = path.c_str()[1]; + } - // check to see if it is already an absolute path - if((first != '/') && - (first != '\\') && - //(first != '.') && - (second != ':')) - { - path = prefix + "/" + path; - } + // check to see if it is already an absolute path + if((first != '/') && + (first != '\\') && + //(first != '.') && + (second != ':')) + { + path = prefix + "/" + path; + } - return path; + return path; } bool Configuration::GetPropertyAbsolutePath(std::string key, std::string &value) { - bool retVal = GetProperty(key, value); + bool retVal = GetProperty(key, value); - if(retVal) - { - value = ConvertToAbsolutePath(GetAbsolutePath(), value); - } + if(retVal) + { + value = ConvertToAbsolutePath(GetAbsolutePath(), value); + } - return retVal; + return retVal; } void Configuration::SetAbsolutePath(std::string absolutePath) { - AbsolutePath = absolutePath; + AbsolutePath = absolutePath; } std::string Configuration::GetAbsolutePath() { - return AbsolutePath; + return AbsolutePath; } bool Configuration::IsVerbose() const { - return Verbose; + return Verbose; } void Configuration::SetVerbose(bool verbose) { - this->Verbose = verbose; + this->Verbose = verbose; } diff --git a/Source/Database/Configuration.h b/Source/Database/Configuration.h index bf3929b..2918ed5 100644 --- a/Source/Database/Configuration.h +++ b/Source/Database/Configuration.h @@ -10,35 +10,35 @@ class Configuration { public: - Configuration(); - virtual ~Configuration(); - static void Initialize(); - static void SetAbsolutePath(std::string absolutePath); - static std::string GetAbsolutePath(); - static std::string ConvertToAbsolutePath(std::string prefix, std::string path); + Configuration(); + virtual ~Configuration(); + static void Initialize(); + static void SetAbsolutePath(std::string absolutePath); + static std::string GetAbsolutePath(); + static std::string ConvertToAbsolutePath(std::string prefix, std::string path); - // gets the global configuration - bool Import(std::string keyPrefix, std::string file); + // gets the global configuration + bool Import(std::string keyPrefix, std::string file); - bool GetProperty(std::string key, std::string &value); - bool GetProperty(std::string key, int &value); - bool GetProperty(std::string key, bool &value); - void GetChildKeyCrumbs(std::string parent, std::vector &children); - void SetProperty(std::string key, std::string value); - bool PropertyExists(std::string key); - bool PropertyPrefixExists(std::string key); - bool GetPropertyAbsolutePath(std::string key, std::string &value); - bool IsVerbose() const; - void SetVerbose(bool verbose); - bool IsRequiredPropertiesSet(); + bool GetProperty(std::string key, std::string &value); + bool GetProperty(std::string key, int &value); + bool GetProperty(std::string key, bool &value); + void GetChildKeyCrumbs(std::string parent, std::vector &children); + void SetProperty(std::string key, std::string value); + bool PropertyExists(std::string key); + bool PropertyPrefixExists(std::string key); + bool GetPropertyAbsolutePath(std::string key, std::string &value); + bool IsVerbose() const; + void SetVerbose(bool verbose); + bool IsRequiredPropertiesSet(); private: - bool ParseLine(std::string keyPrefix, std::string line, int lineCount); - std::string TrimEnds(std::string str); - typedef std::map PropertiesType; - typedef std::pair PropertiesPair; - bool Verbose; + bool ParseLine(std::string keyPrefix, std::string line, int lineCount); + std::string TrimEnds(std::string str); + typedef std::map PropertiesType; + typedef std::pair PropertiesPair; + bool Verbose; - static std::string AbsolutePath; - PropertiesType Properties; + static std::string AbsolutePath; + PropertiesType Properties; }; diff --git a/Source/Database/DB.cpp b/Source/Database/DB.cpp index 2c041fe..fed8f66 100644 --- a/Source/Database/DB.cpp +++ b/Source/Database/DB.cpp @@ -1,5 +1,5 @@ -/* This file is subject to the terms and conditions defined in - * file 'LICENSE.txt', which is part of this source code package. +/* This file is subject to the terms and conditions defined in + * file 'LICENSE.txt', which is part of this source code package. */ #include "DB.h" #include "../Utility/Log.h" @@ -8,42 +8,42 @@ #include DB::DB(std::string dbFile) -: Path(dbFile) -, Handle(NULL) + : Path(dbFile) + , Handle(NULL) { } DB::~DB() { - DeInitialize(); + DeInitialize(); } bool DB::Initialize() { - bool retVal = false; + bool retVal = false; - if(sqlite3_open(Path.c_str(), &Handle) != 0) - { - std::stringstream ss; - ss << "Cannot open database: \"" << Path << "\"" << sqlite3_errmsg(Handle); - Logger::Write(Logger::ZONE_ERROR, "Database", ss.str()); - } - else - { - Logger::Write(Logger::ZONE_INFO, "Database", "Opened database \"" + Path + "\""); - retVal = true; - } + if(sqlite3_open(Path.c_str(), &Handle) != 0) + { + std::stringstream ss; + ss << "Cannot open database: \"" << Path << "\"" << sqlite3_errmsg(Handle); + Logger::Write(Logger::ZONE_ERROR, "Database", ss.str()); + } + else + { + Logger::Write(Logger::ZONE_INFO, "Database", "Opened database \"" + Path + "\""); + retVal = true; + } - return retVal; + return retVal; } void DB::DeInitialize() { - if(Handle != NULL) - { - sqlite3_close(Handle); - Handle = NULL; - } + if(Handle != NULL) + { + sqlite3_close(Handle); + Handle = NULL; + } } diff --git a/Source/Database/DB.h b/Source/Database/DB.h index c3f28a6..7db60d1 100644 --- a/Source/Database/DB.h +++ b/Source/Database/DB.h @@ -1,5 +1,5 @@ -/* This file is subject to the terms and conditions defined in - * file 'LICENSE.txt', which is part of this source code package. +/* This file is subject to the terms and conditions defined in + * file 'LICENSE.txt', which is part of this source code package. */ #pragma once @@ -8,14 +8,17 @@ class DB { public: - DB(std::string dbFile); - bool Initialize(); - void DeInitialize(); - virtual ~DB(); - sqlite3 *GetHandle() { return Handle; } + DB(std::string dbFile); + bool Initialize(); + void DeInitialize(); + virtual ~DB(); + sqlite3 *GetHandle() + { + return Handle; + } private: - sqlite3 *Handle; - std::string Path; + sqlite3 *Handle; + std::string Path; }; diff --git a/Source/Database/MamelistMetadata.cpp b/Source/Database/MamelistMetadata.cpp index 9b2df78..2c6074f 100644 --- a/Source/Database/MamelistMetadata.cpp +++ b/Source/Database/MamelistMetadata.cpp @@ -1,5 +1,5 @@ -/* This file is subject to the terms and conditions defined in - * file 'LICENSE.txt', which is part of this source code package. +/* This file is subject to the terms and conditions defined in + * file 'LICENSE.txt', which is part of this source code package. */ #include "MamelistMetadata.h" #include "DB.h" @@ -13,7 +13,7 @@ MamelistMetadata::MamelistMetadata(DB *dbInstance) -: DBInstance(dbInstance) + : DBInstance(dbInstance) { } @@ -23,97 +23,97 @@ MamelistMetadata::~MamelistMetadata() bool MamelistMetadata::Import(std::string filename, std::string collection) { - bool retVal = true; - rapidxml::xml_document<> doc; - rapidxml::xml_node<> * rootNode; - char *error = NULL; - sqlite3 *handle = DBInstance->GetHandle(); + bool retVal = true; + rapidxml::xml_document<> doc; + rapidxml::xml_node<> * rootNode; + char *error = NULL; + sqlite3 *handle = DBInstance->GetHandle(); - std::ifstream f(filename.c_str()); + std::ifstream f(filename.c_str()); - if (!f.good()) - { - Logger::Write(Logger::ZONE_ERROR, "Mamelist", "Could not find mamelist metadata file at \"" + filename + "\""); + if (!f.good()) + { + Logger::Write(Logger::ZONE_ERROR, "Mamelist", "Could not find mamelist metadata file at \"" + filename + "\""); - retVal = false; - } + retVal = false; + } - f.close(); + f.close(); - if(retVal) - { - Logger::Write(Logger::ZONE_INFO, "Mamelist", "Importing mamelist file \"" + filename + "\""); - std::ifstream file(filename.c_str()); - std::vector buffer((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + if(retVal) + { + Logger::Write(Logger::ZONE_INFO, "Mamelist", "Importing mamelist file \"" + filename + "\""); + std::ifstream file(filename.c_str()); + std::vector buffer((std::istreambuf_iterator(file)), std::istreambuf_iterator()); - buffer.push_back('\0'); + buffer.push_back('\0'); - doc.parse<0>(&buffer[0]); + doc.parse<0>(&buffer[0]); - rootNode = doc.first_node("mame"); + rootNode = doc.first_node("mame"); - sqlite3_exec(handle, "BEGIN IMMEDIATE TRANSACTION;", NULL, NULL, &error); - for (rapidxml::xml_node<> * game = rootNode->first_node("game"); game; game = game->next_sibling()) - { - rapidxml::xml_attribute<> *nameNode = game->first_attribute("name"); - rapidxml::xml_attribute<> *cloneOfXml = game->first_attribute("cloneof"); + sqlite3_exec(handle, "BEGIN IMMEDIATE TRANSACTION;", NULL, NULL, &error); + for (rapidxml::xml_node<> * game = rootNode->first_node("game"); game; game = game->next_sibling()) + { + rapidxml::xml_attribute<> *nameNode = game->first_attribute("name"); + rapidxml::xml_attribute<> *cloneOfXml = game->first_attribute("cloneof"); - if(nameNode != NULL) - { - std::string name = nameNode->value(); - rapidxml::xml_node<> *descriptionNode = game->first_node("description"); - rapidxml::xml_node<> *yearNode = game->first_node("year"); - rapidxml::xml_node<> *manufacturerNode = game->first_node("manufacturer"); - rapidxml::xml_node<> *inputNode = game->first_node("input"); + if(nameNode != NULL) + { + std::string name = nameNode->value(); + rapidxml::xml_node<> *descriptionNode = game->first_node("description"); + rapidxml::xml_node<> *yearNode = game->first_node("year"); + rapidxml::xml_node<> *manufacturerNode = game->first_node("manufacturer"); + rapidxml::xml_node<> *inputNode = game->first_node("input"); - std::string description = (descriptionNode == NULL) ? nameNode->value() : descriptionNode->value(); - std::string year = (yearNode == NULL) ? "" : yearNode->value(); - std::string manufacturer = (manufacturerNode == NULL) ? "" : manufacturerNode->value(); - std::string cloneOf = (cloneOfXml == NULL) ? "" : cloneOfXml->value(); - std::string players; - std::string buttons; + std::string description = (descriptionNode == NULL) ? nameNode->value() : descriptionNode->value(); + std::string year = (yearNode == NULL) ? "" : yearNode->value(); + std::string manufacturer = (manufacturerNode == NULL) ? "" : manufacturerNode->value(); + std::string cloneOf = (cloneOfXml == NULL) ? "" : cloneOfXml->value(); + std::string players; + std::string buttons; - if(inputNode != NULL) - { - rapidxml::xml_attribute<> *playersAttribute = inputNode->first_attribute("players"); - rapidxml::xml_attribute<> *buttonsAttribute = inputNode->first_attribute("buttons"); + if(inputNode != NULL) + { + rapidxml::xml_attribute<> *playersAttribute = inputNode->first_attribute("players"); + rapidxml::xml_attribute<> *buttonsAttribute = inputNode->first_attribute("buttons"); - if(playersAttribute) - { - players = playersAttribute->value(); - } + if(playersAttribute) + { + players = playersAttribute->value(); + } - if(buttonsAttribute) - { - buttons = buttonsAttribute->value(); - } + if(buttonsAttribute) + { + buttons = buttonsAttribute->value(); + } - } + } - sqlite3_stmt *stmt; - sqlite3_prepare_v2(handle, - "UPDATE OR REPLACE Meta SET title=?, year=?, manufacturer=?, players=?, buttons=?, cloneOf=? WHERE name=? AND collectionName=?;", - -1, &stmt, 0); + sqlite3_stmt *stmt; + sqlite3_prepare_v2(handle, + "UPDATE OR REPLACE Meta SET title=?, year=?, manufacturer=?, players=?, buttons=?, cloneOf=? WHERE name=? AND collectionName=?;", + -1, &stmt, 0); - sqlite3_bind_text(stmt, 1, description.c_str(), -1, SQLITE_TRANSIENT); - sqlite3_bind_text(stmt, 2, year.c_str(), -1, SQLITE_TRANSIENT); - sqlite3_bind_text(stmt, 3, manufacturer.c_str(), -1, SQLITE_TRANSIENT); - sqlite3_bind_text(stmt, 4, players.c_str(), -1, SQLITE_TRANSIENT); - sqlite3_bind_text(stmt, 5, buttons.c_str(), -1, SQLITE_TRANSIENT); - sqlite3_bind_text(stmt, 6, cloneOf.c_str(), -1, SQLITE_TRANSIENT); - sqlite3_bind_text(stmt, 7, name.c_str(), -1, SQLITE_TRANSIENT); - sqlite3_bind_text(stmt, 8, collection.c_str(), -1, SQLITE_TRANSIENT); + sqlite3_bind_text(stmt, 1, description.c_str(), -1, SQLITE_TRANSIENT); + sqlite3_bind_text(stmt, 2, year.c_str(), -1, SQLITE_TRANSIENT); + sqlite3_bind_text(stmt, 3, manufacturer.c_str(), -1, SQLITE_TRANSIENT); + sqlite3_bind_text(stmt, 4, players.c_str(), -1, SQLITE_TRANSIENT); + sqlite3_bind_text(stmt, 5, buttons.c_str(), -1, SQLITE_TRANSIENT); + sqlite3_bind_text(stmt, 6, cloneOf.c_str(), -1, SQLITE_TRANSIENT); + sqlite3_bind_text(stmt, 7, name.c_str(), -1, SQLITE_TRANSIENT); + sqlite3_bind_text(stmt, 8, collection.c_str(), -1, SQLITE_TRANSIENT); - sqlite3_step(stmt); - sqlite3_finalize(stmt); + sqlite3_step(stmt); + sqlite3_finalize(stmt); - } - } - sqlite3_exec(handle, "COMMIT TRANSACTION;", NULL, NULL, &error); + } + } + sqlite3_exec(handle, "COMMIT TRANSACTION;", NULL, NULL, &error); - } + } - return retVal; + return retVal; } diff --git a/Source/Database/MamelistMetadata.h b/Source/Database/MamelistMetadata.h index 4cb0b66..3ad87a0 100644 --- a/Source/Database/MamelistMetadata.h +++ b/Source/Database/MamelistMetadata.h @@ -1,5 +1,5 @@ -/* This file is subject to the terms and conditions defined in - * file 'LICENSE.txt', which is part of this source code package. +/* This file is subject to the terms and conditions defined in + * file 'LICENSE.txt', which is part of this source code package. */ #pragma once @@ -10,9 +10,9 @@ class DB; class MamelistMetadata : Metadata { public: - MamelistMetadata(DB *dbInstance); - virtual ~MamelistMetadata(); - bool Import(std::string file, std::string collectionName); + MamelistMetadata(DB *dbInstance); + virtual ~MamelistMetadata(); + bool Import(std::string file, std::string collectionName); private: - DB *DBInstance; + DB *DBInstance; }; diff --git a/Source/Database/Metadata.h b/Source/Database/Metadata.h index 504ff7a..3ab03c1 100644 --- a/Source/Database/Metadata.h +++ b/Source/Database/Metadata.h @@ -5,6 +5,6 @@ class Metadata { public: - virtual ~Metadata() {} - virtual bool Import(std::string file, std::string collectionName) = 0; + virtual ~Metadata() {} + virtual bool Import(std::string file, std::string collectionName) = 0; }; diff --git a/Source/Execute/Launcher.cpp b/Source/Execute/Launcher.cpp index 51d22b6..937d37f 100644 --- a/Source/Execute/Launcher.cpp +++ b/Source/Execute/Launcher.cpp @@ -1,5 +1,5 @@ -/* This file is subject to the terms and conditions defined in - * file 'LICENSE.txt', which is part of this source code package. +/* This file is subject to the terms and conditions defined in + * file 'LICENSE.txt', which is part of this source code package. */ #include "Launcher.h" #include "../Collection/Item.h" @@ -18,309 +18,309 @@ #endif Launcher::Launcher(RetroFE *p) -: Config(p->GetConfiguration()) -, RetroFEInst(p) + : Config(p->GetConfiguration()) + , RetroFEInst(p) { } bool Launcher::Run(std::string collection, Item *collectionItem) { - std::string launcherName = collectionItem->GetLauncher(); - std::string executablePath; - std::string selectedItemsDirectory; - std::string selectedItemsPath; - std::string currentDirectory; - std::string extensions; - std::string matchedExtension; - std::string args; + std::string launcherName = collectionItem->GetLauncher(); + std::string executablePath; + std::string selectedItemsDirectory; + std::string selectedItemsPath; + std::string currentDirectory; + std::string extensions; + std::string matchedExtension; + std::string args; - if(!GetLauncherExecutable(executablePath, currentDirectory, launcherName)) - { - Logger::Write(Logger::ZONE_ERROR, "Launcher", "Failed to find launcher executable (launcher: " + launcherName + " executable: " + executablePath + ")"); - return false; - } - if(!GetExtensions(extensions, collection)) - { - Logger::Write(Logger::ZONE_ERROR, "Launcher", "No file extensions configured for collection \"" + collection + "\""); - return false; - } - if(!GetCollectionDirectory(selectedItemsDirectory, collection)) - { - Logger::Write(Logger::ZONE_ERROR, "Launcher", "Could not find files in directory \"" + selectedItemsDirectory + "\" for collection \"" + collection + "\""); - return false; - } - if(!GetLauncherArgs(args, launcherName)) - { - Logger::Write(Logger::ZONE_ERROR, "Launcher", "No launcher arguments specified for launcher " + launcherName); - return false; - } - if(!FindFile(selectedItemsPath, matchedExtension, selectedItemsDirectory, collectionItem->GetName(), extensions)) - { - // FindFile() prints out diagnostic messages for us, no need to print anything here - return false; - } - args = ReplaceVariables(args, - selectedItemsPath, - collectionItem->GetName(), - collectionItem->GetFileName(), - selectedItemsDirectory, - collection); + if(!GetLauncherExecutable(executablePath, currentDirectory, launcherName)) + { + Logger::Write(Logger::ZONE_ERROR, "Launcher", "Failed to find launcher executable (launcher: " + launcherName + " executable: " + executablePath + ")"); + return false; + } + if(!GetExtensions(extensions, collection)) + { + Logger::Write(Logger::ZONE_ERROR, "Launcher", "No file extensions configured for collection \"" + collection + "\""); + return false; + } + if(!GetCollectionDirectory(selectedItemsDirectory, collection)) + { + Logger::Write(Logger::ZONE_ERROR, "Launcher", "Could not find files in directory \"" + selectedItemsDirectory + "\" for collection \"" + collection + "\""); + return false; + } + if(!GetLauncherArgs(args, launcherName)) + { + Logger::Write(Logger::ZONE_ERROR, "Launcher", "No launcher arguments specified for launcher " + launcherName); + return false; + } + if(!FindFile(selectedItemsPath, matchedExtension, selectedItemsDirectory, collectionItem->GetName(), extensions)) + { + // FindFile() prints out diagnostic messages for us, no need to print anything here + return false; + } + args = ReplaceVariables(args, + selectedItemsPath, + collectionItem->GetName(), + collectionItem->GetFileName(), + selectedItemsDirectory, + collection); - executablePath = ReplaceVariables(executablePath, - selectedItemsPath, - collectionItem->GetName(), - collectionItem->GetFileName(), - selectedItemsDirectory, - collection); + executablePath = ReplaceVariables(executablePath, + selectedItemsPath, + collectionItem->GetName(), + collectionItem->GetFileName(), + selectedItemsDirectory, + collection); - currentDirectory = ReplaceVariables(currentDirectory, - selectedItemsPath, - collectionItem->GetName(), - collectionItem->GetFileName(), - selectedItemsDirectory, - collection); + currentDirectory = ReplaceVariables(currentDirectory, + selectedItemsPath, + collectionItem->GetName(), + collectionItem->GetFileName(), + selectedItemsDirectory, + collection); - if(!ExecuteCommand(executablePath, args, currentDirectory)) - { - Logger::Write(Logger::ZONE_ERROR, "Launcher", "Failed to launch."); - return false; - } + if(!ExecuteCommand(executablePath, args, currentDirectory)) + { + Logger::Write(Logger::ZONE_ERROR, "Launcher", "Failed to launch."); + return false; + } - return true; + return true; } std::string Launcher::ReplaceVariables(std::string str, - std::string itemFilePath, - std::string itemName, - std::string itemFilename, - std::string itemDirectory, - std::string itemCollectionName) + std::string itemFilePath, + std::string itemName, + std::string itemFilename, + std::string itemDirectory, + std::string itemCollectionName) { - str = Utils::Replace(str, "%ITEM_FILEPATH%", itemFilePath); - str = Utils::Replace(str, "%ITEM_NAME%", itemName); - str = Utils::Replace(str, "%ITEM_FILENAME%", itemFilename); - str = Utils::Replace(str, "%ITEM_DIRECTORY%", itemDirectory); - str = Utils::Replace(str, "%ITEM_COLLECTION_NAME%", itemCollectionName); - str = Utils::Replace(str, "%RETROFE_PATH%", Configuration::GetAbsolutePath()); + str = Utils::Replace(str, "%ITEM_FILEPATH%", itemFilePath); + str = Utils::Replace(str, "%ITEM_NAME%", itemName); + str = Utils::Replace(str, "%ITEM_FILENAME%", itemFilename); + str = Utils::Replace(str, "%ITEM_DIRECTORY%", itemDirectory); + str = Utils::Replace(str, "%ITEM_COLLECTION_NAME%", itemCollectionName); + str = Utils::Replace(str, "%RETROFE_PATH%", Configuration::GetAbsolutePath()); #ifdef WIN32 - str = Utils::Replace(str, "%RETROFE_EXEC_PATH%", Configuration::GetAbsolutePath() + "/RetroFE.exe"); + str = Utils::Replace(str, "%RETROFE_EXEC_PATH%", Configuration::GetAbsolutePath() + "/RetroFE.exe"); #else - str = Utils::Replace(str, "%RETROFE_EXEC_PATH%", Configuration::GetAbsolutePath() + "/RetroFE"); + str = Utils::Replace(str, "%RETROFE_EXEC_PATH%", Configuration::GetAbsolutePath() + "/RetroFE"); #endif - return str; + return str; } bool Launcher::ExecuteCommand(std::string executable, std::string args, std::string currentDirectory) { - bool retVal = false; - std::string executionString = "\"" + executable + "\" " + args; + bool retVal = false; + std::string executionString = "\"" + executable + "\" " + args; - Logger::Write(Logger::ZONE_INFO, "Launcher", "Attempting to launch: " + executionString); - Logger::Write(Logger::ZONE_INFO, "Launcher", " from within folder: " + currentDirectory); + Logger::Write(Logger::ZONE_INFO, "Launcher", "Attempting to launch: " + executionString); + Logger::Write(Logger::ZONE_INFO, "Launcher", " from within folder: " + currentDirectory); - //todo: use delegation instead of depending on knowing the RetroFE class (tie to an interface) - RetroFEInst->LaunchEnter(); + //todo: use delegation instead of depending on knowing the RetroFE class (tie to an interface) + RetroFEInst->LaunchEnter(); #ifdef WIN32 - STARTUPINFO startupInfo; - PROCESS_INFORMATION processInfo; - char applicationName[256]; - char currDir[256]; - memset(&applicationName, 0, sizeof(applicationName)); - memset(&startupInfo, 0, sizeof(startupInfo)); - memset(&processInfo, 0, sizeof(processInfo)); - strncpy(applicationName, executionString.c_str(), sizeof(applicationName)); - strncpy(currDir, currentDirectory.c_str(), sizeof(currDir)); - startupInfo.dwFlags = STARTF_USESTDHANDLES; - startupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE); - startupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); - startupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE); - startupInfo.wShowWindow = SW_SHOWDEFAULT; + STARTUPINFO startupInfo; + PROCESS_INFORMATION processInfo; + char applicationName[256]; + char currDir[256]; + memset(&applicationName, 0, sizeof(applicationName)); + memset(&startupInfo, 0, sizeof(startupInfo)); + memset(&processInfo, 0, sizeof(processInfo)); + strncpy(applicationName, executionString.c_str(), sizeof(applicationName)); + strncpy(currDir, currentDirectory.c_str(), sizeof(currDir)); + startupInfo.dwFlags = STARTF_USESTDHANDLES; + startupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE); + startupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); + startupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE); + startupInfo.wShowWindow = SW_SHOWDEFAULT; - if(!CreateProcess(NULL, applicationName, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &startupInfo, &processInfo)) + if(!CreateProcess(NULL, applicationName, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &startupInfo, &processInfo)) #else - if(system(executionString.c_str()) != 0) + if(system(executionString.c_str()) != 0) #endif - { - Logger::Write(Logger::ZONE_ERROR, "Launcher", "Failed to run: " + executable); - } + { + Logger::Write(Logger::ZONE_ERROR, "Launcher", "Failed to run: " + executable); + } - else - { + else + { #ifdef WIN32 - while(WAIT_OBJECT_0 != MsgWaitForMultipleObjects(1, &processInfo.hProcess, FALSE, INFINITE, QS_ALLINPUT)) - { - MSG msg; - while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) - { - DispatchMessage(&msg); - } - } + while(WAIT_OBJECT_0 != MsgWaitForMultipleObjects(1, &processInfo.hProcess, FALSE, INFINITE, QS_ALLINPUT)) + { + MSG msg; + while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) + { + DispatchMessage(&msg); + } + } - // result = GetExitCodeProcess(processInfo.hProcess, &exitCode); - CloseHandle(processInfo.hProcess); + // result = GetExitCodeProcess(processInfo.hProcess, &exitCode); + CloseHandle(processInfo.hProcess); #endif - retVal = true; - } + retVal = true; + } - Logger::Write(Logger::ZONE_INFO, "Launcher", "Completed"); - RetroFEInst->LaunchExit(); + Logger::Write(Logger::ZONE_INFO, "Launcher", "Completed"); + RetroFEInst->LaunchExit(); - return retVal; + return retVal; } bool Launcher::GetLauncherName(std::string &launcherName, std::string collection) { - std::string launcherKey = "collections." + collection + ".launcher"; + std::string launcherKey = "collections." + collection + ".launcher"; - // find the launcher for the particular item - if(!Config->GetProperty(launcherKey, launcherName)) - { - std::stringstream ss; + // find the launcher for the particular item + if(!Config->GetProperty(launcherKey, launcherName)) + { + std::stringstream ss; - ss << "Launch failed. Could not find a configured launcher for collection \"" - << collection - << "\" (could not find a property for \"" - << launcherKey - << "\")"; + ss << "Launch failed. Could not find a configured launcher for collection \"" + << collection + << "\" (could not find a property for \"" + << launcherKey + << "\")"; - Logger::Write(Logger::ZONE_ERROR, "Launcher", ss.str()); + Logger::Write(Logger::ZONE_ERROR, "Launcher", ss.str()); - return false; - } + return false; + } - std::stringstream ss; - ss << "collections." - << collection - << " is configured to use launchers." - << launcherName - << "\""; + std::stringstream ss; + ss << "collections." + << collection + << " is configured to use launchers." + << launcherName + << "\""; - Logger::Write(Logger::ZONE_DEBUG, "Launcher", ss.str()); + Logger::Write(Logger::ZONE_DEBUG, "Launcher", ss.str()); - return true; + return true; } bool Launcher::GetLauncherExecutable(std::string &executable, std::string ¤tDirectory, std::string launcherName) { - std::string executableKey = "launchers." + launcherName + ".executable"; + std::string executableKey = "launchers." + launcherName + ".executable"; - if(!Config->GetProperty(executableKey, executable)) - { - return false; - } + if(!Config->GetProperty(executableKey, executable)) + { + return false; + } - std::string currentDirectoryKey = "launchers." + launcherName + ".currentDirectory"; - currentDirectory = Utils::GetDirectory(executable); + std::string currentDirectoryKey = "launchers." + launcherName + ".currentDirectory"; + currentDirectory = Utils::GetDirectory(executable); - Config->GetProperty(currentDirectoryKey, currentDirectory); + Config->GetProperty(currentDirectoryKey, currentDirectory); - return true; + return true; } bool Launcher::GetLauncherArgs(std::string &args, std::string launcherName) { - std::string argsKey = "launchers." + launcherName + ".arguments"; + std::string argsKey = "launchers." + launcherName + ".arguments"; - if(!Config->GetProperty(argsKey, args)) - { - Logger::Write(Logger::ZONE_ERROR, "Launcher", "No arguments specified for: " + argsKey); + if(!Config->GetProperty(argsKey, args)) + { + Logger::Write(Logger::ZONE_ERROR, "Launcher", "No arguments specified for: " + argsKey); - return false; - } - return true; + return false; + } + return true; } bool Launcher::GetExtensions(std::string &extensions, std::string collection) { - std::string extensionsKey = "collections." + collection + ".list.extensions"; + std::string extensionsKey = "collections." + collection + ".list.extensions"; - if(!Config->GetProperty(extensionsKey, extensions)) - { - Logger::Write(Logger::ZONE_ERROR, "Launcher", "No extensions specified for: " + extensionsKey); - return false; - } + if(!Config->GetProperty(extensionsKey, extensions)) + { + Logger::Write(Logger::ZONE_ERROR, "Launcher", "No extensions specified for: " + extensionsKey); + return false; + } - extensions = Utils::Replace(extensions, " ", ""); - extensions = Utils::Replace(extensions, ".", ""); + extensions = Utils::Replace(extensions, " ", ""); + extensions = Utils::Replace(extensions, ".", ""); - return true; + return true; } bool Launcher::GetCollectionDirectory(std::string &directory, std::string collection) { - std::string itemsPathKey = "collections." + collection + ".list.path"; - std::string itemsPathValue; + std::string itemsPathKey = "collections." + collection + ".list.path"; + std::string itemsPathValue; - // find the items path folder (i.e. ROM path) - if(!Config->GetPropertyAbsolutePath(itemsPathKey, itemsPathValue)) - { - directory = ""; - } - else - { - directory += itemsPathValue + "/"; - } + // find the items path folder (i.e. ROM path) + if(!Config->GetPropertyAbsolutePath(itemsPathKey, itemsPathValue)) + { + directory = ""; + } + else + { + directory += itemsPathValue + "/"; + } - return true; + return true; } bool Launcher::FindFile(std::string &foundFilePath, std::string &foundFilename, std::string directory, std::string filenameWithoutExtension, std::string extensions) { - std::string extension; - bool fileFound = false; - std::stringstream ss; - ss << extensions; + std::string extension; + bool fileFound = false; + std::stringstream ss; + ss << extensions; - while(!fileFound && std::getline(ss, extension, ',') ) - { - std::string selectedItemsPath = directory + filenameWithoutExtension + "." + extension; - std::ifstream f(selectedItemsPath.c_str()); + while(!fileFound && std::getline(ss, extension, ',') ) + { + std::string selectedItemsPath = directory + filenameWithoutExtension + "." + extension; + std::ifstream f(selectedItemsPath.c_str()); - if (f.good()) - { - std::stringstream ss; + if (f.good()) + { + std::stringstream ss; - ss <<"Checking to see if \"" - << selectedItemsPath << "\" exists [Yes]"; + ss <<"Checking to see if \"" + << selectedItemsPath << "\" exists [Yes]"; - fileFound = true; + fileFound = true; - Logger::Write(Logger::ZONE_INFO, "Launcher", ss.str()); + Logger::Write(Logger::ZONE_INFO, "Launcher", ss.str()); - foundFilePath = selectedItemsPath; - foundFilename = extension; - } - else - { - std::stringstream ss; + foundFilePath = selectedItemsPath; + foundFilename = extension; + } + else + { + std::stringstream ss; - ss << "Checking to see if \"" - << selectedItemsPath << "\" exists [No]"; + ss << "Checking to see if \"" + << selectedItemsPath << "\" exists [No]"; - Logger::Write(Logger::ZONE_WARNING, "Launcher", ss.str()); - } + Logger::Write(Logger::ZONE_WARNING, "Launcher", ss.str()); + } - f.close(); - } + f.close(); + } - // get the launchers executable + // get the launchers executable - if(!fileFound) - { - std::stringstream ss; - ss <<"Could not find any files with the name \"" - << filenameWithoutExtension << "\" in folder \"" - << directory; + if(!fileFound) + { + std::stringstream ss; + ss <<"Could not find any files with the name \"" + << filenameWithoutExtension << "\" in folder \"" + << directory; - Logger::Write(Logger::ZONE_ERROR, "Launcher", ss.str()); + Logger::Write(Logger::ZONE_ERROR, "Launcher", ss.str()); - } + } - return fileFound; + return fileFound; } diff --git a/Source/Execute/Launcher.h b/Source/Execute/Launcher.h index ca70e6f..efc022b 100644 --- a/Source/Execute/Launcher.h +++ b/Source/Execute/Launcher.h @@ -1,5 +1,5 @@ -/* This file is subject to the terms and conditions defined in - * file 'LICENSE.txt', which is part of this source code package. +/* This file is subject to the terms and conditions defined in + * file 'LICENSE.txt', which is part of this source code package. */ #pragma once @@ -12,29 +12,29 @@ class RetroFE; class Launcher { public: - Launcher(RetroFE *p); - bool Run(std::string collection, Item *collectionItem); + Launcher(RetroFE *p); + bool Run(std::string collection, Item *collectionItem); private: - std::string ReplaceString( - std::string subject, - const std::string &search, - const std::string &replace); + std::string ReplaceString( + std::string subject, + const std::string &search, + const std::string &replace); - bool GetLauncherName(std::string &launcherName, std::string collection); - bool GetLauncherExecutable(std::string &executable, std::string ¤tDirectory, std::string launcherName); - bool GetLauncherArgs(std::string &args, std::string launcherName); - bool GetExtensions(std::string &extensions, std::string launcherName); - bool GetCollectionDirectory(std::string &directory, std::string collection); - bool ExecuteCommand(std::string executable, std::string arguments, std::string currentDirectory); - bool FindFile(std::string &foundFilePath, std::string &foundFilename, std::string directory, std::string filenameWithoutExtension, std::string extensions); - std::string ReplaceVariables(std::string str, - std::string itemFilePath, - std::string itemName, - std::string itemFilename, - std::string itemDirectory, - std::string itemCollectionName); + bool GetLauncherName(std::string &launcherName, std::string collection); + bool GetLauncherExecutable(std::string &executable, std::string ¤tDirectory, std::string launcherName); + bool GetLauncherArgs(std::string &args, std::string launcherName); + bool GetExtensions(std::string &extensions, std::string launcherName); + bool GetCollectionDirectory(std::string &directory, std::string collection); + bool ExecuteCommand(std::string executable, std::string arguments, std::string currentDirectory); + bool FindFile(std::string &foundFilePath, std::string &foundFilename, std::string directory, std::string filenameWithoutExtension, std::string extensions); + std::string ReplaceVariables(std::string str, + std::string itemFilePath, + std::string itemName, + std::string itemFilename, + std::string itemDirectory, + std::string itemCollectionName); - Configuration *Config; - RetroFE *RetroFEInst; + Configuration *Config; + RetroFE *RetroFEInst; }; diff --git a/Source/Graphics/Animate/Tween.cpp b/Source/Graphics/Animate/Tween.cpp index 5cd926f..ed91f72 100644 --- a/Source/Graphics/Animate/Tween.cpp +++ b/Source/Graphics/Animate/Tween.cpp @@ -11,360 +11,360 @@ std::map Tween::TweenTypeMap; std::map Tween::TweenPropertyMap; Tween::Tween(TweenProperty property, TweenAlgorithm type, double start, double end, double duration) -: Property(property) -, Type(type) -, Start(start) -, End(end) -, Duration(duration) + : Property(property) + , Type(type) + , Start(start) + , End(end) + , Duration(duration) { } TweenProperty Tween::GetProperty() const { - return Property; + return Property; } bool Tween::GetTweenProperty(std::string name, TweenProperty &property) { - bool retVal = false; + bool retVal = false; - if(TweenPropertyMap.size() == 0) - { - TweenPropertyMap["x"] = TWEEN_PROPERTY_X; - TweenPropertyMap["y"] = TWEEN_PROPERTY_Y; - TweenPropertyMap["angle"] = TWEEN_PROPERTY_ANGLE; - TweenPropertyMap["transparency"] = TWEEN_PROPERTY_TRANSPARENCY; - TweenPropertyMap["width"] = TWEEN_PROPERTY_WIDTH; - TweenPropertyMap["height"] = TWEEN_PROPERTY_HEIGHT; - TweenPropertyMap["xorigin"] = TWEEN_PROPERTY_X_ORIGIN; - TweenPropertyMap["yorigin"] = TWEEN_PROPERTY_Y_ORIGIN; - TweenPropertyMap["xoffset"] = TWEEN_PROPERTY_X_OFFSET; - TweenPropertyMap["yoffset"] = TWEEN_PROPERTY_Y_OFFSET; - TweenPropertyMap["fontSize"] = TWEEN_PROPERTY_FONT_SIZE; - } + if(TweenPropertyMap.size() == 0) + { + TweenPropertyMap["x"] = TWEEN_PROPERTY_X; + TweenPropertyMap["y"] = TWEEN_PROPERTY_Y; + TweenPropertyMap["angle"] = TWEEN_PROPERTY_ANGLE; + TweenPropertyMap["transparency"] = TWEEN_PROPERTY_TRANSPARENCY; + TweenPropertyMap["width"] = TWEEN_PROPERTY_WIDTH; + TweenPropertyMap["height"] = TWEEN_PROPERTY_HEIGHT; + TweenPropertyMap["xorigin"] = TWEEN_PROPERTY_X_ORIGIN; + TweenPropertyMap["yorigin"] = TWEEN_PROPERTY_Y_ORIGIN; + TweenPropertyMap["xoffset"] = TWEEN_PROPERTY_X_OFFSET; + TweenPropertyMap["yoffset"] = TWEEN_PROPERTY_Y_OFFSET; + TweenPropertyMap["fontSize"] = TWEEN_PROPERTY_FONT_SIZE; + } - std::transform(name.begin(), name.end(), name.begin(), ::tolower); + std::transform(name.begin(), name.end(), name.begin(), ::tolower); - if(TweenPropertyMap.find(name) != TweenPropertyMap.end()) - { - property = TweenPropertyMap[name]; - retVal = true; - } + if(TweenPropertyMap.find(name) != TweenPropertyMap.end()) + { + property = TweenPropertyMap[name]; + retVal = true; + } - return retVal; + return retVal; } TweenAlgorithm Tween::GetTweenType(std::string name) { - if(TweenTypeMap.size() == 0) - { - TweenTypeMap["easeinquadratic"] = EASE_IN_QUADRATIC; - TweenTypeMap["easeoutquadratic"] = EASE_OUT_QUADRATIC; - TweenTypeMap["easeinoutquadratic"] = EASE_INOUT_QUADRATIC; - TweenTypeMap["easeincubic"] = EASE_IN_CUBIC; - TweenTypeMap["easeoutcubic"] = EASE_OUT_CUBIC; - TweenTypeMap["easeinoutcubic"] = EASE_INOUT_CUBIC; - TweenTypeMap["easeinquartic"] = EASE_IN_QUARTIC; - TweenTypeMap["easeoutquartic"] = EASE_OUT_QUARTIC; - TweenTypeMap["easeinoutquartic"] = EASE_INOUT_QUARTIC; - TweenTypeMap["easeinquintic"] = EASE_IN_QUINTIC; - TweenTypeMap["easeoutquintic"] = EASE_OUT_QUINTIC; - TweenTypeMap["easeinoutquintic"] = EASE_INOUT_QUINTIC; - TweenTypeMap["easeinsine"] = EASE_IN_SINE; - TweenTypeMap["easeoutsine"] = EASE_OUT_SINE; - TweenTypeMap["easeinoutsine"] = EASE_INOUT_SINE; - TweenTypeMap["easeinexponential"] = EASE_IN_EXPONENTIAL; - TweenTypeMap["easeoutexponential"] = EASE_OUT_EXPONENTIAL; - TweenTypeMap["easeinoutexponential"] = EASE_INOUT_EXPONENTIAL; - TweenTypeMap["easeincircular"] = EASE_IN_CIRCULAR; - TweenTypeMap["easeoutcircular"] = EASE_OUT_CIRCULAR; - TweenTypeMap["easeinoutcircular"] = EASE_INOUT_CIRCULAR; - TweenTypeMap["linear"] = LINEAR; - } + if(TweenTypeMap.size() == 0) + { + TweenTypeMap["easeinquadratic"] = EASE_IN_QUADRATIC; + TweenTypeMap["easeoutquadratic"] = EASE_OUT_QUADRATIC; + TweenTypeMap["easeinoutquadratic"] = EASE_INOUT_QUADRATIC; + TweenTypeMap["easeincubic"] = EASE_IN_CUBIC; + TweenTypeMap["easeoutcubic"] = EASE_OUT_CUBIC; + TweenTypeMap["easeinoutcubic"] = EASE_INOUT_CUBIC; + TweenTypeMap["easeinquartic"] = EASE_IN_QUARTIC; + TweenTypeMap["easeoutquartic"] = EASE_OUT_QUARTIC; + TweenTypeMap["easeinoutquartic"] = EASE_INOUT_QUARTIC; + TweenTypeMap["easeinquintic"] = EASE_IN_QUINTIC; + TweenTypeMap["easeoutquintic"] = EASE_OUT_QUINTIC; + TweenTypeMap["easeinoutquintic"] = EASE_INOUT_QUINTIC; + TweenTypeMap["easeinsine"] = EASE_IN_SINE; + TweenTypeMap["easeoutsine"] = EASE_OUT_SINE; + TweenTypeMap["easeinoutsine"] = EASE_INOUT_SINE; + TweenTypeMap["easeinexponential"] = EASE_IN_EXPONENTIAL; + TweenTypeMap["easeoutexponential"] = EASE_OUT_EXPONENTIAL; + TweenTypeMap["easeinoutexponential"] = EASE_INOUT_EXPONENTIAL; + TweenTypeMap["easeincircular"] = EASE_IN_CIRCULAR; + TweenTypeMap["easeoutcircular"] = EASE_OUT_CIRCULAR; + TweenTypeMap["easeinoutcircular"] = EASE_INOUT_CIRCULAR; + TweenTypeMap["linear"] = LINEAR; + } - std::transform(name.begin(), name.end(), name.begin(), ::tolower); + std::transform(name.begin(), name.end(), name.begin(), ::tolower); - if(TweenTypeMap.find(name) != TweenTypeMap.end()) - { - return TweenTypeMap[name]; - } - else - { - return TweenTypeMap["linear"]; - } + if(TweenTypeMap.find(name) != TweenTypeMap.end()) + { + return TweenTypeMap[name]; + } + else + { + return TweenTypeMap["linear"]; + } } float Tween::Animate(double elapsedTime) { - return AnimateSingle(Type, Start, End, Duration, elapsedTime); + return AnimateSingle(Type, Start, End, Duration, elapsedTime); } //todo: SDL likes floats, consider having casting being performed elsewhere float Tween::AnimateSingle(TweenAlgorithm type, double start, double end, double duration, double elapsedTime) { - double a = start; - double b = end - start; - double result = 0; + double a = start; + double b = end - start; + double result = 0; - switch(type) - { - case EASE_IN_QUADRATIC: - result = EaseInQuadratic(elapsedTime, duration, a, b); - break; + switch(type) + { + case EASE_IN_QUADRATIC: + result = EaseInQuadratic(elapsedTime, duration, a, b); + break; - case EASE_OUT_QUADRATIC: - result = EaseOutQuadratic(elapsedTime, duration, a, b); - break; + case EASE_OUT_QUADRATIC: + result = EaseOutQuadratic(elapsedTime, duration, a, b); + break; - case EASE_INOUT_QUADRATIC: - result = EaseInOutQuadratic(elapsedTime, duration, a, b); - break; + case EASE_INOUT_QUADRATIC: + result = EaseInOutQuadratic(elapsedTime, duration, a, b); + break; - case EASE_IN_CUBIC: - result = EaseInCubic(elapsedTime, duration, a, b); - break; + case EASE_IN_CUBIC: + result = EaseInCubic(elapsedTime, duration, a, b); + break; - case EASE_OUT_CUBIC: - result = EaseOutCubic(elapsedTime, duration, a, b); - break; + case EASE_OUT_CUBIC: + result = EaseOutCubic(elapsedTime, duration, a, b); + break; - case EASE_INOUT_CUBIC: - result = EaseInOutCubic(elapsedTime, duration, a, b); - break; + case EASE_INOUT_CUBIC: + result = EaseInOutCubic(elapsedTime, duration, a, b); + break; - case EASE_IN_QUARTIC: - result = EaseInQuartic(elapsedTime, duration, a, b); - break; + case EASE_IN_QUARTIC: + result = EaseInQuartic(elapsedTime, duration, a, b); + break; - case EASE_OUT_QUARTIC: - result = EaseOutQuartic(elapsedTime, duration, a, b); - break; + case EASE_OUT_QUARTIC: + result = EaseOutQuartic(elapsedTime, duration, a, b); + break; - case EASE_INOUT_QUARTIC: - result = EaseInOutQuartic(elapsedTime, duration, a, b); - break; + case EASE_INOUT_QUARTIC: + result = EaseInOutQuartic(elapsedTime, duration, a, b); + break; - case EASE_IN_QUINTIC: - result = EaseInQuintic(elapsedTime, duration, a, b); - break; + case EASE_IN_QUINTIC: + result = EaseInQuintic(elapsedTime, duration, a, b); + break; - case EASE_OUT_QUINTIC: - result = EaseOutQuintic(elapsedTime, duration, a, b); - break; + case EASE_OUT_QUINTIC: + result = EaseOutQuintic(elapsedTime, duration, a, b); + break; - case EASE_INOUT_QUINTIC: - result = EaseInOutQuintic(elapsedTime, duration, a, b); - break; + case EASE_INOUT_QUINTIC: + result = EaseInOutQuintic(elapsedTime, duration, a, b); + break; - case EASE_IN_SINE: - result = EaseInSine(elapsedTime, duration, a, b); - break; + case EASE_IN_SINE: + result = EaseInSine(elapsedTime, duration, a, b); + break; - case EASE_OUT_SINE: - result = EaseOutSine(elapsedTime, duration, a, b); - break; + case EASE_OUT_SINE: + result = EaseOutSine(elapsedTime, duration, a, b); + break; - case EASE_INOUT_SINE: - result = EaseInOutSine(elapsedTime, duration, a, b); - break; + case EASE_INOUT_SINE: + result = EaseInOutSine(elapsedTime, duration, a, b); + break; - case EASE_IN_EXPONENTIAL: - result = EaseInExponential(elapsedTime, duration, a, b); - break; + case EASE_IN_EXPONENTIAL: + result = EaseInExponential(elapsedTime, duration, a, b); + break; - case EASE_OUT_EXPONENTIAL: - result = EaseOutExponential(elapsedTime, duration, a, b); - break; + case EASE_OUT_EXPONENTIAL: + result = EaseOutExponential(elapsedTime, duration, a, b); + break; - case EASE_INOUT_EXPONENTIAL: - result = EaseInOutExponential(elapsedTime, duration, a, b); - break; + case EASE_INOUT_EXPONENTIAL: + result = EaseInOutExponential(elapsedTime, duration, a, b); + break; - case EASE_IN_CIRCULAR: - result = EaseInCircular(elapsedTime, duration, a, b); - break; + case EASE_IN_CIRCULAR: + result = EaseInCircular(elapsedTime, duration, a, b); + break; - case EASE_OUT_CIRCULAR: - result = EaseOutCircular(elapsedTime, duration, a, b); - break; + case EASE_OUT_CIRCULAR: + result = EaseOutCircular(elapsedTime, duration, a, b); + break; - case EASE_INOUT_CIRCULAR: - result = EaseInOutCircular(elapsedTime, duration, a, b); - break; + case EASE_INOUT_CIRCULAR: + result = EaseInOutCircular(elapsedTime, duration, a, b); + break; - case LINEAR: - default: - result = Linear(elapsedTime, duration, a, b); - break; - } + case LINEAR: + default: + result = Linear(elapsedTime, duration, a, b); + break; + } - return static_cast(result); + return static_cast(result); } double Tween::Linear(double t, double d, double b, double c) { - if(d == 0) return b; - return c*t/d + b; + if(d == 0) return b; + return c*t/d + b; }; double Tween::EaseInQuadratic(double t, double d, double b, double c) { - if(d == 0) return b; - t /= d; - return c*t*t + b; + if(d == 0) return b; + t /= d; + return c*t*t + b; }; double Tween::EaseOutQuadratic(double t, double d, double b, double c) { - if(d == 0) return b; - t /= d; - return -c * t*(t-2) + b; + if(d == 0) return b; + t /= d; + return -c * t*(t-2) + b; }; double Tween::EaseInOutQuadratic(double t, double d, double b, double c) { - if(d == 0) return b; - t /= d/2; - if (t < 1) return c/2*t*t + b; - t--; - return -c/2 * (t*(t-2) - 1) + b; + if(d == 0) return b; + t /= d/2; + if (t < 1) return c/2*t*t + b; + t--; + return -c/2 * (t*(t-2) - 1) + b; }; double Tween::EaseInCubic(double t, double d, double b, double c) { - if(d == 0) return b; - t /= d; - return c*t*t*t + b; + if(d == 0) return b; + t /= d; + return c*t*t*t + b; }; double Tween::EaseOutCubic(double t, double d, double b, double c) { - if(d == 0) return b; - t /= d; - t--; - return c*(t*t*t + 1) + b; + if(d == 0) return b; + t /= d; + t--; + return c*(t*t*t + 1) + b; }; double Tween::EaseInOutCubic(double t, double d, double b, double c) { - if(d == 0) return b; - t /= d/2; - if (t < 1) return c/2*t*t*t + b; - t -= 2; - return c/2*(t*t*t + 2) + b; + if(d == 0) return b; + t /= d/2; + if (t < 1) return c/2*t*t*t + b; + t -= 2; + return c/2*(t*t*t + 2) + b; }; double Tween::EaseInQuartic(double t, double d, double b, double c) { - if(d == 0) return b; - t /= d; - return c*t*t*t*t + b; + if(d == 0) return b; + t /= d; + return c*t*t*t*t + b; }; double Tween::EaseOutQuartic(double t, double d, double b, double c) { - if(d == 0) return b; - t /= d; - t--; - return -c * (t*t*t*t - 1) + b; + if(d == 0) return b; + t /= d; + t--; + return -c * (t*t*t*t - 1) + b; }; double Tween::EaseInOutQuartic(double t, double d, double b, double c) { - if(d == 0) return b; - t /= d/2; - if (t < 1) return c/2*t*t*t*t + b; - t -= 2; - return -c/2 * (t*t*t*t - 2) + b; + if(d == 0) return b; + t /= d/2; + if (t < 1) return c/2*t*t*t*t + b; + t -= 2; + return -c/2 * (t*t*t*t - 2) + b; }; double Tween::EaseInQuintic(double t, double d, double b, double c) { - if(d == 0) return b; - t /= d; - return c*t*t*t*t*t + b; + if(d == 0) return b; + t /= d; + return c*t*t*t*t*t + b; }; double Tween::EaseOutQuintic(double t, double d, double b, double c) { - if(d == 0) return b; - t /= d; - t--; - return c*(t*t*t*t*t + 1) + b; + if(d == 0) return b; + t /= d; + t--; + return c*(t*t*t*t*t + 1) + b; }; double Tween::EaseInOutQuintic(double t, double d, double b, double c) { - if(d == 0) return b; - t /= d/2; - if (t < 1) return c/2*t*t*t*t*t + b; - t -= 2; - return c/2*(t*t*t*t*t + 2) + b; + if(d == 0) return b; + t /= d/2; + if (t < 1) return c/2*t*t*t*t*t + b; + t -= 2; + return c/2*(t*t*t*t*t + 2) + b; }; double Tween::EaseInSine(double t, double d, double b, double c) { - return -c * cos(t/d * (M_PI/2)) + c + b; + return -c * cos(t/d * (M_PI/2)) + c + b; }; double Tween::EaseOutSine(double t, double d, double b, double c) { - return c * sin(t/d * (M_PI/2)) + b; + return c * sin(t/d * (M_PI/2)) + b; }; double Tween::EaseInOutSine(double t, double d, double b, double c) { - return -c/2 * (cos( M_PI*t/d) - 1) + b; + return -c/2 * (cos( M_PI*t/d) - 1) + b; }; double Tween::EaseInExponential(double t, double d, double b, double c) { - return c * pow( 2, 10 * (t/d - 1) ) + b; + return c * pow( 2, 10 * (t/d - 1) ) + b; }; double Tween::EaseOutExponential(double t, double d, double b, double c) { - return c * ( - pow( 2, -10 * t/d ) + 1 ) + b; + return c * ( - pow( 2, -10 * t/d ) + 1 ) + b; }; double Tween::EaseInOutExponential(double t, double d, double b, double c) { - t /= d/2; - if (t < 1) return c/2 * pow( 2, 10 * (t - 1) ) + b; - t--; - return c/2 * ( -1* pow( 2, -10 * t) + 2 ) + b; + t /= d/2; + if (t < 1) return c/2 * pow( 2, 10 * (t - 1) ) + b; + t--; + return c/2 * ( -1* pow( 2, -10 * t) + 2 ) + b; }; double Tween::EaseInCircular(double t, double d, double b, double c) { - t /= d; - return -c * (sqrt(1 - t*t) - 1) + b; + t /= d; + return -c * (sqrt(1 - t*t) - 1) + b; }; double Tween::EaseOutCircular(double t, double d, double b, double c) { - t /= d; - t--; - return c * sqrt(1 - t*t) + b; + t /= d; + t--; + return c * sqrt(1 - t*t) + b; }; double Tween::EaseInOutCircular(double t, double d, double b, double c) { - t /= d/2; - if (t < 1) return -c/2 * (sqrt(1 - t*t) - 1) + b; - t -= 2; - return c/2 * (sqrt(1 - t*t) + 1) + b; + t /= d/2; + if (t < 1) return -c/2 * (sqrt(1 - t*t) - 1) + b; + t -= 2; + return c/2 * (sqrt(1 - t*t) + 1) + b; } ; //todo: sdl requires floats, should the casting be done at this layer? float Tween::GetDuration() const { - return static_cast(Duration); + return static_cast(Duration); } diff --git a/Source/Graphics/Animate/Tween.h b/Source/Graphics/Animate/Tween.h index 9150b3e..9afecec 100644 --- a/Source/Graphics/Animate/Tween.h +++ b/Source/Graphics/Animate/Tween.h @@ -13,43 +13,43 @@ class Tween { public: - Tween(TweenProperty name, TweenAlgorithm type, double start, double end, double duration); - float Animate(double elapsedTime); - static float AnimateSingle(TweenAlgorithm type, double start, double end, double duration, double elapsedTime); - static TweenAlgorithm GetTweenType(std::string name); - static bool GetTweenProperty(std::string name, TweenProperty &property); - TweenProperty GetProperty() const; - float GetDuration() const; + Tween(TweenProperty name, TweenAlgorithm type, double start, double end, double duration); + float Animate(double elapsedTime); + static float AnimateSingle(TweenAlgorithm type, double start, double end, double duration, double elapsedTime); + static TweenAlgorithm GetTweenType(std::string name); + static bool GetTweenProperty(std::string name, TweenProperty &property); + TweenProperty GetProperty() const; + float GetDuration() const; private: - static double EaseInQuadratic(double elapsedTime, double duration, double b, double c); - static double EaseOutQuadratic(double elapsedTime, double duration, double b, double c); - static double EaseInOutQuadratic(double elapsedTime, double duration, double b, double c); - static double EaseInCubic(double elapsedTime, double duration, double b, double c); - static double EaseOutCubic(double elapsedTime, double duration, double b, double c); - static double EaseInOutCubic(double elapsedTime, double duration, double b, double c); - static double EaseInQuartic(double elapsedTime, double duration, double b, double c); - static double EaseOutQuartic(double elapsedTime, double duration, double b, double c); - static double EaseInOutQuartic(double elapsedTime, double duration, double b, double c); - static double EaseInQuintic(double elapsedTime, double duration, double b, double c); - static double EaseOutQuintic(double elapsedTime, double duration, double b, double c); - static double EaseInOutQuintic(double elapsedTime, double duration, double b, double c); - static double EaseInSine(double elapsedTime, double duration, double b, double c); - static double EaseOutSine(double elapsedTime, double duration, double b, double c); - static double EaseInOutSine(double elapsedTime, double duration, double b, double c); - static double EaseInExponential(double elapsedTime, double duration, double b, double c); - static double EaseOutExponential(double elapsedTime, double duration, double b, double c); - static double EaseInOutExponential(double elapsedTime, double duration, double b, double c); - static double EaseInCircular(double elapsedTime, double duration, double b, double c); - static double EaseOutCircular(double elapsedTime, double duration, double b, double c); - static double EaseInOutCircular(double elapsedTime, double duration, double b, double c); - static double Linear(double elapsedTime, double duration, double b, double c); + static double EaseInQuadratic(double elapsedTime, double duration, double b, double c); + static double EaseOutQuadratic(double elapsedTime, double duration, double b, double c); + static double EaseInOutQuadratic(double elapsedTime, double duration, double b, double c); + static double EaseInCubic(double elapsedTime, double duration, double b, double c); + static double EaseOutCubic(double elapsedTime, double duration, double b, double c); + static double EaseInOutCubic(double elapsedTime, double duration, double b, double c); + static double EaseInQuartic(double elapsedTime, double duration, double b, double c); + static double EaseOutQuartic(double elapsedTime, double duration, double b, double c); + static double EaseInOutQuartic(double elapsedTime, double duration, double b, double c); + static double EaseInQuintic(double elapsedTime, double duration, double b, double c); + static double EaseOutQuintic(double elapsedTime, double duration, double b, double c); + static double EaseInOutQuintic(double elapsedTime, double duration, double b, double c); + static double EaseInSine(double elapsedTime, double duration, double b, double c); + static double EaseOutSine(double elapsedTime, double duration, double b, double c); + static double EaseInOutSine(double elapsedTime, double duration, double b, double c); + static double EaseInExponential(double elapsedTime, double duration, double b, double c); + static double EaseOutExponential(double elapsedTime, double duration, double b, double c); + static double EaseInOutExponential(double elapsedTime, double duration, double b, double c); + static double EaseInCircular(double elapsedTime, double duration, double b, double c); + static double EaseOutCircular(double elapsedTime, double duration, double b, double c); + static double EaseInOutCircular(double elapsedTime, double duration, double b, double c); + static double Linear(double elapsedTime, double duration, double b, double c); - static std::map TweenTypeMap; - static std::map TweenPropertyMap; - TweenProperty Property; - TweenAlgorithm Type; - double Start; - double End; - double Duration; + static std::map TweenTypeMap; + static std::map TweenPropertyMap; + TweenProperty Property; + TweenAlgorithm Type; + double Start; + double End; + double Duration; }; diff --git a/Source/Graphics/Animate/TweenTypes.h b/Source/Graphics/Animate/TweenTypes.h index a90c55a..d02149e 100644 --- a/Source/Graphics/Animate/TweenTypes.h +++ b/Source/Graphics/Animate/TweenTypes.h @@ -1,45 +1,45 @@ -/* This file is subject to the terms and conditions defined in - * file 'LICENSE.txt', which is part of this source code package. +/* This file is subject to the terms and conditions defined in + * file 'LICENSE.txt', which is part of this source code package. */ #pragma once enum TweenAlgorithm { - LINEAR, - EASE_IN_QUADRATIC, - EASE_OUT_QUADRATIC, - EASE_INOUT_QUADRATIC, - EASE_IN_CUBIC, - EASE_OUT_CUBIC, - EASE_INOUT_CUBIC, - EASE_IN_QUARTIC, - EASE_OUT_QUARTIC, - EASE_INOUT_QUARTIC, - EASE_IN_QUINTIC, - EASE_OUT_QUINTIC, - EASE_INOUT_QUINTIC, - EASE_IN_SINE, - EASE_OUT_SINE, - EASE_INOUT_SINE, - EASE_IN_EXPONENTIAL, - EASE_OUT_EXPONENTIAL, - EASE_INOUT_EXPONENTIAL, - EASE_IN_CIRCULAR, - EASE_OUT_CIRCULAR, - EASE_INOUT_CIRCULAR, + LINEAR, + EASE_IN_QUADRATIC, + EASE_OUT_QUADRATIC, + EASE_INOUT_QUADRATIC, + EASE_IN_CUBIC, + EASE_OUT_CUBIC, + EASE_INOUT_CUBIC, + EASE_IN_QUARTIC, + EASE_OUT_QUARTIC, + EASE_INOUT_QUARTIC, + EASE_IN_QUINTIC, + EASE_OUT_QUINTIC, + EASE_INOUT_QUINTIC, + EASE_IN_SINE, + EASE_OUT_SINE, + EASE_INOUT_SINE, + EASE_IN_EXPONENTIAL, + EASE_OUT_EXPONENTIAL, + EASE_INOUT_EXPONENTIAL, + EASE_IN_CIRCULAR, + EASE_OUT_CIRCULAR, + EASE_INOUT_CIRCULAR, }; enum TweenProperty { - TWEEN_PROPERTY_HEIGHT, - TWEEN_PROPERTY_WIDTH, - TWEEN_PROPERTY_ANGLE, - TWEEN_PROPERTY_TRANSPARENCY, - TWEEN_PROPERTY_X, - TWEEN_PROPERTY_Y, - TWEEN_PROPERTY_X_ORIGIN, - TWEEN_PROPERTY_Y_ORIGIN, - TWEEN_PROPERTY_X_OFFSET, - TWEEN_PROPERTY_Y_OFFSET, - TWEEN_PROPERTY_FONT_SIZE + TWEEN_PROPERTY_HEIGHT, + TWEEN_PROPERTY_WIDTH, + TWEEN_PROPERTY_ANGLE, + TWEEN_PROPERTY_TRANSPARENCY, + TWEEN_PROPERTY_X, + TWEEN_PROPERTY_Y, + TWEEN_PROPERTY_X_ORIGIN, + TWEEN_PROPERTY_Y_ORIGIN, + TWEEN_PROPERTY_X_OFFSET, + TWEEN_PROPERTY_Y_OFFSET, + TWEEN_PROPERTY_FONT_SIZE }; diff --git a/Source/Graphics/Component/Component.cpp b/Source/Graphics/Component/Component.cpp index 3614558..cc0e73c 100644 --- a/Source/Graphics/Component/Component.cpp +++ b/Source/Graphics/Component/Component.cpp @@ -8,34 +8,34 @@ Component::Component() { - OnEnterTweens = NULL; - OnExitTweens = NULL; - OnIdleTweens = NULL; - OnHighlightEnterTweens = NULL; - OnHighlightExitTweens = NULL; - SelectedItem = NULL; - NewItemSelectedSinceEnter = false; - FreeGraphicsMemory(); + OnEnterTweens = NULL; + OnExitTweens = NULL; + OnIdleTweens = NULL; + OnHighlightEnterTweens = NULL; + OnHighlightExitTweens = NULL; + SelectedItem = NULL; + NewItemSelectedSinceEnter = false; + FreeGraphicsMemory(); } Component::~Component() { - FreeGraphicsMemory(); + FreeGraphicsMemory(); } void Component::FreeGraphicsMemory() { - CurrentAnimationState = HIDDEN; - EnterRequested = false; - ExitRequested = false; - NewItemSelected = false; - HighlightExitComplete = false; - CurrentTweens = NULL; - CurrentTweenIndex = 0; - CurrentTweenComplete = false; - ElapsedTweenTime =0; - ScrollActive = false; + CurrentAnimationState = HIDDEN; + EnterRequested = false; + ExitRequested = false; + NewItemSelected = false; + HighlightExitComplete = false; + CurrentTweens = NULL; + CurrentTweenIndex = 0; + CurrentTweenComplete = false; + ElapsedTweenTime =0; + ScrollActive = false; } void Component::AllocateGraphicsMemory() { @@ -43,240 +43,240 @@ void Component::AllocateGraphicsMemory() void Component::TriggerEnterEvent() { - EnterRequested = true; + EnterRequested = true; } void Component::TriggerExitEvent() { - ExitRequested = true; + ExitRequested = true; } void Component::TriggerHighlightEvent(Item *selectedItem) { - NewItemSelected = true; - this->SelectedItem = selectedItem; + NewItemSelected = true; + this->SelectedItem = selectedItem; } bool Component::IsIdle() { - return (CurrentAnimationState == IDLE); + return (CurrentAnimationState == IDLE); } bool Component::IsHidden() { - return (CurrentAnimationState == HIDDEN); + return (CurrentAnimationState == HIDDEN); } bool Component::IsWaiting() { - return (CurrentAnimationState == HIGHLIGHT_WAIT); + return (CurrentAnimationState == HIGHLIGHT_WAIT); } void Component::Update(float dt) { - ElapsedTweenTime += dt; - HighlightExitComplete = false; - if(IsHidden() || IsWaiting() || (IsIdle() && ExitRequested)) - { - CurrentTweenComplete = true; - } + ElapsedTweenTime += dt; + HighlightExitComplete = false; + if(IsHidden() || IsWaiting() || (IsIdle() && ExitRequested)) + { + CurrentTweenComplete = true; + } - if(CurrentTweenComplete) - { - CurrentTweens = NULL; + if(CurrentTweenComplete) + { + CurrentTweens = NULL; - // There was no request to override our state path. Continue on as normal. - switch(CurrentAnimationState) - { - case ENTER: + // There was no request to override our state path. Continue on as normal. + switch(CurrentAnimationState) + { + case ENTER: CurrentTweens = OnHighlightEnterTweens; CurrentAnimationState = HIGHLIGHT_ENTER; break; - case EXIT: + case EXIT: CurrentTweens = NULL; CurrentAnimationState = HIDDEN; break; - case HIGHLIGHT_ENTER: + case HIGHLIGHT_ENTER: CurrentTweens = OnIdleTweens; CurrentAnimationState = IDLE; break; - case IDLE: + case IDLE: // prevent us from automatically jumping to the exit tween upon enter if(EnterRequested) { - EnterRequested = false; - NewItemSelected = false; + EnterRequested = false; + NewItemSelected = false; } else if(IsScrollActive() || NewItemSelected || ExitRequested) { - CurrentTweens = OnHighlightExitTweens; - CurrentAnimationState = HIGHLIGHT_EXIT; + CurrentTweens = OnHighlightExitTweens; + CurrentAnimationState = HIGHLIGHT_EXIT; } else { - CurrentTweens = OnIdleTweens; - CurrentAnimationState = IDLE; + CurrentTweens = OnIdleTweens; + CurrentAnimationState = IDLE; } break; - case HIGHLIGHT_EXIT: + case HIGHLIGHT_EXIT: - // intentionally break down - case HIGHLIGHT_WAIT: + // intentionally break down + case HIGHLIGHT_WAIT: if(ExitRequested && (CurrentAnimationState == HIGHLIGHT_WAIT)) { - CurrentTweens = OnHighlightExitTweens; - CurrentAnimationState = HIGHLIGHT_EXIT; + CurrentTweens = OnHighlightExitTweens; + CurrentAnimationState = HIGHLIGHT_EXIT; } else if(ExitRequested && (CurrentAnimationState == HIGHLIGHT_EXIT)) { - CurrentTweens = OnExitTweens; - CurrentAnimationState = EXIT; - ExitRequested = false; + CurrentTweens = OnExitTweens; + CurrentAnimationState = EXIT; + ExitRequested = false; } else if(IsScrollActive()) { - CurrentTweens = NULL; - CurrentAnimationState = HIGHLIGHT_WAIT; + CurrentTweens = NULL; + CurrentAnimationState = HIGHLIGHT_WAIT; } else if(NewItemSelected) { - CurrentTweens = OnHighlightEnterTweens; - CurrentAnimationState = HIGHLIGHT_ENTER; - HighlightExitComplete = true; - NewItemSelected = false; + CurrentTweens = OnHighlightEnterTweens; + CurrentAnimationState = HIGHLIGHT_ENTER; + HighlightExitComplete = true; + NewItemSelected = false; } else { - CurrentTweens = NULL; - CurrentAnimationState = HIGHLIGHT_WAIT; + CurrentTweens = NULL; + CurrentAnimationState = HIGHLIGHT_WAIT; } break; - case HIDDEN: + case HIDDEN: if(EnterRequested || ExitRequested) { - CurrentTweens = OnEnterTweens; - CurrentAnimationState = ENTER; + CurrentTweens = OnEnterTweens; + CurrentAnimationState = ENTER; } else { - CurrentTweens = NULL; - CurrentAnimationState = HIDDEN; + CurrentTweens = NULL; + CurrentAnimationState = HIDDEN; } - } + } - CurrentTweenIndex = 0; - CurrentTweenComplete = false; + CurrentTweenIndex = 0; + CurrentTweenComplete = false; - ElapsedTweenTime = 0; - } + ElapsedTweenTime = 0; + } - CurrentTweenComplete = Animate(IsIdle()); + CurrentTweenComplete = Animate(IsIdle()); } bool Component::Animate(bool loop) { - bool completeDone = false; - if(!CurrentTweens || CurrentTweenIndex >= CurrentTweens->size()) - { - completeDone = true; - } - else if(CurrentTweens) - { - bool currentDone = true; - std::vector *tweenSet = CurrentTweens->at(CurrentTweenIndex); + bool completeDone = false; + if(!CurrentTweens || CurrentTweenIndex >= CurrentTweens->size()) + { + completeDone = true; + } + else if(CurrentTweens) + { + bool currentDone = true; + std::vector *tweenSet = CurrentTweens->at(CurrentTweenIndex); - for(unsigned int i = 0; i < tweenSet->size(); i++) - { - Tween *tween = tweenSet->at(i); - float elapsedTime = ElapsedTweenTime; + for(unsigned int i = 0; i < tweenSet->size(); i++) + { + Tween *tween = tweenSet->at(i); + float elapsedTime = ElapsedTweenTime; - //todo: too many levels of nesting - if(elapsedTime < tween->GetDuration()) - { - currentDone = false; - } - else - { - elapsedTime = tween->GetDuration(); - } + //todo: too many levels of nesting + if(elapsedTime < tween->GetDuration()) + { + currentDone = false; + } + else + { + elapsedTime = tween->GetDuration(); + } - float value = tween->Animate(elapsedTime); + float value = tween->Animate(elapsedTime); - switch(tween->GetProperty()) - { - case TWEEN_PROPERTY_X: - GetBaseViewInfo()->SetX(value); - break; + switch(tween->GetProperty()) + { + case TWEEN_PROPERTY_X: + GetBaseViewInfo()->SetX(value); + break; - case TWEEN_PROPERTY_Y: - GetBaseViewInfo()->SetY(value); - break; + case TWEEN_PROPERTY_Y: + GetBaseViewInfo()->SetY(value); + break; - case TWEEN_PROPERTY_HEIGHT: - GetBaseViewInfo()->SetHeight(value); - break; + case TWEEN_PROPERTY_HEIGHT: + GetBaseViewInfo()->SetHeight(value); + break; - case TWEEN_PROPERTY_WIDTH: - GetBaseViewInfo()->SetWidth(value); - break; + case TWEEN_PROPERTY_WIDTH: + GetBaseViewInfo()->SetWidth(value); + break; - case TWEEN_PROPERTY_ANGLE: - GetBaseViewInfo()->SetAngle(value); - break; + case TWEEN_PROPERTY_ANGLE: + GetBaseViewInfo()->SetAngle(value); + break; - case TWEEN_PROPERTY_TRANSPARENCY: - GetBaseViewInfo()->SetTransparency(value); - break; + case TWEEN_PROPERTY_TRANSPARENCY: + GetBaseViewInfo()->SetTransparency(value); + break; - case TWEEN_PROPERTY_X_ORIGIN: - GetBaseViewInfo()->SetXOrigin(value); - break; + case TWEEN_PROPERTY_X_ORIGIN: + GetBaseViewInfo()->SetXOrigin(value); + break; - case TWEEN_PROPERTY_Y_ORIGIN: - GetBaseViewInfo()->SetYOrigin(value); - break; + case TWEEN_PROPERTY_Y_ORIGIN: + GetBaseViewInfo()->SetYOrigin(value); + break; - case TWEEN_PROPERTY_X_OFFSET: - GetBaseViewInfo()->SetXOffset(value); - break; + case TWEEN_PROPERTY_X_OFFSET: + GetBaseViewInfo()->SetXOffset(value); + break; - case TWEEN_PROPERTY_Y_OFFSET: - GetBaseViewInfo()->SetYOffset(value); - break; + case TWEEN_PROPERTY_Y_OFFSET: + GetBaseViewInfo()->SetYOffset(value); + break; - case TWEEN_PROPERTY_FONT_SIZE: - GetBaseViewInfo()->SetFontSize(value); - break; - } - } + case TWEEN_PROPERTY_FONT_SIZE: + GetBaseViewInfo()->SetFontSize(value); + break; + } + } - if(currentDone) - { - CurrentTweenIndex++; - ElapsedTweenTime = 0; - } - } + if(currentDone) + { + CurrentTweenIndex++; + ElapsedTweenTime = 0; + } + } - if(!CurrentTweens || CurrentTweenIndex >= CurrentTweens->size()) - { - if(loop) - { - CurrentTweenIndex = 0; - } - completeDone = true; - } + if(!CurrentTweens || CurrentTweenIndex >= CurrentTweens->size()) + { + if(loop) + { + CurrentTweenIndex = 0; + } + completeDone = true; + } - return completeDone; + return completeDone; } diff --git a/Source/Graphics/Component/Component.h b/Source/Graphics/Component/Component.h index d522d39..ff0807c 100644 --- a/Source/Graphics/Component/Component.h +++ b/Source/Graphics/Component/Component.h @@ -13,110 +13,110 @@ class Component { public: - Component(); - virtual ~Component(); - virtual void FreeGraphicsMemory(); - virtual void AllocateGraphicsMemory(); - virtual void LaunchEnter() {} - virtual void LaunchExit() {} - void TriggerEnterEvent(); - void TriggerExitEvent(); - void TriggerHighlightEvent(Item *selectedItem); - bool IsIdle(); - bool IsHidden(); - bool IsWaiting(); - typedef std::vector *> TweenSets; + Component(); + virtual ~Component(); + virtual void FreeGraphicsMemory(); + virtual void AllocateGraphicsMemory(); + virtual void LaunchEnter() {} + virtual void LaunchExit() {} + void TriggerEnterEvent(); + void TriggerExitEvent(); + void TriggerHighlightEvent(Item *selectedItem); + bool IsIdle(); + bool IsHidden(); + bool IsWaiting(); + typedef std::vector *> TweenSets; - void SetOnEnterTweens(TweenSets *tweens) - { - this->OnEnterTweens = tweens; - } + void SetOnEnterTweens(TweenSets *tweens) + { + this->OnEnterTweens = tweens; + } - void SetOnExitTweens(TweenSets *tweens) - { - this->OnExitTweens = tweens; - } + void SetOnExitTweens(TweenSets *tweens) + { + this->OnExitTweens = tweens; + } - void SetOnIdleTweens(TweenSets *tweens) - { - this->OnIdleTweens = tweens; - } + void SetOnIdleTweens(TweenSets *tweens) + { + this->OnIdleTweens = tweens; + } - void SetOnHighlightEnterTweens(TweenSets *tweens) - { - this->OnHighlightEnterTweens = tweens; - } + void SetOnHighlightEnterTweens(TweenSets *tweens) + { + this->OnHighlightEnterTweens = tweens; + } - void SetOnHighlightExitTweens(TweenSets *tweens) - { - this->OnHighlightExitTweens = tweens; - } - virtual void Update(float dt); + void SetOnHighlightExitTweens(TweenSets *tweens) + { + this->OnHighlightExitTweens = tweens; + } + virtual void Update(float dt); - virtual void Draw() = 0; + virtual void Draw() = 0; - ViewInfo *GetBaseViewInfo() - { - return &BaseViewInfo; - } - void UpdateBaseViewInfo(ViewInfo &info) - { - BaseViewInfo = info; - } + ViewInfo *GetBaseViewInfo() + { + return &BaseViewInfo; + } + void UpdateBaseViewInfo(ViewInfo &info) + { + BaseViewInfo = info; + } - bool IsScrollActive() const - { - return ScrollActive; - } + bool IsScrollActive() const + { + return ScrollActive; + } - void SetScrollActive(bool scrollActive) - { - ScrollActive = scrollActive; - } + void SetScrollActive(bool scrollActive) + { + ScrollActive = scrollActive; + } protected: - Item *GetSelectedItem() - { - return SelectedItem; - } - enum AnimationState - { - IDLE, - ENTER, - HIGHLIGHT_EXIT, - HIGHLIGHT_WAIT, - HIGHLIGHT_ENTER, - EXIT, - HIDDEN - }; + Item *GetSelectedItem() + { + return SelectedItem; + } + enum AnimationState + { + IDLE, + ENTER, + HIGHLIGHT_EXIT, + HIGHLIGHT_WAIT, + HIGHLIGHT_ENTER, + EXIT, + HIDDEN + }; - AnimationState CurrentAnimationState; - bool EnterRequested; - bool ExitRequested; - bool NewItemSelected; - bool HighlightExitComplete; - bool NewItemSelectedSinceEnter; + AnimationState CurrentAnimationState; + bool EnterRequested; + bool ExitRequested; + bool NewItemSelected; + bool HighlightExitComplete; + bool NewItemSelectedSinceEnter; private: - bool Animate(bool loop); - bool IsTweenSequencingComplete(); - void ResetTweenSequence(std::vector *tweens); + bool Animate(bool loop); + bool IsTweenSequencingComplete(); + void ResetTweenSequence(std::vector *tweens); - TweenSets *OnEnterTweens; - TweenSets *OnExitTweens; - TweenSets *OnIdleTweens; - TweenSets *OnHighlightEnterTweens; - TweenSets *OnHighlightExitTweens; + TweenSets *OnEnterTweens; + TweenSets *OnExitTweens; + TweenSets *OnIdleTweens; + TweenSets *OnHighlightEnterTweens; + TweenSets *OnHighlightExitTweens; - TweenSets *CurrentTweens; - unsigned int CurrentTweenIndex; + TweenSets *CurrentTweens; + unsigned int CurrentTweenIndex; - bool CurrentTweenComplete; - ViewInfo BaseViewInfo; + bool CurrentTweenComplete; + ViewInfo BaseViewInfo; - float ElapsedTweenTime; - Tween *TweenInst; - Item *SelectedItem; - bool ScrollActive; + float ElapsedTweenTime; + Tween *TweenInst; + Item *SelectedItem; + bool ScrollActive; }; diff --git a/Source/Graphics/Component/Image.cpp b/Source/Graphics/Component/Image.cpp index 9ac12f9..ab91425 100644 --- a/Source/Graphics/Component/Image.cpp +++ b/Source/Graphics/Component/Image.cpp @@ -8,68 +8,68 @@ #include Image::Image(std::string file, float scaleX, float scaleY) -: Texture(NULL) -, File(file) -, ScaleX(scaleX) -, ScaleY(scaleY) + : Texture(NULL) + , File(file) + , ScaleX(scaleX) + , ScaleY(scaleY) { - AllocateGraphicsMemory(); + AllocateGraphicsMemory(); } Image::~Image() { - FreeGraphicsMemory(); + FreeGraphicsMemory(); } void Image::FreeGraphicsMemory() { - Component::FreeGraphicsMemory(); + Component::FreeGraphicsMemory(); - SDL_LockMutex(SDL::GetMutex()); - if (Texture != NULL) - { - SDL_DestroyTexture(Texture); - Texture = NULL; - } - SDL_UnlockMutex(SDL::GetMutex()); + SDL_LockMutex(SDL::GetMutex()); + if (Texture != NULL) + { + SDL_DestroyTexture(Texture); + Texture = NULL; + } + SDL_UnlockMutex(SDL::GetMutex()); } void Image::AllocateGraphicsMemory() { - int width; - int height; + int width; + int height; - Component::AllocateGraphicsMemory(); + Component::AllocateGraphicsMemory(); - if(!Texture) - { - SDL_LockMutex(SDL::GetMutex()); - Texture = IMG_LoadTexture(SDL::GetRenderer(), File.c_str()); + if(!Texture) + { + SDL_LockMutex(SDL::GetMutex()); + Texture = IMG_LoadTexture(SDL::GetRenderer(), File.c_str()); - if (Texture != NULL) - { - SDL_SetTextureBlendMode(Texture, SDL_BLENDMODE_BLEND); - SDL_QueryTexture(Texture, NULL, NULL, &width, &height); - GetBaseViewInfo()->SetImageWidth(width * ScaleX); - GetBaseViewInfo()->SetImageHeight(height * ScaleY); - } - SDL_UnlockMutex(SDL::GetMutex()); + if (Texture != NULL) + { + SDL_SetTextureBlendMode(Texture, SDL_BLENDMODE_BLEND); + SDL_QueryTexture(Texture, NULL, NULL, &width, &height); + GetBaseViewInfo()->SetImageWidth(width * ScaleX); + GetBaseViewInfo()->SetImageHeight(height * ScaleY); + } + SDL_UnlockMutex(SDL::GetMutex()); - } + } } void Image::Draw() { - if(Texture) - { - ViewInfo *info = GetBaseViewInfo(); - SDL_Rect rect; + if(Texture) + { + ViewInfo *info = GetBaseViewInfo(); + SDL_Rect rect; - rect.x = static_cast(info->GetXRelativeToOrigin()); - rect.y = static_cast(info->GetYRelativeToOrigin()); - rect.h = static_cast(info->GetHeight()); - rect.w = static_cast(info->GetWidth()); + rect.x = static_cast(info->GetXRelativeToOrigin()); + rect.y = static_cast(info->GetYRelativeToOrigin()); + rect.h = static_cast(info->GetHeight()); + rect.w = static_cast(info->GetWidth()); - SDL::RenderCopy(Texture, static_cast((info->GetTransparency() * 255)), NULL, &rect, info->GetAngle()); - } + SDL::RenderCopy(Texture, static_cast((info->GetTransparency() * 255)), NULL, &rect, info->GetAngle()); + } } diff --git a/Source/Graphics/Component/Image.h b/Source/Graphics/Component/Image.h index db37492..593539a 100644 --- a/Source/Graphics/Component/Image.h +++ b/Source/Graphics/Component/Image.h @@ -10,15 +10,15 @@ class Image : public Component { public: - Image(std::string file, float scaleX, float scaleY); - virtual ~Image(); - void FreeGraphicsMemory(); - void AllocateGraphicsMemory(); - void Draw(); + Image(std::string file, float scaleX, float scaleY); + virtual ~Image(); + void FreeGraphicsMemory(); + void AllocateGraphicsMemory(); + void Draw(); protected: - SDL_Texture *Texture; - std::string File; - float ScaleX; - float ScaleY; + SDL_Texture *Texture; + std::string File; + float ScaleX; + float ScaleY; }; diff --git a/Source/Graphics/Component/ImageBuilder.cpp b/Source/Graphics/Component/ImageBuilder.cpp index 77bfdac..443caa7 100644 --- a/Source/Graphics/Component/ImageBuilder.cpp +++ b/Source/Graphics/Component/ImageBuilder.cpp @@ -8,23 +8,23 @@ Image * ImageBuilder::CreateImage(std::string path, std::string name, float scaleX, float scaleY) { - Image *image = NULL; - std::vector extensions; + Image *image = NULL; + std::vector extensions; - extensions.push_back("png"); - extensions.push_back("PNG"); - extensions.push_back("jpg"); - extensions.push_back("JPG"); - extensions.push_back("jpeg"); - extensions.push_back("JPEG"); + extensions.push_back("png"); + extensions.push_back("PNG"); + extensions.push_back("jpg"); + extensions.push_back("JPG"); + extensions.push_back("jpeg"); + extensions.push_back("JPEG"); - std::string prefix = path + "/" + name; - std::string file; + std::string prefix = path + "/" + name; + std::string file; - if(Utils::FindMatchingFile(prefix, extensions, file)) - { - image = new Image(file, scaleX, scaleY); - } + if(Utils::FindMatchingFile(prefix, extensions, file)) + { + image = new Image(file, scaleX, scaleY); + } - return image; + return image; } diff --git a/Source/Graphics/Component/ImageBuilder.h b/Source/Graphics/Component/ImageBuilder.h index 4f37732..bd4cb06 100644 --- a/Source/Graphics/Component/ImageBuilder.h +++ b/Source/Graphics/Component/ImageBuilder.h @@ -11,5 +11,5 @@ class ImageBuilder { public: - Image * CreateImage(std::string path, std::string name, float scaleX, float scaleY); + Image * CreateImage(std::string path, std::string name, float scaleX, float scaleY); }; diff --git a/Source/Graphics/Component/ReloadableMedia.cpp b/Source/Graphics/Component/ReloadableMedia.cpp index b1a9815..4a8e817 100644 --- a/Source/Graphics/Component/ReloadableMedia.cpp +++ b/Source/Graphics/Component/ReloadableMedia.cpp @@ -15,158 +15,158 @@ #include ReloadableMedia::ReloadableMedia(std::string imagePath, std::string videoPath, bool isVideo, float scaleX, float scaleY) -: LoadedComponent(NULL) -, ImagePath(imagePath) -, VideoPath(videoPath) -, ReloadRequested(false) -, FirstLoad(true) -, IsVideo(isVideo) -, ScaleX(scaleX) -, ScaleY(scaleY) + : LoadedComponent(NULL) + , ImagePath(imagePath) + , VideoPath(videoPath) + , ReloadRequested(false) + , FirstLoad(true) + , IsVideo(isVideo) + , ScaleX(scaleX) + , ScaleY(scaleY) { - AllocateGraphicsMemory(); + AllocateGraphicsMemory(); } ReloadableMedia::~ReloadableMedia() { - if (LoadedComponent != NULL) - { - delete LoadedComponent; - } + if (LoadedComponent != NULL) + { + delete LoadedComponent; + } } void ReloadableMedia::Update(float dt) { - if(NewItemSelected) - { - ReloadRequested = true; - } - // wait for the right moment to reload the image - if (ReloadRequested && (HighlightExitComplete || FirstLoad)) - { - ReloadTexture(); - ReloadRequested = false; - FirstLoad = false; - } + if(NewItemSelected) + { + ReloadRequested = true; + } + // wait for the right moment to reload the image + if (ReloadRequested && (HighlightExitComplete || FirstLoad)) + { + ReloadTexture(); + ReloadRequested = false; + FirstLoad = false; + } - if(LoadedComponent) - { - LoadedComponent->Update(dt); - } + if(LoadedComponent) + { + LoadedComponent->Update(dt); + } // needs to be ran at the end to prevent the NewItemSelected flag from being detected - Component::Update(dt); + Component::Update(dt); } void ReloadableMedia::AllocateGraphicsMemory() { - FirstLoad = true; + FirstLoad = true; - if(LoadedComponent) - { - LoadedComponent->AllocateGraphicsMemory(); - } + if(LoadedComponent) + { + LoadedComponent->AllocateGraphicsMemory(); + } - // NOTICE! needs to be done last to prevent flags from being missed - Component::AllocateGraphicsMemory(); + // NOTICE! needs to be done last to prevent flags from being missed + Component::AllocateGraphicsMemory(); } void ReloadableMedia::LaunchEnter() { - if(LoadedComponent) - { - LoadedComponent->LaunchEnter(); - } + if(LoadedComponent) + { + LoadedComponent->LaunchEnter(); + } } void ReloadableMedia::LaunchExit() { - if(LoadedComponent) - { - LoadedComponent->LaunchExit(); - } + if(LoadedComponent) + { + LoadedComponent->LaunchExit(); + } } void ReloadableMedia::FreeGraphicsMemory() { - Component::FreeGraphicsMemory(); + Component::FreeGraphicsMemory(); - if(LoadedComponent) - { - LoadedComponent->FreeGraphicsMemory(); - } + if(LoadedComponent) + { + LoadedComponent->FreeGraphicsMemory(); + } } void ReloadableMedia::ReloadTexture() { - bool found = false; + bool found = false; - if(LoadedComponent) - { - delete LoadedComponent; - LoadedComponent = NULL; - } + if(LoadedComponent) + { + delete LoadedComponent; + LoadedComponent = NULL; + } - Item *selectedItem = GetSelectedItem(); + Item *selectedItem = GetSelectedItem(); - if (selectedItem != NULL) - { - if(IsVideo) - { - std::vector names; + if (selectedItem != NULL) + { + if(IsVideo) + { + std::vector names; - names.push_back(selectedItem->GetName()); + names.push_back(selectedItem->GetName()); - if(selectedItem->GetCloneOf().length() > 0) - { - names.push_back(selectedItem->GetCloneOf()); - } - - for(unsigned int n = 0; n < names.size() && !found; ++n) - { - std::string filePrefix; - filePrefix.append(VideoPath); - filePrefix.append("/"); - filePrefix.append(names[n]); - - std::string file; - - VideoBuilder videoBuild; - - LoadedComponent = videoBuild.CreateVideo(VideoPath, names[n], ScaleX, ScaleY); - - if(LoadedComponent) + if(selectedItem->GetCloneOf().length() > 0) { - LoadedComponent->AllocateGraphicsMemory(); - found = true; + names.push_back(selectedItem->GetCloneOf()); } - } - } - if(!LoadedComponent) - { - ImageBuilder imageBuild; - LoadedComponent = imageBuild.CreateImage(ImagePath, selectedItem->GetFullTitle(), ScaleX, ScaleY); + for(unsigned int n = 0; n < names.size() && !found; ++n) + { + std::string filePrefix; + filePrefix.append(VideoPath); + filePrefix.append("/"); + filePrefix.append(names[n]); - if (LoadedComponent != NULL) - { - LoadedComponent->AllocateGraphicsMemory(); - GetBaseViewInfo()->SetImageWidth(LoadedComponent->GetBaseViewInfo()->GetImageWidth()); - GetBaseViewInfo()->SetImageHeight(LoadedComponent->GetBaseViewInfo()->GetImageHeight()); - } - } - } + std::string file; + + VideoBuilder videoBuild; + + LoadedComponent = videoBuild.CreateVideo(VideoPath, names[n], ScaleX, ScaleY); + + if(LoadedComponent) + { + LoadedComponent->AllocateGraphicsMemory(); + found = true; + } + } + } + + if(!LoadedComponent) + { + ImageBuilder imageBuild; + LoadedComponent = imageBuild.CreateImage(ImagePath, selectedItem->GetFullTitle(), ScaleX, ScaleY); + + if (LoadedComponent != NULL) + { + LoadedComponent->AllocateGraphicsMemory(); + GetBaseViewInfo()->SetImageWidth(LoadedComponent->GetBaseViewInfo()->GetImageWidth()); + GetBaseViewInfo()->SetImageHeight(LoadedComponent->GetBaseViewInfo()->GetImageHeight()); + } + } + } } void ReloadableMedia::Draw() { - ViewInfo *info = GetBaseViewInfo(); + ViewInfo *info = GetBaseViewInfo(); - if(LoadedComponent) - { - info->SetImageHeight(LoadedComponent->GetBaseViewInfo()->GetImageHeight()); - info->SetImageWidth(LoadedComponent->GetBaseViewInfo()->GetImageWidth()); - LoadedComponent->UpdateBaseViewInfo(*info); - LoadedComponent->Draw(); - } + if(LoadedComponent) + { + info->SetImageHeight(LoadedComponent->GetBaseViewInfo()->GetImageHeight()); + info->SetImageWidth(LoadedComponent->GetBaseViewInfo()->GetImageWidth()); + LoadedComponent->UpdateBaseViewInfo(*info); + LoadedComponent->Draw(); + } } diff --git a/Source/Graphics/Component/ReloadableMedia.h b/Source/Graphics/Component/ReloadableMedia.h index 88dff9b..43d0d37 100644 --- a/Source/Graphics/Component/ReloadableMedia.h +++ b/Source/Graphics/Component/ReloadableMedia.h @@ -14,25 +14,25 @@ class Image; class ReloadableMedia : public Component { public: - ReloadableMedia(std::string imagePath, std::string videoPath, bool isVideo, float scaleX, float scaleY); - virtual ~ReloadableMedia(); - void Update(float dt); - void Draw(); - void FreeGraphicsMemory(); - void AllocateGraphicsMemory(); - void LaunchEnter(); - void LaunchExit(); + ReloadableMedia(std::string imagePath, std::string videoPath, bool isVideo, float scaleX, float scaleY); + virtual ~ReloadableMedia(); + void Update(float dt); + void Draw(); + void FreeGraphicsMemory(); + void AllocateGraphicsMemory(); + void LaunchEnter(); + void LaunchExit(); private: - void ReloadTexture(); - Component *LoadedComponent; - std::string ImagePath; - std::string VideoPath; - bool ReloadRequested; - bool FirstLoad; - IVideo *VideoInst; + void ReloadTexture(); + Component *LoadedComponent; + std::string ImagePath; + std::string VideoPath; + bool ReloadRequested; + bool FirstLoad; + IVideo *VideoInst; - bool IsVideo; - float ScaleX; - float ScaleY; + bool IsVideo; + float ScaleX; + float ScaleY; }; diff --git a/Source/Graphics/Component/ReloadableText.cpp b/Source/Graphics/Component/ReloadableText.cpp index f54fe86..7d65158 100644 --- a/Source/Graphics/Component/ReloadableText.cpp +++ b/Source/Graphics/Component/ReloadableText.cpp @@ -11,80 +11,80 @@ #include ReloadableText::ReloadableText(std::string type, Font *font, SDL_Color color, std::string layoutKey, std::string collection, float scaleX, float scaleY) -: ImageInst(NULL) -, LayoutKey(layoutKey) -, Collection(collection) -, ReloadRequested(false) -, FirstLoad(true) -, FontInst(font) -, FontColor(color) -, ScaleX(scaleX) -, ScaleY(scaleY) + : ImageInst(NULL) + , LayoutKey(layoutKey) + , Collection(collection) + , ReloadRequested(false) + , FirstLoad(true) + , FontInst(font) + , FontColor(color) + , ScaleX(scaleX) + , ScaleY(scaleY) { - Type = TextTypeUnknown; + Type = TextTypeUnknown; - if(type == "numberButtons") - { - Type = TextTypeNumberButtons; - } - else if(type == "numberPlayers") - { - Type = TextTypeNumberPlayers; - } - else if(type == "year") - { - Type = TextTypeYear; - } - else if(type == "title") - { - Type = TextTypeTitle; - } - else if(type == "manufacturer") - { - Type = TextTypeManufacturer; - } + if(type == "numberButtons") + { + Type = TextTypeNumberButtons; + } + else if(type == "numberPlayers") + { + Type = TextTypeNumberPlayers; + } + else if(type == "year") + { + Type = TextTypeYear; + } + else if(type == "title") + { + Type = TextTypeTitle; + } + else if(type == "manufacturer") + { + Type = TextTypeManufacturer; + } - AllocateGraphicsMemory(); + AllocateGraphicsMemory(); } ReloadableText::~ReloadableText() { - if (ImageInst != NULL) - { - delete ImageInst; - } + if (ImageInst != NULL) + { + delete ImageInst; + } } void ReloadableText::Update(float dt) { - if(NewItemSelected) - { - ReloadRequested = true; - } - // wait for the right moment to reload the image - if (ReloadRequested && (HighlightExitComplete || FirstLoad)) - { - ReloadTexture(); - ReloadRequested = false; - FirstLoad = false; - } + if(NewItemSelected) + { + ReloadRequested = true; + } + // wait for the right moment to reload the image + if (ReloadRequested && (HighlightExitComplete || FirstLoad)) + { + ReloadTexture(); + ReloadRequested = false; + FirstLoad = false; + } - // needs to be ran at the end to prevent the NewItemSelected flag from being detected - Component::Update(dt); + // needs to be ran at the end to prevent the NewItemSelected flag from being detected + Component::Update(dt); } void ReloadableText::AllocateGraphicsMemory() { - FirstLoad = true; + FirstLoad = true; - ReloadTexture(); + ReloadTexture(); - // NOTICE! needs to be done last to prevent flags from being missed - Component::AllocateGraphicsMemory(); + // NOTICE! needs to be done last to prevent flags from being missed + Component::AllocateGraphicsMemory(); } void ReloadableText::LaunchEnter() @@ -97,61 +97,61 @@ void ReloadableText::LaunchExit() void ReloadableText::FreeGraphicsMemory() { - Component::FreeGraphicsMemory(); + Component::FreeGraphicsMemory(); - if (ImageInst != NULL) - { - delete ImageInst; - ImageInst = NULL; - } + if (ImageInst != NULL) + { + delete ImageInst; + ImageInst = NULL; + } } void ReloadableText::ReloadTexture() { - if (ImageInst != NULL) - { - delete ImageInst; - ImageInst = NULL; - } + if (ImageInst != NULL) + { + delete ImageInst; + ImageInst = NULL; + } - Item *selectedItem = GetSelectedItem(); + Item *selectedItem = GetSelectedItem(); - if (selectedItem != NULL) - { - std::stringstream ss; - std::string text; - switch(Type) - { - case TextTypeNumberButtons: - ss << selectedItem->GetNumberButtons(); - break; - case TextTypeNumberPlayers: - ss << selectedItem->GetNumberPlayers(); - break; - case TextTypeYear: - ss << selectedItem->GetYear(); - break; - case TextTypeTitle: - ss << selectedItem->GetTitle(); - break; - case TextTypeManufacturer: - ss << selectedItem->GetManufacturer(); - break; - default: - break; - } + if (selectedItem != NULL) + { + std::stringstream ss; + std::string text; + switch(Type) + { + case TextTypeNumberButtons: + ss << selectedItem->GetNumberButtons(); + break; + case TextTypeNumberPlayers: + ss << selectedItem->GetNumberPlayers(); + break; + case TextTypeYear: + ss << selectedItem->GetYear(); + break; + case TextTypeTitle: + ss << selectedItem->GetTitle(); + break; + case TextTypeManufacturer: + ss << selectedItem->GetManufacturer(); + break; + default: + break; + } - ImageInst = new Text(ss.str(), FontInst, FontColor, ScaleX, ScaleY); - } + ImageInst = new Text(ss.str(), FontInst, FontColor, ScaleX, ScaleY); + } } void ReloadableText::Draw() { - ViewInfo *info = GetBaseViewInfo(); + ViewInfo *info = GetBaseViewInfo(); - if(ImageInst) - { - ImageInst->UpdateBaseViewInfo(*info); - ImageInst->Draw(); - } + if(ImageInst) + { + ImageInst->UpdateBaseViewInfo(*info); + ImageInst->Draw(); + } } diff --git a/Source/Graphics/Component/ReloadableText.h b/Source/Graphics/Component/ReloadableText.h index 02c709e..71e26c4 100644 --- a/Source/Graphics/Component/ReloadableText.h +++ b/Source/Graphics/Component/ReloadableText.h @@ -12,37 +12,37 @@ class ReloadableText : public Component { public: - ReloadableText(std::string type, Font *font, SDL_Color color, std::string layoutKey, std::string collectionName, float scaleX, float scaleY); - virtual ~ReloadableText(); - void Update(float dt); - void Draw(); - void FreeGraphicsMemory(); - void AllocateGraphicsMemory(); - void LaunchEnter(); - void LaunchExit(); + ReloadableText(std::string type, Font *font, SDL_Color color, std::string layoutKey, std::string collectionName, float scaleX, float scaleY); + virtual ~ReloadableText(); + void Update(float dt); + void Draw(); + void FreeGraphicsMemory(); + void AllocateGraphicsMemory(); + void LaunchEnter(); + void LaunchExit(); private: - enum TextType - { - TextTypeUnknown = 0, - TextTypeNumberButtons, - TextTypeNumberPlayers, - TextTypeYear, - TextTypeTitle, - TextTypeManufacturer, - }; + enum TextType + { + TextTypeUnknown = 0, + TextTypeNumberButtons, + TextTypeNumberPlayers, + TextTypeYear, + TextTypeTitle, + TextTypeManufacturer, + }; - void ReloadTexture(); + void ReloadTexture(); - Text *ImageInst; - TextType Type; - std::string LayoutKey; - std::string Collection; - bool ReloadRequested; - bool FirstLoad; - Font *FontInst; - SDL_Color FontColor; + Text *ImageInst; + TextType Type; + std::string LayoutKey; + std::string Collection; + bool ReloadRequested; + bool FirstLoad; + Font *FontInst; + SDL_Color FontColor; - float ScaleX; - float ScaleY; + float ScaleX; + float ScaleY; }; diff --git a/Source/Graphics/Component/ScrollingList.cpp b/Source/Graphics/Component/ScrollingList.cpp index 8d30d2e..2a14c4f 100644 --- a/Source/Graphics/Component/ScrollingList.cpp +++ b/Source/Graphics/Component/ScrollingList.cpp @@ -1,5 +1,5 @@ -/* This file is subject to the terms and conditions defined in - * file 'LICENSE.txt', which is part of this source code package. +/* This file is subject to the terms and conditions defined in + * file 'LICENSE.txt', which is part of this source code package. */ #include "../Animate/Tween.h" #include "../Animate/TweenTypes.h" @@ -22,38 +22,38 @@ //todo: remove coupling from configuration data (if possible) -ScrollingList::ScrollingList(Configuration *c, - float scaleX, - float scaleY, - Font *font, - SDL_Color fontColor, - std::string layoutKey, - std::string collectionName, +ScrollingList::ScrollingList(Configuration *c, + float scaleX, + float scaleY, + Font *font, + SDL_Color fontColor, + std::string layoutKey, + std::string collectionName, std::string imageType) -: IsScrollChangedStarted(true) -, IsScrollChangedSignalled(false) -, IsScrollChangedComplete(false) -, SpriteList(NULL) -, ScrollPoints(NULL) -, TweenEnterTime(0) -, FirstSpriteIndex(0) -, SelectedSpriteListIndex(0) -, CurrentAnimateTime(0) // in seconds -, ScrollTime(0) // in seconds -, CurrentScrollDirection(ScrollDirectionIdle) -, RequestedScrollDirection(ScrollDirectionIdle) -, CurrentScrollState(ScrollStateIdle) -, ScrollAcceleration(6) // todo: make configurable -, ScrollVelocity(0) -, Config(c) -, ScaleX(scaleX) -, ScaleY(scaleY) -, FontInst(font) -, FontColor(fontColor) -, LayoutKey(layoutKey) -, CollectionName(collectionName) -, ImageType(imageType) -, MaxLayer(0) + : IsScrollChangedStarted(true) + , IsScrollChangedSignalled(false) + , IsScrollChangedComplete(false) + , SpriteList(NULL) + , ScrollPoints(NULL) + , TweenEnterTime(0) + , FirstSpriteIndex(0) + , SelectedSpriteListIndex(0) + , CurrentAnimateTime(0) // in seconds + , ScrollTime(0) // in seconds + , CurrentScrollDirection(ScrollDirectionIdle) + , RequestedScrollDirection(ScrollDirectionIdle) + , CurrentScrollState(ScrollStateIdle) + , ScrollAcceleration(6) // todo: make configurable + , ScrollVelocity(0) + , Config(c) + , ScaleX(scaleX) + , ScaleY(scaleY) + , FontInst(font) + , FontColor(fontColor) + , LayoutKey(layoutKey) + , CollectionName(collectionName) + , ImageType(imageType) + , MaxLayer(0) { } @@ -63,592 +63,592 @@ ScrollingList::~ScrollingList() void ScrollingList::SetItems(std::vector *spriteList) { - SpriteList = spriteList; - FirstSpriteIndex = 0; + SpriteList = spriteList; + FirstSpriteIndex = 0; - // loop the scroll points if there are not enough - unsigned int originalSize = SpriteList->size(); + // loop the scroll points if there are not enough + unsigned int originalSize = SpriteList->size(); - while(ScrollPoints && ScrollPoints->size()+4 > SpriteList->size()) - { - for(unsigned int i = 0; i < originalSize; ++i) - { - Item *newItem = new Item(); - Item *originalItem = SpriteList->at(i)->GetCollectionItem(); + while(ScrollPoints && ScrollPoints->size()+4 > SpriteList->size()) + { + for(unsigned int i = 0; i < originalSize; ++i) + { + Item *newItem = new Item(); + Item *originalItem = SpriteList->at(i)->GetCollectionItem(); - *newItem = *originalItem; - ComponentItemBinding *newSprite = new ComponentItemBinding(newItem); - SpriteList->push_back(newSprite); - } - } - for(unsigned int i = 0; SpriteList && ScrollPoints && i < SelectedSpriteListIndex; ++i) - { - CircularDecrement(FirstSpriteIndex, SpriteList); - } + *newItem = *originalItem; + ComponentItemBinding *newSprite = new ComponentItemBinding(newItem); + SpriteList->push_back(newSprite); + } + } + for(unsigned int i = 0; SpriteList && ScrollPoints && i < SelectedSpriteListIndex; ++i) + { + CircularDecrement(FirstSpriteIndex, SpriteList); + } - IsScrollChangedComplete = true; + IsScrollChangedComplete = true; } void ScrollingList::SetPoints(std::vector *scrollPoints) { - ScrollPoints = scrollPoints; - for(unsigned int i = 0; i != scrollPoints->size(); ++i) - { - ViewInfo *info = scrollPoints->at(i); - MaxLayer = (MaxLayer < info->GetLayer()) ? MaxLayer : info->GetLayer(); - } + ScrollPoints = scrollPoints; + for(unsigned int i = 0; i != scrollPoints->size(); ++i) + { + ViewInfo *info = scrollPoints->at(i); + MaxLayer = (MaxLayer < info->GetLayer()) ? MaxLayer : info->GetLayer(); + } } void ScrollingList::SetSelectedIndex(int selectedIndex) { - SelectedSpriteListIndex = selectedIndex; + SelectedSpriteListIndex = selectedIndex; - for(unsigned int i = 0; SpriteList && ScrollPoints && i < SelectedSpriteListIndex; ++i) - { - CircularDecrement(FirstSpriteIndex, SpriteList); - } + for(unsigned int i = 0; SpriteList && ScrollPoints && i < SelectedSpriteListIndex; ++i) + { + CircularDecrement(FirstSpriteIndex, SpriteList); + } } void ScrollingList::Click() { - if(CurrentScrollDirection == ScrollDirectionBack) - { - CircularDecrement(FirstSpriteIndex, SpriteList); - IsScrollChangedComplete = true; - } - if(CurrentScrollDirection == ScrollDirectionForward) - { - CircularIncrement(FirstSpriteIndex, SpriteList); - IsScrollChangedComplete = true; - } + if(CurrentScrollDirection == ScrollDirectionBack) + { + CircularDecrement(FirstSpriteIndex, SpriteList); + IsScrollChangedComplete = true; + } + if(CurrentScrollDirection == ScrollDirectionForward) + { + CircularIncrement(FirstSpriteIndex, SpriteList); + IsScrollChangedComplete = true; + } } unsigned int ScrollingList::GetNextTween(unsigned int currentIndex, std::vector *list) { - if(CurrentScrollDirection == ScrollDirectionForward) - { - CircularDecrement(currentIndex, list); - } - else if(CurrentScrollDirection == ScrollDirectionBack) - { - CircularIncrement(currentIndex, list); - } + if(CurrentScrollDirection == ScrollDirectionForward) + { + CircularDecrement(currentIndex, list); + } + else if(CurrentScrollDirection == ScrollDirectionBack) + { + CircularIncrement(currentIndex, list); + } - return currentIndex; + return currentIndex; } void ScrollingList::PageUp() { - if(ScrollPoints && ScrollPoints->size() > 4) - { - ScrollVelocity = 0; - unsigned int counts = ScrollPoints->size() - 4; + if(ScrollPoints && ScrollPoints->size() > 4) + { + ScrollVelocity = 0; + unsigned int counts = ScrollPoints->size() - 4; - for(unsigned int i = 0; i < counts; i++) - { - CircularDecrement(FirstSpriteIndex, SpriteList); - } - } + for(unsigned int i = 0; i < counts; i++) + { + CircularDecrement(FirstSpriteIndex, SpriteList); + } + } - CurrentScrollState = ScrollStatePageChange; - IsScrollChangedStarted = true; - IsScrollChangedSignalled = false; - IsScrollChangedComplete = false; + CurrentScrollState = ScrollStatePageChange; + IsScrollChangedStarted = true; + IsScrollChangedSignalled = false; + IsScrollChangedComplete = false; } void ScrollingList::PageDown() { - if(ScrollPoints && ScrollPoints->size() > 4) - { - unsigned int counts = ScrollPoints->size() - 4; + if(ScrollPoints && ScrollPoints->size() > 4) + { + unsigned int counts = ScrollPoints->size() - 4; - ScrollVelocity = 0; - for(unsigned int i = 0; i < counts; i++) - { - CircularIncrement(FirstSpriteIndex, SpriteList); - } - } + ScrollVelocity = 0; + for(unsigned int i = 0; i < counts; i++) + { + CircularIncrement(FirstSpriteIndex, SpriteList); + } + } - CurrentScrollState = ScrollStatePageChange; - IsScrollChangedStarted = true; - IsScrollChangedSignalled = false; - IsScrollChangedComplete = false; + CurrentScrollState = ScrollStatePageChange; + IsScrollChangedStarted = true; + IsScrollChangedSignalled = false; + IsScrollChangedComplete = false; } void ScrollingList::FreeGraphicsMemory() { - Component::FreeGraphicsMemory(); - TweenEnterTime = 0; - CurrentAnimateTime = 0; - ScrollTime = 0; - CurrentScrollDirection = ScrollDirectionIdle; - RequestedScrollDirection = ScrollDirectionIdle; - CurrentScrollState = ScrollStateIdle; - ScrollAcceleration = 6; // todo: make configurable - ScrollVelocity = 0; + Component::FreeGraphicsMemory(); + TweenEnterTime = 0; + CurrentAnimateTime = 0; + ScrollTime = 0; + CurrentScrollDirection = ScrollDirectionIdle; + RequestedScrollDirection = ScrollDirectionIdle; + CurrentScrollState = ScrollStateIdle; + ScrollAcceleration = 6; // todo: make configurable + ScrollVelocity = 0; - for(unsigned int i = 0; i < SpriteList->size(); i++) - { - ComponentItemBinding *s = SpriteList->at(i); + for(unsigned int i = 0; i < SpriteList->size(); i++) + { + ComponentItemBinding *s = SpriteList->at(i); - DeallocateTexture(s); - } + DeallocateTexture(s); + } } void ScrollingList::Update(float dt) { - float scrollPeriod = 0; - Component::Update(dt); + float scrollPeriod = 0; + Component::Update(dt); - if(!ScrollPoints) - { - return; - } + if(!ScrollPoints) + { + return; + } - switch(CurrentScrollState) - { - case ScrollStateActive: - if(RequestedScrollDirection != CurrentScrollDirection) - { + switch(CurrentScrollState) + { + case ScrollStateActive: + if(RequestedScrollDirection != CurrentScrollDirection) + { CurrentScrollState = ScrollStateStopping; - } + } - break; + break; - case ScrollStateIdle: - ScrollTime = 0; - CurrentAnimateTime = 0; - ScrollVelocity = 0; + case ScrollStateIdle: + ScrollTime = 0; + CurrentAnimateTime = 0; + ScrollVelocity = 0; - if(RequestedScrollDirection != ScrollDirectionIdle) - { + if(RequestedScrollDirection != ScrollDirectionIdle) + { CurrentScrollState = ScrollStateActive; CurrentScrollDirection = RequestedScrollDirection; - } - break; - default: - break; + } + break; + default: + break; - }; + }; - if(CurrentScrollState != ScrollStatePageChange && CurrentScrollState != ScrollStateIdle) - { - IsScrollChangedStarted = true; - ScrollTime += dt; - CurrentAnimateTime += dt; - ScrollVelocity = ScrollTime * ScrollAcceleration; + if(CurrentScrollState != ScrollStatePageChange && CurrentScrollState != ScrollStateIdle) + { + IsScrollChangedStarted = true; + ScrollTime += dt; + CurrentAnimateTime += dt; + ScrollVelocity = ScrollTime * ScrollAcceleration; - // clip at 5 items scrolled per second - if(ScrollVelocity > 30) - { - ScrollVelocity = 30; - } - if(ScrollVelocity > 0) - { - scrollPeriod = 1 / ScrollVelocity; - } + // clip at 5 items scrolled per second + if(ScrollVelocity > 30) + { + ScrollVelocity = 30; + } + if(ScrollVelocity > 0) + { + scrollPeriod = 1 / ScrollVelocity; + } - // have we exceeded the time of when to stop on the next item in the list? - if(CurrentScrollState == ScrollStateStopping && CurrentAnimateTime >= scrollPeriod) - { - Click(); - CurrentAnimateTime = 0; - ScrollVelocity = 0; - CurrentScrollState = ScrollStateIdle; - } - } + // have we exceeded the time of when to stop on the next item in the list? + if(CurrentScrollState == ScrollStateStopping && CurrentAnimateTime >= scrollPeriod) + { + Click(); + CurrentAnimateTime = 0; + ScrollVelocity = 0; + CurrentScrollState = ScrollStateIdle; + } + } - while(CurrentScrollState != ScrollStatePageChange && ScrollVelocity > 0 && CurrentAnimateTime >= scrollPeriod) - { - Click(); - CurrentAnimateTime -= scrollPeriod; - } + while(CurrentScrollState != ScrollStatePageChange && ScrollVelocity > 0 && CurrentAnimateTime >= scrollPeriod) + { + Click(); + CurrentAnimateTime -= scrollPeriod; + } - if(ScrollPoints && SpriteList->size() > 0 && FirstSpriteIndex < SpriteList->size()) - { - unsigned int spriteIndex = FirstSpriteIndex; - unsigned int numIterations = (ScrollPoints->size() > SpriteList->size()) ? SpriteList->size() : ScrollPoints->size(); - unsigned int start = (ScrollPoints->size() > SpriteList->size()) ? SelectedSpriteListIndex : 0; + if(ScrollPoints && SpriteList->size() > 0 && FirstSpriteIndex < SpriteList->size()) + { + unsigned int spriteIndex = FirstSpriteIndex; + unsigned int numIterations = (ScrollPoints->size() > SpriteList->size()) ? SpriteList->size() : ScrollPoints->size(); + unsigned int start = (ScrollPoints->size() > SpriteList->size()) ? SelectedSpriteListIndex : 0; - for(unsigned int i = start; i < start+numIterations; i++) - { - ComponentItemBinding *s = SpriteList->at(spriteIndex); - unsigned int nextI = GetNextTween(i, ScrollPoints); + for(unsigned int i = start; i < start+numIterations; i++) + { + ComponentItemBinding *s = SpriteList->at(spriteIndex); + unsigned int nextI = GetNextTween(i, ScrollPoints); - ViewInfo *currentViewInfo = ScrollPoints->at(i); - ViewInfo *nextViewInfo = ScrollPoints->at(nextI); + ViewInfo *currentViewInfo = ScrollPoints->at(i); + ViewInfo *nextViewInfo = ScrollPoints->at(nextI); - AllocateTexture(s); + AllocateTexture(s); - Component *c = s->GetComponent(); - if(c) - { - currentViewInfo->SetImageHeight(c->GetBaseViewInfo()->GetImageHeight()); - currentViewInfo->SetImageWidth(c->GetBaseViewInfo()->GetImageWidth()); - nextViewInfo->SetImageHeight(c->GetBaseViewInfo()->GetImageHeight()); - nextViewInfo->SetImageWidth(c->GetBaseViewInfo()->GetImageWidth()); + Component *c = s->GetComponent(); + if(c) + { + currentViewInfo->SetImageHeight(c->GetBaseViewInfo()->GetImageHeight()); + currentViewInfo->SetImageWidth(c->GetBaseViewInfo()->GetImageWidth()); + nextViewInfo->SetImageHeight(c->GetBaseViewInfo()->GetImageHeight()); + nextViewInfo->SetImageWidth(c->GetBaseViewInfo()->GetImageWidth()); - //todo: 30 is a magic number - ViewInfo *spriteViewInfo = c->GetBaseViewInfo(); + //todo: 30 is a magic number + ViewInfo *spriteViewInfo = c->GetBaseViewInfo(); - spriteViewInfo->SetX(Tween::AnimateSingle(LINEAR, currentViewInfo->GetX(), nextViewInfo->GetX(), scrollPeriod, CurrentAnimateTime)); - spriteViewInfo->SetY(Tween::AnimateSingle(LINEAR, currentViewInfo->GetY(), nextViewInfo->GetY(), scrollPeriod, CurrentAnimateTime)); - spriteViewInfo->SetXOrigin(Tween::AnimateSingle(LINEAR, currentViewInfo->GetXOrigin(), nextViewInfo->GetXOrigin(), scrollPeriod, CurrentAnimateTime)); - spriteViewInfo->SetYOrigin(Tween::AnimateSingle(LINEAR, currentViewInfo->GetYOrigin(), nextViewInfo->GetYOrigin(), scrollPeriod, CurrentAnimateTime)); - spriteViewInfo->SetXOffset(Tween::AnimateSingle(LINEAR, currentViewInfo->GetXOffset(), nextViewInfo->GetXOffset(), scrollPeriod, CurrentAnimateTime)); - spriteViewInfo->SetYOffset(Tween::AnimateSingle(LINEAR, currentViewInfo->GetYOffset(), nextViewInfo->GetYOffset(), scrollPeriod, CurrentAnimateTime)); - spriteViewInfo->SetHeight(Tween::AnimateSingle(LINEAR, currentViewInfo->GetHeight(), nextViewInfo->GetHeight(), scrollPeriod, CurrentAnimateTime)); - spriteViewInfo->SetWidth(Tween::AnimateSingle(LINEAR, currentViewInfo->GetWidth(), nextViewInfo->GetWidth(), scrollPeriod, CurrentAnimateTime)); - spriteViewInfo->SetTransparency(Tween::AnimateSingle(LINEAR, currentViewInfo->GetTransparency(), nextViewInfo->GetTransparency(), scrollPeriod, CurrentAnimateTime)); - spriteViewInfo->SetAngle(Tween::AnimateSingle(LINEAR, currentViewInfo->GetAngle(), nextViewInfo->GetAngle(), scrollPeriod, CurrentAnimateTime)); - spriteViewInfo->SetFontSize(Tween::AnimateSingle(LINEAR, currentViewInfo->GetFontSize(), nextViewInfo->GetFontSize(), scrollPeriod, CurrentAnimateTime)); - c->Update(dt); + spriteViewInfo->SetX(Tween::AnimateSingle(LINEAR, currentViewInfo->GetX(), nextViewInfo->GetX(), scrollPeriod, CurrentAnimateTime)); + spriteViewInfo->SetY(Tween::AnimateSingle(LINEAR, currentViewInfo->GetY(), nextViewInfo->GetY(), scrollPeriod, CurrentAnimateTime)); + spriteViewInfo->SetXOrigin(Tween::AnimateSingle(LINEAR, currentViewInfo->GetXOrigin(), nextViewInfo->GetXOrigin(), scrollPeriod, CurrentAnimateTime)); + spriteViewInfo->SetYOrigin(Tween::AnimateSingle(LINEAR, currentViewInfo->GetYOrigin(), nextViewInfo->GetYOrigin(), scrollPeriod, CurrentAnimateTime)); + spriteViewInfo->SetXOffset(Tween::AnimateSingle(LINEAR, currentViewInfo->GetXOffset(), nextViewInfo->GetXOffset(), scrollPeriod, CurrentAnimateTime)); + spriteViewInfo->SetYOffset(Tween::AnimateSingle(LINEAR, currentViewInfo->GetYOffset(), nextViewInfo->GetYOffset(), scrollPeriod, CurrentAnimateTime)); + spriteViewInfo->SetHeight(Tween::AnimateSingle(LINEAR, currentViewInfo->GetHeight(), nextViewInfo->GetHeight(), scrollPeriod, CurrentAnimateTime)); + spriteViewInfo->SetWidth(Tween::AnimateSingle(LINEAR, currentViewInfo->GetWidth(), nextViewInfo->GetWidth(), scrollPeriod, CurrentAnimateTime)); + spriteViewInfo->SetTransparency(Tween::AnimateSingle(LINEAR, currentViewInfo->GetTransparency(), nextViewInfo->GetTransparency(), scrollPeriod, CurrentAnimateTime)); + spriteViewInfo->SetAngle(Tween::AnimateSingle(LINEAR, currentViewInfo->GetAngle(), nextViewInfo->GetAngle(), scrollPeriod, CurrentAnimateTime)); + spriteViewInfo->SetFontSize(Tween::AnimateSingle(LINEAR, currentViewInfo->GetFontSize(), nextViewInfo->GetFontSize(), scrollPeriod, CurrentAnimateTime)); + c->Update(dt); - } + } - CircularIncrement(spriteIndex, SpriteList); - } - - // start freeing up memory if the list is too large - if(SpriteList->size() + 4 > ScrollPoints->size()) - { - spriteIndex = FirstSpriteIndex; - - CircularDecrement(spriteIndex, SpriteList); - DeallocateTexture(SpriteList->at(spriteIndex)); - - CircularDecrement(spriteIndex, SpriteList); - DeallocateTexture(SpriteList->at(spriteIndex)); - - - // point to the end of the list to start deallocating.. - // It's not fast, but it's easy to read - spriteIndex = FirstSpriteIndex; - for(unsigned int i = 0; i < ScrollPoints->size(); i++) - { CircularIncrement(spriteIndex, SpriteList); - } + } - CircularIncrement(spriteIndex, SpriteList); - DeallocateTexture(SpriteList->at(spriteIndex)); + // start freeing up memory if the list is too large + if(SpriteList->size() + 4 > ScrollPoints->size()) + { + spriteIndex = FirstSpriteIndex; - CircularIncrement(spriteIndex, SpriteList); - DeallocateTexture(SpriteList->at(spriteIndex)); - } - } + CircularDecrement(spriteIndex, SpriteList); + DeallocateTexture(SpriteList->at(spriteIndex)); - if(IsScrollChangedStarted && !IsScrollChangedSignalled) - { - IsScrollChangedSignalled = true; - ComponentItemBinding *sprite = GetPendingCollectionItemSprite(); - Item *item = NULL; + CircularDecrement(spriteIndex, SpriteList); + DeallocateTexture(SpriteList->at(spriteIndex)); - if(sprite) - { - item = sprite->GetCollectionItem(); - } - for(std::vector::iterator it = NotificationComponents.begin(); - it != NotificationComponents.end(); - it++) - { - MenuNotifierInterface *c = *it; - if(c && item) - { - c->OnNewItemSelected(item); - } - } + // point to the end of the list to start deallocating.. + // It's not fast, but it's easy to read + spriteIndex = FirstSpriteIndex; + for(unsigned int i = 0; i < ScrollPoints->size(); i++) + { + CircularIncrement(spriteIndex, SpriteList); + } - if(CurrentScrollState == ScrollStatePageChange) - { - IsScrollChangedComplete = true; - CurrentScrollState = ScrollStateIdle; - } - } + CircularIncrement(spriteIndex, SpriteList); + DeallocateTexture(SpriteList->at(spriteIndex)); - if(IsScrollChangedStarted && IsScrollChangedSignalled && IsScrollChangedComplete) - { - IsScrollChangedStarted = false; - IsScrollChangedComplete = false; - IsScrollChangedSignalled = false; - } + CircularIncrement(spriteIndex, SpriteList); + DeallocateTexture(SpriteList->at(spriteIndex)); + } + } + + if(IsScrollChangedStarted && !IsScrollChangedSignalled) + { + IsScrollChangedSignalled = true; + ComponentItemBinding *sprite = GetPendingCollectionItemSprite(); + Item *item = NULL; + + if(sprite) + { + item = sprite->GetCollectionItem(); + } + + for(std::vector::iterator it = NotificationComponents.begin(); + it != NotificationComponents.end(); + it++) + { + MenuNotifierInterface *c = *it; + if(c && item) + { + c->OnNewItemSelected(item); + } + } + + if(CurrentScrollState == ScrollStatePageChange) + { + IsScrollChangedComplete = true; + CurrentScrollState = ScrollStateIdle; + } + } + + if(IsScrollChangedStarted && IsScrollChangedSignalled && IsScrollChangedComplete) + { + IsScrollChangedStarted = false; + IsScrollChangedComplete = false; + IsScrollChangedSignalled = false; + } } void ScrollingList::AllocateTexture(ComponentItemBinding *s) { - //todo: move this outside of the Draw routine - if(s && s->GetComponent() == NULL) - { - const Item *item = s->GetCollectionItem(); - //todo: will create a runtime fault if not of the right type - //todo: remove coupling from knowing the collection name + //todo: move this outside of the Draw routine + if(s && s->GetComponent() == NULL) + { + const Item *item = s->GetCollectionItem(); + //todo: will create a runtime fault if not of the right type + //todo: remove coupling from knowing the collection name - std::string collectionKey ="collections." + CollectionName + ".media." + ImageType; - std::string videoKey ="collections." + CollectionName + ".media.video"; - std::string imagePath; - std::string videoPath; + std::string collectionKey ="collections." + CollectionName + ".media." + ImageType; + std::string videoKey ="collections." + CollectionName + ".media.video"; + std::string imagePath; + std::string videoPath; - Component *t = NULL; + Component *t = NULL; - /* - // todo: to be supported at a later date - if(c->GetProperty(videoKey, videoPath)) - { - t = new VideoComponent(videoPath, item->GetFullTitle(), ScaleX, ScaleY); - } -*/ - if(!t && Config->GetPropertyAbsolutePath(collectionKey, imagePath)) - { - ImageBuilder imageBuild; - t = imageBuild.CreateImage(imagePath, item->GetName(), ScaleX, ScaleY); + /* + // todo: to be supported at a later date + if(c->GetProperty(videoKey, videoPath)) + { + t = new VideoComponent(videoPath, item->GetFullTitle(), ScaleX, ScaleY); + } + */ + if(!t && Config->GetPropertyAbsolutePath(collectionKey, imagePath)) + { + ImageBuilder imageBuild; + t = imageBuild.CreateImage(imagePath, item->GetName(), ScaleX, ScaleY); - if(!t && item->GetTitle() != item->GetFullTitle()) - { - t = imageBuild.CreateImage(imagePath, item->GetFullTitle(), ScaleX, ScaleY); - } - } - if (!t) - { - t = new Text(item->GetTitle(), FontInst, FontColor, ScaleX, ScaleY); - } + if(!t && item->GetTitle() != item->GetFullTitle()) + { + t = imageBuild.CreateImage(imagePath, item->GetFullTitle(), ScaleX, ScaleY); + } + } + if (!t) + { + t = new Text(item->GetTitle(), FontInst, FontColor, ScaleX, ScaleY); + } - if(t) - { - s->SetComponent(t); - } - } + if(t) + { + s->SetComponent(t); + } + } } void ScrollingList::DeallocateTexture(ComponentItemBinding *s) { - if(s && s->GetComponent() != NULL) - { - delete s->GetComponent(); - } - s->SetComponent(NULL); + if(s && s->GetComponent() != NULL) + { + delete s->GetComponent(); + } + s->SetComponent(NULL); } void ScrollingList::Draw() { - //todo: Poor design implementation. - // caller should instead call ScrollingList::Draw(unsigned int layer) + //todo: Poor design implementation. + // caller should instead call ScrollingList::Draw(unsigned int layer) } //todo: this is kind of a hack. Aggregation needs to happen differently void ScrollingList::Draw(unsigned int layer) { - if(ScrollPoints && SpriteList && SpriteList->size() > 0 && FirstSpriteIndex < SpriteList->size()) - { - unsigned int spriteIndex = FirstSpriteIndex; + if(ScrollPoints && SpriteList && SpriteList->size() > 0 && FirstSpriteIndex < SpriteList->size()) + { + unsigned int spriteIndex = FirstSpriteIndex; - for(unsigned int i = 0; i < ScrollPoints->size(); i++) - { - std::vector::iterator it = SpriteList->begin() + spriteIndex; - Component *c = (*it)->GetComponent(); - ViewInfo *currentViewInfo = ScrollPoints->at(i); + for(unsigned int i = 0; i < ScrollPoints->size(); i++) + { + std::vector::iterator it = SpriteList->begin() + spriteIndex; + Component *c = (*it)->GetComponent(); + ViewInfo *currentViewInfo = ScrollPoints->at(i); - if(currentViewInfo && currentViewInfo->GetLayer() == layer) - { - c->Draw(); - } - CircularIncrement(spriteIndex, SpriteList); - } - } + if(currentViewInfo && currentViewInfo->GetLayer() == layer) + { + c->Draw(); + } + CircularIncrement(spriteIndex, SpriteList); + } + } } void ScrollingList::SetScrollDirection(ScrollDirection direction) { - RequestedScrollDirection = direction; + RequestedScrollDirection = direction; } void ScrollingList::RemoveSelectedItem() { - ComponentItemBinding *sprite = GetSelectedCollectionItemSprite(); - if(sprite) - { - Item *item = sprite->GetCollectionItem(); - DeallocateTexture(sprite); - int index = (FirstSpriteIndex + SelectedSpriteListIndex) % SpriteList->size(); + ComponentItemBinding *sprite = GetSelectedCollectionItemSprite(); + if(sprite) + { + Item *item = sprite->GetCollectionItem(); + DeallocateTexture(sprite); + int index = (FirstSpriteIndex + SelectedSpriteListIndex) % SpriteList->size(); - std::vector::iterator it = SpriteList->begin() + index; + std::vector::iterator it = SpriteList->begin() + index; - SpriteList->erase(it); - delete sprite; + SpriteList->erase(it); + delete sprite; - if(item) - { - delete item; - } + if(item) + { + delete item; + } - if(SelectedSpriteListIndex >= SpriteList->size()) - { - SelectedSpriteListIndex = 0; - } - if(FirstSpriteIndex >= SpriteList->size()) - { - FirstSpriteIndex = 0; - } - } - IsScrollChangedComplete = true; + if(SelectedSpriteListIndex >= SpriteList->size()) + { + SelectedSpriteListIndex = 0; + } + if(FirstSpriteIndex >= SpriteList->size()) + { + FirstSpriteIndex = 0; + } + } + IsScrollChangedComplete = true; } std::vector *ScrollingList::GetCollectionItemSprites() { - return SpriteList; + return SpriteList; } ComponentItemBinding* ScrollingList::GetSelectedCollectionItemSprite() { - ComponentItemBinding *item = NULL; + ComponentItemBinding *item = NULL; - if(SpriteList && SpriteList->size() > 0) - { - int index = (FirstSpriteIndex + SelectedSpriteListIndex) % SpriteList->size(); + if(SpriteList && SpriteList->size() > 0) + { + int index = (FirstSpriteIndex + SelectedSpriteListIndex) % SpriteList->size(); - item = SpriteList->at(index); - } + item = SpriteList->at(index); + } - return item; + return item; } ComponentItemBinding* ScrollingList::GetPendingCollectionItemSprite() { - ComponentItemBinding *item = NULL; - unsigned int index = FirstSpriteIndex; - if(CurrentScrollState != ScrollStatePageChange) - { - if(CurrentScrollDirection == ScrollDirectionBack) - { - CircularDecrement(index, SpriteList); - } - if(CurrentScrollDirection == ScrollDirectionForward) - { - CircularIncrement(index, SpriteList); - } - } - if(SpriteList && SpriteList->size() > 0) - { - index = (index + SelectedSpriteListIndex) % SpriteList->size(); + ComponentItemBinding *item = NULL; + unsigned int index = FirstSpriteIndex; + if(CurrentScrollState != ScrollStatePageChange) + { + if(CurrentScrollDirection == ScrollDirectionBack) + { + CircularDecrement(index, SpriteList); + } + if(CurrentScrollDirection == ScrollDirectionForward) + { + CircularIncrement(index, SpriteList); + } + } + if(SpriteList && SpriteList->size() > 0) + { + index = (index + SelectedSpriteListIndex) % SpriteList->size(); - item = SpriteList->at(index); - } + item = SpriteList->at(index); + } - return item; + return item; } void ScrollingList::AddComponentForNotifications(MenuNotifierInterface *c) { - NotificationComponents.push_back(c); + NotificationComponents.push_back(c); } void ScrollingList::RemoveComponentForNotifications(MenuNotifierInterface *c) { - for(std::vector::iterator it = NotificationComponents.begin(); - it != NotificationComponents.end(); - it++) - { - if(c == *it) - { - NotificationComponents.erase(it); - break; - } - } + for(std::vector::iterator it = NotificationComponents.begin(); + it != NotificationComponents.end(); + it++) + { + if(c == *it) + { + NotificationComponents.erase(it); + break; + } + } } ComponentItemBinding* ScrollingList::GetPendingSelectedCollectionItemSprite() { - ComponentItemBinding *item = NULL; + ComponentItemBinding *item = NULL; - unsigned int index = SelectedSpriteListIndex; + unsigned int index = SelectedSpriteListIndex; - if(CurrentScrollDirection == ScrollDirectionBack) - { - CircularDecrement(index, SpriteList); - } - if(CurrentScrollDirection == ScrollDirectionForward) - { - CircularIncrement(index, SpriteList); - } + if(CurrentScrollDirection == ScrollDirectionBack) + { + CircularDecrement(index, SpriteList); + } + if(CurrentScrollDirection == ScrollDirectionForward) + { + CircularIncrement(index, SpriteList); + } - if(SpriteList && SpriteList->size() > 0) - { - index = (index + SelectedSpriteListIndex) % SpriteList->size(); + if(SpriteList && SpriteList->size() > 0) + { + index = (index + SelectedSpriteListIndex) % SpriteList->size(); - item = SpriteList->at(index); - } + item = SpriteList->at(index); + } - return item; + return item; } bool ScrollingList::IsIdle() { - return (Component::IsIdle() && CurrentScrollState == ScrollStateIdle); + return (Component::IsIdle() && CurrentScrollState == ScrollStateIdle); } void ScrollingList::CircularIncrement(unsigned int &index, std::vector* list) { - index++; + index++; - if(index >= list->size()) - { - index = 0; - } + if(index >= list->size()) + { + index = 0; + } } void ScrollingList::CircularDecrement(unsigned int &index, std::vector* list) { - if(index > 0) - { - index--; - } - else - { - if(list->size() > 0) - { - index = list->size() - 1; - } - else - { - index = 0; - } - } + if(index > 0) + { + index--; + } + else + { + if(list->size() > 0) + { + index = list->size() - 1; + } + else + { + index = 0; + } + } } void ScrollingList::CircularIncrement(unsigned int &index, std::vector *list) { - index++; + index++; - if(index >= list->size()) - { - index = 0; - } + if(index >= list->size()) + { + index = 0; + } } void ScrollingList::CircularDecrement(unsigned int &index, std::vector *list) { - if(index > 0) - { - index--; - } - else - { - if(list && list->size() > 0) - { - index = list->size() - 1; - } - else - { - index = 0; - } - } + if(index > 0) + { + index--; + } + else + { + if(list && list->size() > 0) + { + index = list->size() - 1; + } + else + { + index = 0; + } + } } diff --git a/Source/Graphics/Component/ScrollingList.h b/Source/Graphics/Component/ScrollingList.h index 29180b0..c34b558 100644 --- a/Source/Graphics/Component/ScrollingList.h +++ b/Source/Graphics/Component/ScrollingList.h @@ -23,83 +23,83 @@ class Font; class ScrollingList : public Component { public: - enum ScrollDirection - { - ScrollDirectionBack, - ScrollDirectionForward, - ScrollDirectionIdle, + enum ScrollDirection + { + ScrollDirectionBack, + ScrollDirectionForward, + ScrollDirectionIdle, - }; + }; - ScrollingList(Configuration *c, float scaleX, float scaleY, Font *font, SDL_Color fontColor, std::string layoutKey, std::string CollectionName, std::string imageType); - virtual ~ScrollingList(); - void AllocateTexture(ComponentItemBinding *s); - void DeallocateTexture(ComponentItemBinding *s); - void SetItems(std::vector *spriteList); - void SetPoints(std::vector *scrollPoints); - void SetScrollDirection(ScrollDirection direction); - void PageUp(); - void PageDown(); - bool IsIdle(); - void SetSelectedIndex(int selectedIndex); - ComponentItemBinding *GetSelectedCollectionItemSprite(); - ComponentItemBinding *GetPendingCollectionItemSprite(); - ComponentItemBinding *GetPendingSelectedCollectionItemSprite(); - void AddComponentForNotifications(MenuNotifierInterface *c); - void RemoveComponentForNotifications(MenuNotifierInterface *c); - std::vector *GetCollectionItemSprites(); - void RemoveSelectedItem(); - void FreeGraphicsMemory(); - void Update(float dt); - void Draw(); - void Draw(unsigned int layer); + ScrollingList(Configuration *c, float scaleX, float scaleY, Font *font, SDL_Color fontColor, std::string layoutKey, std::string CollectionName, std::string imageType); + virtual ~ScrollingList(); + void AllocateTexture(ComponentItemBinding *s); + void DeallocateTexture(ComponentItemBinding *s); + void SetItems(std::vector *spriteList); + void SetPoints(std::vector *scrollPoints); + void SetScrollDirection(ScrollDirection direction); + void PageUp(); + void PageDown(); + bool IsIdle(); + void SetSelectedIndex(int selectedIndex); + ComponentItemBinding *GetSelectedCollectionItemSprite(); + ComponentItemBinding *GetPendingCollectionItemSprite(); + ComponentItemBinding *GetPendingSelectedCollectionItemSprite(); + void AddComponentForNotifications(MenuNotifierInterface *c); + void RemoveComponentForNotifications(MenuNotifierInterface *c); + std::vector *GetCollectionItemSprites(); + void RemoveSelectedItem(); + void FreeGraphicsMemory(); + void Update(float dt); + void Draw(); + void Draw(unsigned int layer); private: - void Click(); - unsigned int GetNextTween(unsigned int currentIndex, std::vector *list); - bool IsScrollChangedStarted; - bool IsScrollChangedSignalled; - bool IsScrollChangedComplete; + void Click(); + unsigned int GetNextTween(unsigned int currentIndex, std::vector *list); + bool IsScrollChangedStarted; + bool IsScrollChangedSignalled; + bool IsScrollChangedComplete; -enum ScrollState - { - ScrollStateActive, - ScrollStatePageChange, - ScrollStateStopping, - ScrollStateIdle - }; + enum ScrollState + { + ScrollStateActive, + ScrollStatePageChange, + ScrollStateStopping, + ScrollStateIdle + }; - std::vector *SpriteList; - std::vector *ScrollPoints; - std::vector NotificationComponents; - float TweenEnterTime; + std::vector *SpriteList; + std::vector *ScrollPoints; + std::vector NotificationComponents; + float TweenEnterTime; - unsigned int FirstSpriteIndex; - unsigned int SelectedSpriteListIndex; - float CurrentAnimateTime; - float ScrollTime; + unsigned int FirstSpriteIndex; + unsigned int SelectedSpriteListIndex; + float CurrentAnimateTime; + float ScrollTime; - ScrollDirection CurrentScrollDirection; - ScrollDirection RequestedScrollDirection; - ScrollState CurrentScrollState; - float ScrollAcceleration; - float ScrollVelocity; + ScrollDirection CurrentScrollDirection; + ScrollDirection RequestedScrollDirection; + ScrollState CurrentScrollState; + float ScrollAcceleration; + float ScrollVelocity; - void CircularIncrement(unsigned &index, std::vector *list); - void CircularDecrement(unsigned &index, std::vector *list); - void CircularIncrement(unsigned &index, std::vector *list); - void CircularDecrement(unsigned &index, std::vector *list); - void UpdateOffset(float dt); + void CircularIncrement(unsigned &index, std::vector *list); + void CircularDecrement(unsigned &index, std::vector *list); + void CircularIncrement(unsigned &index, std::vector *list); + void CircularDecrement(unsigned &index, std::vector *list); + void UpdateOffset(float dt); - std::string Collection; - Configuration *Config; - float ScaleX; - float ScaleY; - Font *FontInst; - SDL_Color FontColor; - std::string LayoutKey; - std::string CollectionName; - std::string ImageType; - unsigned int MaxLayer; + std::string Collection; + Configuration *Config; + float ScaleX; + float ScaleY; + Font *FontInst; + SDL_Color FontColor; + std::string LayoutKey; + std::string CollectionName; + std::string ImageType; + unsigned int MaxLayer; }; diff --git a/Source/Graphics/Component/Text.cpp b/Source/Graphics/Component/Text.cpp index 18141cf..e217295 100644 --- a/Source/Graphics/Component/Text.cpp +++ b/Source/Graphics/Component/Text.cpp @@ -8,96 +8,96 @@ #include Text::Text(std::string text, Font *font, SDL_Color fontColor, float scaleX, float scaleY) -: TextData(text) -, FontInst(font) -, FontColor(fontColor) -, ScaleX(scaleX) -, ScaleY(scaleY) + : TextData(text) + , FontInst(font) + , FontColor(fontColor) + , ScaleX(scaleX) + , ScaleY(scaleY) { - AllocateGraphicsMemory(); + AllocateGraphicsMemory(); } Text::~Text() { - FreeGraphicsMemory(); + FreeGraphicsMemory(); } void Text::FreeGraphicsMemory() { - Component::FreeGraphicsMemory(); + Component::FreeGraphicsMemory(); } void Text::AllocateGraphicsMemory() { - //todo: make the font blend color a parameter that is passed in - Component::AllocateGraphicsMemory(); + //todo: make the font blend color a parameter that is passed in + Component::AllocateGraphicsMemory(); } void Text::Draw() { - SDL_Texture *t = FontInst->GetTexture(); + SDL_Texture *t = FontInst->GetTexture(); - ViewInfo *info = GetBaseViewInfo(); - float imageHeight = 0; - float imageWidth = 0; + ViewInfo *info = GetBaseViewInfo(); + float imageHeight = 0; + float imageWidth = 0; - // determine image width - for(unsigned int i = 0; i < TextData.size(); ++i) - { - Font::GlyphInfo glyph; - if(FontInst->GetRect(TextData[i], glyph)) - { - imageWidth += glyph.Advance; - imageHeight = (imageHeight >= glyph.Rect.h) ? imageHeight : glyph.Rect.h; - } - } + // determine image width + for(unsigned int i = 0; i < TextData.size(); ++i) + { + Font::GlyphInfo glyph; + if(FontInst->GetRect(TextData[i], glyph)) + { + imageWidth += glyph.Advance; + imageHeight = (imageHeight >= glyph.Rect.h) ? imageHeight : glyph.Rect.h; + } + } - float scale = (float)info->GetFontSize() / (float)imageHeight; + float scale = (float)info->GetFontSize() / (float)imageHeight; - float width = info->GetRawWidth(); - float height = info->GetRawHeight(); + float width = info->GetRawWidth(); + float height = info->GetRawHeight(); - info->SetWidth(imageWidth*scale); - info->SetHeight(imageHeight*scale); + info->SetWidth(imageWidth*scale); + info->SetHeight(imageHeight*scale); - float xOrigin = info->GetXRelativeToOrigin(); - float yOrigin = info->GetYRelativeToOrigin(); + float xOrigin = info->GetXRelativeToOrigin(); + float yOrigin = info->GetYRelativeToOrigin(); - info->SetWidth(width); - info->SetHeight(height); + info->SetWidth(width); + info->SetHeight(height); - SDL_Rect rect; - rect.x = static_cast(xOrigin); + SDL_Rect rect; + rect.x = static_cast(xOrigin); - for(unsigned int i = 0; i < TextData.size(); ++i) - { - Font::GlyphInfo glyph; + for(unsigned int i = 0; i < TextData.size(); ++i) + { + Font::GlyphInfo glyph; - if(FontInst->GetRect(TextData[i], glyph) && glyph.Rect.h > 0) - { - SDL_Rect charRect = glyph.Rect; - float h = static_cast(charRect.h * scale); - float w = static_cast(charRect.w * scale); - rect.h = static_cast(h); - rect.w = static_cast(w); - rect.y = static_cast(yOrigin); - /* - std::stringstream ss; - ss << " cx:" << charRect.x << " cy:" << charRect.y << " cw:" << charRect.w << " ch:" << charRect.h; - ss << " x:" << rect.x << " y:" << rect.y << " w:" << rect.w << " h:" << rect.h; - Logger::Write(Logger::ZONE_DEBUG, "Text", ss.str()); - */ + if(FontInst->GetRect(TextData[i], glyph) && glyph.Rect.h > 0) + { + SDL_Rect charRect = glyph.Rect; + float h = static_cast(charRect.h * scale); + float w = static_cast(charRect.w * scale); + rect.h = static_cast(h); + rect.w = static_cast(w); + rect.y = static_cast(yOrigin); + /* + std::stringstream ss; + ss << " cx:" << charRect.x << " cy:" << charRect.y << " cw:" << charRect.w << " ch:" << charRect.h; + ss << " x:" << rect.x << " y:" << rect.y << " w:" << rect.w << " h:" << rect.h; + Logger::Write(Logger::ZONE_DEBUG, "Text", ss.str()); + */ - SDL_LockMutex(SDL::GetMutex()); - SDL_SetTextureColorMod(t, FontColor.r, FontColor.g, FontColor.b); - SDL_UnlockMutex(SDL::GetMutex()); + SDL_LockMutex(SDL::GetMutex()); + SDL_SetTextureColorMod(t, FontColor.r, FontColor.g, FontColor.b); + SDL_UnlockMutex(SDL::GetMutex()); - SDL::RenderCopy(t, static_cast(info->GetTransparency() * 255), &charRect, &rect, info->GetAngle()); - rect.x += static_cast(glyph.Advance * scale); - } - } + SDL::RenderCopy(t, static_cast(info->GetTransparency() * 255), &charRect, &rect, info->GetAngle()); + rect.x += static_cast(glyph.Advance * scale); + } + } } diff --git a/Source/Graphics/Component/Text.h b/Source/Graphics/Component/Text.h index 2bede32..9c63c09 100644 --- a/Source/Graphics/Component/Text.h +++ b/Source/Graphics/Component/Text.h @@ -13,17 +13,17 @@ class Font; class Text : public Component { public: - //todo: should have a Font flass that references fontcache, pass that in as an argument - Text(std::string text, Font *font, SDL_Color fontColor, float scaleX, float scaleY); - virtual ~Text(); - void AllocateGraphicsMemory(); - void FreeGraphicsMemory(); - void Draw(); + //todo: should have a Font flass that references fontcache, pass that in as an argument + Text(std::string text, Font *font, SDL_Color fontColor, float scaleX, float scaleY); + virtual ~Text(); + void AllocateGraphicsMemory(); + void FreeGraphicsMemory(); + void Draw(); private: - std::string TextData; - Font *FontInst; - SDL_Color FontColor; - float ScaleX; - float ScaleY; + std::string TextData; + Font *FontInst; + SDL_Color FontColor; + float ScaleX; + float ScaleY; }; diff --git a/Source/Graphics/Component/VideoBuilder.cpp b/Source/Graphics/Component/VideoBuilder.cpp index 637b75c..b01fb77 100644 --- a/Source/Graphics/Component/VideoBuilder.cpp +++ b/Source/Graphics/Component/VideoBuilder.cpp @@ -10,27 +10,27 @@ VideoComponent * VideoBuilder::CreateVideo(std::string path, std::string name, float scaleX, float scaleY) { - VideoComponent *component = NULL; - std::vector extensions; + VideoComponent *component = NULL; + std::vector extensions; - extensions.push_back("mp4"); - extensions.push_back("MP4"); - extensions.push_back("avi"); - extensions.push_back("AVI"); + extensions.push_back("mp4"); + extensions.push_back("MP4"); + extensions.push_back("avi"); + extensions.push_back("AVI"); - std::string prefix = path + "/" + name; - std::string file; + std::string prefix = path + "/" + name; + std::string file; - if(Utils::FindMatchingFile(prefix, extensions, file)) - { - IVideo *video = Factory.CreateVideo(); + if(Utils::FindMatchingFile(prefix, extensions, file)) + { + IVideo *video = Factory.CreateVideo(); - if(video) - { - component = new VideoComponent(video, file, scaleX, scaleY); - } - } + if(video) + { + component = new VideoComponent(video, file, scaleX, scaleY); + } + } - return component; + return component; } diff --git a/Source/Graphics/Component/VideoBuilder.h b/Source/Graphics/Component/VideoBuilder.h index 89a36f3..a42cb62 100644 --- a/Source/Graphics/Component/VideoBuilder.h +++ b/Source/Graphics/Component/VideoBuilder.h @@ -11,8 +11,8 @@ class VideoBuilder { public: - VideoComponent * CreateVideo(std::string path, std::string name, float scaleX, float scaleY); + VideoComponent * CreateVideo(std::string path, std::string name, float scaleX, float scaleY); private: - VideoFactory Factory; + VideoFactory Factory; }; diff --git a/Source/Graphics/Component/VideoComponent.cpp b/Source/Graphics/Component/VideoComponent.cpp index 2a9343c..16ecc47 100644 --- a/Source/Graphics/Component/VideoComponent.cpp +++ b/Source/Graphics/Component/VideoComponent.cpp @@ -8,77 +8,77 @@ #include "../../SDL.h" VideoComponent::VideoComponent(IVideo *videoInst, std::string videoFile, float scaleX, float scaleY) -: VideoTexture(NULL) -, VideoFile(videoFile) -, VideoInst(videoInst) -, ScaleX(scaleX) -, ScaleY(scaleY) -, IsPlaying(false) + : VideoTexture(NULL) + , VideoFile(videoFile) + , VideoInst(videoInst) + , ScaleX(scaleX) + , ScaleY(scaleY) + , IsPlaying(false) { // AllocateGraphicsMemory(); } VideoComponent::~VideoComponent() { - FreeGraphicsMemory(); + FreeGraphicsMemory(); - if(VideoInst) - { - VideoInst->Stop(); - } + if(VideoInst) + { + VideoInst->Stop(); + } } void VideoComponent::Update(float dt) { - if(IsPlaying) - { - VideoInst->Update(dt); - } + if(IsPlaying) + { + VideoInst->Update(dt); + } - Component::Update(dt); + Component::Update(dt); } void VideoComponent::AllocateGraphicsMemory() { - Component::AllocateGraphicsMemory(); + Component::AllocateGraphicsMemory(); - if(!IsPlaying) - { - IsPlaying = VideoInst->Play(VideoFile); - } + if(!IsPlaying) + { + IsPlaying = VideoInst->Play(VideoFile); + } } void VideoComponent::FreeGraphicsMemory() { - VideoInst->Stop(); - IsPlaying = false; + VideoInst->Stop(); + IsPlaying = false; - if (VideoTexture != NULL) - { - SDL_LockMutex(SDL::GetMutex()); - SDL_DestroyTexture(VideoTexture); - SDL_UnlockMutex(SDL::GetMutex()); - } + if (VideoTexture != NULL) + { + SDL_LockMutex(SDL::GetMutex()); + SDL_DestroyTexture(VideoTexture); + SDL_UnlockMutex(SDL::GetMutex()); + } - Component::FreeGraphicsMemory(); + Component::FreeGraphicsMemory(); } void VideoComponent::Draw() { - ViewInfo *info = GetBaseViewInfo(); - SDL_Rect rect; + ViewInfo *info = GetBaseViewInfo(); + SDL_Rect rect; - rect.x = static_cast(info->GetXRelativeToOrigin()); - rect.y = static_cast(info->GetYRelativeToOrigin()); - rect.h = static_cast(info->GetHeight()); - rect.w = static_cast(info->GetWidth()); + rect.x = static_cast(info->GetXRelativeToOrigin()); + rect.y = static_cast(info->GetYRelativeToOrigin()); + rect.h = static_cast(info->GetHeight()); + rect.w = static_cast(info->GetWidth()); - VideoInst->Draw(); - SDL_Texture *texture = VideoInst->GetTexture(); + VideoInst->Draw(); + SDL_Texture *texture = VideoInst->GetTexture(); - if(texture) - { - SDL::RenderCopy(texture, static_cast(info->GetTransparency() * 255), NULL, &rect, info->GetAngle()); - } + if(texture) + { + SDL::RenderCopy(texture, static_cast(info->GetTransparency() * 255), NULL, &rect, info->GetAngle()); + } } diff --git a/Source/Graphics/Component/VideoComponent.h b/Source/Graphics/Component/VideoComponent.h index 7922fcf..f71fb01 100644 --- a/Source/Graphics/Component/VideoComponent.h +++ b/Source/Graphics/Component/VideoComponent.h @@ -12,21 +12,27 @@ class VideoComponent : public Component { public: - VideoComponent(IVideo *videoInst, std::string videoFile, float scaleX, float scaleY); - virtual ~VideoComponent(); - void Update(float dt); - void Draw(); - void FreeGraphicsMemory(); - void AllocateGraphicsMemory(); - void LaunchEnter() {FreeGraphicsMemory(); } - void LaunchExit() { AllocateGraphicsMemory(); } + VideoComponent(IVideo *videoInst, std::string videoFile, float scaleX, float scaleY); + virtual ~VideoComponent(); + void Update(float dt); + void Draw(); + void FreeGraphicsMemory(); + void AllocateGraphicsMemory(); + void LaunchEnter() + { + FreeGraphicsMemory(); + } + void LaunchExit() + { + AllocateGraphicsMemory(); + } private: - SDL_Texture *VideoTexture; - std::string VideoFile; - std::string Name; - IVideo *VideoInst; - float ScaleX; - float ScaleY; - bool IsPlaying; + SDL_Texture *VideoTexture; + std::string VideoFile; + std::string Name; + IVideo *VideoInst; + float ScaleX; + float ScaleY; + bool IsPlaying; }; diff --git a/Source/Graphics/ComponentItemBinding.cpp b/Source/Graphics/ComponentItemBinding.cpp index 5a308f4..599a3f7 100644 --- a/Source/Graphics/ComponentItemBinding.cpp +++ b/Source/Graphics/ComponentItemBinding.cpp @@ -1,17 +1,17 @@ -/* This file is subject to the terms and conditions defined in - * file 'LICENSE.txt', which is part of this source code package. +/* This file is subject to the terms and conditions defined in + * file 'LICENSE.txt', which is part of this source code package. */ #include "ComponentItemBinding.h" ComponentItemBinding::ComponentItemBinding( Component *c, Item *item) -: CollectionComponent(c) -, CollectionItem(item) + : CollectionComponent(c) + , CollectionItem(item) { } ComponentItemBinding::ComponentItemBinding(Item *item) -: CollectionComponent(NULL) -, CollectionItem(item) + : CollectionComponent(NULL) + , CollectionItem(item) { } @@ -21,15 +21,15 @@ ComponentItemBinding::~ComponentItemBinding() Item* ComponentItemBinding::GetCollectionItem() const { - return CollectionItem; + return CollectionItem; } void ComponentItemBinding::SetComponent(Component *c) { - CollectionComponent = c; + CollectionComponent = c; } Component* ComponentItemBinding::GetComponent() const { - return CollectionComponent; + return CollectionComponent; } diff --git a/Source/Graphics/ComponentItemBinding.h b/Source/Graphics/ComponentItemBinding.h index 59a8418..50b3221 100644 --- a/Source/Graphics/ComponentItemBinding.h +++ b/Source/Graphics/ComponentItemBinding.h @@ -1,5 +1,5 @@ -/* This file is subject to the terms and conditions defined in - * file 'LICENSE.txt', which is part of this source code package. +/* This file is subject to the terms and conditions defined in + * file 'LICENSE.txt', which is part of this source code package. */ #pragma once @@ -9,15 +9,15 @@ class ComponentItemBinding { public: - ComponentItemBinding(Component *c, Item *item); - ComponentItemBinding(Item *item); - virtual ~ComponentItemBinding(); - Item* GetCollectionItem() const; + ComponentItemBinding(Component *c, Item *item); + ComponentItemBinding(Item *item); + virtual ~ComponentItemBinding(); + Item* GetCollectionItem() const; - void SetComponent(Component *c); - Component* GetComponent() const; + void SetComponent(Component *c); + Component* GetComponent() const; private: - Component *CollectionComponent; - Item *CollectionItem; + Component *CollectionComponent; + Item *CollectionItem; }; diff --git a/Source/Graphics/ComponentItemBindingBuilder.cpp b/Source/Graphics/ComponentItemBindingBuilder.cpp index 406d1b8..9397024 100644 --- a/Source/Graphics/ComponentItemBindingBuilder.cpp +++ b/Source/Graphics/ComponentItemBindingBuilder.cpp @@ -1,5 +1,5 @@ -/* This file is subject to the terms and conditions defined in - * file 'LICENSE.txt', which is part of this source code package. +/* This file is subject to the terms and conditions defined in + * file 'LICENSE.txt', which is part of this source code package. */ #include "ComponentItemBindingBuilder.h" #include "ComponentItemBinding.h" @@ -16,14 +16,14 @@ ComponentItemBindingBuilder::~ComponentItemBindingBuilder() std::vector *ComponentItemBindingBuilder::BuildCollectionItems(std::vector *infoList) { - std::vector *sprites = new std::vector(); - std::vector::iterator it; + std::vector *sprites = new std::vector(); + std::vector::iterator it; - for(it = infoList->begin(); it != infoList->end(); ++it) - { - ComponentItemBinding *s = new ComponentItemBinding(*it); - sprites->push_back(s); - } + for(it = infoList->begin(); it != infoList->end(); ++it) + { + ComponentItemBinding *s = new ComponentItemBinding(*it); + sprites->push_back(s); + } - return sprites; + return sprites; } diff --git a/Source/Graphics/ComponentItemBindingBuilder.h b/Source/Graphics/ComponentItemBindingBuilder.h index a5fa8f9..4f1170e 100644 --- a/Source/Graphics/ComponentItemBindingBuilder.h +++ b/Source/Graphics/ComponentItemBindingBuilder.h @@ -1,5 +1,5 @@ -/* This file is subject to the terms and conditions defined in - * file 'LICENSE.txt', which is part of this source code package. +/* This file is subject to the terms and conditions defined in + * file 'LICENSE.txt', which is part of this source code package. */ #pragma once @@ -12,7 +12,7 @@ class ComponentItemBinding; class ComponentItemBindingBuilder { public: - ComponentItemBindingBuilder(); - virtual ~ComponentItemBindingBuilder(); - static std::vector *BuildCollectionItems(std::vector *infoList); + ComponentItemBindingBuilder(); + virtual ~ComponentItemBindingBuilder(); + static std::vector *BuildCollectionItems(std::vector *infoList); }; diff --git a/Source/Graphics/Font.cpp b/Source/Graphics/Font.cpp index 569ef63..ce3ebc6 100644 --- a/Source/Graphics/Font.cpp +++ b/Source/Graphics/Font.cpp @@ -1,6 +1,6 @@ /* This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. - */ + */ #include "Font.h" #include "../SDL.h" #include "../Utility/Log.h" @@ -8,138 +8,138 @@ #include Font::Font() -: Texture(NULL) + : Texture(NULL) { } Font::~Font() { - DeInitialize(); + DeInitialize(); } SDL_Texture *Font::GetTexture() { - return Texture; + return Texture; } bool Font::GetRect(unsigned int charCode, GlyphInfo &glyph) { - std::map::iterator it = Atlas.find(charCode); + std::map::iterator it = Atlas.find(charCode); - if(it != Atlas.end()) - { - GlyphInfoBuild *info = it->second; + if(it != Atlas.end()) + { + GlyphInfoBuild *info = it->second; - glyph = info->Glyph; + glyph = info->Glyph; - return true; - } + return true; + } - return false; + return false; } bool Font::Initialize(std::string fontPath, SDL_Color color) { - TTF_Font *font = TTF_OpenFont(fontPath.c_str(), 128); + TTF_Font *font = TTF_OpenFont(fontPath.c_str(), 128); - if (!font) - { - Logger::Write(Logger::ZONE_ERROR, "FontCache", "TTF_OpenFont failed"); - return false; - } + if (!font) + { + Logger::Write(Logger::ZONE_ERROR, "FontCache", "TTF_OpenFont failed"); + return false; + } - int x = 0; - int y = 0; - int atlasHeight = 0; - int atlasWidth = 0; + int x = 0; + int y = 0; + int atlasHeight = 0; + int atlasWidth = 0; - for(unsigned short int i = 32; i < 128; ++i) - { - GlyphInfoBuild *info = new GlyphInfoBuild; - memset(info, sizeof(GlyphInfoBuild), 0); + for(unsigned short int i = 32; i < 128; ++i) + { + GlyphInfoBuild *info = new GlyphInfoBuild; + memset(info, sizeof(GlyphInfoBuild), 0); - info->Surface = TTF_RenderGlyph_Blended(font, i, color); - TTF_GlyphMetrics(font, i, &info->Glyph.MinX, &info->Glyph.MaxX, &info->Glyph.MinY, &info->Glyph.MaxY, &info->Glyph.Advance); + info->Surface = TTF_RenderGlyph_Blended(font, i, color); + TTF_GlyphMetrics(font, i, &info->Glyph.MinX, &info->Glyph.MaxX, &info->Glyph.MinY, &info->Glyph.MaxY, &info->Glyph.Advance); - if(x + info->Surface->w >= 1024) - { - atlasHeight += y; - atlasWidth = (atlasWidth >= x) ? atlasWidth : x; - x = 0; - y = 0; - } + if(x + info->Surface->w >= 1024) + { + atlasHeight += y; + atlasWidth = (atlasWidth >= x) ? atlasWidth : x; + x = 0; + y = 0; + } - info->Glyph.Rect.w = info->Surface->w; - info->Glyph.Rect.h = info->Surface->h; - info->Glyph.Rect.x = x; - info->Glyph.Rect.y = atlasHeight; - Atlas[i] = info; + info->Glyph.Rect.w = info->Surface->w; + info->Glyph.Rect.h = info->Surface->h; + info->Glyph.Rect.x = x; + info->Glyph.Rect.y = atlasHeight; + Atlas[i] = info; - x += info->Glyph.Rect.w; - y = (y > info->Glyph.Rect.h) ? y : info->Glyph.Rect.h; - /* - std::stringstream ss; - ss << " tw:" << atlasWidth << " th:" << atlasHeight << " x:" << x << " y:" << y << " w:" << info->Glyph.Rect.w << " h:" << info->Glyph.Rect.h; - Logger::Write(Logger::ZONE_ERROR, "FontCache", ss.str()); - */ - } + x += info->Glyph.Rect.w; + y = (y > info->Glyph.Rect.h) ? y : info->Glyph.Rect.h; + /* + std::stringstream ss; + ss << " tw:" << atlasWidth << " th:" << atlasHeight << " x:" << x << " y:" << y << " w:" << info->Glyph.Rect.w << " h:" << info->Glyph.Rect.h; + Logger::Write(Logger::ZONE_ERROR, "FontCache", ss.str()); + */ + } - atlasWidth = (atlasWidth >= x) ? atlasWidth : x; - atlasHeight += y; + atlasWidth = (atlasWidth >= x) ? atlasWidth : x; + atlasHeight += y; - unsigned int rmask; - unsigned int gmask; - unsigned int bmask; - unsigned int amask; + unsigned int rmask; + unsigned int gmask; + unsigned int bmask; + unsigned int amask; #if SDL_BYTEORDER == SDL_BIG_ENDIAN - rmask = 0xff000000; - gmask = 0x00ff0000; - bmask = 0x0000ff00; - amask = 0x000000ff; + rmask = 0xff000000; + gmask = 0x00ff0000; + bmask = 0x0000ff00; + amask = 0x000000ff; #else - rmask = 0x000000ff; - gmask = 0x0000ff00; - bmask = 0x00ff0000; - amask = 0xff000000; + rmask = 0x000000ff; + gmask = 0x0000ff00; + bmask = 0x00ff0000; + amask = 0xff000000; #endif - SDL_Surface *atlasSurface = SDL_CreateRGBSurface(0, atlasWidth, atlasHeight, 24, rmask, gmask, bmask, amask); + SDL_Surface *atlasSurface = SDL_CreateRGBSurface(0, atlasWidth, atlasHeight, 24, rmask, gmask, bmask, amask); - std::map::iterator it; - for(it = Atlas.begin(); it != Atlas.end(); it++) - { - GlyphInfoBuild *info = it->second; - SDL_BlitSurface(info->Surface, NULL, atlasSurface, &info->Glyph.Rect); - SDL_FreeSurface(info->Surface); - info->Surface = NULL; - } + std::map::iterator it; + for(it = Atlas.begin(); it != Atlas.end(); it++) + { + GlyphInfoBuild *info = it->second; + SDL_BlitSurface(info->Surface, NULL, atlasSurface, &info->Glyph.Rect); + SDL_FreeSurface(info->Surface); + info->Surface = NULL; + } - SDL_LockMutex(SDL::GetMutex()); - SDL_SetColorKey(atlasSurface, SDL_TRUE, SDL_MapRGB(atlasSurface->format, 0, 0, 0)); - Texture = SDL_CreateTextureFromSurface(SDL::GetRenderer(), atlasSurface); - SDL_FreeSurface(atlasSurface); - SDL_UnlockMutex(SDL::GetMutex()); + SDL_LockMutex(SDL::GetMutex()); + SDL_SetColorKey(atlasSurface, SDL_TRUE, SDL_MapRGB(atlasSurface->format, 0, 0, 0)); + Texture = SDL_CreateTextureFromSurface(SDL::GetRenderer(), atlasSurface); + SDL_FreeSurface(atlasSurface); + SDL_UnlockMutex(SDL::GetMutex()); - TTF_CloseFont(font); + TTF_CloseFont(font); - return true; + return true; } void Font::DeInitialize() { - if(Texture) - { - SDL_LockMutex(SDL::GetMutex()); - SDL_DestroyTexture(Texture); - Texture = NULL; - SDL_UnlockMutex(SDL::GetMutex()); - } + if(Texture) + { + SDL_LockMutex(SDL::GetMutex()); + SDL_DestroyTexture(Texture); + Texture = NULL; + SDL_UnlockMutex(SDL::GetMutex()); + } - std::map::iterator atlasIt = Atlas.begin(); - while(atlasIt != Atlas.end()) - { - delete atlasIt->second; - Atlas.erase(atlasIt); - atlasIt = Atlas.begin(); - } + std::map::iterator atlasIt = Atlas.begin(); + while(atlasIt != Atlas.end()) + { + delete atlasIt->second; + Atlas.erase(atlasIt); + atlasIt = Atlas.begin(); + } } diff --git a/Source/Graphics/Font.h b/Source/Graphics/Font.h index e4f9f67..83cad32 100644 --- a/Source/Graphics/Font.h +++ b/Source/Graphics/Font.h @@ -1,6 +1,6 @@ /* This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. - */ + */ #pragma once #include @@ -10,33 +10,33 @@ class Font { public: - struct GlyphInfo - { - int MinX; - int MaxX; - int MinY; - int MaxY; - int Advance; - SDL_Rect Rect; - }; + struct GlyphInfo + { + int MinX; + int MaxX; + int MinY; + int MaxY; + int Advance; + SDL_Rect Rect; + }; - Font(); - virtual ~Font(); - bool Initialize(std::string fontPath, SDL_Color color); - void DeInitialize(); - SDL_Texture *GetTexture(); - bool GetRect(unsigned int charCode, GlyphInfo &glyph); + Font(); + virtual ~Font(); + bool Initialize(std::string fontPath, SDL_Color color); + void DeInitialize(); + SDL_Texture *GetTexture(); + bool GetRect(unsigned int charCode, GlyphInfo &glyph); private: - struct GlyphInfoBuild - { - Font::GlyphInfo Glyph; - SDL_Surface *Surface; - }; + struct GlyphInfoBuild + { + Font::GlyphInfo Glyph; + SDL_Surface *Surface; + }; - std::map Atlas; - SDL_Texture *Texture; + std::map Atlas; + SDL_Texture *Texture; }; diff --git a/Source/Graphics/FontCache.cpp b/Source/Graphics/FontCache.cpp index b2d31b9..ed4b360 100644 --- a/Source/Graphics/FontCache.cpp +++ b/Source/Graphics/FontCache.cpp @@ -1,6 +1,6 @@ /* This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. - */ + */ #include "FontCache.h" #include "Font.h" #include "../Utility/Log.h" @@ -10,63 +10,63 @@ //todo: memory leak when launching games FontCache::FontCache() -: IsInitialized(false) + : IsInitialized(false) { } FontCache::~FontCache() { - DeInitialize(); + DeInitialize(); } void FontCache::DeInitialize() { - IsInitialized = false; - std::map::iterator it = FontFaceMap.begin(); - while(it != FontFaceMap.end()) - { - delete it->second; - FontFaceMap.erase(it); - it = FontFaceMap.begin(); - } + IsInitialized = false; + std::map::iterator it = FontFaceMap.begin(); + while(it != FontFaceMap.end()) + { + delete it->second; + FontFaceMap.erase(it); + it = FontFaceMap.begin(); + } - SDL_LockMutex(SDL::GetMutex()); - TTF_Quit(); - SDL_UnlockMutex(SDL::GetMutex()); + SDL_LockMutex(SDL::GetMutex()); + TTF_Quit(); + SDL_UnlockMutex(SDL::GetMutex()); } void FontCache::Initialize() { - //todo: make bool - TTF_Init(); - IsInitialized = true; + //todo: make bool + TTF_Init(); + IsInitialized = true; } Font *FontCache::GetFont(std::string fontPath) { - Font *t = NULL; + Font *t = NULL; - std::map::iterator it = FontFaceMap.find(fontPath); + std::map::iterator it = FontFaceMap.find(fontPath); - if(it != FontFaceMap.end()) - { - t = it->second; - } + if(it != FontFaceMap.end()) + { + t = it->second; + } - return t; + return t; } bool FontCache::LoadFont(std::string fontPath, SDL_Color color) { - std::map::iterator it = FontFaceMap.find(fontPath); + std::map::iterator it = FontFaceMap.find(fontPath); - if(it == FontFaceMap.end()) - { - Font *f = new Font(); - f->Initialize(fontPath, color); - FontFaceMap[fontPath] = f; - } + if(it == FontFaceMap.end()) + { + Font *f = new Font(); + f->Initialize(fontPath, color); + FontFaceMap[fontPath] = f; + } - return true; + return true; } diff --git a/Source/Graphics/FontCache.h b/Source/Graphics/FontCache.h index bb958fd..4d724db 100644 --- a/Source/Graphics/FontCache.h +++ b/Source/Graphics/FontCache.h @@ -1,6 +1,6 @@ /* This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. - */ + */ #pragma once #include "Font.h" @@ -10,17 +10,17 @@ class FontCache { public: - void Initialize(); - void DeInitialize(); - FontCache(); - bool LoadFont(std::string font, SDL_Color color); - Font *GetFont(std::string font); + void Initialize(); + void DeInitialize(); + FontCache(); + bool LoadFont(std::string font, SDL_Color color); + Font *GetFont(std::string font); - virtual ~FontCache(); + virtual ~FontCache(); private: - bool IsInitialized; + bool IsInitialized; - std::map FontFaceMap; + std::map FontFaceMap; }; diff --git a/Source/Graphics/MenuNotifierInterface.h b/Source/Graphics/MenuNotifierInterface.h index 7915273..c66ca47 100644 --- a/Source/Graphics/MenuNotifierInterface.h +++ b/Source/Graphics/MenuNotifierInterface.h @@ -1,6 +1,6 @@ /* This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. - */ + */ #pragma once #include "../Collection/Item.h" @@ -8,7 +8,7 @@ class MenuNotifierInterface { public: - virtual ~MenuNotifierInterface() {} - virtual void OnNewItemSelected(Item *) = 0; + virtual ~MenuNotifierInterface() {} + virtual void OnNewItemSelected(Item *) = 0; }; diff --git a/Source/Graphics/Page.cpp b/Source/Graphics/Page.cpp index 3272f31..dcd2850 100644 --- a/Source/Graphics/Page.cpp +++ b/Source/Graphics/Page.cpp @@ -11,145 +11,145 @@ #include Page::Page(std::string collectionName) -: CollectionName(collectionName) -, Menu(NULL) -, Items(NULL) -, ScrollActive(false) -, SelectedItem(NULL) -, SelectedItemChanged(false) -, LoadSoundChunk(NULL) -, UnloadSoundChunk(NULL) -, HighlightSoundChunk(NULL) -, SelectSoundChunk(NULL) -, HasSoundedWhenActive(false) -, FirstSoundPlayed(false) + : CollectionName(collectionName) + , Menu(NULL) + , Items(NULL) + , ScrollActive(false) + , SelectedItem(NULL) + , SelectedItemChanged(false) + , LoadSoundChunk(NULL) + , UnloadSoundChunk(NULL) + , HighlightSoundChunk(NULL) + , SelectSoundChunk(NULL) + , HasSoundedWhenActive(false) + , FirstSoundPlayed(false) { } Page::~Page() { - if(Menu) - { - Menu->RemoveComponentForNotifications(this); - } + if(Menu) + { + Menu->RemoveComponentForNotifications(this); + } - for(unsigned int i = 0; i < sizeof(LayerComponents)/sizeof(LayerComponents[0]); ++i) - { - for(std::vector::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) - { - delete *it; - } + for(unsigned int i = 0; i < sizeof(LayerComponents)/sizeof(LayerComponents[0]); ++i) + { + for(std::vector::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) + { + delete *it; + } - LayerComponents[i].clear(); - } + LayerComponents[i].clear(); + } - if(Menu) - { - delete Menu; - } + if(Menu) + { + delete Menu; + } - if(LoadSoundChunk) - { - delete LoadSoundChunk; - LoadSoundChunk = NULL; - } + if(LoadSoundChunk) + { + delete LoadSoundChunk; + LoadSoundChunk = NULL; + } - if(UnloadSoundChunk) - { - delete UnloadSoundChunk; - UnloadSoundChunk = NULL; - } + if(UnloadSoundChunk) + { + delete UnloadSoundChunk; + UnloadSoundChunk = NULL; + } - if(HighlightSoundChunk) - { - delete HighlightSoundChunk; - HighlightSoundChunk = NULL; - } + if(HighlightSoundChunk) + { + delete HighlightSoundChunk; + HighlightSoundChunk = NULL; + } - if(SelectSoundChunk) - { - delete SelectSoundChunk; - SelectSoundChunk = NULL; - } + if(SelectSoundChunk) + { + delete SelectSoundChunk; + SelectSoundChunk = NULL; + } } void Page::OnNewItemSelected(Item *item) { - SelectedItem = item; - SelectedItemChanged = true; + SelectedItem = item; + SelectedItemChanged = true; } void Page::SetMenu(ScrollingList *s) { - // todo: delete the old menu - Menu = s; + // todo: delete the old menu + Menu = s; - if(Menu) - { - Menu->AddComponentForNotifications(this); - } + if(Menu) + { + Menu->AddComponentForNotifications(this); + } } bool Page::AddComponent(Component *c) { - bool retVal = false; + bool retVal = false; - unsigned int layer = c->GetBaseViewInfo()->GetLayer(); + unsigned int layer = c->GetBaseViewInfo()->GetLayer(); - if(layer < NUM_LAYERS) - { - LayerComponents[layer].push_back(c); + if(layer < NUM_LAYERS) + { + LayerComponents[layer].push_back(c); - retVal = true; - } - else - { - std::stringstream ss; - ss << "Component layer too large Layer: " << layer; - Logger::Write(Logger::ZONE_ERROR, "Page", ss.str()); - } + retVal = true; + } + else + { + std::stringstream ss; + ss << "Component layer too large Layer: " << layer; + Logger::Write(Logger::ZONE_ERROR, "Page", ss.str()); + } - return retVal; + return retVal; } bool Page::IsIdle() { - bool idle = true; + bool idle = true; - if(Menu != NULL && !Menu->IsIdle()) - { - idle = false; - } + if(Menu != NULL && !Menu->IsIdle()) + { + idle = false; + } - for(unsigned int i = 0; i < NUM_LAYERS && idle; ++i) - { - for(std::vector::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end() && idle; ++it) - { - idle = (*it)->IsIdle(); - } - } + for(unsigned int i = 0; i < NUM_LAYERS && idle; ++i) + { + for(std::vector::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end() && idle; ++it) + { + idle = (*it)->IsIdle(); + } + } - return idle; + return idle; } bool Page::IsHidden() { - bool hidden = true; + bool hidden = true; if(Menu != NULL) { - hidden = Menu->IsHidden(); + hidden = Menu->IsHidden(); } for(unsigned int i = 0; hidden && i < NUM_LAYERS; ++i) { - for(std::vector::iterator it = LayerComponents[i].begin(); hidden && it != LayerComponents[i].end(); ++it) - { - hidden = (*it)->IsHidden(); - } + for(std::vector::iterator it = LayerComponents[i].begin(); hidden && it != LayerComponents[i].end(); ++it) + { + hidden = (*it)->IsHidden(); + } } return hidden; @@ -157,250 +157,250 @@ bool Page::IsHidden() void Page::Start() { - Menu->TriggerEnterEvent(); + Menu->TriggerEnterEvent(); - if(LoadSoundChunk) - { - LoadSoundChunk->Play(); - } + if(LoadSoundChunk) + { + LoadSoundChunk->Play(); + } - for(unsigned int i = 0; i < NUM_LAYERS; ++i) - { - for(std::vector::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) - { - (*it)->TriggerEnterEvent(); - } - } + for(unsigned int i = 0; i < NUM_LAYERS; ++i) + { + for(std::vector::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) + { + (*it)->TriggerEnterEvent(); + } + } } void Page::Stop() { - Menu->TriggerExitEvent(); + Menu->TriggerExitEvent(); - if(UnloadSoundChunk) - { - UnloadSoundChunk->Play(); - } + if(UnloadSoundChunk) + { + UnloadSoundChunk->Play(); + } - for(unsigned int i = 0; i < NUM_LAYERS; ++i) - { - for(std::vector::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) - { - (*it)->TriggerExitEvent(); - } - } + for(unsigned int i = 0; i < NUM_LAYERS; ++i) + { + for(std::vector::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) + { + (*it)->TriggerExitEvent(); + } + } } Item *Page::GetSelectedItem() { - return SelectedItem; + return SelectedItem; } void Page::RemoveSelectedItem() { - if(Menu) - { - //todo: change method to RemoveItem() and pass in SelectedItem - Menu->RemoveSelectedItem(); - SelectedItem = NULL; - } + if(Menu) + { + //todo: change method to RemoveItem() and pass in SelectedItem + Menu->RemoveSelectedItem(); + SelectedItem = NULL; + } } void Page::Highlight() { - Item *item = SelectedItem; + Item *item = SelectedItem; - if(item) - { - if(Menu) - { - Menu->TriggerHighlightEvent(item); - Menu->SetScrollActive(ScrollActive); - } + if(item) + { + if(Menu) + { + Menu->TriggerHighlightEvent(item); + Menu->SetScrollActive(ScrollActive); + } - for(unsigned int i = 0; i < NUM_LAYERS; ++i) - { - for(std::vector::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) - { - (*it)->TriggerHighlightEvent(item); - (*it)->SetScrollActive(ScrollActive); - } - } - } + for(unsigned int i = 0; i < NUM_LAYERS; ++i) + { + for(std::vector::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) + { + (*it)->TriggerHighlightEvent(item); + (*it)->SetScrollActive(ScrollActive); + } + } + } } void Page::SetScrolling(ScrollDirection direction) { - ScrollingList::ScrollDirection menuDirection; + ScrollingList::ScrollDirection menuDirection; - switch(direction) - { - case ScrollDirectionForward: - menuDirection = ScrollingList::ScrollDirectionForward; - ScrollActive = true; - break; - case ScrollDirectionBack: - menuDirection = ScrollingList::ScrollDirectionBack; - ScrollActive = true; - break; - case ScrollDirectionIdle: - default: - menuDirection = ScrollingList::ScrollDirectionIdle; - ScrollActive = false; - break; - } - if(Menu) - { - Menu->SetScrollDirection(menuDirection); - } + switch(direction) + { + case ScrollDirectionForward: + menuDirection = ScrollingList::ScrollDirectionForward; + ScrollActive = true; + break; + case ScrollDirectionBack: + menuDirection = ScrollingList::ScrollDirectionBack; + ScrollActive = true; + break; + case ScrollDirectionIdle: + default: + menuDirection = ScrollingList::ScrollDirectionIdle; + ScrollActive = false; + break; + } + if(Menu) + { + Menu->SetScrollDirection(menuDirection); + } } void Page::PageScroll(ScrollDirection direction) { - if(Menu) - { - if(direction == ScrollDirectionForward) - { - Menu->PageDown(); - } - if(direction == ScrollDirectionBack) - { - Menu->PageUp(); - } - } + if(Menu) + { + if(direction == ScrollDirectionForward) + { + Menu->PageDown(); + } + if(direction == ScrollDirectionBack) + { + Menu->PageUp(); + } + } } void Page::SetItems(std::vector *items) { - std::vector *sprites = ComponentItemBindingBuilder::BuildCollectionItems(items); + std::vector *sprites = ComponentItemBindingBuilder::BuildCollectionItems(items); - if(Menu != NULL) - { - Menu->SetItems(sprites); - } + if(Menu != NULL) + { + Menu->SetItems(sprites); + } } void Page::Update(float dt) { - if(Menu != NULL) - { - Menu->Update(dt); - } - if(SelectedItemChanged && !HasSoundedWhenActive && HighlightSoundChunk) - { - // skip the first sound being played (as it is part of the on-enter) - if(FirstSoundPlayed) - { - HighlightSoundChunk->Play(); - HasSoundedWhenActive = true; - } - FirstSoundPlayed = true; - } + if(Menu != NULL) + { + Menu->Update(dt); + } + if(SelectedItemChanged && !HasSoundedWhenActive && HighlightSoundChunk) + { + // skip the first sound being played (as it is part of the on-enter) + if(FirstSoundPlayed) + { + HighlightSoundChunk->Play(); + HasSoundedWhenActive = true; + } + FirstSoundPlayed = true; + } - if(SelectedItemChanged && !ScrollActive) - { - Highlight(); - SelectedItemChanged = false; - HasSoundedWhenActive = false; - } + if(SelectedItemChanged && !ScrollActive) + { + Highlight(); + SelectedItemChanged = false; + HasSoundedWhenActive = false; + } - for(unsigned int i = 0; i < NUM_LAYERS; ++i) - { - for(std::vector::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) - { - (*it)->Update(dt); - } - } + for(unsigned int i = 0; i < NUM_LAYERS; ++i) + { + for(std::vector::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) + { + (*it)->Update(dt); + } + } } void Page::Draw() { - for(unsigned int i = 0; i < NUM_LAYERS; ++i) - { - for(std::vector::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) - { - (*it)->Draw(); - } + for(unsigned int i = 0; i < NUM_LAYERS; ++i) + { + for(std::vector::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) + { + (*it)->Draw(); + } - Menu->Draw(i); - } + Menu->Draw(i); + } } const std::string& Page::GetCollectionName() const { - return CollectionName; + return CollectionName; } void Page::FreeGraphicsMemory() { - Logger::Write(Logger::ZONE_DEBUG, "Page", "Free"); - Menu->FreeGraphicsMemory(); + Logger::Write(Logger::ZONE_DEBUG, "Page", "Free"); + Menu->FreeGraphicsMemory(); - if(LoadSoundChunk) LoadSoundChunk->Free(); - if(UnloadSoundChunk) UnloadSoundChunk->Free(); - if(HighlightSoundChunk) HighlightSoundChunk->Free(); - if(SelectSoundChunk) SelectSoundChunk->Free(); + if(LoadSoundChunk) LoadSoundChunk->Free(); + if(UnloadSoundChunk) UnloadSoundChunk->Free(); + if(HighlightSoundChunk) HighlightSoundChunk->Free(); + if(SelectSoundChunk) SelectSoundChunk->Free(); - for(unsigned int i = 0; i < NUM_LAYERS; ++i) - { - for(std::vector::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) - { - (*it)->FreeGraphicsMemory(); - } - } + for(unsigned int i = 0; i < NUM_LAYERS; ++i) + { + for(std::vector::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) + { + (*it)->FreeGraphicsMemory(); + } + } } void Page::AllocateGraphicsMemory() { - FirstSoundPlayed = false; - Logger::Write(Logger::ZONE_DEBUG, "Page", "Allocating graphics memory"); - Menu->AllocateGraphicsMemory(); + FirstSoundPlayed = false; + Logger::Write(Logger::ZONE_DEBUG, "Page", "Allocating graphics memory"); + Menu->AllocateGraphicsMemory(); - if(LoadSoundChunk) LoadSoundChunk->Allocate(); - if(UnloadSoundChunk) UnloadSoundChunk->Allocate(); - if(HighlightSoundChunk) HighlightSoundChunk->Allocate(); - if(SelectSoundChunk) SelectSoundChunk->Allocate(); + if(LoadSoundChunk) LoadSoundChunk->Allocate(); + if(UnloadSoundChunk) UnloadSoundChunk->Allocate(); + if(HighlightSoundChunk) HighlightSoundChunk->Allocate(); + if(SelectSoundChunk) SelectSoundChunk->Allocate(); - for(unsigned int i = 0; i < NUM_LAYERS; ++i) - { - for(std::vector::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) - { - (*it)->AllocateGraphicsMemory(); - } - } - Logger::Write(Logger::ZONE_DEBUG, "Page", "Allocate graphics memory complete"); + for(unsigned int i = 0; i < NUM_LAYERS; ++i) + { + for(std::vector::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) + { + (*it)->AllocateGraphicsMemory(); + } + } + Logger::Write(Logger::ZONE_DEBUG, "Page", "Allocate graphics memory complete"); } void Page::LaunchEnter() { - Menu->LaunchEnter(); + Menu->LaunchEnter(); - for(unsigned int i = 0; i < NUM_LAYERS; ++i) - { - for(std::vector::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) - { - (*it)->LaunchEnter(); - } - } + for(unsigned int i = 0; i < NUM_LAYERS; ++i) + { + for(std::vector::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) + { + (*it)->LaunchEnter(); + } + } } void Page::LaunchExit() { - Menu->LaunchExit(); + Menu->LaunchExit(); - for(unsigned int i = 0; i < NUM_LAYERS; ++i) - { - for(std::vector::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) - { - (*it)->LaunchExit(); - } - } + for(unsigned int i = 0; i < NUM_LAYERS; ++i) + { + for(std::vector::iterator it = LayerComponents[i].begin(); it != LayerComponents[i].end(); ++it) + { + (*it)->LaunchExit(); + } + } } diff --git a/Source/Graphics/Page.h b/Source/Graphics/Page.h index 37950e8..e9dc2af 100644 --- a/Source/Graphics/Page.h +++ b/Source/Graphics/Page.h @@ -16,56 +16,68 @@ class Sound; class Page : public MenuNotifierInterface { public: - enum ScrollDirection - { - ScrollDirectionForward, - ScrollDirectionBack, - ScrollDirectionIdle + enum ScrollDirection + { + ScrollDirectionForward, + ScrollDirectionBack, + ScrollDirectionIdle - }; + }; - Page(std::string collectionName); - virtual ~Page(); - virtual void OnNewItemSelected(Item *); - void SetItems(std::vector *items); - void SetMenu(ScrollingList *s); - void SetLoadSound(Sound *chunk) { LoadSoundChunk = chunk; } - void SetUnloadSound(Sound *chunk) { UnloadSoundChunk = chunk; } - void SetHighlightSound(Sound *chunk) { HighlightSoundChunk = chunk; } - void SetSelectSound(Sound *chunk) { SelectSoundChunk = chunk; } - bool AddComponent(Component *c); - void PageScroll(ScrollDirection direction); - void Start(); - void Stop(); - void SetScrolling(ScrollDirection direction); - Item *GetSelectedItem(); - Item *GetPendingSelectedItem(); - void RemoveSelectedItem(); - bool IsIdle(); - bool IsHidden(); - void Update(float dt); - void Draw(); - void FreeGraphicsMemory(); - void AllocateGraphicsMemory(); - void LaunchEnter(); - void LaunchExit(); - const std::string& GetCollectionName() const; + Page(std::string collectionName); + virtual ~Page(); + virtual void OnNewItemSelected(Item *); + void SetItems(std::vector *items); + void SetMenu(ScrollingList *s); + void SetLoadSound(Sound *chunk) + { + LoadSoundChunk = chunk; + } + void SetUnloadSound(Sound *chunk) + { + UnloadSoundChunk = chunk; + } + void SetHighlightSound(Sound *chunk) + { + HighlightSoundChunk = chunk; + } + void SetSelectSound(Sound *chunk) + { + SelectSoundChunk = chunk; + } + bool AddComponent(Component *c); + void PageScroll(ScrollDirection direction); + void Start(); + void Stop(); + void SetScrolling(ScrollDirection direction); + Item *GetSelectedItem(); + Item *GetPendingSelectedItem(); + void RemoveSelectedItem(); + bool IsIdle(); + bool IsHidden(); + void Update(float dt); + void Draw(); + void FreeGraphicsMemory(); + void AllocateGraphicsMemory(); + void LaunchEnter(); + void LaunchExit(); + const std::string& GetCollectionName() const; private: - void Highlight(); - std::string CollectionName; - ScrollingList *Menu; - static const unsigned int NUM_LAYERS = 8; - std::vector LayerComponents[NUM_LAYERS]; - std::vector *Items; - bool ScrollActive; - Item *SelectedItem; - bool SelectedItemChanged; - Sound *LoadSoundChunk; - Sound *UnloadSoundChunk; - Sound *HighlightSoundChunk; - Sound *SelectSoundChunk; - bool HasSoundedWhenActive; - bool FirstSoundPlayed; + void Highlight(); + std::string CollectionName; + ScrollingList *Menu; + static const unsigned int NUM_LAYERS = 8; + std::vector LayerComponents[NUM_LAYERS]; + std::vector *Items; + bool ScrollActive; + Item *SelectedItem; + bool SelectedItemChanged; + Sound *LoadSoundChunk; + Sound *UnloadSoundChunk; + Sound *HighlightSoundChunk; + Sound *SelectSoundChunk; + bool HasSoundedWhenActive; + bool FirstSoundPlayed; }; diff --git a/Source/Graphics/PageBuilder.cpp b/Source/Graphics/PageBuilder.cpp index 4e00e9f..896b184 100644 --- a/Source/Graphics/PageBuilder.cpp +++ b/Source/Graphics/PageBuilder.cpp @@ -26,21 +26,21 @@ using namespace rapidxml; PageBuilder::PageBuilder(std::string layoutKey, std::string collection, Configuration *c, FontCache *fc) -: LayoutKey(layoutKey) -, Collection(collection) -, Config(c) -, ScaleX(1) -, ScaleY(1) -, ScreenHeight(0) -, ScreenWidth(0) -, FC(fc) + : LayoutKey(layoutKey) + , Collection(collection) + , Config(c) + , ScaleX(1) + , ScaleY(1) + , ScreenHeight(0) + , ScreenWidth(0) + , FC(fc) { - ScreenWidth = SDL::GetWindowWidth(); - ScreenHeight = SDL::GetWindowHeight(); - FontColor.a = 255; - FontColor.r = 255; - FontColor.g = 0; - FontColor.b = 0; + ScreenWidth = SDL::GetWindowWidth(); + ScreenHeight = SDL::GetWindowHeight(); + FontColor.a = 255; + FontColor.r = 255; + FontColor.g = 0; + FontColor.b = 0; } PageBuilder::~PageBuilder() @@ -49,234 +49,234 @@ PageBuilder::~PageBuilder() Page *PageBuilder::BuildPage() { - Page *page = NULL; + Page *page = NULL; - std::string layoutFile; - std::string layoutName = LayoutKey; + std::string layoutFile; + std::string layoutName = LayoutKey; - LayoutPath = Configuration::GetAbsolutePath() + "/Layouts/" + layoutName; - layoutFile = LayoutPath + "/Layout.xml"; + LayoutPath = Configuration::GetAbsolutePath() + "/Layouts/" + layoutName; + layoutFile = LayoutPath + "/Layout.xml"; - Logger::Write(Logger::ZONE_INFO, "Layout", "Initializing " + layoutFile); + Logger::Write(Logger::ZONE_INFO, "Layout", "Initializing " + layoutFile); - rapidxml::xml_document<> doc; - std::ifstream file(layoutFile.c_str()); - std::vector buffer((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + rapidxml::xml_document<> doc; + std::ifstream file(layoutFile.c_str()); + std::vector buffer((std::istreambuf_iterator(file)), std::istreambuf_iterator()); - if(!file.good()) - { - Logger::Write(Logger::ZONE_INFO, "Layout", "could not find layout file: " + layoutFile); - return NULL; - } + if(!file.good()) + { + Logger::Write(Logger::ZONE_INFO, "Layout", "could not find layout file: " + layoutFile); + return NULL; + } - try - { - buffer.push_back('\0'); + try + { + buffer.push_back('\0'); - doc.parse<0>(&buffer[0]); + doc.parse<0>(&buffer[0]); - xml_node<> *root = doc.first_node("layout"); + xml_node<> *root = doc.first_node("layout"); - if(!root) - { - Logger::Write(Logger::ZONE_ERROR, "Layout", "Missing tag"); - return NULL; - } - else - { - xml_attribute<> *layoutWidthXml = root->first_attribute("width"); - xml_attribute<> *layoutHeightXml = root->first_attribute("height"); - xml_attribute<> *fontXml = root->first_attribute("font"); - xml_attribute<> *fontColorXml = root->first_attribute("fontColor"); - int layoutHeight; - int layoutWidth; - if(!layoutWidthXml || !layoutHeightXml) - { - Logger::Write(Logger::ZONE_ERROR, "Layout", " tag must specify a width and height"); + if(!root) + { + Logger::Write(Logger::ZONE_ERROR, "Layout", "Missing tag"); return NULL; - } - if(fontXml) - { - //todo: reuse from ComponentBuilder. Not sure how since it relies on knowing the collection - std::string fontPropertyKey = "layouts." + LayoutKey + ".font"; - Config->SetProperty(fontPropertyKey, fontXml->value()); + } + else + { + xml_attribute<> *layoutWidthXml = root->first_attribute("width"); + xml_attribute<> *layoutHeightXml = root->first_attribute("height"); + xml_attribute<> *fontXml = root->first_attribute("font"); + xml_attribute<> *fontColorXml = root->first_attribute("fontColor"); + int layoutHeight; + int layoutWidth; + if(!layoutWidthXml || !layoutHeightXml) + { + Logger::Write(Logger::ZONE_ERROR, "Layout", " tag must specify a width and height"); + return NULL; + } + if(fontXml) + { + //todo: reuse from ComponentBuilder. Not sure how since it relies on knowing the collection + std::string fontPropertyKey = "layouts." + LayoutKey + ".font"; + Config->SetProperty(fontPropertyKey, fontXml->value()); - Font = Config->ConvertToAbsolutePath( - Config->GetAbsolutePath() + "/Layouts/" + LayoutKey + "/", - fontXml->value()); + Font = Config->ConvertToAbsolutePath( + Config->GetAbsolutePath() + "/Layouts/" + LayoutKey + "/", + fontXml->value()); - Logger::Write(Logger::ZONE_DEBUG, "Layout", "Layout font set to " + Font); + Logger::Write(Logger::ZONE_DEBUG, "Layout", "Layout font set to " + Font); - } + } + + if(fontColorXml) + { + int intColor = 0; + std::stringstream ss; + ss << std::hex << fontColorXml->value(); + ss >> intColor; + + FontColor.b = intColor & 0xFF; + intColor >>= 8; + FontColor.g = intColor & 0xFF; + intColor >>= 8; + FontColor.r = intColor & 0xFF; + } + + layoutWidth = Utils::ConvertInt(layoutWidthXml->value()); + layoutHeight = Utils::ConvertInt(layoutHeightXml->value()); + + if(layoutWidth == 0 || layoutHeight == 0) + { + Logger::Write(Logger::ZONE_ERROR, "Layout", "Layout width and height cannot be set to 0"); + return NULL; + } + + ScaleX = (float)ScreenWidth / (float)layoutWidth; + ScaleY = (float)ScreenHeight / (float)layoutHeight; - if(fontColorXml) - { - int intColor = 0; std::stringstream ss; - ss << std::hex << fontColorXml->value(); - ss >> intColor; + ss << layoutWidth << "x" << layoutHeight << " (scale " << ScaleX << "x" << ScaleY << ")"; + Logger::Write(Logger::ZONE_DEBUG, "Layout", "Layout resolution " + ss.str()); - FontColor.b = intColor & 0xFF; - intColor >>= 8; - FontColor.g = intColor & 0xFF; - intColor >>= 8; - FontColor.r = intColor & 0xFF; - } + page = new Page(Collection); - layoutWidth = Utils::ConvertInt(layoutWidthXml->value()); - layoutHeight = Utils::ConvertInt(layoutHeightXml->value()); - - if(layoutWidth == 0 || layoutHeight == 0) - { - Logger::Write(Logger::ZONE_ERROR, "Layout", "Layout width and height cannot be set to 0"); - return NULL; - } - - ScaleX = (float)ScreenWidth / (float)layoutWidth; - ScaleY = (float)ScreenHeight / (float)layoutHeight; - - std::stringstream ss; - ss << layoutWidth << "x" << layoutHeight << " (scale " << ScaleX << "x" << ScaleY << ")"; - Logger::Write(Logger::ZONE_DEBUG, "Layout", "Layout resolution " + ss.str()); - - page = new Page(Collection); - - // load sounds - for(xml_node<> *sound = root->first_node("sound"); sound; sound = sound->next_sibling("sound")) - { - xml_attribute<> *src = sound->first_attribute("src"); - xml_attribute<> *type = sound->first_attribute("type"); - std::string file = Configuration::ConvertToAbsolutePath(LayoutPath, src->value()); - if(!type) + // load sounds + for(xml_node<> *sound = root->first_node("sound"); sound; sound = sound->next_sibling("sound")) { - Logger::Write(Logger::ZONE_ERROR, "Layout", "Sound tag missing type attribute"); + xml_attribute<> *src = sound->first_attribute("src"); + xml_attribute<> *type = sound->first_attribute("type"); + std::string file = Configuration::ConvertToAbsolutePath(LayoutPath, src->value()); + if(!type) + { + Logger::Write(Logger::ZONE_ERROR, "Layout", "Sound tag missing type attribute"); + } + else + { + Sound *sound = new Sound(file); + std::string soundType = type->value(); + + if(!soundType.compare("load")) + { + page->SetLoadSound(sound); + } + else if(!soundType.compare("unload")) + { + page->SetUnloadSound(sound); + } + else if(!soundType.compare("highlight")) + { + page->SetHighlightSound(sound); + } + else if(!soundType.compare("select")) + { + page->SetSelectSound(sound); + } + else + { + Logger::Write(Logger::ZONE_WARNING, "Layout", "Unsupported sound effect type \"" + soundType + "\""); + } + } } - else + if(!BuildComponents(root, page)) { - Sound *sound = new Sound(file); - std::string soundType = type->value(); - - if(!soundType.compare("load")) - { - page->SetLoadSound(sound); - } - else if(!soundType.compare("unload")) - { - page->SetUnloadSound(sound); - } - else if(!soundType.compare("highlight")) - { - page->SetHighlightSound(sound); - } - else if(!soundType.compare("select")) - { - page->SetSelectSound(sound); - } - else - { - Logger::Write(Logger::ZONE_WARNING, "Layout", "Unsupported sound effect type \"" + soundType + "\""); - } + delete page; + page = NULL; } - } - if(!BuildComponents(root, page)) - { - delete page; - page = NULL; - } - } + } - } - catch(rapidxml::parse_error &e) - { - std::string what = e.what(); - long line = static_cast(std::count(&buffer.front(), e.where(), char('\n')) + 1); - std::stringstream ss; - ss << "Could not parse layout file. [Line: " << line << "] Reason: " << e.what(); + } + catch(rapidxml::parse_error &e) + { + std::string what = e.what(); + long line = static_cast(std::count(&buffer.front(), e.where(), char('\n')) + 1); + std::stringstream ss; + ss << "Could not parse layout file. [Line: " << line << "] Reason: " << e.what(); - Logger::Write(Logger::ZONE_ERROR, "Layout", ss.str()); - } - catch(std::exception &e) - { - std::string what = e.what(); - Logger::Write(Logger::ZONE_ERROR, "Layout", "Could not parse layout file. Reason: " + what); - } + Logger::Write(Logger::ZONE_ERROR, "Layout", ss.str()); + } + catch(std::exception &e) + { + std::string what = e.what(); + Logger::Write(Logger::ZONE_ERROR, "Layout", "Could not parse layout file. Reason: " + what); + } - if(page) - { - Logger::Write(Logger::ZONE_DEBUG, "Layout", "Created page"); - } + if(page) + { + Logger::Write(Logger::ZONE_DEBUG, "Layout", "Created page"); + } - return page; + return page; } float PageBuilder::GetHorizontalAlignment(xml_attribute<> *attribute, float valueIfNull) { - float value; - std::string str; + float value; + std::string str; - if(!attribute) - { - value = valueIfNull; - } - else - { - str = attribute->value(); + if(!attribute) + { + value = valueIfNull; + } + else + { + str = attribute->value(); - if(!str.compare("left")) - { - value = 0; - } - else if(!str.compare("center")) - { - value = static_cast(ScreenWidth) / 2; - } - else if(!str.compare("right") || !str.compare("stretch")) - { - value = static_cast(ScreenWidth); - } - else - { - value = Utils::ConvertFloat(str) * ScaleX; - } - } + if(!str.compare("left")) + { + value = 0; + } + else if(!str.compare("center")) + { + value = static_cast(ScreenWidth) / 2; + } + else if(!str.compare("right") || !str.compare("stretch")) + { + value = static_cast(ScreenWidth); + } + else + { + value = Utils::ConvertFloat(str) * ScaleX; + } + } - return value; + return value; } float PageBuilder::GetVerticalAlignment(xml_attribute<> *attribute, float valueIfNull) { - float value; - std::string str; - if(!attribute) - { - value = valueIfNull; - } - else - { - str = attribute->value(); + float value; + std::string str; + if(!attribute) + { + value = valueIfNull; + } + else + { + str = attribute->value(); - if(!str.compare("top")) - { - value = 0; - } - else if(!str.compare("center")) - { - value = static_cast(ScreenHeight / 2); - } - else if(!str.compare("bottom") || !str.compare("stretch")) - { - value = static_cast(ScreenHeight); - } - else - { - value = Utils::ConvertFloat(str) * ScaleY; - } - } - return value; + if(!str.compare("top")) + { + value = 0; + } + else if(!str.compare("center")) + { + value = static_cast(ScreenHeight / 2); + } + else if(!str.compare("bottom") || !str.compare("stretch")) + { + value = static_cast(ScreenHeight); + } + else + { + value = Utils::ConvertFloat(str) * ScaleY; + } + } + return value; } @@ -284,391 +284,391 @@ float PageBuilder::GetVerticalAlignment(xml_attribute<> *attribute, float valueI bool PageBuilder::BuildComponents(xml_node<> *layout, Page *page) { - bool retVal = true; - xml_node<> *menuXml = layout->first_node("menu"); - if(!menuXml) - { - Logger::Write(Logger::ZONE_ERROR, "Layout", "Missing menu tag"); - retVal = false; - } - else if(menuXml) - { - ScrollingList *scrollingList = BuildCustomMenu(menuXml); - page->SetMenu(scrollingList); + bool retVal = true; + xml_node<> *menuXml = layout->first_node("menu"); + if(!menuXml) + { + Logger::Write(Logger::ZONE_ERROR, "Layout", "Missing menu tag"); + retVal = false; + } + else if(menuXml) + { + ScrollingList *scrollingList = BuildCustomMenu(menuXml); + page->SetMenu(scrollingList); - for(xml_node<> *componentXml = layout->first_node("image"); componentXml; componentXml = componentXml->next_sibling("image")) - { - xml_attribute<> *src = componentXml->first_attribute("src"); + for(xml_node<> *componentXml = layout->first_node("image"); componentXml; componentXml = componentXml->next_sibling("image")) + { + xml_attribute<> *src = componentXml->first_attribute("src"); - if (!src) - { - Logger::Write(Logger::ZONE_ERROR, "Layout", "Image component in layout does not specify a source image file"); - } - else - { - std::string imagePath; - imagePath = Configuration::ConvertToAbsolutePath(LayoutPath, imagePath); + if (!src) + { + Logger::Write(Logger::ZONE_ERROR, "Layout", "Image component in layout does not specify a source image file"); + } + else + { + std::string imagePath; + imagePath = Configuration::ConvertToAbsolutePath(LayoutPath, imagePath); - imagePath.append("/"); - imagePath.append(src->value()); + imagePath.append("/"); + imagePath.append(src->value()); - Image *c = new Image(imagePath, ScaleX, ScaleY); - ViewInfo *v = c->GetBaseViewInfo(); - BuildViewInfo(componentXml, v); - LoadTweens(c, componentXml); - page->AddComponent(c); - } - } + Image *c = new Image(imagePath, ScaleX, ScaleY); + ViewInfo *v = c->GetBaseViewInfo(); + BuildViewInfo(componentXml, v); + LoadTweens(c, componentXml); + page->AddComponent(c); + } + } - for(xml_node<> *componentXml = layout->first_node("text"); componentXml; componentXml = componentXml->next_sibling("text")) - { - xml_attribute<> *value = componentXml->first_attribute("value"); + for(xml_node<> *componentXml = layout->first_node("text"); componentXml; componentXml = componentXml->next_sibling("text")) + { + xml_attribute<> *value = componentXml->first_attribute("value"); - if (!value) - { - Logger::Write(Logger::ZONE_WARNING, "Layout", "Text component in layout does not specify a value"); - } - else - { - FC->LoadFont(Font, FontColor); - Text *c = new Text(value->value(), FC->GetFont(Font), FontColor, ScaleX, ScaleY); - ViewInfo *v = c->GetBaseViewInfo(); + if (!value) + { + Logger::Write(Logger::ZONE_WARNING, "Layout", "Text component in layout does not specify a value"); + } + else + { + FC->LoadFont(Font, FontColor); + Text *c = new Text(value->value(), FC->GetFont(Font), FontColor, ScaleX, ScaleY); + ViewInfo *v = c->GetBaseViewInfo(); - BuildViewInfo(componentXml, v); + BuildViewInfo(componentXml, v); - LoadTweens(c, componentXml); - page->AddComponent(c); - } - } + LoadTweens(c, componentXml); + page->AddComponent(c); + } + } - LoadReloadableImages(layout, "reloadableImage", page); - LoadReloadableImages(layout, "reloadableVideo", page); - LoadReloadableImages(layout, "reloadableText", page); - } + LoadReloadableImages(layout, "reloadableImage", page); + LoadReloadableImages(layout, "reloadableVideo", page); + LoadReloadableImages(layout, "reloadableText", page); + } - return retVal; + return retVal; } void PageBuilder::LoadReloadableImages(xml_node<> *layout, std::string tagName, Page *page) { - for(xml_node<> *componentXml = layout->first_node(tagName.c_str()); componentXml; componentXml = componentXml->next_sibling(tagName.c_str())) - { - std::string reloadableImagePath; - std::string reloadableVideoPath; - xml_attribute<> *type = componentXml->first_attribute("type"); + for(xml_node<> *componentXml = layout->first_node(tagName.c_str()); componentXml; componentXml = componentXml->next_sibling(tagName.c_str())) + { + std::string reloadableImagePath; + std::string reloadableVideoPath; + xml_attribute<> *type = componentXml->first_attribute("type"); - if(tagName == "reloadableVideo") - { - type = componentXml->first_attribute("imageType"); - } + if(tagName == "reloadableVideo") + { + type = componentXml->first_attribute("imageType"); + } - if(!type && tagName == "reloadableVideo") - { - Logger::Write(Logger::ZONE_WARNING, "Layout", " component in layout does not specify an imageType for when the video does not exist"); - } - if(!type && (tagName == "reloadableImage" || tagName == "reloadableText")) - { - Logger::Write(Logger::ZONE_ERROR, "Layout", "Image component in layout does not specify a source image file"); - } + if(!type && tagName == "reloadableVideo") + { + Logger::Write(Logger::ZONE_WARNING, "Layout", " component in layout does not specify an imageType for when the video does not exist"); + } + if(!type && (tagName == "reloadableImage" || tagName == "reloadableText")) + { + Logger::Write(Logger::ZONE_ERROR, "Layout", "Image component in layout does not specify a source image file"); + } - if(type && (tagName == "reloadableVideo" || tagName == "reloadableImage")) - { - std::string configImagePath = "collections." + Collection + ".media." + type->value(); - if(!Config->GetPropertyAbsolutePath(configImagePath, reloadableImagePath)) - { - Logger::Write(Logger::ZONE_ERROR, "Layout", "Cannot process reloadable images because property \"" + configImagePath + "\" does not exist"); - } + if(type && (tagName == "reloadableVideo" || tagName == "reloadableImage")) + { + std::string configImagePath = "collections." + Collection + ".media." + type->value(); + if(!Config->GetPropertyAbsolutePath(configImagePath, reloadableImagePath)) + { + Logger::Write(Logger::ZONE_ERROR, "Layout", "Cannot process reloadable images because property \"" + configImagePath + "\" does not exist"); + } - std::string configVideoPath = "collections." + Collection + ".media.video"; + std::string configVideoPath = "collections." + Collection + ".media.video"; - if(!Config->GetPropertyAbsolutePath(configVideoPath, reloadableVideoPath)) - { - Logger::Write(Logger::ZONE_WARNING, "Layout", "Could not find videos folder as \"" + configVideoPath + "\" does not exist"); - } - } + if(!Config->GetPropertyAbsolutePath(configVideoPath, reloadableVideoPath)) + { + Logger::Write(Logger::ZONE_WARNING, "Layout", "Could not find videos folder as \"" + configVideoPath + "\" does not exist"); + } + } - Component *c = NULL; + Component *c = NULL; - if(tagName == "reloadableText") - { - if(type) - { - FC->LoadFont(Font, FontColor); - c = new ReloadableText(type->value(), FC->GetFont(Font), FontColor, LayoutKey, Collection, ScaleX, ScaleY); - } - } - else - { - c = new ReloadableMedia(reloadableImagePath, reloadableVideoPath, (tagName == "reloadableVideo"), ScaleX, ScaleY); - } + if(tagName == "reloadableText") + { + if(type) + { + FC->LoadFont(Font, FontColor); + c = new ReloadableText(type->value(), FC->GetFont(Font), FontColor, LayoutKey, Collection, ScaleX, ScaleY); + } + } + else + { + c = new ReloadableMedia(reloadableImagePath, reloadableVideoPath, (tagName == "reloadableVideo"), ScaleX, ScaleY); + } - if(c) - { - LoadTweens(c, componentXml); + if(c) + { + LoadTweens(c, componentXml); - page->AddComponent(c); - } - } + page->AddComponent(c); + } + } } void PageBuilder::LoadTweens(Component *c, xml_node<> *componentXml) { - ViewInfo *v = c->GetBaseViewInfo(); + ViewInfo *v = c->GetBaseViewInfo(); - BuildViewInfo(componentXml, v); + BuildViewInfo(componentXml, v); - Component::TweenSets *tweenSets; - tweenSets = new std::vector *>(); - GetTweenSets(componentXml->first_node("onEnter"), tweenSets); - c->SetOnEnterTweens(tweenSets); + Component::TweenSets *tweenSets; + tweenSets = new std::vector *>(); + GetTweenSets(componentXml->first_node("onEnter"), tweenSets); + c->SetOnEnterTweens(tweenSets); - tweenSets = new std::vector *>(); - GetTweenSets(componentXml->first_node("onExit"), tweenSets); - c->SetOnExitTweens(tweenSets); + tweenSets = new std::vector *>(); + GetTweenSets(componentXml->first_node("onExit"), tweenSets); + c->SetOnExitTweens(tweenSets); - tweenSets = new std::vector *>(); - GetTweenSets(componentXml->first_node("onIdle"), tweenSets); - c->SetOnIdleTweens(tweenSets); + tweenSets = new std::vector *>(); + GetTweenSets(componentXml->first_node("onIdle"), tweenSets); + c->SetOnIdleTweens(tweenSets); - tweenSets = new std::vector *>(); - GetTweenSets(componentXml->first_node("onHighlightEnter"), tweenSets); - c->SetOnHighlightEnterTweens(tweenSets); + tweenSets = new std::vector *>(); + GetTweenSets(componentXml->first_node("onHighlightEnter"), tweenSets); + c->SetOnHighlightEnterTweens(tweenSets); - tweenSets = new std::vector *>(); - GetTweenSets(componentXml->first_node("onHighlightExit"), tweenSets); - c->SetOnHighlightExitTweens(tweenSets); + tweenSets = new std::vector *>(); + GetTweenSets(componentXml->first_node("onHighlightExit"), tweenSets); + c->SetOnHighlightExitTweens(tweenSets); } ScrollingList * PageBuilder::BuildCustomMenu(xml_node<> *menuXml) { - ScrollingList *menu = NULL; - std::string imageType="null"; + ScrollingList *menu = NULL; + std::string imageType="null"; - xml_attribute<> *imageTypeXml = menuXml->first_attribute("imageType"); + xml_attribute<> *imageTypeXml = menuXml->first_attribute("imageType"); - if(imageTypeXml) - { - imageType = imageTypeXml->value(); - } + if(imageTypeXml) + { + imageType = imageTypeXml->value(); + } - FC->LoadFont(Font, FontColor); - menu = new ScrollingList(Config, ScaleX, ScaleY, FC->GetFont(Font), FontColor, LayoutKey, Collection, imageType); + FC->LoadFont(Font, FontColor); + menu = new ScrollingList(Config, ScaleX, ScaleY, FC->GetFont(Font), FontColor, LayoutKey, Collection, imageType); - ViewInfo *v = menu->GetBaseViewInfo(); - BuildViewInfo(menuXml, v); + ViewInfo *v = menu->GetBaseViewInfo(); + BuildViewInfo(menuXml, v); - std::vector *points = new std::vector(); + std::vector *points = new std::vector(); - int i = 0; - for(xml_node<> *componentXml = menuXml->first_node("item"); componentXml; componentXml = componentXml->next_sibling("item")) - { - ViewInfo *viewInfo = new ViewInfo(); - BuildViewInfo(componentXml, viewInfo); + int i = 0; + for(xml_node<> *componentXml = menuXml->first_node("item"); componentXml; componentXml = componentXml->next_sibling("item")) + { + ViewInfo *viewInfo = new ViewInfo(); + BuildViewInfo(componentXml, viewInfo); - points->push_back(viewInfo); + points->push_back(viewInfo); - xml_attribute<> *selected = componentXml->first_attribute("selected"); + xml_attribute<> *selected = componentXml->first_attribute("selected"); - if(selected) - { - menu->SetSelectedIndex(i); - } + if(selected) + { + menu->SetSelectedIndex(i); + } - i++; - } + i++; + } - menu->SetPoints(points); + menu->SetPoints(points); - return menu; + return menu; } xml_attribute<> *PageBuilder::FindRecursiveAttribute(xml_node<> *componentXml, std::string attribute) { - xml_attribute<> *attributeXml = NULL; - xml_node<> *parent = componentXml->parent(); + xml_attribute<> *attributeXml = NULL; + xml_node<> *parent = componentXml->parent(); - // root xml node height and width attributes are to define the layout size itself, not the elements - if(parent && parent->parent()) - { - attributeXml = componentXml->first_attribute(attribute.c_str()); + // root xml node height and width attributes are to define the layout size itself, not the elements + if(parent && parent->parent()) + { + attributeXml = componentXml->first_attribute(attribute.c_str()); - if(!attributeXml) - { - attributeXml = FindRecursiveAttribute(parent, attribute); - } - } + if(!attributeXml) + { + attributeXml = FindRecursiveAttribute(parent, attribute); + } + } - return attributeXml; + return attributeXml; } void PageBuilder::BuildViewInfo(xml_node<> *componentXml, ViewInfo *info) { - xml_attribute<> *x = FindRecursiveAttribute(componentXml, "x"); - xml_attribute<> *y = FindRecursiveAttribute(componentXml, "y"); - xml_attribute<> *xOffset = FindRecursiveAttribute(componentXml, "xOffset"); - xml_attribute<> *yOffset = FindRecursiveAttribute(componentXml, "yOffset"); - xml_attribute<> *xOrigin = FindRecursiveAttribute(componentXml, "xOrigin"); - xml_attribute<> *yOrigin = FindRecursiveAttribute(componentXml, "yOrigin"); - xml_attribute<> *height = FindRecursiveAttribute(componentXml, "height"); - xml_attribute<> *width = FindRecursiveAttribute(componentXml, "width"); - xml_attribute<> *fontSize = FindRecursiveAttribute(componentXml, "fontSize"); - xml_attribute<> *minHeight = FindRecursiveAttribute(componentXml, "minHeight"); - xml_attribute<> *minWidth = FindRecursiveAttribute(componentXml, "minWidth"); - xml_attribute<> *maxHeight = FindRecursiveAttribute(componentXml, "maxHeight"); - xml_attribute<> *maxWidth = FindRecursiveAttribute(componentXml, "maxWidth"); - xml_attribute<> *transparency = FindRecursiveAttribute(componentXml, "transparency"); - xml_attribute<> *angle = FindRecursiveAttribute(componentXml, "angle"); - xml_attribute<> *layer = FindRecursiveAttribute(componentXml, "layer"); + xml_attribute<> *x = FindRecursiveAttribute(componentXml, "x"); + xml_attribute<> *y = FindRecursiveAttribute(componentXml, "y"); + xml_attribute<> *xOffset = FindRecursiveAttribute(componentXml, "xOffset"); + xml_attribute<> *yOffset = FindRecursiveAttribute(componentXml, "yOffset"); + xml_attribute<> *xOrigin = FindRecursiveAttribute(componentXml, "xOrigin"); + xml_attribute<> *yOrigin = FindRecursiveAttribute(componentXml, "yOrigin"); + xml_attribute<> *height = FindRecursiveAttribute(componentXml, "height"); + xml_attribute<> *width = FindRecursiveAttribute(componentXml, "width"); + xml_attribute<> *fontSize = FindRecursiveAttribute(componentXml, "fontSize"); + xml_attribute<> *minHeight = FindRecursiveAttribute(componentXml, "minHeight"); + xml_attribute<> *minWidth = FindRecursiveAttribute(componentXml, "minWidth"); + xml_attribute<> *maxHeight = FindRecursiveAttribute(componentXml, "maxHeight"); + xml_attribute<> *maxWidth = FindRecursiveAttribute(componentXml, "maxWidth"); + xml_attribute<> *transparency = FindRecursiveAttribute(componentXml, "transparency"); + xml_attribute<> *angle = FindRecursiveAttribute(componentXml, "angle"); + xml_attribute<> *layer = FindRecursiveAttribute(componentXml, "layer"); - info->SetX(GetHorizontalAlignment(x, 0)); - info->SetY(GetVerticalAlignment(y, 0)); + info->SetX(GetHorizontalAlignment(x, 0)); + info->SetY(GetVerticalAlignment(y, 0)); - info->SetXOffset( GetHorizontalAlignment(xOffset, 0)); - info->SetYOffset( GetVerticalAlignment(yOffset, 0)); - float xOriginRelative = GetHorizontalAlignment(xOrigin, 0); - float yOriginRelative = GetVerticalAlignment(yOrigin, 0); + info->SetXOffset( GetHorizontalAlignment(xOffset, 0)); + info->SetYOffset( GetVerticalAlignment(yOffset, 0)); + float xOriginRelative = GetHorizontalAlignment(xOrigin, 0); + float yOriginRelative = GetVerticalAlignment(yOrigin, 0); - // the origins need to be saved as a percent since the heights and widths can be scaled - info->SetXOrigin(xOriginRelative / ScreenWidth); - info->SetYOrigin(yOriginRelative / ScreenHeight); + // the origins need to be saved as a percent since the heights and widths can be scaled + info->SetXOrigin(xOriginRelative / ScreenWidth); + info->SetYOrigin(yOriginRelative / ScreenHeight); - if(!height && !width) - { - info->SetHeight(-1); - info->SetWidth(-1); - } - else - { - info->SetHeight(GetVerticalAlignment(height, -1)); - info->SetWidth(GetHorizontalAlignment(width, -1)); - } - info->SetFontSize(GetVerticalAlignment(fontSize, -1)); - /* - std::stringstream ss; - ss << "font size is \"" << info->GetFontSize() << "\""; - Logger::Write(Logger::ZONE_ERROR, "Layout", ss.str()); - */ - info->SetMinHeight(GetVerticalAlignment(minHeight, 0)); - info->SetMinWidth(GetHorizontalAlignment(minWidth, 0)); - info->SetMaxHeight(GetVerticalAlignment(maxHeight, FLT_MAX)); - info->SetMaxWidth(GetVerticalAlignment(maxWidth, FLT_MAX)); - info->SetTransparency( transparency ? Utils::ConvertFloat(transparency->value()) : 1); - info->SetAngle( angle ? Utils::ConvertFloat(angle->value()) : 0); - info->SetLayer( layer ? Utils::ConvertInt(layer->value()) : 0); + if(!height && !width) + { + info->SetHeight(-1); + info->SetWidth(-1); + } + else + { + info->SetHeight(GetVerticalAlignment(height, -1)); + info->SetWidth(GetHorizontalAlignment(width, -1)); + } + info->SetFontSize(GetVerticalAlignment(fontSize, -1)); + /* + std::stringstream ss; + ss << "font size is \"" << info->GetFontSize() << "\""; + Logger::Write(Logger::ZONE_ERROR, "Layout", ss.str()); + */ + info->SetMinHeight(GetVerticalAlignment(minHeight, 0)); + info->SetMinWidth(GetHorizontalAlignment(minWidth, 0)); + info->SetMaxHeight(GetVerticalAlignment(maxHeight, FLT_MAX)); + info->SetMaxWidth(GetVerticalAlignment(maxWidth, FLT_MAX)); + info->SetTransparency( transparency ? Utils::ConvertFloat(transparency->value()) : 1); + info->SetAngle( angle ? Utils::ConvertFloat(angle->value()) : 0); + info->SetLayer( layer ? Utils::ConvertInt(layer->value()) : 0); } void PageBuilder::GetTweenSets(xml_node<> *node, std::vector *> *tweenSets) { - if(node) - { - for(xml_node<> *set = node->first_node("set"); set; set = set->next_sibling("set")) - { - std::vector *tweens = new std::vector(); - GetTweenSet(set, *tweens); - tweenSets->push_back(tweens); - } - } + if(node) + { + for(xml_node<> *set = node->first_node("set"); set; set = set->next_sibling("set")) + { + std::vector *tweens = new std::vector(); + GetTweenSet(set, *tweens); + tweenSets->push_back(tweens); + } + } } void PageBuilder::GetTweenSet(xml_node<> *node, std::vector &tweens) { - xml_attribute<> *durationXml = node->first_attribute("duration"); + xml_attribute<> *durationXml = node->first_attribute("duration"); - if(!durationXml) - { - Logger::Write(Logger::ZONE_ERROR, "Layout", "Animation set tag missing \"duration\" attribute"); - } - else - { - for(xml_node<> *animate = node->first_node("animate"); animate; animate = animate->next_sibling("animate")) - { - xml_attribute<> *type = animate->first_attribute("type"); - xml_attribute<> *from = animate->first_attribute("from"); - xml_attribute<> *to = animate->first_attribute("to"); - xml_attribute<> *algorithmXml = animate->first_attribute("algorithm"); + if(!durationXml) + { + Logger::Write(Logger::ZONE_ERROR, "Layout", "Animation set tag missing \"duration\" attribute"); + } + else + { + for(xml_node<> *animate = node->first_node("animate"); animate; animate = animate->next_sibling("animate")) + { + xml_attribute<> *type = animate->first_attribute("type"); + xml_attribute<> *from = animate->first_attribute("from"); + xml_attribute<> *to = animate->first_attribute("to"); + xml_attribute<> *algorithmXml = animate->first_attribute("algorithm"); - if(!type) - { - Logger::Write(Logger::ZONE_ERROR, "Layout", "Animate tag missing \"type\" attribute"); - } - else if(!from) - { - Logger::Write(Logger::ZONE_ERROR, "Layout", "Animate tag missing \"from\" attribute"); - } - else if(!to) - { - Logger::Write(Logger::ZONE_ERROR, "Layout", "Animate tag missing \"to\" attribute"); - } - else - { - float fromValue = Utils::ConvertFloat(from->value()); - float toValue = Utils::ConvertFloat(to->value()); - float durationValue = Utils::ConvertFloat(durationXml->value()); - - TweenAlgorithm algorithm = LINEAR; - TweenProperty property; - - if(algorithmXml) + if(!type) { - algorithm = Tween::GetTweenType(algorithmXml->value()); - + Logger::Write(Logger::ZONE_ERROR, "Layout", "Animate tag missing \"type\" attribute"); } - - if(Tween::GetTweenProperty(type->value(), property)) + else if(!from) { - switch(property) - { - case TWEEN_PROPERTY_WIDTH: - case TWEEN_PROPERTY_X: - case TWEEN_PROPERTY_X_OFFSET: - fromValue = GetHorizontalAlignment(from, 0); - toValue = GetHorizontalAlignment(to, 0); - break; - - // x origin gets translated to a percent - case TWEEN_PROPERTY_X_ORIGIN: - fromValue = GetHorizontalAlignment(from, 0) / ScreenWidth; - toValue = GetHorizontalAlignment(to, 0) / ScreenWidth; - break; - - case TWEEN_PROPERTY_HEIGHT: - case TWEEN_PROPERTY_Y: - case TWEEN_PROPERTY_Y_OFFSET: - case TWEEN_PROPERTY_FONT_SIZE: - fromValue = GetVerticalAlignment(from, 0); - toValue = GetVerticalAlignment(to, 0); - break; - - // y origin gets translated to a percent - case TWEEN_PROPERTY_Y_ORIGIN: - fromValue = GetVerticalAlignment(from, 0) / ScreenHeight; - toValue = GetVerticalAlignment(to, 0) / ScreenHeight; - break; - - default: - break; - } - - Tween *t = new Tween(property, algorithm, fromValue, toValue, durationValue); - tweens.push_back(t); + Logger::Write(Logger::ZONE_ERROR, "Layout", "Animate tag missing \"from\" attribute"); + } + else if(!to) + { + Logger::Write(Logger::ZONE_ERROR, "Layout", "Animate tag missing \"to\" attribute"); } else { - std::stringstream ss; - ss << "Unsupported tween type attribute \"" << type->value() << "\""; - Logger::Write(Logger::ZONE_ERROR, "Layout", ss.str()); + float fromValue = Utils::ConvertFloat(from->value()); + float toValue = Utils::ConvertFloat(to->value()); + float durationValue = Utils::ConvertFloat(durationXml->value()); + + TweenAlgorithm algorithm = LINEAR; + TweenProperty property; + + if(algorithmXml) + { + algorithm = Tween::GetTweenType(algorithmXml->value()); + + } + + if(Tween::GetTweenProperty(type->value(), property)) + { + switch(property) + { + case TWEEN_PROPERTY_WIDTH: + case TWEEN_PROPERTY_X: + case TWEEN_PROPERTY_X_OFFSET: + fromValue = GetHorizontalAlignment(from, 0); + toValue = GetHorizontalAlignment(to, 0); + break; + + // x origin gets translated to a percent + case TWEEN_PROPERTY_X_ORIGIN: + fromValue = GetHorizontalAlignment(from, 0) / ScreenWidth; + toValue = GetHorizontalAlignment(to, 0) / ScreenWidth; + break; + + case TWEEN_PROPERTY_HEIGHT: + case TWEEN_PROPERTY_Y: + case TWEEN_PROPERTY_Y_OFFSET: + case TWEEN_PROPERTY_FONT_SIZE: + fromValue = GetVerticalAlignment(from, 0); + toValue = GetVerticalAlignment(to, 0); + break; + + // y origin gets translated to a percent + case TWEEN_PROPERTY_Y_ORIGIN: + fromValue = GetVerticalAlignment(from, 0) / ScreenHeight; + toValue = GetVerticalAlignment(to, 0) / ScreenHeight; + break; + + default: + break; + } + + Tween *t = new Tween(property, algorithm, fromValue, toValue, durationValue); + tweens.push_back(t); + } + else + { + std::stringstream ss; + ss << "Unsupported tween type attribute \"" << type->value() << "\""; + Logger::Write(Logger::ZONE_ERROR, "Layout", ss.str()); + } } - } - } - } + } + } } diff --git a/Source/Graphics/PageBuilder.h b/Source/Graphics/PageBuilder.h index b7d5aeb..fd6a585 100644 --- a/Source/Graphics/PageBuilder.h +++ b/Source/Graphics/PageBuilder.h @@ -18,42 +18,42 @@ class Configuration; class PageBuilder { public: - PageBuilder(std::string layoutKey, std::string collection, Configuration *c, FontCache *fc); - virtual ~PageBuilder(); - Page *BuildPage(); + PageBuilder(std::string layoutKey, std::string collection, Configuration *c, FontCache *fc); + virtual ~PageBuilder(); + Page *BuildPage(); private: - std::string LayoutKey; - std::string LayoutPath; - std::string Collection; - Configuration *Config; - float ScaleX; - float ScaleY; - int ScreenHeight; - int ScreenWidth; - SDL_Color FontColor; - std::string Font; - FontCache *FC; //todo: don't need Font itself, just need cache instances - void LoadReloadableImages(rapidxml::xml_node<> *layout, std::string tagName, Page *page); + std::string LayoutKey; + std::string LayoutPath; + std::string Collection; + Configuration *Config; + float ScaleX; + float ScaleY; + int ScreenHeight; + int ScreenWidth; + SDL_Color FontColor; + std::string Font; + FontCache *FC; //todo: don't need Font itself, just need cache instances + void LoadReloadableImages(rapidxml::xml_node<> *layout, std::string tagName, Page *page); - float GetVerticalAlignment(rapidxml::xml_attribute<> *attribute, float valueIfNull); - float GetHorizontalAlignment(rapidxml::xml_attribute<> *attribute, float valueIfNull); - void BuildViewInfo(rapidxml::xml_node<> *componentXml, ViewInfo *info); - bool BuildComponents(rapidxml::xml_node<> *layout, Page *page); - void LoadTweens(Component *c, rapidxml::xml_node<> *componentXml); - ScrollingList * BuildCustomMenu(rapidxml::xml_node<> *menuXml); - rapidxml::xml_attribute<> *FindRecursiveAttribute(rapidxml::xml_node<> *componentXml, std::string attribute); + float GetVerticalAlignment(rapidxml::xml_attribute<> *attribute, float valueIfNull); + float GetHorizontalAlignment(rapidxml::xml_attribute<> *attribute, float valueIfNull); + void BuildViewInfo(rapidxml::xml_node<> *componentXml, ViewInfo *info); + bool BuildComponents(rapidxml::xml_node<> *layout, Page *page); + void LoadTweens(Component *c, rapidxml::xml_node<> *componentXml); + ScrollingList * BuildCustomMenu(rapidxml::xml_node<> *menuXml); + rapidxml::xml_attribute<> *FindRecursiveAttribute(rapidxml::xml_node<> *componentXml, std::string attribute); - void GetTweenSets(rapidxml::xml_node<> *node, std::vector *> *tweenSets); - void GetTweenSet(rapidxml::xml_node<> *node, std::vector &tweens); + void GetTweenSets(rapidxml::xml_node<> *node, std::vector *> *tweenSets); + void GetTweenSet(rapidxml::xml_node<> *node, std::vector &tweens); - void LoadLayoutXml(); - void LoadAnimations(std::string keyPrefix, Component &component, ViewInfo *defaults); - std::vector *BuildTweenPoints(std::string iteratorPrefix, ViewInfo *defaults); - Component * LoadComponent(std::string keyPrefix); - ScrollingList * LoadMenu(); + void LoadLayoutXml(); + void LoadAnimations(std::string keyPrefix, Component &component, ViewInfo *defaults); + std::vector *BuildTweenPoints(std::string iteratorPrefix, ViewInfo *defaults); + Component * LoadComponent(std::string keyPrefix); + ScrollingList * LoadMenu(); - void LoadListItems(std::string keyPrefix, std::vector *tweenPointList, ViewInfo *defaults, int &selectedItemIndex); - void UpdateViewInfoFromTag(std::string keyPrefix, ViewInfo *p, ViewInfo *defaults); + void LoadListItems(std::string keyPrefix, std::vector *tweenPointList, ViewInfo *defaults, int &selectedItemIndex); + void UpdateViewInfoFromTag(std::string keyPrefix, ViewInfo *p, ViewInfo *defaults); }; diff --git a/Source/Graphics/ViewInfo.cpp b/Source/Graphics/ViewInfo.cpp index 7173b12..d795174 100644 --- a/Source/Graphics/ViewInfo.cpp +++ b/Source/Graphics/ViewInfo.cpp @@ -7,24 +7,24 @@ #include ViewInfo::ViewInfo() -: X(0) -, Y(0) -, XOrigin(0) -, YOrigin(0) -, XOffset(0) -, YOffset(0) -, Width(-1) -, MinWidth(0) -, MaxWidth(FLT_MAX) -, Height(-1) -, MinHeight(0) -, MaxHeight(FLT_MAX) -, ImageWidth(0) -, ImageHeight(0) -, FontSize(-1) -, Angle(0) -, Transparency(1) -, Layer(0) + : X(0) + , Y(0) + , XOrigin(0) + , YOrigin(0) + , XOffset(0) + , YOffset(0) + , Width(-1) + , MinWidth(0) + , MaxWidth(FLT_MAX) + , Height(-1) + , MinHeight(0) + , MaxHeight(FLT_MAX) + , ImageWidth(0) + , ImageHeight(0) + , FontSize(-1) + , Angle(0) + , Transparency(1) + , Layer(0) { } @@ -35,266 +35,266 @@ ViewInfo::~ViewInfo() float ViewInfo::GetXRelativeToOrigin() const { - return X + XOffset - XOrigin*GetWidth(); + return X + XOffset - XOrigin*GetWidth(); } float ViewInfo::GetYRelativeToOrigin() const { - return Y + YOffset - YOrigin*GetHeight(); + return Y + YOffset - YOrigin*GetHeight(); } float ViewInfo::GetHeight() const { - float value = Height; + float value = Height; - if(Height == -1 && Width == -1) - { - value = ImageHeight; - } - else - { - if (Height == -1 && ImageWidth != 0) - { - value = ImageHeight * Width / ImageWidth; - } + if(Height == -1 && Width == -1) + { + value = ImageHeight; + } + else + { + if (Height == -1 && ImageWidth != 0) + { + value = ImageHeight * Width / ImageWidth; + } - if (value < MinHeight) - { - value = MinHeight; - } - else if (value > MaxHeight) - { - value = MaxHeight; - } - } + if (value < MinHeight) + { + value = MinHeight; + } + else if (value > MaxHeight) + { + value = MaxHeight; + } + } - return value; + return value; } float ViewInfo::GetWidth() const { - float value = Width; + float value = Width; - if(Height == -1 && Width == -1) - { - value = ImageWidth; - } - else - { - if (Width == -1 && ImageHeight != 0) - { - value = ImageWidth * Height / ImageHeight; - } - if (value < MinWidth) - { - value = MinWidth; - } - else if (value > MaxWidth) - { - value = MaxWidth; - } - } + if(Height == -1 && Width == -1) + { + value = ImageWidth; + } + else + { + if (Width == -1 && ImageHeight != 0) + { + value = ImageWidth * Height / ImageHeight; + } + if (value < MinWidth) + { + value = MinWidth; + } + else if (value > MaxWidth) + { + value = MaxWidth; + } + } - return value; + return value; } float ViewInfo::GetXOffset() const { - return XOffset; + return XOffset; } float ViewInfo::GetXOrigin() const { - return XOrigin; + return XOrigin; } float ViewInfo::GetYOffset() const { - return YOffset; + return YOffset; } float ViewInfo::GetYOrigin() const { - return YOrigin; + return YOrigin; } float ViewInfo::GetAngle() const { - return Angle; + return Angle; } void ViewInfo::SetAngle(float angle) { - Angle = angle; + Angle = angle; } float ViewInfo::GetImageHeight() const { - return ImageHeight; + return ImageHeight; } void ViewInfo::SetImageHeight(float imageheight) { - ImageHeight = imageheight; + ImageHeight = imageheight; } float ViewInfo::GetImageWidth() const { - return ImageWidth; + return ImageWidth; } void ViewInfo::SetImageWidth(float imagewidth) { - ImageWidth = imagewidth; + ImageWidth = imagewidth; } unsigned int ViewInfo::GetLayer() const { - return Layer; + return Layer; } void ViewInfo::SetLayer(unsigned int layer) { - Layer = layer; + Layer = layer; } float ViewInfo::GetMaxHeight() const { - return MaxHeight; + return MaxHeight; } void ViewInfo::SetMaxHeight(float maxheight) { - MaxHeight = maxheight; + MaxHeight = maxheight; } float ViewInfo::GetMaxWidth() const { - return MaxWidth; + return MaxWidth; } void ViewInfo::SetMaxWidth(float maxwidth) { - MaxWidth = maxwidth; + MaxWidth = maxwidth; } float ViewInfo::GetMinHeight() const { - return MinHeight; + return MinHeight; } void ViewInfo::SetMinHeight(float minheight) { - MinHeight = minheight; + MinHeight = minheight; } float ViewInfo::GetMinWidth() const { - return MinWidth; + return MinWidth; } void ViewInfo::SetMinWidth(float minwidth) { - MinWidth = minwidth; + MinWidth = minwidth; } float ViewInfo::GetTransparency() const { - return Transparency; + return Transparency; } void ViewInfo::SetTransparency(float transparency) { - Transparency = transparency; + Transparency = transparency; } float ViewInfo::GetX() const { - return X; + return X; } void ViewInfo::SetX(float x) { - X = x; + X = x; } void ViewInfo::SetXOffset(float offset) { - XOffset = offset; + XOffset = offset; } void ViewInfo::SetXOrigin(float origin) { - XOrigin = origin; + XOrigin = origin; } float ViewInfo::GetY() const { - return Y; + return Y; } void ViewInfo::SetY(float y) { - Y = y; + Y = y; } void ViewInfo::SetYOffset(float offset) { - YOffset = offset; + YOffset = offset; } void ViewInfo::SetYOrigin(float origin) { - YOrigin = origin; + YOrigin = origin; } float ViewInfo::GetRawYOrigin() { - return YOrigin; + return YOrigin; } float ViewInfo::GetRawXOrigin() { - return XOrigin; + return XOrigin; } float ViewInfo::GetRawWidth() { - return Width; + return Width; } float ViewInfo::GetRawHeight() { - return Height; + return Height; } void ViewInfo::SetHeight(float height) { - Height = height; + Height = height; } void ViewInfo::SetWidth(float width) { - Width = width; + Width = width; } float ViewInfo::GetFontSize() const { - if(FontSize == -1) - { - return GetHeight(); - } - else - { - return FontSize; - } + if(FontSize == -1) + { + return GetHeight(); + } + else + { + return FontSize; + } } void ViewInfo::SetFontSize(float fontSize) { - FontSize = fontSize; + FontSize = fontSize; } diff --git a/Source/Graphics/ViewInfo.h b/Source/Graphics/ViewInfo.h index 3383cd2..4bbde83 100644 --- a/Source/Graphics/ViewInfo.h +++ b/Source/Graphics/ViewInfo.h @@ -11,79 +11,79 @@ class ViewInfo { public: - ViewInfo(); - virtual ~ViewInfo(); + ViewInfo(); + virtual ~ViewInfo(); - float GetXRelativeToOrigin() const; - float GetYRelativeToOrigin() const; + float GetXRelativeToOrigin() const; + float GetYRelativeToOrigin() const; - float GetHeight() const; - float GetWidth() const; - float GetAngle() const; - void SetAngle(float angle); - float GetImageHeight() const; - void SetImageHeight(float imageheight); - float GetImageWidth() const; - void SetImageWidth(float imagewidth); - unsigned int GetLayer() const; - void SetLayer(unsigned int layer); - float GetMaxHeight() const; - void SetMaxHeight(float maxheight); - float GetMaxWidth() const; - void SetMaxWidth(float maxwidth); - float GetMinHeight() const; - void SetMinHeight(float minheight); - float GetMinWidth() const; - void SetMinWidth(float minwidth); - float GetTransparency() const; - void SetTransparency(float transparency); - float GetX() const; - void SetX(float x); - float GetXOffset() const; - void SetXOffset(float offset); - float GetXOrigin() const; - void SetXOrigin(float origin); - float GetY() const; - void SetY(float y); - float GetYOffset() const; - void SetYOffset(float offset); - float GetYOrigin() const; - void SetYOrigin(float origin); - float GetRawYOrigin(); - float GetRawXOrigin(); - float GetRawWidth(); - float GetRawHeight(); + float GetHeight() const; + float GetWidth() const; + float GetAngle() const; + void SetAngle(float angle); + float GetImageHeight() const; + void SetImageHeight(float imageheight); + float GetImageWidth() const; + void SetImageWidth(float imagewidth); + unsigned int GetLayer() const; + void SetLayer(unsigned int layer); + float GetMaxHeight() const; + void SetMaxHeight(float maxheight); + float GetMaxWidth() const; + void SetMaxWidth(float maxwidth); + float GetMinHeight() const; + void SetMinHeight(float minheight); + float GetMinWidth() const; + void SetMinWidth(float minwidth); + float GetTransparency() const; + void SetTransparency(float transparency); + float GetX() const; + void SetX(float x); + float GetXOffset() const; + void SetXOffset(float offset); + float GetXOrigin() const; + void SetXOrigin(float origin); + float GetY() const; + void SetY(float y); + float GetYOffset() const; + void SetYOffset(float offset); + float GetYOrigin() const; + void SetYOrigin(float origin); + float GetRawYOrigin(); + float GetRawXOrigin(); + float GetRawWidth(); + float GetRawHeight(); - void SetHeight(float height); - void SetWidth(float width); - float GetFontSize() const; - void SetFontSize(float fontSize); + void SetHeight(float height); + void SetWidth(float width); + float GetFontSize() const; + void SetFontSize(float fontSize); - static const int AlignCenter = -1; - static const int AlignLeft = -2; - static const int AlignTop = -3; - static const int AlignRight = -4; - static const int AlignBottom = -5; + static const int AlignCenter = -1; + static const int AlignLeft = -2; + static const int AlignTop = -3; + static const int AlignRight = -4; + static const int AlignBottom = -5; private: - float X; - float Y; - float XOrigin; - float YOrigin; - float XOffset; - float YOffset; - float Width; - float MinWidth; - float MaxWidth; - float Height; - float MinHeight; - float MaxHeight; - float ImageWidth; - float ImageHeight; - float FontSize; - float Angle; - float Transparency; - unsigned int Layer; - float HorizontalScale; - float VerticalScale; + float X; + float Y; + float XOrigin; + float YOrigin; + float XOffset; + float YOffset; + float Width; + float MinWidth; + float MaxWidth; + float Height; + float MinHeight; + float MaxHeight; + float ImageWidth; + float ImageHeight; + float FontSize; + float Angle; + float Transparency; + unsigned int Layer; + float HorizontalScale; + float VerticalScale; }; diff --git a/Source/Main.cpp b/Source/Main.cpp index 3e7ee11..6d3e7c1 100644 --- a/Source/Main.cpp +++ b/Source/Main.cpp @@ -22,171 +22,173 @@ CollectionDatabase *InitializeCollectionDatabase(DB &db, Configuration &config); int main(int argc, char *argv[]) { - Configuration::Initialize(); + Configuration::Initialize(); - Configuration config; + Configuration config; - if(!StartLogging()) { - return -1; - } + if(!StartLogging()) + { + return -1; + } - if(!ImportConfiguration(&config)) - { - return -1; - } + if(!ImportConfiguration(&config)) + { + return -1; + } - DB db(Configuration::GetAbsolutePath() + "/cache.db"); + DB db(Configuration::GetAbsolutePath() + "/cache.db"); - if(!db.Initialize()) - { - return -1; - } - + if(!db.Initialize()) + { + return -1; + } - CollectionDatabase *cdb = InitializeCollectionDatabase(db, config); - if(!cdb) { - return -1; - } - RetroFE p(cdb, &config); + CollectionDatabase *cdb = InitializeCollectionDatabase(db, config); + if(!cdb) + { + return -1; + } - if(p.Initialize()) - { - p.Run(); - } + RetroFE p(cdb, &config); - p.DeInitialize(); + if(p.Initialize()) + { + p.Run(); + } - Logger::DeInitialize(); + p.DeInitialize(); - return 0; + Logger::DeInitialize(); + + return 0; } bool ImportConfiguration(Configuration *c) { - std::string configPath = Configuration::GetAbsolutePath(); - std::string launchersPath = Configuration::GetAbsolutePath() + "/Launchers"; - std::string collectionsPath = Configuration::GetAbsolutePath() + "/Collections"; - DIR *dp; - struct dirent *dirp; + std::string configPath = Configuration::GetAbsolutePath(); + std::string launchersPath = Configuration::GetAbsolutePath() + "/Launchers"; + std::string collectionsPath = Configuration::GetAbsolutePath() + "/Collections"; + DIR *dp; + struct dirent *dirp; - if(!c->Import("", configPath + "/Settings.conf")) - { - Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not import \"" + configPath + "/Settings.conf\""); - return false; - } + if(!c->Import("", configPath + "/Settings.conf")) + { + Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not import \"" + configPath + "/Settings.conf\""); + return false; + } - if(!c->Import("controls", configPath + "/Controls.conf")) - { - Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not import \"" + configPath + "/Settings.conf\""); - return false; - } + if(!c->Import("controls", configPath + "/Controls.conf")) + { + Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not import \"" + configPath + "/Settings.conf\""); + return false; + } - dp = opendir(launchersPath.c_str()); + dp = opendir(launchersPath.c_str()); - if(dp == NULL) - { - Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not read directory \"" + launchersPath + "\""); - return false; - } + if(dp == NULL) + { + Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not read directory \"" + launchersPath + "\""); + return false; + } - while((dirp = readdir(dp)) != NULL) - { - if (dirp->d_type != DT_DIR && std::string(dirp->d_name) != "." && std::string(dirp->d_name) != "..") - { - std::string basename = dirp->d_name; - - // if(basename.length() > 0) - { - std::string extension = basename.substr(basename.find_last_of("."), basename.size()-1); - basename = basename.substr(0, basename.find_last_of(".")); - - if(extension == ".conf") - { - std::string prefix = "launchers." + basename; - - std::string importFile = launchersPath + "/" + std::string(dirp->d_name); - - if(!c->Import(prefix, importFile)) - { - Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not import \"" + importFile + "\""); - return false; - } - } - } - } - } - - dp = opendir(collectionsPath.c_str()); - - if(dp == NULL) - { - Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not read directory \"" + collectionsPath + "\""); - return false; - } - - while((dirp = readdir(dp)) != NULL) - { - if (dirp->d_type == DT_DIR && std::string(dirp->d_name) != "." && std::string(dirp->d_name) != "..") - { - std::string prefix = "collections." + std::string(dirp->d_name); - - std::string settingsFile = collectionsPath + "/" + dirp->d_name + "/Settings.conf"; - - if(!c->Import(prefix, settingsFile)) + while((dirp = readdir(dp)) != NULL) + { + if (dirp->d_type != DT_DIR && std::string(dirp->d_name) != "." && std::string(dirp->d_name) != "..") { - Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not import \"" + settingsFile + "\""); - return false; + std::string basename = dirp->d_name; + + // if(basename.length() > 0) + { + std::string extension = basename.substr(basename.find_last_of("."), basename.size()-1); + basename = basename.substr(0, basename.find_last_of(".")); + + if(extension == ".conf") + { + std::string prefix = "launchers." + basename; + + std::string importFile = launchersPath + "/" + std::string(dirp->d_name); + + if(!c->Import(prefix, importFile)) + { + Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not import \"" + importFile + "\""); + return false; + } + } + } } - } - } + } - Logger::Write(Logger::ZONE_INFO, "RetroFE", "Imported configuration"); + dp = opendir(collectionsPath.c_str()); - return true; + if(dp == NULL) + { + Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not read directory \"" + collectionsPath + "\""); + return false; + } + + while((dirp = readdir(dp)) != NULL) + { + if (dirp->d_type == DT_DIR && std::string(dirp->d_name) != "." && std::string(dirp->d_name) != "..") + { + std::string prefix = "collections." + std::string(dirp->d_name); + + std::string settingsFile = collectionsPath + "/" + dirp->d_name + "/Settings.conf"; + + if(!c->Import(prefix, settingsFile)) + { + Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not import \"" + settingsFile + "\""); + return false; + } + } + } + + Logger::Write(Logger::ZONE_INFO, "RetroFE", "Imported configuration"); + + return true; } -bool StartLogging() +bool StartLogging() { - std::string logFile = Configuration::GetAbsolutePath() + "/Log.txt"; + std::string logFile = Configuration::GetAbsolutePath() + "/Log.txt"; - if(!Logger::Initialize(logFile)) - { - Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not open \"" + logFile + "\" for writing"); - return false; - } + if(!Logger::Initialize(logFile)) + { + Logger::Write(Logger::ZONE_ERROR, "RetroFE", "Could not open \"" + logFile + "\" for writing"); + return false; + } - Logger::Write(Logger::ZONE_INFO, "RetroFE", "Version " + Version::GetString() + " starting"); + Logger::Write(Logger::ZONE_INFO, "RetroFE", "Version " + Version::GetString() + " starting"); #ifdef WIN32 - Logger::Write(Logger::ZONE_INFO, "RetroFE", "OS: Windows"); + Logger::Write(Logger::ZONE_INFO, "RetroFE", "OS: Windows"); #else - Logger::Write(Logger::ZONE_INFO, "RetroFE", "OS: Linux"); + Logger::Write(Logger::ZONE_INFO, "RetroFE", "OS: Linux"); #endif - Logger::Write(Logger::ZONE_INFO, "RetroFE", "Absolute path: " + Configuration::GetAbsolutePath()); + Logger::Write(Logger::ZONE_INFO, "RetroFE", "Absolute path: " + Configuration::GetAbsolutePath()); - return true; + return true; } -CollectionDatabase *InitializeCollectionDatabase(DB &db, Configuration &config) +CollectionDatabase *InitializeCollectionDatabase(DB &db, Configuration &config) { - CollectionDatabase *cdb = NULL; - std::string dbFile = (Configuration::GetAbsolutePath() + "/cache.db"); - std::ifstream infile(dbFile.c_str()); + CollectionDatabase *cdb = NULL; + std::string dbFile = (Configuration::GetAbsolutePath() + "/cache.db"); + std::ifstream infile(dbFile.c_str()); - cdb = new CollectionDatabase(&db, &config); + cdb = new CollectionDatabase(&db, &config); - if(!cdb->Initialize()) - { - delete cdb; - cdb = NULL; - } - else if(!cdb->Import()) - { - delete cdb; - cdb = NULL; - } + if(!cdb->Initialize()) + { + delete cdb; + cdb = NULL; + } + else if(!cdb->Import()) + { + delete cdb; + cdb = NULL; + } - return cdb; + return cdb; } \ No newline at end of file diff --git a/Source/RetroFE.cpp b/Source/RetroFE.cpp index b442dcb..c6d0cb3 100644 --- a/Source/RetroFE.cpp +++ b/Source/RetroFE.cpp @@ -26,474 +26,474 @@ Page *page = NULL; RetroFE::RetroFE(CollectionDatabase *db, Configuration *c) -: Config(c) -, CollectionDB(db) -, Input(Config) -, KeyInputDisable(0) -, InactiveKeyTime(0) -, AttractMode(false) -, CurrentTime(0) -, VideoInst(NULL) + : Config(c) + , CollectionDB(db) + , Input(Config) + , KeyInputDisable(0) + , InactiveKeyTime(0) + , AttractMode(false) + , CurrentTime(0) + , VideoInst(NULL) { } RetroFE::~RetroFE() { - DeInitialize(); + DeInitialize(); } void RetroFE::Render() { - SDL_LockMutex(SDL::GetMutex()); - SDL_SetRenderDrawColor(SDL::GetRenderer(), 0x0, 0x0, 0x00, 0xFF); - SDL_RenderClear(SDL::GetRenderer()); + SDL_LockMutex(SDL::GetMutex()); + SDL_SetRenderDrawColor(SDL::GetRenderer(), 0x0, 0x0, 0x00, 0xFF); + SDL_RenderClear(SDL::GetRenderer()); - Page *page = PageChain.back(); + Page *page = PageChain.back(); - if(page) - { - page->Draw(); - } + if(page) + { + page->Draw(); + } - SDL_RenderPresent(SDL::GetRenderer()); - SDL_UnlockMutex(SDL::GetMutex()); + SDL_RenderPresent(SDL::GetRenderer()); + SDL_UnlockMutex(SDL::GetMutex()); } bool RetroFE::Initialize() { - Logger::Write(Logger::ZONE_INFO, "RetroFE", "Initializing"); + Logger::Write(Logger::ZONE_INFO, "RetroFE", "Initializing"); - if(!Input.Initialize()) return false; - if(!SDL::Initialize(Config)) return false; - FC.Initialize(); + if(!Input.Initialize()) return false; + if(!SDL::Initialize(Config)) return false; + FC.Initialize(); - bool videoEnable = true; - int videoLoop = 0; + bool videoEnable = true; + int videoLoop = 0; - Config->GetProperty("videoEnable", videoEnable); - Config->GetProperty("videoLoop", videoLoop); + Config->GetProperty("videoEnable", videoEnable); + Config->GetProperty("videoLoop", videoLoop); - VideoFactory::SetEnabled(videoEnable); - VideoFactory::SetNumLoops(videoLoop); - VideoFactory vf; - VideoInst = vf.CreateVideo(); + VideoFactory::SetEnabled(videoEnable); + VideoFactory::SetNumLoops(videoLoop); + VideoFactory vf; + VideoInst = vf.CreateVideo(); - return true; + return true; } void RetroFE::LaunchEnter() { - if(PageChain.size() > 0) - { - Page *p = PageChain.back(); - p->LaunchEnter(); - } - SDL_SetWindowGrab(SDL::GetWindow(), SDL_FALSE); + if(PageChain.size() > 0) + { + Page *p = PageChain.back(); + p->LaunchEnter(); + } + SDL_SetWindowGrab(SDL::GetWindow(), SDL_FALSE); } void RetroFE::LaunchExit() { - SDL_RestoreWindow(SDL::GetWindow()); - SDL_SetWindowGrab(SDL::GetWindow(), SDL_TRUE); + SDL_RestoreWindow(SDL::GetWindow()); + SDL_SetWindowGrab(SDL::GetWindow(), SDL_TRUE); - if(PageChain.size() > 0) - { - Page *p = PageChain.back(); - p->LaunchExit(); - } + if(PageChain.size() > 0) + { + Page *p = PageChain.back(); + p->LaunchExit(); + } } void RetroFE::FreeGraphicsMemory() { - if(PageChain.size() > 0) - { - Page *p = PageChain.back(); - p->FreeGraphicsMemory(); - } - FC.DeInitialize(); + if(PageChain.size() > 0) + { + Page *p = PageChain.back(); + p->FreeGraphicsMemory(); + } + FC.DeInitialize(); - SDL::DeInitialize(); + SDL::DeInitialize(); } void RetroFE::AllocateGraphicsMemory() { - SDL::Initialize(Config); + SDL::Initialize(Config); - FC.Initialize(); + FC.Initialize(); - if(PageChain.size() > 0) - { - Page *p = PageChain.back(); - p->AllocateGraphicsMemory(); - p->Start(); - } + if(PageChain.size() > 0) + { + Page *p = PageChain.back(); + p->AllocateGraphicsMemory(); + p->Start(); + } } bool RetroFE::DeInitialize() { - bool retVal = true; - FreeGraphicsMemory(); + bool retVal = true; + FreeGraphicsMemory(); - bool videoEnable = true; + bool videoEnable = true; - while(PageChain.size() > 0) - { - Page *page = PageChain.back(); - delete page; - PageChain.pop_back(); - } + while(PageChain.size() > 0) + { + Page *page = PageChain.back(); + delete page; + PageChain.pop_back(); + } - if(VideoInst) - { - delete VideoInst; - VideoInst = NULL; - } + if(VideoInst) + { + delete VideoInst; + VideoInst = NULL; + } - //todo: handle video deallocation - return retVal; + //todo: handle video deallocation + return retVal; } Configuration *RetroFE::GetConfiguration() { - return Config; + return Config; } void RetroFE::Run() { - int attractModeTime = 0; - bool attractMode = false; - std::string firstCollection = "Main"; + int attractModeTime = 0; + bool attractMode = false; + std::string firstCollection = "Main"; - Config->GetProperty("attractModeTime", attractModeTime); - Config->GetProperty("firstCollection", firstCollection); + Config->GetProperty("attractModeTime", attractModeTime); + Config->GetProperty("firstCollection", firstCollection); - bool running = true; - Item *nextPageItem = NULL; - bool adminMode = false; - float attractModeRandomTime = 0; - bool selectActive = false; + bool running = true; + Item *nextPageItem = NULL; + bool adminMode = false; + float attractModeRandomTime = 0; + bool selectActive = false; - //todo: break up into helper methods - Logger::Write(Logger::ZONE_INFO, "RetroFE", "Loading first page"); + //todo: break up into helper methods + Logger::Write(Logger::ZONE_INFO, "RetroFE", "Loading first page"); - page = LoadPage(firstCollection); + page = LoadPage(firstCollection); - float frameCount = 0; - float fpsStartTime = 0; - RETROFE_STATE state = RETROFE_IDLE; + float frameCount = 0; + float fpsStartTime = 0; + RETROFE_STATE state = RETROFE_IDLE; - while (running) - { - float lastTime = 0; - float deltaTime = 0; - page = PageChain.back(); - Launcher l(this); + while (running) + { + float lastTime = 0; + float deltaTime = 0; + page = PageChain.back(); + Launcher l(this); - if(!page) - { - Logger::Write(Logger::ZONE_WARNING, "RetroFE", "Could not load page"); - running = false; - break; - } + if(!page) + { + Logger::Write(Logger::ZONE_WARNING, "RetroFE", "Could not load page"); + running = false; + break; + } - // todo: This could be transformed to use the state design pattern. - switch(state) - { - case RETROFE_IDLE: - state = ProcessUserInput(); - break; + // todo: This could be transformed to use the state design pattern. + switch(state) + { + case RETROFE_IDLE: + state = ProcessUserInput(); + break; - case RETROFE_NEXT_PAGE_REQUEST: - page->Stop(); - state = RETROFE_NEXT_PAGE_WAIT; - break; + case RETROFE_NEXT_PAGE_REQUEST: + page->Stop(); + state = RETROFE_NEXT_PAGE_WAIT; + break; - case RETROFE_NEXT_PAGE_WAIT: - if(page->IsHidden()) - { - page = LoadPage(NextPageItem->GetName()); - state = RETROFE_NEW; - } - break; + case RETROFE_NEXT_PAGE_WAIT: + if(page->IsHidden()) + { + page = LoadPage(NextPageItem->GetName()); + state = RETROFE_NEW; + } + break; - case RETROFE_LAUNCH_REQUEST: - l.Run(page->GetCollectionName(), NextPageItem); - state = RETROFE_IDLE; - break; + case RETROFE_LAUNCH_REQUEST: + l.Run(page->GetCollectionName(), NextPageItem); + state = RETROFE_IDLE; + break; - case RETROFE_BACK_REQUEST: - page->Stop(); - state = RETROFE_BACK_WAIT; - break; + case RETROFE_BACK_REQUEST: + page->Stop(); + state = RETROFE_BACK_WAIT; + break; - case RETROFE_BACK_WAIT: - if(page->IsHidden()) - { - PageChain.pop_back(); - delete page; + case RETROFE_BACK_WAIT: + if(page->IsHidden()) + { + PageChain.pop_back(); + delete page; - page = PageChain.back(); + page = PageChain.back(); + CurrentTime = (float)SDL_GetTicks() / 1000; + + page->AllocateGraphicsMemory(); + page->Start(); + state = RETROFE_NEW; + } + break; + + case RETROFE_NEW: + if(page->IsIdle()) + { + state = RETROFE_IDLE; + } + break; + + case RETROFE_QUIT_REQUEST: + page->Stop(); + state = RETROFE_QUIT; + break; + + case RETROFE_QUIT: + if(page->IsHidden()) + { + running = false; + } + + break; + } + + // the logic below could be done in a helper method + if(running) + { + lastTime = CurrentTime; CurrentTime = (float)SDL_GetTicks() / 1000; - page->AllocateGraphicsMemory(); - page->Start(); - state = RETROFE_NEW; - } - break; - - case RETROFE_NEW: - if(page->IsIdle()) - { - state = RETROFE_IDLE; - } - break; - - case RETROFE_QUIT_REQUEST: - page->Stop(); - state = RETROFE_QUIT; - break; - - case RETROFE_QUIT: - if(page->IsHidden()) - { - running = false; - } - - break; - } - - // the logic below could be done in a helper method - if(running) - { - lastTime = CurrentTime; - CurrentTime = (float)SDL_GetTicks() / 1000; - - if (CurrentTime < lastTime) - { - CurrentTime = lastTime; - } - - deltaTime = CurrentTime - lastTime; - double sleepTime = 1000.0/60.0 - deltaTime*1000; - if(sleepTime > 0) - { - SDL_Delay(static_cast(sleepTime)); - } - - ++frameCount; - - if(CurrentTime - fpsStartTime > 1.0) - { - // don't print the first framerate, it's likely inaccurate - bool logFps = false; - Config->GetProperty("debug.logfps", logFps); - - if(fpsStartTime != 0 && logFps) + if (CurrentTime < lastTime) { - std::stringstream fpsstream; - fpsstream << frameCount/(CurrentTime - fpsStartTime) << " FPS"; - Logger::Write(Logger::ZONE_DEBUG, "RetroFE", fpsstream.str()); + CurrentTime = lastTime; } - fpsStartTime = CurrentTime; - frameCount = 0; - } - - InactiveKeyTime += deltaTime; - - if(!AttractMode && InactiveKeyTime > attractModeTime) - { - AttractMode = true; - InactiveKeyTime = 0; - attractModeRandomTime = ((float)((1000+rand()) % 5000)) / 1000; - } - - if(attractMode) - { - page->SetScrolling(Page::ScrollDirectionForward); - - if(InactiveKeyTime > attractModeRandomTime) + deltaTime = CurrentTime - lastTime; + double sleepTime = 1000.0/60.0 - deltaTime*1000; + if(sleepTime > 0) { - InactiveKeyTime = 0; - attractMode = false; - page->SetScrolling(Page::ScrollDirectionIdle); + SDL_Delay(static_cast(sleepTime)); } - } - page->Update(deltaTime); - Render(); - } - } + ++frameCount; + + if(CurrentTime - fpsStartTime > 1.0) + { + // don't print the first framerate, it's likely inaccurate + bool logFps = false; + Config->GetProperty("debug.logfps", logFps); + + if(fpsStartTime != 0 && logFps) + { + std::stringstream fpsstream; + fpsstream << frameCount/(CurrentTime - fpsStartTime) << " FPS"; + Logger::Write(Logger::ZONE_DEBUG, "RetroFE", fpsstream.str()); + } + + fpsStartTime = CurrentTime; + frameCount = 0; + } + + InactiveKeyTime += deltaTime; + + if(!AttractMode && InactiveKeyTime > attractModeTime) + { + AttractMode = true; + InactiveKeyTime = 0; + attractModeRandomTime = ((float)((1000+rand()) % 5000)) / 1000; + } + + if(attractMode) + { + page->SetScrolling(Page::ScrollDirectionForward); + + if(InactiveKeyTime > attractModeRandomTime) + { + InactiveKeyTime = 0; + attractMode = false; + page->SetScrolling(Page::ScrollDirectionIdle); + } + } + + page->Update(deltaTime); + Render(); + } + } } bool RetroFE::ItemSelected() { - Item *item = page->GetSelectedItem(); + Item *item = page->GetSelectedItem(); - if(!item) return false; + if(!item) return false; - if(item->IsLeaf()) - { - Launcher l(this); + if(item->IsLeaf()) + { + Launcher l(this); - l.Run(page->GetCollectionName(), item); - } - else - { - NextPageItem = item; - LoadPage(page->GetCollectionName()); - page->Stop(); - } + l.Run(page->GetCollectionName(), item); + } + else + { + NextPageItem = item; + LoadPage(page->GetCollectionName()); + page->Stop(); + } - return true; + return true; } bool RetroFE::Back(bool &exit) { - bool canGoBack = false; + bool canGoBack = false; - bool exitOnBack = false; - Config->GetProperty("exitOnFirstPageBack", exitOnBack); - exit = false; + bool exitOnBack = false; + Config->GetProperty("exitOnFirstPageBack", exitOnBack); + exit = false; - if(PageChain.size() > 1) - { - page->Stop(); - canGoBack = true; - } - else if(PageChain.size() == 1 && exitOnBack) - { - page->Stop(); - exit = true; - canGoBack = true; - } + if(PageChain.size() > 1) + { + page->Stop(); + canGoBack = true; + } + else if(PageChain.size() == 1 && exitOnBack) + { + page->Stop(); + exit = true; + canGoBack = true; + } - return canGoBack; + return canGoBack; } RetroFE::RETROFE_STATE RetroFE::ProcessUserInput() { - SDL_Event e; - bool exit = false; - RETROFE_STATE state = RETROFE_IDLE; + SDL_Event e; + bool exit = false; + RETROFE_STATE state = RETROFE_IDLE; - if (SDL_PollEvent(&e) == 0) return state; + if (SDL_PollEvent(&e) == 0) return state; - if(e.type == SDL_KEYDOWN || e.type == SDL_KEYUP) - { - const Uint8 *keys = SDL_GetKeyboardState(NULL); + if(e.type == SDL_KEYDOWN || e.type == SDL_KEYUP) + { + const Uint8 *keys = SDL_GetKeyboardState(NULL); - InactiveKeyTime = 0; - AttractMode = false; + InactiveKeyTime = 0; + AttractMode = false; - if (keys[Input.GetScancode(UserInput::KeyCodePreviousItem)]) - { - page->SetScrolling(Page::ScrollDirectionBack); - } - if (keys[Input.GetScancode(UserInput::KeyCodeNextItem)]) - { - page->SetScrolling(Page::ScrollDirectionForward); - } - if (keys[Input.GetScancode(UserInput::KeyCodePageUp)]) - { - page->PageScroll(Page::ScrollDirectionBack); - } - if (keys[Input.GetScancode(UserInput::KeyCodePageDown)]) - { - page->PageScroll(Page::ScrollDirectionForward); - } - if (keys[Input.GetScancode(UserInput::KeyCodeAdminMode)]) - { - //todo: add admin mode support - } - if (keys[Input.GetScancode(UserInput::KeyCodeSelect)]) - { - NextPageItem = page->GetSelectedItem(); + if (keys[Input.GetScancode(UserInput::KeyCodePreviousItem)]) + { + page->SetScrolling(Page::ScrollDirectionBack); + } + if (keys[Input.GetScancode(UserInput::KeyCodeNextItem)]) + { + page->SetScrolling(Page::ScrollDirectionForward); + } + if (keys[Input.GetScancode(UserInput::KeyCodePageUp)]) + { + page->PageScroll(Page::ScrollDirectionBack); + } + if (keys[Input.GetScancode(UserInput::KeyCodePageDown)]) + { + page->PageScroll(Page::ScrollDirectionForward); + } + if (keys[Input.GetScancode(UserInput::KeyCodeAdminMode)]) + { + //todo: add admin mode support + } + if (keys[Input.GetScancode(UserInput::KeyCodeSelect)]) + { + NextPageItem = page->GetSelectedItem(); - if(NextPageItem) - { - state = (NextPageItem->IsLeaf()) ? RETROFE_LAUNCH_REQUEST : RETROFE_NEXT_PAGE_REQUEST; - } - } + if(NextPageItem) + { + state = (NextPageItem->IsLeaf()) ? RETROFE_LAUNCH_REQUEST : RETROFE_NEXT_PAGE_REQUEST; + } + } - if (keys[Input.GetScancode(UserInput::KeyCodeBack)]) - { - if(Back(exit)) - { - state = (exit) ? RETROFE_QUIT_REQUEST : RETROFE_BACK_REQUEST; - } - } + if (keys[Input.GetScancode(UserInput::KeyCodeBack)]) + { + if(Back(exit)) + { + state = (exit) ? RETROFE_QUIT_REQUEST : RETROFE_BACK_REQUEST; + } + } - if (keys[Input.GetScancode(UserInput::KeyCodeQuit)]) - { - state = RETROFE_QUIT_REQUEST; - } + if (keys[Input.GetScancode(UserInput::KeyCodeQuit)]) + { + state = RETROFE_QUIT_REQUEST; + } - if(!keys[Input.GetScancode(UserInput::KeyCodePreviousItem)] && - !keys[Input.GetScancode(UserInput::KeyCodeNextItem)] && - !keys[Input.GetScancode(UserInput::KeyCodePageUp)] && - !keys[Input.GetScancode(UserInput::KeyCodePageDown)]) - { - page->SetScrolling(Page::ScrollDirectionIdle); - } - } + if(!keys[Input.GetScancode(UserInput::KeyCodePreviousItem)] && + !keys[Input.GetScancode(UserInput::KeyCodeNextItem)] && + !keys[Input.GetScancode(UserInput::KeyCodePageUp)] && + !keys[Input.GetScancode(UserInput::KeyCodePageDown)]) + { + page->SetScrolling(Page::ScrollDirectionIdle); + } + } - return state; + return state; } Page *RetroFE::LoadPage(std::string collectionName) { - Logger::Write(Logger::ZONE_INFO, "RetroFE", "Creating page for collection " + collectionName); + Logger::Write(Logger::ZONE_INFO, "RetroFE", "Creating page for collection " + collectionName); - Page *page = NULL; - std::vector *collection = new std::vector(); // the page will deallocate this once its done - MenuParser mp; + Page *page = NULL; + std::vector *collection = new std::vector(); // the page will deallocate this once its done + MenuParser mp; - mp.GetMenuItems(CollectionDB, collectionName, *collection); - CollectionDB->GetCollection(collectionName, *collection); + mp.GetMenuItems(CollectionDB, collectionName, *collection); + CollectionDB->GetCollection(collectionName, *collection); - //todo: handle this in a more esthetically pleasing way instead of crashing - if(collection->size() == 0) - { - Logger::Write(Logger::ZONE_WARNING, "RetroFE", "No list items found for collection " + collectionName); - } - else - { - std::string layoutKeyName = "collections." + collectionName + ".layout"; - std::string layoutName = "Default 16x9"; + //todo: handle this in a more esthetically pleasing way instead of crashing + if(collection->size() == 0) + { + Logger::Write(Logger::ZONE_WARNING, "RetroFE", "No list items found for collection " + collectionName); + } + else + { + std::string layoutKeyName = "collections." + collectionName + ".layout"; + std::string layoutName = "Default 16x9"; - if(!Config->GetProperty(layoutKeyName, layoutName)) - { - Config->GetProperty("layout", layoutName); - } + if(!Config->GetProperty(layoutKeyName, layoutName)) + { + Config->GetProperty("layout", layoutName); + } - if(PageChain.size() > 0) - { - Page *oldPage = PageChain.back(); + if(PageChain.size() > 0) + { + Page *oldPage = PageChain.back(); - if(oldPage) - { - oldPage->FreeGraphicsMemory(); - } - } + if(oldPage) + { + oldPage->FreeGraphicsMemory(); + } + } - PageBuilder pb(layoutName, collectionName, Config, &FC); - page = pb.BuildPage(); - page->SetItems(collection); - page->Start(); + PageBuilder pb(layoutName, collectionName, Config, &FC); + page = pb.BuildPage(); + page->SetItems(collection); + page->Start(); - if(page) - { - PageChain.push_back(page); - } - } + if(page) + { + PageChain.push_back(page); + } + } - return page; + return page; } diff --git a/Source/RetroFE.h b/Source/RetroFE.h index 203da6d..a1d00e3 100644 --- a/Source/RetroFE.h +++ b/Source/RetroFE.h @@ -17,49 +17,49 @@ class Page; class RetroFE { public: - RetroFE(CollectionDatabase *db, Configuration *c); - virtual ~RetroFE(); - bool Initialize(); - bool DeInitialize(); - void Run(); - Configuration *GetConfiguration(); - void FreeGraphicsMemory(); - void AllocateGraphicsMemory(); - void LaunchEnter(); - void LaunchExit(); + RetroFE(CollectionDatabase *db, Configuration *c); + virtual ~RetroFE(); + bool Initialize(); + bool DeInitialize(); + void Run(); + Configuration *GetConfiguration(); + void FreeGraphicsMemory(); + void AllocateGraphicsMemory(); + void LaunchEnter(); + void LaunchExit(); private: - enum RETROFE_STATE - { - RETROFE_IDLE, - RETROFE_NEXT_PAGE_REQUEST, - RETROFE_NEXT_PAGE_WAIT, - RETROFE_LAUNCH_REQUEST, - RETROFE_BACK_REQUEST, - RETROFE_BACK_WAIT, - RETROFE_NEW, - RETROFE_QUIT_REQUEST, - RETROFE_QUIT, - }; + enum RETROFE_STATE + { + RETROFE_IDLE, + RETROFE_NEXT_PAGE_REQUEST, + RETROFE_NEXT_PAGE_WAIT, + RETROFE_LAUNCH_REQUEST, + RETROFE_BACK_REQUEST, + RETROFE_BACK_WAIT, + RETROFE_NEW, + RETROFE_QUIT_REQUEST, + RETROFE_QUIT, + }; - void Render(); - bool ItemSelected(); - bool Back(bool &exit); - void Quit(); - Page *LoadPage(std::string collectionName); - RETROFE_STATE ProcessUserInput(); - void Update(float dt, bool scrollActive); + void Render(); + bool ItemSelected(); + bool Back(bool &exit); + void Quit(); + Page *LoadPage(std::string collectionName); + RETROFE_STATE ProcessUserInput(); + void Update(float dt, bool scrollActive); - Configuration *Config; - CollectionDatabase *CollectionDB; - UserInput Input; - std::list PageChain; - float KeyInputDisable; - float InactiveKeyTime; - bool AttractMode; - float CurrentTime; - Item *NextPageItem; - FontCache FC; - IVideo *VideoInst; + Configuration *Config; + CollectionDatabase *CollectionDB; + UserInput Input; + std::list PageChain; + float KeyInputDisable; + float InactiveKeyTime; + bool AttractMode; + float CurrentTime; + Item *NextPageItem; + FontCache FC; + IVideo *VideoInst; }; diff --git a/Source/SDL.cpp b/Source/SDL.cpp index a056fc5..2304a84 100644 --- a/Source/SDL.cpp +++ b/Source/SDL.cpp @@ -1,6 +1,6 @@ /* This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. - */ + */ #include "SDL.h" #include "Database/Configuration.h" #include "Utility/Log.h" @@ -18,239 +18,239 @@ bool SDL::Fullscreen = false; bool SDL::Initialize(Configuration *config) { - bool retVal = true; - std::string hString; - std::string vString; - Uint32 windowFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_BORDERLESS; - int audioRate = MIX_DEFAULT_FREQUENCY; - Uint16 audioFormat = MIX_DEFAULT_FORMAT; /* 16-bit stereo */ - int audioChannels = 1; - int audioBuffers = 4096; - bool hideMouse; + bool retVal = true; + std::string hString; + std::string vString; + Uint32 windowFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_BORDERLESS; + int audioRate = MIX_DEFAULT_FREQUENCY; + Uint16 audioFormat = MIX_DEFAULT_FORMAT; /* 16-bit stereo */ + int audioChannels = 1; + int audioBuffers = 4096; + bool hideMouse; - Logger::Write(Logger::ZONE_DEBUG, "SDL", "Initializing"); - if (retVal && SDL_Init(SDL_INIT_EVERYTHING) != 0) - { - std::string error = SDL_GetError(); - Logger::Write(Logger::ZONE_ERROR, "SDL", "Initialize failed: " + error); - retVal = false; - } + Logger::Write(Logger::ZONE_DEBUG, "SDL", "Initializing"); + if (retVal && SDL_Init(SDL_INIT_EVERYTHING) != 0) + { + std::string error = SDL_GetError(); + Logger::Write(Logger::ZONE_ERROR, "SDL", "Initialize failed: " + error); + retVal = false; + } - if(retVal && config->GetProperty("hideMouse", hideMouse)) - { - if(hideMouse) - { - SDL_ShowCursor(SDL_FALSE); - } - else - { - SDL_ShowCursor(SDL_TRUE); - } - } + if(retVal && config->GetProperty("hideMouse", hideMouse)) + { + if(hideMouse) + { + SDL_ShowCursor(SDL_FALSE); + } + else + { + SDL_ShowCursor(SDL_TRUE); + } + } - // check for a few other necessary Configurations - if(retVal) - { - // Get current display mode of all displays. - for(int i = 0; i < SDL_GetNumVideoDisplays(); ++i) - { - SDL_DisplayMode mode; - if(SDL_GetCurrentDisplayMode(i, &mode) == 0) - { - DisplayWidth = mode.w; - DisplayHeight = mode.h; - break; - } - } - - - if(!config->GetProperty("horizontal", hString)) - { - Logger::Write(Logger::ZONE_ERROR, "Configuration", "Missing property \"horizontal\""); - retVal = false; - } - else if(hString == "stretch") - { - // Get current display mode of all displays. - for(int i = 0; i < SDL_GetNumVideoDisplays(); ++i) - { + // check for a few other necessary Configurations + if(retVal) + { + // Get current display mode of all displays. + for(int i = 0; i < SDL_GetNumVideoDisplays(); ++i) + { SDL_DisplayMode mode; if(SDL_GetCurrentDisplayMode(i, &mode) == 0) { - WindowWidth = mode.w; - break; + DisplayWidth = mode.w; + DisplayHeight = mode.h; + break; } - } - } - else if(!config->GetProperty("horizontal", WindowWidth)) - { - Logger::Write(Logger::ZONE_ERROR, "Configuration", "Invalid property value for \"horizontal\""); - } - } + } - // check for a few other necessary Configurations - if(retVal) - { - if(!config->GetProperty("vertical", hString)) - { - Logger::Write(Logger::ZONE_ERROR, "Configuration", "Missing property \"vertical\""); - retVal = false; - } - else if(hString == "stretch") - { - // Get current display mode of all displays. - for(int i = 0; i < SDL_GetNumVideoDisplays(); ++i) - { - SDL_DisplayMode mode; - if(SDL_GetDesktopDisplayMode(i, &mode) == 0) + + if(!config->GetProperty("horizontal", hString)) + { + Logger::Write(Logger::ZONE_ERROR, "Configuration", "Missing property \"horizontal\""); + retVal = false; + } + else if(hString == "stretch") + { + // Get current display mode of all displays. + for(int i = 0; i < SDL_GetNumVideoDisplays(); ++i) { - WindowHeight = mode.h; - break; + SDL_DisplayMode mode; + if(SDL_GetCurrentDisplayMode(i, &mode) == 0) + { + WindowWidth = mode.w; + break; + } } - } - } - else if(!config->GetProperty("vertical", WindowHeight)) - { - Logger::Write(Logger::ZONE_ERROR, "Configuration", "Invalid property value for \"vertical\""); - } - } + } + else if(!config->GetProperty("horizontal", WindowWidth)) + { + Logger::Write(Logger::ZONE_ERROR, "Configuration", "Invalid property value for \"horizontal\""); + } + } - if(retVal && !config->GetProperty("fullscreen", Fullscreen)) - { - Logger::Write(Logger::ZONE_ERROR, "Configuration", "Missing property: \"fullscreen\""); - retVal = false; - } + // check for a few other necessary Configurations + if(retVal) + { + if(!config->GetProperty("vertical", hString)) + { + Logger::Write(Logger::ZONE_ERROR, "Configuration", "Missing property \"vertical\""); + retVal = false; + } + else if(hString == "stretch") + { + // Get current display mode of all displays. + for(int i = 0; i < SDL_GetNumVideoDisplays(); ++i) + { + SDL_DisplayMode mode; + if(SDL_GetDesktopDisplayMode(i, &mode) == 0) + { + WindowHeight = mode.h; + break; + } + } + } + else if(!config->GetProperty("vertical", WindowHeight)) + { + Logger::Write(Logger::ZONE_ERROR, "Configuration", "Invalid property value for \"vertical\""); + } + } - if (retVal && Fullscreen) - { - windowFlags |= SDL_WINDOW_FULLSCREEN_DESKTOP; - } + if(retVal && !config->GetProperty("fullscreen", Fullscreen)) + { + Logger::Write(Logger::ZONE_ERROR, "Configuration", "Missing property: \"fullscreen\""); + retVal = false; + } - if(retVal) - { - std::stringstream ss; - ss << "Creating "<< WindowWidth << "x" << WindowHeight << " window (fullscreen: " << Fullscreen << ")"; - Logger::Write(Logger::ZONE_DEBUG, "SDL", ss.str()); + if (retVal && Fullscreen) + { + windowFlags |= SDL_WINDOW_FULLSCREEN_DESKTOP; + } - Window = SDL_CreateWindow("RetroFE", - SDL_WINDOWPOS_CENTERED, - SDL_WINDOWPOS_CENTERED, - WindowWidth, - WindowHeight, - windowFlags); + if(retVal) + { + std::stringstream ss; + ss << "Creating "<< WindowWidth << "x" << WindowHeight << " window (fullscreen: " << Fullscreen << ")"; + Logger::Write(Logger::ZONE_DEBUG, "SDL", ss.str()); - if (Window == NULL) - { - std::string error = SDL_GetError(); - Logger::Write(Logger::ZONE_ERROR, "SDL", "Create window failed: " + error); - retVal = false; - } - } + Window = SDL_CreateWindow("RetroFE", + SDL_WINDOWPOS_CENTERED, + SDL_WINDOWPOS_CENTERED, + WindowWidth, + WindowHeight, + windowFlags); - if(retVal) - { - Renderer = SDL_CreateRenderer(Window, - -1, - SDL_RENDERER_ACCELERATED); + if (Window == NULL) + { + std::string error = SDL_GetError(); + Logger::Write(Logger::ZONE_ERROR, "SDL", "Create window failed: " + error); + retVal = false; + } + } - if (Renderer == NULL) - { - std::string error = SDL_GetError(); - Logger::Write(Logger::ZONE_ERROR, "SDL", "Create renderer failed: " + error); - retVal = false; - } - } + if(retVal) + { + Renderer = SDL_CreateRenderer(Window, + -1, + SDL_RENDERER_ACCELERATED); - if(retVal) - { - Mutex = SDL_CreateMutex(); + if (Renderer == NULL) + { + std::string error = SDL_GetError(); + Logger::Write(Logger::ZONE_ERROR, "SDL", "Create renderer failed: " + error); + retVal = false; + } + } - if (Mutex == NULL) - { - std::string error = SDL_GetError(); - Logger::Write(Logger::ZONE_ERROR, "SDL", "Mutex creation failed: " + error); - retVal = false; - } - } + if(retVal) + { + Mutex = SDL_CreateMutex(); - //todo: specify in configuration file - if (retVal && Mix_OpenAudio(audioRate, audioFormat, audioChannels, audioBuffers) == -1) - { - std::string error = Mix_GetError(); - Logger::Write(Logger::ZONE_ERROR, "SDL", "Audio initialize failed: " + error); - retVal = false; - } + if (Mutex == NULL) + { + std::string error = SDL_GetError(); + Logger::Write(Logger::ZONE_ERROR, "SDL", "Mutex creation failed: " + error); + retVal = false; + } + } - return retVal; + //todo: specify in configuration file + if (retVal && Mix_OpenAudio(audioRate, audioFormat, audioChannels, audioBuffers) == -1) + { + std::string error = Mix_GetError(); + Logger::Write(Logger::ZONE_ERROR, "SDL", "Audio initialize failed: " + error); + retVal = false; + } + + return retVal; } bool SDL::DeInitialize() { - std::string error = SDL_GetError(); - Logger::Write(Logger::ZONE_DEBUG, "SDL", "DeInitializing"); + std::string error = SDL_GetError(); + Logger::Write(Logger::ZONE_DEBUG, "SDL", "DeInitializing"); - Mix_CloseAudio(); - Mix_Quit(); - if(Mutex) - { - SDL_DestroyMutex(Mutex); - Mutex = NULL; - } + Mix_CloseAudio(); + Mix_Quit(); + if(Mutex) + { + SDL_DestroyMutex(Mutex); + Mutex = NULL; + } - if(Renderer) - { - SDL_DestroyRenderer(Renderer); - Renderer = NULL; - } + if(Renderer) + { + SDL_DestroyRenderer(Renderer); + Renderer = NULL; + } - if(Window) - { - SDL_DestroyWindow(Window); - Window = NULL; - } + if(Window) + { + SDL_DestroyWindow(Window); + Window = NULL; + } - SDL_ShowCursor(SDL_TRUE); + SDL_ShowCursor(SDL_TRUE); - SDL_Quit(); + SDL_Quit(); - return true; + return true; } SDL_Renderer* SDL::GetRenderer() { - return Renderer; + return Renderer; } SDL_mutex* SDL::GetMutex() { - return Mutex; + return Mutex; } SDL_Window* SDL::GetWindow() { - return Window; + return Window; } bool SDL::RenderCopy(SDL_Texture *texture, unsigned char transparency, SDL_Rect *src, SDL_Rect *dest, double angle) { - SDL_Rect rotateRect; - rotateRect.w = dest->w; - rotateRect.h = dest->h; + SDL_Rect rotateRect; + rotateRect.w = dest->w; + rotateRect.h = dest->h; - if(Fullscreen) - { - rotateRect.x = dest->x + (DisplayWidth - WindowWidth)/2; - rotateRect.y = dest->y + (DisplayHeight - WindowHeight)/2; - } - else - { - rotateRect.x = dest->x; - rotateRect.y = dest->y; - } + if(Fullscreen) + { + rotateRect.x = dest->x + (DisplayWidth - WindowWidth)/2; + rotateRect.y = dest->y + (DisplayHeight - WindowHeight)/2; + } + else + { + rotateRect.x = dest->x; + rotateRect.y = dest->y; + } - SDL_SetTextureAlphaMod(texture, transparency); - SDL_RenderCopyEx(GetRenderer(), texture, src, &rotateRect, angle, NULL, SDL_FLIP_NONE); + SDL_SetTextureAlphaMod(texture, transparency); + SDL_RenderCopyEx(GetRenderer(), texture, src, &rotateRect, angle, NULL, SDL_FLIP_NONE); - return true; + return true; } diff --git a/Source/SDL.h b/Source/SDL.h index 5545c50..cb78cb0 100644 --- a/Source/SDL.h +++ b/Source/SDL.h @@ -1,6 +1,6 @@ /* This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. - */ + */ #pragma once #include @@ -10,23 +10,32 @@ class Configuration; class SDL { public: - static bool Initialize(Configuration *config); - static bool DeInitialize(); - static SDL_Renderer *GetRenderer(); - static SDL_mutex *GetMutex(); - static SDL_Window *GetWindow(); - static bool RenderCopy(SDL_Texture *texture, unsigned char transparency, SDL_Rect *src, SDL_Rect *dest, double angle); - static int GetWindowWidth() { return WindowWidth; } - static int GetWindowHeight() { return WindowHeight; } - static bool IsFullscreen() { return Fullscreen; } + static bool Initialize(Configuration *config); + static bool DeInitialize(); + static SDL_Renderer *GetRenderer(); + static SDL_mutex *GetMutex(); + static SDL_Window *GetWindow(); + static bool RenderCopy(SDL_Texture *texture, unsigned char transparency, SDL_Rect *src, SDL_Rect *dest, double angle); + static int GetWindowWidth() + { + return WindowWidth; + } + static int GetWindowHeight() + { + return WindowHeight; + } + static bool IsFullscreen() + { + return Fullscreen; + } private: - static SDL_Window *Window; - static SDL_Renderer *Renderer; - static SDL_mutex *Mutex; - static int DisplayWidth; - static int DisplayHeight; - static int WindowWidth; - static int WindowHeight; - static bool Fullscreen; + static SDL_Window *Window; + static SDL_Renderer *Renderer; + static SDL_mutex *Mutex; + static int DisplayWidth; + static int DisplayHeight; + static int WindowWidth; + static int WindowHeight; + static bool Fullscreen; }; diff --git a/Source/Sound/Sound.cpp b/Source/Sound/Sound.cpp index ca1775e..35ed47c 100644 --- a/Source/Sound/Sound.cpp +++ b/Source/Sound/Sound.cpp @@ -1,54 +1,54 @@ /* This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. - */ + */ #include "Sound.h" #include "../Utility/Log.h" Sound::Sound(std::string file) -: File(file) -, Chunk(NULL) + : File(file) + , Chunk(NULL) { - if(!Allocate()) - { - Logger::Write(Logger::ZONE_ERROR, "Sound", "Cannot load " + File); - } + if(!Allocate()) + { + Logger::Write(Logger::ZONE_ERROR, "Sound", "Cannot load " + File); + } } Sound::~Sound() { - if(Chunk) - { - Mix_FreeChunk(Chunk); - Chunk = NULL; - } + if(Chunk) + { + Mix_FreeChunk(Chunk); + Chunk = NULL; + } } void Sound::Play() { - if(Chunk) - { - (void)Mix_PlayChannel(-1, Chunk, 0); - } + if(Chunk) + { + (void)Mix_PlayChannel(-1, Chunk, 0); + } } bool Sound::Free() { - if(Chunk) - { - Mix_FreeChunk(Chunk); - Chunk = NULL; - } + if(Chunk) + { + Mix_FreeChunk(Chunk); + Chunk = NULL; + } - return true; + return true; } bool Sound::Allocate() { - if(!Chunk) - { - Chunk = Mix_LoadWAV(File.c_str()); - } + if(!Chunk) + { + Chunk = Mix_LoadWAV(File.c_str()); + } - return (Chunk != NULL); + return (Chunk != NULL); } diff --git a/Source/Sound/Sound.h b/Source/Sound/Sound.h index d96e7b9..17b75fb 100644 --- a/Source/Sound/Sound.h +++ b/Source/Sound/Sound.h @@ -1,6 +1,6 @@ /* This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. - */ + */ #pragma once #include @@ -8,12 +8,12 @@ class Sound { public: - Sound(std::string file); - virtual ~Sound(); - void Play(); - bool Allocate(); - bool Free(); + Sound(std::string file); + virtual ~Sound(); + void Play(); + bool Allocate(); + bool Free(); private: - std::string File; - Mix_Chunk *Chunk; + std::string File; + Mix_Chunk *Chunk; }; diff --git a/Source/Utility/Log.cpp b/Source/Utility/Log.cpp index b03a963..8621529 100644 --- a/Source/Utility/Log.cpp +++ b/Source/Utility/Log.cpp @@ -1,5 +1,5 @@ -/* This file is subject to the terms and conditions defined in - * file 'LICENSE.txt', which is part of this source code package. +/* This file is subject to the terms and conditions defined in + * file 'LICENSE.txt', which is part of this source code package. */ #include "Log.h" #include @@ -12,53 +12,53 @@ std::streambuf *Logger::CoutStream = NULL; bool Logger::Initialize(std::string file) { - WriteFileStream.open(file.c_str()); + WriteFileStream.open(file.c_str()); - CerrStream = std::cerr.rdbuf(WriteFileStream.rdbuf()); - CoutStream = std::cout.rdbuf(WriteFileStream.rdbuf()); + CerrStream = std::cerr.rdbuf(WriteFileStream.rdbuf()); + CoutStream = std::cout.rdbuf(WriteFileStream.rdbuf()); - return WriteFileStream.is_open(); + return WriteFileStream.is_open(); } void Logger::DeInitialize() { - if(WriteFileStream.is_open()) - { - WriteFileStream.close(); + if(WriteFileStream.is_open()) + { + WriteFileStream.close(); - } + } - std::cerr.rdbuf(CerrStream); - std::cout.rdbuf(CoutStream); + std::cerr.rdbuf(CerrStream); + std::cout.rdbuf(CoutStream); } void Logger::Write(Zone zone, std::string component, std::string message) { - std::string zoneStr; + std::string zoneStr; - switch(zone) - { - case ZONE_INFO: - zoneStr = "INFO"; - break; - case ZONE_DEBUG: - zoneStr = "DEBUG"; - break; - case ZONE_WARNING: - zoneStr = "WARNING"; - break; - case ZONE_ERROR: - zoneStr = "ERROR"; - break; - } - std::time_t rawtime = std::time(NULL); - struct tm* timeinfo = std::localtime(&rawtime); + switch(zone) + { + case ZONE_INFO: + zoneStr = "INFO"; + break; + case ZONE_DEBUG: + zoneStr = "DEBUG"; + break; + case ZONE_WARNING: + zoneStr = "WARNING"; + break; + case ZONE_ERROR: + zoneStr = "ERROR"; + break; + } + std::time_t rawtime = std::time(NULL); + struct tm* timeinfo = std::localtime(&rawtime); - static char timeStr[60]; - std::strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", timeinfo); + static char timeStr[60]; + std::strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", timeinfo); - std::stringstream ss; - ss << "[" << timeStr << "] [" << zoneStr << "] [" << component << "] " << message << std::endl; - std::cout << ss.str(); + std::stringstream ss; + ss << "[" << timeStr << "] [" << zoneStr << "] [" << component << "] " << message << std::endl; + std::cout << ss.str(); } diff --git a/Source/Utility/Log.h b/Source/Utility/Log.h index 2828f86..3cecb3d 100644 --- a/Source/Utility/Log.h +++ b/Source/Utility/Log.h @@ -1,5 +1,5 @@ -/* This file is subject to the terms and conditions defined in - * file 'LICENSE.txt', which is part of this source code package. +/* This file is subject to the terms and conditions defined in + * file 'LICENSE.txt', which is part of this source code package. */ #pragma once @@ -12,20 +12,20 @@ class Logger { public: - enum Zone - { - ZONE_DEBUG, - ZONE_INFO, - ZONE_WARNING, - ZONE_ERROR + enum Zone + { + ZONE_DEBUG, + ZONE_INFO, + ZONE_WARNING, + ZONE_ERROR - }; - static bool Initialize(std::string file); - static void Write(Zone zone, std::string component, std::string message); - static void DeInitialize(); + }; + static bool Initialize(std::string file); + static void Write(Zone zone, std::string component, std::string message); + static void DeInitialize(); private: - static std::streambuf *CerrStream; - static std::streambuf *CoutStream; - static std::ofstream WriteFileStream; + static std::streambuf *CerrStream; + static std::streambuf *CoutStream; + static std::ofstream WriteFileStream; }; diff --git a/Source/Utility/Utils.cpp b/Source/Utility/Utils.cpp index 4fba56d..b358eba 100644 --- a/Source/Utility/Utils.cpp +++ b/Source/Utility/Utils.cpp @@ -20,112 +20,112 @@ Utils::~Utils() bool Utils::FindMatchingFile(std::string prefix, std::vector &extensions, std::string &file) { - for(unsigned int i = 0; i < extensions.size(); ++i) - { - std::string temp = prefix + "." + extensions[i]; - temp = Configuration::ConvertToAbsolutePath(Configuration::GetAbsolutePath(), temp); + for(unsigned int i = 0; i < extensions.size(); ++i) + { + std::string temp = prefix + "." + extensions[i]; + temp = Configuration::ConvertToAbsolutePath(Configuration::GetAbsolutePath(), temp); - std::ifstream f(temp.c_str()); + std::ifstream f(temp.c_str()); - if (f.good()) - { - file = temp; - return true; - } - } + if (f.good()) + { + file = temp; + return true; + } + } - return false; + return false; } std::string Utils::Replace( - std::string subject, - const std::string& search, - const std::string& replace) + std::string subject, + const std::string& search, + const std::string& replace) { - size_t pos = 0; - while ((pos = subject.find(search, pos)) != std::string::npos) - { - subject.replace(pos, search.length(), replace); - pos += replace.length(); - } - return subject; + size_t pos = 0; + while ((pos = subject.find(search, pos)) != std::string::npos) + { + subject.replace(pos, search.length(), replace); + pos += replace.length(); + } + return subject; } float Utils::ConvertFloat(std::string content) { - float retVal = 0; - std::stringstream ss; - ss << content; - ss >> retVal; + float retVal = 0; + std::stringstream ss; + ss << content; + ss >> retVal; - return retVal; + return retVal; } int Utils::ConvertInt(std::string content) { - int retVal = 0; - std::stringstream ss; - ss << content; - ss >> retVal; + int retVal = 0; + std::stringstream ss; + ss << content; + ss >> retVal; - return retVal; + return retVal; } void Utils::NormalizeBackSlashes(std::string& content) { - std::replace(content.begin(), content.end(), '\\', '/'); + std::replace(content.begin(), content.end(), '\\', '/'); } std::string Utils::GetDirectory(std::string filePath) { - NormalizeBackSlashes(filePath); - std::string directory = filePath; + NormalizeBackSlashes(filePath); + std::string directory = filePath; - const size_t last_slash_idx = filePath.rfind('/'); - if (std::string::npos != last_slash_idx) - { - directory = filePath.substr(0, last_slash_idx); - } + const size_t last_slash_idx = filePath.rfind('/'); + if (std::string::npos != last_slash_idx) + { + directory = filePath.substr(0, last_slash_idx); + } - return directory; + return directory; } std::string Utils::GetParentDirectory(std::string directory) { - NormalizeBackSlashes(directory); + NormalizeBackSlashes(directory); - size_t last_slash_idx = directory.find_last_of('/'); - if(directory.length() - 1 == last_slash_idx) - { - directory = directory.erase(last_slash_idx, directory.length()-1); - last_slash_idx = directory.find_last_of('/'); - } + size_t last_slash_idx = directory.find_last_of('/'); + if(directory.length() - 1 == last_slash_idx) + { + directory = directory.erase(last_slash_idx, directory.length()-1); + last_slash_idx = directory.find_last_of('/'); + } - if (std::string::npos != last_slash_idx) - { - directory = directory.erase(last_slash_idx, directory.length()); - } + if (std::string::npos != last_slash_idx) + { + directory = directory.erase(last_slash_idx, directory.length()); + } - return directory; + return directory; } std::string Utils::GetFileName(std::string filePath) { - NormalizeBackSlashes(filePath); - std::string filename = filePath; + NormalizeBackSlashes(filePath); + std::string filename = filePath; - const size_t last_slash_idx = filePath.rfind('/'); - if (std::string::npos != last_slash_idx) - { - filename = filePath.erase(0, last_slash_idx+1); - } + const size_t last_slash_idx = filePath.rfind('/'); + if (std::string::npos != last_slash_idx) + { + filename = filePath.erase(0, last_slash_idx+1); + } - return filename; + return filename; } diff --git a/Source/Utility/Utils.h b/Source/Utility/Utils.h index f503a0d..7917ed4 100644 --- a/Source/Utility/Utils.h +++ b/Source/Utility/Utils.h @@ -9,18 +9,18 @@ class Utils { public: - static std::string Replace(std::string subject, const std::string& search, - const std::string& replace); + static std::string Replace(std::string subject, const std::string& search, + const std::string& replace); - static float ConvertFloat(std::string content); - static int ConvertInt(std::string content); - static void NormalizeBackSlashes(std::string &content); - static std::string GetDirectory(std::string filePath); - static std::string GetParentDirectory(std::string filePath); - static std::string GetFileName(std::string filePath); - static bool FindMatchingFile(std::string prefix, std::vector &extensions, std::string &file); + static float ConvertFloat(std::string content); + static int ConvertInt(std::string content); + static void NormalizeBackSlashes(std::string &content); + static std::string GetDirectory(std::string filePath); + static std::string GetParentDirectory(std::string filePath); + static std::string GetFileName(std::string filePath); + static bool FindMatchingFile(std::string prefix, std::vector &extensions, std::string &file); private: - Utils(); - virtual ~Utils(); + Utils(); + virtual ~Utils(); }; diff --git a/Source/Version.cpp b/Source/Version.cpp index 1c78a8f..a435949 100644 --- a/Source/Version.cpp +++ b/Source/Version.cpp @@ -22,16 +22,16 @@ std::string Version::GetString() { - std::stringstream version; - version << RETROFE_VERSION_MAJOR; - version << "."; - version << RETROFE_VERSION_MINOR; - version << "."; - version << RETROFE_VERSION_BUILD; + std::stringstream version; + version << RETROFE_VERSION_MAJOR; + version << "."; + version << RETROFE_VERSION_MINOR; + version << "."; + version << RETROFE_VERSION_BUILD; #ifdef RETROFE_VERSION_BETA - version << "-beta"; + version << "-beta"; #endif - return version.str(); + return version.str(); } diff --git a/Source/Version.h b/Source/Version.h index f3cb1fc..55000fc 100644 --- a/Source/Version.h +++ b/Source/Version.h @@ -1,6 +1,6 @@ /* This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. - */ + */ #pragma once #include @@ -8,5 +8,5 @@ class Version { public: - static std::string GetString(); + static std::string GetString(); }; diff --git a/Source/Video/GStreamerVideo.cpp b/Source/Video/GStreamerVideo.cpp index 25a8c48..74ce0a5 100644 --- a/Source/Video/GStreamerVideo.cpp +++ b/Source/Video/GStreamerVideo.cpp @@ -23,329 +23,329 @@ bool GStreamerVideo::Initialized = false; // MUST match video size gboolean GStreamerVideo::BusCallback(GstBus *bus, GstMessage *msg, gpointer data) { - // this callback only needs to be defined so we can loop the video once it completes - return TRUE; + // this callback only needs to be defined so we can loop the video once it completes + return TRUE; } GStreamerVideo::GStreamerVideo() -: Playbin(NULL) -, VideoBin(NULL) -, VideoSink(NULL) -, VideoConvert(NULL) -, VideoConvertCaps(NULL) -, VideoBus(NULL) -, Texture(NULL) -, Height(0) -, Width(0) -, VideoBuffer(NULL) -, FrameReady(false) -, IsPlaying(false) -, PlayCount(0) -, NumLoops(0) + : Playbin(NULL) + , VideoBin(NULL) + , VideoSink(NULL) + , VideoConvert(NULL) + , VideoConvertCaps(NULL) + , VideoBus(NULL) + , Texture(NULL) + , Height(0) + , Width(0) + , VideoBuffer(NULL) + , FrameReady(false) + , IsPlaying(false) + , PlayCount(0) + , NumLoops(0) { } GStreamerVideo::~GStreamerVideo() { - Stop(); + Stop(); } void GStreamerVideo::SetNumLoops(int n) { - NumLoops = n; + NumLoops = n; } SDL_Texture *GStreamerVideo::GetTexture() const { - return Texture; + return Texture; } void GStreamerVideo::ProcessNewBuffer (GstElement *fakesink, GstBuffer *buf, GstPad *new_pad, gpointer userdata) { - GStreamerVideo *video = (GStreamerVideo *)userdata; - GstMapInfo map; - SDL_LockMutex(SDL::GetMutex()); + GStreamerVideo *video = (GStreamerVideo *)userdata; + GstMapInfo map; + SDL_LockMutex(SDL::GetMutex()); - if (!video->FrameReady && video && video->IsPlaying && gst_buffer_map (buf, &map, GST_MAP_READ)) - { - if(!video->Width || !video->Height) - { - GstCaps *caps = gst_pad_get_current_caps (new_pad); - GstStructure *s = gst_caps_get_structure(caps, 0); + if (!video->FrameReady && video && video->IsPlaying && gst_buffer_map (buf, &map, GST_MAP_READ)) + { + if(!video->Width || !video->Height) + { + GstCaps *caps = gst_pad_get_current_caps (new_pad); + GstStructure *s = gst_caps_get_structure(caps, 0); - gst_structure_get_int(s, "width", &video->Width); - gst_structure_get_int(s, "height", &video->Height); - } + gst_structure_get_int(s, "width", &video->Width); + gst_structure_get_int(s, "height", &video->Height); + } - if(video->Height && video->Width) - { - if(!video->VideoBuffer) - { - video->VideoBuffer = new char[map.size]; - } - memcpy(video->VideoBuffer, map.data, map.size); - gst_buffer_unmap(buf, &map); - video->FrameReady = true; - } - } - SDL_UnlockMutex(SDL::GetMutex()); + if(video->Height && video->Width) + { + if(!video->VideoBuffer) + { + video->VideoBuffer = new char[map.size]; + } + memcpy(video->VideoBuffer, map.data, map.size); + gst_buffer_unmap(buf, &map); + video->FrameReady = true; + } + } + SDL_UnlockMutex(SDL::GetMutex()); } bool GStreamerVideo::Initialize() { - bool retVal = true; + bool retVal = true; - std::string path = Configuration::GetAbsolutePath() + "/Core"; - gst_init(NULL, NULL); - GstRegistry *registry = gst_registry_get(); - gst_registry_scan_path(registry, path.c_str()); + std::string path = Configuration::GetAbsolutePath() + "/Core"; + gst_init(NULL, NULL); + GstRegistry *registry = gst_registry_get(); + gst_registry_scan_path(registry, path.c_str()); - Initialized = true; + Initialized = true; - return retVal; + return retVal; } bool GStreamerVideo::DeInitialize() { - gst_deinit(); - Initialized = false; - return true; + gst_deinit(); + Initialized = false; + return true; } bool GStreamerVideo::Stop() { - if(!Initialized) - { - return false; - } + if(!Initialized) + { + return false; + } - if(VideoSink) - { - g_object_set(G_OBJECT(VideoSink), "signal-handoffs", FALSE, NULL); - } + if(VideoSink) + { + g_object_set(G_OBJECT(VideoSink), "signal-handoffs", FALSE, NULL); + } - if(Playbin) - { - (void)gst_element_set_state(Playbin, GST_STATE_NULL); - } + if(Playbin) + { + (void)gst_element_set_state(Playbin, GST_STATE_NULL); + } - FreeElements(); + FreeElements(); - IsPlaying = false; + IsPlaying = false; - if(Texture) - { - SDL_DestroyTexture(Texture); - Texture = NULL; - } - IsPlaying = false; - Height = 0; - Width = 0; - FrameReady = false; + if(Texture) + { + SDL_DestroyTexture(Texture); + Texture = NULL; + } + IsPlaying = false; + Height = 0; + Width = 0; + FrameReady = false; - if(VideoBuffer) - { - delete VideoBuffer; - VideoBuffer = NULL; - } - return true; + if(VideoBuffer) + { + delete VideoBuffer; + VideoBuffer = NULL; + } + return true; } bool GStreamerVideo::Play(std::string file) { - PlayCount = 0; + PlayCount = 0; - if(!Initialized) - { - return false; - } + if(!Initialized) + { + return false; + } - CurrentFile = file; + CurrentFile = file; - const gchar *uriFile = gst_filename_to_uri (file.c_str(), NULL); - if(!uriFile) - { - return false; - } - else - { - Configuration::ConvertToAbsolutePath(Configuration::GetAbsolutePath(), file); - file = uriFile; + const gchar *uriFile = gst_filename_to_uri (file.c_str(), NULL); + if(!uriFile) + { + return false; + } + else + { + Configuration::ConvertToAbsolutePath(Configuration::GetAbsolutePath(), file); + file = uriFile; - // Pipeline = gst_pipeline_new("pipeline"); - Playbin = gst_element_factory_make("playbin", "player"); - VideoBin = gst_bin_new("SinkBin"); - VideoSink = gst_element_factory_make("fakesink", "video_sink"); - VideoConvert = gst_element_factory_make("capsfilter", "video_convert"); - VideoConvertCaps = gst_caps_from_string("video/x-raw,format=(string)YUY2"); - Height = 0; - Width = 0; - if(!Playbin) - { - Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not create playbin"); - FreeElements(); - return false; - } - if(!VideoSink) - { - Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not create video sink"); - FreeElements(); - return false; - } - if(!VideoConvert) - { - Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not create video converter"); - FreeElements(); - return false; - } - if(!VideoConvertCaps) - { - Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not create video caps"); - FreeElements(); - return false; - } + // Pipeline = gst_pipeline_new("pipeline"); + Playbin = gst_element_factory_make("playbin", "player"); + VideoBin = gst_bin_new("SinkBin"); + VideoSink = gst_element_factory_make("fakesink", "video_sink"); + VideoConvert = gst_element_factory_make("capsfilter", "video_convert"); + VideoConvertCaps = gst_caps_from_string("video/x-raw,format=(string)YUY2"); + Height = 0; + Width = 0; + if(!Playbin) + { + Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not create playbin"); + FreeElements(); + return false; + } + if(!VideoSink) + { + Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not create video sink"); + FreeElements(); + return false; + } + if(!VideoConvert) + { + Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not create video converter"); + FreeElements(); + return false; + } + if(!VideoConvertCaps) + { + Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not create video caps"); + FreeElements(); + return false; + } - gst_bin_add_many(GST_BIN(VideoBin), VideoConvert, VideoSink, NULL); - gst_element_link_filtered(VideoConvert, VideoSink, VideoConvertCaps); - GstPad *videoConvertSinkPad = gst_element_get_static_pad(VideoConvert, "sink"); + gst_bin_add_many(GST_BIN(VideoBin), VideoConvert, VideoSink, NULL); + gst_element_link_filtered(VideoConvert, VideoSink, VideoConvertCaps); + GstPad *videoConvertSinkPad = gst_element_get_static_pad(VideoConvert, "sink"); - if(!videoConvertSinkPad) - { - Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not get video convert sink pad"); - FreeElements(); - return false; - } + if(!videoConvertSinkPad) + { + Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not get video convert sink pad"); + FreeElements(); + return false; + } - g_object_set(G_OBJECT(VideoSink), "sync", TRUE, "qos", TRUE, NULL); + g_object_set(G_OBJECT(VideoSink), "sync", TRUE, "qos", TRUE, NULL); - GstPad *videoSinkPad = gst_ghost_pad_new("sink", videoConvertSinkPad); - if(!videoSinkPad) - { - Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not get video bin sink pad"); - FreeElements(); - gst_object_unref(videoConvertSinkPad); - videoConvertSinkPad = NULL; - return false; - } + GstPad *videoSinkPad = gst_ghost_pad_new("sink", videoConvertSinkPad); + if(!videoSinkPad) + { + Logger::Write(Logger::ZONE_DEBUG, "Video", "Could not get video bin sink pad"); + FreeElements(); + gst_object_unref(videoConvertSinkPad); + videoConvertSinkPad = NULL; + return false; + } - gst_element_add_pad(VideoBin, videoSinkPad); - gst_object_unref(videoConvertSinkPad); - videoConvertSinkPad = NULL; + gst_element_add_pad(VideoBin, videoSinkPad); + gst_object_unref(videoConvertSinkPad); + videoConvertSinkPad = NULL; - g_object_set(G_OBJECT(Playbin), "uri", file.c_str(), "video-sink", VideoBin, NULL); + g_object_set(G_OBJECT(Playbin), "uri", file.c_str(), "video-sink", VideoBin, NULL); - IsPlaying = true; + IsPlaying = true; - g_object_set(G_OBJECT(VideoSink), "signal-handoffs", TRUE, NULL); - g_signal_connect(VideoSink, "handoff", G_CALLBACK(ProcessNewBuffer), this); + g_object_set(G_OBJECT(VideoSink), "signal-handoffs", TRUE, NULL); + g_signal_connect(VideoSink, "handoff", G_CALLBACK(ProcessNewBuffer), this); - VideoBus = gst_pipeline_get_bus(GST_PIPELINE(Playbin)); - gst_bus_add_watch(VideoBus, &BusCallback, this); + VideoBus = gst_pipeline_get_bus(GST_PIPELINE(Playbin)); + gst_bus_add_watch(VideoBus, &BusCallback, this); - /* Start playing */ - GstStateChangeReturn playState = gst_element_set_state(GST_ELEMENT(Playbin), GST_STATE_PLAYING); - if (playState != GST_STATE_CHANGE_ASYNC) - { - IsPlaying = false; - std::stringstream ss; - ss << "Unable to set the pipeline to the playing state: "; - ss << playState; - Logger::Write(Logger::ZONE_ERROR, "Video", ss.str()); - FreeElements(); - return false; - } - } + /* Start playing */ + GstStateChangeReturn playState = gst_element_set_state(GST_ELEMENT(Playbin), GST_STATE_PLAYING); + if (playState != GST_STATE_CHANGE_ASYNC) + { + IsPlaying = false; + std::stringstream ss; + ss << "Unable to set the pipeline to the playing state: "; + ss << playState; + Logger::Write(Logger::ZONE_ERROR, "Video", ss.str()); + FreeElements(); + return false; + } + } - return true; + return true; } void GStreamerVideo::FreeElements() { - if(VideoBin) - { - gst_object_unref(VideoBin); - VideoBin = NULL; - } - if(VideoSink) - { - gst_object_unref(VideoSink); - VideoSink = NULL; - } - if(VideoConvert) - { - gst_object_unref(VideoConvert); - VideoConvert = NULL; - } - if(VideoConvertCaps) - { - gst_object_unref(VideoConvertCaps); - VideoConvertCaps = NULL; - } - if(Playbin) - { - gst_object_unref(Playbin); - Playbin = NULL; - } - + if(VideoBin) + { + gst_object_unref(VideoBin); + VideoBin = NULL; + } + if(VideoSink) + { + gst_object_unref(VideoSink); + VideoSink = NULL; + } + if(VideoConvert) + { + gst_object_unref(VideoConvert); + VideoConvert = NULL; + } + if(VideoConvertCaps) + { + gst_object_unref(VideoConvertCaps); + VideoConvertCaps = NULL; + } + if(Playbin) + { + gst_object_unref(Playbin); + Playbin = NULL; + } + } void GStreamerVideo::Draw() { - FrameReady = false; + FrameReady = false; } void GStreamerVideo::Update(float dt) { - SDL_LockMutex(SDL::GetMutex()); - if(!Texture && Width != 0 && Height != 0) - { - Texture = SDL_CreateTexture(SDL::GetRenderer(), SDL_PIXELFORMAT_YUY2, - SDL_TEXTUREACCESS_STREAMING, Width, Height); - SDL_SetTextureBlendMode(Texture, SDL_BLENDMODE_BLEND); - } + SDL_LockMutex(SDL::GetMutex()); + if(!Texture && Width != 0 && Height != 0) + { + Texture = SDL_CreateTexture(SDL::GetRenderer(), SDL_PIXELFORMAT_YUY2, + SDL_TEXTUREACCESS_STREAMING, Width, Height); + SDL_SetTextureBlendMode(Texture, SDL_BLENDMODE_BLEND); + } - if(VideoBuffer && FrameReady && Texture && Width && Height) - { - //todo: change to width of cap - void *pixels; - int pitch; - SDL_LockTexture(Texture, NULL, &pixels, &pitch); - memcpy(pixels, VideoBuffer, Width*Height*2); //todo: magic number - SDL_UnlockTexture(Texture); - } - SDL_UnlockMutex(SDL::GetMutex()); + if(VideoBuffer && FrameReady && Texture && Width && Height) + { + //todo: change to width of cap + void *pixels; + int pitch; + SDL_LockTexture(Texture, NULL, &pixels, &pitch); + memcpy(pixels, VideoBuffer, Width*Height*2); //todo: magic number + SDL_UnlockTexture(Texture); + } + SDL_UnlockMutex(SDL::GetMutex()); - if(VideoBus) - { - GstMessage *msg = gst_bus_pop(VideoBus); - if(msg) - { - if(GST_MESSAGE_TYPE(msg) == GST_MESSAGE_EOS) - { - Logger::Write(Logger::ZONE_ERROR, "Video", "EOS!"); - - PlayCount++; - - //todo: nesting hazard - // if number of loops is 0, set to infinite (todo: this is misleading, rename variable) - if(!NumLoops || NumLoops > PlayCount) + if(VideoBus) + { + GstMessage *msg = gst_bus_pop(VideoBus); + if(msg) + { + if(GST_MESSAGE_TYPE(msg) == GST_MESSAGE_EOS) { - gst_element_seek(Playbin, - 1.0, - GST_FORMAT_TIME, - GST_SEEK_FLAG_FLUSH, - GST_SEEK_TYPE_SET, - 0, - GST_SEEK_TYPE_NONE, - GST_CLOCK_TIME_NONE); - } - } + Logger::Write(Logger::ZONE_ERROR, "Video", "EOS!"); - gst_message_unref(msg); - } - } + PlayCount++; + + //todo: nesting hazard + // if number of loops is 0, set to infinite (todo: this is misleading, rename variable) + if(!NumLoops || NumLoops > PlayCount) + { + gst_element_seek(Playbin, + 1.0, + GST_FORMAT_TIME, + GST_SEEK_FLAG_FLUSH, + GST_SEEK_TYPE_SET, + 0, + GST_SEEK_TYPE_NONE, + GST_CLOCK_TIME_NONE); + } + } + + gst_message_unref(msg); + } + } } diff --git a/Source/Video/GStreamerVideo.h b/Source/Video/GStreamerVideo.h index 521e465..80ff89e 100644 --- a/Source/Video/GStreamerVideo.h +++ b/Source/Video/GStreamerVideo.h @@ -15,36 +15,36 @@ extern "C" class GStreamerVideo : public IVideo { public: - GStreamerVideo(); - ~GStreamerVideo(); - bool Initialize(); - bool Play(std::string file); - bool Stop(); - bool DeInitialize(); - SDL_Texture *GetTexture() const; - void Update(float dt); - void Draw(); - void SetNumLoops(int n); - void FreeElements(); + GStreamerVideo(); + ~GStreamerVideo(); + bool Initialize(); + bool Play(std::string file); + bool Stop(); + bool DeInitialize(); + SDL_Texture *GetTexture() const; + void Update(float dt); + void Draw(); + void SetNumLoops(int n); + void FreeElements(); private: - static void ProcessNewBuffer (GstElement *fakesink, GstBuffer *buf, GstPad *pad, gpointer data); - static gboolean BusCallback(GstBus *bus, GstMessage *msg, gpointer data); + static void ProcessNewBuffer (GstElement *fakesink, GstBuffer *buf, GstPad *pad, gpointer data); + static gboolean BusCallback(GstBus *bus, GstMessage *msg, gpointer data); - GstElement *Playbin; - GstElement *VideoBin; - GstElement *VideoSink; - GstElement *VideoConvert; - GstCaps *VideoConvertCaps; - GstBus *VideoBus; - SDL_Texture* Texture; - gint Height; - gint Width; - char *VideoBuffer; - bool FrameReady; - bool IsPlaying; - static bool Initialized; - int PlayCount; - std::string CurrentFile; - int NumLoops; + GstElement *Playbin; + GstElement *VideoBin; + GstElement *VideoSink; + GstElement *VideoConvert; + GstCaps *VideoConvertCaps; + GstBus *VideoBus; + SDL_Texture* Texture; + gint Height; + gint Width; + char *VideoBuffer; + bool FrameReady; + bool IsPlaying; + static bool Initialized; + int PlayCount; + std::string CurrentFile; + int NumLoops; }; diff --git a/Source/Video/IVideo.h b/Source/Video/IVideo.h index 4490538..51bd449 100644 --- a/Source/Video/IVideo.h +++ b/Source/Video/IVideo.h @@ -9,12 +9,12 @@ class IVideo { public: - virtual ~IVideo() {} - virtual bool Initialize() = 0; - virtual bool Play(std::string file) = 0; - virtual bool Stop() = 0; - virtual bool DeInitialize() = 0; - virtual SDL_Texture *GetTexture() const = 0; - virtual void Update(float dt) = 0; - virtual void Draw() = 0; + virtual ~IVideo() {} + virtual bool Initialize() = 0; + virtual bool Play(std::string file) = 0; + virtual bool Stop() = 0; + virtual bool DeInitialize() = 0; + virtual SDL_Texture *GetTexture() const = 0; + virtual void Update(float dt) = 0; + virtual void Draw() = 0; }; diff --git a/Source/Video/VideoFactory.cpp b/Source/Video/VideoFactory.cpp index 7ae7da3..c8a188f 100644 --- a/Source/Video/VideoFactory.cpp +++ b/Source/Video/VideoFactory.cpp @@ -1,6 +1,6 @@ /* This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. - */ + */ #include "VideoFactory.h" #include "IVideo.h" #include "GStreamerVideo.h" @@ -10,24 +10,24 @@ int VideoFactory::NumLoops = 0; IVideo *VideoFactory::CreateVideo() { - IVideo *instance = NULL; + IVideo *instance = NULL; - if(Enabled) - { - instance = new GStreamerVideo(); - instance->Initialize(); - ((GStreamerVideo *)(instance))->SetNumLoops(NumLoops); - } + if(Enabled) + { + instance = new GStreamerVideo(); + instance->Initialize(); + ((GStreamerVideo *)(instance))->SetNumLoops(NumLoops); + } - return instance; + return instance; } void VideoFactory::SetEnabled(bool enabled) { - Enabled = enabled; + Enabled = enabled; } void VideoFactory::SetNumLoops(int numLoops) { - NumLoops = numLoops; + NumLoops = numLoops; } diff --git a/Source/Video/VideoFactory.h b/Source/Video/VideoFactory.h index 9ec47bf..39e3777 100644 --- a/Source/Video/VideoFactory.h +++ b/Source/Video/VideoFactory.h @@ -1,6 +1,6 @@ /* This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. - */ + */ #pragma once class IVideo; @@ -8,11 +8,11 @@ class IVideo; class VideoFactory { public: - IVideo *CreateVideo(); - static void SetEnabled(bool enabled); - static void SetNumLoops(int numLoops); + IVideo *CreateVideo(); + static void SetEnabled(bool enabled); + static void SetNumLoops(int numLoops); private: - static bool Enabled; - static int NumLoops; + static bool Enabled; + static int NumLoops; }; diff --git a/UnitTest/RetroFE/Utility/Utils_UnitTest.cpp b/UnitTest/RetroFE/Utility/Utils_UnitTest.cpp index 34abb15..2823164 100644 --- a/UnitTest/RetroFE/Utility/Utils_UnitTest.cpp +++ b/UnitTest/RetroFE/Utility/Utils_UnitTest.cpp @@ -2,11 +2,11 @@ #include "gmock/gmock.h" #include -class UtilsTest : public ::testing::Test +class UtilsTest : public ::testing::Test { }; -TEST_F(UtilsTest, ConvertsStringToInt) +TEST_F(UtilsTest, ConvertsStringToInt) { - ASSERT_EQ(5, Utils::ConvertInt("5")); + ASSERT_EQ(5, Utils::ConvertInt("5")); }