Package Skype4Py :: Package API :: Module posix_x11
[frames] | no frames]

Source Code for Module Skype4Py.API.posix_x11

  1  ''' 
  2  Low level Skype for Linux interface implemented 
  3  using XWindows messaging. Uses direct Xlib calls 
  4  through ctypes module. 
  5   
  6  This module handles the options that you can pass to L{ISkype.__init__<skype.ISkype.__init__>} 
  7  for Linux machines when the transport is set to X11. 
  8   
  9  No further options are currently supported. 
 10  ''' 
 11   
 12  import threading 
 13  from ctypes import * 
 14  from ctypes.util import find_library 
 15  import time 
 16  from Skype4Py.API import ICommand, _ISkypeAPIBase 
 17  from Skype4Py.enums import * 
 18  from Skype4Py.errors import ISkypeAPIError 
 19   
 20   
 21  # some Xlib constants 
 22  _PropertyChangeMask = 0x400000 
 23  _PropertyNotify = 28 
 24  _ClientMessage = 33 
 25  _PropertyNewValue = 0 
 26  _PropertyDelete = 1 
 27   
 28   
 29  # some Xlib types 
 30  c_ulong_p = POINTER(c_ulong) 
 31  DisplayP = c_void_p 
 32  Atom = c_ulong 
 33  AtomP = c_ulong_p 
 34  XID = c_ulong 
 35  Window = XID 
 36  Bool = c_int 
 37  Status = c_int 
 38  Time = c_ulong 
 39  c_int_p = POINTER(c_int) 
 40   
 41   
 42  # should the structures be aligned to 8 bytes? 
 43  _align = (sizeof(c_long) == 8 and sizeof(c_int) == 4) 
 44   
 45   
 46  # some Xlib structures 
