Textractor_test/extensions/regexreplacer.cpp

72 lines
2.3 KiB
C++
Raw Normal View History

2021-10-19 04:57:36 +08:00
#include "extension.h"
#include "module.h"
#include "blockmarkup.h"
#include <fstream>
extern const wchar_t* REGEX_REPLACER_INSTRUCTIONS;
2021-11-07 03:53:51 +08:00
const char* REPLACE_SAVE_FILE = "SavedRegexReplacements.txt";
2021-10-19 04:57:36 +08:00
2021-11-07 03:53:51 +08:00
std::atomic<std::filesystem::file_time_type> replaceFileLastWrite = {};
2021-10-19 04:57:36 +08:00
concurrency::reader_writer_lock m;
2021-11-07 03:53:51 +08:00
std::vector<std::tuple<std::wregex, std::wstring, std::regex_constants::match_flag_type>> replacements;
void UpdateReplacements()
{
try
{
if (replaceFileLastWrite.exchange(std::filesystem::last_write_time(REPLACE_SAVE_FILE)) == std::filesystem::last_write_time(REPLACE_SAVE_FILE)) return;
std::scoped_lock lock(m);
replacements.clear();
std::ifstream stream(REPLACE_SAVE_FILE, std::ios::binary);
BlockMarkupIterator savedFilters(stream, Array<std::wstring_view>{ L"|REGEX|", L"|BECOMES|", L"|MODIFIER|" });
while (auto read = savedFilters.Next())
{
const auto& [regex, replacement, modifier] = read.value();
try
{
replacements.emplace_back(
std::wregex(regex, modifier.find(L'i') == std::string::npos ? std::regex::ECMAScript : std::regex::icase),
replacement,
modifier.find(L'g') == std::string::npos ? std::regex_constants::format_first_only : std::regex_constants::format_default
);
}
catch (std::regex_error) {}
}
}
catch (std::filesystem::filesystem_error) { replaceFileLastWrite.store({}); }
}
2021-10-19 04:57:36 +08:00
BOOL WINAPI DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
2021-11-07 03:53:51 +08:00
UpdateReplacements();
if (replacements.empty())
2021-10-29 15:25:54 +08:00
{
2021-11-07 03:53:51 +08:00
auto file = std::ofstream(REPLACE_SAVE_FILE, std::ios::binary) << "\xff\xfe";
2021-10-19 04:57:36 +08:00
for (auto ch : std::wstring_view(REGEX_REPLACER_INSTRUCTIONS))
file << (ch == L'\n' ? std::string_view("\r\0\n", 4) : std::string_view((char*)&ch, 2));
2021-11-14 06:49:07 +08:00
SpawnThread([] { _spawnlp(_P_DETACH, "notepad", "notepad", REPLACE_SAVE_FILE, NULL); }); // show file to user
2021-10-19 04:57:36 +08:00
}
}
break;
case DLL_PROCESS_DETACH:
{
}
break;
}
return TRUE;
}
bool ProcessSentence(std::wstring& sentence, SentenceInfo sentenceInfo)
{
2021-11-07 03:53:51 +08:00
UpdateReplacements();
2021-10-19 04:57:36 +08:00
concurrency::reader_writer_lock::scoped_lock_read readLock(m);
2021-11-07 03:53:51 +08:00
for (const auto& [regex, replacement, flags] : replacements) sentence = std::regex_replace(sentence, regex, replacement, flags);
2021-10-19 04:57:36 +08:00
return true;
}