#include "files_image_edit.h" #include #include #include #include #include #include #include namespace { namespace fs=std::filesystem; using namespace ks::files; void expect(bool condition,const char *message) { if(!condition) throw std::runtime_error(message); } template struct Com { T *value{}; ~Com(){if(value) value->Release();} T *operator->() const{return value;} }; void checked(HRESULT result) { expect(SUCCEEDED(result),"WIC fixture encoding failed."); } void encodeNative(const fs::path &path,REFGUID container) { Com factory; checked(CoCreateInstance(CLSID_WICImagingFactory,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&factory.value))); Com stream; checked(factory->CreateStream(&stream.value)); checked(stream->InitializeFromFilename(path.c_str(),GENERIC_WRITE)); Com encoder; checked(factory->CreateEncoder(container,nullptr,&encoder.value)); checked(encoder->Initialize(stream.value,WICBitmapEncoderNoCache)); Com frame; checked(encoder->CreateNewFrame(&frame.value,nullptr)); checked(frame->Initialize(nullptr)); checked(frame->SetSize(8,6)); auto pixelFormat=GUID_WICPixelFormat24bppBGR; checked(frame->SetPixelFormat(&pixelFormat)); expect(pixelFormat==GUID_WICPixelFormat24bppBGR,"fixture pixel format"); std::array pixels{}; for(size_t i=0;iWritePixels(6,8*3,pixels.size(),pixels.data())); checked(frame->Commit()); checked(encoder->Commit()); } struct Temp { fs::path path; Temp() { GUID id{}; wchar_t name[40]{}; expect(SUCCEEDED(CoCreateGuid(&id)) && StringFromGUID2(id,name,40),"temporary file prefix"); path=fs::temp_directory_path()/(L"ks-test-image-"+std::wstring(name)); expect(fs::create_directory(path),"temporary image directory"); } ~Temp(){std::error_code error; fs::remove_all(path,error);} }; void expectDecodeFailure(const fs::path &file,std::string_view text) { try {decodeImage(file,file);} catch(const std::runtime_error &e) { expect(std::string_view(e.what()).find(text)!=std::string_view::npos,e.what()); return; } throw std::runtime_error("invalid image was decoded"); } void verifyImageEdits(const fs::path &root) { ImageRaster original{4,3,{0xff110001,0xff110002,0xff110003,0xff110004, 0xff110005,0x80402010,0xff110007,0xff110008,0xff110009,0xff11000a,0xff11000b,0xff11000c}}; const ImageGeometry initial{{0,0,4,3},0}; const ImageGeometry clockwise{initial.region,1}; const auto rotated=transformImage(original,clockwise); expect(rotated.width==3 && rotated.height==4 && rotated.pixels[0]==original.pixels[8] && rotated.pixels[11]==original.pixels[3],"clockwise rotation changed pixel order"); const auto reversed=transformImage(original,{initial.region,3}); expect(reversed.pixels.front()==original.pixels[3] && reversed.pixels.back()==original.pixels[8], "counterclockwise rotation changed pixel order"); const auto cropped=transformImage(original,cropImage(clockwise,{1,1,2,2})); expect(cropped.width==2 && cropped.height==2 && cropped.pixels==std::vector{ original.pixels[5],original.pixels[1],original.pixels[6],original.pixels[2]}, "crop used coordinates before rotation"); bool outside=false; try {cropImage(clockwise,{2,1,2,2});} catch(const std::runtime_error &) {outside=true;} expect(outside,"out-of-bounds crop was accepted"); const auto png=root/L"Редагування.png"; saveImage(cropped,png); const auto saved=decodeImage(png,png); expect(saved.width==2 && saved.height==2 && saved.pixels==cropped.pixels,"PNG copy lost alpha or pixels"); const auto before=imageRevision(png); bool collision=false; try {saveImage(rotated,png);} catch(const std::system_error &) {collision=true;} expect(collision && sameImageRevision(before,imageRevision(png)), "Save Copy overwrote an existing image"); const auto incoming=root/L"external.png"; saveImage(original,incoming); fs::rename(png,root/L"first.png"); fs::rename(incoming,png); bool stale=false; try {saveImage(cropped,png,&before);} catch(const std::runtime_error &) {stale=true;} expect(stale && decodeImage(png,png).pixels==original.pixels,"Replace overwrote an external revision"); const auto current=imageRevision(png); const auto written=saveImage(cropped,png,¤t); expect(sameImageRevision(written,imageRevision(png)), "returned revision did not track the installed image"); expect(decodeImage(png,png).pixels==cropped.pixels,"confirmed replacement lost image data"); const auto jpeg=root/L"copy.jpg"; const ImageRaster transparent{8,8,std::vector(64,0)}; saveImage(transparent,jpeg); const auto lossy=decodeImage(jpeg,jpeg); expect(lossy.width==8 && lossy.height==8 && lossy.pixels.front()>=0xfffefefe, "JPEG copy failed to composite transparency on white"); for(const auto &entry:fs::directory_iterator(root)) expect(entry.path().extension()!=L".tmp","image operation left a staging file"); } std::vector animatedWebp(const uint8_t *encoded,size_t size) { expect(size>12,"WebP fixture RIFF body"); std::vector bytes{'R','I','F','F',0,0,0,0,'W','E','B','P', 'V','P','8','X',10,0,0,0,0x12,0,0,0,0,0,0,0,0,0, 'A','N','I','M',6,0,0,0,0,0,0,0,0,0, 'A','N','M','F',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,100,0,0,2}; bytes.insert(bytes.end(),encoded+12,encoded+size); const auto storeSize=[&](size_t offset,size_t value) { for(unsigned i=0;i<4;++i) bytes[offset+i]=static_cast(value>>(8*i)); }; storeSize(4,bytes.size()-8); storeSize(48,16+size-12); return bytes; } } int main() { const auto apartment=CoInitializeEx(nullptr,COINIT_MULTITHREADED); int result=0; try { expect(SUCCEEDED(apartment),"initialize COM"); Temp temp; verifyImageEdits(temp.path); for(const auto &[name,container]:std::array{ std::pair{L"знімок.PNG",&GUID_ContainerFormatPng}, std::pair{L"picture.jpeg",&GUID_ContainerFormatJpeg}, std::pair{L"picture.bmp",&GUID_ContainerFormatBmp}}) { const auto path=temp.path/name; expect(isImagePath(path),"supported native extension"); encodeNative(path,*container); const auto decoded=decodeImage(path,path); expect(decoded.width==8 && decoded.height==6 && decoded.pixels.size()==48,"native image dimensions"); const auto first=decoded.pixels.front(); expect((first>>24)==255 && ((first>>16)&255)>150,"native image color and opacity"); } const auto gif=temp.path/L"picture.gif"; constexpr unsigned char gifData[]{0x47,0x49,0x46,0x38,0x39,0x61,1,0,1,0,0x80,0,0, 0,0,0,255,255,255,0x2c,0,0,0,0,1,0,1,0,0,2,2,0x44,1,0,0x3b}; std::ofstream(gif,std::ios::binary).write(reinterpret_cast(gifData),sizeof(gifData)); const auto gifImage=decodeImage(gif,gif); expect(gifImage.width==1 && gifImage.height==1 && gifImage.pixels.size()==1,"GIF first frame"); const auto webp=temp.path/L"picture.webp"; const uint8_t pixel[]{12,84,200,128}; uint8_t *encoded=nullptr; const auto length=WebPEncodeLosslessBGRA(pixel,1,1,4,&encoded); expect(length>0,"WebP fixture"); std::ofstream(webp,std::ios::binary).write(reinterpret_cast(encoded),length); auto animation=animatedWebp(encoded,length); WebPFree(encoded); const auto webpImage=decodeImage(webp,webp); expect(webpImage.width==1 && webpImage.height==1 && webpImage.pixels.size()==1,"WebP dimensions"); const auto color=webpImage.pixels.front(); expect((color>>24)==128 && ((color>>16)&255)>=99 && ((color>>16)&255)<=101,"WebP premultiplied alpha"); const auto animated=temp.path/L"animated.webp"; std::ofstream(animated,std::ios::binary).write(reinterpret_cast(animation.data()),animation.size()); const auto firstFrame=decodeImage(animated,animated); expect(firstFrame.width==1 && firstFrame.height==1 && firstFrame.pixels.front()==color,"animated WebP first frame"); const auto hugeCanvas=temp.path/L"oversized-canvas.webp"; animation[24]=0x1f; animation[25]=0x4e; // 20000 pixels, encoded as width minus one. std::ofstream(hugeCanvas,std::ios::binary).write(reinterpret_cast(animation.data()),animation.size()); expectDecodeFailure(hugeCanvas,"too large"); const auto corrupt=temp.path/L"corrupt.png"; std::ofstream(corrupt,std::ios::binary)<<"not an image"; expectDecodeFailure(corrupt,"damaged"); const auto large=temp.path/L"huge.bmp"; { std::ofstream output(large,std::ios::binary); output.seekp(imageSourceLimit); output.put('\0'); } expectDecodeFailure(large,"too large"); std::stop_source canceled; canceled.request_stop(); bool stopped=false; try{decodeImage(webp,webp,canceled.get_token());} catch(const std::system_error &error){stopped=error.code().value()==ERROR_CANCELLED;} expect(stopped,"canceled image load"); } catch(const std::exception &error){std::cerr<