#!/usr/bin/env python3
# SPDX-License-Identifier: WTFPL
# basic GIF viewer using Qt libs
# usage: qgifview FILE.GIF

# /// script
# dependencies = ["PyQt6"]
# ///

import sys

from PyQt6.QtCore import Qt
from PyQt6.QtGui import QMovie
from PyQt6.QtWidgets import QApplication, QFileDialog, QLabel


app = QApplication(sys.argv)

args = app.arguments()
if len(args) <= 1:
    file, _ = QFileDialog.getOpenFileName(
        None, "Select a image file", ".", "Image (*.gif *.mng *.png *.jpg *.webp)"
    )
    if file:
        movie = QMovie(file)
    else:
        print('usage: %s FILE.GIF' % args[0], file=sys.stderr)
        sys.exit(1)
elif len(args) > 2 or sys.argv[1] in {'-h', '--help'}:
    print('usage: %s FILE.GIF' % args[0], file=sys.stderr)
    sys.exit(1)
else:
    movie = QMovie(args[1])

if not movie.isValid():
    print('invalid GIF file: %s' % args[1], file=sys.stderr)
    sys.exit(2)


class MyLabel(QLabel):
    def keyPressEvent(self, ev):
        if ev.key() == Qt.Key.Key_Escape:
            self.close()
        elif ev.key() == Qt.Key.Key_Space:
            self.movie().setPaused(self.movie().state() == QMovie.MovieState.Running)
        elif ev.key() == Qt.Key.Key_Left:
            # may not always work
            self.movie().jumpToFrame(self.movie().currentFrameNumber() - 1)
        elif ev.key() == Qt.Key.Key_Right:
            self.movie().jumpToFrame(self.movie().currentFrameNumber() + 1)


label = MyLabel()
label.setMovie(movie)

movie.start() # start first so label gets right default size
label.show()

movie.finished.connect(movie.start) # loop

sys.exit(app.exec())
