Initial git import
[oweals/hwdata.git] / inf2mondb.py
1 #!/usr/bin/python
2 #
3 # inf2mondb.py: convert MicroSoft .inf files for monitors to MonitorDB
4 #
5 # originally by Matt Wilson <msw@redhat.com>
6 # option parsing and database comparison by Fred New
7 # ini parsing completely rewritten by Matt Domsch <Matt_Domsch@dell.com> 2006
8 #
9 # Copyright 2002 Red Hat, Inc.
10 # Copyright 2006 Dell, Inc.
11 #
12 # This software may be freely redistributed under the terms of the GNU
13 # library public license.
14 #
15 # You should have received a copy of the GNU Library Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 """
19 """
20
21
22 import sys
23 import string
24 import re
25 import ConfigParser
26
27 # this is a class to deal with various file line endings and leading whitespace
28 # converts all \r line endings to \n.
29 # It also strips leading whitespace.
30 # NOTE: be sure to always return _something_, even if it is just "\n", or we 
31 # break the file API.  (nothing == eof)
32 class myFile(object):
33     def __init__(self, *args):
34         self.fd = open(*args)
35
36     def close(self):
37         return self.fd.close()
38     
39     def readline(self, *args):
40         line = self.fd.readline(*args)
41         line = line.replace('\r', '\n')
42         line = line.replace('\n\n', '\n')
43         line = line.lstrip(" \t")
44         return line
45
46
47 # we will use this to override default option parsing in ConfigParser to handle
48 # Microsoft-style "INI" files. (Which do not necessarily have " = value " after
49 # the option name
50 OPTCRE = re.compile(
51         r'(?P<option>[^:=\s][^:=]*)'          # very permissive!
52         r'\s*(?P<vi>[:=]{0,1})\s*'            # any number of space/tab,
53                                               # optionally followed by
54                                               # separator (either : or =)
55                                               # optionally followed
56                                               # by any # space/tab
57         r'(?P<value>.*)$'                     # everything up to eol
58         )
59
60 def usage():
61     print "No monitor.inf file specified."
62     sys.exit(1)
63     
64 percentSplit = re.compile(r'%(?P<field>.*)%')
65 def percent_to_string(ini, strings, name):
66     mo = percentSplit.match(name)
67     if (mo):
68         field = mo.group('field')
69         try:
70             val = strings[field.lower()]
71         except KeyError:
72             return ""
73         return val.strip()
74     return ""
75
76
77 def main():
78     defaultDB = "/usr/share/hwdata/MonitorsDB"
79     
80     from optparse import OptionParser
81     parser = OptionParser(usage= sys.argv[0] + " [options] filename.inf")
82     parser.add_option("-n", "--new",
83                     action="store_true", dest="newonly", default=False,
84                     help="Compare results with the monitors database and only "
85                         "show DB lines that don't already appear in the "
86                         "database.")
87     parser.add_option("-v", "--verbose",
88                     action="store_true", dest="verbose", default=False,
89                     help="Used with --new to permit us to see which monitors "
90                         "already appear in the monitors database.")
91     parser.add_option("-d", "--database",
92                     dest="database",
93                     default=defaultDB,
94                     help="Used with --new to specify a different "
95                         "monitors database.  "
96                         "The default is " + defaultDB + ".",
97                     metavar="FILE")
98     
99     (options, args) = parser.parse_args()
100     
101     if len(args) < 1:
102         usage()
103
104     ini = ConfigParser.ConfigParser()
105     ini.optionxform = __builtins__.str
106     ini.OPTCRE = OPTCRE
107     f = myFile(args[0])
108     ini.readfp(f)
109     f.close()
110
111     # First, build a dictionary of monitors we already know about.
112     # When we get ready to print the monitors we found in the .inf
113     # file, we can decide whether it is new or not.
114     
115     # Dictionary of booleans showing whether certain monitor EDIDs are known.
116     # knownids[knownID] = True
117     # knownids[unknownID] isn't defined.
118     knownids = {}
119     
120     if options.newonly:
121         try:
122             mdb = open(options.database, 'r')
123         except IOError, (errno, str):
124             print "Unable to open %s: %s" % (options.database, str)
125             sys.exit(1)
126     
127         knowns = mdb.readlines()
128         mdb.close()
129     
130         for known in knowns:
131             if len(string.strip(known)) == 0 or known[0] == '#':
132                 continue
133             knownids[string.lower(string.strip(string.split(known, ';')[2]))] = True
134     
135
136     # a dictionary of manufacturers we're looking at
137     manufacturers = {}
138     # a big fat dictionary of strings to use later on.
139     strings = {}
140
141     # This RE is for EISA info lines
142     # %D5259A%=D5259A, Monitor\HWP0487
143     monitor1Re = re.compile(r'.*,.*Monitor\\(?P<id>[^\s]*)')
144     # This one is for legacy entries
145     # %3020%     =PB3020,   MonID_PB3020
146     monitor2Re = re.compile(r'.*,.*MonID_(?P<id>[^\s]*)')
147     
148     for section in ini.sections():
149         if section.lower() == "manufacturer":
150             for mfr in ini.options(section):
151                 # generate the vendor.arch funny entries
152                 manufacturer_values = string.split(ini.get(section, mfr), ',')
153                 manufacturers[manufacturer_values[0]] = mfr
154                 while len(manufacturer_values) > 1:
155                     manufacturers["%s.%s" % (manufacturer_values[0], manufacturer_values[-1])] = mfr
156                     manufacturer_values = manufacturer_values[0:-1]
157     
158         elif section.lower() == "strings":
159             for key in ini.options(section):
160                 strings[key.lower()] = string.strip(ini.get(section, key))
161     
162     
163     for mfr in manufacturers.keys():
164         if ini.has_section(mfr):
165             monitor_vendor_name = manufacturers[mfr]
166             for monitor_name in ini.options(mfr):
167                 v = ini.get(mfr, monitor_name)
168                 v = v.split(',')
169                 install_key = v[0].strip()
170     
171                 line = ini.get(mfr, monitor_name)
172                 # Find monitor inf IDs and EISA ids
173     
174                 edid = "0"
175                 mo = monitor1Re.match(line)
176                 if mo:
177                     edid = mo.group('id')
178                 else:
179                     mo = monitor2Re.match(line)
180                     if mo:
181                         edid = mo.group('id').strip()
182     
183                 if knownids.has_key(edid.lower()):
184                     continue
185     
186                 if ini.has_section(install_key):
187                     line = ini.get(install_key, "AddReg")
188                     if line:
189                         sline = line.split(',')
190                         registry = sline[0]
191                         try:
192                             resolution = sline[1]
193                         except IndexError:
194                             resolution = ""
195                         try:
196                             dpms = sline[2]
197                         except IndexError:
198                             dpms = ""
199     
200                         if ini.has_section(registry):
201                             for line in ini.options(registry):
202                                 if string.find(line, 'HKR,"MODES') >= 0:
203                                     sline = line.split('"')
204                                     try:
205                                         syncline = sline[3]
206                                     except IndexError:
207                                         syncline = ","
208                                         
209                                     syncline = syncline.split(',')
210                                     hsync = syncline[0].strip()
211                                     vsync = syncline[1].strip()
212     
213                                     output = "%s; %s; %s; %s; %s" % (percent_to_string(ini, strings, monitor_vendor_name),
214                                                                      percent_to_string(ini, strings, monitor_name),
215                                                                      edid, hsync, vsync)
216                                     if dpms.lower().strip() == "dpms":
217                                         output = output + "; 1"
218     
219                                     if not knownids.has_key(edid.lower()):
220                                         print output
221                                         knownids[edid.lower()] = True
222
223
224
225 if __name__ == "__main__":
226     sys.exit(main())