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

Source Code for Module Skype4Py.API.windows

  1  ''' 
  2  Low level Skype for Windows interface implemented 
  3  using Windows messaging. Uses direct WinAPI 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 Windows machines. 
  8   
  9  No options are currently supported. 
 10  ''' 
 11   
 12  import threading 
 13  import time 
 14  import weakref 
 15  from ctypes import * 
 16  from Skype4Py.API import ICommand, _ISkypeAPIBase 
 17  from Skype4Py.enums import * 
 18  from Skype4Py.errors import ISkypeAPIError 
 19   
 20  try: 
 21      WNDPROC = WINFUNCTYPE(c_long, c_int, c_uint, c_int, c_int) 
 22  except NameError: 
 23      # This will allow importing of this module on non-Windows machines. It won't work 
 24      # of course but this will allow building documentation on any platform. 
 25      WNDPROC = c_void_p 
 26   
27 -class _WNDCLASS(Structure):
28 _fields_ = [('style', c_uint), 29 ('lpfnWndProc', WNDPROC), 30 ('cbClsExtra', c_int), 31 ('cbWndExtra', c_int), 32 ('hInstance', c_int), 33 ('hIcon', c_int), 34 ('hCursor', c_int), 35 ('hbrBackground', c_int), 36 ('lpszMenuName', c_char_p), 37 ('lpszClassName', c_char_p)]
38 39
40 -class _MSG(Structure):
41 _fields_ = [('hwnd', c_int), 42 ('message', c_uint), 43 ('wParam', c_int), 44 ('lParam', c_int), 45 ('time', c_int), 46 ('pointX', c_long), 47 ('pointY', c_long)]
48 49
50 -class _COPYDATASTRUCT(Structure):
51 _fields_ = [('dwData', POINTER(c_uint)), 52 ('cbData', c_uint), 53 ('lpData', c_char_p)]
54 PCOPYDATASTRUCT = POINTER(_COPYDATASTRUCT) 55 56 _WM_QUIT = 0x12 57 _WM_COPYDATA = 0x4A 58 59 _HWND_BROADCAST = 0xFFFF 60 61 62
63 -class _ISkypeAPI(_ISkypeAPIBase):
64 - def __init__(self, handler, opts):
65 _ISkypeAPIBase.__init__(self, opts) 66 if opts: 67 raise TypeError('Unexpected parameter(s): %s' % ', '.join(opts.keys())) 68 self.hwnd = None 69 self.Skype = None 70 self.RegisterHandler(handler) 71 self._SkypeControlAPIDiscover = windll.user32.RegisterWindowMessageA('SkypeControlAPIDiscover') 72 self._SkypeControlAPIAttach = windll.user32.RegisterWindowMessageA('SkypeControlAPIAttach') 73 windll.user32.GetWindowLongA.restype = c_ulong 74 self.start() 75 # wait till the thread initializes 76 while not self.hwnd: 77 time.sleep(0.01)
78
79 - def run(self):
80 self.DebugPrint('thread started') 81 if not self.CreateWindow(): 82 self.hwnd = None 83 return 84 85 Msg = _MSG() 86 pMsg = pointer(Msg) 87 while self.hwnd and windll.user32.GetMessageA(pMsg, self.hwnd, 0, 0): 88 windll.user32.TranslateMessage(pMsg) 89 windll.user32.DispatchMessageA(pMsg) 90 91 self.DestroyWindow() 92 self.hwnd = None 93 self.DebugPrint('thread finished')
94
95 - def Close(self):
96 # if there are no active handlers 97 if self.NumOfHandlers() == 0: 98 if self.hwnd: 99 windll.user32.PostMessageA(self.hwnd, _WM_QUIT, 0, 0) 100 while self.hwnd: 101 time.sleep(0.01) 102 self.Skype = None 103 self.DebugPrint('closed')
104
105 - def SetFriendlyName(self, FriendlyName):
106 self.FriendlyName = FriendlyName 107 if self.Skype: 108 self.SendCommand(ICommand(-1, 'NAME %s' % FriendlyName))
109
110 - def GetForegroundWindow(self):
111 fhwnd = windll.user32.GetForegroundWindow() 112 if fhwnd: 113 # awahlig (7.05.2008): 114 # I've found at least one app (RocketDock) that had window style 8 set. 115 # This is odd since windows header files do not contain such a style. 116 # Doing message exchange while this window is a foreground one, causes 117 # lockups if some operations on client UI are involved (for example 118 # sending a 'FOCUS' command). Therefore, we will set our window as 119 # the foreground one for the transmission time. 120 if windll.user32.GetWindowLongA(fhwnd, -16) & 8 == 0: 121 fhwnd = None 122 return fhwnd
123
124 - def Attach(self, Timeout=30000, Wait=True):
125 if self.Skype: 126 return 127 if not self.isAlive(): 128 raise ISkypeAPIError('Skype API closed') 129 self.DebugPrint('->', 'SkypeControlAPIDiscover') 130 fhwnd = self.GetForegroundWindow() 131 try: 132 if fhwnd: 133 windll.user32.SetForegroundWindow(self.hwnd) 134 if not windll.user32.SendMessageTimeoutA(_HWND_BROADCAST, self._SkypeControlAPIDiscover, 135 self.hwnd, None, 2, 5000, None): 136 raise ISkypeAPIError('Could not broadcast Skype discover message') 137 # wait (with timeout) till the WindProc() attaches 138 self.Wait = True 139 def ftimeout(): 140 self.Wait = False
141 t = threading.Timer(Timeout / 1000, ftimeout) 142 if Wait: 143 t.start() 144 while self.Wait and self.AttachmentStatus not in (apiAttachSuccess, apiAttachRefused): 145 if self.AttachmentStatus == apiAttachPendingAuthorization: 146 # disable the timeout 147 t.cancel() 148 elif self.AttachmentStatus == apiAttachAvailable: 149 # rebroadcast 150 self.DebugPrint('->', 'SkypeControlAPIDiscover') 151 windll.user32.SetForegroundWindow(self.hwnd) 152 if not windll.user32.SendMessageTimeoutA(_HWND_BROADCAST, self._SkypeControlAPIDiscover, 153 self.hwnd, None, 2, 5000, None): 154 raise ISkypeAPIError('Could not broadcast Skype discover message') 155 time.sleep(0.01) 156 t.cancel() 157 finally: 158 if fhwnd: 159 windll.user32.SetForegroundWindow(fhwnd) 160 # check if we got the Skype window's hwnd 161 if self.Skype: 162 self.SendCommand(ICommand(-1, 'PROTOCOL %s' % self.Protocol)) 163 elif not self.Wait: 164 raise ISkypeAPIError('Skype attach timeout')
165
166 - def IsRunning(self):
167 return bool(windll.user32.FindWindowA('SkypeWindowClass2', None))
168
169 - def get_skype_path(self):
170 key = c_long() 171 # try to find Skype in HKEY_CURRENT_USER registry tree 172 if windll.advapi32.RegOpenKeyA(0x80000001, 'Software\\Skype\\Phone', byref(key)) != 0: 173 # try to find Skype in HKEY_LOCAL_MACHINE registry tree 174 if windll.advapi32.RegOpenKeyA(0x80000002, 'Software\\Skype\\Phone', byref(key)) != 0: 175 raise ISkypeAPIError('Skype not installed') 176 pathlen = c_long(512) 177 path = create_string_buffer(pathlen.value) 178 if windll.advapi32.RegQueryValueExA(key, 'SkypePath', None, None, path, byref(pathlen)) != 0: 179 windll.advapi32.RegCloseKey(key) 180 raise ISkypeAPIError('Cannot find Skype path') 181 windll.advapi32.RegCloseKey(key) 182 return path.value
183
184 - def Start(self, Minimized=False, Nosplash=False):
185 args = [] 186 if Minimized: 187 args.append('/MINIMIZED') 188 if Nosplash: 189 args.append('/NOSPLASH') 190 try: 191 if self.hwnd: 192 fhwnd = self.GetForegroundWindow() 193 if fhwnd: 194 windll.user32.SetForegroundWindow(self.hwnd) 195 if windll.shell32.ShellExecuteA(None, 'open', self.get_skype_path(), ' '.join(args), None, 0) <= 32: 196 raise ISkypeAPIError('Could not start Skype') 197 finally: 198 if self.hwnd and fhwnd: 199 windll.user32.SetForegroundWindow(fhwnd)
200
201 - def Shutdown(self):
202 try: 203 if self.hwnd: 204 fhwnd = self.GetForegroundWindow() 205 if fhwnd: 206 windll.user32.SetForegroundWindow(self.hwnd) 207 if windll.shell32.ShellExecuteA(None, 'open', self.get_skype_path(), '/SHUTDOWN', None, 0) <= 32: 208 raise ISkypeAPIError('Could not shutdown Skype') 209 finally: 210 if self.hwnd and fhwnd: 211 windll.user32.SetForegroundWindow(fhwnd)
212
213 - def CreateWindow(self):
214 # window class has to be saved as property to keep reference to self.WinProc 215 self.window_class = _WNDCLASS(3, WNDPROC(self.WinProc), 0, 0, 216 windll.kernel32.GetModuleHandleA(None), 217 0, 0, 0, None, 'Skype4Py.%d' % id(self)) 218 219 wclass = windll.user32.RegisterClassA(byref(self.window_class)) 220 if wclass == 0: 221 return False 222 223 self.hwnd = windll.user32.CreateWindowExA(0, 'Skype4Py.%d' % id(self), 'Skype4Py', 224 0xCF0000, 0x80000000, 0x80000000, 225 0x80000000, 0x80000000, None, None, 226 self.window_class.hInstance, 0) 227 if self.hwnd == 0: 228 windll.user32.UnregisterClassA('Skype4Py.%d' % id(self), None) 229 return False 230 231 return True
232
233 - def DestroyWindow(self):
234 if not windll.user32.DestroyWindow(self.hwnd): 235 return False 236 237 if not windll.user32.UnregisterClassA('Skype4Py.%d' % id(self), None): 238 return False 239 240 return True
241
242 - def WinProc(self, hwnd, uMsg, wParam, lParam):
243 if uMsg == self._SkypeControlAPIAttach: 244 self.DebugPrint('<-', 'SkypeControlAPIAttach', lParam) 245 if lParam == apiAttachSuccess: 246 self.Skype = wParam 247 elif lParam in (apiAttachRefused, apiAttachNotAvailable, apiAttachAvailable): 248 self.Skype = None 249 self.SetAttachmentStatus(lParam) 250 return 1 251 elif uMsg == _WM_COPYDATA and wParam == self.Skype and lParam: 252 copydata = cast(lParam, PCOPYDATASTRUCT).contents 253 com8 = copydata.lpData[:copydata.cbData - 1] 254 com = com8.decode('utf-8') 255 self.DebugPrint('<-', repr(com)) 256 if com.startswith(u'#'): 257 p = com.find(u' ') 258 Command = self.CommandsStackPop(int(com[1:p])) 259 if Command: 260 Command.Reply = com[p + 1:] 261 if Command.Blocking: 262 Command._event.set() 263 del Command._event 264 else: 265 Command._timer.cancel() 266 del Command._timer 267 self.CallHandler('rece', Command) 268 else: 269 self.CallHandler('rece_api', com[p + 1:]) 270 else: 271 self.CallHandler('rece_api', com) 272 return 1 273 elif uMsg == apiAttachAvailable: 274 self.DebugPrint('<-', 'apiAttachAvailable') 275 self.Skype = None 276 self.SetAttachmentStatus(uMsg) 277 return 1 278 return windll.user32.DefWindowProcA(c_int(hwnd), c_int(uMsg), c_int(wParam), c_int(lParam))
279
280 - def SendCommand(self, Command):
281 for retry in xrange(2): 282 if not self.Skype: 283 self.Attach(Command.Timeout) 284 self.CommandsStackPush(Command) 285 self.CallHandler('send', Command) 286 com = u'#%d %s' % (Command.Id, Command.Command) 287 com8 = com.encode('utf-8') + '\0' 288 copydata = _COPYDATASTRUCT(None, len(com8), com8) 289 if Command.Blocking: 290 Command._event = event = threading.Event() 291 else: 292 Command._timer = timer = threading.Timer(Command.Timeout / 1000.0, self.CommandsStackPop, (Command.Id,)) 293 self.DebugPrint('->', repr(com)) 294 fhwnd = self.GetForegroundWindow() 295 try: 296 if fhwnd: 297 windll.user32.SetForegroundWindow(self.hwnd) 298 if windll.user32.SendMessageA(self.Skype, _WM_COPYDATA, self.hwnd, byref(copydata)): 299 if Command.Blocking: 300 event.wait(Command.Timeout / 1000.0) 301 if not event.isSet(): 302 raise ISkypeAPIError('Skype command timeout') 303 else: 304 timer.start() 305 break 306 else: 307 self.CommandsStackPop(Command.Id) 308 self.Skype = None 309 # let the loop go back and try to reattach but only once 310 finally: 311 if fhwnd: 312 windll.user32.SetForegroundWindow(fhwnd) 313 else: 314 raise ISkypeAPIError('Skype API error, check if Skype wasn\'t closed')
315