From 4591dbfee7ab8e93487ef056009ef470138dc600 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaakko=20Kera=CC=88nen?= Date: Fri, 29 Jun 2018 12:15:46 +0300 Subject: [PATCH] libdoomsday: Removing Qt dependencies; cleanup --- .../include/doomsday/abstractsession.h | 25 +- .../libdoomsday/include/doomsday/busymode.h | 4 +- .../include/doomsday/console/knownword.h | 2 +- .../include/doomsday/defs/dedfile.h | 4 +- .../include/doomsday/defs/dedregister.h | 4 +- .../include/doomsday/defs/sprite.h | 2 +- .../include/doomsday/doomsdayapp.h | 18 +- .../libdoomsday/include/doomsday/dualstring.h | 4 + .../include/doomsday/filesys/file.h | 7 +- .../include/doomsday/filesys/fileid.h | 17 +- .../include/doomsday/filesys/filetype.h | 20 +- .../include/doomsday/filesys/fs_main.h | 46 +-- .../include/doomsday/filesys/idgameslink.h | 2 +- .../include/doomsday/filesys/lumpindex.h | 8 +- .../include/doomsday/filesys/searchpath.h | 3 - .../include/doomsday/filesys/wad.h | 4 +- .../include/doomsday/filesys/zip.h | 4 +- .../apps/libdoomsday/include/doomsday/game.h | 6 +- .../include/doomsday/gameprofiles.h | 8 +- .../apps/libdoomsday/include/doomsday/games.h | 12 +- .../include/doomsday/libdoomsday.h | 5 +- .../libdoomsday/include/doomsday/library.h | 2 +- .../libdoomsday/include/doomsday/plugins.h | 2 +- .../include/doomsday/resource/animgroup.h | 6 +- .../include/doomsday/resource/bundles.h | 2 +- .../include/doomsday/resource/colorpalette.h | 12 +- .../include/doomsday/resource/composite.h | 36 +- .../include/doomsday/resource/databundle.h | 4 +- .../include/doomsday/resource/lumpcatalog.h | 10 +- .../include/doomsday/resource/lumpdirectory.h | 6 +- .../include/doomsday/resource/manifest.h | 9 +- .../include/doomsday/resource/resourceclass.h | 4 +- .../include/doomsday/resource/resources.h | 2 +- .../include/doomsday/resource/texture.h | 24 +- .../doomsday/resource/texturemanifest.h | 8 +- .../include/doomsday/resource/texturescheme.h | 2 +- .../apps/libdoomsday/include/doomsday/uri.h | 30 +- .../include/doomsday/world/material.h | 32 +- .../include/doomsday/world/materialmanifest.h | 5 +- .../include/doomsday/world/materials.h | 8 +- doomsday/apps/libdoomsday/src/busymode.cpp | 25 +- .../libdoomsday/src/c_wrapper/library.cpp | 15 +- .../apps/libdoomsday/src/console/alias.cpp | 11 +- doomsday/apps/libdoomsday/src/console/cmd.cpp | 18 +- .../apps/libdoomsday/src/console/exec.cpp | 23 +- .../libdoomsday/src/console/knownword.cpp | 39 +-- doomsday/apps/libdoomsday/src/console/var.cpp | 24 +- doomsday/apps/libdoomsday/src/defs/ded.cpp | 32 +- .../apps/libdoomsday/src/defs/dedfile.cpp | 10 +- .../apps/libdoomsday/src/defs/dedparser.cpp | 103 +++--- .../apps/libdoomsday/src/defs/dedregister.cpp | 33 +- .../apps/libdoomsday/src/defs/episode.cpp | 14 +- .../apps/libdoomsday/src/defs/mapinfo.cpp | 4 +- doomsday/apps/libdoomsday/src/defs/sprite.cpp | 8 +- doomsday/apps/libdoomsday/src/doomsdayapp.cpp | 112 +++--- doomsday/apps/libdoomsday/src/dualstring.cpp | 4 + .../libdoomsday/src/filesys/datafolder.cpp | 2 +- .../apps/libdoomsday/src/filesys/file.cpp | 2 +- .../apps/libdoomsday/src/filesys/fileid.cpp | 25 +- .../apps/libdoomsday/src/filesys/filetype.cpp | 8 +- .../apps/libdoomsday/src/filesys/fs_main.cpp | 134 ++++--- .../libdoomsday/src/filesys/fs_scheme.cpp | 47 ++- .../libdoomsday/src/filesys/idgameslink.cpp | 77 ++-- .../src/filesys/idgamespackageinfofile.cpp | 33 +- .../libdoomsday/src/filesys/lumpcache.cpp | 6 +- .../libdoomsday/src/filesys/lumpindex.cpp | 48 +-- .../apps/libdoomsday/src/filesys/readfile.cpp | 4 +- .../libdoomsday/src/filesys/searchpath.cpp | 4 +- .../src/filesys/virtualmappings.cpp | 2 +- doomsday/apps/libdoomsday/src/filesys/zip.cpp | 44 ++- doomsday/apps/libdoomsday/src/game.cpp | 88 ++--- doomsday/apps/libdoomsday/src/game_init.cpp | 11 +- .../apps/libdoomsday/src/gameprofiles.cpp | 39 ++- doomsday/apps/libdoomsday/src/games.cpp | 83 +++-- .../apps/libdoomsday/src/gamestatefolder.cpp | 94 ++--- doomsday/apps/libdoomsday/src/help.cpp | 67 ++-- doomsday/apps/libdoomsday/src/plugins.cpp | 42 +-- .../libdoomsday/src/resource/databundle.cpp | 329 +++++++++--------- .../src/resource/lumpdirectory.cpp | 23 +- .../libdoomsday/src/resource/manifest.cpp | 6 +- doomsday/apps/libdoomsday/src/savegames.cpp | 11 +- doomsday/apps/libdoomsday/src/uri.cpp | 123 +++---- doomsday/apps/libdoomsday/src/urivalue.cpp | 2 +- .../libdoomsday/src/world/entitydatabase.cpp | 15 +- .../libdoomsday/src/world/propertyvalue.cpp | 4 +- 85 files changed, 1066 insertions(+), 1191 deletions(-) diff --git a/doomsday/apps/libdoomsday/include/doomsday/abstractsession.h b/doomsday/apps/libdoomsday/include/doomsday/abstractsession.h index 984d8e28ee..29f477988e 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/abstractsession.h +++ b/doomsday/apps/libdoomsday/include/doomsday/abstractsession.h @@ -25,7 +25,7 @@ #include #include #include -#include +#include class GameStateFolder; @@ -95,29 +95,6 @@ class LIBDOOMSDAY_PUBLIC AbstractSession */ void setThinkerMapping(world::IThinkerMapping *mapping); -public: -// /** -// * Configuration profile. -// * @todo Remove this. Could just point to a GameProfile instead. -jk -// */ -// struct Profile -// { -// // Unique identifier of the game this profile is used with. -// de::String gameId; - -// // List of resource files (specified via the command line or in a cfg, or found using -// // the default search algorithm (e.g., /auto and DOOMWADDIR)). -// QStringList resourceFiles; -// }; - - /* - * Returns the current configuration profile for the game session. - */ -// static Profile &profile(); - - // Convenient method of looking up the game identity key from the game session profile. -// static de::String gameId() const; - protected: void setMapUri(de::Uri const &uri); void setInProgress(bool inProgress); diff --git a/doomsday/apps/libdoomsday/include/doomsday/busymode.h b/doomsday/apps/libdoomsday/include/doomsday/busymode.h index 4aba7c1e2d..93013009c2 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/busymode.h +++ b/doomsday/apps/libdoomsday/include/doomsday/busymode.h @@ -37,7 +37,7 @@ struct LIBDOOMSDAY_PUBLIC BusyTask void *workerData; ///< Data context for the worker thread. int mode; ///< Busy mode flags @ref busyModeFlags - char const *name; ///< Optional task name (drawn with the progress bar). + const char *name; ///< Optional task name (drawn with the progress bar). /// Used with task lists: int maxProgress; @@ -134,7 +134,7 @@ class LIBDOOMSDAY_PUBLIC BusyMode * * @return Return value from the worker. */ - int runNewTaskWithName(int mode, de::String const &taskName, std::function worker); + int runNewTaskWithName(int mode, de::String const &taskName, const std::function& worker); /** * Abnormally aborts the currently running task. Call this when the task encounters diff --git a/doomsday/apps/libdoomsday/include/doomsday/console/knownword.h b/doomsday/apps/libdoomsday/include/doomsday/console/knownword.h index 3aa358ebd2..7a9f0e6fb9 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/console/knownword.h +++ b/doomsday/apps/libdoomsday/include/doomsday/console/knownword.h @@ -103,7 +103,7 @@ LIBDOOMSDAY_PUBLIC knownword_t const **Con_CollectKnownWordsMatchingWord(char co LIBDOOMSDAY_PUBLIC AutoStr *Con_KnownWordToString(knownword_t const *word); -LIBDOOMSDAY_PUBLIC de::String Con_AnnotatedConsoleTerms(QStringList terms); +LIBDOOMSDAY_PUBLIC de::String Con_AnnotatedConsoleTerms(const de::StringList &terms); /** * Collects all the known words of the console into a Lexicon. diff --git a/doomsday/apps/libdoomsday/include/doomsday/defs/dedfile.h b/doomsday/apps/libdoomsday/include/doomsday/defs/dedfile.h index 4278f71506..5cb7f9e555 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/defs/dedfile.h +++ b/doomsday/apps/libdoomsday/include/doomsday/defs/dedfile.h @@ -26,7 +26,7 @@ #include "ded.h" #include -LIBDOOMSDAY_PUBLIC void Def_ReadProcessDED(ded_t *defs, de::String path); +LIBDOOMSDAY_PUBLIC void Def_ReadProcessDED(ded_t *defs, const de::String& path); /** * Reads definitions from the given lump. @@ -47,7 +47,7 @@ LIBDOOMSDAY_PUBLIC int DED_ReadData(ded_t *ded, char const *buffer, de::String s /** * @return @c true, if the file was successfully loaded. */ -int DED_Read(ded_t *ded, de::String path); +int DED_Read(ded_t *ded, const de::String& path); void DED_SetError(de::String const &message); diff --git a/doomsday/apps/libdoomsday/include/doomsday/defs/dedregister.h b/doomsday/apps/libdoomsday/include/doomsday/defs/dedregister.h index 41bffd5bbf..190501673a 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/defs/dedregister.h +++ b/doomsday/apps/libdoomsday/include/doomsday/defs/dedregister.h @@ -56,7 +56,7 @@ class LIBDOOMSDAY_PUBLIC DEDRegister DefaultLookup = 0 ///< Latest in order, case insensitive, omitted from copies. }; - Q_DECLARE_FLAGS(LookupFlags, LookupFlag) + using LookupFlags = de::Flags; public: DEDRegister(de::Record &names); @@ -104,7 +104,7 @@ class LIBDOOMSDAY_PUBLIC DEDRegister de::Record const & operator [] (int index) const; de::Record * tryFind(de::String const &key, de::String const &value); - de::Record const * tryFind(de::String const &key, de::String value) const; + de::Record const * tryFind(de::String const &key, de::String const &value) const; de::Record & find(de::String const &key, de::String const &value); de::Record const & find(de::String const &key, de::String const &value) const; diff --git a/doomsday/apps/libdoomsday/include/doomsday/defs/sprite.h b/doomsday/apps/libdoomsday/include/doomsday/defs/sprite.h index fa82b9993d..5ce7cc21c2 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/defs/sprite.h +++ b/doomsday/apps/libdoomsday/include/doomsday/defs/sprite.h @@ -42,7 +42,7 @@ struct LIBDOOMSDAY_PUBLIC CompiledSprite de::Uri uri; bool mirrorX = false; }; - QVector views; // missing ones have an empty Uri + de::List views; // missing ones have an empty Uri int viewCount = 0; // number of non-missing views CompiledSprite(); diff --git a/doomsday/apps/libdoomsday/include/doomsday/doomsdayapp.h b/doomsday/apps/libdoomsday/include/doomsday/doomsdayapp.h index 1ae0abad46..3ced57f968 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/doomsdayapp.h +++ b/doomsday/apps/libdoomsday/include/doomsday/doomsdayapp.h @@ -30,7 +30,6 @@ #include #include -#include #include namespace res { class Bundles; } @@ -98,7 +97,7 @@ class LIBDOOMSDAY_PUBLIC DoomsdayApp * Lists all the files found on the command line "-file" option (and its aliases). * @return List of files. */ - QList filesFromCommandLine() const; + de::List filesFromCommandLine() const; /** * Release all cached uncompressed entries. If the contents of the compressed @@ -111,12 +110,11 @@ class LIBDOOMSDAY_PUBLIC DoomsdayApp */ void clearCache(); - enum Behavior - { - AllowReload = 0x1, + enum Behavior { + AllowReload = 0x1, DefaultBehavior = 0, }; - Q_DECLARE_FLAGS(Behaviors, Behavior) + using Behaviors = de::Flags; /** * Switch to/activate the specified game. @@ -127,7 +125,7 @@ class LIBDOOMSDAY_PUBLIC DoomsdayApp * @param behaviors Change behavior flags. */ bool changeGame(GameProfile const &profile, - std::function gameActivationFunc, + const std::function &gameActivationFunc, Behaviors behaviors = DefaultBehavior); static bool isGameBeingChanged(); @@ -199,8 +197,8 @@ class LIBDOOMSDAY_PUBLIC DoomsdayApp static BusyMode & busyMode(); static SaveGames & saveGames(); - static de::NativePath steamBasePath(); - static QList gogComPaths(); + static de::NativePath steamBasePath(); + static de::List gogComPaths(); /** * Sets the currently active game. DoomsdayApp does not take ownership of @@ -256,6 +254,4 @@ class LIBDOOMSDAY_PUBLIC DoomsdayApp */ LIBDOOMSDAY_PUBLIC bool App_GameLoaded(); -Q_DECLARE_OPERATORS_FOR_FLAGS(DoomsdayApp::Behaviors) - #endif // LIBDOOMSDAY_DOOMSDAYAPP_H diff --git a/doomsday/apps/libdoomsday/include/doomsday/dualstring.h b/doomsday/apps/libdoomsday/include/doomsday/dualstring.h index 05f0d63b04..dc5bff65ba 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/dualstring.h +++ b/doomsday/apps/libdoomsday/include/doomsday/dualstring.h @@ -1,3 +1,5 @@ +#if 0 /* obsolete */ + /** * @file dualstring.h * Utility class for strings that need both Unicode and C-string access. @@ -114,3 +116,5 @@ class LIBDOOMSDAY_PUBLIC DualString : public de::String #endif // __cplusplus #endif // LIBDOOMSDAY_DUALSTRING_H + +#endif // 0 diff --git a/doomsday/apps/libdoomsday/include/doomsday/filesys/file.h b/doomsday/apps/libdoomsday/include/doomsday/filesys/file.h index 5b29ad52b7..a8fd12082c 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/filesys/file.h +++ b/doomsday/apps/libdoomsday/include/doomsday/filesys/file.h @@ -61,7 +61,6 @@ class LIBDOOMSDAY_PUBLIC File1 /// All resources are by default flagged as "custom". DefaultFlags = Custom }; - Q_DECLARE_FLAGS(Flags, Flag) /// This file is not contained. @ingroup errors DE_ERROR(NotContainedError); @@ -95,7 +94,7 @@ class LIBDOOMSDAY_PUBLIC File1 * * @return The composed URI. */ - virtual de::Uri composeUri(QChar delimiter = '/') const; + virtual de::Uri composeUri(Char delimiter = '/') const; /** * Compose the absolute VFS path to this file. @@ -106,7 +105,7 @@ class LIBDOOMSDAY_PUBLIC File1 * * @deprecated Prefer to use composeUri() instead. */ - String composePath(QChar delimiter = '/') const { + String composePath(Char delimiter = '/') const { return composeUri(delimiter).compose(); } @@ -270,8 +269,6 @@ class LIBDOOMSDAY_PUBLIC File1 uint order; }; -Q_DECLARE_OPERATORS_FOR_FLAGS(File1::Flags) - } // namespace de #endif /* DE_FILESYS_FILE_H */ diff --git a/doomsday/apps/libdoomsday/include/doomsday/filesys/fileid.h b/doomsday/apps/libdoomsday/include/doomsday/filesys/fileid.h index 9e2e9d8aef..49c7184182 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/filesys/fileid.h +++ b/doomsday/apps/libdoomsday/include/doomsday/filesys/fileid.h @@ -29,7 +29,7 @@ #define DE_FILEID_H #include "../libdoomsday.h" -#include +#include #include #include @@ -41,10 +41,10 @@ namespace de { class LIBDOOMSDAY_PUBLIC FileId : public LogEntry::Arg::Base { public: - typedef QByteArray Md5Hash; + typedef Block Md5Hash; public: - explicit FileId(Md5Hash _md5); + explicit FileId(const Md5Hash& _md5); FileId(FileId const& other); @@ -61,16 +61,9 @@ class LIBDOOMSDAY_PUBLIC FileId : public LogEntry::Arg::Base friend void swap(FileId& first, FileId& second) // nothrow { -#ifdef DE_QT_4_8_OR_NEWER - first.md5_.swap(second.md5_); -# ifdef DE_DEBUG - first.path_.swap(second.path_); -# endif -#else std::swap(first.md5_, second.md5_); -# ifdef DE_DEBUG +#ifdef DE_DEBUG std::swap(first.path_, second.path_); -# endif #endif } @@ -103,7 +96,7 @@ class LIBDOOMSDAY_PUBLIC FileId : public LogEntry::Arg::Base * @param path Path to be hashed. * @return Newly construced FileId. */ - static FileId fromPath(String path); + static FileId fromPath(const String& path); /** * Calculate an MD5 identifier for the absolute @a path. diff --git a/doomsday/apps/libdoomsday/include/doomsday/filesys/filetype.h b/doomsday/apps/libdoomsday/include/doomsday/filesys/filetype.h index 5444aef3d1..03f6e3e76f 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/filesys/filetype.h +++ b/doomsday/apps/libdoomsday/include/doomsday/filesys/filetype.h @@ -30,8 +30,8 @@ #ifdef __cplusplus #ifndef DE_C_API_ONLY -#include -#include +#include +#include #include #include #include @@ -50,7 +50,7 @@ namespace de class LIBDOOMSDAY_PUBLIC FileType { public: - FileType(String _name, resourceclassid_t _defaultClass) + FileType(const String& _name, resourceclassid_t _defaultClass) : name_(_name), defaultClass_(_defaultClass) {} @@ -75,7 +75,7 @@ namespace de * @param ext Extension to add (including period). * @return This instance. */ - FileType& addKnownExtension(String ext) + FileType& addKnownExtension(const String& ext) { knownFileNameExtensions_.push_back(ext); return *this; @@ -87,7 +87,7 @@ namespace de * * @return List of known extensions. */ - QStringList const& knownFileNameExtensions() const + StringList const& knownFileNameExtensions() const { return knownFileNameExtensions_; } @@ -98,13 +98,13 @@ namespace de * @param path File name/path to test. * @return @c true if matched. */ - bool fileNameIsKnown(String path) const + bool fileNameIsKnown(const String& path) const { // We require an extension for this. String ext = path.fileNameExtension(); if (!ext.isEmpty()) { - return knownFileNameExtensions_.contains(ext, Qt::CaseInsensitive); + return String::contains(knownFileNameExtensions_, ext, CaseInsensitive); } return false; } @@ -117,7 +117,7 @@ namespace de resourceclassid_t defaultClass_; /// List of known extensions for this file type. - QStringList knownFileNameExtensions_; + StringList knownFileNameExtensions_; }; /** @@ -143,7 +143,7 @@ namespace de class LIBDOOMSDAY_PUBLIC NativeFileType : public FileType { public: - NativeFileType(String name, resourceclassid_t rclassId) + NativeFileType(const String& name, resourceclassid_t rclassId) : FileType(name, rclassId) {} @@ -165,7 +165,7 @@ namespace de } /// Map of symbolic file type names to file types (not owned). - typedef QMap FileTypes; + typedef Map FileTypes; } // namespace de diff --git a/doomsday/apps/libdoomsday/include/doomsday/filesys/fs_main.h b/doomsday/apps/libdoomsday/include/doomsday/filesys/fs_main.h index 366e9794f3..3f3c12fce2 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/filesys/fs_main.h +++ b/doomsday/apps/libdoomsday/include/doomsday/filesys/fs_main.h @@ -51,16 +51,17 @@ #ifdef __cplusplus -#include -#include -#include -#include #include "fileinfo.h" #include "filetype.h" #include "searchpath.h" #include "../resource/resourceclass.h" #include "../filesys/lumpindex.h" +#include +#include +#include +#include + /** * @defgroup fs File System */ @@ -147,13 +148,12 @@ class LIBDOOMSDAY_PUBLIC FS1 /// @see mapPath() MappedInPackages = 0x01 }; - Q_DECLARE_FLAGS(Flags, Flag) /// Groups of search paths ordered by priority. - typedef QMultiMap SearchPaths; + typedef std::multimap SearchPaths; /// List of found file nodes. - typedef QList FoundNodes; + typedef de::List FoundNodes; public: explicit Scheme(String symbolicName, Flags flags = 0); @@ -204,7 +204,7 @@ class LIBDOOMSDAY_PUBLIC FS1 * * @return Number of found resources. */ - int findAll(String name, FoundNodes &found); + int findAll(const String& name, FoundNodes &found); /** * Add a new search path to this scheme. Newer paths have priority over @@ -260,7 +260,7 @@ class LIBDOOMSDAY_PUBLIC FS1 }; /// File system subspace schemes. - typedef QMap Schemes; + typedef Map Schemes; /** * PathListItem represents a found path for find file search results. @@ -281,10 +281,10 @@ class LIBDOOMSDAY_PUBLIC FS1 }; /// List of found path search results. - typedef QList PathList; + typedef List PathList; /// List of file search results. - typedef QList FileList; + typedef List FileList; public: /** @@ -306,19 +306,19 @@ class LIBDOOMSDAY_PUBLIC FS1 * @param name Symbolic name of the scheme. * @return Scheme associated with @a name. */ - Scheme &scheme(String name); + Scheme &scheme(const String& name); /** * @param name Unique symbolic name of the new scheme. Must be at least * @c Scheme::min_name_length characters long. * @param flags @ref Scheme::Flag */ - Scheme &createScheme(String name, Scheme::Flags flags = 0); + Scheme &createScheme(const String& name, Flags flags = 0); /** * Returns @c true iff a Scheme exists with the symbolic @a name. */ - bool knownScheme(String name); + bool knownScheme(const String& name); /** * Returns the schemes for efficient traversal. @@ -331,7 +331,7 @@ class LIBDOOMSDAY_PUBLIC FS1 */ inline void resetAllSchemes() { Schemes schemes = allSchemes(); - DE_FOR_EACH(Schemes, i, schemes){ (*i)->reset(); } + for (auto &i : schemes) { i.second->reset(); } } /** @@ -505,16 +505,18 @@ class LIBDOOMSDAY_PUBLIC FS1 { findAll(predicate, parameters, found); // Filter out the wrong types. - QMutableListIterator i(found); - while (i.hasNext()) + for (auto i = found.begin(); i != found.end(); ) { - i.next(); - if (!is(i.value()->file())) + if (!is((*i)->file())) + { + i = found.erase(i); + } + else { - i.remove(); + ++i; } } - return found.count(); + return found.sizei(); } /** @@ -578,8 +580,6 @@ class LIBDOOMSDAY_PUBLIC FS1 DE_PRIVATE(d) }; -Q_DECLARE_OPERATORS_FOR_FLAGS(FS1::Scheme::Flags) - } // namespace de LIBDOOMSDAY_PUBLIC de::FS1 &App_FileSystem(); diff --git a/doomsday/apps/libdoomsday/include/doomsday/filesys/idgameslink.h b/doomsday/apps/libdoomsday/include/doomsday/filesys/idgameslink.h index 8b3a6b7324..6a7e4901f1 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/filesys/idgameslink.h +++ b/doomsday/apps/libdoomsday/include/doomsday/filesys/idgameslink.h @@ -29,7 +29,7 @@ class IdgamesLink : public de::filesys::WebHostedLink de::File *populateRemotePath(de::String const &packageId, de::filesys::RepositoryPath const &path) const override; - void parseRepositoryIndex(QByteArray data) override; + void parseRepositoryIndex(const de::Block &data) override; de::StringList categoryTags() const override; diff --git a/doomsday/apps/libdoomsday/include/doomsday/filesys/lumpindex.h b/doomsday/apps/libdoomsday/include/doomsday/filesys/lumpindex.h index 8d5eedae67..f91062b4a2 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/filesys/lumpindex.h +++ b/doomsday/apps/libdoomsday/include/doomsday/filesys/lumpindex.h @@ -29,7 +29,9 @@ #include "file.h" #include "fileinfo.h" -#include +#include +#include +#include #include namespace de { @@ -47,7 +49,7 @@ class LIBDOOMSDAY_PUBLIC LumpIndex /// No file(s) found. @ingroup errors DE_ERROR(NotFoundError); - typedef QList Lumps; + typedef de::List Lumps; typedef std::list FoundIndices; /** @@ -103,7 +105,7 @@ class LIBDOOMSDAY_PUBLIC LumpIndex KnownDataCount }; - typedef QMap Lumps; + typedef Map Lumps; public: /** diff --git a/doomsday/apps/libdoomsday/include/doomsday/filesys/searchpath.h b/doomsday/apps/libdoomsday/include/doomsday/filesys/searchpath.h index 3137c1ac57..3d5cd42dac 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/filesys/searchpath.h +++ b/doomsday/apps/libdoomsday/include/doomsday/filesys/searchpath.h @@ -57,7 +57,6 @@ class LIBDOOMSDAY_PUBLIC SearchPath : public Uri /// Interpreters should not decend into branches. NoDescend = 0x1 }; - Q_DECLARE_FLAGS(Flags, Flag) public: /** @@ -101,8 +100,6 @@ class LIBDOOMSDAY_PUBLIC SearchPath : public Uri Flags flags_; }; -Q_DECLARE_OPERATORS_FOR_FLAGS(SearchPath::Flags) - } // namespace de namespace std { diff --git a/doomsday/apps/libdoomsday/include/doomsday/filesys/wad.h b/doomsday/apps/libdoomsday/include/doomsday/filesys/wad.h index 4fbf09a722..d4be2010fd 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/filesys/wad.h +++ b/doomsday/apps/libdoomsday/include/doomsday/filesys/wad.h @@ -70,7 +70,7 @@ class LIBDOOMSDAY_PUBLIC Wad : public File1, public LumpIndex * * @return The absolute URI. */ - Uri composeUri(QChar delimiter = '/') const; + Uri composeUri(Char delimiter = '/') const; /** * Retrieve the directory node for this file. @@ -221,7 +221,7 @@ class LIBDOOMSDAY_PUBLIC Wad : public File1, public LumpIndex { dint32 offset; dint32 size; - QScopedPointer lumpFile; ///< File system object for the lump data. + std::unique_ptr lumpFile; ///< File system object for the lump data. uint crc; ///< CRC for the lump data. Entry(PathTree::NodeArgs const &args) diff --git a/doomsday/apps/libdoomsday/include/doomsday/filesys/zip.h b/doomsday/apps/libdoomsday/include/doomsday/filesys/zip.h index 178c384509..0222c4cd32 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/filesys/zip.h +++ b/doomsday/apps/libdoomsday/include/doomsday/filesys/zip.h @@ -72,7 +72,7 @@ class LIBDOOMSDAY_PUBLIC Zip : public File1, public LumpIndex * * @return The absolute URI. */ - Uri composeUri(QChar delimiter = '/') const; + Uri composeUri(Char delimiter = '/') const; /** * Retrieve the directory node for this file. @@ -278,7 +278,7 @@ class LIBDOOMSDAY_PUBLIC Zip : public File1, public LumpIndex dsize offset; dsize size; dsize compressedSize; - QScopedPointer lumpFile; ///< File system object for the lump data. + std::unique_ptr lumpFile; ///< File system object for the lump data. Entry(PathTree::NodeArgs const &args) : Node(args), offset(0), size(0), compressedSize(0) diff --git a/doomsday/apps/libdoomsday/include/doomsday/game.h b/doomsday/apps/libdoomsday/include/doomsday/game.h index 556ba78ef1..9f07621f80 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/game.h +++ b/doomsday/apps/libdoomsday/include/doomsday/game.h @@ -30,7 +30,7 @@ #include #include #include -#include +#include class ResourceManifest; namespace de { class File1; } @@ -53,7 +53,7 @@ class LIBDOOMSDAY_PUBLIC Game : public de::IObject Incomplete }; - typedef QMultiMap Manifests; + typedef std::multimap Manifests; /** * Specifies the game that this game is a variant of. For instance, "Final @@ -99,7 +99,7 @@ class LIBDOOMSDAY_PUBLIC Game : public de::IObject * * @param packageIds List of package IDs. */ - void setRequiredPackages(de::StringList packageIds); + void setRequiredPackages(const de::StringList &packageIds); void addRequiredPackage(de::String const &packageId); diff --git a/doomsday/apps/libdoomsday/include/doomsday/gameprofiles.h b/doomsday/apps/libdoomsday/include/doomsday/gameprofiles.h index 765d082821..e13c0bcae8 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/gameprofiles.h +++ b/doomsday/apps/libdoomsday/include/doomsday/gameprofiles.h @@ -51,7 +51,7 @@ class LIBDOOMSDAY_PUBLIC GameProfiles : public de::Profiles void setGame(de::String const &id); void setCustomDataFile(const de::String &id); - void setPackages(de::StringList packagesInOrder); + void setPackages(const de::StringList& packagesInOrder); void setUserCreated(bool userCreated); void setUseGameRequirements(bool useGameRequirements); void setAutoStartMap(de::String const &map); @@ -130,9 +130,9 @@ class LIBDOOMSDAY_PUBLIC GameProfiles : public de::Profiles de::LoopResult forAll(std::function func); de::LoopResult forAll(std::function func) const; - QList allPlayableProfiles() const; - QList profilesInFamily(de::String const &family); - QList profilesSortedByFamily(); + de::List allPlayableProfiles() const; + de::List profilesInFamily(de::String const &family); + de::List profilesSortedByFamily(); static Profile const &null(); diff --git a/doomsday/apps/libdoomsday/include/doomsday/games.h b/doomsday/apps/libdoomsday/include/doomsday/games.h index 9ff425a75c..ef1bd837a7 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/games.h +++ b/doomsday/apps/libdoomsday/include/doomsday/games.h @@ -26,7 +26,7 @@ #include #include #include -#include +#include /** * Encapsulates a collection of Game instances and the logical operations @@ -46,7 +46,7 @@ class LIBDOOMSDAY_PUBLIC Games { Game *game; - GameListItem(Game *game = 0) : game(game) + GameListItem(Game *game = nullptr) : game(game) {} /// @return @c true= this game's title is lexically less than that of @a other. @@ -55,8 +55,8 @@ class LIBDOOMSDAY_PUBLIC Games } }; - typedef QList GameList; - typedef QList All; + typedef de::List GameList; + typedef de::List All; /// Notified when a new game is added. DE_DEFINE_AUDIENCE2(Addition, void gameAdded(Game &game)) @@ -76,7 +76,7 @@ class LIBDOOMSDAY_PUBLIC Games static Game &nullGame(); /// @return Total number of registered games. - inline int count() const { return all().count(); } + inline int count() const { return all().sizei(); } /// @return Number of games marked as currently playable. int numPlayable() const; @@ -120,7 +120,7 @@ class LIBDOOMSDAY_PUBLIC Games */ All const &all() const; - de::LoopResult forAll(std::function callback) const; + de::LoopResult forAll(const std::function& callback) const; /** * Notify observers to update the readiness of games. diff --git a/doomsday/apps/libdoomsday/include/doomsday/libdoomsday.h b/doomsday/apps/libdoomsday/include/doomsday/libdoomsday.h index 242f9a4268..f7e3b76a77 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/libdoomsday.h +++ b/doomsday/apps/libdoomsday/include/doomsday/libdoomsday.h @@ -19,6 +19,8 @@ #ifndef LIBDOOMSDAY_MAIN_H #define LIBDOOMSDAY_MAIN_H +#include + /** * @mainpage Doomsday Engine * @@ -41,8 +43,7 @@ # define LIBDOOMSDAY_PUBLIC __declspec(dllimport) # endif #else -// No need to use any special declarators. -# define LIBDOOMSDAY_PUBLIC +# define LIBDOOMSDAY_PUBLIC DE_PUBLIC #endif #ifdef __cplusplus diff --git a/doomsday/apps/libdoomsday/include/doomsday/library.h b/doomsday/apps/libdoomsday/include/doomsday/library.h index 1ca43ba6d0..d89a088426 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/library.h +++ b/doomsday/apps/libdoomsday/include/doomsday/library.h @@ -103,7 +103,7 @@ LIBDOOMSDAY_PUBLIC void *Library_Symbol(Library *lib, char const *symbolName); LIBDOOMSDAY_PUBLIC de::LibraryFile &Library_File(Library *lib); -LIBDOOMSDAY_PUBLIC de::LoopResult Library_ForAll(std::function func); +LIBDOOMSDAY_PUBLIC de::LoopResult Library_ForAll(const std::function& func); #endif #endif // LIBDOOMSDAY_LIBRARY_H diff --git a/doomsday/apps/libdoomsday/include/doomsday/plugins.h b/doomsday/apps/libdoomsday/include/doomsday/plugins.h index bdf46d44bf..98147ba75c 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/plugins.h +++ b/doomsday/apps/libdoomsday/include/doomsday/plugins.h @@ -364,7 +364,7 @@ class LIBDOOMSDAY_PUBLIC Plugins * * @see callAllHooks() */ - de::LoopResult forAllHooks(HookType type, std::function func) const; + de::LoopResult forAllHooks(HookType type, const std::function& func) const; /** * Convenient method of executing all hook functions of the given @a type in diff --git a/doomsday/apps/libdoomsday/include/doomsday/resource/animgroup.h b/doomsday/apps/libdoomsday/include/doomsday/resource/animgroup.h index c665bb7882..6c01da2231 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/resource/animgroup.h +++ b/doomsday/apps/libdoomsday/include/doomsday/resource/animgroup.h @@ -22,10 +22,12 @@ #define LIBDOOMSDAY_RESOURCE_ANIMATIONGROUP_H #include "../TextureManifest" -#include +#include namespace res { +using namespace de; + /** * Material Animation group. * @@ -65,7 +67,7 @@ class LIBDOOMSDAY_PUBLIC AnimGroup ushort _randomTics; }; - typedef QList Frames; + typedef List Frames; public: /** diff --git a/doomsday/apps/libdoomsday/include/doomsday/resource/bundles.h b/doomsday/apps/libdoomsday/include/doomsday/resource/bundles.h index ae0aaad802..ccd09d6a2e 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/resource/bundles.h +++ b/doomsday/apps/libdoomsday/include/doomsday/resource/bundles.h @@ -38,7 +38,7 @@ namespace res { class LIBDOOMSDAY_PUBLIC Bundles { public: - typedef QList BlockElements; + typedef de::List BlockElements; /// Notified when a data bundle refresh/identification has been completed. DE_DEFINE_AUDIENCE2(Identify, void dataBundlesIdentified()) diff --git a/doomsday/apps/libdoomsday/include/doomsday/resource/colorpalette.h b/doomsday/apps/libdoomsday/include/doomsday/resource/colorpalette.h index ba78f735ef..d7f86fa1dd 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/resource/colorpalette.h +++ b/doomsday/apps/libdoomsday/include/doomsday/resource/colorpalette.h @@ -26,8 +26,7 @@ #include #include #include - -#include +#include namespace res { @@ -53,8 +52,7 @@ class LIBDOOMSDAY_PUBLIC ColorTableReader * @param colorCount Number of discreet colors in @a colorData. * @param colorData Color data (at least @a colorCount * 3 values). */ - static QVector read(de::String format, int colorCount, - de::dbyte const *colorData); + static de::List read(de::String format, int colorCount, de::dbyte const *colorData); }; /** @@ -72,7 +70,7 @@ class LIBDOOMSDAY_PUBLIC ColorPalette DE_DEFINE_AUDIENCE(ColorTableChange, void colorPaletteColorTableChanged(ColorPalette &colorPalette)) /// Palette index translation mapping table. - typedef QVector Translation; + typedef de::List Translation; public: /** @@ -85,7 +83,7 @@ class LIBDOOMSDAY_PUBLIC ColorPalette * * @param colors Color table to initialize from. A copy is made. */ - ColorPalette(QVector const &colors); + ColorPalette(de::List const &colors); /// @see color() inline de::Vec3ub operator [] (int colorIndex) const { @@ -128,7 +126,7 @@ class LIBDOOMSDAY_PUBLIC ColorPalette * * @param colorTable The replacement color table. A copy is made. */ - ColorPalette &replaceColorTable(QVector const &colorTable); + ColorPalette &replaceColorTable(de::List const &colorTable); /** * Given an R8G8B8 color triplet return the closet matching color index. diff --git a/doomsday/apps/libdoomsday/include/doomsday/resource/composite.h b/doomsday/apps/libdoomsday/include/doomsday/resource/composite.h index 2649c7b9b0..778fe47f93 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/resource/composite.h +++ b/doomsday/apps/libdoomsday/include/doomsday/resource/composite.h @@ -23,8 +23,7 @@ #include "patchname.h" -#include -#include +#include #include #include @@ -34,6 +33,8 @@ namespace res { +using namespace de; + /** * A logical texture composite of one or more @em component images. * @@ -51,7 +52,6 @@ class LIBDOOMSDAY_PUBLIC Composite enum Flag { Custom = 0x1 ///< The texture does not originate from the current game. }; - Q_DECLARE_FLAGS(Flags, Flag) /** * Archived format variants. @@ -67,12 +67,12 @@ class LIBDOOMSDAY_PUBLIC Composite struct LIBDOOMSDAY_PUBLIC Component { public: - explicit Component(de::Vec2i const &origin = de::Vec2i()); + explicit Component(Vec2i const &origin = Vec2i()); - void setOrigin(de::Vec2i const &origin); + void setOrigin(Vec2i const &origin); /// Origin of the top left corner of the component (in texture space units). - de::Vec2i const &origin() const; + Vec2i const &origin() const; bool operator == (Component const &other) const; bool operator != (Component const &other) const; @@ -90,17 +90,17 @@ class LIBDOOMSDAY_PUBLIC Composite void setLumpNum(lumpnum_t num); private: - de::Vec2i _origin; ///< Top left corner in the texture coordinate space. + Vec2i _origin; ///< Top left corner in the texture coordinate space. lumpnum_t _lumpNum; ///< Index of the lump containing the associated image. }; - typedef QList Components; + typedef List Components; public: /** * Construct a default composite texture. */ - explicit Composite(de::String const &percentEncodedName = "", - de::Vec2ui const &logicalDimensions = de::Vec2ui(), + explicit Composite(String const &percentEncodedName = "", + Vec2ui const &logicalDimensions = Vec2ui(), Flags flags = 0); /** @@ -115,8 +115,8 @@ class LIBDOOMSDAY_PUBLIC Composite * * @return The deserialized composite texture. Caller gets ownership. */ - static Composite *constructFrom(de::Reader &reader, - QVector const &patchNames, + static Composite *constructFrom(Reader &reader, + const List &patchNames, ArchiveFormat format = DoomFormat); /** @@ -131,13 +131,13 @@ class LIBDOOMSDAY_PUBLIC Composite } /// Returns the percent-endcoded symbolic name of the texture. - de::String percentEncodedName() const; + String percentEncodedName() const; /// Returns the percent-endcoded symbolic name of the texture. - de::String const &percentEncodedNameRef() const; + String const &percentEncodedNameRef() const; /// Returns the logical dimensions of the texture (in map space units). - de::Vec2ui const &logicalDimensions() const; + Vec2ui const &logicalDimensions() const; /// Returns the logical width of the texture (in map space units). inline int logicalWidth() const { return int(logicalDimensions().x); } @@ -146,7 +146,7 @@ class LIBDOOMSDAY_PUBLIC Composite inline int logicalHeight() const { return int(logicalDimensions().y); } /// Returns the pixel dimensions of the texture. - de::Vec2ui const &dimensions() const; + Vec2ui const &dimensions() const; /// Returns the pixel width of the texture. inline int width() const { return int(dimensions().x); } @@ -184,14 +184,12 @@ class LIBDOOMSDAY_PUBLIC Composite * @param flagsToChange Flags to change the value of. * @param operation Logical operation to perform on the flags. */ - void setFlags(Flags flagsToChange, de::FlagOp operation = de::SetFlags); + void setFlags(Flags flagsToChange, FlagOp operation = SetFlags); private: DE_PRIVATE(d) }; -Q_DECLARE_OPERATORS_FOR_FLAGS(Composite::Flags) - typedef Composite::Component CompositeComponent; } // namespace res diff --git a/doomsday/apps/libdoomsday/include/doomsday/resource/databundle.h b/doomsday/apps/libdoomsday/include/doomsday/resource/databundle.h index e1ce67e5e9..bc6d409986 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/resource/databundle.h +++ b/doomsday/apps/libdoomsday/include/doomsday/resource/databundle.h @@ -173,7 +173,7 @@ class LIBDOOMSDAY_PUBLIC DataBundle : public de::IByteArray * * @return List of bundles. */ - static QList loadedBundles(); + static de::List loadedBundles(); /** * Finds all DataFile and DataFolder instances with a matching file name or @@ -186,7 +186,7 @@ class LIBDOOMSDAY_PUBLIC DataBundle : public de::IByteArray * * @return List of matching files. */ - static QList findAllNative(de::String const &fileNameOrPartialNativePath); + static de::List findAllNative(de::String const &fileNameOrPartialNativePath); static de::StringList gameTags(); static de::String anyGameTagPattern(); diff --git a/doomsday/apps/libdoomsday/include/doomsday/resource/lumpcatalog.h b/doomsday/apps/libdoomsday/include/doomsday/resource/lumpcatalog.h index 85ad108671..f8c6476b3a 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/resource/lumpcatalog.h +++ b/doomsday/apps/libdoomsday/include/doomsday/resource/lumpcatalog.h @@ -25,8 +25,6 @@ #include #include -#include - namespace res { using namespace de; @@ -62,18 +60,18 @@ class LIBDOOMSDAY_PUBLIC LumpCatalog */ bool setPackages(const StringList &packageIds); - void setBundles(const QList &bundles); + void setBundles(const List &bundles); inline void setBundles(std::initializer_list bundles) { - setBundles(QList(bundles)); + setBundles(List(bundles)); } LumpPos find(const String &lumpName) const; - QList findAll(const String &lumpName) const; + List findAll(const String &lumpName) const; - QList flatRanges() const; + List flatRanges() const; /** * Reads the contents of a lump. diff --git a/doomsday/apps/libdoomsday/include/doomsday/resource/lumpdirectory.h b/doomsday/apps/libdoomsday/include/doomsday/resource/lumpdirectory.h index 0a53eda2e9..39e1f4ad93 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/resource/lumpdirectory.h +++ b/doomsday/apps/libdoomsday/include/doomsday/resource/lumpdirectory.h @@ -107,11 +107,11 @@ class LIBDOOMSDAY_PUBLIC LumpDirectory */ Pos find(const Block &lumpName) const; - QList findAll(const Block &lumpName) const; + List findAll(const Block &lumpName) const; - QList findRanges(RangeType rangeType) const; + List findRanges(RangeType rangeType) const; - QList findMaps() const; + List findMaps() const; StringList findMapLumpNames() const; diff --git a/doomsday/apps/libdoomsday/include/doomsday/resource/manifest.h b/doomsday/apps/libdoomsday/include/doomsday/resource/manifest.h index a021d58730..7d266b52b5 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/resource/manifest.h +++ b/doomsday/apps/libdoomsday/include/doomsday/resource/manifest.h @@ -22,7 +22,6 @@ #define LIBDOOMSDAY_RESOURCE_MANIFEST_H #include -#include #include "resourceclass.h" /** @@ -39,7 +38,7 @@ class LIBDOOMSDAY_PUBLIC ResourceManifest * @param fFlags @ref fileFlags * @param name An expected name for the associated file. */ - ResourceManifest(resourceclassid_t rClass, int fFlags, de::String *name = 0); + ResourceManifest(resourceclassid_t rClass, int fFlags, de::String *name = nullptr); /// @return Class of the associated resource. resourceclassid_t resourceClass() const; @@ -50,7 +49,7 @@ class LIBDOOMSDAY_PUBLIC ResourceManifest /** * Returns a list of "identity keys" used to identify the resource. */ - QStringList const &identityKeys() const; + de::StringList const &identityKeys() const; /** * Add a new file segment identity key to the list for this manifest. @@ -62,14 +61,14 @@ class LIBDOOMSDAY_PUBLIC ResourceManifest /** * Returns a list of known-names for the associated resource. */ - QStringList const &names() const; + de::StringList const &names() const; /** * Add a new file name to the list of names for this manifest. * * @param newName New name for this file. Newer names have precedence. */ - void addName(de::String newName); + void addName(const de::String& newName); /** * Attempt to locate this file by systematically resolving and then diff --git a/doomsday/apps/libdoomsday/include/doomsday/resource/resourceclass.h b/doomsday/apps/libdoomsday/include/doomsday/resource/resourceclass.h index a644b36138..939eeab56a 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/resource/resourceclass.h +++ b/doomsday/apps/libdoomsday/include/doomsday/resource/resourceclass.h @@ -52,7 +52,7 @@ typedef enum resourceclassid_e { #ifdef __cplusplus #include -#include +#include namespace de { class FileType; } @@ -65,7 +65,7 @@ namespace de { class FileType; } class LIBDOOMSDAY_PUBLIC ResourceClass { public: - typedef QList FileTypes; + typedef de::List FileTypes; public: ResourceClass(de::String name, de::String defaultScheme); diff --git a/doomsday/apps/libdoomsday/include/doomsday/resource/resources.h b/doomsday/apps/libdoomsday/include/doomsday/resource/resources.h index 0e676ed427..9342743d4d 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/resource/resources.h +++ b/doomsday/apps/libdoomsday/include/doomsday/resource/resources.h @@ -138,7 +138,7 @@ namespace res { auto const *path = reinterpret_cast(context); /// @todo Use PathTree::Node::compare() - return manifest.path().toStringRef().beginsWith(*path, de::String::CaseInsensitive); + return manifest.path().toString().beginsWith(*path, de::CaseInsensitive); } } diff --git a/doomsday/apps/libdoomsday/include/doomsday/resource/texture.h b/doomsday/apps/libdoomsday/include/doomsday/resource/texture.h index eeedd1140d..2aa0721bf9 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/resource/texture.h +++ b/doomsday/apps/libdoomsday/include/doomsday/resource/texture.h @@ -26,11 +26,12 @@ #include #include #include -#include -#include +#include namespace res { +using namespace de; + class TextureManifest; /** @@ -61,7 +62,6 @@ class LIBDOOMSDAY_PUBLIC Texture /// Apply the upscaleAndSharpen filter to the processed image. UpscaleAndSharpen = 0x8 }; - Q_DECLARE_FLAGS(Flags, Flag) /** * Image analysis identifiers. @@ -108,14 +108,14 @@ class LIBDOOMSDAY_PUBLIC Texture * * @return Human-friendly description/overview of the texture. */ - virtual de::String description() const; + virtual String description() const; /** * Returns the world dimensions of the texture, in map coordinate space * units. The DimensionsChange audience is notified whenever dimensions * are changed. */ - de::Vec2ui const &dimensions() const; + Vec2ui const &dimensions() const; /** * Convenient accessor method for returning the X axis size (width) of @@ -139,7 +139,7 @@ class LIBDOOMSDAY_PUBLIC Texture * * @todo Update any Materials (and thus Surfaces) which reference this. */ - void setDimensions(de::Vec2ui const &newDimensions); + void setDimensions(Vec2ui const &newDimensions); /** * Change the world width of the texture. @@ -147,7 +147,7 @@ class LIBDOOMSDAY_PUBLIC Texture * * @todo Update any Materials (and thus Surfaces) which reference this. */ - void setWidth(de::duint newWidth); + void setWidth(duint newWidth); /** * Change the world height of the texture. @@ -155,18 +155,18 @@ class LIBDOOMSDAY_PUBLIC Texture * * @todo Update any Materials (and thus Surfaces) which reference this. */ - void setHeight(de::duint newHeight); + void setHeight(duint newHeight); /** * Returns the world origin offset of texture in map coordinate space units. */ - de::Vec2i const &origin() const; + Vec2i const &origin() const; /** * Change the world origin offset of the texture. * @param newOrigin New origin in map coordinate space units. */ - void setOrigin(de::Vec2i const &newOrigin); + void setOrigin(Vec2i const &newOrigin); /** * Returns @c true if the texture is flagged @a flagsToTest. @@ -184,7 +184,7 @@ class LIBDOOMSDAY_PUBLIC Texture * @param flagsToChange Flags to change the value of. * @param operation Logical operation to perform on the flags. */ - void setFlags(Flags flagsToChange, de::FlagOp operation = de::SetFlags); + void setFlags(Flags flagsToChange, FlagOp operation = SetFlags); /** * Release prepared GL-textures for identified variants. @@ -243,8 +243,6 @@ class LIBDOOMSDAY_PUBLIC Texture DE_PRIVATE(d) }; -Q_DECLARE_OPERATORS_FOR_FLAGS(Texture::Flags) - } // namespace res #endif // LIBDOOMSDAY_RESOURCE_TEXTURE_H diff --git a/doomsday/apps/libdoomsday/include/doomsday/resource/texturemanifest.h b/doomsday/apps/libdoomsday/include/doomsday/resource/texturemanifest.h index a8f4874d0a..7840058874 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/resource/texturemanifest.h +++ b/doomsday/apps/libdoomsday/include/doomsday/resource/texturemanifest.h @@ -88,7 +88,7 @@ class LIBDOOMSDAY_PUBLIC TextureManifest : public de::PathTree::Node * The path component of the URI will contain the percent-encoded path * of the TextureManifest. */ - inline de::Uri composeUri(QChar sep = '/') const + inline de::Uri composeUri(Char sep = '/') const { return de::Uri(schemeName(), path(sep)); } @@ -107,7 +107,7 @@ class LIBDOOMSDAY_PUBLIC TextureManifest : public de::PathTree::Node */ inline de::Uri composeUrn() const { - return de::Uri("urn", de::String("%1:%2").arg(schemeName()).arg(uniqueId(), 0, 10)); + return de::Uri("urn", de::String::format("%s:%i", schemeName().c_str(), uniqueId())); } /** @@ -184,7 +184,7 @@ class LIBDOOMSDAY_PUBLIC TextureManifest : public de::PathTree::Node /** * Returns the texture flags property of the manifest. */ - Texture::Flags flags() const; + Flags flags() const; /** * Change the texture flags property of the manifest. @@ -192,7 +192,7 @@ class LIBDOOMSDAY_PUBLIC TextureManifest : public de::PathTree::Node * @param flagsToChange Flags to change the value of. * @param operation Logical operation to perform on the flags. */ - void setFlags(Texture::Flags flagsToChange, de::FlagOp operation = de::SetFlags); + void setFlags(Flags flagsToChange, de::FlagOp operation = de::SetFlags); /** * Returns @c true if a Texture is presently associated with the manifest. diff --git a/doomsday/apps/libdoomsday/include/doomsday/resource/texturescheme.h b/doomsday/apps/libdoomsday/include/doomsday/resource/texturescheme.h index c4ec808ed4..0b079f9195 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/resource/texturescheme.h +++ b/doomsday/apps/libdoomsday/include/doomsday/resource/texturescheme.h @@ -100,7 +100,7 @@ class LIBDOOMSDAY_PUBLIC TextureScheme * @return The (possibly newly created) manifest at @a path. */ Manifest &declare(de::Path const &path, - Texture::Flags flags, + de::Flags flags, de::Vec2ui const &dimensions, de::Vec2i const &origin, int uniqueId, diff --git a/doomsday/apps/libdoomsday/include/doomsday/uri.h b/doomsday/apps/libdoomsday/include/doomsday/uri.h index 23d533f408..9e3ac22680 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/uri.h +++ b/doomsday/apps/libdoomsday/include/doomsday/uri.h @@ -73,9 +73,9 @@ class LIBDOOMSDAY_PUBLIC Uri : public ISerializable DefaultComposeAsTextFlags = 0 }; - Q_DECLARE_FLAGS(ComposeAsTextFlags, ComposeAsTextFlag) + using ComposeAsTextFlags = Flags; - typedef String (*ResolverFunc)(String const &symbol); + typedef String (*ResolverFunc)(const String &symbol); public: /** @@ -99,7 +99,7 @@ class LIBDOOMSDAY_PUBLIC Uri : public ISerializable * @param sep Character used to separate path segments * in @a path. */ - Uri(String const &percentEncoded, resourceclassid_t defaultResClass, QChar sep = '/'); + Uri(String const &percentEncoded, resourceclassid_t defaultResClass, Char sep = '/'); /** * Construct a Uri from a textual scheme and a path. @@ -204,7 +204,7 @@ class LIBDOOMSDAY_PUBLIC Uri : public ISerializable * attempting to resolve ambiguous cases (only the one argument * is provided. */ - static Uri fromUserInput(char **argv, int argc, bool (*knownScheme) (String name) = 0); + static Uri fromUserInput(char **argv, int argc, bool (*knownScheme)(String name) = nullptr); /** * Convert this URI to a text string. @@ -234,8 +234,6 @@ class LIBDOOMSDAY_PUBLIC Uri : public ISerializable */ String resolved() const; - String const &resolvedRef() const; - /** * @return Scheme of the URI. */ @@ -256,15 +254,15 @@ class LIBDOOMSDAY_PUBLIC Uri : public ISerializable */ char const *pathCStr() const; - /** + /* * @return Scheme of the URI as plain text (UTF-8 encoding). */ - struct ddstring_s const *schemeStr() const; +// struct ddstring_s const *schemeStr() const; - /** + /* * @return Path of the URI as plain text (UTF-8 encoding). */ - struct ddstring_s const *pathStr() const; +// struct ddstring_s const *pathStr() const; /** * Change the scheme of the URI to @a newScheme. @@ -284,7 +282,7 @@ class LIBDOOMSDAY_PUBLIC Uri : public ISerializable * @param newPath New path for the URI. * @param sep Character used to separate path segments in @a path. */ - Uri &setPath(String newPath, QChar sep = '/'); + Uri &setPath(const String& newPath, Char sep = '/'); Uri &setPath(char const *newPathUtf8, char sep = '/'); @@ -299,7 +297,7 @@ class LIBDOOMSDAY_PUBLIC Uri : public ISerializable * * @param sep Character used to separate path segments in @a path. */ - Uri &setUri(String newUri, resourceclassid_t defaultResourceClass = RC_IMPLICIT, QChar sep = '/'); + Uri &setUri(const String& newUri, resourceclassid_t defaultResourceClass = RC_IMPLICIT, Char sep = '/'); /** * Compose from this URI a plain-text representation. Any symbolic identifiers @@ -312,7 +310,7 @@ class LIBDOOMSDAY_PUBLIC Uri : public ISerializable * @return Plain-text String representation. */ String compose(ComposeAsTextFlags compositionFlags = DefaultComposeAsTextFlags, - QChar sep = '/') const; + Char sep = '/') const; /** * Transform the URI into a human-friendly representation. Percent-encoded @@ -329,7 +327,7 @@ class LIBDOOMSDAY_PUBLIC Uri : public ISerializable void operator << (Reader &from) override; // Legacy Reader/Writer. - void readUri(reader_s *reader, de::String defaultScheme = ""); + void readUri(reader_s *reader, const de::String& defaultScheme = ""); void writeUri(writer_s *writer, int omitComponents = 0) const; public: @@ -344,9 +342,7 @@ class LIBDOOMSDAY_PUBLIC Uri : public ISerializable DE_PRIVATE(d) }; -Q_DECLARE_OPERATORS_FOR_FLAGS(Uri::ComposeAsTextFlags) - -inline Uri makeUri(String const &percentEncoded, QChar sep = '/') +inline Uri makeUri(String const &percentEncoded, Char sep = '/') { return Uri(percentEncoded, RC_NULL, sep); } diff --git a/doomsday/apps/libdoomsday/include/doomsday/world/material.h b/doomsday/apps/libdoomsday/include/doomsday/world/material.h index 51c83e8e40..f45ba2fbf6 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/world/material.h +++ b/doomsday/apps/libdoomsday/include/doomsday/world/material.h @@ -24,7 +24,7 @@ #include "../res/Texture" #include "mapelement.h" -#include +#include #include #include #include @@ -32,6 +32,8 @@ namespace world { +using namespace de; + class MaterialManifest; /** @@ -69,7 +71,7 @@ class LIBDOOMSDAY_PUBLIC Material : public MapElement /** * Returns the dimension metrics of the material. */ - de::Vec2ui const &dimensions() const; + Vec2ui const &dimensions() const; inline int width () const { return int(dimensions().x); } inline int height() const { return int(dimensions().y); } @@ -77,7 +79,7 @@ class LIBDOOMSDAY_PUBLIC Material : public MapElement /** * Change the world dimensions of the material to @a newDimensions. */ - void setDimensions(de::Vec2ui const &newDimensions); + void setDimensions(Vec2ui const &newDimensions); void setWidth (int newWidth); void setHeight(int newHeight); @@ -131,12 +133,12 @@ class LIBDOOMSDAY_PUBLIC Material : public MapElement /** * Returns a human-friendly, textual name for the object. */ - virtual de::String describe() const; + virtual String describe() const; /** * Returns a human-friendly, textual description of the full material configuration. */ - virtual de::String description() const; + virtual String description() const; //- Layers ------------------------------------------------------------------------------ @@ -178,7 +180,7 @@ class LIBDOOMSDAY_PUBLIC Material : public MapElement * Returns a human-friendly, textual description of the animation stage * configuration. */ - virtual de::String description() const = 0; + virtual String description() const = 0; }; public: @@ -189,17 +191,17 @@ class LIBDOOMSDAY_PUBLIC Material : public MapElement /** * Returns a human-friendly, textual name for the type of material layer. */ - virtual de::String describe() const; + virtual String describe() const; /** * Returns a human-friendly, textual synopsis of the material layer. */ - de::String description() const; + String description() const; /** * Returns the total number of animation stages for the material layer. */ - inline int stageCount() const { return _stages.size(); } + inline int stageCount() const { return _stages.sizei(); } /** * Returns @c true if the material layer is animated; otherwise @c false. @@ -216,16 +218,14 @@ class LIBDOOMSDAY_PUBLIC Material : public MapElement int nextStageIndex(int index) const; protected: - typedef QVector Stages; + typedef List Stages; Stages _stages; }; /** * Returns the number of material layers. */ - inline int layerCount() const { - return _layers.count(); - } + inline int layerCount() const { return _layers.sizei(); } /** * Add a new layer at the given layer stack position. @@ -277,19 +277,15 @@ class LIBDOOMSDAY_PUBLIC Material : public MapElement Valid = 0x8, ///< Marked as @em valid. DefaultFlags = Valid }; - Q_DECLARE_FLAGS(Flags, Flag) private: - // Heavily used; visible for inline access: /// Layers (owned), from bottom-most to top-most draw order. - QVector _layers; + List _layers; // Heavily used; visible for inline access. Flags _flags = DefaultFlags; DE_PRIVATE(d) }; -Q_DECLARE_OPERATORS_FOR_FLAGS(Material::Flags) - typedef Material::Layer MaterialLayer; } // namespace world diff --git a/doomsday/apps/libdoomsday/include/doomsday/world/materialmanifest.h b/doomsday/apps/libdoomsday/include/doomsday/world/materialmanifest.h index 95450cb4d1..cc86339534 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/world/materialmanifest.h +++ b/doomsday/apps/libdoomsday/include/doomsday/world/materialmanifest.h @@ -58,7 +58,6 @@ class LIBDOOMSDAY_PUBLIC MaterialManifest : public de::PathTree::Node /// The manifest was not produced for an original game resource. Custom }; - Q_DECLARE_FLAGS(Flags, Flag) typedef std::function MaterialConstructor; @@ -93,7 +92,7 @@ class LIBDOOMSDAY_PUBLIC MaterialManifest : public de::PathTree::Node * The path component of the URI will contain the percent-encoded path * of the material manifest. */ - inline de::Uri composeUri(QChar sep = '/') const { + inline de::Uri composeUri(Char sep = '/') const { return de::Uri(schemeName(), path(sep)); } @@ -170,8 +169,6 @@ class LIBDOOMSDAY_PUBLIC MaterialManifest : public de::PathTree::Node DE_PRIVATE(d) }; -Q_DECLARE_OPERATORS_FOR_FLAGS(MaterialManifest::Flags) - } // namespace world #endif // LIBDOOMSDAY_WORLD_MATERIALMANIFEST_H diff --git a/doomsday/apps/libdoomsday/include/doomsday/world/materials.h b/doomsday/apps/libdoomsday/include/doomsday/world/materials.h index 26a23b2e36..8a88d3c22b 100644 --- a/doomsday/apps/libdoomsday/include/doomsday/world/materials.h +++ b/doomsday/apps/libdoomsday/include/doomsday/world/materials.h @@ -24,8 +24,8 @@ #include "MaterialScheme" #include "../uri.h" -#include -#include +#include +#include namespace world { @@ -38,8 +38,8 @@ class LIBDOOMSDAY_PUBLIC Materials /// The specified material id was invalid (out of range). @ingroup errors DE_ERROR(UnknownMaterialIdError); - typedef QSet MaterialManifestGroup; - typedef QList MaterialManifestGroups; + typedef Set MaterialManifestGroup; + typedef List MaterialManifestGroups; static Materials &get(); diff --git a/doomsday/apps/libdoomsday/src/busymode.cpp b/doomsday/apps/libdoomsday/src/busymode.cpp index 665b400c40..29f9adb7b6 100644 --- a/doomsday/apps/libdoomsday/src/busymode.cpp +++ b/doomsday/apps/libdoomsday/src/busymode.cpp @@ -27,7 +27,6 @@ #include #include #include -#include using namespace de; @@ -86,18 +85,10 @@ DE_PIMPL(BusyMode) return result.returnValue; } - DE_PIMPL_AUDIENCE(Beginning) - DE_PIMPL_AUDIENCE(End) - DE_PIMPL_AUDIENCE(Abort) - DE_PIMPL_AUDIENCE(TaskWillStart) - DE_PIMPL_AUDIENCE(TaskComplete) + DE_PIMPL_AUDIENCES(Beginning, End, Abort, TaskWillStart, TaskComplete) }; -DE_AUDIENCE_METHOD(BusyMode, Beginning) -DE_AUDIENCE_METHOD(BusyMode, End) -DE_AUDIENCE_METHOD(BusyMode, Abort) -DE_AUDIENCE_METHOD(BusyMode, TaskWillStart) -DE_AUDIENCE_METHOD(BusyMode, TaskComplete) +DE_AUDIENCE_METHODS(BusyMode, Beginning, End, Abort, TaskWillStart, TaskComplete) BusyMode::BusyMode() : d(new Impl(this)) {} @@ -149,8 +140,10 @@ void BusyMode::abort(String const &message) * @param workerData Data context for the worker thread. * @param taskName Optional task name (drawn with the progress bar). */ -static BusyTask *newTask(int mode, std::function worker, void* workerData, - String const &taskName) +static BusyTask *newTask(int mode, + const std::function &worker, + void * workerData, + const String & taskName) { BusyTask *task = new BusyTask; zapPtr(task); @@ -163,7 +156,7 @@ static BusyTask *newTask(int mode, std::function worker, void* wor // Take a copy of the task name. if (!taskName.isEmpty()) { - task->name = M_StrDup(taskName.toLatin1()); + task->name = M_StrDup(taskName.c_str()); } return task; @@ -172,11 +165,11 @@ static BusyTask *newTask(int mode, std::function worker, void* wor static void deleteTask(BusyTask *task) { DE_ASSERT(task); - if (task->name) M_Free((void *)task->name); + if (task->name) M_Free((void *) task->name); delete task; } -int BusyMode::runNewTaskWithName(int mode, String const &taskName, std::function worker) +int BusyMode::runNewTaskWithName(int mode, String const &taskName, const std::function& worker) { BusyTask *task = newTask(mode, worker, nullptr, taskName); int result = runTask(task); diff --git a/doomsday/apps/libdoomsday/src/c_wrapper/library.cpp b/doomsday/apps/libdoomsday/src/c_wrapper/library.cpp index c1783b60ff..88d32ab231 100644 --- a/doomsday/apps/libdoomsday/src/c_wrapper/library.cpp +++ b/doomsday/apps/libdoomsday/src/c_wrapper/library.cpp @@ -26,12 +26,11 @@ #include #include #include +#include #include #include #include -#include - struct library_s // typedef Library { Str *path = nullptr; ///< de::FS path of the library (e.g., "/bin/doom.dll"). @@ -42,7 +41,7 @@ struct library_s // typedef Library static ddstring_t *lastError; -typedef QList LoadedLibs; +typedef de::List LoadedLibs; static LoadedLibs loadedLibs; void Library_Init() @@ -129,7 +128,7 @@ Library *Library_New(char const *filePath) } catch (de::Error const &er) { - Str_Set(lastError, er.asText().toLatin1().constData()); + Str_Set(lastError, er.asText().c_str()); LOG_RES_WARNING("Library_New: Error opening \"%s\": ") << filePath << er.asText(); } return nullptr; @@ -172,7 +171,7 @@ void *Library_Symbol(Library *lib, char const *symbolName) } catch (de::Library::SymbolMissingError const &er) { - Str_Set(lastError, er.asText().toLatin1().constData()); + Str_Set(lastError, er.asText().c_str()); return nullptr; } } @@ -182,10 +181,10 @@ char const *Library_LastError() return Str_Text(lastError); } -de::LoopResult Library_ForAll(std::function func) +de::LoopResult Library_ForAll(const std::function& func) { - auto const &libs = de::App::fileSystem().indexFor(DE_TYPE_NAME(de::LibraryFile)); - foreach (de::File *file, libs.files()) + const auto &libs = de::App::fileSystem().indexFor(DE_TYPE_NAME(de::LibraryFile)); + for (auto *file : libs.files()) { if (file->path().beginsWith("/bin/")) { diff --git a/doomsday/apps/libdoomsday/src/console/alias.cpp b/doomsday/apps/libdoomsday/src/console/alias.cpp index 908b13a524..d2b5dcb090 100644 --- a/doomsday/apps/libdoomsday/src/console/alias.cpp +++ b/doomsday/apps/libdoomsday/src/console/alias.cpp @@ -68,7 +68,7 @@ calias_t *Con_FindAlias(char const *name) { pivot = bottomIdx + (topIdx - bottomIdx)/2; - result = qstricmp(caliases[pivot]->name, name); + result = iCmpStrCase(caliases[pivot]->name, name); if (result == 0) { // Found. @@ -105,7 +105,7 @@ calias_t* Con_AddAlias(char const* name, char const* command) uint idx; for (idx = 0; idx < numCAliases-1; ++idx) { - if (qstricmp(caliases[idx]->name, name) > 0) + if (iCmpStrCase(caliases[idx]->name, name) > 0) break; } @@ -152,12 +152,7 @@ void Con_DeleteAlias(calias_t* cal) String Con_AliasAsStyledText(calias_t *alias) { - QString str; - QTextStream os(&str); - - os << _E(b) << alias->name << _E(.) " == " _E(>) << alias->command << _E(<); - - return str; + return String(_E(b)) + alias->name + _E(.) " == " _E(>) + alias->command + _E(<); } void Con_AddKnownWordsForAliases() diff --git a/doomsday/apps/libdoomsday/src/console/cmd.cpp b/doomsday/apps/libdoomsday/src/console/cmd.cpp index ce26f8b716..bcf9289a12 100644 --- a/doomsday/apps/libdoomsday/src/console/cmd.cpp +++ b/doomsday/apps/libdoomsday/src/console/cmd.cpp @@ -27,7 +27,7 @@ #include #include #include -#include +#include using namespace de; @@ -39,7 +39,7 @@ static blockset_t *ccmdBlockSet; /// Running total of the number of uniquely-named commands. static uint numUniqueNamedCCmds; -static QMap mappedConfigVariables; +static Map mappedConfigVariables; void Con_InitCommands() { @@ -249,7 +249,7 @@ ccmd_t *Con_FindCommand(char const *name) { for (ccmd_t *ccmd = ccmdListHead; ccmd; ccmd = ccmd->next) { - if (qstricmp(name, ccmd->name)) continue; + if (iCmpStrCase(name, ccmd->name)) continue; // Locate the head of the overload list. while (ccmd->prevOverload) { ccmd = ccmd->prevOverload; } @@ -397,11 +397,11 @@ String Con_CmdAsStyledText(ccmd_t *cmd) char const *str; if ((str = DH_GetString(DH_Find(cmd->name), HST_DESCRIPTION))) { - return String(_E(b) "%1 " _E(.) _E(>) _E(2) "%2" _E(.) _E(<)).arg(cmd->name).arg(str); + return String::format(_E(b) "%1 " _E(.) _E(>) _E(2) "%2" _E(.) _E(<), cmd->name, str); } else { - return String(_E(b) "%1" _E(.)).arg(cmd->name); + return String::format(_E(b) "%s" _E(.), cmd->name); } } @@ -410,10 +410,10 @@ D_CMD(MappedConfigVariable) DE_UNUSED(src); // Look up the variable. - auto const found = mappedConfigVariables.constFind(argv[0]); - DE_ASSERT(found != mappedConfigVariables.constEnd()); // mapping must be defined + auto const found = mappedConfigVariables.find(argv[0]); + DE_ASSERT(found != mappedConfigVariables.end()); // mapping must be defined - Variable &var = Config::get(found.value()); + Variable &var = Config::get(found->second); if (argc == 1) { @@ -421,7 +421,7 @@ D_CMD(MappedConfigVariable) LOG_SCR_MSG(_E(b) "%s" _E(.) " = " _E(>) "%s " _E(l)_E(C) "[Config.%s]") << argv[0] << var.value().asText() - << found.value(); + << found->second; } else if (argc > 1) { diff --git a/doomsday/apps/libdoomsday/src/console/exec.cpp b/doomsday/apps/libdoomsday/src/console/exec.cpp index b8bd4b1f86..5d14ce8f40 100644 --- a/doomsday/apps/libdoomsday/src/console/exec.cpp +++ b/doomsday/apps/libdoomsday/src/console/exec.cpp @@ -29,8 +29,6 @@ #include #include #include -#include -#include #include #include @@ -660,7 +658,7 @@ static int executeSubCmd(const char *subCmd, byte src, dd_bool isNetCmd) hasCallback = (cvar->notifyChanged != 0); if (args.argc == 2 || - (args.argc == 3 && !qstricmp(args.argv[1], "force"))) + (args.argc == 3 && !iCmpStrCase(args.argv[1], "force"))) { char* argptr = args.argv[args.argc - 1]; dd_bool forced = args.argc == 3; @@ -889,16 +887,15 @@ bool Con_Parse(File const &file, bool silently) String contents = String::fromUtf8(utf8); // This file is filled with console commands. - QTextStream in(&contents); int currentLine = 1; - while (!in.atEnd()) + for (const auto &lineRef : contents.splitRef("\n")) { // Each line is a command. - String const line = String(in.readLine()).leftStrip(); + String const line = String(lineRef).leftStrip(); if (!line.isEmpty() && line.first() != '#') { // Execute the commands silently. - if (!Con_Execute(CMDS_CONFIG, line.toUtf8(), silently, false)) + if (!Con_Execute(CMDS_CONFIG, line, silently, false)) { if (!silently) { @@ -1084,11 +1081,11 @@ D_CMD(AddSub) } if (argc >= 4) { - force = !qstricmp(argv[3], "force"); + force = !iCmpStrCase(argv[3], "force"); } delta = strtod(argv[2], NULL); - if (!qstricmp(argv[0], "sub")) + if (!iCmpStrCase(argv[0], "sub")) delta = -delta; return cvarAddSub(argv[1], delta, force); @@ -1113,7 +1110,7 @@ D_CMD(IncDec) } if (argc >= 3) { - force = !qstricmp(argv[2], "force"); + force = !iCmpStrCase(argv[2], "force"); } cvar = Con_FindVariable(argv[1]); if (!cvar) @@ -1126,7 +1123,7 @@ D_CMD(IncDec) } val = CVar_Float(cvar); - val += !qstricmp(argv[0], "inc")? 1 : -1; + val += !iCmpStrCase(argv[0], "inc")? 1 : -1; if (!force) { @@ -1190,7 +1187,7 @@ D_CMD(If) // Which operator? for (i = 0; operators[i].opstr; ++i) - if (!qstricmp(operators[i].opstr, argv[2])) + if (!iCmpStrCase(operators[i].opstr, argv[2])) { oper = operators[i].op; break; @@ -1230,7 +1227,7 @@ D_CMD(If) } case CVT_CHARPTR: { - int comp = qstricmp(CV_CHARPTR(var), argv[3]); + int comp = iCmpStrCase(CV_CHARPTR(var), argv[3]); isTrue = (oper == IF_EQUAL ? comp == 0 : oper == IF_NOT_EQUAL ? comp != 0 : diff --git a/doomsday/apps/libdoomsday/src/console/knownword.cpp b/doomsday/apps/libdoomsday/src/console/knownword.cpp index d1189c5e82..d68b9c3cad 100644 --- a/doomsday/apps/libdoomsday/src/console/knownword.cpp +++ b/doomsday/apps/libdoomsday/src/console/knownword.cpp @@ -31,14 +31,14 @@ #include #include #include -#include -#include +#include +#include using namespace de; /// The list of known words (for completion). /// @todo Replace with a persistent self-balancing BST (Treap?)? -static QList knownWords; +static List knownWords; static dd_bool knownWordsNeedUpdate; static void (*appWordsCallback)(); @@ -61,7 +61,7 @@ static bool compareKnownWordByName(knownword_t const &a, knownword_t const &b) case WT_CALIAS: textA = AutoStr_FromTextStd(((calias_t *)wA->data)->name); break; case WT_CCMD: textA = AutoStr_FromTextStd(((ccmd_t *)wA->data)->name); break; case WT_CVAR: textA = CVar_ComposePath((cvar_t *)wA->data); break; - case WT_GAME: textA = AutoStr_FromTextStd(reinterpret_cast(wA->data)->id().toUtf8().constData()); break; + case WT_GAME: textA = AutoStr_FromTextStd(reinterpret_cast(wA->data)->id()); break; default: DE_ASSERT_FAIL("compareKnownWordByName: Invalid type for word A"); @@ -73,7 +73,7 @@ static bool compareKnownWordByName(knownword_t const &a, knownword_t const &b) case WT_CALIAS: textB = AutoStr_FromTextStd(((calias_t *)wB->data)->name); break; case WT_CCMD: textB = AutoStr_FromTextStd(((ccmd_t *)wB->data)->name); break; case WT_CVAR: textB = CVar_ComposePath((cvar_t *)wB->data); break; - case WT_GAME: textB = AutoStr_FromTextStd(reinterpret_cast(wB->data)->id().toUtf8().constData()); break; + case WT_GAME: textB = AutoStr_FromTextStd(reinterpret_cast(wB->data)->id()); break; default: DE_ASSERT_FAIL("compareKnownWordByName: Invalid type for word B"); @@ -95,7 +95,7 @@ static AutoStr *textForKnownWord(knownword_t const *word) case WT_CALIAS: text = AutoStr_FromTextStd(((calias_t *)word->data)->name); break; case WT_CCMD: text = AutoStr_FromTextStd(((ccmd_t *)word->data)->name); break; case WT_CVAR: text = CVar_ComposePath((cvar_t *)word->data); break; - case WT_GAME: text = AutoStr_FromTextStd(reinterpret_cast(word->data)->id().toUtf8().constData()); break; + case WT_GAME: text = AutoStr_FromTextStd(reinterpret_cast(word->data)->id()); break; default: DE_ASSERT_FAIL("textForKnownWord: Invalid type for word"); @@ -185,7 +185,7 @@ static void updateKnownWords(void) } // Sort it so we get nice alphabetical word completions. - qSort(knownWords.begin(), knownWords.end(), compareKnownWordByName); + std::sort(knownWords.begin(), knownWords.end(), compareKnownWordByName); knownWordsNeedUpdate = false; } @@ -212,11 +212,11 @@ int Con_IterateKnownWords(KnownWordMatchMode matchMode, knownwordtype_t matchType = (VALID_KNOWNWORDTYPE(type)? type : WT_ANY); size_t patternLength = (pattern? strlen(pattern) : 0); int result = 0; - QRegExp const regex(matchMode == KnownWordRegex? pattern : "", Qt::CaseInsensitive); + RegExp const regex(matchMode == KnownWordRegex? pattern : "", CaseInsensitive); updateKnownWords(); - for (int i = 0; i < knownWords.size(); ++i) + for (int i = 0; i < knownWords.sizei(); ++i) { knownword_t const *word = &knownWords.at(i); if (matchType != WT_ANY && word->type != type) continue; @@ -226,12 +226,12 @@ int Con_IterateKnownWords(KnownWordMatchMode matchMode, AutoStr* textString = textForKnownWord(word); if (matchMode == KnownWordStartsWith) { - if (qstrnicmp(Str_Text(textString), pattern, patternLength)) + if (iCmpStrNCase(Str_Text(textString), pattern, patternLength)) continue; // Didn't match. } else if (matchMode == KnownWordExactMatch) { - if (strcasecmp(Str_Text(textString), pattern)) + if (iCmpStrCase(Str_Text(textString), pattern)) continue; // Didn't match. } else if (matchMode == KnownWordRegex) @@ -304,8 +304,7 @@ static int aproposPrinter(knownword_t const *word, void *matching) "cmd ", "var ", "alias ", "game " }; - String str; - QTextStream os(&str); + std::ostringstream os; os << _E(l) << wType[word->type] << _E(0) << _E(b) << Str_Text(text) << " " << _E(2) << _E(>); @@ -327,7 +326,7 @@ static int aproposPrinter(knownword_t const *word, void *matching) os << tmp; - LOG_SCR_MSG("%s") << str; + LOG_SCR_MSG("%s") << os.str(); } return 0; @@ -349,7 +348,7 @@ D_CMD(HelpApropos) struct AnnotationWork { - QSet terms; + de::Set terms; de::String result; }; @@ -399,14 +398,14 @@ static int annotateMatchedWordCallback(knownword_t const *word, void *parameters return false; // don't stop } -de::String Con_AnnotatedConsoleTerms(QStringList terms) +de::String Con_AnnotatedConsoleTerms(const StringList &terms) { AnnotationWork work; - foreach (QString term, terms) + for (const String &term : terms) { work.terms.insert(term); } - Con_IterateKnownWords(NULL, WT_ANY, annotateMatchedWordCallback, &work); + Con_IterateKnownWords(nullptr, WT_ANY, annotateMatchedWordCallback, &work); return work.result; } @@ -420,7 +419,7 @@ static int addToTerms(knownword_t const *word, void *parameters) shell::Lexicon Con_Lexicon() { shell::Lexicon lexi; - Con_IterateKnownWords(0, WT_ANY, addToTerms, &lexi); + Con_IterateKnownWords(nullptr, WT_ANY, addToTerms, &lexi); lexi.setAdditionalWordChars("-_."); return lexi; } @@ -440,6 +439,6 @@ static int addToStringList(knownword_t const *word, void *parameters) void Con_TermsRegex(StringList &terms, String const &pattern, knownwordtype_t wordType) { terms.clear(); - Con_IterateKnownWords(KnownWordRegex, pattern.toUtf8(), wordType, + Con_IterateKnownWords(KnownWordRegex, pattern, wordType, addToStringList, &terms); } diff --git a/doomsday/apps/libdoomsday/src/console/var.cpp b/doomsday/apps/libdoomsday/src/console/var.cpp index a4b1d3e074..81b4fb574d 100644 --- a/doomsday/apps/libdoomsday/src/console/var.cpp +++ b/doomsday/apps/libdoomsday/src/console/var.cpp @@ -230,8 +230,7 @@ AutoStr *CVar_ComposePath(cvar_t const *var) { DE_ASSERT(var != 0); CVarDirectory::Node &node = *reinterpret_cast(var->directoryNode); - QByteArray path = node.path(CVARDIRECTORY_DELIMITER).toUtf8(); - return AutoStr_FromTextStd(path.constData()); + return AutoStr_FromTextStd(node.path(CVARDIRECTORY_DELIMITER)); } void CVar_SetUri2(cvar_t *var, de::Uri const &uri, int svFlags) @@ -314,7 +313,7 @@ void CVar_SetString2(cvar_t *var, char const *text, int svFlags) if (oldLen == 0 && newLen == 0) return; - if (oldLen != newLen || qstricmp(text, CV_CHARPTR(var))) + if (oldLen != newLen || iCmpStrCase(text, CV_CHARPTR(var))) changed = true; // Free the old string, if one exists. @@ -324,7 +323,7 @@ void CVar_SetString2(cvar_t *var, char const *text, int svFlags) // Allocate a new string. var->flags |= CVF_CAN_FREE; CV_CHARPTR(var) = (char*) M_Malloc(newLen + 1); - qstrcpy(CV_CHARPTR(var), text); + strcpy(CV_CHARPTR(var), text); // Make the change notification callback if (var->notifyChanged != NULL && changed) @@ -565,8 +564,7 @@ String Con_VarAsStyledText(cvar_t *var, char const *prefix) if ((var->flags & CVF_PROTECTED) || (var->flags & CVF_READ_ONLY)) equals = ':'; - String str; - QTextStream os(&str); + std::ostringstream os; if (prefix) os << prefix; @@ -584,11 +582,11 @@ String Con_VarAsStyledText(cvar_t *var, char const *prefix) os << "\"" << (CV_URIPTR(var)? CV_URIPTR(var)->asText() : "") << "\""; break; } default: - DE_ASSERT(false); + DE_ASSERT_FAIL("Invalid cvar type"); break; } os << _E(<); - return str; + return os.str(); } void Con_PrintCVar(cvar_t* var, char const *prefix) @@ -641,11 +639,11 @@ int Con_GetVariableInteger(Path const &varPath) static Value *Function_Console_Get(Context &, Function::ArgumentValues const &args) { String const name = args.at(0)->asText(); - cvar_t *var = Con_FindVariable(name.toUtf8()); + cvar_t *var = Con_FindVariable(name.c_str()); if (!var) { throw Error("Function_Console_Get", - QString("Unknown console variable: %1").arg(name)); + stringf("Unknown console variable: %s", name.c_str())); } switch (var->type) { @@ -673,11 +671,11 @@ static Value *Function_Console_Get(Context &, Function::ArgumentValues const &ar static Value *Function_Console_Set(Context &, Function::ArgumentValues const &args) { String const name = args.at(0)->asText(); - cvar_t *var = Con_FindVariable(name.toUtf8()); + cvar_t *var = Con_FindVariable(name.c_str()); if (!var) { throw Error("Function_Console_Set", - QString("Unknown console variable: %1").arg(name)); + stringf("Unknown console variable: %1", name.c_str())); } Value const &value = *args.at(1); @@ -693,7 +691,7 @@ static Value *Function_Console_Set(Context &, Function::ArgumentValues const &ar break; case CVT_CHARPTR: ///< ptr points to a char*, which points to the string. - CVar_SetString(var, value.asText().toUtf8()); + CVar_SetString(var, value.asText()); break; case CVT_URIPTR: diff --git a/doomsday/apps/libdoomsday/src/defs/ded.cpp b/doomsday/apps/libdoomsday/src/defs/ded.cpp index 6e6b3216ca..30bfa00841 100644 --- a/doomsday/apps/libdoomsday/src/defs/ded.cpp +++ b/doomsday/apps/libdoomsday/src/defs/ded.cpp @@ -366,7 +366,7 @@ int ded_s::getMobjNum(String const &id) const } /* for (i = 0; i < mobjs.size(); ++i) - if (!qstricmp(mobjs[i].id, id)) + if (!iCmpStrCase(mobjs[i].id, id)) return i;*/ return -1; @@ -379,7 +379,7 @@ int ded_s::getMobjNumForName(const char *name) const /* for (int i = mobjs.size() - 1; i >= 0; --i) - if (!qstricmp(mobjs[i].name, name)) + if (!iCmpStrCase(mobjs[i].name, name)) return i;*/ if (Record const *def = things.tryFind("name", name)) { @@ -420,7 +420,7 @@ dint ded_s::evalFlags(char const *ptr) const { ptr = M_SkipWhite(const_cast(ptr)); - dint flagNameLength = M_FindWhite(const_cast(ptr)) - ptr; + dsize flagNameLength = M_FindWhite(const_cast(ptr)) - ptr; String flagName(ptr, flagNameLength); ptr += flagNameLength; @@ -496,7 +496,7 @@ int ded_s::getModelNum(const char *id) const { int i = 0; do { - if (!qstricmp(models[i].id, id)) idx = i; + if (!iCmpStrCase(models[i].id, id)) idx = i; } while (idx == -1 && ++i < (int)models.size()); } return idx;*/ @@ -514,7 +514,7 @@ int ded_s::getSkyNum(char const *id) const for (int i = skies.size() - 1; i >= 0; i--) { - if (!qstricmp(skies[i].id, id)) + if (!iCmpStrCase(skies[i].id, id)) return i; } return -1;*/ @@ -522,7 +522,7 @@ int ded_s::getSkyNum(char const *id) const int ded_s::getSoundNum(String const &id) const { - return getSoundNum(id.toUtf8()); + return getSoundNum(id.c_str()); } int ded_s::getSoundNum(const char *id) const @@ -532,7 +532,7 @@ int ded_s::getSoundNum(const char *id) const { int i = 0; do { - if (!qstricmp(sounds[i].id, id)) idx = i; + if (!iCmpStrCase(sounds[i].id, id)) idx = i; } while (idx == -1 && ++i < sounds.size()); } return idx; @@ -544,7 +544,7 @@ int ded_s::getSoundNumForName(const char *name) const return -1; for (int i = 0; i < sounds.size(); ++i) - if (!qstricmp(sounds[i].name, name)) + if (!iCmpStrCase(sounds[i].name, name)) return i; return 0; @@ -552,7 +552,7 @@ int ded_s::getSoundNumForName(const char *name) const int ded_s::getSpriteNum(String const &id) const { - return getSpriteNum(id.toLatin1()); + return getSpriteNum(id.c_str()); } int ded_s::getSpriteNum(char const *id) const @@ -561,7 +561,7 @@ int ded_s::getSpriteNum(char const *id) const { for (dint i = 0; i < sprites.size(); ++i) { - if (!qstricmp(sprites[i].id, id)) + if (!iCmpStrCase(sprites[i].id, id)) return i; } } @@ -581,7 +581,7 @@ int ded_s::getMusicNum(char const *id) const { int i = 0; do { - if (!qstricmp(musics[i].id, id)) idx = i; + if (!iCmpStrCase(musics[i].id, id)) idx = i; } while (idx == -1 && ++i < musics.size()); } return idx;*/ @@ -594,7 +594,7 @@ int ded_s::getValueNum(char const *id) const // Read backwards to allow patching. for (dint i = values.size() - 1; i >= 0; i--) { - if (!qstricmp(values[i].id, id)) + if (!iCmpStrCase(values[i].id, id)) return i; } } @@ -603,7 +603,7 @@ int ded_s::getValueNum(char const *id) const int ded_s::getValueNum(String const &id) const { - return getValueNum(id.toLatin1()); + return getValueNum(id.c_str()); } ded_value_t *ded_s::getValueById(char const *id) const @@ -613,14 +613,14 @@ ded_value_t *ded_s::getValueById(char const *id) const // Read backwards to allow patching. for (dint i = values.size() - 1; i >= 0; i--) { - if (!qstricmp(values[i].id, id)) + if (!iCmpStrCase(values[i].id, id)) return &values[i]; } return nullptr; } ded_value_t *ded_s::getValueById(String const &id) const { - return getValueById(id.toLatin1()); + return getValueById(id.c_str()); } ded_value_t *ded_s::getValueByUri(de::Uri const &uri) const @@ -697,7 +697,7 @@ int ded_s::getTextNum(char const *id) const // Search in reverse insertion order to allow patching. for (int i = text.size() - 1; i >= 0; i--) { - if (!qstricmp(text[i].id, id)) return i; + if (!iCmpStrCase(text[i].id, id)) return i; } } return -1; // Not found. diff --git a/doomsday/apps/libdoomsday/src/defs/dedfile.cpp b/doomsday/apps/libdoomsday/src/defs/dedfile.cpp index 209b34a00b..8db56b6c0d 100644 --- a/doomsday/apps/libdoomsday/src/defs/dedfile.cpp +++ b/doomsday/apps/libdoomsday/src/defs/dedfile.cpp @@ -36,10 +36,10 @@ static char dedReadError[512]; void DED_SetError(String const &message) { String msg = "Error: " + message + "."; - strncpy(dedReadError, msg.toUtf8().constData(), sizeof(dedReadError)); + strncpy(dedReadError, msg, sizeof(dedReadError)); } -void Def_ReadProcessDED(ded_t *defs, String sourcePath) +void Def_ReadProcessDED(ded_t *defs, const String& sourcePath) { LOG_AS("Def_ReadProcessDED"); @@ -50,7 +50,7 @@ void Def_ReadProcessDED(ded_t *defs, String sourcePath) { Block text; App::rootFolder().locate(sourcePath) >> text; - if (!DED_ReadData(defs, text, sourcePath, true/*consider it custom; there is no way to check...*/)) + if (!DED_ReadData(defs, String(text), sourcePath, true/*consider it custom; there is no way to check...*/)) { App_FatalError("Def_ReadProcessDED: %s\n", dedReadError); } @@ -103,14 +103,14 @@ int DED_ReadLump(ded_t *ded, lumpnum_t lumpNum) return false; } -int DED_Read(ded_t *ded, String path) +int DED_Read(ded_t *ded, const String& path) { // Attempt to open a definition file on this path. try { // Relative paths are relative to the native working directory. String fullPath = (NativePath::workPath() / NativePath(path).expand()).withSeparators('/'); - QScopedPointer hndl(&App_FileSystem().openFile(fullPath, "rb")); + std::unique_ptr hndl(&App_FileSystem().openFile(fullPath, "rb")); // We will buffer a local copy of the file. How large a buffer do we need? hndl->seek(0, SeekEnd); diff --git a/doomsday/apps/libdoomsday/src/defs/dedparser.cpp b/doomsday/apps/libdoomsday/src/defs/dedparser.cpp index fb8539af8d..a34c1c7527 100644 --- a/doomsday/apps/libdoomsday/src/defs/dedparser.cpp +++ b/doomsday/apps/libdoomsday/src/defs/dedparser.cpp @@ -235,7 +235,7 @@ DE_PIMPL(DEDParser) String readPosAsText() { return "\"" + (source? source->fileName : "[buffered-data]") + "\"" - " on line #" + String::number(source? source->lineNumber : 0); + " on line #" + String::asText(source? source->lineNumber : 0); } void setError(String const &message) @@ -438,10 +438,10 @@ DE_PIMPL(DEDParser) int ReadString(char *dest, int maxLen) { - DE_ASSERT(dest != 0); + DE_ASSERT(dest != nullptr); String buffer; if (!ReadString(buffer)) return false; - qstrncpy(dest, buffer.toUtf8().constData(), maxLen); + strncpy(dest, buffer, maxLen); return true; } @@ -464,13 +464,11 @@ DE_PIMPL(DEDParser) return false; // Get rid of the old string. - if (*dest) - M_Free(*dest); + if (*dest) M_Free(*dest); // Make a copy. - QByteArray bufferUtf8 = buffer.toUtf8(); - *dest = (char *) M_Malloc(bufferUtf8.length() + 1); - qstrcpy(*dest, bufferUtf8.constData()); + *dest = (char *) M_Malloc(buffer.size() + 1); + strcpy(*dest, buffer); return true; } @@ -633,12 +631,12 @@ DE_PIMPL(DEDParser) if (!flag.isEmpty()) { - *dest = ded->evalFlags(flag.toUtf8().constData()); + *dest = ded->evalFlags(flag); } return true; } - forever + for (;;) { // Read the flag. ReadToken(); @@ -655,7 +653,7 @@ DE_PIMPL(DEDParser) if (!flag.isEmpty()) { - *dest |= ded->evalFlags(flag.toUtf8().constData()); + *dest |= ded->evalFlags(flag); } if (!ReadToken()) @@ -704,7 +702,7 @@ DE_PIMPL(DEDParser) // The old format. if (!ReadString(flag)) return false; - bm = blendmode_t(ded->evalFlags(flag.toUtf8().constData())); + bm = blendmode_t(ded->evalFlags(flag)); } else { @@ -713,7 +711,7 @@ DE_PIMPL(DEDParser) flag = String("bm_") + String(token); - bm = blendmode_t(ded->evalFlags(flag.toUtf8().constData())); + bm = blendmode_t(ded->evalFlags(flag)); } if (bm != BM_NORMAL) @@ -949,7 +947,7 @@ DE_PIMPL(DEDParser) de::zap(id); FINDBEGIN; - forever + for (;;) { READLABEL; RV_STR("ID", id) @@ -959,7 +957,7 @@ DE_PIMPL(DEDParser) CHECKSC; } - if (qstrlen(id)) + if (strlen(id)) { ded->addFlag(id, value); Record &flag = ded->flags.find(VAR_ID, id); @@ -1023,7 +1021,7 @@ DE_PIMPL(DEDParser) int hub = 0; int notHubMap = 0; FINDBEGIN; - forever + for (;;) { READLABEL; // ID cannot be changed when modifying @@ -1050,7 +1048,7 @@ DE_PIMPL(DEDParser) int map = 0; FINDBEGIN; - forever + for (;;) { READLABEL; RV_STR("ID", (*hubRec)[VAR_ID]) @@ -1059,10 +1057,10 @@ DE_PIMPL(DEDParser) // Add another map. if (map >= int(hubRec->geta("map").size())) { - QScopedPointer map(new Record); + std::unique_ptr map(new Record); defn::MapGraphNode(*map).resetToDefaults(); (*hubRec)["map"].array() - .add(new RecordValue(map.take(), RecordValue::OwnsRecord)); + .add(new RecordValue(map.release(), RecordValue::OwnsRecord)); } DE_ASSERT(map < int(hubRec->geta("map").size())); Record &mapRec = *hubRec->geta("map")[map].as().record(); @@ -1070,7 +1068,7 @@ DE_PIMPL(DEDParser) int exit = 0; FINDBEGIN; - forever + for (;;) { READLABEL; RV_URI("ID", mapRec[VAR_ID], "Maps") @@ -1089,7 +1087,7 @@ DE_PIMPL(DEDParser) if (source->custom) exitRec.set("custom", true); FINDBEGIN; - forever + for (;;) { READLABEL; RV_STR("ID", exitRec[VAR_ID]) @@ -1114,10 +1112,10 @@ DE_PIMPL(DEDParser) // Add another none-hub map. if (notHubMap >= int(epsd->geta("map").size())) { - QScopedPointer map(new Record); + std::unique_ptr map(new Record); defn::MapGraphNode(*map).resetToDefaults(); (*epsd)["map"].array() - .add(new RecordValue(map.take(), RecordValue::OwnsRecord)); + .add(new RecordValue(map.release(), RecordValue::OwnsRecord)); } DE_ASSERT(notHubMap < int(epsd->geta("map").size())); Record &mapRec = *epsd->geta("map")[notHubMap].as().record(); @@ -1125,7 +1123,7 @@ DE_PIMPL(DEDParser) int exit = 0; FINDBEGIN; - forever + for (;;) { READLABEL; RV_URI("ID", mapRec[VAR_ID], "Maps") @@ -1144,7 +1142,7 @@ DE_PIMPL(DEDParser) if (source->custom) exitRec.set("custom", true); FINDBEGIN; - forever + for (;;) { READLABEL; RV_STR("ID", exitRec[VAR_ID]) @@ -1498,7 +1496,7 @@ DE_PIMPL(DEDParser) int decor = 0; int layer = 0; FINDBEGIN; - forever + for (;;) { READLABEL; // ID cannot be changed when modifying @@ -1525,7 +1523,7 @@ DE_PIMPL(DEDParser) int stage = 0; FINDBEGIN; - forever + for (;;) { READLABEL; if (ISLABEL("Stage")) @@ -1545,7 +1543,7 @@ DE_PIMPL(DEDParser) Record &st = layerDef.stage(stage); FINDBEGIN; - forever + for (;;) { READLABEL; RV_URI("Texture", st["texture"], 0) // Default to "any" scheme. @@ -1579,7 +1577,7 @@ DE_PIMPL(DEDParser) int stage = 0; FINDBEGIN; - forever + for (;;) { READLABEL; RV_VEC_VAR("Pattern offset", decorDef.def()["patternOffset"], 2) @@ -1594,7 +1592,7 @@ DE_PIMPL(DEDParser) Record &st = decorDef.stage(stage); FINDBEGIN; - forever + for (;;) { READLABEL; RV_INT("Tics", st["tics"]) @@ -1662,7 +1660,7 @@ DE_PIMPL(DEDParser) if (source->custom) mdl.set("custom", true); FINDBEGIN; - forever + for (;;) { READLABEL; RV_STR("ID", mdl[VAR_ID]) @@ -1825,7 +1823,7 @@ DE_PIMPL(DEDParser) if (source->custom) music->set("custom", true); FINDBEGIN; - forever + for (;;) { READLABEL; // ID cannot be changed when modifying @@ -1866,7 +1864,7 @@ DE_PIMPL(DEDParser) if (source->custom) sky.set("custom", true); FINDBEGIN; - forever + for (;;) { READLABEL; RV_STR("ID", sky[VAR_ID]) @@ -1881,7 +1879,7 @@ DE_PIMPL(DEDParser) if (source->custom) layerDef.set("custom", true); FINDBEGIN; - forever + for (;;) { READLABEL; RV_URI("Material", layerDef["material"], 0) @@ -1917,7 +1915,7 @@ DE_PIMPL(DEDParser) if (source->custom) mdlDef.set("custom", true); FINDBEGIN; - forever + for (;;) { READLABEL; RV_STR("ID", mdlDef[VAR_ID]) @@ -1988,7 +1986,7 @@ DE_PIMPL(DEDParser) { bool negate = false; bool testCustom = false; - forever + for (;;) { ReadToken(); if (ISTOKEN("{")) @@ -2052,7 +2050,7 @@ DE_PIMPL(DEDParser) if (source->custom) sky.set("custom", true); FINDBEGIN; - forever + for (;;) { READLABEL; // ID cannot be changed when modifying @@ -2089,7 +2087,7 @@ DE_PIMPL(DEDParser) if (source->custom) layerDef.set("custom", true); FINDBEGIN; - forever + for (;;) { READLABEL; RV_URI("Material", layerDef["material"], 0) @@ -2125,7 +2123,7 @@ DE_PIMPL(DEDParser) if (source->custom) mdlDef.set("custom", true); FINDBEGIN; - forever + for (;;) { READLABEL; RV_STR("ID", mdlDef[VAR_ID]) @@ -2169,9 +2167,8 @@ DE_PIMPL(DEDParser) String buffer; if (ReadString(buffer)) { - QByteArray bufferUtf8 = buffer.toUtf8(); - txt->text = (char *) M_Realloc(txt->text, bufferUtf8.length() + 1); - qstrcpy(txt->text, bufferUtf8.constData()); + txt->text = (char *) M_Realloc(txt->text, buffer.size() + 1); + strcpy(txt->text, buffer); } else { @@ -2309,9 +2306,9 @@ DE_PIMPL(DEDParser) idx = DED_AddValue(ded, 0); ded_value_t *val = &ded->values[idx]; - QByteArray bufferUtf8 = buffer.toUtf8(); - val->text = (char *) M_Malloc(bufferUtf8.length() + 1); - qstrcpy(val->text, bufferUtf8.constData()); +// QByteArray bufferUtf8 = buffer.toUtf8(); + val->text = (char *) M_Malloc(buffer.size() + 1); + strcpy(val->text, buffer); // Compose the identifier. val->id = (char *) M_Malloc(strlen(rootStr) + strlen(label) + 1); @@ -2575,7 +2572,7 @@ DE_PIMPL(DEDParser) if (source->custom) fin.set("custom", true); FINDBEGIN; - forever + for (;;) { READLABEL; RV_STR("ID", fin[VAR_ID]) @@ -2584,8 +2581,7 @@ DE_PIMPL(DEDParser) RV_INT("Game", dummyInt) if (ISLABEL("Script")) { - String buffer; buffer.reserve(1600); - + String buffer; FINDBEGIN; ReadToken(); while (!ISTOKEN("}") && !source->atEnd) @@ -2601,7 +2597,6 @@ DE_PIMPL(DEDParser) } ReadToken(); } - buffer.squeeze(); fin.set("script", buffer); } else RV_END @@ -2624,7 +2619,7 @@ DE_PIMPL(DEDParser) defn::Decoration mainDef(decor); int light = 0; FINDBEGIN; - forever + for (;;) { READLABEL; RV_FLAGS("Flags", decor["flags"], "dcf_") @@ -2656,7 +2651,7 @@ DE_PIMPL(DEDParser) // One implicit stage. Record &st = (lightDef.stageCount()? lightDef.stage(0) : lightDef.addStage()); FINDBEGIN; - forever + for (;;) { READLABEL; RV_VEC_VAR("Offset", st["origin"], 2) @@ -2703,7 +2698,7 @@ DE_PIMPL(DEDParser) int sub = 0; FINDBEGIN; - forever + for (;;) { READLABEL; if (ISLABEL("Texture") || ISLABEL("Flat")) @@ -2718,7 +2713,7 @@ DE_PIMPL(DEDParser) ded_group_member_t *memb = &grp->members[sub]; FINDBEGIN; - forever + for (;;) { READLABEL; RV_URI("ID", &memb->material, (haveTexture? "Textures" : "Flats")) @@ -3064,7 +3059,7 @@ DE_PIMPL(DEDParser) if (!F_IsAbsolute(&tmp)) { Str_PrependChar(&tmp, '/'); - Str_Prepend(&tmp, parentDirectory.toUtf8().constData()); + Str_Prepend(&tmp, parentDirectory); } Def_ReadProcessDED(ded, String(Str_Text(&tmp))); diff --git a/doomsday/apps/libdoomsday/src/defs/dedregister.cpp b/doomsday/apps/libdoomsday/src/defs/dedregister.cpp index d35778f700..b4d5f8970e 100644 --- a/doomsday/apps/libdoomsday/src/defs/dedregister.cpp +++ b/doomsday/apps/libdoomsday/src/defs/dedregister.cpp @@ -23,8 +23,9 @@ #include #include #include -#include -#include +#include +#include +#include using namespace de; @@ -42,9 +43,9 @@ DE_PIMPL(DEDRegister) LookupFlags flags; Key(LookupFlags const &f = DefaultLookup) : flags(f) {} }; - typedef QMap Keys; + typedef Map Keys; Keys keys; - QMap parents; + Map parents; Impl(Public *i, Record &rec) : Base(i), names(&rec) { @@ -69,9 +70,9 @@ DE_PIMPL(DEDRegister) #ifdef DE_DEBUG DE_ASSERT(parents.isEmpty()); - foreach (String const &key, keys.keys()) + for (const auto &k : keys) { - DE_ASSERT(lookup(key).size() == 0); + DE_ASSERT(lookup(k.first).size() == 0); } #endif } @@ -108,10 +109,10 @@ DE_PIMPL(DEDRegister) Type lookupOperation(String const &key, String value, std::function operation) const { - auto foundKey = keys.constFind(key); - if (foundKey == keys.constEnd()) return 0; + auto foundKey = keys.find(key); + if (foundKey == keys.end()) return Type{0}; - if (!foundKey.value().flags.testFlag(CaseSensitive)) + if (!foundKey->second.flags.testFlag(CaseSensitive)) { // Case insensitive lookup is done in lower case. value = value.lower(); @@ -126,7 +127,7 @@ DE_PIMPL(DEDRegister) [] (DictionaryValue const &lut, String v) -> Record const * { TextValue const val(v); auto i = lut.elements().find(DictionaryValue::ValueRef(&val)); - if (i == lut.elements().end()) return 0; // Value not in dictionary. + if (i == lut.elements().end()) return nullptr; // Value not in dictionary. return i->second->as().record(); }); } @@ -298,18 +299,18 @@ Record &DEDRegister::appendCopy(int index) Record &DEDRegister::copy(int fromIndex, Record &to) { - QStringList omitted; + StringList omitted; omitted << "__.*"; // double-underscore // By default lookup keys are not copied, as they are used as identifiers and // therefore duplicates should not occur. - DE_FOR_EACH_CONST(Impl::Keys, i, d->keys) + for (const auto &i : d->keys) { - if (i.value().flags.testFlag(AllowCopy)) continue; - omitted << i.key(); + if (i.second.flags.testFlag(AllowCopy)) continue; + omitted << i.first; } - return to.assign((*this)[fromIndex], QRegExp(omitted.join("|"))); + return to.assign((*this)[fromIndex], RegExp(String::join(omitted, "|"))); } int DEDRegister::size() const @@ -337,7 +338,7 @@ Record *DEDRegister::tryFind(String const &key, String const &value) return const_cast(d->tryFind(key, value)); } -Record const *DEDRegister::tryFind(String const &key, String value) const +Record const *DEDRegister::tryFind(String const &key, const String &value) const { return d->tryFind(key, value); } diff --git a/doomsday/apps/libdoomsday/src/defs/episode.cpp b/doomsday/apps/libdoomsday/src/defs/episode.cpp index d6a29c73e3..d95f721566 100644 --- a/doomsday/apps/libdoomsday/src/defs/episode.cpp +++ b/doomsday/apps/libdoomsday/src/defs/episode.cpp @@ -83,7 +83,7 @@ Record *Episode::tryFindHubByMapId(String const &mapId) for (int i = 0; i < hubCount(); ++i) { Record &hubRec = hub(i); - foreach (Value *mapIt, hubRec.geta("map").elements()) + for (auto *mapIt : hubRec.geta("map").elements()) { Record &mgNodeDef = mapIt->as().dereference(); if (mapUri == de::makeUri(mgNodeDef.gets(VAR_ID))) @@ -93,7 +93,7 @@ Record *Episode::tryFindHubByMapId(String const &mapId) } } } - return 0; // Not found. + return nullptr; // Not found. } Record *Episode::tryFindMapGraphNode(String const &mapId) @@ -105,7 +105,7 @@ Record *Episode::tryFindMapGraphNode(String const &mapId) for (int i = 0; i < hubCount(); ++i) { Record const &hubRec = hub(i); - foreach (Value *mapIt, hubRec.geta("map").elements()) + for (Value *mapIt : hubRec.geta("map").elements()) { Record &mgNodeDef = mapIt->as().dereference(); if (mapUri == de::makeUri(mgNodeDef.gets(VAR_ID))) @@ -115,7 +115,7 @@ Record *Episode::tryFindMapGraphNode(String const &mapId) } } // Try the non-hub maps. - foreach (Value *mapIt, geta("map").elements()) + for (Value *mapIt : geta("map").elements()) { Record &mgNodeDef = mapIt->as().dereference(); if (mapUri == de::makeUri(mgNodeDef.gets(VAR_ID))) @@ -135,7 +135,7 @@ de::Record *Episode::tryFindMapGraphNodeByWarpNumber(int warpNumber) for (int i = 0; i < hubCount(); ++i) { Record const &hubRec = hub(i); - foreach (Value *mapIt, hubRec.geta("map").elements()) + for (Value *mapIt : hubRec.geta("map").elements()) { Record &mgNodeDef = mapIt->as().dereference(); if (mgNodeDef.geti("warpNumber") == warpNumber) @@ -145,7 +145,7 @@ de::Record *Episode::tryFindMapGraphNodeByWarpNumber(int warpNumber) } } // Try the non-hub maps. - foreach (Value *mapIt, geta("map").elements()) + for (Value *mapIt : geta("map").elements()) { Record &mgNodeDef = mapIt->as().dereference(); if (mgNodeDef.geti("warpNumber") == warpNumber) @@ -154,7 +154,7 @@ de::Record *Episode::tryFindMapGraphNodeByWarpNumber(int warpNumber) } } } - return 0; // Not found. + return nullptr; // Not found. } } // namespace defn diff --git a/doomsday/apps/libdoomsday/src/defs/mapinfo.cpp b/doomsday/apps/libdoomsday/src/defs/mapinfo.cpp index bf903ede17..4729745813 100644 --- a/doomsday/apps/libdoomsday/src/defs/mapinfo.cpp +++ b/doomsday/apps/libdoomsday/src/defs/mapinfo.cpp @@ -50,9 +50,9 @@ void MapInfo::resetToDefaults() def().addText ("execute", ""); def().addText (QStringLiteral("intermissionBg"), ""); - QScopedPointer sky(new Record); + std::unique_ptr sky(new Record); Sky(*sky).resetToDefaults(); - def().add ("sky", sky.take()); + def().add ("sky", sky.release()); } } // namespace defn diff --git a/doomsday/apps/libdoomsday/src/defs/sprite.cpp b/doomsday/apps/libdoomsday/src/defs/sprite.cpp index 7110b9a4bb..a20a1ff1c2 100644 --- a/doomsday/apps/libdoomsday/src/defs/sprite.cpp +++ b/doomsday/apps/libdoomsday/src/defs/sprite.cpp @@ -32,10 +32,10 @@ using namespace de; namespace defn { -static QString const VAR_VIEWS ("views"); -static QString const VAR_FRONT_ONLY("frontOnly"); -static QString const VAR_MATERIAL ("material"); // UriValue -static QString const VAR_MIRROR_X ("mirrorX"); +static String const VAR_VIEWS ("views"); +static String const VAR_FRONT_ONLY("frontOnly"); +static String const VAR_MATERIAL ("material"); // UriValue +static String const VAR_MIRROR_X ("mirrorX"); //--------------------------------------------------------------------------------------- diff --git a/doomsday/apps/libdoomsday/src/doomsdayapp.cpp b/doomsday/apps/libdoomsday/src/doomsdayapp.cpp index 2473520002..e11906c336 100644 --- a/doomsday/apps/libdoomsday/src/doomsdayapp.cpp +++ b/doomsday/apps/libdoomsday/src/doomsdayapp.cpp @@ -48,20 +48,21 @@ #include #include #include +#include #include #include #include #include +#include #include #include #include #include -#include -#include -#include -#include -#include +//#include +//#include +//#include +//#include #ifdef WIN32 # define WIN32_LEAN_AND_MEAN @@ -83,24 +84,24 @@ DE_PIMPL(DoomsdayApp) { std::string ddBasePath; // Doomsday root directory is at...? - Binder binder; - bool initialized = false; - bool gameBeingChanged = false; - bool shuttingDown = false; - Plugins plugins; - Games games; - Game *currentGame = nullptr; - GameProfile adhocProfile; - GameProfile const *currentProfile = nullptr; - StringList preGamePackages; - GameProfiles gameProfiles; - BusyMode busyMode; - Players players; - res::Bundles dataBundles; + Binder binder; + bool initialized = false; + bool gameBeingChanged = false; + bool shuttingDown = false; + Plugins plugins; + Games games; + Game * currentGame = nullptr; + GameProfile adhocProfile; + GameProfile const * currentProfile = nullptr; + StringList preGamePackages; + GameProfiles gameProfiles; + BusyMode busyMode; + Players players; + res::Bundles dataBundles; shell::PackageDownloader packageDownloader; - SaveGames saveGames; - LoopCallback mainCall; - QTimer configSaveTimer; + SaveGames saveGames; + LoopCallback mainCall; + Timer configSaveTimer; #ifdef WIN32 HINSTANCE hInstance = NULL; @@ -123,7 +124,7 @@ DE_PIMPL(DoomsdayApp) GameChangeScriptAudience scriptAudienceForGameChange; - Impl(Public *i, Players::Constructor playerConstructor) + Impl(Public *i, const Players::Constructor &playerConstructor) : Base(i) , players(playerConstructor) { @@ -144,9 +145,9 @@ DE_PIMPL(DoomsdayApp) audienceForFolderPopulation += this; // Periodically save the configuration files (after they've been changed). - configSaveTimer.setInterval(1000); + configSaveTimer.setInterval(1.0); configSaveTimer.setSingleShot(false); - QObject::connect(&configSaveTimer, &QTimer::timeout, [this] () + configSaveTimer += [this]() { DE_FOR_PUBLIC_AUDIENCE2(PeriodicAutosave, i) { @@ -155,7 +156,7 @@ DE_PIMPL(DoomsdayApp) i->periodicAutosave(); } } - }); + }; configSaveTimer.start(); // File system extensions. @@ -282,7 +283,7 @@ DE_PIMPL(DoomsdayApp) { auto &cmdLine = CommandLine::get(); cmdLine.makeAbsolutePath(pos); - Folder &argFolder = FS::get().makeFolder(String("/sys/cmdline/arg%1").arg(pos, 3, 10, QChar('0'))); + Folder &argFolder = FS::get().makeFolder(String::format("/sys/cmdline/arg%03i", pos)); File const &argFile = DirectoryFeed::manuallyPopulateSingleFile (cmdLine.at(pos), argFolder); // For future reference, store the name of the actual intended file as @@ -293,8 +294,9 @@ DE_PIMPL(DoomsdayApp) catch (Error const &er) { throw Error("DoomsdayApp::initCommandLineFiles", - QString("Problem with file path in command line argument %1: %2") - .arg(pos).arg(er.asText())); + stringf("Problem with file path in command line argument %u: %s", + pos, + er.asText().c_str())); } }); } @@ -346,7 +348,7 @@ DE_PIMPL(DoomsdayApp) // Check for games installed from GOG.com. if (!cmdLine.has("-nogog")) { - foreach (NativePath gogPath, gogComPaths()) + for (const NativePath &gogPath : gogComPaths()) { attachWadFeed("GOG.com", gogPath); } @@ -364,8 +366,7 @@ DE_PIMPL(DoomsdayApp) if (getenv("DOOMWADPATH")) { // Interpreted similarly to the PATH variable. - QStringList paths = String(getenv("DOOMWADPATH")) - .split(ENV_PATH_SEP_CHAR, String::SkipEmptyParts); + StringList paths = String(getenv("DOOMWADPATH")).split(ENV_PATH_SEP_CHAR); while (!paths.isEmpty()) { attachWadFeed(_E(m) "DOOMWADPATH" _E(.), startupPath / paths.takeLast()); @@ -390,7 +391,7 @@ DE_PIMPL(DoomsdayApp) // Command line paths. if (auto arg = cmdLine.check("-iwad", 1)) // has at least one parameter { - for (dint p = arg.pos + 1; p < cmdLine.count(); ++p) + for (dint p = arg.pos + 1; p < cmdLine.sizei(); ++p) { if (cmdLine.isOption(p)) break; @@ -430,7 +431,7 @@ DE_PIMPL(DoomsdayApp) // Command line paths. if (auto arg = cmdLine.check("-packs", 1)) { - for (dint p = arg.pos + 1; p < cmdLine.count(); ++p) + for (dint p = arg.pos + 1; p < cmdLine.sizei(); ++p) { if (cmdLine.isOption(p)) break; @@ -538,10 +539,8 @@ void DoomsdayApp::initialize() auto &fs = FileSystem::get(); // Folder for temporary native files. - NativePath tmpPath = NativePath(QStandardPaths::writableLocation(QStandardPaths::TempLocation)) - / ("doomsday-" + QString::number(qApp->applicationPid())); Folder &tmpFolder = fs.makeFolder("/tmp"); - tmpFolder.attach(new DirectoryFeed(tmpPath, + tmpFolder.attach(new DirectoryFeed(App::tempPath(), DirectoryFeed::AllowWrite | DirectoryFeed::CreateIfMissing | DirectoryFeed::OnlyThisFolder)); @@ -582,14 +581,14 @@ void DoomsdayApp::initPackageFolders() d->initPackageFolders(); } -QList DoomsdayApp::filesFromCommandLine() const +List DoomsdayApp::filesFromCommandLine() const { - QList files; + List files; FS::locate("/sys/cmdline").forContents([&files] (String name, File &file) { try { - if (name.startsWith("arg")) + if (name.beginsWith("arg")) { files << &FS::locate(file.as().objectNamespace().gets("argPath")); } @@ -671,21 +670,21 @@ NativePath DoomsdayApp::steamBasePath() } return ""; #elif MACOSX - return NativePath(QDir::homePath()) / "Library/Application Support/Steam/"; + return NativePath::homePath() / "Library/Application Support/Steam/"; #else /// @todo Where are Steam apps located on Linux? return ""; #endif } -QList DoomsdayApp::gogComPaths() +List DoomsdayApp::gogComPaths() { - QList paths; + List paths; #ifdef WIN32 // Look up all the Doom GOG.com paths. - QList const subfolders({ "", "doom2", "master\\wads", "Plutonia", "TNT" }); - QList const gogIds ({ "1435827232", "1435848814", "1435848742" }); + StringList const subfolders({ "", "doom2", "master\\wads", "Plutonia", "TNT" }); + StringList const gogIds ({ "1435827232", "1435848814", "1435848742" }); foreach (auto gogId, gogIds) { NativePath basePath = QSettings("HKEY_LOCAL_MACHINE\\Software\\GOG.com\\Games\\" + gogId, @@ -766,12 +765,15 @@ bool DoomsdayApp::isGameLoaded() StringList DoomsdayApp::loadedPackagesAffectingGameplay() // static { StringList ids = PackageLoader::get().loadedPackageIdsInOrder(); - QMutableListIterator iter(ids); - while (iter.hasNext()) + for (auto iter = ids.begin(); iter != ids.end(); ) + { + if (!GameStateFolder::isPackageAffectingGameplay(*iter)) { - if (!GameStateFolder::isPackageAffectingGameplay(iter.next())) + iter = ids.erase(iter); + } + else { - iter.remove(); + ++iter; } } return ids; @@ -800,11 +802,11 @@ void DoomsdayApp::unloadGame(GameProfile const &/*upcomingGame*/) } // Unload all packages that weren't loaded before the game was loaded. - for (String const &packageId : PackageLoader::get().loadedPackages().keys()) + for (const auto &i : PackageLoader::get().loadedPackages()) { - if (!d->preGamePackages.contains(packageId)) + if (!d->preGamePackages.contains(i.first)) { - PackageLoader::get().unload(packageId); + PackageLoader::get().unload(i.first); } } @@ -904,8 +906,8 @@ void DoomsdayApp::makeGameCurrent(const GameProfile &profile) if (!plugins().exchangeGameEntryPoints(newGame.pluginId())) { throw Plugins::EntryPointError("DoomsdayApp::makeGameCurrent", - "Failed to exchange entrypoints with plugin " + - QString::number(newGame.pluginId())); + stringf("Failed to exchange entrypoints with plugin %i", + newGame.pluginId())); } } @@ -942,7 +944,7 @@ extern int loadGameStartupResourcesBusyWorker(void *context); extern int loadAddonResourcesBusyWorker(void *context); bool DoomsdayApp::changeGame(GameProfile const &profile, - std::function gameActivationFunc, + const std::function &gameActivationFunc, Behaviors behaviors) { const auto &newGame = profile.game(); diff --git a/doomsday/apps/libdoomsday/src/dualstring.cpp b/doomsday/apps/libdoomsday/src/dualstring.cpp index f3df8100d6..9a3b78271a 100644 --- a/doomsday/apps/libdoomsday/src/dualstring.cpp +++ b/doomsday/apps/libdoomsday/src/dualstring.cpp @@ -1,3 +1,5 @@ +#if 0 /* obsolete */ + /** @file dualstring.cpp * * Utility class for strings that need both Unicode and C-string access. @@ -102,3 +104,5 @@ const char* DualString::utf8CStr() { return Str_Text(toStrUtf8()); } + +#endif // 0 diff --git a/doomsday/apps/libdoomsday/src/filesys/datafolder.cpp b/doomsday/apps/libdoomsday/src/filesys/datafolder.cpp index 6c94e836a2..1fc2a84bbd 100644 --- a/doomsday/apps/libdoomsday/src/filesys/datafolder.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/datafolder.cpp @@ -60,7 +60,7 @@ String DataFolder::describe() const String const feedDesc = describeFeeds(); if (!feedDesc.isEmpty()) { - desc += String(" (%1)").arg(feedDesc); + desc += String::format(" (%s)", feedDesc.c_str()); } return desc; diff --git a/doomsday/apps/libdoomsday/src/filesys/file.cpp b/doomsday/apps/libdoomsday/src/filesys/file.cpp index 65a276aa5a..2ef600b17b 100644 --- a/doomsday/apps/libdoomsday/src/filesys/file.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/file.cpp @@ -70,7 +70,7 @@ FileHandle &File1::handle() return *handle_; } -Uri File1::composeUri(QChar delimiter) const +Uri File1::composeUri(Char delimiter) const { return Uri(path_, RC_NULL, delimiter); } diff --git a/doomsday/apps/libdoomsday/src/filesys/fileid.cpp b/doomsday/apps/libdoomsday/src/filesys/fileid.cpp index c5cdaf55b6..2bf158400c 100644 --- a/doomsday/apps/libdoomsday/src/filesys/fileid.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/fileid.cpp @@ -22,9 +22,6 @@ * 02110-1301 USA */ -#include -#include - #include #include @@ -33,7 +30,7 @@ using namespace de; -FileId::FileId(Md5Hash _md5) +FileId::FileId(const Md5Hash& _md5) : md5_(_md5.left(16)) #ifdef DE_DEBUG , path_("unknown-path") @@ -71,16 +68,10 @@ bool FileId::operator != (FileId const &other) const String FileId::asText() const { - String txt; - txt.reserve(32); - for (int i = 0; i < 16; ++i) - { - txt += String("%1").arg(String::number((byte)md5_.at(i), 16), 2, '0'); - } - return txt; + return md5_.asHexadecimalText(); } -FileId FileId::fromPath(String path) +FileId FileId::fromPath(const String& path) { FileId fileId = FileId(hash(path)); #ifdef DE_DEBUG @@ -92,14 +83,12 @@ FileId FileId::fromPath(String path) FileId::Md5Hash FileId::hash(String path) { // Ensure we've a normalized path. - if (QDir::isRelativePath(path)) - { - path = App_BasePath() / path; - } + path = App_BasePath() / path; #if defined(WIN32) || defined(MACOSX) // This is a case insensitive operation. - path = path.toUpper(); + path = path.upper(); #endif - return QCryptographicHash::hash(path.toUtf8(), QCryptographicHash::Md5); + + return Block(path).md5Hash(); } diff --git a/doomsday/apps/libdoomsday/src/filesys/filetype.cpp b/doomsday/apps/libdoomsday/src/filesys/filetype.cpp index 560db3f6d0..e4c4379f46 100644 --- a/doomsday/apps/libdoomsday/src/filesys/filetype.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/filetype.cpp @@ -27,15 +27,15 @@ static FileTypes fileTypeMap; void DD_AddFileType(FileType const &ftype) { - fileTypeMap.insert(ftype.name().toLower(), &ftype); + fileTypeMap.insert(ftype.name().lower(), &ftype); } FileType const &DD_FileTypeByName(String name) { if (!name.isEmpty()) { - FileTypes::const_iterator found = fileTypeMap.constFind(name.toLower()); - if (found != fileTypeMap.constEnd()) return **found; + FileTypes::const_iterator found = fileTypeMap.find(name.lower()); + if (found != fileTypeMap.end()) return *found->second; } return nullFileType; // Not found. } @@ -46,7 +46,7 @@ FileType const &DD_GuessFileTypeFromFileName(String path) { DE_FOR_EACH_CONST(FileTypes, i, fileTypeMap) { - FileType const &ftype = **i; + FileType const &ftype = *i->second; if (ftype.fileNameIsKnown(path)) return ftype; } diff --git a/doomsday/apps/libdoomsday/src/filesys/fs_main.cpp b/doomsday/apps/libdoomsday/src/filesys/fs_main.cpp index 7850621f12..d909f21407 100644 --- a/doomsday/apps/libdoomsday/src/filesys/fs_main.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/fs_main.cpp @@ -33,9 +33,6 @@ #include "doomsday/filesys/zip.h" #include -#include -#include -#include #include #include #include @@ -50,7 +47,7 @@ extern uint F_GetLastModified(char const *path); static FS1 *fileSystem; -typedef QList FileIds; +typedef List FileIds; /** * Virtual (file) path => Lump name mapping. @@ -59,8 +56,8 @@ typedef QList FileIds; * unique, several of the existing algorithms which match using patterns * assume they are sorted in a quasi load ordering. */ -typedef QPair LumpMapping; -typedef QList LumpMappings; +typedef std::pair LumpMapping; +typedef List LumpMappings; /** * Virtual file-directory mapping. @@ -70,8 +67,8 @@ typedef QList LumpMappings; * unique, several of the existing algorithms which match using patterns * assume they are sorted in a quasi load ordering. */ -typedef QPair PathMapping; -typedef QList PathMappings; +typedef std::pair PathMapping; +typedef List PathMappings; /** * @note Performance is O(n). @@ -106,7 +103,7 @@ static FS1::FileList::iterator findListFileByPath(FS1::FileList &list, String pa for (i = list.begin(); i != list.end(); ++i) { File1 &file = (*i)->file(); - if (!file.composePath().compare(path, Qt::CaseInsensitive)) + if (!file.composePath().compare(path, CaseInsensitive)) { break; // This is the node we are looking for. } @@ -127,23 +124,24 @@ static bool applyPathMapping(ddstring_t *path, PathMapping const &vdm); */ static bool matchFileName(String const &string, String const &pattern) { - static QChar const ASTERISK('*'); - static QChar const QUESTION_MARK('?'); + static const Char ASTERISK('*'); + static const Char QUESTION_MARK('?'); - QChar const *in = string.constData(), *st = pattern.constData(); + mb_iterator in = string.begin(); + mb_iterator st = pattern.begin(); - while (!in->isNull()) + while (*in) { if (*st == ASTERISK) { - st++; + ++st; continue; } - if (*st != QUESTION_MARK && st->toLower() != in->toLower()) + if (*st != QUESTION_MARK && towlower(*st) != towlower(*in)) { // A mismatch. Hmm. Go back to a previous '*'. - while (st >= pattern && *st != ASTERISK) { st--; } + while (st >= pattern && *st != ASTERISK) { --st; } if (st < pattern) return false; // No match! @@ -151,16 +149,16 @@ static bool matchFileName(String const &string, String const &pattern) } // This character of the pattern is OK. - st++; - in++; + ++st; + ++in; } // Match is good if the end of the pattern was reached. // Skip remaining asterisks. - while (*st == ASTERISK) { st++; } + while (*st == ASTERISK) { ++st; } - return st->isNull(); + return *st == 0; } DE_PIMPL(FS1) @@ -205,18 +203,18 @@ DE_PIMPL(FS1) { DE_FOR_EACH(Schemes, i, schemes) { - delete *i; + delete i->second; } schemes.clear(); } /// @return @c true if the FileId associated with @a path was released. - bool releaseFileId(String path) + bool releaseFileId(const String& path) { if (!path.isEmpty()) { FileId fileId = FileId::fromPath(path); - FileIds::iterator place = qLowerBound(fileIds.begin(), fileIds.end(), fileId); + FileIds::iterator place = std::lower_bound(fileIds.begin(), fileIds.end(), fileId); if (place != fileIds.end() && *place == fileId) { LOGDEV_RES_XVERBOSE_DEBUGONLY("Released FileId %s - \"%s\"", *place << fileId.path()); @@ -232,7 +230,7 @@ DE_PIMPL(FS1) loadedFilesCRC = 0; // Unload in reverse load order. - for (int i = loadedFiles.size() - 1; i >= 0; i--) + for (int i = loadedFiles.sizei() - 1; i >= 0; i--) { File1 &file = loadedFiles[i]->file(); if (!index || index->catalogues(file)) @@ -291,8 +289,8 @@ DE_PIMPL(FS1) {} // Ignore this error. // Try a wider search of the whole virtual file system. - QScopedPointer file(openFile(search.path(), "rb", 0, true /* allow duplicates */)); - if (!file.isNull()) + std::unique_ptr file(openFile(search.path(), "rb", 0, true /* allow duplicates */)); + if (file) { return file->composePath(); } @@ -305,10 +303,7 @@ DE_PIMPL(FS1) if (path.isEmpty()) return 0; // We must have an absolute path - prepend the base path if necessary. - if (QDir::isRelativePath(path)) - { - path = App_BasePath() / path; - } + path = NativePath(App_BasePath()) / path; // First check the Zip lump index. lumpnum_t lumpNum = zipFileIndex.findLast(path); @@ -351,7 +346,7 @@ DE_PIMPL(FS1) // First try a real native file at this absolute path. NativePath nativePath = NativePath(path); - FILE *nativeFile = fopen(nativePath.toUtf8().constData(), mode); + FILE *nativeFile = fopen(nativePath, mode); if (nativeFile) { foundPath = nativePath.expand().withSeparators('/'); @@ -361,16 +356,15 @@ DE_PIMPL(FS1) // Nope. Any applicable virtual directory mappings? if (!pathMappings.empty()) { - QByteArray pathUtf8 = path.toUtf8(); AutoStr *mapped = AutoStr_NewStd(); DE_FOR_EACH_CONST(PathMappings, i, pathMappings) { - Str_Set(mapped, pathUtf8.constData()); + Str_Set(mapped, path); if (!applyPathMapping(mapped, *i)) continue; // The mapping was successful. nativePath = NativePath(Str_Text(mapped)); - nativeFile = fopen(nativePath.toUtf8().constData(), mode); + nativeFile = fopen(nativePath, mode); if (nativeFile) { foundPath = nativePath.expand().withSeparators('/'); @@ -434,7 +428,7 @@ DE_PIMPL(FS1) hndl = FileHandle::fromNativeFile(*found, baseOffset); // Prepare the temporary info descriptor. - info = FileInfo(F_GetLastModified(foundPath.toUtf8().constData())); + info = FileInfo(F_GetLastModified(foundPath)); } } @@ -459,7 +453,7 @@ DE_PIMPL(FS1) FS1::FS1() : d(new Impl(this)) {} -FS1::Scheme &FS1::createScheme(String name, Scheme::Flags flags) +FS1::Scheme &FS1::createScheme(const String& name, Flags flags) { DE_ASSERT(name.length() >= Scheme::min_name_length); @@ -468,7 +462,7 @@ FS1::Scheme &FS1::createScheme(String name, Scheme::Flags flags) // Create a new scheme. Scheme *newScheme = new Scheme(name, flags); - d->schemes.insert(name.toLower(), newScheme); + d->schemes.insert(name.lower(), newScheme); return *newScheme; } @@ -544,10 +538,7 @@ File1 &FS1::find(de::Uri const &search) String searchPath = search.resolved(); // Convert to an absolute path. - if (!QDir::isAbsolutePath(searchPath)) - { - searchPath = App_BasePath() / searchPath; - } + searchPath = NativePath(App_BasePath()) / searchPath; FileList::iterator found = findListFileByPath(d->loadedFiles, searchPath); if (found != d->loadedFiles.end()) @@ -592,13 +583,13 @@ String FS1::findPath(de::Uri const &search, int flags, ResourceClass &rclass) /* * Try each expected file type name extension for this resource class. */ - String searchPathWithoutFileNameExtension = searchPath.fileNamePath() / searchPath.fileNameWithoutExtension(); + String searchPathWithoutFileNameExtension = + String(searchPath.fileNamePath()) / searchPath.fileNameWithoutExtension(); DE_FOR_EACH_CONST(ResourceClass::FileTypes, typeIt, rclass.fileTypes()) { - DE_FOR_EACH_CONST(QStringList, i, (*typeIt)->knownFileNameExtensions()) + for (auto &ext : (*typeIt)->knownFileNameExtensions()) { - String const &ext = *i; String found = d->findPath(de::Uri(search.scheme(), searchPathWithoutFileNameExtension + ext)); if (!found.isEmpty()) return found; } @@ -664,7 +655,7 @@ int FS1::unloadAllNonStartupFiles() // Perform non-startup file unloading (in reverse load order). int numUnloadedFiles = 0; - for (int i = d->loadedFiles.size() - 1; i >= 0; i--) + for (int i = d->loadedFiles.sizei() - 1; i >= 0; i--) { File1 &file = d->loadedFiles[i]->file(); if (file.hasStartup()) continue; @@ -734,7 +725,7 @@ lumpnum_t FS1::lumpNumForName(String name) void FS1::releaseFile(File1 &file) { - for (int i = d->openFiles.size() - 1; i >= 0; i--) + for (int i = d->openFiles.sizei() - 1; i >= 0; i--) { FileHandle &hndl = *(d->openFiles[i]); if (&hndl.file() == &file) @@ -802,10 +793,7 @@ int FS1::findAllPaths(Path searchPattern, int flags, FS1::PathList &found) int const numFoundSoFar = found.count(); // We must have an absolute path - prepend the base path if necessary. - if (!QDir::isAbsolutePath(searchPattern)) - { - searchPattern = App_BasePath() / searchPattern; - } + searchPattern = Path(App_BasePath()) / searchPattern; /* * Check the Zip directory. @@ -859,15 +847,15 @@ int FS1::findAllPaths(Path searchPattern, int flags, FS1::PathList &found) String searchDirectory = searchPattern.toString().fileNamePath(); if (!searchDirectory.isEmpty()) { - QByteArray searchDirectoryUtf8 = searchDirectory.toUtf8(); +// QByteArray searchDirectoryUtf8 = searchDirectory.toUtf8(); PathList nativeFilePaths; AutoStr *wildPath = AutoStr_NewStd(); - Str_Reserve(wildPath, searchDirectory.length() + 2 + 16); // Conservative estimate. + Str_Reserve(wildPath, searchDirectory.size() + 2 + 16); // Conservative estimate. for (int i = -1; i < (int)d->pathMappings.count(); ++i) { Str_Clear(wildPath); - Str_Appendf(wildPath, "%s/", searchDirectoryUtf8.constData()); + Str_Appendf(wildPath, "%s/", searchDirectory.c_str()); if (i > -1) { @@ -896,7 +884,7 @@ int FS1::findAllPaths(Path searchPattern, int flags, FS1::PathList &found) } // Sort the native file paths. - qSort(nativeFilePaths.begin(), nativeFilePaths.end()); + std::sort(nativeFilePaths.begin(), nativeFilePaths.end()); // Add the native file paths to the found results. found.append(nativeFilePaths); @@ -950,9 +938,10 @@ File1 &FS1::interpret(FileHandle &hndl, String filePath, FileInfo const &info) FileHandle &FS1::openFile(String const &path, String const &mode, size_t baseOffset, bool allowDuplicate) { #ifdef DE_DEBUG - for (int i = 0; i < mode.length(); ++i) + //for (int i = 0; i < mode.length(); ++i) + for (Char i : mode) { - if (mode[i] != 'r' && mode[i] != 't' && mode[i] != 'b' && mode[i] != 'f') + if (i != 'r' && i != 't' && i != 'b' && i != 'f') throw Error("FS1::openFile", "Unknown argument in mode string '" + mode + "'"); } #endif @@ -978,8 +967,8 @@ bool FS1::accessFile(de::Uri const &search) { try { - QScopedPointer file(d->openFile(search.resolved(), "rb", 0, true /* allow duplicates */)); - return !file.isNull(); + std::unique_ptr file(d->openFile(search.resolved(), "rb", 0, true /* allow duplicates */)); + return bool(file); } catch (de::Uri::ResolveError const &er) { @@ -994,7 +983,7 @@ void FS1::addPathLumpMapping(String lumpName, String destination) if (lumpName.isEmpty() || destination.isEmpty()) return; // We require an absolute path - prepend the CWD if necessary. - if (QDir::isRelativePath(destination)) + if (NativePath(destination).isRelative()) { String workPath = DE_APP->currentWorkPath().withSeparators('/'); destination = workPath / destination; @@ -1005,7 +994,7 @@ void FS1::addPathLumpMapping(String lumpName, String destination) for (; found != d->lumpMappings.end(); ++found) { LumpMapping const &ldm = *found; - if (!ldm.first.compare(destination, Qt::CaseInsensitive)) + if (!ldm.first.compare(destination, CaseInsensitive)) break; } @@ -1035,14 +1024,15 @@ void FS1::clearPathLumpMappings() static bool applyPathMapping(ddstring_t *path, PathMapping const &pm) { if (!path) return false; - QByteArray destUtf8 = pm.first.toUtf8(); - AutoStr *dest = AutoStr_FromTextStd(destUtf8.constData()); - if (qstrnicmp(Str_Text(path), Str_Text(dest), Str_Length(dest))) return false; +// QByteArray destUtf8 = pm.first.toUtf8(); + const auto &dest = pm.first; +// AutoStr *dest = AutoStr_FromTextStd(dest); + if (iCmpStrNCase(Str_Text(path), dest, dest.size())) return false; // Replace the beginning with the source path. - QByteArray sourceUtf8 = pm.second.toUtf8(); - AutoStr *temp = AutoStr_FromTextStd(sourceUtf8.constData()); - Str_PartAppend(temp, Str_Text(path), pm.first.length(), Str_Length(path) - pm.first.length()); + const auto &source = pm.second; + AutoStr *temp = AutoStr_FromTextStd(source); + Str_PartAppend(temp, Str_Text(path), pm.first.size(), Str_Length(path) - pm.first.size()); Str_Copy(path, temp); return true; } @@ -1056,7 +1046,7 @@ void FS1::addPathMapping(String source, String destination) for (; found != d->pathMappings.end(); ++found) { PathMapping const &pm = *found; - if (!pm.second.compare(source, Qt::CaseInsensitive)) + if (!pm.second.compare(source, CaseInsensitive)) break; } @@ -1102,22 +1092,22 @@ void FS1::printDirectory(Path path) } } -bool FS1::knownScheme(String name) +bool FS1::knownScheme(const String& name) { if (!name.isEmpty()) { - Schemes::iterator found = d->schemes.find(name.toLower()); + Schemes::iterator found = d->schemes.find(name.lower()); if (found != d->schemes.end()) return true; } return false; } -FS1::Scheme &FS1::scheme(String name) +FS1::Scheme &FS1::scheme(const String& name) { if (!name.isEmpty()) { - Schemes::iterator found = d->schemes.find(name.toLower()); - if (found != d->schemes.end()) return **found; + Schemes::iterator found = d->schemes.find(name.lower()); + if (found != d->schemes.end()) return *found->second; } /// @throw UnknownSchemeError An unknown scheme was referenced. throw UnknownSchemeError("FS1::scheme", "No scheme found matching '" + name + "'"); diff --git a/doomsday/apps/libdoomsday/src/filesys/fs_scheme.cpp b/doomsday/apps/libdoomsday/src/filesys/fs_scheme.cpp index 4a118a6deb..8bae7ffaab 100644 --- a/doomsday/apps/libdoomsday/src/filesys/fs_scheme.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/fs_scheme.cpp @@ -19,9 +19,6 @@ * 02110-1301 USA */ -#include -#include - #include #include #include @@ -143,9 +140,9 @@ struct NameHash { hash_type hashKey = 0; int op = 0; - for (int i = 0; i < str.length(); ++i) + for (Char ch : str) { - ushort unicode = str.at(i).toLower().unicode(); + Char unicode = towlower(ch); switch (op) { case 0: hashKey ^= unicode; ++op; break; @@ -165,7 +162,7 @@ struct FS1::Scheme::Impl String name; /// Flags which govern behavior. - FS1::Scheme::Flags flags; + Flags flags; /// Associated path directory. /// @todo It should not be necessary for a unique directory per scheme. @@ -184,7 +181,7 @@ struct FS1::Scheme::Impl /// Each set is in order of greatest-importance, right to left. FS1::Scheme::SearchPaths searchPaths; - Impl(FS1::Scheme &d, String _name, FS1::Scheme::Flags _flags) + Impl(FS1::Scheme &d, String _name, Flags _flags) : self(d), name(_name), flags(_flags), directory(), rootNode(0), nameHash(), nameHashIsDirty(true) {} @@ -217,10 +214,10 @@ struct FS1::Scheme::Impl */ void addFromSearchPaths(FS1::PathGroup group) { - for (FS1::Scheme::SearchPaths::const_iterator i = searchPaths.find(group); - i != searchPaths.end() && i.key() == group; ++i) + const auto found = searchPaths.equal_range(group); + for (auto i = found.first; i != found.second; ++i) { - addFromSearchPath(*i); + addFromSearchPath(i->second); } } @@ -229,12 +226,12 @@ struct FS1::Scheme::Impl if (path.isEmpty()) return 0; // Try to make it a relative path. - if (QDir::isAbsolutePath(path)) + if (NativePath(path).isAbsolute()) { String const basePath = App_BasePath(); if (path.beginsWith(basePath)) { - path = path.mid(basePath.length() + 1); + path = path.substr(basePath.sizeb() + 1); } } @@ -276,8 +273,10 @@ struct FS1::Scheme::Impl * param isFolder @c true = @a filePath is a folder in the virtual file system. * @param flags @ref searchPathFlags */ - void addDirectoryPathAndMaybeDescendBranch(bool descendBranch, - String filePath, bool /*isFolder*/, int flags) + void addDirectoryPathAndMaybeDescendBranch(bool descendBranch, + const String &filePath, + bool /*isFolder*/, + int flags) { // Add this path to the directory. UserDataNode *node = addDirectoryPath(filePath); @@ -294,7 +293,7 @@ struct FS1::Scheme::Impl // Process it again? DE_FOR_EACH_CONST(PathTree::Nodes, i, directory.leafNodes()) { - PathTree::Node &sibling = **i; + PathTree::Node &sibling = *i->second; if (&sibling.parent() == node) { self.add(sibling); @@ -323,7 +322,7 @@ struct FS1::Scheme::Impl FS1::Scheme::Scheme(String symbolicName, Flags flags) { - d = new Impl(*this, symbolicName, flags); + d = new Impl(*this, std::move(symbolicName), flags); } FS1::Scheme::~Scheme() @@ -445,15 +444,15 @@ bool FS1::Scheme::addSearchPath(SearchPath const &search, FS1::PathGroup group) DE_FOR_EACH(SearchPaths, i, d->searchPaths) { // Compare using the unresolved textual representations. - if (!i->asText().compareWithoutCase(search.asText())) + if (!i->second.asText().compareWithoutCase(search.asText())) { - i->setFlags(search.flags()); + i->second.setFlags(search.flags()); return true; } } // Prepend to the path list - newer paths have priority. - d->searchPaths.insert(group, search); + d->searchPaths.insert(std::make_pair(group, search)); LOGDEV_RES_MSG("\"%s\" added to scheme '%s' (group:%s)") << search << name() << nameForPathGroup(group); @@ -463,7 +462,7 @@ bool FS1::Scheme::addSearchPath(SearchPath const &search, FS1::PathGroup group) void FS1::Scheme::clearSearchPathGroup(FS1::PathGroup group) { - d->searchPaths.remove(group); + d->searchPaths.erase(group); } void FS1::Scheme::clearAllSearchPaths() @@ -476,7 +475,7 @@ FS1::Scheme::SearchPaths const &FS1::Scheme::allSearchPaths() const return d->searchPaths; } -int FS1::Scheme::findAll(String name, FoundNodes &found) +int FS1::Scheme::findAll(const String& name, FoundNodes &found) { int numFoundSoFar = found.count(); @@ -500,7 +499,7 @@ int FS1::Scheme::findAll(String name, FoundNodes &found) FileRef &fileRef = hashNode->fileRef; PathTree::Node &node = fileRef.directoryNode(); - if (!name.isEmpty() && !node.name().beginsWith(name, String::CaseInsensitive)) continue; + if (!name.isEmpty() && !node.name().beginsWith(name, CaseInsensitive)) continue; found.push_back(&node); } @@ -518,8 +517,8 @@ bool FS1::Scheme::mapPath(String &path) const // Does this path qualify for mapping? if (path.length() <= name().length()) return false; - if (path.at(name().length()) != '/') return false; - if (!path.beginsWith(name(), String::CaseInsensitive)) return false; + if (path.substr(name().sizec(), 1) != "/") return false; + if (!path.beginsWith(name(), CaseInsensitive)) return false; // Yes. path = String("$(App.DataPath)/$(GamePlugin.Name)") / path; diff --git a/doomsday/apps/libdoomsday/src/filesys/idgameslink.cpp b/doomsday/apps/libdoomsday/src/filesys/idgameslink.cpp index 4235eb12d9..66fb7409df 100644 --- a/doomsday/apps/libdoomsday/src/filesys/idgameslink.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/idgameslink.cpp @@ -25,8 +25,8 @@ #include #include -#include -#include +#include +//#include using namespace de; @@ -61,38 +61,37 @@ DE_PIMPL(IdgamesLink) String packageIdentifierForFileEntry(FileEntry const &entry) const { - if (entry.name().fileNameExtension() == QStringLiteral(".zip")) + if (entry.name().fileNameExtension() == DE_STR(".zip")) { Path const path = entry.path(); - String id = QString("%1_%2") - .arg(DataBundle::cleanIdentifier(path.fileName().fileNameWithoutExtension())) - .arg(DataBundle::versionFromTimestamp(entry.modTime)); + String id = DataBundle::cleanIdentifier(path.fileName().fileNameWithoutExtension()) + + "_" + DataBundle::versionFromTimestamp(entry.modTime); // Remove the hour:minute part. - id.truncate(id.size() - 5); + id.truncate(id.sizeb() - 5); if (path.segment(1) == CATEGORY_MUSIC || path.segment(1) == CATEGORY_SOUNDS || path.segment(1) == CATEGORY_THEMES) { - return String("%1.%2.%3") - .arg(DOMAIN_IDGAMES) - .arg(path.segment(1)) - .arg(id); + return String::format("%s.%s.%s", + DOMAIN_IDGAMES.c_str(), + path.segment(1).toString().c_str(), + id.c_str()); } if (path.segment(1) == CATEGORY_LEVELS) { String subset; - if (path.segment(3) == QStringLiteral("deathmatch")) subset = QStringLiteral("deathmatch."); - else if (path.segment(3) == QStringLiteral("megawads")) subset = QStringLiteral("megawads."); - return String("%1.%2.%3.%4%5") - .arg(DOMAIN_IDGAMES) - .arg(CATEGORY_LEVELS) - .arg(path.segment(2)) - .arg(subset) - .arg(id); + if (path.segment(3) == DE_STR("deathmatch")) subset = DE_STR("deathmatch."); + else if (path.segment(3) == DE_STR("megawads")) subset = DE_STR("megawads."); + return String::format("%s.%s.%s.%s%s", + DOMAIN_IDGAMES.c_str(), + CATEGORY_LEVELS.c_str(), + path.segment(2).toString().c_str(), + subset.c_str(), + id.c_str()); } - return String("%1.%2").arg(DOMAIN_IDGAMES).arg(id); + return String::format("%s.%s", DOMAIN_IDGAMES.c_str(), id.c_str()); } else { @@ -117,7 +116,7 @@ DE_PIMPL(IdgamesLink) } } - qDebug() << "idgames package index has" << packageIndex.size() << "entries"; + debug("idgames package index has %zu entries", packageIndex.size()); } PackageIndexEntry const *findPackage(String const &packageId) const @@ -151,29 +150,28 @@ IdgamesLink::IdgamesLink(String const &address) , d(new Impl(this)) {} -void IdgamesLink::parseRepositoryIndex(QByteArray data) +void IdgamesLink::parseRepositoryIndex(const Block &data) { // This may be a long list, so let's do it in a background thread. // The link will be marked connected only after the data has been parsed. scope() += async([this, data] () -> String { - Block const listing = gDecompress(data); - QTextStream is(listing, QIODevice::ReadOnly); - is.setCodec("UTF-8"); - QRegularExpression const reDir("^\\.?(.*):$"); - QRegularExpression const reTotal("^total\\s+\\d+$"); - QRegularExpression const reFile("^(-|d)[-rwxs]+\\s+\\d+\\s+\\w+\\s+\\w+\\s+" + const String listing = gDecompress(data); + + const RegExp reDir("^\\.?(.*):$"); + const RegExp reTotal("^total\\s+\\d+$"); + const RegExp reFile("^(-|d)[-rwxs]+\\s+\\d+\\s+\\w+\\s+\\w+\\s+" "(\\d+)\\s+(\\w+\\s+\\d+\\s+[0-9:]+)\\s+(.*)$", - QRegularExpression::CaseInsensitiveOption); + CaseInsensitive); String currentPath; bool ignore = false; - QRegularExpression const reIncludedPaths("^/(levels|music|sounds|themes)"); + const RegExp reIncludedPaths("^/(levels|music|sounds|themes)"); std::unique_ptr tree(new FileTree); - while (!is.atEnd()) + for (const auto &lineRef : listing.splitRef("\n")) { - if (String const line = is.readLine().trimmed()) + if (const String line = String(lineRef).strip()) { if (!currentPath) { @@ -196,14 +194,14 @@ void IdgamesLink::parseRepositoryIndex(QByteArray data) auto match = reFile.match(line); if (match.hasMatch()) { - bool const isFolder = (match.captured(1) == QStringLiteral("d")); + bool const isFolder = (match.captured(1) == DE_STR("d")); if (!isFolder) { String const name = match.captured(4); - if (name.startsWith(QChar('.')) || name.contains(" -> ")) + if (name.beginsWith('.') || name.contains(" -> ")) continue; - auto &entry = tree->insert((currentPath / name).toLower()); + auto &entry = tree->insert((currentPath / name).lower()); entry.size = match.captured(2).toULongLong(nullptr, 10);; entry.modTime = Time::fromText(match.captured(3), Time::UnixLsStyleDateTime); } @@ -215,7 +213,7 @@ void IdgamesLink::parseRepositoryIndex(QByteArray data) currentPath.clear(); } } - qDebug() << "idgames file tree contains" << tree->size() << "entries"; + debug("idgames file tree contains %zu entries", tree->size()); setFileTree(tree.release()); return String(); }, @@ -235,10 +233,7 @@ void IdgamesLink::parseRepositoryIndex(QByteArray data) StringList IdgamesLink::categoryTags() const { - return StringList({ CATEGORY_LEVELS, - CATEGORY_MUSIC, - CATEGORY_SOUNDS, - CATEGORY_THEMES }); + return {CATEGORY_LEVELS, CATEGORY_MUSIC, CATEGORY_SOUNDS, CATEGORY_THEMES}; } LoopResult IdgamesLink::forPackageIds(std::function func) const @@ -265,7 +260,7 @@ String IdgamesLink::findPackagePath(String const &packageId) const filesys::Link *IdgamesLink::construct(String const &address) { - if ((address.startsWith("http:") || address.startsWith("https:")) && + if ((address.beginsWith("http:") || address.beginsWith("https:")) && !address.contains("dengine.net")) { return new IdgamesLink(address); diff --git a/doomsday/apps/libdoomsday/src/filesys/idgamespackageinfofile.cpp b/doomsday/apps/libdoomsday/src/filesys/idgamespackageinfofile.cpp index 00b0dabad7..58208819b8 100644 --- a/doomsday/apps/libdoomsday/src/filesys/idgamespackageinfofile.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/idgamespackageinfofile.cpp @@ -26,8 +26,7 @@ #include #include #include - -#include +#include using namespace de; @@ -48,7 +47,7 @@ DE_PIMPL(IdgamesPackageInfoFile) String cacheFolderPath() const { String const hex = dataFile->metaId().asHexadecimalText(); - return RemoteFile::CACHE_PATH / hex.right(1) / hex; + return RemoteFile::CACHE_PATH / hex.right(String::CharPos(1)) / hex; } void assetStateChanged(Asset &) @@ -56,7 +55,7 @@ DE_PIMPL(IdgamesPackageInfoFile) if (!assets.isEmpty() && assets.isReady()) { // Looks like we can process the file contents. - qDebug() << "[IdgamesPackageInfoFile] Time to unzip and analyze!"; + debug("[IdgamesPackageInfoFile] Time to unzip and analyze!"); DE_ASSERT(dataFile->isReady()); DE_ASSERT(descriptionFile->isReady()); @@ -90,7 +89,7 @@ DE_PIMPL(IdgamesPackageInfoFile) // qDebug() << dataFile->target().size() << dataFile->target().status().modifiedAt.asText(); //qDebug() << "remote file timestamp:" << DataBundle::versionFromTimestamp(dataFile->target().status().modifiedAt); - meta.set("title", dataFile->name().fileNameWithoutExtension().toUpper() + " (idgames)"); + meta.set("title", dataFile->name().fileNameWithoutExtension().upper() + " (idgames)"); meta.set("version", DataBundle::versionFromTimestamp(dataFile->target().status().modifiedAt)); if (Folder *zip = const_cast(maybeAs(dataFile->target()))) @@ -98,7 +97,7 @@ DE_PIMPL(IdgamesPackageInfoFile) zip->populate(); zip->forContents([this, &dataFiles] (String name, File &file) { - String const ext = name.fileNameExtension().toLower(); + String const ext = name.fileNameExtension().lower(); if (ext == ".wad" || ext == ".deh" || ext == ".lmp" || ext == ".pk3") { File &copied = FS::copySerialized @@ -110,7 +109,7 @@ DE_PIMPL(IdgamesPackageInfoFile) FS::waitForIdle(); StringList components; - foreach (String path, dataFiles) + for (String path : dataFiles) { if (DataBundle const *bundle = FS::tryLocate(path)) { @@ -145,26 +144,26 @@ DE_PIMPL(IdgamesPackageInfoFile) } } std::unique_ptr comps { new ArrayValue }; - foreach (String comp, components) + for (const String &comp : components) { comps->add(new TextValue(comp)); } meta.addArray("dataFiles", comps.release()); meta.set("tags", meta.gets("tags", "") - .removed(QRegularExpression("\\b(hidden|cached)\\b")) + .removed(RegExp("\\b(hidden|cached)\\b")) .normalizeWhitespace()); // Version should match the idgames index version (or overridden from // metadata with an actual version). - qDebug() << "idgames package will contain:" << components; - qDebug() << meta.asText().toUtf8().constData(); + debug("idgames package will contain: %s", String::join(components, " ").c_str()); + debug(meta.asText().c_str()); if (packageId.segment(1) == "levels") { // Tag with the right game. meta.set("tags", meta.gets("tags", "") - .removed(QRegularExpression(DataBundle::anyGameTagPattern())) + .removed(RegExp(DataBundle::anyGameTagPattern())) .normalizeWhitespace()); meta.appendUniqueWord("tags", packageId.segment(2).toString()); } @@ -180,11 +179,11 @@ DE_PIMPL(IdgamesPackageInfoFile) delete info.remove("path"); String const cachePath = cacheFolderPath(); ArrayValue *pkgData = new ArrayValue; - foreach (String path, info.getStringList("dataFiles")) + for (String path : info.getStringList("dataFiles")) { - if (path.startsWith(cachePath)) + if (path.beginsWith(cachePath)) { - path.remove(0, cachePath.size() + 1); + path.remove(BytePos(0), cachePath.size() + 1); } pkgData->add(new TextValue(path)); } @@ -240,8 +239,8 @@ void IdgamesPackageInfoFile::download() void IdgamesPackageInfoFile::cancelDownload() {} -IIStream const &IdgamesPackageInfoFile::operator >> (IByteArray &bytes) const +IIStream const &IdgamesPackageInfoFile::operator>>(IByteArray &bytes) const { - bytes.set(0, d->serializedContent.dataConst(), d->serializedContent.size()); + bytes.set(0, d->serializedContent.data(), d->serializedContent.size()); return *this; } diff --git a/doomsday/apps/libdoomsday/src/filesys/lumpcache.cpp b/doomsday/apps/libdoomsday/src/filesys/lumpcache.cpp index 63c0b03365..0af63198f5 100644 --- a/doomsday/apps/libdoomsday/src/filesys/lumpcache.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/lumpcache.cpp @@ -120,7 +120,7 @@ uint8_t const *LumpCache::data(uint lumpIdx) const LumpCache &LumpCache::insert(uint lumpIdx, uint8_t *data) { LOG_AS("LumpCache::insert"); - if (!isValidIndex(lumpIdx)) throw Error("LumpCache::insert", QString("Invalid index %1").arg(lumpIdx)); + if (!isValidIndex(lumpIdx)) throw Error("LumpCache::insert", stringf("Invalid index %u", lumpIdx)); // Time to allocate the data cache? if (!_dataCache) @@ -141,7 +141,7 @@ LumpCache &LumpCache::insertAndLock(uint lumpIdx, uint8_t *data) LumpCache &LumpCache::lock(uint lumpIdx) { LOG_AS("LumpCache::lock"); - if (!isValidIndex(lumpIdx)) throw Error("LumpCache::lock", QString("Invalid index %1").arg(lumpIdx)); + if (!isValidIndex(lumpIdx)) throw Error("LumpCache::lock", stringf("Invalid index %u", lumpIdx)); Data* record = cacheRecord(lumpIdx); record->lock(); return *this; @@ -150,7 +150,7 @@ LumpCache &LumpCache::lock(uint lumpIdx) LumpCache &LumpCache::unlock(uint lumpIdx) { LOG_AS("LumpCache::unlock"); - if (!isValidIndex(lumpIdx)) throw Error("LumpCache::unlock", QString("Invalid index %1").arg(lumpIdx)); + if (!isValidIndex(lumpIdx)) throw Error("LumpCache::unlock", stringf("Invalid index %u", lumpIdx)); Data* record = cacheRecord(lumpIdx); record->unlock(); return *this; diff --git a/doomsday/apps/libdoomsday/src/filesys/lumpindex.cpp b/doomsday/apps/libdoomsday/src/filesys/lumpindex.cpp index cf3233d346..34f0e51c83 100644 --- a/doomsday/apps/libdoomsday/src/filesys/lumpindex.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/lumpindex.cpp @@ -24,9 +24,9 @@ */ #include "doomsday/filesys/lumpindex.h" -#include -#include -#include +#include +#include +#include #include namespace de { @@ -44,7 +44,7 @@ namespace internal LumpSortInfo const *infoA = (LumpSortInfo const *)a; LumpSortInfo const *infoB = (LumpSortInfo const *)b; - if (int delta = infoA->path.compare(infoB->path, Qt::CaseInsensitive)) + if (int delta = infoA->path.compare(infoB->path, CaseInsensitive)) return delta; // Still matched; try the file load order indexes. @@ -152,8 +152,8 @@ LumpIndex::Id1MapRecognizer::Id1MapRecognizer(LumpIndex const &lumpIndex, lumpnu duint numVertexes = 0, numThings = 0, numLines = 0, numSides = 0, numSectors = 0, numLights = 0; DE_FOR_EACH_CONST(Lumps, i, d->lumps) { - DataType const dataType = i.key(); - File1 const &lump = *i.value(); + DataType const dataType = i->first; + File1 const &lump = *i->second; // Determine the number of map data objects of each data type. duint *elemCountAddr = 0; @@ -216,7 +216,7 @@ LumpIndex::Id1MapRecognizer::Lumps const &LumpIndex::Id1MapRecognizer::lumps() c File1 *LumpIndex::Id1MapRecognizer::sourceFile() const { if (d->lumps.isEmpty()) return nullptr; - return &lumps().first()->container(); + return &lumps().begin()->second->container(); } lumpnum_t LumpIndex::Id1MapRecognizer::lastLump() const @@ -242,7 +242,7 @@ String const &LumpIndex::Id1MapRecognizer::formatName(Format id) // static LumpIndex::Id1MapRecognizer::DataType LumpIndex::Id1MapRecognizer::typeForLumpName(String name) // static { - static QHash const lumpTypeInfo + static const Hash lumpTypeInfo { std::make_pair(String("THINGS"), ThingData ), std::make_pair(String("LINEDEFS"), LineDefData ), @@ -269,10 +269,10 @@ LumpIndex::Id1MapRecognizer::DataType LumpIndex::Id1MapRecognizer::typeForLumpNa }; // Ignore the file extension if present. - auto found = lumpTypeInfo.constFind(name.fileNameWithoutExtension().toUpper()); - if (found != lumpTypeInfo.constEnd()) + auto found = lumpTypeInfo.find(name.fileNameWithoutExtension().upper()); + if (found != lumpTypeInfo.end()) { - return found.value(); + return found->second; } return UnknownData; } @@ -331,8 +331,8 @@ DE_PIMPL(LumpIndex) { lumpnum_t head, nextInLoadOrder; }; - typedef QVector PathHash; - QScopedPointer lumpsByPath; + typedef List PathHash; + std::unique_ptr lumpsByPath; Impl(Public *i) : Base(i) @@ -344,7 +344,7 @@ DE_PIMPL(LumpIndex) void buildLumpsByPathIfNeeded() { - if (!lumpsByPath.isNull()) return; + if (lumpsByPath) return; int const numElements = lumps.size(); lumpsByPath.reset(new PathHash(numElements)); @@ -376,7 +376,7 @@ DE_PIMPL(LumpIndex) * * @return Number of lumps newly flagged during this op. */ - int flagContainedLumps(QBitArray &pruneFlags, File1 &file) + int flagContainedLumps(BitArray &pruneFlags, File1 &file) { DE_ASSERT(pruneFlags.size() == lumps.size()); @@ -397,7 +397,7 @@ DE_PIMPL(LumpIndex) * @param pruneFlags Passed by reference to avoid deep copy on value-write. * @return Number of lumps newly flagged during this op. */ - int flagDuplicateLumps(QBitArray &pruneFlags) + int flagDuplicateLumps(BitArray &pruneFlags) { DE_ASSERT(pruneFlags.size() == lumps.size()); @@ -426,7 +426,7 @@ DE_PIMPL(LumpIndex) for (int i = 1; i < numRecords; ++i) { if (pruneFlags.testBit(i)) continue; - if (sortInfos[i - 1].path.compare(sortInfos[i].path, Qt::CaseInsensitive)) continue; + if (sortInfos[i - 1].path.compare(sortInfos[i].path, CaseInsensitive)) continue; pruneFlags.setBit(sortInfos[i].origIndex, true); numFlagged += 1; } @@ -438,7 +438,7 @@ DE_PIMPL(LumpIndex) } /// @return Number of pruned lumps. - int pruneFlaggedLumps(QBitArray flaggedLumps) + int pruneFlaggedLumps(const BitArray &flaggedLumps) { DE_ASSERT(flaggedLumps.size() == lumps.size()); @@ -485,7 +485,7 @@ DE_PIMPL(LumpIndex) int const numRecords = lumps.size(); if (numRecords <= 1) return; - QBitArray pruneFlags(numRecords); + BitArray pruneFlags(numRecords); flagDuplicateLumps(pruneFlags); pruneFlaggedLumps(pruneFlags); } @@ -507,9 +507,9 @@ bool LumpIndex::hasLump(lumpnum_t lumpNum) const static String LumpIndex_invalidIndexMessage(int invalidIdx, int lastValidIdx) { - String msg = String("Invalid lump index %1").arg(invalidIdx); + String msg = String::format("Invalid lump index %i", invalidIdx); if (lastValidIdx < 0) msg += " (file is empty)"; - else msg += String(", valid range: [0..%2)").arg(lastValidIdx); + else msg += String::format(", valid range: [0..%i)", lastValidIdx); return msg; } @@ -541,7 +541,7 @@ int LumpIndex::pruneByFile(File1 &file) if (d->lumps.empty()) return 0; int const numRecords = d->lumps.size(); - QBitArray pruneFlags(numRecords); + BitArray pruneFlags(numRecords); // We may need to prune path-duplicate lumps. We'll fold those into this // op as pruning may result in reallocations. @@ -623,7 +623,7 @@ int LumpIndex::findAll(Path const &path, FoundIndices &found) const d->buildLumpsByPathIfNeeded(); // Perform the search. - DE_ASSERT(!d->lumpsByPath.isNull()); + DE_ASSERT(d->lumpsByPath); ushort hash = path.lastSegment().hash() % d->lumpsByPath->size(); for (int idx = (*d->lumpsByPath)[hash].head; idx != -1; idx = (*d->lumpsByPath)[idx].nextInLoadOrder) @@ -648,7 +648,7 @@ lumpnum_t LumpIndex::findLast(Path const &path) const d->buildLumpsByPathIfNeeded(); // Perform the search. - DE_ASSERT(!d->lumpsByPath.isNull()); + DE_ASSERT(d->lumpsByPath); ushort hash = path.lastSegment().hash() % d->lumpsByPath->size(); for (int idx = (*d->lumpsByPath)[hash].head; idx != -1; idx = (*d->lumpsByPath)[idx].nextInLoadOrder) diff --git a/doomsday/apps/libdoomsday/src/filesys/readfile.cpp b/doomsday/apps/libdoomsday/src/filesys/readfile.cpp index 3347a63f3a..3f9e3b30c9 100644 --- a/doomsday/apps/libdoomsday/src/filesys/readfile.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/readfile.cpp @@ -124,7 +124,7 @@ AutoStr *M_ReadFileIntoString(ddstring_t const *path, dd_bool *isCustom) // Try the virtual file system. try { - QScopedPointer hndl(&App_FileSystem().openFile(Str_Text(path), "rb")); + std::unique_ptr hndl(&App_FileSystem().openFile(Str_Text(path), "rb")); if (isCustom) { @@ -141,7 +141,7 @@ AutoStr *M_ReadFileIntoString(ddstring_t const *path, dd_bool *isCustom) Block buffer; buffer.resize(lumpLength); hndl->read((uint8_t *)buffer.data(), lumpLength); - string = Str_PartAppend(AutoStr_NewStd(), buffer.constData(), 0, lumpLength); + string = Str_PartAppend(AutoStr_NewStd(), buffer.c_str(), 0, lumpLength); } App_FileSystem().releaseFile(hndl->file()); diff --git a/doomsday/apps/libdoomsday/src/filesys/searchpath.cpp b/doomsday/apps/libdoomsday/src/filesys/searchpath.cpp index b93272574e..cd05c1ac13 100644 --- a/doomsday/apps/libdoomsday/src/filesys/searchpath.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/searchpath.cpp @@ -22,7 +22,7 @@ namespace de { -SearchPath::SearchPath(de::Uri const &_uri, SearchPath::Flags _flags) +SearchPath::SearchPath(de::Uri const &_uri, Flags _flags) : Uri(_uri), flags_(_flags) {} @@ -30,7 +30,7 @@ SearchPath::SearchPath(SearchPath const &other) : Uri(other), flags_(other.flags_) {} -SearchPath::Flags SearchPath::flags() const +Flags SearchPath::flags() const { return flags_; } diff --git a/doomsday/apps/libdoomsday/src/filesys/virtualmappings.cpp b/doomsday/apps/libdoomsday/src/filesys/virtualmappings.cpp index c6f5fc5030..cd58e27d1a 100644 --- a/doomsday/apps/libdoomsday/src/filesys/virtualmappings.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/virtualmappings.cpp @@ -44,7 +44,7 @@ void FS_InitVirtualPathMappings() dint argC = CommandLine_Count(); for (dint i = 0; i < argC; ++i) { - if (qstrnicmp("-vdmap", CommandLine_At(i), 6)) + if (iCmpStrNCase("-vdmap", CommandLine_At(i), 6)) { continue; } diff --git a/doomsday/apps/libdoomsday/src/filesys/zip.cpp b/doomsday/apps/libdoomsday/src/filesys/zip.cpp index 1f96650152..0b051b045e 100644 --- a/doomsday/apps/libdoomsday/src/filesys/zip.cpp +++ b/doomsday/apps/libdoomsday/src/filesys/zip.cpp @@ -201,8 +201,8 @@ static bool applyGamePathMappings(String &path) // Manually mapped to Defs? if (path.beginsWith('@')) { - path.remove(0, 1); - if (path.at(0) == '/') path.remove(0, 1); + path.remove(BytePos(0), 1); + if (path.first() == '/') path.remove(BytePos(0), 1); path = String("$(App.DefsPath)/$(GamePlugin.Name)/auto") / path; return true; @@ -211,11 +211,11 @@ static bool applyGamePathMappings(String &path) // Manually mapped to Data? if (path.beginsWith('#')) { - path.remove(0, 1); - if (path.at(0) == '/') path.remove(0, 1); + path.remove(BytePos(0), 1); + if (path.first() == '/') path.remove(BytePos(0), 1); // Is there a prefix to be omitted in the name? - if (int slash = path.lastIndexOf('/')) + if (auto slash = path.lastIndexOf('/')) { // The slash must not be too early in the string. if (slash >= 2) @@ -257,7 +257,7 @@ static bool applyGamePathMappings(String &path) FS1::Schemes const &schemes = App_FileSystem().allSchemes(); DE_FOR_EACH_CONST(FS1::Schemes, i, schemes) { - if ((*i)->mapPath(path)) + if (i->second->mapPath(path)) { return true; } @@ -280,7 +280,7 @@ String const &Zip::LumpFile::name() const return directoryNode().name(); } -Uri Zip::LumpFile::composeUri(QChar delimiter) const +Uri Zip::LumpFile::composeUri(Char delimiter) const { return directoryNode().path(delimiter); } @@ -319,7 +319,7 @@ Zip &Zip::LumpFile::zip() const DE_PIMPL(Zip) { LumpTree entries; ///< Directory structure and entry records for all lumps. - QScopedPointer dataCache; ///< Data payload cache. + std::unique_ptr dataCache; ///< Data payload cache. Impl(Public *i) : Base(i) {} @@ -340,7 +340,10 @@ DE_PIMPL(Zip) { bool result; uint8_t *compressedData = (uint8_t *) M_Malloc(lumpInfo.compressedSize); - if (!compressedData) throw Error("Zip::bufferLump", QString("Failed on allocation of %1 bytes for decompression buffer").arg(lumpInfo.compressedSize)); + if (!compressedData) + throw Error("Zip::bufferLump", + stringf("Failed on allocation of %zu bytes for decompression buffer", + lumpInfo.compressedSize)); // Read the compressed data into a temporary buffer for decompression. self().handle_->read(compressedData, lumpInfo.compressedSize); @@ -405,7 +408,11 @@ Zip::Zip(FileHandle &hndl, String path, FileInfo const &info, File1 *container) // local buffer before we process it into our runtime representation. // Read the entire central directory into memory. void *centralDirectory = M_Malloc(summary.size); - if (!centralDirectory) throw FormatError("Zip", String("Failed on allocation of %1 bytes for temporary copy of the central centralDirectory").arg(summary.size)); + if (!centralDirectory) + throw FormatError("Zip", + stringf("Failed on allocation of %u bytes for temporary copy of the " + "central centralDirectory", + summary.size)); handle_->seek(summary.offset, SeekSet); handle_->read((uint8_t *)centralDirectory, summary.size); @@ -536,7 +543,7 @@ void Zip::clearCachedLump(int lumpIndex, bool *retCleared) if (hasLump(lumpIndex)) { - if (!d->dataCache.isNull()) + if (d->dataCache) { d->dataCache->remove(lumpIndex, retCleared); } @@ -550,7 +557,7 @@ void Zip::clearCachedLump(int lumpIndex, bool *retCleared) void Zip::clearLumpCache() { LOG_AS("Zip::clearLumpCache"); - if (!d->dataCache.isNull()) + if (d->dataCache) { d->dataCache->clear(); } @@ -568,7 +575,7 @@ uint8_t const *Zip::cacheLump(int lumpIndex) << (lumpFile.info().isCompressed()? ", compressed" : "")); // Time to create the cache? - if (d->dataCache.isNull()) + if (!d->dataCache) { d->dataCache.reset(new LumpCache(lumpCount())); } @@ -577,7 +584,8 @@ uint8_t const *Zip::cacheLump(int lumpIndex) if (data) return data; uint8_t *region = (uint8_t *) Z_Malloc(lumpFile.info().size, PU_APPSTATIC, 0); - if (!region) throw Error("Zip::cacheLump", QString("Failed on allocation of %1 bytes for cache copy of lump #%2").arg(lumpFile.info().size).arg(lumpIndex)); + if (!region) throw Error("Zip::cacheLump", stringf("Failed on allocation of %zu bytes for cache copy of lump #%i", + lumpFile.info().size, lumpIndex)); readLump(lumpIndex, region, false); d->dataCache->insert(lumpIndex, region); @@ -593,7 +601,7 @@ void Zip::unlockLump(int lumpIndex) if (hasLump(lumpIndex)) { - if (!d->dataCache.isNull()) + if (d->dataCache) { d->dataCache->unlock(lumpIndex); } @@ -627,7 +635,7 @@ size_t Zip::readLump(int lumpIndex, uint8_t *buffer, size_t startOffset, // Try to avoid a file system read by checking for a cached copy. if (tryCache) { - uint8_t const *data = (!d->dataCache.isNull() ? d->dataCache->data(lumpIndex) : 0); + uint8_t const *data = (d->dataCache ? d->dataCache->data(lumpIndex) : 0); LOGDEV_RES_XVERBOSE("Cache %s on #%i", (data? "hit" : "miss") << lumpIndex); if (data) { @@ -647,7 +655,7 @@ size_t Zip::readLump(int lumpIndex, uint8_t *buffer, size_t startOffset, { // Allocate a temporary buffer and read the whole lump into it(!). uint8_t *readBuf = (uint8_t *) M_Malloc(lumpFile.size()); - if (!readBuf) throw Error("Zip::readLump", QString("Failed on allocation of %1 bytes for work buffer").arg(lumpFile.size())); + if (!readBuf) throw Error("Zip::readLump", stringf("Failed on allocation of %u bytes for work buffer", lumpFile.size())); if (d->bufferLump(lumpFile, readBuf)) { @@ -660,7 +668,7 @@ size_t Zip::readLump(int lumpIndex, uint8_t *buffer, size_t startOffset, /// @todo Do not check the read length here. if (readBytes < de::min(size_t(lumpFile.size()), length)) - throw Error("Zip::readLump", QString("Only read %1 of %2 bytes of lump #%3").arg(readBytes).arg(length).arg(lumpIndex)); + throw Error("Zip::readLump", stringf("Only read %zu of %zu bytes of lump #%i", readBytes, length, lumpIndex)); return readBytes; } diff --git a/doomsday/apps/libdoomsday/src/game.cpp b/doomsday/apps/libdoomsday/src/game.cpp index 891cb2c8fa..7541bef860 100644 --- a/doomsday/apps/libdoomsday/src/game.cpp +++ b/doomsday/apps/libdoomsday/src/game.cpp @@ -37,7 +37,7 @@ #include #include #include -#include +#include using namespace de; @@ -92,7 +92,7 @@ DE_PIMPL(Game), public Lockable ~Impl() { DENG2_GUARD(this); - qDeleteAll(manifests); + for (auto &i : manifests) delete i.second; } GameProfile *profile() const @@ -152,13 +152,13 @@ String Game::family() const return ""; } -void Game::setRequiredPackages(StringList packageIds) +void Game::setRequiredPackages(const StringList &packageIds) { DENG2_GUARD(d); d->requiredPackages = packageIds; } -void Game::addRequiredPackage(String const &packageId) +void Game::addRequiredPackage(const String &packageId) { DENG2_GUARD(d); d->requiredPackages.append(packageId); @@ -218,11 +218,12 @@ void Game::addManifest(ResourceManifest &manifest) { DENG2_GUARD(d); // Ensure we don't add duplicates. - Manifests::const_iterator found = d->manifests.find(manifest.resourceClass(), &manifest); - if (found == d->manifests.end()) - { - d->manifests.insert(manifest.resourceClass(), &manifest); - } +// auto found = d->manifests.find(manifest.resourceClass(), &manifest); +// if (found == d->manifests.end()) +// { +// d->manifests.insert(manifest.resourceClass(), &manifest); +// } + d->manifests.insert(std::make_pair(manifest.resourceClass(), &manifest)); } bool Game::allStartupFilesFound() const @@ -235,9 +236,9 @@ bool Game::allStartupFilesFound() const return false; } - foreach (ResourceManifest *manifest, d->manifests) + for (const auto &i : d->manifests) { - int const flags = manifest->fileFlags(); + int const flags = i.second->fileFlags(); if ((flags & FF_STARTUP) && !(flags & FF_FOUND)) return false; @@ -289,21 +290,21 @@ String const &Game::statusAsText() const String Game::description() const { DENG2_GUARD(d); - return String(_E(b) "%1 - %2\n" _E(.) - _E(l) "ID: " _E(.) "%3 " - _E(l) "PluginId: " _E(.) "%4\n" - _E(D)_E(b) "Packages:\n" _E(.)_E(.) "%5\n" + return String::format(_E(b) "%s - %s\n" _E(.) + _E(l) "ID: " _E(.) "%s " + _E(l) "PluginId: " _E(.) "%i\n" + _E(D)_E(b) "Packages:\n" _E(.)_E(.) "%s\n" //_E(D)_E(b) "Startup resources:\n" _E(.)_E(.) "%6\n" - _E(D)_E(b) "Custom resources:\n" _E(.)_E(.) "%7\n" - _E(D)_E(b) "Status: " _E(.) "%8") - .arg(title()) - .arg(author()) - .arg(id()) - .arg(int(pluginId())) - .arg(" - " _E(>) + String::join(d->requiredPackages, _E(<) "\n - " _E(>)) + _E(<)) + _E(D)_E(b) "Custom resources:\n" _E(.)_E(.) "%s\n" + _E(D)_E(b) "Status: " _E(.) "%s", + title().c_str(), + author().c_str(), + id().c_str(), + int(pluginId()), + (" - " _E(>) + String::join(d->requiredPackages, _E(<) "\n - " _E(>)) + _E(<)).c_str(), //.arg(filesAsText(FF_STARTUP)) - .arg(filesAsText(0, false)) - .arg(statusAsText()); + filesAsText(0, false).c_str(), + statusAsText().c_str()); } pluginid_t Game::pluginId() const @@ -427,13 +428,13 @@ bool Game::isRequiredFile(File1 &file) const String absolutePath = rootFile.composePath(); bool isRequired = false; - for (Manifests::const_iterator i = d->manifests.find(RC_PACKAGE); - i != d->manifests.end() && i.key() == RC_PACKAGE; ++i) + const auto packages = d->manifests.equal_range(RC_PACKAGE); + for (auto i = packages.first; i != packages.second; ++i) { - ResourceManifest &manifest = **i; + ResourceManifest &manifest = *i->second; if (!(manifest.fileFlags() & FF_STARTUP)) continue; - if (!manifest.resolvedPath(true/*try locate*/).compare(absolutePath, Qt::CaseInsensitive)) + if (!manifest.resolvedPath(true/*try locate*/).compare(absolutePath, CaseInsensitive)) { isRequired = true; break; @@ -451,7 +452,7 @@ void Game::addResource(resourceclassid_t classId, dint rflags, if (!VALID_RESOURCECLASSID(classId)) { throw Error("Game::addResource", - "Unknown resource class " + QString::number(classId)); + "Unknown resource class " + String::asText(classId)); } if (!names || !names[0]) @@ -464,8 +465,8 @@ void Game::addResource(resourceclassid_t classId, dint rflags, addManifest(*manifest); // Add the name list to the resource record. - QStringList nameList = String(names).split(";", QString::SkipEmptyParts); - foreach (QString const &nameRef, nameList) + StringList nameList = String(names).split(";"); + for (String const &nameRef : nameList) { manifest->addName(nameRef); } @@ -473,8 +474,8 @@ void Game::addResource(resourceclassid_t classId, dint rflags, if (params && classId == RC_PACKAGE) { // Add the identityKey list to the resource record. - QStringList idKeys = String((char const *) params).split(";", QString::SkipEmptyParts); - foreach (QString const &idKeyRef, idKeys) + StringList idKeys = String((char const *) params).split(";"); + for (String const &idKeyRef : idKeys) { manifest->addIdentityKey(idKeyRef); } @@ -514,10 +515,10 @@ String Game::filesAsText(int rflags, bool withStatus) const for (uint i = 0; i < RESOURCECLASS_COUNT; ++i) { resourceclassid_t const classId = resourceclassid_t(i); - for (Manifests::const_iterator i = manifs.find(classId); - i != manifs.end() && i.key() == classId; ++i) + const auto range = manifs.equal_range(classId); + for (auto i = range.first; i != range.second; ++i) { - ResourceManifest &manifest = **i; + ResourceManifest &manifest = *i->second; if (rflags >= 0 && (rflags & manifest.fileFlags())) { bool const resourceFound = (manifest.fileFlags() & FF_FOUND) != 0; @@ -530,16 +531,21 @@ String Game::filesAsText(int rflags, bool withStatus) const } // Format the resource name list. - text += String(_E(>) "%1%2") - .arg(!resourceFound? _E(D) : "") - .arg(manifest.names().join(_E(l) " or " _E(.))); + text += String::format(_E(>) "%1%2", + !resourceFound? _E(D) : "", + String::join(manifest.names(), _E(l) " or " _E(.)).c_str()); if (withStatus) { text += String(": ") + _E(>) + (!resourceFound? _E(b) "missing " _E(.) : ""); if (resourceFound) { - text += String(_E(C) "\"%1\"" _E(.)).arg(NativePath(manifest.resolvedPath(false/*don't try to locate*/)).expand().pretty()); + text += String::format( + _E(C) "\"%s\"" _E(.), + NativePath(manifest.resolvedPath(false /*don't try to locate*/)) + .expand() + .pretty() + .c_str()); } text += _E(<); } @@ -563,7 +569,7 @@ D_CMD(InspectGame) { DE_UNUSED(src); - Game const *game = 0; + Game const *game = nullptr; if (argc < 2) { // No game identity key was specified - assume the current game. diff --git a/doomsday/apps/libdoomsday/src/game_init.cpp b/doomsday/apps/libdoomsday/src/game_init.cpp index 6e4d6fc40f..7f9a2b28c6 100644 --- a/doomsday/apps/libdoomsday/src/game_init.cpp +++ b/doomsday/apps/libdoomsday/src/game_init.cpp @@ -42,8 +42,7 @@ using namespace de; static void updateProgress(int progress) { - DE_FOR_EACH_OBSERVER(Games::ProgressAudience, i, - DoomsdayApp::games().audienceForProgress()) + DE_FOR_EACH_OBSERVER(i, DoomsdayApp::games().audienceForProgress()) { i->gameWorkerProgress(progress); } @@ -304,16 +303,16 @@ int loadGameStartupResourcesBusyWorker(void *context) * against by the virtual file system layer. */ GameManifests const &gameManifests = DoomsdayApp::game().manifests(); - int const numPackages = gameManifests.count(RC_PACKAGE); + const dsize numPackages = gameManifests.count(RC_PACKAGE); if (numPackages) { LOG_RES_MSG("Loading game resources..."); int packageIdx = 0; - for (GameManifests::const_iterator i = gameManifests.find(RC_PACKAGE); - i != gameManifests.end() && i.key() == RC_PACKAGE; ++i, ++packageIdx) + const auto packages = gameManifests.equal_range(RC_PACKAGE); + for (auto i = packages.first; i != packages.second; ++i, ++packageIdx) { - loadResource(**i); + loadResource(*i->second); // Update our progress. if (parms.initiatedBusyMode) diff --git a/doomsday/apps/libdoomsday/src/gameprofiles.cpp b/doomsday/apps/libdoomsday/src/gameprofiles.cpp index 0895cdcbd7..d4f533524a 100644 --- a/doomsday/apps/libdoomsday/src/gameprofiles.cpp +++ b/doomsday/apps/libdoomsday/src/gameprofiles.cpp @@ -27,7 +27,7 @@ #include #include -#include +#include using namespace de; @@ -112,9 +112,9 @@ LoopResult GameProfiles::forAll(std::function func }); } -QList GameProfiles::profilesInFamily(de::String const &family) +List GameProfiles::profilesInFamily(de::String const &family) { - QList profs; + List profs; forAll([&profs, &family] (GameProfile &profile) { if (profile.game().family() == family) @@ -126,15 +126,15 @@ QList GameProfiles::profilesInFamily(de::String const &family) return profs; } -QList GameProfiles::profilesSortedByFamily() +List GameProfiles::profilesSortedByFamily() { - QList profs; + List profs; forAll([&profs] (GameProfile &profile) { profs << &profile; return LoopContinue; }); - qSort(profs.begin(), profs.end(), [] (GameProfile const *a, GameProfile const *b) + std::sort(profs.begin(), profs.end(), [] (GameProfile const *a, GameProfile const *b) { String family1 = a->game().family(); String family2 = b->game().family(); @@ -149,9 +149,9 @@ QList GameProfiles::profilesSortedByFamily() return profs; } -QList GameProfiles::allPlayableProfiles() const +List GameProfiles::allPlayableProfiles() const { - QList playable; + List playable; forAll([&playable] (Profile const &prof) { if (prof.isPlayable()) playable << &prof; @@ -286,7 +286,7 @@ void GameProfiles::Profile::setCustomDataFile(const String &id) } } -void GameProfiles::Profile::setPackages(StringList packagesInOrder) +void GameProfiles::Profile::setPackages(const StringList& packagesInOrder) { if (d->packages != packagesInOrder) { @@ -526,12 +526,15 @@ StringList GameProfiles::Profile::allRequiredPackages() const StringList GameProfiles::Profile::packagesAffectingGameplay() const { StringList ids = PackageLoader::get().expandDependencies(allRequiredPackages()); - QMutableListIterator iter(ids); - while (iter.hasNext()) + for (auto iter = ids.begin(); iter != ids.end(); ) { - if (!GameStateFolder::isPackageAffectingGameplay(iter.next())) + if (!GameStateFolder::isPackageAffectingGameplay(*iter)) + { + iter = ids.erase(iter); + } + else { - iter.remove(); + ++iter; } } return ids; @@ -570,7 +573,7 @@ void GameProfiles::Profile::loadPackages() const void GameProfiles::Profile::unloadPackages() const { StringList const allPackages = allRequiredPackages(); - for (int i = allPackages.size() - 1; i >= 0; --i) + for (int i = allPackages.sizei() - 1; i >= 0; --i) { PackageLoader::get().unload(allPackages.at(i)); } @@ -586,9 +589,7 @@ bool GameProfiles::Profile::resetToDefaults() String GameProfiles::Profile::toInfoSource() const { - String info; - QTextStream os(&info); - os.setCodec("UTF-8"); + std::ostringstream os; os << VAR_GAME << ": " << d->gameId << "\n" << VAR_PACKAGES << " <" << String::join(de::map(d->packages, Info::quoteString), ", ") << ">\n" @@ -615,7 +616,7 @@ String GameProfiles::Profile::toInfoSource() const indented.replace("\n", "\n "); os << "\n" << VAR_VALUES << " {\n " << indented << "\n}"; } - return info; + return os.str(); } Record &GameProfiles::Profile::objectNamespace() @@ -634,7 +635,7 @@ bool GameProfiles::arePackageListsCompatible(StringList const &list1, StringList // The package lists must match order and IDs, but currently we ignore the // versions. - for (int i = 0; i < list1.size(); ++i) + for (int i = 0; i < list1.sizei(); ++i) { if (!Package::equals(list1.at(i), list2.at(i))) { diff --git a/doomsday/apps/libdoomsday/src/games.cpp b/doomsday/apps/libdoomsday/src/games.cpp index d3292e07d2..6f98557d41 100644 --- a/doomsday/apps/libdoomsday/src/games.cpp +++ b/doomsday/apps/libdoomsday/src/games.cpp @@ -34,7 +34,7 @@ #include #include #include -#include +#include using namespace de; @@ -47,10 +47,10 @@ DE_PIMPL(Games) /// Special "null-game" object for this collection. NullGame *nullGame; - QHash idLookup; // not owned, lower case + Hash idLookup; // not owned, lower case LoopCallback mainCall; - QSet lastCheckedPlayable; // determines when notification sent + Set lastCheckedPlayable; // determines when notification sent /** * Delegates game addition notifications to scripts. @@ -69,7 +69,7 @@ DE_PIMPL(Games) GameAdditionScriptAudience scriptAudienceForGameAddition; - Impl(Public *i) : Base(i), games(), nullGame(0) + Impl(Public *i) : Base(i), games(), nullGame(nullptr) { /* * One-time creation and initialization of the special "null-game" @@ -91,9 +91,9 @@ DE_PIMPL(Games) void clear() { - DE_ASSERT(nullGame != 0); + DE_ASSERT(nullGame); - qDeleteAll(games); + deleteAll(games); games.clear(); idLookup.clear(); } @@ -103,7 +103,7 @@ DE_PIMPL(Games) DE_ASSERT(game != nullptr); games.push_back(game); - idLookup.insert(game->id().toLower(), game); + idLookup.insert(game->id().lower(), game); DoomsdayApp::bundles().audienceForIdentify() += this; @@ -115,17 +115,16 @@ DE_PIMPL(Games) Game *findById(String id) const { - if (id.beginsWith("doom-")) + if (id.beginsWith("doom-")) { // Originally, Freedoom and BFG variants used an inconsistently named ID. id = "doom1-" + id.substr(5); } - - auto found = idLookup.constFind(id.toLower()); - if (found != idLookup.constEnd()) + auto found = idLookup.find(id.lower()); + if (found != idLookup.end()) { - return found.value(); - } + return found->second; + } return nullptr; } @@ -137,14 +136,10 @@ DE_PIMPL(Games) } } - DE_PIMPL_AUDIENCE(Addition) - DE_PIMPL_AUDIENCE(Readiness) - DE_PIMPL_AUDIENCE(Progress) + DE_PIMPL_AUDIENCES(Addition, Readiness, Progress) }; -DE_AUDIENCE_METHOD(Games, Addition) -DE_AUDIENCE_METHOD(Games, Readiness) -DE_AUDIENCE_METHOD(Games, Progress) +DE_AUDIENCE_METHODS(Games, Addition, Readiness, Progress) Games::Games() : d(new Impl(this)) {} @@ -162,7 +157,7 @@ Game &Games::nullGame() // static int Games::numPlayable() const { int count = 0; - foreach (Game *game, d->games) + for (Game *game : d->games) { if (game->allStartupFilesFound()) { @@ -175,7 +170,7 @@ int Games::numPlayable() const int Games::numPlayable(String const &family) const { int count = 0; - foreach (Game *game, d->games) + for (Game *game : d->games) { if (game->isPlayableWithDefaultPackages() && game->family() == family) { @@ -187,7 +182,7 @@ int Games::numPlayable(String const &family) const GameProfile const *Games::firstPlayable() const { - foreach (Game *game, d->games) + for (Game *game : d->games) { if (game->profile().isPlayable()) return &game->profile(); } @@ -214,10 +209,10 @@ bool Games::contains(String const &id) const Game &Games::byIndex(int idx) const { - if (idx < 0 || idx > d->games.count()) + if (idx < 0 || idx > d->games.sizei()) { /// @throw NotFoundError No game is associated with index @a idx. - throw NotFoundError("Games::byIndex", QString("There is no Game at index %i").arg(idx)); + throw NotFoundError("Games::byIndex", stringf("There is no Game at index %i", idx)); } return *d->games[idx]; } @@ -234,12 +229,12 @@ Games::All const &Games::all() const int Games::collectAll(GameList &collected) { - int numFoundSoFar = collected.count(); - foreach (Game *game, d->games) + int numFoundSoFar = collected.sizei(); + for (Game *game : d->games) { collected.push_back(GameListItem(game)); } - return collected.count() - numFoundSoFar; + return collected.sizei() - numFoundSoFar; } Game &Games::defineGame(String const &id, Record const ¶meters) @@ -297,9 +292,9 @@ void Games::locateStartupResources(Game &game) } */ -LoopResult Games::forAll(std::function callback) const +LoopResult Games::forAll(const std::function& callback) const { - foreach (Game *game, all()) + for (Game *game : all()) { if (auto result = callback(*game)) { @@ -342,8 +337,8 @@ void Games::checkReadiness() }); */ - QSet playable; - forAll([&playable](Game &game) { + Set playable; + forAll([&playable] (Game &game) if (game.isPlayable()) playable.insert(&game); return LoopContinue; }); @@ -356,12 +351,12 @@ void Games::checkReadiness() i->gameReadinessUpdated(); } } - d->lastCheckedPlayable = playable; + d->lastCheckedPlayable = std::move(playable); } /*void Games::forgetAllResources() { - foreach (Game *game, d->games) + for (Game *game : d->games) { foreach (ResourceManifest *manifest, game->manifests()) { @@ -393,7 +388,7 @@ D_CMD(ListGames) Games::GameList found; games.collectAll(found); // Sort so we get a nice alphabetical list. - qSort(found.begin(), found.end()); + found.sort(); String list; @@ -405,16 +400,16 @@ D_CMD(ListGames) if (!list.isEmpty()) list += "\n"; - list += String(_E(0) - _E(Ta) "%1%2 " - _E(Tb) "%3 " - _E(Tc) _E(2) "%4 " _E(i) "(%5)") - .arg(isCurrent? _E(B) _E(b) : - !game->allStartupFilesFound()? _E(D) : "") - .arg(isCurrent? "*" : !game->allStartupFilesFound()? "!" : " ") - .arg(game->id()) - .arg(game->title()) - .arg(game->author()); + list += String::format(_E(0) + _E(Ta) "%s%s " + _E(Tb) "%s " + _E(Tc) _E(2) "%s " _E(i) "(%s)", + isCurrent? _E(B) _E(b) : + !game->allStartupFilesFound()? _E(D) : "", + isCurrent? "*" : !game->allStartupFilesFound()? "!" : " ", + game->id().c_str(), + game->title().c_str(), + game->author().c_str()); if (game->allStartupFilesFound()) { diff --git a/doomsday/apps/libdoomsday/src/gamestatefolder.cpp b/doomsday/apps/libdoomsday/src/gamestatefolder.cpp index 3631f3d7e5..44fdb48cb3 100644 --- a/doomsday/apps/libdoomsday/src/gamestatefolder.cpp +++ b/doomsday/apps/libdoomsday/src/gamestatefolder.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #include #include @@ -260,27 +261,27 @@ void GameStateFolder::Metadata::parse(String const &source) clear(); Info info; - info.setAllowDuplicateBlocksOfType(QStringList() << BLOCK_GROUP << BLOCK_GAMERULE); + info.setAllowDuplicateBlocksOfType({BLOCK_GROUP, BLOCK_GAMERULE}); info.parse(source); // Rebuild the game rules subrecord. Record &rules = addSubrecord("gameRules"); - foreach (Info::Element const *elem, info.root().contentsInOrder()) + for (const auto *elem : info.root().contentsInOrder()) { if (Info::KeyElement const *key = maybeAs(elem)) { - QScopedPointer v(makeValueFromInfoValue(key->value())); - add(key->name()) = v.take(); + std::unique_ptr v(makeValueFromInfoValue(key->value())); + add(key->name()) = v.release(); continue; } if (Info::ListElement const *list = maybeAs(elem)) { - QScopedPointer arr(new ArrayValue); - foreach (Info::Element::Value const &v, list->values()) + std::unique_ptr arr(new ArrayValue); + for (Info::Element::Value const &v : list->values()) { *arr << makeValueFromInfoValue(v); } - addArray(list->name(), arr.take()); + addArray(list->name(), arr.release()); continue; } if (Info::BlockElement const *block = maybeAs(elem)) @@ -288,7 +289,7 @@ void GameStateFolder::Metadata::parse(String const &source) // Perhaps a ruleset group? if (block->blockType() == BLOCK_GROUP) { - foreach (Info::Element const *grpElem, block->contentsInOrder()) + for (Info::Element const *grpElem : block->contentsInOrder()) { if (!grpElem->isBlock()) continue; @@ -296,8 +297,8 @@ void GameStateFolder::Metadata::parse(String const &source) Info::BlockElement const &ruleBlock = grpElem->as(); if (ruleBlock.blockType() == BLOCK_GAMERULE) { - QScopedPointer v(makeValueFromInfoValue(ruleBlock.keyValue("value"))); - rules.add(ruleBlock.name()) = v.take(); + std::unique_ptr v(makeValueFromInfoValue(ruleBlock.keyValue("value"))); + rules.add(ruleBlock.name()) = v.release(); } } } @@ -306,7 +307,7 @@ void GameStateFolder::Metadata::parse(String const &source) } // Ensure the map URI has the "Maps" scheme set. - if (!gets("mapUri").beginsWith("Maps:", String::CaseInsensitive)) + if (!gets("mapUri").beginsWith("Maps:", CaseInsensitive)) { set("mapUri", String("Maps:") + gets("mapUri")); } @@ -317,14 +318,14 @@ void GameStateFolder::Metadata::parse(String const &source) // is encoded in the map URI and extract it. if (!has("episode")) { - String const mapUriPath = gets("mapUri").substr(5); - if (mapUriPath.beginsWith("MAP", String::CaseInsensitive)) + String const mapUriPath = gets("mapUri").substr(BytePos(5)); + if (mapUriPath.beginsWith("MAP", CaseInsensitive)) { set("episode", "1"); } - else if (mapUriPath.at(0).toLower() == 'e' && mapUriPath.at(2).toLower() == 'm') + else if (towlower(mapUriPath.first()) == 'e' && towlower(mapUriPath.at(BytePos(2))) == 'm') { - set("episode", mapUriPath.substr(1, 1)); + set("episode", mapUriPath.substr(BytePos(1), 1)); } else { @@ -364,11 +365,11 @@ void GameStateFolder::Metadata::parse(String const &source) String GameStateFolder::Metadata::asStyledText() const { - String currentMapText = String( - _E(Ta)_E(l) " Episode: " _E(.)_E(Tb) "%1\n" - _E(Ta)_E(l) " Uri: " _E(.)_E(Tb) "%2") - .arg(gets("episode")) - .arg(gets("mapUri")); + String currentMapText = String::format( + _E(Ta)_E(l) " Episode: " _E(.)_E(Tb) "%s\n" + _E(Ta)_E(l) " Uri: " _E(.)_E(Tb) "%s", + gets("episode").c_str(), + gets("mapUri").c_str()); // Is the time in the current map known? if (has("mapTime")) { @@ -376,15 +377,16 @@ String GameStateFolder::Metadata::asStyledText() const int const hours = time / 3600; time -= hours * 3600; int const minutes = time / 60; time -= minutes * 60; int const seconds = time; - currentMapText += String("\n" _E(Ta)_E(l) " Time: " _E(.)_E(Tb) "%1:%2:%3" ) - .arg(hours, 2, 10, QChar('0')) - .arg(minutes, 2, 10, QChar('0')) - .arg(seconds, 2, 10, QChar('0')); + currentMapText += String::format( + "\n" _E(Ta) _E(l) " Time: " _E(.) _E(Tb) "%02d:%02d:%02d", hours, minutes, seconds); } - QStringList rules = gets("gameRules", "None").split("\n", QString::SkipEmptyParts); - rules.replaceInStrings(QRegExp("\\s*(.*)\\s*:\\s*([^ ].*)\\s*"), _E(l) "\\1: " _E(.) "\\2"); - String gameRulesText = String::join(toStringList(rules), "\n - "); + StringList rules = gets("gameRules", "None").split(RegExp::WHITESPACE); + for (auto &r : rules) + { + r.replace(RegExp("\\s*(.*)\\s*:\\s*([^ ].*)\\s*"), _E(l) "\\1: " _E(.) "\\2"); + } + String gameRulesText = String::join(rules, "\n - "); auto const &pkgs = geta("packages"); StringList pkgIds; @@ -393,18 +395,18 @@ String GameStateFolder::Metadata::asStyledText() const pkgIds << Package::splitToHumanReadable(val->asText()); } - return String(_E(1) "%1\n" _E(.) - _E(Ta)_E(l) " Game: " _E(.)_E(Tb) "%2\n" - _E(Ta)_E(l) " Session ID: " _E(.)_E(Tb)_E(m) "0x%3" _E(.) "\n" - _E(T`)_E(D) "Current map:\n" _E(.) "%4\n" - _E(T`)_E(D) "Game rules:\n" _E(.) " - %5\n" - _E(T`)_E(D) "Packages:\n" _E(.) " - %6") - .arg(gets("userDescription", "")) - .arg(gets("gameIdentityKey", "")) - .arg(getui("sessionId", 0), 0, 16) - .arg(currentMapText) - .arg(gameRulesText) - .arg(String::join(pkgIds, "\n - ")); + return String::format(_E(1) "%s\n" _E(.) + _E(Ta)_E(l) " Game: " _E(.)_E(Tb) "%s\n" + _E(Ta)_E(l) " Session ID: " _E(.)_E(Tb)_E(m) "0x%x" _E(.) "\n" + _E(T`)_E(D) "Current map:\n" _E(.) "%s\n" + _E(T`)_E(D) "Game rules:\n" _E(.) " - %s\n" + _E(T`)_E(D) "Packages:\n" _E(.) " - %s", + gets("userDescription", "").c_str(), + gets("gameIdentityKey", "").c_str(), + getui("sessionId"), + currentMapText.c_str(), + gameRulesText.c_str(), + String::join(pkgIds, "\n - ").c_str()); } /* @@ -415,9 +417,7 @@ String GameStateFolder::Metadata::asInfo() const { /// @todo Use a more generic Record => Info conversion logic. - String text; - QTextStream os(&text); - os.setCodec("UTF-8"); + std::ostringstream os; if (has("gameIdentityKey")) os << "gameIdentityKey: " << gets("gameIdentityKey"); if (has("packages")) @@ -425,7 +425,7 @@ String GameStateFolder::Metadata::asInfo() const os << "\npackages " << geta("packages").asInfo(); } if (has("episode")) os << "\nepisode: " << gets("episode"); - if (has("mapTime")) os << "\nmapTime: " << String::number(geti("mapTime")); + if (has("mapTime")) os << "\nmapTime: " << geti("mapTime"); if (has("mapUri")) os << "\nmapUri: " << gets("mapUri"); if (has("players")) { @@ -443,7 +443,7 @@ String GameStateFolder::Metadata::asInfo() const { os << "\nvisitedMaps " << geta("visitedMaps").asInfo(); } - if (has("sessionId")) os << "\nsessionId: " << String::number(geti("sessionId")); + if (has("sessionId")) os << "\nsessionId: " << geti("sessionId"); if (has("userDescription")) os << "\nuserDescription: " << gets("userDescription"); if (hasSubrecord("gameRules")) @@ -453,18 +453,18 @@ String GameStateFolder::Metadata::asInfo() const Record const &rules = subrecord("gameRules"); DE_FOR_EACH_CONST(Record::Members, i, rules.members()) { - Value const &value = i.value()->value(); + const Value &value = i->second->value(); String valueAsText = value.asText(); if (is(value)) { valueAsText = "\"" + valueAsText.replace("\"", "''") + "\""; } - os << "\n " << BLOCK_GAMERULE << " \"" << i.key() << "\"" + os << "\n " << BLOCK_GAMERULE << " \"" << i->first << "\"" << " { value = " << valueAsText << " }"; } os << "\n}"; } - return text; + return os.str(); } diff --git a/doomsday/apps/libdoomsday/src/help.cpp b/doomsday/apps/libdoomsday/src/help.cpp index 1cf46d7a65..5781825756 100644 --- a/doomsday/apps/libdoomsday/src/help.cpp +++ b/doomsday/apps/libdoomsday/src/help.cpp @@ -28,13 +28,12 @@ #include #include -#include -#include +#include using namespace de; -typedef QMap StringsByType; // HST_* type => string -typedef QMap HelpStrings; // id => typed strings +typedef Map StringsByType; // HST_* type => string +typedef Map HelpStrings; // id => typed strings static HelpStrings helps; @@ -49,68 +48,70 @@ void Help_ReadStrings(File const &file) LOG_RES_VERBOSE("Reading help strings from ") << file.description(); de::Reader reader(file); - StringsByType *node = 0; + StringsByType *node = nullptr; while (!reader.atEnd()) { - String line = reader.readLine().trimmed(); + String line = reader.readLine().strip(); // Comments and empty lines are ignored. - if (line.isEmpty() || line.startsWith("#")) + if (line.isEmpty() || line.beginsWith("#")) continue; // A new node? - if (line.startsWith("[")) + if (line.beginsWith("[")) { - int end = line.indexOf(']'); - String id = line.mid(1, end > 0? end - 1 : -1).trimmed().toLower(); - node = &helps.insert(id, StringsByType()).value(); + auto end = line.indexOf(']'); + String id = line.substr(BytePos(1), end > 0 ? (end.index - 1) : String::npos) + .strip().lower(); + helps.insert(id, StringsByType()); + node = &helps.find(id)->second; LOG_TRACE_DEBUGONLY("Help node '%s'", id); } else if (node && line.contains('=')) // It must be a key? { int type = HST_DESCRIPTION; - if (line.startsWith("cv", Qt::CaseInsensitive)) + if (line.beginsWith("cv", CaseInsensitive)) { type = HST_CONSOLE_VARIABLE; } - else if (line.startsWith("def", Qt::CaseInsensitive)) + else if (line.beginsWith("def", CaseInsensitive)) { type = HST_DEFAULT_VALUE; } - else if (line.startsWith("inf", Qt::CaseInsensitive)) + else if (line.beginsWith("inf", CaseInsensitive)) { type = HST_INFO; } // Strip the beginning. - line = line.mid(line.indexOf('=') + 1).trimmed(); + line = line.substr(line.indexOf('=') + 1).strip(); // The full text is collected here. - QString text; + String text; // The value may be split over multiple lines. while (!line.isEmpty()) { // Process the current line. bool escape = false; - foreach (QChar ch, line) + for (Char ch : line) { - if (ch == QChar('\\')) + if (ch == Char('\\')) { escape = true; } else if (escape) { - if (ch == QChar('n') ) text = text % "\n"; - else if (ch == QChar('b') ) text = text % "\b"; - else if (ch == QChar('\\')) text = text % "\\"; + if (ch == Char('n') ) text += "\n"; + else if (ch == Char('b') ) text += "\b"; + else if (ch == Char('\\')) text += "\\"; escape = false; } else { - text = text % ch; + text += ch; } } @@ -120,7 +121,7 @@ void Help_ReadStrings(File const &file) if (escape) { // Line ended with a backslash; read the next line. - line = reader.readLine().trimmed(); + line = reader.readLine().strip(); } } @@ -134,27 +135,27 @@ void Help_ReadStrings(File const &file) HelpId DH_Find(char const *id) { // The identifiers are case insensitive. - HelpStrings::const_iterator found = helps.constFind(String(id).lower()); - if (found != helps.constEnd()) + HelpStrings::const_iterator found = helps.find(String(id).lower()); + if (found != helps.end()) { - return &found.value(); + return &found->second; } - return 0; + return nullptr; } char const *DH_GetString(HelpId found, int type) { - if (!found) return 0; - if (type < 0 || type > NUM_HELPSTRING_TYPES) return 0; + if (!found) return nullptr; + if (type < 0 || type > NUM_HELPSTRING_TYPES) return nullptr; StringsByType const *hs = reinterpret_cast(found); - StringsByType::const_iterator i = hs->constFind(type); - if (i != hs->constEnd()) + StringsByType::const_iterator i = hs->find(type); + if (i != hs->end()) { - return Str_Text(AutoStr_FromTextStd(i.value().toUtf8().constData())); + return Str_Text(AutoStr_FromTextStd(i->second.c_str())); } - return 0; + return nullptr; } void DD_InitHelp() diff --git a/doomsday/apps/libdoomsday/src/plugins.cpp b/doomsday/apps/libdoomsday/src/plugins.cpp index 2383a1fed2..82e5c1035e 100644 --- a/doomsday/apps/libdoomsday/src/plugins.cpp +++ b/doomsday/apps/libdoomsday/src/plugins.cpp @@ -25,8 +25,8 @@ #include #include #include -#include -#include +#include +#include using namespace de; @@ -36,15 +36,7 @@ struct ThreadState ThreadState() : currentPlugin(0) {} }; -#ifndef DE_QT_4_8_OR_NEWER // Qt 4.7 requires a pointer as the local data type -# define DE_LOCAL_DATA_POINTER -QThreadStorage pluginState; ///< Thread-local plugin state. -void initLocalData() { - if (!pluginState.hasLocalData()) pluginState.setLocalData(new ThreadState); -} -#else -QThreadStorage pluginState; ///< Thread-local plugin state. -#endif +static de::ThreadLocal pluginState; ///< Thread-local plugin state. bool Plugins::Hook::operator == (Hook const &other) const { @@ -81,7 +73,7 @@ DE_PIMPL_NOREF(Plugins) ::Library *hInstPlug[MAX_PLUGS]; ///< @todo Remove arbitrary MAX_PLUGS. - typedef QList HookRegister; + typedef List HookRegister; HookRegister hooks[NUM_HOOK_TYPES]; Impl() @@ -113,13 +105,13 @@ DE_PIMPL_NOREF(Plugins) #endif DE_ASSERT(!lib.path().isEmpty()); - if (strcasestr("/bin/audio_", lib.path().toUtf8().constData())) + if (lib.path().beginsWith("/bin/audio_", CaseInsensitive)) { // Do not touch audio plugins at this point. return true; } - ::Library *plugin = Library_New(lib.path().toUtf8().constData()); + ::Library *plugin = Library_New(lib.path()); if (!plugin) { #ifdef UNIX @@ -189,30 +181,18 @@ DE_PIMPL_NOREF(Plugins) void setActivePluginId(pluginid_t id) { -#ifdef DE_LOCAL_DATA_POINTER - initLocalData(); - pluginState.localData()->currentPlugin = id; -#else - pluginState.localData().currentPlugin = id; -#endif + pluginState.get().currentPlugin = id; } pluginid_t activePluginId() const { -#ifdef DE_LOCAL_DATA_POINTER - initLocalData(); - return pluginState.localData()->currentPlugin; -#else - return pluginState.localData().currentPlugin; -#endif + return pluginState.get().currentPlugin; } - DE_PIMPL_AUDIENCE(PublishAPI) - DE_PIMPL_AUDIENCE(Notification) + DE_PIMPL_AUDIENCES(PublishAPI, Notification) }; -DE_AUDIENCE_METHOD(Plugins, PublishAPI) -DE_AUDIENCE_METHOD(Plugins, Notification) +DE_AUDIENCE_METHODS(Plugins, PublishAPI, Notification) Plugins::Plugins() : d(new Impl) {} @@ -399,7 +379,7 @@ bool Plugins::removeHook(HookType type, hookfunc_t function) return false; } -LoopResult Plugins::forAllHooks(HookType type, std::function func) const +LoopResult Plugins::forAllHooks(HookType type, const std::function& func) const { for (Hook const &hook : d->hooks[type]) { diff --git a/doomsday/apps/libdoomsday/src/resource/databundle.cpp b/doomsday/apps/libdoomsday/src/resource/databundle.cpp index 61b92689ab..60625a798b 100644 --- a/doomsday/apps/libdoomsday/src/resource/databundle.cpp +++ b/doomsday/apps/libdoomsday/src/resource/databundle.cpp @@ -36,27 +36,27 @@ #include #include #include -#include -#include -#include +#include using namespace de; -static String const VAR_PATH ("path"); -static String const VAR_VERSION ("version"); -static String const VAR_LICENSE ("license"); -static String const VAR_AUTHOR ("author"); -static String const VAR_TITLE ("title"); -static String const VAR_TAGS ("tags"); -static String const VAR_NOTES ("notes"); -static String const VAR_DATA_FILES ("dataFiles"); -static String const VAR_BUNDLE_SCORE("bundleScore"); -static String const VAR_REQUIRES ("requires"); -static String const VAR_RECOMMENDS ("recommends"); -static String const VAR_EXTRAS ("extras"); -static String const VAR_CATEGORY ("category"); - -static String const CACHE_CATEGORY ("DataBundle"); +DE_STATIC_STRING(VAR_PATH, "path"); +DE_STATIC_STRING(VAR_VERSION, "version"); +DE_STATIC_STRING(VAR_LICENSE, "license"); +DE_STATIC_STRING(VAR_AUTHOR, "author"); +DE_STATIC_STRING(VAR_TITLE, "title"); +DE_STATIC_STRING(VAR_TAGS, "tags"); +DE_STATIC_STRING(VAR_NOTES, "notes"); +DE_STATIC_STRING(VAR_DATA_FILES, "dataFiles"); +DE_STATIC_STRING(VAR_BUNDLE_SCORE, "bundleScore"); +DE_STATIC_STRING(VAR_REQUIRES, "requires"); +DE_STATIC_STRING(VAR_RECOMMENDS, "recommends"); +DE_STATIC_STRING(VAR_EXTRAS, "extras"); +DE_STATIC_STRING(VAR_CATEGORY, "category"); + +DE_STATIC_STRING(CACHE_CATEGORY, "DataBundle"); + +static const char *TIMESTAMP_FORMAT = "0.%Y.%m%d.%H%M"; namespace internal { @@ -95,7 +95,7 @@ DE_PIMPL(DataBundle), public Lockable static Folder &bundleFolder() { - return App::rootFolder().locate(QStringLiteral("/sys/bundles")); + return App::rootFolder().locate(DE_STR("/sys/bundles")); } bool readLumpDirectory() @@ -215,8 +215,8 @@ DE_PIMPL(DataBundle), public Lockable // Finally, make a link that represents the package. if (auto chosen = chooseUniqueLinkPathAndVersion(self().asFile(), packageId, - meta.gets(VAR_VERSION), - meta.geti(VAR_BUNDLE_SCORE))) + meta.gets(VAR_VERSION()), + meta.geti(VAR_BUNDLE_SCORE()))) { LOGDEV_RES_VERBOSE("Linking %s as %s") << self().asFile().path() << chosen.path; @@ -227,7 +227,7 @@ DE_PIMPL(DataBundle), public Lockable // Set up package metadata in the link. Record &metadata = Package::initializeMetadata(*pkgLink, packageId); metadata.copyMembersFrom(meta); - metadata.set(VAR_VERSION, !chosen.version.isEmpty()? chosen.version : "0.0"); + metadata.set(VAR_VERSION(), !chosen.version.isEmpty()? chosen.version : "0.0"); // Compose a versioned ID. if (!chosen.version.isEmpty()) @@ -246,15 +246,15 @@ DE_PIMPL(DataBundle), public Lockable { //File &containerFile = *container->d->pkgLink; - String subset = VAR_RECOMMENDS; - String parentFolder = self().asFile().path().fileNamePath().fileName(); - if (!parentFolder.compareWithoutCase(QStringLiteral("Extra"))) + String subset = VAR_RECOMMENDS(); + String parentFolder = String(self().asFile().path().fileNamePath()).fileName(); + if (!parentFolder.compareWithoutCase(DE_STR("Extra"))) { - subset = VAR_EXTRAS; + subset = VAR_EXTRAS(); } - else if (!parentFolder.compareWithoutCase(QStringLiteral("Required"))) + else if (!parentFolder.compareWithoutCase(DE_STR("Required"))) { - subset = VAR_REQUIRES; + subset = VAR_REQUIRES(); } container->packageMetadata().insertToSortedArray(subset, new TextValue(versionedPackageId)); @@ -298,7 +298,7 @@ DE_PIMPL(DataBundle), public Lockable try { // Maybe we already have this? - if (Block cached = MetadataBank::get().check(CACHE_CATEGORY, metaId)) + if (Block cached = MetadataBank::get().check(CACHE_CATEGORY(), metaId)) { // Well, our work here has already been done. cached = cached.decompressed(); @@ -317,7 +317,7 @@ DE_PIMPL(DataBundle), public Lockable { Block buf; Writer(buf).withHeader() << meta; - MetadataBank::get().setMetadata(CACHE_CATEGORY, metaId, buf.compressed()); + MetadataBank::get().setMetadata(CACHE_CATEGORY(), metaId, buf.compressed()); } return meta; @@ -333,24 +333,24 @@ DE_PIMPL(DataBundle), public Lockable // Metadata for the package will be collected into this record. Record meta; - meta.set(VAR_PATH, dataFilePath); - meta.set(VAR_BUNDLE_SCORE, matched.bestScore); + meta.set(VAR_PATH(), dataFilePath); + meta.set(VAR_BUNDLE_SCORE(), matched.bestScore); if (format != Collection) { // Classic data files are loaded via the "dataFiles" array (in the listed order). // However, collections are represented directly as Doomsday packages. // Paths in "dataFiles" are relative to the package root. - meta.addArray(VAR_DATA_FILES, new ArrayValue({ new TextValue(dataFilePath.fileName()) })); + meta.addArray(VAR_DATA_FILES(), new ArrayValue({ new TextValue(dataFilePath.fileName()) })); } else { - meta.addArray(VAR_DATA_FILES); + meta.addArray(VAR_DATA_FILES()); // Collections have a number of subsets. - meta.addArray(VAR_REQUIRES); - meta.addArray(VAR_RECOMMENDS); - meta.addArray(VAR_EXTRAS); + meta.addArray(VAR_REQUIRES()); + meta.addArray(VAR_RECOMMENDS()); + meta.addArray(VAR_EXTRAS()); } // At least two criteria must match -- otherwise simply having the correct @@ -362,22 +362,22 @@ DE_PIMPL(DataBundle), public Lockable if (lumpDir) { - meta.set(QStringLiteral("lumpDirCRC32"), lumpDir->crc32()) + meta.set(DE_STR("lumpDirCRC32"), lumpDir->crc32()) .value().setSemanticHints(NumberValue::Hex); } meta.set(Package::VAR_TITLE, matched.bestMatch->keyValue("info:title")); - meta.set(VAR_VERSION, matched.packageVersion.fullNumber()); - meta.set(VAR_AUTHOR, matched.bestMatch->keyValue("info:author")); - meta.set(VAR_LICENSE, matched.bestMatch->keyValue("info:license", "Unknown")); - meta.set(VAR_TAGS, matched.bestMatch->keyValue("info:tags")); + meta.set(VAR_VERSION(), matched.packageVersion.fullNumber()); + meta.set(VAR_AUTHOR(), matched.bestMatch->keyValue("info:author")); + meta.set(VAR_LICENSE(), matched.bestMatch->keyValue("info:license", "Unknown")); + meta.set(VAR_TAGS(), matched.bestMatch->keyValue("info:tags")); } else { meta.set(Package::VAR_TITLE, self().asFile().name()); - meta.set(VAR_AUTHOR, "Unknown"); - meta.set(VAR_LICENSE, "Unknown"); - meta.set(VAR_TAGS, (format == Iwad || format == Pwad)? ".wad" : ""); + meta.set(VAR_AUTHOR(), "Unknown"); + meta.set(VAR_LICENSE(), "Unknown"); + meta.set(VAR_TAGS(), (format == Iwad || format == Pwad)? ".wad" : ""); // Generate a default identifier based on the information we have. static String const formatDomains[] = { @@ -414,13 +414,12 @@ DE_PIMPL(DataBundle), public Lockable &parsedVersion); if (strippedName != source->name() && parsedVersion.isValid()) { - meta.set(VAR_VERSION, parsedVersion.fullNumber()); + meta.set(VAR_VERSION(), parsedVersion.fullNumber()); } else { // Compose a default version number from file status. - meta.set(VAR_VERSION, self().asFile().status().modifiedAt - .asDateTime().toString("0.yyyy.MMdd.hhmm")); + meta.set(VAR_VERSION(), self().asFile().status().modifiedAt.asText(TIMESTAMP_FORMAT)); } packageId = stripRedundantParts(formatDomains[format] @@ -442,9 +441,9 @@ DE_PIMPL(DataBundle), public Lockable { // Check the Snowberry-style ID. String fn = dataFilePath.fileName(); - if (int dotPos = fn.lastIndexOf('.')) + if (auto dotPos = fn.lastIndexOf('.')) { - if (dotPos >= 0) fn[dotPos] = '-'; + *fn.writablePointer(dotPos) = '-'; } sbInfo = root.tryLocate(dataFilePath.fileNamePath()/fn + ".manifest"); } @@ -469,16 +468,16 @@ DE_PIMPL(DataBundle), public Lockable if (container && container->format() == Collection) { // Box contents are normally hidden. - meta.appendUniqueWord(VAR_TAGS, "hidden"); + meta.appendUniqueWord(VAR_TAGS(), "hidden"); } // Check for built-in tags. { // Cached copies of remote files. - if (dataFilePath.startsWith("/home/cache/remote/")) + if (dataFilePath.beginsWith("/home/cache/remote/")) { - meta.appendUniqueWord(VAR_TAGS, "hidden"); - meta.appendUniqueWord(VAR_TAGS, "cached"); + meta.appendUniqueWord(VAR_TAGS(), "hidden"); + meta.appendUniqueWord(VAR_TAGS(), "cached"); } // Master Levels of Doom. @@ -517,9 +516,9 @@ DE_PIMPL(DataBundle), public Lockable LOG_RES_VERBOSE("Identified \"%s\" %s %s score: %i") << packageId - << meta.gets(VAR_VERSION) + << meta.gets(VAR_VERSION()) << ::internal::formatDescriptions[format] - << meta.geti(VAR_BUNDLE_SCORE); // matched.bestScore; + << meta.geti(VAR_BUNDLE_SCORE()); // matched.bestScore; return meta; } @@ -534,7 +533,7 @@ DE_PIMPL(DataBundle), public Lockable { Block txt; *wadTxt >> txt; - meta.set(VAR_NOTES, _E(m) + String::fromCP437(txt)); + meta.set(VAR_NOTES(), _E(m) + String::fromCP437(txt)); } } } @@ -551,8 +550,8 @@ DE_PIMPL(DataBundle), public Lockable if (path.segmentCount() >= 3) { - String const parent = path.reverseSegment(1).toString().toLower(); - String const grandParent = path.reverseSegment(2).toString().toLower(); + String const parent = path.reverseSegment(1).toString().lower(); + String const grandParent = path.reverseSegment(2).toString().lower(); if (parent.fileNameExtension() == ".pk3" || parent.fileNameExtension() == ".zip" /*|| @@ -616,7 +615,7 @@ DE_PIMPL(DataBundle), public Lockable auto const &rootBlock = info.root(); // Tag it as a Snowberry package. - meta.appendUniqueWord(VAR_TAGS, "legacy"); + meta.appendUniqueWord(VAR_TAGS(), "legacy"); if (rootBlock.contains("name")) { @@ -628,16 +627,16 @@ DE_PIMPL(DataBundle), public Lockable { if (!component.compareWithoutCase("game-jdoom")) { - meta.appendUniqueWord(VAR_TAGS, "doom"); - meta.appendUniqueWord(VAR_TAGS, "doom2"); + meta.appendUniqueWord(VAR_TAGS(), "doom"); + meta.appendUniqueWord(VAR_TAGS(), "doom2"); } else if (!component.compareWithoutCase("game-jheretic")) { - meta.appendUniqueWord(VAR_TAGS, "heretic"); + meta.appendUniqueWord(VAR_TAGS(), "heretic"); } else if (!component.compareWithoutCase("game-jhexen")) { - meta.appendUniqueWord(VAR_TAGS, "hexen"); + meta.appendUniqueWord(VAR_TAGS(), "hexen"); } } @@ -651,8 +650,8 @@ DE_PIMPL(DataBundle), public Lockable category = category.trimmed(); if (!category.isEmpty()) { - meta.appendUniqueWord(VAR_TAGS, category); - meta.set(VAR_CATEGORY, category); + meta.appendUniqueWord(VAR_TAGS(), category); + meta.set(VAR_CATEGORY(), category); } } @@ -661,29 +660,29 @@ DE_PIMPL(DataBundle), public Lockable if (english->blockType() == "language") { // Doomsday must understand the version number. - Version const sbVer(english->keyValue(VAR_VERSION)); + Version const sbVer(english->keyValue(VAR_VERSION())); if (sbVer.isValid()) { - meta.set(VAR_VERSION, sbVer.fullNumber()); + meta.set(VAR_VERSION(), sbVer.fullNumber()); } - meta.set(VAR_AUTHOR, english->keyValue("author")); - meta.set(VAR_LICENSE, english->keyValue("license")); + meta.set(VAR_AUTHOR(), english->keyValue("author")); + meta.set(VAR_LICENSE(), english->keyValue("license")); meta.set("contact", english->keyValue("contact")); String notes = english->keyValue("readme").text.strip(); if (!notes.isEmpty()) { - notes.replace(QRegExp("\\s+"), " "); // normalize whitespace - meta.set(VAR_NOTES, notes); + notes.replace(RegExp::WHITESPACE, " "); // normalize whitespace + meta.set(VAR_NOTES(), notes); } } } if (parseErrorMsg) { - meta.appendUniqueWord(VAR_TAGS, "error"); - meta.set(VAR_NOTES, QObject::tr("There is an error in the metadata of this package: %1") - .arg(parseErrorMsg) + "\n\n" + meta.gets(VAR_NOTES, "")); + meta.appendUniqueWord(VAR_TAGS(), "error"); + meta.set(VAR_NOTES(), "There is an error in the metadata of this package: " + + parseErrorMsg + "\n\n" + meta.gets(VAR_NOTES(), "")); } } @@ -692,28 +691,23 @@ DE_PIMPL(DataBundle), public Lockable */ void parseNotesForMetadata(Record &meta) { - static QRegularExpression const reTitle - ("^[\\s\x1Bm]*Title\\s*:?\\s*(.*)", QRegularExpression::CaseInsensitiveOption); - static QRegularExpression const reVersion - ("^\\s*Version\\s*:\\s*(.*)", QRegularExpression::CaseInsensitiveOption); - static QRegularExpression const reReleaseDate - ("^\\s*Release( date)?\\s*:\\s*(.*)", QRegularExpression::CaseInsensitiveOption); - static QRegularExpression const reAuthor - ("^\\s*Author(s)?\\s*:?\\s*(.*)", QRegularExpression::CaseInsensitiveOption); - static QRegularExpression const reContact - ("^\\s*Email address\\s*:?\\s*(.*)", QRegularExpression::CaseInsensitiveOption); + static RegExp const reTitle ("^[\\s\x1Bm]*Title\\s*:\\s*(.*)", CaseInsensitive); + static RegExp const reVersion ("^\\s*Version\\s*:\\s*(.*)", CaseInsensitive); + static RegExp const reReleaseDate("^\\s*Release( date)?\\s*:\\s*(.*)", CaseInsensitive); + static RegExp const reAuthor ("^\\s*Author(s)?\\s*:\\s*(.*)", CaseInsensitive); + static RegExp const reContact ("^\\s*Email address\\s*:\\s*(.*)", CaseInsensitive); bool foundVersion = false; bool foundTitle = false; - foreach (String line, meta.gets(VAR_NOTES, "").split('\n')) + for (const auto &line : meta.gets(VAR_NOTES(), "").splitRef("\n")) { + RegExpMatch match; if (!foundTitle) { - auto match = reTitle.match(line); - if (match.hasMatch()) + if (reTitle.match(line, match)) { - meta.set(VAR_TITLE, match.captured(1).trimmed()); + meta.set(VAR_TITLE(), match.captured(1).strip()); foundTitle = true; continue; } @@ -721,44 +715,40 @@ DE_PIMPL(DataBundle), public Lockable if (!foundVersion) { - auto match = reReleaseDate.match(line); - if (match.hasMatch()) + if (reReleaseDate.match(line, match)) { - Date const releaseDate = Date::fromText(match.captured(2).trimmed()); + Date const releaseDate = Date::fromText(match.captured(2).strip()); if (releaseDate.isValid()) { - meta.set(VAR_VERSION, QString("%1.%2.%3") - .arg(releaseDate.year()) - .arg(releaseDate.month()) - .arg(releaseDate.dayOfMonth())); + meta.set(VAR_VERSION(), String::format("%i.%i.%i", + releaseDate.year(), + releaseDate.month(), + releaseDate.dayOfMonth())); } continue; } } - auto match = reVersion.match(line); - if (match.hasMatch()) + if (reVersion.match(line, match)) { - Version parsed(match.captured(1).trimmed()); + Version parsed(match.captured(1).strip()); if (parsed.isValid()) { - meta.set(VAR_VERSION, parsed.fullNumber()); + meta.set(VAR_VERSION(), parsed.fullNumber()); foundVersion = true; } continue; } - match = reAuthor.match(line); - if (match.hasMatch()) + if (reAuthor.match(line, match)) { - meta.set(VAR_AUTHOR, match.captured(2).trimmed()); + meta.set(VAR_AUTHOR(), match.captured(2).strip()); continue; } - match = reContact.match(line); - if (match.hasMatch()) + if (reContact.match(line, match)) { - meta.set("contact", match.captured(1).trimmed()); + meta.set("contact", match.captured(1).strip()); continue; } } @@ -771,7 +761,7 @@ DE_PIMPL(DataBundle), public Lockable identifiedTag.clear(); // Look for terms that refer to specific games. - static QList> terms; + static List> terms; if (terms.isEmpty()) { terms << std::make_pair(String("doom2"), StringList({ "\\b(doom2|doom 2|DoomII|Doom II|final\\s*doom|plutonia|tnt)\\b" })); @@ -779,14 +769,13 @@ DE_PIMPL(DataBundle), public Lockable terms << std::make_pair(String("heretic"), StringList({ "\\b(jheretic|heretic)\\b", "\\b(d'sparil|serpent rider)\\b" })); terms << std::make_pair(String("hexen"), StringList({ "\\b(jhexen|hexen)\\b", "\\b(korax|mage|warrior|cleric)\\b" })); } - QHash scores; - for (auto i : terms) //= terms.constBegin(); i != terms.constEnd(); ++i) + Hash scores; + for (auto &i : terms) //= terms.constBegin(); i != terms.constEnd(); ++i) { for (String const &term : i.second) { - QRegularExpression re(term, QRegularExpression::CaseInsensitiveOption); - auto match = re.match(text); - if (match.hasMatch()) + const RegExp re(term, CaseInsensitive); + if (re.hasMatch(text)) { //qDebug() << "match:" << term << "in" << match.captured() << "scoring for:" << i.first; //scores[i.key()]++; @@ -828,8 +817,9 @@ DE_PIMPL(DataBundle), public Lockable int count = 0; for (auto const &tag : gameTags()) { - if (QRegExp(QString("\\b%1\\b").arg(tag), Qt::CaseInsensitive) - .indexIn(meta.gets(VAR_TAGS)) >= 0) + const RegExp re(String::format("\\b%s\\b", tag.c_str()), CaseInsensitive); + RegExpMatch match; + if (re.hasMatch(meta.gets(VAR_TAGS()))) { // Already has at least one game tag. count++; @@ -840,17 +830,17 @@ DE_PIMPL(DataBundle), public Lockable static void removeGameTags(Record &meta) { - String newTags = meta.gets(VAR_TAGS); - newTags.remove(QRegularExpression(anyGameTagPattern())); -// foreach (QString tag, Package::tags(meta.gets(VAR_TAGS))) + String newTags = meta.gets(VAR_TAGS()); + newTags = newTags.removed(RegExp(anyGameTagPattern())); +// foreach (QString tag, Package::tags(meta.gets(VAR_TAGS()))) // { // if (!gameTags().contains(tag)) // { -// if (!newTags.isEmpty()) newTags += QStringLiteral(" "); +// if (!newTags.isEmpty()) newTags += DE_STR(" "); // newTags += tag; // } // } - meta.set(VAR_TAGS, newTags); + meta.set(VAR_TAGS(), newTags); } /** @@ -859,35 +849,35 @@ DE_PIMPL(DataBundle), public Lockable */ void determineGameTags(Record &meta) { - //qDebug() << "Determining:" << meta.gets(VAR_TITLE) << meta.gets(VAR_TAGS); + //qDebug() << "Determining:" << meta.gets(VAR_TITLE()) << meta.gets(VAR_TAGS()); if (!containsAmbiguousGameTags(meta)) { // Already has exactly one game tag. - //qDebug() << meta.gets(VAR_TITLE) << "- unambiguous"; + //qDebug() << meta.gets(VAR_TITLE()) << "- unambiguous"; return; } - String const oldTags = meta.gets(VAR_TAGS); + String const oldTags = meta.gets(VAR_TAGS()); String tag; - if (identifyMostLikelyGame(meta.gets(VAR_TITLE), tag)) + if (identifyMostLikelyGame(meta.gets(VAR_TITLE()), tag)) { - //qDebug() << meta.gets(VAR_TITLE)<< "- from title:" << tag; + //qDebug() << meta.gets(VAR_TITLE())<< "- from title:" << tag; removeGameTags(meta); - meta.appendUniqueWord(VAR_TAGS, tag); + meta.appendUniqueWord(VAR_TAGS(), tag); } else if (identifyMostLikelyGame(meta.gets("ID"), tag)) { - //qDebug() << meta.gets(VAR_TITLE) << "- from package ID:" << tag; + //qDebug() << meta.gets(VAR_TITLE()) << "- from package ID:" << tag; removeGameTags(meta); - meta.appendUniqueWord(VAR_TAGS, tag); + meta.appendUniqueWord(VAR_TAGS(), tag); } - else if (identifyMostLikelyGame(meta.gets(VAR_NOTES, ""), tag)) + else if (identifyMostLikelyGame(meta.gets(VAR_NOTES(), ""), tag)) { - //qDebug() << meta.gets(VAR_TITLE)<< "- from notes:" << tag; + //qDebug() << meta.gets(VAR_TITLE())<< "- from notes:" << tag; removeGameTags(meta); - meta.appendUniqueWord(VAR_TAGS, tag); + meta.appendUniqueWord(VAR_TAGS(), tag); } if (!containsAnyGameTag(meta)) @@ -897,19 +887,19 @@ DE_PIMPL(DataBundle), public Lockable Path const path(self().asFile().path()); for (int i = 0; i < path.segmentCount(); ++i) { - if (identifyMostLikelyGame(path.segment(i), tag)) + if (identifyMostLikelyGame(path.segment(i).toString(), tag)) { - //qDebug() << meta.gets(VAR_TITLE)<< "- from path:" << tag; - meta.appendUniqueWord(VAR_TAGS, tag); + //qDebug() << meta.gets(VAR_TITLE())<< "- from path:" << tag; + meta.appendUniqueWord(VAR_TAGS(), tag); } } } if (!containsAnyGameTag(meta)) { - //qDebug() << meta.gets(VAR_TITLE)<< "- falling back to:" << oldTags; + //qDebug() << meta.gets(VAR_TITLE())<< "- falling back to:" << oldTags; // Failed to figure out anything, so fall back to the old tags. - meta.set(VAR_TAGS, oldTags); + meta.set(VAR_TAGS(), oldTags); } } @@ -968,18 +958,18 @@ DE_PIMPL(DataBundle), public Lockable // Larger versions are preferred when multiple versions are available, // so use the major version 0 to avoid always preferring these date-based // versions. - version = dataFile.status().modifiedAt.asDateTime().toString("0.yyyy.MMdd.hhmm"); + version = dataFile.status().modifiedAt.asText(TIMESTAMP_FORMAT); break; } if (!version.isEmpty()) { DE_ASSERT(Version(version).isValid()); - linkPath += QString("_%1.pack").arg(version); + linkPath += String::format("_%s.pack", version.c_str()); } else { - linkPath += QStringLiteral(".pack"); + linkPath += DE_STR(".pack"); } //qDebug() << "checking" << linkPath; @@ -1025,15 +1015,15 @@ DE_PIMPL(DataBundle), public Lockable { if (!pkgLink) return String(); - QSet tags; - foreach (QString tag, Package::tags(*pkgLink)) tags.insert(tag); + Set tags; + for (const String &tag : Package::tags(*pkgLink)) tags.insert(tag); // Check for tags matching game IDs. /* { String matchingGameId; if (DoomsdayApp::games().forAll([&tags, &matchingGameId] (Game &game) { - QRegularExpression re(QString("\\b%1\\b").arg(game.id())); + RegExp re(QString("\\b%1\\b").arg(game.id())); if (re.match(text).hasMatch()) { matchinGameId = game.id(); @@ -1110,9 +1100,7 @@ String DataBundle::description() const { return "invalid data bundle"; } - return QString("%1 %2") - .arg(::internal::formatDescriptions[d->format]) - .arg(d->source->description()); + return String(::internal::formatDescriptions[d->format]) + " " + d->source->description(); } File &DataBundle::asFile() @@ -1179,13 +1167,13 @@ void DataBundle::set(Offset, Byte const *, Size) Record &DataBundle::objectNamespace() { DE_ASSERT(dynamic_cast(this) != nullptr); - return asFile().objectNamespace().subrecord(QStringLiteral("package")); + return asFile().objectNamespace().subrecord(DE_STR("package")); } Record const &DataBundle::objectNamespace() const { DE_ASSERT(dynamic_cast(this) != nullptr); - return asFile().objectNamespace().subrecord(QStringLiteral("package")); + return asFile().objectNamespace().subrecord(DE_STR("package")); } DataBundle::Format DataBundle::packageBundleFormat(String const &packageId) // static @@ -1315,7 +1303,7 @@ File *DataBundle::Interpreter::interpretFile(File *sourceData) const } // Naive check using the file extension. - static struct { String str; Format format; } formats[] = { + static const struct { String str; Format format; } formats[] = { { ".pk3.zip", Pk3 }, { ".pk3", Pk3 }, { ".wad", Wad /* type (I or P) checked later */ }, @@ -1324,10 +1312,10 @@ File *DataBundle::Interpreter::interpretFile(File *sourceData) const { ".deh", Dehacked }, { ".box", Collection }, }; - //String const ext = sourceData->extension(); + for (auto const &fmt : formats) { - if (sourceData->name().endsWith(fmt.str, String::CaseInsensitive)) + if (sourceData->name().endsWith(fmt.str, CaseInsensitive)) { LOG_RES_XVERBOSE("Interpreted %s as %s", sourceData->description() << @@ -1348,9 +1336,9 @@ File *DataBundle::Interpreter::interpretFile(File *sourceData) const return nullptr; } -QList DataBundle::loadedBundles() // static +List DataBundle::loadedBundles() // static { - QList loaded; + List loaded; // Check all the loaded packages to see which ones are data bundles. for (auto *f : PackageLoader::get().loadedPackagesAsFilesInPackageOrder()) @@ -1367,9 +1355,9 @@ QList DataBundle::loadedBundles() // static DE_ASSERT(pkg); auto const &meta = Package::metadata(*f); - if (meta.has(VAR_DATA_FILES)) + if (meta.has(VAR_DATA_FILES())) { - foreach (Value const *v, meta.geta(VAR_DATA_FILES).elements()) + for (const Value *v : meta.geta(VAR_DATA_FILES()).elements()) { String const dataFilePath = v->asText(); @@ -1401,15 +1389,15 @@ QList DataBundle::loadedBundles() // static return loaded; } -QList DataBundle::findAllNative(String const &fileNameOrPartialNativePath) +List DataBundle::findAllNative(String const &fileNameOrPartialNativePath) { NativePath const searchPath = NativePath(fileNameOrPartialNativePath).expand(); FS::FoundFiles found; - FS::get().findAllOfTypes(StringList({ DE_TYPE_NAME(DataFile), - DE_TYPE_NAME(DataFolder) }), - searchPath.fileName().toLower(), found); - QList bundles; + FS::get().findAllOfTypes({DE_TYPE_NAME(DataFile), + DE_TYPE_NAME(DataFolder) }, + searchPath.fileName().lower(), found); + List bundles; for (auto const *f : found) { DE_ASSERT(dynamic_cast(f)); @@ -1425,7 +1413,7 @@ QList DataBundle::findAllNative(String const &fileNameOrPart if (bundlePath.isEmpty()) return false; //qDebug() << "bundle:" << path.asText() << "searchTerm:" << searchPath.fileNamePath(); if (bundlePath.toString().endsWith(searchPath.fileNamePath(), - String::CaseInsensitive)) + CaseInsensitive)) { return true; } @@ -1444,7 +1432,7 @@ StringList DataBundle::gameTags() String DataBundle::anyGameTagPattern() { - return String("\\b(%1)\\b").arg(String::join(gameTags(), "|")); + return String::format("\\b(%1)\\b", String::join(gameTags(), "|").c_str()); } String DataBundle::cleanIdentifier(String const &text) @@ -1454,23 +1442,24 @@ String DataBundle::cleanIdentifier(String const &text) // Info syntax has ambiguous quote/double-quote escaping in strings, so // we'll also get rid of single quotes. (For example, Info converts a string // containing ['"] to ['''].) - String cleaned = text.toLower(); - cleaned.replace(QRegExp("[._'\\s]"), "-"); + String cleaned = text.lower(); + cleaned.replace(RegExp("[._'\\s]"), "-"); return cleaned; } String DataBundle::stripVersion(String const &text, Version *version) { - QRegExp re(".*([-_. ]v?([0-9._-]+))$"); - if (re.exactMatch(text)) + static const RegExp re(".*([-_. ]v?([0-9._-]+))$"); + RegExpMatch match; + if (re.exactMatch(text, match)) { if (version) { - String str = re.cap(2); + String str = match.captured(2); str.replace("_", "."); version->parseVersionString(str); } - return text.mid(0, text.size() - re.cap(1).size()); + return text.substr(BytePos(0), text.size() - match.captured(1).size()); } return text; } @@ -1478,15 +1467,15 @@ String DataBundle::stripVersion(String const &text, Version *version) String DataBundle::stripRedundantParts(String const &id) { DotPath const path(id); - String stripped = path.segment(0); + String stripped = path.segment(0).toString(); for (int i = 1; i < path.segmentCount(); ++i) { String seg = path.segment(i); for (int k = 1; k <= i; ++k) // Check all previous segments. { - if (seg.startsWith(path.segment(i - k) + "-")) + if (seg.beginsWith(path.segment(i - 1) + "-")) { - seg = seg.mid(path.segment(i - k).size() + 1); + seg = seg.substr(BytePos(CString(path.segment(i - k)).size()) + 1); break; } } @@ -1497,7 +1486,7 @@ String DataBundle::stripRedundantParts(String const &id) de::String DataBundle::versionFromTimestamp(const Time ×tamp) { - return timestamp.asDateTime().toString(QStringLiteral("0.yyyy.MMdd.hhmm")); + return timestamp.asText(TIMESTAMP_FORMAT); } void DataBundle::checkAuxiliaryNotes(Record &packageMetadata) diff --git a/doomsday/apps/libdoomsday/src/resource/lumpdirectory.cpp b/doomsday/apps/libdoomsday/src/resource/lumpdirectory.cpp index b9db0c2100..3bc7a48d0e 100644 --- a/doomsday/apps/libdoomsday/src/resource/lumpdirectory.cpp +++ b/doomsday/apps/libdoomsday/src/resource/lumpdirectory.cpp @@ -21,8 +21,7 @@ #include #include #include -#include -#include +#include using namespace de; @@ -32,17 +31,17 @@ const dsize LumpDirectory::InvalidPos = dsize(-1); static const String CACHE_CATEGORY = "LumpDirectory"; -static const QRegularExpression regExMy ("^E[1-9]M[1-9]$"); -static const QRegularExpression regMAPxx("^MAP[0-9][0-9]$"); -static const Block flatMarkers[4] = {"FF_START", "FF_END", "F_START", "F_END"}; +static const RegExp regExMy ("^E[1-9]M[1-9]$"); +static const RegExp regMAPxx("^MAP[0-9][0-9]$"); +static const Block flatMarkers[4] = {"FF_START", "FF_END", "F_START", "F_END"}; DE_PIMPL_NOREF(LumpDirectory), public ISerializable { - Type type = Invalid; - MapType mapType = None; - duint32 crc = 0; - QList entries; - QHash index; // points to entries + Type type = Invalid; + MapType mapType = None; + duint32 crc = 0; + List entries; + Hash index; // points to entries void read(IByteArray const &source) { @@ -69,7 +68,7 @@ DE_PIMPL_NOREF(LumpDirectory), public ISerializable reader.setOffset(dirOffset); reader.readBytes(16 * count, data); - crc = M_CRC32(data.dataConst(), uint(data.size())); + crc = crc32_Block(data); // Read all the entries. Reader lumpReader(data); @@ -78,7 +77,7 @@ DE_PIMPL_NOREF(LumpDirectory), public ISerializable Entry entry; lumpReader >> entry.offset >> entry.size; lumpReader.readBytes(8, entry.name); - entry.name.resize(qstrlen(entry.name)); // QByteArray is zero-terminated + entry.name.resize(strlen(entry.name.data())); // QByteArray is zero-terminated entries.append(entry); } diff --git a/doomsday/apps/libdoomsday/src/resource/manifest.cpp b/doomsday/apps/libdoomsday/src/resource/manifest.cpp index f8802a7506..1ac40c455d 100644 --- a/doomsday/apps/libdoomsday/src/resource/manifest.cpp +++ b/doomsday/apps/libdoomsday/src/resource/manifest.cpp @@ -37,11 +37,11 @@ DE_PIMPL(ResourceManifest) resourceclassid_t classId; int flags; ///< @ref fileFlags. - QStringList names; ///< Known names in precedence order. + StringList names; ///< Known names in precedence order. /// Vector of resource identifier keys (e.g., file or lump names). /// Used for identification purposes. - QStringList identityKeys; + StringList identityKeys; /// Index (in Manifest::Impl::names) of the name used to locate /// this resource if found. Set during resource location. @@ -68,7 +68,7 @@ ResourceManifest::ResourceManifest(resourceclassid_t resClass, int fFlags, Strin if (name) addName(*name); } -void ResourceManifest::addName(String newName) +void ResourceManifest::addName(const String& newName) { if (newName.isEmpty()) return; diff --git a/doomsday/apps/libdoomsday/src/savegames.cpp b/doomsday/apps/libdoomsday/src/savegames.cpp index b6161b1da7..73e45af5e6 100644 --- a/doomsday/apps/libdoomsday/src/savegames.cpp +++ b/doomsday/apps/libdoomsday/src/savegames.cpp @@ -30,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -108,9 +109,9 @@ DE_PIMPL(SaveGames) String const outputPath = String("/home/savegames") / gameId; FileSystem::get().makeFolder(outputPath); - Str_Set(Str_InitStd(&parm.sourcePath), sourcePath.toUtf8().constData()); - Str_Set(Str_InitStd(&parm.outputPath), outputPath.toUtf8().constData()); - Str_Set(Str_InitStd(&parm.fallbackGameId), gameId.toUtf8().constData()); + Str_Set(Str_InitStd(&parm.sourcePath), sourcePath); + Str_Set(Str_InitStd(&parm.outputPath), outputPath); + Str_Set(Str_InitStd(&parm.fallbackGameId), gameId); } else { @@ -232,9 +233,9 @@ bool SaveGames::convertLegacySavegames(String const &gameId, String const &sourc /// attempting to convert Hexen's map state sidecar files separately when this /// is called from Doomsday Script (in bootstrap.de). Game const &game = DoomsdayApp::games()[gameId]; - QRegExp namePattern(game.legacySavegameNameExp(), Qt::CaseInsensitive); - if (namePattern.isValid() && !namePattern.isEmpty()) + if (game.legacySavegameNameExp()) { + RegExp namePattern(game.legacySavegameNameExp(), CaseInsensitive); saveFolder->forContents([this, &gameId, &namePattern, &didSchedule] (String name, File &file) { if (namePattern.exactMatch(name.fileName())) diff --git a/doomsday/apps/libdoomsday/src/uri.cpp b/doomsday/apps/libdoomsday/src/uri.cpp index 7209b7c932..c12a73e4e4 100644 --- a/doomsday/apps/libdoomsday/src/uri.cpp +++ b/doomsday/apps/libdoomsday/src/uri.cpp @@ -34,9 +34,6 @@ #include #include -#include -#include - namespace de { static Uri::ResolverFunc resolverFunc; @@ -51,22 +48,23 @@ static Uri::ResolverFunc resolverFunc; static String extractScheme(String &stringWithScheme) { String scheme; - int pos = stringWithScheme.indexOf(':'); - if (pos > URI_MINSCHEMELENGTH) // could be Windows-style driver letter "c:" + auto pos = stringWithScheme.indexOf(':'); + if (pos && pos > URI_MINSCHEMELENGTH) // could be Windows-style driver letter "c:" { scheme = stringWithScheme.left(pos); - stringWithScheme.remove(0, pos + 1); + stringWithScheme.remove(BytePos(0), pos + 1); } return scheme; } DE_PIMPL_NOREF(Uri) { - Path path; ///< Path of the Uri. + DE_NO_ASSIGN(Impl) - DualString strPath; // Redundant; for legacy access, remove this! + Path path; ///< Path of the Uri. - DualString scheme; ///< Scheme of the Uri. + String strPath; // Redundant; for legacy access, remove this! + String scheme; ///< Scheme of the Uri. /// Cached copy of the resolved path. Path resolvedPath; @@ -77,9 +75,9 @@ DE_PIMPL_NOREF(Uri) * @note Add any other conditions here that result in different results for * resolveUri(). */ - void *resolvedForGame; + const Game *resolvedForGame; - Impl() : resolvedForGame(0) + Impl() : resolvedForGame(nullptr) {} Impl(Impl const &other) @@ -94,10 +92,10 @@ DE_PIMPL_NOREF(Uri) void clearCachedResolved() { resolvedPath.clear(); - resolvedForGame = 0; + resolvedForGame = nullptr; } - void parseRawUri(String rawUri, QChar sep, resourceclassid_t defaultResourceClass) + void parseRawUri(String rawUri, Char sep, resourceclassid_t defaultResourceClass) { LOG_AS("Uri::parseRawUri"); @@ -131,16 +129,16 @@ DE_PIMPL_NOREF(Uri) } } - String resolveSymbol(QStringRef const &symbol) const + String resolveSymbol(const String &symbol) const { if (!resolverFunc) { - return symbol.toString(); + return symbol; } - return resolverFunc(symbol.toString()); + return resolverFunc(symbol); } - inline String parseExpression(QStringRef const &expression) const + inline String parseExpression(const String &expression) const { // Presently the expression consists of a single symbol. return resolveSymbol(expression); @@ -153,33 +151,33 @@ DE_PIMPL_NOREF(Uri) String result; // Keep scanning the path for embedded expressions. - QStringRef expression; - int expEnd = 0, expBegin; - while ((expBegin = strPath.indexOf('$', expEnd)) >= 0) + String expression; + BytePos expEnd{0}, expBegin; + while ((expBegin = strPath.indexOf("$", expEnd)) != BytePos::npos) { // Is the next char the start-of-expression character? if (strPath.at(expBegin + 1) == '(') { // Copy everything up to the '$'. - result += strPath.mid(expEnd, expBegin - expEnd); + result += strPath.substr(expEnd, expBegin - expEnd); // Skip over the '$'. ++expBegin; // Find the end-of-expression character. - expEnd = strPath.indexOf(')', expBegin); - if (expEnd < 0) + expEnd = strPath.indexOf(")", expBegin); + if (!expEnd) { LOG_RES_WARNING("Ignoring expression \"" + strPath + "\": " "missing a closing ')'"); - expEnd = strPath.length(); + expEnd = strPath.sizeb(); } // Skip over the '('. ++expBegin; // The range of the expression substring is now known. - expression = strPath.midRef(expBegin, expEnd - expBegin); + expression = strPath.substr(expBegin, expEnd - expBegin); result += parseExpression(expression); } @@ -193,12 +191,10 @@ DE_PIMPL_NOREF(Uri) } // Copy anything remaining. - result += strPath.mid(expEnd); + result += strPath.substr(expEnd); return result; } - - Impl &operator = (Impl const &) = delete; // no assignment }; Uri::Uri() : d(new Impl) @@ -212,7 +208,7 @@ Uri::Uri(String const &percentEncoded) : d(new Impl) } } -Uri::Uri(String const &percentEncoded, resourceclassid_t defaultResourceClass, QChar sep) +Uri::Uri(String const &percentEncoded, resourceclassid_t defaultResourceClass, Char sep) : d(new Impl) { if (!percentEncoded.isEmpty()) @@ -253,12 +249,11 @@ Uri Uri::fromUserInput(char **argv, int argc, bool (*knownScheme) (String name)) case 1: { // Try to extract the scheme and encode the rest of the path. String rawUri(argv[0]); - int pos = rawUri.indexOf(':'); - if (pos >= 0) + if (auto pos = rawUri.indexOf(':')) { output.setScheme(rawUri.left(pos)); - rawUri.remove(0, pos + 1); - output.setPath(Path::normalize(QString(QByteArray(rawUri.toUtf8()).toPercentEncoding()))); + rawUri.remove(BytePos(0), pos + 1); + output.setPath(Path::normalize(rawUri.toPercentEncoding())); } // Just a scheme name? else if (knownScheme && knownScheme(rawUri)) @@ -268,7 +263,7 @@ Uri Uri::fromUserInput(char **argv, int argc, bool (*knownScheme) (String name)) else { // Just a path. - output.setPath(Path::normalize(QString(QByteArray(rawUri.toUtf8()).toPercentEncoding()))); + output.setPath(Path::normalize(rawUri.toPercentEncoding())); } break; } @@ -276,7 +271,7 @@ Uri Uri::fromUserInput(char **argv, int argc, bool (*knownScheme) (String name)) case 2: // Assign the scheme and encode the path. output.setScheme(argv[0]); - output.setPath(Path::normalize(QString(QByteArray(argv[1]).toPercentEncoding()))); + output.setPath(Path::normalize(String(argv[1]).toPercentEncoding())); break; default: break; @@ -296,7 +291,7 @@ Uri Uri::fromNativePath(NativePath const &path, resourceclassid_t defaultResourc Uri Uri::fromNativeDirPath(NativePath const &nativeDirPath, resourceclassid_t defaultResourceClass) { // Uri follows the convention of having a slash at the end for directories. - return Uri(nativeDirPath.expand().withSeparators('/') + '/', defaultResourceClass); + return Uri(nativeDirPath.expand().withSeparators('/') + "/", defaultResourceClass); } bool Uri::isEmpty() const @@ -318,9 +313,9 @@ bool Uri::operator == (Uri const &other) const try { // Do not match partial paths. - if (resolvedRef().length() != other.resolvedRef().length()) return false; + if (resolved().length() != other.resolved().length()) return false; - return resolvedRef().compareWithoutCase(other.resolvedRef()) == 0; + return resolved().compareWithoutCase(other.resolved()) == 0; } catch (ResolveError const &) { @@ -350,15 +345,15 @@ Path const &Uri::path() const char const *Uri::schemeCStr() const { - return d->scheme.utf8CStr(); + return d->scheme; } char const *Uri::pathCStr() const { - return d->strPath.utf8CStr(); + return d->strPath; } -ddstring_s const *Uri::schemeStr() const +/*ddstring_s const *Uri::schemeStr() const { return d->scheme.toStr(); } @@ -366,22 +361,18 @@ ddstring_s const *Uri::schemeStr() const ddstring_s const *Uri::pathStr() const { return d->strPath.toStr(); -} +}*/ String Uri::resolved() const { - return resolvedRef(); -} - -String const &Uri::resolvedRef() const -{ - void *currentGame = (void *) (!App::appExists() || DoomsdayApp::game().isNull()? 0 : &DoomsdayApp::game()); + const Game *currentGame = + (!App::appExists() || DoomsdayApp::game().isNull() ? nullptr : &DoomsdayApp::game()); #ifndef DE_DISABLE_URI_RESOLVE_CACHING if (d->resolvedForGame && d->resolvedForGame == currentGame) { // We can just return the previously prepared resolved URI. - return d->resolvedPath.toStringRef(); + return d->resolvedPath; } #endif @@ -390,16 +381,16 @@ String const &Uri::resolvedRef() const // Keep a copy of this, we'll likely need it many, many times. d->resolvedPath = d->resolve(); - DE_ASSERT(d->resolvedPath.separator() == QChar('/')); + DE_ASSERT(d->resolvedPath.separator() == Char('/')); d->resolvedForGame = currentGame; - return d->resolvedPath.toStringRef(); + return d->resolvedPath.toString(); } Uri &Uri::setScheme(String newScheme) { - d->scheme = newScheme; + d->scheme = std::move(newScheme); d->clearCachedResolved(); return *this; } @@ -409,29 +400,29 @@ Uri &Uri::setPath(Path const &newPath) // Force to slashes. d->path = newPath.withSeparators('/'); - d->strPath = d->path.toStringRef(); // legacy support + d->strPath = d->path.toString(); // legacy support d->clearCachedResolved(); return *this; } -Uri &Uri::setPath(String newPath, QChar sep) +Uri &Uri::setPath(const String& newPath, Char sep) { - return setPath(Path(newPath.trimmed(), sep)); + return setPath(Path(newPath.strip(), sep)); } Uri &Uri::setPath(char const *newPathUtf8, char sep) { - return setPath(Path(QString::fromUtf8(newPathUtf8).trimmed(), sep)); + return setPath(Path(String(newPathUtf8).strip(), sep)); } -Uri &Uri::setUri(String rawUri, resourceclassid_t defaultResourceClass, QChar sep) +Uri &Uri::setUri(const String& rawUri, resourceclassid_t defaultResourceClass, Char sep) { LOG_AS("Uri::setUri"); - d->parseRawUri(rawUri.trimmed(), sep, defaultResourceClass); + d->parseRawUri(rawUri.strip(), sep, defaultResourceClass); return *this; } -String Uri::compose(ComposeAsTextFlags compositionFlags, QChar sep) const +String Uri::compose(ComposeAsTextFlags compositionFlags, Char sep) const { String text; if (!(compositionFlags & OmitScheme)) @@ -443,10 +434,10 @@ String Uri::compose(ComposeAsTextFlags compositionFlags, QChar sep) const } if (!(compositionFlags & OmitPath)) { - QString path = d->path.withSeparators(sep); + String path = d->path.withSeparators(sep); if (compositionFlags & DecodePath) { - path = QByteArray::fromPercentEncoding(path.toUtf8()); + path = String::fromPercentEncoding(path); } text += path; } @@ -477,7 +468,7 @@ void Uri::setResolverFunc(ResolverFunc resolver) resolverFunc = resolver; } -void Uri::readUri(reader_s *reader, String defaultScheme) +void Uri::readUri(reader_s *reader, const String& defaultScheme) { clear(); @@ -491,7 +482,7 @@ void Uri::readUri(reader_s *reader, String defaultScheme) if (Str_IsEmpty(&scheme) && !defaultScheme.isEmpty()) { - Str_Set(&scheme, defaultScheme.toUtf8().constData()); + Str_Set(&scheme, defaultScheme); } setScheme(Str_Text(&scheme)); @@ -508,9 +499,9 @@ void Uri::writeUri(writer_s *writer, int omitComponents) const } else { - Str_Write(DualString(scheme()).toStrUtf8(), writer); + Str_Write(AutoStr_FromTextStd(scheme()), writer); } - Str_Write(DualString(path()).toStrUtf8(), writer); + Str_Write(AutoStr_FromTextStd(path()), writer); } #ifdef _DEBUG @@ -608,7 +599,7 @@ DE_DEFINE_UNITTEST(Uri) } catch (Error const &er) { - qWarning() << er.asText(); + er.warnPlainText(); return false; } return true; diff --git a/doomsday/apps/libdoomsday/src/urivalue.cpp b/doomsday/apps/libdoomsday/src/urivalue.cpp index 0f85351034..a63953199b 100644 --- a/doomsday/apps/libdoomsday/src/urivalue.cpp +++ b/doomsday/apps/libdoomsday/src/urivalue.cpp @@ -65,7 +65,7 @@ bool UriValue::contains(Value const &value) const // type conversions. if (is(value)) { - return _uri.asText().indexOf(value.asText(), Qt::CaseSensitive) >= 0; + return _uri.asText().indexOf(value.asText(), CaseSensitive) >= 0; } return Value::contains(value); } diff --git a/doomsday/apps/libdoomsday/src/world/entitydatabase.cpp b/doomsday/apps/libdoomsday/src/world/entitydatabase.cpp index 3a4a02a5e0..094fa5df23 100644 --- a/doomsday/apps/libdoomsday/src/world/entitydatabase.cpp +++ b/doomsday/apps/libdoomsday/src/world/entitydatabase.cpp @@ -88,9 +88,10 @@ DE_PIMPL(EntityDatabase) Entity const *entity = entityByElementIndex(*set, elementIndex, false /*do not create*/); if (!entity) { - throw Error("EntityDatabase::property", QString("There is no element %1 of type %2") - .arg(elementIndex) - .arg(Str_Text(P_NameForMapEntityDef(def.entity)))); + throw Error("EntityDatabase::property", + stringf("There is no element %i of type %s", + elementIndex, + Str_Text(P_NameForMapEntityDef(def.entity)))); } Entity::const_iterator found = entity->find(def.id); if (found == entity->end()) @@ -127,10 +128,10 @@ PropertyValue const &EntityDatabase::property(MapEntityPropertyDef const *def, return *propValue; } throw Error("EntityDatabase::property", - QString("Element %1 of type %2 has no value for property %3") - .arg(elementIndex) - .arg(Str_Text(P_NameForMapEntityDef(def->entity))) - .arg(def->id)); + stringf("Element %i of type %s has no value for property %i", + elementIndex, + Str_Text(P_NameForMapEntityDef(def->entity)), + def->id)); } bool EntityDatabase::hasPropertyValue(MapEntityPropertyDef const *def, int elementIndex) const diff --git a/doomsday/apps/libdoomsday/src/world/propertyvalue.cpp b/doomsday/apps/libdoomsday/src/world/propertyvalue.cpp index 422f13bef3..73161f7902 100644 --- a/doomsday/apps/libdoomsday/src/world/propertyvalue.cpp +++ b/doomsday/apps/libdoomsday/src/world/propertyvalue.cpp @@ -26,7 +26,7 @@ using namespace de; PropertyValue *BuildPropertyValue(valuetype_t type, void *valueAdr) { - DE_ASSERT(valueAdr != 0); + DE_ASSERT(valueAdr != nullptr); switch (type) { case DDVT_BYTE: return new PropertyByteValue (*( (byte *) valueAdr)); @@ -37,6 +37,6 @@ PropertyValue *BuildPropertyValue(valuetype_t type, void *valueAdr) case DDVT_FLOAT: return new PropertyFloatValue (*( (float *) valueAdr)); case DDVT_DOUBLE: return new PropertyDoubleValue(*( (double *) valueAdr)); default: - throw Error("BuildPropertyValue", QString("Unknown/not-supported value type %1").arg(type)); + throw Error("BuildPropertyValue", stringf("Unknown/not-supported value type %d", type)); } }