summaryrefslogtreecommitdiff
path: root/python/ldtp2
blob: 8207d4ff4b6b66f61ea10c4a529b571889acf4f3 (plain)
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
#!/usr/bin/env python
#############################################################################
#
#  Linux Desktop Testing Project http://ldtp.freedesktop.org
# 
#  Author:
#     Nagappan Alagappan <nagappan@gmail.com>
# 
#  Copyright 2004 - 2007 Novell, Inc.
#  Copyright 2008 - 2009 Nagappan Alagappan
# 
#  This library is free software; you can redistribute it and/or
#  modify it under the terms of the GNU Library General Public
#  License as published by the Free Software Foundation; either
#  version 2 of the License, or (at your option) any later version.
# 
#  This library is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#  Library General Public License for more details.
# 
#  You should have received a copy of the GNU Library General Public
#  License along with this library; if not, write to the
#  Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
#  Boston, MA 02110, USA.
#
#############################################################################

__author__ = "Nagappan Alagappan <nagappan@gmail.com>"
# __maintainer__ = "Nagappan Alagappan"
__version__ = "1.5.1"

import re
import os
import sys
import xml
import time
import signal
import threading
import traceback
from xml.sax import saxutils
from xml.parsers.expat import ExpatError
from xml.dom.minidom import parse, parseString

# Let us not register our application under at-spi application list
os.environ ['GTK_MODULES'] = ''

try:
    # Try importing pyatspi
    import pyatspi as atspi, Accessibility
except ImportError:
    # If not use orca atspi module
    import atspi
    import Accessibility

from ldtplib import *
from ldtplib.ldtplibutils import *
from ldtplib.ldtpcommon import *

_ldtpDebug = os.getenv ('LDTP_DEBUG')

def __shutdownAndExit (signum, frame):
    try:
        atspi.Registry ().stop ()
    except RuntimeError:
        pass
    if _ldtpDebug:
        print "Goodbye."

class SearchObjInfo:
    def __init__ (self, key = None, window = False, pattern = None):
        self.key     = key
        self.window  = window
        self.pattern = pattern

class UnknLabelProperty:
    def __init__ (self, appmapType = True, childIndex = -1, parentName = None, objName = None):
        self.appmapType = appmapType
        self.childIndex = childIndex
        self.parentName = parentName
        self.objName    = objName

