From 57051b7a4a75cbdf87c6c5e8fc41943b9f068a3e Mon Sep 17 00:00:00 2001 From: Marcus Huderle Date: Wed, 17 Feb 2021 18:20:14 -0600 Subject: [PATCH] [clang-format] Format source code --- include/config.h | 73 +- include/core/block.h | 17 +- include/core/blockdata.h | 3 +- include/core/editcommands.h | 222 +- include/core/event.h | 25 +- include/core/heallocation.h | 10 +- include/core/history.h | 6 +- include/core/map.h | 43 +- include/core/mapconnection.h | 4 +- include/core/maplayout.h | 7 +- include/core/metatile.h | 13 +- include/core/metatileparser.h | 5 +- include/core/paletteutil.h | 18 +- include/core/parseutil.h | 45 +- include/core/regionmap.h | 40 +- include/core/tile.h | 20 +- include/core/tileset.h | 9 +- include/core/wildmoninfo.h | 2 +- include/editor.h | 105 +- include/lib/orderedjson.h | 165 +- include/lib/orderedmap.h | 3767 ++++++++--------- include/lib/qstringhash.h | 6 +- include/mainwindow.h | 105 +- include/project.h | 32 +- include/scripting.h | 11 +- include/settings.h | 3 +- include/ui/aboutporymap.h | 8 +- include/ui/adjustingstackedwidget.h | 10 +- include/ui/bordermetatilespixmapitem.h | 7 +- include/ui/citymappixmapitem.h | 8 +- include/ui/collisionpixmapitem.h | 13 +- include/ui/connectionpixmapitem.h | 4 +- .../ui/currentselectedmetatilespixmapitem.h | 8 +- include/ui/cursortilerect.h | 31 +- include/ui/customattributestable.h | 9 +- include/ui/draggablepixmapitem.h | 29 +- include/ui/eventpropertiesframe.h | 9 +- include/ui/filterchildrenproxymodel.h | 9 +- include/ui/flowlayout.h | 18 +- include/ui/graphicsview.h | 26 +- include/ui/imageproviders.h | 19 +- include/ui/mapimageexporter.h | 19 +- include/ui/mappixmapitem.h | 49 +- include/ui/mapruler.h | 66 +- include/ui/mapsceneeventfilter.h | 8 +- include/ui/metatilelayersitem.h | 10 +- include/ui/metatileselector.h | 18 +- include/ui/montabwidget.h | 10 +- include/ui/movablerect.h | 19 +- include/ui/movementpermissionsselector.h | 4 +- include/ui/multikeyedit.h | 26 +- include/ui/neweventtoolbutton.h | 22 +- include/ui/newmappopup.h | 13 +- include/ui/newtilesetdialog.h | 9 +- include/ui/noscrollcombobox.h | 7 +- include/ui/noscrollspinbox.h | 9 +- include/ui/overlay.h | 32 +- include/ui/paletteeditor.h | 12 +- include/ui/preferenceeditor.h | 14 +- include/ui/regionmapeditor.h | 49 +- include/ui/regionmapentriespixmapitem.h | 12 +- include/ui/regionmaplayoutpixmapitem.h | 14 +- include/ui/regionmappixmapitem.h | 24 +- include/ui/selectablepixmapitem.h | 3 +- include/ui/shortcut.h | 39 +- include/ui/shortcutseditor.h | 42 +- include/ui/tilemaptileselector.h | 4 +- include/ui/tileseteditor.h | 47 +- include/ui/tileseteditormetatileselector.h | 10 +- include/ui/tileseteditortileselector.h | 9 +- src/config.cpp | 93 +- src/core/block.cpp | 37 +- src/core/blockdata.cpp | 2 +- src/core/editcommands.cpp | 124 +- src/core/event.cpp | 185 +- src/core/heallocation.cpp | 18 +- src/core/imageexport.cpp | 95 +- src/core/map.cpp | 95 +- src/core/metatile.cpp | 10 +- src/core/metatileparser.cpp | 51 +- src/core/paletteutil.cpp | 56 +- src/core/parseutil.cpp | 119 +- src/core/regionmap.cpp | 78 +- src/core/tileset.cpp | 22 +- src/core/wildmoninfo.cpp | 12 +- src/editor.cpp | 414 +- src/lib/orderedjson.cpp | 984 +++-- src/log.cpp | 22 +- src/main.cpp | 3 +- src/mainwindow.cpp | 1022 ++--- src/mainwindow_scriptapi.cpp | 38 +- src/project.cpp | 466 +- src/scripting.cpp | 62 +- src/settings.cpp | 3 +- src/ui/aboutporymap.cpp | 8 +- src/ui/bordermetatilespixmapitem.cpp | 12 +- src/ui/citymappixmapitem.cpp | 16 +- src/ui/collisionpixmapitem.cpp | 34 +- src/ui/connectionpixmapitem.cpp | 16 +- src/ui/currentselectedmetatilespixmapitem.cpp | 8 +- src/ui/cursortilerect.cpp | 48 +- src/ui/customattributestable.cpp | 33 +- src/ui/draggablepixmapitem.cpp | 35 +- src/ui/eventpropertiesframe.cpp | 12 +- src/ui/filterchildrenproxymodel.cpp | 22 +- src/ui/flowlayout.cpp | 41 +- src/ui/graphicsview.cpp | 12 +- src/ui/imageproviders.cpp | 112 +- src/ui/mapimageexporter.cpp | 322 +- src/ui/mappixmapitem.cpp | 286 +- src/ui/mapruler.cpp | 66 +- src/ui/mapsceneeventfilter.cpp | 15 +- src/ui/metatilelayersitem.cpp | 43 +- src/ui/metatileselector.cpp | 37 +- src/ui/montabwidget.cpp | 105 +- src/ui/movablerect.cpp | 6 +- src/ui/movementpermissionsselector.cpp | 4 +- src/ui/multikeyedit.cpp | 63 +- src/ui/neweventtoolbutton.cpp | 38 +- src/ui/newmappopup.cpp | 68 +- src/ui/newtilesetdialog.cpp | 16 +- src/ui/noscrollcombobox.cpp | 11 +- src/ui/noscrollspinbox.cpp | 9 +- src/ui/overlay.cpp | 6 +- src/ui/paletteeditor.cpp | 55 +- src/ui/preferenceeditor.cpp | 17 +- src/ui/regionmapeditor.cpp | 304 +- src/ui/regionmapentriespixmapitem.cpp | 21 +- src/ui/regionmaplayoutpixmapitem.cpp | 17 +- src/ui/regionmappixmapitem.cpp | 20 +- src/ui/selectablepixmapitem.cpp | 62 +- src/ui/shortcut.cpp | 66 +- src/ui/shortcutseditor.cpp | 75 +- src/ui/tilemaptileselector.cpp | 16 +- src/ui/tileseteditor.cpp | 326 +- src/ui/tileseteditormetatileselector.cpp | 42 +- src/ui/tileseteditortileselector.cpp | 13 +- 137 files changed, 5697 insertions(+), 6416 deletions(-) diff --git a/include/config.h b/include/config.h index ed5403a2..4f30ea14 100644 --- a/include/config.h +++ b/include/config.h @@ -10,18 +10,18 @@ #include enum MapSortOrder { - Group = 0, - Area = 1, - Layout = 2, + Group = 0, + Area = 1, + Layout = 2, }; -class KeyValueConfigBase : public QObject -{ +class KeyValueConfigBase : public QObject { public: void save(); void load(); virtual ~KeyValueConfigBase(); virtual void reset() = 0; + protected: virtual QString getConfigFilepath() = 0; virtual void parseConfigKeyValue(QString key, QString value) = 0; @@ -30,8 +30,7 @@ protected: virtual void setUnreadKeys() = 0; }; -class PorymapConfig: public KeyValueConfigBase -{ +class PorymapConfig : public KeyValueConfigBase { public: PorymapConfig() { reset(); @@ -64,8 +63,8 @@ public: void setMonitorFiles(bool monitor); void setRegionMapDimensions(int width, int height); void setTheme(QString theme); - void setTextEditorOpenFolder(const QString &command); - void setTextEditorGotoLine(const QString &command); + void setTextEditorOpenFolder(const QString& command); + void setTextEditorGotoLine(const QString& command); QString getRecentProject(); MapSortOrder getMapSortOrder(); bool getPrettyCursors(); @@ -82,12 +81,14 @@ public: QString getTheme(); QString getTextEditorOpenFolder(); QString getTextEditorGotoLine(); + protected: virtual QString getConfigFilepath() override; virtual void parseConfigKeyValue(QString key, QString value) override; virtual QMap getKeyValueMap() override; - virtual void onNewConfigFileCreated() override {}; - virtual void setUnreadKeys() override {}; + virtual void onNewConfigFileCreated() override{}; + virtual void setUnreadKeys() override{}; + private: QString recentProject; QString stringFromByteArray(QByteArray); @@ -124,8 +125,7 @@ enum BaseGameVersion { pokeemerald, }; -class ProjectConfig: public KeyValueConfigBase -{ +class ProjectConfig : public KeyValueConfigBase { public: ProjectConfig() { reset(); @@ -148,7 +148,7 @@ public: } void setBaseGameVersion(BaseGameVersion baseGameVersion); BaseGameVersion getBaseGameVersion(); - void setRecentMap(const QString &map); + void setRecentMap(const QString& map); QString getRecentMap(); void setEncounterJsonActive(bool active); bool getEncounterJsonActive(); @@ -176,12 +176,14 @@ public: bool getTripleLayerMetatilesEnabled(); void setCustomScripts(QList scripts); QList getCustomScripts(); + protected: virtual QString getConfigFilepath() override; virtual void parseConfigKeyValue(QString key, QString value) override; virtual QMap getKeyValueMap() override; virtual void onNewConfigFileCreated() override; virtual void setUnreadKeys() override; + private: BaseGameVersion baseGameVersion; QString projectDir; @@ -206,48 +208,41 @@ extern ProjectConfig projectConfig; class QAction; class Shortcut; -class ShortcutsConfig : public KeyValueConfigBase -{ +class ShortcutsConfig : public KeyValueConfigBase { public: - ShortcutsConfig() : - user_shortcuts({ }), - default_shortcuts({ }) - { } + ShortcutsConfig() : user_shortcuts({}), default_shortcuts({}) { + } - virtual void reset() override { user_shortcuts.clear(); } + virtual void reset() override { + user_shortcuts.clear(); + } // Call this before applying user shortcuts so that the user can restore defaults. - void setDefaultShortcuts(const QObjectList &objects); - QList defaultShortcuts(const QObject *object) const; + void setDefaultShortcuts(const QObjectList& objects); + QList defaultShortcuts(const QObject* object) const; - void setUserShortcuts(const QObjectList &objects); - void setUserShortcuts(const QMultiMap &objects_keySequences); - QList userShortcuts(const QObject *object) const; + void setUserShortcuts(const QObjectList& objects); + void setUserShortcuts(const QMultiMap& objects_keySequences); + QList userShortcuts(const QObject* object) const; protected: virtual QString getConfigFilepath() override; virtual void parseConfigKeyValue(QString key, QString value) override; virtual QMap getKeyValueMap() override; - virtual void onNewConfigFileCreated() override { }; - virtual void setUnreadKeys() override { }; + virtual void onNewConfigFileCreated() override{}; + virtual void setUnreadKeys() override{}; private: QMultiMap user_shortcuts; QMultiMap default_shortcuts; - enum StoreType { - User, - Default - }; + enum StoreType { User, Default }; - QString cfgKey(const QObject *object) const; - QList currentShortcuts(const QObject *object) const; + QString cfgKey(const QObject* object) const; + QList currentShortcuts(const QObject* object) const; - void storeShortcutsFromList(StoreType storeType, const QObjectList &objects); - void storeShortcuts( - StoreType storeType, - const QString &cfgKey, - const QList &keySequences); + void storeShortcutsFromList(StoreType storeType, const QObjectList& objects); + void storeShortcuts(StoreType storeType, const QString& cfgKey, const QList& keySequences); }; extern ShortcutsConfig shortcutsConfig; diff --git a/include/core/block.h b/include/core/block.h index 9bb1877f..e34f83bf 100644 --- a/include/core/block.h +++ b/include/core/block.h @@ -4,19 +4,18 @@ #include -class Block -{ +class Block { public: Block(); Block(uint16_t); Block(uint16_t tile, uint16_t collision, uint16_t elevation); - Block(const Block &); - Block &operator=(const Block &); - bool operator ==(Block) const; - bool operator !=(Block) const; - uint16_t tile:10; - uint16_t collision:2; - uint16_t elevation:4; + Block(const Block&); + Block& operator=(const Block&); + bool operator==(Block) const; + bool operator!=(Block) const; + uint16_t tile : 10; + uint16_t collision : 2; + uint16_t elevation : 4; uint16_t rawValue() const; }; diff --git a/include/core/blockdata.h b/include/core/blockdata.h index a1e45b63..5874fe49 100644 --- a/include/core/blockdata.h +++ b/include/core/blockdata.h @@ -7,8 +7,7 @@ #include #include -class Blockdata : public QVector -{ +class Blockdata : public QVector { public: QByteArray serialize() const; }; diff --git a/include/core/editcommands.h b/include/core/editcommands.h index 9b96ea3c..59074699 100644 --- a/include/core/editcommands.h +++ b/include/core/editcommands.h @@ -32,28 +32,28 @@ enum CommandId { ID_EventDuplicate, }; -#define IDMask_EventType_Object (1 << 8) -#define IDMask_EventType_Warp (1 << 9) -#define IDMask_EventType_BG (1 << 10) +#define IDMask_EventType_Object (1 << 8) +#define IDMask_EventType_Warp (1 << 9) +#define IDMask_EventType_BG (1 << 10) #define IDMask_EventType_Trigger (1 << 11) -#define IDMask_EventType_Heal (1 << 12) +#define IDMask_EventType_Heal (1 << 12) /// Implements a command to commit metatile paint actions /// onto the map using the pencil tool. class PaintMetatile : public QUndoCommand { public: - PaintMetatile(Map *map, - const Blockdata &oldMetatiles, const Blockdata &newMetatiles, - unsigned actionId, QUndoCommand *parent = nullptr); + PaintMetatile(Map* map, const Blockdata& oldMetatiles, const Blockdata& newMetatiles, unsigned actionId, QUndoCommand* parent = nullptr); void undo() override; void redo() override; - bool mergeWith(const QUndoCommand *command) override; - int id() const override { return CommandId::ID_PaintMetatile; } + bool mergeWith(const QUndoCommand* command) override; + int id() const override { + return CommandId::ID_PaintMetatile; + } private: - Map *map; + Map* map; Blockdata newMetatiles; Blockdata oldMetatiles; @@ -61,39 +61,37 @@ private: unsigned actionId; }; - - /// Implements a command to commit paint actions /// on the metatile collision and elevation. class PaintCollision : public PaintMetatile { public: - PaintCollision(Map *map, - const Blockdata &oldCollision, const Blockdata &newCollision, - unsigned actionId, QUndoCommand *parent = nullptr) - : PaintMetatile(map, oldCollision, newCollision, actionId, parent) { + PaintCollision(Map* map, const Blockdata& oldCollision, const Blockdata& newCollision, unsigned actionId, QUndoCommand* parent = nullptr) + : PaintMetatile(map, oldCollision, newCollision, actionId, parent) { setText("Paint Collision"); } - int id() const override { return CommandId::ID_PaintCollision; } + int id() const override { + return CommandId::ID_PaintCollision; + } }; - - /// Implements a command to commit paint actions on the map border. class PaintBorder : public QUndoCommand { public: - PaintBorder(Map *map, - const Blockdata &oldBorder, const Blockdata &newBorder, - unsigned actionId, QUndoCommand *parent = nullptr); + PaintBorder(Map* map, const Blockdata& oldBorder, const Blockdata& newBorder, unsigned actionId, QUndoCommand* parent = nullptr); void undo() override; void redo() override; - bool mergeWith(const QUndoCommand *) override { return false; }; - int id() const override { return CommandId::ID_PaintBorder; } + bool mergeWith(const QUndoCommand*) override { + return false; + }; + int id() const override { + return CommandId::ID_PaintBorder; + } private: - Map *map; + Map* map; Blockdata newBorder; Blockdata oldBorder; @@ -101,88 +99,82 @@ private: unsigned actionId; }; - - /// Implements a command to commit flood fill metatile actions /// with the bucket tool onto the map. class BucketFillMetatile : public PaintMetatile { public: - BucketFillMetatile(Map *map, - const Blockdata &oldMetatiles, const Blockdata &newMetatiles, - unsigned actionId, QUndoCommand *parent = nullptr) - : PaintMetatile(map, oldMetatiles, newMetatiles, actionId, parent) { + BucketFillMetatile(Map* map, const Blockdata& oldMetatiles, const Blockdata& newMetatiles, unsigned actionId, QUndoCommand* parent = nullptr) + : PaintMetatile(map, oldMetatiles, newMetatiles, actionId, parent) { setText("Bucket Fill Metatiles"); } - int id() const override { return CommandId::ID_BucketFillMetatile; } + int id() const override { + return CommandId::ID_BucketFillMetatile; + } }; - - /// Implements a command to commit flood fill actions /// on the metatile collision and elevation. class BucketFillCollision : public PaintCollision { public: - BucketFillCollision(Map *map, - const Blockdata &oldCollision, const Blockdata &newCollision, - QUndoCommand *parent = nullptr) - : PaintCollision(map, oldCollision, newCollision, -1, parent) { + BucketFillCollision(Map* map, const Blockdata& oldCollision, const Blockdata& newCollision, QUndoCommand* parent = nullptr) + : PaintCollision(map, oldCollision, newCollision, -1, parent) { setText("Flood Fill Collision"); } - bool mergeWith(const QUndoCommand *) override { return false; } - int id() const override { return CommandId::ID_BucketFillCollision; } + bool mergeWith(const QUndoCommand*) override { + return false; + } + int id() const override { + return CommandId::ID_BucketFillCollision; + } }; - - /// Implements a command to commit magic fill metatile actions /// with the bucket or paint tool onto the map. class MagicFillMetatile : public PaintMetatile { public: - MagicFillMetatile(Map *map, - const Blockdata &oldMetatiles, const Blockdata &newMetatiles, - unsigned actionId, QUndoCommand *parent = nullptr) - : PaintMetatile(map, oldMetatiles, newMetatiles, actionId, parent) { + MagicFillMetatile(Map* map, const Blockdata& oldMetatiles, const Blockdata& newMetatiles, unsigned actionId, QUndoCommand* parent = nullptr) + : PaintMetatile(map, oldMetatiles, newMetatiles, actionId, parent) { setText("Magic Fill Metatiles"); } - int id() const override { return CommandId::ID_MagicFillMetatile; } + int id() const override { + return CommandId::ID_MagicFillMetatile; + } }; - - /// Implements a command to commit magic fill collision actions. class MagicFillCollision : public PaintCollision { public: - MagicFillCollision(Map *map, - const Blockdata &oldCollision, const Blockdata &newCollision, - QUndoCommand *parent = nullptr) - : PaintCollision(map, oldCollision, newCollision, -1, parent) { + MagicFillCollision(Map* map, const Blockdata& oldCollision, const Blockdata& newCollision, QUndoCommand* parent = nullptr) + : PaintCollision(map, oldCollision, newCollision, -1, parent) { setText("Magic Fill Collision"); } - bool mergeWith(const QUndoCommand *) override { return false; } - int id() const override { return CommandId::ID_MagicFillCollision; } + bool mergeWith(const QUndoCommand*) override { + return false; + } + int id() const override { + return CommandId::ID_MagicFillCollision; + } }; - - /// Implements a command to commit metatile shift actions. class ShiftMetatiles : public QUndoCommand { public: - ShiftMetatiles(Map *map, - const Blockdata &oldMetatiles, const Blockdata &newMetatiles, - unsigned actionId, QUndoCommand *parent = nullptr); + ShiftMetatiles(Map* map, const Blockdata& oldMetatiles, const Blockdata& newMetatiles, unsigned actionId, QUndoCommand* parent = nullptr); void undo() override; void redo() override; - bool mergeWith(const QUndoCommand *command) override; - int id() const override { return CommandId::ID_ShiftMetatiles; } + bool mergeWith(const QUndoCommand* command) override; + int id() const override { + return CommandId::ID_ShiftMetatiles; + } private: - Map *map; + Map* map; Blockdata newMetatiles; Blockdata oldMetatiles; @@ -190,25 +182,24 @@ private: unsigned actionId; }; - - /// Implements a command to commit a map or border resize action. class ResizeMap : public QUndoCommand { public: - ResizeMap(Map *map, QSize oldMapDimensions, QSize newMapDimensions, - const Blockdata &oldMetatiles, const Blockdata &newMetatiles, - QSize oldBorderDimensions, QSize newBorderDimensions, - const Blockdata &oldBorder, const Blockdata &newBorder, - QUndoCommand *parent = nullptr); + ResizeMap(Map* map, QSize oldMapDimensions, QSize newMapDimensions, const Blockdata& oldMetatiles, const Blockdata& newMetatiles, QSize oldBorderDimensions, + QSize newBorderDimensions, const Blockdata& oldBorder, const Blockdata& newBorder, QUndoCommand* parent = nullptr); void undo() override; void redo() override; - bool mergeWith(const QUndoCommand *) override { return false; } - int id() const override { return CommandId::ID_ResizeMap; } + bool mergeWith(const QUndoCommand*) override { + return false; + } + int id() const override { + return CommandId::ID_ResizeMap; + } private: - Map *map; + Map* map; int oldMapWidth; int oldMapHeight; @@ -227,126 +218,115 @@ private: Blockdata oldBorder; }; - - /// Implements a command to commit a single- or multi-Event move action. /// Actions are merged into one until the mouse is released. class EventMove : public QUndoCommand { public: - EventMove(QList events, - int deltaX, int deltaY, unsigned actionId, - QUndoCommand *parent = nullptr); + EventMove(QList events, int deltaX, int deltaY, unsigned actionId, QUndoCommand* parent = nullptr); void undo() override; void redo() override; - bool mergeWith(const QUndoCommand *command) override; + bool mergeWith(const QUndoCommand* command) override; int id() const override; private: - QList events; + QList events; int deltaX; int deltaY; unsigned actionId; }; - - /// Implements a command to commit Event shift actions. class EventShift : public EventMove { public: - EventShift(QList events, - int deltaX, int deltaY, unsigned actionId, - QUndoCommand *parent = nullptr); + EventShift(QList events, int deltaX, int deltaY, unsigned actionId, QUndoCommand* parent = nullptr); int id() const override; + private: - QList events; + QList events; }; - - /// Implements a command to commit Event create actions. /// Works for a single Event only. class EventCreate : public QUndoCommand { public: - EventCreate(Editor *editor, Map *map, Event *event, - QUndoCommand *parent = nullptr); + EventCreate(Editor* editor, Map* map, Event* event, QUndoCommand* parent = nullptr); void undo() override; void redo() override; - bool mergeWith(const QUndoCommand *) override { return false; } + bool mergeWith(const QUndoCommand*) override { + return false; + } int id() const override; private: - Map *map; - Event *event; - Editor *editor; + Map* map; + Event* event; + Editor* editor; }; - - /// Implements a command to commit Event deletions. /// Applies to every currently selected Event. class EventDelete : public QUndoCommand { public: - EventDelete(Editor *editor, Map *map, - QList selectedEvents, Event *nextSelectedEvent, - QUndoCommand *parent = nullptr); + EventDelete(Editor* editor, Map* map, QList selectedEvents, Event* nextSelectedEvent, QUndoCommand* parent = nullptr); void undo() override; void redo() override; - bool mergeWith(const QUndoCommand *) override { return false; } + bool mergeWith(const QUndoCommand*) override { + return false; + } int id() const override; private: - Editor *editor; - Map *map; - QList selectedEvents; // allow multiple deletion of events - Event *nextSelectedEvent; + Editor* editor; + Map* map; + QList selectedEvents; // allow multiple deletion of events + Event* nextSelectedEvent; }; - - /// Implements a command to commit Event duplications. class EventDuplicate : public QUndoCommand { public: - EventDuplicate(Editor *editor, Map *map, QList selectedEvents, - QUndoCommand *parent = nullptr); + EventDuplicate(Editor* editor, Map* map, QList selectedEvents, QUndoCommand* parent = nullptr); void undo() override; void redo() override; - bool mergeWith(const QUndoCommand *) override { return false; } + bool mergeWith(const QUndoCommand*) override { + return false; + } int id() const override; private: - Map *map; - QList selectedEvents; // allow multiple deletion of events - Editor *editor; + Map* map; + QList selectedEvents; // allow multiple deletion of events + Editor* editor; }; - - /// Implements a command to commit map edits from the scripting API. /// The scripting api can edit metatiles and map dimensions. class ScriptEditMap : public QUndoCommand { public: - ScriptEditMap(Map *map, - QSize oldMapDimensions, QSize newMapDimensions, - const Blockdata &oldMetatiles, const Blockdata &newMetatiles, - QUndoCommand *parent = nullptr); + ScriptEditMap( + Map* map, QSize oldMapDimensions, QSize newMapDimensions, const Blockdata& oldMetatiles, const Blockdata& newMetatiles, QUndoCommand* parent = nullptr); void undo() override; void redo() override; - bool mergeWith(const QUndoCommand *) override { return false; } - int id() const override { return CommandId::ID_ScriptEditMap; } + bool mergeWith(const QUndoCommand*) override { + return false; + } + int id() const override { + return CommandId::ID_ScriptEditMap; + } private: - Map *map; + Map* map; Blockdata newMetatiles; Blockdata oldMetatiles; diff --git a/include/core/event.h b/include/core/event.h index 6ee59ac5..d89010af 100644 --- a/include/core/event.h +++ b/include/core/event.h @@ -10,8 +10,7 @@ using OrderedJson = poryjson::Json; -class EventType -{ +class EventType { public: static QString Object; static QString Warp; @@ -25,12 +24,12 @@ public: class DraggablePixmapItem; class Project; -class Event -{ +class Event { public: Event(); Event(const Event&); Event(QJsonObject, QString); + public: int x() const { return getInt("x"); @@ -47,16 +46,16 @@ public: void setY(int y) { put("y", y); } - QString get(const QString &key) const { + QString get(const QString& key) const { return values.value(key); } - int getInt(const QString &key) const { + int getInt(const QString& key) const { return values.value(key).toInt(nullptr, 0); } - uint16_t getU16(const QString &key) const { + uint16_t getU16(const QString& key) const { return values.value(key).toUShort(nullptr, 0); } - int16_t getS16(const QString &key) const { + int16_t getS16(const QString& key) const { return values.value(key).toShort(nullptr, 0); } void put(QString key, int value) { @@ -77,7 +76,7 @@ public: static Event* createNewSecretBaseEvent(Project*); OrderedJson::object buildObjectEventJSON(); - OrderedJson::object buildWarpEventJSON(const QMap &); + OrderedJson::object buildWarpEventJSON(const QMap&); OrderedJson::object buildTriggerEventJSON(); OrderedJson::object buildWeatherTriggerEventJSON(); OrderedJson::object buildSignEventJSON(); @@ -88,7 +87,7 @@ public: int getPixelY(); QMap getExpectedFields(); void readCustomValues(QJsonObject values); - void addCustomValuesTo(OrderedJson::object *obj); + void addCustomValuesTo(OrderedJson::object* obj); void setFrameFromMovement(QString); QMap values; @@ -100,8 +99,10 @@ public: bool hFlip = false; bool usingSprite; - DraggablePixmapItem *pixmapItem = nullptr; - void setPixmapItem(DraggablePixmapItem *item) { pixmapItem = item; } + DraggablePixmapItem* pixmapItem = nullptr; + void setPixmapItem(DraggablePixmapItem* item) { + pixmapItem = item; + } }; #endif // EVENT_H diff --git a/include/core/heallocation.h b/include/core/heallocation.h index a39386c1..f62def83 100644 --- a/include/core/heallocation.h +++ b/include/core/heallocation.h @@ -9,16 +9,16 @@ class HealLocation { public: - HealLocation()=default; + HealLocation() = default; HealLocation(QString, QString, int, uint16_t, uint16_t, QString = "", uint16_t = 0); - friend QDebug operator<<(QDebug debug, const HealLocation &hl); + friend QDebug operator<<(QDebug debug, const HealLocation& hl); public: QString idName; QString mapName; - int index; - uint16_t x; - uint16_t y; + int index; + uint16_t x; + uint16_t y; QString respawnMap; uint16_t respawnNPC; static HealLocation fromEvent(Event*); diff --git a/include/core/history.h b/include/core/history.h index 75883d2d..7d1e1e05 100644 --- a/include/core/history.h +++ b/include/core/history.h @@ -4,10 +4,10 @@ #include -template -class History { +template class History { public: - History() { } + History() { + } T back() { if (head > 0) { return history.at(--head); diff --git a/include/core/map.h b/include/core/map.h index dd6256cd..2515a32f 100644 --- a/include/core/map.h +++ b/include/core/map.h @@ -25,11 +25,10 @@ class MapPixmapItem; class CollisionPixmapItem; class BorderMetatilesPixmapItem; -class Map : public QObject -{ +class Map : public QObject { Q_OBJECT public: - explicit Map(QObject *parent = nullptr); + explicit Map(QObject* parent = nullptr); ~Map(); public: @@ -52,7 +51,7 @@ public: QString sharedEventsMap = ""; QString sharedScriptsMap = ""; QMap customHeaders; - MapLayout *layout; + MapLayout* layout; bool isPersistedToFile = true; bool needsLayoutDir = true; QImage collision_image; @@ -73,22 +72,22 @@ public: int getHeight(); int getBorderWidth(); int getBorderHeight(); - QPixmap render(bool ignoreCache, MapLayout * fromLayout = nullptr); + QPixmap render(bool ignoreCache, MapLayout* fromLayout = nullptr); QPixmap renderCollision(qreal opacity, bool ignoreCache); - bool mapBlockChanged(int i, const Blockdata &cache); - bool borderBlockChanged(int i, const Blockdata &cache); + bool mapBlockChanged(int i, const Blockdata& cache); + bool borderBlockChanged(int i, const Blockdata& cache); void cacheBlockdata(); void cacheCollision(); - bool getBlock(int x, int y, Block *out); + bool getBlock(int x, int y, Block* out); void setBlock(int x, int y, Block block, bool enableScriptCallback = false); void floodFillCollisionElevation(int x, int y, uint16_t collision, uint16_t elevation); void _floodFillCollisionElevation(int x, int y, uint16_t collision, uint16_t elevation); void magicFillCollisionElevation(int x, int y, uint16_t collision, uint16_t elevation); QList getAllEvents() const; - QStringList eventScriptLabels(const QString &event_group_type = QString()) const; + QStringList eventScriptLabels(const QString& event_group_type = QString()) const; void removeEvent(Event*); void addEvent(Event*); - QPixmap renderConnection(MapConnection, MapLayout *); + QPixmap renderConnection(MapConnection, MapLayout*); QPixmap renderBorder(bool ignoreCache = false); void setDimensions(int newWidth, int newHeight, bool setNewBlockdata = true); void setBorderDimensions(int newWidth, int newHeight, bool setNewBlockdata = true); @@ -96,16 +95,22 @@ public: bool hasUnsavedChanges(); // for memory management - QVector ownedEvents; + QVector ownedEvents; - MapPixmapItem *mapItem = nullptr; - void setMapItem(MapPixmapItem *item) { mapItem = item; } + MapPixmapItem* mapItem = nullptr; + void setMapItem(MapPixmapItem* item) { + mapItem = item; + } - CollisionPixmapItem *collisionItem = nullptr; - void setCollisionItem(CollisionPixmapItem *item) { collisionItem = item; } + CollisionPixmapItem* collisionItem = nullptr; + void setCollisionItem(CollisionPixmapItem* item) { + collisionItem = item; + } - BorderMetatilesPixmapItem *borderItem = nullptr; - void setBorderItem(BorderMetatilesPixmapItem *item) { borderItem = item; } + BorderMetatilesPixmapItem* borderItem = nullptr; + void setBorderItem(BorderMetatilesPixmapItem* item) { + borderItem = item; + } QUndoStack editHistory; @@ -114,8 +119,8 @@ private: void setNewBorderDimensionsBlockdata(int newWidth, int newHeight); signals: - void mapChanged(Map *map); - void mapDimensionsChanged(const QSize &size); + void mapChanged(Map* map); + void mapDimensionsChanged(const QSize& size); void mapNeedsRedrawing(); }; diff --git a/include/core/mapconnection.h b/include/core/mapconnection.h index b6be238e..23488098 100644 --- a/include/core/mapconnection.h +++ b/include/core/mapconnection.h @@ -12,11 +12,11 @@ public: QString map_name; }; -inline bool operator==(const MapConnection &c1, const MapConnection &c2) { +inline bool operator==(const MapConnection& c1, const MapConnection& c2) { return c1.map_name == c2.map_name; } -inline uint qHash(const MapConnection &key) { +inline uint qHash(const MapConnection& key) { return qHash(key.map_name); } diff --git a/include/core/maplayout.h b/include/core/maplayout.h index 38bb3f23..842ee57f 100644 --- a/include/core/maplayout.h +++ b/include/core/maplayout.h @@ -10,7 +10,8 @@ class MapLayout { public: - MapLayout() {} + MapLayout() { + } static QString layoutConstantFromName(QString mapName); QString id; QString name; @@ -22,8 +23,8 @@ public: QString blockdata_path; QString tileset_primary_label; QString tileset_secondary_label; - Tileset *tileset_primary = nullptr; - Tileset *tileset_secondary = nullptr; + Tileset* tileset_primary = nullptr; + Tileset* tileset_secondary = nullptr; Blockdata blockdata; QImage border_image; QPixmap border_pixmap; diff --git a/include/core/metatile.h b/include/core/metatile.h index 5b9bb813..e8fb9fa2 100644 --- a/include/core/metatile.h +++ b/include/core/metatile.h @@ -7,23 +7,22 @@ #include #include -class Metatile -{ +class Metatile { public: Metatile(); - Metatile(const Metatile &other) = default; - Metatile &operator=(const Metatile &other) = default; + Metatile(const Metatile& other) = default; + Metatile& operator=(const Metatile& other) = default; public: QList tiles; - uint16_t behavior; // 8 bits RSE, 9 bits FRLG + uint16_t behavior; // 8 bits RSE, 9 bits FRLG uint8_t layerType; uint8_t encounterType; // FRLG only - uint8_t terrainType; // FRLG only + uint8_t terrainType; // FRLG only QString label; static int getBlockIndex(int); - static QPoint coordFromPixmapCoord(const QPointF &pixelCoord); + static QPoint coordFromPixmapCoord(const QPointF& pixelCoord); }; #endif // METATILE_H diff --git a/include/core/metatileparser.h b/include/core/metatileparser.h index 2008d60f..84761822 100644 --- a/include/core/metatileparser.h +++ b/include/core/metatileparser.h @@ -6,11 +6,10 @@ #include #include -class MetatileParser -{ +class MetatileParser { public: MetatileParser(); - QList parse(QString filepath, bool *error, bool primaryTileset); + QList parse(QString filepath, bool* error, bool primaryTileset); }; #endif // METATILEPARSER_H diff --git a/include/core/paletteutil.h b/include/core/paletteutil.h index abc1700a..e6d8e73c 100644 --- a/include/core/paletteutil.h +++ b/include/core/paletteutil.h @@ -6,19 +6,19 @@ #include #include -class PaletteUtil -{ +class PaletteUtil { public: PaletteUtil(); - QList parse(QString filepath, bool *error); + QList parse(QString filepath, bool* error); void writeJASC(QString filepath, QVector colors, int offset, int nColors); + private: - QList parsePal(QString filepath, bool *error); - QList parseJASC(QString filepath, bool *error); - QList parseAdvanceMapPal(QString filepath, bool *error); - QList parseAdobeColorTable(QString filepath, bool *error); - QList parseTileLayerPro(QString filepath, bool *error); - QList parseAdvancePaletteEditor(QString filepath, bool *error); + QList parsePal(QString filepath, bool* error); + QList parseJASC(QString filepath, bool* error); + QList parseAdvanceMapPal(QString filepath, bool* error); + QList parseAdobeColorTable(QString filepath, bool* error); + QList parseTileLayerPro(QString filepath, bool* error); + QList parseAdvancePaletteEditor(QString filepath, bool* error); int clampColorValue(int value); }; diff --git a/include/core/parseutil.h b/include/core/parseutil.h index 7c9b225e..2f4419d2 100644 --- a/include/core/parseutil.h +++ b/include/core/parseutil.h @@ -36,33 +36,32 @@ public: int operatorPrecedence; // only relevant for operator tokens }; -class ParseUtil -{ +class ParseUtil { public: - ParseUtil() { }; - void set_root(const QString &dir); - static QString readTextFile(const QString &path); - static int textFileLineCount(const QString &path); - QList parseAsm(const QString &filename); + ParseUtil(){}; + void set_root(const QString& dir); + static QString readTextFile(const QString& path); + static int textFileLineCount(const QString& path); + QList parseAsm(const QString& filename); int evaluateDefine(const QString&, const QMap&); - QStringList readCArray(const QString &text, const QString &label); - QMap readNamedIndexCArray(const QString &text, const QString &label); - QString readCIncbin(const QString &text, const QString &label); - QMap readCDefines(const QString &filename, const QStringList &prefixes, QMap = { }); - QStringList readCDefinesSorted(const QString&, const QStringList&, const QMap& = { }); + QStringList readCArray(const QString& text, const QString& label); + QMap readNamedIndexCArray(const QString& text, const QString& label); + QString readCIncbin(const QString& text, const QString& label); + QMap readCDefines(const QString& filename, const QStringList& prefixes, QMap = {}); + QStringList readCDefinesSorted(const QString&, const QStringList&, const QMap& = {}); QList getLabelMacros(const QList&, const QString&); QStringList getLabelValues(const QList&, const QString&); - bool tryParseJsonFile(QJsonDocument *out, const QString &filepath); - bool ensureFieldsExist(const QJsonObject &obj, const QList &fields); + bool tryParseJsonFile(QJsonDocument* out, const QString& filepath); + bool ensureFieldsExist(const QJsonObject& obj, const QList& fields); // Returns the 1-indexed line number for the definition of scriptLabel in the scripts file at filePath. // Returns 0 if a definition for scriptLabel cannot be found. - static int getScriptLineNumber(const QString &filePath, const QString &scriptLabel); - static int getRawScriptLineNumber(QString text, const QString &scriptLabel); - static int getPoryScriptLineNumber(QString text, const QString &scriptLabel); + static int getScriptLineNumber(const QString& filePath, const QString& scriptLabel); + static int getRawScriptLineNumber(QString text, const QString& scriptLabel); + static int getPoryScriptLineNumber(QString text, const QString& scriptLabel); static QString removeStringLiterals(QString text); - static QString removeLineComments(QString text, const QString &commentSymbol); - static QString removeLineComments(QString text, const QStringList &commentSymbols); + static QString removeLineComments(QString text, const QString& commentSymbol); + static QString removeLineComments(QString text, const QStringList& commentSymbols); static QStringList splitShellCommand(QStringView command); @@ -70,10 +69,10 @@ private: QString root; QString text; QString file; - QList tokenizeExpression(QString expression, const QMap &knownIdentifiers); - QList generatePostfix(const QList &tokens); - int evaluatePostfix(const QList &postfix); - void error(const QString &message, const QString &expression); + QList tokenizeExpression(QString expression, const QMap& knownIdentifiers); + QList generatePostfix(const QList& tokens); + int evaluatePostfix(const QList& postfix); + void error(const QString& message, const QString& expression); }; #endif // PARSEUTIL_H diff --git a/include/core/regionmap.h b/include/core/regionmap.h index a24ae1ea..9b20e968 100644 --- a/include/core/regionmap.h +++ b/include/core/regionmap.h @@ -17,7 +17,7 @@ enum RegionMapEditorBox { BackgroundImage = 1, - CityMapImage = 2, + CityMapImage = 2, }; class RegionMapHistoryItem { @@ -38,19 +38,19 @@ public: this->mapWidth = width; this->mapHeight = height; } - ~RegionMapHistoryItem() {} + ~RegionMapHistoryItem() { + } }; -class RegionMapEntry -{ +class RegionMapEntry { public: - RegionMapEntry()=default; + RegionMapEntry() = default; RegionMapEntry(int x_, int y_, int width_, int height_, QString name_) { - this-> x = x_; - this-> y = y_; - this-> width = width_; - this-> height = height_; - this-> name = name_; + this->x = x_; + this->y = y_; + this->width = width_; + this->height = height_; + this->name = name_; } int x; int y; @@ -64,8 +64,7 @@ public: void setHeight(int); }; -class RegionMapSquare -{ +class RegionMapSquare { public: int x = -1; int y = -1; @@ -79,16 +78,15 @@ public: QString city_map_name; }; -class RegionMap : public QObject -{ +class RegionMap : public QObject { Q_OBJECT public: RegionMap() = default; - ~RegionMap() {}; + ~RegionMap(){}; - Project *project = nullptr; + Project* project = nullptr; QVector map_squares; History history; @@ -97,9 +95,9 @@ public: QMap mapSecToMapEntry; QVector sMapNames; - const int padLeft = 1; - const int padRight = 3; - const int padTop = 2; + const int padLeft = 1; + const int padRight = 3; + const int padTop = 2; const int padBottom = 3; bool init(Project*); @@ -119,8 +117,8 @@ public: void clearImage(); void replaceSectionId(unsigned oldId, unsigned newId); - int width(); - int height(); + int width(); + int height(); QSize imgSize(); unsigned getTileId(int x, int y); int getMapSquareIndex(int x, int y); diff --git a/include/core/tile.h b/include/core/tile.h index dfcb7117..98d4d2df 100644 --- a/include/core/tile.h +++ b/include/core/tile.h @@ -2,23 +2,13 @@ #ifndef TILE_H #define TILE_H - -class Tile -{ +class Tile { public: - Tile() : - tile(0), - xflip(false), - yflip(false), - palette(0) - { } + Tile() : tile(0), xflip(false), yflip(false), palette(0) { + } - Tile(int tile, bool xflip, bool yflip, int palette) : - tile(tile), - xflip(xflip), - yflip(yflip), - palette(palette) - { } + Tile(int tile, bool xflip, bool yflip, int palette) : tile(tile), xflip(xflip), yflip(yflip), palette(palette) { + } public: int tile; diff --git a/include/core/tileset.h b/include/core/tileset.h index 2ffeea85..ee074ed2 100644 --- a/include/core/tileset.h +++ b/include/core/tileset.h @@ -6,12 +6,11 @@ #include "tile.h" #include -class Tileset -{ +class Tileset { public: Tileset() = default; - Tileset(const Tileset &other) = default; - Tileset &operator=(const Tileset &other) = default; + Tileset(const Tileset& other) = default; + Tileset& operator=(const Tileset& other) = default; public: QString name; @@ -38,7 +37,7 @@ public: static Metatile* getMetatile(int, Tileset*, Tileset*); static QList> getBlockPalettes(Tileset*, Tileset*, bool useTruePalettes = false); static QList getPalette(int, Tileset*, Tileset*, bool useTruePalettes = false); - static bool metatileIsValid(uint16_t metatileId, Tileset *, Tileset *); + static bool metatileIsValid(uint16_t metatileId, Tileset*, Tileset*); bool appendToHeaders(QString headerFile, QString friendlyName); bool appendToGraphics(QString graphicsFile, QString friendlyName, bool primary); diff --git a/include/core/wildmoninfo.h b/include/core/wildmoninfo.h index 06877622..cf57ca96 100644 --- a/include/core/wildmoninfo.h +++ b/include/core/wildmoninfo.h @@ -29,6 +29,6 @@ struct EncounterField { typedef QVector EncounterFields; WildMonInfo getDefaultMonInfo(EncounterField field); -WildMonInfo copyMonInfoFromTab(QTableWidget *table, EncounterField monField); +WildMonInfo copyMonInfoFromTab(QTableWidget* table, EncounterField monField); #endif // GUARD_WILDMONINFO_H diff --git a/include/editor.h b/include/editor.h index 2b70a6f6..01c32c84 100644 --- a/include/editor.h +++ b/include/editor.h @@ -29,23 +29,22 @@ class DraggablePixmapItem; class MetatilesPixmapItem; -class Editor : public QObject -{ +class Editor : public QObject { Q_OBJECT public: Editor(Ui::MainWindow* ui); ~Editor(); Editor() = delete; - Editor(const Editor &) = delete; - Editor & operator = (const Editor &) = delete; + Editor(const Editor&) = delete; + Editor& operator=(const Editor&) = delete; public: Ui::MainWindow* ui; - QObject *parent = nullptr; - Project *project = nullptr; - Map *map = nullptr; - Settings *settings; + QObject* parent = nullptr; + Project* project = nullptr; + Map* map = nullptr; + Settings* settings; void saveProject(); void save(); void closeProject(); @@ -81,7 +80,7 @@ public: void setConnectionMap(QString mapName); void addNewConnection(); void removeCurrentConnection(); - void addNewWildMonGroup(QWidget *window); + void addNewWildMonGroup(QWidget* window); void deleteWildMonGroup(); void updateDiveMap(QString mapName); void updateEmergeMap(QString mapName); @@ -89,48 +88,48 @@ public: void updatePrimaryTileset(QString tilesetLabel, bool forceLoad = false); void updateSecondaryTileset(QString tilesetLabel, bool forceLoad = false); void toggleBorderVisibility(bool visible); - void updateCustomMapHeaderValues(QTableWidget *); - void configureEncounterJSON(QWidget *); - Tileset *getCurrentMapPrimaryTileset(); + void updateCustomMapHeaderValues(QTableWidget*); + void configureEncounterJSON(QWidget*); + Tileset* getCurrentMapPrimaryTileset(); - DraggablePixmapItem *addMapEvent(Event *event); - void selectMapEvent(DraggablePixmapItem *object); - void selectMapEvent(DraggablePixmapItem *object, bool toggle); - DraggablePixmapItem *addNewEvent(QString event_type); - void deleteEvent(Event *); + DraggablePixmapItem* addMapEvent(Event* event); + void selectMapEvent(DraggablePixmapItem* object); + void selectMapEvent(DraggablePixmapItem* object, bool toggle); + DraggablePixmapItem* addNewEvent(QString event_type); + void deleteEvent(Event*); void updateSelectedEvents(); void duplicateSelectedEvents(); - void redrawObject(DraggablePixmapItem *item); - QList getObjects(); + void redrawObject(DraggablePixmapItem* item); + QList getObjects(); - QGraphicsScene *scene = nullptr; - QGraphicsPixmapItem *current_view = nullptr; - MapPixmapItem *map_item = nullptr; + QGraphicsScene* scene = nullptr; + QGraphicsPixmapItem* current_view = nullptr; + MapPixmapItem* map_item = nullptr; ConnectionPixmapItem* selected_connection_item = nullptr; QList connection_items; QList connection_edit_items; - QGraphicsPathItem *connection_mask = nullptr; - CollisionPixmapItem *collision_item = nullptr; - QGraphicsItemGroup *events_group = nullptr; + QGraphicsPathItem* connection_mask = nullptr; + CollisionPixmapItem* collision_item = nullptr; + QGraphicsItemGroup* events_group = nullptr; QList borderItems; QList gridLines; - MovableRect *playerViewRect = nullptr; - CursorTileRect *cursorMapTileRect = nullptr; - MapRuler *map_ruler = nullptr; + MovableRect* playerViewRect = nullptr; + CursorTileRect* cursorMapTileRect = nullptr; + MapRuler* map_ruler = nullptr; - QGraphicsScene *scene_metatiles = nullptr; - QGraphicsScene *scene_current_metatile_selection = nullptr; - QGraphicsScene *scene_selected_border_metatiles = nullptr; - QGraphicsScene *scene_collision_metatiles = nullptr; - QGraphicsScene *scene_elevation_metatiles = nullptr; - MetatileSelector *metatile_selector_item = nullptr; + QGraphicsScene* scene_metatiles = nullptr; + QGraphicsScene* scene_current_metatile_selection = nullptr; + QGraphicsScene* scene_selected_border_metatiles = nullptr; + QGraphicsScene* scene_collision_metatiles = nullptr; + QGraphicsScene* scene_elevation_metatiles = nullptr; + MetatileSelector* metatile_selector_item = nullptr; - BorderMetatilesPixmapItem *selected_border_metatiles_item = nullptr; - CurrentSelectedMetatilesPixmapItem *current_metatile_selection_item = nullptr; - MovementPermissionsSelector *movement_permissions_selector_item = nullptr; + BorderMetatilesPixmapItem* selected_border_metatiles_item = nullptr; + CurrentSelectedMetatilesPixmapItem* current_metatile_selection_item = nullptr; + MovementPermissionsSelector* movement_permissions_selector_item = nullptr; - QList *events = nullptr; - QList *selected_events = nullptr; + QList* events = nullptr; + QList* selected_events = nullptr; QString map_edit_mode = "paint"; QString obj_edit_mode = "select"; @@ -139,7 +138,7 @@ public: double scale_base = sqrt(2); // adjust scale factor with this qreal collisionOpacity = 0.5; - void objectsView_onMousePress(QMouseEvent *event); + void objectsView_onMousePress(QMouseEvent* event); int getBorderDrawDistance(int dimension); @@ -149,11 +148,11 @@ public: void shouldReselectEvents(); void scaleMapView(int); - void openInTextEditor(const QString &path, int lineNum = 0) const; + void openInTextEditor(const QString& path, int lineNum = 0) const; public slots: void openMapScripts() const; - void openScript(const QString &scriptLabel) const; + void openScript(const QString& scriptLabel) const; void openProjectInTextEditor() const; void maskNonVisibleConnectionTiles(); @@ -175,18 +174,16 @@ private: void updateEncounterFields(EncounterFields newFields); QString getMovementPermissionText(uint16_t collision, uint16_t elevation); QString getMetatileDisplayMessage(uint16_t metatileId); - bool eventLimitReached(Map *, QString); - bool startDetachedProcess(const QString &command, - const QString &workingDirectory = QString(), - qint64 *pid = nullptr) const; + bool eventLimitReached(Map*, QString); + bool startDetachedProcess(const QString& command, const QString& workingDirectory = QString(), qint64* pid = nullptr) const; private slots: - void onMapStartPaint(QGraphicsSceneMouseEvent *event, MapPixmapItem *item); - void onMapEndPaint(QGraphicsSceneMouseEvent *event, MapPixmapItem *item); - void setSmartPathCursorMode(QGraphicsSceneMouseEvent *event); - void setStraightPathCursorMode(QGraphicsSceneMouseEvent *event); - void mouseEvent_map(QGraphicsSceneMouseEvent *event, MapPixmapItem *item); - void mouseEvent_collision(QGraphicsSceneMouseEvent *event, CollisionPixmapItem *item); + void onMapStartPaint(QGraphicsSceneMouseEvent* event, MapPixmapItem* item); + void onMapEndPaint(QGraphicsSceneMouseEvent* event, MapPixmapItem* item); + void setSmartPathCursorMode(QGraphicsSceneMouseEvent* event); + void setStraightPathCursorMode(QGraphicsSceneMouseEvent* event); + void mouseEvent_map(QGraphicsSceneMouseEvent* event, MapPixmapItem* item); + void mouseEvent_collision(QGraphicsSceneMouseEvent* event, CollisionPixmapItem* item); void onConnectionMoved(MapConnection*); void onConnectionItemSelected(ConnectionPixmapItem* connectionItem); void onConnectionItemDoubleClicked(ConnectionPixmapItem* connectionItem); @@ -196,7 +193,7 @@ private slots: void onHoveredMovementPermissionCleared(); void onHoveredMetatileSelectionChanged(uint16_t); void onHoveredMetatileSelectionCleared(); - void onHoveredMapMetatileChanged(const QPoint &pos); + void onHoveredMapMetatileChanged(const QPoint& pos); void onHoveredMapMetatileCleared(); void onHoveredMapMovementPermissionChanged(int, int); void onHoveredMapMovementPermissionCleared(); @@ -210,7 +207,7 @@ signals: void wildMonDataChanged(); void warpEventDoubleClicked(QString mapName, QString warpNum); void currentMetatilesSelectionChanged(); - void mapRulerStatusChanged(const QString &); + void mapRulerStatusChanged(const QString&); }; #endif // EDITOR_H diff --git a/include/lib/orderedjson.h b/include/lib/orderedjson.h index 20463cee..c18f633e 100644 --- a/include/lib/orderedjson.h +++ b/include/lib/orderedjson.h @@ -68,80 +68,90 @@ #include "orderedmap.h" #ifdef _MSC_VER - #if _MSC_VER <= 1800 // VS 2013 - #ifndef noexcept - #define noexcept throw() - #endif +#if _MSC_VER <= 1800 // VS 2013 +#ifndef noexcept +#define noexcept throw() +#endif - #ifndef snprintf - #define snprintf _snprintf_s - #endif - #endif +#ifndef snprintf +#define snprintf _snprintf_s +#endif +#endif #endif namespace poryjson { -enum JsonParse { - STANDARD, COMMENTS -}; +enum JsonParse { STANDARD, COMMENTS }; class JsonValue; class Json final { public: // Types - enum Type { - NUL, NUMBER, BOOL, STRING, ARRAY, OBJECT - }; + enum Type { NUL, NUMBER, BOOL, STRING, ARRAY, OBJECT }; // Array and object typedefs typedef QVector array; typedef tsl::ordered_map object; // Constructors for the various types of JSON value. - Json() noexcept; // NUL - Json(std::nullptr_t) noexcept; // NUL - Json(double value); // NUMBER - Json(int value); // NUMBER - Json(bool value); // BOOL - Json(const QString &value); // STRING - Json(QString &&value); // STRING - Json(const char * value); // STRING - Json(const array &values); // ARRAY - Json(array &&values); // ARRAY - Json(const object &values); // OBJECT - Json(object &&values); // OBJECT + Json() noexcept; // NUL + Json(std::nullptr_t) noexcept; // NUL + Json(double value); // NUMBER + Json(int value); // NUMBER + Json(bool value); // BOOL + Json(const QString& value); // STRING + Json(QString&& value); // STRING + Json(const char* value); // STRING + Json(const array& values); // ARRAY + Json(array&& values); // ARRAY + Json(const object& values); // OBJECT + Json(object&& values); // OBJECT // Implicit constructor: anything with a to_json() function. - template - Json(const T & t) : Json(t.to_json()) {} + template Json(const T& t) : Json(t.to_json()) { + } // Implicit constructor: map-like objects (std::map, std::unordered_map, etc) - template ().begin()->first)>::value - && std::is_constructible().begin()->second)>::value, - int>::type = 0> - Json(const M & m) : Json(object(m.begin(), m.end())) {} + template ().begin()->first)>::value + && std::is_constructible().begin()->second)>::value, + int>::type + = 0> + Json(const M& m) + : Json(object(m.begin(), m.end())) { + } // Implicit constructor: vector-like objects (std::list, std::vector, std::set, etc) - template ().begin())>::value, - int>::type = 0> - Json(const V & v) : Json(array(v.begin(), v.end())) {} + template ().begin())>::value, int>::type = 0> + Json(const V& v) + : Json(array(v.begin(), v.end())) { + } // This prevents Json(some_pointer) from accidentally producing a bool. Use // Json(bool(some_pointer)) if that behavior is desired. - Json(void *) = delete; + Json(void*) = delete; // Accessors Type type() const; - bool is_null() const { return type() == NUL; } - bool is_number() const { return type() == NUMBER; } - bool is_bool() const { return type() == BOOL; } - bool is_string() const { return type() == STRING; } - bool is_array() const { return type() == ARRAY; } - bool is_object() const { return type() == OBJECT; } + bool is_null() const { + return type() == NUL; + } + bool is_number() const { + return type() == NUMBER; + } + bool is_bool() const { + return type() == BOOL; + } + bool is_string() const { + return type() == STRING; + } + bool is_array() const { + return type() == ARRAY; + } + bool is_object() const { + return type() == OBJECT; + } // Return the enclosed value if this is a number, 0 otherwise. Note that poryjson does not // distinguish between integer and non-integer numbers - number_value() and int_value() @@ -152,20 +162,20 @@ public: // Return the enclosed value if this is a boolean, false otherwise. bool bool_value() const; // Return the enclosed string if this is a string, "" otherwise. - const QString &string_value() const; + const QString& string_value() const; // Return the enclosed std::vector if this is an array, or an empty vector otherwise. - const array &array_items() const; + const array& array_items() const; // Return the enclosed std::map if this is an object, or an empty map otherwise. - const object &object_items() const; + const object& object_items() const; // Return a reference to arr[i] if this is an array, Json() otherwise. - const Json & operator[](int i) const; + const Json& operator[](int i) const; // Return a reference to obj[key] if this is an object, Json() otherwise. - const Json & operator[](const QString &key) const; + const Json& operator[](const QString& key) const; // Serialize. - void dump(QString &out, int *) const; - QString dump(int *indent = nullptr) const { + void dump(QString& out, int*) const; + QString dump(int* indent = nullptr) const { QString out; if (!indent) { int temp = 0; @@ -176,12 +186,8 @@ public: } // Parse. If parse fails, return Json() and assign an error message to err. - static Json parse(const QString & in, - QString & err, - JsonParse strategy = JsonParse::STANDARD); - static Json parse(const char * in, - QString & err, - JsonParse strategy = JsonParse::STANDARD) { + static Json parse(const QString& in, QString& err, JsonParse strategy = JsonParse::STANDARD); + static Json parse(const char* in, QString& err, JsonParse strategy = JsonParse::STANDARD) { if (in) { return parse(QString(in), err, strategy); } else { @@ -190,12 +196,20 @@ public: } } - bool operator== (const Json &rhs) const; - bool operator< (const Json &rhs) const; - bool operator!= (const Json &rhs) const { return !(*this == rhs); } - bool operator<= (const Json &rhs) const { return !(rhs < *this); } - bool operator> (const Json &rhs) const { return (rhs < *this); } - bool operator>= (const Json &rhs) const { return !(*this < rhs); } + bool operator==(const Json& rhs) const; + bool operator<(const Json& rhs) const; + bool operator!=(const Json& rhs) const { + return !(*this == rhs); + } + bool operator<=(const Json& rhs) const { + return !(rhs < *this); + } + bool operator>(const Json& rhs) const { + return (rhs < *this); + } + bool operator>=(const Json& rhs) const { + return !(*this < rhs); + } private: std::shared_ptr m_ptr; @@ -203,19 +217,19 @@ private: class JsonDoc { public: - JsonDoc(Json *object) { + JsonDoc(Json* object) { this->m_obj = object; this->m_indent = 0; }; - void dump(QFile *file) { + void dump(QFile* file) { QTextStream fileStream(file); fileStream << m_obj->dump(&m_indent); fileStream << "\n"; // pad file with newline } private: - Json *m_obj; + Json* m_obj; int m_indent; }; @@ -226,18 +240,19 @@ protected: friend class JsonInt; friend class JsonDouble; virtual Json::Type type() const = 0; - virtual bool equals(const JsonValue * other) const = 0; - virtual bool less(const JsonValue * other) const = 0; - virtual void dump(QString &out, int *indent) const = 0; + virtual bool equals(const JsonValue* other) const = 0; + virtual bool less(const JsonValue* other) const = 0; + virtual void dump(QString& out, int* indent) const = 0; virtual double number_value() const; virtual int int_value() const; virtual bool bool_value() const; - virtual const QString &string_value() const; - virtual const Json::array &array_items() const; - virtual const Json &operator[](int i) const; - virtual const Json::object &object_items() const; - virtual const Json &operator[](const QString &key) const; - virtual ~JsonValue() {} + virtual const QString& string_value() const; + virtual const Json::array& array_items() const; + virtual const Json& operator[](int i) const; + virtual const Json::object& object_items() const; + virtual const Json& operator[](const QString& key) const; + virtual ~JsonValue() { + } }; } // namespace poryjson diff --git a/include/lib/orderedmap.h b/include/lib/orderedmap.h index 40882d9f..215c8184 100644 --- a/include/lib/orderedmap.h +++ b/include/lib/orderedmap.h @@ -1,18 +1,18 @@ /** * MIT License - * + * * Copyright (c) 2017 Tessil - * + * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: - * + * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. - * + * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,7 +25,6 @@ #ifndef TSL_ORDERED_MAP_H #define TSL_ORDERED_MAP_H - #include #include #include @@ -45,1643 +44,1503 @@ #include #include - /** * Macros for compatibility with GCC 4.8 */ #if (defined(__GNUC__) && (__GNUC__ == 4) && (__GNUC_MINOR__ < 9)) -# define TSL_OH_NO_CONTAINER_ERASE_CONST_ITERATOR -# define TSL_OH_NO_CONTAINER_EMPLACE_CONST_ITERATOR +#define TSL_OH_NO_CONTAINER_ERASE_CONST_ITERATOR +#define TSL_OH_NO_CONTAINER_EMPLACE_CONST_ITERATOR #endif /** - * Only activate tsl_oh_assert if TSL_DEBUG is defined. + * Only activate tsl_oh_assert if TSL_DEBUG is defined. * This way we avoid the performance hit when NDEBUG is not defined with assert as tsl_oh_assert is used a lot * (people usually compile with "-O3" and not "-O3 -DNDEBUG"). */ #ifdef TSL_DEBUG -# define tsl_oh_assert(expr) assert(expr) +#define tsl_oh_assert(expr) assert(expr) #else -# define tsl_oh_assert(expr) (static_cast(0)) +#define tsl_oh_assert(expr) (static_cast(0)) #endif /** * If exceptions are enabled, throw the exception passed in parameter, otherwise call std::terminate. */ -#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || (defined (_MSC_VER) && defined (_CPPUNWIND))) && !defined(TSL_NO_EXCEPTIONS) -# define TSL_OH_THROW_OR_TERMINATE(ex, msg) throw ex(msg) +#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || (defined(_MSC_VER) && defined(_CPPUNWIND))) && !defined(TSL_NO_EXCEPTIONS) +#define TSL_OH_THROW_OR_TERMINATE(ex, msg) throw ex(msg) #else -# define TSL_OH_NO_EXCEPTIONS -# ifdef NDEBUG -# define TSL_OH_THROW_OR_TERMINATE(ex, msg) std::terminate() -# else -# include -# define TSL_OH_THROW_OR_TERMINATE(ex, msg) do { std::cerr << msg << std::endl; std::terminate(); } while(0) -# endif +#define TSL_OH_NO_EXCEPTIONS +#ifdef NDEBUG +#define TSL_OH_THROW_OR_TERMINATE(ex, msg) std::terminate() +#else +#include +#define TSL_OH_THROW_OR_TERMINATE(ex, msg) \ + do { \ + std::cerr << msg << std::endl; \ + std::terminate(); \ + } while (0) +#endif #endif - namespace tsl { namespace detail_ordered_hash { - -template -struct make_void { - using type = void; -}; -template -struct has_is_transparent: std::false_type { -}; + template struct make_void { using type = void; }; -template -struct has_is_transparent::type>: std::true_type { -}; + template struct has_is_transparent : std::false_type {}; + template struct has_is_transparent::type> : std::true_type {}; -template -struct is_vector: std::false_type { -}; + template struct is_vector : std::false_type {}; -template -struct is_vector>::value - >::type>: std::true_type { -}; + template + struct is_vector>::value>::type> + : std::true_type {}; -template -static T numeric_cast(U value, const char* error_message = "numeric_cast() failed.") { - T ret = static_cast(value); - if(static_cast(ret) != value) { - TSL_OH_THROW_OR_TERMINATE(std::runtime_error, error_message); + template static T numeric_cast(U value, const char* error_message = "numeric_cast() failed.") { + T ret = static_cast(value); + if (static_cast(ret) != value) { + TSL_OH_THROW_OR_TERMINATE(std::runtime_error, error_message); + } + + const bool is_same_signedness = (std::is_unsigned::value && std::is_unsigned::value) || (std::is_signed::value && std::is_signed::value); + if (!is_same_signedness && (ret < T{}) != (value < U{})) { + TSL_OH_THROW_OR_TERMINATE(std::runtime_error, error_message); + } + + return ret; } - - const bool is_same_signedness = (std::is_unsigned::value && std::is_unsigned::value) || - (std::is_signed::value && std::is_signed::value); - if(!is_same_signedness && (ret < T{}) != (value < U{})) { - TSL_OH_THROW_OR_TERMINATE(std::runtime_error, error_message); - } - - return ret; -} + /** + * Fixed size type used to represent size_type values on serialization. Need to be big enough + * to represent a std::size_t on 32 and 64 bits platforms, and must be the same size on both platforms. + */ + using slz_size_type = std::uint64_t; + static_assert(std::numeric_limits::max() >= std::numeric_limits::max(), "slz_size_type must be >= std::size_t"); -/** - * Fixed size type used to represent size_type values on serialization. Need to be big enough - * to represent a std::size_t on 32 and 64 bits platforms, and must be the same size on both platforms. - */ -using slz_size_type = std::uint64_t; -static_assert(std::numeric_limits::max() >= std::numeric_limits::max(), - "slz_size_type must be >= std::size_t"); - -template -static T deserialize_value(Deserializer& deserializer) { - // MSVC < 2017 is not conformant, circumvent the problem by removing the template keyword -#if defined (_MSC_VER) && _MSC_VER < 1910 - return deserializer.Deserializer::operator()(); + template static T deserialize_value(Deserializer& deserializer) { +// MSVC < 2017 is not conformant, circumvent the problem by removing the template keyword +#if defined(_MSC_VER) && _MSC_VER < 1910 + return deserializer.Deserializer::operator()(); #else - return deserializer.Deserializer::template operator()(); + return deserializer.Deserializer::template operator()(); #endif -} + } + /** + * Each bucket entry stores an index which is the index in m_values corresponding to the bucket's value + * and a hash (which may be truncated to 32 bits depending on IndexType) corresponding to the hash of the value. + * + * The size of IndexType limits the size of the hash table to std::numeric_limits::max() - 1 elements (-1 due to + * a reserved value used to mark a bucket as empty). + */ + template class bucket_entry { + static_assert(std::is_unsigned::value, "IndexType must be an unsigned value."); + static_assert(std::numeric_limits::max() <= std::numeric_limits::max(), + "std::numeric_limits::max() must be <= std::numeric_limits::max()."); -/** - * Each bucket entry stores an index which is the index in m_values corresponding to the bucket's value - * and a hash (which may be truncated to 32 bits depending on IndexType) corresponding to the hash of the value. - * - * The size of IndexType limits the size of the hash table to std::numeric_limits::max() - 1 elements (-1 due to - * a reserved value used to mark a bucket as empty). - */ -template -class bucket_entry { - static_assert(std::is_unsigned::value, "IndexType must be an unsigned value."); - static_assert(std::numeric_limits::max() <= std::numeric_limits::max(), - "std::numeric_limits::max() must be <= std::numeric_limits::max()."); - -public: - using index_type = IndexType; - using truncated_hash_type = typename std::conditional::max() <= - std::numeric_limits::max(), - std::uint_least32_t, - std::size_t>::type; - - bucket_entry() noexcept: m_index(EMPTY_MARKER_INDEX), m_hash(0) { - } - - bool empty() const noexcept { - return m_index == EMPTY_MARKER_INDEX; - } - - void clear() noexcept { - m_index = EMPTY_MARKER_INDEX; - } - - index_type index() const noexcept { - tsl_oh_assert(!empty()); - return m_index; - } - - index_type& index_ref() noexcept { - tsl_oh_assert(!empty()); - return m_index; - } - - void set_index(index_type index) noexcept { - tsl_oh_assert(index <= max_size()); - - m_index = index; - } - - truncated_hash_type truncated_hash() const noexcept { - tsl_oh_assert(!empty()); - return m_hash; - } - - truncated_hash_type& truncated_hash_ref() noexcept { - tsl_oh_assert(!empty()); - return m_hash; - } - - void set_hash(std::size_t hash) noexcept { - m_hash = truncate_hash(hash); - } - - template - void serialize(Serializer& serializer) const { - const slz_size_type index = m_index; - serializer(index); - - const slz_size_type hash = m_hash; - serializer(hash); - } - - template - static bucket_entry deserialize(Deserializer& deserializer) { - const slz_size_type index = deserialize_value(deserializer); - const slz_size_type hash = deserialize_value(deserializer); - - bucket_entry bentry; - bentry.m_index = numeric_cast(index, "Deserialized index is too big."); - bentry.m_hash = numeric_cast(hash, "Deserialized hash is too big."); - - return bentry; - } - - - - static truncated_hash_type truncate_hash(std::size_t hash) noexcept { - return truncated_hash_type(hash); - } - - static std::size_t max_size() noexcept { - return static_cast(std::numeric_limits::max()) - NB_RESERVED_INDEXES; - } - -private: - static const index_type EMPTY_MARKER_INDEX = std::numeric_limits::max(); - static const std::size_t NB_RESERVED_INDEXES = 1; - - index_type m_index; - truncated_hash_type m_hash; -}; - - - -/** - * Internal common class used by ordered_map and ordered_set. - * - * ValueType is what will be stored by ordered_hash (usually std::pair for map and Key for set). - * - * KeySelect should be a FunctionObject which takes a ValueType in parameter and return a reference to the key. - * - * ValueSelect should be a FunctionObject which takes a ValueType in parameter and return a reference to the value. - * ValueSelect should be void if there is no value (in set for example). - * - * ValueTypeContainer is the container which will be used to store ValueType values. - * Usually a std::deque or std::vector. - * - * - * - * The orderd_hash structure is a hash table which preserves the order of insertion of the elements. - * To do so, it stores the values in the ValueTypeContainer (m_values) using emplace_back at each - * insertion of a new element. Another structure (m_buckets of type std::vector) will - * serve as buckets array for the hash table part. Each bucket stores an index which corresponds to - * the index in m_values where the bucket's value is and the (truncated) hash of this value. An index - * is used instead of a pointer to the value to reduce the size of each bucket entry. - * - * To resolve collisions in the buckets array, the structures use robin hood linear probing with - * backward shift deletion. - */ -template -class ordered_hash: private Hash, private KeyEqual { -private: - template - using has_mapped_type = typename std::integral_constant::value>; - - static_assert(std::is_same::value, - "ValueTypeContainer::value_type != ValueType. " - "Check that the ValueTypeContainer has 'Key' as type for a set or 'std::pair' as type for a map."); - - static_assert(std::is_same::value, - "ValueTypeContainer::allocator_type != Allocator. " - "Check that the allocator for ValueTypeContainer is the same as Allocator."); - - static_assert(std::is_same::value, - "Allocator::value_type != ValueType. " - "Check that the allocator has 'Key' as type for a set or 'std::pair' as type for a map."); - - -public: - template - class ordered_iterator; - - using key_type = typename KeySelect::key_type; - using value_type = ValueType; - using size_type = std::size_t; - using difference_type = std::ptrdiff_t; - using hasher = Hash; - using key_equal = KeyEqual; - using allocator_type = Allocator; - using reference = value_type&; - using const_reference = const value_type&; - using pointer = value_type*; - using const_pointer = const value_type*; - using iterator = ordered_iterator; - using const_iterator = ordered_iterator; - using reverse_iterator = std::reverse_iterator; - using const_reverse_iterator = std::reverse_iterator; - - using values_container_type = ValueTypeContainer; - -public: - template - class ordered_iterator { - friend class ordered_hash; - - private: - using iterator = typename std::conditional::type; - - - ordered_iterator(iterator it) noexcept: m_iterator(it) { - } - public: - using iterator_category = std::random_access_iterator_tag; - using value_type = const typename ordered_hash::value_type; - using difference_type = typename iterator::difference_type; - using reference = value_type&; - using pointer = value_type*; - - - ordered_iterator() noexcept { - } - - // Copy constructor from iterator to const_iterator. - template::type* = nullptr> - ordered_iterator(const ordered_iterator& other) noexcept: m_iterator(other.m_iterator) { + using index_type = IndexType; + using truncated_hash_type = typename std::conditional::max() <= std::numeric_limits::max(), + std::uint_least32_t, std::size_t>::type; + + bucket_entry() noexcept : m_index(EMPTY_MARKER_INDEX), m_hash(0) { } - ordered_iterator(const ordered_iterator& other) = default; - ordered_iterator(ordered_iterator&& other) = default; - ordered_iterator& operator=(const ordered_iterator& other) = default; - ordered_iterator& operator=(ordered_iterator&& other) = default; - - const typename ordered_hash::key_type& key() const { - return KeySelect()(*m_iterator); + bool empty() const noexcept { + return m_index == EMPTY_MARKER_INDEX; } - template::value && IsConst>::type* = nullptr> - const typename U::value_type& value() const { - return U()(*m_iterator); + void clear() noexcept { + m_index = EMPTY_MARKER_INDEX; } - template::value && !IsConst>::type* = nullptr> - typename U::value_type& value() { - return U()(*m_iterator); - } - - reference operator*() const { return *m_iterator; } - pointer operator->() const { return m_iterator.operator->(); } - - ordered_iterator& operator++() { ++m_iterator; return *this; } - ordered_iterator& operator--() { --m_iterator; return *this; } - - ordered_iterator operator++(int) { ordered_iterator tmp(*this); ++(*this); return tmp; } - ordered_iterator operator--(int) { ordered_iterator tmp(*this); --(*this); return tmp; } - - reference operator[](difference_type n) const { return m_iterator[n]; } - - ordered_iterator& operator+=(difference_type n) { m_iterator += n; return *this; } - ordered_iterator& operator-=(difference_type n) { m_iterator -= n; return *this; } - - ordered_iterator operator+(difference_type n) { ordered_iterator tmp(*this); tmp += n; return tmp; } - ordered_iterator operator-(difference_type n) { ordered_iterator tmp(*this); tmp -= n; return tmp; } - - friend bool operator==(const ordered_iterator& lhs, const ordered_iterator& rhs) { - return lhs.m_iterator == rhs.m_iterator; - } - - friend bool operator!=(const ordered_iterator& lhs, const ordered_iterator& rhs) { - return lhs.m_iterator != rhs.m_iterator; - } - - friend bool operator<(const ordered_iterator& lhs, const ordered_iterator& rhs) { - return lhs.m_iterator < rhs.m_iterator; - } - - friend bool operator>(const ordered_iterator& lhs, const ordered_iterator& rhs) { - return lhs.m_iterator > rhs.m_iterator; - } - - friend bool operator<=(const ordered_iterator& lhs, const ordered_iterator& rhs) { - return lhs.m_iterator <= rhs.m_iterator; - } - - friend bool operator>=(const ordered_iterator& lhs, const ordered_iterator& rhs) { - return lhs.m_iterator >= rhs.m_iterator; + index_type index() const noexcept { + tsl_oh_assert(!empty()); + return m_index; } - friend ordered_iterator operator+(difference_type n, const ordered_iterator& it) { - return n + it.m_iterator; + index_type& index_ref() noexcept { + tsl_oh_assert(!empty()); + return m_index; } - friend difference_type operator-(const ordered_iterator& lhs, const ordered_iterator& rhs) { - return lhs.m_iterator - rhs.m_iterator; + void set_index(index_type index) noexcept { + tsl_oh_assert(index <= max_size()); + + m_index = index; + } + + truncated_hash_type truncated_hash() const noexcept { + tsl_oh_assert(!empty()); + return m_hash; + } + + truncated_hash_type& truncated_hash_ref() noexcept { + tsl_oh_assert(!empty()); + return m_hash; + } + + void set_hash(std::size_t hash) noexcept { + m_hash = truncate_hash(hash); + } + + template void serialize(Serializer& serializer) const { + const slz_size_type index = m_index; + serializer(index); + + const slz_size_type hash = m_hash; + serializer(hash); + } + + template static bucket_entry deserialize(Deserializer& deserializer) { + const slz_size_type index = deserialize_value(deserializer); + const slz_size_type hash = deserialize_value(deserializer); + + bucket_entry bentry; + bentry.m_index = numeric_cast(index, "Deserialized index is too big."); + bentry.m_hash = numeric_cast(hash, "Deserialized hash is too big."); + + return bentry; + } + + static truncated_hash_type truncate_hash(std::size_t hash) noexcept { + return truncated_hash_type(hash); + } + + static std::size_t max_size() noexcept { + return static_cast(std::numeric_limits::max()) - NB_RESERVED_INDEXES; } private: - iterator m_iterator; - }; - - -private: - using bucket_entry = tsl::detail_ordered_hash::bucket_entry; - - using buckets_container_allocator = typename - std::allocator_traits::template rebind_alloc; - - using buckets_container_type = std::vector; - - - using truncated_hash_type = typename bucket_entry::truncated_hash_type; - using index_type = typename bucket_entry::index_type; - -public: - ordered_hash(size_type bucket_count, - const Hash& hash, - const KeyEqual& equal, - const Allocator& alloc, - float max_load_factor): Hash(hash), - KeyEqual(equal), - m_buckets_data(alloc), - m_buckets(static_empty_bucket_ptr()), - m_mask(0), - m_values(alloc), - m_grow_on_next_insert(false) - { - if(bucket_count > max_bucket_count()) { - TSL_OH_THROW_OR_TERMINATE(std::length_error, "The map exceeds its maxmimum size."); - } - - if(bucket_count > 0) { - bucket_count = round_up_to_power_of_two(bucket_count); - - m_buckets_data.resize(bucket_count); - m_buckets = m_buckets_data.data(), - m_mask = bucket_count - 1; - } - - this->max_load_factor(max_load_factor); - } - - ordered_hash(const ordered_hash& other): Hash(other), - KeyEqual(other), - m_buckets_data(other.m_buckets_data), - m_buckets(m_buckets_data.empty()?static_empty_bucket_ptr(): - m_buckets_data.data()), - m_mask(other.m_mask), - m_values(other.m_values), - m_grow_on_next_insert(other.m_grow_on_next_insert), - m_max_load_factor(other.m_max_load_factor), - m_load_threshold(other.m_load_threshold) - { - } - - ordered_hash(ordered_hash&& other) noexcept(std::is_nothrow_move_constructible::value && - std::is_nothrow_move_constructible::value && - std::is_nothrow_move_constructible::value && - std::is_nothrow_move_constructible::value) - : Hash(std::move(static_cast(other))), - KeyEqual(std::move(static_cast(other))), - m_buckets_data(std::move(other.m_buckets_data)), - m_buckets(m_buckets_data.empty()?static_empty_bucket_ptr(): - m_buckets_data.data()), - m_mask(other.m_mask), - m_values(std::move(other.m_values)), - m_grow_on_next_insert(other.m_grow_on_next_insert), - m_max_load_factor(other.m_max_load_factor), - m_load_threshold(other.m_load_threshold) - { - other.m_buckets_data.clear(); - other.m_buckets = static_empty_bucket_ptr(); - other.m_mask = 0; - other.m_values.clear(); - other.m_grow_on_next_insert = false; - other.m_load_threshold = 0; - } - - ordered_hash& operator=(const ordered_hash& other) { - if(&other != this) { - Hash::operator=(other); - KeyEqual::operator=(other); - - m_buckets_data = other.m_buckets_data; - m_buckets = m_buckets_data.empty()?static_empty_bucket_ptr(): - m_buckets_data.data(); - - m_mask = other.m_mask; - m_values = other.m_values; - m_grow_on_next_insert = other.m_grow_on_next_insert; - m_max_load_factor = other.m_max_load_factor; - m_load_threshold = other.m_load_threshold; - } - - return *this; - } - - ordered_hash& operator=(ordered_hash&& other) { - other.swap(*this); - other.clear(); - - return *this; - } - - allocator_type get_allocator() const { - return m_values.get_allocator(); - } - - - /* - * Iterators - */ - iterator begin() noexcept { - return iterator(m_values.begin()); - } - - const_iterator begin() const noexcept { - return cbegin(); - } - - const_iterator cbegin() const noexcept { - return const_iterator(m_values.cbegin()); - } - - iterator end() noexcept { - return iterator(m_values.end()); - } - - const_iterator end() const noexcept { - return cend(); - } - - const_iterator cend() const noexcept { - return const_iterator(m_values.cend()); - } - - - reverse_iterator rbegin() noexcept { - return reverse_iterator(m_values.end()); - } - - const_reverse_iterator rbegin() const noexcept { - return rcbegin(); - } - - const_reverse_iterator rcbegin() const noexcept { - return const_reverse_iterator(m_values.cend()); - } - - reverse_iterator rend() noexcept { - return reverse_iterator(m_values.begin()); - } - - const_reverse_iterator rend() const noexcept { - return rcend(); - } - - const_reverse_iterator rcend() const noexcept { - return const_reverse_iterator(m_values.cbegin()); - } - - - /* - * Capacity - */ - bool empty() const noexcept { - return m_values.empty(); - } - - size_type size() const noexcept { - return m_values.size(); - } - - size_type max_size() const noexcept { - return std::min(bucket_entry::max_size(), m_values.max_size()); - } - + static const index_type EMPTY_MARKER_INDEX = std::numeric_limits::max(); + static const std::size_t NB_RESERVED_INDEXES = 1; - /* - * Modifiers + index_type m_index; + truncated_hash_type m_hash; + }; + + /** + * Internal common class used by ordered_map and ordered_set. + * + * ValueType is what will be stored by ordered_hash (usually std::pair for map and Key for set). + * + * KeySelect should be a FunctionObject which takes a ValueType in parameter and return a reference to the key. + * + * ValueSelect should be a FunctionObject which takes a ValueType in parameter and return a reference to the value. + * ValueSelect should be void if there is no value (in set for example). + * + * ValueTypeContainer is the container which will be used to store ValueType values. + * Usually a std::deque or std::vector. + * + * + * + * The orderd_hash structure is a hash table which preserves the order of insertion of the elements. + * To do so, it stores the values in the ValueTypeContainer (m_values) using emplace_back at each + * insertion of a new element. Another structure (m_buckets of type std::vector) will + * serve as buckets array for the hash table part. Each bucket stores an index which corresponds to + * the index in m_values where the bucket's value is and the (truncated) hash of this value. An index + * is used instead of a pointer to the value to reduce the size of each bucket entry. + * + * To resolve collisions in the buckets array, the structures use robin hood linear probing with + * backward shift deletion. */ - void clear() noexcept { - for(auto& bucket: m_buckets_data) { - bucket.clear(); + template + class ordered_hash : private Hash, private KeyEqual { + private: + template using has_mapped_type = typename std::integral_constant::value>; + + static_assert(std::is_same::value, + "ValueTypeContainer::value_type != ValueType. " + "Check that the ValueTypeContainer has 'Key' as type for a set or 'std::pair' as type for a map."); + + static_assert(std::is_same::value, + "ValueTypeContainer::allocator_type != Allocator. " + "Check that the allocator for ValueTypeContainer is the same as Allocator."); + + static_assert(std::is_same::value, + "Allocator::value_type != ValueType. " + "Check that the allocator has 'Key' as type for a set or 'std::pair' as type for a map."); + + public: + template class ordered_iterator; + + using key_type = typename KeySelect::key_type; + using value_type = ValueType; + using size_type = std::size_t; + using difference_type = std::ptrdiff_t; + using hasher = Hash; + using key_equal = KeyEqual; + using allocator_type = Allocator; + using reference = value_type&; + using const_reference = const value_type&; + using pointer = value_type*; + using const_pointer = const value_type*; + using iterator = ordered_iterator; + using const_iterator = ordered_iterator; + using reverse_iterator = std::reverse_iterator; + using const_reverse_iterator = std::reverse_iterator; + + using values_container_type = ValueTypeContainer; + + public: + template class ordered_iterator { + friend class ordered_hash; + + private: + using iterator = typename std::conditional::type; + + ordered_iterator(iterator it) noexcept : m_iterator(it) { + } + + public: + using iterator_category = std::random_access_iterator_tag; + using value_type = const typename ordered_hash::value_type; + using difference_type = typename iterator::difference_type; + using reference = value_type&; + using pointer = value_type*; + + ordered_iterator() noexcept { + } + + // Copy constructor from iterator to const_iterator. + template ::type* = nullptr> + ordered_iterator(const ordered_iterator& other) noexcept : m_iterator(other.m_iterator) { + } + + ordered_iterator(const ordered_iterator& other) = default; + ordered_iterator(ordered_iterator&& other) = default; + ordered_iterator& operator=(const ordered_iterator& other) = default; + ordered_iterator& operator=(ordered_iterator&& other) = default; + + const typename ordered_hash::key_type& key() const { + return KeySelect()(*m_iterator); + } + + template ::value && IsConst>::type* = nullptr> + const typename U::value_type& value() const { + return U()(*m_iterator); + } + + template ::value && !IsConst>::type* = nullptr> typename U::value_type& value() { + return U()(*m_iterator); + } + + reference operator*() const { + return *m_iterator; + } + pointer operator->() const { + return m_iterator.operator->(); + } + + ordered_iterator& operator++() { + ++m_iterator; + return *this; + } + ordered_iterator& operator--() { + --m_iterator; + return *this; + } + + ordered_iterator operator++(int) { + ordered_iterator tmp(*this); + ++(*this); + return tmp; + } + ordered_iterator operator--(int) { + ordered_iterator tmp(*this); + --(*this); + return tmp; + } + + reference operator[](difference_type n) const { + return m_iterator[n]; + } + + ordered_iterator& operator+=(difference_type n) { + m_iterator += n; + return *this; + } + ordered_iterator& operator-=(difference_type n) { + m_iterator -= n; + return *this; + } + + ordered_iterator operator+(difference_type n) { + ordered_iterator tmp(*this); + tmp += n; + return tmp; + } + ordered_iterator operator-(difference_type n) { + ordered_iterator tmp(*this); + tmp -= n; + return tmp; + } + + friend bool operator==(const ordered_iterator& lhs, const ordered_iterator& rhs) { + return lhs.m_iterator == rhs.m_iterator; + } + + friend bool operator!=(const ordered_iterator& lhs, const ordered_iterator& rhs) { + return lhs.m_iterator != rhs.m_iterator; + } + + friend bool operator<(const ordered_iterator& lhs, const ordered_iterator& rhs) { + return lhs.m_iterator < rhs.m_iterator; + } + + friend bool operator>(const ordered_iterator& lhs, const ordered_iterator& rhs) { + return lhs.m_iterator > rhs.m_iterator; + } + + friend bool operator<=(const ordered_iterator& lhs, const ordered_iterator& rhs) { + return lhs.m_iterator <= rhs.m_iterator; + } + + friend bool operator>=(const ordered_iterator& lhs, const ordered_iterator& rhs) { + return lhs.m_iterator >= rhs.m_iterator; + } + + friend ordered_iterator operator+(difference_type n, const ordered_iterator& it) { + return n + it.m_iterator; + } + + friend difference_type operator-(const ordered_iterator& lhs, const ordered_iterator& rhs) { + return lhs.m_iterator - rhs.m_iterator; + } + + private: + iterator m_iterator; + }; + + private: + using bucket_entry = tsl::detail_ordered_hash::bucket_entry; + + using buckets_container_allocator = typename std::allocator_traits::template rebind_alloc; + + using buckets_container_type = std::vector; + + using truncated_hash_type = typename bucket_entry::truncated_hash_type; + using index_type = typename bucket_entry::index_type; + + public: + ordered_hash(size_type bucket_count, const Hash& hash, const KeyEqual& equal, const Allocator& alloc, float max_load_factor) + : Hash(hash), + KeyEqual(equal), + m_buckets_data(alloc), + m_buckets(static_empty_bucket_ptr()), + m_mask(0), + m_values(alloc), + m_grow_on_next_insert(false) { + if (bucket_count > max_bucket_count()) { + TSL_OH_THROW_OR_TERMINATE(std::length_error, "The map exceeds its maxmimum size."); + } + + if (bucket_count > 0) { + bucket_count = round_up_to_power_of_two(bucket_count); + + m_buckets_data.resize(bucket_count); + m_buckets = m_buckets_data.data(), m_mask = bucket_count - 1; + } + + this->max_load_factor(max_load_factor); } - - m_values.clear(); - m_grow_on_next_insert = false; - } - - template - std::pair insert(P&& value) { - return insert_impl(KeySelect()(value), std::forward

(value)); - } - - template - iterator insert_hint(const_iterator hint, P&& value) { - if(hint != cend() && compare_keys(KeySelect()(*hint), KeySelect()(value))) { - return mutable_iterator(hint); + + ordered_hash(const ordered_hash& other) + : Hash(other), + KeyEqual(other), + m_buckets_data(other.m_buckets_data), + m_buckets(m_buckets_data.empty() ? static_empty_bucket_ptr() : m_buckets_data.data()), + m_mask(other.m_mask), + m_values(other.m_values), + m_grow_on_next_insert(other.m_grow_on_next_insert), + m_max_load_factor(other.m_max_load_factor), + m_load_threshold(other.m_load_threshold) { } - - return insert(std::forward

(value)).first; - } - - template - void insert(InputIt first, InputIt last) { - if(std::is_base_of::iterator_category>::value) - { - const auto nb_elements_insert = std::distance(first, last); - const size_type nb_free_buckets = m_load_threshold - size(); - tsl_oh_assert(m_load_threshold >= size()); - - if(nb_elements_insert > 0 && nb_free_buckets < size_type(nb_elements_insert)) { - reserve(size() + size_type(nb_elements_insert)); + + ordered_hash(ordered_hash&& other) noexcept(std::is_nothrow_move_constructible::value&& std::is_nothrow_move_constructible::value&& + std::is_nothrow_move_constructible::value&& std::is_nothrow_move_constructible::value) + : Hash(std::move(static_cast(other))), + KeyEqual(std::move(static_cast(other))), + m_buckets_data(std::move(other.m_buckets_data)), + m_buckets(m_buckets_data.empty() ? static_empty_bucket_ptr() : m_buckets_data.data()), + m_mask(other.m_mask), + m_values(std::move(other.m_values)), + m_grow_on_next_insert(other.m_grow_on_next_insert), + m_max_load_factor(other.m_max_load_factor), + m_load_threshold(other.m_load_threshold) { + other.m_buckets_data.clear(); + other.m_buckets = static_empty_bucket_ptr(); + other.m_mask = 0; + other.m_values.clear(); + other.m_grow_on_next_insert = false; + other.m_load_threshold = 0; + } + + ordered_hash& operator=(const ordered_hash& other) { + if (&other != this) { + Hash::operator=(other); + KeyEqual::operator=(other); + + m_buckets_data = other.m_buckets_data; + m_buckets = m_buckets_data.empty() ? static_empty_bucket_ptr() : m_buckets_data.data(); + + m_mask = other.m_mask; + m_values = other.m_values; + m_grow_on_next_insert = other.m_grow_on_next_insert; + m_max_load_factor = other.m_max_load_factor; + m_load_threshold = other.m_load_threshold; + } + + return *this; + } + + ordered_hash& operator=(ordered_hash&& other) { + other.swap(*this); + other.clear(); + + return *this; + } + + allocator_type get_allocator() const { + return m_values.get_allocator(); + } + + /* + * Iterators + */ + iterator begin() noexcept { + return iterator(m_values.begin()); + } + + const_iterator begin() const noexcept { + return cbegin(); + } + + const_iterator cbegin() const noexcept { + return const_iterator(m_values.cbegin()); + } + + iterator end() noexcept { + return iterator(m_values.end()); + } + + const_iterator end() const noexcept { + return cend(); + } + + const_iterator cend() const noexcept { + return const_iterator(m_values.cend()); + } + + reverse_iterator rbegin() noexcept { + return reverse_iterator(m_values.end()); + } + + const_reverse_iterator rbegin() const noexcept { + return rcbegin(); + } + + const_reverse_iterator rcbegin() const noexcept { + return const_reverse_iterator(m_values.cend()); + } + + reverse_iterator rend() noexcept { + return reverse_iterator(m_values.begin()); + } + + const_reverse_iterator rend() const noexcept { + return rcend(); + } + + const_reverse_iterator rcend() const noexcept { + return const_reverse_iterator(m_values.cbegin()); + } + + /* + * Capacity + */ + bool empty() const noexcept { + return m_values.empty(); + } + + size_type size() const noexcept { + return m_values.size(); + } + + size_type max_size() const noexcept { + return std::min(bucket_entry::max_size(), m_values.max_size()); + } + + /* + * Modifiers + */ + void clear() noexcept { + for (auto& bucket : m_buckets_data) { + bucket.clear(); + } + + m_values.clear(); + m_grow_on_next_insert = false; + } + + template std::pair insert(P&& value) { + return insert_impl(KeySelect()(value), std::forward

(value)); + } + + template iterator insert_hint(const_iterator hint, P&& value) { + if (hint != cend() && compare_keys(KeySelect()(*hint), KeySelect()(value))) { + return mutable_iterator(hint); + } + + return insert(std::forward

(value)).first; + } + + template void insert(InputIt first, InputIt last) { + if (std::is_base_of::iterator_category>::value) { + const auto nb_elements_insert = std::distance(first, last); + const size_type nb_free_buckets = m_load_threshold - size(); + tsl_oh_assert(m_load_threshold >= size()); + + if (nb_elements_insert > 0 && nb_free_buckets < size_type(nb_elements_insert)) { + reserve(size() + size_type(nb_elements_insert)); + } + } + + for (; first != last; ++first) { + insert(*first); } } - - for(; first != last; ++first) { - insert(*first); - } - } - - - - template - std::pair insert_or_assign(K&& key, M&& value) { - auto it = try_emplace(std::forward(key), std::forward(value)); - if(!it.second) { - it.first.value() = std::forward(value); - } - - return it; - } - - template - iterator insert_or_assign(const_iterator hint, K&& key, M&& obj) { - if(hint != cend() && compare_keys(KeySelect()(*hint), key)) { - auto it = mutable_iterator(hint); - it.value() = std::forward(obj); - + + template std::pair insert_or_assign(K&& key, M&& value) { + auto it = try_emplace(std::forward(key), std::forward(value)); + if (!it.second) { + it.first.value() = std::forward(value); + } + return it; } - - return insert_or_assign(std::forward(key), std::forward(obj)).first; - } - - - - template - std::pair emplace(Args&&... args) { - return insert(value_type(std::forward(args)...)); - } - - template - iterator emplace_hint(const_iterator hint, Args&&... args) { - return insert_hint(hint, value_type(std::forward(args)...)); - } - - - - template - std::pair try_emplace(K&& key, Args&&... value_args) { - return insert_impl(key, std::piecewise_construct, - std::forward_as_tuple(std::forward(key)), - std::forward_as_tuple(std::forward(value_args)...)); - } - - template - iterator try_emplace_hint(const_iterator hint, K&& key, Args&&... args) { - if(hint != cend() && compare_keys(KeySelect()(*hint), key)) { - return mutable_iterator(hint); - } - - return try_emplace(std::forward(key), std::forward(args)...).first; - } - - - - /** - * Here to avoid `template size_type erase(const K& key)` being used when - * we use an `iterator` instead of a `const_iterator`. - */ - iterator erase(iterator pos) { - return erase(const_iterator(pos)); - } - - iterator erase(const_iterator pos) { - tsl_oh_assert(pos != cend()); - - const std::size_t index_erase = iterator_to_index(pos); - - auto it_bucket = find_key(pos.key(), hash_key(pos.key())); - tsl_oh_assert(it_bucket != m_buckets_data.end()); - - erase_value_from_bucket(it_bucket); - - /* - * One element was removed from m_values, due to the left shift the next element - * is now at the position of the previous element (or end if none). - */ - return begin() + index_erase; - } - iterator erase(const_iterator first, const_iterator last) { - if(first == last) { - return mutable_iterator(first); + template iterator insert_or_assign(const_iterator hint, K&& key, M&& obj) { + if (hint != cend() && compare_keys(KeySelect()(*hint), key)) { + auto it = mutable_iterator(hint); + it.value() = std::forward(obj); + + return it; + } + + return insert_or_assign(std::forward(key), std::forward(obj)).first; } - - tsl_oh_assert(std::distance(first, last) > 0); - const std::size_t start_index = iterator_to_index(first); - const std::size_t nb_values = std::size_t(std::distance(first, last)); - const std::size_t end_index = start_index + nb_values; - - // Delete all values -#ifdef TSL_OH_NO_CONTAINER_ERASE_CONST_ITERATOR - auto next_it = m_values.erase(mutable_iterator(first).m_iterator, mutable_iterator(last).m_iterator); + + template std::pair emplace(Args&&... args) { + return insert(value_type(std::forward(args)...)); + } + + template iterator emplace_hint(const_iterator hint, Args&&... args) { + return insert_hint(hint, value_type(std::forward(args)...)); + } + + template std::pair try_emplace(K&& key, Args&&... value_args) { + return insert_impl( + key, std::piecewise_construct, std::forward_as_tuple(std::forward(key)), std::forward_as_tuple(std::forward(value_args)...)); + } + + template iterator try_emplace_hint(const_iterator hint, K&& key, Args&&... args) { + if (hint != cend() && compare_keys(KeySelect()(*hint), key)) { + return mutable_iterator(hint); + } + + return try_emplace(std::forward(key), std::forward(args)...).first; + } + + /** + * Here to avoid `template size_type erase(const K& key)` being used when + * we use an `iterator` instead of a `const_iterator`. + */ + iterator erase(iterator pos) { + return erase(const_iterator(pos)); + } + + iterator erase(const_iterator pos) { + tsl_oh_assert(pos != cend()); + + const std::size_t index_erase = iterator_to_index(pos); + + auto it_bucket = find_key(pos.key(), hash_key(pos.key())); + tsl_oh_assert(it_bucket != m_buckets_data.end()); + + erase_value_from_bucket(it_bucket); + + /* + * One element was removed from m_values, due to the left shift the next element + * is now at the position of the previous element (or end if none). + */ + return begin() + index_erase; + } + + iterator erase(const_iterator first, const_iterator last) { + if (first == last) { + return mutable_iterator(first); + } + + tsl_oh_assert(std::distance(first, last) > 0); + const std::size_t start_index = iterator_to_index(first); + const std::size_t nb_values = std::size_t(std::distance(first, last)); + const std::size_t end_index = start_index + nb_values; + +// Delete all values +#ifdef TSL_OH_NO_CONTAINER_ERASE_CONST_ITERATOR + auto next_it = m_values.erase(mutable_iterator(first).m_iterator, mutable_iterator(last).m_iterator); #else - auto next_it = m_values.erase(first.m_iterator, last.m_iterator); + auto next_it = m_values.erase(first.m_iterator, last.m_iterator); #endif - + + /* + * Mark the buckets corresponding to the values as empty and do a backward shift. + * + * Also, the erase operation on m_values has shifted all the values on the right of last.m_iterator. + * Adapt the indexes for these values. + */ + std::size_t ibucket = 0; + while (ibucket < m_buckets_data.size()) { + if (m_buckets[ibucket].empty()) { + ibucket++; + } else if (m_buckets[ibucket].index() >= start_index && m_buckets[ibucket].index() < end_index) { + m_buckets[ibucket].clear(); + backward_shift(ibucket); + // Don't increment ibucket, backward_shift may have replaced current bucket. + } else if (m_buckets[ibucket].index() >= end_index) { + m_buckets[ibucket].set_index(index_type(m_buckets[ibucket].index() - nb_values)); + ibucket++; + } else { + ibucket++; + } + } + + return iterator(next_it); + } + + template size_type erase(const K& key) { + return erase(key, hash_key(key)); + } + + template size_type erase(const K& key, std::size_t hash) { + return erase_impl(key, hash); + } + + void swap(ordered_hash& other) { + using std::swap; + + swap(static_cast(*this), static_cast(other)); + swap(static_cast(*this), static_cast(other)); + swap(m_buckets_data, other.m_buckets_data); + swap(m_buckets, other.m_buckets); + swap(m_mask, other.m_mask); + swap(m_values, other.m_values); + swap(m_grow_on_next_insert, other.m_grow_on_next_insert); + swap(m_max_load_factor, other.m_max_load_factor); + swap(m_load_threshold, other.m_load_threshold); + } + /* - * Mark the buckets corresponding to the values as empty and do a backward shift. - * - * Also, the erase operation on m_values has shifted all the values on the right of last.m_iterator. - * Adapt the indexes for these values. + * Lookup */ - std::size_t ibucket = 0; - while(ibucket < m_buckets_data.size()) { - if(m_buckets[ibucket].empty()) { - ibucket++; - } - else if(m_buckets[ibucket].index() >= start_index && m_buckets[ibucket].index() < end_index) { - m_buckets[ibucket].clear(); - backward_shift(ibucket); - // Don't increment ibucket, backward_shift may have replaced current bucket. - } - else if(m_buckets[ibucket].index() >= end_index) { - m_buckets[ibucket].set_index(index_type(m_buckets[ibucket].index() - nb_values)); - ibucket++; - } - else { - ibucket++; - } + template ::value>::type* = nullptr> + typename U::value_type& at(const K& key) { + return at(key, hash_key(key)); } - - return iterator(next_it); - } - - template - size_type erase(const K& key) { - return erase(key, hash_key(key)); - } - - template - size_type erase(const K& key, std::size_t hash) { - return erase_impl(key, hash); - } - - void swap(ordered_hash& other) { - using std::swap; - - swap(static_cast(*this), static_cast(other)); - swap(static_cast(*this), static_cast(other)); - swap(m_buckets_data, other.m_buckets_data); - swap(m_buckets, other.m_buckets); - swap(m_mask, other.m_mask); - swap(m_values, other.m_values); - swap(m_grow_on_next_insert, other.m_grow_on_next_insert); - swap(m_max_load_factor, other.m_max_load_factor); - swap(m_load_threshold, other.m_load_threshold); - } - - - + template ::value>::type* = nullptr> + typename U::value_type& at(const K& key, std::size_t hash) { + return const_cast(static_cast(this)->at(key, hash)); + } - /* - * Lookup - */ - template::value>::type* = nullptr> - typename U::value_type& at(const K& key) { - return at(key, hash_key(key)); - } - - template::value>::type* = nullptr> - typename U::value_type& at(const K& key, std::size_t hash) { - return const_cast(static_cast(this)->at(key, hash)); - } - - template::value>::type* = nullptr> - const typename U::value_type& at(const K& key) const { - return at(key, hash_key(key)); - } - - template::value>::type* = nullptr> - const typename U::value_type& at(const K& key, std::size_t hash) const { - auto it = find(key, hash); - if(it != end()) { - return it.value(); + template ::value>::type* = nullptr> + const typename U::value_type& at(const K& key) const { + return at(key, hash_key(key)); } - else { - TSL_OH_THROW_OR_TERMINATE(std::out_of_range, "Couldn't find the key."); + + template ::value>::type* = nullptr> + const typename U::value_type& at(const K& key, std::size_t hash) const { + auto it = find(key, hash); + if (it != end()) { + return it.value(); + } else { + TSL_OH_THROW_OR_TERMINATE(std::out_of_range, "Couldn't find the key."); + } } - } - - - template::value>::type* = nullptr> - typename U::value_type& operator[](K&& key) { - return try_emplace(std::forward(key)).first.value(); - } - - - template - size_type count(const K& key) const { - return count(key, hash_key(key)); - } - - template - size_type count(const K& key, std::size_t hash) const { - if(find(key, hash) == cend()) { - return 0; + + template ::value>::type* = nullptr> + typename U::value_type& operator[](K&& key) { + return try_emplace(std::forward(key)).first.value(); } - else { + + template size_type count(const K& key) const { + return count(key, hash_key(key)); + } + + template size_type count(const K& key, std::size_t hash) const { + if (find(key, hash) == cend()) { + return 0; + } else { + return 1; + } + } + + template iterator find(const K& key) { + return find(key, hash_key(key)); + } + + template iterator find(const K& key, std::size_t hash) { + auto it_bucket = find_key(key, hash); + return (it_bucket != m_buckets_data.end()) ? iterator(m_values.begin() + it_bucket->index()) : end(); + } + + template const_iterator find(const K& key) const { + return find(key, hash_key(key)); + } + + template const_iterator find(const K& key, std::size_t hash) const { + auto it_bucket = find_key(key, hash); + return (it_bucket != m_buckets_data.cend()) ? const_iterator(m_values.begin() + it_bucket->index()) : end(); + } + + template std::pair equal_range(const K& key) { + return equal_range(key, hash_key(key)); + } + + template std::pair equal_range(const K& key, std::size_t hash) { + iterator it = find(key, hash); + return std::make_pair(it, (it == end()) ? it : std::next(it)); + } + + template std::pair equal_range(const K& key) const { + return equal_range(key, hash_key(key)); + } + + template std::pair equal_range(const K& key, std::size_t hash) const { + const_iterator it = find(key, hash); + return std::make_pair(it, (it == cend()) ? it : std::next(it)); + } + + /* + * Bucket interface + */ + size_type bucket_count() const { + return m_buckets_data.size(); + } + + size_type max_bucket_count() const { + return m_buckets_data.max_size(); + } + + /* + * Hash policy + */ + float load_factor() const { + if (bucket_count() == 0) { + return 0; + } + + return float(size()) / float(bucket_count()); + } + + float max_load_factor() const { + return m_max_load_factor; + } + + void max_load_factor(float ml) { + if (ml < MAX_LOAD_FACTOR__MINIMUM) { + ml = MAX_LOAD_FACTOR__MINIMUM; + } else if (ml > MAX_LOAD_FACTOR__MAXIMUM) { + ml = MAX_LOAD_FACTOR__MAXIMUM; + } + + m_max_load_factor = ml; + m_load_threshold = size_type(float(bucket_count()) * m_max_load_factor); + } + + void rehash(size_type count) { + count = std::max(count, size_type(std::ceil(float(size()) / max_load_factor()))); + rehash_impl(count); + } + + void reserve(size_type count) { + reserve_space_for_values(count); + + count = size_type(std::ceil(float(count) / max_load_factor())); + rehash(count); + } + + /* + * Observers + */ + hasher hash_function() const { + return static_cast(*this); + } + + key_equal key_eq() const { + return static_cast(*this); + } + + /* + * Other + */ + iterator mutable_iterator(const_iterator pos) { + return iterator(m_values.begin() + iterator_to_index(pos)); + } + + iterator nth(size_type index) { + tsl_oh_assert(index <= size()); + return iterator(m_values.begin() + index); + } + + const_iterator nth(size_type index) const { + tsl_oh_assert(index <= size()); + return const_iterator(m_values.cbegin() + index); + } + + const_reference front() const { + tsl_oh_assert(!empty()); + return m_values.front(); + } + + const_reference back() const { + tsl_oh_assert(!empty()); + return m_values.back(); + } + + const values_container_type& values_container() const noexcept { + return m_values; + } + + template ::value>::type* = nullptr> + const typename values_container_type::value_type* data() const noexcept { + return m_values.data(); + } + + template ::value>::type* = nullptr> size_type capacity() const noexcept { + return m_values.capacity(); + } + + void shrink_to_fit() { + m_values.shrink_to_fit(); + } + + template std::pair insert_at_position(const_iterator pos, P&& value) { + return insert_at_position_impl(pos.m_iterator, KeySelect()(value), std::forward

(value)); + } + + template std::pair emplace_at_position(const_iterator pos, Args&&... args) { + return insert_at_position(pos, value_type(std::forward(args)...)); + } + + template std::pair try_emplace_at_position(const_iterator pos, K&& key, Args&&... value_args) { + return insert_at_position_impl(pos.m_iterator, key, std::piecewise_construct, std::forward_as_tuple(std::forward(key)), + std::forward_as_tuple(std::forward(value_args)...)); + } + + void pop_back() { + tsl_oh_assert(!empty()); + erase(std::prev(end())); + } + + /** + * Here to avoid `template size_type unordered_erase(const K& key)` being used when + * we use a iterator instead of a const_iterator. + */ + iterator unordered_erase(iterator pos) { + return unordered_erase(const_iterator(pos)); + } + + iterator unordered_erase(const_iterator pos) { + const std::size_t index_erase = iterator_to_index(pos); + unordered_erase(pos.key()); + + /* + * One element was deleted, index_erase now points to the next element as the elements after + * the deleted value were shifted to the left in m_values (will be end() if we deleted the last element). + */ + return begin() + index_erase; + } + + template size_type unordered_erase(const K& key) { + return unordered_erase(key, hash_key(key)); + } + + template size_type unordered_erase(const K& key, std::size_t hash) { + auto it_bucket_key = find_key(key, hash); + if (it_bucket_key == m_buckets_data.end()) { + return 0; + } + + /** + * If we are not erasing the last element in m_values, we swap + * the element we are erasing with the last element. We then would + * just have to do a pop_back() in m_values. + */ + if (!compare_keys(key, KeySelect()(back()))) { + auto it_bucket_last_elem = find_key(KeySelect()(back()), hash_key(KeySelect()(back()))); + tsl_oh_assert(it_bucket_last_elem != m_buckets_data.end()); + tsl_oh_assert(it_bucket_last_elem->index() == m_values.size() - 1); + + using std::swap; + swap(m_values[it_bucket_key->index()], m_values[it_bucket_last_elem->index()]); + swap(it_bucket_key->index_ref(), it_bucket_last_elem->index_ref()); + } + + erase_value_from_bucket(it_bucket_key); + return 1; } - } - - template - iterator find(const K& key) { - return find(key, hash_key(key)); - } - - template - iterator find(const K& key, std::size_t hash) { - auto it_bucket = find_key(key, hash); - return (it_bucket != m_buckets_data.end())?iterator(m_values.begin() + it_bucket->index()):end(); - } - - template - const_iterator find(const K& key) const { - return find(key, hash_key(key)); - } - - template - const_iterator find(const K& key, std::size_t hash) const { - auto it_bucket = find_key(key, hash); - return (it_bucket != m_buckets_data.cend())?const_iterator(m_values.begin() + it_bucket->index()):end(); - } - - - template - std::pair equal_range(const K& key) { - return equal_range(key, hash_key(key)); - } - - template - std::pair equal_range(const K& key, std::size_t hash) { - iterator it = find(key, hash); - return std::make_pair(it, (it == end())?it:std::next(it)); - } - - template - std::pair equal_range(const K& key) const { - return equal_range(key, hash_key(key)); - } - - template - std::pair equal_range(const K& key, std::size_t hash) const { - const_iterator it = find(key, hash); - return std::make_pair(it, (it == cend())?it:std::next(it)); - } - - - /* - * Bucket interface - */ - size_type bucket_count() const { - return m_buckets_data.size(); - } - - size_type max_bucket_count() const { - return m_buckets_data.max_size(); - } - - /* - * Hash policy - */ - float load_factor() const { - if(bucket_count() == 0) { - return 0; - } - - return float(size())/float(bucket_count()); - } - - float max_load_factor() const { - return m_max_load_factor; - } - - void max_load_factor(float ml) { - if(ml < MAX_LOAD_FACTOR__MINIMUM) { - ml = MAX_LOAD_FACTOR__MINIMUM; - } - else if(ml > MAX_LOAD_FACTOR__MAXIMUM) { - ml = MAX_LOAD_FACTOR__MAXIMUM; + + template void serialize(Serializer& serializer) const { + serialize_impl(serializer); } - m_max_load_factor = ml; - m_load_threshold = size_type(float(bucket_count())*m_max_load_factor); - } - - void rehash(size_type count) { - count = std::max(count, size_type(std::ceil(float(size())/max_load_factor()))); - rehash_impl(count); - } - - void reserve(size_type count) { - reserve_space_for_values(count); - - count = size_type(std::ceil(float(count)/max_load_factor())); - rehash(count); - } - - - /* - * Observers - */ - hasher hash_function() const { - return static_cast(*this); - } - - key_equal key_eq() const { - return static_cast(*this); - } - - - /* - * Other - */ - iterator mutable_iterator(const_iterator pos) { - return iterator(m_values.begin() + iterator_to_index(pos)); - } - - iterator nth(size_type index) { - tsl_oh_assert(index <= size()); - return iterator(m_values.begin() + index); - } - - const_iterator nth(size_type index) const { - tsl_oh_assert(index <= size()); - return const_iterator(m_values.cbegin() + index); - } - - const_reference front() const { - tsl_oh_assert(!empty()); - return m_values.front(); - } - - const_reference back() const { - tsl_oh_assert(!empty()); - return m_values.back(); - } - - const values_container_type& values_container() const noexcept { - return m_values; - } - - template::value>::type* = nullptr> - const typename values_container_type::value_type* data() const noexcept { - return m_values.data(); - } - - template::value>::type* = nullptr> - size_type capacity() const noexcept { - return m_values.capacity(); - } - - void shrink_to_fit() { - m_values.shrink_to_fit(); - } - - - template - std::pair insert_at_position(const_iterator pos, P&& value) { - return insert_at_position_impl(pos.m_iterator, KeySelect()(value), std::forward

(value)); - } - - template - std::pair emplace_at_position(const_iterator pos, Args&&... args) { - return insert_at_position(pos, value_type(std::forward(args)...)); - } - - template - std::pair try_emplace_at_position(const_iterator pos, K&& key, Args&&... value_args) { - return insert_at_position_impl(pos.m_iterator, key, - std::piecewise_construct, - std::forward_as_tuple(std::forward(key)), - std::forward_as_tuple(std::forward(value_args)...)); - } - - - void pop_back() { - tsl_oh_assert(!empty()); - erase(std::prev(end())); - } - - - /** - * Here to avoid `template size_type unordered_erase(const K& key)` being used when - * we use a iterator instead of a const_iterator. - */ - iterator unordered_erase(iterator pos) { - return unordered_erase(const_iterator(pos)); - } - - iterator unordered_erase(const_iterator pos) { - const std::size_t index_erase = iterator_to_index(pos); - unordered_erase(pos.key()); - - /* - * One element was deleted, index_erase now points to the next element as the elements after - * the deleted value were shifted to the left in m_values (will be end() if we deleted the last element). - */ - return begin() + index_erase; - } - - template - size_type unordered_erase(const K& key) { - return unordered_erase(key, hash_key(key)); - } - - template - size_type unordered_erase(const K& key, std::size_t hash) { - auto it_bucket_key = find_key(key, hash); - if(it_bucket_key == m_buckets_data.end()) { - return 0; + template void deserialize(Deserializer& deserializer, bool hash_compatible) { + deserialize_impl(deserializer, hash_compatible); } - + + friend bool operator==(const ordered_hash& lhs, const ordered_hash& rhs) { + return lhs.m_values == rhs.m_values; + } + + friend bool operator!=(const ordered_hash& lhs, const ordered_hash& rhs) { + return lhs.m_values != rhs.m_values; + } + + friend bool operator<(const ordered_hash& lhs, const ordered_hash& rhs) { + return lhs.m_values < rhs.m_values; + } + + friend bool operator<=(const ordered_hash& lhs, const ordered_hash& rhs) { + return lhs.m_values <= rhs.m_values; + } + + friend bool operator>(const ordered_hash& lhs, const ordered_hash& rhs) { + return lhs.m_values > rhs.m_values; + } + + friend bool operator>=(const ordered_hash& lhs, const ordered_hash& rhs) { + return lhs.m_values >= rhs.m_values; + } + + private: + template std::size_t hash_key(const K& key) const { + return Hash::operator()(key); + } + + template bool compare_keys(const K1& key1, const K2& key2) const { + return KeyEqual::operator()(key1, key2); + } + + template typename buckets_container_type::iterator find_key(const K& key, std::size_t hash) { + auto it = static_cast(this)->find_key(key, hash); + return m_buckets_data.begin() + std::distance(m_buckets_data.cbegin(), it); + } + /** - * If we are not erasing the last element in m_values, we swap - * the element we are erasing with the last element. We then would - * just have to do a pop_back() in m_values. + * Return bucket which has the key 'key' or m_buckets_data.end() if none. + * + * From the bucket_for_hash, search for the value until we either find an empty bucket + * or a bucket which has a value with a distance from its ideal bucket longer + * than the probe length for the value we are looking for. */ - if(!compare_keys(key, KeySelect()(back()))) { - auto it_bucket_last_elem = find_key(KeySelect()(back()), hash_key(KeySelect()(back()))); - tsl_oh_assert(it_bucket_last_elem != m_buckets_data.end()); - tsl_oh_assert(it_bucket_last_elem->index() == m_values.size() - 1); - - using std::swap; - swap(m_values[it_bucket_key->index()], m_values[it_bucket_last_elem->index()]); - swap(it_bucket_key->index_ref(), it_bucket_last_elem->index_ref()); - } - - erase_value_from_bucket(it_bucket_key); - - return 1; - } - - template - void serialize(Serializer& serializer) const { - serialize_impl(serializer); - } - - template - void deserialize(Deserializer& deserializer, bool hash_compatible) { - deserialize_impl(deserializer, hash_compatible); - } - - friend bool operator==(const ordered_hash& lhs, const ordered_hash& rhs) { - return lhs.m_values == rhs.m_values; - } - - friend bool operator!=(const ordered_hash& lhs, const ordered_hash& rhs) { - return lhs.m_values != rhs.m_values; - } - - friend bool operator<(const ordered_hash& lhs, const ordered_hash& rhs) { - return lhs.m_values < rhs.m_values; - } - - friend bool operator<=(const ordered_hash& lhs, const ordered_hash& rhs) { - return lhs.m_values <= rhs.m_values; - } - - friend bool operator>(const ordered_hash& lhs, const ordered_hash& rhs) { - return lhs.m_values > rhs.m_values; - } - - friend bool operator>=(const ordered_hash& lhs, const ordered_hash& rhs) { - return lhs.m_values >= rhs.m_values; - } - - -private: - template - std::size_t hash_key(const K& key) const { - return Hash::operator()(key); - } - - template - bool compare_keys(const K1& key1, const K2& key2) const { - return KeyEqual::operator()(key1, key2); - } - - template - typename buckets_container_type::iterator find_key(const K& key, std::size_t hash) { - auto it = static_cast(this)->find_key(key, hash); - return m_buckets_data.begin() + std::distance(m_buckets_data.cbegin(), it); - } - - /** - * Return bucket which has the key 'key' or m_buckets_data.end() if none. - * - * From the bucket_for_hash, search for the value until we either find an empty bucket - * or a bucket which has a value with a distance from its ideal bucket longer - * than the probe length for the value we are looking for. - */ - template - typename buckets_container_type::const_iterator find_key(const K& key, std::size_t hash) const { - for(std::size_t ibucket = bucket_for_hash(hash), dist_from_ideal_bucket = 0; ; - ibucket = next_bucket(ibucket), dist_from_ideal_bucket++) - { - if(m_buckets[ibucket].empty()) { - return m_buckets_data.end(); - } - else if(m_buckets[ibucket].truncated_hash() == bucket_entry::truncate_hash(hash) && - compare_keys(key, KeySelect()(m_values[m_buckets[ibucket].index()]))) - { - return m_buckets_data.begin() + ibucket; - } - else if(dist_from_ideal_bucket > distance_from_ideal_bucket(ibucket)) { - return m_buckets_data.end(); - } - } - } - - void rehash_impl(size_type bucket_count) { - tsl_oh_assert(bucket_count >= size_type(std::ceil(float(size())/max_load_factor()))); - - if(bucket_count > max_bucket_count()) { - TSL_OH_THROW_OR_TERMINATE(std::length_error, "The map exceeds its maxmimum size."); - } - - if(bucket_count > 0) { - bucket_count = round_up_to_power_of_two(bucket_count); - } - - if(bucket_count == this->bucket_count()) { - return; - } - - - buckets_container_type old_buckets(bucket_count); - m_buckets_data.swap(old_buckets); - m_buckets = m_buckets_data.empty()?static_empty_bucket_ptr(): - m_buckets_data.data(); - // Everything should be noexcept from here. - - m_mask = (bucket_count > 0)?(bucket_count - 1):0; - this->max_load_factor(m_max_load_factor); - m_grow_on_next_insert = false; - - - - for(const bucket_entry& old_bucket: old_buckets) { - if(old_bucket.empty()) { - continue; - } - - truncated_hash_type insert_hash = old_bucket.truncated_hash(); - index_type insert_index = old_bucket.index(); - - for(std::size_t ibucket = bucket_for_hash(insert_hash), dist_from_ideal_bucket = 0; ; - ibucket = next_bucket(ibucket), dist_from_ideal_bucket++) - { - if(m_buckets[ibucket].empty()) { - m_buckets[ibucket].set_index(insert_index); - m_buckets[ibucket].set_hash(insert_hash); - break; + template typename buckets_container_type::const_iterator find_key(const K& key, std::size_t hash) const { + for (std::size_t ibucket = bucket_for_hash(hash), dist_from_ideal_bucket = 0;; ibucket = next_bucket(ibucket), dist_from_ideal_bucket++) { + if (m_buckets[ibucket].empty()) { + return m_buckets_data.end(); + } else if (m_buckets[ibucket].truncated_hash() == bucket_entry::truncate_hash(hash) + && compare_keys(key, KeySelect()(m_values[m_buckets[ibucket].index()]))) { + return m_buckets_data.begin() + ibucket; + } else if (dist_from_ideal_bucket > distance_from_ideal_bucket(ibucket)) { + return m_buckets_data.end(); } - + } + } + + void rehash_impl(size_type bucket_count) { + tsl_oh_assert(bucket_count >= size_type(std::ceil(float(size()) / max_load_factor()))); + + if (bucket_count > max_bucket_count()) { + TSL_OH_THROW_OR_TERMINATE(std::length_error, "The map exceeds its maxmimum size."); + } + + if (bucket_count > 0) { + bucket_count = round_up_to_power_of_two(bucket_count); + } + + if (bucket_count == this->bucket_count()) { + return; + } + + buckets_container_type old_buckets(bucket_count); + m_buckets_data.swap(old_buckets); + m_buckets = m_buckets_data.empty() ? static_empty_bucket_ptr() : m_buckets_data.data(); + // Everything should be noexcept from here. + + m_mask = (bucket_count > 0) ? (bucket_count - 1) : 0; + this->max_load_factor(m_max_load_factor); + m_grow_on_next_insert = false; + + for (const bucket_entry& old_bucket : old_buckets) { + if (old_bucket.empty()) { + continue; + } + + truncated_hash_type insert_hash = old_bucket.truncated_hash(); + index_type insert_index = old_bucket.index(); + + for (std::size_t ibucket = bucket_for_hash(insert_hash), dist_from_ideal_bucket = 0;; + ibucket = next_bucket(ibucket), dist_from_ideal_bucket++) { + if (m_buckets[ibucket].empty()) { + m_buckets[ibucket].set_index(insert_index); + m_buckets[ibucket].set_hash(insert_hash); + break; + } + + const std::size_t distance = distance_from_ideal_bucket(ibucket); + if (dist_from_ideal_bucket > distance) { + std::swap(insert_index, m_buckets[ibucket].index_ref()); + std::swap(insert_hash, m_buckets[ibucket].truncated_hash_ref()); + dist_from_ideal_bucket = distance; + } + } + } + } + + template ::value>::type* = nullptr> + void reserve_space_for_values(size_type count) { + m_values.reserve(count); + } + + template ::value>::type* = nullptr> + void reserve_space_for_values(size_type /*count*/) { + } + + /** + * Swap the empty bucket with the values on its right until we cross another empty bucket + * or if the other bucket has a distance_from_ideal_bucket == 0. + */ + void backward_shift(std::size_t empty_ibucket) noexcept { + tsl_oh_assert(m_buckets[empty_ibucket].empty()); + + std::size_t previous_ibucket = empty_ibucket; + for (std::size_t current_ibucket = next_bucket(previous_ibucket); + !m_buckets[current_ibucket].empty() && distance_from_ideal_bucket(current_ibucket) > 0; + previous_ibucket = current_ibucket, current_ibucket = next_bucket(current_ibucket)) { + std::swap(m_buckets[current_ibucket], m_buckets[previous_ibucket]); + } + } + + void erase_value_from_bucket(typename buckets_container_type::iterator it_bucket) { + tsl_oh_assert(it_bucket != m_buckets_data.end() && !it_bucket->empty()); + + m_values.erase(m_values.begin() + it_bucket->index()); + + /* + * m_values.erase shifted all the values on the right of the erased value, + * shift the indexes by -1 in the buckets array for these values. + */ + if (it_bucket->index() != m_values.size()) { + shift_indexes_in_buckets(it_bucket->index(), -1); + } + + // Mark the bucket as empty and do a backward shift of the values on the right + it_bucket->clear(); + backward_shift(std::size_t(std::distance(m_buckets_data.begin(), it_bucket))); + } + + /** + * Go through each value from [from_ivalue, m_values.size()) in m_values and for each + * bucket corresponding to the value, shift the index by delta. + * + * delta must be equal to 1 or -1. + */ + void shift_indexes_in_buckets(index_type from_ivalue, int delta) noexcept { + tsl_oh_assert(delta == 1 || delta == -1); + + for (std::size_t ivalue = from_ivalue; ivalue < m_values.size(); ivalue++) { + // All the values in m_values have been shifted by delta. Find the bucket corresponding + // to the value m_values[ivalue] + const index_type old_index = static_cast(ivalue - delta); + + std::size_t ibucket = bucket_for_hash(hash_key(KeySelect()(m_values[ivalue]))); + while (m_buckets[ibucket].index() != old_index) { + ibucket = next_bucket(ibucket); + } + + m_buckets[ibucket].set_index(index_type(ivalue)); + } + } + + template size_type erase_impl(const K& key, std::size_t hash) { + auto it_bucket = find_key(key, hash); + if (it_bucket != m_buckets_data.end()) { + erase_value_from_bucket(it_bucket); + + return 1; + } else { + return 0; + } + } + + /** + * Insert the element at the end. + */ + template std::pair insert_impl(const K& key, Args&&... value_type_args) { + const std::size_t hash = hash_key(key); + + std::size_t ibucket = bucket_for_hash(hash); + std::size_t dist_from_ideal_bucket = 0; + + while (!m_buckets[ibucket].empty() && dist_from_ideal_bucket <= distance_from_ideal_bucket(ibucket)) { + if (m_buckets[ibucket].truncated_hash() == bucket_entry::truncate_hash(hash) + && compare_keys(key, KeySelect()(m_values[m_buckets[ibucket].index()]))) { + return std::make_pair(begin() + m_buckets[ibucket].index(), false); + } + + ibucket = next_bucket(ibucket); + dist_from_ideal_bucket++; + } + + if (size() >= max_size()) { + TSL_OH_THROW_OR_TERMINATE(std::length_error, "We reached the maximum size for the hash table."); + } + + if (grow_on_high_load()) { + ibucket = bucket_for_hash(hash); + dist_from_ideal_bucket = 0; + } + + m_values.emplace_back(std::forward(value_type_args)...); + insert_index(ibucket, dist_from_ideal_bucket, index_type(m_values.size() - 1), bucket_entry::truncate_hash(hash)); + + return std::make_pair(std::prev(end()), true); + } + + /** + * Insert the element before insert_position. + */ + template + std::pair insert_at_position_impl( + typename values_container_type::const_iterator insert_position, const K& key, Args&&... value_type_args) { + const std::size_t hash = hash_key(key); + + std::size_t ibucket = bucket_for_hash(hash); + std::size_t dist_from_ideal_bucket = 0; + + while (!m_buckets[ibucket].empty() && dist_from_ideal_bucket <= distance_from_ideal_bucket(ibucket)) { + if (m_buckets[ibucket].truncated_hash() == bucket_entry::truncate_hash(hash) + && compare_keys(key, KeySelect()(m_values[m_buckets[ibucket].index()]))) { + return std::make_pair(begin() + m_buckets[ibucket].index(), false); + } + + ibucket = next_bucket(ibucket); + dist_from_ideal_bucket++; + } + + if (size() >= max_size()) { + TSL_OH_THROW_OR_TERMINATE(std::length_error, "We reached the maximum size for the hash table."); + } + + if (grow_on_high_load()) { + ibucket = bucket_for_hash(hash); + dist_from_ideal_bucket = 0; + } + + const index_type index_insert_position = index_type(std::distance(m_values.cbegin(), insert_position)); + +#ifdef TSL_OH_NO_CONTAINER_EMPLACE_CONST_ITERATOR + m_values.emplace(m_values.begin() + std::distance(m_values.cbegin(), insert_position), std::forward(value_type_args)...); +#else + m_values.emplace(insert_position, std::forward(value_type_args)...); +#endif + + insert_index(ibucket, dist_from_ideal_bucket, index_insert_position, bucket_entry::truncate_hash(hash)); + + /* + * The insertion didn't happend at the end of the m_values container, + * we need to shift the indexes in m_buckets_data. + */ + if (index_insert_position != m_values.size() - 1) { + shift_indexes_in_buckets(index_insert_position + 1, 1); + } + + return std::make_pair(iterator(m_values.begin() + index_insert_position), true); + } + + void insert_index(std::size_t ibucket, std::size_t dist_from_ideal_bucket, index_type index_insert, truncated_hash_type hash_insert) noexcept { + while (!m_buckets[ibucket].empty()) { const std::size_t distance = distance_from_ideal_bucket(ibucket); - if(dist_from_ideal_bucket > distance) { - std::swap(insert_index, m_buckets[ibucket].index_ref()); - std::swap(insert_hash, m_buckets[ibucket].truncated_hash_ref()); + if (dist_from_ideal_bucket > distance) { + std::swap(index_insert, m_buckets[ibucket].index_ref()); + std::swap(hash_insert, m_buckets[ibucket].truncated_hash_ref()); + dist_from_ideal_bucket = distance; } - } - } - } - - template::value>::type* = nullptr> - void reserve_space_for_values(size_type count) { - m_values.reserve(count); - } - - template::value>::type* = nullptr> - void reserve_space_for_values(size_type /*count*/) { - } - - /** - * Swap the empty bucket with the values on its right until we cross another empty bucket - * or if the other bucket has a distance_from_ideal_bucket == 0. - */ - void backward_shift(std::size_t empty_ibucket) noexcept { - tsl_oh_assert(m_buckets[empty_ibucket].empty()); - - std::size_t previous_ibucket = empty_ibucket; - for(std::size_t current_ibucket = next_bucket(previous_ibucket); - !m_buckets[current_ibucket].empty() && distance_from_ideal_bucket(current_ibucket) > 0; - previous_ibucket = current_ibucket, current_ibucket = next_bucket(current_ibucket)) - { - std::swap(m_buckets[current_ibucket], m_buckets[previous_ibucket]); - } - } - - void erase_value_from_bucket(typename buckets_container_type::iterator it_bucket) { - tsl_oh_assert(it_bucket != m_buckets_data.end() && !it_bucket->empty()); - - m_values.erase(m_values.begin() + it_bucket->index()); - - /* - * m_values.erase shifted all the values on the right of the erased value, - * shift the indexes by -1 in the buckets array for these values. - */ - if(it_bucket->index() != m_values.size()) { - shift_indexes_in_buckets(it_bucket->index(), -1); - } - - // Mark the bucket as empty and do a backward shift of the values on the right - it_bucket->clear(); - backward_shift(std::size_t(std::distance(m_buckets_data.begin(), it_bucket))); - } - - /** - * Go through each value from [from_ivalue, m_values.size()) in m_values and for each - * bucket corresponding to the value, shift the index by delta. - * - * delta must be equal to 1 or -1. - */ - void shift_indexes_in_buckets(index_type from_ivalue, int delta) noexcept { - tsl_oh_assert(delta == 1 || delta == -1); - - for(std::size_t ivalue = from_ivalue; ivalue < m_values.size(); ivalue++) { - // All the values in m_values have been shifted by delta. Find the bucket corresponding - // to the value m_values[ivalue] - const index_type old_index = static_cast(ivalue - delta); - - std::size_t ibucket = bucket_for_hash(hash_key(KeySelect()(m_values[ivalue]))); - while(m_buckets[ibucket].index() != old_index) { + ibucket = next_bucket(ibucket); - } - - m_buckets[ibucket].set_index(index_type(ivalue)); - } - } - - template - size_type erase_impl(const K& key, std::size_t hash) { - auto it_bucket = find_key(key, hash); - if(it_bucket != m_buckets_data.end()) { - erase_value_from_bucket(it_bucket); - - return 1; - } - else { - return 0; - } - } - - /** - * Insert the element at the end. - */ - template - std::pair insert_impl(const K& key, Args&&... value_type_args) { - const std::size_t hash = hash_key(key); - - std::size_t ibucket = bucket_for_hash(hash); - std::size_t dist_from_ideal_bucket = 0; - - while(!m_buckets[ibucket].empty() && dist_from_ideal_bucket <= distance_from_ideal_bucket(ibucket)) { - if(m_buckets[ibucket].truncated_hash() == bucket_entry::truncate_hash(hash) && - compare_keys(key, KeySelect()(m_values[m_buckets[ibucket].index()]))) - { - return std::make_pair(begin() + m_buckets[ibucket].index(), false); - } - - ibucket = next_bucket(ibucket); - dist_from_ideal_bucket++; - } - - if(size() >= max_size()) { - TSL_OH_THROW_OR_TERMINATE(std::length_error, "We reached the maximum size for the hash table."); - } - - - if(grow_on_high_load()) { - ibucket = bucket_for_hash(hash); - dist_from_ideal_bucket = 0; - } - - - m_values.emplace_back(std::forward(value_type_args)...); - insert_index(ibucket, dist_from_ideal_bucket, - index_type(m_values.size() - 1), bucket_entry::truncate_hash(hash)); - - - return std::make_pair(std::prev(end()), true); - } - - /** - * Insert the element before insert_position. - */ - template - std::pair insert_at_position_impl(typename values_container_type::const_iterator insert_position, - const K& key, Args&&... value_type_args) - { - const std::size_t hash = hash_key(key); - - std::size_t ibucket = bucket_for_hash(hash); - std::size_t dist_from_ideal_bucket = 0; - - while(!m_buckets[ibucket].empty() && dist_from_ideal_bucket <= distance_from_ideal_bucket(ibucket)) { - if(m_buckets[ibucket].truncated_hash() == bucket_entry::truncate_hash(hash) && - compare_keys(key, KeySelect()(m_values[m_buckets[ibucket].index()]))) - { - return std::make_pair(begin() + m_buckets[ibucket].index(), false); - } - - ibucket = next_bucket(ibucket); - dist_from_ideal_bucket++; - } - - if(size() >= max_size()) { - TSL_OH_THROW_OR_TERMINATE(std::length_error, "We reached the maximum size for the hash table."); - } - - - if(grow_on_high_load()) { - ibucket = bucket_for_hash(hash); - dist_from_ideal_bucket = 0; - } - - - const index_type index_insert_position = index_type(std::distance(m_values.cbegin(), insert_position)); - -#ifdef TSL_OH_NO_CONTAINER_EMPLACE_CONST_ITERATOR - m_values.emplace(m_values.begin() + std::distance(m_values.cbegin(), insert_position), std::forward(value_type_args)...); -#else - m_values.emplace(insert_position, std::forward(value_type_args)...); -#endif + dist_from_ideal_bucket++; - insert_index(ibucket, dist_from_ideal_bucket, - index_insert_position, bucket_entry::truncate_hash(hash)); - - /* - * The insertion didn't happend at the end of the m_values container, - * we need to shift the indexes in m_buckets_data. + if (dist_from_ideal_bucket > REHASH_ON_HIGH_NB_PROBES__NPROBES && !m_grow_on_next_insert + && load_factor() >= REHASH_ON_HIGH_NB_PROBES__MIN_LOAD_FACTOR) { + // We don't want to grow the map now as we need this method to be noexcept. + // Do it on next insert. + m_grow_on_next_insert = true; + } + } + + m_buckets[ibucket].set_index(index_insert); + m_buckets[ibucket].set_hash(hash_insert); + } + + std::size_t distance_from_ideal_bucket(std::size_t ibucket) const noexcept { + const std::size_t ideal_bucket = bucket_for_hash(m_buckets[ibucket].truncated_hash()); + + if (ibucket >= ideal_bucket) { + return ibucket - ideal_bucket; + } + // If the bucket is smaller than the ideal bucket for the value, there was a wrapping at the end of the + // bucket array due to the modulo. + else { + return (bucket_count() + ibucket) - ideal_bucket; + } + } + + std::size_t next_bucket(std::size_t index) const noexcept { + tsl_oh_assert(index < m_buckets_data.size()); + + index++; + return (index < m_buckets_data.size()) ? index : 0; + } + + std::size_t bucket_for_hash(std::size_t hash) const noexcept { + return hash & m_mask; + } + + std::size_t iterator_to_index(const_iterator it) const noexcept { + const auto dist = std::distance(cbegin(), it); + tsl_oh_assert(dist >= 0); + + return std::size_t(dist); + } + + /** + * Return true if the map has been rehashed. */ - if(index_insert_position != m_values.size() - 1) { - shift_indexes_in_buckets(index_insert_position + 1, 1); - } - - return std::make_pair(iterator(m_values.begin() + index_insert_position), true); - } - - void insert_index(std::size_t ibucket, std::size_t dist_from_ideal_bucket, - index_type index_insert, truncated_hash_type hash_insert) noexcept - { - while(!m_buckets[ibucket].empty()) { - const std::size_t distance = distance_from_ideal_bucket(ibucket); - if(dist_from_ideal_bucket > distance) { - std::swap(index_insert, m_buckets[ibucket].index_ref()); - std::swap(hash_insert, m_buckets[ibucket].truncated_hash_ref()); - - dist_from_ideal_bucket = distance; - } + bool grow_on_high_load() { + if (m_grow_on_next_insert || size() >= m_load_threshold) { + rehash_impl(std::max(size_type(1), bucket_count() * 2)); + m_grow_on_next_insert = false; - - ibucket = next_bucket(ibucket); - dist_from_ideal_bucket++; - - - if(dist_from_ideal_bucket > REHASH_ON_HIGH_NB_PROBES__NPROBES && !m_grow_on_next_insert && - load_factor() >= REHASH_ON_HIGH_NB_PROBES__MIN_LOAD_FACTOR) - { - // We don't want to grow the map now as we need this method to be noexcept. - // Do it on next insert. - m_grow_on_next_insert = true; + return true; + } else { + return false; } } - - - m_buckets[ibucket].set_index(index_insert); - m_buckets[ibucket].set_hash(hash_insert); - } - - std::size_t distance_from_ideal_bucket(std::size_t ibucket) const noexcept { - const std::size_t ideal_bucket = bucket_for_hash(m_buckets[ibucket].truncated_hash()); - - if(ibucket >= ideal_bucket) { - return ibucket - ideal_bucket; - } - // If the bucket is smaller than the ideal bucket for the value, there was a wrapping at the end of the - // bucket array due to the modulo. - else { - return (bucket_count() + ibucket) - ideal_bucket; - } - } - - std::size_t next_bucket(std::size_t index) const noexcept { - tsl_oh_assert(index < m_buckets_data.size()); - - index++; - return (index < m_buckets_data.size())?index:0; - } - - std::size_t bucket_for_hash(std::size_t hash) const noexcept { - return hash & m_mask; - } - - std::size_t iterator_to_index(const_iterator it) const noexcept { - const auto dist = std::distance(cbegin(), it); - tsl_oh_assert(dist >= 0); - - return std::size_t(dist); - } - - /** - * Return true if the map has been rehashed. - */ - bool grow_on_high_load() { - if(m_grow_on_next_insert || size() >= m_load_threshold) { - rehash_impl(std::max(size_type(1), bucket_count() * 2)); - m_grow_on_next_insert = false; - - return true; - } - else { - return false; - } - } - - template - void serialize_impl(Serializer& serializer) const { - const slz_size_type version = SERIALIZATION_PROTOCOL_VERSION; - serializer(version); - - const slz_size_type nb_elements = m_values.size(); - serializer(nb_elements); - - const slz_size_type bucket_count = m_buckets_data.size(); - serializer(bucket_count); - - const float max_load_factor = m_max_load_factor; - serializer(max_load_factor); - - - for(const value_type& value: m_values) { - serializer(value); - } - - for(const bucket_entry& bucket: m_buckets_data) { - bucket.serialize(serializer); - } - } - - template - void deserialize_impl(Deserializer& deserializer, bool hash_compatible) { - tsl_oh_assert(m_buckets_data.empty()); // Current hash table must be empty - - const slz_size_type version = deserialize_value(deserializer); - // For now we only have one version of the serialization protocol. - // If it doesn't match there is a problem with the file. - if(version != SERIALIZATION_PROTOCOL_VERSION) { - TSL_OH_THROW_OR_TERMINATE(std::runtime_error, "Can't deserialize the ordered_map/set. " - "The protocol version header is invalid."); - } - - const slz_size_type nb_elements = deserialize_value(deserializer); - const slz_size_type bucket_count_ds = deserialize_value(deserializer); - const float max_load_factor = deserialize_value(deserializer); - if(max_load_factor < MAX_LOAD_FACTOR__MINIMUM || max_load_factor > MAX_LOAD_FACTOR__MAXIMUM) { - TSL_OH_THROW_OR_TERMINATE(std::runtime_error, "Invalid max_load_factor. Check that the serializer " - "and deserializer supports floats correctly as they " - "can be converted implicitly to ints."); - } - - - this->max_load_factor(max_load_factor); - - if(bucket_count_ds == 0) { - tsl_oh_assert(nb_elements == 0); - return; - } - - - if(!hash_compatible) { - reserve(numeric_cast(nb_elements, "Deserialized nb_elements is too big.")); - for(slz_size_type el = 0; el < nb_elements; el++) { - insert(deserialize_value(deserializer)); + template void serialize_impl(Serializer& serializer) const { + const slz_size_type version = SERIALIZATION_PROTOCOL_VERSION; + serializer(version); + + const slz_size_type nb_elements = m_values.size(); + serializer(nb_elements); + + const slz_size_type bucket_count = m_buckets_data.size(); + serializer(bucket_count); + + const float max_load_factor = m_max_load_factor; + serializer(max_load_factor); + + for (const value_type& value : m_values) { + serializer(value); + } + + for (const bucket_entry& bucket : m_buckets_data) { + bucket.serialize(serializer); } } - else { - m_buckets_data.reserve(numeric_cast(bucket_count_ds, "Deserialized bucket_count is too big.")); - m_buckets = m_buckets_data.data(), - m_mask = m_buckets_data.capacity() - 1; - - reserve_space_for_values(numeric_cast(nb_elements, "Deserialized nb_elements is too big.")); - for(slz_size_type el = 0; el < nb_elements; el++) { - m_values.push_back(deserialize_value(deserializer)); + + template void deserialize_impl(Deserializer& deserializer, bool hash_compatible) { + tsl_oh_assert(m_buckets_data.empty()); // Current hash table must be empty + + const slz_size_type version = deserialize_value(deserializer); + // For now we only have one version of the serialization protocol. + // If it doesn't match there is a problem with the file. + if (version != SERIALIZATION_PROTOCOL_VERSION) { + TSL_OH_THROW_OR_TERMINATE(std::runtime_error, "Can't deserialize the ordered_map/set. " + "The protocol version header is invalid."); } - - for(slz_size_type b = 0; b < bucket_count_ds; b++) { - m_buckets_data.push_back(bucket_entry::deserialize(deserializer)); + + const slz_size_type nb_elements = deserialize_value(deserializer); + const slz_size_type bucket_count_ds = deserialize_value(deserializer); + const float max_load_factor = deserialize_value(deserializer); + + if (max_load_factor < MAX_LOAD_FACTOR__MINIMUM || max_load_factor > MAX_LOAD_FACTOR__MAXIMUM) { + TSL_OH_THROW_OR_TERMINATE(std::runtime_error, "Invalid max_load_factor. Check that the serializer " + "and deserializer supports floats correctly as they " + "can be converted implicitly to ints."); + } + + this->max_load_factor(max_load_factor); + + if (bucket_count_ds == 0) { + tsl_oh_assert(nb_elements == 0); + return; + } + + if (!hash_compatible) { + reserve(numeric_cast(nb_elements, "Deserialized nb_elements is too big.")); + for (slz_size_type el = 0; el < nb_elements; el++) { + insert(deserialize_value(deserializer)); + } + } else { + m_buckets_data.reserve(numeric_cast(bucket_count_ds, "Deserialized bucket_count is too big.")); + m_buckets = m_buckets_data.data(), m_mask = m_buckets_data.capacity() - 1; + + reserve_space_for_values(numeric_cast(nb_elements, "Deserialized nb_elements is too big.")); + for (slz_size_type el = 0; el < nb_elements; el++) { + m_values.push_back(deserialize_value(deserializer)); + } + + for (slz_size_type b = 0; b < bucket_count_ds; b++) { + m_buckets_data.push_back(bucket_entry::deserialize(deserializer)); + } } } - } - - static std::size_t round_up_to_power_of_two(std::size_t value) { - if(is_power_of_two(value)) { - return value; + + static std::size_t round_up_to_power_of_two(std::size_t value) { + if (is_power_of_two(value)) { + return value; + } + + if (value == 0) { + return 1; + } + + --value; + for (std::size_t i = 1; i < sizeof(std::size_t) * CHAR_BIT; i *= 2) { + value |= value >> i; + } + + return value + 1; } - - if(value == 0) { - return 1; + + static constexpr bool is_power_of_two(std::size_t value) { + return value != 0 && (value & (value - 1)) == 0; } - - --value; - for(std::size_t i = 1; i < sizeof(std::size_t) * CHAR_BIT; i *= 2) { - value |= value >> i; + + public: + static const size_type DEFAULT_INIT_BUCKETS_SIZE = 0; + static constexpr float DEFAULT_MAX_LOAD_FACTOR = 0.75f; + + private: + static constexpr float MAX_LOAD_FACTOR__MINIMUM = 0.1f; + static constexpr float MAX_LOAD_FACTOR__MAXIMUM = 0.95f; + + static const size_type REHASH_ON_HIGH_NB_PROBES__NPROBES = 128; + static constexpr float REHASH_ON_HIGH_NB_PROBES__MIN_LOAD_FACTOR = 0.15f; + + /** + * Protocol version currenlty used for serialization. + */ + static const slz_size_type SERIALIZATION_PROTOCOL_VERSION = 1; + + /** + * Return an always valid pointer to an static empty bucket_entry with last_bucket() == true. + */ + bucket_entry* static_empty_bucket_ptr() { + static bucket_entry empty_bucket; + return &empty_bucket; } - - return value + 1; - } - - static constexpr bool is_power_of_two(std::size_t value) { - return value != 0 && (value & (value - 1)) == 0; - } - -public: - static const size_type DEFAULT_INIT_BUCKETS_SIZE = 0; - static constexpr float DEFAULT_MAX_LOAD_FACTOR = 0.75f; + private: + buckets_container_type m_buckets_data; -private: - static constexpr float MAX_LOAD_FACTOR__MINIMUM = 0.1f; - static constexpr float MAX_LOAD_FACTOR__MAXIMUM = 0.95f; + /** + * Points to m_buckets_data.data() if !m_buckets_data.empty() otherwise points to static_empty_bucket_ptr. + * This variable is useful to avoid the cost of checking if m_buckets_data is empty when trying + * to find an element. + * + * TODO Remove m_buckets_data and only use a pointer+size instead of a pointer+vector to save some space in the ordered_hash object. + */ + bucket_entry* m_buckets; - static const size_type REHASH_ON_HIGH_NB_PROBES__NPROBES = 128; - static constexpr float REHASH_ON_HIGH_NB_PROBES__MIN_LOAD_FACTOR = 0.15f; - - /** - * Protocol version currenlty used for serialization. - */ - static const slz_size_type SERIALIZATION_PROTOCOL_VERSION = 1; - - /** - * Return an always valid pointer to an static empty bucket_entry with last_bucket() == true. - */ - bucket_entry* static_empty_bucket_ptr() { - static bucket_entry empty_bucket; - return &empty_bucket; - } - -private: - buckets_container_type m_buckets_data; - - /** - * Points to m_buckets_data.data() if !m_buckets_data.empty() otherwise points to static_empty_bucket_ptr. - * This variable is useful to avoid the cost of checking if m_buckets_data is empty when trying - * to find an element. - * - * TODO Remove m_buckets_data and only use a pointer+size instead of a pointer+vector to save some space in the ordered_hash object. - */ - bucket_entry* m_buckets; - - size_type m_mask; - - values_container_type m_values; - - bool m_grow_on_next_insert; - float m_max_load_factor; - size_type m_load_threshold; -}; + size_type m_mask; + values_container_type m_values; + + bool m_grow_on_next_insert; + float m_max_load_factor; + size_type m_load_threshold; + }; } // end namespace detail_ordered_hash - - /** * Implementation of an hash map using open adressing with robin hood with backshift delete to resolve collisions. - * + * * The particularity of this hash map is that it remembers the order in which the elements were added and - * provide a way to access the structure which stores these values through the 'values_container()' method. + * provide a way to access the structure which stores these values through the 'values_container()' method. * The used container is defined by ValueTypeContainer, by default a std::deque is used (grows faster) but - * a std::vector may be used. In this case the map provides a 'data()' method which give a direct access + * a std::vector may be used. In this case the map provides a 'data()' method which give a direct access * to the memory used to store the values (which can be usefull to communicate with C API's). - * + * * The Key and T must be copy constructible and/or move constructible. To use `unordered_erase` they both * must be swappable. - * + * * The behaviour of the hash map is undefinded if the destructor of Key or T throws an exception. - * + * * By default the maximum size of a map is limited to 2^32 - 1 values, if needed this can be changed through * the IndexType template parameter. Using an `uint64_t` will raise this limit to 2^64 - 1 values but each * bucket will use 16 bytes instead of 8 bytes in addition to the space needed to store the values. - * + * * Iterators invalidation: * - clear, operator=, reserve, rehash: always invalidate the iterators (also invalidate end()). - * - insert, emplace, emplace_hint, operator[]: when a std::vector is used as ValueTypeContainer - * and if size() < capacity(), only end(). + * - insert, emplace, emplace_hint, operator[]: when a std::vector is used as ValueTypeContainer + * and if size() < capacity(), only end(). * Otherwise all the iterators are invalidated if an insert occurs. - * - erase, unordered_erase: when a std::vector is used as ValueTypeContainer invalidate the iterator of - * the erased element and all the ones after the erased element (including end()). + * - erase, unordered_erase: when a std::vector is used as ValueTypeContainer invalidate the iterator of + * the erased element and all the ones after the erased element (including end()). * Otherwise all the iterators are invalidated if an erase occurs. */ -template, - class KeyEqual = std::equal_to, - class Allocator = std::allocator>, - class ValueTypeContainer = std::deque, Allocator>, - class IndexType = std::uint_least32_t> +template , class KeyEqual = std::equal_to, class Allocator = std::allocator>, + class ValueTypeContainer = std::deque, Allocator>, class IndexType = std::uint_least32_t> class ordered_map { private: - template - using has_is_transparent = tsl::detail_ordered_hash::has_is_transparent; - + template using has_is_transparent = tsl::detail_ordered_hash::has_is_transparent; + class KeySelect { public: using key_type = Key; - + const key_type& operator()(const std::pair& key_value) const noexcept { return key_value.first; } - + key_type& operator()(std::pair& key_value) noexcept { return key_value.first; } - }; - + }; + class ValueSelect { public: using value_type = T; - + const value_type& operator()(const std::pair& key_value) const noexcept { return key_value.second; } - + value_type& operator()(std::pair& key_value) noexcept { return key_value.second; } }; - - using ht = detail_ordered_hash::ordered_hash, KeySelect, ValueSelect, - Hash, KeyEqual, Allocator, ValueTypeContainer, IndexType>; - + + using ht = detail_ordered_hash::ordered_hash, KeySelect, ValueSelect, Hash, KeyEqual, Allocator, ValueTypeContainer, IndexType>; + public: using key_type = typename ht::key_type; using mapped_type = T; @@ -1699,704 +1558,770 @@ public: using const_iterator = typename ht::const_iterator; using reverse_iterator = typename ht::reverse_iterator; using const_reverse_iterator = typename ht::const_reverse_iterator; - + using values_container_type = typename ht::values_container_type; - - + /* * Constructors */ - ordered_map(): ordered_map(ht::DEFAULT_INIT_BUCKETS_SIZE) { + ordered_map() : ordered_map(ht::DEFAULT_INIT_BUCKETS_SIZE) { } - - explicit ordered_map(size_type bucket_count, - const Hash& hash = Hash(), - const KeyEqual& equal = KeyEqual(), - const Allocator& alloc = Allocator()): - m_ht(bucket_count, hash, equal, alloc, ht::DEFAULT_MAX_LOAD_FACTOR) - { + + explicit ordered_map(size_type bucket_count, const Hash& hash = Hash(), const KeyEqual& equal = KeyEqual(), const Allocator& alloc = Allocator()) + : m_ht(bucket_count, hash, equal, alloc, ht::DEFAULT_MAX_LOAD_FACTOR) { } - - ordered_map(size_type bucket_count, - const Allocator& alloc): ordered_map(bucket_count, Hash(), KeyEqual(), alloc) - { + + ordered_map(size_type bucket_count, const Allocator& alloc) : ordered_map(bucket_count, Hash(), KeyEqual(), alloc) { } - - ordered_map(size_type bucket_count, - const Hash& hash, - const Allocator& alloc): ordered_map(bucket_count, hash, KeyEqual(), alloc) - { + + ordered_map(size_type bucket_count, const Hash& hash, const Allocator& alloc) : ordered_map(bucket_count, hash, KeyEqual(), alloc) { } - - explicit ordered_map(const Allocator& alloc): ordered_map(ht::DEFAULT_INIT_BUCKETS_SIZE, alloc) { + + explicit ordered_map(const Allocator& alloc) : ordered_map(ht::DEFAULT_INIT_BUCKETS_SIZE, alloc) { } - - template - ordered_map(InputIt first, InputIt last, - size_type bucket_count = ht::DEFAULT_INIT_BUCKETS_SIZE, - const Hash& hash = Hash(), - const KeyEqual& equal = KeyEqual(), - const Allocator& alloc = Allocator()): ordered_map(bucket_count, hash, equal, alloc) - { + + template + ordered_map(InputIt first, InputIt last, size_type bucket_count = ht::DEFAULT_INIT_BUCKETS_SIZE, const Hash& hash = Hash(), + const KeyEqual& equal = KeyEqual(), const Allocator& alloc = Allocator()) + : ordered_map(bucket_count, hash, equal, alloc) { insert(first, last); } - - template - ordered_map(InputIt first, InputIt last, - size_type bucket_count, - const Allocator& alloc): ordered_map(first, last, bucket_count, Hash(), KeyEqual(), alloc) - { - } - - template - ordered_map(InputIt first, InputIt last, - size_type bucket_count, - const Hash& hash, - const Allocator& alloc): ordered_map(first, last, bucket_count, hash, KeyEqual(), alloc) - { + + template + ordered_map(InputIt first, InputIt last, size_type bucket_count, const Allocator& alloc) + : ordered_map(first, last, bucket_count, Hash(), KeyEqual(), alloc) { } - ordered_map(std::initializer_list init, - size_type bucket_count = ht::DEFAULT_INIT_BUCKETS_SIZE, - const Hash& hash = Hash(), - const KeyEqual& equal = KeyEqual(), - const Allocator& alloc = Allocator()): - ordered_map(init.begin(), init.end(), bucket_count, hash, equal, alloc) - { + template + ordered_map(InputIt first, InputIt last, size_type bucket_count, const Hash& hash, const Allocator& alloc) + : ordered_map(first, last, bucket_count, hash, KeyEqual(), alloc) { } - ordered_map(std::initializer_list init, - size_type bucket_count, - const Allocator& alloc): - ordered_map(init.begin(), init.end(), bucket_count, Hash(), KeyEqual(), alloc) - { + ordered_map(std::initializer_list init, size_type bucket_count = ht::DEFAULT_INIT_BUCKETS_SIZE, const Hash& hash = Hash(), + const KeyEqual& equal = KeyEqual(), const Allocator& alloc = Allocator()) + : ordered_map(init.begin(), init.end(), bucket_count, hash, equal, alloc) { } - ordered_map(std::initializer_list init, - size_type bucket_count, - const Hash& hash, - const Allocator& alloc): - ordered_map(init.begin(), init.end(), bucket_count, hash, KeyEqual(), alloc) - { + ordered_map(std::initializer_list init, size_type bucket_count, const Allocator& alloc) + : ordered_map(init.begin(), init.end(), bucket_count, Hash(), KeyEqual(), alloc) { + } + + ordered_map(std::initializer_list init, size_type bucket_count, const Hash& hash, const Allocator& alloc) + : ordered_map(init.begin(), init.end(), bucket_count, hash, KeyEqual(), alloc) { } - ordered_map& operator=(std::initializer_list ilist) { m_ht.clear(); - + m_ht.reserve(ilist.size()); m_ht.insert(ilist.begin(), ilist.end()); - + return *this; } - - allocator_type get_allocator() const { return m_ht.get_allocator(); } - - + allocator_type get_allocator() const { + return m_ht.get_allocator(); + } + /* * Iterators */ - iterator begin() noexcept { return m_ht.begin(); } - const_iterator begin() const noexcept { return m_ht.begin(); } - const_iterator cbegin() const noexcept { return m_ht.cbegin(); } - - iterator end() noexcept { return m_ht.end(); } - const_iterator end() const noexcept { return m_ht.end(); } - const_iterator cend() const noexcept { return m_ht.cend(); } - - reverse_iterator rbegin() noexcept { return m_ht.rbegin(); } - const_reverse_iterator rbegin() const noexcept { return m_ht.rbegin(); } - const_reverse_iterator rcbegin() const noexcept { return m_ht.rcbegin(); } - - reverse_iterator rend() noexcept { return m_ht.rend(); } - const_reverse_iterator rend() const noexcept { return m_ht.rend(); } - const_reverse_iterator rcend() const noexcept { return m_ht.rcend(); } - - + iterator begin() noexcept { + return m_ht.begin(); + } + const_iterator begin() const noexcept { + return m_ht.begin(); + } + const_iterator cbegin() const noexcept { + return m_ht.cbegin(); + } + + iterator end() noexcept { + return m_ht.end(); + } + const_iterator end() const noexcept { + return m_ht.end(); + } + const_iterator cend() const noexcept { + return m_ht.cend(); + } + + reverse_iterator rbegin() noexcept { + return m_ht.rbegin(); + } + const_reverse_iterator rbegin() const noexcept { + return m_ht.rbegin(); + } + const_reverse_iterator rcbegin() const noexcept { + return m_ht.rcbegin(); + } + + reverse_iterator rend() noexcept { + return m_ht.rend(); + } + const_reverse_iterator rend() const noexcept { + return m_ht.rend(); + } + const_reverse_iterator rcend() const noexcept { + return m_ht.rcend(); + } + /* * Capacity */ - bool empty() const noexcept { return m_ht.empty(); } - size_type size() const noexcept { return m_ht.size(); } - size_type max_size() const noexcept { return m_ht.max_size(); } - + bool empty() const noexcept { + return m_ht.empty(); + } + size_type size() const noexcept { + return m_ht.size(); + } + size_type max_size() const noexcept { + return m_ht.max_size(); + } + /* * Modifiers */ - void clear() noexcept { m_ht.clear(); } - - - - std::pair insert(const value_type& value) { return m_ht.insert(value); } - - template::value>::type* = nullptr> - std::pair insert(P&& value) { return m_ht.emplace(std::forward

(value)); } - - std::pair insert(value_type&& value) { return m_ht.insert(std::move(value)); } - - + void clear() noexcept { + m_ht.clear(); + } + + std::pair insert(const value_type& value) { + return m_ht.insert(value); + } + + template ::value>::type* = nullptr> std::pair insert(P&& value) { + return m_ht.emplace(std::forward

(value)); + } + + std::pair insert(value_type&& value) { + return m_ht.insert(std::move(value)); + } + iterator insert(const_iterator hint, const value_type& value) { return m_ht.insert_hint(hint, value); } - - template::value>::type* = nullptr> + + template ::value>::type* = nullptr> iterator insert(const_iterator hint, P&& value) { return m_ht.emplace_hint(hint, std::forward

(value)); } - - iterator insert(const_iterator hint, value_type&& value) { + + iterator insert(const_iterator hint, value_type&& value) { return m_ht.insert_hint(hint, std::move(value)); } - - - template - void insert(InputIt first, InputIt last) { m_ht.insert(first, last); } - void insert(std::initializer_list ilist) { m_ht.insert(ilist.begin(), ilist.end()); } - - - - template - std::pair insert_or_assign(const key_type& k, M&& obj) { - return m_ht.insert_or_assign(k, std::forward(obj)); + template void insert(InputIt first, InputIt last) { + m_ht.insert(first, last); + } + void insert(std::initializer_list ilist) { + m_ht.insert(ilist.begin(), ilist.end()); } - template - std::pair insert_or_assign(key_type&& k, M&& obj) { - return m_ht.insert_or_assign(std::move(k), std::forward(obj)); + template std::pair insert_or_assign(const key_type& k, M&& obj) { + return m_ht.insert_or_assign(k, std::forward(obj)); } - - - template - iterator insert_or_assign(const_iterator hint, const key_type& k, M&& obj) { + + template std::pair insert_or_assign(key_type&& k, M&& obj) { + return m_ht.insert_or_assign(std::move(k), std::forward(obj)); + } + + template iterator insert_or_assign(const_iterator hint, const key_type& k, M&& obj) { return m_ht.insert_or_assign(hint, k, std::forward(obj)); } - - template - iterator insert_or_assign(const_iterator hint, key_type&& k, M&& obj) { + + template iterator insert_or_assign(const_iterator hint, key_type&& k, M&& obj) { return m_ht.insert_or_assign(hint, std::move(k), std::forward(obj)); } - + /** * Due to the way elements are stored, emplace will need to move or copy the key-value once. * The method is equivalent to insert(value_type(std::forward(args)...)); - * + * * Mainly here for compatibility with the std::unordered_map interface. */ - template - std::pair emplace(Args&&... args) { return m_ht.emplace(std::forward(args)...); } - + template std::pair emplace(Args&&... args) { + return m_ht.emplace(std::forward(args)...); + } + /** * Due to the way elements are stored, emplace_hint will need to move or copy the key-value once. * The method is equivalent to insert(hint, value_type(std::forward(args)...)); - * + * * Mainly here for compatibility with the std::unordered_map interface. */ - template - iterator emplace_hint(const_iterator hint, Args&&... args) { + template iterator emplace_hint(const_iterator hint, Args&&... args) { return m_ht.emplace_hint(hint, std::forward(args)...); } - - - - - template - std::pair try_emplace(const key_type& k, Args&&... args) { + + template std::pair try_emplace(const key_type& k, Args&&... args) { return m_ht.try_emplace(k, std::forward(args)...); } - - template - std::pair try_emplace(key_type&& k, Args&&... args) { + + template std::pair try_emplace(key_type&& k, Args&&... args) { return m_ht.try_emplace(std::move(k), std::forward(args)...); } - - template - iterator try_emplace(const_iterator hint, const key_type& k, Args&&... args) { + + template iterator try_emplace(const_iterator hint, const key_type& k, Args&&... args) { return m_ht.try_emplace_hint(hint, k, std::forward(args)...); } - - template - iterator try_emplace(const_iterator hint, key_type&& k, Args&&... args) { + + template iterator try_emplace(const_iterator hint, key_type&& k, Args&&... args) { return m_ht.try_emplace_hint(hint, std::move(k), std::forward(args)...); } - - - /** * When erasing an element, the insert order will be preserved and no holes will be present in the container - * returned by 'values_container()'. - * + * returned by 'values_container()'. + * * The method is in O(n), if the order is not important 'unordered_erase(...)' method is faster with an O(1) * average complexity. */ - iterator erase(iterator pos) { return m_ht.erase(pos); } - + iterator erase(iterator pos) { + return m_ht.erase(pos); + } + /** * @copydoc erase(iterator pos) */ - iterator erase(const_iterator pos) { return m_ht.erase(pos); } - + iterator erase(const_iterator pos) { + return m_ht.erase(pos); + } + /** * @copydoc erase(iterator pos) - */ - iterator erase(const_iterator first, const_iterator last) { return m_ht.erase(first, last); } - + */ + iterator erase(const_iterator first, const_iterator last) { + return m_ht.erase(first, last); + } + /** * @copydoc erase(iterator pos) - */ - size_type erase(const key_type& key) { return m_ht.erase(key); } - + */ + size_type erase(const key_type& key) { + return m_ht.erase(key); + } + /** * @copydoc erase(iterator pos) - * + * * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same * as hash_function()(key). Usefull to speed-up the lookup to the value if you already have the hash. - */ - size_type erase(const key_type& key, std::size_t precalculated_hash) { - return m_ht.erase(key, precalculated_hash); + */ + size_type erase(const key_type& key, std::size_t precalculated_hash) { + return m_ht.erase(key, precalculated_hash); } - + /** * @copydoc erase(iterator pos) - * - * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. + * + * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. * If so, K must be hashable and comparable to Key. */ - template::value>::type* = nullptr> - size_type erase(const K& key) { return m_ht.erase(key); } - + template ::value>::type* = nullptr> size_type erase(const K& key) { + return m_ht.erase(key); + } + /** * @copydoc erase(const key_type& key, std::size_t precalculated_hash) - * - * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. + * + * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. * If so, K must be hashable and comparable to Key. */ - template::value>::type* = nullptr> - size_type erase(const K& key, std::size_t precalculated_hash) { - return m_ht.erase(key, precalculated_hash); + template ::value>::type* = nullptr> + size_type erase(const K& key, std::size_t precalculated_hash) { + return m_ht.erase(key, precalculated_hash); } - - - - void swap(ordered_map& other) { other.m_ht.swap(m_ht); } - + + void swap(ordered_map& other) { + other.m_ht.swap(m_ht); + } + /* * Lookup */ - T& at(const Key& key) { return m_ht.at(key); } - + T& at(const Key& key) { + return m_ht.at(key); + } + /** * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash. */ - T& at(const Key& key, std::size_t precalculated_hash) { return m_ht.at(key, precalculated_hash); } - - - const T& at(const Key& key) const { return m_ht.at(key); } - + T& at(const Key& key, std::size_t precalculated_hash) { + return m_ht.at(key, precalculated_hash); + } + + const T& at(const Key& key) const { + return m_ht.at(key); + } + /** * @copydoc at(const Key& key, std::size_t precalculated_hash) */ - const T& at(const Key& key, std::size_t precalculated_hash) const { return m_ht.at(key, precalculated_hash); } - - + const T& at(const Key& key, std::size_t precalculated_hash) const { + return m_ht.at(key, precalculated_hash); + } + /** - * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. + * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. * If so, K must be hashable and comparable to Key. */ - template::value>::type* = nullptr> - T& at(const K& key) { return m_ht.at(key); } - + template ::value>::type* = nullptr> T& at(const K& key) { + return m_ht.at(key); + } + /** * @copydoc at(const K& key) - * + * * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash. - */ - template::value>::type* = nullptr> - T& at(const K& key, std::size_t precalculated_hash) { return m_ht.at(key, precalculated_hash); } - + */ + template ::value>::type* = nullptr> + T& at(const K& key, std::size_t precalculated_hash) { + return m_ht.at(key, precalculated_hash); + } + /** * @copydoc at(const K& key) */ - template::value>::type* = nullptr> - const T& at(const K& key) const { return m_ht.at(key); } - + template ::value>::type* = nullptr> const T& at(const K& key) const { + return m_ht.at(key); + } + /** * @copydoc at(const K& key, std::size_t precalculated_hash) - */ - template::value>::type* = nullptr> - const T& at(const K& key, std::size_t precalculated_hash) const { return m_ht.at(key, precalculated_hash); } - - - - T& operator[](const Key& key) { return m_ht[key]; } - T& operator[](Key&& key) { return m_ht[std::move(key)]; } - - - - size_type count(const Key& key) const { return m_ht.count(key); } - + */ + template ::value>::type* = nullptr> + const T& at(const K& key, std::size_t precalculated_hash) const { + return m_ht.at(key, precalculated_hash); + } + + T& operator[](const Key& key) { + return m_ht[key]; + } + T& operator[](Key&& key) { + return m_ht[std::move(key)]; + } + + size_type count(const Key& key) const { + return m_ht.count(key); + } + /** * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash. */ size_type count(const Key& key, std::size_t precalculated_hash) const { - return m_ht.count(key, precalculated_hash); - } - - /** - * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. - * If so, K must be hashable and comparable to Key. - */ - template::value>::type* = nullptr> - size_type count(const K& key) const { return m_ht.count(key); } - - /** - * @copydoc count(const K& key) const - * - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash. - */ - template::value>::type* = nullptr> - size_type count(const K& key, std::size_t precalculated_hash) const { return m_ht.count(key, precalculated_hash); } - - - - iterator find(const Key& key) { return m_ht.find(key); } - + + /** + * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. + * If so, K must be hashable and comparable to Key. + */ + template ::value>::type* = nullptr> size_type count(const K& key) const { + return m_ht.count(key); + } + + /** + * @copydoc count(const K& key) const + * + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash. + */ + template ::value>::type* = nullptr> + size_type count(const K& key, std::size_t precalculated_hash) const { + return m_ht.count(key, precalculated_hash); + } + + iterator find(const Key& key) { + return m_ht.find(key); + } + /** * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash. */ - iterator find(const Key& key, std::size_t precalculated_hash) { return m_ht.find(key, precalculated_hash); } - - const_iterator find(const Key& key) const { return m_ht.find(key); } - + iterator find(const Key& key, std::size_t precalculated_hash) { + return m_ht.find(key, precalculated_hash); + } + + const_iterator find(const Key& key) const { + return m_ht.find(key); + } + /** * @copydoc find(const Key& key, std::size_t precalculated_hash) */ const_iterator find(const Key& key, std::size_t precalculated_hash) const { return m_ht.find(key, precalculated_hash); } - + /** - * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. + * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. * If so, K must be hashable and comparable to Key. */ - template::value>::type* = nullptr> - iterator find(const K& key) { return m_ht.find(key); } - - /** - * @copydoc find(const K& key) - * - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash. - */ - template::value>::type* = nullptr> - iterator find(const K& key, std::size_t precalculated_hash) { return m_ht.find(key, precalculated_hash); } - - /** - * @copydoc find(const K& key) - */ - template::value>::type* = nullptr> - const_iterator find(const K& key) const { return m_ht.find(key); } - - /** - * @copydoc find(const K& key) - * - * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same - * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash. - */ - template - const_iterator find(const K& key, std::size_t precalculated_hash) const { - return m_ht.find(key, precalculated_hash); + template ::value>::type* = nullptr> iterator find(const K& key) { + return m_ht.find(key); + } + + /** + * @copydoc find(const K& key) + * + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash. + */ + template ::value>::type* = nullptr> + iterator find(const K& key, std::size_t precalculated_hash) { + return m_ht.find(key, precalculated_hash); + } + + /** + * @copydoc find(const K& key) + */ + template ::value>::type* = nullptr> const_iterator find(const K& key) const { + return m_ht.find(key); + } + + /** + * @copydoc find(const K& key) + * + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash. + */ + template const_iterator find(const K& key, std::size_t precalculated_hash) const { + return m_ht.find(key, precalculated_hash); + } + + bool contains(const Key& key) const { + return find(key) != this->end(); + }; + + std::pair equal_range(const Key& key) { + return m_ht.equal_range(key); } - bool contains(const Key& key) const {return find(key) != this->end();}; - - std::pair equal_range(const Key& key) { return m_ht.equal_range(key); } - /** * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash. */ std::pair equal_range(const Key& key, std::size_t precalculated_hash) { - return m_ht.equal_range(key, precalculated_hash); + return m_ht.equal_range(key, precalculated_hash); } - - std::pair equal_range(const Key& key) const { return m_ht.equal_range(key); } - + + std::pair equal_range(const Key& key) const { + return m_ht.equal_range(key); + } + /** * @copydoc equal_range(const Key& key, std::size_t precalculated_hash) */ std::pair equal_range(const Key& key, std::size_t precalculated_hash) const { - return m_ht.equal_range(key, precalculated_hash); + return m_ht.equal_range(key, precalculated_hash); } /** - * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. + * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. * If so, K must be hashable and comparable to Key. */ - template::value>::type* = nullptr> - std::pair equal_range(const K& key) { return m_ht.equal_range(key); } - + template ::value>::type* = nullptr> + std::pair equal_range(const K& key) { + return m_ht.equal_range(key); + } + /** * @copydoc equal_range(const K& key) - * + * * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash. */ - template::value>::type* = nullptr> - std::pair equal_range(const K& key, std::size_t precalculated_hash) { - return m_ht.equal_range(key, precalculated_hash); + template ::value>::type* = nullptr> + std::pair equal_range(const K& key, std::size_t precalculated_hash) { + return m_ht.equal_range(key, precalculated_hash); } - + /** * @copydoc equal_range(const K& key) */ - template::value>::type* = nullptr> - std::pair equal_range(const K& key) const { return m_ht.equal_range(key); } - + template ::value>::type* = nullptr> + std::pair equal_range(const K& key) const { + return m_ht.equal_range(key); + } + /** * @copydoc equal_range(const K& key, std::size_t precalculated_hash) - */ - template::value>::type* = nullptr> - std::pair equal_range(const K& key, std::size_t precalculated_hash) const { - return m_ht.equal_range(key, precalculated_hash); + */ + template ::value>::type* = nullptr> + std::pair equal_range(const K& key, std::size_t precalculated_hash) const { + return m_ht.equal_range(key, precalculated_hash); } - - - + /* - * Bucket interface + * Bucket interface */ - size_type bucket_count() const { return m_ht.bucket_count(); } - size_type max_bucket_count() const { return m_ht.max_bucket_count(); } - - + size_type bucket_count() const { + return m_ht.bucket_count(); + } + size_type max_bucket_count() const { + return m_ht.max_bucket_count(); + } + /* - * Hash policy + * Hash policy */ - float load_factor() const { return m_ht.load_factor(); } - float max_load_factor() const { return m_ht.max_load_factor(); } - void max_load_factor(float ml) { m_ht.max_load_factor(ml); } - - void rehash(size_type count) { m_ht.rehash(count); } - void reserve(size_type count) { m_ht.reserve(count); } - - + float load_factor() const { + return m_ht.load_factor(); + } + float max_load_factor() const { + return m_ht.max_load_factor(); + } + void max_load_factor(float ml) { + m_ht.max_load_factor(ml); + } + + void rehash(size_type count) { + m_ht.rehash(count); + } + void reserve(size_type count) { + m_ht.reserve(count); + } + /* * Observers */ - hasher hash_function() const { return m_ht.hash_function(); } - key_equal key_eq() const { return m_ht.key_eq(); } - - - + hasher hash_function() const { + return m_ht.hash_function(); + } + key_equal key_eq() const { + return m_ht.key_eq(); + } + /* * Other */ - + /** * Convert a const_iterator to an iterator. */ iterator mutable_iterator(const_iterator pos) { return m_ht.mutable_iterator(pos); } - + /** * Requires index <= size(). - * + * * Return an iterator to the element at index. Return end() if index == size(). */ - iterator nth(size_type index) { return m_ht.nth(index); } - + iterator nth(size_type index) { + return m_ht.nth(index); + } + /** * @copydoc nth(size_type index) */ - const_iterator nth(size_type index) const { return m_ht.nth(index); } - - + const_iterator nth(size_type index) const { + return m_ht.nth(index); + } + /** * Return const_reference to the first element. Requires the container to not be empty. */ - const_reference front() const { return m_ht.front(); } - + const_reference front() const { + return m_ht.front(); + } + /** * Return const_reference to the last element. Requires the container to not be empty. */ - const_reference back() const { return m_ht.back(); } - - + const_reference back() const { + return m_ht.back(); + } + /** * Only available if ValueTypeContainer is a std::vector. Same as calling 'values_container().data()'. */ - template::value>::type* = nullptr> - const typename values_container_type::value_type* data() const noexcept { return m_ht.data(); } - + template ::value>::type* = nullptr> + const typename values_container_type::value_type* data() const noexcept { + return m_ht.data(); + } + /** * Return the container in which the values are stored. The values are in the same order as the insertion order * and are contiguous in the structure, no holes (size() == values_container().size()). */ - const values_container_type& values_container() const noexcept { return m_ht.values_container(); } + const values_container_type& values_container() const noexcept { + return m_ht.values_container(); + } + + template ::value>::type* = nullptr> + size_type capacity() const noexcept { + return m_ht.capacity(); + } + + void shrink_to_fit() { + m_ht.shrink_to_fit(); + } - template::value>::type* = nullptr> - size_type capacity() const noexcept { return m_ht.capacity(); } - - void shrink_to_fit() { m_ht.shrink_to_fit(); } - - - /** - * Insert the value before pos shifting all the elements on the right of pos (including pos) one position + * Insert the value before pos shifting all the elements on the right of pos (including pos) one position * to the right. - * + * * Amortized linear time-complexity in the distance between pos and end(). */ - std::pair insert_at_position(const_iterator pos, const value_type& value) { - return m_ht.insert_at_position(pos, value); + std::pair insert_at_position(const_iterator pos, const value_type& value) { + return m_ht.insert_at_position(pos, value); } - + /** * @copydoc insert_at_position(const_iterator pos, const value_type& value) */ - std::pair insert_at_position(const_iterator pos, value_type&& value) { - return m_ht.insert_at_position(pos, std::move(value)); + std::pair insert_at_position(const_iterator pos, value_type&& value) { + return m_ht.insert_at_position(pos, std::move(value)); } - + /** * @copydoc insert_at_position(const_iterator pos, const value_type& value) - * + * * Same as insert_at_position(pos, value_type(std::forward(args)...), mainly * here for coherence. */ - template - std::pair emplace_at_position(const_iterator pos, Args&&... args) { - return m_ht.emplace_at_position(pos, std::forward(args)...); + template std::pair emplace_at_position(const_iterator pos, Args&&... args) { + return m_ht.emplace_at_position(pos, std::forward(args)...); } - + /** * @copydoc insert_at_position(const_iterator pos, const value_type& value) - */ - template - std::pair try_emplace_at_position(const_iterator pos, const key_type& k, Args&&... args) { + */ + template std::pair try_emplace_at_position(const_iterator pos, const key_type& k, Args&&... args) { return m_ht.try_emplace_at_position(pos, k, std::forward(args)...); } - + /** * @copydoc insert_at_position(const_iterator pos, const value_type& value) - */ - template - std::pair try_emplace_at_position(const_iterator pos, key_type&& k, Args&&... args) { + */ + template std::pair try_emplace_at_position(const_iterator pos, key_type&& k, Args&&... args) { return m_ht.try_emplace_at_position(pos, std::move(k), std::forward(args)...); } - - - - void pop_back() { m_ht.pop_back(); } - + + void pop_back() { + m_ht.pop_back(); + } + /** * Faster erase operation with an O(1) average complexity but it doesn't preserve the insertion order. - * + * * If an erasure occurs, the last element of the map will take the place of the erased element. */ - iterator unordered_erase(iterator pos) { return m_ht.unordered_erase(pos); } - + iterator unordered_erase(iterator pos) { + return m_ht.unordered_erase(pos); + } + /** * @copydoc unordered_erase(iterator pos) */ - iterator unordered_erase(const_iterator pos) { return m_ht.unordered_erase(pos); } - + iterator unordered_erase(const_iterator pos) { + return m_ht.unordered_erase(pos); + } + /** * @copydoc unordered_erase(iterator pos) - */ - size_type unordered_erase(const key_type& key) { return m_ht.unordered_erase(key); } - + */ + size_type unordered_erase(const key_type& key) { + return m_ht.unordered_erase(key); + } + /** * @copydoc unordered_erase(iterator pos) - * + * * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash. - */ - size_type unordered_erase(const key_type& key, std::size_t precalculated_hash) { - return m_ht.unordered_erase(key, precalculated_hash); + */ + size_type unordered_erase(const key_type& key, std::size_t precalculated_hash) { + return m_ht.unordered_erase(key, precalculated_hash); } - + /** * @copydoc unordered_erase(iterator pos) - * - * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. + * + * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. * If so, K must be hashable and comparable to Key. */ - template::value>::type* = nullptr> - size_type unordered_erase(const K& key) { return m_ht.unordered_erase(key); } - + template ::value>::type* = nullptr> size_type unordered_erase(const K& key) { + return m_ht.unordered_erase(key); + } + /** * @copydoc unordered_erase(const K& key) - * + * * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same * as hash_function()(key). Usefull to speed-up the lookup if you already have the hash. */ - template::value>::type* = nullptr> - size_type unordered_erase(const K& key, std::size_t precalculated_hash) { - return m_ht.unordered_erase(key, precalculated_hash); + template ::value>::type* = nullptr> + size_type unordered_erase(const K& key, std::size_t precalculated_hash) { + return m_ht.unordered_erase(key, precalculated_hash); } - + /** * Serialize the map through the `serializer` parameter. - * + * * The `serializer` parameter must be a function object that supports the following call: * - `template void operator()(const U& value);` where the types `std::uint64_t`, `float` and `std::pair` must be supported for U. - * + * * The implementation leaves binary compatibilty (endianness, IEEE 754 for floats, ...) of the types it serializes * in the hands of the `Serializer` function object if compatibilty is required. */ - template - void serialize(Serializer& serializer) const { + template void serialize(Serializer& serializer) const { m_ht.serialize(serializer); } /** * Deserialize a previouly serialized map through the `deserializer` parameter. - * + * * The `deserializer` parameter must be a function object that supports the following calls: * - `template U operator()();` where the types `std::uint64_t`, `float` and `std::pair` must be supported for U. - * + * * If the deserialized hash map type is hash compatible with the serialized map, the deserialization process can be - * sped up by setting `hash_compatible` to true. To be hash compatible, the Hash and KeyEqual must behave the same way + * sped up by setting `hash_compatible` to true. To be hash compatible, the Hash and KeyEqual must behave the same way * than the ones used on the serialized map. The `std::size_t` must also be of the same size as the one on the platform used - * to serialize the map, the same apply for `IndexType`. If these criteria are not met, the behaviour is undefined with + * to serialize the map, the same apply for `IndexType`. If these criteria are not met, the behaviour is undefined with * `hash_compatible` sets to true. - * + * * The behaviour is undefined if the type `Key` and `T` of the `ordered_map` are not the same as the * types used during serialization. - * - * The implementation leaves binary compatibilty (endianness, IEEE 754 for floats, size of int, ...) of the types it + * + * The implementation leaves binary compatibilty (endianness, IEEE 754 for floats, size of int, ...) of the types it * deserializes in the hands of the `Deserializer` function object if compatibilty is required. */ - template - static ordered_map deserialize(Deserializer& deserializer, bool hash_compatible = false) { + template static ordered_map deserialize(Deserializer& deserializer, bool hash_compatible = false) { ordered_map map(0); map.m_ht.deserialize(deserializer, hash_compatible); return map; } - - - - friend bool operator==(const ordered_map& lhs, const ordered_map& rhs) { return lhs.m_ht == rhs.m_ht; } - friend bool operator!=(const ordered_map& lhs, const ordered_map& rhs) { return lhs.m_ht != rhs.m_ht; } - friend bool operator<(const ordered_map& lhs, const ordered_map& rhs) { return lhs.m_ht < rhs.m_ht; } - friend bool operator<=(const ordered_map& lhs, const ordered_map& rhs) { return lhs.m_ht <= rhs.m_ht; } - friend bool operator>(const ordered_map& lhs, const ordered_map& rhs) { return lhs.m_ht > rhs.m_ht; } - friend bool operator>=(const ordered_map& lhs, const ordered_map& rhs) { return lhs.m_ht >= rhs.m_ht; } - - friend void swap(ordered_map& lhs, ordered_map& rhs) { lhs.swap(rhs); } + + friend bool operator==(const ordered_map& lhs, const ordered_map& rhs) { + return lhs.m_ht == rhs.m_ht; + } + friend bool operator!=(const ordered_map& lhs, const ordered_map& rhs) { + return lhs.m_ht != rhs.m_ht; + } + friend bool operator<(const ordered_map& lhs, const ordered_map& rhs) { + return lhs.m_ht < rhs.m_ht; + } + friend bool operator<=(const ordered_map& lhs, const ordered_map& rhs) { + return lhs.m_ht <= rhs.m_ht; + } + friend bool operator>(const ordered_map& lhs, const ordered_map& rhs) { + return lhs.m_ht > rhs.m_ht; + } + friend bool operator>=(const ordered_map& lhs, const ordered_map& rhs) { + return lhs.m_ht >= rhs.m_ht; + } + + friend void swap(ordered_map& lhs, ordered_map& rhs) { + lhs.swap(rhs); + } private: ht m_ht; diff --git a/include/lib/qstringhash.h b/include/lib/qstringhash.h index a9affaf7..32942645 100644 --- a/include/lib/qstringhash.h +++ b/include/lib/qstringhash.h @@ -10,11 +10,11 @@ // a key in a std::hash structure. Qt 5.14 added this function, so // this file should only be included in earlier versions. namespace std { - template<> struct hash { +template <> struct hash { std::size_t operator()(const QString& s) const noexcept { - return static_cast(qHash(s)); + return static_cast(qHash(s)); } - }; +}; } #endif // QSTRINGHASH_H diff --git a/include/mainwindow.h b/include/mainwindow.h index 63d430a7..2ca25f0f 100644 --- a/include/mainwindow.h +++ b/include/mainwindow.h @@ -29,17 +29,16 @@ namespace Ui { class MainWindow; } -class MainWindow : public QMainWindow -{ +class MainWindow : public QMainWindow { Q_OBJECT public: - explicit MainWindow(QWidget *parent); + explicit MainWindow(QWidget* parent); ~MainWindow(); MainWindow() = delete; - MainWindow(const MainWindow &) = delete; - MainWindow & operator = (const MainWindow &) = delete; + MainWindow(const MainWindow&) = delete; + MainWindow& operator=(const MainWindow&) = delete; // Scripting API Q_INVOKABLE QJSValue getBlock(int x, int y); @@ -71,20 +70,20 @@ public: Q_INVOKABLE void addRect(int x, int y, int width, int height, QString color = "#000000"); Q_INVOKABLE void addFilledRect(int x, int y, int width, int height, QString color = "#000000"); Q_INVOKABLE void addImage(int x, int y, QString filepath); - void refreshAfterPaletteChange(Tileset *tileset); - void setTilesetPalette(Tileset *tileset, int paletteIndex, QList> colors); + void refreshAfterPaletteChange(Tileset* tileset); + void setTilesetPalette(Tileset* tileset, int paletteIndex, QList> colors); Q_INVOKABLE void setPrimaryTilesetPalette(int paletteIndex, QList> colors); Q_INVOKABLE void setPrimaryTilesetPalettes(QList>> palettes); Q_INVOKABLE void setSecondaryTilesetPalette(int paletteIndex, QList> colors); Q_INVOKABLE void setSecondaryTilesetPalettes(QList>> palettes); - QJSValue getTilesetPalette(const QList> &palettes, int paletteIndex); - QJSValue getTilesetPalettes(const QList> &palettes); + QJSValue getTilesetPalette(const QList>& palettes, int paletteIndex); + QJSValue getTilesetPalettes(const QList>& palettes); Q_INVOKABLE QJSValue getPrimaryTilesetPalette(int paletteIndex); Q_INVOKABLE QJSValue getPrimaryTilesetPalettes(); Q_INVOKABLE QJSValue getSecondaryTilesetPalette(int paletteIndex); Q_INVOKABLE QJSValue getSecondaryTilesetPalettes(); void refreshAfterPalettePreviewChange(); - void setTilesetPalettePreview(Tileset *tileset, int paletteIndex, QList> colors); + void setTilesetPalettePreview(Tileset* tileset, int paletteIndex, QList> colors); Q_INVOKABLE void setPrimaryTilesetPalettePreview(int paletteIndex, QList> colors); Q_INVOKABLE void setPrimaryTilesetPalettesPreview(QList>> palettes); Q_INVOKABLE void setSecondaryTilesetPalettePreview(int paletteIndex, QList> colors); @@ -115,21 +114,21 @@ public: private slots: void on_action_Open_Project_triggered(); void on_action_Reload_Project_triggered(); - void on_mapList_activated(const QModelIndex &index); + void on_mapList_activated(const QModelIndex& index); void on_action_Save_Project_triggered(); void openWarpMap(QString map_name, QString warp_num); void duplicate(); void onLoadMapRequested(QString, QString); - void onMapChanged(Map *map); + void onMapChanged(Map* map); void onMapNeedsRedrawing(); void onTilesetsSaved(QString, QString); void onWildMonDataChanged(); void openNewMapPopupWindow(int, QVariant); void onNewMapCreated(); void onMapCacheCleared(); - void onMapRulerStatusChanged(const QString &); + void onMapRulerStatusChanged(const QString&); void applyUserShortcuts(); void on_action_NewMap_triggered(); @@ -137,11 +136,11 @@ private slots: void on_action_Save_triggered(); void on_tabWidget_2_currentChanged(int index); void on_action_Exit_triggered(); - void on_comboBox_Song_currentTextChanged(const QString &arg1); - void on_comboBox_Location_currentTextChanged(const QString &arg1); - void on_comboBox_Weather_currentTextChanged(const QString &arg1); - void on_comboBox_Type_currentTextChanged(const QString &arg1); - void on_comboBox_BattleScene_currentTextChanged(const QString &arg1); + void on_comboBox_Song_currentTextChanged(const QString& arg1); + void on_comboBox_Location_currentTextChanged(const QString& arg1); + void on_comboBox_Weather_currentTextChanged(const QString& arg1); + void on_comboBox_Type_currentTextChanged(const QString& arg1); + void on_comboBox_BattleScene_currentTextChanged(const QString& arg1); void on_checkBox_ShowLocation_clicked(bool checked); void on_checkBox_AllowRunning_clicked(bool checked); void on_checkBox_AllowBiking_clicked(bool checked); @@ -179,7 +178,7 @@ private slots: void on_toolButton_Move_clicked(); void on_toolButton_Shift_clicked(); - void onOpenMapListContextMenu(const QPoint &point); + void onOpenMapListContextMenu(const QPoint& point); void onAddNewMapToGroupClick(QAction* triggeredAction); void onAddNewMapToAreaClick(QAction* triggeredAction); void onAddNewMapToLayoutClick(QAction* triggeredAction); @@ -189,15 +188,15 @@ private slots: void on_actionExport_Stitched_Map_Image_triggered(); void on_actionExport_Map_Timelapse_Image_triggered(); - void on_comboBox_ConnectionDirection_currentIndexChanged(const QString &arg1); + void on_comboBox_ConnectionDirection_currentIndexChanged(const QString& arg1); void on_spinBox_ConnectionOffset_valueChanged(int offset); - void on_comboBox_ConnectedMap_currentTextChanged(const QString &mapName); + void on_comboBox_ConnectedMap_currentTextChanged(const QString& mapName); void on_pushButton_AddConnection_clicked(); void on_pushButton_RemoveConnection_clicked(); - void on_comboBox_DiveMap_currentTextChanged(const QString &mapName); - void on_comboBox_EmergeMap_currentTextChanged(const QString &mapName); - void on_comboBox_PrimaryTileset_currentTextChanged(const QString &arg1); - void on_comboBox_SecondaryTileset_currentTextChanged(const QString &arg1); + void on_comboBox_DiveMap_currentTextChanged(const QString& mapName); + void on_comboBox_EmergeMap_currentTextChanged(const QString& mapName); + void on_comboBox_PrimaryTileset_currentTextChanged(const QString& arg1); + void on_comboBox_SecondaryTileset_currentTextChanged(const QString& arg1); void on_pushButton_ChangeDimensions_clicked(); void on_checkBox_smartPaths_stateChanged(int selected); void on_checkBox_Visibility_clicked(bool checked); @@ -207,12 +206,12 @@ private slots: void on_actionTileset_Editor_triggered(); - void mapSortOrder_changed(QAction *action); + void mapSortOrder_changed(QAction* action); - void on_lineEdit_filterBox_textChanged(const QString &arg1); + void on_lineEdit_filterBox_textChanged(const QString& arg1); - void moveEvent(QMoveEvent *event); - void closeEvent(QCloseEvent *); + void moveEvent(QMoveEvent* event); + void closeEvent(QCloseEvent*); void eventTabChanged(int index); @@ -237,41 +236,41 @@ private slots: void togglePreferenceSpecificUi(); private: - Ui::MainWindow *ui; - QLabel *label_MapRulerStatus = nullptr; + Ui::MainWindow* ui; + QLabel* label_MapRulerStatus = nullptr; QPointer tilesetEditor = nullptr; QPointer regionMapEditor = nullptr; QPointer shortcutsEditor = nullptr; QPointer mapImageExporter = nullptr; QPointer newmapprompt = nullptr; QPointer preferenceEditor = nullptr; - FilterChildrenProxyModel *mapListProxyModel; - QStandardItemModel *mapListModel; - QList *mapGroupItemsList; + FilterChildrenProxyModel* mapListProxyModel; + QStandardItemModel* mapListModel; + QList* mapGroupItemsList; QMap mapListIndexes; - Editor *editor = nullptr; + Editor* editor = nullptr; QIcon* mapIcon; QIcon* mapEditedIcon; QIcon* mapOpenedIcon; - QAction *undoAction; - QAction *redoAction; + QAction* undoAction; + QAction* redoAction; - QWidget *eventTabObjectWidget; - QWidget *eventTabWarpWidget; - QWidget *eventTabTriggerWidget; - QWidget *eventTabBGWidget; - QWidget *eventTabHealspotWidget; - QWidget *eventTabMultipleWidget; + QWidget* eventTabObjectWidget; + QWidget* eventTabWarpWidget; + QWidget* eventTabTriggerWidget; + QWidget* eventTabBGWidget; + QWidget* eventTabHealspotWidget; + QWidget* eventTabMultipleWidget; - DraggablePixmapItem *selectedObject; - DraggablePixmapItem *selectedWarp; - DraggablePixmapItem *selectedTrigger; - DraggablePixmapItem *selectedBG; - DraggablePixmapItem *selectedHealspot; + DraggablePixmapItem* selectedObject; + DraggablePixmapItem* selectedWarp; + DraggablePixmapItem* selectedTrigger; + DraggablePixmapItem* selectedBG; + DraggablePixmapItem* selectedHealspot; - QList registeredActions; - QVector openScriptButtons; + QList registeredActions; + QVector openScriptButtons; bool isProgrammaticEventTabChange; bool projectHasUnsavedChanges; @@ -292,7 +291,7 @@ private: void setRecentMap(QString map_name); QStandardItem* createMapItem(QString mapName, int groupNum, int inGroupNum); - void drawMapListIcons(QAbstractItemModel *model); + void drawMapListIcons(QAbstractItemModel* model); void updateMapList(); void displayMapProperties(); @@ -316,7 +315,7 @@ private: void setTheme(QString); bool openRecentProject(); void updateTilesetEditor(); - QString getEventGroupFromTabWidget(QWidget *tab); + QString getEventGroupFromTabWidget(QWidget* tab); void closeSupplementaryWindows(); void setWindowDisabled(bool); @@ -334,7 +333,7 @@ private: enum MapListUserRoles { GroupRole = Qt::UserRole + 1, // Used to hold the map group number. - TypeRole, // Used to differentiate between the different layers of the map list tree view. + TypeRole, // Used to differentiate between the different layers of the map list tree view. TypeRole2, // Used for various extra data needed. }; diff --git a/include/project.h b/include/project.h index 1ea1b1a3..a51db4e9 100644 --- a/include/project.h +++ b/include/project.h @@ -21,17 +21,18 @@ static QString NONE_MAP_CONSTANT = "MAP_NONE"; static QString NONE_MAP_NAME = "None"; -class Project : public QObject -{ +class Project : public QObject { Q_OBJECT public: - Project(QWidget *parent = nullptr); + Project(QWidget* parent = nullptr); ~Project(); - Project(const Project &) = delete; - Project & operator = (const Project &) = delete; + Project(const Project&) = delete; + Project& operator=(const Project&) = delete; - inline QWidget *parentWidget() const { return static_cast(parent()); } + inline QWidget* parentWidget() const { + return static_cast(parent()); + } public: QString root; @@ -76,8 +77,7 @@ public: void clearMapCache(); void clearTilesetCache(); - struct DataQualifiers - { + struct DataQualifiers { bool isStatic; bool isConst; }; @@ -89,7 +89,7 @@ public: Map* getMap(QString); QMap tilesetCache; - Tileset* loadTileset(QString, Tileset *tileset = nullptr); + Tileset* loadTileset(QString, Tileset* tileset = nullptr); Tileset* getTileset(QString, bool forceLoad = false); QMap tilesetLabels; @@ -131,7 +131,7 @@ public: void saveLayoutBlockdata(Map*); void saveLayoutBorder(Map*); - void writeBlockdata(QString, const Blockdata &); + void writeBlockdata(QString, const Blockdata&); void saveAllMaps(); void saveMap(Map*); void saveAllDataStructures(); @@ -177,12 +177,12 @@ public: QString getScriptFileExtension(bool usePoryScript) const; QString getScriptDefaultString(bool usePoryScript, QString mapName) const; - QString getMapScriptsFilePath(const QString &mapName) const; + QString getMapScriptsFilePath(const QString& mapName) const; QStringList getEventScriptsFilePaths() const; - bool loadMapBorder(Map *map); + bool loadMapBorder(Map* map); - void saveMapHealEvents(Map *map); + void saveMapHealEvents(Map* map); static int getNumTilesPrimary(); static int getNumTilesTotal(); @@ -205,9 +205,9 @@ private: void setNewMapHeader(Map* map, int mapIndex); void setNewMapLayout(Map* map); void setNewMapBlockdata(Map* map); - void setNewMapBorder(Map *map); - void setNewMapEvents(Map *map); - void setNewMapConnections(Map *map); + void setNewMapBorder(Map* map); + void setNewMapEvents(Map* map); + void setNewMapConnections(Map* map); void ignoreWatchedFileTemporarily(QString filepath); diff --git a/include/scripting.h b/include/scripting.h index 6f3b0d16..e3bedc49 100644 --- a/include/scripting.h +++ b/include/scripting.h @@ -15,14 +15,13 @@ enum CallbackType { OnMapOpened, }; -class Scripting -{ +class Scripting { public: - Scripting(MainWindow *mainWindow); + Scripting(MainWindow* mainWindow); static QJSValue fromBlock(Block block); static QJSValue dimensions(int width, int height); - static QJSEngine *getEngine(); - static void init(MainWindow *mainWindow); + static QJSEngine* getEngine(); + static void init(MainWindow* mainWindow); static void registerAction(QString functionName, QString actionName); static int numRegisteredActions(); static void invokeAction(QString actionName); @@ -32,7 +31,7 @@ public: static void cb_MapOpened(QString mapName); private: - QJSEngine *engine; + QJSEngine* engine; QStringList filepaths; QList modules; QMap registeredActions; diff --git a/include/settings.h b/include/settings.h index d37283cd..170b712b 100644 --- a/include/settings.h +++ b/include/settings.h @@ -4,8 +4,7 @@ #include -class Settings -{ +class Settings { public: Settings(); bool smartPathsEnabled; diff --git a/include/ui/aboutporymap.h b/include/ui/aboutporymap.h index 5e35032c..3550e206 100644 --- a/include/ui/aboutporymap.h +++ b/include/ui/aboutporymap.h @@ -7,13 +7,13 @@ namespace Ui { class AboutPorymap; } -class AboutPorymap : public QMainWindow -{ +class AboutPorymap : public QMainWindow { public: - explicit AboutPorymap(QWidget *parent = nullptr); + explicit AboutPorymap(QWidget* parent = nullptr); ~AboutPorymap(); + private: - Ui::AboutPorymap *ui; + Ui::AboutPorymap* ui; }; #endif // ABOUTPORYMAP_H diff --git a/include/ui/adjustingstackedwidget.h b/include/ui/adjustingstackedwidget.h index 8de23d11..41498639 100644 --- a/include/ui/adjustingstackedwidget.h +++ b/include/ui/adjustingstackedwidget.h @@ -3,14 +3,12 @@ #include - - -class AdjustingStackedWidget : public QStackedWidget -{ +class AdjustingStackedWidget : public QStackedWidget { Q_OBJECT public: - AdjustingStackedWidget(QWidget *parent = nullptr) : QStackedWidget(parent) {} + AdjustingStackedWidget(QWidget* parent = nullptr) : QStackedWidget(parent) { + } // override this to allow the stacked widget's current page to dictate size virtual void setCurrentIndex(int index) { @@ -18,7 +16,7 @@ public: for (int i = 0; i < this->count(); ++i) { this->widget(i)->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); } - this->widget(index)->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + this->widget(index)->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); } }; diff --git a/include/ui/bordermetatilespixmapitem.h b/include/ui/bordermetatilespixmapitem.h index 870c975e..85731cec 100644 --- a/include/ui/bordermetatilespixmapitem.h +++ b/include/ui/bordermetatilespixmapitem.h @@ -8,17 +8,18 @@ class BorderMetatilesPixmapItem : public QObject, public QGraphicsPixmapItem { Q_OBJECT public: - BorderMetatilesPixmapItem(Map *map_, MetatileSelector *metatileSelector) { + BorderMetatilesPixmapItem(Map* map_, MetatileSelector* metatileSelector) { this->map = map_; this->map->setBorderItem(this); this->metatileSelector = metatileSelector; setAcceptHoverEvents(true); } - MetatileSelector *metatileSelector; - Map *map; + MetatileSelector* metatileSelector; + Map* map; void draw(); signals: void borderMetatilesChanged(); + protected: void mousePressEvent(QGraphicsSceneMouseEvent*); }; diff --git a/include/ui/citymappixmapitem.h b/include/ui/citymappixmapitem.h index 5fe285de..6a329fcc 100644 --- a/include/ui/citymappixmapitem.h +++ b/include/ui/citymappixmapitem.h @@ -14,13 +14,13 @@ private: using QGraphicsPixmapItem::paint; public: - CityMapPixmapItem(QString fname, TilemapTileSelector *tile_selector) { + CityMapPixmapItem(QString fname, TilemapTileSelector* tile_selector) { this->file = fname; this->tile_selector = tile_selector; setAcceptHoverEvents(true); init(); } - TilemapTileSelector *tile_selector; + TilemapTileSelector* tile_selector; QString file; @@ -29,7 +29,7 @@ public: void init(); void save(); void create(QString); - virtual void paint(QGraphicsSceneMouseEvent *); + virtual void paint(QGraphicsSceneMouseEvent*); virtual void draw(); int getIndexAt(int, int); int width(); @@ -43,7 +43,7 @@ private: int height_; signals: - void mouseEvent(QGraphicsSceneMouseEvent *, CityMapPixmapItem *); + void mouseEvent(QGraphicsSceneMouseEvent*, CityMapPixmapItem*); void hoveredRegionMapTileChanged(int x, int y); void hoveredRegionMapTileCleared(); diff --git a/include/ui/collisionpixmapitem.h b/include/ui/collisionpixmapitem.h index bd208c1b..60ffccf2 100644 --- a/include/ui/collisionpixmapitem.h +++ b/include/ui/collisionpixmapitem.h @@ -10,15 +10,16 @@ class CollisionPixmapItem : public MapPixmapItem { Q_OBJECT public: - CollisionPixmapItem(Map *map, MovementPermissionsSelector *movementPermissionsSelector, MetatileSelector *metatileSelector, Settings *settings, qreal *opacity) - : MapPixmapItem(map, metatileSelector, settings){ + CollisionPixmapItem( + Map* map, MovementPermissionsSelector* movementPermissionsSelector, MetatileSelector* metatileSelector, Settings* settings, qreal* opacity) + : MapPixmapItem(map, metatileSelector, settings) { this->movementPermissionsSelector = movementPermissionsSelector; this->opacity = opacity; map->setCollisionItem(this); } - MovementPermissionsSelector *movementPermissionsSelector; - qreal *opacity; - void updateMovementPermissionSelection(QGraphicsSceneMouseEvent *event); + MovementPermissionsSelector* movementPermissionsSelector; + qreal* opacity; + void updateMovementPermissionSelection(QGraphicsSceneMouseEvent* event); virtual void paint(QGraphicsSceneMouseEvent*); virtual void floodFill(QGraphicsSceneMouseEvent*); virtual void magicFill(QGraphicsSceneMouseEvent*); @@ -29,7 +30,7 @@ private: unsigned actionId_ = 0; signals: - void mouseEvent(QGraphicsSceneMouseEvent *, CollisionPixmapItem *); + void mouseEvent(QGraphicsSceneMouseEvent*, CollisionPixmapItem*); void hoveredMapMovementPermissionChanged(int, int); void hoveredMapMovementPermissionCleared(); diff --git a/include/ui/connectionpixmapitem.h b/include/ui/connectionpixmapitem.h index a4cdf4e2..bd01ccc9 100644 --- a/include/ui/connectionpixmapitem.h +++ b/include/ui/connectionpixmapitem.h @@ -8,7 +8,7 @@ class ConnectionPixmapItem : public QObject, public QGraphicsPixmapItem { Q_OBJECT public: - ConnectionPixmapItem(QPixmap pixmap, MapConnection* connection, int x, int y, int baseMapWidth, int baseMapHeight): QGraphicsPixmapItem(pixmap) { + ConnectionPixmapItem(QPixmap pixmap, MapConnection* connection, int x, int y, int baseMapWidth, int baseMapHeight) : QGraphicsPixmapItem(pixmap) { this->basePixmap = pixmap; this->connection = connection; setFlag(ItemIsMovable); @@ -31,7 +31,7 @@ public: int getMaxOffset(); protected: - QVariant itemChange(GraphicsItemChange change, const QVariant &value); + QVariant itemChange(GraphicsItemChange change, const QVariant& value); void mousePressEvent(QGraphicsSceneMouseEvent*); void mouseDoubleClickEvent(QGraphicsSceneMouseEvent*); diff --git a/include/ui/currentselectedmetatilespixmapitem.h b/include/ui/currentselectedmetatilespixmapitem.h index 0bc8e0e3..5d5c1e5b 100644 --- a/include/ui/currentselectedmetatilespixmapitem.h +++ b/include/ui/currentselectedmetatilespixmapitem.h @@ -8,15 +8,17 @@ class CurrentSelectedMetatilesPixmapItem : public QObject, public QGraphicsPixmapItem { Q_OBJECT public: - CurrentSelectedMetatilesPixmapItem(Map *map, MetatileSelector *metatileSelector) { + CurrentSelectedMetatilesPixmapItem(Map* map, MetatileSelector* metatileSelector) { this->map = map; this->metatileSelector = metatileSelector; } Map* map = nullptr; - MetatileSelector *metatileSelector; + MetatileSelector* metatileSelector; void draw(); - void setMap(Map *map) { this->map = map; } + void setMap(Map* map) { + this->map = map; + } }; #endif // CURRENTSELECTEDMETATILESPIXMAPITEM_H diff --git a/include/ui/cursortilerect.h b/include/ui/cursortilerect.h index 5d0c5f15..72fd90b5 100644 --- a/include/ui/cursortilerect.h +++ b/include/ui/cursortilerect.h @@ -5,12 +5,10 @@ #include #include -class CursorTileRect : public QGraphicsItem -{ +class CursorTileRect : public QGraphicsItem { public: - CursorTileRect(bool *enabled, QRgb color); - QRectF boundingRect() const override - { + CursorTileRect(bool* enabled, QRgb color); + QRectF boundingRect() const override { int width = this->width; int height = this->height; if (this->singleTileMode) { @@ -21,15 +19,12 @@ public: height = 32; } qreal penWidth = 4; - return QRectF(-penWidth, - -penWidth, - width + penWidth * 2, - height + penWidth * 2); + return QRectF(-penWidth, -penWidth, width + penWidth * 2, height + penWidth * 2); } - void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) override - { - if (!(*enabled)) return; + void paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*) override { + if (!(*enabled)) + return; int width = this->width; int height = this->height; if (this->singleTileMode) { @@ -51,15 +46,20 @@ public: void initRightClickSelectionAnchor(int coordX, int coordY); void stopRightClickSelectionAnchor(); void setSmartPathMode(bool enable); - bool getSmartPathMode() { return this->smartPathMode; } + bool getSmartPathMode() { + return this->smartPathMode; + } void setStraightPathMode(bool enable); - bool getStraightPathMode() { return this->straightPathMode; } + bool getStraightPathMode() { + return this->straightPathMode; + } void setSingleTileMode(); void stopSingleTileMode(); void updateLocation(int x, int y); void updateSelectionSize(int width, int height); void setVisibility(bool visible); - bool *enabled; + bool* enabled; + private: bool visible; int width; @@ -77,5 +77,4 @@ private: bool smartPathInEffect(); }; - #endif // CURSORTILERECT_H diff --git a/include/ui/customattributestable.h b/include/ui/customattributestable.h index de353b7c..d4401df2 100644 --- a/include/ui/customattributestable.h +++ b/include/ui/customattributestable.h @@ -6,15 +6,14 @@ #include #include -class CustomAttributesTable : public QFrame -{ +class CustomAttributesTable : public QFrame { public: - explicit CustomAttributesTable(Event *event, QWidget *parent = nullptr); + explicit CustomAttributesTable(Event* event, QWidget* parent = nullptr); ~CustomAttributesTable(); private: - Event *event; - QTableWidget *table; + Event* event; + QTableWidget* table; void resizeVertically(); QMap getTableFields(); }; diff --git a/include/ui/draggablepixmapitem.h b/include/ui/draggablepixmapitem.h index 4bbdf982..1fe1f22d 100644 --- a/include/ui/draggablepixmapitem.h +++ b/include/ui/draggablepixmapitem.h @@ -15,18 +15,19 @@ class Editor; class DraggablePixmapItem : public QObject, public QGraphicsPixmapItem { Q_OBJECT public: - DraggablePixmapItem(QPixmap pixmap): QGraphicsPixmapItem(pixmap) {} - - DraggablePixmapItem(Event *event_, Editor *editor_) : QGraphicsPixmapItem(event_->pixmap) { + DraggablePixmapItem(QPixmap pixmap) : QGraphicsPixmapItem(pixmap) { + } + + DraggablePixmapItem(Event* event_, Editor* editor_) : QGraphicsPixmapItem(event_->pixmap) { event = event_; event->setPixmapItem(this); editor = editor_; updatePosition(); } - Editor *editor = nullptr; - Event *event = nullptr; - QGraphicsItemAnimation *pos_anim = nullptr; + Editor* editor = nullptr; + Event* event = nullptr; + QGraphicsItemAnimation* pos_anim = nullptr; bool active; int last_x; @@ -36,11 +37,11 @@ public: void move(int x, int y); void emitPositionChanged(); void updatePixmap(); - void bind(QComboBox *combo, QString key); - void bindToUserData(QComboBox *combo, QString key); + void bind(QComboBox* combo, QString key); + void bindToUserData(QComboBox* combo, QString key); signals: - void positionChanged(Event *event); + void positionChanged(Event* event); void xChanged(int); void yChanged(int); void elevationChanged(int); @@ -48,23 +49,23 @@ signals: void onPropertyChanged(QString key, QString value); public slots: - void set_x(const QString &text) { + void set_x(const QString& text) { event->put("x", text); updatePosition(); } - void set_y(const QString &text) { + void set_y(const QString& text) { event->put("y", text); updatePosition(); } - void set_elevation(const QString &text) { + void set_elevation(const QString& text) { event->put("elevation", text); updatePosition(); } - void set_sprite(const QString &text) { + void set_sprite(const QString& text) { event->put("sprite", text); updatePixmap(); } - void set_script(const QString &text) { + void set_script(const QString& text) { event->put("script_label", text); } diff --git a/include/ui/eventpropertiesframe.h b/include/ui/eventpropertiesframe.h index 7e526ab7..181f9642 100644 --- a/include/ui/eventpropertiesframe.h +++ b/include/ui/eventpropertiesframe.h @@ -9,20 +9,19 @@ namespace Ui { class EventPropertiesFrame; } -class EventPropertiesFrame : public QFrame -{ +class EventPropertiesFrame : public QFrame { Q_OBJECT public: - explicit EventPropertiesFrame(Event *event, QWidget *parent = nullptr); + explicit EventPropertiesFrame(Event* event, QWidget* parent = nullptr); ~EventPropertiesFrame(); void paintEvent(QPaintEvent*); public: - Ui::EventPropertiesFrame *ui; + Ui::EventPropertiesFrame* ui; private: - Event *event; + Event* event; bool firstShow = true; }; diff --git a/include/ui/filterchildrenproxymodel.h b/include/ui/filterchildrenproxymodel.h index b73cbd62..f1774e36 100644 --- a/include/ui/filterchildrenproxymodel.h +++ b/include/ui/filterchildrenproxymodel.h @@ -3,15 +3,14 @@ #include -class FilterChildrenProxyModel : public QSortFilterProxyModel -{ +class FilterChildrenProxyModel : public QSortFilterProxyModel { Q_OBJECT public: - explicit FilterChildrenProxyModel(QObject *parent = nullptr); -protected: - bool filterAcceptsRow(int source_row, const QModelIndex & source_parent) const; + explicit FilterChildrenProxyModel(QObject* parent = nullptr); +protected: + bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const; }; #endif // FILTERCHILDRENPROXYMODEL_H diff --git a/include/ui/flowlayout.h b/include/ui/flowlayout.h index 6364dfd0..2afc2436 100644 --- a/include/ui/flowlayout.h +++ b/include/ui/flowlayout.h @@ -4,32 +4,30 @@ #include #include - -class FlowLayout : public QLayout -{ +class FlowLayout : public QLayout { public: - explicit FlowLayout(QWidget *parent, int margin = -1, int hSpacing = -1, int vSpacing = -1); + explicit FlowLayout(QWidget* parent, int margin = -1, int hSpacing = -1, int vSpacing = -1); explicit FlowLayout(int margin = -1, int hSpacing = -1, int vSpacing = -1); ~FlowLayout(); - void addItem(QLayoutItem *item) override; + void addItem(QLayoutItem* item) override; int horizontalSpacing() const; int verticalSpacing() const; Qt::Orientations expandingDirections() const override; bool hasHeightForWidth() const override; int heightForWidth(int) const override; int count() const override; - QLayoutItem *itemAt(int index) const override; + QLayoutItem* itemAt(int index) const override; QSize minimumSize() const override; - void setGeometry(const QRect &rect) override; + void setGeometry(const QRect& rect) override; QSize sizeHint() const override; - QLayoutItem *takeAt(int index) override; + QLayoutItem* takeAt(int index) override; private: - int doLayout(const QRect &rect, bool testOnly) const; + int doLayout(const QRect& rect, bool testOnly) const; int smartSpacing(QStyle::PixelMetric pm) const; - QList itemList; + QList itemList; int horzSpace; int vertSpace; }; diff --git a/include/ui/graphicsview.h b/include/ui/graphicsview.h index 960f7dc4..5d4190ee 100644 --- a/include/ui/graphicsview.h +++ b/include/ui/graphicsview.h @@ -7,24 +7,26 @@ class Editor; -class GraphicsView : public QGraphicsView -{ +class GraphicsView : public QGraphicsView { public: - GraphicsView() : QGraphicsView() {} - GraphicsView(QWidget *parent) : QGraphicsView(parent) {} + GraphicsView() : QGraphicsView() { + } + GraphicsView(QWidget* parent) : QGraphicsView(parent) { + } public: -// GraphicsView_Object object; - Editor *editor; + // GraphicsView_Object object; + Editor* editor; Overlay overlay; + protected: - void mousePressEvent(QMouseEvent *event); - void mouseMoveEvent(QMouseEvent *event); - void mouseReleaseEvent(QMouseEvent *event); - void drawForeground(QPainter *painter, const QRectF &rect); - void moveEvent(QMoveEvent *event); + void mousePressEvent(QMouseEvent* event); + void mouseMoveEvent(QMouseEvent* event); + void mouseReleaseEvent(QMouseEvent* event); + void drawForeground(QPainter* painter, const QRectF& rect); + void moveEvent(QMoveEvent* event); }; -//Q_DECLARE_METATYPE(GraphicsView) +// Q_DECLARE_METATYPE(GraphicsView) #endif // GRAPHICSVIEW_H diff --git a/include/ui/imageproviders.h b/include/ui/imageproviders.h index c90ce995..4e42b197 100644 --- a/include/ui/imageproviders.h +++ b/include/ui/imageproviders.h @@ -11,24 +11,11 @@ QImage getCollisionMetatileImage(int, int); QImage getMetatileImage(uint16_t, Tileset*, Tileset*, QList, QList, bool useTruePalettes = false); QImage getTileImage(uint16_t, Tileset*, Tileset*); QImage getPalettedTileImage(uint16_t, Tileset*, Tileset*, int, bool useTruePalettes = false); -QImage getGreyscaleTileImage(uint16_t tile, Tileset *primaryTileset, Tileset *secondaryTileset); +QImage getGreyscaleTileImage(uint16_t tile, Tileset* primaryTileset, Tileset* secondaryTileset); static QList greyscalePalette({ - qRgb(0, 0, 0), - qRgb(16, 16, 16), - qRgb(32, 32, 32), - qRgb(48, 48, 48), - qRgb(64, 64, 64), - qRgb(80, 80, 80), - qRgb(96, 96, 96), - qRgb(112, 112, 112), - qRgb(128, 128, 128), - qRgb(144, 144, 144), - qRgb(160, 160, 160), - qRgb(176, 176, 176), - qRgb(192, 192, 192), - qRgb(208, 208, 208), - qRgb(224, 224, 224), + qRgb(0, 0, 0), qRgb(16, 16, 16), qRgb(32, 32, 32), qRgb(48, 48, 48), qRgb(64, 64, 64), qRgb(80, 80, 80), qRgb(96, 96, 96), qRgb(112, 112, 112), + qRgb(128, 128, 128), qRgb(144, 144, 144), qRgb(160, 160, 160), qRgb(176, 176, 176), qRgb(192, 192, 192), qRgb(208, 208, 208), qRgb(224, 224, 224), qRgb(240, 240, 240), }); diff --git a/include/ui/mapimageexporter.h b/include/ui/mapimageexporter.h index 6d8ae643..af51a3e3 100644 --- a/include/ui/mapimageexporter.h +++ b/include/ui/mapimageexporter.h @@ -16,20 +16,19 @@ enum ImageExporterMode { Timelapse, }; -class MapImageExporter : public QDialog -{ +class MapImageExporter : public QDialog { Q_OBJECT public: - explicit MapImageExporter(QWidget *parent, Editor *editor, ImageExporterMode mode); + explicit MapImageExporter(QWidget* parent, Editor* editor, ImageExporterMode mode); ~MapImageExporter(); private: - Ui::MapImageExporter *ui; + Ui::MapImageExporter* ui; - Map *map = nullptr; - Editor *editor = nullptr; - QGraphicsScene *scene = nullptr; + Map* map = nullptr; + Editor* editor = nullptr; + QGraphicsScene* scene = nullptr; QPixmap preview; @@ -51,9 +50,9 @@ private: void updatePreview(); void saveImage(); - QPixmap getStitchedImage(QProgressDialog *progress, bool includeBorder); - QPixmap getFormattedMapPixmap(Map *map, bool ignoreBorder); - bool historyItemAppliesToFrame(const QUndoCommand *command); + QPixmap getStitchedImage(QProgressDialog* progress, bool includeBorder); + QPixmap getFormattedMapPixmap(Map* map, bool ignoreBorder); + bool historyItemAppliesToFrame(const QUndoCommand* command); private slots: void on_checkBox_Objects_stateChanged(int state); diff --git a/include/ui/mappixmapitem.h b/include/ui/mappixmapitem.h index e9d999b4..3fd367b1 100644 --- a/include/ui/mappixmapitem.h +++ b/include/ui/mappixmapitem.h @@ -13,12 +13,8 @@ private: using QGraphicsPixmapItem::paint; public: - enum class PaintMode { - Disabled, - Metatiles, - EventObjects - }; - MapPixmapItem(Map *map_, MetatileSelector *metatileSelector, Settings *settings) { + enum class PaintMode { Disabled, Metatiles, EventObjects }; + MapPixmapItem(Map* map_, MetatileSelector* metatileSelector, Settings* settings) { this->map = map_; this->map->setMapItem(this); this->metatileSelector = metatileSelector; @@ -29,9 +25,9 @@ public: setAcceptHoverEvents(true); } MapPixmapItem::PaintMode paintingMode; - Map *map; - MetatileSelector *metatileSelector; - Settings *settings; + Map* map; + MetatileSelector* metatileSelector; + Settings* settings; bool active; bool has_mouse = false; bool right_click; @@ -40,11 +36,7 @@ public: bool prevStraightPathState; int straight_path_initial_x; int straight_path_initial_y; - enum Axis { - None = 0, - X, - Y - }; + enum Axis { None = 0, X, Y }; MapPixmapItem::Axis lockedAxis; QPoint selection_origin; QList selection; @@ -53,30 +45,21 @@ public: virtual void magicFill(QGraphicsSceneMouseEvent*); void magicFill(int x, int y, uint16_t metatileId, bool fromScriptCall = false); void magicFill(int x, int y, bool fromScriptCall = false); - void magicFill( - int initialX, - int initialY, - QPoint selectionDimensions, - QList *selectedMetatiles, - QList> *selectedCollisions, - bool fromScriptCall = false); + void magicFill(int initialX, int initialY, QPoint selectionDimensions, QList* selectedMetatiles, + QList>* selectedCollisions, bool fromScriptCall = false); void floodFill(int x, int y, bool fromScriptCall = false); void floodFill(int x, int y, uint16_t metatileId, bool fromScriptCall = false); - void floodFill(int initialX, - int initialY, - QPoint selectionDimensions, - QList *selectedMetatiles, - QList> *selectedCollisions, - bool fromScriptCall = false); + void floodFill(int initialX, int initialY, QPoint selectionDimensions, QList* selectedMetatiles, + QList>* selectedCollisions, bool fromScriptCall = false); void floodFillSmartPath(int initialX, int initialY, bool fromScriptCall = false); virtual void pick(QGraphicsSceneMouseEvent*); virtual void select(QGraphicsSceneMouseEvent*); virtual void shift(QGraphicsSceneMouseEvent*); void shift(int xDelta, int yDelta, bool fromScriptCall = false); virtual void draw(bool ignoreCache = false); - void updateMetatileSelection(QGraphicsSceneMouseEvent *event); + void updateMetatileSelection(QGraphicsSceneMouseEvent* event); void paintNormal(int x, int y, bool fromScriptCall = false); - void lockNondominantAxis(QGraphicsSceneMouseEvent *event); + void lockNondominantAxis(QGraphicsSceneMouseEvent* event); QPoint adjustCoords(QPoint pos); private: @@ -86,10 +69,10 @@ private: unsigned actionId_ = 0; signals: - void startPaint(QGraphicsSceneMouseEvent *, MapPixmapItem *); - void endPaint(QGraphicsSceneMouseEvent *, MapPixmapItem *); - void mouseEvent(QGraphicsSceneMouseEvent *, MapPixmapItem *); - void hoveredMapMetatileChanged(const QPoint &pos); + void startPaint(QGraphicsSceneMouseEvent*, MapPixmapItem*); + void endPaint(QGraphicsSceneMouseEvent*, MapPixmapItem*); + void mouseEvent(QGraphicsSceneMouseEvent*, MapPixmapItem*); + void hoveredMapMetatileChanged(const QPoint& pos); void hoveredMapMetatileCleared(); protected: diff --git a/include/ui/mapruler.h b/include/ui/mapruler.h index 151492e3..a47b503d 100644 --- a/include/ui/mapruler.h +++ b/include/ui/mapruler.h @@ -4,9 +4,7 @@ #include #include - -class MapRuler : public QGraphicsObject, private QLine -{ +class MapRuler : public QGraphicsObject, private QLine { Q_OBJECT public: @@ -15,35 +13,55 @@ public: QRectF boundingRect() const override; QPainterPath shape() const override; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) override; - bool eventFilter(QObject *, QEvent *event) override; + void paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*) override; + bool eventFilter(QObject*, QEvent* event) override; - bool isAnchored() const { return anchored; } - bool isLocked() const { return locked; } + bool isAnchored() const { + return anchored; + } + bool isLocked() const { + return locked; + } // Ruler start point in metatiles - QPoint anchor() const { return QLine::p1(); } + QPoint anchor() const { + return QLine::p1(); + } // Ruler end point in metatiles - QPoint endPos() const { return QLine::p2(); } + QPoint endPos() const { + return QLine::p2(); + } // X-coordinate of the ruler's left edge in metatiles - int left() const { return qMin(anchor().x(), endPos().x()); } + int left() const { + return qMin(anchor().x(), endPos().x()); + } // Y-coordinate of the ruler's top edge in metatiles - int top() const { return qMin(anchor().y(), endPos().y()); } + int top() const { + return qMin(anchor().y(), endPos().y()); + } // Horizontal component of the ruler in metatiles - int deltaX() const { return QLine::dx(); } + int deltaX() const { + return QLine::dx(); + } // Vertical component of the ruler in metatiles - int deltaY() const { return QLine::dy(); } + int deltaY() const { + return QLine::dy(); + } // Ruler width in metatiles - int width() const { return qAbs(deltaX()); } + int width() const { + return qAbs(deltaX()); + } // Ruler height in metatiles - int height() const { return qAbs(deltaY()); } + int height() const { + return qAbs(deltaY()); + } public slots: - void mouseEvent(QGraphicsSceneMouseEvent *event); - void setMapDimensions(const QSize &size); + void mouseEvent(QGraphicsSceneMouseEvent* event); + void setMapDimensions(const QSize& size); signals: - void statusChanged(const QString &statusMessage); + void statusChanged(const QString& statusMessage); private: const int thickness; @@ -58,13 +76,17 @@ private: bool locked; void reset(); - void setAnchor(const QPointF &scenePos); - void setEndPos(const QPointF &scenePos); + void setAnchor(const QPointF& scenePos); + void setEndPos(const QPointF& scenePos); QPoint snapToWithinBounds(QPoint pos) const; void updateGeometry(); void updateStatus(Qt::Corner corner); - int pixWidth() const { return width() * 16; } - int pixHeight() const { return height() * 16; } + int pixWidth() const { + return width() * 16; + } + int pixHeight() const { + return height() * 16; + } }; #endif // MAPRULER_H diff --git a/include/ui/mapsceneeventfilter.h b/include/ui/mapsceneeventfilter.h index 7de427e3..76f9ff22 100644 --- a/include/ui/mapsceneeventfilter.h +++ b/include/ui/mapsceneeventfilter.h @@ -3,13 +3,13 @@ #include -class MapSceneEventFilter : public QObject -{ +class MapSceneEventFilter : public QObject { Q_OBJECT protected: - bool eventFilter(QObject *obj, QEvent *event) override; + bool eventFilter(QObject* obj, QEvent* event) override; + public: - explicit MapSceneEventFilter(QObject *parent = nullptr); + explicit MapSceneEventFilter(QObject* parent = nullptr); signals: void wheelZoom(int delta); diff --git a/include/ui/metatilelayersitem.h b/include/ui/metatilelayersitem.h index 87c6f066..5b5e2e76 100644 --- a/include/ui/metatilelayersitem.h +++ b/include/ui/metatilelayersitem.h @@ -6,10 +6,10 @@ #include #include -class MetatileLayersItem: public SelectablePixmapItem { +class MetatileLayersItem : public SelectablePixmapItem { Q_OBJECT public: - MetatileLayersItem(Metatile *metatile, Tileset *primaryTileset, Tileset *secondaryTileset): SelectablePixmapItem(16, 16, 6, 2) { + MetatileLayersItem(Metatile* metatile, Tileset* primaryTileset, Tileset* secondaryTileset) : SelectablePixmapItem(16, 16, 6, 2) { this->metatile = metatile; this->primaryTileset = primaryTileset; this->secondaryTileset = secondaryTileset; @@ -19,15 +19,17 @@ public: void setTilesets(Tileset*, Tileset*); void setMetatile(Metatile*); void clearLastModifiedCoords(); + private: Metatile* metatile; - Tileset *primaryTileset; - Tileset *secondaryTileset; + Tileset* primaryTileset; + Tileset* secondaryTileset; QPoint prevChangedTile; void getBoundedCoords(QPointF, int*, int*); signals: void tileChanged(int, int); void selectedTilesChanged(QPoint, int, int); + protected: void mousePressEvent(QGraphicsSceneMouseEvent*); void mouseMoveEvent(QGraphicsSceneMouseEvent*); diff --git a/include/ui/metatileselector.h b/include/ui/metatileselector.h index 321343d6..857445bb 100644 --- a/include/ui/metatileselector.h +++ b/include/ui/metatileselector.h @@ -7,10 +7,10 @@ #include "tileset.h" #include "maplayout.h" -class MetatileSelector: public SelectablePixmapItem { +class MetatileSelector : public SelectablePixmapItem { Q_OBJECT public: - MetatileSelector(int numMetatilesWide, Map *map): SelectablePixmapItem(16, 16) { + MetatileSelector(int numMetatilesWide, Map* map) : SelectablePixmapItem(16, 16) { this->externalSelection = false; this->numMetatilesWide = numMetatilesWide; this->map = map; @@ -31,23 +31,25 @@ public: void setExternalSelection(int, int, QList, QList>); QPoint getMetatileIdCoordsOnWidget(uint16_t); void setMap(Map*); + protected: void mousePressEvent(QGraphicsSceneMouseEvent*); void mouseMoveEvent(QGraphicsSceneMouseEvent*); void mouseReleaseEvent(QGraphicsSceneMouseEvent*); void hoverMoveEvent(QGraphicsSceneHoverEvent*); void hoverLeaveEvent(QGraphicsSceneHoverEvent*); + private: bool externalSelection; int numMetatilesWide; - Map *map; - Tileset *primaryTileset; - Tileset *secondaryTileset; - QList *selectedMetatiles; - QList> *selectedCollisions; + Map* map; + Tileset* primaryTileset; + Tileset* secondaryTileset; + QList* selectedMetatiles; + QList>* selectedCollisions; int externalSelectionWidth; int externalSelectionHeight; - QList *externalSelectedMetatiles; + QList* externalSelectedMetatiles; void updateSelectedMetatiles(); uint16_t getMetatileId(int x, int y); diff --git a/include/ui/montabwidget.h b/include/ui/montabwidget.h index c5aaab9a..f3978574 100644 --- a/include/ui/montabwidget.h +++ b/include/ui/montabwidget.h @@ -13,29 +13,29 @@ class MonTabWidget : public QTabWidget { Q_OBJECT public: - explicit MonTabWidget(Editor *editor = nullptr, QWidget *parent = nullptr); + explicit MonTabWidget(Editor* editor = nullptr, QWidget* parent = nullptr); ~MonTabWidget(){}; void populate(); void populateTab(int tabIndex, WildMonInfo monInfo, QString fieldName); void clear(); - void createSpeciesTableRow(QTableWidget *table, WildPokemon mon, int index, QString fieldName); + void createSpeciesTableRow(QTableWidget* table, WildPokemon mon, int index, QString fieldName); void clearTableAt(int index); - QTableWidget *tableAt(int tabIndex); + QTableWidget* tableAt(int tabIndex); public slots: void setTabActive(int index, bool active = true); private: - bool eventFilter(QObject *object, QEvent *event); + bool eventFilter(QObject* object, QEvent* event); void askActivateTab(int tabIndex, QPoint menuPos); QVector activeTabs; - Editor *editor; + Editor* editor; }; #endif // MONTABWIDGET_H diff --git a/include/ui/movablerect.h b/include/ui/movablerect.h index f73e360a..685d2522 100644 --- a/include/ui/movablerect.h +++ b/include/ui/movablerect.h @@ -5,21 +5,15 @@ #include #include -class MovableRect : public QGraphicsItem -{ +class MovableRect : public QGraphicsItem { public: - MovableRect(bool *enabled, int width, int height, QRgb color); - QRectF boundingRect() const override - { + MovableRect(bool* enabled, int width, int height, QRgb color); + QRectF boundingRect() const override { qreal penWidth = 4; - return QRectF(-penWidth, - -penWidth, - 30 * 8 + penWidth * 2, - 20 * 8 + penWidth * 2); + return QRectF(-penWidth, -penWidth, 30 * 8 + penWidth * 2, 20 * 8 + penWidth * 2); } - void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) override - { + void paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*) override { painter->setPen(this->color); painter->drawRect(-2, -2, this->width + 3, this->height + 3); painter->setPen(QColor(0, 0, 0)); @@ -27,7 +21,8 @@ public: painter->drawRect(-1, -1, this->width + 1, this->height + 1); } void updateLocation(int x, int y); - bool *enabled; + bool* enabled; + private: int width; int height; diff --git a/include/ui/movementpermissionsselector.h b/include/ui/movementpermissionsselector.h index a962f01a..cf97acab 100644 --- a/include/ui/movementpermissionsselector.h +++ b/include/ui/movementpermissionsselector.h @@ -3,10 +3,10 @@ #include "selectablepixmapitem.h" -class MovementPermissionsSelector: public SelectablePixmapItem { +class MovementPermissionsSelector : public SelectablePixmapItem { Q_OBJECT public: - MovementPermissionsSelector(): SelectablePixmapItem(32, 32, 1, 1) { + MovementPermissionsSelector() : SelectablePixmapItem(32, 32, 1, 1) { setAcceptHoverEvents(true); } void draw(); diff --git a/include/ui/multikeyedit.h b/include/ui/multikeyedit.h index 27231330..f1061ffd 100644 --- a/include/ui/multikeyedit.h +++ b/include/ui/multikeyedit.h @@ -6,39 +6,37 @@ class QLineEdit; - // A collection of QKeySequenceEdit's laid out horizontally. -class MultiKeyEdit : public QWidget -{ +class MultiKeyEdit : public QWidget { Q_OBJECT public: - MultiKeyEdit(QWidget *parent = nullptr, int fieldCount = 2); + MultiKeyEdit(QWidget* parent = nullptr, int fieldCount = 2); - bool eventFilter(QObject *watched, QEvent *event) override; + bool eventFilter(QObject* watched, QEvent* event) override; int fieldCount() const; void setFieldCount(int count); QList keySequences() const; - bool removeOne(const QKeySequence &keySequence); - bool contains(const QKeySequence &keySequence) const; + bool removeOne(const QKeySequence& keySequence); + bool contains(const QKeySequence& keySequence) const; void setContextMenuPolicy(Qt::ContextMenuPolicy policy); bool isClearButtonEnabled() const; void setClearButtonEnabled(bool enable); public slots: void clear(); - void setKeySequences(const QList &keySequences); - void addKeySequence(const QKeySequence &keySequence); + void setKeySequences(const QList& keySequences); + void addKeySequence(const QKeySequence& keySequence); signals: - void keySequenceChanged(const QKeySequence &keySequence); + void keySequenceChanged(const QKeySequence& keySequence); void editingFinished(); - void customContextMenuRequested(const QPoint &pos); + void customContextMenuRequested(const QPoint& pos); private: - QVector keySequenceEdit_vec; - QList keySequence_list; // Used to track changes + QVector keySequenceEdit_vec; + QList keySequence_list; // Used to track changes void addNewKeySequenceEdit(); void alignKeySequencesLeft(); @@ -46,7 +44,7 @@ private: private slots: void onEditingFinished(); - void showDefaultContextMenu(QLineEdit *lineEdit, const QPoint &pos); + void showDefaultContextMenu(QLineEdit* lineEdit, const QPoint& pos); }; #endif // MULTIKEYEDIT_H diff --git a/include/ui/neweventtoolbutton.h b/include/ui/neweventtoolbutton.h index 1168d447..4eba3812 100644 --- a/include/ui/neweventtoolbutton.h +++ b/include/ui/neweventtoolbutton.h @@ -4,20 +4,19 @@ #include "event.h" #include -class NewEventToolButton : public QToolButton -{ +class NewEventToolButton : public QToolButton { Q_OBJECT public: - explicit NewEventToolButton(QWidget *parent = nullptr); + explicit NewEventToolButton(QWidget* parent = nullptr); QString getSelectedEventType(); - QAction *newObjectAction; - QAction *newWarpAction; - QAction *newHealLocationAction; - QAction *newTriggerAction; - QAction *newWeatherTriggerAction; - QAction *newSignAction; - QAction *newHiddenItemAction; - QAction *newSecretBaseAction; + QAction* newObjectAction; + QAction* newWarpAction; + QAction* newHealLocationAction; + QAction* newTriggerAction; + QAction* newWeatherTriggerAction; + QAction* newSignAction; + QAction* newHiddenItemAction; + QAction* newSecretBaseAction; public slots: void newObject(); void newWarp(); @@ -29,6 +28,7 @@ public slots: void newSecretBase(); signals: void newEventAdded(QString); + private: QString selectedEventType; void init(); diff --git a/include/ui/newmappopup.h b/include/ui/newmappopup.h index c573b16e..e3d0407c 100644 --- a/include/ui/newmappopup.h +++ b/include/ui/newmappopup.h @@ -11,13 +11,12 @@ namespace Ui { class NewMapPopup; } -class NewMapPopup : public QMainWindow -{ +class NewMapPopup : public QMainWindow { Q_OBJECT public: - explicit NewMapPopup(QWidget *parent = nullptr, Project *project = nullptr); + explicit NewMapPopup(QWidget* parent = nullptr, Project* project = nullptr); ~NewMapPopup(); - Map *map; + Map* map; int group; bool existingLayout; QString layoutId; @@ -29,14 +28,14 @@ signals: void applied(); private: - Ui::NewMapPopup *ui; - Project *project; + Ui::NewMapPopup* ui; + Project* project; void setDefaultValues(int, QString); bool checkNewMapDimensions(); private slots: void on_pushButton_NewMap_Accept_clicked(); - void on_lineEdit_NewMap_Name_textChanged(const QString &); + void on_lineEdit_NewMap_Name_textChanged(const QString&); }; #endif // NEWMAPPOPUP_H diff --git a/include/ui/newtilesetdialog.h b/include/ui/newtilesetdialog.h index a292c67e..2c3fc8a9 100644 --- a/include/ui/newtilesetdialog.h +++ b/include/ui/newtilesetdialog.h @@ -8,12 +8,11 @@ namespace Ui { class NewTilesetDialog; } -class NewTilesetDialog : public QDialog -{ +class NewTilesetDialog : public QDialog { Q_OBJECT public: - explicit NewTilesetDialog(Project *project, QWidget *parent = nullptr); + explicit NewTilesetDialog(Project* project, QWidget* parent = nullptr); ~NewTilesetDialog(); QString path; QString fullSymbolName; @@ -25,8 +24,8 @@ private slots: void SecondaryChanged(); private: - Ui::NewTilesetDialog *ui; - Project *project = nullptr; + Ui::NewTilesetDialog* ui; + Project* project = nullptr; }; #endif // NEWTILESETDIALOG_H diff --git a/include/ui/noscrollcombobox.h b/include/ui/noscrollcombobox.h index 1291c7e9..1d368cb0 100644 --- a/include/ui/noscrollcombobox.h +++ b/include/ui/noscrollcombobox.h @@ -3,13 +3,12 @@ #include -class NoScrollComboBox : public QComboBox -{ +class NoScrollComboBox : public QComboBox { Q_OBJECT public: - explicit NoScrollComboBox(QWidget *parent = nullptr); - void wheelEvent(QWheelEvent *event); + explicit NoScrollComboBox(QWidget* parent = nullptr); + void wheelEvent(QWheelEvent* event); private: }; diff --git a/include/ui/noscrollspinbox.h b/include/ui/noscrollspinbox.h index 0cc11043..47e06b05 100644 --- a/include/ui/noscrollspinbox.h +++ b/include/ui/noscrollspinbox.h @@ -3,14 +3,13 @@ #include -class NoScrollSpinBox : public QSpinBox -{ +class NoScrollSpinBox : public QSpinBox { Q_OBJECT public: - explicit NoScrollSpinBox(QWidget *parent = nullptr); - void wheelEvent(QWheelEvent *event) override; - void focusOutEvent(QFocusEvent *event) override; + explicit NoScrollSpinBox(QWidget* parent = nullptr); + void wheelEvent(QWheelEvent* event) override; + void focusOutEvent(QFocusEvent* event) override; unsigned getActionId(); diff --git a/include/ui/overlay.h b/include/ui/overlay.h index 87be19bd..84ed9297 100644 --- a/include/ui/overlay.h +++ b/include/ui/overlay.h @@ -8,9 +8,10 @@ class OverlayItem { public: - OverlayItem() {} - virtual ~OverlayItem() {}; - virtual void render(QPainter *) {}; + OverlayItem() { + } + virtual ~OverlayItem(){}; + virtual void render(QPainter*){}; }; class OverlayText : public OverlayItem { @@ -22,8 +23,10 @@ public: this->color = color; this->fontSize = fontSize; } - ~OverlayText() {} - virtual void render(QPainter *painter); + ~OverlayText() { + } + virtual void render(QPainter* painter); + private: QString text; int x; @@ -42,8 +45,10 @@ public: this->color = color; this->filled = filled; } - ~OverlayRect() {} - virtual void render(QPainter *painter); + ~OverlayRect() { + } + virtual void render(QPainter* painter); + private: int x; int y; @@ -60,18 +65,20 @@ public: this->y = y; this->image = image; } - ~OverlayImage() {} - virtual void render(QPainter *painter); + ~OverlayImage() { + } + virtual void render(QPainter* painter); + private: int x; int y; QImage image; }; -class Overlay -{ +class Overlay { public: - Overlay() {} + Overlay() { + } ~Overlay() { this->clearItems(); } @@ -80,6 +87,7 @@ public: void addText(QString text, int x, int y, QString color = "#000000", int fontSize = 12); void addRect(int x, int y, int width, int height, QString color = "#000000", bool filled = false); void addImage(int x, int y, QString filepath); + private: QList items; }; diff --git a/include/ui/paletteeditor.h b/include/ui/paletteeditor.h index 2dbd6d29..a68ecec5 100644 --- a/include/ui/paletteeditor.h +++ b/include/ui/paletteeditor.h @@ -20,22 +20,22 @@ public: } }; -class PaletteEditor : public QMainWindow { +class PaletteEditor : public QMainWindow { Q_OBJECT public: - explicit PaletteEditor(Project*, Tileset*, Tileset*, int paletteId, QWidget *parent = nullptr); + explicit PaletteEditor(Project*, Tileset*, Tileset*, int paletteId, QWidget* parent = nullptr); ~PaletteEditor(); void setPaletteId(int); void setTilesets(Tileset*, Tileset*); private: - Ui::PaletteEditor *ui; - Project *project = nullptr; + Ui::PaletteEditor* ui; + Project* project = nullptr; QList> sliders; QList frames; QList rgbLabels; - Tileset *primaryTileset; - Tileset *secondaryTileset; + Tileset* primaryTileset; + Tileset* secondaryTileset; QList> palettesHistory; void disableSliderSignals(); void enableSliderSignals(); diff --git a/include/ui/preferenceeditor.h b/include/ui/preferenceeditor.h index c16716d9..b9c1606f 100644 --- a/include/ui/preferenceeditor.h +++ b/include/ui/preferenceeditor.h @@ -6,32 +6,30 @@ class NoScrollComboBox; class QAbstractButton; - namespace Ui { class PreferenceEditor; } -class PreferenceEditor : public QMainWindow -{ +class PreferenceEditor : public QMainWindow { Q_OBJECT public: - explicit PreferenceEditor(QWidget *parent = nullptr); + explicit PreferenceEditor(QWidget* parent = nullptr); ~PreferenceEditor(); signals: void preferencesSaved(); - void themeChanged(const QString &theme); + void themeChanged(const QString& theme); private: - Ui::PreferenceEditor *ui; - NoScrollComboBox *themeSelector; + Ui::PreferenceEditor* ui; + NoScrollComboBox* themeSelector; void populateFields(); void saveFields(); private slots: - void dialogButtonClicked(QAbstractButton *button); + void dialogButtonClicked(QAbstractButton* button); }; #endif // PREFERENCES_H diff --git a/include/ui/regionmapeditor.h b/include/ui/regionmapeditor.h index cba14251..fa97cb2e 100644 --- a/include/ui/regionmapeditor.h +++ b/include/ui/regionmapeditor.h @@ -16,15 +16,14 @@ namespace Ui { class RegionMapEditor; } -class RegionMapEditor : public QMainWindow -{ +class RegionMapEditor : public QMainWindow { Q_OBJECT public: - explicit RegionMapEditor(QWidget *parent = 0, Project *pro = nullptr); + explicit RegionMapEditor(QWidget* parent = 0, Project* pro = nullptr); ~RegionMapEditor(); - RegionMap *region_map; + RegionMap* region_map; bool loadRegionMapData(); bool loadCityMaps(); @@ -39,7 +38,7 @@ public: void onRegionMapLayoutHoveredTileChanged(int index); void onRegionMapLayoutHoveredTileCleared(); - void onRegionMapEntriesSelectedTileChanged(QString) {}; + void onRegionMapEntriesSelectedTileChanged(QString){}; void onRegionMapEntryDragged(int, int); void undo(); @@ -53,8 +52,8 @@ public slots: void applyUserShortcuts(); private: - Ui::RegionMapEditor *ui; - Project *project; + Ui::RegionMapEditor* ui; + Project* project; History history; @@ -71,20 +70,20 @@ private: double scaleUpFactor = 2.0; double initialScale = 30.0; - QGraphicsScene *scene_region_map_image = nullptr; - QGraphicsScene *scene_city_map_image = nullptr; - QGraphicsScene *scene_region_map_layout = nullptr; - QGraphicsScene *scene_region_map_entries = nullptr; - QGraphicsScene *scene_region_map_tiles = nullptr; - QGraphicsScene *scene_city_map_tiles = nullptr; + QGraphicsScene* scene_region_map_image = nullptr; + QGraphicsScene* scene_city_map_image = nullptr; + QGraphicsScene* scene_region_map_layout = nullptr; + QGraphicsScene* scene_region_map_entries = nullptr; + QGraphicsScene* scene_region_map_tiles = nullptr; + QGraphicsScene* scene_city_map_tiles = nullptr; - TilemapTileSelector *mapsquare_selector_item = nullptr; - TilemapTileSelector *city_map_selector_item = nullptr; + TilemapTileSelector* mapsquare_selector_item = nullptr; + TilemapTileSelector* city_map_selector_item = nullptr; - RegionMapEntriesPixmapItem *region_map_entries_item = nullptr; - RegionMapLayoutPixmapItem *region_map_layout_item = nullptr; - RegionMapPixmapItem *region_map_item = nullptr; - CityMapPixmapItem *city_map_item = nullptr; + RegionMapEntriesPixmapItem* region_map_entries_item = nullptr; + RegionMapLayoutPixmapItem* region_map_layout_item = nullptr; + RegionMapPixmapItem* region_map_item = nullptr; + CityMapPixmapItem* city_map_item = nullptr; void initShortcuts(); void displayRegionMap(); @@ -118,8 +117,8 @@ private slots: void on_action_Import_CityMap_ImageTiles_triggered(); void on_tabWidget_Region_Map_currentChanged(int); void on_pushButton_RM_Options_delete_clicked(); - void on_comboBox_RM_ConnectedMap_activated(const QString &); - void on_comboBox_RM_Entry_MapSection_activated(const QString &); + void on_comboBox_RM_ConnectedMap_activated(const QString&); + void on_comboBox_RM_Entry_MapSection_activated(const QString&); void on_spinBox_RM_Entry_x_valueChanged(int); void on_spinBox_RM_Entry_y_valueChanged(int); void on_spinBox_RM_Entry_width_valueChanged(int); @@ -129,12 +128,12 @@ private slots: void on_verticalSlider_Zoom_Image_Tiles_valueChanged(int); void on_verticalSlider_Zoom_City_Map_valueChanged(int); void on_verticalSlider_Zoom_City_Tiles_valueChanged(int); - void on_comboBox_CityMap_picker_currentTextChanged(const QString &); - void on_lineEdit_RM_MapName_textEdited(const QString &); + void on_comboBox_CityMap_picker_currentTextChanged(const QString&); + void on_lineEdit_RM_MapName_textEdited(const QString&); void onHoveredRegionMapTileChanged(int x, int y); void onHoveredRegionMapTileCleared(); - void mouseEvent_region_map(QGraphicsSceneMouseEvent *event, RegionMapPixmapItem *item); - void mouseEvent_city_map(QGraphicsSceneMouseEvent *event, CityMapPixmapItem *item); + void mouseEvent_region_map(QGraphicsSceneMouseEvent* event, RegionMapPixmapItem* item); + void mouseEvent_city_map(QGraphicsSceneMouseEvent* event, CityMapPixmapItem* item); }; #endif // REGIONMAPEDITOR_H diff --git a/include/ui/regionmapentriespixmapitem.h b/include/ui/regionmapentriespixmapitem.h index 12808c33..0f443c68 100644 --- a/include/ui/regionmapentriespixmapitem.h +++ b/include/ui/regionmapentriespixmapitem.h @@ -7,12 +7,12 @@ class RegionMapEntriesPixmapItem : public SelectablePixmapItem { Q_OBJECT public: - RegionMapEntriesPixmapItem(RegionMap *rm, TilemapTileSelector *ts) : SelectablePixmapItem(8, 8, 1, 1) { - this->region_map = rm; - this->tile_selector = ts; + RegionMapEntriesPixmapItem(RegionMap* rm, TilemapTileSelector* ts) : SelectablePixmapItem(8, 8, 1, 1) { + this->region_map = rm; + this->tile_selector = ts; } - RegionMap *region_map; - TilemapTileSelector *tile_selector; + RegionMap* region_map; + TilemapTileSelector* tile_selector; QString currentSection = QString(); int selectedTile; int highlightedTile; @@ -27,7 +27,7 @@ private: void updateSelectedTile(); signals: - void mouseEvent(QGraphicsSceneMouseEvent *, RegionMapEntriesPixmapItem *); + void mouseEvent(QGraphicsSceneMouseEvent*, RegionMapEntriesPixmapItem*); void hoveredTileChanged(int); void hoveredTileCleared(); void selectedTileChanged(QString); diff --git a/include/ui/regionmaplayoutpixmapitem.h b/include/ui/regionmaplayoutpixmapitem.h index f3d2a258..a67a6bcb 100644 --- a/include/ui/regionmaplayoutpixmapitem.h +++ b/include/ui/regionmaplayoutpixmapitem.h @@ -7,13 +7,13 @@ class RegionMapLayoutPixmapItem : public SelectablePixmapItem { Q_OBJECT public: - RegionMapLayoutPixmapItem(RegionMap *rmap, TilemapTileSelector *ts) : SelectablePixmapItem(8, 8, 1, 1) { - this->region_map = rmap; - this->tile_selector = ts; - setAcceptHoverEvents(true); + RegionMapLayoutPixmapItem(RegionMap* rmap, TilemapTileSelector* ts) : SelectablePixmapItem(8, 8, 1, 1) { + this->region_map = rmap; + this->tile_selector = ts; + setAcceptHoverEvents(true); } - RegionMap *region_map; - TilemapTileSelector *tile_selector; + RegionMap* region_map; + TilemapTileSelector* tile_selector; int selectedTile; int highlightedTile; void draw(); @@ -25,7 +25,7 @@ private: void updateSelectedTile(); signals: - void mouseEvent(QGraphicsSceneMouseEvent *, RegionMapLayoutPixmapItem *); + void mouseEvent(QGraphicsSceneMouseEvent*, RegionMapLayoutPixmapItem*); void hoveredTileChanged(int); void hoveredTileCleared(); void selectedTileChanged(int); diff --git a/include/ui/regionmappixmapitem.h b/include/ui/regionmappixmapitem.h index 2f8bc9af..d107b2b3 100644 --- a/include/ui/regionmappixmapitem.h +++ b/include/ui/regionmappixmapitem.h @@ -12,29 +12,29 @@ private: using QGraphicsPixmapItem::paint; public: - RegionMapPixmapItem(RegionMap *rmap, TilemapTileSelector *tile_selector) { + RegionMapPixmapItem(RegionMap* rmap, TilemapTileSelector* tile_selector) { this->region_map = rmap; this->tile_selector = tile_selector; setAcceptHoverEvents(true); } - RegionMap *region_map; - TilemapTileSelector *tile_selector; - - virtual void paint(QGraphicsSceneMouseEvent *); - virtual void select(QGraphicsSceneMouseEvent *); + RegionMap* region_map; + TilemapTileSelector* tile_selector; + + virtual void paint(QGraphicsSceneMouseEvent*); + virtual void select(QGraphicsSceneMouseEvent*); virtual void draw(); signals: - void mouseEvent(QGraphicsSceneMouseEvent *, RegionMapPixmapItem *); + void mouseEvent(QGraphicsSceneMouseEvent*, RegionMapPixmapItem*); void hoveredRegionMapTileChanged(int x, int y); void hoveredRegionMapTileCleared(); protected: - void hoverMoveEvent(QGraphicsSceneHoverEvent *); - void hoverLeaveEvent(QGraphicsSceneHoverEvent *); - void mousePressEvent(QGraphicsSceneMouseEvent *); - void mouseMoveEvent(QGraphicsSceneMouseEvent *); - void mouseReleaseEvent(QGraphicsSceneMouseEvent *); + void hoverMoveEvent(QGraphicsSceneHoverEvent*); + void hoverLeaveEvent(QGraphicsSceneHoverEvent*); + void mousePressEvent(QGraphicsSceneMouseEvent*); + void mouseMoveEvent(QGraphicsSceneMouseEvent*); + void mouseReleaseEvent(QGraphicsSceneMouseEvent*); }; #endif // REGIONMAPPIXMAPITEM_H diff --git a/include/ui/selectablepixmapitem.h b/include/ui/selectablepixmapitem.h index cdab4a6a..ba02ee00 100644 --- a/include/ui/selectablepixmapitem.h +++ b/include/ui/selectablepixmapitem.h @@ -7,7 +7,8 @@ class SelectablePixmapItem : public QObject, public QGraphicsPixmapItem { Q_OBJECT public: - SelectablePixmapItem(int cellWidth, int cellHeight): SelectablePixmapItem(cellWidth, cellHeight, INT_MAX, INT_MAX) {} + SelectablePixmapItem(int cellWidth, int cellHeight) : SelectablePixmapItem(cellWidth, cellHeight, INT_MAX, INT_MAX) { + } SelectablePixmapItem(int cellWidth, int cellHeight, int maxSelectionWidth, int maxSelectionHeight) { this->cellWidth = cellWidth; this->cellHeight = cellHeight; diff --git a/include/ui/shortcut.h b/include/ui/shortcut.h index 58980a3b..87fa86fe 100644 --- a/include/ui/shortcut.h +++ b/include/ui/shortcut.h @@ -5,11 +5,9 @@ #include #include - // Alternative to QShortcut that adds support for multiple key sequences. // Use this to allow the shortcut to be editable in ShortcutsEditor. -class Shortcut : public QObject -{ +class Shortcut : public QObject { Q_OBJECT Q_DECLARE_PRIVATE(QShortcut) Q_PROPERTY(QKeySequence key READ key WRITE setKey) @@ -19,21 +17,19 @@ class Shortcut : public QObject Q_PROPERTY(Qt::ShortcutContext context READ context WRITE setContext) public: - explicit Shortcut(QWidget *parent); - Shortcut(const QKeySequence &key, QWidget *parent, - const char *member = nullptr, const char *ambiguousMember = nullptr, - Qt::ShortcutContext shortcutContext = Qt::WindowShortcut); - Shortcut(const QList &keys, QWidget *parent, - const char *member = nullptr, const char *ambiguousMember = nullptr, - Qt::ShortcutContext shortcutContext = Qt::WindowShortcut); + explicit Shortcut(QWidget* parent); + Shortcut(const QKeySequence& key, QWidget* parent, const char* member = nullptr, const char* ambiguousMember = nullptr, + Qt::ShortcutContext shortcutContext = Qt::WindowShortcut); + Shortcut(const QList& keys, QWidget* parent, const char* member = nullptr, const char* ambiguousMember = nullptr, + Qt::ShortcutContext shortcutContext = Qt::WindowShortcut); ~Shortcut(); - void addKey(const QKeySequence &key); - void setKey(const QKeySequence &key); + void addKey(const QKeySequence& key); + void setKey(const QKeySequence& key); QKeySequence key() const; - void addKeys(const QList &keys); - void setKeys(const QList &keys); + void addKeys(const QList& keys); + void setKeys(const QList& keys); QList keys() const; void setEnabled(bool enable); @@ -42,7 +38,7 @@ public: void setContext(Qt::ShortcutContext context); Qt::ShortcutContext context() const; - void setWhatsThis(const QString &text); + void setWhatsThis(const QString& text); QString whatsThis() const; void setAutoRepeat(bool on); @@ -51,21 +47,22 @@ public: int id() const; QList ids() const; - inline QWidget *parentWidget() const - { return static_cast(QObject::parent()); } + inline QWidget* parentWidget() const { + return static_cast(QObject::parent()); + } signals: void activated(); void activatedAmbiguously(); protected: - bool event(QEvent *e) override; + bool event(QEvent* e) override; private: - const char *sc_member; - const char *sc_ambiguousmember; + const char* sc_member; + const char* sc_ambiguousmember; Qt::ShortcutContext sc_context; - QVector sc_vec; + QVector sc_vec; }; #endif // SHORTCUT_H diff --git a/include/ui/shortcutseditor.h b/include/ui/shortcutseditor.h index 31b0279e..c28a21e5 100644 --- a/include/ui/shortcutseditor.h +++ b/include/ui/shortcutseditor.h @@ -13,48 +13,46 @@ class QFormLayout; class MultiKeyEdit; class QAbstractButton; - namespace Ui { class ShortcutsEditor; } -class ShortcutsEditor : public QMainWindow -{ +class ShortcutsEditor : public QMainWindow { Q_OBJECT public: - explicit ShortcutsEditor(QWidget *parent = nullptr); - explicit ShortcutsEditor(const QObjectList &shortcutableObjects, QWidget *parent = nullptr); + explicit ShortcutsEditor(QWidget* parent = nullptr); + explicit ShortcutsEditor(const QObjectList& shortcutableObjects, QWidget* parent = nullptr); ~ShortcutsEditor(); - void setShortcutableObjects(const QObjectList &shortcutableObjects); + void setShortcutableObjects(const QObjectList& shortcutableObjects); signals: void shortcutsSaved(); private: - Ui::ShortcutsEditor *ui; - QWidget *main_container; - QMultiMap labels_objects; - QHash contexts_layouts; - QHash multiKeyEdits_objects; + Ui::ShortcutsEditor* ui; + QWidget* main_container; + QMultiMap labels_objects; + QHash contexts_layouts; + QHash multiKeyEdits_objects; - void parseObjectList(const QObjectList &objectList); - QString getLabel(const QObject *object) const; - bool stringPropertyIsNotEmpty(const QObject *object, const char *name) const; + void parseObjectList(const QObjectList& objectList); + QString getLabel(const QObject* object) const; + bool stringPropertyIsNotEmpty(const QObject* object, const char* name) const; void populateMainContainer(); - QString getShortcutContext(const QObject *object) const; - void addNewContextGroup(const QString &shortcutContext); - void addNewMultiKeyEdit(const QObject *object, const QString &shortcutContext); - QList siblings(MultiKeyEdit *multiKeyEdit) const; - void promptUserOnDuplicateFound(MultiKeyEdit *current, MultiKeyEdit *sender); - void removeKeySequence(const QKeySequence &keySequence, MultiKeyEdit *multiKeyEdit); + QString getShortcutContext(const QObject* object) const; + void addNewContextGroup(const QString& shortcutContext); + void addNewMultiKeyEdit(const QObject* object, const QString& shortcutContext); + QList siblings(MultiKeyEdit* multiKeyEdit) const; + void promptUserOnDuplicateFound(MultiKeyEdit* current, MultiKeyEdit* sender); + void removeKeySequence(const QKeySequence& keySequence, MultiKeyEdit* multiKeyEdit); void saveShortcuts(); void resetShortcuts(); private slots: - void checkForDuplicates(const QKeySequence &keySequence); - void dialogButtonClicked(QAbstractButton *button); + void checkForDuplicates(const QKeySequence& keySequence); + void dialogButtonClicked(QAbstractButton* button); }; #endif // SHORTCUTSEDITOR_H diff --git a/include/ui/tilemaptileselector.h b/include/ui/tilemaptileselector.h index 95650e4b..9cba23ef 100644 --- a/include/ui/tilemaptileselector.h +++ b/include/ui/tilemaptileselector.h @@ -3,10 +3,10 @@ #include "selectablepixmapitem.h" -class TilemapTileSelector: public SelectablePixmapItem { +class TilemapTileSelector : public SelectablePixmapItem { Q_OBJECT public: - TilemapTileSelector(QPixmap pixmap_): SelectablePixmapItem(8, 8, 1, 1) { + TilemapTileSelector(QPixmap pixmap_) : SelectablePixmapItem(8, 8, 1, 1) { this->tilemap = pixmap_; this->setPixmap(this->tilemap); this->numTilesWide = tilemap.width() / 8; diff --git a/include/ui/tileseteditor.h b/include/ui/tileseteditor.h index 1af92f35..28639670 100644 --- a/include/ui/tileseteditor.h +++ b/include/ui/tileseteditor.h @@ -16,7 +16,7 @@ class TilesetEditor; class MetatileHistoryItem { public: - MetatileHistoryItem(uint16_t metatileId, Metatile *prevMetatile, Metatile *newMetatile) { + MetatileHistoryItem(uint16_t metatileId, Metatile* prevMetatile, Metatile* newMetatile) { this->metatileId = metatileId; this->prevMetatile = prevMetatile; this->newMetatile = newMetatile; @@ -26,19 +26,18 @@ public: delete this->newMetatile; } uint16_t metatileId; - Metatile *prevMetatile; - Metatile *newMetatile; + Metatile* prevMetatile; + Metatile* newMetatile; }; -class TilesetEditor : public QMainWindow -{ +class TilesetEditor : public QMainWindow { Q_OBJECT public: - explicit TilesetEditor(Project*, Map*, QWidget *parent = nullptr); + explicit TilesetEditor(Project*, Map*, QWidget* parent = nullptr); ~TilesetEditor(); - void update(Map *map, QString primaryTilsetLabel, QString secondaryTilesetLabel); - void updateMap(Map *map); + void update(Map* map, QString primaryTilsetLabel, QString secondaryTilesetLabel); + void updateMap(Map* map); void updateTilesets(QString primaryTilsetLabel, QString secondaryTilesetLabel); bool selectMetatile(uint16_t metatileId); @@ -79,7 +78,7 @@ private slots: void on_actionRedo_triggered(); - void on_comboBox_metatileBehaviors_activated(const QString &arg1); + void on_comboBox_metatileBehaviors_activated(const QString& arg1); void on_lineEdit_metatileLabel_editingFinished(); @@ -120,26 +119,26 @@ private: void saveMetatileLabel(); void closeEvent(QCloseEvent*); - Ui::TilesetEditor *ui; + Ui::TilesetEditor* ui; History metatileHistory; - TilesetEditorMetatileSelector *metatileSelector = nullptr; - TilesetEditorTileSelector *tileSelector = nullptr; - MetatileLayersItem *metatileLayersItem = nullptr; - PaletteEditor *paletteEditor = nullptr; - Project *project = nullptr; - Map *map = nullptr; - Metatile *metatile = nullptr; + TilesetEditorMetatileSelector* metatileSelector = nullptr; + TilesetEditorTileSelector* tileSelector = nullptr; + MetatileLayersItem* metatileLayersItem = nullptr; + PaletteEditor* paletteEditor = nullptr; + Project* project = nullptr; + Map* map = nullptr; + Metatile* metatile = nullptr; int paletteId; bool tileXFlip; bool tileYFlip; bool hasUnsavedChanges; - Tileset *primaryTileset = nullptr; - Tileset *secondaryTileset = nullptr; - QGraphicsScene *metatilesScene = nullptr; - QGraphicsScene *tilesScene = nullptr; - QGraphicsScene *selectedTileScene = nullptr; - QGraphicsPixmapItem *selectedTilePixmapItem = nullptr; - QGraphicsScene *metatileLayersScene = nullptr; + Tileset* primaryTileset = nullptr; + Tileset* secondaryTileset = nullptr; + QGraphicsScene* metatilesScene = nullptr; + QGraphicsScene* tilesScene = nullptr; + QGraphicsScene* selectedTileScene = nullptr; + QGraphicsPixmapItem* selectedTilePixmapItem = nullptr; + QGraphicsScene* metatileLayersScene = nullptr; signals: void tilesetsSaved(QString, QString); diff --git a/include/ui/tileseteditormetatileselector.h b/include/ui/tileseteditormetatileselector.h index 87133a0b..2923dd53 100644 --- a/include/ui/tileseteditormetatileselector.h +++ b/include/ui/tileseteditormetatileselector.h @@ -5,17 +5,17 @@ #include "tileset.h" #include "map.h" -class TilesetEditorMetatileSelector: public SelectablePixmapItem { +class TilesetEditorMetatileSelector : public SelectablePixmapItem { Q_OBJECT public: - TilesetEditorMetatileSelector(Tileset *primaryTileset, Tileset *secondaryTileset, Map *map): SelectablePixmapItem(32, 32, 1, 1) { + TilesetEditorMetatileSelector(Tileset* primaryTileset, Tileset* secondaryTileset, Map* map) : SelectablePixmapItem(32, 32, 1, 1) { this->primaryTileset = primaryTileset; this->secondaryTileset = secondaryTileset; this->numMetatilesWide = 8; this->map = map; setAcceptHoverEvents(true); } - Map *map = nullptr; + Map* map = nullptr; void draw(); bool select(uint16_t metatileId); void setTilesets(Tileset*, Tileset*); @@ -31,8 +31,8 @@ protected: void hoverLeaveEvent(QGraphicsSceneHoverEvent*); private: - Tileset *primaryTileset = nullptr; - Tileset *secondaryTileset = nullptr; + Tileset* primaryTileset = nullptr; + Tileset* secondaryTileset = nullptr; uint16_t selectedMetatile; int numMetatilesWide; uint16_t getMetatileId(int x, int y); diff --git a/include/ui/tileseteditortileselector.h b/include/ui/tileseteditortileselector.h index 80f346ae..609a2471 100644 --- a/include/ui/tileseteditortileselector.h +++ b/include/ui/tileseteditortileselector.h @@ -4,11 +4,10 @@ #include "selectablepixmapitem.h" #include "tileset.h" -class TilesetEditorTileSelector: public SelectablePixmapItem { +class TilesetEditorTileSelector : public SelectablePixmapItem { Q_OBJECT public: - TilesetEditorTileSelector(Tileset *primaryTileset, Tileset *secondaryTileset, bool isTripleLayer) - : SelectablePixmapItem(16, 16, isTripleLayer ? 6 : 4, 2) { + TilesetEditorTileSelector(Tileset* primaryTileset, Tileset* secondaryTileset, bool isTripleLayer) : SelectablePixmapItem(16, 16, isTripleLayer ? 6 : 4, 2) { this->primaryTileset = primaryTileset; this->secondaryTileset = secondaryTileset; this->numTilesWide = 16; @@ -45,8 +44,8 @@ private: QList externalSelectedTiles; QList externalSelectedPos; - Tileset *primaryTileset; - Tileset *secondaryTileset; + Tileset* primaryTileset; + Tileset* secondaryTileset; QList selectedTiles; int numTilesWide; int paletteId; diff --git a/src/config.cpp b/src/config.cpp index 0ea49b6c..7dc6f684 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -16,7 +16,6 @@ #include KeyValueConfigBase::~KeyValueConfigBase() { - } void KeyValueConfigBase::load() { @@ -81,15 +80,11 @@ void KeyValueConfigBase::save() { } const QMap mapSortOrderMap = { - {MapSortOrder::Group, "group"}, - {MapSortOrder::Layout, "layout"}, - {MapSortOrder::Area, "area"}, + { MapSortOrder::Group, "group" }, { MapSortOrder::Layout, "layout" }, { MapSortOrder::Area, "area" }, }; const QMap mapSortOrderReverseMap = { - {"group", MapSortOrder::Group}, - {"layout", MapSortOrder::Layout}, - {"area", MapSortOrder::Area}, + { "group", MapSortOrder::Group }, { "layout", MapSortOrder::Layout }, { "area", MapSortOrder::Area }, }; PorymapConfig porymapConfig; @@ -217,8 +212,7 @@ QMap PorymapConfig::getKeyValueMap() { map.insert("show_player_view", this->showPlayerView ? "1" : "0"); map.insert("show_cursor_tile", this->showCursorTile ? "1" : "0"); map.insert("monitor_files", this->monitorFiles ? "1" : "0"); - map.insert("region_map_dimensions", QString("%1x%2").arg(this->regionMapDimensions.width()) - .arg(this->regionMapDimensions.height())); + map.insert("region_map_dimensions", QString("%1x%2").arg(this->regionMapDimensions.width()).arg(this->regionMapDimensions.height())); map.insert("theme", this->theme); map.insert("text_editor_open_directory", this->textEditorOpenFolder); map.insert("text_editor_goto_line", this->textEditorGotoLine); @@ -262,8 +256,7 @@ void PorymapConfig::setMonitorFiles(bool monitor) { this->save(); } -void PorymapConfig::setMainGeometry(QByteArray mainWindowGeometry_, QByteArray mainWindowState_, - QByteArray mapSplitterState_, QByteArray mainSplitterState_) { +void PorymapConfig::setMainGeometry(QByteArray mainWindowGeometry_, QByteArray mainWindowState_, QByteArray mapSplitterState_, QByteArray mainSplitterState_) { this->mainWindowGeometry = mainWindowGeometry_; this->mainWindowState = mainWindowState_; this->mapSplitterState = mapSplitterState_; @@ -317,12 +310,12 @@ void PorymapConfig::setTheme(QString theme) { this->theme = theme; } -void PorymapConfig::setTextEditorOpenFolder(const QString &command) { +void PorymapConfig::setTextEditorOpenFolder(const QString& command) { this->textEditorOpenFolder = command; this->save(); } -void PorymapConfig::setTextEditorGotoLine(const QString &command) { +void PorymapConfig::setTextEditorGotoLine(const QString& command) { this->textEditorGotoLine = command; this->save(); } @@ -414,15 +407,11 @@ QString PorymapConfig::getTextEditorGotoLine() { } const QMap baseGameVersionMap = { - {BaseGameVersion::pokeruby, "pokeruby"}, - {BaseGameVersion::pokefirered, "pokefirered"}, - {BaseGameVersion::pokeemerald, "pokeemerald"}, + { BaseGameVersion::pokeruby, "pokeruby" }, { BaseGameVersion::pokefirered, "pokefirered" }, { BaseGameVersion::pokeemerald, "pokeemerald" }, }; const QMap baseGameVersionReverseMap = { - {"pokeruby", BaseGameVersion::pokeruby}, - {"pokefirered", BaseGameVersion::pokefirered}, - {"pokeemerald", BaseGameVersion::pokeemerald}, + { "pokeruby", BaseGameVersion::pokeruby }, { "pokefirered", BaseGameVersion::pokefirered }, { "pokeemerald", BaseGameVersion::pokeemerald }, }; ProjectConfig projectConfig; @@ -527,14 +516,22 @@ void ProjectConfig::parseConfigKeyValue(QString key, QString value) { void ProjectConfig::setUnreadKeys() { // Set game-version specific defaults for any config field that wasn't read bool isPokefirered = this->baseGameVersion == BaseGameVersion::pokefirered; - if (!readKeys.contains("use_custom_border_size")) this->useCustomBorderSize = isPokefirered; - if (!readKeys.contains("enable_event_weather_trigger")) this->enableEventWeatherTrigger = !isPokefirered; - if (!readKeys.contains("enable_event_secret_base")) this->enableEventSecretBase = !isPokefirered; - if (!readKeys.contains("enable_hidden_item_quantity")) this->enableHiddenItemQuantity = isPokefirered; - if (!readKeys.contains("enable_hidden_item_requires_itemfinder")) this->enableHiddenItemRequiresItemfinder = isPokefirered; - if (!readKeys.contains("enable_heal_location_respawn_data")) this->enableHealLocationRespawnData = isPokefirered; - if (!readKeys.contains("enable_object_event_in_connection")) this->enableObjectEventInConnection = isPokefirered; - if (!readKeys.contains("enable_floor_number")) this->enableFloorNumber = isPokefirered; + if (!readKeys.contains("use_custom_border_size")) + this->useCustomBorderSize = isPokefirered; + if (!readKeys.contains("enable_event_weather_trigger")) + this->enableEventWeatherTrigger = !isPokefirered; + if (!readKeys.contains("enable_event_secret_base")) + this->enableEventSecretBase = !isPokefirered; + if (!readKeys.contains("enable_hidden_item_quantity")) + this->enableHiddenItemQuantity = isPokefirered; + if (!readKeys.contains("enable_hidden_item_requires_itemfinder")) + this->enableHiddenItemRequiresItemfinder = isPokefirered; + if (!readKeys.contains("enable_heal_location_respawn_data")) + this->enableHealLocationRespawnData = isPokefirered; + if (!readKeys.contains("enable_object_event_in_connection")) + this->enableObjectEventInConnection = isPokefirered; + if (!readKeys.contains("enable_floor_number")) + this->enableFloorNumber = isPokefirered; } QMap ProjectConfig::getKeyValueMap() { @@ -568,7 +565,7 @@ void ProjectConfig::onNewConfigFileCreated() { QFormLayout form(&dialog); - QComboBox *baseGameVersionComboBox = new QComboBox(); + QComboBox* baseGameVersionComboBox = new QComboBox(); baseGameVersionComboBox->addItem("pokeruby", BaseGameVersion::pokeruby); baseGameVersionComboBox->addItem("pokefirered", BaseGameVersion::pokefirered); baseGameVersionComboBox->addItem("pokeemerald", BaseGameVersion::pokeemerald); @@ -614,7 +611,7 @@ BaseGameVersion ProjectConfig::getBaseGameVersion() { return this->baseGameVersion; } -void ProjectConfig::setRecentMap(const QString &map) { +void ProjectConfig::setRecentMap(const QString& map) { this->recentMap = map; this->save(); } @@ -762,42 +759,38 @@ QMap ShortcutsConfig::getKeyValueMap() { return map; } -void ShortcutsConfig::setDefaultShortcuts(const QObjectList &objects) { +void ShortcutsConfig::setDefaultShortcuts(const QObjectList& objects) { storeShortcutsFromList(StoreType::Default, objects); save(); } -QList ShortcutsConfig::defaultShortcuts(const QObject *object) const { +QList ShortcutsConfig::defaultShortcuts(const QObject* object) const { return default_shortcuts.values(cfgKey(object)); } -void ShortcutsConfig::setUserShortcuts(const QObjectList &objects) { +void ShortcutsConfig::setUserShortcuts(const QObjectList& objects) { storeShortcutsFromList(StoreType::User, objects); save(); } -void ShortcutsConfig::setUserShortcuts(const QMultiMap &objects_keySequences) { - for (auto *object : objects_keySequences.uniqueKeys()) +void ShortcutsConfig::setUserShortcuts(const QMultiMap& objects_keySequences) { + for (auto* object : objects_keySequences.uniqueKeys()) if (!object->objectName().isEmpty() && !object->objectName().startsWith("_q_")) storeShortcuts(StoreType::User, cfgKey(object), objects_keySequences.values(object)); save(); } -QList ShortcutsConfig::userShortcuts(const QObject *object) const { +QList ShortcutsConfig::userShortcuts(const QObject* object) const { return user_shortcuts.values(cfgKey(object)); } -void ShortcutsConfig::storeShortcutsFromList(StoreType storeType, const QObjectList &objects) { - for (const auto *object : objects) +void ShortcutsConfig::storeShortcutsFromList(StoreType storeType, const QObjectList& objects) { + for (const auto* object : objects) if (!object->objectName().isEmpty() && !object->objectName().startsWith("_q_")) storeShortcuts(storeType, cfgKey(object), currentShortcuts(object)); } -void ShortcutsConfig::storeShortcuts( - StoreType storeType, - const QString &cfgKey, - const QList &keySequences) -{ +void ShortcutsConfig::storeShortcuts(StoreType storeType, const QString& cfgKey, const QList& keySequences) { bool storeUser = (storeType == User) || !user_shortcuts.contains(cfgKey); if (storeType == Default) @@ -820,11 +813,11 @@ void ShortcutsConfig::storeShortcuts( } } -/* Creates a config key from the object's name prepended with the parent +/* Creates a config key from the object's name prepended with the parent * window's object name, and converts camelCase to snake_case. */ -QString ShortcutsConfig::cfgKey(const QObject *object) const { +QString ShortcutsConfig::cfgKey(const QObject* object) const { auto cfg_key = QString(); - auto *parentWidget = static_cast(object->parent()); + auto* parentWidget = static_cast(object->parent()); if (parentWidget) cfg_key = parentWidget->window()->objectName() + '_'; cfg_key += object->objectName(); @@ -839,19 +832,19 @@ QString ShortcutsConfig::cfgKey(const QObject *object) const { return cfg_key.toLower(); } -QList ShortcutsConfig::currentShortcuts(const QObject *object) const { +QList ShortcutsConfig::currentShortcuts(const QObject* object) const { if (object->inherits("QAction")) { - const auto *action = qobject_cast(object); + const auto* action = qobject_cast(object); return action->shortcuts(); } else if (object->inherits("Shortcut")) { - const auto *shortcut = qobject_cast(object); + const auto* shortcut = qobject_cast(object); return shortcut->keys(); } else if (object->inherits("QShortcut")) { - const auto *qshortcut = qobject_cast(object); + const auto* qshortcut = qobject_cast(object); return { qshortcut->key() }; } else if (object->property("shortcut").isValid()) { return { object->property("shortcut").value() }; } else { - return { }; + return {}; } } diff --git a/src/core/block.cpp b/src/core/block.cpp index 680384fd..121f149a 100644 --- a/src/core/block.cpp +++ b/src/core/block.cpp @@ -1,26 +1,18 @@ #include "block.h" -Block::Block() : tile(0), collision(0), elevation(0) { } +Block::Block() : tile(0), collision(0), elevation(0) { +} -Block::Block(uint16_t tile, uint16_t collision, uint16_t elevation) : - tile(tile), - collision(collision), - elevation(elevation) -{ } +Block::Block(uint16_t tile, uint16_t collision, uint16_t elevation) : tile(tile), collision(collision), elevation(elevation) { +} -Block::Block(uint16_t word) : - tile(word & 0x3ff), - collision((word >> 10) & 0x3), - elevation((word >> 12) & 0xf) -{ } +Block::Block(uint16_t word) : tile(word & 0x3ff), collision((word >> 10) & 0x3), elevation((word >> 12) & 0xf) { +} -Block::Block(const Block &other) : - tile(other.tile), - collision(other.collision), - elevation(other.elevation) -{ } +Block::Block(const Block& other) : tile(other.tile), collision(other.collision), elevation(other.elevation) { +} -Block &Block::operator=(const Block &other) { +Block& Block::operator=(const Block& other) { tile = other.tile; collision = other.collision; elevation = other.elevation; @@ -28,16 +20,13 @@ Block &Block::operator=(const Block &other) { } uint16_t Block::rawValue() const { - return static_cast( - (tile & 0x3ff) + - ((collision & 0x3) << 10) + - ((elevation & 0xf) << 12)); + return static_cast((tile & 0x3ff) + ((collision & 0x3) << 10) + ((elevation & 0xf) << 12)); } -bool Block::operator ==(Block other) const { +bool Block::operator==(Block other) const { return (tile == other.tile) && (collision == other.collision) && (elevation == other.elevation); } -bool Block::operator !=(Block other) const { - return !(operator ==(other)); +bool Block::operator!=(Block other) const { + return !(operator==(other)); } diff --git a/src/core/blockdata.cpp b/src/core/blockdata.cpp index 5fcd4e32..772c501f 100644 --- a/src/core/blockdata.cpp +++ b/src/core/blockdata.cpp @@ -2,7 +2,7 @@ QByteArray Blockdata::serialize() const { QByteArray data; - for (const auto &block : *this) { + for (const auto& block : *this) { uint16_t word = block.rawValue(); data.append(static_cast(word & 0xff)); data.append(static_cast((word >> 8) & 0xff)); diff --git a/src/core/editcommands.cpp b/src/core/editcommands.cpp index e7a3d300..04dfbae5 100644 --- a/src/core/editcommands.cpp +++ b/src/core/editcommands.cpp @@ -6,19 +6,17 @@ #include -int getEventTypeMask(QList events) { +int getEventTypeMask(QList events) { int eventTypeMask = 0; for (auto event : events) { if (event->get("event_type") == EventType::Object) { eventTypeMask |= IDMask_EventType_Object; } else if (event->get("event_type") == EventType::Warp) { eventTypeMask |= IDMask_EventType_Warp; - } else if (event->get("event_type") == EventType::Trigger || - event->get("event_type") == EventType::WeatherTrigger) { + } else if (event->get("event_type") == EventType::Trigger || event->get("event_type") == EventType::WeatherTrigger) { eventTypeMask |= IDMask_EventType_Trigger; - } else if (event->get("event_type") == EventType::Sign || - event->get("event_type") == EventType::HiddenItem || - event->get("event_type") == EventType::SecretBase) { + } else if (event->get("event_type") == EventType::Sign || event->get("event_type") == EventType::HiddenItem + || event->get("event_type") == EventType::SecretBase) { eventTypeMask |= IDMask_EventType_BG; } else if (event->get("event_type") == EventType::HealLocation) { eventTypeMask |= IDMask_EventType_Heal; @@ -27,14 +25,13 @@ int getEventTypeMask(QList events) { return eventTypeMask; } -void renderMapBlocks(Map *map, bool ignoreCache = false) { +void renderMapBlocks(Map* map, bool ignoreCache = false) { map->mapItem->draw(ignoreCache); map->collisionItem->draw(ignoreCache); } -PaintMetatile::PaintMetatile(Map *map, - const Blockdata &oldMetatiles, const Blockdata &newMetatiles, - unsigned actionId, QUndoCommand *parent) : QUndoCommand(parent) { +PaintMetatile::PaintMetatile(Map* map, const Blockdata& oldMetatiles, const Blockdata& newMetatiles, unsigned actionId, QUndoCommand* parent) + : QUndoCommand(parent) { setText("Paint Metatiles"); this->map = map; @@ -47,7 +44,8 @@ PaintMetatile::PaintMetatile(Map *map, void PaintMetatile::redo() { QUndoCommand::redo(); - if (!map) return; + if (!map) + return; map->layout->blockdata = newMetatiles; @@ -57,7 +55,8 @@ void PaintMetatile::redo() { } void PaintMetatile::undo() { - if (!map) return; + if (!map) + return; map->layout->blockdata = oldMetatiles; @@ -68,8 +67,8 @@ void PaintMetatile::undo() { QUndoCommand::undo(); } -bool PaintMetatile::mergeWith(const QUndoCommand *command) { - const PaintMetatile *other = static_cast(command); +bool PaintMetatile::mergeWith(const QUndoCommand* command) { + const PaintMetatile* other = static_cast(command); if (map != other->map) return false; @@ -86,9 +85,7 @@ bool PaintMetatile::mergeWith(const QUndoCommand *command) { ************************************************************************ ******************************************************************************/ -PaintBorder::PaintBorder(Map *map, - const Blockdata &oldBorder, const Blockdata &newBorder, - unsigned actionId, QUndoCommand *parent) : QUndoCommand(parent) { +PaintBorder::PaintBorder(Map* map, const Blockdata& oldBorder, const Blockdata& newBorder, unsigned actionId, QUndoCommand* parent) : QUndoCommand(parent) { setText("Paint Border"); this->map = map; @@ -101,7 +98,8 @@ PaintBorder::PaintBorder(Map *map, void PaintBorder::redo() { QUndoCommand::redo(); - if (!map) return; + if (!map) + return; map->layout->border = newBorder; @@ -109,7 +107,8 @@ void PaintBorder::redo() { } void PaintBorder::undo() { - if (!map) return; + if (!map) + return; map->layout->border = oldBorder; @@ -122,9 +121,8 @@ void PaintBorder::undo() { ************************************************************************ ******************************************************************************/ -ShiftMetatiles::ShiftMetatiles(Map *map, - const Blockdata &oldMetatiles, const Blockdata &newMetatiles, - unsigned actionId, QUndoCommand *parent) : QUndoCommand(parent) { +ShiftMetatiles::ShiftMetatiles(Map* map, const Blockdata& oldMetatiles, const Blockdata& newMetatiles, unsigned actionId, QUndoCommand* parent) + : QUndoCommand(parent) { setText("Shift Metatiles"); this->map = map; @@ -137,7 +135,8 @@ ShiftMetatiles::ShiftMetatiles(Map *map, void ShiftMetatiles::redo() { QUndoCommand::redo(); - if (!map) return; + if (!map) + return; map->layout->blockdata = newMetatiles; @@ -147,7 +146,8 @@ void ShiftMetatiles::redo() { } void ShiftMetatiles::undo() { - if (!map) return; + if (!map) + return; map->layout->blockdata = oldMetatiles; @@ -158,8 +158,8 @@ void ShiftMetatiles::undo() { QUndoCommand::undo(); } -bool ShiftMetatiles::mergeWith(const QUndoCommand *command) { - const ShiftMetatiles *other = static_cast(command); +bool ShiftMetatiles::mergeWith(const QUndoCommand* command) { + const ShiftMetatiles* other = static_cast(command); if (this->map != other->map) return false; @@ -176,11 +176,9 @@ bool ShiftMetatiles::mergeWith(const QUndoCommand *command) { ************************************************************************ ******************************************************************************/ -ResizeMap::ResizeMap(Map *map, QSize oldMapDimensions, QSize newMapDimensions, - const Blockdata &oldMetatiles, const Blockdata &newMetatiles, - QSize oldBorderDimensions, QSize newBorderDimensions, - const Blockdata &oldBorder, const Blockdata &newBorder, - QUndoCommand *parent) : QUndoCommand(parent) { +ResizeMap::ResizeMap(Map* map, QSize oldMapDimensions, QSize newMapDimensions, const Blockdata& oldMetatiles, const Blockdata& newMetatiles, + QSize oldBorderDimensions, QSize newBorderDimensions, const Blockdata& oldBorder, const Blockdata& newBorder, QUndoCommand* parent) + : QUndoCommand(parent) { setText("Resize Map"); this->map = map; @@ -207,7 +205,8 @@ ResizeMap::ResizeMap(Map *map, QSize oldMapDimensions, QSize newMapDimensions, void ResizeMap::redo() { QUndoCommand::redo(); - if (!map) return; + if (!map) + return; map->layout->blockdata = newMetatiles; map->setDimensions(newMapWidth, newMapHeight, false); @@ -221,7 +220,8 @@ void ResizeMap::redo() { } void ResizeMap::undo() { - if (!map) return; + if (!map) + return; map->layout->blockdata = oldMetatiles; map->setDimensions(oldMapWidth, oldMapHeight, false); @@ -240,9 +240,7 @@ void ResizeMap::undo() { ************************************************************************ ******************************************************************************/ -EventMove::EventMove(QList events, - int deltaX, int deltaY, unsigned actionId, - QUndoCommand *parent) : QUndoCommand(parent) { +EventMove::EventMove(QList events, int deltaX, int deltaY, unsigned actionId, QUndoCommand* parent) : QUndoCommand(parent) { setText("Move Event"); this->events = events; @@ -256,21 +254,21 @@ EventMove::EventMove(QList events, void EventMove::redo() { QUndoCommand::redo(); - for (Event *event : events) { + for (Event* event : events) { event->pixmapItem->move(deltaX, deltaY); } } void EventMove::undo() { - for (Event *event : events) { + for (Event* event : events) { event->pixmapItem->move(-deltaX, -deltaY); } QUndoCommand::undo(); } -bool EventMove::mergeWith(const QUndoCommand *command) { - const EventMove *other = static_cast(command); +bool EventMove::mergeWith(const QUndoCommand* command) { + const EventMove* other = static_cast(command); if (actionId != other->actionId) return false; @@ -291,10 +289,8 @@ int EventMove::id() const { ************************************************************************ ******************************************************************************/ -EventShift::EventShift(QList events, - int deltaX, int deltaY, unsigned actionId, - QUndoCommand *parent) - : EventMove(events, deltaX, deltaY, actionId, parent) { +EventShift::EventShift(QList events, int deltaX, int deltaY, unsigned actionId, QUndoCommand* parent) + : EventMove(events, deltaX, deltaY, actionId, parent) { this->events = events; setText("Shift Events"); } @@ -307,8 +303,7 @@ int EventShift::id() const { ************************************************************************ ******************************************************************************/ -EventCreate::EventCreate(Editor *editor, Map *map, Event *event, - QUndoCommand *parent) : QUndoCommand(parent) { +EventCreate::EventCreate(Editor* editor, Map* map, Event* event, QUndoCommand* parent) : QUndoCommand(parent) { setText("Create Event"); this->editor = editor; @@ -344,16 +339,14 @@ void EventCreate::undo() { } int EventCreate::id() const { - return CommandId::ID_EventCreate | getEventTypeMask(QList({this->event})); + return CommandId::ID_EventCreate | getEventTypeMask(QList({ this->event })); } /****************************************************************************** ************************************************************************ ******************************************************************************/ -EventDelete::EventDelete(Editor *editor, Map *map, - QList selectedEvents, Event *nextSelectedEvent, - QUndoCommand *parent) : QUndoCommand(parent) { +EventDelete::EventDelete(Editor* editor, Map* map, QList selectedEvents, Event* nextSelectedEvent, QUndoCommand* parent) : QUndoCommand(parent) { if (selectedEvents.size() > 1) { setText("Delete Events"); } else { @@ -370,7 +363,7 @@ EventDelete::EventDelete(Editor *editor, Map *map, void EventDelete::redo() { QUndoCommand::redo(); - for (Event *event : selectedEvents) { + for (Event* event : selectedEvents) { map->removeEvent(event); if (editor->scene->items().contains(event->pixmapItem)) { @@ -386,7 +379,7 @@ void EventDelete::redo() { } void EventDelete::undo() { - for (Event *event : selectedEvents) { + for (Event* event : selectedEvents) { map->addEvent(event); editor->project->loadEventPixmaps(map->getAllEvents()); @@ -395,7 +388,7 @@ void EventDelete::undo() { // select these events editor->selected_events->clear(); - for (Event *event : selectedEvents) { + for (Event* event : selectedEvents) { editor->selected_events->append(event->pixmapItem); } editor->shouldReselectEvents(); @@ -411,9 +404,7 @@ int EventDelete::id() const { ************************************************************************ ******************************************************************************/ -EventDuplicate::EventDuplicate(Editor *editor, Map *map, - QList selectedEvents, - QUndoCommand *parent) : QUndoCommand(parent) { +EventDuplicate::EventDuplicate(Editor* editor, Map* map, QList selectedEvents, QUndoCommand* parent) : QUndoCommand(parent) { setText("Duplicate Event"); this->editor = editor; @@ -425,26 +416,26 @@ EventDuplicate::EventDuplicate(Editor *editor, Map *map, void EventDuplicate::redo() { QUndoCommand::redo(); - for (Event *event : selectedEvents) { + for (Event* event : selectedEvents) { map->addEvent(event); } editor->project->loadEventPixmaps(map->getAllEvents()); - for (Event *event : selectedEvents) { + for (Event* event : selectedEvents) { editor->addMapEvent(event); } // select these events editor->selected_events->clear(); - for (Event *event : selectedEvents) { + for (Event* event : selectedEvents) { editor->selected_events->append(event->pixmapItem); } editor->shouldReselectEvents(); } void EventDuplicate::undo() { - for (Event *event : selectedEvents) { + for (Event* event : selectedEvents) { map->removeEvent(event); if (editor->scene->items().contains(event->pixmapItem)) { @@ -466,10 +457,9 @@ int EventDuplicate::id() const { ************************************************************************ ******************************************************************************/ -ScriptEditMap::ScriptEditMap(Map *map, - QSize oldMapDimensions, QSize newMapDimensions, - const Blockdata &oldMetatiles, const Blockdata &newMetatiles, - QUndoCommand *parent) : QUndoCommand(parent) { +ScriptEditMap::ScriptEditMap( + Map* map, QSize oldMapDimensions, QSize newMapDimensions, const Blockdata& oldMetatiles, const Blockdata& newMetatiles, QUndoCommand* parent) + : QUndoCommand(parent) { setText("Script Edit Map"); this->map = map; @@ -486,7 +476,8 @@ ScriptEditMap::ScriptEditMap(Map *map, void ScriptEditMap::redo() { QUndoCommand::redo(); - if (!map) return; + if (!map) + return; map->layout->blockdata = newMetatiles; if (newMapWidth != map->getWidth() || newMapHeight != map->getHeight()) { @@ -500,7 +491,8 @@ void ScriptEditMap::redo() { } void ScriptEditMap::undo() { - if (!map) return; + if (!map) + return; map->layout->blockdata = oldMetatiles; if (oldMapWidth != map->getWidth() || oldMapHeight != map->getHeight()) { diff --git a/src/core/event.cpp b/src/core/event.cpp index ea8e078f..e886846d 100644 --- a/src/core/event.cpp +++ b/src/core/event.cpp @@ -12,32 +12,27 @@ QString EventType::HiddenItem = "event_hidden_item"; QString EventType::SecretBase = "event_secret_base"; QString EventType::HealLocation = "event_heal_location"; -Event::Event() : - spriteWidth(16), - spriteHeight(16), - usingSprite(false) -{ } +Event::Event() : spriteWidth(16), spriteHeight(16), usingSprite(false) { +} -Event::Event(const Event& toCopy) : - values(toCopy.values), - customValues(toCopy.customValues), - pixmap(toCopy.pixmap), - spriteWidth(toCopy.spriteWidth), - spriteHeight(toCopy.spriteHeight), - frame(toCopy.frame), - hFlip(toCopy.hFlip), - usingSprite(toCopy.usingSprite) -{ } +Event::Event(const Event& toCopy) + : values(toCopy.values), + customValues(toCopy.customValues), + pixmap(toCopy.pixmap), + spriteWidth(toCopy.spriteWidth), + spriteHeight(toCopy.spriteHeight), + frame(toCopy.frame), + hFlip(toCopy.hFlip), + usingSprite(toCopy.usingSprite) { +} -Event::Event(QJsonObject obj, QString type) : Event() -{ +Event::Event(QJsonObject obj, QString type) : Event() { this->put("event_type", type); this->readCustomValues(obj); } -Event* Event::createNewEvent(QString event_type, QString map_name, Project *project) -{ - Event *event = nullptr; +Event* Event::createNewEvent(QString event_type, QString map_name, Project* project) { + Event* event = nullptr; if (event_type == EventType::Object) { event = createNewObjectEvent(project); event->setFrameFromMovement(event->get("movement_type")); @@ -65,9 +60,8 @@ Event* Event::createNewEvent(QString event_type, QString map_name, Project *proj return event; } -Event* Event::createNewObjectEvent(Project *project) -{ - Event *event = new Event; +Event* Event::createNewObjectEvent(Project* project) { + Event* event = new Event; event->put("event_group_type", "object_event_group"); event->put("event_type", EventType::Object); event->put("sprite", project->getEventObjGfxConstants().keys().first()); @@ -86,9 +80,8 @@ Event* Event::createNewObjectEvent(Project *project) return event; } -Event* Event::createNewWarpEvent(QString map_name) -{ - Event *event = new Event; +Event* Event::createNewWarpEvent(QString map_name) { + Event* event = new Event; event->put("event_group_type", "warp_event_group"); event->put("event_type", EventType::Warp); event->put("destination_warp", 0); @@ -97,12 +90,11 @@ Event* Event::createNewWarpEvent(QString map_name) return event; } -Event* Event::createNewHealLocationEvent(QString map_name) -{ - Event *event = new Event; +Event* Event::createNewHealLocationEvent(QString map_name) { + Event* event = new Event; event->put("event_group_type", "heal_event_group"); event->put("event_type", EventType::HealLocation); - event->put("loc_name", QString(Map::mapConstantFromName(map_name)).remove(0,4)); + event->put("loc_name", QString(Map::mapConstantFromName(map_name)).remove(0, 4)); event->put("id_name", map_name.replace(QRegularExpression("([a-z])([A-Z])"), "\\1_\\2").toUpper()); event->put("elevation", 3); if (projectConfig.getHealLocationRespawnDataEnabled()) { @@ -112,9 +104,8 @@ Event* Event::createNewHealLocationEvent(QString map_name) return event; } -Event* Event::createNewTriggerEvent(Project *project) -{ - Event *event = new Event; +Event* Event::createNewTriggerEvent(Project* project) { + Event* event = new Event; event->put("event_group_type", "coord_event_group"); event->put("event_type", EventType::Trigger); event->put("script_label", "NULL"); @@ -124,9 +115,8 @@ Event* Event::createNewTriggerEvent(Project *project) return event; } -Event* Event::createNewWeatherTriggerEvent(Project *project) -{ - Event *event = new Event; +Event* Event::createNewWeatherTriggerEvent(Project* project) { + Event* event = new Event; event->put("event_group_type", "coord_event_group"); event->put("event_type", EventType::WeatherTrigger); event->put("weather", project->coordEventWeatherNames.first()); @@ -134,9 +124,8 @@ Event* Event::createNewWeatherTriggerEvent(Project *project) return event; } -Event* Event::createNewSignEvent(Project *project) -{ - Event *event = new Event; +Event* Event::createNewSignEvent(Project* project) { + Event* event = new Event; event->put("event_group_type", "bg_event_group"); event->put("event_type", EventType::Sign); event->put("player_facing_direction", project->bgEventFacingDirections.first()); @@ -145,9 +134,8 @@ Event* Event::createNewSignEvent(Project *project) return event; } -Event* Event::createNewHiddenItemEvent(Project *project) -{ - Event *event = new Event; +Event* Event::createNewHiddenItemEvent(Project* project) { + Event* event = new Event; event->put("event_group_type", "bg_event_group"); event->put("event_type", EventType::HiddenItem); event->put("item", project->itemNames.first()); @@ -162,9 +150,8 @@ Event* Event::createNewHiddenItemEvent(Project *project) return event; } -Event* Event::createNewSecretBaseEvent(Project *project) -{ - Event *event = new Event; +Event* Event::createNewSecretBaseEvent(Project* project) { + Event* event = new Event; event->put("event_group_type", "bg_event_group"); event->put("event_type", EventType::SecretBase); event->put("secret_base_id", project->secretBaseIds.first()); @@ -172,84 +159,44 @@ Event* Event::createNewSecretBaseEvent(Project *project) return event; } -int Event::getPixelX() -{ +int Event::getPixelX() { return (this->x() * 16) - qMax(0, (this->spriteWidth - 16) / 2); } -int Event::getPixelY() -{ +int Event::getPixelY() { return (this->y() * 16) - qMax(0, this->spriteHeight - 16); } -static QMap expectedObjectFields { - {"graphics_id", true}, - {"x", true}, - {"y", true}, - {"elevation", true}, - {"movement_type", true}, - {"movement_range_x", true}, - {"movement_range_y", true}, - {"trainer_type", true}, - {"trainer_sight_or_berry_tree_id", true}, - {"script", true}, - {"flag", true}, +static QMap expectedObjectFields{ + { "graphics_id", true }, { "x", true }, { "y", true }, { "elevation", true }, { "movement_type", true }, { "movement_range_x", true }, + { "movement_range_y", true }, { "trainer_type", true }, { "trainer_sight_or_berry_tree_id", true }, { "script", true }, { "flag", true }, }; -static QMap expectedWarpFields { - {"x", true}, - {"y", true}, - {"elevation", true}, - {"dest_map", true}, - {"dest_warp_id", true}, +static QMap expectedWarpFields{ + { "x", true }, { "y", true }, { "elevation", true }, { "dest_map", true }, { "dest_warp_id", true }, }; -static QMap expectedTriggerFields { - {"type", true}, - {"x", true}, - {"y", true}, - {"elevation", true}, - {"var", true}, - {"var_value", true}, - {"script", true}, +static QMap expectedTriggerFields{ + { "type", true }, { "x", true }, { "y", true }, { "elevation", true }, { "var", true }, { "var_value", true }, { "script", true }, }; -static QMap expectedWeatherTriggerFields { - {"type", true}, - {"x", true}, - {"y", true}, - {"elevation", true}, - {"weather", true}, +static QMap expectedWeatherTriggerFields{ + { "type", true }, { "x", true }, { "y", true }, { "elevation", true }, { "weather", true }, }; -static QMap expectedSignFields { - {"type", true}, - {"x", true}, - {"y", true}, - {"elevation", true}, - {"player_facing_dir", true}, - {"script", true}, +static QMap expectedSignFields{ + { "type", true }, { "x", true }, { "y", true }, { "elevation", true }, { "player_facing_dir", true }, { "script", true }, }; -static QMap expectedHiddenItemFields { - {"type", true}, - {"x", true}, - {"y", true}, - {"elevation", true}, - {"item", true}, - {"flag", true}, +static QMap expectedHiddenItemFields{ + { "type", true }, { "x", true }, { "y", true }, { "elevation", true }, { "item", true }, { "flag", true }, }; -static QMap expectedSecretBaseFields { - {"type", true}, - {"x", true}, - {"y", true}, - {"elevation", true}, - {"secret_base_id", true}, +static QMap expectedSecretBaseFields{ + { "type", true }, { "x", true }, { "y", true }, { "elevation", true }, { "secret_base_id", true }, }; -QMap Event::getExpectedFields() -{ +QMap Event::getExpectedFields() { QString type = this->get("event_type"); QMap expectedFields = QMap(); if (type == EventType::Object) { @@ -260,7 +207,7 @@ QMap Event::getExpectedFields() } else if (type == EventType::Warp) { expectedFields = expectedWarpFields; } else if (type == EventType::Trigger) { - expectedFields = expectedTriggerFields; + expectedFields = expectedTriggerFields; } else if (type == EventType::WeatherTrigger) { expectedFields = expectedWeatherTriggerFields; } else if (type == EventType::Sign) { @@ -279,8 +226,7 @@ QMap Event::getExpectedFields() return expectedFields; }; -void Event::readCustomValues(QJsonObject values) -{ +void Event::readCustomValues(QJsonObject values) { this->customValues.clear(); QMap expectedValues = this->getExpectedFields(); for (QString key : values.keys()) { @@ -290,8 +236,7 @@ void Event::readCustomValues(QJsonObject values) } } -void Event::addCustomValuesTo(OrderedJson::object *obj) -{ +void Event::addCustomValuesTo(OrderedJson::object* obj) { for (QString key : this->customValues.keys()) { if (!obj->contains(key)) { (*obj)[key] = this->customValues[key]; @@ -299,8 +244,7 @@ void Event::addCustomValuesTo(OrderedJson::object *obj) } } -OrderedJson::object Event::buildObjectEventJSON() -{ +OrderedJson::object Event::buildObjectEventJSON() { OrderedJson::object eventObj; eventObj["graphics_id"] = this->get("sprite"); if (projectConfig.getObjectEventInConnectionEnabled()) { @@ -321,8 +265,7 @@ OrderedJson::object Event::buildObjectEventJSON() return eventObj; } -OrderedJson::object Event::buildWarpEventJSON(const QMap &mapNamesToMapConstants) -{ +OrderedJson::object Event::buildWarpEventJSON(const QMap& mapNamesToMapConstants) { OrderedJson::object warpObj; warpObj["x"] = this->getU16("x"); warpObj["y"] = this->getU16("y"); @@ -334,8 +277,7 @@ OrderedJson::object Event::buildWarpEventJSON(const QMap &mapN return warpObj; } -OrderedJson::object Event::buildTriggerEventJSON() -{ +OrderedJson::object Event::buildTriggerEventJSON() { OrderedJson::object triggerObj; triggerObj["type"] = "trigger"; triggerObj["x"] = this->getU16("x"); @@ -349,8 +291,7 @@ OrderedJson::object Event::buildTriggerEventJSON() return triggerObj; } -OrderedJson::object Event::buildWeatherTriggerEventJSON() -{ +OrderedJson::object Event::buildWeatherTriggerEventJSON() { OrderedJson::object weatherObj; weatherObj["type"] = "weather"; weatherObj["x"] = this->getU16("x"); @@ -362,8 +303,7 @@ OrderedJson::object Event::buildWeatherTriggerEventJSON() return weatherObj; } -OrderedJson::object Event::buildSignEventJSON() -{ +OrderedJson::object Event::buildSignEventJSON() { OrderedJson::object signObj; signObj["type"] = "sign"; signObj["x"] = this->getU16("x"); @@ -376,8 +316,7 @@ OrderedJson::object Event::buildSignEventJSON() return signObj; } -OrderedJson::object Event::buildHiddenItemEventJSON() -{ +OrderedJson::object Event::buildHiddenItemEventJSON() { OrderedJson::object hiddenItemObj; hiddenItemObj["type"] = "hidden_item"; hiddenItemObj["x"] = this->getU16("x"); @@ -396,8 +335,7 @@ OrderedJson::object Event::buildHiddenItemEventJSON() return hiddenItemObj; } -OrderedJson::object Event::buildSecretBaseEventJSON() -{ +OrderedJson::object Event::buildSecretBaseEventJSON() { OrderedJson::object secretBaseObj; secretBaseObj["type"] = "secret_base"; secretBaseObj["x"] = this->getU16("x"); @@ -409,8 +347,7 @@ OrderedJson::object Event::buildSecretBaseEventJSON() return secretBaseObj; } -void Event::setPixmapFromSpritesheet(QImage spritesheet, int spriteWidth, int spriteHeight, int frame, bool hFlip) -{ +void Event::setPixmapFromSpritesheet(QImage spritesheet, int spriteWidth, int spriteHeight, int frame, bool hFlip) { // Set first palette color fully transparent. QImage img = spritesheet.copy(frame * spriteWidth % spritesheet.width(), 0, spriteWidth, spriteHeight); if (hFlip) { diff --git a/src/core/heallocation.cpp b/src/core/heallocation.cpp index 8ecb70a8..f807a8a8 100644 --- a/src/core/heallocation.cpp +++ b/src/core/heallocation.cpp @@ -2,8 +2,7 @@ #include "config.h" #include "map.h" -HealLocation::HealLocation(QString id, QString map, int i, uint16_t x, uint16_t y, QString respawnMap, uint16_t respawnNPC) -{ +HealLocation::HealLocation(QString id, QString map, int i, uint16_t x, uint16_t y, QString respawnMap, uint16_t respawnNPC) { this->idName = id; this->mapName = map; this->index = i; @@ -13,28 +12,25 @@ HealLocation::HealLocation(QString id, QString map, int i, uint16_t x, uint16_t this->respawnNPC = respawnNPC; } -HealLocation HealLocation::fromEvent(Event *event) -{ +HealLocation HealLocation::fromEvent(Event* event) { HealLocation hl; hl.idName = event->get("id_name"); hl.mapName = event->get("loc_name"); try { hl.index = event->get("index").toInt(); - } - catch(...) { + } catch (...) { hl.index = 0; } - hl.x = event->getU16("x"); - hl.y = event->getU16("y"); + hl.x = event->getU16("x"); + hl.y = event->getU16("y"); if (projectConfig.getHealLocationRespawnDataEnabled()) { hl.respawnNPC = event->getU16("respawn_npc"); - hl.respawnMap = Map::mapConstantFromName(event->get("respawn_map")).remove(0,4); + hl.respawnMap = Map::mapConstantFromName(event->get("respawn_map")).remove(0, 4); } return hl; } -QDebug operator<<(QDebug debug, const HealLocation &hl) -{ +QDebug operator<<(QDebug debug, const HealLocation& hl) { debug << "HealLocation_" + hl.mapName << "(" << hl.x << ',' << hl.y << ")"; return debug; } diff --git a/src/core/imageexport.cpp b/src/core/imageexport.cpp index b57c6dd9..715125c9 100644 --- a/src/core/imageexport.cpp +++ b/src/core/imageexport.cpp @@ -11,22 +11,21 @@ unsigned long crc_table[256]; int crc_table_computed = 0; /* Make the table for a fast CRC. */ -void make_crc_table(void) -{ - unsigned long c; - int n, k; +void make_crc_table(void) { + unsigned long c; + int n, k; - for (n = 0; n < 256; n++) { - c = (unsigned long) n; - for (k = 0; k < 8; k++) { - if (c & 1) - c = 0xedb88320L ^ (c >> 1); - else - c = c >> 1; + for (n = 0; n < 256; n++) { + c = (unsigned long)n; + for (k = 0; k < 8; k++) { + if (c & 1) + c = 0xedb88320L ^ (c >> 1); + else + c = c >> 1; + } + crc_table[n] = c; } - crc_table[n] = c; - } - crc_table_computed = 1; + crc_table_computed = 1; } /* Update a running CRC with the bytes buf[0..len-1]--the CRC @@ -34,24 +33,21 @@ void make_crc_table(void) is the 1's complement of the final running CRC (see the crc() routine below)). */ -unsigned long update_crc(unsigned long crc, QByteArray buf, - int len) -{ - unsigned long c = crc; - int n; +unsigned long update_crc(unsigned long crc, QByteArray buf, int len) { + unsigned long c = crc; + int n; - if (!crc_table_computed) - make_crc_table(); - for (n = 0; n < len; n++) { - c = crc_table[(c ^ static_cast(buf[n])) & 0xff] ^ (c >> 8); - } - return c; + if (!crc_table_computed) + make_crc_table(); + for (n = 0; n < len; n++) { + c = crc_table[(c ^ static_cast(buf[n])) & 0xff] ^ (c >> 8); + } + return c; } /* Return the CRC of the bytes buf[0..len-1]. */ -unsigned long crc(QByteArray buf, int len) -{ - return update_crc(0xffffffffL, buf, len) ^ 0xffffffffL; +unsigned long crc(QByteArray buf, int len) { + return update_crc(0xffffffffL, buf, len) ^ 0xffffffffL; } // Qt does not have the ability to export indexed PNG files with a @@ -60,8 +56,7 @@ unsigned long crc(QByteArray buf, int len) // and re-importing into porymap (Qt), will cause the image to be // interpreted as having too many colors. By properly exporting 16-palette // images in porymap, we can effectively avoid that issue. -void exportIndexed4BPPPng(QImage image, QString filepath) -{ +void exportIndexed4BPPPng(QImage image, QString filepath) { // Verify that the image is not empty if (image.isNull()) { logError(QString("Failed to export %1: the image is null.").arg(filepath)); @@ -83,13 +78,13 @@ void exportIndexed4BPPPng(QImage image, QString filepath) int width = image.width(); ihdr.append(static_cast((width >> 24) & 0xFF)); ihdr.append(static_cast((width >> 16) & 0xFF)); - ihdr.append(static_cast((width >> 8) & 0xFF)); - ihdr.append(static_cast((width >> 0) & 0xFF)); + ihdr.append(static_cast((width >> 8) & 0xFF)); + ihdr.append(static_cast((width >> 0) & 0xFF)); int height = image.height(); ihdr.append(static_cast((height >> 24) & 0xFF)); ihdr.append(static_cast((height >> 16) & 0xFF)); - ihdr.append(static_cast((height >> 8) & 0xFF)); - ihdr.append(static_cast((height >> 0) & 0xFF)); + ihdr.append(static_cast((height >> 8) & 0xFF)); + ihdr.append(static_cast((height >> 0) & 0xFF)); ihdr.append(static_cast(4)); // bit depth ihdr.append(static_cast(3)); // indexed color type ihdr.append(static_cast(0)); // compression method @@ -98,8 +93,8 @@ void exportIndexed4BPPPng(QImage image, QString filepath) unsigned long ihdrCRC = crc(ihdr, 17); ihdr.append(static_cast((ihdrCRC >> 24) & 0xFF)); ihdr.append(static_cast((ihdrCRC >> 16) & 0xFF)); - ihdr.append(static_cast((ihdrCRC >> 8) & 0xFF)); - ihdr.append(static_cast((ihdrCRC >> 0) & 0xFF)); + ihdr.append(static_cast((ihdrCRC >> 8) & 0xFF)); + ihdr.append(static_cast((ihdrCRC >> 0) & 0xFF)); // PLTE Chunk int numColors = image.colorCount(); @@ -114,8 +109,8 @@ void exportIndexed4BPPPng(QImage image, QString filepath) unsigned long plteCRC = crc(plte, numColors * 3 + 4); plte.append(static_cast((plteCRC >> 24) & 0xFF)); plte.append(static_cast((plteCRC >> 16) & 0xFF)); - plte.append(static_cast((plteCRC >> 8) & 0xFF)); - plte.append(static_cast((plteCRC >> 0) & 0xFF)); + plte.append(static_cast((plteCRC >> 8) & 0xFF)); + plte.append(static_cast((plteCRC >> 0) & 0xFF)); // IDAT Chunk QByteArray idat; @@ -146,8 +141,8 @@ void exportIndexed4BPPPng(QImage image, QString filepath) unsigned long idatCRC = crc(idat, compressedPixelData.length() + 4); idat.append(static_cast((idatCRC >> 24) & 0xFF)); idat.append(static_cast((idatCRC >> 16) & 0xFF)); - idat.append(static_cast((idatCRC >> 8) & 0xFF)); - idat.append(static_cast((idatCRC >> 0) & 0xFF)); + idat.append(static_cast((idatCRC >> 8) & 0xFF)); + idat.append(static_cast((idatCRC >> 0) & 0xFF)); // IEND Chunk QByteArray iend; @@ -155,30 +150,30 @@ void exportIndexed4BPPPng(QImage image, QString filepath) unsigned long iendCRC = crc(iend, 4); iend.append(static_cast((iendCRC >> 24) & 0xFF)); iend.append(static_cast((iendCRC >> 16) & 0xFF)); - iend.append(static_cast((iendCRC >> 8) & 0xFF)); - iend.append(static_cast((iendCRC >> 0) & 0xFF)); + iend.append(static_cast((iendCRC >> 8) & 0xFF)); + iend.append(static_cast((iendCRC >> 0) & 0xFF)); QByteArray data; data.append(pngHeader); data.append(static_cast(((ihdr.length() - 8) >> 24) & 0xFF)); data.append(static_cast(((ihdr.length() - 8) >> 16) & 0xFF)); - data.append(static_cast(((ihdr.length() - 8) >> 8) & 0xFF)); - data.append(static_cast(((ihdr.length() - 8) >> 0) & 0xFF)); + data.append(static_cast(((ihdr.length() - 8) >> 8) & 0xFF)); + data.append(static_cast(((ihdr.length() - 8) >> 0) & 0xFF)); data.append(ihdr); data.append(static_cast(((plte.length() - 8) >> 24) & 0xFF)); data.append(static_cast(((plte.length() - 8) >> 16) & 0xFF)); - data.append(static_cast(((plte.length() - 8) >> 8) & 0xFF)); - data.append(static_cast(((plte.length() - 8) >> 0) & 0xFF)); + data.append(static_cast(((plte.length() - 8) >> 8) & 0xFF)); + data.append(static_cast(((plte.length() - 8) >> 0) & 0xFF)); data.append(plte); data.append(static_cast(((idat.length() - 8) >> 24) & 0xFF)); data.append(static_cast(((idat.length() - 8) >> 16) & 0xFF)); - data.append(static_cast(((idat.length() - 8) >> 8) & 0xFF)); - data.append(static_cast(((idat.length() - 8) >> 0) & 0xFF)); + data.append(static_cast(((idat.length() - 8) >> 8) & 0xFF)); + data.append(static_cast(((idat.length() - 8) >> 0) & 0xFF)); data.append(idat); data.append(static_cast(((iend.length() - 8) >> 24) & 0xFF)); data.append(static_cast(((iend.length() - 8) >> 16) & 0xFF)); - data.append(static_cast(((iend.length() - 8) >> 8) & 0xFF)); - data.append(static_cast(((iend.length() - 8) >> 0) & 0xFF)); + data.append(static_cast(((iend.length() - 8) >> 8) & 0xFF)); + data.append(static_cast(((iend.length() - 8) >> 0) & 0xFF)); data.append(iend); QFile file(filepath); diff --git a/src/core/map.cpp b/src/core/map.cpp index 3d839ecc..d5d41abf 100644 --- a/src/core/map.cpp +++ b/src/core/map.cpp @@ -10,17 +10,16 @@ #include #include - -Map::Map(QObject *parent) : QObject(parent) -{ +Map::Map(QObject* parent) : QObject(parent) { editHistory.setClean(); } Map::~Map() { // delete all associated events while (!ownedEvents.isEmpty()) { - Event *last = ownedEvents.takeLast(); - if (last) delete last; + Event* last = ownedEvents.takeLast(); + if (last) + delete last; } } @@ -42,23 +41,19 @@ QString Map::mapConstantFromName(QString mapName) { return constantName; } -QString Map::objectEventsLabelFromName(QString mapName) -{ +QString Map::objectEventsLabelFromName(QString mapName) { return QString("%1_EventObjects").arg(mapName); } -QString Map::warpEventsLabelFromName(QString mapName) -{ +QString Map::warpEventsLabelFromName(QString mapName) { return QString("%1_MapWarps").arg(mapName); } -QString Map::coordEventsLabelFromName(QString mapName) -{ +QString Map::coordEventsLabelFromName(QString mapName) { return QString("%1_MapCoordEvents").arg(mapName); } -QString Map::bgEventsLabelFromName(QString mapName) -{ +QString Map::bgEventsLabelFromName(QString mapName) { return QString("%1_MapBGEvents").arg(mapName); } @@ -78,7 +73,7 @@ int Map::getBorderHeight() { return layout->border_height.toInt(nullptr, 0); } -bool Map::mapBlockChanged(int i, const Blockdata &cache) { +bool Map::mapBlockChanged(int i, const Blockdata& cache) { if (cache.length() <= i) return true; if (layout->blockdata.length() <= i) @@ -87,7 +82,7 @@ bool Map::mapBlockChanged(int i, const Blockdata &cache) { return layout->blockdata.at(i) != cache.at(i); } -bool Map::borderBlockChanged(int i, const Blockdata &cache) { +bool Map::borderBlockChanged(int i, const Blockdata& cache) { if (cache.length() <= i) return true; if (layout->border.length() <= i) @@ -98,19 +93,19 @@ bool Map::borderBlockChanged(int i, const Blockdata &cache) { void Map::cacheBorder() { layout->cached_border.clear(); - for (const auto &block : layout->border) + for (const auto& block : layout->border) layout->cached_border.append(block); } void Map::cacheBlockdata() { layout->cached_blockdata.clear(); - for (const auto &block : layout->blockdata) + for (const auto& block : layout->blockdata) layout->cached_blockdata.append(block); } void Map::cacheCollision() { layout->cached_collision.clear(); - for (const auto &block : layout->blockdata) + for (const auto& block : layout->blockdata) layout->cached_collision.append(block); } @@ -153,7 +148,7 @@ QPixmap Map::renderCollision(qreal opacity, bool ignoreCache) { return collision_pixmap; } -QPixmap Map::render(bool ignoreCache = false, MapLayout * fromLayout) { +QPixmap Map::render(bool ignoreCache = false, MapLayout* fromLayout) { bool changed_any = false; int width_ = getWidth(); int height_ = getHeight(); @@ -173,13 +168,8 @@ QPixmap Map::render(bool ignoreCache = false, MapLayout * fromLayout) { } changed_any = true; Block block = layout->blockdata.at(i); - QImage metatile_image = getMetatileImage( - block.tile, - fromLayout ? fromLayout->tileset_primary : layout->tileset_primary, - fromLayout ? fromLayout->tileset_secondary : layout->tileset_secondary, - metatileLayerOrder, - metatileLayerOpacity - ); + QImage metatile_image = getMetatileImage(block.tile, fromLayout ? fromLayout->tileset_primary : layout->tileset_primary, + fromLayout ? fromLayout->tileset_secondary : layout->tileset_secondary, metatileLayerOrder, metatileLayerOpacity); int map_y = width_ ? i / width_ : 0; int map_x = width_ ? i % width_ : 0; QPoint metatile_origin = QPoint(map_x * 16, map_y * 16); @@ -232,7 +222,7 @@ QPixmap Map::renderBorder(bool ignoreCache) { return layout->border_pixmap; } -QPixmap Map::renderConnection(MapConnection connection, MapLayout * fromLayout) { +QPixmap Map::renderConnection(MapConnection connection, MapLayout* fromLayout) { render(true, fromLayout); int x, y, w, h; if (connection.direction == "up") { @@ -263,7 +253,7 @@ QPixmap Map::renderConnection(MapConnection connection, MapLayout * fromLayout) h = getHeight(); } QImage connection_image = image.copy(x * 16, y * 16, w * 16, h * 16); - //connection_image = connection_image.convertToFormat(QImage::Format_Grayscale8); + // connection_image = connection_image.convertToFormat(QImage::Format_Grayscale8); return QPixmap::fromImage(connection_image); } @@ -274,14 +264,14 @@ void Map::setNewDimensionsBlockdata(int newWidth, int newHeight) { Blockdata newBlockdata; for (int y = 0; y < newHeight; y++) - for (int x = 0; x < newWidth; x++) { - if (x < oldWidth && y < oldHeight) { - int index = y * oldWidth + x; - newBlockdata.append(layout->blockdata.value(index)); - } else { - newBlockdata.append(0); + for (int x = 0; x < newWidth; x++) { + if (x < oldWidth && y < oldHeight) { + int index = y * oldWidth + x; + newBlockdata.append(layout->blockdata.value(index)); + } else { + newBlockdata.append(0); + } } - } layout->blockdata = newBlockdata; } @@ -293,14 +283,14 @@ void Map::setNewBorderDimensionsBlockdata(int newWidth, int newHeight) { Blockdata newBlockdata; for (int y = 0; y < newHeight; y++) - for (int x = 0; x < newWidth; x++) { - if (x < oldWidth && y < oldHeight) { - int index = y * oldWidth + x; - newBlockdata.append(layout->border.value(index)); - } else { - newBlockdata.append(0); + for (int x = 0; x < newWidth; x++) { + if (x < oldWidth && y < oldHeight) { + int index = y * oldWidth + x; + newBlockdata.append(layout->border.value(index)); + } else { + newBlockdata.append(0); + } } - } layout->border = newBlockdata; } @@ -328,7 +318,7 @@ void Map::setBorderDimensions(int newWidth, int newHeight, bool setNewBlockdata) emit mapChanged(this); } -bool Map::getBlock(int x, int y, Block *out) { +bool Map::getBlock(int x, int y, Block* out) { if (x >= 0 && x < getWidth() && y >= 0 && y < getHeight()) { int i = y * getWidth() + x; *out = layout->blockdata.value(i); @@ -409,21 +399,21 @@ void Map::magicFillCollisionElevation(int initialX, int initialY, uint16_t colli } } -QList Map::getAllEvents() const { - QList all_events; - for (const auto &event_list : events) { +QList Map::getAllEvents() const { + QList all_events; + for (const auto& event_list : events) { all_events << event_list; } return all_events; } -QStringList Map::eventScriptLabels(const QString &event_group_type) const { +QStringList Map::eventScriptLabels(const QString& event_group_type) const { QStringList scriptLabels; if (event_group_type.isEmpty()) { - for (const auto *event : getAllEvents()) + for (const auto* event : getAllEvents()) scriptLabels << event->get("script_label"); } else { - for (const auto *event : events.value(event_group_type)) + for (const auto* event : events.value(event_group_type)) scriptLabels << event->get("script_label"); } @@ -437,15 +427,16 @@ QStringList Map::eventScriptLabels(const QString &event_group_type) const { return scriptLabels; } -void Map::removeEvent(Event *event) { +void Map::removeEvent(Event* event) { for (QString key : events.keys()) { events[key].removeAll(event); } } -void Map::addEvent(Event *event) { +void Map::addEvent(Event* event) { events[event->get("event_group_type")].append(event); - if (!ownedEvents.contains(event)) ownedEvents.append(event); + if (!ownedEvents.contains(event)) + ownedEvents.append(event); } bool Map::hasUnsavedChanges() { diff --git a/src/core/metatile.cpp b/src/core/metatile.cpp index 4c97418d..a70ffd4a 100644 --- a/src/core/metatile.cpp +++ b/src/core/metatile.cpp @@ -2,12 +2,8 @@ #include "tileset.h" #include "project.h" -Metatile::Metatile() : - behavior(0), - layerType(0), - encounterType(0), - terrainType(0) -{ } +Metatile::Metatile() : behavior(0), layerType(0), encounterType(0), terrainType(0) { +} int Metatile::getBlockIndex(int index) { if (index < Project::getNumMetatilesPrimary()) { @@ -17,7 +13,7 @@ int Metatile::getBlockIndex(int index) { } } -QPoint Metatile::coordFromPixmapCoord(const QPointF &pixelCoord) { +QPoint Metatile::coordFromPixmapCoord(const QPointF& pixelCoord) { int x = static_cast(pixelCoord.x()) / 16; int y = static_cast(pixelCoord.y()) / 16; return QPoint(x, y); diff --git a/src/core/metatileparser.cpp b/src/core/metatileparser.cpp index 3bbed668..c71d27b5 100644 --- a/src/core/metatileparser.cpp +++ b/src/core/metatileparser.cpp @@ -3,18 +3,15 @@ #include "log.h" #include "project.h" -MetatileParser::MetatileParser() -{ - +MetatileParser::MetatileParser() { } -QList MetatileParser::parse(QString filepath, bool *error, bool primaryTileset) -{ +QList MetatileParser::parse(QString filepath, bool* error, bool primaryTileset) { QFile file(filepath); if (!file.open(QIODevice::ReadOnly)) { *error = true; logError(QString("Could not open Advance Map 1.92 Metatile .bvd file '%1': ").arg(filepath) + file.errorString()); - return { }; + return {}; } QByteArray in = file.readAll(); @@ -23,81 +20,69 @@ QList MetatileParser::parse(QString filepath, bool *error, bool prima if (in.length() < 9 || in.length() % 2 != 0) { *error = true; logError(QString("Advance Map 1.92 Metatile .bvd file '%1' is an unexpected size.").arg(filepath)); - return { }; + return {}; } int projIdOffset = in.length() - 4; int metatileSize = 16; int attrSize; BaseGameVersion version; - if (in.at(projIdOffset + 0) == 'R' - && in.at(projIdOffset + 1) == 'S' - && in.at(projIdOffset + 2) == 'E' - && in.at(projIdOffset + 3) == ' ') { + if (in.at(projIdOffset + 0) == 'R' && in.at(projIdOffset + 1) == 'S' && in.at(projIdOffset + 2) == 'E' && in.at(projIdOffset + 3) == ' ') { // ruby and emerald are handled equally here. version = BaseGameVersion::pokeemerald; attrSize = 2; - } else if (in.at(projIdOffset + 0) == 'F' - && in.at(projIdOffset + 1) == 'R' - && in.at(projIdOffset + 2) == 'L' - && in.at(projIdOffset + 3) == 'G') { + } else if (in.at(projIdOffset + 0) == 'F' && in.at(projIdOffset + 1) == 'R' && in.at(projIdOffset + 2) == 'L' && in.at(projIdOffset + 3) == 'G') { version = BaseGameVersion::pokefirered; attrSize = 4; } else { *error = true; logError(QString("Detected unsupported game type from .bvd file. Last 4 bytes of file must be 'RSE ' or 'FRLG'.")); - return { }; + return {}; } int maxMetatiles = primaryTileset ? Project::getNumMetatilesPrimary() : Project::getNumMetatilesTotal() - Project::getNumMetatilesPrimary(); - int numMetatiles = static_cast(in.at(0)) | - (static_cast(in.at(1)) << 8) | - (static_cast(in.at(2)) << 16) | - (static_cast(in.at(3)) << 24); + int numMetatiles = static_cast(in.at(0)) | (static_cast(in.at(1)) << 8) | (static_cast(in.at(2)) << 16) + | (static_cast(in.at(3)) << 24); if (numMetatiles > maxMetatiles) { *error = true; logError(QString(".bvd file contains data for %1 metatiles, but the maximum number of metatiles is %2.").arg(numMetatiles).arg(maxMetatiles)); - return { }; + return {}; } if (numMetatiles < 1) { *error = true; logError(QString(".bvd file contains no data for metatiles.")); - return { }; + return {}; } int expectedFileSize = 4 + (metatileSize * numMetatiles) + (attrSize * numMetatiles) + 4; if (in.length() != expectedFileSize) { *error = true; logError(QString(".bvd file is an unexpected size. Expected %1 bytes, but it has %2 bytes.").arg(expectedFileSize).arg(in.length())); - return { }; + return {}; } QList metatiles; for (int i = 0; i < numMetatiles; i++) { - Metatile *metatile = new Metatile(); + Metatile* metatile = new Metatile(); QList tiles; for (int j = 0; j < 8; j++) { int metatileOffset = 4 + i * metatileSize + j * 2; - uint16_t word = static_cast( - static_cast(in.at(metatileOffset)) | - (static_cast(in.at(metatileOffset + 1)) << 8)); + uint16_t word + = static_cast(static_cast(in.at(metatileOffset)) | (static_cast(in.at(metatileOffset + 1)) << 8)); Tile tile(word & 0x3ff, (word >> 10) & 1, (word >> 11) & 1, (word >> 12) & 0xf); tiles.append(tile); } int attrOffset = 4 + (numMetatiles * metatileSize) + (i * attrSize); if (version == BaseGameVersion::pokefirered) { - int value = static_cast(in.at(attrOffset)) | - (static_cast(in.at(attrOffset + 1)) << 8) | - (static_cast(in.at(attrOffset + 2)) << 16) | - (static_cast(in.at(attrOffset + 3)) << 24); + int value = static_cast(in.at(attrOffset)) | (static_cast(in.at(attrOffset + 1)) << 8) + | (static_cast(in.at(attrOffset + 2)) << 16) | (static_cast(in.at(attrOffset + 3)) << 24); metatile->behavior = value & 0x1FF; metatile->terrainType = (value & 0x3E00) >> 9; metatile->encounterType = (value & 0x7000000) >> 24; metatile->layerType = (value & 0x60000000) >> 29; } else { - int value = static_cast(in.at(attrOffset)) | - (static_cast(in.at(attrOffset + 1)) << 8); + int value = static_cast(in.at(attrOffset)) | (static_cast(in.at(attrOffset + 1)) << 8); metatile->behavior = value & 0xFF; metatile->layerType = (value & 0xF000) >> 12; metatile->encounterType = 0; diff --git a/src/core/paletteutil.cpp b/src/core/paletteutil.cpp index 3a6f7ff7..475e0234 100644 --- a/src/core/paletteutil.cpp +++ b/src/core/paletteutil.cpp @@ -3,12 +3,10 @@ #include #include -PaletteUtil::PaletteUtil() -{ - +PaletteUtil::PaletteUtil() { } -QList PaletteUtil::parse(QString filepath, bool *error) { +QList PaletteUtil::parse(QString filepath, bool* error) { QFileInfo info(filepath); QString extension = info.completeSuffix(); if (extension.isNull()) { @@ -34,7 +32,7 @@ QList PaletteUtil::parse(QString filepath, bool *error) { return QList(); } -QList PaletteUtil::parsePal(QString filepath, bool *error) { +QList PaletteUtil::parsePal(QString filepath, bool* error) { QFile file(filepath); if (!file.open(QIODevice::ReadOnly)) { *error = true; @@ -53,7 +51,7 @@ QList PaletteUtil::parsePal(QString filepath, bool *error) { } } -QList PaletteUtil::parseJASC(QString filepath, bool *error) { +QList PaletteUtil::parseJASC(QString filepath, bool* error) { QFile file(filepath); if (!file.open(QIODevice::ReadOnly)) { *error = true; @@ -105,9 +103,7 @@ QList PaletteUtil::parseJASC(QString filepath, bool *error) { return QList(); } - palette.append(qRgb(this->clampColorValue(red), - this->clampColorValue(green), - this->clampColorValue(blue))); + palette.append(qRgb(this->clampColorValue(red), this->clampColorValue(green), this->clampColorValue(blue))); } else { *error = true; logError(QString("JASC palette file '%1' had an unexpected format. Invalid color '%2'.").arg(filepath).arg(line)); @@ -120,7 +116,7 @@ QList PaletteUtil::parseJASC(QString filepath, bool *error) { return palette; } -QList PaletteUtil::parseAdvanceMapPal(QString filepath, bool *error) { +QList PaletteUtil::parseAdvanceMapPal(QString filepath, bool* error) { QFile file(filepath); if (!file.open(QIODevice::ReadOnly)) { *error = true; @@ -133,7 +129,9 @@ QList PaletteUtil::parseAdvanceMapPal(QString filepath, bool *error) { if (in.length() % 4 != 0) { *error = true; - logError(QString("Advance Map 1.92 palette file '%1' had an unexpected format. File's length must be a multiple of 4, but the length is %2.").arg(filepath).arg(in.length())); + logError(QString("Advance Map 1.92 palette file '%1' had an unexpected format. File's length must be a multiple of 4, but the length is %2.") + .arg(filepath) + .arg(in.length())); return QList(); } @@ -143,16 +141,14 @@ QList PaletteUtil::parseAdvanceMapPal(QString filepath, bool *error) { unsigned char red = static_cast(in.at(i)); unsigned char green = static_cast(in.at(i + 1)); unsigned char blue = static_cast(in.at(i + 2)); - palette.append(qRgb(this->clampColorValue(red), - this->clampColorValue(green), - this->clampColorValue(blue))); + palette.append(qRgb(this->clampColorValue(red), this->clampColorValue(green), this->clampColorValue(blue))); i += 4; } return palette; } -QList PaletteUtil::parseAdobeColorTable(QString filepath, bool *error) { +QList PaletteUtil::parseAdobeColorTable(QString filepath, bool* error) { QFile file(filepath); if (!file.open(QIODevice::ReadOnly)) { *error = true; @@ -165,7 +161,9 @@ QList PaletteUtil::parseAdobeColorTable(QString filepath, bool *error) { if (in.length() != 0x300) { *error = true; - logError(QString("Adobe Color Table palette file '%1' had an unexpected format. File's length must be exactly 768, but the length is %2.").arg(filepath).arg(in.length())); + logError(QString("Adobe Color Table palette file '%1' had an unexpected format. File's length must be exactly 768, but the length is %2.") + .arg(filepath) + .arg(in.length())); return QList(); } @@ -175,16 +173,14 @@ QList PaletteUtil::parseAdobeColorTable(QString filepath, bool *error) { unsigned char red = static_cast(in.at(i)); unsigned char green = static_cast(in.at(i + 1)); unsigned char blue = static_cast(in.at(i + 2)); - palette.append(qRgb(this->clampColorValue(red), - this->clampColorValue(green), - this->clampColorValue(blue))); + palette.append(qRgb(this->clampColorValue(red), this->clampColorValue(green), this->clampColorValue(blue))); i += 3; } return palette; } -QList PaletteUtil::parseTileLayerPro(QString filepath, bool *error) { +QList PaletteUtil::parseTileLayerPro(QString filepath, bool* error) { QFile file(filepath); if (!file.open(QIODevice::ReadOnly)) { *error = true; @@ -203,7 +199,9 @@ QList PaletteUtil::parseTileLayerPro(QString filepath, bool *error) { if (in.length() != 0x304) { *error = true; - logError(QString("Tile Layer Pro palette file '%1' had an unexpected format. File's length must be exactly 772, but the length is %2.").arg(filepath).arg(in.length())); + logError(QString("Tile Layer Pro palette file '%1' had an unexpected format. File's length must be exactly 772, but the length is %2.") + .arg(filepath) + .arg(in.length())); return QList(); } @@ -213,16 +211,14 @@ QList PaletteUtil::parseTileLayerPro(QString filepath, bool *error) { unsigned char red = static_cast(in.at(i)); unsigned char green = static_cast(in.at(i + 1)); unsigned char blue = static_cast(in.at(i + 2)); - palette.append(qRgb(this->clampColorValue(red), - this->clampColorValue(green), - this->clampColorValue(blue))); + palette.append(qRgb(this->clampColorValue(red), this->clampColorValue(green), this->clampColorValue(blue))); i += 3; } return palette; } -QList PaletteUtil::parseAdvancePaletteEditor(QString filepath, bool *error) { +QList PaletteUtil::parseAdvancePaletteEditor(QString filepath, bool* error) { QFile file(filepath); if (!file.open(QIODevice::ReadOnly)) { *error = true; @@ -254,13 +250,11 @@ QList PaletteUtil::parseAdvancePaletteEditor(QString filepath, bool *error return QList(); } - raw = ((raw & 0xFF)<< 8) | ((raw >> 8) & 0xFF); + raw = ((raw & 0xFF) << 8) | ((raw >> 8) & 0xFF); int red = (raw & 0x1F) * 8; int green = ((raw >> 5) & 0x1F) * 8; int blue = ((raw >> 10) & 0x1F) * 8; - palette.append(qRgb(this->clampColorValue(red), - this->clampColorValue(green), - this->clampColorValue(blue))); + palette.append(qRgb(this->clampColorValue(red), this->clampColorValue(green), this->clampColorValue(blue))); } file.close(); @@ -282,9 +276,7 @@ void PaletteUtil::writeJASC(QString filepath, QVector palette, int offset, for (int i = offset; i < offset + nColors; i++) { QRgb color = palette.at(i); - text += QString::number(qRed(color)) + " " - + QString::number(qGreen(color)) + " " - + QString::number(qBlue(color)) + "\r\n"; + text += QString::number(qRed(color)) + " " + QString::number(qGreen(color)) + " " + QString::number(qBlue(color)) + "\r\n"; } QFile file(filepath); diff --git a/src/core/parseutil.cpp b/src/core/parseutil.cpp index 30ebe19c..6b50bae3 100644 --- a/src/core/parseutil.cpp +++ b/src/core/parseutil.cpp @@ -6,23 +6,23 @@ #include #include - -void ParseUtil::set_root(const QString &dir) { +void ParseUtil::set_root(const QString& dir) { this->root = dir; } -void ParseUtil::error(const QString &message, const QString &expression) { +void ParseUtil::error(const QString& message, const QString& expression) { QStringList lines = text.split(QRegularExpression("[\r\n]")); int lineNum = 0, colNum = 0; for (QString line : lines) { lineNum++; colNum = line.indexOf(expression) + 1; - if (colNum) break; + if (colNum) + break; } logError(QString("%1:%2:%3: %4").arg(file).arg(lineNum).arg(colNum).arg(message)); } -QString ParseUtil::readTextFile(const QString &path) { +QString ParseUtil::readTextFile(const QString& path) { QFile file(path); if (!file.open(QIODevice::ReadOnly)) { logError(QString("Could not open '%1': ").arg(path) + file.errorString()); @@ -37,17 +37,17 @@ QString ParseUtil::readTextFile(const QString &path) { return text; } -int ParseUtil::textFileLineCount(const QString &path) { +int ParseUtil::textFileLineCount(const QString& path) { const QString text = readTextFile(path); return text.split('\n').count() + 1; } -QList ParseUtil::parseAsm(const QString &filename) { +QList ParseUtil::parseAsm(const QString& filename) { QList parsed; text = readTextFile(root + '/' + filename); const QStringList lines = removeLineComments(text, "@").split('\n'); - for (const auto &line : lines) { + for (const auto& line : lines) { const QString trimmedLine = line.trimmed(); if (trimmedLine.isEmpty()) { continue; @@ -70,17 +70,23 @@ QList ParseUtil::parseAsm(const QString &filename) { return parsed; } -int ParseUtil::evaluateDefine(const QString &define, const QMap &knownDefines) { +int ParseUtil::evaluateDefine(const QString& define, const QMap& knownDefines) { QList tokens = tokenizeExpression(define, knownDefines); QList postfixExpression = generatePostfix(tokens); return evaluatePostfix(postfixExpression); } -QList ParseUtil::tokenizeExpression(QString expression, const QMap &knownIdentifiers) { +QList ParseUtil::tokenizeExpression(QString expression, const QMap& knownIdentifiers) { QList tokens; - QStringList tokenTypes = (QStringList() << "hex" << "decimal" << "identifier" << "operator" << "leftparen" << "rightparen"); - QRegularExpression re("^(?0x[0-9a-fA-F]+)|(?[0-9]+)|(?[a-zA-Z_0-9]+)|(?[+\\-*\\/<>|^%]+)|(?\\()|(?\\))"); + QStringList tokenTypes = (QStringList() << "hex" + << "decimal" + << "identifier" + << "operator" + << "leftparen" + << "rightparen"); + QRegularExpression re( + "^(?0x[0-9a-fA-F]+)|(?[0-9]+)|(?[a-zA-Z_0-9]+)|(?[+\\-*\\/<>|^%]+)|(?\\()|(?\\))"); expression = expression.trimmed(); while (!expression.isEmpty()) { @@ -100,15 +106,12 @@ QList ParseUtil::tokenizeExpression(QString expression, const QMap ParseUtil::tokenizeExpression(QString expression, const QMap Token::precedenceMap = QMap( -{ - {"*", 3}, - {"/", 3}, - {"+", 4}, - {"-", 4}, - {"<<", 5}, - {">>", 5}, - {"&", 8}, - {"^", 9}, - {"|", 10} -}); +QMap Token::precedenceMap + = QMap({ { "*", 3 }, { "/", 3 }, { "+", 4 }, { "-", 4 }, { "<<", 5 }, { ">>", 5 }, { "&", 8 }, { "^", 9 }, { "|", 10 } }); // Shunting-yard algorithm for generating postfix notation. // https://en.wikipedia.org/wiki/Shunting-yard_algorithm -QList ParseUtil::generatePostfix(const QList &tokens) { +QList ParseUtil::generatePostfix(const QList& tokens) { QList output; QStack operatorStack; for (Token token : tokens) { @@ -157,9 +150,7 @@ QList ParseUtil::generatePostfix(const QList &tokens) { } } else { // token is an operator - while (!operatorStack.isEmpty() - && operatorStack.top().operatorPrecedence <= token.operatorPrecedence - && operatorStack.top().value != "(") { + while (!operatorStack.isEmpty() && operatorStack.top().operatorPrecedence <= token.operatorPrecedence && operatorStack.top().value != "(") { output.append(operatorStack.pop()); } operatorStack.push(token); @@ -179,7 +170,7 @@ QList ParseUtil::generatePostfix(const QList &tokens) { // Evaluate postfix expression. // https://en.wikipedia.org/wiki/Reverse_Polish_notation#Postfix_evaluation_algorithm -int ParseUtil::evaluatePostfix(const QList &postfix) { +int ParseUtil::evaluatePostfix(const QList& postfix) { QStack stack; for (Token token : postfix) { if (token.type == TokenClass::Operator && stack.size() > 1) { @@ -213,7 +204,7 @@ int ParseUtil::evaluatePostfix(const QList &postfix) { return stack.size() ? stack.pop().value.toInt(nullptr, 0) : 0; } -QString ParseUtil::readCIncbin(const QString &filename, const QString &label) { +QString ParseUtil::readCIncbin(const QString& filename, const QString& label) { QString path; if (label.isNull()) { @@ -222,11 +213,11 @@ QString ParseUtil::readCIncbin(const QString &filename, const QString &label) { text = readTextFile(root + "/" + filename); - QRegExp *re = new QRegExp(QString( - "\\b%1\\b" - "\\s*\\[?\\s*\\]?\\s*=\\s*" - "INCBIN_[US][0-9][0-9]?" - "\\(\\s*\"([^\"]*)\"\\s*\\)").arg(label)); + QRegExp* re = new QRegExp(QString("\\b%1\\b" + "\\s*\\[?\\s*\\]?\\s*=\\s*" + "INCBIN_[US][0-9][0-9]?" + "\\(\\s*\"([^\"]*)\"\\s*\\)") + .arg(label)); int pos = re->indexIn(text); if (pos != -1) { @@ -236,10 +227,7 @@ QString ParseUtil::readCIncbin(const QString &filename, const QString &label) { return path; } -QMap ParseUtil::readCDefines(const QString &filename, - const QStringList &prefixes, - QMap allDefines) -{ +QMap ParseUtil::readCDefines(const QString& filename, const QStringList& prefixes, QMap allDefines) { QMap filteredDefines; file = filename; @@ -267,7 +255,8 @@ QMap ParseUtil::readCDefines(const QString &filename, QRegularExpressionMatch match = iter.next(); QString name = match.captured("defineName"); QString expression = match.captured("defineValue"); - if (expression == " ") continue; + if (expression == " ") + continue; int value = evaluateDefine(expression, allDefines); allDefines.insert(name, value); for (QString prefix : prefixes) { @@ -279,10 +268,7 @@ QMap ParseUtil::readCDefines(const QString &filename, return filteredDefines; } -QStringList ParseUtil::readCDefinesSorted(const QString &filename, - const QStringList &prefixes, - const QMap &knownDefines) -{ +QStringList ParseUtil::readCDefinesSorted(const QString& filename, const QStringList& prefixes, const QMap& knownDefines) { QMap defines = readCDefines(filename, prefixes, knownDefines); // The defines should to be sorted by their underlying value, not alphabetically. @@ -294,7 +280,7 @@ QStringList ParseUtil::readCDefinesSorted(const QString &filename, return definesInverse.values(); } -QStringList ParseUtil::readCArray(const QString &filename, const QString &label) { +QStringList ParseUtil::readCArray(const QString& filename, const QString& label) { QStringList list; if (label.isNull()) { @@ -312,7 +298,8 @@ QStringList ParseUtil::readCArray(const QString &filename, const QString &label) QStringList split = body.split(','); for (QString item : split) { item = item.trimmed(); - if (!item.contains(QRegularExpression("[^A-Za-z0-9_&()\\s]"))) list.append(item); + if (!item.contains(QRegularExpression("[^A-Za-z0-9_&()\\s]"))) + list.append(item); // do not print error info here because this is called dozens of times } } @@ -320,7 +307,7 @@ QStringList ParseUtil::readCArray(const QString &filename, const QString &label) return list; } -QMap ParseUtil::readNamedIndexCArray(const QString &filename, const QString &label) { +QMap ParseUtil::readNamedIndexCArray(const QString& filename, const QString& label) { text = readTextFile(root + "/" + filename); QMap map; @@ -340,10 +327,10 @@ QMap ParseUtil::readNamedIndexCArray(const QString &filename, return map; } -QList ParseUtil::getLabelMacros(const QList &list, const QString &label) { +QList ParseUtil::getLabelMacros(const QList& list, const QString& label) { bool in_label = false; QList new_list; - for (const auto ¶ms : list) { + for (const auto& params : list) { const QString macro = params.value(0); if (macro == ".label") { if (params.value(1) == label) { @@ -364,10 +351,10 @@ QList ParseUtil::getLabelMacros(const QList &list, con // For if you don't care about filtering by macro, // and just want all values associated with some label. -QStringList ParseUtil::getLabelValues(const QList &list, const QString &label) { +QStringList ParseUtil::getLabelValues(const QList& list, const QString& label) { const QList labelMacros = getLabelMacros(list, label); QStringList values; - for (const auto ¶ms : labelMacros) { + for (const auto& params : labelMacros) { const QString macro = params.value(0); if (macro == ".align" || macro == ".ifdef" || macro == ".ifndef") { continue; @@ -379,7 +366,7 @@ QStringList ParseUtil::getLabelValues(const QList &list, const QStr return values; } -bool ParseUtil::tryParseJsonFile(QJsonDocument *out, const QString &filepath) { +bool ParseUtil::tryParseJsonFile(QJsonDocument* out, const QString& filepath) { QFile file(filepath); if (!file.open(QIODevice::ReadOnly)) { logError(QString("Error: Could not open %1 for reading").arg(filepath)); @@ -399,7 +386,7 @@ bool ParseUtil::tryParseJsonFile(QJsonDocument *out, const QString &filepath) { return true; } -bool ParseUtil::ensureFieldsExist(const QJsonObject &obj, const QList &fields) { +bool ParseUtil::ensureFieldsExist(const QJsonObject& obj, const QList& fields) { for (QString field : fields) { if (!obj.contains(field)) { logError(QString("JSON object is missing field '%1'.").arg(field)); @@ -409,7 +396,7 @@ bool ParseUtil::ensureFieldsExist(const QJsonObject &obj, const QList & return true; } -int ParseUtil::getScriptLineNumber(const QString &filePath, const QString &scriptLabel) { +int ParseUtil::getScriptLineNumber(const QString& filePath, const QString& scriptLabel) { if (scriptLabel.isEmpty()) return 0; @@ -421,7 +408,7 @@ int ParseUtil::getScriptLineNumber(const QString &filePath, const QString &scrip return 0; } -int ParseUtil::getRawScriptLineNumber(QString text, const QString &scriptLabel) { +int ParseUtil::getRawScriptLineNumber(QString text, const QString& scriptLabel) { text = removeStringLiterals(text); text = removeLineComments(text, "@"); @@ -436,9 +423,9 @@ int ParseUtil::getRawScriptLineNumber(QString text, const QString &scriptLabel) return 0; } -int ParseUtil::getPoryScriptLineNumber(QString text, const QString &scriptLabel) { +int ParseUtil::getPoryScriptLineNumber(QString text, const QString& scriptLabel) { text = removeStringLiterals(text); - text = removeLineComments(text, {"//", "#"}); + text = removeLineComments(text, { "//", "#" }); static const QRegularExpression re_poryScriptLabel("\\b(script)(\\((global|local)\\))?\\s*\\b(?