efficient vim config
[dotfiles/.git] / .local / lib / python3.9 / site-packages / pywal / image.py
1 """
2 Get the image file.
3 """
4 import logging
5 import os
6 import random
7 import re
8 import sys
9
10 from .settings import CACHE_DIR
11 from . import util
12 from . import wallpaper
13
14
15 def get_image_dir(img_dir):
16     """Get all images in a directory."""
17     current_wall = wallpaper.get()
18     current_wall = os.path.basename(current_wall)
19
20     file_types = (".png", ".jpg", ".jpeg", ".jpe", ".gif")
21
22     return [img.name for img in os.scandir(img_dir)
23             if img.name.lower().endswith(file_types)], current_wall
24
25
26 def get_random_image(img_dir):
27     """Pick a random image file from a directory."""
28     images, current_wall = get_image_dir(img_dir)
29
30     if len(images) > 2 and current_wall in images:
31         images.remove(current_wall)
32
33     elif not images:
34         logging.error("No images found in directory.")
35         sys.exit(1)
36
37     random.shuffle(images)
38     return os.path.join(img_dir, images[0])
39
40
41 def get_next_image(img_dir):
42     """Get the next image in a dir."""
43     images, current_wall = get_image_dir(img_dir)
44     images.sort(key=lambda img: [int(x) if x.isdigit() else x
45                                  for x in re.split('([0-9]+)', img)])
46
47     try:
48         next_index = images.index(current_wall) + 1
49
50     except ValueError:
51         next_index = 0
52
53     try:
54         image = images[next_index]
55
56     except IndexError:
57         image = images[0]
58
59     return os.path.join(img_dir, image)
60
61
62 def get(img, cache_dir=CACHE_DIR, iterative=False):
63     """Validate image input."""
64     if os.path.isfile(img):
65         wal_img = img
66
67     elif os.path.isdir(img):
68         if iterative:
69             wal_img = get_next_image(img)
70
71         else:
72             wal_img = get_random_image(img)
73
74     else:
75         logging.error("No valid image file found.")
76         sys.exit(1)
77
78     wal_img = os.path.abspath(wal_img)
79
80     # Cache the image file path.
81     util.save_file(wal_img, os.path.join(cache_dir, "wal"))
82
83     logging.info("Using image \033[1;37m%s\033[0m.", os.path.basename(wal_img))
84     return wal_img