47 -class _XClientMessageEvent(Structure):
48 if _align: 49 _fields_ = [('type', c_int), 50 ('pad0', c_int), 51 ('serial', c_ulong), 52 ('send_event', Bool), 53 ('pad1', c_int), 54 ('display', DisplayP), 55 ('window', Window), 56 ('message_type', Atom), 57 ('format', c_int), 58 ('pad2', c_int), 59 ('data', c_char * 20)] 60 else: 61 _fields_ = [('type', c_int), 62 ('serial', c_ulong), 63 ('send_event', Bool), 64 ('display', DisplayP), 65 ('window', Window), 66 ('message_type', Atom), 67 ('format', c_int), 68 ('data', c_char * 20)]
69
70 -class _XPropertyEvent(Structure):
71 if _align: 72 _fields_ = [('type', c_int), 73 ('pad0', c_int), 74 ('serial', c_ulong), 75 ('send_event', Bool), 76 ('pad1', c_int), 77 ('display', DisplayP), 78 ('window', Window), 79 ('atom', Atom), 80 ('time', Time), 81 ('state', c_int), 82 ('pad2', c_int)] 83 else: 84 _fields_ = [('type', c_int), 85 ('serial', c_ulong), 86 ('send_event', Bool), 87 ('display', DisplayP), 88 ('window', Window), 89 ('atom', Atom), 90 ('time', Time), 91 ('state', c_int)]
92
93 -class _XErrorEvent(Structure):
94 if _align: 95 _fields_ = [('type', c_int), 96 ('pad0', c_int), 97 ('display', DisplayP), 98 ('resourceid', XID), 99 ('serial', c_ulong), 100 ('error_code', c_ubyte), 101 ('request_code', c_ubyte), 102 ('minor_code', c_ubyte)] 103 else: 104 _fields_ = [('type', c_int), 105 ('display', DisplayP), 106 ('resourceid', XID), 107 ('serial', c_ulong), 108 ('error_code', c_ubyte), 109 ('request_code', c_ubyte), 110 ('minor_code', c_ubyte)]
111
112 -class _XEvent(Union):
113 if _align: 114 _fields_ = [('type', c_int), 115 ('xclient', _XClientMessageEvent), 116 ('xproperty', _XPropertyEvent), 117 ('xerror', _XErrorEvent), 118 ('pad', c_long * 24)] 119 else: 120 _fields_ = [('type', c_int), 121 ('xclient', _XClientMessageEvent), 122 ('xproperty', _XPropertyEvent), 123 ('xerror', _XErrorEvent), 124 ('pad', c_long * 24)]
125 126 XEventP = POINTER(_XEvent) 127 128 129 # Xlib error handler type 130 XErrorHandlerP = CFUNCTYPE(c_int, DisplayP, POINTER(_XErrorEvent)) 131 132
133 -class _ISkypeAPI(_ISkypeAPIBase):
134 - def __init__(self, handler, opts):
135 _ISkypeAPIBase.__init__(self, opts) 136 self.RegisterHandler(handler) 137 138 # check options 139 if opts: 140 raise TypeError('Unexpected parameter(s): %s' % ', '.join(opts.keys())) 141 142 # setup Xlib 143 libpath = find_library('X11') 144 if not libpath: 145 raise ImportError('Could not find X11 library') 146 self.x11 = cdll.LoadLibrary(libpath) 147 148 # setup Xlib function prototypes 149 self.x11.XCloseDisplay.argtypes = (DisplayP,) 150 self.x11.XCloseDisplay.restype = None 151 self.x11.XCreateSimpleWindow.argtypes = (DisplayP, Window, c_int, c_int, c_uint, 152 c_uint, c_uint, c_ulong, c_ulong) 153 self.x11.XCreateSimpleWindow.restype = Window 154 self.x11.XDefaultRootWindow.argtypes = (DisplayP,) 155 self.x11.XDefaultRootWindow.restype = Window 156 self.x11.XDeleteProperty.argtypes = (DisplayP, Window, Atom) 157 self.x11.XDeleteProperty.restype = None 158 self.x11.XDestroyWindow.argtypes = (DisplayP, Window) 159 self.x11.XDestroyWindow.restype = None 160 self.x11.XFlush.argtypes = (DisplayP,) 161 self.x11.XFlush.restype = None 162 self.x11.XGetAtomName.argtypes = (DisplayP, Atom) 163 self.x11.XGetAtomName.restype = c_char_p 164 self.x11.XGetErrorText.argtypes = (DisplayP, c_int, c_char_p, c_int) 165 self.x11.XGetErrorText.restype = None 166 self.x11.XGetWindowProperty.argtypes = (DisplayP, Window, Atom, c_long, c_long, Bool, 167 Atom, AtomP, c_int_p, c_ulong_p, c_ulong_p, POINTER(POINTER(Window))) 168 self.x11.XGetWindowProperty.restype = c_int 169 self.x11.XInitThreads.argtypes = () 170 self.x11.XInitThreads.restype = Status 171 self.x11.XInternAtom.argtypes = (DisplayP, c_char_p, Bool) 172 self.x11.XInternAtom.restype = Atom 173 self.x11.XNextEvent.argtypes = (DisplayP, XEventP) 174 self.x11.XNextEvent.restype = None 175 self.x11.XOpenDisplay.argtypes = (c_char_p,) 176 self.x11.XOpenDisplay.restype = DisplayP 177 self.x11.XSelectInput.argtypes = (DisplayP, Window, c_long) 178 self.x11.XSelectInput.restype = None 179 self.x11.XSendEvent.argtypes = (DisplayP, Window, Bool, c_long, XEventP) 180 self.x11.XSendEvent.restype = Status 181 self.x11.XSetErrorHandler.argtypes = (XErrorHandlerP,) 182 self.x11.XSetErrorHandler.restype = None 183 184 # init Xlib 185 self.x11.XInitThreads() 186 self.error = None 187 # callback has to be saved to keep reference to bound method 188 self._error_handler_callback = XErrorHandlerP(self._error_handler) 189 self.x11.XSetErrorHandler(self._error_handler_callback) 190 self.disp = self.x11.XOpenDisplay(None) 191 if not self.disp: 192 raise ISkypeAPIError('Could not open XDisplay') 193 self.win_root = self.x11.XDefaultRootWindow(self.disp) 194 self.win_self = self.x11.XCreateSimpleWindow(self.disp, self.win_root, 195 100, 100, 100, 100, 1, 0, 0) 196 self.x11.XSelectInput(self.disp, self.win_root, _PropertyChangeMask) 197 self.win_skype = self.get_skype() 198 ctrl = 'SKYPECONTROLAPI_MESSAGE' 199 self.atom_msg = self.x11.XInternAtom(self.disp, ctrl, False) 200 self.atom_msg_begin = self.x11.XInternAtom(self.disp, ctrl + '_BEGIN', False) 201 self.atom_stop_loop = self.x11.XInternAtom(self.disp, 'STOP_LOOP', False)
202
203 - def __del__(self):
204 if hasattr(self, 'x11'): 205 if hasattr(self, 'disp'): 206 if hasattr(self, 'win_self'): 207 self.x11.XDestroyWindow(self.disp, self.win_self) 208 self.x11.XCloseDisplay(self.disp)
209
210 - def run(self):
211 self.DebugPrint('thread started') 212 # main loop 213 event = _XEvent() 214 data = '' 215 while True: 216 self.x11.XNextEvent(self.disp, byref(event)) 217 if event.type == _ClientMessage: 218 if event.xclient.format == 8: 219 if event.xclient.message_type == self.atom_msg_begin: 220 data = str(event.xclient.data) 221 elif event.xclient.message_type == self.atom_msg: 222 if data != '': 223 data += str(event.xclient.data) 224 else: 225 print 'Warning! Middle of message received with no beginning!' 226 elif event.xclient.message_type == self.atom_stop_loop: 227 break 228 if len(event.xclient.data) != 20 and data: 229 self.notify(data.decode('utf-8')) 230 data = '' 231 elif event.type == _PropertyNotify: 232 if self.x11.XGetAtomName(self.disp, event.xproperty.atom) == '_SKYPE_INSTANCE': 233 if event.xproperty.state == _PropertyNewValue: 234 self.win_skype = self.get_skype() 235 # changing attachment status can cause an event handler to be fired, in 236 # turn it could try to call Attach() and doing this immediately seems to 237 # confuse Skype (command '#0 NAME xxx' returns '#0 CONNSTATUS OFFLINE' :D); 238 # to fix this, we give Skype some time to initialize itself 239 time.sleep(1.0) 240 self.SetAttachmentStatus(apiAttachAvailable) 241 elif event.xproperty.state == _PropertyDelete: 242 self.win_skype = None 243 self.SetAttachmentStatus(apiAttachNotAvailable) 244 self.DebugPrint('thread finished')
245
246 - def _error_handler(self, disp, error):
247 # called from within Xlib when error occures 248 self.error = error.contents.error_code 249 self.DebugPrint('Xlib error', self.error) 250 # stop all pending commands 251 for command in self.Commands.values(): 252 if hasattr(command, '_event'): 253 command._event.set() 254 return 0
255
256 - def error_check(self):
257 '''Checks last Xlib error and raises an exception if needed.''' 258 if self.error != None: 259 if self.error == 3: # BadWindow 260 self.win_skype = None 261 self.SetAttachmentStatus(apiAttachNotAvailable) 262 buf = create_string_buffer(256) 263 self.x11.XGetErrorText(self.disp, self.error, buf, 256) 264 error = ISkypeAPIError('X11 error: %s' % buf.value) 265 self.error = None 266 raise error
267
268 - def get_skype(self):
269 '''Returns Skype window ID or None if Skype not running.''' 270 skype_inst = self.x11.XInternAtom(self.disp, '_SKYPE_INSTANCE', True) 271 type_ret = Atom() 272 format_ret = c_int() 273 nitems_ret = c_ulong() 274 bytes_after_ret = c_ulong() 275 winp = pointer(Window()) 276 fail = self.x11.XGetWindowProperty(self.disp, self.win_root, skype_inst, 277 0, 1, False, 33, byref(type_ret), byref(format_ret), 278 byref(nitems_ret), byref(bytes_after_ret), byref(winp)) 279 if not fail and self.error == None and format_ret.value == 32 and nitems_ret.value == 1: 280 return winp.contents.value
281
282 - def Close(self):
283 event = _XEvent() 284 event.xclient.type = _ClientMessage 285 event.xclient.display = self.disp 286 event.xclient.window = self.win_self 287 event.xclient.message_type = self.atom_stop_loop 288 event.xclient.format = 8 289 self.x11.XSendEvent(self.disp, self.win_self, True, 0, byref(event)) 290 self.x11.XFlush(self.disp) 291 while self.isAlive(): 292 time.sleep(0.01) 293 self.DebugPrint('closed')
294
295 - def SetFriendlyName(self, FriendlyName):
296 self.FriendlyName = FriendlyName 297 if self.AttachmentStatus == apiAttachSuccess: 298 # reattach with the new name 299 self.SetAttachmentStatus(apiAttachUnknown) 300 self.Attach()
301
302 - def Attach(self, Timeout=30000, Wait=True):
303 if self.AttachmentStatus == apiAttachSuccess: 304 return 305 if not self.isAlive(): 306 try: 307 self.start() 308 except AssertionError: 309 raise ISkypeAPIError('Skype API closed') 310 try: 311 self.wait = True 312 def ftimeout(): 313 self.wait = False
314 t = threading.Timer(Timeout / 1000.0, ftimeout) 315 if Wait: 316 t.start() 317 while self.wait: 318 self.win_skype = self.get_skype() 319 if self.win_skype != None: 320 break 321 else: 322 time.sleep(1.0) 323 else: 324 raise ISkypeAPIError('Skype attach timeout') 325 finally: 326 t.cancel() 327 c = ICommand(-1, 'NAME %s' % self.FriendlyName, '', True, Timeout) 328 self.SendCommand(c, True) 329 if c.Reply != 'OK': 330 self.win_skype = None 331 self.SetAttachmentStatus(apiAttachRefused) 332 return 333 self.SendCommand(ICommand(-1, 'PROTOCOL %s' % self.Protocol), True) 334 self.SetAttachmentStatus(apiAttachSuccess)
335
336 - def IsRunning(self):
337 return self.get_skype() != None
338
339 - def Start(self, Minimized=False, Nosplash=False):
340 # options are not supported as of Skype 1.4 Beta for Linux 341 if not self.IsRunning(): 342 import os 343 if os.fork() == 0: # we're the child 344 os.setsid() 345 os.execlp('skype')
346
347 - def Shutdown(self):
348 import os 349 from signal import SIGINT 350 fh = os.popen('ps -o %p --no-heading -C skype') 351 pid = fh.readline().strip() 352 fh.close() 353 if pid: 354 os.kill(int(pid), SIGINT) 355 # Skype sometimes doesn't delete the '_SKYPE_INSTANCE' property 356 skype_inst = self.x11.XInternAtom(self.disp, '_SKYPE_INSTANCE', True) 357 self.x11.XDeleteProperty(self.disp, self.win_root, skype_inst) 358 self.win_skype = None 359 self.SetAttachmentStatus(apiAttachNotAvailable)
360
361 - def SendCommand(self, Command, Force=False):
362 if self.AttachmentStatus != apiAttachSuccess and not Force: 363 self.Attach(Command.Timeout) 364 self.CommandsStackPush(Command) 365 self.CallHandler('send', Command) 366 com = u'#%d %s' % (Command.Id, Command.Command) 367 self.DebugPrint('->', repr(com)) 368 if Command.Blocking: 369 Command._event = bevent = threading.Event() 370 else: 371 Command._timer = timer = threading.Timer(Command.Timeout / 1000.0, self.CommandsStackPop, (Command.Id,)) 372 event = _XEvent() 373 event.xclient.type = _ClientMessage 374 event.xclient.display = self.disp 375 event.xclient.window = self.win_self 376 event.xclient.message_type = self.atom_msg_begin 377 event.xclient.format = 8 378 com = unicode(com).encode('utf-8') + '\x00' 379 for i in xrange(0, len(com), 20): 380 event.xclient.data = com[i:i+20] 381 if self.x11.XSendEvent(self.disp, self.win_skype, False, 0, byref(event)) == 0: 382 self.error_check() 383 event.xclient.message_type = self.atom_msg 384 self.x11.XSync(self.disp, False) 385 self.error_check() 386 if Command.Blocking: 387 bevent.wait(Command.Timeout / 1000.0) 388 self.error_check() 389 if not bevent.isSet(): 390 raise ISkypeAPIError('Skype command timeout') 391 else: 392 timer.start()
393
394 - def notify(self, com):
395 self.DebugPrint('<-', repr(com)) 396 # Called by main loop for all received Skype commands. 397 if com.startswith(u'#'): 398 p = com.find(u' ') 399 Command = self.CommandsStackPop(int(com[1:p])) 400 if Command: 401 Command.Reply = com[p + 1:] 402 if Command.Blocking: 403 Command._event.set() 404 del Command._event 405 else: 406 Command._timer.cancel() 407 del Command._timer 408 self.CallHandler('rece', Command) 409 else: 410 self.CallHandler('rece_api', com[p + 1:]) 411 else: 412 self.CallHandler('rece_api', com)
413