#include "files_image_edit.h" #include "files_win32_replace.h" #include namespace ks::files { namespace { struct ImageFile { HANDLE handle=INVALID_HANDLE_VALUE; ~ImageFile() {if(handle!=INVALID_HANDLE_VALUE) CloseHandle(handle);} }; struct StagedImage { std::filesystem::path path; ~StagedImage() {if(!path.empty()) DeleteFileW(path.c_str());} }; [[noreturn]] void fail(const char *message,DWORD error=GetLastError()) { throw std::system_error(static_cast(error),std::system_category(),message); } ImageRevision readRevision(HANDLE handle) { const auto revision=fileVersion(handle); if(revision.info.dwFileAttributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)) throw std::runtime_error("Choose a regular local image."); return revision; } bool contains(unsigned width,unsigned height,const ImageRegion &area) { return area.width && area.height && area.x=4 || !contains(sideways?region.height:region.width,sideways?region.width:region.height,area)) throw std::runtime_error("The crop rectangle must fit inside the image."); const auto width=region.width, height=region.height; switch(geometry.turns) { case 0: region.x+=area.x; region.y+=area.y; break; case 1: region.x+=area.y; region.y+=height-area.x-area.width; break; case 2: region.x+=width-area.x-area.width; region.y+=height-area.y-area.height; break; case 3: region.x+=width-area.y-area.height; region.y+=area.x; break; } region.width=sideways?area.height:area.width; region.height=sideways?area.width:area.height; return geometry; } ImageRaster transformImage(const ImageRaster &original,const ImageGeometry &geometry) { const auto ®ion=geometry.region; if(geometry.turns>=4 || !contains(original.width,original.height,region) || original.pixels.size()!=size_t(original.width)*original.height) throw std::runtime_error("The image edit exceeds the original bounds."); const bool sideways=geometry.turns&1; ImageRaster output{sideways?region.height:region.width,sideways?region.width:region.height,{}}; output.pixels.resize(size_t(output.width)*output.height); for(unsigned y=0;y