460 lines
17 KiB
C++
460 lines
17 KiB
C++
#include "files_image_view.h"
|
||
#include "platform.h"
|
||
#include <windowsx.h>
|
||
#include <algorithm>
|
||
#include <array>
|
||
#include <cmath>
|
||
#include <cstring>
|
||
#include <future>
|
||
#include <map>
|
||
#include <memory>
|
||
#include <thread>
|
||
#include <utility>
|
||
|
||
namespace ks::files
|
||
{
|
||
namespace
|
||
{
|
||
namespace fs=std::filesystem;
|
||
constexpr wchar_t imageWindowClass[]=L"KSwitcherFilesImageViewer";
|
||
constexpr UINT_PTR imageTimer=1;
|
||
enum Action { previous=1, following, zoomOut, zoomIn, fitImage, actualSize };
|
||
|
||
void fillImageView(HDC dc,const RECT &rect,COLORREF color)
|
||
{
|
||
SetDCBrushColor(dc,color);
|
||
FillRect(dc,&rect,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||
}
|
||
|
||
struct ImageView
|
||
{
|
||
HWND window{};
|
||
bool embedded{};
|
||
ImageViewStyle style;
|
||
std::vector<fs::path> images;
|
||
size_t position{};
|
||
ImageLoad load;
|
||
std::function<void(HWND)> onClose;
|
||
std::array<HWND,6> buttons{};
|
||
HFONT font{};
|
||
UINT fontDpi{};
|
||
HBITMAP bitmap{};
|
||
unsigned width{},height{};
|
||
fs::path requested;
|
||
std::wstring error;
|
||
std::future<ImageRaster> reading;
|
||
std::stop_source stop;
|
||
uint64_t revision{}, started{};
|
||
double zoom=1, x{}, y{};
|
||
bool fit=true, dragging{};
|
||
POINT lastMouse{};
|
||
|
||
~ImageView()
|
||
{
|
||
stop.request_stop();
|
||
if(bitmap) DeleteObject(bitmap);
|
||
if(font) DeleteObject(font);
|
||
}
|
||
|
||
int scale(int pixels) const {return MulDiv(pixels,GetDpiForWindow(window),96);}
|
||
|
||
RECT viewport() const
|
||
{
|
||
RECT area{};
|
||
GetClientRect(window,&area);
|
||
area.top=std::min(area.bottom,static_cast<LONG>(scale(35)));
|
||
area.bottom=std::max(area.top,area.bottom-scale(27));
|
||
return area;
|
||
}
|
||
|
||
void layout()
|
||
{
|
||
const auto dpi=GetDpiForWindow(window);
|
||
if(fontDpi!=dpi)
|
||
{
|
||
LOGFONTW definition=style.font;
|
||
definition.lfHeight=-MulDiv(style.tenthsOfPoint,dpi,720);
|
||
if(const auto next=CreateFontIndirectW(&definition))
|
||
{
|
||
if(font) DeleteObject(font);
|
||
font=next;
|
||
fontDpi=dpi;
|
||
}
|
||
}
|
||
RECT bounds{};
|
||
GetClientRect(window,&bounds);
|
||
const int left=scale(4), gap=scale(3), height=scale(27);
|
||
const int count=embedded?4:6;
|
||
const int available=std::max(0,static_cast<int>(bounds.right)-left*2-gap*(count-1));
|
||
const int unit=std::min(scale(80),available/count);
|
||
int x=left;
|
||
for(auto button:buttons)
|
||
{
|
||
if(!button) continue;
|
||
SetWindowPos(button,nullptr,x,scale(4),unit,height,SWP_NOZORDER|SWP_NOACTIVATE);
|
||
x+=unit+gap;
|
||
}
|
||
clampOffset();
|
||
InvalidateRect(window,nullptr,FALSE);
|
||
}
|
||
|
||
void updateButtons() const
|
||
{
|
||
if(!embedded)
|
||
{
|
||
EnableWindow(buttons[previous-1],position>0);
|
||
EnableWindow(buttons[following-1],position+1<images.size());
|
||
}
|
||
for(unsigned id=zoomOut;id<=actualSize;++id) EnableWindow(buttons[id-1],bitmap!=nullptr);
|
||
for(auto button:buttons)
|
||
if(button) InvalidateRect(button,nullptr,FALSE);
|
||
}
|
||
|
||
void request(const fs::path &path)
|
||
{
|
||
if(requested==path) return;
|
||
requested=path;
|
||
++revision;
|
||
stop.request_stop();
|
||
error.clear();
|
||
if(bitmap) DeleteObject(std::exchange(bitmap,nullptr));
|
||
width=height=0;
|
||
fit=true;
|
||
x=y=0;
|
||
if(!embedded)
|
||
{
|
||
const auto label=L"Viewer — "+path.filename().wstring();
|
||
SetWindowTextW(window,label.c_str());
|
||
}
|
||
updateButtons();
|
||
SetTimer(window,imageTimer,30,nullptr);
|
||
InvalidateRect(window,nullptr,FALSE);
|
||
}
|
||
|
||
void show(ImageRaster image)
|
||
{
|
||
BITMAPINFO info{};
|
||
info.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
|
||
info.bmiHeader.biWidth=static_cast<LONG>(image.width);
|
||
info.bmiHeader.biHeight=-static_cast<LONG>(image.height);
|
||
info.bmiHeader.biPlanes=1;
|
||
info.bmiHeader.biBitCount=32;
|
||
info.bmiHeader.biCompression=BI_RGB;
|
||
void *bits=nullptr;
|
||
bitmap=CreateDIBSection(nullptr,&info,DIB_RGB_COLORS,&bits,nullptr,0);
|
||
if(!bitmap || !bits) throw std::runtime_error("Could not display this image.");
|
||
std::memcpy(bits,image.pixels.data(),image.pixels.size()*sizeof(uint32_t));
|
||
width=image.width;
|
||
height=image.height;
|
||
updateButtons();
|
||
}
|
||
|
||
void poll()
|
||
{
|
||
if(reading.valid())
|
||
{
|
||
if(reading.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
|
||
try
|
||
{
|
||
auto image=reading.get();
|
||
if(revision==started) show(std::move(image));
|
||
}
|
||
catch(const std::exception &e)
|
||
{
|
||
if(revision==started) error=wide(e.what());
|
||
}
|
||
if(revision==started)
|
||
{
|
||
KillTimer(window,imageTimer);
|
||
InvalidateRect(window,nullptr,FALSE);
|
||
return;
|
||
}
|
||
}
|
||
if(requested.empty())
|
||
{
|
||
KillTimer(window,imageTimer);
|
||
return;
|
||
}
|
||
stop=std::stop_source{};
|
||
started=revision;
|
||
std::packaged_task<ImageRaster()> task([path=requested,decoder=load,token=stop.get_token()]
|
||
{
|
||
return decoder?decoder(path,token):decodeImage(path,path,token);
|
||
});
|
||
reading=task.get_future();
|
||
try {std::thread(std::move(task)).detach();}
|
||
catch(const std::exception &e)
|
||
{
|
||
reading={};
|
||
error=wide(e.what());
|
||
KillTimer(window,imageTimer);
|
||
InvalidateRect(window,nullptr,FALSE);
|
||
}
|
||
}
|
||
|
||
double factor() const
|
||
{
|
||
if(!fit || !width || !height) return zoom;
|
||
const auto area=viewport();
|
||
return std::min({1.0,static_cast<double>(std::max(1L,area.right-area.left))/width,
|
||
static_cast<double>(std::max(1L,area.bottom-area.top))/height});
|
||
}
|
||
|
||
void clampOffset()
|
||
{
|
||
const auto area=viewport();
|
||
const auto value=factor();
|
||
const auto limitX=std::max(0.0,(width*value-(area.right-area.left))/2);
|
||
const auto limitY=std::max(0.0,(height*value-(area.bottom-area.top))/2);
|
||
x=std::clamp(x,-limitX,limitX);
|
||
y=std::clamp(y,-limitY,limitY);
|
||
}
|
||
|
||
void changeZoom(double multiplier,const POINT *anchor=nullptr)
|
||
{
|
||
if(!bitmap) return;
|
||
const auto before=factor();
|
||
fit=false;
|
||
zoom=std::clamp(before*multiplier,std::min(0.025,before),16.0);
|
||
if(anchor)
|
||
{
|
||
const auto area=viewport();
|
||
const double dx=anchor->x-(area.left+area.right)/2.0;
|
||
const double dy=anchor->y-(area.top+area.bottom)/2.0;
|
||
x=dx+(x-dx)*zoom/before;
|
||
y=dy+(y-dy)*zoom/before;
|
||
}
|
||
clampOffset();
|
||
InvalidateRect(window,nullptr,FALSE);
|
||
}
|
||
|
||
void action(UINT id)
|
||
{
|
||
if(id==previous && position>0) request(images[--position]);
|
||
else if(id==following && position+1<images.size()) request(images[++position]);
|
||
else if(id==zoomOut || id==zoomIn) changeZoom(id==zoomIn?1.25:0.8);
|
||
else if(id==fitImage || id==actualSize)
|
||
{
|
||
fit=id==fitImage;
|
||
zoom=1;
|
||
x=y=0;
|
||
InvalidateRect(window,nullptr,FALSE);
|
||
}
|
||
}
|
||
|
||
void paintButton(const DRAWITEMSTRUCT &item) const
|
||
{
|
||
const bool enabled=(item.itemState&ODS_DISABLED)==0;
|
||
const auto mix=[](BYTE a,BYTE b){return (int(a)+b)/2;};
|
||
const auto foreground=enabled?style.toolbarText:RGB(
|
||
mix(GetRValue(style.toolbar),GetRValue(style.toolbarText)),
|
||
mix(GetGValue(style.toolbar),GetGValue(style.toolbarText)),
|
||
mix(GetBValue(style.toolbar),GetBValue(style.toolbarText)));
|
||
fillImageView(item.hDC,item.rcItem,(item.itemState&(ODS_FOCUS|ODS_SELECTED))?style.selection:style.toolbar);
|
||
SetDCBrushColor(item.hDC,foreground);
|
||
FrameRect(item.hDC,&item.rcItem,static_cast<HBRUSH>(GetStockObject(DC_BRUSH)));
|
||
if(font) SelectObject(item.hDC,font);
|
||
SetBkMode(item.hDC,TRANSPARENT);
|
||
SetTextColor(item.hDC,foreground);
|
||
wchar_t label[24]{};
|
||
GetWindowTextW(item.hwndItem,label,static_cast<int>(std::size(label)));
|
||
auto labelArea=item.rcItem;
|
||
InflateRect(&labelArea,-scale(2),0);
|
||
DrawTextW(item.hDC,label,-1,&labelArea,DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX);
|
||
}
|
||
|
||
void paint()
|
||
{
|
||
PAINTSTRUCT repaint{};
|
||
const auto dc=BeginPaint(window,&repaint);
|
||
RECT all{};
|
||
GetClientRect(window,&all);
|
||
const auto area=viewport();
|
||
fillImageView(dc,all,style.toolbar);
|
||
fillImageView(dc,area,style.background);
|
||
if(font) SelectObject(dc,font);
|
||
SetBkMode(dc,TRANSPARENT);
|
||
SetTextColor(dc,style.text);
|
||
if(bitmap)
|
||
{
|
||
if(const auto source=CreateCompatibleDC(dc))
|
||
{
|
||
const auto old=SelectObject(source,bitmap);
|
||
const auto saved=SaveDC(dc);
|
||
IntersectClipRect(dc,area.left,area.top,area.right,area.bottom);
|
||
const auto displayWidth=std::max(1L,std::lround(width*factor()));
|
||
const auto displayHeight=std::max(1L,std::lround(height*factor()));
|
||
const auto left=std::lround((area.left+area.right-displayWidth)/2.0+x);
|
||
const auto top=std::lround((area.top+area.bottom-displayHeight)/2.0+y);
|
||
const double horizontal=double(displayWidth)/width, vertical=double(displayHeight)/height;
|
||
const auto clippedSource=[](LONG edge,LONG start,double ratio,unsigned size,bool end)
|
||
{
|
||
const auto pixel=(edge-start)/ratio;
|
||
return static_cast<int>(std::clamp(end?std::ceil(pixel):std::floor(pixel),0.0,double(size)));
|
||
};
|
||
const int startX=clippedSource(area.left,left,horizontal,width,false);
|
||
const int endX=clippedSource(area.right,left,horizontal,width,true);
|
||
const int startY=clippedSource(area.top,top,vertical,height,false);
|
||
const int endY=clippedSource(area.bottom,top,vertical,height,true);
|
||
const auto destX=left+std::lround(startX*horizontal), destY=top+std::lround(startY*vertical);
|
||
AlphaBlend(dc,destX,destY,left+std::lround(endX*horizontal)-destX,top+std::lround(endY*vertical)-destY,
|
||
source,startX,startY,endX-startX,endY-startY,{AC_SRC_OVER,0,255,AC_SRC_ALPHA});
|
||
if(saved) RestoreDC(dc,saved);
|
||
SelectObject(source,old);
|
||
DeleteDC(source);
|
||
}
|
||
}
|
||
else if(!requested.empty())
|
||
{
|
||
auto message=area;
|
||
InflateRect(&message,-scale(8),0);
|
||
DrawTextW(dc,error.empty()?L"Loading image…":error.c_str(),-1,&message,
|
||
DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX);
|
||
}
|
||
SetTextColor(dc,style.toolbarText);
|
||
auto status=requested.filename().wstring();
|
||
if(bitmap) status+=L" · "+std::to_wstring(width)+L" × "+std::to_wstring(height)+L" · "+
|
||
std::to_wstring(std::lround(factor()*100))+L"%";
|
||
RECT footer{scale(8),area.bottom,all.right-scale(8),all.bottom};
|
||
DrawTextW(dc,status.c_str(),-1,&footer,DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS|DT_NOPREFIX);
|
||
EndPaint(window,&repaint);
|
||
}
|
||
};
|
||
|
||
std::map<HWND,std::shared_ptr<ImageView>> imageViews;
|
||
|
||
LRESULT CALLBACK imageProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp)
|
||
{
|
||
if(message==WM_NCCREATE)
|
||
{
|
||
const auto *created=reinterpret_cast<const CREATESTRUCTW *>(lp);
|
||
const auto state=*static_cast<std::shared_ptr<ImageView> *>(created->lpCreateParams);
|
||
state->window=window;
|
||
imageViews.emplace(window,state);
|
||
}
|
||
const auto found=imageViews.find(window);
|
||
if(found==imageViews.end()) return DefWindowProcW(window,message,wp,lp);
|
||
const auto state=found->second;
|
||
auto &view=*state;
|
||
switch(message)
|
||
{
|
||
case WM_CREATE:
|
||
{
|
||
constexpr const wchar_t *labels[]{L"Previous",L"Next",L"−",L"+",L"Fit",L"100%"};
|
||
for(unsigned id=view.embedded?zoomOut:previous;id<=actualSize;++id)
|
||
view.buttons[id-1]=CreateWindowW(L"BUTTON",labels[id-1],WS_CHILD|WS_VISIBLE|BS_OWNERDRAW,
|
||
0,0,0,0,window,reinterpret_cast<HMENU>(static_cast<INT_PTR>(id)),GetModuleHandleW(nullptr),nullptr);
|
||
view.layout();
|
||
view.updateButtons();
|
||
return 0;
|
||
}
|
||
case WM_SIZE: view.layout(); return 0;
|
||
case WM_DPICHANGED:
|
||
if(!view.embedded)
|
||
{
|
||
const auto &bounds=*reinterpret_cast<const RECT *>(lp);
|
||
SetWindowPos(window,nullptr,bounds.left,bounds.top,bounds.right-bounds.left,bounds.bottom-bounds.top,
|
||
SWP_NOACTIVATE|SWP_NOZORDER);
|
||
}
|
||
view.layout();
|
||
return 0;
|
||
case WM_DPICHANGED_AFTERPARENT: view.layout(); return 0;
|
||
case WM_ERASEBKGND: return 1;
|
||
case WM_PAINT: view.paint(); return 0;
|
||
case WM_DRAWITEM: view.paintButton(*reinterpret_cast<const DRAWITEMSTRUCT *>(lp)); return TRUE;
|
||
case WM_TIMER: if(wp==imageTimer) view.poll(); return 0;
|
||
case WM_COMMAND:
|
||
if(HIWORD(wp)==BN_CLICKED) {view.action(LOWORD(wp)); SetFocus(window);}
|
||
return 0;
|
||
case WM_LBUTTONDOWN:
|
||
{
|
||
const auto area=view.viewport();
|
||
const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
||
if(view.bitmap && PtInRect(&area,point))
|
||
{
|
||
SetFocus(window);
|
||
view.dragging=true;
|
||
view.lastMouse=point;
|
||
SetCapture(window);
|
||
}
|
||
return 0;
|
||
}
|
||
case WM_MOUSEMOVE:
|
||
if(view.dragging)
|
||
{
|
||
const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
||
view.x+=point.x-view.lastMouse.x;
|
||
view.y+=point.y-view.lastMouse.y;
|
||
view.lastMouse=point;
|
||
view.clampOffset();
|
||
InvalidateRect(window,nullptr,FALSE);
|
||
}
|
||
return 0;
|
||
case WM_LBUTTONUP:
|
||
if(view.dragging) ReleaseCapture();
|
||
return 0;
|
||
case WM_CAPTURECHANGED: view.dragging=false; return 0;
|
||
case WM_MOUSEWHEEL:
|
||
{
|
||
POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)};
|
||
ScreenToClient(window,&point);
|
||
view.changeZoom(std::pow(1.25,static_cast<double>(GET_WHEEL_DELTA_WPARAM(wp))/WHEEL_DELTA),&point);
|
||
return 0;
|
||
}
|
||
case WM_KEYDOWN:
|
||
if(wp==VK_ADD || wp==VK_OEM_PLUS) view.action(zoomIn);
|
||
else if(wp==VK_SUBTRACT || wp==VK_OEM_MINUS) view.action(zoomOut);
|
||
else if(wp=='0') view.action(fitImage);
|
||
else if(wp=='1') view.action(actualSize);
|
||
else if(!view.embedded && (wp==VK_LEFT || wp==VK_PRIOR)) view.action(previous);
|
||
else if(!view.embedded && (wp==VK_RIGHT || wp==VK_NEXT)) view.action(following);
|
||
else if(!view.embedded && (wp==VK_ESCAPE || wp==VK_F10)) DestroyWindow(window);
|
||
else break;
|
||
return 0;
|
||
case WM_NCDESTROY:
|
||
imageViews.erase(found);
|
||
if(view.onClose) view.onClose(window);
|
||
break;
|
||
}
|
||
return DefWindowProcW(window,message,wp,lp);
|
||
}
|
||
}
|
||
|
||
HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector<std::filesystem::path> images,
|
||
const std::filesystem::path &initial,ImageLoad load,std::function<void(HWND)> onClose)
|
||
{
|
||
const auto instance=GetModuleHandleW(nullptr);
|
||
static const bool registered=[instance]
|
||
{
|
||
WNDCLASSW type{};
|
||
type.hInstance=instance;
|
||
type.hCursor=LoadCursorW(nullptr,IDC_ARROW);
|
||
type.lpfnWndProc=imageProcedure;
|
||
type.lpszClassName=imageWindowClass;
|
||
return RegisterClassW(&type)!=0;
|
||
}();
|
||
if(!registered) return nullptr;
|
||
auto state=std::make_shared<ImageView>();
|
||
state->embedded=embedded;
|
||
state->style=style;
|
||
state->images=std::move(images);
|
||
state->load=std::move(load);
|
||
state->onClose=std::move(onClose);
|
||
const auto position=std::find(state->images.begin(),state->images.end(),initial);
|
||
if(position!=state->images.end()) state->position=static_cast<size_t>(position-state->images.begin());
|
||
RECT bounds{};
|
||
if(!embedded) GetWindowRect(owner,&bounds);
|
||
const auto window=CreateWindowExW(embedded?0:WS_EX_APPWINDOW,imageWindowClass,embedded?L"Quick View":L"Viewer",
|
||
embedded?(WS_CHILD|WS_CLIPCHILDREN|WS_CLIPSIBLINGS):(WS_OVERLAPPEDWINDOW|WS_CLIPCHILDREN),
|
||
bounds.left,bounds.top,bounds.right-bounds.left,bounds.bottom-bounds.top,
|
||
embedded?owner:nullptr,nullptr,instance,&state);
|
||
if(window) state->request(initial);
|
||
return window;
|
||
}
|
||
|
||
void showImageViewFile(HWND window,const std::filesystem::path &path)
|
||
{
|
||
if(const auto found=imageViews.find(window);found!=imageViews.end()) found->second->request(path);
|
||
}
|
||
}
|