summaryrefslogtreecommitdiff
path: root/components/images/CachingImage.qml
blob: 01411a1bef4978ffcdd9f668a9f109a2bd8a0340 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import qs.utils
import Quickshell
import Quickshell.Io
import QtQuick

Image {
    id: root

    property string path
    property string hash
    readonly property string cachePath: `${Paths.stringify(Paths.imagecache)}/${hash}@${effectiveWidth}x${effectiveHeight}.png`

    readonly property real effectiveScale: QsWindow.window?.devicePixelRatio ?? 1
    readonly property int effectiveWidth: Math.ceil(width * effectiveScale)
    readonly property int effectiveHeight: Math.ceil(height * effectiveScale)

    asynchronous: true
    fillMode: Image.PreserveAspectCrop
    sourceSize.width: effectiveWidth
    sourceSize.height: effectiveHeight

    onPathChanged: shaProc.exec(["sha256sum", Paths.strip(path)])

    onCachePathChanged: {
        if (hash)
            source = cachePath;
    }

    onStatusChanged: {
        if (source == cachePath && status === Image.Error)
            source = path;
        else if (source == path && status === Image.Ready) {
            Paths.mkdir(Paths.imagecache);
            const grabPath = cachePath;
            grabToImage(res => res.saveToFile(grabPath));
        }
    }

    Process {
        id: shaProc

        stdout: StdioCollector {
            onStreamFinished: root.hash = text.split(" ")[0]
        }
    }
}