summaryrefslogtreecommitdiff
path: root/python/ldtplib/ldtplibutils.py
blob: 5ff8fe697cbc9d256409adcce0f2cd36612d4b63 (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
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
############################################################################
#
#  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.
#
#############################################################################

import os
import re
import sys
import time
import socket
import struct
import thread
import select
import inspect
import logging
import commands
import traceback
import threading
import logging.config
from xml.sax import saxutils

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

try:
    import pyatspi as atspi, Accessibility
except ImportError:
    import atspi
    import Accessibility

_ldtpDebug = os.getenv ('LDTP_DEBUG')

class RecordCommand:
    index = 0
    GETOBJECTNAME = index; index += 1
    GETWINDOWNAME = index; index += 1
    INVALID       = index; index += 1
    NOTIFICATION  = index; index += 1
    STOP          = index; index += 1
    WINDOWEXIST   = index; index += 1

# General functions
class command:
    index = 0
    ACTIVATETEXT = index; index += 1
    APPENDTEXT = index; index += 1
    APPUNDERTEST = index; index += 1
    BINDTEXT = index; index += 1
    CAPTURETOFILE = index; index += 1
    CHECK = index; index += 1
    CHECKROW = index; index += 1
    CLICK = index; index += 1
    COMBOSELECT = index; index += 1
    COMBOSELECTINDEX = index ; index += 1
    COMPARETEXTPROPERTY = index; index += 1
    CONTAINSTEXTPROPERTY = index; index += 1
    COPYTEXT = index; index += 1
    CUTTEXT = index; index += 1
    DECREASE = index; index += 1
    DELETETEXT = index; index += 1
    DOESMENUITEMEXIST = index; index += 1
    DOESROWEXIST = index; index += 1
    DOUBLECLICK = index; index += 1
    DOUBLECLICKROW = index; index += 1
    DOUBLECLICKROWINDEX = index; index += 1
    EXPANDTABLECELL = index; index += 1
    GENERATEKEYEVENT = index; index += 1
    GENERATEMD5 = index; index += 1
    GENERATEMOUSEEVENT = index; index += 1
    GETALLSTATES = index; index += 1
    GETAPPLIST = index; index += 1
    GETCELLVALUE = index; index += 1
    GETCHARCOUNT = index; index += 1
    GETCHILD = index; index += 1
    GETCURSORPOSITION = index; index += 1
    GETFILE = index; index += 1
    GETLABEL = index; index += 1
    GETLABELATINDEX = index; index += 1
    GETMAXVALUE = index; index += 1
    GETMININCREMENT = index; index += 1
    GETMINVALUE = index; index += 1
    GETOBJECTINFO = index; index += 1
    GETOBJECTLIST = index; index += 1
    GETOBJECTPROPERTY = index; index += 1
    GETOBJECTSIZE = index; index += 1
    GETPANELCHILDCOUNT = index; index += 1
    GETROWCOUNT = index; index += 1
    GETSLIDERVALUE = index; index += 1
    GETSTATUSBARTEXT = index; index += 1
    GETTABCOUNT = index; index += 1
    GETTABLEROWINDEX = index; index += 1
    GETTABNAME = index; index += 1
    GETTEXTPROPERTY = index; index += 1
    GETTEXTVALUE = index; index += 1
    GETTREETABLEROWINDEX = index; index += 1
    GETVALUE = index; index += 1
    GETWINDOWLIST = index; index += 1
    GETWINDOWSIZE = index; index += 1
    GRABFOCUS = index; index += 1
    GUIEXIST = index; index += 1
    GUITIMEOUT = index; index += 1
    HASSTATE = index; index += 1
    HIDELIST = index; index += 1
    INCREASE = index; index += 1
    INITAPPMAP = index; index += 1
    INSERTTEXT = index; index += 1
    IVALID = index; index += 1
    INVOKEMENU = index; index += 1
    ISCHILDINDEXSELECTED = index; index += 1
    ISCHILDITEMINDEXSELECTED = index; index += 1
    ISCHILDITEMSELECTED = index; index += 1
    ISCHILDSELECTED = index; index += 1
    ISTEXTSTATEENABLED = index; index += 1
    KBDENTER = index; index += 1
    KEYPRESS = index; index += 1
    KEYRELEASE = index; index += 1
    LAUNCHAPP = index; index += 1
    LISTSUBMENUS = index; index += 1
    LOG = index; index += 1
    MENUCHECK = index; index += 1
    MENUITEMENABLED = index; index += 1
    MENUUNCHECK = index; index += 1
    MOUSELEFTCLICK = index; index += 1
    MOUSEMOVE = index; index += 1
    MOUSERIGHTCLICK = index; index += 1
    OBJTIMEOUT = index; index += 1
    ONEDOWN = index; index += 1
    ONELEFT = index; index += 1
    ONERIGHT = index; index += 1
    ONEUP = index; index += 1
    ONWINDOWCREATE = index; index += 1
    PASTETEXT = index; index += 1
    PRESS = index; index += 1
    REINITLDTP = index; index += 1
    RELEASECONTEXT = index ; index += 1
    REMAP = index; index += 1
    REMOVECALLBACK = index; index += 1
    RIGHTCLICK = index; index += 1
    SCROLLDOWN = index; index += 1
    SCROLLLEFT = index; index += 1
    SCROLLRIGHT = index; index += 1
    SCROLLUP = index; index += 1
    SELECTALL = index; index += 1
    SELECTCALENDARDATE = index; index += 1
    SELECTEDITEMCOUNT = index; index += 1
    SELECTEVENT = index; index += 1
    SELECTEVENTINDEX = index; index += 1
    SELECTINDEX = index; index += 1
    SELECTITEM = index; index += 1
    SELECTLABELSPANELBYNAME = index; index += 1
    SELECTLASTROW = index; index += 1
    SELECTMENUITEM = index; index += 1
    SELECTPANEL = index; index += 1
    SELECTPANELNAME = index; index += 1
    SELECTPOPUPMENU = index; index += 1
    SELECTROW = index; index += 1
    SELECTROWINDEX = index; index += 1
    SELECTROWPARTIALMATCH = index; index += 1
    SELECTTAB = index; index += 1
    SELECTTABINDEX = index; index += 1
    SELECTTEXTBYINDEXANDREGION = index; index += 1
    SELECTTEXTBYNAME = index; index += 1
    SELECTTEXTITEM = index; index += 1
    SETAPPMAP = index; index += 1
    SETCELLVALUE = index; index += 1
    SETCONTEXT = index; index += 1
    SETCURSORPOSITION = index; index += 1
    SETLOCALE = index; index += 1
    SETMAX = index; index += 1
    SETMIN = index; index += 1
    SETTEXTVALUE = index; index += 1
    SETVALUE = index; index += 1
    SHOWLIST = index; index += 1
    SINGLECLICKROW = index; index += 1
    SORTCOLUMN = index; index += 1
    SORTCOLUMNINDEX = index; index += 1
    STARTLOG = index; index += 1
    STATEENABLED = index; index += 1
    STOPLOG = index; index += 1
    STOPSCRIPTENGINE = index; index += 1
    TITLEBARSELECTMENUITEM = index; index += 1
    UNCHECK = index; index += 1
    UNCHECKROW = index; index += 1
    UNSELECTALL = index; index += 1
    UNSELECTINDEX = index; index += 1
    UNSELECTITEM = index; index += 1
    UNSELECTITEMINDEX = index; index += 1
    VERIFYBUTTONCOUNT = index; index += 1
    VERIFYCHECK = index; index += 1
    VERIFYCHECKROW = index; index += 1
    VERIFYDROPDOWN = index; index += 1
    VERIFYEVENTEXIST = index; index += 1
    VERIFYHIDELIST = index; index += 1
    VERIFYMENUCHECK = index; index += 1
    VERIFYMENUUNCHECK = index; index += 1
    VERIFYPARTIALMATCH = index; index += 1
    VERIFYPARTIALTABLECELL = index; index += 1
    VERIFYPUSHBUTTON = index; index += 1
    VERIFYPROGRESSBAR = index; index += 1
    VERIFYPROGRESSBARVISIBLE = index; index += 1
    VERIFYSCROLLBAR = index; index += 1
    VERIFYSCROLLBARHORIZONTAL = index; index += 1
    VERIFYSCROLLBARVERTICAL = index; index += 1
    VERIFYSELECT = index; index += 1
    VERIFYSETTEXT = index; index += 1
    VERIFYSETVALUE = index; index += 1
    VERIFYSHOWLIST = index; index += 1
    VERIFYSLIDER = index; index += 1
    VERIFYSLIDERHORIZONTAL = index; index += 1
    VERIFYSLIDERVERTICAL = index; index += 1
    VERIFYSTATUSBAR = index; index += 1
    VERIFYSTATUSBARVISIBLE = index; index += 1
    VERIFYTABLECELL = index; index += 1
    VERIFYTABNAME = index; index += 1
    VERIFYTOGGLED = index; index += 1
    VERIFYUNCHECK = index; index += 1
    VERIFYUNCHECKROW = index; index += 1
    VERIFYVISIBLEBUTTONCOUNT = index; index += 1
    WAITTILLGUIEXIST = index; index += 1
    WAITTILLGUINOTEXIST = index; index += 1
    WINDOWUPTIME = index; index += 1

class state:
    """
    INVALID - Accessibility.STATE_INVALID
    ACTIVE - Accessibility.STATE_ACTIVE
    ARMED = Accessibility.STATE_ARMED
    BUSY = Accessibility.STATE_BUSY
    CHECKED = Accessibility.STATE_CHECKED
    COLLAPSED = Accessibility.STATE_COLLAPSED
    DEFUNCT = Accessibility.STATE_DEFUNCT
    EDITABLE = Accessibility.STATE_EDITABLE
    ENABLED = Accessibility.STATE_ENABLED
    EXPANDABLE = Accessibility.STATE_EXPANDABLE
    EXPANDED = Accessibility.STATE_EXPANDED
    FOCUSABLE = Accessibility.STATE_FOCUSABLE
    FOCUSED = Accessibility.STATE_FOCUSED
    HAS_TOOLTIP = Accessibility.STATE_HAS_TOOLTIP
    HORIZONTAL - Accessibility.STATE_HORIZONTAL
    ICONIFIED - Accessibility.STATE_ICONIFIED
    MODAL - Accessibility.STATE_MODAL
    MULTI_LINE - Accessibility.STATE_MULTI_LINE
    MULTISELECTABLE - Accessibility.STATE_MULTISELECTABLE
    OPAQUE - Accessibility.STATE_OPAQUE
    PRESSED - Accessibility.STATE_PRESSED
    RESIZABLE - Accessibility.STATE_RESIZABLE
    SELECTABLE - Accessibility.STATE_SELECTABLE
    SELECTED - Accessibility.STATE_SELECTED
    SENSITIVE - Accessibility.STATE_SENSITIVE
    SHOWING - Accessibility.STATE_SHOWING
    SINGLE_LINE - Accessibility.STATE_SINGLE_LINE
    STALE - Accessibility.STATE_STALE
    TRANSIENT - Accessibility.STATE_TRANSIENT
    VERTICAL - Accessibility.STATE_VERTICAL
    VISIBLE - Accessibility.STATE_VISIBLE
    MANAGES_DESCENDANTS - Accessibility.STATE_MANAGES_DESCENDANTS
    INDETERMINATE - Accessibility.STATE_INDETERMINATE
    LAST_DEFINED - Accessibility.STATE_LAST_DEFINED
    TRUNCATED - Accessibility.STATE_TRUNCATED
    REQUIRED - Accessibility.STATE_REQUIRED
    INVALID_ENTRY - Accessibility.STATE_INVALID_ENTRY
    SUPPORTS_AUTOCOMPLETION - Accessibility.STATE_SUPPORTS_AUTOCOMPLETION
    SELECTABLE_TEXT - Accessibility.STATE_SELECTABLE_TEXT
    IS_DEFAULT - Accessibility.STATE_IS_DEFAULT
    VISISTED - Accessibility.STATE_VISITED
    """
    INVALID = Accessibility.STATE_INVALID
    ACTIVE = Accessibility.STATE_ACTIVE
    ARMED = Accessibility.STATE_ARMED
    BUSY = Accessibility.STATE_BUSY
    CHECKED = Accessibility.STATE_CHECKED
    COLLAPSED = Accessibility.STATE_COLLAPSED
    DEFUNCT = Accessibility.STATE_DEFUNCT
    EDITABLE = Accessibility.STATE_EDITABLE
    ENABLED = Accessibility.STATE_ENABLED
    EXPANDABLE = Accessibility.STATE_EXPANDABLE
    EXPANDED = Accessibility.STATE_EXPANDED
    FOCUSABLE = Accessibility.STATE_FOCUSABLE
    FOCUSED = Accessibility.STATE_FOCUSED
    # FIXME: Dirty hack
    # this is due to a mismatch between CSPI
    # and pyatspi accessibility state
    __addValue = 0
    try:
        # This does not exist in AT-CSPI - GNOME 2.20
        HAS_TOOLTIP = Accessibility.STATE_HAS_TOOLTIP
        __addValue = -1
    except:
        pass
    HORIZONTAL = Accessibility.STATE_HORIZONTAL + __addValue
    ICONIFIED = Accessibility.STATE_ICONIFIED + __addValue
    MODAL = Accessibility.STATE_MODAL + __addValue
    MULTI_LINE = Accessibility.STATE_MULTI_LINE + __addValue
    MULTISELECTABLE = Accessibility.STATE_MULTISELECTABLE + __addValue
    OPAQUE = Accessibility.STATE_OPAQUE + __addValue
    PRESSED = Accessibility.STATE_PRESSED + __addValue
    RESIZABLE = Accessibility.STATE_RESIZABLE + __addValue
    SELECTABLE = Accessibility.STATE_SELECTABLE + __addValue
    SELECTED = Accessibility.STATE_SELECTED + __addValue
    SENSITIVE = Accessibility.STATE_SENSITIVE + __addValue
    SHOWING = Accessibility.STATE_SHOWING + __addValue
    SINGLE_LINE = Accessibility.STATE_SINGLE_LINE + __addValue
    STALE = Accessibility.STATE_STALE + __addValue
    TRANSIENT = Accessibility.STATE_TRANSIENT + __addValue
    VERTICAL = Accessibility.STATE_VERTICAL + __addValue
    VISIBLE = Accessibility.STATE_VISIBLE + __addValue
    MANAGES_DESCENDANTS = Accessibility.STATE_MANAGES_DESCENDANTS + __addValue
    INDETERMINATE = Accessibility.STATE_INDETERMINATE + __addValue
    LAST_DEFINED = Accessibility.STATE_LAST_DEFINED + __addValue
    try:
        TRUNCATED = Accessibility.STATE_TRUNCATED + __addValue
        REQUIRED = Accessibility.STATE_REQUIRED + __addValue
        INVALID_ENTRY = Accessibility.STATE_INVALID_ENTRY + __addValue
        SUPPORTS_AUTOCOMPLETION = Accessibility.STATE_SUPPORTS_AUTOCOMPLETION + __addValue
        SELECTABLE_TEXT = Accessibility.STATE_SELECTABLE_TEXT + __addValue
        IS_DEFAULT = Accessibility.STATE_IS_DEFAULT + __addValue
        VISISTED = Accessibility.STATE_VISITED + __addValue
    except:
        if _ldtpDebug:
            print 'New roles'
        pass

class LdtpErrorCode:
    SUCCESS = [0, "Success"]
    ARGUMENT_NONE = [-1001, "Argument None"]
    ACCEPT_FAILED = -1002
    UNABLE_TO_REINIT_LDTP = -1003
    UNABLE_TO_ALLOCATE_MEMORY = -1004
    UNABLE_TO_GET_APPLICATION_LIST = [-1005, "Unable to get application list"]
    UNABLE_TO_GET_OBJECT_LIST = [-1006, "Unable to get object list"]
    THREAD_CREATION_FAILED = -1007
    THREAD_DETACH_FAILED = -1008
    PACKET_INVALID = [-1009, "Invalid packet"]
    RECEIVE_RESPONSE = [-1010, "Receive response"]
    SENDING_RESPONSE = [-1011, "Sending response"]
    PARTIAL_DATA_SENT = [-1012, "Partial data sent"]
    INVALID_COMMAND = [-1013, "Invalid command"]
    INVALID_STATE = [-1014, "Invalid state"]
    APPMAP_NOT_INITIALIZED = [-1015, "Appmap not initialized"]
    OPENING_APPMAP_FILE = -1016
    OPENING_LOG_FILE = -1017
    APP_NOT_RUNNING = [-1018, "Application not running"]
    UNABLE_TO_UPDATE_APPMAP = [-1019, "Unable to update appmap"]
    WIN_NAME_NOT_FOUND_IN_APPMAP = [-1020, "Window name not found in appmap"]
    OBJ_NAME_NOT_FOUND_IN_APPMAP = [-1021, "Object name not found in appmap"]
    WIN_NOT_OPEN = [-1022, "Window does not exist"]
    UNABLE_TO_GET_CONTEXT_HANDLE = [-1023, "Unable to get context handle"]
    UNABLE_TO_GET_COMPONENT_HANDLE = [-1024, "Unable to get component handle"]
    UNABLE_TO_GET_PROPERTY = [-1025, "Unable to get property"]
    GET_OBJ_HANDLE_FAILED = [-1026, "Get object handle failed"]
    UNABLE_TO_GET_CELL_HANDLE_FAILED = [-1027, "Unable to get cell handle failed"]
    OBJ_INFO_MISMATCH = [-1028, "Object info mismatch"]
    COMMAND_NOT_IMPLEMENTED = [-1029, "Requested action on mentioned object is not implemented - Welcome contribution ;)"]
    GETTEXTVALUE_FAILED = -1030
    STATUSBAR_GETTEXT_FAILED = -1031
    STATUSBAR_NOT_VISIBLE = -1032
    CHILD_TYPE_UNIDENTIFIED = [-1033, "Child type unidentified"]
    SELECTITEM_FAILED = -1034
    VERIFY_ITEM_FAILED = -1035
    SELECTINDEX_FAILED = -1036
    TEXT_NOT_FOUND = -1037
    TEXT_STATE_ENABLED = -1038
    TEXT_STATE_NOT_ENABLED = -1039
    SETTEXTVALUE_FAILED = -1040
    VERIFY_SETTEXTVALUE_FAILED = -1041
    CLICK_FAILED = [-1042, "Click failed"]
    DOUBLE_CLICK_FAILED = -1043
    RIGHT_CLICK_FAILED = -1044
    CHILD_IN_FOCUS = -10045
    CHILD_NOT_FOCUSSED = -1046
    UNABLE_TO_GET_MENU_HANDLE = -1047
    UNABLE_TO_FIND_POPUP_MENU = -1048
    MENU_VISIBLE = -1049
    MENU_NOT_VISIBLE = -1050
    HIDELIST_FAILED = -1051
    SHOWLIST_FAILED = -1052
    VERIFY_SHOWLIST_FAILED = -1053
    ITEM_NOT_FOUND = -1054
    FILECAPTURE_FAILED_OPEN_OUTPUT_FILE = -1055
    VERIFY_DROPDOWN_FAILED = -1056
    CALENDAR_EVENT_INDEX_GREATER = -1057
    UNABLE_TO_SELECT_CALENDAR_EVENT_INDEX = -1058
    UNABLE_TO_SELECT_CALENDAR_EVENT_NAME = -1059
    NO_APPOINTMENTS_IN_CALENDAR = -1060
    UNABLE_TO_GET_VALUE = -1061
    UNABLE_TO_GRAB_FOCUS = [-1062, "Unable to grab focus"]
    OBJ_NOT_COMPONENT_TYPE = -1063
    INVALID_DATE = -1064
    INVALID_OBJECT_STATE = [-1065, "Invalid object state"]
    CHECK_ACTION_FAILED = -1066
    UNCHECK_ACTION_FAILED = -1067
    STATE_CHECKED = -1068
    STATE_UNCHECKED = -1069
    UNABLE_TO_SELECT_LABEL = -1070
    LABEL_NOT_FOUND = -1071
    UNABLE_TO_SELECT_LAYERED_PANE_ITEM = -1072
    UNABLE_TO_SELECT_TEXT_ITEM = -1073
    LIST_INDEX_GREATER = -1074
    UNABLE_TO_GET_SELECTED_CHILD = -1075
    UNABLE_TO_SELECT_CHILD = -1076
    UNABLE_TO_GET_CHILD_MENU_ITEM = -1077
    UNABLE_TO_LIST_MENU_ITEMS = -1078
    UNABLE_TO_SELECT_LIST_ITEM = -1079
    MENU_ITEM_DOES_NOT_EXIST = -1080
    MENU_ITEM_STATE_DISABLED = -1081
    SELECT_MENU_ITEM_FAILED = -1082
    PAGE_TAB_NAME_SELECTION_FAILED = -1083
    PAGE_TAB_NAME_ALREADY_IN_SELECTED_STATE = -1084
    PAGE_TAB_NAME_DOESNOT_EXIST = -1085
    PAGE_TAB_INDEX_DOESNOT_EXIST = -1086
    PAGE_TAB_NAME_INPUT_DOESNOT_EXIST = -1087
    PAGE_TAB_INDEX_INPUT_DOESNOT_EXIST = -1088
    NO_PANEL_EXIST = -1089
    PANEL_NAME_SELECTION_FAILED = -1090
    PANEL_INDEX_SELECTION_FAILED = -1091
    PANEL_COUNT_LESS_THAN_TOTAL_PANEL = -1092
    RADIO_BUTTON_ALREADY_CHECKED = -1093
    RADIO_BUTTON_STATE_NOT_ENABLED = -1094
    RADIO_BUTTON_CHECKED = -1095
    RADIO_BUTTON_NOT_CHECKED = -1096
    RADIO_MENU_ITEM_ALREADY_CHECKED = -1097
    RADIO_MENU_ITEM_CHECKED = -1098
    RADIO_MENU_ITEM_NOT_CHECKED = -1099
    NOT_VERTICAL_SCROLL_BAR = -1100
    UNABLE_TO_SCROLL_WITH_GIVEN_VALUE = -1101
    NOT_HORIZONTAL_SCROLL_BAR = -1102
    SCROLL_BAR_MAX_REACHED = -1103
    SCROLL_BAR_MIN_REACHED = -1104
    NOT_VERTICAL_SLIDER = -1105
    NOT_HORIZONTAL_SLIDER = -1106
    SLIDER_SET_MAX_FAILED = -1107
    SLIDER_SET_MIN_FAILED = -1108
    SLIDER_MAX_REACHED = -1109
    SLIDER_MIN_REACHED = -1110
    UNABLE_TO_INCREASE_SLIDER_VALUE = -1111
    UNABLE_TO_DECREASE_SLIDER_VALUE = -1112
    UNABLE_TO_GET_SLIDER_VALUE = -1113
    UNABLE_TO_SET_SPIN_BUTTON_VALUE = -1114
    UNABLE_TO_SPIN_BUTTON_VALUES_NOT_SAME = -1115
    TOGGLE_ACTION_FAILED = -1116
    TOGGLE_CHECKED = -1117
    TOGGLE_NOT_CHECKED = -1118
    TOOLBAR_VISIBLE_BUTTON_COUNT_FAILED = -1119
    TOOLBAR_BUTTON_COUNT_FAILED = -1120
    UNABLE_TO_SET_TEXT = -1121
    UNABLE_TO_CUT_TEXT = -1122
    UNABLE_TO_COPY_TEXT = -1123
    UNABLE_TO_PASTE_TEXT = -1124
    UNABLE_TO_DELETE_TEXT = -1125
    UNABLE_TO_SELECT_TEXT = -1126
    UNABLE_TO_ACTIVATE_TEXT = -1127
    UNABLE_TO_APPEND_TEXT = -1128
    UNABLE_TO_INSERT_TEXT = -1129
    UNABLE_TO_GET_TEXT_PROPERTY = -1130
    ONE_OR_MORE_PROPERTIES_DOES_NOT_MATCH = -1131
    TEXT_OBJECT_VALUE_CONTAINS_DIFF_PROEPRTY = -1132
    TEXT_OBJECT_DOES_NOT_CONTAIN_PROEPRTY = -1133
    TEXT_PROEPRTY_VALUE_PAIR_IS_INVALID = -1134
    TEXT_TO_INSERT_IS_EMPTY = -1135
    VERIFY_SET_TEXT_FAILED = -1136
    VERIFY_PARTIAL_MATCH_FAILED = -1137
    INVALID_COLUMN_INDEX_TO_SORT = -1138
    UNABLE_TO_SORT = -1139
    ROW_DOES_NOT_EXIST = -1140
    COLUMN_DOES_NOT_EXIST = -1141
    UNABLE_TO_SELECT_ROW = -1142
    UNABLE_TO_GET_ROW_INDEX = -1143
    SET_TABLE_CELL_FAILED = -1144
    GET_TABLE_CELL_FAILED = -1145
    VERIFY_TABLE_CELL_FAILED = -1146
    VERIFY_TABLE_CELL_PARTIAL_MATCH_FAILED = -1147
    ACTUAL_ROW_COUNT_LESS_THAN_GIVEN_ROW_COUNT = -1148
    ACTUAL_COLUMN_COUNT_LESS_THAN_GIVEN_COLUMN_COUNT = -1149
    GET_TREE_TABLE_CELL_FAILED = -1150
    NO_CHILD_TEXT_TYPE_UNDER_TABLE = -1151
    UNABLE_TO_PERFORM_ACTION = [-1152, "Unable to perform action"]
    GUI_EXIST = [-1153, "GUI exist"]
    GUI_NOT_EXIST = [-1154, "GUI not exist"]
    CALLBACK = -1155
    UNABLE_TO_CREATE_PO = -1156
    UNABLE_TO_DELETE_PO = -1157
    ONLY_MO_MODE_SUPPORTED = -1158
    UTF8_ENGLISH_LANG = -1159
    UNABLE_TO_STAT_DIR = -1160
    ROLE_NOT_IMPLEMENTED = [-1161, "Role not implemented"]
    UNABLE_TO_MOVE_MOUSE = -1162
    INVALID_FORMAT = [-1163, "Invalid format"]
    TOKEN_NOT_FOUND = [-1164, "Token not found"]
    UNABLE_TO_ENTER_KEY = -1165
    UNABLE_TO_SET_CARET = -1166
    OFFSET_OUT_OF_BOUND = -1167
    TEXT_NOT_ACCESSIBLE = -1168
    STOP_SCRIPT_ENGINE = -1169
    WRONG_COMMAND_SEQUENCE = [-1170, "Wrong command sequence"]
    UNABLE_TO_LAUNCH_APP = [-1171, "Unable to launch app"]
    CLIENT_DISCONNECTED = [-1172, "Client disconnected"]
    EVENT_NOTIFIER_NOT_ENABLED = -1173
    SET_GUI_TIMEOUT_FAILED = -1174
    SET_OBJ_TIMEOUT_FAILED = -1175
    UNABLE_TO_GET_DEVICE = -1176
    UNABLE_TO_GET_CHILD_WITH_PROVIDED_ROLE = -1177
    UNABLE_TO_GET_PAGE_TAB_NAME = -1178
    UNABLE_TO_VERIFY_PAGE_TAB_NAME = -1179
    CHECK_BOX_STATE_NOT_ENABLED = -1180
    PUSH_BUTTON_STATE_NOT_ENABLED = -1181
    TOGGLE_BUTTON_STATE_NOT_ENABLED = -1182
    UNABLE_TO_GET_WINDOW_LIST = [-1183, "Unable to get window list"]
    COMMAND_FAILED = [-1184, "Command failed"]
    UNABLE_TO_SET_SLIDER_VALUE = [-1185, "Unable to set slider value"]
    COMMAND_NOT_SUPPORTED = [-1186, "Command not supported on this platform"]
    UNABLE_TO_GET_OBJECT_STATE = [-1187,
                                   "Unable to get all object states"]
    SET_APP_UNDER_TEST_NAME_FAILED = [-1188,
                                       "Setting application name under test failed"]
    UNABLE_TO_DESELECT_LAYERED_PANE_ITEM = [-1189,
                                             "Unable to deselect layared pane item"]
    CHILD_NOT_SELECTED = [-1190, "Child not selected"]
    UNABLE_TO_GET_SELECTED_ITEM_COUNT = [-1191,
                                          "Unable to get selected item count"]
    MOUSE_ACTION_FAILED = [-1192, "Mouse action failed"]
    PROGRESSBAR_NOT_VISIBLE = [-1193, "Progress bar not visible"]

class ExtendedRole:
    CALENDAR_VIEW = 1001 # Extended role, so using custom value
    CALENDAR_EVENT = 1002 # Extended role, so using custom value

class XmlTags:
    XML_HEADER                   = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
    RESPONSE_ELEMENT             = "<RESPONSE>"
    RESPONSE_ID_ELEMENT          = "<ID>"
    RESPONSE_ID_END_ELEMENT      = "</ID>"
    STATUS_ELEMENT               = "<STATUS>"
    ATTRIBUTE_CODE_ELEMENT       = "<CODE>"
    ATTRIBUTE_CODE_END_ELEMENT   = "</CODE>"
    ATTRIBUTE_MSG_ELEMENT        = "<MESSAGE>"
    ATTRIBUTE_MSG_END_ELEMENT    = "</MESSAGE>"
    STATUS_END_ELEMENT           = "</STATUS>"
    DATA_ELEMENT                 = "<DATA>"
    ATTRIBUTE_LENGTH_ELEMENT     = "<LENGTH>"
    ATTRIBUTE_LENGTH_END_ELEMENT = "</LENGTH>"
    ATTRIBUTE_FILE_ELEMENT       = "<FILE>"
    ATTRIBUTE_FILE_END_ELEMENT   = "</FILE>"
    ATTRIBUTE_NAME_ELEMENT       = "<NAME>"
    ATTRIBUTE_NAME_END_ELEMENT   = "</NAME>"
    ATTRIBUTE_VALUE_ELEMENT      = "<VALUE><![CDATA["
    ATTRIBUTE_VALUE_END_ELEMENT  = "]]></VALUE>"
    DATA_END_ELEMENT             = "</DATA>"
    RESPONSE_END_ELEMENT         = "</RESPONSE>"
    NOTIFICATION_ELEMENT         = "<NOTIFICATION>"
    NOTIFICATION_END_ELEMENT     = "</NOTIFICATION>"

class error (Exception):
    def __init__ (self, value):
        self.value = value
    def __str__ (self):
        return repr (self.value)

class LdtpExecutionError (Exception):
    def __init__ (self, value):
        self.value = value
    def __str__ (self):
        return repr (self.value)

class ConnectionLost (Exception):
    def __init__ (self, value):
        self.value = value
    def __str__ (self):
        return repr (self.value)

def connect2LdtpExecutionEngine ():
    _display = os.getenv ('DISPLAY')
    
    if _display == None:
        raise LdtpExecutionError ('Missing DISPLAY environment variable. Running in text mode ?')    

    _userName = 'LDTP'
    if os.getenv ('USER'):
        _userName = os.getenv ('USER')
    elif os.getenv ('LOGNAME'):
        _userName = os.getenv ('LOGNAME')

    if _ldtpDebug:
        commands.getstatusoutput ('mkdir -p /tmp/ldtp-%s' % _userName)

    _mainSock = None
    _socketPath = '/tmp/ldtp-%s-%s' % (_userName, _display)
    
    _ldtpUseTcp = False
    _ldtpServerAddr = None
    _ldtpServerPort = None
    if os.environ.has_key ("LDTP_SERVER_ADDR"):
        _ldtpServerAddr = os.environ ["LDTP_SERVER_ADDR"]
        if os.environ.has_key ("LDTP_SERVER_PORT"):
            _ldtpServerPort = int (os.environ ["LDTP_SERVER_PORT"])
        else:
            _ldtpServerPort = 23456
        _ldtpUseTcp = True

    try:
        # Create a client socket
        _mainSock = None
        if _ldtpUseTcp:
            _mainSock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
        else:
            _mainSock = socket.socket (socket.AF_UNIX, socket.SOCK_STREAM)
    except socket.error,msg:
        if _ldtpUseTcp:
            raise LdtpExecutionError ('Error while creating socket  ' + str (msg))
        else:
            raise LdtpExecutionError ('Error while creating UNIX socket  ' + str (msg))    
    
    # Let us retry connecting to the server for 3 times
    _retryCount = 0

    while True:
        try:
            try:
                # Connect to server socket
                if _ldtpUseTcp:
                    _mainSock.connect((_ldtpServerAddr, _ldtpServerPort))
                else:
                    _mainSock.connect (_socketPath)
                return _mainSock, _ldtpUseTcp
            except TypeError:
                raise ConnectionLost ('Environment LDTP_AUTH_SOCK variable not set')
        except socket.error, msg:
            if _retryCount == 3:
                raise ConnectionLost ('Could not establish connection ' + str (msg))
            _retryCount += 1
            #If we are not trying to connect to a remote server then we can attempt to
            #startup the ldtp server and then try to re-connect to it.
            if not _ldtpUseTcp:
                _pid = os.fork ()
                if _pid == 0:
                    try:
                        os.execvpe ('ldtp', [''], os.environ)
                    except OSError:
                        raise LdtpExecutionError ('ldtp executable not in PATH')
                else:
                    # Let us wait for 1 second, let the server starts
                    time.sleep (1)

def getText (nodelist):
    rc = ""
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc = rc + node.data
    return rc

def getCData (nodelist):
    rc = ""
    for node in nodelist:
        if node.nodeType == node.CDATA_SECTION_NODE:
            rc = rc + node.data
    return rc

def wait (seconds = 5):
    try:
        time.sleep (seconds)
    except TypeError:
        time.sleep (5)

def waitnanoseconds (nanoSeconds = 30000.0):
    try:
        time.sleep (nanoSeconds / pow (10, 9))
    except TypeError:
        time.sleep (30000.0 / pow (10, 9))

def timeElapsed (prevTime):
    currTime = int (time.time () - prevTime)
    return currTime

# Send given packet to server
def sendpacket (msg, clientFd = None, recorder = False):
    flag = False
    try:
        try:
            _sendLck.acquire ()
            flag = True
            if clientFd is None:
                # Get client socket fd based on thread id
                clientFd = sockFdPool.get (threading.currentThread ())
                if clientFd is None:
                    _mainSock, _ldtpUseTcp = connect2LdtpExecutionEngine ()
                    clientFd = sockFdPool [threading.currentThread ()] = _mainSock

            # Encode the message in UTF-8 so we don't break on extended
            # characters in the application GUIs
            try:
                buf = msg.encode ('utf-8')
            except UnicodeDecodeError:
                buf = unicode (msg, 'utf-8').encode ('utf-8')
			
            # Pack length (integer value) in network byte order
            msglen = struct.pack ('!i', len (buf))
            # Send message length
            clientFd.send (msglen)
            # Send message
            clientFd.send (buf)
            if _ldtpDebug != None and _ldtpDebug == '2':
                print 'Send packet', buf
            #_sendLck.release ()
        except socket.error, msg:
            if not recorder:
                _mainSock, _ldtpUseTcp = connect2LdtpExecutionEngine ()
                sockFdPool [threading.currentThread ()] = _mainSock
            raise LdtpExecutionError ('Server aborted')
        except:
            if hasattr (traceback, 'format_exc'):
                if _ldtpDebug:
                    print traceback.format_exc ()
                raise LdtpExecutionError (str (traceback.format_exc ()))
            else:
                if _ldtpDebug:
                    print traceback.print_exc ()
                raise LdtpExecutionError (str (traceback.print_exc ()))
    finally:
        if flag:
            # Reason for using the flag:
            # 'Do not call this method when the lock is unlocked.'
            _sendLck.release ()
            flag = False

def recvpacket (sockfd = None):
    try:
        clientFd = None
        # Get client socket fd based on thread id
        if sockfd:
            clientFd = sockfd
        else:
            clientFd = sockFdPool.get (threading.currentThread ())
        _responsePacket = None
        clientFd.settimeout (5.0)
        # Hardcoded 4 bytes, as the server sends 4 bytes as packet length
        data = clientFd.recv (4)
        if data == '' or data == None:
            if _ldtpDebug:
                print 'No data received'
            return None
        _actualPacketSize, = struct.unpack('!i', data)
        if _ldtpDebug != None and _ldtpDebug == '2':
            print 'Received packet size', _actualPacketSize

        _receivedPacketSize = 0
        _responsePacket = ''
        _receivePacketSize = 512
        while _receivedPacketSize < _actualPacketSize:
            # Receive given packet size
            _receivedPacket = clientFd.recv (_receivePacketSize)
            # append received packet to the response packet
            _responsePacket += _receivedPacket
            # Add the received packet size
            _receivedPacketSize += len (_receivedPacket)
            # Check the packets remaining to be received
            # If total received packet size + 512 is greater than actual packet size
            # then use the difference size else use 512 bytes per read
            if _receivedPacketSize + 512 > _actualPacketSize:
                _receivePacketSize = _actualPacketSize - _receivedPacketSize
        if _ldtpDebug != None and _ldtpDebug == '2':
            print 'Received response Packet', _responsePacket
        return _responsePacket
    except struct.error, msg:
        raise LdtpExecutionError ('Invalid packet length ' + str (msg))
    except socket.timeout:
        # Incase of timeout, let LdtpExecutionError be raised with Timeout string
        raise LdtpExecutionError, "Timeout"
    except:
        if hasattr (traceback, 'format_exc'):
            raise LdtpExecutionError ('Error while receiving packet ' + str (traceback.format_exc ()))
        else:
            raise LdtpExecutionError ('Error while receiving packet ' + str (traceback.print_exc ()))

def getErrorMessage (errorCode, args):
    msg = None
    if errorCode == LdtpErrorCode.SUCCESS: 
        msg = "Successfully completed"
    elif errorCode == LdtpErrorCode.ARGUMENT_NONE:
        msg = "Argument cannot be None. Please check the arguments."
    elif errorCode == LdtpErrorCode.ACCEPT_FAILED:
        msg = "Error occurred while accepting request from client.  Please retry."
    elif errorCode == LdtpErrorCode.UNABLE_TO_REINIT_LDTP:
        msg = "Unable to reinitialize LDTP"
    elif errorCode == LdtpErrorCode.UNABLE_TO_ALLOCATE_MEMORY:
        msg = "Unable to allocate memory"
    elif errorCode == LdtpErrorCode.UNABLE_TO_GET_APPLICATION_LIST:
        msg = "Unable to get application list"
    elif errorCode == LdtpErrorCode.UNABLE_TO_GET_OBJECT_LIST:
        msg = "Unable to get object list"
    elif errorCode == LdtpErrorCode.THREAD_CREATION_FAILED:
        msg = "Error creating client thread. Please retry."
    elif errorCode == LdtpErrorCode.THREAD_DETACH_FAILED:
        msg = "Unable to detach the thread"
    elif errorCode == LdtpErrorCode.PACKET_INVALID:
        msg = "Packet received from client is not valid"
    elif errorCode == LdtpErrorCode.RECEIVE_RESPONSE:
        msg = "Error occurred while receiving response from client"
    elif errorCode == LdtpErrorCode.SENDING_RESPONSE:
        msg = "Error occurred while sending response to client"
    elif errorCode == LdtpErrorCode.PARTIAL_DATA_SENT:
        msg = "Warning!! Partial data sent"
    elif errorCode == LdtpErrorCode.INVALID_COMMAND:
        msg = "Invalid command"
    elif errorCode == LdtpErrorCode.INVALID_STATE:
        msg = "Invalid state"
    elif errorCode == LdtpErrorCode.APPMAP_NOT_INITIALIZED:
        msg = "Application map not initialized"
    elif errorCode == LdtpErrorCode.OPENING_APPMAP_FILE: # FIXME: its better we show the filename with full path
        msg = "Unable to open appmap file"
    elif errorCode == LdtpErrorCode.OPENING_LOG_FILE: # FIXME: its better we show the filename with full path
        msg = "Unable to open log file"
    elif errorCode == LdtpErrorCode.APP_NOT_RUNNING:
        msg = "Application not running"
    elif errorCode == LdtpErrorCode.UNABLE_TO_UPDATE_APPMAP:
        msg = "Unable to update appmap at runtime"
    elif errorCode == LdtpErrorCode.WIN_NAME_NOT_FOUND_IN_APPMAP:
        msg = "Unable to find window name in application map."
    elif errorCode == LdtpErrorCode.OBJ_NAME_NOT_FOUND_IN_APPMAP:
        msg = "Unable to find object name in application map"
    elif errorCode == LdtpErrorCode.WIN_NOT_OPEN:
        msg = "Window does not exist"
    elif errorCode == LdtpErrorCode.UNABLE_TO_GET_CONTEXT_HANDLE:
        msg = "Unable to get context handle"
    elif errorCode == LdtpErrorCode.UNABLE_TO_GET_COMPONENT_HANDLE:
        msg = "Unable to get component handle"
    elif errorCode == LdtpErrorCode.UNABLE_TO_GET_PROPERTY:
        msg = "Unable to get property"
    elif errorCode == LdtpErrorCode.GET_OBJ_HANDLE_FAILED:
        msg = "Unable to get object handle"
    elif errorCode == LdtpErrorCode.UNABLE_TO_GET_CELL_HANDLE_FAILED:
        msg = "Unable to get cell handle"
    elif errorCode == LdtpErrorCode.OBJ_INFO_MISMATCH:
        msg = "Object information does not match with application map entry"
    elif errorCode == LdtpErrorCode.COMMAND_NOT_IMPLEMENTED:
        msg = "Requested action on mentioned object is not implemented"
    elif errorCode == LdtpErrorCode.GETTEXTVALUE_FAILED:
        msg = "GetTextValue action on mentioned object failed"
    elif errorCode == LdtpErrorCode.CHILD_TYPE_UNIDENTIFIED:
        msg = "Unable to identify the child type of mentioned object"
    elif errorCode == LdtpErrorCode.SELECTITEM_FAILED:
        msg = "SelectItem action on mentioned object failed."
    elif errorCode == LdtpErrorCode.VERIFY_ITEM_FAILED:
        msg = "Verification of selectitem failed on the mentioned object"
    elif errorCode == LdtpErrorCode.SELECTINDEX_FAILED:
        msg = "SelectIndex action on mentioned object failed."
    elif errorCode == LdtpErrorCode.TEXT_NOT_FOUND:
        msg = "Text not found"
    elif errorCode == LdtpErrorCode.TEXT_STATE_ENABLED:
        msg = "Text state enabled"
    elif errorCode == LdtpErrorCode.TEXT_STATE_NOT_ENABLED:
        msg = "Text state not enabled"
    elif errorCode == LdtpErrorCode.SETTEXTVALUE_FAILED:
        msg = "SetTextValue action on mentioned object failed"
    elif errorCode == LdtpErrorCode.VERIFY_SETTEXTVALUE_FAILED:
        msg = "Verification of settextvalue failed on the mentioned object"
    elif errorCode == LdtpErrorCode.CLICK_FAILED:
        msg = "Click action on mentioned object failed"
    elif errorCode == LdtpErrorCode.DOUBLE_CLICK_FAILED:
        msg = "Dobule click action on mentioned object failed"
    elif errorCode == LdtpErrorCode.RIGHT_CLICK_FAILED:
        msg = "Right click action on mentioned object failed"
    elif errorCode == LdtpErrorCode.CHILD_IN_FOCUS:
        msg = "Verelification of HideList failed on the mentioned object as object's list is still in focus"
    elif errorCode == LdtpErrorCode.CHILD_NOT_FOCUSSED:
        msg = "Verelification of DropDown failed on the mentioned object as object's list is not in focus"
    elif errorCode == LdtpErrorCode.MENU_VISIBLE:
        msg = "Verelification of HideList failed on the mentioned object as object's menu is visible"
    elif errorCode == LdtpErrorCode.MENU_NOT_VISIBLE:
        msg = "Verelification of DropDown failed on the mentioned object as object's menu is not visible"
    elif errorCode == LdtpErrorCode.HIDELIST_FAILED:
        msg = "Hide-List action on the mentioned object failed"
    elif errorCode == LdtpErrorCode.SHOWLIST_FAILED:
        msg = "Show-List action on the mentioned object failed"
    elif errorCode == LdtpErrorCode.VERIFY_SHOWLIST_FAILED:
        msg = "Verify show list on the mentioned object failed"
    elif errorCode == LdtpErrorCode.ITEM_NOT_FOUND:
        msg = "SelectItem failed as the mentioned item was not found in the object"
    elif errorCode == LdtpErrorCode.FILECAPTURE_FAILED_OPEN_OUTPUT_FILE:
        msg = "Capture to file action failed: Cannot open output file"
    elif errorCode == LdtpErrorCode.VERIFY_DROPDOWN_FAILED:
        msg = "Verification of dropdown action failed."
    elif errorCode == LdtpErrorCode.CALENDAR_EVENT_INDEX_GREATER:
        msg = "Calendar event index greater than child count"
    elif errorCode == LdtpErrorCode.UNABLE_TO_SELECT_CALENDAR_EVENT_INDEX:
        msg = "Unable to select calendar event index"
    elif errorCode == LdtpErrorCode.UNABLE_TO_SELECT_CALENDAR_EVENT_NAME:
        msg = "Unable to select calendar event based on name"
    elif errorCode == LdtpErrorCode.NO_APPOINTMENTS_IN_CALENDAR:
        msg = "No appointments in calendar"
    elif errorCode == LdtpErrorCode.UNABLE_TO_GET_VALUE:
        msg = "Unable to get value"
    elif errorCode == LdtpErrorCode.UNABLE_TO_GRAB_FOCUS:
        msg = "Unable to grab focus"
    elif errorCode == LdtpErrorCode.OBJ_NOT_COMPONENT_TYPE:
        msg = "Object is not of type component"
    elif errorCode == LdtpErrorCode.INVALID_DATE:
        msg = "Ivalid date, can't be selected"
    elif errorCode == LdtpErrorCode.INVALID_OBJECT_STATE:
        msg = "Invalid object state"
    elif errorCode == LdtpErrorCode.CHECK_ACTION_FAILED:
        msg = "Check action failed"
    elif errorCode == LdtpErrorCode.UNCHECK_ACTION_FAILED:
        msg = "Uncheck action failed"
    elif errorCode == LdtpErrorCode.STATE_CHECKED:
        msg = "Object state is checked"
    elif errorCode == LdtpErrorCode.STATE_UNCHECKED:
        msg = "Object state is unchecked"
    elif errorCode == LdtpErrorCode.UNABLE_TO_SELECT_LABEL:
        msg = "Unable to select label"
    elif errorCode == LdtpErrorCode.LABEL_NOT_FOUND:
        msg = "Label not found"
    elif errorCode == LdtpErrorCode.UNABLE_TO_SELECT_LAYERED_PANE_ITEM:
        msg = "Unable to select item in layered pane"
    elif errorCode == LdtpErrorCode.UNABLE_TO_SELECT_TEXT_ITEM:
        msg = "Unable to select text item in the list"
    elif errorCode == LdtpErrorCode.LIST_INDEX_GREATER:
        msg = "List index value is greater than available index"
    elif errorCode == LdtpErrorCode.UNABLE_TO_GET_SELECTED_CHILD:
        msg = "Unable to get the selected child item from the list"
    elif errorCode == LdtpErrorCode.UNABLE_TO_SELECT_CHILD:
        msg = "Unable to select the child item in the list"
    elif errorCode == LdtpErrorCode.UNABLE_TO_GET_CHILD_MENU_ITEM:
        msg = "Unable to get the child menu item"
    elif errorCode == LdtpErrorCode.UNABLE_TO_GET_MENU_HANDLE:
        msg = "Unable to get menu handle"
    elif errorCode == LdtpErrorCode.MENU_ITEM_DOES_NOT_EXIST:
        msg = "Menu item does not exist"
    elif errorCode == LdtpErrorCode.UNABLE_TO_FIND_POPUP_MENU:
        msg = "Unable to find popup menu"
    elif errorCode == LdtpErrorCode.MENU_ITEM_STATE_DISABLED:
        msg = "Menu item state disabled"
    elif errorCode == LdtpErrorCode.SELECT_MENU_ITEM_FAILED:
        msg = "Select menu item failed"
    elif errorCode == LdtpErrorCode.UNABLE_TO_LIST_MENU_ITEMS:
        msg = "Unable to list menu items"
    elif errorCode == LdtpErrorCode.UNABLE_TO_SELECT_LIST_ITEM:
        msg = "Unable to select list item"
    elif errorCode == LdtpErrorCode.PAGE_TAB_NAME_SELECTION_FAILED:
        msg = "Page tab name selection failed"
    elif errorCode == LdtpErrorCode.PAGE_TAB_NAME_ALREADY_IN_SELECTED_STATE:
        msg = "Page tab name already in selected state"
    elif errorCode == LdtpErrorCode.PAGE_TAB_NAME_DOESNOT_EXIST:
        msg = "Page tab name does not exist"
    elif errorCode == LdtpErrorCode.PAGE_TAB_INDEX_DOESNOT_EXIST:
        msg = "Page tab index does not exist"
    elif errorCode == LdtpErrorCode.PAGE_TAB_NAME_INPUT_DOESNOT_EXIST:
        msg = "Page tab name does not exist"
    elif errorCode == LdtpErrorCode.PAGE_TAB_INDEX_INPUT_DOESNOT_EXIST:
        msg = "Page tab index does not exist"
    elif errorCode == LdtpErrorCode.NO_PANEL_EXIST:
        msg = "No panel exist"
    elif errorCode == LdtpErrorCode.PANEL_NAME_SELECTION_FAILED:
        msg = "Panel name selection failed"
    elif errorCode == LdtpErrorCode.PANEL_INDEX_SELECTION_FAILED:
        msg = "Panel index selection failed"
    elif errorCode == LdtpErrorCode.PANEL_COUNT_LESS_THAN_TOTAL_PANEL:
        msg = "Panels count less than total panel number"
    elif errorCode == LdtpErrorCode.RADIO_BUTTON_ALREADY_CHECKED:
        msg = "Radio button already checked"
    elif errorCode == LdtpErrorCode.RADIO_BUTTON_CHECKED:
        msg = "Radio button checked"
    elif errorCode == LdtpErrorCode.RADIO_BUTTON_STATE_NOT_ENABLED:
        msg = "Radio button state not enabled"
    elif errorCode == LdtpErrorCode.RADIO_BUTTON_NOT_CHECKED:
        msg = "Radio button not checked"
    elif errorCode == LdtpErrorCode.RADIO_MENU_ITEM_ALREADY_CHECKED:
        msg = "Radio menu item already checked"
    elif errorCode == LdtpErrorCode.RADIO_MENU_ITEM_CHECKED:
        msg = "Radio menu item checked"
    elif errorCode == LdtpErrorCode.RADIO_MENU_ITEM_NOT_CHECKED:
        msg = "Radio menu item not checked"
    elif errorCode == LdtpErrorCode.NOT_VERTICAL_SCROLL_BAR:
        msg = "Object not a vertical scrollbar"
    elif errorCode == LdtpErrorCode.UNABLE_TO_SCROLL_WITH_GIVEN_VALUE:
        msg = "Unable to scroll with the given value"
    elif errorCode == LdtpErrorCode.NOT_HORIZONTAL_SCROLL_BAR:
        msg = "Object not a horizontal scrollbar"
    elif errorCode == LdtpErrorCode.SCROLL_BAR_MAX_REACHED:
        msg = "Scrollbar trying to access more than maximum limit"
    elif errorCode == LdtpErrorCode.SCROLL_BAR_MIN_REACHED:
        msg = "Scrollbar trying to access less than minimum limit"
    elif errorCode == LdtpErrorCode.NOT_VERTICAL_SLIDER:
        msg = "Object not a vertical slider"
    elif errorCode == LdtpErrorCode.NOT_HORIZONTAL_SLIDER:
        msg = "Object not a horizontal slider"
    elif errorCode == LdtpErrorCode.SLIDER_SET_MAX_FAILED:
        msg = "Slider set maximum value failed"
    elif errorCode == LdtpErrorCode.SLIDER_SET_MIN_FAILED:
        msg = "Slider set minimum value failed"
    elif errorCode == LdtpErrorCode.UNABLE_TO_INCREASE_SLIDER_VALUE:
        msg = "Unable to increase slider value"
    elif errorCode == LdtpErrorCode.UNABLE_TO_DECREASE_SLIDER_VALUE:
        msg = "Unable to decrease slider value"
    elif errorCode == LdtpErrorCode.SLIDER_MAX_REACHED:
        msg = "Slider trying to access more than maximum limit"
    elif errorCode == LdtpErrorCode.SLIDER_MIN_REACHED:
        msg = "Slider trying to access less than minimum limit"
    elif errorCode == LdtpErrorCode.UNABLE_TO_GET_SLIDER_VALUE:
        msg = "Unable to get slider value"
    elif errorCode == LdtpErrorCode.UNABLE_TO_SET_SPIN_BUTTON_VALUE:
        msg = "Unable to set spin button value"
    elif errorCode == LdtpErrorCode.UNABLE_TO_SPIN_BUTTON_VALUES_NOT_SAME:
        msg = "Spin button values are not same"
    elif errorCode == LdtpErrorCode.STATUSBAR_GETTEXT_FAILED:
        msg = "Unable to get text from status bar"
    elif errorCode == LdtpErrorCode.STATUSBAR_NOT_VISIBLE:
        msg = "Status bar not visible"
    elif errorCode == LdtpErrorCode.TOGGLE_ACTION_FAILED:
        msg = "Toggle action failed"
    elif errorCode == LdtpErrorCode.TOGGLE_CHECKED:
        msg = "Toggle button checked"
    elif errorCode == LdtpErrorCode.TOGGLE_NOT_CHECKED:
        msg = "Toggle button not checked"
    elif errorCode == LdtpErrorCode.TOOLBAR_VISIBLE_BUTTON_COUNT_FAILED:
        msg = "Toolbar visible button count failed"
    elif errorCode == LdtpErrorCode.TOOLBAR_BUTTON_COUNT_FAILED:
        msg = "Toolbar button count failed"
    elif errorCode == LdtpErrorCode.UNABLE_TO_SET_TEXT:
        msg = "Unable to set text"
    elif errorCode == LdtpErrorCode.VERIFY_SET_TEXT_FAILED:
        msg = "Verify set text value failed"
    elif errorCode == LdtpErrorCode.VERIFY_PARTIAL_MATCH_FAILED:
        msg = "Verify partial match failed"
    elif errorCode == LdtpErrorCode.UNABLE_TO_CUT_TEXT:
        msg = "Unable to cut text"
    elif errorCode == LdtpErrorCode.UNABLE_TO_COPY_TEXT:
        msg = "Unable to copy text"
    elif errorCode == LdtpErrorCode.UNABLE_TO_INSERT_TEXT:
        msg = "Unable to insert text"
    elif errorCode == LdtpErrorCode.UNABLE_TO_GET_TEXT_PROPERTY:
        msg = "Unable to get text property"
    elif errorCode == LdtpErrorCode.TEXT_OBJECT_VALUE_CONTAINS_DIFF_PROEPRTY:
        msg = "Text object value contains different property"
    elif errorCode == LdtpErrorCode.TEXT_OBJECT_DOES_NOT_CONTAIN_PROEPRTY:
        msg = "Text object does not contain property"
    elif errorCode == LdtpErrorCode.TEXT_PROEPRTY_VALUE_PAIR_IS_INVALID:
        msg = "Given text property value pair is invalid"
    elif errorCode == LdtpErrorCode.ONE_OR_MORE_PROPERTIES_DOES_NOT_MATCH:
        msg = "One or more properties does not match"
    elif errorCode == LdtpErrorCode.TEXT_TO_INSERT_IS_EMPTY:
        msg = "Text to insert is empty"
    elif errorCode == LdtpErrorCode.UNABLE_TO_ACTIVATE_TEXT:
        msg = "Unable to activate text"
    elif errorCode == LdtpErrorCode.UNABLE_TO_PASTE_TEXT:
        msg = "Unable to paste text"
    elif errorCode == LdtpErrorCode.UNABLE_TO_DELETE_TEXT:
        msg = "Unable to delete text"
    elif errorCode == LdtpErrorCode.UNABLE_TO_SELECT_TEXT:
        msg = "Unable to select text"
    elif errorCode == LdtpErrorCode.UNABLE_TO_APPEND_TEXT:
        msg = "Unable to append text"
    elif errorCode == LdtpErrorCode.INVALID_COLUMN_INDEX_TO_SORT:
        msg = "Invalid column index given for sorting"
    elif errorCode == LdtpErrorCode.UNABLE_TO_SORT:
        msg = "Unable to sort"
    elif errorCode == LdtpErrorCode.ROW_DOES_NOT_EXIST:
        msg = "Row does not exist"
    elif errorCode == LdtpErrorCode.COLUMN_DOES_NOT_EXIST:
        msg = "Column does not exist"
    elif errorCode == LdtpErrorCode.UNABLE_TO_SELECT_ROW:
        msg = "Unable to select row"
    elif errorCode == LdtpErrorCode.VERIFY_TABLE_CELL_FAILED:
        msg = "Verify table cell failed"
    elif errorCode == LdtpErrorCode.VERIFY_TABLE_CELL_PARTIAL_MATCH_FAILED:
        msg = "Verify table cell partial match failed"
    elif errorCode == LdtpErrorCode.SET_TABLE_CELL_FAILED:
        msg = "Set table cell failed"
    elif errorCode == LdtpErrorCode.GET_TABLE_CELL_FAILED:
        msg = "Get table cell failed"
    elif errorCode == LdtpErrorCode.GET_TREE_TABLE_CELL_FAILED:
        msg = "Get table cell failed"
    elif errorCode == LdtpErrorCode.UNABLE_TO_GET_ROW_INDEX:
        msg = "Unable to find row index"
    elif errorCode == LdtpErrorCode.NO_CHILD_TEXT_TYPE_UNDER_TABLE:
        msg = "Table cell has no child of type text"
    elif errorCode == LdtpErrorCode.ACTUAL_ROW_COUNT_LESS_THAN_GIVEN_ROW_COUNT:
        msg = "Actual row count less than given row count"
    elif errorCode == LdtpErrorCode.ACTUAL_COLUMN_COUNT_LESS_THAN_GIVEN_COLUMN_COUNT:
        msg = "Actual column count less than given column count"
    elif errorCode == LdtpErrorCode.UNABLE_TO_PERFORM_ACTION:
        msg = "Unable to perform action"
    elif errorCode == LdtpErrorCode.GUI_EXIST:
        msg = "GUI exist"
    elif errorCode == LdtpErrorCode.GUI_NOT_EXIST:
        msg = "GUI does not exist"
    elif errorCode == LdtpErrorCode.CALLBACK:
        msg = "callback"
    elif errorCode == LdtpErrorCode.UNABLE_TO_CREATE_PO:
        msg = "Unable to create po"
    elif errorCode == LdtpErrorCode.UNABLE_TO_DELETE_PO:
        msg = "Unable to delete po"
    elif errorCode == LdtpErrorCode.ONLY_MO_MODE_SUPPORTED:
        msg = "Only MO mode supported"
    elif errorCode == LdtpErrorCode.UTF8_ENGLISH_LANG:
        msg = "UTF8 default English language"
    elif errorCode == LdtpErrorCode.UNABLE_TO_STAT_DIR:
        msg = "Unable to stat directory"
    elif errorCode == LdtpErrorCode.ROLE_NOT_IMPLEMENTED:
        msg = "Mentioned role not implemented."
    elif errorCode == LdtpErrorCode.UNABLE_TO_MOVE_MOUSE:
        msg = "Mouse Cursor move failed"
    elif errorCode == LdtpErrorCode.INVALID_FORMAT:
        msg = "Invalid Format"
    elif errorCode == LdtpErrorCode.TOKEN_NOT_FOUND:
        msg = "Invalid Key"
    elif errorCode == LdtpErrorCode.UNABLE_TO_ENTER_KEY:
        msg = "Error while entering key"
    elif errorCode == LdtpErrorCode.OFFSET_OUT_OF_BOUND:
        msg = "Offset value greater than number of characters"
    elif errorCode == LdtpErrorCode.UNABLE_TO_SET_CARET:
        msg = "Unable to set the cursor position"
    elif errorCode == LdtpErrorCode.TEXT_NOT_ACCESSIBLE:
        msg = "Text box not Accessible"
    elif errorCode == LdtpErrorCode.STOP_SCRIPT_ENGINE:
        msg = "Stop LDTP script engine"
    elif errorCode == LdtpErrorCode.WRONG_COMMAND_SEQUENCE:
        msg = "Wrong command sequence, stop called before start"
    elif errorCode == LdtpErrorCode.UNABLE_TO_LAUNCH_APP:
        msg = "Unable to launch application"
    elif errorCode == LdtpErrorCode.CLIENT_DISCONNECTED:
        msg = "Client disconnected"
    elif errorCode == LdtpErrorCode.EVENT_NOTIFIER_NOT_ENABLED:
        msg = "Event notifier not registered"
    elif errorCode == LdtpErrorCode.SET_GUI_TIMEOUT_FAILED:
        msg = "Unable to set gui timeout period"
    elif errorCode == LdtpErrorCode.SET_OBJ_TIMEOUT_FAILED:
        msg = "Unable to set object timeout period"
    elif errorCode == LdtpErrorCode.UNABLE_TO_GET_DEVICE:
        msg = "Unable to get device control"
    elif errorCode == LdtpErrorCode.UNABLE_TO_GET_CHILD_WITH_PROVIDED_ROLE:
        msg = "Unable to get child with provided role"
    elif errorCode == LdtpErrorCode.UNABLE_TO_GET_PAGE_TAB_NAME:
        msg = "Unable to get page tab name"
    elif errorCode == LdtpErrorCode.UNABLE_TO_VERIFY_PAGE_TAB_NAME:
        msg = "Unable to verify page tab name"
    elif errorCode == LdtpErrorCode.CHECK_BOX_STATE_NOT_ENABLED:
        msg = "Check box state not enabled"
    elif errorCode == LdtpErrorCode.PUSH_BUTTON_STATE_NOT_ENABLED:
        msg = "Push button state not enabled"
    elif errorCode == LdtpErrorCode.TOGGLE_BUTTON_STATE_NOT_ENABLED:
        msg = "Toggle button state not enabled"
    elif errorCode == LdtpErrorCode.UNABLE_TO_GET_WINDOW_LIST:
        msg = "Unable to get window list"
    elif errorCode == LdtpErrorCode.PROGRESSBAR_NOT_VISIBLE:
        msg = "Progress bar not visible"
    else:
        msg = "Error code not found"
    return msg

LDTP_LOG_TESTSTART = 61
LDTP_LOG_TESTEND   = 62
LDTP_LOG_BEGIN     = 63
LDTP_LOG_END       = 64
LDTP_LOG_FAIL      = 65
LDTP_LOG_PASS      = 66
LDTP_LOG_CAUSE     = 67
LDTP_LOG_COMMENT   = 68
LDTP_LOG_GROUPSTART  = 69
LDTP_LOG_GROUPEND    = 70
LDTP_LOG_SCRIPTSTART = 71
LDTP_LOG_SCRIPTEND   = 72
LDTP_LOG_MEMINFO     = 73
LDTP_LOG_CPUINFO     = 74
LDTP_LOG_CATEGORYSTART  = 75
LDTP_LOG_CATEGORYEND    = 76
LDTP_LOG_CATEGORYSTATUS = 77
LDTP_LOG_LOGSTARTTAG    = 78
LDTP_LOG_LOGSTOPTAG     = 79
LDTP_LOG_GROUPSSTATUS   = 80
LDTP_LOG_TIMEINFO       = 81
LDTP_LOG_TOTALTIMEINFO  = 82
LDTP_LOG_SCREENSHOT     = 83

logging.addLevelName (LDTP_LOG_TESTSTART, 'teststart')
logging.addLevelName (LDTP_LOG_TESTEND, 'testend')
logging.addLevelName (LDTP_LOG_BEGIN, 'begin')
logging.addLevelName (LDTP_LOG_END, 'end')
logging.addLevelName (LDTP_LOG_FAIL, 'fail')
logging.addLevelName (LDTP_LOG_PASS, 'pass')
logging.addLevelName (LDTP_LOG_CAUSE, 'cause')
logging.addLevelName (LDTP_LOG_COMMENT, 'comment')
logging.addLevelName (LDTP_LOG_GROUPSTART, 'groupstart')
logging.addLevelName (LDTP_LOG_GROUPSSTATUS, 'groupsstatus')
logging.addLevelName (LDTP_LOG_GROUPEND, 'groupend')
logging.addLevelName (LDTP_LOG_SCRIPTSTART, 'scriptstart')
logging.addLevelName (LDTP_LOG_SCRIPTEND, 'scriptend')
logging.addLevelName (LDTP_LOG_MEMINFO, 'meminfo')
logging.addLevelName (LDTP_LOG_CPUINFO, 'cpuinfo')
logging.addLevelName (LDTP_LOG_LOGSTARTTAG, 'logstarttag')
logging.addLevelName (LDTP_LOG_LOGSTOPTAG, 'logstoptag')
logging.addLevelName (LDTP_LOG_TIMEINFO, 'timeinfo')
logging.addLevelName (LDTP_LOG_TOTALTIMEINFO, 'totaltimeinfo')
logging.addLevelName (LDTP_LOG_CATEGORYSTART, 'categorystart')
logging.addLevelName (LDTP_LOG_CATEGORYEND, 'categoryend')
logging.addLevelName (LDTP_LOG_CATEGORYSTATUS, 'categorystatus')
logging.addLevelName (LDTP_LOG_SCREENSHOT, 'screenshot')

_customLogLevel = {}
_customLogIndex = 1001

def setInternalLogLevel (level, logHandler):
    if logHandler == None:
        return 0
    if type (level) == unicode or type (level) == str:
        regexp = re.compile ('\A' + level, re.I)
        logLevel = None
        if regexp.search ('critical') != None:
            logLevel = logging.CRITICAL
        elif regexp.search ('error') != None:
            logLevel = logging.ERROR
        elif regexp.search ('warning') != None:
            logLevel = logging.WARNING
        elif regexp.search ('info') != None:
            logLevel = logging.INFO
        elif regexp.search ('debug') != None:
            logLevel = logging.DEBUG
        if logLevel != None:
            try:
                logHandler.setLevel (logLevel)
            except:
                logLevel = logging.INFO
            return 1
        else:
            return 0
    logHandler.setLevel (level)
    return 1

class LdtpLogRecord (logging.LogRecord):
    """
    LogRecord subclass that stores a unique -- transaction -- time
    as an additional attribute
    """
    def __init__ (self, name, level, pathname, lineno, msg, args, exc_info):
        if level == LDTP_LOG_LOGSTARTTAG:
            msg = '<' + saxutils.escape (msg) + '>'
        elif level == LDTP_LOG_LOGSTOPTAG:
            msg = '</' + saxutils.escape (msg) + '>'
        elif level == LDTP_LOG_GROUPSTART:
            msg = '<group name=\"' + saxutils.escape (msg) + '\">'
        elif level == LDTP_LOG_GROUPEND:
            msg = '</group>'
        elif level == LDTP_LOG_CATEGORYSTART:
            msg = '<category name=\"' + saxutils.escape (msg) + '\">'
        elif level == LDTP_LOG_CATEGORYEND:
            msg = '</category>'
        elif level == LDTP_LOG_SCRIPTSTART:
            msg = '<script name=\"' + saxutils.escape (msg) + '\">'
        elif level == LDTP_LOG_SCRIPTEND:
            msg = '</script>'
        elif level == LDTP_LOG_TESTSTART:
            msg = '<test name=\"' + saxutils.escape (msg) + '\">'
        elif level == LDTP_LOG_TESTEND:
            msg = '</test>'
        elif level == LDTP_LOG_BEGIN:
            msg = '<testsuite name=\"' + saxutils.escape (msg) + '\">'
        elif level == LDTP_LOG_END:
            msg = '</testsuite>'
        elif level == LDTP_LOG_PASS:
            msg = '<pass>1</pass>'
        elif level == LDTP_LOG_FAIL:
            msg = '<pass>0</pass>'
        elif level == LDTP_LOG_GROUPSSTATUS:
            msg = '<groupsstatus ' + saxutils.escape (msg) + '></groupsstatus>'
        elif level == LDTP_LOG_CATEGORYSTATUS:
            msg = '<categorystatus ' + saxutils.escape (msg) + '></categorystatus>'
        elif level == LDTP_LOG_TIMEINFO:
            msg = '<timeinfo ' + saxutils.escape (msg) + '></timeinfo>'
        elif level == LDTP_LOG_TOTALTIMEINFO:
            msg = '<totaltimeinfo ' + saxutils.escape (msg) + '></totaltimeinfo>'
        else:
            msg = '<' + logging.getLevelName (level).lower () +'>' + \
                saxutils.escape (msg) + '</' + logging.getLevelName (level).lower () + '>'
        if sys.version_info [0] >= 3 or (sys.version_info [0] >= 2 and \
                                             sys.version_info [1] >= 5):
            logging.LogRecord.__init__ (self, name, level, pathname, \
                                            lineno, msg, args, exc_info, None)
        else:
            logging.LogRecord.__init__ (self, name, level, pathname, \
                                            lineno, msg, args, exc_info)

if sys.version_info [0] >= 3 or (sys.version_info [0] >= 2 and sys.version_info [1] >= 5):
    def makeRecord (self, name, level, fn, lno, msg, args, exc_info, func = None, extra = None):
        if type (level) != int and len (msg) == 0:
            exc_info = args
            args = msg
            msg = lno
            lno = fn
            fn = level
            level = name
            name = logging.getLogger ('XML').name
            return LdtpLogRecord (name, level, fn, lno, msg, args, exc_info)
else:
    def makeRecord (name, level, fn, lno, msg, args, exc_info, func = None, extra = None):
        return LdtpLogRecord (name, level, fn, lno, msg, args, exc_info)
        
class LdtpLogger (logging.Logger):
    """
    Logger subclass that uses CustomLogRecord as its LogRecord class
    """
    def __init__ (self, name, level = logging.NOTSET):
        logging.Logger.__init__ (self, name, level)

def startInternalLog (logFileName, fileOverWrite, loggerCode):
    try:
        logging.setLoggerClass (LdtpLogger)
        logHandler = logging.getLogger (loggerCode)
        xmlHdlr = None
        xmlLogMode = 'w'
        if fileOverWrite == 0:
            xmlLogMode = 'a'
        try:
            if logFileName [0] == "~":
                logFileName = os.path.expanduser (logFileName)
            elif logFileName [0] == ".":
                logFileName = os.path.abspath (logFileName)
            xmlHdlr = logging.FileHandler (logFileName, xmlLogMode)
            logHandler.addHandler (xmlHdlr)
            logHandler.setLevel (logging.WARNING)
            logHandler.makeRecord = makeRecord
            if fileOverWrite == 1:
                logHandler.log (LDTP_LOG_LOGSTARTTAG, 'ldtp')
        except IOError:
            if _ldtpDebug:
                if hasattr (traceback, 'format_exc'):
                    print traceback.format_exc ()
                else:
                    print traceback.print_exc ()
                return None, None
        if not xmlHdlr:
            # If xmlHdlr handler is not created, then let us enable this
            logHandler.manager.emittedNoHandlerWarning = 1
        return logHandler, xmlHdlr
    except:
        if _ldtpDebug:
            if hasattr (traceback, 'format_exc'):
                print traceback.format_exc ()
            else:
                print traceback.print_exc ()
        return None, None

def isPriority (priority, givenPriority):
    regexp = re.compile ('\A' + priority, re.I)
    if regexp.search (givenPriority) == None:
        return False
    return True

def internalLog (message, priority, logHandler):
    if logHandler == None:
        # Let us not process anything
        return 1

    if message is None:
        # Let us not process anything
        return 1
    if message.__class__ == LdtpExecutionError:
        message = message.value

    if priority == None or priority == '' or type (priority) != str or \
            isPriority ('debug', priority):
        logHandler.debug (message)
    elif isPriority ('info', priority):
        logHandler.info (message)
    elif isPriority ('pass', priority):
        logHandler.log (LDTP_LOG_PASS, message)
    elif isPriority ('fail', priority):
        logHandler.log (LDTP_LOG_FAIL, message)
    elif isPriority ('error', priority):
        logHandler.error (message)
    elif isPriority ('critical', priority):
        logHandler.critical (message)
    elif isPriority ('screenshot', priority):
        logHandler.log (LDTP_LOG_SCREENSHOT, message)
    elif isPriority ('warn', priority):
        logHandler.warning (message)
    elif isPriority ('cause', priority):
        logHandler.log (LDTP_LOG_CAUSE, message)
    elif isPriority ('comment', priority):
        logHandler.log (LDTP_LOG_COMMENT, message)
    elif isPriority ('meminfo', priority):
        logHandler.log (LDTP_LOG_MEMINFO, message)
    elif isPriority ('cpuinfo', priority):
        logHandler.log (LDTP_LOG_CPUINFO, message)
    elif isPriority ('groupstart', priority):
        logHandler.log (LDTP_LOG_GROUPSTART, message)
    elif isPriority ('categorystart', priority):
        logHandler.log (LDTP_LOG_CATEGORYSTART, message)
    elif isPriority ('groupsstatus', priority):
        logHandler.log (LDTP_LOG_GROUPSSTATUS, message)
    elif isPriority ('groupend', priority):
        logHandler.log (LDTP_LOG_GROUPEND, message)
    elif isPriority ('categoryend', priority):
        logHandler.log (LDTP_LOG_CATEGORYEND, message)
    elif isPriority ('categorystatus', priority):
        logHandler.log (LDTP_LOG_CATEGORYSTATUS, message)
    elif isPriority ('scriptstart', priority):
        logHandler.log (LDTP_LOG_SCRIPTSTART, message)
    elif isPriority ('scriptend', priority):
        logHandler.log (LDTP_LOG_SCRIPTEND, message)
    elif isPriority ('teststart', priority):
        logHandler.log (LDTP_LOG_TESTSTART, message)
    elif isPriority ('testend', priority):
        logHandler.log (LDTP_LOG_TESTEND, message)
    elif isPriority ('begin', priority):
        logHandler.log (LDTP_LOG_BEGIN, message)
    elif isPriority ('end', priority):
        logHandler.log (LDTP_LOG_END, message)
    elif isPriority ('timeinfo', priority):
        logHandler.log (LDTP_LOG_TIMEINFO, message)
    elif isPriority ('totaltimeinfo', priority):
        logHandler.log (LDTP_LOG_TOTALTIMEINFO, message)
    else:
        global _customLogLevel, _customLogIndex
        if priority not in _customLogLevel:
            logging.addLevelName (_customLogIndex, priority)
            _customLogLevel [priority] = _customLogIndex
            _customLogIndex += 1
            logHandler.log (_customLogLevel [priority], message)
        else:
            logHandler.log (_customLogLevel [priority], message)
    return 1

def internalStopLog (handler, xmlHdlr, logHandler):
    if handler:
        logHandler.removeHandler (handler)
    elif xmlHdlr:
        logHandler.log (LDTP_LOG_LOGSTOPTAG, 'ldtp')
        logHandler.removeHandler (xmlHdlr)
    return 1

def addInternalLogger (confFileName):
    logging.config.fileConfig (confFileName)

def escapeChars (str2escape, escapeDot = True):
    str2escape = re.sub ("(?i) +", "", str2escape)
    str2escape = re.sub ("(?i)\n+", "", str2escape)
    if escapeDot:
        str2escape = re.sub ("(?i)\.+", "", str2escape)
        str2escape = re.sub ("(?i)_+", "", str2escape)
        str2escape = re.sub ("(?i):+", "", str2escape)
    return str2escape

def escapeChar (str2escape, char):
    if char == '*':
        char = ".*"
    str2escape = re.sub ("(?i)%s+" % char, "", str2escape)
    return str2escape

def lineno ():
    """Return the current file and line number"""
    if re.search ('/', inspect.currentframe ().f_back.f_code.co_filename):
        _fileName = re.split ('/',
                              inspect.currentframe ().f_back.f_code.co_filename) [-1]
    else:
        _fileName = inspect.currentframe ().f_back.f_code.co_filename
    return '%s : %d' % (_fileName,
                        inspect.currentframe ().f_back.f_lineno)

def grabFocus (accessible):
    if accessible is None:
        return LdtpErrorCode.ARGUMENT_NONE
    try:
        _component = accessible.queryComponent ()
        _flag = False
        if _component:
            _flag = _component.grabFocus ()
            if _ldtpDebug:
                print 'Grab focus %s' % _flag
            _component.unref ()
        else:
            return LdtpErrorCode.OBJ_NOT_COMPONENT_TYPE
        if _flag:
            return LdtpErrorCode.SUCCESS
        else:
            return LdtpErrorCode.UNABLE_TO_GRAB_FOCUS
    except:
        return LdtpErrorCode.OBJ_NOT_COMPONENT_TYPE

# Send lock
_sendLck = threading.Lock ()
# Recieve lock
_recvLck = threading.Lock ()

# Socket fd pool
sockFdPool = {}