class CommPacket:
    def __init__ (self, clientFd):
        self.clientFd = clientFd
        self.timeDelay = os.getenv ('LDTP_DELAY_CMD')

    def generatenotificationxml (self, windowName, objectName, objectType, eventType,
                                 timeElapsed, key = None, data = None, detail1 = None,
                                 detail2 = None):
        """This Function will generate some information to LDTP packet
        INPUT: windowname, objectname, objecttype, eventtype[, key[, data]]

        OUTPUT: returns a string in the LDTP packet (XML lib2) format"""
        _xml = '<?xml version=\"1.0\"?>' ## should this header be there in the packets?
        _xml += '<NOTIFICATION>'
        # Fill action name
        _xml = _xml + '<WINDOWNAME>' + saxutils.escape (windowName) + '</WINDOWNAME>'
        _xml = _xml + '<OBJECTNAME>' + saxutils.escape (objectName) + '</OBJECTNAME>'
        _xml = _xml + '<OBJECTTYPE>' + objectType + '</OBJECTTYPE>'
        _xml = _xml + '<EVENTTYPE>' + eventType + '</EVENTTYPE>'
        _xml = _xml + '<TIMEELAPSED>' + str (timeElapsed) + '</TIMEELAPSED>'
        if key:
            _xml = _xml + '<KEY>' + saxutils.escape (key) + '</KEY>'
        if data:
            _xml = _xml + '<DATA>' + saxutils.escape (data) + '</DATA>'
        if detail1:
            _xml = _xml + '<DETAIL1>' + str (detail1) + '</DETAIL1>'
        if detail2:
            _xml = _xml + '<DETAIL2>' + str (detail2) + '</DETAIL2>'
        _xml += '</NOTIFICATION>'
        return _xml

    def generateresponsexml (self, requestId, status, data = None):
        """This Function will generate some information to LDTP packet
        INPUT: windowname, objectname, objecttype, eventtype[, key[, data]]

        OUTPUT: returns a string in the LDTP packet (XML lib2) format"""
	
        _xml = '<?xml version=\"1.0\"?><RESPONSE>'
        # Fill action name
        if requestId:
            _xml += '<ID>%s</ID>' %  requestId
        _xml += '<STATUS><CODE>%s</CODE><MESSAGE>%s</MESSAGE></STATUS>' % (str (status [0]),
                                                                           status [1])
        if data:
            _xml += '<DATA><LENGTH>%d</LENGTH><VALUE><![CDATA[%s]]></VALUE></DATA>' % (len (data), data)
        _xml += '</RESPONSE>'
        return _xml

    def parsexml (self, xmlpacket):
        """Returns the value obtained from the clients LDTP packet"""
        _requestCommand = 0
        _context        = None
        _component      = None
        _requestId      = None
        _requestObj     = None
        _argumentList   = []

        try:
            dom = parseString (xmlpacket)
            try:
                _requestObj  = dom.getElementsByTagName ('REQUEST')[0]
            except IndexError:
                if _ldtpDebug:
                    print 'Invalid request'
                return None
            try:
                _requestCommand = int (getText (_requestObj.getElementsByTagName ('ACTION') [0].childNodes))
            except ValueError:
                if _ldtpDebug:
                    print 'Invalid Command'
                return None
            except IndexError:
                if _ldtpDebug:
                    print 'Invalid Command'
                return None
            try:
                _requestId  = getText (_requestObj.getElementsByTagName ('ID') [0].childNodes)
            except IndexError:
                pass
            try:
                _context = getText (_requestObj.getElementsByTagName ('CONTEXT') [0].childNodes)
            except ValueError:
                pass
            except IndexError:
                # In getapplist, getwindowlist context will be None
                pass
            try:
                _component = getText (_requestObj.getElementsByTagName ('COMPONENT') [0].childNodes)
            except ValueError:
                pass
            except IndexError:
                # In getapplist, getwindowlist, guiexist, etc component will be None
                pass
            try:
                _arguments = dom.getElementsByTagName ('ARGUMENTS')
                if _arguments == None:
                    raise LdtpExecutionError ('Invalid Argument List')
                for dataelements in _arguments:
                    for data in dataelements.getElementsByTagName ('ARGUMENT'):
                        _argumentList.append (getText (data.childNodes))
            except IndexError:
                # _argumentList will be []
                pass
        except ExpatError, msg:
            if msg.code == xml.parsers.expat.errors.XML_ERROR_NO_ELEMENTS:
                return None
            if xml.parsers.expat.ErrorString (msg.code) == xml.parsers.expat.errors.XML_ERROR_NO_ELEMENTS:
                return None
        # Return all the respective values, let the calling function decide what to do with the values
        return _requestId, _requestCommand, _context, _component, _argumentList

    # Send given packet to server
    def send (self, msg):
        return sendpacket (msg, self.clientFd)

    def recv (self):
        return recvpacket (self.clientFd)

