10
|
1 #!/usr/bin/env python3
|
|
2 # bing4desktop.py - skrypt tray dla Cinnamon oraz Matte i innych WM
|
|
3 # inspiracja: https://pystray.readthedocs.io/en/latest/usage.html
|
|
4 # oraz 'zasłyszane' w internecie :)
|
|
5 # licencja: Public Domain
|
|
6 # edytor: Geany
|
|
7 # data: 05-II-2024
|
|
8 # napisał: Prymula
|
|
9
|
|
10 # python3-pillow-tk
|
|
11
|
|
12 import pystray
|
|
13 from pystray import Icon as icon, Menu as menu, MenuItem as item
|
|
14 import tkinter as tk
|
|
15 from tkinter import messagebox
|
|
16 from PIL import ImageTk, Image
|
|
17
|
|
18 import os, sys, subprocess
|
|
19 import requests
|
|
20 import json
|
|
21 import tempfile
|
|
22 import shutil
|
11
|
23 import glob
|
10
|
24
|
11
|
25 ver = "0.240206-0"
|
10
|
26
|
|
27 BING_URI_BASE = "http://www.bing.com"
|
11
|
28 BING_WALLPAPER_PATH = "/HPImageArchive.aspx?format=js&idx=1&n=1&mkt=en-US"
|
10
|
29 full_path=""
|
|
30 actualImage = -1
|
|
31 COPYRIGHT_TXT = ""
|
11
|
32 TITLE = ""
|
10
|
33
|
|
34 tmp_path = tempfile.mkdtemp()
|
|
35
|
|
36 class WPaper:
|
|
37 def get(self):
|
11
|
38 global full_path, COPYRIGHT_TXT, TITLE
|
10
|
39 # open the Bing HPImageArchive URI and ask for a JSON response
|
|
40 resp = requests.get(BING_URI_BASE + BING_WALLPAPER_PATH)
|
|
41
|
|
42 if resp.status_code == 200:
|
|
43 json_response = json.loads(resp.content)
|
|
44 wallpaper_path = json_response['images'][0]['url']
|
|
45 COPYRIGHT_TXT = json_response['images'][0]['copyright']
|
11
|
46 TITLE = json_response['images'][0]['title']
|
|
47
|
10
|
48 filename = wallpaper_path.split('/')[-1]
|
|
49 wallpaper_uri = BING_URI_BASE + wallpaper_path
|
|
50 filename_short = filename.split('&')
|
|
51 print ("filemname_short", filename_short[0])
|
|
52 # open the actual wallpaper uri, and write the response as an image on the filesystem
|
|
53 response = requests.get(wallpaper_uri)
|
|
54 if resp.status_code == 200:
|
|
55 desktop_env = os.environ.get('DESKTOP_SESSION')
|
|
56 if desktop_env=="windows":
|
|
57 messagebox.showinfo("Błąd","Brak wsparcia dla Windows i Mac !")
|
|
58 cleanup()
|
|
59 exit
|
|
60 else:
|
|
61 full_path = tmp_path + filename_short[0]
|
|
62 with open(full_path, 'wb') as f:
|
|
63 f.write(response.content)
|
|
64 else:
|
|
65 raise ValueError("[ERROR] non-200 response from Bing server for '{}'".format(wallpaper_uri))
|
|
66 COPYRIGHT_TXT = "[ERROR] non-200 response from Bing server for " + str(format(wallpaper_uri))
|
|
67 return False
|
|
68 else:
|
|
69 raise ValueError("[ERROR] non-200 response from Bing server for '{}'".format(BING_URI_BASE + BING_WALLPAPER_PATH))
|
|
70 COPYRIGHT_TXT = "[ERROR] non-200 response from Bing server for " + str(format(BING_URI_BASE + BING_WALLPAPER_PATH))
|
|
71 return False
|
|
72 return True
|
|
73
|
|
74 def set(self,file_loc, first_run):
|
|
75 global full_path
|
|
76 desktop_env = os.environ.get('DESKTOP_SESSION')
|
|
77
|
|
78 if len(full_path) == 0:
|
|
79 messagebox.showinfo("Błąd","Niewybrano obrazu, najpierw wybierz obraz")
|
|
80 return
|
|
81 try:
|
|
82 if desktop_env in ["gnome-classic", "gnome", "unity", "default"]:
|
|
83 uri = "'file://%s'" % file_loc
|
|
84 try:
|
|
85 SCHEMA = "org.gnome.desktop.background"
|
|
86 KEY = "picture-uri"
|
|
87 gsettings = Gio.Settings.new(SCHEMA)
|
|
88 gsettings.set_string(KEY, uri)
|
|
89 except:
|
|
90 args = ["gsettings", "set", "org.gnome.desktop.background", "picture-uri", uri]
|
|
91 subprocess.Popen(args)
|
|
92 elif desktop_env in ["cinnamon"]:
|
|
93 uri = "'file://%s'" % file_loc
|
|
94 try:
|
|
95 SCHEMA = "org.cinnamon.desktop.background"
|
|
96 KEY = "picture-uri"
|
|
97 gsettings = Gio.Settings.new(SCHEMA)
|
|
98 gsettings.set_string(KEY, uri)
|
|
99 except:
|
|
100 args = ["gsettings", "set", "org.cinnamon.desktop.background", "picture-uri", uri]
|
|
101 subprocess.Popen(args)
|
|
102 elif desktop_env=="mate":
|
|
103 try: # MATE >= 1.6
|
|
104 # info from http://wiki.mate-desktop.org/docs:gsettings
|
|
105 args = ["gsettings", "set", "org.mate.background", "picture-filename", "'%s'" % file_loc]
|
|
106 subprocess.Popen(args)
|
|
107 except: # MATE < 1.6
|
|
108 # From https://bugs.launchpad.net/variety/+bug/1033918
|
|
109 args = ["mateconftool-2","-t","string","--set","/desktop/mate/background/picture_filename",'"%s"' %file_loc]
|
|
110 subprocess.Popen(args)
|
|
111 elif desktop_env=="gnome2": # Not tested
|
|
112 # From https://bugs.launchpad.net/variety/+bug/1033918
|
|
113 args = ["gconftool-2","-t","string","--set","/desktop/gnome/background/picture_filename", '"%s"' %file_loc]
|
|
114 subprocess.Popen(args)
|
|
115 ## KDE4 is difficult
|
|
116 ## see http://blog.zx2c4.com/699 for a solution that might work
|
|
117 elif desktop_env in ["kde3", "trinity"]:
|
|
118 # From http://ubuntuforums.org/archive/index.php/t-803417.html
|
|
119 args = 'dcop kdesktop KBackgroundIface setWallpaper 0 "%s" 6' % file_loc
|
|
120 subprocess.Popen(args,shell=True)
|
|
121
|
|
122 elif desktop_env=="xfce4":
|
|
123 #From http://www.commandlinefu.com/commands/view/2055/change-wallpaper-for-xfce4-4.6.0
|
|
124 if first_run:
|
|
125 args0 = ["xfconf-query", "-c", "xfce4-desktop", "-p", "/backdrop/screen0/monitor0/image-path", "-s", file_loc]
|
|
126 args1 = ["xfconf-query", "-c", "xfce4-desktop", "-p", "/backdrop/screen0/monitor0/image-style", "-s", "3"]
|
|
127 args2 = ["xfconf-query", "-c", "xfce4-desktop", "-p", "/backdrop/screen0/monitor0/image-show", "-s", "true"]
|
|
128 subprocess.Popen(args0)
|
|
129 subprocess.Popen(args1)
|
|
130 subprocess.Popen(args2)
|
|
131 args = ["xfdesktop","--reload"]
|
|
132 subprocess.Popen(args)
|
|
133
|
|
134 elif desktop_env in ["fluxbox","jwm","openbox","afterstep"]:
|
|
135 #http://fluxbox-wiki.org/index.php/Howto_set_the_background
|
|
136 # used fbsetbg on jwm too since I am too lazy to edit the XML configuration
|
|
137 # now where fbsetbg does the job excellent anyway.
|
|
138 # and I have not figured out how else it can be set on Openbox and AfterSTep
|
|
139 # but fbsetbg works excellent here too.
|
|
140 try:
|
|
141 args = ["fbsetbg", file_loc]
|
|
142 subprocess.Popen(args)
|
|
143 except:
|
|
144 sys.stderr.write("ERROR: Failed to set wallpaper with fbsetbg!\n")
|
|
145 sys.stderr.write("Please make sre that You have fbsetbg installed.\n")
|
|
146 elif desktop_env=="icewm":
|
|
147 # command found at http://urukrama.wordpress.com/2007/12/05/desktop-backgrounds-in-window-managers/
|
|
148 args = ["icewmbg", file_loc]
|
|
149 subprocess.Popen(args)
|
|
150 elif desktop_env=="blackbox":
|
|
151 # command found at http://blackboxwm.sourceforge.net/BlackboxDocumentation/BlackboxBackground
|
|
152 args = ["bsetbg", "-full", file_loc]
|
|
153 subprocess.Popen(args)
|
|
154 elif desktop_env=="lxde":
|
|
155 args = "pcmanfm --set-wallpaper %s --wallpaper-mode=scaled" % file_loc
|
|
156 subprocess.Popen(args,shell=True)
|
|
157 elif desktop_env=="WindowMaker":
|
|
158 # From http://www.commandlinefu.com/commands/view/3857/set-wallpaper-on-windowmaker-in-one-line
|
|
159 args = "wmsetbg -s -u %s" % file_loc
|
|
160 subprocess.Popen(args,shell=True)
|
|
161 elif desktop_env=="windows": #Not tested since I do not run this on Windows
|
|
162 #From https://stackoverflow.com/questions/1977694/change-desktop-background
|
|
163 import ctypes
|
|
164 SPI_SETDESKWALLPAPER = 20
|
|
165 ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, file_loc , 0)
|
|
166 else:
|
|
167 if first_run: #don't spam the user with the same message over and over again
|
|
168 sys.stderr.write("Warning: Failed to set wallpaper. Your desktop environment is not supported.")
|
|
169 sys.stderr.write("You can try manually to set Your wallpaper to %s" % file_loc)
|
|
170 return False
|
|
171 return True
|
|
172 except:
|
|
173 sys.stderr.write("ERROR: Failed to set wallpaper. There might be a bug.\n")
|
|
174 return False
|
|
175
|
|
176
|
|
177 class Gui():
|
11
|
178 global COPYRIGHT_TXT, TITLE
|
10
|
179
|
|
180 def __init__(self):
|
|
181 self.window = tk.Tk()
|
11
|
182 self.image = None
|
|
183 for ico in ['./bing.ico', '/usr/share/bing4desktop/bing.ico']:
|
|
184 try:
|
|
185 self.image = Image.open(ico)
|
|
186 except FileNotFoundError as fs:
|
|
187 print ('W bieżącym katalogu, brak ikony, ', fs)
|
|
188 finally:
|
|
189 break
|
|
190
|
|
191 #if self.image != None:
|
|
192 # break
|
|
193
|
|
194 self.tmp = None
|
10
|
195 self.menu = (
|
|
196 item("Ustaw Tapetę", lambda icon, item: wp.set(full_path, True)),
|
|
197 item('Tapeta poprzednia', lambda icon, item: self.change_pic(1)),
|
|
198 item('Tapeta następna', lambda icon, item: self.change_pic(-1)),
|
11
|
199 item('Opis zdjęcia', lambda icon, item: icon.notify(TITLE + ' --- ' + COPYRIGHT_TXT)),
|
10
|
200 item('O Programie', lambda icon, item: self.about()),
|
|
201
|
|
202 item('Wyjdź', self.quit_window)
|
|
203 )
|
|
204 self.frame = tk.Frame(self.window, width=600, height=400)
|
|
205 self.frame.pack()
|
|
206 self.frame.place(anchor='center', relx=0.5, rely=5)
|
|
207
|
|
208 #self.window.title("Bing4Desktop")
|
|
209 #self.window.geometry('800x600')
|
|
210 #self.window.protocol('WM_DELETE_WINDOW', self.withdraw_window)
|
|
211 self.withdraw_window()
|
|
212 self.window.mainloop()
|
|
213
|
|
214 def about(self):
|
|
215 global ver
|
|
216 messagebox.showinfo("Bing4Desktop","Inspracja:\npystray.readthedocs.io/en/latest/usage.html\n\nNapisał: Prymula\n\nLuty 2024\n\nLicencja:\nPublic Domain\n\nWersja: "+ver)
|
|
217 # możliwe że nieprawidlowe
|
|
218 self.window.destroy()
|
|
219 self.window.update()
|
|
220
|
|
221 def change_pic(self, n):
|
|
222 global actualImage, BING_WALLPAPER_PATH
|
|
223 BASE = "/HPImageArchive.aspx?format=js&idx="
|
|
224 OFF = "&n=1&mkt=en-US"
|
|
225
|
|
226 actualImage = actualImage + n;
|
|
227 if (actualImage < 0):
|
|
228 actualImage = 10
|
|
229 elif (actualImage > 10):
|
|
230 actualImage = 0
|
|
231
|
|
232 wp=WPaper()
|
|
233 if wp.get():
|
|
234 BING_WALLPAPER_PATH = BASE+str(actualImage)+OFF
|
|
235 if wp.get() == False:
|
|
236 cleanup()
|
|
237 exit
|
|
238
|
11
|
239 # Wszystko pięknie tylko metoda 'show', zmienia nazwę pliku przechowywanego w TMP
|
|
240 # Pozatym nie ubija a nie znalazłem nic lepszego
|
|
241 print ("GLOB: ", glob.glob( os.path.join('/tmp', '*.PNG')))
|
|
242 for infile in glob.glob( os.path.join('/tmp', '*.PNG')):
|
|
243 print ("INFILE: ", infile)
|
|
244 viewer = subprocess.Popen(['/usr/bin/eom', infile])
|
|
245 viewer.terminate()
|
|
246 viewer.kill() # make sure the viewer is gone; not needed on Windows
|
|
247
|
10
|
248 img = Image.open(full_path) #.convert('RGBA') # PIL solution
|
11
|
249 self.tmp = img.resize((600, 400), None, None, 3.0)
|
|
250 self.tmp.show()
|
10
|
251
|
|
252 def quit_window(self):
|
|
253 self.icon.stop()
|
|
254 self.window.destroy()
|
|
255
|
|
256 def show_window(self):
|
|
257 self.icon.stop()
|
|
258 self.window.protocol('WM_DELETE_WINDOW', self.withdraw_window)
|
|
259 self.window.after(0, self.window.deiconify)
|
|
260
|
|
261 def withdraw_window(self):
|
|
262 self.window.withdraw()
|
|
263 self.icon = pystray.Icon("name", self.image, "title", self.menu)
|
|
264 self.icon.run()
|
|
265
|
|
266 def cleanup():
|
|
267 # NIEBEZPIECZNA ! lepiej niczym innym nie nadpisywać tych zmiennych
|
|
268 shutil.rmtree(tmp_path)
|
|
269
|
|
270 if __name__ in '__main__':
|
|
271 wp=WPaper()
|
|
272 if wp.get():
|
|
273 wp.set(full_path, True)
|
|
274 g = Gui()
|
|
275 cleanup()
|