diff --git a/.clang-format b/.clang-format index 9767e004cf..397d92fcfd 100644 --- a/.clang-format +++ b/.clang-format @@ -1,20 +1,20 @@ # A clang-format style that approximates Python's PEP 7 # Useful for IDE integration +# https://clang.llvm.org/docs/ClangFormatStyleOptions.html#configurable-format-style-options +Language: Cpp BasedOnStyle: Google -AllowShortIfStatementsOnASingleLine: false + AlignAfterOpenBracket: Align +AllowShortIfStatementsOnASingleLine: false +AlwaysBreakAfterReturnType: None # Don't break after return type BreakBeforeBraces: Stroustrup ColumnLimit: 120 DerivePointerAlignment: false IndentWidth: 4 -Language: Cpp PointerAlignment: Right ReflowComments: true +SortIncludes: false # Sorting includes breaks build SpaceBeforeParens: ControlStatements SpacesInParentheses: false TabWidth: 4 UseTab: Never -# sorting includes breaks build -SortIncludes: false -# don't break after return type -AlwaysBreakAfterReturnType: None diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 95d0b0fc0e..4816d046ab 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -10,3 +10,6 @@ # 2024-05-28 formatted trailing-whitespaces and end-of-file with pre-commit 452e3dafc126faa978d67a946385bf2514477411 + +# 2024-05-28 formatted c++ source with clang-format +637448f8252ab142eedd539ddf9b08259b73eecc diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index fb05eee83e..3478f91f7d 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -110,7 +110,7 @@ jobs: python-version: "3.8" cache: pip cache-dependency-path: .github/workflows/main.yml - - run: pip install pycln + - run: pip install clang-format pycln - run: pycln . --config=pycln.toml --check - uses: chartboost/ruff-action@v1 with: @@ -118,6 +118,10 @@ jobs: - uses: psf/black@stable with: options: "--fast --check --diff --verbose" + - run: | # Too many files to fit in a single command, exclude vendored Scintilla and mapi_headers + clang-format --Werror --dry-run $(git ls-files '*.cpp') + clang-format --Werror --dry-run $(git ls-files '*.h' ':!:Pythonwin/Scintilla/' ':!:com/win32comext/mapi/src/mapi_headers/') + shell: powershell mypy: runs-on: windows-2019 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 19d63b2023..72acb051e0 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,7 +1,7 @@ # You can run this locally with `pre-commit run [--all]` repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.5.0 + rev: v4.6.0 hooks: - id: trailing-whitespace args: [--markdown-linebreak-ext=md] @@ -10,10 +10,10 @@ repos: args: [--fix=crlf] - id: check-case-conflict - repo: https://github.com/macisamuele/language-formatters-pre-commit-hooks - rev: v2.12.0 + rev: v2.13.0 hooks: - id: pretty-format-toml - args: [--autofix, --trailing-commas] + args: [--autofix, --trailing-commas, --inline-comment-spaces, "1", --no-sort] - id: pretty-format-yaml args: [--autofix, --indent, "2", --offset, "2", --preserve-quotes] - id: pretty-format-ini @@ -30,10 +30,18 @@ repos: - id: ruff # Run the linter. args: [--fix] - repo: https://github.com/psf/black-pre-commit-mirror - rev: 24.2.0 + rev: 24.4.2 hooks: - id: black verbose: true + - repo: https://github.com/pre-commit/mirrors-clang-format + rev: v18.1.5 + hooks: + - id: clang-format + # Supports a lot more filetypes, but only tagging those we use + # https://github.com/pre-commit/mirrors-clang-format/blob/main/.pre-commit-hooks.yaml#L6 + types: [c++] + # Vendored exclude: ^(com/win32comext/mapi/src/mapi_headers/|Pythonwin/Scintilla/).*$ diff --git a/AutoDuck/BuildHHP.py b/AutoDuck/BuildHHP.py index 52662d8f4a..aacc62e37f 100644 --- a/AutoDuck/BuildHHP.py +++ b/AutoDuck/BuildHHP.py @@ -41,7 +41,7 @@ def handle_globs(lGlobs): new = glob.glob(g) if len(new) == 0: print(f"The pattern '{g}' yielded no files!") - lFiles = lFiles + new + lFiles.extend(new) # lFiles is now the list of origin files. # Normalize all of the paths: cFiles = len(lFiles) @@ -52,9 +52,9 @@ def handle_globs(lGlobs): while i < cFiles: if not os.path.isfile(lFiles[i]): del lFiles[i] - cFiles = cFiles - 1 + cFiles -= 1 continue - i = i + 1 + i += 1 # Find the common prefix of all of the files sCommonPrefix = os.path.commonprefix(lFiles) # Damn - more commonprefix problems @@ -67,7 +67,7 @@ def handle_globs(lGlobs): # else we have a trailing slash - it means we _expect_ it to be a patch as-is. assert ( os.path.isdir(sCommonPrefix) and sCommonPrefix[-1] == "\\" - ), "commonprefix splitting aint gunna work!" + ), "commonprefix splitting ain't gunna work!" print("sCommonPrefix=", sCommonPrefix) # Ok, now remove this common prefix from every file: lRelativeFiles = [] @@ -111,12 +111,12 @@ def main(): shutil.copyfile(lSrcFiles[i], file) for file in lDestFiles: - html_files = html_files + f"{html_dir}\\{file}\n" + html_files += f"{html_dir}\\{file}\n" for cat in doc: - html_files = html_files + f"{output_dir}\\{cat.id}.html\n" + html_files += f"{output_dir}\\{cat.id}.html\n" for suffix in "_overview _modules _objects _constants".split(): - html_files = html_files + f"{output_dir}\\{cat.id}{suffix}.html\n" + html_files += f"{output_dir}\\{cat.id}{suffix}.html\n" f.write(sHHPFormat % {"output": output, "target": target, "html_files": html_files}) f.close() diff --git a/AutoDuck/Dump2HHC.py b/AutoDuck/Dump2HHC.py index 42790a9d81..ef16a38168 100644 --- a/AutoDuck/Dump2HHC.py +++ b/AutoDuck/Dump2HHC.py @@ -412,7 +412,7 @@ def genTOC(cats, output, title, target): **locals() ) ) - # Dont show 'children' for objects - params etc don't need their own child nodes! + # Don't show 'children' for objects - params etc don't need their own child nodes! _genItemsFromDict(cat.objects, cat, output, target, do_children=0) output.write( """ diff --git a/AutoDuck/InsertExternalOverviews.py b/AutoDuck/InsertExternalOverviews.py index ea7c2c7228..c0465e40bc 100644 --- a/AutoDuck/InsertExternalOverviews.py +++ b/AutoDuck/InsertExternalOverviews.py @@ -25,21 +25,21 @@ def processFile(input, out, extLinksHTML, extTopicHTML, importantHTML): def genHTML(doc): s = "" for cat in doc: - s = s + f"

{cat.label}

\n" + s += f"

{cat.label}

\n" dict = {} for item in cat.overviewItems.items: dict[item.name] = item.href keys = list(dict.keys()) keys.sort() for k in keys: - s = s + f'
  • {k}\n' + s += f'
  • {k}\n' return s def genLinksHTML(links): s = "" for link in links: - s = s + f'
  • {link.name}\n' + s += f'
  • {link.name}\n' return s diff --git a/AutoDuck/makedfromi.py b/AutoDuck/makedfromi.py index b83c51e201..4fd2f44acb 100644 --- a/AutoDuck/makedfromi.py +++ b/AutoDuck/makedfromi.py @@ -13,7 +13,7 @@ def GetComments(line, lineNo, lines): doc = "" if len(data) == 2: doc = data[1].strip() - lineNo = lineNo + 1 + lineNo += 1 while lineNo < len(lines): line = lines[lineNo] data = line.split("//", 2) @@ -24,10 +24,10 @@ def GetComments(line, lineNo, lines): if data[1].strip().startswith("@"): # new command break - doc = doc + "\n// " + data[1].strip() - lineNo = lineNo + 1 - # This line doesnt match - step back - lineNo = lineNo - 1 + doc += "\n// " + data[1].strip() + lineNo += 1 + # This line doesn't match - step back + lineNo -= 1 return doc, lineNo @@ -87,7 +87,7 @@ def make_doc_summary(inFile, outFile): _, msg, _ = sys.exc_info() print("Line %d is badly formed - %s" % (lineNo, msg)) - lineNo = lineNo + 1 + lineNo += 1 # autoduck seems to crash when > ~97 methods. Loop multiple times, # creating a synthetic module name when this happens. @@ -106,9 +106,9 @@ def make_doc_summary(inFile, outFile): if chunk_number == 0: pass elif chunk_number == 1: - thisModName = thisModName + " (more)" + thisModName += " (more)" else: - thisModName = thisModName + " (more %d)" % (chunk_number + 1,) + thisModName += " (more %d)" % (chunk_number + 1,) outFile.write("\n") for meth, extras in these_methods: diff --git a/CHANGES.txt b/CHANGES.txt index 1855816774..66426f629b 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -15,13 +15,15 @@ Coming in build 307, as yet unreleased -------------------------------------- ### pywin32 -* Marked `exc_type` and `exc_traceback` in `win32comext.axscript.client.error.AXScriptException.__init__` as deprecated. +* Add EnumDesktopWindows (#2219, @CristiFati) +* Marked `exc_type` and `exc_traceback` in `win32comext.axscript.client.error.AXScriptException.__init__` as deprecated. (#2236 , @Avasam) They are now unused and all information is taken from the `exc_value` parameter. * Fixed non-overriden `pywin.scintilla.formatter.Formatter.ColorizeString` raising `TypeError` instead of `RuntimeError` due to too many parameters (#2216, @Avasam) * Fixed broken since Python 3 tokenization in `win32comext.axdebug.codecontainer.pySourceCodeContainer.GetSyntaxColorAttributes` (#2216, @Avasam) * Fixed a `TypeError` due to incorrect kwargs in `win32comext.axscript.client.pydumper.Register` (#2216, @Avasam) * Fixed error reporting of file copy failure for for installing debug dlls (#2216, @Avasam) * Fixed `py.exe -m win32verstamp` command and other quote typos caused by Implied String Concatenation (#2225, @Avasam) +* Fixed tons of quote-related typos in strings, docs and comments (#2271 , @Avasam) * Fixed VT_SAFEARRAY(VT_RECORD) which were missing the last element (#2247) * Fixed `MFC redist DLLs not found` by preferring corresponding version but accepting different version (#2248, @andreabravetti) * Fixed `pywintypes.error: (5, 'RegOpenKeyEx', 'Access is denied.')` when running service with debug parameter and no elevation (#2238, @jmartens) @@ -135,6 +137,7 @@ Coming in build 307, as yet unreleased * Use byte-string (`b""`) for constant bytes values instead of superfluous `.encode` calls (#2046, @Avasam) * Cleaned up unused imports (#1986, #2051, #1990, #2124, #2126, @Avasam) * Removed duplicated declarations, constants and definitions (#2050 , #1950, #1990, @Avasam) +* Small generalized optimization by using augmented assignements (in-place operators) where possible (#2274, @Avasam) * General speed and size improvements due to all the removed code. (#2046, #1986, #2050, #1950, #2085, #2087, #2051, #1990, #2106, #2127, #2124, #2126, #2177, #2218, #2202, #2205, #2217) ### adodbapi diff --git a/Pythonwin/Win32uiHostGlue.h b/Pythonwin/Win32uiHostGlue.h index fe942090ef..2bee28c946 100644 --- a/Pythonwin/Win32uiHostGlue.h +++ b/Pythonwin/Win32uiHostGlue.h @@ -102,10 +102,11 @@ inline HKEY Win32uiHostGlue::GetRegistryRootKey() #ifndef LINK_WITH_WIN32UI -#define CHECK_PFN(p) if (!p) { \ - wsprintf(err_buf, _T("Failed to load ##p - %d\n"), GetLastError()); \ - goto fail_with_error_dlg; \ -} +#define CHECK_PFN(p) \ + if (!p) { \ + wsprintf(err_buf, _T("Failed to load ##p - %d\n"), GetLastError()); \ + goto fail_with_error_dlg; \ + } inline BOOL Win32uiHostGlue::DynamicApplicationInit(const TCHAR *cmd, const TCHAR *additionalPaths) { @@ -186,19 +187,23 @@ inline BOOL Win32uiHostGlue::DynamicApplicationInit(const TCHAR *cmd, const TCHA (*pfnPyInit)(); } - PyObject* (*pPyImport_ImportModule)(const char *name) = (PyObject* (*)(const char *name))GetProcAddress(hModCore, "PyImport_ImportModule"); + PyObject *(*pPyImport_ImportModule)(const char *name) = + (PyObject * (*)(const char *name)) GetProcAddress(hModCore, "PyImport_ImportModule"); CHECK_PFN(pPyImport_ImportModule); - PyObject* (*pPyObject_GetAttrString)(PyObject *o, const char *attr_name) = (PyObject* (*)(PyObject *o, const char *attr_name))GetProcAddress(hModCore, "PyObject_GetAttrString"); + PyObject *(*pPyObject_GetAttrString)(PyObject *o, const char *attr_name) = + (PyObject * (*)(PyObject * o, const char *attr_name)) GetProcAddress(hModCore, "PyObject_GetAttrString"); CHECK_PFN(pPyObject_GetAttrString); - Py_ssize_t (*pPyUnicode_AsWideChar)(PyObject *unicode, wchar_t *w, Py_ssize_t size) = (Py_ssize_t (*)(PyObject *unicode, wchar_t *w, Py_ssize_t size))GetProcAddress(hModCore, "PyUnicode_AsWideChar"); + Py_ssize_t (*pPyUnicode_AsWideChar)(PyObject *unicode, wchar_t *w, Py_ssize_t size) = + (Py_ssize_t(*)(PyObject * unicode, wchar_t * w, Py_ssize_t size)) + GetProcAddress(hModCore, "PyUnicode_AsWideChar"); CHECK_PFN(pPyUnicode_AsWideChar); - PyObject* win32ui = pPyImport_ImportModule("win32ui"); + PyObject *win32ui = pPyImport_ImportModule("win32ui"); if (!win32ui) { wsprintf(err_buf, _T("Failed to import win32ui\n")); goto fail_with_error_dlg; } - PyObject* pyfn = pPyObject_GetAttrString(win32ui, "__file__"); + PyObject *pyfn = pPyObject_GetAttrString(win32ui, "__file__"); if (!pyfn) { wsprintf(err_buf, _T("Failed to get __file__ from win32ui\n")); goto fail_with_error_dlg; @@ -231,14 +236,14 @@ inline BOOL Win32uiHostGlue::DynamicApplicationInit(const TCHAR *cmd, const TCHA Py_ssize_t len = _tcslen(err_buf); Py_ssize_t bufLeft = sizeof(err_buf) / sizeof(TCHAR) - len; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), - err_buf + len, PyWin_SAFE_DOWNCAST(bufLeft, Py_ssize_t, DWORD), NULL); + err_buf + len, PyWin_SAFE_DOWNCAST(bufLeft, Py_ssize_t, DWORD), NULL); AfxMessageBox(err_buf); return FALSE; } #else // LINK_WITH_WIN32UI defined -extern "C" __declspec(dllimport) BOOL - Win32uiApplicationInit(Win32uiHostGlue *pGlue, const TCHAR *cmd, const TCHAR *addnPaths); +extern "C" __declspec(dllimport) BOOL Win32uiApplicationInit(Win32uiHostGlue *pGlue, const TCHAR *cmd, + const TCHAR *addnPaths); extern "C" void initwin32ui(); inline BOOL Win32uiHostGlue::ApplicationInit(const TCHAR *cmd, const TCHAR *additionalPaths) @@ -248,7 +253,7 @@ inline BOOL Win32uiHostGlue::ApplicationInit(const TCHAR *cmd, const TCHAR *addi Py_Initialize(); } // Make sure the statically linked win32ui is the one Python sees - // (and doesnt go searching for a new one) + // (and doesn't go searching for a new one) PyInit_win32ui(); return Win32uiApplicationInit(this, cmd, additionalPaths); diff --git a/Pythonwin/contents.d b/Pythonwin/contents.d index b2d955e6cb..86101de597 100644 --- a/Pythonwin/contents.d +++ b/Pythonwin/contents.d @@ -128,7 +128,7 @@ was used for the first block is used for the entire file. Another common scenario where things go wrong is when pasting code into a new file. You create a new file (which sets the tabs to your defaults), then paste in a huge chunk of code that is indented differently. The editor is still using -the defaults, which dont reflect the code that now exists in the buffer. +the defaults, which don't reflect the code that now exists in the buffer. The "tab-timmy" shows up these problems very quickly, and you can quickly toggle the current tab settings by pressing Ctrl+T, or change the indent width by pressing Ctrl+U. diff --git a/Pythonwin/ddemodule.h b/Pythonwin/ddemodule.h index 5f02d50f48..256556db7b 100644 --- a/Pythonwin/ddemodule.h +++ b/Pythonwin/ddemodule.h @@ -1,4 +1,4 @@ -//#define PY_SSIZE_T_CLEAN // defined in win32virt.cpp which runs the z# format here +// #define PY_SSIZE_T_CLEAN // defined in win32virt.cpp which runs the z# format here extern PyObject *BASED_CODE dde_module_error; diff --git a/Pythonwin/dllmain.cpp b/Pythonwin/dllmain.cpp index 59723fb290..806b16b8d9 100644 --- a/Pythonwin/dllmain.cpp +++ b/Pythonwin/dllmain.cpp @@ -100,13 +100,12 @@ CInProcApp::CInProcApp(LPCTSTR lpszAppName) : CWinApp(lpszAppName) ///////////////////////////////////////////////////////////////////////////// // CInProcApp initialization -extern "C" PYW_EXPORT BOOL - Win32uiApplicationInit(Win32uiHostGlue *pGlue, const TCHAR *cmd, const TCHAR *addnPaths); +extern "C" PYW_EXPORT BOOL Win32uiApplicationInit(Win32uiHostGlue *pGlue, const TCHAR *cmd, const TCHAR *addnPaths); BOOL CInProcApp::InitInstance() { // Avoid dynamic search for Win32uiApplicationInit from inside DLL - //if (!glue.DynamicApplicationInit()) + // if (!glue.DynamicApplicationInit()) if (!Win32uiApplicationInit(&glue, NULL, NULL)) return FALSE; return glue.InitInstance(); @@ -115,9 +114,9 @@ BOOL CInProcApp::InitInstance() // Check that we have a valid CWinApp object to use. bool CheckGoodWinApp() { - // Shouldnt need special symbols now that we delay the creation. + // shouldn't need special symbols now that we delay the creation. // If the host exports a special symbol, then - // dont create a host app. + // don't create a host app. // HMODULE hModule = GetModuleHandle(NULL); // BOOL hasSymbol = (GetProcAddress(hModule, "NoCreateWinApp") != NULL); if (AfxGetApp() == NULL) { // && !hasSymbol) { @@ -207,7 +206,7 @@ extern "C" __declspec(dllexport) int __stdcall DllMainwin32ui(HINSTANCE hInstanc if (pCreatedApp) { pCreatedApp->CleanupMainWindow(); - // We dont call ExitInstance, as the InitInstance we called could + // We don't call ExitInstance, as the InitInstance we called could // not have possibly called back to Python, as the Python app object // could not have been created. Let the Python code manage if it wants! Win32uiFinalize(); diff --git a/Pythonwin/pythonview.cpp b/Pythonwin/pythonview.cpp index 9ffe6a0e5c..7ba31ee662 100644 --- a/Pythonwin/pythonview.cpp +++ b/Pythonwin/pythonview.cpp @@ -96,9 +96,9 @@ void CPythonListViewImpl::DrawItem(LPDRAWITEMSTRUCT lpDIS) obDC = Py_None; } - helper.call_args("iiiiiiO(iiii)O", lpDIS->CtlType, lpDIS->CtlID, lpDIS->itemID, lpDIS->itemAction, - lpDIS->itemState, lpDIS->hwndItem, obDC, lpDIS->rcItem.left, lpDIS->rcItem.top, - lpDIS->rcItem.right, lpDIS->rcItem.bottom, obData); + helper.call_args("iiiiiiO(iiii)O", lpDIS->CtlType, lpDIS->CtlID, lpDIS->itemID, lpDIS->itemAction, lpDIS->itemState, + lpDIS->hwndItem, obDC, lpDIS->rcItem.left, lpDIS->rcItem.top, lpDIS->rcItem.right, + lpDIS->rcItem.bottom, obData); // The DC is no longer valid. Python_delete_assoc(pDC); } @@ -132,9 +132,9 @@ void CPythonTreeViewImpl::DrawItem(LPDRAWITEMSTRUCT lpDIS) obDC = Py_None; } - helper.call_args("iiiiiiO(iiii)O", lpDIS->CtlType, lpDIS->CtlID, lpDIS->itemID, lpDIS->itemAction, - lpDIS->itemState, lpDIS->hwndItem, obDC, lpDIS->rcItem.left, lpDIS->rcItem.top, - lpDIS->rcItem.right, lpDIS->rcItem.bottom, obData); + helper.call_args("iiiiiiO(iiii)O", lpDIS->CtlType, lpDIS->CtlID, lpDIS->itemID, lpDIS->itemAction, lpDIS->itemState, + lpDIS->hwndItem, obDC, lpDIS->rcItem.left, lpDIS->rcItem.top, lpDIS->rcItem.right, + lpDIS->rcItem.bottom, obData); // The DC is no longer valid. Python_delete_assoc(pDC); } diff --git a/Pythonwin/pythonwin.cpp b/Pythonwin/pythonwin.cpp index 6b8af10863..2d904413f7 100644 --- a/Pythonwin/pythonwin.cpp +++ b/Pythonwin/pythonwin.cpp @@ -59,7 +59,7 @@ BOOL CPythonWinApp::InitInstance() { if (!glue.InitInstance()) return FALSE; - // dialog based apps dont have a message pump. + // dialog based apps don't have a message pump. return m_pMainWnd && !m_pMainWnd->IsKindOf(RUNTIME_CLASS(CDialog)); } int CPythonWinApp::ExitInstance() diff --git a/Pythonwin/pywin/Demos/app/basictimerapp.py b/Pythonwin/pywin/Demos/app/basictimerapp.py index a932ae0604..c60271b952 100644 --- a/Pythonwin/pywin/Demos/app/basictimerapp.py +++ b/Pythonwin/pywin/Demos/app/basictimerapp.py @@ -144,9 +144,9 @@ def OnTimer(self, id, timeVal): if nextTime: timeDiffSeconds = nextTime - now timeDiffMinutes = int(timeDiffSeconds / 60) - timeDiffSeconds = timeDiffSeconds % 60 + timeDiffSeconds %= 60 timeDiffHours = int(timeDiffMinutes / 60) - timeDiffMinutes = timeDiffMinutes % 60 + timeDiffMinutes %= 60 self.dlg.prompt1.SetWindowText( "Next connection due in %02d:%02d:%02d" % (timeDiffHours, timeDiffMinutes, timeDiffSeconds) @@ -200,7 +200,7 @@ def SetFirstTime(self, now): lst[pos] = 0 ret = time.mktime(tuple(lst)) if bAdd: - ret = ret + self.timeAdd + ret += self.timeAdd return ret def SetNextTime(self, lastTime, now): diff --git a/Pythonwin/pywin/Demos/app/customprint.py b/Pythonwin/pywin/Demos/app/customprint.py index 442737b5bd..4a666ca41a 100644 --- a/Pythonwin/pywin/Demos/app/customprint.py +++ b/Pythonwin/pywin/Demos/app/customprint.py @@ -47,7 +47,7 @@ def OnDraw(self, dc): delta = 2 colors = list(self.colors.keys()) colors.sort() - colors = colors * 2 + colors *= 2 for color in colors: if oldPen is None: oldPen = dc.SelectObject(self.pens[color]) @@ -58,7 +58,7 @@ def OnDraw(self, dc): dc.LineTo((x - delta, y - delta)) dc.LineTo((delta, y - delta)) dc.LineTo((delta, delta)) - delta = delta + 4 + delta += 4 if x - delta <= 0 or y - delta <= 0: break dc.SelectObject(oldPen) @@ -108,10 +108,10 @@ def OnPrint(self, dc, pInfo): cyChar = metrics["tmHeight"] left, top, right, bottom = pInfo.GetDraw() dc.TextOut(0, 2 * cyChar, doc.GetTitle()) - top = top + (7 * cyChar) / 2 + top += 7 * cyChar / 2 dc.MoveTo(left, top) dc.LineTo(right, top) - top = top + cyChar + top += cyChar # this seems to have not effect... # get what I want with the dc.SetWindowOrg calls pInfo.SetDraw((left, top, right, bottom)) @@ -131,7 +131,7 @@ def OnPrint(self, dc, pInfo): y = (3 * cyChar) / 2 dc.TextOut(x, y, doc.GetTitle()) - y = y + cyChar + y += cyChar class PrintDemoApp(app.CApp): diff --git a/Pythonwin/pywin/Demos/app/helloapp.py b/Pythonwin/pywin/Demos/app/helloapp.py index 6ac35b431a..b0209288ca 100644 --- a/Pythonwin/pywin/Demos/app/helloapp.py +++ b/Pythonwin/pywin/Demos/app/helloapp.py @@ -19,7 +19,7 @@ # The main frame. -# Does almost nothing at all - doesnt even create a child window! +# Does almost nothing at all - doesn't even create a child window! class HelloWindow(window.Wnd): def __init__(self): # The window.Wnd ctor creates a Window object, and places it in diff --git a/Pythonwin/pywin/Demos/cmdserver.py b/Pythonwin/pywin/Demos/cmdserver.py index 08a6e81e6c..4ec6e49b3f 100644 --- a/Pythonwin/pywin/Demos/cmdserver.py +++ b/Pythonwin/pywin/Demos/cmdserver.py @@ -52,7 +52,7 @@ def Test(): while num < 1000: print("Hello there no " + str(num)) win32api.Sleep(50) - num = num + 1 + num += 1 class flags: diff --git a/Pythonwin/pywin/Demos/dibdemo.py b/Pythonwin/pywin/Demos/dibdemo.py index 615227abf2..141746bf6f 100644 --- a/Pythonwin/pywin/Demos/dibdemo.py +++ b/Pythonwin/pywin/Demos/dibdemo.py @@ -1,6 +1,6 @@ # A demo which creates a view and a frame which displays a PPM format bitmap # -# This hasnnt been run in a while, as I dont have many of that format around! +# This hasnnt been run in a while, as I don't have many of that format around! import win32api import win32con @@ -46,7 +46,7 @@ def __init__(self, filename, *bPBM): rowcollist = f.readline().split() cols = int(rowcollist[0]) rows = int(rowcollist[1]) - f.readline() # whats this one? + f.readline() # what's this one? dib.LoadPBMData(f, (cols, rows)) else: dib.LoadWindowsFormatFile(f) diff --git a/Pythonwin/pywin/Demos/dlgtest.py b/Pythonwin/pywin/Demos/dlgtest.py index acef880176..2fb0b60cd9 100644 --- a/Pythonwin/pywin/Demos/dlgtest.py +++ b/Pythonwin/pywin/Demos/dlgtest.py @@ -50,7 +50,7 @@ def OnNotify(self, controlid, code): # kill focus for the edit box. # Simply increment the value in the text box. def KillFocus(self, msg): - self.counter = self.counter + 1 + self.counter += 1 if self.edit is not None: self.edit.SetWindowText(str(self.counter)) diff --git a/Pythonwin/pywin/Demos/hiertest.py b/Pythonwin/pywin/Demos/hiertest.py index 3762946112..a22dc3b946 100644 --- a/Pythonwin/pywin/Demos/hiertest.py +++ b/Pythonwin/pywin/Demos/hiertest.py @@ -7,7 +7,7 @@ # directory listbox -# This has obvious limitations - doesnt track subdirs, etc. Demonstrates +# This has obvious limitations - doesn't track subdirs, etc. Demonstrates # simple use of Python code for querying the tree as needed. # Only use strings, and lists of strings (from curdir()) class DirHierList(hierlist.HierList): diff --git a/Pythonwin/pywin/Demos/ocx/flash.py b/Pythonwin/pywin/Demos/ocx/flash.py index 239240ee33..f2994e50a6 100644 --- a/Pythonwin/pywin/Demos/ocx/flash.py +++ b/Pythonwin/pywin/Demos/ocx/flash.py @@ -33,9 +33,9 @@ def __init__(self): def OnFSCommand(self, command, args): print("FSCommend", command, args) - self.x = self.x + 20 - self.y = self.y + 20 - self.angle = self.angle + 20 + self.x += 20 + self.y += 20 + self.angle += 20 if self.x > 200 or self.y > 200: self.x = 0 self.y = 0 @@ -60,7 +60,7 @@ def __init__(self, url=None): self.url = regutil.GetRegisteredHelpFile("Main Python Documentation") else: self.url = url - pass # Dont call base class doc/view version... + pass # Don't call base class doc/view version... def Create(self, title, rect=None, parent=None): style = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.WS_OVERLAPPEDWINDOW diff --git a/Pythonwin/pywin/Demos/ocx/msoffice.py b/Pythonwin/pywin/Demos/ocx/msoffice.py index b158e609f1..5162e5a05d 100644 --- a/Pythonwin/pywin/Demos/ocx/msoffice.py +++ b/Pythonwin/pywin/Demos/ocx/msoffice.py @@ -88,7 +88,7 @@ def OnSetFocus(self, msg): wnd = item.GetInPlaceWindow() if wnd is not None: wnd.SetFocus() - return 0 # Dont get the base version called. + return 0 # Don't get the base version called. return 1 # Call the base version. def OnSize(self, params): @@ -115,7 +115,7 @@ class WordFrame(window.MDIChildWnd): def __init__(self, doc=None): self._obj_ = win32ui.CreateMDIChild() self._obj_.AttachObject(self) - # Dont call base class doc/view version... + # Don't call base class doc/view version... def Create(self, title, rect=None, parent=None): WordModule = gencache.EnsureModule( diff --git a/Pythonwin/pywin/Demos/ocx/ocxtest.py b/Pythonwin/pywin/Demos/ocx/ocxtest.py index 9d37ba8f11..695f708b88 100644 --- a/Pythonwin/pywin/Demos/ocx/ocxtest.py +++ b/Pythonwin/pywin/Demos/ocx/ocxtest.py @@ -173,7 +173,7 @@ def OnOK(self): # class OCXFrame(window.MDIChildWnd): def __init__(self): - pass # Dont call base class doc/view version... + pass # Don't call base class doc/view version... def Create(self, controlClass, title, rect=None, parent=None): style = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.WS_OVERLAPPEDWINDOW diff --git a/Pythonwin/pywin/Demos/ocx/webbrowser.py b/Pythonwin/pywin/Demos/ocx/webbrowser.py index 1dc318c198..89c713c265 100644 --- a/Pythonwin/pywin/Demos/ocx/webbrowser.py +++ b/Pythonwin/pywin/Demos/ocx/webbrowser.py @@ -35,7 +35,7 @@ def __init__(self, url=None): self.url = "http://www.python.org" else: self.url = url - pass # Dont call base class doc/view version... + pass # Don't call base class doc/view version... def Create(self, title, rect=None, parent=None): style = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.WS_OVERLAPPEDWINDOW diff --git a/Pythonwin/pywin/Demos/openGLDemo.py b/Pythonwin/pywin/Demos/openGLDemo.py index 9274949dea..f7449d1e02 100644 --- a/Pythonwin/pywin/Demos/openGLDemo.py +++ b/Pythonwin/pywin/Demos/openGLDemo.py @@ -50,13 +50,13 @@ def ComponentFromIndex(i, nbits, shift): # val = (unsigned char) (i >> shift); val = (i >> shift) & 0xF if nbits == 1: - val = val & 0x1 + val &= 0x1 return oneto8[val] elif nbits == 2: - val = val & 0x3 + val &= 0x3 return twoto8[val] elif nbits == 3: - val = val & 0x7 + val &= 0x7 return threeto8[val] else: return 0 @@ -72,7 +72,7 @@ def PreCreateWindow(self, cc): # include CS_PARENTDC for the class style. Refer to SetPixelFormat # documentation in the "Comments" section for further information. style = cc[5] - style = style | win32con.WS_CLIPSIBLINGS | win32con.WS_CLIPCHILDREN + style |= win32con.WS_CLIPSIBLINGS | win32con.WS_CLIPCHILDREN cc = cc[0], cc[1], cc[2], cc[3], cc[4], style, cc[6], cc[7], cc[8] cc = self._obj_.PreCreateWindow(cc) return cc @@ -160,10 +160,10 @@ def _DestroyContexts(self): # The methods to support OpenGL def DrawScene(self): - assert 0, "You must override this method" + raise NotImplementedError("You must override this method") def Init(self): - assert 0, "You must override this method" + raise NotImplementedError("You must override this method") def OnSizeChange(self, cx, cy): pass @@ -287,9 +287,9 @@ def DrawScene(self): glRotatef(self.wAngleY, 0.0, 1.0, 0.0) glRotatef(self.wAngleZ, 0.0, 0.0, 1.0) - self.wAngleX = self.wAngleX + 1.0 - self.wAngleY = self.wAngleY + 10.0 - self.wAngleZ = self.wAngleZ + 5.0 + self.wAngleX += 1.0 + self.wAngleY += 10.0 + self.wAngleZ += 5.0 glBegin(GL_QUAD_STRIP) glColor3f(1.0, 0.0, 1.0) diff --git a/Pythonwin/pywin/Demos/progressbar.py b/Pythonwin/pywin/Demos/progressbar.py index 81cd7e381d..e16a42cb48 100644 --- a/Pythonwin/pywin/Demos/progressbar.py +++ b/Pythonwin/pywin/Demos/progressbar.py @@ -86,7 +86,7 @@ def OnInitDialog(self): def OnOK(self): # NB: StepIt wraps at the end if you increment past the upper limit! # self.pbar.StepIt() - self.progress = self.progress + self.pincr + self.progress += self.pincr if self.progress > 100: self.progress = 100 if self.progress <= 100: diff --git a/Pythonwin/pywin/Demos/threadedgui.py b/Pythonwin/pywin/Demos/threadedgui.py index 5b0704ef3b..917b3ad64f 100644 --- a/Pythonwin/pywin/Demos/threadedgui.py +++ b/Pythonwin/pywin/Demos/threadedgui.py @@ -51,7 +51,7 @@ def OnDestroy(self, msg): timer.kill_timer(self.timerid) def OnTimer(self, id, timeVal): - self.index = self.index + self.incr + self.index += self.incr if self.index > len(self.text): self.incr = -1 self.index = len(self.text) @@ -95,7 +95,7 @@ def OnPrepareDC(self, dc, printinfo): class FontFrame(window.MDIChildWnd): def __init__(self): - pass # Dont call base class doc/view version... + pass # Don't call base class doc/view version... def Create(self, title, rect=None, parent=None): style = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.WS_OVERLAPPEDWINDOW @@ -134,7 +134,7 @@ def ExitInstance(self): class ThreadedFontFrame(window.MDIChildWnd): def __init__(self): - pass # Dont call base class doc/view version... + pass # Don't call base class doc/view version... self.thread = None def Create(self, title, rect=None, parent=None): diff --git a/Pythonwin/pywin/Demos/toolbar.py b/Pythonwin/pywin/Demos/toolbar.py index e56aefef18..0dfbb6a05a 100644 --- a/Pythonwin/pywin/Demos/toolbar.py +++ b/Pythonwin/pywin/Demos/toolbar.py @@ -15,7 +15,7 @@ def OnCreateClient(self, cp, context): # handlers for toolbar buttons self.HookCommand(self.OnPrevious, 401) self.HookCommand(self.OnNext, 402) - # Its not necessary for us to hook both of these - the + # It's not necessary for us to hook both of these - the # common controls should fall-back all by themselves. # Indeed, given we hook TTN_NEEDTEXTW, commctrl.TTN_NEEDTEXTA # will not be called. @@ -85,7 +85,7 @@ def OnPrevious(self, id, cmd): \r The first item's tooltips is provided by Python code.\r \r -(Dont close the window with the toolbar in a floating state - it may not re-appear!)\r +(Don't close the window with the toolbar in a floating state - it may not re-appear!)\r """ diff --git a/Pythonwin/pywin/debugger/__init__.py b/Pythonwin/pywin/debugger/__init__.py index 6a6b65da7f..4bcb7202a8 100644 --- a/Pythonwin/pywin/debugger/__init__.py +++ b/Pythonwin/pywin/debugger/__init__.py @@ -85,7 +85,7 @@ def set_trace(): return # App closing if d.stopframe != d.botframe: - # If im not "running" + # If I'm not "running" return sys.settrace(None) # May be hooked diff --git a/Pythonwin/pywin/debugger/debugger.py b/Pythonwin/pywin/debugger/debugger.py index 17e64f7c5d..2c29043919 100644 --- a/Pythonwin/pywin/debugger/debugger.py +++ b/Pythonwin/pywin/debugger/debugger.py @@ -132,7 +132,7 @@ def GetSubList(self): self.last_stack.append((frame, lineno)) if ( frame is debugger.userbotframe - ): # Dont bother showing frames below our bottom frame. + ): # Don't bother showing frames below our bottom frame. break for frame, lineno in self.last_stack: ret.append(HierFrameItem(frame, debugger)) @@ -289,7 +289,7 @@ def CreateWindow(self, parent): list.InsertColumn(0, itemDetails) col = 1 for title, width in self.columns[1:]: - col = col + 1 + col += 1 itemDetails = (commctrl.LVCFMT_LEFT, width, title, 0) list.InsertColumn(col, itemDetails) parent.HookNotify(self.OnListEndLabelEdit, LVN_ENDLABELEDIT) @@ -455,7 +455,7 @@ def OnListEndLabelEdit(self, std, extra): def DeleteSelected(self): try: num = self.GetNextItem(-1, commctrl.LVNI_SELECTED) - if num < self.GetItemCount() - 1: # We cant delete the last + if num < self.GetItemCount() - 1: # We can't delete the last self.DeleteItem(num) except win32ui.error: win32api.MessageBeep() @@ -608,7 +608,7 @@ def close(self, frameShutdown=0): SetInteractiveContext(None, None) frame = win32ui.GetMainFrame() - # Hide the debuger toolbars (as they wont normally form part of the main toolbar state. + # Hide the debuger toolbars (as they won't normally form part of the main toolbar state. for id, klass, float in DebuggerDialogInfos: try: tb = frame.GetControlBar(id) @@ -623,7 +623,7 @@ def close(self, frameShutdown=0): return 1 def StopDebuggerPump(self): - assert self.pumping, "Can't stop the debugger pump if Im not pumping!" + assert self.pumping, "Can't stop the debugger pump if I'm not pumping!" # After stopping a pump, I may never return. if self.GUIAboutToFinishInteract(): self.pumping = 0 @@ -674,7 +674,7 @@ def cmdloop(self): self.GUIAboutToBreak() def print_stack_entry(self, frame): - # We dont want a stack printed - our GUI is better :-) + # We don't want a stack printed - our GUI is better :-) pass def user_return(self, frame, return_value): @@ -746,7 +746,7 @@ def run(self, cmd, globals=None, locals=None, start_stepping=1): self.prep_run(cmd) sys.settrace(self.trace_dispatch) if not isinstance(cmd, types.CodeType): - cmd = cmd + "\n" + cmd += "\n" try: try: if start_stepping: @@ -828,7 +828,7 @@ def set_trace(self): self.userbotframe = None while frame: # scriptutils.py creates a local variable with name - # '_debugger_stop_frame_', and we dont go past it + # '_debugger_stop_frame_', and we don't go past it # (everything above this is Pythonwin framework code) if "_debugger_stop_frame_" in frame.f_locals: self.userbotframe = frame @@ -851,7 +851,7 @@ def set_cur_frame(self, frame): self.curindex = index break else: - assert 0, "Can't find the frame in the stack." + assert False, "Can't find the frame in the stack." SetInteractiveContext(frame.f_globals, frame.f_locals) self.GUIRespondDebuggerData() self.ShowCurrentLine() @@ -883,7 +883,7 @@ def RespondDebuggerState(self, state): win32ui.LoadString(win32ui.IDR_MAINFRAME) + title ) if self.debuggerState == DBGSTATE_QUITTING and state != DBGSTATE_NOT_DEBUGGING: - print("Ignoring state change cos Im trying to stop!", state) + print("Ignoring state change cos I'm trying to stop!", state) return self.debuggerState = state try: @@ -931,7 +931,7 @@ def GetDebuggerBar(self, barName): for id, klass, float in DebuggerDialogInfos: if klass.title == barName: return frame.GetControlBar(id) - assert 0, "Can't find a bar of that name!" + assert False, "Can't find a bar of that name!" def GUIRespondDebuggerData(self): if not self.inited: # GUI not inited - no toolbars etc. diff --git a/Pythonwin/pywin/debugger/fail.py b/Pythonwin/pywin/debugger/fail.py index 97721576c8..dbb5320ae4 100644 --- a/Pythonwin/pywin/debugger/fail.py +++ b/Pythonwin/pywin/debugger/fail.py @@ -3,7 +3,7 @@ # The ONLY purpose for this script is testing/demoing the # Pythonwin debugger package. -# It does nothing useful, and it even doesnt do that! +# It does nothing useful, and it even doesn't do that! import sys import time diff --git a/Pythonwin/pywin/default.cfg b/Pythonwin/pywin/default.cfg index 1d08809d6a..9366e2dfb6 100644 --- a/Pythonwin/pywin/default.cfg +++ b/Pythonwin/pywin/default.cfg @@ -113,7 +113,7 @@ Alt+I = WindowBack # Toggle back to previous window. Home = InteractiveHome # A sample Event defined in this file. Shift+Home = InteractiveHomeExtend # A sample Event defined in this file. -# When docked, the Ctrl+Tab and Shift+Ctrl+Tab keys dont work as expected. +# When docked, the Ctrl+Tab and Shift+Ctrl+Tab keys don't work as expected. Ctrl+Tab = MDINext Ctrl+Shift+Tab = MDIPrev diff --git a/Pythonwin/pywin/dialogs/list.py b/Pythonwin/pywin/dialogs/list.py index b9934ce71d..4e1877955d 100644 --- a/Pythonwin/pywin/dialogs/list.py +++ b/Pythonwin/pywin/dialogs/list.py @@ -103,7 +103,7 @@ def FillList(self): for col in self.colHeadings: itemDetails = (commctrl.LVCFMT_LEFT, int(width / numCols), col, 0) self.itemsControl.InsertColumn(index, itemDetails) - index = index + 1 + index += 1 index = 0 for items in self.items: index = self.itemsControl.InsertItem(index + 1, str(items[0]), 0) diff --git a/Pythonwin/pywin/docking/DockingBar.py b/Pythonwin/pywin/docking/DockingBar.py index 3e9b4131a6..55868b446b 100644 --- a/Pythonwin/pywin/docking/DockingBar.py +++ b/Pythonwin/pywin/docking/DockingBar.py @@ -295,7 +295,7 @@ def OnLButtonUp(self, msg): if not self.bTracking: return 1 # pass it on. self.StopTracking(1) - return 0 # Dont pass on + return 0 # Don't pass on def OnLButtonDown(self, msg): # UINT nFlags, CPoint point) @@ -356,10 +356,10 @@ def OnMouseMove(self, msg): # Convert unsigned 16 bit to signed 32 bit. x = win32api.LOWORD(lparam) if x & 32768: - x = x | -65536 + x |= -65536 y = win32api.HIWORD(lparam) if y & 32768: - y = y | -65536 + y |= -65536 pt = x, y cpt = CenterPoint(self.rectTracker) pt = self.ClientToWnd(pt) @@ -374,7 +374,7 @@ def OnMouseMove(self, msg): self.rectTracker = OffsetRect(self.rectTracker, (pt[0] - cpt[0], 0)) self.OnInvertTracker(self.rectTracker) - return 0 # Dont pass it on. + return 0 # Don't pass it on. # def OnBarStyleChange(self, old, new): @@ -388,11 +388,11 @@ def OnNcCalcSize(self, bCalcValid, size_info): dwBorderStyle = self._obj_.dwStyle | afxres.CBRS_BORDER_ANY if self.nDockBarID == afxres.AFX_IDW_DOCKBAR_TOP: - dwBorderStyle = dwBorderStyle & ~afxres.CBRS_BORDER_BOTTOM - rc0.left = rc0.left + self.cxGripper - rc0.bottom = rc0.bottom - self.cxEdge - rc0.top = rc0.top + self.cxBorder - rc0.right = rc0.right - self.cxBorder + dwBorderStyle &= ~afxres.CBRS_BORDER_BOTTOM + rc0.left += self.cxGripper + rc0.bottom -= self.cxEdge + rc0.top += self.cxBorder + rc0.right -= self.cxBorder self.rectBorder = ( self.rectBorder[0], self.rectBorder[3] - self.cxEdge, @@ -400,11 +400,11 @@ def OnNcCalcSize(self, bCalcValid, size_info): self.rectBorder[3], ) elif self.nDockBarID == afxres.AFX_IDW_DOCKBAR_BOTTOM: - dwBorderStyle = dwBorderStyle & ~afxres.CBRS_BORDER_TOP - rc0.left = rc0.left + self.cxGripper - rc0.top = rc0.top + self.cxEdge - rc0.bottom = rc0.bottom - self.cxBorder - rc0.right = rc0.right - self.cxBorder + dwBorderStyle &= ~afxres.CBRS_BORDER_TOP + rc0.left += self.cxGripper + rc0.top += self.cxEdge + rc0.bottom -= self.cxBorder + rc0.right -= self.cxBorder self.rectBorder = ( self.rectBorder[0], self.rectBorder[1], @@ -412,11 +412,11 @@ def OnNcCalcSize(self, bCalcValid, size_info): self.rectBorder[1] + self.cxEdge, ) elif self.nDockBarID == afxres.AFX_IDW_DOCKBAR_LEFT: - dwBorderStyle = dwBorderStyle & ~afxres.CBRS_BORDER_RIGHT - rc0.right = rc0.right - self.cxEdge - rc0.left = rc0.left + self.cxBorder - rc0.bottom = rc0.bottom - self.cxBorder - rc0.top = rc0.top + self.cxGripper + dwBorderStyle &= ~afxres.CBRS_BORDER_RIGHT + rc0.right -= self.cxEdge + rc0.left += self.cxBorder + rc0.bottom -= self.cxBorder + rc0.top += self.cxGripper self.rectBorder = ( self.rectBorder[2] - self.cxEdge, self.rectBorder[1], @@ -424,11 +424,11 @@ def OnNcCalcSize(self, bCalcValid, size_info): self.rectBorder[3], ) elif self.nDockBarID == afxres.AFX_IDW_DOCKBAR_RIGHT: - dwBorderStyle = dwBorderStyle & ~afxres.CBRS_BORDER_LEFT - rc0.left = rc0.left + self.cxEdge - rc0.right = rc0.right - self.cxBorder - rc0.bottom = rc0.bottom - self.cxBorder - rc0.top = rc0.top + self.cxGripper + dwBorderStyle &= ~afxres.CBRS_BORDER_LEFT + rc0.left += self.cxEdge + rc0.right -= self.cxBorder + rc0.bottom -= self.cxBorder + rc0.top += self.cxGripper self.rectBorder = ( self.rectBorder[0], self.rectBorder[1], @@ -486,7 +486,7 @@ def StartTracking(self): self.rectTracker = self.rectBorder if not self.IsHorz(): l, t, r, b = self.rectTracker - b = b - 4 + b -= 4 self.rectTracker = l, t, r, b self.OnInvertTracker(self.rectTracker) @@ -517,13 +517,13 @@ def StopTracking(self, bAccept): pt = CenterPoint(self.rectTracker) if self.nDockBarID == afxres.AFX_IDW_DOCKBAR_TOP: - newsize = newsize + (pt[1] - self.ptOld[1]) + newsize += pt[1] - self.ptOld[1] elif self.nDockBarID == afxres.AFX_IDW_DOCKBAR_BOTTOM: - newsize = newsize + (-pt[1] + self.ptOld[1]) + newsize += -pt[1] + self.ptOld[1] elif self.nDockBarID == afxres.AFX_IDW_DOCKBAR_LEFT: - newsize = newsize + (pt[0] - self.ptOld[0]) + newsize += pt[0] - self.ptOld[0] elif self.nDockBarID == afxres.AFX_IDW_DOCKBAR_RIGHT: - newsize = newsize + (-pt[0] + self.ptOld[0]) + newsize += -pt[0] + self.ptOld[0] newsize = max(minsize, min(maxsize, newsize)) if self.IsHorz(): self.sizeHorz = self.sizeHorz[0], newsize @@ -565,9 +565,9 @@ def IsHorz(self): def ClientToWnd(self, pt): x, y = pt if self.nDockBarID == afxres.AFX_IDW_DOCKBAR_BOTTOM: - y = y + self.cxEdge + y += self.cxEdge elif self.nDockBarID == afxres.AFX_IDW_DOCKBAR_RIGHT: - x = x + self.cxEdge + x += self.cxEdge return x, y def DrawGripper(self, dc): @@ -600,9 +600,9 @@ def DrawGripper(self, dc): self.rectUndock, win32con.DFC_CAPTION, win32con.DFCS_CAPTIONMAX ) - gt = gt + 38 - gb = gb - 10 - gl = gl + 10 + gt += 38 + gb -= 10 + gl += 10 gr = gl + 3 gripper = gl, gt, gr, gb dc.Draw3dRect(gripper, clrBtnHilight, clrBtnShadow) @@ -620,9 +620,9 @@ def DrawGripper(self, dc): dc.DrawFrameControl( self.rectUndock, win32con.DFC_CAPTION, win32con.DFCS_CAPTIONMAX ) - gr = gr - 38 - gl = gl + 10 - gt = gt + 10 + gr -= 38 + gl += 10 + gt += 10 gb = gt + 3 gripper = gl, gt, gr, gb diff --git a/Pythonwin/pywin/framework/app.py b/Pythonwin/pywin/framework/app.py index 20beecc1d8..4d1ae22477 100644 --- a/Pythonwin/pywin/framework/app.py +++ b/Pythonwin/pywin/framework/app.py @@ -25,7 +25,7 @@ def SaveWindowSize(section, rect, state=""): (same format as CREATESTRUCT position tuples).""" left, top, right, bottom = rect if state: - state = state + " " + state += " " win32ui.WriteProfileVal(section, state + "left", left) win32ui.WriteProfileVal(section, state + "top", top) win32ui.WriteProfileVal(section, state + "right", right) @@ -35,7 +35,7 @@ def SaveWindowSize(section, rect, state=""): def LoadWindowSize(section, state=""): """Loads a section from an INI file, and returns a rect in a tuple (see SaveWindowSize)""" if state: - state = state + " " + state += " " left = win32ui.GetProfileVal(section, state + "left", 0) top = win32ui.GetProfileVal(section, state + "top", 0) right = win32ui.GetProfileVal(section, state + "right", 0) @@ -211,7 +211,7 @@ def OnHelp(self, id, code): def DoLoadModules(self, modules): # XXX - this should go, but the debugger uses it :-( - # dont do much checking! + # don't do much checking! for module in modules: __import__(module) @@ -270,7 +270,7 @@ def OnDropFiles(self, msg): # No longer used by Pythonwin, as the C++ code has this same basic functionality # but handles errors slightly better. # It all still works, tho, so if you need similar functionality, you can use it. - # Therefore I havent deleted this code completely! + # Therefore I haven't deleted this code completely! # def CallbackManager( self, ob, args = () ): # """Manage win32 callbacks. Trap exceptions, report on them, then return 'All OK' # to the frame-work. """ diff --git a/Pythonwin/pywin/framework/bitmap.py b/Pythonwin/pywin/framework/bitmap.py index 7619006f1f..890b2f3fb3 100644 --- a/Pythonwin/pywin/framework/bitmap.py +++ b/Pythonwin/pywin/framework/bitmap.py @@ -81,7 +81,7 @@ def OnCreateClient(self, createparams, context): borderX = win32api.GetSystemMetrics(win32con.SM_CXFRAME) borderY = win32api.GetSystemMetrics(win32con.SM_CYFRAME) titleY = win32api.GetSystemMetrics(win32con.SM_CYCAPTION) # includes border - # try and maintain default window pos, else adjust if cant fit + # try and maintain default window pos, else adjust if can't fit # get the main client window dimensions. mdiClient = win32ui.GetMainFrame().GetWindow(win32con.GW_CHILD) clientWindowRect = mdiClient.ScreenToClient(mdiClient.GetWindowRect()) @@ -138,7 +138,7 @@ def MatchDocType(self, fileName, fileType): ) win32ui.GetApp().AddDocTemplate(bitmapTemplate) -# This works, but just didnt make it through the code reorg. +# This works, but just didn't make it through the code reorg. # class PPMBitmap(Bitmap): # def LoadBitmapFile(self, file ): # magic=file.readline() @@ -147,7 +147,7 @@ def MatchDocType(self, fileName, fileType): # rowcollist=file.readline().split() # cols=int(rowcollist[0]) # rows=int(rowcollist[1]) -# file.readline() # whats this one? +# file.readline() # what's this one? # self.bitmap.LoadPPMFile(file,(cols,rows)) diff --git a/Pythonwin/pywin/framework/cmdline.py b/Pythonwin/pywin/framework/cmdline.py index a6b3f91cb8..b4bb846858 100644 --- a/Pythonwin/pywin/framework/cmdline.py +++ b/Pythonwin/pywin/framework/cmdline.py @@ -12,13 +12,13 @@ def ParseArgs(str): while pos < length: try: while str[pos] in string.whitespace: - pos = pos + 1 + pos += 1 except IndexError: break if pos >= length: break if str[pos] == '"': - pos = pos + 1 + pos += 1 try: endPos = str.index('"', pos) - 1 nextPos = endPos + 2 @@ -28,7 +28,7 @@ def ParseArgs(str): else: endPos = pos while endPos < length and not str[endPos] in string.whitespace: - endPos = endPos + 1 + endPos += 1 nextPos = endPos + 1 ret.append(str[pos : endPos + 1].strip()) pos = nextPos diff --git a/Pythonwin/pywin/framework/editor/__init__.py b/Pythonwin/pywin/framework/editor/__init__.py index 16e3158184..59a52cd34e 100644 --- a/Pythonwin/pywin/framework/editor/__init__.py +++ b/Pythonwin/pywin/framework/editor/__init__.py @@ -2,7 +2,7 @@ # # We used to support optional editors - eg, color or non-color. # -# This really isnt necessary with Scintilla, and scintilla +# This really isn't necessary with Scintilla, and scintilla # is getting so deeply embedded that it was too much work. import win32ui @@ -45,7 +45,7 @@ def LoadDefaultEditor(): ## del rc ## ## try: -## # Try and load the default one - dont catch errors here. +## # Try and load the default one - don't catch errors here. ## if mod is None: ## prefModule = "pywin.framework.editor.color.coloreditor" ## mod = __import__(prefModule) diff --git a/Pythonwin/pywin/framework/editor/color/coloreditor.py b/Pythonwin/pywin/framework/editor/color/coloreditor.py index 6b42de93bf..ffc1cb35e0 100644 --- a/Pythonwin/pywin/framework/editor/color/coloreditor.py +++ b/Pythonwin/pywin/framework/editor/color/coloreditor.py @@ -258,14 +258,14 @@ def DoConfigChange(self): # Tab size can never be guessed - set at user preference. ext.config(usetabs=usetabs, indentwidth=indentwidth, tabwidth=tabSize) else: - # Dont want smart-tabs - just set the options! + # Don't want smart-tabs - just set the options! ext.config(usetabs=bUseTabs, tabwidth=tabSize, indentwidth=indentSize) self.SCISetIndent(indentSize) self.SCISetTabWidth(tabSize) def OnDebuggerStateChange(self, state): if state == dbgcon.DBGSTATE_NOT_DEBUGGING: - # Indicate breakpoints arent really usable. + # Indicate breakpoints aren't really usable. # Not quite white - useful when no marker margin, so set as background color. self.SCIMarkerSetBack(MARKER_BREAKPOINT, win32api.RGB(0xEF, 0xEF, 0xEF)) else: @@ -287,7 +287,7 @@ def _EndUserStateChange(self, info): scrollOff = info[1] - self.GetFirstVisibleLine() if scrollOff: self.LineScroll(scrollOff) - # Make sure we dont reset the cursor beyond the buffer. + # Make sure we don't reset the cursor beyond the buffer. max = self.GetTextLength() newPos = min(info[0][0], max), min(info[0][1], max) self.SetSel(newPos) @@ -609,7 +609,7 @@ def CheckIDLEMenus(self, idle): event, ["editor"] ) if keyname is not None: - text = text + "\t" + keyname + text += "\t" + keyname submenu.AppendMenu(flags, id, text) mainMenu = self.GetSharedMenu() diff --git a/Pythonwin/pywin/framework/editor/configui.py b/Pythonwin/pywin/framework/editor/configui.py index 174cb907ba..96d8e560a7 100644 --- a/Pythonwin/pywin/framework/editor/configui.py +++ b/Pythonwin/pywin/framework/editor/configui.py @@ -253,7 +253,7 @@ def OnInitDialog(self): for c in paletteVGA: if tt_color == win32api.RGB(c[1], c[2], c[3]): break - sel = sel + 1 + sel += 1 else: sel = -1 self.cbo.SetCurSel(sel) diff --git a/Pythonwin/pywin/framework/editor/document.py b/Pythonwin/pywin/framework/editor/document.py index 162d8400e8..c7ff78f09e 100644 --- a/Pythonwin/pywin/framework/editor/document.py +++ b/Pythonwin/pywin/framework/editor/document.py @@ -235,13 +235,13 @@ def _UpdateUIForState(self): try: # This seems necessary so the internal state of the window becomes # "visible". without it, it is still shown, but certain functions - # (such as updating the title) dont immediately work? + # (such as updating the title) don't immediately work? self.GetFirstView().ShowWindow(win32con.SW_SHOW) title = win32ui.GetFileTitle(filename) except win32ui.error: title = filename if self._IsReadOnly(): - title = title + " (read-only)" + title += " (read-only)" self.SetTitle(title) def MakeDocumentWritable(self): @@ -257,7 +257,7 @@ def MakeDocumentWritable(self): msg = "Would you like to check this file out?" defButton = win32con.MB_YESNO if self.IsModified(): - msg = msg + "\r\n\r\nALL CHANGES IN THE EDITOR WILL BE LOST" + msg += "\r\n\r\nALL CHANGES IN THE EDITOR WILL BE LOST" defButton = win32con.MB_YESNO if win32ui.MessageBox(msg, None, defButton) != win32con.IDYES: return 0 diff --git a/Pythonwin/pywin/framework/editor/editor.py b/Pythonwin/pywin/framework/editor/editor.py index a1208cba6f..facb5b23f1 100644 --- a/Pythonwin/pywin/framework/editor/editor.py +++ b/Pythonwin/pywin/framework/editor/editor.py @@ -236,7 +236,7 @@ def SetLineColor(self, lineNo, color): try: if color is None: color = self.defCharFormat[4] - lineNo = lineNo - 1 + lineNo -= 1 startIndex = self.LineIndex(lineNo) if startIndex != -1: self.SetSel(startIndex, self.LineIndex(lineNo + 1)) @@ -261,7 +261,7 @@ def Indent(self): if ch == "\t": curCol = ((curCol / self.tabSize) + 1) * self.tabSize else: - curCol = curCol + 1 + curCol += 1 nextColumn = ((curCol / self.indentSize) + 1) * self.indentSize # print("curCol is", curCol, "nextColumn is", nextColumn) ins = None @@ -274,7 +274,7 @@ def Indent(self): if check in ("\t", " "): ins = check break - lookLine = lookLine - 1 + lookLine -= 1 else: # See if the previous char can tell us check = line[realCol - 1] if check in ("\t", " "): @@ -290,7 +290,7 @@ def Indent(self): if ins == " ": # Calc the number of spaces to take us to the next stop - ins = ins * (nextColumn - curCol) + ins *= nextColumn - curCol self._obj_.ReplaceSel(ins) @@ -410,17 +410,17 @@ def OnKeyEnter(self, key): if res > 0 and curLine.strip(): curIndent = patIndent.group(1) self._obj_.ReplaceSel(curIndent) - return 0 # dont pass on + return 0 # don't pass on def OnKeyCtrlY(self, key): if not self.GetDocument().CheckMakeDocumentWritable(): return 0 self.CutCurLine() - return 0 # dont let him have it! + return 0 # don't let him have it! def OnKeyCtrlG(self, key): self.GotoLine() - return 0 # dont let him have it! + return 0 # don't let him have it! def OnKeyTab(self, key): if not self.GetDocument().CheckMakeDocumentWritable(): diff --git a/Pythonwin/pywin/framework/editor/template.py b/Pythonwin/pywin/framework/editor/template.py index bbaed4e689..3dbc202985 100644 --- a/Pythonwin/pywin/framework/editor/template.py +++ b/Pythonwin/pywin/framework/editor/template.py @@ -1,6 +1,5 @@ import os -import pywin.framework.window import win32api import win32ui from pywin.mfc import docview @@ -19,10 +18,10 @@ def __init__( ParentEditorTemplate.__init__(self, res, makeDoc, makeFrame, makeView) def _CreateDocTemplate(self, resourceId): - assert 0, "You must override this" + raise NotImplementedError("You must override this") def CreateWin32uiDocument(self): - assert 0, "You must override this" + raise NotImplementedError("You must override this") def GetFileExtensions(self): return ".txt", ".py" @@ -55,6 +54,6 @@ def OpenDocumentFile(self, filename, bMakeVisible=1): filename = os.path.join(path, filename) # print("filename") except (win32api.error, IndexError) as details: - # print("Couldnt get the full filename!", details) + # print("Couldn't get the full filename!", details) pass return self._obj_.OpenDocumentFile(filename, bMakeVisible) diff --git a/Pythonwin/pywin/framework/help.py b/Pythonwin/pywin/framework/help.py index 3d7676eb4d..a042b18658 100644 --- a/Pythonwin/pywin/framework/help.py +++ b/Pythonwin/pywin/framework/help.py @@ -52,7 +52,7 @@ def OpenHelpFile(fileName, helpCmd=None, helpArg=None): global htmlhelp_handle helpCmd = html_help_command_translators.get(helpCmd, helpCmd) # frame = win32ui.GetMainFrame().GetSafeHwnd() - frame = 0 # Dont want it overlapping ours! + frame = 0 # Don't want it overlapping ours! if htmlhelp_handle is None: htmlhelp_hwnd, htmlhelp_handle = win32help.HtmlHelp( frame, None, win32help.HH_INITIALIZE @@ -97,7 +97,7 @@ def _ListAllHelpFilesInRoot(root): helpDesc = win32api.RegEnumKey(key, keyNo) helpFile = win32api.RegQueryValue(key, helpDesc) retList.append((helpDesc, helpFile)) - keyNo = keyNo + 1 + keyNo += 1 except win32api.error as exc: import winerror @@ -149,12 +149,12 @@ def SetHelpMenuOtherHelp(mainMenu): if fname not in excludeFnames: helpIDMap[cmdID] = (desc, fname) win32ui.GetMainFrame().HookCommand(HandleHelpOtherCommand, cmdID) - cmdID = cmdID + 1 + cmdID += 1 helpMenu = mainMenu.GetSubMenu( mainMenu.GetMenuItemCount() - 1 ) # Help menu always last. - otherHelpMenuPos = 2 # cant search for ID, as sub-menu has no ID. + otherHelpMenuPos = 2 # can't search for ID, as sub-menu has no ID. otherMenu = helpMenu.GetSubMenu(otherHelpMenuPos) while otherMenu.GetMenuItemCount(): otherMenu.DeleteMenu(0, win32con.MF_BYPOSITION) diff --git a/Pythonwin/pywin/framework/interact.py b/Pythonwin/pywin/framework/interact.py index 9c4b52dd89..50d4b3e4d9 100644 --- a/Pythonwin/pywin/framework/interact.py +++ b/Pythonwin/pywin/framework/interact.py @@ -211,7 +211,7 @@ def ColorizeInteractiveCode(self, cdoc, styleStart, stylePyStart): # and ask the Python colorizer to color that. end = startSeg while end < lengthDoc and cdoc[end] not in b"\r\n": - end = end + 1 + end += 1 self.ColorizePythonCode(cdoc[:end], startSeg, state) stylePyStart = self.GetStringStyle(end - 1) if stylePyStart is None: @@ -224,7 +224,7 @@ def ColorizeInteractiveCode(self, cdoc, styleStart, stylePyStart): state = STYLE_INTERACTIVE_EOL if lastState != state: lastState = state - i = i + 1 + i += 1 # and the rest if startSeg < i: self.ColorSeg(startSeg, i - 1, state) @@ -243,7 +243,7 @@ def Colorize(self, start=0, end=-1): # If TQString, we continue it. Otherwise, we reset. look = start - 1 while look and self.scintilla.SCIGetCharAt(look) in "\n\r": - look = look - 1 + look -= 1 if look and look < start - 1: # Did we find a char before the \n\r sets? strstyle = self.GetStringStyle(look) quote_char = None @@ -452,12 +452,12 @@ def GetBlockBoundary(self, lineNo): while startLineNo > 0: if GetPromptPrefix(self.DoGetLine(startLineNo - 1)) is not None: break # there _is_ a prompt - startLineNo = startLineNo - 1 + startLineNo -= 1 endLineNo = lineNo while endLineNo < maxLineNo: if GetPromptPrefix(self.DoGetLine(endLineNo + 1)) is not None: break # there _is_ a prompt - endLineNo = endLineNo + 1 + endLineNo += 1 else: # Code block flag = 1 startLineNo = lineNo @@ -466,7 +466,7 @@ def GetBlockBoundary(self, lineNo): if prefix is None: break # there is no prompt. - startLineNo = startLineNo - 1 + startLineNo -= 1 endLineNo = lineNo while endLineNo < maxLineNo: prefix = GetPromptPrefix(self.DoGetLine(endLineNo + 1)) @@ -474,7 +474,7 @@ def GetBlockBoundary(self, lineNo): break # there is no prompt if prefix == str(sys.ps1): break # this is another command - endLineNo = endLineNo + 1 + endLineNo += 1 # continue until end of buffer, or no prompt return (startLineNo, endLineNo, flag) @@ -485,7 +485,7 @@ def ExtractCommand(self, lines): thisLine = self.DoGetLine(end) promptLen = len(GetPromptPrefix(thisLine)) retList = [thisLine[promptLen:]] + retList - end = end - 1 + end -= 1 return retList def OutputGrab(self): @@ -537,7 +537,7 @@ def ProcessEnterEvent(self, event): lines = self.ExtractCommand((start, end)) - # If we are in a code-block, but it isnt at the end of the buffer + # If we are in a code-block, but it isn't at the end of the buffer # then copy it to the end ready for editing and subsequent execution if end != self.GetLineCount() - 1: win32ui.SetStatusText("Press ENTER to execute command") @@ -565,7 +565,7 @@ def ProcessEnterEvent(self, event): ): # Need more input! bNeedIndent = 1 else: - # If the last line isnt empty, append a newline + # If the last line isn't empty, append a newline if self.history is not None: self.history.history_store(source) self.AppendToPrompt([]) @@ -582,10 +582,10 @@ def ProcessEnterEvent(self, event): pos = 0 indent = "" while len(curLine) > pos and curLine[pos] in string.whitespace: - indent = indent + curLine[pos] - pos = pos + 1 + indent += curLine[pos] + pos += 1 if _is_block_opener(curLine): - indent = indent + "\t" + indent += "\t" elif _is_block_closer(curLine): indent = indent[:-1] # use ReplaceSel to ensure it goes at the cursor rather than end of buffer. diff --git a/Pythonwin/pywin/framework/intpyapp.py b/Pythonwin/pywin/framework/intpyapp.py index 54b4c6e59a..84544b4127 100644 --- a/Pythonwin/pywin/framework/intpyapp.py +++ b/Pythonwin/pywin/framework/intpyapp.py @@ -123,7 +123,7 @@ def OnCommand(self, wparam, lparam): class InteractivePythonApp(app.CApp): - # This works if necessary - just we dont need to override the Run method. + # This works if necessary - just we don't need to override the Run method. # def Run(self): # return self._obj_.Run() @@ -482,12 +482,12 @@ def OnViewOptions(self, id, code): pages = [] for template in self.GetDocTemplateList(): try: - # Dont actually call the function with the exception handler. + # Don't actually call the function with the exception handler. getter = template.GetPythonPropertyPages except AttributeError: # Template does not provide property pages! continue - pages = pages + getter() + pages.extend(getter()) # Debugger template goes at the end try: @@ -519,7 +519,7 @@ def OnUpdateInteractiveWindow(self, cmdui): try: interact = sys.modules["pywin.framework.interact"] state = interact.IsInteractiveWindowVisible() - except KeyError: # Interactive module hasnt ever been imported. + except KeyError: # Interactive module hasn't ever been imported. state = 0 cmdui.Enable() cmdui.SetCheck(state) diff --git a/Pythonwin/pywin/framework/mdi_pychecker.py b/Pythonwin/pywin/framework/mdi_pychecker.py index 1ff336c5e0..71ba1af0c7 100644 --- a/Pythonwin/pywin/framework/mdi_pychecker.py +++ b/Pythonwin/pywin/framework/mdi_pychecker.py @@ -54,7 +54,7 @@ def getsubdirs(d): for f in flist: if os.path.isdir(f): dlist.append(f) - dlist = dlist + getsubdirs(f) + dlist.extend(getsubdirs(f)) return dlist @@ -234,9 +234,9 @@ def setInitParams(self, paramstr): paramstr = win32ui.GetProfileVal("Pychecker", "Params", "\t\t\t1\t0\t0") params = paramstr.split("\t") if len(params) < 3: - params = params + [""] * (3 - len(params)) + params.extend([""] * (3 - len(params))) if len(params) < 6: - params = params + [0] * (6 - len(params)) + params.extend([0] * (6 - len(params))) self.dirpattern = params[0] self.filpattern = params[1] self.greppattern = params[2] or "-#1000 --only" @@ -381,7 +381,7 @@ def threadPycheckerRun(self): self.SetModifiedFlag(0) def _inactive_idleHandler(self, handler, count): - self.fndx = self.fndx + 1 + self.fndx += 1 if self.fndx < len(self.flist): f = self.flist[self.fndx] if self.verbose: @@ -394,14 +394,14 @@ def _inactive_idleHandler(self, handler, count): self.GetFirstView().Append(f + "(" + repr(i + 1) + ") " + line) else: self.fndx = -1 - self.fpndx = self.fpndx + 1 + self.fpndx += 1 if self.fpndx < len(self.fplist): self.flist = glob.glob( self.dp[self.dpndx] + "\\" + self.fplist[self.fpndx] ) else: self.fpndx = 0 - self.dpndx = self.dpndx + 1 + self.dpndx += 1 if self.dpndx < len(self.dp): self.flist = glob.glob( self.dp[self.dpndx] + "\\" + self.fplist[self.fpndx] @@ -479,7 +479,7 @@ def OnLDblClick(self, params): fname = regexGrepResult.group(1) line = int(regexGrepResult.group(2)) scriptutils.JumpToDocument(fname, line) - return 0 # dont pass on + return 0 # don't pass on return 1 # pass it on by default. def OnRClick(self, params): @@ -712,10 +712,10 @@ def getMore(self, section, key): i = 0 newitems = dlg.getNew() if newitems: - items = items + newitems + items.extend(newitems) for item in items: win32api.WriteProfileVal(section, repr(i), item, ini) - i = i + 1 + i += 1 self.UpdateData(0) def OnOK(self): diff --git a/Pythonwin/pywin/framework/scriptutils.py b/Pythonwin/pywin/framework/scriptutils.py index aedeaee6a8..98c34b4778 100644 --- a/Pythonwin/pywin/framework/scriptutils.py +++ b/Pythonwin/pywin/framework/scriptutils.py @@ -17,10 +17,12 @@ from .cmdline import ParseArgs -RS_DEBUGGER_NONE = 0 # Dont run under the debugger. +RS_DEBUGGER_NONE = 0 # Don't run under the debugger. RS_DEBUGGER_STEP = 1 # Start stepping under the debugger RS_DEBUGGER_GO = 2 # Just run under the debugger, stopping only at break-points. -RS_DEBUGGER_PM = 3 # Dont run under debugger, but do post-mortem analysis on exception. +RS_DEBUGGER_PM = ( + 3 # Don't run under debugger, but do post-mortem analysis on exception. +) debugging_options = """No debugging Step-through in the debugger @@ -159,7 +161,7 @@ def GetActiveEditControl(): def GetActiveEditorDocument(): """Returns the active editor document and view, or (None,None) if no - active document or its not an editor document. + active document or it's not an editor document. """ view = GetActiveView() if view is None or isinstance(view, TreeView): @@ -173,7 +175,7 @@ def GetActiveEditorDocument(): def GetActiveFileName(bAutoSave=1): """Gets the file name for the active frame, saving it if necessary. - Returns None if it cant be found, or raises KeyboardInterrupt. + Returns None if it can't be found, or raises KeyboardInterrupt. """ pathName = None active = GetActiveView() @@ -280,7 +282,7 @@ def RunScript(defName=None, defArgs=None, bShowDialog=1, debuggingType=None): if ( len(os.path.splitext(script)[1]) == 0 ): # check if no extension supplied, and give one. - script = script + ".py" + script += ".py" # If no path specified, try and locate the file path, fnameonly = os.path.split(script) if len(path) == 0: @@ -365,7 +367,7 @@ def RunScript(defName=None, defArgs=None, bShowDialog=1, debuggingType=None): exec(codeObject, __main__.__dict__) bWorked = 1 except bdb.BdbQuit: - # Dont print tracebacks when the debugger quit, but do print a message. + # Don't print tracebacks when the debugger quit, but do print a message. print("Debugging session cancelled.") exitCode = 1 bWorked = 1 @@ -373,7 +375,7 @@ def RunScript(defName=None, defArgs=None, bShowDialog=1, debuggingType=None): exitCode = code bWorked = 1 except KeyboardInterrupt: - # Consider this successful, as we dont want the debugger. + # Consider this successful, as we don't want the debugger. # (but we do want a traceback!) if interact.edit and interact.edit.currentView: interact.edit.currentView.EnsureNoPrompt() @@ -431,7 +433,7 @@ def ImportFile(): pathName = dlg.GetPathName() - # If already imported, dont look for package + # If already imported, don't look for package path, modName = os.path.split(pathName) modName, modExt = os.path.splitext(modName) newPath = None @@ -505,7 +507,7 @@ def CheckFile(): try: f = open(pathName) except OSError as details: - print(f"Cant open file '{pathName}' - {details}") + print(f"Can't open file '{pathName}' - {details}") return try: code = f.read() + "\n" @@ -556,7 +558,7 @@ def RunTabNanny(filename): pass win32ui.SetStatusText("The TabNanny found trouble at line %d" % lineno) except (IndexError, TypeError, ValueError): - print("The tab nanny complained, but I cant see where!") + print("The tab nanny complained, but I can't see where!") print(data) return 0 return 1 @@ -568,7 +570,7 @@ def _JumpToPosition(fileName, lineno, col=1): def JumpToDocument(fileName, lineno=0, col=1, nChars=0, bScrollToTop=0): # Jump to the position in a file. - # If lineno is <= 0, dont move the position - just open/restore. + # If lineno is <= 0, don't move the position - just open/restore. # if nChars > 0, select that many characters. # if bScrollToTop, the specified line will be moved to the top of the window # (eg, bScrollToTop should be false when jumping to an error line to retain the @@ -592,7 +594,7 @@ def JumpToDocument(fileName, lineno=0, col=1, nChars=0, bScrollToTop=0): try: view.EnsureCharsVisible(charNo) except AttributeError: - print("Doesnt appear to be one of our views?") + print("Doesn't appear to be one of our views?") view.SetSel(min(start, size), min(start + nChars, size)) if bScrollToTop: curTop = view.GetFirstVisibleLine() @@ -675,7 +677,7 @@ def LocatePythonFile(fileName, bBrowseIfDir=1): else: return None else: - fileName = fileName + ".py" + fileName += ".py" if os.path.isfile(fileName): break # Found it! diff --git a/Pythonwin/pywin/framework/sgrepmdi.py b/Pythonwin/pywin/framework/sgrepmdi.py index 6383c939d5..539fe6d124 100644 --- a/Pythonwin/pywin/framework/sgrepmdi.py +++ b/Pythonwin/pywin/framework/sgrepmdi.py @@ -36,7 +36,7 @@ def getsubdirs(d): for f in flist: if os.path.isdir(f): dlist.append(f) - dlist = dlist + getsubdirs(f) + dlist += getsubdirs(f) return dlist @@ -218,9 +218,9 @@ def setInitParams(self, paramstr): paramstr = win32ui.GetProfileVal("Grep", "Params", "\t\t\t1\t0\t0") params = paramstr.split("\t") if len(params) < 3: - params = params + [""] * (3 - len(params)) + params.extend([""] * (3 - len(params))) if len(params) < 6: - params = params + [0] * (6 - len(params)) + params.extend([0] * (6 - len(params))) self.dirpattern = params[0] self.filpattern = params[1] self.greppattern = params[2] @@ -290,7 +290,7 @@ def doSearch(self): win32ui.GetApp().AddIdleHandler(self.SearchFile) def SearchFile(self, handler, count): - self.fndx = self.fndx + 1 + self.fndx += 1 if self.fndx < len(self.flist): f = self.flist[self.fndx] if self.verbose: @@ -306,14 +306,14 @@ def SearchFile(self, handler, count): self.GetFirstView().Append(f + "(" + repr(i + 1) + ") " + line) else: self.fndx = -1 - self.fpndx = self.fpndx + 1 + self.fpndx += 1 if self.fpndx < len(self.fplist): self.flist = glob.glob( self.dp[self.dpndx] + "\\" + self.fplist[self.fpndx] ) else: self.fpndx = 0 - self.dpndx = self.dpndx + 1 + self.dpndx += 1 if self.dpndx < len(self.dp): self.flist = glob.glob( self.dp[self.dpndx] + "\\" + self.fplist[self.fpndx] @@ -387,7 +387,7 @@ def OnLDblClick(self, params): fname = regexGrepResult.group(1) line = int(regexGrepResult.group(2)) scriptutils.JumpToDocument(fname, line) - return 0 # dont pass on + return 0 # don't pass on return 1 # pass it on by default. def OnRClick(self, params): @@ -624,10 +624,10 @@ def getMore(self, section, key): i = 0 newitems = dlg.getNew() if newitems: - items = items + newitems + items.extend(newitems) for item in items: win32api.WriteProfileVal(section, repr(i), item, ini) - i = i + 1 + i += 1 self.UpdateData(0) def OnOK(self): diff --git a/Pythonwin/pywin/framework/startup.py b/Pythonwin/pywin/framework/startup.py index d10eecf35a..3cc6c01691 100644 --- a/Pythonwin/pywin/framework/startup.py +++ b/Pythonwin/pywin/framework/startup.py @@ -39,7 +39,7 @@ # To fix a problem with Pythonwin when started from the Pythonwin directory, # we update the pywin path to ensure it is absolute. # If it is indeed relative, it will be relative to our current directory. -# If its already absolute, then this will have no affect. +# If it's already absolute, then this will have no affect. import pywin import pywin.framework diff --git a/Pythonwin/pywin/framework/stdin.py b/Pythonwin/pywin/framework/stdin.py index 91fe7ef3e1..5fe7bffc32 100644 --- a/Pythonwin/pywin/framework/stdin.py +++ b/Pythonwin/pywin/framework/stdin.py @@ -119,7 +119,7 @@ def readlines(self, *sizehint): line = self.readline() if line == "": break - total_read = total_read + len(line) + total_read += len(line) result.append(line) return result diff --git a/Pythonwin/pywin/framework/toolmenu.py b/Pythonwin/pywin/framework/toolmenu.py index 1f16f9fca1..d1b7e80bbe 100644 --- a/Pythonwin/pywin/framework/toolmenu.py +++ b/Pythonwin/pywin/framework/toolmenu.py @@ -41,7 +41,7 @@ def LoadToolMenuItems(): break cmd = win32ui.GetProfileVal("Tools Menu\\%s" % lookNo, "Command", "") items.append((menu, cmd)) - lookNo = lookNo + 1 + lookNo += 1 if len(items) == 0: items = defaultToolMenuItems @@ -64,14 +64,14 @@ def WriteToolMenuItems(items): break win32api.RegDeleteKey(toolKey, subkey) # Keys are now removed - write the new ones. - # But first check if we have the defaults - and if so, dont write anything! + # But first check if we have the defaults - and if so, don't write anything! if items == defaultToolMenuItems: return itemNo = 1 for menu, cmd in items: win32ui.WriteProfileVal("Tools Menu\\%s" % itemNo, "", menu) win32ui.WriteProfileVal("Tools Menu\\%s" % itemNo, "Command", cmd) - itemNo = itemNo + 1 + itemNo += 1 def SetToolsMenu(menu, menuPos=None): @@ -90,7 +90,7 @@ def SetToolsMenu(menu, menuPos=None): win32con.MF_ENABLED | win32con.MF_STRING, idPos, menuString ) win32ui.GetMainFrame().HookCommand(HandleToolCommand, idPos) - idPos = idPos + 1 + idPos += 1 # Find the correct spot to insert the new tools menu. if menuPos is None: @@ -191,7 +191,7 @@ def OnInitDialog(self): for desc, cmd in LoadToolMenuItems(): lc.InsertItem(itemNo, desc) lc.SetItemText(itemNo, 1, cmd) - itemNo = itemNo + 1 + itemNo += 1 self.listControl = lc return dialog.PropertyPage.OnInitDialog(self) @@ -209,7 +209,7 @@ def OnOK(self): except win32ui.error: # no more items! break - itemLook = itemLook + 1 + itemLook += 1 WriteToolMenuItems(items) return self._obj_.OnOK() diff --git a/Pythonwin/pywin/framework/winout.py b/Pythonwin/pywin/framework/winout.py index 1e831c2ea9..c98c98ff85 100644 --- a/Pythonwin/pywin/framework/winout.py +++ b/Pythonwin/pywin/framework/winout.py @@ -180,9 +180,9 @@ def HandleSpecialLine(self): fileNameSpec = fileName fileName = scriptutils.LocatePythonFile(fileName) if fileName is None: - # Dont force update, so it replaces the idle prompt. + # Don't force update, so it replaces the idle prompt. win32ui.SetStatusText( - "Cant locate the file '%s'" % (fileNameSpec), 0 + "Can't locate the file '%s'" % (fileNameSpec), 0 ) return 1 @@ -228,7 +228,7 @@ def HookHandlers(self): def OnLDoubleClick(self, params): if self.HandleSpecialLine(): - return 0 # dont pass on + return 0 # don't pass on return 1 # pass it on by default. def RestoreKillBuffer(self): @@ -290,7 +290,7 @@ def OnScintillaDoubleClick(self, std, extra): self.HandleSpecialLine() ## def OnLDoubleClick(self,params): - ## return 0 # never dont pass on + ## return 0 # never don't pass on def RestoreKillBuffer(self): assert len(self.template.killBuffer) in (0, 1), "Unexpected killbuffer contents" @@ -463,7 +463,7 @@ def QueueIdleHandler(self, handler, count): except KeyboardInterrupt: # First interrupt since idle we just pass on. # later ones we dump the queue and give up. - self.interruptCount = self.interruptCount + 1 + self.interruptCount += 1 if self.interruptCount > 1: # Drop the queue quickly as the user is already annoyed :-) self.outputQueue = queue.Queue(-1) @@ -511,7 +511,7 @@ def QueueFlush(self, max=None): rc = 1 break if max is not None: - max = max - 1 + max -= 1 if len(items) != 0: if not self.CheckRecreateWindow(): debug(":Recreate failed!\n") diff --git a/Pythonwin/pywin/idle/AutoExpand.py b/Pythonwin/pywin/idle/AutoExpand.py index 3b302ee93d..37fb811529 100644 --- a/Pythonwin/pywin/idle/AutoExpand.py +++ b/Pythonwin/pywin/idle/AutoExpand.py @@ -91,5 +91,5 @@ def getprevword(self): line = self.text.get("insert linestart", "insert") i = len(line) while i > 0 and line[i - 1] in self.wordchars: - i = i - 1 + i -= 1 return line[i:] diff --git a/Pythonwin/pywin/idle/AutoIndent.py b/Pythonwin/pywin/idle/AutoIndent.py index 0ed506e5ab..e433097e91 100644 --- a/Pythonwin/pywin/idle/AutoIndent.py +++ b/Pythonwin/pywin/idle/AutoIndent.py @@ -148,7 +148,7 @@ def smart_backspace_event(self, event): ncharsdeleted = 0 while 1: chars = chars[:-1] - ncharsdeleted = ncharsdeleted + 1 + ncharsdeleted += 1 have = len(chars.expandtabs(self.tabwidth)) if have <= want or chars[-1] not in " \t": break @@ -203,7 +203,7 @@ def newline_and_indent_event(self, event): line = text.get("insert linestart", "insert") i, n = 0, len(line) while i < n and line[i] in " \t": - i = i + 1 + i += 1 if i == n: # the cursor is in or at leading indentation; just inject # an empty line at the start and strip space from current line @@ -215,7 +215,7 @@ def newline_and_indent_event(self, event): i = 0 while line and line[-1] in " \t": line = line[:-1] - i = i + 1 + i += 1 if i: text.delete("insert - %d chars" % i, "insert") # strip whitespace after insert point @@ -262,7 +262,7 @@ def newline_and_indent_event(self, event): else: self.reindent_to(y.compute_backslash_indent()) else: - assert 0, "bogus continuation type " + repr(c) + raise ValueError(f"bogus continuation type {c!r}") return "break" # This line starts a brand new stmt; indent relative to @@ -298,7 +298,7 @@ def indent_region_event(self, event): line = lines[pos] if line: raw, effective = classifyws(line, self.tabwidth) - effective = effective + self.indentwidth + effective += self.indentwidth lines[pos] = self._make_blanks(effective) + line[raw:] self.set_region(head, tail, chars, lines) return "break" @@ -473,10 +473,10 @@ def classifyws(s, tabwidth): raw = effective = 0 for ch in s: if ch == " ": - raw = raw + 1 - effective = effective + 1 + raw += 1 + effective += 1 elif ch == "\t": - raw = raw + 1 + raw += 1 effective = (effective // tabwidth + 1) * tabwidth else: break diff --git a/Pythonwin/pywin/idle/CallTips.py b/Pythonwin/pywin/idle/CallTips.py index 810d8c8818..c158479551 100644 --- a/Pythonwin/pywin/idle/CallTips.py +++ b/Pythonwin/pywin/idle/CallTips.py @@ -88,7 +88,7 @@ def get_object_at_cursor( chars = text.get("insert linestart", "insert") i = len(chars) while i and chars[i - 1] in wordchars: - i = i - 1 + i -= 1 word = chars[i:] if word: # How is this for a hack! @@ -147,8 +147,8 @@ def get_arg_text(ob): if pos < 0 or pos > 70: pos = 70 if argText: - argText = argText + "\n" - argText = argText + doc[:pos] + argText += "\n" + argText += doc[:pos] return argText diff --git a/Pythonwin/pywin/idle/FormatParagraph.py b/Pythonwin/pywin/idle/FormatParagraph.py index b3e74c532e..caecb0f1f9 100644 --- a/Pythonwin/pywin/idle/FormatParagraph.py +++ b/Pythonwin/pywin/idle/FormatParagraph.py @@ -12,7 +12,7 @@ # applied. # * If a comment block has leading whitespace that mixes tabs and # spaces, they will not be considered part of the same block. -# * Fancy comments, like this bulleted list, arent handled :-) +# * Fancy comments, like this bulleted list, aren't handled :-) import re @@ -61,9 +61,9 @@ def format_paragraph_event(self, event): newdata = reformat_paragraph(data, format_width) # re-split and re-insert the comment header. newdata = newdata.split("\n") - # If the block ends in a \n, we dont want the comment - # prefix inserted after it. (Im not sure it makes sense to - # reformat a comment block that isnt made of complete + # If the block ends in a \n, we don't want the comment + # prefix inserted after it. (I'm not sure it makes sense to + # reformat a comment block that isn't made of complete # lines, but whatever!) Can't think of a clean soltution, # so we hack away block_suffix = "" @@ -91,7 +91,7 @@ def find_paragraph(text, mark): lineno, col = list(map(int, mark.split("."))) line = text.get("%d.0" % lineno, "%d.0 lineend" % lineno) while text.compare("%d.0" % lineno, "<", "end") and is_all_white(line): - lineno = lineno + 1 + lineno += 1 line = text.get("%d.0" % lineno, "%d.0 lineend" % lineno) first_lineno = lineno comment_header = get_comment_header(line) @@ -99,7 +99,7 @@ def find_paragraph(text, mark): while get_comment_header(line) == comment_header and not is_all_white( line[comment_header_len:] ): - lineno = lineno + 1 + lineno += 1 line = text.get("%d.0" % lineno, "%d.0 lineend" % lineno) last = "%d.0" % lineno # Search back to beginning of paragraph @@ -110,7 +110,7 @@ def find_paragraph(text, mark): and get_comment_header(line) == comment_header and not is_all_white(line[comment_header_len:]) ): - lineno = lineno - 1 + lineno -= 1 line = text.get("%d.0" % lineno, "%d.0 lineend" % lineno) first = "%d.0" % (lineno + 1) return first, last, comment_header, text.get(first, last) @@ -121,7 +121,7 @@ def reformat_paragraph(data, limit=70): i = 0 n = len(lines) while i < n and is_all_white(lines[i]): - i = i + 1 + i += 1 if i >= n: return data indent1 = get_indent(lines[i]) @@ -141,10 +141,10 @@ def reformat_paragraph(data, limit=70): if len((partial + word).expandtabs()) > limit and partial != indent1: new.append(partial.rstrip()) partial = indent2 - partial = partial + word + " " + partial += word + " " if j + 1 < len(words) and words[j + 1] != " ": - partial = partial + " " - i = i + 1 + partial += " " + i += 1 new.append(partial.rstrip()) # XXX Should reformat remaining paragraphs as well new.extend(lines[i:]) diff --git a/Pythonwin/pywin/idle/IdleHistory.py b/Pythonwin/pywin/idle/IdleHistory.py index 24e6924008..11b5158f06 100644 --- a/Pythonwin/pywin/idle/IdleHistory.py +++ b/Pythonwin/pywin/idle/IdleHistory.py @@ -45,9 +45,9 @@ def history_do(self, reverse): nprefix = len(prefix) while 1: if reverse: - pointer = pointer - 1 + pointer -= 1 else: - pointer = pointer + 1 + pointer += 1 if pointer < 0 or pointer >= nhist: self.text.bell() if self._get_source("iomark", "end-1c") != prefix: diff --git a/Pythonwin/pywin/idle/PyParse.py b/Pythonwin/pywin/idle/PyParse.py index 8a994254e4..f817fb1ce3 100644 --- a/Pythonwin/pywin/idle/PyParse.py +++ b/Pythonwin/pywin/idle/PyParse.py @@ -252,26 +252,26 @@ def _study1(self): i, n = 0, len(str) while i < n: ch = str[i] - i = i + 1 + i += 1 # cases are checked in decreasing order of frequency if ch == "x": continue if ch == "\n": - lno = lno + 1 + lno += 1 if level == 0: push_good(lno) # else we're in an unclosed bracket structure continue if ch == "(": - level = level + 1 + level += 1 continue if ch == ")": if level: - level = level - 1 + level -= 1 # else the program is invalid, but we can't complain continue @@ -279,22 +279,22 @@ def _study1(self): # consume the string quote = ch if str[i - 1 : i + 2] == quote * 3: - quote = quote * 3 + quote *= 3 w = len(quote) - 1 - i = i + w + i += w while i < n: ch = str[i] - i = i + 1 + i += 1 if ch == "x": continue if str[i - 1 : i + w] == quote: - i = i + w + i += w break if ch == "\n": - lno = lno + 1 + lno += 1 if w == 0: # unterminated single-quoted string if level == 0: @@ -305,8 +305,8 @@ def _study1(self): if ch == "\\": assert i < n if str[i] == "\n": - lno = lno + 1 - i = i + 1 + lno += 1 + i += 1 continue # else comment char or paren inside string @@ -326,10 +326,10 @@ def _study1(self): assert ch == "\\" assert i < n if str[i] == "\n": - lno = lno + 1 + lno += 1 if i + 1 == n: continuation = C_BACKSLASH - i = i + 1 + i += 1 # The last stmt may be continued for all 3 reasons. # String continuation takes precedence over bracket @@ -381,7 +381,7 @@ def _study2(self): # The stmt str[p:q] isn't a continuation, but may be blank # or a non-indenting comment line. if _junkre(str, p): - i = i - 1 + i -= 1 else: break if i == 0: @@ -404,7 +404,7 @@ def _study2(self): # back up over totally boring whitespace i = newp - 1 # index of last boring char while i >= p and str[i] in " \t\n": - i = i - 1 + i -= 1 if i >= p: lastch = str[i] p = newp @@ -416,14 +416,14 @@ def _study2(self): if ch in "([{": push_stack(p) lastch = ch - p = p + 1 + p += 1 continue if ch in ")]}": if stack: del stack[-1] lastch = ch - p = p + 1 + p += 1 continue if ch == '"' or ch == "'": @@ -445,12 +445,12 @@ def _study2(self): continue assert ch == "\\" - p = p + 1 # beyond backslash + p += 1 # beyond backslash assert p < q if str[p] != "\n": # the program is invalid, but can't complain lastch = ch + str[p] - p = p + 1 # beyond escaped char + p += 1 # beyond escaped char # end while p < q: @@ -468,7 +468,7 @@ def compute_bracket_indent(self): str = self.str n = len(str) origi = i = str.rfind("\n", 0, j) + 1 - j = j + 1 # one beyond open bracket + j += 1 # one beyond open bracket # find first list item; set i to start of its line while j < n: m = _itemre(str, j) @@ -484,7 +484,7 @@ def compute_bracket_indent(self): # reproduce the bracket line's indentation + a level j = i = origi while str[j] in " \t": - j = j + 1 + j += 1 extra = self.indentwidth return len(str[i:j].expandtabs(self.tabwidth)) + extra @@ -507,7 +507,7 @@ def compute_backslash_indent(self): str = self.str i = self.stmt_start while str[i] in " \t": - i = i + 1 + i += 1 startpos = i # See whether the initial line starts an assignment stmt; i.e., @@ -517,12 +517,12 @@ def compute_backslash_indent(self): while i < endpos: ch = str[i] if ch in "([{": - level = level + 1 - i = i + 1 + level += 1 + i += 1 elif ch in ")]}": if level: - level = level - 1 - i = i + 1 + level -= 1 + i += 1 elif ch == '"' or ch == "'": i = _match_stringre(str, i, endpos).end() elif ch == "#": @@ -536,12 +536,12 @@ def compute_backslash_indent(self): found = 1 break else: - i = i + 1 + i += 1 if found: # found a legit =, but it may be the last interesting # thing on the line - i = i + 1 # move beyond the = + i += 1 # move beyond the = found = re.match(r"\s*\\", str[i:endpos]) is None if not found: @@ -549,7 +549,7 @@ def compute_backslash_indent(self): # of non-whitespace chars i = startpos while str[i] not in " \t\n": - i = i + 1 + i += 1 return len(str[self.stmt_start : i].expandtabs(self.tabwidth)) + 1 @@ -562,7 +562,7 @@ def get_base_indent_string(self): j = i str = self.str while j < n and str[j] in " \t": - j = j + 1 + j += 1 return str[i:j] # Did the last interesting stmt open a block? diff --git a/Pythonwin/pywin/mfc/dialog.py b/Pythonwin/pywin/mfc/dialog.py index 41107e54d3..93a5ba6504 100644 --- a/Pythonwin/pywin/mfc/dialog.py +++ b/Pythonwin/pywin/mfc/dialog.py @@ -201,7 +201,7 @@ def __init__(self, id, dllid=None, caption=0): dlg = win32ui.CreatePropertyPage(id, caption) if self.dll: win32ui.SetResource(oldRes) - # dont call dialog init! + # don't call dialog init! window.Wnd.__init__(self, dlg) self.HookCommands() diff --git a/Pythonwin/pywin/mfc/object.py b/Pythonwin/pywin/mfc/object.py index 62062a5351..218b67e665 100644 --- a/Pythonwin/pywin/mfc/object.py +++ b/Pythonwin/pywin/mfc/object.py @@ -24,11 +24,11 @@ def __getattr__( return getattr(o, attr) # Only raise this error for non "internal" names - # Python may be calling __len__, __bool__, etc, so - # we dont want this exception + # we don't want this exception if attr[0] != "_" and attr[-1] != "_": raise win32ui.error("The MFC object has died.") except KeyError: - # No _obj_ at all - dont report MFC object died when there isnt one! + # No _obj_ at all - don't report MFC object died when there isn't one! pass raise AttributeError(attr) diff --git a/Pythonwin/pywin/scintilla/IDLEenvironment.py b/Pythonwin/pywin/scintilla/IDLEenvironment.py index 79048d65f5..f3153c9a74 100644 --- a/Pythonwin/pywin/scintilla/IDLEenvironment.py +++ b/Pythonwin/pywin/scintilla/IDLEenvironment.py @@ -208,19 +208,19 @@ def _NextTok(str, pos): if pos >= end: return None, 0 while pos < end and str[pos] in string.whitespace: - pos = pos + 1 + pos += 1 # Special case for +- if str[pos] in "+-": return str[pos], pos + 1 # Digits also a special case. endPos = pos while endPos < end and str[endPos] in string.digits + ".": - endPos = endPos + 1 + endPos += 1 if pos != endPos: return str[pos:endPos], endPos endPos = pos while endPos < end and str[endPos] not in string.whitespace + string.digits + "+-": - endPos = endPos + 1 + endPos += 1 if pos != endPos: return str[pos:endPos], endPos return None, 0 @@ -236,7 +236,7 @@ def TkIndexToOffset(bm, edit, marks): if col == "first" or col == "last": # Tag name if line != "sel": - raise ValueError("Tags arent here!") + raise ValueError("Tags aren't here!") sel = edit.GetSel() if sel[0] == sel[1]: raise EmptyRange @@ -253,7 +253,7 @@ def TkIndexToOffset(bm, edit, marks): pos = edit.LineIndex(line) if pos == -1: pos = edit.GetTextLength() - pos = pos + int(col) + pos += int(col) except (ValueError, IndexError): raise ValueError("Unexpected literal in '%s'" % base) elif base == "insert": @@ -262,7 +262,7 @@ def TkIndexToOffset(bm, edit, marks): pos = edit.GetTextLength() # Pretend there is a trailing '\n' if necessary if pos and edit.SCIGetCharAt(pos - 1) != "\n": - pos = pos + 1 + pos += 1 else: try: pos = marks[base] @@ -283,23 +283,23 @@ def TkIndexToOffset(bm, edit, marks): if what[0] != "c": raise ValueError("+/- only supports chars") if word == "+": - pos = pos + int(num) + pos += int(num) else: - pos = pos - int(num) + pos -= int(num) elif word == "wordstart": while pos > 0 and edit.SCIGetCharAt(pos - 1) in wordchars: - pos = pos - 1 + pos -= 1 elif word == "wordend": end = edit.GetTextLength() while pos < end and edit.SCIGetCharAt(pos) in wordchars: - pos = pos + 1 + pos += 1 elif word == "linestart": while pos > 0 and edit.SCIGetCharAt(pos - 1) not in "\n\r": - pos = pos - 1 + pos -= 1 elif word == "lineend": end = edit.GetTextLength() while pos < end and edit.SCIGetCharAt(pos) not in "\n\r": - pos = pos + 1 + pos += 1 else: raise ValueError("Unsupported relative offset '%s'" % word) return max(pos, 0) # Tkinter is tollerant of -ve indexes - we aren't @@ -322,8 +322,8 @@ def __init__(self, edit): ## size = self.edit.GetTabWidth() ## if size==8: return "" # Tk default ## return size # correct semantics? - ## elif item=="font": # Used for measurements we dont need to do! - ## return "Dont know the font" + ## elif item=="font": # Used for measurements we don't need to do! + ## return "Don't know the font" ## raise IndexError, "Invalid index '%s'" % item def make_calltip_window(self): if self.calltips is None: @@ -351,13 +351,13 @@ def _fix_indexes(self, start, end): and self.edit.SCIGetCharAt(start) == "\n" and self.edit.SCIGetCharAt(start - 1) == "\r" ): - start = start - 1 + start -= 1 if ( end < self.edit.GetTextLength() and self.edit.SCIGetCharAt(end - 1) == "\r" and self.edit.SCIGetCharAt(end) == "\n" ): - end = end + 1 + end += 1 return start, end ## def get_tab_width(self): @@ -397,7 +397,7 @@ def get(self, start, end=None): ret = self.edit.GetTextRange(start, end) # pretend a trailing '\n' exists if necessary. if checkEnd and (not ret or ret[-1] != "\n"): - ret = ret + "\n" + ret += "\n" return ret.replace("\r", "") def index(self, spec): @@ -447,7 +447,7 @@ def delete(self, start, end=None): if old >= start and old < end: old = start elif old >= end: - old = old - (end - start) + old -= end - start self.edit.SetSel(old) def bell(self): @@ -480,7 +480,7 @@ def tag_add(self, name, start, end): def tag_remove(self, name, start, end): if name != "sel" or start != "1.0" or end != "end": - raise ValueError("Cant remove this tag") + raise ValueError("Can't remove this tag") # Turn the sel into a cursor self.edit.SetSel(self.edit.GetSel()[0]) diff --git a/Pythonwin/pywin/scintilla/bindings.py b/Pythonwin/pywin/scintilla/bindings.py index 16ed461a87..60001c7494 100644 --- a/Pythonwin/pywin/scintilla/bindings.py +++ b/Pythonwin/pywin/scintilla/bindings.py @@ -25,7 +25,7 @@ def assign_command_id(event, id=0): id = event_to_commands.get(event, 0) if id == 0: id = next_id - next_id = next_id + 1 + next_id += 1 # Only map the ones we allocated - specified ones are assumed to have a handler command_to_events[id] = event event_to_commands[event] = id @@ -164,13 +164,11 @@ def fire_key_event(self, msg): key = msg[2] keyState = 0 if win32api.GetKeyState(win32con.VK_CONTROL) & 0x8000: - keyState = ( - keyState | win32con.RIGHT_CTRL_PRESSED | win32con.LEFT_CTRL_PRESSED - ) + keyState |= win32con.RIGHT_CTRL_PRESSED | win32con.LEFT_CTRL_PRESSED if win32api.GetKeyState(win32con.VK_SHIFT) & 0x8000: - keyState = keyState | win32con.SHIFT_PRESSED + keyState |= win32con.SHIFT_PRESSED if win32api.GetKeyState(win32con.VK_MENU) & 0x8000: - keyState = keyState | win32con.LEFT_ALT_PRESSED | win32con.RIGHT_ALT_PRESSED + keyState |= win32con.LEFT_ALT_PRESSED | win32con.RIGHT_ALT_PRESSED keyinfo = key, keyState # Special hacks for the dead-char key on non-US keyboards. # (XXX - which do not work :-( diff --git a/Pythonwin/pywin/scintilla/config.py b/Pythonwin/pywin/scintilla/config.py index 8113a0a89c..6f5a6396fd 100644 --- a/Pythonwin/pywin/scintilla/config.py +++ b/Pythonwin/pywin/scintilla/config.py @@ -133,7 +133,7 @@ def __init__(self, f): line = fp.readline() if not line: break - lineno = lineno + 1 + lineno += 1 section, subsection = get_section_header(line) if not line: break @@ -151,7 +151,7 @@ def __init__(self, f): f"Unrecognised section header '{section}:{subsection}'" ) line = fp.readline() - lineno = lineno + 1 + lineno += 1 if b_close: fp.close() # Check critical data. @@ -201,7 +201,7 @@ def configure(self, editor, subsections=None): for name, func in list(ns.items()): if isinstance(func, types.FunctionType) and name[:1] != "_": bindings.bind(name, func) - num = num + 1 + num += 1 trace("Configuration Extension code loaded", num, "events") # Load the idle extensions for subsection in subsections: @@ -218,7 +218,7 @@ def configure(self, editor, subsections=None): for subsection in subsections: keymap = subsection_keymap.get(subsection, {}) bindings.update_keymap(keymap) - num_bound = num_bound + len(keymap) + num_bound += len(keymap) trace("Configuration bound", num_bound, "keys") def get_key_binding(self, event, subsections=None): @@ -250,7 +250,7 @@ def report_warning(self, msg): def _readline(self, fp, lineno, bStripComments=1): line = fp.readline() - lineno = lineno + 1 + lineno += 1 if line: bBreak = ( get_section_header(line)[0] is not None diff --git a/Pythonwin/pywin/scintilla/configui.py b/Pythonwin/pywin/scintilla/configui.py index 2a47a0e0da..9da2fbf75e 100644 --- a/Pythonwin/pywin/scintilla/configui.py +++ b/Pythonwin/pywin/scintilla/configui.py @@ -230,7 +230,7 @@ def UpdateUIForStyle(self, style): if format[4] == c[1]: # print("Style", style.name, "is", c[0]) break - sel = sel + 1 + sel += 1 else: sel = -1 self.cbo.SetCurSel(sel) diff --git a/Pythonwin/pywin/scintilla/control.py b/Pythonwin/pywin/scintilla/control.py index 5430e65d35..18984b9c29 100644 --- a/Pythonwin/pywin/scintilla/control.py +++ b/Pythonwin/pywin/scintilla/control.py @@ -26,7 +26,7 @@ ) except ( win32api.error - ): # Not there - we dont _need_ a debug ver, so ignore this error. + ): # Not there - we don't _need_ a debug ver, so ignore this error. pass if dllid is None: try: @@ -36,7 +36,7 @@ except win32api.error: pass if dllid is None: - # Still not there - lets see if Windows can find it by searching? + # Still not there - let's see if Windows can find it by searching? dllid = win32api.LoadLibrary("Scintilla.DLL") null_byte = b"\0" @@ -514,7 +514,7 @@ def GetFirstVisibleLine(self): def SetWordWrap(self, mode): if mode != win32ui.CRichEditView_WrapNone: - raise ValueError("We dont support word-wrap (I dont think :-)") + raise ValueError("We don't support word-wrap (I don't think :-)") class CScintillaColorEditInterface(CScintillaEditInterface): diff --git a/Pythonwin/pywin/scintilla/document.py b/Pythonwin/pywin/scintilla/document.py index bf0a2f03be..fca20f0607 100644 --- a/Pythonwin/pywin/scintilla/document.py +++ b/Pythonwin/pywin/scintilla/document.py @@ -151,7 +151,7 @@ def _LoadTextFromFile(self, f): if view.IsWindow(): # Turn off undo collection while loading view.SendScintilla(scintillacon.SCI_SETUNDOCOLLECTION, 0, 0) - # Make sure the control isnt read-only + # Make sure the control isn't read-only view.SetReadOnly(0) view.SendScintilla(scintillacon.SCI_CLEARALL) view.SendMessage(scintillacon.SCI_ADDTEXT, text) @@ -240,7 +240,7 @@ def MarkerAdd(self, lineNo, marker): def MarkerCheck(self, lineNo, marker): v = self.GetEditorView() - lineNo = lineNo - 1 # Make 0 based + lineNo -= 1 # Make 0 based markerState = v.SCIMarkerGet(lineNo) return markerState & (1 << marker) != 0 diff --git a/Pythonwin/pywin/scintilla/find.py b/Pythonwin/pywin/scintilla/find.py index b7b5a81c61..796fd291c7 100644 --- a/Pythonwin/pywin/scintilla/find.py +++ b/Pythonwin/pywin/scintilla/find.py @@ -27,7 +27,7 @@ def __init__(self, other=None): else: self.__dict__.update(other.__dict__) - # Helper so we cant misspell attributes :-) + # Helper so we can't misspell attributes :-) def __setattr__(self, attr, val): if not hasattr(self, attr): raise AttributeError(attr) @@ -84,9 +84,9 @@ def _FindIt(control, searchParams): # Move to the next char, so we find the next one. flags = 0 if searchParams.matchWords: - flags = flags | win32con.FR_WHOLEWORD + flags |= win32con.FR_WHOLEWORD if searchParams.matchCase: - flags = flags | win32con.FR_MATCHCASE + flags |= win32con.FR_MATCHCASE if searchParams.sel == (-1, -1): sel = control.GetSel() # If the position is the same as we found last time, @@ -119,7 +119,7 @@ def _FindIt(control, searchParams): try: doc = control.GetParent().GetDocument() except AttributeError: - print("Cant find a document for the control!") + print("Can't find a document for the control!") doc = None if doc is not None: template = doc.GetDocTemplate() @@ -500,7 +500,7 @@ def OnReplaceAll(self, id, code): num = 1 lastSearch.replaceText = self.editReplaceText.GetWindowText() while _ReplaceIt(control) == FOUND_NORMAL: - num = num + 1 + num += 1 win32ui.SetStatusText("Replaced %d occurrences" % num) if num > 0 and not self.butKeepDialogOpen.GetCheck(): diff --git a/Pythonwin/pywin/scintilla/formatter.py b/Pythonwin/pywin/scintilla/formatter.py index b8aad0b130..6e3459dcc9 100644 --- a/Pythonwin/pywin/scintilla/formatter.py +++ b/Pythonwin/pywin/scintilla/formatter.py @@ -99,7 +99,7 @@ def GetStringStyle(self, pos): try: style = self.styles_by_id[self.scintilla.SCIGetStyleAt(pos)] except KeyError: - # A style we dont know about - probably not even a .py file - can't be a string + # A style we don't know about - probably not even a .py file - can't be a string return None if style.name in self.string_style_names: return style @@ -238,7 +238,7 @@ def SavePreference(self, name, value): class Formatter(FormatterBase): def __init__(self, scintilla): self.bCompleteWhileIdle = 0 - self.bHaveIdleHandler = 0 # Dont currently have an idle handle + self.bHaveIdleHandler = 0 # Don't currently have an idle handle self.nextstylenum = 0 FormatterBase.__init__(self, scintilla) @@ -265,18 +265,18 @@ def OnStyleNeeded(self, std, extra): self.Colorize(endStyled, notify.position) def ColorSeg(self, start, end, styleName): - end = end + 1 + end += 1 # assert end-start>=0, "Can't have negative styling" stylenum = self.styles[styleName].stylenum while start < end: self.style_buffer[start] = stylenum - start = start + 1 + start += 1 # self.scintilla.SCISetStyling(end - start + 1, stylenum) def RegisterStyle(self, style, stylenum=None): if stylenum is None: stylenum = self.nextstylenum - self.nextstylenum = self.nextstylenum + 1 + self.nextstylenum += 1 FormatterBase.RegisterStyle(self, style, stylenum) def ColorizeString(self, str, styleStart): @@ -519,7 +519,7 @@ def ColorizePythonCode(self, cdoc, charStart, styleStart): startSeg = i state = STYLE_COMMENT if chNext == '"' and chNext2 == '"': - i = i + 2 + i += 2 state = STYLE_TQDSTRING ch = " " chPrev = " " @@ -533,7 +533,7 @@ def ColorizePythonCode(self, cdoc, charStart, styleStart): startSeg = i state = STYLE_COMMENT if chNext == "'" and chNext2 == "'": - i = i + 2 + i += 2 state = STYLE_TQSSTRING ch = " " chPrev = " " @@ -558,7 +558,7 @@ def ColorizePythonCode(self, cdoc, charStart, styleStart): state = STYLE_COMMENT elif ch == '"': if chNext == '"' and chNext2 == '"': - i = i + 2 + i += 2 state = STYLE_TQDSTRING ch = " " chPrev = " " @@ -569,7 +569,7 @@ def ColorizePythonCode(self, cdoc, charStart, styleStart): state = STYLE_STRING elif ch == "'": if chNext == "'" and chNext2 == "'": - i = i + 2 + i += 2 state = STYLE_TQSSTRING ch = " " chPrev = " " @@ -589,7 +589,7 @@ def ColorizePythonCode(self, cdoc, charStart, styleStart): elif state == STYLE_STRING: if ch == "\\": if chNext == '"' or chNext == "'" or chNext == "\\": - i = i + 1 + i += 1 ch = chNext chNext = " " if i + 1 < lengthDoc: @@ -601,7 +601,7 @@ def ColorizePythonCode(self, cdoc, charStart, styleStart): elif state == STYLE_SQSTRING: if ch == "\\": if chNext == '"' or chNext == "'" or chNext == "\\": - i = i + 1 + i += 1 ch = chNext chNext = " " if i + 1 < lengthDoc: @@ -628,7 +628,7 @@ def ColorizePythonCode(self, cdoc, charStart, styleStart): chPrev3 = chPrev2 chPrev2 = chPrev chPrev = ch - i = i + 1 + i += 1 if startSeg < lengthDoc: if state == STYLE_KEYWORD: self.ClassifyWord(cdoc, startSeg, lengthDoc - 1, prevWord) @@ -668,7 +668,7 @@ def RegisterStyle(self, style, stylenum=None): assert style.stylenum is None, "Style has already been registered" if stylenum is None: stylenum = self.nextstylenum - self.nextstylenum = self.nextstylenum + 1 + self.nextstylenum += 1 assert self.styles.get(stylenum) is None, "We are reusing a style number!" style.stylenum = stylenum self.styles[style.name] = style diff --git a/Pythonwin/pywin/scintilla/keycodes.py b/Pythonwin/pywin/scintilla/keycodes.py index fa896991a2..d94ccda474 100644 --- a/Pythonwin/pywin/scintilla/keycodes.py +++ b/Pythonwin/pywin/scintilla/keycodes.py @@ -70,7 +70,7 @@ def get_vk(chardesc): def parse_key_name(name): - name = name + "-" # Add a sentinal + name += "-" # Add a sentinal start = pos = 0 max = len(name) toks = [] @@ -121,7 +121,7 @@ def make_key_name(vk, flags): for name, checkflag in moddata: if flags & checkflag: parts.append(name) - flags_done = flags_done & checkflag + flags_done &= checkflag break if flags_done & flags: parts.append(hex(flags & ~flags_done)) diff --git a/Pythonwin/pywin/scintilla/view.py b/Pythonwin/pywin/scintilla/view.py index 6146c20cdb..8dca7de138 100644 --- a/Pythonwin/pywin/scintilla/view.py +++ b/Pythonwin/pywin/scintilla/view.py @@ -130,7 +130,7 @@ def _get_class_attributes(ob): # Recurse into base classes looking for attributes items = [] try: - items = items + dir(ob) + items.extend(dir(ob)) for i in ob.__bases__: for item in _get_class_attributes(i): if item not in items: @@ -272,7 +272,7 @@ def OnWinIniChange(self, section=None): self.bindings.complete_configure() def DoConfigChange(self): - # Bit of a hack I dont kow what to do about - these should be "editor options" + # Bit of a hack I don't kow what to do about - these should be "editor options" from pywin.framework.editor import GetEditorOption self.bAutoCompleteAttributes = GetEditorOption("Autocomplete Attributes", 1) @@ -295,7 +295,7 @@ def OnDestroy(self, msg): def OnMouseWheel(self, msg): zDelta = msg[2] >> 16 vpos = self.GetScrollPos(win32con.SB_VERT) - vpos = vpos - zDelta / 40 # 3 lines per notch + vpos -= zDelta / 40 # 3 lines per notch self.SetScrollPos(win32con.SB_VERT, vpos) self.SendScintilla( win32con.WM_VSCROLL, (vpos << 16) | win32con.SB_THUMBPOSITION, 0 @@ -322,7 +322,7 @@ def EnsureCharsVisible(self, start, end=None): lineEnd = self.LineFromChar(max(start, end)) while lineStart <= lineEnd: self.SCIEnsureVisible(lineStart) - lineStart = lineStart + 1 + lineStart += 1 # Helper to add an event to a menu. def AppendMenu(self, menu, text="", event=None, flags=None, checked=0): @@ -339,11 +339,11 @@ def AppendMenu(self, menu, text="", event=None, flags=None, checked=0): return keyname = configManager.get_key_binding(event, self._GetSubConfigNames()) if keyname is not None: - text = text + "\t" + keyname + text += "\t" + keyname if flags is None: flags = win32con.MF_STRING | win32con.MF_ENABLED if checked: - flags = flags | win32con.MF_CHECKED + flags |= win32con.MF_CHECKED menu.AppendMenu(flags, cmdid, text) def OnKeyDown(self, msg): @@ -489,7 +489,7 @@ def list2dict(l): pass # object has no __dict__ if hasattr(ob, "__class__"): items_dict.update(list2dict(_get_class_attributes(ob.__class__))) - # The object may be a COM object with typelib support - lets see if we can get its props. + # The object may be a COM object with typelib support - let's see if we can get its props. # (contributed by Stefan Migowsky) try: # Get the automation attributes @@ -500,7 +500,7 @@ def list2dict(l): # append to the already evaluated list except AttributeError: pass - # The object might be a pure COM dynamic dispatch with typelib support - lets see if we can get its props. + # The object might be a pure COM dynamic dispatch with typelib support - let's see if we can get its props. if hasattr(ob, "_oleobj_"): try: for iTI in range(0, ob._oleobj_.GetTypeInfoCount()): @@ -673,20 +673,20 @@ def _GetWordSplit(self, pos=-1, bAllowCalls=0): index = pos - 1 wordbreaks_use = wordbreaks if bAllowCalls: - wordbreaks_use = wordbreaks_use + "()[]" + wordbreaks_use += "()[]" while index >= 0: char = self.SCIGetCharAt(index) if char not in wordbreaks_use: break before.insert(0, char) - index = index - 1 + index -= 1 index = pos while index <= limit: char = self.SCIGetCharAt(index) if char not in wordbreaks_use: break after.append(char) - index = index + 1 + index += 1 return "".join(before), "".join(after) def OnPrepareDC(self, dc, pInfo): @@ -714,7 +714,7 @@ def OnPrepareDC(self, dc, pInfo): def OnPreparePrinting(self, pInfo): flags = ( win32ui.PD_USEDEVMODECOPIES | win32ui.PD_ALLPAGES | win32ui.PD_NOSELECTION - ) # Dont support printing just a selection. + ) # Don't support printing just a selection. # NOTE: Custom print dialogs are stopping the user's values from coming back :-( # self.prtDlg = PrintDialog(pInfo, PRINTDLGORD, flags) # pInfo.SetPrintDialog(self.prtDlg) @@ -741,11 +741,11 @@ def CalculatePageRanges(self, dc, pInfo): textLen = self.GetTextLength() while pageStart < textLen: pageStart = self.FormatRange(dc, pageStart, textLen, rc, 0) - maxPage = maxPage + 1 + maxPage += 1 self.starts[maxPage] = pageStart # And a sentinal for one page past the end self.starts[maxPage + 1] = textLen - # When actually printing, maxPage doesnt have any effect at this late state. + # When actually printing, maxPage doesn't have any effect at this late state. # but is needed to make the Print Preview work correctly. pInfo.SetMaxPage(maxPage) @@ -801,10 +801,10 @@ def OnPrint(self, dc, pInfo): dc.SetTextAlign(win32con.TA_RIGHT) dc.TextOut(right, 2 * cyChar, pagenum_str) dc.SetTextAlign(win32con.TA_LEFT) - top = top + int((7 * cyChar) / 2) + top += int(7 * cyChar / 2) dc.MoveTo(left, top) dc.LineTo(right, top) - top = top + cyChar + top += cyChar rc = (left, top, right, bottom) nextPageStart = self.FormatRange( dc, self.starts[pageNum], self.starts[pageNum + 1], rc, 1 @@ -813,7 +813,7 @@ def OnPrint(self, dc, pInfo): def LoadConfiguration(): global configManager - # Bit of a hack I dont kow what to do about? + # Bit of a hack I don't kow what to do about? from .config import ConfigManager configName = rc = win32ui.GetProfileVal("Editor", "Keyboard Config", "default") @@ -824,7 +824,7 @@ def LoadConfiguration(): f"Error loading configuration '{configName}'\n\n{configManager.last_error}" ) if configName != "default": - msg = msg + "\n\nThe default configuration will be loaded." + msg += "\n\nThe default configuration will be loaded." bTryDefault = 1 win32ui.MessageBox(msg) if bTryDefault: diff --git a/Pythonwin/pywin/test/test_exe.py b/Pythonwin/pywin/test/test_exe.py index 3063c3eed7..d545bc6365 100644 --- a/Pythonwin/pywin/test/test_exe.py +++ b/Pythonwin/pywin/test/test_exe.py @@ -46,7 +46,7 @@ def setUp(self): dst = os.path.dirname(pythonwinexe_path) + os.sep + pydll if not os.path.isfile(dst): try: - assert os.path.isfile(src) + self.assertTrue(os.path.isfile(src)) print(f"-- symlink {dst!r} -> {src!r}", file=sys.stderr) os.symlink(src, dst) except (OSError, AssertionError) as e: @@ -62,8 +62,8 @@ def test_exe(self): rc = "TIMEOUT" with open(self.tfn) as f: outs = f.read() - assert rc == 0, f"rc is {rc!r}, outs={outs!r}" - assert "Success!" in outs, outs + self.assertEqual(rc, 0, f"outs={outs!r}") + self.assertIn("Success!", outs) print("-- test_exe Ok! --", file=sys.stderr) def tearDown(self): diff --git a/Pythonwin/pywin/test/test_pywin.py b/Pythonwin/pywin/test/test_pywin.py index 63178e2a14..b38d87ec03 100644 --- a/Pythonwin/pywin/test/test_pywin.py +++ b/Pythonwin/pywin/test/test_pywin.py @@ -4,9 +4,7 @@ import argparse import os -import re import sys -import time import traceback import types import unittest @@ -21,8 +19,6 @@ import win32ui from pywin.framework import scriptutils -_clock = time.perf_counter - user_interaction = getattr(__main__, "user_interaction", False) # from all.py maybe file_abs = os.path.abspath(__file__) src_dir = os.path.dirname(file_abs) @@ -76,13 +72,13 @@ def test_1_pydocs_and_finddlg(self): # open a source file some_fn = src_dir + "\\_dbgscript.py" - assert some_fn != file_abs + self.assertNotEqual(some_fn, file_abs) scriptutils.JumpToDocument(some_fn) a = scriptutils.GetActiveFileName() - assert some_fn == a + self.assertEqual(some_fn, a) v = scriptutils.GetActiveEditControl() s = read_file(some_fn, encoding="latin-1", newline="\r\n") - assert s == v.GetTextRange(), "doc encoding not detected" + self.assertEqual(s, v.GetTextRange(), "doc encoding not detected") # open my own source file and check the text content scriptutils.JumpToDocument(__file__) @@ -91,14 +87,14 @@ def test_1_pydocs_and_finddlg(self): f"Hello from test_pydocs() args={sys.argv} {os.getcwd()}" ) v = scriptutils.GetActiveEditControl() - assert file_abs == v.GetDocument().GetPathName() + self.assertEqual(file_abs, v.GetDocument().GetPathName()) t = v.GetTextRange() testpat = "self.app = thisApp" - assert testpat in t + self.assertIn(testpat, t) # Umlauts for encoding test: áéúäöü - assert read_file(__file__, encoding="utf-8", newline="\r\n") == t + self.assertEqual(read_file(__file__, encoding="utf-8", newline="\r\n"), t) v.SetSel(0) - assert v.GetSel() == (0, 0) + self.assertEqual(v.GetSel(), (0, 0)) # raise the Find dialog using the menu and test it import pywin.scintilla.find @@ -111,15 +107,15 @@ def test_1_pydocs_and_finddlg(self): if "&Edit" != es: ix += 1 es = m.GetMenuString(ix, wc.MF_BYPOSITION) - assert "&Edit" == es + self.assertEqual("&Edit", es) editm = m.GetSubMenu(ix) - assert editm.GetMenuItemCount() > 10 + self.assertGreater(editm.GetMenuItemCount(), 10) for i in range(14): s = editm.GetMenuString(i, wc.MF_BYPOSITION) if s.startswith("R&eplace"): break else: - assert 0, "Replace menu entry not found" + raise AssertionError("Replace menu entry not found") replace_id = editm.GetMenuItemID(i) win32gui.PumpWaitingMessages() v.SendMessage(wc.WM_COMMAND, replace_id) @@ -127,7 +123,8 @@ def test_1_pydocs_and_finddlg(self): d.editFindText.SetWindowText(testpat) d.OnFindNext(0, 0) s, e = v.GetSel() - assert e - s == len(testpat) and s > 0 + self.assertEqual(e - s, len(testpat)) + self.assertGreater(s, 0) def test_browseobj(self): """Test object browser""" @@ -148,41 +145,43 @@ def t_Browse(*args): ), mock.patch("pywin.tools.browser.Browse", t_Browse): self.app.OnViewBrowse(0, 0) hl = o.dlg.hier_list - assert len(hl.itemHandleMap) > 10 - assert hl.listControl.GetCount() > 10 + self.assertGreater(len(hl.itemHandleMap), 10) + self.assertGreater(hl.listControl.GetCount(), 10) item = hl.GetSelectedItem() - assert "TestCase" in str(hl.listControl.GetItem(item)) - assert "TestCase" in hl.ItemFromHandle(item).GetText() + self.assertIn("TestCase", str(hl.listControl.GetItem(item))) + self.assertIn("TestCase", hl.ItemFromHandle(item).GetText()) item2 = hl.listControl.GetNextVisibleItem(item) - assert "Runs and tests" in str(hl.listControl.GetItem(item2)) + self.assertIn("Runs and tests", str(hl.listControl.GetItem(item2))) def test_options_propsheet(self): """Check Pythonwin options property sheet""" lres = [] + test = self + def t_DoModal(self): self.CreateWindow() p = self.GetPage(4) # format_page self.SetActivePage(p) p = self.GetPage(4) - assert p._DoButDefaultFont - assert ( # fixed / prop. font radio + test.assertTrue(p._DoButDefaultFont) + test.assertTrue( # fixed / prop. font radio p.GetDlgItem(win32ui.IDC_RADIO1).GetCheck() ^ p.GetDlgItem(win32ui.IDC_RADIO2).GetCheck() ) - assert p.listbox.GetCount() >= 16 # styles list - assert p.GetSelectedStyle().name + test.assertGreaterEqual(p.listbox.GetCount(), 16) # styles list + test.assertTrue(p.GetSelectedStyle().name) lres.append("done") w_obj = weakref.ref(p._obj_) - assert w_obj() + test.assertTrue(w_obj()) self.DestroyWindow() - assert p._obj_ is None - assert self._obj_ is None + test.assertIsNone(p._obj_) + test.assertIsNone(self._obj_) with mock.patch("pywin.mfc.dialog.PropertySheet.DoModal", t_DoModal): self.app.OnViewOptions(0, 0) - assert lres + self.assertTrue(lres) def test_ctrls(self): from pywin.mfc import dialog @@ -213,9 +212,9 @@ def test_ctrls(self): slider.CreateWindow(_cst, (0, 10, 200, 40), d, 100) win32gui.PumpWaitingMessages() mi, ma = slider.GetRange() - assert slider.GetPos() == 0 + self.assertEqual(slider.GetPos(), 0) slider.SetPos(20) - assert slider.GetPos() == 20 + self.assertEqual(slider.GetPos(), 20) # progress pc = win32ui.CreateProgressCtrl() @@ -227,9 +226,9 @@ def test_ctrls(self): # edit edit = win32ui.CreateEdit() edit.CreateWindow(_cst | wc.WS_BORDER, (5, 60, 100, 80), d, 101) - assert d.GetDlgItem(101) is edit + self.assertIs(d.GetDlgItem(101), edit) d.DestroyWindow() - assert d._obj_ is None + self.assertIsNone(d._obj_) def test_dc(self): from pywin.mfc import window @@ -290,8 +289,16 @@ def OnPaint(self): self.addCleanup(lambda: (o.cnt_ondestroy or w.DestroyWindow())) win32gui.PumpWaitingMessages() dc = w.GetDC() - assert o.cnt_onpaint > 0, "".join( - traceback.format_exception(None, o.exc, o.exc.__traceback__) + self.assertGreater( + o.cnt_onpaint, + 0, + ( + "".join( + traceback.format_exception(type(o.exc), o.exc, o.exc.__traceback__) + ) + if hasattr(o, "exc") + else None + ), ) pix = dc.GetPixel(1, 1) bmp = win32ui.CreateBitmap() @@ -300,13 +307,13 @@ def OnPaint(self): dcb.SelectObject(bmp) dcb.BitBlt((0, 0), (30, 30), dc, (0, 0), wc.SRCCOPY) sbits = bmp.GetBitmapBits(0) - assert any(sbits[:4]) + self.assertTrue(any(sbits[:4])) w.ReleaseDC(dc) - assert pix == 255 # red - assert o.cnt_ondestroy == 0 + self.assertEqual(pix, 255, "not red") + self.assertEqual(o.cnt_ondestroy, 0) w.DestroyWindow() - assert o.cnt_ondestroy == 1 + self.assertEqual(o.cnt_ondestroy, 1) def test_ia(self): """Test interactive, run, autocomplete, exec""" @@ -318,8 +325,9 @@ def test_ia(self): scriptutils.JumpToDocument(fn) cmGo = win32ui.IDC_DBG_GO mf.SendMessage(wc.WM_COMMAND, cmGo) - assert __main__.aa == 33 == ia.interp.globals["aa"] - assert __main__.ff() == 132 + self.assertEqual(__main__.aa, 33) + self.assertEqual(ia.interp.globals["aa"], 33) + self.assertEqual(__main__.ff(), 132) # ia auto-indent + auto-complete + exec ia.SetFocus() @@ -329,18 +337,20 @@ def test_ia(self): ia.ProcessEnterEvent(None) ia.ReplaceSel("CC") tail1 = ia.GetTextRange(ia.GetTextLength() - 20) - assert tail1.endswith("... \tCC"), "wrong auto-indent: %r" % tail1 + self.assertTrue(tail1.endswith("... \tCC"), f"wrong auto-indent: {tail1!r}") ia.SendMessage(wc.WM_KEYDOWN, win32api.VkKeyScan(".")) ia.SendMessage(wc.WM_KEYUP, win32api.VkKeyScan(".")) ia.SendMessage(wc.WM_KEYDOWN, wc.VK_TAB) # select 1st entry ia.SendMessage(wc.WM_KEYUP, wc.VK_TAB) tail2 = ia.GetTextRange(ia.GetTextLength() - 20) - assert tail2.endswith("... \tCC.cc"), "wrong auto-complete: %r" % tail2 + self.assertTrue( + tail2.endswith("... \tCC.cc"), f"wrong auto-complete: {tail2!r}" + ) ia.ProcessEnterEvent(None) ia.SendMessage(wc.WM_KEYDOWN, wc.VK_RETURN) ia.SendMessage(wc.WM_KEYUP, wc.VK_RETURN) execd = ia.GetTextRange(ia.GetTextLength() - 20) - assert "\n44" in execd, "wrong result: %r" % execd # CC.cc == 44 + self.assertIn("\n44", execd, "wrong result") # CC.cc == 44 # ia calltip + call exec ia.SetFocus() @@ -350,18 +360,18 @@ def test_ia(self): shift = ss_vk & 0x100 ## N/E win32api.SendInput() t_GKS = lambda key: (key == wc.VK_SHIFT and shift) and 0x8000 or 0 with mock.patch("win32api.GetKeyState", t_GKS): - assert not ia.SCICallTipActive() + self.assertFalse(ia.SCICallTipActive()) ia.SendMessage(wc.WM_KEYDOWN, ss_vk & 0xFF) ia.SendMessage(wc.WM_CHAR, ord("(")) ia.SendMessage(wc.WM_KEYUP, ss_vk & 0xFF) - assert ia.SCICallTipActive() + self.assertTrue(ia.SCICallTipActive()) if ia.GetSel()[1] == ia.GetTextLength(): # no auto close bracket ia.SendMessage(wc.WM_CHAR, ord(")")) ia.GotoEndOfFileEvent(None) ia.SendMessage(wc.WM_KEYDOWN, wc.VK_RETURN) ia.SendMessage(wc.WM_KEYUP, wc.VK_RETURN) execd = ia.GetTextRange(ia.GetTextLength() - 20) - assert "\n132" in execd, execd # ff() == 132 + self.assertIn("\n132", execd) # ff() == 132 def test_docedit(self): import tempfile @@ -370,15 +380,15 @@ def test_docedit(self): ##doc = pywin.framework.editor.editorTemplate.OpenDocumentFile(None) def t_print(*args): - assert "ERROR" not in str(args) # XXX put asserts into that test() - assert 0, "should not print at all" + self.assertNotIn("ERROR", str(args)) # XXX put asserts into that test() + raise AssertionError("should not print at all") with mock.patch("builtins.print", t_print): pywin.scintilla.IDLEenvironment.test() ed = scriptutils.GetActiveEditControl() doc = ed.GetDocument() - assert "hi there" in ed.GetTextRange() - assert doc.IsModified() + self.assertIn("hi there", ed.GetTextRange()) + self.assertTrue(doc.IsModified()) # edit w auto-indent ed.SetWindowText("") @@ -389,7 +399,7 @@ def t_print(*args): ed.SendMessage(wc.WM_KEYDOWN, wc.VK_RETURN) ed.SendMessage(wc.WM_KEYUP, wc.VK_RETURN) s = ed.GetTextRange() - assert re.match(r"(?m)if 1:\r\n[ \t]+CC\r\n[ \t]+\r\n$", s), "no auto-indent" + self.assertRegex(s, r"(?m)if 1:\r\n[ \t]+CC\r\n[ \t]+\r\n$", "no auto-indent") # save doc to temp file fh, tfn = tempfile.mkstemp(suffix=".py", prefix="pywintest-") @@ -397,7 +407,7 @@ def t_print(*args): self.addCleanup(lambda: os.remove(tfn)) doc.OnSaveDocument(tfn) r = read_file(tfn, "rb").decode() - assert s == r + self.assertEqual(s, r) doc.OnCloseDocument() def test_debugger(self): @@ -413,7 +423,7 @@ def test_debugger(self): win32gui.PumpWaitingMessages() src = v.GetTextRange() - assert "aa = 33" in src + self.assertIn("aa = 33", src) def getlno(s): return src[: src.index(s)].count("\n") + 1 @@ -438,10 +448,10 @@ def t_brk(self): "pywin.debugger.debugger.Debugger.GUIAboutToBreak", t_brk ): mf.SendMessage(wc.WM_COMMAND, cmGo) # debh.OnGo(0, 0) - assert not cmds_brk_next, "break commands remaining" - assert obj.brk_linenos[0] == getlno("aa = 22") - assert obj.brk_linenos[1] == getlno("aa = 77") - assert dmod.aa == 22 # aa = 33 not executed / cmClose + self.assertFalse(cmds_brk_next, "break commands remaining") + self.assertEqual(obj.brk_linenos[0], getlno("aa = 22")) + self.assertEqual(obj.brk_linenos[1], getlno("aa = 77")) + self.assertEqual(dmod.aa, 22) # aa = 33 not executed / cmClose if __name__ == "__main__": @@ -451,7 +461,7 @@ def t_brk(self): ##ts = unittest.TestLoader().loadTestsFromTestCase(T) _tests = ts._tests[:] r = ts.debug() - assert teared_down + t.assertTrue(teared_down) print(_tests, "ok!") sys.exit() diff --git a/Pythonwin/pywin/tools/TraceCollector.py b/Pythonwin/pywin/tools/TraceCollector.py index 093ecf133d..97ac75f551 100644 --- a/Pythonwin/pywin/tools/TraceCollector.py +++ b/Pythonwin/pywin/tools/TraceCollector.py @@ -62,7 +62,7 @@ def MakeOutputWindow(): global outputWindow if outputWindow is None: title = "Python Trace Collector" - # queueingFlag doesnt matter, as all output will come from new thread + # queueingFlag doesn't matter, as all output will come from new thread outputWindow = WindowOutput(title, title) # Let people know what this does! msg = """\ diff --git a/Pythonwin/pywin/tools/browseProjects.py b/Pythonwin/pywin/tools/browseProjects.py index d7f5cd4671..e246387b12 100644 --- a/Pythonwin/pywin/tools/browseProjects.py +++ b/Pythonwin/pywin/tools/browseProjects.py @@ -188,7 +188,7 @@ def GetSubList(self): path = win32api.GetFullPathName( os.path.join(self.path, "..\\win32comext") ) - ret = ret + MakePathSubList(path) + ret.extend(MakePathSubList(path)) except win32ui.error: pass return ret @@ -209,7 +209,7 @@ def IsExpandable(self): def GetSubList(self): paths = regutil.GetRegisteredNamedPath(self.projectName) pathList = paths.split(";") - if len(pathList) == 1: # Single dir - dont bother putting the dir in + if len(pathList) == 1: # Single dir - don't bother putting the dir in ret = MakePathSubList(pathList[0]) else: ret = list(map(HLIDirectoryItem, pathList)) @@ -233,7 +233,7 @@ def GetSubList(self): while 1: try: ret.append(HLIProjectRoot(win32api.RegEnumKey(hKey, index))) - index = index + 1 + index += 1 except win32api.error: break return ret diff --git a/Pythonwin/pywin/tools/browser.py b/Pythonwin/pywin/tools/browser.py index 5422b5fb65..b0fd7cab17 100644 --- a/Pythonwin/pywin/tools/browser.py +++ b/Pythonwin/pywin/tools/browser.py @@ -87,7 +87,7 @@ def GetSubList(self): pass try: for name in self.myobject.__methods__: - ret.append(HLIMethod(name)) # no MakeHLI, as cant auto detect + ret.append(HLIMethod(name)) # no MakeHLI, as can't auto detect except (AttributeError, TypeError): pass try: @@ -175,7 +175,7 @@ def GetSubList(self): ret = [] for base in self.myobject.__bases__: ret.append(MakeHLI(base, "Base class: " + base.__name__)) - ret = ret + HLIPythonObject.GetSubList(self) + ret.extend(HLIPythonObject.GetSubList(self)) return ret @@ -224,7 +224,7 @@ def IsExpandable(self): def GetSubList(self): ret = [] ret.append(MakeHLI(self.myobject.__class__)) - ret = ret + HLIPythonObject.GetSubList(self) + ret.extend(HLIPythonObject.GetSubList(self)) return ret @@ -261,7 +261,7 @@ def GetSubList(self): pos = 0 for item in self.myobject: ret.append(MakeHLI(item, "[" + str(pos) + "]")) - pos = pos + 1 + pos += 1 self.InsertDocString(ret) return ret @@ -298,7 +298,7 @@ def GetSubList(self): return ret -# strings and Unicode have builtin methods, but we dont really want to see these +# strings and Unicode have builtin methods, but we don't really want to see these class HLIString(HLIPythonObject): def IsExpandable(self): return 0 @@ -327,7 +327,7 @@ def MakeHLI(ob, name=None): cls = TypeMap[type(ob)] except KeyError: # hrmph - this check gets more and more bogus as Python - # improves. Its possible we should just *always* use + # improves. It's possible we should just *always* use # HLIInstance? if hasattr(ob, "__class__"): # 'new style' class cls = HLIInstance diff --git a/Pythonwin/pywin/tools/hierlist.py b/Pythonwin/pywin/tools/hierlist.py index ebf3e93c4c..bfe08da4f8 100644 --- a/Pythonwin/pywin/tools/hierlist.py +++ b/Pythonwin/pywin/tools/hierlist.py @@ -119,7 +119,7 @@ def DeleteAllItems(self): self.filledItemHandlesMap = {} def HierTerm(self): - # Dont want notifies as we kill the list. + # Don't want notifies as we kill the list. parent = self.notify_parent # GetParentFrame() parent.HookNotify(None, commctrl.TVN_ITEMEXPANDINGW) parent.HookNotify(None, commctrl.TVN_SELCHANGEDW) @@ -215,7 +215,7 @@ def Refresh(self, hparent=None): if old_items[iold] == new_items[inewlook]: matched = 1 break - inewlook = inewlook + 1 + inewlook += 1 if matched: # Insert the new items. # print("Inserting after", old_items[iold], old_handles[iold]) diff --git a/Pythonwin/pywin/tools/regedit.py b/Pythonwin/pywin/tools/regedit.py index e05224a6c0..70a6aaac79 100644 --- a/Pythonwin/pywin/tools/regedit.py +++ b/Pythonwin/pywin/tools/regedit.py @@ -197,7 +197,7 @@ def UpdateForRegItem(self, item): name = "(Default)" self.InsertItem(valNum, name) self.SetItemText(valNum, 1, str(res[1])) - valNum = valNum + 1 + valNum += 1 finally: win32api.RegCloseKey(hkey) @@ -216,7 +216,7 @@ def OnInitDialog(self): style = win32api.GetWindowLong( self.edit.GetSafeHwnd(), win32con.GWL_STYLE ) - style = style & (~win32con.ES_WANTRETURN) + style &= ~win32con.ES_WANTRETURN win32api.SetWindowLong( self.edit.GetSafeHwnd(), win32con.GWL_STYLE, style ) @@ -362,7 +362,7 @@ def GetSubList(self): except win32api.error: break ret.append(HLIRegistryKey(self.keyRoot, self.keyName + "\\" + key, key)) - keyNum = keyNum + 1 + keyNum += 1 finally: win32api.RegCloseKey(hkey) win32ui.DoWaitCursor(0) diff --git a/Pythonwin/stdafx.h b/Pythonwin/stdafx.h index 320ac2efd7..b8d9811e01 100644 --- a/Pythonwin/stdafx.h +++ b/Pythonwin/stdafx.h @@ -29,7 +29,7 @@ // allow memory leaks to give me the line number. // #define new DEBUG_NEW -/* dont really need to undef these anymore, but helpful to +/* don't really need to undef these anymore, but helpful to programmers who forget to use the new names. */ #undef INCREF #undef DECREF @@ -42,7 +42,7 @@ programmers who forget to use the new names. */ #include "import.h" // Python: for dynamicattach routines. #include "pywintypes.h" -// dont need all of these for all, but it cant hurt (and keep the speed up!) +// don't need all of these for all, but it can't hurt (and keep the speed up!) #include "win32ui.h" diff --git a/Pythonwin/stdafxole.h b/Pythonwin/stdafxole.h index ce94bb6549..1731eb138a 100644 --- a/Pythonwin/stdafxole.h +++ b/Pythonwin/stdafxole.h @@ -19,7 +19,7 @@ #include "limits.h" // allow memory leaks to give me the line number. -//#define new DEBUG_NEW +// #define new DEBUG_NEW // windows defines "small" as "char" which breaks Python's accu.h #undef small @@ -28,7 +28,7 @@ #include "traceback.h" #include "pythonrun.h" -// dont need all of these for all, but it cant hurt (and keep the speed up!) +// don't need all of these for all, but it can't hurt (and keep the speed up!) #include "pywintypes.h" #include "win32ui.h" diff --git a/Pythonwin/stddde.cpp b/Pythonwin/stddde.cpp index 74bb181753..19d82d30c9 100644 --- a/Pythonwin/stddde.cpp +++ b/Pythonwin/stddde.cpp @@ -476,9 +476,9 @@ BOOL CDDEConv::Request(UINT wFmt, const TCHAR *pszItem, CString &ret) BYTE *pData = ::DdeAccessData(hData, &dwSize); DWORD nChars = (dwSize / sizeof(TCHAR)) - 1; - if(wFmt == CF_TEXT) { + if (wFmt == CF_TEXT) { nChars = (dwSize / sizeof(CHAR)) - 1; - ret = CString((CHAR*)pData, nChars); + ret = CString((CHAR *)pData, nChars); } else { ret = CString((TCHAR *)pData, nChars); @@ -1431,7 +1431,7 @@ BOOL CDDEServer::DoCallback(WORD wType, WORD wFmt, HCONV hConv, HSZ hszTopic, HS if (!b) { // // Nobody took the data. - // Maybe its not a supported item or format + // Maybe it's not a supported item or format // Status(_T("Poke %s|%s failed"), (const TCHAR *)strTopic, (const TCHAR *)strItem); @@ -1473,7 +1473,7 @@ BOOL CDDEServer::DoCallback(WORD wType, WORD wFmt, HCONV hConv, HSZ hszTopic, HS if (!b) { // // Nobody took the data. - // Maybe its not of interrest + // Maybe it's not of interrest // Status(_T("AdviseData %s|%s failed"), (const TCHAR *)strTopic, (const TCHAR *)strItem); diff --git a/Pythonwin/win32RichEdit.cpp b/Pythonwin/win32RichEdit.cpp index bac553d20f..ac1f17ef68 100644 --- a/Pythonwin/win32RichEdit.cpp +++ b/Pythonwin/win32RichEdit.cpp @@ -199,7 +199,7 @@ static PyObject *PyCRichEditView_save_text_file(PyObject *self, PyObject *args) size += size; // try doubling! } if (bytesCopied == size) // hit max. - --bytesCopied; // so NULL doesnt overshoot. + --bytesCopied; // so NULL doesn't overshoot. buf[bytesCopied] = 0; if (i < lineCount - 1) fwrite(buf, sizeof(TCHAR), bytesCopied, f); diff --git a/Pythonwin/win32app.cpp b/Pythonwin/win32app.cpp index 8b87bd3866..c6a4880ffe 100644 --- a/Pythonwin/win32app.cpp +++ b/Pythonwin/win32app.cpp @@ -103,13 +103,9 @@ extern BOOL bDebuggerPumpStopRequested; // Application object // ////////////////////////////////////////////////////////////////////// -PyCWinApp::PyCWinApp() -{ -} +PyCWinApp::PyCWinApp() {} -PyCWinApp::~PyCWinApp() -{ -} +PyCWinApp::~PyCWinApp() {} // @pymethod |PyCWinApp|AddDocTemplate|Adds a template to the application list. static PyObject *ui_app_add_doc_template(PyObject *self, PyObject *args) @@ -401,7 +397,4 @@ static struct PyMethodDef PyCWinApp_methods[] = { ui_type_CObject PyCWinApp::type("PyCWinApp", &PyCWinThread::type, RUNTIME_CLASS(CWinApp), sizeof(PyCWinApp), PYOBJ_OFFSET(PyCWinApp), PyCWinApp_methods, GET_PY_CTOR(PyCWinApp)); -void PyCWinApp::cleanup() -{ - PyCWinThread::cleanup(); -} +void PyCWinApp::cleanup() { PyCWinThread::cleanup(); } diff --git a/Pythonwin/win32assoc.cpp b/Pythonwin/win32assoc.cpp index b517fbd619..a228821a5c 100644 --- a/Pythonwin/win32assoc.cpp +++ b/Pythonwin/win32assoc.cpp @@ -40,7 +40,7 @@ CAssocManager::~CAssocManager() #ifdef _DEBUG TCHAR buf[256]; if (cacheLookups) { - // cant use TRACE, as CWinApp may no longer be valid. + // can't use TRACE, as CWinApp may no longer be valid. wsprintf(buf, _T("AssocManager cache hit ratio is %d percent\n"), cacheHits * 100 / cacheLookups); OutputDebugString(buf); } @@ -74,7 +74,7 @@ void CAssocManager::RemoveAssoc(void *handle) map.RemoveKey(handle); if (ob != Py_None) // The object isn't necessarily dead (ie, its refcount may - // not be about to hit zero), but its 'dead' from our POV, so + // not be about to hit zero), but it's 'dead' from our POV, so // let it free any MFC etc resources the object owns. // XXX - this kinda sucks - just relying on the object // destructor *should* be OK... @@ -127,7 +127,7 @@ ui_assoc_object *CAssocManager::GetAssocObject(void *handle) cacheLookups++; #endif // implement a basic 1 item cache. - // XXX - ::Assoc above means a cached "no object" might be incorrect? + // XXX - ::Assoc above means a cached "no object" might be incorrect? if (lastLookup == handle) { weakref = lastObjectWeakRef; #ifdef _DEBUG @@ -201,11 +201,11 @@ bool ui_assoc_CObject::CheckCppObject(ui_type *ui_type_check) const return false; CObject *pObj = (CObject *)assoc; // Assert triggers occasionally for brand new window objects - - // Removing this ASSERT cant hurt too much (as I have never seen it + // Removing this ASSERT can't hurt too much (as I have never seen it // fire legitimately // ASSERT_VALID(pObj); // NULL has already been handled before now. if (ui_type_check == NULL) - return true; // Cant check anything! + return true; // Can't check anything! ui_type_CObject *pTyp = (ui_type_CObject *)ui_type_check; if (pTyp->pCObjectClass == NULL) { diff --git a/Pythonwin/win32assoc.h b/Pythonwin/win32assoc.h index fcca61d94e..7b94a49de4 100644 --- a/Pythonwin/win32assoc.h +++ b/Pythonwin/win32assoc.h @@ -3,7 +3,7 @@ // #pragma once // afxmt.h is often not included by default in stdafx.h -// Try and include it here - it wont hurt if stfafx.h has already done it! +// Try and include it here - it won't hurt if stfafx.h has already done it! #include // CCriticalSection, etc // Handle Manager maps between pointers of some sort, and an associated @@ -43,7 +43,7 @@ class CAssocManager // ui_assoc_object // class PYW_EXPORT ui_assoc_object : public ui_base_class { - public: // some probably shouldnt be, but... + public: // some probably shouldn't be, but... PyObject *GetGoodRet(); static ui_assoc_object *make(ui_type &makeType, void *search, bool skipLookup = false); diff --git a/Pythonwin/win32bitmap.cpp b/Pythonwin/win32bitmap.cpp index 31e9890ff8..157457063f 100644 --- a/Pythonwin/win32bitmap.cpp +++ b/Pythonwin/win32bitmap.cpp @@ -195,7 +195,7 @@ PyObject *ui_bitmap_load_bitmap_file(PyObject *self, PyObject *args) } BITMAPFILEHEADER bmFileHeader; memcpy(&bmFileHeader, PyBytes_AsString(result), len); - Py_DECREF(result); // dont need this anymore + Py_DECREF(result); // don't need this anymore if (bmFileHeader.bfType != DIB_HEADER_MARKER) { Py_DECREF(reader); PyErr_SetString(PyExc_TypeError, "File is not a DIB format file"); @@ -242,7 +242,7 @@ PyObject *ui_bitmap_load_bitmap_file(PyObject *self, PyObject *args) char *pBits = new char[len]; // XXX - need memory exception handler. memcpy(pBits, PyBytes_AsString(result), len); - Py_DECREF(result); // dont need this. + Py_DECREF(result); // don't need this. Py_DECREF(reader); // or this. // kill old palette @@ -335,7 +335,7 @@ PyObject *ui_bitmap_load_ppm_file(PyObject *self, PyObject *args) pMem[col + 2] = pImg[col]; } - Py_DECREF(result); // dont need this. + Py_DECREF(result); // don't need this. Py_DECREF(reader); // or this. // delete old palette - none for this format diff --git a/Pythonwin/win32cmd.h b/Pythonwin/win32cmd.h index 698c5f7874..33e0dd7c45 100644 --- a/Pythonwin/win32cmd.h +++ b/Pythonwin/win32cmd.h @@ -8,7 +8,7 @@ class PYW_EXPORT PyCCmdTarget : public ui_assoc_CObject { friend CVirtualHelper::CVirtualHelper(const char *iname, void *iassoc, EnumVirtualErrorHandling veh); - public: // some probably shouldnt be, but... + public: // some probably shouldn't be, but... CMapWordToPtr *pNotifyHookList; CMapWordToPtr *pCommandHookList; CMapWordToPtr *pOleEventHookList; diff --git a/Pythonwin/win32cmdui.cpp b/Pythonwin/win32cmdui.cpp index a52a456129..617c8e5f62 100644 --- a/Pythonwin/win32cmdui.cpp +++ b/Pythonwin/win32cmdui.cpp @@ -27,18 +27,18 @@ inline void *GetPythonOleProcAddress(const char *procName) #endif hMod = GetModuleHandle(buf); -// XXX It is unclear why the code previously tried to identify a loaded PythonCOM DLL of -// any Python version 1.5 .. 3.9. If some InprocServer would load the DLL of a different -// Python version that would likely cause a crash. Thus deactivated. -// -// for (int i = 0; hMod == NULL && i < 40; i++) { -// #ifdef _DEBUG -// wsprintf(buf, _T("PythonCOM3%d_d.dll"), i); -// #else -// wsprintf(buf, _T("PythonCOM3%d.dll"), i); -// #endif -// hMod = GetModuleHandle(buf); -// } + // XXX It is unclear why the code previously tried to identify a loaded PythonCOM DLL of + // any Python version 1.5 .. 3.9. If some InprocServer would load the DLL of a different + // Python version that would likely cause a crash. Thus deactivated. + // + // for (int i = 0; hMod == NULL && i < 40; i++) { + // #ifdef _DEBUG + // wsprintf(buf, _T("PythonCOM3%d_d.dll"), i); + // #else + // wsprintf(buf, _T("PythonCOM3%d.dll"), i); + // #endif + // hMod = GetModuleHandle(buf); + // } if (hMod) { void *rc = GetProcAddress(hMod, procName); @@ -143,7 +143,7 @@ BOOL Python_OnCmdMsg(CCmdTarget *obj, UINT nID, int nCode, void *pExtra, AFX_CMD // user interface element. Enable the element. pUI->Enable(); rc = TRUE; // did handle it. - } // else RC remains FALSE. + } // else RC remains FALSE. } else { // is the command itself. // allow either a general or specific handler to be called diff --git a/Pythonwin/win32control.cpp b/Pythonwin/win32control.cpp index 78631f43f9..45aff22582 100644 --- a/Pythonwin/win32control.cpp +++ b/Pythonwin/win32control.cpp @@ -1051,7 +1051,7 @@ static PyObject *PyCComboBox_get_lb_text(PyObject *self, PyObject *args) if (!PyArg_ParseTuple(args, "i", &pos)) return NULL; CString cs; - // Prevent MFC ASSERTing when empty - dont use the CString version. + // Prevent MFC ASSERTing when empty - don't use the CString version. GUI_BGN_SAVE; int size = pLB->GetLBTextLen(pos); if (size != LB_ERR) { diff --git a/Pythonwin/win32control.h b/Pythonwin/win32control.h index 7be5bd1584..cbb6e2134c 100644 --- a/Pythonwin/win32control.h +++ b/Pythonwin/win32control.h @@ -8,7 +8,8 @@ class PYW_EXPORT PyCCtrlView_Type : public ui_type_CObject { public: PyCCtrlView_Type(const char *name, ui_type *pBaseType, ui_type_CObject *pControlType, CRuntimeClass *rtClass, - Py_ssize_t typeSize, ptrdiff_t pyobjOffset, struct PyMethodDef *methodList, ui_base_class *(*thector)()); + Py_ssize_t typeSize, ptrdiff_t pyobjOffset, struct PyMethodDef *methodList, + ui_base_class *(*thector)()); public: ui_type_CObject *control; diff --git a/Pythonwin/win32ctledit.cpp b/Pythonwin/win32ctledit.cpp index e55715f5af..44c2f40fd2 100644 --- a/Pythonwin/win32ctledit.cpp +++ b/Pythonwin/win32ctledit.cpp @@ -368,7 +368,7 @@ static PyObject *PyCEdit_get_line(PyObject *self, PyObject *args) TRACE0("Doubling buffer for GetLine value\n"); } if (bytesCopied == size) // hit max. - --bytesCopied; // so NULL doesnt overshoot. + --bytesCopied; // so NULL doesn't overshoot. if (buf[bytesCopied - 1] == '\r' || buf[bytesCopied - 1] == '\n') // kill newlines. --bytesCopied; buf[bytesCopied] = '\0'; diff --git a/Pythonwin/win32ctrlRichEdit.cpp b/Pythonwin/win32ctrlRichEdit.cpp index 611d4497d9..8d921e1e99 100644 --- a/Pythonwin/win32ctrlRichEdit.cpp +++ b/Pythonwin/win32ctrlRichEdit.cpp @@ -436,7 +436,7 @@ static PyObject *PyCRichEditCtrl_get_line(PyObject *self, PyObject *args) TRACE0("Doubling buffer for GetLine value\n"); } if (bytesCopied == size) // hit max. - --bytesCopied; // so NULL doesnt overshoot. + --bytesCopied; // so NULL doesn't overshoot. // if (buf[bytesCopied-1]=='\r' || buf[bytesCopied-1]=='\n') // kill newlines. // --bytesCopied; buf[bytesCopied] = '\0'; diff --git a/Pythonwin/win32dc.cpp b/Pythonwin/win32dc.cpp index 794aa82803..1e3015dc63 100644 --- a/Pythonwin/win32dc.cpp +++ b/Pythonwin/win32dc.cpp @@ -106,7 +106,7 @@ CDC *ui_dc_object::GetDC(PyObject *self) { return (CDC *)GetGoodCppObject(self, void ui_dc_object::SetAssocInvalid() { - return; // do nothing. Dont call base as dont want my handle wiped. + return; // do nothing. Don't call base as don't want my handle wiped. } ui_dc_object::~ui_dc_object() diff --git a/Pythonwin/win32dlg.cpp b/Pythonwin/win32dlg.cpp index e2a5dc79fd..598aae410b 100644 --- a/Pythonwin/win32dlg.cpp +++ b/Pythonwin/win32dlg.cpp @@ -403,7 +403,7 @@ void Python_do_exchange(CDialog *pDlg, CDataExchange *pDX) PyCDialog *dob = (PyCDialog *)ui_assoc_object::GetAssocObject(pDlg); if (!dob) { TRACE("do_exchange called on dialog with no Python object!\n"); - return; // dont print an exception + return; // don't print an exception } for (int i = 0; i < PyList_Size(dob->ddlist); i++) { PyObject *ob = PyList_GetItem(dob->ddlist, i); @@ -569,7 +569,7 @@ static PyObject *ui_dialog_do_modal(PyObject *self, PyObject *args) RETURN_ERR("InitModalIndirect failed"); } - Py_INCREF(self); // make sure Python doesnt kill the object while in a modal call. + Py_INCREF(self); // make sure Python doesn't kill the object while in a modal call. // really only for the common dialog, and other non CPythonDlg's INT_PTR ret; GUI_BGN_SAVE; @@ -737,7 +737,7 @@ ui_type_CObject PyCDialog::type("PyCDialog", static struct PyMethodDef ui_common_dialog_methods[] = {{NULL, NULL}}; ui_type_CObject PyCCommonDialog::type("PyCCommonDialog", &PyCDialog::type, - NULL, // CCommonDialog doesnt have RTTI??? + NULL, // CCommonDialog doesn't have RTTI??? sizeof(PyCCommonDialog), PYOBJ_OFFSET(PyCCommonDialog), ui_common_dialog_methods, NULL); @@ -1058,7 +1058,7 @@ PyObject *PyCFontDialog::ui_font_dialog_create(PyObject * /*self*/, PyObject *ar GUI_BGN_SAVE; \ int ret = pDlg->mfcName(); \ GUI_END_SAVE; \ - return PyLong_FromLong(ret); \ + return PyLong_FromLong(ret); \ } #define MAKE_INT_PTR_METH(fnname, mfcName) \ diff --git a/Pythonwin/win32dlg.h b/Pythonwin/win32dlg.h index da94fbb031..2d79ab8eee 100644 --- a/Pythonwin/win32dlg.h +++ b/Pythonwin/win32dlg.h @@ -1,6 +1,6 @@ // dialog objects -// hack the associations a bit. When the dialog window closes, I dont +// hack the associations a bit. When the dialog window closes, I don't // destroy the association. ///////////////////////////////////////////////////////// diff --git a/Pythonwin/win32doc.cpp b/Pythonwin/win32doc.cpp index 21f91da6ab..431ccad8f3 100644 --- a/Pythonwin/win32doc.cpp +++ b/Pythonwin/win32doc.cpp @@ -104,7 +104,7 @@ PyObject *ui_doc_get_first_view(PyObject *self, PyObject *args) GUI_END_SAVE; // @comm For more info, see - ASSERT(pWnd); // shouldnt be possible. + ASSERT(pWnd); // shouldn't be possible. return ui_assoc_object::make(UITypeFromCObject(pWnd), pWnd)->GetGoodRet(); } @@ -123,7 +123,7 @@ PyObject *ui_doc_get_all_views(PyObject *self, PyObject *args) GUI_BGN_SAVE; CView *pWnd = pDoc->GetNextView(pos); // @pyseemfc CDocument|GetNextView GUI_END_SAVE; - ASSERT(pWnd); // shouldnt be possible. + ASSERT(pWnd); // shouldn't be possible. if (pWnd == NULL) { Py_DECREF(retList); RETURN_ERR("No view was available!"); diff --git a/Pythonwin/win32gdi.cpp b/Pythonwin/win32gdi.cpp index 64a6fbafdf..3b012cf6dc 100644 --- a/Pythonwin/win32gdi.cpp +++ b/Pythonwin/win32gdi.cpp @@ -33,7 +33,7 @@ bool PyCGdiObject::CheckCppObject(ui_type *ui_type_check) const CGdiObject *PyCGdiObject::GetGdiObject(PyObject *self, DWORD gtype) { CGdiObject *pGdi = (CGdiObject *)GetGoodCppObject(self, &type); - if (gtype && pGdi->m_hObject && ::GetObjectType(pGdi->m_hObject) != gtype) + if (gtype && pGdi->m_hObject && ::GetObjectType(pGdi->m_hObject) != gtype) RETURN_ERR("The associated GDI object is not of the required type"); return pGdi; } diff --git a/Pythonwin/win32gdi.h b/Pythonwin/win32gdi.h index b1742770eb..58e8d26ce4 100644 --- a/Pythonwin/win32gdi.h +++ b/Pythonwin/win32gdi.h @@ -24,7 +24,7 @@ class PyCGdiObject : public ui_assoc_CObject { // XXX - PyCGDIObject used to have an 'm_deleteObject' attribute - but all // it did was cause a normal 'delete' of the object - ie, identical to the - // base-class bManualDelete. Its likely the original intent was for the new + // base-class bManualDelete. It's likely the original intent was for the new // attribute to determine if ::DeleteObject() should have been called, but // that apparently has never happened... }; diff --git a/Pythonwin/win32menu.cpp b/Pythonwin/win32menu.cpp index 4604a1ad5e..96b4a2a9de 100644 --- a/Pythonwin/win32menu.cpp +++ b/Pythonwin/win32menu.cpp @@ -86,7 +86,7 @@ PyObject *PyCMenu::load_menu(PyObject *self, PyObject *args) ////////////////////////////////////////////////////////////////////// void PyCMenu::SetAssocInvalid() { - return; // do nothing. Dont call base as dont want my handle wiped. + return; // do nothing. Don't call base as don't want my handle wiped. } // Menu Methods // @pymethod |PyCMenu|AppendMenu|Appends a new item to the end of a menu. Python can specify the state of the menu item diff --git a/Pythonwin/win32notify.cpp b/Pythonwin/win32notify.cpp index 89c1b50c2d..21dd6ef299 100644 --- a/Pythonwin/win32notify.cpp +++ b/Pythonwin/win32notify.cpp @@ -50,7 +50,7 @@ PyObject *PyNotifyMakeExtraTuple(NMHDR *ptr, char *fmt) { char *use = (*fmt == 'z') ? *(char **)pUse : pUse; ob = bIgnore ? NULL : PyBytes_FromString(""); // HACK HACK - FIX ME FIX ME - if (*fmt == 's') { // followed by buffer size; + if (*fmt == 's') { // followed by buffer size; int val = 0; while (fmt[1] && isdigit(fmt[1])) { val = val * 10 + (fmt[1] - '0'); @@ -68,7 +68,7 @@ PyObject *PyNotifyMakeExtraTuple(NMHDR *ptr, char *fmt) { char *use = (*fmt == 'Z') ? *(char **)pUse : pUse; ob = bIgnore ? NULL : PyBytes_FromString(""); // HACK HACK - FIX ME FIX ME - if (*fmt == 'S') { // followed by buffer size; + if (*fmt == 'S') { // followed by buffer size; int val = 0; while (fmt[1] && isdigit(fmt[1])) { val = val * 10 + (fmt[1] - '0'); @@ -372,7 +372,7 @@ BOOL Python_OnNotify(CWnd *pFrom, WPARAM, LPARAM lParam, LRESULT *pResult) PyObject *result = Python_do_callback(method, args); if (result == NULL) PyErr_Warn(PyExc_Warning, "Exception in OnNotify() handler"); - else if (result == Py_None) // allow for None "dont pass on", else result to windows + else if (result == Py_None) // allow for None "don't pass on", else result to windows bPassOn = TRUE; else if (PyTuple_Check(result)) { // Result should be a tuple of the LRESULT and a tuple to fill the appropriate @@ -382,11 +382,12 @@ BOOL Python_OnNotify(CWnd *pFrom, WPARAM, LPARAM lParam, LRESULT *pResult) if (PyErr_Occurred()) { gui_print_error(); PyErr_Format(ui_module_error, "Error parsing OnNotify() extra return info for code %d, fmt='%s'", code, - fmt); + fmt); gui_print_error(); } - // Otherwise result is just the LRESULT, which can be anything that fits in pointer size - } else if (!PyWinObject_AsSimplePARAM(result, (LPARAM *)&rc)) { + // Otherwise result is just the LRESULT, which can be anything that fits in pointer size + } + else if (!PyWinObject_AsSimplePARAM(result, (LPARAM *)&rc)) { gui_print_error(); PyErr_SetString(ui_module_error, "OnNotify did not return an LRESULT, or a tuple of (LRESULT, notify info tuple)"); diff --git a/Pythonwin/win32prinfo.cpp b/Pythonwin/win32prinfo.cpp index 9ff8c7088b..3b1af9c5d9 100644 --- a/Pythonwin/win32prinfo.cpp +++ b/Pythonwin/win32prinfo.cpp @@ -67,7 +67,7 @@ CPrintInfo *ui_prinfo_object::GetPrintInfo(PyObject *self) void ui_prinfo_object::SetAssocInvalid() { - return; // do nothing. Dont call base as dont want my handle wiped. + return; // do nothing. Don't call base as don't want my handle wiped. } ui_prinfo_object::~ui_prinfo_object() diff --git a/Pythonwin/win32prop.cpp b/Pythonwin/win32prop.cpp index 3bd3669778..651aa75939 100644 --- a/Pythonwin/win32prop.cpp +++ b/Pythonwin/win32prop.cpp @@ -314,7 +314,7 @@ PyObject *ui_propsheet_do_modal(PyObject *self, PyObject *args) return NULL; if (!PropSheetCheckForDisplay(pPS)) return NULL; - Py_INCREF(self); // make sure Python doesnt kill the object while in a modal call. + Py_INCREF(self); // make sure Python doesn't kill the object while in a modal call. // really only for the common dialog(!?), and other non CPythonPropSheet's INT_PTR ret; GUI_BGN_SAVE; @@ -590,7 +590,7 @@ ui_type_CObject PyCPropertySheet::type("PyCPropertySheet", &PyCWnd::type, RUNTIM ////////////////////////////////////////////////////////////////////// PyCPropertyPage::PyCPropertyPage() { - bManualDelete = FALSE; // dont "delete" the CWnd. + bManualDelete = FALSE; // don't "delete" the CWnd. } PyCPropertyPage::~PyCPropertyPage() { diff --git a/Pythonwin/win32prop.h b/Pythonwin/win32prop.h index c612611888..2674aa25ec 100644 --- a/Pythonwin/win32prop.h +++ b/Pythonwin/win32prop.h @@ -1,7 +1,7 @@ // property page/sheet objects // property sheets are a "clone" -// hack the associations a bit. When the dialog window closes, I dont +// hack the associations a bit. When the dialog window closes, I don't // destroy the association. ///////////////////////////////////////////////////////// diff --git a/Pythonwin/win32splitter.h b/Pythonwin/win32splitter.h index 6a8f52ef8c..a9c4ece29b 100644 --- a/Pythonwin/win32splitter.h +++ b/Pythonwin/win32splitter.h @@ -22,7 +22,7 @@ class CPythonSplitter : public CPythonWndFramework { DECLARE_MESSAGE_MAP() void AssertValid() const - { // MFCs version wont allow us to call it before created, and our framework want's to! + { // MFCs version won't allow us to call it before created, and our framework want's to! CWnd::AssertValid(); } }; diff --git a/Pythonwin/win32thread.cpp b/Pythonwin/win32thread.cpp index d48f8c938a..c26e8c7a1e 100644 --- a/Pythonwin/win32thread.cpp +++ b/Pythonwin/win32thread.cpp @@ -83,7 +83,8 @@ class CPythonWinThread : public CWinThread { if (!helper.HaveHandler()) { helper.release_full(); // important ret = CWinThread::Run(); - } else { + } + else { helper.call(); helper.retval(ret); } @@ -96,8 +97,7 @@ class CPythonWinThread : public CWinThread { void CProtectedWinThread::PumpIdle() { long lIdleCount = 0; - while (OnIdle(lIdleCount++)) - ; + while (OnIdle(lIdleCount++)); return; } @@ -245,7 +245,7 @@ static PyObject *ui_thread_set_main_frame(PyObject *self, PyObject *args) if (wndObject == Py_None) { // @comm You can pass None to this function to reset the main frame. - pThread->m_pMainWnd = NULL; // Should I free this? I dont think so! + pThread->m_pMainWnd = NULL; // Should I free this? I don't think so! } else { CWnd *pMainWnd = GetWndPtr(wndObject); diff --git a/Pythonwin/win32toolbar.cpp b/Pythonwin/win32toolbar.cpp index b14cad2abd..fd29148bc8 100644 --- a/Pythonwin/win32toolbar.cpp +++ b/Pythonwin/win32toolbar.cpp @@ -923,7 +923,7 @@ ui_type_CObject PyCToolBar::type("PyCToolBar", &PyCControlBar::type, RUNTIME_CLA RETURN_NONE; \ } -//#define MAKE_SET_INT_BOOL_METHOD(mfcName) MAKE_SET_INT_INT_METHOD(mfcName) +// #define MAKE_SET_INT_BOOL_METHOD(mfcName) MAKE_SET_INT_INT_METHOD(mfcName) PyCToolBarCtrl::PyCToolBarCtrl() { diff --git a/Pythonwin/win32ui.h b/Pythonwin/win32ui.h index 31d7d4ffcb..425c4d327d 100644 --- a/Pythonwin/win32ui.h +++ b/Pythonwin/win32ui.h @@ -138,8 +138,8 @@ class ui_base_class; // helper typeobject class. class PYW_EXPORT ui_type : public PyTypeObject { public: - ui_type(const char *name, ui_type *pBaseType, Py_ssize_t typeSize, ptrdiff_t pyobjOffset, struct PyMethodDef *methodList, - ui_base_class *(*thector)()); + ui_type(const char *name, ui_type *pBaseType, Py_ssize_t typeSize, ptrdiff_t pyobjOffset, + struct PyMethodDef *methodList, ui_base_class *(*thector)()); ~ui_type(); public: @@ -154,8 +154,8 @@ class PYW_EXPORT ui_type : public PyTypeObject { // helper typeCObject class. class PYW_EXPORT ui_type_CObject : public ui_type { public: - ui_type_CObject(const char *name, ui_type *pBaseType, CRuntimeClass *pRT, Py_ssize_t typeSize, ptrdiff_t pyobjOffset, - struct PyMethodDef *methodList, ui_base_class *(*thector)()); + ui_type_CObject(const char *name, ui_type *pBaseType, CRuntimeClass *pRT, Py_ssize_t typeSize, + ptrdiff_t pyobjOffset, struct PyMethodDef *methodList, ui_base_class *(*thector)()); ~ui_type_CObject(); public: @@ -245,9 +245,9 @@ PYW_EXPORT PyObject *gui_call_object(PyObject *themeth, PyObject *thearglist); PYW_EXPORT void gui_print_error(void); void gui_decref(PyObject *o); -//#endif // Py_ALLOBJECTS_H +// #endif // Py_ALLOBJECTS_H // -// CreateContext used when creating frames etc. +// CreateContext used when creating frames etc. // class PYW_EXPORT PythonCreateContext : public CCreateContext { public: @@ -312,8 +312,8 @@ class PYW_EXPORT CVirtualHelper : public CEnterLeavePython { BOOL call(const MSG *); BOOL call(WPARAM, LPARAM); BOOL call(UINT nID, int nCode, void *pExtra, AFX_CMDHANDLERINFO *pHandlerInfo); - PyObject* build_args(const char* format, ...); - BOOL call_args(const char* format, ...); + PyObject *build_args(const char *format, ...); + BOOL call_args(const char *format, ...); // All the retval functions will ASSERT if the call failed! BOOL retval(int &ret); BOOL retval(long &ret); diff --git a/Pythonwin/win32ui.rc b/Pythonwin/win32ui.rc index be8896b2c8..4cf2cac5b0 100644 --- a/Pythonwin/win32ui.rc +++ b/Pythonwin/win32ui.rc @@ -909,7 +909,7 @@ BEGIN CONTROL "View end of line markers",IDC_VIEW_EOL,"Button", BS_AUTOCHECKBOX | WS_TABSTOP,141,50,97,12 GROUPBOX "Tab-Timmy",IDC_STATIC,7,67,242,48 - CONTROL "Dont show inconsistent indentation",IDC_TABTIMMY_NONE, + CONTROL "Don't show inconsistent indentation",IDC_TABTIMMY_NONE, "Button",BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP,14, 76,122,12 CONTROL "Show as indicator",IDC_TABTIMMY_IND,"Button", diff --git a/Pythonwin/win32uiExt.h b/Pythonwin/win32uiExt.h index 3c8ab48ddd..6d70302e10 100644 --- a/Pythonwin/win32uiExt.h +++ b/Pythonwin/win32uiExt.h @@ -29,7 +29,7 @@ template class CPythonWndFramework : public T { public: // EEEK - It seem necessary to have the _union_ of all possible base class ctors. - // The ctors seem to only be referenced when used, so they dont worry classes that dont use them?? + // The ctors seem to only be referenced when used, so they don't worry classes that don't use them?? // What a pain - anyone know how to avoid???? // CWnd @@ -301,8 +301,8 @@ class CPythonWndFramework : public T { Py_INCREF(obPos); } else - obPos = helper.build_args("iiiiiii", pwp->hwnd, pwp->hwndInsertAfter, pwp->x, pwp->y, pwp->cx, pwp->cy, - pwp->flags); + obPos = helper.build_args("iiiiiii", pwp->hwnd, pwp->hwndInsertAfter, pwp->x, pwp->y, pwp->cx, + pwp->cy, pwp->flags); helper.call_args("i(NNNN)", bCalcValidRects, rc1, rc2, rc3, obPos); } else { @@ -877,7 +877,8 @@ class CPythonViewFramework : public CPythonWndFramework { // @pyparm object|hint|| helper.release_full(); T::OnUpdate(pSender, lHint, pHint); - } else + } + else helper.call(pSender, (PyObject *)lHint); } }; diff --git a/Pythonwin/win32uimodule.cpp b/Pythonwin/win32uimodule.cpp index 5a22057fa7..25cb0d8af1 100644 --- a/Pythonwin/win32uimodule.cpp +++ b/Pythonwin/win32uimodule.cpp @@ -171,10 +171,10 @@ ui_type::ui_type(const char *name, ui_type *pBase, Py_ssize_t typeSize, *((PyTypeObject *)this) = type_template; ((PyObject *)this)->ob_type = &PyType_Type; tp_methods = methodList; - //#define funky_offsetof_weakreflist ((size_t) &((PyObject *)(ui_base_class *)0)->weakreflist) + // #define funky_offsetof_weakreflist ((size_t) &((PyObject *)(ui_base_class *)0)->weakreflist) tp_weaklistoffset -= pyobjOffset; - // cast away const, as Python doesnt use it. + // cast away const, as Python doesn't use it. tp_name = (char *)name; tp_basicsize = typeSize; tp_base = pBase; @@ -244,7 +244,7 @@ ui_base_class *ui_base_class::make(ui_type &makeTypeRef) _Py_NewReference(pNew); #ifdef _DEBUG // this is really only for internal errors, and they should be ironed out! if (!pNew->is_uiobject(makeType)) - RETURN_ERR("Internal error - created type isnt what was requested!"); + RETURN_ERR("Internal error - created type isn't what was requested!"); #endif #ifdef TRACE_LIFETIMES TRACE("Constructing a '%s' at %p\n", pNew->ob_type->tp_name, pNew); @@ -506,7 +506,7 @@ BOOL DisplayPythonTraceback(PyObject *exc_type, PyObject *exc_val, PyObject *exc free(msg_free); #ifdef _DEBUG { - // doesnt seem to like long strings. + // doesn't seem to like long strings. CString cs(useMsg); int i = 0; while (i < cs.GetLength()) { @@ -566,8 +566,8 @@ int Python_run_command_with_log(const char *command) void Python_set_error(const char *msg) {} // In DEBUG builds, access voilations will normally trip my debugger, and -// hence I dont want them trapped. Stack Overflows normally mean runaway Python -// code, and I dont really want these trapped. +// hence I don't want them trapped. Stack Overflows normally mean runaway Python +// code, and I don't really want these trapped. #ifdef _DEBUG static int bTrapAccessViolations = FALSE; #endif @@ -857,7 +857,7 @@ static PyObject *ui_output_debug(PyObject *self, PyObject *args) while (*msg) { // not sure what's going on here. NT seems to add a \n each call.. - // Im sure msvc16 doesnt...(well, I _think_ Im sure..:) + // I'm sure msvc16 doesn't...(well, I _think_ I'm sure..:) while (*msg && *msg != '\n') *uiod++ = *msg++; *uiod = '\0'; // replace with NULL; if (*msg) { // must be \n @@ -2416,7 +2416,7 @@ PYWIN_MODULE_INIT_FUNC(win32ui) Py_XDECREF(dllhandle); // Ensure we have a __file__ attribute (Python itself normally // adds one, but if this is called not as part of the standard - // import process, we dont have one! + // import process, we don't have one! TCHAR pathName[MAX_PATH]; GetModuleFileName(hWin32uiDll, pathName, sizeof(pathName) / sizeof(pathName[0])); PyObject *obPathName = PyWinObject_FromTCHAR(pathName); @@ -2473,7 +2473,8 @@ int Win32uiRun(void) if (!helper.HaveHandler()) { helper.release_full(); // important ret = GetApp()->CWinApp::Run(); - } else { + } + else { helper.call(); helper.retval(ret); } @@ -2542,7 +2543,8 @@ BOOL Win32uiOnIdle(LONG lCount) return ret; } -extern "C" PYW_EXPORT BOOL Win32uiApplicationInit(Win32uiHostGlue *pGlue, const TCHAR *cmd, const TCHAR *additionalPaths) +extern "C" PYW_EXPORT BOOL Win32uiApplicationInit(Win32uiHostGlue *pGlue, const TCHAR *cmd, + const TCHAR *additionalPaths) { #ifdef _DEBUG afxDump.SetDepth(1); // deep dump of objects at exit. diff --git a/Pythonwin/win32uioleClientItem.cpp b/Pythonwin/win32uioleClientItem.cpp index 34745ccb03..a6b3fac6bd 100644 --- a/Pythonwin/win32uioleClientItem.cpp +++ b/Pythonwin/win32uioleClientItem.cpp @@ -61,7 +61,8 @@ class PythonOleClientItem : public COleClientItem { BOOL bRet; if (helper.call_args("(iiii)", rectPos.left, rectPos.top, rectPos.right, rectPos.bottom)) { helper.retval(bRet); - } else { + } + else { helper.release_full(); bRet = COleClientItem::OnChangeItemPosition(rectPos); } diff --git a/Pythonwin/win32util.cpp b/Pythonwin/win32util.cpp index 529aae5281..dcaefb5a70 100644 --- a/Pythonwin/win32util.cpp +++ b/Pythonwin/win32util.cpp @@ -37,8 +37,8 @@ generates Windows .hlp files. class PyCRectType : public ui_type { public: - PyCRectType(const char *name, ui_type *pBaseType, Py_ssize_t typeSize, ptrdiff_t pyobjOffset, struct PyMethodDef *methodList, - ui_base_class *(*thector)()); + PyCRectType(const char *name, ui_type *pBaseType, Py_ssize_t typeSize, ptrdiff_t pyobjOffset, + struct PyMethodDef *methodList, ui_base_class *(*thector)()); }; // @object PyCRect|A Python interface the the MFC CRect class. class PyCRect : public ui_base_class { @@ -178,7 +178,7 @@ PyCRectType PyCRect::type("PyCRect", &ui_base_class::type, sizeof(PyCRect), PYOB NULL); // The CREATESTRUCT just has pointers (no buffers) for the name -// and classname. Therefore, I dont treat them as strings, just +// and classname. Therefore, I don't treat them as strings, just // pointers (via long casts) // @object CREATESTRUCT|A representation of a Windows CREATESTRUCT structure. PyObject *PyObjectFromCreateStruct(LPCREATESTRUCT lpcs) @@ -260,7 +260,7 @@ BOOL DictToLogFont(PyObject *font_props, LOGFONT *pLF) szFontClipPrecision, szFontQuality, szFontPitch, szFontName, NULL}; // font default values - pLF->lfCharSet = DEFAULT_CHARSET; // dont use ANSI_CHARSET to support Japanese charset. + pLF->lfCharSet = DEFAULT_CHARSET; // don't use ANSI_CHARSET to support Japanese charset. pLF->lfQuality = PROOF_QUALITY; // don't scale raster fonts and force anti aliasing if (!PyDict_Check(font_props)) { PyErr_Format(PyExc_TypeError, "LOGFONT must be a dict, not %s", font_props->ob_type->tp_name); @@ -1137,11 +1137,12 @@ CString GetReprText(PyObject *objectUse) PyObject *s; CString csRet; s = PyObject_Str(objectUse); - if (s) if (TmpWCHAR ts=s) { - csRet = CString(ts); - Py_DECREF(s); - return csRet; - } + if (s) + if (TmpWCHAR ts = s) { + csRet = CString(ts); + Py_DECREF(s); + return csRet; + } PyErr_Clear(); s = PyObject_Repr(objectUse); if (s == NULL) { @@ -1152,7 +1153,7 @@ CString GetReprText(PyObject *objectUse) // repr() should always return a unicode string, but for hysterical raisens we check if it is bytes. if (PyUnicode_Check(s)) - if (TmpWCHAR ts=s) + if (TmpWCHAR ts = s) csRet = ts; else { PyErr_Clear(); diff --git a/Pythonwin/win32virt.cpp b/Pythonwin/win32virt.cpp index 2f46c84359..5d049fbf37 100644 --- a/Pythonwin/win32virt.cpp +++ b/Pythonwin/win32virt.cpp @@ -85,11 +85,11 @@ void CVirtualHelper::release_full() release(); } -PyObject* CVirtualHelper::build_args(const char* format, ...) +PyObject *CVirtualHelper::build_args(const char *format, ...) { // Helper to create Python objects when called outside the GIL. va_list va; - PyObject* retval; + PyObject *retval; va_start(va, format); retval = Py_VaBuildValue(format, va); va_end(va); @@ -117,7 +117,7 @@ BOOL CVirtualHelper::do_call(PyObject *args) if (obRepr) { if (PyBytes_Check(obRepr)) szRepr = PyBytes_AS_STRING(obRepr); - else if (TmpWCHAR tmpw=obRepr) + else if (TmpWCHAR tmpw = obRepr) szRepr = W2A(tmpw); } @@ -147,13 +147,13 @@ BOOL CVirtualHelper::do_call(PyObject *args) return TRUE; } -BOOL CVirtualHelper::call_args(const char* format, ...) +BOOL CVirtualHelper::call_args(const char *format, ...) { if (!handler) return FALSE; // Duplicate build_args va_list va; - PyObject* args; + PyObject *args; va_start(va, format); args = Py_VaBuildValue(format, va); va_end(va); @@ -523,7 +523,7 @@ BOOL CVirtualHelper::retnone() { ASSERT(retVal); if (!retVal) - return FALSE; // failed - assume didnt work in non debug + return FALSE; // failed - assume didn't work in non debug return (retVal == Py_None); } @@ -531,7 +531,7 @@ BOOL CVirtualHelper::retval(MSG *msg) { ASSERT(retVal); if (!retVal) - return FALSE; // failed - assume didnt work in non debug + return FALSE; // failed - assume didn't work in non debug if (!PyWinObject_AsMSG(retVal, msg)) { gui_print_error(); return FALSE; @@ -542,7 +542,7 @@ BOOL CVirtualHelper::retval(int &ret) { ASSERT(retVal); if (!retVal) - return FALSE; // failed - assume didnt work in non debug + return FALSE; // failed - assume didn't work in non debug if (retVal == Py_None) { ret = 0; return TRUE; @@ -559,7 +559,7 @@ BOOL CVirtualHelper::retval(long &ret) { ASSERT(retVal); if (!retVal) - return FALSE; // failed - assume didnt work in non debug + return FALSE; // failed - assume didn't work in non debug if (retVal == Py_None) { ret = 0; return TRUE; @@ -576,7 +576,7 @@ BOOL CVirtualHelper::retval(HANDLE &ret) { ASSERT(retVal); if (!retVal) - return FALSE; // failed - assume didnt work in non debug + return FALSE; // failed - assume didn't work in non debug if (retVal == Py_None) { ret = 0; return TRUE; @@ -592,7 +592,7 @@ BOOL CVirtualHelper::retval(CString &ret) { ASSERT(retVal); if (!retVal) - return FALSE; // failed - assume didnt work in non debug + return FALSE; // failed - assume didn't work in non debug if (retVal == Py_None) { ret.Empty(); return TRUE; @@ -611,7 +611,7 @@ BOOL CVirtualHelper::retval(_object *&ret) { ASSERT(retVal); if (!retVal) - return FALSE; // failed - assume didnt work in non debug + return FALSE; // failed - assume didn't work in non debug ret = retVal; /** what was I thinking? if (!PyArg_Parse(retVal, "O",&ret)) { @@ -627,7 +627,7 @@ BOOL CVirtualHelper::retval(CREATESTRUCT &cs) USES_CONVERSION; ASSERT(retVal); if (!retVal || retVal == Py_None) - return FALSE; // failed - assume didnt work in non debug + return FALSE; // failed - assume didn't work in non debug if (!CreateStructFromPyObject(&cs, retVal)) { gui_print_error(); CString msgBuf; diff --git a/Pythonwin/win32win.cpp b/Pythonwin/win32win.cpp index 51c4d365cf..f7db04170c 100644 --- a/Pythonwin/win32win.cpp +++ b/Pythonwin/win32win.cpp @@ -63,7 +63,8 @@ class WndHack : public CWnd { BOOL Python_check_message(const MSG *msg) // TRUE if fully processed. { - // Our Python convention is TRUE means "pass it on", which we only want to do if the message if valid, and the callback returns TRUE + // Our Python convention is TRUE means "pass it on", which we only want to do if the message if valid, and the + // callback returns TRUE BOOL ret = FALSE; ui_assoc_object *pObj = NULL; PyObject *method; @@ -621,7 +622,7 @@ BOOL PyCWnd::check_key_stroke(WPARAM ch) CWnd *PyCWnd::GetPythonGenericWnd(PyObject *self, ui_type_CObject *pType) { - // Damn it - only pass PyCWnd::type so the RTTI check wont fail + // Damn it - only pass PyCWnd::type so the RTTI check won't fail // for builtin controls. return (CWnd *)GetGoodCppObject(self, &type); } @@ -646,7 +647,7 @@ CWnd *PyCWnd::GetPythonGenericWnd(PyObject *self, ui_type_CObject *pType) #include "D:\Program Files\DevStudio\VC\mfc\src\WINHAND_.H" extern AFX_MODULE_THREAD_STATE * PyWin_MainModuleThreadState; - // Lets see if it is in the main thread state + // Let's see if it is in the main thread state if (PyWin_MainModuleThreadState->m_pmapHWND && (AfxGetModuleThreadState() != PyWin_MainModuleThreadState)) { // Gross hack - look it up in the internal map structure. @@ -666,7 +667,7 @@ CWnd *PyCWnd::GetPythonGenericWnd(PyObject *self, ui_type_CObject *pType) if (makeType.pCObjectClass && makeType.pCObjectClass->m_pfnCreateObject) { pWnd = (CWnd *)makeType.pCObjectClass->CreateObject(); if (pWnd == NULL) { - PyErr_SetString(PyExc_MemoryError, "Cant create the window object"); + PyErr_SetString(PyExc_MemoryError, "Can't create the window object"); return NULL; } ASSERT(pWnd->IsKindOf(RUNTIME_CLASS(CWnd))); // Must be a window object we just created! @@ -2199,7 +2200,8 @@ PyObject *ui_window_send_message(PyObject *self, PyObject *args) if (oblParam != Py_None) { if (!PyWinObject_AsPARAM(oblParam, &lp)) return NULL; - } else if (wp.bufferView.ok() && PyTuple_Size(args) == 2) { + } + else if (wp.bufferView.ok() && PyTuple_Size(args) == 2) { // old code compatibily: (msg, buffer_ob) -> lparam==&buffer, wparam=len(buffer) lp = (WPARAM)wp.bufferView.ptr(); wp = (WPARAM)wp.bufferView.len(); // doesn't release the held bufferView so far @@ -3513,7 +3515,7 @@ static PyObject *PyCFrameWnd_DockControlBar(PyObject *self, PyObject *args) Py_INCREF(Py_None); } __except (EXCEPTION_EXECUTE_HANDLER) { - rc = NULL; // Cant set Python error till we have the lock back. + rc = NULL; // Can't set Python error till we have the lock back. } GUI_END_SAVE; if (rc == NULL) diff --git a/Pythonwin/win32win.h b/Pythonwin/win32win.h index c23033ad6f..888635562d 100644 --- a/Pythonwin/win32win.h +++ b/Pythonwin/win32win.h @@ -4,7 +4,7 @@ // Window Objects // class PYW_EXPORT PyCWnd : public PyCCmdTarget { - public: // probably shouldnt be, but... + public: // probably shouldn't be, but... MAKE_PY_CTOR(PyCWnd) CMapWordToPtr *pMessageHookList; CMapWordToPtr *pKeyHookList; diff --git a/SWIG/swig_lib/python/pywintypes.i b/SWIG/swig_lib/python/pywintypes.i index 4ebeca825b..7ef58a4d8d 100644 --- a/SWIG/swig_lib/python/pywintypes.i +++ b/SWIG/swig_lib/python/pywintypes.i @@ -403,6 +403,10 @@ typedef float HWND; $target=PyWinLong_FromHANDLE($source); } +%typemap(python, out) HDESK { + $target = PyWinLong_FromHANDLE($source); +} + //--------------------------------------------------------------------------- // // LARGE_INTEGER support diff --git a/adodbapi/ado_consts.py b/adodbapi/ado_consts.py index ecb2147dc4..8e2125765b 100644 --- a/adodbapi/ado_consts.py +++ b/adodbapi/ado_consts.py @@ -47,7 +47,7 @@ def ado_direction_name(ado_dir): try: return "adParam" + directions[ado_dir] except: - return "unknown direction (" + str(ado_dir) + ")" + return f"unknown direction ({ado_dir})" # ObjectStateEnum @@ -166,7 +166,7 @@ def ado_direction_name(ado_dir): def ado_type_name(ado_type): - return adTypeNames.get(ado_type, "unknown type (" + str(ado_type) + ")") + return adTypeNames.get(ado_type, f"unknown type ({ado_type})") # here in decimal, sorted by value diff --git a/adodbapi/adodbapi.py b/adodbapi/adodbapi.py index 5d82260939..0f84a890a6 100644 --- a/adodbapi/adodbapi.py +++ b/adodbapi/adodbapi.py @@ -168,7 +168,7 @@ def _configure_parameter(p, value, adotype, settings_known): L = min(L, p.Size) # v2.1 Cole limit data to defined size p.Value = value[:L] # v2.1 Jevon & v2.1 Cole else: - p.Value = value # dont limit if db column is numeric + p.Value = value # don't limit if db column is numeric if L > 0: # v2.1 Cole something does not like p.Size as Zero p.Size = L # v2.1 Jevon @@ -243,7 +243,7 @@ def __init__(self): # now define the instance attributes def connect(self, kwargs, connection_maker=make_COM_connecter): if verbose > 9: - print("kwargs=", repr(kwargs)) + print(f"kwargs={kwargs!r}") try: self.connection_string = ( kwargs["connection_string"] % kwargs @@ -415,8 +415,7 @@ def __setattr__(self, name, value): if value not in api.accepted_paramstyles: self._raiseConnectionError( api.NotSupportedError, - 'paramstyle="%s" not in:%s' - % (value, repr(api.accepted_paramstyles)), + f"paramstyle={value!r} not in:{api.accepted_paramstyles!r}", ) elif name == "variantConversions": value = copy.copy( @@ -731,8 +730,7 @@ def _new_command(self, command_type=adc.adCmdText): except: self._raiseCursorError( api.DatabaseError, - 'Error creating new ADODB.Command object for "%s"' - % repr(self.commandText), + f"Error creating new ADODB.Command object for {self.commandText!r}", ) def _execute_command(self): @@ -856,7 +854,7 @@ def _buildADOparameterList(self, parameters, sproc=False): "ADO detected Params=", format_parameters(self.cmd.Parameters, True), ) - print("Program Parameters=", repr(parameters)) + print(f"Program Parameters={parameters!r}") parameters_known = True except api.Error: if verbose: @@ -879,17 +877,14 @@ def _buildADOparameterList(self, parameters, sproc=False): p, parameters[pm_name], p.Type, parameters_known ) except Exception as e: - _message = ( - "Error Converting Parameter %s: %s, %s <- %s\n" - % ( - p.Name, - adc.ado_type_name(p.Type), - p.Value, - repr(parameters[pm_name]), - ) + _message = "Error Converting Parameter {}: {}, {} <- {!r}\n".format( + p.Name, + adc.ado_type_name(p.Type), + p.Value, + parameters[pm_name], ) self._raiseCursorError( - api.DataError, _message + "->" + repr(e.args) + api.DataError, f"{_message}->{e.args!r}" ) else: # regular sequence of parameters for value in parameters: @@ -902,17 +897,14 @@ def _buildADOparameterList(self, parameters, sproc=False): try: _configure_parameter(p, value, p.Type, parameters_known) except Exception as e: - _message = ( - "Error Converting Parameter %s: %s, %s <- %s\n" - % ( - p.Name, - adc.ado_type_name(p.Type), - p.Value, - repr(value), - ) + _message = "Error Converting Parameter {}: {}, {} <- {!r}\n".format( + p.Name, + adc.ado_type_name(p.Type), + p.Value, + value, ) self._raiseCursorError( - api.DataError, _message + "->" + repr(e.args) + api.DataError, f"{_message}->{e.args!r}" ) i += 1 else: # -- build own parameter list @@ -929,14 +921,16 @@ def _buildADOparameterList(self, parameters, sproc=False): try: self.cmd.Parameters.Append(p) except Exception as e: - _message = "Error Building Parameter %s: %s, %s <- %s\n" % ( - p.Name, - adc.ado_type_name(p.Type), - p.Value, - repr(elem), + _message = ( + "Error Building Parameter {}: {}, {} <- {!r}\n".format( + p.Name, + adc.ado_type_name(p.Type), + p.Value, + elem, + ) ) self._raiseCursorError( - api.DataError, _message + "->" + repr(e.args) + api.DataError, f"{_message}->{e.args!r}" ) else: # expecting the usual sequence of parameters if sproc: @@ -955,14 +949,16 @@ def _buildADOparameterList(self, parameters, sproc=False): try: self.cmd.Parameters.Append(p) except Exception as e: - _message = "Error Building Parameter %s: %s, %s <- %s\n" % ( - p.Name, - adc.ado_type_name(p.Type), - p.Value, - repr(elem), + _message = ( + "Error Building Parameter {}: {}, {} <- {!r}\n".format( + p.Name, + adc.ado_type_name(p.Type), + p.Value, + elem, + ) ) self._raiseCursorError( - api.DataError, _message + "->" + repr(e.args) + api.DataError, f"{_message}->{e.args!r}" ) i += 1 if self._ado_prepared == "setup": @@ -1150,7 +1146,7 @@ def _last_query(self): # let the programmer see what query we actually used if self.parameters is None: ret = self.commandText else: - ret = "%s,parameters=%s" % (self.commandText, repr(self.parameters)) + ret = f"{self.commandText},parameters={self.parameters!r}" except: ret = None return ret diff --git a/adodbapi/apibase.py b/adodbapi/apibase.py index 711eda706c..1fb1b133db 100644 --- a/adodbapi/apibase.py +++ b/adodbapi/apibase.py @@ -170,7 +170,7 @@ def COMDate(self, obj): try: return self.ComDateFromTuple(obj) except: - raise ValueError('Cannot convert "%s" to COMdate.' % repr(obj)) + raise ValueError(f'Cannot convert "{obj!r}" to COMdate.') def ComDateFromTuple(self, t, microseconds=0): d = datetime.date(t[0], t[1], t[2]) @@ -207,7 +207,7 @@ def DateObjectToIsoFormatString(self, obj): try: # but may be time.struct_time s = time.strftime("%Y-%m-%d %H:%M:%S", obj) except: - raise ValueError('Cannot convert "%s" to isoformat' % repr(obj)) + raise ValueError(f'Cannot convert "{obj!r}" to isoformat') return s @@ -389,7 +389,7 @@ def pyTypeToADOType(d): return adc.adBigInt if isinstance(d, numbers.Real): return adc.adDouble - raise DataError('cannot convert "%s" (type=%s) to ADO' % (repr(d), tp)) + raise DataError(f'cannot convert "{d!r}" (type={tp}) to ADO') # # # # # # # # # # # # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -451,7 +451,7 @@ def identity(x): def cvtUnusual(variant): if verbose > 1: - sys.stderr.write("Conversion called for Unusual data=%s\n" % repr(variant)) + sys.stderr.write(f"Conversion called for Unusual data={variant!r}\n") return variant # cannot find conversion function -- just give the data to the user @@ -545,9 +545,7 @@ def __getitem__(self, key): # used for row[key] type of value access ) # extension row[columnName] designation except (KeyError, TypeError): er, st, tr = sys.exc_info() - raise er( - 'No such key as "%s" in %s' % (repr(key), self.__repr__()) - ).with_traceback(tr) + raise er(f'No such key as "{key!r}" in {self!r}').with_traceback(tr) def __iter__(self): return iter(self.__next__()) @@ -560,7 +558,7 @@ def __repr__(self): # create a human readable representation taglist = sorted(list(self.rows.columnNames.items()), key=lambda x: x[1]) s = "" def __str__(self): # create a pretty human readable representation @@ -609,7 +607,7 @@ def __getitem__(self, item): # used for row or row,column access try: j = self.columnNames[j.lower()] # convert named column to numeric except KeyError: - raise KeyError('adodbapi: no such column name as "%s"' % repr(j)) + raise KeyError(f"adodbapi: no such column name as {j!r}") if self.recordset_format == RS_ARRAY: # retrieve from two-dimensional array v = self.ado_results[j, i] elif self.recordset_format == RS_REMOTE: diff --git a/adodbapi/process_connect_string.py b/adodbapi/process_connect_string.py index 11a62c69be..d8b29f280c 100644 --- a/adodbapi/process_connect_string.py +++ b/adodbapi/process_connect_string.py @@ -68,9 +68,9 @@ def macro_call(macro_name, args, kwargs): tempfile.gettempdir(), "adodbapi_test", args[1] ) - raise ValueError("Unknown connect string macro=%s" % macro_name) + raise ValueError(f"Unknown connect string macro={macro_name}") except: - raise ValueError("Error in macro processing %s %s" % (macro_name, repr(args))) + raise ValueError(f"Error in macro processing {macro_name} {args!r}") def process( diff --git a/adodbapi/readme.txt b/adodbapi/readme.txt index b5798677bb..00f76f7c2f 100644 --- a/adodbapi/readme.txt +++ b/adodbapi/readme.txt @@ -40,7 +40,7 @@ notes for 2.6.2: The definitive source has been moved to https://github.com/mhammond/pywin32/tree/master/adodbapi. Remote has proven too hard to configure and test with Pyro4. I am moving it to unsupported status until I can change to a different connection method. -whats new in version 2.6 +what's new in version 2.6 A cursor.prepare() method and support for prepared SQL statements. Lots of refactoring, especially of the Remote and Server modules (still to be treated as Beta code). The quick start document 'quick_reference.odt' will export as a nice-looking pdf. @@ -48,7 +48,7 @@ whats new in version 2.6 parameters to your .execute() method. If your 'paramstyle' is 'format' 'pyformat' or 'dynamic', you _may_ pass a dictionary of parameters -- provided your SQL operation string is formatted correctly. -whats new in version 2.5 +what's new in version 2.5 Remote module: (works on Linux!) allows a Windows computer to serve ADO databases via PyRO Server module: PyRO server for ADO. Run using a command like= C:>python -m adodbapi.server (server has simple connection string macros: is64bit, getuser, sql_provider, auto_security) diff --git a/adodbapi/test/adodbapitest.py b/adodbapi/test/adodbapitest.py index 9e1ba7aab5..a1450d1a57 100644 --- a/adodbapi/test/adodbapitest.py +++ b/adodbapi/test/adodbapitest.py @@ -352,7 +352,7 @@ def helpTestDataType( ok = False self.assertTrue( rs[0] in allowedReturnValues, - 'Value "%s" not in %s' % (repr(rs[0]), allowedReturnValues), + f'Value "{rs[0]!r}" not in {allowedReturnValues}', ) else: self.assertEqual( @@ -697,17 +697,15 @@ def testRowIterator(self): rec[j] == inParam[j] ), 'returned value:"%s" != test value:"%s"' % (rec[j], inParam[j]) # check that we can get a complete tuple from a row - assert tuple(rec) == inParam, 'returned value:"%s" != test value:"%s"' % ( - repr(rec), - repr(inParam), - ) + assert ( + tuple(rec) == inParam + ), f'returned value:"{rec!r}" != test value:"{inParam!r}"' # test that slices of rows work slice1 = tuple(rec[:-1]) slice2 = tuple(inParam[0:2]) - assert slice1 == slice2, 'returned value:"%s" != test value:"%s"' % ( - repr(slice1), - repr(slice2), - ) + assert ( + slice1 == slice2 + ), f'returned value:"{slice1!r}" != test value:"{slice2!r}"' # now test named column retrieval assert rec["fldTwo"] == inParam[0] assert rec.fldThree == inParam[1] @@ -1027,10 +1025,9 @@ def testAutoRollback(self): row = crsr.fetchone() except api.DatabaseError: row = None # if the entire table disappeared the rollback was perfect and the test passed - assert row is None, ( - "cursor.fetchone should return None if a query retrieves no rows. Got %s" - % repr(row) - ) + assert ( + row is None + ), f"cursor.fetchone should return None if a query retrieves no rows. Got {row!r}" self.helpRollbackTblTemp() def testAutoCommit(self): @@ -1164,11 +1161,11 @@ def testVariableReturningStoredProcedure(self): retvalues = crsr.callproc( "sp_DeleteMeOnlyForTesting", ("Dodsworth", "Anne", " ") ) - assert retvalues[0] == "Dodsworth", '%s is not "Dodsworth"' % repr(retvalues[0]) - assert retvalues[1] == "Anne", '%s is not "Anne"' % repr(retvalues[1]) - assert retvalues[2] == "DodsworthAnne", '%s is not "DodsworthAnne"' % repr( - retvalues[2] - ) + assert retvalues[0] == "Dodsworth", f'{retvalues[0]!r} is not "Dodsworth"' + assert retvalues[1] == "Anne", f'{retvalues[1]!r} is not "Anne"' + assert ( + retvalues[2] == "DodsworthAnne" + ), f'{retvalues[2]!r} is not "DodsworthAnne"' self.conn.rollback() def testMultipleSetReturn(self): @@ -1344,19 +1341,16 @@ def testOkConnect(self): # /* (SELECT 'a small string' as result; */ # END $$ # """ - # # crsr.execute(spdef) - # # retvalues = crsr.callproc( # "DeleteMeOnlyForTesting", ("Dodsworth", "Anne", " ") # ) - # print("return value (mysql)=", repr(crsr.returnValue)) - # assert retvalues[0] == "Dodsworth", '%s is not "Dodsworth"' % repr(retvalues[0]) - # assert retvalues[1] == "Anne", '%s is not "Anne"' % repr(retvalues[1]) - # assert retvalues[2] == "DodsworthAnne", '%s is not "DodsworthAnne"' % repr( - # retvalues[2] - # ) - # + # # print(f"return value (mysql)={crsr.returnValue!r}") + # assert retvalues[0] == "Dodsworth", f'{retvalues[0]!r} is not "Dodsworth"' + # assert retvalues[1] == "Anne", f'{retvalues[1]!r} is not "Anne"' + # assert ( + # retvalues[2] == "DodsworthAnne" + # ), f'{retvalues[2]!r} is not "DodsworthAnne"' # try: # crsr.execute("DROP PROCEDURE, DeleteMeOnlyForTesting") # self.conn.commit() @@ -1413,12 +1407,12 @@ def testOkConnect(self): # retvalues = crsr.callproc( # "DeleteMeOnlyForTesting", ("Dodsworth", "Anne", " ") # ) - # # print("return value (pg)=", repr(crsr.returnValue)) - # assert retvalues[0] == "Dodsworth", '%s is not "Dodsworth"' % repr(retvalues[0]) - # assert retvalues[1] == "Anne", '%s is not "Anne"' % repr(retvalues[1]) - # assert retvalues[2] == "Dodsworth Anne", '%s is not "Dodsworth Anne"' % repr( - # retvalues[2] - # ) + # # print(f"return value (pg)={crsr.returnValue!r}") + # assert retvalues[0] == "Dodsworth", f'{retvalues[0]!r} is not "Dodsworth"' + # assert retvalues[1] == "Anne", f'{retvalues[1]!r} is not "Anne"' + # assert ( + # retvalues[2] == "DodsworthAnne" + # ), f'{retvalues[2]!r} is not "DodsworthAnne"' # self.conn.rollback() # try: # crsr.execute("DROP PROCEDURE, DeleteMeOnlyForTesting") @@ -1490,7 +1484,7 @@ def testDateObjectFromCOMDate(self): t2 = time.gmtime( time.mktime((2002, 6, 29, 12, 14, 2, 4, 31 + 28 + 31 + 30 + 31 + 28, -1)) ) - assert t1 < cmd < t2, '"%s" should be about 2002-6-28 12:15:01' % repr(cmd) + assert t1 < cmd < t2, f'"{cmd}" should be about 2002-6-28 12:15:01' def testDate(self): t1 = time.mktime((2002, 6, 28, 18, 15, 1, 4, 31 + 28 + 31 + 30 + 31 + 30, 0)) diff --git a/adodbapi/test/dbapi20.py b/adodbapi/test/dbapi20.py index 97ce0a0c6a..f356fe3b1d 100644 --- a/adodbapi/test/dbapi20.py +++ b/adodbapi/test/dbapi20.py @@ -465,13 +465,13 @@ def _paraminsert(self, cur): res[0][1], trouble, "cursor.fetchall retrieved incorrect data, or data inserted " - "incorrectly. Got=%s, Expected=%s" % (repr(res[0][1]), repr(trouble)), + f"incorrectly. Got={res[0][1]!r}, Expected={trouble!r}", ) self.assertEqual( res[1][1], trouble, "cursor.fetchall retrieved incorrect data, or data inserted " - "incorrectly. Got=%s, Expected=%s" % (repr(res[1][1]), repr(trouble)), + f"incorrectly. Got={res[1][1]!r}, Expected={trouble!r}", ) def test_executemany(self): diff --git a/adodbapi/test/test_adodbapi_dbapi20.py b/adodbapi/test/test_adodbapi_dbapi20.py index e5d36282c9..6218b7997e 100644 --- a/adodbapi/test/test_adodbapi_dbapi20.py +++ b/adodbapi/test/test_adodbapi_dbapi20.py @@ -81,8 +81,8 @@ testmdb = setuptestframework.makemdb(testfolder) connStr = r"Provider=%s;Data Source=%s" % (driver, testmdb) -print("Using Connection String like=%s" % connStr) -print("Keywords=%s" % repr(conn_kws)) +print(f"Using Connection String like={connStr}") +print(f"Keywords={conn_kws!r}") class test_adodbapi(dbapi20.DatabaseAPI20Test): diff --git a/adodbapi/test/tryconnection.py b/adodbapi/test/tryconnection.py index e0f7e06025..1dc8bbe259 100644 --- a/adodbapi/test/tryconnection.py +++ b/adodbapi/test/tryconnection.py @@ -10,7 +10,7 @@ def try_connection(verbose, *args, **kwargs): s.close() # thanks, it worked, goodbye except adodbapi.DatabaseError as inst: print(inst.args[0]) # should be the error message - print("***Failed getting connection using=", repr(args), repr(kwargs)) + print(f"***Failed getting connection using= {args!r} {kwargs!r}") return False, (args, kwargs), None print(" (successful)") diff --git a/com/TestSources/PyCOMTest/DSCArrayTest.h b/com/TestSources/PyCOMTest/DSCArrayTest.h index ea16befa85..64e2581836 100644 --- a/com/TestSources/PyCOMTest/DSCArrayTest.h +++ b/com/TestSources/PyCOMTest/DSCArrayTest.h @@ -3,7 +3,7 @@ #ifndef __ARRAYTEST_H_ #define __ARRAYTEST_H_ -//#include "resource.h" // main symbols +// #include "resource.h" // main symbols ///////////////////////////////////////////////////////////////////////////// // DSCArrayTest diff --git a/com/TestSources/PyCOMTest/PyCOMTest.idl b/com/TestSources/PyCOMTest/PyCOMTest.idl index a006934fb9..f4ab945906 100644 --- a/com/TestSources/PyCOMTest/PyCOMTest.idl +++ b/com/TestSources/PyCOMTest/PyCOMTest.idl @@ -26,7 +26,7 @@ typedef enum // Missing EnumTestAttributes2 uuid(6bcdcb60-5605-11d0-ae5f-cadd4c000000), version(1.1), // an extended character in the help string should stress things... - helpstring("Python COM Test Harness 1.0 Type Library, © pywin32 contributors") + helpstring("Python COM Test Harness 1.0 Type Library, � pywin32 contributors") ] library PyCOMTestLib { @@ -70,7 +70,7 @@ library PyCOMTestLib const long LongTest2 = 0x7FFFFFFFL; const unsigned char UCharTest = 255; const char CharTest = -1; - const LPWSTR StringTest = L"Hello Wo®ld"; + const LPWSTR StringTest = L"Hello Wo�ld"; }; enum TestAttributes3{ // Note missing the enum name. @@ -371,7 +371,7 @@ library PyCOMTestLib [ uuid(638630ac-a734-45a2-8080-fda5c1e47f66), - helpstring("PyCOMTest Class that doesnt derive from IDispatch") + helpstring("PyCOMTest Class that doesn't derive from IDispatch") ] coclass CoPyCOMTestNoDispatch { diff --git a/com/TestSources/PyCOMTest/SimpleCounter.cpp b/com/TestSources/PyCOMTest/SimpleCounter.cpp index 8946cad588..a691e2d627 100644 --- a/com/TestSources/PyCOMTest/SimpleCounter.cpp +++ b/com/TestSources/PyCOMTest/SimpleCounter.cpp @@ -10,7 +10,7 @@ CSimpleCounter::CSimpleCounter() { - m_minIndex = 1; // have 1 based index, just cos Python doesnt! + m_minIndex = 1; // have 1 based index, just cos Python doesn't! m_maxIndex = 10; } STDMETHODIMP CSimpleCounter::get_Count(long *retval) diff --git a/com/TestSources/PyCOMVBTest/Tester.cls b/com/TestSources/PyCOMVBTest/Tester.cls index b21226197e..12b4e5601d 100644 --- a/com/TestSources/PyCOMVBTest/Tester.cls +++ b/com/TestSources/PyCOMVBTest/Tester.cls @@ -23,7 +23,7 @@ Private mvarCollectionProperty As Collection 'local copy 'local variable(s) to hold property value(s) Private mvarVariantPutref As Variant 'local copy 'local variable(s) to hold property value(s) -' I cant seem to declare properties as returning native arrays. +' I can't seem to declare properties as returning native arrays. ' I can only declare them as variant which hopefully holds an array. Private mvarArrayProperty As Variant 'local copy @@ -250,7 +250,7 @@ Public Sub DoSomeCallbacks(ob As Object) Dim rg(1) As Integer Dim rgv(1) As Variant Dim rg_new As Variant - Rem On Error GoTo failed ' Dont really need this - error is correctly propogated back to Python! + Rem On Error GoTo failed ' Don't really need this - error is correctly propogated back to Python! Rem Can check byrefs for gateways here, as VB passes all params byref! i = 99 @@ -270,7 +270,7 @@ Public Sub DoSomeCallbacks(ob As Object) If variantResult <> Null Then MsgBox "After CallbackResultOneByRefButReturnNone, the param was in error - was " & variantResult & " but expected Null" ' See what happens to a ByRef with a void function! ' XXX - was expecting this to fail - VB passes as VT_VARIANT|VT_BYREF - ' and Python sets the Variant to NULL - but VB doesnt complain! + ' and Python sets the Variant to NULL - but VB doesn't complain! ob.CallbackVoidOneByRefButReturnNone i If i <> 100 Then MsgBox "After CallbackVoidOneByRefButReturnNone, the param was in error - was " & i & " but expected 100" rgv(0) = 0 @@ -292,7 +292,7 @@ Public Sub DoSomeCallbacks(ob As Object) ' rg_new should now be rg before the call. If rg_new(0) <> 1 Or rg_new(1) <> 2 Then MsgBox "CallbackArrayResultOneArrayByRef - result wrong - - (" & rg_new(0) & "," & rg_new(1) & ")!!" ' The byref array gets incremented. - ' EEEK - this doesnt work. + ' EEEK - this doesn't work. ' Cos we are using function call syntax, the array is _not_ passed byref!!! 'If rg(0) <> 1 Or rg(1) <> 2 Then MsgBox "CallbackArrayResultOneArrayByRef - byref param wrong - - (" & rg(0) & "," & rg(1) & ")!!" Exit Sub diff --git a/com/changes.txt b/com/changes.txt index 5e16e89a99..f94adde87a 100644 --- a/com/changes.txt +++ b/com/changes.txt @@ -45,7 +45,7 @@ fixed (eg, all MSOffice test run both as dynamic and makepy - the only differenc speed. Note that Office97 can be _very_ slow at startup without makep support loaded. * Full support for Office 97. Note that Word97 has changed its object model, and -their "compatibility" layer doesnt work with Python - you will need to change any code +their "compatibility" layer doesn't work with Python - you will need to change any code that uses Word. See the win32com\test\testMSOffice.py for a demo of talking to word. * Support for interfaces with variable arguments supported. diff --git a/com/win32com/HTML/GeneratedSupport.html b/com/win32com/HTML/GeneratedSupport.html index b6fa50f74d..9cbb548bca 100644 --- a/com/win32com/HTML/GeneratedSupport.html +++ b/com/win32com/HTML/GeneratedSupport.html @@ -26,7 +26,7 @@

    Usage

    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)

    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.

    Using makepy to help with the runtime generation

    -

    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 cant 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!

    +

    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!

    win32com.client.gencache functions

    def MakeModuleForTypelib(typelibCLSID, lcid, major, minor, progressInstance = None):

    Generate support for a type library.

    diff --git a/com/win32com/changes.txt b/com/win32com/changes.txt index 266d231f96..3b3a0588e3 100644 --- a/com/win32com/changes.txt +++ b/com/win32com/changes.txt @@ -48,7 +48,7 @@ fixed (eg, all MSOffice test run both as dynamic and makepy - the only differenc speed. Note that Office97 can be _very_ slow at startup without makep support loaded. * Full support for Office 97. Note that Word97 has changed its object model, and -their "compatibility" layer doesnt work with Python - you will need to change any code +their "compatibility" layer doesn't work with Python - you will need to change any code that uses Word. See the win32com\test\testMSOffice.py for a demo of talking to word. * Support for interfaces with variable arguments supported. diff --git a/com/win32com/client/__init__.py b/com/win32com/client/__init__.py index 4c86d011de..967698ba8b 100644 --- a/com/win32com/client/__init__.py +++ b/com/win32com/client/__init__.py @@ -130,7 +130,7 @@ def DispatchEx( if clsctx is None: clsctx = pythoncom.CLSCTX_SERVER if machine is not None: - clsctx = clsctx & ~pythoncom.CLSCTX_INPROC + clsctx &= ~pythoncom.CLSCTX_INPROC if machine is None: serverInfo = None else: @@ -507,7 +507,7 @@ def __init__(self, oobj=None): if details.hresult != winerror.E_NOINTERFACE: raise oobj = oobj._oleobj_ - self.__dict__["_oleobj_"] = oobj # so we dont call __setattr__ + self.__dict__["_oleobj_"] = oobj # so we don't call __setattr__ def __dir__(self): lst = ( diff --git a/com/win32com/client/build.py b/com/win32com/client/build.py index 987f0ab3d3..8fc5d7c8c9 100644 --- a/com/win32com/client/build.py +++ b/com/win32com/client/build.py @@ -33,7 +33,7 @@ class NotSupportedException(Exception): - pass # Raised when we cant support a param type. + pass # Raised when we can't support a param type. DropIndirection = "DropIndirection" @@ -233,7 +233,7 @@ def _AddFunc_(self, typeinfo, fdesc, bForUser): hidden = (funcflags & pythoncom.FUNCFLAG_FHIDDEN) != 0 if invkind == pythoncom.INVOKE_PROPERTYGET: map = self.propMapGet - # This is not the best solution, but I dont think there is + # This is not the best solution, but I don't think there is # one without specific "set" syntax. # If there is a single PUT or PUTREF, it will function as a property. # If there are both, then the PUT remains a property, and the PUTREF @@ -251,7 +251,7 @@ def _AddFunc_(self, typeinfo, fdesc, bForUser): self.mapFuncs["Set" + name] = existing map = self.propMapPut # existing gets overwritten below. else: - map = self.propMapPut # first time weve seen it. + map = self.propMapPut # first time we've seen it. elif invkind == pythoncom.INVOKE_FUNC: map = self.mapFuncs @@ -262,7 +262,7 @@ def _AddFunc_(self, typeinfo, fdesc, bForUser): # sys.stderr.write("Warning - overwriting existing method/attribute %s\n" % name) map[name] = MapEntry(fdesc, names, doc, resultCLSID, resultDoc, hidden) # any methods that can't be reached via DISPATCH we return None - # for, so dynamic dispatch doesnt see it. + # for, so dynamic dispatch doesn't see it. if fdesc.funckind != pythoncom.FUNC_DISPATCH: return None return (name, map) @@ -328,15 +328,15 @@ def CountInOutOptArgs(self, argTuple): for argCheck in argTuple: inOut = argCheck[1] if inOut == 0: - ins = ins + 1 - out = out + 1 + ins += 1 + out += 1 else: if inOut & pythoncom.PARAMFLAG_FIN: - ins = ins + 1 + ins += 1 if inOut & pythoncom.PARAMFLAG_FOPT: - opts = opts + 1 + opts += 1 if inOut & pythoncom.PARAMFLAG_FOUT: - out = out + 1 + out += 1 return ins, out, opts def MakeFuncMethod(self, entry, name, bMakeClass=1): @@ -422,37 +422,24 @@ def MakeDispatchFuncMethod(self, entry, name, bMakeClass=1): repr(argsDesc), _BuildArgList(fdesc, names), ) - s = s + f"{linePrefix}\tif ret is not None:\n" + s += f"{linePrefix}\tif ret is not None:\n" if rd == pythoncom.VT_UNKNOWN: - s = ( - s - + f"{linePrefix}\t\t# See if this IUnknown is really an IDispatch\n" - ) - s = s + f"{linePrefix}\t\ttry:\n" - s = ( - s - + f"{linePrefix}\t\t\tret = ret.QueryInterface(pythoncom.IID_IDispatch)\n" - ) - s = s + f"{linePrefix}\t\texcept pythoncom.error:\n" - s = s + f"{linePrefix}\t\t\treturn ret\n" - s = ( - s - + f"{linePrefix}\t\tret = Dispatch(ret, {repr(name)}, {resclsid})\n" - ) - s = s + "%s\treturn ret" % (linePrefix) + s += f"{linePrefix}\t\t# See if this IUnknown is really an IDispatch\n" + s += f"{linePrefix}\t\ttry:\n" + s += f"{linePrefix}\t\t\tret = ret.QueryInterface(pythoncom.IID_IDispatch)\n" + s += f"{linePrefix}\t\texcept pythoncom.error:\n" + s += f"{linePrefix}\t\t\treturn ret\n" + s += f"{linePrefix}\t\tret = Dispatch(ret, {name!r}, {resclsid})\n" + s += "%s\treturn ret" % linePrefix elif rd == pythoncom.VT_BSTR: s = f"{linePrefix}\t# Result is a Unicode object\n" - s = ( - s - + "%s\treturn self._oleobj_.InvokeTypes(%d, LCID, %s, %s, %s%s)" - % ( - linePrefix, - id, - fdesc[4], - retDesc, - repr(argsDesc), - _BuildArgList(fdesc, names), - ) + s += "%s\treturn self._oleobj_.InvokeTypes(%d, LCID, %s, %s, %s%s)" % ( + linePrefix, + id, + fdesc[4], + retDesc, + repr(argsDesc), + _BuildArgList(fdesc, names), ) # else s remains None if s is None: @@ -500,7 +487,7 @@ def MakeVarArgsFuncMethod(self, entry, name, bMakeClass=1): class VTableItem(DispatchItem): def Build(self, typeinfo, attr, bForUser=1): DispatchItem.Build(self, typeinfo, attr, bForUser) - assert typeinfo is not None, "Cant build vtables without type info!" + assert typeinfo is not None, "Can't build vtables without type info!" meth_list = ( list(self.mapFuncs.values()) @@ -546,7 +533,7 @@ def _ResolveType(typerepr, itypeinfo): # We need to drop an indirection level on pointer to user defined interfaces. # eg, (VT_PTR, (VT_USERDEFINED, somehandle)) needs to become VT_DISPATCH # only when "somehandle" is an object. - # but (VT_PTR, (VT_USERDEFINED, otherhandle)) doesnt get the indirection dropped. + # but (VT_PTR, (VT_USERDEFINED, otherhandle)) doesn't get the indirection dropped. was_user = ( isinstance(subrepr, tuple) and subrepr[0] == pythoncom.VT_USERDEFINED ) @@ -624,7 +611,7 @@ def _BuildArgList(fdesc, names): # As per BuildCallList(), avoid huge lines. # Hack a "\n" at the end of every 5th name for i in range(0, len(names), 5): - names[i] = names[i] + "\n\t\t\t" + names[i] += "\n\t\t\t" return "," + ", ".join(names) @@ -644,7 +631,7 @@ def demunge_leading_underscores(className): def MakePublicAttributeName(className, is_global=False): # Given a class attribute that needs to be public, convert it to a # reasonable name. - # Also need to be careful that the munging doesnt + # Also need to be careful that the munging doesn't # create duplicates - eg, just removing a leading "_" is likely to cause # a clash. # if is_global is True, then the name is a global variable that may @@ -726,7 +713,7 @@ def BuildCallList( strval = "" if numOptArgs == -1: # Special value that says "var args after here" firstOptArg = numArgs - numArgs = numArgs - 1 + numArgs -= 1 else: firstOptArg = numArgs - numOptArgs for arg in range(numArgs): @@ -763,15 +750,15 @@ def BuildCallList( # This may still fail if the arg names are insane, but that seems # unlikely. See also _BuildArgList() if (arg + 1) % 5 == 0: - strval = strval + "\n" + strval += "\n" if is_comment: - strval = strval + "#" - strval = strval + "\t\t\t" - strval = strval + ", " + argName + strval += "#" + strval += "\t\t\t" + strval += ", " + argName if defArgVal: - strval = strval + "=" + defArgVal + strval += "=" + defArgVal if numOptArgs == -1: - strval = strval + ", *" + names[-1] + strval += ", *" + names[-1] return strval diff --git a/com/win32com/client/combrowse.py b/com/win32com/client/combrowse.py index a5e76a85ba..2f7dc4004a 100644 --- a/com/win32com/client/combrowse.py +++ b/com/win32com/client/combrowse.py @@ -235,11 +235,11 @@ def GetSubList(self): except win32api.error: fname = "" collected.append((lcid, platform, fname)) - lcidnum = lcidnum + 1 + lcidnum += 1 win32api.RegCloseKey(lcidkey) except ValueError: pass - num = num + 1 + num += 1 finally: win32ui.DoWaitCursor(0) win32api.RegCloseKey(key) @@ -462,7 +462,7 @@ def MakeReturnType(self, returnTypeDesc): first = returnTypeDesc[0] result = self.MakeReturnType(first) if first != pythoncom.VT_USERDEFINED: - result = result + " " + self.MakeReturnType(returnTypeDesc[1]) + result += " " + self.MakeReturnType(returnTypeDesc[1]) return result else: return self.MakeReturnTypeName(returnTypeDesc) @@ -481,16 +481,16 @@ def GetSubList(self): typ, flags, default = fd[8] val = self.MakeReturnType(typ) if flags: - val = "%s (Flags=%d, default=%s)" % (val, flags, default) + val += f" (Flags={flags}, default={default})" ret.append(browser.MakeHLI(val, "Return Type")) for argDesc in fd[2]: typ, flags, default = argDesc val = self.MakeReturnType(typ) if flags: - val = "%s (Flags=%d)" % (val, flags) + val += f" (Flags={flags})" if default is not None: - val = f"{val} (Default={default})" + val += f" (Default={default})" ret.append(browser.MakeHLI(val, "Argument")) try: @@ -581,12 +581,12 @@ def GetSubList(self): if versionFlt > bestVersion: bestVersion = versionFlt name = win32api.RegQueryValue(subKey, versionStr) - subNum = subNum + 1 + subNum += 1 finally: win32api.RegCloseKey(subKey) if name is not None: ret.append(HLIRegisteredTypeLibrary((keyName, versionStr), name)) - num = num + 1 + num += 1 finally: win32api.RegCloseKey(key) win32ui.DoWaitCursor(0) diff --git a/com/win32com/client/dynamic.py b/com/win32com/client/dynamic.py index 9dcfdd3f36..1bfca05a54 100644 --- a/com/win32com/client/dynamic.py +++ b/com/win32com/client/dynamic.py @@ -216,7 +216,7 @@ def __call__(self, *args): def __bool__(self): return True # ie "if object:" should always be "true" - without this, __len__ is tried. - # _Possibly_ want to defer to __len__ if available, but Im not sure this is + # _Possibly_ want to defer to __len__ if available, but I'm not sure this is # desirable??? def __repr__(self): @@ -426,7 +426,7 @@ def _make_method_(self, name): return None def _Release_(self): - """Cleanup object - like a close - to force cleanup when you dont + """Cleanup object - like a close - to force cleanup when you don't want to rely on Python's reference counting.""" for childCont in self._mapCachedItems_.values(): childCont._Release_() diff --git a/com/win32com/client/gencache.py b/com/win32com/client/gencache.py index 4e0a997495..6b5d569299 100644 --- a/com/win32com/client/gencache.py +++ b/com/win32com/client/gencache.py @@ -413,7 +413,7 @@ def ForgetAboutTypelibInterface(typelib_ob): try: del demandGeneratedTypeLibraries[info] except KeyError: - # Not worth raising an exception - maybe they dont know we only remember for demand generated, etc. + # Not worth raising an exception - maybe they don't know we only remember for demand generated, etc. print( f"ForgetAboutTypelibInterface:: Warning - type library with info {info} is not being remembered!" ) @@ -515,9 +515,9 @@ def EnsureModule( filePath = filePathPrefix + ".py" filePathPyc = filePathPrefix + ".py" if __debug__: - filePathPyc = filePathPyc + "c" + filePathPyc += "c" else: - filePathPyc = filePathPyc + "o" + filePathPyc += "o" # Verify that type library is up to date. # If we have a differing MinorVersion or genpy has bumped versions, update the file from . import genpy @@ -730,7 +730,7 @@ def Rebuild(verbose=1): """Rebuild the cache indexes from the file system.""" clsidToTypelib.clear() infos = GetGeneratedInfos() - if verbose and len(infos): # Dont bother reporting this when directory is empty! + if verbose and len(infos): # Don't bother reporting this when directory is empty! print("Rebuilding cache of generated files for COM support...") for info in infos: iid, lcid, major, minor = info @@ -742,7 +742,7 @@ def Rebuild(verbose=1): print( f"Could not add module {info} - {sys.exc_info()[0]}: {sys.exc_info()[1]}" ) - if verbose and len(infos): # Dont bother reporting this when directory is empty! + if verbose and len(infos): # Don't bother reporting this when directory is empty! print("Done.") _SaveDicts() diff --git a/com/win32com/client/genpy.py b/com/win32com/client/genpy.py index c8b88fd637..87c19ad1b6 100644 --- a/com/win32com/client/genpy.py +++ b/com/win32com/client/genpy.py @@ -272,7 +272,7 @@ def WriteVTableMap(self, generator): print("\t((", end=" ", file=stream) for name in names: print(repr(name), ",", end=" ", file=stream) - item_num = item_num + 1 + item_num += 1 if item_num % 5 == 0: print("\n\t\t\t", end=" ", file=stream) print( @@ -281,7 +281,7 @@ def WriteVTableMap(self, generator): file=stream, ) for arg in desc.args: - item_num = item_num + 1 + item_num += 1 if item_num % 5 == 0: print("\n\t\t\t", end=" ", file=stream) defval = build.MakeDefaultArgRepr(arg) @@ -479,7 +479,7 @@ def WriteClassBody(self, generator): lkey = "value" elif dispid == pythoncom.DISPID_NEWENUM: specialItems["_newenum"] = (entry, entry.desc.invkind, None) - continue # Dont build this one now! + continue # Don't build this one now! else: lkey = name.lower() if ( @@ -608,7 +608,7 @@ def WriteClassBody(self, generator): if defArgDesc is None: defArgDesc = "" else: - defArgDesc = defArgDesc + "," + defArgDesc += "," print( '\t\t"%s" : ((%s, LCID, %d, 0),(%s)),' % ( @@ -675,7 +675,7 @@ def WriteClassBody(self, generator): else: invkind = pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET resultCLSID = "None" - # If we dont have a good CLSID for the enum result, assume it is the same as the Item() method. + # If we don't have a good CLSID for the enum result, assume it is the same as the Item() method. if resultCLSID == "None" and "Item" in self.mapFuncs: resultCLSID = self.mapFuncs["Item"].GetResultCLSIDStr() print("\tdef __iter__(self):", file=stream) @@ -979,7 +979,7 @@ def _Build_Interface(self, type_info_tuple): def BuildOleItemsFromType(self): assert ( self.bBuildHidden - ), "This code doesnt look at the hidden flag - I thought everyone set it true!?!?!" + ), "This code doesn't look at the hidden flag - I thought everyone set it true!?!?!" oleItems = {} enumItems = {} recordItems = {} @@ -1005,7 +1005,7 @@ def BuildOleItemsFromType(self): newItem = RecordItem(info, attr, doc) recordItems[newItem.clsid] = newItem elif infotype == pythoncom.TKIND_ALIAS: - # We dont care about alias' - handled intrinsicly. + # We don't care about alias' - handled intrinsicly. continue elif infotype == pythoncom.TKIND_COCLASS: newItem, child_infos = self._Build_CoClass(type_info_tuple) @@ -1317,7 +1317,7 @@ def generate_child(self, child, dir): assert ( found - ), f"Cant find the '{child}' interface in the CoClasses, or the interfaces" + ), f"Can't find the '{child}' interface in the CoClasses, or the interfaces" # Make a map of iid: dispitem, vtableitem) items = {} for key, value in oleItems.items(): diff --git a/com/win32com/client/makepy.py b/com/win32com/client/makepy.py index 99158deb62..79e66fb674 100644 --- a/com/win32com/client/makepy.py +++ b/com/win32com/client/makepy.py @@ -208,7 +208,7 @@ def GetTypeLibsForSpec(arg): print("Could not locate a type library matching '%s'" % (arg)) for spec in tlbs: # Version numbers not always reliable if enumerated from registry. - # (as some libs use hex, other's dont. Both examples from MS, of course.) + # (as some libs use hex, other's don't. Both examples from MS, of course.) if spec.dll is None: tlb = pythoncom.LoadRegTypeLib( spec.clsid, spec.major, spec.minor, spec.lcid @@ -387,9 +387,9 @@ def main(): elif o == "-o": outputName = v elif o == "-v": - verboseLevel = verboseLevel + 1 + verboseLevel += 1 elif o == "-q": - verboseLevel = verboseLevel - 1 + verboseLevel -= 1 elif o == "-i": if len(args) == 0: ShowInfo(None) diff --git a/com/win32com/client/selecttlb.py b/com/win32com/client/selecttlb.py index 56197128f5..bf8627f5ff 100644 --- a/com/win32com/client/selecttlb.py +++ b/com/win32com/client/selecttlb.py @@ -25,7 +25,7 @@ def __init__(self, clsid, lcid, major, minor, flags=0): def __getitem__(self, item): if item == 0: return self.ver_desc - raise IndexError("Cant index me!") + raise IndexError("Can't index me!") def __lt__(self, other): me = ( @@ -83,7 +83,7 @@ def EnumKeys(root): val = "" # code using this assumes a string. ret.append((item, val)) - index = index + 1 + index += 1 return ret diff --git a/com/win32com/client/tlbrowse.py b/com/win32com/client/tlbrowse.py index c20be148fb..ac83e34324 100644 --- a/com/win32com/client/tlbrowse.py +++ b/com/win32com/client/tlbrowse.py @@ -155,12 +155,9 @@ def _GetMainInfoTypes(self): typeFlags = attr[11] desc = doc[0] - desc = ( - desc - + f", Flags=0x{flags:x}, typeKind=0x{typeKind:x}, typeFlags=0x{typeFlags:x}" - ) + desc += f", Flags=0x{flags:x}, typeKind=0x{typeKind:x}, typeFlags=0x{typeFlags:x}" if flags & pythoncom.IMPLTYPEFLAG_FSOURCE: - desc = desc + "(Source)" + desc += "(Source)" infos.append(("Implements", desc)) return infos diff --git a/com/win32com/makegw/makegw.py b/com/win32com/makegw/makegw.py index 3170f4ade8..c144e28a9c 100644 --- a/com/win32com/makegw/makegw.py +++ b/com/win32com/makegw/makegw.py @@ -235,21 +235,17 @@ def _write_ifc_cpp(f, interface): val = argCvt.GetFormatChar() if val: f.write("\t" + argCvt.GetAutoduckString() + "\n") - formatChars = formatChars + val - argsParseTuple = ( - argsParseTuple + ", " + argCvt.GetParseTupleArg() - ) - codePobjects = ( - codePobjects + argCvt.DeclareParseArgTupleInputConverter() - ) - codePost = codePost + argCvt.GetParsePostCode() + formatChars += val + argsParseTuple += ", " + argCvt.GetParseTupleArg() + codePobjects += argCvt.DeclareParseArgTupleInputConverter() + codePost += argCvt.GetParsePostCode() needConversion = needConversion or argCvt.NeedUSES_CONVERSION() - cleanup = cleanup + argCvt.GetInterfaceArgCleanup() - cleanup_gil = cleanup_gil + argCvt.GetInterfaceArgCleanupGIL() + cleanup += argCvt.GetInterfaceArgCleanup() + cleanup_gil += argCvt.GetInterfaceArgCleanupGIL() comArgName, comArgDeclString = argCvt.GetInterfaceCppObjectInfo() if comArgDeclString: # If we should declare a variable - codeCobjects = codeCobjects + "\t%s;\n" % (comArgDeclString) - argsCOM = argsCOM + ", " + comArgName + codeCobjects += "\t%s;\n" % comArgDeclString + argsCOM += ", " + comArgName except makegwparse.error_not_supported as why: f.write( f'// *** The input argument {arg.name} of type "{arg.raw_type}" was not processed ***\n// Please check the conversion function is appropriate and exists!\n' @@ -259,16 +255,12 @@ def _write_ifc_cpp(f, interface): f.write( f"\t// @pyparm |{arg.name}||Description for {arg.name}\n" ) - codePost = ( - codePost - + f"\tif (bPythonIsHappy && !PyObject_As{arg.type}( ob{arg.name}, &{arg.name} )) bPythonIsHappy = FALSE;\n" - ) + codePost += f"\tif (bPythonIsHappy && !PyObject_As{arg.type}( ob{arg.name}, &{arg.name} )) bPythonIsHappy = FALSE;\n" + formatChars += "O" + argsParseTuple += ", &ob%s" % arg.name - formatChars = formatChars + "O" - argsParseTuple = argsParseTuple + ", &ob%s" % (arg.name) - - argsCOM = argsCOM + ", " + arg.name - cleanup = cleanup + f"\tPyObject_Free{arg.type}({arg.name});\n" + argsCOM += ", " + arg.name + cleanup += f"\tPyObject_Free{arg.type}({arg.name});\n" if needConversion: f.write("\tUSES_CONVERSION;\n") @@ -305,11 +297,11 @@ def _write_ifc_cpp(f, interface): argCvt = makegwparse.make_arg_converter(arg) formatChar = argCvt.GetFormatChar() if formatChar: - formatChars = formatChars + formatChar - codePre = codePre + argCvt.GetBuildForInterfacePreCode() - codePost = codePost + argCvt.GetBuildForInterfacePostCode() - codeVarsPass = codeVarsPass + ", " + argCvt.GetBuildValueArg() - codeDecl = codeDecl + argCvt.DeclareParseArgTupleInputConverter() + formatChars += formatChar + codePre += argCvt.GetBuildForInterfacePreCode() + codePost += argCvt.GetBuildForInterfacePostCode() + codeVarsPass += ", " + argCvt.GetBuildValueArg() + codeDecl += argCvt.DeclareParseArgTupleInputConverter() except makegwparse.error_not_supported as why: f.write( f'// *** The output argument {arg.name} of type "{arg.raw_type}" was not processed ***\n// {why}\n' @@ -445,7 +437,7 @@ def _write_gw_cpp(f, interface): if method.args: for arg in method.args: if arg.HasAttribute("out"): - cout = cout + 1 + cout += 1 if arg.indirectionLevel == 2: f.write("\tif (%s==NULL) return E_POINTER;\n" % arg.name) if arg.HasAttribute("in"): @@ -456,13 +448,11 @@ def _write_gw_cpp(f, interface): needConversion = needConversion or argCvt.NeedUSES_CONVERSION() if formatchar: - formatChars = formatChars + formatchar - codeVars = ( - codeVars + argCvt.DeclareParseArgTupleInputConverter() - ) - argStr = argStr + ", " + argCvt.GetBuildValueArg() - codePre = codePre + argCvt.GetBuildForGatewayPreCode() - codePost = codePost + argCvt.GetBuildForGatewayPostCode() + formatChars += formatchar + codeVars += argCvt.DeclareParseArgTupleInputConverter() + argStr += ", " + argCvt.GetBuildValueArg() + codePre += argCvt.GetBuildForGatewayPreCode() + codePost += argCvt.GetBuildForGatewayPostCode() except makegwparse.error_not_supported as why: f.write( f'// *** The input argument {arg.name} of type "{arg.raw_type}" was not processed ***\n// - Please ensure this conversion function exists, and is appropriate\n// - {why}\n' @@ -473,9 +463,9 @@ def _write_gw_cpp(f, interface): f.write( f'\tif (ob{arg.name}==NULL) return MAKE_PYCOM_GATEWAY_FAILURE_CODE("{method.name}");\n' ) - codePost = codePost + "\tPy_DECREF(ob%s);\n" % arg.name - formatChars = formatChars + "O" - argStr = argStr + ", ob%s" % (arg.name) + codePost += "\tPy_DECREF(ob%s);\n" % arg.name + formatChars += "O" + argStr += ", ob%s" % arg.name if needConversion: f.write("\tUSES_CONVERSION;\n") @@ -510,14 +500,10 @@ def _write_gw_cpp(f, interface): argCvt.SetGatewayMode() val = argCvt.GetFormatChar() if val: - formatChars = formatChars + val - argsParseTuple = ( - argsParseTuple + ", " + argCvt.GetParseTupleArg() - ) - codePobjects = ( - codePobjects + argCvt.DeclareParseArgTupleInputConverter() - ) - codePost = codePost + argCvt.GetParsePostCode() + formatChars += val + argsParseTuple += ", " + argCvt.GetParseTupleArg() + codePobjects += argCvt.DeclareParseArgTupleInputConverter() + codePost += argCvt.GetParsePostCode() needConversion = needConversion or argCvt.NeedUSES_CONVERSION() except makegwparse.error_not_supported as why: f.write( diff --git a/com/win32com/makegw/makegwparse.py b/com/win32com/makegw/makegwparse.py index a41de3d935..a1e45edd64 100644 --- a/com/win32com/makegw/makegwparse.py +++ b/com/win32com/makegw/makegwparse.py @@ -250,9 +250,9 @@ def GetBuildForGatewayPreCode(self): def GetParsePostCode(self): s = "\t" if self.gatewayMode: - s = s + self._IndirectPrefix(self._GetDeclaredIndirection(), 0) - s = s + self.arg.name - s = s + " = (float)dbl%s;\n" % self.arg.name + s += self._IndirectPrefix(self._GetDeclaredIndirection(), 0) + s += self.arg.name + s += " = (float)dbl%s;\n" % self.arg.name return s @@ -289,9 +289,9 @@ def GetBuildForGatewayPreCode(self): def GetParsePostCode(self): s = "\t" if self.gatewayMode: - s = s + self._IndirectPrefix(self._GetDeclaredIndirection(), 0) - s = s + self.arg.name - s = s + " = i%s;\n" % self.arg.name + s += self._IndirectPrefix(self._GetDeclaredIndirection(), 0) + s += self.arg.name + s += " = i%s;\n" % self.arg.name return s @@ -456,7 +456,7 @@ def __init__(self, arg, builtinIndirection, declaredIndirection=0): if arg.indirectionLevel == 0 and arg.unc_type[:2] == "LP": arg.unc_type = arg.unc_type[2:] # reduce the builtin and increment the declaration - arg.indirectionLevel = arg.indirectionLevel + 1 + arg.indirectionLevel += 1 builtinIndirection = 0 ArgFormatterPythonCOM.__init__( self, arg, builtinIndirection, declaredIndirection @@ -806,7 +806,7 @@ def HasAttribute(self, typ): def GetRawDeclaration(self): ret = f"{self.raw_type} {self.name}" if self.arrayDecl: - ret = ret + "[]" + ret += "[]" return ret diff --git a/com/win32com/server/connect.py b/com/win32com/server/connect.py index 6efe4f7111..e99555a046 100644 --- a/com/win32com/server/connect.py +++ b/com/win32com/server/connect.py @@ -52,7 +52,7 @@ def Advise(self, pUnk): ) except pythoncom.com_error: raise COMException(scode=olectl.CONNECT_E_NOCONNECTION) - self.cookieNo = self.cookieNo + 1 + self.cookieNo += 1 self.connections[self.cookieNo] = interface return self.cookieNo diff --git a/com/win32com/server/exception.py b/com/win32com/server/exception.py index 043933fa0e..a6b3111fec 100644 --- a/com/win32com/server/exception.py +++ b/com/win32com/server/exception.py @@ -18,7 +18,7 @@ # Note that we derive from com_error, which derives from builtin Exception -# Also note that we dont support "self.args", as we dont support tuple-unpacking +# Also note that we don't support "self.args", as we don't support tuple-unpacking class COMException(pythoncom.com_error): """An Exception object that is understood by the framework. @@ -58,7 +58,7 @@ def __init__( # convert a WIN32 error into an HRESULT scode = scode or hresult - if scode and scode != 1: # We dont want S_FALSE mapped! + if scode and scode != 1: # We don't want S_FALSE mapped! if scode >= -32768 and scode < 32768: # this is HRESULT_FROM_WIN32() scode = -2147024896 | (scode & 0x0000FFFF) diff --git a/com/win32com/server/policy.py b/com/win32com/server/policy.py index f234ed83b4..36f1bdd46e 100644 --- a/com/win32com/server/policy.py +++ b/com/win32com/server/policy.py @@ -608,7 +608,7 @@ def _GetTypeInfo_(self, index, lcid): def _allocnextdispid(self, last_dispid): while 1: - last_dispid = last_dispid + 1 + last_dispid += 1 if ( last_dispid not in self._dispid_to_func_ and last_dispid not in self._dispid_to_get_ @@ -631,7 +631,7 @@ def _invokeex_(self, dispid, lcid, wFlags, args, kwArgs, serviceProvider): try: func = getattr(self._obj_, funcname) except AttributeError: - # May have a dispid, but that doesnt mean we have the function! + # May have a dispid, but that doesn't mean we have the function! raise COMException(scode=winerror.DISP_E_MEMBERNOTFOUND) # Should check callable here try: @@ -780,7 +780,7 @@ def resolve_func(spec): idx = spec.rindex(".") mname = spec[:idx] fname = spec[idx + 1 :] - # Dont attempt to optimize by looking in sys.modules, + # Don't attempt to optimize by looking in sys.modules, # as another thread may also be performing the import - this # way we take advantage of the built-in import lock. module = _import_module(mname) @@ -818,5 +818,5 @@ def _import_module(mname): # still reference them here. These will end up being removed. try: from .dispatcher import DispatcherTrace, DispatcherWin32trace -except ImportError: # Quite likely a frozen executable that doesnt need dispatchers +except ImportError: # Quite likely a frozen executable that doesn't need dispatchers pass diff --git a/com/win32com/server/register.py b/com/win32com/server/register.py index 2074782dc1..3c3a5dcfa9 100644 --- a/com/win32com/server/register.py +++ b/com/win32com/server/register.py @@ -214,9 +214,9 @@ def RegisterServer( sys.frozen ), "pythoncom is frozen, but sys.frozen is not set - don't know the context!" if sys.frozen == "dll": - clsctx = clsctx & pythoncom.CLSCTX_INPROC_SERVER + clsctx &= pythoncom.CLSCTX_INPROC_SERVER else: - clsctx = clsctx & pythoncom.CLSCTX_LOCAL_SERVER + clsctx &= pythoncom.CLSCTX_LOCAL_SERVER # Now setup based on the clsctx left over. if clsctx & pythoncom.CLSCTX_INPROC_SERVER: # get the module to use for registration. @@ -304,7 +304,7 @@ def RegisterServer( if addPyComCat is None: addPyComCat = pythoncom.frozen == 0 if addPyComCat: - catids = catids + [CATID_PythonCOMServer] + catids.append(CATID_PythonCOMServer) # Set up the implemented categories if catids: @@ -360,7 +360,7 @@ def GetUnregisterServerKeys(clsid, progID=None, verProgID=None, customKeys=None) ret.append(("AppID\\%s" % str(clsid), win32con.HKEY_CLASSES_ROOT)) # Any custom keys? if customKeys: - ret = ret + customKeys + ret.extend(customKeys) return ret @@ -536,7 +536,7 @@ def UnregisterInfoClasses(*classes, **flags): verProgID = _get(cls, "_reg_verprogid_") customKeys = _get(cls, "_reg_remove_keys_") - ret = ret + GetUnregisterServerKeys(clsid, progID, verProgID, customKeys) + ret.extend(GetUnregisterServerKeys(clsid, progID, verProgID, customKeys)) return ret diff --git a/com/win32com/src/ErrorUtils.cpp b/com/win32com/src/ErrorUtils.cpp index a0a48d1bef..ff16d99858 100644 --- a/com/win32com/src/ErrorUtils.cpp +++ b/com/win32com/src/ErrorUtils.cpp @@ -155,7 +155,8 @@ static BOOL PyCom_ExcepInfoFromServerExceptionInstance(PyObject *v, EXCEPINFO *p return TRUE; } -BSTR BstrFromOb(PyObject *value) { +BSTR BstrFromOb(PyObject *value) +{ BSTR result = NULL; if (!PyWinObject_AsBstr(value, &result, TRUE, NULL)) { PyCom_LoggerNonServerException(NULL, L"Failed to convert exception element to a string"); @@ -278,20 +279,15 @@ void PyCom_CleanupExcepInfo(EXCEPINFO *pexcepinfo) } } -HRESULT PyCom_CheckIEnumNextResult(HRESULT hr, REFIID riid) { +HRESULT PyCom_CheckIEnumNextResult(HRESULT hr, REFIID riid) +{ return PyCom_SetCOMErrorFromSimple( - hr, - riid, - L"Could not convert the result from Next()/Clone() into the required COM interface" - ); + hr, riid, L"Could not convert the result from Next()/Clone() into the required COM interface"); } -HRESULT PyCom_HandleIEnumNoSequence(REFIID riid) { - return PyCom_SetCOMErrorFromSimple( - E_FAIL, - riid, - L"Next() did not return a sequence of objects" - ); +HRESULT PyCom_HandleIEnumNoSequence(REFIID riid) +{ + return PyCom_SetCOMErrorFromSimple(E_FAIL, riid, L"Next() did not return a sequence of objects"); } HRESULT PyCom_SetCOMErrorFromSimple(HRESULT hr, REFIID riid /* = IID_NULL */, const WCHAR *description /* = NULL*/) @@ -362,7 +358,7 @@ void PyCom_StreamMessage(const WCHAR *pszMessageText) { OutputDebugString(pszMessageText); // PySys_WriteStderr has an internal 1024 limit due to varargs. - // weve already resolved them, so we gotta do it the hard way + // we've already resolved them, so we gotta do it the hard way // We can't afford to screw with the Python exception state PyObject *typ, *val, *tb; PyErr_Fetch(&typ, &val, &tb); @@ -370,7 +366,7 @@ void PyCom_StreamMessage(const WCHAR *pszMessageText) if (pyfile) { PyObject *obUnicode = PyWinObject_FromWCHAR(pszMessageText); if (obUnicode) { - if (PyFile_WriteObject(obUnicode, pyfile, Py_PRINT_RAW) != 0) { + if (PyFile_WriteObject(obUnicode, pyfile, Py_PRINT_RAW) != 0) { // eeek - Python error writing this error - write it to stdout. fwprintf(stdout, L"%s", pszMessageText); } diff --git a/com/win32com/src/MiscTypes.cpp b/com/win32com/src/MiscTypes.cpp index de93a35fc3..64808d6f0d 100644 --- a/com/win32com/src/MiscTypes.cpp +++ b/com/win32com/src/MiscTypes.cpp @@ -32,8 +32,8 @@ static PyTypeObject PyInterfaceType_Type = { "Define the behavior of a PythonCOM Interface type.", /* tp_doc */ }; -PyComTypeObject::PyComTypeObject(const char *name, PyComTypeObject *pBase, Py_ssize_t typeSize, struct PyMethodDef *methodList, - PyIUnknown *(*thector)(IUnknown *)) +PyComTypeObject::PyComTypeObject(const char *name, PyComTypeObject *pBase, Py_ssize_t typeSize, + struct PyMethodDef *methodList, PyIUnknown *(*thector)(IUnknown *)) { // originally, this copied the typeobject of the parent, but as it is impossible // to guarantee order of static object construction, I went this way. This is @@ -75,7 +75,7 @@ PyComTypeObject::PyComTypeObject(const char *name, PyComTypeObject *pBase, Py_ss *((PyTypeObject *)this) = type_template; ctor = thector; - // cast away const, as Python doesnt use it. + // cast away const, as Python doesn't use it. tp_name = (char *)name; tp_basicsize = typeSize; ((PyObject *)this)->ob_type = &PyType_Type; diff --git a/com/win32com/src/PyComHelpers.cpp b/com/win32com/src/PyComHelpers.cpp index b6ee18bdfe..5de3bff272 100644 --- a/com/win32com/src/PyComHelpers.cpp +++ b/com/win32com/src/PyComHelpers.cpp @@ -270,12 +270,12 @@ PyObject *PyCom_PyObjectFromSTATSTG(STATSTG *pStat) pStat->type, // @tupleitem 1|int|type|Indicates the type of storage object. This is one of the values from the // storagecon.STGTY_* values. obSize, // @tupleitem 2||size|Specifies the size in bytes of the stream or byte array. - obmtime, // @tupleitem 3||modificationTime|Indicates the last modification time for this storage, - // stream, or byte array. - obctime, // @tupleitem 4||creationTime|Indicates the creation time for this storage, stream, or byte - // array. - obatime, // @tupleitem 5||accessTime|Indicates the last access time for this storage, stream or byte - // array. + obmtime, // @tupleitem 3||modificationTime|Indicates the last modification time for this storage, + // stream, or byte array. + obctime, // @tupleitem 4||creationTime|Indicates the creation time for this storage, stream, or + // byte array. + obatime, // @tupleitem 5||accessTime|Indicates the last access time for this storage, stream or + // byte array. pStat->grfMode, // @tupleitem 6|int|mode|Indicates the access mode specified when the object was opened. This // member is only valid in calls to Stat methods. pStat->grfLocksSupported, // @tupleitem 7|int|locksSupported|Indicates the types of region locking supported by @@ -356,9 +356,8 @@ BOOL PyCom_PyObjectAsSTGOPTIONS(PyObject *obstgoptions, STGOPTIONS **ppstgoption (*ppstgoptions)->pwcsTemplateFile = NULL; dummy_tuple = PyTuple_New(0); ret = PyArg_ParseTupleAndKeywords(dummy_tuple, obstgoptions, "|lllU", stgmembers, &(*ppstgoptions)->usVersion, - &(*ppstgoptions)->reserved, &(*ppstgoptions)->ulSectorSize, - &ptw->u) - && ((*ppstgoptions)->pwcsTemplateFile=ptw->u2w()); + &(*ppstgoptions)->reserved, &(*ppstgoptions)->ulSectorSize, &ptw->u) && + ((*ppstgoptions)->pwcsTemplateFile = ptw->u2w()); Py_DECREF(dummy_tuple); if (!ret) { PyErr_Clear(); diff --git a/com/win32com/src/PyFactory.cpp b/com/win32com/src/PyFactory.cpp index 59fe29ba19..101b5336a7 100644 --- a/com/win32com/src/PyFactory.cpp +++ b/com/win32com/src/PyFactory.cpp @@ -77,7 +77,7 @@ STDMETHODIMP CPyFactory::CreateInstance(IUnknown *punkOuter, REFIID riid, void * hr = E_FAIL; } } - Py_XDECREF(pNewInstance); // Dont need it any more. + Py_XDECREF(pNewInstance); // Don't need it any more. } PyCom_DLLReleaseRef(); return hr; diff --git a/com/win32com/src/PyGatewayBase.cpp b/com/win32com/src/PyGatewayBase.cpp index ef48bd159d..b6da6ac041 100644 --- a/com/win32com/src/PyGatewayBase.cpp +++ b/com/win32com/src/PyGatewayBase.cpp @@ -87,7 +87,7 @@ PyGatewayBase::PyGatewayBase(PyObject *instance) m_pBaseObject = NULL; m_cRef = 1; m_pPyObject = instance; - Py_XINCREF(instance); // instance should never be NULL - but whats an X between friends! + Py_XINCREF(instance); // instance should never be NULL - but what's an X between friends! PyCom_DLLAddRef(); @@ -377,7 +377,7 @@ static HRESULT invoke_setup(DISPPARAMS FAR *params, LCID lcid, PyObject **pPyArg params->cNamedArgs != 1 || params->rgdispidNamedArgs[0] != DISPID_PROPERTYPUT ? params->cNamedArgs : 0; for (i = 0; i < numNamedArgs; i++) { - // make sure its not a special DISPID we don't understand. + // make sure it's not a special DISPID we don't understand. if (params->rgdispidNamedArgs[i] < 0) return DISP_E_PARAMNOTFOUND; numArgs = max(numArgs, (UINT)params->rgdispidNamedArgs[i] + 1); @@ -492,8 +492,8 @@ static void fill_byref_offsets(DISPPARAMS *pDispParams, unsigned *pOffsets, unsi // named params could have their dispid in any order - so we sort // them - but only if necessary if (numNamedArgs && ioffset < noffsets) { - // NOTE: optimizations possible - if only 1 named param its - // obvious which one it is! If 2 params its very easy to work + // NOTE: optimizations possible - if only 1 named param it's + // obvious which one it is! If 2 params it's very easy to work // it out - so we should only qsort for 3 or more. NPI *npi = (NPI *)_malloca(sizeof(NPI) * pDispParams->cNamedArgs); // death if we fail :) for (unsigned i = 0; i < pDispParams->cNamedArgs; i++) { @@ -580,7 +580,7 @@ static HRESULT invoke_finish(PyObject *dispatcher, /* The dispatcher for the // here - otherwise returning an array of objects would be difficult. // NOTE: Although this is not ideal, it would be evil if the parameters determined // how the Python result was unpacked. VB, for example, will often pass everything - // BYREF, but Python wont. This would mean Python and VB would see different results + // BYREF, but Python won't. This would mean Python and VB would see different results // from the same function. if (PyTuple_Check(userResult)) { unsigned cUserResult = PyWin_SAFE_DOWNCAST(PyTuple_Size(userResult), Py_ssize_t, UINT); @@ -616,7 +616,7 @@ static HRESULT invoke_finish(PyObject *dispatcher, /* The dispatcher for the ob = PyTuple_GetItem(userResult, i + firstByRef); if (!ob) goto done; - Py_INCREF(ob); // tuple fetch doesnt do this! + Py_INCREF(ob); // tuple fetch doesn't do this! // Need to use the ArgHelper to get correct BYREF semantics. PythonOleArgHelper arghelper; arghelper.m_reqdType = V_VT(pv); @@ -847,7 +847,6 @@ STDMETHODIMP PyGatewayBase::GetNameSpaceParent(IUnknown **ppunk) return PyCom_SetCOMErrorFromPyException(IID_IDispatchEx); } - //////////////////////////////////////////////////////////////////////////// // // Extra Python helpers... diff --git a/com/win32com/src/PyIBase.cpp b/com/win32com/src/PyIBase.cpp index d303b650d3..10f26b4429 100644 --- a/com/win32com/src/PyIBase.cpp +++ b/com/win32com/src/PyIBase.cpp @@ -3,7 +3,8 @@ static PyComTypeObject type("PyIBase", NULL, sizeof(PyIBase), NULL, NULL); -PyIBase::PyIBase() { +PyIBase::PyIBase() +{ // ob_type will be overridden to the real type once the subclasses // constructor body runs, however, _Py_NewReference() sometimes wants // ob_type to be valid (particularly when tracemalloc is enabled!) diff --git a/com/win32com/src/PyIDispatch.cpp b/com/win32com/src/PyIDispatch.cpp index 71b4541b2b..d308e1b765 100644 --- a/com/win32com/src/PyIDispatch.cpp +++ b/com/win32com/src/PyIDispatch.cpp @@ -666,7 +666,7 @@ PyObject *PyIDispatchEx::InvokeEx(PyObject *self, PyObject *args) } // TODO - We do not yet support the Type Description here - // (Im not even sure if we need it!) + // (I'm not even sure if we need it!) if (types != Py_None || obReturnDesc != Py_None) { PyErr_SetString(PyExc_TypeError, "Type descriptions are not yet supported."); return NULL; diff --git a/com/win32com/src/PyRecord.cpp b/com/win32com/src/PyRecord.cpp index 05e93d3fe2..df389bf79f 100644 --- a/com/win32com/src/PyRecord.cpp +++ b/com/win32com/src/PyRecord.cpp @@ -157,7 +157,7 @@ PyObject *pythoncom_GetRecordFromGuids(PyObject *self, PyObject *args) &obInfoGuid, // @pyparm |infoIID||The GUID of the record info in the library &obdata)) // @pyparm string or buffer|data|None|The raw data to initialize the record with. return NULL; - PyWinBufferView pybuf(obdata, false, true); // None ok + PyWinBufferView pybuf(obdata, false, true); // None ok if (!pybuf.ok()) return NULL; GUID guid, infoGuid; @@ -493,7 +493,7 @@ PyObject *PyRecord::getattro(PyObject *self, PyObject *obname) return PyCom_BuildPyException(hr, pyrec->pri, IID_IRecordInfo); } - // Short-circuit sub-structs and arrays here, so we dont allocate a new chunk + // Short-circuit sub-structs and arrays here, so we don't allocate a new chunk // of memory and copy it - we need sub-structs to persist. if (V_VT(&vret) == (VT_BYREF | VT_RECORD)) return new PyRecord(V_RECORDINFO(&vret), V_RECORD(&vret), pyrec->owner); diff --git a/com/win32com/src/PythonCOM.cpp b/com/win32com/src/PythonCOM.cpp index 906ae93a37..6b76b7c98c 100644 --- a/com/win32com/src/PythonCOM.cpp +++ b/com/win32com/src/PythonCOM.cpp @@ -752,7 +752,7 @@ static PyObject *pythoncom_WrapObject(PyObject *self, PyObject *args) IUnknown *pLook = (IUnknown *)(*ppv); IInternalUnwrapPythonObject *pTemp; if (pLook->QueryInterface(IID_IInternalUnwrapPythonObject, (void **)&pTemp)==S_OK) { - // One of our objects, so set the base object if it doesnt already have one + // One of our objects, so set the base object if it doesn't already have one PyGatewayBase *pG = (PyGatewayBase *)pTemp; // Eeek - just these few next lines need to be thread-safe :-( PyWin_AcquireGlobalLock(); @@ -1299,7 +1299,6 @@ static PyObject *pythoncom_CoReleaseMarshalData(PyObject *self, PyObject *args) return Py_None; } - // @pymethod |pythoncom|CoGetObject|Converts a display name into a moniker that identifies the object // named, and then binds to the object identified by the moniker. static PyObject *pythoncom_CoGetObject(PyObject *self, PyObject *args) @@ -2186,7 +2185,7 @@ PYWIN_MODULE_INIT_FUNC(pythoncom) HRESULT hr = PyCom_CoInitializeEx(NULL, coinit_flags); if (hr == E_NOTIMPL) // Special return val from PyCom_Co.. indicates not DCOM. hr = PyCom_CoInitialize(NULL); - // If HR fails, we really dont care - the import should work. User can + // If HR fails, we really don't care - the import should work. User can // manually CoInit() to see! PYWIN_MODULE_INIT_PREPARE(pythoncom, pythoncom_methods, "A module, encapsulating the OLE automation API"); @@ -2201,10 +2200,8 @@ PYWIN_MODULE_INIT_FUNC(pythoncom) PyDict_SetItemString(dict, "ServerInterfaces", g_obPyCom_MapGatewayIIDToName); PyDict_SetItemString(dict, "InterfaceNames", g_obPyCom_MapInterfaceNameToIID); - if (PyType_Ready(&PyOleEmptyType) == -1 || - PyType_Ready(&PyOleMissingType) == -1 || - PyType_Ready(&PyOleArgNotFoundType) == -1 || - PyType_Ready(&PyOleNothingType) == -1) + if (PyType_Ready(&PyOleEmptyType) == -1 || PyType_Ready(&PyOleMissingType) == -1 || + PyType_Ready(&PyOleArgNotFoundType) == -1 || PyType_Ready(&PyOleNothingType) == -1) PYWIN_MODULE_INIT_RETURN_ERROR; g_obEmpty = new PyOleEmpty; PyDict_SetItemString(dict, "Empty", g_obEmpty); @@ -2628,12 +2625,12 @@ PYWIN_MODULE_INIT_FUNC(pythoncom) ADD_CONSTANT(DESCKIND_FUNCDESC); ADD_CONSTANT(DESCKIND_VARDESC); - // Expose the frozen flag, as Python itself doesnt!! + // Expose the frozen flag, as Python itself doesn't!! // @prop int|frozen|1 if the host is a frozen program, else 0 AddConstant(dict, "frozen", Py_FrozenFlag); // And finally some gross hacks relating to DCOM - // Im really not sure what a better option is! + // I'm really not sure what a better option is! // // If these #error pragma's fire it means this needs revisiting for // an upgrade to the MSVC header files! diff --git a/com/win32com/src/dllmain.cpp b/com/win32com/src/dllmain.cpp index 230f85a371..bac646ece1 100644 --- a/com/win32com/src/dllmain.cpp +++ b/com/win32com/src/dllmain.cpp @@ -39,7 +39,7 @@ static BOOL hasInitialized = FALSE; void PyCom_DLLAddRef(void) { - // Must be thread-safe, although cant have the Python lock! + // Must be thread-safe, although can't have the Python lock! CEnterLeaveFramework _celf; LONG cnt = InterlockedIncrement(&g_cLockCount); if (cnt == 1) { // First call @@ -83,7 +83,7 @@ void PyCom_DLLReleaseRef(void) /*** NOTE: We no longer finalize Python EVER in the COM world see pycom-dev mailing list archives from April 2000 for why ***/ - // Must be thread-safe, although cant have the Python lock! + // Must be thread-safe, although can't have the Python lock! // only needed when we finalize. // CEnterLeaveFramework _celf; LONG cnt = InterlockedDecrement(&g_cLockCount); @@ -161,7 +161,7 @@ typedef HRESULT(WINAPI *PFNCoInitializeEx)(LPVOID pvReserved, DWORD dwCoInit); // XXX - Needs more thought about threading implications. HRESULT PyCom_CoInitializeEx(LPVOID reserved, DWORD dwInit) { - // Must be thread-safe, although doesnt need the Python lock. + // Must be thread-safe, although doesn't need the Python lock. CEnterLeaveFramework _celf; if (g_bCoInitThreadHasInit && g_dwCoInitThread == GetCurrentThreadId()) return S_OK; @@ -197,7 +197,7 @@ HRESULT PyCom_CoInitializeEx(LPVOID reserved, DWORD dwInit) HRESULT PyCom_CoInitialize(LPVOID reserved) { - // Must be thread-safe, although doesnt need the Python lock. + // Must be thread-safe, although doesn't need the Python lock. CEnterLeaveFramework _celf; // If our "main" thread has ever called this before, just // ignore it. If it is another thread, then that thread @@ -220,7 +220,7 @@ HRESULT PyCom_CoInitialize(LPVOID reserved) void PyCom_CoUninitialize() { - // Must be thread-safe, although doesnt need the Python lock. + // Must be thread-safe, although doesn't need the Python lock. CEnterLeaveFramework _celf; if (g_dwCoInitThread == GetCurrentThreadId()) { // being asked to terminate on our "main" thread @@ -241,7 +241,7 @@ void PyCom_CoUninitialize() STDAPI DllCanUnloadNow(void) { - // If we dont finalize Python, we should never unload! + // If we don't finalize Python, we should never unload! return S_FALSE; // return g_cLockCount ? S_FALSE : S_OK; } diff --git a/com/win32com/src/extensions/PyFUNCDESC.cpp b/com/win32com/src/extensions/PyFUNCDESC.cpp index 717331f1eb..e2a25178bb 100644 --- a/com/win32com/src/extensions/PyFUNCDESC.cpp +++ b/com/win32com/src/extensions/PyFUNCDESC.cpp @@ -107,11 +107,14 @@ static PySequenceMethods PyFUNCDESC_Sequence = { NULL, // sq_ass_slice; }; -static PyObject *PyFUNCDESC_Repr(PyObject *self) { +static PyObject *PyFUNCDESC_Repr(PyObject *self) +{ PyFUNCDESC *f = (PyFUNCDESC *)self; return PyUnicode_FromFormat( - "PyFUNCDESC(memid=%d, scodeArray=%R, args=%R, funckind=%d, invkind=%d, callconv=%d, cParamsOpt=%d, oVft=%d, rettype=%R, wFuncFlags=%d)", - f->memid, f->scodeArray, f->args, f->funckind, f->invkind, f->callconv, f->cParamsOpt, f->oVft, f->rettype, f->wFuncFlags); + "PyFUNCDESC(memid=%d, scodeArray=%R, args=%R, funckind=%d, invkind=%d, callconv=%d, cParamsOpt=%d, oVft=%d, " + "rettype=%R, wFuncFlags=%d)", + f->memid, f->scodeArray, f->args, f->funckind, f->invkind, f->callconv, f->cParamsOpt, f->oVft, f->rettype, + f->wFuncFlags); } PyTypeObject PyFUNCDESC::Type = { @@ -157,17 +160,17 @@ PyTypeObject PyFUNCDESC::Type = { #define OFF(e) offsetof(PyFUNCDESC, e) /*static*/ struct PyMemberDef PyFUNCDESC::members[] = { - {"memid", T_INT, OFF(memid)}, // @prop integer|memid| - {"scodeArray", T_OBJECT, OFF(scodeArray)}, // @prop (int, ...)|scodeArray| - {"args", T_OBJECT, OFF(args)}, // @prop (, ...)|args| - {"funckind", T_INT, OFF(funckind)}, // @prop int|funckind| - {"invkind", T_INT, OFF(invkind)}, // @prop int|invkind| - {"callconv", T_INT, OFF(callconv)}, // @prop int|callconv| - {"cParamsOpt", T_INT, OFF(cParamsOpt)}, // @prop int|cParamsOpt| - {"oVft", T_INT, OFF(oVft)}, // @prop int|oVft| - {"rettype", T_OBJECT, OFF(rettype)}, // @prop |rettype| - {"wFuncFlags", T_INT, OFF(wFuncFlags)}, // @prop int|wFuncFlags| - {"desckind", T_INT, OFF(desckind), READONLY}, // @prop int|desckind|Always DESCKIND_FUNCDESC + {"memid", T_INT, OFF(memid)}, // @prop integer|memid| + {"scodeArray", T_OBJECT, OFF(scodeArray)}, // @prop (int, ...)|scodeArray| + {"args", T_OBJECT, OFF(args)}, // @prop (, ...)|args| + {"funckind", T_INT, OFF(funckind)}, // @prop int|funckind| + {"invkind", T_INT, OFF(invkind)}, // @prop int|invkind| + {"callconv", T_INT, OFF(callconv)}, // @prop int|callconv| + {"cParamsOpt", T_INT, OFF(cParamsOpt)}, // @prop int|cParamsOpt| + {"oVft", T_INT, OFF(oVft)}, // @prop int|oVft| + {"rettype", T_OBJECT, OFF(rettype)}, // @prop |rettype| + {"wFuncFlags", T_INT, OFF(wFuncFlags)}, // @prop int|wFuncFlags| + {"desckind", T_INT, OFF(desckind), READONLY}, // @prop int|desckind|Always DESCKIND_FUNCDESC {NULL}}; PyFUNCDESC::PyFUNCDESC() diff --git a/com/win32com/src/extensions/PyIStorage.cpp b/com/win32com/src/extensions/PyIStorage.cpp index e5bab5db07..f5a1b1ab60 100644 --- a/com/win32com/src/extensions/PyIStorage.cpp +++ b/com/win32com/src/extensions/PyIStorage.cpp @@ -354,12 +354,12 @@ PyObject *PyIStorage::SetElementTimes(PyObject *self, PyObject *args) return NULL; // @pyparm str|name||The name of the storage object element whose times are to be modified. If NULL, the time is set // on the root storage rather than one of its elements. - // @pyparm |ctime||Either the new creation time for the element or None if the creation time is not to be - // modified. + // @pyparm |ctime||Either the new creation time for the element or None if the creation time is not to + // be modified. // @pyparm |atime||Either the new access time for the element or None if the access time is not to be // modified. - // @pyparm |mtime||Either the new modification time for the element or None if the modification time is - // not to be modified. + // @pyparm |mtime||Either the new modification time for the element or None if the modification time + // is not to be modified. PyObject *obName; PyObject *obpctime; PyObject *obpatime; diff --git a/com/win32com/src/extensions/PySTGMEDIUM.cpp b/com/win32com/src/extensions/PySTGMEDIUM.cpp index 501b53d3eb..ec26cd116f 100644 --- a/com/win32com/src/extensions/PySTGMEDIUM.cpp +++ b/com/win32com/src/extensions/PySTGMEDIUM.cpp @@ -63,7 +63,9 @@ PyObject *PySet(PyObject *self, PyObject *args) buf = (void *)PyBytes_AS_STRING(ob); } else if (PyUnicode_Check(ob)) { - buf = tmpw = ob; if (!tmpw) return NULL; + buf = tmpw = ob; + if (!tmpw) + return NULL; cb = (tmpw.length + 1) * sizeof(WCHAR); } else { diff --git a/com/win32com/src/extensions/PyTYPEATTR.cpp b/com/win32com/src/extensions/PyTYPEATTR.cpp index a7fa4d6c38..2fd2cf2e15 100644 --- a/com/win32com/src/extensions/PyTYPEATTR.cpp +++ b/com/win32com/src/extensions/PyTYPEATTR.cpp @@ -144,7 +144,7 @@ PyTYPEATTR::PyTYPEATTR(const TYPEATTR *attr) wMinorVerNum = attr->wMinorVerNum; // Some (only a few 16 bit MSOffice only one so far, and even then only occasionally!) - // servers seem to send invalid tdescAlias when its not actually an alias. + // servers seem to send invalid tdescAlias when it's not actually an alias. if (attr->typekind == TKIND_ALIAS) obDescAlias = PyObject_FromTYPEDESC(&attr->tdescAlias); else { diff --git a/com/win32com/src/extensions/PyVARDESC.cpp b/com/win32com/src/extensions/PyVARDESC.cpp index 5f660a7f91..4ccb119984 100644 --- a/com/win32com/src/extensions/PyVARDESC.cpp +++ b/com/win32com/src/extensions/PyVARDESC.cpp @@ -74,11 +74,11 @@ BOOL PyObject_AsVARDESC(PyObject *ob, VARDESC **pp) return rc; } -static PyObject *PyVARDESC_Repr(PyObject *self) { +static PyObject *PyVARDESC_Repr(PyObject *self) +{ PyVARDESC *v = (PyVARDESC *)self; - return PyUnicode_FromFormat( - "PyVARDESC(memid=%d, value=%R, elemdescVar=%R, wVarFlags=%d, varkind=%d)", - v->memid, v->value, v->elemdescVar, v->wVarFlags, v->varkind); + return PyUnicode_FromFormat("PyVARDESC(memid=%d, value=%R, elemdescVar=%R, wVarFlags=%d, varkind=%d)", v->memid, + v->value, v->elemdescVar, v->wVarFlags, v->varkind); } void PyObject_FreeVARDESC(VARDESC *p) { FreeMoreBuffer(p); } @@ -140,10 +140,10 @@ PyTypeObject PyVARDESC::Type = { {"memid", T_INT, OFF(memid)}, // @prop int|memid|The dispid of the member {"value", T_OBJECT, OFF(value)}, // @prop int/object|value|A value for the variant. If PERINSTANCE then an offset // into the instance, otherwise a variant converted to a Python object. - {"elemdescVar", T_OBJECT, OFF(elemdescVar)}, // @prop |elemdescVar|Object describing the member. - {"wVarFlags", T_INT, OFF(wVarFlags)}, // @prop int|varFlags|Variable flags - {"varkind", T_INT, OFF(varkind)}, // @prop int|varkind|Kind flags. - {"desckind", T_INT, OFF(desckind), READONLY}, // @prop int|desckind|Always DESCKIND_VARDESC + {"elemdescVar", T_OBJECT, OFF(elemdescVar)}, // @prop |elemdescVar|Object describing the member. + {"wVarFlags", T_INT, OFF(wVarFlags)}, // @prop int|varFlags|Variable flags + {"varkind", T_INT, OFF(varkind)}, // @prop int|varkind|Kind flags. + {"desckind", T_INT, OFF(desckind), READONLY}, // @prop int|desckind|Always DESCKIND_VARDESC {NULL}}; PyVARDESC::PyVARDESC() diff --git a/com/win32com/src/include/PyIEnumGUID.h b/com/win32com/src/include/PyIEnumGUID.h index c2cc8b5a9f..8e7453f09c 100644 --- a/com/win32com/src/include/PyIEnumGUID.h +++ b/com/win32com/src/include/PyIEnumGUID.h @@ -39,7 +39,6 @@ class PyGEnumGUID : public PyGatewayBase, public IEnumGUID { STDMETHOD(Clone)(IEnumGUID __RPC_FAR *__RPC_FAR *ppenum); }; - ///////////////////////////////////////////////////////////////////////////// // class PyIEnumCATEGORYINFO class PyIEnumCATEGORYINFO : public PyIUnknown { diff --git a/com/win32com/src/include/PythonCOM.h b/com/win32com/src/include/PythonCOM.h index 3c862e9acf..446500acdb 100644 --- a/com/win32com/src/include/PythonCOM.h +++ b/com/win32com/src/include/PythonCOM.h @@ -158,8 +158,8 @@ class PYCOM_EXPORT PyComEnumTypeObject : public PyComTypeObject { public: static PyObject *iter(PyObject *self); static PyObject *iternext(PyObject *self); - PyComEnumTypeObject(const char *name, PyComTypeObject *pBaseType, Py_ssize_t typeSize, struct PyMethodDef *methodList, - PyIUnknown *(*thector)(IUnknown *)); + PyComEnumTypeObject(const char *name, PyComTypeObject *pBaseType, Py_ssize_t typeSize, + struct PyMethodDef *methodList, PyIUnknown *(*thector)(IUnknown *)); }; // Very very base class - not COM specific - Should exist in the @@ -347,7 +347,7 @@ PYCOM_EXPORT HRESULT PyCom_HandleIEnumNoSequence(REFIID riid); PYCOM_EXPORT HRESULT PyCom_SetCOMErrorFromPyException(REFIID riid = IID_NULL); // A couple of EXCEPINFO helpers - could be private to IDispatch -// if it wasnt for the AXScript support (and ITypeInfo if we get around to that :-) +// if it wasn't for the AXScript support (and ITypeInfo if we get around to that :-) // These functions do not set any error states to either Python or // COM - they simply convert to/from PyObjects and EXCEPINFOs @@ -367,7 +367,7 @@ PYCOM_EXPORT PyObject *PyCom_PyObjectFromExcepInfo(const EXCEPINFO *pexcepInfo); /////////////////////////////////////////////////////////////////// // // External C++ helpers - these helpers are for other DLLs which -// may need similar functionality, but dont want to duplicate all +// may need similar functionality, but don't want to duplicate all // This helper is for an application that has an IDispatch, and COM arguments // and wants to call a Python function. It is assumed the caller can map the IDispatch @@ -413,11 +413,11 @@ class PYCOM_EXPORT PyOleNothing : public PyObject { // These helpers allow each type object to create it. #define MAKE_PYCOM_CTOR(classname) \ static PyIUnknown *PyObConstruct(IUnknown *pInitObj) { return new classname(pInitObj); } -#define MAKE_PYCOM_CTOR_ERRORINFO(classname, iid) \ - static PyIUnknown *PyObConstruct(IUnknown *pInitObj) { return new classname(pInitObj); } \ - static PyObject *SetPythonCOMError(PyObject *self, HRESULT hr) \ - { \ - return PyCom_BuildPyException(hr, GetI(self), iid); \ +#define MAKE_PYCOM_CTOR_ERRORINFO(classname, iid) \ + static PyIUnknown *PyObConstruct(IUnknown *pInitObj) { return new classname(pInitObj); } \ + static PyObject *SetPythonCOMError(PyObject *self, HRESULT hr) \ + { \ + return PyCom_BuildPyException(hr, GetI(self), iid); \ } #define GET_PYCOM_CTOR(classname) classname::PyObConstruct @@ -648,9 +648,9 @@ class PYCOM_EXPORT PyIConnectionPointContainer : public PyIUnknown { // which need to convert from a Python object when the specific OLE // type is known - eg, when a TypeInfo is available. // -// The type of conversion determines who owns what buffers etc. I wish BYREF didnt exist :-) +// The type of conversion determines who owns what buffers etc. I wish BYREF didn't exist :-) typedef enum { - // We dont know what sort of conversion it is yet. + // We don't know what sort of conversion it is yet. POAH_CONVERT_UNKNOWN, // A PyObject is given, we convert to a VARIANT, make the COM call, then BYREFs back to a PyObject // ie, this is typically a "normal" COM call, where Python initiates the call diff --git a/com/win32com/src/include/PythonCOMRegister.h b/com/win32com/src/include/PythonCOMRegister.h index ab960f5334..f288e47770 100644 --- a/com/win32com/src/include/PythonCOMRegister.h +++ b/com/win32com/src/include/PythonCOMRegister.h @@ -20,52 +20,24 @@ typedef struct { } PyCom_InterfaceSupportInfo; -#define PYCOM_INTERFACE_IID_ONLY(ifc) \ - { \ - &IID_I##ifc, "I" #ifc, "IID_I" #ifc, NULL, NULL \ - } -#define PYCOM_INTERFACE_CLSID_ONLY(ifc) \ - { \ - &CLSID_##ifc, "CLSID_" #ifc, "CLSID_" #ifc, NULL, NULL \ - } -#define PYCOM_INTERFACE_CATID_ONLY(ifc) \ - { \ - &CATID_##ifc, "CATID_" #ifc, "CATID_" #ifc, NULL, NULL \ - } -#define PYCOM_INTERFACE_CLIENT_ONLY(ifc) \ - { \ - &IID_I##ifc, "I" #ifc, "IID_I" #ifc, &PyI##ifc::type, NULL \ - } -#define PYCOM_INTERFACE_SERVER_ONLY(ifc) \ - { \ - &IID_I##ifc, "I" #ifc, "IID_I" #ifc, NULL, GET_PYGATEWAY_CTOR(PyG##ifc) \ - } -#define PYCOM_INTERFACE_FULL(ifc) \ - { \ - &IID_I##ifc, "I" #ifc, "IID_I" #ifc, &PyI##ifc::type, GET_PYGATEWAY_CTOR(PyG##ifc) \ - } +#define PYCOM_INTERFACE_IID_ONLY(ifc) {&IID_I##ifc, "I" #ifc, "IID_I" #ifc, NULL, NULL} +#define PYCOM_INTERFACE_CLSID_ONLY(ifc) {&CLSID_##ifc, "CLSID_" #ifc, "CLSID_" #ifc, NULL, NULL} +#define PYCOM_INTERFACE_CATID_ONLY(ifc) {&CATID_##ifc, "CATID_" #ifc, "CATID_" #ifc, NULL, NULL} +#define PYCOM_INTERFACE_CLIENT_ONLY(ifc) {&IID_I##ifc, "I" #ifc, "IID_I" #ifc, &PyI##ifc::type, NULL} +#define PYCOM_INTERFACE_SERVER_ONLY(ifc) {&IID_I##ifc, "I" #ifc, "IID_I" #ifc, NULL, GET_PYGATEWAY_CTOR(PyG##ifc)} +#define PYCOM_INTERFACE_FULL(ifc) {&IID_I##ifc, "I" #ifc, "IID_I" #ifc, &PyI##ifc::type, GET_PYGATEWAY_CTOR(PyG##ifc)} // Versions that use __uuidof() to get the IID, which seems to avoid the need // to link with a lib holding the IIDs. Note that almost all extensions // build with __uuidof() being the default; the build failed at 'shell' - so // we could consider making this the default and making the 'explicit' version // above the special case. -#define PYCOM_INTERFACE_IID_ONLY_UUIDOF(ifc) \ - { \ - &__uuidof(I##ifc), "I" #ifc, "IID_I" #ifc, NULL, NULL \ - } -#define PYCOM_INTERFACE_CLIENT_ONLY_UUIDOF(ifc) \ - { \ - &__uuidof(I##ifc), "I" #ifc, "IID_I" #ifc, &PyI##ifc::type, NULL \ - } -#define PYCOM_INTERFACE_SERVER_ONLY_UUIDOF(ifc) \ - { \ - &__uuidof(I##ifc), "I" #ifc, "IID_I" #ifc, NULL, GET_PYGATEWAY_CTOR(PyG##ifc) \ - } -#define PYCOM_INTERFACE_FULL_UUIDOF(ifc) \ - { \ - &__uuidof(I##ifc), "I" #ifc, "IID_I" #ifc, &PyI##ifc::type, GET_PYGATEWAY_CTOR(PyG##ifc) \ - } +#define PYCOM_INTERFACE_IID_ONLY_UUIDOF(ifc) {&__uuidof(I##ifc), "I" #ifc, "IID_I" #ifc, NULL, NULL} +#define PYCOM_INTERFACE_CLIENT_ONLY_UUIDOF(ifc) {&__uuidof(I##ifc), "I" #ifc, "IID_I" #ifc, &PyI##ifc::type, NULL} +#define PYCOM_INTERFACE_SERVER_ONLY_UUIDOF(ifc) \ + {&__uuidof(I##ifc), "I" #ifc, "IID_I" #ifc, NULL, GET_PYGATEWAY_CTOR(PyG##ifc)} +#define PYCOM_INTERFACE_FULL_UUIDOF(ifc) \ + {&__uuidof(I##ifc), "I" #ifc, "IID_I" #ifc, &PyI##ifc::type, GET_PYGATEWAY_CTOR(PyG##ifc)} // Prototypes for the register functions diff --git a/com/win32com/src/include/PythonCOMServer.h b/com/win32com/src/include/PythonCOMServer.h index f026168a0c..752d223a44 100644 --- a/com/win32com/src/include/PythonCOMServer.h +++ b/com/win32com/src/include/PythonCOMServer.h @@ -27,34 +27,33 @@ HRESULT PyCom_MakeRegisteredGatewayObject(REFIID iid, PyObject *instance, PyGate // A version of the above which support classes being derived from // other than IUnknown -#define PYGATEWAY_MAKE_SUPPORT2(classname, IInterface, theIID, gatewaybaseclass) \ - public: \ - static HRESULT PyGatewayConstruct(PyObject *pPyInstance, PyGatewayBase *unkBase, void **ppResult, \ - REFIID iid) \ - { \ - if (ppResult == NULL) \ - return E_INVALIDARG; \ - classname *newob = new classname(pPyInstance); \ - newob->m_pBaseObject = unkBase; \ - if (unkBase) \ - unkBase->AddRef(); \ - *ppResult = newob->ThisAsIID(iid); \ - return *ppResult ? S_OK : E_OUTOFMEMORY; \ - } \ - \ - protected: \ - virtual IID GetIID(void) { return theIID; } \ - virtual void *ThisAsIID(IID iid) \ - { \ - if (this == NULL) \ - return NULL; \ - if (iid == theIID) \ - return (IInterface *)this; \ - else \ - return gatewaybaseclass::ThisAsIID(iid); \ - } \ - STDMETHOD_(ULONG, AddRef)(void) { return gatewaybaseclass::AddRef(); } \ - STDMETHOD_(ULONG, Release)(void) { return gatewaybaseclass::Release(); } \ +#define PYGATEWAY_MAKE_SUPPORT2(classname, IInterface, theIID, gatewaybaseclass) \ + public: \ + static HRESULT PyGatewayConstruct(PyObject *pPyInstance, PyGatewayBase *unkBase, void **ppResult, REFIID iid) \ + { \ + if (ppResult == NULL) \ + return E_INVALIDARG; \ + classname *newob = new classname(pPyInstance); \ + newob->m_pBaseObject = unkBase; \ + if (unkBase) \ + unkBase->AddRef(); \ + *ppResult = newob->ThisAsIID(iid); \ + return *ppResult ? S_OK : E_OUTOFMEMORY; \ + } \ + \ + protected: \ + virtual IID GetIID(void) { return theIID; } \ + virtual void *ThisAsIID(IID iid) \ + { \ + if (this == NULL) \ + return NULL; \ + if (iid == theIID) \ + return (IInterface *)this; \ + else \ + return gatewaybaseclass::ThisAsIID(iid); \ + } \ + STDMETHOD_(ULONG, AddRef)(void) { return gatewaybaseclass::AddRef(); } \ + STDMETHOD_(ULONG, Release)(void) { return gatewaybaseclass::Release(); } \ STDMETHOD(QueryInterface)(REFIID iid, void **obj) { return gatewaybaseclass::QueryInterface(iid, obj); }; // This is the "old" version to use, or use it if you derive @@ -85,10 +84,9 @@ interface IInternalUnwrapPythonObject : public IUnknown // // Base class for all gateways. // -class PYCOM_EXPORT PyGatewayBase : - public IDispatchEx, // IDispatch comes along for the ride! - public ISupportErrorInfo, - public IInternalUnwrapPythonObject { +class PYCOM_EXPORT PyGatewayBase : public IDispatchEx, // IDispatch comes along for the ride! + public ISupportErrorInfo, + public IInternalUnwrapPythonObject { protected: PyGatewayBase(PyObject *instance); virtual ~PyGatewayBase(); @@ -127,9 +125,8 @@ class PYCOM_EXPORT PyGatewayBase : STDMETHOD(Unwrap)(PyObject **ppPyObject); // Basically just PYGATEWAY_MAKE_SUPPORT(PyGatewayBase, IDispatch, IID_IDispatch); - // but with special handling as its the base class. - static HRESULT PyGatewayConstruct(PyObject *pPyInstance, PyGatewayBase *gatewayBase, void **ppResult, - REFIID iid) + // but with special handling as it's the base class. + static HRESULT PyGatewayConstruct(PyObject *pPyInstance, PyGatewayBase *gatewayBase, void **ppResult, REFIID iid) { if (ppResult == NULL) return E_INVALIDARG; @@ -142,7 +139,7 @@ class PYCOM_EXPORT PyGatewayBase : } // Currently this is used only for ISupportErrorInfo, // so hopefully this will never be called in this base class. - // (however, this is not a rule, so we wont assert or anything!) + // (however, this is not a rule, so we won't assert or anything!) virtual IID GetIID(void) { return IID_IUnknown; } virtual void *ThisAsIID(IID iid); // End of PYGATEWAY_MAKE_SUPPORT diff --git a/com/win32com/src/include/stdafx.h b/com/win32com/src/include/stdafx.h index 4dd5505ba4..8b8b513376 100644 --- a/com/win32com/src/include/stdafx.h +++ b/com/win32com/src/include/stdafx.h @@ -4,7 +4,7 @@ // // _WIN32_DCOM screws win95 and NT :-( However, we need to define this -// so we dont lose all the constants etc that come with DCOM +// so we don't lose all the constants etc that come with DCOM // #define _WIN32_DCOM #define _WIN32_WINNT 0x0501 // we use some of these features. diff --git a/com/win32com/src/oleargs.cpp b/com/win32com/src/oleargs.cpp index c6fad6c215..0187949f6f 100644 --- a/com/win32com/src/oleargs.cpp +++ b/com/win32com/src/oleargs.cpp @@ -119,7 +119,7 @@ BOOL PyCom_VariantFromPyObject(PyObject *obj, VARIANT *var) BOOL bGoodEmpty = FALSE; // Set if VT_EMPTY should really be used. V_VT(var) = VT_EMPTY; if ( -// In py3k we don't convert PyBytes_Check objects (ie, bytes) to BSTR... + // In py3k we don't convert PyBytes_Check objects (ie, bytes) to BSTR... PyUnicode_Check(obj)) { if (!PyWinObject_AsBstr(obj, &V_BSTR(var))) { PyErr_SetString(PyExc_MemoryError, "Making BSTR for variant"); @@ -327,13 +327,13 @@ PyObject *PyCom_PyObjectFromVariant(const VARIANT *var) return Py_None; } /* skip past any variant references to a "real" variant - (Why do we do this? Why is it only a VARIANT? whats the story, morning glory? + (Why do we do this? Why is it only a VARIANT? what's the story, morning glory? */ while (V_VT(var) == (VT_BYREF | VT_VARIANT)) var = V_VARIANTREF(var); /* ### note: we shouldn't see this, it is illegal in a VARIANT */ if (V_ISVECTOR(var)) { - return OleSetTypeError(_T("Cant convert vectors!")); + return OleSetTypeError(_T("Can't convert vectors!")); } if (V_ISARRAY(var)) { @@ -692,7 +692,7 @@ static BOOL PyCom_SAFEARRAYFromPyObjectEx(PyObject *obj, SAFEARRAY **ppSA, bool // Seek down searching for total dimension count. // Item zero of each element will do for now // (as all must be same) - // First we _will_ allow None here (just dont use it if it crashes :-) + // First we _will_ allow None here (just don't use it if it crashes :-) if (obj == Py_None) { if (bAllocNewArray) *ppSA = NULL; @@ -1075,7 +1075,7 @@ PythonOleArgHelper::~PythonOleArgHelper() // First check we actually have ownership of any buffers. if (m_convertDirection == POAH_CONVERT_UNKNOWN || m_convertDirection == POAH_CONVERT_FROM_VARIANT) return; - // OK - its is possible we own the buffers - check for sure based on the type... + // OK - it is possible we own the buffers - check for sure based on the type... if (m_reqdType & VT_ARRAY) { // Array datatype - cleanup (but how?) if (m_reqdType & VT_BYREF) { @@ -1089,8 +1089,8 @@ PythonOleArgHelper::~PythonOleArgHelper() } #endif } // have array pointer -#endif // BYREF_ARRAY_USE_EXISTING_ARRAY - } // BYREF array. +#endif // BYREF_ARRAY_USE_EXISTING_ARRAY + } // BYREF array. } else { switch (m_reqdType) { @@ -1154,7 +1154,7 @@ BOOL PythonOleArgHelper::ParseTypeInformation(PyObject *reqdObjectTuple) BOOL PythonOleArgHelper::MakeObjToVariant(PyObject *obj, VARIANT *var, PyObject *reqdObjectTuple) { - // Check my logic still holds up - basically we cant call this twice on the same object. + // Check my logic still holds up - basically we can't call this twice on the same object. assert(m_convertDirection == POAH_CONVERT_UNKNOWN || m_convertDirection == POAH_CONVERT_FROM_VARIANT); // If this is the "driving" conversion, then we allocate buffers. // Otherwise, we are simply filling in the buffers as provided by the caller. @@ -1225,7 +1225,7 @@ BOOL PythonOleArgHelper::MakeObjToVariant(PyObject *obj, VARIANT *var, PyObject return TRUE; // All done with array! } if (m_reqdType & VT_VECTOR) { // we have been asked for an array. - OleSetTypeError(_T("Sorry - cant support VT_VECTOR arguments")); + OleSetTypeError(_T("Sorry - can't support VT_VECTOR arguments")); return FALSE; } BOOL rc = TRUE; @@ -1610,7 +1610,7 @@ PyObject *PythonOleArgHelper::MakeVariantToObj(VARIANT *var) // performed first, then Python called, then the ObjToVariant conversion will // happen later. In this case, remember the buffer for the Variant - // Check my logic still holds up - basically we cant call this twice on the same object. + // Check my logic still holds up - basically we can't call this twice on the same object. assert(m_convertDirection == POAH_CONVERT_UNKNOWN || m_convertDirection == POAH_CONVERT_FROM_PYOBJECT); // If this is the "driving" conversion, then the callers owns the buffers - we just use-em if (m_convertDirection == POAH_CONVERT_UNKNOWN) { diff --git a/com/win32com/src/univgw.cpp b/com/win32com/src/univgw.cpp index eab2798e30..aec11ad124 100644 --- a/com/win32com/src/univgw.cpp +++ b/com/win32com/src/univgw.cpp @@ -125,9 +125,9 @@ static HRESULT univgw_dispatch(DWORD index, gw_object *_this, va_list argPtr) Py_DECREF(result); // ### Greg> what to do for non-HRESULT return values? - // ### Bill> If its not a float/double then + // ### Bill> If it's not a float/double then // ### then they'll see a 32bit sign-extended value. - // ### If its a float/double they're currently out of luck. + // ### If it's a float/double they're currently out of luck. // ### The smart ones only declare int, HRESULT, or void // ### functions in any event... // ### on X86s __stdcall return values go into: @@ -146,7 +146,7 @@ static HRESULT univgw_dispatch(DWORD index, gw_object *_this, va_list argPtr) return hr; } -//#define COMPILE_MOCKUP +// #define COMPILE_MOCKUP #ifdef COMPILE_MOCKUP STDMETHODIMP mockup(gw_object *_this) @@ -263,7 +263,7 @@ static pfnGWMethod make_method(DWORD index, UINT argsize, UINT argc) } #else // other arches /* The MAINWIN toolkit allows us to build this on Linux!!! */ -#pragma message("XXXXXXXXX - win32com.universal wont work on this platform - need make_method") +#pragma message("XXXXXXXXX - win32com.universal won't work on this platform - need make_method") PyErr_SetString(PyExc_NotImplementedError, "not implemented on this platform"); code = NULL; #endif diff --git a/com/win32com/src/univgw_dataconv.cpp b/com/win32com/src/univgw_dataconv.cpp index 13dd414240..23107d01db 100644 --- a/com/win32com/src/univgw_dataconv.cpp +++ b/com/win32com/src/univgw_dataconv.cpp @@ -705,7 +705,7 @@ PyObject *dataconv_ReadFromInTuple(PyObject *self, PyObject *args) // barf here, we don't wtf they were thinking... break; } // switch - } // if ARRAY + } // if ARRAY if (obArg == NULL) { goto Error; diff --git a/com/win32com/test/daodump.py b/com/win32com/test/daodump.py index 0b6cc95174..41f6f70942 100644 --- a/com/win32com/test/daodump.py +++ b/com/win32com/test/daodump.py @@ -42,7 +42,7 @@ def DumpRelations(db, bDeep=1): print(f"Relation {relation.Name} - {relation.Table}->{relation.ForeignTable}") -#### This dont work. TLB says it is a Fields collection, but apparently not! +#### This don't work. TLB says it is a Fields collection, but apparently not! #### if bDeep: DumpFields(relation.Fields) diff --git a/com/win32com/test/testConversionErrors.py b/com/win32com/test/testConversionErrors.py index 773b9b80f3..43bf326664 100644 --- a/com/win32com/test/testConversionErrors.py +++ b/com/win32com/test/testConversionErrors.py @@ -28,11 +28,7 @@ def __float__(self): class TestCase(win32com.test.util.TestCase): def test_float(self): - try: - test_ob().TestValue(BadConversions()) - raise Exception("Should not have worked") - except Exception as e: - assert isinstance(e, TestException) + self.assertRaises(TestException, test_ob().TestValue, BadConversions()) if __name__ == "__main__": diff --git a/com/win32com/test/testDictionary.py b/com/win32com/test/testDictionary.py index dfcbb98d4b..3e66913322 100644 --- a/com/win32com/test/testDictionary.py +++ b/com/win32com/test/testDictionary.py @@ -62,7 +62,7 @@ def TestDict(quiet=None): print("Failure tests") try: dict() - raise Exception("default method with no args worked when it shouldnt have!") + raise Exception("default method with no args worked when it shouldn't have!") except pythoncom.com_error as xxx_todo_changeme: (hr, desc, exc, argErr) = xxx_todo_changeme.args assert ( @@ -71,7 +71,7 @@ def TestDict(quiet=None): try: dict("hi", "there") - raise Exception("multiple args worked when it shouldnt have!") + raise Exception("multiple args worked when it shouldn't have!") except pythoncom.com_error as xxx_todo_changeme1: (hr, desc, exc, argErr) = xxx_todo_changeme1.args assert ( @@ -80,7 +80,7 @@ def TestDict(quiet=None): try: dict(0) - raise Exception("int key worked when it shouldnt have!") + raise Exception("int key worked when it shouldn't have!") except pythoncom.com_error as xxx_todo_changeme2: (hr, desc, exc, argErr) = xxx_todo_changeme2.args assert ( diff --git a/com/win32com/test/testGIT.py b/com/win32com/test/testGIT.py index f5228a6b23..611cba2d67 100644 --- a/com/win32com/test/testGIT.py +++ b/com/win32com/test/testGIT.py @@ -2,7 +2,7 @@ Uses standard COM marshalling to pass objects between threads. Even though Python generally seems to work when you just pass COM objects -between threads, it shouldnt. +between threads, it shouldn't. This shows the "correct" way to do it. @@ -110,7 +110,7 @@ def test(fn): if rc >= win32event.WAIT_OBJECT_0 and rc < win32event.WAIT_OBJECT_0 + len( events ): - numFinished = numFinished + 1 + numFinished += 1 if numFinished >= len(events): break elif rc == win32event.WAIT_OBJECT_0 + len(events): # a message diff --git a/com/win32com/test/testGatewayAddresses.py b/com/win32com/test/testGatewayAddresses.py index ee3682badd..aeafbec759 100644 --- a/com/win32com/test/testGatewayAddresses.py +++ b/com/win32com/test/testGatewayAddresses.py @@ -59,7 +59,7 @@ def CheckObjectIdentity(ob1, ob2): def FailObjectIdentity(ob1, ob2, when): if not CheckObjectIdentity(ob1, ob2): global numErrors - numErrors = numErrors + 1 + numErrors += 1 print(when, f"are not identical ({repr(ob1)}, {repr(ob2)})") @@ -93,7 +93,7 @@ def _query_interface_(self, iid): def TestGatewayInheritance(): # By default, wrap() creates and discards a temporary object. # This is not necessary, but just the current implementation of wrap. - # As the object is correctly discarded, it doesnt affect this test. + # As the object is correctly discarded, it doesn't affect this test. o = wrap(Dummy(), pythoncom.IID_IPersistStorage) o2 = o.QueryInterface(pythoncom.IID_IUnknown) FailObjectIdentity(o, o2, "IID_IPersistStorage->IID_IUnknown") diff --git a/com/win32com/test/testIterators.py b/com/win32com/test/testIterators.py index 8eba364a70..fe336e54e4 100644 --- a/com/win32com/test/testIterators.py +++ b/com/win32com/test/testIterators.py @@ -124,7 +124,7 @@ def tearDown(self): def suite(): - # We dont want our base class run + # We don't want our base class run suite = unittest.TestSuite() for item in list(globals().values()): if ( diff --git a/com/win32com/test/testMSOffice.py b/com/win32com/test/testMSOffice.py index b65a964b00..37a37fe935 100644 --- a/com/win32com/test/testMSOffice.py +++ b/com/win32com/test/testMSOffice.py @@ -86,7 +86,7 @@ def TestWord8(word): # XXX - note that # for para in paras: # para().Font... - # doesnt seem to work - no error, just doesnt work + # doesn't seem to work - no error, just doesn't work # Should check if it works for VB! doc.Close(SaveChanges=0) word.Quit() diff --git a/com/win32com/test/testMSOfficeEvents.py b/com/win32com/test/testMSOfficeEvents.py index e677afc67f..f44e1d9b8b 100644 --- a/com/win32com/test/testMSOfficeEvents.py +++ b/com/win32com/test/testMSOfficeEvents.py @@ -16,7 +16,7 @@ class ExcelEvents: def OnNewWorkbook(self, wb): if not isinstance(wb, types.InstanceType): raise RuntimeError( - "The transformer doesnt appear to have translated this for us!" + "The transformer doesn't appear to have translated this for us!" ) self.seen_events["OnNewWorkbook"] = None @@ -25,7 +25,7 @@ def OnWindowActivate(self, wb, wn): wn, types.InstanceType ): raise RuntimeError( - "The transformer doesnt appear to have translated this for us!" + "The transformer doesn't appear to have translated this for us!" ) self.seen_events["OnWindowActivate"] = None diff --git a/com/win32com/test/testMarshal.py b/com/win32com/test/testMarshal.py index 6c9a6ce902..f17cd29d52 100644 --- a/com/win32com/test/testMarshal.py +++ b/com/win32com/test/testMarshal.py @@ -2,7 +2,7 @@ Uses standard COM marshalling to pass objects between threads. Even though Python generally seems to work when you just pass COM objects -between threads, it shouldnt. +between threads, it shouldn't. This shows the "correct" way to do it. @@ -74,14 +74,14 @@ def BeginThreadsSimpleMarshal(self, numThreads): t = threading.Thread( target=self._testInterpInThread, args=(hEvent, interpStream) ) - t.setDaemon(1) # so errors dont cause shutdown hang + t.setDaemon(1) # so errors don't cause shutdown hang t.start() threads.append(t) interp = None return threads, events # - # NOTE - this doesnt quite work - Im not even sure it should, but Greg reckons + # NOTE - this doesn't quite work - I'm not even sure it should, but Greg reckons # you should be able to avoid the marshal per thread! # I think that refers to CoMarshalInterface though... def BeginThreadsFastMarshal(self, numThreads): @@ -101,7 +101,7 @@ def BeginThreadsFastMarshal(self, numThreads): for i in range(numThreads): hEvent = win32event.CreateEvent(None, 0, 0, None) t = threading.Thread(target=self._testInterpInThread, args=(hEvent, interp)) - t.setDaemon(1) # so errors dont cause shutdown hang + t.setDaemon(1) # so errors don't cause shutdown hang t.start() events.append(hEvent) threads.append(t) @@ -125,7 +125,7 @@ def _DoTestMarshal(self, fn, bCoWait=0): rc >= win32event.WAIT_OBJECT_0 and rc < win32event.WAIT_OBJECT_0 + len(events) ): - numFinished = numFinished + 1 + numFinished += 1 if numFinished >= len(events): break elif rc == win32event.WAIT_OBJECT_0 + len(events): # a message diff --git a/com/win32com/test/testNetscape.py b/com/win32com/test/testNetscape.py index ed36380318..8347aae995 100644 --- a/com/win32com/test/testNetscape.py +++ b/com/win32com/test/testNetscape.py @@ -1,4 +1,4 @@ -## AHH - I cant make this work!!! +## AHH - I can't make this work!!! # But this is the general idea. diff --git a/com/win32com/test/testPersist.py b/com/win32com/test/testPersist.py index 5ca6053f7d..aecdd27fbf 100644 --- a/com/win32com/test/testPersist.py +++ b/com/win32com/test/testPersist.py @@ -50,7 +50,7 @@ def WriteAt(self, offset, data): newdata = self.data[0:offset] + data print(len(newdata)) if len(self.data) >= offset + len(data): - newdata = newdata + self.data[offset + len(data) :] + newdata += self.data[offset + len(data) :] print(len(newdata)) self.data = newdata return len(data) @@ -64,7 +64,7 @@ def Flush(self, whatsthis=0): def SetSize(self, size): print("Set Size" + str(size)) if size > len(self.data): - self.data = self.data + b"\000" * (size - len(self.data)) + self.data += b"\000" * (size - len(self.data)) else: self.data = self.data[0:size] return S_OK @@ -206,7 +206,7 @@ def test(): # XXX - note that # for para in paras: # para().Font... - # doesnt seem to work - no error, just doesnt work + # doesn't seem to work - no error, just doesn't work # Should check if it works for VB! dpcom.Save(stcom, 0) diff --git a/com/win32com/test/testPyComTest.py b/com/win32com/test/testPyComTest.py index a906de5c99..4964d0a510 100644 --- a/com/win32com/test/testPyComTest.py +++ b/com/win32com/test/testPyComTest.py @@ -1,5 +1,5 @@ # NOTE - Still seems to be a leak here somewhere -# gateway count doesnt hit zero. Hence the print statements! +# gateway count doesn't hit zero. Hence the print statements! import sys @@ -96,7 +96,7 @@ def _Init(self): def OnFire(self, no): try: - self.fireds[no] = self.fireds[no] + 1 + self.fireds[no] += 1 except KeyError: self.fireds[no] = 0 @@ -190,7 +190,7 @@ def TestCommon(o, is_generated): assert o.GetSetUnsignedLong(-1) == 0xFFFFFFFF, "unsigned -1 failed" # We want to explicitly test > 32 bits. - # 'maxsize+1' is no good on 64bit platforms as its 65 bits! + # 'maxsize+1' is no good on 64bit platforms as it's 65 bits! big = 2147483647 for l in big, big + 1, 1 << 65: check_get_set(o.GetSetVariant, l) @@ -625,10 +625,10 @@ def TestCounter(counter, bIsGenerated): counter.SetBounds(bounds[0], bounds[1]) for item in counter: - num = num + 1 + num += 1 assert num == len( counter - ), "*** Length of counter and loop iterations dont match ***" + ), "*** Length of counter and loop iterations don't match ***" assert num == 10, "*** Unexpected number of loop iterations ***" try: @@ -640,7 +640,7 @@ def TestCounter(counter, bIsGenerated): counter.Reset() num = 0 for item in counter: - num = num + 1 + num += 1 assert num == 10, f"*** Unexpected number of loop iterations - got {num} ***" progress("Finished testing counter") diff --git a/com/win32com/test/testStorage.py b/com/win32com/test/testStorage.py index 27ae640e0d..e8f3d5d172 100644 --- a/com/win32com/test/testStorage.py +++ b/com/win32com/test/testStorage.py @@ -24,7 +24,7 @@ def testit(self): storagecon.STGM_READWRITE | storagecon.STGM_CREATE | storagecon.STGM_SHARE_EXCLUSIVE, - ) ## its very picky about flag combinations! + ) ## it's very picky about flag combinations! psuser.WriteMultiple((3, 4), ("hey", "bubba")) psuser.WritePropertyNames((3, 4), ("property3", "property4")) expected_summaries = [] diff --git a/com/win32com/test/testStreams.py b/com/win32com/test/testStreams.py index b43da524f3..9e905ce8be 100644 --- a/com/win32com/test/testStreams.py +++ b/com/win32com/test/testStreams.py @@ -51,7 +51,7 @@ def __init__(self, data): def Read(self, amount): result = self.data[self.index : self.index + amount] - self.index = self.index + amount + self.index += amount return result def Write(self, data): @@ -63,7 +63,7 @@ def Seek(self, dist, origin): if origin == pythoncom.STREAM_SEEK_SET: self.index = dist elif origin == pythoncom.STREAM_SEEK_CUR: - self.index = self.index + dist + self.index += dist elif origin == pythoncom.STREAM_SEEK_END: self.index = len(self.data) + dist else: diff --git a/com/win32com/test/testall.py b/com/win32com/test/testall.py index e9abe10361..9667f2348a 100644 --- a/com/win32com/test/testall.py +++ b/com/win32com/test/testall.py @@ -226,7 +226,7 @@ def make_test_suite(test_level=1): test = mod.suite() else: test = loader.loadTestsFromModule(mod) - assert test.countTestCases() > 0, "No tests loaded from %r" % mod + assert test.countTestCases() > 0, f"No tests loaded from {mod!r}" suite.addTest(test) for cmd, output in output_checked_programs[i]: suite.addTest(ShellTestCase(cmd, output)) @@ -247,7 +247,7 @@ def make_test_suite(test_level=1): test = mod.suite() else: test = loader.loadTestsFromModule(mod) - assert test.countTestCases() > 0, "No tests loaded from %r" % mod + assert test.countTestCases() > 0, f"No tests loaded from {mod!r}" suite.addTest(test) return suite, import_failures diff --git a/com/win32com/test/testvb.py b/com/win32com/test/testvb.py index b36052c556..480c1c742b 100644 --- a/com/win32com/test/testvb.py +++ b/com/win32com/test/testvb.py @@ -107,7 +107,7 @@ def TestVB(vbtest, bUseGenerated): assert vbtest.TakeByValObject(vbtest) == vbtest - # Python doesnt support PUTREF properties without a typeref + # Python doesn't support PUTREF properties without a typeref # (although we could) if bUseGenerated: ob = vbtest.TakeByRefObject(vbtest) @@ -118,7 +118,7 @@ def TestVB(vbtest, bUseGenerated): assert ( vbtest.VariantPutref._oleobj_ == vbtest._oleobj_ ), "Could not set the VariantPutref property correctly." - # Cant test further types for this VariantPutref, as only + # Can't test further types for this VariantPutref, as only # COM objects can be stored ByRef. # A "set" type property - only works for generated. @@ -133,7 +133,7 @@ def TestVB(vbtest, bUseGenerated): # Result should be just the byref. assert vbtest.IncrementIntegerParam(1) == 2, "Could not pass an integer byref" - # Sigh - we cant have *both* "ommited byref" and optional args + # Sigh - we can't have *both* "ommited byref" and optional args # We really have to opt that args nominated as optional work as optional # rather than simply all byrefs working as optional. # assert vbtest.IncrementIntegerParam() == 1, "Could not pass an omitted integer byref" @@ -154,7 +154,7 @@ def TestVB(vbtest, bUseGenerated): assert ret == 2, f"Could not increment the integer - {ret}" TestVBInterface(vbtest) - # Python doesnt support byrefs without some sort of generated support. + # Python doesn't support byrefs without some sort of generated support. if bUseGenerated: # This is a VB function that takes a single byref # Hence 2 return values - function and byref. @@ -260,7 +260,7 @@ def _DoTestArray(vbtest, data, expected_exception=None): def TestArrays(vbtest, bUseGenerated): # Try and use a safe array (note that the VB code has this declared as a VARIANT - # and I cant work out how to force it to use native arrays! + # and I can't work out how to force it to use native arrays! # (NOTE Python will convert incoming arrays to tuples, so we pass a tuple, even tho # a list works fine - just makes it easier for us to compare the result! # Empty array @@ -315,7 +315,7 @@ def TestArrays(vbtest, bUseGenerated): except pythoncom.com_error as exc: assert ( exc.excepinfo[1] == "Python COM Server Internal Error" - ), f"Didnt get the correct exception - '{exc}'" + ), f"Didn't get the correct exception - '{exc}'" if bUseGenerated: # This one is a bit strange! The array param is "ByRef", as VB insists. diff --git a/com/win32com/test/util.py b/com/win32com/test/util.py index 8fd15c40e4..d66734a5c1 100644 --- a/com/win32com/test/util.py +++ b/com/win32com/test/util.py @@ -59,7 +59,7 @@ def RegisterPythonServer(filename, progids=None, verbose=0): else: # print(f"Skipping registration of '{filename}' - already registered") return - # needs registration - see if its likely! + # needs registration - see if it's likely! try: from win32com.shell.shell import IsUserAnAdmin except ImportError: @@ -100,7 +100,7 @@ def ExecuteShellCommand( tracebacks_ok=0, # OK if the output contains a t/b? ): output_name = tempfile.mktemp("win32com_test") - cmd = cmd + ' > "%s" 2>&1' % output_name + cmd += ' > "%s" 2>&1' % output_name rc = os.system(cmd) output = open(output_name, "r").read().strip() os.remove(output_name) diff --git a/com/win32com/universal.py b/com/win32com/universal.py index 5fcbe1ce5b..4b759fd70f 100644 --- a/com/win32com/universal.py +++ b/com/win32com/universal.py @@ -93,7 +93,7 @@ def _doCreateVTable(iid, interface_name, is_dispatch, method_defs): def _CalcTypeSize(typeTuple): t = typeTuple[0] if t & (pythoncom.VT_BYREF | pythoncom.VT_ARRAY): - # Its a pointer. + # It's a pointer. cb = _univgw.SizeOfVT(pythoncom.VT_PTR)[1] elif t == pythoncom.VT_RECORD: # Just because a type library uses records doesn't mean the user @@ -131,7 +131,7 @@ def __init__(self, method_info, isEventSink=0): self.dispid = dispid self.invkind = invkind - # We dont use this ATM. + # We don't use this ATM. # self.ret = Arg(ret_def) if isEventSink and name[:2] != "On": name = "On%s" % name @@ -141,7 +141,7 @@ def __init__(self, method_info, isEventSink=0): for argDesc in arg_defs: arg = Arg(argDesc) arg.offset = cbArgs - cbArgs = cbArgs + arg.size + cbArgs += arg.size self.args.append(arg) self.cbArgs = cbArgs self._gw_in_args = self._GenerateInArgTuple() diff --git a/com/win32comext/adsi/__init__.py b/com/win32comext/adsi/__init__.py index 1b464d10a3..16afd3b784 100644 --- a/com/win32comext/adsi/__init__.py +++ b/com/win32comext/adsi/__init__.py @@ -88,7 +88,7 @@ def _NewEnum(self): try: return ADSIEnumerator(self) except pythoncom.com_error: - # doesnt support it - let our base try! + # doesn't support it - let our base try! return win32com.client.CDispatch._NewEnum(self) def __getattr__(self, attr): diff --git a/com/win32comext/adsi/demos/test.py b/com/win32comext/adsi/demos/test.py index 8cbf42b13c..43c85d6b83 100644 --- a/com/win32comext/adsi/demos/test.py +++ b/com/win32comext/adsi/demos/test.py @@ -73,15 +73,15 @@ def DumpSchema(): class_name = child.Class if class_name == "classSchema": _DumpClass(child) - nclasses = nclasses + 1 + nclasses += 1 elif class_name == "attributeSchema": _DumpAttribute(child) - nattr = nattr + 1 + nattr += 1 elif class_name == "subSchema": - nsub = nsub + 1 + nsub += 1 else: print("Unknown class:", class_name) - nunk = nunk + 1 + nunk += 1 if verbose_level: print("Processed", nclasses, "classes") print("Processed", nattr, "attributes") @@ -160,7 +160,7 @@ def DumpSchema2(): print( f"Class: Name={item.Name}, Flags={desc}, Primary Interface={iid_name}" ) - nclass = nclass + 1 + nclass += 1 elif item_class == "property": if item.MultiValued: val_type = "Multi-Valued" @@ -168,12 +168,12 @@ def DumpSchema2(): val_type = "Single-Valued" if verbose_level >= 2: print(f"Property: Name={item.Name}, {val_type}") - nprop = nprop + 1 + nprop += 1 elif item_class == "syntax": data_type = vt_map.get(item.OleAutoDataType, "") if verbose_level >= 2: print(f"Syntax: Name={item.Name}, Datatype = {data_type}") - nsyntax = nsyntax + 1 + nsyntax += 1 if verbose_level >= 1: print("Processed", nclass, "classes") print("Processed", nprop, "properties") @@ -236,14 +236,14 @@ def main(): for opt, val in opts: if opt == "-s": if val[-1] not in "\\/": - val = val + "/" + val += "/" global server server = val if opt == "-h": usage(tests) if opt == "-v": global verbose_level - verbose_level = verbose_level + 1 + verbose_level += 1 if len(args) == 0: print("Running all tests - use '-h' to see command-line options...") diff --git a/com/win32comext/adsi/src/PyADSIUtil.cpp b/com/win32comext/adsi/src/PyADSIUtil.cpp index 31663ae6b4..07f3093d19 100644 --- a/com/win32comext/adsi/src/PyADSIUtil.cpp +++ b/com/win32comext/adsi/src/PyADSIUtil.cpp @@ -37,7 +37,7 @@ PyObject *OleSetADSIError(HRESULT hr, IUnknown *pUnk, REFIID iid) info.bstrSource = SysAllocString(szNameBuf); info.bstrDescription = SysAllocString(szErrorBuf); // Technically, we probably should return DISP_E_EXCEPTION so we - // appear to follow COM's rules - however, we really dont + // appear to follow COM's rules - however, we really don't // _need_ to (as only Python sees this result), and having the native // HRESULT is preferable. return PyCom_BuildPyExceptionFromEXCEPINFO(dwErrCode, &info); @@ -61,7 +61,7 @@ PyObject *OleSetADSIError(HRESULT hr, IUnknown *pUnk, REFIID iid) info.bstrSource = SysAllocString(szNameBuf); info.bstrDescription = SysAllocString(szErrorBuf); // Technically, we probably should return DISP_E_EXCEPTION so we - // appear to follow COM's rules - however, we really dont + // appear to follow COM's rules - however, we really don't // _need_ to (as only Python sees this result), and having the native // HRESULT is preferable. return PyCom_BuildPyExceptionFromEXCEPINFO(dwErrCode, &info); @@ -162,7 +162,7 @@ BOOL PyADSIObject_AsTypedValue(PyObject *val, ADSVALUE &v) { BOOL ok = TRUE; switch (v.dwType) { - // OK - get lazy - we know its a union! + // OK - get lazy - we know it's a union! case ADSTYPE_DN_STRING: case ADSTYPE_CASE_EXACT_STRING: case ADSTYPE_CASE_IGNORE_STRING: @@ -184,7 +184,7 @@ BOOL PyADSIObject_AsTypedValue(PyObject *val, ADSVALUE &v) ok = PyWinObject_AsLARGE_INTEGER(val, &v.LargeInteger); break; default: - PyErr_SetString(PyExc_TypeError, "Cant convert to this type"); + PyErr_SetString(PyExc_TypeError, "Can't convert to this type"); return FALSE; } return ok; @@ -470,9 +470,9 @@ class PyADS_ATTR_INFO : public PyObject { return PyObject_GenericGetAttr(self, obname); } - //#pragma warning( disable : 4251 ) + // #pragma warning( disable : 4251 ) static struct PyMemberDef memberlist[]; - //#pragma warning( default : 4251 ) + // #pragma warning( default : 4251 ) static PyTypeObject Type; protected: @@ -675,7 +675,7 @@ BOOL PyADSIObject_AsADS_SEARCHPREF_INFOs(PyObject *ob, ADS_SEARCHPREF_INFO **ppr // ADSERR.h is built from a message file. // Therefore, there _must_ be a DLL around we can call // FormatMessage with. -// However, its not obvious, and this code was cut directly from MSDN. +// However, it's not obvious, and this code was cut directly from MSDN. #include "adserr.h" typedef struct tagADSERRMSG { HRESULT hr; diff --git a/com/win32comext/adsi/src/adsi.i b/com/win32comext/adsi/src/adsi.i index fa569b93a5..838ccee430 100644 --- a/com/win32comext/adsi/src/adsi.i +++ b/com/win32comext/adsi/src/adsi.i @@ -135,7 +135,7 @@ class PyIADsEnumVARIANT : public PyIEnumVARIANT { virtual ~PyIADsEnumVARIANT() { if (m_obj) { ADsFreeEnumerator((IEnumVARIANT *)m_obj); - m_obj = NULL; // so base dtor doesnt "Release" + m_obj = NULL; // so base dtor doesn't "Release" } } }; diff --git a/com/win32comext/axdebug/Test/host.py b/com/win32comext/axdebug/Test/host.py index 44b6f9a7c7..e9e95df545 100644 --- a/com/win32comext/axdebug/Test/host.py +++ b/com/win32comext/axdebug/Test/host.py @@ -15,11 +15,11 @@ class ExternalConnection: numExtRefs = 0 def AddConnection(self, extconn, reserved): - self.numExtRefs = self.numExtRefs + 1 + self.numExtRefs += 1 return self.numExtRefs def ReleaseConnection(self, extconn, reserved, fLastReleaseCloses): - self.numExtRefs = self.numExtRefs - 1 + self.numExtRefs -= 1 return self.numExtRefs diff --git a/com/win32comext/axdebug/adb.py b/com/win32comext/axdebug/adb.py index 2345ce5d69..b947627c96 100644 --- a/com/win32comext/axdebug/adb.py +++ b/com/win32comext/axdebug/adb.py @@ -148,7 +148,7 @@ def break_anywhere(self, frame): def dispatch_return(self, frame, arg): traceenter("dispatch_return", _dumpf(frame), arg) if self.logicalbotframe is frame: - # We dont want to debug parent frames. + # We don't want to debug parent frames. tracev("dispatch_return resetting sys.trace") sys.settrace(None) return diff --git a/com/win32comext/axdebug/codecontainer.py b/com/win32comext/axdebug/codecontainer.py index d6d48048f3..d82ee00089 100644 --- a/com/win32comext/axdebug/codecontainer.py +++ b/com/win32comext/axdebug/codecontainer.py @@ -55,7 +55,7 @@ def GetText(self): return self.text def GetName(self, dnt): - assert 0, "You must subclass this" + raise NotImplementedError("You must subclass this") def GetFileName(self): return self.fileName @@ -75,9 +75,9 @@ def GetLineOfPosition(self, charPos): if lineOffset > charPos: break lastOffset = lineOffset - lineNo = lineNo + 1 + lineNo += 1 else: # for not broken. - # print("Cant find", charPos, "in", self.lineOffsets) + # print("Can't find", charPos, "in", self.lineOffsets) raise COMException(scode=winerror.S_FALSE) # print("GLOP ret=", lineNo, (charPos - lastOffset)) return lineNo, (charPos - lastOffset) @@ -87,7 +87,7 @@ def GetNextLine(self): self.nextLineNo = 0 # auto-reset. return "" rc = self.lines[self.nextLineNo] - self.nextLineNo = self.nextLineNo + 1 + self.nextLineNo += 1 return rc def GetLine(self, num): @@ -261,12 +261,12 @@ def GetName(self, dnt): attrlen = 0 for attr in attrs: if isinstance(attr, tuple): - attrlen = attrlen + attr[1] + attrlen += attr[1] else: - attrlen = attrlen + 1 + attrlen += 1 text = sc.GetText() if attrlen != len(text): - print(f"Lengths dont match!!! ({attrlen}/{len(text)})") + print(f"Lengths don't match!!! ({attrlen}/{len(text)})") # print("Attributes:") # print(attrs) diff --git a/com/win32comext/axdebug/contexts.py b/com/win32comext/axdebug/contexts.py index 08443b2515..df6e97760f 100644 --- a/com/win32comext/axdebug/contexts.py +++ b/com/win32comext/axdebug/contexts.py @@ -11,7 +11,7 @@ class DebugCodeContext(gateways.DebugCodeContext, gateways.DebugDocumentContext): # NOTE: We also implement the IDebugDocumentContext interface for Simple Hosts. # Thus, debugDocument may be NULL when we have smart hosts - but in that case, we - # wont be called upon to provide it. + # won't be called upon to provide it. _public_methods_ = ( gateways.DebugCodeContext._public_methods_ + gateways.DebugDocumentContext._public_methods_ @@ -40,7 +40,7 @@ def GetDocumentContext(self): self.codeContainer.sourceContext, self.offset, self.length ) else: - # Simple host - Fine - Ill do it myself! + # Simple host - Fine - I'll do it myself! return _wrap(self, axdebug.IID_IDebugDocumentContext) def SetBreakPoint(self, bps): diff --git a/com/win32comext/axdebug/debugger.py b/com/win32comext/axdebug/debugger.py index 65a682680c..c0b1089f10 100644 --- a/com/win32comext/axdebug/debugger.py +++ b/com/win32comext/axdebug/debugger.py @@ -81,7 +81,7 @@ def __init__(self, axdebugger): self.axdebugger.RefreshAllModules(self.nodes, self) def FromFileName(self, fname): - # It appears we cant add modules during a debug session! + # It appears we can't add modules during a debug session! # if self.currentNumModules != len(sys.modules): # self.axdebugger.RefreshAllModules(self.nodes, self) # self.currentNumModules = len(sys.modules) diff --git a/com/win32comext/axdebug/gateways.py b/com/win32comext/axdebug/gateways.py index 19f803eaf6..beefab2e63 100644 --- a/com/win32comext/axdebug/gateways.py +++ b/com/win32comext/axdebug/gateways.py @@ -440,7 +440,7 @@ def Advise(self, pUnk): # Creates a connection to the client. Simply allocate a new cookie, # find the clients interface, and store it in a dictionary. interface = pUnk.QueryInterface(axdebug.IID_IDebugDocumentTextEvents, 1) - self.cookieNo = self.cookieNo + 1 + self.cookieNo += 1 self.connections[self.cookieNo] = interface return self.cookieNo diff --git a/com/win32comext/axdebug/stackframe.py b/com/win32comext/axdebug/stackframe.py index a5c888872c..16994715cb 100644 --- a/com/win32comext/axdebug/stackframe.py +++ b/com/win32comext/axdebug/stackframe.py @@ -30,7 +30,7 @@ def __init__(self, debugger): try: address = frame.f_locals["__axstack_address__"] except KeyError: - # print("Couldnt find stack address for",frame.f_code.co_filename, frame.f_lineno-1) + # print("Couldn't find stack address for",frame.f_code.co_filename, frame.f_lineno-1) # Use this one, even tho it is wrong :-( address = axdebug.GetStackAddress() frameInfo = ( @@ -107,11 +107,11 @@ def GetDescriptionString(self, fLong): filename = self.frame.f_code.co_filename s = "" if 0: # fLong: - s = s + filename + s += filename if self.frame.f_code.co_name: - s = s + self.frame.f_code.co_name + s += self.frame.f_code.co_name else: - s = s + "" + s += "" return s def GetLanguageString(self, fLong): diff --git a/com/win32comext/axscript/client/debug.py b/com/win32comext/axscript/client/debug.py index bdae7aac62..554f96095a 100644 --- a/com/win32comext/axscript/client/debug.py +++ b/com/win32comext/axscript/client/debug.py @@ -61,7 +61,7 @@ def __init__(self, scriptEngine): if self.debugApplication is None: # Try to get/create the default one - # NOTE - Dont catch exceptions here - let the parent do it, + # NOTE - Don't catch exceptions here - let the parent do it, # so it knows debug support is available. pdm = pythoncom.CoCreateInstance( axdebug.CLSID_ProcessDebugManager, @@ -144,7 +144,7 @@ def OnLeaveScript(self): self.adb.ResetAXDebugging() def AddScriptBlock(self, codeBlock): - # If we dont have debugging support, dont bother. + # If we don't have debugging support, don't bother. cc = DebugCodeBlockContainer(codeBlock, self.scriptSiteDebug) if self.IsSimpleHost(): document = documents.DebugDocumentText(cc) diff --git a/com/win32comext/axscript/client/framework.py b/com/win32comext/axscript/client/framework.py index 5f37626815..3e836103e7 100644 --- a/com/win32comext/axscript/client/framework.py +++ b/com/win32comext/axscript/client/framework.py @@ -140,7 +140,7 @@ def __init__( self.beenExecuted = 0 def GetFileName(self): - # Gets the "file name" for Python - uses <...> so Python doesnt think + # Gets the "file name" for Python - uses <...> so Python doesn't think # it is a real file. return "<%s>" % self.name @@ -487,7 +487,7 @@ def FindBuildSubItemEvents(self): fdesc = defaultType.GetFuncDesc(index) except pythoncom.com_error: break # No more funcs - index = index + 1 + index += 1 dispid = fdesc[0] funckind = fdesc[3] invkind = fdesc[4] @@ -690,9 +690,9 @@ def ParseScriptText( or self.scriptState == axscript.SCRIPTSTATE_CONNECTED or self.scriptState == axscript.SCRIPTSTATE_DISCONNECTED ): - flags = flags | SCRIPTTEXT_FORCEEXECUTION + flags |= SCRIPTTEXT_FORCEEXECUTION else: - flags = flags & (~SCRIPTTEXT_FORCEEXECUTION) + flags &= ~SCRIPTTEXT_FORCEEXECUTION if flags & SCRIPTTEXT_FORCEEXECUTION: # About to execute the code. @@ -924,7 +924,7 @@ def Clone(self): # IObjectSafety # Note that IE seems to insist we say we support all the flags, even tho - # we dont accept them all. If unknown flags come in, they are ignored, and never + # we don't accept them all. If unknown flags come in, they are ignored, and never # reflected in GetInterfaceSafetyOptions and the QIs obviously fail, but still IE # allows our engine to initialize. def SetInterfaceSafetyOptions(self, iid, optionsMask, enabledOptions): @@ -1200,19 +1200,19 @@ def HandleException(self, codeBlock: AXScriptCodeBlock | None) -> NoReturn: # likely to have originated from the script code itself, and therefore # needs to be reported like any other exception. if IsCOMServerException(exc_type): - # Ensure the traceback doesnt cause a cycle. + # Ensure the traceback doesn't cause a cycle. raise # It could be an error by another script. if ( isinstance(exc_value, pythoncom.com_error) and exc_value.hresult == axscript.SCRIPT_E_REPORTED ): - # Ensure the traceback doesnt cause a cycle. + # Ensure the traceback doesn't cause a cycle. raise COMException(scode=exc_value.hresult) exception = error.AXScriptException(self, codeBlock, exc_value=exc_value) - # Ensure the traceback doesnt cause a cycle. + # Ensure the traceback doesn't cause a cycle. result_exception = error.ProcessAXScriptException( self.scriptSite, self.debugManager, exception ) diff --git a/com/win32comext/axscript/client/pyscript.py b/com/win32comext/axscript/client/pyscript.py index d53559e300..5bf46eb801 100644 --- a/com/win32comext/axscript/client/pyscript.py +++ b/com/win32comext/axscript/client/pyscript.py @@ -238,7 +238,7 @@ def Reset(self): return framework.COMScript.Reset(self) def _GetNextCodeBlockNumber(self): - self.codeBlockCounter = self.codeBlockCounter + 1 + self.codeBlockCounter += 1 return self.codeBlockCounter def RegisterNamedItem(self, item): @@ -341,8 +341,8 @@ def DoProcessScriptItemEvent(self, item, event, lcid, wFlags, args): if codeBlock is not None: realCode = "def %s():\n" % funcName for line in framework.RemoveCR(codeBlock.codeText).split("\n"): - realCode = realCode + "\t" + line + "\n" - realCode = realCode + "\n" + realCode += "\t" + line + "\n" + realCode += "\n" if not self.CompileInScriptedSection(codeBlock, "exec", realCode): return dict = {} @@ -382,7 +382,7 @@ def DoParseScriptText( num = self._GetNextCodeBlockNumber() if num == 1: num = "" - name = f"{name} {num}" + name += f" {num}" codeBlock = AXScriptCodeBlock( name, code, sourceContextCookie, startLineNumber, flags ) diff --git a/com/win32comext/axscript/demos/client/ie/FOO.HTM b/com/win32comext/axscript/demos/client/ie/FOO.HTM index 34a880fa8d..5565025424 100644 --- a/com/win32comext/axscript/demos/client/ie/FOO.HTM +++ b/com/win32comext/axscript/demos/client/ie/FOO.HTM @@ -1,6 +1,6 @@ -Lets try this out: +Let's try this out:
    diff --git a/com/win32comext/axscript/demos/client/ie/demo_intro.htm b/com/win32comext/axscript/demos/client/ie/demo_intro.htm index 94494ec16b..9987d89726 100644 --- a/com/win32comext/axscript/demos/client/ie/demo_intro.htm +++ b/com/win32comext/axscript/demos/client/ie/demo_intro.htm @@ -26,7 +26,7 @@

    Object model

    Known bugs and problems

      -
    • This release seems to have broken Aaron's mouse-trace sample. No idea why, and Im supposed to be looking into it. +

    • This release seems to have broken Aaron's mouse-trace sample. No idea why, and I'm supposed to be looking into it.

    • Builtin objects such as MARQUEE are giving me grief. Objects accessed via forms are generally no problem.

    • If you are trying to use Python with the Windows Scripting Host, note that diff --git a/com/win32comext/axscript/demos/client/ie/foo2.htm b/com/win32comext/axscript/demos/client/ie/foo2.htm index d967822b9e..7849dfb8db 100644 --- a/com/win32comext/axscript/demos/client/ie/foo2.htm +++ b/com/win32comext/axscript/demos/client/ie/foo2.htm @@ -61,7 +61,7 @@ @@ -84,7 +84,7 @@ print("Y is ", y) def PythonGlobalFunction(): - window.alert("Hello from Python - Im about to call JScript!") + window.alert("Hello from Python - I'm about to call JScript!") window.JScriptFunction() def Window_OnLoad(): diff --git a/com/win32comext/axscript/src/AXScript.h b/com/win32comext/axscript/src/AXScript.h index 687e065233..902e7cce63 100644 --- a/com/win32comext/axscript/src/AXScript.h +++ b/com/win32comext/axscript/src/AXScript.h @@ -126,7 +126,7 @@ class PYAXSCRIPT_EXPORT PyGActiveScript : public PyGatewayBase, public IActiveSc STDMETHOD(GetScriptState) (THIS_ - /* [out] */ SCRIPTSTATE *pssState); + /* [out] */ SCRIPTSTATE *pssState); STDMETHOD(Close)(void); diff --git a/com/win32comext/axscript/src/PyGActiveScript.cpp b/com/win32comext/axscript/src/PyGActiveScript.cpp index 88bc70fe94..dad76db297 100644 --- a/com/win32comext/axscript/src/PyGActiveScript.cpp +++ b/com/win32comext/axscript/src/PyGActiveScript.cpp @@ -143,7 +143,7 @@ STDMETHODIMP PyGActiveScript::GetScriptThreadID( hr = PyCom_SetCOMErrorFromPyException(GetIID()); } else - hr = PyCom_SetCOMErrorFromSimple(E_FAIL, GetIID(), L"Python didnt return an integer"); + hr = PyCom_SetCOMErrorFromSimple(E_FAIL, GetIID(), L"Python didn't return an integer"); return hr; } diff --git a/com/win32comext/axscript/test/leakTest.py b/com/win32comext/axscript/test/leakTest.py index 98a589d3ef..7b52e36a98 100644 --- a/com/win32comext/axscript/test/leakTest.py +++ b/com/win32comext/axscript/test/leakTest.py @@ -51,7 +51,7 @@ def echo(self, *args): # self._connect_server_.Broadcast(last) -#### Connections currently wont work, as there is no way for the engine to +#### Connections currently won't work, as there is no way for the engine to #### know what events we support. We need typeinfo support. IID_ITestEvents = pythoncom.MakeIID("{8EB72F90-0D44-11d1-9C4B-00AA00125A98}") @@ -145,7 +145,7 @@ def doTestEngine(engine, echoer): print("***** Calling 'hello' failed", exc) return if echoer.last != "Goober": - print("***** Function call didnt set value correctly", repr(echoer.last)) + print("***** Function call didn't set value correctly", repr(echoer.last)) if str(ob.prop) != "Property Value": print("***** Property Value not correct - ", repr(ob.prop)) diff --git a/com/win32comext/axscript/test/testHost.py b/com/win32comext/axscript/test/testHost.py index 1dba19ed11..3b1181bb6c 100644 --- a/com/win32comext/axscript/test/testHost.py +++ b/com/win32comext/axscript/test/testHost.py @@ -69,7 +69,7 @@ def fail(self, *args): # self._connect_server_.Broadcast(last) -#### Connections currently wont work, as there is no way for the engine to +#### Connections currently won't work, as there is no way for the engine to #### know what events we support. We need typeinfo support. IID_ITestEvents = pythoncom.MakeIID("{8EB72F90-0D44-11d1-9C4B-00AA00125A98}") diff --git a/com/win32comext/directsound/src/PyIDirectSoundCaptureBuffer.cpp b/com/win32comext/directsound/src/PyIDirectSoundCaptureBuffer.cpp index 9654529b61..75ccf1f8de 100644 --- a/com/win32comext/directsound/src/PyIDirectSoundCaptureBuffer.cpp +++ b/com/win32comext/directsound/src/PyIDirectSoundCaptureBuffer.cpp @@ -322,7 +322,7 @@ PyObject *PyIDirectSoundCaptureBuffer::Update(PyObject *self, PyObject *args) return obData; -error : { +error: { // need extra block for local variables from PY_INTERFACE_UPCALL macro PY_INTERFACE_PRECALL; hr = pIDSCB->Unlock(lpAudioPtr1, dwAudioBytes1, lpAudioPtr2, dwAudioBytes2); diff --git a/com/win32comext/directsound/src/directsound.cpp b/com/win32comext/directsound/src/directsound.cpp index dc4c2d42c7..fa56e6acbc 100644 --- a/com/win32comext/directsound/src/directsound.cpp +++ b/com/win32comext/directsound/src/directsound.cpp @@ -422,7 +422,7 @@ PYWIN_MODULE_INIT_FUNC(directsound) ADD_CONSTANT(DS_OK); ADD_CONSTANT(DS_NO_VIRTUALIZATION); -// ADD_CONSTANT(DS_INCOMPLETE); not sure why this can't be found? + // ADD_CONSTANT(DS_INCOMPLETE); not sure why this can't be found? ADD_CONSTANT(DSERR_ACCESSDENIED); ADD_CONSTANT(DSERR_ALLOCATED); ADD_CONSTANT(DSERR_ALREADYINITIALIZED); diff --git a/com/win32comext/ifilter/demo/filterDemo.py b/com/win32comext/ifilter/demo/filterDemo.py index 513f70081c..5c598fa98b 100644 --- a/com/win32comext/ifilter/demo/filterDemo.py +++ b/com/win32comext/ifilter/demo/filterDemo.py @@ -126,11 +126,11 @@ def Parse(self, fileName, maxErrors=10): errCnt = 0 if flags == CHUNK_TEXT: - # its a text segment - get all available text for this chunk. + # it's a text segment - get all available text for this chunk. body_chunks = properties.setdefault(propName, []) self._get_text(body_chunks) elif flags == CHUNK_VALUE: - # its a data segment - get the value + # it's a data segment - get the value properties[propName] = self.f.GetValue() else: self._trace("Unknown flag returned by GetChunk:", flags) diff --git a/com/win32comext/ifilter/src/stdafx.h b/com/win32comext/ifilter/src/stdafx.h index 6672c006db..8a9b1c26c5 100644 --- a/com/win32comext/ifilter/src/stdafx.h +++ b/com/win32comext/ifilter/src/stdafx.h @@ -4,7 +4,7 @@ // // _WIN32_DCOM screws win95 and NT :-( However, we need to define this -// so we dont lose all the constants etc that come with DCOM +// so we don't lose all the constants etc that come with DCOM // #define _WIN32_DCOM diff --git a/com/win32comext/internet/src/internet.cpp b/com/win32comext/internet/src/internet.cpp index c16f9e2f70..741af00070 100644 --- a/com/win32comext/internet/src/internet.cpp +++ b/com/win32comext/internet/src/internet.cpp @@ -106,7 +106,7 @@ BOOL PyObject_AsBINDINFO(PyObject *ob, BINDINFO *pPD) if (!PyWinObject_AsTaskAllocatedWCHAR(obExtra, &pPD->szExtraInfo, /*bNoneOK=*/TRUE)) goto done; if (obSTGM != Py_None) { - PyErr_SetString(PyExc_TypeError, "Sorry - dont support STGMEDIUM yet - must be None"); + PyErr_SetString(PyExc_TypeError, "Sorry - don't support STGMEDIUM yet - must be None"); goto done; } if (!PyWinObject_AsTaskAllocatedWCHAR(obCustomVerb, &pPD->szCustomVerb, /*bNoneOK=*/TRUE)) diff --git a/com/win32comext/mapi/mapiutil.py b/com/win32comext/mapi/mapiutil.py index 8716a650a9..896a8b0d0e 100644 --- a/com/win32comext/mapi/mapiutil.py +++ b/com/win32comext/mapi/mapiutil.py @@ -86,7 +86,7 @@ def GetMapiTypeName(propType, rawType=True): ptTable[value] = name if rawType: - propType = propType & ~mapitags.MV_FLAG + propType &= ~mapitags.MV_FLAG return ptTable.get(propType, str(hex(propType))) @@ -206,6 +206,6 @@ def SetProperties(msg, propDict): f"The type of object {repr(val)}({type(val)}) can not be written" ) key = mapitags.PROP_TAG(tagType, mapitags.PROP_ID(newIds[newIdNo])) - newIdNo = newIdNo + 1 + newIdNo += 1 newProps.append((key, val)) msg.SetProps(newProps) diff --git a/com/win32comext/mapi/src/PyIMAPIAdviseSink.cpp b/com/win32comext/mapi/src/PyIMAPIAdviseSink.cpp index 96cc759018..60cfe1ad31 100644 --- a/com/win32comext/mapi/src/PyIMAPIAdviseSink.cpp +++ b/com/win32comext/mapi/src/PyIMAPIAdviseSink.cpp @@ -54,8 +54,8 @@ PyObject *PyObject_FromNOTIFICATION(NOTIFICATION *n) #else "k(s#s#kNk)", #endif - n->ulEventType, newmail.lpEntryID, (Py_ssize_t)newmail.cbEntryID, newmail.lpParentID, (Py_ssize_t)newmail.cbParentID, - newmail.ulFlags, msg_class, newmail.ulMessageFlags); + n->ulEventType, newmail.lpEntryID, (Py_ssize_t)newmail.cbEntryID, newmail.lpParentID, + (Py_ssize_t)newmail.cbParentID, newmail.ulFlags, msg_class, newmail.ulMessageFlags); break; } case fnevObjectCopied: @@ -74,8 +74,9 @@ PyObject *PyObject_FromNOTIFICATION(NOTIFICATION *n) #else "k(s#is#s#s#N)", #endif - n->ulEventType, obj.lpEntryID, (Py_ssize_t)obj.cbEntryID, obj.ulObjType, obj.lpParentID, (Py_ssize_t)obj.cbParentID, - obj.lpOldID, (Py_ssize_t)obj.cbOldID, obj.lpOldParentID, (Py_ssize_t)obj.cbOldParentID, obArray); + n->ulEventType, obj.lpEntryID, (Py_ssize_t)obj.cbEntryID, obj.ulObjType, obj.lpParentID, + (Py_ssize_t)obj.cbParentID, obj.lpOldID, (Py_ssize_t)obj.cbOldID, obj.lpOldParentID, + (Py_ssize_t)obj.cbOldParentID, obArray); break; } case fnevTableModified: { diff --git a/com/win32comext/mapi/src/mapi_headers/EdkMdb.h b/com/win32comext/mapi/src/mapi_headers/EdkMdb.h index 887d64c351..6de3859165 100644 --- a/com/win32comext/mapi/src/mapi_headers/EdkMdb.h +++ b/com/win32comext/mapi/src/mapi_headers/EdkMdb.h @@ -17,22 +17,21 @@ * literals declared here instead of the numerical values. */ -#define pidStoreNonTransMin 0x0E40 -#define pidExchangeXmitReservedMin 0x3FE0 -#define pidExchangeNonXmitReservedMin 0x65E0 -#define pidProfileMin 0x6600 -#define pidStoreMin 0x6618 -#define pidFolderMin 0x6638 -#define pidMessageReadOnlyMin 0x6640 -#define pidMessageWriteableMin 0x6658 -#define pidAttachReadOnlyMin 0x666C -#define pidSpecialMin 0x6670 -#define pidAdminMin 0x6690 -#define pidSecureProfileMin PROP_ID_SECURE_MIN -#define pidRenMsgFldMin 0x1080 -#define pidLocalStoreInternalMin 0x6500 // Using a portion of the user-defined non-tranmittable prop for local store -#define pidLocalStoreInternalMax 0x65C0 - +#define pidStoreNonTransMin 0x0E40 +#define pidExchangeXmitReservedMin 0x3FE0 +#define pidExchangeNonXmitReservedMin 0x65E0 +#define pidProfileMin 0x6600 +#define pidStoreMin 0x6618 +#define pidFolderMin 0x6638 +#define pidMessageReadOnlyMin 0x6640 +#define pidMessageWriteableMin 0x6658 +#define pidAttachReadOnlyMin 0x666C +#define pidSpecialMin 0x6670 +#define pidAdminMin 0x6690 +#define pidSecureProfileMin PROP_ID_SECURE_MIN +#define pidRenMsgFldMin 0x1080 +#define pidLocalStoreInternalMin 0x6500 // Using a portion of the user-defined non-tranmittable prop for local store +#define pidLocalStoreInternalMax 0x65C0 /*------------------------------------------------------------------------ * @@ -49,136 +48,132 @@ /* GUID of the global section */ -#define pbGlobalProfileSectionGuid "\x13\xDB\xB0\xC8\xAA\x05\x10\x1A\x9B\xB0\x00\xAA\x00\x2F\xC4\x5A" - +#define pbGlobalProfileSectionGuid "\x13\xDB\xB0\xC8\xAA\x05\x10\x1A\x9B\xB0\x00\xAA\x00\x2F\xC4\x5A" /* Properties in the global section */ -#define PR_PROFILE_VERSION PROP_TAG( PT_LONG, pidProfileMin+0x00) -#define PR_PROFILE_CONFIG_FLAGS PROP_TAG( PT_LONG, pidProfileMin+0x01) -#define PR_PROFILE_HOME_SERVER PROP_TAG( PT_STRING8, pidProfileMin+0x02) -#define PR_PROFILE_HOME_SERVER_DN PROP_TAG( PT_STRING8, pidProfileMin+0x12) -#define PR_PROFILE_HOME_SERVER_ADDRS PROP_TAG( PT_MV_STRING8, pidProfileMin+0x13) -#define PR_PROFILE_USER PROP_TAG( PT_STRING8, pidProfileMin+0x03) -#define PR_PROFILE_CONNECT_FLAGS PROP_TAG( PT_LONG, pidProfileMin+0x04) -#define PR_PROFILE_TRANSPORT_FLAGS PROP_TAG( PT_LONG, pidProfileMin+0x05) -#define PR_PROFILE_UI_STATE PROP_TAG( PT_LONG, pidProfileMin+0x06) -#define PR_PROFILE_UNRESOLVED_NAME PROP_TAG( PT_STRING8, pidProfileMin+0x07) -#define PR_PROFILE_UNRESOLVED_SERVER PROP_TAG( PT_STRING8, pidProfileMin+0x08) -#define PR_PROFILE_BINDING_ORDER PROP_TAG( PT_STRING8, pidProfileMin+0x09) -#define PR_PROFILE_MAX_RESTRICT PROP_TAG( PT_LONG, pidProfileMin+0x0D) -#define PR_PROFILE_AB_FILES_PATH PROP_TAG( PT_STRING8, pidProfileMin+0xE) -#define PR_PROFILE_OFFLINE_STORE_PATH PROP_TAG( PT_STRING8, pidProfileMin+0x10) -#define PR_PROFILE_OFFLINE_INFO PROP_TAG( PT_BINARY, pidProfileMin+0x11) -#define PR_PROFILE_ADDR_INFO PROP_TAG( PT_BINARY, pidSpecialMin+0x17) -#define PR_PROFILE_OPTIONS_DATA PROP_TAG( PT_BINARY, pidSpecialMin+0x19) -#define PR_PROFILE_SECURE_MAILBOX PROP_TAG( PT_BINARY, pidSecureProfileMin + 0) -#define PR_DISABLE_WINSOCK PROP_TAG( PT_LONG, pidProfileMin+0x18) -#define PR_PROFILE_AUTH_PACKAGE PROP_TAG( PT_LONG, pidProfileMin+0x19) // dup tag of PR_USER_ENTRYID -#define PR_PROFILE_RECONNECT_INTERVAL PROP_TAG( PT_LONG, pidProfileMin+0x1a) // dup tag of PR_USER_NAME -#define PR_PROFILE_SERVER_VERSION PROP_TAG( PT_LONG, pidProfileMin+0x1b) +#define PR_PROFILE_VERSION PROP_TAG(PT_LONG, pidProfileMin + 0x00) +#define PR_PROFILE_CONFIG_FLAGS PROP_TAG(PT_LONG, pidProfileMin + 0x01) +#define PR_PROFILE_HOME_SERVER PROP_TAG(PT_STRING8, pidProfileMin + 0x02) +#define PR_PROFILE_HOME_SERVER_DN PROP_TAG(PT_STRING8, pidProfileMin + 0x12) +#define PR_PROFILE_HOME_SERVER_ADDRS PROP_TAG(PT_MV_STRING8, pidProfileMin + 0x13) +#define PR_PROFILE_USER PROP_TAG(PT_STRING8, pidProfileMin + 0x03) +#define PR_PROFILE_CONNECT_FLAGS PROP_TAG(PT_LONG, pidProfileMin + 0x04) +#define PR_PROFILE_TRANSPORT_FLAGS PROP_TAG(PT_LONG, pidProfileMin + 0x05) +#define PR_PROFILE_UI_STATE PROP_TAG(PT_LONG, pidProfileMin + 0x06) +#define PR_PROFILE_UNRESOLVED_NAME PROP_TAG(PT_STRING8, pidProfileMin + 0x07) +#define PR_PROFILE_UNRESOLVED_SERVER PROP_TAG(PT_STRING8, pidProfileMin + 0x08) +#define PR_PROFILE_BINDING_ORDER PROP_TAG(PT_STRING8, pidProfileMin + 0x09) +#define PR_PROFILE_MAX_RESTRICT PROP_TAG(PT_LONG, pidProfileMin + 0x0D) +#define PR_PROFILE_AB_FILES_PATH PROP_TAG(PT_STRING8, pidProfileMin + 0xE) +#define PR_PROFILE_OFFLINE_STORE_PATH PROP_TAG(PT_STRING8, pidProfileMin + 0x10) +#define PR_PROFILE_OFFLINE_INFO PROP_TAG(PT_BINARY, pidProfileMin + 0x11) +#define PR_PROFILE_ADDR_INFO PROP_TAG(PT_BINARY, pidSpecialMin + 0x17) +#define PR_PROFILE_OPTIONS_DATA PROP_TAG(PT_BINARY, pidSpecialMin + 0x19) +#define PR_PROFILE_SECURE_MAILBOX PROP_TAG(PT_BINARY, pidSecureProfileMin + 0) +#define PR_DISABLE_WINSOCK PROP_TAG(PT_LONG, pidProfileMin + 0x18) +#define PR_PROFILE_AUTH_PACKAGE PROP_TAG(PT_LONG, pidProfileMin + 0x19) // dup tag of PR_USER_ENTRYID +#define PR_PROFILE_RECONNECT_INTERVAL PROP_TAG(PT_LONG, pidProfileMin + 0x1a) // dup tag of PR_USER_NAME +#define PR_PROFILE_SERVER_VERSION PROP_TAG(PT_LONG, pidProfileMin + 0x1b) /* SE 233155 - MarkH: EMSABP DCR /* /* Properties in the abp section - I got these values from AlecDun (Outlook team) */ -#define PR_PROFILE_ABP_ALLOW_RECONNECT PROP_TAG( PT_LONG, pidProfileMin+0x39) -#define PR_PROFILE_ABP_MTHREAD_TIMEOUT_SECS PROP_TAG( PT_LONG, pidProfileMin+0x3A) +#define PR_PROFILE_ABP_ALLOW_RECONNECT PROP_TAG(PT_LONG, pidProfileMin + 0x39) +#define PR_PROFILE_ABP_MTHREAD_TIMEOUT_SECS PROP_TAG(PT_LONG, pidProfileMin + 0x3A) /* Properties passed through the Service Entry to the OST */ -#define PR_OST_ENCRYPTION PROP_TAG(PT_LONG, 0x6702) +#define PR_OST_ENCRYPTION PROP_TAG(PT_LONG, 0x6702) /* Values for PR_OST_ENCRYPTION */ -#define OSTF_NO_ENCRYPTION ((DWORD)0x80000000) -#define OSTF_COMPRESSABLE_ENCRYPTION ((DWORD)0x40000000) -#define OSTF_BEST_ENCRYPTION ((DWORD)0x20000000) +#define OSTF_NO_ENCRYPTION ((DWORD)0x80000000) +#define OSTF_COMPRESSABLE_ENCRYPTION ((DWORD)0x40000000) +#define OSTF_BEST_ENCRYPTION ((DWORD)0x20000000) /* Properties in each profile section */ -#define PR_PROFILE_OPEN_FLAGS PROP_TAG( PT_LONG, pidProfileMin+0x09) -#define PR_PROFILE_TYPE PROP_TAG( PT_LONG, pidProfileMin+0x0A) -#define PR_PROFILE_MAILBOX PROP_TAG( PT_STRING8, pidProfileMin+0x0B) -#define PR_PROFILE_SERVER PROP_TAG( PT_STRING8, pidProfileMin+0x0C) -#define PR_PROFILE_SERVER_DN PROP_TAG( PT_STRING8, pidProfileMin+0x14) +#define PR_PROFILE_OPEN_FLAGS PROP_TAG(PT_LONG, pidProfileMin + 0x09) +#define PR_PROFILE_TYPE PROP_TAG(PT_LONG, pidProfileMin + 0x0A) +#define PR_PROFILE_MAILBOX PROP_TAG(PT_STRING8, pidProfileMin + 0x0B) +#define PR_PROFILE_SERVER PROP_TAG(PT_STRING8, pidProfileMin + 0x0C) +#define PR_PROFILE_SERVER_DN PROP_TAG(PT_STRING8, pidProfileMin + 0x14) /* Properties in the Public Folders section */ -#define PR_PROFILE_FAVFLD_DISPLAY_NAME PROP_TAG(PT_STRING8, pidProfileMin+0x0F) -#define PR_PROFILE_FAVFLD_COMMENT PROP_TAG(PT_STRING8, pidProfileMin+0x15) -#define PR_PROFILE_ALLPUB_DISPLAY_NAME PROP_TAG(PT_STRING8, pidProfileMin+0x16) -#define PR_PROFILE_ALLPUB_COMMENT PROP_TAG(PT_STRING8, pidProfileMin+0x17) +#define PR_PROFILE_FAVFLD_DISPLAY_NAME PROP_TAG(PT_STRING8, pidProfileMin + 0x0F) +#define PR_PROFILE_FAVFLD_COMMENT PROP_TAG(PT_STRING8, pidProfileMin + 0x15) +#define PR_PROFILE_ALLPUB_DISPLAY_NAME PROP_TAG(PT_STRING8, pidProfileMin + 0x16) +#define PR_PROFILE_ALLPUB_COMMENT PROP_TAG(PT_STRING8, pidProfileMin + 0x17) /* Properties for Multiple Offline Address Book support (MOAB) */ -#define PR_PROFILE_MOAB PROP_TAG( PT_STRING8, pidSpecialMin + 0x0B ) -#define PR_PROFILE_MOAB_GUID PROP_TAG( PT_STRING8, pidSpecialMin + 0x0C ) -#define PR_PROFILE_MOAB_SEQ PROP_TAG( PT_LONG, pidSpecialMin + 0x0D ) +#define PR_PROFILE_MOAB PROP_TAG(PT_STRING8, pidSpecialMin + 0x0B) +#define PR_PROFILE_MOAB_GUID PROP_TAG(PT_STRING8, pidSpecialMin + 0x0C) +#define PR_PROFILE_MOAB_SEQ PROP_TAG(PT_LONG, pidSpecialMin + 0x0D) // Property for setting a list of prop_ids to be excluded // from the GetProps(NULL) call. -#define PR_GET_PROPS_EXCLUDE_PROP_ID_LIST PROP_TAG( PT_BINARY, pidSpecialMin + 0x0E ) +#define PR_GET_PROPS_EXCLUDE_PROP_ID_LIST PROP_TAG(PT_BINARY, pidSpecialMin + 0x0E) // Current value for PR_PROFILE_VERSION -#define PROFILE_VERSION ((ULONG)0x501) +#define PROFILE_VERSION ((ULONG)0x501) // Bit values for PR_PROFILE_CONFIG_FLAGS -#define CONFIG_SERVICE ((ULONG)0x00000001) -#define CONFIG_SHOW_STARTUP_UI ((ULONG)0x00000002) -#define CONFIG_SHOW_CONNECT_UI ((ULONG)0x00000004) -#define CONFIG_PROMPT_FOR_CREDENTIALS ((ULONG)0x00000008) -#define CONFIG_NO_AUTO_DETECT ((ULONG)0x00000010) -#define CONFIG_OST_CACHE_ONLY ((ULONG)0x00000020) +#define CONFIG_SERVICE ((ULONG)0x00000001) +#define CONFIG_SHOW_STARTUP_UI ((ULONG)0x00000002) +#define CONFIG_SHOW_CONNECT_UI ((ULONG)0x00000004) +#define CONFIG_PROMPT_FOR_CREDENTIALS ((ULONG)0x00000008) +#define CONFIG_NO_AUTO_DETECT ((ULONG)0x00000010) +#define CONFIG_OST_CACHE_ONLY ((ULONG)0x00000020) // Bit values for PR_PROFILE_CONNECT_FLAGS -#define CONNECT_USE_ADMIN_PRIVILEGE ((ULONG)1) -#define CONNECT_NO_RPC_ENCRYPTION ((ULONG)2) -#define CONNECT_USE_SEPARATE_CONNECTION ((ULONG)4) -#define CONNECT_NO_UNDER_COVER_CONNECTION ((ULONG)8) -#define CONNECT_ANONYMOUS_ACCESS ((ULONG)16) -#define CONNECT_NO_NOTIFICATIONS ((ULONG)32) -#define CONNECT_NO_TABLE_NOTIFICATIONS ((ULONG)32) /* BUGBUG: TEMPORARY */ -#define CONNECT_NO_ADDRESS_RESOLUTION ((ULONG)64) -#define CONNECT_RESTORE_DATABASE ((ULONG)128) - +#define CONNECT_USE_ADMIN_PRIVILEGE ((ULONG)1) +#define CONNECT_NO_RPC_ENCRYPTION ((ULONG)2) +#define CONNECT_USE_SEPARATE_CONNECTION ((ULONG)4) +#define CONNECT_NO_UNDER_COVER_CONNECTION ((ULONG)8) +#define CONNECT_ANONYMOUS_ACCESS ((ULONG)16) +#define CONNECT_NO_NOTIFICATIONS ((ULONG)32) +#define CONNECT_NO_TABLE_NOTIFICATIONS ((ULONG)32) /* BUGBUG: TEMPORARY */ +#define CONNECT_NO_ADDRESS_RESOLUTION ((ULONG)64) +#define CONNECT_RESTORE_DATABASE ((ULONG)128) // Bit values for PR_PROFILE_TRANSPORT_FLAGS -#define TRANSPORT_DOWNLOAD ((ULONG)1) -#define TRANSPORT_UPLOAD ((ULONG)2) +#define TRANSPORT_DOWNLOAD ((ULONG)1) +#define TRANSPORT_UPLOAD ((ULONG)2) // Bit values for PR_PROFILE_OPEN_FLAGS -#define OPENSTORE_USE_ADMIN_PRIVILEGE ((ULONG)0x00000001) -#define OPENSTORE_PUBLIC ((ULONG)0x00000002) -#define OPENSTORE_HOME_LOGON ((ULONG)0x00000004) -#define OPENSTORE_TAKE_OWNERSHIP ((ULONG)0x00000008) -#define OPENSTORE_OVERRIDE_HOME_MDB ((ULONG)0x00000010) -#define OPENSTORE_TRANSPORT ((ULONG)0x00000020) -#define OPENSTORE_REMOTE_TRANSPORT ((ULONG)0x00000040) -#define OPENSTORE_INTERNET_ANONYMOUS ((ULONG)0x00000080) -#define OPENSTORE_ALTERNATE_SERVER ((ULONG)0x00000100) /* reserved for internal use */ -#define OPENSTORE_IGNORE_HOME_MDB ((ULONG)0x00000200) /* reserved for internal use */ -#define OPENSTORE_NO_MAIL ((ULONG)0x00000400) /* reserved for internal use */ -#define OPENSTORE_OVERRIDE_LAST_MODIFIER ((ULONG)0x00000800) -#define OPENSTORE_CALLBACK_LOGON ((ULONG)0x00001000) /* reserved for internal use */ -#define OPENSTORE_LOCAL ((ULONG)0x00002000) -#define OPENSTORE_FAIL_IF_NO_MAILBOX ((ULONG)0x00004000) /* reserved for internal use */ -#define OPENSTORE_CACHE_EXCHANGE ((ULONG)0x00008000) -#define OPENSTORE_CLI_WITH_NAMEDPROP_FIX ((ULONG)0x00010000) /* reserved for internal use */ -#define OPENSTORE_ENABLE_LAZY_LOGGING ((ULONG)0x00020000) /* reserved for internal use */ -#define OPENSTORE_CLI_WITH_REPLID_GUID_MAPPING_FIX ((ULONG)0x00040000) /* reserved for internal use */ -#define OPENSTORE_NO_LOCALIZATION ((ULONG)0x00080000) /* reserved for internal use */ -#define OPENSTORE_RESTORE_DATABASE ((ULONG)0x00100000) -#define OPENSTORE_XFOREST_MOVE ((ULONG)0x00200000) /* reserved for internal use */ - +#define OPENSTORE_USE_ADMIN_PRIVILEGE ((ULONG)0x00000001) +#define OPENSTORE_PUBLIC ((ULONG)0x00000002) +#define OPENSTORE_HOME_LOGON ((ULONG)0x00000004) +#define OPENSTORE_TAKE_OWNERSHIP ((ULONG)0x00000008) +#define OPENSTORE_OVERRIDE_HOME_MDB ((ULONG)0x00000010) +#define OPENSTORE_TRANSPORT ((ULONG)0x00000020) +#define OPENSTORE_REMOTE_TRANSPORT ((ULONG)0x00000040) +#define OPENSTORE_INTERNET_ANONYMOUS ((ULONG)0x00000080) +#define OPENSTORE_ALTERNATE_SERVER ((ULONG)0x00000100) /* reserved for internal use */ +#define OPENSTORE_IGNORE_HOME_MDB ((ULONG)0x00000200) /* reserved for internal use */ +#define OPENSTORE_NO_MAIL ((ULONG)0x00000400) /* reserved for internal use */ +#define OPENSTORE_OVERRIDE_LAST_MODIFIER ((ULONG)0x00000800) +#define OPENSTORE_CALLBACK_LOGON ((ULONG)0x00001000) /* reserved for internal use */ +#define OPENSTORE_LOCAL ((ULONG)0x00002000) +#define OPENSTORE_FAIL_IF_NO_MAILBOX ((ULONG)0x00004000) /* reserved for internal use */ +#define OPENSTORE_CACHE_EXCHANGE ((ULONG)0x00008000) +#define OPENSTORE_CLI_WITH_NAMEDPROP_FIX ((ULONG)0x00010000) /* reserved for internal use */ +#define OPENSTORE_ENABLE_LAZY_LOGGING ((ULONG)0x00020000) /* reserved for internal use */ +#define OPENSTORE_CLI_WITH_REPLID_GUID_MAPPING_FIX ((ULONG)0x00040000) /* reserved for internal use */ +#define OPENSTORE_NO_LOCALIZATION ((ULONG)0x00080000) /* reserved for internal use */ +#define OPENSTORE_RESTORE_DATABASE ((ULONG)0x00100000) +#define OPENSTORE_XFOREST_MOVE ((ULONG)0x00200000) /* reserved for internal use */ // Values for PR_PROFILE_TYPE -#define PROFILE_PRIMARY_USER ((ULONG)1) -#define PROFILE_DELEGATE ((ULONG)2) -#define PROFILE_PUBLIC_STORE ((ULONG)3) -#define PROFILE_SUBSCRIPTION ((ULONG)4) - +#define PROFILE_PRIMARY_USER ((ULONG)1) +#define PROFILE_DELEGATE ((ULONG)2) +#define PROFILE_PUBLIC_STORE ((ULONG)3) +#define PROFILE_SUBSCRIPTION ((ULONG)4) /*------------------------------------------------------------------------ * @@ -188,111 +183,111 @@ /* PR_MDB_PROVIDER GUID in stores table */ -#define pbExchangeProviderPrimaryUserGuid "\x54\x94\xA1\xC0\x29\x7F\x10\x1B\xA5\x87\x08\x00\x2B\x2A\x25\x17" -#define pbExchangeProviderDelegateGuid "\x9e\xb4\x77\x00\x74\xe4\x11\xce\x8c\x5e\x00\xaa\x00\x42\x54\xe2" -#define pbExchangeProviderPublicGuid "\x78\xb2\xfa\x70\xaf\xf7\x11\xcd\x9b\xc8\x00\xaa\x00\x2f\xc4\x5a" -#define pbExchangeProviderXportGuid "\xa9\x06\x40\xe0\xd6\x93\x11\xcd\xaf\x95\x00\xaa\x00\x4a\x35\xc3" -#define pbExchangeProviderLocalStoreGuid "\x2D\xE5\x6B\xA1\x64\x6E\x11\xd2\x8D\x4E\x00\xC0\x4F\xAE\x23\x71" -#define pbExchangeProviderPersistStoreGuid "\x98\xA2\x3D\x67\x62\xCF\x4d\x34\x82\x79\xDB\xFA\x6A\x50\x8B\x31" +#define pbExchangeProviderPrimaryUserGuid "\x54\x94\xA1\xC0\x29\x7F\x10\x1B\xA5\x87\x08\x00\x2B\x2A\x25\x17" +#define pbExchangeProviderDelegateGuid "\x9e\xb4\x77\x00\x74\xe4\x11\xce\x8c\x5e\x00\xaa\x00\x42\x54\xe2" +#define pbExchangeProviderPublicGuid "\x78\xb2\xfa\x70\xaf\xf7\x11\xcd\x9b\xc8\x00\xaa\x00\x2f\xc4\x5a" +#define pbExchangeProviderXportGuid "\xa9\x06\x40\xe0\xd6\x93\x11\xcd\xaf\x95\x00\xaa\x00\x4a\x35\xc3" +#define pbExchangeProviderLocalStoreGuid "\x2D\xE5\x6B\xA1\x64\x6E\x11\xd2\x8D\x4E\x00\xC0\x4F\xAE\x23\x71" +#define pbExchangeProviderPersistStoreGuid "\x98\xA2\x3D\x67\x62\xCF\x4d\x34\x82\x79\xDB\xFA\x6A\x50\x8B\x31" // All properties in this section are readonly // Identity of store - // All stores -#define PR_USER_ENTRYID PROP_TAG( PT_BINARY, pidStoreMin+0x01) -#define PR_USER_NAME PROP_TAG( PT_STRING8, pidStoreMin+0x02) +// All stores +#define PR_USER_ENTRYID PROP_TAG(PT_BINARY, pidStoreMin + 0x01) +#define PR_USER_NAME PROP_TAG(PT_STRING8, pidStoreMin + 0x02) - // All mailbox stores -#define PR_MAILBOX_OWNER_ENTRYID PROP_TAG( PT_BINARY, pidStoreMin+0x03) -#define PR_MAILBOX_OWNER_NAME PROP_TAG( PT_STRING8, pidStoreMin+0x04) -#define PR_OOF_STATE PROP_TAG( PT_BOOLEAN, pidStoreMin+0x05) +// All mailbox stores +#define PR_MAILBOX_OWNER_ENTRYID PROP_TAG(PT_BINARY, pidStoreMin + 0x03) +#define PR_MAILBOX_OWNER_NAME PROP_TAG(PT_STRING8, pidStoreMin + 0x04) +#define PR_OOF_STATE PROP_TAG(PT_BOOLEAN, pidStoreMin + 0x05) // Bug#255023 Provide quota information to MAPI clients to avoid large emails from ever reaching the server -#define PR_MAX_SUBMIT_MESSAGE_SIZE PROP_TAG( PT_LONG, 0x666D) -#define PR_PROHIBIT_SEND_QUOTA PROP_TAG( PT_LONG, 0x666E) +#define PR_MAX_SUBMIT_MESSAGE_SIZE PROP_TAG(PT_LONG, 0x666D) +#define PR_PROHIBIT_SEND_QUOTA PROP_TAG(PT_LONG, 0x666E) - // Public stores -- name of hierarchy server -#define PR_HIERARCHY_SERVER PROP_TAG( PT_TSTRING, pidStoreMin+0x1B) +// Public stores -- name of hierarchy server +#define PR_HIERARCHY_SERVER PROP_TAG(PT_TSTRING, pidStoreMin + 0x1B) // Entryids of special folders - // All mailbox stores -#define PR_SCHEDULE_FOLDER_ENTRYID PROP_TAG( PT_BINARY, pidStoreMin+0x06) - - // All mailbox and gateway stores -#define PR_IPM_DAF_ENTRYID PROP_TAG( PT_BINARY, pidStoreMin+0x07) - - // Public store -#define PR_NON_IPM_SUBTREE_ENTRYID PROP_TAG( PT_BINARY, pidStoreMin+0x08) -#define PR_EFORMS_REGISTRY_ENTRYID PROP_TAG( PT_BINARY, pidStoreMin+0x09) -#define PR_SPLUS_FREE_BUSY_ENTRYID PROP_TAG( PT_BINARY, pidStoreMin+0x0A) -#define PR_OFFLINE_ADDRBOOK_ENTRYID PROP_TAG( PT_BINARY, pidStoreMin+0x0B) -#define PR_NNTP_CONTROL_FOLDER_ENTRYID PROP_TAG( PT_BINARY, pidSpecialMin+0x1B) -#define PR_EFORMS_FOR_LOCALE_ENTRYID PROP_TAG( PT_BINARY, pidStoreMin+0x0C) -#define PR_FREE_BUSY_FOR_LOCAL_SITE_ENTRYID PROP_TAG( PT_BINARY, pidStoreMin+0x0D) -#define PR_ADDRBOOK_FOR_LOCAL_SITE_ENTRYID PROP_TAG( PT_BINARY, pidStoreMin+0x0E) -#define PR_NEWSGROUP_ROOT_FOLDER_ENTRYID PROP_TAG( PT_BINARY, pidSpecialMin+0x1C) -#define PR_OFFLINE_MESSAGE_ENTRYID PROP_TAG( PT_BINARY, pidStoreMin+0x0F) -#define PR_IPM_FAVORITES_ENTRYID PROP_TAG( PT_BINARY, pidStoreMin+0x18) -#define PR_IPM_PUBLIC_FOLDERS_ENTRYID PROP_TAG( PT_BINARY, pidStoreMin+0x19) -#define PR_FAVORITES_DEFAULT_NAME PROP_TAG( PT_STRING8, pidStoreMin+0x1D) -#define PR_SYS_CONFIG_FOLDER_ENTRYID PROP_TAG( PT_BINARY, pidStoreMin+0x1E) -#define PR_NNTP_ARTICLE_FOLDER_ENTRYID PROP_TAG( PT_BINARY, pidSpecialMin+0x1A) -#define PR_EVENTS_ROOT_FOLDER_ENTRYID PROP_TAG( PT_BINARY, pidSpecialMin+0xA) - - // Gateway stores -#define PR_GW_MTSIN_ENTRYID PROP_TAG( PT_BINARY, pidStoreMin+0x10) -#define PR_GW_MTSOUT_ENTRYID PROP_TAG( PT_BINARY, pidStoreMin+0x11) -#define PR_TRANSFER_ENABLED PROP_TAG( PT_BOOLEAN, pidStoreMin+0x12) +// All mailbox stores +#define PR_SCHEDULE_FOLDER_ENTRYID PROP_TAG(PT_BINARY, pidStoreMin + 0x06) + +// All mailbox and gateway stores +#define PR_IPM_DAF_ENTRYID PROP_TAG(PT_BINARY, pidStoreMin + 0x07) + +// Public store +#define PR_NON_IPM_SUBTREE_ENTRYID PROP_TAG(PT_BINARY, pidStoreMin + 0x08) +#define PR_EFORMS_REGISTRY_ENTRYID PROP_TAG(PT_BINARY, pidStoreMin + 0x09) +#define PR_SPLUS_FREE_BUSY_ENTRYID PROP_TAG(PT_BINARY, pidStoreMin + 0x0A) +#define PR_OFFLINE_ADDRBOOK_ENTRYID PROP_TAG(PT_BINARY, pidStoreMin + 0x0B) +#define PR_NNTP_CONTROL_FOLDER_ENTRYID PROP_TAG(PT_BINARY, pidSpecialMin + 0x1B) +#define PR_EFORMS_FOR_LOCALE_ENTRYID PROP_TAG(PT_BINARY, pidStoreMin + 0x0C) +#define PR_FREE_BUSY_FOR_LOCAL_SITE_ENTRYID PROP_TAG(PT_BINARY, pidStoreMin + 0x0D) +#define PR_ADDRBOOK_FOR_LOCAL_SITE_ENTRYID PROP_TAG(PT_BINARY, pidStoreMin + 0x0E) +#define PR_NEWSGROUP_ROOT_FOLDER_ENTRYID PROP_TAG(PT_BINARY, pidSpecialMin + 0x1C) +#define PR_OFFLINE_MESSAGE_ENTRYID PROP_TAG(PT_BINARY, pidStoreMin + 0x0F) +#define PR_IPM_FAVORITES_ENTRYID PROP_TAG(PT_BINARY, pidStoreMin + 0x18) +#define PR_IPM_PUBLIC_FOLDERS_ENTRYID PROP_TAG(PT_BINARY, pidStoreMin + 0x19) +#define PR_FAVORITES_DEFAULT_NAME PROP_TAG(PT_STRING8, pidStoreMin + 0x1D) +#define PR_SYS_CONFIG_FOLDER_ENTRYID PROP_TAG(PT_BINARY, pidStoreMin + 0x1E) +#define PR_NNTP_ARTICLE_FOLDER_ENTRYID PROP_TAG(PT_BINARY, pidSpecialMin + 0x1A) +#define PR_EVENTS_ROOT_FOLDER_ENTRYID PROP_TAG(PT_BINARY, pidSpecialMin + 0xA) + +// Gateway stores +#define PR_GW_MTSIN_ENTRYID PROP_TAG(PT_BINARY, pidStoreMin + 0x10) +#define PR_GW_MTSOUT_ENTRYID PROP_TAG(PT_BINARY, pidStoreMin + 0x11) +#define PR_TRANSFER_ENABLED PROP_TAG(PT_BOOLEAN, pidStoreMin + 0x12) // This property is preinitialized to 256 bytes of zeros // GetProp on this property is guaranteed to RPC. May be used // to determine line speed of connection to server. -#define PR_TEST_LINE_SPEED PROP_TAG( PT_BINARY, pidStoreMin+0x13) +#define PR_TEST_LINE_SPEED PROP_TAG(PT_BINARY, pidStoreMin + 0x13) // Used with OpenProperty to get interface, also on folders -#define PR_HIERARCHY_SYNCHRONIZER PROP_TAG( PT_OBJECT, pidStoreMin+0x14) -#define PR_CONTENTS_SYNCHRONIZER PROP_TAG( PT_OBJECT, pidStoreMin+0x15) -#define PR_COLLECTOR PROP_TAG( PT_OBJECT, pidStoreMin+0x16) +#define PR_HIERARCHY_SYNCHRONIZER PROP_TAG(PT_OBJECT, pidStoreMin + 0x14) +#define PR_CONTENTS_SYNCHRONIZER PROP_TAG(PT_OBJECT, pidStoreMin + 0x15) +#define PR_COLLECTOR PROP_TAG(PT_OBJECT, pidStoreMin + 0x16) // Used with OpenProperty to get interface for folders, messages, attachmentson -#define PR_FAST_TRANSFER PROP_TAG( PT_OBJECT, pidStoreMin+0x17) +#define PR_FAST_TRANSFER PROP_TAG(PT_OBJECT, pidStoreMin + 0x17) // Used with OpenProperty to get interface for store object -#define PR_CHANGE_ADVISOR PROP_TAG( PT_OBJECT, pidStoreMin+0x1C) +#define PR_CHANGE_ADVISOR PROP_TAG(PT_OBJECT, pidStoreMin + 0x1C) // used to set the ics notification suppression guid -#define PR_CHANGE_NOTIFICATION_GUID PROP_TAG( PT_CLSID, pidStoreMin+0x1F) +#define PR_CHANGE_NOTIFICATION_GUID PROP_TAG(PT_CLSID, pidStoreMin + 0x1F) // This property is available on mailbox and public stores. If it exists // and its value is TRUE, the store is connected to the offline store provider. -#define PR_STORE_OFFLINE PROP_TAG( PT_BOOLEAN, pidStoreMin+0x1A) +#define PR_STORE_OFFLINE PROP_TAG(PT_BOOLEAN, pidStoreMin + 0x1A) // In transit state for store object. This state is // set when mail is being moved and it pauses mail delivery // to the mail box -#define PR_IN_TRANSIT PROP_TAG( PT_BOOLEAN, pidStoreMin) +#define PR_IN_TRANSIT PROP_TAG(PT_BOOLEAN, pidStoreMin) // Writable only with Admin rights, available on public stores and folders -#define PR_REPLICATION_STYLE PROP_TAG( PT_LONG, pidAdminMin) -#define PR_REPLICATION_SCHEDULE PROP_TAG( PT_BINARY, pidAdminMin+0x01) -#define PR_REPLICATION_MESSAGE_PRIORITY PROP_TAG( PT_LONG, pidAdminMin+0x02) +#define PR_REPLICATION_STYLE PROP_TAG(PT_LONG, pidAdminMin) +#define PR_REPLICATION_SCHEDULE PROP_TAG(PT_BINARY, pidAdminMin + 0x01) +#define PR_REPLICATION_MESSAGE_PRIORITY PROP_TAG(PT_LONG, pidAdminMin + 0x02) // Writable only with Admin rights, available on public stores -#define PR_OVERALL_MSG_AGE_LIMIT PROP_TAG( PT_LONG, pidAdminMin+0x03 ) -#define PR_REPLICATION_ALWAYS_INTERVAL PROP_TAG( PT_LONG, pidAdminMin+0x04 ) -#define PR_REPLICATION_MSG_SIZE PROP_TAG( PT_LONG, pidAdminMin+0x05 ) +#define PR_OVERALL_MSG_AGE_LIMIT PROP_TAG(PT_LONG, pidAdminMin + 0x03) +#define PR_REPLICATION_ALWAYS_INTERVAL PROP_TAG(PT_LONG, pidAdminMin + 0x04) +#define PR_REPLICATION_MSG_SIZE PROP_TAG(PT_LONG, pidAdminMin + 0x05) // default replication style=always interval (minutes) -#define STYLE_ALWAYS_INTERVAL_DEFAULT (ULONG) 15 +#define STYLE_ALWAYS_INTERVAL_DEFAULT (ULONG)15 // default replication message size limit (KB) -#define REPLICATION_MESSAGE_SIZE_LIMIT_DEFAULT (ULONG) 300 +#define REPLICATION_MESSAGE_SIZE_LIMIT_DEFAULT (ULONG)300 // Values for PR_REPLICATION_STYLE -#define STYLE_NEVER (ULONG) 0 // never replicate -#define STYLE_NORMAL (ULONG) 1 // use 84 byte schedule TIB -#define STYLE_ALWAYS (ULONG) 2 // replicate at fastest rate -#define STYLE_DEFAULT (ULONG) -1 // default value +#define STYLE_NEVER (ULONG)0 // never replicate +#define STYLE_NORMAL (ULONG)1 // use 84 byte schedule TIB +#define STYLE_ALWAYS (ULONG)2 // replicate at fastest rate +#define STYLE_DEFAULT (ULONG) - 1 // default value /*------------------------------------------------------------------------ * @@ -301,16 +296,16 @@ * *-----------------------------------------------------------------------*/ -#define PR_SOURCE_KEY PROP_TAG( PT_BINARY, pidExchangeNonXmitReservedMin+0x0) -#define PR_PARENT_SOURCE_KEY PROP_TAG( PT_BINARY, pidExchangeNonXmitReservedMin+0x1) -#define PR_CHANGE_KEY PROP_TAG( PT_BINARY, pidExchangeNonXmitReservedMin+0x2) -#define PR_PREDECESSOR_CHANGE_LIST PROP_TAG( PT_BINARY, pidExchangeNonXmitReservedMin+0x3) +#define PR_SOURCE_KEY PROP_TAG(PT_BINARY, pidExchangeNonXmitReservedMin + 0x0) +#define PR_PARENT_SOURCE_KEY PROP_TAG(PT_BINARY, pidExchangeNonXmitReservedMin + 0x1) +#define PR_CHANGE_KEY PROP_TAG(PT_BINARY, pidExchangeNonXmitReservedMin + 0x2) +#define PR_PREDECESSOR_CHANGE_LIST PROP_TAG(PT_BINARY, pidExchangeNonXmitReservedMin + 0x3) // msg-folder only property // actual FID for a msg-folder row // ptagFID for message rows // ptagInstanceID for subfolder rows -#define PR_SOURCE_FID PROP_TAG(PT_I8, pidStoreNonTransMin+0x1F) +#define PR_SOURCE_FID PROP_TAG(PT_I8, pidStoreNonTransMin + 0x1F) /*------------------------------------------------------------------------ * @@ -320,92 +315,91 @@ // folders table property used by PKM to define the catalog guid for content // indexing and searching; doubles as index enable/disable -#define PR_CATALOG PROP_TAG(PT_BINARY, pidStoreNonTransMin+0x1B) +#define PR_CATALOG PROP_TAG(PT_BINARY, pidStoreNonTransMin + 0x1B) // Is CI searching enabled on this folder? -#define PR_CI_SEARCH_ENABLED PROP_TAG(PT_BOOLEAN, pidStoreNonTransMin+0x1C) +#define PR_CI_SEARCH_ENABLED PROP_TAG(PT_BOOLEAN, pidStoreNonTransMin + 0x1C) // Is notification-based indexing enabled on this folder? -#define PR_CI_NOTIFICATION_ENABLED PROP_TAG(PT_BOOLEAN, pidStoreNonTransMin+0x1D) +#define PR_CI_NOTIFICATION_ENABLED PROP_TAG(PT_BOOLEAN, pidStoreNonTransMin + 0x1D) // Max number of cached view allowed -#define PR_MAX_CACHED_VIEWS PROP_TAG(PT_LONG, pidStoreNonTransMin+0x28) +#define PR_MAX_CACHED_VIEWS PROP_TAG(PT_LONG, pidStoreNonTransMin + 0x28) // Max number of indices allowed // Review : this ptag is used for PR_MIME_HANDLER_CLASSIDS, but because the context // is different I am reusing it here. -#define PR_MAX_INDICES PROP_TAG(PT_LONG, pidStoreNonTransMin+0x1E) +#define PR_MAX_INDICES PROP_TAG(PT_LONG, pidStoreNonTransMin + 0x1E) // folders table property containing list of guid/restriction pairs -#define PR_IMPLIED_RESTRICTIONS PROP_TAG( PT_MV_BINARY, pidSpecialMin+0x0F) +#define PR_IMPLIED_RESTRICTIONS PROP_TAG(PT_MV_BINARY, pidSpecialMin + 0x0F) // Read only, available on all folders -#define PR_FOLDER_CHILD_COUNT PROP_TAG( PT_LONG, pidFolderMin) -#define PR_RIGHTS PROP_TAG( PT_LONG, pidFolderMin+0x01) -#define PR_ACL_TABLE PROP_TAG( PT_OBJECT, pidExchangeXmitReservedMin) -#define PR_RULES_TABLE PROP_TAG( PT_OBJECT, pidExchangeXmitReservedMin+0x1) -#define PR_HAS_RULES PROP_TAG( PT_BOOLEAN, pidFolderMin+0x02) -#define PR_HAS_MODERATOR_RULES PROP_TAG( PT_BOOLEAN, pidFolderMin+0x07 ) - -//Read only, available only for public folders -#define PR_ADDRESS_BOOK_ENTRYID PROP_TAG( PT_BINARY, pidFolderMin+0x03) - -//Writable, available on folders in all stores -#define PR_ACL_DATA PROP_TAG( PT_BINARY, pidExchangeXmitReservedMin) -#define PR_RULES_DATA PROP_TAG( PT_BINARY, pidExchangeXmitReservedMin+0x1) -#define PR_EXTENDED_ACL_DATA PROP_TAG( PT_BINARY, pidExchangeXmitReservedMin+0x1E) -#define PR_FOLDER_DESIGN_FLAGS PROP_TAG( PT_LONG, pidExchangeXmitReservedMin+0x2) -#define PR_DESIGN_IN_PROGRESS PROP_TAG( PT_BOOLEAN, pidExchangeXmitReservedMin+0x4) -#define PR_SECURE_ORIGINATION PROP_TAG( PT_BOOLEAN, pidExchangeXmitReservedMin+0x5) - -//Writable, available only for public folders -#define PR_PUBLISH_IN_ADDRESS_BOOK PROP_TAG( PT_BOOLEAN, pidExchangeXmitReservedMin+0x6) -#define PR_RESOLVE_METHOD PROP_TAG( PT_LONG, pidExchangeXmitReservedMin+0x7) -#define PR_ADDRESS_BOOK_DISPLAY_NAME PROP_TAG( PT_TSTRING, pidExchangeXmitReservedMin+0x8) - -//Writable, used to indicate locale id for eforms registry subfolders -#define PR_EFORMS_LOCALE_ID PROP_TAG( PT_LONG, pidExchangeXmitReservedMin+0x9) +#define PR_FOLDER_CHILD_COUNT PROP_TAG(PT_LONG, pidFolderMin) +#define PR_RIGHTS PROP_TAG(PT_LONG, pidFolderMin + 0x01) +#define PR_ACL_TABLE PROP_TAG(PT_OBJECT, pidExchangeXmitReservedMin) +#define PR_RULES_TABLE PROP_TAG(PT_OBJECT, pidExchangeXmitReservedMin + 0x1) +#define PR_HAS_RULES PROP_TAG(PT_BOOLEAN, pidFolderMin + 0x02) +#define PR_HAS_MODERATOR_RULES PROP_TAG(PT_BOOLEAN, pidFolderMin + 0x07) + +// Read only, available only for public folders +#define PR_ADDRESS_BOOK_ENTRYID PROP_TAG(PT_BINARY, pidFolderMin + 0x03) + +// Writable, available on folders in all stores +#define PR_ACL_DATA PROP_TAG(PT_BINARY, pidExchangeXmitReservedMin) +#define PR_RULES_DATA PROP_TAG(PT_BINARY, pidExchangeXmitReservedMin + 0x1) +#define PR_EXTENDED_ACL_DATA PROP_TAG(PT_BINARY, pidExchangeXmitReservedMin + 0x1E) +#define PR_FOLDER_DESIGN_FLAGS PROP_TAG(PT_LONG, pidExchangeXmitReservedMin + 0x2) +#define PR_DESIGN_IN_PROGRESS PROP_TAG(PT_BOOLEAN, pidExchangeXmitReservedMin + 0x4) +#define PR_SECURE_ORIGINATION PROP_TAG(PT_BOOLEAN, pidExchangeXmitReservedMin + 0x5) + +// Writable, available only for public folders +#define PR_PUBLISH_IN_ADDRESS_BOOK PROP_TAG(PT_BOOLEAN, pidExchangeXmitReservedMin + 0x6) +#define PR_RESOLVE_METHOD PROP_TAG(PT_LONG, pidExchangeXmitReservedMin + 0x7) +#define PR_ADDRESS_BOOK_DISPLAY_NAME PROP_TAG(PT_TSTRING, pidExchangeXmitReservedMin + 0x8) + +// Writable, used to indicate locale id for eforms registry subfolders +#define PR_EFORMS_LOCALE_ID PROP_TAG(PT_LONG, pidExchangeXmitReservedMin + 0x9) // Writable only with Admin rights, available only for public folders -#define PR_REPLICA_LIST PROP_TAG( PT_BINARY, pidAdminMin+0x8) -#define PR_OVERALL_AGE_LIMIT PROP_TAG( PT_LONG, pidAdminMin+0x9) +#define PR_REPLICA_LIST PROP_TAG(PT_BINARY, pidAdminMin + 0x8) +#define PR_OVERALL_AGE_LIMIT PROP_TAG(PT_LONG, pidAdminMin + 0x9) // Newsgroup related properties. Writable only with Admin rights. -#define PR_IS_NEWSGROUP_ANCHOR PROP_TAG( PT_BOOLEAN, pidAdminMin+0x06) -#define PR_IS_NEWSGROUP PROP_TAG( PT_BOOLEAN, pidAdminMin+0x07) -#define PR_NEWSGROUP_COMPONENT PROP_TAG( PT_STRING8, pidAdminMin+0x15) -#define PR_INTERNET_NEWSGROUP_NAME PROP_TAG( PT_STRING8, pidAdminMin+0x17) -#define PR_NEWSFEED_INFO PROP_TAG( PT_BINARY, pidAdminMin+0x16) +#define PR_IS_NEWSGROUP_ANCHOR PROP_TAG(PT_BOOLEAN, pidAdminMin + 0x06) +#define PR_IS_NEWSGROUP PROP_TAG(PT_BOOLEAN, pidAdminMin + 0x07) +#define PR_NEWSGROUP_COMPONENT PROP_TAG(PT_STRING8, pidAdminMin + 0x15) +#define PR_INTERNET_NEWSGROUP_NAME PROP_TAG(PT_STRING8, pidAdminMin + 0x17) +#define PR_NEWSFEED_INFO PROP_TAG(PT_BINARY, pidAdminMin + 0x16) // Newsgroup related property. -#define PR_PREVENT_MSG_CREATE PROP_TAG( PT_BOOLEAN, pidExchangeNonXmitReservedMin+0x14) +#define PR_PREVENT_MSG_CREATE PROP_TAG(PT_BOOLEAN, pidExchangeNonXmitReservedMin + 0x14) // IMAP internal date -#define PR_IMAP_INTERNAL_DATE PROP_TAG( PT_SYSTIME, pidExchangeNonXmitReservedMin+0x15) +#define PR_IMAP_INTERNAL_DATE PROP_TAG(PT_SYSTIME, pidExchangeNonXmitReservedMin + 0x15) // Virtual properties to refer to Newsfeed DNs. Cannot get/set these on // any object. Supported currently only in specifying restrictions. -#define PR_INBOUND_NEWSFEED_DN PROP_TAG( PT_STRING8, pidSpecialMin+0x1D) -#define PR_OUTBOUND_NEWSFEED_DN PROP_TAG( PT_STRING8, pidSpecialMin+0x1E) +#define PR_INBOUND_NEWSFEED_DN PROP_TAG(PT_STRING8, pidSpecialMin + 0x1D) +#define PR_OUTBOUND_NEWSFEED_DN PROP_TAG(PT_STRING8, pidSpecialMin + 0x1E) // Used for controlling content conversion in NNTP -#define PR_INTERNET_CHARSET PROP_TAG( PT_TSTRING, pidAdminMin+0xA) +#define PR_INTERNET_CHARSET PROP_TAG(PT_TSTRING, pidAdminMin + 0xA) -//PR_RESOLVE_METHOD values -#define RESOLVE_METHOD_DEFAULT ((LONG)0) // default handling attach conflicts -#define RESOLVE_METHOD_LAST_WRITER_WINS ((LONG)1) // the last writer will win conflict -#define RESOLVE_METHOD_NO_CONFLICT_NOTIFICATION ((LONG)2) // no conflict notif +// PR_RESOLVE_METHOD values +#define RESOLVE_METHOD_DEFAULT ((LONG)0) // default handling attach conflicts +#define RESOLVE_METHOD_LAST_WRITER_WINS ((LONG)1) // the last writer will win conflict +#define RESOLVE_METHOD_NO_CONFLICT_NOTIFICATION ((LONG)2) // no conflict notif -//Read only, available only for public folder favorites -#define PR_PUBLIC_FOLDER_ENTRYID PROP_TAG( PT_BINARY, pidFolderMin+0x04) +// Read only, available only for public folder favorites +#define PR_PUBLIC_FOLDER_ENTRYID PROP_TAG(PT_BINARY, pidFolderMin + 0x04) -//Read only. changes everytime a subfolder is created or deleted -#define PR_HIERARCHY_CHANGE_NUM PROP_TAG( PT_LONG, pidFolderMin+0x06) +// Read only. changes everytime a subfolder is created or deleted +#define PR_HIERARCHY_CHANGE_NUM PROP_TAG(PT_LONG, pidFolderMin + 0x06) // For IFS/OLEDB to set and get user sid in LOGON -#define PR_USER_SID PROP_TAG(PT_BINARY, PROP_ID(ptagSearchState)) // pidInternalNoAccessNonTransMin+0x23) -#define PR_CREATOR_TOKEN PR_USER_SID - +#define PR_USER_SID PROP_TAG(PT_BINARY, PROP_ID(ptagSearchState)) // pidInternalNoAccessNonTransMin+0x23) +#define PR_CREATOR_TOKEN PR_USER_SID /*------------------------------------------------------------------------ * @@ -414,141 +408,140 @@ *-----------------------------------------------------------------------*/ // Read only, automatically set on all messages in all stores -#define PR_HAS_NAMED_PROPERTIES PROP_TAG(PT_BOOLEAN, pidMessageReadOnlyMin+0x0A) +#define PR_HAS_NAMED_PROPERTIES PROP_TAG(PT_BOOLEAN, pidMessageReadOnlyMin + 0x0A) // Read only but outside the provider specific range for replication thru GDK-GWs -#define PR_CREATOR_NAME PROP_TAG(PT_TSTRING, pidExchangeXmitReservedMin+0x18) -#define PR_CREATOR_ENTRYID PROP_TAG(PT_BINARY, pidExchangeXmitReservedMin+0x19) -#define PR_LAST_MODIFIER_NAME PROP_TAG(PT_TSTRING, pidExchangeXmitReservedMin+0x1A) -#define PR_LAST_MODIFIER_ENTRYID PROP_TAG(PT_BINARY, pidExchangeXmitReservedMin+0x1B) -#define PR_REPLY_RECIPIENT_SMTP_PROXIES PROP_TAG(PT_TSTRING, pidExchangeXmitReservedMin+0x1C) +#define PR_CREATOR_NAME PROP_TAG(PT_TSTRING, pidExchangeXmitReservedMin + 0x18) +#define PR_CREATOR_ENTRYID PROP_TAG(PT_BINARY, pidExchangeXmitReservedMin + 0x19) +#define PR_LAST_MODIFIER_NAME PROP_TAG(PT_TSTRING, pidExchangeXmitReservedMin + 0x1A) +#define PR_LAST_MODIFIER_ENTRYID PROP_TAG(PT_BINARY, pidExchangeXmitReservedMin + 0x1B) +#define PR_REPLY_RECIPIENT_SMTP_PROXIES PROP_TAG(PT_TSTRING, pidExchangeXmitReservedMin + 0x1C) // Read only, appears on messages which have DAM's pointing to them -#define PR_HAS_DAMS PROP_TAG( PT_BOOLEAN, pidExchangeXmitReservedMin+0x0A) -#define PR_RULE_TRIGGER_HISTORY PROP_TAG( PT_BINARY, pidExchangeXmitReservedMin+0x12) -#define PR_MOVE_TO_STORE_ENTRYID PROP_TAG( PT_BINARY, pidExchangeXmitReservedMin+0x13) -#define PR_MOVE_TO_FOLDER_ENTRYID PROP_TAG( PT_BINARY, pidExchangeXmitReservedMin+0x14) +#define PR_HAS_DAMS PROP_TAG(PT_BOOLEAN, pidExchangeXmitReservedMin + 0x0A) +#define PR_RULE_TRIGGER_HISTORY PROP_TAG(PT_BINARY, pidExchangeXmitReservedMin + 0x12) +#define PR_MOVE_TO_STORE_ENTRYID PROP_TAG(PT_BINARY, pidExchangeXmitReservedMin + 0x13) +#define PR_MOVE_TO_FOLDER_ENTRYID PROP_TAG(PT_BINARY, pidExchangeXmitReservedMin + 0x14) // Read only, available only on messages in the public store -#define PR_REPLICA_SERVER PROP_TAG(PT_TSTRING, pidMessageReadOnlyMin+0x04) -#define PR_REPLICA_VERSION PROP_TAG(PT_I8, pidMessageReadOnlyMin+0x0B) +#define PR_REPLICA_SERVER PROP_TAG(PT_TSTRING, pidMessageReadOnlyMin + 0x04) +#define PR_REPLICA_VERSION PROP_TAG(PT_I8, pidMessageReadOnlyMin + 0x0B) // SID versions of standard messaging properties -#define PR_CREATOR_SID PROP_TAG(PT_BINARY, pidStoreNonTransMin+0x18) -#define PR_LAST_MODIFIER_SID PROP_TAG(PT_BINARY, pidStoreNonTransMin+0x19) -#define PR_SENDER_SID PROP_TAG(PT_BINARY, pidStoreNonTransMin+0x0d) -#define PR_SENT_REPRESENTING_SID PROP_TAG(PT_BINARY, pidStoreNonTransMin+0x0e) -#define PR_ORIGINAL_SENDER_SID PROP_TAG(PT_BINARY, pidStoreNonTransMin+0x0f) -#define PR_ORIGINAL_SENT_REPRESENTING_SID PROP_TAG(PT_BINARY, pidStoreNonTransMin+0x10) -#define PR_READ_RECEIPT_SID PROP_TAG(PT_BINARY, pidStoreNonTransMin+0x11) -#define PR_REPORT_SID PROP_TAG(PT_BINARY, pidStoreNonTransMin+0x12) -#define PR_ORIGINATOR_SID PROP_TAG(PT_BINARY, pidStoreNonTransMin+0x13) -#define PR_REPORT_DESTINATION_SID PROP_TAG(PT_BINARY, pidStoreNonTransMin+0x14) -#define PR_ORIGINAL_AUTHOR_SID PROP_TAG(PT_BINARY, pidStoreNonTransMin+0x15) -#define PR_RECEIVED_BY_SID PROP_TAG(PT_BINARY, pidStoreNonTransMin+0x16) -#define PR_RCVD_REPRESENTING_SID PROP_TAG(PT_BINARY, pidStoreNonTransMin+0x17) - -#define PR_TRUST_SENDER_NO 0x00000000L -#define PR_TRUST_SENDER_YES 0x00000001L -#define PR_TRUST_SENDER PROP_TAG(PT_LONG, pidStoreNonTransMin+0x39) +#define PR_CREATOR_SID PROP_TAG(PT_BINARY, pidStoreNonTransMin + 0x18) +#define PR_LAST_MODIFIER_SID PROP_TAG(PT_BINARY, pidStoreNonTransMin + 0x19) +#define PR_SENDER_SID PROP_TAG(PT_BINARY, pidStoreNonTransMin + 0x0d) +#define PR_SENT_REPRESENTING_SID PROP_TAG(PT_BINARY, pidStoreNonTransMin + 0x0e) +#define PR_ORIGINAL_SENDER_SID PROP_TAG(PT_BINARY, pidStoreNonTransMin + 0x0f) +#define PR_ORIGINAL_SENT_REPRESENTING_SID PROP_TAG(PT_BINARY, pidStoreNonTransMin + 0x10) +#define PR_READ_RECEIPT_SID PROP_TAG(PT_BINARY, pidStoreNonTransMin + 0x11) +#define PR_REPORT_SID PROP_TAG(PT_BINARY, pidStoreNonTransMin + 0x12) +#define PR_ORIGINATOR_SID PROP_TAG(PT_BINARY, pidStoreNonTransMin + 0x13) +#define PR_REPORT_DESTINATION_SID PROP_TAG(PT_BINARY, pidStoreNonTransMin + 0x14) +#define PR_ORIGINAL_AUTHOR_SID PROP_TAG(PT_BINARY, pidStoreNonTransMin + 0x15) +#define PR_RECEIVED_BY_SID PROP_TAG(PT_BINARY, pidStoreNonTransMin + 0x16) +#define PR_RCVD_REPRESENTING_SID PROP_TAG(PT_BINARY, pidStoreNonTransMin + 0x17) + +#define PR_TRUST_SENDER_NO 0x00000000L +#define PR_TRUST_SENDER_YES 0x00000001L +#define PR_TRUST_SENDER PROP_TAG(PT_LONG, pidStoreNonTransMin + 0x39) // XML versions of SID properties -#define PR_CREATOR_SID_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin+0x2C) -#define PR_LAST_MODIFIER_SID_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin+0x2D) -#define PR_SENDER_SID_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin+0x2E) -#define PR_SENT_REPRESENTING_SID_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin+0x2F) -#define PR_ORIGINAL_SENDER_SID_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin+0x30) -#define PR_ORIGINAL_SENT_REPRESENTING_SID_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin+0x31) -#define PR_READ_RECEIPT_SID_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin+0x32) -#define PR_REPORT_SID_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin+0x33) -#define PR_ORIGINATOR_SID_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin+0x34) -#define PR_REPORT_DESTINATION_SID_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin+0x35) -#define PR_ORIGINAL_AUTHOR_SID_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin+0x36) -#define PR_RECEIVED_BY_SID_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin+0x37) -#define PR_RCVD_REPRESENTING_SID_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin+0x38) - +#define PR_CREATOR_SID_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin + 0x2C) +#define PR_LAST_MODIFIER_SID_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin + 0x2D) +#define PR_SENDER_SID_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin + 0x2E) +#define PR_SENT_REPRESENTING_SID_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin + 0x2F) +#define PR_ORIGINAL_SENDER_SID_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin + 0x30) +#define PR_ORIGINAL_SENT_REPRESENTING_SID_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin + 0x31) +#define PR_READ_RECEIPT_SID_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin + 0x32) +#define PR_REPORT_SID_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin + 0x33) +#define PR_ORIGINATOR_SID_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin + 0x34) +#define PR_REPORT_DESTINATION_SID_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin + 0x35) +#define PR_ORIGINAL_AUTHOR_SID_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin + 0x36) +#define PR_RECEIVED_BY_SID_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin + 0x37) +#define PR_RCVD_REPRESENTING_SID_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin + 0x38) // those two are pseudo-properties on folder. calling OFOLD::EcGetProps(PR_RESERVE_RANGE_OF_IDS) is // equivalent to calling EcGetLocalRepIdsOp(), calling OFOLD::EcSetProps(PR_MERGE_MIDSET_DELETED) // is equivalen to calling OFOLD::EcSetLocalRepMidsetDeleted() -#define PR_MERGE_MIDSET_DELETED PROP_TAG(PT_BINARY, pidStoreNonTransMin+0x3a) // 0x0E7A0102 -#define PR_RESERVE_RANGE_OF_IDS PROP_TAG(PT_BINARY, pidStoreNonTransMin+0x3b) // 0x0E7B0102 +#define PR_MERGE_MIDSET_DELETED PROP_TAG(PT_BINARY, pidStoreNonTransMin + 0x3a) // 0x0E7A0102 +#define PR_RESERVE_RANGE_OF_IDS PROP_TAG(PT_BINARY, pidStoreNonTransMin + 0x3b) // 0x0E7B0102 // computed message property (read only) // 44 byte binary property - used by PKM as globally unique message key // 22 bytes of global ID for FID // 22 bytes of global ID for VID -#define PR_FID_VID PROP_TAG(PT_BINARY, pidMessageReadOnlyMin+0x0C) -#define PR_FID_MID PR_FID_VID //NSK : temporary to allow transition +#define PR_FID_VID PROP_TAG(PT_BINARY, pidMessageReadOnlyMin + 0x0C) +#define PR_FID_MID PR_FID_VID // NSK : temporary to allow transition // message property - read only, xref ID in global ID format - used by PKM -#define PR_ORIGIN_ID PROP_TAG( PT_BINARY, pidMessageReadOnlyMin+0x0D) +#define PR_ORIGIN_ID PROP_TAG(PT_BINARY, pidMessageReadOnlyMin + 0x0D) // computed message property used in search folders to determine quality of // search hit match // NOTE: ptag.h consumers, see also ptagMsgFolderTemplateRes3 -#define PR_RANK PROP_TAG( PT_LONG, pidAdminMin+0x82 ) +#define PR_RANK PROP_TAG(PT_LONG, pidAdminMin + 0x82) // msg-folder property, read only // value is PR_MSG_DELIVERY_TIME if it exists, else PR_CREATION_TIME // used as the default sort time when subfolder rows are returned in views -#define PR_MSG_FOLD_TIME PROP_TAG( PT_SYSTIME, pidMessageReadOnlyMin+0x14) -#define PR_ICS_CHANGE_KEY PROP_TAG( PT_BINARY, pidMessageReadOnlyMin+0x15) +#define PR_MSG_FOLD_TIME PROP_TAG(PT_SYSTIME, pidMessageReadOnlyMin + 0x14) +#define PR_ICS_CHANGE_KEY PROP_TAG(PT_BINARY, pidMessageReadOnlyMin + 0x15) -#define PR_DEFERRED_SEND_NUMBER PROP_TAG( PT_LONG, pidExchangeXmitReservedMin+0xB) -#define PR_DEFERRED_SEND_UNITS PROP_TAG( PT_LONG, pidExchangeXmitReservedMin+0xC) -#define PR_EXPIRY_NUMBER PROP_TAG( PT_LONG, pidExchangeXmitReservedMin+0xD) -#define PR_EXPIRY_UNITS PROP_TAG( PT_LONG, pidExchangeXmitReservedMin+0xE) +#define PR_DEFERRED_SEND_NUMBER PROP_TAG(PT_LONG, pidExchangeXmitReservedMin + 0xB) +#define PR_DEFERRED_SEND_UNITS PROP_TAG(PT_LONG, pidExchangeXmitReservedMin + 0xC) +#define PR_EXPIRY_NUMBER PROP_TAG(PT_LONG, pidExchangeXmitReservedMin + 0xD) +#define PR_EXPIRY_UNITS PROP_TAG(PT_LONG, pidExchangeXmitReservedMin + 0xE) // Writeable, deferred send time -#define PR_DEFERRED_SEND_TIME PROP_TAG( PT_SYSTIME, pidExchangeXmitReservedMin+0xF) +#define PR_DEFERRED_SEND_TIME PROP_TAG(PT_SYSTIME, pidExchangeXmitReservedMin + 0xF) -//Writeable, intended for both folders and messages in gateway mailbox -#define PR_GW_ADMIN_OPERATIONS PROP_TAG( PT_LONG, pidMessageWriteableMin) +// Writeable, intended for both folders and messages in gateway mailbox +#define PR_GW_ADMIN_OPERATIONS PROP_TAG(PT_LONG, pidMessageWriteableMin) -//Writeable, used for DMS messages -#define PR_P1_CONTENT PROP_TAG( PT_BINARY, 0x1100) -#define PR_P1_CONTENT_TYPE PROP_TAG( PT_BINARY, 0x1101) +// Writeable, used for DMS messages +#define PR_P1_CONTENT PROP_TAG(PT_BINARY, 0x1100) +#define PR_P1_CONTENT_TYPE PROP_TAG(PT_BINARY, 0x1101) // Properties on deferred action messages -#define PR_CLIENT_ACTIONS PROP_TAG(PT_BINARY, pidMessageReadOnlyMin+0x5) -#define PR_DAM_ORIGINAL_ENTRYID PROP_TAG(PT_BINARY, pidMessageReadOnlyMin+0x6) -#define PR_DAM_BACK_PATCHED PROP_TAG( PT_BOOLEAN, pidMessageReadOnlyMin+0x7) +#define PR_CLIENT_ACTIONS PROP_TAG(PT_BINARY, pidMessageReadOnlyMin + 0x5) +#define PR_DAM_ORIGINAL_ENTRYID PROP_TAG(PT_BINARY, pidMessageReadOnlyMin + 0x6) +#define PR_DAM_BACK_PATCHED PROP_TAG(PT_BOOLEAN, pidMessageReadOnlyMin + 0x7) // Properties on deferred action error messages -#define PR_RULE_ERROR PROP_TAG(PT_LONG, pidMessageReadOnlyMin+0x8) -#define PR_RULE_ACTION_TYPE PROP_TAG(PT_LONG, pidMessageReadOnlyMin+0x9) -#define PR_RULE_ACTION_NUMBER PROP_TAG(PT_LONG, pidMessageReadOnlyMin+0x10) -#define PR_RULE_FOLDER_ENTRYID PROP_TAG(PT_BINARY, pidMessageReadOnlyMin+0x11) +#define PR_RULE_ERROR PROP_TAG(PT_LONG, pidMessageReadOnlyMin + 0x8) +#define PR_RULE_ACTION_TYPE PROP_TAG(PT_LONG, pidMessageReadOnlyMin + 0x9) +#define PR_RULE_ACTION_NUMBER PROP_TAG(PT_LONG, pidMessageReadOnlyMin + 0x10) +#define PR_RULE_FOLDER_ENTRYID PROP_TAG(PT_BINARY, pidMessageReadOnlyMin + 0x11) // Mime representation of a message. // Defined as 3 different types for convenience. Will be stored as file handle // internally. -#define PR_INTERNET_CONTENT PROP_TAG(PT_BINARY, pidMessageWriteableMin+0x1) -#define PR_INTERNET_CONTENT_HANDLE PROP_TAG(PT_FILE_HANDLE, pidMessageWriteableMin+0x1) -#define PR_INTERNET_CONTENT_EA PROP_TAG(PT_FILE_EA, pidMessageWriteableMin+0x1) +#define PR_INTERNET_CONTENT PROP_TAG(PT_BINARY, pidMessageWriteableMin + 0x1) +#define PR_INTERNET_CONTENT_HANDLE PROP_TAG(PT_FILE_HANDLE, pidMessageWriteableMin + 0x1) +#define PR_INTERNET_CONTENT_EA PROP_TAG(PT_FILE_EA, pidMessageWriteableMin + 0x1) // Dot-stuff state property on message -#define PR_DOTSTUFF_STATE PROP_TAG(PT_LONG, pidUserNonTransmitMin+0x1) +#define PR_DOTSTUFF_STATE PROP_TAG(PT_LONG, pidUserNonTransmitMin + 0x1) // Raw byte count of mime stream, if mime exists. -#define PR_MIME_SIZE PROP_TAG(PT_LONG, 0x6746) -#define PR_MIME_SIZE_EXTENDED PROP_TAG(PT_I8, 0x6746) +#define PR_MIME_SIZE PROP_TAG(PT_LONG, 0x6746) +#define PR_MIME_SIZE_EXTENDED PROP_TAG(PT_I8, 0x6746) // Raw byte count of ptagInternetContent, whether it is a mime message // or freedoc using OURL -#define PR_FILE_SIZE PROP_TAG(PT_LONG, 0x6747) -#define PR_FILE_SIZE_EXTENDED PROP_TAG(PT_I8, 0x6747) +#define PR_FILE_SIZE PROP_TAG(PT_LONG, 0x6747) +#define PR_FILE_SIZE_EXTENDED PROP_TAG(PT_I8, 0x6747) // Sender's editor format -#define PR_MSG_EDITOR_FORMAT PROP_TAG( PT_LONG, 0x5909 ) +#define PR_MSG_EDITOR_FORMAT PROP_TAG(PT_LONG, 0x5909) -#define EDITOR_FORMAT_DONTKNOW ((ULONG)0) -#define EDITOR_FORMAT_PLAINTEXT ((ULONG)1) -#define EDITOR_FORMAT_HTML ((ULONG)2) -#define EDITOR_FORMAT_RTF ((ULONG)3) +#define EDITOR_FORMAT_DONTKNOW ((ULONG)0) +#define EDITOR_FORMAT_PLAINTEXT ((ULONG)1) +#define EDITOR_FORMAT_HTML ((ULONG)2) +#define EDITOR_FORMAT_RTF ((ULONG)3) -#ifdef pidInternalWriteableNonTransMin +#ifdef pidInternalWriteableNonTransMin #if pidInternalWritableNonTranMin - 0x6740 #pragma error("pidInternalWritableNonTransMin definition has changed, must change definition of PR_MIME_SIZE") #endif @@ -556,72 +549,70 @@ // State of this inid as far as conversion is concerned. // Reusing mailbox table property -#define PR_CONVERSION_STATE PROP_TAG(PT_LONG, PROP_ID(ptagAdminNickName)) +#define PR_CONVERSION_STATE PROP_TAG(PT_LONG, PROP_ID(ptagAdminNickName)) // Property to represent native html content - assumed to be in the internet // codepage as determined by PR_INTERNET_CPID // -#define PR_HTML PROP_TAG( PT_BINARY, PROP_ID( PR_BODY_HTML ) ) +#define PR_HTML PROP_TAG(PT_BINARY, PROP_ID(PR_BODY_HTML)) // computed property used for moderated folder rule -// its an EntryId whose value is: +// it's an EntryId whose value is: // ptagSenderEntryId on delivery // LOGON::PbUserEntryId() for all other cases (move/copy/post) -#define PR_ACTIVE_USER_ENTRYID PROP_TAG(PT_BINARY, pidMessageReadOnlyMin+0x12) +#define PR_ACTIVE_USER_ENTRYID PROP_TAG(PT_BINARY, pidMessageReadOnlyMin + 0x12) // Property on conflict notification indicating entryid of conflicting object -#define PR_CONFLICT_ENTRYID PROP_TAG(PT_BINARY, pidExchangeXmitReservedMin+0x10) +#define PR_CONFLICT_ENTRYID PROP_TAG(PT_BINARY, pidExchangeXmitReservedMin + 0x10) // Property on messages to indicate the language client used to create this message -#define PR_MESSAGE_LOCALE_ID PROP_TAG(PT_LONG, pidExchangeXmitReservedMin+0x11) -#define PR_MESSAGE_CODEPAGE PROP_TAG( PT_LONG, pidExchangeXmitReservedMin+0x1D) +#define PR_MESSAGE_LOCALE_ID PROP_TAG(PT_LONG, pidExchangeXmitReservedMin + 0x11) +#define PR_MESSAGE_CODEPAGE PROP_TAG(PT_LONG, pidExchangeXmitReservedMin + 0x1D) // Properties on Quota warning messages to indicate Storage quota and Excess used -#define PR_STORAGE_QUOTA_LIMIT PROP_TAG(PT_LONG, pidExchangeXmitReservedMin+0x15) -#define PR_EXCESS_STORAGE_USED PROP_TAG(PT_LONG, pidExchangeXmitReservedMin+0x16) -#define PR_SVR_GENERATING_QUOTA_MSG PROP_TAG(PT_TSTRING, pidExchangeXmitReservedMin+0x17) +#define PR_STORAGE_QUOTA_LIMIT PROP_TAG(PT_LONG, pidExchangeXmitReservedMin + 0x15) +#define PR_EXCESS_STORAGE_USED PROP_TAG(PT_LONG, pidExchangeXmitReservedMin + 0x16) +#define PR_SVR_GENERATING_QUOTA_MSG PROP_TAG(PT_TSTRING, pidExchangeXmitReservedMin + 0x17) // Property affixed by delegation rule and deleted on forwards -#define PR_DELEGATED_BY_RULE PROP_TAG( PT_BOOLEAN, pidExchangeXmitReservedMin+0x3) +#define PR_DELEGATED_BY_RULE PROP_TAG(PT_BOOLEAN, pidExchangeXmitReservedMin + 0x3) // Message status bit used to indicate message is in conflict -#define MSGSTATUS_IN_CONFLICT ((ULONG) 0x800) +#define MSGSTATUS_IN_CONFLICT ((ULONG)0x800) // Message status bit used to indicate the IMAP4 $MDNSent flag -#define MSGSTATUS_MDNSENT ((ULONG) 0x4000) +#define MSGSTATUS_MDNSENT ((ULONG)0x4000) // used to indicate how much X400 private extension data is present: none, just the // message level, or both the message and recipient levels // !!The high order byte of this ULONG is reserved.!! -#define ENV_BLANK ((ULONG)0x00000000) -#define ENV_RECIP_NUM ((ULONG)0x00000001) -#define ENV_MSG_EXT ((ULONG)0x00000002) -#define ENV_RECIP_EXT ((ULONG)0x00000004) +#define ENV_BLANK ((ULONG)0x00000000) +#define ENV_RECIP_NUM ((ULONG)0x00000001) +#define ENV_MSG_EXT ((ULONG)0x00000002) +#define ENV_RECIP_EXT ((ULONG)0x00000004) - - -#define PR_X400_ENVELOPE_TYPE PROP_TAG(PT_LONG, pidMessageReadOnlyMin+0x13) -#define X400_ENV_PLAIN (ENV_BLANK) // no extension -#define X400_ENV_VALID_RECIP (ENV_RECIP_NUM | ENV_MSG_EXT) // just the message level extension -#define X400_ENV_FULL_EXT (ENV_RECIP_NUM | ENV_MSG_EXT | ENV_RECIP_EXT) // both message and recipient levels +#define PR_X400_ENVELOPE_TYPE PROP_TAG(PT_LONG, pidMessageReadOnlyMin + 0x13) +#define X400_ENV_PLAIN (ENV_BLANK) // no extension +#define X400_ENV_VALID_RECIP (ENV_RECIP_NUM | ENV_MSG_EXT) // just the message level extension +#define X400_ENV_FULL_EXT (ENV_RECIP_NUM | ENV_MSG_EXT | ENV_RECIP_EXT) // both message and recipient levels // // bitmask that indicates whether RN, NRN, DR, NDR, OOF, Auto-Reply should be suppressed // -#define AUTO_RESPONSE_SUPPRESS_DR ((ULONG)0x00000001) -#define AUTO_RESPONSE_SUPPRESS_NDR ((ULONG)0x00000002) -#define AUTO_RESPONSE_SUPPRESS_RN ((ULONG)0x00000004) -#define AUTO_RESPONSE_SUPPRESS_NRN ((ULONG)0x00000008) -#define AUTO_RESPONSE_SUPPRESS_OOF ((ULONG)0x00000010) -#define AUTO_RESPONSE_SUPPRESS_AUTO_REPLY ((ULONG)0x00000020) +#define AUTO_RESPONSE_SUPPRESS_DR ((ULONG)0x00000001) +#define AUTO_RESPONSE_SUPPRESS_NDR ((ULONG)0x00000002) +#define AUTO_RESPONSE_SUPPRESS_RN ((ULONG)0x00000004) +#define AUTO_RESPONSE_SUPPRESS_NRN ((ULONG)0x00000008) +#define AUTO_RESPONSE_SUPPRESS_OOF ((ULONG)0x00000010) +#define AUTO_RESPONSE_SUPPRESS_AUTO_REPLY ((ULONG)0x00000020) // raid 91101 - Flag indicates No RFC821 From field #define AUTO_RESPONSE_SUPPRESS_NORFC821FROM ((ULONG)0x00000040) -#define PR_AUTO_RESPONSE_SUPPRESS PROP_TAG(PT_LONG, pidExchangeXmitReservedMin - 0x01) -#define PR_INTERNET_CPID PROP_TAG(PT_LONG, pidExchangeXmitReservedMin - 0x02) +#define PR_AUTO_RESPONSE_SUPPRESS PROP_TAG(PT_LONG, pidExchangeXmitReservedMin - 0x01) +#define PR_INTERNET_CPID PROP_TAG(PT_LONG, pidExchangeXmitReservedMin - 0x02) -#define PR_SYNCEVENT_FIRED PROP_TAG(PT_BOOLEAN, pidMessageReadOnlyMin + 0x0F) +#define PR_SYNCEVENT_FIRED PROP_TAG(PT_BOOLEAN, pidMessageReadOnlyMin + 0x0F) /*------------------------------------------------------------------------ * @@ -631,8 +622,7 @@ // Appears on attachments to a message marked to be in conflict. Identifies // those attachments which are conflicting versions of the top level message -#define PR_IN_CONFLICT PROP_TAG(PT_BOOLEAN, pidAttachReadOnlyMin) - +#define PR_IN_CONFLICT PROP_TAG(PT_BOOLEAN, pidAttachReadOnlyMin) /*------------------------------------------------------------------------ * @@ -642,67 +632,66 @@ // Indicates when a message, folder, or mailbox has been deleted. // (Read only, non transmittable property). -#define PR_DELETED_ON PROP_TAG(PT_SYSTIME, pidSpecialMin+0x1F) +#define PR_DELETED_ON PROP_TAG(PT_SYSTIME, pidSpecialMin + 0x1F) // Read-only folder properties which indicate the number of messages, and child folders // that have been "soft" deleted in this folder (and the time the first message was deleted). -#define PR_DELETED_MSG_COUNT PROP_TAG(PT_LONG, pidFolderMin+0x08) -#define PR_DELETED_ASSOC_MSG_COUNT PROP_TAG(PT_LONG, pidFolderMin+0x0B) -#define PR_DELETED_FOLDER_COUNT PROP_TAG(PT_LONG, pidFolderMin + 0x09) -#define PR_OLDEST_DELETED_ON PROP_TAG(PT_SYSTIME, pidFolderMin + 0x0A) +#define PR_DELETED_MSG_COUNT PROP_TAG(PT_LONG, pidFolderMin + 0x08) +#define PR_DELETED_ASSOC_MSG_COUNT PROP_TAG(PT_LONG, pidFolderMin + 0x0B) +#define PR_DELETED_FOLDER_COUNT PROP_TAG(PT_LONG, pidFolderMin + 0x09) +#define PR_OLDEST_DELETED_ON PROP_TAG(PT_SYSTIME, pidFolderMin + 0x0A) // Total size of all soft deleted messages -#define PR_DELETED_MESSAGE_SIZE_EXTENDED PROP_TAG(PT_I8, pidAdminMin+0xB) +#define PR_DELETED_MESSAGE_SIZE_EXTENDED PROP_TAG(PT_I8, pidAdminMin + 0xB) // Total size of all normal soft deleted messages -#define PR_DELETED_NORMAL_MESSAGE_SIZE_EXTENDED PROP_TAG(PT_I8, pidAdminMin+0xC) +#define PR_DELETED_NORMAL_MESSAGE_SIZE_EXTENDED PROP_TAG(PT_I8, pidAdminMin + 0xC) // Total size of all associated soft deleted messages -#define PR_DELETED_ASSOC_MESSAGE_SIZE_EXTENDED PROP_TAG(PT_I8, pidAdminMin+0xD) +#define PR_DELETED_ASSOC_MESSAGE_SIZE_EXTENDED PROP_TAG(PT_I8, pidAdminMin + 0xD) // This property controls the retention age limit (minutes) for the Private/Public MDB, // Mailbox (private only), or Folder (public). // Note - the Folder/Mailbox retention, if set, overrides the MDB retention. -#define PR_RETENTION_AGE_LIMIT PROP_TAG(PT_LONG, pidAdminMin+0x34) +#define PR_RETENTION_AGE_LIMIT PROP_TAG(PT_LONG, pidAdminMin + 0x34) // This property controls if we maintain per user read/unread for a public // folder. By default (if this property is missing or set to FALSE) we will // maintain per user read/unread. -#define PR_DISABLE_PERUSER_READ PROP_TAG(PT_BOOLEAN, pidAdminMin+0x35) +#define PR_DISABLE_PERUSER_READ PROP_TAG(PT_BOOLEAN, pidAdminMin + 0x35) // This property is set by JET after a full backup has occurred. // It is used to determine whether or not messages and folders can be "hard" deleted // before a full backup has captured the last modification to the object. -#define PR_LAST_FULL_BACKUP PROP_TAG(PT_SYSTIME, pidSpecialMin+0x15) +#define PR_LAST_FULL_BACKUP PROP_TAG(PT_SYSTIME, pidSpecialMin + 0x15) /*------------------------------------------------------------------------ * URL related properties *-----------------------------------------------------------------------*/ // This is read only property. -#define PR_URL_NAME PROP_TAG(PT_TSTRING, pidAdminMin+0x77) //0x6707 -#define PR_URL_NAME_A PROP_TAG(PT_STRING8, pidAdminMin+0x77) -#define PR_URL_NAME_W PROP_TAG(PT_UNICODE, pidAdminMin+0x77) +#define PR_URL_NAME PROP_TAG(PT_TSTRING, pidAdminMin + 0x77) // 0x6707 +#define PR_URL_NAME_A PROP_TAG(PT_STRING8, pidAdminMin + 0x77) +#define PR_URL_NAME_W PROP_TAG(PT_UNICODE, pidAdminMin + 0x77) // This is a read-write property. -#define PR_URL_COMP_NAME PROP_TAG(PT_TSTRING, pidRenMsgFldMin+0x73) -#define PR_URL_COMP_NAME_A PROP_TAG(PT_STRING8, pidRenMsgFldMin+0x73) -#define PR_URL_COMP_NAME_W PROP_TAG(PT_UNICODE, pidRenMsgFldMin+0x73) +#define PR_URL_COMP_NAME PROP_TAG(PT_TSTRING, pidRenMsgFldMin + 0x73) +#define PR_URL_COMP_NAME_A PROP_TAG(PT_STRING8, pidRenMsgFldMin + 0x73) +#define PR_URL_COMP_NAME_W PROP_TAG(PT_UNICODE, pidRenMsgFldMin + 0x73) // this is a read-only property -#define PR_PARENT_URL_NAME PROP_TAG(PT_TSTRING, pidAdminMin+0x7D) // 0x670d -#define PR_PARENT_URL_NAME_A PROP_TAG(PT_STRING8, pidAdminMin+0x7D) -#define PR_PARENT_URL_NAME_W PROP_TAG(PT_UNICODE, pidAdminMin+0x7D) +#define PR_PARENT_URL_NAME PROP_TAG(PT_TSTRING, pidAdminMin + 0x7D) // 0x670d +#define PR_PARENT_URL_NAME_A PROP_TAG(PT_STRING8, pidAdminMin + 0x7D) +#define PR_PARENT_URL_NAME_W PROP_TAG(PT_UNICODE, pidAdminMin + 0x7D) // read-only property -#define PR_FLAT_URL_NAME PROP_TAG(PT_TSTRING, pidAdminMin+0x7E) // 0x670e -#define PR_FLAT_URL_NAME_A PROP_TAG(PT_STRING8, pidAdminMin+0x7E) -#define PR_FLAT_URL_NAME_W PROP_TAG(PT_UNICODE, pidAdminMin+0x7E) +#define PR_FLAT_URL_NAME PROP_TAG(PT_TSTRING, pidAdminMin + 0x7E) // 0x670e +#define PR_FLAT_URL_NAME_A PROP_TAG(PT_STRING8, pidAdminMin + 0x7E) +#define PR_FLAT_URL_NAME_W PROP_TAG(PT_UNICODE, pidAdminMin + 0x7E) // read-only property -#define PR_SRC_URL_NAME PROP_TAG(PT_TSTRING, pidAdminMin+0x7F) // 0x670f -#define PR_SRC_URL_NAME_A PROP_TAG(PT_STRING8, pidAdminMin+0x7F) -#define PR_SRC_URL_NAME_W PROP_TAG(PT_UNICODE, pidAdminMin+0x7F) - +#define PR_SRC_URL_NAME PROP_TAG(PT_TSTRING, pidAdminMin + 0x7F) // 0x670f +#define PR_SRC_URL_NAME_A PROP_TAG(PT_STRING8, pidAdminMin + 0x7F) +#define PR_SRC_URL_NAME_W PROP_TAG(PT_UNICODE, pidAdminMin + 0x7F) // Constant wstring to specify URL with fid encoded directly in the URL // For example, URL L"/~FlatUrlSpace/1-401" will refer to folder with FID 1-401 @@ -710,23 +699,23 @@ // in that folder. // But remember that the FID/MID have to be long term, i.e GUID-Globcnt, // the replid used above is simply to explain the idea simpler. -#define WSZ_URL_FLAT_FOLDER_SPACE L"/-FlatUrlSpace-/" -#define cwchUrlFlatFolderSpace 16 +#define WSZ_URL_FLAT_FOLDER_SPACE L"/-FlatUrlSpace-/" +#define cwchUrlFlatFolderSpace 16 // Property that defines whether a folder is secure or not -#define PR_SECURE_IN_SITE PROP_TAG(PT_BOOLEAN, pidAdminMin+0xE) +#define PR_SECURE_IN_SITE PROP_TAG(PT_BOOLEAN, pidAdminMin + 0xE) // PR_LOCAL_COMMIT_TIME is maintained on folders and messages. It is the // FileTime when the object was modified last on the given MDB. It is updated // any time the object is modified (including replicated in change).This is // strictly computed, non-transmittable and non-copyable. -#define PR_LOCAL_COMMIT_TIME PROP_TAG(PT_SYSTIME, pidAdminMin+0x79) +#define PR_LOCAL_COMMIT_TIME PROP_TAG(PT_SYSTIME, pidAdminMin + 0x79) // PR_LOCAL_COMMIT_TIME_MAX is maintained on folders only. // It is >= PR_LOCAL_COMMIT_TIME of all messages in the folder. It is updated // any time any message in the folder is modified. This is strictly computed, // non-transmittable and non-copyable. -#define PR_LOCAL_COMMIT_TIME_MAX PROP_TAG(PT_SYSTIME, pidAdminMin+0x7a) +#define PR_LOCAL_COMMIT_TIME_MAX PROP_TAG(PT_SYSTIME, pidAdminMin + 0x7a) // PR_DELETED_COUNT_TOTAL is maintained on folders only. // It is the total number of messages deleted in this folder from the beginning @@ -735,14 +724,14 @@ // 4 bytes, it will start again at 0. This is updated whenever a message in the // folder is deleted. This is strictly computed, non-transmitabble and // non-copyable. -#define PR_DELETED_COUNT_TOTAL PROP_TAG(PT_LONG, pidAdminMin+0x7b) +#define PR_DELETED_COUNT_TOTAL PROP_TAG(PT_LONG, pidAdminMin + 0x7b) -// PR_AUTO_RESET is maintained on messages only. Its PT_MV_CLSID and is deleted +// PR_AUTO_RESET is maintained on messages only. It's PT_MV_CLSID and is deleted // (by the store) anytime a message is saved, if it has not been // explicitly set on the message between the time it was opened and saved // (by the user/app that opened and later saved the message). // It is intended to be used by async callback agents. -#define PR_AUTO_RESET PROP_TAG(PT_MV_CLSID, pidAdminMin+0x7c) +#define PR_AUTO_RESET PROP_TAG(PT_MV_CLSID, pidAdminMin + 0x7c) /*------------------------------------------------------------------------ * @@ -752,14 +741,13 @@ * *-----------------------------------------------------------------------*/ -//This property can be used in a contents table to get PR_ENTRYID returned -//as a long term entryid instead of a short term entryid. -#define PR_LONGTERM_ENTRYID_FROM_TABLE PROP_TAG(PT_BINARY, pidSpecialMin) +// This property can be used in a contents table to get PR_ENTRYID returned +// as a long term entryid instead of a short term entryid. +#define PR_LONGTERM_ENTRYID_FROM_TABLE PROP_TAG(PT_BINARY, pidSpecialMin) // This is read only property that is used for contents tables that include // subfolder entries. -#define PR_SUBFOLDER PROP_TAG(PT_BOOLEAN, pidAdminMin+0x78) - +#define PR_SUBFOLDER PROP_TAG(PT_BOOLEAN, pidAdminMin + 0x78) /*------------------------------------------------------------------------ * @@ -769,25 +757,25 @@ * *-----------------------------------------------------------------------*/ -#define PR_ORIGINATOR_NAME PROP_TAG( PT_TSTRING, pidMessageWriteableMin+0x3) -#define PR_ORIGINATOR_ADDR PROP_TAG( PT_TSTRING, pidMessageWriteableMin+0x4) -#define PR_ORIGINATOR_ADDRTYPE PROP_TAG( PT_TSTRING, pidMessageWriteableMin+0x5) -#define PR_ORIGINATOR_ENTRYID PROP_TAG( PT_BINARY, pidMessageWriteableMin+0x6) -#define PR_ARRIVAL_TIME PROP_TAG( PT_SYSTIME, pidMessageWriteableMin+0x7) -#define PR_TRACE_INFO PROP_TAG( PT_BINARY, pidMessageWriteableMin+0x8) -#define PR_INTERNAL_TRACE_INFO PROP_TAG( PT_BINARY, pidMessageWriteableMin+0x12) -#define PR_SUBJECT_TRACE_INFO PROP_TAG( PT_BINARY, pidMessageWriteableMin+0x9) -#define PR_RECIPIENT_NUMBER PROP_TAG( PT_LONG, pidMessageWriteableMin+0xA) -#define PR_MTS_SUBJECT_ID PROP_TAG(PT_BINARY, pidMessageWriteableMin+0xB) -#define PR_REPORT_DESTINATION_NAME PROP_TAG(PT_TSTRING, pidMessageWriteableMin+0xC) -#define PR_REPORT_DESTINATION_ENTRYID PROP_TAG(PT_BINARY, pidMessageWriteableMin+0xD) -#define PR_CONTENT_SEARCH_KEY PROP_TAG(PT_BINARY, pidMessageWriteableMin+0xE) -#define PR_FOREIGN_ID PROP_TAG(PT_BINARY, pidMessageWriteableMin+0xF) -#define PR_FOREIGN_REPORT_ID PROP_TAG(PT_BINARY, pidMessageWriteableMin+0x10) -#define PR_FOREIGN_SUBJECT_ID PROP_TAG(PT_BINARY, pidMessageWriteableMin+0x11) -#define PR_PROMOTE_PROP_ID_LIST PROP_TAG(PT_BINARY, pidMessageWriteableMin+0x13) -#define PR_MTS_ID PR_MESSAGE_SUBMISSION_ID -#define PR_MTS_REPORT_ID PR_MESSAGE_SUBMISSION_ID +#define PR_ORIGINATOR_NAME PROP_TAG(PT_TSTRING, pidMessageWriteableMin + 0x3) +#define PR_ORIGINATOR_ADDR PROP_TAG(PT_TSTRING, pidMessageWriteableMin + 0x4) +#define PR_ORIGINATOR_ADDRTYPE PROP_TAG(PT_TSTRING, pidMessageWriteableMin + 0x5) +#define PR_ORIGINATOR_ENTRYID PROP_TAG(PT_BINARY, pidMessageWriteableMin + 0x6) +#define PR_ARRIVAL_TIME PROP_TAG(PT_SYSTIME, pidMessageWriteableMin + 0x7) +#define PR_TRACE_INFO PROP_TAG(PT_BINARY, pidMessageWriteableMin + 0x8) +#define PR_INTERNAL_TRACE_INFO PROP_TAG(PT_BINARY, pidMessageWriteableMin + 0x12) +#define PR_SUBJECT_TRACE_INFO PROP_TAG(PT_BINARY, pidMessageWriteableMin + 0x9) +#define PR_RECIPIENT_NUMBER PROP_TAG(PT_LONG, pidMessageWriteableMin + 0xA) +#define PR_MTS_SUBJECT_ID PROP_TAG(PT_BINARY, pidMessageWriteableMin + 0xB) +#define PR_REPORT_DESTINATION_NAME PROP_TAG(PT_TSTRING, pidMessageWriteableMin + 0xC) +#define PR_REPORT_DESTINATION_ENTRYID PROP_TAG(PT_BINARY, pidMessageWriteableMin + 0xD) +#define PR_CONTENT_SEARCH_KEY PROP_TAG(PT_BINARY, pidMessageWriteableMin + 0xE) +#define PR_FOREIGN_ID PROP_TAG(PT_BINARY, pidMessageWriteableMin + 0xF) +#define PR_FOREIGN_REPORT_ID PROP_TAG(PT_BINARY, pidMessageWriteableMin + 0x10) +#define PR_FOREIGN_SUBJECT_ID PROP_TAG(PT_BINARY, pidMessageWriteableMin + 0x11) +#define PR_PROMOTE_PROP_ID_LIST PROP_TAG(PT_BINARY, pidMessageWriteableMin + 0x13) +#define PR_MTS_ID PR_MESSAGE_SUBMISSION_ID +#define PR_MTS_REPORT_ID PR_MESSAGE_SUBMISSION_ID /*------------------------------------------------------------------------ * @@ -797,62 +785,58 @@ * *-----------------------------------------------------------------------*/ -#define MAX_ADMD_NAME_SIZ 17 -#define MAX_PRMD_NAME_SIZ 17 -#define MAX_COUNTRY_NAME_SIZ 4 -#define MAX_MTA_NAME_SIZ 33 +#define MAX_ADMD_NAME_SIZ 17 +#define MAX_PRMD_NAME_SIZ 17 +#define MAX_COUNTRY_NAME_SIZ 4 +#define MAX_MTA_NAME_SIZ 33 -#define ADMN_PAD 3 -#define PRMD_PAD 3 -#define COUNTRY_PAD 0 -#define MTA_PAD 3 -#define PRMD_PAD_FOR_ACTIONS 2 -#define MTA_PAD_FOR_ACTIONS 2 +#define ADMN_PAD 3 +#define PRMD_PAD 3 +#define COUNTRY_PAD 0 +#define MTA_PAD 3 +#define PRMD_PAD_FOR_ACTIONS 2 +#define MTA_PAD_FOR_ACTIONS 2 typedef struct { - LONG lAction; // The routing action the tracing site - // took.(1984 actions only) - FILETIME ftArrivalTime; // The time at which the communique - // entered the tracing site. - FILETIME ftDeferredTime; // The time are which the tracing site - // released the message. - char rgchADMDName[MAX_ADMD_NAME_SIZ+ADMN_PAD]; // ADMD - char rgchCountryName[MAX_COUNTRY_NAME_SIZ+COUNTRY_PAD]; // Country - char rgchPRMDId[MAX_PRMD_NAME_SIZ+PRMD_PAD]; // PRMD - char rgchAttADMDName[MAX_ADMD_NAME_SIZ+ADMN_PAD]; // Attempted ADMD - char rgchAttCountryName[MAX_COUNTRY_NAME_SIZ+COUNTRY_PAD]; // Attempted Country - char rgchAttPRMDId[MAX_PRMD_NAME_SIZ+PRMD_PAD_FOR_ACTIONS]; // Attempted PRMD - BYTE bAdditionalActions; // 1998 additional actions -} TRACEENTRY, FAR * LPTRACEENTRY; + LONG lAction; // The routing action the tracing site + // took.(1984 actions only) + FILETIME ftArrivalTime; // The time at which the communique + // entered the tracing site. + FILETIME ftDeferredTime; // The time are which the tracing site + // released the message. + char rgchADMDName[MAX_ADMD_NAME_SIZ + ADMN_PAD]; // ADMD + char rgchCountryName[MAX_COUNTRY_NAME_SIZ + COUNTRY_PAD]; // Country + char rgchPRMDId[MAX_PRMD_NAME_SIZ + PRMD_PAD]; // PRMD + char rgchAttADMDName[MAX_ADMD_NAME_SIZ + ADMN_PAD]; // Attempted ADMD + char rgchAttCountryName[MAX_COUNTRY_NAME_SIZ + COUNTRY_PAD]; // Attempted Country + char rgchAttPRMDId[MAX_PRMD_NAME_SIZ + PRMD_PAD_FOR_ACTIONS]; // Attempted PRMD + BYTE bAdditionalActions; // 1998 additional actions +} TRACEENTRY, FAR *LPTRACEENTRY; typedef struct { - ULONG cEntries; // Number of trace entries - TRACEENTRY rgtraceentry[MAPI_DIM]; // array of trace entries -} TRACEINFO, FAR * LPTRACEINFO; - -typedef struct -{ - LONG lAction; // The 1984 routing action the tracing domain took. - FILETIME ftArrivalTime; // The time at which the communique entered the tracing domain. - FILETIME ftDeferredTime; // The time are which the tracing domain released the message. - char rgchADMDName[MAX_ADMD_NAME_SIZ+ADMN_PAD]; // ADMD - char rgchCountryName[MAX_COUNTRY_NAME_SIZ+COUNTRY_PAD]; // Country - char rgchPRMDId[MAX_PRMD_NAME_SIZ+PRMD_PAD]; // PRMD - char rgchAttADMDName[MAX_ADMD_NAME_SIZ+ADMN_PAD]; // Attempted ADMD - char rgchAttCountryName[MAX_COUNTRY_NAME_SIZ+COUNTRY_PAD]; // Attempted Country - char rgchAttPRMDId[MAX_PRMD_NAME_SIZ+PRMD_PAD]; // Attempted PRMD - char rgchMTAName[MAX_MTA_NAME_SIZ+MTA_PAD]; // MTA Name - char rgchAttMTAName[MAX_MTA_NAME_SIZ+MTA_PAD_FOR_ACTIONS]; // Attempted MTA Name - BYTE bAdditionalActions; // 1988 additional actions -}INTTRACEENTRY, *PINTTRACEENTRY; - - -typedef struct -{ - ULONG cEntries; // Number of trace entries - INTTRACEENTRY rgIntTraceEntry[MAPI_DIM]; // array of internal trace entries -}INTTRACEINFO, *PINTTRACEINFO; + ULONG cEntries; // Number of trace entries + TRACEENTRY rgtraceentry[MAPI_DIM]; // array of trace entries +} TRACEINFO, FAR *LPTRACEINFO; +typedef struct { + LONG lAction; // The 1984 routing action the tracing domain took. + FILETIME ftArrivalTime; // The time at which the communique entered the tracing domain. + FILETIME ftDeferredTime; // The time are which the tracing domain released the message. + char rgchADMDName[MAX_ADMD_NAME_SIZ + ADMN_PAD]; // ADMD + char rgchCountryName[MAX_COUNTRY_NAME_SIZ + COUNTRY_PAD]; // Country + char rgchPRMDId[MAX_PRMD_NAME_SIZ + PRMD_PAD]; // PRMD + char rgchAttADMDName[MAX_ADMD_NAME_SIZ + ADMN_PAD]; // Attempted ADMD + char rgchAttCountryName[MAX_COUNTRY_NAME_SIZ + COUNTRY_PAD]; // Attempted Country + char rgchAttPRMDId[MAX_PRMD_NAME_SIZ + PRMD_PAD]; // Attempted PRMD + char rgchMTAName[MAX_MTA_NAME_SIZ + MTA_PAD]; // MTA Name + char rgchAttMTAName[MAX_MTA_NAME_SIZ + MTA_PAD_FOR_ACTIONS]; // Attempted MTA Name + BYTE bAdditionalActions; // 1988 additional actions +} INTTRACEENTRY, *PINTTRACEENTRY; + +typedef struct { + ULONG cEntries; // Number of trace entries + INTTRACEENTRY rgIntTraceEntry[MAPI_DIM]; // array of internal trace entries +} INTTRACEINFO, *PINTTRACEINFO; /*------------------------------------------------------------------------ * @@ -862,85 +846,74 @@ typedef struct * *-----------------------------------------------------------------------*/ - /* ulRowFlags */ -#define ROWLIST_REPLACE ((ULONG)1) - -#define ROW_ADD ((ULONG)1) -#define ROW_MODIFY ((ULONG)2) -#define ROW_REMOVE ((ULONG)4) -#define ROW_EMPTY (ROW_ADD|ROW_REMOVE) - -typedef struct _ROWENTRY -{ - ULONG ulRowFlags; - ULONG cValues; - LPSPropValue rgPropVals; -} ROWENTRY, FAR * LPROWENTRY; - -typedef struct _ROWLIST -{ - ULONG cEntries; - ROWENTRY aEntries[MAPI_DIM]; -} ROWLIST, FAR * LPROWLIST; - -#define EXCHANGE_IEXCHANGEMODIFYTABLE_METHODS(IPURE) \ - MAPIMETHOD(GetLastError) \ - (THIS_ HRESULT hResult, \ - ULONG ulFlags, \ - LPMAPIERROR FAR * lppMAPIError) IPURE; \ - MAPIMETHOD(GetTable) \ - (THIS_ ULONG ulFlags, \ - LPMAPITABLE FAR * lppTable) IPURE; \ - MAPIMETHOD(ModifyTable) \ - (THIS_ ULONG ulFlags, \ - LPROWLIST lpMods) IPURE; - -#undef INTERFACE -#define INTERFACE IExchangeModifyTable -DECLARE_MAPI_INTERFACE_(IExchangeModifyTable, IUnknown) -{ - MAPI_IUNKNOWN_METHODS(PURE) - EXCHANGE_IEXCHANGEMODIFYTABLE_METHODS(PURE) -}; -#undef IMPL +#define ROWLIST_REPLACE ((ULONG)1) + +#define ROW_ADD ((ULONG)1) +#define ROW_MODIFY ((ULONG)2) +#define ROW_REMOVE ((ULONG)4) +#define ROW_EMPTY (ROW_ADD | ROW_REMOVE) + +typedef struct _ROWENTRY { + ULONG ulRowFlags; + ULONG cValues; + LPSPropValue rgPropVals; +} ROWENTRY, FAR *LPROWENTRY; + +typedef struct _ROWLIST { + ULONG cEntries; + ROWENTRY aEntries[MAPI_DIM]; +} ROWLIST, FAR *LPROWLIST; + +#define EXCHANGE_IEXCHANGEMODIFYTABLE_METHODS(IPURE) \ + MAPIMETHOD(GetLastError) \ + (THIS_ HRESULT hResult, ULONG ulFlags, LPMAPIERROR FAR * lppMAPIError) IPURE; \ + MAPIMETHOD(GetTable) \ + (THIS_ ULONG ulFlags, LPMAPITABLE FAR * lppTable) IPURE; \ + MAPIMETHOD(ModifyTable) \ + (THIS_ ULONG ulFlags, LPROWLIST lpMods) IPURE; + +#undef INTERFACE +#define INTERFACE IExchangeModifyTable +DECLARE_MAPI_INTERFACE_(IExchangeModifyTable, + IUnknown){MAPI_IUNKNOWN_METHODS(PURE) EXCHANGE_IEXCHANGEMODIFYTABLE_METHODS(PURE)}; +#undef IMPL #define IMPL -DECLARE_MAPI_INTERFACE_PTR(IExchangeModifyTable, LPEXCHANGEMODIFYTABLE); +DECLARE_MAPI_INTERFACE_PTR(IExchangeModifyTable, LPEXCHANGEMODIFYTABLE); /* Special flag bit for GetContentsTable, GetHierarchyTable and - OpenEntry. - Supported by > 5.x servers - If set in GetContentsTable and GetHierarchyTable - we will show only items that are soft deleted, i.e deleted - by user but not yet purged from the system. If set in OpenEntry - we will open this item even if it is soft deleted */ + OpenEntry. + Supported by > 5.x servers + If set in GetContentsTable and GetHierarchyTable + we will show only items that are soft deleted, i.e deleted + by user but not yet purged from the system. If set in OpenEntry + we will open this item even if it is soft deleted */ /* Flag bits must not collide by existing definitions in Mapi */ /****** MAPI_UNICODE ((ULONG) 0x80000000) above */ /****** MAPI_DEFERRED_ERRORS ((ULONG) 0x00000008) below */ /****** MAPI_ASSOCIATED ((ULONG) 0x00000040) below */ /****** CONVENIENT_DEPTH ((ULONG) 0x00000001) */ -#define SHOW_SOFT_DELETES ((ULONG) 0x00000002) -#define SHOW_SUBFOLDERS ((ULONG) 0x00000004) +#define SHOW_SOFT_DELETES ((ULONG)0x00000002) +#define SHOW_SUBFOLDERS ((ULONG)0x00000004) // reserved flag bit(s) - do not set -#define MAPI_RESERVED1 ((ULONG) 0x00010000) +#define MAPI_RESERVED1 ((ULONG)0x00010000) // Do not block this OpenMessage (MAPI's OpenEntry) -#define MDB_OPEN_MSG_NO_BLOCK ((ULONG) 0x00000020) +#define MDB_OPEN_MSG_NO_BLOCK ((ULONG)0x00000020) // Unlock a MID at SaveChanges /****** KEEP_OPEN_READONLY ((ULONG) 0x00000001) */ /****** KEEP_OPEN_READWRITE ((ULONG) 0x00000002) */ /****** FORCE_SAVE ((ULONG) 0x00000004) */ /****** MAPI_DEFERRED_ERRORS ((ULONG) 0x00000008) */ -#define MDB_SAVE_MSG_UNLOCK ((ULONG) 0x00000040) - +#define MDB_SAVE_MSG_UNLOCK ((ULONG)0x00000040) /* Special flag bit for DeleteFolder - Supported by > 5.x servers - If set the server will hard delete the folder (i.e it will not be - retained for later recovery) */ + Supported by > 5.x servers + If set the server will hard delete the folder (i.e it will not be + retained for later recovery) */ /* Flag bits must not collide by existing definitions in Mapi */ /* DeleteFolder */ /***** #define DEL_MESSAGES ((ULONG) 0x00000001) */ @@ -949,33 +922,32 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeModifyTable, LPEXCHANGEMODIFYTABLE); /* EmptyFolder */ /***** #define DEL_ASSOCIATED ((ULONG) 0x00000008) */ -#define DELETE_HARD_DELETE ((ULONG) 0x00000010) +#define DELETE_HARD_DELETE ((ULONG)0x00000010) /* Access Control Specifics */ -//Properties -#define PR_MEMBER_ID PROP_TAG(PT_I8, pidSpecialMin+0x01) -#define PR_MEMBER_NAME PROP_TAG(PT_TSTRING, pidSpecialMin+0x02) -#define PR_MEMBER_ENTRYID PR_ENTRYID -#define PR_MEMBER_RIGHTS PROP_TAG(PT_LONG, pidSpecialMin+0x03) +// Properties +#define PR_MEMBER_ID PROP_TAG(PT_I8, pidSpecialMin + 0x01) +#define PR_MEMBER_NAME PROP_TAG(PT_TSTRING, pidSpecialMin + 0x02) +#define PR_MEMBER_ENTRYID PR_ENTRYID +#define PR_MEMBER_RIGHTS PROP_TAG(PT_LONG, pidSpecialMin + 0x03) -//Security bits +// Security bits typedef DWORD RIGHTS; -#define frightsReadAny 0x0000001L -#define frightsCreate 0x0000002L -#define frightsEditOwned 0x0000008L -#define frightsDeleteOwned 0x0000010L -#define frightsEditAny 0x0000020L -#define frightsDeleteAny 0x0000040L -#define frightsCreateSubfolder 0x0000080L -#define frightsOwner 0x0000100L -#define frightsContact 0x0000200L // NOTE: not part of rightsAll -#define frightsVisible 0x0000400L -#define rightsNone 0x00000000 -#define rightsReadOnly frightsReadAny -#define rightsReadWrite (frightsReadAny|frightsEditAny) -#define rightsAll 0x00005FBL - +#define frightsReadAny 0x0000001L +#define frightsCreate 0x0000002L +#define frightsEditOwned 0x0000008L +#define frightsDeleteOwned 0x0000010L +#define frightsEditAny 0x0000020L +#define frightsDeleteAny 0x0000040L +#define frightsCreateSubfolder 0x0000080L +#define frightsOwner 0x0000100L +#define frightsContact 0x0000200L // NOTE: not part of rightsAll +#define frightsVisible 0x0000400L +#define rightsNone 0x00000000 +#define rightsReadOnly frightsReadAny +#define rightsReadWrite (frightsReadAny | frightsEditAny) +#define rightsAll 0x00005FBL // // Mailbox specific access rights. @@ -988,91 +960,94 @@ typedef DWORD RIGHTS; // #define fsdpermUserDeleteMailbox DELETE #define fsdpermUserMailboxOwner 0x00000001 -#define fsdpermUserSendAs 0x00000002 -#define fsdpermUserPrimaryUser 0x00000004 - +#define fsdpermUserSendAs 0x00000002 +#define fsdpermUserPrimaryUser 0x00000004 -#define sdpermUserGenericRead (STANDARD_RIGHTS_READ) +#define sdpermUserGenericRead (STANDARD_RIGHTS_READ) // generic execute -#define sdpermUserGenericExecute (STANDARD_RIGHTS_EXECUTE) +#define sdpermUserGenericExecute (STANDARD_RIGHTS_EXECUTE) // generic write -#define sdpermUserGenericWrite (STANDARD_RIGHTS_WRITE | fsdpermUserDeleteMailbox) +#define sdpermUserGenericWrite (STANDARD_RIGHTS_WRITE | fsdpermUserDeleteMailbox) // generic all -#define sdpermUserGenericAll (STANDARD_RIGHTS_ALL | fsdpermUserMailboxOwner | fsdpermUserSendAs | fsdpermUserPrimaryUser) +#define sdpermUserGenericAll \ + (STANDARD_RIGHTS_ALL | fsdpermUserMailboxOwner | fsdpermUserSendAs | fsdpermUserPrimaryUser) // // Message specific rights. // typedef DWORD SDRIGHTS; -#define fsdrightReadBody 0x00000001 //** ONLY ON MESSAGES, SAME AS FILE_READ_DATA -#define fsdrightListContents 0x00000001 //** ONLY ON FOLDERS, SAME AS FILE_LIST_DATA - IGNORED -#define fsdrightWriteBody 0x00000002 //** ONLY ON MESSAGES, SAME AS FILE_WRITE_DATA -#define fsdrightCreateItem 0x00000002 //** ONLY ON FOLDERs, SAME AS FILE_ADD_FILE +#define fsdrightReadBody 0x00000001 //** ONLY ON MESSAGES, SAME AS FILE_READ_DATA +#define fsdrightListContents 0x00000001 //** ONLY ON FOLDERS, SAME AS FILE_LIST_DATA - IGNORED +#define fsdrightWriteBody 0x00000002 //** ONLY ON MESSAGES, SAME AS FILE_WRITE_DATA +#define fsdrightCreateItem 0x00000002 //** ONLY ON FOLDERs, SAME AS FILE_ADD_FILE -#define fsdrightAppendMsg 0x00000004 //** ONLY ON MESSAGES, SAME AS FILE_WRITE_DATA. ENFORCED BY IFS. -#define fsdrightCreateContainer 0x00000004 //** ONLY ON FOLDERS, SAME AS FILE_ADD_FILE +#define fsdrightAppendMsg 0x00000004 //** ONLY ON MESSAGES, SAME AS FILE_WRITE_DATA. ENFORCED BY IFS. +#define fsdrightCreateContainer 0x00000004 //** ONLY ON FOLDERS, SAME AS FILE_ADD_FILE -#define fsdrightReadProperty 0x00000008 //** SAME AS FILE_READ_EA -#define fsdrightWriteProperty 0x00000010 //** SAME AS FILE_WRITE_EA +#define fsdrightReadProperty 0x00000008 //** SAME AS FILE_READ_EA +#define fsdrightWriteProperty 0x00000010 //** SAME AS FILE_WRITE_EA -#define fsdrightExecute 0x00000020 // Same as FILE_EXECUTE/FILE_TRAVERSE. ENFORCED BY IFS -#define fsdrightReserved1 0x00000040 // Same as FILE_DELETE_CHILD.. Currently unused -#define fsdrightReadAttributes 0x00000080 // Same as FILE_READ_ATTRIBUTES. Currently unused -#define fsdrightWriteAttributes 0x00000100 // Same as FILE_WRITE_ATTRIBUTES. Currently unused +#define fsdrightExecute 0x00000020 // Same as FILE_EXECUTE/FILE_TRAVERSE. ENFORCED BY IFS +#define fsdrightReserved1 0x00000040 // Same as FILE_DELETE_CHILD.. Currently unused +#define fsdrightReadAttributes 0x00000080 // Same as FILE_READ_ATTRIBUTES. Currently unused +#define fsdrightWriteAttributes 0x00000100 // Same as FILE_WRITE_ATTRIBUTES. Currently unused -#define fsdrightWriteOwnProperty 0x00000200 //** ONLY ON MESSAGES -#define fsdrightDeleteOwnItem 0x00000400 //** ONLY ON MESSAGES -#define fsdrightViewItem 0x00000800 -#define fsdrightOwner 0x00004000 //** ONLY ON FOLDERS -#define fsdrightContact 0x00008000 //** ONLY ON FOLDERS +#define fsdrightWriteOwnProperty 0x00000200 //** ONLY ON MESSAGES +#define fsdrightDeleteOwnItem 0x00000400 //** ONLY ON MESSAGES +#define fsdrightViewItem 0x00000800 +#define fsdrightOwner 0x00004000 //** ONLY ON FOLDERS +#define fsdrightContact 0x00008000 //** ONLY ON FOLDERS // // Standard NT rights. // -#define fsdrightWriteSD WRITE_DAC -#define fsdrightDelete DELETE -#define fsdrightWriteOwner WRITE_OWNER -#define fsdrightReadControl READ_CONTROL -#define fsdrightSynchronize SYNCHRONIZE - -#define sdrightsNone 0x00000000 -#define sdrightsBestAccess MAXIMUM_ALLOWED -#define sdrightsReadOnly GENERIC_READ -#define sdrightsReadWrite GENERIC_READ | GENERIC_WRITE - -#define sdrightsGenericRead (fsdrightReadControl | fsdrightReadBody | fsdrightReadAttributes | fsdrightReadProperty | fsdrightViewItem |\ - fsdrightSynchronize) -#define sdrightsGenericWrite (fsdrightReadControl | fsdrightWriteBody | fsdrightWriteAttributes | fsdrightWriteProperty | \ - fsdrightAppendMsg | fsdrightCreateItem | fsdrightDelete | fsdrightCreateContainer | \ - fsdrightOwner | fsdrightSynchronize | fsdrightWriteSD | fsdrightWriteOwner) - -#define sdrightsGenericExecute (fsdrightReadControl | fsdrightReadAttributes | fsdrightExecute | fsdrightViewItem | fsdrightSynchronize) - -#define sdrightsGenericAll (fsdrightDelete | fsdrightReadProperty | fsdrightWriteProperty |\ - fsdrightCreateItem | fsdrightCreateContainer | fsdrightReadControl | fsdrightWriteSD |\ - fsdrightWriteOwner | fsdrightReadControl | \ - fsdrightViewItem | fsdrightOwner | \ - fsdrightWriteOwnProperty | fsdrightDeleteOwnItem | fsdrightSynchronize | \ - fsdrightExecute | fsdrightReserved1 | fsdrightReadAttributes | fsdrightWriteAttributes | \ - fsdrightReadBody | fsdrightWriteBody | fsdrightSynchronize | fsdrightContact) +#define fsdrightWriteSD WRITE_DAC +#define fsdrightDelete DELETE +#define fsdrightWriteOwner WRITE_OWNER +#define fsdrightReadControl READ_CONTROL +#define fsdrightSynchronize SYNCHRONIZE + +#define sdrightsNone 0x00000000 +#define sdrightsBestAccess MAXIMUM_ALLOWED +#define sdrightsReadOnly GENERIC_READ +#define sdrightsReadWrite GENERIC_READ | GENERIC_WRITE + +#define sdrightsGenericRead \ + (fsdrightReadControl | fsdrightReadBody | fsdrightReadAttributes | fsdrightReadProperty | fsdrightViewItem | \ + fsdrightSynchronize) +#define sdrightsGenericWrite \ + (fsdrightReadControl | fsdrightWriteBody | fsdrightWriteAttributes | fsdrightWriteProperty | fsdrightAppendMsg | \ + fsdrightCreateItem | fsdrightDelete | fsdrightCreateContainer | fsdrightOwner | fsdrightSynchronize | \ + fsdrightWriteSD | fsdrightWriteOwner) + +#define sdrightsGenericExecute \ + (fsdrightReadControl | fsdrightReadAttributes | fsdrightExecute | fsdrightViewItem | fsdrightSynchronize) + +#define sdrightsGenericAll \ + (fsdrightDelete | fsdrightReadProperty | fsdrightWriteProperty | fsdrightCreateItem | fsdrightCreateContainer | \ + fsdrightReadControl | fsdrightWriteSD | fsdrightWriteOwner | fsdrightReadControl | fsdrightViewItem | \ + fsdrightOwner | fsdrightWriteOwnProperty | fsdrightDeleteOwnItem | fsdrightSynchronize | fsdrightExecute | \ + fsdrightReserved1 | fsdrightReadAttributes | fsdrightWriteAttributes | fsdrightReadBody | fsdrightWriteBody | \ + fsdrightSynchronize | fsdrightContact) // // SDRights that together make up rightsOwner. // -#define sdrightsFolderOwner (fsdrightWriteProperty | fsdrightOwner | fsdrightWriteSD | fsdrightDelete | \ - fsdrightWriteOwner | fsdrightWriteAttributes) +#define sdrightsFolderOwner \ + (fsdrightWriteProperty | fsdrightOwner | fsdrightWriteSD | fsdrightDelete | fsdrightWriteOwner | \ + fsdrightWriteAttributes) // // Rights that are valid on folders. // -#define sdrightsFolders (fsdrightDelete | fsdrightReadProperty | fsdrightReadAttributes | \ - fsdrightWriteProperty | fsdrightWriteAttributes | fsdrightWriteOwner | \ - fsdrightReadControl | fsdrightWriteSD | fsdrightExecute | \ - fsdrightCreateContainer | fsdrightViewItem | fsdrightOwner | \ - fsdrightContact | fsdrightCreateItem | fsdrightSynchronize | fsdrightListContents | fsdrightReserved1) +#define sdrightsFolders \ + (fsdrightDelete | fsdrightReadProperty | fsdrightReadAttributes | fsdrightWriteProperty | \ + fsdrightWriteAttributes | fsdrightWriteOwner | fsdrightReadControl | fsdrightWriteSD | fsdrightExecute | \ + fsdrightCreateContainer | fsdrightViewItem | fsdrightOwner | fsdrightContact | fsdrightCreateItem | \ + fsdrightSynchronize | fsdrightListContents | fsdrightReserved1) // // Rights that are valid on messages. @@ -1080,30 +1055,31 @@ typedef DWORD SDRIGHTS; // // NB: fsdrightWriteOwnProperty/fsdrightDeleteOwnItem are NOT in this list. // -#define sdrightsItems (fsdrightDelete | fsdrightReadBody | fsdrightReadAttributes | fsdrightReadProperty | \ - fsdrightWriteProperty | fsdrightWriteBody | fsdrightWriteAttributes | fsdrightReadControl | \ - fsdrightWriteOwner | fsdrightWriteSD | fsdrightViewItem | fsdrightWriteOwnProperty | \ - fsdrightDeleteOwnItem | fsdrightSynchronize | fsdrightExecute | fsdrightAppendMsg) +#define sdrightsItems \ + (fsdrightDelete | fsdrightReadBody | fsdrightReadAttributes | fsdrightReadProperty | fsdrightWriteProperty | \ + fsdrightWriteBody | fsdrightWriteAttributes | fsdrightReadControl | fsdrightWriteOwner | fsdrightWriteSD | \ + fsdrightViewItem | fsdrightWriteOwnProperty | fsdrightDeleteOwnItem | fsdrightSynchronize | fsdrightExecute | \ + fsdrightAppendMsg) // // These access rights are ignored in the determination of a canonical ACL. Since the exchange store ignores // these rights, their presence or absense doesn't make an ACL canonical. // -#define sdrightsIgnored (fsdrightExecute | fsdrightAppendMsg | fsdrightContact | fsdrightReserved1) +#define sdrightsIgnored (fsdrightExecute | fsdrightAppendMsg | fsdrightContact | fsdrightReserved1) // // Backwards Compatible rights definitions. // -#define msgrightsGenericRead (sdrightsGenericRead & sdrightsItems) -#define msgrightsGenericWrite (sdrightsGenericWrite & sdrightsItems) -#define msgrightsGenericExecute (sdrightsGenericExecute & sdrightsItems) -#define msgrightsGenericAll (sdrightsGenericAll & sdrightsItems) +#define msgrightsGenericRead (sdrightsGenericRead & sdrightsItems) +#define msgrightsGenericWrite (sdrightsGenericWrite & sdrightsItems) +#define msgrightsGenericExecute (sdrightsGenericExecute & sdrightsItems) +#define msgrightsGenericAll (sdrightsGenericAll & sdrightsItems) -#define fldrightsGenericRead (sdrightsGenericRead & sdrightsFolders) -#define fldrightsGenericWrite (sdrightsGenericWrite & sdrightsFolders) -#define fldrightsGenericExecute (sdrightsGenericExecute & sdrightsFolders) -#define fldrightsGenericAll (sdrightsGenericAll & sdrightsFolders) +#define fldrightsGenericRead (sdrightsGenericRead & sdrightsFolders) +#define fldrightsGenericWrite (sdrightsGenericWrite & sdrightsFolders) +#define fldrightsGenericExecute (sdrightsGenericExecute & sdrightsFolders) +#define fldrightsGenericAll (sdrightsGenericAll & sdrightsFolders) // // If set in the RM control field of an NTSD, allows @@ -1120,14 +1096,15 @@ typedef DWORD SDRIGHTS; #define SET_GUID_PROP_ID(pguid, ptag) (pguid)->Data1 = PROP_ID(ptag) #define SET_GUID_SUB_PROP_ID(pguid, ptag, subptag) (pguid)->Data1 = (PROP_ID(ptag) | PROP_ID(subptag) << 16) -#define PROPERTY_GUID(ptag) { PROP_ID(ptag), \ - 0x6585, 0x11d3, \ - {0xb6, 0x19, 0x00, 0xaa, 0x00, 0x4b, 0x9c, 0x30}} \ - -#define SUB_PROPERTY_GUID(ptag, subptag) { PROP_ID(subptag) << 16 | PROP_ID(ptag), \ - 0x6585, 0x11d3, \ - {0xb6, 0x19, 0x00, 0xaa, 0x00, 0x4b, 0x9c, 0x30}} \ +#define PROPERTY_GUID(ptag) \ + { \ + PROP_ID(ptag), 0x6585, 0x11d3, { 0xb6, 0x19, 0x00, 0xaa, 0x00, 0x4b, 0x9c, 0x30 } \ + } +#define SUB_PROPERTY_GUID(ptag, subptag) \ + { \ + PROP_ID(subptag) << 16 | PROP_ID(ptag), 0x6585, 0x11d3, { 0xb6, 0x19, 0x00, 0xaa, 0x00, 0x4b, 0x9c, 0x30 } \ + } // // Transfer version for PR_NT_SECURITY_DESCRIPTOR. @@ -1156,12 +1133,12 @@ typedef DWORD SDRIGHTS; // // Please note that OLEDB/DAV reserves the even numbers of the transfer version, so it must ALWAYS be an odd number. // -#define SECURITY_DESCRIPTOR_TRANSFER_VERSION 0x0003 +#define SECURITY_DESCRIPTOR_TRANSFER_VERSION 0x0003 -#define SECURITY_DESCRIPTOR_OF(pb) (((BYTE *)(pb)) + *((WORD *)(pb))) +#define SECURITY_DESCRIPTOR_OF(pb) (((BYTE *)(pb)) + *((WORD *)(pb))) #define SECURITY_DESCRIPTOR_VERSION(pb) (*((WORD *)((pb) + sizeof(WORD)))) #define SECURITY_INFORMATION_OF(pb) (*((DWORD *)((pb) + sizeof(WORD) + sizeof(WORD)))) -#define CbSecurityDescriptorHeader(pb) (*((WORD *)(pb))) +#define CbSecurityDescriptorHeader(pb) (*((WORD *)(pb))) // // To check to see if the security descriptor version matches the currently compiled @@ -1173,57 +1150,56 @@ typedef DWORD SDRIGHTS; // Role scopes // typedef BYTE ROLESCOPE; -#define ROLESCOPE_OBJECT 0x00 // Roles will be read from the object (folder or item) itself -#define ROLESCOPE_FOLDER 0x01 // Roles will be read from the folder itself, or the containing folder if it is an item -#define ROLESCOPE_MAX ROLESCOPE_FOLDER +#define ROLESCOPE_OBJECT 0x00 // Roles will be read from the object (folder or item) itself +#define ROLESCOPE_FOLDER 0x01 // Roles will be read from the folder itself, or the containing folder if it is an item +#define ROLESCOPE_MAX ROLESCOPE_FOLDER // // Security authority used for role sids // -#define SECURITY_EXCHANGE_AUTHORITY {0,0,0,0,0,8} +#define SECURITY_EXCHANGE_AUTHORITY {0, 0, 0, 0, 0, 8} // // Application role properties // -#define PR_XMT_SECURITY_ROLE_1 PROP_TAG(PT_BINARY,0x3d25) -#define PR_XMT_SECURITY_ROLE_1_AS_XML PROP_TAG(PT_TSTRING,0x3d25) -#define PR_XMT_SECURITY_ROLE_2 PROP_TAG(PT_BINARY,0x3d26) -#define PR_XMT_SECURITY_ROLE_2_AS_XML PROP_TAG(PT_TSTRING,0x3d26) -#define PR_XMT_SECURITY_ROLE_3 PROP_TAG(PT_BINARY,0x3d27) -#define PR_XMT_SECURITY_ROLE_3_AS_XML PROP_TAG(PT_TSTRING,0x3d27) -#define PR_XMT_SECURITY_ROLE_4 PROP_TAG(PT_BINARY,0x3d28) -#define PR_XMT_SECURITY_ROLE_4_AS_XML PROP_TAG(PT_TSTRING,0x3d28) -#define PR_XMT_SECURITY_ROLE_5 PROP_TAG(PT_BINARY,0x3d29) -#define PR_XMT_SECURITY_ROLE_5_AS_XML PROP_TAG(PT_TSTRING,0x3d29) -#define PR_XMT_SECURITY_ROLE_6 PROP_TAG(PT_BINARY,0x3d2A) -#define PR_XMT_SECURITY_ROLE_6_AS_XML PROP_TAG(PT_TSTRING,0x3d2A) -#define PR_XMT_SECURITY_ROLE_7 PROP_TAG(PT_BINARY,0x3d2B) -#define PR_XMT_SECURITY_ROLE_7_AS_XML PROP_TAG(PT_TSTRING,0x3d2B) -#define PR_XMT_SECURITY_ROLE_8 PROP_TAG(PT_BINARY,0x3d2C) -#define PR_XMT_SECURITY_ROLE_8_AS_XML PROP_TAG(PT_TSTRING,0x3d2C) -#define PR_NON_XMT_SECURITY_ROLE_1 PROP_TAG(PT_BINARY,0x0E7C) -#define PR_NON_XMT_SECURITY_ROLE_1_AS_XML PROP_TAG(PT_TSTRING,0x0E7C) -#define PR_NON_XMT_SECURITY_ROLE_2 PROP_TAG(PT_BINARY,0x0E7D) -#define PR_NON_XMT_SECURITY_ROLE_2_AS_XML PROP_TAG(PT_TSTRING,0x0E7D) -#define PR_NON_XMT_SECURITY_ROLE_3 PROP_TAG(PT_BINARY,0x0E7E) -#define PR_NON_XMT_SECURITY_ROLE_3_AS_XML PROP_TAG(PT_TSTRING,0x0E7E) -#define PR_NON_XMT_SECURITY_ROLE_4 PROP_TAG(PT_BINARY,0x0E7F) -#define PR_NON_XMT_SECURITY_ROLE_4_AS_XML PROP_TAG(PT_TSTRING,0x0E7F) -#define PR_NON_XMT_SECURITY_ROLE_5 PROP_TAG(PT_BINARY,0x0E80) -#define PR_NON_XMT_SECURITY_ROLE_5_AS_XML PROP_TAG(PT_TSTRING,0x0E80) -#define PR_NON_XMT_SECURITY_ROLE_6 PROP_TAG(PT_BINARY,0x0E81) -#define PR_NON_XMT_SECURITY_ROLE_6_AS_XML PROP_TAG(PT_TSTRING,0x0E81) -#define PR_NON_XMT_SECURITY_ROLE_7 PROP_TAG(PT_BINARY,0x0E82) -#define PR_NON_XMT_SECURITY_ROLE_7_AS_XML PROP_TAG(PT_TSTRING,0x0E82) -#define PR_NON_XMT_SECURITY_ROLE_8 PROP_TAG(PT_BINARY,0x0E83) -#define PR_NON_XMT_SECURITY_ROLE_8_AS_XML PROP_TAG(PT_TSTRING,0x0E83) - +#define PR_XMT_SECURITY_ROLE_1 PROP_TAG(PT_BINARY, 0x3d25) +#define PR_XMT_SECURITY_ROLE_1_AS_XML PROP_TAG(PT_TSTRING, 0x3d25) +#define PR_XMT_SECURITY_ROLE_2 PROP_TAG(PT_BINARY, 0x3d26) +#define PR_XMT_SECURITY_ROLE_2_AS_XML PROP_TAG(PT_TSTRING, 0x3d26) +#define PR_XMT_SECURITY_ROLE_3 PROP_TAG(PT_BINARY, 0x3d27) +#define PR_XMT_SECURITY_ROLE_3_AS_XML PROP_TAG(PT_TSTRING, 0x3d27) +#define PR_XMT_SECURITY_ROLE_4 PROP_TAG(PT_BINARY, 0x3d28) +#define PR_XMT_SECURITY_ROLE_4_AS_XML PROP_TAG(PT_TSTRING, 0x3d28) +#define PR_XMT_SECURITY_ROLE_5 PROP_TAG(PT_BINARY, 0x3d29) +#define PR_XMT_SECURITY_ROLE_5_AS_XML PROP_TAG(PT_TSTRING, 0x3d29) +#define PR_XMT_SECURITY_ROLE_6 PROP_TAG(PT_BINARY, 0x3d2A) +#define PR_XMT_SECURITY_ROLE_6_AS_XML PROP_TAG(PT_TSTRING, 0x3d2A) +#define PR_XMT_SECURITY_ROLE_7 PROP_TAG(PT_BINARY, 0x3d2B) +#define PR_XMT_SECURITY_ROLE_7_AS_XML PROP_TAG(PT_TSTRING, 0x3d2B) +#define PR_XMT_SECURITY_ROLE_8 PROP_TAG(PT_BINARY, 0x3d2C) +#define PR_XMT_SECURITY_ROLE_8_AS_XML PROP_TAG(PT_TSTRING, 0x3d2C) +#define PR_NON_XMT_SECURITY_ROLE_1 PROP_TAG(PT_BINARY, 0x0E7C) +#define PR_NON_XMT_SECURITY_ROLE_1_AS_XML PROP_TAG(PT_TSTRING, 0x0E7C) +#define PR_NON_XMT_SECURITY_ROLE_2 PROP_TAG(PT_BINARY, 0x0E7D) +#define PR_NON_XMT_SECURITY_ROLE_2_AS_XML PROP_TAG(PT_TSTRING, 0x0E7D) +#define PR_NON_XMT_SECURITY_ROLE_3 PROP_TAG(PT_BINARY, 0x0E7E) +#define PR_NON_XMT_SECURITY_ROLE_3_AS_XML PROP_TAG(PT_TSTRING, 0x0E7E) +#define PR_NON_XMT_SECURITY_ROLE_4 PROP_TAG(PT_BINARY, 0x0E7F) +#define PR_NON_XMT_SECURITY_ROLE_4_AS_XML PROP_TAG(PT_TSTRING, 0x0E7F) +#define PR_NON_XMT_SECURITY_ROLE_5 PROP_TAG(PT_BINARY, 0x0E80) +#define PR_NON_XMT_SECURITY_ROLE_5_AS_XML PROP_TAG(PT_TSTRING, 0x0E80) +#define PR_NON_XMT_SECURITY_ROLE_6 PROP_TAG(PT_BINARY, 0x0E81) +#define PR_NON_XMT_SECURITY_ROLE_6_AS_XML PROP_TAG(PT_TSTRING, 0x0E81) +#define PR_NON_XMT_SECURITY_ROLE_7 PROP_TAG(PT_BINARY, 0x0E82) +#define PR_NON_XMT_SECURITY_ROLE_7_AS_XML PROP_TAG(PT_TSTRING, 0x0E82) +#define PR_NON_XMT_SECURITY_ROLE_8 PROP_TAG(PT_BINARY, 0x0E83) +#define PR_NON_XMT_SECURITY_ROLE_8_AS_XML PROP_TAG(PT_TSTRING, 0x0E83) /* Rules specifics */ // Property types -#define PT_SRESTRICTION ((ULONG) 0x00FD) -#define PT_ACTIONS ((ULONG) 0x00FE) +#define PT_SRESTRICTION ((ULONG)0x00FD) +#define PT_ACTIONS ((ULONG)0x00FE) /*----------------------------------------------------------------------- * PT_FILE_HANDLE: real data is in file specified by handle. @@ -1236,205 +1212,194 @@ typedef BYTE ROLESCOPE; * is not supported for outside calls. *-----------------------------------------------------------------------*/ -#define PT_FILE_HANDLE ((ULONG) 0x0103) -#define PT_FILE_EA ((ULONG) 0x0104) -#define PT_VIRTUAL ((ULONG) 0x0105) - -#define FVirtualProp(ptag) (PROP_TYPE(ptag) == PT_VIRTUAL) -#define FFileHandleProp(ptag) (PROP_TYPE(ptag) == PT_FILE_HANDLE || PROP_TYPE(ptag) == PT_FILE_EA) - -//Properties in rule table -#define PR_RULE_ID PROP_TAG(PT_I8, pidSpecialMin+0x04) -#define PR_RULE_IDS PROP_TAG(PT_BINARY, pidSpecialMin+0x05) -#define PR_RULE_SEQUENCE PROP_TAG(PT_LONG, pidSpecialMin+0x06) -#define PR_RULE_STATE PROP_TAG(PT_LONG, pidSpecialMin+0x07) -#define PR_RULE_USER_FLAGS PROP_TAG(PT_LONG, pidSpecialMin+0x08) -#define PR_RULE_CONDITION PROP_TAG(PT_SRESTRICTION, pidSpecialMin+0x09) -#define PR_RULE_ACTIONS PROP_TAG(PT_ACTIONS, pidSpecialMin+0x10) -#define PR_RULE_PROVIDER PROP_TAG(PT_STRING8, pidSpecialMin+0x11) -#define PR_RULE_NAME PROP_TAG(PT_TSTRING, pidSpecialMin+0x12) -#define PR_RULE_LEVEL PROP_TAG(PT_LONG, pidSpecialMin+0x13) -#define PR_RULE_PROVIDER_DATA PROP_TAG(PT_BINARY, pidSpecialMin+0x14) - -#define PR_EXTENDED_RULE_ACTIONS PROP_TAG(PT_BINARY, pidStoreNonTransMin+0x59) -#define PR_EXTENDED_RULE_CONDITION PROP_TAG(PT_BINARY, pidStoreNonTransMin+0x5a) -#define PR_EXTENDED_RULE_SIZE_LIMIT PROP_TAG(PT_LONG, pidStoreNonTransMin+0x5b) +#define PT_FILE_HANDLE ((ULONG)0x0103) +#define PT_FILE_EA ((ULONG)0x0104) +#define PT_VIRTUAL ((ULONG)0x0105) + +#define FVirtualProp(ptag) (PROP_TYPE(ptag) == PT_VIRTUAL) +#define FFileHandleProp(ptag) (PROP_TYPE(ptag) == PT_FILE_HANDLE || PROP_TYPE(ptag) == PT_FILE_EA) + +// Properties in rule table +#define PR_RULE_ID PROP_TAG(PT_I8, pidSpecialMin + 0x04) +#define PR_RULE_IDS PROP_TAG(PT_BINARY, pidSpecialMin + 0x05) +#define PR_RULE_SEQUENCE PROP_TAG(PT_LONG, pidSpecialMin + 0x06) +#define PR_RULE_STATE PROP_TAG(PT_LONG, pidSpecialMin + 0x07) +#define PR_RULE_USER_FLAGS PROP_TAG(PT_LONG, pidSpecialMin + 0x08) +#define PR_RULE_CONDITION PROP_TAG(PT_SRESTRICTION, pidSpecialMin + 0x09) +#define PR_RULE_ACTIONS PROP_TAG(PT_ACTIONS, pidSpecialMin + 0x10) +#define PR_RULE_PROVIDER PROP_TAG(PT_STRING8, pidSpecialMin + 0x11) +#define PR_RULE_NAME PROP_TAG(PT_TSTRING, pidSpecialMin + 0x12) +#define PR_RULE_LEVEL PROP_TAG(PT_LONG, pidSpecialMin + 0x13) +#define PR_RULE_PROVIDER_DATA PROP_TAG(PT_BINARY, pidSpecialMin + 0x14) + +#define PR_EXTENDED_RULE_ACTIONS PROP_TAG(PT_BINARY, pidStoreNonTransMin + 0x59) +#define PR_EXTENDED_RULE_CONDITION PROP_TAG(PT_BINARY, pidStoreNonTransMin + 0x5a) +#define PR_EXTENDED_RULE_SIZE_LIMIT PROP_TAG(PT_LONG, pidStoreNonTransMin + 0x5b) // moved to ptag.h (scottno) - still needed for 2.27 upgrader // #define PR_RULE_VERSION PROP_TAG( PT_I2, pidSpecialMin+0x1D) -//PR_STATE property values -#define ST_DISABLED 0x0000 -#define ST_ENABLED 0x0001 -#define ST_ERROR 0x0002 -#define ST_ONLY_WHEN_OOF 0x0004 -#define ST_KEEP_OOF_HIST 0x0008 -#define ST_EXIT_LEVEL 0x0010 -#define ST_SKIP_IF_SCL_IS_SAFE 0x0020 -#define ST_RULE_PARSE_ERROR 0x0040 -#define ST_CLEAR_OOF_HIST 0x80000000 +// PR_STATE property values +#define ST_DISABLED 0x0000 +#define ST_ENABLED 0x0001 +#define ST_ERROR 0x0002 +#define ST_ONLY_WHEN_OOF 0x0004 +#define ST_KEEP_OOF_HIST 0x0008 +#define ST_EXIT_LEVEL 0x0010 +#define ST_SKIP_IF_SCL_IS_SAFE 0x0020 +#define ST_RULE_PARSE_ERROR 0x0040 +#define ST_CLEAR_OOF_HIST 0x80000000 -//Empty restriction -#define NULL_RESTRICTION 0xff +// Empty restriction +#define NULL_RESTRICTION 0xff // special RELOP for Member of DL -#define RELOP_MEMBER_OF_DL 100 - -//Action types -typedef enum -{ - OP_MOVE = 1, - OP_COPY, - OP_REPLY, - OP_OOF_REPLY, - OP_DEFER_ACTION, - OP_BOUNCE, - OP_FORWARD, - OP_DELEGATE, - OP_TAG, - OP_DELETE, - OP_MARK_AS_READ, +#define RELOP_MEMBER_OF_DL 100 + +// Action types +typedef enum { + OP_MOVE = 1, + OP_COPY, + OP_REPLY, + OP_OOF_REPLY, + OP_DEFER_ACTION, + OP_BOUNCE, + OP_FORWARD, + OP_DELEGATE, + OP_TAG, + OP_DELETE, + OP_MARK_AS_READ, } ACTTYPE; // provider name for moderator rules -#define szProviderModeratorRule "MSFT:MR" -#define wszProviderModeratorRule L"MSFT:MR" +#define szProviderModeratorRule "MSFT:MR" +#define wszProviderModeratorRule L"MSFT:MR" // action flavors // for OP_REPLY -#define DO_NOT_SEND_TO_ORIGINATOR 1 -#define STOCK_REPLY_TEMPLATE 2 +#define DO_NOT_SEND_TO_ORIGINATOR 1 +#define STOCK_REPLY_TEMPLATE 2 // for OP_FORWARD -#define FWD_PRESERVE_SENDER 1 -#define FWD_DO_NOT_MUNGE_MSG 2 -#define FWD_AS_ATTACHMENT 4 - -//scBounceCode values -#define BOUNCE_MESSAGE_SIZE_TOO_LARGE (SCODE) MAPI_DIAG_LENGTH_CONSTRAINT_VIOLATD -#define BOUNCE_FORMS_MISMATCH (SCODE) MAPI_DIAG_RENDITION_UNSUPPORTED -#define BOUNCE_ACCESS_DENIED (SCODE) MAPI_DIAG_MAIL_REFUSED - -//Message class prefix for Reply and OOF Reply templates -#define szReplyTemplateMsgClassPrefix "IPM.Note.Rules.ReplyTemplate." -#define szOofTemplateMsgClassPrefix "IPM.Note.Rules.OofTemplate." - -//Action structure -typedef struct _action -{ - ACTTYPE acttype; - - // to indicate which flavor of the action. - ULONG ulActionFlavor; - - // Action restriction - // currently unused and must be set to NULL - LPSRestriction lpRes; - - // currently unused and must be set to NULL. - LPSPropTagArray lpPropTagArray; - - // User defined flags - ULONG ulFlags; - - // padding to align the union on 8 byte boundary - ULONG dwAlignPad; - - union - { - // used for OP_MOVE and OP_COPY actions - struct - { - ULONG cbStoreEntryId; - LPENTRYID lpStoreEntryId; - ULONG cbFldEntryId; - LPENTRYID lpFldEntryId; - } actMoveCopy; - - // used for OP_REPLY and OP_OOF_REPLY actions - struct - { - ULONG cbEntryId; - LPENTRYID lpEntryId; - GUID guidReplyTemplate; - } actReply; - - // used for OP_DEFER_ACTION action - struct - { - ULONG cbData; - BYTE *pbData; - } actDeferAction; - - // Error code to set for OP_BOUNCE action - SCODE scBounceCode; - - // list of address for OP_FORWARD and OP_DELEGATE action - LPADRLIST lpadrlist; - - // prop value for OP_TAG action - SPropValue propTag; - }; -} ACTION, FAR * LPACTION; +#define FWD_PRESERVE_SENDER 1 +#define FWD_DO_NOT_MUNGE_MSG 2 +#define FWD_AS_ATTACHMENT 4 + +// scBounceCode values +#define BOUNCE_MESSAGE_SIZE_TOO_LARGE (SCODE) MAPI_DIAG_LENGTH_CONSTRAINT_VIOLATD +#define BOUNCE_FORMS_MISMATCH (SCODE) MAPI_DIAG_RENDITION_UNSUPPORTED +#define BOUNCE_ACCESS_DENIED (SCODE) MAPI_DIAG_MAIL_REFUSED + +// Message class prefix for Reply and OOF Reply templates +#define szReplyTemplateMsgClassPrefix "IPM.Note.Rules.ReplyTemplate." +#define szOofTemplateMsgClassPrefix "IPM.Note.Rules.OofTemplate." + +// Action structure +typedef struct _action { + ACTTYPE acttype; + + // to indicate which flavor of the action. + ULONG ulActionFlavor; + + // Action restriction + // currently unused and must be set to NULL + LPSRestriction lpRes; + + // currently unused and must be set to NULL. + LPSPropTagArray lpPropTagArray; + + // User defined flags + ULONG ulFlags; + + // padding to align the union on 8 byte boundary + ULONG dwAlignPad; + + union { + // used for OP_MOVE and OP_COPY actions + struct { + ULONG cbStoreEntryId; + LPENTRYID lpStoreEntryId; + ULONG cbFldEntryId; + LPENTRYID lpFldEntryId; + } actMoveCopy; + + // used for OP_REPLY and OP_OOF_REPLY actions + struct { + ULONG cbEntryId; + LPENTRYID lpEntryId; + GUID guidReplyTemplate; + } actReply; + + // used for OP_DEFER_ACTION action + struct { + ULONG cbData; + BYTE *pbData; + } actDeferAction; + + // Error code to set for OP_BOUNCE action + SCODE scBounceCode; + + // list of address for OP_FORWARD and OP_DELEGATE action + LPADRLIST lpadrlist; + + // prop value for OP_TAG action + SPropValue propTag; + }; +} ACTION, FAR *LPACTION; // Rules version -#define EDK_RULES_VERSION 1 - -//Array of actions -typedef struct _actions -{ - ULONG ulVersion; // use the #define above - UINT cActions; - LPACTION lpAction; +#define EDK_RULES_VERSION 1 + +// Array of actions +typedef struct _actions { + ULONG ulVersion; // use the #define above + UINT cActions; + LPACTION lpAction; } ACTIONS; #ifdef __cplusplus extern "C" { #endif -HRESULT WINAPI -HrSerializeSRestriction(IMAPIProp * pprop, LPSRestriction prest, BYTE ** ppbRest, ULONG * pcbRest); +HRESULT WINAPI HrSerializeSRestriction(IMAPIProp *pprop, LPSRestriction prest, BYTE **ppbRest, ULONG *pcbRest); -HRESULT WINAPI -HrDeserializeSRestriction(IMAPIProp * pprop, BYTE * pbRest, ULONG cbRest, LPSRestriction * pprest); +HRESULT WINAPI HrDeserializeSRestriction(IMAPIProp *pprop, BYTE *pbRest, ULONG cbRest, LPSRestriction *pprest); -HRESULT WINAPI -HrSerializeActions(IMAPIProp * pprop, ACTIONS * pActions, BYTE ** ppbActions, ULONG * pcbActions); +HRESULT WINAPI HrSerializeActions(IMAPIProp *pprop, ACTIONS *pActions, BYTE **ppbActions, ULONG *pcbActions); -HRESULT WINAPI -HrDeserializeActions(IMAPIProp * pprop, BYTE * pbActions, ULONG cbActions, ACTIONS ** ppActions); +HRESULT WINAPI HrDeserializeActions(IMAPIProp *pprop, BYTE *pbActions, ULONG cbActions, ACTIONS **ppActions); #ifdef __cplusplus -} // extern "C" +} // extern "C" #endif // message class definitions for Deferred Action and Deffered Error messages -#define szDamMsgClass "IPC.Microsoft Exchange 4.0.Deferred Action" -#define szDemMsgClass "IPC.Microsoft Exchange 4.0.Deferred Error" +#define szDamMsgClass "IPC.Microsoft Exchange 4.0.Deferred Action" +#define szDemMsgClass "IPC.Microsoft Exchange 4.0.Deferred Error" -#define szExRuleMsgClass "IPM.ExtendedRule.Message" -#define wszExRuleMsgClass L"IPM.ExtendedRule.Message" +#define szExRuleMsgClass "IPM.ExtendedRule.Message" +#define wszExRuleMsgClass L"IPM.ExtendedRule.Message" /* * Rule error codes * Values for PR_RULE_ERROR */ -#define RULE_ERR_UNKNOWN 1 //general catchall error -#define RULE_ERR_LOAD 2 //unable to load folder rules -#define RULE_ERR_DELIVERY 3 //unable to deliver message temporarily -#define RULE_ERR_PARSING 4 //error while parsing -#define RULE_ERR_CREATE_DAE 5 //error creating DAE message -#define RULE_ERR_NO_FOLDER 6 //folder to move/copy doesn't exist -#define RULE_ERR_NO_RIGHTS 7 //no rights to move/copy into folder -#define RULE_ERR_CREATE_DAM 8 //error creating DAM -#define RULE_ERR_NO_SENDAS 9 //can not send as another user -#define RULE_ERR_NO_TEMPLATE 10 //reply template is missing -#define RULE_ERR_EXECUTION 11 //error in rule execution -#define RULE_ERR_QUOTA_EXCEEDED 12 //mailbox quota size exceeded -#define RULE_ERR_TOO_MANY_RECIPS 13 //number of recips exceded upper limit - -#define RULE_ERR_FIRST RULE_ERR_UNKNOWN -#define RULE_ERR_LAST RULE_ERR_TOO_MANY_RECIPS +#define RULE_ERR_UNKNOWN 1 // general catchall error +#define RULE_ERR_LOAD 2 // unable to load folder rules +#define RULE_ERR_DELIVERY 3 // unable to deliver message temporarily +#define RULE_ERR_PARSING 4 // error while parsing +#define RULE_ERR_CREATE_DAE 5 // error creating DAE message +#define RULE_ERR_NO_FOLDER 6 // folder to move/copy doesn't exist +#define RULE_ERR_NO_RIGHTS 7 // no rights to move/copy into folder +#define RULE_ERR_CREATE_DAM 8 // error creating DAM +#define RULE_ERR_NO_SENDAS 9 // can not send as another user +#define RULE_ERR_NO_TEMPLATE 10 // reply template is missing +#define RULE_ERR_EXECUTION 11 // error in rule execution +#define RULE_ERR_QUOTA_EXCEEDED 12 // mailbox quota size exceeded +#define RULE_ERR_TOO_MANY_RECIPS 13 // number of recips exceded upper limit + +#define RULE_ERR_FIRST RULE_ERR_UNKNOWN +#define RULE_ERR_LAST RULE_ERR_TOO_MANY_RECIPS /*------------------------------------------------------------------------ * @@ -1444,22 +1409,17 @@ HrDeserializeActions(IMAPIProp * pprop, BYTE * pbActions, ULONG cbActions, ACTIO * *-----------------------------------------------------------------------*/ -#define EXCHANGE_IEXCHANGERULEACTION_METHODS(IPURE) \ - MAPIMETHOD(ActionCount) \ - (THIS_ ULONG FAR * lpcActions) IPURE; \ - MAPIMETHOD(GetAction) \ - (THIS_ ULONG ulActionNumber, \ - LARGE_INTEGER * lpruleid, \ - LPACTION FAR * lppAction) IPURE; - -#undef INTERFACE -#define INTERFACE IExchangeRuleAction -DECLARE_MAPI_INTERFACE_(IExchangeRuleAction, IUnknown) -{ - MAPI_IUNKNOWN_METHODS(PURE) - EXCHANGE_IEXCHANGERULEACTION_METHODS(PURE) -}; -#undef IMPL +#define EXCHANGE_IEXCHANGERULEACTION_METHODS(IPURE) \ + MAPIMETHOD(ActionCount) \ + (THIS_ ULONG FAR * lpcActions) IPURE; \ + MAPIMETHOD(GetAction) \ + (THIS_ ULONG ulActionNumber, LARGE_INTEGER * lpruleid, LPACTION FAR * lppAction) IPURE; + +#undef INTERFACE +#define INTERFACE IExchangeRuleAction +DECLARE_MAPI_INTERFACE_(IExchangeRuleAction, + IUnknown){MAPI_IUNKNOWN_METHODS(PURE) EXCHANGE_IEXCHANGERULEACTION_METHODS(PURE)}; +#undef IMPL #define IMPL DECLARE_MAPI_INTERFACE_PTR(IExchangeRuleAction, LPEXCHANGERULEACTION); @@ -1472,43 +1432,26 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeRuleAction, LPEXCHANGERULEACTION); * *-----------------------------------------------------------------------*/ -#define EXCHANGE_IEXCHANGEMANAGESTORE_METHODS(IPURE) \ - MAPIMETHOD(CreateStoreEntryID) \ - (THIS_ LPSTR lpszMsgStoreDN, \ - LPSTR lpszMailboxDN, \ - ULONG ulFlags, \ - ULONG FAR * lpcbEntryID, \ - LPENTRYID FAR * lppEntryID) IPURE; \ - MAPIMETHOD(EntryIDFromSourceKey) \ - (THIS_ ULONG cFolderKeySize, \ - BYTE FAR * lpFolderSourceKey, \ - ULONG cMessageKeySize, \ - BYTE FAR * lpMessageSourceKey, \ - ULONG FAR * lpcbEntryID, \ - LPENTRYID FAR * lppEntryID) IPURE; \ - MAPIMETHOD(GetRights) \ - (THIS_ ULONG cbUserEntryID, \ - LPENTRYID lpUserEntryID, \ - ULONG cbEntryID, \ - LPENTRYID lpEntryID, \ - ULONG FAR * lpulRights) IPURE; \ - MAPIMETHOD(GetMailboxTable) \ - (THIS_ LPSTR lpszServerName, \ - LPMAPITABLE FAR * lppTable, \ - ULONG ulFlags) IPURE; \ - MAPIMETHOD(GetPublicFolderTable) \ - (THIS_ LPSTR lpszServerName, \ - LPMAPITABLE FAR * lppTable, \ - ULONG ulFlags) IPURE; - -#undef INTERFACE -#define INTERFACE IExchangeManageStore -DECLARE_MAPI_INTERFACE_(IExchangeManageStore, IUnknown) -{ - MAPI_IUNKNOWN_METHODS(PURE) - EXCHANGE_IEXCHANGEMANAGESTORE_METHODS(PURE) -}; -#undef IMPL +#define EXCHANGE_IEXCHANGEMANAGESTORE_METHODS(IPURE) \ + MAPIMETHOD(CreateStoreEntryID) \ + (THIS_ LPSTR lpszMsgStoreDN, LPSTR lpszMailboxDN, ULONG ulFlags, ULONG FAR * lpcbEntryID, \ + LPENTRYID FAR * lppEntryID) IPURE; \ + MAPIMETHOD(EntryIDFromSourceKey) \ + (THIS_ ULONG cFolderKeySize, BYTE FAR * lpFolderSourceKey, ULONG cMessageKeySize, BYTE FAR * lpMessageSourceKey, \ + ULONG FAR * lpcbEntryID, LPENTRYID FAR * lppEntryID) IPURE; \ + MAPIMETHOD(GetRights) \ + (THIS_ ULONG cbUserEntryID, LPENTRYID lpUserEntryID, ULONG cbEntryID, LPENTRYID lpEntryID, ULONG FAR * lpulRights) \ + IPURE; \ + MAPIMETHOD(GetMailboxTable) \ + (THIS_ LPSTR lpszServerName, LPMAPITABLE FAR * lppTable, ULONG ulFlags) IPURE; \ + MAPIMETHOD(GetPublicFolderTable) \ + (THIS_ LPSTR lpszServerName, LPMAPITABLE FAR * lppTable, ULONG ulFlags) IPURE; + +#undef INTERFACE +#define INTERFACE IExchangeManageStore +DECLARE_MAPI_INTERFACE_(IExchangeManageStore, + IUnknown){MAPI_IUNKNOWN_METHODS(PURE) EXCHANGE_IEXCHANGEMANAGESTORE_METHODS(PURE)}; +#undef IMPL #define IMPL DECLARE_MAPI_INTERFACE_PTR(IExchangeManageStore, LPEXCHANGEMANAGESTORE); @@ -1521,26 +1464,20 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeManageStore, LPEXCHANGEMANAGESTORE); * *-----------------------------------------------------------------------*/ -#define EXCHANGE_IEXCHANGEMANAGESTORE2_METHODS(IPURE) \ - MAPIMETHOD(CreateNewsgroupNameEntryID) \ - (THIS_ LPSTR lpszNewsgroupName, \ - ULONG FAR * lpcbEntryID, \ - LPENTRYID FAR * lppEntryID) IPURE; - -#undef INTERFACE -#define INTERFACE IExchangeManageStore2 -DECLARE_MAPI_INTERFACE_(IExchangeManageStore2, IUnknown) -{ - MAPI_IUNKNOWN_METHODS(PURE) - EXCHANGE_IEXCHANGEMANAGESTORE_METHODS(PURE) - EXCHANGE_IEXCHANGEMANAGESTORE2_METHODS(PURE) -}; -#undef IMPL +#define EXCHANGE_IEXCHANGEMANAGESTORE2_METHODS(IPURE) \ + MAPIMETHOD(CreateNewsgroupNameEntryID) \ + (THIS_ LPSTR lpszNewsgroupName, ULONG FAR * lpcbEntryID, LPENTRYID FAR * lppEntryID) IPURE; + +#undef INTERFACE +#define INTERFACE IExchangeManageStore2 +DECLARE_MAPI_INTERFACE_(IExchangeManageStore2, IUnknown){MAPI_IUNKNOWN_METHODS(PURE) + EXCHANGE_IEXCHANGEMANAGESTORE_METHODS(PURE) + EXCHANGE_IEXCHANGEMANAGESTORE2_METHODS(PURE)}; +#undef IMPL #define IMPL DECLARE_MAPI_INTERFACE_PTR(IExchangeManageStore2, LPEXCHANGEMANAGESTORE2); - /*------------------------------------------------------------------------ * * "IExchangeManageStore3" Interface Declaration @@ -1549,28 +1486,20 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeManageStore2, LPEXCHANGEMANAGESTORE2); * *-----------------------------------------------------------------------*/ -#define EXCHANGE_IEXCHANGEMANAGESTORE3_METHODS(IPURE) \ - MAPIMETHOD(GetMailboxTableOffset) \ - (THIS_ LPSTR lpszServerName, \ - LPMAPITABLE FAR * lppTable, \ - ULONG ulFlags, \ - UINT uOffset) IPURE; - -#undef INTERFACE -#define INTERFACE IExchangeManageStore3 -DECLARE_MAPI_INTERFACE_(IExchangeManageStore3, IUnknown) -{ - MAPI_IUNKNOWN_METHODS(PURE) - EXCHANGE_IEXCHANGEMANAGESTORE_METHODS(PURE) - EXCHANGE_IEXCHANGEMANAGESTORE2_METHODS(PURE) - EXCHANGE_IEXCHANGEMANAGESTORE3_METHODS(PURE) -}; -#undef IMPL +#define EXCHANGE_IEXCHANGEMANAGESTORE3_METHODS(IPURE) \ + MAPIMETHOD(GetMailboxTableOffset) \ + (THIS_ LPSTR lpszServerName, LPMAPITABLE FAR * lppTable, ULONG ulFlags, UINT uOffset) IPURE; + +#undef INTERFACE +#define INTERFACE IExchangeManageStore3 +DECLARE_MAPI_INTERFACE_(IExchangeManageStore3, IUnknown){ + MAPI_IUNKNOWN_METHODS(PURE) EXCHANGE_IEXCHANGEMANAGESTORE_METHODS(PURE) EXCHANGE_IEXCHANGEMANAGESTORE2_METHODS(PURE) + EXCHANGE_IEXCHANGEMANAGESTORE3_METHODS(PURE)}; +#undef IMPL #define IMPL DECLARE_MAPI_INTERFACE_PTR(IExchangeManageStore3, LPEXCHANGEMANAGESTORE3); - /*------------------------------------------------------------------------ * * "IExchangeManageStore4" Interface Declaration @@ -1579,29 +1508,20 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeManageStore3, LPEXCHANGEMANAGESTORE3); * *-----------------------------------------------------------------------*/ -#define EXCHANGE_IEXCHANGEMANAGESTORE4_METHODS(IPURE) \ - MAPIMETHOD(GetPublicFolderTableOffset) \ - (THIS_ LPSTR lpszServerName, \ - LPMAPITABLE FAR * lppTable, \ - ULONG ulFlags, \ - UINT uOffset) IPURE; - -#undef INTERFACE -#define INTERFACE IExchangeManageStore4 -DECLARE_MAPI_INTERFACE_(IExchangeManageStore4, IUnknown) -{ - MAPI_IUNKNOWN_METHODS(PURE) - EXCHANGE_IEXCHANGEMANAGESTORE_METHODS(PURE) - EXCHANGE_IEXCHANGEMANAGESTORE2_METHODS(PURE) - EXCHANGE_IEXCHANGEMANAGESTORE3_METHODS(PURE) - EXCHANGE_IEXCHANGEMANAGESTORE4_METHODS(PURE) -}; -#undef IMPL +#define EXCHANGE_IEXCHANGEMANAGESTORE4_METHODS(IPURE) \ + MAPIMETHOD(GetPublicFolderTableOffset) \ + (THIS_ LPSTR lpszServerName, LPMAPITABLE FAR * lppTable, ULONG ulFlags, UINT uOffset) IPURE; + +#undef INTERFACE +#define INTERFACE IExchangeManageStore4 +DECLARE_MAPI_INTERFACE_(IExchangeManageStore4, IUnknown){ + MAPI_IUNKNOWN_METHODS(PURE) EXCHANGE_IEXCHANGEMANAGESTORE_METHODS(PURE) EXCHANGE_IEXCHANGEMANAGESTORE2_METHODS(PURE) + EXCHANGE_IEXCHANGEMANAGESTORE3_METHODS(PURE) EXCHANGE_IEXCHANGEMANAGESTORE4_METHODS(PURE)}; +#undef IMPL #define IMPL DECLARE_MAPI_INTERFACE_PTR(IExchangeManageStore4, LPEXCHANGEMANAGESTORE4); - /*------------------------------------------------------------------------ * * "IExchangeNntpNewsfeed" Interface Declaration @@ -1610,110 +1530,101 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeManageStore4, LPEXCHANGEMANAGESTORE4); * *-----------------------------------------------------------------------*/ -#define EXCHANGE_IEXCHANGENNTPNEWSFEED_METHODS(IPURE) \ - MAPIMETHOD(Configure) \ - (THIS_ LPSTR lpszNewsfeedDN, \ - ULONG cValues, \ - LPSPropValue lpIMailPropArray) IPURE; \ - MAPIMETHOD(CheckMsgIds) \ - (THIS_ LPSTR lpszMsgIds, \ - ULONG FAR * lpcfWanted, \ - BYTE FAR ** lppfWanted) IPURE; \ - MAPIMETHOD(OpenArticleStream) \ - (THIS_ LPSTREAM FAR * lppStream) IPURE; \ - - -#undef INTERFACE -#define INTERFACE IExchangeNntpNewsfeed -DECLARE_MAPI_INTERFACE_(IExchangeNntpNewsfeed, IUnknown) -{ - MAPI_IUNKNOWN_METHODS(PURE) - EXCHANGE_IEXCHANGENNTPNEWSFEED_METHODS(PURE) -}; -#undef IMPL +#define EXCHANGE_IEXCHANGENNTPNEWSFEED_METHODS(IPURE) \ + MAPIMETHOD(Configure) \ + (THIS_ LPSTR lpszNewsfeedDN, ULONG cValues, LPSPropValue lpIMailPropArray) IPURE; \ + MAPIMETHOD(CheckMsgIds) \ + (THIS_ LPSTR lpszMsgIds, ULONG FAR * lpcfWanted, BYTE FAR * *lppfWanted) IPURE; \ + MAPIMETHOD(OpenArticleStream) \ + (THIS_ LPSTREAM FAR * lppStream) IPURE; + +#undef INTERFACE +#define INTERFACE IExchangeNntpNewsfeed +DECLARE_MAPI_INTERFACE_(IExchangeNntpNewsfeed, + IUnknown){MAPI_IUNKNOWN_METHODS(PURE) EXCHANGE_IEXCHANGENNTPNEWSFEED_METHODS(PURE)}; +#undef IMPL #define IMPL DECLARE_MAPI_INTERFACE_PTR(IExchangeNntpNewsfeed, LPEXCHANGENNTPNEWSFEED); // Properties for GetMailboxTable -#define PR_NT_USER_NAME PROP_TAG(PT_TSTRING, pidAdminMin+0x10) +#define PR_NT_USER_NAME PROP_TAG(PT_TSTRING, pidAdminMin + 0x10) // // PR_LOCALE_ID definition has been moved down and combined with other // locale-specific properties. It is still being returned through the // mailbox table. // -//#define PR_LOCALE_ID PROP_TAG( PT_LONG, pidAdminMin+0x11 ) -#define PR_LAST_LOGON_TIME PROP_TAG(PT_SYSTIME, pidAdminMin+0x12 ) -#define PR_LAST_LOGOFF_TIME PROP_TAG(PT_SYSTIME, pidAdminMin+0x13 ) -#define PR_STORAGE_LIMIT_INFORMATION PROP_TAG(PT_LONG, pidAdminMin+0x14 ) +// #define PR_LOCALE_ID PROP_TAG( PT_LONG, pidAdminMin+0x11 ) +#define PR_LAST_LOGON_TIME PROP_TAG(PT_SYSTIME, pidAdminMin + 0x12) +#define PR_LAST_LOGOFF_TIME PROP_TAG(PT_SYSTIME, pidAdminMin + 0x13) +#define PR_STORAGE_LIMIT_INFORMATION PROP_TAG(PT_LONG, pidAdminMin + 0x14) // property on disabling message read (unread) receipt // reusing Folders table property (pidAdminMin+0x15) -#define PR_INTERNET_MDNS PROP_TAG(PT_BOOLEAN, PROP_ID(PR_NEWSGROUP_COMPONENT)) +#define PR_INTERNET_MDNS PROP_TAG(PT_BOOLEAN, PROP_ID(PR_NEWSGROUP_COMPONENT)) // properties for mailbox quota info - reusing properties from folder table - // folder pathname, owner, and contacts re-used. -#define PR_QUOTA_WARNING_THRESHOLD PROP_TAG(PT_LONG, pidAdminMin+0x91) -#define PR_QUOTA_SEND_THRESHOLD PROP_TAG(PT_LONG, pidAdminMin+0x92) -#define PR_QUOTA_RECEIVE_THRESHOLD PROP_TAG(PT_LONG, pidAdminMin+0x93) - +#define PR_QUOTA_WARNING_THRESHOLD PROP_TAG(PT_LONG, pidAdminMin + 0x91) +#define PR_QUOTA_SEND_THRESHOLD PROP_TAG(PT_LONG, pidAdminMin + 0x92) +#define PR_QUOTA_RECEIVE_THRESHOLD PROP_TAG(PT_LONG, pidAdminMin + 0x93) // Properties for GetPublicFolderTable -#define PR_FOLDER_FLAGS PROP_TAG(PT_LONG, pidAdminMin+0x18) -#define PR_LAST_ACCESS_TIME PROP_TAG(PT_SYSTIME, pidAdminMin+0x19) -#define PR_RESTRICTION_COUNT PROP_TAG(PT_LONG, pidAdminMin+0x1A) -#define PR_CATEG_COUNT PROP_TAG(PT_LONG, pidAdminMin+0x1B) -#define PR_CACHED_COLUMN_COUNT PROP_TAG(PT_LONG, pidAdminMin+0x1C) -#define PR_NORMAL_MSG_W_ATTACH_COUNT PROP_TAG(PT_LONG, pidAdminMin+0x1D) -#define PR_ASSOC_MSG_W_ATTACH_COUNT PROP_TAG(PT_LONG, pidAdminMin+0x1E) -#define PR_RECIPIENT_ON_NORMAL_MSG_COUNT PROP_TAG(PT_LONG, pidAdminMin+0x1F) -#define PR_RECIPIENT_ON_ASSOC_MSG_COUNT PROP_TAG(PT_LONG, pidAdminMin+0x20) -#define PR_ATTACH_ON_NORMAL_MSG_COUNT PROP_TAG(PT_LONG, pidAdminMin+0x21) -#define PR_ATTACH_ON_ASSOC_MSG_COUNT PROP_TAG(PT_LONG, pidAdminMin+0x22) -#define PR_NORMAL_MESSAGE_SIZE PROP_TAG(PT_LONG, pidAdminMin+0x23) -#define PR_NORMAL_MESSAGE_SIZE_EXTENDED PROP_TAG(PT_I8, pidAdminMin+0x23) -#define PR_ASSOC_MESSAGE_SIZE PROP_TAG(PT_LONG, pidAdminMin+0x24) -#define PR_ASSOC_MESSAGE_SIZE_EXTENDED PROP_TAG(PT_I8, pidAdminMin+0x24) -#define PR_FOLDER_PATHNAME PROP_TAG(PT_TSTRING, pidAdminMin+0x25) -#define PR_OWNER_COUNT PROP_TAG(PT_LONG, pidAdminMin+0x26) -#define PR_CONTACT_COUNT PROP_TAG(PT_LONG, pidAdminMin+0x27) +#define PR_FOLDER_FLAGS PROP_TAG(PT_LONG, pidAdminMin + 0x18) +#define PR_LAST_ACCESS_TIME PROP_TAG(PT_SYSTIME, pidAdminMin + 0x19) +#define PR_RESTRICTION_COUNT PROP_TAG(PT_LONG, pidAdminMin + 0x1A) +#define PR_CATEG_COUNT PROP_TAG(PT_LONG, pidAdminMin + 0x1B) +#define PR_CACHED_COLUMN_COUNT PROP_TAG(PT_LONG, pidAdminMin + 0x1C) +#define PR_NORMAL_MSG_W_ATTACH_COUNT PROP_TAG(PT_LONG, pidAdminMin + 0x1D) +#define PR_ASSOC_MSG_W_ATTACH_COUNT PROP_TAG(PT_LONG, pidAdminMin + 0x1E) +#define PR_RECIPIENT_ON_NORMAL_MSG_COUNT PROP_TAG(PT_LONG, pidAdminMin + 0x1F) +#define PR_RECIPIENT_ON_ASSOC_MSG_COUNT PROP_TAG(PT_LONG, pidAdminMin + 0x20) +#define PR_ATTACH_ON_NORMAL_MSG_COUNT PROP_TAG(PT_LONG, pidAdminMin + 0x21) +#define PR_ATTACH_ON_ASSOC_MSG_COUNT PROP_TAG(PT_LONG, pidAdminMin + 0x22) +#define PR_NORMAL_MESSAGE_SIZE PROP_TAG(PT_LONG, pidAdminMin + 0x23) +#define PR_NORMAL_MESSAGE_SIZE_EXTENDED PROP_TAG(PT_I8, pidAdminMin + 0x23) +#define PR_ASSOC_MESSAGE_SIZE PROP_TAG(PT_LONG, pidAdminMin + 0x24) +#define PR_ASSOC_MESSAGE_SIZE_EXTENDED PROP_TAG(PT_I8, pidAdminMin + 0x24) +#define PR_FOLDER_PATHNAME PROP_TAG(PT_TSTRING, pidAdminMin + 0x25) +#define PR_OWNER_COUNT PROP_TAG(PT_LONG, pidAdminMin + 0x26) +#define PR_CONTACT_COUNT PROP_TAG(PT_LONG, pidAdminMin + 0x27) /* the absolute size limitation of a public folder */ -#define PR_PF_OVER_HARD_QUOTA_LIMIT PROP_TAG(PT_LONG, pidAdminMin+0x91) +#define PR_PF_OVER_HARD_QUOTA_LIMIT PROP_TAG(PT_LONG, pidAdminMin + 0x91) /* the size limit of a message in a public folder */ -#define PR_PF_MSG_SIZE_LIMIT PROP_TAG(PT_LONG, pidAdminMin+0x92) +#define PR_PF_MSG_SIZE_LIMIT PROP_TAG(PT_LONG, pidAdminMin + 0x92) // Do not inherit expiry settings from the MDB wide settings and instead use folder specific ones // (if folder specific is not set, it will still not get from MDB and remain with no expiry at all) -#define PR_PF_DISALLOW_MDB_WIDE_EXPIRY PROP_TAG(PT_BOOLEAN, pidAdminMin+0x93) +#define PR_PF_DISALLOW_MDB_WIDE_EXPIRY PROP_TAG(PT_BOOLEAN, pidAdminMin + 0x93) // Locale-specific properties -#define PR_LOCALE_ID PROP_TAG(PT_LONG, pidAdminMin+0x11) -#define PR_CODE_PAGE_ID PROP_TAG(PT_LONG, pidAdminMin+0x33) -#define PR_SORT_LOCALE_ID PROP_TAG(PT_LONG, pidAdminMin+0x75) +#define PR_LOCALE_ID PROP_TAG(PT_LONG, pidAdminMin + 0x11) +#define PR_CODE_PAGE_ID PROP_TAG(PT_LONG, pidAdminMin + 0x33) +#define PR_SORT_LOCALE_ID PROP_TAG(PT_LONG, pidAdminMin + 0x75) // PT_I8 version of PR_MESSAGE_SIZE defined in mapitags.h -#define PR_MESSAGE_SIZE_EXTENDED PROP_TAG(PT_I8, PROP_ID(PR_MESSAGE_SIZE)) +#define PR_MESSAGE_SIZE_EXTENDED PROP_TAG(PT_I8, PROP_ID(PR_MESSAGE_SIZE)) /* Bits in PR_FOLDER_FLAGS */ -#define MDB_FOLDER_IPM 0x1 -#define MDB_FOLDER_SEARCH 0x2 -#define MDB_FOLDER_NORMAL 0x4 -#define MDB_FOLDER_RULES 0x8 +#define MDB_FOLDER_IPM 0x1 +#define MDB_FOLDER_SEARCH 0x2 +#define MDB_FOLDER_NORMAL 0x4 +#define MDB_FOLDER_RULES 0x8 /* Bits used in ulFlags in GetPublicFolderTable() */ -#define MDB_NON_IPM 0x10 -#define MDB_IPM 0x20 +#define MDB_NON_IPM 0x10 +#define MDB_IPM 0x20 /* Bits in PR_STORAGE_LIMIT_INFORMATION */ -#define MDB_LIMIT_BELOW 0x1 -#define MDB_LIMIT_ISSUE_WARNING 0x2 -#define MDB_LIMIT_PROHIBIT_SEND 0x4 -#define MDB_LIMIT_NO_CHECK 0x8 -#define MDB_LIMIT_DISABLED 0x10 +#define MDB_LIMIT_BELOW 0x1 +#define MDB_LIMIT_ISSUE_WARNING 0x2 +#define MDB_LIMIT_PROHIBIT_SEND 0x4 +#define MDB_LIMIT_NO_CHECK 0x8 +#define MDB_LIMIT_DISABLED 0x10 /* A define for "no quota infomation" when retrieving the quota information */ -#define MDB_QUOTA_NOQUOTA 0xFFFFFFFF +#define MDB_QUOTA_NOQUOTA 0xFFFFFFFF /*------------------------------------------------------------------------ * @@ -1729,40 +1640,28 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeNntpNewsfeed, LPEXCHANGENNTPNEWSFEED); // Use MAPI_MOVE for move option // Transfer methods -#define TRANSFER_COPYTO 1 -#define TRANSFER_COPYPROPS 2 -#define TRANSFER_COPYMESSAGES 3 -#define TRANSFER_COPYFOLDER 4 - - -#define EXCHANGE_IEXCHANGEFASTTRANSFER_METHODS(IPURE) \ - MAPIMETHOD(Config) \ - (THIS_ ULONG ulFlags, \ - ULONG ulTransferMethod) IPURE; \ - MAPIMETHOD(TransferBuffer) \ - (THIS_ ULONG cb, \ - LPBYTE lpb, \ - ULONG *lpcbProcessed) IPURE; \ - STDMETHOD_(BOOL, IsInterfaceOk) \ - (THIS_ ULONG ulTransferMethod, \ - REFIID refiid, \ - LPSPropTagArray lpptagList, \ - ULONG ulFlags) IPURE; - -#undef INTERFACE -#define INTERFACE IExchangeFastTransfer -DECLARE_MAPI_INTERFACE_(IExchangeFastTransfer, IUnknown) -{ - MAPI_IUNKNOWN_METHODS(PURE) - EXCHANGE_IEXCHANGEFASTTRANSFER_METHODS(PURE) -}; -#undef IMPL +#define TRANSFER_COPYTO 1 +#define TRANSFER_COPYPROPS 2 +#define TRANSFER_COPYMESSAGES 3 +#define TRANSFER_COPYFOLDER 4 + +#define EXCHANGE_IEXCHANGEFASTTRANSFER_METHODS(IPURE) \ + MAPIMETHOD(Config) \ + (THIS_ ULONG ulFlags, ULONG ulTransferMethod) IPURE; \ + MAPIMETHOD(TransferBuffer) \ + (THIS_ ULONG cb, LPBYTE lpb, ULONG * lpcbProcessed) IPURE; \ + STDMETHOD_(BOOL, IsInterfaceOk) \ + (THIS_ ULONG ulTransferMethod, REFIID refiid, LPSPropTagArray lpptagList, ULONG ulFlags) IPURE; + +#undef INTERFACE +#define INTERFACE IExchangeFastTransfer +DECLARE_MAPI_INTERFACE_(IExchangeFastTransfer, + IUnknown){MAPI_IUNKNOWN_METHODS(PURE) EXCHANGE_IEXCHANGEFASTTRANSFER_METHODS(PURE)}; +#undef IMPL #define IMPL DECLARE_MAPI_INTERFACE_PTR(IExchangeFastTransfer, LPEXCHANGEFASTTRANSFER); - - /*------------------------------------------------------------------------ * * "IExchangeExportChanges" Interface Declaration @@ -1771,33 +1670,22 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeFastTransfer, LPEXCHANGEFASTTRANSFER); * *-----------------------------------------------------------------------*/ -#define EXCHANGE_IEXCHANGEEXPORTCHANGES_METHODS(IPURE) \ - MAPIMETHOD(GetLastError) \ - (THIS_ HRESULT hResult, \ - ULONG ulFlags, \ - LPMAPIERROR FAR * lppMAPIError) IPURE; \ - MAPIMETHOD(Config) \ - (THIS_ LPSTREAM lpStream, \ - ULONG ulFlags, \ - LPUNKNOWN lpUnk, \ - LPSRestriction lpRestriction, \ - LPSPropTagArray lpIncludeProps, \ - LPSPropTagArray lpExcludeProps, \ - ULONG ulBufferSize) IPURE; \ - MAPIMETHOD(Synchronize) \ - (THIS_ ULONG FAR * lpulSteps, \ - ULONG FAR * lpulProgress) IPURE; \ - MAPIMETHOD(UpdateState) \ - (THIS_ LPSTREAM lpStream) IPURE; - -#undef INTERFACE -#define INTERFACE IExchangeExportChanges -DECLARE_MAPI_INTERFACE_(IExchangeExportChanges, IUnknown) -{ - MAPI_IUNKNOWN_METHODS(PURE) - EXCHANGE_IEXCHANGEEXPORTCHANGES_METHODS(PURE) -}; -#undef IMPL +#define EXCHANGE_IEXCHANGEEXPORTCHANGES_METHODS(IPURE) \ + MAPIMETHOD(GetLastError) \ + (THIS_ HRESULT hResult, ULONG ulFlags, LPMAPIERROR FAR * lppMAPIError) IPURE; \ + MAPIMETHOD(Config) \ + (THIS_ LPSTREAM lpStream, ULONG ulFlags, LPUNKNOWN lpUnk, LPSRestriction lpRestriction, \ + LPSPropTagArray lpIncludeProps, LPSPropTagArray lpExcludeProps, ULONG ulBufferSize) IPURE; \ + MAPIMETHOD(Synchronize) \ + (THIS_ ULONG FAR * lpulSteps, ULONG FAR * lpulProgress) IPURE; \ + MAPIMETHOD(UpdateState) \ + (THIS_ LPSTREAM lpStream) IPURE; + +#undef INTERFACE +#define INTERFACE IExchangeExportChanges +DECLARE_MAPI_INTERFACE_(IExchangeExportChanges, + IUnknown){MAPI_IUNKNOWN_METHODS(PURE) EXCHANGE_IEXCHANGEEXPORTCHANGES_METHODS(PURE)}; +#undef IMPL #define IMPL DECLARE_MAPI_INTERFACE_PTR(IExchangeExportChanges, LPEXCHANGEEXPORTCHANGES); @@ -1811,25 +1699,17 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeExportChanges, LPEXCHANGEEXPORTCHANGES); * *-----------------------------------------------------------------------*/ -#define EXCHANGE_IEXCHANGEEXPORTCHANGES2_METHODS(IPURE) \ - MAPIMETHOD(ConfigForConversionStream) \ - (THIS_ LPSTREAM lpStream, \ - ULONG ulFlags, \ - LPUNKNOWN lpUnk, \ - LPSRestriction lpRestriction, \ - ULONG cValuesConversion, \ - LPSPropValue lpPropArrayConversion, \ - ULONG ulBufferSize) IPURE; - -#undef INTERFACE -#define INTERFACE IExchangeExportChanges2 -DECLARE_MAPI_INTERFACE_(IExchangeExportChanges2, IExchangeExportChanges) -{ - MAPI_IUNKNOWN_METHODS(PURE) - EXCHANGE_IEXCHANGEEXPORTCHANGES_METHODS(PURE) - EXCHANGE_IEXCHANGEEXPORTCHANGES2_METHODS(PURE) -}; -#undef IMPL +#define EXCHANGE_IEXCHANGEEXPORTCHANGES2_METHODS(IPURE) \ + MAPIMETHOD(ConfigForConversionStream) \ + (THIS_ LPSTREAM lpStream, ULONG ulFlags, LPUNKNOWN lpUnk, LPSRestriction lpRestriction, ULONG cValuesConversion, \ + LPSPropValue lpPropArrayConversion, ULONG ulBufferSize) IPURE; + +#undef INTERFACE +#define INTERFACE IExchangeExportChanges2 +DECLARE_MAPI_INTERFACE_(IExchangeExportChanges2, IExchangeExportChanges){ + MAPI_IUNKNOWN_METHODS(PURE) EXCHANGE_IEXCHANGEEXPORTCHANGES_METHODS(PURE) + EXCHANGE_IEXCHANGEEXPORTCHANGES2_METHODS(PURE)}; +#undef IMPL #define IMPL DECLARE_MAPI_INTERFACE_PTR(IExchangeExportChanges2, LPEXCHANGEEXPORTCHANGES2); @@ -1843,36 +1723,25 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeExportChanges2, LPEXCHANGEEXPORTCHANGES2); * *-----------------------------------------------------------------------*/ -#define EXCHANGE_IEXCHANGEEXPORTCHANGES3_METHODS(IPURE) \ - MAPIMETHOD(ConfigForSelectiveSync) \ - (THIS_ LPSTREAM lpStream, \ - ULONG ulFlags, \ - LPUNKNOWN lpUnk, \ - LPENTRYLIST lpMsgList, \ - LPSRestriction lpRestriction, \ - LPSPropTagArray lpIncludeProps, \ - LPSPropTagArray lpExcludeProps, \ - ULONG ulBufferSize) IPURE; - -#undef INTERFACE -#define INTERFACE IExchangeExportChanges3 -DECLARE_MAPI_INTERFACE_(IExchangeExportChanges3, IExchangeExportChanges2) -{ - MAPI_IUNKNOWN_METHODS(PURE) - EXCHANGE_IEXCHANGEEXPORTCHANGES_METHODS(PURE) - EXCHANGE_IEXCHANGEEXPORTCHANGES2_METHODS(PURE) - EXCHANGE_IEXCHANGEEXPORTCHANGES3_METHODS(PURE) -}; -#undef IMPL +#define EXCHANGE_IEXCHANGEEXPORTCHANGES3_METHODS(IPURE) \ + MAPIMETHOD(ConfigForSelectiveSync) \ + (THIS_ LPSTREAM lpStream, ULONG ulFlags, LPUNKNOWN lpUnk, LPENTRYLIST lpMsgList, LPSRestriction lpRestriction, \ + LPSPropTagArray lpIncludeProps, LPSPropTagArray lpExcludeProps, ULONG ulBufferSize) IPURE; + +#undef INTERFACE +#define INTERFACE IExchangeExportChanges3 +DECLARE_MAPI_INTERFACE_(IExchangeExportChanges3, IExchangeExportChanges2){ + MAPI_IUNKNOWN_METHODS(PURE) EXCHANGE_IEXCHANGEEXPORTCHANGES_METHODS(PURE) + EXCHANGE_IEXCHANGEEXPORTCHANGES2_METHODS(PURE) EXCHANGE_IEXCHANGEEXPORTCHANGES3_METHODS(PURE)}; +#undef IMPL #define IMPL DECLARE_MAPI_INTERFACE_PTR(IExchangeExportChanges3, LPEXCHANGEEXPORTCHANGES3); -typedef struct _ReadState -{ - ULONG cbSourceKey; - BYTE * pbSourceKey; - ULONG ulFlags; +typedef struct _ReadState { + ULONG cbSourceKey; + BYTE *pbSourceKey; + ULONG ulFlags; } READSTATE, *LPREADSTATE; /*------------------------------------------------------------------------ @@ -1883,53 +1752,32 @@ typedef struct _ReadState * *-----------------------------------------------------------------------*/ - -#define EXCHANGE_IEXCHANGEIMPORTCONTENTSCHANGES_METHODS(IPURE) \ - MAPIMETHOD(GetLastError) \ - (THIS_ HRESULT hResult, \ - ULONG ulFlags, \ - LPMAPIERROR FAR * lppMAPIError) IPURE; \ - MAPIMETHOD(Config) \ - (THIS_ LPSTREAM lpStream, \ - ULONG ulFlags) IPURE; \ - MAPIMETHOD(UpdateState) \ - (THIS_ LPSTREAM lpStream) IPURE; \ - MAPIMETHOD(ImportMessageChange) \ - (THIS_ ULONG cpvalChanges, \ - LPSPropValue ppvalChanges, \ - ULONG ulFlags, \ - LPMESSAGE *lppmessage) IPURE; \ - MAPIMETHOD(ImportMessageDeletion) \ - (THIS_ ULONG ulFlags, \ - LPENTRYLIST lpSrcEntryList) IPURE; \ - MAPIMETHOD(ImportPerUserReadStateChange) \ - (THIS_ ULONG cElements, \ - LPREADSTATE lpReadState) IPURE; \ - MAPIMETHOD(ImportMessageMove) \ - (THIS_ ULONG cbSourceKeySrcFolder, \ - BYTE FAR * pbSourceKeySrcFolder, \ - ULONG cbSourceKeySrcMessage, \ - BYTE FAR * pbSourceKeySrcMessage, \ - ULONG cbPCLMessage, \ - BYTE FAR * pbPCLMessage, \ - ULONG cbSourceKeyDestMessage, \ - BYTE FAR * pbSourceKeyDestMessage, \ - ULONG cbChangeNumDestMessage, \ - BYTE FAR * pbChangeNumDestMessage) IPURE; - - -#undef INTERFACE -#define INTERFACE IExchangeImportContentsChanges -DECLARE_MAPI_INTERFACE_(IExchangeImportContentsChanges, IUnknown) -{ - MAPI_IUNKNOWN_METHODS(PURE) - EXCHANGE_IEXCHANGEIMPORTCONTENTSCHANGES_METHODS(PURE) -}; -#undef IMPL +#define EXCHANGE_IEXCHANGEIMPORTCONTENTSCHANGES_METHODS(IPURE) \ + MAPIMETHOD(GetLastError) \ + (THIS_ HRESULT hResult, ULONG ulFlags, LPMAPIERROR FAR * lppMAPIError) IPURE; \ + MAPIMETHOD(Config) \ + (THIS_ LPSTREAM lpStream, ULONG ulFlags) IPURE; \ + MAPIMETHOD(UpdateState) \ + (THIS_ LPSTREAM lpStream) IPURE; \ + MAPIMETHOD(ImportMessageChange) \ + (THIS_ ULONG cpvalChanges, LPSPropValue ppvalChanges, ULONG ulFlags, LPMESSAGE * lppmessage) IPURE; \ + MAPIMETHOD(ImportMessageDeletion) \ + (THIS_ ULONG ulFlags, LPENTRYLIST lpSrcEntryList) IPURE; \ + MAPIMETHOD(ImportPerUserReadStateChange) \ + (THIS_ ULONG cElements, LPREADSTATE lpReadState) IPURE; \ + MAPIMETHOD(ImportMessageMove) \ + (THIS_ ULONG cbSourceKeySrcFolder, BYTE FAR * pbSourceKeySrcFolder, ULONG cbSourceKeySrcMessage, \ + BYTE FAR * pbSourceKeySrcMessage, ULONG cbPCLMessage, BYTE FAR * pbPCLMessage, ULONG cbSourceKeyDestMessage, \ + BYTE FAR * pbSourceKeyDestMessage, ULONG cbChangeNumDestMessage, BYTE FAR * pbChangeNumDestMessage) IPURE; + +#undef INTERFACE +#define INTERFACE IExchangeImportContentsChanges +DECLARE_MAPI_INTERFACE_(IExchangeImportContentsChanges, + IUnknown){MAPI_IUNKNOWN_METHODS(PURE) EXCHANGE_IEXCHANGEIMPORTCONTENTSCHANGES_METHODS(PURE)}; +#undef IMPL #define IMPL -DECLARE_MAPI_INTERFACE_PTR(IExchangeImportContentsChanges, - LPEXCHANGEIMPORTCONTENTSCHANGES); +DECLARE_MAPI_INTERFACE_PTR(IExchangeImportContentsChanges, LPEXCHANGEIMPORTCONTENTSCHANGES); /*------------------------------------------------------------------------ * @@ -1941,33 +1789,21 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeImportContentsChanges, * *-----------------------------------------------------------------------*/ - -#define EXCHANGE_IEXCHANGEIMPORTCONTENTSCHANGES2_METHODS(IPURE) \ - MAPIMETHOD(ConfigForConversionStream) \ - (THIS_ LPSTREAM lpStream, \ - ULONG ulFlags, \ - ULONG cValuesConversion, \ - LPSPropValue lpPropArrayConversion) IPURE; \ - MAPIMETHOD(ImportMessageChangeAsAStream) \ - (THIS_ ULONG cpvalChanges, \ - LPSPropValue ppvalChanges, \ - ULONG ulFlags, \ - LPSTREAM *lppstream) IPURE; \ - - -#undef INTERFACE -#define INTERFACE IExchangeImportContentsChanges2 -DECLARE_MAPI_INTERFACE_(IExchangeImportContentsChanges2, IExchangeImportContentsChanges) -{ - MAPI_IUNKNOWN_METHODS(PURE) - EXCHANGE_IEXCHANGEIMPORTCONTENTSCHANGES_METHODS(PURE) - EXCHANGE_IEXCHANGEIMPORTCONTENTSCHANGES2_METHODS(PURE) -}; -#undef IMPL +#define EXCHANGE_IEXCHANGEIMPORTCONTENTSCHANGES2_METHODS(IPURE) \ + MAPIMETHOD(ConfigForConversionStream) \ + (THIS_ LPSTREAM lpStream, ULONG ulFlags, ULONG cValuesConversion, LPSPropValue lpPropArrayConversion) IPURE; \ + MAPIMETHOD(ImportMessageChangeAsAStream) \ + (THIS_ ULONG cpvalChanges, LPSPropValue ppvalChanges, ULONG ulFlags, LPSTREAM * lppstream) IPURE; + +#undef INTERFACE +#define INTERFACE IExchangeImportContentsChanges2 +DECLARE_MAPI_INTERFACE_(IExchangeImportContentsChanges2, IExchangeImportContentsChanges){ + MAPI_IUNKNOWN_METHODS(PURE) EXCHANGE_IEXCHANGEIMPORTCONTENTSCHANGES_METHODS(PURE) + EXCHANGE_IEXCHANGEIMPORTCONTENTSCHANGES2_METHODS(PURE)}; +#undef IMPL #define IMPL -DECLARE_MAPI_INTERFACE_PTR(IExchangeImportContentsChanges2, - LPEXCHANGEIMPORTCONTENTSCHANGES2); +DECLARE_MAPI_INTERFACE_PTR(IExchangeImportContentsChanges2, LPEXCHANGEIMPORTCONTENTSCHANGES2); /*------------------------------------------------------------------------ * @@ -1977,86 +1813,62 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeImportContentsChanges2, * *-----------------------------------------------------------------------*/ -#define EXCHANGE_IEXCHANGEIMPORTHIERARCHYCHANGES_METHODS(IPURE) \ - MAPIMETHOD(GetLastError) \ - (THIS_ HRESULT hResult, \ - ULONG ulFlags, \ - LPMAPIERROR FAR * lppMAPIError) IPURE; \ - MAPIMETHOD(Config) \ - (THIS_ LPSTREAM lpStream, \ - ULONG ulFlags) IPURE; \ - MAPIMETHOD(UpdateState) \ - (THIS_ LPSTREAM lpStream) IPURE; \ - MAPIMETHOD(ImportFolderChange) \ - (THIS_ ULONG cpvalChanges, \ - LPSPropValue ppvalChanges) IPURE; \ - MAPIMETHOD(ImportFolderDeletion) \ - (THIS_ ULONG ulFlags, \ - LPENTRYLIST lpSrcEntryList) IPURE; - -#undef INTERFACE -#define INTERFACE IExchangeImportHierarchyChanges -DECLARE_MAPI_INTERFACE_(IExchangeImportHierarchyChanges, IUnknown) -{ - MAPI_IUNKNOWN_METHODS(PURE) - EXCHANGE_IEXCHANGEIMPORTHIERARCHYCHANGES_METHODS(PURE) -}; -#undef IMPL +#define EXCHANGE_IEXCHANGEIMPORTHIERARCHYCHANGES_METHODS(IPURE) \ + MAPIMETHOD(GetLastError) \ + (THIS_ HRESULT hResult, ULONG ulFlags, LPMAPIERROR FAR * lppMAPIError) IPURE; \ + MAPIMETHOD(Config) \ + (THIS_ LPSTREAM lpStream, ULONG ulFlags) IPURE; \ + MAPIMETHOD(UpdateState) \ + (THIS_ LPSTREAM lpStream) IPURE; \ + MAPIMETHOD(ImportFolderChange) \ + (THIS_ ULONG cpvalChanges, LPSPropValue ppvalChanges) IPURE; \ + MAPIMETHOD(ImportFolderDeletion) \ + (THIS_ ULONG ulFlags, LPENTRYLIST lpSrcEntryList) IPURE; + +#undef INTERFACE +#define INTERFACE IExchangeImportHierarchyChanges +DECLARE_MAPI_INTERFACE_(IExchangeImportHierarchyChanges, + IUnknown){MAPI_IUNKNOWN_METHODS(PURE) EXCHANGE_IEXCHANGEIMPORTHIERARCHYCHANGES_METHODS(PURE)}; +#undef IMPL #define IMPL -DECLARE_MAPI_INTERFACE_PTR(IExchangeImportHierarchyChanges, - LPEXCHANGEIMPORTHIERARCHYCHANGES); - -#define ulHierChanged (0x01) - -#define EXCHANGE_IEXCHANGECHANGEADVISESINK_METHODS(IPURE) \ - MAPIMETHOD_(ULONG, OnNotify) \ - (THIS_ ULONG ulFlags, \ - LPENTRYLIST lpEntryList) IPURE; \ - -#undef INTERFACE -#define INTERFACE IExchangeChangeAdviseSink -DECLARE_MAPI_INTERFACE_(IExchangeChangeAdviseSink, IUnknown) -{ - BEGIN_INTERFACE - MAPI_IUNKNOWN_METHODS(PURE) - EXCHANGE_IEXCHANGECHANGEADVISESINK_METHODS(PURE) -}; -#undef IMPL +DECLARE_MAPI_INTERFACE_PTR(IExchangeImportHierarchyChanges, LPEXCHANGEIMPORTHIERARCHYCHANGES); + +#define ulHierChanged (0x01) + +#define EXCHANGE_IEXCHANGECHANGEADVISESINK_METHODS(IPURE) \ + MAPIMETHOD_(ULONG, OnNotify) \ + (THIS_ ULONG ulFlags, LPENTRYLIST lpEntryList) IPURE; + +#undef INTERFACE +#define INTERFACE IExchangeChangeAdviseSink +DECLARE_MAPI_INTERFACE_(IExchangeChangeAdviseSink, IUnknown){BEGIN_INTERFACE MAPI_IUNKNOWN_METHODS(PURE) + EXCHANGE_IEXCHANGECHANGEADVISESINK_METHODS(PURE)}; +#undef IMPL #define IMPL -DECLARE_MAPI_INTERFACE_PTR(IExchangeChangeAdviseSink, - LPEXCHANGECHANGEADVISESINK); - -#define EXCHANGE_IEXCHANGECHANGEADVISOR_METHODS(IPURE) \ - MAPIMETHOD(GetLastError) \ - (THIS_ HRESULT hResult, \ - ULONG ulFlags, \ - LPMAPIERROR FAR * lppMAPIError) IPURE; \ - MAPIMETHOD(Config) \ - (THIS_ LPSTREAM lpStream, \ - LPGUID lpGUID, \ - LPEXCHANGECHANGEADVISESINK lpAdviseSink, \ - ULONG ulFlags) IPURE; \ - MAPIMETHOD(UpdateState) \ - (THIS_ LPSTREAM lpStream) IPURE; \ - MAPIMETHOD(AddKeys) \ - (THIS_ LPENTRYLIST lpEntryList) IPURE; \ - MAPIMETHOD(RemoveKeys) \ - (THIS_ LPENTRYLIST lpEntryList) IPURE; - -#undef INTERFACE -#define INTERFACE IExchangeChangeAdvisor -DECLARE_MAPI_INTERFACE_(IExchangeChangeAdvisor, IUnknown) -{ - MAPI_IUNKNOWN_METHODS(PURE) - EXCHANGE_IEXCHANGECHANGEADVISOR_METHODS(PURE) -}; -#undef IMPL +DECLARE_MAPI_INTERFACE_PTR(IExchangeChangeAdviseSink, LPEXCHANGECHANGEADVISESINK); + +#define EXCHANGE_IEXCHANGECHANGEADVISOR_METHODS(IPURE) \ + MAPIMETHOD(GetLastError) \ + (THIS_ HRESULT hResult, ULONG ulFlags, LPMAPIERROR FAR * lppMAPIError) IPURE; \ + MAPIMETHOD(Config) \ + (THIS_ LPSTREAM lpStream, LPGUID lpGUID, LPEXCHANGECHANGEADVISESINK lpAdviseSink, ULONG ulFlags) IPURE; \ + MAPIMETHOD(UpdateState) \ + (THIS_ LPSTREAM lpStream) IPURE; \ + MAPIMETHOD(AddKeys) \ + (THIS_ LPENTRYLIST lpEntryList) IPURE; \ + MAPIMETHOD(RemoveKeys) \ + (THIS_ LPENTRYLIST lpEntryList) IPURE; + +#undef INTERFACE +#define INTERFACE IExchangeChangeAdvisor +DECLARE_MAPI_INTERFACE_(IExchangeChangeAdvisor, + IUnknown){MAPI_IUNKNOWN_METHODS(PURE) EXCHANGE_IEXCHANGECHANGEADVISOR_METHODS(PURE)}; +#undef IMPL #define IMPL -DECLARE_MAPI_INTERFACE_PTR(IExchangeChangeAdvisor, - LPEXCHANGECHANGEADVISOR); +DECLARE_MAPI_INTERFACE_PTR(IExchangeChangeAdvisor, LPEXCHANGECHANGEADVISOR); /*-------------------------------------------------------------------- * @@ -2066,27 +1878,19 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeChangeAdvisor, * *--------------------------------------------------------------------*/ -#define EXCHANGE_IEXCHANGEBADITEMCALLBACK_METHODS(IPURE) \ - MAPIMETHOD(BadItem) \ - (THIS_ HRESULT hResult, \ - ULONG ulFlags, \ - LPWSTR lpwszFolderName, \ - LPSBinary lpsbFolderEid, \ - ULONG cValues, \ - LPSPropValue lpPropArray) IPURE; - -#undef INTERFACE -#define INTERFACE IExchangeBadItemCallback -DECLARE_MAPI_INTERFACE_(IExchangeBadItemCallback, IUnknown) -{ - MAPI_IUNKNOWN_METHODS(PURE) - EXCHANGE_IEXCHANGEBADITEMCALLBACK_METHODS(PURE) -}; -#undef IMPL +#define EXCHANGE_IEXCHANGEBADITEMCALLBACK_METHODS(IPURE) \ + MAPIMETHOD(BadItem) \ + (THIS_ HRESULT hResult, ULONG ulFlags, LPWSTR lpwszFolderName, LPSBinary lpsbFolderEid, ULONG cValues, \ + LPSPropValue lpPropArray) IPURE; + +#undef INTERFACE +#define INTERFACE IExchangeBadItemCallback +DECLARE_MAPI_INTERFACE_(IExchangeBadItemCallback, + IUnknown){MAPI_IUNKNOWN_METHODS(PURE) EXCHANGE_IEXCHANGEBADITEMCALLBACK_METHODS(PURE)}; +#undef IMPL #define IMPL -DECLARE_MAPI_INTERFACE_PTR(IExchangeBadItemCallback, - LPEXCHANGEBADITEMCALLBACK); +DECLARE_MAPI_INTERFACE_PTR(IExchangeBadItemCallback, LPEXCHANGEBADITEMCALLBACK); /*-------------------------------------------------------------------- * @@ -2096,35 +1900,27 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeBadItemCallback, * *--------------------------------------------------------------------*/ -#define EXCHANGE_IEXCHANGEMOVEUSERPROGRESS_METHODS(IPURE) \ - MAPIMETHOD(NextFolder) \ - (THIS_ ULONG ulFlags, \ - LPWSTR lpwszFolderName) IPURE; \ - MAPIMETHOD(Progress) \ - (THIS_ ULONG ulFlags, \ - ULONG ulCount, \ - ULONG ulTotal) IPURE; \ - MAPIMETHOD(Restart) \ - (THIS_ ULONG ulFlags) IPURE; \ - -#undef INTERFACE -#define INTERFACE IExchangeMoveUserProgress -DECLARE_MAPI_INTERFACE_(IExchangeMoveUserProgress, IUnknown) -{ - MAPI_IUNKNOWN_METHODS(PURE) - EXCHANGE_IEXCHANGEMOVEUSERPROGRESS_METHODS(PURE) -}; -#undef IMPL +#define EXCHANGE_IEXCHANGEMOVEUSERPROGRESS_METHODS(IPURE) \ + MAPIMETHOD(NextFolder) \ + (THIS_ ULONG ulFlags, LPWSTR lpwszFolderName) IPURE; \ + MAPIMETHOD(Progress) \ + (THIS_ ULONG ulFlags, ULONG ulCount, ULONG ulTotal) IPURE; \ + MAPIMETHOD(Restart) \ + (THIS_ ULONG ulFlags) IPURE; + +#undef INTERFACE +#define INTERFACE IExchangeMoveUserProgress +DECLARE_MAPI_INTERFACE_(IExchangeMoveUserProgress, + IUnknown){MAPI_IUNKNOWN_METHODS(PURE) EXCHANGE_IEXCHANGEMOVEUSERPROGRESS_METHODS(PURE)}; +#undef IMPL #define IMPL -DECLARE_MAPI_INTERFACE_PTR(IExchangeMoveUserProgress, - LPEXCHANGEMOVEUSERPROGRESS); +DECLARE_MAPI_INTERFACE_PTR(IExchangeMoveUserProgress, LPEXCHANGEMOVEUSERPROGRESS); // Internal flag for IMsgStore::CopyTo which tells the move user processing // that there are potential extended callback objects hanhing off of the // IMAPIProgress object. -#define MAPI_EXTENDEDCALLBACKS ((ULONG) 0x00000400) - +#define MAPI_EXTENDEDCALLBACKS ((ULONG)0x00000400) /*------------------------------------------------------------------------ * @@ -2132,21 +1928,21 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeMoveUserProgress, * *-----------------------------------------------------------------------*/ -#define MAKE_SYNC_E(err) (MAKE_SCODE(SEVERITY_ERROR, FACILITY_ITF, err)) -#define MAKE_SYNC_W(warn) (MAKE_SCODE(SEVERITY_SUCCESS, FACILITY_ITF, warn)) +#define MAKE_SYNC_E(err) (MAKE_SCODE(SEVERITY_ERROR, FACILITY_ITF, err)) +#define MAKE_SYNC_W(warn) (MAKE_SCODE(SEVERITY_SUCCESS, FACILITY_ITF, warn)) -#define SYNC_E_UNKNOWN_FLAGS MAPI_E_UNKNOWN_FLAGS -#define SYNC_E_INVALID_PARAMETER E_INVALIDARG -#define SYNC_E_ERROR E_FAIL -#define SYNC_E_OBJECT_DELETED MAKE_SYNC_E(0x800) -#define SYNC_E_IGNORE MAKE_SYNC_E(0x801) -#define SYNC_E_CONFLICT MAKE_SYNC_E(0x802) -#define SYNC_E_NO_PARENT MAKE_SYNC_E(0x803) -#define SYNC_E_CYCLE MAKE_SYNC_E(0x804) -#define SYNC_E_UNSYNCHRONIZED MAKE_SYNC_E(0x805) +#define SYNC_E_UNKNOWN_FLAGS MAPI_E_UNKNOWN_FLAGS +#define SYNC_E_INVALID_PARAMETER E_INVALIDARG +#define SYNC_E_ERROR E_FAIL +#define SYNC_E_OBJECT_DELETED MAKE_SYNC_E(0x800) +#define SYNC_E_IGNORE MAKE_SYNC_E(0x801) +#define SYNC_E_CONFLICT MAKE_SYNC_E(0x802) +#define SYNC_E_NO_PARENT MAKE_SYNC_E(0x803) +#define SYNC_E_CYCLE MAKE_SYNC_E(0x804) +#define SYNC_E_UNSYNCHRONIZED MAKE_SYNC_E(0x805) -#define SYNC_W_PROGRESS MAKE_SYNC_W(0x820) -#define SYNC_W_CLIENT_CHANGE_NEWER MAKE_SYNC_W(0x821) +#define SYNC_W_PROGRESS MAKE_SYNC_W(0x820) +#define SYNC_W_CLIENT_CHANGE_NEWER MAKE_SYNC_W(0x821) /*------------------------------------------------------------------------ * @@ -2154,25 +1950,25 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeMoveUserProgress, * *-----------------------------------------------------------------------*/ -#define SYNC_UNICODE 0x01 -#define SYNC_NO_DELETIONS 0x02 -#define SYNC_NO_SOFT_DELETIONS 0x04 -#define SYNC_READ_STATE 0x08 -#define SYNC_ASSOCIATED 0x10 -#define SYNC_NORMAL 0x20 -#define SYNC_NO_CONFLICTS 0x40 -#define SYNC_ONLY_SPECIFIED_PROPS 0x80 -#define SYNC_NO_FOREIGN_KEYS 0x100 -#define SYNC_LIMITED_IMESSAGE 0x200 -#define SYNC_CATCHUP 0x400 -#define SYNC_NEW_MESSAGE 0x800 // only applicable to ImportMessageChange() -#define SYNC_MSG_SELECTIVE 0x1000 // Used internally. Will reject if used by clients. -#define SYNC_BEST_BODY 0x2000 +#define SYNC_UNICODE 0x01 +#define SYNC_NO_DELETIONS 0x02 +#define SYNC_NO_SOFT_DELETIONS 0x04 +#define SYNC_READ_STATE 0x08 +#define SYNC_ASSOCIATED 0x10 +#define SYNC_NORMAL 0x20 +#define SYNC_NO_CONFLICTS 0x40 +#define SYNC_ONLY_SPECIFIED_PROPS 0x80 +#define SYNC_NO_FOREIGN_KEYS 0x100 +#define SYNC_LIMITED_IMESSAGE 0x200 +#define SYNC_CATCHUP 0x400 +#define SYNC_NEW_MESSAGE 0x800 // only applicable to ImportMessageChange() +#define SYNC_MSG_SELECTIVE 0x1000 // Used internally. Will reject if used by clients. +#define SYNC_BEST_BODY 0x2000 #define SYNC_IGNORE_SPECIFIED_ON_ASSOCIATED 0x4000 -#define SYNC_PROGRESS_MODE 0x8000 // AirMapi progress mode -#define SYNC_FXRECOVERMODE 0x10000 -#define SYNC_DEFER_CONFIG 0x20000 -#define SYNC_FORCE_UNICODE 0x40000 // Forces server to return Unicode properties +#define SYNC_PROGRESS_MODE 0x8000 // AirMapi progress mode +#define SYNC_FXRECOVERMODE 0x10000 +#define SYNC_DEFER_CONFIG 0x20000 +#define SYNC_FORCE_UNICODE 0x40000 // Forces server to return Unicode properties /*------------------------------------------------------------------------ * @@ -2180,8 +1976,8 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeMoveUserProgress, * *-----------------------------------------------------------------------*/ -#define SYNC_SOFT_DELETE 0x01 -#define SYNC_EXPIRY 0x02 +#define SYNC_SOFT_DELETE 0x01 +#define SYNC_EXPIRY 0x02 /*------------------------------------------------------------------------ * @@ -2189,7 +1985,7 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeMoveUserProgress, * *-----------------------------------------------------------------------*/ -#define SYNC_READ 0x01 +#define SYNC_READ 0x01 /*------------------------------------------------------------------------ * @@ -2197,8 +1993,8 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeMoveUserProgress, * *-----------------------------------------------------------------------*/ -#define MESSAGE_BEST_BODY 0x10 -#define MESSAGE_SEND_ENTRYID 0x20 +#define MESSAGE_BEST_BODY 0x10 +#define MESSAGE_SEND_ENTRYID 0x20 /*------------------------------------------------------------------------ * @@ -2208,7 +2004,6 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeMoveUserProgress, #define SUPRESS_NOTIFICATIONS_ON_MY_ACTIONS 0x01000 - /*------------------------------------------------------------------------ * * "IExchangeFavorites" Interface Declaration @@ -2220,26 +2015,20 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeMoveUserProgress, * *-----------------------------------------------------------------------*/ -#define EXCHANGE_IEXCHANGEFAVORITES_METHODS(IPURE) \ - MAPIMETHOD(GetLastError) \ - (THIS_ HRESULT hResult, \ - ULONG ulFlags, \ - LPMAPIERROR FAR * lppMAPIError) IPURE; \ - MAPIMETHOD(AddFavorites) \ - (THIS_ LPENTRYLIST lpEntryList) IPURE; \ - MAPIMETHOD(DelFavorites) \ - (THIS_ LPENTRYLIST lpEntryList) IPURE; \ - -#undef INTERFACE -#define INTERFACE IExchangeFavorites -DECLARE_MAPI_INTERFACE_(IExchangeFavorites, IUnknown) -{ - MAPI_IUNKNOWN_METHODS(PURE) - EXCHANGE_IEXCHANGEFAVORITES_METHODS(PURE) -}; +#define EXCHANGE_IEXCHANGEFAVORITES_METHODS(IPURE) \ + MAPIMETHOD(GetLastError) \ + (THIS_ HRESULT hResult, ULONG ulFlags, LPMAPIERROR FAR * lppMAPIError) IPURE; \ + MAPIMETHOD(AddFavorites) \ + (THIS_ LPENTRYLIST lpEntryList) IPURE; \ + MAPIMETHOD(DelFavorites) \ + (THIS_ LPENTRYLIST lpEntryList) IPURE; -DECLARE_MAPI_INTERFACE_PTR(IExchangeFavorites, LPEXCHANGEFAVORITES); +#undef INTERFACE +#define INTERFACE IExchangeFavorites +DECLARE_MAPI_INTERFACE_(IExchangeFavorites, + IUnknown){MAPI_IUNKNOWN_METHODS(PURE) EXCHANGE_IEXCHANGEFAVORITES_METHODS(PURE)}; +DECLARE_MAPI_INTERFACE_PTR(IExchangeFavorites, LPEXCHANGEFAVORITES); /*------------------------------------------------------------------------ * @@ -2247,17 +2036,16 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeFavorites, LPEXCHANGEFAVORITES); * *-----------------------------------------------------------------------*/ -#define PR_AUTO_ADD_NEW_SUBS PROP_TAG(PT_BOOLEAN, pidExchangeNonXmitReservedMin+0x5) -#define PR_NEW_SUBS_GET_AUTO_ADD PROP_TAG(PT_BOOLEAN, pidExchangeNonXmitReservedMin+0x6) +#define PR_AUTO_ADD_NEW_SUBS PROP_TAG(PT_BOOLEAN, pidExchangeNonXmitReservedMin + 0x5) +#define PR_NEW_SUBS_GET_AUTO_ADD PROP_TAG(PT_BOOLEAN, pidExchangeNonXmitReservedMin + 0x6) /*------------------------------------------------------------------------ * * Properties used by the Offline Folders API * *-----------------------------------------------------------------------*/ -#define PR_OFFLINE_FLAGS PROP_TAG(PT_LONG, pidFolderMin+0x5) -#define PR_SYNCHRONIZE_FLAGS PROP_TAG(PT_LONG, pidExchangeNonXmitReservedMin+0x4) - +#define PR_OFFLINE_FLAGS PROP_TAG(PT_LONG, pidFolderMin + 0x5) +#define PR_SYNCHRONIZE_FLAGS PROP_TAG(PT_LONG, pidExchangeNonXmitReservedMin + 0x4) /*------------------------------------------------------------------------ * @@ -2265,10 +2053,10 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeFavorites, LPEXCHANGEFAVORITES); * *-----------------------------------------------------------------------*/ -#define OF_AVAILABLE_OFFLINE ((ULONG) 0x00000001) -#define OF_FORCE ((ULONG) 0x80000000) +#define OF_AVAILABLE_OFFLINE ((ULONG)0x00000001) +#define OF_FORCE ((ULONG)0x80000000) -#define SF_DISABLE_STARTUP_SYNC ((ULONG) 0x00000001) +#define SF_DISABLE_STARTUP_SYNC ((ULONG)0x00000001) /*------------------------------------------------------------------------ * @@ -2278,39 +2066,33 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeFavorites, LPEXCHANGEFAVORITES); * *-----------------------------------------------------------------------*/ -#define EXCHANGE_IEXCHANGEMESSAGECONVERSION_METHODS(IPURE) \ - MAPIMETHOD(OpenStream) \ - (THIS_ ULONG cValues, \ - LPSPropValue lpPropArray, \ - LPSTREAM FAR * lppStream) IPURE; -#undef INTERFACE -#define INTERFACE IExchangeMessageConversion -DECLARE_MAPI_INTERFACE_(IExchangeMessageConversion, IUnknown) -{ - MAPI_IUNKNOWN_METHODS(PURE) - EXCHANGE_IEXCHANGEMESSAGECONVERSION_METHODS(PURE) -}; -#undef IMPL +#define EXCHANGE_IEXCHANGEMESSAGECONVERSION_METHODS(IPURE) \ + MAPIMETHOD(OpenStream) \ + (THIS_ ULONG cValues, LPSPropValue lpPropArray, LPSTREAM FAR * lppStream) IPURE; +#undef INTERFACE +#define INTERFACE IExchangeMessageConversion +DECLARE_MAPI_INTERFACE_(IExchangeMessageConversion, + IUnknown){MAPI_IUNKNOWN_METHODS(PURE) EXCHANGE_IEXCHANGEMESSAGECONVERSION_METHODS(PURE)}; +#undef IMPL #define IMPL DECLARE_MAPI_INTERFACE_PTR(IExchangeMessageConversion, LPEXCHANGEMESSAGECONVERSION); -#define PR_MESSAGE_SITE_NAME PROP_TAG(PT_TSTRING, pidExchangeNonXmitReservedMin+0x7) -#define PR_MESSAGE_SITE_NAME_A PROP_TAG(PT_STRING8, pidExchangeNonXmitReservedMin+0x7) -#define PR_MESSAGE_SITE_NAME_W PROP_TAG(PT_UNICODE, pidExchangeNonXmitReservedMin+0x7) - -#define PR_MESSAGE_PROCESSED PROP_TAG(PT_BOOLEAN, pidExchangeNonXmitReservedMin+0x8) +#define PR_MESSAGE_SITE_NAME PROP_TAG(PT_TSTRING, pidExchangeNonXmitReservedMin + 0x7) +#define PR_MESSAGE_SITE_NAME_A PROP_TAG(PT_STRING8, pidExchangeNonXmitReservedMin + 0x7) +#define PR_MESSAGE_SITE_NAME_W PROP_TAG(PT_UNICODE, pidExchangeNonXmitReservedMin + 0x7) -#define PR_MSG_BODY_ID PROP_TAG(PT_LONG, pidExchangeXmitReservedMin-0x03) +#define PR_MESSAGE_PROCESSED PROP_TAG(PT_BOOLEAN, pidExchangeNonXmitReservedMin + 0x8) +#define PR_MSG_BODY_ID PROP_TAG(PT_LONG, pidExchangeXmitReservedMin - 0x03) -#define PR_BILATERAL_INFO PROP_TAG(PT_BINARY, pidExchangeXmitReservedMin-0x04) -#define PR_DL_REPORT_FLAGS PROP_TAG(PT_LONG, pidExchangeXmitReservedMin-0x05) +#define PR_BILATERAL_INFO PROP_TAG(PT_BINARY, pidExchangeXmitReservedMin - 0x04) +#define PR_DL_REPORT_FLAGS PROP_TAG(PT_LONG, pidExchangeXmitReservedMin - 0x05) -#define PRIV_DL_HIDE_MEMBERS 0x00000001 -#define PRIV_DL_REPORT_TO_ORIG 0x00000002 +#define PRIV_DL_HIDE_MEMBERS 0x00000001 +#define PRIV_DL_REPORT_TO_ORIG 0x00000002 #define PRIV_DL_REPORT_TO_OWNER 0x00000004 -#define PRIV_DL_ALLOW_OOF 0x00000008 +#define PRIV_DL_ALLOW_OOF 0x00000008 /*--------------------------------------------------------------------------------- * @@ -2320,95 +2102,92 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeMessageConversion, LPEXCHANGEMESSAGECONVERSI * if the message is not read, or NULL if it is read. * *---------------------------------------------------------------------------------*/ -#define PR_ABSTRACT PROP_TAG(PT_TSTRING, pidExchangeXmitReservedMin-0x06) -#define PR_ABSTRACT_A PROP_TAG(PT_STRING8, pidExchangeXmitReservedMin-0x06) -#define PR_ABSTRACT_W PROP_TAG(PT_UNICODE, pidExchangeXmitReservedMin-0x06) +#define PR_ABSTRACT PROP_TAG(PT_TSTRING, pidExchangeXmitReservedMin - 0x06) +#define PR_ABSTRACT_A PROP_TAG(PT_STRING8, pidExchangeXmitReservedMin - 0x06) +#define PR_ABSTRACT_W PROP_TAG(PT_UNICODE, pidExchangeXmitReservedMin - 0x06) -#define PR_PREVIEW PROP_TAG(PT_TSTRING, pidExchangeXmitReservedMin-0x07) -#define PR_PREVIEW_A PROP_TAG(PT_STRING8, pidExchangeXmitReservedMin-0x07) -#define PR_PREVIEW_W PROP_TAG(PT_UNICODE, pidExchangeXmitReservedMin-0x07) +#define PR_PREVIEW PROP_TAG(PT_TSTRING, pidExchangeXmitReservedMin - 0x07) +#define PR_PREVIEW_A PROP_TAG(PT_STRING8, pidExchangeXmitReservedMin - 0x07) +#define PR_PREVIEW_W PROP_TAG(PT_UNICODE, pidExchangeXmitReservedMin - 0x07) -#define PR_PREVIEW_UNREAD PROP_TAG(PT_TSTRING, pidExchangeXmitReservedMin-0x08) -#define PR_PREVIEW_UNREAD_A PROP_TAG(PT_STRING8, pidExchangeXmitReservedMin-0x08) -#define PR_PREVIEW_UNREAD_W PROP_TAG(PT_UNICODE, pidExchangeXmitReservedMin-0x08) +#define PR_PREVIEW_UNREAD PROP_TAG(PT_TSTRING, pidExchangeXmitReservedMin - 0x08) +#define PR_PREVIEW_UNREAD_A PROP_TAG(PT_STRING8, pidExchangeXmitReservedMin - 0x08) +#define PR_PREVIEW_UNREAD_W PROP_TAG(PT_UNICODE, pidExchangeXmitReservedMin - 0x08) // // Informs IMAIL that full fidelity should be discarded for this message. // -#define PR_DISABLE_FULL_FIDELITY PROP_TAG(PT_BOOLEAN, pidRenMsgFldMin+0x72) +#define PR_DISABLE_FULL_FIDELITY PROP_TAG(PT_BOOLEAN, pidRenMsgFldMin + 0x72) // file attributes for messages / folders // need to be in REN property range in order to replicate -#define PR_ATTR_HIDDEN PROP_TAG(PT_BOOLEAN, pidRenMsgFldMin+0x74) -#define PR_ATTR_SYSTEM PROP_TAG(PT_BOOLEAN, pidRenMsgFldMin+0x75) -#define PR_ATTR_READONLY PROP_TAG(PT_BOOLEAN, pidRenMsgFldMin+0x76) +#define PR_ATTR_HIDDEN PROP_TAG(PT_BOOLEAN, pidRenMsgFldMin + 0x74) +#define PR_ATTR_SYSTEM PROP_TAG(PT_BOOLEAN, pidRenMsgFldMin + 0x75) +#define PR_ATTR_READONLY PROP_TAG(PT_BOOLEAN, pidRenMsgFldMin + 0x76) // Flag indicating whether msg has been read or not (read-only prop for now - not replicated). -#define PR_READ PROP_TAG(PT_BOOLEAN, pidStoreNonTransMin+0x29) +#define PR_READ PROP_TAG(PT_BOOLEAN, pidStoreNonTransMin + 0x29) // Administrative security descriptor for a folder, if present. // -#define PR_ADMIN_SECURITY_DESCRIPTOR PROP_TAG(PT_BINARY, 0x3d21) +#define PR_ADMIN_SECURITY_DESCRIPTOR PROP_TAG(PT_BINARY, 0x3d21) // // Win32 compatible representation of folder/message security descriptor // -#define PR_WIN32_SECURITY_DESCRIPTOR PROP_TAG(PT_BINARY, 0x3d22) +#define PR_WIN32_SECURITY_DESCRIPTOR PROP_TAG(PT_BINARY, 0x3d22) // // TRUE if PR_NT_SECURITY_DESCRIPTOR describes non Win32 ACL semantics. // If this is set, components that use PR_WIN32_SECURITY_DESCRIPTOR cannot // allow modification of PR_NT_SECURITY_DESCRIPTOR (or PR_DEFAULT_MESSAGE_SD). // -#define PR_NON_WIN32_ACL PROP_TAG(PT_BOOLEAN, 0x3d23) +#define PR_NON_WIN32_ACL PROP_TAG(PT_BOOLEAN, 0x3d23) // // TRUE if any items in the folder contain item level ACLs // -#define PR_ITEM_LEVEL_ACL PROP_TAG(PT_BOOLEAN, 0x3d24) +#define PR_ITEM_LEVEL_ACL PROP_TAG(PT_BOOLEAN, 0x3d24) -#define PR_DAV_TRANSFER_SECURITY_DESCRIPTOR PROP_TAG(PT_BINARY, 0x0E84) +#define PR_DAV_TRANSFER_SECURITY_DESCRIPTOR PROP_TAG(PT_BINARY, 0x0E84) // // XML formatted versions of the NT SECURITY DESCRIPTOR properties -#define PR_NT_SECURITY_DESCRIPTOR_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin+0x2A) -#define PR_NT_SECURITY_DESCRIPTOR_AS_XML_A PROP_TAG(PT_STRING8, pidStoreNonTransMin+0x2A) -#define PR_NT_SECURITY_DESCRIPTOR_AS_XML_W PROP_TAG(PT_UNICODE, pidStoreNonTransMin+0x2A) -#define PR_ADMIN_SECURITY_DESCRIPTOR_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin+0x2B) -#define PR_ADMIN_SECURITY_DESCRIPTOR_AS_XML_A PROP_TAG(PT_STRING8, pidStoreNonTransMin+0x2B) -#define PR_ADMIN_SECURITY_DESCRIPTOR_AS_XML_W PROP_TAG(PT_UNICODE, pidStoreNonTransMin+0x2B) - +#define PR_NT_SECURITY_DESCRIPTOR_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin + 0x2A) +#define PR_NT_SECURITY_DESCRIPTOR_AS_XML_A PROP_TAG(PT_STRING8, pidStoreNonTransMin + 0x2A) +#define PR_NT_SECURITY_DESCRIPTOR_AS_XML_W PROP_TAG(PT_UNICODE, pidStoreNonTransMin + 0x2A) +#define PR_ADMIN_SECURITY_DESCRIPTOR_AS_XML PROP_TAG(PT_TSTRING, pidStoreNonTransMin + 0x2B) +#define PR_ADMIN_SECURITY_DESCRIPTOR_AS_XML_A PROP_TAG(PT_STRING8, pidStoreNonTransMin + 0x2B) +#define PR_ADMIN_SECURITY_DESCRIPTOR_AS_XML_W PROP_TAG(PT_UNICODE, pidStoreNonTransMin + 0x2B) /*------------------------------------------------------------------------------------ -* -* OWA Info Property -* -*------------------------------------------------------------------------------------*/ -#define PR_OWA_URL PROP_TAG (PT_STRING8, pidRenMsgFldMin+0x71) - + * + * OWA Info Property + * + *------------------------------------------------------------------------------------*/ +#define PR_OWA_URL PROP_TAG(PT_STRING8, pidRenMsgFldMin + 0x71) //$ The value of this property ID will change in the future. Do not rely on //$ its current value. Rely on the define only. -#define PR_STORE_SLOWLINK PROP_TAG(PT_BOOLEAN, 0x7c0a) - +#define PR_STORE_SLOWLINK PROP_TAG(PT_BOOLEAN, 0x7c0a) /* * Registry locations of settings */ #if defined(WIN32) && !defined(MAC) -#define SZ_HPC_V2 "Software\\Microsoft\\Windows CE Services" -#define SZ_HPC_V2_MAJOR "MajorVersion" // = 2 -#define SZ_HPC_V2_MINOR "MinorVersion" // = 0 or 1 +#define SZ_HPC_V2 "Software\\Microsoft\\Windows CE Services" +#define SZ_HPC_V2_MAJOR "MajorVersion" // = 2 +#define SZ_HPC_V2_MINOR "MinorVersion" // = 0 or 1 -#define SZ_HPC_V1 "Software\\Microsoft\\Pegasus" -#define SZ_HPC_V1_MAJOR "MajorVersion" // = 1 Major and Minor numbers didn't appear -#define SZ_HPC_V1_MINOR "MinorVersion" // = 1 until after v1.0 was released -#define SZ_HPC_V1_0 "InstalledDir" // present for v1.0 +#define SZ_HPC_V1 "Software\\Microsoft\\Pegasus" +#define SZ_HPC_V1_MAJOR "MajorVersion" // = 1 Major and Minor numbers didn't appear +#define SZ_HPC_V1_MINOR "MinorVersion" // = 1 until after v1.0 was released +#define SZ_HPC_V1_0 "InstalledDir" // present for v1.0 #define SZ_OUTL_OST_OPTIONS "Software\\Microsoft\\Office\\8.0\\Outlook\\OST" #define SZ_NO_OST "NoOST" -#define NO_OST_FLAG_ALLOWED 0 // OST's are allowed on the machine -#define NO_OST_FLAG_CACHE_ONLY 1 // OST can only be used as a cache -#define NO_OST_FLAG_NOT_ALLOWED 2 // OST's are not allowed on the machine -#define NO_OST_FLAG_NO_CACHE 3 // OST's are not allowed as a cache -#define NO_OST_DEFAULT NO_OST_FLAG_ALLOWED +#define NO_OST_FLAG_ALLOWED 0 // OST's are allowed on the machine +#define NO_OST_FLAG_CACHE_ONLY 1 // OST can only be used as a cache +#define NO_OST_FLAG_NOT_ALLOWED 2 // OST's are not allowed on the machine +#define NO_OST_FLAG_NO_CACHE 3 // OST's are not allowed as a cache +#define NO_OST_DEFAULT NO_OST_FLAG_ALLOWED #endif /* @@ -2418,7 +2197,7 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeMessageConversion, LPEXCHANGEMESSAGECONVERSI * sync events for that folder by specifying the corresponding GUID in * the NEWLOGON object. */ -#define PR_SYNCEVENT_SUPPRESS_GUID PROP_TAG( PT_BINARY, 0x3880 ) +#define PR_SYNCEVENT_SUPPRESS_GUID PROP_TAG(PT_BINARY, 0x3880) /* * The following are the well-known GUIDS for the different special folders. @@ -2427,7 +2206,7 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeMessageConversion, LPEXCHANGEMESSAGECONVERSI * each folder. */ // {B2DC5B57-AF2D-4915-BAE3-90E5BDFB0070} -//static const GUID guidOutboxSyncEvents = +// static const GUID guidOutboxSyncEvents = //{ // 0xb2dc5b57, 0xaf2d, 0x4915, // { @@ -2436,7 +2215,7 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeMessageConversion, LPEXCHANGEMESSAGECONVERSI //}; // // {2185EE91-28CD-4d9b-BFB4-BC49BB1DD8C0} -//static const GUID guidMTSInSyncEvents = +// static const GUID guidMTSInSyncEvents = //{ // 0x2185ee91, 0x28cd, 0x4d9b, // { @@ -2445,7 +2224,7 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeMessageConversion, LPEXCHANGEMESSAGECONVERSI //}; // // {1BDBAFD3-1384-449b-A200-DE4745B07839} -//static const GUID guidMTSOutSyncEvents = +// static const GUID guidMTSOutSyncEvents = //{ // 0x1bdbafd3, 0x1384, 0x449b, // { @@ -2454,7 +2233,7 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeMessageConversion, LPEXCHANGEMESSAGECONVERSI //}; // // {221ED74D-0B5C-4c0e-8807-23AFDD8AC2FF} -//static const GUID guidTransportTempFolderSyncEvents = +// static const GUID guidTransportTempFolderSyncEvents = //{ // 0x221ed74d, 0xb5c, 0x4c0e, // { @@ -2462,63 +2241,62 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeMessageConversion, LPEXCHANGEMESSAGECONVERSI // } //}; - /* * Lock properties */ - //REVIEW:: some of these definitions appear both in MAPITAGS.H and EDKMDB.H - //one set of definitions should be removed -#define PR_LOCK_BRANCH_ID PROP_TAG( PT_I8, 0x3800 ) -#define PR_LOCK_RESOURCE_FID PROP_TAG( PT_I8, 0x3801 ) -#define PR_LOCK_RESOURCE_DID PROP_TAG( PT_I8, 0x3802 ) -#define PR_LOCK_RESOURCE_VID PROP_TAG( PT_I8, 0x3803 ) -#define PR_LOCK_ENLISTMENT_CONTEXT PROP_TAG( PT_BINARY, 0x3804 ) -#define PR_LOCK_TYPE PROP_TAG( PT_SHORT, 0x3805 ) -#define PR_LOCK_SCOPE PROP_TAG( PT_SHORT, 0x3806 ) -#define PR_LOCK_TRANSIENT_ID PROP_TAG( PT_BINARY, 0x3807 ) -#define PR_LOCK_DEPTH PROP_TAG( PT_LONG, 0x3808 ) -#define PR_LOCK_TIMEOUT PROP_TAG( PT_LONG, 0x3809 ) -#define PR_LOCK_EXPIRY_TIME PROP_TAG( PT_SYSTIME, 0x380a ) -#define PR_LOCK_GLID PROP_TAG( PT_BINARY, 0x380b ) -#define PR_LOCK_NULL_URL_W PROP_TAG( PT_UNICODE, 0x380c ) +// REVIEW:: some of these definitions appear both in MAPITAGS.H and EDKMDB.H +// one set of definitions should be removed +#define PR_LOCK_BRANCH_ID PROP_TAG(PT_I8, 0x3800) +#define PR_LOCK_RESOURCE_FID PROP_TAG(PT_I8, 0x3801) +#define PR_LOCK_RESOURCE_DID PROP_TAG(PT_I8, 0x3802) +#define PR_LOCK_RESOURCE_VID PROP_TAG(PT_I8, 0x3803) +#define PR_LOCK_ENLISTMENT_CONTEXT PROP_TAG(PT_BINARY, 0x3804) +#define PR_LOCK_TYPE PROP_TAG(PT_SHORT, 0x3805) +#define PR_LOCK_SCOPE PROP_TAG(PT_SHORT, 0x3806) +#define PR_LOCK_TRANSIENT_ID PROP_TAG(PT_BINARY, 0x3807) +#define PR_LOCK_DEPTH PROP_TAG(PT_LONG, 0x3808) +#define PR_LOCK_TIMEOUT PROP_TAG(PT_LONG, 0x3809) +#define PR_LOCK_EXPIRY_TIME PROP_TAG(PT_SYSTIME, 0x380a) +#define PR_LOCK_GLID PROP_TAG(PT_BINARY, 0x380b) +#define PR_LOCK_NULL_URL_W PROP_TAG(PT_UNICODE, 0x380c) /* * Lock flags */ -#define LOCK_NON_PERSISTENT 0x00000001 -#define LOCK_BLOCKING_MID_LOCK 0x00000002 -#define LOCK_NULL_RESOURCE 0x00000004 -#define LOCK_READ_ACCESS_CHECK_ONLY 0x00000008 -#define LOCK_WRITE_THROUGH_GOP 0x00010000 +#define LOCK_NON_PERSISTENT 0x00000001 +#define LOCK_BLOCKING_MID_LOCK 0x00000002 +#define LOCK_NULL_RESOURCE 0x00000004 +#define LOCK_READ_ACCESS_CHECK_ONLY 0x00000008 +#define LOCK_WRITE_THROUGH_GOP 0x00010000 // This bit is reserved and must not be set! -#define LOCK_RESERVED 0x80000000 +#define LOCK_RESERVED 0x80000000 /* * Unlock flags */ -#define UNLOCK_CHECKIN_ABORT 0x00000001 -#define UNLOCK_CHECKIN_KEEP_LOCKED 0x00000002 -#define UNLOCK_BLOCKING_MID_LOCK_ALL 0x00000004 -#define UNLOCK_BLOCKING_MID_LOCK_LOGON_ONLY 0x00000008 -#define UNLOCK_NULL_RESOURCE 0x00000010 -#define UNLOCK_WRITE_THROUGH_GOP 0x00010000 +#define UNLOCK_CHECKIN_ABORT 0x00000001 +#define UNLOCK_CHECKIN_KEEP_LOCKED 0x00000002 +#define UNLOCK_BLOCKING_MID_LOCK_ALL 0x00000004 +#define UNLOCK_BLOCKING_MID_LOCK_LOGON_ONLY 0x00000008 +#define UNLOCK_NULL_RESOURCE 0x00000010 +#define UNLOCK_WRITE_THROUGH_GOP 0x00010000 /* * Versioning flags for folder */ -#define wNonVersionedFolder ((WORD)0x0000) -#define wVersionedFolderSimple ((WORD)0x0001) -#define wVersionedFolderAuto ((WORD)0x0002) //When you auto version it is simple versioned as well. +#define wNonVersionedFolder ((WORD)0x0000) +#define wVersionedFolderSimple ((WORD)0x0001) +#define wVersionedFolderAuto ((WORD)0x0002) // When you auto version it is simple versioned as well. /* * Versioning operation codes for version rows in ptagVersionedOperation */ -#define fVersionedDelete ((ULONG)0x01) -#define fVersionedUnDelete ((ULONG)0x02) -#define fVersionedPin ((ULONG)0x04) -#define fVersionedUnPin ((ULONG)0x08) -#define fVersionedMoveIn ((ULONG)0x10) -#define fVersionedMoveOut ((ULONG)0x20) +#define fVersionedDelete ((ULONG)0x01) +#define fVersionedUnDelete ((ULONG)0x02) +#define fVersionedPin ((ULONG)0x04) +#define fVersionedUnPin ((ULONG)0x08) +#define fVersionedMoveIn ((ULONG)0x10) +#define fVersionedMoveOut ((ULONG)0x20) /*------------------------------------------------------------------------ * @@ -2527,28 +2305,28 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeMessageConversion, LPEXCHANGEMESSAGECONVERSI * These are properties that will be used internally by local store. * Properties that are listed here are used in components other than the local store *-----------------------------------------------------------------------*/ -#define pidLISMsgFolderPropMin pidLocalStoreInternalMin+0xa0 // 0x65a0 -#define pidLISMsgFolderPropMax pidLocalStoreInternalMin+0xc0 // 0x65c0 +#define pidLISMsgFolderPropMin pidLocalStoreInternalMin + 0xa0 // 0x65a0 +#define pidLISMsgFolderPropMax pidLocalStoreInternalMin + 0xc0 // 0x65c0 -#define pidLISErrorCodeMin pidLISMsgFolderPropMin+0xa // 0x65aa -#define pidLISErrorCodeMax pidLISMsgFolderPropMin+0x10 // 0x65b0 +#define pidLISErrorCodeMin pidLISMsgFolderPropMin + 0xa // 0x65aa +#define pidLISErrorCodeMax pidLISMsgFolderPropMin + 0x10 // 0x65b0 -#define pidLISInterfacePropMin pidLocalStoreInternalMin+0xd0 // 0x65d0 -#define pidLISInterfacePropMax pidLocalStoreInternalMin+0xe0 // 0x65e0 +#define pidLISInterfacePropMin pidLocalStoreInternalMin + 0xd0 // 0x65d0 +#define pidLISInterfacePropMax pidLocalStoreInternalMin + 0xe0 // 0x65e0 -#define ptagLISSubfolders PROP_TAG( PT_BOOLEAN, pidLocalStoreInternalMin+0x0) -#define ptagLISUnreadCount PROP_TAG( PT_LONG, pidLocalStoreInternalMin+0x1) +#define ptagLISSubfolders PROP_TAG(PT_BOOLEAN, pidLocalStoreInternalMin + 0x0) +#define ptagLISUnreadCount PROP_TAG(PT_LONG, pidLocalStoreInternalMin + 0x1) -#define ptagLISErrorCode PROP_TAG( PT_LONG, pidLISErrorCodeMin+0x0) // PROP_TAG(PT_LONG, 0x65aa) -#define ptagLISErrorItemType PROP_TAG( PT_LONG, pidLISErrorCodeMin+0x1) // PROP_TAG(PT_LONG, 0x65ab) -#define ptagLISErrorOperation PROP_TAG( PT_LONG, pidLISErrorCodeMin+0x2) // PROP_TAG(PT_LONG, 0x65ac) -#define ptagLISErrorItemUrl PROP_TAG( PT_UNICODE, pidLISErrorCodeMin+0x3) // PROP_TAG(PT_UNICODE, 0x65ad) -#define ptagLISErrorSourceUrl PROP_TAG( PT_UNICODE, pidLISErrorCodeMin+0x4) // PROP_TAG(PT_UNICODE, 0x65ae) -#define ptagLISModifiedPropertyList PROP_TAG( PT_UNICODE, pidLISErrorCodeMin+0x5) // PROP_TAG(PT_UNICODE, 0x65af) -#define ptagLISExtendedErrorinfo PROP_TAG( PT_LONG, pidLISErrorCodeMin+0x6) // PROP_TAG(PT_LONG, 0x65b0) +#define ptagLISErrorCode PROP_TAG(PT_LONG, pidLISErrorCodeMin + 0x0) // PROP_TAG(PT_LONG, 0x65aa) +#define ptagLISErrorItemType PROP_TAG(PT_LONG, pidLISErrorCodeMin + 0x1) // PROP_TAG(PT_LONG, 0x65ab) +#define ptagLISErrorOperation PROP_TAG(PT_LONG, pidLISErrorCodeMin + 0x2) // PROP_TAG(PT_LONG, 0x65ac) +#define ptagLISErrorItemUrl PROP_TAG(PT_UNICODE, pidLISErrorCodeMin + 0x3) // PROP_TAG(PT_UNICODE, 0x65ad) +#define ptagLISErrorSourceUrl PROP_TAG(PT_UNICODE, pidLISErrorCodeMin + 0x4) // PROP_TAG(PT_UNICODE, 0x65ae) +#define ptagLISModifiedPropertyList PROP_TAG(PT_UNICODE, pidLISErrorCodeMin + 0x5) // PROP_TAG(PT_UNICODE, 0x65af) +#define ptagLISExtendedErrorinfo PROP_TAG(PT_LONG, pidLISErrorCodeMin + 0x6) // PROP_TAG(PT_LONG, 0x65b0) // Not in msgfolder prop range -#define ptagLISErrorLogUrl PROP_TAG( PT_UNICODE, pidLocalStoreInternalMin+0x70) // PROP_TAG(PT_UNICODE, 0x6570) +#define ptagLISErrorLogUrl PROP_TAG(PT_UNICODE, pidLocalStoreInternalMin + 0x70) // PROP_TAG(PT_UNICODE, 0x6570) // Ptags used between EXOLEDB and LSCache on client machine to pass // along the actual client SQL query from EXOLEDB to LSCache in the RES_COMMENT @@ -2557,18 +2335,18 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeMessageConversion, LPEXCHANGEMESSAGECONVERSI // // ptagSql = The identifying property for the SQL restriction. // The value will be the original complete clause. -#define ptagSql PROP_TAG(PT_UNICODE, pidLISInterfacePropMin+0x0) -#define ptagSqlSelect PROP_TAG(PT_UNICODE, pidLISInterfacePropMin+0x1) -#define ptagSqlFrom PROP_TAG(PT_UNICODE, pidLISInterfacePropMin+0x2) -#define ptagSqlWhere PROP_TAG(PT_UNICODE, pidLISInterfacePropMin+0x3) -#define ptagSqlOrder PROP_TAG(PT_UNICODE, pidLISInterfacePropMin+0x4) -#define ptagSqlGroup PROP_TAG(PT_UNICODE, pidLISInterfacePropMin+0x5) +#define ptagSql PROP_TAG(PT_UNICODE, pidLISInterfacePropMin + 0x0) +#define ptagSqlSelect PROP_TAG(PT_UNICODE, pidLISInterfacePropMin + 0x1) +#define ptagSqlFrom PROP_TAG(PT_UNICODE, pidLISInterfacePropMin + 0x2) +#define ptagSqlWhere PROP_TAG(PT_UNICODE, pidLISInterfacePropMin + 0x3) +#define ptagSqlOrder PROP_TAG(PT_UNICODE, pidLISInterfacePropMin + 0x4) +#define ptagSqlGroup PROP_TAG(PT_UNICODE, pidLISInterfacePropMin + 0x5) -#define PR_RULE_SERVER_RULE_ID PROP_TAG(PT_I8, pidLISMsgFolderPropMin+0x0) // Corresponding server RUID for LIS +#define PR_RULE_SERVER_RULE_ID PROP_TAG(PT_I8, pidLISMsgFolderPropMin + 0x0) // Corresponding server RUID for LIS // this is a hackish property to be used by sync event code to say that changes // need client refresh. The only valid value is TRUE. See #168797 for more info -#define PR_FORCE_CLIENT_REFRESH PROP_TAG(PT_BOOLEAN, pidLISMsgFolderPropMin+0x1) +#define PR_FORCE_CLIENT_REFRESH PROP_TAG(PT_BOOLEAN, pidLISMsgFolderPropMin + 0x1) /*------------------------------------------------------------------------ * @@ -2578,46 +2356,45 @@ DECLARE_MAPI_INTERFACE_PTR(IExchangeMessageConversion, LPEXCHANGEMESSAGECONVERSI *-----------------------------------------------------------------------*/ // Name and version of anti-virus product that performed the last scan of an item. -#define PR_ANTIVIRUS_VENDOR PROP_TAG(PT_STRING8, pidStoreNonTransMin+0x45) // 0x0E85001E -#define PR_ANTIVIRUS_VERSION PROP_TAG(PT_LONG, pidStoreNonTransMin+0x46) // 0x0E860003 +#define PR_ANTIVIRUS_VENDOR PROP_TAG(PT_STRING8, pidStoreNonTransMin + 0x45) // 0x0E85001E +#define PR_ANTIVIRUS_VERSION PROP_TAG(PT_LONG, pidStoreNonTransMin + 0x46) // 0x0E860003 // Results ot the last scan of an item. -#define PR_ANTIVIRUS_SCAN_STATUS PROP_TAG(PT_LONG, pidStoreNonTransMin+0x47) // 0x0E870003 +#define PR_ANTIVIRUS_SCAN_STATUS PROP_TAG(PT_LONG, pidStoreNonTransMin + 0x47) // 0x0E870003 // List of virus identification strings of all viruses found by the last scan, if virus has been cleaned // or detected, separated by commans. Empty string if no virus has been found. -#define PR_ANTIVIRUS_SCAN_INFO PROP_TAG(PT_STRING8, pidStoreNonTransMin+0x48) // 0x0E88001F +#define PR_ANTIVIRUS_SCAN_INFO PROP_TAG(PT_STRING8, pidStoreNonTransMin + 0x48) // 0x0E88001F /* * Possible values of PR_ANTIVIRUS_SCAN_STATUS */ // Anti-virus product has completed scanning of an item, and found no virus. -#define ANTIVIRUS_SCAN_NO_VIRUS 0 +#define ANTIVIRUS_SCAN_NO_VIRUS 0 // Anti-virus product has detected a virus in an item, or assumed the item may contain a virus // based on item's properties, like filename or content type. -#define ANTIVIRUS_SCAN_VIRUS_PRESENT 1 +#define ANTIVIRUS_SCAN_VIRUS_PRESENT 1 // Anti-virus product has detected a virus in an item, and applied changes to remove the virus. // The item should be safe to use after modifications. -#define ANTIVIRUS_SCAN_VIRUS_CLEANED 2 +#define ANTIVIRUS_SCAN_VIRUS_CLEANED 2 // Anti-virus product has detected a virus in an item, and has requested that the message be // deleted. This item shouldn't be allowed to be opened. -#define ANTIVIRUS_SCAN_VIRUS_DELETED 3 +#define ANTIVIRUS_SCAN_VIRUS_DELETED 3 // Presents the same list as PR_DISPLAY_TO except uses the format "[addrtype1:addr1]; [addrtype2:addr2]" -#define PR_ADDR_TO PROP_TAG(PT_TSTRING, pidStoreNonTransMin+0x57) // 0x0E97 -#define PR_ADDR_TO_A PROP_TAG(PT_STRING8, pidStoreNonTransMin+0x57) -#define PR_ADDR_TO_W PROP_TAG(PT_UNICODE, pidStoreNonTransMin+0x57) +#define PR_ADDR_TO PROP_TAG(PT_TSTRING, pidStoreNonTransMin + 0x57) // 0x0E97 +#define PR_ADDR_TO_A PROP_TAG(PT_STRING8, pidStoreNonTransMin + 0x57) +#define PR_ADDR_TO_W PROP_TAG(PT_UNICODE, pidStoreNonTransMin + 0x57) // Presents the same list as PR_DISPLAY_CC except uses the format "[addrtype1:addr1]; [addrtype2:addr2]" -#define PR_ADDR_CC PROP_TAG(PT_TSTRING, pidStoreNonTransMin+0x58) // 0x0E98 -#define PR_ADDR_CC_A PROP_TAG(PT_STRING8, pidStoreNonTransMin+0x58) -#define PR_ADDR_CC_W PROP_TAG(PT_UNICODE, pidStoreNonTransMin+0x58) - +#define PR_ADDR_CC PROP_TAG(PT_TSTRING, pidStoreNonTransMin + 0x58) // 0x0E98 +#define PR_ADDR_CC_A PROP_TAG(PT_STRING8, pidStoreNonTransMin + 0x58) +#define PR_ADDR_CC_W PROP_TAG(PT_UNICODE, pidStoreNonTransMin + 0x58) // This property IS NO LONGER USED. I've left it here to avoid possible build break. -#define ptagLISNewMail PROP_TAG(PT_BOOLEAN, 0x65c5) +#define ptagLISNewMail PROP_TAG(PT_BOOLEAN, 0x65c5) -#endif //EDKMDB_INCLUDED +#endif // EDKMDB_INCLUDED diff --git a/com/win32comext/mapi/src/mapi_stub_library/StubUtils.cpp b/com/win32comext/mapi/src/mapi_stub_library/StubUtils.cpp index 707bd2a9d8..898a73fedb 100644 --- a/com/win32comext/mapi/src/mapi_stub_library/StubUtils.cpp +++ b/com/win32comext/mapi/src/mapi_stub_library/StubUtils.cpp @@ -234,24 +234,21 @@ HMODULE LoadRegisteredMapiClient(LPCWSTR pwzProviderOverride) if (!pwzProvider) { // Get Outlook application path registry value DWORD dwSize = sizeof(rgchMailClient); - if - SUCCEEDED(RegQueryValueExW(hkey, nullptr, 0, &dwType, (LPBYTE)&rgchMailClient, &dwSize)) + if SUCCEEDED (RegQueryValueExW(hkey, nullptr, 0, &dwType, (LPBYTE)&rgchMailClient, &dwSize)) - if (dwType != REG_SZ) - goto Error; + if (dwType != REG_SZ) + goto Error; pwzProvider = rgchMailClient; } if (pwzProvider) { - if - SUCCEEDED(RegOpenKeyExW(hkey, pwzProvider, 0, KEY_READ, &hkeyMapiClient)) - { - hinstMapi = LoadMailClientFromMSIData(hkeyMapiClient); - - if (!hinstMapi) - hinstMapi = LoadMailClientFromDllPath(hkeyMapiClient); - } + if SUCCEEDED (RegOpenKeyExW(hkey, pwzProvider, 0, KEY_READ, &hkeyMapiClient)) { + hinstMapi = LoadMailClientFromMSIData(hkeyMapiClient); + + if (!hinstMapi) + hinstMapi = LoadMailClientFromDllPath(hkeyMapiClient); + } } } diff --git a/com/win32comext/mapi/src/mapiutil.cpp b/com/win32comext/mapi/src/mapiutil.cpp index e09e03c1da..b704c77f6e 100644 --- a/com/win32comext/mapi/src/mapiutil.cpp +++ b/com/win32comext/mapi/src/mapiutil.cpp @@ -512,7 +512,7 @@ PyObject *PyMAPIObject_FromSPropValue(SPropValue *pv) default: printf("File %s: Unsupported MAPI property type 0x%X", __FILE__, PROP_TYPE(pv->ulPropTag)); - /* Dont set exception, as this prevents otherwise valid props from + /* Don't set exception, as this prevents otherwise valid props from being returned */ val = Py_None; diff --git a/com/win32comext/propsys/src/propsys.cpp b/com/win32comext/propsys/src/propsys.cpp index 613f540fba..f92f5a0aab 100644 --- a/com/win32comext/propsys/src/propsys.cpp +++ b/com/win32comext/propsys/src/propsys.cpp @@ -309,7 +309,7 @@ static PyObject *PyStgDeserializePropVariant(PyObject *self, PyObject *args) if (!pybuf.ok()) return NULL; PY_INTERFACE_PRECALL; - hr = StgDeserializePropVariant((SERIALIZEDPROPERTYVALUE*)pybuf.ptr(), pybuf.len(), &pv); + hr = StgDeserializePropVariant((SERIALIZEDPROPERTYVALUE *)pybuf.ptr(), pybuf.len(), &pv); PY_INTERFACE_POSTCALL; if (FAILED(hr)) return PyCom_BuildPyException(hr); diff --git a/com/win32comext/shell/demos/IFileOperationProgressSink.py b/com/win32comext/shell/demos/IFileOperationProgressSink.py index b327707404..9c73f544aa 100644 --- a/com/win32comext/shell/demos/IFileOperationProgressSink.py +++ b/com/win32comext/shell/demos/IFileOperationProgressSink.py @@ -15,7 +15,7 @@ def decode_flags(flags): for k, v in tsf_flags: if flags & v: if flag_txt: - flag_txt = flag_txt + "|" + k + flag_txt += "|" + k else: flag_txt = k return flag_txt diff --git a/com/win32comext/shell/demos/ITransferAdviseSink.py b/com/win32comext/shell/demos/ITransferAdviseSink.py index ae4a7dea71..a0a696e2f1 100644 --- a/com/win32comext/shell/demos/ITransferAdviseSink.py +++ b/com/win32comext/shell/demos/ITransferAdviseSink.py @@ -19,7 +19,7 @@ def decode_flags(flags): for k, v in tsf_flags: if flags & v: if flag_txt: - flag_txt = flag_txt + "|" + k + flag_txt += "|" + k else: flag_txt = k return flag_txt diff --git a/com/win32comext/shell/demos/explorer_browser.py b/com/win32comext/shell/demos/explorer_browser.py index 14dc2fa91d..faef813184 100644 --- a/com/win32comext/shell/demos/explorer_browser.py +++ b/com/win32comext/shell/demos/explorer_browser.py @@ -35,7 +35,7 @@ def OnViewCreated(self, view): # be that view! try: pyview = unwrap(view) - print("and look - its a Python implemented view!", pyview) + print("and look - it's a Python implemented view!", pyview) except ValueError: pass diff --git a/com/win32comext/shell/demos/servers/empty_volume_cache.py b/com/win32comext/shell/demos/servers/empty_volume_cache.py index 6d5a90198c..084e97c4f6 100644 --- a/com/win32comext/shell/demos/servers/empty_volume_cache.py +++ b/com/win32comext/shell/demos/servers/empty_volume_cache.py @@ -87,14 +87,14 @@ def _GetDirectories(self): ] def _WalkCallback(self, arg, directory, files): - # callback function for os.path.walk - no need to be member, but its + # callback function for os.path.walk - no need to be member, but it's # close to the callers :) callback, total_list = arg for file in files: fqn = os.path.join(directory, file).lower() if file.endswith(".pyc") or file.endswith(".pyo"): # See below - total_list is None means delete files, - # otherwise it is a list where the result is stored. Its a + # otherwise it is a list where the result is stored. It's a # list simply due to the way os.walk works - only [0] is # referenced if total_list is None: diff --git a/com/win32comext/shell/demos/servers/folder_view.py b/com/win32comext/shell/demos/servers/folder_view.py index 7651f1503d..a26ac840ef 100644 --- a/com/win32comext/shell/demos/servers/folder_view.py +++ b/com/win32comext/shell/demos/servers/folder_view.py @@ -58,7 +58,7 @@ def _make_ids(s): # These strings are what the user sees and would be localized. -# XXX - its possible that the shell might persist these values, so +# XXX - it's possible that the shell might persist these values, so # this scheme wouldn't really be suitable in a real ap. IDS_UNSPECIFIED = _make_ids("unspecified") IDS_SMALL = _make_ids("small") @@ -529,7 +529,7 @@ def QueryContextMenu(self, hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags): def InvokeCommand(self, ci): mask, hwnd, verb, params, dir, nShow, hotkey, hicon = ci - # this seems very convuluted, but its what the sample does :) + # this seems very convuluted, but it's what the sample does :) for verb_name, verb_id, flag in folderViewImplContextMenuIDs: if isinstance(verb, int): matches = verb == verb_id @@ -538,12 +538,12 @@ def InvokeCommand(self, ci): if matches: break else: - assert False, ci # failed to find our ID + raise AssertionError(ci, "failed to find our ID") if verb_id == MENUVERB_DISPLAY: sia = shell.SHCreateShellItemArrayFromDataObject(self.dataobj) DisplayItem(hwnd, sia) else: - assert False, ci # Got some verb we weren't expecting? + raise AssertionError(ci, "Got some verb we weren't expecting?") def GetCommandString(self, cmd, typ): raise COMException(hresult=winerror.E_NOTIMPL) @@ -642,7 +642,7 @@ def GetAttributesOf(self, pidls, attrFlags): # Retrieves an OLE interface that can be used to carry out # actions on the specified file objects or folders. def GetUIObjectOf(self, hwndOwner, pidls, iid, inout): - assert len(pidls) == 1, "oops - arent expecting more than one!" + assert len(pidls) == 1, "oops - aren't expecting more than one!" assert len(pidls[0]) == 1, "assuming relative pidls!" item = pidl_to_item(pidls[0]) if iid == shell.IID_IContextMenu: @@ -780,7 +780,7 @@ def MapColumnToSCID(self, iCol): # IPersistFolder2 methods # Retrieves the PIDLIST_ABSOLUTE for the folder object. def GetCurFolder(self): - # The docs say this is OK, but I suspect its a problem in this case :) + # The docs say this is OK, but I suspect it's a problem in this case :) # assert self.pidl, "haven't been initialized?" return self.pidl diff --git a/com/win32comext/shell/demos/servers/shell_view.py b/com/win32comext/shell/demos/servers/shell_view.py index f50977933f..a42e9484e9 100644 --- a/com/win32comext/shell/demos/servers/shell_view.py +++ b/com/win32comext/shell/demos/servers/shell_view.py @@ -175,7 +175,7 @@ def CompareIDs(self, param, id1, id2): def GetUIObjectOf(self, hwndOwner, pidls, iid, inout): # delegate to the shell. - assert len(pidls) == 1, "oops - arent expecting more than one!" + assert len(pidls) == 1, "oops - aren't expecting more than one!" pidl = pidls[0] folder, child_pidl = self._GetFolderAndPIDLForPIDL(pidl) try: diff --git a/com/win32comext/shell/shellcon.py b/com/win32comext/shell/shellcon.py index 37841a9710..90a5073ebb 100644 --- a/com/win32comext/shell/shellcon.py +++ b/com/win32comext/shell/shellcon.py @@ -856,12 +856,12 @@ def EIRESID(x): ASSOCF_OPEN_BYEXENAME = 0x00000002 # executable is being passed in ASSOCF_INIT_DEFAULTTOSTAR = 0x00000004 # treat "*" as the BaseClass ASSOCF_INIT_DEFAULTTOFOLDER = 0x00000008 # treat "Folder" as the BaseClass -ASSOCF_NOUSERSETTINGS = 0x00000010 # dont use HKCU -ASSOCF_NOTRUNCATE = 0x00000020 # dont truncate the return string +ASSOCF_NOUSERSETTINGS = 0x00000010 # don't use HKCU +ASSOCF_NOTRUNCATE = 0x00000020 # don't truncate the return string ASSOCF_VERIFY = 0x00000040 # verify data is accurate (DISK HITS) ASSOCF_REMAPRUNDLL = 0x00000080 # actually gets info about rundlls target if applicable ASSOCF_NOFIXUPS = 0x00000100 # attempt to fix errors if found -ASSOCF_IGNOREBASECLASS = 0x00000200 # dont recurse into the baseclass +ASSOCF_IGNOREBASECLASS = 0x00000200 # don't recurse into the baseclass ASSOCSTR_COMMAND = 1 # shell\verb\command string ASSOCSTR_EXECUTABLE = 2 # the executable part of command string diff --git a/com/win32comext/shell/src/PyIQueryAssociations.h b/com/win32comext/shell/src/PyIQueryAssociations.h index 416b6273e8..5eaba23acb 100644 --- a/com/win32comext/shell/src/PyIQueryAssociations.h +++ b/com/win32comext/shell/src/PyIQueryAssociations.h @@ -18,12 +18,12 @@ enum { ASSOCF_OPEN_BYEXENAME = 0x00000002, // executable is being passed in ASSOCF_INIT_DEFAULTTOSTAR = 0x00000004, // treat "*" as the BaseClass ASSOCF_INIT_DEFAULTTOFOLDER = 0x00000008, // treat "Folder" as the BaseClass - ASSOCF_NOUSERSETTINGS = 0x00000010, // dont use HKCU - ASSOCF_NOTRUNCATE = 0x00000020, // dont truncate the return string + ASSOCF_NOUSERSETTINGS = 0x00000010, // don't use HKCU + ASSOCF_NOTRUNCATE = 0x00000020, // don't truncate the return string ASSOCF_VERIFY = 0x00000040, // verify data is accurate (DISK HITS) ASSOCF_REMAPRUNDLL = 0x00000080, // actually gets info about rundlls target if applicable ASSOCF_NOFIXUPS = 0x00000100, // attempt to fix errors if found - ASSOCF_IGNOREBASECLASS = 0x00000200, // dont recurse into the baseclass + ASSOCF_IGNOREBASECLASS = 0x00000200, // don't recurse into the baseclass }; typedef DWORD ASSOCF; #define LWSTDAPI STDAPI diff --git a/com/win32comext/shell/src/PyIShellFolder.cpp b/com/win32comext/shell/src/PyIShellFolder.cpp index 2a4341224b..65cc210d02 100644 --- a/com/win32comext/shell/src/PyIShellFolder.cpp +++ b/com/win32comext/shell/src/PyIShellFolder.cpp @@ -217,14 +217,14 @@ PyObject *PyIShellFolder::CompareIDs(PyObject *self, PyObject *args) PyCom_BuildPyException(hr, pISF, IID_IShellFolder); else // special handling of hresult if ((short)HRESULT_CODE(hr) < 0) - /* pidl1 comes first */ - ret = PyLong_FromLong(-1); - else if ((short)HRESULT_CODE(hr) > 0) - /* pidl2 comes first */ - ret = PyLong_FromLong(1); - else - /* the two pidls are equal */ - ret = PyLong_FromLong(0); + /* pidl1 comes first */ + ret = PyLong_FromLong(-1); + else if ((short)HRESULT_CODE(hr) > 0) + /* pidl2 comes first */ + ret = PyLong_FromLong(1); + else + /* the two pidls are equal */ + ret = PyLong_FromLong(0); } PyObject_FreePIDL(pidl1); PyObject_FreePIDL(pidl2); diff --git a/com/win32comext/shell/src/PyITransferAdviseSink.cpp b/com/win32comext/shell/src/PyITransferAdviseSink.cpp index 5e8d8db165..697ba69e8c 100644 --- a/com/win32comext/shell/src/PyITransferAdviseSink.cpp +++ b/com/win32comext/shell/src/PyITransferAdviseSink.cpp @@ -385,11 +385,9 @@ STDMETHODIMP PyGTransferAdviseSink::SubStreamFailure( HRESULT hr = InvokeViaPolicy("SubStreamFailure", &result, "OOl", obpsi, obpszStreamName, hrError); Py_XDECREF(obpsi); Py_XDECREF(obpszStreamName); - if - FAILED(hr) - hr = MAKE_PYCOM_GATEWAY_FAILURE_CODE("SubStreamFailure"); - else - { + if FAILED (hr) + hr = MAKE_PYCOM_GATEWAY_FAILURE_CODE("SubStreamFailure"); + else { hr = PyLong_AsLong(result); if (hr == -1 && PyErr_Occurred()) hr = MAKE_PYCOM_GATEWAY_FAILURE_CODE("SubStreamFailure"); @@ -418,11 +416,9 @@ STDMETHODIMP PyGTransferAdviseSink::PropertyFailure( HRESULT hr = InvokeViaPolicy("PropertyFailure", &result, "OOl", obpsi, obkey, hrError); Py_XDECREF(obpsi); Py_DECREF(obkey); - if - FAILED(hr) - hr = MAKE_PYCOM_GATEWAY_FAILURE_CODE("PropertyFailure"); - else - { + if FAILED (hr) + hr = MAKE_PYCOM_GATEWAY_FAILURE_CODE("PropertyFailure"); + else { hr = PyLong_AsLong(result); if (hr == -1 && PyErr_Occurred()) hr = MAKE_PYCOM_GATEWAY_FAILURE_CODE("PropertyFailure"); diff --git a/com/win32comext/shell/src/shell.cpp b/com/win32comext/shell/src/shell.cpp index 757647b672..27d51f8d6f 100644 --- a/com/win32comext/shell/src/shell.cpp +++ b/com/win32comext/shell/src/shell.cpp @@ -241,7 +241,7 @@ PyObject *PyObject_FromPIDL(LPCITEMIDLIST pidl, BOOL bFreeSystemPIDL) } // The length may be too large to read (and causing an // exception deep inside Python doesn't always leave - // things in a good state! Its also inconvenient to + // things in a good state! It's also inconvenient to // always pass the size of the object - so explicitly // check we can read the memory. UINT cbdata = pidl->mkid.cb - sizeof(pidl->mkid.cb); @@ -2802,7 +2802,7 @@ static PyObject *PySHCreateShellFolderView(PyObject *self, PyObject *args) else ret = PyCom_PyObjectFromIUnknown(view, IID_IShellView, FALSE); // ref on view consumed by ret object. -done : { +done: { PY_INTERFACE_PRECALL; if (create.pshf) create.pshf->Release(); diff --git a/com/win32comext/taskscheduler/src/PyIScheduledWorkItem.cpp b/com/win32comext/taskscheduler/src/PyIScheduledWorkItem.cpp index 261c532d07..84baabeab9 100644 --- a/com/win32comext/taskscheduler/src/PyIScheduledWorkItem.cpp +++ b/com/win32comext/taskscheduler/src/PyIScheduledWorkItem.cpp @@ -488,7 +488,7 @@ PyObject *PyIScheduledWorkItem::SetWorkItemData(PyObject *self, PyObject *args) else // Task Scheduler won't take an empty string for data anymore ?????? if (data_len == 0) - workitem_data = NULL; + workitem_data = NULL; } HRESULT hr; diff --git a/com/win32comext/taskscheduler/test/test_addtask_1.py b/com/win32comext/taskscheduler/test/test_addtask_1.py index 284e3511e0..5f1356af17 100644 --- a/com/win32comext/taskscheduler/test/test_addtask_1.py +++ b/com/win32comext/taskscheduler/test/test_addtask_1.py @@ -36,7 +36,7 @@ new_task.SetApplicationName("py.exe") new_task.SetPriority(taskscheduler.REALTIME_PRIORITY_CLASS) new_task.SetParameters( - "-c\"import win32ui,time;win32ui.MessageBox('why aint you doing no work ?');\"" + "-c\"import win32ui,time;win32ui.MessageBox('why ain't you doing no work ?');\"" ) new_task.SetCreator("test_addtask_1.py") new_task.SetAccountInformation(win32api.GetUserName(), None) diff --git a/isapi/install.py b/isapi/install.py index 55235e8791..157d2735a2 100644 --- a/isapi/install.py +++ b/isapi/install.py @@ -364,7 +364,7 @@ def _AssignScriptMapsReplace(target, script_maps): def _AssignScriptMapsEnd(target, script_maps): unique_new_maps = get_unique_items(script_maps, target.ScriptMaps) - target.ScriptMaps = target.ScriptMaps + unique_new_maps + target.ScriptMaps += unique_new_maps def _AssignScriptMapsStart(target, script_maps): diff --git a/isapi/src/PyExtensionObjects.cpp b/isapi/src/PyExtensionObjects.cpp index 3351979dcc..19208c19f4 100644 --- a/isapi/src/PyExtensionObjects.cpp +++ b/isapi/src/PyExtensionObjects.cpp @@ -23,14 +23,13 @@ ====================================================================== */ -//#define PY_SSIZE_T_CLEAN // defined by isapi\src\StdAfx.h +// #define PY_SSIZE_T_CLEAN // defined by isapi\src\StdAfx.h #include "stdafx.h" #include "pywintypes.h" #include "Utils.h" #include "PyExtensionObjects.h" #include "PythonEng.h" - // Asynch IO callbacks are a little tricky, as we never know how many // callbacks a single connection might make (often each callback will trigger // another IO request.) So we keep the Python objects used by the callback @@ -122,7 +121,7 @@ extern "C" void WINAPI DoIOCallback(EXTENSION_CONTROL_BLOCK *ecb, PVOID pContext Py_DECREF(result); worked = TRUE; done: - // If the callback failed, then its likely this request will end + // If the callback failed, then it's likely this request will end // up hanging. So on error we nuke ourselves from the map then // call DoneWithSession. We still hold the GIL, so we should be // safe from races... @@ -176,7 +175,9 @@ PyObject *PyVERSION_INFO::getattro(PyObject *self, PyObject *obname) PyVERSION_INFO *me = (PyVERSION_INFO *)self; if (!me->m_pvi) return PyErr_Format(PyExc_RuntimeError, "VERSION_INFO structure no longer exists"); - TmpWCHAR name = obname; if (!name) return NULL; + TmpWCHAR name = obname; + if (!name) + return NULL; if (_tcscmp(name, _T("ExtensionDesc")) == 0) { return PyBytes_FromString(me->m_pvi->lpszExtensionDesc); } @@ -186,7 +187,9 @@ PyObject *PyVERSION_INFO::getattro(PyObject *self, PyObject *obname) int PyVERSION_INFO::setattro(PyObject *self, PyObject *obname, PyObject *v) { PyVERSION_INFO *me = (PyVERSION_INFO *)self; - TmpWCHAR name = obname; if (!name) return -1; + TmpWCHAR name = obname; + if (!name) + return -1; if (!me->m_pvi) { PyErr_Format(PyExc_RuntimeError, "VERSION_INFO structure no longer exists"); return -1; @@ -345,7 +348,9 @@ PyECB::~PyECB() PyObject *PyECB::getattro(PyObject *self, PyObject *obname) { - TmpWCHAR name = obname; if (!name) return NULL; + TmpWCHAR name = obname; + if (!name) + return NULL; if (_tcscmp(name, _T("softspace")) == 0) // help 'print' semantics. return PyLong_FromLong(1); @@ -385,7 +390,9 @@ int PyECB::setattro(PyObject *self, PyObject *obname, PyObject *v) PyErr_SetString(PyExc_AttributeError, "can't delete ECB attributes"); return -1; } - TmpWCHAR name = obname; if (!name) return -1; + TmpWCHAR name = obname; + if (!name) + return -1; if (_tcscmp(name, _T("HttpStatusCode")) == 0) { PyECB *pecb = (PyECB *)self; @@ -683,9 +690,11 @@ PyObject *PyECB::GetAnonymousToken(PyObject *self, PyObject *args) Py_END_ALLOW_THREADS } else if (PyUnicode_Check(obStr)) { - TmpWCHAR tmpw = obStr; if (!tmpw) return NULL; - Py_BEGIN_ALLOW_THREADS bRes = ecb->ServerSupportFunction(ecb->ConnID, HSE_REQ_GET_UNICODE_ANONYMOUS_TOKEN, - tmpw, (DWORD *)&handle, NULL); + TmpWCHAR tmpw = obStr; + if (!tmpw) + return NULL; + Py_BEGIN_ALLOW_THREADS bRes = + ecb->ServerSupportFunction(ecb->ConnID, HSE_REQ_GET_UNICODE_ANONYMOUS_TOKEN, tmpw, (DWORD *)&handle, NULL); Py_END_ALLOW_THREADS } else diff --git a/isapi/src/PyFilterObjects.cpp b/isapi/src/PyFilterObjects.cpp index 312d69de8e..0239313f0c 100644 --- a/isapi/src/PyFilterObjects.cpp +++ b/isapi/src/PyFilterObjects.cpp @@ -23,7 +23,7 @@ ====================================================================== */ -//#define PY_SSIZE_T_CLEAN // defined by isapi\src\StdAfx.h +// #define PY_SSIZE_T_CLEAN // defined by isapi\src\StdAfx.h #include "stdafx.h" #include "pywintypes.h" #include "Utils.h" @@ -69,7 +69,9 @@ PyObject *PyFILTER_VERSION::getattro(PyObject *self, PyObject *obname) PyFILTER_VERSION *me = (PyFILTER_VERSION *)self; if (!me->m_pfv) return PyErr_Format(PyExc_RuntimeError, "FILTER_VERSION structure no longer exists"); - TmpWCHAR name = obname; if (!name) return NULL; + TmpWCHAR name = obname; + if (!name) + return NULL; // @prop int|ServerFilterVersion|(read-only) if (_tcscmp(name, _T("ServerFilterVersion")) == 0) { return PyLong_FromLong(me->m_pfv->dwServerFilterVersion); @@ -100,7 +102,9 @@ int PyFILTER_VERSION::setattro(PyObject *self, PyObject *obname, PyObject *v) PyErr_SetString(PyExc_AttributeError, "can't delete FILTER_VERSION attributes"); return -1; } - TmpWCHAR name = obname; if (!name) return -1; + TmpWCHAR name = obname; + if (!name) + return -1; if (_tcscmp(name, _T("FilterVersion")) == 0) { if (!PyLong_Check(v)) { PyErr_Format(PyExc_ValueError, "FilterVersion must be an int (got %s)", v->ob_type->tp_name); @@ -416,7 +420,9 @@ PyHFC::~PyHFC() PyObject *PyHFC::getattro(PyObject *self, PyObject *obname) { - TmpWCHAR name = obname; if (!name) return NULL; + TmpWCHAR name = obname; + if (!name) + return NULL; // other manual attributes. if (_tcscmp(name, _T("FilterContext")) == 0) { @@ -435,7 +441,9 @@ PyObject *PyHFC::getattro(PyObject *self, PyObject *obname) int PyHFC::setattro(PyObject *self, PyObject *obname, PyObject *v) { - TmpWCHAR name = obname; if (!name) return -1; + TmpWCHAR name = obname; + if (!name) + return -1; if (v == NULL) { PyErr_SetString(PyExc_AttributeError, "can't delete ECB attributes"); return -1; @@ -537,7 +545,9 @@ PyObject *PyURL_MAP::getattro(PyObject *self, PyObject *obname) if (!pMap) return NULL; // @prop string|URL| - TmpWCHAR name = obname; if (!name) return NULL; + TmpWCHAR name = obname; + if (!name) + return NULL; if (_tcscmp(name, _T("URL")) == 0) { return PyBytes_FromString(pMap->pszURL); } @@ -553,7 +563,9 @@ int PyURL_MAP::setattro(PyObject *self, PyObject *obname, PyObject *v) HTTP_FILTER_URL_MAP *pMap = ((PyURL_MAP *)self)->GetURLMap(); if (!pMap) return NULL; - TmpWCHAR name = obname; if (!name) return -1; + TmpWCHAR name = obname; + if (!name) + return -1; if (_tcscmp(name, _T("PhysicalPath")) == 0) { if (!PyBytes_Check(v)) { PyErr_Format(PyExc_TypeError, "PhysicalPath must be a string"); @@ -780,7 +792,9 @@ PyObject *PyRAW_DATA::getattro(PyObject *self, PyObject *obname) if (!pRD) return NULL; // @prop string|InData| - TmpWCHAR name = obname; if (!name) return NULL; + TmpWCHAR name = obname; + if (!name) + return NULL; if (_tcscmp(name, _T("InData")) == 0) { if (pRD->pvInData == NULL) { Py_INCREF(Py_None); @@ -800,7 +814,9 @@ int PyRAW_DATA::setattro(PyObject *self, PyObject *obname, PyObject *v) if (!pRD || !pFC) return NULL; - TmpWCHAR name = obname; if (!name) return -1; + TmpWCHAR name = obname; + if (!name) + return -1; if (_tcscmp(name, _T("InData")) == 0) { if (!PyBytes_Check(v)) { PyErr_Format(PyExc_TypeError, "InData must be a string (got %s)", v->ob_type->tp_name); @@ -886,7 +902,9 @@ PyObject *PyAUTHENT::getattro(PyObject *self, PyObject *obname) HTTP_FILTER_AUTHENT *pAE = ((PyAUTHENT *)self)->GetAUTHENT(); if (!pAE) return NULL; - TmpWCHAR name = obname; if (!name) return NULL; + TmpWCHAR name = obname; + if (!name) + return NULL; // @prop string|User| if (_tcscmp(name, _T("User")) == 0) { if (pAE->pszUser == NULL) { @@ -914,7 +932,9 @@ int PyAUTHENT::setattro(PyObject *self, PyObject *obname, PyObject *v) if (!pAE || !pFC) return NULL; - TmpWCHAR name = obname; if (!name) return -1; + TmpWCHAR name = obname; + if (!name) + return -1; if (_tcscmp(name, _T("User")) == 0) { if (!PyBytes_Check(v)) { PyErr_Format(PyExc_TypeError, "User must be a string (got %s)", v->ob_type->tp_name); @@ -999,7 +1019,9 @@ PyObject *PyFILTER_LOG::getattro(PyObject *self, PyObject *obname) HTTP_FILTER_LOG *pLog = ((PyFILTER_LOG *)self)->GetFilterLog(); if (!pLog) return NULL; - TmpWCHAR name = obname; if (!name) return NULL; + TmpWCHAR name = obname; + if (!name) + return NULL; // @prop string|ClientHostName| if (_tcscmp(name, _T("ClientHostName")) == 0) return PyBytes_FromString(pLog->pszClientHostName); @@ -1032,28 +1054,28 @@ PyObject *PyFILTER_LOG::getattro(PyObject *self, PyObject *obname) #define CHECK_SET_FILTER_LOG_STRING(struct_elem) \ if (_tcscmp(name, _T(#struct_elem)) == 0) { \ - if (!PyBytes_Check(v)) { \ + if (!PyBytes_Check(v)) { \ PyErr_Format(PyExc_TypeError, #struct_elem " must be a string"); \ return -1; \ } \ - int cc = PyBytes_Size(v) + sizeof(CHAR); \ + int cc = PyBytes_Size(v) + sizeof(CHAR); \ char *buf = (char *)pFC->AllocMem(pFC, cc, 0); \ if (!buf) { \ PyErr_NoMemory(); \ return -1; \ } \ - strncpy(buf, PyBytes_AS_STRING(v), cc); \ + strncpy(buf, PyBytes_AS_STRING(v), cc); \ pLog->psz##struct_elem = buf; \ return 0; \ } #define CHECK_SET_FILTER_LOG_LONG(struct_elem) \ if (_tcscmp(name, _T(#struct_elem)) == 0) { \ - if (!PyLong_Check(v)) { \ + if (!PyLong_Check(v)) { \ PyErr_Format(PyExc_TypeError, #struct_elem " must be an integer"); \ return -1; \ } \ - pLog->dw##struct_elem = PyLong_AsLong(v); \ + pLog->dw##struct_elem = PyLong_AsLong(v); \ return 0; \ } @@ -1064,7 +1086,9 @@ int PyFILTER_LOG::setattro(PyObject *self, PyObject *obname, PyObject *v) HTTP_FILTER_LOG *pLog = ((PyFILTER_LOG *)self)->GetFilterLog(); if (!pLog || !pFC) return NULL; - TmpWCHAR name = obname; if (!name) return -1; + TmpWCHAR name = obname; + if (!name) + return -1; CHECK_SET_FILTER_LOG_STRING(ClientHostName) CHECK_SET_FILTER_LOG_STRING(ClientUserName) CHECK_SET_FILTER_LOG_STRING(ServerName) diff --git a/isapi/threaded_extension.py b/isapi/threaded_extension.py index ecf24c8460..310bbb84be 100644 --- a/isapi/threaded_extension.py +++ b/isapi/threaded_extension.py @@ -176,7 +176,7 @@ def HandleDispatchError(self, ecb): ) except ExtensionError: # The client disconnected without reading the error body - - # its probably not a real browser at the other end, ignore it. + # it's probably not a real browser at the other end, ignore it. pass except: print("FAILED to render the error message!") diff --git a/mypy.ini b/mypy.ini index 34ac87ef01..eb8e23ae9e 100644 --- a/mypy.ini +++ b/mypy.ini @@ -35,16 +35,16 @@ disable_error_code = ; Cannot assign to a method (we do lots of monkey patching) method-assign, exclude = (?x)( - ^build/ - ; Vendored - | ^Pythonwin/Scintilla/ - ; Forked IDLE extensions predating Python 2.3. They now live in idlelib in https://github.com/python/cpython/tree/main/Lib/idlelib - | ^Pythonwin/pywin/idle/ - ; TODO: adodbapi should be updated and fixed separately - | ^adodbapi/ - ; TODO: Ignoring non-public APIs until all public API is typed - | ([Tt]est|[Dd]emos?)/ - ) + ^build/ + ; Vendored + | ^Pythonwin/Scintilla/ + ; Forked IDLE extensions predating Python 2.3. They now live in idlelib in https://github.com/python/cpython/tree/main/Lib/idlelib + | ^Pythonwin/pywin/idle/ + ; TODO: adodbapi should be updated and fixed separately + | ^adodbapi/ + ; TODO: Ignoring non-public APIs until all public API is typed + | ([Tt]est|[Dd]emos?)/ + ) ; C-modules that will need type-stubs [mypy-adsi.*,dde,exchange,exchdapi,mapi,perfmon,servicemanager,win32api,win32console,win32clipboard,win32comext.adsi.adsi,win32event,win32evtlog,win32file,win32gui,win32help,win32pdh,win32process,win32ras,win32security,win32service,win32trace,win32ui,win32uiole,win32wnet,_win32sysloader,_winxptheme] diff --git a/pywin32_testall.py b/pywin32_testall.py index 9071549174..2aa92098cb 100644 --- a/pywin32_testall.py +++ b/pywin32_testall.py @@ -76,7 +76,7 @@ def main(): extras = [] if args.user_interaction: - extras += ["-user-interaction"] + extras.append("-user-interaction") extras.extend(remains) scripts = [ "win32/test/testall.py", diff --git a/ruff.toml b/ruff.toml index 704ef1d1ba..8c5daa2a9d 100644 --- a/ruff.toml +++ b/ruff.toml @@ -1,5 +1,4 @@ -# Target the oldest supported version -target-version = "py37" +target-version = "py37" # Target the oldest supported version [lint] select = [ @@ -13,10 +12,10 @@ select = [ "YTT", # flake8-2020 # String formatting, concatenating, interpolation, ... - "ISC001", # single-line-implicit-string-concatenation - "ISC002", # multi-line-implicit-string-concatenation "FLY", # static-join-to-f-string "G", # flake8-logging-format + # Note, we still want to allow multiline ISC + "ISC001", # single-line-implicit-string-concatenation "UP025", # Remove unicode literals from strings "UP030", # Use implicit references for positional format fields # TODO: Still lots of manual fixes needed @@ -38,7 +37,7 @@ select = [ # Explicit re-exports is fine in __init__.py, still a code smell elsewhere. "__init__.py" = ["PLC0414"] # TODO: Make adodbapi changes in their own PRs -"adodbapi/*" = ["C4", "YTT301", "UP031", "UP032", "ISC002"] +"adodbapi/*" = ["C4", "YTT301", "UP031", "UP032"] [lint.isort] combine-as-imports = true @@ -53,6 +52,3 @@ known-third-party = [ "distutils", ] extra-standard-library = ["setuptools"] - -[lint.flake8-implicit-str-concat] -allow-multiline = false # Enables ISC002, ignore ISC003 with this option disabled diff --git a/setup.py b/setup.py index 19f87fbfe2..1e777c007c 100644 --- a/setup.py +++ b/setup.py @@ -54,7 +54,7 @@ build_id_patch = build_id if not "." in build_id_patch: - build_id_patch = build_id_patch + ".0" + build_id_patch += ".0" pywin32_version = "%d.%d.%s" % ( sys.version_info.major, sys.version_info.minor, @@ -174,7 +174,7 @@ def finalize_options(self, build_ext): # like Python, always use debug info, even in release builds # (note the compiler doesn't include debug info, so you only get - # basic info - but its better than nothing!) + # basic info - but it's better than nothing!) # For now use the temp dir - later we may package them, so should # maybe move them next to the output file. pch_dir = os.path.join(build_ext.build_temp) @@ -1039,7 +1039,7 @@ def spawn(self, cmd): # We want mt.exe run with the original manifest for i in range(len(cmd)): if cmd[i] == "-manifest": - cmd[i + 1] = cmd[i + 1] + ".orig" + cmd[i + 1] += ".orig" break super().spawn(cmd) if is_link: diff --git a/win32/Demos/FileSecurityTest.py b/win32/Demos/FileSecurityTest.py index 3b8940b644..4cb1aea2d7 100644 --- a/win32/Demos/FileSecurityTest.py +++ b/win32/Demos/FileSecurityTest.py @@ -131,7 +131,7 @@ calc_mask = 0 # calculate the mask so we can see if we are printing all of the permissions for i in permissions: if getattr(ntsecuritycon, i) & ace[1] == getattr(ntsecuritycon, i): - calc_mask = calc_mask | getattr(ntsecuritycon, i) + calc_mask |= getattr(ntsecuritycon, i) print(" ", i) print(" ", "Calculated Check Mask=", hex(calc_mask)) print(" -SID\n ", win32security.LookupAccountSid(None, ace[2])) diff --git a/win32/Demos/desktopmanager.py b/win32/Demos/desktopmanager.py index 6ffaf2a94b..ff2441e06a 100644 --- a/win32/Demos/desktopmanager.py +++ b/win32/Demos/desktopmanager.py @@ -81,7 +81,7 @@ def get_new_desktop_name(parent_hwnd): def new_icon(hdesk, desktop_name): """Runs as a thread on each desktop to create a new tray icon and handle its messages""" global id - id = id + 1 + id += 1 hdesk.SetThreadDesktop() ## apparently the threads can't use same hinst, so each needs its own window class windowclassname = "PythonDesktopManager" + desktop_name @@ -185,9 +185,9 @@ def icon_wndproc(hwnd, msg, wp, lp): mf_flags = win32con.MF_STRING ## if you switch to winlogon yourself, there's nothing there and you're stuck if desktops[d - 1].lower() in ("winlogon", "disconnect"): - mf_flags = mf_flags | win32con.MF_GRAYED | win32con.MF_DISABLED + mf_flags |= win32con.MF_GRAYED | win32con.MF_DISABLED if desktops[d - 1] == curr_desktop_name: - mf_flags = mf_flags | win32con.MF_CHECKED + mf_flags |= win32con.MF_CHECKED win32gui.AppendMenu(m, mf_flags, d, desktops[d - 1]) win32gui.AppendMenu(m, win32con.MF_STRING, desktop_cnt + 1, "Create new ...") win32gui.AppendMenu(m, win32con.MF_STRING, desktop_cnt + 2, "Exit") diff --git a/win32/Demos/eventLogDemo.py b/win32/Demos/eventLogDemo.py index b87f462288..1e327a80e0 100644 --- a/win32/Demos/eventLogDemo.py +++ b/win32/Demos/eventLogDemo.py @@ -21,7 +21,7 @@ def ReadLog(computer, logType="Application", dumpEachRecord=0): if not objects: break for object in objects: - # get it for testing purposes, but dont print it. + # get it for testing purposes, but don't print it. msg = win32evtlogutil.SafeFormatMessage(object, logType) if object.Sid is not None: try: @@ -46,7 +46,7 @@ def ReadLog(computer, logType="Application", dumpEachRecord=0): print("(unicode error printing message: repr() follows...)") print(repr(msg)) - num = num + len(objects) + num += len(objects) if numRecords == num: print("Successfully read all", numRecords, "records") @@ -62,8 +62,8 @@ def ReadLog(computer, logType="Application", dumpEachRecord=0): def usage(): print("Writes an event to the event log.") - print("-w : Dont write any test records.") - print("-r : Dont read the event log") + print("-w : Don't write any test records.") + print("-r : Don't read the event log") print("-c : computerName : Process the log on the specified computer") print("-v : Verbose") print("-t : LogType - Use the specified log - default = 'Application'") @@ -102,7 +102,7 @@ def test(): if opt == "-w": do_write = 0 if opt == "-v": - verbose = verbose + 1 + verbose += 1 if do_write: ph = win32api.GetCurrentProcess() th = win32security.OpenProcessToken(ph, win32con.TOKEN_READ) diff --git a/win32/Demos/security/security_enums.py b/win32/Demos/security/security_enums.py index ab3cc6d361..8850b442c0 100644 --- a/win32/Demos/security/security_enums.py +++ b/win32/Demos/security/security_enums.py @@ -37,7 +37,7 @@ def lookup_flags(self, flags): for k, v in self.__dict__.items(): if flags & v == v: flag_names.append(k) - unknown_flags = unknown_flags & ~v + unknown_flags &= ~v return flag_names, unknown_flags diff --git a/win32/Demos/service/pipeTestService.py b/win32/Demos/service/pipeTestService.py index 27aec92555..f062fcd2c9 100644 --- a/win32/Demos/service/pipeTestService.py +++ b/win32/Demos/service/pipeTestService.py @@ -77,7 +77,7 @@ def DoProcessClient(self, pipeHandle, tid): hr = winerror.ERROR_MORE_DATA while hr == winerror.ERROR_MORE_DATA: hr, thisd = ReadFile(pipeHandle, 256) - d = d + thisd + d += thisd print("Read", d) ok = 1 except error: @@ -85,7 +85,7 @@ def DoProcessClient(self, pipeHandle, tid): ok = 0 # A secure service would handle (and ignore!) errors writing to the - # pipe, but for the sake of this demo we dont (if only to see what errors + # pipe, but for the sake of this demo we don't (if only to see what errors # we can get when our clients break at strange times :-) if ok: msg = ( @@ -162,7 +162,7 @@ def SvcDoRun(self): else: # Pipe event - spawn thread to deal with it. _thread.start_new_thread(self.ProcessClient, (pipeHandle,)) - num_connections = num_connections + 1 + num_connections += 1 # Sleep to ensure that any new threads are in the list, and then # wait for all current threads to finish. diff --git a/win32/Demos/service/pipeTestServiceClient.py b/win32/Demos/service/pipeTestServiceClient.py index cc12dc66a3..507219c09e 100644 --- a/win32/Demos/service/pipeTestServiceClient.py +++ b/win32/Demos/service/pipeTestServiceClient.py @@ -38,7 +38,7 @@ def CallPipe(fn, args): ret = None retryCount = 0 while retryCount < 8: # Keep looping until user cancels. - retryCount = retryCount + 1 + retryCount += 1 try: return fn(*args) except win32api.error as exc: diff --git a/win32/Demos/timer_demo.py b/win32/Demos/timer_demo.py index 61115f0655..0ce1d0210b 100644 --- a/win32/Demos/timer_demo.py +++ b/win32/Demos/timer_demo.py @@ -26,7 +26,7 @@ def __init__(self, delay=1000, max=10): def increment(self, id, time): print("x = %d" % self.x) - self.x = self.x + 1 + self.x += 1 # if we've reached the max count, # kill off the timer. if self.x > self.max: diff --git a/win32/Demos/win32clipboardDemo.py b/win32/Demos/win32clipboardDemo.py index 1c1c9f5d0f..094c0c8520 100644 --- a/win32/Demos/win32clipboardDemo.py +++ b/win32/Demos/win32clipboardDemo.py @@ -34,7 +34,7 @@ def TestText(): SetClipboardText(text) got = GetClipboardData(win32con.CF_TEXT) # CF_TEXT always gives us 'bytes' back . - assert got == text_bytes, f"Didnt get the correct result back - '{got!r}'." + assert got == text_bytes, f"Didn't get the correct result back - '{got!r}'." finally: CloseClipboard() @@ -42,12 +42,12 @@ def TestText(): try: # CF_UNICODE text always gives unicode objects back. got = GetClipboardData(win32con.CF_UNICODETEXT) - assert got == text, f"Didnt get the correct result back - '{got!r}'." - assert isinstance(got, str), f"Didnt get the correct result back - '{got!r}'." + assert got == text, f"Didn't get the correct result back - '{got!r}'." + assert isinstance(got, str), f"Didn't get the correct result back - '{got!r}'." # CF_OEMTEXT is a bytes-based format. got = GetClipboardData(win32con.CF_OEMTEXT) - assert got == text_bytes, f"Didnt get the correct result back - '{got!r}'." + assert got == text_bytes, f"Didn't get the correct result back - '{got!r}'." # Unicode tests EmptyClipboard() @@ -57,8 +57,8 @@ def TestText(): SetClipboardData(win32con.CF_UNICODETEXT, text) # Get it in Unicode. got = GetClipboardData(win32con.CF_UNICODETEXT) - assert got == text, f"Didnt get the correct result back - '{got!r}'." - assert isinstance(got, str), f"Didnt get the correct result back - '{got!r}'." + assert got == text, f"Didn't get the correct result back - '{got!r}'." + assert isinstance(got, str), f"Didn't get the correct result back - '{got!r}'." # Close and open the clipboard to ensure auto-conversions take place. finally: @@ -68,12 +68,12 @@ def TestText(): try: # Make sure I can still get the text as bytes got = GetClipboardData(win32con.CF_TEXT) - assert got == text_bytes, f"Didnt get the correct result back - '{got!r}'." + assert got == text_bytes, f"Didn't get the correct result back - '{got!r}'." # Make sure we get back the correct types. got = GetClipboardData(win32con.CF_UNICODETEXT) - assert isinstance(got, str), f"Didnt get the correct result back - '{got!r}'." + assert isinstance(got, str), f"Didn't get the correct result back - '{got!r}'." got = GetClipboardData(win32con.CF_OEMTEXT) - assert got == text_bytes, f"Didnt get the correct result back - '{got!r}'." + assert got == text_bytes, f"Didn't get the correct result back - '{got!r}'." print("Clipboard text tests worked correctly") finally: CloseClipboard() @@ -127,7 +127,7 @@ def TestCustomFormat(): # Now read it back. data = GetClipboardData(fmt) loaded_object = pickle.loads(data) - assert pickle.loads(data) == pickled_object, "Didnt get the correct data!" + assert pickle.loads(data) == pickled_object, "Didn't get the correct data!" print("Clipboard custom format tests worked correctly") finally: diff --git a/win32/Demos/win32comport_demo.py b/win32/Demos/win32comport_demo.py index 2ee4c3c154..1596e41395 100644 --- a/win32/Demos/win32comport_demo.py +++ b/win32/Demos/win32comport_demo.py @@ -11,7 +11,7 @@ # This demo uses userlapped IO, so that none of the read or write operations actually block (however, # in this sample, the very next thing we do _is_ block - so it shows off the concepts even though it -# doesnt exploit them. +# doesn't exploit them. import msvcrt # For the getch() function. import sys diff --git a/win32/Demos/win32gui_dialog.py b/win32/Demos/win32gui_dialog.py index 40ff8bbbe7..956265a25e 100644 --- a/win32/Demos/win32gui_dialog.py +++ b/win32/Demos/win32gui_dialog.py @@ -69,7 +69,7 @@ def toparam(self): # alternate strategy would be to use unicode natively # and use the 'W' version of the messages - eg, # LVM_SETITEMW etc. - val = val + "\0" + val += "\x00" if isinstance(val, str): val = val.encode("mbcs") str_buf = array.array("b", val) diff --git a/win32/Demos/win32netdemo.py b/win32/Demos/win32netdemo.py index 35aecda2e5..ac5f305db5 100644 --- a/win32/Demos/win32netdemo.py +++ b/win32/Demos/win32netdemo.py @@ -59,7 +59,7 @@ def UserEnum(): ) for user in data: verbose("Found user %s" % user["name"]) - nuser = nuser + 1 + nuser += 1 if not resume: break assert nuser, "Could not find any users!" @@ -82,12 +82,12 @@ def GroupEnum(): ) for member in memberdata: verbose(" Member {name}".format(**member)) - nmembers = nmembers + 1 + nmembers += 1 if memberresume == 0: break if not resume: break - assert nmembers, "Couldnt find a single member in a single group!" + assert nmembers, "Couldn't find a single member in a single group!" print("Enumerated all the groups") @@ -109,13 +109,13 @@ def LocalGroupEnum(): username, domain, type = win32security.LookupAccountSid( server, member["sid"] ) - nmembers = nmembers + 1 + nmembers += 1 verbose(" Member {} ({})".format(username, member["domainandname"])) if memberresume == 0: break if not resume: break - assert nmembers, "Couldnt find a single member in a single group!" + assert nmembers, "Couldn't find a single member in a single group!" print("Enumerated all the local groups") @@ -206,7 +206,7 @@ def SetInfo(userName=None): def SetComputerInfo(): - "Doesnt actually change anything, just make sure we could ;-)" + "Doesn't actually change anything, just make sure we could ;-)" info = win32net.NetWkstaGetInfo(None, 502) # *sob* - but we can't! Why not!!! # win32net.NetWkstaSetInfo(None, 502, info) @@ -242,7 +242,7 @@ def main(): usage(tests) if opt == "-v": global verbose_level - verbose_level = verbose_level + 1 + verbose_level += 1 if opt == "-c": create_user = True diff --git a/win32/Demos/win32wnet/testwnet.py b/win32/Demos/win32wnet/testwnet.py index ea18e4808c..d13917cf2f 100644 --- a/win32/Demos/win32wnet/testwnet.py +++ b/win32/Demos/win32wnet/testwnet.py @@ -113,7 +113,7 @@ def TestGetUser(): u = win32wnet.WNetGetUser() print("Current global user is", repr(u)) if u != win32wnet.WNetGetUser(None): - raise RuntimeError("Default value didnt seem to work!") + raise RuntimeError("Default value didn't seem to work!") TestGetUser() diff --git a/win32/Lib/pywin32_testutil.py b/win32/Lib/pywin32_testutil.py index 4dc33d1ae8..d9e5179136 100644 --- a/win32/Lib/pywin32_testutil.py +++ b/win32/Lib/pywin32_testutil.py @@ -31,7 +31,7 @@ def __init__(self, real_test): self.num_test_cases = 1 self.num_leak_iters = 2 # seems to be enough! if hasattr(sys, "gettotalrefcount"): - self.num_test_cases = self.num_test_cases + self.num_leak_iters + self.num_test_cases += self.num_leak_iters def countTestCases(self): return self.num_test_cases @@ -61,7 +61,7 @@ def __call__(self, result=None): result.addFailure(self.real_test, (exc.__class__, exc, None)) def runTest(self): - assert 0, "not used" + raise NotImplementedError("not used") def _do_leak_tests(self, result=None): try: diff --git a/win32/Lib/regcheck.py b/win32/Lib/regcheck.py index 4bb2419aae..27aab3e5d6 100644 --- a/win32/Lib/regcheck.py +++ b/win32/Lib/regcheck.py @@ -77,7 +77,7 @@ def CheckPythonPaths(verbose): else: if verbose: print("(empty)") - keyNo = keyNo + 1 + keyNo += 1 except win32api.error: break finally: @@ -116,7 +116,7 @@ def CheckHelpFiles(verbose): print(helpFile) except OSError: print("** Help file %s does not exist" % helpFile) - keyNo = keyNo + 1 + keyNo += 1 except win32api.error as exc: import winerror diff --git a/win32/Lib/regutil.py b/win32/Lib/regutil.py index 9837637327..f85b06b224 100644 --- a/win32/Lib/regutil.py +++ b/win32/Lib/regutil.py @@ -76,7 +76,7 @@ def RegisterPythonExe(exeFullPath, exeAlias=None, exeAppPath=None): of the filename is used. exeAppPath -- Not supported. """ - # Note - Dont work on win32s (but we dont care anymore!) + # Note - Don't work on win32s (but we don't care anymore!) if exeAppPath: raise error("Do not support exeAppPath argument currently") if exeAlias is None: @@ -107,7 +107,7 @@ def RegisterNamedPath(name, path): """Register a named path - ie, a named PythonPath entry.""" keyStr = BuildDefaultPythonKey() + "\\PythonPath" if name: - keyStr = keyStr + "\\" + name + keyStr += "\\" + name win32api.RegSetValue(GetRootKey(), keyStr, win32con.REG_SZ, path) @@ -125,10 +125,10 @@ def UnregisterNamedPath(name): def GetRegisteredNamedPath(name): - """Get a registered named path, or None if it doesnt exist.""" + """Get a registered named path, or None if it doesn't exist.""" keyStr = BuildDefaultPythonKey() + "\\PythonPath" if name: - keyStr = keyStr + "\\" + name + keyStr += "\\" + name try: return win32api.RegQueryValue(GetRootKey(), keyStr) except win32api.error as exc: diff --git a/win32/Lib/sspi.py b/win32/Lib/sspi.py index 79afa58393..803559fba9 100644 --- a/win32/Lib/sspi.py +++ b/win32/Lib/sspi.py @@ -39,7 +39,7 @@ def _get_next_seq_num(self): implementation is to increment a counter """ ret = self.next_seq_num - self.next_seq_num = self.next_seq_num + 1 + self.next_seq_num += 1 return ret def encrypt(self, data): diff --git a/win32/Lib/win32gui_struct.py b/win32/Lib/win32gui_struct.py index 2725de0023..e87a55364f 100644 --- a/win32/Lib/win32gui_struct.py +++ b/win32/Lib/win32gui_struct.py @@ -80,9 +80,9 @@ def UnpackNMITEMACTIVATE(lparam): if is64bit: # the struct module doesn't handle this correctly as some of the items # are actually structs in structs, which get individually aligned. - format = format + "iiiiiiixxxxP" + format += "iiiiiiixxxxP" else: - format = format + "iiiiiiiP" + format += "iiiiiiiP" buf = win32gui.PyMakeBuffer(struct.calcsize(format), lparam) return _MakeResult( "NMITEMACTIVATE hwndFrom idFrom code iItem iSubItem uNewState uOldState uChanged actionx actiony lParam", @@ -522,10 +522,10 @@ def UnpackTVNOTIFY(lparam): item_size = struct.calcsize(_tvitem_fmt) format = _nmhdr_fmt + _nmhdr_align_padding if is64bit: - format = format + "ixxxx" + format += "ixxxx" else: - format = format + "i" - format = format + "%ds%ds" % (item_size, item_size) + format += "i" + format += "%ds%ds" % (item_size, item_size) buf = win32gui.PyGetMemory(lparam, struct.calcsize(format)) hwndFrom, id, code, action, buf_old, buf_new = struct.unpack(format, buf) item_old = UnpackTVITEM(buf_old) @@ -670,8 +670,8 @@ def UnpackLVDISPINFO(lparam): def UnpackLVNOTIFY(lparam): format = _nmhdr_fmt + _nmhdr_align_padding + "7i" if is64bit: - format = format + "xxxx" # point needs padding. - format = format + "P" + format += "xxxx" # point needs padding. + format += "P" buf = win32gui.PyGetMemory(lparam, struct.calcsize(format)) ( hwndFrom, diff --git a/win32/Lib/win32pdhquery.py b/win32/Lib/win32pdhquery.py index 71d77e03aa..3f458e0a88 100644 --- a/win32/Lib/win32pdhquery.py +++ b/win32/Lib/win32pdhquery.py @@ -443,7 +443,7 @@ def getinstpaths( try: while instances[cur + 1] == object: temp.append(object) - cur = cur + 1 + cur += 1 except IndexError: # if we went over the end pass paths = [] diff --git a/win32/Lib/win32pdhutil.py b/win32/Lib/win32pdhutil.py index 850e0ab89d..4b733ac3fb 100644 --- a/win32/Lib/win32pdhutil.py +++ b/win32/Lib/win32pdhutil.py @@ -103,7 +103,7 @@ def FindPerformanceAttributesByName( instance_dict = {} for instance in instances: try: - instance_dict[instance] = instance_dict[instance] + 1 + instance_dict[instance] += 1 except KeyError: instance_dict[instance] = 0 @@ -128,7 +128,7 @@ def ShowAllProcesses(): instance_dict = {} for instance in instances: try: - instance_dict[instance] = instance_dict[instance] + 1 + instance_dict[instance] += 1 except KeyError: instance_dict[instance] = 0 diff --git a/win32/Lib/win32serviceutil.py b/win32/Lib/win32serviceutil.py index 0552e5fc3f..2284536c3a 100644 --- a/win32/Lib/win32serviceutil.py +++ b/win32/Lib/win32serviceutil.py @@ -218,7 +218,7 @@ def InstallService( startType = win32service.SERVICE_DEMAND_START serviceType = win32service.SERVICE_WIN32_OWN_PROCESS if bRunInteractive: - serviceType = serviceType | win32service.SERVICE_INTERACTIVE_PROCESS + serviceType |= win32service.SERVICE_INTERACTIVE_PROCESS if errorControl is None: errorControl = win32service.SERVICE_ERROR_NORMAL @@ -304,7 +304,7 @@ def ChangeServiceConfig( hscm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS) serviceType = win32service.SERVICE_WIN32_OWN_PROCESS if bRunInteractive: - serviceType = serviceType | win32service.SERVICE_INTERACTIVE_PROCESS + serviceType |= win32service.SERVICE_INTERACTIVE_PROCESS commandLine = _GetCommandLine(exeName, exeArgs) try: hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS) @@ -452,7 +452,7 @@ def __FindSvcDeps(findName): svc = win32api.RegEnumKey(k, num) except win32api.error: break - num = num + 1 + num += 1 sk = win32api.RegOpenKey(k, svc) try: deps, typ = win32api.RegQueryValueEx(sk, "DependOnService") @@ -835,7 +835,7 @@ def HandleCommandLine( # Note that we install the service before calling the custom option # handler, so if the custom handler fails, we have an installed service (from NT's POV) # but is unlikely to work, as the Python code controlling it failed. Therefore - # we remove the service if the first bit works, but the second doesnt! + # we remove the service if the first bit works, but the second doesn't! try: InstallService( serviceClassString, @@ -981,11 +981,11 @@ def GetAcceptedControls(self): # override this. accepted = 0 if hasattr(self, "SvcStop"): - accepted = accepted | win32service.SERVICE_ACCEPT_STOP + accepted |= win32service.SERVICE_ACCEPT_STOP if hasattr(self, "SvcPause") and hasattr(self, "SvcContinue"): - accepted = accepted | win32service.SERVICE_ACCEPT_PAUSE_CONTINUE + accepted |= win32service.SERVICE_ACCEPT_PAUSE_CONTINUE if hasattr(self, "SvcShutdown"): - accepted = accepted | win32service.SERVICE_ACCEPT_SHUTDOWN + accepted |= win32service.SERVICE_ACCEPT_SHUTDOWN return accepted def ReportServiceStatus( @@ -1004,7 +1004,7 @@ def ReportServiceStatus( ]: checkPoint = 0 else: - self.checkPoint = self.checkPoint + 1 + self.checkPoint += 1 checkPoint = self.checkPoint # Now report the status to the control manager diff --git a/win32/Lib/win32verstamp.py b/win32/Lib/win32verstamp.py index a705c967fd..e9f8c5e45d 100644 --- a/win32/Lib/win32verstamp.py +++ b/win32/Lib/win32verstamp.py @@ -71,7 +71,7 @@ def String(key, value): key = nullterm(key) value = nullterm(value) result = struct.pack("hh", len(value) // 2, 1) # wValueLength, wType - result = result + key + result += key result = pad32(result) + value return addlen(result) @@ -79,16 +79,16 @@ def String(key, value): def StringTable(key, data): key = nullterm(key) result = struct.pack("hh", 0, 1) # wValueLength, wType - result = result + key + result += key for k, v in data.items(): - result = result + String(k, v) + result += String(k, v) result = pad32(result) return addlen(result) def StringFileInfo(data): result = struct.pack("hh", 0, 1) # wValueLength, wType - result = result + nullterm("StringFileInfo") + result += nullterm("StringFileInfo") # result = pad32(result) + StringTable('040904b0', data) result = pad32(result) + StringTable("040904E4", data) return addlen(result) @@ -96,24 +96,24 @@ def StringFileInfo(data): def Var(key, value): result = struct.pack("hh", len(value), 0) # wValueLength, wType - result = result + nullterm(key) + result += nullterm(key) result = pad32(result) + value return addlen(result) def VarFileInfo(data): result = struct.pack("hh", 0, 1) # wValueLength, wType - result = result + nullterm("VarFileInfo") + result += nullterm("VarFileInfo") result = pad32(result) for k, v in data.items(): - result = result + Var(k, v) + result += Var(k, v) return addlen(result) def VS_VERSION_INFO(maj, min, sub, build, sdata, vdata, debug=0, is_dll=1): ffi = VS_FIXEDFILEINFO(maj, min, sub, build, debug, is_dll) result = struct.pack("hh", len(ffi), 0) # wValueLength, wType - result = result + nullterm("VS_VERSION_INFO") + result += nullterm("VS_VERSION_INFO") result = pad32(result) + ffi result = pad32(result) + StringFileInfo(sdata) + VarFileInfo(vdata) return addlen(result) @@ -121,7 +121,7 @@ def VS_VERSION_INFO(maj, min, sub, build, sdata, vdata, debug=0, is_dll=1): def stamp(pathname, options): # For some reason, the API functions report success if the file is open - # but doesnt work! Try and open the file for writing, just to see if it is + # but doesn't work! Try and open the file for writing, just to see if it is # likely the stamp will work! try: f = open(pathname, "a+b") diff --git a/win32/help/win32net.html b/win32/help/win32net.html index 36e351b1f6..6d4d62e188 100644 --- a/win32/help/win32net.html +++ b/win32/help/win32net.html @@ -217,7 +217,7 @@

      Creating a share

      Selecting that link will show a number of different PySHARE_INFO -structures; lets assume we want to use the PySHARE_INFO_2 structure. +structures; let's assume we want to use the PySHARE_INFO_2 structure. So do you create this PySHARE_INFO_2 Object? It is really quite simple: diff --git a/win32/scripts/ControlService.py b/win32/scripts/ControlService.py index d2281add2b..b4d35685ce 100644 --- a/win32/scripts/ControlService.py +++ b/win32/scripts/ControlService.py @@ -315,7 +315,7 @@ def ReloadData(self): svc[0], ) ) - i = i + 1 + i += 1 if service and service[1] == svc[0]: self.listCtrl.SetCurSel(pos) diff --git a/win32/scripts/VersionStamp/bulkstamp.py b/win32/scripts/VersionStamp/bulkstamp.py index 81f7cbcd53..3a039ebb81 100644 --- a/win32/scripts/VersionStamp/bulkstamp.py +++ b/win32/scripts/VersionStamp/bulkstamp.py @@ -63,7 +63,7 @@ def walk(arg, dirname, names): desc = descriptions[os.path.normcase(name)] try: verstamp.stamp(vars, pathname, desc, is_dll=is_dll) - numStamped = numStamped + 1 + numStamped += 1 except win32api.error as exc: print( "Could not stamp", diff --git a/win32/scripts/VersionStamp/vssutil.py b/win32/scripts/VersionStamp/vssutil.py index ae9259c1a7..ca9d9e344b 100644 --- a/win32/scripts/VersionStamp/vssutil.py +++ b/win32/scripts/VersionStamp/vssutil.py @@ -74,14 +74,14 @@ def VssLog(project, linePrefix="", noLabels=5, maxItems=150): num = 0 labelNum = 0 for i in project.GetVersions(constants.VSSFLAG_RECURSYES): - num = num + 1 + num += 1 if num > maxItems: break commentDesc = itemDesc = "" if i.Action[:5] == "Added": continue if len(i.Label): - labelNum = labelNum + 1 + labelNum += 1 itemDesc = i.Action else: itemDesc = i.VSSItem.Name @@ -110,7 +110,7 @@ def SubstituteVSSInFile(projectName, inName, outName): if version.Label: break else: - print("Couldnt find a label in the sourcesafe project!") + print("Couldn't find a label in the sourcesafe project!") return # Setup some local helpers for the conversion strings. vss_label = version.Label @@ -123,10 +123,10 @@ def CountCheckouts(item): num = 0 if item.Type == constants.VSSITEM_PROJECT: for sub in item.Items: - num = num + CountCheckouts(sub) + num += CountCheckouts(sub) else: if item.IsCheckedOut: - num = num + 1 + num += 1 return num @@ -165,7 +165,7 @@ def MakeNewBuildNo(project, buildDesc=None, auto=0, bRebrand=0): try: buildNo = int(buildNo) if not bRebrand: - buildNo = buildNo + 1 + buildNo += 1 buildNo = str(buildNo) except ValueError: raise error("The previous label could not be incremented: %s" % (oldBuild)) diff --git a/win32/scripts/backupEventLog.py b/win32/scripts/backupEventLog.py index 325da9da5f..2a4ea5024e 100644 --- a/win32/scripts/backupEventLog.py +++ b/win32/scripts/backupEventLog.py @@ -23,7 +23,7 @@ def BackupClearLog(logType): os.stat(fname) except OSError: fileExists = 0 - retry = retry + 1 + retry += 1 # OK - have unique file name. try: hlog = win32evtlog.OpenEventLog(None, logType) diff --git a/win32/scripts/rasutil.py b/win32/scripts/rasutil.py index 75426341f0..6eaa318875 100644 --- a/win32/scripts/rasutil.py +++ b/win32/scripts/rasutil.py @@ -42,7 +42,7 @@ def Connect(rasEntryName, numRetries=5): break print("Retrying...") win32api.Sleep(5000) - retryCount = retryCount - 1 + retryCount -= 1 if errCode: raise ConnectionError(errCode, win32ras.GetErrorString(errCode)) diff --git a/win32/src/PerfMon/PerfObjectType.cpp b/win32/src/PerfMon/PerfObjectType.cpp index f6feb1732d..b496b99412 100644 --- a/win32/src/PerfMon/PerfObjectType.cpp +++ b/win32/src/PerfMon/PerfObjectType.cpp @@ -129,7 +129,7 @@ void PyPERF_OBJECT_TYPE::Term() m_obPerfMonManager = NULL; } -// Get the counter objects that Im gunna use. +// Get the counter objects that I'm gunna use. BOOL PyPERF_OBJECT_TYPE::InitPythonObjects(PyObject *obCounters) { m_obCounters = obCounters; @@ -138,8 +138,8 @@ BOOL PyPERF_OBJECT_TYPE::InitPythonObjects(PyObject *obCounters) } // Init the memory layout of the win32 perfmon structures from the mapping manager. -// Doesnt keep a reference to the mapping manager, but assumes it will stay alive -// until Im term'd! +// Doesn't keep a reference to the mapping manager, but assumes it will stay alive +// until I'm term'd! // Also _removes_ the reference to the counters' and _adds_ a reference to // the PyPerMonManager object BOOL PyPERF_OBJECT_TYPE::InitMemoryLayout(MappingManager *pmm, PyPerfMonManager *obPerfMonManager) diff --git a/win32/src/PerfMon/PyPerfMonControl.h b/win32/src/PerfMon/PyPerfMonControl.h index e3b0a358ce..8a450683ea 100644 --- a/win32/src/PerfMon/PyPerfMonControl.h +++ b/win32/src/PerfMon/PyPerfMonControl.h @@ -5,7 +5,7 @@ // A PERF_OBJECT_TYPE // A number of PERF_COUNTER_DEFINITIONs -// dont manage these size better cos I cant be bothered! +// don't manage these size better cos I can't be bothered! const int MMCD_SERVICE_SIZE = 25; const int MMCD_EVENTSOURCE_SIZE = 25; diff --git a/win32/src/PerfMon/perfmondata.cpp b/win32/src/PerfMon/perfmondata.cpp index 995b856bc4..0533879961 100644 --- a/win32/src/PerfMon/perfmondata.cpp +++ b/win32/src/PerfMon/perfmondata.cpp @@ -24,7 +24,7 @@ // LOG_DEBUG = Minimum Debugging // LOG_VERBOSE = Maximum Debugging -//#define LOG_NONE 0 +// #define LOG_NONE 0 #define LOG_USER 1 #define LOG_DEBUG 2 #define LOG_VERBOSE 3 @@ -171,7 +171,7 @@ DWORD APIENTRY OpenPerformanceData(LPWSTR lpDeviceNames) if (!dwOpenCount) { // open Eventlog interface // The memmapped file name is derived from the DLL name. // Later we may offer to look up a string resource, but not now! - // NOTE - We dont open the event log yet, as we may wish to open it with a custom name + // NOTE - We don't open the event log yet, as we may wish to open it with a custom name // open shared memory used by application to pass performance values hSharedMemory = OpenFileMapping(FILE_MAP_READ, FALSE, szFileMapping); diff --git a/win32/src/PyACL.cpp b/win32/src/PyACL.cpp index 304b2083c1..fb2ec35308 100644 --- a/win32/src/PyACL.cpp +++ b/win32/src/PyACL.cpp @@ -727,7 +727,7 @@ PyObject *PyACL::AddAuditAccessAce(PyObject *self, PyObject *args) unsigned int required_size = psacl->AclSize + sizeof(SYSTEM_AUDIT_ACE) + GetLengthSid(psid); // max ACL size is USHRT_MAX if (required_size > USHRT_MAX) - return PyErr_Format(PyExc_OverflowError, "%s: adding ACE would put ACL over size limit", __FUNCTION__ ); + return PyErr_Format(PyExc_OverflowError, "%s: adding ACE would put ACL over size limit", __FUNCTION__); psacl_padded = (ACL *)malloc(required_size); if (psacl_padded == NULL) return PyErr_Format(PyExc_MemoryError, "AddAuditAccessAce: unable to allocated %d bytes", required_size); @@ -789,7 +789,7 @@ PyObject *PyACL::AddAuditAccessAceEx(PyObject *self, PyObject *args) unsigned int required_size = psacl->AclSize + sizeof(SYSTEM_AUDIT_ACE) + GetLengthSid(psid); // max ACL size is USHRT_MAX if (required_size > USHRT_MAX) - return PyErr_Format(PyExc_OverflowError, "%s: adding ACE would put ACL over size limit", __FUNCTION__ ); + return PyErr_Format(PyExc_OverflowError, "%s: adding ACE would put ACL over size limit", __FUNCTION__); psacl_padded = (ACL *)malloc(required_size); if (psacl_padded == NULL) return PyErr_Format(PyExc_MemoryError, "AddAuditAccessAceEx: unable to allocated %d bytes", required_size); @@ -867,10 +867,10 @@ PyObject *PyACL::AddAuditAccessObjectAce(PyObject *self, PyObject *args) if (err != ERROR_ALLOTTED_SPACE_EXCEEDED) return PyWin_SetAPIError("AddAuditAccessObjectAce", err); // resize if acl too small - unsigned int required_size = psacl->AclSize + sizeof(SYSTEM_AUDIT_OBJECT_ACE) + GetLengthSid(psid); + unsigned int required_size = psacl->AclSize + sizeof(SYSTEM_AUDIT_OBJECT_ACE) + GetLengthSid(psid); // max ACL size is USHRT_MAX if (required_size > USHRT_MAX) - return PyErr_Format(PyExc_OverflowError, "%s: adding ACE would put ACL over size limit", __FUNCTION__ ); + return PyErr_Format(PyExc_OverflowError, "%s: adding ACE would put ACL over size limit", __FUNCTION__); psacl_padded = (ACL *)malloc(required_size); if (psacl_padded == NULL) return PyErr_Format(PyExc_MemoryError, "AddAuditAccessObjectAce: unable to allocated %d bytes", diff --git a/win32/src/PyHANDLE.cpp b/win32/src/PyHANDLE.cpp index 4fdad48f06..c1baf754f6 100644 --- a/win32/src/PyHANDLE.cpp +++ b/win32/src/PyHANDLE.cpp @@ -111,9 +111,9 @@ struct PyMethodDef PyHANDLE::methods[] = { {NULL}}; static PyNumberMethods PyHANDLE_NumberMethods = { - PyHANDLE::binaryFailureFunc, /* nb_add */ - PyHANDLE::binaryFailureFunc, /* nb_subtract */ - PyHANDLE::binaryFailureFunc, /* nb_multiply */ + PyHANDLE::binaryFailureFunc, /* nb_add */ + PyHANDLE::binaryFailureFunc, /* nb_subtract */ + PyHANDLE::binaryFailureFunc, /* nb_multiply */ PyHANDLE::binaryFailureFunc, /* nb_remainder */ PyHANDLE::binaryFailureFunc, /* nb_divmod */ PyHANDLE::ternaryFailureFunc, /* nb_power */ @@ -128,23 +128,22 @@ static PyNumberMethods PyHANDLE_NumberMethods = { PyHANDLE::binaryFailureFunc, /* nb_and */ PyHANDLE::binaryFailureFunc, /* nb_xor */ PyHANDLE::binaryFailureFunc, /* nb_or */ - PyHANDLE::intFunc, /* nb_int */ - PyHANDLE::longFunc, /* nb_long */ - PyHANDLE::unaryFailureFunc, /* nb_float */ - // These removed in 3.0 + PyHANDLE::intFunc, /* nb_int */ + PyHANDLE::longFunc, /* nb_long */ + PyHANDLE::unaryFailureFunc, /* nb_float */ + // These removed in 3.0 }; // @pymeth __int__|Used when an integer representation of the handle object is required. PYWINTYPES_EXPORT PyTypeObject PyHANDLEType = { PYWIN_OBJECT_HEAD "PyHANDLE", sizeof(PyHANDLE), 0, PyHANDLE::deallocFunc, /* tp_dealloc */ - 0, - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_compare */ - PyHANDLE::strFunc, /* tp_repr */ - &PyHANDLE_NumberMethods, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ + 0, 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + PyHANDLE::strFunc, /* tp_repr */ + &PyHANDLE_NumberMethods, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ // @pymeth __hash__|Used when the hash value of an object is required PyHANDLE::hashFunc, /* tp_hash */ 0, /* tp_call */ @@ -301,7 +300,7 @@ int PyHANDLE::print(FILE *fp, int flags) // ### runtime library) Hack it by getting Python to do the print! // // ### - Double Ack - Always use the hack! - //#ifdef _DEBUG + // #ifdef _DEBUG PyObject *ob = PyWinCoreString_FromString(resBuf); PyObject_Print(ob, fp, flags | Py_PRINT_RAW); Py_DECREF(ob); diff --git a/win32/src/PySID.cpp b/win32/src/PySID.cpp index fcb5215e22..e7d8da1463 100644 --- a/win32/src/PySID.cpp +++ b/win32/src/PySID.cpp @@ -53,7 +53,7 @@ PyObject *PyWinMethod_NewSID(PyObject *self, PyObject *args) return new PySID(pNew); } } - if (bufSize > INT_MAX) { + if (bufSize > INT_MAX) { PyErr_SetString(PyExc_ValueError, "SID buffer size beyond INT_MAX"); return NULL; } diff --git a/win32/src/PyTime.cpp b/win32/src/PyTime.cpp index de0c32cda4..502ed8787a 100644 --- a/win32/src/PyTime.cpp +++ b/win32/src/PyTime.cpp @@ -18,11 +18,7 @@ const double ONETHOUSANDMILLISECONDS = 0.00001157407407407407407407407407; PyObject *PyWin_NewTime(PyObject *timeOb); -BOOL PyWinTime_Check(PyObject *ob) -{ - return PyDateTime_Check(ob) || - PyObject_HasAttrString(ob, "timetuple"); -} +BOOL PyWinTime_Check(PyObject *ob) { return PyDateTime_Check(ob) || PyObject_HasAttrString(ob, "timetuple"); } // Timezone helpers... // Returns a timezone object representing UTC. Implementation currently @@ -155,7 +151,7 @@ PyTypeObject PyWinDateTimeType = { PyWinDateTimeType_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ - // we fill tp_base in at runtime; its not available statically. + // we fill tp_base in at runtime; it's not available statically. 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ @@ -264,190 +260,190 @@ static WORD SequenceIndexAsWORD(PyObject *seq, int index) PyObject *PyWin_NewTime(PyObject *timeOb) { // If it already a datetime object, just return it as-is. - if (PyDateTime_Check(timeOb)) { - Py_INCREF(timeOb); - return timeOb; - } - - PyObject *result = NULL; - PyObject *cleanupOb = NULL; // must be xdefref'd. + if (PyDateTime_Check(timeOb)) { + Py_INCREF(timeOb); + return timeOb; + } - // Support other objects with a "timetuple" method. - PyObject *method = PyObject_GetAttrString(timeOb, "timetuple"); - if (method == NULL) - PyErr_Clear(); - else { - timeOb = PyEval_CallObject(method, NULL); - Py_DECREF(method); - if (!timeOb) - return NULL; - cleanupOb = timeOb; // new reference that must be nuked. - // now we should fall into the sequence check! - } - if (PyNumber_Check(timeOb)) { - PyObject *longob = PyNumber_Long(timeOb); - if (longob) { - long t = PyLong_AsLong(longob); - if (t == -1) { - if (!PyErr_Occurred()) - PyErr_BadArgument(); - } - else - result = PyWinTimeObject_Fromtime_t(t); - Py_DECREF(longob); - } - } - else if (PySequence_Check(timeOb)) { - assert(!PyErr_Occurred()); // should be no stale errors! - // convert a timetuple, with optional millisecond extension, - // into a datetime object. ie: - // >>> datetime.datetime.fromtimestamp(time.mktime(timetuple)) - // but we 'inline' the time.mktime step... - struct tm buf; - time_t tt; - int millisec = 0; - // must use a tuple as we use ParseTuple with an optional arg. - PyObject *tuple_args = PySequence_Tuple(timeOb); - if (!tuple_args) - return NULL; - BOOL ok = gettmarg(tuple_args, &buf, &millisec); - Py_DECREF(tuple_args); - if (!ok) - return NULL; - tt = mktime(&buf); - if (tt == (time_t)(-1)) { - PyErr_SetString(PyExc_OverflowError, "mktime argument out of range"); - return NULL; + PyObject *result = NULL; + PyObject *cleanupOb = NULL; // must be xdefref'd. + + // Support other objects with a "timetuple" method. + PyObject *method = PyObject_GetAttrString(timeOb, "timetuple"); + if (method == NULL) + PyErr_Clear(); + else { + timeOb = PyEval_CallObject(method, NULL); + Py_DECREF(method); + if (!timeOb) + return NULL; + cleanupOb = timeOb; // new reference that must be nuked. + // now we should fall into the sequence check! + } + if (PyNumber_Check(timeOb)) { + PyObject *longob = PyNumber_Long(timeOb); + if (longob) { + long t = PyLong_AsLong(longob); + if (t == -1) { + if (!PyErr_Occurred()) + PyErr_BadArgument(); } - double dval = (double)tt + (millisec / 1000.0); - PyObject *args = Py_BuildValue("(d)", dval); - if (!args) - return NULL; - result = PyDateTimeAPI->DateTime_FromTimestamp((PyObject *)(&PyWinDateTimeType), args, NULL); - Py_DECREF(args); + else + result = PyWinTimeObject_Fromtime_t(t); + Py_DECREF(longob); } - else - // result stays NULL. - PyErr_Format(PyExc_TypeError, "Objects of type '%s' can not be used as a time object", - timeOb->ob_type->tp_name); - Py_XDECREF(cleanupOb); - return result; } - - PyObject *PyWinObject_FromSYSTEMTIME(const SYSTEMTIME &t) - { - // SYSTEMTIME structures explicitly use UTC. - PyObject *obtz = GetTZUTC(); - if (!obtz) + else if (PySequence_Check(timeOb)) { + assert(!PyErr_Occurred()); // should be no stale errors! + // convert a timetuple, with optional millisecond extension, + // into a datetime object. ie: + // >>> datetime.datetime.fromtimestamp(time.mktime(timetuple)) + // but we 'inline' the time.mktime step... + struct tm buf; + time_t tt; + int millisec = 0; + // must use a tuple as we use ParseTuple with an optional arg. + PyObject *tuple_args = PySequence_Tuple(timeOb); + if (!tuple_args) + return NULL; + BOOL ok = gettmarg(tuple_args, &buf, &millisec); + Py_DECREF(tuple_args); + if (!ok) + return NULL; + tt = mktime(&buf); + if (tt == (time_t)(-1)) { + PyErr_SetString(PyExc_OverflowError, "mktime argument out of range"); return NULL; - // If the value is larger than the datetime module can handle, we return - // the max datetime value. - PyObject *ret; - if (t.wYear > 9999) { // sadly this constant isn't exposed. - ret = PyObject_GetAttrString((PyObject *)PyDateTimeAPI->DateTimeType, "max"); - } - else { - ret = PyDateTimeAPI->DateTime_FromDateAndTime(t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, - t.wMilliseconds * 1000, obtz, &PyWinDateTimeType); } - Py_DECREF(obtz); - return ret; + double dval = (double)tt + (millisec / 1000.0); + PyObject *args = Py_BuildValue("(d)", dval); + if (!args) + return NULL; + result = PyDateTimeAPI->DateTime_FromTimestamp((PyObject *)(&PyWinDateTimeType), args, NULL); + Py_DECREF(args); } + else + // result stays NULL. + PyErr_Format(PyExc_TypeError, "Objects of type '%s' can not be used as a time object", + timeOb->ob_type->tp_name); + Py_XDECREF(cleanupOb); + return result; +} - PyObject *PyWinObject_FromFILETIME(const FILETIME &t) - { - // XXX - We should create a datetime object using the localtz here, - // but for now we only have a utc tz available, so convert to a - // systemtime and go from there. - SYSTEMTIME st; - if (!FileTimeToSystemTime(&t, &st)) - return PyWin_SetAPIError("FileTimeToSystemTime"); - return PyWinObject_FromSYSTEMTIME(st); +PyObject *PyWinObject_FromSYSTEMTIME(const SYSTEMTIME &t) +{ + // SYSTEMTIME structures explicitly use UTC. + PyObject *obtz = GetTZUTC(); + if (!obtz) + return NULL; + // If the value is larger than the datetime module can handle, we return + // the max datetime value. + PyObject *ret; + if (t.wYear > 9999) { // sadly this constant isn't exposed. + ret = PyObject_GetAttrString((PyObject *)PyDateTimeAPI->DateTimeType, "max"); } - - static double round(double Value, int Digits) - { - assert(Digits >= -4 && Digits <= 4); - int Idx = Digits + 4; - double v[] = {1e-4, 1e-3, 1e-2, 1e-1, 1, 10, 1e2, 1e3, 1e4}; - return floor(Value * v[Idx] + 0.5) / (v[Idx]); + else { + ret = PyDateTimeAPI->DateTime_FromDateAndTime(t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, + t.wMilliseconds * 1000, obtz, &PyWinDateTimeType); } + Py_DECREF(obtz); + return ret; +} - PyObject *PyWinObject_FromDATE(DATE t) - { - // via https://www.codeproject.com/Articles/17576/SystemTime-to-VariantTime-with-Milliseconds - // (in particular, see the comments) - double fraction = t - (int)t; // extracts the fraction part - double hours = (fraction - (int)fraction) * 24.0; - double minutes = (hours - (int)hours) * 60.0; - double seconds = round((minutes - (int)minutes) * 60.0, 4); - double milliseconds = round((seconds - (int)seconds) * 1000.0, 0); - // Strip off the msec part of time - double TimeWithoutMsecs = t - (ONETHOUSANDMILLISECONDS / 1000.0 * milliseconds); - - // We might have rounded ms to 1000 which blows up datetime. Round up - // to the next second. - if (milliseconds >= 1000) { - TimeWithoutMsecs += ONETHOUSANDMILLISECONDS; - milliseconds = 0; - } +PyObject *PyWinObject_FromFILETIME(const FILETIME &t) +{ + // XXX - We should create a datetime object using the localtz here, + // but for now we only have a utc tz available, so convert to a + // systemtime and go from there. + SYSTEMTIME st; + if (!FileTimeToSystemTime(&t, &st)) + return PyWin_SetAPIError("FileTimeToSystemTime"); + return PyWinObject_FromSYSTEMTIME(st); +} - // Let the OS translate the variant date/time - SYSTEMTIME st; - if (!VariantTimeToSystemTime(TimeWithoutMsecs, &st)) { - return PyWin_SetAPIError("VariantTimeToSystemTime"); - } - if (milliseconds > 0.0) { - // add the msec part to the systemtime object - st.wMilliseconds = (WORD)milliseconds; - } - return PyWinObject_FromSYSTEMTIME(st); - } +static double round(double Value, int Digits) +{ + assert(Digits >= -4 && Digits <= 4); + int Idx = Digits + 4; + double v[] = {1e-4, 1e-3, 1e-2, 1e-1, 1, 10, 1e2, 1e3, 1e4}; + return floor(Value * v[Idx] + 0.5) / (v[Idx]); +} - PyObject *PyWinTimeObject_Fromtime_t(time_t t) - { - PyObject *args = Py_BuildValue("(i)", (int)t); - if (!args) - return NULL; - PyObject *ret = PyDateTimeAPI->DateTime_FromTimestamp((PyObject *)(&PyWinDateTimeType), args, NULL); - if (ret == NULL) { - // datetime throws an OSError on failure, but for compatibility with - // Python 2, we turn that into a ValueError. - PyErr_Clear(); - PyErr_SetString(PyExc_ValueError, "invalid timestamp"); - } - Py_DECREF(args); - return ret; +PyObject *PyWinObject_FromDATE(DATE t) +{ + // via https://www.codeproject.com/Articles/17576/SystemTime-to-VariantTime-with-Milliseconds + // (in particular, see the comments) + double fraction = t - (int)t; // extracts the fraction part + double hours = (fraction - (int)fraction) * 24.0; + double minutes = (hours - (int)hours) * 60.0; + double seconds = round((minutes - (int)minutes) * 60.0, 4); + double milliseconds = round((seconds - (int)seconds) * 1000.0, 0); + // Strip off the msec part of time + double TimeWithoutMsecs = t - (ONETHOUSANDMILLISECONDS / 1000.0 * milliseconds); + + // We might have rounded ms to 1000 which blows up datetime. Round up + // to the next second. + if (milliseconds >= 1000) { + TimeWithoutMsecs += ONETHOUSANDMILLISECONDS; + milliseconds = 0; } - // Converts a TimeStamp, which is in 100 nanosecond units like a FILETIME - // See comments in pywintypes.h re LARGE_INTEGER vs TimeStamp - PyObject *PyWinObject_FromTimeStamp(const LARGE_INTEGER &ts) - { - FILETIME ft; - ft.dwHighDateTime = ts.HighPart; - ft.dwLowDateTime = ts.LowPart; - return PyWinObject_FromFILETIME(ft); + // Let the OS translate the variant date/time + SYSTEMTIME st; + if (!VariantTimeToSystemTime(TimeWithoutMsecs, &st)) { + return PyWin_SetAPIError("VariantTimeToSystemTime"); } - - // A couple of public functions used by the module init - BOOL _PyWinDateTime_Init() - { - PyDateTime_IMPORT; - if (!PyDateTimeAPI) - return NULL; - PyWinDateTimeType.tp_base = PyDateTimeAPI->DateTimeType; - PyWinDateTimeType.tp_basicsize = PyDateTimeAPI->DateTimeType->tp_basicsize; - PyWinDateTimeType.tp_new = PyDateTimeAPI->DateTimeType->tp_new; - PyWinDateTimeType.tp_dealloc = PyDateTimeAPI->DateTimeType->tp_dealloc; - if (PyType_Ready(&PyWinDateTimeType) == -1) - return FALSE; - return TRUE; + if (milliseconds > 0.0) { + // add the msec part to the systemtime object + st.wMilliseconds = (WORD)milliseconds; } + return PyWinObject_FromSYSTEMTIME(st); +} - BOOL _PyWinDateTime_PrepareModuleDict(PyObject * dict) - { - if (PyDict_SetItemString(dict, "TimeType", (PyObject *)&PyWinDateTimeType) == -1) - return FALSE; - return TRUE; +PyObject *PyWinTimeObject_Fromtime_t(time_t t) +{ + PyObject *args = Py_BuildValue("(i)", (int)t); + if (!args) + return NULL; + PyObject *ret = PyDateTimeAPI->DateTime_FromTimestamp((PyObject *)(&PyWinDateTimeType), args, NULL); + if (ret == NULL) { + // datetime throws an OSError on failure, but for compatibility with + // Python 2, we turn that into a ValueError. + PyErr_Clear(); + PyErr_SetString(PyExc_ValueError, "invalid timestamp"); } + Py_DECREF(args); + return ret; +} + +// Converts a TimeStamp, which is in 100 nanosecond units like a FILETIME +// See comments in pywintypes.h re LARGE_INTEGER vs TimeStamp +PyObject *PyWinObject_FromTimeStamp(const LARGE_INTEGER &ts) +{ + FILETIME ft; + ft.dwHighDateTime = ts.HighPart; + ft.dwLowDateTime = ts.LowPart; + return PyWinObject_FromFILETIME(ft); +} + +// A couple of public functions used by the module init +BOOL _PyWinDateTime_Init() +{ + PyDateTime_IMPORT; + if (!PyDateTimeAPI) + return NULL; + PyWinDateTimeType.tp_base = PyDateTimeAPI->DateTimeType; + PyWinDateTimeType.tp_basicsize = PyDateTimeAPI->DateTimeType->tp_basicsize; + PyWinDateTimeType.tp_new = PyDateTimeAPI->DateTimeType->tp_new; + PyWinDateTimeType.tp_dealloc = PyDateTimeAPI->DateTimeType->tp_dealloc; + if (PyType_Ready(&PyWinDateTimeType) == -1) + return FALSE; + return TRUE; +} + +BOOL _PyWinDateTime_PrepareModuleDict(PyObject *dict) +{ + if (PyDict_SetItemString(dict, "TimeType", (PyObject *)&PyWinDateTimeType) == -1) + return FALSE; + return TRUE; +} diff --git a/win32/src/PyUnicode.cpp b/win32/src/PyUnicode.cpp index 5bb7b084dc..b7382401ed 100644 --- a/win32/src/PyUnicode.cpp +++ b/win32/src/PyUnicode.cpp @@ -21,12 +21,12 @@ BOOL PyWinObject_AsPfnAllocatedWCHAR(PyObject *stringObject, void *(*pfnAllocato if (buf == NULL) return FALSE; - /* We assume that we dont need more 'wide characters' for the result + /* We assume that we don't need more 'wide characters' for the result then the number of bytes in the input. Often we will need less, as the input may contain multi-byte chars, but we should never need more */ - PYWIN_CHECK_SSIZE_DWORD(cch+1, FALSE); + PYWIN_CHECK_SSIZE_DWORD(cch + 1, FALSE); *ppResult = (LPWSTR)(*pfnAllocator)((cch + 1) * sizeof(WCHAR)); if (*ppResult) /* convert and get the final character size */ @@ -34,7 +34,9 @@ BOOL PyWinObject_AsPfnAllocatedWCHAR(PyObject *stringObject, void *(*pfnAllocato } else if (PyUnicode_Check(stringObject)) { // copy the value, including embedded NULLs - TmpWCHAR v = stringObject; if (!v) return FALSE; + TmpWCHAR v = stringObject; + if (!v) + return FALSE; Py_ssize_t cch = v.length; *ppResult = (WCHAR *)pfnAllocator((cch + 1) * sizeof(WCHAR)); if (*ppResult) @@ -182,7 +184,9 @@ BOOL PyWinObject_AsBstr(PyObject *stringObject, BSTR *pResult, BOOL bNoneOK /*= // copy the value, including embedded NULLs // Py3.12+: only conversion yields the correct number of wide chars (incl. surrogate pairs). // For simplicity we use a temp buffer. - TmpWCHAR tw = stringObject; if (!tw) return FALSE; + TmpWCHAR tw = stringObject; + if (!tw) + return FALSE; PYWIN_CHECK_SSIZE_DWORD(tw.length, NULL); // SysAllocStringLen allocates length+1 wchars (and puts a \0 at end); like PyUnicode_AsWideCharString *pResult = SysAllocStringLen(tw, (UINT)tw.length); diff --git a/win32/src/PyWinTypes.h b/win32/src/PyWinTypes.h index b45184cf2e..620aada9c1 100644 --- a/win32/src/PyWinTypes.h +++ b/win32/src/PyWinTypes.h @@ -127,14 +127,12 @@ PYWINTYPES_EXPORT PyObject *PyWin_SetBasicCOMError(HRESULT hr); // (We also use this for UINT and ULONG, all of which are 32bit unsigned ints.) // Sometimes we need to downcast from a ssize_t to a DWORD -inline bool PyWin_is_ssize_dword(Py_ssize_t val) { - return val <= MAXDWORD; -} +inline bool PyWin_is_ssize_dword(Py_ssize_t val) { return val <= MAXDWORD; } -#define PYWIN_CHECK_SSIZE_DWORD(val, failResult) \ - if (!PyWin_is_ssize_dword(val)) { \ +#define PYWIN_CHECK_SSIZE_DWORD(val, failResult) \ + if (!PyWin_is_ssize_dword(val)) { \ PyErr_SetString(PyExc_ValueError, "value is larger than a DWORD"); \ - return failResult; \ + return failResult; \ } // Almost all of these are roughly identical! But start with BSTR @@ -171,7 +169,7 @@ PYWINTYPES_EXPORT void PyWinObject_FreeChars(char *pResult); // Automatically freed WCHAR that can be used anywhere WCHAR * is required class TmpWCHAR { public: - WCHAR *tmp; // (NULL after conversion error) + WCHAR *tmp; // (NULL after conversion error) Py_ssize_t length; // only set after successful auto-conversion; w/o trailing \0 PyObject *u; // auxiliary slot for u2w() @@ -179,7 +177,8 @@ class TmpWCHAR { TmpWCHAR(WCHAR *t) { tmp = t; } TmpWCHAR(PyObject *ob) : tmp(NULL) { *this = ob; } WCHAR *u2w() { return *this = u; } - WCHAR *operator=(PyObject *ob) { + WCHAR *operator=(PyObject *ob) + { if (tmp) PyMem_Free(tmp); if (ob == NULL) @@ -198,11 +197,16 @@ class TmpWCHAR { WCHAR **operator&() { return &tmp; } boolean operator==(WCHAR *t) { return tmp == t; } operator WCHAR *() { return tmp; } - ~TmpWCHAR() { if (tmp) PyMem_Free(tmp); } + ~TmpWCHAR() + { + if (tmp) + PyMem_Free(tmp); + } + private: // Block unwanted copy construction - TmpWCHAR(const TmpWCHAR& o); // = delete; - const TmpWCHAR& operator=(const TmpWCHAR& o); // = delete; + TmpWCHAR(const TmpWCHAR &o); // = delete; + const TmpWCHAR &operator=(const TmpWCHAR &o); // = delete; }; // More string helpers - how many do we need? @@ -251,35 +255,35 @@ PYWINTYPES_EXPORT BOOL PyWinObject_AsCharArray(PyObject *str_seq, char ***pchars // Bytes/Buffer helpers. // replacement for PyWinObject_AsReadBuffer and PyWinObject_AsWriteBuffer -class PYWINTYPES_EXPORT PyWinBufferView -{ -public: +class PYWINTYPES_EXPORT PyWinBufferView { + public: PyWinBufferView() { m_view.obj = NULL; } - PyWinBufferView(PyObject *ob, bool bWrite = false, bool bNoneOk = false) { + PyWinBufferView(PyObject *ob, bool bWrite = false, bool bNoneOk = false) + { m_view.obj = NULL; init(ob, bWrite, bNoneOk); } ~PyWinBufferView() { release(); } bool init(PyObject *ob, bool bWrite = false, bool bNoneOk = false); - void release() { + void release() + { if (m_view.obj != NULL && m_view.obj != Py_None) { PyBuffer_Release(&m_view); // sets view->obj = NULL } } bool ok() { return m_view.obj != NULL; } - void* ptr() { return m_view.buf; } + void *ptr() { return m_view.buf; } DWORD len() { return static_cast(m_view.len); } -private: + private: Py_buffer m_view; // don't copy objects and don't use C++ >= 11 -> not implemented private // copy ctor and assignment operator - PyWinBufferView(const PyWinBufferView& src); - PyWinBufferView& operator=(PyWinBufferView const &); + PyWinBufferView(const PyWinBufferView &src); + PyWinBufferView &operator=(PyWinBufferView const &); }; - // For 64-bit python compatibility, convert sequence to tuple and check length fits in a DWORD PYWINTYPES_EXPORT PyObject *PyWinSequence_Tuple(PyObject *obseq, DWORD *len); @@ -399,34 +403,36 @@ PYWINTYPES_EXPORT void PyWinObject_FreeResourceId(WCHAR *resource_id); // Auto-freed WPARAM / LPARAM which ensure any memory referenced remains valid when a String or // Buffer object is used. Make sure the destructor is called with the GIL held. class PyWin_PARAMHolder { - protected: + protected: WPARAM _pa; // Holds *either* a PyWinBufferView (which will auto-free) *or* a "void *" that we // will auto-free. void *_pymem; - void _free() { + void _free() + { if (_pymem) { PyMem_Free(_pymem); _pymem = NULL; } } - public: + + public: PyWinBufferView bufferView; - PyWin_PARAMHolder(WPARAM t=0):_pa(t),_pymem(NULL) {} - ~PyWin_PARAMHolder() { - _free(); - } - WCHAR *set_allocated(WCHAR *t) { - assert(!bufferView.ok()); // should be one or the other. + PyWin_PARAMHolder(WPARAM t = 0) : _pa(t), _pymem(NULL) {} + ~PyWin_PARAMHolder() { _free(); } + WCHAR *set_allocated(WCHAR *t) + { + assert(!bufferView.ok()); // should be one or the other. _free(); _pymem = t; _pa = (WPARAM)t; return t; } // When init_buffer() fails, an appropriate Python error has been set too - bool init_buffer(PyObject *ob) { - assert(!_pymem); // should be one or the other! + bool init_buffer(PyObject *ob) + { + assert(!_pymem); // should be one or the other! _free(); if (!bufferView.init(ob)) { return false; @@ -435,9 +441,7 @@ class PyWin_PARAMHolder { return true; } - WPARAM operator=(WPARAM t) { - return _pa = t; - } + WPARAM operator=(WPARAM t) { return _pa = t; } operator WPARAM() { return _pa; } operator LPARAM() { return (LPARAM)_pa; } }; @@ -447,7 +451,10 @@ inline PyObject *PyWinObject_FromPARAM(WPARAM param) { return PyWinObject_FromUL inline PyObject *PyWinObject_FromPARAM(LPARAM param) { return PyWinObject_FromULONG_PTR(param); } PYWINTYPES_EXPORT BOOL PyWinObject_AsSimplePARAM(PyObject *ob, WPARAM *pparam); -inline BOOL PyWinObject_AsSimplePARAM(PyObject *ob, LPARAM *pparam) { return PyWinObject_AsSimplePARAM(ob, (WPARAM *)pparam); } +inline BOOL PyWinObject_AsSimplePARAM(PyObject *ob, LPARAM *pparam) +{ + return PyWinObject_AsSimplePARAM(ob, (WPARAM *)pparam); +} // RECT conversions // @object PyRECT|Tuple of 4 ints defining a rectangle: (left, top, right, bottom) @@ -530,7 +537,7 @@ PYWINTYPES_EXPORT PyObject *PyWinMethod_NewHANDLE(PyObject *self, PyObject *args // A global function that does the right thing wrt closing a "handle". // The object can be either a PyHANDLE or an integer. -// If result is FALSE, a Python error is all setup (cf PyHANDLE::Close(), which doesnt set the Python error) +// If result is FALSE, a Python error is all setup (cf PyHANDLE::Close(), which doesn't set the Python error) PYWINTYPES_EXPORT BOOL PyWinObject_CloseHANDLE(PyObject *obHandle); PYWINTYPES_EXPORT BOOL PyWinObject_AsHKEY(PyObject *ob, HKEY *pRes); diff --git a/win32/src/PyWinTypesmodule.cpp b/win32/src/PyWinTypesmodule.cpp index 313dfeb1a3..1564f84d52 100644 --- a/win32/src/PyWinTypesmodule.cpp +++ b/win32/src/PyWinTypesmodule.cpp @@ -601,7 +601,8 @@ void PyWinObject_FreeResourceId(WCHAR *resource_id) // Conversion for WPARAM and LPARAM from a simple integer value. Used when we // can't guarantee memory pointed at will remain valid as long as necessary. // In that scenario, the caller is responsible for arranging memory safety. -BOOL PyWinObject_AsSimplePARAM(PyObject *ob, WPARAM *wparam) { +BOOL PyWinObject_AsSimplePARAM(PyObject *ob, WPARAM *wparam) +{ // convert simple integers directly void *simple = PyLong_AsVoidPtr(ob); if (simple || !PyErr_Occurred()) { @@ -615,8 +616,7 @@ BOOL PyWinObject_AsSimplePARAM(PyObject *ob, WPARAM *wparam) { return TRUE; } - PyErr_Format(PyExc_TypeError, "WPARAM is simple, so must be an int object (got %s)", - ob->ob_type->tp_name); + PyErr_Format(PyExc_TypeError, "WPARAM is simple, so must be an int object (got %s)", ob->ob_type->tp_name); return FALSE; } @@ -691,9 +691,11 @@ bool PyWinBufferView::init(PyObject *ob, bool bWrite, bool bNoneOk) m_view.obj = Py_None; m_view.buf = NULL; m_view.len = 0; - } else + } + else PyErr_SetString(PyExc_TypeError, "Buffer cannot be None"); - } else if (ob != NULL) { + } + else if (ob != NULL) { PyObject_GetBuffer(ob, &m_view, bWrite ? PyBUF_WRITABLE : PyBUF_SIMPLE); #ifdef _WIN64 @@ -702,7 +704,8 @@ bool PyWinBufferView::init(PyObject *ob, bool bWrite, bool bNoneOk) PyErr_Format(PyExc_ValueError, "Buffer length can be at most %d characters", MAXDWORD); } #endif - } else // ob == NULL handled as not ok + } + else // ob == NULL handled as not ok m_view.obj = NULL; return ok(); } @@ -764,9 +767,9 @@ static struct PyMethodDef pywintypes_functions[] = { #endif {"Time", PyWinMethod_NewTime, 1}, // @pymeth Time|Makes a object from the argument. {"TimeStamp", PyWinMethod_NewTimeStamp, 1}, // @pymeth Time|Makes a object from the argument. - {"CreateGuid", PyWin_CreateGuid, 1}, // @pymeth CreateGuid|Creates a new, unique GUIID. - {"ACL", PyWinMethod_NewACL, 1}, // @pymeth ACL|Creates a new object. - {"SID", PyWinMethod_NewSID, 1}, // @pymeth SID|Creates a new object. + {"CreateGuid", PyWin_CreateGuid, 1}, // @pymeth CreateGuid|Creates a new, unique GUIID. + {"ACL", PyWinMethod_NewACL, 1}, // @pymeth ACL|Creates a new object. + {"SID", PyWinMethod_NewSID, 1}, // @pymeth SID|Creates a new object. {"SECURITY_ATTRIBUTES", PyWinMethod_NewSECURITY_ATTRIBUTES, 1}, // @pymeth SECURITY_ATTRIBUTES|Creates a new object. {"SECURITY_DESCRIPTOR", PyWinMethod_NewSECURITY_DESCRIPTOR, @@ -798,8 +801,7 @@ int PyWinGlobals_Ensure() PyDict_SetItemString(d, "Exception", PyExc_Exception); PyDict_SetItemString(d, "__name__", name); Py_DECREF(name); - PyObject *bimod = PyImport_ImportModule( - "builtins"); + PyObject *bimod = PyImport_ImportModule("builtins"); if ((bimod == NULL) || PyDict_SetItemString(d, "__builtins__", bimod) == -1) { Py_XDECREF(bimod); return -1; @@ -875,14 +877,12 @@ int PyWinGlobals_Ensure() ??? All extension modules that call this need to be changed to check the exit code ??? */ if (PyType_Ready(&PyHANDLEType) == -1 || PyType_Ready(&PyOVERLAPPEDType) == -1 || - PyType_Ready(&PyDEVMODEWType) == -1 || - PyType_Ready(&PyWAVEFORMATEXType) == -1 + PyType_Ready(&PyDEVMODEWType) == -1 || PyType_Ready(&PyWAVEFORMATEXType) == -1 #ifndef NO_PYWINTYPES_IID || PyType_Ready(&PyIIDType) == -1 #endif // NO_PYWINTYPES_IID || PyType_Ready(&PySECURITY_DESCRIPTORType) == -1 || PyType_Ready(&PySECURITY_ATTRIBUTESType) == -1 || - PyType_Ready(&PySIDType) == -1 || PyType_Ready(&PyACLType) == -1 - ) + PyType_Ready(&PySIDType) == -1 || PyType_Ready(&PyACLType) == -1) return -1; if (!_PyWinDateTime_Init()) @@ -966,8 +966,7 @@ PYWIN_MODULE_INIT_FUNC(pywintypes) PYWIN_MODULE_INIT_RETURN_SUCCESS; } -extern "C" __declspec(dllexport) - BOOL WINAPI DllMain(HANDLE hInstance, DWORD dwReason, LPVOID lpReserved) +extern "C" __declspec(dllexport) BOOL WINAPI DllMain(HANDLE hInstance, DWORD dwReason, LPVOID lpReserved) { FARPROC fp; // dll usually will already be loaded @@ -1063,10 +1062,10 @@ extern "C" __declspec(dllexport) } // Function to format a python traceback into a character string. -#define GPEM_ERROR(what) \ - { \ +#define GPEM_ERROR(what) \ + { \ errorMsg = L""; \ - goto done; \ + goto done; \ } PYWINTYPES_EXPORT WCHAR *GetPythonTraceback(PyObject *exc_type, PyObject *exc_value, PyObject *exc_tb) { @@ -1085,15 +1084,15 @@ PYWINTYPES_EXPORT WCHAR *GetPythonTraceback(PyObject *exc_type, PyObject *exc_va modStringIO = PyImport_ImportModule("io"); if (modStringIO == NULL) - GPEM_ERROR("cant import cStringIO"); + GPEM_ERROR("can't import cStringIO"); modTB = PyImport_ImportModule("traceback"); if (modTB == NULL) - GPEM_ERROR("cant import traceback"); + GPEM_ERROR("can't import traceback"); /* Construct a cStringIO object */ obFuncStringIO = PyObject_GetAttrString(modStringIO, "StringIO"); if (obFuncStringIO == NULL) - GPEM_ERROR("cant find cStringIO.StringIO"); + GPEM_ERROR("can't find cStringIO.StringIO"); obStringIO = PyObject_CallObject(obFuncStringIO, NULL); if (obStringIO == NULL) GPEM_ERROR("cStringIO.StringIO() failed"); @@ -1101,21 +1100,18 @@ PYWINTYPES_EXPORT WCHAR *GetPythonTraceback(PyObject *exc_type, PyObject *exc_va /* Get the traceback.print_exception function, and call it. */ obFuncTB = PyObject_GetAttrString(modTB, "print_exception"); if (obFuncTB == NULL) - GPEM_ERROR("cant find traceback.print_exception"); + GPEM_ERROR("can't find traceback.print_exception"); // Py3k has added an undocumented 'chain' argument which defaults to True // and causes all kinds of exceptions while trying to print a traceback! // This *could* be useful thought if we can tame it - later! int chain = 0; - argsTB = Py_BuildValue( - "OOOOOi", - exc_type ? exc_type : Py_None, exc_value ? exc_value : Py_None, exc_tb ? exc_tb : Py_None, - Py_None, // limit - obStringIO, - chain - ); + argsTB = Py_BuildValue("OOOOOi", exc_type ? exc_type : Py_None, exc_value ? exc_value : Py_None, + exc_tb ? exc_tb : Py_None, + Py_None, // limit + obStringIO, chain); if (argsTB == NULL) - GPEM_ERROR("cant make print_exception arguments"); + GPEM_ERROR("can't make print_exception arguments"); obResult = PyObject_CallObject(obFuncTB, argsTB); if (obResult == NULL) { @@ -1131,7 +1127,7 @@ PYWINTYPES_EXPORT WCHAR *GetPythonTraceback(PyObject *exc_type, PyObject *exc_va Py_DECREF(obFuncStringIO); obFuncStringIO = PyObject_GetAttrString(obStringIO, "getvalue"); if (obFuncStringIO == NULL) - GPEM_ERROR("cant find getvalue function"); + GPEM_ERROR("can't find getvalue function"); Py_DECREF(obResult); obResult = PyObject_CallObject(obFuncStringIO, NULL); if (obResult == NULL) diff --git a/win32/src/PythonService.cpp b/win32/src/PythonService.cpp index 7f02a30e5e..181c97b50c 100644 --- a/win32/src/PythonService.cpp +++ b/win32/src/PythonService.cpp @@ -146,10 +146,10 @@ SERVICE_STATUS stoppedStatus = {SERVICE_WIN32_OWN_PROCESS, SERVICE_STATUS stoppedErrorStatus = {SERVICE_WIN32_OWN_PROCESS, SERVICE_STOPPED, - 0, // dwControlsAccepted - ERROR_SERVICE_SPECIFIC_ERROR, // dwWin32ExitCode - 0x20000001, // dwServiceSpecificExitCode - 0, // dwCheckPoint + 0, // dwControlsAccepted + ERROR_SERVICE_SPECIFIC_ERROR, // dwWin32ExitCode + 0x20000001, // dwServiceSpecificExitCode + 0, // dwCheckPoint 0}; // The Service Control Manager/Event Log seems to interpret dwServiceSpecificExitCode as a Win32 Error code // (https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes) @@ -599,7 +599,7 @@ static void PyService_InitPython() have_init = TRUE; // Often for a service, __argv[0] will be just "ExeName", rather // than "c:\path\to\ExeName.exe" - // This, however, shouldnt be a problem, as Python itself + // This, however, shouldn't be a problem, as Python itself // knows how to get the .EXE name when it needs. int pyargc; WCHAR **pyargv = CommandLineToArgvW(GetCommandLineW(), &pyargc); @@ -844,7 +844,7 @@ void WINAPI service_main(DWORD dwArgc, LPTSTR *lpszArgv) instance = LoadPythonServiceInstance(pe->klass, dwArgc, lpszArgv); // If Python has not yet registered the service control handler, then // we are in serious trouble - it is likely the service will enter a - // zombie state, where it wont do anything, but you can not start + // zombie state, where it won't do anything, but you can not start // another. Therefore, we still create register the handler, thereby // getting a handle, so we can immediately tell Windows the service // is rooted (that is a technical term!) @@ -899,7 +899,7 @@ void WINAPI service_main(DWORD dwArgc, LPTSTR *lpszArgv) // try to report the stopped status to the service control manager. Py_XDECREF(start); Py_XDECREF(instance); - if (pe && pe->sshStatusHandle) { // Wont be true if debugging. + if (pe && pe->sshStatusHandle) { // Won't be true if debugging. if (!SetServiceStatus(pe->sshStatusHandle, (stopWithError ? &stoppedErrorStatus : &stoppedStatus))) ReportAPIError(PYS_E_API_CANT_SET_STOPPED); } @@ -1461,9 +1461,10 @@ int _tmain(int argc, TCHAR **argv) // now get the handle to the DLL, and call the main function. if (PyBytes_Check(f)) hmod = GetModuleHandleA(PyBytes_AsString(f)); - else if (TmpWCHAR tw=f) { + else if (TmpWCHAR tw = f) { hmod = GetModuleHandleW(tw); - } else { + } + else { PyErr_SetString(PyExc_TypeError, "servicemanager.__file__ is not a string or unicode !"); goto failed; } diff --git a/win32/src/_win32sysloader.cpp b/win32/src/_win32sysloader.cpp index 2a5db22ce4..0a9e4dcac7 100644 --- a/win32/src/_win32sysloader.cpp +++ b/win32/src/_win32sysloader.cpp @@ -52,15 +52,12 @@ static PyObject *PyLoadModule(PyObject *self, PyObject *args) if (!modName) return NULL; - // Python 3.7 vs 3.8 use different flags for LoadLibraryEx and we match them. - // See github issue 1787. + // Python 3.7 vs 3.8 use different flags for LoadLibraryEx and we match them. + // See github issue 1787. #if (PY_VERSION_HEX < 0x03080000) - HINSTANCE hinst = LoadLibraryEx(modName, NULL, - LOAD_WITH_ALTERED_SEARCH_PATH); + HINSTANCE hinst = LoadLibraryEx(modName, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); #else - HINSTANCE hinst = LoadLibraryEx(modName, NULL, - LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | - LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR); + HINSTANCE hinst = LoadLibraryEx(modName, NULL, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR); #endif PyMem_Free(modName); if (hinst == NULL) { diff --git a/win32/src/_winxptheme.i b/win32/src/_winxptheme.i index 7b2b72bfaf..3ef07bbb9c 100644 --- a/win32/src/_winxptheme.i +++ b/win32/src/_winxptheme.i @@ -168,7 +168,7 @@ typedef long FLAGS; // class name) to provide the class an opportunity // to get the "best" match between the class and // the current theme. For example, a button might -// pass L"OkButton, Button" if its ID=ID_OK. If +// pass L"OkButton, Button" if it's ID=ID_OK. If // the current theme has an entry for OkButton, // that will be used. Otherwise, we fall back on // the normal Button entry. diff --git a/win32/src/odbc.cpp b/win32/src/odbc.cpp index dfbe4c4fe1..6190ce53c1 100644 --- a/win32/src/odbc.cpp +++ b/win32/src/odbc.cpp @@ -716,13 +716,14 @@ static int ibindDate(cursorObject *cur, int column, PyObject *item) // Last 3 items are ignored. PyObject *obwday, *obyday, *obdst; if (!PyArg_ParseTuple(timeseq, "hhh|hhhOOO:TIMESTAMP_STRUCT", &dt->year, &dt->month, &dt->day, &dt->hour, - &dt->minute, &dt->second, &obwday, &obyday, &obdst)) + &dt->minute, &dt->second, &obwday, &obyday, &obdst)) return 0; TmpPyObject usec = PyObject_GetAttrString(item, "microsecond"); if (usec == NULL) { PyErr_Clear(); - } else { + } + else { dt->fraction = PyLong_AsUnsignedLong(usec); if (dt->fraction == -1 && PyErr_Occurred()) return 0; @@ -817,7 +818,9 @@ static int ibindString(cursorObject *cur, int column, PyObject *item) static int ibindUnicode(cursorObject *cur, int column, PyObject *item) { - TmpWCHAR wval = item; if (!wval) return 0; + TmpWCHAR wval = item; + if (!wval) + return 0; Py_ssize_t nchars = wval.length + 1; Py_ssize_t nbytes = nchars * sizeof(WCHAR); @@ -853,8 +856,7 @@ static int rewriteQuery(TCHAR *out, const TCHAR *in) parseContext ctx; initParseContext(&ctx, in); - while (*out++ = doParse(&ctx)) - ; + while (*out++ = doParse(&ctx)); return ctx.parmCount; } @@ -893,8 +895,7 @@ static int bindInput(cursorObject *cur, PyObject *vars, int columns) else if (PyWinTime_Check(item)) { rv = ibindDate(cur, iCol, item); } - else if (PyObject_CheckBuffer(item)) - { + else if (PyObject_CheckBuffer(item)) { rv = ibindRaw(cur, iCol, item); } else { @@ -1016,7 +1017,8 @@ static BOOL bindOutput(cursorObject *cur) break; case SQL_VARCHAR: case SQL_WVARCHAR: - if (!bindOutputVar(cur, wcharCopy, SQL_C_WCHAR, (((vsize == 0) ? cur->max_width : vsize) + 1) * sizeof(WCHAR), pos, false)) + if (!bindOutputVar(cur, wcharCopy, SQL_C_WCHAR, + (((vsize == 0) ? cur->max_width : vsize) + 1) * sizeof(WCHAR), pos, false)) return FALSE; typeOf = DbiString; break; diff --git a/win32/src/stddde.h b/win32/src/stddde.h index 2e36398e26..85688c1f92 100644 --- a/win32/src/stddde.h +++ b/win32/src/stddde.h @@ -56,8 +56,8 @@ class CDDEAllocator { LPBYTE p = (LPBYTE)(const TCHAR *)cs; DWORD cb = (cs.GetLength() + 1) * sizeof(TCHAR); - if(m_wFmt == CF_TEXT) { - p = (LPBYTE)(const char*)CT2CA(cs); + if (m_wFmt == CF_TEXT) { + p = (LPBYTE)(const char *)CT2CA(cs); cb = (cs.GetLength() + 1) * sizeof(const char); } diff --git a/win32/src/timermodule.cpp b/win32/src/timermodule.cpp index 826cb19432..cc47889188 100644 --- a/win32/src/timermodule.cpp +++ b/win32/src/timermodule.cpp @@ -9,7 +9,7 @@ // @doc - Contains autoduck comments for documentation #include "pywintypes.h" -//#include "abstract.h" +// #include "abstract.h" static PyObject *timer_id_callback_map = NULL; diff --git a/win32/src/win32apimodule.cpp b/win32/src/win32apimodule.cpp index c6a0dad4b4..026816e69d 100644 --- a/win32/src/win32apimodule.cpp +++ b/win32/src/win32apimodule.cpp @@ -1180,11 +1180,14 @@ static PyObject *PyLoadCursor(PyObject *self, PyObject *args) return PyWinLong_FromHANDLE(ret); } -// @pymethod [string]|win32api|CommandLineToArgv|Parses a command line string and returns a list of command line arguments, in a way that is similar to sys.argv. +// @pymethod [string]|win32api|CommandLineToArgv|Parses a command line string and returns a list of command line +// arguments, in a way that is similar to sys.argv. static PyObject *PyCommandLineToArgv(PyObject *self, PyObject *args) { TmpWCHAR cmd; - if (!PyArg_ParseTuple(args, "U", &cmd.u) || !cmd.u2w()) // @pyparm string|cmdLine||A string that contains the full command line. If this parameter is an empty string the function returns the path to the current executable file. + if (!PyArg_ParseTuple(args, "U", &cmd.u) || + !cmd.u2w()) // @pyparm string|cmdLine||A string that contains the full command line. If this parameter is an + // empty string the function returns the path to the current executable file. return NULL; int numArgs = 0; LPWSTR *szArglist = CommandLineToArgvW(cmd, &numArgs); @@ -1195,7 +1198,7 @@ static PyObject *PyCommandLineToArgv(PyObject *self, PyObject *args) if (!result) goto done; - for (int i=0; i < numArgs; i++) { + for (int i = 0; i < numArgs; i++) { PyObject *ob = PyWinObject_FromWCHAR(szArglist[i]); if (ob == NULL) { Py_DECREF(result); @@ -1400,7 +1403,9 @@ static PyObject *PyVkKeyScan(PyObject *self, PyObject *args) PyErr_SetString(PyExc_TypeError, "must be a unicode string of length 1"); return NULL; } - TmpWCHAR ts(obkey); if (!ts) return NULL; + TmpWCHAR ts(obkey); + if (!ts) + return NULL; PyW32_BEGIN_ALLOW_THREADS // @pyseeapi VkKeyScanW ret = VkKeyScanW(ts[0]); @@ -1445,7 +1450,9 @@ static PyObject *PyVkKeyScanEx(PyObject *self, PyObject *args) PyErr_SetString(PyExc_TypeError, "must be a unicode string of length 1"); return NULL; } - TmpWCHAR ts(obkey); if (!ts) return NULL; + TmpWCHAR ts(obkey); + if (!ts) + return NULL; PyW32_BEGIN_ALLOW_THREADS // @pyseeapi VkKeyScanExW ret = VkKeyScanExW(ts[0], hkl); @@ -1920,7 +1927,7 @@ static PyObject *PyGetProfileSection(PyObject *self, PyObject *args) delete[] szRetBuf; size *= 2; } - szRetBuf = new TCHAR[size]; /* cant fail - may raise exception */ + szRetBuf = new TCHAR[size]; /* can't fail - may raise exception */ if (szRetBuf == NULL) { PyErr_SetString(PyExc_MemoryError, "Error allocating space for return buffer"); break; @@ -2105,9 +2112,7 @@ static PyObject *PyGetLongPathNameW(PyObject *self, PyObject *args) // The length is the buffer needed, which includes the NULL. // PyUnicode_FromWideChar adds one. PyW32_BEGIN_ALLOW_THREADS DWORD length2 = (*pfnGetLongPathNameW)(fileName, buf, length); - PyW32_END_ALLOW_THREADS - if (length2) - obLongPathNameW = PyUnicode_FromWideChar(buf, -1); + PyW32_END_ALLOW_THREADS if (length2) obLongPathNameW = PyUnicode_FromWideChar(buf, -1); // On success, it is the number of chars copied *not* including // the NULL. Check this is true. assert(length2 + 1 == length); @@ -2119,13 +2124,13 @@ static PyObject *PyGetLongPathNameW(PyObject *self, PyObject *args) return obLongPathNameW; } -// @pymethod int|win32api|GetTickCount|Returns the (64bit) number of milliseconds since windows started. Uses Win API GetTickCount64(). +// @pymethod int|win32api|GetTickCount|Returns the (64bit) number of milliseconds since windows started. Uses Win API +// GetTickCount64(). static PyObject *PyGetTickCount(PyObject *self, PyObject *args) { if (!PyArg_ParseTuple(args, ":PyGetTickCount")) return NULL; - PyW32_BEGIN_ALLOW_THREADS - ULONGLONG count = GetTickCount64(); + PyW32_BEGIN_ALLOW_THREADS ULONGLONG count = GetTickCount64(); PyW32_END_ALLOW_THREADS return Py_BuildValue("K", count); @@ -2223,9 +2228,9 @@ static PyObject *PyGetTimeZoneInformation(PyObject *self, PyObject *args) // example, this member could contain "EST" to indicate Eastern Standard Time. This string is not used by the // operating system, so anything stored there using the SetTimeZoneInformation function is returned unchanged by the // GetTimeZoneInformation function. This string can be empty. - // @tupleitem 2|/tuple|standardTime|Specifies a SYSTEMTIME object that contains a date and local time when - // the transition from daylight saving time to standard time occurs on this operating system. If this date is not - // specified, the wMonth member in the SYSTEMTIME structure must be zero. If this date is specified, the + // @tupleitem 2|/tuple|standardTime|Specifies a SYSTEMTIME object that contains a date and local time + // when the transition from daylight saving time to standard time occurs on this operating system. If this date is + // not specified, the wMonth member in the SYSTEMTIME structure must be zero. If this date is specified, the // DaylightDate value in the TIME_ZONE_INFORMATION structure must also be specified. To select the correct day // in the month, set the wYear member to zero, the wDayOfWeek member to an appropriate weekday, and the wDay member // to a value in the range 1 through 5. Using this notation, the first Sunday in April can be specified, as can the @@ -2517,7 +2522,7 @@ static PyObject *PyGetVersionEx(PyObject *self, PyObject *args) // system. ver.dwBuildNumber, // @tupleitem 2|int|buildNumber|Identifies the build number of the operating system in // the low-order word. (The high-order word contains the major and minor version - // numbers.) + // numbers.) ver.dwPlatformId, // @tupleitem 3|int|platformId|Identifies the platform supported by the operating system. // May be one of VER_PLATFORM_WIN32s, VER_PLATFORM_WIN32_WINDOWS or // VER_PLATFORM_WIN32_NT @@ -2538,7 +2543,7 @@ static PyObject *PyGetVersionEx(PyObject *self, PyObject *args) // system. ver.dwBuildNumber, // @tupleitem 2|int|buildNumber|Identifies the build number of the operating system in // the low-order word. (The high-order word contains the major and minor version - // numbers.) + // numbers.) ver.dwPlatformId, // @tupleitem 3|int|platformId|Identifies the platform supported by the operating system. // May be one of VER_PLATFORM_WIN32s, VER_PLATFORM_WIN32_WINDOWS or // VER_PLATFORM_WIN32_NT @@ -2699,7 +2704,8 @@ PyObject *PyPostMessage(PyObject *self, PyObject *args) PyW32_BEGIN_ALLOW_THREADS; BOOL ok = ::PostMessage(hwnd, message, wParam, lParam); PyW32_END_ALLOW_THREADS; - if (!ok) return ReturnAPIError("PostMessage"); + if (!ok) + return ReturnAPIError("PostMessage"); Py_INCREF(Py_None); return Py_None; } @@ -2727,7 +2733,8 @@ PyObject *PyPostThreadMessage(PyObject *self, PyObject *args) PyW32_BEGIN_ALLOW_THREADS; BOOL ok = ::PostThreadMessage(threadId, message, wParam, lParam); PyW32_END_ALLOW_THREADS; - if (!ok) return ReturnAPIError("PostThreadMessage"); + if (!ok) + return ReturnAPIError("PostThreadMessage"); Py_INCREF(Py_None); return Py_None; } @@ -3266,17 +3273,16 @@ static BOOL PyWinObject_AsRegistryValue(PyObject *value, DWORD typ, BYTE **retDa } return FALSE; case REG_BINARY: - // ALSO handle ALL unknown data types here. Even if we cant support + // ALSO handle ALL unknown data types here. Even if we can't support // it natively, we should handle the bits. - default: - { - PyWinBufferView pybuf(value, false, true); // None ok + default: { + PyWinBufferView pybuf(value, false, true); // None ok if (!pybuf.ok()) return FALSE; // note: this might be unsafe, as we give away the buffer pointer to a // client outside of the scope where our RAII object 'pybuf' resides. - *retDataBuf = (BYTE*)pybuf.ptr(); + *retDataBuf = (BYTE *)pybuf.ptr(); *retDataSize = pybuf.len(); return TRUE; } @@ -3347,7 +3353,7 @@ static PyObject *PyWinObject_FromRegistryValue(BYTE *retDataBuf, DWORD retDataSi break; } case REG_BINARY: - // ALSO handle ALL unknown data types here. Even if we cant support + // ALSO handle ALL unknown data types here. Even if we can't support // it natively, we should handle the bits. default: if (retDataSize == 0) { @@ -4772,7 +4778,10 @@ static PyObject *PySetSystemTime(PyObject *self, PyObject *args) { return ReturnAPIError("SetSystemTime"); } - else { return Py_BuildValue("i", result); } + else + { + return Py_BuildValue("i", result); + } } // @pymethod |win32api|SetThreadLocale|Sets the current thread's locale. @@ -5176,8 +5185,8 @@ PyObject *PyEnumResourceLanguages(PyObject *self, PyObject *args) // Win32 Exception Handler. // // A recursive routine called by the exception handler! -// (I hope this doesnt wind too far on a stack overflow :-) -// Limited testing indicates it doesnt, and this can handle +// (I hope this doesn't wind too far on a stack overflow :-) +// Limited testing indicates it doesn't, and this can handle // a stack overflow fine. PyObject *MakeExceptionRecord(PEXCEPTION_RECORD pExceptionRecord) { @@ -5820,12 +5829,11 @@ PyObject *PyGetPwrCapabilities(PyObject *self, PyObject *args) "DefaultLowLatencyWake", PyLong_FromLong(spc.DefaultLowLatencyWake)); } - // @pymethod dict|win32api|GetSystemPowerStatus|Retrieves the power status of the system // @pyseeapi GetSystemPowerStatus // @comm Requires Winxp or later. // @rdesc Returns a dict representing a SYSTEM_POWER_STATUS struct -PyObject* PyGetSystemPowerStatus(PyObject *self, PyObject *args) +PyObject *PyGetSystemPowerStatus(PyObject *self, PyObject *args) { SYSTEM_POWER_STATUS sps; BOOL res = FALSE; @@ -5835,16 +5843,13 @@ PyObject* PyGetSystemPowerStatus(PyObject *self, PyObject *args) if (!res) return PyWin_SetAPIError("GetSystemPowerStatus"); return Py_BuildValue( - "{s:h, s:h, s:h, s:B, s:L, s:L}", - "ACLineStatus", (sps.ACLineStatus == (BYTE)-1) ? -1 : sps.ACLineStatus, - "BatteryFlag", (sps.BatteryFlag == (BYTE)-1) ? -1 : sps.BatteryFlag, - "BatteryLifePercent", (sps.BatteryLifePercent == (BYTE)-1) ? -1 : sps.BatteryLifePercent, - "SystemStatusFlag", sps.SystemStatusFlag, + "{s:h, s:h, s:h, s:B, s:L, s:L}", "ACLineStatus", (sps.ACLineStatus == (BYTE)-1) ? -1 : sps.ACLineStatus, + "BatteryFlag", (sps.BatteryFlag == (BYTE)-1) ? -1 : sps.BatteryFlag, "BatteryLifePercent", + (sps.BatteryLifePercent == (BYTE)-1) ? -1 : sps.BatteryLifePercent, "SystemStatusFlag", sps.SystemStatusFlag, "BatteryLifeTime", (sps.BatteryLifeTime == (DWORD)-1) ? -1 : (long long)sps.BatteryLifeTime, "BatteryFullLifeTime", (sps.BatteryFullLifeTime == (DWORD)-1) ? -1 : (long long)sps.BatteryFullLifeTime); } - /* List of functions exported by this module */ // @module win32api|A module, encapsulating the Windows Win32 API. static struct PyMethodDef win32api_functions[] = { @@ -5865,10 +5870,12 @@ static struct PyMethodDef win32api_functions[] = { METH_VARARGS | METH_KEYWORDS}, // @pymeth ChangeDisplaySettingsEx|Changes video mode for specified display {"ClipCursor", PyClipCursor, 1}, // @pymeth ClipCursor|Confines the cursor to a rectangular area on the screen. {"CloseHandle", PyCloseHandle, 1}, // @pymeth CloseHandle|Closes an open handle. - {"CommandLineToArgv", PyCommandLineToArgv, 1}, // @pymeth CommandLineToArgv|Parses a Unicode command line string and returns a list of command line arguments, in a way that is similar to sys.argv. - {"CopyFile", PyCopyFile, 1}, // @pymeth CopyFile|Copy a file. - {"DebugBreak", PyDebugBreak, 1}, // @pymeth DebugBreak|Breaks into the C debugger. - {"DeleteFile", PyDeleteFile, 1}, // @pymeth DeleteFile|Deletes the specified file. + {"CommandLineToArgv", PyCommandLineToArgv, + 1}, // @pymeth CommandLineToArgv|Parses a Unicode command line string and returns a list of command line + // arguments, in a way that is similar to sys.argv. + {"CopyFile", PyCopyFile, 1}, // @pymeth CopyFile|Copy a file. + {"DebugBreak", PyDebugBreak, 1}, // @pymeth DebugBreak|Breaks into the C debugger. + {"DeleteFile", PyDeleteFile, 1}, // @pymeth DeleteFile|Deletes the specified file. {"DragQueryFile", PyDragQueryFile, 1}, // @pymeth DragQueryFile|Retrieve the file names for dropped files. {"DragFinish", PyDragFinish, 1}, // @pymeth DragFinish|Free memory associated with dropped files. {"DuplicateHandle", PyDuplicateHandle, 1}, // @pymeth DuplicateHandle|Duplicates a handle. @@ -6013,9 +6020,9 @@ static struct PyMethodDef win32api_functions[] = { 1}, // @pymeth GetNativeSystemInfo|Retrieves information about the current system for a Wow64 process. {"GetSystemMetrics", PyGetSystemMetrics, 1}, // @pymeth GetSystemMetrics|Returns the specified system metrics. {"GetSystemPowerStatus", PyGetSystemPowerStatus, - METH_NOARGS}, // @pymeth GetSystemPowerStatus|Retrieves the power status of the system - {"GetSystemTime", PyGetSystemTime, 1}, // @pymeth GetSystemTime|Returns the current system time. - {"GetTempFileName", PyGetTempFileName, 1}, // @pymeth GetTempFileName|Creates a temporary file. + METH_NOARGS}, // @pymeth GetSystemPowerStatus|Retrieves the power status of the system + {"GetSystemTime", PyGetSystemTime, 1}, // @pymeth GetSystemTime|Returns the current system time. + {"GetTempFileName", PyGetTempFileName, 1}, // @pymeth GetTempFileName|Creates a temporary file. {"GetTempPath", PyGetTempPath, 1}, // @pymeth GetTempPath|Returns the path designated as holding temporary files. {"GetThreadLocale", PyGetThreadLocale, 1}, // @pymeth GetThreadLocale|Returns the current thread's locale. {"GetTickCount", PyGetTickCount, 1}, // @pymeth GetTickCount|Returns the milliseconds since windows started. @@ -6062,7 +6069,7 @@ static struct PyMethodDef win32api_functions[] = { {"MoveFile", PyMoveFile, 1}, // @pymeth MoveFile|Moves or renames a file. {"MoveFileEx", PyMoveFileEx, 1}, // @pymeth MoveFileEx|Moves or renames a file. {"OpenProcess", PyOpenProcess, 1}, // @pymeth OpenProcess|Retrieves a handle to an existing process. - {"OpenThread", PyOpenThread, 1}, // @pymeth OpenProcess|Retrieves a handle to an existing thread. + {"OpenThread", PyOpenThread, 1}, // @pymeth OpenProcess|Retrieves a handle to an existing thread. {"OutputDebugString", PyOutputDebugString, 1}, // @pymeth OutputDebugString|Writes output to the Windows debugger. {"PostMessage", PyPostMessage, 1}, // @pymeth PostMessage|Post a message to a window. {"PostQuitMessage", PyPostQuitMessage, 1}, // @pymeth PostQuitMessage|Posts a quit message. @@ -6150,9 +6157,9 @@ static struct PyMethodDef win32api_functions[] = { // specified offset into the extra class memory for the window. {"SetClassWord", PySetClassWord, 1}, // @pymeth SetClassWord|Replaces the specified 32-bit (long) value at the // specified offset into the extra class memory for the window. - {"SetWindowWord", PySetWindowWord, 1}, // @pymeth SetWindowWord| + {"SetWindowWord", PySetWindowWord, 1}, // @pymeth SetWindowWord| {"SetCursor", PySetCursor, 1}, // @pymeth SetCursor|Set the cursor to the HCURSOR object. -// @pymeth SetEnvironmentVariable|Creates, deletes, or changes the value of an environment variable. + // @pymeth SetEnvironmentVariable|Creates, deletes, or changes the value of an environment variable. {"SetEnvironmentVariable", PySetEnvironmentVariableW, 1}, {"SetEnvironmentVariableW", PySetEnvironmentVariableW, 1}, // @pymeth SetEnvironmentVariableW|Creates, deletes, or changes the value of an environment variable. @@ -6288,8 +6295,7 @@ PYWIN_MODULE_INIT_FUNC(win32api) if (hmodule != NULL) { pfnEnumDisplayMonitors = (EnumDisplayMonitorsfunc)GetProcAddress(hmodule, "EnumDisplayMonitors"); pfnEnumDisplayDevices = (EnumDisplayDevicesfunc)GetProcAddress(hmodule, "EnumDisplayDevicesW"); - pfnChangeDisplaySettingsEx = - (ChangeDisplaySettingsExfunc)GetProcAddress(hmodule, "ChangeDisplaySettingsExW"); + pfnChangeDisplaySettingsEx = (ChangeDisplaySettingsExfunc)GetProcAddress(hmodule, "ChangeDisplaySettingsExW"); pfnMonitorFromWindow = (MonitorFromWindowfunc)GetProcAddress(hmodule, "MonitorFromWindow"); pfnMonitorFromRect = (MonitorFromRectfunc)GetProcAddress(hmodule, "MonitorFromRect"); pfnMonitorFromPoint = (MonitorFromPointfunc)GetProcAddress(hmodule, "MonitorFromPoint"); diff --git a/win32/src/win32clipboardmodule.cpp b/win32/src/win32clipboardmodule.cpp index 8f552f6917..9ffe4b0760 100644 --- a/win32/src/win32clipboardmodule.cpp +++ b/win32/src/win32clipboardmodule.cpp @@ -863,7 +863,7 @@ static PyObject *py_set_clipboard_data(PyObject *self, PyObject *args) buf = pybuf.ptr(); bufSize = pybuf.len(); if ((PyBytes_Check(obhandle)) && (isTextFormat(format))) - bufSize++; // size doesnt include nulls! + bufSize++; // size doesn't include nulls! // else assume buffer needs no terminator... } handle = GlobalAlloc(GHND, bufSize); diff --git a/win32/src/win32consolemodule.cpp b/win32/src/win32consolemodule.cpp index d1ff661b33..daae981cf4 100644 --- a/win32/src/win32consolemodule.cpp +++ b/win32/src/win32consolemodule.cpp @@ -1295,7 +1295,8 @@ PyObject *PyConsoleScreenBuffer::PyScrollConsoleScreenBuffer(PyObject *self, PyO if (!ScrollConsoleScreenBuffer(((PyConsoleScreenBuffer *)self)->m_handle, pscrollrect, pcliprect, *pdestcoord, &char_info)) { PyWin_SetAPIError("ScrollConsoleScreenBuffer"); - } else { + } + else { Py_INCREF(Py_None); return Py_None; } @@ -1813,7 +1814,8 @@ static PyObject *PyAddConsoleAlias(PyObject *self, PyObject *args, PyObject *kwa PyWinObject_AsWCHAR(obexename, &exename, FALSE)) { if (!(*pfnAddConsoleAlias)(source, target, exename)) { PyWin_SetAPIError("AddConsoleAlias"); - } else { + } + else { Py_INCREF(Py_None); ret = Py_None; } diff --git a/win32/src/win32credmodule.cpp b/win32/src/win32credmodule.cpp index efcddfe99a..2825c2213c 100644 --- a/win32/src/win32credmodule.cpp +++ b/win32/src/win32credmodule.cpp @@ -535,13 +535,12 @@ PyObject *PyCredEnumerate(PyObject *self, PyObject *args, PyObject *kwargs) // @pymethod dict|win32cred|CredGetSessionTypes|Returns maximum persistence supported by the current logon session // @rdesc Returns an integer list -PyObject* PyCredGetSessionTypes(PyObject* self, PyObject* args, PyObject* kwargs) +PyObject *PyCredGetSessionTypes(PyObject *self, PyObject *args, PyObject *kwargs) { static char *keywords[] = {"MaximumPersistCount", NULL}; DWORD mpc = CRED_TYPE_MAXIMUM; - if (!PyArg_ParseTupleAndKeywords( - args, kwargs, "|k:CredGetSessionTypes", keywords, - &mpc)) // @pyparm int|MaximumPersistCount|CRED_TYPE_MAXIMUM|Maximum array entries + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|k:CredGetSessionTypes", keywords, + &mpc)) // @pyparm int|MaximumPersistCount|CRED_TYPE_MAXIMUM|Maximum array entries return NULL; if ((mpc == 0) || (mpc > CRED_TYPE_MAXIMUM)) { PyErr_SetString(PyExc_ValueError, "Argument must be between 1 and CRED_TYPE_MAXIMUM"); @@ -555,8 +554,7 @@ PyObject* PyCredGetSessionTypes(PyObject* self, PyObject* args, PyObject* kwargs if (!res) return PyWin_SetAPIError("CredGetSessionTypes"); PyObject *ret = PyList_New(mpc); - for (DWORD i = 0; i < mpc; ++i) - PyList_SET_ITEM(ret, i, PyLong_FromUnsignedLong(arr[i])); + for (DWORD i = 0; i < mpc; ++i) PyList_SET_ITEM(ret, i, PyLong_FromUnsignedLong(arr[i])); return ret; } diff --git a/win32/src/win32crypt/PyCERTSTORE.cpp b/win32/src/win32crypt/PyCERTSTORE.cpp index ca79106725..ace33b4e33 100644 --- a/win32/src/win32crypt/PyCERTSTORE.cpp +++ b/win32/src/win32crypt/PyCERTSTORE.cpp @@ -136,16 +136,16 @@ PyObject *PyCERTSTORE::PyCertCloseStore(PyObject *self, PyObject *args, PyObject { static char *keywords[] = {"Flags", NULL}; HCERTSTORE hcertstore = ((PyCERTSTORE *)self)->GetHCERTSTORE(); - DWORD dwFlags = (DWORD)-1; // DEPRECATED and not actually used other than to warn if it is specified. - if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|k:PyCERTSTORE::CertCloseStore", keywords, - &dwFlags)) + DWORD dwFlags = (DWORD)-1; // DEPRECATED and not actually used other than to warn if it is specified. + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|k:PyCERTSTORE::CertCloseStore", keywords, &dwFlags)) return NULL; if (hcertstore == NULL) { PyErr_SetString(PyExc_SystemError, "Certificate store is already closed"); return NULL; } if (dwFlags != (DWORD)-1) { - PyErr_Warn(PyExc_PendingDeprecationWarning, "The Flags param to CertCloseStore is deprecated; a non-zero value is likely to crash"); + PyErr_Warn(PyExc_PendingDeprecationWarning, + "The Flags param to CertCloseStore is deprecated; a non-zero value is likely to crash"); } BOOL bsuccess; Py_BEGIN_ALLOW_THREADS; @@ -156,7 +156,8 @@ PyObject *PyCERTSTORE::PyCertCloseStore(PyObject *self, PyObject *args, PyObject ((PyCERTSTORE *)self)->hcertstore = NULL; Py_XDECREF(((PyCERTSTORE *)self)->obcertstore); ((PyCERTSTORE *)self)->obcertstore = NULL; - if (!bsuccess) return PyWin_SetAPIError("PyCERTSTORE::CertCloseStore"); + if (!bsuccess) + return PyWin_SetAPIError("PyCERTSTORE::CertCloseStore"); Py_INCREF(Py_None); return Py_None; } @@ -181,7 +182,8 @@ PyObject *PyCERTSTORE::PyCertControlStore(PyObject *self, PyObject *args, PyObje Py_BEGIN_ALLOW_THREADS; bsuccess = CertControlStore(hcertstore, dwFlags, dwCtrlType, hevent); Py_END_ALLOW_THREADS; - if (!bsuccess) return PyWin_SetAPIError("CertControlStore"); + if (!bsuccess) + return PyWin_SetAPIError("CertControlStore"); Py_INCREF(Py_None); return Py_None; } @@ -201,8 +203,7 @@ PyObject *PyCERTSTORE::PyCertEnumCertificatesInStore(PyObject *self, PyObject *a Py_BEGIN_ALLOW_THREADS; pccert_context = CertEnumCertificatesInStore(hcertstore, pccert_context); Py_END_ALLOW_THREADS; - if (pccert_context != NULL) - { + if (pccert_context != NULL) { // increments reference count py_pccert_context = CertDuplicateCertificateContext(pccert_context); ret_item = PyWinObject_FromCERT_CONTEXT(py_pccert_context); @@ -240,8 +241,7 @@ PyObject *PyCERTSTORE::PyCertEnumCTLsInStore(PyObject *self, PyObject *args) Py_BEGIN_ALLOW_THREADS; ctl_context = CertEnumCTLsInStore(hcertstore, ctl_context); Py_END_ALLOW_THREADS; - if (ctl_context != NULL) - { + if (ctl_context != NULL) { py_ctl_context = CertDuplicateCTLContext(ctl_context); ret_item = PyWinObject_FromCTL_CONTEXT(py_ctl_context); if ((ret_item == NULL) || (PyList_Append(ret, ret_item) == -1)) { @@ -305,12 +305,11 @@ PyObject *PyCERTSTORE::PyCertSaveStore(PyObject *self, PyObject *args, PyObject } BOOL bsuccess; Py_BEGIN_ALLOW_THREADS; - bsuccess = - CertSaveStore(hcertstore, dwMsgAndCertEncodingType, dwSaveAs, dwSaveTo, pvSaveToPara, dwFlags); + bsuccess = CertSaveStore(hcertstore, dwMsgAndCertEncodingType, dwSaveAs, dwSaveTo, pvSaveToPara, dwFlags); Py_END_ALLOW_THREADS; - if (!bsuccess) PyWin_SetAPIError("PyCERTSTORE::CertSaveStore"); - else - { + if (!bsuccess) + PyWin_SetAPIError("PyCERTSTORE::CertSaveStore"); + else { Py_INCREF(Py_None); ret = Py_None; } @@ -342,11 +341,11 @@ PyObject *PyCERTSTORE::PyCertAddEncodedCertificateToStore(PyObject *self, PyObje return NULL; BOOL bsuccess; Py_BEGIN_ALLOW_THREADS; - bsuccess = - CertAddEncodedCertificateToStore(hcertstore, dwCertEncodingType, (BYTE*)pybuf.ptr(), pybuf.len(), - dwAddDisposition, (const struct _CERT_CONTEXT **)&newcert_context); + bsuccess = CertAddEncodedCertificateToStore(hcertstore, dwCertEncodingType, (BYTE *)pybuf.ptr(), pybuf.len(), + dwAddDisposition, (const struct _CERT_CONTEXT **)&newcert_context); Py_END_ALLOW_THREADS; - if (!bsuccess) return PyWin_SetAPIError("PyCERTSTORE::CertAddEncodedCertificateToStore"); + if (!bsuccess) + return PyWin_SetAPIError("PyCERTSTORE::CertAddEncodedCertificateToStore"); return PyWinObject_FromCERT_CONTEXT(newcert_context); } @@ -368,10 +367,10 @@ PyObject *PyCERTSTORE::PyCertAddCertificateContextToStore(PyObject *self, PyObje return NULL; BOOL bsuccess; Py_BEGIN_ALLOW_THREADS; - bsuccess = - CertAddCertificateContextToStore(hcertstore, pcert_context, dwAddDisposition, &newcert_context); + bsuccess = CertAddCertificateContextToStore(hcertstore, pcert_context, dwAddDisposition, &newcert_context); Py_END_ALLOW_THREADS; - if (!bsuccess) return PyWin_SetAPIError("CertAddCertificateContextToStore"); + if (!bsuccess) + return PyWin_SetAPIError("CertAddCertificateContextToStore"); return PyWinObject_FromCERT_CONTEXT(newcert_context); } @@ -393,10 +392,10 @@ PyObject *PyCERTSTORE::PyCertAddCertificateLinkToStore(PyObject *self, PyObject return NULL; BOOL bsuccess; Py_BEGIN_ALLOW_THREADS; - bsuccess = - CertAddCertificateLinkToStore(hcertstore, pcert_context, dwAddDisposition, &newcert_context); + bsuccess = CertAddCertificateLinkToStore(hcertstore, pcert_context, dwAddDisposition, &newcert_context); Py_END_ALLOW_THREADS; - if (!bsuccess) return PyWin_SetAPIError("CertAddCertificateLinkToStore"); + if (!bsuccess) + return PyWin_SetAPIError("CertAddCertificateLinkToStore"); return PyWinObject_FromCERT_CONTEXT(newcert_context); } @@ -419,7 +418,8 @@ PyObject *PyCERTSTORE::PyCertAddCTLContextToStore(PyObject *self, PyObject *args Py_BEGIN_ALLOW_THREADS; bsuccess = CertAddCTLContextToStore(hcertstore, pctl, dwAddDisposition, &new_pctl); Py_END_ALLOW_THREADS; - if (!bsuccess) return PyWin_SetAPIError("CertAddCTLContextToStore"); + if (!bsuccess) + return PyWin_SetAPIError("CertAddCTLContextToStore"); return PyWinObject_FromCTL_CONTEXT(new_pctl); } @@ -443,7 +443,8 @@ PyObject *PyCERTSTORE::PyCertAddCTLLinkToStore(PyObject *self, PyObject *args, P Py_BEGIN_ALLOW_THREADS; bsuccess = CertAddCTLLinkToStore(hcertstore, pctl, dwAddDisposition, &new_pctl); Py_END_ALLOW_THREADS; - if (!bsuccess) return PyWin_SetAPIError("CertAddCTLLinkToStore"); + if (!bsuccess) + return PyWin_SetAPIError("CertAddCTLLinkToStore"); return PyWinObject_FromCTL_CONTEXT(new_pctl); } @@ -469,7 +470,8 @@ PyObject *PyCERTSTORE::PyCertAddStoreToCollection(PyObject *self, PyObject *args Py_BEGIN_ALLOW_THREADS; bsuccess = CertAddStoreToCollection(hcertstore, sibling, flags, priority); Py_END_ALLOW_THREADS; - if (!bsuccess) return PyWin_SetAPIError("CertAddStoreToCollection"); + if (!bsuccess) + return PyWin_SetAPIError("CertAddStoreToCollection"); Py_INCREF(Py_None); return Py_None; @@ -520,7 +522,8 @@ PyObject *PyCERTSTORE::PyPFXExportCertStoreEx(PyObject *self, PyObject *args, Py Py_BEGIN_ALLOW_THREADS; bsuccess = PFXExportCertStoreEx(hcertstore, &out, password, NULL, flags); Py_END_ALLOW_THREADS; - if (!bsuccess) return PyWin_SetAPIError("PFXExportCertStoreEx"); + if (!bsuccess) + return PyWin_SetAPIError("PFXExportCertStoreEx"); out.pbData = (BYTE *)malloc(out.cbData); if (out.pbData == NULL) return PyErr_NoMemory(); @@ -529,8 +532,10 @@ PyObject *PyCERTSTORE::PyPFXExportCertStoreEx(PyObject *self, PyObject *args, Py Py_BEGIN_ALLOW_THREADS; bsuccess = PFXExportCertStoreEx(hcertstore, &out, password, NULL, flags); Py_END_ALLOW_THREADS; - if (!bsuccess) PyWin_SetAPIError("PFXExportCertStoreEx"); - else ret = PyBytes_FromStringAndSize((char *)out.pbData, out.cbData); + if (!bsuccess) + PyWin_SetAPIError("PFXExportCertStoreEx"); + else + ret = PyBytes_FromStringAndSize((char *)out.pbData, out.cbData); free(out.pbData); return ret; } diff --git a/win32/src/win32crypt/PyCERT_CONTEXT.cpp b/win32/src/win32crypt/PyCERT_CONTEXT.cpp index cd2ecf0590..fb1b01f553 100644 --- a/win32/src/win32crypt/PyCERT_CONTEXT.cpp +++ b/win32/src/win32crypt/PyCERT_CONTEXT.cpp @@ -129,13 +129,13 @@ PyObject *PyWinObject_FromCERT_EXTENSIONArray(PCERT_EXTENSION pce, DWORD ext_cnt return ret; } -#define CHECK_CERT_CONTEXT(p) \ - if (p == NULL) { \ +#define CHECK_CERT_CONTEXT(p) \ + if (p == NULL) { \ PyErr_SetString(PyExc_ValueError, "The certificate context has been closed"); \ - return NULL; \ + return NULL; \ } -#define GET_CERT_CONTEXT(varname) \ +#define GET_CERT_CONTEXT(varname) \ PCCERT_CONTEXT varname = ((PyCERT_CONTEXT *)self)->GetPCCERT_CONTEXT(); \ CHECK_CERT_CONTEXT(varname); @@ -205,15 +205,14 @@ PyObject *PyCERT_CONTEXT::getattro(PyObject *self, PyObject *obname) return PyObject_GenericGetAttr(self, obname); } -PyCERT_CONTEXT::~PyCERT_CONTEXT(void) { +PyCERT_CONTEXT::~PyCERT_CONTEXT(void) +{ if (pccert_context) { CertFreeCertificateContext(pccert_context); } } -void PyCERT_CONTEXT::deallocFunc(PyObject *ob) { - delete (PyCERT_CONTEXT *)ob; -} +void PyCERT_CONTEXT::deallocFunc(PyObject *ob) { delete (PyCERT_CONTEXT *)ob; } PyCERT_CONTEXT::PyCERT_CONTEXT(PCCERT_CONTEXT pccert_context) { @@ -261,7 +260,8 @@ PyObject *PyCERT_CONTEXT::PyCertFreeCertificateContext(PyObject *self, PyObject Py_BEGIN_ALLOW_THREADS; bsuccess = CertFreeCertificateContext(pcc); Py_END_ALLOW_THREADS; - if (!bsuccess) return PyWin_SetAPIError("CertFreeCertificateContext"); + if (!bsuccess) + return PyWin_SetAPIError("CertFreeCertificateContext"); ((PyCERT_CONTEXT *)self)->pccert_context = NULL; Py_INCREF(Py_None); return Py_None; @@ -619,7 +619,7 @@ PyObject *PyCERT_CONTEXT::PyCertSetCertificateContextProperty(PyObject *self, Py case CERT_CTL_USAGE_PROP_ID: if (!pybuf.init(obData)) goto cleanup; - cdb.pbData = (BYTE*)pybuf.ptr(); + cdb.pbData = (BYTE *)pybuf.ptr(); cdb.cbData = pybuf.len(); pvData = &cdb; break; diff --git a/win32/src/win32crypt/PyCRYPTHASH.cpp b/win32/src/win32crypt/PyCRYPTHASH.cpp index 6dfdf272a8..7b5e963d72 100644 --- a/win32/src/win32crypt/PyCRYPTHASH.cpp +++ b/win32/src/win32crypt/PyCRYPTHASH.cpp @@ -137,7 +137,7 @@ PyObject *PyCRYPTHASH::PyCryptHashData(PyObject *self, PyObject *args, PyObject dwDataLen = pybuf.len(); if (dwFlags & CRYPT_USERDATA) dwDataLen = 0; - if (CryptHashData(hcrypthash, (BYTE*)pybuf.ptr(), dwDataLen, dwFlags)) { + if (CryptHashData(hcrypthash, (BYTE *)pybuf.ptr(), dwDataLen, dwFlags)) { Py_INCREF(Py_None); return Py_None; } diff --git a/win32/src/win32crypt/PyCRYPTPROV.cpp b/win32/src/win32crypt/PyCRYPTPROV.cpp index 248e763779..c65b82be19 100644 --- a/win32/src/win32crypt/PyCRYPTPROV.cpp +++ b/win32/src/win32crypt/PyCRYPTPROV.cpp @@ -401,7 +401,7 @@ PyObject *PyCRYPTPROV::PyCryptImportKey(PyObject *self, PyObject *args, PyObject if (!pybuf.ok()) return NULL; - if (!CryptImportKey(hcryptprov, (BYTE*)pybuf.ptr(), pybuf.len(), pubkey, flags, &retkey)) + if (!CryptImportKey(hcryptprov, (BYTE *)pybuf.ptr(), pybuf.len(), pubkey, flags, &retkey)) return PyWin_SetAPIError("PyCRYPTPROV::CryptImportKey"); return new PyCRYPTKEY(retkey, self); } diff --git a/win32/src/win32crypt/PyCTL_CONTEXT.cpp b/win32/src/win32crypt/PyCTL_CONTEXT.cpp index aea1a6f8d3..91487a7bb3 100644 --- a/win32/src/win32crypt/PyCTL_CONTEXT.cpp +++ b/win32/src/win32crypt/PyCTL_CONTEXT.cpp @@ -84,13 +84,13 @@ PyObject *PyWinObject_FromCTL_CONTEXT(PCCTL_CONTEXT pcc) return ret; } -#define CHECK_CTL_CONTEXT(p) \ - if (p == NULL) { \ +#define CHECK_CTL_CONTEXT(p) \ + if (p == NULL) { \ PyErr_SetString(PyExc_ValueError, "The certificate trust context has been closed"); \ - return NULL; \ + return NULL; \ } -#define GET_CTL_CONTEXT(varname) \ +#define GET_CTL_CONTEXT(varname) \ PCCTL_CONTEXT varname = ((PyCTL_CONTEXT *)self)->GetCTL_CONTEXT(); \ CHECK_CTL_CONTEXT(varname); diff --git a/win32/src/win32crypt/win32crypt_structs.cpp b/win32/src/win32crypt/win32crypt_structs.cpp index 668ffbcb8f..d4424c795b 100644 --- a/win32/src/win32crypt/win32crypt_structs.cpp +++ b/win32/src/win32crypt/win32crypt_structs.cpp @@ -10,7 +10,7 @@ BOOL PyWinObject_AsDATA_BLOB(PyObject *ob, DATA_BLOB *b) return FALSE; // note: this might be unsafe, as we give away the buffer pointer to a // client outside of the scope where our RAII object 'pybuf' resides. - b->pbData = (BYTE*)pybuf.ptr(); + b->pbData = (BYTE *)pybuf.ptr(); b->cbData = PyWin_SAFE_DOWNCAST(pybuf.len(), Py_ssize_t, int); return TRUE; } @@ -228,12 +228,13 @@ BOOL PyWinObject_AsCRYPT_ALGORITHM_IDENTIFIER(PyObject *obcai, PCRYPT_ALGORITHM_ } ZeroMemory(pcai, sizeof(CRYPT_ALGORITHM_IDENTIFIER)); Py_ssize_t cbData; - BOOL ok = PyArg_ParseTupleAndKeywords( - dummy_tuple, obcai, "sz#:CRYPT_ALGORITHM_IDENTIFIER", cai_keys, - &pcai->pszObjId, // @prop str|ObjId|An szOID_* string identifying the algorithm - &pcai->Parameters.pbData, - &cbData); // @prop str|Parameters|Blob of binary data containing encoded parameters - if (ok) pcai->Parameters.cbData = (DWORD)cbData; + BOOL ok = + PyArg_ParseTupleAndKeywords(dummy_tuple, obcai, "sz#:CRYPT_ALGORITHM_IDENTIFIER", cai_keys, + &pcai->pszObjId, // @prop str|ObjId|An szOID_* string identifying the algorithm + &pcai->Parameters.pbData, + &cbData); // @prop str|Parameters|Blob of binary data containing encoded parameters + if (ok) + pcai->Parameters.cbData = (DWORD)cbData; return ok; } @@ -280,11 +281,11 @@ BOOL PyWinObject_AsCRYPT_BIT_BLOB(PyObject *obcbb, PCRYPT_BIT_BLOB pcbb) dummy_tuple, obcbb, "Ok:CRYPT_BIT_BLOB", cbb_keys, &obdata, // @prop buffer|Data|Binary data &pcbb->cUnusedBits) // @prop int|UnusedBits|Nbr of bits of last byte that are unused - ) + ) if (pybuf.init(obdata)) { // note: this might be unsafe, as we give away the buffer pointer to a // client outside of the scope where our RAII object 'pybuf' resides. - pcbb->pbData = (BYTE*)pybuf.ptr(); + pcbb->pbData = (BYTE *)pybuf.ptr(); pcbb->cbData = pybuf.len(); return TRUE; } @@ -832,7 +833,7 @@ BOOL PyWinObject_AsPBYTEArray(PyObject *str_seq, PBYTE **pbyte_array, DWORD **by goto cleanup; // note: this might be unsafe, as we give away the buffer pointer to a // client outside of the scope where our RAII object 'pybuf' resides. - (*pbyte_array)[tuple_index] = (BYTE*)pybuf.ptr(); + (*pbyte_array)[tuple_index] = (BYTE *)pybuf.ptr(); (*byte_lens)[tuple_index] = pybuf.len(); } ret = TRUE; @@ -978,7 +979,7 @@ PyObject *PyWinObject_FromCERT_BASIC_CONSTRAINTS_INFO(PCERT_BASIC_CONSTRAINTS_IN return NULL; for (DWORD i = 0; i < pcbci->cSubtreesConstraint; i++) { PyObject *nb = PyBytes_FromStringAndSize((char *)pcbci->rgSubtreesConstraint[i].pbData, - pcbci->rgSubtreesConstraint[i].cbData); + pcbci->rgSubtreesConstraint[i].cbData); if (nb == NULL) { Py_DECREF(sc); return NULL; @@ -1013,7 +1014,7 @@ PyObject *PyWinObject_FromCERT_POLICY_INFO(PCERT_POLICY_INFO pcpi) PyObject *qual = Py_BuildValue( "{s:s,s:N}", "PolicyQualifierId", pcpi->rgPolicyQualifier[qual_ind].pszPolicyQualifierId, "Qualifier", PyBytes_FromStringAndSize((char *)pcpi->rgPolicyQualifier[qual_ind].Qualifier.pbData, - pcpi->rgPolicyQualifier[qual_ind].Qualifier.cbData)); + pcpi->rgPolicyQualifier[qual_ind].Qualifier.cbData)); if (qual == NULL) { Py_DECREF(quals); return NULL; diff --git a/win32/src/win32crypt/win32cryptmodule.cpp b/win32/src/win32crypt/win32cryptmodule.cpp index 730fbf551a..3f801fc12b 100644 --- a/win32/src/win32crypt/win32cryptmodule.cpp +++ b/win32/src/win32crypt/win32cryptmodule.cpp @@ -486,7 +486,7 @@ static PyObject *PyCertEnumSystemStore(PyObject *self, PyObject *args, PyObject CertEnumSystemStore(dwFlags, pvSystemStoreLocationPara, ret, CertEnumSystemStoreCallback); Py_END_ALLOW_THREADS - if (!bsuccess) + if (!bsuccess) { Py_DECREF(ret); ret = NULL; @@ -494,8 +494,7 @@ static PyObject *PyCertEnumSystemStore(PyObject *self, PyObject *args, PyObject PyWin_SetAPIError("CertEnumSystemStore"); } - if (pvSystemStoreLocationPara != NULL) - { + if (pvSystemStoreLocationPara != NULL) { if (dwFlags & CERT_SYSTEM_STORE_RELOCATE_FLAG) PyWinObject_FreeWCHAR((WCHAR *)cssrp.pwszSystemStore); else @@ -609,7 +608,7 @@ static PyObject *PyCertOpenStore(PyObject *self, PyObject *args, PyObject *kwarg case CERT_STORE_PROV_PKCS7: { if (!pybuf.init(obpvPara)) return NULL; - crypt_data_blob.pbData = (BYTE*)pybuf.ptr(); + crypt_data_blob.pbData = (BYTE *)pybuf.ptr(); crypt_data_blob.cbData = pybuf.len(); pvPara = (void *)&crypt_data_blob; break; @@ -824,7 +823,7 @@ static PyObject *PyCryptGetKeyIdentifierProperty(PyObject *self, PyObject *args, PyWinBufferView pybuf(obkeyid); if (!pybuf.ok()) return NULL; - chb.pbData = (BYTE*)pybuf.ptr(); + chb.pbData = (BYTE *)pybuf.ptr(); chb.cbData = pybuf.len(); if (!PyWinObject_AsWCHAR(obcomputername, &computername, TRUE)) return NULL; @@ -931,7 +930,7 @@ static PyObject *PyCryptEnumKeyIdentifierProperties(PyObject *self, PyObject *ar if (obkeyid != Py_None) { if (!pybuf.init(obkeyid)) return NULL; - chb.pbData = (BYTE*)pybuf.ptr(); + chb.pbData = (BYTE *)pybuf.ptr(); chb.cbData = pybuf.len(); } if (!PyWinObject_AsWCHAR(obcomputername, &computername, TRUE)) @@ -1024,9 +1023,8 @@ static PyObject *PyCertAddSerializedElementToStore(PyObject *self, PyObject *arg return NULL; BOOL bsuccess; - Py_BEGIN_ALLOW_THREADS bsuccess = CertAddSerializedElementToStore(hcertstore, (BYTE*)pybuf.ptr(), pybuf.len(), - adddisposition, flags, contexttype, - &contexttype_out, &context); + Py_BEGIN_ALLOW_THREADS bsuccess = CertAddSerializedElementToStore( + hcertstore, (BYTE *)pybuf.ptr(), pybuf.len(), adddisposition, flags, contexttype, &contexttype_out, &context); Py_END_ALLOW_THREADS if (!bsuccess) return PyWin_SetAPIError("CertAddSerializedElementToStore"); @@ -1077,7 +1075,7 @@ static PyObject *PyCryptQueryObject(PyObject *self, PyObject *args, PyObject *kw case CERT_QUERY_OBJECT_BLOB: if (!pybuf.init(obinput)) return NULL; - blob_input.pbData = (BYTE*)pybuf.ptr(); + blob_input.pbData = (BYTE *)pybuf.ptr(); blob_input.cbData = pybuf.len(); input = (void *)&blob_input; break; @@ -1092,11 +1090,11 @@ static PyObject *PyCryptQueryObject(PyObject *self, PyObject *args, PyObject *kw BOOL bsuccess; Py_BEGIN_ALLOW_THREADS; - bsuccess = - CryptQueryObject(objecttype, input, contenttype, formattype, flags, &encoding, &contenttypeout, &formattypeout, - &hcertstore, &hcryptmsg, (const void **)&context); + bsuccess = CryptQueryObject(objecttype, input, contenttype, formattype, flags, &encoding, &contenttypeout, + &formattypeout, &hcertstore, &hcryptmsg, (const void **)&context); Py_END_ALLOW_THREADS; - if (!bsuccess) return PyWin_SetAPIError("CryptQueryObject"); + if (!bsuccess) + return PyWin_SetAPIError("CryptQueryObject"); switch (contenttypeout) { case CERT_QUERY_CONTENT_CERT: @@ -1169,7 +1167,7 @@ static PyObject *PyCryptDecodeMessage(PyObject *self, PyObject *args, PyObject * return NULL; Py_BEGIN_ALLOW_THREADS bsuccess = - CryptDecodeMessage(msg_type_flags, &cdmp, &cvmp, signer_ind, (BYTE*)pybuf.ptr(), pybuf.len(), prev_inner_type, + CryptDecodeMessage(msg_type_flags, &cdmp, &cvmp, signer_ind, (BYTE *)pybuf.ptr(), pybuf.len(), prev_inner_type, &msg_type, &inner_type, output_buf, &output_bufsize, &exchange_cert, &signer_cert); Py_END_ALLOW_THREADS if (!bsuccess) { @@ -1190,7 +1188,7 @@ static PyObject *PyCryptDecodeMessage(PyObject *self, PyObject *args, PyObject * if (output_buf == NULL) return PyErr_NoMemory(); Py_BEGIN_ALLOW_THREADS bsuccess = - CryptDecodeMessage(msg_type_flags, &cdmp, &cvmp, signer_ind, (BYTE*)pybuf.ptr(), pybuf.len(), prev_inner_type, + CryptDecodeMessage(msg_type_flags, &cdmp, &cvmp, signer_ind, (BYTE *)pybuf.ptr(), pybuf.len(), prev_inner_type, &msg_type, &inner_type, output_buf, &output_bufsize, NULL, NULL); Py_END_ALLOW_THREADS if (!bsuccess) { @@ -1238,9 +1236,8 @@ static PyObject *PyCryptEncryptMessage(PyObject *self, PyObject *args, PyObject return NULL; if (!PyWinObject_AsCERT_CONTEXTArray(obrecipients, &recipients, &recipient_cnt)) return NULL; - Py_BEGIN_ALLOW_THREADS bsuccess = - CryptEncryptMessage(&cemp, recipient_cnt, recipients, (BYTE*)pybuf.ptr(), pybuf.len(), outputbuf, - &output_bufsize); + Py_BEGIN_ALLOW_THREADS bsuccess = CryptEncryptMessage(&cemp, recipient_cnt, recipients, (BYTE *)pybuf.ptr(), + pybuf.len(), outputbuf, &output_bufsize); Py_END_ALLOW_THREADS if (!bsuccess) PyWin_SetAPIError("CryptEncryptMessage"); else { @@ -1248,9 +1245,8 @@ static PyObject *PyCryptEncryptMessage(PyObject *self, PyObject *args, PyObject if (outputbuf == NULL) PyErr_Format(PyExc_MemoryError, "CryptEncryptMessage: Unable to allocate %d bytes", output_bufsize); else { - Py_BEGIN_ALLOW_THREADS bsuccess = CryptEncryptMessage(&cemp, recipient_cnt, recipients, - (BYTE*)pybuf.ptr(), pybuf.len(), - outputbuf, &output_bufsize); + Py_BEGIN_ALLOW_THREADS bsuccess = CryptEncryptMessage(&cemp, recipient_cnt, recipients, (BYTE *)pybuf.ptr(), + pybuf.len(), outputbuf, &output_bufsize); Py_END_ALLOW_THREADS if (!bsuccess) PyWin_SetAPIError("CryptEncryptMessage"); else ret = PyBytes_FromStringAndSize((char *)outputbuf, output_bufsize); } @@ -1286,7 +1282,7 @@ static PyObject *PyCryptDecryptMessage(PyObject *self, PyObject *args, PyObject return NULL; Py_BEGIN_ALLOW_THREADS bsuccess = - CryptDecryptMessage(&cdmp, (BYTE*)pybuf.ptr(), pybuf.len(), output_buf, &output_bufsize, NULL); + CryptDecryptMessage(&cdmp, (BYTE *)pybuf.ptr(), pybuf.len(), output_buf, &output_bufsize, NULL); Py_END_ALLOW_THREADS if (!bsuccess) return PyWin_SetAPIError("CryptDecryptMessage"); output_buf = (BYTE *)malloc(output_bufsize); @@ -1294,7 +1290,7 @@ static PyObject *PyCryptDecryptMessage(PyObject *self, PyObject *args, PyObject return PyErr_NoMemory(); Py_BEGIN_ALLOW_THREADS bsuccess = - CryptDecryptMessage(&cdmp, (BYTE*)pybuf.ptr(), pybuf.len(), output_buf, &output_bufsize, &exchange_cert); + CryptDecryptMessage(&cdmp, (BYTE *)pybuf.ptr(), pybuf.len(), output_buf, &output_bufsize, &exchange_cert); Py_END_ALLOW_THREADS if (!bsuccess) PyWin_SetAPIError("CryptDecryptMessage"); else ret = Py_BuildValue("NN", PyBytes_FromStringAndSize((char *)output_buf, output_bufsize), PyWinObject_FromCERT_CONTEXT(exchange_cert)); @@ -1331,9 +1327,8 @@ static PyObject *PyCryptSignAndEncryptMessage(PyObject *self, PyObject *args, Py goto cleanup; BOOL bsuccess; - Py_BEGIN_ALLOW_THREADS bsuccess = CryptSignAndEncryptMessage(&csmp, &cemp, recipient_cnt, recipients, - (BYTE*)pybuf.ptr(), pybuf.len(), output_buf, - &output_bufsize); + Py_BEGIN_ALLOW_THREADS bsuccess = CryptSignAndEncryptMessage( + &csmp, &cemp, recipient_cnt, recipients, (BYTE *)pybuf.ptr(), pybuf.len(), output_buf, &output_bufsize); Py_END_ALLOW_THREADS if (!bsuccess) { PyWin_SetAPIError("CryptSignAndEncryptMessage"); @@ -1346,9 +1341,8 @@ static PyObject *PyCryptSignAndEncryptMessage(PyObject *self, PyObject *args, Py goto cleanup; } - Py_BEGIN_ALLOW_THREADS bsuccess = CryptSignAndEncryptMessage(&csmp, &cemp, recipient_cnt, recipients, - (BYTE*)pybuf.ptr(), pybuf.len(), output_buf, - &output_bufsize); + Py_BEGIN_ALLOW_THREADS bsuccess = CryptSignAndEncryptMessage( + &csmp, &cemp, recipient_cnt, recipients, (BYTE *)pybuf.ptr(), pybuf.len(), output_buf, &output_bufsize); Py_END_ALLOW_THREADS if (!bsuccess) { PyWin_SetAPIError("CryptSignAndEncryptMessage"); @@ -1391,7 +1385,7 @@ static PyObject *PyCryptVerifyMessageSignature(PyObject *self, PyObject *args, P if (!PyWinObject_AsCRYPT_VERIFY_MESSAGE_PARA(obcvmp, &cvmp)) return NULL; - Py_BEGIN_ALLOW_THREADS bsuccess = CryptVerifyMessageSignature(&cvmp, signer_ind, (BYTE*)pybuf.ptr(), pybuf.len(), + Py_BEGIN_ALLOW_THREADS bsuccess = CryptVerifyMessageSignature(&cvmp, signer_ind, (BYTE *)pybuf.ptr(), pybuf.len(), output_buf, &output_bufsize, &signer_cert); Py_END_ALLOW_THREADS // Callback may have already set an exception @@ -1410,9 +1404,8 @@ static PyObject *PyCryptVerifyMessageSignature(PyObject *self, PyObject *args, P if (output_buf == NULL) PyErr_NoMemory(); else { - Py_BEGIN_ALLOW_THREADS bsuccess = - CryptVerifyMessageSignature(&cvmp, signer_ind, (BYTE*)pybuf.ptr(), pybuf.len(), output_buf, - &output_bufsize, NULL); + Py_BEGIN_ALLOW_THREADS bsuccess = CryptVerifyMessageSignature(&cvmp, signer_ind, (BYTE *)pybuf.ptr(), + pybuf.len(), output_buf, &output_bufsize, NULL); Py_END_ALLOW_THREADS if (!bsuccess) { // Callback may have already set an exception @@ -1452,7 +1445,7 @@ static PyObject *PyCryptGetMessageCertificates(PyObject *self, PyObject *args, P if (!PyWinObject_AsHCRYPTPROV(obcsp, &csp, TRUE)) return NULL; Py_BEGIN_ALLOW_THREADS hcertstore = - CryptGetMessageCertificates(encoding_type, csp, flags, (BYTE*)pybuf.ptr(), pybuf.len()); + CryptGetMessageCertificates(encoding_type, csp, flags, (BYTE *)pybuf.ptr(), pybuf.len()); Py_END_ALLOW_THREADS if (hcertstore == NULL) return PyWin_SetAPIError("CryptGetMessageCertificates"); return PyWinObject_FromCERTSTORE(hcertstore); } @@ -1474,7 +1467,7 @@ static PyObject *PyCryptGetMessageSignerCount(PyObject *self, PyObject *args, Py PyWinBufferView pybuf(obbuf); if (!pybuf.ok()) return NULL; - Py_BEGIN_ALLOW_THREADS signer_cnt = CryptGetMessageSignerCount(encoding_type, (BYTE*)pybuf.ptr(), pybuf.len()); + Py_BEGIN_ALLOW_THREADS signer_cnt = CryptGetMessageSignerCount(encoding_type, (BYTE *)pybuf.ptr(), pybuf.len()); Py_END_ALLOW_THREADS if (signer_cnt == -1) return PyWin_SetAPIError("CryptGetMessageSignerCount"); return PyLong_FromLong(signer_cnt); } @@ -1563,9 +1556,8 @@ static PyObject *PyCryptVerifyDetachedMessageSignature(PyObject *self, PyObject return NULL; BOOL bsuccess; - Py_BEGIN_ALLOW_THREADS bsuccess = CryptVerifyDetachedMessageSignature(&cvmp, signer_ind, (BYTE*)pybuf.ptr(), - pybuf.len(), msg_cnt, (const BYTE **)msgs, - msg_sizes, &signer_cert); + Py_BEGIN_ALLOW_THREADS bsuccess = CryptVerifyDetachedMessageSignature( + &cvmp, signer_ind, (BYTE *)pybuf.ptr(), pybuf.len(), msg_cnt, (const BYTE **)msgs, msg_sizes, &signer_cert); Py_END_ALLOW_THREADS if (!bsuccess) PyWin_SetAPIError("CryptVerifyDetachedMessageSignature"); else ret = PyWinObject_FromCERT_CONTEXT(signer_cert); @@ -1608,14 +1600,15 @@ static PyObject *PyCryptDecryptAndVerifyMessageSignature(PyObject *self, PyObjec BOOL bsuccess; Py_BEGIN_ALLOW_THREADS bsuccess = CryptDecryptAndVerifyMessageSignature( - &cdmp, &cvmp, signer_ind, (BYTE*)pybuf.ptr(), pybuf.len(), output_buf, &output_bufsize, NULL, NULL); + &cdmp, &cvmp, signer_ind, (BYTE *)pybuf.ptr(), pybuf.len(), output_buf, &output_bufsize, NULL, NULL); Py_END_ALLOW_THREADS if (!bsuccess) return PyWin_SetAPIError("CryptDecryptAndVerifyMessageSignature"); output_buf = (BYTE *)malloc(output_bufsize); if (output_buf == NULL) return PyErr_NoMemory(); - Py_BEGIN_ALLOW_THREADS bsuccess = CryptDecryptAndVerifyMessageSignature( - &cdmp, &cvmp, signer_ind, (BYTE*)pybuf.ptr(), pybuf.len(), output_buf, &output_bufsize, &exchange_cert, &signer_cert); + Py_BEGIN_ALLOW_THREADS bsuccess = + CryptDecryptAndVerifyMessageSignature(&cdmp, &cvmp, signer_ind, (BYTE *)pybuf.ptr(), pybuf.len(), output_buf, + &output_bufsize, &exchange_cert, &signer_cert); Py_END_ALLOW_THREADS if (!bsuccess) PyWin_SetAPIError("CryptDecryptAndVerifyMessageSignature"); else ret = Py_BuildValue( "{s:N,s:N,s:N}", "Decrypted", PyBytes_FromStringAndSize((char *)output_buf, output_bufsize), "XchgCert", @@ -1755,9 +1748,8 @@ static PyObject *PyCryptDecodeObjectEx(PyObject *self, PyObject *args, PyObject } BOOL bsuccess; - Py_BEGIN_ALLOW_THREADS bsuccess = - CryptDecodeObjectEx(encoding, structtype, (BYTE*)pybuf.ptr(), pybuf.len(), flags, NULL, &output_buf, - &output_bufsize); + Py_BEGIN_ALLOW_THREADS bsuccess = CryptDecodeObjectEx(encoding, structtype, (BYTE *)pybuf.ptr(), pybuf.len(), flags, + NULL, &output_buf, &output_bufsize); Py_END_ALLOW_THREADS if (!bsuccess) { PyWin_SetAPIError("CryptDecodeObjectEx"); @@ -1817,7 +1809,7 @@ static PyObject *PyCryptDecodeObjectEx(PyObject *self, PyObject *args, PyObject else if (oid_is_str && (strcmp(structtype, szOID_SUBJECT_KEY_IDENTIFIER) == 0)) // @flag szOID_SUBJECT_KEY_IDENTIFIER|Binary string containing the key identifier ret = PyBytes_FromStringAndSize((char *)((CRYPT_DATA_BLOB *)output_buf)->pbData, - ((CRYPT_DATA_BLOB *)output_buf)->cbData); + ((CRYPT_DATA_BLOB *)output_buf)->cbData); else if ((oid_is_str && (strcmp(structtype, szOID_AUTHORITY_KEY_IDENTIFIER) == 0)) || // @flag szOID_AUTHORITY_KEY_IDENTIFIER| (structtype == X509_AUTHORITY_KEY_ID)) // @flag X509_AUTHORITY_KEY_ID| @@ -1886,7 +1878,7 @@ static PyObject *PyCertNameToStr(PyObject *self, PyObject *args, PyObject *kwarg PyWinBufferView pybuf(obname); if (!pybuf.ok()) return NULL; - cnb.pbData = (BYTE*)pybuf.ptr(); + cnb.pbData = (BYTE *)pybuf.ptr(); cnb.cbData = pybuf.len(); Py_BEGIN_ALLOW_THREADS output_buflen = CertNameToStr(encoding, &cnb, strtype, output_buf, output_buflen); @@ -1938,16 +1930,14 @@ static PyObject *PyCryptFormatObject(PyObject *self, PyObject *args, PyObject *k BOOL bsuccess; Py_BEGIN_ALLOW_THREADS bsuccess = CryptFormatObject(encoding, fmt_type, string_fmt, fmt_struct, oid, - (BYTE*)pybuf.ptr(), pybuf.len(), output_buf, - &output_bufsize); + (BYTE *)pybuf.ptr(), pybuf.len(), output_buf, &output_bufsize); Py_END_ALLOW_THREADS if (!bsuccess) return PyWin_SetAPIError("CryptFormatObject"); output_buf = malloc(output_bufsize); if (output_buf == NULL) return PyErr_Format(PyExc_MemoryError, "Unable to allocate %d bytes", output_bufsize); Py_BEGIN_ALLOW_THREADS bsuccess = CryptFormatObject(encoding, fmt_type, string_fmt, fmt_struct, oid, - (BYTE*)pybuf.ptr(), pybuf.len(), output_buf, - &output_bufsize); + (BYTE *)pybuf.ptr(), pybuf.len(), output_buf, &output_bufsize); Py_END_ALLOW_THREADS if (!bsuccess) PyWin_SetAPIError("CryptFormatObject"); else ret = PyWinObject_FromWCHAR((WCHAR *)output_buf); free(output_buf); @@ -2045,16 +2035,16 @@ static PyObject *PyCryptBinaryToString(PyObject *self, PyObject *args, PyObject if (!pybuf.ok()) return NULL; BOOL bsuccess; - Py_BEGIN_ALLOW_THREADS bsuccess = CryptBinaryToString((BYTE*)pybuf.ptr(), pybuf.len(), flags, - output_buf, &output_size); + Py_BEGIN_ALLOW_THREADS bsuccess = + CryptBinaryToString((BYTE *)pybuf.ptr(), pybuf.len(), flags, output_buf, &output_size); Py_END_ALLOW_THREADS if (!bsuccess) return PyWin_SetAPIError("CryptBinaryToString"); output_buf = (WCHAR *)malloc(output_size * sizeof(WCHAR)); if (output_buf == NULL) return PyErr_NoMemory(); PyObject *ret = NULL; - Py_BEGIN_ALLOW_THREADS bsuccess = CryptBinaryToString((BYTE*)pybuf.ptr(), pybuf.len(), flags, - output_buf, &output_size); + Py_BEGIN_ALLOW_THREADS bsuccess = + CryptBinaryToString((BYTE *)pybuf.ptr(), pybuf.len(), flags, output_buf, &output_size); Py_END_ALLOW_THREADS if (!bsuccess) PyWin_SetAPIError("CryptBinaryToString"); else ret = PyWinObject_FromWCHAR(output_buf, output_size); free(output_buf); diff --git a/win32/src/win32dynamicdialog.cpp b/win32/src/win32dynamicdialog.cpp index c5b815c259..bef6473748 100644 --- a/win32/src/win32dynamicdialog.cpp +++ b/win32/src/win32dynamicdialog.cpp @@ -599,7 +599,7 @@ static BOOL ParseDlgItemList(CPythonDialogTemplate *dlg, PyObject *tmpl) if (IS_INTRESOURCE(wclass)) ret = dlg->Add((WORD)wclass, &tpl, caption); else - ret = dlg->Add(wclass, &tpl, caption, pybuf.len(), (BYTE*)pybuf.ptr()); + ret = dlg->Add(wclass, &tpl, caption, pybuf.len(), (BYTE *)pybuf.ptr()); cleanup: PyWinObject_FreeResourceId(wclass); diff --git a/win32/src/win32file_comm.cpp b/win32/src/win32file_comm.cpp index 77121e0668..bcd2d3667f 100644 --- a/win32/src/win32file_comm.cpp +++ b/win32/src/win32file_comm.cpp @@ -162,8 +162,11 @@ PyDCB::PyDCB(const DCB &other) PyDCB::~PyDCB(void) {} -#define GET_BITFIELD_ENTRY(bitfield_name) \ - else if (strcmp(name, #bitfield_name) == 0) { return PyLong_FromLong(pydcb->m_DCB.##bitfield_name); } +#define GET_BITFIELD_ENTRY(bitfield_name) \ + else if (strcmp(name, #bitfield_name) == 0) \ + { \ + return PyLong_FromLong(pydcb->m_DCB.##bitfield_name); \ + } PyObject *PyDCB::getattro(PyObject *self, PyObject *obname) { @@ -194,11 +197,11 @@ PyObject *PyDCB::getattro(PyObject *self, PyObject *obname) #define SET_BITFIELD_ENTRY(bitfield_name) \ else if (strcmp(name, #bitfield_name) == 0) \ { \ - if (!PyLong_Check(v)) { \ + if (!PyLong_Check(v)) { \ PyErr_Format(PyExc_TypeError, szNeedIntAttr, #bitfield_name); \ return -1; \ } \ - pydcb->m_DCB.##bitfield_name = PyLong_AsLong(v); \ + pydcb->m_DCB.##bitfield_name = PyLong_AsLong(v); \ return 0; \ } @@ -361,8 +364,11 @@ PyCOMSTAT::PyCOMSTAT(const COMSTAT &other) PyCOMSTAT::~PyCOMSTAT(void) {} #undef GET_BITFIELD_ENTRY -#define GET_BITFIELD_ENTRY(bitfield_name) \ - else if (strcmp(name, #bitfield_name) == 0) { return PyLong_FromLong(pyCOMSTAT->m_COMSTAT.##bitfield_name); } +#define GET_BITFIELD_ENTRY(bitfield_name) \ + else if (strcmp(name, #bitfield_name) == 0) \ + { \ + return PyLong_FromLong(pyCOMSTAT->m_COMSTAT.##bitfield_name); \ + } PyObject *PyCOMSTAT::getattro(PyObject *self, PyObject *obname) { @@ -387,11 +393,11 @@ PyObject *PyCOMSTAT::getattro(PyObject *self, PyObject *obname) #define SET_BITFIELD_ENTRY(bitfield_name) \ else if (strcmp(name, #bitfield_name) == 0) \ { \ - if (!PyLong_Check(v)) { \ + if (!PyLong_Check(v)) { \ PyErr_Format(PyExc_TypeError, szNeedIntAttr, #bitfield_name); \ return -1; \ } \ - pyCOMSTAT->m_COMSTAT.##bitfield_name = PyLong_AsLong(v); \ + pyCOMSTAT->m_COMSTAT.##bitfield_name = PyLong_AsLong(v); \ return 0; \ } diff --git a/win32/src/win32gui.i b/win32/src/win32gui.i index d466cc3350..a59ae28232 100644 --- a/win32/src/win32gui.i +++ b/win32/src/win32gui.i @@ -1995,121 +1995,159 @@ LRESULT DefWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); %{ struct PyEnumWindowsCallback { - PyObject *func; - PyObject *extra; + PyObject *func; + PyObject *extra; }; BOOL CALLBACK PyEnumWindowsProc( HWND hwnd, // handle to parent window LPARAM lParam // application-defined value ) { - BOOL result = TRUE; - PyEnumWindowsCallback *cb = (PyEnumWindowsCallback *)lParam; - CEnterLeavePython _celp; - PyObject *args = Py_BuildValue("(NO)", PyWinLong_FromHANDLE(hwnd), cb->extra); - if (args == NULL) - return FALSE; - PyObject *ret = PyEval_CallObject(cb->func, args); - Py_DECREF(args); - if (ret == NULL) - return FALSE; - if (ret != Py_None){ - result = PyLong_AsLong(ret); - if (result == -1 && PyErr_Occurred()) - result = FALSE; - } - Py_DECREF(ret); - return result; + BOOL result = TRUE; + PyEnumWindowsCallback *cb = (PyEnumWindowsCallback *)lParam; + CEnterLeavePython _celp; + PyObject *args = Py_BuildValue("(NO)", PyWinLong_FromHANDLE(hwnd), cb->extra); + if (args == NULL) + return FALSE; + PyObject *ret = PyObject_CallObject(cb->func, args); + Py_DECREF(args); + if (ret == NULL) + return FALSE; + if (ret != Py_None) { + result = PyLong_AsLong(ret); + if ((result == -1) && (PyErr_Occurred())) + result = FALSE; + } + Py_DECREF(ret); + return result; } // @pyswig |EnumWindows|Enumerates all top-level windows on the screen by passing the handle to each window, in turn, to an application-defined callback function. static PyObject *PyEnumWindows(PyObject *self, PyObject *args) { - BOOL rc; - PyObject *obFunc, *obOther; - // @pyparm function|callback||A Python function to be used as the callback. Function can return False to stop enumeration, or raise an exception. - // @pyparm object|extra||Any python object - this is passed to the callback function as the second param (first is the hwnd). - if (!PyArg_ParseTuple(args, "OO", &obFunc, &obOther)) - return NULL; - if (!PyCallable_Check(obFunc)) { - PyErr_SetString(PyExc_TypeError, "First param must be a callable object"); - return NULL; - } - PyEnumWindowsCallback cb; - cb.func = obFunc; - cb.extra = obOther; + BOOL rc; + PyObject *obFunc, *obOther; + // @pyparm function|callback||A Python function to be used as the callback. Function can return False to stop enumeration, or raise an exception. + // @pyparm object|extra||Any python object - this is passed to the callback function as the second param (first is the hwnd). + if (!PyArg_ParseTuple(args, "OO", &obFunc, &obOther)) + return NULL; + if (!PyCallable_Check(obFunc)) { + PyErr_SetString(PyExc_TypeError, "First param must be a callable object"); + return NULL; + } + PyEnumWindowsCallback cb; + cb.func = obFunc; + cb.extra = obOther; Py_BEGIN_ALLOW_THREADS - rc = EnumWindows(PyEnumWindowsProc, (LPARAM)&cb); + rc = EnumWindows(PyEnumWindowsProc, (LPARAM)&cb); Py_END_ALLOW_THREADS - if (!rc){ - // Callback may have raised an exception already - if (PyErr_Occurred()) - return NULL; - return PyWin_SetAPIError("EnumWindows"); - } - Py_INCREF(Py_None); - return Py_None; + if (!rc) { + // Callback may have raised an exception already + if (PyErr_Occurred()) + return NULL; + return PyWin_SetAPIErrorOrReturnNone("EnumWindows"); + } + Py_RETURN_NONE; } // @pyswig |EnumThreadWindows|Enumerates all top-level windows associated with a thread on the screen by passing the handle to each window, in turn, to an application-defined callback function. EnumThreadWindows continues until the last top-level window associated with the thread is enumerated or the callback function returns FALSE static PyObject *PyEnumThreadWindows(PyObject *self, PyObject *args) { - BOOL rc; - PyObject *obFunc, *obOther; - DWORD dwThreadId; - // @pyparm int|dwThreadId||The id of the thread for which the windows need to be enumerated. - // @pyparm object|callback||A Python function to be used as the callback. - // @pyparm object|extra||Any python object - this is passed to the callback function as the second param (first is the hwnd). - if (!PyArg_ParseTuple(args, "lOO", &dwThreadId, &obFunc, &obOther)) - return NULL; - if (!PyCallable_Check(obFunc)) { - PyErr_SetString(PyExc_TypeError, "Second param must be a callable object"); - return NULL; - } - PyEnumWindowsCallback cb; - cb.func = obFunc; - cb.extra = obOther; + BOOL rc; + PyObject *obFunc, *obOther; + DWORD dwThreadId; + // @pyparm int|dwThreadId||The id of the thread for which the windows need to be enumerated. + // @pyparm object|callback||A Python function to be used as the callback. + // @pyparm object|extra||Any python object - this is passed to the callback function as the second param (first is the hwnd). + if (!PyArg_ParseTuple(args, "lOO", &dwThreadId, &obFunc, &obOther)) + return NULL; + if (!PyCallable_Check(obFunc)) { + PyErr_SetString(PyExc_TypeError, "Second param must be a callable object"); + return NULL; + } + PyEnumWindowsCallback cb; + cb.func = obFunc; + cb.extra = obOther; Py_BEGIN_ALLOW_THREADS - rc = EnumThreadWindows(dwThreadId, PyEnumWindowsProc, (LPARAM)&cb); + rc = EnumThreadWindows(dwThreadId, PyEnumWindowsProc, (LPARAM)&cb); Py_END_ALLOW_THREADS - if (!rc) - return PyWin_SetAPIError("EnumThreadWindows"); - Py_INCREF(Py_None); - return Py_None; + if (!rc) { + // Callback may have raised an exception already + if (PyErr_Occurred()) + return NULL; + return PyWin_SetAPIErrorOrReturnNone("EnumThreadWindows"); + } + Py_RETURN_NONE; } // @pyswig |EnumChildWindows|Enumerates the child windows that belong to the specified parent window by passing the handle to each child window, in turn, to an application-defined callback function. EnumChildWindows continues until the last child window is enumerated or the callback function returns FALSE. static PyObject *PyEnumChildWindows(PyObject *self, PyObject *args) { - PyObject *obhwnd, *obFunc, *obOther; - HWND hwnd; - // @pyparm |hwnd||The handle to the window to enumerate. - // @pyparm object|callback||A Python function to be used as the callback. - // @pyparm object|extra||Any python object - this is passed to the callback function as the second param (first is the hwnd). - if (!PyArg_ParseTuple(args, "OOO", &obhwnd, &obFunc, &obOther)) - return NULL; - if (!PyWinObject_AsHANDLE(obhwnd, (HANDLE *)&hwnd)) - return NULL; - if (!PyCallable_Check(obFunc)) { - PyErr_SetString(PyExc_TypeError, "First param must be a callable object"); - return NULL; - } - PyEnumWindowsCallback cb; - cb.func = obFunc; - cb.extra = obOther; + PyObject *obhwnd, *obFunc, *obOther; + HWND hwnd; + // @pyparm |hwnd||The handle to the window to enumerate. + // @pyparm object|callback||A Python function to be used as the callback. + // @pyparm object|extra||Any python object - this is passed to the callback function as the second param (first is the hwnd). + if (!PyArg_ParseTuple(args, "OOO", &obhwnd, &obFunc, &obOther)) + return NULL; + if (!PyWinObject_AsHANDLE(obhwnd, (HANDLE *)&hwnd)) + return NULL; + if (!PyCallable_Check(obFunc)) { + PyErr_SetString(PyExc_TypeError, "Second param must be a callable object"); + return NULL; + } + PyEnumWindowsCallback cb; + cb.func = obFunc; + cb.extra = obOther; Py_BEGIN_ALLOW_THREADS - // According to MSDN, the return value is not used, and according to - // #1350, may cause spurious exceptions. - EnumChildWindows(hwnd, PyEnumWindowsProc, (LPARAM)&cb); + // According to MSDN, the return value is not used, and according to + // #1350, may cause spurious exceptions. + EnumChildWindows(hwnd, PyEnumWindowsProc, (LPARAM)&cb); Py_END_ALLOW_THREADS - Py_INCREF(Py_None); - return Py_None; + if (PyErr_Occurred()) + return NULL; + Py_RETURN_NONE; +} + +// @pyswig |EnumDesktopWindows|Enumerates all top-level windows associated with a desktop on the screen by passing the handle to each window, in turn, to an application-defined callback function. EnumThreadWindows continues until the last top-level window associated with the thread is enumerated or the callback function returns FALSE +static PyObject *PyEnumDesktopWindows(PyObject *self, PyObject *args) +{ + BOOL rc; + PyObject *obDesktop, *obFunc, *obOther; + HDESK hDesktop = NULL; + // @pyparm |hDesktop||The id of the desktop for which the windows need to be enumerated. + // @pyparm object|callback||A Python function to be used as the callback. + // @pyparm object|extra||Any python object - this is passed to the callback function as the second param (first is the hwnd). + if (!PyArg_ParseTuple(args, "OOO", &obDesktop, &obFunc, &obOther)) + return NULL; + if (!PyWinObject_AsHANDLE(obDesktop, (HANDLE *)&hDesktop)) + return NULL; + if (!PyCallable_Check(obFunc)) { + PyErr_SetString(PyExc_TypeError, "Second param must be a callable object"); + return NULL; + } + PyEnumWindowsCallback cb; + cb.func = obFunc; + cb.extra = obOther; + Py_BEGIN_ALLOW_THREADS + rc = EnumDesktopWindows(hDesktop, PyEnumWindowsProc, (LPARAM)&cb); + Py_END_ALLOW_THREADS + if (!rc) { + // Callback may have raised an exception already + if (PyErr_Occurred()) + return NULL; + return PyWin_SetAPIErrorOrReturnNone("EnumDesktopWindows"); + } + Py_RETURN_NONE; } %} %native (EnumWindows) PyEnumWindows; %native (EnumThreadWindows) PyEnumThreadWindows; %native (EnumChildWindows) PyEnumChildWindows; +%native (EnumDesktopWindows) PyEnumDesktopWindows; + +HDESK GetThreadDesktop(DWORD dwThreadId); // @pyswig int|DialogBox|Creates a modal dialog box. %{ @@ -5972,7 +6010,7 @@ PyGetClassName(PyObject *self, PyObject *args) return NULL; if (!PyWinObject_AsHANDLE(obhwnd, (HANDLE *)&hwnd)) return NULL; - // dont bother with lock - no callback possible. + // don't bother with lock - no callback possible. int nchars = GetClassName(hwnd, buf, sizeof buf/sizeof buf[0]); if (nchars==0) return PyWin_SetAPIError("GetClassName"); diff --git a/win32/src/win32helpmodule.cpp b/win32/src/win32helpmodule.cpp index f9094b5ed1..9bf9bf7816 100644 --- a/win32/src/win32helpmodule.cpp +++ b/win32/src/win32helpmodule.cpp @@ -66,10 +66,8 @@ static PyObject *PyWinHelp(PyObject *self, PyObject *args) data = (ULONG_PTR)pybuf.ptr(); if (!PyWinObject_AsTCHAR(obhlpFile, &hlpFile, FALSE)) return NULL; - PyW32_BEGIN_ALLOW_THREADS - BOOL ok = ::WinHelp(hwnd, hlpFile, cmd, data); - PyW32_END_ALLOW_THREADS - PyWinObject_FreeTCHAR(hlpFile); + PyW32_BEGIN_ALLOW_THREADS BOOL ok = ::WinHelp(hwnd, hlpFile, cmd, data); + PyW32_END_ALLOW_THREADS PyWinObject_FreeTCHAR(hlpFile); if (!ok) return ReturnAPIError("WinHelp"); Py_INCREF(Py_None); @@ -1527,7 +1525,7 @@ PyNMHDR::PyNMHDR(const NMHDR *pNMHDR) memcpy(&m_NMHDR, pNMHDR, sizeof(m_NMHDR)); } -PyNMHDR::~PyNMHDR(void){}; +PyNMHDR::~PyNMHDR(void) {}; /*static*/ void PyNMHDR::deallocFunc(PyObject *ob) { delete (PyNMHDR *)ob; } @@ -2377,7 +2375,8 @@ file must be a string"); } if (dataOb == Py_None) { data = 0; - } else { + } + else { if (!PyWinObject_AsTCHAR(dataOb, &dataObAsTCHAR, FALSE, NULL)) return NULL; data = (DWORD_PTR)dataObAsTCHAR; @@ -2488,11 +2487,10 @@ data tuple items must be integers"); } HWND helpWnd; - PyW32_BEGIN_ALLOW_THREADS - helpWnd = ::HtmlHelp(hwnd, file, cmd, data); + PyW32_BEGIN_ALLOW_THREADS helpWnd = ::HtmlHelp(hwnd, file, cmd, data); PyW32_END_ALLOW_THREADS - PyWinObject_FreeTCHAR(dataObAsTCHAR); + PyWinObject_FreeTCHAR(dataObAsTCHAR); PyWinObject_FreeTCHAR(file); PyObject *ret; diff --git a/win32/src/win32net/win32netgroup.cpp b/win32/src/win32net/win32netgroup.cpp index 5fcb0357d4..3e30ff88af 100644 --- a/win32/src/win32net/win32netgroup.cpp +++ b/win32/src/win32net/win32netgroup.cpp @@ -8,26 +8,11 @@ #include "win32net.h" #include "stddef.h" -#define GI0_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(GROUP_INFO_0, grpi0_##name), r \ - } -#define GI1_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(GROUP_INFO_1, grpi1_##name), r \ - } -#define GI2_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(GROUP_INFO_2, grpi2_##name), r \ - } -#define GI1002_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(GROUP_INFO_1002, grpi1002_##name), r \ - } -#define GI1005_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(GROUP_INFO_1005, grpi1005_##name), r \ - } +#define GI0_ENTRY(name, t, r) {#name, t, offsetof(GROUP_INFO_0, grpi0_##name), r} +#define GI1_ENTRY(name, t, r) {#name, t, offsetof(GROUP_INFO_1, grpi1_##name), r} +#define GI2_ENTRY(name, t, r) {#name, t, offsetof(GROUP_INFO_2, grpi2_##name), r} +#define GI1002_ENTRY(name, t, r) {#name, t, offsetof(GROUP_INFO_1002, grpi1002_##name), r} +#define GI1005_ENTRY(name, t, r) {#name, t, offsetof(GROUP_INFO_1005, grpi1005_##name), r} // @object PyGROUP_INFO_0|A dictionary holding the information in a Win32 GROUP_INFO_0 structure. static struct PyNET_STRUCT_ITEM gi0[] = { @@ -65,18 +50,9 @@ static struct PyNET_STRUCT group_infos[] = { // @flagh Level|Data {1005, gi1005, sizeof(GROUP_INFO_1005)}, // @flag 1005| {0, NULL, 0}}; -#define LGI0_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(LOCALGROUP_INFO_0, lgrpi0_##name), r \ - } -#define LGI1_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(LOCALGROUP_INFO_1, lgrpi1_##name), r \ - } -#define LGI1002_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(LOCALGROUP_INFO_1002, lgrpi1002_##name), r \ - } +#define LGI0_ENTRY(name, t, r) {#name, t, offsetof(LOCALGROUP_INFO_0, lgrpi0_##name), r} +#define LGI1_ENTRY(name, t, r) {#name, t, offsetof(LOCALGROUP_INFO_1, lgrpi1_##name), r} +#define LGI1002_ENTRY(name, t, r) {#name, t, offsetof(LOCALGROUP_INFO_1002, lgrpi1002_##name), r} // @object PyLOCALGROUP_INFO_0|A dictionary holding the information in a Win32 LOCALGROUP_INFO_0 structure. static struct PyNET_STRUCT_ITEM LGI0[] = { @@ -101,19 +77,13 @@ static struct PyNET_STRUCT localgroup_infos[] = { // @flagh Level|Data {1002, LGI1002, sizeof(LOCALGROUP_INFO_1002)}, // @flag 1002| {0, NULL, 0}}; -#define LGMI0_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(LOCALGROUP_MEMBERS_INFO_0, lgrmi0_##name), r \ - } +#define LGMI0_ENTRY(name, t, r) {#name, t, offsetof(LOCALGROUP_MEMBERS_INFO_0, lgrmi0_##name), r} // @object PyLOCALGROUP_MEMBERS_INFO_0|A dictionary holding the information in a Win32 LOCALGROUP_MEMBERS_INFO_0 // structure. static struct PyNET_STRUCT_ITEM lgmi0[] = {LGMI0_ENTRY(sid, NSI_SID, 0), // @prop |sid| {NULL}}; -#define LGMI1_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(LOCALGROUP_MEMBERS_INFO_1, lgrmi1_##name), r \ - } +#define LGMI1_ENTRY(name, t, r) {#name, t, offsetof(LOCALGROUP_MEMBERS_INFO_1, lgrmi1_##name), r} // @object PyLOCALGROUP_MEMBERS_INFO_1|A dictionary holding the information in a Win32 LOCALGROUP_MEMBERS_INFO_1 // structure. static struct PyNET_STRUCT_ITEM lgmi1[] = {LGMI1_ENTRY(sid, NSI_SID, 0), // @prop |sid| @@ -121,10 +91,7 @@ static struct PyNET_STRUCT_ITEM lgmi1[] = {LGMI1_ENTRY(sid, NSI_SID, 0), LGMI1_ENTRY(name, NSI_WSTR, 0), // @prop string/|name| {NULL}}; -#define LGMI2_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(LOCALGROUP_MEMBERS_INFO_2, lgrmi2_##name), r \ - } +#define LGMI2_ENTRY(name, t, r) {#name, t, offsetof(LOCALGROUP_MEMBERS_INFO_2, lgrmi2_##name), r} // @object PyLOCALGROUP_MEMBERS_INFO_2|A dictionary holding the information in a Win32 LOCALGROUP_MEMBERS_INFO_2 // structure. static struct PyNET_STRUCT_ITEM lgmi2[] = { @@ -134,10 +101,7 @@ static struct PyNET_STRUCT_ITEM lgmi2[] = { // the member prefixed by the domain name and the "\" separator character {NULL}}; -#define LGMI3_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(LOCALGROUP_MEMBERS_INFO_3, lgrmi3_##name), r \ - } +#define LGMI3_ENTRY(name, t, r) {#name, t, offsetof(LOCALGROUP_MEMBERS_INFO_3, lgrmi3_##name), r} // @object PyLOCALGROUP_MEMBERS_INFO_3|A dictionary holding the information in a Win32 LOCALGROUP_MEMBERS_INFO_3 // structure. static struct PyNET_STRUCT_ITEM lgmi3[] = { @@ -153,14 +117,8 @@ static struct PyNET_STRUCT localgroup_members_infos[] = { // @flagh Level|Data {3, lgmi3, sizeof(LOCALGROUP_MEMBERS_INFO_3)}, // @flag 3| {NULL}}; -#define GUI0_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(GROUP_USERS_INFO_0, grui0_##name), r \ - } -#define GUI1_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(GROUP_USERS_INFO_1, grui1_##name), r \ - } +#define GUI0_ENTRY(name, t, r) {#name, t, offsetof(GROUP_USERS_INFO_0, grui0_##name), r} +#define GUI1_ENTRY(name, t, r) {#name, t, offsetof(GROUP_USERS_INFO_1, grui1_##name), r} // @object PyGROUP_USERS_INFO_0|A dictionary holding the information in a Win32 GROUP_USERS_INFO_0 structure. static struct PyNET_STRUCT_ITEM gui0[] = { GUI0_ENTRY(name, NSI_WSTR, 0), // @prop string/|name|Name of the group or user diff --git a/win32/src/win32net/win32netmisc.cpp b/win32/src/win32net/win32netmisc.cpp index 4aa0e796f7..025665e36f 100644 --- a/win32/src/win32net/win32netmisc.cpp +++ b/win32/src/win32net/win32netmisc.cpp @@ -10,28 +10,19 @@ #include "win32net.h" #include "stddef.h" -#define SI0_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(SHARE_INFO_0, shi0_##name), r \ - } +#define SI0_ENTRY(name, t, r) {#name, t, offsetof(SHARE_INFO_0, shi0_##name), r} // @object PySHARE_INFO_0|A dictionary holding the infomation in a Win32 SHARE_INFO_0 structure. static struct PyNET_STRUCT_ITEM si0[] = {SI0_ENTRY(netname, NSI_WSTR, 0), // @prop string/|netname| {NULL}}; -#define SI1_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(SHARE_INFO_1, shi1_##name), r \ - } +#define SI1_ENTRY(name, t, r) {#name, t, offsetof(SHARE_INFO_1, shi1_##name), r} // @object PySHARE_INFO_1|A dictionary holding the infomation in a Win32 SHARE_INFO_1 structure. static struct PyNET_STRUCT_ITEM si1[] = {SI1_ENTRY(netname, NSI_WSTR, 0), // @prop string/|netname| SI1_ENTRY(type, NSI_DWORD, 0), // @prop int|type| SI1_ENTRY(remark, NSI_WSTR, 0), // @prop string/|remark| {NULL}}; -#define SI2_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(SHARE_INFO_2, shi2_##name), r \ - } +#define SI2_ENTRY(name, t, r) {#name, t, offsetof(SHARE_INFO_2, shi2_##name), r} // @object PySHARE_INFO_2|A dictionary holding the infomation in a Win32 SHARE_INFO_2 structure. static struct PyNET_STRUCT_ITEM si2[] = {SI2_ENTRY(netname, NSI_WSTR, 0), // @prop string/|netname| SI2_ENTRY(type, NSI_DWORD, 0), // @prop int|type| @@ -43,10 +34,7 @@ static struct PyNET_STRUCT_ITEM si2[] = {SI2_ENTRY(netname, NSI_WSTR, 0), SI2_ENTRY(passwd, NSI_WSTR, 0), // @prop string/|passwd| {NULL}}; -#define SI501_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(SHARE_INFO_501, shi501_##name), r \ - } +#define SI501_ENTRY(name, t, r) {#name, t, offsetof(SHARE_INFO_501, shi501_##name), r} // @object PySHARE_INFO_501|A dictionary holding the infomation in a Win32 SHARE_INFO_501 structure. static struct PyNET_STRUCT_ITEM si501[] = {SI501_ENTRY(netname, NSI_WSTR, 0), // @prop string/|netname| SI501_ENTRY(type, NSI_DWORD, 0), // @prop int|type| @@ -54,10 +42,7 @@ static struct PyNET_STRUCT_ITEM si501[] = {SI501_ENTRY(netname, NSI_WSTR, 0), / SI501_ENTRY(flags, NSI_DWORD, 0), // @prop int|flags| {NULL}}; -#define SI502_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(SHARE_INFO_502, shi502_##name), r \ - } +#define SI502_ENTRY(name, t, r) {#name, t, offsetof(SHARE_INFO_502, shi502_##name), r} // @object PySHARE_INFO_502|A dictionary holding the infomation in a Win32 SHARE_INFO_502 structure. static struct PyNET_STRUCT_ITEM si502[] = {SI502_ENTRY(netname, NSI_WSTR, 0), // @prop string/|netname| SI502_ENTRY(type, NSI_DWORD, 0), // @prop int|type| @@ -81,10 +66,7 @@ static struct PyNET_STRUCT share_infos[] = { // @flagh Level|Data {502, si502, sizeof(SHARE_INFO_502)}, // @flag 502| {0, NULL, 0}}; -#define WKI100_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(WKSTA_INFO_100, wki100_##name), r \ - } +#define WKI100_ENTRY(name, t, r) {#name, t, offsetof(WKSTA_INFO_100, wki100_##name), r} // @object PyWKSTA_INFO_100|A dictionary holding the infomation in a Win32 WKSTA_INFO_100 structure. static struct PyNET_STRUCT_ITEM wki100[] = { WKI100_ENTRY(platform_id, NSI_DWORD, @@ -98,10 +80,7 @@ static struct PyNET_STRUCT_ITEM wki100[] = { 0), // @prop int|ver_minor|Minor version number of operating system running on the computer {NULL}}; -#define WKI101_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(WKSTA_INFO_101, wki101_##name), r \ - } +#define WKI101_ENTRY(name, t, r) {#name, t, offsetof(WKSTA_INFO_101, wki101_##name), r} // @object PyWKSTA_INFO_101|A dictionary holding the infomation in a Win32 WKSTA_INFO_101 structure. static struct PyNET_STRUCT_ITEM wki101[] = { WKI101_ENTRY(platform_id, NSI_DWORD, @@ -116,10 +95,7 @@ static struct PyNET_STRUCT_ITEM wki101[] = { WKI101_ENTRY(lanroot, NSI_WSTR, 0), // @prop string/|lanroot|Path to the LANMAN directory {NULL}}; -#define WKI102_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(WKSTA_INFO_102, wki102_##name), r \ - } +#define WKI102_ENTRY(name, t, r) {#name, t, offsetof(WKSTA_INFO_102, wki102_##name), r} // @object PyWKSTA_INFO_102|A dictionary holding the infomation in a Win32 WKSTA_INFO_102 structure. static struct PyNET_STRUCT_ITEM wki102[] = { WKI102_ENTRY(platform_id, NSI_DWORD, @@ -136,10 +112,7 @@ static struct PyNET_STRUCT_ITEM wki102[] = { 0), // @prop int|logged_on_users|Number of users who are logged on to the local computer {NULL}}; -#define WKI302_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(WKSTA_INFO_302, wki302_##name), r \ - } +#define WKI302_ENTRY(name, t, r) {#name, t, offsetof(WKSTA_INFO_302, wki302_##name), r} // @object PyWKSTA_INFO_302|A dictionary holding the infomation in a Win32 WKSTA_INFO_302 structure. static struct PyNET_STRUCT_ITEM wki302[] = { WKI302_ENTRY( @@ -193,10 +166,7 @@ static struct PyNET_STRUCT_ITEM wki302[] = { 0), // @prop int|num_dgram_buf|Specifies the number of buffers to allocate for receiving datagrams. {NULL}}; -#define WKI402_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(WKSTA_INFO_402, wki402_##name), r \ - } +#define WKI402_ENTRY(name, t, r) {#name, t, offsetof(WKSTA_INFO_402, wki402_##name), r} // @object PyWKSTA_INFO_402|A dictionary holding the infomation in a Win32 WKSTA_INFO_402 structure. static struct PyNET_STRUCT_ITEM wki402[] = { WKI402_ENTRY( @@ -235,10 +205,7 @@ static struct PyNET_STRUCT_ITEM wki402[] = { 0), // @prop int|max_threads|Number of threads the computer can dedicate to the network {NULL}}; -#define WKI502_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(WKSTA_INFO_502, wki502_##name), r \ - } +#define WKI502_ENTRY(name, t, r) {#name, t, offsetof(WKSTA_INFO_502, wki502_##name), r} // @object PyWKSTA_INFO_502|A dictionary holding the infomation in a Win32 WKSTA_INFO_502 structure. static struct PyNET_STRUCT_ITEM wki502[] = { WKI502_ENTRY( @@ -309,20 +276,14 @@ static struct PyNET_STRUCT wksta_infos[] = { // @flagh Level|Data {502, wki502, sizeof(WKSTA_INFO_502)}, // @flag 502,| {0, NULL, 0}}; -#define WKUI0_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(WKSTA_USER_INFO_0, wkui0_##name), r \ - } +#define WKUI0_ENTRY(name, t, r) {#name, t, offsetof(WKSTA_USER_INFO_0, wkui0_##name), r} // @object PyWKSTA_USER_INFO_0|A dictionary holding the infomation in a Win32 WKSTA_USER_INFO_0 structure. static struct PyNET_STRUCT_ITEM wkui0[] = { WKUI0_ENTRY(username, NSI_WSTR, 0), // @prop string/|username|Name of user currently logged on to the workstation {NULL}}; -#define WKUI1_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(WKSTA_USER_INFO_1, wkui1_##name), r \ - } +#define WKUI1_ENTRY(name, t, r) {#name, t, offsetof(WKSTA_USER_INFO_1, wkui1_##name), r} // @object PyWKSTA_USER_INFO_1|A dictionary holding the infomation in a Win32 WKSTA_USER_INFO_1 structure. static struct PyNET_STRUCT_ITEM wkui1[] = { WKUI1_ENTRY(username, NSI_WSTR, @@ -343,10 +304,7 @@ static struct PyNET_STRUCT wktau_infos[] = { // @flagh Level|Data {1, wkui1, sizeof(WKSTA_USER_INFO_1)}, // @flag 1,| {0, NULL, 0}}; -#define WKTI0_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(WKSTA_TRANSPORT_INFO_0, wkti0_##name), r \ - } +#define WKTI0_ENTRY(name, t, r) {#name, t, offsetof(WKSTA_TRANSPORT_INFO_0, wkti0_##name), r} // @object PyWKSTA_TRANSPORT_INFO_0|A dictionary holding the infomation in a Win32 WKSTA_TRANSPORT_INFO_0 structure. static struct PyNET_STRUCT_ITEM wkti0[] = { WKTI0_ENTRY(quality_of_service, NSI_DWORD, @@ -415,11 +373,11 @@ static PyObject *PyNetShareEnum1(WCHAR *szServerName) return NULL; } - p_nr++; // next object (its a ++ because it is a typed pointer) + p_nr++; // next object (it's a ++ because it is a typed pointer) dwCount--; } while (dwCount); }; // if dwCount - } // if Errno == NERR_Sucess + } // if Errno == NERR_Sucess else { Py_DECREF(pRetlist); @@ -576,18 +534,12 @@ PyObject *PyNetShareCheck(PyObject *self, PyObject *args) // @pyseeapi NetShareCheck } -#define SV100_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(SERVER_INFO_100, sv100_##name), r \ - } +#define SV100_ENTRY(name, t, r) {#name, t, offsetof(SERVER_INFO_100, sv100_##name), r} // @object PySERVER_INFO_100|A dictionary holding the information in a Win32 SERVER_INFO_100 structure. static struct PyNET_STRUCT_ITEM sv100[] = {SV100_ENTRY(platform_id, NSI_DWORD, 0), // @prop int|platform_id| SV100_ENTRY(name, NSI_WSTR, 0), // @prop string/|name| {NULL}}; -#define SV101_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(SERVER_INFO_101, sv101_##name), r \ - } +#define SV101_ENTRY(name, t, r) {#name, t, offsetof(SERVER_INFO_101, sv101_##name), r} // @object PySERVER_INFO_101|A dictionary holding the information in a Win32 SERVER_INFO_101 structure. static struct PyNET_STRUCT_ITEM sv101[] = { SV101_ENTRY(platform_id, NSI_DWORD, 0), // @prop int|platform_id| @@ -598,10 +550,7 @@ static struct PyNET_STRUCT_ITEM sv101[] = { SV101_ENTRY(comment, NSI_WSTR, 0), // @prop string/|comment| {NULL}}; -#define SV102_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(SERVER_INFO_102, sv102_##name), r \ - } +#define SV102_ENTRY(name, t, r) {#name, t, offsetof(SERVER_INFO_102, sv102_##name), r} // @object PySERVER_INFO_102|A dictionary holding the information in a Win32 SERVER_INFO_102 structure. static struct PyNET_STRUCT_ITEM sv102[] = { SV102_ENTRY(platform_id, NSI_DWORD, 0), // @prop int|platform_id| @@ -618,10 +567,7 @@ static struct PyNET_STRUCT_ITEM sv102[] = { SV102_ENTRY(userpath, NSI_WSTR, 0), // @prop string/|userpath| {NULL}}; -#define SV402_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(SERVER_INFO_402, sv402_##name), r \ - } +#define SV402_ENTRY(name, t, r) {#name, t, offsetof(SERVER_INFO_402, sv402_##name), r} // @object PySERVER_INFO_402|A dictionary holding the information in a Win32 SERVER_INFO_402 structure. static struct PyNET_STRUCT_ITEM sv402[] = { SV402_ENTRY(ulist_mtime, NSI_DWORD, 0), // @prop int|ulist_mtime| @@ -656,10 +602,7 @@ static struct PyNET_STRUCT_ITEM sv402[] = { SV402_ENTRY(srvheuristics, NSI_WSTR, 0), // @prop string/|srvheuristics| {NULL}}; -#define SV403_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(SERVER_INFO_403, sv403_##name), r \ - } +#define SV403_ENTRY(name, t, r) {#name, t, offsetof(SERVER_INFO_403, sv403_##name), r} // @object PySERVER_INFO_403|A dictionary holding the information in a Win32 SERVER_INFO_403 structure. static struct PyNET_STRUCT_ITEM sv403[] = { SV403_ENTRY(ulist_mtime, NSI_DWORD, 0), // @prop int|ulist_mtime| @@ -697,10 +640,7 @@ static struct PyNET_STRUCT_ITEM sv403[] = { SV403_ENTRY(autopath, NSI_WSTR, 0), // @prop string/|autopath| {NULL}}; -#define SV502_ENTRY(name, t) \ - { \ -#name, t, offsetof(SERVER_INFO_502, sv502_##name), 0 \ - } +#define SV502_ENTRY(name, t) {#name, t, offsetof(SERVER_INFO_502, sv502_##name), 0} // @object PySERVER_INFO_502|A dictionary holding the information in a Win32 SERVER_INFO_502 structure. static struct PyNET_STRUCT_ITEM sv502[] = { SV502_ENTRY(sessopens, NSI_DWORD), // @prop int|sessopens| @@ -722,10 +662,7 @@ static struct PyNET_STRUCT_ITEM sv502[] = { SV502_ENTRY(lmannounce, NSI_BOOL), // @prop bool|lmannounce| {NULL}}; -#define SV503_ENTRY(name, t) \ - { \ -#name, t, offsetof(SERVER_INFO_503, sv503_##name), 0 \ - } +#define SV503_ENTRY(name, t) {#name, t, offsetof(SERVER_INFO_503, sv503_##name), 0} // @object PySERVER_INFO_503|A dictionary holding the information in a Win32 SERVER_INFO_503 structure. static struct PyNET_STRUCT_ITEM sv503[] = { SV503_ENTRY(sessopens, NSI_DWORD), // @prop int|sessopens| @@ -1484,10 +1421,12 @@ static BOOL PyObject_AsAUTH_INPUT(PyObject *ob, NET_VALIDATE_AUTHENTICATION_INPU kw = ob; args = PyTuple_New(0); BOOL decref_args = (args != 0); - } else if (PyTuple_Check(ob)) { + } + else if (PyTuple_Check(ob)) { kw = NULL; args = ob; - } else { + } + else { PyErr_SetString(PyExc_TypeError, "Must be tuple or dict"); return FALSE; } @@ -1536,10 +1475,12 @@ static BOOL PyObject_AsCHANGE_INPUT(PyObject *ob, NET_VALIDATE_PASSWORD_CHANGE_I kw = ob; args = PyTuple_New(0); BOOL decref_args = (args != 0); - } else if (PyTuple_Check(ob)) { + } + else if (PyTuple_Check(ob)) { kw = NULL; args = ob; - } else { + } + else { PyErr_SetString(PyExc_TypeError, "Must be tuple or dict"); return FALSE; } @@ -1554,7 +1495,8 @@ static BOOL PyObject_AsCHANGE_INPUT(PyObject *ob, NET_VALIDATE_PASSWORD_CHANGE_I &Length, &p->PasswordMatch); // @pyparm int|PasswordMatch|0|Note MSDN incorrectly documents this member as // PasswordMatched - if (rc) p->HashedPassword.Length = Length; + if (rc) + p->HashedPassword.Length = Length; if (decref_args) Py_DECREF(args); diff --git a/win32/src/win32net/win32netuse.cpp b/win32/src/win32net/win32netuse.cpp index a3d49e560e..8ddfce2a52 100644 --- a/win32/src/win32net/win32netuse.cpp +++ b/win32/src/win32net/win32netuse.cpp @@ -9,19 +9,13 @@ #include "win32net.h" #include "stddef.h" -#define UI0_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(USE_INFO_0, ui0_##name), r \ - } +#define UI0_ENTRY(name, t, r) {#name, t, offsetof(USE_INFO_0, ui0_##name), r} // @object PyUSE_INFO_0|A dictionary holding the infomation in a Win32 USE_INFO_0 structure. static struct PyNET_STRUCT_ITEM ui0[] = {UI0_ENTRY(local, NSI_WSTR, 0), // @prop string/|local| UI0_ENTRY(remote, NSI_WSTR, 0), // @prop string/|remote| {NULL}}; -#define UI1_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(USE_INFO_1, ui1_##name), r \ - } +#define UI1_ENTRY(name, t, r) {#name, t, offsetof(USE_INFO_1, ui1_##name), r} // @object PyUSE_INFO_1|A dictionary holding the infomation in a Win32 USE_INFO_1 structure. static struct PyNET_STRUCT_ITEM ui1[] = {UI1_ENTRY(local, NSI_WSTR, 0), // @prop string/|local| UI1_ENTRY(remote, NSI_WSTR, 0), // @prop string/|remote| @@ -32,10 +26,7 @@ static struct PyNET_STRUCT_ITEM ui1[] = {UI1_ENTRY(local, NSI_WSTR, 0), // UI1_ENTRY(usecount, NSI_DWORD, 0), // @prop int|usecount| {NULL}}; -#define UI2_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(USE_INFO_2, ui2_##name), r \ - } +#define UI2_ENTRY(name, t, r) {#name, t, offsetof(USE_INFO_2, ui2_##name), r} // @object PyUSE_INFO_2|A dictionary holding the infomation in a Win32 USE_INFO_2 structure. static struct PyNET_STRUCT_ITEM ui2[] = {UI2_ENTRY(local, NSI_WSTR, 0), // @prop string/|local| UI2_ENTRY(remote, NSI_WSTR, 0), // @prop string/|remote| @@ -48,10 +39,7 @@ static struct PyNET_STRUCT_ITEM ui2[] = {UI2_ENTRY(local, NSI_WSTR, 0), // UI2_ENTRY(domainname, NSI_WSTR, 0), // @prop string/|domainname| {NULL}}; -#define UI3_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(USE_INFO_3, ui3_##name), r \ - } +#define UI3_ENTRY(name, t, r) {#name, t, offsetof(USE_INFO_3, ui3_##name), r} // @object PyUSE_INFO_3|A dictionary holding the infomation in a Win32 USE_INFO_3 structure. static struct PyNET_STRUCT_ITEM ui3[] = { UI2_ENTRY(local, NSI_WSTR, 0), // @prop string/|local| diff --git a/win32/src/win32net/win32netuser.cpp b/win32/src/win32net/win32netuser.cpp index f7a903bf0b..e3977d4d1c 100644 --- a/win32/src/win32net/win32netuser.cpp +++ b/win32/src/win32net/win32netuser.cpp @@ -12,87 +12,27 @@ of the Network API. This is part of the win32net module. #include "win32net.h" #include "stddef.h" -#define UI0_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(USER_INFO_0, usri0_##name), r \ - } -#define UI1_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(USER_INFO_1, usri1_##name), r \ - } -#define UI2_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(USER_INFO_2, usri2_##name), r \ - } -#define UI3_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(USER_INFO_3, usri3_##name), r \ - } -#define UI4_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(USER_INFO_4, usri4_##name), r \ - } -#define UI10_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(USER_INFO_10, usri10_##name), r \ - } -#define UI11_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(USER_INFO_11, usri11_##name), r \ - } -#define UI20_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(USER_INFO_20, usri20_##name), r \ - } -#define UI1003_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(USER_INFO_1003, usri1003_##name), r \ - } -#define UI1005_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(USER_INFO_1005, usri1005_##name), r \ - } -#define UI1006_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(USER_INFO_1006, usri1006_##name), r \ - } -#define UI1007_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(USER_INFO_1007, usri1007_##name), r \ - } -#define UI1008_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(USER_INFO_1008, usri1008_##name), r \ - } -#define UI1009_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(USER_INFO_1009, usri1009_##name), r \ - } -#define UI1010_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(USER_INFO_1010, usri1010_##name), r \ - } -#define UI1011_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(USER_INFO_1011, usri1011_##name), r \ - } - -#define UMI0_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(USER_MODALS_INFO_0, usrmod0_##name), r \ - } -#define UMI1_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(USER_MODALS_INFO_1, usrmod1_##name), r \ - } -#define UMI2_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(USER_MODALS_INFO_2, usrmod2_##name), r \ - } -#define UMI3_ENTRY(name, t, r) \ - { \ -#name, t, offsetof(USER_MODALS_INFO_3, usrmod3_##name), r \ - } +#define UI0_ENTRY(name, t, r) {#name, t, offsetof(USER_INFO_0, usri0_##name), r} +#define UI1_ENTRY(name, t, r) {#name, t, offsetof(USER_INFO_1, usri1_##name), r} +#define UI2_ENTRY(name, t, r) {#name, t, offsetof(USER_INFO_2, usri2_##name), r} +#define UI3_ENTRY(name, t, r) {#name, t, offsetof(USER_INFO_3, usri3_##name), r} +#define UI4_ENTRY(name, t, r) {#name, t, offsetof(USER_INFO_4, usri4_##name), r} +#define UI10_ENTRY(name, t, r) {#name, t, offsetof(USER_INFO_10, usri10_##name), r} +#define UI11_ENTRY(name, t, r) {#name, t, offsetof(USER_INFO_11, usri11_##name), r} +#define UI20_ENTRY(name, t, r) {#name, t, offsetof(USER_INFO_20, usri20_##name), r} +#define UI1003_ENTRY(name, t, r) {#name, t, offsetof(USER_INFO_1003, usri1003_##name), r} +#define UI1005_ENTRY(name, t, r) {#name, t, offsetof(USER_INFO_1005, usri1005_##name), r} +#define UI1006_ENTRY(name, t, r) {#name, t, offsetof(USER_INFO_1006, usri1006_##name), r} +#define UI1007_ENTRY(name, t, r) {#name, t, offsetof(USER_INFO_1007, usri1007_##name), r} +#define UI1008_ENTRY(name, t, r) {#name, t, offsetof(USER_INFO_1008, usri1008_##name), r} +#define UI1009_ENTRY(name, t, r) {#name, t, offsetof(USER_INFO_1009, usri1009_##name), r} +#define UI1010_ENTRY(name, t, r) {#name, t, offsetof(USER_INFO_1010, usri1010_##name), r} +#define UI1011_ENTRY(name, t, r) {#name, t, offsetof(USER_INFO_1011, usri1011_##name), r} + +#define UMI0_ENTRY(name, t, r) {#name, t, offsetof(USER_MODALS_INFO_0, usrmod0_##name), r} +#define UMI1_ENTRY(name, t, r) {#name, t, offsetof(USER_MODALS_INFO_1, usrmod1_##name), r} +#define UMI2_ENTRY(name, t, r) {#name, t, offsetof(USER_MODALS_INFO_2, usrmod2_##name), r} +#define UMI3_ENTRY(name, t, r) {#name, t, offsetof(USER_MODALS_INFO_3, usrmod3_##name), r} // @object PyUSER_INFO_0|A dictionary holding the information in a Win32 USER_INFO_0 structure. static struct PyNET_STRUCT_ITEM ui0[] = {UI0_ENTRY(name, NSI_WSTR, 0), // @prop string/|name| @@ -571,7 +511,7 @@ PyObject *PyNetUserGetGroups(PyObject *self, PyObject *args) return NULL; } - p_nr++; // next object (its a ++ because it is a typed pointer!) + p_nr++; // next object (it's a ++ because it is a typed pointer!) dwCount--; } while (dwCount); }; // if (dwCount > 0) @@ -657,7 +597,7 @@ PyObject *PyNetUserGetLocalGroups(PyObject *self, PyObject *args) return NULL; } - p_nr++; // next object (its a ++ because it is a typed pointer!) + p_nr++; // next object (it's a ++ because it is a typed pointer!) dwCount--; } while (dwCount); }; // if (dwCount > 0) diff --git a/win32/src/win32pdhmodule.cpp b/win32/src/win32pdhmodule.cpp index 26d5df5c23..5631da52a7 100644 --- a/win32/src/win32pdhmodule.cpp +++ b/win32/src/win32pdhmodule.cpp @@ -665,7 +665,7 @@ static PyObject *PyGetFormattedCounterValue(PyObject *self, PyObject *args) else if (format & PDH_FMT_LARGE) rc = PyLong_FromLongLong(result.largeValue); else { - PyErr_SetString(PyExc_ValueError, "Dont know how to convert the result"); + PyErr_SetString(PyExc_ValueError, "Don't know how to convert the result"); rc = NULL; } PyObject *realrc = Py_BuildValue("iO", type, rc); @@ -697,8 +697,7 @@ static PyObject *PyPdhGetFormattedCounterArray(PyObject *self, PyObject *args) pdhStatus = (*pPdhGetFormattedCounterArray)(handle, format, &size, &count, pItems); Py_END_ALLOW_THREADS; if (pdhStatus != PDH_MORE_DATA) { - return PyWin_SetAPIError("PdhGetFormattedCounterArray", - pdhStatus); + return PyWin_SetAPIError("PdhGetFormattedCounterArray", pdhStatus); } pItems = (PDH_FMT_COUNTERVALUE_ITEM *)malloc(size); if (pItems == NULL) { @@ -709,8 +708,7 @@ static PyObject *PyPdhGetFormattedCounterArray(PyObject *self, PyObject *args) Py_BEGIN_ALLOW_THREADS; pdhStatus = (*pPdhGetFormattedCounterArray)(handle, format, &size, &count, pItems); Py_END_ALLOW_THREADS; - if (pdhStatus != ERROR_SUCCESS) - { + if (pdhStatus != ERROR_SUCCESS) { free(pItems); return PyWin_SetAPIError("PdhGetFormattedCounterArray", pdhStatus); } @@ -733,7 +731,7 @@ static PyObject *PyPdhGetFormattedCounterArray(PyObject *self, PyObject *args) else if (format & PDH_FMT_LARGE) value = PyLong_FromLongLong(pItems[i].FmtValue.largeValue); else { - PyErr_SetString(PyExc_ValueError, "Dont know how to convert the result"); + PyErr_SetString(PyExc_ValueError, "Don't know how to convert the result"); Py_XDECREF(rc); Py_XDECREF(key); rc = NULL; diff --git a/win32/src/win32print/win32print.cpp b/win32/src/win32print/win32print.cpp index 6962767cf9..9a4ce5829e 100644 --- a/win32/src/win32print/win32print.cpp +++ b/win32/src/win32print/win32print.cpp @@ -218,7 +218,7 @@ static PyObject *PyWinObject_FromPRINTER_INFO(LPBYTE printer_info, DWORD level) pi5->TransmissionRetryTimeout); case 6: PRINTER_INFO_6 *pi6; - pi6 = (PRINTER_INFO_6*)printer_info; + pi6 = (PRINTER_INFO_6 *)printer_info; return Py_BuildValue("{s:k}", "Status", pi6->dwStatus); case 7: PRINTER_INFO_7 *pi7; @@ -335,16 +335,15 @@ void PyWinObject_FreePRINTER_INFO(DWORD level, LPBYTE pbuf) free(pbuf); } -#define AsPRINTER_INFO__INIT_PRINTER_INFO_X(_PRINTER_INFO_X, _PIX_PTR) \ - _PRINTER_INFO_X *_PIX_PTR; \ - bufsize = sizeof(_PRINTER_INFO_X); \ - if ((*pbuf = (LPBYTE)malloc(bufsize)) == NULL) { \ +#define AsPRINTER_INFO__INIT_PRINTER_INFO_X(_PRINTER_INFO_X, _PIX_PTR) \ + _PRINTER_INFO_X *_PIX_PTR; \ + bufsize = sizeof(_PRINTER_INFO_X); \ + if ((*pbuf = (LPBYTE)malloc(bufsize)) == NULL) { \ PyErr_Format(PyExc_MemoryError, "Malloc failed for %d bytes", bufsize); \ - break; \ - } \ - ZeroMemory(*pbuf, bufsize); \ - _PIX_PTR = (_PRINTER_INFO_X*)*pbuf; - + break; \ + } \ + ZeroMemory(*pbuf, bufsize); \ + _PIX_PTR = (_PRINTER_INFO_X *)*pbuf; BOOL PyWinObject_AsPRINTER_INFO(DWORD level, PyObject *obinfo, LPBYTE *pbuf) { @@ -459,9 +458,7 @@ BOOL PyWinObject_AsPRINTER_INFO(DWORD level, PyObject *obinfo, LPBYTE *pbuf) break; } case 6: { - static char *pi6_keys[] = { - "Status", - NULL }; + static char *pi6_keys[] = {"Status", NULL}; static char *pi6_format = "k:PRINTER_INFO_6"; AsPRINTER_INFO__INIT_PRINTER_INFO_X(PRINTER_INFO_6, pi6); ret = PyArg_ParseTupleAndKeywords(dummy_tuple, obinfo, pi6_format, pi6_keys, &pi6->dwStatus); @@ -1139,7 +1136,7 @@ static PyObject *PyGetJob(PyObject *self, PyObject *args) // Convert a python dictionary to a JOB_INFO_* structure. // Returned buffer must be freed. -BOOL PytoJob(DWORD level, PyObject *pyjobinfo, LPBYTE *pbuf, TmpWCHAR* tmpw_shelve) +BOOL PytoJob(DWORD level, PyObject *pyjobinfo, LPBYTE *pbuf, TmpWCHAR *tmpw_shelve) { static char *job1_keys[] = {"JobId", "pPrinterName", "pMachineName", "pUserName", "pDocument", "pDatatype", "pStatus", "Status", "Priority", "Position", @@ -1161,7 +1158,7 @@ BOOL PytoJob(DWORD level, PyObject *pyjobinfo, LPBYTE *pbuf, TmpWCHAR* tmpw_shel // record conversions unicode / None --> WCHAR* / NULL int i, u2w_count = 0; TmpWCHAR *ptw = tmpw_shelve; -#define U2W(target) (ptw->u=(PyObject*)target, ptw++, u2w_count++, target) +#define U2W(target) (ptw->u = (PyObject *)target, ptw++, u2w_count++, target) *pbuf = NULL; switch (level) { @@ -1185,9 +1182,9 @@ BOOL PytoJob(DWORD level, PyObject *pyjobinfo, LPBYTE *pbuf, TmpWCHAR* tmpw_shel ZeroMemory(job1, sizeof(JOB_INFO_1)); if (PyArg_ParseTupleAndKeywords(dummy_tuple, pyjobinfo, job1_format, job1_keys, &job1->JobId, U2W(&job1->pPrinterName), U2W(&job1->pMachineName), U2W(&job1->pUserName), - U2W(&job1->pDocument), U2W(&job1->pDatatype), U2W(&job1->pStatus), &job1->Status, - &job1->Priority, &job1->Position, &job1->TotalPages, &job1->PagesPrinted, - &obsubmitted) && + U2W(&job1->pDocument), U2W(&job1->pDatatype), U2W(&job1->pStatus), + &job1->Status, &job1->Priority, &job1->Position, &job1->TotalPages, + &job1->PagesPrinted, &obsubmitted) && ((obsubmitted == Py_None) || PyWinObject_AsSYSTEMTIME(obsubmitted, &job1->Submitted))) ret = TRUE; break; @@ -1205,10 +1202,11 @@ BOOL PytoJob(DWORD level, PyObject *pyjobinfo, LPBYTE *pbuf, TmpWCHAR* tmpw_shel ZeroMemory(job2, sizeof(JOB_INFO_2)); if (PyArg_ParseTupleAndKeywords( dummy_tuple, pyjobinfo, job2_format, job2_keys, &job2->JobId, U2W(&job2->pPrinterName), - U2W(&job2->pMachineName), U2W(&job2->pUserName), U2W(&job2->pDocument), U2W(&job2->pNotifyName), U2W(&job2->pDatatype), - U2W(&job2->pPrintProcessor), U2W(&job2->pParameters), U2W(&job2->pDriverName), &obdevmode, U2W(&job2->pStatus), - &obsecurity_descriptor, &job2->Status, &job2->Priority, &job2->Position, &job2->StartTime, - &job2->UntilTime, &job2->TotalPages, &job2->Size, &obsubmitted, &job2->Time, &job2->PagesPrinted) && + U2W(&job2->pMachineName), U2W(&job2->pUserName), U2W(&job2->pDocument), U2W(&job2->pNotifyName), + U2W(&job2->pDatatype), U2W(&job2->pPrintProcessor), U2W(&job2->pParameters), + U2W(&job2->pDriverName), &obdevmode, U2W(&job2->pStatus), &obsecurity_descriptor, &job2->Status, + &job2->Priority, &job2->Position, &job2->StartTime, &job2->UntilTime, &job2->TotalPages, + &job2->Size, &obsubmitted, &job2->Time, &job2->PagesPrinted) && PyWinObject_AsDEVMODE(obdevmode, &job2->pDevMode, TRUE) && PyWinObject_AsSECURITY_DESCRIPTOR(obsecurity_descriptor, &job2->pSecurityDescriptor, TRUE) && ((obsubmitted == Py_None) || PyWinObject_AsSYSTEMTIME(obsubmitted, &job2->Submitted))) @@ -1234,11 +1232,11 @@ BOOL PytoJob(DWORD level, PyObject *pyjobinfo, LPBYTE *pbuf, TmpWCHAR* tmpw_shel } // Conversions unicode / None --> WCHAR* / NULL (held by tmpw_shelve) - for (i=0, ptw = tmpw_shelve; ret && i < u2w_count; i++, ptw++) { - PyObject *o = *(PyObject**)ptw->u; + for (i = 0, ptw = tmpw_shelve; ret && i < u2w_count; i++, ptw++) { + PyObject *o = *(PyObject **)ptw->u; if (o == Py_None) - *(WCHAR**)ptw->u = NULL; - else if (!(*(WCHAR**)ptw->u = *ptw = o)) // convert, hold and store in target + *(WCHAR **)ptw->u = NULL; + else if (!(*(WCHAR **)ptw->u = *ptw = o)) // convert, hold and store in target ret = FALSE; } #undef U2W @@ -1710,7 +1708,7 @@ BOOL PyWinObject_AsSIZEL(PyObject *obsizel, SIZEL *sizel) // @prop dict|ImageableArea|A dictionary representing a RECTL structure {'left':int, 'top':int, 'right':int, // 'bottom':int} -BOOL PyWinObject_AsFORM_INFO_1(PyObject *obform, FORM_INFO_1W *fi1, TmpWCHAR* ptw) +BOOL PyWinObject_AsFORM_INFO_1(PyObject *obform, FORM_INFO_1W *fi1, TmpWCHAR *ptw) { static char *form_keys[] = {"Flags", "Name", "Size", "ImageableArea", 0}; static char *err_msg = @@ -1720,8 +1718,8 @@ BOOL PyWinObject_AsFORM_INFO_1(PyObject *obform, FORM_INFO_1W *fi1, TmpWCHAR* pt return FALSE; } return PyArg_ParseTupleAndKeywords(dummy_tuple, obform, "kUO&O&:FORM_INFO_1", form_keys, &fi1->Flags, &ptw->u, - PyWinObject_AsSIZEL, &fi1->Size, PyWinObject_AsRECTL, &fi1->ImageableArea) - && (fi1->pName=ptw->u2w()); + PyWinObject_AsSIZEL, &fi1->Size, PyWinObject_AsRECTL, &fi1->ImageableArea) && + (fi1->pName = ptw->u2w()); } // @pymethod |win32print|AddForm|Adds a form for a printer @@ -1736,8 +1734,8 @@ static PyObject *PyAddForm(PyObject *self, PyObject *args) PyObject *py_form1; TmpWCHAR tmpw_shelve[1]; - if (!PyArg_ParseTuple(args, "O&O:AddForm", PyWinObject_AsPrinterHANDLE, &hprinter, &py_form1) - || !PyWinObject_AsFORM_INFO_1(py_form1, &fi1, tmpw_shelve)) + if (!PyArg_ParseTuple(args, "O&O:AddForm", PyWinObject_AsPrinterHANDLE, &hprinter, &py_form1) || + !PyWinObject_AsFORM_INFO_1(py_form1, &fi1, tmpw_shelve)) return NULL; if (!(*pfnAddForm)(hprinter, 1, (LPBYTE)&fi1)) return PyWin_SetAPIError("AddForm"); @@ -1755,7 +1753,8 @@ static PyObject *PyDeleteForm(PyObject *self, PyObject *args) TmpWCHAR formname; CHECK_PFN(DeleteForm); - if (!PyArg_ParseTuple(args, "O&U:DeleteForm", PyWinObject_AsPrinterHANDLE, &hprinter, &formname.u) || !formname.u2w()) + if (!PyArg_ParseTuple(args, "O&U:DeleteForm", PyWinObject_AsPrinterHANDLE, &hprinter, &formname.u) || + !formname.u2w()) return NULL; if (!(*pfnDeleteForm)(hprinter, formname)) return PyWin_SetAPIError("DeleteForm"); @@ -1809,8 +1808,8 @@ static PyObject *PySetForm(PyObject *self, PyObject *args) TmpWCHAR tmpw_shelve[1]; CHECK_PFN(SetForm); - if (!PyArg_ParseTuple(args, "O&UO:SetForm", PyWinObject_AsPrinterHANDLE, &hprinter, &formname.u, &py_form1) - || !formname.u2w() || !PyWinObject_AsFORM_INFO_1(py_form1, &fi1, tmpw_shelve)) + if (!PyArg_ParseTuple(args, "O&UO:SetForm", PyWinObject_AsPrinterHANDLE, &hprinter, &formname.u, &py_form1) || + !formname.u2w() || !PyWinObject_AsFORM_INFO_1(py_form1, &fi1, tmpw_shelve)) return NULL; if (!(*pfnSetForm)(hprinter, formname, 1, (LPBYTE)&fi1)) return PyWin_SetAPIError("SetForm"); @@ -1892,7 +1891,7 @@ static PyObject *PyDeviceCapabilities(PyObject *self, PyObject *args) static DWORD papernamesize = 64; // same for DC_PAPERNAMES, DC_MEDIATYPENAMES, DC_MEDIAREADY, DC_FILEDEPENDENCIES static DWORD binnamesize = 24; // DC_BINNAMES static DWORD personalitysize = 32; // DC_PERSONALITY - DWORD retsize, actual_ret_size ; + DWORD retsize, actual_ret_size; if (!PyArg_ParseTuple(args, "OOh|O:DeviceCapabilities", &obdevice, &obport, &capability, &obdevmode)) return NULL; @@ -2459,7 +2458,8 @@ static PyObject *PyDeletePrinterDriver(PyObject *self, PyObject *args) // @comm Does not delete associated driver files - use if this is required if (PyArg_ParseTuple(args, "OOO:DeletePrinterDriver", &observername, &obenvironment, &obdrivername) && PyWinObject_AsWCHAR(observername, &servername, TRUE) && - PyWinObject_AsWCHAR(obenvironment, &environment, TRUE) && PyWinObject_AsWCHAR(obdrivername, &drivername, FALSE)) { + PyWinObject_AsWCHAR(obenvironment, &environment, TRUE) && + PyWinObject_AsWCHAR(obdrivername, &drivername, FALSE)) { if (DeletePrinterDriverW(servername, environment, drivername)) { Py_INCREF(Py_None); ret = Py_None; @@ -2495,7 +2495,8 @@ static PyObject *PyDeletePrinterDriverEx(PyObject *self, PyObject *args) if (PyArg_ParseTuple(args, "OOOll:DeletePrinterDriverEx", &observername, &obenvironment, &obdrivername, &deleteflag, &versionflag) && PyWinObject_AsWCHAR(observername, &servername, TRUE) && - PyWinObject_AsWCHAR(obenvironment, &environment, TRUE) && PyWinObject_AsWCHAR(obdrivername, &drivername, FALSE)) { + PyWinObject_AsWCHAR(obenvironment, &environment, TRUE) && + PyWinObject_AsWCHAR(obdrivername, &drivername, FALSE)) { if ((*pfnDeletePrinterDriverEx)(servername, environment, drivername, deleteflag, versionflag)) { Py_INCREF(Py_None); ret = Py_None; diff --git a/win32/src/win32process.i b/win32/src/win32process.i index c7e95ddaa0..beeb85981a 100644 --- a/win32/src/win32process.i +++ b/win32/src/win32process.i @@ -460,7 +460,7 @@ static PyObject *myCreateRemoteThread(PyObject *self, PyObject *args) %native (CreateRemoteThread) myCreateRemoteThread; -// Wont expose ExitThread!!! May leak all sorts of things! +// Won't expose ExitThread!!! May leak all sorts of things! %{ diff --git a/win32/src/win32security_sspi.cpp b/win32/src/win32security_sspi.cpp index 8322769ebf..32960b4299 100644 --- a/win32/src/win32security_sspi.cpp +++ b/win32/src/win32security_sspi.cpp @@ -67,7 +67,7 @@ PySequenceMethods PySecBufferDesc_sequencemethods = { NULL, // objobjproc sq_contains; NULL, // binaryfunc sq_inplace_concat; NULL // intargfunc sq_inplace_repeat; -}; // ??? why isnt append included ??? +}; // ??? why isn't append included ??? // @object PySecBufferDesc|Sequence-like object that contains a group of buffers to be used with SSPI functions. // @comm This object is created using win32security.PySecBufferDescType(Version), where Version is an int that @@ -192,11 +192,11 @@ PyObject *PySecBufferDesc::tp_new(PyTypeObject *typ, PyObject *args, PyObject *k return new PySecBufferDesc(ulVersion); } -PyObject * PySecBufferDesc::tp_repr(PyObject * obj) +PyObject *PySecBufferDesc::tp_repr(PyObject *obj) { PSecBufferDesc psecbufferdesc = ((PySecBufferDesc *)obj)->GetSecBufferDesc(); return PyUnicode_FromFormat("PySecBufferDesc(ulVersion: %i | cBuffers: %i | pBuffers: %p)", - psecbufferdesc->ulVersion, psecbufferdesc->cBuffers, psecbufferdesc->pBuffers); + psecbufferdesc->ulVersion, psecbufferdesc->cBuffers, psecbufferdesc->pBuffers); } BOOL PyWinObject_AsSecBufferDesc(PyObject *ob, PSecBufferDesc *ppSecBufferDesc, BOOL bNoneOk) @@ -365,8 +365,7 @@ PySecBuffer::PySecBuffer(ULONG cbBuffer, ULONG BufferType) secbuffer.BufferType = BufferType; allocBuffer = NULL; - if (cbBuffer > 0) - { + if (cbBuffer > 0) { // Stores our allocated memory in a class property so we don't try and free memory that wasn't allocated by us. // Windows could change where pvBuffer points to after a function call and we should only be concerned about // freeing memory that we have allocated ourselves. @@ -452,11 +451,11 @@ PyObject *PySecBuffer::tp_new(PyTypeObject *typ, PyObject *args, PyObject *kwarg return new PySecBuffer(cbBuffer, BufferType); } -PyObject * PySecBuffer::tp_repr(PyObject * obj) +PyObject *PySecBuffer::tp_repr(PyObject *obj) { PSecBuffer psecbuffer = ((PySecBuffer *)obj)->GetSecBuffer(); return PyUnicode_FromFormat("PySecBuffer(cbBuffer: %i | BufferType: %i | pvBuffer: %p)", psecbuffer->cbBuffer, - psecbuffer->BufferType, psecbuffer->pvBuffer); + psecbuffer->BufferType, psecbuffer->pvBuffer); } // @pymethod |PySecBuffer|Clear|Resets the buffer to all NULL's, and set the current size to maximum @@ -896,7 +895,8 @@ PyObject *PyCtxtHandle::QueryContextAttributes(PyObject *self, PyObject *args) pe = (PSecPkgContext_PasswordExpiry)&buf; ret = PyWinObject_FromTimeStamp(pe->tsPasswordExpires); break; - // @flag SECPKG_ATTR_LIFESPAN|(,) - returns time period during which context is valid + // @flag SECPKG_ATTR_LIFESPAN|(,) - returns time period during which context is + // valid case SECPKG_ATTR_LIFESPAN: PSecPkgContext_Lifespan ls; ls = (PSecPkgContext_Lifespan)&buf; diff --git a/win32/src/win32security_sspi.h b/win32/src/win32security_sspi.h index e850a372ff..262ed9cb62 100644 --- a/win32/src/win32security_sspi.h +++ b/win32/src/win32security_sspi.h @@ -51,7 +51,7 @@ class PySecBuffer : public PyObject { static PyObject *getattro(PyObject *self, PyObject *name); static int setattro(PyObject *self, PyObject *obname, PyObject *obvalue); static PyObject *tp_new(PyTypeObject *, PyObject *, PyObject *); - static PyObject *tp_repr(PyObject * obj); + static PyObject *tp_repr(PyObject *obj); static PyObject *Clear(PyObject *self, PyObject *args); PSecBuffer GetSecBuffer(void); @@ -83,7 +83,7 @@ class PySecBufferDesc : public PyObject { static PyObject *getattro(PyObject *self, PyObject *name); static int setattro(PyObject *self, PyObject *obname, PyObject *obvalue); static PyObject *tp_new(PyTypeObject *, PyObject *, PyObject *); - static PyObject *tp_repr(PyObject * obj); + static PyObject *tp_repr(PyObject *obj); static PySequenceMethods sequencemethods; PSecBufferDesc GetSecBufferDesc(void); PyObject **obBuffers; diff --git a/win32/src/win32wnet/PyNetresource.cpp b/win32/src/win32wnet/PyNetresource.cpp index 62be645b32..9d928b326e 100644 --- a/win32/src/win32wnet/PyNetresource.cpp +++ b/win32/src/win32wnet/PyNetresource.cpp @@ -65,36 +65,36 @@ __declspec(dllexport) PyTypeObject PyNETRESOURCEType = { 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ - 0, /* tp_as_async */ - 0, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* hash? */ - 0, /* tp_call */ - 0, /* tp_str */ - PyNETRESOURCE::getattro, /* tp_getattro */ - PyNETRESOURCE::setattro, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - 0, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - PyNETRESOURCE::members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - NETRESOURCE_new, /* tp_new */ + 0, /* tp_as_async */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* hash? */ + 0, /* tp_call */ + 0, /* tp_str */ + PyNETRESOURCE::getattro, /* tp_getattro */ + PyNETRESOURCE::setattro, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + 0, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + PyNETRESOURCE::members, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + NETRESOURCE_new, /* tp_new */ }; #define OFF(e) offsetof(PyNETRESOURCE, e) diff --git a/win32/src/win32wnet/win32wnet.cpp b/win32/src/win32wnet/win32wnet.cpp index beb18c8330..fe5c6ccb12 100644 --- a/win32/src/win32wnet/win32wnet.cpp +++ b/win32/src/win32wnet/win32wnet.cpp @@ -149,8 +149,7 @@ static PyObject *PyWNetAddConnection2(PyObject *self, PyObject *args, PyObject * if (!PyWinObject_AsTCHAR(obPassword, &Password, TRUE) || !PyWinObject_AsTCHAR(obUsername, &Username, TRUE)) goto done; - Py_BEGIN_ALLOW_THREADS - ErrorNo = WNetAddConnection2(pNetResource, Password, Username, flags); + Py_BEGIN_ALLOW_THREADS ErrorNo = WNetAddConnection2(pNetResource, Password, Username, flags); Py_END_ALLOW_THREADS if (ErrorNo != NO_ERROR) ReturnNetError("WNetAddConnection2", ErrorNo); else { @@ -315,7 +314,7 @@ static PyObject *PyWNetEnumResource(PyObject *self, PyObject *args) // nothing hard & fast here, just a rough sizing..have to figure out something better later if (dwMaxCount == 0) // using 0 to mean a default - dwMaxCount = dwCount = 64; // lets default at 64 items + dwMaxCount = dwCount = 64; // let's default at 64 items else dwCount = dwMaxCount; // yes virginia, 0xffffffff is a LOT of items @@ -365,7 +364,7 @@ static PyObject *PyWNetEnumResource(PyObject *self, PyObject *args) return (ReturnError("Unable to create return list", "WNetEnumResource")); } - p_nr++; // next NETRESOURCE object (its a ++ because it is a typed pointer) + p_nr++; // next NETRESOURCE object (it's a ++ because it is a typed pointer) dwCount--; } while (dwCount); }; // if @@ -458,7 +457,7 @@ static PyObject *PyWNetGetUniversalName(PyObject *self, PyObject *args) // First get the buffer size. { - Py_BEGIN_ALLOW_THREADS char temp_buf[] = ""; // doesnt appear to like NULL!! + Py_BEGIN_ALLOW_THREADS char temp_buf[] = ""; // doesn't appear to like NULL!! errcode = WNetGetUniversalName(szLocalPath, level, &temp_buf, &length); Py_END_ALLOW_THREADS } diff --git a/win32/test/handles.py b/win32/test/handles.py index eb71524952..01b7f17ef9 100644 --- a/win32/test/handles.py +++ b/win32/test/handles.py @@ -93,7 +93,7 @@ def testOtherHandle(self): # but the above doesn't really test everything - we want a way to # pass the handle directly into PyWinLong_AsVoidPtr. One way to # to that is to abuse win32api.GetProcAddress() - the 2nd param - # is passed to PyWinLong_AsVoidPtr() if its not a string. + # is passed to PyWinLong_AsVoidPtr() if it's not a string. # passing a handle value of '1' should work - there is something # at that ordinal win32api.GetProcAddress(sys.dllhandle, h) diff --git a/win32/test/test_exceptions.py b/win32/test/test_exceptions.py index 984d7271ba..c222f0adeb 100644 --- a/win32/test/test_exceptions.py +++ b/win32/test/test_exceptions.py @@ -5,7 +5,6 @@ import pythoncom import pywintypes import win32api -import win32file import winerror @@ -100,7 +99,7 @@ def testStrangeArgsNotEnough(self): raise pywintypes.error("foo") self.fail("Expected exception") except pywintypes.error as exc: - assert exc.args[0] == "foo" + self.assertEqual(exc.args[0], "foo") # 'winerror' always args[0] self.assertEqual(exc.winerror, "foo") self.assertEqual(exc.funcname, None) diff --git a/win32/test/test_pywintypes.py b/win32/test/test_pywintypes.py index 67c4a5afe5..cf679b7566 100644 --- a/win32/test/test_pywintypes.py +++ b/win32/test/test_pywintypes.py @@ -22,7 +22,7 @@ def testPyTimeFormat(self): def testPyTimePrint(self): # This used to crash with an invalid, or too early time. # We don't really want to check that it does cause a ValueError - # (as hopefully this wont be true forever). So either working, or + # (as hopefully this won't be true forever). So either working, or # ValueError is OK. try: t = pywintypes.Time(-2) diff --git a/win32/test/test_sspi.py b/win32/test/test_sspi.py index 17256b75b1..6b113aeb0e 100644 --- a/win32/test/test_sspi.py +++ b/win32/test/test_sspi.py @@ -1,7 +1,6 @@ # Some tests of the win32security sspi functions. # Stolen from Roger's original test_sspi.c, a version of which is in "Demos" # See also the other SSPI demos. -import re import unittest import sspi @@ -196,33 +195,33 @@ def testSequenceEncrypt(self): def testSecBufferRepr(self): desc = win32security.PySecBufferDescType() - assert re.match( - r"PySecBufferDesc\(ulVersion: 0 \| cBuffers: 0 \| pBuffers: 0x[\da-fA-F]{8,16}\)", + self.assertRegex( repr(desc), + r"PySecBufferDesc\(ulVersion: 0 \| cBuffers: 0 \| pBuffers: 0x[\da-fA-F]{8,16}\)", ) buffer1 = win32security.PySecBufferType(0, sspicon.SECBUFFER_TOKEN) - assert re.match( - r"PySecBuffer\(cbBuffer: 0 \| BufferType: 2 \| pvBuffer: 0x[\da-fA-F]{8,16}\)", + self.assertRegex( repr(buffer1), + r"PySecBuffer\(cbBuffer: 0 \| BufferType: 2 \| pvBuffer: 0x[\da-fA-F]{8,16}\)", ) desc.append(buffer1) - assert re.match( - r"PySecBufferDesc\(ulVersion: 0 \| cBuffers: 1 \| pBuffers: 0x[\da-fA-F]{8,16}\)", + self.assertRegex( repr(desc), + r"PySecBufferDesc\(ulVersion: 0 \| cBuffers: 1 \| pBuffers: 0x[\da-fA-F]{8,16}\)", ) buffer2 = win32security.PySecBufferType(4, sspicon.SECBUFFER_DATA) - assert re.match( - r"PySecBuffer\(cbBuffer: 4 \| BufferType: 1 \| pvBuffer: 0x[\da-fA-F]{8,16}\)", + self.assertRegex( repr(buffer2), + r"PySecBuffer\(cbBuffer: 4 \| BufferType: 1 \| pvBuffer: 0x[\da-fA-F]{8,16}\)", ) desc.append(buffer2) - assert re.match( - r"PySecBufferDesc\(ulVersion: 0 \| cBuffers: 2 \| pBuffers: 0x[\da-fA-F]{8,16}\)", + self.assertRegex( repr(desc), + r"PySecBufferDesc\(ulVersion: 0 \| cBuffers: 2 \| pBuffers: 0x[\da-fA-F]{8,16}\)", ) diff --git a/win32/test/test_win32file.py b/win32/test/test_win32file.py index 159c45e678..fd72c614d7 100644 --- a/win32/test/test_win32file.py +++ b/win32/test/test_win32file.py @@ -313,7 +313,7 @@ def testSimpleOverlapped(self): for i in range(num_loops): win32file.WriteFile(h, chunk_data, overlapped) win32event.WaitForSingleObject(overlapped.hEvent, win32event.INFINITE) - overlapped.Offset = overlapped.Offset + len(chunk_data) + overlapped.Offset += len(chunk_data) h.Close() # Now read the data back overlapped overlapped = pywintypes.OVERLAPPED() @@ -328,7 +328,7 @@ def testSimpleOverlapped(self): try: hr, data = win32file.ReadFile(h, buffer, overlapped) win32event.WaitForSingleObject(overlapped.hEvent, win32event.INFINITE) - overlapped.Offset = overlapped.Offset + len(data) + overlapped.Offset += len(data) if not data is buffer: self.fail( "Unexpected result from ReadFile - should be the same buffer we passed it" @@ -351,7 +351,7 @@ def testCompletionPortsMultiple(self): sock.listen(1) socks.append(sock) new = win32file.CreateIoCompletionPort(sock.fileno(), ioport, PORT, 0) - assert new is ioport + self.assertIs(new, ioport) for s in socks: s.close() hv = int(ioport) @@ -552,11 +552,11 @@ def testIter(self): set2 = set() for file in win32file.FindFilesIterator(dir): set2.add(file) - assert len(set2) > 5, "This directory has less than 5 files!?" + self.assertGreater(len(set2), 5, "This directory has less than 5 files!?") self.assertEqual(set1, set2) def testBadDir(self): - dir = os.path.join(os.getcwd(), "a dir that doesnt exist", "*") + dir = os.path.join(os.getcwd(), "a dir that doesn't exist", "*") self.assertRaises(win32file.error, win32file.FindFilesIterator, dir) def testEmptySpec(self): @@ -724,7 +724,7 @@ def testEncrypt(self): except win32file.error as details: if details.winerror != winerror.ERROR_ACCESS_DENIED: raise - print("It appears this is not NTFS - cant encrypt/decrypt") + print("It appears this is not NTFS - can't encrypt/decrypt") win32file.DecryptFile(fname) finally: if f is not None: diff --git a/win32/test/test_win32gui.py b/win32/test/test_win32gui.py index ad96bd4352..c5754722c3 100644 --- a/win32/test/test_win32gui.py +++ b/win32/test/test_win32gui.py @@ -1,9 +1,12 @@ # tests for win32gui import array import operator +import sys import unittest import pywin32_testutil +import pywintypes +import win32api import win32gui @@ -61,5 +64,150 @@ def test_memory_not_writable(self): self.assertRaises(TypeError, operator.setitem, got, 0, 1) +class TestEnumWindowsFamily(unittest.TestCase): + @classmethod + def enum_callback_sle(cls, handle, data): + win32api.SetLastError(1) + return data + + @classmethod + def enum_callback_exc(cls, handle, data): + raise ValueError + + @classmethod + def enum_callback(cls, handle, data): + return data + + def setUp(self): + self.default_data_set = (None, -1, 0, 1, True, False) + self.type_data_set = ("", (), {}) + + def test_enumwindows(self): + win32api.SetLastError(0) + for data in (0, False): + self.assertRaises( + pywintypes.error, win32gui.EnumWindows, self.enum_callback_sle, data + ) + for data in (None, 1, True): + self.assertIsNone(win32gui.EnumWindows(self.enum_callback_sle, data)) + win32api.SetLastError(0) + for data in self.default_data_set: + self.assertIsNone(win32gui.EnumWindows(self.enum_callback, data)) + for data in self.default_data_set: + self.assertRaises( + ValueError, win32gui.EnumWindows, self.enum_callback_exc, data + ) + for func in ( + self.enum_callback, + self.enum_callback_sle, + ): + for data in self.type_data_set: + self.assertRaises(TypeError, win32gui.EnumWindows, func, data) + if sys.version_info >= (3, 10): + for func in ( + self.enum_callback, + self.enum_callback_sle, + ): + self.assertRaises( + TypeError, win32gui.EnumWindows, func, self.enum_callback, 2.718282 + ) + + def test_enumchildwindows(self): + win32api.SetLastError(0) + for data in self.default_data_set: + self.assertIsNone(win32gui.EnumChildWindows(None, self.enum_callback, data)) + for data in self.default_data_set: + self.assertIsNone( + win32gui.EnumChildWindows(None, self.enum_callback_sle, data) + ) + win32api.SetLastError(0) + for data in self.default_data_set: + self.assertRaises( + ValueError, + win32gui.EnumChildWindows, + None, + self.enum_callback_exc, + data, + ) + for data in self.type_data_set: + for func in ( + self.enum_callback, + self.enum_callback_sle, + ): + self.assertRaises( + TypeError, win32gui.EnumChildWindows, None, func, data + ) + if sys.version_info >= (3, 10): + for func in ( + self.enum_callback, + self.enum_callback_sle, + ): + self.assertRaises( + TypeError, + win32gui.EnumChildWindows, + None, + func, + self.enum_callback, + 2.718282, + ) + + def test_enumdesktopwindows(self): + win32api.SetLastError(0) + desktop = None + for data in (0, False): + self.assertRaises( + pywintypes.error, + win32gui.EnumDesktopWindows, + desktop, + self.enum_callback_sle, + data, + ) + for data in (None, 1, True): + self.assertIsNone( + win32gui.EnumDesktopWindows(desktop, self.enum_callback_sle, data) + ) + win32api.SetLastError(0) + for data in self.default_data_set: + self.assertIsNone( + win32gui.EnumDesktopWindows(desktop, self.enum_callback, data) + ) + for data in self.default_data_set: + self.assertRaises( + ValueError, + win32gui.EnumDesktopWindows, + desktop, + self.enum_callback_exc, + data, + ) + desktops = (0, None) + for desktop in desktops: + for data in self.default_data_set: + self.assertRaises( + ValueError, + win32gui.EnumDesktopWindows, + desktop, + self.enum_callback_exc, + data, + ) + for func in ( + self.enum_callback, + self.enum_callback_sle, + ): + for desktop in desktops: + for data in self.type_data_set: + self.assertRaises( + TypeError, win32gui.EnumDesktopWindows, 0, func, data + ) + if sys.version_info >= (3, 10): + for func in ( + self.enum_callback, + self.enum_callback_sle, + ): + for desktop in desktops: + self.assertRaises( + TypeError, win32gui.EnumDesktopWindows, 0, func, 2.718282 + ) + + if __name__ == "__main__": unittest.main() diff --git a/win32/test/test_win32inet.py b/win32/test/test_win32inet.py index bf4a9af3cc..fe7de185c0 100644 --- a/win32/test/test_win32inet.py +++ b/win32/test/test_win32inet.py @@ -53,9 +53,8 @@ def testPythonDotOrg(self): break chunks.append(chunk) data = b"".join(chunks) - assert data.find(b"Python") > 0, repr( - data - ) # This must appear somewhere on the main page! + # This must appear somewhere on the main page! + self.assertGreater(data.find(b"Python"), 0, repr(data)) def testFtpCommand(self): # ftp.python.org doesn't exist. ftp.gnu.org is what Python's urllib diff --git a/win32/test/test_win32profile.py b/win32/test/test_win32profile.py index 71432363fd..4ddc8d3826 100644 --- a/win32/test/test_win32profile.py +++ b/win32/test/test_win32profile.py @@ -10,9 +10,9 @@ class Tester(unittest.TestCase): def test_environment(self): os.environ["FOO"] = "bar=baz" env = win32profile.GetEnvironmentStrings() - assert "FOO" in env - assert env["FOO"] == "bar=baz" - assert os.environ["FOO"] == "bar=baz" + self.assertIn("FOO", env) + self.assertEqual(env["FOO"], "bar=baz") + self.assertEqual(os.environ["FOO"], "bar=baz") if __name__ == "__main__": diff --git a/win32/test/test_win32trace.py b/win32/test/test_win32trace.py index 48ef0141c2..d1b64d5720 100644 --- a/win32/test/test_win32trace.py +++ b/win32/test/test_win32trace.py @@ -152,7 +152,7 @@ def testFlush(self): def testIsatty(self): tracer = win32trace.GetTracer() - assert tracer.isatty() == False + self.assertFalse(tracer.isatty()) def testRoundTrip(self): traceObject = win32trace.GetTracer() @@ -195,7 +195,7 @@ def tearDown(self): def areBucketsFull(self): bucketsAreFull = True for each in self.buckets: - assert each <= self.FullBucket, each + self.assertLessEqual(each, self.FullBucket) if each != self.FullBucket: bucketsAreFull = False break @@ -207,7 +207,7 @@ def read(self): for ch in readString: integer = int(ch) count = self.buckets[integer] - assert count != -1 + self.assertNotEqual(count, -1) self.buckets[integer] = count + 1 if self.buckets[integer] == self.FullBucket: if self.areBucketsFull(): @@ -220,8 +220,8 @@ def testThreads(self): for each in self.threads: each.join() for each in self.threads: - assert each.verifyWritten() - assert self.areBucketsFull() + self.assertTrue(each.verifyWritten()) + self.assertTrue(self.areBucketsFull()) class TestHugeChunks(unittest.TestCase): @@ -238,7 +238,7 @@ def testHugeChunks(self): data = "*" * 1023 + "\n" while len(data) <= self.BiggestChunk: win32trace.write(data) - data = data + data + data += data # If we made it here, we passed. def tearDown(self): @@ -305,7 +305,7 @@ def setUpWriters(self): def areBucketsFull(self): bucketsAreFull = True for each in self.buckets: - assert each <= self.FullBucket, each + self.assertLessEqual(each, self.FullBucket) if each != self.FullBucket: bucketsAreFull = False break @@ -317,7 +317,7 @@ def read(self): for ch in readString: integer = int(ch) count = self.buckets[integer] - assert count != -1 + self.assertNotEqual(count, -1) self.buckets[integer] = count + 1 if self.buckets[integer] == self.FullBucket: if self.areBucketsFull(): @@ -330,8 +330,8 @@ def testProcesses(self): for each in self.processes: each.join() for each in self.processes: - assert each.verifyWritten() - assert self.areBucketsFull() + self.assertTrue(each.verifyWritten()) + self.assertTrue(self.areBucketsFull()) def _RunAsTestProcess():