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
|
16
|
25 ver = "0.240206-4"
|
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)
|
13
|
186 except:
|
|
187 print ('W bieżącym katalogu, brak ikony ' + ico)
|
11
|
188 finally:
|
13
|
189 if self.image != None:
|
|
190 break
|
11
|
191
|
|
192 self.tmp = None
|
10
|
193 self.menu = (
|
|
194 item("Ustaw Tapetę", lambda icon, item: wp.set(full_path, True)),
|
|
195 item('Tapeta poprzednia', lambda icon, item: self.change_pic(1)),
|
|
196 item('Tapeta następna', lambda icon, item: self.change_pic(-1)),
|
11
|
197 item('Opis zdjęcia', lambda icon, item: icon.notify(TITLE + ' --- ' + COPYRIGHT_TXT)),
|
10
|
198 item('O Programie', lambda icon, item: self.about()),
|
|
199
|
|
200 item('Wyjdź', self.quit_window)
|
|
201 )
|
|
202 self.frame = tk.Frame(self.window, width=600, height=400)
|
|
203 self.frame.pack()
|
|
204 self.frame.place(anchor='center', relx=0.5, rely=5)
|
|
205
|
|
206 #self.window.title("Bing4Desktop")
|
|
207 #self.window.geometry('800x600')
|
|
208 #self.window.protocol('WM_DELETE_WINDOW', self.withdraw_window)
|
|
209 self.withdraw_window()
|
|
210 self.window.mainloop()
|
|
211
|
|
212 def about(self):
|
|
213 global ver
|
15
|
214 messagebox.showinfo("Bing4Desktop","Inspiracja:\npystray.readthedocs.io/en/latest/usage.html\n\nNapisał: Prymula\n\nLuty 2024\n\nLicencja:\nPublic Domain\n\nWersja: "+ver)
|
13
|
215 # możliwe że nieprawidlowe po wyjściu z aplikacji zwróci bląd :(
|
10
|
216 self.window.destroy()
|
|
217 self.window.update()
|
|
218
|
|
219 def change_pic(self, n):
|
|
220 global actualImage, BING_WALLPAPER_PATH
|
|
221 BASE = "/HPImageArchive.aspx?format=js&idx="
|
|
222 OFF = "&n=1&mkt=en-US"
|
|
223
|
|
224 actualImage = actualImage + n;
|
|
225 if (actualImage < 0):
|
|
226 actualImage = 10
|
|
227 elif (actualImage > 10):
|
|
228 actualImage = 0
|
|
229
|
|
230 wp=WPaper()
|
|
231 if wp.get():
|
|
232 BING_WALLPAPER_PATH = BASE+str(actualImage)+OFF
|
|
233 if wp.get() == False:
|
|
234 cleanup()
|
|
235 exit
|
|
236
|
11
|
237 # Wszystko pięknie tylko metoda 'show', zmienia nazwę pliku przechowywanego w TMP
|
|
238 # Pozatym nie ubija a nie znalazłem nic lepszego
|
|
239 print ("GLOB: ", glob.glob( os.path.join('/tmp', '*.PNG')))
|
|
240 for infile in glob.glob( os.path.join('/tmp', '*.PNG')):
|
|
241 print ("INFILE: ", infile)
|
|
242 viewer = subprocess.Popen(['/usr/bin/eom', infile])
|
|
243 viewer.terminate()
|
|
244 viewer.kill() # make sure the viewer is gone; not needed on Windows
|
|
245
|
10
|
246 img = Image.open(full_path) #.convert('RGBA') # PIL solution
|
11
|
247 self.tmp = img.resize((600, 400), None, None, 3.0)
|
|
248 self.tmp.show()
|
10
|
249
|
|
250 def quit_window(self):
|
|
251 self.icon.stop()
|
|
252 self.window.destroy()
|
|
253
|
|
254 def show_window(self):
|
|
255 self.icon.stop()
|
|
256 self.window.protocol('WM_DELETE_WINDOW', self.withdraw_window)
|
|
257 self.window.after(0, self.window.deiconify)
|
|
258
|
|
259 def withdraw_window(self):
|
|
260 self.window.withdraw()
|
|
261 self.icon = pystray.Icon("name", self.image, "title", self.menu)
|
|
262 self.icon.run()
|
|
263
|
|
264 def cleanup():
|
|
265 # NIEBEZPIECZNA ! lepiej niczym innym nie nadpisywać tych zmiennych
|
|
266 shutil.rmtree(tmp_path)
|
|
267
|
|
268 if __name__ in '__main__':
|
|
269 wp=WPaper()
|
|
270 if wp.get():
|
|
271 wp.set(full_path, True)
|
|
272 g = Gui()
|
|
273 cleanup()
|