PyGUI should now work without installation

This commit is contained in:
Skyler
2012-01-05 20:06:00 -05:00
parent a1b07a33c1
commit b1c83def71
298 changed files with 24226 additions and 0 deletions
+7
View File
@@ -0,0 +1,7 @@
#--------------------------------------------------------------------
#
# PyGUI - Alert - Win32
#
#--------------------------------------------------------------------
from GUI.GAlertClasses import Alert, Alert2, Alert3
+115
View File
@@ -0,0 +1,115 @@
#--------------------------------------------------------------------
#
# PyGUI - Application - Win32
#
#--------------------------------------------------------------------
import win32con as wc, win32ui as ui, win32clipboard as wcb, win32api as api, \
win32gui as gui, win32process as wp
from GUI import export
from GUI import Component, Window, WinUtils
from GUI.GApplications import Application as GApplication
class Application(GApplication):
def __init__(self, *args, **kwds):
self._win_recycle_list = []
self._win_app = ui.GetApp()
self._win_app.AttachObject(self)
self._win_app.SetMainFrame(WinUtils.win_none)
GApplication.__init__(self, *args, **kwds)
def set_menus(self, x):
#print "Application.set_menus" ###
GApplication.set_menus(self, x)
for window in self.windows:
window._win_menus_changed()
def _event_loop(self, window):
if window:
window._begin_modal()
try:
self._win_app.Run()
finally:
if window:
window._end_modal()
def _exit_event_loop(self):
api.PostQuitMessage(0)
def zero_windows_allowed(self):
return False
def get_target(self):
try:
win = ui.GetFocus()
except ui.error:
win = None
if isinstance(win, Component):
return win
else:
return self
def get_target_window(self):
win = ui.GetActiveWindow()
if isinstance(win, Window):
return win
def OnIdle(self, n):
#print "Application.OnIdle" ###
trash = self._win_recycle_list
while trash:
trash.pop().DestroyWindow()
self._win_idle()
return 0
def _win_idle(self):
self._check_for_no_windows()
def _check_for_no_windows(self):
#print "Application._check_for_no_windows" ###
apid = wp.GetCurrentProcessId()
#print "... apid =", apid ###
htop = gui.GetDesktopWindow()
hwin = gui.GetWindow(htop, wc.GW_CHILD)
while hwin:
wpid = wp.GetWindowThreadProcessId(hwin)[1]
if wpid == apid:
#print "... hwin", hwin ###
if gui.GetWindowLong(hwin, wc.GWL_STYLE) & wc.WS_VISIBLE:
#print "...... is visible" ###
return
hwin = gui.GetWindow(hwin, wc.GW_HWNDNEXT)
#print "... none visible" ###
self.no_visible_windows()
# def PreTranslateMessage(self, msg):
# print "Application.PreTranslateMessage:", msg ###
def _win_recycle(self, win):
# It's not safe to destroy a window inside code called from its
# own OnCommand handler, so we use this method to delay it until
# a better time.
self._win_recycle_list.append(win)
def query_clipboard(self):
wcb.OpenClipboard()
result = wcb.IsClipboardFormatAvailable(wc.CF_TEXT)
wcb.CloseClipboard()
return result
def get_clipboard(self):
wcb.OpenClipboard()
try:
result = wcb.GetClipboardData()
except TypeError:
result = None
wcb.CloseClipboard()
return result
def set_clipboard(self, x):
wcb.OpenClipboard()
wcb.SetClipboardData(wc.CF_TEXT, x)
wcb.CloseClipboard()
export(Application)
+61
View File
@@ -0,0 +1,61 @@
#--------------------------------------------------------------------
#
# PyGUI - BaseAlert - Win32
#
#--------------------------------------------------------------------
import win32con as wc, win32gui as gui, win32api as api
from GUI import export
from GUI import application
from GUI.WinUtils import win_bg_color
from GUI import View
from GUI.GBaseAlerts import BaseAlert as GBaseAlert
win_icon_ids = {
'stop': wc.IDI_HAND,
'caution': wc.IDI_EXCLAMATION,
'note': wc.IDI_ASTERISK,
'query': wc.IDI_QUESTION,
}
win_icon_size = (
api.GetSystemMetrics(wc.SM_CXICON),
api.GetSystemMetrics(wc.SM_CYICON)
)
def win_load_icon(id):
return gui.LoadIcon(0, id)
class AlertIcon(View):
_win_transparent = True
def __init__(self, id, **kwds):
View.__init__(self, size = win_icon_size, **kwds)
#hwnd = self._win.GetSafeHwnd()
self.win_icon = win_load_icon(id)
def draw(self, c, r):
gfx = c._win_graphics
hdc = gfx.GetHDC()
gui.DrawIcon(hdc, 0, 0, self.win_icon)
gfx.ReleaseHDC(hdc)
# def draw(self, c, r):
# dc = c._win_dc
# dc.DrawIcon((0, 0), self.win_icon)
class BaseAlert(GBaseAlert):
_win_icon = None
def _layout_icon(self, kind):
id = win_icon_ids.get(kind)
if id:
icon = AlertIcon(id, position = (self._left_margin, self._top_margin))
self.add(icon)
return icon.size
else:
return (0, 0)
export(BaseAlert)
+95
View File
@@ -0,0 +1,95 @@
#--------------------------------------------------------------------
#
# PyGUI - File Dialogs - Win32
#
#--------------------------------------------------------------------
import win32con as wc, win32ui as ui, win32api as api
from GUI.Files import FileRef, DirRef
win_ofn_flags = wc.OFN_FILEMUSTEXIST | wc.OFN_PATHMUSTEXIST | wc.OFN_HIDEREADONLY \
| wc.OFN_NOCHANGEDIR | wc.OFN_OVERWRITEPROMPT
def win_filter(file_types):
filters = []
if file_types:
for ftype in file_types:
suffix = ftype.suffix
if suffix:
pattern = "*.%s" % suffix
filters.append("%s (%s)|%s" % (ftype.name, pattern, pattern))
return "|".join(filters) + "||"
def win_fix_prompt(prompt):
for s in ("as:", ":"):
if prompt.lower().endswith(s):
prompt = prompt[:-len(s)]
return prompt.strip()
def win_set_prompt(dlog, prompt):
dlog.SetOFNTitle(win_fix_prompt(prompt))
def fileref(path, file_type = None):
if file_type:
suffix = file_type.suffix
if suffix:
ext = "." + suffix
if not path.endswith(suffix):
path += ext
return FileRef(path = path)
def _request_old_file(prompt, default_dir, file_types, multiple):
flags = win_ofn_flags
if multiple:
flags |= wc.OFN_ALLOWMULTISELECT
filter = win_filter(file_types)
dlog = ui.CreateFileDialog(True, None, None, flags, filter)
win_set_prompt(dlog, prompt)
if default_dir:
dlog.SetOFNInitialDir(default_dir.path)
code = dlog.DoModal()
if code == 1: # IDOK
if multiple:
return map(fileref, dlog.GetPathNames())
else:
return fileref(dlog.GetPathName())
def _request_old_dir(prompt, default_dir):
from win32com.shell import shell as sh
import win32com.shell.shellcon as sc
win_bif_flags = sc.BIF_RETURNONLYFSDIRS # | sc.BIF_EDITBOX | wc.BIF_VALIDATE
if default_dir:
def callback(hwnd, msg, lp, data):
if msg == sc.BFFM_INITIALIZED:
api.SendMessage(hwnd, sc.BFFM_SETSELECTION, True, default_dir.path)
else:
callback = None
(idl, name, images) = sh.SHBrowseForFolder(None, None,
win_fix_prompt(prompt), win_bif_flags, callback)
if idl:
return DirRef(sh.SHGetPathFromIDList(idl))
def _request_old_dirs(prompt, default_dir):
raise NotImplementedError("Requesting multiple directories")
def _request_old(prompt, default_dir, file_types, dir, multiple):
if dir:
if multiple:
return _request_old_dirs(prompt, default_dir)
else:
return _request_old_dir(prompt, default_dir)
else:
return _request_old_file(prompt, default_dir, file_types, multiple)
def _request_new(prompt, default_dir, default_name, file_type, dir):
if file_type:
filter = win_filter([file_type])
else:
filter = "" # None
dlog = ui.CreateFileDialog(False, None, default_name, win_ofn_flags, filter)
win_set_prompt(dlog, prompt)
if default_dir:
dlog.SetOFNInitialDir(default_dir.path)
code = dlog.DoModal()
if code == 1: # IDOK
return fileref(dlog.GetPathName(), file_type)
+63
View File
@@ -0,0 +1,63 @@
#--------------------------------------------------------------------
#
# PyGUI - Button - Win32
#
#--------------------------------------------------------------------
from time import sleep
import win32con as wc, win32ui as ui, win32gui as gui
from GUI import export
from GUI.ButtonBases import ButtonBase
from GUI.GButtons import Button as GButton
win_hpad = 40
win_style_map = {
'normal': wc.BS_PUSHBUTTON,
'default': wc.BS_DEFPUSHBUTTON,
'cancel': wc.BS_PUSHBUTTON,
}
def win_style(style):
try:
return win_style_map[style]
except KeyError:
raise ValueError("Invalid Button style %r" % style)
#--------------------------------------------------------------------
class Button(ButtonBase, GButton):
_vertical_padding = 10
_color = None
def __init__(self, title = "New Button", **kwds):
font = self._win_predict_font(kwds)
style = kwds.pop('style', 'normal')
self._style = style
w = font.width(title) + win_hpad
h = self._calc_height(font)
win = self._win_create_button(title, win_style(style), w, h)
GButton.__init__(self, _win = win, **kwds)
def get_style(self):
return self._style
def set_style(self, x):
self._style = x
self._win.SetButtonStyle(win_style(x))
def flash(self):
win = self._win
win.SetState(True)
sleep(0.05)
win.SetState(False)
def _win_bn_clicked(self):
self.do_action()
def _win_activate(self):
self.do_action()
export(Button)
+25
View File
@@ -0,0 +1,25 @@
#--------------------------------------------------------------------
#
# PyGUI - Button base - Win32
#
#--------------------------------------------------------------------
class ButtonBase(object):
def key_down(self, event):
if not event.auto:
c = event.char
if c == ' ' or c == '\r':
self._win.SetState(True)
else:
GControl.key_down(self, event)
def key_up(self, event):
c = event.char
if c == ' ' or c == '\r':
if self._win.GetState() & 4:
self._win.SetState(False)
self._win_activate()
else:
GControl.key_down(self, event)
+336
View File
@@ -0,0 +1,336 @@
#--------------------------------------------------------------------
#
# PyGUI - Canvas - Win32
#
#--------------------------------------------------------------------
from math import sin, cos, pi
import win32con as wc, win32ui as ui, win32gui as gui
from win32con import PS_SOLID, BS_SOLID, RGN_AND
#from win32ui import CreatePen, CreateBrush
#from win32gui import CloseFigure, PathToRegion, AngleArc
from GUI import export
import GUI.GDIPlus as gdip
from GUI.StdColors import black, white
from GUI.StdFonts import application_font
from GUI.WinUtils import win_null_brush
from GUI.GCanvases import Canvas as GCanvas
deg = pi / 180
def ir(x, i = int, r = round):
return i(r(x))
def irr(rect, ir = ir):
l, t, r, b = rect
return (ir(l), ir(t), ir(r), ir(b))
#--------------------------------------------------------------------
class GState(object):
pencolor = black
fillcolor = black
textcolor = black
backcolor = white
pensize = 1
font = application_font
win_pen = gdip.Pen(pencolor._win_argb, 1)
win_fill_brush = gdip.SolidBrush(fillcolor._win_argb)
win_text_brush = gdip.SolidBrush(textcolor._win_argb)
win_bg_brush = gdip.SolidBrush(backcolor._win_argb)
def __init__(self, clone = None):
if clone:
self.__dict__.update(clone.__dict__)
#--------------------------------------------------------------------
class Canvas(GCanvas):
_current_point = None
# def __init__(self, win_graphics, dc = None):
# if not dc:
# print "Canvas.__init__: before get dc: clip bounds =", win_graphics.GetClipBounds() ###
# dc = ui.CreateDCFromHandle(win_graphics.GetHDC())
# print "Canvas.__init__: after get dc: clip bounds =", win_graphics.GetClipBounds() ###
# dc.SetBkMode(wc.TRANSPARENT)
# dc.SetTextAlign(wc.TA_LEFT | wc.TA_BASELINE | wc.TA_UPDATECP)
# print "Canvas.__init__: clip bounds =", win_graphics.GetClipBounds() ###
# self._win_graphics = win_graphics
# self._win_dc = dc
# self._win_hdc = dc.GetHandleOutput()
# self._win_path = gdip.GraphicsPath()
# self._state = GState()
# self._stack = []
def __init__(self, win_graphics, for_printing = False):
self._win_graphics = win_graphics
self._win_path = gdip.GraphicsPath()
self._state = GState()
self._stack = []
if for_printing:
unit = gdip.UnitPoint
win_graphics.SetPageUnit(unit)
#else:
# unit = gdip.UnitPixel
# dpix = win_graphics.GetDpiX()
# dpiy = win_graphics.GetDpiY()
# print "Canvas: dpi =", dpix, dpiy ###
# win_graphics.SetPageUnit(gdip.UnitPoint)
# if not for_printing:
# sx = 72.0 / dpix
# sy = 72.0 / dpiy
# self.scale(sx, sy)
def _from_win_dc(cls, dc):
return cls._from_win_hdc(dc.GetSafeHdc())
_from_win_dc = classmethod(_from_win_dc)
def _from_win_hdc(cls, hdc, **kwds):
win_graphics = gdip.Graphics.from_hdc(hdc)
return cls(win_graphics, **kwds)
_from_win_hdc = classmethod(_from_win_hdc)
def _from_win_image(cls, win_image):
win_graphics = gdip.Graphics.from_image(win_image)
#print "Canvas._from_win_image: win_graphics =", win_graphics ###
#print "... clip bounds =", win_graphics.GetClipBounds() ###
return cls(win_graphics)
_from_win_image = classmethod(_from_win_image)
def get_pencolor(self):
return self._state.pencolor
def set_pencolor(self, c):
state = self._state
state.pencolor = c
state.win_pen = gdip.Pen(c._win_argb, state.pensize)
def get_fillcolor(self):
return self._state.fillcolor
def set_fillcolor(self, c):
state = self._state
state.fillcolor = c
state.win_fill_brush = gdip.SolidBrush(c._win_argb)
def get_textcolor(self):
return self._state.textcolor
def set_textcolor(self, c):
state = self._state
state.textcolor = c
state.win_text_brush = gdip.SolidBrush(c._win_argb)
def get_backcolor(self):
return self._state.backcolor
def set_backcolor(self, c):
state = self._state
state.backcolor = c
state.win_bg_brush = gdip.SolidBrush(c._win_argb)
def get_pensize(self):
return self._state.pensize
def set_pensize(self, x):
state = self._state
state.pensize = x
state.win_pen = gdip.Pen(state.pencolor._win_argb, x)
def get_current_point(self):
return self._current_point
def get_font(self):
return self._state.font
def set_font(self, f):
self._state.font = f
def newpath(self):
self._win_path.Reset()
def moveto(self, x, y):
p = (x, y)
self._current_point = p
self._win_path.StartFigure()
def lineto(self, x, y):
x0, y0 = self._current_point
self._win_path.AddLine_4f(x0, y0, x, y)
self._current_point = (x, y)
def curveto(self, p1, p2, p3):
p0 = self._current_point
self._win_path.AddBezier_4p(p0, p1, p2, p3)
self._current_point = p3
def arc(self, c, r, a0, a1):
g = self._win_path
g.AddArc_p3f(c, r, a0, a1)
self._current_point = g.GetLastPoint()
def closepath(self):
self._win_path.CloseFigure()
self._current_point = None
def fill(self):
self._win_graphics.FillPath(self._state.win_fill_brush, self._win_path)
def stroke(self):
self._win_graphics.DrawPath(self._state.win_pen, self._win_path)
def erase(self):
g = self._win_graphics
g.SetSourceCopyMode()
g.FillPath(self._state.win_bg_brush, self._win_path)
g.SetSourceOverMode()
def show_text(self, text):
font = self._state.font
gf = font._win_gdip_font
x, y = self._current_point
brush = self._state.win_text_brush
g = self._win_graphics
w = g.DrawAndMeasureStringWidth_2f(text, gf, x, y, brush)
self._current_point = x + w, y
##
## GDI+ screws up some fonts (e.g. Times) for some reason.
## Using plain GDI to draw text for now.
##
# def show_text(self, text):
# state = self._state
# x, y = self._current_point
# dc = self._win_dc
# dc.SelectObject(state.font._win_font)
# dc.SetTextColor(state.textcolor._win_color)
# dc.MoveTo(ir(x), ir(y))
# dc.TextOut(20, 20, text)
# self._current_point = dc.GetCurrentPosition()
def clip(self):
self._win_graphics.SetClip_PI(self._win_path)
def rectclip(self, rect):
self._win_graphics.SetClip_rI(rect)
def gsave(self):
old_state = self._state
old_state.win_state = self._win_graphics.Save()
self._stack.append(old_state)
self._state = GState(old_state)
def grestore(self):
old_state = self._stack.pop()
self._win_graphics.Restore(old_state.win_state)
self._state = old_state
# Rectangles
def rect(self, rect):
self._win_path.AddRectangle_r(rect)
self._current_point = None
def fill_rect(self, rect):
self._win_graphics.FillRectangle_r(self._state.win_fill_brush, rect)
def stroke_rect(self, rect):
self._win_graphics.DrawRectangle_r(self._state.win_pen, rect)
def erase_rect(self, rect):
self._win_graphics.FillRectangle_r(self._state.win_bg_brush, rect)
# Ovals
def oval(self, rect):
self._win_path.AddEllipse_r(rect)
self._current_point = None
def fill_oval(self, rect):
self._win_graphics.FillEllipse_r(self._state.win_fill_brush, rect)
def stroke_oval(self, rect):
self._win_graphics.DrawEllipse_r(self._state.win_pen, rect)
def erase_oval(self, rect):
self._win_graphics.FillEllipse_r(self._state.win_bg_brush, rect)
# Arcs
def stroke_arc(self, c, r, a0, a1):
self._win_graphics.DrawArc_3pf(self._state.win_pen, c, r, a0, a1)
# Wedges
def wedge(self, c, r, a0, a1):
self._win_path.AddPie_p3f(c, r, a0, a1)
self._current_point = None
def stroke_wedge(self, c, r, a0, a1):
self._win_graphics.DrawPie_p3f(self._state.win_pen, c, r, a0, a1)
def fill_wedge(self, c, r, a0, a1):
self._win_graphics.FillPie_p3f(self._state.win_fill_brush, c, r, a0, a1)
def erase_wedge(self, c, r, a0, a1):
self._win_graphics.FillPie_p3f(self._state.win_bg_brush, c, r, a0, a1)
# Polylines
def lines(self, points):
self._win_path.AddLines_pv(points)
self._current_point = points[-1]
def linesto(self, points):
self.lines([self._current_point] + points)
def stroke_lines(self, points):
self._win_graphics.DrawLines_pv(self._state.win_pen, points)
# Polygons
def poly(self, points):
self._win_path.AddPolygon_pv(points)
self._current_point = None
def stroke_poly(self, points):
self._win_graphics.DrawPolygon_pv(self._state.win_pen, points)
def fill_poly(self, points):
self._win_graphics.FillPolygon_pv(self._state.win_fill_brush, points)
def erase_poly(self, points):
self._win_graphics.FillPolygon_pv(self._state.win_bg_brush, points)
# Polycurves
def curves(self, points):
self._win_path.AddBeziers_pv(points)
self._current_point = points[-1]
def curvesto(self, points):
self.curves([self._current_point] + points)
def stroke_curves(self, points):
self._win_graphics.DrawBeziers_pv(self._state.win_pen, points)
# Transformations
def translate(self, dx, dy):
self._win_graphics.Translate_2f(dx, dy)
def scale(self, sx, sy):
self._win_graphics.Scale_2f(sx, sy)
def rotate(self, rotation):
self._win_graphics.Rotate_1f(rotation)
export(Canvas)
+78
View File
@@ -0,0 +1,78 @@
#--------------------------------------------------------------------
#
# PyGUI - CheckBox - Win32
#
#--------------------------------------------------------------------
import win32con as wc, win32ui as ui
from GUI import export
from GUI.StdFonts import system_font
from GUI.ButtonBases import ButtonBase
from GUI.GCheckBoxes import CheckBox as GCheckBox
win_check_size = 13
win_hpad = 5
win_styles = (
[wc.BS_CHECKBOX, wc.BS_AUTOCHECKBOX],
[wc.BS_3STATE, wc.BS_AUTO3STATE],
)
win_states = (
[False, True],
[False, True, 'mixed'],
)
class CheckBox(ButtonBase, GCheckBox):
#_win_transparent = True
def __init__(self, title = "New Checkbox", **kwds):
font = self._win_predict_font(kwds)
self._auto_toggle = kwds.pop('auto_toggle', True)
self._mixed = kwds.get('mixed', False)
w = font.width(title) + win_hpad + win_check_size
h = max(self._calc_height(font), win_check_size)
win_style = self._win_button_style()
win = self._win_create_button(title, win_style, w, h)
GCheckBox.__init__(self, _win = win, **kwds)
def get_auto_toggle(self):
return win_styles[self._mixed].index(self._win.GetButtonStyle()) != 0
def set_auto_toggle(self, x):
self._auto_toggle = bool(x)
self._win_update_button_style()
def set_mixed(self, v):
GCheckBox.set_mixed(self, v)
self._win_update_button_style()
def get_on(self):
return win_states[self._mixed][self._win.GetCheck() & 0x3]
def set_on(self, x):
try:
state = win_states[self._mixed].index(x)
except ValueError:
raise ValueError("Invalid CheckBox state '%s'" % x)
self._win.SetCheck(state)
def _win_update_button_style(self):
self._win.SetButtonStyle(self._win_button_style())
def _win_button_style(self):
return win_styles[self._mixed][self._auto_toggle]
def _win_bn_clicked(self):
#print "CheckBox._win_bn_clicked:", self ###
self.do_action()
def _win_activate(self):
if self.auto_toggle:
states = win_states[self._mixed]
i = states.index(self.on)
self.on = states[(i+1) % len(states)]
self.do_action()
export(CheckBox)
+69
View File
@@ -0,0 +1,69 @@
#--------------------------------------------------------------------
#
# PyGUI - Color - Win32
#
#--------------------------------------------------------------------
from __future__ import division
import win32con as wc, win32ui as ui
from GUI import export
from GUI.GColors import Color as GColor
#--------------------------------------------------------------------
class Color(GColor):
# _win_color 00BBGGRR
# _win_argb AARRGGBB
_win_brush_cache = None
def get_red(self):
return self._red
def get_green(self):
return self._green
def get_blue(self):
return self._blue
def get_alpha(self):
return self._alpha
def _get_win_brush(self):
b = self._win_brush_cache
if not b:
b = ui.CreateBrush(wc.BS_SOLID, self._win_color, 0)
self._win_brush_cache = b
return b
_win_brush = property(_get_win_brush)
def _from_win_color(cls, c):
self = cls.__new__(cls)
self._win_color = c
r = c & 0xff
g = (c >> 8) & 0xff
b = (c >> 16) & 0xff
self._red = r / 255
self._green = g / 255
self._blue = b / 255
self._alpha = 1.0
self._win_argb = 0xff000000 | (r << 16) | (g << 8) | b
return self
_from_win_color = classmethod(_from_win_color)
def _from_win_argb(cls, c):
self = cls.__new__()
self._win_argb = c
a = (c >> 24) & 0xff
r = (c >> 16) & 0xff
g = (c >> 8) & 0xff
b = c & 0xff
self._red = r / 255
self._green = g / 255
self._blue = b / 255
self._alpha = a / 255
self._win_color = (b << 16) | (g << 8) | r
export(Color)
+31
View File
@@ -0,0 +1,31 @@
#--------------------------------------------------------------------
#
# PyGUI - Color utilities - Win32
#
#--------------------------------------------------------------------
import win32con as wc, win32api as api
from GUI import Color
def rgb(red, green, blue, alpha = 1.0):
color = Color()
color._red = red
color._green = green
color._blue = blue
color._alpha = alpha
color._win_color = (
int(red * 255) |
int(green * 255) << 8 |
int(blue * 255) << 16)
color._win_argb = (
int(blue * 255) |
int(green * 255) << 8 |
int(red * 255) << 16 |
int(alpha * 255) << 24)
return color
selection_forecolor = Color._from_win_color(
api.GetSysColor(wc.COLOR_HIGHLIGHTTEXT))
selection_backcolor = Color._from_win_color(
api.GetSysColor(wc.COLOR_HIGHLIGHT))
+263
View File
@@ -0,0 +1,263 @@
#--------------------------------------------------------------------
#
# PyGUI - Component - Win32
#
#--------------------------------------------------------------------
import win32con as wc, win32ui as ui, win32gui as gui, win32api as api
from GUI import export
from GUI.Geometry import sub_pt
from GUI import application
from GUI.WinUtils import win_none, win_event_messages
from GUI.WinEvents import win_message_to_event, win_prev_key_state
from GUI.Exceptions import Cancel
from GUI.GComponents import Component as GComponent, transform_coords
win_swp_flags = wc.SWP_NOACTIVATE | wc.SWP_NOZORDER
win_sws_flags = win_swp_flags | wc.SWP_NOMOVE
# Virtual key code to menu key char
win_menu_key_map = {
0xc0: '`',
0xbd: '-',
0xbb: '=',
0xdb: '[',
0xdd: ']',
0xba: ';',
0xde: "'",
0xbc: ',',
0xbe: '.',
0xbf: '/',
0xdc: '\\',
}
# Virtual key codes of modifier keys
win_virt_modifiers = (0x10, 0x11, 0x12, 0x14, 0x90)
# Translate virtual key code to menu key char
def win_translate_virtual_menu_key(virt):
if 0x41 <= virt <= 0x5a or 0x30 <= virt <= 0x39:
return chr(virt)
else:
return win_menu_key_map.get(virt)
#--------------------------------------------------------------------
class Component(GComponent):
_has_local_coords = True
_win_hooks_events = False
_win_transparent = False
_win_captures_mouse = False
_h_scroll_offset = 0
_v_scroll_offset = 0
_win_tracking_mouse = False
def __init__(self, _win, **kwds):
if self._win_transparent:
_win.ModifyStyleEx(0, wc.WS_EX_TRANSPARENT, 0)
self._win = _win
self._bounds = self._win_get_actual_bounds()
_win.AttachObject(self)
self._win_install_event_hooks()
GComponent.__init__(self, **kwds)
def destroy(self):
GComponent.destroy(self)
wo = self._win
if wo:
wo.AttachObject(None)
wo.ShowWindow(wc.SW_HIDE)
application()._win_recycle(wo)
#self._win = None
def _win_get_flag(self, flag):
return self._win.GetStyle() & flag != 0
def _win_set_flag(self, b, flag, swp_flags = 0):
if b:
state = flag
else:
state = 0
self._win.ModifyStyle(flag, state, swp_flags)
def _win_set_ex_flag(self, b, flag, swp_flags = 0):
if b:
state = flag
else:
state = 0
self._win.ModifyStyleEx(flag, state, swp_flags)
def _change_container(self, new_container):
GComponent._change_container(self, new_container)
if new_container:
win_new_parent = new_container._win
else:
win_new_parent = win_none
hwnd = self._win.GetSafeHwnd()
gui.SetParent(hwnd, win_new_parent.GetSafeHwnd())
if new_container:
self._win_move_window(self._bounds)
def _win_install_event_hooks(self):
def hook(message):
return self._win_event_message(message)
win = self._win
for msg in win_event_messages:
win.HookMessage(hook, msg)
win.HookMessage(self._win_wm_setfocus, wc.WM_SETFOCUS)
win.HookMessage(self._win_wm_killfocus, wc.WM_KILLFOCUS)
def _win_wm_setfocus(self, msg):
#print "Component._win_wm_setfocus:", self ###
self.targeted()
return True
def targeted(self):
pass
def _win_wm_killfocus(self, msg):
#print "Component._win_wm_killfocus:", self ###
self.untargeted()
return True
def untargeted(self):
pass
def _win_on_ctlcolor(self, dc, typ):
pass
# def OnCtlColor(self, dc, comp, typ):
# #print "Component.OnCtlColor" ###
# meth = getattr(comp, '_win_on_ctlcolor', None)
# if meth:
# return meth(dc, typ)
def get_bounds(self):
return self._bounds
def set_bounds(self, rect):
self._win_move_window(rect)
self._win_change_bounds(rect)
def _win_change_bounds(self, rect):
l0, t0, r0, b0 = self._bounds
l1, t1, r1, b1 = rect
w0 = r0 - l0
h0 = b0 - t0
w1 = r1 - l1
h1 = b1 - t1
self._bounds = rect
if w0 != w1 or h0 != h1:
self._resized((w1 - w0, h1 - h0))
def _win_move_window(self, bounds):
container = self.container
if container:
rect = container._win_adjust_bounds(bounds)
self._win.MoveWindow(rect)
def _win_adjust_bounds(self, bounds):
# Scrollable views override this to adjust for the scroll offset.
return bounds
def _win_get_actual_bounds(self):
win = self._win
parent = win.GetParent()
sbounds = win.GetWindowRect()
return parent._win.ScreenToClient(sbounds)
def become_target(self):
#print "Component.become_target:", self ###
window = self.window
if window:
if window._win_is_active():
#print "...setting focus" ###
self._win.SetFocus()
else:
#print "...saving focus in", window ###
window._win_saved_target = self
def invalidate_rect(self, r):
#print "Component.invalidate_rect:", self, r ###
self._invalidate_rect(r)
if self._win_transparent:
cont = self.container
if cont:
cont.invalidate_rect(self.local_to_container(r))
def _invalidate_rect(self, r):
self._win.InvalidateRect(r)
def local_to_global(self, p):
return self._win.ClientToScreen(p)
def global_to_local(self, p):
return self._win.ScreenToClient(p)
def container_to_local(self, p):
return transform_coords(self.container, self, p)
def local_to_container(self, p):
return transform_coords(self, self.container, p)
def _win_event_message(self, message):
try:
if 0:
from WinUtils import win_message_name ###
print "Component._win_event_message: %s 0x%08x 0x%08x" % ( ###
win_message_name(message[1]),
message[2] & 0xffffffff,
message[3] & 0xffffffff) ###
event = win_message_to_event(message, self)
kind = event.kind
if kind.startswith('key') and message[2] in win_virt_modifiers:
# Do not produce Events for modifier keys
return True
if kind == 'mouse_down' and self._win_captures_mouse:
self._win.SetCapture()
if self._win_tracking_mouse:
if 'mouse' in kind:
self._win_mouse_event = event
api.PostQuitMessage(0)
pass_message = False
else:
if kind == 'key_down' and event.control and event.char:
key = win_translate_virtual_menu_key(message[2])
top = self._win.GetTopLevelFrame()
if top._win_possible_menu_key(key, event.shift, event.option):
return False
pass_message = not self._event_custom_handled(event)
if kind == 'mouse_up' and self._win_captures_mouse:
self._win.ReleaseCapture()
# #<<<
# if kind.startswith('key'):
# if pass_message:
# print "Component._win_event_message: passing", event ###
# else:
# print "Component._win_event_message: absorbing", event ###
# #>>>
return pass_message
except Cancel:
pass
except:
application().report_error()
# print "Component._win_event_message: Posting quit message with 1" ###
# api.PostQuitMessage(1)
def _win_dump_flags(self):
from WinUtils import win_deconstruct_style, win_deconstruct_style_ex
print "%s.%s: style:" % (self.__class__.__module__, self.__class__.__name__)
win_deconstruct_style(self._win.GetStyle())
win_deconstruct_style_ex(self._win.GetExStyle())
# def PreTranslateMessage(self, message):
# print "Component.PreTranslateMessage:", self, \
# message[0], win_message_name(message[1]), \
# message[2]
#
#from WinUtils import win_message_name
export(Component)
+29
View File
@@ -0,0 +1,29 @@
#--------------------------------------------------------------------
#
# PyGUI - Container - Win32
#
#--------------------------------------------------------------------
import win32con as wc
from win32api import HIWORD, LOWORD
from GUI import export
from GUI.Geometry import add_pt, sub_pt
from GUI.WinUtils import WinMessageReflector
from GUI.GContainers import Container as GContainer
class Container(GContainer, WinMessageReflector):
def get_content_size(self):
return sub_pt(self.size, self._win_content_size_adjustment())
def set_content_size(self, size):
self.size = add_pt(size, self._win_content_size_adjustment())
def _win_content_size_adjustment(self):
win = self._win
wl, wt, wr, wb = win.GetWindowRect()
cl, ct, cr, cb = win.GetClientRect()
return ((wr - wl) - (cr - cl), (wb - wt) - (cb - ct))
export(Container)
+87
View File
@@ -0,0 +1,87 @@
#--------------------------------------------------------------------
#
# PyGUI - Control - Win32
#
#--------------------------------------------------------------------
from math import ceil
import win32con as wc, win32ui as ui
from GUI import export
from GUI.StdColors import black
from GUI.StdFonts import system_font
from GUI.WinUtils import win_none, win_null_hbrush
from GUI.GControls import Control as GControl
class Control(GControl):
_vertical_padding = 5 # Amount to add when calculating height from font size
_color = black
_just = 'left'
_font = None
def get_title(self):
return self._win.GetWindowText()
def set_title(self, x):
self._win.SetWindowText(x)
def get_enabled(self):
return self._win.IsWindowEnabled()
def set_enabled(self, x):
self._win.EnableWindow(x)
# def get_visible(self, x):
# self._win.IsWindowVisible()
#
# def set_visible(self, x):
# if x:
# self._win.ShowWindow(wc.SW_SHOW)
# else:
# self._win.ShowWindow(wc.SW_HIDE)
def get_font(self):
return self._font
def set_font(self, x):
self._font = x
self._win.SetFont(x._win_font)
self.invalidate()
def get_color(self):
return self._color
def set_color(self, x):
self._color = x
self.invalidate()
def get_just(self):
return self._just
def set_just(self, x):
self._just = x
self.invalidate()
def _win_create_button(self, title, style, w, h):
w = int(ceil(w))
win = ui.CreateButton()
win.CreateWindow(title, style, (0, 0, w, h), win_none, 0)
#if self._win_transparent:
# win.ModifyStyleEx(0, wc.WS_EX_TRANSPARENT, 0)
win.ShowWindow(wc.SW_SHOW)
return win
def _win_on_ctlcolor(self, dc, typ):
#print "Control._win_on_ctlcolor:", self ###
c = self._color
if c:
dc.SetTextColor(c._win_color)
if self._win_transparent:
dc.SetBkMode(wc.TRANSPARENT)
return win_null_hbrush
def _win_predict_font(self, kwds):
return kwds.setdefault('font', system_font)
export(Control)
+36
View File
@@ -0,0 +1,36 @@
#--------------------------------------------------------------------------
#
# Python GUI - Cursors - Win32
#
#--------------------------------------------------------------------------
import win32gui as gui
from GUI import export
from GUI.GCursors import Cursor as GCursor
class Cursor(GCursor):
def _from_win_cursor(cls, hcursor):
cursor = cls.__new__(cls)
cursor._win_cursor = hcursor
return cursor
_from_win_cursor = classmethod(_from_win_cursor)
def __str__(self):
return "<Cursor hcursor=0x%x>" % self._win_cursor
def _init_from_image_and_hotspot(self, image, hotspot):
#print "Cursor._init_from_image_and_hotspot:" ###
hicon = image._win_image.GetHICON()
iconinfo = gui.GetIconInfo(hicon)
gui.DestroyIcon(hicon)
flag, xhot, yhot, hbmMask, hbmColor = iconinfo
xhot, yhot = hotspot
cursorinfo = (True, xhot, yhot, hbmMask, hbmColor)
win_cursor = gui.CreateIconIndirect(cursorinfo)
gui.DeleteObject(hbmMask)
gui.DeleteObject(hbmColor)
self._win_cursor = win_cursor
export(Cursor)
+10
View File
@@ -0,0 +1,10 @@
#--------------------------------------------------------------------
#
# PyGUI - Dialog - Win32
#
#--------------------------------------------------------------------
from GUI import export
from GUI.GDialogs import Dialog
export(Dialog)
+68
View File
@@ -0,0 +1,68 @@
#--------------------------------------------------------------------
#
# PyGUI - DrawableContainer - Win32
#
#--------------------------------------------------------------------
from GUI import export
from GUI import Canvas
from GUI.Geometry import rect_topleft, rect_size, offset_rect, empty_rect
from GUI.GDrawableContainers import DrawableContainer as GDrawableContainer
import GUI.GDIPlus as gdi
class DrawableContainer(GDrawableContainer):
_double_buffer = True
_win_paint_broken = False
def update(self):
self._win.UpdateWindow()
def with_canvas(self, body):
win = self._win
dc = win.GetDC()
self._win_prepare_dc(dc)
try:
canvas = Canvas._from_win_dc(dc)
body(canvas)
finally:
win.ReleaseDC(dc)
def OnPaint(self):
if not self._win_paint_broken:
try:
win = self._win
dc, ps = win.BeginPaint()
try:
win_update_rect = ps[2]
if not empty_rect(win_update_rect):
#print "DrawableContainer.OnPaint: win_update_rect =", win_update_rect ###
scroll_offset = self._win_scroll_offset()
view_update_rect = offset_rect(win_update_rect, scroll_offset)
if self._double_buffer:
dx, dy = rect_topleft(view_update_rect)
width, height = rect_size(view_update_rect)
buffer = gdi.Bitmap(width, height)
canvas = Canvas._from_win_image(buffer)
canvas.translate(-dx, -dy)
self.draw(canvas, view_update_rect)
graphics = gdi.Graphics.from_dc(dc)
src_rect = (0, 0, width, height)
graphics.DrawImage_rr(buffer, win_update_rect, src_rect)
else:
self._win_prepare_dc(dc)
canvas = Canvas._from_win_dc(dc)
self.draw(canvas, view_update_rect)
finally:
win.EndPaint(ps)
except Exception:
self._win_paint_broken = True
raise
def _win_prepare_dc(self, dc):
dc.SetWindowOrg(self._win_scroll_offset())
def _win_scroll_offset(self):
return (0, 0)
export(DrawableContainer)
+22
View File
@@ -0,0 +1,22 @@
#
# PyGUI - Edit command handling - Win32
#
from GUI import export
from GUI.GEditCmdHandlers import EditCmdHandler as GEditCmdHandler
class EditCmdHandler(GEditCmdHandler):
def cut_cmd(self):
self._win.Cut()
def copy_cmd(self):
self._win.Copy()
def paste_cmd(self):
self._win.Paste()
def clear_cmd(self):
self._win.Clear()
export(EditCmdHandler)
+15
View File
@@ -0,0 +1,15 @@
#--------------------------------------------------------------------
#
# PyGUI - Event - Win32
#
#--------------------------------------------------------------------
from GUI import export
from GUI.GEvents import Event as GEvent
class Event(GEvent):
def _platform_modifiers_str(self):
return ""
export(Event)
+7
View File
@@ -0,0 +1,7 @@
#--------------------------------------------------------------------
#
# PyGUI - Files - Win32
#
#--------------------------------------------------------------------
from GUI.GFiles import FileRef, DirRef, FileType
+219
View File
@@ -0,0 +1,219 @@
#--------------------------------------------------------------------
#
# PyGUI - Font - Win32
#
#--------------------------------------------------------------------
import win32con as wc, win32gui as gui, win32ui as ui, win32api as api
from GUI import export
from WinUtils import win_none
import GUI.GDI as gdi
import GUI.GDIPlus as gdip
from GUI.GFonts import Font as GFont
#win_family_map = {
# "Decorative": wc.FF_DECORATIVE | wc.DEFAULT_PITCH,
# "Fixed": wc.FF_MODERN | wc.FIXED_PITCH,
# "Courier": wc.FF_MODERN | wc.FIXED_PITCH,
# "Modern": wc.FF_MODERN | wc.DEFAULT_PITCH,
# "Serif": wc.FF_ROMAN | wc.VARIABLE_PITCH,
# "Roman": wc.FF_ROMAN | wc.VARIABLE_PITCH,
# "Times": wc.FF_ROMAN | wc.VARIABLE_PITCH,
# "Sans": wc.FF_SWISS | wc.VARIABLE_PITCH,
# "Helvetica": wc.FF_SWISS | wc.VARIABLE_PITCH,
# "Script": wc.FF_SCRIPT | wc.DEFAULT_PITCH,
# "Cursive": wc.FF_SCRIPT | wc.DEFAULT_PITCH,
#}
#win_default_pf = wc.FF_DONTCARE | wc.DEFAULT_PITCH
def win_create_font(**kwds):
# Work around bug in CreateFont
for name in 'italic', 'underline':
if name in kwds and not kwds[name]:
del kwds[name]
return ui.CreateFont(kwds)
#def win_pf_to_name(pf):
# if pf & 0x3 == wc.FIXED_PITCH:
# return "Fixed"
# for name, npf in win_family_map.iteritems():
# if pf & 0xf0 == npf & 0xf0:
# return name
# return "Unknown"
win_generic_family_map = {
"Sans": "Arial",
"Serif": "Times New Roman",
"Fixed": "Courier New",
"Times": "Times New Roman",
"Courier": "Courier New",
}
# PyWin32 build 212 and earlier negate the value of the height
# passed to CreateFont.
pywin32_info = api.GetFileVersionInfo(api.__file__, '\\')
pywin32_build = pywin32_info['FileVersionLS'] >> 16
if pywin32_build <= 212:
win_height_sign = 1
else:
win_height_sign = -1
#--------------------------------------------------------------------
class Font(GFont):
# _win_font PyCFont
# _win_gfont GDIPlus.Font
def __init__(self, family = "Times", size = 12, style = []):
win_family = win_generic_family_map.get(family, family)
self._family = family
self._win_family = win_family
self._size = size
self._style = style
if 'bold' in style:
win_weight = wc.FW_BOLD
else:
win_weight = wc.FW_NORMAL
#print "Font: calling win_create_font" ###
height = int(round(size))
#print "Font: height =", height ###
win_font = win_create_font(
name = win_family,
height = win_height_sign * height,
weight = win_weight,
italic = 'italic' in style)
#pitch_and_family = 0) ###win_family_map.get(family, win_default_pf))
self._win_font = win_font
self._win_update_metrics()
#global dc ###
#dc = win_none.GetDC()
#dc.SelectObject(win_font)
#self._win_gfont = gdip.Font.from_hdc(dc.GetSafeHdc())
#win_none.ReleaseDC(dc)
# def __init__(self, family = "Times", size = 12, style = []):
# self._family = family
# self._size = size
# self._style = style
# hfont = gdi.create_hfont(family, size, style)
# self._win_hfont = hfont
# self._win_update_metrics()
def get_family(self):
return self._family
def get_size(self):
return self._size
def get_style(self):
return self._style
def get_ascent(self):
return self._ascent
def get_descent(self):
return self._descent
def get_leading(self):
return self._leading
def get_cap_height(self):
return self._ascent - self._internal_leading
def get_x_height(self):
return self._ascent - self._internal_leading - self._descent
def get_height(self):
return self._ascent + self._descent
def get_line_height(self):
return self._ascent + self._descent + self._leading
def _win_update_metrics(self):
dc = win_none.GetDC()
dc.SelectObject(self._win_font)
met = dc.GetTextMetrics()
self._ascent = met['tmAscent']
self._descent = met['tmDescent']
self._internal_leading = met['tmInternalLeading']
self._leading = met['tmExternalLeading']
self._win_overhang = met['tmOverhang']
#print "Font: tmOverhang =", self._win_overhang ###
win_none.ReleaseDC(dc)
self._win_gdip_font = gdip.Font(self._win_family, self._size, self._style)
def _width(self, s):
dc = win_none.GetDC()
dc.SelectObject(self._win_font)
w, h = dc.GetTextExtent(s)
win_none.ReleaseDC(dc)
return w
# def _width(self, s):
# dc = win_none.GetDC()
# g = gdip.Graphics.from_hdc(dc.GetSafeHdc())
# w = g.MeasureStringWidth(s, self._win_gdip_font)
# win_none.ReleaseDC(dc)
# return w
def info(self):
return "<Font family=%r size=%s style=%s ascent=%s descent=%s " \
"leading=%s height=%s cap_height=%s x_height=%s line_height=%s>" % \
(self.family, self.size, self.style, self.ascent, self.descent,
self.leading, self.height, self.cap_height, self.x_height,
self.line_height)
def tm_info(self):
win = ui.CreateWnd()
dc = win.GetDC()
dc.SelectObject(self._win_font)
tm = dc.GetTextMetrics()
win.ReleaseDC(dc)
return tm
# def _from_win_logfont(cls, lf):
# #print "Font._from_win_logfont:", lf ###
# #for name in dir(lf): ###
# # print name, "=", getattr(lf, name) ###
# font = cls.__new__(cls)
# font._family = win_pf_to_name(lf.lfPitchAndFamily)
# font._size = abs(lf.lfHeight)
# style = []
# if lf.lfWeight >= wc.FW_BOLD:
# style.append('bold')
# if lf.lfItalic:
# style.append('italic')
# font._style = style
# font._win_font = win_create_font(
# width = lf.lfWidth,
# #height = abs(lf.lfHeight),
# height = lf.lfHeight,
# weight = lf.lfWeight,
# italic = lf.lfItalic,
# underline = lf.lfUnderline,
# pitch_and_family = lf.lfPitchAndFamily,
# charset = lf.lfCharSet)
# font._win_update_metrics()
# return font
#
# _from_win_logfont = classmethod(_from_win_logfont)
def _from_win(cls, win):
dc = win.GetDC()
family = dc.GetTextFace()
tm = dc.GetTextMetrics()
#print family, tm
size = tm['tmAscent'] - tm['tmInternalLeading'] + tm['tmDescent']
style = []
if tm['tmWeight'] >= wc.FW_BOLD:
style.append('bold')
if tm['tmItalic']:
style.append('italic')
win.ReleaseDC(dc)
return Font(family, size, style)
_from_win = classmethod(_from_win)
export(Font)
+24
View File
@@ -0,0 +1,24 @@
#--------------------------------------------------------------------
#
# PyGUI - Frame - Win32
#
#--------------------------------------------------------------------
import win32con as wc, win32ui as ui
from GUI import export
from GUI.WinUtils import win_none
from GUI.GFrames import Frame as GFrame
win_flags = wc.WS_CHILD | wc.WS_VISIBLE
class Frame(GFrame):
_win_transparent = True
def __init__(self, **kwds):
w, h = self._default_size
win = ui.CreateWnd()
win.CreateWindow(None, None, win_flags, (0, 0, w, h), win_none, 0)
GFrame.__init__(self, _win = win, **kwds)
export(Frame)
+50
View File
@@ -0,0 +1,50 @@
#--------------------------------------------------------------------
#
# PyGUI - Win32 - GDI
#
#--------------------------------------------------------------------
LF_FACESIZE = 32
from ctypes import *
from ctypes.wintypes import *
class LOGFONT(Structure):
_fields_ = [ ('lfHeight', c_long),
('lfWidth', c_long),
('lfEscapement', c_long),
('lfOrientation', c_long),
('lfWeight', c_long),
('lfItalic', c_byte),
('lfUnderline', c_byte),
('lfStrikeOut', c_byte),
('lfCharSet', c_byte),
('lfOutPrecision', c_byte),
('lfClipPrecision', c_byte),
('lfQuality', c_byte),
('lfPitchAndFamily', c_byte),
('lfFaceName', c_char * LF_FACESIZE) ]
def __init__(self):
self.lfHeight = 10
self.lfWidth = 0
self.lfEscapement = 10
self.lfOrientation = 0
self.lfUnderline = 0
self.lfStrikeOut = 0
self.lfCharSet = 0 # ANSI_CHARSET
#self.lfPitchAndFamily = 0
self.lfOutPrecision = 0
self.lfClipPrecision = 0
self.lfQuality = 0
self.lfPitchAndFamily = 2
def create_hfont(family, size, style):
lf = LOGFONT()
lf.lfFaceName = family
lf.lfHeight = size
if 'italic' in style:
lf.lfItalic = 1
if 'bold' in style:
lf.lfWeight = 10
return windll.gdi32.CreateFontIndirectA(byref(lf))
+494
View File
@@ -0,0 +1,494 @@
#--------------------------------------------------------------------
#
# PyGUI - Win32 - GDI Plus
#
#--------------------------------------------------------------------
from ctypes import *
from ctypes.wintypes import BOOL
try:
from numpy import ndarray, float32
except ImportError:
class ndarray(object):
pass
#wg = windll.gdiplus
wg = oledll.gdiplus
#--------------------------------------------------------------------
# enum Unit
UnitWorld = 0
UnitDisplay = 1
UnitPixel = 2
UnitPoint = 3
# enum FillMode
FillModeAlternate = 0
# enum CombineMode
CombineModeIntersect = 1
# enum MatrixOrder
MatrixOrderPrepend = 0
MatrixOrderAppend = 1
# Pixel Formats
# In-memory pixel data formats:
# bits 0-7 = format index
# bits 8-15 = pixel size (in bits)
# bits 16-23 = flags
# bits 24-31 = reserved
PixelFormatIndexed = 0x00010000 # Indexes into a palette
PixelFormatGDI = 0x00020000 # Is a GDI-supported format
PixelFormatAlpha = 0x00040000 # Has an alpha component
PixelFormatPAlpha = 0x00080000 # Pre-multiplied alpha
PixelFormatExtended = 0x00100000 # Extended color 16 bits/channel
PixelFormatCanonical = 0x00200000
PixelFormat1bppIndexed = (1 | ( 1 << 8) | PixelFormatIndexed | PixelFormatGDI)
PixelFormat4bppIndexed = (2 | ( 4 << 8) | PixelFormatIndexed | PixelFormatGDI)
PixelFormat8bppIndexed = (3 | ( 8 << 8) | PixelFormatIndexed | PixelFormatGDI)
PixelFormat16bppGrayScale = (4 | (16 << 8) | PixelFormatExtended)
PixelFormat16bppRGB555 = (5 | (16 << 8) | PixelFormatGDI)
PixelFormat16bppRGB565 = (6 | (16 << 8) | PixelFormatGDI)
PixelFormat16bppARGB1555 = (7 | (16 << 8) | PixelFormatAlpha | PixelFormatGDI)
PixelFormat24bppRGB = (8 | (24 << 8) | PixelFormatGDI)
PixelFormat32bppRGB = (9 | (32 << 8) | PixelFormatGDI)
PixelFormat32bppARGB = (10 | (32 << 8) | PixelFormatAlpha | PixelFormatGDI | PixelFormatCanonical)
PixelFormat32bppPARGB = (11 | (32 << 8) | PixelFormatAlpha | PixelFormatPAlpha | PixelFormatGDI)
PixelFormat48bppRGB = (12 | (48 << 8) | PixelFormatExtended)
PixelFormat64bppARGB = (13 | (64 << 8) | PixelFormatAlpha | PixelFormatCanonical | PixelFormatExtended)
PixelFormat64bppPARGB = (14 | (64 << 8) | PixelFormatAlpha | PixelFormatPAlpha | PixelFormatExtended)
# enum FontStyle
FontStyleBold = 1
FontStyleItalic = 2
FontStyleUnderline = 4
FontStyleStrikeout = 8
class PointF(Structure):
_fields_ = [("x", c_float), ("y", c_float)]
class RectF(Structure):
_fields_ = [
("x", c_float), ("y", c_float),
("width", c_float), ("height", c_float)]
#--------------------------------------------------------------------
def rect_args(rect):
l, t, r, b = rect
return c_float(l), c_float(t), c_float(r - l), c_float(b - t)
def points_args(points):
if isinstance(points, ndarray) and points.flags['C_CONTIGUOUS'] and points.dtype == float32:
#print "GDIPlus.points_args: using ndarray" ###
n = points.size // 2
buf = points.ctypes.data
else:
n = len(points)
buf = (PointF * n)()
for i, p in enumerate(points):
buf[i].x, buf[i].y = p
return buf, n
def arc_args(c, r, a0, a1):
x, y = c
d = c_float(2 * r)
return c_float(x - r), c_float(y - r), d, d, \
c_float(a0), c_float((a1 - a0) % 360.0)
#--------------------------------------------------------------------
class GdiplusStartupInput(Structure):
_fields_ = [
('GdiplusVersion', c_uint),
('DebugEventCallback', c_void_p),
('SuppressBackgroundThread', BOOL),
('SuppressExternalCodecs', BOOL),
]
def __init__(self):
Structure.__init__(self)
self.GdiplusVersion = 1
self.DebugEventCallback = None
self.SuppressBackgroundThread = 0
self.SuppressExternalCodecs = 0
StartupInput = GdiplusStartupInput()
token = c_ulong()
wg.GdiplusStartup(pointer(token), pointer(StartupInput), None)
#--------------------------------------------------------------------
class Pen(object):
def __init__(self, argb, size):
ptr = c_void_p()
wg.GdipCreatePen1(argb, c_float(size), UnitWorld, byref(ptr))
self.ptr = ptr
def __del__(self, wg = wg):
wg.GdipDeletePen(self.ptr)
#--------------------------------------------------------------------
class SolidBrush(object):
def __init__(self, argb):
ptr = c_void_p()
wg.GdipCreateSolidFill(argb, byref(ptr))
self.ptr = ptr
def __del__(self, wg = wg):
wg.GdipDeleteBrush(self.ptr)
def __str__(self):
argb = c_ulong()
wg.GdipGetSolidFillColor(self.ptr, byref(argb))
return "<SolidBrush argb=0x%08x>" % argb.value
#--------------------------------------------------------------------
class Font(object):
def __init__(self, family, size, style):
uname = create_unicode_buffer(family)
fam = c_void_p()
wg.GdipCreateFontFamilyFromName(uname, None, byref(fam))
flags = 0
if 'bold' in style:
flags |= FontStyleBold
if 'italic' in style:
flags |= FontStyleItalic
ptr = c_void_p()
wg.GdipCreateFont(fam, c_float(size), flags, UnitWorld, byref(ptr))
self.ptr = ptr
wg.GdipDeleteFontFamily(fam)
def from_hdc(cls, hdc):
self = cls.__new__(cls)
ptr = c_void_p()
wg.GdipCreateFontFromDC(hdc, byref(ptr))
self.ptr = ptr
return self
from_hdc = classmethod(from_hdc)
def __del__(self, wg = wg):
wg.GdipDeleteFont(self.ptr)
#--------------------------------------------------------------------
class Image(object):
def __str__(self):
return "<Image 0x%x>" % self.ptr.value
def from_file(cls, path):
self = cls.__new__(cls)
ptr = c_void_p()
upath = create_unicode_buffer(path)
self._create_from_file(upath, ptr)
self.ptr = ptr
return self
from_file = classmethod(from_file)
def _create_from_file(self, upath, ptr):
wg.GdipLoadImageFromFile(upath, byref(ptr))
def __del__(self, wg = wg):
wg.GdipDisposeImage(self.ptr)
def GetWidth(self):
uint = c_uint()
wg.GdipGetImageWidth(self.ptr, byref(uint))
return uint.value
def GetHeight(self):
uint = c_uint()
wg.GdipGetImageHeight(self.ptr, byref(uint))
return uint.value
#--------------------------------------------------------------------
class Bitmap(Image):
def __init__(self, width, height):
ptr = c_void_p()
format = PixelFormat32bppARGB
wg.GdipCreateBitmapFromScan0(width, height, 0, format, None, byref(ptr))
self.ptr = ptr
#print "GDIPlus.Bitmap:", (width, height), repr(self), "ptr =", self.ptr ###
def _create_from_file(self, upath, ptr):
wg.GdipCreateBitmapFromFile(upath, byref(ptr))
def from_data(cls, width, height, format, data):
self = cls.__new__(cls)
ptr = c_void_p()
bits_per_pixel = (format >> 8) & 0xff
row_stride = (width * bits_per_pixel) >> 3
wg.GdipCreateBitmapFromScan0(width, height, row_stride, format, data, byref(ptr))
self.ptr = ptr
return self
from_data = classmethod(from_data)
def __str__(self):
return "<Bitmap 0x%x>" % self.ptr.value
def GetHICON(self):
hicon = c_ulong()
wg.GdipCreateHICONFromBitmap(self.ptr, byref(hicon))
return hicon.value
def GetPixel(self, x, y):
c = c_ulong()
wg.GdipBitmapGetPixel(self.ptr, x, y, byref(c))
return c.value
def SetPixel(self, x, y, c):
wg.GdipBitmapSetPixel(self.ptr, x, y, c)
#--------------------------------------------------------------------
class GraphicsPath(object):
def __init__(self):
ptr = c_void_p()
wg.GdipCreatePath(FillModeAlternate, byref(ptr))
self.ptr = ptr
def __del__(self, wg = wg):
wg.GdipDeletePath(self.ptr)
def Reset(self):
wg.GdipResetPath(self.ptr)
def StartFigure(self):
wg.GdipStartPathFigure(self.ptr)
def AddLine_4f(self, x0, y0, x1, y1):
wg.GdipAddPathLine(self.ptr,
c_float(x0), c_float(y0), c_float(x1), c_float(y1))
def AddBezier_4p(self, p0, p1, p2, p3):
x0, y0 = p0
x1, y1 = p1
x2, y2 = p2
x3, y3 = p3
wg.GdipAddPathBezier(self.ptr,
c_float(x0), c_float(y0), c_float(x1), c_float(y1),
c_float(x2), c_float(y2), c_float(x3), c_float(y3))
def AddBeziers_pv(self, points):
wg.GdipAddPathBeziers(self.ptr, *points_args(points))
def AddRectangle_r(self, rect):
wg.GdipAddPathRectangle(self.ptr, *rect_args(rect))
def AddEllipse_r(self, rect):
wg.GdipAddPathEllipse(self.ptr, *rect_args(rect))
def AddArc_p3f(self, c, r, a0, a1):
wg.GdipAddPathArc(self.ptr, *arc_args(c, r, a0, a1))
def AddPie_p3f(self, c, r, a0, a1):
wg.GdipAddPathPie(self.ptr, *arc_args(c, r, a0, a1))
def AddLines_pv(self, points):
wg.GdipAddPathLine2(self.ptr, *points_args(points))
def AddPolygon_pv(self, points):
wg.GdipAddPathPolygon(self.ptr, *points_args(points))
def CloseFigure(self):
wg.GdipClosePathFigure(self.ptr)
def GetLastPoint(self):
p = PointF()
wg.GdipGetPathLastPoint(self.ptr, byref(p))
return p.x, p.y
#--------------------------------------------------------------------
class Graphics(object):
def from_hdc(cls, hdc):
self = cls.__new__(cls)
ptr = c_void_p()
wg.GdipCreateFromHDC(c_ulong(hdc), byref(ptr))
self.ptr = ptr
return self
from_hdc = classmethod(from_hdc)
def from_dc(cls, dc):
return cls.from_hdc(dc.GetSafeHdc())
from_dc = classmethod(from_dc)
def from_image(cls, image):
#print "Graphics.from_image:", repr(image) ###
#print "...", image ###
self = cls.__new__(cls)
ptr = c_void_p()
wg.GdipGetImageGraphicsContext(image.ptr, byref(ptr))
self.ptr = ptr
return self
from_image = classmethod(from_image)
def __del__(self, wg = wg):
wg.GdipDeleteGraphics(self.ptr)
def __str__(self):
return "<Graphics 0x%x>" % self.ptr.value
def GetHDC(self):
hdc = c_long()
wg.GdipGetDC(self.ptr, byref(hdc))
return hdc.value
def ReleaseHDC(self, hdc):
wg.GdipReleaseDC(self.ptr, hdc)
def GetDpiX(self):
result = c_float()
wg.GdipGetDpiX(self.ptr, byref(result))
return result.value
def GetDpiY(self):
result = c_float()
wg.GdipGetDpiY(self.ptr, byref(result))
return result.value
def SetPageUnit(self, unit):
self.unit = unit
wg.GdipSetPageUnit(self.ptr, unit)
def GetClipBounds(self):
r = RectF()
wg.GdipGetClipBounds(self.ptr, byref(r))
return (r.x, r.y, r.x + r.width, r.y + r.height)
def Save(self):
state = c_uint()
wg.GdipSaveGraphics(self.ptr, byref(state))
return state.value
def Restore(self, state):
wg.GdipRestoreGraphics(self.ptr, state)
def DrawImage_rr(self, image, dst_rect, src_rect):
sl, st, sr, sb = src_rect
dl, dt, dr, db = dst_rect
wg.GdipDrawImageRectRect(self.ptr, image.ptr,
c_float(dl), c_float(dt), c_float(dr - dl), c_float(db - dt),
c_float(sl), c_float(st), c_float(sr - sl), c_float(sb - st),
UnitPixel, None, None, None)
def DrawPath(self, pen, path):
wg.GdipDrawPath(self.ptr, pen.ptr, path.ptr)
def FillPath(self, brush, path):
wg.GdipFillPath(self.ptr, brush.ptr, path.ptr)
def DrawAndMeasureStringWidth_2f(self, text, font, x, y, brush):
wtext = unicode(text)
n = len(text)
pos = PointF(x, y)
flags = 5 # DriverStringOptions CmapLookup+RealizedAdvance
b = RectF()
wg.GdipDrawDriverString(self.ptr, wtext, n, font.ptr, brush.ptr,
byref(pos), flags, None)
wg.GdipMeasureDriverString(self.ptr, wtext, n, font.ptr, byref(pos),
flags, None, byref(b))
return b.width
def MeasureStringWidth(self, text, font):
wtext = unicode(text)
n = len(text)
pos = PointF(0, 0)
flags = 5 # DriverStringOptions CmapLookup+RealizedAdvance
b = RectF()
wg.GdipMeasureDriverString(self.ptr, wtext, n, font.ptr, byref(pos),
flags, None, byref(b))
return b.width
def SetClip_PI(self, path):
wg.GdipSetClipPath(self.ptr, path.ptr, CombineModeIntersect)
def SetClip_rI(self, rect):
x, y, w, h = rect_args(rect)
wg.GdipSetClipRect(self.ptr, x, y, w, h, CombineModeIntersect)
def DrawRectangle_r(self, pen, rect):
wg.GdipDrawRectangle(self.ptr, pen.ptr, *rect_args(rect))
def FillRectangle_r(self, brush, rect):
#print "Graphics.FillRectangle_r:", self, brush, rect ###
#print "... clip bounds =", self.GetClipBounds() ###
wg.GdipFillRectangle(self.ptr, brush.ptr, *rect_args(rect))
def DrawEllipse_r(self, pen, rect):
wg.GdipDrawEllipse(self.ptr, pen.ptr, *rect_args(rect))
def FillEllipse_r(self, brush, rect):
wg.GdipFillEllipse(self.ptr, brush.ptr, *rect_args(rect))
def DrawArc_3pf(self, pen, c, r, a0, a1):
wg.GdipDrawArc(self.ptr, pen.ptr, *arc_args(c, r, a0, a1))
def DrawPie_p3f(self, pen, c, r, a0, a1):
wg.GdipDrawPie(self.ptr, pen.ptr, *arc_args(c, r, a0, a1))
def FillPie_p3f(self, brush, c, r, a0, a1):
wg.GdipFillPie(self.ptr, brush.ptr, *arc_args(c, r, a0, a1))
def DrawPolygon_pv(self, pen, points):
wg.GdipDrawPolygon(self.ptr, pen.ptr, *points_args(points))
def FillPolygon_pv(self, brush, points):
buf, n = points_args(points)
wg.GdipFillPolygon(self.ptr, brush.ptr, buf, n, FillModeAlternate)
def DrawBeziers_pv(self, pen, points):
wg.GdipDrawBeziers(self.ptr, pen.ptr, *points_args(points))
def DrawLines_pv(self, pen, points):
wg.GdipDrawLines(self.ptr, pen.ptr, *points_args(points))
def Translate_2f(self, dx, dy):
wg.GdipTranslateWorldTransform(self.ptr, c_float(dx), c_float(dy),
MatrixOrderAppend)
def Scale_2f(self, sx, sy):
wg.GdipScaleWorldTransform(self.ptr, c_float(sx), c_float(sy),
MatrixOrderAppend)
def Rotate_1f(self, r):
wg.GdipRotateWorldTransform(self.ptr, c_float(r),
MatrixOrderAppend)
def GetTransform(self):
matrix = c_void_p()
elems = (c_float * 6)()
wg.GdipCreateMatrix(byref(matrix))
wg.GdipGetWorldTransform(self.ptr, matrix)
wg.GdipGetMatrixElements(matrix, elems)
wg.GdipDeleteMatrix(matrix)
return list(elems)
+270
View File
@@ -0,0 +1,270 @@
#------------------------------------------------------------------------------
#
# PyGUI - OpenGL - Win32
#
#------------------------------------------------------------------------------
import win32con as wc, win32ui as ui, win32gui as gui
#import OpenGL.GL as gl ###
import GUI.GDIPlus as gdi
from OpenGL import WGL as wgl
from OpenGL.WGL import ChoosePixelFormat
#print "Using ctypes ChoosePixelFormat"
#from WGL import ChoosePixelFormat
from GUI.WinUtils import win_none
from GUI.GGLViews import GLView as GGLView
from GUI.GGLPixmaps import GLPixmap as GGLPixmap
from GUI.GGLConfig import GLConfig as GGLConfig, GLConfigError
from GUI.GLContexts import GLContext
from GUI.GLTextures import Texture
win_style = wc.WS_VISIBLE | wc.WS_CLIPCHILDREN | wc.WS_CLIPSIBLINGS
win_default_size = GGLView._default_size
win_default_rect = (0, 0, win_default_size[0], win_default_size[1])
#------------------------------------------------------------------------------
class GLConfig(GGLConfig):
def _as_win_pixelformat(self, mode):
#print "GLConfig._as_win_pixelformat: mode =", mode ###
pf = wgl.PIXELFORMATDESCRIPTOR()
flags = wgl.PFD_SUPPORT_OPENGL
if mode == 'screen' or mode == 'both':
#print "GLConfig: requesting screen drawing" ###
flags |= wgl.PFD_DRAW_TO_WINDOW
if self._double_buffer:
flags |= wgl.PFD_DOUBLEBUFFER | wgl.PFD_SWAP_EXCHANGE
else:
flags |= wgl.PFD_DOUBLEBUFFER_DONTCARE
if mode == 'pixmap' or mode == 'both':
#print "GLConfig: requesting pixmap drawing" ###
flags |= wgl.PFD_DRAW_TO_BITMAP | wgl.PFD_SUPPORT_GDI
if not self._depth_buffer:
flags |= wgl.PFD_DEPTH_DONTCARE
if self._stereo:
flags |= wgl.PFD_STEREO
else:
flags |= wgl.PFD_STEREO_DONTCARE
pf.dwFlags = flags & 0xffffffff
pf.iPixelType = wgl.PFD_TYPE_RGBA
#pf.cColorBits = 3 * self._color_size
#pf.cColorBits = 32 ###
pf.cRedBits = pf.cGreenBits = pf.cBluedBits = self._color_size
if self._alpha:
pf.cAlphaBits = self._alpha_size
pf.cAuxBuffers = self._aux_buffers
if self._depth_buffer:
pf.cDepthBits = self._depth_size
if self._stencil_buffer:
pf.cStencilBits = self._stencil_size
if self._accum_buffer:
pf.cAccumBits = 3 * self._accum_size
pf.iLayerType = wgl.PFD_MAIN_PLANE
return pf
def _from_win_pixelformat(cls, pf):
self = cls.__new__(cls)
flags = pf.dwFlags
self._double_buffer = flags & wgl.PFD_DOUBLEBUFFER != 0
self._alpha = pf.cAlphaSize > 0
self._color_size = pf.cColorBits
self._alpha_size = pf.cAlphaSize
self._stereo = flags & wgl.PFD_STEREO != 0
self._aux_buffers = pf.cAuxBuffers
self._depth_buffer = pf.cDepthBits > 0
self._depth_size = pf.cDepthBits
self._stencil_buffer = pf.cStencilBits > 0
self._stencil_size = pf.cStencilBits
self._accum_size = pf.cAccumBits
self._accum_buffer = self._accum_size > 0
self._multisample = False
self._samples_per_pixel = 1
return self
def _check_win_pixelformat(self, pf, mode):
flags = pf.dwFlags
if mode == 'screen' or mode == 'both':
if not flags & wgl.PFD_DRAW_TO_WINDOW:
raise GLConfigError("Rendering to screen not supported")
if mode == 'pixmap' or mode == 'both':
if not flags & wgl.PFD_DRAW_TO_BITMAP:
raise GLConfigError("Rendering to pixmap not supported")
if self._alpha and pf.cAlphaBits == 0:
raise GLConfigError("Alpha channel not available")
if self._stereo and not flags & wgl.PFD_STEREO:
raise GLConfigError("Stereo buffer not available")
if self._aux_buffers and pf.cAuxBuffers == 0:
raise GLConfigError("Auxiliary buffers not available")
if self._depth_buffer and pf.cDepthBits == 0:
raise GLConfigError("Depth buffer not available")
if self._stencil_buffer and pf.cStencilBits == 0:
raise GLConfigError("Stencil buffer not available")
if self.accum_buffer and pf.cAccumBits == 0:
raise GLConfigError("Accumulation buffer not available")
def _win_supported_pixelformat(self, hdc, mode):
reqpf = self._as_win_pixelformat(mode)
#print "GLConfig._win_supported_pixelformat" ###
#print "Requested format:" ###
#win_dump_pixelformat(reqpf) ###
#print "GLConfig: Choosing pixel format for hdc", hdc ###
ipf = wgl.ChoosePixelFormat(hdc, reqpf)
#print "... result =", ipf ###
actpf = wgl.PIXELFORMATDESCRIPTOR()
#print "GLConfig: Describing pixel format", ipf, "for hdc", hdc ###
wgl.DescribePixelFormat(hdc, ipf, actpf.nSize, actpf)
#print "Actual format:" ###
#win_dump_pixelformat(actpf) ###
return ipf, actpf
def supported(self, mode = 'both'):
dc = win_none.GetDC()
hdc = dc.GetSafeHdc()
ipf, actpf = self._win_supported_pixelformat(hdc, mode)
win_none.ReleaseDC(dc)
return GLConfig._from_win_pixelformat(actpf)
#------------------------------------------------------------------------------
class GLView(GGLView):
def __init__(self, config = None, share_group = None, **kwds):
config = GLConfig._from_args(config, kwds)
win = ui.CreateWnd()
win.CreateWindow(None, None, win_style, win_default_rect,
win_none, 0)
dc = win.GetDC()
hdc = dc.GetSafeHdc()
GLContext.__init__(self, share_group, config, hdc, 'screen')
GGLView.__init__(self, _win = win)
self.set(**kwds)
self._with_context(hdc, self._init_context)
win.ReleaseDC(dc)
# def _init_context(self):
# print "GL_VENDOR:", gl.glGetString(gl.GL_VENDOR)
# print "GL_RENDERER:", gl.glGetString(gl.GL_RENDERER)
# print "GL_VERSION:", gl.glGetString(gl.GL_VERSION)
# print "GL_EXTENSIONS:"
# for name in gl.glGetString(gl.GL_EXTENSIONS).split():
# print " ", name
# GGLView._init_context(self)
def destroy(self):
GLContext.destroy(self)
GGLView.destroy(self)
def with_context(self, proc, flush = False):
win = self._win
dc = win.GetDC()
hdc = dc.GetSafeHdc()
try:
self._with_context(hdc, proc, flush)
finally:
win.ReleaseDC(dc)
def OnPaint(self):
#print "GLView.OnPaint" ###
win = self._win
dc, ps = win.BeginPaint()
try:
hdc = dc.GetSafeHdc()
self._with_context(hdc, self._render, True)
finally:
win.EndPaint(ps)
def _resized(self, delta):
self.with_context(self._update_viewport)
#------------------------------------------------------------------------------
#class GLPixmap(GGLPixmap):
#
# def __init__(self, width, height, config = None, share_group = None, **kwds):
# print "GLPixmap:", width, height, kwds ###
# config = GLConfig._from_args(config, kwds)
# image = gdi.Bitmap(width, height)
# self._win_image = image
# graphics = gdi.Graphics.from_image(image)
# self._win_graphics = graphics
# hdc = graphics.GetHDC()
# self._win_hdc = hdc
# GLContext.__init__(self, share_group, config, hdc, 'pixmap')
# self._with_context(hdc, self._init_context)
# print "GLPixmap: done" ###
#
# def __del__(self):
# graphics = self._win_graphics
# graphics.ReleaseHDC(self._win_hdc)
#
# def with_context(self, proc, flush = False):
# try:
# self._with_context(self._hdc, proc, flush)
# finally:
# graphics.ReleaseHDC(hdc)
#------------------------------------------------------------------------------
class GLPixmap(GGLPixmap):
def __init__(self, width, height, config = None, share_group = None, **kwds):
#print "GLPixmap:", width, height, kwds ###
config = GLConfig._from_args(config, kwds)
dc0 = win_none.GetDC()
dc = dc0.CreateCompatibleDC(dc0)
bm = ui.CreateBitmap()
bm.CreateCompatibleBitmap(dc0, width, height)
win_none.ReleaseDC(dc0)
dc.SelectObject(bm)
self._win_dc = dc
self._win_bm = bm
hdc = dc.GetSafeHdc()
win_dump_bitmap(bm) ###
GLContext.__init__(self, share_group, config, hdc, 'pixmap')
self._with_context(hdc, self._init_context)
#print "GLPixmap: done" ###
def with_context(self, proc, flush = False):
hdc = self._win_dc.GetSafeHdc()
self._with_context(hdc, proc, flush)
#------------------------------------------------------------------------------
def win_dump_pixelformat(pf):
print "nSize =", pf.nSize
print "nVersion =", pf.nVersion
print "dwFlags = 0x%08x" % pf.dwFlags
print "iPixelType =", pf.iPixelType
print "cColorBits =", pf.cColorBits
print "cRedBits =", pf.cRedBits
print "cRedShift =", pf.cRedShift
print "cGreenBits =", pf.cGreenBits
print "cGreenShift =", pf.cGreenShift
print "cBlueBits =", pf.cBlueBits
print "cBlueShift =", pf.cBlueShift
print "cAlphaBits =", pf.cAlphaBits
print "cAlphaShift =", pf.cAlphaShift
print "cAccumBits =", pf.cAccumBits
print "cAccumRedBits =", pf.cAccumRedBits
print "cAccumGreenBits =", pf.cAccumGreenBits
print "cAccumBlueBits =", pf.cAccumBlueBits
print "cDepthBits =", pf.cDepthBits
print "cStencilBits =", pf.cStencilBits
print "cAuxBuffers =", pf.cAuxBuffers
print "iLayerType =", pf.iLayerType
print "bReserved =", pf.bReserved
print "dwLayerMask =", pf.dwLayerMask
print "dwVisibleMask =", pf.dwVisibleMask
print "dwDamageMask =", pf.dwDamageMask
def win_dump_bitmap(bm):
info = bm.GetInfo()
print "bmType =", info['bmType']
print "bmWidth =", info['bmWidth']
print "bmHeight =", info['bmHeight']
print "bmWidthBytes =", info['bmWidthBytes']
print "bmPlanes =", info['bmPlanes']
print "bmBitsPixel =", info['bmBitsPixel']
+51
View File
@@ -0,0 +1,51 @@
#------------------------------------------------------------------------------
#
# PyGUI - GLContext - Win32
#
#------------------------------------------------------------------------------
import OpenGL as gl
from OpenGL import WGL as wgl
from GUI.GGLContexts import GLContext as GGLContext
class GLContext(GGLContext):
# _win_dc Device context
# _win_context WGL context
# _win_dblbuf Is double buffered
def __init__(self, share_group, config, hdc, mode):
#print "GLContext: mode =", mode ###
GGLContext.__init__(self, share_group)
shared_context = self._get_shared_context()
if shared_context:
share_ctx = shared_context._win_context
else:
share_ctx = None
ipf, actpf = config._win_supported_pixelformat(hdc, mode)
config._check_win_pixelformat(actpf, mode)
#print "GLContext: Setting pixel format", ipf, "for hdc", hdc ###
wgl.SetPixelFormat(hdc, ipf, actpf)
#print "GLContext: Creating context for hdc", hdc ###
ctx = wgl.wglCreateContext(hdc)
if share_ctx:
wgl.wglShareLists(share_ctx, ctx)
self._win_context = ctx
self._win_dblbuf = actpf.dwFlags & wgl.PFD_DOUBLEBUFFER != 0
def destroy(self):
wgl.wglDeleteContext(self._win_context)
def _with_context(self, hdc, proc, flush = False):
old_hdc = wgl.wglGetCurrentDC()
old_ctx = wgl.wglGetCurrentContext()
result = wgl.wglMakeCurrent(hdc, self._win_context)
try:
self._with_share_group(proc)
if flush:
if self._win_dblbuf:
wgl.SwapBuffers(hdc)
else:
gl.glFlush()
finally:
wgl.wglMakeCurrent(old_hdc, old_ctx)
+52
View File
@@ -0,0 +1,52 @@
#------------------------------------------------------------------------------
#
# PyGUI - GLContext - Win32
#
#------------------------------------------------------------------------------
import OpenGL as gl
from OpenGL import WGL as wgl
import WGL
from GUI.GGLContexts import GLContext as GGLContext
class GLContext(GGLContext):
# _win_context WGL context
# _win_dblbuf Is double buffered
def __init__(self, share_group, config, hdc, mode):
print "GLContext: mode =", mode ###
GGLContext.__init__(self, share_group)
shared_context = self._get_shared_context()
if shared_context:
share_ctx = shared_context._win_context
else:
share_ctx = None
ipf, act_attrs = config._win_supported_pixelformat(hdc, mode)
if ipf is None:
raise GLConfigError
#config._check_win_pixelattrs(act_attrs, mode)
print "GLContext: Setting pixel format", ipf, "for hdc", hdc ###
WGL.SetPixelFormat(hdc, ipfs)
ctx = wgl.wglCreateContext(hdc)
if share_ctx:
wgl.wglShareLists(share_ctx, ctx)
self._win_context = ctx
self._win_dblbuf = actpf.dwFlags & wgl.PFD_DOUBLEBUFFER != 0
def destroy(self):
wgl.wglDeleteContext(self._win_context)
def _with_context(self, hdc, proc, flush = False):
old_hdc = wgl.wglGetCurrentDC()
old_ctx = wgl.wglGetCurrentContext()
result = wgl.wglMakeCurrent(hdc, self._win_context)
try:
self._with_share_group(proc)
if flush:
if self._win_dblbuf:
wgl.SwapBuffers(hdc)
else:
gl.glFlush()
finally:
wgl.wglMakeCurrent(old_hdc, old_ctx)
+51
View File
@@ -0,0 +1,51 @@
#------------------------------------------------------------------------------
#
# PyGUI - GLContext - Win32
#
#------------------------------------------------------------------------------
import OpenGL as gl
from OpenGL import WGL as wgl
from GUI.GGLContexts import GLContext as GGLContext
class GLContext(GGLContext):
# _win_dc Device context
# _win_context WGL context
# _win_dblbuf Is double buffered
def __init__(self, share_group, config, hdc, mode):
print "GLContext: mode =", mode ###
GGLContext.__init__(self, share_group)
shared_context = self._get_shared_context()
if shared_context:
share_ctx = shared_context._win_context
else:
share_ctx = None
ipf, actpf = config._win_supported_pixelformat(hdc, mode)
config._check_win_pixelformat(actpf, mode)
print "GLContext: Setting pixel format", ipf, "for hdc", hdc ###
wgl.SetPixelFormat(hdc, ipf, actpf)
print "GLContext: Creating context for hdc", hdc ###
ctx = wgl.wglCreateContext(hdc)
if share_ctx:
wgl.wglShareLists(share_ctx, ctx)
self._win_context = ctx
self._win_dblbuf = actpf.dwFlags & wgl.PFD_DOUBLEBUFFER != 0
def destroy(self):
wgl.wglDeleteContext(self._win_context)
def _with_context(self, hdc, proc, flush = False):
old_hdc = wgl.wglGetCurrentDC()
old_ctx = wgl.wglGetCurrentContext()
result = wgl.wglMakeCurrent(hdc, self._win_context)
try:
self._with_share_group(proc)
if flush:
if self._win_dblbuf:
wgl.SwapBuffers(hdc)
else:
gl.glFlush()
finally:
wgl.wglMakeCurrent(old_hdc, old_ctx)
+10
View File
@@ -0,0 +1,10 @@
#
# PyGUI - OpenGL Textures - Win32
#
from GUI.GGLTextures import Texture as GTexture
class Texture(GTexture):
def _gl_get_texture_data(self, image):
raise NotImplementedError("Loading texture from image not yet implemented for Win32")
+264
View File
@@ -0,0 +1,264 @@
#------------------------------------------------------------------------------
#
# PyGUI - OpenGL - Win32
#
#------------------------------------------------------------------------------
import win32con as wc, win32ui as ui, win32gui as gui
import GDIPlus as gdi
import WGL
from GUI.Components import win_none
from GUI.OpenGL import WGL as wgl
from GUI.GGLViews import GLView as GGLView
from GUI.GGLPixmaps import GLPixmap as GGLPixmap
from GUI.GGLConfig import GLConfig as GGLConfig, GLConfigError
from GUI.GLContexts import GLContext
from GUI.GLTextures import Texture
win_style = wc.WS_VISIBLE | wc.WS_CLIPCHILDREN | wc.WS_CLIPSIBLINGS
win_default_size = GGLView._default_size
win_default_rect = (0, 0, win_default_size[0], win_default_size[1])
#------------------------------------------------------------------------------
class GLConfig(GGLConfig):
def _as_win_pixelattrs(self, mode):
print "GLConfig._as_arb_pixelattrs: mode =", mode ###
attrs = {}
attrs[wgl.WGL_SUPPORT_OPENGL_ARB] = True
if mode == 'screen' or mode == 'both':
print "GLConfig: requesting screen drawing" ###
attrs[wgl.WGL_DRAW_TO_WINDOW_ARB] = True
if self._double_buffer:
attrs[wgl.WGL_DOUBLE_BUFFER_ARB] = True
if mode == 'pixmap' or mode == 'both':
print "GLConfig: requesting pixmap drawing" ###
attrs[wgl.WGL_DRAW_TO_PBUFFER_ARB] = True
if self._stereo:
attrs[wgl.WGL_STEREO_ARB] = True
attrs[wgl.WGL_PIXEL_TYPE_ARB] = wgl.WGL_TYPE_RGBA_ARB
bits = self._color_size
attrs[wgl.WGL_RED_BITS_ARB] = bits
attrs[wgl.WGL_GREEN_BITS_ARB] = bits
attrs[wgl.WGL_BLUE_BITS_ARB] = bits
if self._alpha:
attrs[wgl.WGL_ALPHA_BITS_ARB] = self._alpha_size
attrs[wgl.WGL_AUX_BUFFERS_ARB] = self._aux_buffers
if self._depth_buffer:
attrs[wgl.WGL_DEPTH_BITS_ARB] = self._depth_size
if self._stencil_buffer:
attrs[wgl.WGL_STENCIL_BITS_ARB] = self._stencil_size
if self._accum_buffer:
bits = self._accum_size
attrs[wgl.WGL_ACCUM_RED_BITS_ARB] = bits
attrs[wgl.WGL_ACCUM_GREEN_BITS_ARB] = bits
attrs[wgl.WGL_ACCUM_BLUE_BITS_ARB] = bits
return attrs
def _from_win_pixelattrs(cls, attrs):
self = cls.__new__(cls)
self._double_buffer = attrs[wgl.WGL_DOUBLE_BUFFER_ARB]
self._color_size = attrs[wgl.WGL_COLOR_BITS_ARB] // 3
self._alpha_size = attrs[wgl.WGL_ALPHA_BITS_ARB]
self._alpha = self._alpha_size > 0
self._stereo = attrs[wgl.WGL_STEREO_ARB] #flags & wgl.PFD_STEREO != 0
self._aux_buffers = attrs[wgl.WGL_AUX_BUFFERS_ARB] > 0
self._depth_size = attrs[wgl.WGL_DEPTH_BITS_ARB]
self._depth_buffer = self._depth_size > 0
self._stencil_size = attrs[wgl.WGL_STENCIL_BITS_ARB]
self._stencil_buffer = self._stencil_bits > 0
self._accum_size = attrs[wgl.WGL_ACCUM_BITS_ARB] // 3
self._accum_buffer = self._accum_size > 0
self._multisample = False
self._samples_per_pixel = 1
return self
# def _check_win_pixelattrs(self, attrs, mode):
# if mode == 'screen' or mode == 'both':
# if not attrs[wgl.WGL_DRAW_TO_WINDOW_ARB]:
# raise GLConfigError("Rendering to screen not supported")
# if mode == 'pixmap' or mode == 'both':
# if not attrs[wgl.WGL_DRAW_TO_PBUFFER_ARB]:
# raise GLConfigError("Rendering to pixmap not supported")
# if self._alpha and attrs[wgl.WGL_ALPHA_BITS_ARB] == 0:
# raise GLConfigError("Alpha channel not available")
# if self._stereo and not attrs[wgl.WGL_STEREO_ARB]:
# raise GLConfigError("Stereo buffer not available")
# if self._aux_buffers and attrs]wgl.WGL_AUX_BUFFERS_ARB] == 0:
# raise GLConfigError("Auxiliary buffers not available")
# if self._depth_buffer and attrs[wgl.WGL_DEPTH_BITS_ARB] == 0:
# raise GLConfigError("Depth buffer not available")
# if self._stencil_buffer and attrs[wgl.WGL_STENCIL_BITS] == 0:
# raise GLConfigError("Stencil buffer not available")
# if self.accum_buffer and attrs[wgl.WGL_ACCUM_BITS] == 0:
# raise GLConfigError("Accumulation buffer not available")
_win_query_pixelattr_keys = [
wgl.WGL_SUPPORT_OPENGL_ARB,
wgl.WGL_DRAW_TO_WINDOW_ARB,
wgl.WGL_DOUBLE_BUFFER_ARB,
wgl.WGL_DRAW_TO_PBUFFER_ARB,
wgl.WGL_STEREO_ARB,
wgl.WGL_PIXEL_TYPE_ARB,
wgl.WGL_COLOR_BITS_ARB,
wgl.WGL_ALPHA_BITS_ARB,
wgl.WGL_AUX_BUFFERS_ARB,
wgl.WGL_DEPTH_BITS_ARB,
wgl.WGL_STENCIL_BITS_ARB,
wgl.WGL_ACCUM_BITS_ARB,
]
def _win_supported_pixelformat(self, hdc, mode):
req_attrs = self._as_win_pixelattrs(mode)
print "GLConfig: Choosing pixel format for hdc", hdc ###
print "Requested attributes:", req_attrs ###
req_array = WGL.attr_array(req_attrs)
print "Requested array:", req_array ###
ipfs, nf = wgl.wglChoosePixelFormatEXT(hdc, req_array, None, 1)
print "Pixel formats:", ipfs ###
print "No. of formats:", nf ###
if not ipfs:
req_attrs[wgl.WGL_DOUBLE_BUFFER_ARB] = not self._double_buffer
req_array = WGL.attr_array(req_attrs)
ipfs, nf = wglChoosePixelFormatARB(hdc, req_array, None, 1)
if not ipfs:
return None, None
print "GLConfig: Describing pixel format", ipf, "for hdc", hdc ###
keys = _win_query_pixelattr_keys
values = wglGetPixelFormatAttribivARB(hdc, ipf, 0, keys)
print "Actual values:", values ###
act_attrs = WGL.attr_dict(keys, values)
print "Actual attrs:", act_attrs ###
return ipfs[0], act_attrs
def supported(self, mode = 'both'):
dc = win_none.GetDC()
hdc = dc.GetSafeHdc()
ipf, act_attrs = self._win_supported_pixelformat(hdc, mode)
win_none.ReleaseDC(dc)
if ipf is None:
return None
return GLConfig._from_win_pixelattrs(act_attrs)
#------------------------------------------------------------------------------
class GLView(GGLView):
def __init__(self, config = None, share_group = None, **kwds):
config = GLConfig._from_args(config, kwds)
win = ui.CreateWnd()
win.CreateWindow(None, None, win_style, win_default_rect,
win_none, 0)
dc = win.GetDC()
hdc = dc.GetSafeHdc()
GLContext.__init__(self, share_group, config, hdc, 'screen')
GGLView.__init__(self, _win = win, **kwds)
self._with_context(hdc, self._init_context)
win.ReleaseDC(dc)
def destroy(self):
GLContext.destroy(self)
GGLView.destroy(self)
def with_context(self, proc, flush = False):
win = self._win
dc = win.GetDC()
hdc = dc.GetSafeHdc()
try:
self._with_context(hdc, proc, flush)
finally:
win.ReleaseDC(dc)
def OnPaint(self):
#print "GLView.OnPaint" ###
win = self._win
dc, ps = win.BeginPaint()
try:
hdc = dc.GetSafeHdc()
self._with_context(hdc, self.render, True)
finally:
win.EndPaint(ps)
def _resized(self, delta):
self.with_context(self._update_viewport)
#------------------------------------------------------------------------------
#class GLPixmap(GGLPixmap):
#
# def __init__(self, width, height, config = None, share_group = None, **kwds):
# print "GLPixmap:", width, height, kwds ###
# config = GLConfig._from_args(config, kwds)
# image = gdi.Bitmap(width, height)
# self._win_image = image
# graphics = gdi.Graphics.from_image(image)
# self._win_graphics = graphics
# hdc = graphics.GetHDC()
# self._win_hdc = hdc
# GLContext.__init__(self, share_group, config, hdc, 'pixmap')
# self._with_context(hdc, self._init_context)
# print "GLPixmap: done" ###
#
# def __del__(self):
# graphics = self._win_graphics
# graphics.ReleaseHDC(self._win_hdc)
#
# def with_context(self, proc, flush = False):
# try:
# self._with_context(self._hdc, proc, flush)
# finally:
# graphics.ReleaseHDC(hdc)
#------------------------------------------------------------------------------
class GLPixmap(GGLPixmap):
def __init__(self, width, height, config = None, share_group = None, **kwds):
print "GLPixmap:", width, height, kwds ###
config = GLConfig._from_args(config, kwds)
pyhdc = gui.CreateCompatibleDC(0)
dc = ui.CreateDCFromHandle(pyhdc)
hdc = dc.GetSafeHdc()
hbm = gui.CreateCompatibleBitmap(hdc, width, height)
bm = ui.CreateBitmapFromHandle(hbm)
dc.SelectObject(bm)
self._win_dc = dc
self._win_hbm = hbm
self._win_bm = bm
GLContext.__init__(self, share_group, config, hdc, 'pixmap')
self._with_context(hdc, self._init_context)
print "GLPixmap: done" ###
def with_context(self, proc, flush = False):
hdc = self._win_dc.GetSafeHdc()
self._with_context(hdc, proc, flush)
#------------------------------------------------------------------------------
def win_dump_pixelformat(pf):
print "nSize =", pf.nSize
print "nVersion =", pf.nVersion
print "dwFlags = 0x%08x" % pf.dwFlags
print "iPixelType =", pf.iPixelType
print "cColorBits =", pf.cColorBits
print "cRedBits =", pf.cRedBits
print "cRedShift =", pf.cRedShift
print "cGreenBits =", pf.cGreenBits
print "cGreenShift =", pf.cGreenShift
print "cBlueBits =", pf.cBlueBits
print "cBlueShift =", pf.cBlueShift
print "cAlphaBits =", pf.cAlphaBits
print "cAlphaShift =", pf.cAlphaShift
print "cAccumBits =", pf.cAccumBits
print "cAccumRedBits =", pf.cAccumRedBits
print "cAccumGreenBits =", pf.cAccumGreenBits
print "cAccumBlueBits =", pf.cAccumBlueBits
print "cDepthBits =", pf.cDepthBits
print "cStencilBits =", pf.cStencilBits
print "cAuxBuffers =", pf.cAuxBuffers
print "iLayerType =", pf.iLayerType
print "bReserved =", pf.bReserved
print "dwLayerMask =", pf.dwLayerMask
print "dwVisibleMask =", pf.dwVisibleMask
print "dwDamageMask =", pf.dwDamageMask
+258
View File
@@ -0,0 +1,258 @@
#------------------------------------------------------------------------------
#
# PyGUI - OpenGL - Win32
#
#------------------------------------------------------------------------------
import win32con as wc, win32ui as ui, win32gui as gui
import GUI.GDIPlus as gdi
from GUI.Components import win_none
from GUI.OpenGL import WGL as wgl
from GUI.GGLViews import GLView as GGLView
from GUI.GGLPixmaps import GLPixmap as GGLPixmap
from GUI.GGLConfig import GLConfig as GGLConfig, GLConfigError
from GUI.GLContexts import GLContext
from GUI.GLTextures import Texture
win_style = wc.WS_VISIBLE | wc.WS_CLIPCHILDREN | wc.WS_CLIPSIBLINGS
win_default_size = GGLView._default_size
win_default_rect = (0, 0, win_default_size[0], win_default_size[1])
#------------------------------------------------------------------------------
class GLConfig(GGLConfig):
def _as_win_pixelformat(self, mode):
print "GLConfig._as_win_pixelformat: mode =", mode ###
pf = wgl.PIXELFORMATDESCRIPTOR()
flags = wgl.PFD_SUPPORT_OPENGL
if mode == 'screen' or mode == 'both':
print "GLConfig: requesting screen drawing" ###
flags |= wgl.PFD_DRAW_TO_WINDOW
if self._double_buffer:
flags |= wgl.PFD_DOUBLEBUFFER | wgl.PFD_SWAP_EXCHANGE
else:
flags |= wgl.PFD_DOUBLEBUFFER_DONTCARE
if mode == 'pixmap' or mode == 'both':
print "GLConfig: requesting pixmap drawing" ###
flags |= wgl.PFD_DRAW_TO_BITMAP | wgl.PFD_SUPPORT_GDI
if not self._depth_buffer:
flags |= wgl.PFD_DEPTH_DONTCARE
if self._stereo:
flags |= wgl.PFD_STEREO
else:
flags |= wgl.PFD_STEREO_DONTCARE
pf.dwFlags = flags & 0xffffffff
pf.iPixelType = wgl.PFD_TYPE_RGBA
#pf.cColorBits = 3 * self._color_size
pf.cColorBits = 32 ###
pf.cAlphaBits = 8 ###
pf.cAlphaShift = 24 ###
if self._alpha:
pf.cAlphaBits = self._alpha_size
pf.cAuxBuffers = self._aux_buffers
if self._depth_buffer:
pf.cDepthBits = self._depth_size
if self._stencil_buffer:
pf.cStencilBits = self._stencil_size
if self._accum_buffer:
pf.cAccumBits = 3 * self._accum_size
pf.iLayerType = wgl.PFD_MAIN_PLANE
return pf
def _from_win_pixelformat(cls, pf):
self = cls.__new__(cls)
flags = pf.dwFlags
self._double_buffer = flags & wgl.PFD_DOUBLEBUFFER != 0
self._alpha = pf.cAlphaSize > 0
self._color_size = pf.cColorBits
self._alpha_size = pf.cAlphaSize
self._stereo = flags & wgl.PFD_STEREO != 0
self._aux_buffers = pf.cAuxBuffers
self._depth_buffer = pf.cDepthBits > 0
self._depth_size = pf.cDepthBits
self._stencil_buffer = pf.cStencilBits > 0
self._stencil_size = pf.cStencilBits
self._accum_size = pf.cAccumBits
self._accum_buffer = self._accum_size > 0
self._multisample = False
self._samples_per_pixel = 1
return self
def _check_win_pixelformat(self, pf, mode):
flags = pf.dwFlags
if mode == 'screen' or mode == 'both':
if not flags & wgl.PFD_DRAW_TO_WINDOW:
raise GLConfigError("Rendering to screen not supported")
if mode == 'pixmap' or mode == 'both':
if not flags & wgl.PFD_DRAW_TO_BITMAP:
raise GLConfigError("Rendering to pixmap not supported")
if self._alpha and pf.cAlphaBits == 0:
raise GLConfigError("Alpha channel not available")
if self._stereo and not flags & wgl.PFD_STEREO:
raise GLConfigError("Stereo buffer not available")
if self._aux_buffers and pf.cAuxBuffers == 0:
raise GLConfigError("Auxiliary buffers not available")
if self._depth_buffer and pf.cDepthBits == 0:
raise GLConfigError("Depth buffer not available")
if self._stencil_buffer and pf.cStencilBits == 0:
raise GLConfigError("Stencil buffer not available")
if self.accum_buffer and pf.cAccumBits == 0:
raise GLConfigError("Accumulation buffer not available")
def _win_supported_pixelformat(self, hdc, mode):
reqpf = self._as_win_pixelformat(mode)
print "GLConfig._win_supported_pixelformat" ###
print "Requested format:" ###
win_dump_pixelformat(reqpf) ###
print "GLConfig: Choosing pixel format for hdc", hdc ###
ipf = wgl.ChoosePixelFormat(hdc, reqpf)
print "... result =", ipf ###
actpf = wgl.PIXELFORMATDESCRIPTOR()
print "GLConfig: Describing pixel format", ipf, "for hdc", hdc ###
wgl.DescribePixelFormat(hdc, ipf, actpf.nSize, actpf)
print "Actual format:" ###
win_dump_pixelformat(actpf) ###
return ipf, actpf
def supported(self, mode = 'both'):
dc = win_none.GetDC()
hdc = dc.GetSafeHdc()
ipf, actpf = self._win_supported_pixelformat(hdc, mode)
win_none.ReleaseDC(dc)
return GLConfig._from_win_pixelformat(actpf)
#------------------------------------------------------------------------------
class GLView(GGLView):
def __init__(self, config = None, share_group = None, **kwds):
config = GLConfig._from_args(config, kwds)
win = ui.CreateWnd()
win.CreateWindow(None, None, win_style, win_default_rect,
win_none, 0)
dc = win.GetDC()
hdc = dc.GetSafeHdc()
GLContext.__init__(self, share_group, config, hdc, 'screen')
GGLView.__init__(self, _win = win, **kwds)
self._with_context(hdc, self._init_context)
win.ReleaseDC(dc)
def destroy(self):
GLContext.destroy(self)
GGLView.destroy(self)
def with_context(self, proc, flush = False):
win = self._win
dc = win.GetDC()
hdc = dc.GetSafeHdc()
try:
self._with_context(hdc, proc, flush)
finally:
win.ReleaseDC(dc)
def OnPaint(self):
#print "GLView.OnPaint" ###
win = self._win
dc, ps = win.BeginPaint()
try:
hdc = dc.GetSafeHdc()
self._with_context(hdc, self.render, True)
finally:
win.EndPaint(ps)
def _resized(self, delta):
self.with_context(self._update_viewport)
#------------------------------------------------------------------------------
class GLPixmap(GGLPixmap):
def __init__(self, width, height, config = None, share_group = None, **kwds):
print "GLPixmap:", width, height, kwds ###
config = GLConfig._from_args(config, kwds)
image = gdi.Bitmap(width, height)
self._win_image = image
graphics = gdi.Graphics.from_image(image)
self._win_graphics = graphics
hdc = graphics.GetHDC()
self._win_hdc = hdc
GLContext.__init__(self, share_group, config, hdc, 'pixmap')
self._with_context(hdc, self._init_context)
print "GLPixmap: done" ###
def __del__(self):
graphics = self._win_graphics
graphics.ReleaseHDC(self._win_hdc)
def with_context(self, proc, flush = False):
try:
self._with_context(self._hdc, proc, flush)
finally:
graphics.ReleaseHDC(hdc)
#------------------------------------------------------------------------------
#class GLPixmap(GGLPixmap):
#
# def __init__(self, width, height, config = None, share_group = None, **kwds):
# print "GLPixmap:", width, height, kwds ###
# config = GLConfig._from_args(config, kwds)
# dc0 = win_none.GetDC()
# dc = dc0.CreateCompatibleDC(dc0)
# bm = ui.CreateBitmap()
# ###bm.CreateCompatibleBitmap(dc0, width, height)
# bm.CreateCompatibleBitmap(dc0, 1, 1)
# win_none.ReleaseDC(dc0)
# dc.SelectObject(bm)
# self._win_dc = dc
# self._win_bm = bm
# hdc = dc.GetSafeHdc()
# win_dump_bitmap(bm) ###
# GLContext.__init__(self, share_group, config, hdc, 'pixmap')
# self._with_context(hdc, self._init_context)
# print "GLPixmap: done" ###
#
# def with_context(self, proc, flush = False):
# hdc = self._win_dc.GetSafeHdc()
# self._with_context(hdc, proc, flush)
#------------------------------------------------------------------------------
def win_dump_pixelformat(pf):
print "nSize =", pf.nSize
print "nVersion =", pf.nVersion
print "dwFlags = 0x%08x" % pf.dwFlags
print "iPixelType =", pf.iPixelType
print "cColorBits =", pf.cColorBits
print "cRedBits =", pf.cRedBits
print "cRedShift =", pf.cRedShift
print "cGreenBits =", pf.cGreenBits
print "cGreenShift =", pf.cGreenShift
print "cBlueBits =", pf.cBlueBits
print "cBlueShift =", pf.cBlueShift
print "cAlphaBits =", pf.cAlphaBits
print "cAlphaShift =", pf.cAlphaShift
print "cAccumBits =", pf.cAccumBits
print "cAccumRedBits =", pf.cAccumRedBits
print "cAccumGreenBits =", pf.cAccumGreenBits
print "cAccumBlueBits =", pf.cAccumBlueBits
print "cDepthBits =", pf.cDepthBits
print "cStencilBits =", pf.cStencilBits
print "cAuxBuffers =", pf.cAuxBuffers
print "iLayerType =", pf.iLayerType
print "bReserved =", pf.bReserved
print "dwLayerMask =", pf.dwLayerMask
print "dwVisibleMask =", pf.dwVisibleMask
print "dwDamageMask =", pf.dwDamageMask
def win_dump_bitmap(bm):
info = bm.GetInfo()
print "bmType =", info['bmType']
print "bmWidth =", info['bmWidth']
print "bmHeight =", info['bmHeight']
print "bmWidthBytes =", info['bmWidthBytes']
print "bmPlanes =", info['bmPlanes']
print "bmBitsPixel =", info['bmBitsPixel']
+7
View File
@@ -0,0 +1,7 @@
#--------------------------------------------------------------------
#
# PyGUI - Geometry - Win32
#
#--------------------------------------------------------------------
from GUI.GGeometry import *
+16
View File
@@ -0,0 +1,16 @@
#--------------------------------------------------------------------
#
# PyGUI - Image - Win32
#
#--------------------------------------------------------------------
import GDIPlus as gdi
from GUI import export
from GUI.GImages import Image as GImage
class Image(GImage):
def _init_from_file(self, path):
self._win_image = gdi.Bitmap.from_file(path)
export(Image)
+22
View File
@@ -0,0 +1,22 @@
#--------------------------------------------------------------------
#
# PyGUI - ImageBase - Win32
#
#--------------------------------------------------------------------
from GUI import export
from GUI.GImageBases import ImageBase as GImageBase
class ImageBase(GImageBase):
# _win_image GdiPlus.Image
def get_width(self):
return self._win_image.GetWidth()
def get_height(self):
return self._win_image.GetHeight()
def draw(self, canvas, src_rect, dst_rect):
canvas._win_graphics.DrawImage_rr(self._win_image, dst_rect, src_rect)
export(ImageBase)
+81
View File
@@ -0,0 +1,81 @@
#--------------------------------------------------------------------
#
# PyGUI - Label - Win32
#
#--------------------------------------------------------------------
from math import ceil
import win32con as wc, win32ui as ui
from GUI import export
from GUI.StdColors import black
from GUI.StdFonts import system_font
from GUI.WinUtils import win_none
from GUI.GLabels import Label as GLabel
win_style = wc.WS_CLIPSIBLINGS | wc.WS_VISIBLE
win_dt_format = wc.DT_NOPREFIX | wc.DT_SINGLELINE | wc.DT_NOCLIP
win_dt_align_map = {
'l': wc.DT_LEFT | win_dt_format,
'c': wc.DT_CENTER | win_dt_format,
'r': wc.DT_RIGHT | win_dt_format,
}
#--------------------------------------------------------------------
class Label(GLabel):
_win_transparent = True
_font = None
_color = black
_just = 'l'
def __init__(self, text = "New Label", **kwds):
self._set_lines(text)
lines = self._lines
font = self._win_predict_font(kwds)
w = 0
for line in lines:
w = max(w, font.width(line))
w = int(ceil(w))
h = self._calc_height(font, len(lines))
win = ui.CreateWnd()
win.CreateWindow(None, None, win_style, (0, 0, w, h), win_none, 0)
#win.ModifyStyleEx(0, wc.WS_EX_TRANSPARENT, 0)
GLabel.__init__(self, _win = win, **kwds)
def get_text(self):
return "\n".join(self._lines)
def set_text(self, x):
self._set_lines(x)
self.invalidate()
def _set_lines(self, x):
self._lines = x.split("\n")
def OnPaint(self):
win = self._win
dc, paint_struct = win.BeginPaint()
font = self._font
win_font = font._win_font
dc.SetBkMode(wc.TRANSPARENT)
dc.SelectObject(win_font)
c = self._color._win_color
#print "Label.OnPaint: win color = 0x%08x" % c
dc.SetTextColor(c)
rm = self.width
y = 0
h = font.line_height
just = self._just[:1]
dt_format = win_dt_align_map[just]
for line in self._lines:
r = (0, y, rm, y + h)
dc.DrawText(line, r, dt_format)
y += h
win.EndPaint(paint_struct)
export(Label)
+47
View File
@@ -0,0 +1,47 @@
#--------------------------------------------------------------------
#
# PyGUI - ListButton - Win32
#
#--------------------------------------------------------------------
import win32con as wc, win32ui as ui, win32gui as gui
from GUI import export
from GUI.WinUtils import win_none
from GUI.WinComboBox import CreateComboBox
from GUI.GListButtons import ListButton as GListButton
class ListButton(GListButton):
_pass_key_events_to_platform = True
def __init__(self, **kwds):
titles, values = self._extract_initial_items(kwds)
self._titles = titles
self._values = values
win = CreateComboBox(win_none, (0, 0), (100, 320), wc.CBS_DROPDOWNLIST)
win.ShowWindow()
self._win_update_items(win)
GListButton.__init__(self, _win = win, **kwds)
def _update_items(self):
self._win_update_items(self._win)
def _win_update_items(self, win):
win.ResetContent()
for title in self._titles:
win.AddString(title)
def _get_selected_index(self):
return self._win.GetCurSel()
def _set_selected_index(self, x):
try:
self._win.SetCurSel(x)
except ui.error:
pass
def _cbn_sel_change(self):
self.do_action()
export(ListButton)
+66
View File
@@ -0,0 +1,66 @@
#--------------------------------------------------------------------
#
# PyGUI - Menu - Win32
#
#--------------------------------------------------------------------
import win32ui as ui, win32con as wc
from GUI import export
from GUI.WinMenus import win_command_to_id
from GUI.GMenus import Menu as GMenu
class Menu(GMenu):
def __init__(self, *args, **kwds):
GMenu.__init__(self, *args, **kwds)
def _update_platform_menu(self):
# Don't need to do anything here because platform menu item
# states are updated by HookCommandUpdate handlers.
pass
def _win_create_menu(self):
# Create a fresh platform menu reflecting the current items. Need
# to do this because it's not possible to share submenu handles
# between windows.
self._rebuild_platform_menu()
win_menu = self._win_menu
self._win_menu = None # So we don't accidentally try to reuse it
return win_menu
def _clear_platform_menu(self):
self._win_menu = ui.CreatePopupMenu()
# def _clear_platform_menu(self):
# #print "Menu._clear_platform_menu:", self ###
# bypos = wc.MF_BYPOSITION
# win_menu = self._win_menu
# n = win_menu.GetMenuItemCount()
# for i in xrange(n-1, -1, -1):
# win_menu.DeleteMenu(i, bypos)
def _add_separator_to_platform_menu(self):
#print "Menu._add_separator_to_platform_menu:", self ###
self._win_menu.AppendMenu(wc.MF_SEPARATOR, 0)
def _add_item_to_platform_menu(self, item, name, command_name, *args):
#print "Menu._add_item_to_platform_menu:", self, item, name ###
win_text = name.replace("&", "&&")
key = item._key
if key:
win_text += "\tCtrl+"
if item._shift:
win_text += "Shift+"
if item._option:
win_text += "Alt+"
win_text += key
flags = wc.MF_STRING
# These are done by HookCommandUpdate handler
#if not item.enabled:
# flags |= wc.MF_GRAYED
#if item.checked:
# flags |= wc.MF_CHECKED
id = win_command_to_id(command_name, *args)
self._win_menu.AppendMenu(flags, id, win_text)
export(Menu)
+49
View File
@@ -0,0 +1,49 @@
#--------------------------------------------------------------
#
# PyGUI - NumPy interface - Windows
#
#--------------------------------------------------------------
from numpy import ndarray, uint8
from GUI import GDIPlus as gdi
from GUI import Image
def image_from_ndarray(array, format, size = None):
"""
Creates an Image from a numpy ndarray object. The format
may be 'RGB' or 'RGBA'. If a size is specified, the array
will be implicitly reshaped to that size, otherwise the size
is inferred from the first two dimensions of the array.
"""
if array.itemsize <> 1:
raise ValueError("Color component size must be 1 byte")
if size is None:
shape = array.shape
if len(shape) <> 3:
raise ValueError("Array has wrong number of dimensions")
height, width, pixel_size = shape
if pixel_size <> len(format):
raise ValueError("Last dimension of array does not match format")
else:
width, height = size
pixel_size = len(format)
data_size = array.size
if data_size <> width * height * pixel_size:
raise ValueError("Array has wrong shape for specified size and format")
shape = (height, width, pixel_size)
array = array.reshape(shape)
swapped = ndarray(shape, uint8)
swapped[..., 0] = array[..., 2]
swapped[..., 1] = array[..., 1]
swapped[..., 2] = array[..., 0]
if pixel_size == 4:
fmt = gdi.PixelFormat32bppARGB
swapped[..., 3] = array[..., 3]
else:
fmt = gdi.PixelFormat24bppRGB
data = swapped.tostring()
bitmap = gdi.Bitmap.from_data(width, height, fmt, data)
image = Image.__new__(Image)
image._win_image = bitmap
image._data = data
return image
+33
View File
@@ -0,0 +1,33 @@
#--------------------------------------------------------------
#
# PyGUI - PIL interface - Windows
#
#--------------------------------------------------------------
from __future__ import absolute_import
from GUI import GDIPlus as gdi
from GUI import Image
from Image import merge
def image_from_pil_image(pil_image):
"""Creates an Image from a Python Imaging Library (PIL)
Image object."""
pil_image.load()
mode = pil_image.mode
w, h = pil_image.size
if mode == "RGB":
r, g, b = pil_image.split()
pil_image = merge(mode, (b, g, r))
fmt = gdi.PixelFormat24bppRGB
elif mode == "RGBA":
r, g, b, a = pil_image.split()
pil_image = merge(mode, (b, g, r, a))
fmt = gdi.PixelFormat32bppARGB
else:
raise ValueError("Unsupported PIL image mode '%s'" % mode)
data = pil_image.tostring()
bitmap = gdi.Bitmap.from_data(w, h, fmt, data)
image = Image.__new__(Image)
image._win_image = bitmap
image._data = data
return image
+20
View File
@@ -0,0 +1,20 @@
#--------------------------------------------------------------------------
#
# Python GUI - Pixmaps - Win32
#
#--------------------------------------------------------------------------
import GDIPlus as gdi
from GUI import export
from GUI import Canvas
from GUI.GPixmaps import Pixmap as GPixmap
class Pixmap(GPixmap):
def __init__(self, width, height):
self._win_image = gdi.Bitmap(width, height)
def with_canvas(self, proc):
proc(Canvas._from_win_image(self._win_image))
export(Pixmap)
+255
View File
@@ -0,0 +1,255 @@
#------------------------------------------------------------------------------
#
# PyGUI - Printing - Win32
#
#------------------------------------------------------------------------------
import WinPageSetup as wps, WinPrint as wp
import win32print as wp2
from GUI.GPrinting import PageSetup as GPageSetup, Printable as GPrintable, \
Paginator
from GUI import Canvas
#------------------------------------------------------------------------------
win_paper_names = {
1: "Letter", # Letter 8 1/2 x 11 in
2: "Letter Small", # Letter Small 8 1/2 x 11 in
3: "Tabloid", # Tabloid 11 x 17 in
4: "Ledger", # Ledger 17 x 11 in
5: "Legal", # Legal 8 1/2 x 14 in
6: "Statement", # Statement 5 1/2 x 8 1/2 in
7: "Executive", # Executive 7 1/4 x 10 1/2 in
8: "A3", # A3 297 x 420 mm
9: "A4", # A4 210 x 297 mm
10: "A4 Small", # A4 Small 210 x 297 mm
11: "A5", # A5 148 x 210 mm
12: "B4 (JIS)", # B4 (JIS) 250 x 354
13: "B5 (JIS)", # B5 (JIS) 182 x 257 mm
14: "Folio", # Folio 8 1/2 x 13 in
15: "Quarto", # Quarto 215 x 275 mm
16: "10x14", # 10x14 in
17: "11x17", # 11x17 in
18: "Note", # Note 8 1/2 x 11 in
19: "Envelope #9", # Envelope #9 3 7/8 x 8 7/8
20: "Envelope #10", # Envelope #10 4 1/8 x 9 1/2
21: "Envelope #11", # Envelope #11 4 1/2 x 10 3/8
22: "Envelope #12", # Envelope #12 4 \276 x 11
23: "Envelope #14", # Envelope #14 5 x 11 1/2
24: "C Sheet", # C size sheet
25: "D Sheet", # D size sheet
26: "E Sheet", # E size sheet
27: "Envelope DL", # Envelope DL 110 x 220mm
28: "Envelope C5", # Envelope C5 162 x 229 mm
29: "Envelope C3", # Envelope C3 324 x 458 mm
30: "Envelope C4", # Envelope C4 229 x 324 mm
31: "Envelope C6", # Envelope C6 114 x 162 mm
32: "Envelope C65", # Envelope C65 114 x 229 mm
33: "Envelope B4", # Envelope B4 250 x 353 mm
34: "Envelope B5", # Envelope B5 176 x 250 mm
35: "Envelope B6", # Envelope B6 176 x 125 mm
36: "Envelope", # Envelope 110 x 230 mm
37: "Envelope Monarch", # Envelope Monarch 3.875 x 7.5 in
38: "6 3/4 Envelope", # 6 3/4 Envelope 3 5/8 x 6 1/2 in
39: "US Std Fanfold", # US Std Fanfold 14 7/8 x 11 in
40: "German Std Fanfold", # German Std Fanfold 8 1/2 x 12 in
41: "German Legal Fanfold", # German Legal Fanfold 8 1/2 x 13 in
42: "B4", # B4 (ISO) 250 x 353 mm
43: "Japanese Postcard", # Japanese Postcard 100 x 148 mm
44: "9x11", # 9 x 11 in
45: "10x11", # 10 x 11 in
46: "15x11", # 15 x 11 in
47: "Envelope Invite", # Envelope Invite 220 x 220 mm
#48: "", # RESERVED--DO NOT USE
#49: "", # RESERVED--DO NOT USE
50: "Letter Extra", # Letter Extra 9 \275 x 12 in
51: "Legal Extra", # Legal Extra 9 \275 x 15 in
52: "Tabloid Extra", # Tabloid Extra 11.69 x 18 in
53: "A4 Extra", # A4 Extra 9.27 x 12.69 in
54: "Letter Transverse", # Letter Transverse 8 \275 x 11 in
55: "A4 Transverse", # A4 Transverse 210 x 297 mm
56: "Letter Extra Transverse", # Letter Extra Transverse 9\275 x 12 in
57: "SuperA", # SuperA/SuperA/A4 227 x 356 mm
58: "SuperB", # SuperB/SuperB/A3 305 x 487 mm
59: "Letter Plus", # Letter Plus 8.5 x 12.69 in
60: "A4 Plus", # A4 Plus 210 x 330 mm
61: "A5 Transverse", # A5 Transverse 148 x 210 mm
62: "B5 (JIS) Transverse", # B5 (JIS) Transverse 182 x 257 mm
63: "A3 Extra", # A3 Extra 322 x 445 mm
64: "A5 Extra", # A5 Extra 174 x 235 mm
65: "B5 (ISO) Extra", # B5 (ISO) Extra 201 x 276 mm
66: "A2", # A2 420 x 594 mm
67: "A3 Transverse", # A3 Transverse 297 x 420 mm
68: "A3 Extra Transverse", # A3 Extra Transverse 322 x 445 mm
}
win_paper_codes = dict([(name, code)
for (code, name) in win_paper_names.iteritems()])
def ti_to_pts(x):
return x * 0.072
def pts_to_ti(x):
return int(round(x / 0.072))
#------------------------------------------------------------------------------
class PageSetup(GPageSetup):
def __new__(cls):
self = GPageSetup.__new__(cls)
self._win_psd = wps.get_defaults()
return self
def __init__(self):
self.margins = (36, 36, 36, 36)
def __getstate__(self):
psd = self._win_psd
state = GPageSetup.__getstate__(self)
state['_win_devmode'] = wps.get_handle_contents(psd.hDevMode)
state['_win_devnames'] = wps.get_handle_contents(psd.hDevNames)
return state
def __setstate__(self, state):
psd = self._win_psd
dm = state.pop('_win_devmode', None)
dn = state.pop('_win_devnames', None)
GPageSetup.__setstate__(self, state)
if dm:
wps.GlobalFree(psd.hDevMode)
psd.hDevMode = handle_with_contents(dm)
if dn:
wps.GlobalFree(psd.hDevNames)
psd.hDevNames = handle_with_contents(dn)
def _win_lock_devmode(self):
return wps.lock_devmode_handle(self._win_psd.hDevMode)
def _win_unlock_devmode(self):
wps.GlobalUnlock(self._win_psd.hDevMode)
def get_printable_rect(self):
psd = self._win_psd
pw, ph = self.paper_size
mm = psd.rtMinMargin
ml = ti_to_pts(mm.left)
mt = ti_to_pts(mm.top)
mr = ti_to_pts(mm.right)
mb = ti_to_pts(mm.bottom)
return (ml, mt, pw - mr, ph - mb)
def get_paper_name(self):
dm = self._win_lock_devmode()
result = win_paper_names.get(dm.dmPaperSize, "Custom")
self._win_unlock_devmode()
return result
def set_paper_name(self, name):
dm = self._win_lock_devmode()
dm.dmPaperSize = win_paper_codes.get(name, 0)
self._win_unlock_devmode()
def get_paper_width(self):
return ti_to_pts(self._win_psd.ptPaperSize.x)
def get_paper_height(self):
return ti_to_pts(self._win_psd.ptPaperSize.y)
def set_paper_width(self, v):
self._win_psd.ptPaperSize.x = pts_to_ti(v)
def set_paper_height(self, v):
self._win_psd.ptPaperSize.y = pts_to_ti(v)
def get_left_margin(self):
return ti_to_pts(self._win_psd.rtMargin.left)
def get_top_margin(self):
return ti_to_pts(self._win_psd.rtMargin.top)
def get_right_margin(self):
return ti_to_pts(self._win_psd.rtMargin.right)
def get_bottom_margin(self):
return ti_to_pts(self._win_psd.rtMargin.bottom)
def set_left_margin(self, v):
self._win_psd.rtMargin.left = pts_to_ti(v)
def set_top_margin(self, v):
self._win_psd.rtMargin.top = pts_to_ti(v)
def set_right_margin(self, v):
self._win_psd.rtMargin.right = pts_to_ti(v)
def set_bottom_margin(self, v):
self._win_psd.rtMargin.bottom = pts_to_ti(v)
def get_orientation(self):
dm = self._win_lock_devmode()
result = win_orientation_names.get(dm.dmOrientation, 'portrait')
self._win_unlock_devmode()
return result
def set_orientation(self, v):
dm = self._win_lock_devmode()
dm.dmOrientation = win_orientation_codes.get(v, 1)
self._win_unlock_devmode()
def get_printer_name(self):
dm = self._win_lock_devmode()
result = dm.dmDeviceName
self._win_unlock_devmode()
return result
def set_printer_name(self, v):
dm = self._win_lock_devmode()
dm.dmDeviceName = v
self._win_unlock_devmode()
#------------------------------------------------------------------------------
class Printable(GPrintable):
def print_view(self, page_setup, prompt = True):
paginator = Paginator(self, page_setup)
psd = page_setup._win_psd
pd = wp.PRINTDLG()
pd.hDevMode = psd.hDevMode
pd.hDevNames = psd.hDevNames
pd.nMinPage = 1
pd.nMaxPage = paginator.num_pages
pd.nCopies = 1
if wp.PrintDlg(pd):
title = self.print_title
di = wp.DOCINFO()
di.lpszDocName = title
devnames = wps.DevNames(psd.hDevNames)
if devnames.output == "FILE:":
from FileDialogs import request_new_file
f = request_new_file("Print '%s' to file:" % title)
if not f:
return
output_path = f.path
di.lpszOutput = output_path
try:
hdc = pd.hDC
dx, dy = wp.GetPrintingOffset(hdc)
print "TODO: Printable: Implement a Cancel dialog" ###
#wp.install_abort_proc(hdc)
wp.StartDoc(hdc, di)
for page_num in xrange(pd.nFromPage - 1, pd.nToPage):
wp.StartPage(hdc)
canvas = Canvas._from_win_hdc(hdc, for_printing = True)
canvas.translate(-dx, -dy)
paginator.draw_page(canvas, page_num)
wp.EndPage(hdc)
wp.EndDoc(hdc)
finally:
wp.DeleteDC(hdc)
#------------------------------------------------------------------------------
def present_page_setup_dialog(page_setup):
return wps.PageSetupDlg(page_setup._win_psd)
+57
View File
@@ -0,0 +1,57 @@
#--------------------------------------------------------------------
#
# PyGUI - RadioButton - Win32
#
#--------------------------------------------------------------------
import win32con as wc, win32ui as ui
from GUI import export
from GUI.StdFonts import system_font
from GUI.ButtonBases import ButtonBase
from GUI.GRadioButtons import RadioButton as GRadioButton
win_check_size = 13
win_hpad = 5
class RadioButton(ButtonBase, GRadioButton):
#_win_transparent = True
def __init__(self, title = "New Radio Button", **kwds):
font = self._win_predict_font(kwds)
w = font.width(title) + win_hpad + win_check_size
h = max(self._calc_height(font), win_check_size)
win_style = wc.BS_RADIOBUTTON
win = self._win_create_button(title, win_style, w, h)
GRadioButton.__init__(self, _win = win, **kwds)
def _value_changed(self):
self._win_update()
def _win_update(self):
group = self._group
if group:
state = self._value == group._value
else:
state = False
self._win.SetCheck(state)
# Unbelievably, a BN_CLICKED message is sent when the
# button is focused, making it impossible to tell whether
# it was clicked or tabbed into.
#
# def _win_bn_clicked(self):
# print "RadioButton._win_bn_clicked" ###
# self._win_activate()
def _win_activate(self):
group = self._group
if group:
group.value = self._value
def mouse_up(self, event):
if self._win.GetState() & 0x4: # highlight
self._win_activate()
GRadioButton.mouse_up(self, event)
export(RadioButton)
+22
View File
@@ -0,0 +1,22 @@
#--------------------------------------------------------------------
#
# PyGUI - RadioGroup - Win32
#
#--------------------------------------------------------------------
from GUI import export
from GUI.GRadioGroups import RadioGroup as GRadioGroup
class RadioGroup(GRadioGroup):
def _item_added(self, item):
item._win_update()
def _item_removed(self, item):
item._win_update()
def _value_changed(self):
for item in self._items:
item._win_update()
export(RadioGroup)
+178
View File
@@ -0,0 +1,178 @@
#--------------------------------------------------------------------
#
# PyGUI - ScrollableView - Win32
#
#--------------------------------------------------------------------
import win32con as wc, win32ui as ui, win32gui as gui
from GUI import export
from GUI.WinUtils import win_plain_class, win_none
from GUI import Canvas
from GUI.GScrollableViews import ScrollableView as GScrollableView, \
default_extent, default_line_scroll_amount, default_scrolling
from GUI.Geometry import add_pt, sub_pt, offset_rect, offset_rect_neg
from GUI.GDrawableContainers import default_size
from GUI.Geometry import offset_rect_neg
win_style = wc.WS_CHILD | wc.WS_CLIPCHILDREN | wc.WS_CLIPSIBLINGS | \
wc.WS_VISIBLE ###| wc.WS_VSCROLL| wc.WS_HSCROLL
win_ex_style = 0 # wc.WS_EX_CLIENTEDGE
win_default_rect = (0, 0, default_size[0], default_size[1])
win_scroll_flags = wc.SW_INVALIDATE | wc.SW_SCROLLCHILDREN
win_swp_flags = wc.SWP_DRAWFRAME #| wc.SWP_FRAMECHANGED
class ScrollableView(GScrollableView):
_line_scroll_amount = default_line_scroll_amount
_extent = (500, 500)
def __init__(self, **kwds):
kwds.setdefault('border', True)
kwds.setdefault('extent', default_extent)
kwds.setdefault('scrolling', default_scrolling)
win = ui.CreateWnd()
win.CreateWindowEx(win_ex_style, win_plain_class, None, win_style, win_default_rect, win_none, 0)
win.HookMessage(self._win_wm_hscroll, wc.WM_HSCROLL)
win.HookMessage(self._win_wm_vscroll, wc.WM_VSCROLL)
GScrollableView.__init__(self, _win = win)
self.set(**kwds)
def get_hscrolling(self):
return self._win_get_flag(wc.WS_HSCROLL)
def get_vscrolling(self):
return self._win_get_flag(wc.WS_VSCROLL)
def set_hscrolling(self, x):
#print "ScrollableView.set_hscrolling:", x ###
self._win_set_flag(x, wc.WS_HSCROLL, win_swp_flags)
self._win_update_h_scrollbar()
def set_vscrolling(self, x):
#print "ScrollableView.set_vscrolling:", x ###
self._win_set_flag(x, wc.WS_VSCROLL, win_swp_flags)
self._win_update_v_scrollbar()
def set_border(self, x):
self._border = x
self._win_set_ex_flag(x, wc.WS_EX_CLIENTEDGE, win_swp_flags)
def get_line_scroll_amount(self):
return self._line_scroll_amount
def get_extent(self):
return self._extent
def set_extent(self, extent):
self._extent = extent
self._win_update_scroll_sizes()
def get_scroll_offset(self):
return self._h_scroll_offset, self._v_scroll_offset
def set_scroll_offset(self, p):
px = int(round(p[0]))
py = int(round(p[1]))
if px <> self._h_scroll_offset or py <> self._v_scroll_offset:
self._win_update_scroll_offset(px, py)
def _win_update_scroll_sizes(self):
self._win_update_scroll_offset(self._h_scroll_offset, self._v_scroll_offset)
def _win_update_scroll_offset(self, px, py):
ex, ey = self.extent
vx, vy = self.content_size
xmax = max(0, ex - vx)
ymax = max(0, ey - vy)
x = max(0, min(px, xmax))
y = max(0, min(py, ymax))
self._win_scroll_to(x, y)
self._win_update_h_scrollbar()
self._win_update_v_scrollbar()
def _win_update_h_scrollbar(self):
self._win_update_scrollbar(self.hscrolling, wc.SB_HORZ, 0)
def _win_update_v_scrollbar(self):
self._win_update_scrollbar(self.vscrolling, wc.SB_VERT, 1)
def _win_update_scrollbar(self, enabled, nbar, i):
# It is important not to update a disabled scrollbar, or
# subtle problems occur.
if enabled:
#print "ScrollableView._win_update_scrollbar:", enabled, nbar, i ###
f = wc.SIF_DISABLENOSCROLL
info = (f, 0, self.extent[i], self.content_size[i], self.scroll_offset[i])
self._win.SetScrollInfo(nbar, info, True)
def _scroll_range(self):
return (xmax, ymax)
def _win_scroll_to(self, x, y):
dx = self._h_scroll_offset - x
dy = self._v_scroll_offset - y
if dx or dy:
hwnd = self._win.GetSafeHwnd()
gui.ScrollWindowEx(hwnd, dx, dy, None, None, None, win_scroll_flags)
self._h_scroll_offset = x
self._v_scroll_offset = y
def set_bounds(self, bounds):
GScrollableView.set_bounds(self, bounds)
self._win_update_scroll_sizes()
def _invalidate_rect(self, r):
win = self._win
s = self.scroll_offset
self._win.InvalidateRect(offset_rect_neg(r, s))
def local_to_global(self, p):
q = sub_pt(p, self.scroll_offset)
return self._win.ClientToScreen(q)
def global_to_local(self, g):
q = self._win.ScreenToClient(g)
return add_pt(q, self.scroll_offset)
# def _win_prepare_dc(self, dc):
# dc.SetWindowOrg(self.scroll_offset)
def _win_scroll_offset(self):
return self.scroll_offset
def _win_wm_hscroll(self, message):
code = message[2] & 0xffff
if code == 0:
self.scroll_line_left()
elif code == 1:
self.scroll_line_right()
elif code == 2:
self.scroll_page_left()
elif code == 3:
self.scroll_page_right()
elif code == 5:
x = self._win_thumb_track_pos(wc.SB_HORZ)
self.scroll_offset = (x, self._v_scroll_offset)
def _win_wm_vscroll(self, message):
code = message[2] & 0xffff
if code == 0:
self.scroll_line_up()
elif code == 1:
self.scroll_line_down()
elif code == 2:
self.scroll_page_up()
elif code == 3:
self.scroll_page_down()
elif code == 5:
y = self._win_thumb_track_pos(wc.SB_VERT)
self.scroll_offset = (self._h_scroll_offset, y)
def _win_thumb_track_pos(self, nbar):
info = self._win.GetScrollInfo(nbar)
return info[5]
def _win_adjust_bounds(self, bounds):
return offset_rect_neg(bounds, self.scroll_offset)
export(ScrollableView)
+128
View File
@@ -0,0 +1,128 @@
#--------------------------------------------------------------------
#
# PyGUI - ScrollableView - Win32
#
#--------------------------------------------------------------------
import win32con as wc, win32ui as ui
from GUI.Components import win_none
from GUI.Canvases import Canvas
from GUI.GScrollableViews import ScrollableView as GScrollableView, \
default_extent, default_line_scroll_amount
from GUI.Geometry import add_pt, sub_pt, offset_rect, offset_rect_neg
win_style = ui.AFX_WS_DEFAULT_VIEW
#print "ScrollableViews: Creating dummy doc"
# PyWin32 insists on being given a CDocument when creating a CScrollView,
# and doesn't provide any way of creating a real one without using a resource.
if 1:
# The following uses a resource included in win32ui.pyd.
import pywin.mfc.object
win_dummy_doc_template = pywin.mfc.object.CmdTarget(
ui.CreateDocTemplate(ui.IDR_PYTHONTYPE))
ui.GetApp().AddDocTemplate(win_dummy_doc_template)
def win_get_dummy_doc():
return win_dummy_doc_template.DoCreateDoc()
else:
# The following hack creates something that looks enough
# like a CDocument to keep it happy. But it doesn't work with
# pywin32 builds later than 212.
win_dummy_doc = ui.CreateRichEditView().GetDocument()
def win_get_dummy_doc():
return win_dummy_doc
class ScrollableView(GScrollableView):
_line_scroll_amount = default_line_scroll_amount
def __init__(self, **kwds):
kwds.setdefault('extent', default_extent)
doc = win_get_dummy_doc()
win = ui.CreateView(doc)
#win.CreateWindow(win_none, 0, win_style, (0, 0, 100, 100))
win.CreateWindow(win_none, ui.AFX_IDW_PANE_FIRST, win_style, (0, 0, 100, 100))
GScrollableView.__init__(self, _win = win)
self.set(**kwds)
def get_hscrolling(self):
return self._win.GetStyle() & wc.WS_HSCROLL != 0
def get_vscrolling(self):
return self._win.GetStyle() & wc.WS_VSCROLL != 0
def set_hscrolling(self, x):
self._win_set_flag(x, wc.WS_HSCROLL)
def set_vscrolling(self, x):
self._win_set_flag(x, wc.WS_VSCROLL)
def get_line_scroll_amount(self):
return self._line_scroll_amount
def get_extent(self):
return self._win.GetTotalSize()
def set_extent(self, extent):
self._win_update_scroll_sizes(extent)
def get_scroll_offset(self):
return self._win.GetScrollPosition()
def set_scroll_offset(self, p):
px, py = p
ex, ey = self.extent
vx, vy = self.content_size
xmax = max(0, ex - vx)
ymax = max(0, ey - vy)
x = max(0, min(px, xmax))
y = max(0, min(py, ymax))
self._win.ScrollToPosition((x, y))
def set_bounds(self, bounds):
GScrollableView.set_bounds(self, bounds)
extent = self._win.GetTotalSize()
self._win_update_scroll_sizes(extent)
def _invalidate_rect(self, r):
win = self._win
s = win.GetScrollPosition()
self._win.InvalidateRect(offset_rect_neg(r, s))
def local_to_global(self, p):
win = self._win
q = sub_pt(p, win.GetScrollPosition())
return win.ClientToScreen(q)
def global_to_local(self, g):
win = self._win
q = win.ScreenToClient(g)
return add_pt(q, win.GetScrollPosition())
# def global_to_local(self, g):
# win = self._win
# l = win.ScreenToClient(g)
# s = win.GetScrollPosition()
# q = add_pt(l, s)
# print "ScrollableView.global_to_local: g =", g, "l =", l, "s =", s, "q =", q ###
# return q
def _win_update_scroll_sizes(self, extent):
ph = self.h_page_scroll_amount()
pv = self.v_page_scroll_amount()
ls = self.line_scroll_amount
self._win.SetScrollSizes(wc.MM_TEXT, extent, (ph, pv), ls)
def OnDraw(self, dc):
#print "ScrollableView.OnDraw" ###
update_rect = dc.GetClipBox()
canvas = Canvas._from_win_dc(dc)
self.draw(canvas, update_rect)
def _win_prepare_dc(self, dc, pinfo = None):
self._win.OnPrepareDC(dc, None)
+157
View File
@@ -0,0 +1,157 @@
#--------------------------------------------------------------------
#
# PyGUI - Slider - Win32
#
#--------------------------------------------------------------------
from __future__ import division
import win32con as wc, win32ui as ui
from GUI import export
from GUI.WinUtils import win_none
from GUI.GSliders import Slider as GSlider
win_base_flags = wc.WS_CHILD | wc.WS_VISIBLE
win_styles = {
'h': 0x0, # TBS_HORZ | TBS_BOTTOM
#'v': 0x6, # TBS_VERT | TBS_LEFT
'v': 0x2, # TBS_VERT | TBS_RIGHT
}
win_no_ticks = 0x10 # TBS_NOTICKS
win_continuous_range = 10000
class Slider(GSlider):
#_win_transparent = True
_default_breadth = 20
_min_value = 0.0
_max_value = 1.0
_discrete = False
_ticks = 0
_live = True
def __init__(self, orient, **kwds):
win = ui.CreateSliderCtrl()
win_flags = win_base_flags | win_no_ticks
try:
style = win_styles[orient]
except KeyError:
raise ValueError("Invalid Slider orientation %r" % orient)
l = self._default_length
b = self._default_breadth
if orient == 'h':
rect = (0, 0, l, b)
else:
rect = (0, 0, b, l)
win.CreateWindow(style | win_flags, rect, win_none, 0)
win.SetRange(0, win_continuous_range)
GSlider.__init__(self, _win = win, **kwds)
def get_value(self):
win = self._win
p = win.GetPos()
q = win.GetRangeMax()
x0 = self._min_value
x1 = self._max_value
return x0 + (x1 - x0) * p / q
def set_value(self, x):
win = self._win
x0 = self._min_value
x1 = self._max_value
q = win.GetRangeMax()
p = int(round(q * (x - x0) / (x1 - x0)))
self._win.SetPos(p)
def get_min_value(self):
return self._min_value
def set_min_value(self, x):
self._min_value = x
self._win_update_range()
def get_max_value(self):
return self._max_value
def set_max_value(self, x):
self._max_value = x
self._win_update_range()
def get_ticks(self):
return self._ticks
def set_ticks(self, n):
self._ticks = n
self._win_update_ticks()
def get_discrete(self):
return self._discrete
def set_discrete(self, d):
if self._discrete != d:
self._discrete = d
self._win_update_range()
def get_live(self):
return self._live
def set_live(self, x):
self._live = x
def _win_update_range(self):
if self._discrete:
x1 = max(0, self._ticks - 1)
else:
x1 = win_continuous_range
self._win.SetRange(0, x1)
self._win_update_ticks()
def _win_update_ticks(self):
#print "Slider._win_update_ticks" ###
win = self._win
n = self._ticks
if n >= 2:
if self._discrete:
f = 1
else:
f = int(round(win_continuous_range / (n - 1)))
win.ModifyStyle(win_no_ticks, 0)
win.ClearTics(False)
for i in xrange(n + 1):
win.SetTic(int(round(i * f)))
else:
win.ModifyStyle(0, win_no_ticks)
def _win_wm_scroll(self, code):
#print "Slider._win_wm_scroll:", code ###
if self._live:
report = code != 8
else:
report = code == 8
if report:
self.do_action()
def _win_on_ctlcolor(self, dc, typ):
#print "Slider._win_on_ctlcolor:", self ###
return self._win.OnCtlColor(dc, self._win, typ)
def key_down(self, event):
k = event.key
if k == 'left_arrow' or k == 'up_arrow':
self._nudge_value(-1)
elif k == 'right_arrow' or k == 'down_arrow':
self._nudge_value(1)
else:
GSlider.key_down(self, event)
def _nudge_value(self, d):
if not self.discrete:
d *= (win_continuous_range // 100)
win = self._win
p = win.GetPos()
win.SetPos(p + d)
self.do_action()
export(Slider)
+45
View File
@@ -0,0 +1,45 @@
#--------------------------------------------------------------------------
#
# Python GUI - Standard Cursors - Win32
#
#--------------------------------------------------------------------------
import win32con as wc, win32ui as ui
from GUI import Cursor
__all__ = [
'arrow',
'ibeam',
'crosshair',
'fist',
'hand',
'finger',
'invisible',
]
def win_get_std_cursor(id):
app = ui.GetApp()
win_app = getattr(app, '_win_app', app)
hcursor = win_app.LoadStandardCursor(id)
return Cursor._from_win_cursor(hcursor)
arrow = win_get_std_cursor(wc.IDC_ARROW)
ibeam = win_get_std_cursor(wc.IDC_IBEAM)
crosshair = win_get_std_cursor(wc.IDC_CROSS)
fist = Cursor("cursors/fist.tiff")
hand = Cursor("cursors/hand.tiff")
finger = win_get_std_cursor(wc.IDC_HAND)
invisible = Cursor._from_win_cursor(0)
def empty_cursor():
return invisible
# Win32 only
wait = win_get_std_cursor(wc.IDC_WAIT)
up_arrow = win_get_std_cursor(wc.IDC_UPARROW)
size_all = win_get_std_cursor(wc.IDC_SIZEALL)
size_w_e = win_get_std_cursor(wc.IDC_SIZEWE)
size_n_s = win_get_std_cursor(wc.IDC_SIZENS)
size_nw_se = win_get_std_cursor(wc.IDC_SIZENWSE)
size_ne_sw = win_get_std_cursor(wc.IDC_SIZENESW)
+37
View File
@@ -0,0 +1,37 @@
#--------------------------------------------------------------------
#
# PyGUI - Standard Fonts - Win32
#
#--------------------------------------------------------------------
from __future__ import division
import win32con as wc, win32gui as gui, win32ui as ui
from GUI import Font
from GUI.WinUtils import win_none
def _get_win_ppi():
dc = win_none.GetDC()
ppi = dc.GetDeviceCaps(wc.LOGPIXELSY)
win_none.ReleaseDC(dc)
return ppi
_win_ppi = _get_win_ppi()
def _win_pts_to_pixels(x):
return int(round(x * _win_ppi / 72))
def _win_stock_font(id):
h = gui.GetStockObject(id)
lf = gui.GetObject(h)
return Font._from_win_logfont(lf)
#system_font = _win_stock_font(wc.SYSTEM_FONT)
#system_font = _win_stock_font(17) # DEFAULT_GUI_FONT
#system_font = Font._from_win(win_none)
#system_font = Font("System", 13)
#system_font = Font("Tahoma", 10)
#system_font = Font("Tahoma", 11)
system_font = Font("Tahoma", _win_pts_to_pixels(8))
#print "StdFonts: System font ascent =", system_font.ascent
#print "StdFonts: System font descent =", system_font.descent
application_font = system_font
+53
View File
@@ -0,0 +1,53 @@
#--------------------------------------------------------------------
#
# PyGUI - Menus - Win32
#
#--------------------------------------------------------------------
from GUI.GStdMenus import build_menus, \
fundamental_cmds, help_cmds, pref_cmds, file_cmds, print_cmds, edit_cmds
_file_menu_items = [
("New/N", 'new_cmd'),
("Open.../O", 'open_cmd'),
("Close/W", 'close_cmd'),
"-",
("Save/S", 'save_cmd'),
("Save As...", 'save_as_cmd'),
("Revert", 'revert_cmd'),
"-",
("Page Setup...", 'page_setup_cmd'),
("Print.../P", 'print_cmd'),
"-",
("Exit/Q", 'quit_cmd'),
]
_edit_menu_items = [
("Undo/Z", 'undo_cmd'),
("Redo/^Z", 'redo_cmd'),
"-",
("Cut/X", 'cut_cmd'),
("Copy/C", 'copy_cmd'),
("Paste/V", 'paste_cmd'),
("Clear", 'clear_cmd'),
"-",
("Select All/A", 'select_all_cmd'),
"-",
("Preferences...", 'preferences_cmd'),
]
_help_menu_items = [
("About <app>", 'about_cmd'),
]
#------------------------------------------------------------------------------
def basic_menus(substitutions = {}, include = None, exclude = None):
return build_menus([
("File", _file_menu_items, False),
("Edit", _edit_menu_items, False),
("Help", _help_menu_items, True),
],
substitutions = substitutions,
include = include,
exclude = exclude)
+80
View File
@@ -0,0 +1,80 @@
#--------------------------------------------------------------------
#
# PyGUI - Task - Win32
#
#--------------------------------------------------------------------
from weakref import WeakValueDictionary
import win32con as wc, win32ui as ui
from GUI import export, application
from GUI.WinUtils import win_none
from GUI.GTasks import Task as GTask
#--------------------------------------------------------------------
class TimerWnd(object):
def __init__(self):
win = ui.CreateFrame()
win.CreateWindow(None, "", 0, (0, 0, 0, 0))
win.AttachObject(self)
self._win = win
self.tasks = WeakValueDictionary()
def schedule(self, task):
self.cancel(task)
event_id = id(task)
timer_id = self._win.SetTimer(event_id, task._milliseconds)
if not timer_id:
raise ValueError("Out of timers")
task._win_timer_id = timer_id
self.tasks[event_id] = task
def cancel(self, task):
timer_id = task._win_timer_id
if timer_id:
self._win.KillTimer(timer_id)
task._win_timer_id = None
def OnTimer(self, event_id):
#print "TimerWnd.OnTimer:", event_id
task = self.tasks.get(event_id)
if task:
if not task._repeat:
self.cancel(task)
task._proc()
# We do this so that the application can't get starved of idle time
# by a repeatedly-firing Task:
application()._win_idle()
timer_wnd = TimerWnd()
#--------------------------------------------------------------------
class Task(GTask):
_win_timer_id = 0
def __init__(self, proc, interval, repeat = False, start = True):
self._proc = proc
self._milliseconds = int(1000 * interval)
self._repeat = repeat
if start:
self.start()
def __del__(self, timer_wnd = timer_wnd):
timer_wnd.cancel(self)
def get_interval(self):
return self._milliseconds / 1000.0
def get_repeat(self):
return self._repeat
def start(self):
timer_wnd.schedule(self)
def stop(self):
timer_wnd.cancel(self)
export(Task)
+85
View File
@@ -0,0 +1,85 @@
#
# Python GUI - Text Editor - Win32
#
from __future__ import division
import win32con as wc, win32ui as ui
from GUI import export
from GUI.GTextEditors import TextEditor as GTextEditor
from GUI.WinUtils import win_none
from GUI.StdFonts import application_font
PFM_TABSTOPS = 0x10
MAX_TAB_STOPS = 32
LOGPIXELSX = 88
ui.InitRichEdit()
class TextEditor(GTextEditor):
_pass_key_events_to_platform = True
def __init__(self, scrolling = 'hv', **kwds):
win_style = ui.AFX_WS_DEFAULT_VIEW #| wc.WS_HSCROLL | wc.WS_VSCROLL
win = ui.CreateRichEditView()
ctl = win.GetRichEditCtrl()
self._win_ctl = ctl
if 'h' in scrolling:
win.SetWordWrap(0) # Must do before CreateWindow
win.CreateWindow(win_none, 1, win_style, (0, 0, 100, 100))
#if 'v' not in scrolling:
# Disabled because it doesn't work properly -- auto-scrolling is prevented
# but a vertical scroll bar still appears when text goes past bottom of window.
#ctl.SetOptions(wc.ECOOP_XOR, wc.ECO_AUTOVSCROLL) # Must do after CreateWindow
ctl.SetOptions(wc.ECOOP_XOR, wc.ECO_NOHIDESEL)
win.ShowScrollBar(wc.SB_BOTH, False)
# We allow automatic scroll bar show/hide -- resistance is futile
win.ShowWindow()
kwds.setdefault('font', application_font)
GTextEditor.__init__(self, _win = win, **kwds)
# self.tab_spacing = self.font.width("X") * 4 ###
def get_selection(self):
return self._win.GetSel()
def set_selection(self, value):
self._win.SetSel(*value)
def get_text(self):
return self._win.GetWindowText()
def set_text(self, text):
self._win.SetWindowText(text)
def get_text_length(self):
return self._win.GetTextLength()
def get_font(self):
return self._font
def set_font(self, x):
self._font = x
self._win.SetFont(x._win_font)
self.invalidate()
def get_tab_spacing(self):
pf = self._win_ctl.GetParaFormat()
tabs = pf[8]
if tabs:
return tabs[0] // 20
else:
return 36
def set_tab_spacing(self, x):
dc = self._win.GetDC()
dpi = dc.GetDeviceCaps(LOGPIXELSX)
mask = PFM_TABSTOPS
twips = 1440 * x / dpi
tabs = [int(round((i + 1) * twips)) for i in xrange(MAX_TAB_STOPS)]
pf = (mask, 0, 0, 0, 0, 0, 0, tabs)
old_sel = self.selection
self.select_all()
self._win_ctl.SetParaFormat(pf)
self.selection = old_sel
export(TextEditor)
+104
View File
@@ -0,0 +1,104 @@
#--------------------------------------------------------------------
#
# PyGUI - TextField - Win32
#
#--------------------------------------------------------------------
import win32con as wc, win32ui as ui
from GUI import export
from GUI.StdFonts import application_font
from GUI.WinUtils import win_none
from GUI.GTextFields import TextField as GTextField
win_vpad = 5
win_style = wc.WS_VISIBLE | wc.WS_CLIPSIBLINGS | wc.ES_AUTOHSCROLL # | wc.WS_TABSTOP
win_ex_style = wc.WS_EX_CLIENTEDGE
win_multiline_style = wc.ES_MULTILINE | wc.ES_AUTOVSCROLL
win_password_style = wc.ES_PASSWORD
win_just_mask = wc.ES_LEFT | wc.ES_CENTER | wc.ES_RIGHT
win_just_flags = {
'l': wc.ES_LEFT,
'c': wc.ES_CENTER,
'r': wc.ES_RIGHT,
}
class TextField(GTextField):
_pass_key_events_to_platform = True
def __init__(self, **kwds):
font = kwds.setdefault('font', application_font)
multiline = kwds.setdefault('multiline', False)
password = kwds.pop('password', False)
self._multiline = multiline
self._password = password
h = self._calc_height(font)
flags = win_style
if multiline:
flags |= win_multiline_style
if password:
flags |= win_password_style
win = ui.CreateEdit()
# Border can get lost if we construct it with too big a rect, so
# we set the initial size after creation.
win.CreateWindow(flags, (0, 0, 0, 0), win_none, 0)
win.ModifyStyleEx(0, win_ex_style)
win.MoveWindow((0, 0, 100, h))
GTextField.__init__(self, _win = win, **kwds)
def get_text(self):
return self._win.GetWindowText().replace("\r\n", "\n")
def set_text(self, x):
self._win.SetWindowText(x.replace("\n", "\r\n"))
def set_just(self, x):
self._just = x
try:
flags = win_just_flags[x[:1]]
except KeyError:
raise ValueError("Invalid TextField justification %r" % x)
self._win.ModifyFlags(win_just_mask, flags)
def get_selection(self):
sel = self._win.GetSel()
if self._multiline:
sel = self._win_adjust_sel(sel, -1)
return sel
def set_selection(self, sel):
if self._multiline:
sel = self._win_adjust_sel(sel, 1)
self._win.SetSel(*sel)
self.become_target()
def _win_adjust_sel(self, sel, d):
text = self._win.GetWindowText()
if d > 0:
text = text.replace("\r\n", "\n")
nl = "\n"
else:
nl = "\r\n"
def adj(x):
return x + d * text.count(nl, 0, x)
return map(adj, sel)
def get_multiline(self):
return self._multiline
def get_password(self):
return self._password
def _tab_in(self):
self.select_all()
def key_down(self, event):
#print "TextField.key_down" ###
if event.char == "\t":
self.pass_event_to_next_handler(event)
else:
GTextField.key_down(self, event)
export(TextField)
+24
View File
@@ -0,0 +1,24 @@
#--------------------------------------------------------------------
#
# PyGUI - View - Win32
#
#--------------------------------------------------------------------
import win32con as wc, win32ui as ui
from GUI import export
from GUI.WinUtils import win_none
from GUI.GViews import View as GView
win_style = wc.WS_VISIBLE
win_default_rect = (0, 0, GView._default_size[0], GView._default_size[1])
class View(GView):
def __init__(self, **kwds):
win = ui.CreateWnd()
win.CreateWindow(None, None, win_style, win_default_rect,
win_none, 0)
GView.__init__(self, _win = win)
self.set(**kwds)
export(View)
+56
View File
@@ -0,0 +1,56 @@
#--------------------------------------------------------------------
#
# PyGUI - ViewBase - Win32
#
#--------------------------------------------------------------------
import win32gui as gui
from GUI import export
from GUI import application
from GUI.GViewBases import ViewBase as GViewBase
class ViewBase(GViewBase):
_win_captures_mouse = True
_cursor = None
# def track_mouse(self):
# #print "ViewBase.track_mouse: enter" ###
# self._win_tracking_mouse = True
# try:
# while 1:
# application().event_loop()
# event = self._win_mouse_event
# yield event
# if event.kind == 'mouse_up':
# break
# finally:
# self._win_tracking_mouse = False
# #print "ViewBase.track_mouse: exit" ###
def track_mouse(self):
self._win_tracking_mouse = True
while 1:
application().event_loop()
event = self._win_mouse_event
yield event
if event.kind == 'mouse_up':
break
self._win_tracking_mouse = False
def get_cursor(self):
return self._cursor
def set_cursor(self, c):
self._cursor = c
def OnSetCursor(self, wnd, hit, message):
if hit == 1: # HTCLIENT
cursor = self._cursor
if cursor:
gui.SetCursor(cursor._win_cursor)
return
self._win.OnSetCursor(wnd._win, hit, message)
export(ViewBase)
+22
View File
@@ -0,0 +1,22 @@
#------------------------------------------------------------------------------
#
# PyGUI - WGL - Win32
#
#------------------------------------------------------------------------------
from ctypes import *
gdi32 = windll.gdi32
def SetPixelFormat(hdc, ipf):
gdi32.SetPixelFormat(hdc, ipf, None)
def attr_array(d):
a = []
for k, v in d.iteritems():
a.append(k)
a.append(v)
a.append(0)
return a
def attr_dict(keys, values):
return dict(zip(keys, values))
+37
View File
@@ -0,0 +1,37 @@
#--------------------------------------------------------------------
#
# PyGUI - Win32 - ComboBox
#
#--------------------------------------------------------------------
import win32ui as ui, win32con as wc, win32gui as gui
class ComboBox(object):
def __init__(self, parent, pos, size, style = wc.CBS_DROPDOWNLIST):
parent_hwnd = parent.GetSafeHwnd()
self.hwnd = gui.CreateWindow("COMBOBOX", "Blarg",
wc.WS_CHILD | wc.CBS_DROPDOWNLIST,
pos[0], pos[1], size[0], size[1],
parent_hwnd, 0, 0, None)
self.pycwnd = ui.CreateWindowFromHandle(self.hwnd)
print "ComboBox: pycwnd =", self.pycwnd ###
def __del__(self):
gui.DestroyWindow(self.hwnd)
def ShowWindow(self):
gui.ShowWindow(self.hwnd, wc.SW_SHOW)
def AddString(self, text):
print "ComboBox: Adding string %r" % text ###
gui.SendMessage(self.hwnd, wc.CB_ADDSTRING, 0, text)
def CreateComboBox(parent, pos, size, style = wc.CBS_DROPDOWNLIST):
parent_hwnd = parent.GetSafeHwnd()
hwnd = gui.CreateWindow("COMBOBOX", "Blarg",
wc.WS_CHILD | wc.CBS_DROPDOWNLIST,
pos[0], pos[1], size[0], size[1],
parent_hwnd, 0, 0, None)
return ui.CreateWindowFromHandle(hwnd)
+109
View File
@@ -0,0 +1,109 @@
#--------------------------------------------------------------------
#
# PyGUI - Event utilities - Win32
#
#--------------------------------------------------------------------
import win32con as wc, win32api as api, win32gui as gui, win32ui as ui
from GUI import Event
win_message_map = {
wc.WM_KEYDOWN: ('key_down', None),
wc.WM_KEYUP: ('key_up', None),
wc.WM_SYSKEYDOWN: ('key_down', None),
wc.WM_SYSKEYUP: ('key_up', None),
wc.WM_MOUSEMOVE: ('mouse_move', None),
wc.WM_LBUTTONDOWN: ('mouse_down', 'left'),
wc.WM_LBUTTONDBLCLK: ('mouse_down', 'left'),
wc.WM_LBUTTONUP: ('mouse_up', 'left'),
wc.WM_MBUTTONDOWN: ('mouse_down', 'middle'),
wc.WM_MBUTTONDBLCLK: ('mouse_down', 'middle'),
wc.WM_MBUTTONUP: ('mouse_up', 'middle'),
wc.WM_RBUTTONDOWN: ('mouse_down', 'right'),
wc.WM_RBUTTONDBLCLK: ('mouse_down', 'right'),
wc.WM_RBUTTONUP: ('mouse_up', 'right'),
}
win_special_keys = {
0x70: 'f1',
0x71: 'f2',
0x72: 'f3',
0x73: 'f4',
0x74: 'f5',
0x75: 'f6',
0x76: 'f7',
0x77: 'f8',
0x78: 'f9',
0x79: 'f10',
0x7a: 'f11',
0x7b: 'f12',
0x91: 'f14',
0x13: 'f15',
#0x2d: 'help',
0x2d: 'insert',
0x2e: 'delete',
0x24: 'home',
0x23: 'end',
0x21: 'page_up',
0x22: 'page_down',
0x25: 'left_arrow',
0x27: 'right_arrow',
0x26: 'up_arrow',
0x28: 'down_arrow',
}
win_button_flags = wc.MK_LBUTTON | wc.MK_MBUTTON | wc.MK_RBUTTON
win_prev_key_state = 1 << 30
win_last_mouse_down = None
win_dbl_time = gui.GetDoubleClickTime() / 1000.0 # 0.25
win_dbl_xdist = api.GetSystemMetrics(wc.SM_CXDOUBLECLK)
win_dbl_ydist = api.GetSystemMetrics(wc.SM_CYDOUBLECLK)
def win_message_to_event(message, target = None):
hwnd, msg, wParam, lParam, milliseconds, gpos = message
kind, button = win_message_map[msg]
time = milliseconds / 1000.0
if kind == 'mouse_move' and wParam & win_button_flags <> 0:
kind = 'mouse_drag'
if target:
lpos = target.global_to_local(gpos)
else:
lpos = gpos
event = Event()
event.kind = kind
event.global_position = gpos
event.position = lpos
event.time = time
event.button = button
shift = api.GetKeyState(wc.VK_SHIFT) & 0x80 <> 0
control = api.GetKeyState(wc.VK_CONTROL) & 0x80 <> 0
option = api.GetKeyState(wc.VK_MENU) & 0x80 <> 0
event.shift = event.extend_contig = shift
event.control = event.extend_noncontig = control
event.option = option
vkey = None
if kind == 'mouse_down':
global win_last_mouse_down
last = win_last_mouse_down
if last and last.button == button and time - last.time <= win_dbl_time:
x0, y0 = last.global_position
x1, y1 = gpos
if abs(x1 - x0) <= win_dbl_xdist and abs(y1 - y0) <= win_dbl_ydist:
event.num_clicks = last.num_clicks + 1
win_last_mouse_down = event
elif kind == 'key_down' or kind == 'key_up':
event.unichars = ui.TranslateVirtualKey(wParam)
event.char = event.unichars.decode('ascii')
event._keycode = wParam
if wParam == 0x0d:
if (lParam & 0x1000000):
event.key = 'enter'
else:
event.key = 'return'
else:
event.key = win_special_keys.get(wParam) or event.char
if kind == 'key_down':
event.auto = lParam & win_prev_key_state <> 0
return event
+62
View File
@@ -0,0 +1,62 @@
#--------------------------------------------------------------------
#
# PyGUI - Menu utilities - Win32
#
#--------------------------------------------------------------------
from weakref import WeakKeyDictionary, WeakValueDictionary
import win32con as wc, win32ui as ui
from GUI import application
win_command_map = {}
win_command_list = []
def win_command_to_id(name, index = None):
if index is not None:
key = (name, index)
else:
key = name
id = win_command_map.get(key)
if not id:
id = len(win_command_list) + 1
win_command_map[key] = id
win_command_list.append(key)
application()._win_app.HookCommandUpdate(win_command_update, id)
return id
def win_command_update(cmd):
win_menu = cmd.m_pMenu
if win_menu:
menu = win_get_menu_for_hmenu(win_menu.GetHandle())
if menu:
item = menu._get_flat_item(cmd.m_nIndex)
cmd.Enable(item.enabled)
cmd.SetCheck(bool(item.checked))
def win_id_to_command(id):
if 1 <= id <= len(win_command_list):
return win_command_list[id - 1]
win_hmenu_to_menubar = WeakValueDictionary()
def win_get_menu_for_hmenu(hmenu):
menubar = win_hmenu_to_menubar.get(hmenu)
if menubar:
return menubar.hmenu_to_menu.get(hmenu)
#--------------------------------------------------------------------
class MenuBar(object):
# Wrapper around a PyCMenu
def __init__(self):
self.win_menu = ui.CreateMenu()
self.hmenu_to_menu = {}
def append_menu(self, menu):
win_menu = menu._win_create_menu()
hmenu = win_menu.Detach()
self.win_menu.AppendMenu(wc.MF_POPUP | wc.MF_STRING, hmenu, menu.title)
win_hmenu_to_menubar[hmenu] = self
self.hmenu_to_menu[hmenu] = menu
+168
View File
@@ -0,0 +1,168 @@
#------------------------------------------------------------------------------
#
# PyGUI - Win32 API - Page setup dialog
#
#------------------------------------------------------------------------------
from ctypes import *
from ctypes.wintypes import *
comdlg32 = windll.comdlg32
kernel32 = windll.kernel32
CCHDEVICENAME = 32
CCHFORMNAME = 32
PSD_MARGINS = 0x2
PSD_INTHOUSANDTHSOFINCHES = 0x4
PSD_RETURNDEFAULT = 0x400
LPPAGESETUPHOOK = c_void_p
LPPAGEPAINTHOOK = c_void_p
class PAGESETUPDLG(Structure):
_fields_ = [
('lStructSize', DWORD),
('hwndOwner', HWND),
('hDevMode', HGLOBAL),
('hDevNames', HGLOBAL),
('Flags', DWORD),
('ptPaperSize', POINT),
('rtMinMargin', RECT),
('rtMargin', RECT),
('hInstance', HINSTANCE),
('lCustData', LPARAM),
('lpfnPageSetupHook', LPPAGESETUPHOOK),
('lpfnPagePaintHook', LPPAGEPAINTHOOK),
('lpPageSetupTemplateName', LPCSTR),
('hPageSetupTemplate', HGLOBAL),
]
def __del__(self):
print "PAGESETUPDLG.__del__" ###
GlobalFree(self.hDevMode)
GlobalFree(self.hDevNames)
class DEVMODE(Structure):
_fields_ = [
('dmDeviceName', c_char * CCHDEVICENAME),
('dmSpecVersion', WORD),
('dmDriverVersion', WORD),
('dmSize', WORD),
('dmDriverExtra', WORD),
('dmFields', DWORD),
('dmOrientation', c_short),
('dmPaperSize', c_short),
('dmPaperLength', c_short),
('dmPaperWidth', c_short),
('dmScale', c_short),
('dmCopies', c_short),
('dmDefaultSource', c_short),
('dmPrintQuality', c_short),
('dmColor', c_short),
('dmDuplex', c_short),
('dmYResolution', c_short),
('dmTTOption', c_short),
('dmCollate', c_short),
('dmFormName', c_char * CCHFORMNAME),
('dmLogPixels', WORD),
('dmBitsPerPel', DWORD),
('dmPelsWidth', DWORD),
('dmPelsHeight', DWORD),
('dmDisplayFlags', DWORD),
('dmDisplayFrequency', DWORD),
('dmICMMethod', DWORD),
('dmICMIntent', DWORD),
('dmMediaType', DWORD),
('dmDitherType', DWORD),
('dmReserved1', DWORD),
('dmReserved2', DWORD),
('dmPanningWidth', DWORD),
('dmPanningHeight', DWORD),
]
class DEVNAMES(Structure):
_fields_ = [
('wDriverOffset', WORD),
('wDeviceOffset', WORD),
('wOutputOffset', WORD),
('wDefault', WORD),
]
_PageSetupDlg = comdlg32.PageSetupDlgA
_PageSetupDlg.argtypes = [POINTER(PAGESETUPDLG)]
GlobalAlloc = kernel32.GlobalAlloc
GlobalAlloc.argtypes = [UINT, DWORD]
GlobalSize = kernel32.GlobalSize
GlobalSize.argtypes = [HGLOBAL]
GlobalLock = kernel32.GlobalLock
GlobalLock.argtypes = [HGLOBAL]
GlobalUnlock = kernel32.GlobalUnlock
GlobalUnlock.argtypes = [HGLOBAL]
GlobalFree = kernel32.GlobalFree
GlobalFree.argtypes = [HGLOBAL]
def PageSetupDlg(psd):
psd.Flags = PSD_INTHOUSANDTHSOFINCHES | PSD_MARGINS
return bool(_PageSetupDlg(psd))
def get_handle_contents(h):
n = GlobalSize(h)
p = GlobalLock(h)
data = string_at(p, n)
GlobalUnlock(h)
return data
def handle_with_contents(data):
n = len(data)
h = GlobalAlloc(n)
p = GlobalLock(h)
memmove(p, data, n)
GlobalUnlock(h)
return h
def lock_devmode_handle(h):
p = c_void_p(GlobalLock(h))
dmp = cast(p, POINTER(DEVMODE))
return dmp[0]
class DevNames(object):
def __init__(self, hdevnames):
a = GlobalLock(hdevnames)
p = c_void_p(a)
dnp = cast(p, POINTER(DEVNAMES))
dn = dnp[0]
self.driver = c_char_p(a + dn.wDriverOffset).value
self.device = c_char_p(a + dn.wDeviceOffset).value
self.output = c_char_p(a + dn.wOutputOffset).value
self.default = dn.wDefault
GlobalUnlock(hdevnames)
def get_defaults():
psd = PAGESETUPDLG()
psd.lStructSize = sizeof(PAGESETUPDLG)
psd.Flags = PSD_INTHOUSANDTHSOFINCHES | PSD_RETURNDEFAULT
_PageSetupDlg(psd)
return psd
if __name__ == "__main__":
def dump_psd(header, psd):
print "%s:" % header, psd
for name, _ in PAGESETUPDLG._fields_:
print " %s = %r" % (name, getattr(psd, name))
psd = PAGESETUPDLG()
psd.lStructSize = sizeof(PAGESETUPDLG)
dump_psd("Initial psd", psd)
result = _PageSetupDlg(psd)
print "Result:", result
dump_psd("Final psd", psd)
#print "DevMode:", repr(get_handle_contents(psd.hDevMode)[:sizeof(DEVMODE)])
dm = lock_devmode_handle(psd.hDevMode)
print "dmDeviceName:", dm.dmDeviceName
#print "DevNames:", repr(get_handle_contents(psd.hDevNames))
+129
View File
@@ -0,0 +1,129 @@
#------------------------------------------------------------------------------
#
# PyGUI - Win32 API - Printing
#
#------------------------------------------------------------------------------
from ctypes import *
from ctypes.wintypes import *
comdlg32 = windll.comdlg32
gdi32 = windll.gdi32
PD_ALLPAGES = 0x0
PD_RETURNDC = 0x100
LOGPIXELSX = 88
LOGPIXELSY = 90
PHYSICALOFFSETX = 112
PHYSICALOFFSETY = 113
LPDWORD = POINTER(DWORD)
LPHANDLE = POINTER(HANDLE)
LPPOINT = POINTER(POINT)
LPPRINTHOOKPROC = c_void_p
LPSETUPHOOKPROC = c_void_p
ABORTPROC = CFUNCTYPE(c_int, HDC, c_int)
LPPRINTER_DEFAULTS = c_void_p
class PRINTDLG(Structure):
_pack_ = 2
_fields_ = [
('lStructSize', DWORD),
('hwndOwner', HWND),
('hDevMode', HGLOBAL),
('hDevNames', HGLOBAL),
('hDC', HDC),
('Flags', DWORD),
('nFromPage', WORD),
('nToPage', WORD),
('nMinPage', WORD),
('nMaxPage', WORD),
('nCopies', WORD),
('hInstance', HINSTANCE),
('lCustData', LPARAM),
('lpfnPrintHook', LPPRINTHOOKPROC),
('lpfnSetupHook', LPSETUPHOOKPROC),
('lpPrintTemplateName', LPCSTR),
('lpSetupTemplateName', LPCSTR),
('hPrintTemplate', HGLOBAL),
('hSetupTemplate', HGLOBAL),
]
def __init__(self):
self.lStructSize = sizeof(PRINTDLG)
class DOCINFO(Structure):
_fields_ = [
('cbSize', c_int),
('lpszDocName', LPCSTR),
('lpszOutput', LPCSTR),
('lpszDatatype', LPCSTR),
('fwType', DWORD),
]
def __init__(self):
self.cbSize = sizeof(DOCINFO)
class FORM_INFO_1_W(Structure):
_fields_ = [
('Flags', DWORD),
('pName', LPWSTR),
('Size', SIZEL),
('ImageableArea', RECTL),
]
_PrintDlg = comdlg32.PrintDlgA
_PrintDlg.argtypes = [POINTER(PRINTDLG)]
SetAbortProc = gdi32.SetAbortProc
SetAbortProc.argtypes = [HDC, ABORTPROC]
StartDoc = gdi32.StartDocA
StartDoc.argtypes = [HDC, POINTER(DOCINFO)]
StartPage = gdi32.StartPage
StartPage.argtypes = [HDC]
EndPage = gdi32.EndPage
EndPage.argtypes = [HDC]
EndDoc = gdi32.EndDoc
EndDoc.argtypes = [HDC]
DeleteDC = gdi32.DeleteDC
DeleteDC.argtypes = [HDC]
CommDlgExtendedError = comdlg32.CommDlgExtendedError
CommDlgExtendedError.argtypes = []
def PrintDlg(pd):
pd.nFromPage = pd.nMinPage
pd.nToPage = pd.nMaxPage
pd.Flags = PD_RETURNDC
#if pd.nMaxPage > pd.nMinPage:
# pd.Flags |= PD_PAGENUMS
result = _PrintDlg(pd)
if result == 0:
err = CommDlgExtendedError()
if err <> 0:
raise EnvironmentError("Common Dialog error %s" % err)
return bool(result)
def GetPrintingOffset(hdc):
dpix = gdi32.GetDeviceCaps(hdc, LOGPIXELSX)
dpiy = gdi32.GetDeviceCaps(hdc, LOGPIXELSY)
offx = gdi32.GetDeviceCaps(hdc, PHYSICALOFFSETX)
offy = gdi32.GetDeviceCaps(hdc, PHYSICALOFFSETY)
return 72.0 * offx / dpix, 72.0 * offy / dpiy
def abort_proc(hdc, err):
return printing_aborted
def install_abort_proc(hdc):
global printing_aborted
printing_aborted = False
SetAbortProc(hdc, ABORTPROC(abort_proc))
+149
View File
@@ -0,0 +1,149 @@
#--------------------------------------------------------------------
#
# PyGUI - Win32 - Utilities
#
#--------------------------------------------------------------------
import win32con as wc, win32ui as ui, win32gui as gui, win32api as api
from win32api import HIWORD, LOWORD
from GUI import application
from GUI.Exceptions import Cancel, InternalError
win_dlog_class = "#32770"
win_color3dhilight = api.GetSysColor(wc.COLOR_3DHILIGHT)
win_color3dlight = api.GetSysColor(wc.COLOR_3DLIGHT)
win_color3dface = api.GetSysColor(wc.COLOR_3DFACE)
win_color3dshadow = api.GetSysColor(wc.COLOR_3DSHADOW)
win_menubar_height = api.GetSystemMetrics(wc.SM_CYMENU)
win_bg_color = api.GetSysColor(wc.COLOR_3DFACE)
win_screen_width = api.GetSystemMetrics(wc.SM_CXFULLSCREEN)
win_screen_height = api.GetSystemMetrics(wc.SM_CYFULLSCREEN)
win_screen_rect = (0, 0, win_screen_width, win_screen_height)
#win_bg_brush = ui.CreateBrush(wc.BS_SOLID, win_color3dface, 0)
#win_bg_hbrush = win_bg_brush.GetSafeHandle()
# An empty brush for not painting anything with
win_null_brush = ui.CreateBrush(wc.BS_NULL, 0, 0)
win_null_hbrush = win_null_brush.GetSafeHandle()
# All components hook the following messages
win_event_messages = (
wc.WM_KEYDOWN, wc.WM_KEYUP,
wc.WM_SYSKEYDOWN, wc.WM_SYSKEYUP,
wc.WM_MOUSEMOVE,
wc.WM_LBUTTONDOWN, wc.WM_LBUTTONDBLCLK, wc.WM_LBUTTONUP,
wc.WM_MBUTTONDOWN, wc.WM_MBUTTONDBLCLK, wc.WM_MBUTTONUP,
wc.WM_RBUTTONDOWN, wc.WM_RBUTTONDBLCLK, wc.WM_RBUTTONUP,
#wc.WM_MOUSELEAVE,
)
# Dummy CWnd for use as parent of containerless components.
# Also used as the main frame of the CWinApp.
win_none = ui.CreateFrame()
win_none.CreateWindow(None, "", 0, (0, 0, 10, 10))
win_plain = ui.CreateWnd()
win_plain.CreateWindow(None, None, 0, (0, 0, 10, 10), win_none, 0)
win_plain_class = gui.GetClassName(win_plain.GetSafeHwnd())
#--------------------------------------------------------------------
win_command_map = {
0: '_win_bn_clicked', # BN_CLICKED
wc.CBN_SELCHANGE: '_cbn_sel_change',
}
class WinMessageReflector(object):
def _win_install_event_hooks(self, win):
win.HookMessage(self._win_wm_scroll, wc.WM_HSCROLL)
win.HookMessage(self._win_wm_scroll, wc.WM_VSCROLL)
#
# Disabled for now because overriding control colours
# doesn't seem to work properly on XP.
#
# def OnCtlColor(self, dc, comp, typ):
# #print "WinMessageReflector.OnCtlColor" ###
# meth = getattr(comp, '_win_on_ctlcolor', None)
# if meth:
# return meth(dc, typ)
def _win_wm_scroll(self, message):
#print "WinMessageReflector._win_wm_scroll:", self, message ###
wParam = message[2]
code = wParam & 0xffff
lParam = message[3]
self._forward_reflected_message(lParam, '_win_wm_scroll', code)
def OnCommand(self, wParam, lParam):
#print "WinMessageReflector.OnCommand: code = 0x%04x 0x%04x lParam = 0x%08x" % (
# HIWORD(wParam), LOWORD(wParam), lParam)
try:
code = HIWORD(wParam)
id = LOWORD(wParam)
if id:
self._win_menu_command(id)
else:
name = win_command_map.get(code)
if name:
self._forward_reflected_message(lParam, name)
except Cancel:
pass
except:
application().report_error()
def _forward_reflected_message(self, lParam, method_name, *args):
wnd = ui.CreateWindowFromHandle(lParam)
meth = getattr(wnd, method_name, None)
if meth:
meth(*args)
def _win_menu_command(self, id):
raise InternalError("_win_menu_command called on non-window: %r" % self)
win_none_wrapper = WinMessageReflector()
win_none_wrapper._win = win_none
win_none_wrapper._win_install_event_hooks(win_none)
win_none.AttachObject(win_none_wrapper)
#--------------------------------------------------------------------
#
# Debugging routines
#
win_message_names = {}
win_exclude_names = ["WM_MOUSEFIRST"]
for name, value in wc.__dict__.iteritems():
if name.startswith("WM_") and name not in win_exclude_names:
win_message_names[value] = name
def win_message_name(num):
return win_message_names.get(num) or num
def dump_flags(flags):
for name in wc.__dict__.iterkeys():
if name.startswith("WS_") and not name.startswith("WS_EX"):
value = wc.__dict__[name]
if flags & value:
print "%20s = 0x%08x" % (name, value & 0xffffffffL)
def win_deconstruct_style(flags):
win_do_deconstruct_style(flags, "WS_", "WS_EX_")
def win_deconstruct_style_ex(flags):
win_do_deconstruct_style(flags, "WS_EX_")
def win_do_deconstruct_style(flags, prefix, not_prefix = None):
d = wc.__dict__
for name in d.iterkeys():
if name.startswith(prefix):
if not not_prefix or not name.startswith(not_prefix):
value = d[name]
if value and flags & value == value:
print "%25s 0x%08x" % (name, value)
+343
View File
@@ -0,0 +1,343 @@
#--------------------------------------------------------------------
#
# PyGUI - Window - Win32
#
#--------------------------------------------------------------------
import win32con as wc, win32ui as ui, win32gui as gui, win32api as api
from GUI import export
from GUI import WinUtils
from GUI.Geometry import rect_size, sub_pt
from GUI import application
from GUI.Exceptions import Cancel
from GUI.WinEvents import win_message_to_event
from GUI.WinMenus import MenuBar, win_id_to_command
from GUI.GMenus import search_list_for_key
from GUI import Component
from GUI.GWindows import Window as GWindow
#--------------------------------------------------------------------
capabilities = ('hidable', 'zoomable', 'resizable', 'movable', 'closable')
win_defaults = {
'standard': (1, 1, 1, 1, 1),
'nonmodal_dialog': (1, 0, 0, 1, 1),
'modal_dialog': (0, 0, 0, 1, 1),
'alert': (0, 0, 0, 1, 1),
'fullscreen': (0, 0, 0, 0, 0),
}
win_base_flags = wc.WS_CLIPCHILDREN
win_border_flags = wc.WS_DLGFRAME
win_capability_flags = {
'hidable': wc.WS_MINIMIZEBOX | wc.WS_SYSMENU,
'zoomable': wc.WS_MAXIMIZEBOX | wc.WS_SYSMENU,
'resizable': wc.WS_THICKFRAME,
'movable': wc.WS_BORDER,
'closable': wc.WS_SYSMENU,
}
win_no_menu_styles = ('nonmodal_dialog', 'modal_dialog',
'alert', 'fullscreen')
win_ex_flags = 0 #wc.WS_EX_WINDOWEDGE
win_no_ex_flags = wc.WS_EX_CLIENTEDGE
def win_calculate_flags(style, kwds):
# Calculate window flags from the options present in kwds, and
# fill in kwds with default values for missing options that need
# to be passed to the base class constructor.
flags = win_base_flags
if style != 'fullscreen':
flags |= win_border_flags
try:
defaults = win_defaults[style]
except KeyError:
raise ValueError("Invalid window style '%s'" % style)
for name, default in zip(capabilities, defaults):
value = kwds.pop(name, default)
if name == 'closable':
kwds[name] = value
if value:
flags |= win_capability_flags[name]
return flags
#def win_adjust_flags(flags, kwds, option_name, opt_flags):
# option = kwds.pop(option_name, None)
# if option is not None:
# if option:
# flags |= opt_flags
# else:
# flags &= ~opt_flags
# return flags
def win_next_wnd(wnd):
wnd = getattr(wnd, '_win', wnd)
#print "win_next_wnd:", wnd ###
return wnd.GetWindow(wc.GW_HWNDNEXT)
#--------------------------------------------------------------------
class Window(GWindow):
_win_hooks_events = True
_win_has_menubar = True
_win_captures_mouse = True
_win_need_menubar_update = True
_win_saved_target = False
_win_fullscreen = False
def __init__(self, **kwds):
style = kwds.get('style', 'standard')
flags = win_calculate_flags(style, kwds)
#if style == 'fullscreen':
# rect = WinUtils.win_screen_rect
#else:
rect = (0, 0, self._default_width, self._default_height)
frame = ui.CreateFrame()
frame.CreateWindow(None, "New Window", 0, rect)
hwnd = frame.GetSafeHwnd()
#api.SetClassLong(hwnd, wc.GCL_HBRBACKGROUND, win_bg_hbrush)
api.SetClassLong(hwnd, wc.GCL_HBRBACKGROUND, 0)
# print "Window: Setting style:" ###
# win_deconstruct_style(flags) ###
frame.ModifyStyle(-1, flags)
# print "Window: Style is now:" ###
# win_deconstruct_style(frame.GetStyle()) ###
frame.ModifyStyleEx(win_no_ex_flags, win_ex_flags)
if style == 'fullscreen':
self._win_fullscreen = True
frame.HookMessage(self._win_wm_initmenu, wc.WM_INITMENU)
self._win = frame
if style in win_no_menu_styles:
self._win_has_menubar = False
else:
self._win_set_empty_menubar()
kwds['closable'] = flags & wc.WS_CAPTION <> 0
GWindow.__init__(self, _win = frame, **kwds)
def OnPaint(self):
win = self._win
dc, ps = win.BeginPaint()
rect = win.GetClientRect()
dc.FillSolidRect(rect, WinUtils.win_bg_color)
if self._win_has_menubar:
l, t, r, b = rect
dc.Draw3dRect((l, t, r + 1, t + 2),
WinUtils.win_color3dshadow, WinUtils.win_color3dhilight)
win.EndPaint(ps)
def _win_install_event_hooks(self):
self._win.HookMessage(self._wm_activate, wc.WM_ACTIVATE)
#self._win.HookMessage(self._wm_setfocus, wc.WM_SETFOCUS)
self._win.HookMessage(self._wm_windowposchanging, wc.WM_WINDOWPOSCHANGING)
self._win.HookMessage(self._wm_windowposchanged, wc.WM_WINDOWPOSCHANGED)
GWindow._win_install_event_hooks(self)
def _wm_activate(self, msg):
wParam = msg[2]
#print "Window._wm_activate:", msg ###
#print "...wParam =", wParam ###
if wParam == wc.WA_INACTIVE:
#print "Window: Deactivating:", self ###
try:
target = ui.GetFocus()
#print "...target =", target ###
except ui.error, e:
#print "...no target", e ###
target = None
if isinstance(target, Component) and target is not self:
#print "...saving target", target ###
self._win_saved_target = target
def _win_wm_setfocus(self, msg):
#print "Window._win_wm_setfocus:", self ###
target = self._win_saved_target
if target and target.window == self:
#print "...restoring target", target ###
target._win.SetFocus()
self._win_saved_target = None
else:
GWindow._win_wm_setfocus(self, msg)
def get_target(self):
if self._win_is_active():
try:
target = ui.GetFocus()
except ui.error:
target = None
if target and isinstance(target, Component):
return target
return self._saved_target or self
def _win_is_active(self):
try:
active_win = ui.GetActiveWindow()
except ui.error:
active_win = None
return active_win is self
# def _wm_setfocus(self, *args):
# print "Window._wm_setfocus:", args ###
def _wm_windowposchanging(self, message):
#print "Window._wm_windowposchanging"
self._win_old_size = rect_size(self._bounds)
#print "...old size =", self._win_old_size
def _wm_windowposchanged(self, message):
#print "Window._wm_windowposchanged"
old_size = self._win_old_size
new_bounds = self._win_get_actual_bounds()
self._bounds = new_bounds
new_size = rect_size(new_bounds)
#print "...new size =", new_size
if old_size != new_size:
self._resized(sub_pt(new_size, old_size))
def _win_set_empty_menubar(self):
# A completely empty menu bar collapses to zero height, and
# controlling the window bounds is too complicated if the
# menu bar comes and goes, so we add a dummy item to it.
menubar = MenuBar()
menubar.win_menu.AppendMenu(0, 0, "")
self._win.SetMenu(menubar.win_menu)
self._win_menubar = menubar
def get_title(self):
return self._win.GetWindowText()
def set_title(self, x):
self._win.SetWindowText(x)
def get_visible(self):
return self._win.IsWindowVisible()
def set_visible(self, x):
#print "Window.set_visible:", x, self ###
if x:
self._win_update_menubar()
self._win.ShowWindow()
else:
self._win.ShowWindow(wc.SW_HIDE)
def _show(self):
self._win_update_menubar()
win = self._win
if self._win_fullscreen:
win.ShowWindow(wc.SW_SHOWMAXIMIZED)
# win.SetWindowPos(wc.HWND_TOP, (0, 0, 0, 0),
# wc.SWP_NOMOVE | wc.SWP_NOSIZE | wc.SWP_SHOWWINDOW)
win.ShowWindow(wc.SW_SHOWNORMAL)
win.SetActiveWindow()
# def get_bounds(self):
# win = self._win
# r = win.ClientToScreen(win.GetClientRect())
# return r
def _win_get_actual_bounds(self):
win = self._win
return win.ClientToScreen(win.GetClientRect())
def _win_move_window(self, rect):
win = self._win
l, t, r, b = win.CalcWindowRect(rect)
if self._win_has_menubar:
t -= WinUtils.win_menubar_height
self._win.MoveWindow((l, t, r, b))
def set_menus(self, x):
GWindow.set_menus(self, x)
self._win_menus_changed()
def _stagger(self):
#print "Window._stagger:", self ###
win = win_next_wnd(self._win)
while win and not (isinstance(win, Window) and win.visible):
#print "...win =", win ###
win = win_next_wnd(win)
if win:
l, t, r, b = win._win.GetWindowRect()
hwnd = self._win.GetSafeHwnd()
gui.SetWindowPos(hwnd, 0, l + 20, t + 20, 0, 0,
wc.SWP_NOSIZE | wc.SWP_NOZORDER)
def OnClose(self):
#print "Window:", self, "OnClose"
try:
self.close_cmd()
except Cancel:
pass
except:
application().report_error()
def _win_menus_changed(self):
self._win_need_menubar_update = True
if self.visible:
self._win_update_menubar()
def _win_update_menubar(self):
#print "Window._win_update_menubar:", self ###
if self._win_need_menubar_update:
all_menus = application()._effective_menus_for_window(self)
self._all_menus = all_menus
if self._win_has_menubar:
if all_menus:
menubar = MenuBar()
for menu in all_menus:
menubar.append_menu(menu)
self._win.SetMenu(menubar.win_menu)
self._win_menubar = menubar
else:
self._win_set_empty_menubar()
self._win_need_menubar_update = False
def _win_wm_initmenu(self, message):
#print "Window._win_wm_initmenu:", self ###
self._win_perform_menu_setup()
def _win_perform_menu_setup(self):
#print "Window._win_perform_menu_setup:", self ###
application()._perform_menu_setup(self._all_menus)
def _win_menu_command(self, id):
command = win_id_to_command(id)
if command:
application().dispatch_menu_command(command)
def _win_possible_menu_key(self, key, shift, option):
self._win_perform_menu_setup()
command = search_list_for_key(self._all_menus, key, shift, option)
if command:
application().dispatch_menu_command(command)
return True
def _screen_rect(self):
return WinUtils.win_screen_rect
def modal_event_loop(self):
disabled = []
for window in application().windows:
if window is not self:
if not window._win.EnableWindow(False):
#print "Window.modal_event_loop: disabled", window.title ###
disabled.append(window)
status = self._win.RunModalLoop(0)
if status:
print "Window._modal_event_loop:", self, "status =", status ###
#raise Cancel
for window in disabled:
#print "Window.modal_event_loop: enabling", window.title ###
window._win.EnableWindow(True)
if status <> 0: ###
from GUI.Exceptions import InternalError ###
raise InternalError("RunModalLoop returned %s" % status) ###
def exit_modal_event_loop(self):
self._win.EndModalLoop(0)
export(Window)