id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
171,864 | import win32api
import win32ui
def SaveDebuggerOptions(opts):
for key, val in opts.items():
win32ui.WriteProfileVal("Debugger Options", key, val) | null |
171,865 | import bdb
import os
import pdb
import string
import sys
import traceback
import types
import commctrl
import pywin.docking.DockingBar
import win32api
import win32con
import win32ui
from pywin.framework import app, editor, interact, scriptutils
from pywin.framework.editor.color.coloreditor import MARKER_BREAKPOINT, MARKER_CURRENT
from pywin.mfc import afxres, dialog, object, window
from pywin.tools import browser, hierlist
from .dbgcon import *
def SetInteractiveContext(globs, locs):
if interact.edit is not None and interact.edit.currentView is not None:
interact.edit.currentView.SetContext(globs, locs) | null |
171,866 | import bdb
import os
import pdb
import string
import sys
import traceback
import types
import commctrl
import pywin.docking.DockingBar
import win32api
import win32con
import win32ui
from pywin.framework import app, editor, interact, scriptutils
from pywin.framework.editor.color.coloreditor import MARKER_BREAKPOINT, MARKER_CURRENT
from pywin.mfc import afxres, dialog, object, window
from pywin.tools import browser, hierlist
from .dbgcon import *
MARKER_BREAKPOINT = 1
MARKER_CURRENT = 2
LINESTATE_CURRENT = 0x1
def _LineStateToMarker(ls):
if ls == LINESTATE_CURRENT:
return MARKER_CURRENT
# elif ls == LINESTATE_CALLSTACK:
# return MARKER_CALLSTACK
return MARKER_BREAKPOINT | null |
171,867 | import bdb
import os
import pdb
import string
import sys
import traceback
import types
import commctrl
import pywin.docking.DockingBar
import win32api
import win32con
import win32ui
from pywin.framework import app, editor, interact, scriptutils
from pywin.framework.editor.color.coloreditor import MARKER_BREAKPOINT, MARKER_CURRENT
from pywin.mfc import afxres, dialog, object, window
from pywin.tools import browser, hierlist
if win32ui.UNICODE:
LVN_ENDLABELEDIT = commctrl.LVN_ENDLABELEDITW
else:
LVN_ENDLABELEDIT = commctrl.LVN_ENDLABELEDITA
from .dbgcon import *
error = "pywin.debugger.error"
def CreateDebuggerDialog(parent, klass):
control = klass()
control.CreateWindow(parent)
return control
DebuggerDialogInfos = (
(0xE810, DebuggerStackWindow, None),
(0xE811, DebuggerBreakpointsWindow, (10, 10)),
(0xE812, DebuggerWatchWindow, None),
)
import win32ui
def PrepareControlBars(frame):
style = (
win32con.WS_CHILD
| afxres.CBRS_SIZE_DYNAMIC
| afxres.CBRS_TOP
| afxres.CBRS_TOOLTIPS
| afxres.CBRS_FLYBY
)
tbd = win32ui.CreateToolBar(frame, style, win32ui.ID_VIEW_TOOLBAR_DBG)
tbd.ModifyStyle(0, commctrl.TBSTYLE_FLAT)
tbd.LoadToolBar(win32ui.IDR_DEBUGGER)
tbd.EnableDocking(afxres.CBRS_ALIGN_ANY)
tbd.SetWindowText("Debugger")
frame.DockControlBar(tbd)
# and the other windows.
for id, klass, float in DebuggerDialogInfos:
try:
frame.GetControlBar(id)
exists = 1
except win32ui.error:
exists = 0
if exists:
continue
bar = pywin.docking.DockingBar.DockingBar()
style = win32con.WS_CHILD | afxres.CBRS_LEFT # don't create visible.
bar.CreateWindow(
frame,
CreateDebuggerDialog,
klass.title,
id,
style,
childCreatorArgs=(klass,),
)
bar.SetBarStyle(
bar.GetBarStyle()
| afxres.CBRS_TOOLTIPS
| afxres.CBRS_FLYBY
| afxres.CBRS_SIZE_DYNAMIC
)
bar.EnableDocking(afxres.CBRS_ALIGN_ANY)
if float is None:
frame.DockControlBar(bar)
else:
frame.FloatControlBar(bar, float, afxres.CBRS_ALIGN_ANY)
## frame.ShowControlBar(bar, 0, 1) | null |
171,868 | import sys
import time
import pywin.debugger
def b():
b = 1
pywin.debugger.set_trace()
# After importing or running this module, you are likely to be
# sitting at the next line. This is because we explicitely
# broke into the debugger using the "set_trace() function
# "pywin.debugger.brk()" is a shorter alias for this.
c()
def a():
a = 1
try:
b()
except:
# Break into the debugger with the exception information.
pywin.debugger.post_mortem(sys.exc_info()[2])
a = 1
a = 2
a = 3
a = 4 | null |
171,869 | import threading
import time
import win32api
import win32con
import win32ui
from pywin.mfc import dialog
from pywin.mfc.thread import WinThread
def MakeProgressDlgTemplate(caption, staticText=""):
style = (
win32con.DS_MODALFRAME
| win32con.WS_POPUP
| win32con.WS_VISIBLE
| win32con.WS_CAPTION
| win32con.WS_SYSMENU
| win32con.DS_SETFONT
)
cs = win32con.WS_CHILD | win32con.WS_VISIBLE
w = 215
h = 36 # With button
h = 40
dlg = [
[caption, (0, 0, w, h), style, None, (8, "MS Sans Serif")],
]
s = win32con.WS_TABSTOP | cs
dlg.append([130, staticText, 1000, (7, 7, w - 7, h - 32), cs | win32con.SS_LEFT])
# dlg.append([128,
# "Cancel",
# win32con.IDCANCEL,
# (w - 60, h - 18, 50, 14), s | win32con.BS_PUSHBUTTON])
return dlg | null |
171,870 | import threading
import time
import win32api
import win32con
import win32ui
from pywin.mfc import dialog
from pywin.mfc.thread import WinThread
def StatusProgressDialog(title, msg="", maxticks=100, parent=None):
def demo():
d = StatusProgressDialog("A Demo", "Doing something...")
import win32api
for i in range(100):
if i == 50:
d.SetText("Getting there...")
if i == 90:
d.SetText("Nearly done...")
win32api.Sleep(20)
d.Tick()
d.Close() | null |
171,871 | import threading
import time
import win32api
import win32con
import win32ui
from pywin.mfc import dialog
from pywin.mfc.thread import WinThread
def ThreadedStatusProgressDialog(title, msg="", maxticks=100):
t = ProgressThread(title, msg, maxticks)
t.CreateThread()
# Need to run a basic "PumpWaitingMessages" loop just incase we are
# running inside Pythonwin.
# Basic timeout incase things go terribly wrong. Ideally we should use
# win32event.MsgWaitForMultipleObjects(), but we use a threading module
# event - so use a dumb strategy
end_time = time.time() + 10
while time.time() < end_time:
if t.createdEvent.isSet():
break
win32ui.PumpWaitingMessages()
time.sleep(0.1)
return t.dialog
def thread_demo():
d = ThreadedStatusProgressDialog("A threaded demo", "Doing something")
import win32api
for i in range(100):
if i == 50:
d.SetText("Getting there...")
if i == 90:
d.SetText("Nearly done...")
win32api.Sleep(20)
d.Tick()
d.Close() | null |
171,872 | import win32api
import win32con
import win32ui
from pywin.mfc import dialog
def MakeLoginDlgTemplate(title):
style = (
win32con.DS_MODALFRAME
| win32con.WS_POPUP
| win32con.WS_VISIBLE
| win32con.WS_CAPTION
| win32con.WS_SYSMENU
| win32con.DS_SETFONT
)
cs = win32con.WS_CHILD | win32con.WS_VISIBLE
# Window frame and title
dlg = [
[title, (0, 0, 184, 40), style, None, (8, "MS Sans Serif")],
]
# ID label and text box
dlg.append([130, "User ID:", -1, (7, 9, 69, 9), cs | win32con.SS_LEFT])
s = cs | win32con.WS_TABSTOP | win32con.WS_BORDER
dlg.append(["EDIT", None, win32ui.IDC_EDIT1, (50, 7, 60, 12), s])
# Password label and text box
dlg.append([130, "Password:", -1, (7, 22, 69, 9), cs | win32con.SS_LEFT])
s = cs | win32con.WS_TABSTOP | win32con.WS_BORDER
dlg.append(
["EDIT", None, win32ui.IDC_EDIT2, (50, 20, 60, 12), s | win32con.ES_PASSWORD]
)
# OK/Cancel Buttons
s = cs | win32con.WS_TABSTOP
dlg.append(
[128, "OK", win32con.IDOK, (124, 5, 50, 14), s | win32con.BS_DEFPUSHBUTTON]
)
s = win32con.BS_PUSHBUTTON | s
dlg.append([128, "Cancel", win32con.IDCANCEL, (124, 20, 50, 14), s])
return dlg | null |
171,873 | import win32api
import win32con
import win32ui
from pywin.mfc import dialog
def MakePasswordDlgTemplate(title):
style = (
win32con.DS_MODALFRAME
| win32con.WS_POPUP
| win32con.WS_VISIBLE
| win32con.WS_CAPTION
| win32con.WS_SYSMENU
| win32con.DS_SETFONT
)
cs = win32con.WS_CHILD | win32con.WS_VISIBLE
# Window frame and title
dlg = [
[title, (0, 0, 177, 45), style, None, (8, "MS Sans Serif")],
]
# Password label and text box
dlg.append([130, "Password:", -1, (7, 7, 69, 9), cs | win32con.SS_LEFT])
s = cs | win32con.WS_TABSTOP | win32con.WS_BORDER
dlg.append(
["EDIT", None, win32ui.IDC_EDIT1, (50, 7, 60, 12), s | win32con.ES_PASSWORD]
)
# OK/Cancel Buttons
s = cs | win32con.WS_TABSTOP | win32con.BS_PUSHBUTTON
dlg.append(
[128, "OK", win32con.IDOK, (124, 5, 50, 14), s | win32con.BS_DEFPUSHBUTTON]
)
dlg.append([128, "Cancel", win32con.IDCANCEL, (124, 22, 50, 14), s])
return dlg | null |
171,874 | import win32api
import win32con
import win32ui
from pywin.mfc import dialog
class LoginDlg(dialog.Dialog):
def __init__(self, title):
def GetLogin(title="Login", userid="", password=""):
d = LoginDlg(title)
d["userid"] = userid
d["password"] = password
if d.DoModal() != win32con.IDOK:
return (None, None)
else:
return (d["userid"], d["password"]) | null |
171,875 | import win32api
import win32con
import win32ui
from pywin.mfc import dialog
class PasswordDlg(dialog.Dialog):
def __init__(self, title):
dialog.Dialog.__init__(self, MakePasswordDlgTemplate(title))
self.AddDDX(win32ui.IDC_EDIT1, "password")
def GetPassword(title="Password", password=""):
d = PasswordDlg(title)
d["password"] = password
if d.DoModal() != win32con.IDOK:
return None
return d["password"] | null |
171,876 | import commctrl
import win32api
import win32con
import win32ui
from pywin.mfc import dialog
class ListDialog(dialog.Dialog):
def __init__(self, title, list):
def _maketemplate(self, title):
def FillList(self):
def OnListClick(self, id, code):
def OnListItemChange(self, std, extra):
def OnInitDialog(self):
def LayoutControls(self, w, h):
def on_size(self, params):
def SelectFromList(title, lst):
dlg = ListDialog(title, lst)
if dlg.DoModal() == win32con.IDOK:
return dlg.selecteditem
else:
return None | null |
171,877 | import inspect
import string
import sys
import traceback
def _find_constructor(class_ob):
# Given a class object, return a function object used for the
# constructor (ie, __init__() ) or None if we can't find one.
try:
return class_ob.__init__
except AttributeError:
for base in class_ob.__bases__:
rc = _find_constructor(base)
if rc is not None:
return rc
return None
def get_arg_text(ob):
# Get a string describing the arguments for the given object.
argText = ""
if ob is not None:
if inspect.isclass(ob):
# Look for the highest __init__ in the class chain.
fob = _find_constructor(ob)
if fob is None:
fob = lambda: None
else:
fob = ob
if inspect.isfunction(fob) or inspect.ismethod(fob):
try:
argText = str(inspect.signature(fob))
except:
print("Failed to format the args")
traceback.print_exc()
# See if we can use the docstring
if hasattr(ob, "__doc__"):
doc = ob.__doc__
try:
doc = doc.strip()
pos = doc.find("\n")
except AttributeError:
## New style classes may have __doc__ slot without actually
## having a string assigned to it
pass
else:
if pos < 0 or pos > 70:
pos = 70
if argText:
argText = argText + "\n"
argText = argText + doc[:pos]
return argText | null |
171,878 | import inspect
import string
import sys
import traceback
The provided code snippet includes necessary dependencies for implementing the `t1` function. Write a Python function `def t1()` to solve the following problem:
()
Here is the function:
def t1():
"()" | () |
171,879 | import inspect
import string
import sys
import traceback
The provided code snippet includes necessary dependencies for implementing the `t2` function. Write a Python function `def t2(a, b=None)` to solve the following problem:
(a, b=None)
Here is the function:
def t2(a, b=None):
"(a, b=None)" | (a, b=None) |
171,880 | import inspect
import string
import sys
import traceback
The provided code snippet includes necessary dependencies for implementing the `t3` function. Write a Python function `def t3(a, *args)` to solve the following problem:
(a, *args)
Here is the function:
def t3(a, *args):
"(a, *args)" | (a, *args) |
171,881 | import inspect
import string
import sys
import traceback
The provided code snippet includes necessary dependencies for implementing the `t4` function. Write a Python function `def t4(*args)` to solve the following problem:
(*args)
Here is the function:
def t4(*args):
"(*args)" | (*args) |
171,882 | import inspect
import string
import sys
import traceback
The provided code snippet includes necessary dependencies for implementing the `t5` function. Write a Python function `def t5(a, *args)` to solve the following problem:
(a, *args)
Here is the function:
def t5(a, *args):
"(a, *args)" | (a, *args) |
171,883 | import inspect
import string
import sys
import traceback
The provided code snippet includes necessary dependencies for implementing the `t6` function. Write a Python function `def t6(a, b=None, *args, **kw)` to solve the following problem:
(a, b=None, *args, **kw)
Here is the function:
def t6(a, b=None, *args, **kw):
"(a, b=None, *args, **kw)" | (a, b=None, *args, **kw) |
171,884 | import re
def is_all_white(line):
return re.match(r"^\s*$", line) is not None
def get_comment_header(line):
m = re.match(r"^(\s*#*)", line)
if m is None:
return ""
return m.group(1)
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
line = text.get("%d.0" % lineno, "%d.0 lineend" % lineno)
first_lineno = lineno
comment_header = get_comment_header(line)
comment_header_len = len(comment_header)
while get_comment_header(line) == comment_header and not is_all_white(
line[comment_header_len:]
):
lineno = lineno + 1
line = text.get("%d.0" % lineno, "%d.0 lineend" % lineno)
last = "%d.0" % lineno
# Search back to beginning of paragraph
lineno = first_lineno - 1
line = text.get("%d.0" % lineno, "%d.0 lineend" % lineno)
while (
lineno > 0
and get_comment_header(line) == comment_header
and not is_all_white(line[comment_header_len:])
):
lineno = 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) | null |
171,885 | import re
def is_all_white(line):
return re.match(r"^\s*$", line) is not None
def get_indent(line):
return re.match(r"^(\s*)", line).group()
def reformat_paragraph(data, limit=70):
lines = data.split("\n")
i = 0
n = len(lines)
while i < n and is_all_white(lines[i]):
i = i + 1
if i >= n:
return data
indent1 = get_indent(lines[i])
if i + 1 < n and not is_all_white(lines[i + 1]):
indent2 = get_indent(lines[i + 1])
else:
indent2 = indent1
new = lines[:i]
partial = indent1
while i < n and not is_all_white(lines[i]):
# XXX Should take double space after period (etc.) into account
words = re.split("(\s+)", lines[i])
for j in range(0, len(words), 2):
word = words[j]
if not word:
continue # Can happen when line ends in whitespace
if len((partial + word).expandtabs()) > limit and partial != indent1:
new.append(partial.rstrip())
partial = indent2
partial = partial + word + " "
if j + 1 < len(words) and words[j + 1] != " ":
partial = partial + " "
i = i + 1
new.append(partial.rstrip())
# XXX Should reformat remaining paragraphs as well
new.extend(lines[i:])
return "\n".join(new) | null |
171,886 | import sys
import tokenize
from pywin import default_scintilla_encoding
from . import PyParse
def index2line(index):
return int(float(index)) | null |
171,887 | import sys
import tokenize
from pywin import default_scintilla_encoding
from . import PyParse
def classifyws(s, tabwidth):
raw = effective = 0
for ch in s:
if ch == " ":
raw = raw + 1
effective = effective + 1
elif ch == "\t":
raw = raw + 1
effective = (effective // tabwidth + 1) * tabwidth
else:
break
return raw, effective | null |
171,888 | import re
import string
import sys
def dump(*stuff):
sys.__stdout__.write(" ".join(map(str, stuff)) + "\n") | null |
171,889 | import string
import sys
import win32api
import win32con
import win32ui
from pywin import default_scintilla_encoding
from pywin.mfc.dialog import GetSimpleInput
class TextError(Exception):
def GetIDLEModule(module):
try:
# First get it from Pythonwin it is exists.
modname = "pywin.idle." + module
__import__(modname)
except ImportError as details:
msg = (
"The IDLE extension '%s' can not be located.\r\n\r\n"
"Please correct the installation and restart the"
" application.\r\n\r\n%s" % (module, details)
)
win32ui.MessageBox(msg)
return None
mod = sys.modules[modname]
mod.TclError = TextError # A hack that can go soon!
return mod | null |
171,890 | import string
import sys
import win32api
import win32con
import win32ui
from pywin import default_scintilla_encoding
from pywin.mfc.dialog import GetSimpleInput
default_scintilla_encoding = "utf-8"
def fast_readline(self):
if self.finished:
val = ""
else:
if "_scint_lines" not in self.__dict__:
# XXX - note - assumes this is only called once the file is loaded!
self._scint_lines = self.text.edit.GetTextRange().split("\n")
sl = self._scint_lines
i = self.i = self.i + 1
if i >= len(sl):
val = ""
else:
val = sl[i] + "\n"
return val.encode(default_scintilla_encoding) | null |
171,891 | import string
import sys
import win32api
import win32con
import win32ui
from pywin import default_scintilla_encoding
from pywin.mfc.dialog import GetSimpleInput
def TkOffsetToIndex(offset, edit):
lineoff = 0
# May be 1 > actual end if we pretended there was a trailing '\n'
offset = min(offset, edit.GetTextLength())
line = edit.LineFromChar(offset)
lineIndex = edit.LineIndex(line)
return "%d.%d" % (line + 1, offset - lineIndex) | null |
171,892 | import string
import sys
import win32api
import win32con
import win32ui
from pywin import default_scintilla_encoding
from pywin.mfc.dialog import GetSimpleInput
def TkIndexToOffset(bm, edit, marks):
base, nextTokPos = _NextTok(bm, 0)
if base is None:
raise ValueError("Empty bookmark ID!")
if base.find(".") > 0:
try:
line, col = base.split(".", 2)
if col == "first" or col == "last":
# Tag name
if line != "sel":
raise ValueError("Tags arent here!")
sel = edit.GetSel()
if sel[0] == sel[1]:
raise EmptyRange
if col == "first":
pos = sel[0]
else:
pos = sel[1]
else:
# Lines are 1 based for tkinter
line = int(line) - 1
if line > edit.GetLineCount():
pos = edit.GetTextLength() + 1
else:
pos = edit.LineIndex(line)
if pos == -1:
pos = edit.GetTextLength()
pos = pos + int(col)
except (ValueError, IndexError):
raise ValueError("Unexpected literal in '%s'" % base)
elif base == "insert":
pos = edit.GetSel()[0]
elif base == "end":
pos = edit.GetTextLength()
# Pretend there is a trailing '\n' if necessary
if pos and edit.SCIGetCharAt(pos - 1) != "\n":
pos = pos + 1
else:
try:
pos = marks[base]
except KeyError:
raise ValueError("Unsupported base offset or undefined mark '%s'" % base)
while 1:
word, nextTokPos = _NextTok(bm, nextTokPos)
if word is None:
break
if word in ("+", "-"):
num, nextTokPos = _NextTok(bm, nextTokPos)
if num is None:
raise ValueError("+/- operator needs 2 args")
what, nextTokPos = _NextTok(bm, nextTokPos)
if what is None:
raise ValueError("+/- operator needs 2 args")
if what[0] != "c":
raise ValueError("+/- only supports chars")
if word == "+":
pos = pos + int(num)
else:
pos = pos - int(num)
elif word == "wordstart":
while pos > 0 and edit.SCIGetCharAt(pos - 1) in wordchars:
pos = pos - 1
elif word == "wordend":
end = edit.GetTextLength()
while pos < end and edit.SCIGetCharAt(pos) in wordchars:
pos = pos + 1
elif word == "linestart":
while pos > 0 and edit.SCIGetCharAt(pos - 1) not in "\n\r":
pos = pos - 1
elif word == "lineend":
end = edit.GetTextLength()
while pos < end and edit.SCIGetCharAt(pos) not in "\n\r":
pos = pos + 1
else:
raise ValueError("Unsupported relative offset '%s'" % word)
return max(pos, 0) # Tkinter is tollerant of -ve indexes - we aren't
def TestCheck(index, edit, expected=None):
rc = TkIndexToOffset(index, edit, {})
if rc != expected:
print("ERROR: Index", index, ", expected", expected, "but got", rc) | null |
171,893 | import string
import sys
import win32api
import win32con
import win32ui
from pywin import default_scintilla_encoding
from pywin.mfc.dialog import GetSimpleInput
def TestGet(fr, to, t, expected):
got = t.get(fr, to)
if got != expected:
print(
"ERROR: get(%s, %s) expected %s, but got %s"
% (repr(fr), repr(to), repr(expected), repr(got))
) | null |
171,894 | import string
import sys
import win32api
import win32con
import win32ui
from pywin import default_scintilla_encoding
from pywin.mfc.dialog import GetSimpleInput
class TextError(Exception): # When a TclError would normally be raised.
pass
class TkText:
def __init__(self, edit):
self.calltips = None
self.edit = edit
self.marks = {}
## def __getattr__(self, attr):
## if attr=="tk": return self # So text.tk.call works.
## if attr=="master": return None # ditto!
## raise AttributeError, attr
## def __getitem__(self, item):
## if item=="tabs":
## 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"
## raise IndexError, "Invalid index '%s'" % item
def make_calltip_window(self):
if self.calltips is None:
self.calltips = CallTips(self.edit)
return self.calltips
def _getoffset(self, index):
return TkIndexToOffset(index, self.edit, self.marks)
def _getindex(self, off):
return TkOffsetToIndex(off, self.edit)
def _fix_indexes(self, start, end):
# first some magic to handle skipping over utf8 extended chars.
while start > 0 and ord(self.edit.SCIGetCharAt(start)) & 0xC0 == 0x80:
start -= 1
while (
end < self.edit.GetTextLength()
and ord(self.edit.SCIGetCharAt(end)) & 0xC0 == 0x80
):
end += 1
# now handling fixing \r\n->\n disparities...
if (
start > 0
and self.edit.SCIGetCharAt(start) == "\n"
and self.edit.SCIGetCharAt(start - 1) == "\r"
):
start = start - 1
if (
end < self.edit.GetTextLength()
and self.edit.SCIGetCharAt(end - 1) == "\r"
and self.edit.SCIGetCharAt(end) == "\n"
):
end = end + 1
return start, end
## def get_tab_width(self):
## return self.edit.GetTabWidth()
## def call(self, *rest):
## # Crap to support Tk measurement hacks for tab widths
## if rest[0] != "font" or rest[1] != "measure":
## raise ValueError, "Unsupport call type"
## return len(rest[5])
## def configure(self, **kw):
## for name, val in kw.items():
## if name=="tabs":
## self.edit.SCISetTabWidth(int(val))
## else:
## raise ValueError, "Unsupported configuration item %s" % kw
def bind(self, binding, handler):
self.edit.bindings.bind(binding, handler)
def get(self, start, end=None):
try:
start = self._getoffset(start)
if end is None:
end = start + 1
else:
end = self._getoffset(end)
except EmptyRange:
return ""
# Simple semantic checks to conform to the Tk text interface
if end <= start:
return ""
max = self.edit.GetTextLength()
checkEnd = 0
if end > max:
end = max
checkEnd = 1
start, end = self._fix_indexes(start, end)
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"
return ret.replace("\r", "")
def index(self, spec):
try:
return self._getindex(self._getoffset(spec))
except EmptyRange:
return ""
def insert(self, pos, text):
try:
pos = self._getoffset(pos)
except EmptyRange:
raise TextError("Empty range")
self.edit.SetSel((pos, pos))
# IDLE only deals with "\n" - we will be nicer
bits = text.split("\n")
self.edit.SCIAddText(bits[0])
for bit in bits[1:]:
self.edit.SCINewline()
self.edit.SCIAddText(bit)
def delete(self, start, end=None):
try:
start = self._getoffset(start)
if end is not None:
end = self._getoffset(end)
except EmptyRange:
raise TextError("Empty range")
# If end is specified and == start, then we must delete nothing.
if start == end:
return
# If end is not specified, delete one char
if end is None:
end = start + 1
else:
# Tk says not to delete in this case, but our control would.
if end < start:
return
if start == self.edit.GetTextLength():
return # Nothing to delete.
old = self.edit.GetSel()[0] # Lose a selection
# Hack for partial '\r\n' and UTF-8 char removal
start, end = self._fix_indexes(start, end)
self.edit.SetSel((start, end))
self.edit.Clear()
if old >= start and old < end:
old = start
elif old >= end:
old = old - (end - start)
self.edit.SetSel(old)
def bell(self):
win32api.MessageBeep()
def see(self, pos):
# Most commands we use in Scintilla actually force the selection
# to be seen, making this unnecessary.
pass
def mark_set(self, name, pos):
try:
pos = self._getoffset(pos)
except EmptyRange:
raise TextError("Empty range '%s'" % pos)
if name == "insert":
self.edit.SetSel(pos)
else:
self.marks[name] = pos
def tag_add(self, name, start, end):
if name != "sel":
raise ValueError("Only sel tag is supported")
try:
start = self._getoffset(start)
end = self._getoffset(end)
except EmptyRange:
raise TextError("Empty range")
self.edit.SetSel(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")
# Turn the sel into a cursor
self.edit.SetSel(self.edit.GetSel()[0])
def compare(self, i1, op, i2):
try:
i1 = self._getoffset(i1)
except EmptyRange:
i1 = ""
try:
i2 = self._getoffset(i2)
except EmptyRange:
i2 = ""
return eval("%d%s%d" % (i1, op, i2))
def undo_block_start(self):
self.edit.SCIBeginUndoAction()
def undo_block_stop(self):
self.edit.SCIEndUndoAction()
class IDLEWrapper:
def __init__(self, control):
self.text = control
def IDLETest(extension):
import os
import sys
modname = "pywin.idle." + extension
__import__(modname)
mod = sys.modules[modname]
mod.TclError = TextError
klass = getattr(mod, extension)
# Create a new Scintilla Window.
import pywin.framework.editor
d = pywin.framework.editor.editorTemplate.OpenDocumentFile(None)
v = d.GetFirstView()
fname = os.path.splitext(__file__)[0] + ".py"
v.SCIAddText(open(fname).read())
d.SetModifiedFlag(0)
r = klass(IDLEWrapper(TkText(v)))
return r | null |
171,895 | import afxres
import win32api
import win32con
import win32ui
from pywin.framework import scriptutils
from pywin.mfc import dialog
def _ShowDialog(dlgClass):
global curDialog
if curDialog is not None:
if curDialog.__class__ != dlgClass:
curDialog.DestroyWindow()
curDialog = None
else:
curDialog.SetFocus()
if curDialog is None:
curDialog = dlgClass()
curDialog.CreateWindow()
class ReplaceDialog(FindReplaceDialog):
def _GetDialogTemplate(self):
style = (
win32con.DS_MODALFRAME
| win32con.WS_POPUP
| win32con.WS_VISIBLE
| win32con.WS_CAPTION
| win32con.WS_SYSMENU
| win32con.DS_SETFONT
)
visible = win32con.WS_CHILD | win32con.WS_VISIBLE
dt = [
["Replace", (0, 2, 240, 95), style, 0, (8, "MS Sans Serif")],
["Static", "Fi&nd What:", 101, (5, 8, 40, 10), visible],
[
"ComboBox",
"",
102,
(60, 7, 110, 120),
visible
| win32con.WS_BORDER
| win32con.WS_TABSTOP
| win32con.WS_VSCROLL
| win32con.CBS_DROPDOWN
| win32con.CBS_AUTOHSCROLL,
],
["Static", "Re&place with:", 103, (5, 25, 50, 10), visible],
[
"ComboBox",
"",
104,
(60, 24, 110, 120),
visible
| win32con.WS_BORDER
| win32con.WS_TABSTOP
| win32con.WS_VSCROLL
| win32con.CBS_DROPDOWN
| win32con.CBS_AUTOHSCROLL,
],
[
"Button",
"Match &whole word only",
105,
(5, 42, 100, 10),
visible | win32con.BS_AUTOCHECKBOX | win32con.WS_TABSTOP,
],
[
"Button",
"Match &case",
107,
(5, 52, 100, 10),
visible | win32con.BS_AUTOCHECKBOX | win32con.WS_TABSTOP,
],
[
"Button",
"Keep &dialog open",
115,
(5, 62, 100, 10),
visible | win32con.BS_AUTOCHECKBOX | win32con.WS_TABSTOP,
],
[
"Button",
"Across &open files",
116,
(5, 72, 100, 10),
visible | win32con.BS_AUTOCHECKBOX | win32con.WS_TABSTOP,
],
[
"Button",
"&Remember as default search",
117,
(5, 81, 150, 10),
visible | win32con.BS_AUTOCHECKBOX | win32con.WS_TABSTOP,
],
[
"Button",
"&Find Next",
109,
(185, 5, 50, 14),
visible | win32con.BS_DEFPUSHBUTTON | win32con.WS_TABSTOP,
],
[
"Button",
"&Replace",
110,
(185, 23, 50, 14),
visible | win32con.WS_TABSTOP,
],
[
"Button",
"Replace &All",
111,
(185, 41, 50, 14),
visible | win32con.WS_TABSTOP,
],
[
"Button",
"Cancel",
win32con.IDCANCEL,
(185, 59, 50, 14),
visible | win32con.WS_TABSTOP,
],
]
return dt
def OnInitDialog(self):
rc = FindReplaceDialog.OnInitDialog(self)
self.HookCommand(self.OnReplace, 110)
self.HookCommand(self.OnReplaceAll, 111)
self.HookMessage(self.OnActivate, win32con.WM_ACTIVATE)
self.editReplaceText = self.GetDlgItem(104)
self.editReplaceText.SetWindowText(lastSearch.replaceText)
if hasattr(self.editReplaceText, "SetEditSel"):
self.editReplaceText.SetEditSel(0, -1)
else:
self.editReplaceText.SetSel(0, -1)
self.butReplace = self.GetDlgItem(110)
self.butReplaceAll = self.GetDlgItem(111)
self.CheckButtonStates()
return rc # 0 when focus set
def CheckButtonStates(self):
# We can do a "Replace" or "Replace All" if the current selection
# is the same as the search text.
ft = self.editFindText.GetWindowText()
control = _GetControl()
# bCanReplace = len(ft)>0 and control.GetSelText() == ft
bCanReplace = control is not None and lastSearch.sel == control.GetSel()
self.butReplace.EnableWindow(bCanReplace)
# self.butReplaceAll.EnableWindow(bCanReplace)
def OnActivate(self, msg):
wparam = msg[2]
fActive = win32api.LOWORD(wparam)
if fActive != win32con.WA_INACTIVE:
self.CheckButtonStates()
def OnFindNext(self, id, code):
if code != 0:
return 1
self.DoFindNext()
self.CheckButtonStates()
def OnReplace(self, id, code):
if code != 0:
return 1
lastSearch.replaceText = self.editReplaceText.GetWindowText()
_ReplaceIt(None)
def OnReplaceAll(self, id, code):
if code != 0:
return 1
control = _GetControl(None)
if control is not None:
control.SetSel(0)
num = 0
if self.DoFindNext() == FOUND_NORMAL:
num = 1
lastSearch.replaceText = self.editReplaceText.GetWindowText()
while _ReplaceIt(control) == FOUND_NORMAL:
num = num + 1
win32ui.SetStatusText("Replaced %d occurrences" % num)
if num > 0 and not self.butKeepDialogOpen.GetCheck():
self.DestroyWindow()
def ShowReplaceDialog():
_ShowDialog(ReplaceDialog) | null |
171,896 | import afxres
import win32api
import win32con
import win32ui
from pywin.framework import scriptutils
from pywin.mfc import dialog
FOUND_NOTHING = 0
lastSearch = defaultSearch = SearchParams()
def FindNext():
params = SearchParams(lastSearch)
params.sel = (-1, -1)
if not params.findText:
ShowFindDialog()
else:
return _FindIt(None, params)
def _GetControl(control=None):
if control is None:
control = scriptutils.GetActiveEditControl()
return control
def _ReplaceIt(control):
control = _GetControl(control)
statusText = "Can not find '%s'." % lastSearch.findText
rc = FOUND_NOTHING
if control is not None and lastSearch.sel != (-1, -1):
control.ReplaceSel(lastSearch.replaceText)
rc = FindNext()
if rc != FOUND_NOTHING:
statusText = win32ui.LoadString(afxres.AFX_IDS_IDLEMESSAGE)
win32ui.SetStatusText(statusText)
return rc | null |
171,897 | import array
import os
import re
import string
import struct
import sys
import __main__
import afxres
import win32con
import win32ui
from pywin.mfc import dialog, docview
from . import IDLEenvironment
from . import bindings, control, keycodes, scintillacon
_event_commands = [
# File menu
"win32ui.ID_FILE_LOCATE",
"win32ui.ID_FILE_CHECK",
"afxres.ID_FILE_CLOSE",
"afxres.ID_FILE_NEW",
"afxres.ID_FILE_OPEN",
"afxres.ID_FILE_SAVE",
"afxres.ID_FILE_SAVE_AS",
"win32ui.ID_FILE_SAVE_ALL",
# Edit menu
"afxres.ID_EDIT_UNDO",
"afxres.ID_EDIT_REDO",
"afxres.ID_EDIT_CUT",
"afxres.ID_EDIT_COPY",
"afxres.ID_EDIT_PASTE",
"afxres.ID_EDIT_SELECT_ALL",
"afxres.ID_EDIT_FIND",
"afxres.ID_EDIT_REPEAT",
"afxres.ID_EDIT_REPLACE",
# View menu
"win32ui.ID_VIEW_WHITESPACE",
"win32ui.ID_VIEW_FIXED_FONT",
"win32ui.ID_VIEW_BROWSE",
"win32ui.ID_VIEW_INTERACTIVE",
# Window menu
"afxres.ID_WINDOW_ARRANGE",
"afxres.ID_WINDOW_CASCADE",
"afxres.ID_WINDOW_NEW",
"afxres.ID_WINDOW_SPLIT",
"afxres.ID_WINDOW_TILE_HORZ",
"afxres.ID_WINDOW_TILE_VERT",
# Others
"afxres.ID_APP_EXIT",
"afxres.ID_APP_ABOUT",
]
_extra_event_commands = [
("EditDelete", afxres.ID_EDIT_CLEAR),
("LocateModule", win32ui.ID_FILE_LOCATE),
("GotoLine", win32ui.ID_EDIT_GOTO_LINE),
("DbgBreakpointToggle", win32ui.IDC_DBG_ADD),
("DbgGo", win32ui.IDC_DBG_GO),
("DbgStepOver", win32ui.IDC_DBG_STEPOVER),
("DbgStep", win32ui.IDC_DBG_STEP),
("DbgStepOut", win32ui.IDC_DBG_STEPOUT),
("DbgBreakpointClearAll", win32ui.IDC_DBG_CLEAR),
("DbgClose", win32ui.IDC_DBG_CLOSE),
]
event_commands = []
del _event_commands
del _extra_event_commands
def _CreateEvents():
for name in _event_commands:
val = eval(name)
name_parts = name.split("_")[1:]
name_parts = [p.capitalize() for p in name_parts]
event = "".join(name_parts)
event_commands.append((event, val))
for name, id in _extra_event_commands:
event_commands.append((name, id)) | null |
171,898 | import array
import os
import re
import string
import struct
import sys
import __main__
import afxres
import win32con
import win32ui
from pywin.mfc import dialog, docview
from . import IDLEenvironment
from . import bindings, control, keycodes, scintillacon
def DoBraceMatch(control):
curPos = control.SCIGetCurrentPos()
charBefore = " "
if curPos:
charBefore = control.SCIGetCharAt(curPos - 1)
charAt = control.SCIGetCharAt(curPos)
braceAtPos = braceOpposite = -1
if charBefore in "[](){}":
braceAtPos = curPos - 1
if braceAtPos == -1:
if charAt in "[](){}":
braceAtPos = curPos
if braceAtPos != -1:
braceOpposite = control.SCIBraceMatch(braceAtPos, 0)
if braceAtPos != -1 and braceOpposite == -1:
control.SCIBraceBadHighlight(braceAtPos)
else:
# either clear them both or set them both.
control.SCIBraceHighlight(braceAtPos, braceOpposite) | null |
171,899 | import array
import os
import re
import string
import struct
import sys
import __main__
import afxres
import win32con
import win32ui
from pywin.mfc import dialog, docview
from . import IDLEenvironment
from . import bindings, control, keycodes, scintillacon
def _get_class_attributes(ob):
# Recurse into base classes looking for attributes
items = []
try:
items = items + dir(ob)
for i in ob.__bases__:
for item in _get_class_attributes(i):
if item not in items:
items.append(item)
except AttributeError:
pass
return items | null |
171,900 | import array
import os
import re
import string
import struct
import sys
import __main__
import afxres
import win32con
import win32ui
from pywin.mfc import dialog, docview
from . import IDLEenvironment
from . import bindings, control, keycodes, scintillacon
configManager = None
class ConfigManager:
def __init__(self, f):
self.filename = "unknown"
self.last_error = None
self.key_to_events = {}
b_close = False
if hasattr(f, "readline"):
fp = f
self.filename = "<config string>"
compiled_name = None
else:
try:
f = find_config_file(f)
src_stat = os.stat(f)
except os.error:
self.report_error("Config file '%s' not found" % f)
return
self.filename = f
self.basename = os.path.basename(f)
trace("Loading configuration", self.basename)
compiled_name = os.path.splitext(f)[0] + ".cfc"
try:
cf = open(compiled_name, "rb")
try:
ver = marshal.load(cf)
ok = compiled_config_version == ver
if ok:
kblayoutname = marshal.load(cf)
magic = marshal.load(cf)
size = marshal.load(cf)
mtime = marshal.load(cf)
if (
magic == importlib.util.MAGIC_NUMBER
and win32api.GetKeyboardLayoutName() == kblayoutname
and src_stat[stat.ST_MTIME] == mtime
and src_stat[stat.ST_SIZE] == size
):
self.cache = marshal.load(cf)
trace("Configuration loaded cached", compiled_name)
return # We are ready to roll!
finally:
cf.close()
except (os.error, IOError, EOFError):
pass
fp = open(f)
b_close = True
self.cache = {}
lineno = 1
line = fp.readline()
while line:
# Skip to the next section (maybe already there!)
section, subsection = get_section_header(line)
while line and section is None:
line = fp.readline()
if not line:
break
lineno = lineno + 1
section, subsection = get_section_header(line)
if not line:
break
if section == "keys":
line, lineno = self._load_keys(subsection, fp, lineno)
elif section == "extensions":
line, lineno = self._load_extensions(subsection, fp, lineno)
elif section == "idle extensions":
line, lineno = self._load_idle_extensions(subsection, fp, lineno)
elif section == "general":
line, lineno = self._load_general(subsection, fp, lineno)
else:
self.report_error(
"Unrecognised section header '%s:%s'" % (section, subsection)
)
line = fp.readline()
lineno = lineno + 1
if b_close:
fp.close()
# Check critical data.
if not self.cache.get("keys"):
self.report_error("No keyboard definitions were loaded")
if not self.last_error and compiled_name:
try:
cf = open(compiled_name, "wb")
marshal.dump(compiled_config_version, cf)
marshal.dump(win32api.GetKeyboardLayoutName(), cf)
marshal.dump(importlib.util.MAGIC_NUMBER, cf)
marshal.dump(src_stat[stat.ST_SIZE], cf)
marshal.dump(src_stat[stat.ST_MTIME], cf)
marshal.dump(self.cache, cf)
cf.close()
except (IOError, EOFError):
pass # Ignore errors - may be read only.
def configure(self, editor, subsections=None):
# Execute the extension code, and find any events.
# First, we "recursively" connect any we are based on.
if subsections is None:
subsections = []
subsections = [""] + subsections
general = self.get_data("general")
if general:
parents = general.get("based on", [])
for parent in parents:
trace("Configuration based on", parent, "- loading.")
parent = self.__class__(parent)
parent.configure(editor, subsections)
if parent.last_error:
self.report_error(parent.last_error)
bindings = editor.bindings
codeob = self.get_data("extension code")
if codeob is not None:
ns = {}
try:
exec(codeob, ns)
except:
traceback.print_exc()
self.report_error("Executing extension code failed")
ns = None
if ns:
num = 0
for name, func in list(ns.items()):
if type(func) == types.FunctionType and name[:1] != "_":
bindings.bind(name, func)
num = num + 1
trace("Configuration Extension code loaded", num, "events")
# Load the idle extensions
for subsection in subsections:
for ext in self.get_data("idle extensions", {}).get(subsection, []):
try:
editor.idle.IDLEExtension(ext)
trace("Loaded IDLE extension", ext)
except:
self.report_error("Can not load the IDLE extension '%s'" % ext)
# Now bind up the key-map (remembering a reverse map
subsection_keymap = self.get_data("keys")
num_bound = 0
for subsection in subsections:
keymap = subsection_keymap.get(subsection, {})
bindings.update_keymap(keymap)
num_bound = num_bound + len(keymap)
trace("Configuration bound", num_bound, "keys")
def get_key_binding(self, event, subsections=None):
if subsections is None:
subsections = []
subsections = [""] + subsections
subsection_keymap = self.get_data("keys")
for subsection in subsections:
map = self.key_to_events.get(subsection)
if map is None: # Build it
map = {}
keymap = subsection_keymap.get(subsection, {})
for key_info, map_event in list(keymap.items()):
map[map_event] = key_info
self.key_to_events[subsection] = map
info = map.get(event)
if info is not None:
return keycodes.make_key_name(info[0], info[1])
return None
def report_error(self, msg):
self.last_error = msg
print("Error in %s: %s" % (self.filename, msg))
def report_warning(self, msg):
print("Warning in %s: %s" % (self.filename, msg))
def _readline(self, fp, lineno, bStripComments=1):
line = fp.readline()
lineno = lineno + 1
if line:
bBreak = (
get_section_header(line)[0] is not None
) # A new section is starting
if bStripComments and not bBreak:
pos = line.find("#")
if pos >= 0:
line = line[:pos] + "\n"
else:
bBreak = 1
return line, lineno, bBreak
def get_data(self, name, default=None):
return self.cache.get(name, default)
def _save_data(self, name, data):
self.cache[name] = data
return data
def _load_general(self, sub_section, fp, lineno):
map = {}
while 1:
line, lineno, bBreak = self._readline(fp, lineno)
if bBreak:
break
key, val = split_line(line, lineno)
if not key:
continue
key = key.lower()
l = map.get(key, [])
l.append(val)
map[key] = l
self._save_data("general", map)
return line, lineno
def _load_keys(self, sub_section, fp, lineno):
# Builds a nested dictionary of
# (scancode, flags) = event_name
main_map = self.get_data("keys", {})
map = main_map.get(sub_section, {})
while 1:
line, lineno, bBreak = self._readline(fp, lineno)
if bBreak:
break
key, event = split_line(line, lineno)
if not event:
continue
sc, flag = keycodes.parse_key_name(key)
if sc is None:
self.report_warning("Line %d: Invalid key name '%s'" % (lineno, key))
else:
map[sc, flag] = event
main_map[sub_section] = map
self._save_data("keys", main_map)
return line, lineno
def _load_extensions(self, sub_section, fp, lineno):
start_lineno = lineno
lines = []
while 1:
line, lineno, bBreak = self._readline(fp, lineno, 0)
if bBreak:
break
lines.append(line)
try:
c = compile(
"\n" * start_lineno + "".join(lines), # produces correct tracebacks
self.filename,
"exec",
)
self._save_data("extension code", c)
except SyntaxError as details:
errlineno = details.lineno + start_lineno
# Should handle syntax errors better here, and offset the lineno.
self.report_error(
"Compiling extension code failed:\r\nFile: %s\r\nLine %d\r\n%s"
% (details.filename, errlineno, details.msg)
)
return line, lineno
def _load_idle_extensions(self, sub_section, fp, lineno):
extension_map = self.get_data("idle extensions")
if extension_map is None:
extension_map = {}
extensions = []
while 1:
line, lineno, bBreak = self._readline(fp, lineno)
if bBreak:
break
line = line.strip()
if line:
extensions.append(line)
extension_map[sub_section] = extensions
self._save_data("idle extensions", extension_map)
return line, lineno
def LoadConfiguration():
global configManager
# Bit of a hack I dont kow what to do about?
from .config import ConfigManager
configName = rc = win32ui.GetProfileVal("Editor", "Keyboard Config", "default")
configManager = ConfigManager(configName)
if configManager.last_error:
bTryDefault = 0
msg = "Error loading configuration '%s'\n\n%s" % (
configName,
configManager.last_error,
)
if configName != "default":
msg = msg + "\n\nThe default configuration will be loaded."
bTryDefault = 1
win32ui.MessageBox(msg)
if bTryDefault:
configManager = ConfigManager("default")
if configManager.last_error:
win32ui.MessageBox(
"Error loading configuration 'default'\n\n%s"
% (configManager.last_error)
) | null |
171,901 | import glob
import importlib.util
import marshal
import os
import stat
import sys
import traceback
import types
import pywin
import win32api
from . import keycodes
def trace(*args):
sys.stderr.write(" ".join(map(str, args)) + "\n") | null |
171,902 | import glob
import importlib.util
import marshal
import os
import stat
import sys
import traceback
import types
import pywin
import win32api
from . import keycodes
def split_line(line, lineno):
comment_pos = line.find("#")
if comment_pos >= 0:
line = line[:comment_pos]
sep_pos = line.rfind("=")
if sep_pos == -1:
if line.strip():
print("Warning: Line %d: %s is an invalid entry" % (lineno, repr(line)))
return None, None
return "", ""
return line[:sep_pos].strip(), line[sep_pos + 1 :].strip() | null |
171,903 | import glob
import importlib.util
import marshal
import os
import stat
import sys
import traceback
import types
import pywin
import win32api
from . import keycodes
def get_section_header(line):
# Returns the section if the line is a section header, else None
if line[0] == "[":
end = line.find("]")
if end == -1:
end = len(line)
rc = line[1:end].lower()
try:
i = rc.index(":")
return rc[:i], rc[i + 1 :]
except ValueError:
return rc, ""
return None, None | null |
171,904 | import glob
import importlib.util
import marshal
import os
import stat
import sys
import traceback
import types
import pywin
import win32api
from . import keycodes
def find_config_file(f):
return os.path.join(pywin.__path__[0], f + ".cfg") | null |
171,905 | import glob
import importlib.util
import marshal
import os
import stat
import sys
import traceback
import types
import pywin
import win32api
from . import keycodes
def find_config_files():
return [
os.path.split(x)[1]
for x in [
os.path.splitext(x)[0]
for x in glob.glob(os.path.join(pywin.__path__[0], "*.cfg"))
]
] | null |
171,906 | import traceback
import win32api
import win32con
import win32ui
from . import IDLEenvironment, keycodes
next_id = 5000
event_to_commands = {}
command_to_events = {}
def assign_command_id(event, id=0):
global next_id
if id == 0:
id = event_to_commands.get(event, 0)
if id == 0:
id = next_id
next_id = 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
return id | null |
171,907 | import win32api
import win32con
import win32ui
key_name_to_vk = {}
key_code_to_name = {}
_better_names = {
"escape": "esc",
"return": "enter",
"back": "pgup",
"next": "pgdn",
}
def _fillvkmap():
# Pull the VK_names from win32con
names = [entry for entry in win32con.__dict__ if entry.startswith("VK_")]
for name in names:
code = getattr(win32con, name)
n = name[3:].lower()
key_name_to_vk[n] = code
if n in _better_names:
n = _better_names[n]
key_name_to_vk[n] = code
key_code_to_name[code] = n | null |
171,908 | import win32api
import win32con
import win32ui
def _psc(char):
def test1():
for ch in """aA0/?[{}];:'"`~_-+=\\|,<.>/?""":
_psc(ch)
for code in ["Home", "End", "Left", "Right", "Up", "Down", "Menu", "Next"]:
_psc(code) | null |
171,909 | import win32api
import win32con
import win32ui
def _pkn(n):
vk, flags = parse_key_name(n)
print("%s -> %s,%s -> %s" % (n, vk, flags, make_key_name(vk, flags)))
def test2():
_pkn("ctrl+alt-shift+x")
_pkn("ctrl-home")
_pkn("Shift-+")
_pkn("Shift--")
_pkn("Shift+-")
_pkn("Shift++")
_pkn("LShift-+")
_pkn("ctl+home")
_pkn("ctl+enter")
_pkn("alt+return")
_pkn("Alt+/")
_pkn("Alt+BadKeyName")
_pkn("A") # an ascii char - should be seen as 'a'
_pkn("a")
_pkn("Shift-A")
_pkn("Shift-a")
_pkn("a")
_pkn("(")
_pkn("Ctrl+(")
_pkn("Ctrl+Shift-8")
_pkn("Ctrl+*")
_pkn("{")
_pkn("!")
_pkn(".") | null |
171,910 |
def HandleToUlong(h):
return HandleToULong(h) | null |
171,911 |
def UlongToHandle(ul):
return ULongToHandle(ul) | null |
171,912 |
def UlongToPtr(ul):
return ULongToPtr(ul) | null |
171,913 |
def UintToPtr(ui):
return UIntToPtr(ui) | null |
171,914 | import array
import string
import win32api
import win32con
import win32ui
from . import scintillacon
from win32con import CLR_INVALID
from keyword import iskeyword, kwlist
def trace(*args):
win32trace.write(" ".join(map(str, args)) + "\n") | null |
171,915 | import _thread
import sys
import traceback
import win32api
from pywin.framework import winout
def Test():
num = 1
while num < 1000:
print("Hello there no " + str(num))
win32api.Sleep(50)
num = num + 1 | null |
171,916 | import _thread
import sys
import traceback
import win32api
from pywin.framework import winout
class flags:
def ServerThread(myout, cmd, title, bCloseOnEnd):
def StartServer(cmd, title=None, bCloseOnEnd=0, serverFlags=flags.SERVER_BEST):
out = winout.WindowOutput(title, None, winout.flags.WQ_IDLE)
if not title:
title = cmd
out.Create(title)
# ServerThread((out, cmd, title, bCloseOnEnd))
# out = sys.stdout
_thread.start_new_thread(ServerThread, (out, cmd, title, bCloseOnEnd)) | null |
171,917 | import commctrl
import fontdemo
import win32ui
from pywin.mfc import docview, window
class SampleTemplate(docview.DocTemplate):
def __init__(self):
docview.DocTemplate.__init__(
self, win32ui.IDR_PYTHONTYPE, None, SplitterFrame, None
)
def InitialUpdateFrame(self, frame, doc, makeVisible):
# print "frame is ", frame, frame._obj_
# print "doc is ", doc, doc._obj_
self._obj_.InitialUpdateFrame(frame, doc, makeVisible) # call default handler.
frame.InitialUpdateFrame(doc, makeVisible)
def demo():
template = SampleTemplate()
doc = template.OpenDocumentFile(None)
doc.SetTitle("Splitter Demo") | null |
171,918 | import win32con
import win32ui
from pywin.mfc import dialog
class MyDialog(dialog.Dialog):
"""
Example using simple controls
"""
_dialogstyle = (
win32con.WS_MINIMIZEBOX
| win32con.WS_DLGFRAME
| win32con.DS_MODALFRAME
| win32con.WS_POPUP
| win32con.WS_VISIBLE
| win32con.WS_CAPTION
| win32con.WS_SYSMENU
| win32con.DS_SETFONT
)
_buttonstyle = (
win32con.BS_PUSHBUTTON
| win32con.WS_TABSTOP
| win32con.WS_CHILD
| win32con.WS_VISIBLE
)
### The static template, contains all "normal" dialog items
DIALOGTEMPLATE = [
# the dialog itself is the first element in the template
["Example slider", (0, 0, 50, 43), _dialogstyle, None, (8, "MS SansSerif")],
# rest of elements are the controls within the dialog
# standard "Close" button
[128, "Close", win32con.IDCANCEL, (0, 30, 50, 13), _buttonstyle],
]
### ID of the control to be created during dialog initialisation
IDC_SLIDER = 9500
def __init__(self):
dialog.Dialog.__init__(self, self.DIALOGTEMPLATE)
def OnInitDialog(self):
rc = dialog.Dialog.OnInitDialog(self)
# now initialise your controls that you want to create
# programmatically, including those which are OLE controls
# those created directly by win32ui.Create*
# and your "custom controls" which are subclasses/whatever
win32ui.EnableControlContainer()
self.slider = win32ui.CreateSliderCtrl()
self.slider.CreateWindow(
win32con.WS_TABSTOP | win32con.WS_VISIBLE,
(0, 0, 100, 30),
self._obj_,
self.IDC_SLIDER,
)
self.HookMessage(self.OnSliderMove, win32con.WM_HSCROLL)
return rc
def OnSliderMove(self, params):
print("Slider moved")
def OnCancel(self):
print("The slider control is at position", self.slider.GetPos())
self._obj_.OnCancel()
def demo():
dia = MyDialog()
dia.DoModal() | null |
171,919 | import win32api
import win32con
import win32ui
from pywin.mfc import dialog, window
def MakeDlgTemplate():
class TestPieDialog(dialog.Dialog):
def OnInitDialog(self):
def demo(modal=0):
d = TestPieDialog(MakeDlgTemplate())
if modal:
d.DoModal()
else:
d.CreateWindow() | null |
171,920 | import win32ui
from pywin.mfc import docview
class object_template(docview.DocTemplate):
def __init__(self):
def OpenObject(self, object):
def demo():
t = object_template()
d = t.OpenObject(win32ui)
return (t, d) | null |
171,921 | import sys
import __main__
import regutil
import win32api
import win32ui
demos = [ # ('Font', 'import fontdemo;fontdemo.FontDemo()'),
("Open GL Demo", "import openGLDemo;openGLDemo.test()"),
("Threaded GUI", "import threadedgui;threadedgui.ThreadedDemo()"),
("Tree View Demo", "import hiertest;hiertest.demoboth()"),
("3-Way Splitter Window", "import splittst;splittst.demo()"),
("Custom Toolbars and Tooltips", "import toolbar;toolbar.test()"),
("Progress Bar", "import progressbar;progressbar.demo()"),
("Slider Control", "import sliderdemo;sliderdemo.demo()"),
("Dynamic window creation", "import createwin;createwin.demo()"),
("Various Dialog demos", "import dlgtest;dlgtest.demo()"),
("OCX Control Demo", "from ocx import ocxtest;ocxtest.demo()"),
("OCX Serial Port Demo", "from ocx import ocxserialtest; ocxserialtest.test()"),
(
"IE4 Control Demo",
'from ocx import webbrowser; webbrowser.Demo("http://www.python.org")',
),
]
def demo():
try:
# seeif I can locate the demo files.
import fontdemo
except ImportError:
# else put the demos direectory on the path (if not already)
try:
instPath = regutil.GetRegistryDefaultValue(
regutil.BuildDefaultPythonKey() + "\\InstallPath"
)
except win32api.error:
print(
"The InstallPath can not be located, and the Demos directory is not on the path"
)
instPath = "."
demosDir = win32ui.FullPath(instPath + "\\Demos")
for path in sys.path:
if win32ui.FullPath(path) == demosDir:
break
else:
sys.path.append(demosDir)
import fontdemo
import sys
if "/go" in sys.argv:
for name, cmd in demos:
try:
exec(cmd)
except:
print(
"Demo of %s failed - %s:%s"
% (cmd, sys.exc_info()[0], sys.exc_info()[1])
)
return
# Otherwise allow the user to select the demo to run
import pywin.dialogs.list
while 1:
rc = pywin.dialogs.list.SelectFromLists("Select a Demo", demos, ["Demo Title"])
if rc is None:
break
title, cmd = demos[rc]
try:
exec(cmd)
except:
print(
"Demo of %s failed - %s:%s"
% (title, sys.exc_info()[0], sys.exc_info()[1])
) | null |
171,922 | import sys
import win32api
import win32con
import win32ui
NotScriptMsg = """\
This demo program is not designed to be run as a Script, but is
probably used by some other test program. Please try another demo.
"""
from pywin.framework.app import HaveGoodGUI
def NotAScript():
import win32ui
win32ui.MessageBox(NotScriptMsg, "Demos") | null |
171,923 | import sys
import win32api
import win32con
import win32ui
NeedGUIMsg = """\
This demo program can only be run from inside of Pythonwin
You must start Pythonwin, and select 'Run' from the toolbar or File menu
"""
from pywin.framework.app import HaveGoodGUI
def HaveGoodGUI():
"""Returns true if we currently have a good gui available."""
return "pywin.framework.startup" in sys.modules
def NeedGoodGUI():
from pywin.framework.app import HaveGoodGUI
rc = HaveGoodGUI()
if not rc:
win32ui.MessageBox(NeedGUIMsg, "Demos")
return rc | null |
171,924 | import sys
import win32api
import win32con
import win32ui
NeedAppMsg = """\
This demo program is a 'Pythonwin Application'.
It is more demo code than an example of Pythonwin's capabilities.
To run it, you must execute the command:
pythonwin.exe /app "%s"
Would you like to execute it now?
"""
from pywin.framework.app import HaveGoodGUI
def NeedApp():
import win32ui
rc = win32ui.MessageBox(NeedAppMsg % sys.argv[0], "Demos", win32con.MB_YESNO)
if rc == win32con.IDYES:
try:
parent = win32ui.GetMainFrame().GetSafeHwnd()
win32api.ShellExecute(
parent, None, "pythonwin.exe", '/app "%s"' % sys.argv[0], None, 1
)
except win32api.error as details:
win32ui.MessageBox("Error executing command - %s" % (details), "Demos") | null |
171,925 | import timer
import win32api
import win32con
import win32ui
from pywin.mfc import docview, thread, window
from pywin.mfc.thread import WinThread
class FontFrame(window.MDIChildWnd):
def __init__(self):
pass # Dont call base class doc/view version...
def Create(self, title, rect=None, parent=None):
style = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.WS_OVERLAPPEDWINDOW
self._obj_ = win32ui.CreateMDIChild()
self._obj_.AttachObject(self)
self._obj_.CreateWindow(None, title, style, rect, parent)
rect = self.GetClientRect()
rect = (0, 0, rect[2] - rect[0], rect[3] - rect[1])
self.child = FontWindow("Not threaded")
self.child.Create(
"FontDemo", win32con.WS_CHILD | win32con.WS_VISIBLE, rect, self
)
def Demo():
f = FontFrame()
f.Create("Font Demo") | null |
171,926 | import timer
import win32api
import win32con
import win32ui
from pywin.mfc import docview, thread, window
from pywin.mfc.thread import WinThread
class FontFrame(window.MDIChildWnd):
def __init__(self):
def Create(self, title, rect=None, parent=None):
class ThreadedFontFrame(window.MDIChildWnd):
def __init__(self):
def Create(self, title, rect=None, parent=None):
def OnSize(self, msg):
def OnDestroy(self, msg):
def ThreadedDemo():
rect = win32ui.GetMainFrame().GetMDIClient().GetClientRect()
rect = rect[0], int(rect[3] * 3 / 4), int(rect[2] / 4), rect[3]
incr = rect[2]
for i in range(4):
if i == 0:
f = FontFrame()
title = "Not threaded"
else:
f = ThreadedFontFrame()
title = "Threaded GUI Demo"
f.Create(title, rect)
rect = rect[0] + incr, rect[1], rect[2] + incr, rect[3]
# Givem a chance to start
win32api.Sleep(100)
win32ui.PumpWaitingMessages() | null |
171,927 | import sys
import time
import timer
import win32api
import win32con
import win32ui
from pywin.framework import app, cmdline, dlgappcore
def DoDemoWork():
print("Doing the work...")
print("About to connect")
win32api.MessageBeep(win32con.MB_ICONASTERISK)
win32api.Sleep(2000)
print("Doing something else...")
win32api.MessageBeep(win32con.MB_ICONEXCLAMATION)
win32api.Sleep(2000)
print("More work.")
win32api.MessageBeep(win32con.MB_ICONHAND)
win32api.Sleep(2000)
print("The last bit.")
win32api.MessageBeep(win32con.MB_OK)
win32api.Sleep(2000) | null |
171,928 | import sys
import time
import timer
import win32api
import win32con
import win32ui
from pywin.framework import app, cmdline, dlgappcore
class TimerAppDialog(dlgappcore.AppDialog):
softspace = 1
def __init__(self, appName=""):
dlgappcore.AppDialog.__init__(self, win32ui.IDD_GENERAL_STATUS)
self.timerAppName = appName
self.argOff = 0
if len(self.timerAppName) == 0:
if len(sys.argv) > 1 and sys.argv[1][0] != "/":
self.timerAppName = sys.argv[1]
self.argOff = 1
def PreDoModal(self):
# sys.stderr = sys.stdout
pass
def ProcessArgs(self, args):
for arg in args:
if arg == "/now":
self.OnOK()
def OnInitDialog(self):
win32ui.SetProfileFileName("pytimer.ini")
self.title = win32ui.GetProfileVal(
self.timerAppName, "Title", "Remote System Timer"
)
self.buildTimer = win32ui.GetProfileVal(
self.timerAppName, "Timer", "EachMinuteIntervaler()"
)
self.doWork = win32ui.GetProfileVal(self.timerAppName, "Work", "DoDemoWork()")
# replace "\n" with real \n.
self.doWork = self.doWork.replace("\\n", "\n")
dlgappcore.AppDialog.OnInitDialog(self)
self.SetWindowText(self.title)
self.prompt1 = self.GetDlgItem(win32ui.IDC_PROMPT1)
self.prompt2 = self.GetDlgItem(win32ui.IDC_PROMPT2)
self.prompt3 = self.GetDlgItem(win32ui.IDC_PROMPT3)
self.butOK = self.GetDlgItem(win32con.IDOK)
self.butCancel = self.GetDlgItem(win32con.IDCANCEL)
self.prompt1.SetWindowText("Python Timer App")
self.prompt2.SetWindowText("")
self.prompt3.SetWindowText("")
self.butOK.SetWindowText("Do it now")
self.butCancel.SetWindowText("Close")
self.timerManager = TimerManager(self)
self.ProcessArgs(sys.argv[self.argOff :])
self.timerManager.go()
return 1
def OnDestroy(self, msg):
dlgappcore.AppDialog.OnDestroy(self, msg)
self.timerManager.stop()
def OnOK(self):
# stop the timer, then restart after setting special boolean
self.timerManager.stop()
self.timerManager.bConnectNow = 1
self.timerManager.go()
return
def t():
t = TimerAppDialog("Test Dialog")
t.DoModal()
return t | null |
171,929 | import sys
import win32api
import win32con
import win32ui
NotScriptMsg = """\
This demo program is not designed to be run as a Script, but is
probably used by some other test program. Please try another demo.
"""
def NotAScript():
import win32ui
win32ui.MessageBox(NotScriptMsg, "Demos") | null |
171,930 | import sys
import win32api
import win32con
import win32ui
NeedGUIMsg = """\
This demo program can only be run from inside of Pythonwin
You must start Pythonwin, and select 'Run' from the toolbar or File menu
"""
def HaveGoodGUI():
"""Returns true if we currently have a good gui available."""
return "pywin.framework.startup" in sys.modules
def NeedGoodGUI():
from pywin.framework.app import HaveGoodGUI
rc = HaveGoodGUI()
if not rc:
win32ui.MessageBox(NeedGUIMsg, "Demos")
return rc | null |
171,931 | import sys
import win32api
import win32con
import win32ui
NeedAppMsg = """\
This demo program is a 'Pythonwin Application'.
It is more demo code than an example of Pythonwin's capabilities.
To run it, you must execute the command:
pythonwin.exe /app "%s"
Would you like to execute it now?
"""
import sys
if sys.version_info >= (3, 8):
iscoroutinefunction = inspect.iscoroutinefunction
else:
def iscoroutinefunction(func: t.Any) -> bool:
def NeedApp():
import win32ui
rc = win32ui.MessageBox(NeedAppMsg % sys.argv[0], "Demos", win32con.MB_YESNO)
if rc == win32con.IDYES:
try:
parent = win32ui.GetMainFrame().GetSafeHwnd()
win32api.ShellExecute(
parent, None, "pythonwin.exe", '/app "%s"' % sys.argv[0], None, 1
)
except win32api.error as details:
win32ui.MessageBox("Error executing command - %s" % (details), "Demos") | null |
171,932 | import win32api
import win32con
import win32ui
from pywin.framework import app, dlgappcore
class DoJobAppDialog(dlgappcore.AppDialog):
softspace = 1
def __init__(self, appName=""):
self.appName = appName
dlgappcore.AppDialog.__init__(self, win32ui.IDD_GENERAL_STATUS)
def PreDoModal(self):
pass
def ProcessArgs(self, args):
pass
def OnInitDialog(self):
self.SetWindowText(self.appName)
butCancel = self.GetDlgItem(win32con.IDCANCEL)
butCancel.ShowWindow(win32con.SW_HIDE)
p1 = self.GetDlgItem(win32ui.IDC_PROMPT1)
p2 = self.GetDlgItem(win32ui.IDC_PROMPT2)
# Do something here!
p1.SetWindowText("Hello there")
p2.SetWindowText("from the demo")
def OnDestroy(self, msg):
pass
def t():
t = DoJobAppDialog("Copy To")
t.DoModal()
return t | null |
171,933 | import sys
from pywin.mfc import docview
import timer
import win32api
import win32con
import win32ui
threeto8 = [0, 73 >> 1, 146 >> 1, 219 >> 1, 292 >> 1, 365 >> 1, 438 >> 1, 255]
twoto8 = [0, 0x55, 0xAA, 0xFF]
oneto8 = [0, 255]
def ComponentFromIndex(i, nbits, shift):
# val = (unsigned char) (i >> shift);
val = (i >> shift) & 0xF
if nbits == 1:
val = val & 0x1
return oneto8[val]
elif nbits == 2:
val = val & 0x3
return twoto8[val]
elif nbits == 3:
val = val & 0x7
return threeto8[val]
else:
return 0 | null |
171,934 | import sys
import regutil
import win32api
import win32con
import win32ui
from pywin.mfc import activex, window
from win32com.client import gencache
class BrowserFrame(window.MDIChildWnd):
def __init__(self, url=None):
if url is None:
self.url = regutil.GetRegisteredHelpFile("Main Python Documentation")
if self.url is None:
self.url = "http://www.python.org"
else:
self.url = url
pass # Dont call base class doc/view version...
def Create(self, title, rect=None, parent=None):
style = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.WS_OVERLAPPEDWINDOW
self._obj_ = win32ui.CreateMDIChild()
self._obj_.AttachObject(self)
self._obj_.CreateWindow(None, title, style, rect, parent)
rect = self.GetClientRect()
rect = (0, 0, rect[2] - rect[0], rect[3] - rect[1])
self.ocx = MyWebBrowser()
self.ocx.CreateControl(
"Web Browser", win32con.WS_VISIBLE | win32con.WS_CHILD, rect, self, 1000
)
self.ocx.Navigate(self.url)
self.HookMessage(self.OnSize, win32con.WM_SIZE)
def OnSize(self, params):
rect = self.GetClientRect()
rect = (0, 0, rect[2] - rect[0], rect[3] - rect[1])
self.ocx.SetWindowPos(0, rect, 0)
def OnNavigate(self, url):
title = "Web Browser - %s" % (url,)
self.SetWindowText(title)
def Demo(url=None):
if url is None and len(sys.argv) > 1:
url = win32api.GetFullPathName(sys.argv[1])
f = BrowserFrame(url)
f.Create("Web Browser") | null |
171,935 | import sys
import regutil
import win32api
import win32con
import win32ui
from pywin.mfc import activex, window
from win32com.client import gencache
class BrowserFrame(window.MDIChildWnd):
def __init__(self, url=None):
if url is None:
self.url = regutil.GetRegisteredHelpFile("Main Python Documentation")
else:
self.url = url
pass # Dont call base class doc/view version...
def Create(self, title, rect=None, parent=None):
style = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.WS_OVERLAPPEDWINDOW
self._obj_ = win32ui.CreateMDIChild()
self._obj_.AttachObject(self)
self._obj_.CreateWindow(None, title, style, rect, parent)
rect = self.GetClientRect()
rect = (0, 0, rect[2] - rect[0], rect[3] - rect[1])
self.ocx = MyFlashComponent()
self.ocx.CreateControl(
"Flash Player", win32con.WS_VISIBLE | win32con.WS_CHILD, rect, self, 1000
)
self.ocx.LoadMovie(0, flash_url)
self.ocx.Play()
self.HookMessage(self.OnSize, win32con.WM_SIZE)
def OnSize(self, params):
rect = self.GetClientRect()
rect = (0, 0, rect[2] - rect[0], rect[3] - rect[1])
self.ocx.SetWindowPos(0, rect, 0)
def Demo():
url = None
if len(sys.argv) > 1:
url = win32api.GetFullPathName(sys.argv[1])
f = BrowserFrame(url)
f.Create("Flash Player") | null |
171,937 | import sys
import win32api
import win32con
import win32ui
NeedGUIMsg = """\
This demo program can only be run from inside of Pythonwin
You must start Pythonwin, and select 'Run' from the toolbar or File menu
"""
from pywin.framework.app import HaveGoodGUI
def HaveGoodGUI():
def NeedGoodGUI():
from pywin.framework.app import HaveGoodGUI
rc = HaveGoodGUI()
if not rc:
win32ui.MessageBox(NeedGUIMsg, "Demos")
return rc | null |
171,939 | import regutil
import win32con
import win32ui
import win32uiole
from pywin.mfc import activex, docview, object, window
from win32com.client import gencache
class OleTemplate(docview.DocTemplate):
def __init__(
self, resourceId=None, MakeDocument=None, MakeFrame=None, MakeView=None
):
if MakeDocument is None:
MakeDocument = OleDocument
if MakeView is None:
MakeView = ExcelView
docview.DocTemplate.__init__(
self, resourceId, MakeDocument, MakeFrame, MakeView
)
def Demo():
import sys
import win32api
docName = None
if len(sys.argv) > 1:
docName = win32api.GetFullPathName(sys.argv[1])
OleTemplate().OpenDocumentFile(None) | null |
171,940 | import win32api
import win32con
import win32ui
from pywin.mfc import docview
class FontView(docview.ScrollView):
def __init__(
self, doc, text="Python Rules!", font_spec={"name": "Arial", "height": 42}
):
docview.ScrollView.__init__(self, doc)
self.font = win32ui.CreateFont(font_spec)
self.text = text
self.width = self.height = 0
# set up message handlers
self.HookMessage(self.OnSize, win32con.WM_SIZE)
def OnAttachedObjectDeath(self):
docview.ScrollView.OnAttachedObjectDeath(self)
del self.font
def SetFont(self, new_font):
# Change font on the fly
self.font = win32ui.CreateFont(new_font)
# redraw the entire client window
selfInvalidateRect(None)
def OnSize(self, params):
lParam = params[3]
self.width = win32api.LOWORD(lParam)
self.height = win32api.HIWORD(lParam)
def OnPrepareDC(self, dc, printinfo):
# Set up the DC for forthcoming OnDraw call
self.SetScrollSizes(win32con.MM_TEXT, (100, 100))
dc.SetTextColor(win32api.RGB(0, 0, 255))
dc.SetBkColor(win32api.GetSysColor(win32con.COLOR_WINDOW))
dc.SelectObject(self.font)
dc.SetTextAlign(win32con.TA_CENTER | win32con.TA_BASELINE)
def OnDraw(self, dc):
if self.width == 0 and self.height == 0:
left, top, right, bottom = self.GetClientRect()
self.width = right - left
self.height = bottom - top
x, y = self.width // 2, self.height // 2
dc.TextOut(x, y, self.text)
def FontDemo():
# create doc/view
template = docview.DocTemplate(win32ui.IDR_PYTHONTYPE, None, None, FontView)
doc = template.OpenDocumentFile(None)
doc.SetTitle("Font Demo")
# print "template is ", template, "obj is", template._obj_
template.close() | null |
171,941 | import win32con
import win32ui
from pywin.mfc import dialog
def MakeDlgTemplate():
style = (
win32con.DS_MODALFRAME
| win32con.WS_POPUP
| win32con.WS_VISIBLE
| win32con.WS_CAPTION
| win32con.WS_SYSMENU
| win32con.DS_SETFONT
)
cs = win32con.WS_CHILD | win32con.WS_VISIBLE
w = 215
h = 36
dlg = [
[
"Progress bar control example",
(0, 0, w, h),
style,
None,
(8, "MS Sans Serif"),
],
]
s = win32con.WS_TABSTOP | cs
dlg.append(
[
128,
"Tick",
win32con.IDOK,
(10, h - 18, 50, 14),
s | win32con.BS_DEFPUSHBUTTON,
]
)
dlg.append(
[
128,
"Cancel",
win32con.IDCANCEL,
(w - 60, h - 18, 50, 14),
s | win32con.BS_PUSHBUTTON,
]
)
return dlg
class TestDialog(dialog.Dialog):
def OnInitDialog(self):
rc = dialog.Dialog.OnInitDialog(self)
self.pbar = win32ui.CreateProgressCtrl()
self.pbar.CreateWindow(
win32con.WS_CHILD | win32con.WS_VISIBLE, (10, 10, 310, 24), self, 1001
)
# self.pbar.SetStep (5)
self.progress = 0
self.pincr = 5
return rc
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
if self.progress > 100:
self.progress = 100
if self.progress <= 100:
self.pbar.SetPos(self.progress)
def demo(modal=0):
d = TestDialog(MakeDlgTemplate())
if modal:
d.DoModal()
else:
d.CreateWindow() | null |
171,942 | import win32con
import win32ui
from pywin.mfc import dialog, window
def test1():
win32ui.CreateDialogIndirect(MakeDlgTemplate()).DoModal()
def test2():
dialog.Dialog(MakeDlgTemplate()).DoModal()
def test3():
dlg = win32ui.LoadDialogResource(win32ui.IDD_SET_TABSTOPS)
dlg[0][0] = "New Dialog Title"
dlg[0][1] = (80, 20, 161, 60)
dlg[1][1] = "&Confusion:"
cs = (
win32con.WS_CHILD
| win32con.WS_VISIBLE
| win32con.WS_TABSTOP
| win32con.BS_PUSHBUTTON
)
dlg.append([128, "&Help", 100, (111, 41, 40, 14), cs])
dialog.Dialog(dlg).DoModal()
def test4():
page1 = dialog.PropertyPage(win32ui.LoadDialogResource(win32ui.IDD_PROPDEMO1))
page2 = dialog.PropertyPage(win32ui.LoadDialogResource(win32ui.IDD_PROPDEMO2))
ps = dialog.PropertySheet("Property Sheet/Page Demo", None, [page1, page2])
ps.DoModal()
def testall():
test1()
test2()
test3()
test4() | null |
171,944 | import win32con
import win32ui
from pywin.mfc import window
The provided code snippet includes necessary dependencies for implementing the `dllFromDll` function. Write a Python function `def dllFromDll(dllid)` to solve the following problem:
given a 'dll' (maybe a dll, filename, etc), return a DLL object
Here is the function:
def dllFromDll(dllid):
"given a 'dll' (maybe a dll, filename, etc), return a DLL object"
if dllid == None:
return None
elif type("") == type(dllid):
return win32ui.LoadLibrary(dllid)
else:
try:
dllid.GetFileName()
except AttributeError:
raise TypeError("DLL parameter must be None, a filename or a dll object")
return dllid | given a 'dll' (maybe a dll, filename, etc), return a DLL object |
171,945 | import win32ui
import win32uiole
from . import window
def MakeControlClass(controlClass, name=None):
"""Given a CoClass in a generated .py file, this function will return a Class
object which can be used as an OCX control.
This function is used when you do not want to handle any events from the OCX
control. If you need events, then you should derive a class from both the
activex.Control class and the CoClass
"""
if name is None:
name = controlClass.__name__
return new_type("OCX" + name, (Control, controlClass), {})
The provided code snippet includes necessary dependencies for implementing the `MakeControlInstance` function. Write a Python function `def MakeControlInstance(controlClass, name=None)` to solve the following problem:
As for MakeControlClass(), but returns an instance of the class.
Here is the function:
def MakeControlInstance(controlClass, name=None):
"""As for MakeControlClass(), but returns an instance of the class."""
return MakeControlClass(controlClass, name)() | As for MakeControlClass(), but returns an instance of the class. |
171,946 | import struct
import win32api
import win32con
import win32ui
from pywin.mfc import afxres, window
def CenterPoint(rect):
width = rect[2] - rect[0]
height = rect[3] - rect[1]
return rect[0] + width // 2, rect[1] + height // 2 | null |
171,947 | import struct
import win32api
import win32con
import win32ui
from pywin.mfc import afxres, window
def OffsetRect(rect, point):
(x, y) = point
return rect[0] + x, rect[1] + y, rect[2] + x, rect[3] + y | null |
171,948 | import struct
import win32api
import win32con
import win32ui
from pywin.mfc import afxres, window
def DeflateRect(rect, point):
(x, y) = point
return rect[0] + x, rect[1] + y, rect[2] - x, rect[3] - y | null |
171,949 | import struct
import win32api
import win32con
import win32ui
from pywin.mfc import afxres, window
def PtInRect(rect, pt):
return rect[0] <= pt[0] < rect[2] and rect[1] <= pt[1] < rect[3] | null |
171,950 | import struct
import win32api
import win32con
import win32ui
from pywin.mfc import afxres, window
def EditCreator(parent):
d = win32ui.CreateEdit()
es = (
win32con.WS_CHILD
| win32con.WS_VISIBLE
| win32con.WS_BORDER
| win32con.ES_MULTILINE
| win32con.ES_WANTRETURN
)
d.CreateWindow(es, (0, 0, 150, 150), parent, 1000)
return d | null |
171,951 | import re
import regex
import win32api
import win32con
import win32ui
from pywin.framework.editor import (
GetEditorFontOption,
GetEditorOption,
SetEditorFontOption,
SetEditorOption,
defaultCharacterFormat,
)
from pywin.mfc import afxres, dialog, docview
from .document import EditorDocumentBase
from .template import EditorTemplateBase
from pywin.framework.editor import GetDefaultEditorModuleName
def Create(fileName=None, title=None, template=None):
return editorTemplate.OpenDocumentFile(fileName) | null |
171,952 | import pywin.scintilla.config
import win32api
import win32con
import win32ui
from pywin.framework.editor import (
DeleteEditorOption,
GetEditorFontOption,
GetEditorOption,
SetEditorFontOption,
SetEditorOption,
defaultCharacterFormat,
editorTemplate,
)
from pywin.mfc import dialog
from . import document
class EditorWhitespacePropertyPage(dialog.PropertyPage):
def __init__(self):
dialog.PropertyPage.__init__(self, win32ui.IDD_PP_TABS)
self.autooptions = []
self._AddEditorOption(win32ui.IDC_TAB_SIZE, "i", "Tab Size", 4)
self._AddEditorOption(win32ui.IDC_INDENT_SIZE, "i", "Indent Size", 4)
self._AddEditorOption(win32ui.IDC_USE_SMART_TABS, "i", "Smart Tabs", 1)
self._AddEditorOption(win32ui.IDC_VIEW_WHITESPACE, "i", "View Whitespace", 0)
self._AddEditorOption(win32ui.IDC_VIEW_EOL, "i", "View EOL", 0)
self._AddEditorOption(
win32ui.IDC_VIEW_INDENTATIONGUIDES, "i", "View Indentation Guides", 0
)
def _AddEditorOption(self, idd, typ, optionName, defaultVal):
self.AddDDX(idd, optionName, typ)
self[optionName] = GetEditorOption(optionName, defaultVal)
self.autooptions.append((optionName, defaultVal))
def OnInitDialog(self):
for name, val in self.autooptions:
self[name] = GetEditorOption(name, val)
rc = dialog.PropertyPage.OnInitDialog(self)
idc = win32ui.IDC_TABTIMMY_NONE
if GetEditorOption("Use Tab Timmy", 1):
idc = win32ui.IDC_TABTIMMY_IND
self.GetDlgItem(idc).SetCheck(1)
idc = win32ui.IDC_RADIO1
if GetEditorOption("Use Tabs", 0):
idc = win32ui.IDC_USE_TABS
self.GetDlgItem(idc).SetCheck(1)
tt_color = GetEditorOption("Tab Timmy Color", win32api.RGB(0xFF, 0, 0))
self.cbo = self.GetDlgItem(win32ui.IDC_COMBO1)
for c in paletteVGA:
self.cbo.AddString(c[0])
sel = 0
for c in paletteVGA:
if tt_color == win32api.RGB(c[1], c[2], c[3]):
break
sel = sel + 1
else:
sel = -1
self.cbo.SetCurSel(sel)
self.HookCommand(self.OnButSimple, win32ui.IDC_TABTIMMY_NONE)
self.HookCommand(self.OnButSimple, win32ui.IDC_TABTIMMY_IND)
self.HookCommand(self.OnButSimple, win32ui.IDC_TABTIMMY_BG)
# Set ranges for the spinners.
for spinner_id in [win32ui.IDC_SPIN1, win32ui.IDC_SPIN2]:
spinner = self.GetDlgItem(spinner_id)
spinner.SetRange(1, 16)
return rc
def OnButSimple(self, id, code):
if code == win32con.BN_CLICKED:
self.UpdateUIForState()
def UpdateUIForState(self):
timmy = self.GetDlgItem(win32ui.IDC_TABTIMMY_NONE).GetCheck()
self.GetDlgItem(win32ui.IDC_COMBO1).EnableWindow(not timmy)
def OnOK(self):
for name, defVal in self.autooptions:
SetEditorOption(name, self[name])
SetEditorOption("Use Tabs", self.GetDlgItem(win32ui.IDC_USE_TABS).GetCheck())
SetEditorOption(
"Use Tab Timmy", self.GetDlgItem(win32ui.IDC_TABTIMMY_IND).GetCheck()
)
c = paletteVGA[self.cbo.GetCurSel()]
SetEditorOption("Tab Timmy Color", win32api.RGB(c[1], c[2], c[3]))
return 1
def testpp():
ps = dialog.PropertySheet("Editor Options")
ps.AddPage(EditorWhitespacePropertyPage())
ps.DoModal() | null |
171,953 | import os
import sys
import traceback
import win32api
import win32ui
g_sourceSafe = None
def FindVssProjectInfo(fullfname):
"""Looks up the file system for an INI file describing the project.
Looking up the tree is for ni style packages.
Returns (projectName, pathToFileName) where pathToFileName contains
the path from the ini file to the actual file.
"""
path, fnameonly = os.path.split(fullfname)
origPath = path
project = ""
retPaths = [fnameonly]
while not project:
iniName = os.path.join(path, g_iniName)
database = win32api.GetProfileVal("Python", "Database", "", iniName)
project = win32api.GetProfileVal("Python", "Project", "", iniName)
if project:
break
# No valid INI file in this directory - look up a level.
path, addpath = os.path.split(path)
if not addpath: # Root?
break
retPaths.insert(0, addpath)
if not project:
win32ui.MessageBox(
"%s\r\n\r\nThis directory is not configured for Python/VSS" % origPath
)
return
return project, "/".join(retPaths), database
def CheckoutFile(fileName):
global g_sourceSafe
import pythoncom
ok = 0
# Assumes the fileName has a complete path,
# and that the INI file can be found in that path
# (or a parent path if a ni style package)
try:
import win32com.client
import win32com.client.gencache
mod = win32com.client.gencache.EnsureModule(
"{783CD4E0-9D54-11CF-B8EE-00608CC9A71F}", 0, 5, 0
)
if mod is None:
win32ui.MessageBox(
"VSS does not appear to be installed. The TypeInfo can not be created"
)
return ok
rc = FindVssProjectInfo(fileName)
if rc is None:
return
project, vssFname, database = rc
if g_sourceSafe is None:
g_sourceSafe = win32com.client.Dispatch("SourceSafe")
# SS seems a bit wierd. It defaults the arguments as empty strings, but
# then complains when they are used - so we pass "Missing"
if not database:
database = pythoncom.Missing
g_sourceSafe.Open(database, pythoncom.Missing, pythoncom.Missing)
item = g_sourceSafe.VSSItem("$/%s/%s" % (project, vssFname))
item.Checkout(None, fileName)
ok = 1
except pythoncom.com_error as exc:
win32ui.MessageBox(exc.strerror, "Error checking out file")
except:
typ, val, tb = sys.exc_info()
traceback.print_exc()
win32ui.MessageBox("%s - %s" % (str(typ), str(val)), "Error checking out file")
tb = None # Cleanup a cycle
return ok | null |
171,954 | import string
import sys
import win32ui
The provided code snippet includes necessary dependencies for implementing the `FixArgFileName` function. Write a Python function `def FixArgFileName(fileName)` to solve the following problem:
Convert a filename on the commandline to something useful. Given an automatic filename on the commandline, turn it a python module name, with the path added to sys.path.
Here is the function:
def FixArgFileName(fileName):
"""Convert a filename on the commandline to something useful.
Given an automatic filename on the commandline, turn it a python module name,
with the path added to sys.path."""
import os
path, fname = os.path.split(fileName)
if len(path) == 0:
path = os.curdir
path = os.path.abspath(path)
# must check that the command line arg's path is in sys.path
for syspath in sys.path:
if os.path.abspath(syspath) == path:
break
else:
sys.path.append(path)
return os.path.splitext(fname)[0] | Convert a filename on the commandline to something useful. Given an automatic filename on the commandline, turn it a python module name, with the path added to sys.path. |
171,955 | import array
import code
import os
import string
import sys
import traceback
import __main__
import afxres
import pywin.framework.app
import pywin.scintilla.control
import pywin.scintilla.formatter
import pywin.scintilla.IDLEenvironment
import win32api
import win32clipboard
import win32con
import win32ui
import re
from . import winout
sectionProfile = "Interactive Window"
def SavePreference(prefName, prefValue):
win32ui.WriteProfileVal(sectionProfile, prefName, prefValue) | null |
171,956 | import array
import code
import os
import string
import sys
import traceback
import __main__
import afxres
import pywin.framework.app
import pywin.scintilla.control
import pywin.scintilla.formatter
import pywin.scintilla.IDLEenvironment
import win32api
import win32clipboard
import win32con
import win32ui
import re
from . import winout
try:
sys.ps1
except AttributeError:
sys.ps1 = ">>> "
sys.ps2 = "... "
def GetPromptPrefix(line):
ps1 = sys.ps1
if line[: len(ps1)] == ps1:
return ps1
ps2 = sys.ps2
if line[: len(ps2)] == ps2:
return ps2 | null |
171,957 | import array
import code
import os
import string
import sys
import traceback
import __main__
import afxres
import pywin.framework.app
import pywin.scintilla.control
import pywin.scintilla.formatter
import pywin.scintilla.IDLEenvironment
import win32api
import win32clipboard
import win32con
import win32ui
import re
from . import winout
def LoadPreference(preference, default=""):
return win32ui.GetProfileVal(sectionProfile, preference, default)
def CreateInteractiveWindow(makeDoc=None, makeFrame=None):
"""Create a standard or docked interactive window unconditionally"""
assert edit is None, "Creating second interactive window!"
bDocking = LoadPreference("Docking", 0)
if bDocking:
CreateDockedInteractiveWindow()
else:
CreateMDIInteractiveWindow(makeDoc, makeFrame)
assert edit is not None, "Created interactive window, but did not set the global!"
edit.currentView.SetFocus()
The provided code snippet includes necessary dependencies for implementing the `CreateInteractiveWindowUserPreference` function. Write a Python function `def CreateInteractiveWindowUserPreference(makeDoc=None, makeFrame=None)` to solve the following problem:
Create some sort of interactive window if the user's preference say we should.
Here is the function:
def CreateInteractiveWindowUserPreference(makeDoc=None, makeFrame=None):
"""Create some sort of interactive window if the user's preference say we should."""
bCreate = LoadPreference("Show at startup", 1)
if bCreate:
CreateInteractiveWindow(makeDoc, makeFrame) | Create some sort of interactive window if the user's preference say we should. |
171,958 | import array
import code
import os
import string
import sys
import traceback
import __main__
import afxres
import pywin.framework.app
import pywin.scintilla.control
import pywin.scintilla.formatter
import pywin.scintilla.IDLEenvironment
import win32api
import win32clipboard
import win32con
import win32ui
import re
from . import winout
edit = None
The provided code snippet includes necessary dependencies for implementing the `DestroyInteractiveWindow` function. Write a Python function `def DestroyInteractiveWindow()` to solve the following problem:
Destroy the interactive window. This is different to Closing the window, which may automatically re-appear. Once destroyed, it can never be recreated, and a complete new instance must be created (which the various other helper functions will then do after making this call
Here is the function:
def DestroyInteractiveWindow():
"""Destroy the interactive window.
This is different to Closing the window,
which may automatically re-appear. Once destroyed, it can never be recreated,
and a complete new instance must be created (which the various other helper
functions will then do after making this call
"""
global edit
if edit is not None and edit.currentView is not None:
if edit.currentView.GetParentFrame() == win32ui.GetMainFrame():
# It is docked - do nothing now (this is only called at shutdown!)
pass
else:
# It is a standard window - call Close on the container.
edit.Close()
edit = None | Destroy the interactive window. This is different to Closing the window, which may automatically re-appear. Once destroyed, it can never be recreated, and a complete new instance must be created (which the various other helper functions will then do after making this call |
171,959 | import array
import code
import os
import string
import sys
import traceback
import __main__
import afxres
import pywin.framework.app
import pywin.scintilla.control
import pywin.scintilla.formatter
import pywin.scintilla.IDLEenvironment
import win32api
import win32clipboard
import win32con
import win32ui
import re
from . import winout
edit = None
def CreateInteractiveWindow(makeDoc=None, makeFrame=None):
"""Create a standard or docked interactive window unconditionally"""
assert edit is None, "Creating second interactive window!"
bDocking = LoadPreference("Docking", 0)
if bDocking:
CreateDockedInteractiveWindow()
else:
CreateMDIInteractiveWindow(makeDoc, makeFrame)
assert edit is not None, "Created interactive window, but did not set the global!"
edit.currentView.SetFocus()
def CloseInteractiveWindow():
"""Close the interactive window, allowing it to be re-created on demand."""
global edit
if edit is not None and edit.currentView is not None:
if edit.currentView.GetParentFrame() == win32ui.GetMainFrame():
# It is docked, just hide the dock bar.
frame = win32ui.GetMainFrame()
cb = frame.GetControlBar(ID_DOCKED_INTERACTIVE_CONTROLBAR)
frame.ShowControlBar(cb, 0, 1)
else:
# It is a standard window - destroy the frame/view, allowing the object itself to remain.
edit.currentView.GetParentFrame().DestroyWindow()
The provided code snippet includes necessary dependencies for implementing the `ToggleInteractiveWindow` function. Write a Python function `def ToggleInteractiveWindow()` to solve the following problem:
If the interactive window is visible, hide it, otherwise show it.
Here is the function:
def ToggleInteractiveWindow():
"""If the interactive window is visible, hide it, otherwise show it."""
if edit is None:
CreateInteractiveWindow()
else:
if edit.NeedRecreateWindow():
edit.RecreateWindow()
else:
# Close it, allowing a reopen.
CloseInteractiveWindow() | If the interactive window is visible, hide it, otherwise show it. |
171,960 | import array
import code
import os
import string
import sys
import traceback
import __main__
import afxres
import pywin.framework.app
import pywin.scintilla.control
import pywin.scintilla.formatter
import pywin.scintilla.IDLEenvironment
import win32api
import win32clipboard
import win32con
import win32ui
import re
from . import winout
edit = None
def CreateInteractiveWindow(makeDoc=None, makeFrame=None):
"""Create a standard or docked interactive window unconditionally"""
assert edit is None, "Creating second interactive window!"
bDocking = LoadPreference("Docking", 0)
if bDocking:
CreateDockedInteractiveWindow()
else:
CreateMDIInteractiveWindow(makeDoc, makeFrame)
assert edit is not None, "Created interactive window, but did not set the global!"
edit.currentView.SetFocus()
The provided code snippet includes necessary dependencies for implementing the `ShowInteractiveWindow` function. Write a Python function `def ShowInteractiveWindow()` to solve the following problem:
Shows (or creates if necessary) an interactive window
Here is the function:
def ShowInteractiveWindow():
"""Shows (or creates if necessary) an interactive window"""
if edit is None:
CreateInteractiveWindow()
else:
if edit.NeedRecreateWindow():
edit.RecreateWindow()
else:
parent = edit.currentView.GetParentFrame()
if parent == win32ui.GetMainFrame(): # It is docked.
edit.currentView.SetFocus()
else: # It is a "normal" window
edit.currentView.GetParentFrame().AutoRestore()
win32ui.GetMainFrame().MDIActivate(edit.currentView.GetParentFrame()) | Shows (or creates if necessary) an interactive window |
171,961 | import array
import code
import os
import string
import sys
import traceback
import __main__
import afxres
import pywin.framework.app
import pywin.scintilla.control
import pywin.scintilla.formatter
import pywin.scintilla.IDLEenvironment
import win32api
import win32clipboard
import win32con
import win32ui
import re
from . import winout
edit = None
def IsInteractiveWindowVisible():
return edit is not None and not edit.NeedRecreateWindow() | null |
171,962 | import glob
import os
import re
import sys
import time
import win32api
import win32con
import win32ui
from pywin.mfc import dialog, docview, window
from . import scriptutils
def getsubdirs(d):
dlist = []
flist = glob.glob(d + "\\*")
for f in flist:
if os.path.isdir(f):
dlist.append(f)
dlist = dlist + getsubdirs(f)
return dlist | null |
171,963 | import os
import sys
import traceback
import regutil
import win32api
import win32con
import win32ui
from pywin.mfc import afxres, dialog, window
from pywin.mfc.thread import WinApp
from . import scriptutils
def AddIdleHandler(handler):
print(
"app.AddIdleHandler is deprecated - please use win32ui.GetApp().AddIdleHandler() instead."
)
return win32ui.GetApp().AddIdleHandler(handler) | null |
171,964 | import os
import sys
import traceback
import regutil
import win32api
import win32con
import win32ui
from pywin.mfc import afxres, dialog, window
from pywin.mfc.thread import WinApp
from . import scriptutils
def DeleteIdleHandler(handler):
print(
"app.DeleteIdleHandler is deprecated - please use win32ui.GetApp().DeleteIdleHandler() instead."
)
return win32ui.GetApp().DeleteIdleHandler(handler) | null |
171,965 | import os
import sys
import traceback
import regutil
import win32api
import win32con
import win32ui
from pywin.mfc import afxres, dialog, window
from pywin.mfc.thread import WinApp
from . import scriptutils
The provided code snippet includes necessary dependencies for implementing the `SaveWindowSize` function. Write a Python function `def SaveWindowSize(section, rect, state="")` to solve the following problem:
Writes a rectangle to an INI file Args: section = section name in the applications INI file rect = a rectangle in a (cy, cx, y, x) tuple (same format as CREATESTRUCT position tuples).
Here is the function:
def SaveWindowSize(section, rect, state=""):
"""Writes a rectangle to an INI file
Args: section = section name in the applications INI file
rect = a rectangle in a (cy, cx, y, x) tuple
(same format as CREATESTRUCT position tuples)."""
left, top, right, bottom = rect
if state:
state = state + " "
win32ui.WriteProfileVal(section, state + "left", left)
win32ui.WriteProfileVal(section, state + "top", top)
win32ui.WriteProfileVal(section, state + "right", right)
win32ui.WriteProfileVal(section, state + "bottom", bottom) | Writes a rectangle to an INI file Args: section = section name in the applications INI file rect = a rectangle in a (cy, cx, y, x) tuple (same format as CREATESTRUCT position tuples). |
171,966 | import os
import sys
import traceback
import regutil
import win32api
import win32con
import win32ui
from pywin.mfc import afxres, dialog, window
from pywin.mfc.thread import WinApp
from . import scriptutils
The provided code snippet includes necessary dependencies for implementing the `LoadWindowSize` function. Write a Python function `def LoadWindowSize(section, state="")` to solve the following problem:
Loads a section from an INI file, and returns a rect in a tuple (see SaveWindowSize)
Here is the function:
def LoadWindowSize(section, state=""):
"""Loads a section from an INI file, and returns a rect in a tuple (see SaveWindowSize)"""
if state:
state = state + " "
left = win32ui.GetProfileVal(section, state + "left", 0)
top = win32ui.GetProfileVal(section, state + "top", 0)
right = win32ui.GetProfileVal(section, state + "right", 0)
bottom = win32ui.GetProfileVal(section, state + "bottom", 0)
return (left, top, right, bottom) | Loads a section from an INI file, and returns a rect in a tuple (see SaveWindowSize) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.