-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathwallpapercycle
More file actions
executable file
·536 lines (455 loc) · 22.4 KB
/
wallpapercycle
File metadata and controls
executable file
·536 lines (455 loc) · 22.4 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
#!/usr/bin/env python3
import os
import sys
import time
import random
import argparse
import subprocess
from pathlib import Path
from typing import List, Optional
try:
from rich.console import Console
from rich.panel import Panel
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TimeRemainingColumn
from rich.table import Table
from rich.prompt import Prompt
from rich.live import Live
from rich import box
except ImportError:
print("This script requires the 'rich' library.")
print("Please install it with: pip install rich")
sys.exit(1)
# Initialize rich console
console = Console()
# Default settings
DEFAULT_WALLPAPER_DIR = os.path.expanduser("~/Pictures/Wallpapers")
DEFAULT_MIN_WIDTH = 1920 # Lowered from 3840 (4K) to 1920 (Full HD)
DEFAULT_MIN_HEIGHT = 1080 # Lowered from 2160 to 1080
DEFAULT_DELAY = 5
DEFAULT_CURRENT_SYMLINK = os.path.join(DEFAULT_WALLPAPER_DIR, "current")
DEFAULT_SYMLINKS_ONLY = True
DEFAULT_FAVORITES_FILE = os.path.join(DEFAULT_WALLPAPER_DIR, ".favorites")
def show_help():
"""Display help information with rich formatting"""
console.print(Panel.fit(
"[bold cyan]Wallpaper Cycle[/bold cyan]\n\n"
"A beautiful way to cycle through your wallpaper collection",
title="About",
border_style="green"
))
table = Table(show_header=True, header_style="bold magenta", box=box.ROUNDED)
table.add_column("Option", style="dim", width=20)
table.add_column("Description")
table.add_column("Default", justify="right")
table.add_row("-h, --help", "Show this help message", "")
table.add_row("-d, --dir DIR", "Set wallpaper directory", DEFAULT_WALLPAPER_DIR)
table.add_row("-w, --width WIDTH", "Set minimum width", str(DEFAULT_MIN_WIDTH))
table.add_row("-t, --height HEIGHT", "Set minimum height", str(DEFAULT_MIN_HEIGHT))
table.add_row("-s, --seconds SEC", "Set delay in seconds", str(DEFAULT_DELAY))
table.add_row("-l, --loop", "Loop continuously through wallpapers", "False")
table.add_row("-r, --random", "Randomize wallpaper order", "True")
table.add_row("-o, --once", "Set one random wallpaper and exit", "False")
table.add_row("-c, --current PATH", "Path for current wallpaper symlink", DEFAULT_CURRENT_SYMLINK)
table.add_row("-q, --quiet", "Reduce output verbosity", "False")
table.add_row("-a, --all", "Include all image files, not just symlinks", "False")
table.add_row("-f, --favorites", "Use only favorite wallpapers", "False")
table.add_row("-F, --add-favorite", "Add current wallpaper to favorites", "False")
console.print(table)
controls = Table(show_header=True, header_style="bold yellow", box=box.ROUNDED)
controls.add_column("Key", style="dim", width=10)
controls.add_column("Action")
controls.add_row("q", "Quit the program")
controls.add_row("n or Enter", "Skip to next wallpaper")
controls.add_row("f", "Add current wallpaper to favorites")
controls.add_row("Ctrl+C", "Force quit")
console.print(Panel(controls, title="Controls while running", border_style="blue"))
def parse_args():
"""Parse command line arguments"""
parser = argparse.ArgumentParser(
description="Cycle through wallpapers with automatic changing.",
add_help=False # We'll handle help ourselves for prettier output
)
parser.add_argument("-h", "--help", action="store_true", help="Show this help message")
parser.add_argument("-d", "--dir", type=str, default=DEFAULT_WALLPAPER_DIR,
help=f"Set wallpaper directory (default: {DEFAULT_WALLPAPER_DIR})")
parser.add_argument("-w", "--width", type=int, default=DEFAULT_MIN_WIDTH,
help=f"Set minimum width (default: {DEFAULT_MIN_WIDTH})")
parser.add_argument("-t", "--height", type=int, default=DEFAULT_MIN_HEIGHT,
help=f"Set minimum height (default: {DEFAULT_MIN_HEIGHT})")
parser.add_argument("-s", "--seconds", type=int, default=DEFAULT_DELAY,
help=f"Set delay in seconds (default: {DEFAULT_DELAY})")
parser.add_argument("-l", "--loop", action="store_true",
help="Loop continuously through wallpapers")
parser.add_argument("-r", "--random", action="store_true", default=True,
help="Randomize wallpaper order (default: True)")
parser.add_argument("-o", "--once", action="store_true",
help="Set one random wallpaper and exit")
parser.add_argument("-c", "--current", type=str, default=DEFAULT_CURRENT_SYMLINK,
help=f"Path for current wallpaper symlink (default: {DEFAULT_CURRENT_SYMLINK})")
parser.add_argument("-q", "--quiet", action="store_true",
help="Reduce output verbosity")
parser.add_argument("-a", "--all", action="store_false", dest="symlinks_only", default=DEFAULT_SYMLINKS_ONLY,
help="Include all image files, not just symlinks")
parser.add_argument("-f", "--favorites", action="store_true",
help="Use only favorite wallpapers")
parser.add_argument("-F", "--add-favorite", action="store_true",
help="Add current wallpaper to favorites")
parser.add_argument("-D", "--debug", action="store_true",
help="Show debug information")
args = parser.parse_args()
if args.help:
show_help()
sys.exit(0)
return args
def check_dependencies():
"""Check if required commands are available"""
required_commands = ["find", "identify", "feh"]
missing = []
for cmd in required_commands:
try:
subprocess.run(["which", cmd], check=True, capture_output=True)
except subprocess.CalledProcessError:
missing.append(cmd)
if missing:
console.print(Panel(
f"[bold red]Missing required commands:[/bold red] {', '.join(missing)}\n\n"
"Please install the following packages:\n"
"- [yellow]ImageMagick[/yellow] for the 'identify' command\n"
"- [yellow]feh[/yellow] for setting wallpapers",
title="Error",
border_style="red"
))
sys.exit(1)
def find_wallpapers(wallpaper_dir: str, min_width: int, min_height: int, quiet: bool = False, symlinks_only: bool = True, debug: bool = False) -> List[str]:
"""Find wallpapers with minimum resolution"""
if not quiet:
with console.status("[bold green]Searching for wallpapers...", spinner="dots"):
time.sleep(0.5) # Give a moment to see the spinner
if not os.path.isdir(wallpaper_dir):
console.print(f"[bold red]Error:[/bold red] Wallpaper directory '{wallpaper_dir}' not found.")
sys.exit(1)
# Look for symlinks only or both regular files and symlinks
if symlinks_only:
if not quiet:
console.print("[blue]Looking for symlinks only...[/blue]")
# Simpler find command for symlinks
cmd = [
"find", wallpaper_dir, "-type", "l",
"-exec", "identify", "-format", "%w %h %i\\n", "{}", ";"
]
else:
# Command for all image files
cmd = [
"find", wallpaper_dir,
"\\(", "-type", "f", "-o", "-type", "l", "\\)",
"-exec", "identify", "-format", "%w %h %i\\n", "{}", "\\;"
]
try:
if debug:
console.print(f"[dim]Debug: Running command:[/dim] {' '.join(cmd)}")
# Try using shell=True as a fallback if the list approach doesn't work
try:
result = subprocess.run(cmd, capture_output=True, text=True, check=False)
output = result.stdout
# If we got an error, try shell=True approach
if result.stderr and "missing argument to `-exec'" in result.stderr:
if debug:
console.print("[yellow]Debug: Trying shell=True approach[/yellow]")
# Build shell command
if symlinks_only:
shell_cmd = f"find {wallpaper_dir} -type l -exec identify -format '%w %h %i\\n' {{}} \\;"
else:
shell_cmd = f"find {wallpaper_dir} \\( -type f -o -type l \\) -exec identify -format '%w %h %i\\n' {{}} \\;"
if debug:
console.print(f"[dim]Debug: Shell command:[/dim] {shell_cmd}")
result = subprocess.run(shell_cmd, shell=True, capture_output=True, text=True, check=False)
output = result.stdout
except Exception as e:
if debug:
console.print(f"[yellow]Debug: Exception in first attempt: {str(e)}[/yellow]")
# Try the shell=True approach as fallback
if symlinks_only:
shell_cmd = f"find {wallpaper_dir} -type l -exec identify -format '%w %h %i\\n' {{}} \\;"
else:
shell_cmd = f"find {wallpaper_dir} \\( -type f -o -type l \\) -exec identify -format '%w %h %i\\n' {{}} \\;"
if debug:
console.print(f"[dim]Debug: Fallback shell command:[/dim] {shell_cmd}")
result = subprocess.run(shell_cmd, shell=True, capture_output=True, text=True, check=False)
output = result.stdout
if debug and result.stderr:
console.print(f"[yellow]Debug: stderr output:[/yellow] {result.stderr}")
except Exception as e:
console.print(f"[bold red]Error:[/bold red] {str(e)}")
sys.exit(1)
else:
if not os.path.isdir(wallpaper_dir):
sys.exit(1)
# Look for symlinks only or both regular files and symlinks
if symlinks_only:
# Simpler find command for symlinks
cmd = [
"find", wallpaper_dir, "-type", "l",
"-exec", "identify", "-format", "%w %h %i\\n", "{}", ";"
]
else:
# Command for all image files
cmd = [
"find", wallpaper_dir,
"(", "-type", "f", "-o", "-type", "l", ")",
"-exec", "identify", "-format", "%w %h %i\\n", "{}", ";"
]
try:
# Try using shell=True as a fallback if the list approach doesn't work
try:
result = subprocess.run(cmd, capture_output=True, text=True, check=False)
output = result.stdout
# If we got an error, try shell=True approach
if result.stderr and "missing argument to `-exec'" in result.stderr:
# Build shell command
if symlinks_only:
shell_cmd = f"find {wallpaper_dir} -type l -exec identify -format '%w %h %i\\n' {{}} \\;"
else:
shell_cmd = f"find {wallpaper_dir} \\( -type f -o -type l \\) -exec identify -format '%w %h %i\\n' {{}} \\;"
result = subprocess.run(shell_cmd, shell=True, capture_output=True, text=True, check=False)
output = result.stdout
except Exception:
# Try the shell=True approach as fallback
if symlinks_only:
shell_cmd = f"find {wallpaper_dir} -type l -exec identify -format '%w %h %i\\n' {{}} \\;"
else:
shell_cmd = f"find {wallpaper_dir} \\( -type f -o -type l \\) -exec identify -format '%w %h %i\\n' {{}} \\;"
result = subprocess.run(shell_cmd, shell=True, capture_output=True, text=True, check=False)
output = result.stdout
if debug and result.stderr:
print(f"Debug: stderr output: {result.stderr}")
except Exception:
sys.exit(1)
# Filter by resolution
wallpapers = []
if debug and not quiet:
console.print(f"[dim]Debug: Raw output lines: {len(output.splitlines())}[/dim]")
# If we got no output from the find+identify command, try a fallback approach
if not output.strip():
if debug and not quiet:
console.print("[yellow]Debug: No output from find+identify, trying fallback approach[/yellow]")
# Fallback: Just list the symlinks and skip resolution check
if symlinks_only:
try:
# List all symlinks in the directory
if debug and not quiet:
console.print("[dim]Debug: Listing all symlinks in directory[/dim]")
# Use os.walk to find all symlinks
for root, dirs, files in os.walk(wallpaper_dir):
for name in files + dirs:
full_path = os.path.join(root, name)
if os.path.islink(full_path):
# Check if it's an image file by extension
ext = os.path.splitext(name)[1].lower()
if ext in ['.jpg', '.jpeg', '.png', '.gif']:
if debug and not quiet:
console.print(f"[dim]Debug: Found image symlink: {full_path}[/dim]")
wallpapers.append(full_path)
except Exception as e:
if debug and not quiet:
console.print(f"[yellow]Debug: Error in fallback approach: {str(e)}[/yellow]")
# Process the output from find+identify if we got any
for line in output.splitlines():
if not line.strip():
continue
try:
# First try to extract width and height
parts = line.split(' ', 2) # Split into 3 parts: width, height, path
if len(parts) >= 3:
width = int(parts[0])
height = int(parts[1])
path = parts[2] # The rest is the path
# Skip the current symlink to avoid recursion
if os.path.basename(path) == os.path.basename(DEFAULT_CURRENT_SYMLINK):
if debug and not quiet:
console.print(f"[yellow]Debug: Skipping current symlink: {path}[/yellow]")
continue
if debug and not quiet:
console.print(f"[dim]Debug: Found image: {path} ({width}x{height})[/dim]")
if width >= min_width and height >= min_height:
wallpapers.append(path)
elif debug and not quiet:
console.print(f"[yellow]Debug: Image too small: {path} ({width}x{height})[/yellow]")
except (ValueError, IndexError):
# If parsing fails, log it if not in quiet mode
if not quiet:
console.print(f"[yellow]Warning: Could not parse line: {line}[/yellow]")
continue
return wallpapers
def display_countdown(seconds: int, quiet: bool = False) -> bool:
"""Display countdown with progress bar, return True if user wants to skip"""
if quiet:
# Simple sleep with key check in quiet mode
for _ in range(seconds):
time.sleep(1)
if os.read(0, 1) in (b'q', b'n'):
return True
return False
with Progress(
SpinnerColumn(),
TextColumn("[bold blue]Changing wallpaper in"),
BarColumn(bar_width=40),
TextColumn("[bold]{task.percentage:.0f}%"),
TimeRemainingColumn(),
TextColumn("[yellow](press 'q' to quit, 'n' for next)[/yellow]"),
console=console,
transient=True
) as progress:
task = progress.add_task("", total=seconds)
for _ in range(seconds):
progress.update(task, advance=1)
# Check for key press
import select
if select.select([sys.stdin], [], [], 1)[0]:
key = sys.stdin.read(1)
if key == 'q':
console.print("[bold red]Quitting wallpaper cycle.[/bold red]")
sys.exit(0)
elif key == 'n' or key == '\n':
console.print("[bold yellow]Skipping to next wallpaper.[/bold yellow]")
return True
elif key == 'f':
# Add current wallpaper to favorites
if os.path.exists(DEFAULT_CURRENT_SYMLINK):
current = os.path.realpath(DEFAULT_CURRENT_SYMLINK)
save_favorite(current, DEFAULT_FAVORITES_FILE, quiet)
else:
if not quiet:
console.print("[yellow]No current wallpaper set[/yellow]")
return False
def load_favorites(favorites_file: str) -> List[str]:
"""Load favorite wallpapers from file"""
if not os.path.exists(favorites_file):
return []
try:
with open(favorites_file, 'r') as f:
return [line.strip() for line in f if line.strip()]
except Exception:
return []
def save_favorite(path: str, favorites_file: str, quiet: bool = False):
"""Save a wallpaper path to favorites file"""
favorites = load_favorites(favorites_file)
# Don't add duplicates
if path in favorites:
if not quiet:
console.print(f"[yellow]Wallpaper already in favorites: {path}[/yellow]")
return
try:
with open(favorites_file, 'a') as f:
f.write(f"{path}\n")
if not quiet:
console.print(f"[green]Added to favorites: {path}[/green]")
except Exception as e:
if not quiet:
console.print(f"[bold red]Error saving favorite:[/bold red] {str(e)}")
def set_wallpaper(path: str, current_symlink: str, quiet: bool = False):
"""Set wallpaper using feh and update symlink"""
if not quiet:
console.print(f"Setting wallpaper: [cyan]{path}[/cyan]")
try:
# Set wallpaper
subprocess.run(["feh", "--bg-fill", path], check=True, capture_output=True)
# Update symlink
if current_symlink:
# Ensure directory exists
os.makedirs(os.path.dirname(current_symlink), exist_ok=True)
# Remove existing symlink if it exists
if os.path.exists(current_symlink):
os.remove(current_symlink)
# Create new symlink
os.symlink(path, current_symlink)
except Exception as e:
if not quiet:
console.print(f"[bold red]Error:[/bold red] {str(e)}")
sys.exit(1)
def main():
"""Main function"""
# Parse arguments
args = parse_args()
# Check dependencies
check_dependencies()
# Handle adding current wallpaper to favorites
if args.add_favorite:
if os.path.exists(DEFAULT_CURRENT_SYMLINK):
current = os.path.realpath(DEFAULT_CURRENT_SYMLINK)
save_favorite(current, DEFAULT_FAVORITES_FILE, args.quiet)
else:
if not args.quiet:
console.print("[bold red]Error:[/bold red] No current wallpaper set")
sys.exit(0)
# Use favorites if requested
if args.favorites:
favorites = load_favorites(DEFAULT_FAVORITES_FILE)
if not favorites:
if not args.quiet:
console.print("[bold yellow]No favorites found.[/bold yellow] Add favorites with --add-favorite")
sys.exit(1)
wallpapers = favorites
if not args.quiet:
console.print(f"[bold green]Using {len(wallpapers)} favorite wallpapers.[/bold green]")
else:
# Find wallpapers
wallpapers = find_wallpapers(args.dir, args.width, args.height, args.quiet, args.symlinks_only, args.debug)
if not wallpapers:
if not args.quiet:
console.print(Panel(
f"No suitable wallpapers found in '{args.dir}' with minimum resolution {args.width}x{args.height}.",
title="Error",
border_style="red"
))
sys.exit(1)
if not args.quiet:
console.print(f"[bold green]Found {len(wallpapers)} suitable wallpapers.[/bold green]")
# Handle once mode (set one random wallpaper and exit)
if args.once:
wallpaper = random.choice(wallpapers)
set_wallpaper(wallpaper, args.current, args.quiet)
sys.exit(0)
# Main loop
while True:
# Randomize if requested
if args.random:
random.shuffle(wallpapers)
# Cycle through wallpapers
for wallpaper in wallpapers:
# Set wallpaper and update symlink
set_wallpaper(wallpaper, args.current, args.quiet)
# Wait with countdown
skip = display_countdown(args.seconds, args.quiet)
if skip:
continue
if not args.quiet:
console.print("[bold green]Finished cycling through all wallpapers.[/bold green]")
# Exit if not looping
if not args.loop:
break
if not args.quiet:
console.print("[bold blue]Restarting cycle...[/bold blue]")
if __name__ == "__main__":
# Store original terminal settings
fd = sys.stdin.fileno()
old_settings = None
try:
# Only set raw mode if stdin is a terminal
if os.isatty(fd):
import tty
import termios
old_settings = termios.tcgetattr(fd)
tty.setraw(fd)
main()
except KeyboardInterrupt:
console.print("\n[bold red]Program interrupted by user.[/bold red]")
except Exception as e:
console.print(f"\n[bold red]Error:[/bold red] {str(e)}")
finally:
# Restore terminal settings if we changed them
if old_settings:
try:
import termios
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
except:
pass