comparison src/bridge/bridge_constructor/bridge_contructor.py @ 587:952322b1d490

Remove trailing whitespaces.
author Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
date Fri, 18 Jan 2013 17:55:34 +0100
parents ca13633d3b6b
children beaf6bec2fcd
comparison
equal deleted inserted replaced
586:6a718ede8be1 587:952322b1d490
51 from datetime import datetime 51 from datetime import datetime
52 from xml.dom import minidom 52 from xml.dom import minidom
53 53
54 54
55 class ParseError(Exception): 55 class ParseError(Exception):
56 #Used when the signature parsing is going wrong (invalid signature ?) 56 #Used when the signature parsing is going wrong (invalid signature ?)
57 pass 57 pass
58 58
59 class Constructor: 59 class Constructor:
60 60
61 def __init__(self, bridge_template, options): 61 def __init__(self, bridge_template, options):
62 self.bridge_template = bridge_template 62 self.bridge_template = bridge_template
63 self.options = options 63 self.options = options
64 64
65 def getValues(self, name): 65 def getValues(self, name):
72 value = self.bridge_template.get(name, option) 72 value = self.bridge_template.get(name, option)
73 except NoOptionError: 73 except NoOptionError:
74 value = None 74 value = None
75 function[option] = value 75 function[option] = value
76 return function 76 return function
77 77
78 def getDefault(self, name): 78 def getDefault(self, name):
79 """Return default values of a function in a dict 79 """Return default values of a function in a dict
80 @param name: Name of the function to get 80 @param name: Name of the function to get
81 @return: dict, each key is the integer param number (no key if no default value)""" 81 @return: dict, each key is the integer param number (no key if no default value)"""
82 default_dict={} 82 default_dict={}
83 def_re = re.compile(r"param_(\d+)_default") 83 def_re = re.compile(r"param_(\d+)_default")
84 84
85 for option in self.bridge_template.options(name): 85 for option in self.bridge_template.options(name):
86 match = def_re.match(option) 86 match = def_re.match(option)
87 if match: 87 if match:
88 try: 88 try:
89 idx = int(match.group(1)) 89 idx = int(match.group(1))
90 except ValueError: 90 except ValueError:
91 raise ParseError("Invalid value [%s] for parameter number" % match.group(1)) 91 raise ParseError("Invalid value [%s] for parameter number" % match.group(1))
92 default_dict[idx] = self.bridge_template.get(name, option) 92 default_dict[idx] = self.bridge_template.get(name, option)
93 93
94 return default_dict 94 return default_dict
95 95
96 def getFlags(self, name): 96 def getFlags(self, name):
97 """Return list of flags set for this function 97 """Return list of flags set for this function
98 @param name: Name of the function to get 98 @param name: Name of the function to get
100 flags=[] 100 flags=[]
101 for option in self.bridge_template.options(name): 101 for option in self.bridge_template.options(name):
102 if option in FLAGS: 102 if option in FLAGS:
103 flags.append(option) 103 flags.append(option)
104 return flags 104 return flags
105 105
106 def getArgumentsDoc(self, name): 106 def getArgumentsDoc(self, name):
107 """Return documentation of arguments 107 """Return documentation of arguments
108 @param name: Name of the function to get 108 @param name: Name of the function to get
109 @return: dict, each key is the integer param number (no key if no argument doc), value is a tuple (name, doc)""" 109 @return: dict, each key is the integer param number (no key if no argument doc), value is a tuple (name, doc)"""
110 doc_dict={} 110 doc_dict={}
173 """Return arguments to user given a signature 173 """Return arguments to user given a signature
174 @param signature: signature in the short form (using s,a,i,b etc) 174 @param signature: signature in the short form (using s,a,i,b etc)
175 @param name: dictionary of arguments name like given by getArguments 175 @param name: dictionary of arguments name like given by getArguments
176 @param default: dictionary of default values, like given by getDefault 176 @param default: dictionary of default values, like given by getDefault
177 @param unicode_protect: activate unicode protection on strings (return strings as unicode(str)) 177 @param unicode_protect: activate unicode protection on strings (return strings as unicode(str))
178 @return: list of arguments that correspond to a signature (e.g.: "sss" return "arg1, arg2, arg3")""" 178 @return: list of arguments that correspond to a signature (e.g.: "sss" return "arg1, arg2, arg3")"""
179 idx=0 179 idx=0
180 attr_string=[] 180 attr_string=[]
181 181
182 for arg in self.argumentsParser(signature): 182 for arg in self.argumentsParser(signature):
183 attr_string.append(("unicode(%(name)s)%(default)s" if (unicode_protect and arg=='s') else "%(name)s%(default)s") % { 183 attr_string.append(("unicode(%(name)s)%(default)s" if (unicode_protect and arg=='s') else "%(name)s%(default)s") % {
184 'name':name[idx][0] if (name and name.has_key(idx)) else "arg_%i" % idx, 184 'name':name[idx][0] if (name and name.has_key(idx)) else "arg_%i" % idx,
185 'default':"="+default[idx] if (default and default.has_key(idx)) else '' 185 'default':"="+default[idx] if (default and default.has_key(idx)) else ''
186 }) #give arg_1, arg2, etc or name1, name2=default, etc. \ 186 }) #give arg_1, arg2, etc or name1, name2=default, etc. \
187 #give unicode(arg_1), unicode(arg_2), etc. if unicode_protect is set and arg is a string 187 #give unicode(arg_1), unicode(arg_2), etc. if unicode_protect is set and arg is a string
188 idx+=1 188 idx+=1
189 189
190 return ", ".join(attr_string) 190 return ", ".join(attr_string)
191 191
192 def generateCoreSide(self): 192 def generateCoreSide(self):
193 """create the constructor in SàT core side (backend)""" 193 """create the constructor in SàT core side (backend)"""
194 raise NotImplementedError 194 raise NotImplementedError
207 try: 207 try:
208 if not os.path.exists(DEST_DIR): 208 if not os.path.exists(DEST_DIR):
209 os.mkdir(DEST_DIR) 209 os.mkdir(DEST_DIR)
210 full_path=os.path.join(DEST_DIR,filename) 210 full_path=os.path.join(DEST_DIR,filename)
211 if os.path.exists(full_path) and not self.options.force: 211 if os.path.exists(full_path) and not self.options.force:
212 print ("The destination file [%s] already exists ! Use --force to overwrite it" % full_path) 212 print ("The destination file [%s] already exists ! Use --force to overwrite it" % full_path)
213 try: 213 try:
214 with open(full_path,'w') as dest_file: 214 with open(full_path,'w') as dest_file:
215 dest_file.write('\n'.join(file_buf)) 215 dest_file.write('\n'.join(file_buf))
216 except IOError: 216 except IOError:
217 print ("Can't open destination file [%s]" % full_path) 217 print ("Can't open destination file [%s]" % full_path)
221 221
222 class MediawikiConstructor(Constructor): 222 class MediawikiConstructor(Constructor):
223 223
224 def __init__(self, bridge_template, options): 224 def __init__(self, bridge_template, options):
225 Constructor.__init__(self, bridge_template, options) 225 Constructor.__init__(self, bridge_template, options)
226 self.core_template="mediawiki_template.tpl" 226 self.core_template="mediawiki_template.tpl"
227 self.core_dest="mediawiki.wiki" 227 self.core_dest="mediawiki.wiki"
228 228
229 def _addTextDecorations(self, text): 229 def _addTextDecorations(self, text):
230 """Add text decorations like coloration or shortcuts""" 230 """Add text decorations like coloration or shortcuts"""
231 231
232 def anchor_link(match): 232 def anchor_link(match):
257 else: 257 else:
258 wiki.append("; arg_%d: " % i) 258 wiki.append("; arg_%d: " % i)
259 if arg_default.has_key(i): 259 if arg_default.has_key(i):
260 wiki.append(":''DEFAULT: %s''" % arg_default[i]) 260 wiki.append(":''DEFAULT: %s''" % arg_default[i])
261 return "\n".join(wiki) 261 return "\n".join(wiki)
262 262
263 def _wikiReturn(self, name): 263 def _wikiReturn(self, name):
264 """Format return doc with the wiki syntax 264 """Format return doc with the wiki syntax
265 @param name: name of the function 265 @param name: name of the function
266 """ 266 """
267 arg_doc = self.getArgumentsDoc(name) 267 arg_doc = self.getArgumentsDoc(name)
315 ''%(doc)s'' 315 ''%(doc)s''
316 %(deprecated)s 316 %(deprecated)s
317 %(async)s 317 %(async)s
318 {| class="wikitable" style="text-align:left; width:80%%;" 318 {| class="wikitable" style="text-align:left; width:80%%;"
319 ! scope=row | category 319 ! scope=row | category
320 | %(category)s 320 | %(category)s
321 |- 321 |-
322 %(signature)s 322 %(signature)s
323 ! scope=row | parameters 323 ! scope=row | parameters
324 | 324 |
325 %(parameters)s%(return)s 325 %(parameters)s%(return)s
326 |} 326 |}
327 """ % completion) 327 """ % completion)
328 328
329 #at this point, signals_part, and methods_part should be filled, 329 #at this point, signals_part, and methods_part should be filled,
330 #we just have to place them in the right part of the template 330 #we just have to place them in the right part of the template
331 core_bridge = [] 331 core_bridge = []
332 try: 332 try:
333 with open(self.core_template) as core_template: 333 with open(self.core_template) as core_template:
340 core_bridge.append('Generated on %s' % datetime.now()) 340 core_bridge.append('Generated on %s' % datetime.now())
341 else: 341 else:
342 core_bridge.append(line.replace('\n','')) 342 core_bridge.append(line.replace('\n',''))
343 except IOError: 343 except IOError:
344 print ("Can't open template file [%s]" % self.core_template) 344 print ("Can't open template file [%s]" % self.core_template)
345 sys.exit(1) 345 sys.exit(1)
346 346
347 #now we write to final file 347 #now we write to final file
348 self.finalWrite(self.core_dest, core_bridge) 348 self.finalWrite(self.core_dest, core_bridge)
349 349
350 class DbusConstructor(Constructor): 350 class DbusConstructor(Constructor):
351 351
352 def __init__(self, bridge_template, options): 352 def __init__(self, bridge_template, options):
353 Constructor.__init__(self, bridge_template, options) 353 Constructor.__init__(self, bridge_template, options)
354 self.core_template="dbus_core_template.py" 354 self.core_template="dbus_core_template.py"
355 self.frontend_template="dbus_frontend_template.py" 355 self.frontend_template="dbus_frontend_template.py"
356 self.frontend_dest = self.core_dest="DBus.py" 356 self.frontend_dest = self.core_dest="DBus.py"
357 357
358 def generateCoreSide(self): 358 def generateCoreSide(self):
359 signals_part = [] 359 signals_part = []
360 methods_part = [] 360 methods_part = []
361 direct_calls = [] 361 direct_calls = []
369 async = "async" in self.getFlags(section) 369 async = "async" in self.getFlags(section)
370 completion = { 370 completion = {
371 'sig_in':function['sig_in'] or '', 371 'sig_in':function['sig_in'] or '',
372 'sig_out':function['sig_out'] or '', 372 'sig_out':function['sig_out'] or '',
373 'category':'PLUGIN' if function['category'] == 'plugin' else 'CORE', 373 'category':'PLUGIN' if function['category'] == 'plugin' else 'CORE',
374 'name':section, 374 'name':section,
375 'args':self.getArguments(function['sig_in'], name=arg_doc, default=default ) 375 'args':self.getArguments(function['sig_in'], name=arg_doc, default=default )
376 } 376 }
377 377
378 if function["type"] == "signal": 378 if function["type"] == "signal":
379 completion['body'] = "pass" if not self.options.debug else 'debug ("%s")' % section 379 completion['body'] = "pass" if not self.options.debug else 'debug ("%s")' % section
425 core_bridge.append('const_%s = %s' % (const_name, os.environ[ENV_OVERRIDE+const_name])) 425 core_bridge.append('const_%s = %s' % (const_name, os.environ[ENV_OVERRIDE+const_name]))
426 continue 426 continue
427 core_bridge.append(line.replace('\n','')) 427 core_bridge.append(line.replace('\n',''))
428 except IOError: 428 except IOError:
429 print ("Can't open template file [%s]" % self.core_template) 429 print ("Can't open template file [%s]" % self.core_template)
430 sys.exit(1) 430 sys.exit(1)
431 431
432 #now we write to final file 432 #now we write to final file
433 self.finalWrite(self.core_dest, core_bridge) 433 self.finalWrite(self.core_dest, core_bridge)
434 434
435 def generateFrontendSide(self): 435 def generateFrontendSide(self):
444 async = "async" in self.getFlags(section) 444 async = "async" in self.getFlags(section)
445 completion = { 445 completion = {
446 'sig_in':function['sig_in'] or '', 446 'sig_in':function['sig_in'] or '',
447 'sig_out':function['sig_out'] or '', 447 'sig_out':function['sig_out'] or '',
448 'category':'plugin' if function['category'] == 'plugin' else 'core', 448 'category':'plugin' if function['category'] == 'plugin' else 'core',
449 'name':section, 449 'name':section,
450 'args':self.getArguments(function['sig_in'], name=arg_doc, default=default) 450 'args':self.getArguments(function['sig_in'], name=arg_doc, default=default)
451 } 451 }
452 452
453 if function["type"] == "method": 453 if function["type"] == "method":
454 completion['debug'] = "" if not self.options.debug else 'debug ("%s")\n%s' % (section,8*' ') 454 completion['debug'] = "" if not self.options.debug else 'debug ("%s")\n%s' % (section,8*' ')
481 frontend_bridge.append('const_%s = %s' % (const_name, os.environ[ENV_OVERRIDE+const_name])) 481 frontend_bridge.append('const_%s = %s' % (const_name, os.environ[ENV_OVERRIDE+const_name]))
482 continue 482 continue
483 frontend_bridge.append(line.replace('\n','')) 483 frontend_bridge.append(line.replace('\n',''))
484 except IOError: 484 except IOError:
485 print ("Can't open template file [%s]" % self.frontend_template) 485 print ("Can't open template file [%s]" % self.frontend_template)
486 sys.exit(1) 486 sys.exit(1)
487 487
488 #now we write to final file 488 #now we write to final file
489 self.finalWrite(self.frontend_dest, frontend_bridge) 489 self.finalWrite(self.frontend_dest, frontend_bridge)
490 490
491 class DbusXmlConstructor(Constructor): 491 class DbusXmlConstructor(Constructor):
492 """Constructor for DBus XML syntaxt (used by Qt frontend)""" 492 """Constructor for DBus XML syntaxt (used by Qt frontend)"""
493 493
494 def __init__(self, bridge_template, options): 494 def __init__(self, bridge_template, options):
495 Constructor.__init__(self, bridge_template, options) 495 Constructor.__init__(self, bridge_template, options)
496 496
497 self.template="dbus_xml_template.xml" 497 self.template="dbus_xml_template.xml"
498 self.core_dest="org.goffi.sat.xml" 498 self.core_dest="org.goffi.sat.xml"
499 self.default_annotation = { 'a{ss}': 'StringDict', 499 self.default_annotation = { 'a{ss}': 'StringDict',
500 'a(sa{ss}as)': 'QList<Contact>', 500 'a(sa{ss}as)': 'QList<Contact>',
501 'a{i(ss)}': 'HistoryT', 501 'a{i(ss)}': 'HistoryT',
502 'a(sss)': 'QList<MenuT>', 502 'a(sss)': 'QList<MenuT>',
538 annot_elt = doc.createElement("annotation") 538 annot_elt = doc.createElement("annotation")
539 annot_elt.setAttribute('name', "com.trolltech.QtDBus.QtTypeName.In%d" % idx) 539 annot_elt.setAttribute('name', "com.trolltech.QtDBus.QtTypeName.In%d" % idx)
540 annot_elt.setAttribute('value', self.default_annotation[arg]) 540 annot_elt.setAttribute('value', self.default_annotation[arg])
541 new_elt.appendChild(annot_elt) 541 new_elt.appendChild(annot_elt)
542 idx+=1 542 idx+=1
543 543
544 if function['sig_out']: 544 if function['sig_out']:
545 arg_elt = doc.createElement('arg') 545 arg_elt = doc.createElement('arg')
546 arg_elt.setAttribute('type', function['sig_out']) 546 arg_elt.setAttribute('type', function['sig_out'])
547 arg_elt.setAttribute('direction', 'out') 547 arg_elt.setAttribute('direction', 'out')
548 new_elt.appendChild(arg_elt) 548 new_elt.appendChild(arg_elt)
573 raise ConstructorError('Unknown constructor type') 573 raise ConstructorError('Unknown constructor type')
574 574
575 class BridgeConstructor: 575 class BridgeConstructor:
576 def __init__(self): 576 def __init__(self):
577 self.options = None 577 self.options = None
578 578
579 def check_options(self): 579 def check_options(self):
580 """Check command line options""" 580 """Check command line options"""
581 _usage=""" 581 _usage="""
582 %prog [options] 582 %prog [options]
583 583
595 help=("Force overwritting of existing files")) 595 help=("Force overwritting of existing files"))
596 parser.add_option("-d", "--debug", action="store_true", default=False, 596 parser.add_option("-d", "--debug", action="store_true", default=False,
597 help=("Add debug information printing")) 597 help=("Add debug information printing"))
598 parser.add_option("--no_unicode", action="store_false", dest="unicode", default=True, 598 parser.add_option("--no_unicode", action="store_false", dest="unicode", default=True,
599 help=("Remove unicode type protection from string results")) 599 help=("Remove unicode type protection from string results"))
600 parser.add_option("--flags", action="store", type="string", 600 parser.add_option("--flags", action="store", type="string",
601 help=("Constructors' specific flags, comma separated")) 601 help=("Constructors' specific flags, comma separated"))
602 602
603 603
604 (self.options, args) = parser.parse_args() 604 (self.options, args) = parser.parse_args()
605 self.options.flags = self.options.flags.split(',') if self.options.flags else [] 605 self.options.flags = self.options.flags.split(',') if self.options.flags else []