1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
|
#############################################################################
#
# Author: Michel F. SANNER
#
# Copyright: M. Sanner TSRI 2000
#
#############################################################################
# $Header: /opt/cvs/python/packages/share1.5/ViewerFramework/serverCommands.py,v 1.19.4.1 2016/02/12 00:29:31 annao Exp $
#
# $Id: serverCommands.py,v 1.19.4.1 2016/02/12 00:29:31 annao Exp $
#
"""
This module implements classes to start a server and to connect to a server.
"""
from ViewerFramework.VFCommand import Command, CommandGUI
try:
import ViewerFramework.imdCommands as imd
imdFound = True
except ImportError:
imdFound = False
from mglutil.popen2Threads import SysCmdInThread
from mglutil.gui.InputForm.Tk.gui import InputForm, InputFormDescr
import Tkinter
import sys, os
if os.name == 'nt': #sys.platform=='win32':
mswin = True
else:
mswin = False
class StartServer(Command):
""" This class implements methods to start a server"""
def checkDependencies(self, vf):
import thread
def doit(self):
import thread
com = self.vf.socketComm
if com.port:
print 'WARNING: server already running on port', com.port
return
self.vf.socketComm.startServer()
thread.start_new(com.acceptClients, (self.vf.clients_cb,))
self.vf.GUI.ROOT.after(300, self.vf.sendViewerState)
# create a threadsafe command queue
from Queue import Queue
self.vf.cmdQueue = Queue(-1) # infinite size
self.vf.GUI.ROOT.after(10, self.vf.runClientCommands)
class WebDrivenTutorial(Command):
"""start a web browser that can send commands over a socket to Viewerframework
We use Karrigell-2.0.3 as a light webserver. The source of Karrigell
need to be install in the python path.
When a server is started a webbrowser is started and display a url which
should point to a file in the web server root dir.
The commands take 2 keywords argument which specify the path to Karrigell
package, and the file to open in the webbrowser.
If not specify, we search the python path to find karrigell package, and give
the top level of the karigell folder as the file to open as a url.
"""
def onExitFromViewer(self):
""" method which will be call when the Viewer is closed"""
# we need to stop the Karigell webserver
if hasattr(self,'cmd'):
if not mswin:
import os,signal
print 'killing process Karrigell'
pid = self.cmd.com.pid
os.kill(pid,signal.SIGKILL)
#self.cmd.com.kill(signal.SIGKILL)
else:
pass
def doit(self,**kw):
import webbrowser
karrigell_path = kw['karrigell_path']
file = kw['file']
if karrigell_path is None:
server_root = self.findKarrigell()
if server_root is None:
self.warningMsg("Karrigell package not install, Webserver not started.")
else:
karrigell_path = server_root
# Karrigell folder should be in python path, we expect version-2.0.3
import os
# we create a absolute path as windows need it to under path
karrigell_start = os.path.realpath(os.path.join(karrigell_path,'Karrigell.py'))
karrigell_init = os.path.realpath(os.path.join(karrigell_path,'Karrigell.ini'))
status = False
port = 8080
status,port = self.startKarrigell(port,karrigell_start,karrigell_init)
if status:
print 'Karrigell started, listenning on port %d'%port
else:
print 'Karrigell could not be started'
return
# web page have to be in the server_root directory which
# is by default karrigell_path
if file is None:
file = ''
url2open = 'http://localhost:%d/'%port+file
webbrowser.open_new(url2open)
def startKarrigell(self,port,karrigell_start,karrigell_init):
""" start the webserver Karrigell on the port specify in input
return False for failure , True for sucess
"""
if hasattr(self,'cmd'):
del(self.cmd)
print "Trying to start Karrigell on port %d"%port
self.cmd = SysCmdInThread("python -u %s -P %d %s "%(karrigell_start,
port,karrigell_init),
hasGui=False)
self.cmd.start()
status = self.checkKarrigellStatus()
if not status:
# print try to start on another port
port = port + 1
if port > 8180:
self.warningMsg("Could not start Karrigell server, no port available")
return False,0
else:
status,port =self.startKarrigell(port,karrigell_start,karrigell_init)
return status,port
def checkKarrigellStatus(self):
# check the status of Karrigell
# did the webserver started, if so we get the port back
#while not self.cmd.output.empty():
while(1):
if not self.cmd.output.empty():
data = self.cmd.output.get(False)
# server fail to start
if 'Address already in use' in data:
return False
# server start success
if 'running on port' in data:
return True
return False
def findKarrigell(self):
""" method which search the path to the Karrigel directory in the
python path"""
import sys,os
karrigell_path =None
for d in sys.path:
dirname = os.path.join(d,'Karrigell-2.0.3')
if os.path.exists(dirname):
karrigell_path = dirname
return karrigell_path
def guiCallback(self):
kw ={}
server_root = self.findKarrigell()
if server_root is None: return
file = self.vf.askFileOpen(types=[('all', '*')],
idir=server_root,
title='Select a web page or folder')
if file is not None:
import string
webpage = string.split(file,'Karrigell-2.0.3')[1]
kw['karrigell_path']=server_root
kw['file'] = webpage
apply(self.doitWrapper,(),kw)
def __call__(self,karrigell_path=None,file=None,**kw):
""" None<-web_tutorial( karrigell_path=None,file=None,**kw)
karrigell_path = path to server_root of Karrigell webserver
file = file or folder to show as url, should be in the webserver_root
"""
kw['karrigell_path'] = karrigell_path
kw['file'] = file
apply(self.doitWrapper,(),kw)
class StartWebControlServer(Command):
""" This class implements methods to start a communication pipe to
receive commands from a web browser"""
def checkDependencies(self, vf):
import thread
def doit(self):
import thread
com = self.vf.webControl
if com.port:
print 'WARNING: server already running on port', com.port
return
com.startServer()
thread.start_new(com.acceptClients, (self.clients_cb,))
# print port number to a file in file pmv_server.pid in the directory where the
# python process was started, if the package Karigell does not exist, otherwise
# save pmv_server.pid in Karrigell folder.
import os,sys
karrigell_path =None
for d in sys.path:
dirname = os.path.join(d,'Karrigell-2.0.3')
if os.path.exists(dirname):
karrigell_path = dirname
if not karrigell_path:
filename = 'pmv_server.pid'
else:
filename = os.path.join(karrigell_path,'pmv_server.pid')
f = open(filename,'w')
f.write('%d'%com.port)
f.close()
from Queue import Queue
self.cmdQueue = Queue(-1) # infinite size
# start checking for messages from the web controler
self.vf.GUI.ROOT.after(10, self.checkForCommands)
def checkForCommands(self, event=None):
"""periodically check for new commands
cmd should be a string where the Viewerframework command is separate by ||
from a tuple representing the args separated by || from a dictonnary
which represent the keyword arguments of commands
example:
'colorByAtomType||'+ '(self.vf.getSelection(), ('lines',))|| {}'
colorByAtmoType: cmd to run
(self.vf.getSelection(), ('lines',)): arguments to pass to cmd
{}: keyword argument to pass to cmd
"""
if not self.cmdQueue.empty():
cmd = self.cmdQueue.get(False) # do not block if queue empty
if cmd:
#print 'got', cmd
w = cmd.split('||')
if self.vf.commands.has_key(w[0]):
# cmd should be a string where the Viewerframework command is separate by |
# from a tuple representing the args separated by | from a dictonnary
# which represent the keyword arguments of commands
# example:
# "colorByAtomType|"+ "(self.vf.getSelection(), ('lines',))| {}"
# colorByAtmoType: cmd to run
# (self.vf.getSelection(), ('lines',)): arguments to pass to cmd
# {}: keyword argument to pass to cmd
args = eval(w[1])
kw = eval(w[2])
apply( self.vf.commands[w[0]], args,kw )
self.vf.GUI.ROOT.after(10, self.checkForCommands)
def clients_cb(self, client, data):
"""get called every time a web page sends a message
The message is sent using Karrigell's Python in Html
"""
# put it in a thread safe queue
self.cmdQueue.put(data)
class ConnectToServer(Command):
""" This class implements method to connect to a server."""
def checkDependencies(self, vf):
import thread
def doit(self):
import thread
idf = InputFormDescr("Viewerframework server connection!")
idf.append({'widgetType':Tkinter.Entry,
'name': 'host','defaultValue':'localhost',
'wcfg':{'label':'Host name or IP'},
'gridcfg':{'sticky':Tkinter.E}
})
idf.append({'widgetType':Tkinter.Entry,
'name': 'port','defaultValue':'50000',
'wcfg':{'label':"Server's Port"},
'gridcfg':{'sticky':Tkinter.E}
})
self.idf = idf
val = self.vf.getUserInput(idf)
self.vf.socketComm.connectToServer(val['host'], int(val['port']),
self.vf.server_cb)
# create a threadsafe command queue
from Queue import Queue
self.vf.cmdQueue = Queue(-1) # infinite size
self.vf.GUI.ROOT.after(10, self.vf.runServerCommands)
if imdFound:
class ConnectToImdServer(Command):
""" This class implements method to connect to a imd server."""
def checkDependencies(self, vf):
import thread
def setup(self,hostname,port,molname,atmslist="",htype="steered"):
self.host = hostname
self.port = port
self.molname = molname
self.atmslist = atmslist
self.htype = htype
def doit(self,gui=True):
import thread
if self.vf.hasGui and gui:
idf = InputFormDescr("Viewerframework imd server connection!")
idf.append({'widgetType':Tkinter.Entry,
'name': 'host','defaultValue':'localhost',
'wcfg':{'label':'Host name or IP'},
'gridcfg':{'sticky':Tkinter.E}
})
idf.append({'widgetType':Tkinter.Entry,
'name': 'port','defaultValue':'2030',
'wcfg':{'label':"Server's Port"},
'gridcfg':{'sticky':Tkinter.E}
})
idf.append({'widgetType':Tkinter.Entry,
'name': 'molname','defaultValue':'',
'wcfg':{'label':"molecule name"},
'gridcfg':{'sticky':Tkinter.E}
})
idf.append({'widgetType':Tkinter.Entry,
'name': 'handler','defaultValue':'',
'wcfg':{'label':"handler atoms"},
'gridcfg':{'sticky':Tkinter.E}
})
idf.append({'widgetType':Tkinter.Entry,
'name': 'htype','defaultValue':'',
'wcfg':{'label':"handler type"},
'gridcfg':{'sticky':Tkinter.E}
})
self.idf = idf
val = self.vf.getUserInput(idf)
mol = self.vf.getMolFromName(val['molname'])
host = val['host']
port = val['port']
atmslist = val['handler'] #exple
htype = val["htype"]
if len(htype) ==0 : htype = "steered"
else :
mol = self.vf.getMolFromName(self.molname)
host = self.host
port = self.port
atmslist = self.atmslist
htype = self.htype
if type(mol) is list :
slot =[]
for m in mol :
m.allAtoms.addConformation(m.allAtoms.coords[:])
slot.append( len(m.allAtoms[0]._coords) - 1)
else :
mol.allAtoms.addConformation(mol.allAtoms.coords[:])
slot = len(mol.allAtoms[0]._coords) - 1
self.vf.browseCommands('imdCommands',package='ViewerFramework', topCommand=0)
#if two molecule
if type(mol) is list :
N=0
for m in mol :
N+=len(m.allAtoms.coords)
self.vf.imd.mindy = True
#setup the file ? pdb, parameters, psf
self.vf.imd.pdbFile = "/local/MGL/MGLTools-1.5.6/MGLToolsPckgs/ARDemo/mindy/two_alanin.pdb"
self.vf.imd.psfFile = "/local/MGL/MGLTools-1.5.6/MGLToolsPckgs/ARDemo/mindy/two_alanin.psf"
self.vf.imd.paraFile = "/local/MGL/MGLTools-1.5.6/MGLToolsPckgs/ARDemo/mindy/alanin.params"
self.vf.imd.fixedAtoms = []
self.vf.imd.init(host, 0,0, int(port), 1 , 0,N )
else :
self.vf.imd.init(host, 0,0, int(port), 1 , 0,len(mol.allAtoms) )
if not self.vf.imd.mindy :
self.vf.imd.imd_pause()
else :
self.vf.imd.mol = mol
self.vf.imd.slot = slot
#self.vf.imd.gui = True
#set coord at time 0
#get all coordinate, and the total count
#i will first translate mol2
# m2 = self.vf.imd.mol[0]
# vt = []
# M=[0.,0,0]
# #vt=util.ApplyMatrix(numpy.array(self.mol2.allAtoms.coords),M)
# for pt in m2.allAtoms.coords:
# ptx = pt[0]+M[0]
# pty = pt[1]+M[1]
# ptz = pt[2]+M[2]
# vt.append( (ptx, pty, ptz) )
#
# m2.allAtoms.updateCoords(vt,ind=0)
coords=[]
N=0
for m in self.vf.imd.mol:
if hasattr(self.vf,'art'):
self.vf.art.doimd = True
from ARViewer import util
import numpy
M = m.pat.mat_transfo
vt=util.ApplyMatrix(numpy.array(m.allAtoms.coords),M,transpose=False)
else :
vt=m.allAtoms.coords[:]
N+=len(m.allAtoms.coords)
coords.extend(vt)
self.vf.imd.N = N
print "sendFcoords"
self.vf.imd.imd_send_fcoords(self.vf.imd.N,coords)
self.vf.browseCommands('handlerCommand',package='ViewerFramework', topCommand=0)
self.vf.handler.isinited = False
if len(atmslist) :
atms = self.vf.select(atmslist)
self.vf.handler.create(atms,forceType=htype)
if self.vf.hasGui and self.vf.imd.gui :
if not self.vf.imd.mindy :
self.vf.imd.start()
print "after"
self.vf.GUI.ROOT.after(1, self.vf.updateIMD)
# add StartServer Command
StartServerGUI = CommandGUI()
StartServerGUI.addMenuCommand('menuRoot', 'File', 'start server',
cascadeName='server',
cascadeBefore='Exit')
# add StartWebControlServer Command
StartWebControlServerGUI = CommandGUI()
StartWebControlServerGUI.addMenuCommand(
'menuRoot', 'File', 'start web controller', cascadeName='server')
# add ConnectToServer Command
ConnectToServerGUI = CommandGUI()
ConnectToServerGUI.addMenuCommand(
'menuRoot', 'File', 'connect to server', cascadeName='server')
# add ConnectToImdServer Command
if imdFound:
ConnectToImdServerGUI = CommandGUI()
ConnectToImdServerGUI.addMenuCommand(
'menuRoot', 'File', 'connect to imd server', cascadeName='server')
# add WebDrivenTutorial Command
WebDrivenTutorialGUI = CommandGUI()
WebDrivenTutorialGUI.addMenuCommand(
'menuRoot', 'File', 'web tutorial')
commandList = [
{'name':'startServer', 'cmd':StartServer(),
'gui': StartServerGUI},
{'name':'connectToServer', 'cmd':ConnectToServer(),
'gui': ConnectToServerGUI},
{'name':'StartWebControlServer', 'cmd':StartWebControlServer(),
'gui': StartWebControlServerGUI},
{'name':'web tutorial', 'cmd':WebDrivenTutorial(),
'gui': WebDrivenTutorialGUI},
]
if imdFound:
commandList.append(
{'name':'connectToImdServer', 'cmd':ConnectToImdServer(),
'gui': ConnectToImdServerGUI})
def initModule(viewer):
for dict in commandList:
# print 'dict',dict
viewer.addCommand(dict['cmd'], dict['name'], dict['gui'])
|