diff --git a/libaegisub/common/hotkey.cpp b/libaegisub/common/hotkey.cpp index c0be25f8b..a2cebeef9 100644 --- a/libaegisub/common/hotkey.cpp +++ b/libaegisub/common/hotkey.cpp @@ -15,6 +15,7 @@ #include "libaegisub/hotkey.h" #include "libaegisub/cajun/writer.h" +#include "libaegisub/fs.h" #include "libaegisub/io.h" #include "libaegisub/json.h" #include "libaegisub/log.h" @@ -43,6 +44,7 @@ struct hotkey_visitor : json::ConstVisitor { std::string const& context; std::string const& command; Hotkey::HotkeyMap& map; + bool needs_backup = false; hotkey_visitor(std::string const& context, std::string const& command, Hotkey::HotkeyMap& map) : context(context), command(command), map(map) { } @@ -72,6 +74,7 @@ struct hotkey_visitor : json::ConstVisitor { key_str += static_cast(key_it->second); map.insert(make_pair(command, Combo(context, command, std::move(key_str)))); + needs_backup = true; } void Visit(const json::Array& array) override { } @@ -100,6 +103,7 @@ void Hotkey::BuildHotkey(std::string const& context, json::Object const& hotkeys hotkey_visitor visitor{context, command.first, cmd_map}; for (auto const& hotkey : command_hotkeys) hotkey.Accept(visitor); + backup_config_file |= visitor.needs_backup; } } @@ -183,6 +187,9 @@ void Hotkey::Flush() { combo_array.push_back(keys); } + if (backup_config_file && fs::FileExists(config_file) && !fs::FileExists(config_file.string() + ".3_1")) + fs::Copy(config_file, config_file.string() + ".3_1"); + io::Save file(config_file); JsonWriter::Write(root, file.Get()); } diff --git a/libaegisub/include/libaegisub/hotkey.h b/libaegisub/include/libaegisub/hotkey.h index 7d866f6b3..81cae91fb 100644 --- a/libaegisub/include/libaegisub/hotkey.h +++ b/libaegisub/include/libaegisub/hotkey.h @@ -67,6 +67,7 @@ private: HotkeyMap cmd_map; ///< Command name -> Combo std::vector str_map; ///< Sorted by string representation const agi::fs::path config_file; ///< Default user config location. + bool backup_config_file = false; /// Build hotkey map. /// @param context Context being parsed. diff --git a/tests/tests/hotkey.cpp b/tests/tests/hotkey.cpp index f81f99206..de0dc9d08 100644 --- a/tests/tests/hotkey.cpp +++ b/tests/tests/hotkey.cpp @@ -17,6 +17,8 @@ #include #include +#include + using namespace agi::hotkey; static const char simple_valid[] = R"raw({ @@ -196,3 +198,22 @@ TEST(lagi_hotkey, combo_stuff) { EXPECT_STREQ("cmd2", c.CmdName().c_str()); EXPECT_STREQ("Default", c.Context().c_str()); } + +TEST(lagi_hotkey, old_format_is_backed_up_before_migrating) { + { + std::ofstream tmp("data/hotkey_tmp"); + tmp.write(simple_valid, sizeof(simple_valid)); + } + + { + Hotkey h("data/hotkey_tmp", "{}"); + h.SetHotkeyMap(h.GetHotkeyMap()); + } + { + std::ifstream tmp("data/hotkey_tmp.3_1"); + ASSERT_TRUE(tmp.good()); + char buff[sizeof(simple_valid)]; + tmp.read(buff, sizeof(buff)); + ASSERT_TRUE(memcmp(buff, simple_valid, sizeof(buff)) == 0); + } +}