10
|
1 #!/usr/bin/env python3
|
34
|
2 # bing4desktop.py - skrypt tray dla Cinnamon LxQt, oraz Matte i innych WM
|
10
|
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 import pystray
|
|
11 from pystray import Icon as icon, Menu as menu, MenuItem as item
|
|
12 import tkinter as tk
|
|
13 from tkinter import messagebox
|
|
14 from PIL import ImageTk, Image
|
|
15
|
|
16 import os, sys, subprocess
|
|
17 import requests
|
|
18 import json
|
|
19 import tempfile
|
|
20 import shutil
|
11
|
21 import glob
|
10
|
22
|
34
|
23 ver = "0.240209-0"
|
10
|
24
|
|
25 BING_URI_BASE = "http://www.bing.com"
|
31
|
26 BING_WALLPAPER_PATH = "/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US"
|
10
|
27 full_path=""
|
31
|
28 actualImage = 0
|
10
|
29 COPYRIGHT_TXT = ""
|
11
|
30 TITLE = ""
|
17
|
31 TMP_COPYRIGHT = ""
|
|
32 TMP_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):
|
17
|
75 global full_path, TMP_COPYRIGHT, COPYRIGHT_TXT, TMP_TITLE, TITLE
|
10
|
76 desktop_env = os.environ.get('DESKTOP_SESSION')
|
|
77
|
17
|
78 TMP_COPYRIGHT = COPYRIGHT_TXT
|
|
79 TMP_TITLE = TITLE
|
34
|
80
|
|
81 # zawiesza
|
|
82 #if len(full_path) == 0:
|
|
83 # messagebox.showinfo("Błąd","Niewybrano obrazu, najpierw wybierz obraz")
|
|
84 # return
|
10
|
85 try:
|
|
86 if desktop_env in ["gnome-classic", "gnome", "unity", "default"]:
|
|
87 uri = "'file://%s'" % file_loc
|
|
88 try:
|
|
89 SCHEMA = "org.gnome.desktop.background"
|
|
90 KEY = "picture-uri"
|
|
91 gsettings = Gio.Settings.new(SCHEMA)
|
|
92 gsettings.set_string(KEY, uri)
|
|
93 except:
|
|
94 args = ["gsettings", "set", "org.gnome.desktop.background", "picture-uri", uri]
|
|
95 subprocess.Popen(args)
|
|
96 elif desktop_env in ["cinnamon"]:
|
|
97 uri = "'file://%s'" % file_loc
|
|
98 try:
|
|
99 SCHEMA = "org.cinnamon.desktop.background"
|
|
100 KEY = "picture-uri"
|
|
101 gsettings = Gio.Settings.new(SCHEMA)
|
|
102 gsettings.set_string(KEY, uri)
|
|
103 except:
|
|
104 args = ["gsettings", "set", "org.cinnamon.desktop.background", "picture-uri", uri]
|
|
105 subprocess.Popen(args)
|
21
|
106 elif desktop_env in ['mate', 'lightdm-xsession']:
|
10
|
107 try: # MATE >= 1.6
|
|
108 # info from http://wiki.mate-desktop.org/docs:gsettings
|
|
109 args = ["gsettings", "set", "org.mate.background", "picture-filename", "'%s'" % file_loc]
|
|
110 subprocess.Popen(args)
|
|
111 except: # MATE < 1.6
|
|
112 # From https://bugs.launchpad.net/variety/+bug/1033918
|
|
113 args = ["mateconftool-2","-t","string","--set","/desktop/mate/background/picture_filename",'"%s"' %file_loc]
|
|
114 subprocess.Popen(args)
|
|
115 elif desktop_env=="gnome2": # Not tested
|
|
116 # From https://bugs.launchpad.net/variety/+bug/1033918
|
|
117 args = ["gconftool-2","-t","string","--set","/desktop/gnome/background/picture_filename", '"%s"' %file_loc]
|
|
118 subprocess.Popen(args)
|
|
119 ## KDE4 is difficult
|
|
120 ## see http://blog.zx2c4.com/699 for a solution that might work
|
|
121 elif desktop_env in ["kde3", "trinity"]:
|
|
122 # From http://ubuntuforums.org/archive/index.php/t-803417.html
|
|
123 args = 'dcop kdesktop KBackgroundIface setWallpaper 0 "%s" 6' % file_loc
|
|
124 subprocess.Popen(args,shell=True)
|
|
125
|
|
126 elif desktop_env=="xfce4":
|
|
127 #From http://www.commandlinefu.com/commands/view/2055/change-wallpaper-for-xfce4-4.6.0
|
|
128 if first_run:
|
|
129 args0 = ["xfconf-query", "-c", "xfce4-desktop", "-p", "/backdrop/screen0/monitor0/image-path", "-s", file_loc]
|
|
130 args1 = ["xfconf-query", "-c", "xfce4-desktop", "-p", "/backdrop/screen0/monitor0/image-style", "-s", "3"]
|
|
131 args2 = ["xfconf-query", "-c", "xfce4-desktop", "-p", "/backdrop/screen0/monitor0/image-show", "-s", "true"]
|
|
132 subprocess.Popen(args0)
|
|
133 subprocess.Popen(args1)
|
|
134 subprocess.Popen(args2)
|
|
135 args = ["xfdesktop","--reload"]
|
|
136 subprocess.Popen(args)
|
|
137
|
|
138 elif desktop_env in ["fluxbox","jwm","openbox","afterstep"]:
|
|
139 #http://fluxbox-wiki.org/index.php/Howto_set_the_background
|
|
140 # used fbsetbg on jwm too since I am too lazy to edit the XML configuration
|
|
141 # now where fbsetbg does the job excellent anyway.
|
|
142 # and I have not figured out how else it can be set on Openbox and AfterSTep
|
|
143 # but fbsetbg works excellent here too.
|
|
144 try:
|
|
145 args = ["fbsetbg", file_loc]
|
|
146 subprocess.Popen(args)
|
|
147 except:
|
|
148 sys.stderr.write("ERROR: Failed to set wallpaper with fbsetbg!\n")
|
|
149 sys.stderr.write("Please make sre that You have fbsetbg installed.\n")
|
|
150 elif desktop_env=="icewm":
|
|
151 # command found at http://urukrama.wordpress.com/2007/12/05/desktop-backgrounds-in-window-managers/
|
|
152 args = ["icewmbg", file_loc]
|
|
153 subprocess.Popen(args)
|
|
154 elif desktop_env=="blackbox":
|
|
155 # command found at http://blackboxwm.sourceforge.net/BlackboxDocumentation/BlackboxBackground
|
|
156 args = ["bsetbg", "-full", file_loc]
|
|
157 subprocess.Popen(args)
|
32
|
158 elif desktop_env in ['xqt', 'Lubuntu']:
|
|
159 #args = "pcmanfm --set-wallpaper %s --wallpaper-mode=scaled" % file_loc
|
|
160 args = "pcmanfm-qt --set-wallpaper=" + file_loc + " --wallpaper-mode=fit"
|
|
161 print ("ALOCHA: "+args)
|
10
|
162 subprocess.Popen(args,shell=True)
|
|
163 elif desktop_env=="WindowMaker":
|
|
164 # From http://www.commandlinefu.com/commands/view/3857/set-wallpaper-on-windowmaker-in-one-line
|
|
165 args = "wmsetbg -s -u %s" % file_loc
|
|
166 subprocess.Popen(args,shell=True)
|
|
167 elif desktop_env=="windows": #Not tested since I do not run this on Windows
|
|
168 #From https://stackoverflow.com/questions/1977694/change-desktop-background
|
|
169 import ctypes
|
|
170 SPI_SETDESKWALLPAPER = 20
|
|
171 ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, file_loc , 0)
|
|
172 else:
|
|
173 if first_run: #don't spam the user with the same message over and over again
|
|
174 sys.stderr.write("Warning: Failed to set wallpaper. Your desktop environment is not supported.")
|
|
175 sys.stderr.write("You can try manually to set Your wallpaper to %s" % file_loc)
|
|
176 return False
|
|
177 return True
|
|
178 except:
|
|
179 sys.stderr.write("ERROR: Failed to set wallpaper. There might be a bug.\n")
|
|
180 return False
|
|
181
|
|
182
|
|
183 class Gui():
|
17
|
184 global TMP_COPYRIGHT, TMP_TITLE
|
10
|
185
|
34
|
186 def __init__(self, succes_set):
|
10
|
187 self.window = tk.Tk()
|
11
|
188 self.image = None
|
|
189 for ico in ['./bing.ico', '/usr/share/bing4desktop/bing.ico']:
|
|
190 try:
|
|
191 self.image = Image.open(ico)
|
13
|
192 except:
|
|
193 print ('W bieżącym katalogu, brak ikony ' + ico)
|
11
|
194 finally:
|
13
|
195 if self.image != None:
|
|
196 break
|
11
|
197
|
|
198 self.tmp = None
|
10
|
199 self.menu = (
|
|
200 item("Ustaw Tapetę", lambda icon, item: wp.set(full_path, True)),
|
19
|
201 item('Tapeta poprzednia', lambda icon, item: self.change_pic(1, icon)),
|
|
202 item('Tapeta następna', lambda icon, item: self.change_pic(-1, icon)),
|
17
|
203 item('Opis zdjęcia', lambda icon, item: icon.notify(TMP_TITLE + ' --- ' + TMP_COPYRIGHT)),
|
10
|
204 item('O Programie', lambda icon, item: self.about()),
|
|
205 item('Wyjdź', self.quit_window)
|
|
206 )
|
34
|
207
|
10
|
208 self.frame = tk.Frame(self.window, width=600, height=400)
|
|
209 self.frame.pack()
|
|
210 self.frame.place(anchor='center', relx=0.5, rely=5)
|
|
211
|
|
212 #self.window.title("Bing4Desktop")
|
|
213 #self.window.geometry('800x600')
|
|
214 #self.window.protocol('WM_DELETE_WINDOW', self.withdraw_window)
|
34
|
215
|
|
216
|
|
217 #self.withdraw_window()
|
|
218 #self.window.withdraw()
|
|
219 self.window.withdraw()
|
|
220 self.icon = pystray.Icon("name", self.image, "Bing4Desktop", self.menu)
|
|
221 print ("SUCCES: ", succes_set)
|
|
222
|
|
223 # FIXME - Nie działą notyfikacja tylko dialog boc
|
|
224 if succes_set == False:
|
|
225 #self.icon.notify("", "Nie udało połączyć się z serwerem")
|
|
226 self.net_info()
|
|
227
|
|
228 self.icon.run()
|
10
|
229 self.window.mainloop()
|
|
230
|
34
|
231 def net_info(self):
|
|
232 messagebox.showinfo("Bing4Desktop","Nieudało się połączyć z serwerem !")
|
|
233 # możliwe że nieprawidlowe po wyjściu z aplikacji zwróci bląd :(
|
|
234 self.window.destroy()
|
|
235 self.window.update()
|
|
236
|
|
237
|
|
238
|
10
|
239 def about(self):
|
|
240 global ver
|
15
|
241 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
|
242 # możliwe że nieprawidlowe po wyjściu z aplikacji zwróci bląd :(
|
10
|
243 self.window.destroy()
|
|
244 self.window.update()
|
|
245
|
19
|
246 def change_pic(self, n, icon):
|
|
247 global actualImage, BING_WALLPAPER_PATH, TITLE, COPYRIGHT_TXT
|
10
|
248 BASE = "/HPImageArchive.aspx?format=js&idx="
|
|
249 OFF = "&n=1&mkt=en-US"
|
17
|
250
|
10
|
251 actualImage = actualImage + n;
|
|
252 if (actualImage < 0):
|
17
|
253 actualImage = 7
|
|
254 elif (actualImage > 7):
|
10
|
255 actualImage = 0
|
34
|
256
|
10
|
257 wp=WPaper()
|
34
|
258 try:
|
|
259 wp.get()
|
10
|
260 BING_WALLPAPER_PATH = BASE+str(actualImage)+OFF
|
|
261 if wp.get() == False:
|
|
262 cleanup()
|
|
263 exit
|
|
264
|
11
|
265 # Wszystko pięknie tylko metoda 'show', zmienia nazwę pliku przechowywanego w TMP
|
32
|
266 ## Pozatym nie ubija a nie znalazłem nic lepszego
|
|
267 #print ("GLOB: ", glob.glob( os.path.join('/tmp', '*.PNG')))
|
|
268 #for infile in glob.glob( os.path.join('/tmp', '*.PNG')):
|
|
269 # print ("INFILE: ", infile)
|
|
270 # viewer = subprocess.Popen(['/usr/bin/eom', infile])
|
|
271 # viewer.terminate()
|
|
272 # viewer.kill() # make sure the viewer is gone; not needed on Windows
|
11
|
273
|
10
|
274 img = Image.open(full_path) #.convert('RGBA') # PIL solution
|
11
|
275 self.tmp = img.resize((600, 400), None, None, 3.0)
|
|
276 self.tmp.show()
|
19
|
277 icon.notify(TITLE + ' --- ' + COPYRIGHT_TXT)
|
34
|
278 except:
|
|
279 print ("Serewr niedostępny")
|
|
280
|
10
|
281 def quit_window(self):
|
|
282 self.icon.stop()
|
|
283 self.window.destroy()
|
|
284
|
|
285 def show_window(self):
|
|
286 self.icon.stop()
|
|
287 self.window.protocol('WM_DELETE_WINDOW', self.withdraw_window)
|
|
288 self.window.after(0, self.window.deiconify)
|
34
|
289 """
|
10
|
290 def withdraw_window(self):
|
|
291 self.window.withdraw()
|
34
|
292 self.icon = pystray.Icon("name", self.image, "Bing4Desktop", self.menu)
|
10
|
293 self.icon.run()
|
34
|
294 """
|
10
|
295 def cleanup():
|
|
296 # NIEBEZPIECZNA ! lepiej niczym innym nie nadpisywać tych zmiennych
|
|
297 shutil.rmtree(tmp_path)
|
|
298
|
|
299 if __name__ in '__main__':
|
|
300 wp=WPaper()
|
34
|
301 w = False
|
|
302 try:
|
|
303 w = wp.get()
|
10
|
304 wp.set(full_path, True)
|
34
|
305 except:
|
|
306 print ("Serewr niedostępny")
|
|
307 #if w:
|
|
308
|
|
309 g = Gui(w)
|
|
310 cleanup()
|