OpenStructure
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
init.py
Go to the documentation of this file.
1 import __main__
2 import sys
3 import os.path
4 import optparse
5 from ost import io, mol, seq, geom, conop, gui, settings, gfx
6 
7 import ost
8 try:
9  from ost import img
10  import ost.img.alg
11  _img_present=True
12 except ImportError:
13  _img_present=False
14  pass
15 import httplib
16 
17 from PyQt4 import QtGui, QtCore
18 from ost.gui.scene.init_inspector import _InitInspector
19 from ost.gui.init_menubar import _InitMenuBar
20 from ost.gui.init_spacenav import _InitSpaceNav
21 from ost.gui.init_context_menu import _InitContextMenu
22 from ost.gui.init_splash import _InitSplash
23 from ost.gui.dng import termuse
24 from ost.gui.dng import superpositiondialog
25 from ost.gui.scene.remote import RemoteLoader
26 
27 import ost.gui.dng.menu
28 from PyQt4.QtGui import *
29 def _my_exit(code):
30  QtGui.QApplication.instance().quit()
31  gui.GostyApp.Instance().ProcessEvents()
32  sys._exit(code)
33 
34 sys._exit=sys.exit
35 sys.exit=_my_exit
36 
37 def _InitRuleBasedBuilder():
38  compound_lib_path=os.path.join(ost.GetSharedDataPath(), 'compounds.chemlib')
39  if os.path.exists(compound_lib_path):
40  conop_inst=conop.Conopology.Instance()
41  compound_lib=conop.CompoundLib.Load(compound_lib_path)
42  conop_inst.RegisterBuilder(conop.RuleBasedBuilder(compound_lib), 'RBB')
43  conop_inst.SetDefaultBuilder('RBB')
44 
45 # switch to rule-based builder for high fidelity if compounds.chemlib is
46 # available
47 _InitRuleBasedBuilder()
48 
49 def _CheckRestore():
50  settings = QtCore.QSettings()
51  restore = settings.value("restore_settings",QtCore.QVariant(False)).toBool()
52  if not restore:
53  settings.clear()
54  settings.setValue("restore_settings",QtCore.QVariant(True))
55 
56 def _InitPanels(app):
57  panels = app.perspective.panels
58  panels.AddWidgetToPool('ost.gui.FileBrowser', -1)
59  panels.AddWidgetToPool('ost.gui.PythonShell', 1)
60  panels.AddWidgetToPool('ost.gui.SceneWin', 1)
61  panels.AddWidgetToPool('ost.gui.SequenceViewer', 1)
62  panels.AddWidgetToPool('ost.gui.MessageWidget', 1)
63  if not panels.Restore("ui/perspective/panels"):
64  panels.AddWidget(gui.PanelPosition.LEFT_PANEL, app.scene_win)
65  panels.AddWidgetByName(gui.PanelPosition.LEFT_PANEL,
66  'ost.gui.FileBrowser', False)
67  panels.AddWidget(gui.PanelPosition.BOTTOM_PANEL, app.seq_viewer)
68  panels.AddWidget(gui.PanelPosition.BOTTOM_PANEL, app.py_shell)
69  panels.AddWidget(gui.PanelPosition.RIGHT_PANEL, app.message_widget)
70  return False
71  return True
72 
73 
74 def _InitFrontEnd(try_stereo):
75  _CheckRestore()
76  app=gui.GostyApp.Instance()
77  app.SetAppTitle("DNG")
78  app.TryStereo(try_stereo)
79  main_area=app.perspective.main_area
80  _InitSpaceNav(app)
81  _InitContextMenu(app)
82  main_area.AddPersistentWidget("3D Scene", "gl_win" , app.gl_win,
83  int(QtCore.Qt.WindowMaximized))
84  _InitInspector(app)
86  app.perspective.Restore()
87  additional_modules=getattr(__main__, 'ADDITIONAL_GUI_MODULES', [])
88  for module_name in additional_modules:
89  __import__(module_name)
90  app.ProcessEvents()
91 
92 
93 
94  if not _InitPanels(app):
95  _InitSplash()
96 
97 def _load_files():
98  for pdb_id in options.pdb_ids:
99  pdb_id, sel=_SplitIDSel(pdb_id)
100  selection=_get_selection_query(sel)
101  gui.FileLoader.LoadFrom(pdb_id,"pdb.org",selection)
102 
103  input_files=[_SplitIDSel(arg) for arg in loading_list]
104  for f in input_files:
105  selection=_get_selection_query(f[1])
106  gui.FileLoader.LoadObject(f[0],selection)
107 
108 def _get_selection_query(sel):
109  if len(options.query)>0:
110  if len(sel)>0:
111  return '(%s) and (%s)' % (options.query, sel)
112  else:
113  return options.query
114  elif len(sel)>0:
115  return sel
116  return ""
117 
118 def _execute_script():
119  script=script_argv[0]
120  sys_argv_backup=sys.argv
121  sys.argv=script_argv
122  try:
123  execfile(script, __main__.__dict__)
124  finally:
125  sys.argv=sys_argv_backup
126 
127 def show_help(option, opt, value, parser):
128  parser.print_help()
129  QtGui.QApplication.instance().exit()
130  sys.exit(-1)
131 
132 def parse_script_option(option, opt, value, parser):
133  script_argv.append(value)
134  for arg in parser.rargs:
135  script_argv.append(arg)
136  del parser.rargs[0:len(parser.rargs)]
137 
138 def _SplitIDSel(name):
139  pos=name.find('[')
140  if pos>-1:
141  return name[:pos], name[pos+1:-1]
142  return name, ''
143 
144 def stop():
145  gui.GostyApp.Instance().StopScript()
146 
147 
148 loading_list=[]
149 script_argv=[]
150 #images=[]
151 #viewers=[]
152 usage = 'usage: dng [options] [files to load]'
153 class OstOptionParser(optparse.OptionParser):
154  def __init__(self, **kwargs):
155  optparse.OptionParser.__init__(self, **kwargs)
156  def exit(self, status_code, error_message):
157  print error_message,
158  QtGui.QApplication.instance().exit()
159  sys.exit(-1)
160 
161 parser=OstOptionParser(usage=usage,conflict_handler="resolve")
162 parser.add_option("-h", "--help", action="callback", callback=show_help, help="show this help message and exit")
163 parser.add_option("-v", "--verbosity_level", action="store", type="int", dest="vlevel", default=2,
164  help="sets the verbosity level [default: %default]")
165 parser.add_option("-s", "--script", action="callback", default=[], dest="script", type="string", callback=parse_script_option, help="executes a script (syntax: -s SCRIPT [options] [args]) Anything that follows this option is passed to the script")
166 parser.add_option("-p", "--pdb_id", dest="pdb_ids", default=[],action="append", help="PDB file ID. The file will be retrieved from PDB")
167 parser.add_option("-b", "--builder", dest="builder", default="HEURISTIC", help="Type of builder used by the progam (either RULE_BASED or HEURISTIC) [default: %default]")
168 parser.add_option("-c", "--compound_library", dest="complib", default="compounds.chemlib", help="Compound library for the RULE_BASED builder (only used if --builder option is set to RULE_BASED, otherwise ignored [default: %default]")
169 parser.add_option("-q", "--query", dest="query", default="", help="Selection query to be highlighted automatically upon loading (only used together with -p option or when a PDB file is loaded, otherwise ignored [default: None]")
170 parser.add_option("-S","--stereo", dest="try_stereo", default=False, action="store_true",help="try to get a quad-buffer stereo visual")
171 parser.disable_interspersed_args()
172 (options, args) = parser.parse_args()
173 
174 if len(parser.rargs)!=0:
175  for rargs_string in parser.rargs:
176  if not rargs_string.endswith('.py'):
177  loading_list.append(rargs_string)
178  else:
179  print 'Error: one of the files to load is a Python script, use -s flag to execute it\n'
180  QtGui.QApplication.instance().exit()
181  sys.exit(-1)
182 
183 if len(options.script)!=0:
184  script_argv=options.script
185 
186 if options.builder=="RULE_BASED":
187  from ost import conop
188  compound_lib=conop.CompoundLib.Load(options.complib)
189  rbb=conop.RuleBasedBuilder(compound_lib)
190  conop.Conopology.Instance().RegisterBuilder(rbb,'rbb')
191  conop.Conopology.Instance().SetDefaultBuilder('rbb')
192 
193 home = os.getenv('HOME') or os.getenv('USERPROFILE')
194 _ostrc=os.path.join(home, '.ostrc')
195 if os.path.exists(_ostrc):
196  try:
197  exec(open(_ostrc))
198  except Exception, e:
199  print e
200 else:
201  rcfile=open(_ostrc,"w")
202  print >> rcfile, '# This python file is parsed by ost and dng at startup'
203  print >> rcfile, '# Its content is made available in the global namespace'
204  print >> rcfile, '# It can be used to define custom variables and functions'
205  print >> rcfile, '# For example:'
206  print >> rcfile, '# IMPORTANT_DIR="path/to/important/dir"'
207  rcfile.close()
208 
209 ost.gui.PushVerbosityLevel(options.vlevel)
210 working_dir=settings.GetValue("DNG_WORKING_DIR",None)
211 
212 if working_dir != None and os.path.isdir(working_dir):
213  os.chdir(working_dir)
214 
215 _InitFrontEnd(options.try_stereo)
216 
217 if len(loading_list)!=0 or len(options.pdb_ids)!=0:
218  _load_files()
219  gfx.Scene().Autoslab()
220 if len(script_argv)!=0:
221  _execute_script()