class ClientThread:
    def __init__ (self, clientFd, registry):
        self.data      = None
        self.error     = None
        self.clientFd  = clientFd
        self.requestId = None
        self.cctxt        = LdtpClientContext ()
        self.objectInst   = objInst ()
        self.registry     = registry
        self.cctxt.appmap = appmap (self.objectInst,  self.registry)
        self.packet       = CommPacket (clientFd)
        # Default GUI timeout 30 seconds for receiving packet from client
        self._ldtpGuiTimeout = 30

    def addItem2List (self, items):
        if items is None:
            return ""
        itemList = ""
        for item in items:
            itemList += "<OBJECT>%s</OBJECT>" % saxutils.escape (item)
        return itemList

    def hasState (self, accessible, argsList):
        if accessible is None or argsList is None or \
               type (accessible) is not type (Accessibility.Accessible) or \
               type (argsList) is not type (list):
            return LdtpErrorCode.INVALID_STATE
        _stateSet = accessible.getState ()
        if _stateSet is None:
            return LdtpErrorCode.INVALID_STATE
        for i in argsList:
            if _stateSet.contains (int (i)) == False:
                _stateSet.unref ()
                return LdtpErrorCode.INVALID_STATE
        _stateSet.unref ()
        return LdtpErrorCode.SUCCESS

    def handleClient (self):
        while True:
            try:
                _requestPacket = self.packet.recv ()
            except LdtpExecutionError, msg:
                if str(msg) == 'Timeout':
                    continue
                # Client connection broke
                # Let us close the socket
                self.clientFd.close ()
                # and exit the thread
                if _ldtpDebug != None and _ldtpDebug == '2':
                    print 'Client connection broke', self.clientFd
                return
            if _requestPacket == None:
                if _ldtpDebug != None and _ldtpDebug == '2':
                    print 'Client closed connection'
                break
            elif _ldtpDebug != None and _ldtpDebug == '2':
                print _requestPacket
            try:
                self.data = None
                self.error = LdtpErrorCode.COMMAND_FAILED
                self.handleRequest (_requestPacket)
            except:
                if _ldtpDebug:
                    print traceback.format_exc ()
                self.error = LdtpErrorCode.COMMAND_FAILED
            _responsePacket = self.packet.generateresponsexml (self.requestId, self.error, self.data)
            self.packet.send (_responsePacket)

    def handleRequest (self, requestPacket):
        try:
            self.requestId, _requestCommand, _context, _component, _argumentList = self.packet.parsexml (requestPacket)
            self.cctxt.request = LdtpRequest (command = _requestCommand, requestId = self.requestId,
                                              context = _context, component = _component,
                                              argsList = _argumentList)
            if _ldtpDebug:
                print self.requestId, _requestCommand, _context, _component, _argumentList
            if _requestCommand is 0:
                self.error = LdtpErrorCode.INVALID_COMMAND
                return
        except TypeError, msg:
            self.error = LdtpErrorCode.PACKET_INVALID
            if _ldtpDebug != None and _ldtpDebug == '2':
                print 'TypeError', msg
                print "Invalid request packet"
            return
        except LdtpExecutionError, msg:
            self.error = LdtpErrorCode.PACKET_INVALID
            if _ldtpDebug != None and _ldtpDebug == '2':
                print 'TypeError', msg
                print "Invalid request packet"
            return
        if _requestCommand == command.SETLOCALE:
            # FIXME COMMAND_NOT_IMPLEMENTED
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
            return
        elif _requestCommand == command.LAUNCHAPP:
            _status = commands.getstatusoutput ('which ' + str (_context))
            if _status [0] != 0:
                if _ldtpDebug:
                    print 'File ' + str (appName) + ' does not exist in the PATH.'
                self.error = UNABLE_TO_LAUNCH_APP
                return
            pid = os.fork ()
            if pid == 0:
                envVar = os.environ
                if _component and _component == '1':
                    envVar ['GTK_MODULES'] = 'gail:atk-bridge'
                    envVar ['GNOME_ACCESSIBILITY'] = '1'
                fd = self.clientFd
                fd.close ()
                os.execvpe (appName, arg, envVar)
            # Let us wait so that the application launches
            time.sleep (5)
            self.error = LdtpErrorCode.SUCCESS
            return
        elif _requestCommand == command.SETAPPMAP or \
                _requestCommand == command.INITAPPMAP:
            # FIXME COMMAND_NOT_IMPLEMENTED
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
            return
        elif _requestCommand == command.LOG:
            # FIXME COMMAND_NOT_IMPLEMENTED
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
            return
        elif _requestCommand == command.STARTLOG:
            # FIXME COMMAND_NOT_IMPLEMENTED
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
            return
        elif _requestCommand == command.STOPLOG:
            # FIXME COMMAND_NOT_IMPLEMENTED
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
            return
        elif _requestCommand == command.STOPSCRIPTENGINE:
            # FIXME COMMAND_NOT_IMPLEMENTED
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
            return
        elif _requestCommand == command.GENERATEMOUSEEVENT:
            # FIXME COMMAND_NOT_IMPLEMENTED
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
            return
        elif _requestCommand == command.GENERATEKEYEVENT:
            # FIXME COMMAND_NOT_IMPLEMENTED
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
            return
        elif _requestCommand == command.SETCONTEXT:
            # FIXME COMMAND_NOT_IMPLEMENTED
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
            return
        elif _requestCommand == command.RELEASECONTEXT:
            # FIXME COMMAND_NOT_IMPLEMENTED
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
            return
        elif _requestCommand == command.REINITLDTP:
            # FIXME COMMAND_NOT_IMPLEMENTED
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
            return
        elif _requestCommand == command.GUIEXIST:
            self.updateContextName ()
            self.error, _tmpCctxt = self.cctxt.appmap.getGuiHandle (self.cctxt)
            # self.error = self.cctxt.appmap.guiExist (None)
            return
        elif _requestCommand == command.GUITIMEOUT:
            try:
                self.cctxt.guiTimeOut = int (self.cctxt.request.context)
            except TypeError:
                # Default to 30 seconds of delay for window to appear
                self.cctxt.guiTimeOut = 30
            self.error = LdtpErrorCode.SUCCESS
            return
        elif _requestCommand == command.OBJTIMEOUT:
            try:
                self.cctxt.objTimeOut = int (self.cctxt.request.context)
            except TypeError:
                # Default to 5 seconds of delay for object inside a window
                # in an expected state
                self.cctxt.objTimeOut = 5
            self.error = LdtpErrorCode.SUCCESS
            return
        elif _requestCommand == command.WAITTILLGUIEXIST:
            self.updateContextName ()
            # FIXME COMMAND_NOT_IMPLEMENTED
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
            return
        elif _requestCommand == command.WAITTILLGUINOTEXIST:
            self.updateContextName ()
            # FIXME COMMAND_NOT_IMPLEMENTED
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
            return
        elif _requestCommand == command.DOESMENUITEMEXIST or \
                _requestCommand == command.MENUITEMENABLED or \
                _requestCommand == command.MENUCHECK or \
                _requestCommand == command.MENUUNCHECK or \
                _requestCommand == command.VERIFYMENUCHECK or \
                _requestCommand == command.VERIFYMENUUNCHECK or \
                _requestCommand == command.SELECTMENUITEM:
            if re.search (';', self.cctxt.request.component):
                # If ; found then split
                menu = re.split (';', self.cctxt.request.component, 1)
                # Store first index in component
                self.cctxt.request.component = menu [0]
                # Rest in argsList
                self.cctxt.request.argsList = menu [1]
            return
        elif _requestCommand == command.ONWINDOWCREATE:
            # FIXME COMMAND_NOT_IMPLEMENTED
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
            return
        elif _requestCommand == command.REMOVECALLBACK:
            # FIXME COMMAND_NOT_IMPLEMENTED
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
            return
        elif _requestCommand == command.REMAP:
            # FIXME COMMAND_NOT_IMPLEMENTED
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
            return
        elif _requestCommand == command.BINDTEXT:
            # FIXME COMMAND_NOT_IMPLEMENTED
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
            return
        elif _requestCommand == command.GETAPPLIST:
            _appList = self.cctxt.appmap.getAppList ()
            if _appList:
                self.data = "%s<OBJECTLIST>%s</OBJECTLIST>" % (XmlTags.XML_HEADER,
                                                               self.addItem2List (_appList))
                self.error = LdtpErrorCode.SUCCESS
            else:
                self.error = LdtpErrorCode.UNABLE_TO_GET_APPLICATION_LIST
            return
        elif _requestCommand == command.GETWINDOWLIST:
            _windowList = self.cctxt.appmap.getWindowList ()
            self.data = "%s<OBJECTLIST>%s</OBJECTLIST>" % \
                (XmlTags.XML_HEADER, self.addItem2List (_windowList))
            self.error = LdtpErrorCode.SUCCESS
            return
        elif _requestCommand == command.GETOBJECTLIST:
            self.updateContextName ()
            if self.cctxt.appmap.applicationmap == {} or \
                    self.cctxt.request.context in \
                    self.cctxt.appmap.applicationmap == False:
                self.error, _tmpCctxt = self.cctxt.appmap.getGuiHandle (self.cctxt)
                if self.error != LdtpErrorCode.SUCCESS:
                    return
            # FIXME COMMAND_NOT_IMPLEMENTED
            if self.cctxt.appmap.applicationmap != {} and \
                    self.cctxt.request.context in self.cctxt.appmap.applicationmap:
                self.data = "%s<OBJECTLIST>%s</OBJECTLIST>" % \
                    (XmlTags.XML_HEADER,
                     self.addItem2List (self.cctxt.appmap.applicationmap \
                                            [self.cctxt.request.context].children.keys ()))
                self.error = LdtpErrorCode.SUCCESS
            else:
                self.error = LdtpErrorCode.UNABLE_TO_GET_OBJECT_LIST
            return
        elif _requestCommand == command.GETCHILD:
            # FIXME COMMAND_NOT_IMPLEMENTED
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
            return
        elif _requestCommand == command.GETOBJECTINFO:
            # FIXME COMMAND_NOT_IMPLEMENTED
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
            return
        elif _requestCommand == command.GETOBJECTPROPERTY:
            # FIXME COMMAND_NOT_IMPLEMENTED
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
            return

        # Update context name
        self.updateContextName ()

        errCode, self.cctxt = self.cctxt.appmap.getGuiHandle (self.cctxt)

        if errCode != LdtpErrorCode.SUCCESS:
            self.error = errCode
            if _ldtpDebug:
                print 'Unable to get GUI hanlde %s' % str (errCode)
            if self.cctxt.guiHandle and self.cctxt.guiHandle.handle:
                self.cctxt.guiHandle.handle.unref ()
                self.cctxt.guiHandle.handle = None
            return

        if _ldtpDebug:
            print 'Got gui handle: %s : %s' % (self.cctxt.guiHandle.handle.name,
                                               self.cctxt.guiHandle.handle.getRoleName ())

        if _requestCommand == command.HASSTATE:
            self.error = self.hasState (self.cctxt.guiHandle.handle,
                                        self.cctxt.request.argsList)
            self.cctxt.guiHandle.handle.unref ()
            return

        _classId = self.cctxt.guiHandle.handle.getRole ()

        if _classId == Accessibility.ROLE_COMBO_BOX:
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
        elif _classId == Accessibility.ROLE_CHECK_BOX:
            self.error = checkBoxMain (self.cctxt, _requestCommand)
            return
        elif _classId == Accessibility.ROLE_CHECK_MENU_ITEM:
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
        elif _classId == Accessibility.ROLE_RADIO_MENU_ITEM:
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
        elif _classId == Accessibility.ROLE_RADIO_BUTTON:
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
        elif _classId == Accessibility.ROLE_PUSH_BUTTON:
            self.error = pushButtonMain (self.cctxt, _requestCommand)
            return
        elif _classId == Accessibility.ROLE_TOGGLE_BUTTON:
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
        elif _classId == Accessibility.ROLE_EMBEDDED:
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
        elif _classId == Accessibility.ROLE_LIST:
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
        elif _classId == Accessibility.ROLE_TEXT or \
                _classId == Accessibility.ROLE_EDITBAR or \
                _classId == Accessibility.ROLE_PARAGRAPH or \
                _classId == Accessibility.ROLE_AUTOCOMPLETE or \
                _classId == Accessibility.ROLE_PASSWORD_TEXT or \
                _classId == Accessibility.ROLE_ENTRY:
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
        elif _classId == Accessibility.ROLE_PANEL:
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
        elif _classId == Accessibility.ROLE_ICON:
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
        elif _classId == Accessibility.ROLE_LAYERED_PANE:
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
        elif _classId == Accessibility.ROLE_MENU:
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
        elif _classId == Accessibility.ROLE_MENU_ITEM:
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
        elif _classId == Accessibility.ROLE_PAGE_TAB_LIST:
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
        elif _classId == Accessibility.ROLE_CALENDAR:
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
#        elif _classId == Accessibility.ROLE_CALENDAR_VIEW:
#            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
        elif _classId == Accessibility.ROLE_SPIN_BUTTON:
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
        elif _classId == Accessibility.ROLE_TABLE:
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
        elif _classId == Accessibility.ROLE_TREE or \
                _classId == Accessibility.ROLE_TREE_TABLE:
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
        elif _classId == Accessibility.ROLE_SCROLL_BAR:
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
        elif _classId == Accessibility.ROLE_SCROLL_PANE:
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
        elif _classId == Accessibility.ROLE_SLIDER:
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
        elif _classId == Accessibility.ROLE_STATUS_BAR:
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
        elif _classId == Accessibility.ROLE_TOOL_BAR:
            self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
        else:
            if _requestCommand == command.KBDENTER:
                self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
            elif _requestCommand == command.GRABFOCUS:
                self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED
            else:
                self.error = LdtpErrorCode.ROLE_NOT_IMPLEMENTED

        if self.cctxt.guiHandle.handle:
            self.cctxt.guiHandle.handle.unref ()
            self.cctxt.guiHandle.handle = None
            self.cctxt.guiHandle = None

        self.error = LdtpErrorCode.COMMAND_NOT_IMPLEMENTED

    def updateContextName (self):
        if self.cctxt is None:
            if _ldtpDebug:
                print 'Context None - %d' % lineno ()
            return
        if self.cctxt.request and self.cctxt.request.context:
            _windowHandle, _context, flag = \
                self.cctxt.appmap.getAccessibleWindowHandle (None,
                                                             self.cctxt.request.context)
            if _context:
                self.cctxt.request.context = _context
            if _windowHandle:
                # Free accessible handle
                _windowHandle.unref ()

