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