#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
kread-desktopfile.py dumps KDE desktop files. 
It is usefull for debugging KDE Kiosks settings,
where multiple config files are merged into the final configuration.  

The directory hierarchie for resource files 
is based on the KDEDIRS environment variable
and can be made visible by  the command
kde4-config --path config
"""

# $Id: kread-desktopfile.py 838 2010-03-12 14:42:08Z joergs $

import sys
from PyKDE4.kdecore import ki18n, KAboutData, KCmdLineArgs, KCmdLineOptions, KConfig, KDesktopFile
from PyKDE4.kdeui import KApplication
 
#import pprint
#pp = pprint.PrettyPrinter(indent=4)

def getFullName( config ):
  """get the full name of a config group"""
  if config.name() == "<default>":
    return ""

  # check, if function config.parent is defined
  try: config.parent
  except AttributeError:
    # x doesn't exist, do something
    return "[" + config.name() + "]"
  else:
    # x exists, do something else
    parentsNames = getFullName( config.parent() )
    return  parentsNames + "[" + config.name() + "]"



def dumpGroup( config ):
  """print the entries of a config group"""

  # print secton name only if entries exists
  if config.entryMap():
    print getFullName( config )
    #print dir(config)
    #for i in config.entryMap():
    for i in config.keyList():
      immutaleString = ''
      if config.isEntryImmutable( i ):
        immutaleString = "[$i]"
      try:
        #print i + immutaleString, "=", config.readEntry( i ).toUtf8()
        print i + immutaleString, "=", config.readEntry( i )
      except AttributeError:
      # ignore when readEntry does not exist
        print i + " => readEntry not defined"
        #, i.count(), dir(i)
        pass
      except UnicodeEncodeError:
        print i + " => encoding error"
        pass
  print



def dumpSubGroups( config ):
  """print entries of the config group and all subgroups"""
  dumpGroup( config )
  #print dir( config )
  for i in config.groupList():
    configGroup=config.group(str(i))
    dumpSubGroups( configGroup )


appName     = "kreadconfig.py"
catalog     = ""
programName = ki18n ("kreadconfig.py")
version     = "$Rev: 838 $"
description = ki18n ("show KDE configuration files")
license     = KAboutData.License_GPL
copyright   = ki18n ("(c) 2009 Jörg Steffens")
text        = ki18n ("none")
homePage    = "www.dass-it.de"
bugEmail    = "rt@dass-it.de"
 
aboutData   = KAboutData (appName, catalog, programName, version, description,
                        license, copyright, text, homePage, bugEmail)

# command line argument handling
options = KCmdLineOptions()
options.add("+configfile", ki18n("KDE config file name"))
 
KCmdLineArgs.init(sys.argv, aboutData)
# Register the supported options
KCmdLineArgs.addCmdLineOptions( options )

app = KApplication ()

args = KCmdLineArgs.parsedArgs();

# TODO: why is this not detected automatically?
if args.count() != 1:
  args.usage()

configfilename = args.arg(0)
#print configfilename

if not KDesktopFile.isDesktopFile(configfilename):
    print "failed: no desktop file '", configfilename, "' found"
    exit(1)

#config = KConfig(configfilename, KConfig.NoGlobals)
config = KDesktopFile(configfilename)


print "filename:                          ", config.fileName()
print "readName():                        ", config.readName() 
print 'readEntry( "Name" ):               ', config.group("Desktop Entry").readEntry( "Name" )
print 'readEntry( "Name", "default" ):    ', config.group("Desktop Entry").readEntry( "Name", "default" ).toString()
print "readIcon():                        ", config.readIcon() 
print "noDisplay():                       ", config.noDisplay()
print 'readEntry( "NoDisplay" ):          ', config.group("Desktop Entry").readEntry( "NoDisplay" )
print 'readEntry( "NoDisplay", True ):    ', config.group("Desktop Entry").readEntry( "NoDisplay", True ).toString()
print 'readEntry( "NoDisplay", "True" ):  ', config.group("Desktop Entry").readEntry( "NoDisplay", "True" ).toString()
print 'readEntry( "NoDisplay", False ):   ', config.group("Desktop Entry").readEntry( "NoDisplay", False ).toString()
print 'readEntry( "NoDisplay", "False" ): ', config.group("Desktop Entry").readEntry( "NoDisplay", "False" ).toString()


print
print "dump:"

# only show the sub-groups.
# top-level entries will be in the section [MainWindow]
#dumpSubGroups( config )
for i in config.groupList():
  configGroup=config.group(str(i))
  dumpSubGroups( configGroup )