class LdtpService:
    def __init__ (self, useTcp = False):
        self.display = os.getenv ('DISPLAY')
        if self.display == None:
            raise LdtpExecutionError ('Missing DISPLAY environment variable. Running in text mode ?')    
        self.socketpath = '/tmp/ldtp-' + os.getenv ('USER') + '-' + self.display
        self.mainsock = None
        self.ldtpusetcp = useTcp
        if os.environ.has_key("LDTP_SERVER_ADDR"):
            self.ldtpserveraddr = os.environ ["LDTP_SERVER_ADDR"]
            self.ldtpusetcp = True
        if os.environ.has_key ("LDTP_SERVER_PORT"):
            self.ldtpserverport = int (os.environ["LDTP_SERVER_PORT"])
        else:
            self.ldtpserverport = 23457

    def start (self):
        try:
            # Create a client socket
            if self.ldtpusetcp:
                self.mainsock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
            else:
                self.mainsock = socket.socket (socket.AF_UNIX, socket.SOCK_STREAM)
        except socket.error,msg:
            if self.ldtpusetcp:
                raise LdtpExecutionError ('Error while creating socket  ' + str (msg))
            else:
                raise LdtpExecutionError ('Error while creating UNIX socket  ' + str (msg))    

        try:
            self.mainsock.setsockopt (socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            # Connect to server socket
            if self.ldtpusetcp:
                self.mainsock.bind ((self.ldtpserveraddr, self.ldtpserverport))
            else:
                self.mainsock.bind (self.socketpath)
            self.mainsock.listen (5)
            return self.mainsock
        except TypeError:
            raise LdtpExecutionError ('Environment LDTP_AUTH_SOCK variable not set')
        except socket.error, msg:
            raise LdtpExecutionError ('LDTP server could not be start ' + str (msg))

    def stop (self):
        if self.mainsock is not None:
            self.mainsock.close ()
            self.mainsock = None
        if self.ldtpusetcp is False:
            try:
                os.unlink (self.socketpath)
            except OSError:
                if _ldtpDebug:
                    print traceback.format_exc ()
                pass

class PollServer (threading.Thread):
    def __init__ (self, ldtpService, registry):
        threading.Thread.__init__ (self)
        self._events = None
        self.ldtpService = ldtpService
        self.mainSock = None
        self.registry = registry
        self.clientFdPool = {}
        self._serverpoll = select.poll ()

    def run (self):
        try:
            self.mainSock = self.ldtpService.start ()
            self.start_polling_server ()
        except:
            try:
                raise LdtpExecutionError (str (traceback.print_exc ()))
            except AttributeError:
                pass
            except:
                pass

    def start_polling_server (self):
        self._serverDisconnected = False
        self._serverpoll.register (self.mainSock, select.POLLIN)

        while True:
            try:
                self._events = self._serverpoll.poll ()
            except socket.error, msg:
                if _ldtpDebug:
                    print traceback.format_exc ()
                break
            except:
                if _ldtpDebug:
                    print traceback.format_exc ()
                sys.exit ()
            try:
                if self._events == None:
                    break
                for i in range (0, len (self._events)):
                    if (self._events [i][1] & select.POLLIN or self._events [i][1] & select.POLLPRI):
                        if self._events [i][0] == self.mainSock.fileno ():
                            # Accept new client connection
                            clientFd, addr = self.mainSock.accept ()
                            self.clientFdPool [clientFd.fileno ()] = clientFd
                            # Spawn new thread for each new client
                            newClient = ClientThread (clientFd, self.registry)
                            threadId = thread.start_new_thread (newClient.handleClient, ())
                            continue
                    else:
                        self._serverDisconnected = True
                        break
                    if self._serverDisconnected == True:
                        break
            # Checking this exception due to bug # 333090 comment # 6
            except TypeError:
                if _ldtpDebug:
                    print traceback.format_exc ()
                self._serverpoll.unregister (self.mainSock)
                return

    def shutdown (self):
        self.ldtpService.stop ()

class ldtpengine:
    def __init__ (self, pckt = None, registry = None):
        self.windowName = None
        self.windowType = None
        self.objectName = None
        self.objectType = None
        self.objectInst = objInst ()
        self.registry   = registry
        self.appmap = appmap (self.objectInst, self.registry)
        self.hashmap = None

    def start (self):
        try:
            self.registry.start ()
        except:
            if _ldtpDebug and _ldtpDebug == '3':
                print traceback.print_exc ()
            pass

    def windowListenerCallback (self, event):
        role = event.source.getRole ()
        if role == Accessibility.ROLE_FRAME or role == Accessibility.ROLE_DIALOG or \
               role == Accessibility.ROLE_ALERT  or role == Accessibility.ROLE_WINDOW:
            self.windowName = self.getWinNameAppmapFormat (event.source.name, role)
            self.windowType = event.source.getRoleName ()
            if _ldtpDebug and _ldtpDebug == '2':
                print '***WINDOW', event.type, event.source.name, \
                      event.detail1, event.detail2,  \
                      event.any_data
            parent = event.source.parent
            name = None
            if parent is not None:
                name = parent.name
                parent.unref ()
            try:
                self.objectInst.reset ()
                self.remap.dumpTree (event.source, name)
                if self.pckt and (event.type == 'window:create' or event.type == 'window:destroy'):
                    _xml = self.pckt.generatenotificationxml (self.windowName, \
                                                              '', \
                                                              self.windowType, event.type, \
                                                              self.timeElapsed ())
                    self.pckt.sendpacket (_xml)
            except:
                print traceback.print_exc ()

    def nameChangeListenerCallback (self, event):
        _role = event.source.getRole ()
        if _role == Accessibility.ROLE_FRAME or _role == Accessibility.ROLE_DIALOG or _role == Accessibility.ROLE_ALERT:
            self.windowName = self.getWinNameAppmapFormat (event.source.name, _role)
            if _ldtpDebug and _ldtpDebug == '2':
                print 'NAMECHANGE', event.type, event.source.name, \
                      event.detail1, event.detail2,  \
                      event.any_data
            _parent = event.source.parent
            _name = None
            if _parent is not None:
                _name = _parent.name
                _parent.unref ()
            try:
                self.objectInst.reset ()
                self.remap.dumpTree (event.source, _name)
            except:
                print traceback.print_exc ()

    def registerWindowListener (self):
        eventTypes = [
            "window:activate",
            "window:create",
            "window:destroy",
            ]
        for eventType in eventTypes:
            self.registry.registerEventListener (self.windowListenerCallback, eventType)

    def registerNameChangeListener (self):
        eventTypes = [
            "object:property-change:accessible-name"
            ]
        for eventType in eventTypes:
            self.registry.registerEventListener (self.nameChangeListenerCallback, eventType)

_ldtpService = LdtpService ()
registry = atspi.Registry ()
# Start polling server
_pollThread = PollServer (_ldtpService, registry)
# To start the server, just call this function once
def start (pckt = None, registry = None):
    engine = ldtpengine (pckt, registry)
    #engine.registerWindowListener ()
    #engine.registerNameChangeListener ()
    _pollThread.setDaemon (True)
    try:
        _pollThread.start ()
        engine.start ()
    except KeyboardInterrupt:
        _pollThread.shutdown ()
        stop ()
        raise KeyboardInterrupt ()
    except:
        print traceback.print_exc ()
        _pollThread.shutdown ()
        stop ()

# To stop server, just call this function once
def stop (signum = None, frame = None):
    _pollThread.shutdown ()
    __shutdownAndExit (None, None)

server = None

# If this file is directly called like
# $ python server.py
if __name__ == "__main__":
    signal.signal (signal.SIGINT, stop)
    signal.signal (signal.SIGQUIT, stop)
    start (registry = registry)