Home | Trees | Indices | Help |
|
---|
|
1 # -*- coding: latin-1 -*- 2 """GNUmed forms classes 3 4 Business layer for printing all manners of forms, letters, scripts etc. 5 6 license: GPL 7 """ 8 #============================================================ 9 __version__ = "$Revision: 1.79 $" 10 __author__ ="Ian Haywood <ihaywood@gnu.org>, karsten.hilbert@gmx.net" 11 12 13 import os, sys, time, os.path, logging, codecs, re as regex 14 import shutil, random, platform, subprocess 15 import socket # needed for OOo on Windows 16 #, libxml2, libxslt 17 18 19 if __name__ == '__main__': 20 sys.path.insert(0, '../../') 21 from Gnumed.pycommon import gmTools, gmBorg, gmMatchProvider, gmExceptions, gmDispatcher 22 from Gnumed.pycommon import gmPG2, gmBusinessDBObject, gmCfg, gmShellAPI, gmMimeLib, gmLog2 23 from Gnumed.business import gmPerson, gmSurgery, gmPersonSearch 24 25 26 _log = logging.getLogger('gm.forms') 27 _log.info(__version__) 28 29 #============================================================ 30 # this order is also used in choice boxes for the engine 31 form_engine_abbrevs = [u'O', u'L', u'I', u'G'] 32 33 form_engine_names = { 34 u'O': 'OpenOffice', 35 u'L': 'LaTeX', 36 u'I': 'Image editor', 37 u'G': 'Gnuplot script' 38 } 39 40 form_engine_template_wildcards = { 41 u'O': u'*.o?t', 42 u'L': u'*.tex', 43 u'G': u'*.gpl' 44 } 45 46 # is filled in further below after each engine is defined 47 form_engines = {} 48 49 #============================================================ 50 # match providers 51 #============================================================5363 #============================================================55 56 query = u""" 57 select name_long, name_long 58 from ref.v_paperwork_templates 59 where name_long %(fragment_condition)s 60 order by name_long 61 """ 62 gmMatchProvider.cMatchProvider_SQL2.__init__(self, queries = [query])6575 #============================================================67 68 query = u""" 69 select name_short, name_short 70 from ref.v_paperwork_templates 71 where name_short %(fragment_condition)s 72 order by name_short 73 """ 74 gmMatchProvider.cMatchProvider_SQL2.__init__(self, queries = [query])7793 #============================================================79 80 query = u""" 81 select * from ( 82 select pk, _(name) as l10n_name from ref.form_types 83 where _(name) %(fragment_condition)s 84 85 union 86 87 select pk, _(name) as l10n_name from ref.form_types 88 where name %(fragment_condition)s 89 ) as union_result 90 order by l10n_name 91 """ 92 gmMatchProvider.cMatchProvider_SQL2.__init__(self, queries = [query])95 96 _cmd_fetch_payload = u'select * from ref.v_paperwork_templates where pk_paperwork_template = %s' 97 98 _cmds_store_payload = [ 99 u"""update ref.paperwork_templates set 100 name_short = %(name_short)s, 101 name_long = %(name_long)s, 102 fk_template_type = %(pk_template_type)s, 103 instance_type = %(instance_type)s, 104 engine = %(engine)s, 105 in_use = %(in_use)s, 106 filename = %(filename)s, 107 external_version = %(external_version)s 108 where 109 pk = %(pk_paperwork_template)s and 110 xmin = %(xmin_paperwork_template)s 111 """, 112 u"""select xmin_paperwork_template from ref.v_paperwork_templates where pk_paperwork_template = %(pk_paperwork_template)s""" 113 ] 114 115 _updatable_fields = [ 116 u'name_short', 117 u'name_long', 118 u'external_version', 119 u'pk_template_type', 120 u'instance_type', 121 u'engine', 122 u'in_use', 123 u'filename' 124 ] 125 126 _suffix4engine = { 127 u'O': u'.ott', 128 u'L': u'.tex', 129 u'T': u'.txt', 130 u'X': u'.xslt', 131 u'I': u'.img' 132 } 133 134 #--------------------------------------------------------200 #============================================================136 """The template itself better not be arbitrarily large unless you can handle that. 137 138 Note that the data type returned will be a buffer.""" 139 140 cmd = u'SELECT data FROM ref.paperwork_templates WHERE pk = %(pk)s' 141 rows, idx = gmPG2.run_ro_queries (queries = [{'cmd': cmd, 'args': {'pk': self.pk_obj}}], get_col_idx = False) 142 143 if len(rows) == 0: 144 raise gmExceptions.NoSuchBusinessObjectError('cannot retrieve data for template pk = %s' % self.pk_obj) 145 146 return rows[0][0]147 148 template_data = property(_get_template_data, lambda x:x) 149 #--------------------------------------------------------151 """Export form template from database into file.""" 152 153 if filename is None: 154 if self._payload[self._idx['filename']] is None: 155 suffix = self.__class__._suffix4engine[self._payload[self._idx['engine']]] 156 else: 157 suffix = os.path.splitext(self._payload[self._idx['filename']].strip())[1].strip() 158 if suffix in [u'', u'.']: 159 suffix = self.__class__._suffix4engine[self._payload[self._idx['engine']]] 160 161 filename = gmTools.get_unique_filename ( 162 prefix = 'gm-%s-Template-' % self._payload[self._idx['engine']], 163 suffix = suffix 164 ) 165 166 data_query = { 167 'cmd': u'SELECT substring(data from %(start)s for %(size)s) FROM ref.paperwork_templates WHERE pk = %(pk)s', 168 'args': {'pk': self.pk_obj} 169 } 170 171 data_size_query = { 172 'cmd': u'select octet_length(data) from ref.paperwork_templates where pk = %(pk)s', 173 'args': {'pk': self.pk_obj} 174 } 175 176 result = gmPG2.bytea2file ( 177 data_query = data_query, 178 filename = filename, 179 data_size_query = data_size_query, 180 chunk_size = chunksize 181 ) 182 if result is False: 183 return None 184 185 return filename186 #--------------------------------------------------------188 gmPG2.file2bytea ( 189 filename = filename, 190 query = u'update ref.paperwork_templates set data = %(data)s::bytea where pk = %(pk)s and xmin = %(xmin)s', 191 args = {'pk': self.pk_obj, 'xmin': self._payload[self._idx['xmin_paperwork_template']]} 192 ) 193 # adjust for xmin change 194 self.refetch_payload()195 #--------------------------------------------------------197 fname = self.export_to_file() 198 engine = form_engines[self._payload[self._idx['engine']]] 199 return engine(template_file = fname)202 cmd = u'select pk from ref.paperwork_templates where name_long = %(lname)s and external_version = %(ver)s' 203 args = {'lname': name_long, 'ver': external_version} 204 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = False) 205 206 if len(rows) == 0: 207 _log.error('cannot load form template [%s - %s]', name_long, external_version) 208 return None 209 210 return cFormTemplate(aPK_obj = rows[0]['pk'])211 #------------------------------------------------------------212 -def get_form_templates(engine=None, active_only=False, template_types=None, excluded_types=None):213 """Load form templates.""" 214 215 args = {'eng': engine, 'in_use': active_only} 216 where_parts = [u'1 = 1'] 217 218 if engine is not None: 219 where_parts.append(u'engine = %(eng)s') 220 221 if active_only: 222 where_parts.append(u'in_use IS true') 223 224 if template_types is not None: 225 args['incl_types'] = tuple(template_types) 226 where_parts.append(u'template_type IN %(incl_types)s') 227 228 if excluded_types is not None: 229 args['excl_types'] = tuple(excluded_types) 230 where_parts.append(u'template_type NOT IN %(excl_types)s') 231 232 cmd = u"SELECT * FROM ref.v_paperwork_templates WHERE %s ORDER BY in_use desc, name_long" % u'\nAND '.join(where_parts) 233 234 rows, idx = gmPG2.run_ro_queries ( 235 queries = [{'cmd': cmd, 'args': args}], 236 get_col_idx = True 237 ) 238 templates = [ cFormTemplate(row = {'pk_field': 'pk_paperwork_template', 'data': r, 'idx': idx}) for r in rows ] 239 240 return templates241 #------------------------------------------------------------243 244 cmd = u'insert into ref.paperwork_templates (fk_template_type, name_short, name_long, external_version) values (%(type)s, %(nshort)s, %(nlong)s, %(ext_version)s)' 245 rows, idx = gmPG2.run_rw_queries ( 246 queries = [ 247 {'cmd': cmd, 'args': {'type': template_type, 'nshort': name_short, 'nlong': name_long, 'ext_version': 'new'}}, 248 {'cmd': u"select currval(pg_get_serial_sequence('ref.paperwork_templates', 'pk'))"} 249 ], 250 return_data = True 251 ) 252 template = cFormTemplate(aPK_obj = rows[0][0]) 253 return template254 #------------------------------------------------------------256 rows, idx = gmPG2.run_rw_queries ( 257 queries = [ 258 {'cmd': u'delete from ref.paperwork_templates where pk=%(pk)s', 'args': {'pk': template['pk_paperwork_template']}} 259 ] 260 ) 261 return True262 #============================================================ 263 # OpenOffice API 264 #============================================================ 265 uno = None 266 cOOoDocumentCloseListener = None 267 268 #-----------------------------------------------------------270 271 try: 272 which = subprocess.Popen ( 273 args = ('which', 'soffice'), 274 stdout = subprocess.PIPE, 275 stdin = subprocess.PIPE, 276 stderr = subprocess.PIPE, 277 universal_newlines = True 278 ) 279 except (OSError, ValueError, subprocess.CalledProcessError): 280 _log.exception('there was a problem executing [which soffice]') 281 return 282 283 soffice_path, err = which.communicate() 284 soffice_path = soffice_path.strip('\n') 285 uno_path = os.path.abspath ( os.path.join ( 286 os.path.dirname(os.path.realpath(soffice_path)), 287 '..', 288 'basis-link', 289 'program' 290 )) 291 292 _log.info('UNO should be at [%s], appending to sys.path', uno_path) 293 294 sys.path.append(uno_path)295 #-----------------------------------------------------------297 """FIXME: consider this: 298 299 try: 300 import uno 301 except: 302 print "This Script needs to be run with the python from OpenOffice.org" 303 print "Example: /opt/OpenOffice.org/program/python %s" % ( 304 os.path.basename(sys.argv[0])) 305 print "Or you need to insert the right path at the top, where uno.py is." 306 print "Default: %s" % default_path 307 """ 308 global uno 309 if uno is not None: 310 return 311 312 try: 313 import uno 314 except ImportError: 315 __configure_path_to_UNO() 316 import uno 317 318 global unohelper, oooXCloseListener, oooNoConnectException, oooPropertyValue 319 320 import unohelper 321 from com.sun.star.util import XCloseListener as oooXCloseListener 322 from com.sun.star.connection import NoConnectException as oooNoConnectException 323 from com.sun.star.beans import PropertyValue as oooPropertyValue 324 325 #---------------------------------- 326 class _cOOoDocumentCloseListener(unohelper.Base, oooXCloseListener): 327 """Listens for events sent by OOo during the document closing 328 sequence and notifies the GNUmed client GUI so it can 329 import the closed document into the database. 330 """ 331 def __init__(self, document=None): 332 self.document = document333 334 def queryClosing(self, evt, owner): 335 # owner is True/False whether I am the owner of the doc 336 pass 337 338 def notifyClosing(self, evt): 339 pass 340 341 def disposing(self, evt): 342 self.document.on_disposed_by_ooo() 343 self.document = None 344 #---------------------------------- 345 346 global cOOoDocumentCloseListener 347 cOOoDocumentCloseListener = _cOOoDocumentCloseListener 348 349 _log.debug('python UNO bridge successfully initialized') 350 351 #------------------------------------------------------------353 """This class handles the connection to OOo. 354 355 Its Singleton instance stays around once initialized. 356 """ 357 # FIXME: need to detect closure of OOo !445 #------------------------------------------------------------359 360 init_ooo() 361 362 #self.ooo_start_cmd = 'oowriter -invisible -accept="socket,host=localhost,port=2002;urp;"' 363 #self.remote_context_uri = "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" 364 365 pipe_name = "uno-gm2ooo-%s" % str(random.random())[2:] 366 self.ooo_start_cmd = 'oowriter -invisible -norestore -accept="pipe,name=%s;urp"' % pipe_name 367 self.remote_context_uri = "uno:pipe,name=%s;urp;StarOffice.ComponentContext" % pipe_name 368 369 _log.debug('pipe name: %s', pipe_name) 370 _log.debug('startup command: %s', self.ooo_start_cmd) 371 _log.debug('remote context URI: %s', self.remote_context_uri) 372 373 self.resolver_uri = "com.sun.star.bridge.UnoUrlResolver" 374 self.desktop_uri = "com.sun.star.frame.Desktop" 375 376 self.local_context = uno.getComponentContext() 377 self.uri_resolver = self.local_context.ServiceManager.createInstanceWithContext(self.resolver_uri, self.local_context) 378 379 self.__desktop = None380 #--------------------------------------------------------382 if self.__desktop is None: 383 _log.debug('no desktop, no cleanup') 384 return 385 386 try: 387 self.__desktop.terminate() 388 except: 389 _log.exception('cannot terminate OOo desktop')390 #--------------------------------------------------------392 """<filename> must be absolute""" 393 394 if self.desktop is None: 395 _log.error('cannot access OOo desktop') 396 return None 397 398 filename = os.path.expanduser(filename) 399 filename = os.path.abspath(filename) 400 document_uri = uno.systemPathToFileUrl(filename) 401 402 _log.debug('%s -> %s', filename, document_uri) 403 404 doc = self.desktop.loadComponentFromURL(document_uri, "_blank", 0, ()) 405 return doc406 #-------------------------------------------------------- 407 # internal helpers 408 #--------------------------------------------------------410 # later factor this out ! 411 dbcfg = gmCfg.cCfgSQL() 412 self.ooo_startup_settle_time = dbcfg.get2 ( 413 option = u'external.ooo.startup_settle_time', 414 workplace = gmSurgery.gmCurrentPractice().active_workplace, 415 bias = u'workplace', 416 default = 3.0 417 )418 #-------------------------------------------------------- 419 # properties 420 #--------------------------------------------------------422 if self.__desktop is not None: 423 return self.__desktop 424 425 try: 426 self.remote_context = self.uri_resolver.resolve(self.remote_context_uri) 427 except oooNoConnectException: 428 _log.exception('cannot connect to OOo server') 429 _log.info('trying to start OOo server') 430 os.system(self.ooo_start_cmd) 431 self.__get_startup_settle_time() 432 _log.debug('waiting %s seconds for OOo to start up', self.ooo_startup_settle_time) 433 time.sleep(self.ooo_startup_settle_time) # OOo sometimes needs a bit 434 try: 435 self.remote_context = self.uri_resolver.resolve(self.remote_context_uri) 436 except oooNoConnectException: 437 _log.exception('cannot start (or connect to started) OOo server') 438 return None 439 440 self.__desktop = self.remote_context.ServiceManager.createInstanceWithContext(self.desktop_uri, self.remote_context) 441 _log.debug('connection seems established') 442 return self.__desktop443 444 desktop = property(_get_desktop, lambda x:x)447552 #-------------------------------------------------------- 553 # internal helpers 554 #-------------------------------------------------------- 555 556 #============================================================449 450 self.template_file = template_file 451 self.instance_type = instance_type 452 self.ooo_doc = None453 #-------------------------------------------------------- 454 # external API 455 #--------------------------------------------------------457 # connect to OOo 458 ooo_srv = gmOOoConnector() 459 460 # open doc in OOo 461 self.ooo_doc = ooo_srv.open_document(filename = self.template_file) 462 if self.ooo_doc is None: 463 _log.error('cannot open document in OOo') 464 return False 465 466 # listen for close events 467 pat = gmPerson.gmCurrentPatient() 468 pat.locked = True 469 listener = cOOoDocumentCloseListener(document = self) 470 self.ooo_doc.addCloseListener(listener) 471 472 return True473 #-------------------------------------------------------- 476 #--------------------------------------------------------478 479 # new style embedded, implicit placeholders 480 searcher = self.ooo_doc.createSearchDescriptor() 481 searcher.SearchCaseSensitive = False 482 searcher.SearchRegularExpression = True 483 searcher.SearchWords = True 484 searcher.SearchString = handler.placeholder_regex 485 486 placeholder_instance = self.ooo_doc.findFirst(searcher) 487 while placeholder_instance is not None: 488 try: 489 val = handler[placeholder_instance.String] 490 except: 491 _log.exception(val) 492 val = _('error with placeholder [%s]') % placeholder_instance.String 493 494 if val is None: 495 val = _('error with placeholder [%s]') % placeholder_instance.String 496 497 placeholder_instance.String = val 498 placeholder_instance = self.ooo_doc.findNext(placeholder_instance.End, searcher) 499 500 if not old_style_too: 501 return 502 503 # old style "explicit" placeholders 504 text_fields = self.ooo_doc.getTextFields().createEnumeration() 505 while text_fields.hasMoreElements(): 506 text_field = text_fields.nextElement() 507 508 # placeholder ? 509 if not text_field.supportsService('com.sun.star.text.TextField.JumpEdit'): 510 continue 511 # placeholder of type text ? 512 if text_field.PlaceHolderType != 0: 513 continue 514 515 replacement = handler[text_field.PlaceHolder] 516 if replacement is None: 517 continue 518 519 text_field.Anchor.setString(replacement)520 #--------------------------------------------------------522 if filename is not None: 523 target_url = uno.systemPathToFileUrl(os.path.abspath(os.path.expanduser(filename))) 524 save_args = ( 525 oooPropertyValue('Overwrite', 0, True, 0), 526 oooPropertyValue('FormatFilter', 0, 'swriter: StarOffice XML (Writer)', 0) 527 528 ) 529 # "store AS url" stores the doc, marks it unmodified and updates 530 # the internal media descriptor - as opposed to "store TO url" 531 self.ooo_doc.storeAsURL(target_url, save_args) 532 else: 533 self.ooo_doc.store()534 #--------------------------------------------------------536 self.ooo_doc.dispose() 537 pat = gmPerson.gmCurrentPatient() 538 pat.locked = False 539 self.ooo_doc = None540 #--------------------------------------------------------542 # get current file name from OOo, user may have used Save As 543 filename = uno.fileUrlToSystemPath(self.ooo_doc.URL) 544 # tell UI to import the file 545 gmDispatcher.send ( 546 signal = u'import_document_from_file', 547 filename = filename, 548 document_type = self.instance_type, 549 unlock_patient = True 550 ) 551 self.ooo_doc = None558 """Ancestor for forms.""" 559 562 #--------------------------------------------------------641 642 #================================================================ 643 # OOo template forms 644 #----------------------------------------------------------------564 """Parse the template into an instance and replace placeholders with values.""" 565 raise NotImplementedError566 #-------------------------------------------------------- 570 #--------------------------------------------------------572 """Generate output suitable for further processing outside this class, e.g. printing.""" 573 raise NotImplementedError574 #-------------------------------------------------------- 579 #--------------------------------------------------------581 """ 582 A sop to TeX which can't act as a true filter: to delete temporary files 583 """ 584 pass585 #--------------------------------------------------------587 """ 588 Executes the provided command. 589 If command cotains %F. it is substituted with the filename 590 Otherwise, the file is fed in on stdin 591 """ 592 pass593 #--------------------------------------------------------595 """Stores the parameters in the backend. 596 597 - link_obj can be a cursor, a connection or a service name 598 - assigning a cursor to link_obj allows the calling code to 599 group the call to store() into an enclosing transaction 600 (for an example see gmReferral.send_referral()...) 601 """ 602 # some forms may not have values ... 603 if params is None: 604 params = {} 605 patient_clinical = self.patient.get_emr() 606 encounter = patient_clinical.active_encounter['pk_encounter'] 607 # FIXME: get_active_episode is no more 608 #episode = patient_clinical.get_active_episode()['pk_episode'] 609 # generate "forever unique" name 610 cmd = "select name_short || ': <' || name_long || '::' || external_version || '>' from paperwork_templates where pk=%s"; 611 rows = gmPG.run_ro_query('reference', cmd, None, self.pk_def) 612 form_name = None 613 if rows is None: 614 _log.error('error retrieving form def for [%s]' % self.pk_def) 615 elif len(rows) == 0: 616 _log.error('no form def for [%s]' % self.pk_def) 617 else: 618 form_name = rows[0][0] 619 # we didn't get a name but want to store the form anyhow 620 if form_name is None: 621 form_name=time.time() # hopefully unique enough 622 # in one transaction 623 queries = [] 624 # - store form instance in form_instance 625 cmd = "insert into form_instances(fk_form_def, form_name, fk_episode, fk_encounter) values (%s, %s, %s, %s)" 626 queries.append((cmd, [self.pk_def, form_name, episode, encounter])) 627 # - store params in form_data 628 for key in params.keys(): 629 cmd = """ 630 insert into form_data(fk_instance, place_holder, value) 631 values ((select currval('form_instances_pk_seq')), %s, %s::text) 632 """ 633 queries.append((cmd, [key, params[key]])) 634 # - get inserted PK 635 queries.append(("select currval ('form_instances_pk_seq')", [])) 636 status, err = gmPG.run_commit('historica', queries, True) 637 if status is None: 638 _log.error('failed to store form [%s] (%s): %s' % (self.pk_def, form_name, err)) 639 return None 640 return status646 """A forms engine wrapping OOo.""" 647656 657 #================================================================ 658 # LaTeX template forms 659 #----------------------------------------------------------------649 super(self.__class__, self).__init__(template_file = template_file) 650 651 652 path, ext = os.path.splitext(self.template_filename) 653 if ext in [r'', r'.']: 654 ext = r'.odt' 655 self.instance_filename = r'%s-instance%s' % (path, ext)661 """A forms engine wrapping LaTeX.""" 662783 #------------------------------------------------------------ 784 form_engines[u'L'] = cLaTeXForm 785 #============================================================ 786 # Gnuplot template forms 787 #------------------------------------------------------------664 super(self.__class__, self).__init__(template_file = template_file) 665 path, ext = os.path.splitext(self.template_filename) 666 if ext in [r'', r'.']: 667 ext = r'.tex' 668 self.instance_filename = r'%s-instance%s' % (path, ext)669 #--------------------------------------------------------671 672 template_file = codecs.open(self.template_filename, 'rU', 'utf8') 673 instance_file = codecs.open(self.instance_filename, 'wb', 'utf8') 674 675 for line in template_file: 676 677 if line.strip() in [u'', u'\r', u'\n', u'\r\n']: 678 instance_file.write(line) 679 continue 680 681 # 1) find placeholders in this line 682 placeholders_in_line = regex.findall(data_source.placeholder_regex, line, regex.IGNORECASE) 683 # 2) and replace them 684 for placeholder in placeholders_in_line: 685 #line = line.replace(placeholder, self._texify_string(data_source[placeholder])) 686 try: 687 val = data_source[placeholder] 688 except: 689 _log.exception(val) 690 val = _('error with placeholder [%s]') % placeholder 691 692 if val is None: 693 val = _('error with placeholder [%s]') % placeholder 694 695 line = line.replace(placeholder, val) 696 697 instance_file.write(line) 698 699 instance_file.close() 700 template_file.close() 701 702 return703 #--------------------------------------------------------705 706 mimetypes = [ 707 u'application/x-latex', 708 u'application/x-tex', 709 u'text/plain' 710 ] 711 712 for mimetype in mimetypes: 713 editor_cmd = gmMimeLib.get_editor_cmd(mimetype, self.instance_filename) 714 715 if editor_cmd is None: 716 editor_cmd = u'sensible-editor %s' % self.instance_filename 717 718 return gmShellAPI.run_command_in_shell(command = editor_cmd, blocking = True)719 #--------------------------------------------------------721 722 if instance_file is None: 723 instance_file = self.instance_filename 724 725 try: 726 open(instance_file, 'r').close() 727 except: 728 _log.exception('cannot access form instance file [%s]', instance_file) 729 gmLog2.log_stack_trace() 730 return None 731 732 self.instance_filename = instance_file 733 734 _log.debug('ignoring <format> directive [%s], generating PDF', format) 735 736 # create sandbox for LaTeX to play in 737 sandbox_dir = os.path.splitext(self.template_filename)[0] 738 _log.debug('LaTeX sandbox directory: [%s]', sandbox_dir) 739 740 old_cwd = os.getcwd() 741 _log.debug('CWD: [%s]', old_cwd) 742 743 gmTools.mkdir(sandbox_dir) 744 745 os.chdir(sandbox_dir) 746 try: 747 sandboxed_instance_filename = os.path.join(sandbox_dir, os.path.split(self.instance_filename)[1]) 748 shutil.move(self.instance_filename, sandboxed_instance_filename) 749 750 # LaTeX can need up to three runs to get cross-references et al right 751 if platform.system() == 'Windows': 752 cmd = r'pdflatex.exe -interaction nonstopmode %s' % sandboxed_instance_filename 753 else: 754 cmd = r'pdflatex -interaction nonstopmode %s' % sandboxed_instance_filename 755 for run in [1, 2, 3]: 756 if not gmShellAPI.run_command_in_shell(command = cmd, blocking = True, acceptable_return_codes = [0, 1]): 757 _log.error('problem running pdflatex, cannot generate form output') 758 gmDispatcher.send(signal = 'statustext', msg = _('Error running pdflatex. Cannot turn LaTeX template into PDF.'), beep = True) 759 os.chdir(old_cwd) 760 return None 761 finally: 762 os.chdir(old_cwd) 763 764 sandboxed_pdf_name = u'%s.pdf' % os.path.splitext(sandboxed_instance_filename)[0] 765 target_dir = os.path.split(self.instance_filename)[0] 766 try: 767 shutil.move(sandboxed_pdf_name, target_dir) 768 except IOError: 769 _log.exception('cannot move sandboxed PDF: %s -> %s', sandboxed_pdf_name, target_dir) 770 gmDispatcher.send(signal = 'statustext', msg = _('Sandboxed PDF output file cannot be moved.'), beep = True) 771 return None 772 773 final_pdf_name = u'%s.pdf' % os.path.splitext(self.instance_filename)[0] 774 775 try: 776 open(final_pdf_name, 'r').close() 777 except IOError: 778 _log.exception('cannot open target PDF: %s', final_pdf_name) 779 gmDispatcher.send(signal = 'statustext', msg = _('PDF output file cannot be opened.'), beep = True) 780 return None 781 782 return final_pdf_name789 """A forms engine wrapping Gnuplot.""" 790 791 #-------------------------------------------------------- 795 #-------------------------------------------------------- 799 #--------------------------------------------------------833 #------------------------------------------------------------ 834 form_engines[u'G'] = cGnuplotForm 835 #------------------------------------------------------------ 836 #------------------------------------------------------------801 """Generate output suitable for further processing outside this class, e.g. printing. 802 803 Expects .data_filename to be set. 804 """ 805 self.conf_filename = gmTools.get_unique_filename(prefix = 'gm2gpl-', suffix = '.conf') 806 fname_file = codecs.open(self.conf_filename, 'wb', 'utf8') 807 fname_file.write('# setting the gnuplot data file\n') 808 fname_file.write("gm2gpl_datafile = '%s'\n" % self.data_filename) 809 fname_file.close() 810 811 # FIXME: cater for configurable path 812 if platform.system() == 'Windows': 813 exec_name = 'gnuplot.exe' 814 else: 815 exec_name = 'gnuplot' 816 817 args = [exec_name, '-p', self.conf_filename, self.template_filename] 818 _log.debug('plotting args: %s' % str(args)) 819 820 try: 821 gp = subprocess.Popen ( 822 args = args, 823 close_fds = True 824 ) 825 except (OSError, ValueError, subprocess.CalledProcessError): 826 _log.exception('there was a problem executing gnuplot') 827 gmDispatcher.send(signal = u'statustext', msg = _('Error running gnuplot. Cannot plot data.'), beep = True) 828 return 829 830 gp.communicate() 831 832 return838 """A forms engine wrapping LaTeX. 839 """ 843896 897 898 899 900 #================================================================ 901 # define a class for HTML forms (for printing) 902 #================================================================845 try: 846 latex = Cheetah.Template.Template (self.template, filter=LaTeXFilter, searchList=[params]) 847 # create a 'sandbox' directory for LaTeX to play in 848 self.tmp = tempfile.mktemp () 849 os.makedirs (self.tmp) 850 self.oldcwd = os.getcwd () 851 os.chdir (self.tmp) 852 stdin = os.popen ("latex", "w", 2048) 853 stdin.write (str (latex)) #send text. LaTeX spits it's output into stdout 854 # FIXME: send LaTeX output to the logger 855 stdin.close () 856 if not gmShellAPI.run_command_in_shell("dvips texput.dvi -o texput.ps", blocking=True): 857 raise FormError ('DVIPS returned error') 858 except EnvironmentError, e: 859 _log.error(e.strerror) 860 raise FormError (e.strerror) 861 return file ("texput.ps")862864 """ 865 For testing purposes, runs Xdvi on the intermediate TeX output 866 WARNING: don't try this on Windows 867 """ 868 gmShellAPI.run_command_in_shell("xdvi texput.dvi", blocking=True)869871 if "%F" in command: 872 command.replace ("%F", "texput.ps") 873 else: 874 command = "%s < texput.ps" % command 875 try: 876 if not gmShellAPI.run_command_in_shell(command, blocking=True): 877 _log.error("external command %s returned non-zero" % command) 878 raise FormError ('external command %s returned error' % command) 879 except EnvironmentError, e: 880 _log.error(e.strerror) 881 raise FormError (e.strerror) 882 return True883885 command, set1 = gmCfg.getDBParam (workplace = self.workplace, option = 'main.comms.print') 886 self.exe (command)887904 """This class can create XML document from requested data, 905 then process it with XSLT template and display results 906 """ 907 908 # FIXME: make the path configurable ? 909 _preview_program = u'oowriter ' #this program must be in the system PATH 910987 988 989 #===================================================== 990 #class LaTeXFilter(Cheetah.Filters.Filter):912 913 if template is None: 914 raise ValueError(u'%s: cannot create form instance without a template' % __name__) 915 916 cFormEngine.__init__(self, template = template) 917 918 self._FormData = None 919 920 # here we know/can assume that the template was stored as a utf-8 921 # encoded string so use that conversion to create unicode: 922 #self._XSLTData = unicode(str(template.template_data), 'UTF-8') 923 # but in fact, unicode() knows how to handle buffers, so simply: 924 self._XSLTData = unicode(self.template.template_data, 'UTF-8', 'strict') 925 926 # we must still devise a method of extracting the SQL query: 927 # - either by retrieving it from a particular tag in the XSLT or 928 # - by making the stored template actually be a dict which, unpickled, 929 # has the keys "xslt" and "sql" 930 self._SQL_query = u'select 1' #this sql query must output valid xml931 #-------------------------------------------------------- 932 # external API 933 #--------------------------------------------------------935 """get data from backend and process it with XSLT template to produce readable output""" 936 937 # extract SQL (this is wrong but displays what is intended) 938 xslt = libxml2.parseDoc(self._XSLTData) 939 root = xslt.children 940 for child in root: 941 if child.type == 'element': 942 self._SQL_query = child.content 943 break 944 945 # retrieve data from backend 946 rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': self._SQL_query, 'args': sql_parameters}], get_col_idx = False) 947 948 __header = '<?xml version="1.0" encoding="UTF-8"?>\n' 949 __body = rows[0][0] 950 951 # process XML data according to supplied XSLT, producing HTML 952 self._XMLData =__header + __body 953 style = libxslt.parseStylesheetDoc(xslt) 954 xml = libxml2.parseDoc(self._XMLData) 955 html = style.applyStylesheet(xml, None) 956 self._FormData = html.serialize() 957 958 style.freeStylesheet() 959 xml.freeDoc() 960 html.freeDoc()961 #--------------------------------------------------------963 if self._FormData is None: 964 raise ValueError, u'Preview request for empty form. Make sure the form is properly initialized and process() was performed' 965 966 fname = gmTools.get_unique_filename(prefix = u'gm_XSLT_form-', suffix = u'.html') 967 #html_file = os.open(fname, 'wb') 968 #html_file.write(self._FormData.encode('UTF-8')) 969 html_file = codecs.open(fname, 'wb', 'utf8', 'strict') # or 'replace' ? 970 html_file.write(self._FormData) 971 html_file.close() 972 973 cmd = u'%s %s' % (self.__class__._preview_program, fname) 974 975 if not gmShellAPI.run_command_in_shell(command = cmd, blocking = False): 976 _log.error('%s: cannot launch report preview program' % __name__) 977 return False 978 979 #os.unlink(self.filename) #delete file 980 #FIXME: under Windows the temp file is deleted before preview program gets it (under Linux it works OK) 981 982 return True983 #--------------------------------------------------------1030 1031 1032 #=========================================================== 1035 1036 #============================================================ 1037 # convenience functions 1038 #------------------------------------------------------------993 """ 994 Convience function to escape ISO-Latin-1 strings for TeX output 995 WARNING: not all ISO-Latin-1 characters are expressible in TeX 996 FIXME: nevertheless, there are a few more we could support 997 998 Also intelligently convert lists and tuples into TeX-style table lines 999 """ 1000 if type (item) is types.UnicodeType or type (item) is types.StringType: 1001 item = item.replace ("\\", "\\backslash") # I wonder about this, do we want users to be able to use raw TeX? 1002 item = item.replace ("&", "\\&") 1003 item = item.replace ("$", "\\$") 1004 item = item.replace ('"', "") # okay, that's not right, but easiest solution for now 1005 item = item.replace ("\n", "\\\\ ") 1006 if len (item.strip ()) == 0: 1007 item = "\\relax " # sometimes TeX really hates empty strings, this seems to mollify it 1008 # FIXME: cover all of ISO-Latin-1 which can be expressed in TeX 1009 if type (item) is types.UnicodeType: 1010 item = item.encode ('latin-1', 'replace') 1011 trans = {'ß':'\\ss{}', 'ä': '\\"{a}', 'Ä' :'\\"{A}', 'ö': '\\"{o}', 'Ö': '\\"{O}', 'ü': '\\"{u}', 'Ü': '\\"{U}', 1012 '\x8a':'\\v{S}', '\x8a':'\\OE{}', '\x9a':'\\v{s}', '\x9c': '\\oe{}', '\a9f':'\\"{Y}', #Microsloth extensions 1013 '\x86': '{\\dag}', '\x87': '{\\ddag}', '\xa7':'{\\S}', '\xb6': '{\\P}', '\xa9': '{\\copyright}', '\xbf': '?`', 1014 '\xc0':'\\`{A}', '\xa1': "\\'{A}", '\xa2': '\\^{A}', '\xa3':'\\~{A}', '\\xc5': '{\AA}', 1015 '\xc7':'\\c{C}', '\xc8':'\\`{E}', 1016 '\xa1': '!`', 1017 '\xb5':'$\mu$', '\xa3': '\pounds{}', '\xa2':'cent'} 1018 for k, i in trans.items (): 1019 item = item.replace (k, i) 1020 elif type (item) is types.ListType or type (item) is types.TupleType: 1021 item = string.join ([self.filter (i, ' & ') for i in item], table_sep) 1022 elif item is None: 1023 item = '\\relax % Python None\n' 1024 elif type (item) is types.IntType or type (item) is types.FloatType: 1025 item = str (item) 1026 else: 1027 item = str (item) 1028 _log.warning("unknown type %s, string %s" % (type (item), item)) 1029 return item1040 """ 1041 Instantiates a FormEngine based on the form ID or name from the backend 1042 """ 1043 try: 1044 # it's a number: match to form ID 1045 id = int (id) 1046 cmd = 'select template, engine, pk from paperwork_templates where pk = %s' 1047 except ValueError: 1048 # it's a string, match to the form's name 1049 # FIXME: can we somehow OR like this: where name_short=%s OR name_long=%s ? 1050 cmd = 'select template, engine, flags, pk from paperwork_templates where name_short = %s' 1051 result = gmPG.run_ro_query ('reference', cmd, None, id) 1052 if result is None: 1053 _log.error('error getting form [%s]' % id) 1054 raise gmExceptions.FormError ('error getting form [%s]' % id) 1055 if len(result) == 0: 1056 _log.error('no form [%s] found' % id) 1057 raise gmExceptions.FormError ('no such form found [%s]' % id) 1058 if result[0][1] == 'L': 1059 return LaTeXForm (result[0][2], result[0][0]) 1060 elif result[0][1] == 'T': 1061 return TextForm (result[0][2], result[0][0]) 1062 else: 1063 _log.error('no form engine [%s] for form [%s]' % (result[0][1], id)) 1064 raise FormError ('no engine [%s] for form [%s]' % (result[0][1], id))1065 #------------------------------------------------------------- 1072 #------------------------------------------------------------- 1073 1074 test_letter = """ 1075 \\documentclass{letter} 1076 \\address{ $DOCTOR \\\\ 1077 $DOCTORADDRESS} 1078 \\signature{$DOCTOR} 1079 1080 \\begin{document} 1081 \\begin{letter}{$RECIPIENTNAME \\\\ 1082 $RECIPIENTADDRESS} 1083 1084 \\opening{Dear $RECIPIENTNAME} 1085 1086 \\textbf{Re:} $PATIENTNAME, DOB: $DOB, $PATIENTADDRESS \\\\ 1087 1088 $TEXT 1089 1090 \\ifnum$INCLUDEMEDS>0 1091 \\textbf{Medications List} 1092 1093 \\begin{tabular}{lll} 1094 $MEDSLIST 1095 \\end{tabular} 1096 \\fi 1097 1098 \\ifnum$INCLUDEDISEASES>0 1099 \\textbf{Disease List} 1100 1101 \\begin{tabular}{l} 1102 $DISEASELIST 1103 \\end{tabular} 1104 \\fi 1105 1106 \\closing{$CLOSING} 1107 1108 \\end{letter} 1109 \\end{document} 1110 """ 1111 11121114 f = open('../../test-area/ian/terry-form.tex') 1115 params = { 1116 'RECIPIENT': "Dr. R. Terry\n1 Main St\nNewcastle", 1117 'DOCTORSNAME': 'Ian Haywood', 1118 'DOCTORSADDRESS': '1 Smith St\nMelbourne', 1119 'PATIENTNAME':'Joe Bloggs', 1120 'PATIENTADDRESS':'18 Fred St\nMelbourne', 1121 'REQUEST':'echocardiogram', 1122 'THERAPY':'on warfarin', 1123 'CLINICALNOTES':"""heard new murmur 1124 Here's some 1125 crap to demonstrate how it can cover multiple lines.""", 1126 'COPYADDRESS':'Karsten Hilbert\nLeipzig, Germany', 1127 'ROUTINE':1, 1128 'URGENT':0, 1129 'FAX':1, 1130 'PHONE':1, 1131 'PENSIONER':1, 1132 'VETERAN':0, 1133 'PADS':0, 1134 'INSTRUCTIONS':u'Take the blue pill, Neo' 1135 } 1136 form = LaTeXForm (1, f.read()) 1137 form.process (params) 1138 form.xdvi () 1139 form.cleanup ()11401142 form = LaTeXForm (2, test_letter) 1143 params = {'RECIPIENTNAME':'Dr. Richard Terry', 1144 'RECIPIENTADDRESS':'1 Main St\nNewcastle', 1145 'DOCTOR':'Dr. Ian Haywood', 1146 'DOCTORADDRESS':'1 Smith St\nMelbourne', 1147 'PATIENTNAME':'Joe Bloggs', 1148 'PATIENTADDRESS':'18 Fred St, Melbourne', 1149 'TEXT':"""This is the main text of the referral letter""", 1150 'DOB':'12/3/65', 1151 'INCLUDEMEDS':1, 1152 'MEDSLIST':[["Amoxycillin", "500mg", "TDS"], ["Perindopril", "4mg", "OD"]], 1153 'INCLUDEDISEASES':0, 'DISEASELIST':'', 1154 'CLOSING':'Yours sincerely,' 1155 } 1156 form.process (params) 1157 print os.getcwd () 1158 form.xdvi () 1159 form.cleanup ()1160 #------------------------------------------------------------1162 template = open('../../test-area/ian/Formularkopf-DE.tex') 1163 form = LaTeXForm(template=template.read()) 1164 params = { 1165 'PATIENT LASTNAME': 'Kirk', 1166 'PATIENT FIRSTNAME': 'James T.', 1167 'PATIENT STREET': 'Hauptstrasse', 1168 'PATIENT ZIP': '02999', 1169 'PATIENT TOWN': 'Gross Saerchen', 1170 'PATIENT DOB': '22.03.1931' 1171 } 1172 form.process(params) 1173 form.xdvi() 1174 form.cleanup()1175 1176 #============================================================ 1177 # main 1178 #------------------------------------------------------------ 1179 if __name__ == '__main__': 1180 1181 if len(sys.argv) < 2: 1182 sys.exit() 1183 1184 if sys.argv[1] != 'test': 1185 sys.exit() 1186 1187 from Gnumed.pycommon import gmI18N, gmDateTime 1188 gmI18N.activate_locale() 1189 gmI18N.install_domain(domain='gnumed') 1190 gmDateTime.init() 1191 1192 #-------------------------------------------------------- 1193 # OOo 1194 #--------------------------------------------------------1196 init_ooo()1197 #-------------------------------------------------------- 1202 #--------------------------------------------------------1204 srv = gmOOoConnector() 1205 doc = srv.open_document(filename = sys.argv[2]) 1206 print "document:", doc1207 #--------------------------------------------------------1209 doc = cOOoLetter(template_file = sys.argv[2]) 1210 doc.open_in_ooo() 1211 print "document:", doc 1212 raw_input('press <ENTER> to continue') 1213 doc.show() 1214 #doc.replace_placeholders() 1215 #doc.save_in_ooo('~/test_cOOoLetter.odt') 1216 # doc = None 1217 # doc.close_in_ooo() 1218 raw_input('press <ENTER> to continue')1219 #--------------------------------------------------------1221 try: 1222 doc = open_uri_in_ooo(filename=sys.argv[1]) 1223 except: 1224 _log.exception('cannot open [%s] in OOo' % sys.argv[1]) 1225 raise 1226 1227 class myCloseListener(unohelper.Base, oooXCloseListener): 1228 def disposing(self, evt): 1229 print "disposing:"1230 def notifyClosing(self, evt): 1231 print "notifyClosing:" 1232 def queryClosing(self, evt, owner): 1233 # owner is True/False whether I am the owner of the doc 1234 print "queryClosing:" 1235 1236 l = myCloseListener() 1237 doc.addCloseListener(l) 1238 1239 tfs = doc.getTextFields().createEnumeration() 1240 print tfs 1241 print dir(tfs) 1242 while tfs.hasMoreElements(): 1243 tf = tfs.nextElement() 1244 if tf.supportsService('com.sun.star.text.TextField.JumpEdit'): 1245 print tf.getPropertyValue('PlaceHolder') 1246 print " ", tf.getPropertyValue('Hint') 1247 1248 # doc.close(True) # closes but leaves open the dedicated OOo window 1249 doc.dispose() # closes and disposes of the OOo window 1250 #--------------------------------------------------------1252 pat = gmPersonSearch.ask_for_patient() 1253 if pat is None: 1254 return 1255 gmPerson.set_active_patient(patient = pat) 1256 1257 doc = cOOoLetter(template_file = sys.argv[2]) 1258 doc.open_in_ooo() 1259 print doc 1260 doc.show() 1261 #doc.replace_placeholders() 1262 #doc.save_in_ooo('~/test_cOOoLetter.odt') 1263 doc = None 1264 # doc.close_in_ooo() 1265 raw_input('press <ENTER> to continue')1266 #-------------------------------------------------------- 1267 # other 1268 #--------------------------------------------------------1270 template = cFormTemplate(aPK_obj = sys.argv[2]) 1271 print template 1272 print template.export_to_file()1273 #--------------------------------------------------------1275 template = cFormTemplate(aPK_obj = sys.argv[2]) 1276 template.update_template_from_file(filename = sys.argv[3])1277 #--------------------------------------------------------1279 pat = gmPersonSearch.ask_for_patient() 1280 if pat is None: 1281 return 1282 gmPerson.set_active_patient(patient = pat) 1283 1284 gmPerson.gmCurrentProvider(provider = gmPerson.cStaff()) 1285 1286 path = os.path.abspath(sys.argv[2]) 1287 form = cLaTeXForm(template_file = path) 1288 1289 from Gnumed.wxpython import gmMacro 1290 ph = gmMacro.gmPlaceholderHandler() 1291 ph.debug = True 1292 instance_file = form.substitute_placeholders(data_source = ph) 1293 pdf_name = form.generate_output(instance_file = instance_file) 1294 print "final PDF file is:", pdf_name1295 1296 #-------------------------------------------------------- 1297 #-------------------------------------------------------- 1298 # now run the tests 1299 #test_au() 1300 #test_de() 1301 1302 # OOo 1303 #test_init_ooo() 1304 #test_ooo_connect() 1305 #test_open_ooo_doc_from_srv() 1306 #test_open_ooo_doc_from_letter() 1307 #play_with_ooo() 1308 #test_cOOoLetter() 1309 1310 #test_cFormTemplate() 1311 #set_template_from_file() 1312 test_latex_form() 1313 1314 #============================================================ 1315
Home | Trees | Indices | Help |
|
---|
Generated by Epydoc 3.0.1 on Thu Mar 17 03:57:25 2011 | http://epydoc.sourceforge.net |