techprotrade commited on
Commit
69b5490
·
verified ·
1 Parent(s): f36aa21

Add loan-advisor-agent

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/COM_Records.html +382 -0
  3. loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/GeneratedSupport.html +104 -0
  4. loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/PythonCOM.html +90 -0
  5. loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/QuickStartClientCom.html +82 -0
  6. loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/QuickStartServerCom.html +195 -0
  7. loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/docindex.html +23 -0
  8. loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/image/BTN_HomePage.gif +0 -0
  9. loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/image/BTN_ManualTop.gif +0 -0
  10. loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/image/BTN_NextPage.gif +0 -0
  11. loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/image/BTN_PrevPage.gif +0 -0
  12. loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/image/blank.gif +0 -0
  13. loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/image/pycom_blowing.gif +0 -0
  14. loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/image/pythoncom.gif +0 -0
  15. loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/image/www_icon.gif +0 -0
  16. loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/index.html +31 -0
  17. loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/misc.html +18 -0
  18. loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/package.html +37 -0
  19. loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/variant.html +162 -0
  20. loan-advisor-agent/.venv/Lib/site-packages/win32com/License.txt +30 -0
  21. loan-advisor-agent/.venv/Lib/site-packages/win32com/__init__.py +134 -0
  22. loan-advisor-agent/.venv/Lib/site-packages/win32com/client/CLSIDToClass.py +60 -0
  23. loan-advisor-agent/.venv/Lib/site-packages/win32com/client/__init__.py +703 -0
  24. loan-advisor-agent/.venv/Lib/site-packages/win32com/client/build.py +774 -0
  25. loan-advisor-agent/.venv/Lib/site-packages/win32com/client/combrowse.py +605 -0
  26. loan-advisor-agent/.venv/Lib/site-packages/win32com/client/connect.py +48 -0
  27. loan-advisor-agent/.venv/Lib/site-packages/win32com/client/dynamic.py +699 -0
  28. loan-advisor-agent/.venv/Lib/site-packages/win32com/client/gencache.py +825 -0
  29. loan-advisor-agent/.venv/Lib/site-packages/win32com/client/genpy.py +1352 -0
  30. loan-advisor-agent/.venv/Lib/site-packages/win32com/client/makepy.py +453 -0
  31. loan-advisor-agent/.venv/Lib/site-packages/win32com/client/selecttlb.py +182 -0
  32. loan-advisor-agent/.venv/Lib/site-packages/win32com/client/tlbrowse.py +277 -0
  33. loan-advisor-agent/.venv/Lib/site-packages/win32com/client/util.py +103 -0
  34. loan-advisor-agent/.venv/Lib/site-packages/win32com/demos/__init__.py +0 -0
  35. loan-advisor-agent/.venv/Lib/site-packages/win32com/demos/connect.py +97 -0
  36. loan-advisor-agent/.venv/Lib/site-packages/win32com/demos/dump_clipboard.py +74 -0
  37. loan-advisor-agent/.venv/Lib/site-packages/win32com/demos/eventsApartmentThreaded.py +98 -0
  38. loan-advisor-agent/.venv/Lib/site-packages/win32com/demos/eventsFreeThreaded.py +92 -0
  39. loan-advisor-agent/.venv/Lib/site-packages/win32com/demos/excelAddin.py +169 -0
  40. loan-advisor-agent/.venv/Lib/site-packages/win32com/demos/excelRTDServer.py +434 -0
  41. loan-advisor-agent/.venv/Lib/site-packages/win32com/demos/iebutton.py +214 -0
  42. loan-advisor-agent/.venv/Lib/site-packages/win32com/demos/ietoolbar.py +368 -0
  43. loan-advisor-agent/.venv/Lib/site-packages/win32com/demos/outlookAddin.py +135 -0
  44. loan-advisor-agent/.venv/Lib/site-packages/win32com/demos/trybag.py +78 -0
  45. loan-advisor-agent/.venv/Lib/site-packages/win32com/include/PythonCOM.h +746 -0
  46. loan-advisor-agent/.venv/Lib/site-packages/win32com/include/PythonCOMRegister.h +56 -0
  47. loan-advisor-agent/.venv/Lib/site-packages/win32com/include/PythonCOMServer.h +167 -0
  48. loan-advisor-agent/.venv/Lib/site-packages/win32com/libs/axscript.lib +0 -0
  49. loan-advisor-agent/.venv/Lib/site-packages/win32com/libs/pythoncom.lib +3 -0
  50. loan-advisor-agent/.venv/Lib/site-packages/win32com/makegw/__init__.py +1 -0
.gitattributes CHANGED
@@ -718,3 +718,4 @@ loan-advisor-agent/.venv/Lib/site-packages/win32/win32crypt.pyd filter=lfs diff=
718
  loan-advisor-agent/.venv/Lib/site-packages/win32/win32file.pyd filter=lfs diff=lfs merge=lfs -text
719
  loan-advisor-agent/.venv/Lib/site-packages/win32/win32gui.pyd filter=lfs diff=lfs merge=lfs -text
720
  loan-advisor-agent/.venv/Lib/site-packages/win32/win32security.pyd filter=lfs diff=lfs merge=lfs -text
 
 
718
  loan-advisor-agent/.venv/Lib/site-packages/win32/win32file.pyd filter=lfs diff=lfs merge=lfs -text
719
  loan-advisor-agent/.venv/Lib/site-packages/win32/win32gui.pyd filter=lfs diff=lfs merge=lfs -text
720
  loan-advisor-agent/.venv/Lib/site-packages/win32/win32security.pyd filter=lfs diff=lfs merge=lfs -text
721
+ loan-advisor-agent/.venv/Lib/site-packages/win32com/libs/pythoncom.lib filter=lfs diff=lfs merge=lfs -text
loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/COM_Records.html ADDED
@@ -0,0 +1,382 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <html>
2
+ <head>
3
+ <title>COM Record Support</title>
4
+ <meta name="viewport" content="width=device-width, initial-scale=1">
5
+ <meta charset="UTF-8">
6
+ <meta charset="utf-8" content="text/html"/>
7
+ <style>
8
+ @charset "utf-8";
9
+ /*!* GitHub Light v0.4.1 * Copyright(c) 2012 - 2017 GitHub,Inc. * Licensed under MIT(https://github.com/primer/github-syntax-theme-generator/blob/master/LICENSE) */
10
+ .gist{font-size:16px;color:#333;text-align:left;direction:ltr}
11
+ .gist .markdown-body{font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji;font-size:16px;line-height:1.5;word-wrap:break-word}
12
+ .gist .markdown-body kbd{display:inline-block;padding:3px 5px;font:11px SFMono-Regular,Consolas,Liberation Mono,Menlo,monospace;line-height:10px;color:#444d56;vertical-align:middle;background-color:#fafbfc;border:1px solid #d1d5da;border-radius:3px;box-shadow:inset 0 -1px 0 #d1d5da}
13
+ .gist .markdown-body:before{display:table;content:""}
14
+ .gist .markdown-body:after{display:table;clear:both;content:""}
15
+ .gist .markdown-body>:first-child{margin-top:0 !important}
16
+ .gist .markdown-body>:last-child{margin-bottom:0 !important}
17
+ .gist .markdown-body a:not([href]){color:inherit;text-decoration:none}
18
+ .gist .markdown-body .absent{color:#cb2431}
19
+ .gist .markdown-body .anchor{float:left;padding-right:4px;margin-left:-20px;line-height:1}
20
+ .gist .markdown-body .anchor:focus{outline:none}
21
+ .gist .markdown-body blockquote,.gist .markdown-body details,.gist .markdown-body dl,.gist .markdown-body ol,.gist .markdown-body p,.gist .markdown-body pre,.gist .markdown-body table,.gist .markdown-body ul{margin-top:0;margin-bottom:16px}
22
+ .gist .markdown-body hr{height:.25em;padding:0;margin:24px 0;background-color:#e1e4e8;border:0}
23
+ .gist .markdown-body blockquote{padding:0 1em;color:#6a737d;border-left:.25em solid #dfe2e5}
24
+ .gist .markdown-body blockquote>:first-child{margin-top:0}
25
+ .gist .markdown-body blockquote>:last-child{margin-bottom:0}
26
+ .gist .markdown-body h1,.gist .markdown-body h2,.gist .markdown-body h3,.gist .markdown-body h4,.gist .markdown-body h5,.gist .markdown-body h6{margin-top:24px;margin-bottom:16px;font-weight:600;line-height:1.25}
27
+ .gist .markdown-body h1 .octicon-link,.gist .markdown-body h2 .octicon-link,.gist .markdown-body h3 .octicon-link,.gist .markdown-body h4 .octicon-link,.gist .markdown-body h5 .octicon-link,.gist .markdown-body h6 .octicon-link{color:#1b1f23;vertical-align:middle;visibility:hidden}
28
+ .gist .markdown-body h1:hover .anchor,.gist .markdown-body h2:hover .anchor,.gist .markdown-body h3:hover .anchor,.gist .markdown-body h4:hover .anchor,.gist .markdown-body h5:hover .anchor,.gist .markdown-body h6:hover .anchor{text-decoration:none}
29
+ .gist .markdown-body h1:hover .anchor .octicon-link,.gist .markdown-body h2:hover .anchor .octicon-link,.gist .markdown-body h3:hover .anchor .octicon-link,.gist .markdown-body h4:hover .anchor .octicon-link,.gist .markdown-body h5:hover .anchor .octicon-link,.gist .markdown-body h6:hover .anchor .octicon-link{visibility:visible}
30
+ .gist .markdown-body h1 code,.gist .markdown-body h1 tt,.gist .markdown-body h2 code,.gist .markdown-body h2 tt,.gist .markdown-body h3 code,.gist .markdown-body h3 tt,.gist .markdown-body h4 code,.gist .markdown-body h4 tt,.gist .markdown-body h5 code,.gist .markdown-body h5 tt,.gist .markdown-body h6 code,.gist .markdown-body h6 tt{font-size:inherit}
31
+ .gist .markdown-body h1{font-size:2em}
32
+ .gist .markdown-body h1,.gist .markdown-body h2{padding-bottom:.3em;border-bottom:1px solid #eaecef}
33
+ .gist .markdown-body h2{font-size:1.5em}
34
+ .gist .markdown-body h3{font-size:1.25em}
35
+ .gist .markdown-body h4{font-size:1em}
36
+ .gist .markdown-body h5{font-size:.875em}
37
+ .gist .markdown-body h6{font-size:.85em;color:#6a737d}
38
+ .gist .markdown-body ol,.gist .markdown-body ul{padding-left:2em}
39
+ .gist .markdown-body ol.no-list,.gist .markdown-body ul.no-list{padding:0;list-style-type:none}
40
+ .gist .markdown-body ol ol,.gist .markdown-body ol ul,.gist .markdown-body ul ol,.gist .markdown-body ul ul{margin-top:0;margin-bottom:0}
41
+ .gist .markdown-body li{word-wrap:break-all}
42
+ .gist .markdown-body li>p{margin-top:16px}
43
+ .gist .markdown-body li+li{margin-top:.25em}
44
+ .gist .markdown-body dl{padding:0}
45
+ .gist .markdown-body dl dt{padding:0;margin-top:16px;font-size:1em;font-style:italic;font-weight:600}
46
+ .gist .markdown-body dl dd{padding:0 16px;margin-bottom:16px}
47
+ .gist .markdown-body table{display:block;width:100%;overflow:auto}
48
+ .gist .markdown-body table th{font-weight:600}
49
+ .gist .markdown-body table td,.gist .markdown-body table th{padding:6px 13px;border:1px solid #dfe2e5}
50
+ .gist .markdown-body table tr{background-color:#fff;border-top:1px solid #c6cbd1}
51
+ .gist .markdown-body table tr:nth-child(2n){background-color:#f6f8fa}
52
+ .gist .markdown-body table img{background-color:initial}
53
+ .gist .markdown-body img{max-width:100%;box-sizing:initial;background-color:#fff}
54
+ .gist .markdown-body img[align=right]{padding-left:20px}
55
+ .gist .markdown-body img[align=left]{padding-right:20px}
56
+ .gist .markdown-body .emoji{max-width:none;vertical-align:text-top;background-color:initial}
57
+ .gist .markdown-body span.frame{display:block;overflow:hidden}
58
+ .gist .markdown-body span.frame>span{display:block;float:left;width:auto;padding:7px;margin:13px 0 0;overflow:hidden;border:1px solid #dfe2e5}
59
+ .gist .markdown-body span.frame span img{display:block;float:left}
60
+ .gist .markdown-body span.frame span span{display:block;padding:5px 0 0;clear:both;color:#24292e}
61
+ .gist .markdown-body span.align-center{display:block;overflow:hidden;clear:both}
62
+ .gist .markdown-body span.align-center>span{display:block;margin:13px auto 0;overflow:hidden;text-align:center}
63
+ .gist .markdown-body span.align-center span img{margin:0 auto;text-align:center}
64
+ .gist .markdown-body span.align-right{display:block;overflow:hidden;clear:both}
65
+ .gist .markdown-body span.align-right>span{display:block;margin:13px 0 0;overflow:hidden;text-align:right}
66
+ .gist .markdown-body span.align-right span img{margin:0;text-align:right}
67
+ .gist .markdown-body span.float-left{display:block;float:left;margin-right:13px;overflow:hidden}
68
+ .gist .markdown-body span.float-left span{margin:13px 0 0}
69
+ .gist .markdown-body span.float-right{display:block;float:right;margin-left:13px;overflow:hidden}
70
+ .gist .markdown-body span.float-right>span{display:block;margin:13px auto 0;overflow:hidden;text-align:right}
71
+ .gist .markdown-body code,.gist .markdown-body tt{padding:.2em .4em;margin:0;font-size:85%;background-color:#f6f8fa;border-radius:3px}
72
+ .gist .markdown-body code br,.gist .markdown-body tt br{display:none}
73
+ .gist .markdown-body del code{text-decoration:inherit}
74
+ .gist .markdown-body pre{word-wrap:normal}
75
+ .gist .markdown-body pre>code{padding:0;margin:0;font-size:100%;word-break:normal;white-space:pre;background:transparent;border:0}
76
+ .gist .markdown-body .highlight{margin-bottom:16px}
77
+ .gist .markdown-body .highlight pre{margin-bottom:0;word-break:normal}
78
+ .gist .markdown-body .highlight pre,.gist .markdown-body pre{padding:16px;overflow:auto;font-size:85%;line-height:1.45;background-color:#f6f8fa;border-radius:3px}
79
+ .gist .markdown-body pre code,.gist .markdown-body pre tt{display:inline;max-width:auto;padding:0;margin:0;overflow:visible;line-height:inherit;word-wrap:normal;background-color:#f6f8fa;border:0}
80
+ .gist .markdown-body .csv-data td,.gist .markdown-body .csv-data th{padding:5px;overflow:hidden;font-size:12px;line-height:1;text-align:left;white-space:nowrap}
81
+ .gist .markdown-body .csv-data .blob-num{padding:10px 8px 9px;text-align:right;background:#fff;border:0}
82
+ .gist .markdown-body .csv-data tr{border-top:0}
83
+ .gist .markdown-body .csv-data th{font-weight:600;background:#f6f8fa;border-top:0}
84
+ .gist .pl-c{color:#6a737d}
85
+ .gist .pl-c1,.gist .pl-s .pl-v{color:#005cc5}
86
+ .gist .pl-e,.gist .pl-en{color:#6f42c1}
87
+ .gist .pl-s .pl-s1,.gist .pl-smi{color:#24292e}
88
+ .gist .pl-ent{color:#22863a}
89
+ .gist .pl-k{color:#d73a49}
90
+ .gist .pl-pds,.gist .pl-s,.gist .pl-s .pl-pse .pl-s1,.gist .pl-sr,.gist .pl-sr .pl-cce,.gist .pl-sr .pl-sra,.gist .pl-sr .pl-sre{color:#032f62}
91
+ .gist .pl-smw,.gist .pl-v{color:#e36209}
92
+ .gist .pl-bu{color:#b31d28}
93
+ .gist .pl-ii{color:#fafbfc;background-color:#b31d28}
94
+ .gist .pl-c2{color:#fafbfc;background-color:#d73a49}
95
+ .gist .pl-c2:before{content:"^M"}
96
+ .gist .pl-sr .pl-cce{font-weight:700;color:#22863a}
97
+ .gist .pl-ml{color:#735c0f}
98
+ .gist .pl-mh,.gist .pl-mh .pl-en,.gist .pl-ms{font-weight:700;color:#005cc5}
99
+ .gist .pl-mi{font-style:italic;color:#24292e}
100
+ .gist .pl-mb{font-weight:700;color:#24292e}
101
+ .gist .pl-md{color:#b31d28;background-color:#ffeef0}
102
+ .gist .pl-mi1{color:#22863a;background-color:#f0fff4}
103
+ .gist .pl-mc{color:#e36209;background-color:#ffebda}
104
+ .gist .pl-mi2{color:#f6f8fa;background-color:#005cc5}
105
+ .gist .pl-mdr{font-weight:700;color:#6f42c1}
106
+ .gist .pl-ba{color:#586069}
107
+ .gist .pl-sg{color:#959da5}
108
+ .gist .pl-corl{text-decoration:underline;color:#032f62}
109
+ .gist .breadcrumb{font-size:16px;color:#586069}
110
+ .gist .breadcrumb .separator{white-space:pre-wrap}
111
+ .gist .breadcrumb .separator:after,.gist .breadcrumb .separator:before{content:" "}
112
+ .gist .breadcrumb strong.final-path{color:#24292e}
113
+ .gist strong{font-weight:bolder}
114
+ .gist .editor-abort{display:inline;font-size:14px}
115
+ .gist .blob-interaction-bar{position:relative;background-color:#f2f2f2;border-bottom:1px solid #e5e5e5}
116
+ .gist .blob-interaction-bar:before{display:table;content:""}
117
+ .gist .blob-interaction-bar:after{display:table;clear:both;content:""}
118
+ .gist .blob-interaction-bar .octicon-search{position:absolute;top:10px;left:10px;font-size:12px;color:#586069}
119
+ .gist .blob-filter{width:100%;padding:4px 20px 5px 30px;font-size:12px;border:0;border-radius:0;outline:none}
120
+ .gist .blob-filter:focus{outline:none}
121
+ .gist .html-blob{margin-bottom:15px}
122
+ .gist .TagsearchPopover{width:inherit;max-width:600px}
123
+ .gist .TagsearchPopover-content{max-height:300px}
124
+ .gist .TagsearchPopover-list .TagsearchPopover-list-item:hover{background-color:#f6f8fa}
125
+ .gist .TagsearchPopover-list .TagsearchPopover-list-item .TagsearchPopover-item:hover{text-decoration:none}
126
+ .gist .TagsearchPopover-list .blob-code-inner{white-space:pre-wrap}
127
+ .gist .linejump .linejump-input{width:340px;background-color:#fafbfc}
128
+ .gist .linejump .btn,.gist .linejump .linejump-input{padding:10px 15px;font-size:16px}
129
+ .gist .CopyBlock{line-height:20px;cursor:pointer}
130
+ .gist .CopyBlock .octicon-clippy{display:none}
131
+ .gist .CopyBlock:active,.gist .CopyBlock:focus,.gist .CopyBlock:hover{background-color:#fff;outline:none}
132
+ .gist .CopyBlock:active .octicon-clippy,.gist .CopyBlock:focus .octicon-clippy,.gist .CopyBlock:hover .octicon-clippy{display:inline-block}
133
+ .gist .blob-wrapper{overflow-x:auto;overflow-y:hidden}
134
+ .gist .page-blob.height-full .blob-wrapper{overflow-y:auto}
135
+ .gist .page-edit-blob.height-full .CodeMirror{height:300px}
136
+ .gist .page-edit-blob.height-full .CodeMirror,.gist .page-edit-blob.height-full .CodeMirror-scroll{display:flex;flex-direction:column;flex:1 1 auto}
137
+ .gist .blob-wrapper-embedded{max-height:240px;overflow-y:auto}
138
+ .gist .diff-table{width:100%;border-collapse:initial}
139
+ .gist .diff-table .line-comments{padding:10px;vertical-align:top;border-top:1px solid #e1e4e8}
140
+ .gist .diff-table .line-comments:first-child+.empty-cell{border-left-width:1px}
141
+ .gist .diff-table tr:not(:last-child) .line-comments{border-top:1px solid #e1e4e8;border-bottom:1px solid #e1e4e8}
142
+ .gist .blob-num{width:1%;min-width:50px;padding-right:10px;padding-left:10px;font-family:SFMono-Regular,Consolas,Liberation Mono,Menlo,monospace;font-size:12px;line-height:20px;color:rgba(27,31,35,.3);text-align:right;white-space:nowrap;vertical-align:top;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}
143
+ .gist .blob-num:hover{color:rgba(27,31,35,.6)}
144
+ .gist .blob-num:before{content:attr(data-line-number)}
145
+ .gist .blob-num.non-expandable{cursor:default}
146
+ .gist .blob-num.non-expandable:hover{color:rgba(27,31,35,.3)}
147
+ .gist .blob-code{position:relative;padding-right:10px;padding-left:10px;line-height:20px;vertical-align:top}
148
+ .gist .blob-code-inner{overflow:visible;font-family:SFMono-Regular,Consolas,Liberation Mono,Menlo,monospace;font-size:12px;color:#24292e;word-wrap:normal;white-space:pre}
149
+ .gist .blob-code-inner .x-first{border-top-left-radius:.2em;border-bottom-left-radius:.2em}
150
+ .gist .blob-code-inner .x-last{border-top-right-radius:.2em;border-bottom-right-radius:.2em}
151
+ .gist .blob-code-inner.highlighted,.gist .blob-code-inner .highlighted{background-color:#fffbdd}
152
+ .gist .blob-code-marker:before{padding-right:8px;content:attr(data-code-marker)}
153
+ .gist .blob-code-marker-addition:before{content:"+ "}
154
+ .gist .blob-code-marker-deletion:before{content:"- "}
155
+ .gist .blob-code-marker-context:before{content:" "}
156
+ .gist .soft-wrap .diff-table{table-layout:fixed}
157
+ .gist .soft-wrap .blob-code{padding-left:18px;text-indent:-7px}
158
+ .gist .soft-wrap .blob-code-inner{word-wrap:break-word;white-space:pre-wrap}
159
+ .gist .soft-wrap .no-nl-marker{display:none}
160
+ .gist .soft-wrap .add-line-comment{margin-left:-28px}
161
+ .gist .blob-code-hunk,.gist .blob-num-expandable,.gist .blob-num-hunk{color:rgba(27,31,35,.7);vertical-align:middle}
162
+ .gist .blob-num-expandable,.gist .blob-num-hunk{background-color:#dbedff}
163
+ .gist .blob-code-hunk{padding-top:4px;padding-bottom:4px;background-color:#f1f8ff;border-width:1px 0}
164
+ .gist .blob-expanded .blob-code,.gist .blob-expanded .blob-num{background-color:#fafbfc}
165
+ .gist .blob-expanded+tr:not(.blob-expanded) .blob-code,.gist .blob-expanded+tr:not(.blob-expanded) .blob-num,.gist .blob-expanded .blob-num-hunk,.gist tr:not(.blob-expanded)+.blob-expanded .blob-code,.gist tr:not(.blob-expanded)+.blob-expanded .blob-num{border-top:1px solid #eaecef}
166
+ .gist .blob-num-expandable{padding:0;font-size:12px;text-align:center}
167
+ .gist .blob-num-expandable .diff-expander{display:block;width:auto;height:auto;padding:4px 11px 4px 10px;margin-right:-1px;color:#586069;cursor:pointer}
168
+ .gist .blob-num-expandable .diff-expander .octicon{vertical-align:top}
169
+ .gist .blob-num-expandable .directional-expander{display:block;width:auto;height:auto;margin-right:-1px;color:#586069;cursor:pointer}
170
+ .gist .blob-num-expandable .single-expander{padding-top:4px;padding-bottom:4px}
171
+ .gist .blob-num-expandable .diff-expander:hover,.gist .blob-num-expandable .directional-expander:hover{color:#fff;text-shadow:none;background-color:#0366d6;border-color:#0366d6}
172
+ .gist .blob-code-addition{background-color:#e6ffed}
173
+ .gist .blob-code-addition .x{color:#24292e;background-color:#acf2bd}
174
+ .gist .blob-num-addition{background-color:#cdffd8;border-color:#bef5cb}
175
+ .gist .blob-code-deletion{background-color:#ffeef0}
176
+ .gist .blob-code-deletion .x{color:#24292e;background-color:#fdb8c0}
177
+ .gist .blob-num-deletion{background-color:#ffdce0;border-color:#fdaeb7}
178
+ .gist .is-selecting,.gist .is-selecting .blob-num{cursor:ns-resize !important}
179
+ .gist .is-selecting .add-line-comment,.gist .is-selecting a{pointer-events:none;cursor:ns-resize !important}
180
+ .gist .is-selecting .is-hovered .add-line-comment{opacity:0}
181
+ .gist .is-selecting.file-diff-split,.gist .is-selecting.file-diff-split .blob-num{cursor:nwse-resize !important}
182
+ .gist .is-selecting.file-diff-split .add-line-comment,.gist .is-selecting.file-diff-split .empty-cell,.gist .is-selecting.file-diff-split a{pointer-events:none;cursor:nwse-resize !important}
183
+ .gist .selected-line{position:relative}
184
+ .gist .selected-line:after{position:absolute;top:0;left:0;display:block;width:100%;height:100%;box-sizing:border-box;pointer-events:none;content:"";background:rgba(255,223,93,.2);mix-blend-mode:multiply}
185
+ .gist .selected-line.selected-line-top:after{border-top:1px solid #ffd33d}
186
+ .gist .selected-line.selected-line-bottom:after{border-bottom:1px solid #ffd33d}
187
+ .gist .selected-line.selected-line-left:after,.gist .selected-line:first-child:after{border-left:1px solid #ffd33d}
188
+ .gist .selected-line.selected-line-right:after,.gist .selected-line:last-child:after{border-right:1px solid #ffd33d}
189
+ .gist .is-commenting .selected-line.blob-code:before{position:absolute;top:0;left:-1px;display:block;width:4px;height:100%;content:"";background:#0366d6}
190
+ .gist .add-line-comment{position:relative;z-index:5;float:left;width:22px;height:22px;margin:-2px -10px -2px -20px;line-height:21px;color:#fff;text-align:center;text-indent:0;cursor:pointer;background-color:#0366d6;background-image:linear-gradient(#0372ef,#0366d6);border-radius:3px;box-shadow:0 1px 4px rgba(27,31,35,.15);opacity:0;transition:transform .1s ease-in-out;transform:scale(.8)}
191
+ .gist .add-line-comment:hover{transform:scale(1)}
192
+ .gist .add-line-comment:focus,.is-hovered .gist .add-line-comment{opacity:1}
193
+ .gist .add-line-comment .octicon{vertical-align:text-top;pointer-events:none}
194
+ .gist .add-line-comment.octicon-check{background:#333;opacity:1}
195
+ .gist .inline-comment-form{border:1px solid #dfe2e5;border-radius:3px}
196
+ .gist .inline-review-comment{margin-top:0 !important;margin-bottom:10px !important}
197
+ .gist .inline-review-comment .gc:first-child+tr .blob-code,.gist .inline-review-comment .gc:first-child+tr .blob-num{padding-top:5px}
198
+ .gist .inline-review-comment tr:last-child{border-bottom-right-radius:3px;border-bottom-left-radius:3px}
199
+ .gist .inline-review-comment tr:last-child .blob-code,.gist .inline-review-comment tr:last-child .blob-num{padding-bottom:8px}
200
+ .gist .inline-review-comment tr:last-child .blob-code:first-child,.gist .inline-review-comment tr:last-child .blob-num:first-child{border-bottom-left-radius:3px}
201
+ .gist .inline-review-comment tr:last-child .blob-code:last-child,.gist .inline-review-comment tr:last-child .blob-num:last-child{border-bottom-right-radius:3px}
202
+ .gist .timeline-inline-comments{width:100%;table-layout:fixed}
203
+ .gist .show-inline-notes .inline-comments,.gist .timeline-inline-comments .inline-comments{display:table-row}
204
+ .gist .inline-comments,.gist .inline-comments.is-collapsed{display:none}
205
+ .gist .inline-comments .line-comments.is-collapsed{visibility:hidden}
206
+ .gist .inline-comments .line-comments+.blob-num{border-left-width:1px}
207
+ .gist .inline-comments .timeline-comment{margin-bottom:10px}
208
+ .gist .comment-holder,.gist .inline-comments .inline-comment-form,.gist .inline-comments .inline-comment-form-container{max-width:780px}
209
+ .gist .empty-cell+.line-comments,.gist .line-comments+.line-comments{border-left:1px solid #eaecef}
210
+ .gist .inline-comment-form-container .inline-comment-form,.gist .inline-comment-form-container.open .inline-comment-form-actions{display:none}
211
+ .gist .inline-comment-form-container .inline-comment-form-actions,.gist .inline-comment-form-container.open .inline-comment-form{display:block}
212
+ .gist body.full-width .container,.gist body.full-width .container-lg,.gist body.full-width .container-xl,.gist body.split-diff .container,.gist body.split-diff .container-lg,.gist body.split-diff .container-xl{width:100%;max-width:none;padding-right:20px;padding-left:20px}
213
+ .gist body.full-width .repository-content,.gist body.split-diff .repository-content{width:100%}
214
+ .gist body.full-width .new-pr-form,.gist body.split-diff .new-pr-form{max-width:980px}
215
+ .gist .file-diff-split{table-layout:fixed}
216
+ .gist .file-diff-split .blob-code+.blob-num{border-left:1px solid #f6f8fa}
217
+ .gist .file-diff-split .blob-code-inner{word-wrap:break-word;white-space:pre-wrap}
218
+ .gist .file-diff-split .empty-cell{cursor:default;background-color:#fafbfc;border-right-color:#eaecef}
219
+ @media (max-width:1280px){.gist .file-diff-split .write-selected .comment-form-head{margin-bottom:48px !important}
220
+ .gist .file-diff-split markdown-toolbar{position:absolute;right:8px;bottom:-40px}
221
+ }
222
+ .gist .submodule-diff-stats .octicon-diff-removed{color:#cb2431}
223
+ .gist .submodule-diff-stats .octicon-diff-renamed{color:#677a85}
224
+ .gist .submodule-diff-stats .octicon-diff-modified{color:#d0b44c}
225
+ .gist .submodule-diff-stats .octicon-diff-added{color:#28a745}
226
+ .gist .BlobToolbar{left:-17px}
227
+ .gist .BlobToolbar-dropdown{margin-left:-2px}
228
+ .gist .code-navigation-banner{background:linear-gradient(180deg,rgba(242,248,254,0),rgba(242,248,254,.47))}
229
+ .gist .code-navigation-banner .code-navigation-banner-illo{background-image:url(code-navigation-banner-illo.svg);background-repeat:no-repeat;background-position:50%}
230
+ .gist .pl-token.active,.gist .pl-token:hover{cursor:pointer;background:#ffea7f}
231
+ .gist .task-list-item{list-style-type:none}
232
+ .gist .task-list-item label{font-weight:400}
233
+ .gist .task-list-item.enabled label{cursor:pointer}
234
+ .gist .task-list-item+.task-list-item{margin-top:3px}
235
+ .gist .task-list-item .handle{display:none}
236
+ .gist .task-list-item-checkbox{margin:0 .2em .25em -1.6em;vertical-align:middle}
237
+ .gist .reorderable-task-lists .markdown-body .contains-task-list{padding:0}
238
+ .gist .reorderable-task-lists .markdown-body li:not(.task-list-item){margin-left:26px}
239
+ .gist .reorderable-task-lists .markdown-body ol:not(.contains-task-list) li,.gist .reorderable-task-lists .markdown-body ul:not(.contains-task-list) li{margin-left:0}
240
+ .gist .reorderable-task-lists .markdown-body li p{margin-top:0}
241
+ .gist .reorderable-task-lists .markdown-body .task-list-item{padding-right:15px;padding-left:42px;margin-right:-15px;margin-left:-15px;border:1px solid transparent}
242
+ .gist .reorderable-task-lists .markdown-body .task-list-item+.task-list-item{margin-top:0}
243
+ .gist .reorderable-task-lists .markdown-body .task-list-item .contains-task-list{padding-top:4px}
244
+ .gist .reorderable-task-lists .markdown-body .task-list-item .handle{display:block;float:left;width:20px;padding:2px 0 0 2px;margin-left:-43px;opacity:0}
245
+ .gist .reorderable-task-lists .markdown-body .task-list-item .drag-handle{fill:#333}
246
+ .gist .reorderable-task-lists .markdown-body .task-list-item.hovered>.handle{opacity:1}
247
+ .gist .reorderable-task-lists .markdown-body .task-list-item.is-dragging{opacity:0}
248
+ .gist .review-comment-contents .markdown-body .task-list-item{padding-left:42px;margin-right:-12px;margin-left:-12px;border-top-left-radius:3px;border-bottom-left-radius:3px}
249
+ .gist .review-comment-contents .markdown-body .task-list-item.hovered{border-left-color:#ededed}
250
+ .gist .highlight{padding:0;margin:0;font-family:SFMono-Regular,Consolas,Liberation Mono,Menlo,monospace;font-size:12px;font-weight:400;line-height:1.4;color:#333;background:#fff;border:0}
251
+ .gist .octospinner,.gist .render-viewer-error,.gist .render-viewer-fatal,.gist .render-viewer-invalid{display:none}
252
+ .gist iframe.render-viewer{width:100%;height:480px;overflow:hidden;border:0}
253
+ .gist code,.gist pre{font-family:SFMono-Regular,Consolas,Liberation Mono,Menlo,monospace !important}
254
+ .gist .gist-meta{padding:10px;overflow:hidden;font:12px -apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji;color:#586069;background-color:#f7f7f7;border-radius:0 0 3px 3px}
255
+ .gist .gist-meta a{font-weight:600;color:#666;text-decoration:none;border:0}
256
+ .gist .gist-data{overflow:auto;word-wrap:normal;background-color:#fff;border-bottom:1px solid #ddd;border-radius:3px 3px 0 0}
257
+ .gist .gist-file{margin-bottom:1em;font-family:SFMono-Regular,Consolas,Liberation Mono,Menlo,monospace;border:1px solid;border-color:#ddd #ddd #ccc;border-radius:3px}
258
+ .gist .gist-file article{padding:6px}
259
+ .gist .gist-file .scroll .gist-data{position:absolute;top:0;right:0;bottom:30px;left:0;overflow:scroll}
260
+ .gist .gist-file .scroll .gist-meta{position:absolute;right:0;bottom:0;left:0}
261
+ .gist .blob-num{min-width:inherit}
262
+ .gist .blob-code,.gist .blob-num{padding:1px 10px !important;background:transparent}
263
+ .gist .blob-code{text-align:left;border:0}
264
+ .gist .blob-wrapper table{border-collapse:collapse}
265
+ .gist table,.gist table tr,.gist table tr td,.gist table tr th{border-collapse:collapse}
266
+ .gist .blob-wrapper tr:first-child td{padding-top:4px}
267
+ .gist .markdown-body .anchor{display:none}
268
+ </style>
269
+ <style> .gist-file { max-width: 25cm; margin: 0 auto; } </style>
270
+ <style class="formula-style">
271
+ svg.gh-md-to-html-formula {fill: black;}
272
+ </style>
273
+ </head>
274
+ <body>
275
+ <main>
276
+ <div class="gist">
277
+ <div class="gist-file"> <!-- This is the class that is responsible for the boxing! -->
278
+ <div class="gist-data">
279
+ <div class="js-gist-file-update-container js-task-list-container file-box">
280
+ <div class="file" id="user-content-article-COM_Records">
281
+ <div class="Box-body readme blob js-code-block-container p-5 p-xl-6" id="user-content-file-docker-image-pull-md-readme" style="margin-left: 40px; margin-right: 40px; margin-top: 20px; margin-bottom: 20px">
282
+ <article class="markdown-body entry-content container-lg" itemprop="text">
283
+ <div class="markdown-heading"><h1 class="heading-element">COM Record support in pywin32</h1><a aria-label="Permalink: COM Record support in pywin32" class="anchor" href="#user-content-com-record-support-in-pywin32" id="user-content-com-record-support-in-pywin32" name="user-content-com-record-support-in-pywin32"><span aria-hidden="true" class="octicon octicon-link"></span></a></div>
284
+ <p>The pywin32 package provides COM Record support for late-bound and early-bound objects. In both cases it is required that the Type Library which defines the COM Record has been registered in Windows.</p>
285
+ <div class="markdown-heading"><h2 class="heading-element">Late-bound objects</h2><a aria-label="Permalink: Late-bound objects" class="anchor" href="#user-content-late-bound-objects" id="user-content-late-bound-objects" name="user-content-late-bound-objects"><span aria-hidden="true" class="octicon octicon-link"></span></a></div>
286
+ <p>For late-bound objects, were makepy-support is not available, it is possible to create a particular COM Record if the following is known:</p>
287
+ <ul>
288
+ <li>GUID of the Type Library were the Record is defined</li>
289
+ <li>Major version of the registered Type Library</li>
290
+ <li>Minor version of the registered Type Library</li>
291
+ <li>LCID of the registered Type Library</li>
292
+ <li>GUID of the COM Record in this Type Library</li>
293
+ </ul>
294
+ <p>An instance of the COM Record is created with <code>pythoncom.GetRecordFromGuids</code>, e.g.:</p>
295
+ <pre><code>import pythoncom
296
+
297
+ PyCOMTestLib_GUID = '{6bcdcb60-5605-11d0-ae5f-cadd4c000000}'
298
+ MAJVER = 1
299
+ MINVER = 1
300
+ LCID = 0
301
+ TestStruct1_GUID = '{7a4ce6a7-7959-4e85-a3c0-b41442ff0f67}'
302
+
303
+ record1 = pythoncom.GetRecordFromGuids(PyCOMTestLib_GUID, MAJVER, MINVER, LCID, TestStruct1_GUID)
304
+ </code></pre>
305
+ <p>The Python type of the returned COM Record instance is:</p>
306
+ <pre><code>&gt;&gt;&gt; type(record1)
307
+ &lt;class 'com_record'&gt;
308
+ </code></pre>
309
+ <p>which is a generic type that is returned for all COM Records, i.e. COM Records with different GUIDs nevertheless all have the same Python type <code>pythoncom.com_record</code>.</p>
310
+ <p>Instances of <code>&lt;class 'com_record'&gt;</code> can be used as method parameters and are returned by COM methods that return a COM Record. However, it is not possible to differentiate the COM Record Types, i.e. COM Records of different GUID at runtime.</p>
311
+ <div class="markdown-heading"><h2 class="heading-element">Early-bound objects</h2><a aria-label="Permalink: Early-bound objects" class="anchor" href="#user-content-early-bound-objects" id="user-content-early-bound-objects" name="user-content-early-bound-objects"><span aria-hidden="true" class="octicon octicon-link"></span></a></div>
312
+ <p>The availability of makepy-support does in its basic form offer the convenience function <code>win32com.client.Record</code> to create COM Record instances using the COM Record name from the Type Library and an interface object of the same Type Library:</p>
313
+ <pre><code>import win32com.client
314
+
315
+ com_test = win32com.client.Dispatch("PyCOMTest.PyCOMTest")
316
+
317
+ record1 = win32com.client.Record('TestStruct1' ,com_test)
318
+ </code></pre>
319
+ <p>Still the Python type of the returned COM Record instance is:</p>
320
+ <pre><code>&gt;&gt;&gt; type(record1)
321
+ &lt;class 'com_record'&gt;
322
+ </code></pre>
323
+ <p>i.e. the generic base type of all COM Records.</p>
324
+ <div class="markdown-heading"><h3 class="heading-element">Defining subclasses of <code>pythoncom.com_record</code>
325
+ </h3><a aria-label="Permalink: Defining subclasses of pythoncom.com_record" class="anchor" href="#user-content-defining-subclasses-of-pythoncomcom_record" id="user-content-defining-subclasses-of-pythoncomcom_record" name="user-content-defining-subclasses-of-pythoncomcom_record"><span aria-hidden="true" class="octicon octicon-link"></span></a></div>
326
+ <p>It is possible to create subclasses of the base <code>pythoncom.com_record</code> type and register such a subclass for a particular COM Record type. As a prerequisite, it is mandatory for the subclass to define the following class attributes:</p>
327
+ <ul>
328
+ <li>TLBID : The GUID of the containing TypeLibrary as a string</li>
329
+ <li>MJVER : The major version number of the TypeLibrary as an integer</li>
330
+ <li>MNVER : The minor version number of the TypeLibrary as an integer</li>
331
+ <li>LCID : The LCID of the TypeLibrary as an integer</li>
332
+ <li>GUID : The GUID of the COM Record as a string</li>
333
+ </ul>
334
+ <p>with GUID strings in {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} notation, e.g.:</p>
335
+ <pre><code>import pythoncom
336
+
337
+ class TestStruct1(pythoncom.com_record):
338
+ TLBID = '{6bcdcb60-5605-11d0-ae5f-cadd4c000000}'
339
+ MJVER = 1
340
+ MNVER = 1
341
+ LCID = 0
342
+ GUID = '{7a4ce6a7-7959-4e85-a3c0-b41442ff0f67}'
343
+ </code></pre>
344
+ <p>Before this subclass can be used to create <em>TestStruct1</em> instances, it has to be registered with <code>win32com.client.register_record_class</code>, e.g.:</p>
345
+ <pre><code>from win32com.client import register_record_class
346
+
347
+ register_record_class(TestStruct1)
348
+ </code></pre>
349
+ <p>With such a class, registered for a particular COM Record type, it is possible to identify the COM Record type at runtime:</p>
350
+ <pre><code>&gt;&gt;&gt; record1 = TestStruct1()
351
+
352
+ &gt;&gt;&gt; type(record1)
353
+ &lt;class 'main.TestStruct1'&gt;
354
+ </code></pre>
355
+ <p>Also COM methods that return a COM Record type for which a Python class was registered as described above, will return values of the proper Python class type, e.g.:</p>
356
+ <pre><code>&gt;&gt;&gt; # Given the following definition in the Type Library IDL-file:
357
+ &gt;&gt;&gt; # HRESULT GetStruct([out, retval]TestStruct1 *ret);
358
+
359
+ &gt;&gt;&gt; retval = GetStruct()
360
+
361
+ &gt;&gt;&gt; type(retval)
362
+ &lt;class 'main.TestStruct1'&gt;
363
+ </code></pre>
364
+ <p>COM methods that return a COM Record type for which no Python class was registered will continue to return values of the generic type <code>pythoncom.com_record</code>, e.g.:</p>
365
+ <pre><code>&gt;&gt;&gt; # Given the following definition in the Type Library IDL-file:
366
+ &gt;&gt;&gt; # HRESULT GetOtherStruct([out, retval]AnotherStruct *ret);
367
+
368
+ &gt;&gt;&gt; retval = GetOtherStruct()
369
+
370
+ &gt;&gt;&gt; type(retval)
371
+ &lt;class 'com_record'&gt;
372
+ </code></pre>
373
+ </article>
374
+ </div>
375
+ </div>
376
+ </div>
377
+ </div>
378
+ </div>
379
+ </div>
380
+ </main>
381
+ </body>
382
+ </html>
loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/GeneratedSupport.html ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <HTML>
2
+ <HEAD>
3
+ <META HTTP-EQUIV="Content-Type" CONTENT="text/html" charset="utf-8">
4
+ <META NAME="Generator" CONTENT="Microsoft Word 97">
5
+ <TITLE>Generated Python COM Support</TITLE>
6
+ <META NAME="Version" CONTENT="8.0.3410">
7
+ <META NAME="Date" CONTENT="10/11/96">
8
+ <META NAME="Template" CONTENT="D:\Program Files\Microsoft Office\Office\html.dot">
9
+ </HEAD>
10
+ <BODY TEXT="#000000" LINK="#0000ff" VLINK="#800080" BGCOLOR="#ffffff">
11
+
12
+ <P><IMG SRC="image/pycom_blowing.gif" WIDTH=549 HEIGHT=99 ALT="Python and COM - Blowing the others away"></P>
13
+ <H1>Generated Python COM Support</H1>
14
+ <P>This file describes how the Python COM extensions support "generated files". The information contained here is for expert Python users, and people who need to take advantage of the advanced features of the support. More general information is available in the <A HREF="QuickStartClientCom.html">Quick Start to Client Side COM</A> documentation.</P>
15
+ <H2>Introduction</H2>
16
+ <P>Generated Python COM support means that a .py file exists behind a particular COM object. This .py file is created by a generation process from a COM type library.</P>
17
+ <P>This documentation talks about the process of the creation of the .py files.</P>
18
+ <H2>Design Goals</H2>
19
+ <P>The main design goal is that the Python programmer need not know much about the type library they wish to work with. They need not know the name of a specific Python module to use a type library. COM uses an IID, version and LCID to identify a type library. Therefore, the Python programmer only need know this information to obtain a Python module.</P>
20
+ <H2>How to generate support files</H2>
21
+ <P>Support files can be generated either "off-line" by the makepy utility, or in custom Python code.</P>
22
+ <P>Using makepy is in many ways far simpler - you simply pick the type library and you are ready to go! The <A HREF="QuickStartClientCom.html">Quick Start to Client Side COM</A> documentation describes this process.</P>
23
+ <P>Often however, you will want to use code to ensure the type library has been processed. This document describes that process.</P>
24
+ <H2>Usage</H2>
25
+ <P>The win32com.client.gencache module implements all functionality. As described above, if you wish to generate support from code, you need to know the IID, version and LCID of the type library.</P>
26
+ <P>The following functions are defined. The best examples of their usage is probably in the Pythonwin OCX Demos, and the COM Test Suite (particularly testMSOffice.py)</P>
27
+ <P>Note that the gencache.py file supports being run from the command line, and provides some utilities for managing the cache. Run the file to see usage options.</P>
28
+ <H2>Using makepy to help with the runtime generation</H2>
29
+ <P>makepy supports a "-i" option, to print information about a type library. When you select a type library, makepy will print out 2 lines of code that you can't paste into your application. This will then allow your module to generate the makepy .py file at runtime, but will only take you a few seconds!</P>
30
+ <H2>win32com.client.gencache functions</H2>
31
+ <H3>def MakeModuleForTypelib(typelibCLSID, lcid, major, minor, progressInstance = None):</H3>
32
+ <P>Generate support for a type library.</P>
33
+ <P>Given the IID, LCID and version information for a type library, generate and import the necessary support files.</P>
34
+ <B><P>Returns</P>
35
+ </B><P>The Python module. No exceptions are caught.</P>
36
+ <B><P>Params</P>
37
+ </B><I><P>typelibCLSID</I><BR>
38
+ IID of the type library.</P>
39
+ <I><P>major</I><BR>
40
+ Integer major version.</P>
41
+ <I><P>minor</I><BR>
42
+ Integer minor version.</P>
43
+ <I><P>lcid</I><BR>
44
+ Integer LCID for the library.</P>
45
+ <I><P>progressInstance</I><BR>
46
+ A class instance to use as the progress indicator, or None to use the default GUI one.&nbsp;</P>
47
+ <H3>def EnsureModule(typelibCLSID, lcid, major, minor, progressInstance = None):</H3>
48
+ <P>Ensure Python support is loaded for a type library, generating if necessary.</P>
49
+ <P>Given the IID, LCID and version information for a type library, check and if necessary generate, then import the necessary support files.</P>
50
+ <P>Returns:</P>
51
+ <P>The Python module. No exceptions are caught during the generate process.</P>
52
+ <B><P>Params</P>
53
+ </B><I><P>typelibCLSID</I><BR>
54
+ IID of the type library.</P>
55
+ <I><P>major</I><BR>
56
+ Integer major version.</P>
57
+ <I><P>minor</I><BR>
58
+ Integer minor version.</P>
59
+ <I><P>lcid</I><BR>
60
+ Integer LCID for the library.</P>
61
+ <I><P>progressInstance</I><BR>
62
+ A class instance to use as the progress indicator, or None to use the default GUI one.&nbsp;</P>
63
+ <P>&nbsp;</P>
64
+ <H3>def GetClassForProgID(<I>progid</I>):</H3>
65
+ <P>Get a Python class for a Program ID</P>
66
+ <P>Given a Program ID, return a Python class which wraps the COM object</P>
67
+ <B><P>Returns</P>
68
+ </B><P>The Python class, or None if no module is available.</P>
69
+ <B><P>Params</P>
70
+ </B><I><P>progid<BR>
71
+ </I>A COM ProgramID or IID (eg, "Word.Application")</P>
72
+ <P>&nbsp;</P>
73
+ <H3>def GetModuleForProgID(progid):</H3>
74
+ <P>Get a Python module for a Program ID</P>
75
+ <P>Given a Program ID, return a Python module which contains the class which wraps the COM object.</P>
76
+ <B><P>Returns</P>
77
+ </B><P>The Python module, or None if no module is available.</P>
78
+ <B><P>Params:</P>
79
+ </B><I><P>progid <BR>
80
+ </I>A COM ProgramID or IID (eg, "Word.Application")</P>
81
+ <P>&nbsp;</P>
82
+ <H3>def GetModuleForCLSID(clsid):</H3>
83
+ <P>Get a Python module for a CLSID</P>
84
+ <P>Given a CLSID, return a Python module which contains the class which wraps the COM object.</P>
85
+ <B><P>Returns</P>
86
+ </B><P>The Python module, or None if no module is available.</P>
87
+ <B><P>Params</P>
88
+ </B><I><P>progid<BR>
89
+ </I>A COM CLSID (ie, not the description)</P>
90
+ <P>&nbsp;</P>
91
+ <H3>def GetModuleForTypelib(typelibCLSID, lcid, major, minor):</H3>
92
+ <P>Get a Python module for a type library ID</P>
93
+ <B><P>Returns</P>
94
+ </B><P>An imported Python module, else None</P>
95
+ <B><P>Params</B>:</P>
96
+ <I><P>typelibCLSID</I><BR>
97
+ IID of the type library.</P>
98
+ <I><P>major</I><BR>
99
+ Integer major version.</P>
100
+ <I><P>minor</I><BR>
101
+ Integer minor version</P>
102
+ <I><P>lcid</I><BR>
103
+ Integer LCID for the library.</P></BODY>
104
+ </HTML>
loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/PythonCOM.html ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <HTML>
2
+ <HEAD>
3
+ <META HTTP-EQUIV="Content-Type" CONTENT="text/html" charset="utf-8">
4
+ <META NAME="Generator" CONTENT="Microsoft Word 97">
5
+ <TITLE>Untitled</TITLE>
6
+ <META NAME="Template" CONTENT="D:\Program Files\Microsoft Office\Office\html.dot">
7
+ </HEAD>
8
+ <BODY LINK="#0000ff" VLINK="#800080">
9
+
10
+ <H1><IMG SRC="image/pycom_blowing.gif" WIDTH=549 HEIGHT=99 ALT="Python and COM - Blowing the others away"></H1>
11
+ <H1>Python and COM - Implementation Details </H1>
12
+ <H2>Introduction </H2>
13
+ <P>This document describes the technical implementation of the COM support in Python. It is primarily concerned with the underlying C++ interface to COM, although general Python issues are touched. </P>
14
+ <P>This document is targeted at people who wish to maintain/enhance the standard COM support (typically by writing extension modules). For information on using Python and COM from a Python programmers perspective, please see the <A HREF="docindex.html">documentation index</A>. </P>
15
+ <H2>General COM Support. </H2>
16
+ <P>COM support in Python can be broken into 2 general areas - C++ support, and Python support. C++ support exists in the core PythonCOM module (plus any PythonCOM extension modules). Python support exists in the .py files that accompany the core module. </P>
17
+ <H2>Naming Conventions </H2>
18
+ <P>The naming conventions used by Python code will be: </P>
19
+
20
+ <UL>
21
+ <LI>The Python "New Import" (ni) module will be used, allowing packages, or nested modules. </LI>
22
+ <LI>The package name will be "win32com". </LI>
23
+ <LI>The core module name will be "pythoncom" (ie, "win32com.pythoncom") </LI></UL>
24
+
25
+ <P>The rest of the naming conventions are yet to be worked out. </P>
26
+ <H2>Core COM support. </H2>
27
+ <P>This section is involved with the core C++ support in "pythoncom". </P>
28
+ <P>The organisation of PythonCOM support falls into 3 discrete areas. </P>
29
+ <H3>COM Client Support </H3>
30
+ <P>This is the ability to manipulate other COM objects via their exposed interface. This includes use of IDispatch (eg using Python to start Microsoft Word, open a file, and print it.) but also all client side IUnknown derived objects fall into this category, including ITypeLib and IConnectionPoint support. </P>
31
+ <H3>COM Server Support </H3>
32
+ <P>This is ability for Python to create COM Servers, which can be manipulated by another COM client. This includes server side IDispatch (eg, Visual Basic starting a Python interpreter, and asking it to evaluate some code) but also all supported server side IUnknown derived classes. </P>
33
+ <H3>Python/COM type and value conversion </H3>
34
+ <P>This is internal code used by the above areas to managed the conversion to and from Python/COM types and values. This includes code to convert an arbitrary Python object into a COM variant, manages return types, and a few other helpers. </P>
35
+ <H2>COM Structures and Python Types </H2>
36
+ <P>OLE supports many C level structures for the COM API, which must be mapped to Python. </P>
37
+ <H3>VARIANT </H3>
38
+ <P>Variants are never exposed as such to Python programs. The internal framework always converts all variants to and from Python types. In some cases, type descriptions may be used, which force specific mappings, although in general the automatic conversion works fine. </P>
39
+ <H3>TYPEDESC </H3>
40
+ <P>A tuple, containing the elements of the C union. This union will be correctly decoded by the support code. </P>
41
+ <H3>ELEMDESC </H3>
42
+ <P>A tuple of TYPEDESC and PARAMDESC objects. </P>
43
+ <H3>FUNCDESC </H3>
44
+ <P>A funcdesc is a large and unwieldy tuple. Documentation to be supplied. </P>
45
+ <H3>IID/CLSID </H3>
46
+ <P>A native IID in Python is a special type, defined in pythoncom. Whenever a CLSID/IID is required, typically either an object, a tuple of type "iii(iiiiiiii)" or string can be used. </P>
47
+ <P>Helper functions are available to convert to and from IID/CLSID and strings. </P>
48
+ <H2>COM Framework </H2>
49
+ <P>Both client and server side support have a specific framework in place to assist in supporting the widest possible set of interfaces. The framework allows external extension DLLs to be written, which extend the interfaces available to the Python user. </P>
50
+ <P>This allows the core PythonCOM module to support a wide set of common interfaces, and other extensions to support anything obscure. </P>
51
+ <H3>Client Framework </H3>
52
+ <H4>QueryInterface and Types </H4>
53
+ <P>When the only support required by Python is IDispatch, everything is simple - every object returned from QueryInterface is a PyIDispatch object. But this does not extend to other types, such as ITypeLib, IConnectionPoint etc., which are required for full COM support. </P>
54
+ <P>For example, consider the following C++ psuedo-code: </P>
55
+ <CODE><P>IConnectionPoint *conPt;<BR>
56
+ someIDispatch-&gt;QueryInterface(IID_IConnectionPoint, (void **)&amp;conPt);<BR>
57
+ // Note the IID_ and type of the * could be anything!</CODE> </P>
58
+ <P>This cast, and knowledge of a specific IID_* to type must be simulated in Python. </P>
59
+ <P>Python/COM will therefore maintain a map of UID's to Python type objects. Whenever QueryInterface is called, Python will lookup this map, to determine if the object type is supported. If the object is supported, then an object of that type will be returned. If the object is not supported, then a PyIUnknown object will be returned. </P>
60
+ <P>Note that PyIDispatch will be supported by the core engine. Therefore: </P>
61
+ <CODE><P>&gt;&gt;&gt; disp=someobj.QueryInterface(win32com.IID_Dispatch) </P>
62
+ </CODE><P>will return a PyIDispatch object, whereas </P>
63
+ <CODE><P>&gt;&gt;&gt; unk=someobj.QueryInterface(SomeUnknownIID) # returns PyIUnknown<BR>
64
+ &gt;&gt;&gt; disp=unk.QueryInterface(win32com.IID_Dispatch) <BR>
65
+ &gt;&gt;&gt; unk.Release() # Clean up now, rather than waiting for unk death.</CODE> </P>
66
+ <P>Is needed to convert to an IDispatch object. </P>
67
+ <H4>Core Support </H4>
68
+ <P>The core COM support module will support the IUnknown, IDispatch, ITypeInfo, ITypeLib and IConnectionPointContainer and IConnectionPoint interfaces. This implies the core COM module supports 6 different OLE client object types, mapped to the 6 IID_*'s representing the objects. (The IConnection* objects allow for Python to repsond to COM events) </P>
69
+ <P>A psuedo-inheritance scheme is used. The Python types are all derived from the Python IUnknown type (PyIUnknown). Therefore all IUnknown methods are automatically available to all types, just as it should be. The PyIUnknown type manages all object reference counts and destruction. </P>
70
+ <H4>Extensibility </H4>
71
+ <P>To provide the above functionality, a Python map is provided, which maps from a GUID to a Python type object. </P>
72
+ <P>The advantage of this scheme is an external extension modules can hook into the core support. For example, imagine the following code: </P>
73
+ <CODE><P>&gt;&gt;&gt; import myextracom # external .pyd supporting some interface.<BR>
74
+ # myextracom.pyd will do the equivilent of</CODE> </P>
75
+ <CODE><P># pythoncom.mapSupportedTypes(myextracom.IID_Extra, myextracom.ExtraType) <BR>
76
+ &gt;&gt;&gt; someobj.QueryInterface(myextracom.IID_Extra)</CODE> </P>
77
+ <P>Would correctly return an object defined in the extension module. </P>
78
+ <H3>Server Framework </H3>
79
+ <H4>General Framework </H4>
80
+ <P>A server framework has been put in place which provides the following features: </P>
81
+ <P>All Interfaces provide VTBL support - this means that the Servers exposed by Python are callable from C++ and other compiled languages. </P>
82
+ <P>Supports full "inproc" servers. This means that no external .EXE is needed making Python COM servers available in almost all cases. </P>
83
+ <P>An extensible model which allows for extension modules to provide server support for interfaces defined in that module. A map is provided which maps from a GUID to a function pointer which creates the interface. </P>
84
+ <H3>Python and Variant Types Conversion </H3>
85
+ <P>In general, Python and COM are both "type-less". COM is type-less via the VARIANT object, which supports many types, and Python is type-less due to its object model. </P>
86
+ <P>There are a number of areas where Python and OLE clash. </P>
87
+ <H4>Parameters and conversions. </H4>
88
+ <P>For simple calls, there are 2 helpers available which will convert to and from PyObjects and VARIANTS. The call to convert a Python object to a VARIANT is simple in that it returns a VARIANT of the most appropriate type for the Python object - ie, the type of the Python object determines the resulting VARIANT type. </P>
89
+ <P>There are also more complex conversion routines available, wrapped in a C++ helper class. Typically, these helpers are used whenever a specific variant type is known (eg, when an ITypeInfo is available for the object being used). In this case, all efforts are made to convert the Python type to the requested variant type - ie, in this situation, the VARIANT type determines how the Python object is coerced. In addition, this code supports the use of "ByRef" and pointer paramaters, providing and freeing any buffers necessary for the call. </P></BODY>
90
+ </HTML>
loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/QuickStartClientCom.html ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <HTML>
2
+ <HEAD>
3
+ <META HTTP-EQUIV="Content-Type" CONTENT="text/html" charset="utf-8">
4
+ <META NAME="Generator" CONTENT="Microsoft Word 97">
5
+ <TITLE>Quick Start to Client side COM and Python</TITLE>
6
+ <META NAME="Template" CONTENT="D:\Program Files\Microsoft Office\Office\html.dot">
7
+ </HEAD>
8
+ <BODY LINK="#0000ff" VLINK="#800080">
9
+
10
+ <H1>Quick Start to Client side COM and Python</H1>
11
+ <H2>Introduction</H2>
12
+ <P>This documents how to quickly start using COM from Python. It is not a thorough discussion of the COM system, or of the concepts introduced by COM.</P>
13
+ <P>Other good information on COM can be found in various conference tutorials - please see <A HREF="https://web.archive.org/web/20130420121155/http://starship.python.net/crew/mhammond/conferences/">the collection of Mark's conference tutorials</A></P>
14
+ <P>For information on implementing COM objects using Python, please see <A HREF="QuickStartServerCom.html">a Quick Start to Server side COM and Python</A></P>
15
+ <P>In this document we discuss the following topics:</P>
16
+
17
+ <UL>
18
+ <LI><A HREF="#Using">Using a COM object from Python</A> </LI>
19
+ <LI><A HREF="#WhatObjects">How do I know which objects are available?</A> </LI>
20
+ <LI><A HREF="#StaticDispatch">Static Dispatch/Type Safe objects (using the new improved makepy.py)</A></LI>
21
+ <LI><A HREF="#UsingComConstants">Using COM Constants with makepy.</A></LI></UL>
22
+
23
+ <H2>Quick Start</H2>
24
+ <H3><A NAME="Using">To use a COM object from Python</A></H3>
25
+ <CODE><P>import win32com.client<BR>
26
+ o = win32com.client.Dispatch("Object.Name")<BR>
27
+ o.Method()<BR>
28
+ o.property = "New Value"<BR>
29
+ print(o.property)</P>
30
+ </CODE><P>Example</P>
31
+ <CODE><P>o = win32com.client.Dispatch("Excel.Application")<BR>
32
+ o.Visible = 1<BR>
33
+ o.Workbooks.Add()<BR>
34
+ o.Cells(1,1).Value = "Hello"</CODE> </P>
35
+ <P>And we will see the word "Hello" appear in the top cell. </P>
36
+ <H3><A NAME="WhatObjects">How do I know which methods and properties are available?</A></H3>
37
+ <P>Good question. This is hard! You need to use the documentation with the products, or possibly a COM browser. Note however that COM browsers typically rely on these objects registering themselves in certain ways, and many objects to not do this. You are just expected to know.</P>
38
+ <H4>The Python COM browser</H4>
39
+ <P>PythonCOM comes with a basic COM browser that may show you the information you need. Note that this package requires Pythonwin (ie, the MFC GUI environment) to be installed for this to work.</P>
40
+ <P>There are far better COM browsers available - I tend to use the one that comes with MSVC, or this one!</P>
41
+ <P>To run the browser, simply select it from the Pythonwin <I>Tools</I> menu, or double-click on the file <I>win32com\client\combrowse.py</I></P>
42
+ <H2><A NAME="StaticDispatch">Static Dispatch (or Type Safe) objects</A></H2>
43
+ <P>In the above examples, if we printed the '<CODE>repr(o)</CODE>' object above, it would have resulted in</P>
44
+ <CODE><P>&lt;COMObject Excel.Application&gt;</P>
45
+ </CODE><P>This reflects that the object is a generic COM object that Python has no special knowledge of (other than the name you used to create it!). This is known as a "dynamic dispatch" object, as all knowledge is built dynamically. The win32com package also has the concept of <I>static dispatch</I> objects, which gives Python up-front knowledge about the objects that it is working with (including arguments, argument types, etc)</P>
46
+ <P>In a nutshell, Static Dispatch involves the generation of a .py file that contains support for the specific object. For more overview information, please see the documentation references above.</P>
47
+ <P>The generation and management of the .py files is somewhat automatic, and involves one of 2 steps:</P>
48
+
49
+ <UL>
50
+ <LI>Using <I>makepy.py</I> to select a COM library. This process is very similar to Visual Basic, where you select from a list of all objects installed on your system, and once selected the objects are magically useable. </LI></UL>
51
+
52
+ <P>or</P>
53
+
54
+ <UL>
55
+ <LI>Use explicit code to check for, and possibly generate, support at run-time. This is very powerful, as it allows the developer to avoid ensuring the user has selected the appropriate type library. This option is extremely powerful for OCX users, as it allows Python code to sub-class an OCX control, but the actual sub-class can be generated at run-time. Use <I>makepy.py</I> with a </I>-i</I> option to see how to include this support in your Python code.</LI></UL>
56
+
57
+ <P>The <I>win32com.client.gencache</I> module manages these generated files. This module has <A HREF="GeneratedSupport.html">some documentation of its own</A>, but you probably don't need to know the gory details!</P>
58
+ <H3>How do I get at the generated module?</H3>
59
+ <P>You will notice that the generated file name is long and cryptic - obviously not designed for humans to work with! So how do you get at the module object for the generated code?</P>
60
+ <P>Hopefully, the answer is <I>you shouldn't need to</I>. All generated file support is generally available directly via <I>win32com.client.Dispatch</I> and <I>win32com.client.constants</I>. But should you ever really need the Python module object, the win32com.client.gencache module has functions specifically for this. The functions GetModuleForCLSID and GetModuleForProgID both return Python module objects that you can use in your code. See the docstrings in the gencache code for more details.</P>
61
+ <H3>To generate Python Sources supporting a COM object</H3>
62
+ <H4>Example using Microsoft Office 97.</H4>
63
+ <P>Either:</P>
64
+
65
+ <UL>
66
+ <LI>Run '<CODE>win32com\client\makepy.py</CODE>' (eg, run it from the command window, or double-click on it) and a list will be presented. Select the Type Library '<CODE>Microsoft Word 8.0 Object Library</CODE>' </LI>
67
+ <LI>From a command prompt, run the command '<CODE>makepy.py "Microsoft Word 8.0 Object Library"</CODE>' (include the double quotes). This simply avoids the selection process. </LI>
68
+ <LI>If you desire, you can also use explicit code to generate it just before you need to use it at runtime. Run <CODE>'makepy.py -i "Microsoft Word 8.0 Object Library"</CODE>' (include the double quotes) to see how to do this.</LI></UL>
69
+
70
+ <P>And that is it! Nothing more needed. No special import statements needed! Now, you simply need say</P>
71
+ <CODE><P>&gt;&gt;&gt; import win32com.client</P>
72
+ <P>&gt;&gt;&gt; w=win32com.client.Dispatch("Word.Application")</P>
73
+ <P>&gt;&gt;&gt; w.Visible=1</P>
74
+ <P>&gt;&gt;&gt; w</P>
75
+ <P>&lt;win32com.gen_py.Microsoft Word 8.0 Object Library._Application&gt;</P>
76
+ </CODE><P>Note that now Python knows the explicit type of the object.</P>
77
+ <H3><A NAME="UsingComConstants">Using COM Constants</A></H3>
78
+ <P>Makepy automatically installs all generated constants from a type library in an object called <I>win32com.clients.constants</I>. You do not need to do anything special to make these constants work, other than create the object itself (ie, in the example above, the constants relating to <I>Word</I> would automatically be available after the <CODE>w=win32com.client.Dispatch("Word.Application</CODE>") statement<CODE>.</P>
79
+ </CODE><P>For example, immediately after executing the code above, you could execute the following:</P>
80
+ <CODE><P>&gt;&gt;&gt; w.WindowState = win32com.client.constants.wdWindowStateMinimize</P>
81
+ </CODE><P>and Word will Minimize.</P></BODY>
82
+ </HTML>
loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/QuickStartServerCom.html ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <HTML>
2
+ <HEAD>
3
+ <META HTTP-EQUIV="Content-Type" CONTENT="text/html" charset="utf-8">
4
+ <META NAME="Generator" CONTENT="Microsoft Word 97">
5
+ <TITLE>Quick Start to Server Side COM and Python</TITLE>
6
+ <META NAME="Version" CONTENT="8.0.3410">
7
+ <META NAME="Date" CONTENT="10/11/96">
8
+ <META NAME="Template" CONTENT="D:\Program Files\Microsoft Office\Office\html.dot">
9
+ </HEAD>
10
+ <BODY TEXT="#000000" LINK="#0000ff" VLINK="#800080" BGCOLOR="#ffffff">
11
+
12
+ <H1>Quick Start to Server side COM and Python</H1>
13
+ <H2>Introduction</H2>
14
+ <P>This documents how to quickly start implementing COM objects in Python. It is not a thorough discussion of the COM system, or of the concepts introduced by COM.</P>
15
+ <P>For more details information on Python and COM, please see the COM Tutorial given by Greg Stein and Mark Hammond at SPAM 6 <A HREF="https://web.archive.org/web/20001117033400/http://www.python.org:80/windows/win32com/COMTutorial/index.htm">(in HTML format, lost to time)</A> or download the same tutorial <A HREF="https://web.archive.org/web/20060511064916/http://www.python.org/windows/win32com/COMTutorial.ppt">in PowerPoint format.</A></P>
16
+ <P>For information on using external COM objects from Python, please see <A HREF="QuickStartClientCom.html">a Quick Start to Client side COM and Python</A>.</P>
17
+ <P>In this document we discuss the <A HREF="#core">core functionality</A>, <A HREF="#Registering">registering the server</A>, <A HREF="#testing">testing the class</A>, <A HREF="#debugging">debugging the class</A>, <A HREF="#Exception">exception handling</A> and <A HREF="#Policies">server policies</A> (phew!)</P>
18
+ <H2><A NAME="core">Implement the core functionality</A></H2>
19
+ <H3><A NAME="Using">Implement a stand-alone Python class with your functionality</A></H3>
20
+ <CODE><P>class HelloWorld:</P><DIR>
21
+ <DIR>
22
+
23
+ <P>def __init__(self):</P><DIR>
24
+ <DIR>
25
+
26
+ <P>self.softspace = 1</P>
27
+ <P>self.noCalls = 0</P></DIR>
28
+ </DIR>
29
+
30
+ <P>def Hello(self, who):</P><DIR>
31
+ <DIR>
32
+
33
+ <P>self.noCalls = self.noCalls + 1</P>
34
+ <P># insert "softspace" number of spaces</P>
35
+ <P>return "Hello" + " " * self.softspace + who</P></DIR>
36
+ </DIR>
37
+ </DIR>
38
+ </DIR>
39
+
40
+ </CODE><P>This is obviously a very simple server. In particular, custom error handling would be needed for a production class server. In addition, there are some contrived properties just for demonstration purposes.</P>
41
+ <H3>Make Unicode concessions</H3>
42
+ <P>At this stage, Python and Unicode don't really work well together. All strings which come from COM will actually be Unicode objects rather than string objects.</P>
43
+ <P>To make this code work in a COM environment, the last line of the "Hello" method must become:</P><DIR>
44
+ <DIR>
45
+ <DIR>
46
+ <DIR>
47
+
48
+ <CODE><P>return "Hello" + " " * self.softspace + str(who)</P></DIR>
49
+ </DIR>
50
+ </DIR>
51
+ </DIR>
52
+
53
+ </CODE><P>Note the conversion of the "who" to "str(who)". This forces the Unicode object into a native Python string object.</P>
54
+ <P>For details on how to debug COM Servers to find this sort of error, please see <A HREF="#debugging">debugging the class</A></P>
55
+ <H3>Annotate the class with win32com specific attributes</H3>
56
+ <P>This is not a complete list of names, simply a list of properties used by this sample.</P>
57
+ <TABLE CELLSPACING=0 BORDER=0 CELLPADDING=7 WIDTH=637>
58
+ <TR><TD WIDTH="34%" VALIGN="TOP">
59
+ <P><B>Property Name</B></TD>
60
+ <TD WIDTH="66%" VALIGN="TOP">
61
+ <B><P>Description</B></TD>
62
+ </TR>
63
+ <TR><TD WIDTH="34%" VALIGN="TOP">
64
+ <P>_public_methods_</TD>
65
+ <TD WIDTH="66%" VALIGN="TOP">
66
+ <P>List of all method names exposed to remote COM clients</TD>
67
+ </TR>
68
+ <TR><TD WIDTH="34%" VALIGN="TOP">
69
+ <P>_public_attrs_</TD>
70
+ <TD WIDTH="66%" VALIGN="TOP">
71
+ <P>List of all attribute names exposed to remote COM clients</TD>
72
+ </TR>
73
+ <TR><TD WIDTH="34%" VALIGN="TOP" HEIGHT=5>
74
+ <P>_readonly_attrs_</TD>
75
+ <TD WIDTH="66%" VALIGN="TOP" HEIGHT=5>
76
+ <P>List of all attributes which can be accessed, but not set.</TD>
77
+ </TR>
78
+ </TABLE>
79
+
80
+ <P>We change the class header to become:</P>
81
+ <CODE><P>class HelloWorld:</P><DIR>
82
+ <DIR>
83
+
84
+ <P>_public_methods_ = ['Hello']</P>
85
+ <P>_public_attrs_ = ['softspace', 'noCalls']</P>
86
+ <P>_readonly_attrs_ = ['noCalls']</P>
87
+ <P>def __init__(self):</P>
88
+ <P>[Same from here...]</P></DIR>
89
+ </DIR>
90
+
91
+ </CODE><H3><A NAME="Registering">Registering and assigning a CLSID for the object</A></H3>
92
+ <P>COM requires that all objects use a unique CLSID and be registered under a "user friendly" name. This documents the process.</P>
93
+ <H4>Generating the CLSID</H4>
94
+ <P>Microsoft Visual C++ comes with various tools for generating CLSID's, which are quite suitable. Alternatively, the pythoncom module exports the function CreateGuid() to generate these identifiers.</P>
95
+ <CODE><P>&gt;&gt;&gt; import pythoncom<BR>
96
+ &gt;&gt;&gt; print(pythoncom.CreateGuid())<BR>
97
+ {7CC9F362-486D-11D1-BB48-0000E838A65F}</P>
98
+ </CODE><P>Obviously the GUID that you get will be different than that displayed here.</P>
99
+ <H4>Preparing for registration of the Class</H4>
100
+ <P>The win32com package allows yet more annotations to be applied to a class, allowing registration to be effected with 2 lines in your source file. The registration annotations used by this sample are:</P>
101
+ <TABLE CELLSPACING=0 BORDER=0 CELLPADDING=7 WIDTH=636>
102
+ <TR><TD WIDTH="34%" VALIGN="TOP">
103
+ <P><B>Property Name</B></TD>
104
+ <TD WIDTH="66%" VALIGN="TOP">
105
+ <B><P>Description</B></TD>
106
+ </TR>
107
+ <TR><TD WIDTH="34%" VALIGN="TOP">
108
+ <P>_reg_clsid_</TD>
109
+ <TD WIDTH="66%" VALIGN="TOP">
110
+ <P>The CLSID of the COM object</TD>
111
+ </TR>
112
+ <TR><TD WIDTH="34%" VALIGN="TOP">
113
+ <P>_reg_progid_</TD>
114
+ <TD WIDTH="66%" VALIGN="TOP">
115
+ <P>The "program ID", or Name, of the COM Server. This is the name the user usually uses to instantiate the object</TD>
116
+ </TR>
117
+ <TR><TD WIDTH="34%" VALIGN="TOP" HEIGHT=5>
118
+ <P>_reg_desc_</TD>
119
+ <TD WIDTH="66%" VALIGN="TOP" HEIGHT=5>
120
+ <P>Optional: The description of the COM Server. Used primarily for COM browsers. If not specified, the _reg_progid_ is used as the description.</TD>
121
+ </TR>
122
+ <TR><TD WIDTH="34%" VALIGN="TOP" HEIGHT=5>
123
+ <P>_reg_class_spec_</TD>
124
+ <TD WIDTH="66%" VALIGN="TOP" HEIGHT=5>
125
+ <P>Optional: A string which represents how Python can create the class instance. The string is of format<BR>
126
+ [package.subpackage.]module.class</P>
127
+ <P>The portion up to the class name must be valid for Python to "import", and the class portion must be a valid attribute in the specified class.</P>
128
+ <P>This is optional from build 124 of Pythoncom., and has been removed from this sample.</TD>
129
+ </TR>
130
+ <TR><TD WIDTH="34%" VALIGN="TOP" HEIGHT=5>
131
+ <P>_reg_remove_keys_</TD>
132
+ <TD WIDTH="66%" VALIGN="TOP" HEIGHT=5>
133
+ <P>Optional: A list of tuples of extra registry keys to be removed when uninstalling the server. Each tuple is of format ("key", root), where key is a string, and root is one of the win32con.HKEY_* constants (this item is optional, defaulting to HKEY_CLASSES_ROOT)</TD>
134
+ </TR>
135
+ </TABLE>
136
+
137
+ <P>Note there are quite a few other keys available. Also note that these annotations are <I>not</I> required - they just make registration simple. Helper functions in the module <CODE>win32com.server.register</CODE> allow you to explicitly specify each of these attributes without attaching them to the class.</P>
138
+ <P>The header of our class now becomes:</P>
139
+ <CODE><P>class HelloWorld:</P><DIR>
140
+ <DIR>
141
+
142
+ <P>_reg_clsid_ = "{7CC9F362-486D-11D1-BB48-0000E838A65F}"</P>
143
+ <P>_reg_desc_ = "Python Test COM Server"</P>
144
+ <P>_reg_progid_ = "Python.TestServer"</P>
145
+ <P>_public_methods_ = ['Hello']</P>
146
+ <P>[same from here]</P></DIR>
147
+ </DIR>
148
+
149
+ </CODE><H4>Registering the Class</H4>
150
+ <P>The idiom that most Python COM Servers use is that they register themselves when run as a script (ie, when executed from the command line.) Thus the standard "<CODE>if __name__=='__main___':</CODE>" technique works well.</P>
151
+ <P>win32com.server.register contains a number of helper functions. The easiest to use is "<CODE>UseCommandLine</CODE>".</P>
152
+ <P>Registration becomes as simple as:</P>
153
+ <CODE><P>if __name__=='__main__':<BR>
154
+ &#9;# ni only for 1.4!<BR>
155
+ &#9;import ni, win32com.server.register <BR>
156
+ &#9;win32com.server.register.UseCommandLine(HelloWorld)</P>
157
+ </CODE><P>Running the script will register our test server.</P>
158
+ <H2><A NAME="testing">Testing our Class</A></H2>
159
+ <P>For the purposes of this demonstration, we will test the class using Visual Basic. This code should run under any version of Visual Basic, including VBA found in Microsoft Office. Any COM compliant package could be used alternatively. VB has been used just to prove there is no "smoke and mirrors. For information on how to test the server using Python, please see the <A HREF="QuickStartClientCom.html">Quick Start to Client side COM</A> documentation.</P>
160
+ <P>This is not a tutorial in VB. The code is just presented! Run it, and it will work!</P>
161
+ <H2><A NAME="debugging">Debugging the COM Server</A></H2>
162
+ <P>When things go wrong in COM Servers, there is often nowhere useful for the Python traceback to go, even if such a traceback is generated.</P>
163
+ <P>Rather than discuss how it works, I will just present the procedure to debug your server:</P>
164
+ <B><P>To register a debug version of your class</B>, run the script (as above) but pass in a "<CODE>--debug</CODE>" parameter. Eg, for the server above, use the command line "<CODE>testcomserver.py --debug</CODE>".</P>
165
+ <B><P>To see the debug output generated</B> (and any print statements you may choose to add!) you can simply select the "Remote Debug Trace Collector" from the Pythonwin Tools menu, or run the script "win32traceutil.py" from Windows Explorer or a Command Prompt.</P>
166
+ <H2><A NAME="Exception">Exception Handling </A></H2>
167
+ <P>Servers need to be able to provide exception information to their client. In some cases, it may be a simple return code (such as E_NOTIMPLEMENTED), but often it can contain much richer information, describing the error on detail, and even a help file and topic where more information can be found. </P>
168
+ <P>We use Python class based exceptions to provide this information. The COM framework will examine the exception, and look for certain known attributes. These attributes will be copied across to the COM exception, and passed back to the client. </P>
169
+ <P>The following attributes are supported, and correspond to the equivalent entry in the COM Exception structure:<BR>
170
+ <CODE>scode, code, description, source, helpfile and helpcontext</P>
171
+ </CODE><P>To make working with exceptions easier, there is a helper module "win32com.server.exception.py", which defines a single class. An example of its usage would be: </P>
172
+ <CODE><P>raise COMException(desc="Must be a string",scode=winerror.E_INVALIDARG,helpfile="myhelp.hlp",...)</CODE> </P>
173
+ <P>(Note the <CODE>COMException class supports (and translates) "desc" as a shortcut for "description", but the framework requires "description")</P>
174
+ </CODE><H2><A NAME="Policies">Server Policies</A></H2>
175
+ <P>This is information about how it all hangs together. The casual COM author need not know this. </P>
176
+ <P>Whenever a Python Server needs to be created, the C++ framework first instantiates a "policy" object. This "policy" object is the gatekeeper for the COM Server - it is responsible for creating the underlying Python object that is the server (ie, your object), and also for translating the underlying COM requests for the object. </P>
177
+ <P>This policy object handles all of the underlying COM functionality. For example, COM requires all methods and properties to have unique numeric ID's associated with them. The policy object manages the creation of these ID's for the underlying Python methods and attributes. Similarly, when the client whishes to call a method with ID 123, the policy object translates this back to the actual method, and makes the call. </P>
178
+ <P>It should be noted that the operation of the "policy" object could be dictated by the Python object - the policy object has many defaults, but the actual Python class can always dictate its operation. </P>
179
+ <H3>Default Policy attributes </H3>
180
+ <P>The default policy object has a few special attributes that define who the object is exposed to COM. The example above shows the _public_methods attribute, but this section describes all such attributes in detail. </P>
181
+ <H5>_public_methods_ </H5>
182
+ <P>Required list of strings, containing the names of all methods to be exposed to COM. It is possible this will be enhanced in the future (eg, possibly '*' will be recognised to say all methods, or some other ideas...) </P>
183
+ <H5>_public_attrs_ </H5>
184
+ <P>Optional list of strings containing all attribute names to be exposed, both for reading and writing. The attribute names must be valid instance variables. </P>
185
+ <H5>_readonly_attrs_ </H5>
186
+ <P>Optional list of strings defining the name of attributes exposed read-only. </P>
187
+ <H5>_com_interfaces_ </H5>
188
+ <P>Optional list of IIDs exposed by this object. If this attribute is missing, IID_IDispatch is assumed (ie, if not supplied, the COM object will be created as a normal Automation object).</P>
189
+ <P>and actual instance attributes: </P>
190
+ <P>_dynamic_ : optional method </P>
191
+ <P>_value_ : optional attribute </P>
192
+ <P>_query_interface_ : optional method </P>
193
+ <P>_NewEnum : optional method </P>
194
+ <P>_Evaluate : optional method </P></BODY>
195
+ </HTML>
loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/docindex.html ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <HTML>
2
+ <HEAD>
3
+ <META HTTP-EQUIV="Content-Type" CONTENT="text/html" charset="utf-8">
4
+ <META NAME="Generator" CONTENT="Microsoft Word 97">
5
+ <TITLE>win32com Documentation Index</TITLE>
6
+ <META NAME="Template" CONTENT="D:\Program Files\Microsoft Office\Office\html.dot">
7
+ </HEAD>
8
+ <BODY LINK="#0000ff" VLINK="#800080">
9
+
10
+ <H1><IMG SRC="image/pycom_blowing.gif" WIDTH=549 HEIGHT=99 ALT="Python and COM - Blowing the others away"></H1>
11
+ <H1>PythonCOM Documentation Index</H1>
12
+ <P>The following documentation is available</P>
13
+ <P><A HREF="QuickStartClientCom.html">A Quick Start to Client Side COM</A> (including makepy)</P>
14
+ <P><A HREF="QuickStartServerCom.html">A Quick Start to Server Side COM</A></P>
15
+ <P><A HREF="GeneratedSupport.html">Information on generated Python files (ie, what makepy generates)</A></P>
16
+ <P><A HREF="variant.html">An advanced VARIANT object which can give more control over parameter types</A></P>
17
+ <P><A HREF="COM_Records.html">COM Record Support</A></P>
18
+ <P><A HREF="package.html">A brief description of the win32com package structure</A></P>
19
+ <P><A HREF="PythonCOM.html">Python COM Implementation documentation</A></P>
20
+ <P><A HREF="misc.html">Misc stuff I don't know where to put anywhere else</A></P>
21
+ <H3>ActiveX Scripting</H3>
22
+ <P><A HREF="../../win32comext/axscript/demos/client/ie/demo.htm">ActiveX Scripting Demos</A></P></BODY>
23
+ </HTML>
loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/image/BTN_HomePage.gif ADDED
loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/image/BTN_ManualTop.gif ADDED
loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/image/BTN_NextPage.gif ADDED
loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/image/BTN_PrevPage.gif ADDED
loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/image/blank.gif ADDED
loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/image/pycom_blowing.gif ADDED
loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/image/pythoncom.gif ADDED
loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/image/www_icon.gif ADDED
loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/index.html ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <HTML>
2
+ <HEAD>
3
+ <META HTTP-EQUIV="Content-Type" CONTENT="text/html" charset="utf-8">
4
+ <META NAME="Generator" CONTENT="Microsoft Word 97">
5
+ <TITLE>win32com</TITLE>
6
+ <META NAME="Template" CONTENT="C:\Program Files\Microsoft Office\Office\html.dot">
7
+ </HEAD>
8
+ <BODY TEXT="#000000" LINK="#0000ff" VLINK="#0000ff">
9
+ <DIR>
10
+
11
+ <P><!-- Enclose the entire page in UL, so bullets don't indent. --></P>
12
+ <H1><IMG SRC="image/pycom_blowing.gif" WIDTH=549 HEIGHT=99></H1>
13
+ <H2>Python and COM</H2>
14
+ <H3>Introduction</H3>
15
+ <P>Python has an excellent interface to COM (also known variously as OLE2, ActiveX, etc).</P>
16
+ <P>The Python COM package can be used to interface to almost any COM program (such as the MS-Office suite), write servers that can be hosted by any COM client (such as Visual Basic or C++), and has even been used to provide the core ActiveX Scripting Support. </P>
17
+
18
+
19
+ <UL>
20
+ <LI>Note that win32com is now released in the win32all installation package. The <A HREF="../win32all/win32all.exe">installation EXE can be downloaded</A>, or you <A HREF="../win32all/">can jump to the win32all readme</A> for more details. </LI>
21
+ <LI>Here is the <A HREF="win32com_src.zip">win32com source code</A> in a zip file. </LI></UL>
22
+ </DIR>
23
+ <DIR>
24
+
25
+ <H3>Documentation</H3>
26
+ <P><A HREF="ActiveXScripting.html">Preliminary Active Scripting and Debugging documentation</A> is available.</P>
27
+ <P>2 Quick-Start guides have been provided, which also contain other links. See the <A HREF="QuickStartClientCom.html">Quick Start for Client side COM</A> and the <A HREF="QuickStartServerCom.html">Quick Start for Server side COM</A> </P>
28
+ </P></DIR>
29
+ </DIR>
30
+ </BODY>
31
+ </HTML>
loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/misc.html ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <HTML>
2
+ <HEAD>
3
+ <META HTTP-EQUIV="Content-Type" CONTENT="text/html" charset="utf-8">
4
+ <META NAME="Generator" CONTENT="Microsoft Word 97">
5
+ <TITLE>Misc win32com Stuff</TITLE>
6
+ <META NAME="Version" CONTENT="8.0.3410">
7
+ <META NAME="Date" CONTENT="10/11/96">
8
+ <META NAME="Template" CONTENT="D:\Program Files\Microsoft Office\Office\HTML.DOT">
9
+ </HEAD>
10
+ <BODY TEXT="#000000" BGCOLOR="#ffffff">
11
+
12
+ <H1>Misc stuff I don't know where to put anywhere else</H1>
13
+ <H4>Client Side Dispatch</H4>
14
+ <P>Using win32com.client.Dispatch automatically invokes all the win32com client side "smarts", including automatic usage of generated .py files etc.</P>
15
+ <P>If you wish to avoid that, and use truly "dynamic" objects (ie, there is generated .py support available, but you wish to avoid it), you can use win32com.client.dynamic.Dispatch</P>
16
+ <B><P>_print_details_() method</B><BR>
17
+ If win32com.client.dynamic.Dispatch is used, the objects have a _print_details_() method available, which prints all relevant knowledge about an object (for example, all methods and properties). For objects that do not expose runtime type information, _print_details_ may not list anything.</P></BODY>
18
+ </HTML>
loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/package.html ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <HTML>
2
+ <HEAD>
3
+ <META HTTP-EQUIV="Content-Type" CONTENT="text/html" charset="utf-8">
4
+ <META NAME="Generator" CONTENT="Microsoft Word 97">
5
+ <TITLE>The win32com package</TITLE>
6
+ <META NAME="Template" CONTENT="D:\Program Files\Microsoft Office\Office\html.dot">
7
+ </HEAD>
8
+ <BODY LINK="#0000ff" VLINK="#800080">
9
+
10
+ <H1><IMG SRC="image/pycom_blowing.gif" WIDTH=549 HEIGHT=99 ALT="Python and COM - Blowing the others away"></H1>
11
+ <H1>The win32com package </H1>
12
+ <FONT SIZE=2><P>This document describes the win32com package in general terms.</FONT> </P>
13
+ <FONT SIZE=2><P>The COM support can be thought of as existing in 2 main portions - the C++ support code (the core PythonCOM module), and helper code, implemented in Python. The total package is known as "win32com".</FONT> </P>
14
+ <FONT SIZE=2><P>The win32com support is stand-alone. It does not require Pythonwin.</FONT> </P>
15
+ <H2>The win32com package </H2>
16
+ <FONT SIZE=2><P>To facilitate an orderly framework, the Python "ni" module has been used, and the entire package is known as "win32com". As is normal for such packages, win32com itself does not provide any functionality. Some of the modules are described below:</FONT> </P>
17
+
18
+ <UL>
19
+ <B><FONT SIZE=2><LI>win32com.pythoncom - core C++ support</B>. <BR>
20
+ This module is rarely used directly by programmers - instead the other "helper" module are used, which themselves draw on the core pythoncom services.</FONT> </LI>
21
+ <B><FONT SIZE=2><LI>win32com.client package<BR>
22
+ </B>Support for COM clients used by Python. Some of the modules in this package allow for dynamic usage of COM clients, a module for generating .py files for certain COM servers, etc.</FONT> </LI>
23
+ <B><FONT SIZE=2><LI>win32com.server package<BR>
24
+ </B>Support for COM servers written in Python. The modules in this package provide most of the underlying framework for magically turning Python classes into COM servers, exposing the correct public methods, registering your server in the registry, etc. </LI>
25
+ <B><LI>win32com.axscript<BR>
26
+ </B>ActiveX Scripting implementation for Python.</FONT> </LI>
27
+ <B><FONT SIZE=2><LI>win32com.axdebug<BR>
28
+ </B>Active Debugging implementation for Python</FONT> </LI>
29
+ <B><FONT SIZE=2><LI>win32com.mapi<BR>
30
+ </B>Utilities for working with MAPI and the Microsoft Exchange Server</LI></UL>
31
+
32
+ </FONT><P>&nbsp;</P>
33
+ <H2>The pythoncom module </H2>
34
+ <FONT SIZE=2><P>The pythoncom module is the underlying C++ support for all COM related objects. In general, Python programmers will not use this module directly, but use win32com helper classes and functions. </P>
35
+ <P>This module exposes a C++ like interface to COM - there are objects implemented in pythoncom that have methods "QueryInterface()", "Invoke()", just like the C++ API. If you are using COM in C++, you would not call a method directly, you would use pObject-&gt;Invoke( ..., MethodId, argArray...). Similarly, if you are using pythoncom directly, you must also use the Invoke method to call an object's exposed method.</FONT> </P>
36
+ <FONT SIZE=2><P>There are some Python wrappers for hiding this raw interface, meaning you should almost never need to use the pythoncom module directly. These helpers translate a "natural" looking interface (eg, obj.SomeMethod()) into the underlying Invoke call.</P></FONT></BODY>
37
+ </HTML>
loan-advisor-agent/.venv/Lib/site-packages/win32com/HTML/variant.html ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <HTML>
2
+ <HEAD>
3
+ <TITLE>win32com.client.VARIANT</TITLE>
4
+ </HEAD>
5
+ <BODY>
6
+
7
+ <H2>Introduction</H2>
8
+ <p>
9
+ win32com attempts to provide a seamless COM interface and hide many COM
10
+ implementation details, including the use of COM VARIANT structures. This
11
+ means that in most cases, you just call a COM object using normal Python
12
+ objects as parameters and get back normal Python objects as results.
13
+ </p>
14
+
15
+ <p>
16
+ However, in some cases this doesn't work very well, particularly when using
17
+ "dynamic" (aka late-bound) objects, or when using "makepy" (aka early-bound)
18
+ objects which only declare a parameter is a VARIANT.
19
+ </p>
20
+
21
+ <p>
22
+ The <code>win32com.client.VARIANT</code> object is designed to overcome these
23
+ problems.
24
+ </p>
25
+
26
+ <h2>Drawbacks</h2>
27
+ The primary issue with this approach is that the programmer must learn more
28
+ about COM VARIANTs than otherwise - they need to know concepts such as
29
+ variants being <em>byref</em>, holding arrays, or that some may hold 32bit
30
+ unsigned integers while others hold 64bit signed ints, and they need to
31
+ understand this in the context of a single method call. In short, this is
32
+ a relatively advanced feature. The good news though is that use of these
33
+ objects should never cause your program to hard-crash - the worst you should
34
+ expect are Python or COM exceptions being thrown.
35
+
36
+ <h2>The VARIANT object</h2>
37
+
38
+ The VARIANT object lives in <code>win32com.client</code>. The constructor
39
+ takes 2 parameters - the 'variant type' and the value. The 'variant type' is
40
+ an integer and can be one or more of the <code>pythoncom.VT_*</code> values,
41
+ possibly or'd together.
42
+
43
+ <p>For example, to create a VARIANT object which defines a byref array of
44
+ 32bit integers, you could use:
45
+
46
+ <pre>
47
+ >>> from win32com.client import VARIANT
48
+ >>> import pythoncom
49
+ >>> v = VARIANT(pythoncom.VT_BYREF | pythoncom.VT_ARRAY | pythoncom.VT_I4,
50
+ ... [1,2,3,4])
51
+ >>> v
52
+ win32com.client.VARIANT(24579, [1, 2, 3, 4])
53
+ >>>
54
+ </pre>
55
+
56
+ This variable can then be used whereever a COM VARIANT is expected.
57
+
58
+ <h2>Example usage with dynamic objects.</h2>
59
+
60
+ For this example we will use the COM object used for win32com testing,
61
+ <code>PyCOMTest.PyCOMTest</code>. This object defines a method which is
62
+ defined in IDL as:
63
+ <pre>
64
+ HRESULT DoubleInOutString([in,out] BSTR *str);
65
+ </pre>
66
+
67
+ As you can see, it takes a single string parameter which is also used as
68
+ an "out" parameter - the single parameter will be updated after the call.
69
+ The implementation of the method simply "doubles" the string.
70
+
71
+ <p>If the object has a type-library, this method works fine with makepy
72
+ generated support. For example:
73
+
74
+ <pre>
75
+ >>> from win32com.client.gencache import EnsureDispatch
76
+ >>> ob = EnsureDispatch("PyCOMTest.PyCOMTest")
77
+ >>> ob.DoubleInOutString("Hello")
78
+ u'HelloHello'
79
+ >>>
80
+ </pre>
81
+
82
+ However, if makepy support is not available the method does not work as
83
+ expected. For the next example we will use <code>DumbDispatch</code> to
84
+ simulate the object not having a type-library.
85
+
86
+ <pre>
87
+ >>> import win32com.client.dynamic
88
+ >>> ob = win32com.client.dynamic.DumbDispatch("PyCOMTest.PyCOMTest")
89
+ >>> ob.DoubleInOutString("Hello")
90
+ >>>
91
+ </pre>
92
+
93
+ As you can see, no result came back from the function. This is because
94
+ win32com has no type information available to use, so doesn't know the
95
+ parameter should be passed as a <code>byref</code> parameter. To work
96
+ around this, we can use the <code>VARIANT</code> object.
97
+
98
+ <p>The following example explicitly creates a VARIANT object with a
99
+ variant type of a byref string and a value 'Hello'. After making the
100
+ call with this VARIANT the value is updated.
101
+
102
+ <pre>
103
+ >>> import win32com.client.dynamic
104
+ >>> from win32com.client import VARIANT
105
+ >>> import pythoncom
106
+ >>> ob = win32com.client.dynamic.DumbDispatch("PyCOMTest.PyCOMTest")
107
+ >>> variant = VARIANT(pythoncom.VT_BYREF | pythoncom.VT_BSTR, "Hello")
108
+ >>> variant.value # check the value before the call.
109
+ 'Hello'
110
+ >>> ob.DoubleInOutString(variant)
111
+ >>> variant.value
112
+ u'HelloHello'
113
+ >>>
114
+ </pre>
115
+
116
+ <h2>Usage with generated objects</h2>
117
+
118
+ In most cases, objects with makepy support (ie, 'generated' objects) don't
119
+ need to use the VARIANT object - the type information means win32com can guess
120
+ the right thing to pass. However, in some cases the VARIANT object can still
121
+ be useful.
122
+
123
+ Imagine a poorly specified object with IDL like:
124
+
125
+ <pre>
126
+ HRESULT DoSomething([in] VARIANT value);
127
+ </pre>
128
+
129
+ But also imagine that the object has a limitation that if the parameter is an
130
+ integer, it must be a 32bit unsigned value - any other integer representation
131
+ will fail.
132
+
133
+ <p>If you just pass a regular Python integer to this function, it will
134
+ generally be passed as a 32bit signed integer and given the limitation above,
135
+ will fail. The VARIANT object allows you to work around the limitation - just
136
+ create a variant object <code>VARIANT(pythoncom.VT_UI4, int_value)</code> and
137
+ pass that - the function will then be called with the explicit type you
138
+ specified and will succeed.
139
+
140
+ <p>Note that you can not use a VARIANT object to override the types described
141
+ in a type library. If a makepy generated class specifies that a VT_UI2 is
142
+ expected, attempting to pass a VARIANT object will fail. In this case you
143
+ would need to hack around the problem. For example, imagine <code>ob</code>
144
+ was a COM object which a method called <code>foo</code> and you wanted to
145
+ override the type declaration for <code>foo</code> by passing a VARIANT.
146
+ You could do something like:
147
+
148
+ <pre>
149
+ >>> import win32com.client.dynamic
150
+ >>> from win32com.client import VARIANT
151
+ >>> import pythoncom
152
+ >>> dumbob = win32com.client.dynamic.DumbDispatch(ob)
153
+ >>> variant = VARIANT(pythoncom.VT_BYREF | pythoncom.VT_BSTR, "Hello")
154
+ >>> dumbob.foo(variant)
155
+ </pre>
156
+
157
+ The code above converts the makepy supported <code>ob</code> into a
158
+ 'dumb' (ie, non-makepy supported) version of the object, which will then
159
+ allow you to use VARIANT objects for the problematic methods.
160
+
161
+ </BODY>
162
+ </HTML>
loan-advisor-agent/.venv/Lib/site-packages/win32com/License.txt ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Unless stated in the specfic source file, this work is
2
+ Copyright (c) 1996-2008, Greg Stein and Mark Hammond.
3
+ All rights reserved.
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions
7
+ are met:
8
+
9
+ Redistributions of source code must retain the above copyright notice,
10
+ this list of conditions and the following disclaimer.
11
+
12
+ Redistributions in binary form must reproduce the above copyright
13
+ notice, this list of conditions and the following disclaimer in
14
+ the documentation and/or other materials provided with the distribution.
15
+
16
+ Neither names of Greg Stein, Mark Hammond nor the name of contributors may be used
17
+ to endorse or promote products derived from this software without
18
+ specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS
21
+ IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22
+ TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
23
+ PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
24
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
25
+ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
26
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
27
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
28
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
29
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
30
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
loan-advisor-agent/.venv/Lib/site-packages/win32com/__init__.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Initialization for the win32com package
3
+ #
4
+ from __future__ import annotations
5
+
6
+ import os
7
+ import sys
8
+
9
+ import pythoncom
10
+ import win32api
11
+
12
+ # flag if we are in a "frozen" build.
13
+ _frozen = getattr(sys, "frozen", False)
14
+ # pythoncom dumbly defaults this to zero - we believe sys.frozen over it.
15
+ if _frozen and not getattr(pythoncom, "frozen", 0):
16
+ pythoncom.frozen = sys.frozen
17
+
18
+ # Add support for an external "COM Extensions" path.
19
+ # Concept is that you can register a seperate path to be used for
20
+ # COM extensions, outside of the win32com directory. These modules, however,
21
+ # look identical to win32com built-in modules.
22
+ # This is the technique that we use for the "standard" COM extensions.
23
+ # eg "win32com.mapi" or "win32com.axscript" both work, even though they do not
24
+ # live under the main win32com directory.
25
+ __gen_path__ = ""
26
+ __build_path__ = None
27
+ ### TODO - Load _all_ \\Extensions subkeys - for now, we only read the default
28
+ ### Modules will work if loaded into "win32comext" path.
29
+
30
+ # Ensure we're working on __path__ as list, not Iterable
31
+ __path__: list[str] = list(__path__) # type: ignore[no-redef]
32
+
33
+
34
+ def SetupEnvironment():
35
+ HKEY_LOCAL_MACHINE = -2147483646 # Avoid pulling in win32con for just these...
36
+ KEY_QUERY_VALUE = 0x1
37
+ # Open the root key once, as this is quite slow on NT.
38
+ try:
39
+ keyName = "SOFTWARE\\Python\\PythonCore\\%s\\PythonPath\\win32com" % sys.winver
40
+ key = win32api.RegOpenKey(HKEY_LOCAL_MACHINE, keyName, 0, KEY_QUERY_VALUE)
41
+ except (win32api.error, AttributeError):
42
+ key = None
43
+
44
+ try:
45
+ found = 0
46
+ if key is not None:
47
+ try:
48
+ __path__.append(win32api.RegQueryValue(key, "Extensions"))
49
+ found = 1
50
+ except win32api.error:
51
+ # Nothing registered
52
+ pass
53
+ if not found:
54
+ try:
55
+ __path__.append(
56
+ win32api.GetFullPathName(__path__[0] + "\\..\\win32comext")
57
+ )
58
+ except win32api.error:
59
+ # Give up in disgust!
60
+ pass
61
+
62
+ # For the sake of developers, we also look up a "BuildPath" key
63
+ # If extension modules add support, we can load their .pyd's from a completely
64
+ # different directory (see the comments below)
65
+ try:
66
+ if key is not None:
67
+ global __build_path__
68
+ __build_path__ = win32api.RegQueryValue(key, "BuildPath")
69
+ __path__.append(__build_path__)
70
+ except win32api.error:
71
+ # __build_path__ neednt be defined.
72
+ pass
73
+ global __gen_path__
74
+ if key is not None:
75
+ try:
76
+ __gen_path__ = win32api.RegQueryValue(key, "GenPath")
77
+ except win32api.error:
78
+ pass
79
+ finally:
80
+ if key is not None:
81
+ key.Close()
82
+
83
+
84
+ # A Helper for developers. A sub-package's __init__ can call this help function,
85
+ # which allows the .pyd files for the extension to live in a special "Build" directory
86
+ # (which the win32com developers do!)
87
+ def __PackageSupportBuildPath__(package_path):
88
+ # See if we have a special directory for the binaries (for developers)
89
+ if not _frozen and __build_path__:
90
+ package_path.append(__build_path__)
91
+
92
+
93
+ if not _frozen:
94
+ SetupEnvironment()
95
+
96
+ # If we don't have a special __gen_path__, see if we have a gen_py as a
97
+ # normal module and use that (ie, "win32com.gen_py" may already exist as
98
+ # a package.
99
+ if not __gen_path__:
100
+ try:
101
+ import win32com.gen_py
102
+
103
+ # __path__ is only ensured to be an Iterable, not a list.
104
+ __gen_path__ = next(iter(sys.modules["win32com.gen_py"].__path__))
105
+ except ImportError:
106
+ # If a win32com\gen_py directory already exists, then we use it
107
+ # (gencache doesn't insist it have an __init__, but our __import__
108
+ # above does!
109
+ __gen_path__ = os.path.abspath(os.path.join(__path__[0], "gen_py"))
110
+ if not os.path.isdir(__gen_path__):
111
+ # We used to dynamically create a directory under win32com -
112
+ # but this sucks. If the dir doesn't already exist, we
113
+ # create a version specific directory under the user temp
114
+ # directory.
115
+ __gen_path__ = os.path.join(
116
+ win32api.GetTempPath(),
117
+ "gen_py",
118
+ "%d.%d" % (sys.version_info.major, sys.version_info.minor),
119
+ )
120
+
121
+ # we must have a __gen_path__, but may not have a gen_py module -
122
+ # set that up.
123
+ if "win32com.gen_py" not in sys.modules:
124
+ # Create a "win32com.gen_py", but with a custom __path__
125
+ import types
126
+
127
+ gen_py = types.ModuleType("win32com.gen_py")
128
+ gen_py.__path__ = [__gen_path__]
129
+ sys.modules[gen_py.__name__] = gen_py
130
+ del types
131
+ gen_py = sys.modules["win32com.gen_py"]
132
+
133
+ # get rid of these for module users
134
+ del os, sys, win32api, pythoncom
loan-advisor-agent/.venv/Lib/site-packages/win32com/client/CLSIDToClass.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Manages a dictionary of CLSID strings to Python classes.
2
+
3
+ Primary use of this module is to allow modules generated by
4
+ makepy.py to share classes. @makepy@ automatically generates code
5
+ which interacts with this module. You should never need to reference
6
+ this module directly.
7
+
8
+ This module only provides support for modules which have been previously
9
+ been imported. The gencache module provides some support for loading modules
10
+ on demand - once done, this module supports it...
11
+
12
+ As an example, the MSACCESS.TLB type library makes reference to the
13
+ CLSID of the Database object, as defined in DAO3032.DLL. This
14
+ allows code using the MSAccess wrapper to natively use Databases.
15
+
16
+ This obviously applies to all cooperating objects, not just DAO and
17
+ Access.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ mapCLSIDToClass: dict[str, type] = {}
23
+
24
+
25
+ def RegisterCLSID(clsid, pythonClass):
26
+ """Register a class that wraps a CLSID
27
+
28
+ This function allows a CLSID to be globally associated with a class.
29
+ Certain module will automatically convert an IDispatch object to an
30
+ instance of the associated class.
31
+ """
32
+
33
+ mapCLSIDToClass[str(clsid)] = pythonClass
34
+
35
+
36
+ def RegisterCLSIDsFromDict(dict):
37
+ """Register a dictionary of CLSID's and classes.
38
+
39
+ This module performs the same function as @RegisterCLSID@, but for
40
+ an entire dictionary of associations.
41
+
42
+ Typically called by makepy generated modules at import time.
43
+ """
44
+ mapCLSIDToClass.update(dict)
45
+
46
+
47
+ def GetClass(clsid):
48
+ """Given a CLSID, return the globally associated class.
49
+
50
+ clsid -- a string CLSID representation to check.
51
+ """
52
+ return mapCLSIDToClass[clsid]
53
+
54
+
55
+ def HasClass(clsid):
56
+ """Determines if the CLSID has an associated class.
57
+
58
+ clsid -- the string CLSID to check
59
+ """
60
+ return clsid in mapCLSIDToClass
loan-advisor-agent/.venv/Lib/site-packages/win32com/client/__init__.py ADDED
@@ -0,0 +1,703 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This module exists to create the "best" dispatch object for a given
2
+ # object. If "makepy" support for a given object is detected, it is
3
+ # used, otherwise a dynamic dispatch object.
4
+
5
+ # Note that if the unknown dispatch object then returns a known
6
+ # dispatch object, the known class will be used. This contrasts
7
+ # with dynamic.Dispatch behaviour, where dynamic objects are always used.
8
+ from __future__ import annotations
9
+
10
+ import sys
11
+ from itertools import chain
12
+
13
+ import pythoncom
14
+ import pywintypes
15
+
16
+ from . import dynamic, gencache
17
+
18
+ _PyIDispatchType = pythoncom.TypeIIDs[pythoncom.IID_IDispatch]
19
+
20
+
21
+ def __WrapDispatch(
22
+ dispatch,
23
+ userName=None,
24
+ resultCLSID=None,
25
+ typeinfo=None,
26
+ clsctx=pythoncom.CLSCTX_SERVER,
27
+ WrapperClass=None,
28
+ ):
29
+ """
30
+ Helper function to return a makepy generated class for a CLSID if it exists,
31
+ otherwise cope by using CDispatch.
32
+ """
33
+ if resultCLSID is None:
34
+ try:
35
+ typeinfo = dispatch.GetTypeInfo()
36
+ if (
37
+ typeinfo is not None
38
+ ): # Some objects return NULL, some raise exceptions...
39
+ resultCLSID = str(typeinfo.GetTypeAttr()[0])
40
+ except (pythoncom.com_error, AttributeError):
41
+ pass
42
+ if resultCLSID is not None:
43
+ from . import gencache
44
+
45
+ # Attempt to load generated module support
46
+ # This may load the module, and make it available
47
+ klass = gencache.GetClassForCLSID(resultCLSID)
48
+ if klass is not None:
49
+ return klass(dispatch)
50
+
51
+ # Return a "dynamic" object - best we can do!
52
+ if WrapperClass is None:
53
+ WrapperClass = CDispatch
54
+ return dynamic.Dispatch(dispatch, userName, WrapperClass, typeinfo, clsctx=clsctx)
55
+
56
+
57
+ def GetObject(Pathname=None, Class=None, clsctx=None):
58
+ r"""
59
+ Mimic VB's GetObject() function.
60
+
61
+ ob = GetObject(Class = "ProgID") or GetObject(Class = clsid) will
62
+ connect to an already running instance of the COM object.
63
+
64
+ ob = GetObject(r"c:\blah\blah\foo.xls") (aka the COM moniker syntax)
65
+ will return a ready to use Python wrapping of the required COM object.
66
+
67
+ Note: You must specifiy one or the other of these arguments. I know
68
+ this isn't pretty, but it is what VB does. Blech. If you don't
69
+ I'll throw ValueError at you. :)
70
+
71
+ This will most likely throw pythoncom.com_error if anything fails.
72
+ """
73
+ if clsctx is None:
74
+ clsctx = pythoncom.CLSCTX_ALL
75
+
76
+ if (Pathname is None and Class is None) or (
77
+ Pathname is not None and Class is not None
78
+ ):
79
+ raise ValueError(
80
+ "You must specify a value for Pathname or Class, but not both."
81
+ )
82
+
83
+ if Class is not None:
84
+ return GetActiveObject(Class, clsctx)
85
+ else:
86
+ return Moniker(Pathname, clsctx)
87
+
88
+
89
+ def GetActiveObject(Class, clsctx=pythoncom.CLSCTX_ALL):
90
+ """
91
+ Python friendly version of GetObject's ProgID/CLSID functionality.
92
+ """
93
+ resultCLSID = pywintypes.IID(Class)
94
+ dispatch = pythoncom.GetActiveObject(resultCLSID)
95
+ dispatch = dispatch.QueryInterface(pythoncom.IID_IDispatch)
96
+ return __WrapDispatch(dispatch, Class, resultCLSID=resultCLSID, clsctx=clsctx)
97
+
98
+
99
+ def Moniker(Pathname, clsctx=pythoncom.CLSCTX_ALL):
100
+ """
101
+ Python friendly version of GetObject's moniker functionality.
102
+ """
103
+ moniker, i, bindCtx = pythoncom.MkParseDisplayName(Pathname)
104
+ dispatch = moniker.BindToObject(bindCtx, None, pythoncom.IID_IDispatch)
105
+ return __WrapDispatch(dispatch, Pathname, clsctx=clsctx)
106
+
107
+
108
+ def Dispatch(
109
+ dispatch,
110
+ userName=None,
111
+ resultCLSID=None,
112
+ typeinfo=None,
113
+ clsctx=pythoncom.CLSCTX_SERVER,
114
+ ):
115
+ """Creates a Dispatch based COM object."""
116
+ dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch, userName, clsctx)
117
+ return __WrapDispatch(dispatch, userName, resultCLSID, typeinfo, clsctx=clsctx)
118
+
119
+
120
+ def DispatchEx(
121
+ clsid,
122
+ machine=None,
123
+ userName=None,
124
+ resultCLSID=None,
125
+ typeinfo=None,
126
+ clsctx=None,
127
+ ):
128
+ """Creates a Dispatch based COM object on a specific machine."""
129
+ # If InProc is registered, DCOM will use it regardless of the machine name
130
+ # (and regardless of the DCOM config for the object.) So unless the user
131
+ # specifies otherwise, we exclude inproc apps when a remote machine is used.
132
+ if clsctx is None:
133
+ clsctx = pythoncom.CLSCTX_SERVER
134
+ if machine is not None:
135
+ clsctx &= ~pythoncom.CLSCTX_INPROC
136
+ if machine is None:
137
+ serverInfo = None
138
+ else:
139
+ serverInfo = (machine,)
140
+ if userName is None:
141
+ userName = clsid
142
+ dispatch = pythoncom.CoCreateInstanceEx(
143
+ clsid, None, clsctx, serverInfo, (pythoncom.IID_IDispatch,)
144
+ )[0]
145
+ return Dispatch(dispatch, userName, resultCLSID, typeinfo, clsctx=clsctx)
146
+
147
+
148
+ class CDispatch(dynamic.CDispatch):
149
+ """
150
+ The dynamic class used as a last resort.
151
+ The purpose of this overriding of dynamic.CDispatch is to perpetuate the policy
152
+ of using the makepy generated wrapper Python class instead of dynamic.CDispatch
153
+ if/when possible.
154
+ """
155
+
156
+ def _wrap_dispatch_(self, ob, userName=None, returnCLSID=None):
157
+ return Dispatch(ob, userName, returnCLSID)
158
+
159
+ def __dir__(self):
160
+ return dynamic.CDispatch.__dir__(self)
161
+
162
+
163
+ def CastTo(ob, target, typelib=None):
164
+ """'Cast' a COM object to another interface"""
165
+ # todo - should support target being an IID
166
+ mod = None
167
+ if (
168
+ typelib is not None
169
+ ): # caller specified target typelib (TypelibSpec). See e.g. selecttlb.EnumTlbs().
170
+ mod = gencache.MakeModuleForTypelib(
171
+ typelib.clsid, typelib.lcid, int(typelib.major, 16), int(typelib.minor, 16)
172
+ )
173
+ if not hasattr(mod, target):
174
+ raise ValueError(
175
+ f"The interface name '{target}' does not appear in the "
176
+ f"specified library {typelib.ver_desc!r}"
177
+ )
178
+
179
+ elif hasattr(target, "index"): # string like
180
+ # for now, we assume makepy for this to work.
181
+ if "CLSID" not in ob.__class__.__dict__:
182
+ # Eeek - no makepy support - try and build it.
183
+ ob = gencache.EnsureDispatch(ob)
184
+ if "CLSID" not in ob.__class__.__dict__:
185
+ raise ValueError("Must be a makepy-able object for this to work")
186
+ clsid = ob.CLSID
187
+ # Lots of hoops to support "demand-build" - ie, generating
188
+ # code for an interface first time it is used. We assume the
189
+ # interface name exists in the same library as the object.
190
+ # This is generally the case - only referenced typelibs may be
191
+ # a problem, and we can handle that later. Maybe <wink>
192
+ # So get the generated module for the library itself, then
193
+ # find the interface CLSID there.
194
+ mod = gencache.GetModuleForCLSID(clsid)
195
+ # Get the 'root' module.
196
+ mod = gencache.GetModuleForTypelib(
197
+ mod.CLSID, mod.LCID, mod.MajorVersion, mod.MinorVersion
198
+ )
199
+ # Find the CLSID of the target
200
+ target_clsid = mod.NamesToIIDMap.get(target)
201
+ if target_clsid is None:
202
+ raise ValueError(
203
+ f"The interface name '{target}' does not appear in the "
204
+ f"same library as object '{ob!r}'"
205
+ )
206
+ mod = gencache.GetModuleForCLSID(target_clsid)
207
+ if mod is not None:
208
+ target_class = getattr(mod, target)
209
+ # resolve coclass to interface
210
+ target_class = getattr(target_class, "default_interface", target_class)
211
+ return target_class(ob) # auto QI magic happens
212
+ raise ValueError
213
+
214
+
215
+ class Constants:
216
+ """A container for generated COM constants."""
217
+
218
+ def __init__(self):
219
+ self.__dicts__ = [] # A list of dictionaries
220
+
221
+ def __getattr__(self, a):
222
+ for d in self.__dicts__:
223
+ if a in d:
224
+ return d[a]
225
+ raise AttributeError(a)
226
+
227
+
228
+ # And create an instance.
229
+ constants = Constants()
230
+
231
+
232
+ # A helpers for DispatchWithEvents - this becomes __setattr__ for the
233
+ # temporary class.
234
+ def _event_setattr_(self, attr, val):
235
+ try:
236
+ # Does the COM object have an attribute of this name?
237
+ self.__class__.__bases__[0].__setattr__(self, attr, val)
238
+ except AttributeError:
239
+ # Otherwise just stash it away in the instance.
240
+ self.__dict__[attr] = val
241
+
242
+
243
+ # An instance of this "proxy" is created to break the COM circular references
244
+ # that exist (ie, when we connect to the COM events, COM keeps a reference
245
+ # to the object. Thus, the Event connection must be manually broken before
246
+ # our object can die. This solves the problem by manually breaking the connection
247
+ # to the real object as the proxy dies.
248
+ class EventsProxy:
249
+ def __init__(self, ob):
250
+ self.__dict__["_obj_"] = ob
251
+
252
+ def __del__(self):
253
+ try:
254
+ # If there is a COM error on disconnection we should
255
+ # just ignore it - object probably already shut down...
256
+ self._obj_.close()
257
+ except pythoncom.com_error:
258
+ pass
259
+
260
+ def __getattr__(self, attr):
261
+ return getattr(self._obj_, attr)
262
+
263
+ def __setattr__(self, attr, val):
264
+ setattr(self._obj_, attr, val)
265
+
266
+
267
+ def __get_disp_and_event_classes(dispatch):
268
+ # Create/Get the object.
269
+ disp = Dispatch(dispatch)
270
+
271
+ if disp.__class__.__dict__.get("CLSID"):
272
+ disp_class = disp.__class__
273
+ else:
274
+ # Eeek - no makepy support - try and build it.
275
+ error_msg = "This COM object can not automate the makepy process - please run makepy manually for this object"
276
+ try:
277
+ ti = disp._oleobj_.GetTypeInfo()
278
+ disp_clsid = ti.GetTypeAttr()[0]
279
+ tlb, index = ti.GetContainingTypeLib()
280
+ tla = tlb.GetLibAttr()
281
+ gencache.EnsureModule(tla[0], tla[1], tla[3], tla[4], bValidateFile=0)
282
+ # Get the class from the module.
283
+ disp_class = gencache.GetClassForProgID(str(disp_clsid))
284
+ except pythoncom.com_error as error:
285
+ raise TypeError(error_msg) from error
286
+
287
+ if disp_class is None:
288
+ raise TypeError(error_msg)
289
+
290
+ # Get the clsid
291
+ clsid = disp_class.CLSID
292
+ # Create a new class that derives from 2 classes:
293
+ # the event sink class and the user class.
294
+ events_class = getevents(clsid)
295
+ if events_class is None:
296
+ raise ValueError("This COM object does not support events.")
297
+ return disp, disp_class, events_class
298
+
299
+
300
+ def DispatchWithEvents(clsid, user_event_class) -> EventsProxy:
301
+ """Create a COM object that can fire events to a user defined class.
302
+ clsid -- The ProgID or CLSID of the object to create.
303
+ user_event_class -- A Python class object that responds to the events.
304
+
305
+ This requires makepy support for the COM object being created. If
306
+ this support does not exist it will be automatically generated by
307
+ this function. If the object does not support makepy, a TypeError
308
+ exception will be raised.
309
+
310
+ The result is a class instance that both represents the COM object
311
+ and handles events from the COM object.
312
+
313
+ It is important to note that the returned instance is not a direct
314
+ instance of the user_event_class, but an instance of a temporary
315
+ class object that derives from three classes:
316
+ * The makepy generated class for the COM object
317
+ * The makepy generated class for the COM events
318
+ * The user_event_class as passed to this function.
319
+
320
+ If this is not suitable, see the getevents function for an alternative
321
+ technique of handling events.
322
+
323
+ Object Lifetimes: Whenever the object returned from this function is
324
+ cleaned-up by Python, the events will be disconnected from
325
+ the COM object. This is almost always what should happen,
326
+ but see the documentation for getevents() for more details.
327
+
328
+ Example:
329
+
330
+ >>> class IEEvents:
331
+ ... def OnVisible(self, visible):
332
+ ... print("Visible changed:", visible)
333
+ ...
334
+ >>> ie = DispatchWithEvents("InternetExplorer.Application", IEEvents)
335
+ >>> ie.Visible = 1
336
+ Visible changed: 1
337
+ """
338
+ disp, disp_class, events_class = __get_disp_and_event_classes(clsid)
339
+ result_class = type(
340
+ "COMEventClass",
341
+ (disp_class, events_class, user_event_class),
342
+ {"__setattr__": _event_setattr_},
343
+ )
344
+ # This only calls the first base class __init__.
345
+ instance = result_class(disp._oleobj_)
346
+ events_class.__init__(instance, instance)
347
+ if hasattr(user_event_class, "__init__"):
348
+ user_event_class.__init__(instance)
349
+ return EventsProxy(instance)
350
+
351
+
352
+ def WithEvents(disp, user_event_class):
353
+ """Similar to DispatchWithEvents - except that the returned
354
+ object is *not* also usable as the original Dispatch object - that is
355
+ the returned object is not dispatchable.
356
+
357
+ The difference is best summarised by example.
358
+
359
+ >>> class IEEvents:
360
+ ... def OnVisible(self, visible):
361
+ ... print("Visible changed:", visible)
362
+ ...
363
+ >>> ie = Dispatch("InternetExplorer.Application")
364
+ >>> ie_events = WithEvents(ie, IEEvents)
365
+ >>> ie.Visible = 1
366
+ Visible changed: 1
367
+
368
+ Compare with the code sample for DispatchWithEvents, where you get a
369
+ single object that is both the interface and the event handler. Note that
370
+ the event handler instance will *not* be able to use 'self.' to refer to
371
+ IE's methods and properties.
372
+
373
+ This is mainly useful where using DispatchWithEvents causes
374
+ circular reference problems that the simple proxy doesn't deal with
375
+ """
376
+ disp, disp_class, events_class = __get_disp_and_event_classes(disp)
377
+ result_class = type(
378
+ "COMEventClass",
379
+ (events_class, user_event_class),
380
+ {},
381
+ )
382
+ # This only calls the first base class __init__.
383
+ instance = result_class(disp)
384
+ if hasattr(user_event_class, "__init__"):
385
+ user_event_class.__init__(instance)
386
+ return instance
387
+
388
+
389
+ def getevents(clsid):
390
+ """Determine the default outgoing interface for a class, given
391
+ either a clsid or progid. It returns a class - you can
392
+ conveniently derive your own handler from this class and implement
393
+ the appropriate methods.
394
+
395
+ This method relies on the classes produced by makepy. You must use
396
+ either makepy or the gencache module to ensure that the
397
+ appropriate support classes have been generated for the com server
398
+ that you will be handling events from.
399
+
400
+ Beware of COM circular references. When the Events class is connected
401
+ to the COM object, the COM object itself keeps a reference to the Python
402
+ events class. Thus, neither the Events instance or the COM object will
403
+ ever die by themselves. The 'close' method on the events instance
404
+ must be called to break this chain and allow standard Python collection
405
+ rules to manage object lifetimes. Note that DispatchWithEvents() does
406
+ work around this problem by the use of a proxy object, but if you use
407
+ the getevents() function yourself, you must make your own arrangements
408
+ to manage this circular reference issue.
409
+
410
+ Beware of creating Python circular references: this will happen if your
411
+ handler has a reference to an object that has a reference back to
412
+ the event source. Call the 'close' method to break the chain.
413
+
414
+ Example:
415
+
416
+ >>>win32com.client.gencache.EnsureModule('{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}',0,1,1)
417
+ <module 'win32com.gen_py.....
418
+ >>>
419
+ >>> class InternetExplorerEvents(win32com.client.getevents("InternetExplorer.Application.1")):
420
+ ... def OnVisible(self, Visible):
421
+ ... print("Visibility changed: ", Visible)
422
+ ...
423
+ >>>
424
+ >>> ie=win32com.client.Dispatch("InternetExplorer.Application.1")
425
+ >>> events=InternetExplorerEvents(ie)
426
+ >>> ie.Visible=1
427
+ Visibility changed: 1
428
+ >>>
429
+ """
430
+
431
+ # find clsid given progid or clsid
432
+ clsid = str(pywintypes.IID(clsid))
433
+ # return default outgoing interface for that class
434
+ klass = gencache.GetClassForCLSID(clsid)
435
+ try:
436
+ return klass.default_source
437
+ except AttributeError:
438
+ # See if we have a coclass for the interfaces.
439
+ try:
440
+ return gencache.GetClassForCLSID(klass.coclass_clsid).default_source
441
+ except AttributeError:
442
+ return None
443
+
444
+
445
+ # A Record object, as used by the COM struct support
446
+ def Record(name, object):
447
+ """Creates a new record object, given the name of the record,
448
+ and an object from the same type library.
449
+
450
+ Example usage would be:
451
+ app = win32com.client.Dispatch("Some.Application")
452
+ point = win32com.client.Record("SomeAppPoint", app)
453
+ point.x = 0
454
+ point.y = 0
455
+ app.MoveTo(point)
456
+ """
457
+ # XXX - to do - probably should allow "object" to already be a module object.
458
+ from . import gencache
459
+
460
+ object = gencache.EnsureDispatch(object)
461
+ module = sys.modules[object.__class__.__module__]
462
+ # to allow us to work correctly with "demand generated" code,
463
+ # we must use the typelib CLSID to obtain the module
464
+ # (otherwise we get the sub-module for the object, which
465
+ # does not hold the records)
466
+ # thus, package may be module, or may be module's parent if demand generated.
467
+ package = gencache.GetModuleForTypelib(
468
+ module.CLSID, module.LCID, module.MajorVersion, module.MinorVersion
469
+ )
470
+ try:
471
+ struct_guid = package.RecordMap[name]
472
+ except KeyError:
473
+ raise ValueError(f"The structure '{name}' is not defined in module '{package}'")
474
+ return pythoncom.GetRecordFromGuids(
475
+ module.CLSID, module.MajorVersion, module.MinorVersion, module.LCID, struct_guid
476
+ )
477
+
478
+
479
+ # Registration function for com_record subclasses.
480
+ def register_record_class(cls):
481
+ """
482
+ Register a subclass of com_record to enable creation of the represented record objects.
483
+
484
+ A subclass of com_record requires the following class attributes to be instantiable:
485
+
486
+ TLBID : The GUID of the containing TypeLibrary as a string.
487
+ MJVER : The major version number of the TypeLibrary as an integer.
488
+ MNVER : The minor version number of the TypeLibrary as an integer.
489
+ LCID : The LCID of the TypeLibrary as an integer.
490
+ GUID : The GUID of the COM Record as a string.
491
+
492
+ with GUID strings in {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} notation.
493
+
494
+ To instantiate such a subclasses it has to be registered via this function.
495
+ """
496
+ if not issubclass(cls, pythoncom.com_record):
497
+ raise TypeError("Only subclasses of 'com_record' can be registered.")
498
+ try:
499
+ TLBID = cls.TLBID
500
+ MJVER = cls.MJVER
501
+ MNVER = cls.MNVER
502
+ LCID = cls.LCID
503
+ GUID = cls.GUID
504
+ except AttributeError as e:
505
+ raise AttributeError(f"Class {cls.__name__} cannot be instantiated.") from e
506
+ try:
507
+ _ = pythoncom.GetRecordFromGuids(TLBID, MJVER, MNVER, LCID, GUID)
508
+ except Exception as e:
509
+ raise TypeError(f"Class {cls.__name__} cannot be instantiated.") from e
510
+ # Since the class can be instantiated we know that it represents a valid COM Record
511
+ # in a properly registered TypeLibrary and that it has a 'GUID' class attribute.
512
+ if cls.GUID in pythoncom.RecordClasses:
513
+ raise ValueError(
514
+ f"Record class with same GUID {cls.GUID} "
515
+ f"is already registered with name '{pythoncom.RecordClasses[cls.GUID].__name__}'."
516
+ )
517
+ pythoncom.RecordClasses[cls.GUID] = cls
518
+
519
+
520
+ ############################################
521
+ # The base of all makepy generated classes
522
+ ############################################
523
+ class DispatchBaseClass:
524
+ def __init__(self, oobj=None):
525
+ if oobj is None:
526
+ oobj = pythoncom.new(self.CLSID)
527
+ elif isinstance(oobj, (DispatchBaseClass, _PyIDispatchType)):
528
+ try:
529
+ oobj = oobj._oleobj_ if isinstance(oobj, DispatchBaseClass) else oobj
530
+ oobj = oobj.QueryInterface(self.CLSID, pythoncom.IID_IDispatch)
531
+ except pythoncom.com_error as details:
532
+ import winerror
533
+
534
+ # Some stupid objects fail here, even tho it is _already_ IDispatch!!??
535
+ # Eg, Lotus notes.
536
+ # So just let it use the existing object if E_NOINTERFACE
537
+ if details.hresult != winerror.E_NOINTERFACE:
538
+ raise
539
+
540
+ self.__dict__["_oleobj_"] = oobj # so we don't call __setattr__
541
+
542
+ def __dir__(self):
543
+ attributes = chain(
544
+ self.__dict__,
545
+ dir(self.__class__),
546
+ self._prop_map_get_,
547
+ self._prop_map_put_,
548
+ )
549
+
550
+ try:
551
+ attributes = chain(attributes, [p.Name for p in self.Properties_])
552
+ except AttributeError:
553
+ pass
554
+ return list(set(attributes))
555
+
556
+ # Provide a prettier name than the CLSID
557
+ def __repr__(self):
558
+ # Need to get the docstring for the module for this class.
559
+ try:
560
+ mod_doc = sys.modules[self.__class__.__module__].__doc__
561
+ if mod_doc:
562
+ mod_name = "win32com.gen_py." + mod_doc
563
+ else:
564
+ mod_name = sys.modules[self.__class__.__module__].__name__
565
+ except KeyError:
566
+ mod_name = "win32com.gen_py.unknown"
567
+ return f"<{mod_name}.{self.__class__.__name__} instance at 0x{id(self)}>"
568
+
569
+ # Delegate comparison to the oleobjs, as they know how to do identity.
570
+ def __eq__(self, other):
571
+ other = getattr(other, "_oleobj_", other)
572
+ return self._oleobj_ == other
573
+
574
+ def __ne__(self, other):
575
+ other = getattr(other, "_oleobj_", other)
576
+ return self._oleobj_ != other
577
+
578
+ def _ApplyTypes_(self, dispid, wFlags, retType, argTypes, user, resultCLSID, *args):
579
+ return self._get_good_object_(
580
+ self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args),
581
+ user,
582
+ resultCLSID,
583
+ )
584
+
585
+ def __getattr__(self, attr):
586
+ args = self._prop_map_get_.get(attr)
587
+ if args is None:
588
+ raise AttributeError(f"'{self!r}' object has no attribute '{attr}'")
589
+ return self._ApplyTypes_(*args)
590
+
591
+ def __setattr__(self, attr, value):
592
+ if attr in self.__dict__:
593
+ self.__dict__[attr] = value
594
+ return
595
+ try:
596
+ args, defArgs = self._prop_map_put_[attr]
597
+ except KeyError:
598
+ raise AttributeError(f"'{self!r}' object has no attribute '{attr}'")
599
+ self._oleobj_.Invoke(*(args + (value,) + defArgs))
600
+
601
+ def _get_good_single_object_(self, obj, obUserName=None, resultCLSID=None):
602
+ return _get_good_single_object_(obj, obUserName, resultCLSID)
603
+
604
+ def _get_good_object_(self, obj, obUserName=None, resultCLSID=None):
605
+ return _get_good_object_(obj, obUserName, resultCLSID)
606
+
607
+
608
+ # XXX - These should be consolidated with dynamic.py versions.
609
+ def _get_good_single_object_(obj, obUserName=None, resultCLSID=None):
610
+ if isinstance(obj, _PyIDispatchType):
611
+ return Dispatch(obj, obUserName, resultCLSID)
612
+ return obj
613
+
614
+
615
+ def _get_good_object_(obj, obUserName=None, resultCLSID=None):
616
+ if obj is None:
617
+ return None
618
+ elif isinstance(obj, tuple):
619
+ obUserNameTuple = (obUserName,) * len(obj)
620
+ resultCLSIDTuple = (resultCLSID,) * len(obj)
621
+ return tuple(map(_get_good_object_, obj, obUserNameTuple, resultCLSIDTuple))
622
+ else:
623
+ return _get_good_single_object_(obj, obUserName, resultCLSID)
624
+
625
+
626
+ class CoClassBaseClass:
627
+ def __init__(self, oobj=None):
628
+ if oobj is None:
629
+ oobj = pythoncom.new(self.CLSID)
630
+ self.__dict__["_dispobj_"] = self.default_interface(oobj)
631
+
632
+ def __repr__(self):
633
+ return f"<win32com.gen_py.{__doc__}.{self.__class__.__name__}>"
634
+
635
+ def __getattr__(self, attr):
636
+ d = self.__dict__["_dispobj_"]
637
+ if d is not None:
638
+ return getattr(d, attr)
639
+ raise AttributeError(attr)
640
+
641
+ def __setattr__(self, attr, value):
642
+ if attr in self.__dict__:
643
+ self.__dict__[attr] = value
644
+ return
645
+ try:
646
+ d = self.__dict__["_dispobj_"]
647
+ if d is not None:
648
+ d.__setattr__(attr, value)
649
+ return
650
+ except AttributeError:
651
+ pass
652
+ self.__dict__[attr] = value
653
+
654
+ # Special methods don't use __getattr__ etc, so explicitly delegate here.
655
+ # Some wrapped objects might not have them, but that's OK - the attribute
656
+ # error can just bubble up.
657
+ # This was initially implemented to address #1699 which did cause a problem
658
+ # with bool() in #1753 because the code initially implemented __nonzero__
659
+ # instead of __bool__, which was pointed out in the conclusion of #1870.
660
+ def __call__(self, *args, **kwargs):
661
+ return self.__dict__["_dispobj_"](*args, **kwargs)
662
+
663
+ def __str__(self, *args):
664
+ return str(self.__dict__["_dispobj_"])
665
+
666
+ def __int__(self, *args):
667
+ return int(self.__dict__["_dispobj_"])
668
+
669
+ def __iter__(self):
670
+ return iter(self.__dict__["_dispobj_"])
671
+
672
+ def __len__(self):
673
+ return len(self.__dict__["_dispobj_"])
674
+
675
+ def __bool__(self):
676
+ return bool(self.__dict__["_dispobj_"])
677
+
678
+
679
+ # A very simple VARIANT class. Only to be used with poorly-implemented COM
680
+ # objects. If an object accepts an arg which is a simple "VARIANT", but still
681
+ # is very pickly about the actual variant type (eg, isn't happy with a VT_I4,
682
+ # which it would get from a Python integer), you can use this to force a
683
+ # particular VT.
684
+ class VARIANT:
685
+ def __init__(self, vt, value):
686
+ self.varianttype = vt
687
+ self._value = value
688
+
689
+ # 'value' is a property so when set by pythoncom it gets any magic wrapping
690
+ # which normally happens for result objects
691
+ def _get_value(self):
692
+ return self._value
693
+
694
+ def _set_value(self, newval):
695
+ self._value = _get_good_object_(newval)
696
+
697
+ def _del_value(self):
698
+ del self._value
699
+
700
+ value = property(_get_value, _set_value, _del_value)
701
+
702
+ def __repr__(self):
703
+ return f"win32com.client.VARIANT({self.varianttype!r}, {self._value!r})"
loan-advisor-agent/.venv/Lib/site-packages/win32com/client/build.py ADDED
@@ -0,0 +1,774 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Contains knowledge to build a COM object definition.
2
+
3
+ This module is used by both the @dynamic@ and @makepy@ modules to build
4
+ all knowledge of a COM object.
5
+
6
+ This module contains classes which contain the actual knowledge of the object.
7
+ This include parameter and return type information, the COM dispid and CLSID, etc.
8
+
9
+ Other modules may use this information to generate .py files, use the information
10
+ dynamically, or possibly even generate .html documentation for objects.
11
+ """
12
+
13
+ #
14
+ # NOTES: DispatchItem and MapEntry used by dynamic.py.
15
+ # the rest is used by makepy.py
16
+ #
17
+ # OleItem, DispatchItem, MapEntry, BuildCallList() is used by makepy
18
+
19
+ import builtins
20
+ import datetime
21
+ import string
22
+ from itertools import chain
23
+ from keyword import iskeyword
24
+
25
+ import pythoncom
26
+ import winerror
27
+ from pywintypes import TimeType
28
+
29
+ # It isn't really clear what the quoting rules are in a C/IDL string and
30
+ # literals like a quote char and backslashes makes life a little painful to
31
+ # always render the string perfectly - so just punt and fall-back to a repr()
32
+ _makeDocString = repr
33
+
34
+
35
+ class NotSupportedException(Exception):
36
+ pass # Raised when we can't support a param type.
37
+
38
+
39
+ DropIndirection = "DropIndirection"
40
+
41
+ NoTranslateTypes = [
42
+ pythoncom.VT_BOOL,
43
+ pythoncom.VT_CLSID,
44
+ pythoncom.VT_CY,
45
+ pythoncom.VT_DATE,
46
+ pythoncom.VT_DECIMAL,
47
+ pythoncom.VT_EMPTY,
48
+ pythoncom.VT_ERROR,
49
+ pythoncom.VT_FILETIME,
50
+ pythoncom.VT_HRESULT,
51
+ pythoncom.VT_I1,
52
+ pythoncom.VT_I2,
53
+ pythoncom.VT_I4,
54
+ pythoncom.VT_I8,
55
+ pythoncom.VT_INT,
56
+ pythoncom.VT_NULL,
57
+ pythoncom.VT_R4,
58
+ pythoncom.VT_R8,
59
+ pythoncom.VT_NULL,
60
+ pythoncom.VT_STREAM,
61
+ pythoncom.VT_UI1,
62
+ pythoncom.VT_UI2,
63
+ pythoncom.VT_UI4,
64
+ pythoncom.VT_UI8,
65
+ pythoncom.VT_UINT,
66
+ pythoncom.VT_VOID,
67
+ ]
68
+
69
+ NoTranslateMap = set(NoTranslateTypes)
70
+
71
+
72
+ class MapEntry:
73
+ "Simple holder for named attibutes - items in a map."
74
+
75
+ def __init__(
76
+ self,
77
+ desc_or_id,
78
+ names=None,
79
+ doc=None,
80
+ resultCLSID=pythoncom.IID_NULL,
81
+ resultDoc=None,
82
+ hidden=0,
83
+ ):
84
+ if isinstance(desc_or_id, int):
85
+ self.dispid = desc_or_id
86
+ self.desc = None
87
+ else:
88
+ self.dispid = desc_or_id[0]
89
+ self.desc = desc_or_id
90
+
91
+ self.names = names
92
+ self.doc = doc
93
+ self.resultCLSID = resultCLSID
94
+ self.resultDocumentation = resultDoc
95
+ self.wasProperty = (
96
+ 0 # Have I been transformed into a function so I can pass args?
97
+ )
98
+ self.hidden = hidden
99
+
100
+ def __repr__(self):
101
+ return (
102
+ "MapEntry(dispid={s.dispid}, desc={s.desc}, names={s.names}, doc={s.doc!r}, "
103
+ "resultCLSID={s.resultCLSID}, resultDocumentation={s.resultDocumentation}, "
104
+ "wasProperty={s.wasProperty}, hidden={s.hidden}"
105
+ ).format(s=self)
106
+
107
+ def GetResultCLSID(self):
108
+ rc = self.resultCLSID
109
+ if rc == pythoncom.IID_NULL:
110
+ return None
111
+ return rc
112
+
113
+ # Return a string, suitable for output - either "'{...}'" or "None"
114
+ def GetResultCLSIDStr(self):
115
+ rc = self.GetResultCLSID()
116
+ if rc is None:
117
+ return "None"
118
+ # Convert the IID object to a string in a string.
119
+ return f"'{rc}'"
120
+
121
+ def GetResultName(self):
122
+ if self.resultDocumentation is None:
123
+ return None
124
+ return self.resultDocumentation[0]
125
+
126
+
127
+ class OleItem:
128
+ typename = "OleItem"
129
+
130
+ def __init__(self, doc=None):
131
+ self.doc = doc
132
+ if self.doc:
133
+ self.python_name = MakePublicAttributeName(self.doc[0])
134
+ else:
135
+ self.python_name = None
136
+ self.bWritten = 0
137
+ self.bIsDispatch = 0
138
+ self.bIsSink = 0
139
+ self.clsid = None
140
+ self.co_class = None
141
+
142
+
143
+ class DispatchItem(OleItem):
144
+ typename = "DispatchItem"
145
+
146
+ def __init__(self, typeinfo=None, attr=None, doc=None, bForUser=1):
147
+ OleItem.__init__(self, doc)
148
+ self.propMap = {}
149
+ self.propMapGet = {}
150
+ self.propMapPut = {}
151
+ self.mapFuncs = {}
152
+ self.defaultDispatchName = None
153
+ self.hidden = 0
154
+
155
+ if typeinfo:
156
+ self.Build(typeinfo, attr, bForUser)
157
+
158
+ def _propMapPutCheck_(self, key, item):
159
+ ins, outs, opts = self.CountInOutOptArgs(item.desc[2])
160
+ if ins > 1: # if a Put property takes more than 1 arg:
161
+ if opts + 1 == ins or ins == item.desc[6] + 1:
162
+ newKey = "Set" + key
163
+ deleteExisting = 0 # This one is still OK
164
+ else:
165
+ deleteExisting = 1 # No good to us
166
+ if key in self.mapFuncs or key in self.propMapGet:
167
+ newKey = "Set" + key
168
+ else:
169
+ newKey = key
170
+ item.wasProperty = 1
171
+ self.mapFuncs[newKey] = item
172
+ if deleteExisting:
173
+ del self.propMapPut[key]
174
+
175
+ def _propMapGetCheck_(self, key, item):
176
+ ins, outs, opts = self.CountInOutOptArgs(item.desc[2])
177
+ if ins > 0: # if a Get property takes _any_ in args:
178
+ if item.desc[6] == ins or ins == opts:
179
+ newKey = "Get" + key
180
+ deleteExisting = 0 # This one is still OK
181
+ else:
182
+ deleteExisting = 1 # No good to us
183
+ if key in self.mapFuncs:
184
+ newKey = "Get" + key
185
+ else:
186
+ newKey = key
187
+ item.wasProperty = 1
188
+ self.mapFuncs[newKey] = item
189
+ if deleteExisting:
190
+ del self.propMapGet[key]
191
+
192
+ def _AddFunc_(self, typeinfo, fdesc, bForUser):
193
+ assert fdesc.desckind == pythoncom.DESCKIND_FUNCDESC
194
+ id = fdesc.memid
195
+ funcflags = fdesc.wFuncFlags
196
+ try:
197
+ names = typeinfo.GetNames(id)
198
+ name = names[0]
199
+ except pythoncom.ole_error:
200
+ name = ""
201
+ names = None
202
+
203
+ doc = None
204
+ try:
205
+ if bForUser:
206
+ doc = typeinfo.GetDocumentation(id)
207
+ except pythoncom.ole_error:
208
+ pass
209
+
210
+ if id == 0 and name:
211
+ self.defaultDispatchName = name
212
+
213
+ invkind = fdesc.invkind
214
+
215
+ # We need to translate any Alias', Enums, structs etc in result and args
216
+ typerepr, flag, defval = fdesc.rettype
217
+ # sys.stderr.write("%s result - %s -> " % (name, typerepr))
218
+ typerepr, resultCLSID, resultDoc = _ResolveType(typerepr, typeinfo)
219
+ # sys.stderr.write("%s\n" % (typerepr,))
220
+ fdesc.rettype = typerepr, flag, defval, resultCLSID
221
+ # Translate any Alias or Enums in argument list.
222
+ argList = []
223
+ for argDesc in fdesc.args:
224
+ typerepr, flag, defval = argDesc
225
+ # sys.stderr.write("%s arg - %s -> " % (name, typerepr))
226
+ arg_type, arg_clsid, arg_doc = _ResolveType(typerepr, typeinfo)
227
+ argDesc = arg_type, flag, defval, arg_clsid
228
+ # sys.stderr.write("%s\n" % (argDesc[0],))
229
+ argList.append(argDesc)
230
+ fdesc.args = tuple(argList)
231
+
232
+ hidden = (funcflags & pythoncom.FUNCFLAG_FHIDDEN) != 0
233
+ if invkind == pythoncom.INVOKE_PROPERTYGET:
234
+ map = self.propMapGet
235
+ # This is not the best solution, but I don't think there is
236
+ # one without specific "set" syntax.
237
+ # If there is a single PUT or PUTREF, it will function as a property.
238
+ # If there are both, then the PUT remains a property, and the PUTREF
239
+ # gets transformed into a function.
240
+ # (in vb, PUT=="obj=other_obj", PUTREF="set obj=other_obj
241
+ elif invkind in (pythoncom.INVOKE_PROPERTYPUT, pythoncom.INVOKE_PROPERTYPUTREF):
242
+ # Special case
243
+ existing = self.propMapPut.get(name, None)
244
+ if existing is not None:
245
+ if existing.desc[4] == pythoncom.INVOKE_PROPERTYPUT: # Keep this one
246
+ map = self.mapFuncs
247
+ name = "Set" + name
248
+ else: # Existing becomes a func.
249
+ existing.wasProperty = 1
250
+ self.mapFuncs["Set" + name] = existing
251
+ map = self.propMapPut # existing gets overwritten below.
252
+ else:
253
+ map = self.propMapPut # first time we've seen it.
254
+
255
+ elif invkind == pythoncom.INVOKE_FUNC:
256
+ map = self.mapFuncs
257
+ else:
258
+ map = None
259
+ if not map is None:
260
+ # if map.has_key(name):
261
+ # sys.stderr.write("Warning - overwriting existing method/attribute %s\n" % name)
262
+ map[name] = MapEntry(fdesc, names, doc, resultCLSID, resultDoc, hidden)
263
+ # any methods that can't be reached via DISPATCH we return None
264
+ # for, so dynamic dispatch doesn't see it.
265
+ if fdesc.funckind != pythoncom.FUNC_DISPATCH:
266
+ return None
267
+ return (name, map)
268
+ return None
269
+
270
+ def _AddVar_(self, typeinfo, vardesc, bForUser):
271
+ ### need pythoncom.VARFLAG_FRESTRICTED ...
272
+ ### then check it
273
+ assert vardesc.desckind == pythoncom.DESCKIND_VARDESC
274
+
275
+ if vardesc.varkind == pythoncom.VAR_DISPATCH:
276
+ id = vardesc.memid
277
+ names = typeinfo.GetNames(id)
278
+ # Translate any Alias or Enums in result.
279
+ typerepr, flags, defval = vardesc.elemdescVar
280
+ typerepr, resultCLSID, resultDoc = _ResolveType(typerepr, typeinfo)
281
+ vardesc.elemdescVar = typerepr, flags, defval
282
+ doc = None
283
+ try:
284
+ if bForUser:
285
+ doc = typeinfo.GetDocumentation(id)
286
+ except pythoncom.ole_error:
287
+ pass
288
+
289
+ # handle the enumerator specially
290
+ map = self.propMap
291
+ # Check if the element is hidden.
292
+ hidden = (vardesc.wVarFlags & 0x40) != 0 # VARFLAG_FHIDDEN
293
+ map[names[0]] = MapEntry(
294
+ vardesc, names, doc, resultCLSID, resultDoc, hidden
295
+ )
296
+ return (names[0], map)
297
+ else:
298
+ return None
299
+
300
+ def Build(self, typeinfo, attr, bForUser=1):
301
+ self.clsid = attr[0]
302
+ self.bIsDispatch = (attr.wTypeFlags & pythoncom.TYPEFLAG_FDISPATCHABLE) != 0
303
+ if typeinfo is None:
304
+ return
305
+ # Loop over all methods
306
+ for j in range(attr[6]):
307
+ fdesc = typeinfo.GetFuncDesc(j)
308
+ self._AddFunc_(typeinfo, fdesc, bForUser)
309
+
310
+ # Loop over all variables (ie, properties)
311
+ for j in range(attr[7]):
312
+ fdesc = typeinfo.GetVarDesc(j)
313
+ self._AddVar_(typeinfo, fdesc, bForUser)
314
+
315
+ # Now post-process the maps. For any "Get" or "Set" properties
316
+ # that have arguments, we must turn them into methods. If a method
317
+ # of the same name already exists, change the name.
318
+ for key, item in list(self.propMapGet.items()):
319
+ self._propMapGetCheck_(key, item)
320
+
321
+ for key, item in list(self.propMapPut.items()):
322
+ self._propMapPutCheck_(key, item)
323
+
324
+ def CountInOutOptArgs(self, argTuple):
325
+ "Return tuple counting in/outs/OPTS. Sum of result may not be len(argTuple), as some args may be in/out."
326
+ ins = out = opts = 0
327
+ for argCheck in argTuple:
328
+ inOut = argCheck[1]
329
+ if inOut == 0:
330
+ ins += 1
331
+ out += 1
332
+ else:
333
+ if inOut & pythoncom.PARAMFLAG_FIN:
334
+ ins += 1
335
+ if inOut & pythoncom.PARAMFLAG_FOPT:
336
+ opts += 1
337
+ if inOut & pythoncom.PARAMFLAG_FOUT:
338
+ out += 1
339
+ return ins, out, opts
340
+
341
+ def MakeFuncMethod(self, entry, name, bMakeClass=1):
342
+ # If we have a type description, and not varargs...
343
+ if entry.desc is not None and (len(entry.desc) < 6 or entry.desc[6] != -1):
344
+ return self.MakeDispatchFuncMethod(entry, name, bMakeClass)
345
+ else:
346
+ return self.MakeVarArgsFuncMethod(entry, name, bMakeClass)
347
+
348
+ def MakeDispatchFuncMethod(self, entry, name, bMakeClass=1):
349
+ fdesc = entry.desc
350
+ doc = entry.doc
351
+ names = entry.names
352
+ ret = []
353
+ if bMakeClass:
354
+ linePrefix = "\t"
355
+ defNamedOptArg = "defaultNamedOptArg"
356
+ defNamedNotOptArg = "defaultNamedNotOptArg"
357
+ defUnnamedArg = "defaultUnnamedArg"
358
+ else:
359
+ linePrefix = ""
360
+ defNamedOptArg = "pythoncom.Missing"
361
+ defNamedNotOptArg = "pythoncom.Missing"
362
+ defUnnamedArg = "pythoncom.Missing"
363
+ defOutArg = "pythoncom.Missing"
364
+ id = fdesc[0]
365
+
366
+ s = (
367
+ linePrefix
368
+ + "def "
369
+ + name
370
+ + "(self"
371
+ + BuildCallList(
372
+ fdesc,
373
+ names,
374
+ defNamedOptArg,
375
+ defNamedNotOptArg,
376
+ defUnnamedArg,
377
+ defOutArg,
378
+ )
379
+ + "):"
380
+ )
381
+ ret.append(s)
382
+ if doc and doc[1]:
383
+ ret.append(linePrefix + "\t" + _makeDocString(doc[1]))
384
+
385
+ resclsid = entry.GetResultCLSID()
386
+ if resclsid:
387
+ resclsid = "'%s'" % resclsid
388
+ else:
389
+ resclsid = "None"
390
+ # Strip the default values from the arg desc
391
+ retDesc = fdesc[8][:2]
392
+ argsDesc = tuple([what[:2] for what in fdesc[2]])
393
+ # The runtime translation of the return types is expensive, so when we know the
394
+ # return type of the function, there is no need to check the type at runtime.
395
+ # To qualify, this function must return a "simple" type, and have no byref args.
396
+ # Check if we have byrefs or anything in the args which mean we still need a translate.
397
+ param_flags = [what[1] for what in fdesc[2]]
398
+ bad_params = [
399
+ flag
400
+ for flag in param_flags
401
+ if flag & (pythoncom.PARAMFLAG_FOUT | pythoncom.PARAMFLAG_FRETVAL) != 0
402
+ ]
403
+ s = None
404
+ if len(bad_params) == 0 and len(retDesc) == 2 and retDesc[1] == 0:
405
+ rd = retDesc[0]
406
+ if rd in NoTranslateMap:
407
+ s = "{}\treturn self._oleobj_.InvokeTypes({}, LCID, {}, {}, {}{})".format(
408
+ linePrefix,
409
+ id,
410
+ fdesc[4],
411
+ retDesc,
412
+ argsDesc,
413
+ _BuildArgList(fdesc, names),
414
+ )
415
+ elif rd in [pythoncom.VT_DISPATCH, pythoncom.VT_UNKNOWN]:
416
+ s = "{}\tret = self._oleobj_.InvokeTypes({}, LCID, {}, {}, {!r}{})\n".format(
417
+ linePrefix,
418
+ id,
419
+ fdesc[4],
420
+ retDesc,
421
+ argsDesc,
422
+ _BuildArgList(fdesc, names),
423
+ )
424
+ s += f"{linePrefix}\tif ret is not None:\n"
425
+ if rd == pythoncom.VT_UNKNOWN:
426
+ s += "{}\t\t# See if this IUnknown is really an IDispatch\n".format(
427
+ linePrefix
428
+ )
429
+ s += f"{linePrefix}\t\ttry:\n"
430
+ s += "{}\t\t\tret = ret.QueryInterface(pythoncom.IID_IDispatch)\n".format(
431
+ linePrefix
432
+ )
433
+ s += f"{linePrefix}\t\texcept pythoncom.error:\n"
434
+ s += f"{linePrefix}\t\t\treturn ret\n"
435
+ s += f"{linePrefix}\t\tret = Dispatch(ret, {name!r}, {resclsid})\n"
436
+ s += f"{linePrefix}\treturn ret"
437
+ elif rd == pythoncom.VT_BSTR:
438
+ s = f"{linePrefix}\t# Result is a Unicode object\n"
439
+ s += "{}\treturn self._oleobj_.InvokeTypes({}, LCID, {}, {}, {!r}{})".format(
440
+ linePrefix,
441
+ id,
442
+ fdesc[4],
443
+ retDesc,
444
+ argsDesc,
445
+ _BuildArgList(fdesc, names),
446
+ )
447
+ # else s remains None
448
+ if s is None:
449
+ s = "{}\treturn self._ApplyTypes_({}, {}, {}, {}, {!r}, {}{})".format(
450
+ linePrefix,
451
+ id,
452
+ fdesc[4],
453
+ retDesc,
454
+ argsDesc,
455
+ name,
456
+ resclsid,
457
+ _BuildArgList(fdesc, names),
458
+ )
459
+
460
+ ret.append(s)
461
+ ret.append("")
462
+ return ret
463
+
464
+ def MakeVarArgsFuncMethod(self, entry, name, bMakeClass=1):
465
+ fdesc = entry.desc
466
+ names = entry.names
467
+ doc = entry.doc
468
+ ret = []
469
+ argPrefix = "self"
470
+ if bMakeClass:
471
+ linePrefix = "\t"
472
+ else:
473
+ linePrefix = ""
474
+ ret.append(linePrefix + "def " + name + "(" + argPrefix + ", *args):")
475
+ if doc and doc[1]:
476
+ ret.append(linePrefix + "\t" + _makeDocString(doc[1]))
477
+ if fdesc:
478
+ invoketype = fdesc[4]
479
+ else:
480
+ invoketype = pythoncom.DISPATCH_METHOD
481
+ s = linePrefix + "\treturn self._get_good_object_(self._oleobj_.Invoke(*(("
482
+ ret.append(
483
+ s + str(entry.dispid) + ",0,%d,1)+args)),'%s')" % (invoketype, names[0])
484
+ )
485
+ ret.append("")
486
+ return ret
487
+
488
+
489
+ # Note - "DispatchItem" poorly named - need a new intermediate class.
490
+ class VTableItem(DispatchItem):
491
+ def Build(self, typeinfo, attr, bForUser=1):
492
+ DispatchItem.Build(self, typeinfo, attr, bForUser)
493
+ assert typeinfo is not None, "Can't build vtables without type info!"
494
+
495
+ meth_list = sorted(
496
+ chain(
497
+ self.mapFuncs.values(),
498
+ self.propMapGet.values(),
499
+ self.propMapPut.values(),
500
+ ),
501
+ key=lambda m: m.desc[7],
502
+ )
503
+
504
+ # Now turn this list into the run-time representation
505
+ # (ready for immediate use or writing to gencache)
506
+ self.vtableFuncs = [
507
+ (entry.names, entry.dispid, entry.desc) for entry in meth_list
508
+ ]
509
+
510
+
511
+ # A Lazy dispatch item - builds an item on request using info from
512
+ # an ITypeComp. The dynamic module makes the called to build each item,
513
+ # and also holds the references to the typeinfo and typecomp.
514
+ class LazyDispatchItem(DispatchItem):
515
+ typename = "LazyDispatchItem"
516
+
517
+ def __init__(self, attr, doc):
518
+ self.clsid = attr[0]
519
+ DispatchItem.__init__(self, None, attr, doc, 0)
520
+
521
+
522
+ typeSubstMap = {
523
+ pythoncom.VT_INT: pythoncom.VT_I4,
524
+ pythoncom.VT_UINT: pythoncom.VT_UI4,
525
+ pythoncom.VT_HRESULT: pythoncom.VT_I4,
526
+ }
527
+
528
+
529
+ def _ResolveType(typerepr, itypeinfo):
530
+ # Resolve VT_USERDEFINED (often aliases or typed IDispatches)
531
+
532
+ if isinstance(typerepr, tuple):
533
+ indir_vt, subrepr = typerepr
534
+ if indir_vt == pythoncom.VT_PTR:
535
+ # If it is a VT_PTR to a VT_USERDEFINED that is an IDispatch/IUnknown,
536
+ # then it resolves to simply the object.
537
+ # Otherwise, it becomes a ByRef of the resolved type
538
+ # We need to drop an indirection level on pointer to user defined interfaces.
539
+ # eg, (VT_PTR, (VT_USERDEFINED, somehandle)) needs to become VT_DISPATCH
540
+ # only when "somehandle" is an object.
541
+ # but (VT_PTR, (VT_USERDEFINED, otherhandle)) doesn't get the indirection dropped.
542
+ was_user = (
543
+ isinstance(subrepr, tuple) and subrepr[0] == pythoncom.VT_USERDEFINED
544
+ )
545
+ subrepr, sub_clsid, sub_doc = _ResolveType(subrepr, itypeinfo)
546
+ if was_user and subrepr in [
547
+ pythoncom.VT_DISPATCH,
548
+ pythoncom.VT_UNKNOWN,
549
+ ]:
550
+ # Drop the VT_PTR indirection
551
+ return subrepr, sub_clsid, sub_doc
552
+ # Change PTR indirection to byref
553
+ return subrepr | pythoncom.VT_BYREF, sub_clsid, sub_doc
554
+ if indir_vt == pythoncom.VT_SAFEARRAY:
555
+ # resolve the array element, and convert to VT_ARRAY
556
+ subrepr, sub_clsid, sub_doc = _ResolveType(subrepr, itypeinfo)
557
+ return pythoncom.VT_ARRAY | subrepr, sub_clsid, sub_doc
558
+ if indir_vt == pythoncom.VT_CARRAY: # runtime has no support for this yet.
559
+ # resolve the array element, and convert to VT_CARRAY
560
+ # sheesh - return _something_
561
+ return pythoncom.VT_CARRAY, None, None
562
+ if indir_vt == pythoncom.VT_USERDEFINED:
563
+ try:
564
+ resultTypeInfo = itypeinfo.GetRefTypeInfo(subrepr)
565
+ except pythoncom.com_error as details:
566
+ if details.hresult in [
567
+ winerror.TYPE_E_CANTLOADLIBRARY,
568
+ winerror.TYPE_E_LIBNOTREGISTERED,
569
+ ]:
570
+ # an unregistered interface
571
+ return pythoncom.VT_UNKNOWN, None, None
572
+ raise
573
+
574
+ resultAttr = resultTypeInfo.GetTypeAttr()
575
+ typeKind = resultAttr.typekind
576
+ if typeKind == pythoncom.TKIND_ALIAS:
577
+ tdesc = resultAttr.tdescAlias
578
+ return _ResolveType(tdesc, resultTypeInfo)
579
+ elif typeKind in [pythoncom.TKIND_ENUM, pythoncom.TKIND_MODULE]:
580
+ # For now, assume Long
581
+ return pythoncom.VT_I4, None, None
582
+
583
+ elif typeKind == pythoncom.TKIND_DISPATCH:
584
+ clsid = resultTypeInfo.GetTypeAttr()[0]
585
+ retdoc = resultTypeInfo.GetDocumentation(-1)
586
+ return pythoncom.VT_DISPATCH, clsid, retdoc
587
+
588
+ elif typeKind in [pythoncom.TKIND_INTERFACE, pythoncom.TKIND_COCLASS]:
589
+ # XXX - should probably get default interface for CO_CLASS???
590
+ clsid = resultTypeInfo.GetTypeAttr()[0]
591
+ retdoc = resultTypeInfo.GetDocumentation(-1)
592
+ return pythoncom.VT_UNKNOWN, clsid, retdoc
593
+
594
+ elif typeKind == pythoncom.TKIND_RECORD:
595
+ return pythoncom.VT_RECORD, None, None
596
+ raise NotSupportedException("Can not resolve alias or user-defined type")
597
+ return typeSubstMap.get(typerepr, typerepr), None, None
598
+
599
+
600
+ def _BuildArgList(fdesc, names):
601
+ "Builds list of args to the underlying Invoke method."
602
+ # Word has TypeInfo for Insert() method, but says "no args"
603
+ numArgs = max(fdesc[6], len(fdesc[2]))
604
+ names = list(names)
605
+ while None in names:
606
+ i = names.index(None)
607
+ names[i] = "arg%d" % (i,)
608
+ # We've seen 'source safe' libraries offer the name of 'ret' params in
609
+ # 'names' - although we can't reproduce this, it would be insane to offer
610
+ # more args than we have arg infos for - hence the upper limit on names...
611
+ names = list(map(MakePublicAttributeName, names[1 : (numArgs + 1)]))
612
+ name_num = 0
613
+ while len(names) < numArgs:
614
+ names.append("arg%d" % (len(names),))
615
+ # As per BuildCallList(), avoid huge lines.
616
+ # Hack a "\n" at the end of every 5th name
617
+ for i in range(0, len(names), 5):
618
+ names[i] += "\n\t\t\t"
619
+ return "," + ", ".join(names)
620
+
621
+
622
+ valid_identifier_chars = string.ascii_letters + string.digits + "_"
623
+
624
+
625
+ def demunge_leading_underscores(className):
626
+ i = 0
627
+ while className[i] == "_":
628
+ i += 1
629
+ assert i >= 2, "Should only be here with names starting with '__'"
630
+ return className[i - 1 :] + className[: i - 1]
631
+
632
+
633
+ # Given a "public name" (eg, the name of a class, function, etc)
634
+ # make sure it is a legal (and reasonable!) Python name.
635
+ def MakePublicAttributeName(className, is_global=False):
636
+ # Given a class attribute that needs to be public, convert it to a
637
+ # reasonable name.
638
+ # Also need to be careful that the munging doesn't
639
+ # create duplicates - eg, just removing a leading "_" is likely to cause
640
+ # a clash.
641
+ # if is_global is True, then the name is a global variable that may
642
+ # overwrite a builtin - eg, "None"
643
+ if className[:2] == "__":
644
+ return demunge_leading_underscores(className)
645
+ elif className == "None":
646
+ # assign to None is evil (and SyntaxError in 2.4, even though
647
+ # iskeyword says False there) - note that if it was a global
648
+ # it would get picked up below
649
+ className = "NONE"
650
+ elif iskeyword(className):
651
+ # most keywords are lower case (except True, False, etc)
652
+ ret = className.capitalize()
653
+ # but those which aren't get forced upper.
654
+ if ret == className:
655
+ ret = ret.upper()
656
+ return ret
657
+ elif is_global and hasattr(builtins, className):
658
+ # builtins may be mixed case. If capitalizing it doesn't change it,
659
+ # force to all uppercase (eg, "None", "True" become "NONE", "TRUE"
660
+ ret = className.capitalize()
661
+ if ret == className: # didn't change - force all uppercase.
662
+ ret = ret.upper()
663
+ return ret
664
+ elif className.isidentifier():
665
+ # some COM objects have identifiers with national characters
666
+ return className
667
+ # Strip non printable chars
668
+ return "".join([char for char in className if char in valid_identifier_chars])
669
+
670
+
671
+ # Given a default value passed by a type library, return a string with
672
+ # an appropriate repr() for the type.
673
+ # Takes a raw ELEMDESC and returns a repr string, or None
674
+ # (NOTE: The string itself may be '"None"', which is valid, and different to None.
675
+ # XXX - To do: Dates are probably screwed, but can they come in?
676
+ def MakeDefaultArgRepr(defArgVal):
677
+ try:
678
+ inOut = defArgVal[1]
679
+ except IndexError:
680
+ # something strange - assume is in param.
681
+ inOut = pythoncom.PARAMFLAG_FIN
682
+
683
+ if inOut & pythoncom.PARAMFLAG_FHASDEFAULT:
684
+ # times need special handling...
685
+ val = defArgVal[2]
686
+ if isinstance(val, datetime.datetime):
687
+ # VARIANT <-> SYSTEMTIME conversions always lose any sub-second
688
+ # resolution, so just use a 'timetuple' here.
689
+ return repr(tuple(val.utctimetuple()))
690
+ if isinstance(val, TimeType):
691
+ # must be the 'old' pywintypes time object...
692
+ year = val.year
693
+ month = val.month
694
+ day = val.day
695
+ hour = val.hour
696
+ minute = val.minute
697
+ second = val.second
698
+ msec = val.msec
699
+ return (
700
+ "pywintypes.Time((%(year)d, %(month)d, %(day)d, %(hour)d, %(minute)d, %(second)d,0,0,0,%(msec)d))"
701
+ % locals()
702
+ )
703
+ return repr(val)
704
+ return None
705
+
706
+
707
+ def BuildCallList(
708
+ fdesc,
709
+ names,
710
+ defNamedOptArg,
711
+ defNamedNotOptArg,
712
+ defUnnamedArg,
713
+ defOutArg,
714
+ is_comment=False,
715
+ ):
716
+ "Builds a Python declaration for a method."
717
+ # Names[0] is the func name - param names are from 1.
718
+ numArgs = len(fdesc[2])
719
+ numOptArgs = fdesc[6]
720
+ strval = ""
721
+ if numOptArgs == -1: # Special value that says "var args after here"
722
+ firstOptArg = numArgs
723
+ numArgs -= 1
724
+ else:
725
+ firstOptArg = numArgs - numOptArgs
726
+ for arg in range(numArgs):
727
+ try:
728
+ argName = names[arg + 1]
729
+ namedArg = argName is not None
730
+ except IndexError:
731
+ namedArg = 0
732
+ if not namedArg:
733
+ argName = "arg%d" % (arg)
734
+ thisdesc = fdesc[2][arg]
735
+ # See if the IDL specified a default value
736
+ defArgVal = MakeDefaultArgRepr(thisdesc)
737
+ if defArgVal is None:
738
+ # Out params always get their special default
739
+ if (
740
+ thisdesc[1] & (pythoncom.PARAMFLAG_FOUT | pythoncom.PARAMFLAG_FIN)
741
+ == pythoncom.PARAMFLAG_FOUT
742
+ ):
743
+ defArgVal = defOutArg
744
+ else:
745
+ # Unnamed arg - always allow default values.
746
+ if namedArg:
747
+ # Is a named argument
748
+ if arg >= firstOptArg:
749
+ defArgVal = defNamedOptArg
750
+ else:
751
+ defArgVal = defNamedNotOptArg
752
+ else:
753
+ defArgVal = defUnnamedArg
754
+
755
+ argName = MakePublicAttributeName(argName)
756
+ # keep 5 args per line
757
+ # This may still fail if the arg names are insane, but that seems
758
+ # unlikely. See also _BuildArgList()
759
+ if (arg + 1) % 5 == 0:
760
+ strval += "\n"
761
+ if is_comment:
762
+ strval += "#"
763
+ strval += "\t\t\t"
764
+ strval += ", " + argName
765
+ if defArgVal:
766
+ strval += "=" + defArgVal
767
+ if numOptArgs == -1:
768
+ strval += ", *" + names[-1]
769
+
770
+ return strval
771
+
772
+
773
+ if __name__ == "__main__":
774
+ print("Use 'makepy.py' to generate Python code - this module is just a helper")
loan-advisor-agent/.venv/Lib/site-packages/win32com/client/combrowse.py ADDED
@@ -0,0 +1,605 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A utility for browsing COM objects.
2
+
3
+ Usage:
4
+
5
+ Command Prompt
6
+
7
+ Use the command *"python.exe combrowse.py"*. This will display
8
+ display a fairly small, modal dialog.
9
+
10
+ Pythonwin
11
+
12
+ Use the "Run Script" menu item, and this will create the browser in an
13
+ MDI window. This window can be fully resized.
14
+
15
+ Details
16
+
17
+ This module allows browsing of registered Type Libraries, COM categories,
18
+ and running COM objects. The display is similar to the Pythonwin object
19
+ browser, and displays the objects in a hierarchical window.
20
+
21
+ Note that this module requires the win32ui (ie, Pythonwin) distribution to
22
+ work.
23
+
24
+ """
25
+
26
+ import sys
27
+
28
+ import pythoncom
29
+ import pywintypes
30
+ import win32api
31
+ import win32con
32
+ import win32ui
33
+ from pywin.tools import browser
34
+ from win32com.client import util
35
+
36
+
37
+ class HLIRoot(browser.HLIPythonObject):
38
+ def __init__(self, title):
39
+ super().__init__(name=title)
40
+
41
+ def GetSubList(self):
42
+ return [
43
+ HLIHeadingCategory(),
44
+ HLI_IEnumMoniker(
45
+ pythoncom.GetRunningObjectTable().EnumRunning(), "Running Objects"
46
+ ),
47
+ HLIHeadingRegisterdTypeLibs(),
48
+ ]
49
+
50
+ def __lt__(self, other):
51
+ return self.name < other.name
52
+
53
+
54
+ class HLICOM(browser.HLIPythonObject):
55
+ def GetText(self):
56
+ return self.name
57
+
58
+ def CalculateIsExpandable(self):
59
+ return 1
60
+
61
+
62
+ class HLICLSID(HLICOM):
63
+ def __init__(self, myobject, name=None):
64
+ if isinstance(myobject, str):
65
+ myobject = pywintypes.IID(myobject)
66
+ if name is None:
67
+ try:
68
+ name = pythoncom.ProgIDFromCLSID(myobject)
69
+ except pythoncom.com_error:
70
+ name = str(myobject)
71
+ name = "IID: " + name
72
+ HLICOM.__init__(self, myobject, name)
73
+
74
+ def CalculateIsExpandable(self):
75
+ return 0
76
+
77
+ def GetSubList(self):
78
+ return []
79
+
80
+
81
+ class HLI_Interface(HLICOM):
82
+ pass
83
+
84
+
85
+ class HLI_Enum(HLI_Interface):
86
+ def GetBitmapColumn(self):
87
+ return 0 # Always a folder.
88
+
89
+ def CalculateIsExpandable(self):
90
+ if self.myobject is not None:
91
+ rc = len(self.myobject.Next(1)) > 0
92
+ self.myobject.Reset()
93
+ else:
94
+ rc = 0
95
+ return rc
96
+
97
+
98
+ class HLI_IEnumMoniker(HLI_Enum):
99
+ def GetSubList(self):
100
+ ctx = pythoncom.CreateBindCtx()
101
+ ret = []
102
+ for mon in util.Enumerator(self.myobject):
103
+ ret.append(HLI_IMoniker(mon, mon.GetDisplayName(ctx, None)))
104
+ return ret
105
+
106
+
107
+ class HLI_IMoniker(HLI_Interface):
108
+ def GetSubList(self):
109
+ ret = []
110
+ ret.append(browser.MakeHLI(self.myobject.Hash(), "Hash Value"))
111
+ subenum = self.myobject.Enum(1)
112
+ ret.append(HLI_IEnumMoniker(subenum, "Sub Monikers"))
113
+ return ret
114
+
115
+
116
+ class HLIHeadingCategory(HLICOM):
117
+ "A tree heading for registered categories"
118
+
119
+ def GetText(self):
120
+ return "Registered Categories"
121
+
122
+ def GetSubList(self):
123
+ catinf = pythoncom.CoCreateInstance(
124
+ pythoncom.CLSID_StdComponentCategoriesMgr,
125
+ None,
126
+ pythoncom.CLSCTX_INPROC,
127
+ pythoncom.IID_ICatInformation,
128
+ )
129
+ enum = util.Enumerator(catinf.EnumCategories())
130
+ ret = []
131
+ try:
132
+ for catid, lcid, desc in enum:
133
+ ret.append(HLICategory((catid, lcid, desc)))
134
+ except pythoncom.com_error:
135
+ # Registered categories occasionally seem to give spurious errors.
136
+ pass # Use what we already have.
137
+ return ret
138
+
139
+
140
+ class HLICategory(HLICOM):
141
+ "An actual Registered Category"
142
+
143
+ def GetText(self):
144
+ desc = self.myobject[2]
145
+ if not desc:
146
+ desc = "(unnamed category)"
147
+ return desc
148
+
149
+ def GetSubList(self):
150
+ win32ui.DoWaitCursor(1)
151
+ catid, lcid, desc = self.myobject
152
+ catinf = pythoncom.CoCreateInstance(
153
+ pythoncom.CLSID_StdComponentCategoriesMgr,
154
+ None,
155
+ pythoncom.CLSCTX_INPROC,
156
+ pythoncom.IID_ICatInformation,
157
+ )
158
+ ret = []
159
+ for clsid in util.Enumerator(catinf.EnumClassesOfCategories((catid,), ())):
160
+ ret.append(HLICLSID(clsid))
161
+ win32ui.DoWaitCursor(0)
162
+
163
+ return ret
164
+
165
+
166
+ class HLIHelpFile(HLICOM):
167
+ def CalculateIsExpandable(self):
168
+ return 0
169
+
170
+ def GetText(self):
171
+ import os
172
+
173
+ fname, ctx = self.myobject
174
+ base = os.path.split(fname)[1]
175
+ return "Help reference in %s" % (base)
176
+
177
+ def TakeDefaultAction(self):
178
+ fname, ctx = self.myobject
179
+ if ctx:
180
+ cmd = win32con.HELP_CONTEXT
181
+ else:
182
+ cmd = win32con.HELP_FINDER
183
+ win32api.WinHelp(win32ui.GetMainFrame().GetSafeHwnd(), fname, cmd, ctx)
184
+
185
+ def GetBitmapColumn(self):
186
+ return 6
187
+
188
+
189
+ class HLIRegisteredTypeLibrary(HLICOM):
190
+ def GetSubList(self):
191
+ import os
192
+
193
+ clsidstr, versionStr = self.myobject
194
+ collected = []
195
+ helpPath = ""
196
+ key = win32api.RegOpenKey(
197
+ win32con.HKEY_CLASSES_ROOT, f"TypeLib\\{clsidstr}\\{versionStr}"
198
+ )
199
+ win32ui.DoWaitCursor(1)
200
+ try:
201
+ num = 0
202
+ while 1:
203
+ try:
204
+ subKey = win32api.RegEnumKey(key, num)
205
+ except win32api.error:
206
+ break
207
+ hSubKey = win32api.RegOpenKey(key, subKey)
208
+ try:
209
+ value, typ = win32api.RegQueryValueEx(hSubKey, None)
210
+ if typ == win32con.REG_EXPAND_SZ:
211
+ value = win32api.ExpandEnvironmentStrings(value)
212
+ except win32api.error:
213
+ value = ""
214
+ if subKey == "HELPDIR":
215
+ helpPath = value
216
+ elif subKey == "Flags":
217
+ flags = value
218
+ else:
219
+ try:
220
+ lcid = int(subKey)
221
+ lcidkey = win32api.RegOpenKey(key, subKey)
222
+ # Enumerate the platforms
223
+ lcidnum = 0
224
+ while 1:
225
+ try:
226
+ platform = win32api.RegEnumKey(lcidkey, lcidnum)
227
+ except win32api.error:
228
+ break
229
+ try:
230
+ hplatform = win32api.RegOpenKey(lcidkey, platform)
231
+ fname, typ = win32api.RegQueryValueEx(hplatform, None)
232
+ if typ == win32con.REG_EXPAND_SZ:
233
+ fname = win32api.ExpandEnvironmentStrings(fname)
234
+ except win32api.error:
235
+ fname = ""
236
+ collected.append((lcid, platform, fname))
237
+ lcidnum += 1
238
+ win32api.RegCloseKey(lcidkey)
239
+ except ValueError:
240
+ pass
241
+ num += 1
242
+ finally:
243
+ win32ui.DoWaitCursor(0)
244
+ win32api.RegCloseKey(key)
245
+ # Now, loop over my collected objects, adding a TypeLib and a HelpFile
246
+ ret = []
247
+ # if helpPath: ret.append(browser.MakeHLI(helpPath, "Help Path"))
248
+ ret.append(HLICLSID(clsidstr))
249
+ for lcid, platform, fname in collected:
250
+ extraDescs = []
251
+ if platform != "win32":
252
+ extraDescs.append(platform)
253
+ if lcid:
254
+ extraDescs.append("locale=%s" % lcid)
255
+ extraDesc = ""
256
+ if extraDescs:
257
+ extraDesc = " (%s)" % ", ".join(extraDescs)
258
+ ret.append(HLITypeLib(fname, "Type Library" + extraDesc))
259
+ ret.sort()
260
+ return ret
261
+
262
+
263
+ class HLITypeLibEntry(HLICOM):
264
+ def GetText(self):
265
+ tlb, index = self.myobject
266
+ name, doc, ctx, helpFile = tlb.GetDocumentation(index)
267
+ typedesc = HLITypeKinds.get(tlb.GetTypeInfoType(index), (None, "Unknown!"))[1]
268
+ return name + " - " + typedesc
269
+
270
+ def GetSubList(self):
271
+ tlb, index = self.myobject
272
+ name, doc, ctx, helpFile = tlb.GetDocumentation(index)
273
+ ret = []
274
+ if doc:
275
+ ret.append(browser.HLIDocString(doc, "Doc"))
276
+ if helpFile:
277
+ ret.append(HLIHelpFile((helpFile, ctx)))
278
+ return ret
279
+
280
+
281
+ class HLICoClass(HLITypeLibEntry):
282
+ def GetSubList(self):
283
+ ret = HLITypeLibEntry.GetSubList(self)
284
+ tlb, index = self.myobject
285
+ typeinfo = tlb.GetTypeInfo(index)
286
+ attr = typeinfo.GetTypeAttr()
287
+ for j in range(attr[8]):
288
+ flags = typeinfo.GetImplTypeFlags(j)
289
+ refType = typeinfo.GetRefTypeInfo(typeinfo.GetRefTypeOfImplType(j))
290
+ refAttr = refType.GetTypeAttr()
291
+ ret.append(
292
+ browser.MakeHLI(refAttr[0], "Name=%s, Flags = %d" % (refAttr[0], flags))
293
+ )
294
+ return ret
295
+
296
+
297
+ class HLITypeLibMethod(HLITypeLibEntry):
298
+ def __init__(self, ob, name=None):
299
+ self.entry_type = "Method"
300
+ HLITypeLibEntry.__init__(self, ob, name)
301
+
302
+ def GetSubList(self):
303
+ ret = HLITypeLibEntry.GetSubList(self)
304
+ tlb, index = self.myobject
305
+ typeinfo = tlb.GetTypeInfo(index)
306
+ attr = typeinfo.GetTypeAttr()
307
+ for i in range(attr[7]):
308
+ ret.append(HLITypeLibProperty((typeinfo, i)))
309
+ for i in range(attr[6]):
310
+ ret.append(HLITypeLibFunction((typeinfo, i)))
311
+ return ret
312
+
313
+
314
+ class HLITypeLibEnum(HLITypeLibEntry):
315
+ def __init__(self, myitem):
316
+ typelib, index = myitem
317
+ typeinfo = typelib.GetTypeInfo(index)
318
+ self.id = typeinfo.GetVarDesc(index)[0]
319
+ name = typeinfo.GetNames(self.id)[0]
320
+ HLITypeLibEntry.__init__(self, myitem, name)
321
+
322
+ def GetText(self):
323
+ return self.name + " - Enum/Module"
324
+
325
+ def GetSubList(self):
326
+ ret = []
327
+ typelib, index = self.myobject
328
+ typeinfo = typelib.GetTypeInfo(index)
329
+ attr = typeinfo.GetTypeAttr()
330
+ for j in range(attr[7]):
331
+ vdesc = typeinfo.GetVarDesc(j)
332
+ name = typeinfo.GetNames(vdesc[0])[0]
333
+ ret.append(browser.MakeHLI(vdesc[1], name))
334
+ return ret
335
+
336
+
337
+ class HLITypeLibProperty(HLICOM):
338
+ def __init__(self, myitem):
339
+ typeinfo, index = myitem
340
+ self.id = typeinfo.GetVarDesc(index)[0]
341
+ name = typeinfo.GetNames(self.id)[0]
342
+ HLICOM.__init__(self, myitem, name)
343
+
344
+ def GetText(self):
345
+ return self.name + " - Property"
346
+
347
+ def GetSubList(self):
348
+ ret = []
349
+ typeinfo, index = self.myobject
350
+ names = typeinfo.GetNames(self.id)
351
+ if len(names) > 1:
352
+ ret.append(browser.MakeHLI(names[1:], "Named Params"))
353
+ vd = typeinfo.GetVarDesc(index)
354
+ ret.append(browser.MakeHLI(self.id, "Dispatch ID"))
355
+ ret.append(browser.MakeHLI(vd[1], "Value"))
356
+ ret.append(browser.MakeHLI(vd[2], "Elem Desc"))
357
+ ret.append(browser.MakeHLI(vd[3], "Var Flags"))
358
+ ret.append(browser.MakeHLI(vd[4], "Var Kind"))
359
+ return ret
360
+
361
+
362
+ class HLITypeLibFunction(HLICOM):
363
+ funckinds = {
364
+ pythoncom.FUNC_VIRTUAL: "Virtual",
365
+ pythoncom.FUNC_PUREVIRTUAL: "Pure Virtual",
366
+ pythoncom.FUNC_STATIC: "Static",
367
+ pythoncom.FUNC_DISPATCH: "Dispatch",
368
+ }
369
+ invokekinds = {
370
+ pythoncom.INVOKE_FUNC: "Function",
371
+ pythoncom.INVOKE_PROPERTYGET: "Property Get",
372
+ pythoncom.INVOKE_PROPERTYPUT: "Property Put",
373
+ pythoncom.INVOKE_PROPERTYPUTREF: "Property Put by reference",
374
+ }
375
+ funcflags = [
376
+ (pythoncom.FUNCFLAG_FRESTRICTED, "Restricted"),
377
+ (pythoncom.FUNCFLAG_FSOURCE, "Source"),
378
+ (pythoncom.FUNCFLAG_FBINDABLE, "Bindable"),
379
+ (pythoncom.FUNCFLAG_FREQUESTEDIT, "Request Edit"),
380
+ (pythoncom.FUNCFLAG_FDISPLAYBIND, "Display Bind"),
381
+ (pythoncom.FUNCFLAG_FDEFAULTBIND, "Default Bind"),
382
+ (pythoncom.FUNCFLAG_FHIDDEN, "Hidden"),
383
+ (pythoncom.FUNCFLAG_FUSESGETLASTERROR, "Uses GetLastError"),
384
+ ]
385
+
386
+ vartypes = {
387
+ pythoncom.VT_EMPTY: "Empty",
388
+ pythoncom.VT_NULL: "NULL",
389
+ pythoncom.VT_I2: "Integer 2",
390
+ pythoncom.VT_I4: "Integer 4",
391
+ pythoncom.VT_R4: "Real 4",
392
+ pythoncom.VT_R8: "Real 8",
393
+ pythoncom.VT_CY: "CY",
394
+ pythoncom.VT_DATE: "Date",
395
+ pythoncom.VT_BSTR: "String",
396
+ pythoncom.VT_DISPATCH: "IDispatch",
397
+ pythoncom.VT_ERROR: "Error",
398
+ pythoncom.VT_BOOL: "BOOL",
399
+ pythoncom.VT_VARIANT: "Variant",
400
+ pythoncom.VT_UNKNOWN: "IUnknown",
401
+ pythoncom.VT_DECIMAL: "Decimal",
402
+ pythoncom.VT_I1: "Integer 1",
403
+ pythoncom.VT_UI1: "Unsigned integer 1",
404
+ pythoncom.VT_UI2: "Unsigned integer 2",
405
+ pythoncom.VT_UI4: "Unsigned integer 4",
406
+ pythoncom.VT_I8: "Integer 8",
407
+ pythoncom.VT_UI8: "Unsigned integer 8",
408
+ pythoncom.VT_INT: "Integer",
409
+ pythoncom.VT_UINT: "Unsigned integer",
410
+ pythoncom.VT_VOID: "Void",
411
+ pythoncom.VT_HRESULT: "HRESULT",
412
+ pythoncom.VT_PTR: "Pointer",
413
+ pythoncom.VT_SAFEARRAY: "SafeArray",
414
+ pythoncom.VT_CARRAY: "C Array",
415
+ pythoncom.VT_USERDEFINED: "User Defined",
416
+ pythoncom.VT_LPSTR: "Pointer to string",
417
+ pythoncom.VT_LPWSTR: "Pointer to Wide String",
418
+ pythoncom.VT_FILETIME: "File time",
419
+ pythoncom.VT_BLOB: "Blob",
420
+ pythoncom.VT_STREAM: "IStream",
421
+ pythoncom.VT_STORAGE: "IStorage",
422
+ pythoncom.VT_STORED_OBJECT: "Stored object",
423
+ pythoncom.VT_STREAMED_OBJECT: "Streamed object",
424
+ pythoncom.VT_BLOB_OBJECT: "Blob object",
425
+ pythoncom.VT_CF: "CF",
426
+ pythoncom.VT_CLSID: "CLSID",
427
+ }
428
+
429
+ type_flags = [
430
+ (pythoncom.VT_VECTOR, "Vector"),
431
+ (pythoncom.VT_ARRAY, "Array"),
432
+ (pythoncom.VT_BYREF, "ByRef"),
433
+ (pythoncom.VT_RESERVED, "Reserved"),
434
+ ]
435
+
436
+ def __init__(self, myitem):
437
+ typeinfo, index = myitem
438
+ self.id = typeinfo.GetFuncDesc(index)[0]
439
+ name = typeinfo.GetNames(self.id)[0]
440
+ HLICOM.__init__(self, myitem, name)
441
+
442
+ def GetText(self):
443
+ return self.name + " - Function"
444
+
445
+ def MakeReturnTypeName(self, typ):
446
+ justtyp = typ & pythoncom.VT_TYPEMASK
447
+ typname = self.vartypes.get(justtyp, "?Bad type?")
448
+ for flag, desc in self.type_flags:
449
+ if flag & typ:
450
+ typname = f"{desc}({typname})"
451
+ return typname
452
+
453
+ def MakeReturnType(self, returnTypeDesc):
454
+ if isinstance(returnTypeDesc, tuple):
455
+ first = returnTypeDesc[0]
456
+ result = self.MakeReturnType(first)
457
+ if first != pythoncom.VT_USERDEFINED:
458
+ result += " " + self.MakeReturnType(returnTypeDesc[1])
459
+ return result
460
+ else:
461
+ return self.MakeReturnTypeName(returnTypeDesc)
462
+
463
+ def GetSubList(self):
464
+ ret = []
465
+ typeinfo, index = self.myobject
466
+ names = typeinfo.GetNames(self.id)
467
+ ret.append(browser.MakeHLI(self.id, "Dispatch ID"))
468
+ if len(names) > 1:
469
+ ret.append(browser.MakeHLI(", ".join(names[1:]), "Named Params"))
470
+ fd = typeinfo.GetFuncDesc(index)
471
+ if fd[1]:
472
+ ret.append(browser.MakeHLI(fd[1], "Possible result values"))
473
+ if fd[8]:
474
+ typ, flags, default = fd[8]
475
+ val = self.MakeReturnType(typ)
476
+ if flags:
477
+ val += f" (Flags={flags}, default={default})"
478
+ ret.append(browser.MakeHLI(val, "Return Type"))
479
+
480
+ for argDesc in fd[2]:
481
+ typ, flags, default = argDesc
482
+ val = self.MakeReturnType(typ)
483
+ if flags:
484
+ val += f" (Flags={flags})"
485
+ if default is not None:
486
+ val += f" (Default={default})"
487
+ ret.append(browser.MakeHLI(val, "Argument"))
488
+
489
+ fkind = self.funckinds.get(fd[3], "Unknown")
490
+ ret.append(browser.MakeHLI(fkind, "Function Kind"))
491
+ ikind = self.invokekinds.get([fd[4]], "Unknown")
492
+ ret.append(browser.MakeHLI(ikind, "Invoke Kind"))
493
+ # 5 = call conv
494
+ # 5 = offset vtbl
495
+ ret.append(browser.MakeHLI(fd[6], "Number Optional Params"))
496
+ flagDescs = []
497
+ for flag, desc in self.funcflags:
498
+ if flag & fd[9]:
499
+ flagDescs.append(desc)
500
+ if flagDescs:
501
+ ret.append(browser.MakeHLI(", ".join(flagDescs), "Function Flags"))
502
+ return ret
503
+
504
+
505
+ HLITypeKinds = {
506
+ pythoncom.TKIND_ENUM: (HLITypeLibEnum, "Enumeration"),
507
+ pythoncom.TKIND_RECORD: (HLITypeLibEntry, "Record"),
508
+ pythoncom.TKIND_MODULE: (HLITypeLibEnum, "Module"),
509
+ pythoncom.TKIND_INTERFACE: (HLITypeLibMethod, "Interface"),
510
+ pythoncom.TKIND_DISPATCH: (HLITypeLibMethod, "Dispatch"),
511
+ pythoncom.TKIND_COCLASS: (HLICoClass, "CoClass"),
512
+ pythoncom.TKIND_ALIAS: (HLITypeLibEntry, "Alias"),
513
+ pythoncom.TKIND_UNION: (HLITypeLibEntry, "Union"),
514
+ }
515
+
516
+
517
+ class HLITypeLib(HLICOM):
518
+ def GetSubList(self):
519
+ ret = []
520
+ ret.append(browser.MakeHLI(self.myobject, "Filename"))
521
+ try:
522
+ tlb = pythoncom.LoadTypeLib(self.myobject)
523
+ except pythoncom.com_error:
524
+ return [browser.MakeHLI("%s can not be loaded" % self.myobject)]
525
+
526
+ for i in range(tlb.GetTypeInfoCount()):
527
+ try:
528
+ ret.append(HLITypeKinds[tlb.GetTypeInfoType(i)][0]((tlb, i)))
529
+ except pythoncom.com_error:
530
+ ret.append(browser.MakeHLI("The type info can not be loaded!"))
531
+ ret.sort()
532
+ return ret
533
+
534
+
535
+ class HLIHeadingRegisterdTypeLibs(HLICOM):
536
+ "A tree heading for registered type libraries"
537
+
538
+ def GetText(self):
539
+ return "Registered Type Libraries"
540
+
541
+ def GetSubList(self):
542
+ # Explicit lookup in the registry.
543
+ ret = []
544
+ key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "TypeLib")
545
+ win32ui.DoWaitCursor(1)
546
+ try:
547
+ num = 0
548
+ while 1:
549
+ try:
550
+ keyName = win32api.RegEnumKey(key, num)
551
+ except win32api.error:
552
+ break
553
+ # Enumerate all version info
554
+ subKey = win32api.RegOpenKey(key, keyName)
555
+ name = None
556
+ try:
557
+ subNum = 0
558
+ bestVersion = 0.0
559
+ while 1:
560
+ try:
561
+ versionStr = win32api.RegEnumKey(subKey, subNum)
562
+ except win32api.error:
563
+ break
564
+ try:
565
+ versionFlt = float(versionStr)
566
+ except ValueError:
567
+ versionFlt = 0 # ????
568
+ if versionFlt > bestVersion:
569
+ bestVersion = versionFlt
570
+ name = win32api.RegQueryValue(subKey, versionStr)
571
+ subNum += 1
572
+ finally:
573
+ win32api.RegCloseKey(subKey)
574
+ if name is not None:
575
+ ret.append(HLIRegisteredTypeLibrary((keyName, versionStr), name))
576
+ num += 1
577
+ finally:
578
+ win32api.RegCloseKey(key)
579
+ win32ui.DoWaitCursor(0)
580
+ ret.sort()
581
+ return ret
582
+
583
+
584
+ def main(modal=True, mdi=False):
585
+ root = HLIRoot("COM Browser")
586
+ if mdi and "pywin.framework.app" in sys.modules:
587
+ # do it in a MDI window
588
+ browser.MakeTemplate()
589
+ browser.template.OpenObject(root)
590
+ else:
591
+ dlg = browser.dynamic_browser(root)
592
+ if modal:
593
+ dlg.DoModal()
594
+ else:
595
+ dlg.CreateWindow()
596
+ dlg.ShowWindow()
597
+
598
+
599
+ if __name__ == "__main__":
600
+ main(modal=win32api.GetConsoleTitle())
601
+
602
+ ni = pythoncom._GetInterfaceCount()
603
+ ng = pythoncom._GetGatewayCount()
604
+ if ni or ng:
605
+ print("Warning - exiting with %d/%d objects alive" % (ni, ng))
loan-advisor-agent/.venv/Lib/site-packages/win32com/client/connect.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utilities for working with Connections"""
2
+
3
+ import pythoncom
4
+ import win32com.server.policy
5
+ import win32com.server.util
6
+
7
+
8
+ class SimpleConnection:
9
+ "A simple, single connection object"
10
+
11
+ def __init__(self, coInstance=None, eventInstance=None, eventCLSID=None, debug=0):
12
+ self.cp = None
13
+ self.cookie = None
14
+ self.debug = debug
15
+ if not coInstance is None:
16
+ self.Connect(coInstance, eventInstance, eventCLSID)
17
+
18
+ def __del__(self):
19
+ try:
20
+ self.Disconnect()
21
+ except pythoncom.error:
22
+ # Ignore disconnection as we are torn down.
23
+ pass
24
+
25
+ def _wrap(self, obj):
26
+ useDispatcher = (
27
+ win32com.server.policy.DispatcherWin32trace if self.debug else None
28
+ )
29
+ return win32com.server.util.wrap(obj, useDispatcher=useDispatcher)
30
+
31
+ def Connect(self, coInstance, eventInstance, eventCLSID=None):
32
+ try:
33
+ oleobj = coInstance._oleobj_
34
+ except AttributeError:
35
+ oleobj = coInstance
36
+ cpc = oleobj.QueryInterface(pythoncom.IID_IConnectionPointContainer)
37
+ if eventCLSID is None:
38
+ eventCLSID = eventInstance.CLSID
39
+ comEventInstance = self._wrap(eventInstance)
40
+ self.cp = cpc.FindConnectionPoint(eventCLSID)
41
+ self.cookie = self.cp.Advise(comEventInstance)
42
+
43
+ def Disconnect(self):
44
+ if not self.cp is None:
45
+ if self.cookie:
46
+ self.cp.Unadvise(self.cookie)
47
+ self.cookie = None
48
+ self.cp = None
loan-advisor-agent/.venv/Lib/site-packages/win32com/client/dynamic.py ADDED
@@ -0,0 +1,699 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Support for dynamic COM client support.
2
+
3
+ Introduction
4
+ Dynamic COM client support is the ability to use a COM server without
5
+ prior knowledge of the server. This can be used to talk to almost all
6
+ COM servers, including much of MS Office.
7
+
8
+ In general, you should not use this module directly - see below.
9
+
10
+ Example
11
+ >>> import win32com.client
12
+ >>> xl = win32com.client.Dispatch("Excel.Application")
13
+ # The line above invokes the functionality of this class.
14
+ # xl is now an object we can use to talk to Excel.
15
+ >>> xl.Visible = 1 # The Excel window becomes visible.
16
+
17
+ """
18
+
19
+ import traceback
20
+ from itertools import chain
21
+ from types import MethodType
22
+
23
+ import pythoncom # Needed as code we eval() references it.
24
+ import win32com.client
25
+ import winerror
26
+ from pywintypes import IIDType
27
+
28
+ from . import build
29
+
30
+ debugging = 0 # General debugging
31
+ debugging_attr = 0 # Debugging dynamic attribute lookups.
32
+
33
+ LCID = 0x0
34
+
35
+ # These errors generally mean the property or method exists,
36
+ # but can't be used in this context - eg, property instead of a method, etc.
37
+ # Used to determine if we have a real error or not.
38
+ ERRORS_BAD_CONTEXT = [
39
+ winerror.DISP_E_MEMBERNOTFOUND,
40
+ winerror.DISP_E_BADPARAMCOUNT,
41
+ winerror.DISP_E_PARAMNOTOPTIONAL,
42
+ winerror.DISP_E_TYPEMISMATCH,
43
+ winerror.E_INVALIDARG,
44
+ ]
45
+
46
+ ALL_INVOKE_TYPES = [
47
+ pythoncom.INVOKE_PROPERTYGET,
48
+ pythoncom.INVOKE_PROPERTYPUT,
49
+ pythoncom.INVOKE_PROPERTYPUTREF,
50
+ pythoncom.INVOKE_FUNC,
51
+ ]
52
+
53
+
54
+ def debug_print(*args):
55
+ if debugging:
56
+ for arg in args:
57
+ print(arg, end=" ")
58
+ print()
59
+
60
+
61
+ def debug_attr_print(*args):
62
+ if debugging_attr:
63
+ for arg in args:
64
+ print(arg, end=" ")
65
+ print()
66
+
67
+
68
+ # get the type objects for IDispatch and IUnknown
69
+ PyIDispatchType = pythoncom.TypeIIDs[pythoncom.IID_IDispatch]
70
+ PyIUnknownType = pythoncom.TypeIIDs[pythoncom.IID_IUnknown]
71
+
72
+ _GoodDispatchTypes = (str, IIDType)
73
+
74
+
75
+ def _GetGoodDispatch(IDispatch, clsctx=pythoncom.CLSCTX_SERVER):
76
+ # quick return for most common case
77
+ if isinstance(IDispatch, PyIDispatchType):
78
+ return IDispatch
79
+ if isinstance(IDispatch, _GoodDispatchTypes):
80
+ try:
81
+ IDispatch = pythoncom.connect(IDispatch)
82
+ except pythoncom.ole_error:
83
+ IDispatch = pythoncom.CoCreateInstance(
84
+ IDispatch, None, clsctx, pythoncom.IID_IDispatch
85
+ )
86
+ else:
87
+ # may already be a wrapped class.
88
+ IDispatch = getattr(IDispatch, "_oleobj_", IDispatch)
89
+ return IDispatch
90
+
91
+
92
+ def _GetGoodDispatchAndUserName(IDispatch, userName, clsctx):
93
+ # Get a dispatch object, and a 'user name' (ie, the name as
94
+ # displayed to the user in repr() etc.
95
+ if userName is None:
96
+ if isinstance(IDispatch, str):
97
+ userName = IDispatch
98
+ ## ??? else userName remains None ???
99
+ else:
100
+ userName = str(userName)
101
+ return (_GetGoodDispatch(IDispatch, clsctx), userName)
102
+
103
+
104
+ def _GetDescInvokeType(entry, invoke_type):
105
+ # determine the wFlags argument passed as input to IDispatch::Invoke
106
+ # Only ever called by __getattr__ and __setattr__ from dynamic objects!
107
+ # * `entry` is a MapEntry with whatever typeinfo we have about the property we are getting/setting.
108
+ # * `invoke_type` is either INVOKE_PROPERTYGET | INVOKE_PROPERTYSET and really just
109
+ # means "called by __getattr__" or "called by __setattr__"
110
+ if not entry or not entry.desc:
111
+ return invoke_type
112
+
113
+ if entry.desc.desckind == pythoncom.DESCKIND_VARDESC:
114
+ return invoke_type
115
+
116
+ # So it's a FUNCDESC - just use what it specifies.
117
+ return entry.desc.invkind
118
+
119
+
120
+ def Dispatch(
121
+ IDispatch,
122
+ userName=None,
123
+ createClass=None,
124
+ typeinfo=None,
125
+ clsctx=pythoncom.CLSCTX_SERVER,
126
+ ):
127
+ IDispatch, userName = _GetGoodDispatchAndUserName(IDispatch, userName, clsctx)
128
+ if createClass is None:
129
+ createClass = CDispatch
130
+ lazydata = None
131
+ try:
132
+ if typeinfo is None:
133
+ typeinfo = IDispatch.GetTypeInfo()
134
+ if typeinfo is not None:
135
+ try:
136
+ # try for a typecomp
137
+ typecomp = typeinfo.GetTypeComp()
138
+ lazydata = typeinfo, typecomp
139
+ except pythoncom.com_error:
140
+ pass
141
+ except pythoncom.com_error:
142
+ typeinfo = None
143
+ olerepr = MakeOleRepr(IDispatch, typeinfo, lazydata)
144
+ return createClass(IDispatch, olerepr, userName, lazydata=lazydata)
145
+
146
+
147
+ def MakeOleRepr(IDispatch, typeinfo, typecomp):
148
+ olerepr = None
149
+ if typeinfo is not None:
150
+ try:
151
+ attr = typeinfo.GetTypeAttr()
152
+ # If the type info is a special DUAL interface, magically turn it into
153
+ # a DISPATCH typeinfo.
154
+ if (
155
+ attr[5] == pythoncom.TKIND_INTERFACE
156
+ and attr[11] & pythoncom.TYPEFLAG_FDUAL
157
+ ):
158
+ # Get corresponding Disp interface;
159
+ # -1 is a special value which does this for us.
160
+ href = typeinfo.GetRefTypeOfImplType(-1)
161
+ typeinfo = typeinfo.GetRefTypeInfo(href)
162
+ attr = typeinfo.GetTypeAttr()
163
+ if typecomp is None:
164
+ olerepr = build.DispatchItem(typeinfo, attr, None, 0)
165
+ else:
166
+ olerepr = build.LazyDispatchItem(attr, None)
167
+ except pythoncom.ole_error:
168
+ pass
169
+ if olerepr is None:
170
+ olerepr = build.DispatchItem()
171
+ return olerepr
172
+
173
+
174
+ def DumbDispatch(
175
+ IDispatch,
176
+ userName=None,
177
+ createClass=None,
178
+ clsctx=pythoncom.CLSCTX_SERVER,
179
+ ):
180
+ "Dispatch with no type info"
181
+ IDispatch, userName = _GetGoodDispatchAndUserName(IDispatch, userName, clsctx)
182
+ if createClass is None:
183
+ createClass = CDispatch
184
+ return createClass(IDispatch, build.DispatchItem(), userName)
185
+
186
+
187
+ class CDispatch:
188
+ def __init__(self, IDispatch, olerepr, userName=None, lazydata=None):
189
+ if userName is None:
190
+ userName = "<unknown>"
191
+ self.__dict__["_oleobj_"] = IDispatch
192
+ self.__dict__["_username_"] = userName
193
+ self.__dict__["_olerepr_"] = olerepr
194
+ self.__dict__["_mapCachedItems_"] = {}
195
+ self.__dict__["_builtMethods_"] = {}
196
+ self.__dict__["_enum_"] = None
197
+ self.__dict__["_unicode_to_string_"] = None
198
+ self.__dict__["_lazydata_"] = lazydata
199
+
200
+ def __call__(self, *args):
201
+ "Provide 'default dispatch' COM functionality - allow instance to be called"
202
+ if self._olerepr_.defaultDispatchName:
203
+ invkind, dispid = self._find_dispatch_type_(
204
+ self._olerepr_.defaultDispatchName
205
+ )
206
+ else:
207
+ invkind, dispid = (
208
+ pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET,
209
+ pythoncom.DISPID_VALUE,
210
+ )
211
+ if invkind is not None:
212
+ allArgs = (dispid, LCID, invkind, 1) + args
213
+ return self._get_good_object_(
214
+ self._oleobj_.Invoke(*allArgs), self._olerepr_.defaultDispatchName, None
215
+ )
216
+ raise TypeError("This dispatch object does not define a default method")
217
+
218
+ def __bool__(self):
219
+ return True # ie "if object:" should always be "true" - without this, __len__ is tried.
220
+ # _Possibly_ want to defer to __len__ if available, but I'm not sure this is
221
+ # desirable???
222
+
223
+ def __repr__(self):
224
+ return "<COMObject %s>" % (self._username_)
225
+
226
+ def __str__(self):
227
+ # __str__ is used when the user does "print(object)", so we gracefully
228
+ # fall back to the __repr__ if the object has no default method.
229
+ try:
230
+ return str(self.__call__())
231
+ except pythoncom.com_error as details:
232
+ if details.hresult not in ERRORS_BAD_CONTEXT:
233
+ raise
234
+ return self.__repr__()
235
+
236
+ def __dir__(self):
237
+ attributes = chain(self.__dict__, dir(self.__class__), self._dir_ole_())
238
+ try:
239
+ attributes = chain(attributes, [p.Name for p in self.Properties_])
240
+ except AttributeError:
241
+ pass
242
+ return list(set(attributes))
243
+
244
+ def _dir_ole_(self):
245
+ items_dict = {}
246
+ for iTI in range(0, self._oleobj_.GetTypeInfoCount()):
247
+ typeInfo = self._oleobj_.GetTypeInfo(iTI)
248
+ self._UpdateWithITypeInfo_(items_dict, typeInfo)
249
+ return list(items_dict)
250
+
251
+ def _UpdateWithITypeInfo_(self, items_dict, typeInfo):
252
+ typeInfos = [typeInfo]
253
+ # suppress IDispatch and IUnknown methods
254
+ inspectedIIDs = {pythoncom.IID_IDispatch: None}
255
+
256
+ while len(typeInfos) > 0:
257
+ typeInfo = typeInfos.pop()
258
+ typeAttr = typeInfo.GetTypeAttr()
259
+
260
+ if typeAttr.iid not in inspectedIIDs:
261
+ inspectedIIDs[typeAttr.iid] = None
262
+ for iFun in range(0, typeAttr.cFuncs):
263
+ funDesc = typeInfo.GetFuncDesc(iFun)
264
+ funName = typeInfo.GetNames(funDesc.memid)[0]
265
+ if funName not in items_dict:
266
+ items_dict[funName] = None
267
+
268
+ # Inspect the type info of all implemented types
269
+ # E.g. IShellDispatch5 implements IShellDispatch4 which implements IShellDispatch3 ...
270
+ for iImplType in range(0, typeAttr.cImplTypes):
271
+ iRefType = typeInfo.GetRefTypeOfImplType(iImplType)
272
+ refTypeInfo = typeInfo.GetRefTypeInfo(iRefType)
273
+ typeInfos.append(refTypeInfo)
274
+
275
+ # Delegate comparison to the oleobjs, as they know how to do identity.
276
+ def __eq__(self, other):
277
+ other = getattr(other, "_oleobj_", other)
278
+ return self._oleobj_ == other
279
+
280
+ def __ne__(self, other):
281
+ other = getattr(other, "_oleobj_", other)
282
+ return self._oleobj_ != other
283
+
284
+ def __int__(self):
285
+ return int(self.__call__())
286
+
287
+ def __len__(self):
288
+ invkind, dispid = self._find_dispatch_type_("Count")
289
+ if invkind:
290
+ return self._oleobj_.Invoke(dispid, LCID, invkind, 1)
291
+ raise TypeError("This dispatch object does not define a Count method")
292
+
293
+ def _NewEnum(self):
294
+ try:
295
+ invkind = pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET
296
+ enum = self._oleobj_.InvokeTypes(
297
+ pythoncom.DISPID_NEWENUM, LCID, invkind, (13, 10), ()
298
+ )
299
+ except pythoncom.com_error:
300
+ return None # no enumerator for this object.
301
+ from . import util
302
+
303
+ return util.WrapEnum(enum, None)
304
+
305
+ def __getitem__(self, index): # syver modified
306
+ # Improved __getitem__ courtesy Syver Enstad
307
+ # Must check _NewEnum before Item, to ensure b/w compat.
308
+ if isinstance(index, int):
309
+ if self.__dict__["_enum_"] is None:
310
+ self.__dict__["_enum_"] = self._NewEnum()
311
+ if self.__dict__["_enum_"] is not None:
312
+ return self._get_good_object_(self._enum_.__getitem__(index))
313
+ # See if we have an "Item" method/property we can use (goes hand in hand with Count() above!)
314
+ invkind, dispid = self._find_dispatch_type_("Item")
315
+ if invkind is not None:
316
+ return self._get_good_object_(
317
+ self._oleobj_.Invoke(dispid, LCID, invkind, 1, index)
318
+ )
319
+ raise TypeError("This object does not support enumeration")
320
+
321
+ def __setitem__(self, index, *args):
322
+ # XXX - todo - We should support calling Item() here too!
323
+ # print("__setitem__ with", index, args)
324
+ if self._olerepr_.defaultDispatchName:
325
+ invkind, dispid = self._find_dispatch_type_(
326
+ self._olerepr_.defaultDispatchName
327
+ )
328
+ else:
329
+ invkind, dispid = (
330
+ pythoncom.DISPATCH_PROPERTYPUT | pythoncom.DISPATCH_PROPERTYPUTREF,
331
+ pythoncom.DISPID_VALUE,
332
+ )
333
+ if invkind is not None:
334
+ allArgs = (dispid, LCID, invkind, 0, index) + args
335
+ return self._get_good_object_(
336
+ self._oleobj_.Invoke(*allArgs), self._olerepr_.defaultDispatchName, None
337
+ )
338
+ raise TypeError("This dispatch object does not define a default method")
339
+
340
+ def _find_dispatch_type_(self, methodName):
341
+ if methodName in self._olerepr_.mapFuncs:
342
+ item = self._olerepr_.mapFuncs[methodName]
343
+ return item.desc[4], item.dispid
344
+
345
+ if methodName in self._olerepr_.propMapGet:
346
+ item = self._olerepr_.propMapGet[methodName]
347
+ return item.desc[4], item.dispid
348
+
349
+ try:
350
+ dispid = self._oleobj_.GetIDsOfNames(0, methodName)
351
+ except: ### what error?
352
+ return None, None
353
+ return pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET, dispid
354
+
355
+ def _ApplyTypes_(self, dispid, wFlags, retType, argTypes, user, resultCLSID, *args):
356
+ result = self._oleobj_.InvokeTypes(
357
+ *(dispid, LCID, wFlags, retType, argTypes) + args
358
+ )
359
+ return self._get_good_object_(result, user, resultCLSID)
360
+
361
+ def _wrap_dispatch_(
362
+ self,
363
+ ob,
364
+ userName=None,
365
+ returnCLSID=None,
366
+ ):
367
+ # Given a dispatch object, wrap it in a class
368
+ return Dispatch(ob, userName)
369
+
370
+ def _get_good_single_object_(self, ob, userName=None, ReturnCLSID=None):
371
+ if isinstance(ob, PyIDispatchType):
372
+ # make a new instance of (probably this) class.
373
+ return self._wrap_dispatch_(ob, userName, ReturnCLSID)
374
+ if isinstance(ob, PyIUnknownType):
375
+ try:
376
+ ob = ob.QueryInterface(pythoncom.IID_IDispatch)
377
+ except pythoncom.com_error:
378
+ # It is an IUnknown, but not an IDispatch, so just let it through.
379
+ return ob
380
+ return self._wrap_dispatch_(ob, userName, ReturnCLSID)
381
+ return ob
382
+
383
+ def _get_good_object_(self, ob, userName=None, ReturnCLSID=None):
384
+ """Given an object (usually the retval from a method), make it a good object to return.
385
+ Basically checks if it is a COM object, and wraps it up.
386
+ Also handles the fact that a retval may be a tuple of retvals"""
387
+ if ob is None: # Quick exit!
388
+ return None
389
+ elif isinstance(ob, tuple):
390
+ return tuple(
391
+ map(
392
+ lambda o,
393
+ s=self,
394
+ oun=userName,
395
+ rc=ReturnCLSID: s._get_good_single_object_(o, oun, rc),
396
+ ob,
397
+ )
398
+ )
399
+ else:
400
+ return self._get_good_single_object_(ob)
401
+
402
+ def _make_method_(self, name):
403
+ "Make a method object - Assumes in olerepr funcmap"
404
+ methodName = build.MakePublicAttributeName(name) # translate keywords etc.
405
+ methodCodeList = self._olerepr_.MakeFuncMethod(
406
+ self._olerepr_.mapFuncs[name], methodName, 0
407
+ )
408
+ methodCode = "\n".join(methodCodeList)
409
+ try:
410
+ # print(f"Method code for {self._username_} is:\n", methodCode)
411
+ # self._print_details_()
412
+ codeObject = compile(methodCode, "<COMObject %s>" % self._username_, "exec")
413
+ # Exec the code object
414
+ tempNameSpace = {}
415
+ # "Dispatch" in the exec'd code is win32com.client.Dispatch, not ours.
416
+ globNameSpace = globals().copy()
417
+ globNameSpace["Dispatch"] = win32com.client.Dispatch
418
+ exec(
419
+ codeObject, globNameSpace, tempNameSpace
420
+ ) # self.__dict__, self.__dict__
421
+ name = methodName
422
+ # Save the function in map.
423
+ fn = self._builtMethods_[name] = tempNameSpace[name]
424
+ return MethodType(fn, self)
425
+ except:
426
+ debug_print("Error building OLE definition for code ", methodCode)
427
+ traceback.print_exc()
428
+ return None
429
+
430
+ def _Release_(self):
431
+ """Cleanup object - like a close - to force cleanup when you don't
432
+ want to rely on Python's reference counting."""
433
+ for childCont in self._mapCachedItems_.values():
434
+ childCont._Release_()
435
+ self._mapCachedItems_ = {}
436
+ if self._oleobj_:
437
+ self._oleobj_.Release()
438
+ self.__dict__["_oleobj_"] = None
439
+ if self._olerepr_:
440
+ self.__dict__["_olerepr_"] = None
441
+ self._enum_ = None
442
+
443
+ def _proc_(self, name, *args):
444
+ """Call the named method as a procedure, rather than function.
445
+ Mainly used by Word.Basic, which whinges about such things."""
446
+ try:
447
+ item = self._olerepr_.mapFuncs[name]
448
+ dispId = item.dispid
449
+ return self._get_good_object_(
450
+ self._oleobj_.Invoke(*(dispId, LCID, item.desc[4], 0) + (args))
451
+ )
452
+ except KeyError:
453
+ raise AttributeError(name)
454
+
455
+ def _print_details_(self):
456
+ "Debug routine - dumps what it knows about an object."
457
+ print("AxDispatch container", self._username_)
458
+ try:
459
+ print("Methods:")
460
+ for method in self._olerepr_.mapFuncs:
461
+ print("\t", method)
462
+ print("Props:")
463
+ for prop, entry in self._olerepr_.propMap.items():
464
+ print(f"\t{prop} = 0x{entry.dispid:x} - {entry!r}")
465
+ print("Get Props:")
466
+ for prop, entry in self._olerepr_.propMapGet.items():
467
+ print(f"\t{prop} = 0x{entry.dispid:x} - {entry!r}")
468
+ print("Put Props:")
469
+ for prop, entry in self._olerepr_.propMapPut.items():
470
+ print(f"\t{prop} = 0x{entry.dispid:x} - {entry!r}")
471
+ except:
472
+ traceback.print_exc()
473
+
474
+ def __LazyMap__(self, attr):
475
+ try:
476
+ if self._LazyAddAttr_(attr):
477
+ debug_attr_print(
478
+ f"{self._username_}.__LazyMap__({attr}) added something"
479
+ )
480
+ return 1
481
+ except AttributeError:
482
+ return 0
483
+
484
+ # Using the typecomp, lazily create a new attribute definition.
485
+ def _LazyAddAttr_(self, attr):
486
+ if self._lazydata_ is None:
487
+ return 0
488
+ res = 0
489
+ typeinfo, typecomp = self._lazydata_
490
+ olerepr = self._olerepr_
491
+ # We need to explicitly check each invoke type individually - simply
492
+ # specifying '0' will bind to "any member", which may not be the one
493
+ # we are actually after (ie, we may be after prop_get, but returned
494
+ # the info for the prop_put.)
495
+ for i in ALL_INVOKE_TYPES:
496
+ try:
497
+ x, t = typecomp.Bind(attr, i)
498
+ # Support 'Get' and 'Set' properties - see
499
+ # bug 1587023
500
+ if x == 0 and attr[:3] in ("Set", "Get"):
501
+ x, t = typecomp.Bind(attr[3:], i)
502
+ if x == pythoncom.DESCKIND_FUNCDESC: # it's a FUNCDESC
503
+ r = olerepr._AddFunc_(typeinfo, t, 0)
504
+ elif x == pythoncom.DESCKIND_VARDESC: # it's a VARDESC
505
+ r = olerepr._AddVar_(typeinfo, t, 0)
506
+ else: # not found or TYPEDESC/IMPLICITAPP
507
+ r = None
508
+ if not r is None:
509
+ key, map = r[0], r[1]
510
+ item = map[key]
511
+ if map == olerepr.propMapPut:
512
+ olerepr._propMapPutCheck_(key, item)
513
+ elif map == olerepr.propMapGet:
514
+ olerepr._propMapGetCheck_(key, item)
515
+ res = 1
516
+ except:
517
+ pass
518
+ return res
519
+
520
+ def _FlagAsMethod(self, *methodNames):
521
+ """Flag these attribute names as being methods.
522
+ Some objects do not correctly differentiate methods and
523
+ properties, leading to problems when calling these methods.
524
+
525
+ Specifically, trying to say: ob.SomeFunc()
526
+ may yield an exception "None object is not callable"
527
+ In this case, an attempt to fetch the *property* has worked
528
+ and returned None, rather than indicating it is really a method.
529
+ Calling: ob._FlagAsMethod("SomeFunc")
530
+ should then allow this to work.
531
+ """
532
+ for name in methodNames:
533
+ details = build.MapEntry(self.__AttrToID__(name), (name,))
534
+ self._olerepr_.mapFuncs[name] = details
535
+
536
+ def __AttrToID__(self, attr):
537
+ debug_attr_print(
538
+ "Calling GetIDsOfNames for property {} in Dispatch container {}".format(
539
+ attr, self._username_
540
+ )
541
+ )
542
+ return self._oleobj_.GetIDsOfNames(0, attr)
543
+
544
+ def __getattr__(self, attr):
545
+ if attr == "__iter__":
546
+ # We can't handle this as a normal method, as if the attribute
547
+ # exists, then it must return an iterable object.
548
+ try:
549
+ invkind = pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET
550
+ enum = self._oleobj_.InvokeTypes(
551
+ pythoncom.DISPID_NEWENUM, LCID, invkind, (13, 10), ()
552
+ )
553
+ except pythoncom.com_error:
554
+ raise AttributeError("This object can not function as an iterator")
555
+
556
+ # We must return a callable object.
557
+ class Factory:
558
+ def __init__(self, ob):
559
+ self.ob = ob
560
+
561
+ def __call__(self):
562
+ import win32com.client.util
563
+
564
+ return win32com.client.util.Iterator(self.ob)
565
+
566
+ return Factory(enum)
567
+
568
+ if attr.startswith("_") and attr.endswith("_"): # Fast-track.
569
+ raise AttributeError(attr)
570
+ # If a known method, create new instance and return.
571
+ try:
572
+ return MethodType(self._builtMethods_[attr], self)
573
+ except KeyError:
574
+ pass
575
+ # XXX - Note that we current are case sensitive in the method.
576
+ # debug_attr_print("GetAttr called for %s on DispatchContainer %s" % (attr,self._username_))
577
+ # First check if it is in the method map. Note that an actual method
578
+ # must not yet exist, (otherwise we would not be here). This
579
+ # means we create the actual method object - which also means
580
+ # this code will never be asked for that method name again.
581
+ if attr in self._olerepr_.mapFuncs:
582
+ return self._make_method_(attr)
583
+
584
+ # Delegate to property maps/cached items
585
+ retEntry = None
586
+ if self._olerepr_ and self._oleobj_:
587
+ # first check general property map, then specific "put" map.
588
+ retEntry = self._olerepr_.propMap.get(attr)
589
+ if retEntry is None:
590
+ retEntry = self._olerepr_.propMapGet.get(attr)
591
+ # Not found so far - See what COM says.
592
+ if retEntry is None:
593
+ try:
594
+ if self.__LazyMap__(attr):
595
+ if attr in self._olerepr_.mapFuncs:
596
+ return self._make_method_(attr)
597
+ retEntry = self._olerepr_.propMap.get(attr)
598
+ if retEntry is None:
599
+ retEntry = self._olerepr_.propMapGet.get(attr)
600
+ if retEntry is None:
601
+ retEntry = build.MapEntry(self.__AttrToID__(attr), (attr,))
602
+ except pythoncom.ole_error:
603
+ pass # No prop by that name - retEntry remains None.
604
+
605
+ if retEntry is not None: # see if in my cache
606
+ try:
607
+ ret = self._mapCachedItems_[retEntry.dispid]
608
+ debug_attr_print("Cached items has attribute!", ret)
609
+ return ret
610
+ except (KeyError, AttributeError):
611
+ debug_attr_print("Attribute %s not in cache" % attr)
612
+
613
+ # If we are still here, and have a retEntry, get the OLE item
614
+ if retEntry is not None:
615
+ invoke_type = _GetDescInvokeType(retEntry, pythoncom.INVOKE_PROPERTYGET)
616
+ debug_attr_print(
617
+ "Getting property Id 0x%x from OLE object" % retEntry.dispid
618
+ )
619
+ try:
620
+ ret = self._oleobj_.Invoke(retEntry.dispid, 0, invoke_type, 1)
621
+ except pythoncom.com_error as details:
622
+ if details.hresult in ERRORS_BAD_CONTEXT:
623
+ # May be a method.
624
+ self._olerepr_.mapFuncs[attr] = retEntry
625
+ return self._make_method_(attr)
626
+ raise
627
+ debug_attr_print("OLE returned ", ret)
628
+ return self._get_good_object_(ret)
629
+
630
+ # no where else to look.
631
+ raise AttributeError(f"{self._username_}.{attr}")
632
+
633
+ def __setattr__(self, attr, value):
634
+ if (
635
+ attr in self.__dict__
636
+ ): # Fast-track - if already in our dict, just make the assignment.
637
+ # XXX - should maybe check method map - if someone assigns to a method,
638
+ # it could mean something special (not sure what, tho!)
639
+ self.__dict__[attr] = value
640
+ return
641
+ # Allow property assignment.
642
+ debug_attr_print(
643
+ f"SetAttr called for {self._username_}.{attr}={value!r} on DispatchContainer"
644
+ )
645
+
646
+ if self._olerepr_:
647
+ # Check the "general" property map.
648
+ if attr in self._olerepr_.propMap:
649
+ entry = self._olerepr_.propMap[attr]
650
+ invoke_type = _GetDescInvokeType(entry, pythoncom.INVOKE_PROPERTYPUT)
651
+ self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
652
+ return
653
+ # Check the specific "put" map.
654
+ if attr in self._olerepr_.propMapPut:
655
+ entry = self._olerepr_.propMapPut[attr]
656
+ invoke_type = _GetDescInvokeType(entry, pythoncom.INVOKE_PROPERTYPUT)
657
+ self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
658
+ return
659
+
660
+ # Try the OLE Object
661
+ if self._oleobj_:
662
+ if self.__LazyMap__(attr):
663
+ # Check the "general" property map.
664
+ if attr in self._olerepr_.propMap:
665
+ entry = self._olerepr_.propMap[attr]
666
+ invoke_type = _GetDescInvokeType(
667
+ entry, pythoncom.INVOKE_PROPERTYPUT
668
+ )
669
+ self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
670
+ return
671
+ # Check the specific "put" map.
672
+ if attr in self._olerepr_.propMapPut:
673
+ entry = self._olerepr_.propMapPut[attr]
674
+ invoke_type = _GetDescInvokeType(
675
+ entry, pythoncom.INVOKE_PROPERTYPUT
676
+ )
677
+ self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
678
+ return
679
+ try:
680
+ entry = build.MapEntry(self.__AttrToID__(attr), (attr,))
681
+ except pythoncom.com_error:
682
+ # No attribute of that name
683
+ entry = None
684
+ if entry is not None:
685
+ try:
686
+ invoke_type = _GetDescInvokeType(
687
+ entry, pythoncom.INVOKE_PROPERTYPUT
688
+ )
689
+ self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
690
+ self._olerepr_.propMap[attr] = entry
691
+ debug_attr_print(
692
+ "__setattr__ property {} (id=0x{:x}) in Dispatch container {}".format(
693
+ attr, entry.dispid, self._username_
694
+ )
695
+ )
696
+ return
697
+ except pythoncom.com_error:
698
+ pass
699
+ raise AttributeError(f"Property '{self._username_}.{attr}' can not be set.")
loan-advisor-agent/.venv/Lib/site-packages/win32com/client/gencache.py ADDED
@@ -0,0 +1,825 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Manages the cache of generated Python code.
2
+
3
+ Description
4
+ This file manages the cache of generated Python code. When run from the
5
+ command line, it also provides a number of options for managing that cache.
6
+
7
+ Implementation
8
+ Each typelib is generated into a filename of format "{guid}x{lcid}x{major}x{minor}.py"
9
+
10
+ An external persistant dictionary maps from all known IIDs in all known type libraries
11
+ to the type library itself.
12
+
13
+ Thus, whenever Python code knows the IID of an object, it can find the IID, LCID and version of
14
+ the type library which supports it. Given this information, it can find the Python module
15
+ with the support.
16
+
17
+ If necessary, this support can be generated on the fly.
18
+
19
+ Hacks, to do, etc
20
+ Currently just uses a pickled dictionary, but should used some sort of indexed file.
21
+ Maybe an OLE2 compound file, or a bsddb file?
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import contextlib
27
+ import glob
28
+ import os
29
+ import sys
30
+ from importlib import reload
31
+ from types import ModuleType
32
+ from typing import Any
33
+
34
+ import pythoncom
35
+ import pywintypes
36
+ import win32com
37
+ import win32com.client
38
+ import win32event
39
+
40
+ from . import CLSIDToClass
41
+
42
+ bForDemandDefault = 0 # Default value of bForDemand - toggle this to change the world - see also makepy.py
43
+
44
+ # The global dictionary
45
+ clsidToTypelib: dict[str, tuple[str, int, int, int]] = {}
46
+
47
+ # If we have a different version of the typelib generated, this
48
+ # maps the "requested version" to the "generated version".
49
+ versionRedirectMap: dict[tuple[str, int, int, int], ModuleType | None] = {}
50
+
51
+ # There is no reason we *must* be readonly in a .zip, but we are now,
52
+ # Rather than check for ".zip" or other tricks, PEP302 defines
53
+ # a "__loader__" attribute, so we use that.
54
+ # (Later, it may become necessary to check if the __loader__ can update files,
55
+ # as a .zip loader potentially could - but punt all that until a need arises)
56
+ is_readonly = is_zip = hasattr(win32com, "__loader__") and hasattr(
57
+ win32com.__loader__, "archive"
58
+ )
59
+
60
+ # A dictionary of ITypeLibrary objects for demand generation explicitly handed to us
61
+ # Keyed by usual clsid, lcid, major, minor
62
+ # Typing as Any because PyITypeLib is not exposed
63
+ demandGeneratedTypeLibraries: dict[tuple[str, int, int, int], Any] = {}
64
+
65
+ import pickle
66
+
67
+
68
+ def __init__():
69
+ # Initialize the module. Called once explicitly at module import below.
70
+ try:
71
+ _LoadDicts()
72
+ except OSError:
73
+ Rebuild()
74
+
75
+
76
+ pickleVersion = 1
77
+
78
+
79
+ def _SaveDicts():
80
+ if is_readonly:
81
+ raise RuntimeError(
82
+ "Trying to write to a readonly gencache ('%s')!" % win32com.__gen_path__
83
+ )
84
+ f = open(os.path.join(GetGeneratePath(), "dicts.dat"), "wb")
85
+ try:
86
+ p = pickle.Pickler(f)
87
+ p.dump(pickleVersion)
88
+ p.dump(clsidToTypelib)
89
+ finally:
90
+ f.close()
91
+
92
+
93
+ def _LoadDicts():
94
+ # Load the dictionary from a .zip file if that is where we live.
95
+ if is_zip:
96
+ import io
97
+
98
+ loader = win32com.__loader__
99
+ arc_path = loader.archive
100
+ dicts_path = os.path.join(win32com.__gen_path__, "dicts.dat")
101
+ if dicts_path.startswith(arc_path):
102
+ dicts_path = dicts_path[len(arc_path) + 1 :]
103
+ else:
104
+ # Hm. See below.
105
+ return
106
+ try:
107
+ data = loader.get_data(dicts_path)
108
+ except AttributeError:
109
+ # The __loader__ has no get_data method. See below.
110
+ return
111
+ except OSError:
112
+ # Our gencache is in a .zip file (and almost certainly readonly)
113
+ # but no dicts file. That actually needn't be fatal for a frozen
114
+ # application. Assuming they call "EnsureModule" with the same
115
+ # typelib IDs they have been frozen with, that EnsureModule will
116
+ # correctly re-build the dicts on the fly. However, objects that
117
+ # rely on the gencache but have not done an EnsureModule will
118
+ # fail (but their apps are likely to fail running from source
119
+ # with a clean gencache anyway, as then they would be getting
120
+ # Dynamic objects until the cache is built - so the best answer
121
+ # for these apps is to call EnsureModule, rather than freezing
122
+ # the dict)
123
+ return
124
+ f = io.BytesIO(data)
125
+ else:
126
+ # NOTE: OSError on file open must be caught by caller.
127
+ f = open(os.path.join(win32com.__gen_path__, "dicts.dat"), "rb")
128
+ try:
129
+ p = pickle.Unpickler(f)
130
+ version = p.load()
131
+ global clsidToTypelib
132
+ clsidToTypelib = p.load()
133
+ versionRedirectMap.clear()
134
+ finally:
135
+ f.close()
136
+
137
+
138
+ @contextlib.contextmanager
139
+ def ModuleMutex(module_name):
140
+ """Given the output of GetGeneratedFilename, acquire a named mutex for that module
141
+
142
+ This is required so that writes (generation) don't interfere with each other and with reads (import)
143
+ """
144
+ mutex = win32event.CreateMutex(None, False, module_name)
145
+ with contextlib.closing(mutex):
146
+ # acquire mutex
147
+ win32event.WaitForSingleObject(mutex, win32event.INFINITE)
148
+ try:
149
+ yield
150
+ finally:
151
+ win32event.ReleaseMutex(mutex)
152
+
153
+
154
+ def GetGeneratedFileName(clsid, lcid, major, minor):
155
+ """Given the clsid, lcid, major and minor for a type lib, return
156
+ the file name (no extension) providing this support.
157
+ """
158
+ return str(clsid).upper()[1:-1] + f"x{lcid}x{major}x{minor}"
159
+
160
+
161
+ def SplitGeneratedFileName(fname):
162
+ """Reverse of GetGeneratedFileName()"""
163
+ return tuple(fname.split("x", 4))
164
+
165
+
166
+ def GetGeneratePath():
167
+ """Returns the name of the path to generate to.
168
+ Checks the directory is OK.
169
+ """
170
+ assert not is_readonly, "Why do you want the genpath for a readonly store?"
171
+ try:
172
+ os.makedirs(win32com.__gen_path__)
173
+ # os.mkdir(win32com.__gen_path__)
174
+ except OSError:
175
+ pass
176
+ try:
177
+ fname = os.path.join(win32com.__gen_path__, "__init__.py")
178
+ os.stat(fname)
179
+ except OSError:
180
+ f = open(fname, "w")
181
+ f.write(
182
+ "# Generated file - this directory may be deleted to reset the COM cache...\n"
183
+ )
184
+ f.write("import win32com\n")
185
+ f.write(
186
+ "if __path__[:-1] != win32com.__gen_path__: __path__.append(win32com.__gen_path__)\n"
187
+ )
188
+ f.close()
189
+
190
+ return win32com.__gen_path__
191
+
192
+
193
+ #
194
+ # The helpers for win32com.client.Dispatch and OCX clients.
195
+ #
196
+ def GetClassForProgID(progid):
197
+ """Get a Python class for a Program ID
198
+
199
+ Given a Program ID, return a Python class which wraps the COM object
200
+
201
+ Returns the Python class, or None if no module is available.
202
+
203
+ Params
204
+ progid -- A COM ProgramID or IID (eg, "Word.Application")
205
+ """
206
+ clsid = pywintypes.IID(progid) # This auto-converts named to IDs.
207
+ return GetClassForCLSID(clsid)
208
+
209
+
210
+ def GetClassForCLSID(clsid):
211
+ """Get a Python class for a CLSID
212
+
213
+ Given a CLSID, return a Python class which wraps the COM object
214
+
215
+ Returns the Python class, or None if no module is available.
216
+
217
+ Params
218
+ clsid -- A COM CLSID (or string repr of one)
219
+ """
220
+ # first, take a short-cut - we may already have generated support ready-to-roll.
221
+ clsid = str(clsid)
222
+ if CLSIDToClass.HasClass(clsid):
223
+ return CLSIDToClass.GetClass(clsid)
224
+ mod = GetModuleForCLSID(clsid)
225
+ if mod is None:
226
+ return None
227
+ try:
228
+ return CLSIDToClass.GetClass(clsid)
229
+ except KeyError:
230
+ return None
231
+
232
+
233
+ def GetModuleForProgID(progid):
234
+ """Get a Python module for a Program ID
235
+
236
+ Given a Program ID, return a Python module which contains the
237
+ class which wraps the COM object.
238
+
239
+ Returns the Python module, or None if no module is available.
240
+
241
+ Params
242
+ progid -- A COM ProgramID or IID (eg, "Word.Application")
243
+ """
244
+ try:
245
+ iid = pywintypes.IID(progid)
246
+ except pywintypes.com_error:
247
+ return None
248
+ return GetModuleForCLSID(iid)
249
+
250
+
251
+ def GetModuleForCLSID(clsid):
252
+ """Get a Python module for a CLSID
253
+
254
+ Given a CLSID, return a Python module which contains the
255
+ class which wraps the COM object.
256
+
257
+ Returns the Python module, or None if no module is available.
258
+
259
+ Params
260
+ progid -- A COM CLSID (ie, not the description)
261
+ """
262
+ clsid_str = str(clsid)
263
+ try:
264
+ typelibCLSID, lcid, major, minor = clsidToTypelib[clsid_str]
265
+ except KeyError:
266
+ return None
267
+
268
+ try:
269
+ mod = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
270
+ except ImportError:
271
+ mod = None
272
+ if mod is not None:
273
+ sub_mod = mod.CLSIDToPackageMap.get(clsid_str)
274
+ if sub_mod is None:
275
+ sub_mod = mod.VTablesToPackageMap.get(clsid_str)
276
+ if sub_mod is not None:
277
+ sub_mod_name = mod.__name__ + "." + sub_mod
278
+ try:
279
+ with ModuleMutex(mod.__name__.split(".")[-1]):
280
+ __import__(sub_mod_name)
281
+ except ImportError:
282
+ info = typelibCLSID, lcid, major, minor
283
+ # Force the generation. If this typelibrary has explicitly been added,
284
+ # use it (it may not be registered, causing a lookup by clsid to fail)
285
+ if info in demandGeneratedTypeLibraries:
286
+ info = demandGeneratedTypeLibraries[info]
287
+ from . import makepy
288
+
289
+ makepy.GenerateChildFromTypeLibSpec(sub_mod, info)
290
+ # Generate does an import...
291
+ mod = sys.modules[sub_mod_name]
292
+ return mod
293
+
294
+
295
+ def GetModuleForTypelib(typelibCLSID, lcid, major, minor):
296
+ """Get a Python module for a type library ID
297
+
298
+ Given the CLSID of a typelibrary, return an imported Python module,
299
+ else None
300
+
301
+ Params
302
+ typelibCLSID -- IID of the type library.
303
+ major -- Integer major version.
304
+ minor -- Integer minor version
305
+ lcid -- Integer LCID for the library.
306
+ """
307
+ modName = GetGeneratedFileName(typelibCLSID, lcid, major, minor)
308
+ mod = _GetModule(modName)
309
+ # If the import worked, it doesn't mean we have actually added this
310
+ # module to our cache though - check that here.
311
+ if "_in_gencache_" not in mod.__dict__:
312
+ AddModuleToCache(typelibCLSID, lcid, major, minor)
313
+ assert "_in_gencache_" in mod.__dict__
314
+ return mod
315
+
316
+
317
+ def MakeModuleForTypelib(
318
+ typelibCLSID,
319
+ lcid,
320
+ major,
321
+ minor,
322
+ progressInstance=None,
323
+ bForDemand=bForDemandDefault,
324
+ bBuildHidden=1,
325
+ ):
326
+ """Generate support for a type library.
327
+
328
+ Given the IID, LCID and version information for a type library, generate
329
+ and import the necessary support files.
330
+
331
+ Returns the Python module. No exceptions are caught.
332
+
333
+ Params
334
+ typelibCLSID -- IID of the type library.
335
+ major -- Integer major version.
336
+ minor -- Integer minor version.
337
+ lcid -- Integer LCID for the library.
338
+ progressInstance -- Instance to use as progress indicator, or None to
339
+ use the GUI progress bar.
340
+ """
341
+ from . import makepy
342
+
343
+ makepy.GenerateFromTypeLibSpec(
344
+ (typelibCLSID, lcid, major, minor),
345
+ progressInstance=progressInstance,
346
+ bForDemand=bForDemand,
347
+ bBuildHidden=bBuildHidden,
348
+ )
349
+ return GetModuleForTypelib(typelibCLSID, lcid, major, minor)
350
+
351
+
352
+ def MakeModuleForTypelibInterface(
353
+ typelib_ob, progressInstance=None, bForDemand=bForDemandDefault, bBuildHidden=1
354
+ ):
355
+ """Generate support for a type library.
356
+
357
+ Given a PyITypeLib interface generate and import the necessary support files. This is useful
358
+ for getting makepy support for a typelibrary that is not registered - the caller can locate
359
+ and load the type library itself, rather than relying on COM to find it.
360
+
361
+ Returns the Python module.
362
+
363
+ Params
364
+ typelib_ob -- The type library itself
365
+ progressInstance -- Instance to use as progress indicator, or None to
366
+ use the GUI progress bar.
367
+ """
368
+ from . import makepy
369
+
370
+ try:
371
+ makepy.GenerateFromTypeLibSpec(
372
+ typelib_ob,
373
+ progressInstance=progressInstance,
374
+ bForDemand=bForDemandDefault,
375
+ bBuildHidden=bBuildHidden,
376
+ )
377
+ except pywintypes.com_error:
378
+ return None
379
+ tla = typelib_ob.GetLibAttr()
380
+ guid = tla[0]
381
+ lcid = tla[1]
382
+ major = tla[3]
383
+ minor = tla[4]
384
+ return GetModuleForTypelib(guid, lcid, major, minor)
385
+
386
+
387
+ def EnsureModuleForTypelibInterface(
388
+ typelib_ob, progressInstance=None, bForDemand=bForDemandDefault, bBuildHidden=1
389
+ ):
390
+ """Check we have support for a type library, generating if not.
391
+
392
+ Given a PyITypeLib interface generate and import the necessary
393
+ support files if necessary. This is useful for getting makepy support
394
+ for a typelibrary that is not registered - the caller can locate and
395
+ load the type library itself, rather than relying on COM to find it.
396
+
397
+ Returns the Python module.
398
+
399
+ Params
400
+ typelib_ob -- The type library itself
401
+ progressInstance -- Instance to use as progress indicator, or None to
402
+ use the GUI progress bar.
403
+ """
404
+ tla = typelib_ob.GetLibAttr()
405
+ guid = tla[0]
406
+ lcid = tla[1]
407
+ major = tla[3]
408
+ minor = tla[4]
409
+
410
+ # If demand generated, save the typelib interface away for later use
411
+ if bForDemand:
412
+ demandGeneratedTypeLibraries[(str(guid), lcid, major, minor)] = typelib_ob
413
+
414
+ try:
415
+ return GetModuleForTypelib(guid, lcid, major, minor)
416
+ except ImportError:
417
+ pass
418
+ # Generate it.
419
+ return MakeModuleForTypelibInterface(
420
+ typelib_ob, progressInstance, bForDemand, bBuildHidden
421
+ )
422
+
423
+
424
+ def ForgetAboutTypelibInterface(typelib_ob):
425
+ """Drop any references to a typelib previously added with EnsureModuleForTypelibInterface and forDemand"""
426
+ tla = typelib_ob.GetLibAttr()
427
+ guid = tla[0]
428
+ lcid = tla[1]
429
+ major = tla[3]
430
+ minor = tla[4]
431
+ info = str(guid), lcid, major, minor
432
+ try:
433
+ del demandGeneratedTypeLibraries[info]
434
+ except KeyError:
435
+ # Not worth raising an exception - maybe they don't know we only remember for demand generated, etc.
436
+ print(
437
+ "ForgetAboutTypelibInterface:: Warning - type library with info {} is not being remembered!".format(
438
+ info
439
+ )
440
+ )
441
+ # and drop any version redirects to it
442
+ for key, val in versionRedirectMap.items():
443
+ if val == info:
444
+ del versionRedirectMap[key]
445
+
446
+
447
+ def EnsureModule(
448
+ typelibCLSID,
449
+ lcid,
450
+ major,
451
+ minor,
452
+ progressInstance=None,
453
+ bValidateFile=not is_readonly,
454
+ bForDemand=bForDemandDefault,
455
+ bBuildHidden=1,
456
+ ):
457
+ """Ensure Python support is loaded for a type library, generating if necessary.
458
+
459
+ Given the IID, LCID and version information for a type library, check and if
460
+ necessary (re)generate, then import the necessary support files. If we regenerate the file, there
461
+ is no way to totally snuff out all instances of the old module in Python, and thus we will regenerate the file more than necessary,
462
+ unless makepy/genpy is modified accordingly.
463
+
464
+
465
+ Returns the Python module. No exceptions are caught during the generate process.
466
+
467
+ Params
468
+ typelibCLSID -- IID of the type library.
469
+ major -- Integer major version.
470
+ minor -- Integer minor version
471
+ lcid -- Integer LCID for the library.
472
+ progressInstance -- Instance to use as progress indicator, or None to
473
+ use the GUI progress bar.
474
+ bValidateFile -- Whether or not to perform cache validation or not
475
+ bForDemand -- Should a complete generation happen now, or on demand?
476
+ bBuildHidden -- Should hidden members/attributes etc be generated?
477
+ """
478
+ bReloadNeeded = 0
479
+ try:
480
+ try:
481
+ module = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
482
+ except ImportError:
483
+ # If we get an ImportError
484
+ # We may still find a valid cache file under a different MinorVersion #
485
+ # (which windows will search out for us)
486
+ # print("Loading reg typelib", typelibCLSID, major, minor, lcid)
487
+ module = None
488
+ try:
489
+ tlbAttr = pythoncom.LoadRegTypeLib(
490
+ typelibCLSID, major, minor, lcid
491
+ ).GetLibAttr()
492
+ # if the above line doesn't throw a pythoncom.com_error, check if
493
+ # it is actually a different lib than we requested, and if so, suck it in
494
+ if tlbAttr[1] != lcid or tlbAttr[4] != minor:
495
+ # print("Trying 2nd minor #", tlbAttr[1], tlbAttr[3], tlbAttr[4])
496
+ try:
497
+ module = GetModuleForTypelib(
498
+ typelibCLSID, tlbAttr[1], tlbAttr[3], tlbAttr[4]
499
+ )
500
+ except ImportError:
501
+ # We don't have a module, but we do have a better minor
502
+ # version - remember that.
503
+ minor = tlbAttr[4]
504
+ # else module remains None
505
+ except pythoncom.com_error:
506
+ # couldn't load any typelib - mod remains None
507
+ pass
508
+ if module is not None and bValidateFile:
509
+ assert not is_readonly, "Can't validate in a read-only gencache"
510
+ try:
511
+ typLibPath = pythoncom.QueryPathOfRegTypeLib(
512
+ typelibCLSID, major, minor, lcid
513
+ )
514
+ # windows seems to add an extra \0 (via the underlying BSTR)
515
+ # The mainwin toolkit does not add this erroneous \0
516
+ if typLibPath[-1] == "\0":
517
+ typLibPath = typLibPath[:-1]
518
+ suf = getattr(os.path, "supports_unicode_filenames", 0)
519
+ if not suf:
520
+ # can't pass unicode filenames directly - convert
521
+ try:
522
+ typLibPath = typLibPath.encode(sys.getfilesystemencoding())
523
+ except AttributeError: # no sys.getfilesystemencoding
524
+ typLibPath = str(typLibPath)
525
+ tlbAttributes = pythoncom.LoadRegTypeLib(
526
+ typelibCLSID, major, minor, lcid
527
+ ).GetLibAttr()
528
+ except pythoncom.com_error:
529
+ # We have a module, but no type lib - we should still
530
+ # run with what we have though - the typelib may not be
531
+ # deployed here.
532
+ bValidateFile = 0
533
+ if module is not None and bValidateFile:
534
+ assert not is_readonly, "Can't validate in a read-only gencache"
535
+ filePathPrefix = "{}\\{}".format(
536
+ GetGeneratePath(),
537
+ GetGeneratedFileName(typelibCLSID, lcid, major, minor),
538
+ )
539
+ filePath = filePathPrefix + ".py"
540
+ filePathPyc = filePathPrefix + ".py"
541
+ if __debug__:
542
+ filePathPyc += "c"
543
+ else:
544
+ filePathPyc += "o"
545
+ # Verify that type library is up to date.
546
+ # If we have a differing MinorVersion or genpy has bumped versions, update the file
547
+ from . import genpy
548
+
549
+ if (
550
+ module.MinorVersion != tlbAttributes[4]
551
+ or genpy.makepy_version != module.makepy_version
552
+ ):
553
+ # print(f"Version skew: {module.MinorVersion}, {tlbAttributes[4]}")
554
+ # try to erase the bad file from the cache
555
+ try:
556
+ os.unlink(filePath)
557
+ except OSError:
558
+ pass
559
+ try:
560
+ os.unlink(filePathPyc)
561
+ except OSError:
562
+ pass
563
+ if os.path.isdir(filePathPrefix):
564
+ import shutil
565
+
566
+ shutil.rmtree(filePathPrefix)
567
+ minor = tlbAttributes[4]
568
+ module = None
569
+ bReloadNeeded = 1
570
+ else:
571
+ minor = module.MinorVersion
572
+ filePathPrefix = "{}\\{}".format(
573
+ GetGeneratePath(),
574
+ GetGeneratedFileName(typelibCLSID, lcid, major, minor),
575
+ )
576
+ filePath = filePathPrefix + ".py"
577
+ filePathPyc = filePathPrefix + ".pyc"
578
+ # print("Trying py stat: ", filePath)
579
+ fModTimeSet = 0
580
+ try:
581
+ pyModTime = os.stat(filePath)[8]
582
+ fModTimeSet = 1
583
+ except OSError as e:
584
+ # If .py file fails, try .pyc file
585
+ # print("Trying pyc stat", filePathPyc)
586
+ try:
587
+ pyModTime = os.stat(filePathPyc)[8]
588
+ fModTimeSet = 1
589
+ except OSError as e:
590
+ pass
591
+ # print("Trying stat typelib", pyModTime)
592
+ # print(typLibPath)
593
+ typLibModTime = os.stat(typLibPath)[8]
594
+ if fModTimeSet and (typLibModTime > pyModTime):
595
+ bReloadNeeded = 1
596
+ module = None
597
+ except (ImportError, OSError):
598
+ module = None
599
+ if module is None:
600
+ # We need to build an item. If we are in a read-only cache, we
601
+ # can't/don't want to do this - so before giving up, check for
602
+ # a different minor version in our cache - according to COM, this is OK
603
+ if is_readonly:
604
+ key = str(typelibCLSID), lcid, major, minor
605
+ # If we have been asked before, get last result.
606
+ try:
607
+ return versionRedirectMap[key]
608
+ except KeyError:
609
+ pass
610
+ # Find other candidates.
611
+ items = []
612
+ for desc in GetGeneratedInfos():
613
+ if key[0] == desc[0] and key[1] == desc[1] and key[2] == desc[2]:
614
+ items.append(desc)
615
+ if items:
616
+ # Items are all identical, except for last tuple element
617
+ # We want the latest minor version we have - so just sort and grab last
618
+ items.sort()
619
+ new_minor = items[-1][3]
620
+ ret = GetModuleForTypelib(typelibCLSID, lcid, major, new_minor)
621
+ else:
622
+ ret = None
623
+ # remember and return
624
+ versionRedirectMap[key] = ret
625
+ return ret
626
+ # print("Rebuilding: ", major, minor)
627
+ module = MakeModuleForTypelib(
628
+ typelibCLSID,
629
+ lcid,
630
+ major,
631
+ minor,
632
+ progressInstance,
633
+ bForDemand=bForDemand,
634
+ bBuildHidden=bBuildHidden,
635
+ )
636
+ # If we replaced something, reload it
637
+ if bReloadNeeded:
638
+ module = reload(module)
639
+ AddModuleToCache(typelibCLSID, lcid, major, minor)
640
+ return module
641
+
642
+
643
+ def EnsureDispatch(
644
+ prog_id, bForDemand=1
645
+ ): # New fn, so we default the new demand feature to on!
646
+ """Given a COM prog_id, return an object that is using makepy support, building if necessary"""
647
+ disp = win32com.client.Dispatch(prog_id)
648
+ if not hasattr(disp, "CLSID"): # Eeek - no makepy support - try and build it.
649
+ try:
650
+ ti = disp._oleobj_.GetTypeInfo()
651
+ disp_clsid = ti.GetTypeAttr()[0]
652
+ tlb, index = ti.GetContainingTypeLib()
653
+ tla = tlb.GetLibAttr()
654
+ mod = EnsureModule(tla[0], tla[1], tla[3], tla[4], bForDemand=bForDemand)
655
+ GetModuleForCLSID(disp_clsid)
656
+ # Get the class from the module.
657
+ from . import CLSIDToClass
658
+
659
+ disp_class = CLSIDToClass.GetClass(str(disp_clsid))
660
+ disp = disp_class(disp._oleobj_)
661
+ except pythoncom.com_error:
662
+ raise TypeError(
663
+ "This COM object can not automate the makepy process - please run makepy manually for this object"
664
+ )
665
+ return disp
666
+
667
+
668
+ def AddModuleToCache(
669
+ typelibclsid, lcid, major, minor, verbose=1, bFlushNow=not is_readonly
670
+ ):
671
+ """Add a newly generated file to the cache dictionary."""
672
+ fname = GetGeneratedFileName(typelibclsid, lcid, major, minor)
673
+ mod = _GetModule(fname)
674
+ # if mod._in_gencache_ is already true, then we are reloading this
675
+ # module - this doesn't mean anything special though!
676
+ mod._in_gencache_ = 1
677
+ info = str(typelibclsid), lcid, major, minor
678
+ dict_modified = False
679
+
680
+ def SetTypelibForAllClsids(dict):
681
+ nonlocal dict_modified
682
+ for clsid in dict:
683
+ if clsidToTypelib.get(clsid) != info:
684
+ clsidToTypelib[clsid] = info
685
+ dict_modified = True
686
+
687
+ SetTypelibForAllClsids(mod.CLSIDToClassMap)
688
+ SetTypelibForAllClsids(mod.CLSIDToPackageMap)
689
+ SetTypelibForAllClsids(mod.VTablesToClassMap)
690
+ SetTypelibForAllClsids(mod.VTablesToPackageMap)
691
+
692
+ # If this lib was previously redirected, drop it
693
+ if info in versionRedirectMap:
694
+ del versionRedirectMap[info]
695
+ if bFlushNow and dict_modified:
696
+ _SaveDicts()
697
+
698
+
699
+ def GetGeneratedInfos():
700
+ zip_pos = win32com.__gen_path__.find(".zip\\")
701
+ if zip_pos >= 0:
702
+ import zipfile
703
+
704
+ zip_file = win32com.__gen_path__[: zip_pos + 4]
705
+ zip_path = win32com.__gen_path__[zip_pos + 5 :].replace("\\", "/")
706
+ zf = zipfile.ZipFile(zip_file)
707
+ infos = set()
708
+ for n in zf.namelist():
709
+ if not n.startswith(zip_path):
710
+ continue
711
+ base = n[len(zip_path) + 1 :].split("/")[0]
712
+ try:
713
+ iid, lcid, major, minor = base.split("x")
714
+ lcid = int(lcid)
715
+ major = int(major)
716
+ minor = int(minor)
717
+ iid = pywintypes.IID("{" + iid + "}")
718
+ except ValueError:
719
+ continue
720
+ except pywintypes.com_error:
721
+ # invalid IID
722
+ continue
723
+ infos.add((iid, lcid, major, minor))
724
+ zf.close()
725
+ return list(infos)
726
+ else:
727
+ # on the file system
728
+ files = glob.glob(win32com.__gen_path__ + "\\*")
729
+ ret = []
730
+ for file in files:
731
+ if not os.path.isdir(file) and not os.path.splitext(file)[1] == ".py":
732
+ continue
733
+ name = os.path.splitext(os.path.split(file)[1])[0]
734
+ try:
735
+ iid, lcid, major, minor = name.split("x")
736
+ iid = pywintypes.IID("{" + iid + "}")
737
+ lcid = int(lcid)
738
+ major = int(major)
739
+ minor = int(minor)
740
+ except ValueError:
741
+ continue
742
+ except pywintypes.com_error:
743
+ # invalid IID
744
+ continue
745
+ ret.append((iid, lcid, major, minor))
746
+ return ret
747
+
748
+
749
+ def _GetModule(fname):
750
+ """Given the name of a module in the gen_py directory, import and return it."""
751
+ mod_name = "win32com.gen_py.%s" % fname
752
+ with ModuleMutex(fname):
753
+ __import__(mod_name)
754
+ return sys.modules[mod_name]
755
+
756
+
757
+ def Rebuild(verbose=1):
758
+ """Rebuild the cache indexes from the file system."""
759
+ clsidToTypelib.clear()
760
+ infos = GetGeneratedInfos()
761
+ if verbose and len(infos): # Don't bother reporting this when directory is empty!
762
+ print("Rebuilding cache of generated files for COM support...")
763
+ for info in infos:
764
+ iid, lcid, major, minor = info
765
+ if verbose:
766
+ print("Checking", GetGeneratedFileName(*info))
767
+ try:
768
+ AddModuleToCache(iid, lcid, major, minor, verbose, 0)
769
+ except:
770
+ print(
771
+ "Could not add module {} - {}: {}".format(
772
+ info, sys.exc_info()[0], sys.exc_info()[1]
773
+ )
774
+ )
775
+ if verbose and len(infos): # Don't bother reporting this when directory is empty!
776
+ print("Done.")
777
+ _SaveDicts()
778
+
779
+
780
+ def _Dump():
781
+ print("Cache is in directory", win32com.__gen_path__)
782
+ # Build a unique dir
783
+ d = set(clsidToTypelib.values())
784
+ for typelibCLSID, lcid, major, minor in d:
785
+ mod = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
786
+ print(f"{mod.__doc__} - {typelibCLSID}")
787
+
788
+
789
+ # Boot up
790
+ __init__()
791
+
792
+
793
+ def usage():
794
+ usageString = """\
795
+ Usage: gencache [-q] [-d] [-r]
796
+
797
+ -q - Quiet
798
+ -d - Dump the cache (typelibrary description and filename).
799
+ -r - Rebuild the cache dictionary from the existing .py files
800
+ """
801
+ print(usageString)
802
+ sys.exit(1)
803
+
804
+
805
+ if __name__ == "__main__":
806
+ import getopt
807
+
808
+ try:
809
+ opts, args = getopt.getopt(sys.argv[1:], "qrd")
810
+ except getopt.error as message:
811
+ print(message)
812
+ usage()
813
+
814
+ # we only have options - complain about real args, or none at all!
815
+ if len(sys.argv) == 1 or args:
816
+ print(usage())
817
+
818
+ verbose = 1
819
+ for opt, val in opts:
820
+ if opt == "-d": # Dump
821
+ _Dump()
822
+ if opt == "-r":
823
+ Rebuild(verbose)
824
+ if opt == "-q":
825
+ verbose = 0
loan-advisor-agent/.venv/Lib/site-packages/win32com/client/genpy.py ADDED
@@ -0,0 +1,1352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """genpy.py - The worker for makepy. See makepy.py for more details
2
+
3
+ This code was moved simply to speed Python in normal circumstances. As the makepy.py
4
+ is normally run from the command line, it reparses the code each time. Now makepy
5
+ is nothing more than the command line handler and public interface.
6
+
7
+ The makepy command line etc handling is also getting large enough in its own right!
8
+ """
9
+
10
+ # NOTE - now supports a "demand" mechanism - the top-level is a package, and
11
+ # each class etc can be made individually.
12
+ # This should eventually become the default.
13
+ # Then the old non-package technique should be removed.
14
+ # There should be no b/w compat issues, and will just help clean the code.
15
+ # This will be done once the new "demand" mechanism gets a good workout.
16
+ import os
17
+ import sys
18
+ import time
19
+ from itertools import chain
20
+
21
+ import pythoncom
22
+
23
+ from . import build, gencache
24
+
25
+ makepy_version = "0.5.01" # Written to generated file.
26
+
27
+ GEN_FULL = "full"
28
+ GEN_DEMAND_BASE = "demand(base)"
29
+ GEN_DEMAND_CHILD = "demand(child)"
30
+
31
+ # This map is used purely for the users benefit -it shows the
32
+ # raw, underlying type of Alias/Enums, etc. The COM implementation
33
+ # does not use this map at runtime - all Alias/Enum have already
34
+ # been translated.
35
+ mapVTToTypeString = {
36
+ pythoncom.VT_I2: "int",
37
+ pythoncom.VT_I4: "int",
38
+ pythoncom.VT_R4: "float",
39
+ pythoncom.VT_R8: "float",
40
+ pythoncom.VT_BSTR: "str",
41
+ pythoncom.VT_BOOL: "int",
42
+ pythoncom.VT_VARIANT: "type",
43
+ pythoncom.VT_I1: "int",
44
+ pythoncom.VT_UI1: "int",
45
+ pythoncom.VT_UI2: "int",
46
+ pythoncom.VT_UI4: "int",
47
+ pythoncom.VT_I8: "int",
48
+ pythoncom.VT_UI8: "int",
49
+ pythoncom.VT_INT: "int",
50
+ pythoncom.VT_DATE: "datetime.date",
51
+ pythoncom.VT_UINT: "int",
52
+ }
53
+
54
+
55
+ # Given a propget function's arg desc, return the default parameters for all
56
+ # params bar the first. Eg, then Python does a:
57
+ # object.Property = "foo"
58
+ # Python can only pass the "foo" value. If the property has
59
+ # multiple args, and the rest have default values, this allows
60
+ # Python to correctly pass those defaults.
61
+ def MakeDefaultArgsForPropertyPut(argsDesc):
62
+ ret = []
63
+ for desc in argsDesc[1:]:
64
+ default = build.MakeDefaultArgRepr(desc)
65
+ if default is None:
66
+ break
67
+ ret.append(default)
68
+ return tuple(ret)
69
+
70
+
71
+ def MakeMapLineEntry(dispid, wFlags, retType, argTypes, user, resultCLSID):
72
+ # Strip the default value
73
+ argTypes = tuple([what[:2] for what in argTypes])
74
+ return '(%s, %d, %s, %s, "%s", %s)' % (
75
+ dispid,
76
+ wFlags,
77
+ retType[:2],
78
+ argTypes,
79
+ user,
80
+ resultCLSID,
81
+ )
82
+
83
+
84
+ def MakeEventMethodName(eventName):
85
+ if eventName[:2] == "On":
86
+ return eventName
87
+ else:
88
+ return "On" + eventName
89
+
90
+
91
+ def WriteSinkEventMap(obj, stream):
92
+ print("\t_dispid_to_func_ = {", file=stream)
93
+ for entry in chain(
94
+ obj.propMapGet.values(),
95
+ obj.propMapPut.values(),
96
+ obj.mapFuncs.values(),
97
+ ):
98
+ memid = entry.desc.memid
99
+ print(
100
+ '\t\t%9d : "%s",' % (memid, MakeEventMethodName(entry.names[0])),
101
+ file=stream,
102
+ )
103
+ print("\t\t}", file=stream)
104
+
105
+
106
+ # MI is used to join my writable helpers, and the OLE
107
+ # classes.
108
+ class WritableItem:
109
+ def __lt__(self, other):
110
+ if self.order == other.order:
111
+ return self.doc < other.doc
112
+ return self.order < other.order
113
+
114
+ def __repr__(self):
115
+ return f"OleItem: doc={self.doc!r}, order={self.order}"
116
+
117
+
118
+ class RecordItem(build.OleItem, WritableItem):
119
+ order = 9
120
+ typename = "RECORD"
121
+
122
+ def __init__(self, typeInfo, typeAttr, doc=None, bForUser=1):
123
+ ## sys.stderr.write("Record %s: size %s\n" % (doc,typeAttr.cbSizeInstance))
124
+ ## sys.stderr.write(" cVars = %s\n" % (typeAttr.cVars,))
125
+ ## for i in range(typeAttr.cVars):
126
+ ## vdesc = typeInfo.GetVarDesc(i)
127
+ ## sys.stderr.write(" Var %d has value %s, type %d, desc=%s\n" % (i, vdesc.value, vdesc.varkind, vdesc.elemdescVar))
128
+ ## sys.stderr.write(" Doc is %s\n" % (typeInfo.GetDocumentation(vdesc.memid),))
129
+
130
+ build.OleItem.__init__(self, doc)
131
+ self.clsid = typeAttr[0]
132
+
133
+ def WriteClass(self, generator):
134
+ pass
135
+
136
+
137
+ # Given an enum, write all aliases for it.
138
+ # (no longer necessary for new style code, but still used for old code.
139
+ def WriteAliasesForItem(item, aliasItems, stream):
140
+ for alias in aliasItems.values():
141
+ if item.doc and alias.aliasDoc and (alias.aliasDoc[0] == item.doc[0]):
142
+ alias.WriteAliasItem(aliasItems, stream)
143
+
144
+
145
+ class AliasItem(build.OleItem, WritableItem):
146
+ order = 2
147
+ typename = "ALIAS"
148
+
149
+ def __init__(self, typeinfo, attr, doc=None, bForUser=1):
150
+ build.OleItem.__init__(self, doc)
151
+
152
+ ai = attr[14]
153
+ self.attr = attr
154
+ # XXX - This is a hack - why tuples? Need to resolve?
155
+ if isinstance(ai, tuple) and isinstance(ai[1], int):
156
+ href = ai[1]
157
+ alinfo = typeinfo.GetRefTypeInfo(href)
158
+ self.aliasDoc = alinfo.GetDocumentation(-1)
159
+ self.aliasAttr = alinfo.GetTypeAttr()
160
+ else:
161
+ self.aliasDoc = None
162
+ self.aliasAttr = None
163
+
164
+ def WriteAliasItem(self, aliasDict, stream):
165
+ # we could have been written as part of an alias dependency
166
+ if self.bWritten:
167
+ return
168
+
169
+ if self.aliasDoc:
170
+ depName = self.aliasDoc[0]
171
+ if depName in aliasDict:
172
+ aliasDict[depName].WriteAliasItem(aliasDict, stream)
173
+ print(self.doc[0] + " = " + depName, file=stream)
174
+ else:
175
+ ai = self.attr[14]
176
+ if isinstance(ai, int):
177
+ try:
178
+ typeStr = mapVTToTypeString[ai]
179
+ print(f"# {self.doc[0]}={typeStr}", file=stream)
180
+ except KeyError:
181
+ print(
182
+ self.doc[0] + " = None # Can't convert alias info " + str(ai),
183
+ file=stream,
184
+ )
185
+ print(file=stream)
186
+ self.bWritten = 1
187
+
188
+
189
+ class EnumerationItem(build.OleItem, WritableItem):
190
+ order = 1
191
+ typename = "ENUMERATION"
192
+
193
+ def __init__(self, typeinfo, attr, doc=None, bForUser=1):
194
+ build.OleItem.__init__(self, doc)
195
+
196
+ self.clsid = attr[0]
197
+ self.mapVars = {}
198
+ typeFlags = attr[11]
199
+ self.hidden = (
200
+ typeFlags & pythoncom.TYPEFLAG_FHIDDEN
201
+ or typeFlags & pythoncom.TYPEFLAG_FRESTRICTED
202
+ )
203
+
204
+ for j in range(attr[7]):
205
+ vdesc = typeinfo.GetVarDesc(j)
206
+ name = typeinfo.GetNames(vdesc[0])[0]
207
+ self.mapVars[name] = build.MapEntry(vdesc)
208
+
209
+ # def WriteEnumerationHeaders(self, aliasItems, stream):
210
+ # enumName = self.doc[0]
211
+ # print(f"{enumName}=constants # Compatibility with previous versions.", file=stream)
212
+ # WriteAliasesForItem(self, aliasItems)
213
+
214
+ def WriteEnumerationItems(self, stream):
215
+ num = 0
216
+ enumName = self.doc[0]
217
+ # Write in name alpha order
218
+ for name in sorted(self.mapVars):
219
+ entry = self.mapVars[name]
220
+ vdesc = entry.desc
221
+ if vdesc[4] == pythoncom.VAR_CONST:
222
+ val = vdesc[1]
223
+
224
+ use = repr(val)
225
+ # Make sure the repr of the value is valid python syntax
226
+ # still could cause an error on import if it contains a module or type name
227
+ # not available in the global namespace
228
+ try:
229
+ compile(use, "<makepy>", "eval")
230
+ except SyntaxError:
231
+ # At least add the repr as a string, so it can be investigated further
232
+ # Sanitize it, in case the repr contains its own quotes. (??? line breaks too ???)
233
+ use = use.replace('"', "'")
234
+ use = (
235
+ f'"{use}" # This VARIANT type cannot be converted automatically'
236
+ )
237
+ print(
238
+ "\t%-30s=%-10s # from enum %s"
239
+ % (build.MakePublicAttributeName(name, True), use, enumName),
240
+ file=stream,
241
+ )
242
+ num += 1
243
+ return num
244
+
245
+
246
+ class VTableItem(build.VTableItem, WritableItem):
247
+ order = 4
248
+
249
+ def WriteClass(self, generator):
250
+ self.WriteVTableMap(generator)
251
+ self.bWritten = 1
252
+
253
+ def WriteVTableMap(self, generator):
254
+ stream = generator.file
255
+ print(
256
+ "%s_vtables_dispatch_ = %d" % (self.python_name, self.bIsDispatch),
257
+ file=stream,
258
+ )
259
+ print(f"{self.python_name}_vtables_ = [", file=stream)
260
+ for v in self.vtableFuncs:
261
+ names, dispid, desc = v
262
+ assert desc.desckind == pythoncom.DESCKIND_FUNCDESC
263
+ arg_reprs = []
264
+ # more hoops so we don't generate huge lines.
265
+ item_num = 0
266
+ print("\t((", end=" ", file=stream)
267
+ for name in names:
268
+ print(repr(name), ",", end=" ", file=stream)
269
+ item_num += 1
270
+ if item_num % 5 == 0:
271
+ print("\n\t\t\t", end=" ", file=stream)
272
+ print(
273
+ "), %d, (%r, %r, [" % (dispid, desc.memid, desc.scodeArray),
274
+ end=" ",
275
+ file=stream,
276
+ )
277
+ for arg in desc.args:
278
+ item_num += 1
279
+ if item_num % 5 == 0:
280
+ print("\n\t\t\t", end=" ", file=stream)
281
+ defval = build.MakeDefaultArgRepr(arg)
282
+ if arg[3] is None:
283
+ arg3_repr = None
284
+ else:
285
+ arg3_repr = repr(arg[3])
286
+ print(
287
+ repr((arg[0], arg[1], defval, arg3_repr)), ",", end=" ", file=stream
288
+ )
289
+ print("],", end=" ", file=stream)
290
+ print(repr(desc.funckind), ",", end=" ", file=stream)
291
+ print(repr(desc.invkind), ",", end=" ", file=stream)
292
+ print(repr(desc.callconv), ",", end=" ", file=stream)
293
+ print(repr(desc.cParamsOpt), ",", end=" ", file=stream)
294
+ print(repr(desc.oVft), ",", end=" ", file=stream)
295
+ print(repr(desc.rettype), ",", end=" ", file=stream)
296
+ print(repr(desc.wFuncFlags), ",", end=" ", file=stream)
297
+ print(")),", file=stream)
298
+ print("]", file=stream)
299
+ print(file=stream)
300
+
301
+
302
+ class DispatchItem(build.DispatchItem, WritableItem):
303
+ order = 3
304
+
305
+ def __init__(self, typeinfo, attr, doc=None):
306
+ build.DispatchItem.__init__(self, typeinfo, attr, doc)
307
+ self.type_attr = attr
308
+ self.coclass_clsid = None
309
+
310
+ def WriteClass(self, generator):
311
+ if (
312
+ not self.bIsDispatch
313
+ and not self.type_attr.typekind == pythoncom.TKIND_DISPATCH
314
+ ):
315
+ return
316
+ # This is pretty screwey - now we have vtable support we
317
+ # should probably rethink this (ie, maybe write both sides for sinks, etc)
318
+ if self.bIsSink:
319
+ self.WriteEventSinkClassHeader(generator)
320
+ self.WriteCallbackClassBody(generator)
321
+ else:
322
+ self.WriteClassHeader(generator)
323
+ self.WriteClassBody(generator)
324
+ print(file=generator.file)
325
+ self.bWritten = 1
326
+
327
+ def WriteClassHeader(self, generator):
328
+ generator.checkWriteDispatchBaseClass()
329
+ doc = self.doc
330
+ stream = generator.file
331
+ print("class " + self.python_name + "(DispatchBaseClass):", file=stream)
332
+ if doc[1]:
333
+ print("\t" + build._makeDocString(doc[1]), file=stream)
334
+ try:
335
+ progId = pythoncom.ProgIDFromCLSID(self.clsid)
336
+ print(
337
+ "\t# This class is creatable by the name '%s'" % (progId), file=stream
338
+ )
339
+ except pythoncom.com_error:
340
+ pass
341
+ print(f"\tCLSID = {self.clsid!r}", file=stream)
342
+ if self.coclass_clsid is None:
343
+ print("\tcoclass_clsid = None", file=stream)
344
+ else:
345
+ print(f"\tcoclass_clsid = {self.coclass_clsid!r}", file=stream)
346
+ print(file=stream)
347
+ self.bWritten = 1
348
+
349
+ def WriteEventSinkClassHeader(self, generator):
350
+ generator.checkWriteEventBaseClass()
351
+ doc = self.doc
352
+ stream = generator.file
353
+ print("class " + self.python_name + ":", file=stream)
354
+ if doc[1]:
355
+ print("\t" + build._makeDocString(doc[1]), file=stream)
356
+ try:
357
+ progId = pythoncom.ProgIDFromCLSID(self.clsid)
358
+ print(
359
+ "\t# This class is creatable by the name '%s'" % (progId), file=stream
360
+ )
361
+ except pythoncom.com_error:
362
+ pass
363
+ print(f"\tCLSID = CLSID_Sink = {self.clsid!r}", file=stream)
364
+ if self.coclass_clsid is None:
365
+ print("\tcoclass_clsid = None", file=stream)
366
+ else:
367
+ print(f"\tcoclass_clsid = {self.coclass_clsid!r}", file=stream)
368
+ print("\t_public_methods_ = [] # For COM Server support", file=stream)
369
+ WriteSinkEventMap(self, stream)
370
+ print(file=stream)
371
+ print("\tdef __init__(self, oobj = None):", file=stream)
372
+ print("\t\tif oobj is None:", file=stream)
373
+ print("\t\t\tself._olecp = None", file=stream)
374
+ print("\t\telse:", file=stream)
375
+ print("\t\t\timport win32com.server.util", file=stream)
376
+ print(
377
+ "\t\t\tfrom win32com.server.policy import EventHandlerPolicy", file=stream
378
+ )
379
+ print(
380
+ "\t\t\tcpc=oobj._oleobj_.QueryInterface(pythoncom.IID_IConnectionPointContainer)",
381
+ file=stream,
382
+ )
383
+ print("\t\t\tcp=cpc.FindConnectionPoint(self.CLSID_Sink)", file=stream)
384
+ print(
385
+ "\t\t\tcookie=cp.Advise(win32com.server.util.wrap(self, usePolicy=EventHandlerPolicy))",
386
+ file=stream,
387
+ )
388
+ print("\t\t\tself._olecp,self._olecp_cookie = cp,cookie", file=stream)
389
+ print("\tdef __del__(self):", file=stream)
390
+ print("\t\ttry:", file=stream)
391
+ print("\t\t\tself.close()", file=stream)
392
+ print("\t\texcept pythoncom.com_error:", file=stream)
393
+ print("\t\t\tpass", file=stream)
394
+ print("\tdef close(self):", file=stream)
395
+ print("\t\tif self._olecp is not None:", file=stream)
396
+ print(
397
+ "\t\t\tcp,cookie,self._olecp,self._olecp_cookie = self._olecp,self._olecp_cookie,None,None",
398
+ file=stream,
399
+ )
400
+ print("\t\t\tcp.Unadvise(cookie)", file=stream)
401
+ print("\tdef _query_interface_(self, iid):", file=stream)
402
+ print("\t\timport win32com.server.util", file=stream)
403
+ print(
404
+ "\t\tif iid==self.CLSID_Sink: return win32com.server.util.wrap(self)",
405
+ file=stream,
406
+ )
407
+ print(file=stream)
408
+ self.bWritten = 1
409
+
410
+ def WriteCallbackClassBody(self, generator):
411
+ stream = generator.file
412
+ print("\t# Event Handlers", file=stream)
413
+ print(
414
+ "\t# If you create handlers, they should have the following prototypes:",
415
+ file=stream,
416
+ )
417
+ for entry in chain(
418
+ self.propMapGet.values(), self.propMapPut.values(), self.mapFuncs.values()
419
+ ):
420
+ fdesc = entry.desc
421
+ methName = MakeEventMethodName(entry.names[0])
422
+ print(
423
+ "#\tdef "
424
+ + methName
425
+ + "(self"
426
+ + build.BuildCallList(
427
+ fdesc,
428
+ entry.names,
429
+ "defaultNamedOptArg",
430
+ "defaultNamedNotOptArg",
431
+ "defaultUnnamedArg",
432
+ "pythoncom.Missing",
433
+ is_comment=True,
434
+ )
435
+ + "):",
436
+ file=stream,
437
+ )
438
+ if entry.doc and entry.doc[1]:
439
+ print("#\t\t" + build._makeDocString(entry.doc[1]), file=stream)
440
+ print(file=stream)
441
+ self.bWritten = 1
442
+
443
+ def WriteClassBody(self, generator):
444
+ stream = generator.file
445
+ specialItems = {
446
+ "count": None,
447
+ "item": None,
448
+ "value": None,
449
+ "_newenum": None,
450
+ } # If found, will end up with (entry, invoke_tupe)
451
+ # Write in alpha order.
452
+ for name in sorted(self.mapFuncs):
453
+ entry = self.mapFuncs[name]
454
+ assert entry.desc.desckind == pythoncom.DESCKIND_FUNCDESC
455
+ # skip [restricted] methods, unless it is the
456
+ # enumerator (which, being part of the "system",
457
+ # we know about and can use)
458
+ dispid = entry.desc.memid
459
+ if (
460
+ entry.desc.wFuncFlags & pythoncom.FUNCFLAG_FRESTRICTED
461
+ and dispid != pythoncom.DISPID_NEWENUM
462
+ ):
463
+ continue
464
+ # If not accessible via IDispatch, then we can't use it here.
465
+ if entry.desc.funckind != pythoncom.FUNC_DISPATCH:
466
+ continue
467
+ if dispid == pythoncom.DISPID_VALUE:
468
+ lkey = "value"
469
+ elif dispid == pythoncom.DISPID_NEWENUM:
470
+ specialItems["_newenum"] = (entry, entry.desc.invkind, None)
471
+ continue # Don't build this one now!
472
+ else:
473
+ lkey = name.lower()
474
+ if (
475
+ lkey in specialItems and specialItems[lkey] is None
476
+ ): # remember if a special one.
477
+ specialItems[lkey] = (entry, entry.desc.invkind, None)
478
+ if generator.bBuildHidden or not entry.hidden:
479
+ if entry.GetResultName():
480
+ print("\t# Result is of type " + entry.GetResultName(), file=stream)
481
+ if entry.wasProperty:
482
+ print(
483
+ "\t# The method %s is actually a property, but must be used as a method to correctly pass the arguments"
484
+ % name,
485
+ file=stream,
486
+ )
487
+ ret = self.MakeFuncMethod(entry, build.MakePublicAttributeName(name))
488
+ for line in ret:
489
+ print(line, file=stream)
490
+ print("\t_prop_map_get_ = {", file=stream)
491
+ for key in sorted(self.propMap):
492
+ entry = self.propMap[key]
493
+ if generator.bBuildHidden or not entry.hidden:
494
+ resultName = entry.GetResultName()
495
+ if resultName:
496
+ print(
497
+ f"\t\t# Property '{key}' is an object of type '{resultName}'",
498
+ file=stream,
499
+ )
500
+ lkey = key.lower()
501
+ details = entry.desc
502
+ resultDesc = details[2]
503
+ argDesc = ()
504
+ mapEntry = MakeMapLineEntry(
505
+ details.memid,
506
+ pythoncom.DISPATCH_PROPERTYGET,
507
+ resultDesc,
508
+ argDesc,
509
+ key,
510
+ entry.GetResultCLSIDStr(),
511
+ )
512
+
513
+ if details.memid == pythoncom.DISPID_VALUE:
514
+ lkey = "value"
515
+ elif details.memid == pythoncom.DISPID_NEWENUM:
516
+ lkey = "_newenum"
517
+ else:
518
+ lkey = key.lower()
519
+ if (
520
+ lkey in specialItems and specialItems[lkey] is None
521
+ ): # remember if a special one.
522
+ specialItems[lkey] = (
523
+ entry,
524
+ pythoncom.DISPATCH_PROPERTYGET,
525
+ mapEntry,
526
+ )
527
+ # All special methods, except _newenum, are written
528
+ # "normally". This is a mess!
529
+ if details.memid == pythoncom.DISPID_NEWENUM:
530
+ continue
531
+
532
+ print(
533
+ f'\t\t"{build.MakePublicAttributeName(key)}": {mapEntry},',
534
+ file=stream,
535
+ )
536
+ for key in sorted(self.propMapGet):
537
+ entry = self.propMapGet[key]
538
+ if generator.bBuildHidden or not entry.hidden:
539
+ if entry.GetResultName():
540
+ print(
541
+ "\t\t# Method '{}' returns object of type '{}'".format(
542
+ key, entry.GetResultName()
543
+ ),
544
+ file=stream,
545
+ )
546
+ details = entry.desc
547
+ assert details.desckind == pythoncom.DESCKIND_FUNCDESC
548
+ lkey = key.lower()
549
+ argDesc = details[2]
550
+ resultDesc = details[8]
551
+ mapEntry = MakeMapLineEntry(
552
+ details[0],
553
+ pythoncom.DISPATCH_PROPERTYGET,
554
+ resultDesc,
555
+ argDesc,
556
+ key,
557
+ entry.GetResultCLSIDStr(),
558
+ )
559
+ if details.memid == pythoncom.DISPID_VALUE:
560
+ lkey = "value"
561
+ elif details.memid == pythoncom.DISPID_NEWENUM:
562
+ lkey = "_newenum"
563
+ else:
564
+ lkey = key.lower()
565
+ if (
566
+ lkey in specialItems and specialItems[lkey] is None
567
+ ): # remember if a special one.
568
+ specialItems[lkey] = (
569
+ entry,
570
+ pythoncom.DISPATCH_PROPERTYGET,
571
+ mapEntry,
572
+ )
573
+ # All special methods, except _newenum, are written
574
+ # "normally". This is a mess!
575
+ if details.memid == pythoncom.DISPID_NEWENUM:
576
+ continue
577
+ print(
578
+ f'\t\t"{build.MakePublicAttributeName(key)}": {mapEntry},',
579
+ file=stream,
580
+ )
581
+
582
+ print("\t}", file=stream)
583
+
584
+ print("\t_prop_map_put_ = {", file=stream)
585
+ # These are "Invoke" args
586
+ for key in sorted(self.propMap):
587
+ entry = self.propMap[key]
588
+ if generator.bBuildHidden or not entry.hidden:
589
+ lkey = key.lower()
590
+ details = entry.desc
591
+ # If default arg is None, write an empty tuple
592
+ defArgDesc = build.MakeDefaultArgRepr(details[2])
593
+ if defArgDesc is None:
594
+ defArgDesc = ""
595
+ else:
596
+ defArgDesc += ","
597
+ print(
598
+ '\t\t"%s" : ((%s, LCID, %d, 0),(%s)),'
599
+ % (
600
+ build.MakePublicAttributeName(key),
601
+ details[0],
602
+ pythoncom.DISPATCH_PROPERTYPUT,
603
+ defArgDesc,
604
+ ),
605
+ file=stream,
606
+ )
607
+
608
+ for key in sorted(self.propMapPut):
609
+ entry = self.propMapPut[key]
610
+ if generator.bBuildHidden or not entry.hidden:
611
+ details = entry.desc
612
+ defArgDesc = MakeDefaultArgsForPropertyPut(details[2])
613
+ print(
614
+ '\t\t"%s": ((%s, LCID, %d, 0),%s),'
615
+ % (
616
+ build.MakePublicAttributeName(key),
617
+ details[0],
618
+ details[4],
619
+ defArgDesc,
620
+ ),
621
+ file=stream,
622
+ )
623
+ print("\t}", file=stream)
624
+
625
+ if specialItems["value"]:
626
+ entry, invoketype, propArgs = specialItems["value"]
627
+ if propArgs is None:
628
+ typename = "method"
629
+ ret = self.MakeFuncMethod(entry, "__call__")
630
+ else:
631
+ typename = "property"
632
+ ret = [
633
+ "\tdef __call__(self):\n\t\treturn self._ApplyTypes_(*%s)"
634
+ % propArgs
635
+ ]
636
+ print(
637
+ f"\t# Default {typename} for this class is '{entry.names[0]}'",
638
+ file=stream,
639
+ )
640
+ for line in ret:
641
+ print(line, file=stream)
642
+ print("\tdef __str__(self, *args):", file=stream)
643
+ print("\t\treturn str(self.__call__(*args))", file=stream)
644
+ print("\tdef __int__(self, *args):", file=stream)
645
+ print("\t\treturn int(self.__call__(*args))", file=stream)
646
+
647
+ # _NewEnum (DISPID_NEWENUM) does not appear in typelib for many office objects,
648
+ # but it can still be retrieved at runtime, so always create __iter__.
649
+ # Also, some of those same objects use 1-based indexing, causing the old-style
650
+ # __getitem__ iteration to fail for index 0 where the dynamic iteration succeeds.
651
+ if specialItems["_newenum"]:
652
+ enumEntry, invoketype, propArgs = specialItems["_newenum"]
653
+ assert enumEntry.desc.desckind == pythoncom.DESCKIND_FUNCDESC
654
+ invkind = enumEntry.desc.invkind
655
+ # ??? Wouldn't this be the resultCLSID for the iterator itself, rather than the resultCLSID
656
+ # for the result of each Next() call, which is what it's used for ???
657
+ resultCLSID = enumEntry.GetResultCLSIDStr()
658
+ else:
659
+ invkind = pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET
660
+ resultCLSID = "None"
661
+ # If we don't have a good CLSID for the enum result, assume it is the same as the Item() method.
662
+ if resultCLSID == "None" and "Item" in self.mapFuncs:
663
+ resultCLSID = self.mapFuncs["Item"].GetResultCLSIDStr()
664
+ print("\tdef __iter__(self):", file=stream)
665
+ print('\t\t"Return a Python iterator for this object"', file=stream)
666
+ print("\t\ttry:", file=stream)
667
+ print(
668
+ "\t\t\tob = self._oleobj_.InvokeTypes(%d,LCID,%d,(13, 10),())"
669
+ % (pythoncom.DISPID_NEWENUM, invkind),
670
+ file=stream,
671
+ )
672
+ print("\t\texcept pythoncom.error:", file=stream)
673
+ print(
674
+ '\t\t\traise TypeError("This object does not support enumeration")',
675
+ file=stream,
676
+ )
677
+ # Iterator is wrapped as PyIEnumVariant, and each result of __next__ is Dispatch'ed if necessary
678
+ print(
679
+ "\t\treturn win32com.client.util.Iterator(ob, %s)" % resultCLSID,
680
+ file=stream,
681
+ )
682
+
683
+ if specialItems["item"]:
684
+ entry, invoketype, propArgs = specialItems["item"]
685
+ resultCLSID = entry.GetResultCLSIDStr()
686
+ print(
687
+ "\t#This class has Item property/method which allows indexed access with the object[key] syntax.",
688
+ file=stream,
689
+ )
690
+ print(
691
+ "\t#Some objects will accept a string or other type of key in addition to integers.",
692
+ file=stream,
693
+ )
694
+ print(
695
+ "\t#Note that many Office objects do not use zero-based indexing.",
696
+ file=stream,
697
+ )
698
+ print("\tdef __getitem__(self, key):", file=stream)
699
+ print(
700
+ '\t\treturn self._get_good_object_(self._oleobj_.Invoke(*(%d, LCID, %d, 1, key)), "Item", %s)'
701
+ % (entry.desc.memid, invoketype, resultCLSID),
702
+ file=stream,
703
+ )
704
+
705
+ if specialItems["count"]:
706
+ entry, invoketype, propArgs = specialItems["count"]
707
+ if propArgs is None:
708
+ typename = "method"
709
+ ret = self.MakeFuncMethod(entry, "__len__")
710
+ else:
711
+ typename = "property"
712
+ ret = [
713
+ "\tdef __len__(self):\n\t\treturn self._ApplyTypes_(*%s)" % propArgs
714
+ ]
715
+ print(
716
+ "\t#This class has Count() %s - allow len(ob) to provide this"
717
+ % (typename),
718
+ file=stream,
719
+ )
720
+ for line in ret:
721
+ print(line, file=stream)
722
+ # Also include a __bool__
723
+ print(
724
+ "\t#This class has a __len__ - this is needed so 'if object:' always returns TRUE.",
725
+ file=stream,
726
+ )
727
+ print("\tdef __bool__(self):", file=stream)
728
+ print("\t\treturn True", file=stream)
729
+
730
+
731
+ class CoClassItem(build.OleItem, WritableItem):
732
+ order = 5
733
+ typename = "COCLASS"
734
+
735
+ def __init__(self, typeinfo, attr, doc=None, sources=[], interfaces=[], bForUser=1):
736
+ build.OleItem.__init__(self, doc)
737
+ self.clsid = attr[0]
738
+ self.sources = sources
739
+ self.interfaces = interfaces
740
+ self.bIsDispatch = 1 # Pretend it is so it is written to the class map.
741
+
742
+ def WriteClass(self, generator):
743
+ generator.checkWriteCoClassBaseClass()
744
+ doc = self.doc
745
+ stream = generator.file
746
+ if generator.generate_type == GEN_DEMAND_CHILD:
747
+ # Some special imports we must setup.
748
+ referenced_items = []
749
+ for ref, flag in self.sources:
750
+ referenced_items.append(ref)
751
+ for ref, flag in self.interfaces:
752
+ referenced_items.append(ref)
753
+ print("import sys", file=stream)
754
+ for ref in referenced_items:
755
+ print(
756
+ f"__import__('{generator.base_mod_name}.{ref.python_name}')",
757
+ file=stream,
758
+ )
759
+ print(
760
+ "{} = sys.modules['{}.{}'].{}".format(
761
+ ref.python_name,
762
+ generator.base_mod_name,
763
+ ref.python_name,
764
+ ref.python_name,
765
+ ),
766
+ file=stream,
767
+ )
768
+ # And pretend we have written it - the name is now available as if we had!
769
+ ref.bWritten = 1
770
+ try:
771
+ progId = pythoncom.ProgIDFromCLSID(self.clsid)
772
+ print("# This CoClass is known by the name '%s'" % (progId), file=stream)
773
+ except pythoncom.com_error:
774
+ pass
775
+ print(
776
+ "class %s(CoClassBaseClass): # A CoClass" % (self.python_name), file=stream
777
+ )
778
+ if doc and doc[1]:
779
+ print("\t# " + doc[1], file=stream)
780
+ print(f"\tCLSID = {self.clsid!r}", file=stream)
781
+ print("\tcoclass_sources = [", file=stream)
782
+ defItem = None
783
+ for item, flag in self.sources:
784
+ if flag & pythoncom.IMPLTYPEFLAG_FDEFAULT:
785
+ defItem = item
786
+ # If we have written a Python class, reference the name -
787
+ # otherwise just the IID.
788
+ if item.bWritten:
789
+ key = item.python_name
790
+ else:
791
+ key = f"'{item.clsid}'" # really the iid.
792
+ print(f"\t\t{key},", file=stream)
793
+ print("\t]", file=stream)
794
+ if defItem:
795
+ if defItem.bWritten:
796
+ defName = defItem.python_name
797
+ else:
798
+ defName = f"'{defItem.clsid}'" # really the iid.
799
+ print(f"\tdefault_source = {defName}", file=stream)
800
+ print("\tcoclass_interfaces = [", file=stream)
801
+ defItem = None
802
+ for item, flag in self.interfaces:
803
+ if flag & pythoncom.IMPLTYPEFLAG_FDEFAULT: # and dual:
804
+ defItem = item
805
+ # If we have written a class, reference its name, otherwise the IID
806
+ if item.bWritten:
807
+ key = item.python_name
808
+ else:
809
+ key = f"'{item.clsid}'" # really the iid.
810
+ print(f"\t\t{key},", file=stream)
811
+ print("\t]", file=stream)
812
+ if defItem:
813
+ if defItem.bWritten:
814
+ defName = defItem.python_name
815
+ else:
816
+ defName = f"'{defItem.clsid}'" # really the iid.
817
+ print(f"\tdefault_interface = {defName}", file=stream)
818
+ self.bWritten = 1
819
+ print(file=stream)
820
+
821
+
822
+ class GeneratorProgress:
823
+ def __init__(self):
824
+ pass
825
+
826
+ def Starting(self, tlb_desc):
827
+ """Called when the process starts."""
828
+ self.tlb_desc = tlb_desc
829
+
830
+ def Finished(self):
831
+ """Called when the process is complete."""
832
+
833
+ def SetDescription(self, desc, maxticks=None):
834
+ """We are entering a major step. If maxticks, then this
835
+ is how many ticks we expect to make until finished
836
+ """
837
+
838
+ def Tick(self, desc=None):
839
+ """Minor progress step. Can provide new description if necessary"""
840
+
841
+ def VerboseProgress(self, desc):
842
+ """Verbose/Debugging output."""
843
+
844
+ def LogWarning(self, desc):
845
+ """If a warning is generated"""
846
+
847
+ def LogBeginGenerate(self, filename):
848
+ pass
849
+
850
+ def Close(self):
851
+ pass
852
+
853
+
854
+ class Generator:
855
+ def __init__(
856
+ self,
857
+ typelib,
858
+ sourceFilename,
859
+ progressObject,
860
+ bBuildHidden=1,
861
+ ):
862
+ self.bHaveWrittenDispatchBaseClass = 0
863
+ self.bHaveWrittenCoClassBaseClass = 0
864
+ self.bHaveWrittenEventBaseClass = 0
865
+ self.typelib = typelib
866
+ self.sourceFilename = sourceFilename
867
+ self.bBuildHidden = bBuildHidden
868
+ self.progress = progressObject
869
+ # These 2 are later additions and most of the code still 'print's...
870
+ self.file = None
871
+
872
+ def CollectOleItemInfosFromType(self):
873
+ ret = []
874
+ for i in range(self.typelib.GetTypeInfoCount()):
875
+ info = self.typelib.GetTypeInfo(i)
876
+ infotype = self.typelib.GetTypeInfoType(i)
877
+ doc = self.typelib.GetDocumentation(i)
878
+ attr = info.GetTypeAttr()
879
+ ret.append((info, infotype, doc, attr))
880
+ return ret
881
+
882
+ def _Build_CoClass(self, type_info_tuple):
883
+ info, infotype, doc, attr = type_info_tuple
884
+ # find the source and dispinterfaces for the coclass
885
+ child_infos = []
886
+ for j in range(attr[8]):
887
+ flags = info.GetImplTypeFlags(j)
888
+ try:
889
+ refType = info.GetRefTypeInfo(info.GetRefTypeOfImplType(j))
890
+ except pythoncom.com_error:
891
+ # Can't load a dependent typelib?
892
+ continue
893
+ refAttr = refType.GetTypeAttr()
894
+ child_infos.append(
895
+ (
896
+ info,
897
+ refAttr.typekind,
898
+ refType,
899
+ refType.GetDocumentation(-1),
900
+ refAttr,
901
+ flags,
902
+ )
903
+ )
904
+
905
+ # Done generating children - now the CoClass itself.
906
+ newItem = CoClassItem(info, attr, doc)
907
+ return newItem, child_infos
908
+
909
+ def _Build_CoClassChildren(self, coclass, coclass_info, oleItems, vtableItems):
910
+ sources = {}
911
+ interfaces = {}
912
+ for info, info_type, refType, doc, refAttr, flags in coclass_info:
913
+ # sys.stderr.write("Attr typeflags for coclass referenced object %s=%d (%d), typekind=%d\n" % (name, refAttr.wTypeFlags, refAttr.wTypeFlags & pythoncom.TYPEFLAG_FDUAL,refAttr.typekind))
914
+ if refAttr.typekind == pythoncom.TKIND_DISPATCH or (
915
+ refAttr.typekind == pythoncom.TKIND_INTERFACE
916
+ and refAttr[11] & pythoncom.TYPEFLAG_FDISPATCHABLE
917
+ ):
918
+ clsid = refAttr[0]
919
+ if clsid in oleItems:
920
+ dispItem = oleItems[clsid]
921
+ else:
922
+ dispItem = DispatchItem(refType, refAttr, doc)
923
+ oleItems[dispItem.clsid] = dispItem
924
+ dispItem.coclass_clsid = coclass.clsid
925
+ if flags & pythoncom.IMPLTYPEFLAG_FSOURCE:
926
+ dispItem.bIsSink = 1
927
+ sources[dispItem.clsid] = (dispItem, flags)
928
+ else:
929
+ interfaces[dispItem.clsid] = (dispItem, flags)
930
+ # If dual interface, make do that too.
931
+ if clsid not in vtableItems and refAttr[11] & pythoncom.TYPEFLAG_FDUAL:
932
+ refType = refType.GetRefTypeInfo(refType.GetRefTypeOfImplType(-1))
933
+ refAttr = refType.GetTypeAttr()
934
+ assert refAttr.typekind == pythoncom.TKIND_INTERFACE, (
935
+ "must be interface bynow!"
936
+ )
937
+ vtableItem = VTableItem(refType, refAttr, doc)
938
+ vtableItems[clsid] = vtableItem
939
+ coclass.sources = list(sources.values())
940
+ coclass.interfaces = list(interfaces.values())
941
+
942
+ def _Build_Interface(self, type_info_tuple):
943
+ info, infotype, doc, attr = type_info_tuple
944
+ oleItem = vtableItem = None
945
+ if infotype == pythoncom.TKIND_DISPATCH or (
946
+ infotype == pythoncom.TKIND_INTERFACE
947
+ and attr[11] & pythoncom.TYPEFLAG_FDISPATCHABLE
948
+ ):
949
+ oleItem = DispatchItem(info, attr, doc)
950
+ # If this DISPATCH interface dual, then build that too.
951
+ if attr.wTypeFlags & pythoncom.TYPEFLAG_FDUAL:
952
+ # Get the vtable interface
953
+ refhtype = info.GetRefTypeOfImplType(-1)
954
+ info = info.GetRefTypeInfo(refhtype)
955
+ attr = info.GetTypeAttr()
956
+ infotype = pythoncom.TKIND_INTERFACE
957
+ else:
958
+ infotype = None
959
+ assert infotype in [
960
+ None,
961
+ pythoncom.TKIND_INTERFACE,
962
+ ], "Must be a real interface at this point"
963
+ if infotype == pythoncom.TKIND_INTERFACE:
964
+ vtableItem = VTableItem(info, attr, doc)
965
+ return oleItem, vtableItem
966
+
967
+ def BuildOleItemsFromType(self):
968
+ assert self.bBuildHidden, (
969
+ "This code doesn't look at the hidden flag - I thought everyone set it true!?!?!"
970
+ )
971
+ oleItems = {}
972
+ enumItems = {}
973
+ recordItems = {}
974
+ vtableItems = {}
975
+
976
+ for type_info_tuple in self.CollectOleItemInfosFromType():
977
+ info, infotype, doc, attr = type_info_tuple
978
+ clsid = attr[0]
979
+ if infotype == pythoncom.TKIND_ENUM or infotype == pythoncom.TKIND_MODULE:
980
+ newItem = EnumerationItem(info, attr, doc)
981
+ enumItems[newItem.doc[0]] = newItem
982
+ # We never hide interfaces (MSAccess, for example, nominates interfaces as
983
+ # hidden, assuming that you only ever use them via the CoClass)
984
+ elif infotype in [pythoncom.TKIND_DISPATCH, pythoncom.TKIND_INTERFACE]:
985
+ if clsid not in oleItems:
986
+ oleItem, vtableItem = self._Build_Interface(type_info_tuple)
987
+ oleItems[clsid] = oleItem # Even "None" goes in here.
988
+ if vtableItem is not None:
989
+ vtableItems[clsid] = vtableItem
990
+ elif (
991
+ infotype == pythoncom.TKIND_RECORD or infotype == pythoncom.TKIND_UNION
992
+ ):
993
+ newItem = RecordItem(info, attr, doc)
994
+ recordItems[newItem.clsid] = newItem
995
+ elif infotype == pythoncom.TKIND_ALIAS:
996
+ # We don't care about alias' - handled intrinsicly.
997
+ continue
998
+ elif infotype == pythoncom.TKIND_COCLASS:
999
+ newItem, child_infos = self._Build_CoClass(type_info_tuple)
1000
+ self._Build_CoClassChildren(newItem, child_infos, oleItems, vtableItems)
1001
+ oleItems[newItem.clsid] = newItem
1002
+ else:
1003
+ self.progress.LogWarning("Unknown TKIND found: %d" % infotype)
1004
+
1005
+ return oleItems, enumItems, recordItems, vtableItems
1006
+
1007
+ def open_writer(self, filename, encoding="utf-8"):
1008
+ # A place to put code to open a file with the appropriate encoding.
1009
+ # Does *not* set self.file - just opens and returns a file.
1010
+ # Actually returns a handle to a temp file - finish_writer then deletes
1011
+ # the filename asked for and puts everything back in place. This
1012
+ # is so errors don't leave a 1/2 generated file around causing bizarre
1013
+ # errors later, and so that multiple processes writing the same file
1014
+ # don't step on each others' toes.
1015
+ # Could be a classmethod one day...
1016
+ temp_filename = self.get_temp_filename(filename)
1017
+ return open(temp_filename, "wt", encoding=encoding)
1018
+
1019
+ def finish_writer(self, filename, f, worked):
1020
+ f.close()
1021
+ temp_filename = self.get_temp_filename(filename)
1022
+ if worked:
1023
+ os.replace(temp_filename, filename)
1024
+ else:
1025
+ try:
1026
+ os.unlink(filename)
1027
+ os.unlink(temp_filename)
1028
+ except OSError:
1029
+ pass
1030
+
1031
+ def get_temp_filename(self, filename):
1032
+ return "%s.%d.temp" % (filename, os.getpid())
1033
+
1034
+ def generate(self, file, is_for_demand=0):
1035
+ if is_for_demand:
1036
+ self.generate_type = GEN_DEMAND_BASE
1037
+ else:
1038
+ self.generate_type = GEN_FULL
1039
+ self.file = file
1040
+ self.do_generate()
1041
+ self.file = None
1042
+ self.progress.Finished()
1043
+
1044
+ def do_gen_file_header(self):
1045
+ la = self.typelib.GetLibAttr()
1046
+ moduleDoc = self.typelib.GetDocumentation(-1)
1047
+ docDesc = ""
1048
+ if moduleDoc[1]:
1049
+ docDesc = moduleDoc[1]
1050
+
1051
+ # Reset all the 'per file' state
1052
+ self.bHaveWrittenDispatchBaseClass = 0
1053
+ self.bHaveWrittenCoClassBaseClass = 0
1054
+ self.bHaveWrittenEventBaseClass = 0
1055
+ # You must provide a file correctly configured for writing unicode.
1056
+ # We assert this is it may indicate somewhere in pywin32 that needs
1057
+ # upgrading.
1058
+ assert self.file.encoding, self.file
1059
+ encoding = self.file.encoding
1060
+
1061
+ print(f"# -*- coding: {encoding} -*-", file=self.file)
1062
+ print(f"# Created by makepy.py version {makepy_version}", file=self.file)
1063
+ print(
1064
+ "# By python version {}".format(sys.version.replace("\n", "-")),
1065
+ file=self.file,
1066
+ )
1067
+ if self.sourceFilename:
1068
+ print(
1069
+ f"# From type library '{os.path.split(self.sourceFilename)[1]}'",
1070
+ file=self.file,
1071
+ )
1072
+ print("# On %s" % time.ctime(time.time()), file=self.file)
1073
+
1074
+ print(build._makeDocString(docDesc), file=self.file)
1075
+
1076
+ print(f"makepy_version = {makepy_version!r}", file=self.file)
1077
+ print(f"python_version = 0x{sys.hexversion:x}", file=self.file)
1078
+ print(file=self.file)
1079
+ print(
1080
+ "import win32com.client.CLSIDToClass, pythoncom, pywintypes", file=self.file
1081
+ )
1082
+ print("import win32com.client.util", file=self.file)
1083
+ print("from pywintypes import IID", file=self.file)
1084
+ print("from win32com.client import Dispatch", file=self.file)
1085
+ print(file=self.file)
1086
+ print(
1087
+ "# The following 3 lines may need tweaking for the particular server",
1088
+ file=self.file,
1089
+ )
1090
+ print(
1091
+ "# Candidates are pythoncom.Missing, .Empty and .ArgNotFound",
1092
+ file=self.file,
1093
+ )
1094
+ print("defaultNamedOptArg=pythoncom.Empty", file=self.file)
1095
+ print("defaultNamedNotOptArg=pythoncom.Empty", file=self.file)
1096
+ print("defaultUnnamedArg=pythoncom.Empty", file=self.file)
1097
+ print(file=self.file)
1098
+ print(f"CLSID = {la[0]!r}", file=self.file)
1099
+ print(f"MajorVersion = {la[3]}", file=self.file)
1100
+ print(f"MinorVersion = {la[4]}", file=self.file)
1101
+ print(f"LibraryFlags = {la[5]}", file=self.file)
1102
+ print("LCID = " + hex(la[1]), file=self.file)
1103
+ print(file=self.file)
1104
+
1105
+ def do_generate(self):
1106
+ moduleDoc = self.typelib.GetDocumentation(-1)
1107
+ stream = self.file
1108
+ docDesc = ""
1109
+ if moduleDoc[1]:
1110
+ docDesc = moduleDoc[1]
1111
+ self.progress.Starting(docDesc)
1112
+ self.progress.SetDescription("Building definitions from type library...")
1113
+
1114
+ self.do_gen_file_header()
1115
+
1116
+ oleItems, enumItems, recordItems, vtableItems = self.BuildOleItemsFromType()
1117
+
1118
+ self.progress.SetDescription(
1119
+ "Generating...", len(oleItems) + len(enumItems) + len(vtableItems)
1120
+ )
1121
+
1122
+ # Generate the constants and their support.
1123
+ if enumItems:
1124
+ print("class constants:", file=stream)
1125
+ num_written = 0
1126
+ for oleitem in sorted(enumItems.values()):
1127
+ num_written += oleitem.WriteEnumerationItems(stream)
1128
+ self.progress.Tick()
1129
+ if not num_written:
1130
+ print("\tpass", file=stream)
1131
+ print(file=stream)
1132
+
1133
+ if self.generate_type == GEN_FULL:
1134
+ for oleitem in sorted(filter(None, oleItems.values())):
1135
+ self.progress.Tick()
1136
+ oleitem.WriteClass(self)
1137
+
1138
+ for oleitem in sorted(vtableItems.values()):
1139
+ self.progress.Tick()
1140
+ oleitem.WriteClass(self)
1141
+ else:
1142
+ self.progress.Tick(len(oleItems) + len(vtableItems))
1143
+
1144
+ print("RecordMap = {", file=stream)
1145
+ for record in recordItems.values():
1146
+ record_str = f"{record.doc[0]!r}: '{record.clsid}',"
1147
+ if record.clsid == pythoncom.IID_NULL:
1148
+ print(
1149
+ f"\t###{record_str}",
1150
+ "# Record disabled because it doesn't have a non-null GUID",
1151
+ file=stream,
1152
+ )
1153
+ else:
1154
+ print(f"\t{record_str}", file=stream)
1155
+ print("}", file=stream)
1156
+ print(file=stream)
1157
+
1158
+ # Write out _all_ my generated CLSID's in the map
1159
+ if self.generate_type == GEN_FULL:
1160
+ print("CLSIDToClassMap = {", file=stream)
1161
+ for item in oleItems.values():
1162
+ if item is not None and item.bWritten:
1163
+ print(
1164
+ f"\t'{item.clsid}' : {item.python_name},",
1165
+ file=stream,
1166
+ )
1167
+ print("}", file=stream)
1168
+ print("CLSIDToPackageMap = {}", file=stream)
1169
+ print(
1170
+ "win32com.client.CLSIDToClass.RegisterCLSIDsFromDict( CLSIDToClassMap )",
1171
+ file=stream,
1172
+ )
1173
+ print("VTablesToPackageMap = {}", file=stream)
1174
+ print("VTablesToClassMap = {", file=stream)
1175
+ for item in vtableItems.values():
1176
+ print(f"\t'{item.clsid}' : '{item.python_name}',", file=stream)
1177
+ print("}", file=stream)
1178
+ print(file=stream)
1179
+
1180
+ else:
1181
+ print("CLSIDToClassMap = {}", file=stream)
1182
+ print("CLSIDToPackageMap = {", file=stream)
1183
+ for item in oleItems.values():
1184
+ if item is not None:
1185
+ print(
1186
+ f"\t'{item.clsid}' : {item.python_name!r},",
1187
+ file=stream,
1188
+ )
1189
+ print("}", file=stream)
1190
+ print("VTablesToClassMap = {}", file=stream)
1191
+ print("VTablesToPackageMap = {", file=stream)
1192
+ for item in vtableItems.values():
1193
+ print(f"\t'{item.clsid}' : '{item.python_name}',", file=stream)
1194
+ print("}", file=stream)
1195
+ print(file=stream)
1196
+
1197
+ print(file=stream)
1198
+ # Bit of a hack - build a temp map of iteItems + vtableItems - coClasses
1199
+ map = {}
1200
+ for item in oleItems.values():
1201
+ if item is not None and not isinstance(item, CoClassItem):
1202
+ map[item.python_name] = item.clsid
1203
+ for item in vtableItems.values(): # No nones or CoClasses in this map
1204
+ map[item.python_name] = item.clsid
1205
+
1206
+ print("NamesToIIDMap = {", file=stream)
1207
+ for name, iid in map.items():
1208
+ print(f"\t'{name}' : '{iid}',", file=stream)
1209
+ print("}", file=stream)
1210
+ print(file=stream)
1211
+
1212
+ if enumItems:
1213
+ print(
1214
+ "win32com.client.constants.__dicts__.append(constants.__dict__)",
1215
+ file=stream,
1216
+ )
1217
+ print(file=stream)
1218
+
1219
+ def generate_child(self, child, dir):
1220
+ "Generate a single child. May force a few children to be built as we generate deps"
1221
+ self.generate_type = GEN_DEMAND_CHILD
1222
+
1223
+ la = self.typelib.GetLibAttr()
1224
+ lcid = la[1]
1225
+ clsid = la[0]
1226
+ major = la[3]
1227
+ minor = la[4]
1228
+ self.base_mod_name = (
1229
+ "win32com.gen_py." + str(clsid)[1:-1] + f"x{lcid}x{major}x{minor}"
1230
+ )
1231
+ try:
1232
+ # Process the type library's CoClass objects, looking for the
1233
+ # specified name, or where a child has the specified name.
1234
+ # This ensures that all interesting things (including event interfaces)
1235
+ # are generated correctly.
1236
+ oleItems = {}
1237
+ vtableItems = {}
1238
+ infos = self.CollectOleItemInfosFromType()
1239
+ found = 0
1240
+ for type_info_tuple in infos:
1241
+ info, infotype, doc, attr = type_info_tuple
1242
+ if infotype == pythoncom.TKIND_COCLASS:
1243
+ coClassItem, child_infos = self._Build_CoClass(type_info_tuple)
1244
+ found = build.MakePublicAttributeName(doc[0]) == child
1245
+ if not found:
1246
+ # OK, check the child interfaces
1247
+ for (
1248
+ info,
1249
+ info_type,
1250
+ refType,
1251
+ doc,
1252
+ refAttr,
1253
+ flags,
1254
+ ) in child_infos:
1255
+ if build.MakePublicAttributeName(doc[0]) == child:
1256
+ found = 1
1257
+ break
1258
+ if found:
1259
+ oleItems[coClassItem.clsid] = coClassItem
1260
+ self._Build_CoClassChildren(
1261
+ coClassItem, child_infos, oleItems, vtableItems
1262
+ )
1263
+ break
1264
+ if not found:
1265
+ # Doesn't appear in a class defn - look in the interface objects for it
1266
+ for type_info_tuple in infos:
1267
+ info, infotype, doc, attr = type_info_tuple
1268
+ if infotype in [
1269
+ pythoncom.TKIND_INTERFACE,
1270
+ pythoncom.TKIND_DISPATCH,
1271
+ ]:
1272
+ if build.MakePublicAttributeName(doc[0]) == child:
1273
+ found = 1
1274
+ oleItem, vtableItem = self._Build_Interface(type_info_tuple)
1275
+ oleItems[clsid] = oleItem # Even "None" goes in here.
1276
+ if vtableItem is not None:
1277
+ vtableItems[clsid] = vtableItem
1278
+
1279
+ assert found, (
1280
+ f"Can't find the '{child}' interface in the CoClasses, or the interfaces"
1281
+ )
1282
+ # Make a map of iid: dispitem, vtableitem)
1283
+ items = {}
1284
+ for key, value in oleItems.items():
1285
+ items[key] = (value, None)
1286
+ for key, value in vtableItems.items():
1287
+ existing = items.get(key, None)
1288
+ if existing is not None:
1289
+ new_val = existing[0], value
1290
+ else:
1291
+ new_val = None, value
1292
+ items[key] = new_val
1293
+
1294
+ self.progress.SetDescription("Generating...", len(items))
1295
+ for oleitem, vtableitem in items.values():
1296
+ an_item = oleitem or vtableitem
1297
+ assert not self.file, "already have a file?"
1298
+ # like makepy.py, we gen to a .temp file so failure doesn't
1299
+ # leave a 1/2 generated mess.
1300
+ out_name = os.path.join(dir, an_item.python_name) + ".py"
1301
+ worked = False
1302
+ self.file = self.open_writer(out_name)
1303
+ try:
1304
+ if oleitem is not None:
1305
+ self.do_gen_child_item(oleitem)
1306
+ if vtableitem is not None:
1307
+ self.do_gen_child_item(vtableitem)
1308
+ self.progress.Tick()
1309
+ worked = True
1310
+ finally:
1311
+ with gencache.ModuleMutex(self.base_mod_name.split(".")[-1]):
1312
+ self.finish_writer(out_name, self.file, worked)
1313
+ self.file = None
1314
+ finally:
1315
+ self.progress.Finished()
1316
+
1317
+ def do_gen_child_item(self, oleitem):
1318
+ moduleDoc = self.typelib.GetDocumentation(-1)
1319
+ docDesc = ""
1320
+ if moduleDoc[1]:
1321
+ docDesc = moduleDoc[1]
1322
+ self.progress.Starting(docDesc)
1323
+ self.progress.SetDescription("Building definitions from type library...")
1324
+ self.do_gen_file_header()
1325
+ oleitem.WriteClass(self)
1326
+ if oleitem.bWritten:
1327
+ print(
1328
+ 'win32com.client.CLSIDToClass.RegisterCLSID( "{}", {} )'.format(
1329
+ oleitem.clsid, oleitem.python_name
1330
+ ),
1331
+ file=self.file,
1332
+ )
1333
+
1334
+ def checkWriteDispatchBaseClass(self):
1335
+ if not self.bHaveWrittenDispatchBaseClass:
1336
+ print("from win32com.client import DispatchBaseClass", file=self.file)
1337
+ self.bHaveWrittenDispatchBaseClass = 1
1338
+
1339
+ def checkWriteCoClassBaseClass(self):
1340
+ if not self.bHaveWrittenCoClassBaseClass:
1341
+ print("from win32com.client import CoClassBaseClass", file=self.file)
1342
+ self.bHaveWrittenCoClassBaseClass = 1
1343
+
1344
+ def checkWriteEventBaseClass(self):
1345
+ # Not a base class as such...
1346
+ if not self.bHaveWrittenEventBaseClass:
1347
+ # Nothing to do any more!
1348
+ self.bHaveWrittenEventBaseClass = 1
1349
+
1350
+
1351
+ if __name__ == "__main__":
1352
+ print("This is a worker module. Please use makepy to generate Python files.")
loan-advisor-agent/.venv/Lib/site-packages/win32com/client/makepy.py ADDED
@@ -0,0 +1,453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Originally written by Curt Hagenlocher, and various bits
2
+ # and pieces by Mark Hammond (and now Greg Stein has had
3
+ # a go too :-)
4
+
5
+ # Note that the main worker code has been moved to genpy.py
6
+ # As this is normally run from the command line, it reparses the code each time.
7
+ # Now this is nothing more than the command line handler and public interface.
8
+
9
+ # XXX - TO DO
10
+ # XXX - Greg and Mark have some ideas for a revamp - just no
11
+ # time - if you want to help, contact us for details.
12
+ # Main idea is to drop the classes exported and move to a more
13
+ # traditional data driven model.
14
+
15
+ """Generate a .py file from an OLE TypeLibrary file.
16
+
17
+
18
+ This module is concerned only with the actual writing of
19
+ a .py file. It draws on the @build@ module, which builds
20
+ the knowledge of a COM interface.
21
+
22
+ """
23
+
24
+ usageHelp = """ \
25
+
26
+ Usage:
27
+
28
+ makepy.py [-i] [-v|q] [-h] [-u] [-o output_file] [-d] [typelib, ...]
29
+
30
+ -i -- Show information for the specified typelib.
31
+
32
+ -v -- Verbose output.
33
+
34
+ -q -- Quiet output.
35
+
36
+ -h -- Do not generate hidden methods.
37
+
38
+ -u -- Convert all Unicode objects to strings.
39
+
40
+ -o -- Create output in a specified output file. If the path leading
41
+ to the file does not exist, any missing directories will be
42
+ created.
43
+ NOTE: -o cannot be used with -d. This will generate an error.
44
+
45
+ -d -- Generate the base code now and the class code on demand.
46
+ Recommended for large type libraries.
47
+
48
+ typelib -- A TLB, DLL, OCX or anything containing COM type information.
49
+ If a typelib is not specified, a window containing a textbox
50
+ will open from which you can select a registered type
51
+ library.
52
+
53
+ Examples:
54
+
55
+ makepy.py -d
56
+
57
+ Presents a list of registered type libraries from which you can make
58
+ a selection.
59
+
60
+ makepy.py -d "Microsoft Excel 8.0 Object Library"
61
+
62
+ Generate support for the type library with the specified description
63
+ (in this case, the MS Excel object model).
64
+
65
+ """
66
+
67
+ import importlib
68
+ import os
69
+ import sys
70
+
71
+ import pythoncom
72
+ from win32com.client import Dispatch, gencache, genpy, selecttlb
73
+
74
+ bForDemandDefault = 0 # Default value of bForDemand - toggle this to change the world - see also gencache.py
75
+
76
+
77
+ def usage():
78
+ sys.stderr.write(usageHelp)
79
+ sys.exit(2)
80
+
81
+
82
+ def ShowInfo(spec):
83
+ if not spec:
84
+ tlbSpec = selecttlb.SelectTlb(excludeFlags=selecttlb.FLAG_HIDDEN)
85
+ if tlbSpec is None:
86
+ return
87
+ try:
88
+ tlb = pythoncom.LoadRegTypeLib(
89
+ tlbSpec.clsid, tlbSpec.major, tlbSpec.minor, tlbSpec.lcid
90
+ )
91
+ except pythoncom.com_error: # May be badly registered.
92
+ sys.stderr.write(
93
+ "Warning - could not load registered typelib '%s'\n" % (tlbSpec.clsid)
94
+ )
95
+ tlb = None
96
+
97
+ infos = [(tlb, tlbSpec)]
98
+ else:
99
+ infos = GetTypeLibsForSpec(spec)
100
+ for tlb, tlbSpec in infos:
101
+ desc = tlbSpec.desc
102
+ if desc is None:
103
+ if tlb is None:
104
+ desc = "<Could not load typelib %s>" % (tlbSpec.dll)
105
+ else:
106
+ desc = tlb.GetDocumentation(-1)[0]
107
+ print(desc)
108
+ print(
109
+ " {}, lcid={}, major={}, minor={}".format(
110
+ tlbSpec.clsid, tlbSpec.lcid, tlbSpec.major, tlbSpec.minor
111
+ )
112
+ )
113
+ print(" >>> # Use these commands in Python code to auto generate .py support")
114
+ print(" >>> from win32com.client import gencache")
115
+ print(
116
+ " >>> gencache.EnsureModule('{}', {}, {}, {})".format(
117
+ tlbSpec.clsid, tlbSpec.lcid, tlbSpec.major, tlbSpec.minor
118
+ )
119
+ )
120
+
121
+
122
+ class SimpleProgress(genpy.GeneratorProgress):
123
+ """A simple progress class prints its output to stderr"""
124
+
125
+ def __init__(self, verboseLevel):
126
+ self.verboseLevel = verboseLevel
127
+
128
+ def Close(self):
129
+ pass
130
+
131
+ def Finished(self):
132
+ if self.verboseLevel > 1:
133
+ sys.stderr.write("Generation complete..\n")
134
+
135
+ def SetDescription(self, desc, maxticks=None):
136
+ if self.verboseLevel:
137
+ sys.stderr.write(desc + "\n")
138
+
139
+ def Tick(self, desc=None):
140
+ pass
141
+
142
+ def VerboseProgress(self, desc, verboseLevel=2):
143
+ if self.verboseLevel >= verboseLevel:
144
+ sys.stderr.write(desc + "\n")
145
+
146
+ def LogBeginGenerate(self, filename):
147
+ self.VerboseProgress("Generating to %s" % filename, 1)
148
+
149
+ def LogWarning(self, desc):
150
+ self.VerboseProgress("WARNING: " + desc, 1)
151
+
152
+
153
+ class GUIProgress(SimpleProgress):
154
+ def __init__(self, verboseLevel):
155
+ # Import some modules we need to we can trap failure now.
156
+ import pywin # nopycln: import
157
+ import win32ui
158
+
159
+ SimpleProgress.__init__(self, verboseLevel)
160
+ self.dialog = None
161
+
162
+ def Close(self):
163
+ if self.dialog is not None:
164
+ self.dialog.Close()
165
+ self.dialog = None
166
+
167
+ def Starting(self, tlb_desc):
168
+ SimpleProgress.Starting(self, tlb_desc)
169
+ if self.dialog is None:
170
+ from pywin.dialogs import status
171
+
172
+ self.dialog = status.ThreadedStatusProgressDialog(tlb_desc)
173
+ else:
174
+ self.dialog.SetTitle(tlb_desc)
175
+
176
+ def SetDescription(self, desc, maxticks=None):
177
+ self.dialog.SetText(desc)
178
+ if maxticks:
179
+ self.dialog.SetMaxTicks(maxticks)
180
+
181
+ def Tick(self, desc=None):
182
+ self.dialog.Tick()
183
+ if desc is not None:
184
+ self.dialog.SetText(desc)
185
+
186
+
187
+ def GetTypeLibsForSpec(arg):
188
+ """Given an argument on the command line (either a file name, library
189
+ description, or ProgID of an object) return a list of actual typelibs
190
+ to use."""
191
+ typelibs = []
192
+ try:
193
+ try:
194
+ tlb = pythoncom.LoadTypeLib(arg)
195
+ spec = selecttlb.TypelibSpec(None, 0, 0, 0)
196
+ spec.FromTypelib(tlb, arg)
197
+ typelibs.append((tlb, spec))
198
+ except pythoncom.com_error:
199
+ # See if it is a description
200
+ tlbs = selecttlb.FindTlbsWithDescription(arg)
201
+ if len(tlbs) == 0:
202
+ # Maybe it is the name of a COM object?
203
+ try:
204
+ ob = Dispatch(arg)
205
+ # and if so, it must support typelib info
206
+ tlb, index = ob._oleobj_.GetTypeInfo().GetContainingTypeLib()
207
+ spec = selecttlb.TypelibSpec(None, 0, 0, 0)
208
+ spec.FromTypelib(tlb)
209
+ tlbs.append(spec)
210
+ except pythoncom.com_error:
211
+ pass
212
+ if len(tlbs) == 0:
213
+ print("Could not locate a type library matching '%s'" % (arg))
214
+ for spec in tlbs:
215
+ # Version numbers not always reliable if enumerated from registry.
216
+ # (as some libs use hex, other's don't. Both examples from MS, of course.)
217
+ if spec.dll is None:
218
+ tlb = pythoncom.LoadRegTypeLib(
219
+ spec.clsid, spec.major, spec.minor, spec.lcid
220
+ )
221
+ else:
222
+ tlb = pythoncom.LoadTypeLib(spec.dll)
223
+
224
+ # We have a typelib, but it may not be exactly what we specified
225
+ # (due to automatic version matching of COM). So we query what we really have!
226
+ attr = tlb.GetLibAttr()
227
+ spec.major = attr[3]
228
+ spec.minor = attr[4]
229
+ spec.lcid = attr[1]
230
+ typelibs.append((tlb, spec))
231
+ return typelibs
232
+ except pythoncom.com_error:
233
+ t, v, tb = sys.exc_info()
234
+ sys.stderr.write(f"Unable to load type library from '{arg}' - {v}\n")
235
+ tb = None # Storing tb in a local is a cycle!
236
+ sys.exit(1)
237
+
238
+
239
+ def GenerateFromTypeLibSpec(
240
+ typelibInfo,
241
+ file=None,
242
+ verboseLevel=None,
243
+ progressInstance=None,
244
+ bForDemand=bForDemandDefault,
245
+ bBuildHidden=1,
246
+ ):
247
+ if verboseLevel is None:
248
+ verboseLevel = 0 # By default, we use no gui and no verbose level!
249
+
250
+ if bForDemand and file is not None:
251
+ raise RuntimeError(
252
+ "You can only perform a demand-build when the output goes to the gen_py directory"
253
+ )
254
+ if isinstance(typelibInfo, tuple):
255
+ # Tuple
256
+ typelibCLSID, lcid, major, minor = typelibInfo
257
+ tlb = pythoncom.LoadRegTypeLib(typelibCLSID, major, minor, lcid)
258
+ spec = selecttlb.TypelibSpec(typelibCLSID, lcid, major, minor)
259
+ spec.FromTypelib(tlb, str(typelibCLSID))
260
+ typelibs = [(tlb, spec)]
261
+ elif isinstance(typelibInfo, selecttlb.TypelibSpec):
262
+ if typelibInfo.dll is None:
263
+ # Version numbers not always reliable if enumerated from registry.
264
+ tlb = pythoncom.LoadRegTypeLib(
265
+ typelibInfo.clsid,
266
+ typelibInfo.major,
267
+ typelibInfo.minor,
268
+ typelibInfo.lcid,
269
+ )
270
+ else:
271
+ tlb = pythoncom.LoadTypeLib(typelibInfo.dll)
272
+ typelibs = [(tlb, typelibInfo)]
273
+ elif hasattr(typelibInfo, "GetLibAttr"):
274
+ # A real typelib object!
275
+ # Could also use isinstance(typelibInfo, PyITypeLib) instead, but PyITypeLib is not directly exposed by pythoncom.
276
+ # pythoncom.TypeIIDs[pythoncom.IID_ITypeLib] seems to work
277
+ tla = typelibInfo.GetLibAttr()
278
+ guid = tla[0]
279
+ lcid = tla[1]
280
+ major = tla[3]
281
+ minor = tla[4]
282
+ spec = selecttlb.TypelibSpec(guid, lcid, major, minor)
283
+ typelibs = [(typelibInfo, spec)]
284
+ else:
285
+ typelibs = GetTypeLibsForSpec(typelibInfo)
286
+
287
+ if progressInstance is None:
288
+ progressInstance = SimpleProgress(verboseLevel)
289
+ progress = progressInstance
290
+
291
+ bToGenDir = file is None
292
+
293
+ for typelib, info in typelibs:
294
+ gen = genpy.Generator(typelib, info.dll, progress, bBuildHidden=bBuildHidden)
295
+
296
+ this_name = gencache.GetGeneratedFileName(
297
+ info.clsid, info.lcid, info.major, info.minor
298
+ )
299
+
300
+ if file is None:
301
+ full_name = os.path.join(gencache.GetGeneratePath(), this_name)
302
+ if bForDemand:
303
+ try:
304
+ os.unlink(full_name + ".py")
305
+ except OSError:
306
+ pass
307
+ try:
308
+ os.unlink(full_name + ".pyc")
309
+ except OSError:
310
+ pass
311
+ try:
312
+ os.unlink(full_name + ".pyo")
313
+ except OSError:
314
+ pass
315
+ if not os.path.isdir(full_name):
316
+ os.mkdir(full_name)
317
+ outputName = os.path.join(full_name, "__init__.py")
318
+ else:
319
+ outputName = full_name + ".py"
320
+ fileUse = gen.open_writer(outputName)
321
+ progress.LogBeginGenerate(outputName)
322
+ else:
323
+ fileUse = file
324
+
325
+ worked = False
326
+ try:
327
+ gen.generate(fileUse, bForDemand)
328
+ worked = True
329
+ finally:
330
+ if file is None:
331
+ with gencache.ModuleMutex(this_name):
332
+ gen.finish_writer(outputName, fileUse, worked)
333
+ importlib.invalidate_caches()
334
+ if bToGenDir:
335
+ progress.SetDescription("Importing module")
336
+ gencache.AddModuleToCache(info.clsid, info.lcid, info.major, info.minor)
337
+
338
+ progress.Close()
339
+
340
+
341
+ def GenerateChildFromTypeLibSpec(
342
+ child, typelibInfo, verboseLevel=None, progressInstance=None
343
+ ):
344
+ if verboseLevel is None:
345
+ verboseLevel = (
346
+ 0 # By default, we use no gui, and no verbose level for the children.
347
+ )
348
+ if isinstance(typelibInfo, tuple):
349
+ typelibCLSID, lcid, major, minor = typelibInfo
350
+ tlb = pythoncom.LoadRegTypeLib(typelibCLSID, major, minor, lcid)
351
+ else:
352
+ tlb = typelibInfo
353
+ tla = typelibInfo.GetLibAttr()
354
+ typelibCLSID = tla[0]
355
+ lcid = tla[1]
356
+ major = tla[3]
357
+ minor = tla[4]
358
+ spec = selecttlb.TypelibSpec(typelibCLSID, lcid, major, minor)
359
+ spec.FromTypelib(tlb, str(typelibCLSID))
360
+ typelibs = [(tlb, spec)]
361
+
362
+ if progressInstance is None:
363
+ progressInstance = SimpleProgress(verboseLevel)
364
+ progress = progressInstance
365
+
366
+ for typelib, info in typelibs:
367
+ dir_name = gencache.GetGeneratedFileName(
368
+ info.clsid, info.lcid, info.major, info.minor
369
+ )
370
+ dir_path_name = os.path.join(gencache.GetGeneratePath(), dir_name)
371
+ progress.LogBeginGenerate(dir_path_name)
372
+
373
+ gen = genpy.Generator(typelib, info.dll, progress)
374
+ gen.generate_child(child, dir_path_name)
375
+ progress.SetDescription("Importing module")
376
+ importlib.invalidate_caches()
377
+ with gencache.ModuleMutex(dir_name):
378
+ __import__("win32com.gen_py." + dir_name + "." + child)
379
+ progress.Close()
380
+
381
+
382
+ def main():
383
+ import getopt
384
+
385
+ hiddenSpec = 1
386
+ outputName = None
387
+ verboseLevel = 1
388
+ doit = 1
389
+ bForDemand = bForDemandDefault
390
+ try:
391
+ opts, args = getopt.getopt(sys.argv[1:], "vo:huiqd")
392
+ for o, v in opts:
393
+ if o == "-h":
394
+ hiddenSpec = 0
395
+ elif o == "-o":
396
+ outputName = v
397
+ elif o == "-v":
398
+ verboseLevel += 1
399
+ elif o == "-q":
400
+ verboseLevel -= 1
401
+ elif o == "-i":
402
+ if len(args) == 0:
403
+ ShowInfo(None)
404
+ else:
405
+ for arg in args:
406
+ ShowInfo(arg)
407
+ doit = 0
408
+ elif o == "-d":
409
+ bForDemand = not bForDemand
410
+
411
+ except getopt.error as msg:
412
+ sys.stderr.write(str(msg) + "\n")
413
+ usage()
414
+
415
+ if bForDemand and outputName is not None:
416
+ sys.stderr.write("Can not use -d and -o together\n")
417
+ usage()
418
+
419
+ if not doit:
420
+ return 0
421
+ if len(args) == 0:
422
+ rc = selecttlb.SelectTlb()
423
+ if rc is None:
424
+ sys.exit(1)
425
+ args = [rc]
426
+
427
+ if outputName is not None:
428
+ path = os.path.dirname(outputName)
429
+ if path != "" and not os.path.exists(path):
430
+ os.makedirs(path)
431
+ f = open(outputName, "wt", encoding="mbcs")
432
+
433
+ else:
434
+ f = None
435
+
436
+ for arg in args:
437
+ GenerateFromTypeLibSpec(
438
+ arg,
439
+ f,
440
+ verboseLevel=verboseLevel,
441
+ bForDemand=bForDemand,
442
+ bBuildHidden=hiddenSpec,
443
+ )
444
+
445
+ if f:
446
+ f.close()
447
+
448
+
449
+ if __name__ == "__main__":
450
+ rc = main()
451
+ if rc:
452
+ sys.exit(rc)
453
+ sys.exit(0)
loan-advisor-agent/.venv/Lib/site-packages/win32com/client/selecttlb.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utilities for selecting and enumerating the Type Libraries installed on the system"""
2
+
3
+ import pythoncom
4
+ import win32api
5
+ import win32con
6
+
7
+
8
+ class TypelibSpec:
9
+ def __init__(self, clsid, lcid, major, minor, flags=0):
10
+ self.clsid = str(clsid)
11
+ self.lcid = int(lcid)
12
+ # We avoid assuming 'major' or 'minor' are integers - when
13
+ # read from the registry there is some confusion about if
14
+ # they are base 10 or base 16 (they *should* be base 16, but
15
+ # how they are written is beyond our control.)
16
+ self.major = major
17
+ self.minor = minor
18
+ self.dll = None
19
+ self.desc = None
20
+ self.ver_desc = None
21
+ self.flags = flags
22
+
23
+ # For the SelectList
24
+ def __getitem__(self, item):
25
+ if item == 0:
26
+ return self.ver_desc
27
+ raise IndexError("Can't index me!")
28
+
29
+ def __lt__(self, other):
30
+ me = (
31
+ (self.ver_desc or "").lower(),
32
+ (self.desc or "").lower(),
33
+ self.major,
34
+ self.minor,
35
+ )
36
+ them = (
37
+ (other.ver_desc or "").lower(),
38
+ (other.desc or "").lower(),
39
+ other.major,
40
+ other.minor,
41
+ )
42
+ return me < them
43
+
44
+ def __eq__(self, other):
45
+ return (
46
+ (self.ver_desc or "").lower() == (other.ver_desc or "").lower()
47
+ and (self.desc or "").lower() == (other.desc or "").lower()
48
+ and self.major == other.major
49
+ and self.minor == other.minor
50
+ )
51
+
52
+ def Resolve(self):
53
+ if self.dll is None:
54
+ return 0
55
+ tlb = pythoncom.LoadTypeLib(self.dll)
56
+ self.FromTypelib(tlb, None)
57
+ return 1
58
+
59
+ def FromTypelib(self, typelib, dllName=None):
60
+ la = typelib.GetLibAttr()
61
+ self.clsid = str(la[0])
62
+ self.lcid = la[1]
63
+ self.major = la[3]
64
+ self.minor = la[4]
65
+ if dllName:
66
+ self.dll = dllName
67
+
68
+
69
+ def EnumKeys(root):
70
+ index = 0
71
+ ret = []
72
+ while 1:
73
+ try:
74
+ item = win32api.RegEnumKey(root, index)
75
+ except win32api.error:
76
+ break
77
+ try:
78
+ # Note this doesn't handle REG_EXPAND_SZ, but the implementation
79
+ # here doesn't need to - that is handled as the data is read.
80
+ val = win32api.RegQueryValue(root, item)
81
+ except win32api.error:
82
+ val = "" # code using this assumes a string.
83
+
84
+ ret.append((item, val))
85
+ index += 1
86
+ return ret
87
+
88
+
89
+ FLAG_RESTRICTED = 1
90
+ FLAG_CONTROL = 2
91
+ FLAG_HIDDEN = 4
92
+
93
+
94
+ def EnumTlbs(excludeFlags=0):
95
+ """Return a list of TypelibSpec objects, one for each registered library."""
96
+ key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "Typelib")
97
+ iids = EnumKeys(key)
98
+ results = []
99
+ for iid, crap in iids:
100
+ try:
101
+ key2 = win32api.RegOpenKey(key, str(iid))
102
+ except win32api.error:
103
+ # A few good reasons for this, including "access denied".
104
+ continue
105
+ for version, tlbdesc in EnumKeys(key2):
106
+ major_minor = version.split(".", 1)
107
+ if len(major_minor) < 2:
108
+ major_minor.append("0")
109
+ # For some reason, this code used to assume the values were hex.
110
+ # This seems to not be true - particularly for CDO 1.21
111
+ # *sigh* - it appears there are no rules here at all, so when we need
112
+ # to know the info, we must load the tlb by filename and request it.
113
+ # The Resolve() method on the TypelibSpec does this.
114
+ # For this reason, keep the version numbers as strings - that
115
+ # way we can't be wrong! Let code that really needs an int to work
116
+ # out what to do. FWIW, https://www.betaarchive.com/wiki/index.php?title=Microsoft_KB_Archive/816970
117
+ # is pretty clear that they *should* be hex.
118
+ major = major_minor[0]
119
+ minor = major_minor[1]
120
+ key3 = win32api.RegOpenKey(key2, str(version))
121
+ try:
122
+ # The "FLAGS" are at this point
123
+ flags = int(win32api.RegQueryValue(key3, "FLAGS"))
124
+ except (win32api.error, ValueError):
125
+ flags = 0
126
+ if flags & excludeFlags == 0:
127
+ for lcid, crap in EnumKeys(key3):
128
+ try:
129
+ lcid = int(lcid)
130
+ except ValueError: # not an LCID entry
131
+ continue
132
+ # Check for both "{lcid}\win32" and "{lcid}\win64" keys.
133
+ try:
134
+ key4 = win32api.RegOpenKey(key3, f"{lcid}\\win32")
135
+ except win32api.error:
136
+ try:
137
+ key4 = win32api.RegOpenKey(key3, f"{lcid}\\win64")
138
+ except win32api.error:
139
+ continue
140
+ try:
141
+ dll, typ = win32api.RegQueryValueEx(key4, None)
142
+ if typ == win32con.REG_EXPAND_SZ:
143
+ dll = win32api.ExpandEnvironmentStrings(dll)
144
+ except win32api.error:
145
+ dll = None
146
+ spec = TypelibSpec(iid, lcid, major, minor, flags)
147
+ spec.dll = dll
148
+ spec.desc = tlbdesc
149
+ spec.ver_desc = tlbdesc + " (" + version + ")"
150
+ results.append(spec)
151
+ return results
152
+
153
+
154
+ def FindTlbsWithDescription(desc):
155
+ """Find all installed type libraries with the specified description"""
156
+ ret = []
157
+ items = EnumTlbs()
158
+ for item in items:
159
+ if item.desc == desc:
160
+ ret.append(item)
161
+ return ret
162
+
163
+
164
+ def SelectTlb(title="Select Library", excludeFlags=0):
165
+ """Display a list of all the type libraries, and select one. Returns None if cancelled"""
166
+ import pywin.dialogs.list
167
+
168
+ items = EnumTlbs(excludeFlags)
169
+ # fixup versions - we assume hex (see __init__ above)
170
+ for i in items:
171
+ i.major = int(i.major, 16)
172
+ i.minor = int(i.minor, 16)
173
+ items.sort()
174
+ rc = pywin.dialogs.list.SelectFromLists(title, items, ["Type Library"])
175
+ if rc is None:
176
+ return None
177
+ return items[rc]
178
+
179
+
180
+ # Test code.
181
+ if __name__ == "__main__":
182
+ print(SelectTlb().__dict__)
loan-advisor-agent/.venv/Lib/site-packages/win32com/client/tlbrowse.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import commctrl
2
+ import pythoncom
3
+ import win32api
4
+ import win32con
5
+ import win32ui
6
+ from pywin.mfc import dialog
7
+
8
+
9
+ class TLBrowserException(Exception):
10
+ "TypeLib browser internal error"
11
+
12
+
13
+ error = TLBrowserException # Re-exported alias
14
+
15
+ FRAMEDLG_STD = win32con.WS_CAPTION | win32con.WS_SYSMENU
16
+ SS_STD = win32con.WS_CHILD | win32con.WS_VISIBLE
17
+ BS_STD = SS_STD | win32con.WS_TABSTOP
18
+ ES_STD = BS_STD | win32con.WS_BORDER
19
+ LBS_STD = (
20
+ ES_STD | win32con.LBS_NOTIFY | win32con.LBS_NOINTEGRALHEIGHT | win32con.WS_VSCROLL
21
+ )
22
+ CBS_STD = ES_STD | win32con.CBS_NOINTEGRALHEIGHT | win32con.WS_VSCROLL
23
+
24
+ typekindmap = {
25
+ pythoncom.TKIND_ENUM: "Enumeration",
26
+ pythoncom.TKIND_RECORD: "Record",
27
+ pythoncom.TKIND_MODULE: "Module",
28
+ pythoncom.TKIND_INTERFACE: "Interface",
29
+ pythoncom.TKIND_DISPATCH: "Dispatch",
30
+ pythoncom.TKIND_COCLASS: "CoClass",
31
+ pythoncom.TKIND_ALIAS: "Alias",
32
+ pythoncom.TKIND_UNION: "Union",
33
+ }
34
+
35
+ TypeBrowseDialog_Parent = dialog.Dialog
36
+
37
+
38
+ class TypeBrowseDialog(TypeBrowseDialog_Parent):
39
+ "Browse a type library"
40
+
41
+ IDC_TYPELIST = 1000
42
+ IDC_MEMBERLIST = 1001
43
+ IDC_PARAMLIST = 1002
44
+ IDC_LISTVIEW = 1003
45
+
46
+ def __init__(self, typefile=None):
47
+ TypeBrowseDialog_Parent.__init__(self, self.GetTemplate())
48
+ try:
49
+ if typefile:
50
+ self.tlb = pythoncom.LoadTypeLib(typefile)
51
+ else:
52
+ self.tlb = None
53
+ except pythoncom.ole_error:
54
+ self.MessageBox("The file does not contain type information")
55
+ self.tlb = None
56
+ self.HookCommand(self.CmdTypeListbox, self.IDC_TYPELIST)
57
+ self.HookCommand(self.CmdMemberListbox, self.IDC_MEMBERLIST)
58
+
59
+ def OnAttachedObjectDeath(self):
60
+ self.tlb = None
61
+ self.typeinfo = None
62
+ self.attr = None
63
+ return TypeBrowseDialog_Parent.OnAttachedObjectDeath(self)
64
+
65
+ def _SetupMenu(self):
66
+ menu = win32ui.CreateMenu()
67
+ flags = win32con.MF_STRING | win32con.MF_ENABLED
68
+ menu.AppendMenu(flags, win32ui.ID_FILE_OPEN, "&Open...")
69
+ menu.AppendMenu(flags, win32con.IDCANCEL, "&Close")
70
+ mainMenu = win32ui.CreateMenu()
71
+ mainMenu.AppendMenu(flags | win32con.MF_POPUP, menu.GetHandle(), "&File")
72
+ self.SetMenu(mainMenu)
73
+ self.HookCommand(self.OnFileOpen, win32ui.ID_FILE_OPEN)
74
+
75
+ def OnFileOpen(self, id, code):
76
+ openFlags = win32con.OFN_OVERWRITEPROMPT | win32con.OFN_FILEMUSTEXIST
77
+ fspec = "Type Libraries (*.tlb, *.olb)|*.tlb;*.olb|OCX Files (*.ocx)|*.ocx|DLL's (*.dll)|*.dll|All Files (*.*)|*.*||"
78
+ dlg = win32ui.CreateFileDialog(1, None, None, openFlags, fspec)
79
+ if dlg.DoModal() == win32con.IDOK:
80
+ try:
81
+ self.tlb = pythoncom.LoadTypeLib(dlg.GetPathName())
82
+ except pythoncom.ole_error:
83
+ self.MessageBox("The file does not contain type information")
84
+ self.tlb = None
85
+ self._SetupTLB()
86
+
87
+ def OnInitDialog(self):
88
+ self._SetupMenu()
89
+ self.typelb = self.GetDlgItem(self.IDC_TYPELIST)
90
+ self.memberlb = self.GetDlgItem(self.IDC_MEMBERLIST)
91
+ self.paramlb = self.GetDlgItem(self.IDC_PARAMLIST)
92
+ self.listview = self.GetDlgItem(self.IDC_LISTVIEW)
93
+
94
+ # Setup the listview columns
95
+ itemDetails = (commctrl.LVCFMT_LEFT, 100, "Item", 0)
96
+ self.listview.InsertColumn(0, itemDetails)
97
+ itemDetails = (commctrl.LVCFMT_LEFT, 1024, "Details", 0)
98
+ self.listview.InsertColumn(1, itemDetails)
99
+
100
+ if self.tlb is None:
101
+ self.OnFileOpen(None, None)
102
+ else:
103
+ self._SetupTLB()
104
+ return TypeBrowseDialog_Parent.OnInitDialog(self)
105
+
106
+ def _SetupTLB(self):
107
+ self.typelb.ResetContent()
108
+ self.memberlb.ResetContent()
109
+ self.paramlb.ResetContent()
110
+ self.typeinfo = None
111
+ self.attr = None
112
+ if self.tlb is None:
113
+ return
114
+ n = self.tlb.GetTypeInfoCount()
115
+ for i in range(n):
116
+ self.typelb.AddString(self.tlb.GetDocumentation(i)[0])
117
+
118
+ def _SetListviewTextItems(self, items):
119
+ self.listview.DeleteAllItems()
120
+ index = -1
121
+ for item in items:
122
+ index = self.listview.InsertItem(index + 1, item[0])
123
+ data = item[1]
124
+ if data is None:
125
+ data = ""
126
+ self.listview.SetItemText(index, 1, data)
127
+
128
+ def SetupAllInfoTypes(self):
129
+ infos = self._GetMainInfoTypes() + self._GetMethodInfoTypes()
130
+ self._SetListviewTextItems(infos)
131
+
132
+ def _GetMainInfoTypes(self):
133
+ pos = self.typelb.GetCurSel()
134
+ if pos < 0:
135
+ return []
136
+ docinfo = self.tlb.GetDocumentation(pos)
137
+ infos = [("GUID", str(self.attr[0]))]
138
+ infos.append(("Help File", docinfo[3]))
139
+ infos.append(("Help Context", str(docinfo[2])))
140
+ try:
141
+ infos.append(("Type Kind", typekindmap[self.tlb.GetTypeInfoType(pos)]))
142
+ except:
143
+ pass
144
+
145
+ info = self.tlb.GetTypeInfo(pos)
146
+ attr = info.GetTypeAttr()
147
+ infos.append(("Attributes", str(attr)))
148
+
149
+ for j in range(attr[8]):
150
+ flags = info.GetImplTypeFlags(j)
151
+ refInfo = info.GetRefTypeInfo(info.GetRefTypeOfImplType(j))
152
+ doc = refInfo.GetDocumentation(-1)
153
+ attr = refInfo.GetTypeAttr()
154
+ typeKind = attr[5]
155
+ typeFlags = attr[11]
156
+
157
+ desc = doc[0]
158
+ desc += ", Flags=0x{:x}, typeKind=0x{:x}, typeFlags=0x{:x}".format(
159
+ flags, typeKind, typeFlags
160
+ )
161
+ if flags & pythoncom.IMPLTYPEFLAG_FSOURCE:
162
+ desc += "(Source)"
163
+ infos.append(("Implements", desc))
164
+
165
+ return infos
166
+
167
+ def _GetMethodInfoTypes(self):
168
+ pos = self.memberlb.GetCurSel()
169
+ if pos < 0:
170
+ return []
171
+
172
+ realPos, isMethod = self._GetRealMemberPos(pos)
173
+ ret = []
174
+ if isMethod:
175
+ funcDesc = self.typeinfo.GetFuncDesc(realPos)
176
+ id = funcDesc[0]
177
+ ret.append(("Func Desc", str(funcDesc)))
178
+ else:
179
+ id = self.typeinfo.GetVarDesc(realPos)[0]
180
+
181
+ docinfo = self.typeinfo.GetDocumentation(id)
182
+ ret.append(("Help String", docinfo[1]))
183
+ ret.append(("Help Context", str(docinfo[2])))
184
+ return ret
185
+
186
+ def CmdTypeListbox(self, id, code):
187
+ if code == win32con.LBN_SELCHANGE:
188
+ pos = self.typelb.GetCurSel()
189
+ if pos >= 0:
190
+ self.memberlb.ResetContent()
191
+ self.typeinfo = self.tlb.GetTypeInfo(pos)
192
+ self.attr = self.typeinfo.GetTypeAttr()
193
+ for i in range(self.attr[7]):
194
+ id = self.typeinfo.GetVarDesc(i)[0]
195
+ self.memberlb.AddString(self.typeinfo.GetNames(id)[0])
196
+ for i in range(self.attr[6]):
197
+ id = self.typeinfo.GetFuncDesc(i)[0]
198
+ self.memberlb.AddString(self.typeinfo.GetNames(id)[0])
199
+ self.SetupAllInfoTypes()
200
+ return 1
201
+
202
+ def _GetRealMemberPos(self, pos):
203
+ pos = self.memberlb.GetCurSel()
204
+ if pos >= self.attr[7]:
205
+ return pos - self.attr[7], 1
206
+ elif pos >= 0:
207
+ return pos, 0
208
+ else:
209
+ raise error("The position is not valid")
210
+
211
+ def CmdMemberListbox(self, id, code):
212
+ if code == win32con.LBN_SELCHANGE:
213
+ self.paramlb.ResetContent()
214
+ pos = self.memberlb.GetCurSel()
215
+ realPos, isMethod = self._GetRealMemberPos(pos)
216
+ if isMethod:
217
+ id = self.typeinfo.GetFuncDesc(realPos)[0]
218
+ names = self.typeinfo.GetNames(id)
219
+ for i in range(len(names)):
220
+ if i > 0:
221
+ self.paramlb.AddString(names[i])
222
+ self.SetupAllInfoTypes()
223
+ return 1
224
+
225
+ def GetTemplate(self):
226
+ "Return the template used to create this dialog"
227
+
228
+ w = 272 # Dialog width
229
+ h = 192 # Dialog height
230
+ style = (
231
+ FRAMEDLG_STD
232
+ | win32con.WS_VISIBLE
233
+ | win32con.DS_SETFONT
234
+ | win32con.WS_MINIMIZEBOX
235
+ )
236
+ template = [
237
+ ["Type Library Browser", (0, 0, w, h), style, None, (8, "Helv")],
238
+ ]
239
+ template.append([130, "&Type", -1, (10, 10, 62, 9), SS_STD | win32con.SS_LEFT])
240
+ template.append([131, None, self.IDC_TYPELIST, (10, 20, 80, 80), LBS_STD])
241
+ template.append(
242
+ [130, "&Members", -1, (100, 10, 62, 9), SS_STD | win32con.SS_LEFT]
243
+ )
244
+ template.append([131, None, self.IDC_MEMBERLIST, (100, 20, 80, 80), LBS_STD])
245
+ template.append(
246
+ [130, "&Parameters", -1, (190, 10, 62, 9), SS_STD | win32con.SS_LEFT]
247
+ )
248
+ template.append([131, None, self.IDC_PARAMLIST, (190, 20, 75, 80), LBS_STD])
249
+
250
+ lvStyle = (
251
+ SS_STD
252
+ | commctrl.LVS_REPORT
253
+ | commctrl.LVS_AUTOARRANGE
254
+ | commctrl.LVS_ALIGNLEFT
255
+ | win32con.WS_BORDER
256
+ | win32con.WS_TABSTOP
257
+ )
258
+ template.append(
259
+ ["SysListView32", "", self.IDC_LISTVIEW, (10, 110, 255, 65), lvStyle]
260
+ )
261
+
262
+ return template
263
+
264
+
265
+ if __name__ == "__main__":
266
+ import sys
267
+
268
+ fname = None
269
+ try:
270
+ fname = sys.argv[1]
271
+ except:
272
+ pass
273
+ dlg = TypeBrowseDialog(fname)
274
+ if win32api.GetConsoleTitle(): # empty string w/o console
275
+ dlg.DoModal()
276
+ else:
277
+ dlg.CreateWindow(win32ui.GetMainFrame())
loan-advisor-agent/.venv/Lib/site-packages/win32com/client/util.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """General client side utilities.
2
+
3
+ This module contains utility functions, used primarily by advanced COM
4
+ programmers, or other COM modules.
5
+ """
6
+
7
+ import pythoncom
8
+ from win32com.client import _get_good_object_
9
+
10
+ PyIDispatchType = pythoncom.TypeIIDs[pythoncom.IID_IDispatch]
11
+
12
+
13
+ def WrapEnum(ob, resultCLSID=None):
14
+ """Wrap an object in a VARIANT enumerator.
15
+
16
+ All VT_DISPATCHs returned by the enumerator are converted to wrapper objects
17
+ (which may be either a class instance, or a dynamic.Dispatch type object).
18
+
19
+ """
20
+ if not isinstance(ob, pythoncom.TypeIIDs[pythoncom.IID_IEnumVARIANT]):
21
+ ob = ob.QueryInterface(pythoncom.IID_IEnumVARIANT)
22
+ return EnumVARIANT(ob, resultCLSID)
23
+
24
+
25
+ class Enumerator:
26
+ """A class that provides indexed access into an Enumerator
27
+
28
+ By wrapping a PyIEnum* object in this class, you can perform
29
+ natural looping and indexing into the Enumerator.
30
+
31
+ Looping is very efficient, but it should be noted that although random
32
+ access is supported, the underlying object is still an enumerator, so
33
+ this will force many reset-and-seek operations to find the requested index.
34
+
35
+ """
36
+
37
+ def __init__(self, enum):
38
+ self._oleobj_ = enum # a PyIEnumVARIANT
39
+ self.index = -1
40
+
41
+ def __getitem__(self, index):
42
+ return self.__GetIndex(index)
43
+
44
+ def __call__(self, index):
45
+ return self.__GetIndex(index)
46
+
47
+ def __GetIndex(self, index):
48
+ if not isinstance(index, int):
49
+ raise TypeError("Only integer indexes are supported for enumerators")
50
+ # NOTE
51
+ # In this context, self.index is users purely as a flag to say
52
+ # "am I still in sequence". The user may call Next() or Reset() if they
53
+ # so choose, in which case self.index will not be correct (although we
54
+ # still want to stay in sequence)
55
+ if index != self.index + 1:
56
+ # Index requested out of sequence.
57
+ self._oleobj_.Reset()
58
+ if index:
59
+ self._oleobj_.Skip(
60
+ index
61
+ ) # if asked for item 1, must skip 1, Python always zero based.
62
+ self.index = index
63
+ result = self._oleobj_.Next(1)
64
+ if len(result):
65
+ return self._make_retval_(result[0])
66
+ raise IndexError("list index out of range")
67
+
68
+ def Next(self, count=1):
69
+ ret = self._oleobj_.Next(count)
70
+ realRets = []
71
+ for r in ret:
72
+ realRets.append(self._make_retval_(r))
73
+ return tuple(realRets) # Convert back to tuple.
74
+
75
+ def Reset(self):
76
+ return self._oleobj_.Reset()
77
+
78
+ def Clone(self):
79
+ return self.__class__(self._oleobj_.Clone(), self.resultCLSID)
80
+
81
+ def _make_retval_(self, result):
82
+ return result
83
+
84
+
85
+ class EnumVARIANT(Enumerator):
86
+ def __init__(self, enum, resultCLSID=None):
87
+ self.resultCLSID = resultCLSID
88
+ Enumerator.__init__(self, enum)
89
+
90
+ def _make_retval_(self, result):
91
+ return _get_good_object_(result, resultCLSID=self.resultCLSID)
92
+
93
+
94
+ class Iterator:
95
+ def __init__(self, enum, resultCLSID=None):
96
+ self.resultCLSID = resultCLSID
97
+ self._iter_ = iter(enum.QueryInterface(pythoncom.IID_IEnumVARIANT))
98
+
99
+ def __iter__(self):
100
+ return self
101
+
102
+ def __next__(self):
103
+ return _get_good_object_(next(self._iter_), resultCLSID=self.resultCLSID)
loan-advisor-agent/.venv/Lib/site-packages/win32com/demos/__init__.py ADDED
File without changes
loan-advisor-agent/.venv/Lib/site-packages/win32com/demos/connect.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Implements _both_ a connectable client, and a connectable server.
2
+ #
3
+ # Note that we cheat just a little - the Server in this demo is not created
4
+ # via Normal COM - this means we can avoid registering the server.
5
+ # However, the server _is_ accessed as a COM object - just the creation
6
+ # is cheated on - so this is still working as a fully-fledged server.
7
+
8
+ import pythoncom
9
+ import pywintypes
10
+ import win32com.server.connect
11
+ import win32com.server.util
12
+
13
+ # This is the IID of the Events interface both Client and Server support.
14
+ IID_IConnectDemoEvents = pywintypes.IID("{A4988850-49C3-11d0-AE5D-52342E000000}")
15
+
16
+ # The server which implements
17
+ # Create a connectable class, that has a single public method
18
+ # 'DoIt', which echos to a single sink 'DoneIt'
19
+
20
+
21
+ class ConnectableServer(win32com.server.connect.ConnectableServer):
22
+ _public_methods_ = [
23
+ "DoIt"
24
+ ] + win32com.server.connect.ConnectableServer._public_methods_
25
+ _connect_interfaces_ = [IID_IConnectDemoEvents]
26
+
27
+ # The single public method that the client can call on us
28
+ # (ie, as a normal COM server, this exposes just this single method.
29
+ def DoIt(self, arg):
30
+ # Simply broadcast a notification.
31
+ self._BroadcastNotify(self.NotifyDoneIt, (arg,))
32
+
33
+ def NotifyDoneIt(self, interface, arg):
34
+ interface.Invoke(1000, 0, pythoncom.DISPATCH_METHOD, 1, arg)
35
+
36
+
37
+ # Here is the client side of the connection world.
38
+ # Define a COM object which implements the methods defined by the
39
+ # IConnectDemoEvents interface.
40
+ class ConnectableClient:
41
+ # This is another cheat - I _know_ the server defines the "DoneIt" event
42
+ # as DISPID==1000 - I also know from the implementation details of COM
43
+ # that the first method in _public_methods_ gets 1000.
44
+ # Normally some explicit DISPID->Method mapping is required.
45
+ _public_methods_ = ["OnDoneIt"]
46
+
47
+ def __init__(self):
48
+ self.last_event_arg = None
49
+
50
+ # A client must implement QI, and respond to a query for the Event interface.
51
+ # In addition, it must provide a COM object (which server.util.wrap) does.
52
+ def _query_interface_(self, iid):
53
+ # Note that this seems like a necessary hack. I am responding to IID_IConnectDemoEvents
54
+ # but only creating an IDispatch gateway object.
55
+ if iid == IID_IConnectDemoEvents:
56
+ return win32com.server.util.wrap(self)
57
+
58
+ # And here is our event method which gets called.
59
+ def OnDoneIt(self, arg):
60
+ self.last_event_arg = arg
61
+
62
+
63
+ def CheckEvent(server, client, val, verbose):
64
+ client.last_event_arg = None
65
+ server.DoIt(val)
66
+ if client.last_event_arg != val:
67
+ raise RuntimeError(f"Sent {val!r}, but got back {client.last_event_arg!r}")
68
+ if verbose:
69
+ print("Sent and received %r" % val)
70
+
71
+
72
+ # A simple test script for all this.
73
+ # In the real world, it is likely that the code controlling the server
74
+ # will be in the same class as that getting the notifications.
75
+ def test(verbose=0):
76
+ import win32com.client.connect
77
+ import win32com.client.dynamic
78
+ import win32com.server.policy
79
+
80
+ server = win32com.client.dynamic.Dispatch(
81
+ win32com.server.util.wrap(ConnectableServer())
82
+ )
83
+ connection = win32com.client.connect.SimpleConnection()
84
+ client = ConnectableClient()
85
+ connection.Connect(server, client, IID_IConnectDemoEvents)
86
+ CheckEvent(server, client, "Hello", verbose)
87
+ CheckEvent(server, client, b"Here is a null>\x00<", verbose)
88
+ CheckEvent(server, client, "Here is a null>\x00<", verbose)
89
+ val = "test-\xe0\xf2" # 2 extended characters.
90
+ CheckEvent(server, client, val, verbose)
91
+ if verbose:
92
+ print("Everything seemed to work!")
93
+ # Aggressive memory leak checking (ie, do nothing!) :-) All should cleanup OK???
94
+
95
+
96
+ if __name__ == "__main__":
97
+ test(1)
loan-advisor-agent/.venv/Lib/site-packages/win32com/demos/dump_clipboard.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pythoncom
2
+ import win32con
3
+
4
+ formats = """CF_TEXT CF_BITMAP CF_METAFILEPICT CF_SYLK CF_DIF CF_TIFF
5
+ CF_OEMTEXT CF_DIB CF_PALETTE CF_PENDATA CF_RIFF CF_WAVE
6
+ CF_UNICODETEXT CF_ENHMETAFILE CF_HDROP CF_LOCALE CF_MAX
7
+ CF_OWNERDISPLAY CF_DSPTEXT CF_DSPBITMAP CF_DSPMETAFILEPICT
8
+ CF_DSPENHMETAFILE""".split()
9
+ format_name_map = {}
10
+ for f in formats:
11
+ val = getattr(win32con, f)
12
+ format_name_map[val] = f
13
+
14
+ tymeds = [attr for attr in pythoncom.__dict__ if attr.startswith("TYMED_")]
15
+
16
+
17
+ def DumpClipboard():
18
+ do = pythoncom.OleGetClipboard()
19
+ print("Dumping all clipboard formats...")
20
+ for fe in do.EnumFormatEtc():
21
+ fmt, td, aspect, index, tymed = fe
22
+ tymeds_this = [
23
+ getattr(pythoncom, t) for t in tymeds if tymed & getattr(pythoncom, t)
24
+ ]
25
+ print("Clipboard format", format_name_map.get(fmt, str(fmt)))
26
+ for t_this in tymeds_this:
27
+ # As we are enumerating there should be no need to call
28
+ # QueryGetData, but we do anyway!
29
+ fetc_query = fmt, td, aspect, index, t_this
30
+ try:
31
+ do.QueryGetData(fetc_query)
32
+ except pythoncom.com_error:
33
+ print("Eeek - QGD indicated failure for tymed", t_this)
34
+ # now actually get it.
35
+ try:
36
+ medium = do.GetData(fetc_query)
37
+ except pythoncom.com_error as exc:
38
+ print("Failed to get the clipboard data:", exc)
39
+ continue
40
+ if medium.tymed == pythoncom.TYMED_GDI:
41
+ data = "GDI handle %d" % medium.data
42
+ elif medium.tymed == pythoncom.TYMED_MFPICT:
43
+ data = "METAFILE handle %d" % medium.data
44
+ elif medium.tymed == pythoncom.TYMED_ENHMF:
45
+ data = "ENHMETAFILE handle %d" % medium.data
46
+ elif medium.tymed == pythoncom.TYMED_HGLOBAL:
47
+ data = "%d bytes via HGLOBAL" % len(medium.data)
48
+ elif medium.tymed == pythoncom.TYMED_FILE:
49
+ data = "filename '%s'" % data
50
+ elif medium.tymed == pythoncom.TYMED_ISTREAM:
51
+ stream = medium.data
52
+ stream.Seek(0, 0)
53
+ bytes = 0
54
+ while 1:
55
+ chunk = stream.Read(4096)
56
+ if not chunk:
57
+ break
58
+ bytes += len(chunk)
59
+ data = "%d bytes via IStream" % bytes
60
+ elif medium.tymed == pythoncom.TYMED_ISTORAGE:
61
+ data = "a IStorage"
62
+ else:
63
+ data = "*** unknown tymed!"
64
+ print(" -> got", data)
65
+ do = None
66
+
67
+
68
+ if __name__ == "__main__":
69
+ DumpClipboard()
70
+ if pythoncom._GetInterfaceCount() + pythoncom._GetGatewayCount():
71
+ print(
72
+ "XXX - Leaving with %d/%d COM objects alive"
73
+ % (pythoncom._GetInterfaceCount(), pythoncom._GetGatewayCount())
74
+ )
loan-advisor-agent/.venv/Lib/site-packages/win32com/demos/eventsApartmentThreaded.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # A sample originally provided by Richard Bell, and modified by Mark Hammond.
2
+
3
+ # This sample demonstrates how to use COM events in an aparment-threaded
4
+ # world. In this world, COM itself ensures that all calls to and events
5
+ # from an object happen on the same thread that created the object, even
6
+ # if they originated from different threads. For this cross-thread
7
+ # marshalling to work, this main thread *must* run a "message-loop" (ie,
8
+ # a loop fetching and dispatching Windows messages). Without such message
9
+ # processing, dead-locks can occur.
10
+
11
+ # See also eventsFreeThreaded.py for how to do this in a free-threaded
12
+ # world where these marshalling considerations do not exist.
13
+
14
+ # NOTE: This example uses Internet Explorer, but it should not be considerd
15
+ # a "best-practices" for writing against IE events, but for working with
16
+ # events in general. For example:
17
+ # * The first OnDocumentComplete event is not a reliable indicator that the
18
+ # URL has completed loading
19
+ # * As we are demonstrating the most efficient way of handling events, when
20
+ # running this sample you will see an IE Windows briefly appear, but
21
+ # vanish without ever being repainted.
22
+
23
+ import time
24
+
25
+ # sys.coinit_flags not set, so pythoncom initializes apartment-threaded.
26
+ import pythoncom
27
+ import win32api
28
+ import win32com.client
29
+ import win32event
30
+
31
+
32
+ class ExplorerEvents:
33
+ def __init__(self):
34
+ self.event = win32event.CreateEvent(None, 0, 0, None)
35
+
36
+ def OnDocumentComplete(self, pDisp=pythoncom.Empty, URL=pythoncom.Empty):
37
+ thread = win32api.GetCurrentThreadId()
38
+ print("OnDocumentComplete event processed on thread %d" % thread)
39
+ # Set the event our main thread is waiting on.
40
+ win32event.SetEvent(self.event)
41
+
42
+ def OnQuit(self):
43
+ thread = win32api.GetCurrentThreadId()
44
+ print("OnQuit event processed on thread %d" % thread)
45
+ win32event.SetEvent(self.event)
46
+
47
+
48
+ def WaitWhileProcessingMessages(event, timeout=2):
49
+ start = time.perf_counter()
50
+ while True:
51
+ # Wake 4 times a second - we can't just specify the
52
+ # full timeout here, as then it would reset for every
53
+ # message we process.
54
+ rc = win32event.MsgWaitForMultipleObjects(
55
+ (event,), 0, 250, win32event.QS_ALLEVENTS
56
+ )
57
+ if rc == win32event.WAIT_OBJECT_0:
58
+ # event signalled - stop now!
59
+ return True
60
+ if (time.perf_counter() - start) > timeout:
61
+ # Timeout expired.
62
+ return False
63
+ # must be a message.
64
+ pythoncom.PumpWaitingMessages()
65
+
66
+
67
+ def TestExplorerEvents():
68
+ iexplore = win32com.client.DispatchWithEvents(
69
+ "InternetExplorer.Application", ExplorerEvents
70
+ )
71
+
72
+ thread = win32api.GetCurrentThreadId()
73
+ print("TestExplorerEvents created IE object on thread %d" % thread)
74
+
75
+ iexplore.Visible = 1
76
+ try:
77
+ iexplore.Navigate(win32api.GetFullPathName("..\\readme.html"))
78
+ except pythoncom.com_error as details:
79
+ print("Warning - could not open the test HTML file", details)
80
+
81
+ # Wait for the event to be signalled while pumping messages.
82
+ if not WaitWhileProcessingMessages(iexplore.event):
83
+ print("Document load event FAILED to fire!!!")
84
+
85
+ iexplore.Quit()
86
+ #
87
+ # Give IE a chance to shutdown, else it can get upset on fast machines.
88
+ # Note, Quit generates events. Although this test does NOT catch them
89
+ # it is NECESSARY to pump messages here instead of a sleep so that the Quit
90
+ # happens properly!
91
+ if not WaitWhileProcessingMessages(iexplore.event):
92
+ print("OnQuit event FAILED to fire!!!")
93
+
94
+ iexplore = None
95
+
96
+
97
+ if __name__ == "__main__":
98
+ TestExplorerEvents()
loan-advisor-agent/.venv/Lib/site-packages/win32com/demos/eventsFreeThreaded.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # A sample originally provided by Richard Bell, and modified by Mark Hammond.
2
+
3
+ # This sample demonstrates how to use COM events in a free-threaded world.
4
+ # In this world, there is no need to marshall calls across threads, so
5
+ # no message loops are needed at all. This means regular cross-thread
6
+ # sychronization can be used. In this sample we just wait on win32 event
7
+ # objects.
8
+
9
+ # See also ieEventsApartmentThreaded.py for how to do this in an
10
+ # aparment-threaded world, where thread-marshalling complicates things.
11
+
12
+ # NOTE: This example uses Internet Explorer, but it should not be considerd
13
+ # a "best-practices" for writing against IE events, but for working with
14
+ # events in general. For example:
15
+ # * The first OnDocumentComplete event is not a reliable indicator that the
16
+ # URL has completed loading
17
+ # * As we are demonstrating the most efficient way of handling events, when
18
+ # running this sample you will see an IE Windows briefly appear, but
19
+ # vanish without ever being repainted.
20
+
21
+ import sys
22
+
23
+ sys.coinit_flags = 0 # specify free threading
24
+
25
+
26
+ import pythoncom
27
+ import win32api
28
+ import win32com.client
29
+ import win32event
30
+
31
+
32
+ # The print statements indicate that COM has actually started another thread
33
+ # and will deliver the events to that thread (ie, the events do not actually
34
+ # fire on our main thread.
35
+ class ExplorerEvents:
36
+ def __init__(self):
37
+ # We reuse this event for all events.
38
+ self.event = win32event.CreateEvent(None, 0, 0, None)
39
+
40
+ def OnDocumentComplete(self, pDisp=pythoncom.Empty, URL=pythoncom.Empty):
41
+ #
42
+ # Caution: Since the main thread and events thread(s) are different
43
+ # it may be necessary to serialize access to shared data. Because
44
+ # this is a simple test case, that is not required here. Your
45
+ # situation may be different. Caveat programmer.
46
+ #
47
+ thread = win32api.GetCurrentThreadId()
48
+ print("OnDocumentComplete event processed on thread %d" % thread)
49
+ # Set the event our main thread is waiting on.
50
+ win32event.SetEvent(self.event)
51
+
52
+ def OnQuit(self):
53
+ thread = win32api.GetCurrentThreadId()
54
+ print("OnQuit event processed on thread %d" % thread)
55
+ win32event.SetEvent(self.event)
56
+
57
+
58
+ def TestExplorerEvents():
59
+ iexplore = win32com.client.DispatchWithEvents(
60
+ "InternetExplorer.Application", ExplorerEvents
61
+ )
62
+
63
+ thread = win32api.GetCurrentThreadId()
64
+ print("TestExplorerEvents created IE object on thread %d" % thread)
65
+
66
+ iexplore.Visible = 1
67
+ try:
68
+ iexplore.Navigate(win32api.GetFullPathName("..\\readme.html"))
69
+ except pythoncom.com_error as details:
70
+ print("Warning - could not open the test HTML file", details)
71
+
72
+ # In this free-threaded example, we can simply wait until an event has
73
+ # been set - we will give it 2 seconds before giving up.
74
+ rc = win32event.WaitForSingleObject(iexplore.event, 2000)
75
+ if rc != win32event.WAIT_OBJECT_0:
76
+ print("Document load event FAILED to fire!!!")
77
+
78
+ iexplore.Quit()
79
+ # Now we can do the same thing to wait for exit!
80
+ # Although Quit generates events, in this free-threaded world we
81
+ # do *not* need to run any message pumps.
82
+
83
+ rc = win32event.WaitForSingleObject(iexplore.event, 2000)
84
+ if rc != win32event.WAIT_OBJECT_0:
85
+ print("OnQuit event FAILED to fire!!!")
86
+
87
+ iexplore = None
88
+ print("Finished the IE event sample!")
89
+
90
+
91
+ if __name__ == "__main__":
92
+ TestExplorerEvents()
loan-advisor-agent/.venv/Lib/site-packages/win32com/demos/excelAddin.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # A demo plugin for Microsoft Excel
2
+ #
3
+ # This addin simply adds a new button to the main Excel toolbar,
4
+ # and displays a message box when clicked. Thus, it demonstrates
5
+ # how to plug in to Excel itself, and hook Excel events.
6
+ #
7
+ #
8
+ # To register the addin, simply execute:
9
+ # excelAddin.py
10
+ # This will install the COM server, and write the necessary
11
+ # AddIn key to Excel
12
+ #
13
+ # To unregister completely:
14
+ # excelAddin.py --unregister
15
+ #
16
+ # To debug, execute:
17
+ # excelAddin.py --debug
18
+ #
19
+ # Then open Pythonwin, and select "Tools->Trace Collector Debugging Tool"
20
+ # Restart excel, and you should see some output generated.
21
+ #
22
+ # NOTE: If the AddIn fails with an error, Excel will re-register
23
+ # the addin to not automatically load next time Excel starts. To
24
+ # correct this, simply re-register the addin (see above)
25
+ #
26
+ # Author <ekoome@yahoo.com> Eric Koome
27
+ # Copyright (c) 2003 Wavecom Inc. All rights reserved
28
+ #
29
+ # Redistribution and use in source and binary forms, with or without
30
+ # modification, are permitted provided that the following conditions
31
+ # are met:
32
+ #
33
+ # 1. Redistributions of source code must retain the above copyright
34
+ # notice, this list of conditions and the following disclaimer.
35
+ #
36
+ # THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
37
+ # WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38
+ # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39
+ # DISCLAIMED. IN NO EVENT SHALL ERIC KOOME OR
40
+ # ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41
+ # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
42
+ # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
43
+ # USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
44
+ # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45
+ # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46
+ # OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47
+ # SUCH DAMAGE.
48
+
49
+ import sys
50
+
51
+ import pythoncom
52
+ from win32com import universal
53
+ from win32com.client import DispatchWithEvents, constants, gencache
54
+
55
+ # Support for COM objects we use.
56
+ gencache.EnsureModule(
57
+ "{00020813-0000-0000-C000-000000000046}", 0, 1, 3, bForDemand=True
58
+ ) # Excel 9
59
+ gencache.EnsureModule(
60
+ "{2DF8D04C-5BFA-101B-BDE5-00AA0044DE52}", 0, 2, 1, bForDemand=True
61
+ ) # Office 9
62
+
63
+ # The TLB defining the interfaces we implement
64
+ universal.RegisterInterfaces(
65
+ "{AC0714F2-3D04-11D1-AE7D-00A0C90F26F4}", 0, 1, 0, ["_IDTExtensibility2"]
66
+ )
67
+
68
+
69
+ class ButtonEvent:
70
+ def OnClick(self, button, cancel):
71
+ import win32con # Possible, but not necessary, to use a Pythonwin GUI
72
+ import win32ui
73
+
74
+ win32ui.MessageBox("Hello from Python", "Python Test", win32con.MB_OKCANCEL)
75
+ return cancel
76
+
77
+
78
+ class ExcelAddin:
79
+ _com_interfaces_ = ["_IDTExtensibility2"]
80
+ _public_methods_ = []
81
+ _reg_clsctx_ = pythoncom.CLSCTX_INPROC_SERVER
82
+ _reg_clsid_ = "{C5482ECA-F559-45A0-B078-B2036E6F011A}"
83
+ _reg_progid_ = "Python.Test.ExcelAddin"
84
+ _reg_policy_spec_ = "win32com.server.policy.EventHandlerPolicy"
85
+
86
+ def __init__(self):
87
+ self.appHostApp = None
88
+
89
+ def OnConnection(self, application, connectMode, addin, custom):
90
+ print("OnConnection", application, connectMode, addin, custom)
91
+ try:
92
+ self.appHostApp = application
93
+ cbcMyBar = self.appHostApp.CommandBars.Add(
94
+ Name="PythonBar",
95
+ Position=constants.msoBarTop,
96
+ MenuBar=constants.msoBarTypeNormal,
97
+ Temporary=True,
98
+ )
99
+ btnMyButton = cbcMyBar.Controls.Add(
100
+ Type=constants.msoControlButton, Parameter="Greetings"
101
+ )
102
+ btnMyButton = self.toolbarButton = DispatchWithEvents(
103
+ btnMyButton, ButtonEvent
104
+ )
105
+ btnMyButton.Style = constants.msoButtonCaption
106
+ btnMyButton.BeginGroup = True
107
+ btnMyButton.Caption = "&Python"
108
+ btnMyButton.TooltipText = "Python rules the World"
109
+ btnMyButton.Width = "34"
110
+ cbcMyBar.Visible = True
111
+ except pythoncom.com_error as xxx_todo_changeme:
112
+ (hr, msg, exc, arg) = xxx_todo_changeme.args
113
+ print("The Excel call failed with code %d: %s" % (hr, msg))
114
+ if exc is None:
115
+ print("There is no extended error information")
116
+ else:
117
+ wcode, source, text, helpFile, helpId, scode = exc
118
+ print("The source of the error is", source)
119
+ print("The error message is", text)
120
+ print("More info can be found in %s (id=%d)" % (helpFile, helpId))
121
+
122
+ def OnDisconnection(self, mode, custom):
123
+ print("OnDisconnection")
124
+ self.appHostApp.CommandBars("PythonBar").Delete
125
+ self.appHostApp = None
126
+
127
+ def OnAddInsUpdate(self, custom):
128
+ print("OnAddInsUpdate", custom)
129
+
130
+ def OnStartupComplete(self, custom):
131
+ print("OnStartupComplete", custom)
132
+
133
+ def OnBeginShutdown(self, custom):
134
+ print("OnBeginShutdown", custom)
135
+
136
+
137
+ def RegisterAddin(klass):
138
+ import winreg
139
+
140
+ key = winreg.CreateKey(
141
+ winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Office\\Excel\\Addins"
142
+ )
143
+ subkey = winreg.CreateKey(key, klass._reg_progid_)
144
+ winreg.SetValueEx(subkey, "CommandLineSafe", 0, winreg.REG_DWORD, 0)
145
+ winreg.SetValueEx(subkey, "LoadBehavior", 0, winreg.REG_DWORD, 3)
146
+ winreg.SetValueEx(subkey, "Description", 0, winreg.REG_SZ, "Excel Addin")
147
+ winreg.SetValueEx(subkey, "FriendlyName", 0, winreg.REG_SZ, "A Simple Excel Addin")
148
+
149
+
150
+ def UnregisterAddin(klass):
151
+ import winreg
152
+
153
+ try:
154
+ winreg.DeleteKey(
155
+ winreg.HKEY_CURRENT_USER,
156
+ "Software\\Microsoft\\Office\\Excel\\Addins\\" + klass._reg_progid_,
157
+ )
158
+ except OSError:
159
+ pass
160
+
161
+
162
+ if __name__ == "__main__":
163
+ import win32com.server.register
164
+
165
+ win32com.server.register.UseCommandLine(ExcelAddin)
166
+ if "--unregister" in sys.argv:
167
+ UnregisterAddin(ExcelAddin)
168
+ else:
169
+ RegisterAddin(ExcelAddin)
loan-advisor-agent/.venv/Lib/site-packages/win32com/demos/excelRTDServer.py ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Excel IRTDServer implementation.
2
+
3
+ This module is a functional example of how to implement the IRTDServer interface
4
+ in python, using the pywin32 extensions. Further details, about this interface
5
+ and it can be found at:
6
+ https://learn.microsoft.com/en-us/previous-versions/office/developer/office-xp/aa140060(v=office.10)
7
+ """
8
+
9
+ # Copyright (c) 2003-2004 by Chris Nilsson <chris@slort.org>
10
+ #
11
+ # By obtaining, using, and/or copying this software and/or its
12
+ # associated documentation, you agree that you have read, understood,
13
+ # and will comply with the following terms and conditions:
14
+ #
15
+ # Permission to use, copy, modify, and distribute this software and
16
+ # its associated documentation for any purpose and without fee is
17
+ # hereby granted, provided that the above copyright notice appears in
18
+ # all copies, and that both that copyright notice and this permission
19
+ # notice appear in supporting documentation, and that the name of
20
+ # Christopher Nilsson (the author) not be used in advertising or publicity
21
+ # pertaining to distribution of the software without specific, written
22
+ # prior permission.
23
+ #
24
+ # THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
25
+ # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
26
+ # ABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
27
+ # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
28
+ # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
29
+ # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
30
+ # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
31
+ # OF THIS SOFTWARE.
32
+
33
+ import datetime # For the example classes...
34
+ import threading
35
+
36
+ import pythoncom
37
+ import win32com.client
38
+ from win32com import universal
39
+ from win32com.client import gencache
40
+ from win32com.server.exception import COMException
41
+
42
+ # Typelib info for version 10 - aka Excel XP.
43
+ # This is the minimum version of excel that we can work with as this is when
44
+ # Microsoft introduced these interfaces.
45
+ EXCEL_TLB_GUID = "{00020813-0000-0000-C000-000000000046}"
46
+ EXCEL_TLB_LCID = 0
47
+ EXCEL_TLB_MAJOR = 1
48
+ EXCEL_TLB_MINOR = 4
49
+
50
+ # Import the excel typelib to make sure we've got early-binding going on.
51
+ # The "ByRef" parameters we use later won't work without this.
52
+ gencache.EnsureModule(EXCEL_TLB_GUID, EXCEL_TLB_LCID, EXCEL_TLB_MAJOR, EXCEL_TLB_MINOR)
53
+
54
+ # Tell pywin to import these extra interfaces.
55
+ # --
56
+ # QUESTION: Why? The interfaces seem to descend from IDispatch, so
57
+ # I'd have thought, for example, calling callback.UpdateNotify() (on the
58
+ # IRTDUpdateEvent callback excel gives us) would work without molestation.
59
+ # But the callback needs to be cast to a "real" IRTDUpdateEvent type. Hmm...
60
+ # This is where my small knowledge of the pywin framework / COM gets hazy.
61
+ # --
62
+ # Again, we feed in the Excel typelib as the source of these interfaces.
63
+ universal.RegisterInterfaces(
64
+ EXCEL_TLB_GUID,
65
+ EXCEL_TLB_LCID,
66
+ EXCEL_TLB_MAJOR,
67
+ EXCEL_TLB_MINOR,
68
+ ["IRtdServer", "IRTDUpdateEvent"],
69
+ )
70
+
71
+
72
+ class ExcelRTDServer:
73
+ """Base RTDServer class.
74
+
75
+ Provides most of the features needed to implement the IRtdServer interface.
76
+ Manages topic adding, removal, and packing up the values for excel.
77
+
78
+ Shouldn't be instanciated directly.
79
+
80
+ Instead, descendant classes should override the CreateTopic() method.
81
+ Topic objects only need to provide a GetValue() function to play nice here.
82
+ The values given need to be atomic (eg. string, int, float... etc).
83
+
84
+ Also note: nothing has been done within this class to ensure that we get
85
+ time to check our topics for updates. I've left that up to the subclass
86
+ since the ways, and needs, of refreshing your topics will vary greatly. For
87
+ example, the sample implementation uses a timer thread to wake itself up.
88
+ Whichever way you choose to do it, your class needs to be able to wake up
89
+ occaisionally, since excel will never call your class without being asked to
90
+ first.
91
+
92
+ Excel will communicate with our object in this order:
93
+ 1. Excel instanciates our object and calls ServerStart, providing us with
94
+ an IRTDUpdateEvent callback object.
95
+ 2. Excel calls ConnectData when it wants to subscribe to a new "topic".
96
+ 3. When we have new data to provide, we call the UpdateNotify method of the
97
+ callback object we were given.
98
+ 4. Excel calls our RefreshData method, and receives a 2d SafeArray (row-major)
99
+ containing the Topic ids in the 1st dim, and the topic values in the
100
+ 2nd dim.
101
+ 5. When not needed anymore, Excel will call our DisconnectData to
102
+ unsubscribe from a topic.
103
+ 6. When there are no more topics left, Excel will call our ServerTerminate
104
+ method to kill us.
105
+
106
+ Throughout, at undetermined periods, Excel will call our Heartbeat
107
+ method to see if we're still alive. It must return a non-zero value, or
108
+ we'll be killed.
109
+
110
+ NOTE: By default, excel will at most call RefreshData once every 2 seconds.
111
+ This is a setting that needs to be changed excel-side. To change this,
112
+ you can set the throttle interval like this in the excel VBA object model:
113
+ Application.RTD.ThrottleInterval = 1000 ' milliseconds
114
+ """
115
+
116
+ _com_interfaces_ = ["IRtdServer"]
117
+ _public_methods_ = [
118
+ "ConnectData",
119
+ "DisconnectData",
120
+ "Heartbeat",
121
+ "RefreshData",
122
+ "ServerStart",
123
+ "ServerTerminate",
124
+ ]
125
+ _reg_clsctx_ = pythoncom.CLSCTX_INPROC_SERVER
126
+ # _reg_clsid_ = "# subclass must provide this class attribute"
127
+ # _reg_desc_ = "# subclass should provide this description"
128
+ # _reg_progid_ = "# subclass must provide this class attribute"
129
+
130
+ ALIVE = 1
131
+ NOT_ALIVE = 0
132
+
133
+ def __init__(self):
134
+ """Constructor"""
135
+ super().__init__()
136
+ self.IsAlive = self.ALIVE
137
+ self.__callback = None
138
+ self.topics = {}
139
+
140
+ def SignalExcel(self):
141
+ """Use the callback we were given to tell excel new data is available."""
142
+ if self.__callback is None:
143
+ raise COMException(desc="Callback excel provided is Null")
144
+ self.__callback.UpdateNotify()
145
+
146
+ def ConnectData(self, TopicID, Strings, GetNewValues):
147
+ """Creates a new topic out of the Strings excel gives us."""
148
+ try:
149
+ self.topics[TopicID] = self.CreateTopic(Strings)
150
+ except Exception as why:
151
+ raise COMException(desc=str(why))
152
+ GetNewValues = True
153
+ result = self.topics[TopicID]
154
+ if result is None:
155
+ result = "# %s: Waiting for update" % self.__class__.__name__
156
+ else:
157
+ result = result.GetValue()
158
+
159
+ # fire out internal event...
160
+ self.OnConnectData(TopicID)
161
+
162
+ # GetNewValues as per interface is ByRef, so we need to pass it back too.
163
+ return result, GetNewValues
164
+
165
+ def DisconnectData(self, TopicID):
166
+ """Deletes the given topic."""
167
+ self.OnDisconnectData(TopicID)
168
+
169
+ if TopicID in self.topics:
170
+ self.topics[TopicID] = None
171
+ del self.topics[TopicID]
172
+
173
+ def Heartbeat(self):
174
+ """Called by excel to see if we're still here."""
175
+ return self.IsAlive
176
+
177
+ def RefreshData(self, TopicCount):
178
+ """Packs up the topic values. Called by excel when it's ready for an update.
179
+
180
+ Needs to:
181
+ * Return the current number of topics, via the "ByRef" TopicCount
182
+ * Return a 2d SafeArray of the topic data.
183
+ - 1st dim: topic numbers
184
+ - 2nd dim: topic values
185
+
186
+ We could do some caching, instead of repacking everytime...
187
+ But this works for demonstration purposes."""
188
+ TopicCount = len(self.topics)
189
+ self.OnRefreshData()
190
+
191
+ # Grow the lists, so we don't need a heap of calls to append()
192
+ results = [[None] * TopicCount, [None] * TopicCount]
193
+
194
+ # Excel expects a 2-dimensional array. The first dim contains the
195
+ # topic numbers, and the second contains the values for the topics.
196
+ # In true VBA style (yuck), we need to pack the array in row-major format,
197
+ # which looks like:
198
+ # ( (topic_num1, topic_num2, ..., topic_numN), \
199
+ # (topic_val1, topic_val2, ..., topic_valN) )
200
+ for idx, topicdata in enumerate(self.topics.items()):
201
+ topicNum, topic = topicdata
202
+ results[0][idx] = topicNum
203
+ results[1][idx] = topic.GetValue()
204
+
205
+ # TopicCount is meant to be passed to us ByRef, so return it as well, as per
206
+ # the way pywin32 handles ByRef arguments.
207
+ return tuple(results), TopicCount
208
+
209
+ def ServerStart(self, CallbackObject):
210
+ """Excel has just created us... We take its callback for later, and set up shop."""
211
+ self.IsAlive = self.ALIVE
212
+
213
+ if CallbackObject is None:
214
+ raise COMException(desc="Excel did not provide a callback")
215
+
216
+ # Need to "cast" the raw PyIDispatch object to the IRTDUpdateEvent interface
217
+ IRTDUpdateEventKlass = win32com.client.CLSIDToClass.GetClass(
218
+ "{A43788C1-D91B-11D3-8F39-00C04F3651B8}"
219
+ )
220
+ self.__callback = IRTDUpdateEventKlass(CallbackObject)
221
+
222
+ self.OnServerStart()
223
+
224
+ return self.IsAlive
225
+
226
+ def ServerTerminate(self):
227
+ """Called when excel no longer wants us."""
228
+ self.IsAlive = self.NOT_ALIVE # On next heartbeat, excel will free us
229
+ self.OnServerTerminate()
230
+
231
+ def CreateTopic(self, TopicStrings=None):
232
+ """Topic factory method. Subclass must override.
233
+
234
+ Topic objects need to provide:
235
+ * GetValue() method which returns an atomic value.
236
+
237
+ Will raise NotImplemented if not overridden.
238
+ """
239
+ raise NotImplemented("Subclass must implement")
240
+
241
+ # Overridable class events...
242
+ def OnConnectData(self, TopicID):
243
+ """Called when a new topic has been created, at excel's request."""
244
+ pass
245
+
246
+ def OnDisconnectData(self, TopicID):
247
+ """Called when a topic is about to be deleted, at excel's request."""
248
+ pass
249
+
250
+ def OnRefreshData(self):
251
+ """Called when excel has requested all current topic data."""
252
+ pass
253
+
254
+ def OnServerStart(self):
255
+ """Called when excel has instanciated us."""
256
+ pass
257
+
258
+ def OnServerTerminate(self):
259
+ """Called when excel is about to destroy us."""
260
+ pass
261
+
262
+
263
+ class RTDTopic:
264
+ """Base RTD Topic.
265
+ Only method required by our RTDServer implementation is GetValue().
266
+ The others are more for convenience."""
267
+
268
+ def __init__(self, TopicStrings):
269
+ super().__init__()
270
+ self.TopicStrings = TopicStrings
271
+ self.__currentValue = None
272
+ self.__dirty = False
273
+
274
+ def Update(self, sender):
275
+ """Called by the RTD Server.
276
+ Gives us a chance to check if our topic data needs to be
277
+ changed (eg. check a file, quiz a database, etc)."""
278
+ raise NotImplemented("subclass must implement")
279
+
280
+ def Reset(self):
281
+ """Call when this topic isn't considered "dirty" anymore."""
282
+ self.__dirty = False
283
+
284
+ def GetValue(self):
285
+ return self.__currentValue
286
+
287
+ def SetValue(self, value):
288
+ self.__dirty = True
289
+ self.__currentValue = value
290
+
291
+ def HasChanged(self):
292
+ return self.__dirty
293
+
294
+
295
+ # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
296
+
297
+ ######################################
298
+ # Example classes
299
+ ######################################
300
+
301
+
302
+ class TimeServer(ExcelRTDServer):
303
+ """Example Time RTD server.
304
+
305
+ Sends time updates back to excel.
306
+
307
+ example of use, in an excel sheet:
308
+ =RTD("Python.RTD.TimeServer","","seconds","5")
309
+
310
+ This will cause a timestamp string to fill the cell, and update its value
311
+ every 5 seconds (or as close as possible depending on how busy excel is).
312
+
313
+ The empty string parameter denotes the com server is running on the local
314
+ machine. Otherwise, put in the hostname to look on. For more info
315
+ on this, lookup the Excel help for its "RTD" worksheet function.
316
+
317
+ Obviously, you'd want to wrap this kind of thing in a friendlier VBA
318
+ function.
319
+
320
+ Also, remember that the RTD function accepts a maximum of 28 arguments!
321
+ If you want to pass more, you may need to concatenate arguments into one
322
+ string, and have your topic parse them appropriately.
323
+ """
324
+
325
+ # win32com.server setup attributes...
326
+ # Never copy the _reg_clsid_ value in your own classes!
327
+ _reg_clsid_ = "{EA7F2CF1-11A2-45E4-B2D5-68E240DB8CB1}"
328
+ _reg_progid_ = "Python.RTD.TimeServer"
329
+ _reg_desc_ = "Python class implementing Excel IRTDServer -- feeds time"
330
+
331
+ # other class attributes...
332
+ INTERVAL = 0.5 # secs. Threaded timer will wake us up at this interval.
333
+
334
+ def __init__(self):
335
+ super().__init__()
336
+
337
+ # Simply timer thread to ensure we get to update our topics, and
338
+ # tell excel about any changes. This is a pretty basic and dirty way to
339
+ # do this. Ideally, there should be some sort of waitable (eg. either win32
340
+ # event, socket data event...) and be kicked off by that event triggering.
341
+ # As soon as we set up shop here, we _must_ return control back to excel.
342
+ # (ie. we can't block and do our own thing...)
343
+ self.ticker = threading.Timer(self.INTERVAL, self.Update)
344
+
345
+ def OnServerStart(self):
346
+ self.ticker.start()
347
+
348
+ def OnServerTerminate(self):
349
+ if not self.ticker.finished.is_set():
350
+ self.ticker.cancel() # Cancel our wake-up thread. Excel has killed us.
351
+
352
+ def Update(self):
353
+ # Get our wake-up thread ready...
354
+ self.ticker = threading.Timer(self.INTERVAL, self.Update)
355
+ try:
356
+ # Check if any of our topics have new info to pass on
357
+ if len(self.topics):
358
+ refresh = False
359
+ for topic in self.topics.values():
360
+ topic.Update(self)
361
+ if topic.HasChanged():
362
+ refresh = True
363
+ topic.Reset()
364
+
365
+ if refresh:
366
+ self.SignalExcel()
367
+ finally:
368
+ self.ticker.start() # Make sure we get to run again
369
+
370
+ def CreateTopic(self, TopicStrings=None):
371
+ """Topic factory. Builds a TimeTopic object out of the given TopicStrings."""
372
+ return TimeTopic(TopicStrings)
373
+
374
+
375
+ class TimeTopic(RTDTopic):
376
+ """Example topic for example RTD server.
377
+
378
+ Will accept some simple commands to alter how long to delay value updates.
379
+
380
+ Commands:
381
+ * seconds, delay_in_seconds
382
+ * minutes, delay_in_minutes
383
+ * hours, delay_in_hours
384
+ """
385
+
386
+ def __init__(self, TopicStrings):
387
+ super().__init__(TopicStrings)
388
+ try:
389
+ self.cmd, self.delay = self.TopicStrings
390
+ except Exception as E:
391
+ # We could simply return a "# ERROR" type string as the
392
+ # topic value, but explosions like this should be able to get handled by
393
+ # the VBA-side "On Error" stuff.
394
+ raise ValueError("Invalid topic strings: %s" % str(TopicStrings))
395
+
396
+ # self.cmd = str(self.cmd)
397
+ self.delay = float(self.delay)
398
+
399
+ # setup our initial value
400
+ self.checkpoint = self.timestamp()
401
+ self.SetValue(str(self.checkpoint))
402
+
403
+ def timestamp(self):
404
+ return datetime.datetime.now()
405
+
406
+ def Update(self, sender):
407
+ now = self.timestamp()
408
+ delta = now - self.checkpoint
409
+ refresh = False
410
+ if self.cmd == "seconds":
411
+ if delta.seconds >= self.delay:
412
+ refresh = True
413
+ elif self.cmd == "minutes":
414
+ if delta.minutes >= self.delay:
415
+ refresh = True
416
+ elif self.cmd == "hours":
417
+ if delta.hours >= self.delay:
418
+ refresh = True
419
+ else:
420
+ self.SetValue("#Unknown command: " + self.cmd)
421
+
422
+ if refresh:
423
+ self.SetValue(str(now))
424
+ self.checkpoint = now
425
+
426
+
427
+ if __name__ == "__main__":
428
+ import win32com.server.register
429
+
430
+ # Register/Unregister TimeServer example
431
+ # eg. at the command line: excelrtd.py --register
432
+ # Then type in an excel cell something like:
433
+ # =RTD("Python.RTD.TimeServer","","seconds","5")
434
+ win32com.server.register.UseCommandLine(TimeServer)
loan-advisor-agent/.venv/Lib/site-packages/win32com/demos/iebutton.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: latin-1 -*-
2
+
3
+ # PyWin32 Internet Explorer Button
4
+ #
5
+ # written by Leonard Ritter (paniq@gmx.net)
6
+ # and Robert Förtsch (info@robert-foertsch.com)
7
+
8
+
9
+ """
10
+ This sample implements a simple IE Button COM server
11
+ with access to the IWebBrowser2 interface.
12
+
13
+ To demonstrate:
14
+ * Execute this script to register the server.
15
+ * Open Pythonwin's Tools -> Trace Collector Debugging Tool, so you can
16
+ see the output of 'print' statements in this demo.
17
+ * Open a new IE instance. The toolbar should have a new "scissors" icon,
18
+ with tooltip text "IE Button" - this is our new button - click it.
19
+ * Switch back to the Pythonwin window - you should see:
20
+ IOleCommandTarget::Exec called.
21
+ This is the button being clicked. Extending this to do something more
22
+ useful is left as an exercise.
23
+
24
+ Contribtions to this sample to make it a little "friendlier" welcome!
25
+ """
26
+
27
+ # imports section
28
+
29
+ import pythoncom
30
+ import win32api
31
+ import win32com
32
+ import win32com.server.register
33
+
34
+ # This demo uses 'print' - use win32traceutil to see it if we have no
35
+ # console.
36
+ try:
37
+ win32api.GetConsoleTitle()
38
+ except win32api.error:
39
+ import win32traceutil
40
+
41
+
42
+ from win32com.axcontrol import axcontrol
43
+
44
+ # ensure we know the ms internet controls typelib so we have access to IWebBrowser2 later on
45
+ win32com.client.gencache.EnsureModule("{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}", 0, 1, 1)
46
+
47
+
48
+ #
49
+ IObjectWithSite_methods = ["SetSite", "GetSite"]
50
+ IOleCommandTarget_methods = ["Exec", "QueryStatus"]
51
+
52
+ _iebutton_methods_ = IOleCommandTarget_methods + IObjectWithSite_methods
53
+ _iebutton_com_interfaces_ = [
54
+ axcontrol.IID_IOleCommandTarget,
55
+ axcontrol.IID_IObjectWithSite, # IObjectWithSite
56
+ ]
57
+
58
+
59
+ class Stub:
60
+ """
61
+ this class serves as a method stub,
62
+ outputting debug info whenever the object
63
+ is being called.
64
+ """
65
+
66
+ def __init__(self, name):
67
+ self.name = name
68
+
69
+ def __call__(self, *args):
70
+ print("STUB: ", self.name, args)
71
+
72
+
73
+ class IEButton:
74
+ """
75
+ The actual COM server class
76
+ """
77
+
78
+ _com_interfaces_ = _iebutton_com_interfaces_
79
+ _public_methods_ = _iebutton_methods_
80
+ _reg_clsctx_ = pythoncom.CLSCTX_INPROC_SERVER
81
+ _button_text_ = "IE Button"
82
+ _tool_tip_ = "An example implementation for an IE Button."
83
+ _icon_ = ""
84
+ _hot_icon_ = ""
85
+
86
+ def __init__(self):
87
+ # put stubs for non-implemented methods
88
+ for method in self._public_methods_:
89
+ if not hasattr(self, method):
90
+ print("providing default stub for %s" % method)
91
+ setattr(self, method, Stub(method))
92
+
93
+ def QueryStatus(self, pguidCmdGroup, prgCmds, cmdtextf):
94
+ # 'cmdtextf' is the 'cmdtextf' element from the OLECMDTEXT structure,
95
+ # or None if a NULL pointer was passed.
96
+ result = []
97
+ for id, flags in prgCmds:
98
+ flags |= axcontrol.OLECMDF_SUPPORTED | axcontrol.OLECMDF_ENABLED
99
+ result.append((id, flags))
100
+ if cmdtextf is None:
101
+ cmdtext = None # must return None if nothing requested.
102
+ # IE never seems to want any text - this code is here for
103
+ # demo purposes only
104
+ elif cmdtextf == axcontrol.OLECMDTEXTF_NAME:
105
+ cmdtext = "IEButton Name"
106
+ else:
107
+ cmdtext = "IEButton State"
108
+ return result, cmdtext
109
+
110
+ def Exec(self, pguidCmdGroup, nCmdID, nCmdExecOpt, pvaIn):
111
+ print(pguidCmdGroup, nCmdID, nCmdExecOpt, pvaIn)
112
+ print("IOleCommandTarget::Exec called.")
113
+ # self.webbrowser.ShowBrowserBar(GUID_IETOOLBAR, not is_ietoolbar_visible())
114
+
115
+ def SetSite(self, unknown):
116
+ if unknown:
117
+ # first get a command target
118
+ cmdtarget = unknown.QueryInterface(axcontrol.IID_IOleCommandTarget)
119
+ # then travel over to a service provider
120
+ serviceprovider = cmdtarget.QueryInterface(pythoncom.IID_IServiceProvider)
121
+ # finally ask for the internet explorer application, returned as a dispatch object
122
+ self.webbrowser = win32com.client.Dispatch(
123
+ serviceprovider.QueryService(
124
+ "{0002DF05-0000-0000-C000-000000000046}", pythoncom.IID_IDispatch
125
+ )
126
+ )
127
+ else:
128
+ # lose all references
129
+ self.webbrowser = None
130
+
131
+ def GetClassID(self):
132
+ return self._reg_clsid_
133
+
134
+
135
+ def register(classobj):
136
+ import winreg
137
+
138
+ subKeyCLSID = (
139
+ "SOFTWARE\\Microsoft\\Internet Explorer\\Extensions\\%38s"
140
+ % classobj._reg_clsid_
141
+ )
142
+ try:
143
+ hKey = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, subKeyCLSID)
144
+ subKey = winreg.SetValueEx(
145
+ hKey, "ButtonText", 0, winreg.REG_SZ, classobj._button_text_
146
+ )
147
+ winreg.SetValueEx(
148
+ hKey, "ClsidExtension", 0, winreg.REG_SZ, classobj._reg_clsid_
149
+ ) # reg value for calling COM object
150
+ winreg.SetValueEx(
151
+ hKey, "CLSID", 0, winreg.REG_SZ, "{1FBA04EE-3024-11D2-8F1F-0000F87ABD16}"
152
+ ) # CLSID for button that sends command to COM object
153
+ winreg.SetValueEx(hKey, "Default Visible", 0, winreg.REG_SZ, "Yes")
154
+ winreg.SetValueEx(hKey, "ToolTip", 0, winreg.REG_SZ, classobj._tool_tip_)
155
+ winreg.SetValueEx(hKey, "Icon", 0, winreg.REG_SZ, classobj._icon_)
156
+ winreg.SetValueEx(hKey, "HotIcon", 0, winreg.REG_SZ, classobj._hot_icon_)
157
+ except OSError:
158
+ print("Couldn't set standard toolbar reg keys.")
159
+ else:
160
+ print("Set standard toolbar reg keys.")
161
+
162
+
163
+ def unregister(classobj):
164
+ import winreg
165
+
166
+ subKeyCLSID = (
167
+ "SOFTWARE\\Microsoft\\Internet Explorer\\Extensions\\%38s"
168
+ % classobj._reg_clsid_
169
+ )
170
+ try:
171
+ hKey = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, subKeyCLSID)
172
+ subKey = winreg.DeleteValue(hKey, "ButtonText")
173
+ winreg.DeleteValue(hKey, "ClsidExtension") # for calling COM object
174
+ winreg.DeleteValue(hKey, "CLSID")
175
+ winreg.DeleteValue(hKey, "Default Visible")
176
+ winreg.DeleteValue(hKey, "ToolTip")
177
+ winreg.DeleteValue(hKey, "Icon")
178
+ winreg.DeleteValue(hKey, "HotIcon")
179
+ winreg.DeleteKey(winreg.HKEY_LOCAL_MACHINE, subKeyCLSID)
180
+ except OSError:
181
+ print("Couldn't delete Standard toolbar regkey.")
182
+ else:
183
+ print("Deleted Standard toolbar regkey.")
184
+
185
+
186
+ #
187
+ # test implementation
188
+ #
189
+
190
+
191
+ class PyWin32InternetExplorerButton(IEButton):
192
+ _reg_clsid_ = "{104B66A9-9E68-49D1-A3F5-94754BE9E0E6}"
193
+ _reg_progid_ = "PyWin32.IEButton"
194
+ _reg_desc_ = "Test Button"
195
+ _button_text_ = "IE Button"
196
+ _tool_tip_ = "An example implementation for an IE Button."
197
+ _icon_ = ""
198
+ _hot_icon_ = _icon_
199
+
200
+
201
+ def DllRegisterServer():
202
+ register(PyWin32InternetExplorerButton)
203
+
204
+
205
+ def DllUnregisterServer():
206
+ unregister(PyWin32InternetExplorerButton)
207
+
208
+
209
+ if __name__ == "__main__":
210
+ win32com.server.register.UseCommandLine(
211
+ PyWin32InternetExplorerButton,
212
+ finalize_register=DllRegisterServer,
213
+ finalize_unregister=DllUnregisterServer,
214
+ )
loan-advisor-agent/.venv/Lib/site-packages/win32com/demos/ietoolbar.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: latin-1 -*-
2
+
3
+ # PyWin32 Internet Explorer Toolbar
4
+ #
5
+ # written by Leonard Ritter (paniq@gmx.net)
6
+ # and Robert Förtsch (info@robert-foertsch.com)
7
+
8
+
9
+ """
10
+ This sample implements a simple IE Toolbar COM server
11
+ supporting Windows XP styles and access to
12
+ the IWebBrowser2 interface.
13
+
14
+ It also demonstrates how to hijack the parent window
15
+ to catch WM_COMMAND messages.
16
+ """
17
+
18
+ import array
19
+ import struct
20
+
21
+ # imports section
22
+ import sys
23
+ import winreg
24
+
25
+ import commctrl
26
+ import pythoncom
27
+ import win32com
28
+ import win32con
29
+ import win32gui
30
+ import win32ui
31
+ from win32com.axcontrol import axcontrol
32
+ from win32com.client import Dispatch, gencache
33
+ from win32com.shell import shell
34
+ from win32com.shell.shellcon import DBIMF_VARIABLEHEIGHT
35
+
36
+ # ensure we know the ms internet controls typelib so we have access to IWebBrowser2 later on
37
+ gencache.EnsureModule("{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}", 0, 1, 1)
38
+
39
+ #
40
+ IDeskBand_methods = ["GetBandInfo"]
41
+ IDockingWindow_methods = ["ShowDW", "CloseDW", "ResizeBorderDW"]
42
+ IOleWindow_methods = ["GetWindow", "ContextSensitiveHelp"]
43
+ IInputObject_methods = ["UIActivateIO", "HasFocusIO", "TranslateAcceleratorIO"]
44
+ IObjectWithSite_methods = ["SetSite", "GetSite"]
45
+ IPersistStream_methods = ["GetClassID", "IsDirty", "Load", "Save", "GetSizeMax"]
46
+
47
+ _ietoolbar_methods_ = (
48
+ IDeskBand_methods
49
+ + IDockingWindow_methods
50
+ + IOleWindow_methods
51
+ + IInputObject_methods
52
+ + IObjectWithSite_methods
53
+ + IPersistStream_methods
54
+ )
55
+ _ietoolbar_com_interfaces_ = [
56
+ shell.IID_IDeskBand, # IDeskBand
57
+ axcontrol.IID_IObjectWithSite, # IObjectWithSite
58
+ pythoncom.IID_IPersistStream,
59
+ axcontrol.IID_IOleCommandTarget,
60
+ ]
61
+
62
+
63
+ class WIN32STRUCT:
64
+ def __init__(self, **kw):
65
+ full_fmt = ""
66
+ for name, fmt, default in self._struct_items_:
67
+ self.__dict__[name] = None
68
+ if fmt == "z":
69
+ full_fmt += "pi"
70
+ else:
71
+ full_fmt += fmt
72
+ for name, val in kw.items():
73
+ self.__dict__[name] = val
74
+
75
+ def __setattr__(self, attr, val):
76
+ if not attr.startswith("_") and attr not in self.__dict__:
77
+ raise AttributeError(attr)
78
+ self.__dict__[attr] = val
79
+
80
+ def toparam(self):
81
+ self._buffs = []
82
+ full_fmt = ""
83
+ vals = []
84
+ for name, fmt, default in self._struct_items_:
85
+ val = self.__dict__[name]
86
+ if fmt == "z":
87
+ fmt = "Pi"
88
+ if val is None:
89
+ vals.append(0)
90
+ vals.append(0)
91
+ else:
92
+ str_buf = array.array("c", val + "\0")
93
+ vals.append(str_buf.buffer_info()[0])
94
+ vals.append(len(val))
95
+ self._buffs.append(str_buf) # keep alive during the call.
96
+ else:
97
+ if val is None:
98
+ val = default
99
+ vals.append(val)
100
+ full_fmt += fmt
101
+ return struct.pack(*(full_fmt,) + tuple(vals))
102
+
103
+
104
+ class TBBUTTON(WIN32STRUCT):
105
+ _struct_items_ = [
106
+ ("iBitmap", "i", 0),
107
+ ("idCommand", "i", 0),
108
+ ("fsState", "B", 0),
109
+ ("fsStyle", "B", 0),
110
+ ("bReserved", "H", 0),
111
+ ("dwData", "I", 0),
112
+ ("iString", "z", None),
113
+ ]
114
+
115
+
116
+ class Stub:
117
+ """
118
+ this class serves as a method stub,
119
+ outputting debug info whenever the object
120
+ is being called.
121
+ """
122
+
123
+ def __init__(self, name):
124
+ self.name = name
125
+
126
+ def __call__(self, *args):
127
+ print("STUB: ", self.name, args)
128
+
129
+
130
+ class IEToolbarCtrl:
131
+ """
132
+ a tiny wrapper for our winapi-based
133
+ toolbar control implementation.
134
+ """
135
+
136
+ def __init__(self, hwndparent):
137
+ styles = (
138
+ win32con.WS_CHILD
139
+ | win32con.WS_VISIBLE
140
+ | win32con.WS_CLIPSIBLINGS
141
+ | win32con.WS_CLIPCHILDREN
142
+ | commctrl.TBSTYLE_LIST
143
+ | commctrl.TBSTYLE_FLAT
144
+ | commctrl.TBSTYLE_TRANSPARENT
145
+ | commctrl.CCS_TOP
146
+ | commctrl.CCS_NODIVIDER
147
+ | commctrl.CCS_NORESIZE
148
+ | commctrl.CCS_NOPARENTALIGN
149
+ )
150
+ self.hwnd = win32gui.CreateWindow(
151
+ "ToolbarWindow32",
152
+ None,
153
+ styles,
154
+ 0,
155
+ 0,
156
+ 100,
157
+ 100,
158
+ hwndparent,
159
+ 0,
160
+ win32gui.dllhandle,
161
+ None,
162
+ )
163
+ win32gui.SendMessage(self.hwnd, commctrl.TB_BUTTONSTRUCTSIZE, 20, 0)
164
+
165
+ def ShowWindow(self, mode):
166
+ win32gui.ShowWindow(self.hwnd, mode)
167
+
168
+ def AddButtons(self, *buttons):
169
+ tbbuttons = ""
170
+ for button in buttons:
171
+ tbbuttons += button.toparam()
172
+ return win32gui.SendMessage(
173
+ self.hwnd, commctrl.TB_ADDBUTTONS, len(buttons), tbbuttons
174
+ )
175
+
176
+ def GetSafeHwnd(self):
177
+ return self.hwnd
178
+
179
+
180
+ class IEToolbar:
181
+ """
182
+ The actual COM server class
183
+ """
184
+
185
+ _com_interfaces_ = _ietoolbar_com_interfaces_
186
+ _public_methods_ = _ietoolbar_methods_
187
+ _reg_clsctx_ = pythoncom.CLSCTX_INPROC_SERVER
188
+ # if you copy and modify this example, be sure to change the clsid below
189
+ _reg_clsid_ = "{F21202A2-959A-4149-B1C3-68B9013F3335}"
190
+ _reg_progid_ = "PyWin32.IEToolbar"
191
+ _reg_desc_ = "PyWin32 IE Toolbar"
192
+
193
+ def __init__(self):
194
+ # put stubs for non-implemented methods
195
+ for method in self._public_methods_:
196
+ if not hasattr(self, method):
197
+ print("providing default stub for %s" % method)
198
+ setattr(self, method, Stub(method))
199
+
200
+ def GetWindow(self):
201
+ return self.toolbar.GetSafeHwnd()
202
+
203
+ def Load(self, stream):
204
+ # called when the toolbar is loaded
205
+ pass
206
+
207
+ def Save(self, pStream, fClearDirty):
208
+ # called when the toolbar shall save its information
209
+ pass
210
+
211
+ def CloseDW(self, dwReserved):
212
+ del self.toolbar
213
+
214
+ def ShowDW(self, bShow):
215
+ if bShow:
216
+ self.toolbar.ShowWindow(win32con.SW_SHOW)
217
+ else:
218
+ self.toolbar.ShowWindow(win32con.SW_HIDE)
219
+
220
+ def on_first_button(self):
221
+ print("first!")
222
+ self.webbrowser.Navigate2("https://github.com/mhammond/pywin32")
223
+
224
+ def on_second_button(self):
225
+ print("second!")
226
+
227
+ def on_third_button(self):
228
+ print("third!")
229
+
230
+ def toolbar_command_handler(self, args):
231
+ hwnd, message, wparam, lparam, time, point = args
232
+ if lparam == self.toolbar.GetSafeHwnd():
233
+ self._command_map[wparam]()
234
+
235
+ def SetSite(self, unknown):
236
+ if unknown:
237
+ # retrieve the parent window interface for this site
238
+ olewindow = unknown.QueryInterface(pythoncom.IID_IOleWindow)
239
+ # ask the window for its handle
240
+ hwndparent = olewindow.GetWindow()
241
+
242
+ # first get a command target
243
+ cmdtarget = unknown.QueryInterface(axcontrol.IID_IOleCommandTarget)
244
+ # then travel over to a service provider
245
+ serviceprovider = cmdtarget.QueryInterface(pythoncom.IID_IServiceProvider)
246
+ # finally ask for the internet explorer application, returned as a dispatch object
247
+ self.webbrowser = Dispatch(
248
+ serviceprovider.QueryService(
249
+ "{0002DF05-0000-0000-C000-000000000046}", pythoncom.IID_IDispatch
250
+ )
251
+ )
252
+
253
+ # now create and set up the toolbar
254
+ self.toolbar = IEToolbarCtrl(hwndparent)
255
+
256
+ buttons = [
257
+ ("Visit PyWin32 Homepage", self.on_first_button),
258
+ ("Another Button", self.on_second_button),
259
+ ("Yet Another Button", self.on_third_button),
260
+ ]
261
+
262
+ self._command_map = {}
263
+ # wrap our parent window so we can hook message handlers
264
+ window = win32ui.CreateWindowFromHandle(hwndparent)
265
+
266
+ # add the buttons
267
+ for i in range(len(buttons)):
268
+ button = TBBUTTON()
269
+ name, func = buttons[i]
270
+ id = 0x4444 + i
271
+ button.iBitmap = -2
272
+ button.idCommand = id
273
+ button.fsState = commctrl.TBSTATE_ENABLED
274
+ button.fsStyle = commctrl.TBSTYLE_BUTTON
275
+ button.iString = name
276
+ self._command_map[0x4444 + i] = func
277
+ self.toolbar.AddButtons(button)
278
+ window.HookMessage(self.toolbar_command_handler, win32con.WM_COMMAND)
279
+ else:
280
+ # lose all references
281
+ self.webbrowser = None
282
+
283
+ def GetClassID(self):
284
+ return self._reg_clsid_
285
+
286
+ def GetBandInfo(self, dwBandId, dwViewMode, dwMask):
287
+ ptMinSize = (0, 24)
288
+ ptMaxSize = (2000, 24)
289
+ ptIntegral = (0, 0)
290
+ ptActual = (2000, 24)
291
+ wszTitle = "PyWin32 IE Toolbar"
292
+ dwModeFlags = DBIMF_VARIABLEHEIGHT
293
+ crBkgnd = 0
294
+ return (
295
+ ptMinSize,
296
+ ptMaxSize,
297
+ ptIntegral,
298
+ ptActual,
299
+ wszTitle,
300
+ dwModeFlags,
301
+ crBkgnd,
302
+ )
303
+
304
+
305
+ # used for HKLM install
306
+ def DllInstall(bInstall, cmdLine):
307
+ comclass = IEToolbar
308
+
309
+
310
+ # register plugin
311
+ def DllRegisterServer():
312
+ comclass = IEToolbar
313
+
314
+ # register toolbar with IE
315
+ try:
316
+ print("Trying to register Toolbar.\n")
317
+ hkey = winreg.CreateKey(
318
+ winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Internet Explorer\\Toolbar"
319
+ )
320
+ subKey = winreg.SetValueEx(
321
+ hkey, comclass._reg_clsid_, 0, winreg.REG_BINARY, b"\0"
322
+ )
323
+ except OSError:
324
+ print(
325
+ "Couldn't set registry value.\nhkey: %d\tCLSID: %s\n"
326
+ % (hkey, comclass._reg_clsid_)
327
+ )
328
+ else:
329
+ print(
330
+ "Set registry value.\nhkey: %d\tCLSID: %s\n" % (hkey, comclass._reg_clsid_)
331
+ )
332
+ # TODO: implement reg settings for standard toolbar button
333
+
334
+
335
+ # unregister plugin
336
+ def DllUnregisterServer():
337
+ comclass = IEToolbar
338
+
339
+ # unregister toolbar from internet explorer
340
+ try:
341
+ print("Trying to unregister Toolbar.\n")
342
+ hkey = winreg.CreateKey(
343
+ winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Internet Explorer\\Toolbar"
344
+ )
345
+ winreg.DeleteValue(hkey, comclass._reg_clsid_)
346
+ except OSError:
347
+ print(
348
+ "Couldn't delete registry value.\nhkey: %d\tCLSID: %s\n"
349
+ % (hkey, comclass._reg_clsid_)
350
+ )
351
+ else:
352
+ print("Deleting reg key succeeded.\n")
353
+
354
+
355
+ # entry point
356
+ if __name__ == "__main__":
357
+ import win32com.server.register
358
+
359
+ win32com.server.register.UseCommandLine(IEToolbar)
360
+
361
+ # parse actual command line option
362
+ if "--unregister" in sys.argv:
363
+ DllUnregisterServer()
364
+ else:
365
+ DllRegisterServer()
366
+ else:
367
+ # import trace utility for remote debugging
368
+ import win32traceutil
loan-advisor-agent/.venv/Lib/site-packages/win32com/demos/outlookAddin.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # A demo plugin for Microsoft Outlook (NOT Outlook Express)
2
+ #
3
+ # This addin simply adds a new button to the main Outlook toolbar,
4
+ # and displays a message box when clicked. Thus, it demonstrates
5
+ # how to plug in to Outlook itself, and hook outlook events.
6
+ #
7
+ # Additionally, each time a new message arrives in the Inbox, a message
8
+ # is printed with the subject of the message.
9
+ #
10
+ # To register the addin, simply execute:
11
+ # outlookAddin.py
12
+ # This will install the COM server, and write the necessary
13
+ # AddIn key to Outlook
14
+ #
15
+ # To unregister completely:
16
+ # outlookAddin.py --unregister
17
+ #
18
+ # To debug, execute:
19
+ # outlookAddin.py --debug
20
+ #
21
+ # Then open Pythonwin, and select "Tools->Trace Collector Debugging Tool"
22
+ # Restart Outlook, and you should see some output generated.
23
+ #
24
+ # NOTE: If the AddIn fails with an error, Outlook will re-register
25
+ # the addin to not automatically load next time Outlook starts. To
26
+ # correct this, simply re-register the addin (see above)
27
+
28
+ import sys
29
+
30
+ import pythoncom
31
+ from win32com import universal
32
+ from win32com.client import DispatchWithEvents, constants, gencache
33
+
34
+ # Support for COM objects we use.
35
+ gencache.EnsureModule(
36
+ "{00062FFF-0000-0000-C000-000000000046}", 0, 9, 0, bForDemand=True
37
+ ) # Outlook 9
38
+ gencache.EnsureModule(
39
+ "{2DF8D04C-5BFA-101B-BDE5-00AA0044DE52}", 0, 2, 1, bForDemand=True
40
+ ) # Office 9
41
+
42
+ # The TLB defining the interfaces we implement
43
+ universal.RegisterInterfaces(
44
+ "{AC0714F2-3D04-11D1-AE7D-00A0C90F26F4}", 0, 1, 0, ["_IDTExtensibility2"]
45
+ )
46
+
47
+
48
+ class ButtonEvent:
49
+ def OnClick(self, button, cancel):
50
+ import win32ui # Possible, but not necessary, to use a Pythonwin GUI
51
+
52
+ win32ui.MessageBox("Hello from Python")
53
+ return cancel
54
+
55
+
56
+ class FolderEvent:
57
+ def OnItemAdd(self, item):
58
+ try:
59
+ print("An item was added to the inbox with subject:", item.Subject)
60
+ except AttributeError:
61
+ print(f"An item was added to the inbox, but it has no subject! - {item!r}")
62
+
63
+
64
+ class OutlookAddin:
65
+ _com_interfaces_ = ["_IDTExtensibility2"]
66
+ _public_methods_ = []
67
+ _reg_clsctx_ = pythoncom.CLSCTX_INPROC_SERVER
68
+ _reg_clsid_ = "{0F47D9F3-598B-4d24-B7E3-92AC15ED27E2}"
69
+ _reg_progid_ = "Python.Test.OutlookAddin"
70
+ _reg_policy_spec_ = "win32com.server.policy.EventHandlerPolicy"
71
+
72
+ def OnConnection(self, application, connectMode, addin, custom):
73
+ print("OnConnection", application, connectMode, addin, custom)
74
+ # ActiveExplorer may be none when started without a UI (eg, WinCE synchronisation)
75
+ activeExplorer = application.ActiveExplorer()
76
+ if activeExplorer is not None:
77
+ bars = activeExplorer.CommandBars
78
+ toolbar = bars.Item("Standard")
79
+ item = toolbar.Controls.Add(Type=constants.msoControlButton, Temporary=True)
80
+ # Hook events for the item
81
+ item = self.toolbarButton = DispatchWithEvents(item, ButtonEvent)
82
+ item.Caption = "Python"
83
+ item.TooltipText = "Click for Python"
84
+ item.Enabled = True
85
+
86
+ # And now, for the sake of demonstration, setup a hook for all new messages
87
+ inbox = application.Session.GetDefaultFolder(constants.olFolderInbox)
88
+ self.inboxItems = DispatchWithEvents(inbox.Items, FolderEvent)
89
+
90
+ def OnDisconnection(self, mode, custom):
91
+ print("OnDisconnection")
92
+
93
+ def OnAddInsUpdate(self, custom):
94
+ print("OnAddInsUpdate", custom)
95
+
96
+ def OnStartupComplete(self, custom):
97
+ print("OnStartupComplete", custom)
98
+
99
+ def OnBeginShutdown(self, custom):
100
+ print("OnBeginShutdown", custom)
101
+
102
+
103
+ def RegisterAddin(klass):
104
+ import winreg
105
+
106
+ key = winreg.CreateKey(
107
+ winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Office\\Outlook\\Addins"
108
+ )
109
+ subkey = winreg.CreateKey(key, klass._reg_progid_)
110
+ winreg.SetValueEx(subkey, "CommandLineSafe", 0, winreg.REG_DWORD, 0)
111
+ winreg.SetValueEx(subkey, "LoadBehavior", 0, winreg.REG_DWORD, 3)
112
+ winreg.SetValueEx(subkey, "Description", 0, winreg.REG_SZ, klass._reg_progid_)
113
+ winreg.SetValueEx(subkey, "FriendlyName", 0, winreg.REG_SZ, klass._reg_progid_)
114
+
115
+
116
+ def UnregisterAddin(klass):
117
+ import winreg
118
+
119
+ try:
120
+ winreg.DeleteKey(
121
+ winreg.HKEY_CURRENT_USER,
122
+ "Software\\Microsoft\\Office\\Outlook\\Addins\\" + klass._reg_progid_,
123
+ )
124
+ except OSError:
125
+ pass
126
+
127
+
128
+ if __name__ == "__main__":
129
+ import win32com.server.register
130
+
131
+ win32com.server.register.UseCommandLine(OutlookAddin)
132
+ if "--unregister" in sys.argv:
133
+ UnregisterAddin(OutlookAddin)
134
+ else:
135
+ RegisterAddin(OutlookAddin)
loan-advisor-agent/.venv/Lib/site-packages/win32com/demos/trybag.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pythoncom
2
+ from win32com.server import util
3
+ from win32com.server.exception import COMException
4
+
5
+ VT_EMPTY = pythoncom.VT_EMPTY
6
+
7
+
8
+ class Bag:
9
+ _public_methods_ = ["Read", "Write"]
10
+ _com_interfaces_ = [pythoncom.IID_IPropertyBag]
11
+
12
+ def __init__(self):
13
+ self.data = {}
14
+
15
+ def Read(self, propName, varType, errorLog):
16
+ print("read: name=", propName, "type=", varType)
17
+ if propName not in self.data:
18
+ if errorLog:
19
+ hr = 0x80070057
20
+ exc = pythoncom.com_error(0, "Bag.Read", "no such item", None, 0, hr)
21
+ errorLog.AddError(propName, exc)
22
+ raise COMException(scode=hr)
23
+ return self.data[propName]
24
+
25
+ def Write(self, propName, value):
26
+ print("write: name=", propName, "value=", value)
27
+ self.data[propName] = value
28
+
29
+
30
+ class Target:
31
+ _public_methods_ = ["GetClassID", "InitNew", "Load", "Save"]
32
+ _com_interfaces_ = [pythoncom.IID_IPersist, pythoncom.IID_IPersistPropertyBag]
33
+
34
+ def GetClassID(self):
35
+ raise COMException(scode=0x80004005) # E_FAIL
36
+
37
+ def InitNew(self):
38
+ pass
39
+
40
+ def Load(self, bag, log):
41
+ print(bag.Read("prop1", VT_EMPTY, log))
42
+ print(bag.Read("prop2", VT_EMPTY, log))
43
+ try:
44
+ print(bag.Read("prop3", VT_EMPTY, log))
45
+ except COMException:
46
+ pass
47
+
48
+ def Save(self, bag, clearDirty, saveAllProps):
49
+ bag.Write("prop1", "prop1.hello")
50
+ bag.Write("prop2", "prop2.there")
51
+
52
+
53
+ class Log:
54
+ _public_methods_ = ["AddError"]
55
+ _com_interfaces_ = [pythoncom.IID_IErrorLog]
56
+
57
+ def AddError(self, propName, excepInfo):
58
+ print("error: propName=", propName, "error=", excepInfo)
59
+
60
+
61
+ def test():
62
+ bag = Bag()
63
+ target = Target()
64
+ log = Log()
65
+
66
+ target.Save(bag, 1, 1)
67
+ target.Load(bag, log)
68
+
69
+ comBag = util.wrap(bag, pythoncom.IID_IPropertyBag)
70
+ comTarget = util.wrap(target, pythoncom.IID_IPersistPropertyBag)
71
+ comLog = util.wrap(log, pythoncom.IID_IErrorLog)
72
+
73
+ comTarget.Save(comBag, 1, 1)
74
+ comTarget.Load(comBag, comLog)
75
+
76
+
77
+ if __name__ == "__main__":
78
+ test()
loan-advisor-agent/.venv/Lib/site-packages/win32com/include/PythonCOM.h ADDED
@@ -0,0 +1,746 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* PythonCOM.h
2
+
3
+ Main header for Python COM support.
4
+
5
+ This file is involved mainly with client side COM support for
6
+ Python.
7
+
8
+ Most COM work put together by Greg Stein and Mark Hammond, with a
9
+ few others starting to come out of the closet.
10
+
11
+
12
+ --------------------------------------------------------------------
13
+ Thread State Rules
14
+ ------------------
15
+ These rules apply to PythonCOM in general, and not just to
16
+ the client side.
17
+
18
+ The rules are quite simple, but it is critical they be followed.
19
+ In general, errors here will be picked up quite quickly, as Python
20
+ will raise a Fatal Error. However, the Release() issue in particular
21
+ may keep a number of problems well hidden.
22
+
23
+ Interfaces:
24
+ -----------
25
+ Before making ANY call out to COM, you MUST release the Python lock.
26
+ This is true to ANY call whatsoever, including the COM call in question,
27
+ but also any calls to "->Release();"
28
+
29
+ This is normally achieved with the calls
30
+ PY_INTERFACE_PRECALL and PY_INTERFACE_POSTCALL, which release
31
+ and acquire the Python lock.
32
+
33
+ Gateways:
34
+ ---------
35
+ Before doing anything related to Python, gateways MUST acquire the
36
+ Python lock, and must release it before returning.
37
+
38
+ This is normally achieved with PY_GATEWAY_METHOD at the top of a
39
+ gateway method. This macro resolves to a class, which automatically does
40
+ the right thing.
41
+
42
+ Release:
43
+ --------
44
+ As mentioned above for Interfaces, EVERY call to Release() must be done
45
+ with the Python lock released. This is expanded here.
46
+
47
+ This is very important, but an error may not be noticed. The problem will
48
+ only be seen when the Release() is on a Python object and the Release() is the
49
+ final one for the object. In this case, the Python object will attempt to
50
+ acquire the Python lock before destroying itself, and Python will raise a
51
+ fatal error.
52
+
53
+ In many many cases, you will not notice this error, but someday, someone will
54
+ implement the other side in Python, and suddenly FatalErrors will start
55
+ appearing. Make sure you get this right.
56
+
57
+ Eg, this code is correct:
58
+ PY_INTERFACE_PRECALL;
59
+ pSomeObj->SomeFunction(pSomeOtherObject);
60
+ pSomeOtherObject->Release();
61
+ PY_INTERFACE_POSTCALL;
62
+
63
+ However, this code is WRONG, but will RARELY FAIL.
64
+ PY_INTERFACE_PRECALL;
65
+ pSomeObj->SomeFunction(pSomeOtherObject);
66
+ PY_INTERFACE_POSTCALL;
67
+ pSomeOtherObject->Release();
68
+ --------------------------------------------------------------------
69
+ */
70
+ #ifndef __PYTHONCOM_H__
71
+ #define __PYTHONCOM_H__
72
+
73
+ // #define _DEBUG_LIFETIMES // Trace COM object lifetimes.
74
+
75
+ #ifdef FREEZE_PYTHONCOM
76
+ /* The pythoncom module is being included in a frozen .EXE/.DLL */
77
+ #define PYCOM_EXPORT
78
+ #else
79
+ #ifdef BUILD_PYTHONCOM
80
+ /* We are building pythoncomXX.dll */
81
+ #define PYCOM_EXPORT __declspec(dllexport)
82
+ #else
83
+ /* This module uses pythoncomXX.dll */
84
+ #define PYCOM_EXPORT __declspec(dllimport)
85
+ #ifndef _DEBUG
86
+ #pragma comment(lib, "pythoncom.lib")
87
+ #else
88
+ #pragma comment(lib, "pythoncom_d.lib")
89
+ #endif
90
+ #endif
91
+ #endif
92
+
93
+ #ifdef __MINGW32__
94
+ // Special Mingw32 considerations.
95
+ #define NO_PYCOM_ENUMSTATPROPSTG
96
+ #define __try try
97
+ #define __except catch
98
+ #include <olectl.h>
99
+
100
+ #endif // __MINGW32__
101
+
102
+ #include <PyWinTypes.h> // Standard Win32 Types
103
+
104
+ #include <dispex.h> // New header for IDispatchEx interface.
105
+
106
+ #if defined(MAINWIN)
107
+ // Mainwin seems to have 1/2 the VT_RECORD infrastructure in place
108
+ #if !defined(VT_RECORD)
109
+ #define VT_RECORD 36
110
+ #define V_RECORDINFO(X) ((X)->brecVal.pRecInfo)
111
+ #define V_RECORD(X) ((X)->brecVal.pvRecord)
112
+ #else
113
+ #pragma message( \
114
+ "MAINWIN appears to have grown correct VT_RECORD " \
115
+ "support. Please update PythonCOM.h accordingly")
116
+ #endif // VT_RECORD
117
+ #endif // MAINWIN
118
+
119
+ class PyIUnknown;
120
+ // To make life interesting/complicated, I use C++ classes for
121
+ // all Python objects. The main advantage is that I can derive
122
+ // a PyIDispatch object from a PyIUnknown, etc. This provides a
123
+ // clean C++ interface, and "automatically" provides all base
124
+ // Python methods to "derived" Python types.
125
+ //
126
+ // Main disadvantage is that any extension DLLs will need to include
127
+ // these headers, and link with this .lib
128
+ //
129
+ // Base class for (most of) the type objects.
130
+
131
+ class PYCOM_EXPORT PyComTypeObject : public PyTypeObject {
132
+ public:
133
+ PyComTypeObject(const char *name, PyComTypeObject *pBaseType, Py_ssize_t typeSize, struct PyMethodDef *methodList,
134
+ PyIUnknown *(*thector)(IUnknown *));
135
+ ~PyComTypeObject();
136
+
137
+ // is the given object an interface type object? (e.g. PyIUnknown)
138
+ static BOOL is_interface_type(PyObject *ob);
139
+
140
+ public:
141
+ PyIUnknown *(*ctor)(IUnknown *);
142
+ };
143
+
144
+ // A type used for interfaces that can automatically provide enumerators
145
+ // (ie, they themselves aren't enumerable, but do have a suitable default
146
+ // method that returns a PyIEnum object
147
+ class PYCOM_EXPORT PyComEnumProviderTypeObject : public PyComTypeObject {
148
+ public:
149
+ PyComEnumProviderTypeObject(const char *name, PyComTypeObject *pBaseType, Py_ssize_t typeSize,
150
+ struct PyMethodDef *methodList, PyIUnknown *(*thector)(IUnknown *),
151
+ const char *enum_method_name);
152
+ static PyObject *iter(PyObject *self);
153
+ const char *enum_method_name;
154
+ };
155
+
156
+ // A type used for PyIEnum interfaces
157
+ class PYCOM_EXPORT PyComEnumTypeObject : public PyComTypeObject {
158
+ public:
159
+ static PyObject *iter(PyObject *self);
160
+ static PyObject *iternext(PyObject *self);
161
+ PyComEnumTypeObject(const char *name, PyComTypeObject *pBaseType, Py_ssize_t typeSize,
162
+ struct PyMethodDef *methodList, PyIUnknown *(*thector)(IUnknown *));
163
+ };
164
+
165
+ // Very very base class - not COM specific - Should exist in the
166
+ // Python core somewhere, IMO.
167
+ class PYCOM_EXPORT PyIBase : public PyObject {
168
+ public:
169
+ // virtuals for Python support
170
+ virtual PyObject *getattr(char *name);
171
+ virtual int setattr(char *name, PyObject *v);
172
+ virtual PyObject *repr();
173
+ virtual int compare(PyObject *other)
174
+ {
175
+ if (this == other)
176
+ return 0;
177
+ if (this < other)
178
+ return -1;
179
+ return 1;
180
+ }
181
+ // These iter are a little special, in that returning NULL means
182
+ // use the implementation in the type
183
+ virtual PyObject *iter() { return NULL; }
184
+ virtual PyObject *iternext() { return NULL; }
185
+
186
+ protected:
187
+ PyIBase();
188
+ virtual ~PyIBase();
189
+
190
+ public:
191
+ static BOOL is_object(PyObject *, PyComTypeObject *which);
192
+ BOOL is_object(PyComTypeObject *which);
193
+ static void dealloc(PyObject *ob);
194
+ static PyObject *repr(PyObject *ob);
195
+ static PyObject *getattro(PyObject *self, PyObject *name);
196
+ static int setattro(PyObject *op, PyObject *obname, PyObject *v);
197
+ static int cmp(PyObject *ob1, PyObject *ob2);
198
+ static PyObject *richcmp(PyObject *ob1, PyObject *ob2, int op);
199
+ };
200
+
201
+ /* Special Type objects */
202
+ extern PYCOM_EXPORT PyTypeObject PyOleEmptyType; // equivalent to VT_EMPTY
203
+ extern PYCOM_EXPORT PyTypeObject PyOleMissingType; // special Python handling.
204
+ extern PYCOM_EXPORT PyTypeObject PyOleArgNotFoundType; // special VT_ERROR value
205
+ extern PYCOM_EXPORT PyTypeObject PyOleNothingType; // special VT_ERROR value
206
+
207
+ // ALL of these set an appropriate Python error on bad return.
208
+
209
+ // Given a Python object that is a registered COM type, return a given
210
+ // interface pointer on its underlying object, with a new reference added.
211
+ PYCOM_EXPORT BOOL PyCom_InterfaceFromPyObject(PyObject *ob, REFIID iid, LPVOID *ppv, BOOL bNoneOK = TRUE);
212
+
213
+ // As above, but allows instance with "_oleobj_" attribute.
214
+ PYCOM_EXPORT BOOL PyCom_InterfaceFromPyInstanceOrObject(PyObject *ob, REFIID iid, LPVOID *ppv, BOOL bNoneOK = TRUE);
215
+
216
+ // Release an arbitary COM pointer.
217
+ // NOTE: the PRECALL/POSTCALL stuff is probably not strictly necessary
218
+ // since the PyGILSTATE stuff has been in place (and even then, it only
219
+ // mattered when it was the last Release() on a Python implemented object)
220
+ #define PYCOM_RELEASE(pUnk) \
221
+ { \
222
+ if (pUnk) { \
223
+ PY_INTERFACE_PRECALL; \
224
+ (pUnk)->Release(); \
225
+ PY_INTERFACE_POSTCALL; \
226
+ } \
227
+ }
228
+
229
+ // Given an IUnknown and an Interface ID, create and return an object
230
+ // of the appropriate type. eg IID_Unknown->PyIUnknown,
231
+ // IID_IDispatch->PyIDispatch, etc.
232
+ // Uses a map that external extension DLLs can populate with their IID/type.
233
+ // Under the principal of least surprise, this will return Py_None is punk is NULL.
234
+ // Otherwise, a valid PyI*, but with NULL m_obj (and therefore totally useless)
235
+ // object would be created.
236
+ // BOOL bAddRef indicates if a COM reference count should be added to the IUnknown.
237
+ // This depends purely on the context in which it is called. If the IUnknown is obtained
238
+ // from a function that creates a new ref (eg, CoCreateInstance()) then you should use
239
+ // FALSE. If you receive the pointer as (eg) a param to a gateway function, then
240
+ // you normally need to pass TRUE, as this is truly a new reference.
241
+ // *** ALWAYS take the time to get this right. ***
242
+ PYCOM_EXPORT PyObject *PyCom_PyObjectFromIUnknown(IUnknown *punk, REFIID riid, BOOL bAddRef = FALSE);
243
+
244
+ // VARIANT <-> PyObject conversion utilities.
245
+ PYCOM_EXPORT BOOL PyCom_VariantFromPyObject(PyObject *obj, VARIANT *var);
246
+ PYCOM_EXPORT PyObject *PyCom_PyObjectFromVariant(const VARIANT *var);
247
+
248
+ // PROPVARIANT
249
+ PYCOM_EXPORT PyObject *PyObject_FromPROPVARIANT(PROPVARIANT *pVar);
250
+ PYCOM_EXPORT PyObject *PyObject_FromPROPVARIANTs(PROPVARIANT *pVars, ULONG cVars);
251
+ PYCOM_EXPORT BOOL PyObject_AsPROPVARIANT(PyObject *ob, PROPVARIANT *pVar);
252
+
253
+ // Other conversion helpers...
254
+ PYCOM_EXPORT PyObject *PyCom_PyObjectFromSTATSTG(STATSTG *pStat);
255
+ PYCOM_EXPORT BOOL PyCom_PyObjectAsSTATSTG(PyObject *ob, STATSTG *pStat, DWORD flags = 0);
256
+ PYCOM_EXPORT BOOL PyCom_SAFEARRAYFromPyObject(PyObject *obj, SAFEARRAY **ppSA, VARENUM vt = VT_VARIANT);
257
+ PYCOM_EXPORT PyObject *PyCom_PyObjectFromSAFEARRAY(SAFEARRAY *psa, VARENUM vt = VT_VARIANT);
258
+ #ifndef NO_PYCOM_STGOPTIONS
259
+ PYCOM_EXPORT BOOL PyCom_PyObjectAsSTGOPTIONS(PyObject *obstgoptions, STGOPTIONS **ppstgoptions, TmpWCHAR *tmpw_shelve);
260
+ #endif
261
+ PYCOM_EXPORT PyObject *PyCom_PyObjectFromSTATPROPSETSTG(STATPROPSETSTG *pStat);
262
+ PYCOM_EXPORT BOOL PyCom_PyObjectAsSTATPROPSETSTG(PyObject *, STATPROPSETSTG *);
263
+
264
+ // Currency support.
265
+ PYCOM_EXPORT PyObject *PyObject_FromCurrency(CURRENCY &cy);
266
+ PYCOM_EXPORT BOOL PyObject_AsCurrency(PyObject *ob, CURRENCY *pcy);
267
+
268
+ // Decimal support.
269
+ PYCOM_EXPORT PyObject *PyObject_FromDecimal(DECIMAL &dec);
270
+ PYCOM_EXPORT BOOL PyObject_AsDecimal(PyObject *ob, DECIMAL *pdec);
271
+
272
+ // OLEMENUGROUPWIDTHS are used by axcontrol, shell, etc
273
+ PYCOM_EXPORT BOOL PyObject_AsOLEMENUGROUPWIDTHS(PyObject *oblpMenuWidths, OLEMENUGROUPWIDTHS *pWidths);
274
+ PYCOM_EXPORT PyObject *PyObject_FromOLEMENUGROUPWIDTHS(const OLEMENUGROUPWIDTHS *pWidths);
275
+
276
+ /* Functions for Initializing COM, and also letting the core know about it!
277
+ */
278
+ PYCOM_EXPORT HRESULT PyCom_CoInitializeEx(LPVOID reserved, DWORD dwInit);
279
+ PYCOM_EXPORT HRESULT PyCom_CoInitialize(LPVOID reserved);
280
+ PYCOM_EXPORT void PyCom_CoUninitialize();
281
+
282
+ ///////////////////////////////////////////////////////////////////
283
+ // Error related functions
284
+
285
+ // Client related functions - generally called by interfaces before
286
+ // they return NULL back to Python to indicate the error.
287
+ // All these functions return NULL so interfaces can generally
288
+ // just "return PyCom_BuildPyException(hr, punk, IID_IWhatever)"
289
+
290
+ // Uses the HRESULT, and IErrorInfo interfaces if available to
291
+ // create and set a pythoncom.com_error.
292
+ PYCOM_EXPORT PyObject *PyCom_BuildPyException(HRESULT hr, IUnknown *pUnk = NULL, REFIID iid = IID_NULL);
293
+
294
+ // Uses the HRESULT and an EXCEPINFO structure to create and
295
+ // set a pythoncom.com_error.
296
+ PYCOM_EXPORT PyObject *PyCom_BuildPyExceptionFromEXCEPINFO(HRESULT hr, EXCEPINFO *pexcepInfo, UINT nArgErr = (UINT)-1);
297
+
298
+ // Sets a pythoncom.internal_error - no one should ever see these!
299
+ PYCOM_EXPORT PyObject *PyCom_BuildInternalPyException(char *msg);
300
+
301
+ // Log an error to a Python logger object if one can be found, or
302
+ // to stderr if no log available.
303
+ // If logProvider is not NULL, we will call a "_GetLogger_()" method on it.
304
+ // If logProvider is NULL, we attempt to fetch "win32com.logger".
305
+ // If they do not exist, return None, or raise an error fetching them
306
+ // (or even writing to them once fetched), the message still goes to stderr.
307
+ // NOTE: By default, win32com does *not* provide a logger, so default is that
308
+ // all errors are written to stdout.
309
+ // This will *not* write a record if a COM Server error is current.
310
+ PYCOM_EXPORT void PyCom_LoggerNonServerException(PyObject *logProvider, const WCHAR *fmt, ...);
311
+
312
+ // Write an error record, including exception. This will write an error
313
+ // record even if a COM server error is current.
314
+ PYCOM_EXPORT void PyCom_LoggerException(PyObject *logProvider, const WCHAR *fmt, ...);
315
+
316
+ // Write a warning record - in general this does *not* mean a call failed, but
317
+ // still is something in the programmers control that they should change.
318
+ // XXX - if an exception is pending when this is called, the traceback will
319
+ // also be written. This is undesirable and will be changed should this
320
+ // start being a problem.
321
+ PYCOM_EXPORT void PyCom_LoggerWarning(PyObject *logProvider, const WCHAR *fmt, ...);
322
+
323
+ // Server related error functions
324
+ // These are supplied so that any Python errors we detect can be
325
+ // converted into COM error information. The HRESULT returned should
326
+ // be returned by the COM function, and these functions also set the
327
+ // IErrorInfo interfaces, so the caller can extract more detailed
328
+ // information about the Python exception.
329
+
330
+ // Set a COM exception, logging the exception if not an explicitly raised 'server' exception
331
+ PYCOM_EXPORT HRESULT PyCom_SetAndLogCOMErrorFromPyException(const char *methodName, REFIID riid /* = IID_NULL */);
332
+ PYCOM_EXPORT HRESULT PyCom_SetAndLogCOMErrorFromPyExceptionEx(PyObject *provider, const char *methodName,
333
+ REFIID riid /* = IID_NULL */);
334
+
335
+ // Used in gateways to SetErrorInfo() with a simple HRESULT, then return it.
336
+ // The description is generally only useful for debugging purposes,
337
+ // and if you are debugging via a server that supports IErrorInfo (like Python :-)
338
+ // NOTE: this function is usuable from outside the Python context
339
+ PYCOM_EXPORT HRESULT PyCom_SetCOMErrorFromSimple(HRESULT hr, REFIID riid = IID_NULL, const WCHAR *description = NULL);
340
+
341
+ // Used in gateways to check if an IEnum*'s Next() or Clone() method worked.
342
+ PYCOM_EXPORT HRESULT PyCom_CheckIEnumNextResult(HRESULT hr, REFIID riid);
343
+
344
+ // Used in gateways when an enumerator expected a sequence but didn't get it.
345
+ PYCOM_EXPORT HRESULT PyCom_HandleIEnumNoSequence(REFIID riid);
346
+
347
+ // Used in gateways to SetErrorInfo() the current Python exception, and
348
+ // (assuming not a server error explicitly raised) also logs an error
349
+ // to stdout/win32com.logger.
350
+ // NOTE: this function assumes GIL held
351
+ PYCOM_EXPORT HRESULT PyCom_SetCOMErrorFromPyException(REFIID riid = IID_NULL);
352
+
353
+ // A couple of EXCEPINFO helpers - could be private to IDispatch
354
+ // if it wasn't for the AXScript support (and ITypeInfo if we get around to that :-)
355
+ // These functions do not set any error states to either Python or
356
+ // COM - they simply convert to/from PyObjects and EXCEPINFOs
357
+
358
+ // Use the current Python exception to fill an EXCEPINFO structure.
359
+ PYCOM_EXPORT void PyCom_ExcepInfoFromPyException(EXCEPINFO *pExcepInfo);
360
+
361
+ // Fill in an EXCEPINFO structure from a Python instance or tuple object.
362
+ // (ie, similar to the above, except the Python exception object is specified,
363
+ // rather than using the "current"
364
+ PYCOM_EXPORT BOOL PyCom_ExcepInfoFromPyObject(PyObject *obExcepInfo, EXCEPINFO *pexcepInfo, HRESULT *phresult = NULL);
365
+
366
+ // Create a Python object holding the exception information. The exception
367
+ // information is *not* freed by this function. Python exceptions are
368
+ // raised and NULL is returned if an error occurs.
369
+ PYCOM_EXPORT PyObject *PyCom_PyObjectFromExcepInfo(const EXCEPINFO *pexcepInfo);
370
+
371
+ ///////////////////////////////////////////////////////////////////
372
+ //
373
+ // External C++ helpers - these helpers are for other DLLs which
374
+ // may need similar functionality, but don't want to duplicate all
375
+
376
+ // This helper is for an application that has an IDispatch, and COM arguments
377
+ // and wants to call a Python function. It is assumed the caller can map the IDispatch
378
+ // to a Python object, so the Python handler is passed.
379
+ // Args:
380
+ // handler : A Python callable object.
381
+ // dispparms : the COM arguments.
382
+ // pVarResult : The variant for the return value of the Python call.
383
+ // pexcepinfo : Exception info the helper may fill out.
384
+ // puArgErr : Argument error the helper may fill out on exception
385
+ // addnArgs : Any additional arguments to the Python function. May be NULL.
386
+ // If addnArgs is NULL, then it is assumed the Python call should be native -
387
+ // ie, the COM args are packed as normal Python args to the call.
388
+ // If addnArgs is NOT NULL, it is assumed the Python function itself is
389
+ // a helper. This Python function will be called with 2 arguments - both
390
+ // tuples - first one is the COM args, second is the addn args.
391
+ PYCOM_EXPORT BOOL PyCom_MakeOlePythonCall(PyObject *handler, DISPPARAMS FAR *params, VARIANT FAR *pVarResult,
392
+ EXCEPINFO FAR *pexcepinfo, UINT FAR *puArgErr, PyObject *addnlArgs);
393
+
394
+ /////////////////////////////////////////////////////////////////////////////
395
+ // Various special purpose singletons
396
+ class PYCOM_EXPORT PyOleEmpty : public PyObject {
397
+ public:
398
+ PyOleEmpty();
399
+ };
400
+
401
+ class PYCOM_EXPORT PyOleMissing : public PyObject {
402
+ public:
403
+ PyOleMissing();
404
+ };
405
+
406
+ class PYCOM_EXPORT PyOleArgNotFound : public PyObject {
407
+ public:
408
+ PyOleArgNotFound();
409
+ };
410
+
411
+ class PYCOM_EXPORT PyOleNothing : public PyObject {
412
+ public:
413
+ PyOleNothing();
414
+ };
415
+
416
+ // We need to dynamically create C++ Python objects
417
+ // These helpers allow each type object to create it.
418
+ #define MAKE_PYCOM_CTOR(classname) \
419
+ static PyIUnknown *PyObConstruct(IUnknown *pInitObj) { return new classname(pInitObj); }
420
+ #define MAKE_PYCOM_CTOR_ERRORINFO(classname, iid) \
421
+ static PyIUnknown *PyObConstruct(IUnknown *pInitObj) { return new classname(pInitObj); } \
422
+ static PyObject *SetPythonCOMError(PyObject *self, HRESULT hr) \
423
+ { \
424
+ return PyCom_BuildPyException(hr, GetI(self), iid); \
425
+ }
426
+ #define GET_PYCOM_CTOR(classname) classname::PyObConstruct
427
+
428
+ // Macros that interfaces should use. PY_INTERFACE_METHOD at the top of the method
429
+ // The other 2 wrap directly around the underlying method call.
430
+ #define PY_INTERFACE_METHOD
431
+ // Identical to Py_BEGIN_ALLOW_THREADS except no { !!!
432
+ #define PY_INTERFACE_PRECALL PyThreadState *_save = PyEval_SaveThread()
433
+ #define PY_INTERFACE_POSTCALL PyEval_RestoreThread(_save)
434
+
435
+ /////////////////////////////////////////////////////////////////////////////
436
+ // class PyIUnknown
437
+ class PYCOM_EXPORT PyIUnknown : public PyIBase {
438
+ public:
439
+ MAKE_PYCOM_CTOR(PyIUnknown);
440
+ virtual PyObject *repr();
441
+ virtual int compare(PyObject *other);
442
+
443
+ static IUnknown *GetI(PyObject *self);
444
+ IUnknown *m_obj;
445
+ static char *szErrMsgObjectReleased;
446
+ static void SafeRelease(PyIUnknown *ob);
447
+ static PyComTypeObject type;
448
+
449
+ // The Python methods
450
+ static PyObject *QueryInterface(PyObject *self, PyObject *args);
451
+ static PyObject *SafeRelease(PyObject *self, PyObject *args);
452
+
453
+ protected:
454
+ PyIUnknown(IUnknown *punk);
455
+ ~PyIUnknown();
456
+ };
457
+
458
+ /////////////////////////////////////////////////////////////////////////////
459
+ // class PyIDispatch
460
+
461
+ class PYCOM_EXPORT PyIDispatch : public PyIUnknown {
462
+ public:
463
+ MAKE_PYCOM_CTOR(PyIDispatch);
464
+ static IDispatch *GetI(PyObject *self);
465
+ static PyComTypeObject type;
466
+
467
+ // The Python methods
468
+ static PyObject *Invoke(PyObject *self, PyObject *args);
469
+ static PyObject *InvokeTypes(PyObject *self, PyObject *args);
470
+ static PyObject *GetIDsOfNames(PyObject *self, PyObject *args);
471
+ static PyObject *GetTypeInfo(PyObject *self, PyObject *args);
472
+ static PyObject *GetTypeInfoCount(PyObject *self, PyObject *args);
473
+
474
+ protected:
475
+ PyIDispatch(IUnknown *pdisp);
476
+ ~PyIDispatch();
477
+ };
478
+
479
+ /////////////////////////////////////////////////////////////////////////////
480
+ // class PyIDispatchEx
481
+
482
+ class PYCOM_EXPORT PyIDispatchEx : public PyIDispatch {
483
+ public:
484
+ MAKE_PYCOM_CTOR_ERRORINFO(PyIDispatchEx, IID_IDispatchEx);
485
+ static IDispatchEx *GetI(PyObject *self);
486
+ static PyComTypeObject type;
487
+
488
+ // The Python methods
489
+ static PyObject *GetDispID(PyObject *self, PyObject *args);
490
+ static PyObject *InvokeEx(PyObject *self, PyObject *args);
491
+ static PyObject *DeleteMemberByName(PyObject *self, PyObject *args);
492
+ static PyObject *DeleteMemberByDispID(PyObject *self, PyObject *args);
493
+ static PyObject *GetMemberProperties(PyObject *self, PyObject *args);
494
+ static PyObject *GetMemberName(PyObject *self, PyObject *args);
495
+ static PyObject *GetNextDispID(PyObject *self, PyObject *args);
496
+
497
+ protected:
498
+ PyIDispatchEx(IUnknown *pdisp);
499
+ ~PyIDispatchEx();
500
+ };
501
+
502
+ /////////////////////////////////////////////////////////////////////////////
503
+ // class PyIClassFactory
504
+
505
+ class PYCOM_EXPORT PyIClassFactory : public PyIUnknown {
506
+ public:
507
+ MAKE_PYCOM_CTOR(PyIClassFactory);
508
+ static IClassFactory *GetI(PyObject *self);
509
+ static PyComTypeObject type;
510
+
511
+ // The Python methods
512
+ static PyObject *CreateInstance(PyObject *self, PyObject *args);
513
+ static PyObject *LockServer(PyObject *self, PyObject *args);
514
+
515
+ protected:
516
+ PyIClassFactory(IUnknown *pdisp);
517
+ ~PyIClassFactory();
518
+ };
519
+
520
+ /////////////////////////////////////////////////////////////////////////////
521
+ // class PyIProvideTypeInfo
522
+
523
+ class PYCOM_EXPORT PyIProvideClassInfo : public PyIUnknown {
524
+ public:
525
+ MAKE_PYCOM_CTOR(PyIProvideClassInfo);
526
+ static IProvideClassInfo *GetI(PyObject *self);
527
+ static PyComTypeObject type;
528
+
529
+ // The Python methods
530
+ static PyObject *GetClassInfo(PyObject *self, PyObject *args);
531
+
532
+ protected:
533
+ PyIProvideClassInfo(IUnknown *pdisp);
534
+ ~PyIProvideClassInfo();
535
+ };
536
+
537
+ class PYCOM_EXPORT PyIProvideClassInfo2 : public PyIProvideClassInfo {
538
+ public:
539
+ MAKE_PYCOM_CTOR(PyIProvideClassInfo2);
540
+ static IProvideClassInfo2 *GetI(PyObject *self);
541
+ static PyComTypeObject type;
542
+
543
+ // The Python methods
544
+ static PyObject *GetGUID(PyObject *self, PyObject *args);
545
+
546
+ protected:
547
+ PyIProvideClassInfo2(IUnknown *pdisp);
548
+ ~PyIProvideClassInfo2();
549
+ };
550
+
551
+ /////////////////////////////////////////////////////////////////////////////
552
+ // class PyITypeInfo
553
+ class PYCOM_EXPORT PyITypeInfo : public PyIUnknown {
554
+ public:
555
+ MAKE_PYCOM_CTOR(PyITypeInfo);
556
+ static PyComTypeObject type;
557
+ static ITypeInfo *GetI(PyObject *self);
558
+
559
+ PyObject *GetContainingTypeLib();
560
+ PyObject *GetDocumentation(MEMBERID);
561
+ PyObject *GetRefTypeInfo(HREFTYPE href);
562
+ PyObject *GetRefTypeOfImplType(int index);
563
+ PyObject *GetFuncDesc(int pos);
564
+ PyObject *GetIDsOfNames(OLECHAR FAR *FAR *, int);
565
+ PyObject *GetNames(MEMBERID);
566
+ PyObject *GetTypeAttr();
567
+ PyObject *GetVarDesc(int pos);
568
+ PyObject *GetImplTypeFlags(int index);
569
+ PyObject *GetTypeComp();
570
+
571
+ protected:
572
+ PyITypeInfo(IUnknown *);
573
+ ~PyITypeInfo();
574
+ };
575
+
576
+ /////////////////////////////////////////////////////////////////////////////
577
+ // class PyITypeComp
578
+ class PYCOM_EXPORT PyITypeComp : public PyIUnknown {
579
+ public:
580
+ MAKE_PYCOM_CTOR(PyITypeComp);
581
+ static PyComTypeObject type;
582
+ static ITypeComp *GetI(PyObject *self);
583
+
584
+ PyObject *Bind(OLECHAR *szName, unsigned short wflags);
585
+ PyObject *BindType(OLECHAR *szName);
586
+
587
+ protected:
588
+ PyITypeComp(IUnknown *);
589
+ ~PyITypeComp();
590
+ };
591
+
592
+ /////////////////////////////////////////////////////////////////////////////
593
+ // class CPyTypeLib
594
+
595
+ class PYCOM_EXPORT PyITypeLib : public PyIUnknown {
596
+ public:
597
+ MAKE_PYCOM_CTOR(PyITypeLib);
598
+ static PyComTypeObject type;
599
+ static ITypeLib *GetI(PyObject *self);
600
+
601
+ PyObject *GetLibAttr();
602
+ PyObject *GetDocumentation(int pos);
603
+ PyObject *GetTypeInfo(int pos);
604
+ PyObject *GetTypeInfoCount();
605
+ PyObject *GetTypeInfoOfGuid(REFGUID guid);
606
+ PyObject *GetTypeInfoType(int pos);
607
+ PyObject *GetTypeComp();
608
+
609
+ protected:
610
+ PyITypeLib(IUnknown *);
611
+ ~PyITypeLib();
612
+ };
613
+
614
+ /////////////////////////////////////////////////////////////////////////////
615
+ // class PyIConnectionPoint
616
+
617
+ class PYCOM_EXPORT PyIConnectionPoint : public PyIUnknown {
618
+ public:
619
+ MAKE_PYCOM_CTOR_ERRORINFO(PyIConnectionPoint, IID_IConnectionPoint);
620
+ static PyComTypeObject type;
621
+ static IConnectionPoint *GetI(PyObject *self);
622
+
623
+ static PyObject *GetConnectionInterface(PyObject *self, PyObject *args);
624
+ static PyObject *GetConnectionPointContainer(PyObject *self, PyObject *args);
625
+ static PyObject *Advise(PyObject *self, PyObject *args);
626
+ static PyObject *Unadvise(PyObject *self, PyObject *args);
627
+ static PyObject *EnumConnections(PyObject *self, PyObject *args);
628
+
629
+ protected:
630
+ PyIConnectionPoint(IUnknown *);
631
+ ~PyIConnectionPoint();
632
+ };
633
+
634
+ class PYCOM_EXPORT PyIConnectionPointContainer : public PyIUnknown {
635
+ public:
636
+ MAKE_PYCOM_CTOR_ERRORINFO(PyIConnectionPointContainer, IID_IConnectionPointContainer);
637
+ static PyComTypeObject type;
638
+ static IConnectionPointContainer *GetI(PyObject *self);
639
+
640
+ static PyObject *EnumConnectionPoints(PyObject *self, PyObject *args);
641
+ static PyObject *FindConnectionPoint(PyObject *self, PyObject *args);
642
+
643
+ protected:
644
+ PyIConnectionPointContainer(IUnknown *);
645
+ ~PyIConnectionPointContainer();
646
+ };
647
+
648
+ /////////////////////////////////////////////////////////////////////////////
649
+ // class PythonOleArgHelper
650
+ //
651
+ // A PythonOleArgHelper is used primarily to help out Python helpers
652
+ // which need to convert from a Python object when the specific OLE
653
+ // type is known - eg, when a TypeInfo is available.
654
+ //
655
+ // The type of conversion determines who owns what buffers etc. I wish BYREF didn't exist :-)
656
+ typedef enum {
657
+ // We don't know what sort of conversion it is yet.
658
+ POAH_CONVERT_UNKNOWN,
659
+ // A PyObject is given, we convert to a VARIANT, make the COM call, then BYREFs back to a PyObject
660
+ // ie, this is typically a "normal" COM call, where Python initiates the call
661
+ POAH_CONVERT_FROM_PYOBJECT,
662
+ // A VARIANT is given, we convert to a PyObject, make the Python call, then BYREFs back to a VARIANT.
663
+ // ie, this is typically handling a COM event, where COM itself initiates the call.
664
+ POAH_CONVERT_FROM_VARIANT,
665
+ } POAH_CONVERT_DIRECTION;
666
+
667
+ class PYCOM_EXPORT PythonOleArgHelper {
668
+ public:
669
+ PythonOleArgHelper();
670
+ ~PythonOleArgHelper();
671
+ BOOL ParseTypeInformation(PyObject *reqdObjectTuple);
672
+
673
+ // Using this call with reqdObject != NULL will check the existing
674
+ // VT_ of the variant. If not VT_EMPTY, then the result will be coerced to
675
+ // that type. This contrasts with PyCom_PyObjectToVariant which just
676
+ // uses the Python type to determine the variant type.
677
+ BOOL MakeObjToVariant(PyObject *obj, VARIANT *var, PyObject *reqdObjectTuple = NULL);
678
+ PyObject *MakeVariantToObj(VARIANT *var);
679
+
680
+ VARTYPE m_reqdType;
681
+ BOOL m_bParsedTypeInfo;
682
+ BOOL m_bIsOut;
683
+ POAH_CONVERT_DIRECTION m_convertDirection;
684
+ PyObject *m_pyVariant; // if non-null, a win32com.client.VARIANT
685
+ union {
686
+ void *m_pValueHolder;
687
+ short m_sBuf;
688
+ long m_lBuf;
689
+ LONGLONG m_llBuf;
690
+ VARIANT_BOOL m_boolBuf;
691
+ double m_dBuf;
692
+ float m_fBuf;
693
+ IDispatch *m_dispBuf;
694
+ IUnknown *m_unkBuf;
695
+ SAFEARRAY *m_arrayBuf;
696
+ VARIANT *m_varBuf;
697
+ DATE m_dateBuf;
698
+ CY m_cyBuf;
699
+ DECIMAL m_decBuf;
700
+ };
701
+ };
702
+
703
+ /////////////////////////////////////////////////////////////////////////////
704
+ // global functions and variables
705
+ PYCOM_EXPORT BOOL MakePythonArgumentTuples(PyObject **pArgs, PythonOleArgHelper **ppHelpers, PyObject **pNamedArgs,
706
+ PythonOleArgHelper **ppNamedHelpers, DISPPARAMS FAR *params);
707
+
708
+ // Convert a Python object to a BSTR - allow embedded NULLs, None, etc.
709
+ PYCOM_EXPORT BOOL PyCom_BstrFromPyObject(PyObject *stringObject, BSTR *pResult, BOOL bNoneOK = FALSE);
710
+
711
+ // MakeBstrToObj - convert a BSTR into a Python string.
712
+ //
713
+ // ONLY USE THIS FOR TRUE BSTR's - Use the fn below for OLECHAR *'s.
714
+ // NOTE - does not use standard macros, so NULLs get through!
715
+ PYCOM_EXPORT PyObject *MakeBstrToObj(const BSTR bstr);
716
+
717
+ // Size info is available (eg, a fn returns a string and also fills in a size variable)
718
+ PYCOM_EXPORT PyObject *MakeOLECHARToObj(const OLECHAR *str, int numChars);
719
+
720
+ // No size info avail.
721
+ PYCOM_EXPORT PyObject *MakeOLECHARToObj(const OLECHAR *str);
722
+
723
+ PYCOM_EXPORT void PyCom_LogF(const WCHAR *fmt, ...);
724
+
725
+ // Generic conversion from python sequence to VT_VECTOR array
726
+ // Resulting array must be freed with CoTaskMemFree
727
+ template <typename arraytype>
728
+ BOOL SeqToVector(PyObject *ob, arraytype **pA, ULONG *pcount, BOOL (*converter)(PyObject *, arraytype *))
729
+ {
730
+ TmpPyObject seq = PyWinSequence_Tuple(ob, pcount);
731
+ if (seq == NULL)
732
+ return FALSE;
733
+ *pA = (arraytype *)CoTaskMemAlloc(*pcount * sizeof(arraytype));
734
+ if (*pA == NULL) {
735
+ PyErr_NoMemory();
736
+ return FALSE;
737
+ }
738
+ for (ULONG i = 0; i < *pcount; i++) {
739
+ PyObject *item = PyTuple_GET_ITEM((PyObject *)seq, i);
740
+ if (!(*converter)(item, &(*pA)[i]))
741
+ return FALSE;
742
+ }
743
+ return TRUE;
744
+ }
745
+
746
+ #endif // __PYTHONCOM_H__
loan-advisor-agent/.venv/Lib/site-packages/win32com/include/PythonCOMRegister.h ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Support for PythonCOM and its extensions to register the interfaces,
2
+ // gateways and IIDs it supports.
3
+ //
4
+ // The module can simply declare an array of type PyCom_InterfaceSupportInfo, then
5
+ // use the macros to populate it.
6
+ //
7
+ // See Register.cpp and AXScript.cpp for examples on its use.
8
+
9
+ #ifndef __PYTHONCOMREGISTER_H__
10
+ #define __PYTHONCOMREGISTER_H__
11
+
12
+ #include "PythonCOMServer.h" // Need defns in this file...
13
+
14
+ typedef struct {
15
+ const GUID *pGUID; // The supported IID - required
16
+ const char *interfaceName; // Name of the interface - required
17
+ const char *iidName; // Name of the IID that goes into the dict. - required
18
+ PyTypeObject *pTypeOb; // the type object for client PyI* side - NULL for server only support.
19
+ pfnPyGatewayConstructor ctor; // Gateway (PyG*) interface constructor - NULL for client only support
20
+
21
+ } PyCom_InterfaceSupportInfo;
22
+
23
+ #define PYCOM_INTERFACE_IID_ONLY(ifc) {&IID_I##ifc, "I" #ifc, "IID_I" #ifc, NULL, NULL}
24
+ #define PYCOM_INTERFACE_CLSID_ONLY(ifc) {&CLSID_##ifc, "CLSID_" #ifc, "CLSID_" #ifc, NULL, NULL}
25
+ #define PYCOM_INTERFACE_CATID_ONLY(ifc) {&CATID_##ifc, "CATID_" #ifc, "CATID_" #ifc, NULL, NULL}
26
+ #define PYCOM_INTERFACE_CLIENT_ONLY(ifc) {&IID_I##ifc, "I" #ifc, "IID_I" #ifc, &PyI##ifc::type, NULL}
27
+ #define PYCOM_INTERFACE_SERVER_ONLY(ifc) {&IID_I##ifc, "I" #ifc, "IID_I" #ifc, NULL, GET_PYGATEWAY_CTOR(PyG##ifc)}
28
+ #define PYCOM_INTERFACE_FULL(ifc) {&IID_I##ifc, "I" #ifc, "IID_I" #ifc, &PyI##ifc::type, GET_PYGATEWAY_CTOR(PyG##ifc)}
29
+
30
+ // Versions that use __uuidof() to get the IID, which seems to avoid the need
31
+ // to link with a lib holding the IIDs. Note that almost all extensions
32
+ // build with __uuidof() being the default; the build failed at 'shell' - so
33
+ // we could consider making this the default and making the 'explicit' version
34
+ // above the special case.
35
+ #define PYCOM_INTERFACE_IID_ONLY_UUIDOF(ifc) {&__uuidof(I##ifc), "I" #ifc, "IID_I" #ifc, NULL, NULL}
36
+ #define PYCOM_INTERFACE_CLIENT_ONLY_UUIDOF(ifc) {&__uuidof(I##ifc), "I" #ifc, "IID_I" #ifc, &PyI##ifc::type, NULL}
37
+ #define PYCOM_INTERFACE_SERVER_ONLY_UUIDOF(ifc) \
38
+ {&__uuidof(I##ifc), "I" #ifc, "IID_I" #ifc, NULL, GET_PYGATEWAY_CTOR(PyG##ifc)}
39
+ #define PYCOM_INTERFACE_FULL_UUIDOF(ifc) \
40
+ {&__uuidof(I##ifc), "I" #ifc, "IID_I" #ifc, &PyI##ifc::type, GET_PYGATEWAY_CTOR(PyG##ifc)}
41
+
42
+ // Prototypes for the register functions
43
+
44
+ // Register a PythonCOM extension module
45
+ PYCOM_EXPORT int PyCom_RegisterExtensionSupport(PyObject *dict, const PyCom_InterfaceSupportInfo *pInterfaces,
46
+ int numEntries);
47
+
48
+ // THESE SHOULD NO LONGER BE USED. Instead, use the functions above passing an
49
+ // array of PyCom_InterfaceSupportInfo objects.
50
+
51
+ PYCOM_EXPORT int PyCom_RegisterClientType(PyTypeObject *typeOb, const GUID *guid);
52
+
53
+ HRESULT PYCOM_EXPORT PyCom_RegisterGatewayObject(REFIID iid, pfnPyGatewayConstructor ctor, const char *interfaceName);
54
+ PYCOM_EXPORT int PyCom_IsGatewayRegistered(REFIID iid);
55
+
56
+ #endif /* __PYTHONCOMREGISTER_H__ */
loan-advisor-agent/.venv/Lib/site-packages/win32com/include/PythonCOMServer.h ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef __PYTHONCOMSERVER_H__
2
+ #define __PYTHONCOMSERVER_H__
3
+
4
+ // PythonCOMServer.h :Server side COM support
5
+
6
+ #include <Python.h>
7
+
8
+ #define DLLAcquireGlobalLock PyWin_AcquireGlobalLock
9
+ #define DLLReleaseGlobalLock PyWin_ReleaseGlobalLock
10
+
11
+ void PYCOM_EXPORT PyCom_DLLAddRef(void);
12
+ void PYCOM_EXPORT PyCom_DLLReleaseRef(void);
13
+
14
+ // Use this macro at the start of all gateway methods.
15
+ #define PY_GATEWAY_METHOD CEnterLeavePython _celp
16
+
17
+ class PyGatewayBase;
18
+ // Gateway constructors.
19
+ // Each gateway must be able to be created from a "gateway constructor". This
20
+ // is simply a function that takes a Python instance as as argument, and returns
21
+ // a gateway object of the correct type. The MAKE_PYGATEWAY_CTOR is a helper that
22
+ // will embed such a constructor in the class - however, this is not necessary -
23
+ // _any_ function of the correct signature can be used.
24
+
25
+ typedef HRESULT (*pfnPyGatewayConstructor)(PyObject *PythonInstance, PyGatewayBase *, void **ppResult, REFIID iid);
26
+ HRESULT PyCom_MakeRegisteredGatewayObject(REFIID iid, PyObject *instance, PyGatewayBase *base, void **ppv);
27
+
28
+ // A version of the above which support classes being derived from
29
+ // other than IUnknown
30
+ #define PYGATEWAY_MAKE_SUPPORT2(classname, IInterface, theIID, gatewaybaseclass) \
31
+ public: \
32
+ static HRESULT PyGatewayConstruct(PyObject *pPyInstance, PyGatewayBase *unkBase, void **ppResult, REFIID iid) \
33
+ { \
34
+ if (ppResult == NULL) \
35
+ return E_INVALIDARG; \
36
+ classname *newob = new classname(pPyInstance); \
37
+ newob->m_pBaseObject = unkBase; \
38
+ if (unkBase) \
39
+ unkBase->AddRef(); \
40
+ *ppResult = newob->ThisAsIID(iid); \
41
+ return *ppResult ? S_OK : E_OUTOFMEMORY; \
42
+ } \
43
+ \
44
+ protected: \
45
+ virtual IID GetIID(void) { return theIID; } \
46
+ virtual void *ThisAsIID(IID iid) \
47
+ { \
48
+ if (this == NULL) \
49
+ return NULL; \
50
+ if (iid == theIID) \
51
+ return (IInterface *)this; \
52
+ else \
53
+ return gatewaybaseclass::ThisAsIID(iid); \
54
+ } \
55
+ STDMETHOD_(ULONG, AddRef)(void) { return gatewaybaseclass::AddRef(); } \
56
+ STDMETHOD_(ULONG, Release)(void) { return gatewaybaseclass::Release(); } \
57
+ STDMETHOD(QueryInterface)(REFIID iid, void **obj) { return gatewaybaseclass::QueryInterface(iid, obj); };
58
+
59
+ // This is the "old" version to use, or use it if you derive
60
+ // directly from PyGatewayBase
61
+ #define PYGATEWAY_MAKE_SUPPORT(classname, IInterface, theIID) \
62
+ PYGATEWAY_MAKE_SUPPORT2(classname, IInterface, theIID, PyGatewayBase)
63
+
64
+ #define GET_PYGATEWAY_CTOR(classname) classname::PyGatewayConstruct
65
+
66
+ #ifdef _MSC_VER
67
+ // Disable an OK warning...
68
+ #pragma warning(disable : 4275)
69
+ // warning C4275: non dll-interface struct 'IDispatch' used as base for dll-interface class 'PyGatewayBase'
70
+ #endif // _MSC_VER
71
+
72
+ // Helper interface for fetching a Python object from a gateway
73
+
74
+ extern const GUID IID_IInternalUnwrapPythonObject;
75
+
76
+ interface IInternalUnwrapPythonObject : public IUnknown
77
+ {
78
+ public:
79
+ STDMETHOD(Unwrap)(PyObject * *ppPyObject) = 0;
80
+ };
81
+
82
+ /////////////////////////////////////////////////////////////////////////////
83
+ // PyGatewayBase
84
+ //
85
+ // Base class for all gateways.
86
+ //
87
+ class PYCOM_EXPORT PyGatewayBase : public IDispatchEx, // IDispatch comes along for the ride!
88
+ public ISupportErrorInfo,
89
+ public IInternalUnwrapPythonObject {
90
+ protected:
91
+ PyGatewayBase(PyObject *instance);
92
+ virtual ~PyGatewayBase();
93
+
94
+ // Invoke the Python method (via the policy object)
95
+ STDMETHOD(InvokeViaPolicy)(const char *szMethodName, PyObject **ppResult = NULL, const char *szFormat = NULL, ...);
96
+
97
+ public:
98
+ // IUnknown
99
+ STDMETHOD_(ULONG, AddRef)(void);
100
+ STDMETHOD_(ULONG, Release)(void);
101
+ STDMETHOD(QueryInterface)(REFIID iid, void **obj);
102
+
103
+ // IDispatch
104
+ STDMETHOD(GetTypeInfoCount)(UINT FAR *pctInfo);
105
+ STDMETHOD(GetTypeInfo)(UINT itinfo, LCID lcid, ITypeInfo FAR *FAR *pptInfo);
106
+ STDMETHOD(GetIDsOfNames)(REFIID refiid, OLECHAR FAR *FAR *rgszNames, UINT cNames, LCID lcid, DISPID FAR *rgdispid);
107
+ STDMETHOD(Invoke)
108
+ (DISPID dispid, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS FAR *params, VARIANT FAR *pVarResult,
109
+ EXCEPINFO FAR *pexcepinfo, UINT FAR *puArgErr);
110
+
111
+ // IDispatchEx
112
+ STDMETHOD(GetDispID)(BSTR bstrName, DWORD grfdex, DISPID *pid);
113
+ STDMETHOD(InvokeEx)
114
+ (DISPID id, LCID lcid, WORD wFlags, DISPPARAMS *pdp, VARIANT *pvarRes, EXCEPINFO *pei, IServiceProvider *pspCaller);
115
+ STDMETHOD(DeleteMemberByName)(BSTR bstr, DWORD grfdex);
116
+ STDMETHOD(DeleteMemberByDispID)(DISPID id);
117
+ STDMETHOD(GetMemberProperties)(DISPID id, DWORD grfdexFetch, DWORD *pgrfdex);
118
+ STDMETHOD(GetMemberName)(DISPID id, BSTR *pbstrName);
119
+ STDMETHOD(GetNextDispID)(DWORD grfdex, DISPID id, DISPID *pid);
120
+ STDMETHOD(GetNameSpaceParent)(IUnknown **ppunk);
121
+ // ISupportErrorInfo
122
+ STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid);
123
+
124
+ // IInternalUnwrapPythonObject
125
+ STDMETHOD(Unwrap)(PyObject **ppPyObject);
126
+
127
+ // Basically just PYGATEWAY_MAKE_SUPPORT(PyGatewayBase, IDispatch, IID_IDispatch);
128
+ // but with special handling as it's the base class.
129
+ static HRESULT PyGatewayConstruct(PyObject *pPyInstance, PyGatewayBase *gatewayBase, void **ppResult, REFIID iid)
130
+ {
131
+ if (ppResult == NULL)
132
+ return E_INVALIDARG;
133
+ PyGatewayBase *obNew = new PyGatewayBase(pPyInstance);
134
+ obNew->m_pBaseObject = gatewayBase;
135
+ if (gatewayBase)
136
+ gatewayBase->AddRef();
137
+ *ppResult = (IDispatch *)obNew;
138
+ return *ppResult ? S_OK : E_OUTOFMEMORY;
139
+ }
140
+ // Currently this is used only for ISupportErrorInfo,
141
+ // so hopefully this will never be called in this base class.
142
+ // (however, this is not a rule, so we won't assert or anything!)
143
+ virtual IID GetIID(void) { return IID_IUnknown; }
144
+ virtual void *ThisAsIID(IID iid);
145
+ // End of PYGATEWAY_MAKE_SUPPORT
146
+ PyObject *m_pPyObject;
147
+ PyGatewayBase *m_pBaseObject;
148
+
149
+ private:
150
+ LONG m_cRef;
151
+ };
152
+
153
+ #ifdef _MSC_VER
154
+ #pragma warning(default : 4275)
155
+ #endif // _MSC_VER
156
+
157
+ // B/W compat hack for gateways.
158
+ #define PyCom_HandlePythonFailureToCOM() \
159
+ PyCom_SetAndLogCOMErrorFromPyExceptionEx(this->m_pPyObject, "<unknown>", GetIID())
160
+
161
+ // F/W compat hack for gateways! Must be careful about updating
162
+ // PyGatewayBase vtable, so a slightly older pythoncomXX.dll will work
163
+ // with slightly later extensions. So use a #define.
164
+ #define MAKE_PYCOM_GATEWAY_FAILURE_CODE(method_name) \
165
+ PyCom_SetAndLogCOMErrorFromPyExceptionEx(this->m_pPyObject, method_name, GetIID())
166
+
167
+ #endif /* __PYTHONCOMSERVER_H__ */
loan-advisor-agent/.venv/Lib/site-packages/win32com/libs/axscript.lib ADDED
Binary file (72.5 kB). View file
 
loan-advisor-agent/.venv/Lib/site-packages/win32com/libs/pythoncom.lib ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:75c62974b13695933311de7acdde55bf517bad9861acc6afe34e5de8f51d3cc9
3
+ size 160662
loan-advisor-agent/.venv/Lib/site-packages/win32com/makegw/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # indicates a python package.