PyGUI should now work without installation
This commit is contained in:
@@ -0,0 +1,356 @@
|
||||
#------------------------------------------------------------------------------
|
||||
#
|
||||
# Python GUI - Application class - PyObjC
|
||||
#
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
import os, sys, traceback
|
||||
import objc
|
||||
from Foundation import NSObject, NSBundle, NSDefaultRunLoopMode, NSData, NSDate
|
||||
import AppKit
|
||||
from AppKit import NSApplication, NSResponder, NSScreen, NSMenu, NSMenuItem, \
|
||||
NSKeyDown, NSKeyUp, NSMouseMoved, NSLeftMouseDown, NSSystemDefined, \
|
||||
NSCommandKeyMask, NSPasteboard, NSStringPboardType, NSModalPanelRunLoopMode
|
||||
NSAnyEventMask = 0xffffffff
|
||||
from GUI import Globals, GApplications
|
||||
from GUI import application, export
|
||||
from GUI.GApplications import Application as GApplication
|
||||
from GUI import Event
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
Globals.ns_screen_height = None
|
||||
Globals.ns_last_mouse_moved_event = None
|
||||
Globals.pending_exception = None
|
||||
Globals.ns_application = None
|
||||
|
||||
ns_distant_future = NSDate.distantFuture()
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class Application(GApplication):
|
||||
# _ns_app _PyGui_NSApplication
|
||||
# _ns_pasteboard NSPasteboard
|
||||
# _ns_key_window Window
|
||||
|
||||
_ns_menubar_update_pending = False
|
||||
_ns_files_opened = False
|
||||
_ns_using_clargs = False
|
||||
_ns_menus_updated = False
|
||||
|
||||
def __init__(self, **kwds):
|
||||
self._ns_app = Globals.ns_application
|
||||
self._ns_app.pygui_app = self
|
||||
self._ns_pasteboard = NSPasteboard.generalPasteboard()
|
||||
self._ns_key_window = None
|
||||
GApplication.__init__(self, **kwds)
|
||||
self.ns_init_application_name()
|
||||
|
||||
def destroy(self):
|
||||
del self.menus[:]
|
||||
import Windows
|
||||
Windows._ns_zombie_window = None
|
||||
self._ns_app.pygui_app = None
|
||||
self._ns_app = None
|
||||
self._ns_pasteboard = None
|
||||
GApplication.destroy(self)
|
||||
|
||||
def set_menus(self, menu_list):
|
||||
GApplication.set_menus(self, menu_list)
|
||||
self._update_menubar()
|
||||
|
||||
def _update_menubar(self):
|
||||
ns_app = self._ns_app
|
||||
ns_menubar = NSMenu.alloc().initWithTitle_("")
|
||||
menu_list = self._effective_menus()
|
||||
for menu in menu_list:
|
||||
ns_item = NSMenuItem.alloc()
|
||||
ns_item.initWithTitle_action_keyEquivalent_(menu.title, '', "")
|
||||
ns_menubar.addItem_(ns_item)
|
||||
ns_menu = menu._ns_menu
|
||||
# An NSMenu can only be a submenu of one menu at a time, so
|
||||
# remove it from the old menubar if necessary.
|
||||
old_supermenu = ns_menu.supermenu()
|
||||
if old_supermenu:
|
||||
i = old_supermenu.indexOfItemWithSubmenu_(ns_menu)
|
||||
old_supermenu.removeItemAtIndex_(i)
|
||||
ns_menubar.setSubmenu_forItem_(ns_menu, ns_item)
|
||||
# The menu you pass to setAppleMenu_ must *also* be a member of the
|
||||
# main menu.
|
||||
ns_app.setMainMenu_(ns_menubar)
|
||||
if menu_list:
|
||||
ns_app_menu = menu_list[0]._ns_menu
|
||||
ns_app.setAppleMenu_(ns_app_menu)
|
||||
|
||||
def handle_next_event(self, modal_window = None):
|
||||
ns_app = self._ns_app
|
||||
if modal_window:
|
||||
ns_mode = NSModalPanelRunLoopMode
|
||||
ns_modal_window = modal_window._ns_window
|
||||
else:
|
||||
ns_mode = NSDefaultRunLoopMode
|
||||
ns_modal_window = None
|
||||
ns_event = ns_app.nextEventMatchingMask_untilDate_inMode_dequeue_(
|
||||
NSAnyEventMask, ns_distant_future, ns_mode, True)
|
||||
if ns_event:
|
||||
ns_window = ns_event.window()
|
||||
if not ns_window or not ns_modal_window or ns_window == ns_modal_window:
|
||||
ns_app.sendEvent_(ns_event)
|
||||
|
||||
def get_target_window(self):
|
||||
# NSApplication.keyWindow() isn't reliable enough. We keep track
|
||||
# of the key window ourselves.
|
||||
return self._ns_key_window
|
||||
|
||||
def zero_windows_allowed(self):
|
||||
return 1
|
||||
|
||||
def query_clipboard(self):
|
||||
pb = self._ns_pasteboard
|
||||
pb_types = pb.types()
|
||||
return NSStringPboardType in pb_types
|
||||
|
||||
def get_clipboard(self):
|
||||
pb = self._ns_pasteboard
|
||||
ns_data = pb.dataForType_(NSStringPboardType)
|
||||
if ns_data:
|
||||
return ns_data.bytes().tobytes()
|
||||
|
||||
def set_clipboard(self, data):
|
||||
ns_data = NSData.dataWithBytes_length_(data, len(data))
|
||||
pb = self._ns_pasteboard
|
||||
pb.clearContents()
|
||||
pb.setData_forType_(ns_data, NSStringPboardType)
|
||||
|
||||
def setup_menus(self, m):
|
||||
m.hide_app_cmd.enabled = True
|
||||
m.hide_other_apps_cmd.enabled = True
|
||||
m.show_all_apps_cmd.enabled = True
|
||||
if not self._ns_app.modalWindow():
|
||||
GApplication.setup_menus(self, m)
|
||||
|
||||
def process_args(self, args):
|
||||
# Note: When using py2app, argv_emulation should be disabled.
|
||||
if args and args[0].startswith("-psn"):
|
||||
# Launched from MacOSX Finder -- wait for file open/app launch messages
|
||||
pass
|
||||
else:
|
||||
# Not launched from Finder or using argv emulation
|
||||
self._ns_using_clargs = True
|
||||
GApplication.process_args(self, args)
|
||||
|
||||
def run(self, fast_exit = True):
|
||||
try:
|
||||
GApplication.run(self)
|
||||
except (KeyboardInterrupt, SystemExit):
|
||||
pass
|
||||
except:
|
||||
traceback.print_exc()
|
||||
# A py2app bundled application seems to crash on exit if we don't
|
||||
# bail out really quickly here (Python 2.3, PyObjC 1.3.7, py2app 0.2.1,
|
||||
# MacOSX 10.4.4)
|
||||
if fast_exit:
|
||||
os._exit(0)
|
||||
|
||||
def event_loop(self):
|
||||
self._ns_app.run()
|
||||
|
||||
def _quit(self):
|
||||
self._quit_flag = True
|
||||
self._ns_app.stop_(self._ns_app)
|
||||
|
||||
def hide_app_cmd(self):
|
||||
self._ns_app.hide_(self)
|
||||
|
||||
def hide_other_apps_cmd(self):
|
||||
self._ns_app.hideOtherApplications_(self)
|
||||
|
||||
def show_all_apps_cmd(self):
|
||||
self._ns_app.unhideAllApplications_(self)
|
||||
|
||||
def ns_process_key_event(self, ns_event):
|
||||
# Perform menu setup before command-key events.
|
||||
# Send non-command key events to associated window if any,
|
||||
# otherwise pass them to the pygui application. This is necessary
|
||||
# because otherwise there is no way of receiving key events when
|
||||
# there are no windows.
|
||||
if ns_event.modifierFlags() & NSCommandKeyMask:
|
||||
NSApplication.sendEvent_(self._ns_app, ns_event)
|
||||
else:
|
||||
ns_window = ns_event.window()
|
||||
if ns_window:
|
||||
ns_window.sendEvent_(ns_event)
|
||||
else:
|
||||
event = Event(ns_event)
|
||||
self.handle(event.kind, event)
|
||||
|
||||
def ns_menu_needs_update(self, ns_menu):
|
||||
try:
|
||||
if not self._ns_menus_updated:
|
||||
self._perform_menu_setup()
|
||||
self._ns_menus_updated = True
|
||||
except Exception:
|
||||
self.report_exception()
|
||||
|
||||
def ns_init_application_name(self):
|
||||
# Arrange for the application name to be used as the title
|
||||
# of the application menu.
|
||||
ns_bundle = NSBundle.mainBundle()
|
||||
if ns_bundle:
|
||||
ns_info = ns_bundle.localizedInfoDictionary()
|
||||
if not ns_info:
|
||||
ns_info = ns_bundle.infoDictionary()
|
||||
if ns_info:
|
||||
if ns_info['CFBundleName'] == "Python":
|
||||
#print "GUI.Application: NSBundle infoDictionary =", ns_info ###
|
||||
ns_info['CFBundleName'] = Globals.application_name
|
||||
return
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
_ns_key_event_mask = AppKit.NSKeyDownMask | AppKit.NSKeyUpMask
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class _PyGui_NSApplication(NSApplication):
|
||||
|
||||
pygui_app = None
|
||||
|
||||
def sendEvent_(self, ns_event):
|
||||
# Perform special processing of key events.
|
||||
# Perform menu setup when menu bar is clicked.
|
||||
# Remember the most recent mouse-moved event to use as the
|
||||
# location of event types which do not have a location themselves.
|
||||
if Globals.pending_exception:
|
||||
raise_pending_exception()
|
||||
ns_type = ns_event.type()
|
||||
self.pygui_app._ns_menus_updated = False
|
||||
if (1 << ns_type) & _ns_key_event_mask:
|
||||
self.pygui_app.ns_process_key_event(ns_event)
|
||||
else:
|
||||
if ns_type == NSMouseMoved:
|
||||
Globals.ns_last_mouse_moved_event = ns_event
|
||||
ns_window = ns_event.window()
|
||||
if ns_window:
|
||||
ns_view = ns_window.contentView().hitTest_(ns_event.locationInWindow())
|
||||
if ns_view:
|
||||
ns_view.mouseMoved_(ns_event)
|
||||
else:
|
||||
NSApplication.sendEvent_(self, ns_event)
|
||||
|
||||
def menuNeedsUpdate_(self, ns_menu):
|
||||
self.pygui_app.ns_menu_needs_update(ns_menu)
|
||||
|
||||
def menuSelection_(self, ns_menu_item):
|
||||
try:
|
||||
command = ns_menu_item.representedObject()
|
||||
index = ns_menu_item.tag()
|
||||
if index >= 0:
|
||||
dispatch_to_app(self, command, index)
|
||||
else:
|
||||
dispatch_to_app(self, command)
|
||||
except:
|
||||
self.pygui_app.report_error()
|
||||
|
||||
def validateMenuItem_(self, item):
|
||||
return False
|
||||
|
||||
def undo_(self, sender):
|
||||
dispatch_to_app(self, 'undo_cmd')
|
||||
|
||||
def redo_(self, sender):
|
||||
dispatch_to_app(self, 'redo_cmd')
|
||||
|
||||
def cut_(self, sender):
|
||||
dispatch_to_app(self, 'cut_cmd')
|
||||
|
||||
def copy_(self, sender):
|
||||
dispatch_to_app(self, 'copy_cmd')
|
||||
|
||||
def paste_(self, sender):
|
||||
dispatch_to_app(self, 'paste_cmd')
|
||||
|
||||
def clear_(self, sender):
|
||||
dispatch_to_app(self, 'clear_cmd')
|
||||
|
||||
def selectAll_(self, sender):
|
||||
dispatch_to_app(self, 'select_all_cmd')
|
||||
|
||||
def application_openFile_(self, ns_app, path):
|
||||
app = self.pygui_app
|
||||
if app._ns_using_clargs:
|
||||
return True
|
||||
# Bizarrely, argv[0] gets passed to application_openFile_ under
|
||||
# some circumstances. We don't want to try to open it!
|
||||
if path == sys.argv[0]:
|
||||
return True
|
||||
app._ns_files_opened = True
|
||||
try:
|
||||
app.open_path(path)
|
||||
return True
|
||||
except Exception, e:
|
||||
app.report_error()
|
||||
return False
|
||||
|
||||
def applicationDidFinishLaunching_(self, notification):
|
||||
app = self.pygui_app
|
||||
if app._ns_using_clargs:
|
||||
return
|
||||
try:
|
||||
if not app._ns_files_opened:
|
||||
app.open_app()
|
||||
except Exception, e:
|
||||
app.report_error()
|
||||
return False
|
||||
|
||||
export(Application)
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
def raise_pending_exception():
|
||||
exc_type, exc_value, exc_tb = Globals.pending_exception
|
||||
Globals.pending_exception = None
|
||||
raise exc_type, exc_value, exc_tb
|
||||
|
||||
def create_ns_application():
|
||||
ns_app = _PyGui_NSApplication.sharedApplication()
|
||||
ns_app.setDelegate_(ns_app)
|
||||
Globals.ns_application = ns_app
|
||||
|
||||
def dispatch_to_app(ns_app, *args):
|
||||
app = ns_app.pygui_app
|
||||
if app:
|
||||
app.dispatch(*args)
|
||||
|
||||
Globals.ns_screen_height = NSScreen.mainScreen().frame().size.height
|
||||
|
||||
create_ns_application()
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
# Disable this for now, since MachSignals.signal segfaults. :-(
|
||||
#
|
||||
#def _install_sigint_handler():
|
||||
# print "_install_sigint_handler" ###
|
||||
# from Foundation import NSRunLoop
|
||||
# run_loop = NSRunLoop.currentRunLoop()
|
||||
# if not run_loop:
|
||||
# print "...No current run loop" ###
|
||||
# sys.exit(1) ###
|
||||
# MachSignals.signal(signal.SIGINT, _sigint_handler)
|
||||
# #from PyObjCTools.AppHelper import installMachInterrupt
|
||||
# #installMachInterrupt()
|
||||
# print "...done" ###
|
||||
#
|
||||
#def _sigint_handler(signum):
|
||||
# print "_sigint_handler" ###
|
||||
# raise KeyboardInterrupt
|
||||
|
||||
#def _install_sigint_handler():
|
||||
# import signal
|
||||
# signal.signal(signal.SIGINT, _raise_keyboard_interrupt)
|
||||
#
|
||||
#def _raise_keyboard_interrupt(signum, frame):
|
||||
# raise KeyboardInterrupt
|
||||
|
||||
#_install_sigint_handler()
|
||||
@@ -0,0 +1,29 @@
|
||||
#
|
||||
# Python GUI - Basic alert functions - Cocoa
|
||||
#
|
||||
|
||||
from AppKit import \
|
||||
NSRunAlertPanel, NSRunCriticalAlertPanel, NSRunInformationalAlertPanel
|
||||
|
||||
def alert(kind, prompt, ok_label, **kwds):
|
||||
alert_n(kind, prompt, ok_label, None, None)
|
||||
|
||||
def alert2(kind, prompt, yes_label, no_label, **kwds):
|
||||
return alert_n(kind, prompt, yes_label, no_label, None)
|
||||
|
||||
def alert3(kind, prompt, yes_label, no_label, other_label, **kwds):
|
||||
return alert_n(kind, prompt, yes_label, no_label, other_label)
|
||||
|
||||
def alert_n(kind, prompt, label1, label2, label3):
|
||||
splat = prompt.split("\n", 1)
|
||||
title = splat[0]
|
||||
if len(splat) > 1:
|
||||
msg = splat[1]
|
||||
else:
|
||||
msg = ""
|
||||
if kind == 'caution':
|
||||
return NSRunCriticalAlertPanel(title, msg, label1, label2, label3)
|
||||
elif kind == 'note':
|
||||
return NSRunInformationalAlertPanel(title, msg, label1, label2, label3)
|
||||
else:
|
||||
return NSRunAlertPanel(title, msg, label1, label2, label3)
|
||||
@@ -0,0 +1,63 @@
|
||||
#
|
||||
# Python GUI - File selection dialogs - Cocoa
|
||||
#
|
||||
|
||||
from AppKit import NSOpenPanel, NSSavePanel, NSOKButton
|
||||
from GUI.Files import FileRef
|
||||
from GUI import application
|
||||
|
||||
#------------------------------------------------------------------
|
||||
|
||||
def _request_old(prompt, default_dir, file_types, dir, multiple):
|
||||
ns_panel = NSOpenPanel.openPanel()
|
||||
if prompt.endswith(":"):
|
||||
prompt = prompt[:-1]
|
||||
ns_panel.setTitle_(prompt)
|
||||
ns_panel.setCanChooseFiles_(not dir)
|
||||
ns_panel.setCanChooseDirectories_(dir)
|
||||
ns_panel.setAllowsMultipleSelection_(multiple)
|
||||
if default_dir:
|
||||
ns_dir = default_dir.path
|
||||
else:
|
||||
ns_dir = None
|
||||
if file_types:
|
||||
ns_types = []
|
||||
for type in file_types:
|
||||
ns_types.extend(type._ns_file_types())
|
||||
else:
|
||||
ns_types = None
|
||||
result = ns_panel.runModalForDirectory_file_types_(ns_dir, None, ns_types)
|
||||
if result == NSOKButton:
|
||||
if multiple:
|
||||
return [FileRef(path = path) for path in ns_panel.filenames()]
|
||||
else:
|
||||
return FileRef(path = ns_panel.filename())
|
||||
else:
|
||||
return None
|
||||
|
||||
#------------------------------------------------------------------
|
||||
|
||||
def _request_new(prompt, default_dir, default_name, file_type, dir):
|
||||
ns_panel = NSSavePanel.savePanel()
|
||||
#if prompt.endswith(":"):
|
||||
# prompt = prompt[:-1]
|
||||
#if prompt.lower().endswith(" as"):
|
||||
# prompt = prompt[:-3]
|
||||
#ns_panel.setTitle_(prompt)
|
||||
#print "_request_new: setting label to", repr(prompt) ###
|
||||
ns_panel.setNameFieldLabel_(prompt)
|
||||
if default_dir:
|
||||
ns_dir = default_dir.path
|
||||
else:
|
||||
ns_dir = None
|
||||
if file_type:
|
||||
suffix = file_type.suffix
|
||||
if suffix:
|
||||
ns_panel.setCanSelectHiddenExtension_(True)
|
||||
if not file_type.mac_type or file_type.mac_force_suffix:
|
||||
ns_panel.setRequiredFileType_(suffix)
|
||||
result = ns_panel.runModalForDirectory_file_(ns_dir, default_name)
|
||||
if result == NSOKButton:
|
||||
return FileRef(path = ns_panel.filename())
|
||||
else:
|
||||
return None
|
||||
@@ -0,0 +1,45 @@
|
||||
#
|
||||
# Python GUI - Buttons - PyObjC version
|
||||
#
|
||||
|
||||
import AppKit
|
||||
from GUI import export
|
||||
from GUI.StdFonts import system_font
|
||||
from GUI.ButtonBasedControls import ButtonBasedControl
|
||||
from GUI.GButtons import Button as GButton
|
||||
|
||||
_style_to_ns_key_equivalent = {
|
||||
'default': "\x0d",
|
||||
'cancel': "\x1b",
|
||||
}
|
||||
|
||||
_ns_key_equivalent_to_style = {
|
||||
"\x0d": 'default',
|
||||
"\x1b": 'cancel',
|
||||
}
|
||||
|
||||
class Button(ButtonBasedControl, GButton):
|
||||
|
||||
def __init__(self, title = "New Button", font = system_font, **kwds):
|
||||
ns_button = self._create_ns_button(title = title, font = font,
|
||||
ns_button_type = AppKit.NSMomentaryLight,
|
||||
ns_bezel_style = AppKit.NSRoundedBezelStyle,
|
||||
padding = (10, 2)
|
||||
)
|
||||
GButton.__init__(self, _ns_view = ns_button, **kwds)
|
||||
|
||||
def get_style(self):
|
||||
ns_key = self._ns_view.getKeyEquivalent()
|
||||
return _ns_key_equivalent_to_style.get(ns_key, 'normal')
|
||||
|
||||
def set_style(self, style):
|
||||
ns_key = _style_to_ns_key_equivalent.get(style, "")
|
||||
self._ns_view.setKeyEquivalent_(ns_key)
|
||||
|
||||
def activate(self):
|
||||
self._ns_view.performClick_(None)
|
||||
|
||||
# def key_down(self, e): ###
|
||||
# print "Button.key_down:", e ###
|
||||
|
||||
export(Button)
|
||||
@@ -0,0 +1,86 @@
|
||||
#------------------------------------------------------------------------------
|
||||
#
|
||||
# Python GUI - PyObjC version
|
||||
#
|
||||
# Mixin class for controls based on NSButton
|
||||
#
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
from Foundation import NSMutableDictionary, NSAttributedString
|
||||
from AppKit import NSMutableParagraphStyle, NSFontAttributeName, \
|
||||
NSForegroundColorAttributeName, NSParagraphStyleAttributeName, \
|
||||
NSButton
|
||||
from GUI.Utils import NSMultiClass, PyGUI_NS_EventHandler, \
|
||||
ns_set_action, ns_size_to_fit
|
||||
from GUI import Control
|
||||
from GUI.StdColors import black
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class ButtonBasedControl(object):
|
||||
|
||||
_ns_handle_mouse = True
|
||||
|
||||
_color = None
|
||||
|
||||
def _create_ns_button(self, title, font, ns_button_type, ns_bezel_style,
|
||||
padding = (0, 0)):
|
||||
ns_button = PyGUI_NSButton.alloc().init()
|
||||
ns_button.pygui_component = self
|
||||
ns_button.setButtonType_(ns_button_type)
|
||||
ns_button.setBezelStyle_(ns_bezel_style)
|
||||
ns_button.setTitle_(title)
|
||||
ns_button.setFont_(font._ns_font)
|
||||
num_lines = title.count("\n") + 1
|
||||
ns_size_to_fit(ns_button, padding = padding,
|
||||
height = font.line_height * num_lines + 5)
|
||||
ns_set_action(ns_button, 'doAction:')
|
||||
return ns_button
|
||||
|
||||
def set_title(self, title):
|
||||
Control.set_title(self, title)
|
||||
self._ns_update_attributed_title()
|
||||
|
||||
def set_font(self, font):
|
||||
Control.set_font(self, font)
|
||||
self._ns_update_attributed_title()
|
||||
|
||||
def set_just(self, just):
|
||||
Control.set_just(self, just)
|
||||
self._ns_update_attributed_title()
|
||||
|
||||
def get_color(self):
|
||||
if self._color:
|
||||
return self._color
|
||||
else:
|
||||
return black
|
||||
|
||||
def set_color(self, color):
|
||||
self._color = color
|
||||
self._ns_update_attributed_title()
|
||||
|
||||
# There is no direct way of setting the text colour of the title;
|
||||
# it must be done using an attributed string. But when doing
|
||||
# this, the attributes must include the font and alignment
|
||||
# as well. So when using a custom color, we construct a new
|
||||
# attributed string whenever the title, font, alignment or color
|
||||
# is changed.
|
||||
|
||||
def _ns_update_attributed_title(self):
|
||||
if self._color:
|
||||
ns_button = self._ns_view
|
||||
ns_attrs = NSMutableDictionary.alloc().init()
|
||||
ns_attrs[NSFontAttributeName] = ns_button.font()
|
||||
ns_attrs[NSForegroundColorAttributeName] = self._color._ns_color
|
||||
ns_parstyle = NSMutableParagraphStyle.alloc().init()
|
||||
ns_parstyle.setAlignment_(ns_button.alignment())
|
||||
ns_attrs[NSParagraphStyleAttributeName] = ns_parstyle
|
||||
ns_attstr = NSAttributedString.alloc().initWithString_attributes_(
|
||||
ns_button.title(), ns_attrs)
|
||||
ns_button.setAttributedTitle_(ns_attstr)
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class PyGUI_NSButton(NSButton, PyGUI_NS_EventHandler):
|
||||
__metaclass__ = NSMultiClass
|
||||
__slots__ = ['pygui_component']
|
||||
@@ -0,0 +1,321 @@
|
||||
#
|
||||
# Python GUI - Drawing - PyObjC
|
||||
#
|
||||
|
||||
from array import array
|
||||
from Foundation import NSPoint, NSMakeRect, NSString
|
||||
from AppKit import NSGraphicsContext, NSBezierPath, NSEvenOddWindingRule, \
|
||||
NSFontAttributeName, NSForegroundColorAttributeName, \
|
||||
NSCompositeCopy, NSCompositeSourceOver, NSAffineTransform
|
||||
from GUI import export
|
||||
from GUI.StdColors import black, white
|
||||
from GUI.GCanvases import Canvas as GCanvas
|
||||
import math
|
||||
|
||||
class Canvas(GCanvas):
|
||||
|
||||
def __init__(self):
|
||||
self._ns_path = NSBezierPath.bezierPath()
|
||||
self._ns_path.setWindingRule_(NSEvenOddWindingRule)
|
||||
self._stack = []
|
||||
ctx = NSGraphicsContext.currentContext()
|
||||
ctx.setCompositingOperation_(NSCompositeSourceOver)
|
||||
GCanvas.__init__(self)
|
||||
self._printing = not ctx.isDrawingToScreen()
|
||||
self.initgraphics()
|
||||
self.transformstack = [[]]
|
||||
|
||||
def get_pencolor(self):
|
||||
return self._pencolor
|
||||
|
||||
def set_pencolor(self, c):
|
||||
self._pencolor = c
|
||||
|
||||
def get_fillcolor(self):
|
||||
return self._fillcolor
|
||||
|
||||
def set_fillcolor(self, c):
|
||||
self._fillcolor = c
|
||||
|
||||
def get_textcolor(self):
|
||||
return self._textcolor
|
||||
|
||||
def set_textcolor(self, c):
|
||||
self._textcolor = c
|
||||
|
||||
def get_backcolor(self):
|
||||
return self._backcolor
|
||||
|
||||
def set_backcolor(self, c):
|
||||
self._backcolor = c
|
||||
|
||||
def get_pensize(self):
|
||||
return self._pensize
|
||||
|
||||
def set_pensize(self, d):
|
||||
self._pensize = d
|
||||
self._ns_path.setLineWidth_(d)
|
||||
|
||||
def get_font(self):
|
||||
return self._font
|
||||
|
||||
def set_font(self, f):
|
||||
self._font = f
|
||||
|
||||
def get_current_point(self):
|
||||
return self._ns_path.currentPoint()
|
||||
|
||||
def newpath(self):
|
||||
self._ns_path.removeAllPoints()
|
||||
#for i in range(len(self.transformstack)):
|
||||
#j = self.transformstack.pop()
|
||||
#transforms = {"translate":self.translate,"rotate":self.rotate,"scale":self.scale}
|
||||
#transforms[j[0]](*j[1:])
|
||||
|
||||
def moveto(self, x, y):
|
||||
x, y = self._transform(x, y)
|
||||
self._ns_path.moveToPoint_((x, y))
|
||||
|
||||
def rmoveto(self, dx, dy):
|
||||
self._ns_path.relativeMoveToPoint_((dx, dy))
|
||||
|
||||
def lineto(self, x, y):
|
||||
x, y = self._transform(x, y)
|
||||
self._ns_path.lineToPoint_((x, y))
|
||||
|
||||
def rlineto(self, dx, dy):
|
||||
self._ns_path.relativeLineToPoint_((dx, dy))
|
||||
|
||||
def curveto(self, cp1, cp2, ep):
|
||||
cp1 = self._transform(*cp1)
|
||||
cp2 = self._transform(*cp2)
|
||||
ep = self._transform(*ep)
|
||||
self._ns_path.curveToPoint_controlPoint1_controlPoint2_(
|
||||
ep, cp1, cp2)
|
||||
|
||||
def rcurveto(self, cp1, cp2, ep):
|
||||
self._ns_path.relativeCurveToPoint_controlPoint1_controlPoint2_(
|
||||
ep, cp1, cp2)
|
||||
|
||||
def arc(self, c, r, a0, a1):
|
||||
c = self._transform(*c)
|
||||
self._ns_path.appendBezierPathWithArcWithCenter_radius_startAngle_endAngle_(
|
||||
c, r, a0, a1)
|
||||
|
||||
def rect(self, rect):
|
||||
try:
|
||||
rect = self._transform(rect[0],rect[1]) + self._transform(rect[2], rect[3])
|
||||
except:
|
||||
print "Error here - line 113"
|
||||
self._ns_path.appendBezierPathWithRect_(_ns_rect(rect))
|
||||
|
||||
def oval(self, rect):
|
||||
rect = (self._transform(*rect[0]), self._transform(*rect[1]))
|
||||
self._ns_path.appendBezierPathWithOvalInRect(_ns_rect(rect))
|
||||
|
||||
def lines(self, points):
|
||||
# Due to a memory leak in PyObjC 2.3, we need to be very careful
|
||||
# about the type of object that we pass to appendBezierPathWithPoints_count_.
|
||||
# If 'points' is a numpy array, we convert it to an array.array of type 'f',
|
||||
# else we fall back on iterating over the points in Python.
|
||||
# ns = self._ns_path
|
||||
# ns.moveToPoint_(points[0])
|
||||
# ns.appendBezierPathWithPoints_count_(points, len(points))
|
||||
try:
|
||||
p = points.flat
|
||||
except AttributeError:
|
||||
GCanvas.lines(self, points)
|
||||
else:
|
||||
a = array('f', p)
|
||||
ns = self._ns_path
|
||||
ns.moveToPoint_(points[0])
|
||||
ns.appendBezierPathWithPoints_count_(a, len(points))
|
||||
|
||||
|
||||
def poly(self, points):
|
||||
# ns = self._ns_path
|
||||
# ns.moveToPoint_(points[0])
|
||||
# ns.appendBezierPathWithPoints_count_(points, len(points))
|
||||
# ns.closePath()
|
||||
self.lines(points)
|
||||
self.closepath()
|
||||
|
||||
def closepath(self):
|
||||
self._ns_path.closePath()
|
||||
|
||||
def clip(self):
|
||||
ns = self._ns_path
|
||||
ns.addClip()
|
||||
|
||||
def rectclip(self, (l, t, r, b)):
|
||||
ns_rect = NSMakeRect(l, t, r - l, b - t)
|
||||
NSBezierPath.clipRect_(ns_rect)
|
||||
|
||||
def gsave(self):
|
||||
self._stack.append((
|
||||
self._pencolor, self._fillcolor, self._textcolor, self._backcolor,
|
||||
self._pensize, self._font))
|
||||
self.transformstack.append([])
|
||||
NSGraphicsContext.currentContext().saveGraphicsState()
|
||||
|
||||
def grestore(self):
|
||||
(self._pencolor, self._fillcolor, self._textcolor, self._backcolor,
|
||||
self._pensize, self._font) = self._stack.pop()
|
||||
self.transformstack.pop()
|
||||
NSGraphicsContext.currentContext().restoreGraphicsState()
|
||||
|
||||
def stroke(self):
|
||||
ns = self._ns_path
|
||||
self._pencolor._ns_color.set()
|
||||
ns.stroke()
|
||||
|
||||
def fill(self):
|
||||
ns = self._ns_path
|
||||
self._fillcolor._ns_color.set()
|
||||
ns.fill()
|
||||
|
||||
def erase(self):
|
||||
ns = self._ns_path
|
||||
self._backcolor._ns_color.set()
|
||||
ctx = NSGraphicsContext.currentContext()
|
||||
ctx.setCompositingOperation_(NSCompositeCopy)
|
||||
ns.fill()
|
||||
ctx.setCompositingOperation_(NSCompositeSourceOver)
|
||||
|
||||
def fill_stroke(self):
|
||||
ns = self._ns_path
|
||||
self._pencolor._ns_color.set()
|
||||
ns.stroke()
|
||||
self._fillcolor._ns_color.set()
|
||||
ns.fill()
|
||||
|
||||
def show_text(self, text):
|
||||
x, y = self._ns_path.currentPoint()
|
||||
font = self._font
|
||||
ns_font = font._ns_font
|
||||
ns_color = self._textcolor._ns_color
|
||||
ns_string = NSString.stringWithString_(text)
|
||||
ns_attrs = {
|
||||
NSFontAttributeName: ns_font,
|
||||
NSForegroundColorAttributeName: ns_color,
|
||||
}
|
||||
# print "Canvas.show_text:", repr(text) ###
|
||||
# print "family:", ns_font.familyName() ###
|
||||
# print "size:", ns_font.pointSize() ###
|
||||
# print "ascender:", ns_font.ascender() ###
|
||||
# print "descender:", ns_font.descender() ###
|
||||
# print "capHeight:", ns_font.capHeight() ###
|
||||
# print "leading:", ns_font.leading() ###
|
||||
# print "matrix:", ns_font.matrix() ###
|
||||
# print "defaultLineHeightForFont:", ns_font.defaultLineHeightForFont() ###
|
||||
h = ns_font.defaultLineHeightForFont()
|
||||
d = -ns_font.descender()
|
||||
dy = h - d
|
||||
if ns_font.familyName() == "Courier New":
|
||||
dy += ns_font.pointSize() * 0.229167
|
||||
ns_point = NSPoint(x, y - dy)
|
||||
#print "drawing at:", ns_point ###
|
||||
ns_string.drawAtPoint_withAttributes_(ns_point, ns_attrs)
|
||||
dx = ns_font.widthOfString_(ns_string)
|
||||
#self._ns_path.relativeMoveToPoint_(NSPoint(x + dx, y))
|
||||
self._ns_path.relativeMoveToPoint_((dx, 0))
|
||||
|
||||
def _ns_frame_rect(self, (l, t, r, b)):
|
||||
p = self._pensize
|
||||
q = 0.5 * p
|
||||
return NSMakeRect(l + q, t + q, r - l - p, b - t - p)
|
||||
|
||||
def stroke_rect(self, r):
|
||||
self._pencolor._ns_color.set()
|
||||
NSBezierPath.setDefaultLineWidth_(self._pensize)
|
||||
NSBezierPath.strokeRect_(_ns_rect(r))
|
||||
|
||||
def frame_rect(self, r):
|
||||
self._pencolor._ns_color.set()
|
||||
NSBezierPath.setDefaultLineWidth_(self._pensize)
|
||||
NSBezierPath.strokeRect_(self._ns_frame_rect(r))
|
||||
|
||||
def fill_rect(self, r):
|
||||
self._fillcolor._ns_color.set()
|
||||
NSBezierPath.fillRect_(_ns_rect(r))
|
||||
|
||||
def erase_rect(self, r):
|
||||
self._backcolor._ns_color.set()
|
||||
NSBezierPath.fillRect_(_ns_rect(r))
|
||||
|
||||
def _ns_oval_path(self, ns_rect):
|
||||
ns_path = NSBezierPath.bezierPathWithOvalInRect_(ns_rect)
|
||||
ns_path.setLineWidth_(self._pensize)
|
||||
return ns_path
|
||||
|
||||
def stroke_oval(self, r):
|
||||
self._pencolor._ns_color.set()
|
||||
self._ns_oval_path(_ns_rect(r)).stroke()
|
||||
|
||||
def frame_oval(self, r):
|
||||
self._pencolor._ns_color.set()
|
||||
self._ns_oval_path(self._ns_frame_rect(r)).stroke()
|
||||
|
||||
def fill_oval(self, r):
|
||||
self._fillcolor._ns_color.set()
|
||||
self._ns_oval_path(_ns_rect(r)).fill()
|
||||
|
||||
def erase_oval(self, r):
|
||||
self._backcolor._ns_color.set()
|
||||
self._ns_oval_path(_ns_rect(r)).fill()
|
||||
|
||||
def _ns_arc_path(self, c, r, sa, ea):
|
||||
ns_path = NSBezierPath.bezierPath()
|
||||
ns_path.setLineWidth_(self._pensize)
|
||||
ns_path.\
|
||||
appendBezierPathWithArcWithCenter_radius_startAngle_endAngle_(
|
||||
c, r, sa, ea)
|
||||
return ns_path
|
||||
|
||||
def stroke_arc(self, center, radius, start_angle, arc_angle):
|
||||
ns_path = self._ns_arc_path(center, radius, start_angle, arc_angle)
|
||||
self._pencolor._ns_color.set()
|
||||
ns_path.stroke()
|
||||
|
||||
def frame_arc(self, center, radius, start_angle, arc_angle):
|
||||
r = radius - 0.5 * self._pensize
|
||||
ns_path = self._ns_arc_path(center, r, start_angle, arc_angle)
|
||||
self._pencolor._ns_color.set()
|
||||
ns_path.stroke()
|
||||
|
||||
def translate(self, dx, dy):
|
||||
matrix = NSAffineTransform.transform()
|
||||
matrix.translateXBy_yBy_(dx, dy)
|
||||
self._ns_path.transformUsingAffineTransform_(matrix)
|
||||
self.transformstack[-1].append(["translate",dx,dy])
|
||||
|
||||
def rotate(self, rotation):
|
||||
matrix = NSAffineTransform.transform()
|
||||
matrix.rotateByDegrees_(rotation)
|
||||
self._ns_path.transformUsingAffineTransform_(matrix)
|
||||
self.transformstack[-1].append(["rotate",rotation])
|
||||
|
||||
def scale(self, sx, sy):
|
||||
matrix = NSAffineTransform.transform()
|
||||
matrix.scaleXBy_yBy_(sx, sy)
|
||||
self._ns_path.transformUsingAffineTransform_(matrix)
|
||||
self.transformstack[-1].append(["scale",sx,sy])
|
||||
def _transform(self, x, y):
|
||||
for i in self.transformstack: #reversed(self.transformstack):
|
||||
for j in i: # reversed(i):
|
||||
if j[0]=="translate":
|
||||
x = x+j[1]
|
||||
y = y+j[2]
|
||||
elif j[0]=="rotate":
|
||||
x = x*math.cos(j[1])-y*math.sin(j[1])
|
||||
y = x*math.sin(j[1])+y*math.cos(j[1])
|
||||
elif j[0]=="scale":
|
||||
x = x*j[1]
|
||||
y = y*j[2]
|
||||
return x, y
|
||||
|
||||
def _ns_rect((l, t, r, b)):
|
||||
return NSMakeRect(l, t, r - l, b - t)
|
||||
|
||||
export(Canvas)
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
#
|
||||
# Python GUI - Check boxes - PyObjC
|
||||
#
|
||||
|
||||
import AppKit
|
||||
from AppKit import NSOnState, NSOffState, NSMixedState
|
||||
from GUI import export
|
||||
from GUI.Actions import Action
|
||||
from GUI.StdFonts import system_font
|
||||
from GUI.ButtonBasedControls import ButtonBasedControl
|
||||
from GUI.GCheckBoxes import CheckBox as GCheckBox
|
||||
|
||||
class CheckBox(ButtonBasedControl, GCheckBox):
|
||||
|
||||
_ns_mixed = False
|
||||
|
||||
def __init__(self, title = "New Check Box", font = system_font, **kwds):
|
||||
ns_button = self._create_ns_button(title = title, font = font,
|
||||
ns_button_type = AppKit.NSSwitchButton,
|
||||
ns_bezel_style = AppKit.NSRoundedBezelStyle)
|
||||
#if mixed:
|
||||
# self._ns_mixed = True
|
||||
# ns_button.setAllowsMixedState_(True)
|
||||
GCheckBox.__init__(self, _ns_view = ns_button, **kwds)
|
||||
|
||||
def get_mixed(self):
|
||||
return self._ns_view.allowsMixedState()
|
||||
|
||||
def set_mixed(self, x):
|
||||
self._ns_view.setAllowsMixedState_(x)
|
||||
|
||||
def get_on(self):
|
||||
state = self._ns_view.state()
|
||||
if state == NSMixedState:
|
||||
return 'mixed'
|
||||
else:
|
||||
return state <> NSOffState
|
||||
|
||||
def set_on(self, v):
|
||||
if v == 'mixed' and self.mixed:
|
||||
state = NSMixedState
|
||||
elif v:
|
||||
state = NSOnState
|
||||
else:
|
||||
state = NSOffState
|
||||
self._ns_view.setState_(state)
|
||||
|
||||
def do_action(self):
|
||||
if not self._auto_toggle:
|
||||
self.on = not self.on
|
||||
Action.do_action(self)
|
||||
|
||||
export(CheckBox)
|
||||
@@ -0,0 +1,47 @@
|
||||
#
|
||||
# Python GUI - Colors - PyObjC
|
||||
#
|
||||
|
||||
from AppKit import NSColor, NSCalibratedRGBColorSpace
|
||||
from GUI import export
|
||||
from GUI.GColors import Color as GColor
|
||||
|
||||
NSColor.setIgnoresAlpha_(False)
|
||||
|
||||
class Color(GColor):
|
||||
|
||||
def _from_ns_color(cls, ns_color):
|
||||
color = cls.__new__(cls)
|
||||
color._ns_color = ns_color.colorUsingColorSpaceName_(
|
||||
NSCalibratedRGBColorSpace)
|
||||
return color
|
||||
|
||||
_from_ns_color = classmethod(_from_ns_color)
|
||||
|
||||
def __init__(self, red, green, blue, alpha = 1.0):
|
||||
self._ns_color = NSColor.colorWithCalibratedRed_green_blue_alpha_(
|
||||
red, green, blue, alpha)
|
||||
|
||||
def get_red(self):
|
||||
return self._ns_color.redComponent()
|
||||
|
||||
def get_green(self):
|
||||
return self._ns_color.greenComponent()
|
||||
|
||||
def get_blue(self):
|
||||
return self._ns_color.blueComponent()
|
||||
|
||||
def get_alpha(self):
|
||||
return self._ns_color.alphaComponent()
|
||||
|
||||
def get_rgb(self):
|
||||
return self.get_rgba()[:3]
|
||||
|
||||
def get_rgba(self):
|
||||
m = self._ns_color.getRed_green_blue_alpha_
|
||||
try:
|
||||
return m()
|
||||
except TypeError:
|
||||
return m(None, None, None, None)
|
||||
|
||||
export(Color)
|
||||
@@ -0,0 +1,11 @@
|
||||
#
|
||||
# Python GUI - Color constants and functions - Cocoa
|
||||
#
|
||||
|
||||
from AppKit import NSColor
|
||||
from GUI import Color
|
||||
|
||||
rgb = Color
|
||||
|
||||
selection_forecolor = Color._from_ns_color(NSColor.selectedTextColor())
|
||||
selection_backcolor = Color._from_ns_color(NSColor.selectedTextBackgroundColor())
|
||||
@@ -0,0 +1,128 @@
|
||||
#
|
||||
# Python GUI - Components - PyObjC
|
||||
#
|
||||
|
||||
from Foundation import NSRect, NSPoint, NSSize, NSObject
|
||||
from GUI import export
|
||||
from GUI import Globals, application
|
||||
from GUI import Event
|
||||
from GUI.GComponents import Component as GComponent
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
Globals._ns_view_to_component = {} # Mapping from NSView to corresponding Component
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class Component(GComponent):
|
||||
|
||||
_has_local_coords = True
|
||||
_generic_tabbing = False
|
||||
_ns_pass_mouse_events_to_platform = False
|
||||
_ns_handle_mouse = False
|
||||
_ns_accept_first_responder = False
|
||||
|
||||
def __init__(self, _ns_view, _ns_inner_view = None, _ns_responder = None,
|
||||
_ns_set_autoresizing_mask = True, **kwds):
|
||||
self._ns_view = _ns_view
|
||||
if not _ns_inner_view:
|
||||
_ns_inner_view = _ns_view
|
||||
self._ns_inner_view = _ns_inner_view
|
||||
self._ns_responder = _ns_responder or _ns_inner_view
|
||||
Globals._ns_view_to_component[_ns_view] = self
|
||||
GComponent.__init__(self, **kwds)
|
||||
|
||||
def destroy(self):
|
||||
#print "Component.destroy:", self ###
|
||||
GComponent.destroy(self)
|
||||
_ns_view = self._ns_view
|
||||
if _ns_view in Globals._ns_view_to_component:
|
||||
#print "Component.destroy: removing", _ns_view, "from mapping" ###
|
||||
del Globals._ns_view_to_component[_ns_view]
|
||||
#print "Component.destroy: breaking link to", self._ns_view ###
|
||||
self._ns_view = None
|
||||
#if self._ns_inner_view: print "Component.destroy: breaking inner link to", self._ns_inner_view ###
|
||||
self._ns_inner_view = None
|
||||
self._ns_responder = None
|
||||
|
||||
def get_bounds(self):
|
||||
(l, t), (w, h) = self._ns_view.frame()
|
||||
return (l, t, l + w, t + h)
|
||||
|
||||
def set_bounds(self, (l, t, r, b)):
|
||||
ns = self._ns_view
|
||||
w0, h0 = ns.frame().size
|
||||
w1 = r - l
|
||||
h1 = b - t
|
||||
ns_frame = ((l, t), (w1, h1))
|
||||
old_ns_frame = ns.frame()
|
||||
ns.setFrame_(ns_frame)
|
||||
sv = ns.superview()
|
||||
if sv:
|
||||
sv.setNeedsDisplayInRect_(old_ns_frame)
|
||||
sv.setNeedsDisplayInRect_(ns_frame)
|
||||
if w0 != w1 or h0 != h1:
|
||||
self._resized((w1 - w0, h1 - h0))
|
||||
|
||||
def become_target(self):
|
||||
ns_view = self._ns_view
|
||||
ns_window = ns_view.window()
|
||||
if ns_window:
|
||||
self._ns_accept_first_responder = True
|
||||
ns_window.makeFirstResponder_(ns_view)
|
||||
self._ns_accept_first_responder = False
|
||||
|
||||
def _ns_pass_to_platform(self, event, method_name):
|
||||
#print "Component._ns_pass_to_platform:", self ###
|
||||
h = self._ns_responder
|
||||
b = h.__class__.__bases__[0]
|
||||
m = getattr(b, method_name)
|
||||
#print "...ns responder =", object.__repr__(h) ###
|
||||
#print "...ns base class =", b ###
|
||||
#print "...ns method =", m ###
|
||||
m(h, event._ns_event)
|
||||
|
||||
def mouse_down(self, event):
|
||||
if self._ns_handle_mouse:
|
||||
self._ns_pass_to_platform(event, ns_mouse_down_methods[event.button])
|
||||
|
||||
def mouse_drag(self, event):
|
||||
if self._ns_handle_mouse:
|
||||
self._ns_pass_to_platform(event, 'mouseDragged_')
|
||||
|
||||
def mouse_up(self, event):
|
||||
if self._ns_handle_mouse:
|
||||
self._ns_pass_to_platform(event, ns_mouse_up_methods[event.button])
|
||||
|
||||
def mouse_move(self, event):
|
||||
#self._ns_pass_to_platform(event, 'mouseMoved_')
|
||||
pass
|
||||
|
||||
def mouse_enter(self, event):
|
||||
#self._ns_pass_to_platform(event, 'mouseEntered_')
|
||||
pass
|
||||
|
||||
def mouse_leave(self, event):
|
||||
#self._ns_pass_to_platform(event, 'mouseExited_')
|
||||
pass
|
||||
|
||||
def key_down(self, event):
|
||||
#print "Component.key_down:", repr(event.char), "for", self ###
|
||||
self._ns_pass_to_platform(event, 'keyDown_')
|
||||
|
||||
def key_up(self, event):
|
||||
self._ns_pass_to_platform(event, 'keyUp_')
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
ns_mouse_down_methods = {
|
||||
'left': 'mouseDown_', 'middle': 'otherMouseDown_', 'right': 'rightMouseDown_'
|
||||
}
|
||||
|
||||
ns_mouse_up_methods = {
|
||||
'left': 'mouseUp_', 'middle': 'otherMouseUp_', 'right': 'rightMouseUp_'
|
||||
}
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
export(Component)
|
||||
@@ -0,0 +1,31 @@
|
||||
#
|
||||
# Python GUI - Containers - PyObjC version
|
||||
#
|
||||
|
||||
from AppKit import NSView
|
||||
from GUI.Utils import PyGUI_Flipped_NSView
|
||||
from GUI import export
|
||||
from GUI.GContainers import Container as GContainer
|
||||
|
||||
class Container(GContainer):
|
||||
# _ns_inner_view NSView Containing NSView for subcomponents
|
||||
|
||||
# def __init__(self, _ns_view, **kwds):
|
||||
# GContainer.__init__(self, _ns_view = _ns_view, **kwds)
|
||||
|
||||
# def destroy(self):
|
||||
# #print "Container.destroy:", self ###
|
||||
# GContainer.destroy(self)
|
||||
# #print "Container.destroy: breaking inner link to", self._ns_inner_view ###
|
||||
|
||||
def _add(self, comp):
|
||||
GContainer._add(self, comp)
|
||||
self._ns_inner_view.addSubview_(comp._ns_view)
|
||||
|
||||
def _remove(self, comp):
|
||||
GContainer._remove(self, comp)
|
||||
comp._ns_view.removeFromSuperview()
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
export(Container)
|
||||
@@ -0,0 +1,68 @@
|
||||
#
|
||||
# Python GUI - Controls - PyObjC
|
||||
#
|
||||
|
||||
from math import ceil
|
||||
from Foundation import NSSize
|
||||
import AppKit
|
||||
from GUI import export
|
||||
from GUI import StdColors
|
||||
from GUI import Color
|
||||
from GUI import Font
|
||||
from GUI.GControls import Control as GControl
|
||||
|
||||
_ns_alignment_from_just = {
|
||||
'left': AppKit.NSLeftTextAlignment,
|
||||
'center': AppKit.NSCenterTextAlignment,
|
||||
'centre': AppKit.NSCenterTextAlignment,
|
||||
'right': AppKit.NSRightTextAlignment,
|
||||
'flush': AppKit.NSJustifiedTextAlignment,
|
||||
'': AppKit.NSNaturalTextAlignment,
|
||||
}
|
||||
|
||||
_ns_alignment_to_just = {
|
||||
AppKit.NSLeftTextAlignment: 'left',
|
||||
AppKit.NSCenterTextAlignment: 'center',
|
||||
AppKit.NSRightTextAlignment: 'right',
|
||||
AppKit.NSJustifiedTextAlignment: 'flush',
|
||||
AppKit.NSNaturalTextAlignment: '',
|
||||
}
|
||||
|
||||
class Control(GControl):
|
||||
|
||||
#_vertical_padding = 5
|
||||
|
||||
def get_title(self):
|
||||
return self._ns_cell().title()
|
||||
|
||||
def set_title(self, v):
|
||||
self._ns_cell().setTitle_(v)
|
||||
|
||||
def get_enabled(self):
|
||||
return self._ns_cell().enabled()
|
||||
|
||||
def set_enabled(self, v):
|
||||
self._ns_cell().setEnabled_(v)
|
||||
|
||||
def get_color(self):
|
||||
return StdColors.black
|
||||
|
||||
def set_color(self, v):
|
||||
pass
|
||||
|
||||
def get_font(self):
|
||||
return Font._from_ns_font(self._ns_cell().font())
|
||||
|
||||
def set_font(self, f):
|
||||
self._ns_cell().setFont_(f._ns_font)
|
||||
|
||||
def get_just(self):
|
||||
return _ns_alignment_to_just[self._ns_cell().alignment()]
|
||||
|
||||
def set_just(self, v):
|
||||
self._ns_cell().setAlignment_(_ns_alignment_from_just[v])
|
||||
|
||||
def _ns_cell(self):
|
||||
return self._ns_inner_view.cell()
|
||||
|
||||
export(Control)
|
||||
@@ -0,0 +1,27 @@
|
||||
#
|
||||
# Python GUI - Cursors - Cocoa
|
||||
#
|
||||
|
||||
from AppKit import NSCursor
|
||||
from GUI import export
|
||||
from GUI.GCursors import Cursor as GCursor
|
||||
|
||||
class Cursor(GCursor):
|
||||
#
|
||||
# _ns_cursor NSCursor
|
||||
|
||||
def _from_ns_cursor(cls, ns_cursor):
|
||||
cursor = cls.__new__(cls)
|
||||
cursor._ns_cursor = ns_cursor
|
||||
return cursor
|
||||
|
||||
_from_ns_cursor = classmethod(_from_ns_cursor)
|
||||
|
||||
def _init_from_image_and_hotspot(self, image, hotspot):
|
||||
#print "Cursor._init_from_image_and_hotspot:", image, hotspot ###
|
||||
ns_image = image._ns_image.copy()
|
||||
ns_image.setFlipped_(False)
|
||||
self._ns_cursor = NSCursor.alloc().initWithImage_hotSpot_(
|
||||
ns_image, hotspot)
|
||||
|
||||
export(Cursor)
|
||||
@@ -0,0 +1,17 @@
|
||||
#
|
||||
# Python GUI - Dialogs - Cocoa
|
||||
#
|
||||
|
||||
from GUI import export
|
||||
from GUI.GDialogs import Dialog #as GDialog
|
||||
|
||||
#class Dialog(GDialog):
|
||||
#
|
||||
# _default_keys = ['\r']
|
||||
# _cancel_keys = ['\x1b']
|
||||
#
|
||||
# def key_down(self, event):
|
||||
# # Cocoa already takes care of default/cancel button activation
|
||||
# self.pass_to_next_handler('key_down', event)
|
||||
|
||||
export(Dialog)
|
||||
@@ -0,0 +1,86 @@
|
||||
#
|
||||
# Python GUI - DrawableContainers - PyObjC
|
||||
#
|
||||
|
||||
from Foundation import NSMakeRect
|
||||
from AppKit import NSView, NSScrollView, NSColor
|
||||
from GUI import export
|
||||
from GUI.Utils import PyGUI_Flipped_NSView
|
||||
from GUI import Canvas
|
||||
from GUI.Geometry import rect_to_ns_rect
|
||||
from GUI.Utils import NSMultiClass, PyGUI_NS_ViewBase
|
||||
from GUI.GDrawableContainers import default_size, \
|
||||
DrawableContainer as GDrawableContainer
|
||||
|
||||
ns_gray = NSColor.grayColor()
|
||||
|
||||
class DrawableContainer(GDrawableContainer):
|
||||
|
||||
def __init__(self, **kwds):
|
||||
width, height = default_size
|
||||
ns_frame = NSMakeRect(0, 0, width, height)
|
||||
ns_inner_view = PyGUI_User_NSView.alloc().initWithFrame_(ns_frame)
|
||||
if self._ns_scrollable:
|
||||
ns_view = NSScrollView.alloc().initWithFrame_(ns_frame)
|
||||
ns_view.setDocumentView_(ns_inner_view)
|
||||
ns_view.setBackgroundColor_(ns_gray)
|
||||
else:
|
||||
ns_view = ns_inner_view
|
||||
ns_inner_view.pygui_component = self
|
||||
GDrawableContainer.__init__(self, _ns_view = ns_view, _ns_inner_view = ns_inner_view)
|
||||
self.set(**kwds)
|
||||
|
||||
def destroy(self):
|
||||
#print "View.destroy:", self ###
|
||||
ns_inner_view = self._ns_inner_view
|
||||
GDrawableContainer.destroy(self)
|
||||
if ns_inner_view:
|
||||
#print "View.destroy: breaking back link from", ns_inner_view ###
|
||||
ns_inner_view.pygui_component = None
|
||||
|
||||
def get_background_color(self):
|
||||
ns_view = self._ns_inner_view
|
||||
if ns_view.drawsBackground():
|
||||
return Color._from_ns_color(ns_view.backgroundColor())
|
||||
|
||||
def set_background_color(self, x):
|
||||
ns_view = self._ns_inner_view
|
||||
if x:
|
||||
ns_view.setBackgroundColor_(x._ns_color)
|
||||
ns_view.setDrawsBackground_(True)
|
||||
else:
|
||||
ns_view.setDrawsBackground_(False)
|
||||
|
||||
def invalidate(self):
|
||||
self._ns_inner_view.setNeedsDisplay_(True)
|
||||
|
||||
def invalidate_rect(self, r):
|
||||
self._ns_inner_view.setNeedsDisplayInRect_(rect_to_ns_rect(r))
|
||||
|
||||
def with_canvas(self, proc):
|
||||
ns_view = self._ns_view
|
||||
ns_view.lockFocus()
|
||||
proc(Canvas())
|
||||
ns_view.unlockFocus()
|
||||
|
||||
def update(self):
|
||||
self._ns_view.displayIfNeeded()
|
||||
|
||||
def track_mouse(self):
|
||||
return self._ns_track_mouse(self._ns_inner_view)
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class PyGUI_User_NSView(PyGUI_Flipped_NSView, PyGUI_NS_ViewBase):
|
||||
#
|
||||
# pygui_component View
|
||||
|
||||
__metaclass__ = NSMultiClass
|
||||
__slots__ = ['pygui_component']
|
||||
|
||||
def drawRect_(self, ns_rect):
|
||||
(l, t), (w, h) = ns_rect
|
||||
rect = (l, t, l + w, t + h)
|
||||
self.pygui_component.draw(Canvas(), rect)
|
||||
|
||||
export(DrawableContainer)
|
||||
@@ -0,0 +1,62 @@
|
||||
#
|
||||
# PyGUI - Edit command handling - Cocoa
|
||||
#
|
||||
|
||||
from AppKit import NSMenuItem
|
||||
from GUI import export
|
||||
|
||||
class EditCmdHandler(object):
|
||||
# Mixin for Components whose _ns_responder handles the
|
||||
# standard editing commands.
|
||||
|
||||
def setup_menus(self, m):
|
||||
def validate(cmd_name, ns_selector):
|
||||
ns_menu_item = NSMenuItem.alloc().\
|
||||
initWithTitle_action_keyEquivalent_("", ns_selector, "")
|
||||
m[cmd_name].enabled = ns_target.validateMenuItem_(ns_menu_item)
|
||||
ns_target = self.window._ns_window
|
||||
if ns_target:
|
||||
validate('undo_cmd', 'undo:')
|
||||
validate('redo_cmd', 'redo:')
|
||||
ns_target = self._ns_edit_cmd_target()
|
||||
if ns_target:
|
||||
validate('cut_cmd', 'cut:')
|
||||
validate('copy_cmd', 'copy:')
|
||||
validate('paste_cmd', 'paste:')
|
||||
validate('clear_cmd', 'delete:')
|
||||
validate('select_all_cmd', 'selectAll:')
|
||||
|
||||
def undo_cmd(self):
|
||||
ns_window = self.window._ns_window
|
||||
if ns_window:
|
||||
ns_window.undo_(None)
|
||||
|
||||
def redo_cmd(self):
|
||||
ns_window = self.window._ns_window
|
||||
if ns_window:
|
||||
ns_window.redo_(None)
|
||||
|
||||
def cut_cmd(self):
|
||||
self._ns_edit_cmd('cut_')
|
||||
|
||||
def copy_cmd(self):
|
||||
self._ns_edit_cmd('copy_')
|
||||
|
||||
def paste_cmd(self):
|
||||
self._ns_edit_cmd('paste_')
|
||||
|
||||
def clear_cmd(self):
|
||||
self._ns_edit_cmd('delete_')
|
||||
|
||||
def select_all_cmd(self):
|
||||
self._ns_edit_cmd('selectAll_')
|
||||
|
||||
def _ns_edit_cmd(self, ns_method_name):
|
||||
ns_target = self._ns_edit_cmd_target()
|
||||
if ns_target:
|
||||
getattr(ns_target, ns_method_name)(None)
|
||||
|
||||
def _ns_edit_cmd_target(self):
|
||||
return self._ns_responder
|
||||
|
||||
export(EditCmdHandler)
|
||||
@@ -0,0 +1,167 @@
|
||||
#
|
||||
# Python GUI - Events - PyObjC version
|
||||
#
|
||||
|
||||
import AppKit
|
||||
from AppKit import NSEvent, \
|
||||
NSShiftKeyMask, NSControlKeyMask, NSCommandKeyMask, NSAlternateKeyMask
|
||||
from GUI import export
|
||||
from GUI import Globals
|
||||
from GUI.GEvents import Event as GEvent
|
||||
|
||||
_ns_event_type_to_kind = {
|
||||
AppKit.NSLeftMouseDown: 'mouse_down',
|
||||
AppKit.NSLeftMouseUp: 'mouse_up',
|
||||
AppKit.NSRightMouseDown: 'mouse_down',
|
||||
AppKit.NSRightMouseUp: 'mouse_up',
|
||||
AppKit.NSOtherMouseDown: 'mouse_down',
|
||||
AppKit.NSOtherMouseUp: 'mouse_up',
|
||||
AppKit.NSMouseMoved: 'mouse_move',
|
||||
AppKit.NSLeftMouseDragged: 'mouse_drag',
|
||||
AppKit.NSRightMouseDragged: 'mouse_drag',
|
||||
AppKit.NSOtherMouseDragged: 'mouse_drag',
|
||||
AppKit.NSMouseEntered: 'mouse_enter',
|
||||
AppKit.NSMouseExited: 'mouse_leave',
|
||||
AppKit.NSKeyDown: 'key_down',
|
||||
AppKit.NSKeyUp: 'key_up',
|
||||
AppKit.NSFlagsChanged: 'flags_changed',
|
||||
AppKit.NSAppKitDefined: 'app_kit_defined',
|
||||
AppKit.NSSystemDefined: 'system_defined',
|
||||
AppKit.NSApplicationDefined: 'application_defined',
|
||||
AppKit.NSPeriodic: 'periodic',
|
||||
AppKit.NSCursorUpdate: 'cursor_update',
|
||||
}
|
||||
|
||||
_ns_event_type_to_button = {
|
||||
AppKit.NSLeftMouseDown: 'left',
|
||||
AppKit.NSLeftMouseUp: 'left',
|
||||
AppKit.NSRightMouseDown: 'right',
|
||||
AppKit.NSRightMouseUp: 'right',
|
||||
AppKit.NSOtherMouseDown: 'middle',
|
||||
AppKit.NSOtherMouseUp: 'middle',
|
||||
AppKit.NSLeftMouseDragged: 'left',
|
||||
AppKit.NSRightMouseDragged: 'right',
|
||||
AppKit.NSOtherMouseDragged: 'middle',
|
||||
}
|
||||
|
||||
_ns_keycode_to_keyname = {
|
||||
AppKit.NSUpArrowFunctionKey: 'up_arrow',
|
||||
AppKit.NSDownArrowFunctionKey: 'down_arrow',
|
||||
AppKit.NSLeftArrowFunctionKey: 'left_arrow',
|
||||
AppKit.NSRightArrowFunctionKey: 'right_arrow',
|
||||
AppKit.NSF1FunctionKey: 'f1',
|
||||
AppKit.NSF2FunctionKey: 'f2',
|
||||
AppKit.NSF3FunctionKey: 'f3',
|
||||
AppKit.NSF4FunctionKey: 'f4',
|
||||
AppKit.NSF5FunctionKey: 'f5',
|
||||
AppKit.NSF6FunctionKey: 'f6',
|
||||
AppKit.NSF7FunctionKey: 'f7',
|
||||
AppKit.NSF8FunctionKey: 'f8',
|
||||
AppKit.NSF9FunctionKey: 'f9',
|
||||
AppKit.NSF10FunctionKey: 'f10',
|
||||
AppKit.NSF11FunctionKey: 'f11',
|
||||
AppKit.NSF12FunctionKey: 'f12',
|
||||
AppKit.NSF13FunctionKey: 'f13',
|
||||
AppKit.NSF14FunctionKey: 'f14',
|
||||
AppKit.NSF15FunctionKey : 'f15',
|
||||
AppKit.NSDeleteFunctionKey: 'delete',
|
||||
AppKit.NSHomeFunctionKey: 'home',
|
||||
AppKit.NSEndFunctionKey: 'end',
|
||||
AppKit.NSPageUpFunctionKey: 'page_up',
|
||||
AppKit.NSPageDownFunctionKey: 'page_down',
|
||||
AppKit.NSClearLineFunctionKey: 'clear',
|
||||
#AppKit.NSHelpFunctionKey: 'help',
|
||||
AppKit.NSHelpFunctionKey: 'insert',
|
||||
"\r": 'return',
|
||||
"\x03": 'enter',
|
||||
}
|
||||
|
||||
_mouse_events = [
|
||||
'mouse_down', 'mouse_drag', 'mouse_up',
|
||||
'mouse_move', 'mouse_enter', 'mouse_exit'
|
||||
]
|
||||
|
||||
_key_events = [
|
||||
'key_down', 'key_up'
|
||||
]
|
||||
|
||||
_ns_screen_height = None
|
||||
|
||||
class Event(GEvent):
|
||||
"""Platform-dependent modifiers (boolean):
|
||||
command The Macintosh Command key.
|
||||
option The Macintosh Option key.
|
||||
"""
|
||||
|
||||
global_position = (0, 0)
|
||||
position = (0, 0)
|
||||
button = ''
|
||||
num_clicks = 0
|
||||
char = ""
|
||||
unichars = ""
|
||||
key = ''
|
||||
auto = False
|
||||
delta = (0, 0)
|
||||
|
||||
def __init__(self, ns_event):
|
||||
self._ns_event = ns_event
|
||||
_ns_type = ns_event.type()
|
||||
kind = _ns_event_type_to_kind[_ns_type]
|
||||
self.kind = kind
|
||||
self.time = ns_event.timestamp()
|
||||
ns_window = ns_event.window()
|
||||
is_mouse_event = kind in _mouse_events
|
||||
if is_mouse_event:
|
||||
ns_win_pos = ns_event.locationInWindow()
|
||||
x, y = ns_window.convertBaseToScreen_(ns_win_pos)
|
||||
else:
|
||||
ns_last_mouse = Globals.ns_last_mouse_moved_event
|
||||
if ns_last_mouse:
|
||||
ns_window = ns_last_mouse.window()
|
||||
if ns_window:
|
||||
ns_win_pos = ns_last_mouse.locationInWindow()
|
||||
x, y = ns_window.convertBaseToScreen_(ns_win_pos)
|
||||
else:
|
||||
x, y = ns_last_mouse.locationInWindow()
|
||||
else:
|
||||
x, y = NSEvent.mouseLocation()
|
||||
h = Globals.ns_screen_height
|
||||
self.global_position = (x, h - y)
|
||||
if is_mouse_event:
|
||||
self.button = _ns_event_type_to_button.get(_ns_type, '')
|
||||
if kind == 'mouse_down':
|
||||
self.num_clicks = ns_event.clickCount()
|
||||
self.delta = (ns_event.deltaX(), ns_event.deltaY())
|
||||
ns_flags = ns_event.modifierFlags()
|
||||
self.shift = self.extend_contig = (ns_flags & NSShiftKeyMask) <> 0
|
||||
self.control = (ns_flags & NSControlKeyMask) <> 0
|
||||
self.command = self.extend_noncontig = (ns_flags & NSCommandKeyMask) <> 0
|
||||
self.option = (ns_flags & NSAlternateKeyMask) <> 0
|
||||
if kind in _key_events:
|
||||
self.auto = ns_event.isARepeat()
|
||||
ns_chars = ns_event.characters()
|
||||
#print "Event.__init__: ns_chars =", repr(ns_chars) ###
|
||||
self.unichars = ns_chars
|
||||
if len(ns_chars) == 1:
|
||||
if ns_chars == "\x19" and ns_event.keyCode() == 48:
|
||||
self.char = "\t"
|
||||
elif ns_chars == "\x7f":
|
||||
self.char = "\x08"
|
||||
elif ns_chars <= "\x7e":
|
||||
self.char = str(ns_chars)
|
||||
#else:
|
||||
# self.char = ns_chars
|
||||
ns_unmod = ns_event.charactersIgnoringModifiers()
|
||||
key = _ns_keycode_to_keyname.get(ns_chars, '')
|
||||
if not key and u"\x20" <= ns_unmod <= u"\x7e":
|
||||
key = str(ns_unmod)
|
||||
self.key = key
|
||||
if key == 'enter':
|
||||
self.char = "\r"
|
||||
elif key == 'delete':
|
||||
self.char = "\x7f"
|
||||
|
||||
def _platform_modifiers_str(self):
|
||||
return " command:%s option:%s" % (self.command, self.option)
|
||||
|
||||
export(Event)
|
||||
@@ -0,0 +1,43 @@
|
||||
#
|
||||
# Python GUI - File references and types - Cocoa
|
||||
#
|
||||
|
||||
from struct import unpack
|
||||
from Foundation import NSFileTypeForHFSTypeCode, \
|
||||
NSFileManager, NSFileHFSCreatorCode, NSFileHFSTypeCode
|
||||
from GUI.GFiles import FileRef as GFileRef, DirRef, FileType as GFileType
|
||||
|
||||
class FileType(GFileType):
|
||||
|
||||
def _ns_file_types(self):
|
||||
# Return list of Cocoa file type specifications matched
|
||||
# by this file type.
|
||||
result = []
|
||||
mac_type = self._mac_type
|
||||
if mac_type:
|
||||
result.append(NSFileTypeForHFSTypeCode(mac_type))
|
||||
suffix = self._suffix
|
||||
if suffix:
|
||||
result.append(suffix)
|
||||
return result
|
||||
|
||||
|
||||
class FileRef(GFileRef):
|
||||
|
||||
def _set_type(self, file_type):
|
||||
creator = file_type.mac_creator
|
||||
type = file_type.mac_type
|
||||
if creator is not None or type is not None:
|
||||
fm = NSFileManager.defaultManager()
|
||||
attrs = {}
|
||||
if creator is not None:
|
||||
attrs[NSFileHFSCreatorCode] = four_char_code(creator)
|
||||
if type is not None:
|
||||
attrs[NSFileHFSTypeCode] = four_char_code(type)
|
||||
#print "FileRef: Setting attributes of %r to %s" % ( ###
|
||||
# self.path, attrs) ###
|
||||
fm.changeFileAttributes_atPath_(attrs, self.path)
|
||||
|
||||
|
||||
def four_char_code(chars):
|
||||
return unpack(">L", chars)[0]
|
||||
@@ -0,0 +1,77 @@
|
||||
#
|
||||
# Python GUI - Fonts - PyObjC
|
||||
#
|
||||
|
||||
import sys
|
||||
from AppKit import NSFont, NSFontManager, NSBoldFontMask, NSItalicFontMask, \
|
||||
NSLayoutManager
|
||||
from GUI import export
|
||||
from GUI.GFonts import Font as GFont
|
||||
|
||||
_ns_font_manager = NSFontManager.sharedFontManager()
|
||||
_ns_layout_manager = NSLayoutManager.alloc().init()
|
||||
|
||||
class Font(GFont):
|
||||
# _ns_font NSFont
|
||||
|
||||
def _from_ns_font(cls, ns_font):
|
||||
font = cls.__new__(cls)
|
||||
font._ns_font = ns_font
|
||||
return font
|
||||
|
||||
_from_ns_font = classmethod(_from_ns_font)
|
||||
|
||||
def __init__(self, family, size = 12, style = []):
|
||||
traits = 0
|
||||
if 'bold' in style:
|
||||
traits |= NSBoldFontMask
|
||||
if 'italic' in style:
|
||||
traits |= NSItalicFontMask
|
||||
self._ns_font = _ns_font_manager.fontWithFamily_traits_weight_size_(
|
||||
family, traits, 5, size)
|
||||
if not self._ns_font:
|
||||
import StdFonts
|
||||
self._ns_font = StdFonts.application_font._ns_font
|
||||
|
||||
def get_family(self):
|
||||
return self._ns_font.familyName()
|
||||
|
||||
def get_size(self):
|
||||
return self._ns_font.pointSize()
|
||||
|
||||
def get_style(self):
|
||||
style = []
|
||||
traits = _ns_font_manager.traitsOfFont_(self._ns_font)
|
||||
if traits & NSBoldFontMask:
|
||||
style.append('bold')
|
||||
if traits & NSItalicFontMask:
|
||||
style.append('italic')
|
||||
return style
|
||||
|
||||
def get_ascent(self):
|
||||
return self._ns_font.ascender()
|
||||
|
||||
def get_descent(self):
|
||||
return -self._ns_font.descender()
|
||||
|
||||
def get_height(self):
|
||||
ns_font = self._ns_font
|
||||
a = ns_font.ascender()
|
||||
d = ns_font.descender()
|
||||
return a - d
|
||||
|
||||
def get_cap_height(self):
|
||||
return self._ns_font.capHeight()
|
||||
|
||||
def get_x_height(self):
|
||||
return self._ns_font.xHeight()
|
||||
|
||||
def get_line_height(self):
|
||||
# Adding 1 here to match what NSTextField seems to do
|
||||
return _ns_layout_manager.defaultLineHeightForFont_(self._ns_font) + 1
|
||||
|
||||
def width(self, s, start = 0, end = sys.maxint):
|
||||
return self._ns_font.widthOfString_(s[start:end])
|
||||
|
||||
export(Font)
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
#------------------------------------------------------------------------------
|
||||
#
|
||||
# Python GUI - Frames - Cocoa
|
||||
#
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
from GUI.GFrames import Frame as GFrame
|
||||
from GUI import export
|
||||
from GUI.Utils import NSMultiClass
|
||||
from GUI.Utils import PyGUI_NS_EventHandler, PyGUI_Flipped_NSView
|
||||
|
||||
class Frame(GFrame):
|
||||
|
||||
def __init__(self, **kwds):
|
||||
ns_view = PyGUI_Frame.alloc().initWithFrame_(((0, 0), (100, 100)))
|
||||
ns_view.pygui_component = self
|
||||
GFrame.__init__(self, _ns_view = ns_view, **kwds)
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class PyGUI_Frame(PyGUI_Flipped_NSView, PyGUI_NS_EventHandler):
|
||||
__metaclass__ = NSMultiClass
|
||||
__slots__ = ['pygui_component']
|
||||
|
||||
export(Frame)
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
#
|
||||
# PyGUI - OpenGL View - Cocoa
|
||||
#
|
||||
|
||||
__all__ = ['GLConfig', 'GLView', 'GLPixmap']
|
||||
|
||||
import AppKit
|
||||
from Foundation import NSSize
|
||||
from AppKit import NSOpenGLPixelFormat, NSOpenGLView, \
|
||||
NSBitmapImageRep, NSCachedImageRep, NSImage, NSAlphaFirstBitmapFormat, \
|
||||
NSFloatingPointSamplesBitmapFormat
|
||||
from Foundation import NSMakeRect
|
||||
from OpenGL.GL import glViewport, glFlush, glFinish, glReadPixels, \
|
||||
GL_RGB, GL_RGBA, GL_LUMINANCE, GL_LUMINANCE_ALPHA, \
|
||||
GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT, GL_UNSIGNED_INT, GL_FLOAT, \
|
||||
glReadPixelsub, glTexImage2D, glPixelStorei, GL_UNPACK_ALIGNMENT
|
||||
from OpenGL.GLU import gluBuild2DMipmaps
|
||||
from GUI.GGLViews import GLView as GGLView
|
||||
from GUI.GGLPixmaps import GLPixmap as GGLPixmap
|
||||
from GUI.GGLConfig import GLConfig as GGLConfig
|
||||
from GUI.GLContexts import GLContext
|
||||
from GUI.GLTextures import Texture
|
||||
from GUI.GLDisplayLists import DisplayList
|
||||
from GUI.Utils import NSMultiClass, PyGUI_NS_ViewBase
|
||||
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class GLConfig(GGLConfig):
|
||||
# _ns_pixel_format NSOpenGLPixelFormat
|
||||
|
||||
def _ns_get_pixel_format(self, offscreen = False):
|
||||
attrs = [AppKit.NSOpenGLPFAColorSize, self._color_size]
|
||||
if self._double_buffer:
|
||||
attrs += [AppKit.NSOpenGLPFADoubleBuffer]
|
||||
if self._alpha:
|
||||
attrs += [AppKit.NSOpenGLPFAAlphaSize, self._alpha_size]
|
||||
if self._stereo:
|
||||
attrs += [AppKit.NSOpenGLPFAStereo]
|
||||
if self._aux_buffers:
|
||||
attrs += [AppKit.NSOpenGLPFAAuxBuffers, self._aux_buffers]
|
||||
if self._depth_buffer:
|
||||
attrs += [AppKit.NSOpenGLPFADepthSize, self._depth_size]
|
||||
if self._stencil_buffer:
|
||||
attrs += [AppKit.NSOpenGLPFAStencilSize, self._stencil_size]
|
||||
if self._accum_buffer:
|
||||
attrs += [AppKit.NSOpenGLPFAAccumSize, self._accum_size]
|
||||
if self._multisample:
|
||||
attrs += [AppKit.NSOpenGLPFASampleBuffers, 1]
|
||||
attrs += [AppKit.NSOpenGLPFASamples, self._samples_per_pixel]
|
||||
if offscreen:
|
||||
attrs += [AppKit.NSOpenGLPFAOffScreen]
|
||||
attrs.append(0)
|
||||
ns_pf = NSOpenGLPixelFormat.alloc().initWithAttributes_(attrs)
|
||||
if not ns_pf and self._double_buffer:
|
||||
attrs.remove(AppKit.NSOpenGLPFADoubleBuffer)
|
||||
ns_pf = NSOpenGLPixelFormat.alloc().initWithAttributes_(attrs)
|
||||
if not ns_pf:
|
||||
raise GLConfigError
|
||||
return ns_pf
|
||||
|
||||
def _ns_set_pixel_format(self, ns_pf):
|
||||
def ns_attr(attr):
|
||||
return ns_pf.getValues_forAttribute_forVirtualScreen_(attr, 0)[0]
|
||||
self._ns_pixel_format = ns_pf
|
||||
self._double_buffer = ns_attr(AppKit.NSOpenGLPFADoubleBuffer)
|
||||
self._color_size = ns_attr(AppKit.NSOpenGLPFAColorSize)
|
||||
self._alpha_size = ns_attr(AppKit.NSOpenGLPFAAlphaSize)
|
||||
self._alpha = self._alpha_size > 0
|
||||
self._stereo = ns_attr(AppKit.NSOpenGLPFAStereo)
|
||||
self._aux_buffers = ns_attr(AppKit.NSOpenGLPFAAuxBuffers)
|
||||
self._depth_size = ns_attr(AppKit.NSOpenGLPFADepthSize)
|
||||
self._depth_buffer = self._depth_size > 0
|
||||
self._stencil_size = ns_attr(AppKit.NSOpenGLPFAStencilSize)
|
||||
self._stencil_buffer = self._stencil_size > 0
|
||||
self._accum_size = ns_attr(AppKit.NSOpenGLPFAAccumSize)
|
||||
self._accum_buffer = self._accum_size > 0
|
||||
self._multisample = ns_attr(AppKit.NSOpenGLPFASampleBuffers) > 0
|
||||
self._samples_per_pixel = ns_attr(AppKit.NSOpenGLPFASamples)
|
||||
|
||||
def supported(self, mode = 'both'):
|
||||
try:
|
||||
ns_pf = self._ns_get_pixel_format()
|
||||
pf = GLConfig.__new__()
|
||||
pf._ns_set_pixel_format(ns_pf)
|
||||
return pf
|
||||
except GLConfigError:
|
||||
return None
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class GLView(GGLView):
|
||||
# _ns_view NSOpenGLView
|
||||
# _ns_context NSOpenGLContext
|
||||
# _ns_flush function for flushing/swapping buffers
|
||||
|
||||
def __init__(self, config = None, share_group = None, **kwds):
|
||||
pf = GLConfig._from_args(config, kwds)
|
||||
ns_pf = pf._ns_get_pixel_format()
|
||||
width, height = GGLView._default_size
|
||||
ns_rect = NSMakeRect(0, 0, width, height)
|
||||
ns_view = _PyGUI_NSOpenGLView.alloc().initWithFrame_pixelFormat_(
|
||||
ns_rect, ns_pf)
|
||||
ns_view.pygui_component = self
|
||||
GGLView.__init__(self, _ns_view = ns_view)
|
||||
GLContext.__init__(self, share_group = share_group, _ns_pixel_format = ns_pf)
|
||||
ns_context = self._ns_context
|
||||
ns_view.setOpenGLContext_(ns_context)
|
||||
#ns_context.setView_(ns_view) # Docs say this is needed, but
|
||||
# prints warning and seems to work without.
|
||||
if pf.double_buffer:
|
||||
self._ns_flush = ns_context.flushBuffer
|
||||
else:
|
||||
self._ns_flush = glFlush
|
||||
self.set(**kwds)
|
||||
self.with_context(self._init_context)
|
||||
|
||||
def destroy(self):
|
||||
#print "GLView.destroy:", self ###
|
||||
ns_view = self._ns_view
|
||||
GGLView.destroy(self)
|
||||
#print "GLView.destroy: breaking back link from", ns_view ###
|
||||
ns_view.pygui_component = None
|
||||
|
||||
def invalidate(self):
|
||||
self._ns_view.setNeedsDisplay_(True)
|
||||
|
||||
def update(self):
|
||||
self._ns_view.displayIfNeeded()
|
||||
|
||||
def track_mouse(self):
|
||||
return self._ns_track_mouse(self._ns_view)
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class GLPixmap(GGLPixmap):
|
||||
|
||||
def __init__(self, width, height, config = None, share_group = None, **kwds):
|
||||
pf = GLConfig._from_args(config, kwds)
|
||||
ns_pf = pf._ns_get_pixel_format()
|
||||
ns_size = NSSize(width, height)
|
||||
ns_cache = NSCachedImageRep.alloc().initWithSize_depth_separate_alpha_(
|
||||
ns_size, 0, True, True)
|
||||
ns_image = NSImage.alloc().initWithSize_(ns_size)
|
||||
GLContext.__init__(self, share_group = share_group, _ns_pixel_format = ns_pf)
|
||||
self._ns_context.setView_(ns_cache.window().contentView())
|
||||
self._init_with_ns_image(ns_image, flipped = False)
|
||||
self._ns_cache = ns_cache
|
||||
self.with_context(self._init_context)
|
||||
|
||||
def _ns_flush(self):
|
||||
glFlush()
|
||||
width, height = self.size
|
||||
pixels = glReadPixels(0, 0, int(width), int(height), GL_RGBA, GL_UNSIGNED_BYTE)
|
||||
bytes_per_row = int(width) * 4
|
||||
ns_new_bitmap = NSBitmapImageRep.alloc().\
|
||||
initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(
|
||||
(pixels, "", "", "", ""), int(width), int(height), 8, 4, True, False, AppKit.NSDeviceRGBColorSpace, bytes_per_row, 0)
|
||||
ns_image = NSImage.alloc().initWithSize_(NSSize(width, height))
|
||||
ns_image.addRepresentation_(ns_new_bitmap)
|
||||
ns_image.lockFocus()
|
||||
ns_image.unlockFocus()
|
||||
self._ns_image = ns_image
|
||||
self._ns_bitmap_image_rep = ns_new_bitmap
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class _PyGUI_NSOpenGLView(NSOpenGLView, PyGUI_NS_ViewBase):
|
||||
__metaclass__ = NSMultiClass
|
||||
#
|
||||
# pygui_component GLView
|
||||
|
||||
__slots__ = ['pygui_component']
|
||||
|
||||
def isFlipped(self):
|
||||
return True
|
||||
|
||||
def reshape(self):
|
||||
comp = self.pygui_component
|
||||
if comp.window:
|
||||
comp.with_context(comp._update_viewport)
|
||||
|
||||
def drawRect_(self, rect):
|
||||
comp = self.pygui_component
|
||||
comp.with_context(comp._render, flush = True)
|
||||
@@ -0,0 +1,35 @@
|
||||
#
|
||||
# PyGUI - OpenGL Contexts - Cocoa
|
||||
#
|
||||
|
||||
from AppKit import NSOpenGLContext
|
||||
from GUI.GGLContexts import GLContext as GGLContext
|
||||
|
||||
class GLContext(GGLContext):
|
||||
# _ns_context NSOpenGLContext
|
||||
|
||||
def __init__(self, share_group, _ns_pixel_format):
|
||||
GGLContext.__init__(self, share_group)
|
||||
shared_context = self._get_shared_context()
|
||||
if shared_context:
|
||||
ns_share = shared_context._ns_context
|
||||
else:
|
||||
ns_share = None
|
||||
ns_context = NSOpenGLContext.alloc().initWithFormat_shareContext_(
|
||||
_ns_pixel_format, ns_share)
|
||||
self._ns_context = ns_context
|
||||
|
||||
def _with_context(self, proc, flush):
|
||||
#print "GLContext._with_context: Entering context", self._ns_context ###
|
||||
old_context = NSOpenGLContext.currentContext()
|
||||
self._ns_context.makeCurrentContext()
|
||||
try:
|
||||
self._with_share_group(proc)
|
||||
if flush:
|
||||
self._ns_flush()
|
||||
finally:
|
||||
#print "GL: Restoring previous context" ###
|
||||
if old_context:
|
||||
old_context.makeCurrentContext()
|
||||
else:
|
||||
NSOpenGLContext.clearCurrentContext()
|
||||
@@ -0,0 +1,69 @@
|
||||
#
|
||||
# PyGUI - OpenGL Textures - Cocoa
|
||||
#
|
||||
|
||||
from AppKit import NSAlphaFirstBitmapFormat, NSFloatingPointSamplesBitmapFormat
|
||||
from OpenGL import GL
|
||||
from GUI.GGLTextures import Texture as GTexture
|
||||
|
||||
class Texture(GTexture):
|
||||
|
||||
def _gl_get_texture_data(self, image):
|
||||
ns_rep = image._ns_bitmap_image_rep
|
||||
if ns_rep.numberOfPlanes() <> 1:
|
||||
raise ValueError("Cannot use planar image data as GL texture")
|
||||
ns_format = ns_rep.bitmapFormat()
|
||||
if ns_format & NSAlphaFirstBitmapFormat:
|
||||
raise ValueError("Cannot use alpha-first image data as GL texture")
|
||||
fp_samples = ns_format & NSFloatingPointSamplesBitmapFormat <> 0
|
||||
bits_per_pixel = ns_rep.bitsPerPixel()
|
||||
bytes_per_row = ns_rep.bytesPerRow()
|
||||
samples_per_pixel = ns_rep.samplesPerPixel()
|
||||
if bits_per_pixel % samples_per_pixel <> 0:
|
||||
raise ValueError("Image data format not usable as GL texture")
|
||||
bits_per_sample = bits_per_pixel / samples_per_pixel
|
||||
try:
|
||||
gl_format = format_map[samples_per_pixel]
|
||||
gl_type = type_map[bits_per_sample, fp_samples]
|
||||
except KeyError:
|
||||
raise ValueError("Image data format not usable as GL texture")
|
||||
data = ns_rep.bitmapData()
|
||||
if 0:
|
||||
print "GUI.GLTexture._gl_get_texture_data_and_format:" ###
|
||||
print "format =", gl_format_map.get(gl_format) ###
|
||||
print "type =", gl_type_map.get(gl_type) ###
|
||||
print "data length =", len(data) ###
|
||||
print repr(data[:16]) ###
|
||||
GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1)
|
||||
return gl_format, gl_type, str(data)
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
format_map = {
|
||||
3: GL.GL_RGB,
|
||||
4: GL.GL_RGBA,
|
||||
1: GL.GL_LUMINANCE,
|
||||
2: GL.GL_LUMINANCE_ALPHA,
|
||||
}
|
||||
|
||||
type_map = {
|
||||
(8, 0): GL.GL_UNSIGNED_BYTE,
|
||||
(16, 0): GL.GL_UNSIGNED_SHORT,
|
||||
(32, 0): GL.GL_UNSIGNED_INT,
|
||||
(32, 1): GL.GL_FLOAT,
|
||||
}
|
||||
|
||||
gl_format_map = {
|
||||
GL.GL_RGB: 'GL_RGB',
|
||||
GL.GL_RGBA: 'GL_RGBA',
|
||||
GL.GL_LUMINANCE: 'GL_LUMINANCE',
|
||||
GL.GL_LUMINANCE_ALPHA: 'GL_LUMINANCE_ALPHA',
|
||||
}
|
||||
|
||||
gl_type_map = {
|
||||
GL.GL_UNSIGNED_BYTE: 'GL_UNSIGNED_BYTE',
|
||||
GL.GL_UNSIGNED_SHORT: 'GL_UNSIGNED_SHORT',
|
||||
GL.GL_UNSIGNED_INT: 'GL_UNSIGNED_INT',
|
||||
GL.GL_FLOAT: 'GL_FLOAT',
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
#
|
||||
# Python GUI - Points and Rectangles - PyObjC
|
||||
#
|
||||
|
||||
from Foundation import NSMakeRect
|
||||
from GUI.GGeometry import *
|
||||
|
||||
def rect_to_ns_rect((l, t, r, b)):
|
||||
return NSMakeRect(l, t, r - l, b - t)
|
||||
|
||||
def ns_rect_to_rect(((l, t), (w, h))):
|
||||
return (l, t, l + w, t + h)
|
||||
@@ -0,0 +1,31 @@
|
||||
#
|
||||
# Python GUI - Images - Cocoa
|
||||
#
|
||||
|
||||
from Foundation import NSData
|
||||
from AppKit import NSImage, NSBitmapImageRep
|
||||
from GUI import export
|
||||
from GUI.GImages import Image as GImage
|
||||
|
||||
class Image(GImage):
|
||||
# _ns_bitmap_image_rep
|
||||
|
||||
def _init_from_file(self, file):
|
||||
#ns_image = NSImage.alloc().initWithContentsOfFile_(file)
|
||||
#if not ns_image:
|
||||
ns_data = NSData.dataWithContentsOfFile_(file)
|
||||
if not ns_data:
|
||||
raise EnvironmentError("Unable to read image file: %s" % file)
|
||||
ns_rep = NSBitmapImageRep.imageRepWithData_(ns_data)
|
||||
if not ns_rep:
|
||||
raise ValueError("Unrecognised image file type: %s" % file)
|
||||
ns_rep.setSize_((ns_rep.pixelsWide(), ns_rep.pixelsHigh()))
|
||||
self._init_from_ns_rep(ns_rep)
|
||||
|
||||
def _init_from_ns_rep(self, ns_rep):
|
||||
ns_image = NSImage.alloc().init()
|
||||
ns_image.addRepresentation_(ns_rep)
|
||||
self._ns_bitmap_image_rep = ns_rep
|
||||
self._init_with_ns_image(ns_image, flipped = True)
|
||||
|
||||
export(Image)
|
||||
@@ -0,0 +1,33 @@
|
||||
#
|
||||
# Python GUI - Common Image/Pixmap code - Cocoa
|
||||
#
|
||||
|
||||
from AppKit import NSCompositeSourceOver
|
||||
from GUI import export
|
||||
from GUI.Geometry import rect_to_ns_rect
|
||||
from GUI.GImageBases import ImageBase as GImageBase
|
||||
|
||||
class ImageBase(GImageBase):
|
||||
#
|
||||
# Code common to Image, Pixmap and GLPixmap classes
|
||||
|
||||
def _init_with_ns_image(self, ns_image, flipped):
|
||||
ns_image.setFlipped_(flipped)
|
||||
self._ns_image = ns_image
|
||||
|
||||
def get_size(self):
|
||||
return tuple(self._ns_image.size())
|
||||
|
||||
def get_width(self):
|
||||
return self._ns_image.size()[0]
|
||||
|
||||
def get_height(self):
|
||||
return self._ns_image.size()[1]
|
||||
|
||||
def draw(self, canvas, src_rect, dst_rect):
|
||||
ns_src_rect = rect_to_ns_rect(src_rect)
|
||||
ns_dst_rect = rect_to_ns_rect(dst_rect)
|
||||
self._ns_image.drawInRect_fromRect_operation_fraction_(
|
||||
ns_dst_rect, ns_src_rect, NSCompositeSourceOver, 1.0)
|
||||
|
||||
export(ImageBase)
|
||||
@@ -0,0 +1,28 @@
|
||||
#
|
||||
# Python GUI - Labels - PyObjC
|
||||
#
|
||||
|
||||
import AppKit
|
||||
from AppKit import NSView
|
||||
from GUI import export
|
||||
from GUI.StdFonts import system_font
|
||||
from GUI.TextFieldBasedControls import TextFieldBasedControl
|
||||
from GUI.GLabels import Label as GLabel
|
||||
|
||||
ns_label_autoresizing_mask = (AppKit.NSViewWidthSizable
|
||||
| AppKit.NSViewHeightSizable)
|
||||
|
||||
class Label(TextFieldBasedControl, GLabel):
|
||||
|
||||
def __init__(self, text = "New Label", font = system_font, **kwds):
|
||||
ns_textfield = self._create_ns_textfield(editable = False,
|
||||
text = text, font = font)
|
||||
# width, height = ns_textfield.frame().size
|
||||
# ns_view = NSView.alloc().initWithFrame_(((0, 0), (width, height + 5)))
|
||||
# ns_view.addSubview_(ns_textfield)
|
||||
# ns_textfield.setFrameOrigin_((0, 2))
|
||||
# ns_textfield.setAutoresizingMask_(ns_label_autoresizing_mask)
|
||||
ns_view = ns_textfield
|
||||
GLabel.__init__(self, _ns_view = ns_view, _ns_inner_view = ns_textfield, **kwds)
|
||||
|
||||
export(Label)
|
||||
@@ -0,0 +1,48 @@
|
||||
#--------------------------------------------------------------
|
||||
#
|
||||
# PyGUI - Pop-up list control - Cocoa
|
||||
#
|
||||
#--------------------------------------------------------------
|
||||
|
||||
from AppKit import NSPopUpButton
|
||||
from GUI import export
|
||||
from GUI.GListButtons import ListButton as GListButton
|
||||
from GUI.Utils import NSMultiClass, PyGUI_NS_EventHandler, \
|
||||
ns_set_action, ns_size_to_fit
|
||||
|
||||
class ListButton(GListButton):
|
||||
|
||||
_ns_handle_mouse = True
|
||||
|
||||
def __init__(self, **kwds):
|
||||
titles, values = self._extract_initial_items(kwds)
|
||||
self._titles = titles
|
||||
self._values = values
|
||||
frame = ((0, 0), (100, 20))
|
||||
ns = PyGUI_NSPopUpButton.alloc().initWithFrame_pullsDown_(frame, False)
|
||||
ns.pygui_component = self
|
||||
ns_set_action(ns, 'doAction:')
|
||||
self._ns_update_items(ns)
|
||||
ns_size_to_fit(ns)
|
||||
GListButton.__init__(self, _ns_view = ns, **kwds)
|
||||
|
||||
def _update_items(self):
|
||||
self._ns_update_items(self._ns_view)
|
||||
|
||||
def _ns_update_items(self, ns):
|
||||
ns.removeAllItems()
|
||||
ns.addItemsWithTitles_(self._titles)
|
||||
|
||||
def _get_selected_index(self):
|
||||
return self._ns_view.indexOfSelectedItem()
|
||||
|
||||
def _set_selected_index(self, i):
|
||||
self._ns_view.selectItemAtIndex_(i)
|
||||
|
||||
#--------------------------------------------------------------
|
||||
|
||||
class PyGUI_NSPopUpButton(NSPopUpButton, PyGUI_NS_EventHandler):
|
||||
__metaclass__ = NSMultiClass
|
||||
__slots__ = ['pygui_component']
|
||||
|
||||
export(ListButton)
|
||||
@@ -0,0 +1,67 @@
|
||||
#
|
||||
# Python GUI - Menus - PyObjC
|
||||
#
|
||||
|
||||
from AppKit import NSMenu, NSMenuItem, NSOnState, \
|
||||
NSCommandKeyMask, NSShiftKeyMask, NSAlternateKeyMask
|
||||
from GUI import export
|
||||
from GUI import Globals
|
||||
from GUI.GMenus import Menu as GMenu, MenuItem
|
||||
|
||||
#_ns_standard_actions = {
|
||||
# 'undo_cmd': 'undo:',
|
||||
# 'redo_cmd': 'redo:',
|
||||
# 'cut_cmd': 'cut:',
|
||||
# 'copy_cmd': 'copy:',
|
||||
# 'paste_cmd': 'paste:',
|
||||
# 'clear_cmd': 'clear:',
|
||||
# 'select_all_cmd': 'selectAll:',
|
||||
#}
|
||||
|
||||
class Menu(GMenu):
|
||||
|
||||
def __init__(self, title, items, **kwds):
|
||||
#print "Menu: creating with items", items ###
|
||||
GMenu.__init__(self, title, items, **kwds)
|
||||
ns_menu = NSMenu.alloc().initWithTitle_(title)
|
||||
ns_menu.setAutoenablesItems_(False)
|
||||
ns_menu.setDelegate_(Globals.ns_application)
|
||||
self._ns_menu = ns_menu
|
||||
|
||||
def _clear_platform_menu(self):
|
||||
ns_menu = self._ns_menu
|
||||
n = ns_menu.numberOfItems()
|
||||
while n:
|
||||
n -= 1
|
||||
ns_menu.removeItemAtIndex_(n)
|
||||
|
||||
def _add_separator_to_platform_menu(self):
|
||||
ns_item = NSMenuItem.separatorItem()
|
||||
self._ns_menu.addItem_(ns_item)
|
||||
|
||||
def _add_item_to_platform_menu(self, item, name, command = None, index = None):
|
||||
key = item._key or ""
|
||||
if item._shift:
|
||||
key = key.upper()
|
||||
else:
|
||||
key = key.lower()
|
||||
ns_item = NSMenuItem.alloc()
|
||||
#ns_action = _ns_standard_actions.get(command, 'menuSelection:')
|
||||
ns_action = 'menuSelection:'
|
||||
ns_item.initWithTitle_action_keyEquivalent_(name, ns_action, key)
|
||||
ns_item.setEnabled_(item.enabled)
|
||||
if item.checked:
|
||||
ns_item.setState_(NSOnState)
|
||||
ns_modifiers = NSCommandKeyMask
|
||||
if item._option:
|
||||
ns_modifiers |= NSAlternateKeyMask
|
||||
ns_item.setKeyEquivalentModifierMask_(ns_modifiers)
|
||||
ns_item.setRepresentedObject_(command)
|
||||
if index is not None:
|
||||
ns_tag = index
|
||||
else:
|
||||
ns_tag = -1
|
||||
ns_item.setTag_(ns_tag)
|
||||
self._ns_menu.addItem_(ns_item)
|
||||
|
||||
export(Menu)
|
||||
@@ -0,0 +1,50 @@
|
||||
#--------------------------------------------------------------
|
||||
#
|
||||
# PyGUI - NumPy interface - Cocoa
|
||||
#
|
||||
#--------------------------------------------------------------
|
||||
|
||||
from AppKit import NSBitmapImageRep, \
|
||||
NSAlphaNonpremultipliedBitmapFormat, NSCalibratedRGBColorSpace
|
||||
from GUI import Image
|
||||
|
||||
# HACK! PyObjC 2.3 incorrectly wraps the following method, so we change the
|
||||
# signature and pass the bitmap data in using ctypes.
|
||||
NSBitmapImageRep.__dict__['initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bitmapFormat_bytesPerRow_bitsPerPixel_'].signature = '@52@0:4^v8i12i16i20i24c28c32@36I40i44i48'
|
||||
import ctypes
|
||||
planes_t = ctypes.c_void_p * 5
|
||||
|
||||
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 not None:
|
||||
width, height = size
|
||||
data_size = array.size
|
||||
pixel_size = data_size // (width * height)
|
||||
if pixel_size <> len(format):
|
||||
raise ValueError("Array has wrong shape for specified size and format")
|
||||
else:
|
||||
height, width, pixel_size = array.shape
|
||||
if pixel_size <> len(format):
|
||||
raise ValueError("Array has wrong shape for specified format")
|
||||
bps = 8
|
||||
spp = pixel_size
|
||||
alpha = format.endswith("A")
|
||||
csp = NSCalibratedRGBColorSpace
|
||||
bpp = bps * spp
|
||||
bpr = width * pixel_size
|
||||
fmt = NSAlphaNonpremultipliedBitmapFormat
|
||||
ns_rep = NSBitmapImageRep.alloc()
|
||||
planes = planes_t(array.ctypes.data, 0, 0, 0, 0)
|
||||
ns_rep.initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bitmapFormat_bytesPerRow_bitsPerPixel_(
|
||||
ctypes.addressof(planes), width, height, bps, spp, alpha, False, csp, fmt, bpr, bpp)
|
||||
image = Image.__new__(Image)
|
||||
image._init_from_ns_rep(ns_rep)
|
||||
image._data = array
|
||||
return image
|
||||
@@ -0,0 +1,78 @@
|
||||
#--------------------------------------------------------------
|
||||
#
|
||||
# PyGUI - PIL interface - Cocoa
|
||||
#
|
||||
#--------------------------------------------------------------
|
||||
|
||||
import ctypes
|
||||
from AppKit import NSBitmapImageRep, \
|
||||
NSAlphaNonpremultipliedBitmapFormat, NSFloatingPointSamplesBitmapFormat, \
|
||||
NSDeviceCMYKColorSpace, NSCalibratedRGBColorSpace
|
||||
from GUI import Image
|
||||
|
||||
def hack_objc_sig():
|
||||
#print "GUI[Cocoa].PIL: Hacking objc method signature" ###
|
||||
# HACK! PyObjC 2.3 incorrectly wraps the following method, so we change the
|
||||
# signature and pass the bitmap data in using ctypes.
|
||||
NSBitmapImageRep.__dict__['initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bitmapFormat_bytesPerRow_bitsPerPixel_'].signature = '@52@0:4^v8i12i16i20i24c28c32@36I40i44i48'
|
||||
|
||||
planes_t = ctypes.c_char_p * 5
|
||||
|
||||
debug_pil = False
|
||||
|
||||
def image_from_pil_image(pil_image):
|
||||
"""Creates an Image from a Python Imaging Library (PIL)
|
||||
Image object."""
|
||||
mode = pil_image.mode
|
||||
w, h = pil_image.size
|
||||
data = pil_image.tostring()
|
||||
alpha = False
|
||||
cmyk = False
|
||||
floating = False
|
||||
if mode == "1":
|
||||
bps = 1; spp = 1
|
||||
elif mode == "L":
|
||||
bps = 8; spp = 1
|
||||
elif mode == "RGB":
|
||||
bps = 8; spp = 3
|
||||
elif mode == "RGBA":
|
||||
bps = 8; spp = 4; alpha = True
|
||||
elif mode == "CMYK":
|
||||
bps = 8; spp = 4; cmyk = True
|
||||
elif mode == "I":
|
||||
bps = 32; spp = 1
|
||||
elif mode == "F":
|
||||
bps = 32; spp = 1; floating = True
|
||||
else:
|
||||
raise ValueError("Unsupported PIL image mode '%s'" % mode)
|
||||
if cmyk:
|
||||
csp = NSDeviceCMYKColorSpace
|
||||
else:
|
||||
csp = NSCalibratedRGBColorSpace
|
||||
fmt = NSAlphaNonpremultipliedBitmapFormat
|
||||
if floating:
|
||||
fmt |= NSFloatingPointSamplesBitmapFormat
|
||||
bpp = bps * spp
|
||||
bpr = w * ((bpp + 7) // 8)
|
||||
if debug_pil:
|
||||
print "GUI.PIL:"
|
||||
print "image size =", (w, h)
|
||||
print "data size =", len(data)
|
||||
print "bits per sample =", bps
|
||||
print "samples per pixel =", spp
|
||||
print "bits per pixel =", bpp
|
||||
print "bytes per row =", bpr
|
||||
hack_objc_sig()
|
||||
ns_rep = NSBitmapImageRep.alloc()
|
||||
planes = planes_t(data, "", "", "", "")
|
||||
ns_rep.initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bitmapFormat_bytesPerRow_bitsPerPixel_(
|
||||
ctypes.addressof(planes), w, h, bps, spp, alpha, False, csp, fmt, bpr, bpp)
|
||||
# planes = (data, "", "", "", "")
|
||||
# ns_rep.initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(
|
||||
# planes, w, h, bps, spp, alpha, False, csp, bpr, bpp)
|
||||
image = Image.__new__(Image)
|
||||
image._init_from_ns_rep(ns_rep)
|
||||
image._data = data
|
||||
return image
|
||||
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
#
|
||||
# Python GUI - Pixmaps - Cocoa
|
||||
#
|
||||
|
||||
from Foundation import NSSize
|
||||
from AppKit import NSImage, NSCachedImageRep, NSBitmapImageRep, \
|
||||
NSCalibratedRGBColorSpace, NSImageCacheNever, NSGraphicsContext, \
|
||||
NSAffineTransform
|
||||
from GUI import export
|
||||
from GUI import Canvas
|
||||
from GUI.GPixmaps import Pixmap as GPixmap
|
||||
|
||||
class Pixmap(GPixmap):
|
||||
# _ns_bitmap_image_rep NSBitmapImageRep
|
||||
|
||||
def __init__(self, width, height):
|
||||
GPixmap.__init__(self)
|
||||
#ns_size = NSSize(width, height)
|
||||
#ns_image = NSImage.alloc().initWithSize_(ns_size)
|
||||
ns_image = NSImage.alloc().init()
|
||||
ns_image.setCacheMode_(NSImageCacheNever)
|
||||
row_bytes = 4 * width
|
||||
ns_bitmap = NSBitmapImageRep.alloc().\
|
||||
initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(
|
||||
None, width, height, 8, 4, True, False, NSCalibratedRGBColorSpace, row_bytes, 32)
|
||||
ns_image.addRepresentation_(ns_bitmap)
|
||||
ns_bitmap_context = NSGraphicsContext.graphicsContextWithBitmapImageRep_(ns_bitmap)
|
||||
ns_graphics_context = FlippedNSGraphicsContext.alloc().initWithBase_(ns_bitmap_context)
|
||||
ns_tr = NSAffineTransform.transform()
|
||||
ns_tr.translateXBy_yBy_(0.0, height)
|
||||
ns_tr.scaleXBy_yBy_(1.0, -1.0)
|
||||
# Using __class__ to get +saveGraphicsState instead of -saveGraphicsState
|
||||
NSGraphicsContext.__class__.saveGraphicsState()
|
||||
try:
|
||||
NSGraphicsContext.setCurrentContext_(ns_graphics_context)
|
||||
ns_tr.concat()
|
||||
finally:
|
||||
NSGraphicsContext.__class__.restoreGraphicsState()
|
||||
self._init_with_ns_image(ns_image, flipped = True) #False)
|
||||
self._ns_bitmap_image_rep = ns_bitmap
|
||||
self._ns_graphics_context = ns_graphics_context
|
||||
|
||||
def with_canvas(self, proc):
|
||||
NSGraphicsContext.__class__.saveGraphicsState()
|
||||
NSGraphicsContext.setCurrentContext_(self._ns_graphics_context)
|
||||
try:
|
||||
canvas = Canvas()
|
||||
proc(canvas)
|
||||
finally:
|
||||
NSGraphicsContext.__class__.restoreGraphicsState()
|
||||
|
||||
class FlippedNSGraphicsContext(NSGraphicsContext):
|
||||
|
||||
def initWithBase_(self, base):
|
||||
self.base = base
|
||||
self.graphics_port = base.graphicsPort()
|
||||
return self
|
||||
|
||||
def isFlipped(self):
|
||||
return True
|
||||
|
||||
def graphicsPort(self):
|
||||
return self.graphics_port
|
||||
|
||||
def isDrawingToScreen(self):
|
||||
return self.base.isDrawingToScreen()
|
||||
|
||||
def setCompositingOperation_(self, x):
|
||||
self.base.setCompositingOperation_(x)
|
||||
|
||||
def focusStack(self):
|
||||
return self.base.focusStack()
|
||||
|
||||
def saveGraphicsState(self):
|
||||
return self.base.saveGraphicsState()
|
||||
|
||||
def restoreGraphicsState(self):
|
||||
return self.base.restoreGraphicsState()
|
||||
|
||||
export(Pixmap)
|
||||
@@ -0,0 +1,132 @@
|
||||
#------------------------------------------------------------------------------
|
||||
#
|
||||
# PyGUI - Printing - Cocoa
|
||||
#
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
from AppKit import NSPrintInfo, NSPageLayout, NSPrintOperation, \
|
||||
NSKeyedArchiver, NSKeyedUnarchiver, NSData, NSAutoPagination, \
|
||||
NSPortraitOrientation, NSLandscapeOrientation, NSOKButton
|
||||
from GUI.GPrinting import PageSetup as GPageSetup, Printable as GPrintable
|
||||
|
||||
ns_to_generic_orientation = {
|
||||
NSPortraitOrientation: 'portrait',
|
||||
NSLandscapeOrientation: 'landscape',
|
||||
}
|
||||
|
||||
generic_to_ns_orientation = {
|
||||
'portrait': NSPortraitOrientation,
|
||||
'landscape': NSLandscapeOrientation,
|
||||
}
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class PageSetup(GPageSetup):
|
||||
|
||||
def __init__(self):
|
||||
ns_pi = NSPrintInfo.sharedPrintInfo().copy()
|
||||
ns_pi.setLeftMargin_(36)
|
||||
ns_pi.setTopMargin_(36)
|
||||
ns_pi.setRightMargin_(36)
|
||||
ns_pi.setBottomMargin_(36)
|
||||
ns_pi.setHorizontalPagination_(NSAutoPagination)
|
||||
self._ns_print_info = ns_pi
|
||||
|
||||
def __getstate__(self):
|
||||
state = GPageSetup.__getstate__(self)
|
||||
data = NSKeyedArchiver.archivedDataWithRootObject_(self._ns_print_info)
|
||||
state['_ns_print_info'] = data.bytes()
|
||||
return state
|
||||
|
||||
def __setstate__(self, state):
|
||||
bytes = state.pop('_ns_print_info', None)
|
||||
if bytes:
|
||||
data = NSData.dataWithBytes_length_(bytes, len(bytes))
|
||||
self._ns_print_info = NSKeyedArchiver.unarchiveObjectWithData_(data)
|
||||
else:
|
||||
GPageSetup.__setstate__(self, state)
|
||||
|
||||
def copy(self, other):
|
||||
result = PageSetup.__new__()
|
||||
result._ns_print_info = other._ns_print_info.copy()
|
||||
|
||||
def get_paper_name(self):
|
||||
return self._ns_print_info.paperName()
|
||||
|
||||
def set_paper_name(self, x):
|
||||
self._ns_print_info.setPaperName_(x)
|
||||
|
||||
def get_paper_size(self):
|
||||
return tuple(self._ns_print_info.paperSize())
|
||||
|
||||
def set_paper_size(self, x):
|
||||
self._ns_print_info.setPaperSize_(x)
|
||||
|
||||
def get_paper_width(self):
|
||||
return self.paper_size[0]
|
||||
|
||||
def set_paper_width(self, x):
|
||||
self.paper_size = x, self.paper_height
|
||||
|
||||
def get_paper_height(self):
|
||||
return self.paper_size[1]
|
||||
|
||||
def set_paper_height(self, x):
|
||||
self.paper_size = self.paper_width, x
|
||||
|
||||
def get_left_margin(self):
|
||||
return self._ns_print_info.leftMargin()
|
||||
|
||||
def set_get_left_margin(self, x):
|
||||
self._ns_print_info.setLefMargin_(x)
|
||||
|
||||
def get_right_margin(self):
|
||||
return self._ns_print_info.rightMargin()
|
||||
|
||||
def set_get_right_margin(self, x):
|
||||
self._ns_print_info.setRightMargin_(x)
|
||||
|
||||
def get_top_margin(self):
|
||||
return self._ns_print_info.topMargin()
|
||||
|
||||
def set_get_top_margin(self, x):
|
||||
self._ns_print_info.setTopMargin_(x)
|
||||
|
||||
def get_bottom_margin(self):
|
||||
return self._ns_print_info.bottomMargin()
|
||||
|
||||
def set_get_bottom_margin(self, x):
|
||||
self._ns_print_info.setBottomMargin_(x)
|
||||
|
||||
def get_orientation(self):
|
||||
return ns_to_generic_orientation[self._ns_print_info.orientation()]
|
||||
|
||||
def set_orientation(self, x):
|
||||
nso = generic_to_ns_orientation.get(x, 'portrait')
|
||||
self._ns_print_info.setOrientation_(nso)
|
||||
|
||||
def get_printable_rect(self):
|
||||
l, b, w, h = self._ns_print_info.imageablePageBounds()
|
||||
return (l, b - h, l + w, b)
|
||||
|
||||
def get_printer_name(self):
|
||||
return self._ns_print_info.printer().name()
|
||||
|
||||
def set_printer_name(self, x):
|
||||
self._ns_print_info.setPrinter_(NSPrinter.printerWithName_(x))
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class Printable(GPrintable):
|
||||
|
||||
def print_view(self, page_setup, prompt = True):
|
||||
ns_op = NSPrintOperation.printOperationWithView_printInfo_(
|
||||
self._ns_inner_view, page_setup._ns_print_info)
|
||||
ns_op.setShowsPrintPanel_(prompt)
|
||||
ns_op.runOperation()
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
def present_page_setup_dialog(page_setup):
|
||||
result = NSPageLayout.pageLayout().runModalWithPrintInfo_(page_setup._ns_print_info)
|
||||
return result == NSOKButton
|
||||
@@ -0,0 +1,36 @@
|
||||
#
|
||||
# Python GUI - Radio buttons - PyObjC
|
||||
#
|
||||
|
||||
import AppKit
|
||||
from AppKit import NSOnState, NSOffState
|
||||
from GUI import export
|
||||
from GUI.StdFonts import system_font
|
||||
from GUI.ButtonBasedControls import ButtonBasedControl
|
||||
from GUI.GRadioButtons import RadioButton as GRadioButton
|
||||
|
||||
class RadioButton(ButtonBasedControl, GRadioButton):
|
||||
|
||||
def __init__(self, title = "New Radio Button", font = system_font, **kwds):
|
||||
ns_button = self._create_ns_button(title = title, font = font,
|
||||
ns_button_type = AppKit.NSRadioButton,
|
||||
ns_bezel_style = AppKit.NSRoundedBezelStyle)
|
||||
GRadioButton.__init__(self, _ns_view = ns_button, **kwds)
|
||||
|
||||
def do_action(self):
|
||||
if self._group:
|
||||
self._group.value = self._value
|
||||
else:
|
||||
self._ns_view.setState_(NSOffState)
|
||||
|
||||
def _value_changed(self):
|
||||
self._update()
|
||||
|
||||
def _update(self):
|
||||
if self._group and self._value == self._group._value:
|
||||
state = NSOnState
|
||||
else:
|
||||
state = NSOffState
|
||||
self._ns_view.setState_(state)
|
||||
|
||||
export(RadioButton)
|
||||
@@ -0,0 +1,23 @@
|
||||
#
|
||||
# Python GUI - Radio groups - PyObjC
|
||||
#
|
||||
|
||||
from GUI import export
|
||||
from GUI.GRadioGroups import RadioGroup as GRadioGroup
|
||||
|
||||
class RadioGroup(GRadioGroup):
|
||||
|
||||
def __init__(self, items = [], **kwds):
|
||||
GRadioGroup.__init__(self, items, **kwds)
|
||||
|
||||
def _item_added(self, item):
|
||||
item._update()
|
||||
|
||||
def _item_removed(self, item):
|
||||
pass
|
||||
|
||||
def _value_changed(self):
|
||||
for item in self._items:
|
||||
item._update()
|
||||
|
||||
export(RadioGroup)
|
||||
@@ -0,0 +1,96 @@
|
||||
#
|
||||
# Python GUI - Scrollable Views - PyObjC
|
||||
#
|
||||
|
||||
from Foundation import NSPoint, NSMakeRect
|
||||
from AppKit import NSScrollView
|
||||
from GUI import export
|
||||
from GUI.GScrollableViews import ScrollableView as GScrollableView, \
|
||||
default_extent, default_line_scroll_amount, default_scrolling
|
||||
from GUI.Geometry import ns_rect_to_rect
|
||||
|
||||
class ScrollableView(GScrollableView):
|
||||
|
||||
_ns_scrollable = True
|
||||
|
||||
def __init__(self, extent = default_extent,
|
||||
line_scroll_amount = default_line_scroll_amount,
|
||||
scrolling = default_scrolling,
|
||||
**kwds):
|
||||
GScrollableView.__init__(self,
|
||||
extent = extent, line_scroll_amount = line_scroll_amount,
|
||||
scrolling = scrolling, **kwds)
|
||||
|
||||
def get_hscrolling(self):
|
||||
return self._ns_view.hasHorizontalScroller()
|
||||
|
||||
def set_hscrolling(self, value):
|
||||
self._ns_view.setHasHorizontalScroller_(value)
|
||||
|
||||
def get_vscrolling(self):
|
||||
return self._ns_view.hasVerticalScroller()
|
||||
|
||||
def set_vscrolling(self, value):
|
||||
self._ns_view.setHasVerticalScroller_(value)
|
||||
|
||||
# def get_extent(self):
|
||||
# (l, t), (w, h) = self._ns_inner_view.bounds()
|
||||
# return (l, t, l + w, t + h)
|
||||
|
||||
def get_extent(self):
|
||||
return self._ns_inner_view.bounds().size
|
||||
|
||||
# def set_extent(self, (l, t, r, b)):
|
||||
# w = r - l
|
||||
# h = b - t
|
||||
# ns_docview = self._ns_inner_view
|
||||
# ns_docview.setFrame_(NSMakeRect(0, 0, w, h))
|
||||
# ns_docview.setBounds_(NSMakeRect(l, t, w, h))
|
||||
# self.invalidate()
|
||||
|
||||
def set_extent(self, (w, h)):
|
||||
r = NSMakeRect(0, 0, w, h)
|
||||
ns_docview = self._ns_inner_view
|
||||
ns_docview.setFrame_(r)
|
||||
ns_docview.setBounds_(r)
|
||||
self.invalidate()
|
||||
|
||||
def get_content_size(self):
|
||||
return self._ns_view.contentSize()
|
||||
|
||||
def set_content_size(self, size):
|
||||
ns = self._ns_view
|
||||
self.size = NSScrollView.\
|
||||
frameSizeForContentSize_hasHorizontalScroller_hasVerticalScroller_borderType_(
|
||||
size, ns.hasHorizontalScroller(), ns.hasVerticalScroller(), ns.borderType())
|
||||
|
||||
def get_scroll_offset(self):
|
||||
ns_clip_view = self._ns_view.contentView()
|
||||
x, y = ns_clip_view.bounds().origin
|
||||
return x, y
|
||||
|
||||
def set_scroll_offset(self, (x, y)):
|
||||
ns_view = self._ns_view
|
||||
ns_clip_view = ns_view.contentView()
|
||||
new_pt = ns_clip_view.constrainScrollPoint_(NSPoint(x, y))
|
||||
ns_clip_view.scrollToPoint_(new_pt)
|
||||
ns_view.reflectScrolledClipView_(ns_clip_view)
|
||||
|
||||
def get_line_scroll_amount(self):
|
||||
ns_view = self._ns_view
|
||||
x = ns_view.horizontalLineScroll()
|
||||
y = ns_view.verticalLineScroll()
|
||||
return x, y
|
||||
|
||||
def set_line_scroll_amount(self, (x, y)):
|
||||
ns_view = self._ns_view
|
||||
ns_view.setHorizontalLineScroll_(x)
|
||||
ns_view.setVerticalLineScroll_(y)
|
||||
ns_view.setHorizontalPageScroll_(x)
|
||||
ns_view.setVerticalPageScroll_(y)
|
||||
|
||||
def viewed_rect(self):
|
||||
ns_rect = self._ns_view.contentView().documentVisibleRect()
|
||||
return ns_rect_to_rect(ns_rect)
|
||||
|
||||
export(ScrollableView)
|
||||
@@ -0,0 +1,85 @@
|
||||
#------------------------------------------------------------------------------
|
||||
#
|
||||
# Python GUI - Slider - Cocoa
|
||||
#
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
from AppKit import NSSlider
|
||||
from GUI import export
|
||||
from GUI.StdFonts import system_font
|
||||
from GUI.Utils import NSMultiClass, PyGUI_NS_EventHandler, \
|
||||
ns_set_action, ns_size_to_fit
|
||||
from GUI.GSliders import Slider as GSlider
|
||||
|
||||
class Slider(GSlider):
|
||||
|
||||
_ns_handle_mouse = True
|
||||
|
||||
def __init__(self, orient = 'h', ticks = 0, **kwds):
|
||||
length = 100
|
||||
if ticks:
|
||||
breadth = 30
|
||||
else:
|
||||
breadth = 22 # Same as default height of a text-containing control
|
||||
if orient == 'h':
|
||||
ns_frame = ((0, 0), (length, breadth))
|
||||
elif orient == 'v':
|
||||
ns_frame = ((0, 0), (breadth, length))
|
||||
else:
|
||||
raise ValueError("Invalid orientation, should be 'h' or 'v'")
|
||||
ns_slider = PyGUI_NSSlider.alloc().initWithFrame_(ns_frame)
|
||||
ns_slider.pygui_component = self
|
||||
ns_set_action(ns_slider, 'doAction:')
|
||||
GSlider.__init__(self, _ns_view = ns_slider, **kwds)
|
||||
self.set_ticks(ticks)
|
||||
self._last_value = None
|
||||
|
||||
def get_min_value(self):
|
||||
return self._ns_view.minValue()
|
||||
|
||||
def set_min_value(self, x):
|
||||
self._ns_view.setMinValue_(x)
|
||||
|
||||
def get_max_value(self):
|
||||
return self._ns_view.maxValue()
|
||||
|
||||
def set_max_value(self, x):
|
||||
self._ns_view.setMaxValue_(x)
|
||||
|
||||
def get_value(self):
|
||||
return self._ns_view.doubleValue()
|
||||
|
||||
def set_value(self, x):
|
||||
self._ns_view.setDoubleValue_(x)
|
||||
|
||||
def get_ticks(self):
|
||||
return self._ns_view.numberOfTickMarks()
|
||||
|
||||
def set_ticks(self, x):
|
||||
self._ns_view.setNumberOfTickMarks_(x)
|
||||
|
||||
def get_discrete(self):
|
||||
return self._ns_view.allowsTickMarkValuesOnly()
|
||||
|
||||
def set_discrete(self, x):
|
||||
self._ns_view.setAllowsTickMarkValuesOnly_(x)
|
||||
|
||||
def get_live(self):
|
||||
return self._ns_view.isContinuous()
|
||||
|
||||
def set_live(self, x):
|
||||
self._ns_view.setContinuous_(x)
|
||||
|
||||
def do_action(self):
|
||||
value = self._ns_view.doubleValue()
|
||||
if value <> self._last_value:
|
||||
self._last_value = value
|
||||
GSlider.do_action(self)
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class PyGUI_NSSlider(NSSlider, PyGUI_NS_EventHandler):
|
||||
__metaclass__ = NSMultiClass
|
||||
__slots__ = ['pygui_component']
|
||||
|
||||
export(Slider)
|
||||
@@ -0,0 +1,56 @@
|
||||
#
|
||||
# Python GUI - Standard Cursors - Cocoa
|
||||
#
|
||||
|
||||
from AppKit import NSCursor
|
||||
from GUI import Cursor
|
||||
|
||||
__all__ = [
|
||||
'arrow',
|
||||
'ibeam',
|
||||
'crosshair',
|
||||
'fist',
|
||||
'hand',
|
||||
'finger',
|
||||
'invisible',
|
||||
]
|
||||
|
||||
_empty_cursor = None
|
||||
|
||||
def _make_empty_cursor():
|
||||
global _empty_cursor
|
||||
if not _empty_cursor:
|
||||
from AppKit import NSCursor, NSImage, NSBitmapImageRep, NSDeviceRGBColorSpace
|
||||
from GUI import Cursor
|
||||
import sys
|
||||
if sys.version_info >= (3, 0):
|
||||
b = bytes([0])
|
||||
else:
|
||||
b = "\x00"
|
||||
d = b * 1024
|
||||
ns_bitmap = NSBitmapImageRep.alloc().\
|
||||
initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_\
|
||||
((d, d, d, d, d), 16, 16, 8, 4, True, False, NSDeviceRGBColorSpace, 64, 32)
|
||||
ns_image = NSImage.alloc().initWithSize_((16, 16))
|
||||
ns_image.addRepresentation_(ns_bitmap)
|
||||
ns_cursor = NSCursor.alloc().initWithImage_hotSpot_(ns_image, (0, 0))
|
||||
_empty_cursor = Cursor._from_ns_cursor(ns_cursor)
|
||||
_empty_cursor._data = d
|
||||
return _empty_cursor
|
||||
|
||||
arrow = Cursor._from_ns_cursor(NSCursor.arrowCursor())
|
||||
ibeam = Cursor._from_ns_cursor(NSCursor.IBeamCursor())
|
||||
crosshair = Cursor._from_ns_cursor(NSCursor.crosshairCursor())
|
||||
fist = Cursor._from_ns_cursor(NSCursor.closedHandCursor())
|
||||
hand = Cursor._from_ns_cursor(NSCursor.openHandCursor())
|
||||
finger = Cursor._from_ns_cursor(NSCursor.pointingHandCursor())
|
||||
invisible = _make_empty_cursor()
|
||||
|
||||
mac_poof = Cursor._from_ns_cursor(NSCursor.disappearingItemCursor())
|
||||
|
||||
del NSCursor
|
||||
del Cursor
|
||||
del _make_empty_cursor
|
||||
|
||||
def empty_cursor():
|
||||
return invisible
|
||||
@@ -0,0 +1,9 @@
|
||||
#
|
||||
# Python GUI - Standard Fonts - PyObjC
|
||||
#
|
||||
|
||||
from AppKit import NSFont
|
||||
from GUI import Font
|
||||
|
||||
system_font = Font._from_ns_font(NSFont.systemFontOfSize_(0))
|
||||
application_font = Font._from_ns_font(NSFont.userFontOfSize_(0))
|
||||
@@ -0,0 +1,62 @@
|
||||
#
|
||||
# Python GUI - Standard Menus - PyObjC
|
||||
#
|
||||
|
||||
from GUI.GStdMenus import build_menus, \
|
||||
fundamental_cmds, help_cmds, pref_cmds, file_cmds, print_cmds, edit_cmds
|
||||
|
||||
fundamental_cmds += ['hide_app_cmd', 'hide_other_apps_cmd', 'show_all_apps_cmd']
|
||||
|
||||
_appl_menu_items = [
|
||||
("About <app>", 'about_cmd'),
|
||||
"-",
|
||||
("Preferences...", 'preferences_cmd'),
|
||||
"-",
|
||||
("Hide <app>/H", 'hide_app_cmd'),
|
||||
("Hide Others", 'hide_other_apps_cmd'),
|
||||
("Show All", 'show_all_apps_cmd'),
|
||||
"-",
|
||||
("Quit <app>/Q", 'quit_cmd'),
|
||||
]
|
||||
|
||||
_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'),
|
||||
]
|
||||
|
||||
_edit_menu_items = [
|
||||
("Undo/Z", 'undo_cmd'),
|
||||
("Redo/^Z", 'redo_cmd'),
|
||||
"-",
|
||||
("Cut/X", 'cut_cmd'),
|
||||
("Copy/C", 'copy_cmd'),
|
||||
("Paste/V", 'paste_cmd'),
|
||||
("Delete", 'clear_cmd'),
|
||||
"-",
|
||||
("Select All/A", 'select_all_cmd'),
|
||||
]
|
||||
|
||||
_help_menu_items = [
|
||||
("Help", 'help_cmd'),
|
||||
]
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
def basic_menus(substitutions = {}, include = None, exclude = None):
|
||||
return build_menus([
|
||||
("@", _appl_menu_items, False),
|
||||
("File", _file_menu_items, False),
|
||||
("Edit", _edit_menu_items, False),
|
||||
("Help", _help_menu_items, True),
|
||||
],
|
||||
substitutions = substitutions,
|
||||
include = include,
|
||||
exclude = exclude)
|
||||
@@ -0,0 +1,89 @@
|
||||
#
|
||||
# PyGUI - Tasks - Cocoa
|
||||
#
|
||||
|
||||
import sys
|
||||
from weakref import WeakValueDictionary
|
||||
from Foundation import NSTimer, NSRunLoop, NSDefaultRunLoopMode
|
||||
from AppKit import NSEventTrackingRunLoopMode, NSModalPanelRunLoopMode
|
||||
from GUI import export
|
||||
from GUI import Globals
|
||||
from GUI.GTasks import Task as GTask
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
#
|
||||
# Doing things this convoluted way to work around a memory
|
||||
# leak in PyObjC. Need to avoid having the NSTimer trigger
|
||||
# creation of a bound method each time it fires or the bound
|
||||
# methods leak. Also can't use the userInfo of the NSTimer as
|
||||
# it seems to leak too.
|
||||
|
||||
ns_timer_to_task = WeakValueDictionary()
|
||||
|
||||
class TaskTrigger(object):
|
||||
pass
|
||||
|
||||
def fire_(ns_timer):
|
||||
ns_timer_to_task[ns_timer]._ns_fire()
|
||||
|
||||
trigger = TaskTrigger()
|
||||
trigger.fire_ = fire_
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
|
||||
class Task(GTask):
|
||||
|
||||
def __init__(self, proc, interval, repeat = 0, start = 1):
|
||||
self._proc = proc
|
||||
self._interval = interval
|
||||
self._repeat = repeat
|
||||
self._ns_timer = None
|
||||
if start:
|
||||
self.start()
|
||||
|
||||
def destroy(self):
|
||||
#print "Task.destroy:", self ###
|
||||
self.stop()
|
||||
|
||||
def get_scheduled(self):
|
||||
return self._ns_timer is not None
|
||||
|
||||
def get_interval(self):
|
||||
return self._interval
|
||||
|
||||
def get_repeat(self):
|
||||
return self._repeat
|
||||
|
||||
def start(self):
|
||||
self.stop()
|
||||
#ns_timer = \
|
||||
# NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(
|
||||
# self._interval, self._target, '_ns_fire', None, self._repeat)
|
||||
ns_timer = \
|
||||
NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(
|
||||
self._interval, trigger, 'fire:', None, self._repeat)
|
||||
self._ns_timer = ns_timer
|
||||
ns_timer_to_task[ns_timer] = self
|
||||
ns_run_loop = NSRunLoop.currentRunLoop()
|
||||
ns_run_loop.addTimer_forMode_(
|
||||
ns_timer, NSDefaultRunLoopMode)
|
||||
ns_run_loop.addTimer_forMode_(
|
||||
ns_timer, NSEventTrackingRunLoopMode)
|
||||
ns_run_loop.addTimer_forMode_(
|
||||
ns_timer, NSModalPanelRunLoopMode)
|
||||
|
||||
def stop(self):
|
||||
ns_timer = self._ns_timer
|
||||
if ns_timer:
|
||||
ns_timer.invalidate()
|
||||
del ns_timer_to_task[ns_timer]
|
||||
self._ns_timer = None
|
||||
|
||||
def _ns_fire(self):
|
||||
try:
|
||||
self._proc()
|
||||
except:
|
||||
Globals.pending_exception = sys.exc_info()
|
||||
self.stop()
|
||||
|
||||
export(Task)
|
||||
@@ -0,0 +1,104 @@
|
||||
#------------------------------------------------------------------------------
|
||||
#
|
||||
# Python GUI - Text Editor - Cocoa
|
||||
#
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
from AppKit import NSTextView, NSScrollView, NSViewWidthSizable, \
|
||||
NSMutableParagraphStyle
|
||||
from GUI import export
|
||||
from GUI import StdFonts
|
||||
from GUI.Utils import NSMultiClass, PyGUI_NS_EventHandler
|
||||
from GUI.GTextEditors import TextEditor as GTextEditor
|
||||
|
||||
NUM_TAB_STOPS = 32
|
||||
|
||||
class TextEditor(GTextEditor):
|
||||
|
||||
_ns_handle_mouse = True
|
||||
|
||||
def __init__(self, scrolling = 'hv', **kwds):
|
||||
width = 100
|
||||
height = 100
|
||||
frame = ((0, 0), (width, height))
|
||||
ns_outer = NSScrollView.alloc().initWithFrame_(frame)
|
||||
ns_outer.setHasHorizontalScroller_('h' in scrolling)
|
||||
ns_outer.setHasVerticalScroller_('v' in scrolling)
|
||||
if 'h' in scrolling:
|
||||
cwidth = 2000
|
||||
else:
|
||||
cwidth = ns_outer.contentSize()[0]
|
||||
frame = ((0, 0), (cwidth, height))
|
||||
ns_inner = PyGUI_NSTextView.alloc().initWithFrame_(frame)
|
||||
ns_inner.pygui_component = self
|
||||
ps = NSMutableParagraphStyle.alloc().init()
|
||||
ps.setDefaultTabInterval_(ps.tabStops()[0].location())
|
||||
ps.setTabStops_([])
|
||||
ns_inner.setDefaultParagraphStyle_(ps)
|
||||
ns_inner.setAllowsUndo_(True)
|
||||
ns_outer.setDocumentView_(ns_inner)
|
||||
if 'h' not in scrolling:
|
||||
ns_inner.setAutoresizingMask_(NSViewWidthSizable)
|
||||
if 'font' not in kwds:
|
||||
kwds['font'] = StdFonts.application_font
|
||||
GTextEditor.__init__(self, ns_outer,
|
||||
_ns_inner_view = ns_inner, **kwds)
|
||||
|
||||
def get_text(self):
|
||||
return self._ns_inner_view.string()
|
||||
|
||||
def set_text(self, value):
|
||||
self._ns_inner_view.setString_(value)
|
||||
self._ns_apply_style()
|
||||
|
||||
def get_text_length(self):
|
||||
return self._ns_inner_view.textStorage().length()
|
||||
|
||||
def get_selection(self):
|
||||
start, length = self._ns_inner_view.selectedRanges()[0].rangeValue()
|
||||
return (start, start + length)
|
||||
|
||||
def set_selection(self, value):
|
||||
start, stop = value
|
||||
self._ns_inner_view.setSelectedRange_((start, stop - start))
|
||||
|
||||
def get_font(self):
|
||||
return self._font
|
||||
|
||||
def set_font(self, font):
|
||||
self._font = font
|
||||
self._ns_inner_view.setFont_(font._ns_font)
|
||||
|
||||
def get_tab_spacing(self):
|
||||
#ns_storage = self._ns_inner_view.textStorage()
|
||||
#ps, _ = ns_storage.attribute_atIndex_effectiveRange_("NSParagraphStyle", 0)
|
||||
ps = self._ns_inner_view.defaultParagraphStyle()
|
||||
return ps.defaultTabInterval()
|
||||
|
||||
def set_tab_spacing(self, x):
|
||||
ps = NSMutableParagraphStyle.alloc().init()
|
||||
ps.setTabStops_([])
|
||||
ps.setDefaultTabInterval_(x)
|
||||
self._ns_inner_view.setDefaultParagraphStyle_(ps)
|
||||
self._ns_apply_style()
|
||||
|
||||
def paste_cmd(self):
|
||||
GTextEditor.paste_cmd(self)
|
||||
self._ns_apply_style()
|
||||
|
||||
def _ns_apply_style(self):
|
||||
ns_textview = self._ns_inner_view
|
||||
ps = ns_textview.defaultParagraphStyle()
|
||||
font = ns_textview.font()
|
||||
ns_storage = self._ns_inner_view.textStorage()
|
||||
ns_storage.setAttributes_range_(
|
||||
{"NSParagraphStyle": ps, "NSFont": font},
|
||||
(0, self.text_length))
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class PyGUI_NSTextView(NSTextView, PyGUI_NS_EventHandler):
|
||||
__metaclass__ = NSMultiClass
|
||||
__slots__ = ['pygui_component']
|
||||
|
||||
export(TextEditor)
|
||||
@@ -0,0 +1,49 @@
|
||||
#
|
||||
# Python GUI - Text Fields - PyObjC
|
||||
#
|
||||
|
||||
from Foundation import NSRange
|
||||
from GUI import export
|
||||
from GUI.StdFonts import system_font #application_font
|
||||
from GUI import EditCmdHandler
|
||||
from GUI.TextFieldBasedControls import TextFieldBasedControl
|
||||
from GUI.GTextFields import TextField as GTextField
|
||||
|
||||
class TextField(TextFieldBasedControl, GTextField):
|
||||
|
||||
#_vertical_padding = 5
|
||||
_intercept_tab_key = False
|
||||
|
||||
def __init__(self, text = "", font = system_font,
|
||||
multiline = False, password = False, border = True, **kwds):
|
||||
ns_textfield = self._create_ns_textfield(editable = True,
|
||||
multiline = multiline, password = password,
|
||||
text = text, font = font, border = border)
|
||||
GTextField.__init__(self, _ns_view = ns_textfield,
|
||||
multiline = multiline, **kwds)
|
||||
|
||||
def get_selection(self):
|
||||
ns_editor = self._ns_editor()
|
||||
if ns_editor:
|
||||
start, length = ns_editor.selectedRange()
|
||||
return (start, start + length)
|
||||
else:
|
||||
return (0, 0)
|
||||
|
||||
def set_selection(self, (start, end)):
|
||||
self.become_target()
|
||||
ns_editor = self._ns_editor()
|
||||
if ns_editor:
|
||||
ns_editor.setSelectedRange_(NSRange(start, end - start))
|
||||
|
||||
def select_all(self):
|
||||
self.become_target()
|
||||
self._ns_view.selectText_(None)
|
||||
|
||||
def _ns_editor(self):
|
||||
return self._ns_view.currentEditor()
|
||||
|
||||
def _ns_edit_cmd_target(self):
|
||||
return self._ns_editor()
|
||||
|
||||
export(TextField)
|
||||
@@ -0,0 +1,90 @@
|
||||
#
|
||||
# Python GUI - PyObjC
|
||||
#
|
||||
# Base class for controls based on an NSTextField
|
||||
#
|
||||
|
||||
from Foundation import NSRect, NSPoint, NSSize
|
||||
from AppKit import NSTextField, NSSecureTextField, NSTextFieldCell
|
||||
from GUI.Utils import NSMultiClass
|
||||
from GUI import Color
|
||||
from GUI.Utils import ns_size_to_fit, PyGUI_NS_EventHandler
|
||||
from GUI.StdFonts import system_font
|
||||
|
||||
class TextFieldBasedControl(object):
|
||||
|
||||
_ns_handle_mouse = True
|
||||
|
||||
def _create_ns_textfield(self, editable, text, font,
|
||||
multiline = False, password = False, border = False,
|
||||
padding = (0, 0)):
|
||||
self._ns_is_password = password
|
||||
if password:
|
||||
ns_class = PyGUI_NSSecureTextField
|
||||
else:
|
||||
ns_class = PyGUI_NSTextField
|
||||
ns_frame = NSRect(NSPoint(0, 0), NSSize(20, 10))
|
||||
ns_textfield = ns_class.alloc().initWithFrame_(ns_frame)
|
||||
ns_textfield.pygui_component = self
|
||||
if multiline and not password:
|
||||
ns_textfield.pygui_multiline = True
|
||||
# Be careful here -- calling setBordered_ seems to affect isBezeled as well
|
||||
if editable:
|
||||
ns_textfield.setBezeled_(border)
|
||||
else:
|
||||
ns_textfield.setBordered_(border)
|
||||
if not editable:
|
||||
ns_textfield.setDrawsBackground_(False)
|
||||
ns_textfield.setEditable_(editable)
|
||||
ns_textfield.setSelectable_(editable)
|
||||
ns_textfield.setFont_(font._ns_font)
|
||||
ns_textfield.setStringValue_(text)
|
||||
ns_size_to_fit(ns_textfield, padding = padding)
|
||||
return ns_textfield
|
||||
|
||||
def get_border(self):
|
||||
ns_textfield = self._ns_inner_view
|
||||
if ns_textfield.isEditable():
|
||||
return ns_textfield.isBezeled()
|
||||
else:
|
||||
return ns_textfield.isBordered()
|
||||
|
||||
def set_border(self, border):
|
||||
ns_textfield = self._ns_inner_view
|
||||
if ns_textfield.isEditable():
|
||||
ns_textfield.setBezeled_(border)
|
||||
else:
|
||||
ns_textfield.setBordered_(border)
|
||||
|
||||
def get_text(self):
|
||||
return self._ns_inner_view.stringValue()
|
||||
|
||||
def set_text(self, v):
|
||||
self._ns_inner_view.setStringValue_(v)
|
||||
|
||||
def get_color(self):
|
||||
return Color._from_ns_color(self._ns_inner_view.textColor())
|
||||
|
||||
def set_color(self, v):
|
||||
self._ns_inner_view.setTextColor_(v._ns_color)
|
||||
|
||||
def _get_vertical_padding(self):
|
||||
if self.border:
|
||||
return 5
|
||||
else:
|
||||
return 0
|
||||
|
||||
_vertical_padding = property(_get_vertical_padding)
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class PyGUI_NSTextField(NSTextField): #, PyGUI_NS_EventHandler):
|
||||
__metaclass__ = NSMultiClass
|
||||
|
||||
pygui_multiline = False
|
||||
|
||||
class PyGUI_NSSecureTextField(NSSecureTextField): #, PyGUI_NS_EventHandler):
|
||||
__metaclass__ = NSMultiClass
|
||||
|
||||
pygui_multiline = False
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
#------------------------------------------------------------------------------
|
||||
#
|
||||
# Python GUI - Utilities - PyObjC
|
||||
#
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
from math import ceil
|
||||
from inspect import getmro
|
||||
from Foundation import NSObject
|
||||
from AppKit import NSView
|
||||
from GUI import Event, Globals
|
||||
|
||||
def NSMultiClass(name, bases, dic):
|
||||
# Workaround for PyObjC classes not supporting
|
||||
# multiple inheritance properly. Note: MRO is
|
||||
# right to left across the bases.
|
||||
main = bases[0]
|
||||
slots = list(dic.get('__slots__', ()))
|
||||
dic2 = {}
|
||||
for mix in bases[1:]:
|
||||
for cls in getmro(mix)[::-1]:
|
||||
slots2 = cls.__dict__.get('__slots__')
|
||||
if slots2:
|
||||
for slot in slots2:
|
||||
if slot not in slots:
|
||||
slots.append(slot)
|
||||
dic2.update(cls.__dict__)
|
||||
dic2.update(dic)
|
||||
if slots:
|
||||
dic2['__slots__'] = slots
|
||||
cls = type(main)(name, (main,), dic2)
|
||||
return cls
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class PyGUI_Flipped_NSView(NSView):
|
||||
# An NSView with a flipped coordinate system.
|
||||
|
||||
def isFlipped(self):
|
||||
return True
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class PyGUI_NSActionTarget(NSObject):
|
||||
# A shared instance of this class is used as the target of
|
||||
# all action messages from the NSViews of Components. It
|
||||
# performs the action by calling the similarly-named method of
|
||||
# the corresponding Component.
|
||||
|
||||
def doAction_(self, ns_sender):
|
||||
self.call_method('do_action', ns_sender)
|
||||
|
||||
def call_method(self, method_name, ns_sender):
|
||||
component = Globals._ns_view_to_component.get(ns_sender)
|
||||
if component:
|
||||
getattr(component, method_name)()
|
||||
|
||||
_ns_action_target = PyGUI_NSActionTarget.alloc().init()
|
||||
|
||||
def ns_set_action(ns_control, method_name):
|
||||
# Arrange for the 'action' message of the NSControl to
|
||||
# invoke the indicated method of its associated Component.
|
||||
ns_control.setAction_(method_name)
|
||||
ns_control.setTarget_(_ns_action_target)
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class PyGUI_NS_EventHandler:
|
||||
# Methods to be mixed in with NSView subclasses that are
|
||||
# to relay mouse and keyboard events to a Component.
|
||||
#
|
||||
# pygui_component Component
|
||||
|
||||
def mouseDown_(self, ns_event):
|
||||
self._ns_mouse_event(ns_event)
|
||||
|
||||
def mouseUp_(self, ns_event):
|
||||
self._ns_mouse_event(ns_event)
|
||||
|
||||
def mouseDragged_(self, ns_event):
|
||||
self._ns_mouse_event(ns_event)
|
||||
|
||||
def rightMouseDown_(self, ns_event):
|
||||
self._ns_mouse_event(ns_event)
|
||||
|
||||
def rightMouseUp_(self, ns_event):
|
||||
self._ns_mouse_event(ns_event)
|
||||
|
||||
def rightMouseDragged_(self, ns_event):
|
||||
self._ns_mouse_event(ns_event)
|
||||
|
||||
def otherMouseDown_(self, ns_event):
|
||||
self._ns_mouse_event(ns_event)
|
||||
|
||||
def otherMouseUp_(self, ns_event):
|
||||
self._ns_mouse_event(ns_event)
|
||||
|
||||
def otherMouseDragged_(self, ns_event):
|
||||
self._ns_mouse_event(ns_event)
|
||||
|
||||
def mouseMoved_(self, ns_event):
|
||||
self._ns_mouse_event(ns_event)
|
||||
|
||||
def mouseEntered_(self, ns_event):
|
||||
self._ns_mouse_event(ns_event)
|
||||
|
||||
def mouseExited_(self, ns_event):
|
||||
self._ns_mouse_event(ns_event)
|
||||
|
||||
def keyDown_(self, ns_event):
|
||||
#print "PyGUI_NS_EventHandler.keyDown_:", repr(ns_event.characters()), \
|
||||
# "for", object.__repr__(self) ###
|
||||
self._ns_other_event(ns_event)
|
||||
|
||||
def keyUp_(self, ns_event):
|
||||
#print "PyGUI_NS_EventHandler.keyUp_ for", self ###
|
||||
self._ns_other_event(ns_event)
|
||||
|
||||
def _ns_mouse_event(self, ns_event):
|
||||
#print "PyGUI_NS_EventHandler._ns_mouse_event" ###
|
||||
event = self._ns_mouse_event_to_event(ns_event)
|
||||
#print "...sending to", self.pygui_component ###
|
||||
component = self.pygui_component
|
||||
if component:
|
||||
component.handle_event_here(event)
|
||||
|
||||
def _ns_mouse_event_to_event(self, ns_event):
|
||||
event = Event(ns_event)
|
||||
event.position = tuple(self._ns_event_position(ns_event))
|
||||
return event
|
||||
|
||||
def _ns_event_position(self, ns_event):
|
||||
#print "PyGUI_NS_EventHandler._ns_event_position:", self ###
|
||||
#print "...mro =", self.__class__.__mro__ ###
|
||||
ns_win_pos = ns_event.locationInWindow()
|
||||
return self.convertPoint_fromView_(ns_win_pos, None)
|
||||
|
||||
def _ns_other_event(self, ns_event):
|
||||
#print "PyGUI_NS_EventHandler._ns_other_event for", self ###
|
||||
event = Event(ns_event)
|
||||
component = self.pygui_component
|
||||
if component:
|
||||
#print "...passing", event.kind, "to", component ###
|
||||
component.handle_event(event)
|
||||
|
||||
def acceptsFirstResponder(self):
|
||||
###return True
|
||||
return self.pygui_component._ns_accept_first_responder
|
||||
|
||||
# def canBecomeKeyView(self):
|
||||
# return self.pygui_component._tab_stop
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class PyGUI_NS_ViewBase(PyGUI_NS_EventHandler):
|
||||
# Methods to be mixed in with PyGUI_NSView classes.
|
||||
#
|
||||
# pygui_component ViewBase
|
||||
|
||||
__slots__ = ['tracking_rect']
|
||||
|
||||
# tracking_rect = None
|
||||
|
||||
def becomeFirstResponder(self):
|
||||
self.pygui_component.targeted()
|
||||
return True
|
||||
|
||||
def resignFirstResponder(self):
|
||||
self.pygui_component.untargeted()
|
||||
return True
|
||||
|
||||
def resetCursorRects(self):
|
||||
#print "PyGUI_NS_ViewBase: resetCursorRects" ###
|
||||
self.removeCursorRects()
|
||||
self.tracking_rect = self.addTrackingRect_owner_userData_assumeInside_(
|
||||
self.visibleRect(), self, 0, False)
|
||||
self.pygui_component._ns_reset_cursor_rects()
|
||||
|
||||
def removeCursorRects(self):
|
||||
#print "PyGUI_NS_ViewBase: removeCursorRects" ###
|
||||
tag = getattr(self, 'tracking_rect', None)
|
||||
if tag:
|
||||
self.removeTrackingRect_(tag)
|
||||
self.tracking_rect = None
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
def ns_size_to_fit(ns_control, padding = (0, 0), height = None):
|
||||
# Set size of control to fit its contents, plus the given padding.
|
||||
# Height may be overridden, because some controls don't seem to
|
||||
# calculate it properly.
|
||||
# Auto sizing can result in fractional sizes, which seems to cause
|
||||
# problems when NS autoresizing occurs later. So we round the size up
|
||||
# to whole numbers of pixels.
|
||||
ns_control.sizeToFit()
|
||||
w, h = ns_control.frame().size
|
||||
pw, ph = padding
|
||||
ns_control.setFrameSize_((ceil(w + pw), ceil((height or h) + ph)))
|
||||
@@ -0,0 +1,12 @@
|
||||
#
|
||||
# Python GUI - Views - PyObjC
|
||||
#
|
||||
|
||||
from GUI import export
|
||||
from GUI.GViews import View as GView
|
||||
|
||||
class View(GView):
|
||||
|
||||
_ns_scrollable = False
|
||||
|
||||
export(View)
|
||||
@@ -0,0 +1,61 @@
|
||||
#
|
||||
# Python GUI - View Base - PyObjC
|
||||
#
|
||||
|
||||
import Foundation
|
||||
import AppKit
|
||||
from GUI import Globals, export
|
||||
from GUI.Properties import overridable_property
|
||||
from GUI import Event
|
||||
from GUI.Utils import PyGUI_NS_EventHandler
|
||||
from GUI.GViewBases import ViewBase as GViewBase
|
||||
|
||||
ns_tracking_mask = (
|
||||
AppKit.NSLeftMouseDraggedMask |
|
||||
AppKit.NSRightMouseDraggedMask |
|
||||
AppKit.NSOtherMouseDraggedMask |
|
||||
AppKit.NSLeftMouseUpMask |
|
||||
AppKit.NSRightMouseUpMask |
|
||||
AppKit.NSOtherMouseUpMask)
|
||||
|
||||
# Need to use NSDefaultRunLoopMode here otherwise timers don't fire.
|
||||
ns_tracking_mode = Foundation.NSDefaultRunLoopMode # AppKit.NSEventTrackingRunLoopMode
|
||||
|
||||
ns_distant_future = Foundation.NSDate.distantFuture()
|
||||
|
||||
|
||||
class ViewBase(GViewBase):
|
||||
|
||||
def _change_container(self, new_container):
|
||||
self._ns_inner_view.removeCursorRects()
|
||||
super(ViewBase, self)._change_container(new_container)
|
||||
|
||||
def _ns_track_mouse(self, ns_view):
|
||||
ns_app = Globals.ns_application
|
||||
tracking = True
|
||||
while tracking:
|
||||
ns_event = ns_app.nextEventMatchingMask_untilDate_inMode_dequeue_(
|
||||
ns_tracking_mask, ns_distant_future, ns_tracking_mode, True)
|
||||
event = ns_view._ns_mouse_event_to_event(ns_event)
|
||||
yield event
|
||||
tracking = event.kind <> 'mouse_up'
|
||||
|
||||
def _cursor_changed(self):
|
||||
#print "ViewBase._cursor_changed:", self ###
|
||||
ns_view = self._ns_view
|
||||
ns_window = ns_view.window()
|
||||
if ns_window:
|
||||
# invalidateCursorRectsForView_ doesn't seem to trigger
|
||||
# resetCursorRects on the view.
|
||||
#ns_window.invalidateCursorRectsForView_(ns_view)
|
||||
ns_window.resetCursorRects()
|
||||
|
||||
def _ns_reset_cursor_rects(self):
|
||||
#print "ViewBase._ns_reset_cursor_rects:", self ###
|
||||
cursor = self._cursor
|
||||
if cursor:
|
||||
ns_view = self._ns_inner_view
|
||||
ns_rect = ns_view.visibleRect()
|
||||
ns_view.addCursorRect_cursor_(ns_rect, cursor._ns_cursor)
|
||||
|
||||
export(ViewBase)
|
||||
@@ -0,0 +1,292 @@
|
||||
#------------------------------------------------------------------------------
|
||||
#
|
||||
# Python GUI - Windows - PyObjC version
|
||||
#
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
from Foundation import NSRect, NSPoint, NSSize, NSObject
|
||||
import AppKit
|
||||
from AppKit import NSWindow, NSScreen, NSTextView, NSMenu
|
||||
from GUI import export
|
||||
from GUI import Globals
|
||||
from GUI.Utils import NSMultiClass, PyGUI_NS_EventHandler, PyGUI_Flipped_NSView
|
||||
from GUI import application
|
||||
from GUI import Event
|
||||
from GUI.GWindows import Window as GWindow
|
||||
|
||||
_default_options_for_style = {
|
||||
'standard':
|
||||
{'movable': 1, 'closable': 1, 'hidable': 1, 'resizable': 1},
|
||||
'nonmodal_dialog':
|
||||
{'movable': 1, 'closable': 0, 'hidable': 1, 'resizable': 0},
|
||||
'modal_dialog':
|
||||
{'movable': 1, 'closable': 0, 'hidable': 0, 'resizable': 0},
|
||||
'alert':
|
||||
{'movable': 1, 'closable': 0, 'hidable': 0, 'resizable': 0},
|
||||
'fullscreen':
|
||||
{'movable': 0, 'closable': 0, 'hidable': 0, 'resizable': 0},
|
||||
#{'movable': 1, 'closable': 1, 'hidable': 1, 'resizable': 1},
|
||||
}
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class Window(GWindow):
|
||||
# _ns_window PyGUI_NSWindow
|
||||
# _ns_style_mask int
|
||||
|
||||
def __init__(self, style = 'standard', zoomable = None, **kwds):
|
||||
# We ignore zoomable, since it's the same as resizable.
|
||||
self._style = style
|
||||
options = dict(_default_options_for_style[style])
|
||||
for option in ['movable', 'closable', 'hidable', 'resizable']:
|
||||
if option in kwds:
|
||||
options[option] = kwds.pop(option)
|
||||
self._ns_style_mask = self._ns_window_style_mask(**options)
|
||||
if style == 'fullscreen':
|
||||
ns_rect = NSScreen.mainScreen().frame()
|
||||
else:
|
||||
ns_rect = NSRect(NSPoint(0, 0), NSSize(self._default_width, self._default_height))
|
||||
ns_window = PyGUI_NSWindow.alloc()
|
||||
ns_window.initWithContentRect_styleMask_backing_defer_(
|
||||
ns_rect, self._ns_style_mask, AppKit.NSBackingStoreBuffered, True)
|
||||
ns_content = PyGUI_NS_ContentView.alloc()
|
||||
ns_content.initWithFrame_(NSRect(NSPoint(0, 0), NSSize(0, 0)))
|
||||
ns_content.pygui_component = self
|
||||
ns_window.setContentView_(ns_content)
|
||||
ns_window.setAcceptsMouseMovedEvents_(True)
|
||||
ns_window.setDelegate_(ns_window)
|
||||
ns_window.pygui_component = self
|
||||
self._ns_window = ns_window
|
||||
GWindow.__init__(self, style = style, closable = options['closable'],
|
||||
_ns_view = ns_window.contentView(), _ns_responder = ns_window,
|
||||
_ns_set_autoresizing_mask = False,
|
||||
**kwds)
|
||||
|
||||
def _ns_window_style_mask(self, movable, closable, hidable, resizable):
|
||||
if movable or closable or hidable or resizable:
|
||||
mask = AppKit.NSTitledWindowMask
|
||||
if closable:
|
||||
mask |= AppKit.NSClosableWindowMask
|
||||
if hidable:
|
||||
mask |= AppKit.NSMiniaturizableWindowMask
|
||||
if resizable:
|
||||
mask |= AppKit.NSResizableWindowMask
|
||||
else:
|
||||
mask = AppKit.NSBorderlessWindowMask
|
||||
return mask
|
||||
|
||||
def destroy(self):
|
||||
#print "Window.destroy:", self ###
|
||||
self.hide()
|
||||
app = application()
|
||||
if app._ns_key_window is self:
|
||||
app._ns_key_window = None
|
||||
GWindow.destroy(self)
|
||||
# We can't drop all references to the NSWindow yet, because this method
|
||||
# can be called from its windowShouldClose: method, and allowing an
|
||||
# NSWindow to be released while executing one of its own methods seems
|
||||
# to be a very bad idea (Cocoa hangs). So we hide the NSWindow and store
|
||||
# a reference to it in a global. It will be released the next time a
|
||||
# window is closed and the global is re-used.
|
||||
global _ns_zombie_window
|
||||
_ns_zombie_window = self._ns_window
|
||||
self._ns_window.pygui_component = None
|
||||
#self._ns_window = None
|
||||
|
||||
def get_bounds(self):
|
||||
ns_window = self._ns_window
|
||||
ns_frame = ns_window.frame()
|
||||
(l, y), (w, h) = ns_window.contentRectForFrameRect_styleMask_(
|
||||
ns_frame, self._ns_style_mask)
|
||||
b = Globals.ns_screen_height - y
|
||||
result = (l, b - h, l + w, b)
|
||||
return result
|
||||
|
||||
def set_bounds(self, (l, t, r, b)):
|
||||
y = Globals.ns_screen_height - b
|
||||
ns_rect = NSRect(NSPoint(l, y), NSSize(r - l, b - t))
|
||||
ns_window = self._ns_window
|
||||
ns_frame = ns_window.frameRectForContentRect_styleMask_(
|
||||
ns_rect, self._ns_style_mask)
|
||||
ns_window.setFrame_display_(ns_frame, False)
|
||||
|
||||
def get_title(self):
|
||||
return self._ns_window.title()
|
||||
|
||||
def set_title(self, v):
|
||||
self._ns_window.setTitle_(v)
|
||||
|
||||
def get_visible(self):
|
||||
return self._ns_window.isVisible()
|
||||
|
||||
def set_visible(self, v):
|
||||
# At some mysterious time between creating a window and showing
|
||||
# it for the first time, Cocoa adjusts its position so that it
|
||||
# doesn't extend above the menu bar. This is a nuisance for
|
||||
# our fullscreen windows, so we need to readjust the position
|
||||
# before showing.
|
||||
if v:
|
||||
if self._style == 'fullscreen':
|
||||
self._ns_window.setFrameOrigin_(NSPoint(0, 0))
|
||||
self._ns_window.orderFront_(None)
|
||||
else:
|
||||
self._ns_window.orderOut_(None)
|
||||
|
||||
def _show(self):
|
||||
self.visible = True
|
||||
self._ns_window.makeKeyWindow()
|
||||
|
||||
def get_target(self):
|
||||
ns_window = self._ns_window
|
||||
ns_view = ns_window.firstResponder()
|
||||
while ns_view and ns_view is not ns_window:
|
||||
component = Globals._ns_view_to_component.get(ns_view)
|
||||
if component:
|
||||
return component
|
||||
ns_view = ns_view.superview()
|
||||
return self
|
||||
|
||||
def center(self):
|
||||
self._ns_window.center()
|
||||
|
||||
def _stagger(self):
|
||||
key_win = application()._ns_key_window
|
||||
if key_win:
|
||||
(x, y), (w, h) = key_win._ns_window.frame()
|
||||
p = self._ns_window.cascadeTopLeftFromPoint_(NSPoint(x, y + h))
|
||||
self._ns_window.setFrameTopLeftPoint_(p)
|
||||
else:
|
||||
(x, y), (w, h) = NSScreen.mainScreen().visibleFrame()
|
||||
ns_vis_topleft = NSPoint(x, y + h)
|
||||
self._ns_window.setFrameTopLeftPoint_(ns_vis_topleft)
|
||||
|
||||
def _document_needs_saving(self, state):
|
||||
self._ns_window.setDocumentEdited_(state)
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class PyGUI_NSWindow(NSWindow, PyGUI_NS_EventHandler):
|
||||
# pygui_component Window
|
||||
# resize_delta point or None
|
||||
|
||||
__metaclass__ = NSMultiClass
|
||||
__slots__ = ['pygui_component', 'resize_delta', 'pygui_field_editor']
|
||||
|
||||
# pygui_component = None
|
||||
# resize_delta = None
|
||||
# pygui_field_editor = None
|
||||
|
||||
def _ns_event_position(self, ns_event):
|
||||
return ns_event.locationInWindow()
|
||||
|
||||
def windowShouldClose_(self, sender):
|
||||
# We use this to detect when the Aqua window closing button
|
||||
# is pressed, and do the closing ourselves.
|
||||
self.pygui_component.close_cmd()
|
||||
return False
|
||||
|
||||
# The NSWindow is made its own delegate.
|
||||
|
||||
def windowWillResize_toSize_(self, ns_win, new_ns_size):
|
||||
w0, h0 = self.frame().size
|
||||
w1, h1 = new_ns_size
|
||||
self.resize_delta = (w1 - w0, h1 - h0)
|
||||
return new_ns_size
|
||||
|
||||
def windowDidResize_(self, notification):
|
||||
delta = getattr(self, 'resize_delta', None)
|
||||
if delta:
|
||||
self.pygui_component._resized(delta)
|
||||
self.resize_delta = None
|
||||
|
||||
def windowDidBecomeKey_(self, notification):
|
||||
app = application()
|
||||
app._ns_key_window = self.pygui_component
|
||||
app._update_menubar()
|
||||
|
||||
def windowDidResignKey_(self, notification):
|
||||
app = application()
|
||||
app._ns_key_window = None
|
||||
app._update_menubar()
|
||||
|
||||
def windowWillReturnFieldEditor_toObject_(self, ns_window, ns_obj):
|
||||
# Return special field editor for newline handling in text fields.
|
||||
#print "Window: Field editor requested for", object.__repr__(ns_obj) ###
|
||||
#editor = self.pygui_field_editor
|
||||
#if not editor:
|
||||
try:
|
||||
editor = self.pygui_field_editor
|
||||
except AttributeError:
|
||||
#print "...creating new field editor" ###
|
||||
editor = PyGUI_FieldEditor.alloc().initWithFrame_(
|
||||
NSRect(NSPoint(0, 0), NSSize(0, 0)))
|
||||
editor.setFieldEditor_(True)
|
||||
editor.setDrawsBackground_(False)
|
||||
self.pygui_field_editor = editor
|
||||
return editor
|
||||
|
||||
# Need the following two methods so that a fullscreen window can become
|
||||
# the main window. Otherwise it can't, because it has no title bar.
|
||||
|
||||
def canBecomeKeyWindow(self):
|
||||
return self.isVisible()
|
||||
|
||||
def canBecomeMainWindow(self):
|
||||
#print "PyGUI_NSWindow.canBecomeMainWindow"
|
||||
return self.isVisible()
|
||||
|
||||
def windowDidBecomeMain_(self, notification):
|
||||
#print "PyGUI_NSWindow.windowDidBecomeMain_:", self.pygui_component.title ###
|
||||
comp = self.pygui_component
|
||||
if comp and comp._style == 'fullscreen':
|
||||
#print "...hiding menu bar" ###
|
||||
NSMenu.setMenuBarVisible_(False)
|
||||
#self.setFrameOrigin_(NSPoint(0, 0))
|
||||
|
||||
def windowDidResignMain_(self, notification):
|
||||
#print "PyGUI_NSWindow.windowDidResignMain_:", self.pygui_component.title ###
|
||||
comp = self.pygui_component
|
||||
if comp and comp._style == 'fullscreen':
|
||||
#print "...showing menu bar" ###
|
||||
NSMenu.setMenuBarVisible_(True)
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class PyGUI_NS_ContentView(PyGUI_Flipped_NSView, PyGUI_NS_EventHandler):
|
||||
# pygui_component Window
|
||||
|
||||
__metaclass__ = NSMultiClass
|
||||
__slots__ = ['pygui_component']
|
||||
|
||||
def acceptsFirstResponder(self):
|
||||
return False
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class PyGUI_FieldEditorBase(NSTextView):
|
||||
# Special field editor for use by TextFields. Intercepts
|
||||
# return key events and handles them our own way.
|
||||
|
||||
def keyDown_(self, ns_event):
|
||||
#print "PyGUI_FieldEditorBase.keyDown_ for", self.pygui_component ###
|
||||
if ns_event.characters() == "\r":
|
||||
if self.pygui_component._multiline:
|
||||
self.insertText_("\n")
|
||||
return
|
||||
NSTextView.keyDown_(self, ns_event)
|
||||
|
||||
#------------------------------------------------------------------------------
|
||||
|
||||
class PyGUI_FieldEditor(PyGUI_FieldEditorBase, PyGUI_NS_EventHandler):
|
||||
|
||||
__metaclass__ = NSMultiClass
|
||||
|
||||
def get_pygui_component(self):
|
||||
pygui_nstextfield = self.superview().superview()
|
||||
component = pygui_nstextfield.pygui_component
|
||||
component._ns_responder = self
|
||||
return component
|
||||
|
||||
pygui_component = property(get_pygui_component)
|
||||
|
||||
export(Window)
|
||||
Reference in New Issue
Block a user