Debian Codegraph @

bin/fvwm-menu-desktop.in

raw ◀ ▶
Source reconstructed at patch state 1 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 #!@PYTHON@
2
3 # Modification History
4
5 # Changed on 06/01/20 by Dominique Michel:
6 # - Fix converting of multi-images icon files;
7 # use the first one.
8
9 # Changed on 18/03/19 by Jaimos Skriletz:
10 # - Updated script for and require Python 3.
11 # - Drop support for Python 2.
12 # - Added support for xdg.Menu.Separator.
13 # - Added option --term-cmd to state the terminal emulator command
14 # to use with Terminal=True .desktop entries. Default: xterm -e
15
16 # Changed on 16/12/31 by Jaimos Skriletz:
17 # - Added check for FVWM_USERDIR env variable.
18 # - Added check for python-xdg module to print less errors if not found.
19 # - Added option -e/--menu-error to output phython-xdg not found as
20 # a menu for the default-config.
21
22 # Changed on 16/10/27 by Jaimos Skrietz:
23 # - Renamed default menu to XDGMenu and changed the name of the
24 # FvwmForm to FvwmForm-XDGMenu-Config
25 # - Modified the FvwmForm and added the abilty to load defaults from
26 # the Form's data file.
27 # - Changed default to generate menu titles. Disable with --without-titles
28 # - The top level menu now has two additional items:
29 # 'Regenerate' - Regenerates menu.
30 # 'Configure' - Opens up FvwmForm-XDGMenu-Config.
31 # - Added --regen-cmd "CMD" for a fvwm CMD to use on the Regenerate item.
32 # Default: PipeRead `fvwm-menu-desktop`
33 # - Added --include-items [config|regenerate|both|none] option
34 # to control if the additional items are included in the menu.
35 # - Added --dynamic option to be used with dynamic menus.
36 # - Added --all-menus option to generate all menus and not try to determine
37 # which one is best
38 # - Changed default behavior to include menu titles.
39 # - Added new option --without-titles
40
41 # Changed on 25/02/14 by Thomas Funk:
42 # - Converting of icons always to png
43
44 # Changed on 06/10/13 by Thomas Funk:
45 # Some Bugfixes:
46 # - DecodeEncodeErrors in menu names
47 # - no output appears with 'fvwm-menu-desktop --get-menus all|desktop'
48 # - No entry "Regenerate XDG menu(s)" appears with
49 # 'fvwm-menu-desktop --insert-in-menu MenuRoot'
50 # - exchange all tabs with spaces to prevent indention errors
51 # - add two new options: --app-icon --dir-icon
52 # to handle default icons for not available app/dir icons
53 # - fix bug in convert icon routine that background of svg icons are
54 # transparent
55
56 # Changed on 15/06/13 by Thomas Funk:
57 # support for python-xdg > 0.19.
58 # add gettext localization.
59
60 # Changed on 10/01/12 by Thomas Funk:
61 # Unicode support.
62
63 # Changed on 01/26/12 by Dan Espen (dane):
64 # Make compatible with fvwm-menu-desktop.
65 # Restored DestroyMenu, needed for reload menus.
66 # Remove bug, was printing iconpath on converted icons
67 # Replace obsolete optparse, use getopt instead
68 # Change from command line arg for applications.menu
69 # change to using ?$XDG_MENU_PREFIX or theme? fixme
70 # - use "Exec exec" for all commands, remove option.
71
72 # fixme, fix documentation, FvwmForm-Desktop, usage prompt is wrong
73 # change, mini icons are enabled by default.
74 # there are rescalable icons.
75
76 # Author: Piotr Zielinski (http://www.cl.cam.ac.uk/~pz215/)
77 # Licence: GPL 2
78 # Date: 03.12.2005
79
80 # This script takes names of menu files conforming to the XDG Desktop
81 # Menu Specification, and outputs their FVWM equivalents to the
82 # standard output.
83 #
84 # http://standards.freedesktop.org/menu-spec/latest/
85
86 # This script requires the python-xdg module, which in Debian can be
87 # installed by typing
88 #
89 # apt-get install python3-xdg
90 #
91 # On Fedora, python-xdg is installed by default.
92
93 import sys
94 import getopt
95 import os.path
96 import os
97 import fnmatch
98 import time
99 import shutil
100
101 # Test for python-xdg
102 try:
103 import xdg.Menu
104 except ImportError:
105 xdg_import_error = True
106 else:
107 xdg_import_error = False
108 import xdg.IconTheme
109 import xdg.Locale
110 from xdg.DesktopEntry import *
111 from xdg.BaseDirectory import *
112
113 class BaseIconScaleTool(object):
114 size = 32
115 icon_dir = ''
116 enable_icon = True
117
118 def __init__(self, filename):
119 self.filename = filename
120
121 def _do_check(self):
122 sys.stderr.write('Cannot find ImageMagick binaries or PIL module. Skipping scaling icon %s\n' % filename)
123 return True
124
125 def check_size(self):
126 if self.filename.endswith('.svg'):
127 return False
128 try:
129 return self._do_check()
130 except:
131 # Always try to convert if check_size() fails.
132 # Worst case convert() would fail and ignore the icon.
133 return False
134
135 def convert(self, theme_changed):
136 # FVWM knows how to render SVGs
137 if self.filename.endswith('.svg'):
138 return '{0}:{1}x{1}'.format(self.filename, self.size)
139
140 output = self._output_path()
141
142 if theme_changed or not os.path.isfile(output) or os.path.getmtime(self.filename) > os.path.getmtime(output):
143 try:
144 self._do_convert(output)
145 except:
146 sys.stderr.write('Fail to convert %s.\n' % self.filename)
147 return None
148
149 return output
150
151 def _output_path(self):
152 if not os.path.isdir(os.path.expanduser(self.icon_dir)):
153 os.makedirs(os.path.expanduser(self.icon_dir))
154 return os.path.join(os.path.expanduser(self.icon_dir),
155 "%ix%i-" % (self.size, self.size) +
156 os.path.basename(self.filename))
157
158 class ImageMagickIconScaleTool(BaseIconScaleTool):
159 def _do_check(self):
160 with os.popen("identify -format %%w '%s'" % self.filename, 'r') as p:
161 return int(p.read()) == self.size
162
163 def _do_convert(self, output):
164 if os.system("convert '%s'[0] -resize %i '%s'"% (self.filename, self.size, output)) != 0:
165 raise ValueError('convert process return non-zero status code')
166
167 class PILIconScaleTool(BaseIconScaleTool):
168 def _do_check(self):
169 with PIL.Image.open(self.filename) as f:
170 return f.size[0] == self.size
171
172 def _do_convert(self, output):
173 with PIL.Image.open(self.filename) as f:
174 f.thumbnail((self.size, self.size))
175 f.save(output, 'PNG')
176
177 IconScaleTool = BaseIconScaleTool
178
179 try:
180 import PIL.Image
181 IconScaleTool = PILIconScaleTool
182 except:
183 if shutil.which('convert') and shutil.which('identify'):
184 IconScaleTool = ImageMagickIconScaleTool
185 else:
186 sys.stderr.write('No image conversion tools found, using original icon size instead.\n')
187
188 # Main Function
189 def main ():
190
191 description = """
192 Generate Fvwm Menu from xdg files.
193 Standard output is a series Fvwm commands."""
194
195 obs_args=['check-app',
196 'enable-style',
197 'enable-tran-style',
198 'fvwm-icons',
199 'kde_config',
200 'mini-icon-path',
201 'merge-user-menu',
202 'su_gui',
203 'utf8',
204 'wm-icons']
205 dashed_obs_args=[]
206 for a in obs_args :
207 dashed_obs_args.append('--'+a)
208
209 obs_parms=['check-icons',
210 'check-mini-icon',
211 'destroy-type',
212 'dir',
213 'icon-app',
214 'icon-folder',
215 'icon-style',
216 'icon-title',
217 'icon-toptitle',
218 'icons-path',
219 'lang',
220 'menu-style',
221 'name',
222 'png-icons-path',
223 'submenu-name-prefix',
224 'time-limit',
225 'tran-icons-path',
226 'tran-mini-icons-path',
227 'type',
228 'uniconv-exec',
229 'uniconv',
230 'xterm']
231 equaled_obs_parms=[]
232 for a in obs_parms :
233 equaled_obs_parms.append(a+'=')
234 dashed_obs_parms=[]
235 for a in obs_parms :
236 dashed_obs_parms.append('--'+a)
237
238 try:
239 opts, args = getopt.getopt(sys.argv[1:], "hs:t:vwe",
240 ["help", "verbose", "enable-mini-icons", "with-titles", "without-titles", "version",
241 "desktop=", "size=", "theme=", "install-prefix=", "menu-type=", "regen-cmd=", "term-cmd=",
242 "title=", "get-menus=", "set-menus=", "insert-in-menu=", "mini-icon-dir=", "menu-error",
243 "app-icon=", "dir-icon=", "include-items=", "dynamic", "all-menus"]+obs_args+equaled_obs_parms)
244 except getopt.GetoptError as err:
245 # print help information and exit:
246 print(str(err)) # will print something like "option -a not recognized"
247 print(usage)
248 sys.exit(2)
249 global verbose, size, current_theme, icon_dir, top, install_prefix, menu_type, menu_list_length, term_cmd
250 global with_titles, get_menus, timestamp, set_menus, printmode, insert_in_menu, previous_theme
251 global default_app_icon, default_dir_icon, include_items, config_menus, regen_cmd, dynamic_menu, build_all_menus
252 version = "2.4"
253 verbose = False
254 force = False
255 desktop=''
256 size=24
257 current_theme='gnome'
258 previous_theme='gnome'
259 icon_dir="~/.fvwm/icons"
260 top='XDGMenu'
261 insert_in_menu = False
262 install_prefix = ''
263 menu_type = ''
264 with_titles = True
265 menu_list_length = 0
266 get_menus = ''
267 printmode = True
268 set_menus = []
269 build_all_menus = False
270 config_menus = []
271 default_app_icon = "gnome-applications"
272 default_dir_icon = "gnome-fs-directory"
273 include_items = 'both'
274 regen_cmd = 'PipeRead `fvwm-menu-desktop`'
275 dynamic_menu = False
276 menu_error = False
277 term_cmd = "x-terminal-emulator -e" # Debian Policy change xterm to x-terminal-emulator
278
279 # Loads config options from $FVWM_USERDIR/.FvwmForm-XDGMenu-Config
280 if "FVWM_USERDIR" in os.environ:
281 config_file = "%s/.FvwmForm-XDGMenu-Config" % os.environ['FVWM_USERDIR']
282 else:
283 config_file = "%s/.fvwm/.FvwmForm-XDGMenu-Config" % os.environ['HOME']
284 if os.path.isfile(config_file):
285 fvwmform_config = open(config_file, "r", errors="ignore")
286
287 for l in fvwmform_config:
288 o = l.split()
289 if len(o)>2 and o[0] != '#':
290 if o[1][:3] == 'MEN' and o[2] == 'on':
291 config_menus.append(o[1][3:])
292 if o[1] == 'IconsOn' and o[2] == 'on':
293 force = True
294 elif o[1] == 'Size':
295 size = int(o[2])
296 elif o[1] == 'TitlesOn' and o[2] == 'on':
297 with_titles = True
298 elif o[1] == 'Theme':
299 current_theme = o[2]
300 elif o[1] == 'Title':
301 top = o[2]
302 elif o[1] == 'InsertInto':
303 top = o[2]
304 insert_in_menu = True
305 elif o[1] == 'Installprefix':
306 install_prefix = o[2]
307 elif o[1] == 'IconDir':
308 icon_dir = o[2]
309 elif o[1] == 'DirIcon':
310 default_dir_icon = o[2]
311 elif o[1] == 'AppIcon':
312 default_app_icon = o[2]
313 elif o[1] == 'IncludeConfig' and o[2] == 'on':
314 include_items = "config"
315 elif o[1] == 'IncludeRegen' and o[2] == 'on':
316 include_items = "regenerate"
317 elif o[1] == 'IncludeBoth' and o[2] == 'on':
318 include_items = "both"
319 elif o[1] == 'IncludeNone' and o[2] == 'on':
320 include_items = "none"
321 elif o[1] == 'TermCmd':
322 term_cmd = " ".join(o[2:])
323 fvwmform_config.close()
324
325 for o, a in opts:
326 if o in ("-v", "--verbose"):
327 verbose = True
328 if os.path.isfile(config_file):
329 vprint("Defaults loaded from %s\n" % config_file)
330 else:
331 vprint("Config file not found: %s\nUsing built-in defaults.\n" % config_file)
332 elif o in ("-h", "--help") :
333 print(usage)
334 sys.exit()
335 elif o in ("--version") :
336 print("fvwm-menu-desktop version " + version)
337 sys.exit()
338 elif o in ("-e", "--menu-error") :
339 menu_error = True
340 elif o in ("--enable-mini-icons") :
341 force=True
342 elif o in ("--insert-in-menu") :
343 top=a
344 insert_in_menu = True
345 elif o in ("--desktop") :
346 desktop=a
347 elif o in ("-t", "--title") :
348 top=a
349 elif o in ("--get-menus") :
350 if a == 'all' or a == 'desktop' :
351 get_menus=a
352 printmode = False
353 else :
354 sys.stderr.write( "--get-menus argument must be 'all' or 'desktop' found "+a )
355 print(usage)
356 sys.exit(1)
357 elif o in ("-s","--size") :
358 size = int(a)
359 elif o in ("--mini-icon-dir") :
360 icon_dir = a
361 elif o in ("--set-menus") :
362 if a[-1] == ' ':
363 a = a[:-1]
364 set_menus=a.split(' ')
365 elif o in ("--install-prefix") :
366 if a and not os.path.isabs(a):
367 assert False, "install-prefix must be an absolute path"
368 # add trailing slash if not there already
369 if not a[-1] == '/' : # trailing slash
370 a=a + '/'
371 install_prefix = a
372 elif o in ("--theme") :
373 current_theme = a
374 elif o in ("--menu-type") :
375 menu_type = a
376 elif o in ("-w", "--with-titles") :
377 with_titles = True
378 elif o in ("--without-titles") :
379 with_titles = False
380 elif o in ("--app-icon") :
381 default_app_icon = a
382 elif o in ("--dir-icon") :
383 default_dir_icon = a
384 elif o in ("--include-items") :
385 if a in ("both", "none", "config", "regenerate") :
386 include_items = a
387 else:
388 sys.stderr.write( "--include-items argument must be 'config', 'regenerate', 'both' or 'none' found "+a )
389 print(usage)
390 sys.exit(1)
391 elif o in ("--regen-cmd") :
392 regen_cmd = a
393 elif o in ("--term-cmd") :
394 term_cmd = a
395 elif o in ("--dynamic") :
396 dynamic_menu = True
397 elif o in ("--all-menus") :
398 build_all_menus = True
399 elif o in (str(dashed_obs_args+dashed_obs_parms)) :
400 # Ignore
401 sys.stderr.write( "Warning: Arg "+o+" is obsolete and ignored\n" )
402 else:
403 assert False, "unhandled option"
404
405 # Exit if python-xdg not found
406 if xdg_import_error:
407 if menu_error:
408 printtext('DestroyMenu "%s"' % top)
409 printtext('AddToMenu "%s" "%s" Title' % (top, top))
410 printtext('+ "$[gt.Error]: python-xdg $[gt.not found]" Nop')
411 printtext('+ "" Nop')
412 printtext('+ "$[gt.Regenerate]" PipeRead `fvwm-menu-desktop -e`')
413 else:
414 sys.stderr.write('Python module python-xdg not found.')
415 sys.exit(1)
416
417 BaseIconScaleTool.size = size
418 BaseIconScaleTool.icon_dir = icon_dir
419 BaseIconScaleTool.enable_icon = force
420
421 timestamp = time.time()
422
423 if len(set_menus) == 0:
424 xdg_menu_prefix = ((os.environ['XDG_MENU_PREFIX'] if 'XDG_MENU_PREFIX' in os.environ else ''))
425
426 # First check if no user presettings made
427 if desktop == '':
428 # check if $XDG_MENU_PREFIX is set
429 if not xdg_menu_prefix == '':
430 desktop = xdg_menu_prefix.replace('-', '').lower()
431
432 vprint("Parameters for creating menu list:")
433 vprint(" XDG_MENU_PREFIX: \'%s\'" %xdg_menu_prefix)
434 vprint(" --install-prefix: \'%s\'" %install_prefix)
435 vprint(" --desktop: \'%s\'" %desktop)
436 vprint(" --menu-type: \'%s\'" %menu_type)
437
438 vprint("\nStart search ...")
439 menulist, desktop_temp = getmenulist(desktop, menu_type)
440 if not desktop_temp == '':
441 desktop = desktop_temp
442
443 else:
444 menulist = set_menus
445
446 vprint(" Menu list: %s\n" %menulist)
447 menu_list_length = len(menulist)
448 desktop_entries = []
449
450 if menu_list_length == 0:
451 if not desktop == '':
452 desktop = desktop + '-'
453 if menu_error:
454 printtext('DestroyMenu "%s"' % top)
455 printtext('AddToMenu "%s" "%s" Title' % (top, top))
456 printtext('+ "$[gt.Error]: $[gt.No menus found]" Nop')
457 printtext('+ "" Nop')
458 printtext('+ "$[gt.Regenerate]" PipeRead `fvwm-menu-desktop -e`')
459 else:
460 sys.stderr.write(install_prefix+desktop+menu_type+".menu not available on this system. Exiting...\n")
461 sys.exit(1)
462 else:
463 # set previous_theme if <icon_dir>/.theme exist
464 if os.path.exists(os.path.join(os.path.expanduser(icon_dir), ".theme")):
465 previous_theme = next(open(os.path.join(os.path.expanduser(icon_dir), ".theme"), 'r')).replace('\n', '')
466 vprint(" Previous used theme: %s" %previous_theme)
467 vprint(" Current used theme: %s\n" %current_theme)
468
469 sys.stderr.flush()
470 parsemenus(menulist, desktop, desktop_entries)
471
472 # write current_theme to <icon_dir>/.theme if --enable-mini-icons and printmode is set
473 if printmode and force:
474 fh = open(os.path.join(os.path.expanduser(icon_dir), ".theme"), "w")
475 fh.write(current_theme)
476 fh.close()
477
478 for ent in desktop_entries:
479 style_id = ent.getStartupWMClass()
480 if not style_id:
481 style_id = ent.getIcon()
482 if style_id and ent.getIcon():
483 sys.stdout.write('Style "{}" MiniIcon "{}"\n'.format(style_id, geticonfile(ent.getIcon())))
484
485 sys.stdout.flush()
486 vprint("\nProcess took " + str(time.time()-timestamp) + " seconds")
487
488 def getmenulist(desktop, menu_type):
489 menudict = {}
490 config_dirs = []
491 if not install_prefix == '':
492 config_dirs = [install_prefix]
493 else:
494 config_dirs = xdg_config_dirs # xdg_config_dirs is a built-in list from python-xdg
495
496 found_menus = 0
497 for dir in config_dirs:
498 if install_prefix == '':
499 dir = os.path.join(dir, 'menus')
500 # skipping all paths which not available
501 if os.path.exists(dir):
502 filelist = set([])
503 dir_list = os.listdir(dir)
504 #pattern = '*'+desktop+'*'+menu_type+'*.menu'
505 # Always find all menus
506 pattern = '*.menu'
507 for filename in fnmatch.filter(dir_list, pattern):
508 filelist.add(filename)
509
510 # the menudict dictionary has a unsorted list (set) for the values.
511 # set is easier to use then a list for removing items
512 menudict[dir] = filelist
513 found_menus += len(filelist)
514 vprint(" found in %s: %s" %(dir, list(filelist)))
515
516 desktop_dict = {}
517 if not found_menus == 0:
518 all_menus = []
519 # If install_prefix is set /etc/xdg/menus is not used,
520 # instead generate all menus from only this location.
521 if install_prefix == "":
522 # remove all menus in /etc/xdg/menus if exist in user dir
523 for path in list(menudict.keys()):
524 if not path == '/etc/xdg/menus':
525 if path == os.path.join(os.getenv("HOME"), '.config/menus'):
526 menudict['/etc/xdg/menus'] = menudict['/etc/xdg/menus'] - menudict[path]
527 #else:
528 # menudict[path] = menudict[path] - menudict['/etc/xdg/menus']
529 for menu in list(menudict[path]):
530 all_menus.append(path + '/' + menu)
531
532 if not menudict['/etc/xdg/menus'] == 0:
533 for menu in list(menudict['/etc/xdg/menus']):
534 all_menus.append('/etc/xdg/menus/' + menu)
535
536 else:
537 for path in list(menudict.keys()):
538 for menu in list(menudict[path]):
539 all_menus.append(path + menu)
540
541 if get_menus == 'all' or (build_all_menus and desktop == '' and menu_type == ''):
542 return all_menus, ''
543
544 # get menus selected in config file
545 if len(config_menus) > 0:
546 config_menulist = []
547 for i in config_menus:
548 for j in all_menus:
549 if fnmatch.fnmatch( j, "*%s.menu" % i ):
550 config_menulist.append(j)
551 vprint("\n Selected menus from config file: %s " % list(config_menulist))
552 # Use config file if --dekstop not set
553 if len(config_menulist) == 0:
554 vprint(" No menus in config found. Using all menus.")
555 elif desktop == '' and menu_type == '':
556 vprint(" Using menus from config file.")
557 return config_menulist, ''
558 else:
559 vprint(" Ignoring menus in config file, due to --desktop or --menu-type.")
560
561 # filter --desktop and --menu-type options
562 if desktop != '' or menu_type != '':
563 vprint("\n Filtering menus according to --desktop %s and --menu-type %s" % (desktop, menu_type) )
564 pattern = '*'+desktop+'*'+menu_type+'*'
565 for path in list(menudict.keys()):
566 for menu in list(menudict[path]):
567 if not fnmatch.fnmatch( menu, pattern ):
568 menudict[path].remove(menu)
569 if menudict[path] == set([]):
570 del menudict[path]
571 if menudict == {}:
572 sys.stderr.write("No menus found matching --desktop %s and --menu-type %s. Exiting...\n" % (desktop, menu_type) )
573 sys.exit(1)
574
575 vprint("\n Finding best menu in Menu List: %s" % menudict )
576 if build_all_menus:
577 all_menus = []
578 for key in menudict:
579 for i in menudict[key]:
580 all_menus.append(key+'/'+i)
581 return all_menus, ''
582
583 # sort menus related to desktops and create a weighting
584 vprint("\n DE weighting search: DE => [user menus, system menus, overall]")
585 weight_dict = {}
586 if desktop == '':
587 # first the desktops, then debian (shouldn't appear in others) then others holding
588 # all other non DE menus e.g. tools and at the end the nones without prefixes
589 # If there're other prefixes from other WMs - should be added BEFORE debian
590 DEs = ['gnome', 'kde', 'xfce', 'lxde', 'cinnamon', 'mate', 'debian', 'others', 'none']
591 else:
592 DEs = [desktop]
593 for de in DEs:
594 menus = set([])
595 user_menus = 0
596 system_menus = 0
597 filled = False
598 for path in list(menudict.keys()):
599 if de == 'none':
600 pattern = '*'
601 elif de == 'others':
602 pattern = '*-*'
603 else:
604 pattern = '*'+de+'*'
605 # fnmatch.filter returns a list of files the pattern match
606 menu_names = fnmatch.filter(menudict[path], pattern)
607 if not len(menu_names) == 0:
608 filled = True
609 for name in menu_names:
610 menus.add(path+'/'+name)
611 # delete each found DE menu from the actual path. So, the menus will be reduced loop by loop.
612 menudict[path] = menudict[path]-set(menu_names)
613 # count the menus found in the users and systems menu path for later weighting
614 if not path == '/etc/xdg/menus':
615 user_menus = len(menu_names)
616 else:
617 system_menus = len(menu_names)
618 if filled:
619 desktop_dict[de] = menus
620 filled = False
621 # fill the weight dictionary with the counts
622 weight_dict[de] = [user_menus, system_menus, user_menus+system_menus]
623 vprint(" %s => %s" %(de, weight_dict[de]))
624
625 # get the highest rated desktop
626 highest = 0
627 de_highest = ''
628 for de in sorted(weight_dict.keys()):
629 de_user = weight_dict[de][0]
630 de_system = weight_dict[de][1]
631 de_total = weight_dict[de][2]
632 higher = False
633 if not de_highest == '':
634 # don't weight 'none' and 'others cause both not DEs
635 if not de == 'none' and not de == 'others':
636 highest_user = weight_dict[de_highest][0]
637 highest_system = weight_dict[de_highest][1]
638 highest_total = weight_dict[de_highest][2]
639 # first compare the total counts
640 if highest < de_total:
641 higher = True
642 elif highest == de_total:
643 # if the totals equal compare the users
644 if highest_user < de_user:
645 higher = True
646 elif highest_user == de_user:
647 # it the users equal compare the system menus
648 if highest_system < de_system:
649 higher = True
650 # if the systems equal the last wins
651 elif highest_system == de_system:
652 higher = True # fixme, should be biunique. -but how? With atime?
653 else:
654 higher = True
655
656 if higher:
657 highest = de_total
658 de_highest = de
659
660 if highest == 0 : # no dev environments?
661 de_highest = 'others' # use 'others'
662 vprint( "\n Winner: %s" %de_highest)
663
664 # Perhaps there're a global menus available which are not in the highest rated list
665 if 'none' in desktop_dict:
666 for menu in desktop_dict['none']:
667 name = menu.replace('.menu', '').split('/')
668 # the fnmatch.filter will be used to find NO match because then
669 # the menu is not in the list
670 found = fnmatch.filter(desktop_dict[de_highest], '*'+name[-1]+'*')
671 if found == []:
672 desktop_dict[de_highest].add(menu)
673
674 # Add 'others' menus to list, because these could be tool menus like yast, etc
675 if 'others' in desktop_dict:
676 for menu in desktop_dict['others']:
677 desktop_dict[de_highest].add(menu)
678
679 if len(desktop_dict) == 0:
680 return [], ''
681 else:
682 return list(desktop_dict[de_highest]), de_highest
683
684 def vprint(text):
685 if verbose:
686 sys.stderr.write(text+"\n")
687
688 # Encoding error handling of menu entries.
689 def printtext(text):
690 try: print(text)
691 except UnicodeEncodeError:
692 if verbose: print("# UnicodeEncodeError - Attempting to encode")
693 try:
694 sys.stdout.flush()
695 sys.stdout.buffer.write(text.encode())
696 print()
697 except: print(text.encode("ascii", errors="replace").decode("ascii"))
698 except:
699 if verbose: print("# Unknown error - Skipping entry")
700
701 def geticonfile(icon):
702 assert IconScaleTool.enable_icon, "enable_icon option must be True here"
703 iconpath = xdg.IconTheme.getIconPath(icon, size, current_theme, ["svg", "png", "xpm"])
704
705 if not iconpath or not os.path.exists(iconpath):
706 return None
707
708 st = IconScaleTool(iconpath)
709 if st.check_size():
710 return iconpath
711 return st.convert(previous_theme != current_theme)
712
713 def getdefaulticonfile(command):
714 if command.startswith("Popup"):
715 return geticonfile(default_dir_icon)
716 else:
717 return geticonfile(default_app_icon)
718
719 def escapemenutext(text):
720 return text.replace('&', '&&').replace('%', '%%')
721
722 def printmenu(name, icon, command):
723 iconfile = ''
724 if IconScaleTool.enable_icon:
725 iconfile = geticonfile(icon) or getdefaulticonfile(command) or icon
726 if not (iconfile == '' or iconfile == None) and os.path.isfile(iconfile):
727 iconfile = '%'+iconfile+'%'
728 else:
729 vprint(f"{iconfile} icon or default icon not found!")
730 iconfile = ''
731 printtext('+ "%s%s" %s' % (escapemenutext(name), iconfile, command))
732
733 def parsemenus(menulist, desktop, desktop_entries=[]):
734 if menu_list_length == 1:
735 new_menulist = menulist
736 # user defines only one special menu
737 parsemenu(xdg.Menu.parse(menulist[0]), top, '', desktop_entries)
738 else:
739 # create a top title list
740 top_titles = []
741 for file in menulist:
742 # extract and split the filename and set first char of each word to capital
743 name_parts = file.replace('.menu', '').split('/')[-1].split('-')
744 name_parts = [name[0].replace(name[0], name[0].upper())+name[1:] for name in name_parts]
745 top_titles.append(' '.join(name_parts))
746
747 # create the submenus
748 new_toptitles = []
749 new_menulist = []
750 for title, menu in zip(top_titles, menulist):
751 name = 'Fvwm'+title
752 vprint("Create submenu \'%s\' from \'%s\'" %(name, menu))
753 desktop_subentries = []
754 parsemenu(xdg.Menu.parse(menu), name, title, desktop_subentries)
755 # remove a menu if no menu entry was created in its sub menus
756 if desktop_subentries:
757 new_toptitles.append(title)
758 new_menulist.append(menu)
759 desktop_entries += desktop_subentries
760 else:
761 vprint(" Menu is empty - won't be used!")
762
763 # create the root menu
764 if printmode:
765 if not insert_in_menu:
766 if dynamic_menu:
767 printtext('DestroyMenu recreate "%s"' % top)
768 else:
769 printtext('DestroyMenu "%s"' % top)
770 if with_titles and not insert_in_menu:
771 printtext('AddToMenu "%s" "%s" Title' % (top, top))
772 else:
773 printtext('AddToMenu "%s"' % top)
774
775 for title in sorted(new_toptitles):
776 name = 'Fvwm'+title
777 printmenu(title, '', 'Popup "%s"' % name)
778
779 if include_items != 'none':
780 printtext('+ "" Nop')
781 if include_items in ("both", "regenerate"):
782 printmenu("$[gt.Regenerate]", "system-software-update", regen_cmd )
783 if include_items in ("both", "config"):
784 printmenu("$[gt.Configure]", "system-software-update", "Module FvwmPerl -l fvwm-menu-desktop-config.fpl" )
785
786 if not get_menus == '':
787 printtext('%s' % ' '.join(new_menulist))
788
789 def parsemenu(menu, name="", title="", desktop_entries=[]):
790 m = re.compile('%[A-Z]?', re.I) # Pattern for %A-Z (meant for %U)
791 if not name :
792 name = menu.getPath()
793 if not title:
794 title = name
795 if printmode:
796 if not insert_in_menu or not (insert_in_menu and name == top and menu_list_length == 1):
797 if name == top and dynamic_menu:
798 printtext('DestroyMenu recreate "%s"' % name)
799 else:
800 printtext('DestroyMenu "%s"' % name)
801 if with_titles:
802 # for insert-in-menu AddToMenu doesn't have a title for top menu
803 # because this will appear then in the other menu
804 if insert_in_menu and name == top and menu_list_length == 1:
805 printtext('AddToMenu "%s"' % name)
806 else:
807 printtext('AddToMenu "%s" "%s" Title' % (name, title))
808 else:
809 printtext('AddToMenu "%s"' % name)
810 for entry in menu.getEntries():
811 if isinstance(entry, xdg.Menu.Menu):
812 if printmode:
813 printmenu(entry.getName(), entry.getIcon(), 'Popup "%s"' % entry.getPath())
814 elif isinstance(entry, xdg.Menu.MenuEntry):
815 desktop = DesktopEntry(entry.DesktopEntry.getFileName())
816 if printmode:
817 # eliminate '%U' etc behind execute string
818 execProgram = m.sub('', desktop.getExec())
819 if desktop.getTerminal():
820 execProgram = "%s %s" % (term_cmd, execProgram)
821 printmenu(desktop.getName(), desktop.getIcon(), "Exec exec " + execProgram)
822 desktop_entries.append(desktop)
823 elif isinstance(entry, xdg.Menu.Separator):
824 if printmode:
825 printtext( '+ "" Nop' )
826 else:
827 if printmode:
828 printtext('# not supported: ' + str(entry))
829
830 if printmode:
831 # should only appear in a single menu. For more it will insert in parsemenus() when the top menu will built
832 if menu_list_length == 1 and name == top and include_items != 'none':
833 printtext('+ "" Nop')
834 if include_items in ("both", "regenerate"):
835 printmenu("$[gt.Regenerate]", "system-software-update", regen_cmd )
836 if include_items in ("both", "config"):
837 printmenu("$[gt.Configure]", "system-software-update", "Module FvwmPerl -l fvwm-menu-desktop-config.fpl" )
838 printtext('')
839
840 for entry in menu.getEntries():
841 if isinstance(entry, xdg.Menu.Menu):
842 parsemenu(entry, '', '', desktop_entries)
843
844 usage="""
845 A script which parses xdg menu definitions to build
846 the corresponding fvwm menus.
847
848 Usage: $0 [OPTIONS]
849 Options:
850 -h, --help show this help and exit.
851 --version show version and exit.
852 --install-prefix DIR install prefix of the desktop menu files.
853 Per default not set. For system wide menus
854 use /etc/xdg/menus/.
855 --desktop NAME use menus that include NAME in the file name:
856 gnome, kde, xfce, lxde, debian, etc.
857 --menu-type NAME use menus that include NAME in the file name:
858 applications, settings, preferences, etc. When
859 used with --desktop only menus whose file name
860 mathces '*desktop*menutype*' are used.
861 --theme NAME icon theme: gnome (default), oxygen, etc. Don't
862 use hicolor. It's the default fallback theme if
863 no icon is found.
864 -w, --with-titles generate menus with titles. Default.
865 --without-titles generate menus without titles.
866 --enable-mini-icons enable mini-icons in menu.
867 -s, --size NUM set size of mini-icons in menu. Default is 24.
868 --mini-icon-dir DIR set directory for mini-icons.
869 Default is ~/.fvwm/icons.
870 --app-icon NAME set default application icon if no others found.
871 Default is 'gnome-applications'.
872 --dir-icon NAME set default directory icon if no others found.
873 Default is 'gnome-fs-directory'.
874 -t, --title NAME menu title of the top menu used by Popup command.
875 Default is XDGMenu.
876 --insert-in-menu NAME generates a menu to place it in the root level
877 of the menu NAME.
878 --get-menus all|desktop prints a space separated list of full menu paths.
879 'all' is all menus on the system except empty
880 ones. 'desktop' list the menus that would have
881 been generated. No menu generation is done.
882 --set-menus menu_paths expects a space separated list of full menu paths
883 to generate user specified menus.
884 --all-menus generate all menus found.
885 --include-items NAME include additional menu items NAME in top level
886 menu. NAME can be 'config', 'regenerate', 'both'
887 or 'none'. Default both.
888 --regen-cmd ACTION The fvwm ACTION for the 'Regenerate' menu item.
889 Default: 'PipeRead `fvwm-menu-desktop`'
890 --term-cmd CMD Terminal emulator CMD used on terminal entries.
891 Debian Default: x-terminal-emulator -e
892 --dynamic used with dynamic menus.
893 -e, --menu-error out python-xdg not found error in menu.
894 -v, --verbose run and display debug info on STDERR."""
895
896 if __name__ == "__main__":
897 main()
898
899 # Local Variables:
900 # mode: python
901 # compile-command: "python3 fvwm-menu-desktop.in --version"
902 # End: