From 4a243efac706ef2d5ec1224719a6558074651360 Mon Sep 17 00:00:00 2001
From: Christian Heller <c.heller@plomlompom.de>
Date: Sat, 24 Aug 2024 09:17:19 +0200
Subject: [PATCH] Add randomized sort, fix another cell-var-from-loop.

---
 browser.py | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)

diff --git a/browser.py b/browser.py
index fca3b81..212714b 100755
--- a/browser.py
+++ b/browser.py
@@ -1,6 +1,8 @@
 #!/usr/bin/env python3
 from json import dump as json_dump, load as json_load
 from os.path import exists as path_exists, join as path_join, abspath
+from random import shuffle
+from operator import attrgetter
 from exiftool import ExifToolHelper  # type: ignore
 import gi  # type: ignore
 gi.require_version('Gtk', '4.0')
@@ -14,6 +16,7 @@ from stable.gen_params import (GenParams,  # noqa: E402
 
 IMG_DIR = '.'
 CACHE_PATH = 'cache.json'
+SORT_KEY_RANDOM = 'randomize'
 
 
 class FileItem(GObject.GObject):
@@ -83,6 +86,7 @@ class Window(Gtk.ApplicationWindow):
         radio1 = add_sorter('last_mod_time', None)
         for name in ['name'] + list(GEN_PARAMS):
             add_sorter(name.lower(), group=radio1)
+        add_sorter(SORT_KEY_RANDOM, group=radio1)
         popover_menu = Gtk.Popover()
         popover_menu.props.child = vbox
         self.sorter = Gtk.MenuButton(label='SORT', popover=popover_menu)
@@ -117,6 +121,9 @@ class Window(Gtk.ApplicationWindow):
         self.sorter.props.label = f'SORT: {button.props.label}'
 
     def update_sort_order(self, attr_name):
+        if SORT_KEY_RANDOM == attr_name:
+            self.sort_order = [SORT_KEY_RANDOM]
+            return
         if attr_name in self.sort_order:
             self.sort_order.remove(attr_name)
         self.sort_order += [attr_name]
@@ -124,7 +131,10 @@ class Window(Gtk.ApplicationWindow):
     def sort(self):
         self.list_store.remove_all()
         for key in self.sort_order:
-            self.unsorted.sort(key=lambda i: getattr(i, key))
+            if SORT_KEY_RANDOM == key:
+                shuffle(self.unsorted)
+                continue
+            self.unsorted.sort(key=attrgetter(key))
         for file_item in self.unsorted:
             self.list_store.append(file_item)
         if self.item:
-- 
2.30.2