-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmenugenerator
executable file
·366 lines (345 loc) · 16.3 KB
/
menugenerator
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
#!/usr/bin/env python
import os
import sys
import getopt
import xdg.Menu
import xdg.DesktopEntry
import xdg.IconTheme
### Version ###
CurrentVersion="1.1"
### Configurable Params ###
BaseConfiguration={
'Directory':'~/.config/menugenerator/',
'File':'configuration'
}
### RUNNING ###
CurrentRunning = {
'Options': {
'File':{
'Configuration':'~/.config/menugenerator/configuration',
'Menu':'~/.config/menugenerator/applications.menu',
'Cache':'~/.config/menugenerator/cache',
'Output':None
},
'Menu':{
'Debug':False,
'Create':False,
'Syntax':'',
'Piped':False,
'UseGenericName':False
},
'Icons':{
'Use':False,
'Theme':None,
'Size':None,
'Extensions':['png','svg','xpm'],
'ClearCache': False
},
'Categories': {
'Order':None,
'Icons':None,
'Names':None
}
},
'Menu':None,
}
### Functions ###
def FirstRun():
tempfiletowrite=os.path.abspath(os.path.join(os.path.expanduser(BaseConfiguration['Directory']),BaseConfiguration['File']))
if not os.path.isfile(tempfiletowrite):
if not os.path.exists(os.path.abspath(os.path.expanduser(BaseConfiguration['Directory']))):
os.makedirs(os.path.abspath(os.path.expanduser(BaseConfiguration['Directory'])))
tempconfigtowrite="{'Directory':'~/.config/menugenerator/',\n'Icon':{'Size':None,'Theme':None,'Extensions':['png','svg','xpm'],'Cache':'~/.config/menugenerator/cache','Clear':False},\n'Categories':[{'name':'Accessories','display':'Accessori', 'icon': None},{'name':'Graphics','display':'Grafica', 'icon': None},{'name':'Internet','display':'Internet', 'icon': None},{'name':'Multimedia','display':'Multimedia', 'icon': None},{'name':'Office','display':'Ufficio', 'icon': None},{'name':'System','display':'Sistema', 'icon': None}],\n'Menu':{'DefaultVM' : 'fluxbox','File':'/etc/xdg/menus/lxde-applications.menu','UseGenericName':False,'UseIcon':True,'Piped':True, 'Output':None}}\n"
with open(tempfiletowrite,"w") as myconfigurationfile:
myconfigurationfile.write(tempconfigtowrite)
def BuildRunning(tempconfigfile = None):
if tempconfigfile is None:
if os.path.isabs(os.path.expanduser(BaseConfiguration['File'])):
tempconfigfile = BaseConfiguration['File']
else:
tempconfigfile = os.path.abspath(os.path.join(os.path.expanduser(BaseConfiguration['Directory']),BaseConfiguration['File']))
if os.path.isfile(tempconfigfile):
with open(tempconfigfile) as myconfigurationfile:
tempconfiguration=eval(myconfigurationfile.read())
CurrentRunning['Options']['File']['Configuration']=tempconfigfile
if os.path.isabs(os.path.expanduser(tempconfiguration['Menu']['File'])):
CurrentRunning['Options']['File']['Menu']=tempconfiguration['Menu']['File']
else:
CurrentRunning['Options']['File']['Menu']=os.path.abspath(os.path.join(os.path.exanduser(tempconfiguration['Directory']),tempconfiguration['Menu']['File']))
CurrentRunning['Options']['Menu']['Syntax']=tempconfiguration['Menu']['DefaultVM']
CurrentRunning['Options']['Menu']['UseGenericName'] = tempconfiguration['Menu']['UseGenericName']
CurrentRunning['Options']['Icons']['Theme'] = tempconfiguration['Icon']['Theme']
CurrentRunning['Options']['Icons']['Size'] = tempconfiguration['Icon']['Size']
CurrentRunning['Options']['Icons']['Extensions'] = tempconfiguration['Icon']['Extensions']
CurrentRunning['Options']['Icons']['Use']=tempconfiguration['Menu']['UseIcon']
CurrentRunning['Options']['Menu']['Piped']=tempconfiguration['Menu']['Piped']
if tempconfiguration['Menu']['Output'] != None:
if os.path.isabs(os.path.expanduser(tempconfiguration['Menu']['Output'])):
CurrentRunning['Options']['File']['Output']=os.path.abspath(os.path.expanduser(tempconfiguration['Menu']['Output']))
else:
CurrentRunning['Options']['File']['Output']=os.path.abspath(os.path.join(os.path.exanduser(tempconfiguration['Directory']),tempconfiguration['Menu']['Output']))
else:
CurrentRunning['Options']['File']['Output']=None
if os.path.isabs(os.path.expanduser(tempconfiguration['Icon']['Cache'])):
CurrentRunning['Options']['File']['Cache']=os.path.abspath(os.path.expanduser(tempconfiguration['Icon']['Cache']))
else:
CurrentRunning['Options']['File']['Cache']=os.path.abspath(os.path.join(os.path.exanduser(tempconfiguration['Directory']),tempconfiguration['Icon']['Cache']))
CurrentRunning['Options']['Icons']['ClearCache']=tempconfiguration['Icon']['Clear']
tempicon=dict()
tempname=dict()
temporder=list()
for objectcategory in tempconfiguration['Categories']:
temporder.append(objectcategory['name'])
if objectcategory['icon'] is not None:
tempicon[objectcategory['name']] = objectcategory['icon']
tempname[objectcategory['name']]=objectcategory['display']
CurrentRunning['Options']['Categories']['Order']=temporder
CurrentRunning['Options']['Categories']['Icons']=tempicon
CurrentRunning['Options']['Categories']['Names']=tempname
CurrentRunning['Menu']=dict()
def ParseMenu(tempobjectmenu = None):
if tempobjectmenu is None:
if os.path.isabs(os.path.expanduser(CurrentRunning['Options']['File']['Menu'])):
tempobjectmenu = xdg.Menu.parse(os.path.abspath(os.path.expanduser(CurrentRunning['Options']['File']['Menu'])))
else:
tempobjectmenu = xdg.Menu.parse(os.path.abspath(os.path.expanduser(os.path.join(BaseConfiguration['Directory'],BaseConfiguration['File']))))
ParseMenu(tempobjectmenu)
else:
for tempobjectmenuentry in tempobjectmenu.getEntries():
if isinstance(tempobjectmenuentry, xdg.Menu.Menu):
CurrentRunning['Menu'][tempobjectmenuentry.getPath()]=list()
tempicon = ''
if CurrentRunning['Options']['Icons']['Use']:
if tempobjectmenuentry.getPath() not in CurrentRunning['Options']['Categories']['Icons']:
if tempobjectmenuentry.getIcon() != '':
tempiconname=tempobjectmenuentry.getIcon()
else:
tempiconname=tempobjectmenuentry.getPath().lower()
tempicon = ObtainIcon(tempiconname,CurrentRunning['Options']['Icons']['Size'],CurrentRunning['Options']['Icons']['Theme'],CurrentRunning['Options']['Icons']['Extensions'],True)
else:
tempicon = ObtainIcon(CurrentRunning['Options']['Categories']['Icons'][tempobjectmenuentry.getPath()],CurrentRunning['Options']['Icons']['Size'],CurrentRunning['Options']['Icons']['Theme'],CurrentRunning['Options']['Icons']['Extensions'])
CurrentRunning['Options']['Categories']['Icons'][tempobjectmenuentry.getPath()] = tempicon
ParseMenu(tempobjectmenuentry)
elif isinstance(tempobjectmenuentry, xdg.Menu.MenuEntry):
tempobjectcategory=CurrentRunning['Menu'][tempobjectmenu.getPath()]
tempobjectcategory.append(ParseApplication(tempobjectmenuentry))
CurrentRunning['Menu'][tempobjectmenu.getPath()]=tempobjectcategory
def ParseApplication(tempobjectmenuentry):
Result={'name':'', 'desc':'', 'exec':'','icon':''}
tempobjectapplication = xdg.DesktopEntry.DesktopEntry(tempobjectmenuentry.DesktopEntry.getFileName())
if CurrentRunning['Options']['Icons']['Use']:
tempapplicationicon = ObtainIcon(tempobjectapplication.getIcon(),CurrentRunning['Options']['Icons']['Size'],CurrentRunning['Options']['Icons']['Theme'],CurrentRunning['Options']['Icons']['Extensions'])
Result['icon'] = tempapplicationicon
if CurrentRunning['Options']['Menu']['UseGenericName']:
Result['name']=tempobjectapplication.getGenericName()
else:
Result['name']=tempobjectapplication.getName()
Result['desc'] = tempobjectapplication.getComment()
Result['exec']=tempobjectapplication.getExec().split('%')[0]
return Result
def ObtainIcon(tempiconname,tempiconsize=None,tempicontheme=None,tempextensions=['png', 'svg', 'xpm'], searchforcategory=False):
if searchforcategory:
result = ObtainIcon('applications-'+tempiconname,tempiconsize,tempicontheme,tempextensions)
if result == '':
result = ObtainIcon('system-'+tempiconname,tempiconsize,tempicontheme,tempextensions)
return result
if os.path.isabs(tempiconname):
return tempiconname
result = xdg.IconTheme.getIconPath(tempiconname,tempiconsize,tempicontheme,tempextensions)
if result is None:
return ''
else:
return result
# Add support for SVG icon in fluxbox
def clearXmlnsInvalidCode(src,dst):
import re
with open(src, 'r') as readfile:
data = readfile.read()
k = re.findall('xmlns:(.*)=(\".* +.*\")',data, re.MULTILINE)
if k:
for record in k:
data = data.replace('xmlns:'+record[0]+'='+record[1],'xmlns:'+record[0]+'='+record[1].replace(" ",""))
with open(dst, 'w') as writefile:
writefile.write(data)
return True
return False
def clearSvgInvalidCode(src,dst,clear=True):
src=os.path.abspath(os.path.expanduser(src))
dst=os.path.abspath(os.path.expanduser(dst))
import xml.dom.minidom
try:
doc = xml.dom.minidom.parse(src)
except:
# errore xmlns
if clear and clearXmlnsInvalidCode(src,dst):
return clearSvgInvalidCode(dst,dst,False)
else:
return False
lineargradelems=doc.getElementsByTagName('linearGradient')
for elem in lineargradelems :
if elem.hasChildNodes() != True:
elem.parentNode.removeChild(elem)
try:
with open(dst, "w") as f:
doc.writexml(f)
return True
except:
return False
def convertSvgIcon(svgpath, clear=True):
svgpath=os.path.abspath(os.path.expanduser(svgpath))
if not os.path.exists(os.path.abspath(os.path.expanduser(CurrentRunning['Options']['File']['Cache']))):
os.makedirs(os.path.abspath(os.path.expanduser(CurrentRunning['Options']['File']['Cache'])))
import cairosvg
filename = os.path.splitext(os.path.basename(svgpath))[0]
newname = os.path.abspath(os.path.expanduser(CurrentRunning['Options']['File']['Cache']+ "/" + filename + ".png"))
exists = os.path.isfile(newname)
if exists:
if clear and CurrentRunning['Options']['Icons']['ClearCache'] :
os.remove(newname)
else:
return newname
try :
cairosvg.svg2png(url=svgpath, write_to=newname)
except Exception as e :
newname = svgpath
if clear and clearSvgInvalidCode(svgpath,CurrentRunning['Options']['File']['Cache']+ "/" + filename + ".svg") :
newname = convertSvgIcon(CurrentRunning['Options']['File']['Cache']+ "/" + filename + ".svg",False)
return newname
### Menu Syntaxes ###
def CreateFluxboxMenu():
result = ""
for tempcategoryname in CurrentRunning['Options']['Categories']['Order']:
if tempcategoryname in CurrentRunning['Options']['Categories']['Names']:
result += "[submenu] ("+CurrentRunning['Options']['Categories']['Names'][tempcategoryname]+") "
if tempcategoryname in CurrentRunning['Options']['Categories']['Icons']:
if (CurrentRunning['Options']['Categories']['Icons'][tempcategoryname]).endswith('.svg'):
CurrentRunning['Options']['Categories']['Icons'][tempcategoryname] = convertSvgIcon(CurrentRunning['Options']['Categories']['Icons'][tempcategoryname])
result +=" <"+CurrentRunning['Options']['Categories']['Icons'][tempcategoryname]+">"
result += "\n"
if tempcategoryname in CurrentRunning['Menu']:
for tempobjectapp in CurrentRunning['Menu'][tempcategoryname]:
result += "\t[exec] ("+tempobjectapp['name']+") {"+tempobjectapp['exec']+"} "
if tempobjectapp['icon'] != '':
if (tempobjectapp['icon']).endswith('.svg'):
tempobjectapp['icon'] = convertSvgIcon(tempobjectapp['icon'])
result +=" <"+tempobjectapp['icon']+">"
result +="\n"
result += "[end]\n"
return result
def CreateJWMMenu():
result = '<?xml version="1.0"?>\n<JWM>\n'
for tempcategoryname in CurrentRunning['Options']['Categories']['Order']:
if tempcategoryname in CurrentRunning['Options']['Categories']['Names']:
result += '<Menu label="'+CurrentRunning['Options']['Categories']['Names'][tempcategoryname]+'"'
if tempcategoryname in CurrentRunning['Options']['Categories']['Icons']:
result +=' icon="'+CurrentRunning['Options']['Categories']['Icons'][tempcategoryname]+'"'
result += ">\n"
if tempcategoryname in CurrentRunning['Menu']:
for tempobjectapp in CurrentRunning['Menu'][tempcategoryname]:
result += '\t<Program label="'+tempobjectapp['name']+'" '
if tempobjectapp['icon'] != '':
result +=' icon="'+tempobjectapp['icon']+'"'
result +='>'+tempobjectapp['exec']+'</Program>\n'
result += "</Menu>\n"
result +="</JWM>\n"
return result
def CreateOpenboxMenu():
result = '<?xml version="1.0" encoding="UTF-8"?>\n<openbox_pipe_menu>\n'
for tempcategoryname in CurrentRunning['Options']['Categories']['Order']:
if tempcategoryname in CurrentRunning['Options']['Categories']['Names']:
result += '<menu id="'+tempcategoryname.lower()+'" label="'+CurrentRunning['Options']['Categories']['Names'][tempcategoryname]+'"'
if tempcategoryname in CurrentRunning['Options']['Categories']['Icons']:
result +=' icon="'+CurrentRunning['Options']['Categories']['Icons'][tempcategoryname]+'"'
result += ">\n"
if tempcategoryname in CurrentRunning['Menu']:
for tempobjectapp in CurrentRunning['Menu'][tempcategoryname]:
result += '\t<item label="'+tempobjectapp['name']+'" '
if tempobjectapp['icon'] != '':
result +=' icon="'+tempobjectapp['icon']+'"'
result +='><action name="Execute"><command>'+tempobjectapp['exec']+'</command><startupnotify><enabled>yes</enabled></startupnotify></action></item>\n'
result += "</menu>\n"
result +="</openbox_pipe_menu>\n"
return result
def PrintHelp():
print("Usage: menugenerator [options]\n")
print("Options:")
print(" -h , --help: print this message")
print(" -v , --version: print current version")
print(" -d , --dumpconfig: print the configuration file used for process")
print(" -g , --generate: generate the menu with default options")
print(" -i , --icon: use icon in menu")
print(" -c , --clear: clear the icon cache (only for FluxBox png from svg icon)")
print(" -p , --pipe: print the generated menu to stdout")
print(" -o , --options: use these options")
print(" -f , --file=<filename>: save the generated menu to file")
print(" -w <windowmanager> , --wm=<windowmanager>: generate the menu for the window manager specified\n")
print("Supported Window Manager - Value to use:")
print("Fluxbox: fluxbox")
print("JWM: jwm")
print("Openbox: openbox")
print("\nVersion:"+ CurrentVersion + "\n\nAuthor: Black_Codec\nSite: <http://www.icapito.it/>\nRepository: <https://github.com/BlackCodec/MenuGenerator>")
### BEGIN RUN ###
def main(argv):
FirstRun()
BuildRunning()
try:
opts, args = getopt.getopt(argv,"dgihpcvwf:o:",["version","dumpconfig","generate","icon","help","pipe","clear","wm=","file=","options="])
except getopt.GetoptError as e:
print("[ERROR] "+ e.args[0]+"\n")
PrintHelp();
sys.exit(1)
for opt, arg in opts:
if opt in ("-h", "--help"):
PrintHelp()
sys.exit(0)
elif opt in ("-v", "--version"):
print("Openbox: openbox")
print("\nVersion:"+ CurrentVersion + "\n\nAuthor: Black_Codec\nSite: <http://www.icapito.it/>\nRepository: <https://github.com/BlackCodec/MenuGenerator>")
sys.exit(0)
elif opt in ("-g", "--generate"):
CurrentRunning['Options']['Menu']['Create'] = True
elif opt in ("-i", "--icon"):
CurrentRunning['Options']['Menu']['Create'] = True
CurrentRunning['Options']['Icons']['Use'] = True
elif opt in ("-p" , "--pipe"):
CurrentRunning['Options']['Menu']['Create'] = True
CurrentRunning['Options']['Menu']['Piped'] = True
elif opt in ("-c" , "--clear"):
CurrentRunning['Options']['Icons']['ClearCache'] = True
elif opt in ("-w", "--wm"):
CurrentRunning['Options']['Menu']['Create'] = True
CurrentRunning['Options']['Menu']['Syntax'] = arg.lower()
elif opt in ("-d", "--dumpconfig"):
CurrentRunning['Options']['Menu']['Debug'] = True
elif opt in ("-f", "--file"):
CurrentRunning['Options']['Menu']['Create'] = True
CurrentRunning['Options']['Menu']['Piped'] = False
CurrentRunning['Options']['File']['Output'] = arg.lower()
elif opt in ("-o", "--options"):
BuildRunning(arg.lower())
else:
PrintHelp()
sys.exit(0)
# End params
if CurrentRunning['Options']['Menu']['Debug']:
import pprint
pprint.pprint(CurrentRunning)
sys.exit(0)
if CurrentRunning['Options']['Menu']['Create']:
tempmenu=''
ParseMenu()
if CurrentRunning['Options']['Menu']['Syntax'] == "fluxbox":
tempmenu = CreateFluxboxMenu()
elif CurrentRunning['Options']['Menu']['Syntax'] == "jwm":
tempmenu = CreateJWMMenu()
elif CurrentRunning['Options']['Menu']['Syntax'] == "openbox":
tempmenu = CreateOpenboxMenu()
if CurrentRunning['Options']['Menu']['Piped']:
print(tempmenu)
elif CurrentRunning['Options']['File']['Output'] != None:
outfile = open(CurrentRunning['Options']['File']['Output'],"w")
outfile.write(tempmenu)
outfile.close()
sys.exit(0)
if __name__ == "__main__":
main(sys.argv[1:])